Make new logging stuff work on windows; fix a couple of windows typos.
[tor.git] / src / or / routerlist.c
blob8bb8fbbdb2469479c72384487be4ee56639e0f14
1 /* Copyright 2001 Matej Pfajfar.
2 * Copyright 2001-2004 Roger Dingledine.
3 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
5 /* $Id$ */
6 const char routerlist_c_id[] = "$Id$";
8 /**
9 * \file routerlist.c
10 * \brief Code to
11 * maintain and access the global list of routerinfos for known
12 * servers.
13 **/
15 #include "or.h"
17 /****************************************************************************/
19 /* static function prototypes */
20 static routerinfo_t *router_pick_directory_server_impl(int requireother,
21 int fascistfirewall,
22 int for_v2_directory);
23 static trusted_dir_server_t *router_pick_trusteddirserver_impl(
24 int need_v1_support, int requireother, int fascistfirewall);
25 static void mark_all_trusteddirservers_up(void);
26 static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
27 static int router_nickname_matches(routerinfo_t *router, const char *nickname);
28 static void routerstatus_list_update_from_networkstatus(time_t now);
29 static void local_routerstatus_free(local_routerstatus_t *rs);
30 static void trusted_dir_server_free(trusted_dir_server_t *ds);
31 static void update_networkstatus_cache_downloads(time_t now);
32 static void update_networkstatus_client_downloads(time_t now);
33 static int routerdesc_digest_is_recognized(const char *identity,
34 const char *digest);
35 static void routerlist_assert_ok(routerlist_t *rl);
37 /****************************************************************************/
39 /** Global list of a trusted_dir_server_t object for each trusted directory
40 * server. */
41 static smartlist_t *trusted_dir_servers = NULL;
43 /** Global list of all of the routers that we know about. */
44 static routerlist_t *routerlist = NULL;
46 extern int has_fetched_directory; /* from main.c */
48 /** Global list of all of the current network_status documents that we know
49 * about. This list is kept sorted by published_on. */
50 static smartlist_t *networkstatus_list = NULL;
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 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 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;
145 /** Helper: return 1 iff the router log is so big we want to rebuild the
146 * store. */
147 static int
148 router_should_rebuild_store(void)
150 if (router_store_len > (1<<16))
151 return router_journal_len > router_store_len / 2;
152 else
153 return router_journal_len > (1<<15);
156 /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
157 * journal. */
158 static int
159 router_append_to_journal(const char *s, size_t len)
161 or_options_t *options = get_options();
162 size_t fname_len = strlen(options->DataDirectory)+32;
163 char *fname = tor_malloc(len);
165 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
166 options->DataDirectory);
168 if (!len)
169 len = strlen(s);
171 if (append_bytes_to_file(fname, s, len, 0)) {
172 warn(LD_FS, "Unable to store router descriptor");
173 tor_free(fname);
174 return -1;
177 tor_free(fname);
178 router_journal_len += len;
179 return 0;
182 /** If the journal is too long, or if <b>force</b> is true, then atomically
183 * replace the router store with the routers currently in our routerlist, and
184 * clear the journal. Return 0 on success, -1 on failure.
186 static int
187 router_rebuild_store(int force)
189 size_t len = 0;
190 or_options_t *options;
191 size_t fname_len;
192 smartlist_t *chunk_list = NULL;
193 char *fname = NULL;
194 int r = -1, i;
196 if (!force && !router_should_rebuild_store())
197 return 0;
198 if (!routerlist)
199 return 0;
201 /* Don't save deadweight. */
202 routerlist_remove_old_routers();
204 options = get_options();
205 fname_len = strlen(options->DataDirectory)+32;
206 fname = tor_malloc(fname_len);
207 tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
208 chunk_list = smartlist_create();
210 for (i = 0; i < 2; ++i) {
211 smartlist_t *lst = (i == 0) ? routerlist->old_routers : routerlist->routers;
212 SMARTLIST_FOREACH(lst, void *, ptr,
214 signed_descriptor_t *sd = (i==0) ?
215 ((signed_descriptor_t*)ptr): &((routerinfo_t*)ptr)->cache_info;
216 sized_chunk_t *c;
217 if (!sd->signed_descriptor) {
218 warn(LD_BUG, "Bug! No descriptor stored for router.");
219 goto done;
221 c = tor_malloc(sizeof(sized_chunk_t));
222 c->bytes = sd->signed_descriptor;
223 c->len = sd->signed_descriptor_len;
224 smartlist_add(chunk_list, c);
227 if (write_chunks_to_file(fname, chunk_list, 0)<0) {
228 warn(LD_FS, "Error writing router store to disk.");
229 goto done;
232 tor_snprintf(fname, fname_len, "%s/cached-routers.new",
233 options->DataDirectory);
235 write_str_to_file(fname, "", 0);
237 r = 0;
238 router_store_len = len;
239 router_journal_len = 0;
240 done:
241 tor_free(fname);
242 if (chunk_list) {
243 SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
244 smartlist_free(chunk_list);
246 return r;
249 /* Load all cached router descriptors from the store. Return 0 on success and
250 * -1 on failure.
253 router_reload_router_list(void)
255 or_options_t *options = get_options();
256 size_t fname_len = strlen(options->DataDirectory)+32;
257 char *fname = tor_malloc(fname_len);
258 struct stat st;
259 int j;
261 if (!routerlist)
262 router_get_routerlist(); /* mallocs and inits it in place */
264 router_journal_len = router_store_len = 0;
266 for (j = 0; j < 2; ++j) {
267 char *contents;
268 tor_snprintf(fname, fname_len,
269 (j==0)?"%s/cached-routers":"%s/cached-routers.new",
270 options->DataDirectory);
271 contents = read_file_to_str(fname, 0);
272 if (contents) {
273 stat(fname, &st);
274 if (j==0)
275 router_store_len = st.st_size;
276 else
277 router_journal_len = st.st_size;
278 router_load_routers_from_string(contents, 1, NULL);
279 tor_free(contents);
282 tor_free(fname);
284 /* Don't cache expired routers. */
285 routerlist_remove_old_routers();
287 if (router_journal_len) {
288 /* Always clear the journal on startup.*/
289 router_rebuild_store(1);
291 return 0;
294 /** Set *<b>outp</b> to a smartlist containing a list of
295 * trusted_dir_server_t * for all known trusted dirservers. Callers
296 * must not modify the list or its contents.
298 void
299 router_get_trusted_dir_servers(smartlist_t **outp)
301 if (!trusted_dir_servers)
302 trusted_dir_servers = smartlist_create();
304 *outp = trusted_dir_servers;
307 /** Try to find a running dirserver. If there are no running dirservers
308 * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
309 * set all the authoritative ones as running again, and pick one;
310 * if there are then no dirservers at all in our routerlist,
311 * reload the routerlist and try one last time. If for_runningrouters is
312 * true, then only pick a dirserver that can answer runningrouters queries
313 * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
314 * Other args are as in router_pick_directory_server_impl().
316 routerinfo_t *
317 router_pick_directory_server(int requireother,
318 int fascistfirewall,
319 int for_v2_directory,
320 int retry_if_no_servers)
322 routerinfo_t *choice;
324 if (!routerlist)
325 return NULL;
327 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
328 for_v2_directory);
329 if (choice || !retry_if_no_servers)
330 return choice;
332 info(LD_DIR,"No reachable router entries for dirservers. Trying them all again.");
333 /* mark all authdirservers as up again */
334 mark_all_trusteddirservers_up();
335 /* try again */
336 choice = router_pick_directory_server_impl(requireother, fascistfirewall,
337 for_v2_directory);
338 if (choice)
339 return choice;
341 info(LD_DIR,"Still no %s router entries. Reloading and trying again.",
342 firewall_is_fascist() ? "reachable" : "known");
343 has_fetched_directory=0; /* reset it */
344 if (router_reload_router_list()) {
345 return NULL;
347 /* give it one last try */
348 choice = router_pick_directory_server_impl(requireother, 0,
349 for_v2_directory);
350 return choice;
353 trusted_dir_server_t *
354 router_get_trusteddirserver_by_digest(const char *digest)
356 if (!trusted_dir_servers)
357 return NULL;
359 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
361 if (!memcmp(ds->digest, digest, DIGEST_LEN))
362 return ds;
365 return NULL;
368 /** Try to find a running trusted dirserver. If there are no running
369 * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
370 * set them all as running again, and try again.
371 * Other args are as in router_pick_trusteddirserver_impl().
373 trusted_dir_server_t *
374 router_pick_trusteddirserver(int need_v1_support,
375 int requireother,
376 int fascistfirewall,
377 int retry_if_no_servers)
379 trusted_dir_server_t *choice;
381 choice = router_pick_trusteddirserver_impl(need_v1_support,
382 requireother, fascistfirewall);
383 if (choice || !retry_if_no_servers)
384 return choice;
386 info(LD_DIR,"No trusted dirservers are reachable. Trying them all again.");
387 mark_all_trusteddirservers_up();
388 return router_pick_trusteddirserver_impl(need_v1_support,
389 requireother, fascistfirewall);
392 /** Pick a random running verified directory server/mirror from our
393 * routerlist.
394 * If <b>fascistfirewall</b> and we're not using a proxy,
395 * make sure the port we pick is allowed by options-\>firewallports.
396 * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
397 * choose a directory server new enough to support the v2 directory
398 * functionality.
400 static routerinfo_t *
401 router_pick_directory_server_impl(int requireother, int fascistfirewall,
402 int for_v2_directory)
404 routerinfo_t *result;
405 smartlist_t *sl;
407 if (!routerlist)
408 return NULL;
410 if (get_options()->HttpProxy)
411 fascistfirewall = 0;
413 /* Find all the running dirservers we know about. */
414 sl = smartlist_create();
415 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
417 if (!router->is_running || !router->dir_port || !router->is_verified)
418 continue;
419 if (requireother && router_is_me(router))
420 continue;
421 if (fascistfirewall) {
422 if (!fascist_firewall_allows_address(router->addr, router->dir_port))
423 continue;
425 /* Before 0.1.1.6-alpha, only trusted dirservers served status info.
426 * Before 0.1.1.7-alpha, retrieving nonexistent server IDs could bork
427 * the directory server.
429 if (for_v2_directory &&
430 !(tor_version_as_new_as(router->platform,"0.1.1.7-alpha") ||
431 router_digest_is_trusted_dir(router->cache_info.identity_digest)))
432 continue;
433 smartlist_add(sl, router);
436 result = smartlist_choose(sl);
437 smartlist_free(sl);
438 return result;
441 /** Choose randomly from among the trusted dirservers that are up.
442 * If <b>fascistfirewall</b> and we're not using a proxy,
443 * make sure the port we pick is allowed by options-\>firewallports.
444 * If <b>requireother</b>, it cannot be us. If <b>need_v1_support</b>, choose
445 * a trusted authority for the v1 directory system.
447 static trusted_dir_server_t *
448 router_pick_trusteddirserver_impl(int need_v1_support,
449 int requireother, int fascistfirewall)
451 smartlist_t *sl;
452 routerinfo_t *me;
453 trusted_dir_server_t *ds;
454 sl = smartlist_create();
455 me = router_get_my_routerinfo();
457 if (!trusted_dir_servers)
458 return NULL;
460 if (get_options()->HttpProxy)
461 fascistfirewall = 0;
463 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
465 if (!d->is_running) continue;
466 if (need_v1_support && !d->supports_v1_protocol)
467 continue;
468 if (requireother && me && router_digest_is_me(d->digest))
469 continue;
470 if (fascistfirewall) {
471 if (!fascist_firewall_allows_address(d->addr, d->dir_port))
472 continue;
474 smartlist_add(sl, d);
477 ds = smartlist_choose(sl);
478 smartlist_free(sl);
479 return ds;
482 /** Go through and mark the authoritative dirservers as up. */
483 static void
484 mark_all_trusteddirservers_up(void)
486 if (routerlist) {
487 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
488 if (router_digest_is_trusted_dir(router->cache_info.identity_digest) &&
489 router->dir_port > 0) {
490 router->is_running = 1;
493 if (trusted_dir_servers) {
494 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
496 dir->is_running = 1;
497 dir->n_networkstatus_failures = 0;
500 last_networkstatus_download_attempted = 0;
503 /** Reset all internal variables used to count failed downloads of network
504 * status objects. */
505 void
506 router_reset_status_download_failures(void)
508 mark_all_trusteddirservers_up();
511 /** Return 0 if \\exists an authoritative dirserver that's currently
512 * thought to be running, else return 1.
515 all_trusted_directory_servers_down(void)
517 if (!trusted_dir_servers)
518 return 1;
519 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
520 if (dir->is_running) return 0);
521 return 1;
524 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
525 * This is used to make sure we don't pick siblings in a single path.
527 void
528 routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
530 routerinfo_t *r;
531 config_line_t *cl;
533 if (!router->declared_family)
534 return;
536 /* Add every r such that router declares familyness with r, and r
537 * declares familyhood with router. */
538 SMARTLIST_FOREACH(router->declared_family, const char *, n,
540 if (!(r = router_get_by_nickname(n, 0)))
541 continue;
542 if (!r->declared_family)
543 continue;
544 SMARTLIST_FOREACH(r->declared_family, const char *, n2,
546 if (router_nickname_matches(router, n2))
547 smartlist_add(sl, r);
551 /* If the user declared any families locally, honor those too. */
552 for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
553 if (router_nickname_is_in_list(router, cl->value)) {
554 add_nickname_list_to_smartlist(sl, cl->value, 1, 1);
559 /** Given a comma-and-whitespace separated list of nicknames, see which
560 * nicknames in <b>list</b> name routers in our routerlist that are
561 * currently running. Add the routerinfos for those routers to <b>sl</b>.
563 void
564 add_nickname_list_to_smartlist(smartlist_t *sl, const char *list, int warn_if_down, int warn_if_unnamed)
566 routerinfo_t *router;
567 smartlist_t *nickname_list;
569 if (!list)
570 return; /* nothing to do */
571 tor_assert(sl);
573 nickname_list = smartlist_create();
574 if (!warned_nicknames)
575 warned_nicknames = smartlist_create();
577 smartlist_split_string(nickname_list, list, ",",
578 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
580 SMARTLIST_FOREACH(nickname_list, const char *, nick, {
581 int warned;
582 if (!is_legal_nickname_or_hexdigest(nick)) {
583 warn(LD_CONFIG, "Nickname %s is misformed; skipping", nick);
584 continue;
586 router = router_get_by_nickname(nick, warn_if_unnamed);
587 warned = smartlist_string_isin(warned_nicknames, nick);
588 if (router) {
589 if (router->is_running) {
590 smartlist_add(sl,router);
591 if (warned)
592 smartlist_string_remove(warned_nicknames, nick);
593 } else {
594 if (!warned) {
595 log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG, LD_CONFIG,
596 "Nickname list includes '%s' which is known but down.",nick);
597 smartlist_add(warned_nicknames, tor_strdup(nick));
600 } else {
601 if (!warned) {
602 log_fn(has_fetched_directory ? LOG_WARN : LOG_INFO, LD_CONFIG,
603 "Nickname list includes '%s' which isn't a known router.",nick);
604 smartlist_add(warned_nicknames, tor_strdup(nick));
608 SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
609 smartlist_free(nickname_list);
612 /** Return 1 iff any member of the comma-separated list <b>list</b> is an
613 * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
615 static int
616 router_nickname_is_in_list(routerinfo_t *router, const char *list)
618 smartlist_t *nickname_list;
619 int v = 0;
621 if (!list)
622 return 0; /* definitely not */
623 tor_assert(router);
625 nickname_list = smartlist_create();
626 smartlist_split_string(nickname_list, list, ",",
627 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
628 SMARTLIST_FOREACH(nickname_list, const char *, cp,
629 if (router_nickname_matches(router, cp)) {v=1;break;});
630 SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
631 smartlist_free(nickname_list);
632 return v;
635 /** Add every router from our routerlist that is currently running to
636 * <b>sl</b>.
638 static void
639 router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_unverified,
640 int need_uptime, int need_capacity)
642 if (!routerlist)
643 return;
645 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
647 if (router->is_running &&
648 (router->is_verified ||
649 (allow_unverified &&
650 !router_is_unreliable(router, need_uptime, need_capacity)))) {
651 /* If it's running, and either it's verified or we're ok picking
652 * unverified routers and this one is suitable.
654 smartlist_add(sl, router);
659 /** Look through the routerlist until we find a router that has my key.
660 Return it. */
661 routerinfo_t *
662 routerlist_find_my_routerinfo(void)
664 if (!routerlist)
665 return NULL;
667 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
669 if (router_is_me(router))
670 return router;
672 return NULL;
675 /** Find a router that's up, that has this IP address, and
676 * that allows exit to this address:port, or return NULL if there
677 * isn't a good one.
679 routerinfo_t *
680 router_find_exact_exit_enclave(const char *address, uint16_t port)
682 uint32_t addr;
683 struct in_addr in;
685 if (!tor_inet_aton(address, &in))
686 return NULL; /* it's not an IP already */
687 addr = ntohl(in.s_addr);
689 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
691 if (router->is_running &&
692 router->addr == addr &&
693 router_compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
694 ADDR_POLICY_ACCEPTED)
695 return router;
697 return NULL;
700 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
701 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
702 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
703 * bandwidth.
706 router_is_unreliable(routerinfo_t *router, int need_uptime, int need_capacity)
708 if (need_uptime && router->uptime < ROUTER_REQUIRED_MIN_UPTIME)
709 return 1;
710 if (need_capacity && router->bandwidthcapacity < ROUTER_REQUIRED_MIN_BANDWIDTH)
711 return 1;
712 return 0;
715 /** Remove from routerlist <b>sl</b> all routers who have a low uptime. */
716 static void
717 routerlist_sl_remove_unreliable_routers(smartlist_t *sl)
719 int i;
720 routerinfo_t *router;
722 for (i = 0; i < smartlist_len(sl); ++i) {
723 router = smartlist_get(sl, i);
724 if (router_is_unreliable(router, 1, 0)) {
725 // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
726 // router->nickname);
727 smartlist_del(sl, i--);
732 #define MAX_BELIEVABLE_BANDWIDTH 2000000 /* 2 MB/sec */
734 /** Choose a random element of router list <b>sl</b>, weighted by
735 * the advertised bandwidth of each router.
737 routerinfo_t *
738 routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
740 int i;
741 routerinfo_t *router;
742 smartlist_t *bandwidths;
743 uint32_t this_bw, tmp, total_bw=0, rand_bw;
744 uint32_t *p;
746 /* First count the total bandwidth weight, and make a smartlist
747 * of each value. */
748 bandwidths = smartlist_create();
749 for (i = 0; i < smartlist_len(sl); ++i) {
750 router = smartlist_get(sl, i);
751 this_bw = (router->bandwidthcapacity < router->bandwidthrate) ?
752 router->bandwidthcapacity : router->bandwidthrate;
753 /* if they claim something huge, don't believe it */
754 if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
755 this_bw = MAX_BELIEVABLE_BANDWIDTH;
756 p = tor_malloc(sizeof(uint32_t));
757 *p = this_bw;
758 smartlist_add(bandwidths, p);
759 total_bw += this_bw;
761 if (!total_bw) {
762 SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
763 smartlist_free(bandwidths);
764 return smartlist_choose(sl);
766 /* Second, choose a random value from the bandwidth weights. */
767 rand_bw = crypto_rand_int(total_bw);
768 /* Last, count through sl until we get to the element we picked */
769 tmp = 0;
770 for (i=0; ; i++) {
771 tor_assert(i < smartlist_len(sl));
772 p = smartlist_get(bandwidths, i);
773 tmp += *p;
774 if (tmp >= rand_bw)
775 break;
777 SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
778 smartlist_free(bandwidths);
779 return (routerinfo_t *)smartlist_get(sl, i);
782 /** Return a random running router from the routerlist. If any node
783 * named in <b>preferred</b> is available, pick one of those. Never
784 * pick a node named in <b>excluded</b>, or whose routerinfo is in
785 * <b>excludedsmartlist</b>, even if they are the only nodes
786 * available. If <b>strict</b> is true, never pick any node besides
787 * those in <b>preferred</b>.
788 * If <b>need_uptime</b> is non-zero, don't return a router with less
789 * than a minimum uptime.
790 * If <b>need_capacity</b> is non-zero, weight your choice by the
791 * advertised capacity of each router.
793 routerinfo_t *
794 router_choose_random_node(const char *preferred,
795 const char *excluded,
796 smartlist_t *excludedsmartlist,
797 int need_uptime, int need_capacity,
798 int allow_unverified, int strict)
800 smartlist_t *sl, *excludednodes;
801 routerinfo_t *choice;
803 excludednodes = smartlist_create();
804 add_nickname_list_to_smartlist(excludednodes,excluded,0,1);
806 /* Try the preferred nodes first. Ignore need_uptime and need_capacity,
807 * since the user explicitly asked for these nodes. */
808 sl = smartlist_create();
809 add_nickname_list_to_smartlist(sl,preferred,1,1);
810 smartlist_subtract(sl,excludednodes);
811 if (excludedsmartlist)
812 smartlist_subtract(sl,excludedsmartlist);
813 choice = smartlist_choose(sl);
814 smartlist_free(sl);
815 if (!choice && !strict) {
816 /* Then give up on our preferred choices: any node
817 * will do that has the required attributes. */
818 sl = smartlist_create();
819 router_add_running_routers_to_smartlist(sl, allow_unverified,
820 need_uptime, need_capacity);
821 smartlist_subtract(sl,excludednodes);
822 if (excludedsmartlist)
823 smartlist_subtract(sl,excludedsmartlist);
824 if (need_uptime)
825 routerlist_sl_remove_unreliable_routers(sl);
826 if (need_capacity)
827 choice = routerlist_sl_choose_by_bandwidth(sl);
828 else
829 choice = smartlist_choose(sl);
830 smartlist_free(sl);
832 smartlist_free(excludednodes);
833 if (!choice)
834 warn(LD_CIRC,"No available nodes when trying to choose node. Failing.");
835 return choice;
838 /** Return true iff the digest of <b>router</b>'s identity key,
839 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
840 * optionally prefixed with a single dollar sign). Return false if
841 * <b>hexdigest</b> is malformed, or it doesn't match. */
842 static INLINE int
843 router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
845 char digest[DIGEST_LEN];
846 tor_assert(hexdigest);
847 if (hexdigest[0] == '$')
848 ++hexdigest;
850 /* XXXXNM Any place that uses this inside a loop could probably do better. */
851 if (strlen(hexdigest) != HEX_DIGEST_LEN ||
852 base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
853 return 0;
854 return (!memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN));
857 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
858 * (case-insensitive), or if <b>router's</b> identity key digest
859 * matches a hexadecimal value stored in <b>nickname</b>. Return
860 * false otherwise. */
861 static int
862 router_nickname_matches(routerinfo_t *router, const char *nickname)
864 if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
865 return 1;
866 return router_hex_digest_matches(router, nickname);
869 /** Return the router in our routerlist whose (case-insensitive)
870 * nickname or (case-sensitive) hexadecimal key digest is
871 * <b>nickname</b>. Return NULL if no such router is known.
873 routerinfo_t *
874 router_get_by_nickname(const char *nickname, int warn_if_unnamed)
876 int maybedigest;
877 char digest[DIGEST_LEN];
878 routerinfo_t *best_match=NULL;
879 int n_matches = 0;
881 tor_assert(nickname);
882 if (!routerlist)
883 return NULL;
884 if (nickname[0] == '$')
885 return router_get_by_hexdigest(nickname);
886 if (server_mode(get_options()) &&
887 !strcasecmp(nickname, get_options()->Nickname))
888 return router_get_my_routerinfo();
890 maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
891 (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
893 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
895 if (!strcasecmp(router->nickname, nickname)) {
896 if (router->is_named)
897 return router;
898 else {
899 ++n_matches;
900 best_match = router;
902 } else if (maybedigest &&
903 !memcmp(digest, router->cache_info.identity_digest, DIGEST_LEN)) {
904 return router;
908 if (best_match) {
909 if (warn_if_unnamed && n_matches > 1) {
910 smartlist_t *fps = smartlist_create();
911 int any_unwarned = 0;
912 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
914 local_routerstatus_t *rs;
915 char *desc;
916 size_t dlen;
917 char fp[HEX_DIGEST_LEN+1];
918 if (strcasecmp(router->nickname, nickname))
919 continue;
920 rs=router_get_combined_status_by_digest(router->cache_info.identity_digest);
921 if (!rs->name_lookup_warned) {
922 rs->name_lookup_warned = 1;
923 any_unwarned = 1;
925 base16_encode(fp, sizeof(fp), router->cache_info.identity_digest, DIGEST_LEN);
926 dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
927 desc = tor_malloc(dlen);
928 tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
929 fp, router->address, router->or_port);
930 smartlist_add(fps, desc);
932 if (any_unwarned) {
933 char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
934 warn(LD_CONFIG, "There are multiple matches for the nickname \"%s\","
935 " but none is listed as named by the directory authories. "
936 "Choosing one arbitrarily. If you meant one in particular, "
937 "you should say %s.", nickname, alternatives);
938 tor_free(alternatives);
940 SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
941 smartlist_free(fps);
942 } else if (warn_if_unnamed) {
943 local_routerstatus_t *rs =
944 router_get_combined_status_by_digest(best_match->cache_info.identity_digest);
945 if (rs && !rs->name_lookup_warned) {
946 char fp[HEX_DIGEST_LEN+1];
947 base16_encode(fp, sizeof(fp), best_match->cache_info.identity_digest, DIGEST_LEN);
948 warn(LD_CONFIG, "You specified a server \"%s\" by name, but the "
949 "directory authorities do not have a listing for this name. "
950 "To make sure you get the same server in the future, refer to "
951 "it by key, as \"$%s\".", nickname, fp);
952 rs->name_lookup_warned = 1;
955 return best_match;
958 return NULL;
961 /** Return true iff <b>digest</b> is the digest of the identity key of
962 * a trusted directory. */
964 router_digest_is_trusted_dir(const char *digest)
966 if (!trusted_dir_servers)
967 return 0;
968 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
969 if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
970 return 0;
973 /** Return the router in our routerlist whose hexadecimal key digest
974 * is <b>hexdigest</b>. Return NULL if no such router is known. */
975 routerinfo_t *
976 router_get_by_hexdigest(const char *hexdigest)
978 char digest[DIGEST_LEN];
980 tor_assert(hexdigest);
981 if (!routerlist)
982 return NULL;
983 if (hexdigest[0]=='$')
984 ++hexdigest;
985 if (strlen(hexdigest) != HEX_DIGEST_LEN ||
986 base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
987 return NULL;
989 return router_get_by_digest(digest);
992 /** Return the router in our routerlist whose 20-byte key digest
993 * is <b>digest</b>. Return NULL if no such router is known. */
994 routerinfo_t *
995 router_get_by_digest(const char *digest)
997 tor_assert(digest);
999 if (!routerlist) return NULL;
1001 // routerlist_assert_ok(routerlist);
1003 return digestmap_get(routerlist->identity_map, digest);
1006 /** Return the router in our routerlist whose 20-byte descriptor
1007 * is <b>digest</b>. Return NULL if no such router is known. */
1008 signed_descriptor_t *
1009 router_get_by_descriptor_digest(const char *digest)
1011 tor_assert(digest);
1013 if (!routerlist) return NULL;
1015 return digestmap_get(routerlist->desc_digest_map, digest);
1018 /** Return the current list of all known routers. */
1019 routerlist_t *
1020 router_get_routerlist(void)
1022 if (!routerlist) {
1023 routerlist = tor_malloc_zero(sizeof(routerlist_t));
1024 routerlist->routers = smartlist_create();
1025 routerlist->old_routers = smartlist_create();
1026 routerlist->identity_map = digestmap_new();
1027 routerlist->desc_digest_map = digestmap_new();
1029 return routerlist;
1032 /** Free all storage held by <b>router</b>. */
1033 void
1034 routerinfo_free(routerinfo_t *router)
1036 if (!router)
1037 return;
1039 tor_free(router->cache_info.signed_descriptor);
1040 tor_free(router->address);
1041 tor_free(router->nickname);
1042 tor_free(router->platform);
1043 tor_free(router->contact_info);
1044 if (router->onion_pkey)
1045 crypto_free_pk_env(router->onion_pkey);
1046 if (router->identity_pkey)
1047 crypto_free_pk_env(router->identity_pkey);
1048 if (router->declared_family) {
1049 SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
1050 smartlist_free(router->declared_family);
1052 addr_policy_free(router->exit_policy);
1053 tor_free(router);
1056 static void
1057 signed_descriptor_free(signed_descriptor_t *sd)
1059 tor_free(sd->signed_descriptor);
1060 tor_free(sd);
1063 /** frees ri. DOCDOC */
1064 static signed_descriptor_t *
1065 signed_descriptor_from_routerinfo(routerinfo_t *ri)
1067 signed_descriptor_t *sd = tor_malloc_zero(sizeof(signed_descriptor_t));
1068 memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
1069 ri->cache_info.signed_descriptor = NULL;
1070 routerinfo_free(ri);
1071 return sd;
1074 /** Allocate a fresh copy of <b>router</b> */
1075 routerinfo_t *
1076 routerinfo_copy(const routerinfo_t *router)
1078 routerinfo_t *r;
1079 addr_policy_t **e, *tmp;
1081 r = tor_malloc(sizeof(routerinfo_t));
1082 memcpy(r, router, sizeof(routerinfo_t));
1084 r->address = tor_strdup(r->address);
1085 r->nickname = tor_strdup(r->nickname);
1086 r->platform = tor_strdup(r->platform);
1087 if (r->cache_info.signed_descriptor)
1088 r->cache_info.signed_descriptor = tor_strdup(r->cache_info.signed_descriptor);
1089 if (r->onion_pkey)
1090 r->onion_pkey = crypto_pk_dup_key(r->onion_pkey);
1091 if (r->identity_pkey)
1092 r->identity_pkey = crypto_pk_dup_key(r->identity_pkey);
1093 e = &r->exit_policy;
1094 while (*e) {
1095 tmp = tor_malloc(sizeof(addr_policy_t));
1096 memcpy(tmp,*e,sizeof(addr_policy_t));
1097 *e = tmp;
1098 (*e)->string = tor_strdup((*e)->string);
1099 e = & ((*e)->next);
1101 if (r->declared_family) {
1102 r->declared_family = smartlist_create();
1103 SMARTLIST_FOREACH(router->declared_family, const char *, s,
1104 smartlist_add(r->declared_family, tor_strdup(s)));
1106 return r;
1109 /** Free all storage held by a routerlist <b>rl</b> */
1110 void
1111 routerlist_free(routerlist_t *rl)
1113 tor_assert(rl);
1114 digestmap_free(rl->identity_map, NULL);
1115 digestmap_free(rl->desc_digest_map, NULL);
1116 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
1117 routerinfo_free(r));
1118 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
1119 signed_descriptor_free(sd));
1120 smartlist_free(rl->routers);
1121 smartlist_free(rl->old_routers);
1122 tor_free(rl);
1125 static INLINE int
1126 _routerlist_find_elt(smartlist_t *sl, void *ri, int idx)
1128 if (idx < 0 || smartlist_get(sl, idx) != ri) {
1129 idx = -1;
1130 SMARTLIST_FOREACH(sl, routerinfo_t *, r,
1131 if (r == ri) {
1132 idx = r_sl_idx;
1133 break;
1136 return idx;
1139 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1140 * as needed. */
1141 static void
1142 routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
1144 digestmap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
1145 digestmap_set(rl->desc_digest_map, ri->cache_info.signed_descriptor_digest,
1146 &(ri->cache_info));
1147 smartlist_add(rl->routers, ri);
1148 // routerlist_assert_ok(rl);
1151 static void
1152 routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
1154 if (get_options()->DirPort) {
1155 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
1156 digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1157 smartlist_add(rl->old_routers, sd);
1158 } else {
1159 routerinfo_free(ri);
1161 // routerlist_assert_ok(rl);
1164 /** Remove an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1165 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
1166 * idx) == ri, we don't need to do a linear search over the list to decide
1167 * which to remove. We fill the gap in rl-&gt;routers with a later element in
1168 * the list, if any exists. <b>ri</b> is freed. */
1169 void
1170 routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int idx, int make_old)
1172 routerinfo_t *ri_tmp;
1173 idx = _routerlist_find_elt(rl->routers, ri, idx);
1174 if (idx < 0)
1175 return;
1176 smartlist_del(rl->routers, idx);
1177 ri_tmp = digestmap_remove(rl->identity_map, ri->cache_info.identity_digest);
1178 tor_assert(ri_tmp == ri);
1179 if (make_old && get_options()->DirPort) {
1180 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
1181 smartlist_add(rl->old_routers, sd);
1182 digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1183 } else {
1184 ri_tmp = digestmap_remove(rl->desc_digest_map,
1185 ri->cache_info.signed_descriptor_digest);
1186 tor_assert(ri_tmp == ri);
1187 routerinfo_free(ri);
1189 // routerlist_assert_ok(rl);
1192 static void
1193 routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
1195 signed_descriptor_t *sd_tmp;
1196 idx = _routerlist_find_elt(rl->old_routers, sd, idx);
1197 if (idx < 0)
1198 return;
1199 smartlist_del(rl->old_routers, idx);
1200 sd_tmp = digestmap_remove(rl->desc_digest_map,
1201 sd->signed_descriptor_digest);
1202 tor_assert(sd_tmp == sd);
1203 signed_descriptor_free(sd);
1204 routerlist_assert_ok(rl);
1207 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
1208 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
1209 * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
1210 * search over the list to decide which to remove. We put ri_new in the same
1211 * index as ri_old, if possible. ri is freed as appropriate. */
1212 static void
1213 routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
1214 routerinfo_t *ri_new, int idx, int make_old)
1216 tor_assert(ri_old != ri_new);
1217 idx = _routerlist_find_elt(rl->routers, ri_old, idx);
1218 if (idx >= 0) {
1219 smartlist_set(rl->routers, idx, ri_new);
1220 } else {
1221 warn(LD_BUG, "Appending entry from routerlist_replace.");
1222 routerlist_insert(rl, ri_new);
1223 return;
1225 if (memcmp(ri_old->cache_info.identity_digest, ri_new->cache_info.identity_digest, DIGEST_LEN)) {
1226 /* digests don't match; digestmap_set won't replace */
1227 digestmap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
1229 digestmap_set(rl->identity_map, ri_new->cache_info.identity_digest, ri_new);
1230 digestmap_set(rl->desc_digest_map, ri_new->cache_info.signed_descriptor_digest, &(ri_new->cache_info));
1232 if (make_old && get_options()->DirPort) {
1233 signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
1234 smartlist_add(rl->old_routers, sd);
1235 digestmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1236 } else {
1237 if (memcmp(ri_old->cache_info.signed_descriptor_digest,
1238 ri_new->cache_info.signed_descriptor_digest,
1239 DIGEST_LEN)) {
1240 /* digests don't match; digestmap_set didn't replace */
1241 digestmap_remove(rl->desc_digest_map, ri_old->cache_info.signed_descriptor_digest);
1243 routerinfo_free(ri_old);
1245 // routerlist_assert_ok(rl);
1248 /** Free all memory held by the routerlist module. */
1249 void
1250 routerlist_free_all(void)
1252 if (routerlist)
1253 routerlist_free(routerlist);
1254 routerlist = NULL;
1255 if (warned_nicknames) {
1256 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1257 smartlist_free(warned_nicknames);
1258 warned_nicknames = NULL;
1260 if (warned_conflicts) {
1261 SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
1262 smartlist_free(warned_conflicts);
1263 warned_conflicts = NULL;
1265 if (trusted_dir_servers) {
1266 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
1267 trusted_dir_server_free(ds));
1268 smartlist_free(trusted_dir_servers);
1269 trusted_dir_servers = NULL;
1271 if (networkstatus_list) {
1272 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
1273 networkstatus_free(ns));
1274 smartlist_free(networkstatus_list);
1275 networkstatus_list = NULL;
1277 if (routerstatus_list) {
1278 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
1279 local_routerstatus_free(rs));
1280 smartlist_free(routerstatus_list);
1281 routerstatus_list = NULL;
1285 /** Free all storage held by the routerstatus object <b>rs</b>. */
1286 void
1287 routerstatus_free(routerstatus_t *rs)
1289 tor_free(rs);
1292 /** Free all storage held by the local_routerstatus object <b>rs</b>. */
1293 static void
1294 local_routerstatus_free(local_routerstatus_t *rs)
1296 tor_free(rs);
1299 /** Free all storage held by the networkstatus object <b>ns</b>. */
1300 void
1301 networkstatus_free(networkstatus_t *ns)
1303 tor_free(ns->source_address);
1304 tor_free(ns->contact);
1305 if (ns->signing_key)
1306 crypto_free_pk_env(ns->signing_key);
1307 tor_free(ns->client_versions);
1308 tor_free(ns->server_versions);
1309 if (ns->entries) {
1310 SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs, routerstatus_free(rs));
1311 smartlist_free(ns->entries);
1313 tor_free(ns);
1316 /** Forget that we have issued any router-related warnings, so that we'll
1317 * warn again if we see the same errors. */
1318 void
1319 routerlist_reset_warnings(void)
1321 if (!warned_nicknames)
1322 warned_nicknames = smartlist_create();
1323 SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1324 smartlist_clear(warned_nicknames); /* now the list is empty. */
1326 if (!warned_conflicts)
1327 warned_conflicts = smartlist_create();
1328 SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
1329 smartlist_clear(warned_conflicts); /* now the list is empty. */
1331 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
1332 rs->name_lookup_warned = 0);
1334 have_warned_about_unverified_status = 0;
1335 have_warned_about_old_version = 0;
1336 have_warned_about_new_version = 0;
1339 /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
1340 void
1341 router_mark_as_down(const char *digest)
1343 routerinfo_t *router;
1344 tor_assert(digest);
1346 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
1347 if (!memcmp(d->digest, digest, DIGEST_LEN))
1348 d->is_running = 0);
1350 router = router_get_by_digest(digest);
1351 if (!router) /* we don't seem to know about him in the first place */
1352 return;
1353 debug(LD_DIR,"Marking router '%s' as down.",router->nickname);
1354 if (router_is_me(router) && !we_are_hibernating())
1355 warn(LD_NET, "We just marked ourself as down. Are your external addresses reachable?");
1356 router->is_running = 0;
1359 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
1360 * older entries (if any) with the same key. Note: Callers should not hold
1361 * their pointers to <b>router</b> if this function fails; <b>router</b>
1362 * will either be inserted into the routerlist or freed.
1364 * Returns >= 0 if the router was added; less than 0 if it was not.
1366 * If we're returning non-zero, then assign to *<b>msg</b> a static string
1367 * describing the reason for not liking the routerinfo.
1369 * If the return value is less than -1, there was a problem with the
1370 * routerinfo. If the return value is equal to -1, then the routerinfo was
1371 * fine, but out-of-date. If the return value is equal to 1, the
1372 * routerinfo was accepted, but we should notify the generator of the
1373 * descriptor using the message *<b>msg</b>.
1375 * This function should be called *after*
1376 * routers_update_status_from_networkstatus; subsequently, you should call
1377 * router_rebuild_store and control_event_descriptors_changed.
1379 * XXXX never replace your own descriptor.
1382 router_add_to_routerlist(routerinfo_t *router, const char **msg,
1383 int from_cache)
1385 int i;
1386 char id_digest[DIGEST_LEN];
1387 int authdir = get_options()->AuthoritativeDir;
1388 int authdir_verified = 0;
1390 tor_assert(msg);
1392 if (!routerlist)
1393 router_get_routerlist();
1395 /* XXXX NM If this assert doesn't trigger, we should remove the id_digest
1396 * local. */
1397 crypto_pk_get_digest(router->identity_pkey, id_digest);
1398 tor_assert(!memcmp(id_digest, router->cache_info.identity_digest, DIGEST_LEN));
1400 /* Make sure that we haven't already got this exact descriptor. */
1401 if (digestmap_get(routerlist->desc_digest_map,
1402 router->cache_info.signed_descriptor_digest)) {
1403 info(LD_DIR, "Dropping descriptor that we already have for router '%s'",
1404 router->nickname);
1405 *msg = "Router descriptor was not new.";
1406 routerinfo_free(router);
1407 return -1;
1410 if (authdir) {
1411 if (authdir_wants_to_reject_router(router, msg)) {
1412 routerinfo_free(router);
1413 return -2;
1415 authdir_verified = router->is_verified;
1417 } else {
1418 if (! router->xx_is_recognized && !from_cache) {
1419 log_fn(LOG_WARN, "Dropping unrecognized descriptor for router '%s'",
1420 router->nickname);
1421 routerinfo_free(router);
1422 return -1;
1427 /* If we have a router with this name, and the identity key is the same,
1428 * choose the newer one. If the identity key has changed, drop the router.
1430 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
1431 routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
1432 if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
1433 if (router->cache_info.published_on <=
1434 old_router->cache_info.published_on) {
1435 /* Same key, but old */
1436 debug(LD_DIR, "Skipping not-new descriptor for router '%s'",
1437 router->nickname);
1438 routerlist_insert_old(routerlist, router);
1439 *msg = "Router descriptor was not new.";
1440 return -1;
1441 } else {
1442 /* Same key, new. */
1443 int unreachable = 0;
1444 debug(LD_DIR, "Replacing entry for router '%s/%s' [%s]",
1445 router->nickname, old_router->nickname,
1446 hex_str(id_digest,DIGEST_LEN));
1447 if (router->addr == old_router->addr &&
1448 router->or_port == old_router->or_port) {
1449 /* these carry over when the address and orport are unchanged.*/
1450 router->last_reachable = old_router->last_reachable;
1451 router->testing_since = old_router->testing_since;
1452 router->num_unreachable_notifications =
1453 old_router->num_unreachable_notifications;
1455 if (authdir &&
1456 dirserv_thinks_router_is_blatantly_unreachable(router, time(NULL))) {
1457 if (router->num_unreachable_notifications >= 3) {
1458 unreachable = 1;
1459 notice(LD_DIR, "Notifying server '%s' that it's unreachable. (ContactInfo '%s', platform '%s').",
1460 router->nickname, router->contact_info ? router->contact_info : "",
1461 router->platform ? router->platform : "");
1462 } else {
1463 info(LD_DIR,"'%s' may be unreachable -- the %d previous descriptors were thought to be unreachable.", router->nickname, router->num_unreachable_notifications);
1464 router->num_unreachable_notifications++;
1467 routerlist_replace(routerlist, old_router, router, i, 1);
1468 if (!from_cache)
1469 router_append_to_journal(router->cache_info.signed_descriptor,
1470 router->cache_info.signed_descriptor_len);
1471 directory_set_dirty();
1472 *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
1473 authdir_verified ? "Verified server updated" :
1474 "Unverified server updated. (Have you sent us your key fingerprint?)";
1475 return unreachable ? 1 : 0;
1477 } else if (!strcasecmp(router->nickname, old_router->nickname)) {
1478 /* nicknames match, keys don't. */
1479 if (router->is_named) {
1480 /* The new verified router replaces the old one; remove the
1481 * old one. And carry on to the end of the list, in case
1482 * there are more old unverified routers with this nickname
1484 /* mark-for-close connections using the old key, so we can
1485 * make new ones with the new key.
1487 connection_t *conn;
1488 while ((conn = connection_get_by_identity_digest(
1489 old_router->cache_info.identity_digest, CONN_TYPE_OR))) {
1490 // And LD_OR? XXXXNM
1491 info(LD_DIR,"Closing conn to router '%s'; there is now a named router with that name.",
1492 old_router->nickname);
1493 connection_mark_for_close(conn);
1495 routerlist_remove(routerlist, old_router, i--, 0);
1496 } else if (old_router->is_named) {
1497 /* Can't replace a verified router with an unverified one. */
1498 debug(LD_DIR, "Skipping unverified entry for verified router '%s'",
1499 router->nickname);
1500 routerinfo_free(router);
1501 *msg = "Already have named router with same nickname and different key.";
1502 return -2;
1506 /* We haven't seen a router with this name before. Add it to the end of
1507 * the list. */
1508 routerlist_insert(routerlist, router);
1509 if (!from_cache)
1510 router_append_to_journal(router->cache_info.signed_descriptor,
1511 router->cache_info.signed_descriptor_len);
1512 directory_set_dirty();
1513 return 0;
1516 #define MAX_DESCRIPTORS_PER_ROUTER 5
1518 static int
1519 _compare_old_routers_by_identity(const void **_a, const void **_b)
1521 int i;
1522 const signed_descriptor_t *r1 = *_a, *r2 = *_b;
1523 if ((i = memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
1524 return i;
1525 return r1->published_on - r2->published_on;
1528 struct duration_idx_t {
1529 int duration;
1530 int idx;
1531 int old;
1534 static int
1535 _compare_duration_idx(const void *_d1, const void *_d2)
1537 const struct duration_idx_t *d1 = _d1;
1538 const struct duration_idx_t *d2 = _d2;
1539 return d1->duration - d2->duration;
1542 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
1543 * must contain routerinfo_t with the same identity and with publication time
1544 * in ascending order. Remove members from this range until there are no more
1545 * than MAX_DESCRIPTORS_PER_ROUTER remaining. Start by removing the oldest
1546 * members from before <b>cutoff</b>, then remove members which were current
1547 * for the lowest amount of time. The order of members of old_routers at
1548 * indices <b>lo</b> or higher may be changed.
1550 static void
1551 routerlist_remove_old_cached_routers_with_id(time_t cutoff, int lo, int hi)
1553 int i, n = hi-lo+1, n_extra;
1554 int n_rmv = 0;
1555 struct duration_idx_t *lifespans;
1556 uint8_t *rmv;
1557 smartlist_t *lst = routerlist->old_routers;
1558 #if 1
1559 const char *ident;
1560 tor_assert(hi < smartlist_len(lst));
1561 tor_assert(lo <= hi);
1562 ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
1563 for (i = lo+1; i <= hi; ++i) {
1564 signed_descriptor_t *r = smartlist_get(lst, i);
1565 tor_assert(!memcmp(ident, r->identity_digest, DIGEST_LEN));
1567 #endif
1569 /* Check whether we need to do anything at all. */
1570 n_extra = n - MAX_DESCRIPTORS_PER_ROUTER;
1571 if (n_extra <= 0)
1572 return;
1574 lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
1575 rmv = tor_malloc_zero(sizeof(uint8_t)*n);
1576 /* Set lifespans to contain the lifespan and index of each server. */
1577 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
1578 for (i = lo; i <= hi; ++i) {
1579 signed_descriptor_t *r = smartlist_get(lst, i);
1580 signed_descriptor_t *r_next;
1581 lifespans[i-lo].idx = i;
1582 if (i < hi) {
1583 r_next = smartlist_get(lst, i+1);
1584 tor_assert(r->published_on <= r_next->published_on);
1585 lifespans[i-lo].duration = (r_next->published_on - r->published_on);
1586 } else {
1587 r_next = NULL;
1588 lifespans[i-lo].duration = INT_MAX;
1590 if (r->published_on < cutoff && n_rmv < n_extra) {
1591 ++n_rmv;
1592 lifespans[i-lo].old = 1;
1593 rmv[i-lo] = 1;
1597 if (n_rmv < n_extra) {
1599 * We aren't removing enough servers for being old. Sort lifespans by
1600 * the duration of liveness, and remove the ones we're not already going to
1601 * remove based on how long they were alive.
1603 qsort(lifespans, n, sizeof(struct duration_idx_t), _compare_duration_idx);
1604 for (i = 0; i < n && n_rmv < n_extra; ++i) {
1605 if (!lifespans[i].old) {
1606 rmv[lifespans[i].idx-lo] = 1;
1607 ++n_rmv;
1612 for (i = hi; i >= lo; --i) {
1613 if (rmv[i-lo])
1614 routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
1616 tor_free(rmv);
1617 tor_free(lifespans);
1620 /** Deactivate any routers from the routerlist that are more than
1621 * ROUTER_MAX_AGE seconds old; remove old routers from the list of
1622 * cached routers if we have too many.
1624 void
1625 routerlist_remove_old_routers(void)
1627 int i, hi=-1;
1628 const char *cur_id = NULL;
1629 time_t cutoff;
1630 routerinfo_t *router;
1631 if (!routerlist)
1632 return;
1634 cutoff = time(NULL) - ROUTER_MAX_AGE;
1635 /* Remove old members of routerlist->routers. */
1636 for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
1637 router = smartlist_get(routerlist->routers, i);
1638 if (router->cache_info.published_on <= cutoff) {
1639 /* Too old. Remove it. */
1640 info(LD_DIR, "Forgetting obsolete (too old) routerinfo for router '%s'",
1641 router->nickname);
1642 routerlist_remove(routerlist, router, i--, 1);
1646 /* Now we're looking at routerlist->old_routers. First, check whether
1647 * we have too many router descriptors, total. We're okay with having too
1648 * many for some given router, so long as the total number doesn't approach
1649 * MAX_DESCRIPTORS_PER_ROUTER*len(router).
1651 if (smartlist_len(routerlist->old_routers) <
1652 smartlist_len(routerlist->routers) * (MAX_DESCRIPTORS_PER_ROUTER - 1))
1653 return;
1655 smartlist_sort(routerlist->old_routers, _compare_old_routers_by_identity);
1657 /* Iterate through the list from back to front, so when we remove descriptors
1658 * we don't mess up groups we haven't gotten to. */
1659 for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
1660 signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
1661 if (!cur_id) {
1662 cur_id = r->identity_digest;
1663 hi = i;
1665 if (memcmp(cur_id, r->identity_digest, DIGEST_LEN)) {
1666 routerlist_remove_old_cached_routers_with_id(cutoff, i+1, hi);
1667 hi = i;
1670 if (hi>=0)
1671 routerlist_remove_old_cached_routers_with_id(cutoff, 0, hi);
1672 routerlist_assert_ok(routerlist);
1676 * Code to parse a single router descriptor and insert it into the
1677 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
1678 * descriptor was well-formed but could not be added; and 1 if the
1679 * descriptor was added.
1681 * If we don't add it and <b>msg</b> is not NULL, then assign to
1682 * *<b>msg</b> a static string describing the reason for refusing the
1683 * descriptor.
1685 * This is used only by the controller.
1688 router_load_single_router(const char *s, const char **msg)
1690 routerinfo_t *ri;
1691 smartlist_t *lst;
1692 tor_assert(msg);
1693 *msg = NULL;
1695 if (!(ri = router_parse_entry_from_string(s, NULL))) {
1696 warn(LD_DIR, "Error parsing router descriptor; dropping.");
1697 *msg = "Couldn't parse router descriptor.";
1698 return -1;
1700 if (router_is_me(ri)) {
1701 warn(LD_DIR, "Router's identity key matches mine; dropping.");
1702 *msg = "Router's identity key matches mine.";
1703 routerinfo_free(ri);
1704 return 0;
1707 lst = smartlist_create();
1708 smartlist_add(lst, ri);
1709 routers_update_status_from_networkstatus(lst, 0, 1);
1711 if (router_add_to_routerlist(ri, msg, 0)<0) {
1712 warn(LD_DIR, "Couldn't add router to list: %s Dropping.",
1713 *msg?*msg:"(No message).");
1714 /* we've already assigned to *msg now, and ri is already freed */
1715 smartlist_free(lst);
1716 return 0;
1717 } else {
1718 control_event_descriptors_changed(lst);
1719 smartlist_free(lst);
1720 debug(LD_DIR, "Added router to list");
1721 return 1;
1725 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
1726 * routers into our directory. If <b>from_cache</b> is false, the routers
1727 * have come from the network: cache them.
1729 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1730 * uppercased identity fingerprints. Do not update any router whose
1731 * fingerprint is not on the list; after updating a router, remove its
1732 * fingerprint from the list.
1734 void
1735 router_load_routers_from_string(const char *s, int from_cache,
1736 smartlist_t *requested_fingerprints)
1738 smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
1739 char fp[HEX_DIGEST_LEN+1];
1740 const char *msg;
1742 router_parse_list_from_string(&s, routers);
1744 routers_update_status_from_networkstatus(routers, !from_cache, from_cache);
1746 SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
1748 base16_encode(fp, sizeof(fp), ri->cache_info.identity_digest, DIGEST_LEN);
1749 if (requested_fingerprints) {
1750 if (smartlist_string_isin(requested_fingerprints, fp)) {
1751 smartlist_string_remove(requested_fingerprints, fp);
1752 } else {
1753 char *requested =
1754 smartlist_join_strings(requested_fingerprints," ",0,NULL);
1755 warn(LD_DIR, "We received a router descriptor with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
1756 tor_free(requested);
1757 routerinfo_free(ri);
1758 continue;
1762 if (router_add_to_routerlist(ri, &msg, from_cache) >= 0)
1763 smartlist_add(changed, ri);
1766 if (smartlist_len(changed))
1767 control_event_descriptors_changed(changed);
1769 routerlist_assert_ok(routerlist);
1770 router_rebuild_store(0);
1772 smartlist_free(routers);
1773 smartlist_free(changed);
1776 /** Helper: return a newly allocated string containing the name of the filename
1777 * where we plan to cache <b>ns</b>. */
1778 static char *
1779 networkstatus_get_cache_filename(const networkstatus_t *ns)
1781 const char *datadir = get_options()->DataDirectory;
1782 size_t len = strlen(datadir)+64;
1783 char fp[HEX_DIGEST_LEN+1];
1784 char *fn = tor_malloc(len+1);
1785 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
1786 tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
1787 return fn;
1790 /** Helper for smartlist_sort: Compare two networkstatus objects by
1791 * publication date. */
1792 static int
1793 _compare_networkstatus_published_on(const void **_a, const void **_b)
1795 const networkstatus_t *a = *_a, *b = *_b;
1796 if (a->published_on < b->published_on)
1797 return -1;
1798 else if (a->published_on > b->published_on)
1799 return 1;
1800 else
1801 return 0;
1804 /** How far in the future do we allow a network-status to get before removing
1805 * it? (seconds) */
1806 #define NETWORKSTATUS_ALLOW_SKEW (48*60*60)
1807 /** Given a string <b>s</b> containing a network status that we received at
1808 * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
1809 * store it, and put it into our cache is necessary.
1811 * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
1812 * own networkstatus_t (if we're a directory server).
1814 * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
1815 * cache.
1817 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1818 * uppercased identity fingerprints. Do not update any networkstatus whose
1819 * fingerprint is not on the list; after updating a networkstatus, remove its
1820 * fingerprint from the list.
1822 * Return 0 on success, -1 on failure.
1824 * Callers should make sure that routers_update_all_from_networkstatus() is
1825 * invoked after this function succeeds.
1828 router_set_networkstatus(const char *s, time_t arrived_at,
1829 networkstatus_source_t source, smartlist_t *requested_fingerprints)
1831 networkstatus_t *ns;
1832 int i, found;
1833 time_t now;
1834 int skewed = 0;
1835 trusted_dir_server_t *trusted_dir;
1836 char fp[HEX_DIGEST_LEN+1];
1837 char published[ISO_TIME_LEN+1];
1839 ns = networkstatus_parse_from_string(s);
1840 if (!ns) {
1841 warn(LD_DIR, "Couldn't parse network status.");
1842 return -1;
1844 if (!(trusted_dir=router_get_trusteddirserver_by_digest(ns->identity_digest))) {
1845 info(LD_DIR, "Network status was signed, but not by an authoritative directory we recognize.");
1846 networkstatus_free(ns);
1847 return -1;
1849 now = time(NULL);
1850 if (arrived_at > now)
1851 arrived_at = now;
1853 ns->received_on = arrived_at;
1855 format_iso_time(published, ns->published_on);
1857 if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
1858 warn(LD_GENERAL, "Network status from %s was published in the future (%s GMT). Somebody is skewed here: check your clock. Not caching.", trusted_dir->description, published);
1859 skewed = 1;
1862 if (!networkstatus_list)
1863 networkstatus_list = smartlist_create();
1865 if (source == NS_FROM_DIR && router_digest_is_me(ns->identity_digest)) {
1866 /* Don't replace our own networkstatus when we get it from somebody else. */
1867 networkstatus_free(ns);
1868 return 0;
1871 base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
1873 if (requested_fingerprints) {
1874 if (smartlist_string_isin(requested_fingerprints, fp)) {
1875 smartlist_string_remove(requested_fingerprints, fp);
1876 } else {
1877 char *requested = smartlist_join_strings(requested_fingerprints," ",0,NULL);
1878 warn(LD_DIR, "We received a network status with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
1879 tor_free(requested);
1880 return 0;
1884 if (source != NS_FROM_CACHE)
1885 trusted_dir->n_networkstatus_failures = 0;
1887 found = 0;
1888 for (i=0; i < smartlist_len(networkstatus_list); ++i) {
1889 networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
1891 if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
1892 if (!memcmp(old_ns->networkstatus_digest,
1893 ns->networkstatus_digest, DIGEST_LEN)) {
1894 /* Same one we had before. */
1895 networkstatus_free(ns);
1896 info(LD_DIR,
1897 "Not replacing network-status from %s (published %s); "
1898 "we already have it.",
1899 trusted_dir->description, published);
1900 if (old_ns->received_on < arrived_at) {
1901 if (source != NS_FROM_CACHE) {
1902 char *fn = networkstatus_get_cache_filename(old_ns);
1903 /* We use mtime to tell when it arrived, so update that. */
1904 touch_file(fn);
1905 tor_free(fn);
1907 old_ns->received_on = arrived_at;
1909 return 0;
1910 } else if (old_ns->published_on >= ns->published_on) {
1911 char old_published[ISO_TIME_LEN+1];
1912 format_iso_time(old_published, old_ns->published_on);
1913 info(LD_DIR,
1914 "Not replacing network-status from %s (published %s);"
1915 " we have a newer one (published %s) for this authority.",
1916 trusted_dir->description, published,
1917 old_published);
1918 networkstatus_free(ns);
1919 return 0;
1920 } else {
1921 networkstatus_free(old_ns);
1922 smartlist_set(networkstatus_list, i, ns);
1923 found = 1;
1924 break;
1929 if (!found)
1930 smartlist_add(networkstatus_list, ns);
1932 info(LD_DIR, "Setting networkstatus %s %s (published %s)",
1933 source == NS_FROM_CACHE?"cached from":
1934 (source==NS_FROM_DIR?"downloaded from":"generated for"),
1935 trusted_dir->description, published);
1936 networkstatus_list_has_changed = 1;
1938 smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
1940 if (source != NS_FROM_CACHE && !skewed) {
1941 char *fn = networkstatus_get_cache_filename(ns);
1942 if (write_str_to_file(fn, s, 0)<0) {
1943 notice(LD_FS, "Couldn't write cached network status to \"%s\"", fn);
1945 tor_free(fn);
1948 networkstatus_list_update_recent(now);
1950 if (get_options()->DirPort && !skewed)
1951 dirserv_set_cached_networkstatus_v2(s,
1952 ns->identity_digest,
1953 ns->published_on);
1955 return 0;
1958 /** How old do we allow a network-status to get before removing it completely? */
1959 #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
1960 /** Remove all very-old network_status_t objects from memory and from the
1961 * disk cache. */
1962 void
1963 networkstatus_list_clean(time_t now)
1965 int i;
1966 if (!networkstatus_list)
1967 return;
1969 for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
1970 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
1971 char *fname = NULL;;
1972 if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
1973 continue;
1974 /* Okay, this one is too old. Remove it from the list, and delete it
1975 * from the cache. */
1976 smartlist_del(networkstatus_list, i--);
1977 fname = networkstatus_get_cache_filename(ns);
1978 if (file_status(fname) == FN_FILE) {
1979 info(LD_DIR, "Removing too-old networkstatus in %s", fname);
1980 unlink(fname);
1982 tor_free(fname);
1983 if (get_options()->DirPort) {
1984 dirserv_set_cached_networkstatus_v2(NULL, ns->identity_digest, 0);
1986 networkstatus_free(ns);
1990 /** Helper for bsearching a list of routerstatus_t pointers.*/
1991 static int
1992 _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
1994 const char *key = _key;
1995 const routerstatus_t *rs = *_member;
1996 return memcmp(key, rs->identity_digest, DIGEST_LEN);
1999 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
2000 * NULL if none was found. */
2001 static routerstatus_t *
2002 networkstatus_find_entry(networkstatus_t *ns, const char *digest)
2004 return smartlist_bsearch(ns->entries, digest,
2005 _compare_digest_to_routerstatus_entry);
2008 /** Return the consensus view of the status of the router whose digest is
2009 * <b>digest</b>, or NULL if we don't know about any such router. */
2010 local_routerstatus_t *
2011 router_get_combined_status_by_digest(const char *digest)
2013 if (!routerstatus_list)
2014 return NULL;
2015 return smartlist_bsearch(routerstatus_list, digest,
2016 _compare_digest_to_routerstatus_entry);
2019 /** DOCDOC */
2020 static int
2021 routerdesc_digest_is_recognized(const char *identity, const char *digest)
2023 routerstatus_t *rs;
2024 if (!networkstatus_list)
2025 return 0;
2027 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2029 if (!(rs = networkstatus_find_entry(ns, identity)))
2030 continue;
2031 if (!memcmp(rs->descriptor_digest, digest, DIGEST_LEN))
2032 return 1;
2034 return 0;
2037 /* XXXX These should be configurable, perhaps? NM */
2038 #define AUTHORITY_NS_CACHE_INTERVAL 10*60
2039 #define NONAUTHORITY_NS_CACHE_INTERVAL 15*60
2040 /** We are a directory server, and so cache network_status documents.
2041 * Initiate downloads as needed to update them. For authorities, this means
2042 * asking each trusted directory for its network-status. For caches, this
2043 * means asking a random authority for all network-statuses.
2045 static void
2046 update_networkstatus_cache_downloads(time_t now)
2048 int authority = authdir_mode(get_options());
2049 int interval =
2050 authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
2052 if (last_networkstatus_download_attempted + interval >= now)
2053 return;
2054 if (!trusted_dir_servers)
2055 return;
2057 last_networkstatus_download_attempted = now;
2059 if (authority) {
2060 /* An authority launches a separate connection for everybody. */
2061 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2063 char resource[HEX_DIGEST_LEN+6];
2064 if (router_digest_is_me(ds->digest))
2065 continue;
2066 if (connection_get_by_type_addr_port_purpose(
2067 CONN_TYPE_DIR, ds->addr, ds->dir_port,
2068 DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
2069 /* We are already fetching this one. */
2070 continue;
2072 strlcpy(resource, "fp/", sizeof(resource));
2073 base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
2074 strlcat(resource, ".z", sizeof(resource));
2075 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,resource,1);
2077 } else {
2078 /* A non-authority cache launches one connection to a random authority. */
2079 /* (Check whether we're currently fetching network-status objects.) */
2080 if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
2081 DIR_PURPOSE_FETCH_NETWORKSTATUS))
2082 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
2086 /*XXXX Should these be configurable? NM*/
2087 /** How old (in seconds) can a network-status be before we try replacing it? */
2088 #define NETWORKSTATUS_MAX_VALIDITY (48*60*60)
2089 /** How long (in seconds) does a client wait after getting a network status
2090 * before downloading the next in sequence? */
2091 #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
2092 /* How many times do we allow a networkstatus download to fail before we
2093 * assume that the authority isn't publishing? */
2094 #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
2095 /** We are not a directory cache or authority. Update our network-status list
2096 * by launching a new directory fetch for enough network-status documents "as
2097 * necessary". See function comments for implementation details.
2099 static void
2100 update_networkstatus_client_downloads(time_t now)
2102 int n_live = 0, needed = 0, n_running_dirservers, n_dirservers, i;
2103 int most_recent_idx = -1;
2104 trusted_dir_server_t *most_recent = NULL;
2105 time_t most_recent_received = 0;
2106 char *resource, *cp;
2107 size_t resource_len;
2109 if (connection_get_by_type_purpose(CONN_TYPE_DIR,
2110 DIR_PURPOSE_FETCH_NETWORKSTATUS))
2111 return;
2113 /* This is a little tricky. We want to download enough network-status
2114 * objects so that we have at least half of them under
2115 * NETWORKSTATUS_MAX_VALIDITY publication time. We want to download a new
2116 * *one* if the most recent one's publication time is under
2117 * NETWORKSTATUS_CLIENT_DL_INTERVAL.
2119 if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
2120 return;
2121 n_dirservers = n_running_dirservers = smartlist_len(trusted_dir_servers);
2122 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
2124 networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
2125 if (!ns)
2126 continue;
2127 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
2128 --n_running_dirservers;
2129 continue;
2131 if (ns->published_on > now-NETWORKSTATUS_MAX_VALIDITY)
2132 ++n_live;
2133 if (!most_recent || ns->received_on > most_recent_received) {
2134 most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
2135 most_recent = ds;
2136 most_recent_received = ns->received_on;
2140 /* Download enough so we have at least half live, but no more than all the
2141 * trusted dirservers we know.
2143 if (n_live < (n_dirservers/2)+1)
2144 needed = (n_dirservers/2)+1-n_live;
2145 if (needed > n_running_dirservers)
2146 needed = n_running_dirservers;
2148 if (needed)
2149 info(LD_DIR, "For %d/%d running directory servers, we have %d live"
2150 " network-status documents. Downloading %d.",
2151 n_running_dirservers, n_dirservers, n_live, needed);
2153 /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
2154 if (n_running_dirservers &&
2155 most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL && needed < 1) {
2156 info(LD_DIR, "Our most recent network-status document (from %s) "
2157 "is %d seconds old; downloading another.",
2158 most_recent?most_recent->description:"nobody",
2159 (int)(now-most_recent_received));
2160 needed = 1;
2163 if (!needed)
2164 return;
2166 /* If no networkstatus was found, choose a dirserver at random as "most
2167 * recent". */
2168 if (most_recent_idx<0)
2169 most_recent_idx = crypto_rand_int(n_dirservers);
2171 /* Build a request string for all the resources we want. */
2172 resource_len = needed * (HEX_DIGEST_LEN+1) + 6;
2173 resource = tor_malloc(resource_len);
2174 memcpy(resource, "fp/", 3);
2175 cp = resource+3;
2176 for (i = most_recent_idx+1; needed; ++i) {
2177 trusted_dir_server_t *ds;
2178 if (i >= n_dirservers)
2179 i = 0;
2180 ds = smartlist_get(trusted_dir_servers, i);
2181 if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES)
2182 continue;
2183 base16_encode(cp, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
2184 cp += HEX_DIGEST_LEN;
2185 --needed;
2186 if (needed)
2187 *cp++ = '+';
2189 memcpy(cp, ".z", 3);
2190 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
2191 tor_free(resource);
2194 /*DOCDOC*/
2195 void
2196 update_networkstatus_downloads(time_t now)
2198 or_options_t *options = get_options();
2199 if (server_mode(options) && options->DirPort)
2200 update_networkstatus_cache_downloads(time(NULL));
2201 else
2202 update_networkstatus_client_downloads(time(NULL));
2205 /** Decide whether a given addr:port is definitely accepted,
2206 * definitely rejected, probably accepted, or probably rejected by a
2207 * given policy. If <b>addr</b> is 0, we don't know the IP of the
2208 * target address. If <b>port</b> is 0, we don't know the port of the
2209 * target address.
2211 * For now, the algorithm is pretty simple: we look for definite and
2212 * uncertain matches. The first definite match is what we guess; if
2213 * it was preceded by no uncertain matches of the opposite policy,
2214 * then the guess is definite; otherwise it is probable. (If we
2215 * have a known addr and port, all matches are definite; if we have an
2216 * unknown addr/port, any address/port ranges other than "all" are
2217 * uncertain.)
2219 * We could do better by assuming that some ranges never match typical
2220 * addresses (127.0.0.1, and so on). But we'll try this for now.
2222 addr_policy_result_t
2223 router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
2224 addr_policy_t *policy)
2226 int maybe_reject = 0;
2227 int maybe_accept = 0;
2228 int match = 0;
2229 int maybe = 0;
2230 addr_policy_t *tmpe;
2232 for (tmpe=policy; tmpe; tmpe=tmpe->next) {
2233 maybe = 0;
2234 if (!addr) {
2235 /* Address is unknown. */
2236 if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
2237 (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
2238 /* The port definitely matches. */
2239 if (tmpe->msk == 0) {
2240 match = 1;
2241 } else {
2242 maybe = 1;
2244 } else if (!port) {
2245 /* The port maybe matches. */
2246 maybe = 1;
2248 } else {
2249 /* Address is known */
2250 if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
2251 if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
2252 /* Exact match for the policy */
2253 match = 1;
2254 } else if (!port) {
2255 maybe = 1;
2259 if (maybe) {
2260 if (tmpe->policy_type == ADDR_POLICY_REJECT)
2261 maybe_reject = 1;
2262 else
2263 maybe_accept = 1;
2265 if (match) {
2266 if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
2267 /* If we already hit a clause that might trigger a 'reject', than we
2268 * can't be sure of this certain 'accept'.*/
2269 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
2270 } else {
2271 return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED : ADDR_POLICY_REJECTED;
2275 /* accept all by default. */
2276 return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
2279 /** Return 1 if all running sufficiently-stable routers will reject
2280 * addr:port, return 0 if any might accept it. */
2282 router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
2283 int need_uptime)
2285 addr_policy_result_t r;
2286 if (!routerlist) return 1;
2288 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
2290 if (router->is_running &&
2291 !router_is_unreliable(router, need_uptime, 0)) {
2292 r = router_compare_addr_to_addr_policy(addr, port, router->exit_policy);
2293 if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
2294 return 0; /* this one could be ok. good enough. */
2297 return 1; /* all will reject. */
2301 * If <b>policy</b> implicitly allows connections to any port in the
2302 * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
2303 * part of the policy that allows it, and return 1. Else return 0.
2305 * A policy allows an IP:Port combination <em>implicitly</em> if
2306 * it is included in a *: pattern, or in a fallback pattern.
2308 static int
2309 policy_includes_addr_mask_implicitly(addr_policy_t *policy,
2310 uint32_t addr, uint32_t mask,
2311 addr_policy_t **policy_out)
2313 uint32_t addr2;
2314 tor_assert(policy_out);
2315 addr &= mask;
2316 addr2 = addr | ~mask;
2317 for (; policy; policy=policy->next) {
2318 /* Does this policy cover all of the address range we're looking at? */
2319 /* Boolean logic time: range X is contained in range Y if, for
2320 * each bit B, all possible values of B in X are values of B in Y.
2321 * In "addr", we have every fixed bit set to its value, and every
2322 * free bit set to 0. In "addr2", we have every fixed bit set to
2323 * its value, and every free bit set to 1. So if addr and addr2 are
2324 * both in the policy, the range is covered by the policy.
2326 uint32_t p_addr = policy->addr & policy->msk;
2327 if (p_addr == (addr & policy->msk) &&
2328 p_addr == (addr2 & policy->msk) &&
2329 (policy->prt_min <= 1 && policy->prt_max == 65535)) {
2330 return 0;
2332 /* Does this policy cover some of the address range we're looking at? */
2333 /* Boolean logic time: range X and range Y intersect if there is
2334 * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
2335 * This is FALSE iff there is some bit b where Xmask == yMask == 1
2336 * and Xaddr != Yaddr. So if X intersects with Y iff at every
2337 * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
2338 * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
2340 if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
2341 policy->policy_type == ADDR_POLICY_ACCEPT) {
2342 *policy_out = policy;
2343 return 1;
2346 *policy_out = NULL;
2347 return 1;
2350 /** If <b>policy</b> implicitly allows connections to any port on
2351 * 127.*, 192.168.*, etc, then warn (if <b>should_warn</b> is set) and return
2352 * true. Else return false.
2355 exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
2356 int should_warn)
2358 addr_policy_t *p;
2359 int r=0,i;
2360 static struct {
2361 uint32_t addr; uint32_t mask; const char *network;
2362 } private_networks[] = {
2363 { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
2364 { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
2365 { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
2366 { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
2367 { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
2368 { 0,0,NULL},
2370 for (i=0; private_networks[i].addr; ++i) {
2371 p = NULL;
2372 /* log_fn(LOG_INFO,"Checking network %s", private_networks[i].network); */
2373 if (policy_includes_addr_mask_implicitly(
2374 policy, private_networks[i].addr, private_networks[i].mask, &p)) {
2375 if (should_warn)
2376 warn(LD_CONFIG, "Exit policy %s implicitly accepts %s",
2377 p?p->string:"(default)",
2378 private_networks[i].network);
2379 r = 1;
2383 return r;
2386 /** Return true iff <b>router</b> does not permit exit streams.
2389 router_exit_policy_rejects_all(routerinfo_t *router)
2391 return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
2392 == ADDR_POLICY_REJECTED;
2395 /** Add to the list of authorized directory servers one at
2396 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
2397 * <b>address</b> is NULL, add ourself. */
2398 void
2399 add_trusted_dir_server(const char *nickname, const char *address,
2400 uint16_t port, const char *digest, int supports_v1)
2402 trusted_dir_server_t *ent;
2403 uint32_t a;
2404 char *hostname = NULL;
2405 size_t dlen;
2406 if (!trusted_dir_servers)
2407 trusted_dir_servers = smartlist_create();
2409 if (!address) { /* The address is us; we should guess. */
2410 if (resolve_my_address(get_options(), &a, &hostname) < 0) {
2411 warn(LD_CONFIG, "Couldn't find a suitable address when adding ourself as a trusted directory server.");
2412 return;
2414 } else {
2415 if (tor_lookup_hostname(address, &a)) {
2416 warn(LD_CONFIG, "Unable to lookup address for directory server at %s",
2417 address);
2418 return;
2420 hostname = tor_strdup(address);
2421 a = ntohl(a);
2424 ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
2425 ent->nickname = nickname ? tor_strdup(nickname) : NULL;
2426 ent->address = hostname;
2427 ent->addr = a;
2428 ent->dir_port = port;
2429 ent->is_running = 1;
2430 ent->supports_v1_protocol = supports_v1;
2431 memcpy(ent->digest, digest, DIGEST_LEN);
2433 dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
2434 ent->description = tor_malloc(dlen);
2435 if (nickname)
2436 tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
2437 nickname, hostname, (int)port);
2438 else
2439 tor_snprintf(ent->description, dlen, "directory server at %s:%d",
2440 hostname, (int)port);
2442 smartlist_add(trusted_dir_servers, ent);
2445 /** Free storage held in <b>ds</b> */
2446 void
2447 trusted_dir_server_free(trusted_dir_server_t *ds)
2449 tor_free(ds->nickname);
2450 tor_free(ds->description);
2451 tor_free(ds->address);
2452 tor_free(ds);
2455 /** Remove all members from the list of trusted dir servers. */
2456 void
2457 clear_trusted_dir_servers(void)
2459 if (trusted_dir_servers) {
2460 SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
2461 trusted_dir_server_free(ent));
2462 smartlist_clear(trusted_dir_servers);
2463 } else {
2464 trusted_dir_servers = smartlist_create();
2468 /** Return the network status with a given identity digest. */
2469 networkstatus_t *
2470 networkstatus_get_by_digest(const char *digest)
2472 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2474 if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
2475 return ns;
2477 return NULL;
2480 /** If the network-status list has changed since the last time we called this
2481 * function, update the status of every router from the network-status list.
2483 void
2484 routers_update_all_from_networkstatus(void)
2486 #define SELF_OPINION_INTERVAL 90*60
2487 routerinfo_t *me;
2488 time_t now;
2489 if (!routerlist || !networkstatus_list ||
2490 (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
2491 return;
2493 now = time(NULL);
2494 if (networkstatus_list_has_changed)
2495 routerstatus_list_update_from_networkstatus(now);
2497 routers_update_status_from_networkstatus(routerlist->routers, 0, 0);
2499 me = router_get_my_routerinfo();
2500 if (me && !have_warned_about_unverified_status) {
2501 int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0;
2502 routerstatus_t *rs;
2503 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2505 if (ns->received_on + SELF_OPINION_INTERVAL < now)
2506 continue;
2507 ++n_recent;
2508 if (!(rs = networkstatus_find_entry(ns, me->cache_info.identity_digest)))
2509 continue;
2510 ++n_listing;
2511 if (rs->is_valid)
2512 ++n_valid;
2513 if (rs->is_named)
2514 ++n_named;
2517 if (n_recent >= 2 && n_listing >= 2) {
2518 /* XXX When we have more than 3 dirservers, these warnings
2519 * might become spurious depending on which combination of
2520 * network-statuses we have. Perhaps we should wait until we
2521 * have tried all of them? -RD */
2522 if (n_valid <= n_recent/2) {
2523 warn(LD_GENERAL, "%d/%d recent directory servers list us as invalid. Please consider sending your identity fingerprint to the tor-ops.",
2524 n_recent-n_valid, n_recent);
2525 have_warned_about_unverified_status = 1;
2526 } else if (!n_named) { // (n_named <= n_recent/2) {
2527 warn(LD_GENERAL, "%d/%d recent directory servers list us as unnamed. Please consider sending your identity fingerprint to the tor-ops.",
2528 n_recent-n_named, n_recent);
2529 have_warned_about_unverified_status = 1;
2534 helper_nodes_set_status_from_directory();
2536 if (!have_warned_about_old_version) {
2537 int n_recent = 0;
2538 int n_recommended = 0;
2539 int is_server = server_mode(get_options());
2540 version_status_t consensus = VS_RECOMMENDED;
2541 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
2543 version_status_t vs;
2544 if (!ns->recommends_versions ||
2545 ns->received_on + SELF_OPINION_INTERVAL < now )
2546 continue;
2547 vs = tor_version_is_obsolete(
2548 VERSION, is_server ? ns->server_versions : ns->client_versions);
2549 if (vs == VS_RECOMMENDED)
2550 ++n_recommended;
2551 if (n_recent++ == 0) {
2552 consensus = vs;
2553 } else if (consensus != vs) {
2554 consensus = version_status_join(consensus, vs);
2557 if (n_recent > 2 && n_recommended < n_recent/2) {
2558 if (consensus == VS_NEW || consensus == VS_NEW_IN_SERIES) {
2559 if (!have_warned_about_new_version) {
2560 notice(LD_GENERAL, "This version of Tor (%s) is newer than any recommended version%s, according to %d/%d recent network statuses.",
2561 VERSION, consensus == VS_NEW_IN_SERIES ? " in its series" : "",
2562 n_recent-n_recommended, n_recent);
2563 have_warned_about_new_version = 1;
2565 } else {
2566 notice(LD_GENERAL, "This version of Tor (%s) is %s, according to %d/%d recent network statuses.",
2567 VERSION, consensus == VS_OLD ? "obsolete" : "not recommended",
2568 n_recent-n_recommended, n_recent);
2569 have_warned_about_old_version = 1;
2571 } else {
2572 info(LD_GENERAL, "%d/%d recent directories think my version is ok.",
2573 n_recommended, n_recent);
2577 routerstatus_list_has_changed = 0;
2580 /** Allow any network-status newer than this to influence our view of who's
2581 * running. */
2582 #define DEFAULT_RUNNING_INTERVAL 60*60
2583 /** If possible, always allow at least this many network-statuses to influence
2584 * our view of who's running. */
2585 #define MIN_TO_INFLUENCE_RUNNING 3
2587 /** Change the is_recent field of each member of networkstatus_list so that
2588 * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
2589 * at least the MIN_TO_INFLUENCE_RUNNING most recent members are resent, and no
2590 * others are recent. Set networkstatus_list_has_changed if anything happeed.
2592 void
2593 networkstatus_list_update_recent(time_t now)
2595 int n_statuses, n_recent, changed, i;
2596 char published[ISO_TIME_LEN+1];
2598 if (!networkstatus_list)
2599 return;
2601 n_statuses = smartlist_len(networkstatus_list);
2602 n_recent = 0;
2603 changed = 0;
2604 for (i=n_statuses-1; i >= 0; --i) {
2605 networkstatus_t *ns = smartlist_get(networkstatus_list, i);
2606 trusted_dir_server_t *ds =
2607 router_get_trusteddirserver_by_digest(ns->identity_digest);
2608 const char *src = ds?ds->description:ns->source_address;
2609 if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
2610 ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
2611 if (!ns->is_recent) {
2612 format_iso_time(published, ns->published_on);
2613 info(LD_DIR,
2614 "Networkstatus from %s (published %s) is now \"recent\"",
2615 src, published);
2616 changed = 1;
2618 ns->is_recent = 1;
2619 ++n_recent;
2620 } else {
2621 if (ns->is_recent) {
2622 format_iso_time(published, ns->published_on);
2623 info(LD_DIR,
2624 "Networkstatus from %s (published %s) is no longer \"recent\"",
2625 src, published);
2626 changed = 1;
2627 ns->is_recent = 0;
2631 if (changed)
2632 networkstatus_list_has_changed = 1;
2635 /** Update our view of router status (as stored in routerstatus_list) from
2636 * the current set of network status documents (as stored in networkstatus_list).
2637 * Do nothing unless the network status list has changed since the last time
2638 * this function was called.
2640 static void
2641 routerstatus_list_update_from_networkstatus(time_t now)
2643 or_options_t *options = get_options();
2644 int n_trusted, n_statuses, n_recent=0, n_naming=0;
2645 int n_distinct = 0;
2646 int i, warned;
2647 int *index, *size;
2648 networkstatus_t **networkstatus;
2649 smartlist_t *result;
2650 strmap_t *name_map;
2651 char conflict[DIGEST_LEN];
2653 networkstatus_list_update_recent(now);
2655 if (!networkstatus_list_has_changed)
2656 return;
2657 if (!networkstatus_list)
2658 networkstatus_list = smartlist_create();
2659 if (!routerstatus_list)
2660 routerstatus_list = smartlist_create();
2661 if (!trusted_dir_servers)
2662 trusted_dir_servers = smartlist_create();
2663 if (!warned_conflicts)
2664 warned_conflicts = smartlist_create();
2666 n_trusted = smartlist_len(trusted_dir_servers);
2667 n_statuses = smartlist_len(networkstatus_list);
2669 if (n_statuses < (n_trusted/2)+1) {
2670 /* Not enough statuses to adjust status. */
2671 notice(LD_DIR,"Not enough statuses to update router status list. (%d/%d)",
2672 n_statuses, n_trusted);
2673 return;
2676 info(LD_DIR, "Rebuilding router status list.");
2678 index = tor_malloc(sizeof(int)*n_statuses);
2679 size = tor_malloc(sizeof(int)*n_statuses);
2680 networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
2681 for (i = 0; i < n_statuses; ++i) {
2682 index[i] = 0;
2683 networkstatus[i] = smartlist_get(networkstatus_list, i);
2684 size[i] = smartlist_len(networkstatus[i]->entries);
2685 if (networkstatus[i]->binds_names)
2686 ++n_naming;
2687 if (networkstatus[i]->is_recent)
2688 ++n_recent;
2691 name_map = strmap_new();
2692 memset(conflict, 0xff, sizeof(conflict));
2693 for (i = 0; i < n_statuses; ++i) {
2694 if (!networkstatus[i]->binds_names)
2695 continue;
2696 SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
2698 const char *other_digest;
2699 if (!rs->is_named)
2700 continue;
2701 other_digest = strmap_get_lc(name_map, rs->nickname);
2702 warned = smartlist_string_isin(warned_conflicts, rs->nickname);
2703 if (!other_digest) {
2704 strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
2705 if (warned)
2706 smartlist_string_remove(warned_conflicts, rs->nickname);
2707 } else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
2708 other_digest != conflict) {
2709 if (!warned) {
2710 int should_warn = options->DirPort && options->AuthoritativeDir;
2711 char fp1[HEX_DIGEST_LEN+1];
2712 char fp2[HEX_DIGEST_LEN+1];
2713 base16_encode(fp1, sizeof(fp1), other_digest, DIGEST_LEN);
2714 base16_encode(fp2, sizeof(fp2), rs->identity_digest, DIGEST_LEN);
2715 log_fn(should_warn ? LOG_WARN : LOG_INFO, LD_DIR,
2716 "Naming authorities disagree about which key goes with %s. ($%s vs $%s)",
2717 rs->nickname, fp1, fp2);
2718 strmap_set_lc(name_map, rs->nickname, conflict);
2719 smartlist_add(warned_conflicts, tor_strdup(rs->nickname));
2721 } else {
2722 if (warned)
2723 smartlist_string_remove(warned_conflicts, rs->nickname);
2728 result = smartlist_create();
2730 /* Iterate through all of the sorted routerstatus lists in step.
2731 * Invariants:
2732 * - For 0 <= i < n_statuses: index[i] is an index into
2733 * networkstatus[i]->entries, which has size[i] elements.
2734 * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
2735 * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
2736 * networkstatus[i2]->entries[index[i2]]->identity_digest.
2738 * (That is, the indices are always advanced past lower digest before
2739 * higher.)
2741 while (1) {
2742 int n_running=0, n_named=0, n_valid=0, n_listing=0;
2743 const char *the_name = NULL;
2744 local_routerstatus_t *rs_out, *rs_old;
2745 routerstatus_t *rs, *most_recent;
2746 networkstatus_t *ns;
2747 const char *lowest = NULL;
2748 /* Find out which of the digests appears first. */
2749 for (i = 0; i < n_statuses; ++i) {
2750 if (index[i] < size[i]) {
2751 rs = smartlist_get(networkstatus[i]->entries, index[i]);
2752 if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
2753 lowest = rs->identity_digest;
2756 if (!lowest) {
2757 /* We're out of routers. Great! */
2758 break;
2760 /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
2761 * match "lowest" are next in order. Iterate over them, incrementing those
2762 * index[i] as we go. */
2763 ++n_distinct;
2764 most_recent = NULL;
2765 for (i = 0; i < n_statuses; ++i) {
2766 if (index[i] >= size[i])
2767 continue;
2768 ns = networkstatus[i];
2769 rs = smartlist_get(ns->entries, index[i]);
2770 if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
2771 continue;
2772 ++index[i];
2773 ++n_listing;
2774 if (!most_recent || rs->published_on > most_recent->published_on)
2775 most_recent = rs;
2776 if (rs->is_named && ns->binds_names) {
2777 if (!the_name)
2778 the_name = rs->nickname;
2779 if (!strcasecmp(rs->nickname, the_name)) {
2780 ++n_named;
2781 } else if (strcmp(the_name,"**mismatch**")) {
2782 char hd[HEX_DIGEST_LEN+1];
2783 base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
2784 if (! smartlist_string_isin(warned_conflicts, hd)) {
2785 warn(LD_DIR, "Naming authorities disagree about nicknames for $%s (\"%s\" vs \"%s\")",
2786 hd, the_name, rs->nickname);
2787 smartlist_add(warned_conflicts, tor_strdup(hd));
2789 the_name = "**mismatch**";
2792 if (rs->is_valid)
2793 ++n_valid;
2794 if (rs->is_running && ns->is_recent)
2795 ++n_running;
2797 rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
2798 memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
2799 if ((rs_old = router_get_combined_status_by_digest(lowest))) {
2800 rs_out->n_download_failures = rs_old->n_download_failures;
2801 rs_out->next_attempt_at = rs_old->next_attempt_at;
2802 rs_out->name_lookup_warned = rs_old->name_lookup_warned;
2804 smartlist_add(result, rs_out);
2805 debug(LD_DIR, "Router '%s' is listed by %d/%d directories, "
2806 "named by %d/%d, validated by %d/%d, and %d/%d recent directories "
2807 "think it's running.",
2808 rs_out->status.nickname,
2809 n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
2810 n_running, n_recent);
2811 rs_out->status.is_named = 0;
2812 if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
2813 const char *d = strmap_get_lc(name_map, the_name);
2814 if (d && d != conflict)
2815 rs_out->status.is_named = 1;
2816 if (smartlist_string_isin(warned_conflicts, rs_out->status.nickname))
2817 smartlist_string_remove(warned_conflicts, rs_out->status.nickname);
2819 if (rs_out->status.is_named)
2820 strlcpy(rs_out->status.nickname, the_name, sizeof(rs_out->status.nickname));
2821 rs_out->status.is_valid = n_valid > n_statuses/2;
2822 rs_out->status.is_running = n_running > n_recent/2;
2824 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
2825 local_routerstatus_free(rs));
2826 smartlist_free(routerstatus_list);
2827 routerstatus_list = result;
2829 tor_free(networkstatus);
2830 tor_free(index);
2831 tor_free(size);
2832 strmap_free(name_map, NULL);
2834 networkstatus_list_has_changed = 0;
2835 routerstatus_list_has_changed = 1;
2838 /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
2839 * is_named, is_verified, and is_running fields according to our current
2840 * networkstatus_t documents. */
2841 void
2842 routers_update_status_from_networkstatus(smartlist_t *routers, int reset_failures, int assume_recognized)
2844 trusted_dir_server_t *ds;
2845 local_routerstatus_t *rs;
2846 or_options_t *options = get_options();
2847 int authdir = options->AuthoritativeDir;
2848 int namingdir = options->AuthoritativeDir &&
2849 options->NamingAuthoritativeDir;
2851 if (!routerstatus_list)
2852 return;
2854 SMARTLIST_FOREACH(routers, routerinfo_t *, router,
2856 rs = router_get_combined_status_by_digest(router->cache_info.identity_digest);
2857 ds = router_get_trusteddirserver_by_digest(router->cache_info.identity_digest);
2859 if (!rs)
2860 continue;
2862 if (!namingdir)
2863 router->is_named = rs->status.is_named;
2865 if (!authdir) {
2866 /* If we're an authdir, don't believe others. */
2867 router->is_verified = rs->status.is_valid;
2868 router->is_running = rs->status.is_running;
2870 if (router->is_running && ds) {
2871 ds->n_networkstatus_failures = 0;
2873 if (assume_recognized) {
2874 router->xx_is_recognized = 1;
2875 } else {
2876 if (!router->xx_is_recognized) {
2877 router->xx_is_recognized = routerdesc_digest_is_recognized(
2878 router->cache_info.identity_digest, router->cache_info.signed_descriptor_digest);
2880 router->xx_is_extra_new = router->cache_info.published_on > rs->status.published_on;
2882 if (reset_failures && router->xx_is_recognized) {
2883 rs->n_download_failures = 0;
2884 rs->next_attempt_at = 0;
2889 /** Return new list of ID fingerprints for superseded routers. A router is
2890 * superseded if any network-status has a router with a different digest
2891 * published more recently, or if it is listed in the network-status but not
2892 * in the router list.
2894 static smartlist_t *
2895 router_list_downloadable(void)
2897 #define MAX_OLD_SERVER_DOWNLOAD_RATE 2*60*60
2898 int n_conns, i, n_downloadable = 0;
2899 connection_t **carray;
2900 smartlist_t *superseded = smartlist_create();
2901 smartlist_t *downloading;
2902 time_t now = time(NULL);
2903 int mirror = server_mode(get_options()) && get_options()->DirPort;
2904 /* these are just used for logging */
2905 int n_not_ready = 0, n_in_progress = 0, n_uptodate = 0, n_skip_old = 0,
2906 n_obsolete = 0, xx_n_unrecognized = 0, xx_n_extra_new = 0, xx_n_both = 0,
2907 xx_n_unrec_old = 0;
2909 if (!routerstatus_list)
2910 return superseded;
2912 get_connection_array(&carray, &n_conns);
2914 routerstatus_list_update_from_networkstatus(now);
2916 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
2918 if (rs->status.published_on + ROUTER_MAX_AGE < now) {
2919 rs->should_download = 0;
2920 ++n_obsolete;
2921 } if (rs->next_attempt_at < now) {
2922 rs->should_download = 1;
2923 ++n_downloadable;
2924 } else {
2926 char fp[HEX_DIGEST_LEN+1];
2927 base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
2928 log_fn(LOG_NOTICE, "Not yet ready to download %s (%d more seconds)", fp,
2929 (int)(rs->next_attempt_at-now));
2931 rs->should_download = 0;
2932 ++n_not_ready;
2936 downloading = smartlist_create();
2937 for (i = 0; i < n_conns; ++i) {
2938 connection_t *conn = carray[i];
2939 if (conn->type == CONN_TYPE_DIR &&
2940 conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
2941 !conn->marked_for_close) {
2942 if (!strcmpstart(conn->requested_resource, "all"))
2943 n_downloadable = 0;
2944 dir_split_resource_into_fingerprints(conn->requested_resource,
2945 downloading, NULL, 1);
2949 if (n_downloadable) {
2950 SMARTLIST_FOREACH(downloading, const char *, d,
2952 local_routerstatus_t *rs;
2953 if ((rs = router_get_combined_status_by_digest(d)) && rs->should_download) {
2954 rs->should_download = 0;
2955 --n_downloadable;
2956 ++n_in_progress;
2960 SMARTLIST_FOREACH(downloading, char *, cp, tor_free(cp));
2961 smartlist_free(downloading);
2962 if (!n_downloadable)
2963 return superseded;
2965 if (routerlist && n_downloadable) {
2966 SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
2968 local_routerstatus_t *rs;
2969 if (!(rs = router_get_combined_status_by_digest(ri->cache_info.identity_digest)) ||
2970 !rs->should_download) {
2971 // log_fn(LOG_NOTICE, "No status for %s", fp);
2972 continue;
2974 if (!ri->xx_is_recognized) {
2975 ++xx_n_unrecognized;
2976 if (ri->xx_is_extra_new)
2977 ++xx_n_both;
2979 if (ri->xx_is_extra_new)
2980 ++xx_n_extra_new;
2982 /* Change this "or" to be an "and" once dirs generate hashes right.
2983 * Remove the version check once older versions are uncommon.
2984 * XXXXX. NM */
2985 if (!memcmp(ri->cache_info.signed_descriptor_digest, rs->status.descriptor_digest,
2986 DIGEST_LEN) ||
2987 rs->status.published_on <= ri->cache_info.published_on) {
2988 ++n_uptodate;
2989 rs->should_download = 0;
2990 --n_downloadable;
2991 } else if (!mirror &&
2992 ri->platform &&
2993 !tor_version_as_new_as(ri->platform, "0.1.1.6-alpha") &&
2994 ri->cache_info.published_on + MAX_OLD_SERVER_DOWNLOAD_RATE > now) {
2995 /* Same digest, or date is up-to-date, or we have a comparatively recent
2996 * server with an old version.
2997 * No need to download it. */
2998 // log_fn(LOG_NOTICE, "Up-to-date status for %s", fp);
2999 ++n_skip_old;
3000 if (!ri->xx_is_recognized)
3001 ++xx_n_unrec_old;
3002 rs->should_download = 0;
3003 --n_downloadable;
3004 } /* else {
3005 char t1[ISO_TIME_LEN+1];
3006 char t2[ISO_TIME_LEN+1];
3007 format_iso_time(t1, rs->satus.published_on);
3008 format_iso_time(t2, ri->published_on);
3009 log_fn(LOG_NOTICE, "Out-of-date status for %s %s (%d %d) [%s %s]", fp,
3010 ri->nickname,
3011 !memcmp(ri->cache_info.signed_descriptor_digest,rs->status.descriptor_digest,
3012 DIGEST_LEN),
3013 rs->published_on < ri->published_on,
3014 t1, t2);
3015 } */
3019 info(LD_DIR, "%d router descriptors are downloadable; "
3020 "%d are up to date; %d are in progress; "
3021 "%d are not ready to retry; "
3022 "%d are not published recently enough to be worthwhile; "
3023 "%d are running pre-0.1.1.6 Tors and aren't stale enough to replace. "
3024 "%d have unrecognized descriptor hashes; %d are newer than the dirs "
3025 "have told us about; %d are both unrecognized and newer than any "
3026 "publication date in the networkstatus; %d are both "
3027 "unrecognized and running a pre-0.1.1.6 version.",
3028 n_downloadable, n_uptodate, n_in_progress, n_not_ready,
3029 n_obsolete, n_skip_old, xx_n_unrecognized, xx_n_extra_new, xx_n_both,
3030 xx_n_unrec_old);
3032 if (!n_downloadable)
3033 return superseded;
3035 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3037 if (rs->should_download) {
3038 char *fp = tor_malloc(HEX_DIGEST_LEN+1);
3039 base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
3040 smartlist_add(superseded, fp);
3044 return superseded;
3047 /** Initiate new router downloads as needed.
3049 * We only allow one router descriptor download at a time.
3050 * If we have less than two network-status documents, we ask
3051 * a directory for "all descriptors."
3052 * Otherwise, we ask for all descriptors that we think are different
3053 * from what we have.
3055 void
3056 update_router_descriptor_downloads(time_t now)
3058 #define MAX_DL_PER_REQUEST 128
3059 #define MIN_DL_PER_REQUEST 4
3060 #define MIN_REQUESTS 3
3061 #define MAX_DL_TO_DELAY 16
3062 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST 10*60
3063 #define MAX_SERVER_INTERVAL_WITHOUT_REQUEST 1*60
3064 smartlist_t *downloadable = NULL;
3065 int get_all = 0;
3066 int dirserv = server_mode(get_options()) && get_options()->DirPort;
3067 int should_delay, n_downloadable;
3068 if (!networkstatus_list || smartlist_len(networkstatus_list)<2)
3069 get_all = 1;
3071 if (get_all) {
3072 notice(LD_DIR, "Launching request for all routers");
3073 last_routerdesc_download_attempted = now;
3074 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,"all.z",1);
3075 return;
3078 downloadable = router_list_downloadable();
3079 n_downloadable = smartlist_len(downloadable);
3080 if (n_downloadable >= MAX_DL_TO_DELAY) {
3081 debug(LD_DIR,
3082 "There are enough downloadable routerdescs to launch requests.");
3083 should_delay = 0;
3084 } else if (n_downloadable == 0) {
3085 debug(LD_DIR, "No routerdescs need to be downloaded.");
3086 should_delay = 1;
3087 } else {
3088 if (dirserv) {
3089 should_delay = (last_routerdesc_download_attempted +
3090 MAX_SERVER_INTERVAL_WITHOUT_REQUEST) > now;
3091 } else {
3092 should_delay = (last_routerdesc_download_attempted +
3093 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
3095 if (should_delay)
3096 debug(LD_DIR, "There are not many downloadable routerdescs; waiting till we have some more.");
3097 else
3098 info(LD_DIR, "There are not many downloadable routerdescs, but we've been waiting long enough (%d seconds). Downloading.",
3099 (int)(now-last_routerdesc_download_attempted));
3102 if (! should_delay) {
3103 int i, j, n_per_request=MAX_DL_PER_REQUEST;
3104 size_t r_len = MAX_DL_PER_REQUEST*(HEX_DIGEST_LEN+1)+16;
3105 char *resource = tor_malloc(r_len);
3107 if (! dirserv) {
3108 n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
3109 if (n_per_request > MAX_DL_PER_REQUEST)
3110 n_per_request = MAX_DL_PER_REQUEST;
3111 if (n_per_request < MIN_DL_PER_REQUEST)
3112 n_per_request = MIN_DL_PER_REQUEST;
3114 info(LD_DIR, "Launching %d request%s for %d router%s, %d at a time",
3115 (n_downloadable+n_per_request-1)/n_per_request,
3116 n_downloadable>n_per_request?"s":"",
3117 n_downloadable, n_downloadable>1?"s":"", n_per_request);
3118 for (i=0; i < n_downloadable; i += n_per_request) {
3119 char *cp = resource;
3120 memcpy(resource, "fp/", 3);
3121 cp = resource + 3;
3122 for (j=i; j < i+n_per_request && j < n_downloadable; ++j) {
3123 memcpy(cp, smartlist_get(downloadable, j), HEX_DIGEST_LEN);
3124 cp += HEX_DIGEST_LEN;
3125 *cp++ = '+';
3127 memcpy(cp-1, ".z", 3);
3128 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,resource,1);
3130 last_routerdesc_download_attempted = now;
3131 tor_free(resource);
3133 SMARTLIST_FOREACH(downloadable, char *, c, tor_free(c));
3134 smartlist_free(downloadable);
3137 /** Return true iff we have enough networkstatus and router information to
3138 * start building circuits. Right now, this means "at least 2 networkstatus
3139 * documents, and at least 1/4 of expected routers." */
3140 //XXX should consider whether we have enough exiting nodes here.
3141 //and also consider if they're too "old"?
3143 router_have_minimum_dir_info(void)
3145 int tot = 0, avg;
3146 if (!networkstatus_list || smartlist_len(networkstatus_list)<2 ||
3147 !routerlist)
3148 return 0;
3149 SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
3150 tot += smartlist_len(ns->entries));
3151 avg = tot / smartlist_len(networkstatus_list);
3152 return smartlist_len(routerlist->routers) > (avg/4);
3155 /** Reset the descriptor download failure count on all routers, so that we
3156 * can retry any long-failed routers immediately.
3158 void
3159 router_reset_descriptor_download_failures(void)
3161 if (!routerstatus_list)
3162 return;
3163 SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
3165 rs->n_download_failures = 0;
3166 rs->next_attempt_at = 0;
3168 last_routerdesc_download_attempted = 0;
3171 /** Return true iff the only differences between r1 and r2 are such that
3172 * would not cause a recent (post 0.1.1.6) dirserver to republish.
3175 router_differences_are_cosmetic(routerinfo_t *r1, routerinfo_t *r2)
3177 tor_assert(r1 && r2);
3179 /* post-0.1.1.6 servers know what they're doing. */
3180 if (tor_version_as_new_as(r1->platform, "0.1.1.6-alpha") ||
3181 tor_version_as_new_as(r2->platform, "0.1.1.6-alpha"))
3182 return 0;
3184 /* r1 should be the one that was published first. */
3185 if (r1->cache_info.published_on > r2->cache_info.published_on) {
3186 routerinfo_t *ri_tmp = r2;
3187 r2 = r1;
3188 r1 = ri_tmp;
3191 /* If any key fields differ, they're different. */
3192 if (strcasecmp(r1->address, r2->address) ||
3193 strcasecmp(r1->nickname, r2->nickname) ||
3194 r1->or_port != r2->or_port ||
3195 r1->dir_port != r2->dir_port ||
3196 crypto_pk_cmp_keys(r1->onion_pkey, r2->onion_pkey) ||
3197 crypto_pk_cmp_keys(r1->identity_pkey, r2->identity_pkey) ||
3198 strcasecmp(r1->platform, r2->platform) ||
3199 (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
3200 (!r1->contact_info && r2->contact_info) ||
3201 (r1->contact_info && r2->contact_info && strcasecmp(r1->contact_info, r2->contact_info)) ||
3202 r1->is_hibernating != r2->is_hibernating ||
3203 config_cmp_addr_policies(r1->exit_policy, r2->exit_policy))
3204 return 0;
3205 if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
3206 return 0;
3207 if (r1->declared_family && r2->declared_family) {
3208 int i, n;
3209 if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
3210 return 0;
3211 n = smartlist_len(r1->declared_family);
3212 for (i=0; i < n; ++i) {
3213 if (strcasecmp(smartlist_get(r1->declared_family, i),
3214 smartlist_get(r2->declared_family, i)))
3215 return 0;
3219 /* Did bandwidth change a lot? */
3220 if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
3221 (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
3222 return 0;
3224 /* Did more than 12 hours pass? */
3225 if (r1->cache_info.published_on + 12*60*60 < r2->cache_info.published_on)
3226 return 0;
3228 /* Did uptime fail to increase by approximately the amount we would think,
3229 * give or take 30 minutes? */
3230 if (abs(r2->uptime - (r1->uptime + (r2->cache_info.published_on-r1->cache_info.published_on)))>30*60)
3231 return 0;
3233 /* Otherwise, the difference is cosmetic. */
3234 return 1;
3237 static void
3238 routerlist_assert_ok(routerlist_t *rl)
3240 digestmap_iter_t *iter;
3241 routerinfo_t *r2;
3242 signed_descriptor_t *sd2;
3243 if (!routerlist)
3244 return;
3245 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
3247 r2 = digestmap_get(rl->identity_map, r->cache_info.identity_digest);
3248 tor_assert(r == r2);
3249 sd2 = digestmap_get(rl->desc_digest_map, r->cache_info.signed_descriptor_digest);
3250 tor_assert(&(r->cache_info) == sd2);
3252 SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
3254 r2 = digestmap_get(rl->identity_map, sd->identity_digest);
3255 tor_assert(sd != &(r2->cache_info));
3256 sd2 = digestmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
3257 tor_assert(sd == sd2);
3259 iter = digestmap_iter_init(rl->identity_map);
3260 while (!digestmap_iter_done(iter)) {
3261 const char *d;
3262 void *_r;
3263 routerinfo_t *r;
3264 digestmap_iter_get(iter, &d, &_r);
3265 r = _r;
3266 tor_assert(!memcmp(r->cache_info.identity_digest, d, DIGEST_LEN));
3267 iter = digestmap_iter_next(rl->identity_map, iter);
3269 iter = digestmap_iter_init(rl->desc_digest_map);
3270 while (!digestmap_iter_done(iter)) {
3271 const char *d;
3272 void *_sd;
3273 signed_descriptor_t *sd;
3274 digestmap_iter_get(iter, &d, &_sd);
3275 sd = _sd;
3276 tor_assert(!memcmp(sd->signed_descriptor_digest, d, DIGEST_LEN));
3277 iter = digestmap_iter_next(rl->desc_digest_map, iter);