remove a never-used smartlist in routerlist.c
[tor.git] / src / or / routerlist.c
blobb45877f42548b3a0ab293786762e5a7fe050356d
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char routerlist_c_id[] = "$Id$";
8 /**
9 * \file routerlist.c
10 * \brief Code to
11 * maintain and access the global list of routerinfos for known
12 * servers.
13 **/
15 #include "or.h"
17 /****************************************************************************/
19 /** Global list of a trusted_dir_server_t object for each trusted directory
20 * server. */
21 static smartlist_t *trusted_dir_servers = NULL;
23 /* static function prototypes */
24 static routerinfo_t *router_pick_directory_server_impl(int requireother,
25 int fascistfirewall,
26 int for_v2_directory);
27 static trusted_dir_server_t *router_pick_trusteddirserver_impl(
28 int need_v1_support, int requireother, int fascistfirewall);
29 static void mark_all_trusteddirservers_up(void);
30 static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
31 static int router_nickname_matches(routerinfo_t *router, const char *nickname);
32 static void routerstatus_list_update_from_networkstatus(time_t now);
33 static void local_routerstatus_free(local_routerstatus_t *rs);
35 /****************************************************************************/
37 /****
38 * Functions to manage and access our list of known routers. (Note:
39 * dirservers maintain a separate, independent list of known router
40 * descriptors.)
41 ****/
43 /** Global list of all of the routers that we know about. */
44 static routerlist_t *routerlist = NULL;
46 extern int has_fetched_directory; /**< from main.c */
48 /** Global list of all of the current network_status documents that we know
49 * about. This list is kept sorted by published_on. */
50 static smartlist_t *networkstatus_list = NULL;
51 /** Global list of routerstatuses_t for each router, known or unknown. */
52 static smartlist_t *routerstatus_list = NULL;
53 /** True iff any member of networkstatus_list has changed since the last time
54 * we called routerstatus_list_update_from_networkstatus(). */
55 static int networkstatus_list_has_changed = 0;
56 /** True iff any element of routerstatus_list has changed since the last
57 * time we called routers_update_all_from_networkstatus().*/
58 static int routerstatus_list_has_changed = 0;
60 /** Repopulate our list of network_status_t objects from the list cached on
61 * disk. Return 0 on success, -1 on failure. */
62 int
63 router_reload_networkstatus(void)
65 char filename[512];
66 struct stat st;
67 smartlist_t *entries;
68 char *s;
69 tor_assert(get_options()->DataDirectory);
70 if (!networkstatus_list)
71 networkstatus_list = smartlist_create();
73 tor_snprintf(filename,sizeof(filename),"%s/cached-status",
74 get_options()->DataDirectory);
75 entries = tor_listdir(filename);
76 SMARTLIST_FOREACH(entries, const char *, fn, {
77 char buf[DIGEST_LEN];
78 if (strlen(fn) != HEX_DIGEST_LEN ||
79 base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
80 log_fn(LOG_INFO,
81 "Skipping cached-status file with unexpected name \"%s\"",fn);
82 continue;
84 tor_snprintf(filename,sizeof(filename),"%s/cached-status/%s",
85 get_options()->DataDirectory, fn);
86 s = read_file_to_str(filename, 0);
87 if (s) {
88 stat(filename, &st);
89 if (router_set_networkstatus(s, st.st_mtime, NS_FROM_CACHE, NULL)<0) {
90 log_fn(LOG_WARN, "Couldn't load networkstatus from \"%s\"",filename);
92 tor_free(s);
94 });
95 SMARTLIST_FOREACH(entries, char *, fn, tor_free(fn));
96 smartlist_free(entries);
97 networkstatus_list_clean(time(NULL));
98 routers_update_all_from_networkstatus();
99 return 0;
102 /* Router descriptor storage.
104 * Routerdescs are stored in a big file, named "cached-routers". As new
105 * routerdescs arrive, we append them to a journal file named
106 * "cached-routers.new".
108 * From time to time, we replace "cached-routers" with a new file containing
109 * only the live, non-superseded descriptors, and clear cached-routers.new.
111 * On startup, we read both files.
114 /** The size of the router log, in bytes. */
115 static size_t router_journal_len = 0;
116 /** The size of the router store, in bytes. */
117 static size_t router_store_len = 0;
119 /** Helper: return 1 iff the router log is so big we want to rebuild the
120 * store. */
121 static int
122 router_should_rebuild_store(void)
124 if (router_store_len > (1<<16))
125 return router_journal_len > router_store_len / 2;
126 else
127 return router_journal_len > (1<<15);
130 /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
131 * journal. */
132 static int
133 router_append_to_journal(const char *s, size_t len)
135 or_options_t *options = get_options();
136 size_t fname_len = strlen(options->DataDirectory)+32;
137 char *fname = tor_malloc(len);
139 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
140 options->DataDirectory);
142 if (!len)
143 len = strlen(s);
145 if (append_bytes_to_file(fname, s, len, 0)) {
146 log_fn(LOG_WARN, "Unable to store router descriptor");
147 tor_free(fname);
148 return -1;
151 tor_free(fname);
152 router_journal_len += len;
153 return 0;
156 /** If the journal is too long, or if <b>force</b> is true, then atomically
157 * replace the router store with the routers currently in our routerlist, and
158 * clear the journal. Return 0 on success, -1 on failure.
160 static int
161 router_rebuild_store(int force)
163 size_t len = 0;
164 or_options_t *options;
165 size_t fname_len;
166 smartlist_t *chunk_list = NULL;
167 char *fname = NULL;
168 int r = -1;
170 if (!force && !router_should_rebuild_store())
171 return 0;
172 if (!routerlist)
173 return 0;
175 /* Don't save deadweight. */
176 routerlist_remove_old_routers(ROUTER_MAX_AGE);
178 options = get_options();
179 fname_len = strlen(options->DataDirectory)+32;
180 fname = tor_malloc(fname_len);
181 tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
182 chunk_list = smartlist_create();
184 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
186 sized_chunk_t *c;
187 if (!ri->signed_descriptor) {
188 log_fn(LOG_WARN, "Bug! No descriptor stored for router '%s'.",
189 ri->nickname);
190 goto done;
192 c = tor_malloc(sizeof(sized_chunk_t));
193 c->bytes = ri->signed_descriptor;
194 c->len = ri->signed_descriptor_len;
195 smartlist_add(chunk_list, c);
198 if (write_chunks_to_file(fname, chunk_list, 0)<0) {
199 log_fn(LOG_WARN, "Error writing router store to disk.");
200 goto done;
203 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
204 options->DataDirectory);
206 write_str_to_file(fname, "", 0);
208 r = 0;
209 router_store_len = len;
210 router_journal_len = 0;
211 done:
212 tor_free(fname);
213 if (chunk_list) {
214 SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
215 smartlist_free(chunk_list);
217 return r;
220 /* Load all cached router descriptors from the store. Return 0 on success and
221 * -1 on failure.
224 router_reload_router_list(void)
226 or_options_t *options = get_options();
227 size_t fname_len = strlen(options->DataDirectory)+32;
228 char *fname = tor_malloc(fname_len);
229 struct stat st;
230 int j;
232 if (!routerlist) {
233 routerlist = tor_malloc_zero(sizeof(routerlist_t));
234 routerlist->routers = smartlist_create();
237 router_journal_len = router_store_len = 0;
239 for (j = 0; j < 2; ++j) {
240 char *contents;
241 tor_snprintf(fname, fname_len,
242 (j==0)?"%s/cached-routers":"%s/cached-routers.new",
243 options->DataDirectory);
244 contents = read_file_to_str(fname, 0);
245 if (contents) {
246 stat(fname, &st);
247 if (j==0)
248 router_store_len = st.st_size;
249 else
250 router_journal_len = st.st_size;
251 router_load_routers_from_string(contents, 1, NULL);
252 tor_free(contents);
255 tor_free(fname);
257 /* Don't cache expired routers. */
258 routerlist_remove_old_routers(ROUTER_MAX_AGE);
260 if (router_journal_len) {
261 /* Always clear the journal on startup.*/
262 router_rebuild_store(1);
264 return 0;
267 /** Set *<b>outp</b> to a smartlist containing a list of
268 * trusted_dir_server_t * for all known trusted dirservers. Callers
269 * must not modify the list or its contents.
271 void
272 router_get_trusted_dir_servers(smartlist_t **outp)
274 if (!trusted_dir_servers)
275 trusted_dir_servers = smartlist_create();
277 *outp = trusted_dir_servers;
280 /** Try to find a running dirserver. If there are no running dirservers
281 * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
282 * set all the authoritative ones as running again, and pick one;
283 * if there are then no dirservers at all in our routerlist,
284 * reload the routerlist and try one last time. If for_runningrouters is
285 * true, then only pick a dirserver that can answer runningrouters queries
286 * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
287 * Other args are as in router_pick_directory_server_impl().
289 routerinfo_t *
290 router_pick_directory_server(int requireother,
291 int fascistfirewall,
292 int for_v2_directory,
293 int retry_if_no_servers)
295 routerinfo_t *choice;
297 if (!routerlist)
298 return NULL;
300 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
301 for_v2_directory);
302 if (choice || !retry_if_no_servers)
303 return choice;
305 log_fn(LOG_INFO,"No reachable router entries for dirservers. Trying them all again.");
306 /* mark all authdirservers as up again */
307 mark_all_trusteddirservers_up();
308 /* try again */
309 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
310 for_v2_directory);
311 if (choice)
312 return choice;
314 log_fn(LOG_INFO,"Still no %s router entries. Reloading and trying again.",
315 firewall_is_fascist() ? "reachable" : "known");
316 has_fetched_directory=0; /* reset it */
317 if (router_reload_router_list()) {
318 return NULL;
320 /* give it one last try */
321 choice = router_pick_directory_server_impl(requireother, 0,
322 for_v2_directory);
323 return choice;
326 trusted_dir_server_t *
327 router_get_trusteddirserver_by_digest(const char *digest)
329 if (!trusted_dir_servers)
330 return NULL;
332 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
334 if (!memcmp(ds->digest, digest, DIGEST_LEN))
335 return ds;
338 return NULL;
341 /** Try to find a running trusted dirserver. If there are no running
342 * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
343 * set them all as running again, and try again.
344 * Other args are as in router_pick_trusteddirserver_impl().
346 trusted_dir_server_t *
347 router_pick_trusteddirserver(int need_v1_support,
348 int requireother,
349 int fascistfirewall,
350 int retry_if_no_servers)
352 trusted_dir_server_t *choice;
354 choice = router_pick_trusteddirserver_impl(need_v1_support,
355 requireother, fascistfirewall);
356 if (choice || !retry_if_no_servers)
357 return choice;
359 log_fn(LOG_INFO,"No trusted dirservers are reachable. Trying them all again.");
360 mark_all_trusteddirservers_up();
361 return router_pick_trusteddirserver_impl(need_v1_support,
362 requireother, fascistfirewall);
365 /** Pick a random running verified directory server/mirror from our
366 * routerlist.
367 * If <b>fascistfirewall</b> and we're not using a proxy,
368 * make sure the port we pick is allowed by options-\>firewallports.
369 * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
370 * choose a directory server new enough to support the v2 directory
371 * functionality.
373 static routerinfo_t *
374 router_pick_directory_server_impl(int requireother, int fascistfirewall,
375 int for_v2_directory)
377 routerinfo_t *result;
378 smartlist_t *sl;
380 if (!routerlist)
381 return NULL;
383 if (get_options()->HttpProxy)
384 fascistfirewall = 0;
386 /* Find all the running dirservers we know about. */
387 sl = smartlist_create();
388 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
390 if (!router->is_running || !router->dir_port || !router->is_verified)
391 continue;
392 if (requireother && router_is_me(router))
393 continue;
394 if (fascistfirewall) {
395 if (!fascist_firewall_allows_address(router->addr, router->dir_port))
396 continue;
398 /* Before 0.1.1.6-alpha, only trusted dirservers served status info.
399 * Before 0.1.1.7-alpha, retrieving nonexistent server IDs could bork
400 * the directory server.
402 if (for_v2_directory &&
403 !(tor_version_as_new_as(router->platform,"0.1.1.7-alpha") ||
404 router_digest_is_trusted_dir(router->identity_digest)))
405 continue;
406 smartlist_add(sl, router);
409 result = smartlist_choose(sl);
410 smartlist_free(sl);
411 return result;
414 /** Choose randomly from among the trusted dirservers that are up.
415 * If <b>fascistfirewall</b> and we're not using a proxy,
416 * make sure the port we pick is allowed by options-\>firewallports.
417 * If <b>requireother</b>, it cannot be us. If <b>need_v1_support</b>, choose
418 * a trusted authority for the v1 directory system.
420 static trusted_dir_server_t *
421 router_pick_trusteddirserver_impl(int need_v1_support,
422 int requireother, int fascistfirewall)
424 smartlist_t *sl;
425 routerinfo_t *me;
426 trusted_dir_server_t *ds;
427 sl = smartlist_create();
428 me = router_get_my_routerinfo();
430 if (!trusted_dir_servers)
431 return NULL;
433 if (get_options()->HttpProxy)
434 fascistfirewall = 0;
436 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
438 if (!d->is_running) continue;
439 if (need_v1_support && !d->supports_v1_protocol)
440 continue;
441 if (requireother && me &&
442 !memcmp(me->identity_digest, d->digest, DIGEST_LEN))
443 continue;
444 if (fascistfirewall) {
445 if (!fascist_firewall_allows_address(d->addr, d->dir_port))
446 continue;
448 smartlist_add(sl, d);
451 ds = smartlist_choose(sl);
452 smartlist_free(sl);
453 return ds;
456 /** Go through and mark the authoritative dirservers as up. */
457 static void
458 mark_all_trusteddirservers_up(void)
460 if (routerlist) {
461 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
462 if (router_digest_is_trusted_dir(router->identity_digest) &&
463 router->dir_port > 0) {
464 router->is_running = 1;
467 if (trusted_dir_servers) {
468 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
470 dir->is_running = 1;
471 dir->n_networkstatus_failures = 0;
476 /** Return 0 if \\exists an authoritative dirserver that's currently
477 * thought to be running, else return 1.
480 all_trusted_directory_servers_down(void)
482 if (!trusted_dir_servers)
483 return 1;
484 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
485 if (dir->is_running) return 0);
486 return 1;
489 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
490 * This is used to make sure we don't pick siblings in a single path.
492 void
493 routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
495 routerinfo_t *r;
496 config_line_t *cl;
498 if (!router->declared_family)
499 return;
501 /* Add every r such that router declares familyness with r, and r
502 * declares familyhood with router. */
503 SMARTLIST_FOREACH(router->declared_family, const char *, n,
505 if (!(r = router_get_by_nickname(n)))
506 continue;
507 if (!r->declared_family)
508 continue;
509 SMARTLIST_FOREACH(r->declared_family, const char *, n2,
511 if (router_nickname_matches(router, n2))
512 smartlist_add(sl, r);
516 /* If the user declared any families locally, honor those too. */
517 for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
518 if (router_nickname_is_in_list(router, cl->value)) {
519 add_nickname_list_to_smartlist(sl, cl->value, 0);
524 /** List of strings for nicknames we've already warned about and that are
525 * still unknown / unavailable. */
526 static smartlist_t *warned_nicknames = NULL;
528 /** Given a comma-and-whitespace separated list of nicknames, see which
529 * nicknames in <b>list</b> name routers in our routerlist that are
530 * currently running. Add the routerinfos for those routers to <b>sl</b>.
532 void
533 add_nickname_list_to_smartlist(smartlist_t *sl, const char *list, int warn_if_down)
535 routerinfo_t *router;
536 smartlist_t *nickname_list;
538 if (!list)
539 return; /* nothing to do */
540 tor_assert(sl);
542 nickname_list = smartlist_create();
543 if (!warned_nicknames)
544 warned_nicknames = smartlist_create();
546 smartlist_split_string(nickname_list, list, ",",
547 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
549 SMARTLIST_FOREACH(nickname_list, const char *, nick, {
550 int warned;
551 if (!is_legal_nickname_or_hexdigest(nick)) {
552 log_fn(LOG_WARN,"Nickname %s is misformed; skipping", nick);
553 continue;
555 router = router_get_by_nickname(nick);
556 warned = smartlist_string_isin(warned_nicknames, nick);
557 if (router) {
558 if (router->is_running) {
559 smartlist_add(sl,router);
560 if (warned)
561 smartlist_string_remove(warned_nicknames, nick);
562 } else {
563 if (!warned) {
564 log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG,
565 "Nickname list includes '%s' which is known but down.",nick);
566 smartlist_add(warned_nicknames, tor_strdup(nick));
569 } else {
570 if (!warned) {
571 log_fn(has_fetched_directory ? LOG_WARN : LOG_INFO,
572 "Nickname list includes '%s' which isn't a known router.",nick);
573 smartlist_add(warned_nicknames, tor_strdup(nick));
577 SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
578 smartlist_free(nickname_list);
581 /** Return 1 iff any member of the comma-separated list <b>list</b> is an
582 * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
584 static int
585 router_nickname_is_in_list(routerinfo_t *router, const char *list)
587 smartlist_t *nickname_list;
588 int v = 0;
590 if (!list)
591 return 0; /* definitely not */
592 tor_assert(router);
594 nickname_list = smartlist_create();
595 smartlist_split_string(nickname_list, list, ",",
596 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
597 SMARTLIST_FOREACH(nickname_list, const char *, cp,
598 if (router_nickname_matches(router, cp)) {v=1;break;});
599 SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
600 smartlist_free(nickname_list);
601 return v;
604 /** Add every router from our routerlist that is currently running to
605 * <b>sl</b>.
607 static void
608 router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_unverified,
609 int need_uptime, int need_capacity)
611 if (!routerlist)
612 return;
614 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
616 if (router->is_running &&
617 (router->is_verified ||
618 (allow_unverified &&
619 !router_is_unreliable(router, need_uptime, need_capacity)))) {
620 /* If it's running, and either it's verified or we're ok picking
621 * unverified routers and this one is suitable.
623 smartlist_add(sl, router);
628 /** Look through the routerlist until we find a router that has my key.
629 Return it. */
630 routerinfo_t *
631 routerlist_find_my_routerinfo(void)
633 if (!routerlist)
634 return NULL;
636 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
638 if (router_is_me(router))
639 return router;
641 return NULL;
644 /** Find a router that's up, that has this IP address, and
645 * that allows exit to this address:port, or return NULL if there
646 * isn't a good one.
648 routerinfo_t *
649 router_find_exact_exit_enclave(const char *address, uint16_t port)
651 uint32_t addr;
652 struct in_addr in;
654 if (!tor_inet_aton(address, &in))
655 return NULL; /* it's not an IP already */
656 addr = ntohl(in.s_addr);
658 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
660 if (router->is_running &&
661 router->addr == addr &&
662 router_compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
663 ADDR_POLICY_ACCEPTED)
664 return router;
666 return NULL;
669 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
670 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
671 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
672 * bandwidth.
675 router_is_unreliable(routerinfo_t *router, int need_uptime, int need_capacity)
677 if (need_uptime && router->uptime < ROUTER_REQUIRED_MIN_UPTIME)
678 return 1;
679 if (need_capacity && router->bandwidthcapacity < ROUTER_REQUIRED_MIN_BANDWIDTH)
680 return 1;
681 return 0;
684 /** Remove from routerlist <b>sl</b> all routers who have a low uptime. */
685 static void
686 routerlist_sl_remove_unreliable_routers(smartlist_t *sl)
688 int i;
689 routerinfo_t *router;
691 for (i = 0; i < smartlist_len(sl); ++i) {
692 router = smartlist_get(sl, i);
693 if (router_is_unreliable(router, 1, 0)) {
694 // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
695 // router->nickname);
696 smartlist_del(sl, i--);
701 #define MAX_BELIEVABLE_BANDWIDTH 2000000 /* 2 MB/sec */
703 /** Choose a random element of router list <b>sl</b>, weighted by
704 * the advertised bandwidth of each router.
706 routerinfo_t *
707 routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
709 int i;
710 routerinfo_t *router;
711 smartlist_t *bandwidths;
712 uint32_t this_bw, tmp, total_bw=0, rand_bw;
713 uint32_t *p;
715 /* First count the total bandwidth weight, and make a smartlist
716 * of each value. */
717 bandwidths = smartlist_create();
718 for (i = 0; i < smartlist_len(sl); ++i) {
719 router = smartlist_get(sl, i);
720 this_bw = (router->bandwidthcapacity < router->bandwidthrate) ?
721 router->bandwidthcapacity : router->bandwidthrate;
722 /* if they claim something huge, don't believe it */
723 if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
724 this_bw = MAX_BELIEVABLE_BANDWIDTH;
725 p = tor_malloc(sizeof(uint32_t));
726 *p = this_bw;
727 smartlist_add(bandwidths, p);
728 total_bw += this_bw;
730 if (!total_bw) {
731 SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
732 smartlist_free(bandwidths);
733 return smartlist_choose(sl);
735 /* Second, choose a random value from the bandwidth weights. */
736 rand_bw = crypto_pseudo_rand_int(total_bw);
737 /* Last, count through sl until we get to the element we picked */
738 tmp = 0;
739 for (i=0; ; i++) {
740 tor_assert(i < smartlist_len(sl));
741 p = smartlist_get(bandwidths, i);
742 tmp += *p;
743 if (tmp >= rand_bw)
744 break;
746 SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
747 smartlist_free(bandwidths);
748 return (routerinfo_t *)smartlist_get(sl, i);
751 /** Return a random running router from the routerlist. If any node
752 * named in <b>preferred</b> is available, pick one of those. Never
753 * pick a node named in <b>excluded</b>, or whose routerinfo is in
754 * <b>excludedsmartlist</b>, even if they are the only nodes
755 * available. If <b>strict</b> is true, never pick any node besides
756 * those in <b>preferred</b>.
757 * If <b>need_uptime</b> is non-zero, don't return a router with less
758 * than a minimum uptime.
759 * If <b>need_capacity</b> is non-zero, weight your choice by the
760 * advertised capacity of each router.
762 routerinfo_t *
763 router_choose_random_node(const char *preferred,
764 const char *excluded,
765 smartlist_t *excludedsmartlist,
766 int need_uptime, int need_capacity,
767 int allow_unverified, int strict)
769 smartlist_t *sl, *excludednodes;
770 routerinfo_t *choice;
772 excludednodes = smartlist_create();
773 add_nickname_list_to_smartlist(excludednodes,excluded,0);
775 /* Try the preferred nodes first. Ignore need_uptime and need_capacity,
776 * since the user explicitly asked for these nodes. */
777 sl = smartlist_create();
778 add_nickname_list_to_smartlist(sl,preferred,1);
779 smartlist_subtract(sl,excludednodes);
780 if (excludedsmartlist)
781 smartlist_subtract(sl,excludedsmartlist);
782 choice = smartlist_choose(sl);
783 smartlist_free(sl);
784 if (!choice && !strict) {
785 /* Then give up on our preferred choices: any node
786 * will do that has the required attributes. */
787 sl = smartlist_create();
788 router_add_running_routers_to_smartlist(sl, allow_unverified,
789 need_uptime, need_capacity);
790 smartlist_subtract(sl,excludednodes);
791 if (excludedsmartlist)
792 smartlist_subtract(sl,excludedsmartlist);
793 if (need_uptime)
794 routerlist_sl_remove_unreliable_routers(sl);
795 if (need_capacity)
796 choice = routerlist_sl_choose_by_bandwidth(sl);
797 else
798 choice = smartlist_choose(sl);
799 smartlist_free(sl);
801 smartlist_free(excludednodes);
802 if (!choice)
803 log_fn(LOG_WARN,"No available nodes when trying to choose node. Failing.");
804 return choice;
807 /** Return true iff the digest of <b>router</b>'s identity key,
808 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
809 * optionally prefixed with a single dollar sign). Return false if
810 * <b>hexdigest</b> is malformed, or it doesn't match. */
811 static INLINE int
812 router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
814 char digest[DIGEST_LEN];
815 tor_assert(hexdigest);
816 if (hexdigest[0] == '$')
817 ++hexdigest;
819 if (strlen(hexdigest) != HEX_DIGEST_LEN ||
820 base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
821 return 0;
822 return (!memcmp(digest, router->identity_digest, DIGEST_LEN));
825 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
826 * (case-insensitive), or if <b>router's</b> identity key digest
827 * matches a hexadecimal value stored in <b>nickname</b>. Return
828 * false otherwise. */
829 static int
830 router_nickname_matches(routerinfo_t *router, const char *nickname)
832 if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
833 return 1;
834 return router_hex_digest_matches(router, nickname);
837 /** Return the router in our routerlist whose (case-insensitive)
838 * nickname or (case-sensitive) hexadecimal key digest is
839 * <b>nickname</b>. Return NULL if no such router is known.
841 routerinfo_t *
842 router_get_by_nickname(const char *nickname)
844 int maybedigest;
845 char digest[DIGEST_LEN];
847 tor_assert(nickname);
848 if (!routerlist)
849 return NULL;
850 if (nickname[0] == '$')
851 return router_get_by_hexdigest(nickname);
852 if (server_mode(get_options()) &&
853 !strcasecmp(nickname, get_options()->Nickname))
854 return router_get_my_routerinfo();
856 maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
857 (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
859 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
861 /* XXXX011 NM Should this restrict by Named rouers, or warn on
862 * non-named routers, or something? */
863 if (0 == strcasecmp(router->nickname, nickname) ||
864 (maybedigest && 0 == memcmp(digest, router->identity_digest,
865 DIGEST_LEN)))
866 return router;
869 return NULL;
872 /** Return true iff <b>digest</b> is the digest of the identity key of
873 * a trusted directory. */
875 router_digest_is_trusted_dir(const char *digest)
877 if (!trusted_dir_servers)
878 return 0;
879 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
880 if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
881 return 0;
884 /** Return the router in our routerlist whose hexadecimal key digest
885 * is <b>hexdigest</b>. Return NULL if no such router is known. */
886 routerinfo_t *
887 router_get_by_hexdigest(const char *hexdigest)
889 char digest[DIGEST_LEN];
891 tor_assert(hexdigest);
892 if (!routerlist)
893 return NULL;
894 if (hexdigest[0]=='$')
895 ++hexdigest;
896 if (strlen(hexdigest) != HEX_DIGEST_LEN ||
897 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
898 return NULL;
900 return router_get_by_digest(digest);
903 /** Return the router in our routerlist whose 20-byte key digest
904 * is <b>digest</b>. Return NULL if no such router is known. */
905 routerinfo_t *
906 router_get_by_digest(const char *digest)
908 tor_assert(digest);
910 if (!routerlist) return NULL;
912 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t*, router,
914 if (0 == memcmp(router->identity_digest, digest, DIGEST_LEN))
915 return router;
918 return NULL;
921 /** Set *<b>prouterlist</b> to the current list of all known routers. */
922 void
923 router_get_routerlist(routerlist_t **prouterlist)
925 *prouterlist = routerlist;
928 /** Free all storage held by <b>router</b>. */
929 void
930 routerinfo_free(routerinfo_t *router)
932 if (!router)
933 return;
935 tor_free(router->signed_descriptor);
936 tor_free(router->address);
937 tor_free(router->nickname);
938 tor_free(router->platform);
939 tor_free(router->contact_info);
940 if (router->onion_pkey)
941 crypto_free_pk_env(router->onion_pkey);
942 if (router->identity_pkey)
943 crypto_free_pk_env(router->identity_pkey);
944 if (router->declared_family) {
945 SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
946 smartlist_free(router->declared_family);
948 addr_policy_free(router->exit_policy);
949 tor_free(router);
952 /** Allocate a fresh copy of <b>router</b> */
953 routerinfo_t *
954 routerinfo_copy(const routerinfo_t *router)
956 routerinfo_t *r;
957 addr_policy_t **e, *tmp;
959 r = tor_malloc(sizeof(routerinfo_t));
960 memcpy(r, router, sizeof(routerinfo_t));
962 r->address = tor_strdup(r->address);
963 r->nickname = tor_strdup(r->nickname);
964 r->platform = tor_strdup(r->platform);
965 if (r->signed_descriptor)
966 r->signed_descriptor = tor_strdup(r->signed_descriptor);
967 if (r->onion_pkey)
968 r->onion_pkey = crypto_pk_dup_key(r->onion_pkey);
969 if (r->identity_pkey)
970 r->identity_pkey = crypto_pk_dup_key(r->identity_pkey);
971 e = &r->exit_policy;
972 while (*e) {
973 tmp = tor_malloc(sizeof(addr_policy_t));
974 memcpy(tmp,*e,sizeof(addr_policy_t));
975 *e = tmp;
976 (*e)->string = tor_strdup((*e)->string);
977 e = & ((*e)->next);
979 if (r->declared_family) {
980 r->declared_family = smartlist_create();
981 SMARTLIST_FOREACH(router->declared_family, const char *, s,
982 smartlist_add(r->declared_family, tor_strdup(s)));
984 return r;
987 /** Free all storage held by a routerlist <b>rl</b> */
988 void
989 routerlist_free(routerlist_t *rl)
991 tor_assert(rl);
992 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
993 routerinfo_free(r));
994 smartlist_free(rl->routers);
995 tor_free(rl);
998 /** Free all memory held by the rouerlist module */
999 void
1000 routerlist_free_all(void)
1002 if (routerlist)
1003 routerlist_free(routerlist);
1004 routerlist = NULL;
1005 if (warned_nicknames) {
1006 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1007 smartlist_free(warned_nicknames);
1008 warned_nicknames = NULL;
1010 if (trusted_dir_servers) {
1011 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
1012 { tor_free(ds->address); tor_free(ds); });
1013 smartlist_free(trusted_dir_servers);
1014 trusted_dir_servers = NULL;
1016 if (networkstatus_list) {
1017 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
1018 networkstatus_free(ns));
1019 smartlist_free(networkstatus_list);
1020 networkstatus_list = NULL;
1022 if (routerstatus_list) {
1023 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
1024 local_routerstatus_free(rs));
1025 smartlist_free(routerstatus_list);
1026 routerstatus_list = NULL;
1030 /** Free all storage held by the routerstatus object <b>rs</b>. */
1031 void
1032 routerstatus_free(routerstatus_t *rs)
1034 tor_free(rs);
1037 /** Free all storage held by the local_routerstatus object <b>rs</b>. */
1038 static void
1039 local_routerstatus_free(local_routerstatus_t *rs)
1041 tor_free(rs);
1044 /** Free all storage held by the networkstatus object <b>ns</b>. */
1045 void
1046 networkstatus_free(networkstatus_t *ns)
1048 tor_free(ns->source_address);
1049 tor_free(ns->contact);
1050 if (ns->signing_key)
1051 crypto_free_pk_env(ns->signing_key);
1052 tor_free(ns->client_versions);
1053 tor_free(ns->server_versions);
1054 if (ns->entries) {
1055 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs, routerstatus_free(rs));
1056 smartlist_free(ns->entries);
1058 tor_free(ns);
1061 /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
1062 void
1063 router_mark_as_down(const char *digest)
1065 routerinfo_t *router;
1066 tor_assert(digest);
1068 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
1069 if (!memcmp(d->digest, digest, DIGEST_LEN))
1070 d->is_running = 0);
1072 router = router_get_by_digest(digest);
1073 if (!router) /* we don't seem to know about him in the first place */
1074 return;
1075 log_fn(LOG_DEBUG,"Marking router '%s' as down.",router->nickname);
1076 if (router_is_me(router) && !we_are_hibernating())
1077 log_fn(LOG_WARN, "We just marked ourself as down. Are your external addresses reachable?");
1078 router->is_running = 0;
1081 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
1082 * older entries (if any) with the same key. Note: Callers should not hold
1083 * their pointers to <b>router</b> if this function fails; <b>router</b>
1084 * will either be inserted into the routerlist or freed.
1086 * Returns >= 0 if the router was added; less than 0 if it was not.
1088 * If we're returning non-zero, then assign to *<b>msg</b> a static string
1089 * describing the reason for not liking the routerinfo.
1091 * If the return value is less than -1, there was a problem with the
1092 * routerinfo. If the return value is equal to -1, then the routerinfo was
1093 * fine, but out-of-date. If the return value is equal to 1, the
1094 * routerinfo was accepted, but we should notify the generator of the
1095 * descriptor using the message *<b>msg</b>.
1097 * This function should be called *after*
1098 * routers_update_status_from_networkstatus; subsequenctly, you should call
1099 * router_rebuild_store and control_event_descriptors_changed.
1101 * XXXX never replace your own descriptor.
1104 router_add_to_routerlist(routerinfo_t *router, const char **msg,
1105 int from_cache)
1107 int i;
1108 char id_digest[DIGEST_LEN];
1109 int authdir = get_options()->AuthoritativeDir;
1110 int authdir_verified = 0;
1112 tor_assert(msg);
1114 if (!routerlist) {
1115 routerlist = tor_malloc_zero(sizeof(routerlist_t));
1116 routerlist->routers = smartlist_create();
1119 crypto_pk_get_digest(router->identity_pkey, id_digest);
1121 if (authdir) {
1122 if (authdir_wants_to_reject_router(router, msg))
1123 return -2;
1124 authdir_verified = router->is_verified;
1127 /* If we have a router with this name, and the identity key is the same,
1128 * choose the newer one. If the identity key has changed, drop the router.
1130 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
1131 routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
1132 if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
1133 if (router->published_on <= old_router->published_on) {
1134 /* Same key, but old */
1135 log_fn(LOG_DEBUG, "Skipping not-new descriptor for router '%s'",
1136 router->nickname);
1137 routerinfo_free(router);
1138 *msg = "Router descriptor was not new.";
1139 return -1;
1140 } else {
1141 /* Same key, new. */
1142 int unreachable = 0;
1143 log_fn(LOG_DEBUG, "Replacing entry for router '%s/%s' [%s]",
1144 router->nickname, old_router->nickname,
1145 hex_str(id_digest,DIGEST_LEN));
1146 if (router->addr == old_router->addr &&
1147 router->or_port == old_router->or_port) {
1148 /* these carry over when the address and orport are unchanged.*/
1149 router->last_reachable = old_router->last_reachable;
1150 router->testing_since = old_router->testing_since;
1151 router->num_unreachable_notifications =
1152 old_router->num_unreachable_notifications;
1154 if (authdir &&
1155 dirserv_thinks_router_is_blatantly_unreachable(router, time(NULL))) {
1156 if (router->num_unreachable_notifications >= 3) {
1157 unreachable = 1;
1158 log_fn(LOG_NOTICE, "Notifying server '%s' that it's unreachable. (ContactInfo '%s', platform '%s').",
1159 router->nickname, router->contact_info ? router->contact_info : "",
1160 router->platform ? router->platform : "");
1161 } else {
1162 log_fn(LOG_INFO,"'%s' may be unreachable -- the %d previous descriptors were thought to be unreachable.", router->nickname, router->num_unreachable_notifications);
1163 router->num_unreachable_notifications++;
1166 routerinfo_free(old_router);
1167 smartlist_set(routerlist->routers, i, router);
1168 if (!from_cache)
1169 router_append_to_journal(router->signed_descriptor,
1170 router->signed_descriptor_len);
1171 directory_set_dirty();
1172 *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
1173 authdir_verified ? "Verified server updated" :
1174 "Unverified server updated. (Have you sent us your key fingerprint?)";
1175 return unreachable ? 1 : 0;
1177 } else if (!strcasecmp(router->nickname, old_router->nickname)) {
1178 /* nicknames match, keys don't. */
1179 if (router->is_named) {
1180 /* The new verified router replaces the old one; remove the
1181 * old one. And carry on to the end of the list, in case
1182 * there are more old unverified routers with this nickname
1184 /* mark-for-close connections using the old key, so we can
1185 * make new ones with the new key.
1187 connection_t *conn;
1188 while ((conn = connection_get_by_identity_digest(
1189 old_router->identity_digest, CONN_TYPE_OR))) {
1190 log_fn(LOG_INFO,"Closing conn to obsolete router '%s'",
1191 old_router->nickname);
1192 connection_mark_for_close(conn);
1194 routerinfo_free(old_router);
1195 smartlist_del_keeporder(routerlist->routers, i--);
1196 } else if (old_router->is_named) {
1197 /* Can't replace a verified router with an unverified one. */
1198 log_fn(LOG_DEBUG, "Skipping unverified entry for verified router '%s'",
1199 router->nickname);
1200 routerinfo_free(router);
1201 *msg = "Already have verified router with same nickname and different key.";
1202 return -2;
1206 /* We haven't seen a router with this name before. Add it to the end of
1207 * the list. */
1208 smartlist_add(routerlist->routers, router);
1209 if (!from_cache)
1210 router_append_to_journal(router->signed_descriptor,
1211 router->signed_descriptor_len);
1212 directory_set_dirty();
1213 return 0;
1216 /** Remove any routers from the routerlist that are more than <b>age</b>
1217 * seconds old.
1219 void
1220 routerlist_remove_old_routers(int age)
1222 int i;
1223 time_t cutoff;
1224 routerinfo_t *router;
1225 if (!routerlist)
1226 return;
1228 cutoff = time(NULL) - age;
1229 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
1230 router = smartlist_get(routerlist->routers, i);
1231 if (router->published_on <= cutoff) {
1232 /* Too old. Remove it. */
1233 log_fn(LOG_INFO,"Forgetting obsolete routerinfo for router '%s'", router->nickname);
1234 routerinfo_free(router);
1235 smartlist_del(routerlist->routers, i--);
1241 * Code to parse a single router descriptor and insert it into the
1242 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
1243 * descriptor was well-formed but could not be added; and 1 if the
1244 * descriptor was added.
1246 * If we don't add it and <b>msg</b> is not NULL, then assign to
1247 * *<b>msg</b> a static string describing the reason for refusing the
1248 * descriptor.
1250 * This is used only by the controller.
1253 router_load_single_router(const char *s, const char **msg)
1255 routerinfo_t *ri;
1256 tor_assert(msg);
1257 *msg = NULL;
1259 if (!(ri = router_parse_entry_from_string(s, NULL))) {
1260 log_fn(LOG_WARN, "Error parsing router descriptor; dropping.");
1261 *msg = "Couldn't parse router descriptor.";
1262 return -1;
1264 if (router_is_me(ri)) {
1265 log_fn(LOG_WARN, "Router's identity key matches mine; dropping.");
1266 *msg = "Router's identity key matches mine.";
1267 routerinfo_free(ri);
1268 return 0;
1270 /* XXXX011 update router status from networkstatus!! */
1272 if (router_add_to_routerlist(ri, msg, 0)<0) {
1273 log_fn(LOG_WARN, "Couldn't add router to list: %s Dropping.",
1274 *msg?*msg:"(No message).");
1275 /* we've already assigned to *msg now, and ri is already freed */
1276 return 0;
1277 } else {
1278 smartlist_t *changed = smartlist_create();
1279 smartlist_add(changed, ri);
1280 control_event_descriptors_changed(changed);
1281 smartlist_free(changed);
1284 log_fn(LOG_DEBUG, "Added router to list");
1285 return 1;
1288 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
1289 * routers into our directory. If <b>from_cache</b> is false, the routers
1290 * have come from the network: cache them.
1292 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1293 * uppercased identity fingerprints. Do not update any router whose
1294 * fingerprint is not on the list; after updating a router, remove its
1295 * fingerprint from the list.
1297 void
1298 router_load_routers_from_string(const char *s, int from_cache,
1299 smartlist_t *requested_fingerprints)
1301 smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
1302 char fp[HEX_DIGEST_LEN+1];
1303 const char *msg;
1305 router_parse_list_from_string(&s, routers);
1307 routers_update_status_from_networkstatus(routers, !from_cache);
1309 SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
1311 base16_encode(fp, sizeof(fp), ri->identity_digest, DIGEST_LEN);
1312 if (requested_fingerprints) {
1313 if (smartlist_string_isin(requested_fingerprints, fp)) {
1314 smartlist_string_remove(requested_fingerprints, fp);
1315 } else {
1316 char *requested =
1317 smartlist_join_strings(requested_fingerprints," ",0,NULL);
1318 log_fn(LOG_WARN, "We received a router descriptor with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
1319 tor_free(requested);
1320 routerinfo_free(ri);
1321 continue;
1325 if (router_add_to_routerlist(ri, &msg, from_cache) >= 0)
1326 smartlist_add(changed, ri);
1329 control_event_descriptors_changed(changed);
1331 router_rebuild_store(0);
1333 smartlist_free(routers);
1334 smartlist_free(changed);
1337 /** Helper: return a newly allocated string containing the name of the filename
1338 * where we plan to cache <b>ns</b>. */
1339 static char *
1340 networkstatus_get_cache_filename(const networkstatus_t *ns)
1342 const char *datadir = get_options()->DataDirectory;
1343 size_t len = strlen(datadir)+64;
1344 char fp[HEX_DIGEST_LEN+1];
1345 char *fn = tor_malloc(len+1);
1346 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
1347 tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
1348 return fn;
1351 /** Helper for smartlist_sort: Compare two networkstatus objects by
1352 * publication date. */
1353 static int
1354 _compare_networkstatus_published_on(const void **_a, const void **_b)
1356 const networkstatus_t *a = *_a, *b = *_b;
1357 if (a->published_on < b->published_on)
1358 return -1;
1359 else if (a->published_on > b->published_on)
1360 return 1;
1361 else
1362 return 0;
1365 /** How far in the future do we allow a network-status to get before removing
1366 * it? (seconds) */
1367 #define NETWORKSTATUS_ALLOW_SKEW (48*60*60)
1368 /** Given a string <b>s</b> containing a network status that we received at
1369 * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
1370 * store it, and put it into our cache is necessary.
1372 * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
1373 * own networkstatus_t (if we're a directory server).
1375 * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
1376 * cache.
1378 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1379 * uppercased identity fingerprints. Do not update any networkstatus whose
1380 * fingerprint is not on the list; after updating a networkstatus, remove its
1381 * fingerprint from the list.
1383 * Return 0 on success, -1 on failure.
1385 * Callers should make sure that routers_update_all_from_networkstatus() is
1386 * invoked after this function succeeds.
1389 router_set_networkstatus(const char *s, time_t arrived_at,
1390 networkstatus_source_t source, smartlist_t *requested_fingerprints)
1392 networkstatus_t *ns;
1393 int i, found;
1394 time_t now;
1395 int skewed = 0;
1396 trusted_dir_server_t *trusted_dir;
1397 char fp[HEX_DIGEST_LEN+1];
1398 char published[ISO_TIME_LEN+1];
1400 ns = networkstatus_parse_from_string(s);
1401 if (!ns) {
1402 log_fn(LOG_WARN, "Couldn't parse network status.");
1403 return -1;
1405 if (!(trusted_dir=router_get_trusteddirserver_by_digest(ns->identity_digest))) {
1406 log_fn(LOG_INFO, "Network status was signed, but not by an authoritative directory we recognize.");
1407 networkstatus_free(ns);
1408 return -1;
1410 now = time(NULL);
1411 if (arrived_at > now)
1412 arrived_at = now;
1414 ns->received_on = arrived_at;
1416 format_iso_time(published, ns->published_on);
1418 if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
1419 log_fn(LOG_WARN, "Network status was published in the future (%s GMT). Somebody is skewed here: check your clock. Not caching.", published);
1420 skewed = 1;
1423 if (!networkstatus_list)
1424 networkstatus_list = smartlist_create();
1426 if (source == NS_FROM_DIR && router_digest_is_me(ns->identity_digest)) {
1427 /* Don't replace our own networkstatus when we get it from somebody else. */
1428 networkstatus_free(ns);
1429 return 0;
1432 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
1434 if (requested_fingerprints) {
1435 if (smartlist_string_isin(requested_fingerprints, fp)) {
1436 smartlist_string_remove(requested_fingerprints, fp);
1437 } else {
1438 char *requested = smartlist_join_strings(requested_fingerprints," ",0,NULL);
1439 log_fn(LOG_WARN, "We received a network status with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
1440 tor_free(requested);
1441 return 0;
1445 if (source != NS_FROM_CACHE)
1446 trusted_dir->n_networkstatus_failures = 0;
1448 found = 0;
1449 for (i=0; i < smartlist_len(networkstatus_list); ++i) {
1450 networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
1452 if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
1453 if (!memcmp(old_ns->networkstatus_digest,
1454 ns->networkstatus_digest, DIGEST_LEN)) {
1455 /* Same one we had before. */
1456 networkstatus_free(ns);
1457 log_fn(LOG_NOTICE,
1458 "Dropping network-status from %s:%d (published %s); already have it.",
1459 trusted_dir->address, trusted_dir->dir_port, published);
1460 if (old_ns->received_on < arrived_at) {
1461 if (source != NS_FROM_CACHE) {
1462 char *fn = networkstatus_get_cache_filename(old_ns);
1463 /* We use mtime to tell when it arrived, so update that. */
1464 touch_file(fn);
1465 tor_free(fn);
1467 old_ns->received_on = arrived_at;
1469 return 0;
1470 } else if (old_ns->published_on >= ns->published_on) {
1471 char old_published[ISO_TIME_LEN+1];
1472 format_iso_time(old_published, old_ns->published_on);
1473 log_fn(LOG_NOTICE,
1474 "Dropping network-status from %s:%d (published %s);"
1475 " we have a newer one (published %s) for this authority.",
1476 trusted_dir->address, trusted_dir->dir_port, published,
1477 old_published);
1478 networkstatus_free(ns);
1479 return 0;
1480 } else {
1481 networkstatus_free(old_ns);
1482 smartlist_set(networkstatus_list, i, ns);
1483 found = 1;
1484 break;
1489 if (!found)
1490 smartlist_add(networkstatus_list, ns);
1492 /*XXXX011 downgrade to INFO NM */
1493 log_fn(LOG_NOTICE, "Setting networkstatus %s %s:%d (published %s)",
1494 source == NS_FROM_CACHE?"cached from":
1495 (source==NS_FROM_DIR?"downloaded from":"generated for"),
1496 trusted_dir->address, trusted_dir->dir_port, published);
1497 networkstatus_list_has_changed = 1;
1499 smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
1501 if (source != NS_FROM_CACHE && !skewed) {
1502 char *fn = networkstatus_get_cache_filename(ns);
1503 if (write_str_to_file(fn, s, 0)<0) {
1504 log_fn(LOG_NOTICE, "Couldn't write cached network status to \"%s\"", fn);
1506 tor_free(fn);
1509 networkstatus_list_update_recent(now);
1511 if (get_options()->DirPort && !skewed)
1512 dirserv_set_cached_networkstatus_v2(s, fp, ns->published_on);
1514 return 0;
1517 /** How old do we allow a network-status to get before removing it completely? */
1518 #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
1519 /** Remove all very-old network_status_t objects from memory and from the
1520 * disk cache. */
1521 void
1522 networkstatus_list_clean(time_t now)
1524 int i;
1525 if (!networkstatus_list)
1526 return;
1528 for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
1529 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
1530 char *fname = NULL;;
1531 if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
1532 continue;
1533 /* Okay, this one is too old. Remove it from the list, and delete it
1534 * from the cache. */
1535 smartlist_del(networkstatus_list, i--);
1536 fname = networkstatus_get_cache_filename(ns);
1537 if (file_status(fname) == FN_FILE) {
1538 log_fn(LOG_INFO, "Removing too-old networkstatus in %s", fname);
1539 unlink(fname);
1541 tor_free(fname);
1542 if (get_options()->DirPort) {
1543 char fp[HEX_DIGEST_LEN+1];
1544 base16_encode(fp, sizeof(fp), ns->identity_digest, DIGEST_LEN);
1545 dirserv_set_cached_networkstatus_v2(NULL, fp, 0);
1547 networkstatus_free(ns);
1551 /** Helper for bsearching a list of routerstatus_t pointers.*/
1552 static int
1553 _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
1555 const char *key = _key;
1556 const routerstatus_t *rs = *_member;
1557 return memcmp(key, rs->identity_digest, DIGEST_LEN);
1560 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
1561 * NULL if none was found. */
1562 static routerstatus_t *
1563 networkstatus_find_entry(networkstatus_t *ns, const char *digest)
1565 return smartlist_bsearch(ns->entries, digest,
1566 _compare_digest_to_routerstatus_entry);
1569 /** Return the consensus view of the status of the router whose digest is
1570 * <b>digest</b>, or NULL if we don't know about any such router. */
1571 local_routerstatus_t *
1572 router_get_combined_status_by_digest(const char *digest)
1574 if (!routerstatus_list)
1575 return NULL;
1576 return smartlist_bsearch(routerstatus_list, digest,
1577 _compare_digest_to_routerstatus_entry);
1580 /* XXXX These should be configurable, perhaps? NM */
1581 #define AUTHORITY_NS_CACHE_INTERVAL 10*60
1582 #define NONAUTHORITY_NS_CACHE_INTERVAL 15*60
1583 /** We are a directory server, and so cache network_status documents.
1584 * Initiate downloads as needed to update them. For authorities, this means
1585 * asking each trusted directory for its network-status. For caches, this means
1586 * asking a random authority for all network-statuses.
1588 void
1589 update_networkstatus_cache_downloads(time_t now)
1591 static time_t last_downloaded = 0;
1592 int authority = authdir_mode(get_options());
1593 int interval =
1594 authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
1596 /*XXXXX NM we should retry on failure. */
1597 if (last_downloaded + interval >= now)
1598 return;
1599 if (!trusted_dir_servers)
1600 return;
1602 last_downloaded = now;
1604 if (authority) {
1605 /* An authority launches a separate connection for everybody. */
1606 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
1608 char resource[HEX_DIGEST_LEN+6];
1609 if (router_digest_is_me(ds->digest))
1610 continue;
1611 if (connection_get_by_type_addr_port_purpose(
1612 CONN_TYPE_DIR, ds->addr, ds->dir_port,
1613 DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
1614 /* We are already fetching this one. */
1615 continue;
1617 strlcpy(resource, "fp/", sizeof(resource));
1618 base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
1619 strlcat(resource, ".z", sizeof(resource));
1620 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,resource,1);
1622 } else {
1623 /* A non-authority cache launches one connection to a random authority. */
1624 /* (Check whether we're currently fetching network-status objects.) */
1625 if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
1626 DIR_PURPOSE_FETCH_NETWORKSTATUS))
1627 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
1631 /*XXXX Should these be configurable? NM*/
1632 /** How old (in seconds) can a network-status be before we try replacing it? */
1633 #define NETWORKSTATUS_MAX_VALIDITY (48*60*60)
1634 /** How long (in seconds) does a client wait after getting a network status
1635 * before downloading the next in sequence? */
1636 #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
1637 /* How many times do we allow a networkstatus download to fail before we
1638 * assume that the authority isn't publishing? */
1639 #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
1640 /** We are not a directory cache or authority. Update our network-status list
1641 * by launching a new directory fetch for enough network-status documents "as
1642 * necessary". See function comments for implementation details.
1644 void
1645 update_networkstatus_client_downloads(time_t now)
1647 int n_live = 0, needed = 0, n_running_dirservers, n_dirservers, i;
1648 int most_recent_idx = -1;
1649 trusted_dir_server_t *most_recent = NULL;
1650 time_t most_recent_received = 0;
1651 char *resource, *cp;
1652 size_t resource_len;
1654 if (connection_get_by_type_purpose(CONN_TYPE_DIR,
1655 DIR_PURPOSE_FETCH_NETWORKSTATUS))
1656 return;
1658 /* This is a little tricky. We want to download enough network-status
1659 * objects so that we have at least half of them under
1660 * NETWORKSTATUS_MAX_VALIDITY publication time. We want to download a new
1661 * *one* if the most recent one's publication time is under
1662 * NETWORKSTATUS_CLIENT_DL_INTERVAL.
1664 if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
1665 return;
1666 n_dirservers = n_running_dirservers = smartlist_len(trusted_dir_servers);
1667 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
1669 networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
1670 if (!ns)
1671 continue;
1672 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
1673 --n_running_dirservers;
1674 continue;
1676 if (ns->published_on > now-NETWORKSTATUS_MAX_VALIDITY)
1677 ++n_live;
1678 if (!most_recent || ns->received_on > most_recent_received) {
1679 most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
1680 most_recent = ds;
1681 most_recent_received = ns->received_on;
1685 /* Download enough so we have at least half live, but no more than all the
1686 * trusted dirservers we know.
1688 if (n_live < (n_dirservers/2)+1)
1689 needed = (n_dirservers/2)+1-n_live;
1690 if (needed > n_running_dirservers)
1691 needed = n_running_dirservers;
1693 if (needed)
1694 /* XXXX011 Downgrade to info NM */
1695 log_fn(LOG_NOTICE, "For %d/%d running directory servers, we have %d live"
1696 " network-status documents. Downloading %d.",
1697 n_running_dirservers, n_dirservers, n_live, needed);
1699 /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
1700 if (n_running_dirservers &&
1701 most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL && needed < 1) {
1702 const char *addr = most_recent?most_recent->address:"nobody";
1703 int port = most_recent?most_recent->dir_port:0;
1704 log_fn(LOG_NOTICE, "Our most recent network-status document (from %s:%d) "
1705 "is %d seconds old; downloading another.",
1706 addr, port, (int)(now-most_recent_received));
1707 needed = 1;
1710 if (!needed)
1711 return;
1713 /* If no networkstatus was found, choose a dirserver at random as "most
1714 * recent". */
1715 if (most_recent_idx<0)
1716 most_recent_idx = crypto_pseudo_rand_int(n_dirservers);
1718 /* Build a request string for all the resources we want. */
1719 resource_len = needed * (HEX_DIGEST_LEN+1) + 6;
1720 resource = tor_malloc(resource_len);
1721 memcpy(resource, "fp/", 3);
1722 cp = resource+3;
1723 for (i = most_recent_idx+1; needed; ++i) {
1724 trusted_dir_server_t *ds;
1725 if (i >= n_dirservers)
1726 i = 0;
1727 ds = smartlist_get(trusted_dir_servers, i);
1728 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES)
1729 continue;
1730 base16_encode(cp, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
1731 cp += HEX_DIGEST_LEN;
1732 --needed;
1733 if (needed)
1734 *cp++ = '+';
1736 memcpy(cp, ".z", 3);
1737 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
1738 tor_free(resource);
1741 /** Decide whether a given addr:port is definitely accepted,
1742 * definitely rejected, probably accepted, or probably rejected by a
1743 * given policy. If <b>addr</b> is 0, we don't know the IP of the
1744 * target address. If <b>port</b> is 0, we don't know the port of the
1745 * target address.
1747 * For now, the algorithm is pretty simple: we look for definite and
1748 * uncertain matches. The first definite match is what we guess; if
1749 * it was preceded by no uncertain matches of the opposite policy,
1750 * then the guess is definite; otherwise it is probable. (If we
1751 * have a known addr and port, all matches are definite; if we have an
1752 * unknown addr/port, any address/port ranges other than "all" are
1753 * uncertain.)
1755 * We could do better by assuming that some ranges never match typical
1756 * addresses (127.0.0.1, and so on). But we'll try this for now.
1758 addr_policy_result_t
1759 router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
1760 addr_policy_t *policy)
1762 int maybe_reject = 0;
1763 int maybe_accept = 0;
1764 int match = 0;
1765 int maybe = 0;
1766 addr_policy_t *tmpe;
1768 for (tmpe=policy; tmpe; tmpe=tmpe->next) {
1769 maybe = 0;
1770 if (!addr) {
1771 /* Address is unknown. */
1772 if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
1773 (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
1774 /* The port definitely matches. */
1775 if (tmpe->msk == 0) {
1776 match = 1;
1777 } else {
1778 maybe = 1;
1780 } else if (!port) {
1781 /* The port maybe matches. */
1782 maybe = 1;
1784 } else {
1785 /* Address is known */
1786 if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
1787 if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
1788 /* Exact match for the policy */
1789 match = 1;
1790 } else if (!port) {
1791 maybe = 1;
1795 if (maybe) {
1796 if (tmpe->policy_type == ADDR_POLICY_REJECT)
1797 maybe_reject = 1;
1798 else
1799 maybe_accept = 1;
1801 if (match) {
1802 if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
1803 /* If we already hit a clause that might trigger a 'reject', than we
1804 * can't be sure of this certain 'accept'.*/
1805 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
1806 } else {
1807 return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED : ADDR_POLICY_REJECTED;
1811 /* accept all by default. */
1812 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
1815 /** Return 1 if all running sufficiently-stable routers will reject
1816 * addr:port, return 0 if any might accept it. */
1818 router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
1819 int need_uptime)
1821 addr_policy_result_t r;
1822 if (!routerlist) return 1;
1824 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
1826 if (router->is_running &&
1827 !router_is_unreliable(router, need_uptime, 0)) {
1828 r = router_compare_addr_to_addr_policy(addr, port, router->exit_policy);
1829 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
1830 return 0; /* this one could be ok. good enough. */
1833 return 1; /* all will reject. */
1837 * If <b>policy</b> implicitly allows connections to any port in the
1838 * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
1839 * part of the policy that allows it, and return 1. Else return 0.
1841 * A policy allows an IP:Port combination <em>implicitly</em> if
1842 * it is included in a *: pattern, or in a fallback pattern.
1844 static int
1845 policy_includes_addr_mask_implicitly(addr_policy_t *policy,
1846 uint32_t addr, uint32_t mask,
1847 addr_policy_t **policy_out)
1849 uint32_t addr2;
1850 tor_assert(policy_out);
1851 addr &= mask;
1852 addr2 = addr | ~mask;
1853 for (; policy; policy=policy->next) {
1854 /* Does this policy cover all of the address range we're looking at? */
1855 /* Boolean logic time: range X is contained in range Y if, for
1856 * each bit B, all possible values of B in X are values of B in Y.
1857 * In "addr", we have every fixed bit set to its value, and every
1858 * free bit set to 0. In "addr2", we have every fixed bit set to
1859 * its value, and every free bit set to 1. So if addr and addr2 are
1860 * both in the policy, the range is covered by the policy.
1862 uint32_t p_addr = policy->addr & policy->msk;
1863 if (p_addr == (addr & policy->msk) &&
1864 p_addr == (addr2 & policy->msk) &&
1865 (policy->prt_min <= 1 && policy->prt_max == 65535)) {
1866 return 0;
1868 /* Does this policy cover some of the address range we're looking at? */
1869 /* Boolean logic time: range X and range Y intersect if there is
1870 * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
1871 * This is FALSE iff there is some bit b where Xmask == yMask == 1
1872 * and Xaddr != Yaddr. So if X intersects with Y iff at every
1873 * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
1874 * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
1876 if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
1877 policy->policy_type == ADDR_POLICY_ACCEPT) {
1878 *policy_out = policy;
1879 return 1;
1882 *policy_out = NULL;
1883 return 1;
1886 /** If <b>policy</b> implicitly allows connections to any port on
1887 * 127.*, 192.168.*, etc, then warn (if <b>warn</b> is set) and return
1888 * true. Else return false.
1891 exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
1892 int warn)
1894 addr_policy_t *p;
1895 int r=0,i;
1896 static struct {
1897 uint32_t addr; uint32_t mask; const char *network;
1898 } private_networks[] = {
1899 { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
1900 { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
1901 { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
1902 { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
1903 { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
1904 { 0,0,NULL},
1906 for (i=0; private_networks[i].addr; ++i) {
1907 p = NULL;
1908 /* log_fn(LOG_INFO,"Checking network %s", private_networks[i].network); */
1909 if (policy_includes_addr_mask_implicitly(
1910 policy, private_networks[i].addr, private_networks[i].mask, &p)) {
1911 if (warn)
1912 log_fn(LOG_WARN, "Exit policy %s implicitly accepts %s",
1913 p?p->string:"(default)",
1914 private_networks[i].network);
1915 r = 1;
1919 return r;
1922 /** Return true iff <b>router</b> does not permit exit streams.
1925 router_exit_policy_rejects_all(routerinfo_t *router)
1927 return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
1928 == ADDR_POLICY_REJECTED;
1931 /** Add to the list of authorized directory servers one at
1932 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
1933 * <b>address</b> is NULL, add ourself. */
1934 void
1935 add_trusted_dir_server(const char *address, uint16_t port, const char *digest,
1936 int supports_v1)
1938 trusted_dir_server_t *ent;
1939 uint32_t a;
1940 char *hostname = NULL;
1941 if (!trusted_dir_servers)
1942 trusted_dir_servers = smartlist_create();
1944 if (!address) { /* The address is us; we should guess. */
1945 if (resolve_my_address(get_options(), &a, &hostname) < 0) {
1946 log_fn(LOG_WARN, "Couldn't find a suitable address. Returning.");
1947 return;
1949 } else {
1950 if (tor_lookup_hostname(address, &a)) {
1951 log_fn(LOG_WARN, "Unable to lookup address for directory server at %s",
1952 address);
1953 return;
1955 hostname = tor_strdup(address);
1956 a = ntohl(a);
1959 ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
1960 ent->address = hostname;
1961 ent->addr = a;
1962 ent->dir_port = port;
1963 ent->is_running = 1;
1964 ent->supports_v1_protocol = supports_v1;
1965 memcpy(ent->digest, digest, DIGEST_LEN);
1966 smartlist_add(trusted_dir_servers, ent);
1969 /** Remove all members from the list of trusted dir servers. */
1970 void
1971 clear_trusted_dir_servers(void)
1973 if (trusted_dir_servers) {
1974 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
1975 { tor_free(ent->address); tor_free(ent); });
1976 smartlist_clear(trusted_dir_servers);
1977 } else {
1978 trusted_dir_servers = smartlist_create();
1982 /** Return the network status with a given identity digest. */
1983 networkstatus_t *
1984 networkstatus_get_by_digest(const char *digest)
1986 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
1988 if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
1989 return ns;
1991 return NULL;
1994 /** If the network-status list has changed since the last time we called this
1995 * function, update the status of every router from the network-status list.
1997 void
1998 routers_update_all_from_networkstatus(void)
2000 #define SELF_OPINION_INTERVAL 90*60
2001 static int have_warned_about_unverified_status = 0;
2002 static int have_warned_about_old_version = 0;
2003 static int have_warned_about_new_version = 0;
2004 routerinfo_t *me;
2005 time_t now;
2006 if (!routerlist || !networkstatus_list ||
2007 (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
2008 return;
2010 now = time(NULL);
2011 if (networkstatus_list_has_changed)
2012 routerstatus_list_update_from_networkstatus(now);
2014 routers_update_status_from_networkstatus(routerlist->routers, 0);
2016 me = router_get_my_routerinfo();
2017 if (me && !have_warned_about_unverified_status) {
2018 int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0;
2019 routerstatus_t *rs;
2020 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2022 if (ns->received_on + SELF_OPINION_INTERVAL < now)
2023 continue;
2024 ++n_recent;
2025 if (!(rs = networkstatus_find_entry(ns, me->identity_digest)))
2026 continue;
2027 ++n_listing;
2028 if (rs->is_valid)
2029 ++n_valid;
2030 if (rs->is_named)
2031 ++n_named;
2034 if (n_recent >= 2 && n_listing >= 2) {
2035 if (n_valid <= n_recent/2) {
2036 log_fn(LOG_WARN, "%d/%d recent directory servers list us as invalid. Please consider sending your identity fingerprint to the tor-ops.",
2037 n_recent-n_valid, n_recent);
2038 have_warned_about_unverified_status = 1;
2039 } else if (n_named <= n_recent/2) {
2040 log_fn(LOG_WARN, "%d/%d recent directory servers list us as unnamed. Please consider sending your identity fingerprint to the tor-ops.",
2041 n_recent-n_valid, n_recent);
2042 have_warned_about_unverified_status = 1;
2047 helper_nodes_set_status_from_directory();
2049 if (!have_warned_about_old_version) {
2050 int n_recent = 0;
2051 int n_recommended = 0;
2052 int is_server = server_mode(get_options());
2053 version_status_t consensus = VS_RECOMMENDED;
2054 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2056 version_status_t vs;
2057 if (!ns->recommends_versions ||
2058 ns->received_on + SELF_OPINION_INTERVAL < now )
2059 continue;
2060 vs = tor_version_is_obsolete(
2061 VERSION, is_server ? ns->server_versions : ns->client_versions);
2062 if (vs == VS_RECOMMENDED)
2063 ++n_recommended;
2064 if (n_recent++ == 0) {
2065 consensus = vs;
2066 } else if (consensus != vs) {
2067 consensus = version_status_join(consensus, vs);
2070 if (n_recent > 2 && n_recommended < n_recent/2) {
2071 if (consensus == VS_NEW || consensus == VS_NEW_IN_SERIES) {
2072 if (!have_warned_about_new_version) {
2073 log_fn(LOG_NOTICE, "This version of Tor (%s) is newer than any recommended version%s, according to %d/%d recent network statuses.",
2074 VERSION, consensus == VS_NEW_IN_SERIES ? " in its series" : "",
2075 n_recent-n_recommended, n_recent);
2076 have_warned_about_new_version = 1;
2078 } else {
2079 log_fn(LOG_NOTICE, "This version of Tor (%s) is %s, according to %d/%d recent network statuses.",
2080 VERSION, consensus == VS_OLD ? "obsolete" : "not recommended",
2081 n_recent-n_recommended, n_recent);
2082 have_warned_about_old_version = 1;
2084 } else {
2085 log_fn(LOG_INFO, "%d/%d recent directories think my version is ok.",
2086 n_recommended, n_recent);
2090 routerstatus_list_has_changed = 0;
2093 /** Allow any network-status newer than this to influence our view of who's
2094 * running. */
2095 #define DEFAULT_RUNNING_INTERVAL 60*60
2096 /** If possible, always allow at least this many network-statuses to influence
2097 * our view of who's running. */
2098 #define MIN_TO_INFLUENCE_RUNNING 3
2100 /** Change the is_recent field of each member of networkstatus_list so that
2101 * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
2102 * at least the MIN_TO_INFLUENCE_RUNNING most recent members are resent, and no
2103 * others are recent. Set networkstatus_list_has_changed if anything happeed.
2105 void
2106 networkstatus_list_update_recent(time_t now)
2108 int n_statuses, n_recent, changed, i;
2109 char published[ISO_TIME_LEN+1];
2111 if (!networkstatus_list)
2112 return;
2114 n_statuses = smartlist_len(networkstatus_list);
2115 n_recent = 0;
2116 changed = 0;
2117 for (i=n_statuses-1; i >= 0; --i) {
2118 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
2119 if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
2120 ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
2121 if (!ns->is_recent) {
2122 format_iso_time(published, ns->published_on);
2123 log_fn(LOG_NOTICE,
2124 "Networkstatus from %s:%d (published %s) is now \"recent\"",
2125 ns->source_address, ns->source_dirport, published);
2126 changed = 1;
2128 ns->is_recent = 1;
2129 ++n_recent;
2130 } else {
2131 if (ns->is_recent) {
2132 format_iso_time(published, ns->published_on);
2133 log_fn(LOG_NOTICE,
2134 "Networkstatus from %s:%d (published %s) is no longer \"recent\"",
2135 ns->source_address, ns->source_dirport, published);
2136 changed = 1;
2137 ns->is_recent = 0;
2141 if (changed)
2142 networkstatus_list_has_changed = 1;
2145 /** Update our view of router status (as stored in routerstatus_list) from
2146 * the current set of network status documents (as stored in networkstatus_list).
2147 * Do nothing unless the network status list has changed since the last time
2148 * this function was called.
2150 static void
2151 routerstatus_list_update_from_networkstatus(time_t now)
2153 int n_trusted, n_statuses, n_recent=0, n_naming=0;
2154 int n_distinct = 0;
2155 int i;
2156 int *index, *size;
2157 networkstatus_t **networkstatus;
2158 smartlist_t *result;
2159 strmap_t *name_map;
2160 char conflict[DIGEST_LEN];
2162 networkstatus_list_update_recent(now);
2164 if (!networkstatus_list_has_changed)
2165 return;
2166 if (!networkstatus_list)
2167 networkstatus_list = smartlist_create();
2168 if (!routerstatus_list)
2169 routerstatus_list = smartlist_create();
2170 if (!trusted_dir_servers)
2171 trusted_dir_servers = smartlist_create();
2173 n_trusted = smartlist_len(trusted_dir_servers);
2174 n_statuses = smartlist_len(networkstatus_list);
2176 if (n_statuses < (n_trusted/2)+1) {
2177 /* Not enough statuses to adjust status. */
2178 log_fn(LOG_NOTICE,"Not enough statuses to update router status list. (%d/%d)",
2179 n_statuses, n_trusted);
2180 return;
2183 log_fn(LOG_NOTICE, "rebuilding router status list.");
2185 index = tor_malloc(sizeof(int)*n_statuses);
2186 size = tor_malloc(sizeof(int)*n_statuses);
2187 networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
2188 for (i = 0; i < n_statuses; ++i) {
2189 index[i] = 0;
2190 networkstatus[i] = smartlist_get(networkstatus_list, i);
2191 size[i] = smartlist_len(networkstatus[i]->entries);
2192 if (networkstatus[i]->binds_names)
2193 ++n_naming;
2194 if (networkstatus[i]->is_recent)
2195 ++n_recent;
2198 name_map = strmap_new();
2199 memset(conflict, 0xff, sizeof(conflict));
2200 for (i = 0; i < n_statuses; ++i) {
2201 if (!networkstatus[i]->binds_names)
2202 continue;
2203 SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
2205 const char *other_digest;
2206 if (!rs->is_named)
2207 continue;
2208 other_digest = strmap_get_lc(name_map, rs->nickname);
2209 if (!other_digest)
2210 strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
2211 else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
2212 other_digest != conflict) {
2213 /*XXXX011 rate-limit this?*/
2214 log_fn(LOG_WARN,
2215 "Naming authorities disagree about which key goes with %s.",
2216 rs->nickname);
2217 strmap_set_lc(name_map, rs->nickname, conflict);
2222 result = smartlist_create();
2224 /* Iterate through all of the sorted routerstatus lists in step.
2225 * Invariants:
2226 * - For 0 <= i < n_statuses: index[i] is an index into
2227 * networkstatus[i]->entries, which has size[i] elements.
2228 * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
2229 * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
2230 * networkstatus[i2]->entries[index[i2]]->identity_digest.
2232 * (That is, the indices are always advanced past lower digest before
2233 * higher.)
2235 while (1) {
2236 int n_running=0, n_named=0, n_valid=0, n_listing=0;
2237 const char *the_name = NULL;
2238 local_routerstatus_t *rs_out, *rs_old;
2239 routerstatus_t *rs, *most_recent;
2240 networkstatus_t *ns;
2241 const char *lowest = NULL;
2242 /* Find out which of the digests appears first. */
2243 for (i = 0; i < n_statuses; ++i) {
2244 if (index[i] < size[i]) {
2245 rs = smartlist_get(networkstatus[i]->entries, index[i]);
2246 if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
2247 lowest = rs->identity_digest;
2250 if (!lowest) {
2251 /* We're out of routers. Great! */
2252 break;
2254 /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
2255 * match "lowest" are next in order. Iterate over them, incrementing those
2256 * index[i] as we go. */
2257 ++n_distinct;
2258 most_recent = NULL;
2259 for (i = 0; i < n_statuses; ++i) {
2260 if (index[i] >= size[i])
2261 continue;
2262 ns = networkstatus[i];
2263 rs = smartlist_get(ns->entries, index[i]);
2264 if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
2265 continue;
2266 ++index[i];
2267 ++n_listing;
2268 if (!most_recent || rs->published_on > most_recent->published_on)
2269 most_recent = rs;
2270 if (rs->is_named && ns->binds_names) {
2271 if (!the_name)
2272 the_name = rs->nickname;
2273 if (!strcasecmp(rs->nickname, the_name)) {
2274 ++n_named;
2275 } else if (strcmp(the_name,"**mismatch**")) {
2276 char hd[HEX_DIGEST_LEN+1];
2277 base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
2278 log_fn(LOG_WARN, "Naming authorities disagree about nicknames for $%s",
2279 hd);
2280 the_name = "**mismatch**";
2283 if (rs->is_valid)
2284 ++n_valid;
2285 if (rs->is_running && ns->is_recent)
2286 ++n_running;
2288 rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
2289 memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
2290 if ((rs_old = router_get_combined_status_by_digest(lowest))) {
2291 rs_out->n_download_failures = rs_old->n_download_failures;
2292 rs_out->next_attempt_at = rs_old->next_attempt_at;
2294 smartlist_add(result, rs_out);
2295 log_fn(LOG_DEBUG, "Router '%s' is listed by %d/%d directories, "
2296 "named by %d/%d, validated by %d/%d, and %d/%d recent directories "
2297 "think it's running.",
2298 rs_out->status.nickname,
2299 n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
2300 n_running, n_recent);
2301 rs_out->status.is_named = 0;
2302 if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
2303 const char *d = strmap_get_lc(name_map, the_name);
2304 if (d && d != conflict)
2305 rs_out->status.is_named = 1;
2307 if (rs_out->status.is_named)
2308 strlcpy(rs_out->status.nickname, the_name, sizeof(rs_out->status.nickname));
2309 rs_out->status.is_valid = n_valid > n_statuses/2;
2310 rs_out->status.is_running = n_running > n_recent/2;
2312 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
2313 local_routerstatus_free(rs));
2314 smartlist_free(routerstatus_list);
2315 routerstatus_list = result;
2317 tor_free(networkstatus);
2318 tor_free(index);
2319 tor_free(size);
2320 strmap_free(name_map, NULL);
2322 networkstatus_list_has_changed = 0;
2323 routerstatus_list_has_changed = 1;
2326 /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
2327 * is_named, is_verified, and is_running fields according to our current
2328 * networkstatus_t documents. */
2329 void
2330 routers_update_status_from_networkstatus(smartlist_t *routers, int reset_failures)
2332 trusted_dir_server_t *ds;
2333 local_routerstatus_t *rs;
2334 or_options_t *options = get_options();
2335 int authdir = options->AuthoritativeDir;
2336 int namingdir = options->NamingAuthoritativeDir;
2338 if (!routerstatus_list)
2339 return;
2341 SMARTLIST_FOREACH(routers, routerinfo_t *, router,
2343 rs = router_get_combined_status_by_digest(router->identity_digest);
2344 ds = router_get_trusteddirserver_by_digest(router->identity_digest);
2346 if (!rs)
2347 continue;
2349 if (reset_failures) {
2350 rs->n_download_failures = 0;
2351 rs->next_attempt_at = 0;
2354 if (!namingdir)
2355 router->is_named = rs->status.is_named;
2357 if (!authdir) {
2358 /* If we're an authdir, don't believe others. */
2359 router->is_verified = rs->status.is_valid;
2360 router->is_running = rs->status.is_running;
2362 if (router->is_running && ds) {
2363 /* XXXX011 NM Hm. What about authorities? When do they reset
2364 * n_networkstatus_failures? */
2365 ds->n_networkstatus_failures = 0;
2371 /** Return new list of ID fingerprints for superseded routers. A router is
2372 * superseded if any network-status has a router with a different digest
2373 * published more recently, or if it is listed in the network-status but not
2374 * in the router list.
2376 static smartlist_t *
2377 router_list_downloadable(void)
2379 #define MAX_OLD_SERVER_DOWNLOAD_RATE 2*60*60
2380 int n_conns, i, n_downloadable = 0;
2381 int n_uptodate=0,n_skip_old=0;
2382 connection_t **carray;
2383 smartlist_t *superseded = smartlist_create();
2384 smartlist_t *downloading;
2385 time_t now = time(NULL);
2386 int mirror = server_mode(get_options()) && get_options()->DirPort;
2388 if (!routerstatus_list)
2389 return superseded;
2391 get_connection_array(&carray, &n_conns);
2393 routerstatus_list_update_from_networkstatus(now);
2395 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
2397 if (rs->next_attempt_at < now) {
2398 rs->should_download = 1;
2399 ++n_downloadable;
2400 } else {
2402 char fp[HEX_DIGEST_LEN+1];
2403 base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
2404 log_fn(LOG_NOTICE, "Not yet ready to download %s (%d more seconds)", fp,
2405 (int)(rs->next_attempt_at-now));
2407 rs->should_download = 0;
2411 downloading = smartlist_create();
2412 for (i = 0; i < n_conns; ++i) {
2413 connection_t *conn = carray[i];
2414 if (conn->type == CONN_TYPE_DIR &&
2415 conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
2416 !conn->marked_for_close) {
2417 if (!strcmpstart(conn->requested_resource, "all"))
2418 n_downloadable = 0;
2419 dir_split_resource_into_fingerprints(conn->requested_resource,
2420 downloading, NULL);
2425 log_fn(LOG_NOTICE, "%d downloads already in progress",
2426 smartlist_len(downloading));
2427 smartlist_sort_strings(downloading);
2429 if (n_downloadable) {
2430 SMARTLIST_FOREACH(downloading, const char *, dl,
2432 char d[DIGEST_LEN];
2433 local_routerstatus_t *rs;
2434 base16_decode(d, DIGEST_LEN, dl, strlen(dl));
2435 if ((rs = router_get_combined_status_by_digest(d)) && rs->should_download) {
2436 rs->should_download = 0;
2437 --n_downloadable;
2438 // log_fn(LOG_NOTICE, "%s is in-progress; not fetching", dl);
2442 SMARTLIST_FOREACH(downloading, char *, cp, tor_free(cp));
2443 smartlist_free(downloading);
2444 if (!n_downloadable)
2445 return superseded;
2447 if (routerlist) {
2448 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
2450 local_routerstatus_t *rs;
2451 if (!(rs = router_get_combined_status_by_digest(ri->identity_digest)) ||
2452 !rs->should_download) {
2453 // log_fn(LOG_NOTICE, "No status for %s", fp);
2454 continue;
2456 /* Change this "or" to be an "and" once dirs generate hashes right.
2457 * Remove the version check once older versions are uncommon.
2458 * XXXXX. NM */
2459 if (!memcmp(ri->signed_descriptor_digest, rs->status.descriptor_digest,
2460 DIGEST_LEN) ||
2461 rs->status.published_on <= ri->published_on) {
2462 ++n_uptodate;
2463 rs->should_download = 0;
2464 --n_downloadable;
2465 } else if (!mirror &&
2466 ri->platform &&
2467 !tor_version_as_new_as(ri->platform, "0.1.1.6-alpha") &&
2468 ri->published_on + MAX_OLD_SERVER_DOWNLOAD_RATE > now) {
2469 /* Same digest, or date is up-to-date, or we have a comparatively recent
2470 * server with an old version.
2471 * No need to download it. */
2472 // log_fn(LOG_NOTICE, "Up-to-date status for %s", fp);
2473 ++n_skip_old;
2474 rs->should_download = 0;
2475 --n_downloadable;
2476 } /* else {
2477 char t1[ISO_TIME_LEN+1];
2478 char t2[ISO_TIME_LEN+1];
2479 format_iso_time(t1, rs->satus.published_on);
2480 format_iso_time(t2, ri->published_on);
2481 log_fn(LOG_NOTICE, "Out-of-date status for %s %s (%d %d) [%s %s]", fp,
2482 ri->nickname,
2483 !memcmp(ri->signed_descriptor_digest,rs->status.descriptor_digest,
2484 DIGEST_LEN),
2485 rs->published_on < ri->published_on,
2486 t1, t2);
2487 } */
2491 if (n_skip_old)
2492 log_fn(LOG_INFO, "Skipped %d updatable pre-0.1.1.6 servers.", n_skip_old);
2494 if (!n_downloadable)
2495 return superseded;
2497 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
2499 if (rs->should_download) {
2500 char *fp = tor_malloc(HEX_DIGEST_LEN+1);
2501 base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
2502 smartlist_add(superseded, fp);
2506 return superseded;
2509 /** Initiate new router downloads as needed.
2511 * We only allow one router descriptor download at a time.
2512 * If we have less than two network-status documents, we ask
2513 * a directory for "all descriptors."
2514 * Otherwise, we ask for all descriptors that we think are different
2515 * from what we have.
2517 void
2518 update_router_descriptor_downloads(time_t now)
2520 #define MAX_DL_PER_REQUEST 128
2521 #define MIN_DL_PER_REQUEST 4
2522 #define MIN_REQUESTS 3
2523 #define MAX_DL_TO_DELAY 16
2524 #define MAX_INTERVAL_WITHOUT_REQUEST 10*60
2525 smartlist_t *downloadable = NULL;
2526 int get_all = 0;
2527 int mirror = server_mode(get_options()) && get_options()->DirPort;
2528 static time_t last_download_attempted = 0;
2529 if (!networkstatus_list || smartlist_len(networkstatus_list)<2)
2530 get_all = 1;
2532 if (get_all) {
2533 log_fn(LOG_NOTICE, "Launching request for all routers");
2534 last_download_attempted = now;
2535 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,"all.z",1);
2536 return;
2539 downloadable = router_list_downloadable();
2540 if (smartlist_len(downloadable) >= MAX_DL_TO_DELAY ||
2541 (smartlist_len(downloadable) &&
2542 (mirror ||
2543 last_download_attempted + MAX_INTERVAL_WITHOUT_REQUEST < now))) {
2544 int i, j, n, n_per_request=MAX_DL_PER_REQUEST;
2545 size_t r_len = MAX_DL_PER_REQUEST*(HEX_DIGEST_LEN+1)+16;
2546 char *resource = tor_malloc(r_len);
2548 n = smartlist_len(downloadable);
2549 if (! mirror) {
2550 n_per_request = (n+MIN_REQUESTS-1) / MIN_REQUESTS;
2551 if (n_per_request > MAX_DL_PER_REQUEST)
2552 n_per_request = MAX_DL_PER_REQUEST;
2553 if (n_per_request < MIN_DL_PER_REQUEST)
2554 n_per_request = MIN_DL_PER_REQUEST;
2556 log_fn(LOG_NOTICE, "Launching %d request%s for %d router%s, %d at a time",
2557 (n+n_per_request-1)/n_per_request, n>n_per_request?"s":"",
2558 n, n>1?"s":"", n_per_request);
2559 for (i=0; i < n; i += n_per_request) {
2560 char *cp = resource;
2561 memcpy(resource, "fp/", 3);
2562 cp = resource + 3;
2563 for (j=i; j < i+n_per_request && j < n; ++j) {
2564 memcpy(cp, smartlist_get(downloadable, j), HEX_DIGEST_LEN);
2565 cp += HEX_DIGEST_LEN;
2566 *cp++ = '+';
2568 memcpy(cp-1, ".z", 3);
2569 last_download_attempted = now;
2570 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,resource,1);
2572 tor_free(resource);
2574 SMARTLIST_FOREACH(downloadable, char *, c, tor_free(c));
2575 smartlist_free(downloadable);
2578 /** Return true iff we have enough networkstatus and router information to
2579 * start building circuits. Right now, this means "at least 2 networkstatus
2580 * documents, and at least 1/4 of expected routers." */
2582 router_have_minimum_dir_info(void)
2584 int tot = 0, avg;
2585 if (!networkstatus_list || smartlist_len(networkstatus_list)<2 ||
2586 !routerlist)
2587 return 0;
2588 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2589 tot += smartlist_len(ns->entries));
2590 avg = tot / smartlist_len(networkstatus_list);
2591 return smartlist_len(routerlist->routers) > (avg/4);
2594 /** Reset the descriptor download failure count on all routers, so that we
2595 * can retry any long-failed routers immediately.
2597 void
2598 router_reset_descriptor_download_failures(void)
2600 if (!routerstatus_list)
2601 return;
2602 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
2604 rs->n_download_failures = 0;
2605 rs->next_attempt_at = 0;