More cleanups noticed by weasel; also, remove macros that nobody uses.
[tor.git] / src / or / routerlist.c
blob608b585787ead88b79c019c62c46fbe03a7f628d
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char routerlist_c_id[] =
7 "$Id$";
9 /**
10 * \file routerlist.c
11 * \brief Code to
12 * maintain and access the global list of routerinfos for known
13 * servers.
14 **/
16 #include "or.h"
18 /****************************************************************************/
20 /* static function prototypes */
21 static routerstatus_t *router_pick_directory_server_impl(int requireother,
22 int fascistfirewall,
23 int for_v2_directory);
24 static routerstatus_t *router_pick_trusteddirserver_impl(
25 int need_v1_authority, int requireother, int fascistfirewall);
26 static void mark_all_trusteddirservers_up(void);
27 static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
28 static int router_nickname_matches(routerinfo_t *router, const char *nickname);
29 static void routerstatus_list_update_from_networkstatus(time_t now);
30 static void local_routerstatus_free(local_routerstatus_t *rs);
31 static void trusted_dir_server_free(trusted_dir_server_t *ds);
32 static void update_networkstatus_cache_downloads(time_t now);
33 static void update_networkstatus_client_downloads(time_t now);
34 static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
35 static void routerlist_assert_ok(routerlist_t *rl);
37 #define MAX_DESCRIPTORS_PER_ROUTER 5
39 /****************************************************************************/
41 /** Global list of a trusted_dir_server_t object for each trusted directory
42 * server. */
43 static smartlist_t *trusted_dir_servers = NULL;
45 /** Global list of all of the routers that we know about. */
46 static routerlist_t *routerlist = NULL;
48 /** Global list of all of the current network_status documents that we know
49 * about. This list is kept sorted by published_on. */
50 static smartlist_t *networkstatus_list = NULL;
52 /** Global list of local_routerstatus_t for each router, known or unknown. */
53 static smartlist_t *routerstatus_list = NULL;
55 /** True iff any member of networkstatus_list has changed since the last time
56 * we called routerstatus_list_update_from_networkstatus(). */
57 static int networkstatus_list_has_changed = 0;
59 /** True iff any element of routerstatus_list has changed since the last
60 * time we called routers_update_all_from_networkstatus().*/
61 static int routerstatus_list_has_changed = 0;
63 /** List of strings for nicknames we've already warned about and that are
64 * still unknown / unavailable. */
65 static smartlist_t *warned_nicknames = NULL;
67 /** List of strings for nicknames or fingerprints we've already warned about
68 * and that are still conflicted. */
69 static smartlist_t *warned_conflicts = NULL;
71 /** The last time we tried to download any routerdesc, or 0 for "never". We
72 * use this to rate-limit download attempts when the number of routerdescs to
73 * download is low. */
74 static time_t last_routerdesc_download_attempted = 0;
76 /** The last time we tried to download a networkstatus, or 0 for "never". We
77 * use this to rate-limit download attempts for directory caches (including
78 * mirrors). Clients don't use this now. */
79 static time_t last_networkstatus_download_attempted = 0;
81 /* DOCDOC */
82 static int have_warned_about_unverified_status = 0;
83 static int have_warned_about_old_version = 0;
84 static int have_warned_about_new_version = 0;
86 /** Repopulate our list of network_status_t objects from the list cached on
87 * disk. Return 0 on success, -1 on failure. */
88 int
89 router_reload_networkstatus(void)
91 char filename[512];
92 struct stat st;
93 smartlist_t *entries;
94 char *s;
95 tor_assert(get_options()->DataDirectory);
96 if (!networkstatus_list)
97 networkstatus_list = smartlist_create();
99 tor_snprintf(filename,sizeof(filename),"%s/cached-status",
100 get_options()->DataDirectory);
101 entries = tor_listdir(filename);
102 SMARTLIST_FOREACH(entries, const char *, fn, {
103 char buf[DIGEST_LEN];
104 if (strlen(fn) != HEX_DIGEST_LEN ||
105 base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
106 log_info(LD_DIR,
107 "Skipping cached-status file with unexpected name \"%s\"",fn);
108 continue;
110 tor_snprintf(filename,sizeof(filename),"%s/cached-status/%s",
111 get_options()->DataDirectory, fn);
112 s = read_file_to_str(filename, 0);
113 if (s) {
114 stat(filename, &st);
115 if (router_set_networkstatus(s, st.st_mtime, NS_FROM_CACHE, NULL)<0) {
116 log_warn(LD_FS, "Couldn't load networkstatus from \"%s\"",filename);
118 tor_free(s);
121 SMARTLIST_FOREACH(entries, char *, fn, tor_free(fn));
122 smartlist_free(entries);
123 networkstatus_list_clean(time(NULL));
124 routers_update_all_from_networkstatus();
125 return 0;
128 /* Router descriptor storage.
130 * Routerdescs are stored in a big file, named "cached-routers". As new
131 * routerdescs arrive, we append them to a journal file named
132 * "cached-routers.new".
134 * From time to time, we replace "cached-routers" with a new file containing
135 * only the live, non-superseded descriptors, and clear cached-routers.new.
137 * On startup, we read both files.
140 /** The size of the router log, in bytes. */
141 static size_t router_journal_len = 0;
142 /** The size of the router store, in bytes. */
143 static size_t router_store_len = 0;
144 /** Total bytes dropped since last rebuild. */
145 static size_t router_bytes_dropped = 0;
147 /** Helper: return 1 iff the router log is so big we want to rebuild the
148 * store. */
149 static int
150 router_should_rebuild_store(void)
152 if (router_store_len > (1<<16))
153 return (router_journal_len > router_store_len / 2 ||
154 router_bytes_dropped > router_store_len / 2);
155 else
156 return router_journal_len > (1<<15);
159 /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
160 * journal. */
161 static int
162 router_append_to_journal(signed_descriptor_t *desc)
164 or_options_t *options = get_options();
165 size_t fname_len = strlen(options->DataDirectory)+32;
166 char *fname = tor_malloc(fname_len);
167 const char *body = signed_descriptor_get_body(desc);
168 size_t len = desc->signed_descriptor_len;
170 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
171 options->DataDirectory);
173 tor_assert(len == strlen(body));
175 if (append_bytes_to_file(fname, body, len, 0)) {
176 log_warn(LD_FS, "Unable to store router descriptor");
177 tor_free(fname);
178 return -1;
181 tor_free(fname);
182 router_journal_len += len;
183 return 0;
186 /** If the journal is too long, or if <b>force</b> is true, then atomically
187 * replace the router store with the routers currently in our routerlist, and
188 * clear the journal. Return 0 on success, -1 on failure.
190 static int
191 router_rebuild_store(int force)
193 size_t len = 0;
194 or_options_t *options;
195 size_t fname_len;
196 smartlist_t *chunk_list = NULL;
197 char *fname = NULL;
198 int r = -1, i;
200 if (!force && !router_should_rebuild_store())
201 return 0;
202 if (!routerlist)
203 return 0;
205 /* Don't save deadweight. */
206 routerlist_remove_old_routers();
208 options = get_options();
209 fname_len = strlen(options->DataDirectory)+32;
210 fname = tor_malloc(fname_len);
211 tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
212 chunk_list = smartlist_create();
214 for (i = 0; i < 2; ++i) {
215 smartlist_t *lst = (i == 0) ? routerlist->old_routers :
216 routerlist->routers;
217 SMARTLIST_FOREACH(lst, void *, ptr,
219 signed_descriptor_t *sd = (i==0) ?
220 ((signed_descriptor_t*)ptr): &((routerinfo_t*)ptr)->cache_info;
221 sized_chunk_t *c;
222 const char *body = signed_descriptor_get_body(sd);
223 if (!body) {
224 log_warn(LD_BUG, "Bug! No descriptor available for router.");
225 goto done;
227 c = tor_malloc(sizeof(sized_chunk_t));
228 c->bytes = body;
229 c->len = sd->signed_descriptor_len;
230 smartlist_add(chunk_list, c);
233 if (write_chunks_to_file(fname, chunk_list, 0)<0) {
234 log_warn(LD_FS, "Error writing router store to disk.");
235 goto done;
238 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
239 options->DataDirectory);
241 write_str_to_file(fname, "", 0);
243 r = 0;
244 router_store_len = len;
245 router_journal_len = 0;
246 router_bytes_dropped = 0;
247 done:
248 tor_free(fname);
249 if (chunk_list) {
250 SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
251 smartlist_free(chunk_list);
253 return r;
256 /* Load all cached router descriptors from the store. Return 0 on success and
257 * -1 on failure.
260 router_reload_router_list(void)
262 or_options_t *options = get_options();
263 size_t fname_len = strlen(options->DataDirectory)+32;
264 char *fname = tor_malloc(fname_len);
265 struct stat st;
266 int j;
268 if (!routerlist)
269 router_get_routerlist(); /* mallocs and inits it in place */
271 router_journal_len = router_store_len = 0;
273 for (j = 0; j < 2; ++j) {
274 char *contents;
275 tor_snprintf(fname, fname_len,
276 (j==0)?"%s/cached-routers":"%s/cached-routers.new",
277 options->DataDirectory);
278 contents = read_file_to_str(fname, 0);
279 if (contents) {
280 stat(fname, &st);
281 if (j==0)
282 router_store_len = st.st_size;
283 else
284 router_journal_len = st.st_size;
285 router_load_routers_from_string(contents, 1, NULL);
286 tor_free(contents);
289 tor_free(fname);
291 if (router_journal_len) {
292 /* Always clear the journal on startup.*/
293 router_rebuild_store(1);
294 } else {
295 /* Don't cache expired routers. (This is in an else because
296 * router_rebuild_store() also calls remove_old_routers().) */
297 routerlist_remove_old_routers();
300 return 0;
303 /** Set *<b>outp</b> to a smartlist containing a list of
304 * trusted_dir_server_t * for all known trusted dirservers. Callers
305 * must not modify the list or its contents.
307 void
308 router_get_trusted_dir_servers(smartlist_t **outp)
310 if (!trusted_dir_servers)
311 trusted_dir_servers = smartlist_create();
313 *outp = trusted_dir_servers;
316 /** Try to find a running dirserver. If there are no running dirservers
317 * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
318 * set all the authoritative ones as running again, and pick one;
319 * if there are then no dirservers at all in our routerlist,
320 * reload the routerlist and try one last time. If for_runningrouters is
321 * true, then only pick a dirserver that can answer runningrouters queries
322 * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
323 * Don't pick an authority if any non-authority is viable.
324 * Other args are as in router_pick_directory_server_impl().
326 routerstatus_t *
327 router_pick_directory_server(int requireother,
328 int fascistfirewall,
329 int for_v2_directory,
330 int retry_if_no_servers)
332 routerstatus_t *choice;
334 if (!routerlist)
335 return NULL;
337 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
338 for_v2_directory);
339 if (choice || !retry_if_no_servers)
340 return choice;
342 log_info(LD_DIR,
343 "No reachable router entries for dirservers. "
344 "Trying them all again.");
345 /* mark all authdirservers as up again */
346 mark_all_trusteddirservers_up();
347 /* try again */
348 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
349 for_v2_directory);
350 if (choice)
351 return choice;
353 log_info(LD_DIR,"Still no %s router entries. Reloading and trying again.",
354 fascistfirewall ? "reachable" : "known");
355 if (router_reload_router_list()) {
356 return NULL;
358 /* give it one last try */
359 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
360 for_v2_directory);
361 return choice;
364 /** Return the trusted_dir_server_t for the directory authority whose identity
365 * key hashes to <b>digest</b>, or NULL if no such authority is known.
367 trusted_dir_server_t *
368 router_get_trusteddirserver_by_digest(const char *digest)
370 if (!trusted_dir_servers)
371 return NULL;
373 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
375 if (!memcmp(ds->digest, digest, DIGEST_LEN))
376 return ds;
379 return NULL;
382 /** Try to find a running trusted dirserver. If there are no running
383 * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
384 * set them all as running again, and try again.
385 * If <b>need_v1_authority</b> is set, return only trusted servers
386 * that are authorities for the V1 directory protocol.
387 * Other args are as in router_pick_trusteddirserver_impl().
389 routerstatus_t *
390 router_pick_trusteddirserver(int need_v1_authority,
391 int requireother,
392 int fascistfirewall,
393 int retry_if_no_servers)
395 routerstatus_t *choice;
397 choice = router_pick_trusteddirserver_impl(need_v1_authority,
398 requireother, fascistfirewall);
399 if (choice || !retry_if_no_servers)
400 return choice;
402 log_info(LD_DIR,
403 "No trusted dirservers are reachable. Trying them all again.");
404 mark_all_trusteddirservers_up();
405 return router_pick_trusteddirserver_impl(need_v1_authority,
406 requireother, fascistfirewall);
409 /** Pick a random running verified directory server/mirror from our
410 * routerlist. Don't pick an authority if any non-authorities are viable.
411 * If <b>fascistfirewall</b>,
412 * make sure the router we pick is allowed by our firewall options.
413 * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
414 * choose a directory server new enough to support the v2 directory
415 * functionality.
417 static routerstatus_t *
418 router_pick_directory_server_impl(int requireother, int fascistfirewall,
419 int for_v2_directory)
421 routerstatus_t *result;
422 smartlist_t *sl;
423 smartlist_t *trusted;
425 if (!routerstatus_list)
426 return NULL;
428 /* Find all the running dirservers we know about. */
429 sl = smartlist_create();
430 trusted = smartlist_create();
431 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, _local_status,
433 routerstatus_t *status = &(_local_status->status);
434 int is_trusted;
435 if (!status->is_running || !status->dir_port || !status->is_valid)
436 continue;
437 if (requireother && router_digest_is_me(status->identity_digest))
438 continue;
439 if (fascistfirewall) {
440 if (!fascist_firewall_allows_address_dir(status->addr, status->dir_port))
441 continue;
443 is_trusted = router_digest_is_trusted_dir(status->identity_digest);
444 if (for_v2_directory && !(status->is_v2_dir || is_trusted))
445 continue;
446 smartlist_add(is_trusted ? trusted : sl, status);
449 if (smartlist_len(sl))
450 result = smartlist_choose(sl);
451 else
452 result = smartlist_choose(trusted);
453 smartlist_free(sl);
454 smartlist_free(trusted);
455 return result;
458 /** Choose randomly from among the trusted dirservers that are up. If
459 * <b>fascistfirewall</b>, make sure the port we pick is allowed by our
460 * firewall options. If <b>requireother</b>, it cannot be us. If
461 * <b>need_v1_authority</b>, choose a trusted authority for the v1 directory
462 * system.
464 static routerstatus_t *
465 router_pick_trusteddirserver_impl(int need_v1_authority,
466 int requireother, int fascistfirewall)
468 smartlist_t *sl;
469 routerinfo_t *me;
470 routerstatus_t *rs;
471 sl = smartlist_create();
472 me = router_get_my_routerinfo();
474 if (!trusted_dir_servers)
475 return NULL;
477 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
479 if (!d->is_running) continue;
480 if (need_v1_authority && !d->is_v1_authority)
481 continue;
482 if (requireother && me && router_digest_is_me(d->digest))
483 continue;
484 if (fascistfirewall) {
485 if (!fascist_firewall_allows_address_dir(d->addr, d->dir_port))
486 continue;
488 smartlist_add(sl, &d->fake_status);
491 rs = smartlist_choose(sl);
492 smartlist_free(sl);
493 return rs;
496 /** Go through and mark the authoritative dirservers as up. */
497 static void
498 mark_all_trusteddirservers_up(void)
500 if (routerlist) {
501 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
502 if (router_digest_is_trusted_dir(router->cache_info.identity_digest) &&
503 router->dir_port > 0) {
504 router->is_running = 1;
507 if (trusted_dir_servers) {
508 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
510 local_routerstatus_t *rs;
511 dir->is_running = 1;
512 dir->n_networkstatus_failures = 0;
513 rs = router_get_combined_status_by_digest(dir->digest);
514 if (rs)
515 rs->status.is_running = 1;
518 last_networkstatus_download_attempted = 0;
521 /** Reset all internal variables used to count failed downloads of network
522 * status objects. */
523 void
524 router_reset_status_download_failures(void)
526 mark_all_trusteddirservers_up();
529 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
530 * This is used to make sure we don't pick siblings in a single path.
532 void
533 routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
535 routerinfo_t *r;
536 config_line_t *cl;
538 if (!router->declared_family)
539 return;
541 /* Add every r such that router declares familyness with r, and r
542 * declares familyhood with router. */
543 SMARTLIST_FOREACH(router->declared_family, const char *, n,
545 if (!(r = router_get_by_nickname(n, 0)))
546 continue;
547 if (!r->declared_family)
548 continue;
549 SMARTLIST_FOREACH(r->declared_family, const char *, n2,
551 if (router_nickname_matches(router, n2))
552 smartlist_add(sl, r);
556 /* If the user declared any families locally, honor those too. */
557 for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
558 if (router_nickname_is_in_list(router, cl->value)) {
559 add_nickname_list_to_smartlist(sl, cl->value, 0, 1, 1);
564 /** Given a comma-and-whitespace separated list of nicknames, see which
565 * nicknames in <b>list</b> name routers in our routerlist that are
566 * currently running. Add the routerinfos for those routers to <b>sl</b>.
568 void
569 add_nickname_list_to_smartlist(smartlist_t *sl, const char *list,
570 int must_be_running,
571 int warn_if_down, int warn_if_unnamed)
573 routerinfo_t *router;
574 smartlist_t *nickname_list;
575 int have_dir_info = router_have_minimum_dir_info();
577 if (!list)
578 return; /* nothing to do */
579 tor_assert(sl);
581 nickname_list = smartlist_create();
582 if (!warned_nicknames)
583 warned_nicknames = smartlist_create();
585 smartlist_split_string(nickname_list, list, ",",
586 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
588 SMARTLIST_FOREACH(nickname_list, const char *, nick, {
589 int warned;
590 if (!is_legal_nickname_or_hexdigest(nick)) {
591 log_warn(LD_CONFIG, "Nickname '%s' is misformed; skipping", nick);
592 continue;
594 router = router_get_by_nickname(nick, warn_if_unnamed);
595 warned = smartlist_string_isin(warned_nicknames, nick);
596 if (router) {
597 if (!must_be_running || router->is_running) {
598 smartlist_add(sl,router);
599 if (warned)
600 smartlist_string_remove(warned_nicknames, nick);
601 } else {
602 if (!warned) {
603 log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG, LD_CONFIG,
604 "Nickname list includes '%s' which is known but down.",nick);
605 smartlist_add(warned_nicknames, tor_strdup(nick));
608 } else {
609 if (!warned) {
610 log_fn(have_dir_info ? LOG_WARN : LOG_INFO, LD_CONFIG,
611 "Nickname list includes '%s' which isn't a known router.",nick);
612 smartlist_add(warned_nicknames, tor_strdup(nick));
616 SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
617 smartlist_free(nickname_list);
620 /** Return 1 iff any member of the comma-separated list <b>list</b> is an
621 * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
623 static int
624 router_nickname_is_in_list(routerinfo_t *router, const char *list)
626 smartlist_t *nickname_list;
627 int v = 0;
629 if (!list)
630 return 0; /* definitely not */
631 tor_assert(router);
633 nickname_list = smartlist_create();
634 smartlist_split_string(nickname_list, list, ",",
635 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
636 SMARTLIST_FOREACH(nickname_list, const char *, cp,
637 if (router_nickname_matches(router, cp)) {v=1;break;});
638 SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
639 smartlist_free(nickname_list);
640 return v;
643 /** Add every router from our routerlist that is currently running to
644 * <b>sl</b>.
646 static void
647 router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_unverified,
648 int need_uptime, int need_capacity,
649 int need_guard)
651 if (!routerlist)
652 return;
654 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
656 if (router->is_running &&
657 (router->is_verified ||
658 (allow_unverified &&
659 !router_is_unreliable(router, need_uptime,
660 need_capacity, need_guard)))) {
661 /* If it's running, and either it's verified or we're ok picking
662 * unverified routers and this one is suitable.
664 smartlist_add(sl, router);
669 /** Look through the routerlist until we find a router that has my key.
670 Return it. */
671 routerinfo_t *
672 routerlist_find_my_routerinfo(void)
674 if (!routerlist)
675 return NULL;
677 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
679 if (router_is_me(router))
680 return router;
682 return NULL;
685 /** Find a router that's up, that has this IP address, and
686 * that allows exit to this address:port, or return NULL if there
687 * isn't a good one.
689 routerinfo_t *
690 router_find_exact_exit_enclave(const char *address, uint16_t port)
692 uint32_t addr;
693 struct in_addr in;
695 if (!tor_inet_aton(address, &in))
696 return NULL; /* it's not an IP already */
697 addr = ntohl(in.s_addr);
699 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
701 if (router->is_running &&
702 router->addr == addr &&
703 router_compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
704 ADDR_POLICY_ACCEPTED)
705 return router;
707 return NULL;
710 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
711 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
712 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
713 * bandwidth.
716 router_is_unreliable(routerinfo_t *router, int need_uptime,
717 int need_capacity, int need_guard)
719 if (need_uptime && !router->is_stable)
720 return 1;
721 if (need_capacity && !router->is_fast)
722 return 1;
723 if (need_guard && !router->is_possible_guard)
724 return 1;
725 return 0;
728 /** Remove from routerlist <b>sl</b> all routers that are not
729 * sufficiently stable. */
730 static void
731 routerlist_sl_remove_unreliable_routers(smartlist_t *sl, int need_uptime,
732 int need_capacity, int need_guard)
734 int i;
735 routerinfo_t *router;
737 for (i = 0; i < smartlist_len(sl); ++i) {
738 router = smartlist_get(sl, i);
739 if (router_is_unreliable(router, need_uptime,
740 need_capacity, need_guard)) {
741 // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
742 // router->nickname);
743 smartlist_del(sl, i--);
748 #define MAX_BELIEVABLE_BANDWIDTH 1500000 /* 1.5 MB/sec */
750 /** Choose a random element of router list <b>sl</b>, weighted by
751 * the advertised bandwidth of each router.
753 routerinfo_t *
754 routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
756 int i;
757 routerinfo_t *router;
758 smartlist_t *bandwidths;
759 uint32_t this_bw, tmp, total_bw=0, rand_bw;
760 uint32_t *p;
762 /* First count the total bandwidth weight, and make a smartlist
763 * of each value. */
764 bandwidths = smartlist_create();
765 for (i = 0; i < smartlist_len(sl); ++i) {
766 router = smartlist_get(sl, i);
767 this_bw = (router->bandwidthcapacity < router->bandwidthrate) ?
768 router->bandwidthcapacity : router->bandwidthrate;
769 /* if they claim something huge, don't believe it */
770 if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
771 this_bw = MAX_BELIEVABLE_BANDWIDTH;
772 p = tor_malloc(sizeof(uint32_t));
773 *p = this_bw;
774 smartlist_add(bandwidths, p);
775 total_bw += this_bw;
777 if (!total_bw) {
778 SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
779 smartlist_free(bandwidths);
780 return smartlist_choose(sl);
782 /* Second, choose a random value from the bandwidth weights. */
783 rand_bw = crypto_rand_int(total_bw);
784 /* Last, count through sl until we get to the element we picked */
785 tmp = 0;
786 for (i=0; ; i++) {
787 tor_assert(i < smartlist_len(sl));
788 p = smartlist_get(bandwidths, i);
789 tmp += *p;
790 if (tmp >= rand_bw)
791 break;
793 SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
794 smartlist_free(bandwidths);
795 return (routerinfo_t *)smartlist_get(sl, i);
798 /** Return a random running router from the routerlist. If any node
799 * named in <b>preferred</b> is available, pick one of those. Never
800 * pick a node named in <b>excluded</b>, or whose routerinfo is in
801 * <b>excludedsmartlist</b>, even if they are the only nodes
802 * available. If <b>strict</b> is true, never pick any node besides
803 * those in <b>preferred</b>.
804 * If <b>need_uptime</b> is non-zero and any router has more than
805 * a minimum uptime, return one of those.
806 * If <b>need_capacity</b> is non-zero, weight your choice by the
807 * advertised capacity of each router.
809 routerinfo_t *
810 router_choose_random_node(const char *preferred,
811 const char *excluded,
812 smartlist_t *excludedsmartlist,
813 int need_uptime, int need_capacity,
814 int need_guard,
815 int allow_unverified, int strict)
817 smartlist_t *sl, *excludednodes;
818 routerinfo_t *choice = NULL;
820 excludednodes = smartlist_create();
821 add_nickname_list_to_smartlist(excludednodes,excluded,0,0,1);
823 /* Try the preferred nodes first. Ignore need_uptime and need_capacity
824 * and need_guard, since the user explicitly asked for these nodes. */
825 if (preferred) {
826 sl = smartlist_create();
827 add_nickname_list_to_smartlist(sl,preferred,1,1,1);
828 smartlist_subtract(sl,excludednodes);
829 if (excludedsmartlist)
830 smartlist_subtract(sl,excludedsmartlist);
831 choice = smartlist_choose(sl);
832 smartlist_free(sl);
834 if (!choice && !strict) {
835 /* Then give up on our preferred choices: any node
836 * will do that has the required attributes. */
837 sl = smartlist_create();
838 router_add_running_routers_to_smartlist(sl, allow_unverified,
839 need_uptime, need_capacity,
840 need_guard);
841 smartlist_subtract(sl,excludednodes);
842 if (excludedsmartlist)
843 smartlist_subtract(sl,excludedsmartlist);
844 routerlist_sl_remove_unreliable_routers(sl, need_uptime,
845 need_capacity, need_guard);
846 if (need_capacity)
847 choice = routerlist_sl_choose_by_bandwidth(sl);
848 else
849 choice = smartlist_choose(sl);
850 smartlist_free(sl);
851 if (!choice && (need_uptime || need_capacity || need_guard)) {
852 /* try once more -- recurse but with fewer restrictions. */
853 log_info(LD_CIRC,
854 "We couldn't find any live%s%s%s routers; falling back "
855 "to list of all routers.",
856 need_capacity?", fast":"",
857 need_uptime?", stable":"",
858 need_guard?", guard":"");
859 choice = router_choose_random_node(
860 NULL, excluded, excludedsmartlist, 0, 0, 0, allow_unverified, 0);
863 smartlist_free(excludednodes);
864 if (!choice)
865 log_warn(LD_CIRC,
866 "No available nodes when trying to choose node. Failing.");
867 return choice;
870 /** Return true iff the digest of <b>router</b>'s identity key,
871 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
872 * optionally prefixed with a single dollar sign). Return false if
873 * <b>hexdigest</b> is malformed, or it doesn't match. */
874 static INLINE int
875 router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
877 char digest[DIGEST_LEN];
878 tor_assert(hexdigest);
879 if (hexdigest[0] == '$')
880 ++hexdigest;
882 /* XXXXNM Any place that uses this inside a loop could probably do better. */
883 if (strlen(hexdigest) != HEX_DIGEST_LEN ||
884 base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
885 return 0;
886 return (!memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN));
889 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
890 * (case-insensitive), or if <b>router's</b> identity key digest
891 * matches a hexadecimal value stored in <b>nickname</b>. Return
892 * false otherwise. */
893 static int
894 router_nickname_matches(routerinfo_t *router, const char *nickname)
896 if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
897 return 1;
898 return router_hex_digest_matches(router, nickname);
901 /** Return the router in our routerlist whose (case-insensitive)
902 * nickname or (case-sensitive) hexadecimal key digest is
903 * <b>nickname</b>. Return NULL if no such router is known.
905 routerinfo_t *
906 router_get_by_nickname(const char *nickname, int warn_if_unnamed)
908 int maybedigest;
909 char digest[DIGEST_LEN];
910 routerinfo_t *best_match=NULL;
911 int n_matches = 0;
913 tor_assert(nickname);
914 if (!routerlist)
915 return NULL;
916 if (nickname[0] == '$')
917 return router_get_by_hexdigest(nickname);
918 if (server_mode(get_options()) &&
919 !strcasecmp(nickname, get_options()->Nickname))
920 return router_get_my_routerinfo();
922 maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
923 (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
925 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
927 if (!strcasecmp(router->nickname, nickname)) {
928 if (router->is_named)
929 return router;
930 else {
931 ++n_matches;
932 best_match = router;
934 } else if (maybedigest &&
935 !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN)
937 return router;
941 if (best_match) {
942 if (warn_if_unnamed && n_matches > 1) {
943 smartlist_t *fps = smartlist_create();
944 int any_unwarned = 0;
945 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
947 local_routerstatus_t *rs;
948 char *desc;
949 size_t dlen;
950 char fp[HEX_DIGEST_LEN+1];
951 if (strcasecmp(router->nickname, nickname))
952 continue;
953 rs = router_get_combined_status_by_digest(
954 router->cache_info.identity_digest);
955 if (!rs->name_lookup_warned) {
956 rs->name_lookup_warned = 1;
957 any_unwarned = 1;
959 base16_encode(fp, sizeof(fp),
960 router->cache_info.identity_digest, DIGEST_LEN);
961 dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
962 desc = tor_malloc(dlen);
963 tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
964 fp, router->address, router->or_port);
965 smartlist_add(fps, desc);
967 if (any_unwarned) {
968 char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
969 log_warn(LD_CONFIG,
970 "There are multiple matches for the nickname \"%s\","
971 " but none is listed as named by the directory authories. "
972 "Choosing one arbitrarily. If you meant one in particular, "
973 "you should say %s.", nickname, alternatives);
974 tor_free(alternatives);
976 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
977 smartlist_free(fps);
978 } else if (warn_if_unnamed) {
979 local_routerstatus_t *rs = router_get_combined_status_by_digest(
980 best_match->cache_info.identity_digest);
981 if (rs && !rs->name_lookup_warned) {
982 char fp[HEX_DIGEST_LEN+1];
983 base16_encode(fp, sizeof(fp),
984 best_match->cache_info.identity_digest, DIGEST_LEN);
985 log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but the "
986 "directory authorities do not have a listing for this name. "
987 "To make sure you get the same server in the future, refer to "
988 "it by key, as \"$%s\".", nickname, fp);
989 rs->name_lookup_warned = 1;
992 return best_match;
995 return NULL;
998 /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
999 * return 1. If we do, ask tor_version_as_new_as() for the answer.
1002 router_digest_version_as_new_as(const char *digest, const char *cutoff)
1004 routerinfo_t *router = router_get_by_digest(digest);
1005 if (!router)
1006 return 1;
1007 return tor_version_as_new_as(router->platform, cutoff);
1010 /** Return true iff <b>digest</b> is the digest of the identity key of
1011 * a trusted directory. */
1013 router_digest_is_trusted_dir(const char *digest)
1015 if (!trusted_dir_servers)
1016 return 0;
1017 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
1018 if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
1019 return 0;
1022 /** Return the router in our routerlist whose hexadecimal key digest
1023 * is <b>hexdigest</b>. Return NULL if no such router is known. */
1024 routerinfo_t *
1025 router_get_by_hexdigest(const char *hexdigest)
1027 char digest[DIGEST_LEN];
1029 tor_assert(hexdigest);
1030 if (!routerlist)
1031 return NULL;
1032 if (hexdigest[0]=='$')
1033 ++hexdigest;
1034 if (strlen(hexdigest) != HEX_DIGEST_LEN ||
1035 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
1036 return NULL;
1038 return router_get_by_digest(digest);
1041 /** Return the router in our routerlist whose 20-byte key digest
1042 * is <b>digest</b>. Return NULL if no such router is known. */
1043 routerinfo_t *
1044 router_get_by_digest(const char *digest)
1046 tor_assert(digest);
1048 if (!routerlist) return NULL;
1050 // routerlist_assert_ok(routerlist);
1052 return digestmap_get(routerlist->identity_map, digest);
1055 /** Return the router in our routerlist whose 20-byte descriptor
1056 * is <b>digest</b>. Return NULL if no such router is known. */
1057 signed_descriptor_t *
1058 router_get_by_descriptor_digest(const char *digest)
1060 tor_assert(digest);
1062 if (!routerlist) return NULL;
1064 return digestmap_get(routerlist->desc_digest_map, digest);
1067 const char *
1068 signed_descriptor_get_body(signed_descriptor_t *desc)
1070 return desc->signed_descriptor_body;
1073 /** Return the current list of all known routers. */
1074 routerlist_t *
1075 router_get_routerlist(void)
1077 if (!routerlist) {
1078 routerlist = tor_malloc_zero(sizeof(routerlist_t));
1079 routerlist->routers = smartlist_create();
1080 routerlist->old_routers = smartlist_create();
1081 routerlist->identity_map = digestmap_new();
1082 routerlist->desc_digest_map = digestmap_new();
1084 return routerlist;
1087 /** Free all storage held by <b>router</b>. */
1088 void
1089 routerinfo_free(routerinfo_t *router)
1091 if (!router)
1092 return;
1094 tor_free(router->cache_info.signed_descriptor_body);
1095 tor_free(router->address);
1096 tor_free(router->nickname);
1097 tor_free(router->platform);
1098 tor_free(router->contact_info);
1099 if (router->onion_pkey)
1100 crypto_free_pk_env(router->onion_pkey);
1101 if (router->identity_pkey)
1102 crypto_free_pk_env(router->identity_pkey);
1103 if (router->declared_family) {
1104 SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
1105 smartlist_free(router->declared_family);
1107 addr_policy_free(router->exit_policy);
1108 tor_free(router);
1111 /** Release storage held by <b>sd</b>. */
1112 static void
1113 signed_descriptor_free(signed_descriptor_t *sd)
1115 tor_free(sd->signed_descriptor_body);
1116 tor_free(sd);
1119 /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
1121 static signed_descriptor_t *
1122 signed_descriptor_from_routerinfo(routerinfo_t *ri)
1124 signed_descriptor_t *sd = tor_malloc_zero(sizeof(signed_descriptor_t));
1125 memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
1126 ri->cache_info.signed_descriptor_body = NULL;
1127 routerinfo_free(ri);
1128 return sd;
1131 /** Free all storage held by a routerlist <b>rl</b> */
1132 void
1133 routerlist_free(routerlist_t *rl)
1135 tor_assert(rl);
1136 digestmap_free(rl->identity_map, NULL);
1137 digestmap_free(rl->desc_digest_map, NULL);
1138 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
1139 routerinfo_free(r));
1140 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
1141 signed_descriptor_free(sd));
1142 smartlist_free(rl->routers);
1143 smartlist_free(rl->old_routers);
1144 tor_free(rl);
1147 void
1148 dump_routerlist_mem_usage(int severity)
1150 uint64_t livedescs = 0;
1151 uint64_t olddescs = 0;
1152 if (!routerlist)
1153 return;
1154 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
1155 livedescs += r->cache_info.signed_descriptor_len);
1156 SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
1157 olddescs += sd->signed_descriptor_len);
1159 log(severity, LD_GENERAL,
1160 "In %d live descriptors: "U64_FORMAT" bytes. "
1161 "In %d old descriptors: "U64_FORMAT" bytes.",
1162 smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
1163 smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
1166 /** Return non-zero if we have a lot of extra descriptors in our
1167 * routerlist, and should get rid of some of them. Else return 0.
1169 * We should be careful to not return true too eagerly, since we
1170 * could churn. By using "+1" below, we make sure this function
1171 * only returns true at most every smartlist_len(rl-\>routers)
1172 * new descriptors.
1174 static INLINE int
1175 routerlist_is_overfull(routerlist_t *rl)
1177 return smartlist_len(rl->old_routers) >
1178 smartlist_len(rl->routers)*(MAX_DESCRIPTORS_PER_ROUTER+1);
1181 static INLINE int
1182 _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
1184 if (idx < 0 || smartlist_get(sl, idx) != ri) {
1185 idx = -1;
1186 SMARTLIST_FOREACH(sl, routerinfo_t *, r,
1187 if (r == ri) {
1188 idx = r_sl_idx;
1189 break;
1192 return idx;
1195 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1196 * as needed. */
1197 static void
1198 routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
1200 digestmap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
1201 digestmap_set(rl->desc_digest_map, ri->cache_info.signed_descriptor_digest,
1202 &(ri->cache_info));
1203 smartlist_add(rl->routers, ri);
1204 // routerlist_assert_ok(rl);
1207 static void
1208 routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
1210 if (get_options()->DirPort &&
1211 !digestmap_get(rl->desc_digest_map,
1212 ri->cache_info.signed_descriptor_digest)) {
1213 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
1214 digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1215 smartlist_add(rl->old_routers, sd);
1216 } else {
1217 routerinfo_free(ri);
1219 // routerlist_assert_ok(rl);
1222 /** Remove an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1223 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
1224 * idx) == ri, we don't need to do a linear search over the list to decide
1225 * which to remove. We fill the gap in rl-&gt;routers with a later element in
1226 * the list, if any exists. <b>ri</b> is freed. */
1227 void
1228 routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx, int make_old)
1230 routerinfo_t *ri_tmp;
1231 idx = _routerlist_find_elt(rl->routers, ri, idx);
1232 if (idx < 0)
1233 return;
1234 smartlist_del(rl->routers, idx);
1235 ri_tmp = digestmap_remove(rl->identity_map, ri->cache_info.identity_digest);
1236 tor_assert(ri_tmp == ri);
1237 if (make_old && get_options()->DirPort) {
1238 signed_descriptor_t *sd;
1239 sd = signed_descriptor_from_routerinfo(ri);
1240 smartlist_add(rl->old_routers, sd);
1241 digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1242 } else {
1243 ri_tmp = digestmap_remove(rl->desc_digest_map,
1244 ri->cache_info.signed_descriptor_digest);
1245 tor_assert(ri_tmp == ri);
1246 router_bytes_dropped += ri->cache_info.signed_descriptor_len;
1247 routerinfo_free(ri);
1249 // routerlist_assert_ok(rl);
1252 static void
1253 routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
1255 signed_descriptor_t *sd_tmp;
1256 idx = _routerlist_find_elt(rl->old_routers, sd, idx);
1257 if (idx < 0)
1258 return;
1259 smartlist_del(rl->old_routers, idx);
1260 sd_tmp = digestmap_remove(rl->desc_digest_map,
1261 sd->signed_descriptor_digest);
1262 tor_assert(sd_tmp == sd);
1263 router_bytes_dropped += sd->signed_descriptor_len;
1264 signed_descriptor_free(sd);
1265 // routerlist_assert_ok(rl);
1268 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
1269 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
1270 * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
1271 * search over the list to decide which to remove. We put ri_new in the same
1272 * index as ri_old, if possible. ri is freed as appropriate. */
1273 static void
1274 routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
1275 routerinfo_t *ri_new, int idx, int make_old)
1277 tor_assert(ri_old != ri_new);
1278 idx = _routerlist_find_elt(rl->routers, ri_old, idx);
1279 if (idx >= 0) {
1280 smartlist_set(rl->routers, idx, ri_new);
1281 } else {
1282 log_warn(LD_BUG, "Appending entry from routerlist_replace.");
1283 routerlist_insert(rl, ri_new);
1284 return;
1286 if (memcmp(ri_old->cache_info.identity_digest,
1287 ri_new->cache_info.identity_digest, DIGEST_LEN)) {
1288 /* digests don't match; digestmap_set won't replace */
1289 digestmap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
1291 digestmap_set(rl->identity_map, ri_new->cache_info.identity_digest, ri_new);
1292 digestmap_set(rl->desc_digest_map,
1293 ri_new->cache_info.signed_descriptor_digest, &(ri_new->cache_info));
1295 if (make_old && get_options()->DirPort) {
1296 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
1297 smartlist_add(rl->old_routers, sd);
1298 digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1299 } else {
1300 if (memcmp(ri_old->cache_info.signed_descriptor_digest,
1301 ri_new->cache_info.signed_descriptor_digest,
1302 DIGEST_LEN)) {
1303 /* digests don't match; digestmap_set didn't replace */
1304 digestmap_remove(rl->desc_digest_map,
1305 ri_old->cache_info.signed_descriptor_digest);
1307 routerinfo_free(ri_old);
1309 // routerlist_assert_ok(rl);
1312 /** Free all memory held by the routerlist module. */
1313 void
1314 routerlist_free_all(void)
1316 if (routerlist)
1317 routerlist_free(routerlist);
1318 routerlist = NULL;
1319 if (warned_nicknames) {
1320 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1321 smartlist_free(warned_nicknames);
1322 warned_nicknames = NULL;
1324 if (warned_conflicts) {
1325 SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
1326 smartlist_free(warned_conflicts);
1327 warned_conflicts = NULL;
1329 if (trusted_dir_servers) {
1330 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
1331 trusted_dir_server_free(ds));
1332 smartlist_free(trusted_dir_servers);
1333 trusted_dir_servers = NULL;
1335 if (networkstatus_list) {
1336 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
1337 networkstatus_free(ns));
1338 smartlist_free(networkstatus_list);
1339 networkstatus_list = NULL;
1341 if (routerstatus_list) {
1342 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
1343 local_routerstatus_free(rs));
1344 smartlist_free(routerstatus_list);
1345 routerstatus_list = NULL;
1349 /** Free all storage held by the routerstatus object <b>rs</b>. */
1350 void
1351 routerstatus_free(routerstatus_t *rs)
1353 tor_free(rs);
1356 /** Free all storage held by the local_routerstatus object <b>rs</b>. */
1357 static void
1358 local_routerstatus_free(local_routerstatus_t *rs)
1360 tor_free(rs);
1363 /** Free all storage held by the networkstatus object <b>ns</b>. */
1364 void
1365 networkstatus_free(networkstatus_t *ns)
1367 tor_free(ns->source_address);
1368 tor_free(ns->contact);
1369 if (ns->signing_key)
1370 crypto_free_pk_env(ns->signing_key);
1371 tor_free(ns->client_versions);
1372 tor_free(ns->server_versions);
1373 if (ns->entries) {
1374 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
1375 routerstatus_free(rs));
1376 smartlist_free(ns->entries);
1378 tor_free(ns);
1381 /** Forget that we have issued any router-related warnings, so that we'll
1382 * warn again if we see the same errors. */
1383 void
1384 routerlist_reset_warnings(void)
1386 if (!warned_nicknames)
1387 warned_nicknames = smartlist_create();
1388 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1389 smartlist_clear(warned_nicknames); /* now the list is empty. */
1391 if (!warned_conflicts)
1392 warned_conflicts = smartlist_create();
1393 SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
1394 smartlist_clear(warned_conflicts); /* now the list is empty. */
1396 if (!routerstatus_list)
1397 routerstatus_list = smartlist_create();
1398 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
1399 rs->name_lookup_warned = 0);
1401 have_warned_about_unverified_status = 0;
1402 have_warned_about_old_version = 0;
1403 have_warned_about_new_version = 0;
1406 /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
1407 void
1408 router_mark_as_down(const char *digest)
1410 routerinfo_t *router;
1411 local_routerstatus_t *status;
1412 tor_assert(digest);
1414 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
1415 if (!memcmp(d->digest, digest, DIGEST_LEN))
1416 d->is_running = 0);
1418 router = router_get_by_digest(digest);
1419 if (router) {
1420 log_debug(LD_DIR,"Marking router '%s' as down.",router->nickname);
1421 if (router_is_me(router) && !we_are_hibernating())
1422 log_warn(LD_NET, "We just marked ourself as down. Are your external "
1423 "addresses reachable?");
1424 router->is_running = 0;
1426 status = router_get_combined_status_by_digest(digest);
1427 if (status) {
1428 status->status.is_running = 0;
1432 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
1433 * older entries (if any) with the same key. Note: Callers should not hold
1434 * their pointers to <b>router</b> if this function fails; <b>router</b>
1435 * will either be inserted into the routerlist or freed.
1437 * Returns >= 0 if the router was added; less than 0 if it was not.
1439 * If we're returning non-zero, then assign to *<b>msg</b> a static string
1440 * describing the reason for not liking the routerinfo.
1442 * If the return value is less than -1, there was a problem with the
1443 * routerinfo. If the return value is equal to -1, then the routerinfo was
1444 * fine, but out-of-date. If the return value is equal to 1, the
1445 * routerinfo was accepted, but we should notify the generator of the
1446 * descriptor using the message *<b>msg</b>.
1448 * If <b>from_cache</b>, this descriptor came from our disk cache. If
1449 * <b>from_fetch</b>, we received it in response to a request we made.
1450 * (If both are false, that means it was uploaded to us as an auth dir
1451 * server or via the controller.)
1453 * This function should be called *after*
1454 * routers_update_status_from_networkstatus; subsequently, you should call
1455 * router_rebuild_store and control_event_descriptors_changed.
1457 * XXXX never replace your own descriptor.
1460 router_add_to_routerlist(routerinfo_t *router, const char **msg,
1461 int from_cache, int from_fetch)
1463 int i;
1464 char id_digest[DIGEST_LEN];
1465 int authdir = get_options()->AuthoritativeDir;
1466 int authdir_verified = 0;
1468 tor_assert(msg);
1470 if (!routerlist)
1471 router_get_routerlist();
1473 /* XXXX NM If this assert doesn't trigger, we should remove the id_digest
1474 * local. */
1475 crypto_pk_get_digest(router->identity_pkey, id_digest);
1476 tor_assert(!memcmp(id_digest, router->cache_info.identity_digest,
1477 DIGEST_LEN));
1479 /* Make sure that we haven't already got this exact descriptor. */
1480 if (digestmap_get(routerlist->desc_digest_map,
1481 router->cache_info.signed_descriptor_digest)) {
1482 log_info(LD_DIR,
1483 "Dropping descriptor that we already have for router '%s'",
1484 router->nickname);
1485 *msg = "Router descriptor was not new.";
1486 routerinfo_free(router);
1487 return -1;
1490 if (routerlist_is_overfull(routerlist))
1491 routerlist_remove_old_routers();
1493 if (authdir) {
1494 if (authdir_wants_to_reject_router(router, msg,
1495 !from_cache && !from_fetch)) {
1496 tor_assert(*msg);
1497 routerinfo_free(router);
1498 return -2;
1500 authdir_verified = router->is_verified;
1501 } else if (from_fetch) {
1502 /* Only check the descriptor digest against the network statuses when
1503 * we are receiving in response to a fetch. */
1504 if (!signed_desc_digest_is_recognized(&router->cache_info)) {
1505 log_warn(LD_DIR, "Dropping unrecognized descriptor for router '%s'",
1506 router->nickname);
1507 *msg = "Router descriptor is not referenced by any network-status.";
1508 routerinfo_free(router);
1509 return -1;
1513 /* If we have a router with this name, and the identity key is the same,
1514 * choose the newer one. If the identity key has changed, and one of the
1515 * routers is named, drop the unnamed ones. (If more than one are named,
1516 * drop the old ones.)
1518 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
1519 routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
1520 if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
1521 if (router->cache_info.published_on <=
1522 old_router->cache_info.published_on) {
1523 /* Same key, but old */
1524 log_debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
1525 router->nickname);
1526 routerlist_insert_old(routerlist, router);
1527 *msg = "Router descriptor was not new.";
1528 return -1;
1529 } else {
1530 /* Same key, new. */
1531 int unreachable = 0;
1532 log_debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
1533 router->nickname, old_router->nickname,
1534 hex_str(id_digest,DIGEST_LEN));
1535 if (router->addr == old_router->addr &&
1536 router->or_port == old_router->or_port) {
1537 /* these carry over when the address and orport are unchanged.*/
1538 router->last_reachable = old_router->last_reachable;
1539 router->testing_since = old_router->testing_since;
1540 router->num_unreachable_notifications =
1541 old_router->num_unreachable_notifications;
1543 if (authdir &&
1544 dirserv_thinks_router_is_blatantly_unreachable(router,
1545 time(NULL))) {
1546 if (router->num_unreachable_notifications >= 3) {
1547 unreachable = 1;
1548 log_notice(LD_DIR, "Notifying server '%s' that it's unreachable. "
1549 "(ContactInfo '%s', platform '%s').",
1550 router->nickname,
1551 router->contact_info ? router->contact_info : "",
1552 router->platform ? router->platform : "");
1553 } else {
1554 log_info(LD_DIR,"'%s' may be unreachable -- the %d previous "
1555 "descriptors were thought to be unreachable.",
1556 router->nickname, router->num_unreachable_notifications);
1557 router->num_unreachable_notifications++;
1560 routerlist_replace(routerlist, old_router, router, i, 1);
1561 if (!from_cache) {
1562 router_append_to_journal(&router->cache_info);
1564 directory_set_dirty();
1565 *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
1566 authdir_verified ? "Verified server updated" :
1567 ("Unverified server updated. (Have you sent us your key "
1568 "fingerprint?)");
1569 return unreachable ? 1 : 0;
1571 } else if (!strcasecmp(router->nickname, old_router->nickname)) {
1572 /* nicknames match, keys don't. */
1573 if (router->is_named) {
1574 /* The new verified router replaces the old one; remove the
1575 * old one. And carry on to the end of the list, in case
1576 * there are more old unverified routers with this nickname
1578 /* mark-for-close connections using the old key, so we can
1579 * make new ones with the new key.
1581 connection_t *conn;
1582 while ((conn = connection_or_get_by_identity_digest(
1583 old_router->cache_info.identity_digest))) {
1584 // And LD_OR? XXXXNM
1585 log_info(LD_DIR,"Closing conn to router '%s'; there is now a named "
1586 "router with that name.",
1587 old_router->nickname);
1588 connection_mark_for_close(conn);
1590 routerlist_remove(routerlist, old_router, i--, 0);
1591 } else if (old_router->is_named) {
1592 /* Can't replace a verified router with an unverified one. */
1593 log_debug(LD_DIR, "Skipping unverified entry for verified router '%s'",
1594 router->nickname);
1595 routerinfo_free(router);
1596 *msg =
1597 "Already have named router with same nickname and different key.";
1598 return -2;
1602 /* We haven't seen a router with this name before. Add it to the end of
1603 * the list. */
1604 routerlist_insert(routerlist, router);
1605 if (!from_cache)
1606 router_append_to_journal(&router->cache_info);
1607 directory_set_dirty();
1608 return 0;
1611 static int
1612 _compare_old_routers_by_identity(const void **_a, const void **_b)
1614 int i;
1615 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
1616 if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
1617 return i;
1618 return r1->published_on - r2->published_on;
1621 struct duration_idx_t {
1622 int duration;
1623 int idx;
1624 int old;
1627 static int
1628 _compare_duration_idx(const void *_d1, const void *_d2)
1630 const struct duration_idx_t *d1 = _d1;
1631 const struct duration_idx_t *d2 = _d2;
1632 return d1->duration - d2->duration;
1635 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
1636 * must contain routerinfo_t with the same identity and with publication time
1637 * in ascending order. Remove members from this range until there are no more
1638 * than MAX_DESCRIPTORS_PER_ROUTER remaining. Start by removing the oldest
1639 * members from before <b>cutoff</b>, then remove members which were current
1640 * for the lowest amount of time. The order of members of old_routers at
1641 * indices <b>lo</b> or higher may be changed.
1643 static void
1644 routerlist_remove_old_cached_routers_with_id(time_t cutoff, int lo, int hi,
1645 digestmap_t *retain)
1647 int i, n = hi-lo+1, n_extra;
1648 int n_rmv = 0;
1649 struct duration_idx_t *lifespans;
1650 uint8_t *rmv, *must_keep;
1651 smartlist_t *lst = routerlist->old_routers;
1652 #if 1
1653 const char *ident;
1654 tor_assert(hi < smartlist_len(lst));
1655 tor_assert(lo <= hi);
1656 ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
1657 for (i = lo+1; i <= hi; ++i) {
1658 signed_descriptor_t *r = smartlist_get(lst, i);
1659 tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
1661 #endif
1663 /* Check whether we need to do anything at all. */
1664 n_extra = n - MAX_DESCRIPTORS_PER_ROUTER;
1665 if (n_extra <= 0)
1666 return;
1668 lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
1669 rmv = tor_malloc_zero(sizeof(uint8_t)*n);
1670 must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
1671 /* Set lifespans to contain the lifespan and index of each server. */
1672 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
1673 for (i = lo; i <= hi; ++i) {
1674 signed_descriptor_t *r = smartlist_get(lst, i);
1675 signed_descriptor_t *r_next;
1676 lifespans[i-lo].idx = i;
1677 if (retain && digestmap_get(retain, r->signed_descriptor_digest)) {
1678 must_keep[i-lo] = 1;
1680 if (i < hi) {
1681 r_next = smartlist_get(lst, i+1);
1682 tor_assert(r->published_on <= r_next->published_on);
1683 lifespans[i-lo].duration = (r_next->published_on - r->published_on);
1684 } else {
1685 r_next = NULL;
1686 lifespans[i-lo].duration = INT_MAX;
1688 if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
1689 ++n_rmv;
1690 lifespans[i-lo].old = 1;
1691 rmv[i-lo] = 1;
1695 if (n_rmv < n_extra) {
1697 * We aren't removing enough servers for being old. Sort lifespans by
1698 * the duration of liveness, and remove the ones we're not already going to
1699 * remove based on how long they were alive.
1701 qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
1702 for (i = 0; i < n && n_rmv < n_extra; ++i) {
1703 if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
1704 rmv[lifespans[i].idx-lo] = 1;
1705 ++n_rmv;
1710 for (i = hi; i >= lo; --i) {
1711 if (rmv[i-lo])
1712 routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
1714 tor_free(must_keep);
1715 tor_free(rmv);
1716 tor_free(lifespans);
1719 /** Deactivate any routers from the routerlist that are more than
1720 * ROUTER_MAX_AGE seconds old; remove old routers from the list of
1721 * cached routers if we have too many.
1723 void
1724 routerlist_remove_old_routers(void)
1726 int i, hi=-1;
1727 const char *cur_id = NULL;
1728 time_t now = time(NULL);
1729 time_t cutoff;
1730 routerinfo_t *router;
1731 signed_descriptor_t *sd;
1732 digestmap_t *retain;
1733 or_options_t *options = get_options();
1734 if (!routerlist || !networkstatus_list)
1735 return;
1737 retain = digestmap_new();
1738 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
1739 if (server_mode(options) && options->DirPort) {
1740 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
1742 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
1743 if (rs->published_on >= cutoff)
1744 digestmap_set(retain, rs->descriptor_digest, (void*)1));
1748 cutoff = now - ROUTER_MAX_AGE;
1749 /* Remove too-old members of routerlist->routers. */
1750 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
1751 router = smartlist_get(routerlist->routers, i);
1752 if (router->cache_info.published_on <= cutoff &&
1753 !digestmap_get(retain, router->cache_info.signed_descriptor_digest)) {
1754 /* Too old. Remove it. */
1755 log_info(LD_DIR,
1756 "Forgetting obsolete (too old) routerinfo for router '%s'",
1757 router->nickname);
1758 routerlist_remove(routerlist, router, i--, 1);
1762 /* Remove far-too-old members of routerlist->old_routers. */
1763 cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
1764 for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
1765 sd = smartlist_get(routerlist->old_routers, i);
1766 if (sd->published_on <= cutoff &&
1767 !digestmap_get(retain, sd->signed_descriptor_digest)) {
1768 /* Too old. Remove it. */
1769 routerlist_remove_old(routerlist, sd, i--);
1773 /* Now we're looking at routerlist->old_routers for extraneous
1774 * members. (We'd keep all the members if we could, but we'd like to save
1775 * space.) First, check whether we have too many router descriptors, total.
1776 * We're okay with having too many for some given router, so long as the
1777 * total number doesn't approach MAX_DESCRIPTORS_PER_ROUTER*len(router).
1779 if (smartlist_len(routerlist->old_routers) <
1780 smartlist_len(routerlist->routers) * (MAX_DESCRIPTORS_PER_ROUTER - 1))
1781 goto done;
1783 smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
1785 /* Iterate through the list from back to front, so when we remove descriptors
1786 * we don't mess up groups we haven't gotten to. */
1787 for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
1788 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
1789 if (!cur_id) {
1790 cur_id = r->identity_digest;
1791 hi = i;
1793 if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
1794 routerlist_remove_old_cached_routers_with_id(cutoff, i+1, hi, retain);
1795 cur_id = r->identity_digest;
1796 hi = i;
1799 if (hi>=0)
1800 routerlist_remove_old_cached_routers_with_id(cutoff, 0, hi, retain);
1801 routerlist_assert_ok(routerlist);
1803 done:
1804 digestmap_free(retain, NULL);
1808 * Code to parse a single router descriptor and insert it into the
1809 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
1810 * descriptor was well-formed but could not be added; and 1 if the
1811 * descriptor was added.
1813 * If we don't add it and <b>msg</b> is not NULL, then assign to
1814 * *<b>msg</b> a static string describing the reason for refusing the
1815 * descriptor.
1817 * This is used only by the controller.
1820 router_load_single_router(const char *s, const char **msg)
1822 routerinfo_t *ri;
1823 int r;
1824 smartlist_t *lst;
1825 tor_assert(msg);
1826 *msg = NULL;
1828 if (!(ri = router_parse_entry_from_string(s, NULL))) {
1829 log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
1830 *msg = "Couldn't parse router descriptor.";
1831 return -1;
1833 if (router_is_me(ri)) {
1834 log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
1835 *msg = "Router's identity key matches mine.";
1836 routerinfo_free(ri);
1837 return 0;
1840 lst = smartlist_create();
1841 smartlist_add(lst, ri);
1842 routers_update_status_from_networkstatus(lst, 0);
1844 if ((r=router_add_to_routerlist(ri, msg, 0, 0))<0) {
1845 /* we've already assigned to *msg now, and ri is already freed */
1846 tor_assert(*msg);
1847 if (r < -1)
1848 log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
1849 smartlist_free(lst);
1850 return 0;
1851 } else {
1852 control_event_descriptors_changed(lst);
1853 smartlist_free(lst);
1854 log_debug(LD_DIR, "Added router to list");
1855 return 1;
1859 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
1860 * routers into our directory. If <b>from_cache</b> is false, the routers
1861 * are in response to a query to the network: cache them.
1863 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1864 * uppercased identity fingerprints. Do not update any router whose
1865 * fingerprint is not on the list; after updating a router, remove its
1866 * fingerprint from the list.
1868 void
1869 router_load_routers_from_string(const char *s, int from_cache,
1870 smartlist_t *requested_fingerprints)
1872 smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
1873 char fp[HEX_DIGEST_LEN+1];
1874 const char *msg;
1876 router_parse_list_from_string(&s, routers);
1878 routers_update_status_from_networkstatus(routers, !from_cache);
1880 log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
1882 SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
1884 base16_encode(fp, sizeof(fp), ri->cache_info.signed_descriptor_digest,
1885 DIGEST_LEN);
1886 if (requested_fingerprints) {
1887 if (smartlist_string_isin(requested_fingerprints, fp)) {
1888 smartlist_string_remove(requested_fingerprints, fp);
1889 } else {
1890 char *requested =
1891 smartlist_join_strings(requested_fingerprints," ",0,NULL);
1892 log_warn(LD_DIR,
1893 "We received a router descriptor with a fingerprint (%s) "
1894 "that we never requested. (We asked for: %s.) Dropping.",
1895 fp, requested);
1896 tor_free(requested);
1897 routerinfo_free(ri);
1898 continue;
1902 if (router_add_to_routerlist(ri, &msg, from_cache, !from_cache) >= 0)
1903 smartlist_add(changed, ri);
1906 if (smartlist_len(changed))
1907 control_event_descriptors_changed(changed);
1909 routerlist_assert_ok(routerlist);
1910 router_rebuild_store(0);
1912 smartlist_free(routers);
1913 smartlist_free(changed);
1916 /** Helper: return a newly allocated string containing the name of the filename
1917 * where we plan to cache <b>ns</b>. */
1918 static char *
1919 networkstatus_get_cache_filename(const networkstatus_t *ns)
1921 const char *datadir = get_options()->DataDirectory;
1922 size_t len = strlen(datadir)+64;
1923 char fp[HEX_DIGEST_LEN+1];
1924 char *fn = tor_malloc(len+1);
1925 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
1926 tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
1927 return fn;
1930 /** Helper for smartlist_sort: Compare two networkstatus objects by
1931 * publication date. */
1932 static int
1933 _compare_networkstatus_published_on(const void **_a, const void **_b)
1935 const networkstatus_t *a = *_a, *b = *_b;
1936 if (a->published_on < b->published_on)
1937 return -1;
1938 else if (a->published_on > b->published_on)
1939 return 1;
1940 else
1941 return 0;
1944 /** Add the parsed neworkstatus in <b>ns</b> (with original document in
1945 * <b>s</b> to the disk cache (and the in-memory directory server cache) as
1946 * appropriate. */
1947 static int
1948 add_networkstatus_to_cache(const char *s,
1949 networkstatus_source_t source,
1950 networkstatus_t *ns)
1952 if (source != NS_FROM_CACHE) {
1953 char *fn = networkstatus_get_cache_filename(ns);
1954 if (write_str_to_file(fn, s, 0)<0) {
1955 log_notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
1957 tor_free(fn);
1960 if (get_options()->DirPort)
1961 dirserv_set_cached_networkstatus_v2(s,
1962 ns->identity_digest,
1963 ns->published_on);
1965 return 0;
1968 /** How far in the future do we allow a network-status to get before removing
1969 * it? (seconds) */
1970 #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
1971 /** Given a string <b>s</b> containing a network status that we received at
1972 * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
1973 * store it, and put it into our cache is necessary.
1975 * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
1976 * own networkstatus_t (if we're a directory server).
1978 * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
1979 * cache.
1981 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1982 * uppercased identity fingerprints. Do not update any networkstatus whose
1983 * fingerprint is not on the list; after updating a networkstatus, remove its
1984 * fingerprint from the list.
1986 * Return 0 on success, -1 on failure.
1988 * Callers should make sure that routers_update_all_from_networkstatus() is
1989 * invoked after this function succeeds.
1992 router_set_networkstatus(const char *s, time_t arrived_at,
1993 networkstatus_source_t source, smartlist_t *requested_fingerprints)
1995 networkstatus_t *ns;
1996 int i, found;
1997 time_t now;
1998 int skewed = 0;
1999 trusted_dir_server_t *trusted_dir = NULL;
2000 const char *source_desc = NULL;
2001 char fp[HEX_DIGEST_LEN+1];
2002 char published[ISO_TIME_LEN+1];
2004 ns = networkstatus_parse_from_string(s);
2005 if (!ns) {
2006 log_warn(LD_DIR, "Couldn't parse network status.");
2007 return -1;
2009 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
2010 if (!(trusted_dir =
2011 router_get_trusteddirserver_by_digest(ns->identity_digest))) {
2012 log_info(LD_DIR, "Network status was signed, but not by an authoritative "
2013 "directory we recognize.");
2014 if (!get_options()->DirPort) {
2015 networkstatus_free(ns);
2016 return 0;
2018 source_desc = fp;
2019 } else {
2020 source_desc = trusted_dir->description;
2022 now = time(NULL);
2023 if (arrived_at > now)
2024 arrived_at = now;
2026 ns->received_on = arrived_at;
2028 format_iso_time(published, ns->published_on);
2030 if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
2031 log_warn(LD_GENERAL, "Network status from %s was published in the future "
2032 "(%s GMT). Somebody is skewed here: check your clock. "
2033 "Not caching.",
2034 source_desc, published);
2035 skewed = 1;
2038 if (!networkstatus_list)
2039 networkstatus_list = smartlist_create();
2041 if (source == NS_FROM_DIR && router_digest_is_me(ns->identity_digest)) {
2042 /* Don't replace our own networkstatus when we get it from somebody else.*/
2043 networkstatus_free(ns);
2044 return 0;
2047 if (requested_fingerprints) {
2048 if (smartlist_string_isin(requested_fingerprints, fp)) {
2049 smartlist_string_remove(requested_fingerprints, fp);
2050 } else {
2051 char *requested =
2052 smartlist_join_strings(requested_fingerprints," ",0,NULL);
2053 log_warn(LD_DIR,
2054 "We received a network status with a fingerprint (%s) that we "
2055 "never requested. (We asked for: %s.) Dropping.",
2056 fp, requested);
2057 tor_free(requested);
2058 return 0;
2062 if (!trusted_dir) {
2063 if (!skewed && get_options()->DirPort) {
2064 add_networkstatus_to_cache(s, source, ns);
2065 networkstatus_free(ns);
2067 return 0;
2070 if (source != NS_FROM_CACHE && trusted_dir)
2071 trusted_dir->n_networkstatus_failures = 0;
2073 found = 0;
2074 for (i=0; i < smartlist_len(networkstatus_list); ++i) {
2075 networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
2077 if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
2078 if (!memcmp(old_ns->networkstatus_digest,
2079 ns->networkstatus_digest, DIGEST_LEN)) {
2080 /* Same one we had before. */
2081 networkstatus_free(ns);
2082 log_info(LD_DIR,
2083 "Not replacing network-status from %s (published %s); "
2084 "we already have it.",
2085 trusted_dir->description, published);
2086 if (old_ns->received_on < arrived_at) {
2087 if (source != NS_FROM_CACHE) {
2088 char *fn = networkstatus_get_cache_filename(old_ns);
2089 /* We use mtime to tell when it arrived, so update that. */
2090 touch_file(fn);
2091 tor_free(fn);
2093 old_ns->received_on = arrived_at;
2095 return 0;
2096 } else if (old_ns->published_on >= ns->published_on) {
2097 char old_published[ISO_TIME_LEN+1];
2098 format_iso_time(old_published, old_ns->published_on);
2099 log_info(LD_DIR,
2100 "Not replacing network-status from %s (published %s);"
2101 " we have a newer one (published %s) for this authority.",
2102 trusted_dir->description, published,
2103 old_published);
2104 networkstatus_free(ns);
2105 return 0;
2106 } else {
2107 networkstatus_free(old_ns);
2108 smartlist_set(networkstatus_list, i, ns);
2109 found = 1;
2110 break;
2115 if (!found)
2116 smartlist_add(networkstatus_list, ns);
2118 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
2120 if (!router_get_by_descriptor_digest(rs->descriptor_digest))
2121 rs->need_to_mirror = 1;
2124 log_info(LD_DIR, "Setting networkstatus %s %s (published %s)",
2125 source == NS_FROM_CACHE?"cached from":
2126 (source==NS_FROM_DIR?"downloaded from":"generated for"),
2127 trusted_dir->description, published);
2128 networkstatus_list_has_changed = 1;
2130 smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
2132 if (!skewed)
2133 add_networkstatus_to_cache(s, source, ns);
2135 networkstatus_list_update_recent(now);
2137 return 0;
2140 /** How old do we allow a network-status to get before removing it
2141 * completely? */
2142 #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
2143 /** Remove all very-old network_status_t objects from memory and from the
2144 * disk cache. */
2145 void
2146 networkstatus_list_clean(time_t now)
2148 int i;
2149 if (!networkstatus_list)
2150 return;
2152 for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
2153 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
2154 char *fname = NULL;;
2155 if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
2156 continue;
2157 /* Okay, this one is too old. Remove it from the list, and delete it
2158 * from the cache. */
2159 smartlist_del(networkstatus_list, i--);
2160 fname = networkstatus_get_cache_filename(ns);
2161 if (file_status(fname) == FN_FILE) {
2162 log_info(LD_DIR, "Removing too-old networkstatus in %s", fname);
2163 unlink(fname);
2165 tor_free(fname);
2166 if (get_options()->DirPort) {
2167 dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
2169 networkstatus_free(ns);
2173 /** Helper for bsearching a list of routerstatus_t pointers.*/
2174 static int
2175 _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
2177 const char *key = _key;
2178 const routerstatus_t *rs = *_member;
2179 return memcmp(key, rs->identity_digest, DIGEST_LEN);
2182 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
2183 * NULL if none was found. */
2184 static routerstatus_t *
2185 networkstatus_find_entry(networkstatus_t *ns, const char *digest)
2187 return smartlist_bsearch(ns->entries, digest,
2188 _compare_digest_to_routerstatus_entry);
2191 /** Return the consensus view of the status of the router whose digest is
2192 * <b>digest</b>, or NULL if we don't know about any such router. */
2193 local_routerstatus_t *
2194 router_get_combined_status_by_digest(const char *digest)
2196 if (!routerstatus_list)
2197 return NULL;
2198 return smartlist_bsearch(routerstatus_list, digest,
2199 _compare_digest_to_routerstatus_entry);
2202 /** Return true iff any networkstatus includes a descriptor whose digest
2203 * is that of <b>desc</b>. */
2204 static int
2205 signed_desc_digest_is_recognized(signed_descriptor_t *desc)
2207 routerstatus_t *rs;
2208 if (!networkstatus_list)
2209 return 0;
2211 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2213 if (!(rs = networkstatus_find_entry(ns, desc->identity_digest)))
2214 continue;
2215 if (!memcmp(rs->descriptor_digest,
2216 desc->signed_descriptor_digest, DIGEST_LEN))
2217 return 1;
2219 return 0;
2222 /* XXXX These should be configurable, perhaps? NM */
2224 /** How frequently do directory authorities re-download fresh networkstatus
2225 * documents? */
2226 #define AUTHORITY_NS_CACHE_INTERVAL (5*60)
2228 /** How frequently do non-authority directory caches re-download fresh
2229 * networkstatus documents? */
2230 #define NONAUTHORITY_NS_CACHE_INTERVAL (15*60)
2232 /** We are a directory server, and so cache network_status documents.
2233 * Initiate downloads as needed to update them. For authorities, this means
2234 * asking each trusted directory for its network-status. For caches, this
2235 * means asking a random authority for all network-statuses.
2237 static void
2238 update_networkstatus_cache_downloads(time_t now)
2240 int authority = authdir_mode(get_options());
2241 int interval =
2242 authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
2244 if (last_networkstatus_download_attempted + interval >= now)
2245 return;
2246 if (!trusted_dir_servers)
2247 return;
2249 last_networkstatus_download_attempted = now;
2251 if (authority) {
2252 /* An authority launches a separate connection for everybody. */
2253 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2255 char resource[HEX_DIGEST_LEN+6];
2256 if (router_digest_is_me(ds->digest))
2257 continue;
2258 if (connection_get_by_type_addr_port_purpose(
2259 CONN_TYPE_DIR, ds->addr, ds->dir_port,
2260 DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
2261 /* We are already fetching this one. */
2262 continue;
2264 strlcpy(resource, "fp/", sizeof(resource));
2265 base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
2266 strlcat(resource, ".z", sizeof(resource));
2267 directory_initiate_command_routerstatus(
2268 &ds->fake_status, DIR_PURPOSE_FETCH_NETWORKSTATUS,
2269 0, /* Not private */
2270 resource,
2271 NULL, 0 /* No payload. */);
2273 } else {
2274 /* A non-authority cache launches one connection to a random authority. */
2275 /* (Check whether we're currently fetching network-status objects.) */
2276 if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
2277 DIR_PURPOSE_FETCH_NETWORKSTATUS))
2278 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
2282 /** How long (in seconds) does a client wait after getting a network status
2283 * before downloading the next in sequence? */
2284 #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
2285 /* How many times do we allow a networkstatus download to fail before we
2286 * assume that the authority isn't publishing? */
2287 #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
2288 /** We are not a directory cache or authority. Update our network-status list
2289 * by launching a new directory fetch for enough network-status documents "as
2290 * necessary". See function comments for implementation details.
2292 static void
2293 update_networkstatus_client_downloads(time_t now)
2295 int n_live = 0, needed = 0, n_running_dirservers, n_dirservers, i;
2296 int most_recent_idx = -1;
2297 trusted_dir_server_t *most_recent = NULL;
2298 time_t most_recent_received = 0;
2299 char *resource, *cp;
2300 size_t resource_len;
2302 if (connection_get_by_type_purpose(CONN_TYPE_DIR,
2303 DIR_PURPOSE_FETCH_NETWORKSTATUS))
2304 return;
2306 /* This is a little tricky. We want to download enough network-status
2307 * objects so that we have at least half of them under
2308 * NETWORKSTATUS_MAX_AGE publication time. We want to download a new
2309 * *one* if the most recent one's publication time is under
2310 * NETWORKSTATUS_CLIENT_DL_INTERVAL.
2312 if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
2313 return;
2314 n_dirservers = n_running_dirservers = smartlist_len(trusted_dir_servers);
2315 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2317 networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
2318 if (!ns)
2319 continue;
2320 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
2321 --n_running_dirservers;
2322 continue;
2324 if (ns->published_on > now-NETWORKSTATUS_MAX_AGE)
2325 ++n_live;
2326 if (!most_recent || ns->received_on > most_recent_received) {
2327 most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
2328 most_recent = ds;
2329 most_recent_received = ns->received_on;
2333 /* Download enough so we have at least half live, but no more than all the
2334 * trusted dirservers we know.
2336 if (n_live < (n_dirservers/2)+1)
2337 needed = (n_dirservers/2)+1-n_live;
2338 if (needed > n_running_dirservers)
2339 needed = n_running_dirservers;
2341 if (needed)
2342 log_info(LD_DIR, "For %d/%d running directory servers, we have %d live"
2343 " network-status documents. Downloading %d.",
2344 n_running_dirservers, n_dirservers, n_live, needed);
2346 /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
2347 if (n_running_dirservers &&
2348 most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL &&
2349 needed < 1) {
2350 log_info(LD_DIR, "Our most recent network-status document (from %s) "
2351 "is %d seconds old; downloading another.",
2352 most_recent?most_recent->description:"nobody",
2353 (int)(now-most_recent_received));
2354 needed = 1;
2357 if (!needed)
2358 return;
2360 /* If no networkstatus was found, choose a dirserver at random as "most
2361 * recent". */
2362 if (most_recent_idx<0)
2363 most_recent_idx = crypto_rand_int(n_dirservers);
2365 /* Build a request string for all the resources we want. */
2366 resource_len = needed * (HEX_DIGEST_LEN+1) + 6;
2367 resource = tor_malloc(resource_len);
2368 memcpy(resource, "fp/", 3);
2369 cp = resource+3;
2370 for (i = most_recent_idx+1; needed; ++i) {
2371 trusted_dir_server_t *ds;
2372 if (i >= n_dirservers)
2373 i = 0;
2374 ds = smartlist_get(trusted_dir_servers, i);
2375 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES)
2376 continue;
2377 base16_encode(cp, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
2378 cp += HEX_DIGEST_LEN;
2379 --needed;
2380 if (needed)
2381 *cp++ = '+';
2383 memcpy(cp, ".z", 3);
2384 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
2385 tor_free(resource);
2388 /** Launch requests for networkstatus documents as appropriate. */
2389 void
2390 update_networkstatus_downloads(time_t now)
2392 or_options_t *options = get_options();
2393 if (server_mode(options) && options->DirPort)
2394 update_networkstatus_cache_downloads(time(NULL));
2395 else
2396 update_networkstatus_client_downloads(time(NULL));
2399 /** Decide whether a given addr:port is definitely accepted,
2400 * definitely rejected, probably accepted, or probably rejected by a
2401 * given policy. If <b>addr</b> is 0, we don't know the IP of the
2402 * target address. If <b>port</b> is 0, we don't know the port of the
2403 * target address.
2405 * For now, the algorithm is pretty simple: we look for definite and
2406 * uncertain matches. The first definite match is what we guess; if
2407 * it was preceded by no uncertain matches of the opposite policy,
2408 * then the guess is definite; otherwise it is probable. (If we
2409 * have a known addr and port, all matches are definite; if we have an
2410 * unknown addr/port, any address/port ranges other than "all" are
2411 * uncertain.)
2413 * We could do better by assuming that some ranges never match typical
2414 * addresses (127.0.0.1, and so on). But we'll try this for now.
2416 addr_policy_result_t
2417 router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
2418 addr_policy_t *policy)
2420 int maybe_reject = 0;
2421 int maybe_accept = 0;
2422 int match = 0;
2423 int maybe = 0;
2424 addr_policy_t *tmpe;
2426 for (tmpe=policy; tmpe; tmpe=tmpe->next) {
2427 maybe = 0;
2428 if (!addr) {
2429 /* Address is unknown. */
2430 if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
2431 (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
2432 /* The port definitely matches. */
2433 if (tmpe->msk == 0) {
2434 match = 1;
2435 } else {
2436 maybe = 1;
2438 } else if (!port) {
2439 /* The port maybe matches. */
2440 maybe = 1;
2442 } else {
2443 /* Address is known */
2444 if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
2445 if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
2446 /* Exact match for the policy */
2447 match = 1;
2448 } else if (!port) {
2449 maybe = 1;
2453 if (maybe) {
2454 if (tmpe->policy_type == ADDR_POLICY_REJECT)
2455 maybe_reject = 1;
2456 else
2457 maybe_accept = 1;
2459 if (match) {
2460 if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
2461 /* If we already hit a clause that might trigger a 'reject', than we
2462 * can't be sure of this certain 'accept'.*/
2463 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED :
2464 ADDR_POLICY_ACCEPTED;
2465 } else {
2466 return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED :
2467 ADDR_POLICY_REJECTED;
2471 /* accept all by default. */
2472 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
2475 /** Return 1 if all running sufficiently-stable routers will reject
2476 * addr:port, return 0 if any might accept it. */
2478 router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
2479 int need_uptime)
2481 addr_policy_result_t r;
2482 if (!routerlist) return 1;
2484 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
2486 if (router->is_running &&
2487 !router_is_unreliable(router, need_uptime, 0, 0)) {
2488 r = router_compare_addr_to_addr_policy(addr, port, router->exit_policy);
2489 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
2490 return 0; /* this one could be ok. good enough. */
2493 return 1; /* all will reject. */
2496 #if 0
2498 * If <b>policy</b> implicitly allows connections to any port in the
2499 * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
2500 * part of the policy that allows it, and return 1. Else return 0.
2502 * A policy allows an IP:Port combination <em>implicitly</em> if
2503 * it is included in a *: pattern, or in a fallback pattern.
2505 static int
2506 policy_includes_addr_mask_implicitly(addr_policy_t *policy,
2507 uint32_t addr, uint32_t mask,
2508 addr_policy_t **policy_out)
2510 uint32_t addr2;
2511 tor_assert(policy_out);
2512 addr &= mask;
2513 addr2 = addr | ~mask;
2514 for (; policy; policy=policy->next) {
2515 /* Does this policy cover all of the address range we're looking at? */
2516 /* Boolean logic time: range X is contained in range Y if, for
2517 * each bit B, all possible values of B in X are values of B in Y.
2518 * In "addr", we have every fixed bit set to its value, and every
2519 * free bit set to 0. In "addr2", we have every fixed bit set to
2520 * its value, and every free bit set to 1. So if addr and addr2 are
2521 * both in the policy, the range is covered by the policy.
2523 uint32_t p_addr = policy->addr & policy->msk;
2524 if (p_addr == (addr & policy->msk) &&
2525 p_addr == (addr2 & policy->msk) &&
2526 (policy->prt_min <= 1 && policy->prt_max == 65535) &&
2527 policy->policy_type == ADDR_POLICY_REJECT) {
2528 return 0;
2530 /* Does this policy cover some of the address range we're looking at? */
2531 /* Boolean logic time: range X and range Y intersect if there is
2532 * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
2533 * This is FALSE iff there is some bit b where Xmask == yMask == 1
2534 * and Xaddr != Yaddr. So if X intersects with Y iff at every
2535 * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
2536 * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
2538 if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
2539 policy->policy_type == ADDR_POLICY_ACCEPT) {
2540 *policy_out = policy;
2541 return 1;
2544 *policy_out = NULL;
2545 return 1;
2548 /** If <b>policy</b> implicitly allows connections to any port on
2549 * 127.*, 192.168.*, etc, then warn (if <b>should_warn</b> is set) and return
2550 * true. Else return false.
2553 exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
2554 int should_warn)
2556 addr_policy_t *p;
2557 int r=0,i;
2558 static struct {
2559 uint32_t addr; uint32_t mask; const char *network;
2560 } private_networks[] = {
2561 { 0x00000000, 0xff000000, "\"this\" network (0.0.0.0/8)" },
2562 { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
2563 { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
2564 { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
2565 { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
2566 { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
2567 { 0,0,NULL},
2569 for (i=0; private_networks[i].mask; ++i) {
2570 p = NULL;
2571 /* log_info(LD_CONFIG,
2572 "Checking network %s", private_networks[i].network); */
2573 if (policy_includes_addr_mask_implicitly(
2574 policy, private_networks[i].addr, private_networks[i].mask, &p)) {
2575 if (should_warn)
2576 log_warn(LD_CONFIG, "Exit policy %s implicitly accepts %s",
2577 p?p->string:"(default)",
2578 private_networks[i].network);
2579 r = 1;
2583 return r;
2586 #endif
2587 /** Return true iff <b>router</b> does not permit exit streams.
2590 router_exit_policy_rejects_all(routerinfo_t *router)
2592 return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
2593 == ADDR_POLICY_REJECTED;
2596 /** Add to the list of authorized directory servers one at
2597 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
2598 * <b>address</b> is NULL, add ourself. */
2599 void
2600 add_trusted_dir_server(const char *nickname, const char *address,
2601 uint16_t port, const char *digest, int supports_v1)
2603 trusted_dir_server_t *ent;
2604 uint32_t a;
2605 char *hostname = NULL;
2606 size_t dlen;
2607 if (!trusted_dir_servers)
2608 trusted_dir_servers = smartlist_create();
2610 if (!address) { /* The address is us; we should guess. */
2611 if (resolve_my_address(get_options(), &a, &hostname) < 0) {
2612 log_warn(LD_CONFIG,
2613 "Couldn't find a suitable address when adding ourself as a "
2614 "trusted directory server.");
2615 return;
2617 } else {
2618 if (tor_lookup_hostname(address, &a)) {
2619 log_warn(LD_CONFIG,
2620 "Unable to lookup address for directory server at '%s'",
2621 address);
2622 return;
2624 hostname = tor_strdup(address);
2625 a = ntohl(a);
2628 ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
2629 ent->nickname = nickname ? tor_strdup(nickname) : NULL;
2630 ent->address = hostname;
2631 ent->addr = a;
2632 ent->dir_port = port;
2633 ent->is_running = 1;
2634 ent->is_v1_authority = supports_v1;
2635 memcpy(ent->digest, digest, DIGEST_LEN);
2637 dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
2638 ent->description = tor_malloc(dlen);
2639 if (nickname)
2640 tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
2641 nickname, hostname, (int)port);
2642 else
2643 tor_snprintf(ent->description, dlen, "directory server at %s:%d",
2644 hostname, (int)port);
2646 ent->fake_status.addr = ent->addr;
2647 memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
2648 if (nickname)
2649 strlcpy(ent->fake_status.nickname, nickname,
2650 sizeof(ent->fake_status.nickname));
2651 else
2652 ent->fake_status.nickname[0] = '\0';
2653 ent->fake_status.dir_port = ent->dir_port;
2655 smartlist_add(trusted_dir_servers, ent);
2658 /** Free storage held in <b>ds</b> */
2659 void
2660 trusted_dir_server_free(trusted_dir_server_t *ds)
2662 tor_free(ds->nickname);
2663 tor_free(ds->description);
2664 tor_free(ds->address);
2665 tor_free(ds);
2668 /** Remove all members from the list of trusted dir servers. */
2669 void
2670 clear_trusted_dir_servers(void)
2672 if (trusted_dir_servers) {
2673 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
2674 trusted_dir_server_free(ent));
2675 smartlist_clear(trusted_dir_servers);
2676 } else {
2677 trusted_dir_servers = smartlist_create();
2681 /** Return the network status with a given identity digest. */
2682 networkstatus_t *
2683 networkstatus_get_by_digest(const char *digest)
2685 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2687 if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
2688 return ns;
2690 return NULL;
2693 /** We believe networkstatuses more recent than this when they tell us that
2694 * our server is broken, invalid, obsolete, etc. */
2695 #define SELF_OPINION_INTERVAL (90*60)
2697 /** Return a string naming the versions of Tor recommended by
2698 * at least n_needed versioning networkstatuses */
2699 static char *
2700 compute_recommended_versions(time_t now, int client)
2702 int n_seen;
2703 char *current;
2704 smartlist_t *combined, *recommended;
2705 int n_recent;
2706 char *result;
2708 if (!networkstatus_list)
2709 return tor_strdup("<none>");
2711 combined = smartlist_create();
2712 n_recent = 0;
2713 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2715 const char *vers;
2716 if (! ns->recommends_versions)
2717 continue;
2718 if (ns->received_on + SELF_OPINION_INTERVAL < now)
2719 continue;
2720 n_recent++;
2721 vers = client ? ns->client_versions : ns->server_versions;
2722 if (!vers)
2723 continue;
2724 smartlist_split_string(combined, vers, ",",
2725 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2728 sort_version_list(combined);
2730 current = NULL;
2731 n_seen = 0;
2732 recommended = smartlist_create();
2733 SMARTLIST_FOREACH(combined, char *, cp,
2735 if (current && !strcmp(cp, current)) {
2736 ++n_seen;
2737 } else {
2738 if (n_seen >= n_recent/2 && current)
2739 smartlist_add(recommended, current);
2740 n_seen = 0;
2741 current = cp;
2744 if (n_seen >= n_recent/2 && current)
2745 smartlist_add(recommended, current);
2747 result = smartlist_join_strings(recommended, ", ", 0, NULL);
2749 SMARTLIST_FOREACH(combined, char *, cp, tor_free(cp));
2750 smartlist_free(combined);
2751 smartlist_free(recommended);
2753 return result;
2756 /** If the network-status list has changed since the last time we called this
2757 * function, update the status of every routerinfo from the network-status
2758 * list.
2760 void
2761 routers_update_all_from_networkstatus(void)
2763 routerinfo_t *me;
2764 time_t now;
2765 if (!routerlist || !networkstatus_list ||
2766 (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
2767 return;
2769 now = time(NULL);
2770 if (networkstatus_list_has_changed)
2771 routerstatus_list_update_from_networkstatus(now);
2773 routers_update_status_from_networkstatus(routerlist->routers, 0);
2775 me = router_get_my_routerinfo();
2776 if (me && !have_warned_about_unverified_status) {
2777 int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0;
2778 routerstatus_t *rs;
2779 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2781 if (ns->received_on + SELF_OPINION_INTERVAL < now)
2782 continue;
2783 ++n_recent;
2784 if (!(rs = networkstatus_find_entry(ns, me->cache_info.identity_digest)))
2785 continue;
2786 ++n_listing;
2787 if (rs->is_valid)
2788 ++n_valid;
2789 if (rs->is_named)
2790 ++n_named;
2793 if (n_recent >= 2 && n_listing >= 2) {
2794 /* XXX When we have more than 3 dirservers, these warnings
2795 * might become spurious depending on which combination of
2796 * network-statuses we have. Perhaps we should wait until we
2797 * have tried all of them? -RD */
2798 if (n_valid <= n_recent/2) {
2799 log_warn(LD_GENERAL,
2800 "%d/%d recent directory servers list us as invalid. Please "
2801 "consider sending your identity fingerprint to the tor-ops.",
2802 n_recent-n_valid, n_recent);
2803 have_warned_about_unverified_status = 1;
2804 } else if (!n_named) { // (n_named <= n_recent/2) {
2805 log_warn(LD_GENERAL, "0/%d recent directory servers recognize this "
2806 "server. Please consider sending your identity fingerprint "
2807 "to the tor-ops.",
2808 n_recent);
2809 have_warned_about_unverified_status = 1;
2814 entry_guards_set_status_from_directory();
2816 if (!have_warned_about_old_version) {
2817 int n_recent = 0;
2818 int n_recommended = 0;
2819 int is_server = server_mode(get_options());
2820 version_status_t consensus = VS_RECOMMENDED;
2821 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2823 version_status_t vs;
2824 if (!ns->recommends_versions ||
2825 ns->received_on + SELF_OPINION_INTERVAL < now )
2826 continue;
2827 vs = tor_version_is_obsolete(
2828 VERSION, is_server ? ns->server_versions : ns->client_versions);
2829 if (vs == VS_RECOMMENDED)
2830 ++n_recommended;
2831 if (n_recent++ == 0) {
2832 consensus = vs;
2833 } else if (consensus != vs) {
2834 consensus = version_status_join(consensus, vs);
2837 if (n_recent > 2 && n_recommended < n_recent/2) {
2838 if (consensus == VS_NEW || consensus == VS_NEW_IN_SERIES) {
2839 if (!have_warned_about_new_version) {
2840 char *rec = compute_recommended_versions(now, !is_server);
2841 log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
2842 "recommended version%s, according to %d/%d recent network "
2843 "statuses. Versions recommended by at least %d recent "
2844 "authorit%s are: %s",
2845 VERSION,
2846 consensus == VS_NEW_IN_SERIES ? " in its series" : "",
2847 n_recent-n_recommended, n_recent, n_recent/2,
2848 n_recent/2 > 1 ? "ies" : "y", rec);
2849 have_warned_about_new_version = 1;
2850 tor_free(rec);
2852 } else {
2853 char *rec = compute_recommended_versions(now, !is_server);
2854 log_warn(LD_GENERAL, "Please upgrade! "
2855 "This version of Tor (%s) is %s, according to "
2856 "%d/%d recent network statuses. Versions recommended by "
2857 "at least %d recent authorit%s are: %s",
2858 VERSION, consensus == VS_OLD ? "obsolete" : "not recommended",
2859 n_recent-n_recommended, n_recent, n_recent/2,
2860 n_recent/2 > 1 ? "ies" : "y", rec);
2861 have_warned_about_old_version = 1;
2862 tor_free(rec);
2864 } else {
2865 log_info(LD_GENERAL, "%d/%d recent directories think my version is ok.",
2866 n_recommended, n_recent);
2870 routerstatus_list_has_changed = 0;
2873 /** Allow any network-status newer than this to influence our view of who's
2874 * running. */
2875 #define DEFAULT_RUNNING_INTERVAL (60*60)
2876 /** If possible, always allow at least this many network-statuses to influence
2877 * our view of who's running. */
2878 #define MIN_TO_INFLUENCE_RUNNING 3
2880 /** Change the is_recent field of each member of networkstatus_list so that
2881 * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
2882 * at least the MIN_TO_INFLUENCE_RUNNING most recent members are recent, and no
2883 * others are recent. Set networkstatus_list_has_changed if anything happened.
2885 void
2886 networkstatus_list_update_recent(time_t now)
2888 int n_statuses, n_recent, changed, i;
2889 char published[ISO_TIME_LEN+1];
2891 if (!networkstatus_list)
2892 return;
2894 n_statuses = smartlist_len(networkstatus_list);
2895 n_recent = 0;
2896 changed = 0;
2897 for (i=n_statuses-1; i >= 0; --i) {
2898 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
2899 trusted_dir_server_t *ds =
2900 router_get_trusteddirserver_by_digest(ns->identity_digest);
2901 const char *src = ds?ds->description:ns->source_address;
2902 if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
2903 ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
2904 if (!ns->is_recent) {
2905 format_iso_time(published, ns->published_on);
2906 log_info(LD_DIR,
2907 "Networkstatus from %s (published %s) is now \"recent\"",
2908 src, published);
2909 changed = 1;
2911 ns->is_recent = 1;
2912 ++n_recent;
2913 } else {
2914 if (ns->is_recent) {
2915 format_iso_time(published, ns->published_on);
2916 log_info(LD_DIR,
2917 "Networkstatus from %s (published %s) is "
2918 "no longer \"recent\"",
2919 src, published);
2920 changed = 1;
2921 ns->is_recent = 0;
2925 if (changed)
2926 networkstatus_list_has_changed = 1;
2929 /** Helper for routerstatus_list_update_from_networkstatus: remember how many
2930 * authorities recommend a given descriptor digest. */
2931 typedef struct {
2932 routerstatus_t *rs;
2933 int count;
2934 } desc_digest_count_t;
2936 /** Update our view of router status (as stored in routerstatus_list) from the
2937 * current set of network status documents (as stored in networkstatus_list).
2938 * Do nothing unless the network status list has changed since the last time
2939 * this function was called.
2941 static void
2942 routerstatus_list_update_from_networkstatus(time_t now)
2944 or_options_t *options = get_options();
2945 int n_trusted, n_statuses, n_recent = 0, n_naming = 0;
2946 int i, j, warned;
2947 int *index, *size;
2948 networkstatus_t **networkstatus;
2949 smartlist_t *result;
2950 strmap_t *name_map;
2951 char conflict[DIGEST_LEN]; /* Sentinel value */
2952 desc_digest_count_t *digest_counts = NULL;
2954 /* compute which network statuses will have a vote now */
2955 networkstatus_list_update_recent(now);
2957 if (!networkstatus_list_has_changed)
2958 return;
2959 if (!networkstatus_list)
2960 networkstatus_list = smartlist_create();
2961 if (!routerstatus_list)
2962 routerstatus_list = smartlist_create();
2963 if (!trusted_dir_servers)
2964 trusted_dir_servers = smartlist_create();
2965 if (!warned_conflicts)
2966 warned_conflicts = smartlist_create();
2968 n_trusted = smartlist_len(trusted_dir_servers);
2969 n_statuses = smartlist_len(networkstatus_list);
2971 if (n_statuses < (n_trusted/2)+1) {
2972 /* Not enough statuses to adjust status. */
2973 log_notice(LD_DIR,
2974 "Not enough statuses to update router status list. (%d/%d)",
2975 n_statuses, n_trusted);
2976 return;
2979 log_info(LD_DIR, "Rebuilding router status list.");
2981 index = tor_malloc(sizeof(int)*n_statuses);
2982 size = tor_malloc(sizeof(int)*n_statuses);
2983 networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
2984 for (i = 0; i < n_statuses; ++i) {
2985 index[i] = 0;
2986 networkstatus[i] = smartlist_get(networkstatus_list, i);
2987 size[i] = smartlist_len(networkstatus[i]->entries);
2988 if (networkstatus[i]->binds_names)
2989 ++n_naming;
2990 if (networkstatus[i]->is_recent)
2991 ++n_recent;
2994 /** Iterate over all entries in all networkstatuses, and build
2995 * name_map as a map from lc nickname to identity digest. If there
2996 * is a conflict on that nickname, map the lc nickname to conflict.
2998 name_map = strmap_new();
2999 memset(conflict, 0xff, sizeof(conflict));
3000 for (i = 0; i < n_statuses; ++i) {
3001 if (!networkstatus[i]->binds_names)
3002 continue;
3003 SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
3005 const char *other_digest;
3006 if (!rs->is_named)
3007 continue;
3008 other_digest = strmap_get_lc(name_map, rs->nickname);
3009 warned = smartlist_string_isin(warned_conflicts, rs->nickname);
3010 if (!other_digest) {
3011 strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
3012 if (warned)
3013 smartlist_string_remove(warned_conflicts, rs->nickname);
3014 } else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
3015 other_digest != conflict) {
3016 if (!warned) {
3017 int should_warn = options->DirPort && options->AuthoritativeDir;
3018 char fp1[HEX_DIGEST_LEN+1];
3019 char fp2[HEX_DIGEST_LEN+1];
3020 base16_encode(fp1, sizeof(fp1), other_digest, DIGEST_LEN);
3021 base16_encode(fp2, sizeof(fp2), rs->identity_digest, DIGEST_LEN);
3022 log_fn(should_warn ? LOG_WARN : LOG_INFO, LD_DIR,
3023 "Naming authorities disagree about which key goes with %s. "
3024 "($%s vs $%s)",
3025 rs->nickname, fp1, fp2);
3026 strmap_set_lc(name_map, rs->nickname, conflict);
3027 smartlist_add(warned_conflicts, tor_strdup(rs->nickname));
3029 } else {
3030 if (warned)
3031 smartlist_string_remove(warned_conflicts, rs->nickname);
3036 result = smartlist_create();
3037 digest_counts = tor_malloc_zero(sizeof(desc_digest_count_t)*n_statuses);
3039 /* Iterate through all of the sorted routerstatus lists in lockstep.
3040 * Invariants:
3041 * - For 0 <= i < n_statuses: index[i] is an index into
3042 * networkstatus[i]->entries, which has size[i] elements.
3043 * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
3044 * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
3045 * networkstatus[i2]->entries[index[i2]]->identity_digest.
3047 * (That is, the indices are always advanced past lower digest before
3048 * higher.)
3050 while (1) {
3051 int n_running=0, n_named=0, n_valid=0, n_listing=0;
3052 int n_v2_dir=0, n_fast=0, n_stable=0, n_exit=0, n_guard=0;
3053 int n_desc_digests=0, highest_count=0;
3054 const char *the_name = NULL;
3055 local_routerstatus_t *rs_out, *rs_old;
3056 routerstatus_t *rs, *most_recent;
3057 networkstatus_t *ns;
3058 const char *lowest = NULL;
3060 /* Find out which of the digests appears first. */
3061 for (i = 0; i < n_statuses; ++i) {
3062 if (index[i] < size[i]) {
3063 rs = smartlist_get(networkstatus[i]->entries, index[i]);
3064 if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
3065 lowest = rs->identity_digest;
3068 if (!lowest) {
3069 /* We're out of routers. Great! */
3070 break;
3072 /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
3073 * match "lowest" are next in order. Iterate over them, incrementing those
3074 * index[i] as we go. */
3075 for (i = 0; i < n_statuses; ++i) {
3076 if (index[i] >= size[i])
3077 continue;
3078 ns = networkstatus[i];
3079 rs = smartlist_get(ns->entries, index[i]);
3080 if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
3081 continue;
3082 /* At this point, we know that we're looking at a routersatus with
3083 * identity "lowest".
3085 ++index[i];
3086 ++n_listing;
3087 /* Should we name this router? Only if all the names from naming
3088 * authorities match. */
3089 if (rs->is_named && ns->binds_names) {
3090 if (!the_name)
3091 the_name = rs->nickname;
3092 if (!strcasecmp(rs->nickname, the_name)) {
3093 ++n_named;
3094 } else if (strcmp(the_name,"**mismatch**")) {
3095 char hd[HEX_DIGEST_LEN+1];
3096 base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
3097 if (! smartlist_string_isin(warned_conflicts, hd)) {
3098 log_warn(LD_DIR,
3099 "Naming authorities disagree about nicknames for $%s "
3100 "(\"%s\" vs \"%s\")",
3101 hd, the_name, rs->nickname);
3102 smartlist_add(warned_conflicts, tor_strdup(hd));
3104 the_name = "**mismatch**";
3107 /* Keep a running count of how often which descriptor digests
3108 * appear. */
3109 for (j = 0; j < n_desc_digests; ++j) {
3110 if (!memcmp(rs->descriptor_digest,
3111 digest_counts[j].rs->descriptor_digest, DIGEST_LEN)) {
3112 if (++digest_counts[j].count > highest_count)
3113 highest_count = digest_counts[j].count;
3114 goto found;
3117 digest_counts[n_desc_digests].rs = rs;
3118 digest_counts[n_desc_digests].count = 1;
3119 if (!highest_count)
3120 highest_count = 1;
3121 ++n_desc_digests;
3122 found:
3123 /* Now tally up the easily-tallied flags. */
3124 if (rs->is_valid)
3125 ++n_valid;
3126 if (rs->is_running && ns->is_recent)
3127 ++n_running;
3128 if (rs->is_exit)
3129 ++n_exit;
3130 if (rs->is_fast)
3131 ++n_fast;
3132 if (rs->is_possible_guard)
3133 ++n_guard;
3134 if (rs->is_stable)
3135 ++n_stable;
3136 if (rs->is_v2_dir)
3137 ++n_v2_dir;
3139 /* Go over the descriptor digests and figure out which descriptor we
3140 * want. */
3141 most_recent = NULL;
3142 for (i = 0; i < n_desc_digests; ++i) {
3143 /* If any digest appears twice or more, ignore those that don't.*/
3144 if (highest_count >= 2 && digest_counts[i].count < 2)
3145 continue;
3146 if (!most_recent ||
3147 digest_counts[i].rs->published_on > most_recent->published_on)
3148 most_recent = digest_counts[i].rs;
3150 rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
3151 memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
3152 /* Copy status info about this router, if we had any before. */
3153 if ((rs_old = router_get_combined_status_by_digest(lowest))) {
3154 if (!memcmp(rs_out->status.descriptor_digest,
3155 most_recent->descriptor_digest, DIGEST_LEN)) {
3156 rs_out->n_download_failures = rs_old->n_download_failures;
3157 rs_out->next_attempt_at = rs_old->next_attempt_at;
3159 rs_out->name_lookup_warned = rs_old->name_lookup_warned;
3161 smartlist_add(result, rs_out);
3162 log_debug(LD_DIR, "Router '%s' is listed by %d/%d directories, "
3163 "named by %d/%d, validated by %d/%d, and %d/%d recent "
3164 "directories think it's running.",
3165 rs_out->status.nickname,
3166 n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
3167 n_running, n_recent);
3168 rs_out->status.is_named = 0;
3169 if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
3170 const char *d = strmap_get_lc(name_map, the_name);
3171 if (d && d != conflict)
3172 rs_out->status.is_named = 1;
3173 if (smartlist_string_isin(warned_conflicts, rs_out->status.nickname))
3174 smartlist_string_remove(warned_conflicts, rs_out->status.nickname);
3176 if (rs_out->status.is_named)
3177 strlcpy(rs_out->status.nickname, the_name,
3178 sizeof(rs_out->status.nickname));
3179 rs_out->status.is_valid = n_valid > n_statuses/2;
3180 rs_out->status.is_running = n_running > n_recent/2;
3181 rs_out->status.is_exit = n_exit > n_statuses/2;
3182 rs_out->status.is_fast = n_fast > n_statuses/2;
3183 rs_out->status.is_possible_guard = n_guard > n_statuses/2;
3184 rs_out->status.is_stable = n_stable > n_statuses/2;
3185 rs_out->status.is_v2_dir = n_v2_dir > n_statuses/2;
3187 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3188 local_routerstatus_free(rs));
3189 smartlist_free(routerstatus_list);
3190 routerstatus_list = result;
3192 tor_free(networkstatus);
3193 tor_free(index);
3194 tor_free(size);
3195 tor_free(digest_counts);
3196 strmap_free(name_map, NULL);
3198 networkstatus_list_has_changed = 0;
3199 routerstatus_list_has_changed = 1;
3202 /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
3203 * is_named, is_verified, and is_running fields according to our current
3204 * networkstatus_t documents. */
3205 void
3206 routers_update_status_from_networkstatus(smartlist_t *routers,
3207 int reset_failures)
3209 trusted_dir_server_t *ds;
3210 local_routerstatus_t *rs;
3211 routerstatus_t *rs2;
3212 or_options_t *options = get_options();
3213 int authdir = options->AuthoritativeDir;
3214 int namingdir = options->AuthoritativeDir &&
3215 options->NamingAuthoritativeDir;
3217 if (!routerstatus_list)
3218 return;
3220 SMARTLIST_FOREACH(routers, routerinfo_t *, router,
3222 const char *digest = router->cache_info.identity_digest;
3223 rs = router_get_combined_status_by_digest(digest);
3224 ds = router_get_trusteddirserver_by_digest(digest);
3226 if (!rs)
3227 continue;
3229 if (!namingdir)
3230 router->is_named = rs->status.is_named;
3232 if (!authdir) {
3233 /* If we're an authdir, don't believe others. */
3234 router->is_verified = rs->status.is_valid;
3235 router->is_running = rs->status.is_running;
3236 router->is_fast = rs->status.is_fast;
3237 router->is_stable = rs->status.is_stable;
3238 router->is_possible_guard = rs->status.is_possible_guard;
3240 if (router->is_running && ds) {
3241 ds->n_networkstatus_failures = 0;
3243 if (reset_failures) {
3244 rs->n_download_failures = 0;
3245 rs->next_attempt_at = 0;
3248 /* Note that we have this descriptor. This may be redundant? */
3249 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3251 rs2 = networkstatus_find_entry(ns, router->cache_info.identity_digest);
3252 if (rs2 && !memcmp(rs2->descriptor_digest,
3253 router->cache_info.signed_descriptor_digest,
3254 DIGEST_LEN))
3255 rs2->need_to_mirror = 0;
3260 /** For every router descriptor we are currently downloading by descriptor
3261 * digest, set result[d] to 1. */
3262 static void
3263 list_pending_descriptor_downloads(digestmap_t *result)
3265 const char *prefix = "d/";
3266 size_t p_len = strlen(prefix);
3267 int i, n_conns;
3268 connection_t **carray;
3269 smartlist_t *tmp = smartlist_create();
3271 tor_assert(result);
3272 get_connection_array(&carray, &n_conns);
3274 for (i = 0; i < n_conns; ++i) {
3275 connection_t *conn = carray[i];
3276 if (conn->type == CONN_TYPE_DIR &&
3277 conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
3278 !conn->marked_for_close) {
3279 if (!strcmpstart(conn->requested_resource, prefix))
3280 dir_split_resource_into_fingerprints(conn->requested_resource+p_len,
3281 tmp, NULL, 1);
3284 SMARTLIST_FOREACH(tmp, char *, d,
3286 digestmap_set(result, d, (void*)1);
3287 tor_free(d);
3289 smartlist_free(tmp);
3292 /** Launch downloads for all the descriptors whose digests are listed
3293 * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
3294 * If <b>source</b> is given, download from <b>source</b>; otherwise,
3295 * download from an appropriate random directory server.
3297 static void
3298 initiate_descriptor_downloads(routerstatus_t *source,
3299 smartlist_t *digests,
3300 int lo, int hi)
3302 int i, n = hi-lo;
3303 char *resource, *cp;
3304 size_t r_len;
3305 if (n <= 0)
3306 return;
3307 if (lo < 0)
3308 lo = 0;
3309 if (hi > smartlist_len(digests))
3310 hi = smartlist_len(digests);
3312 r_len = 8 + (HEX_DIGEST_LEN+1)*n;
3313 cp = resource = tor_malloc(r_len);
3314 memcpy(cp, "d/", 2);
3315 cp += 2;
3316 for (i = lo; i < hi; ++i) {
3317 base16_encode(cp, r_len-(cp-resource),
3318 smartlist_get(digests,i), DIGEST_LEN);
3319 cp += HEX_DIGEST_LEN;
3320 *cp++ = '+';
3322 memcpy(cp-1, ".z", 3);
3324 if (source) {
3325 /* We know which authority we want. */
3326 directory_initiate_command_routerstatus(source,
3327 DIR_PURPOSE_FETCH_SERVERDESC,
3328 0, /* not private */
3329 resource, NULL, 0);
3330 } else {
3331 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
3332 resource,
3335 tor_free(resource);
3338 /** Clients don't download any descriptor this recent, since it will probably
3339 * not have propageted to enough caches. */
3340 #define ESTIMATED_PROPAGATION_TIME (10*60)
3342 /** Return new list of ID fingerprints for routers that we (as a client) would
3343 * like to download.
3345 static smartlist_t *
3346 router_list_client_downloadable(void)
3348 int n_downloadable = 0;
3349 smartlist_t *downloadable = smartlist_create();
3350 digestmap_t *downloading;
3351 time_t now = time(NULL);
3352 /* these are just used for logging */
3353 int n_not_ready = 0, n_in_progress = 0, n_uptodate = 0,
3354 n_obsolete = 0, n_too_young = 0, n_wouldnt_use = 0;
3356 if (!routerstatus_list)
3357 return downloadable;
3359 downloading = digestmap_new();
3360 list_pending_descriptor_downloads(downloading);
3362 routerstatus_list_update_from_networkstatus(now);
3363 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3365 routerinfo_t *ri;
3366 if (rs->status.published_on + ROUTER_MAX_AGE < now) {
3367 /* This one is too old to consider. */
3368 ++n_obsolete;
3369 } else if (digestmap_get(downloading, rs->status.descriptor_digest)) {
3370 /* We're downloading this one now. */
3371 ++n_in_progress;
3372 } else if (!rs->status.is_running) {
3373 /* If we had this router descriptor, we wouldn't even bother using it. */
3374 ++n_wouldnt_use;
3375 } else if (router_get_by_descriptor_digest(rs->status.descriptor_digest)) {
3376 /* We have the 'best' descriptor for this router. */
3377 ++n_uptodate;
3378 } else if ((ri = router_get_by_digest(rs->status.identity_digest)) &&
3379 ri->cache_info.published_on > rs->status.published_on) {
3380 /* Oddly, we have a descriptor more recent than the 'best' one, but it
3381 was once best. So that's okay. */
3382 ++n_uptodate;
3383 } else if (rs->status.published_on + ESTIMATED_PROPAGATION_TIME > now) {
3384 /* Most caches probably don't have this descriptor yet. */
3385 ++n_too_young;
3386 } else if (rs->next_attempt_at > now) {
3387 /* We failed too recently to try again. */
3388 ++n_not_ready;
3389 } else {
3390 /* Okay, time to try it. */
3391 smartlist_add(downloadable, rs->status.descriptor_digest);
3392 ++n_downloadable;
3396 #if 0
3397 log_info(LD_DIR,
3398 "%d router descriptors are downloadable. %d are too old to consider. "
3399 "%d are in progress. %d are up-to-date. %d are too young to consider. "
3400 "%d are non-useful. %d failed too recently to retry.",
3401 n_downloadable, n_obsolete, n_in_progress, n_uptodate, n_too_young,
3402 n_wouldnt_use, n_not_ready);
3403 #endif
3405 digestmap_free(downloading, NULL);
3406 return downloadable;
3409 /** Initiate new router downloads as needed.
3411 * We only allow one router descriptor download at a time.
3412 * If we have less than two network-status documents, we ask
3413 * a directory for "all descriptors."
3414 * Otherwise, we ask for all descriptors that we think are different
3415 * from what we have.
3417 static void
3418 update_router_descriptor_client_downloads(time_t now)
3420 /* Max amount of hashes to download per request.
3421 * Since squid does not like URLs >= 4096 bytes we limit it to 96.
3422 * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
3423 * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
3424 * So use 96 because it's a nice number.
3426 #define MAX_DL_PER_REQUEST 96
3427 /** Don't split our requests so finely that we are requesting fewer than
3428 * this number per server. */
3429 #define MIN_DL_PER_REQUEST 4
3430 /** To prevent a single screwy cache from confusing us by selective reply,
3431 * try to split our requests into at least this this many requests. */
3432 #define MIN_REQUESTS 3
3433 /** If we want fewer than this many descriptors, wait until we
3434 * want more, or until MAX_(CLIENT|SERVER)_INTERVAL_WITHOUT_REQUEST has
3435 * passed. */
3436 #define MAX_DL_TO_DELAY 16
3437 /** When directory clients have only a few servers to request, they batch
3438 * them until they have more, or until this amount of time has passed. */
3439 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
3440 smartlist_t *downloadable = NULL;
3441 int should_delay, n_downloadable;
3442 or_options_t *options = get_options();
3444 if (server_mode(options) && options->DirPort) {
3445 log_warn(LD_BUG,
3446 "Called router_descriptor_client_downloads() on a mirror?");
3449 if (networkstatus_list && smartlist_len(networkstatus_list) < 2) {
3450 /* XXXX Is this redundant? -NM */
3451 log_info(LD_DIR,
3452 "Not enough networkstatus documents to launch requests.");
3455 downloadable = router_list_client_downloadable();
3456 n_downloadable = smartlist_len(downloadable);
3457 if (n_downloadable >= MAX_DL_TO_DELAY) {
3458 log_debug(LD_DIR,
3459 "There are enough downloadable routerdescs to launch requests.");
3460 should_delay = 0;
3461 } else if (n_downloadable == 0) {
3462 // log_debug(LD_DIR, "No routerdescs need to be downloaded.");
3463 should_delay = 1;
3464 } else {
3465 should_delay = (last_routerdesc_download_attempted +
3466 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
3467 if (!should_delay) {
3468 if (last_routerdesc_download_attempted) {
3469 log_info(LD_DIR,
3470 "There are not many downloadable routerdescs, but we've "
3471 "been waiting long enough (%d seconds). Downloading.",
3472 (int)(now-last_routerdesc_download_attempted));
3473 } else {
3474 log_info(LD_DIR,
3475 "There are not many downloadable routerdescs, but we've "
3476 "never downloaded descriptors before. Downloading.");
3481 if (! should_delay) {
3482 int i, n_per_request;
3483 n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
3484 if (n_per_request > MAX_DL_PER_REQUEST)
3485 n_per_request = MAX_DL_PER_REQUEST;
3486 if (n_per_request < MIN_DL_PER_REQUEST)
3487 n_per_request = MIN_DL_PER_REQUEST;
3489 log_info(LD_DIR,
3490 "Launching %d request%s for %d router%s, %d at a time",
3491 (n_downloadable+n_per_request-1)/n_per_request,
3492 n_downloadable>n_per_request?"s":"",
3493 n_downloadable, n_downloadable>1?"s":"", n_per_request);
3494 for (i=0; i < n_downloadable; i += n_per_request) {
3495 initiate_descriptor_downloads(NULL, downloadable, i, i+n_per_request);
3497 last_routerdesc_download_attempted = now;
3499 smartlist_free(downloadable);
3502 /* DOCDOC */
3503 static void
3504 update_router_descriptor_cache_downloads(time_t now)
3506 smartlist_t **downloadable; /* For each authority, what can we dl from it? */
3507 smartlist_t **download_from; /* ... and, what will we dl from it? */
3508 digestmap_t *map; /* Which descs are in progress, or assigned? */
3509 int i, j, n;
3510 int n_download;
3511 or_options_t *options = get_options();
3513 if (!(server_mode(options) && options->DirPort)) {
3514 log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads() "
3515 "on a non-mirror?");
3518 if (!networkstatus_list || !smartlist_len(networkstatus_list))
3519 return;
3521 map = digestmap_new();
3522 n = smartlist_len(networkstatus_list);
3524 downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
3525 download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
3527 /* Set map[d]=1 for the digest of every descriptor that we are currently
3528 * downloading. */
3529 list_pending_descriptor_downloads(map);
3531 /* For the digest of every descriptor that we don't have, and that we aren't
3532 * downloading, add d to downloadable[i] if the i'th networkstatus knows
3533 * about that descriptor, and we haven't already failed to get that
3534 * descriptor from the corresponding authority.
3536 n_download = 0;
3537 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3539 smartlist_t *dl = smartlist_create();
3540 downloadable[ns_sl_idx] = dl;
3541 download_from[ns_sl_idx] = smartlist_create();
3542 SMARTLIST_FOREACH(ns->entries, routerstatus_t * , rs,
3544 if (!rs->need_to_mirror)
3545 continue;
3546 if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
3547 log_warn(LD_BUG,
3548 "We have a router descriptor, but need_to_mirror=1.");
3549 rs->need_to_mirror = 0;
3550 continue;
3552 if (options->AuthoritativeDir && dirserv_would_reject_router(rs)) {
3553 rs->need_to_mirror = 0;
3554 continue;
3556 if (digestmap_get(map, rs->descriptor_digest)) {
3557 /* We're downloading it already. */
3558 continue;
3559 } else {
3560 /* We could download it from this guy. */
3561 smartlist_add(dl, rs->descriptor_digest);
3562 ++n_download;
3567 /* At random, assign descriptors to authorities such that:
3568 * - if d is a member of some downloadable[x], d is a member of some
3569 * download_from[y]. (Everything we want to download, we try to download
3570 * from somebody.)
3571 * - If d is a mamber of download_from[y], d is a member of downloadable[y].
3572 * (We only try to download descriptors from authorities who claim to have
3573 * them.)
3574 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
3575 * (We don't try to download anything from two authorities concurrently.)
3577 while (n_download) {
3578 int which_ns = crypto_rand_int(n);
3579 smartlist_t *dl = downloadable[which_ns];
3580 int idx;
3581 char *d;
3582 tor_assert(dl);
3583 if (!smartlist_len(dl))
3584 continue;
3585 idx = crypto_rand_int(smartlist_len(dl));
3586 d = smartlist_get(dl, idx);
3587 if (! digestmap_get(map, d)) {
3588 smartlist_add(download_from[which_ns], d);
3589 digestmap_set(map, d, (void*) 1);
3591 smartlist_del(dl, idx);
3592 --n_download;
3595 /* Now, we can actually launch our requests. */
3596 for (i=0; i<n; ++i) {
3597 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
3598 trusted_dir_server_t *ds =
3599 router_get_trusteddirserver_by_digest(ns->identity_digest);
3600 smartlist_t *dl = download_from[i];
3601 if (!ds) {
3602 log_warn(LD_BUG, "Networkstatus with no corresponding authority!");
3603 continue;
3605 if (! smartlist_len(dl))
3606 continue;
3607 log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
3608 smartlist_len(dl), ds->nickname);
3609 for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
3610 initiate_descriptor_downloads(&(ds->fake_status), dl, j,
3611 j+MAX_DL_PER_REQUEST);
3615 for (i=0; i<n; ++i) {
3616 smartlist_free(download_from[i]);
3617 smartlist_free(downloadable[i]);
3619 tor_free(download_from);
3620 tor_free(downloadable);
3621 digestmap_free(map,NULL);
3624 /* DOCDOC */
3625 void
3626 update_router_descriptor_downloads(time_t now)
3628 or_options_t *options = get_options();
3629 if (server_mode(options) && options->DirPort) {
3630 update_router_descriptor_cache_downloads(now);
3631 } else {
3632 update_router_descriptor_client_downloads(now);
3636 /** Return true iff we have enough networkstatus and router information to
3637 * start building circuits. Right now, this means "at least 2 networkstatus
3638 * documents, and at least 1/4 of expected routers." */
3639 //XXX should consider whether we have enough exiting nodes here.
3641 router_have_minimum_dir_info(void)
3643 int tot = 0, num_running = 0;
3644 int n_ns, res, avg;
3645 static int have_enough = 0;
3646 if (!networkstatus_list || !routerlist) {
3647 res = 0;
3648 goto done;
3650 n_ns = smartlist_len(networkstatus_list);
3651 if (n_ns<2) {
3652 res = 0;
3653 goto done;
3655 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3656 tot += smartlist_len(ns->entries));
3657 avg = tot / n_ns;
3658 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3660 if (rs->status.is_running)
3661 num_running++;
3663 res = smartlist_len(routerlist->routers) >= (avg/4) && num_running > 2;
3664 done:
3665 if (res && !have_enough) {
3666 log(LOG_NOTICE, LD_DIR,
3667 "We now have enough directory information to build circuits.");
3669 if (!res && have_enough) {
3670 log(LOG_NOTICE, LD_DIR,"Our directory information is no longer up-to-date "
3671 "enough to build circuits.%s",
3672 num_running > 2 ? "" : " (Not enough servers seem reachable -- "
3673 "is your network connection down?)");
3675 have_enough = res;
3676 return res;
3679 /** Reset the descriptor download failure count on all routers, so that we
3680 * can retry any long-failed routers immediately.
3682 void
3683 router_reset_descriptor_download_failures(void)
3685 if (!routerstatus_list)
3686 return;
3687 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3689 rs->n_download_failures = 0;
3690 rs->next_attempt_at = 0;
3692 tor_assert(networkstatus_list);
3693 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3694 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs,
3696 if (!router_get_by_descriptor_digest(rs->descriptor_digest))
3697 rs->need_to_mirror = 1;
3698 }));
3699 last_routerdesc_download_attempted = 0;
3702 /** Any changes in a router descriptor's publication time larger than this are
3703 * automatically non-cosmetic. */
3704 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
3706 /** Return true iff the only differences between r1 and r2 are such that
3707 * would not cause a recent (post 0.1.1.6) dirserver to republish.
3710 router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
3712 time_t r1pub, r2pub;
3713 tor_assert(r1 && r2);
3715 /* r1 should be the one that was published first. */
3716 if (r1->cache_info.published_on > r2->cache_info.published_on) {
3717 routerinfo_t *ri_tmp = r2;
3718 r2 = r1;
3719 r1 = ri_tmp;
3722 /* If any key fields differ, they're different. */
3723 if (strcasecmp(r1->address, r2->address) ||
3724 strcasecmp(r1->nickname, r2->nickname) ||
3725 r1->or_port != r2->or_port ||
3726 r1->dir_port != r2->dir_port ||
3727 crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
3728 crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
3729 strcasecmp(r1->platform, r2->platform) ||
3730 (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
3731 (!r1->contact_info && r2->contact_info) ||
3732 (r1->contact_info && r2->contact_info &&
3733 strcasecmp(r1->contact_info, r2->contact_info)) ||
3734 r1->is_hibernating != r2->is_hibernating ||
3735 config_cmp_addr_policies(r1->exit_policy, r2->exit_policy))
3736 return 0;
3737 if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
3738 return 0;
3739 if (r1->declared_family && r2->declared_family) {
3740 int i, n;
3741 if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
3742 return 0;
3743 n = smartlist_len(r1->declared_family);
3744 for (i=0; i < n; ++i) {
3745 if (strcasecmp(smartlist_get(r1->declared_family, i),
3746 smartlist_get(r2->declared_family, i)))
3747 return 0;
3751 /* Did bandwidth change a lot? */
3752 if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
3753 (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
3754 return 0;
3756 /* Did more than 12 hours pass? */
3757 if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
3758 < r2->cache_info.published_on)
3759 return 0;
3761 /* Did uptime fail to increase by approximately the amount we would think,
3762 * give or take 30 minutes? */
3763 r1pub = r1->cache_info.published_on;
3764 r2pub = r2->cache_info.published_on;
3765 if (abs(r2->uptime - (r1->uptime + (r2pub - r1pub))))
3766 return 0;
3768 /* Otherwise, the difference is cosmetic. */
3769 return 1;
3772 static void
3773 routerlist_assert_ok(routerlist_t *rl)
3775 digestmap_iter_t *iter;
3776 routerinfo_t *r2;
3777 signed_descriptor_t *sd2;
3778 if (!routerlist)
3779 return;
3780 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
3782 r2 = digestmap_get(rl->identity_map, r->cache_info.identity_digest);
3783 tor_assert(r == r2);
3784 sd2 = digestmap_get(rl->desc_digest_map,
3785 r->cache_info.signed_descriptor_digest);
3786 tor_assert(&(r->cache_info) == sd2);
3788 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
3790 r2 = digestmap_get(rl->identity_map, sd->identity_digest);
3791 tor_assert(sd != &(r2->cache_info));
3792 sd2 = digestmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
3793 tor_assert(sd == sd2);
3795 iter = digestmap_iter_init(rl->identity_map);
3796 while (!digestmap_iter_done(iter)) {
3797 const char *d;
3798 void *_r;
3799 routerinfo_t *r;
3800 digestmap_iter_get(iter, &d, &_r);
3801 r = _r;
3802 tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
3803 iter = digestmap_iter_next(rl->identity_map, iter);
3805 iter = digestmap_iter_init(rl->desc_digest_map);
3806 while (!digestmap_iter_done(iter)) {
3807 const char *d;
3808 void *_sd;
3809 signed_descriptor_t *sd;
3810 digestmap_iter_get(iter, &d, &_sd);
3811 sd = _sd;
3812 tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
3813 iter = digestmap_iter_next(rl->desc_digest_map, iter);
3817 /** Allocate and return a new string representing the contact info
3818 * and platform string for <b>router</b>,
3819 * surrounded by quotes and using standard C escapes.
3821 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
3822 * thread. Also, each call invalidates the last-returned value, so don't
3823 * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
3825 const char *
3826 esc_router_info(routerinfo_t *router)
3828 static char *info;
3829 char *esc_contact, *esc_platform;
3830 size_t len;
3831 if (info)
3832 tor_free(info);
3834 esc_contact = esc_for_log(router->contact_info);
3835 esc_platform = esc_for_log(router->platform);
3837 len = strlen(esc_contact)+strlen(esc_platform)+32;
3838 info = tor_malloc(len);
3839 tor_snprintf(info, len, "Contact %s, Platform %s", esc_contact,
3840 esc_platform);
3841 tor_free(esc_contact);
3842 tor_free(esc_platform);
3844 return info;