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 */
6 const char routerlist_c_id
[] = "$Id$";
11 * maintain and access the global list of routerinfos for known
17 /****************************************************************************/
19 /* static function prototypes */
20 static routerinfo_t
*router_pick_directory_server_impl(int requireother
,
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
,
35 static void routerlist_assert_ok(routerlist_t
*rl
);
37 /****************************************************************************/
39 /** Global list of a trusted_dir_server_t object for each trusted directory
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
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;
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. */
89 router_reload_networkstatus(void)
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
))) {
107 "Skipping cached-status file with unexpected name \"%s\"",fn
);
110 tor_snprintf(filename
,sizeof(filename
),"%s/cached-status/%s",
111 get_options()->DataDirectory
, fn
);
112 s
= read_file_to_str(filename
, 0);
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
);
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();
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
148 router_should_rebuild_store(void)
150 if (router_store_len
> (1<<16))
151 return router_journal_len
> router_store_len
/ 2;
153 return router_journal_len
> (1<<15);
156 /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
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
);
171 if (append_bytes_to_file(fname
, s
, len
, 0)) {
172 warn(LD_FS
, "Unable to store router descriptor");
178 router_journal_len
+= len
;
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.
187 router_rebuild_store(int force
)
190 or_options_t
*options
;
192 smartlist_t
*chunk_list
= NULL
;
196 if (!force
&& !router_should_rebuild_store())
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
, routerinfo_t
*, ri
,
215 if (!ri
->signed_descriptor
) {
216 warn(LD_BUG
, "Bug! No descriptor stored for router '%s'.",
220 c
= tor_malloc(sizeof(sized_chunk_t
));
221 c
->bytes
= ri
->signed_descriptor
;
222 c
->len
= ri
->signed_descriptor_len
;
223 smartlist_add(chunk_list
, c
);
226 if (write_chunks_to_file(fname
, chunk_list
, 0)<0) {
227 warn(LD_FS
, "Error writing router store to disk.");
231 tor_snprintf(fname
, fname_len
, "%s/cached-routers.new",
232 options
->DataDirectory
);
234 write_str_to_file(fname
, "", 0);
237 router_store_len
= len
;
238 router_journal_len
= 0;
242 SMARTLIST_FOREACH(chunk_list
, sized_chunk_t
*, c
, tor_free(c
));
243 smartlist_free(chunk_list
);
248 /* Load all cached router descriptors from the store. Return 0 on success and
252 router_reload_router_list(void)
254 or_options_t
*options
= get_options();
255 size_t fname_len
= strlen(options
->DataDirectory
)+32;
256 char *fname
= tor_malloc(fname_len
);
261 router_get_routerlist(); /* mallocs and inits it in place */
263 router_journal_len
= router_store_len
= 0;
265 for (j
= 0; j
< 2; ++j
) {
267 tor_snprintf(fname
, fname_len
,
268 (j
==0)?"%s/cached-routers":"%s/cached-routers.new",
269 options
->DataDirectory
);
270 contents
= read_file_to_str(fname
, 0);
274 router_store_len
= st
.st_size
;
276 router_journal_len
= st
.st_size
;
277 router_load_routers_from_string(contents
, 1, NULL
);
283 /* Don't cache expired routers. */
284 routerlist_remove_old_routers();
286 if (router_journal_len
) {
287 /* Always clear the journal on startup.*/
288 router_rebuild_store(1);
293 /** Set *<b>outp</b> to a smartlist containing a list of
294 * trusted_dir_server_t * for all known trusted dirservers. Callers
295 * must not modify the list or its contents.
298 router_get_trusted_dir_servers(smartlist_t
**outp
)
300 if (!trusted_dir_servers
)
301 trusted_dir_servers
= smartlist_create();
303 *outp
= trusted_dir_servers
;
306 /** Try to find a running dirserver. If there are no running dirservers
307 * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
308 * set all the authoritative ones as running again, and pick one;
309 * if there are then no dirservers at all in our routerlist,
310 * reload the routerlist and try one last time. If for_runningrouters is
311 * true, then only pick a dirserver that can answer runningrouters queries
312 * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
313 * Other args are as in router_pick_directory_server_impl().
316 router_pick_directory_server(int requireother
,
318 int for_v2_directory
,
319 int retry_if_no_servers
)
321 routerinfo_t
*choice
;
326 choice
= router_pick_directory_server_impl(requireother
, fascistfirewall
,
328 if (choice
|| !retry_if_no_servers
)
331 info(LD_DIR
,"No reachable router entries for dirservers. Trying them all again.");
332 /* mark all authdirservers as up again */
333 mark_all_trusteddirservers_up();
335 choice
= router_pick_directory_server_impl(requireother
, fascistfirewall
,
340 info(LD_DIR
,"Still no %s router entries. Reloading and trying again.",
341 firewall_is_fascist() ? "reachable" : "known");
342 has_fetched_directory
=0; /* reset it */
343 if (router_reload_router_list()) {
346 /* give it one last try */
347 choice
= router_pick_directory_server_impl(requireother
, 0,
352 trusted_dir_server_t
*
353 router_get_trusteddirserver_by_digest(const char *digest
)
355 if (!trusted_dir_servers
)
358 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
360 if (!memcmp(ds
->digest
, digest
, DIGEST_LEN
))
367 /** Try to find a running trusted dirserver. If there are no running
368 * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
369 * set them all as running again, and try again.
370 * Other args are as in router_pick_trusteddirserver_impl().
372 trusted_dir_server_t
*
373 router_pick_trusteddirserver(int need_v1_support
,
376 int retry_if_no_servers
)
378 trusted_dir_server_t
*choice
;
380 choice
= router_pick_trusteddirserver_impl(need_v1_support
,
381 requireother
, fascistfirewall
);
382 if (choice
|| !retry_if_no_servers
)
385 info(LD_DIR
,"No trusted dirservers are reachable. Trying them all again.");
386 mark_all_trusteddirservers_up();
387 return router_pick_trusteddirserver_impl(need_v1_support
,
388 requireother
, fascistfirewall
);
391 /** Pick a random running verified directory server/mirror from our
393 * If <b>fascistfirewall</b> and we're not using a proxy,
394 * make sure the port we pick is allowed by options-\>firewallports.
395 * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
396 * choose a directory server new enough to support the v2 directory
399 static routerinfo_t
*
400 router_pick_directory_server_impl(int requireother
, int fascistfirewall
,
401 int for_v2_directory
)
403 routerinfo_t
*result
;
409 if (get_options()->HttpProxy
)
412 /* Find all the running dirservers we know about. */
413 sl
= smartlist_create();
414 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
416 if (!router
->is_running
|| !router
->dir_port
|| !router
->is_verified
)
418 if (requireother
&& router_is_me(router
))
420 if (fascistfirewall
) {
421 if (!fascist_firewall_allows_address(router
->addr
, router
->dir_port
))
424 /* Before 0.1.1.6-alpha, only trusted dirservers served status info.
425 * Before 0.1.1.7-alpha, retrieving nonexistent server IDs could bork
426 * the directory server.
428 if (for_v2_directory
&&
429 !(tor_version_as_new_as(router
->platform
,"0.1.1.7-alpha") ||
430 router_digest_is_trusted_dir(router
->identity_digest
)))
432 smartlist_add(sl
, router
);
435 result
= smartlist_choose(sl
);
440 /** Choose randomly from among the trusted dirservers that are up.
441 * If <b>fascistfirewall</b> and we're not using a proxy,
442 * make sure the port we pick is allowed by options-\>firewallports.
443 * If <b>requireother</b>, it cannot be us. If <b>need_v1_support</b>, choose
444 * a trusted authority for the v1 directory system.
446 static trusted_dir_server_t
*
447 router_pick_trusteddirserver_impl(int need_v1_support
,
448 int requireother
, int fascistfirewall
)
452 trusted_dir_server_t
*ds
;
453 sl
= smartlist_create();
454 me
= router_get_my_routerinfo();
456 if (!trusted_dir_servers
)
459 if (get_options()->HttpProxy
)
462 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, d
,
464 if (!d
->is_running
) continue;
465 if (need_v1_support
&& !d
->supports_v1_protocol
)
467 if (requireother
&& me
&&
468 !memcmp(me
->identity_digest
, d
->digest
, DIGEST_LEN
))
470 if (fascistfirewall
) {
471 if (!fascist_firewall_allows_address(d
->addr
, d
->dir_port
))
474 smartlist_add(sl
, d
);
477 ds
= smartlist_choose(sl
);
482 /** Go through and mark the authoritative dirservers as up. */
484 mark_all_trusteddirservers_up(void)
487 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
488 if (router_digest_is_trusted_dir(router
->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
,
497 dir
->n_networkstatus_failures
= 0;
500 last_networkstatus_download_attempted
= 0;
503 /** Reset all internal variables used to count failed downloads of network
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
)
519 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, dir
,
520 if (dir
->is_running
) return 0);
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.
528 routerlist_add_family(smartlist_t
*sl
, routerinfo_t
*router
)
533 if (!router
->declared_family
)
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)))
542 if (!r
->declared_family
)
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>.
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
;
570 return; /* nothing to do */
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
, {
582 if (!is_legal_nickname_or_hexdigest(nick
)) {
583 warn(LD_CONFIG
, "Nickname %s is misformed; skipping", nick
);
586 router
= router_get_by_nickname(nick
, warn_if_unnamed
);
587 warned
= smartlist_string_isin(warned_nicknames
, nick
);
589 if (router
->is_running
) {
590 smartlist_add(sl
,router
);
592 smartlist_string_remove(warned_nicknames
, nick
);
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
));
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.
616 router_nickname_is_in_list(routerinfo_t
*router
, const char *list
)
618 smartlist_t
*nickname_list
;
622 return 0; /* definitely not */
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
);
635 /** Add every router from our routerlist that is currently running to
639 router_add_running_routers_to_smartlist(smartlist_t
*sl
, int allow_unverified
,
640 int need_uptime
, int need_capacity
)
645 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
647 if (router
->is_running
&&
648 (router
->is_verified
||
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.
662 routerlist_find_my_routerinfo(void)
667 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
669 if (router_is_me(router
))
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
680 router_find_exact_exit_enclave(const char *address
, uint16_t port
)
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
)
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
706 router_is_unreliable(routerinfo_t
*router
, int need_uptime
, int need_capacity
)
708 if (need_uptime
&& router
->uptime
< ROUTER_REQUIRED_MIN_UPTIME
)
710 if (need_capacity
&& router
->bandwidthcapacity
< ROUTER_REQUIRED_MIN_BANDWIDTH
)
715 /** Remove from routerlist <b>sl</b> all routers who have a low uptime. */
717 routerlist_sl_remove_unreliable_routers(smartlist_t
*sl
)
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.
738 routerlist_sl_choose_by_bandwidth(smartlist_t
*sl
)
741 routerinfo_t
*router
;
742 smartlist_t
*bandwidths
;
743 uint32_t this_bw
, tmp
, total_bw
=0, rand_bw
;
746 /* First count the total bandwidth weight, and make a smartlist
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));
758 smartlist_add(bandwidths
, p
);
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 */
771 tor_assert(i
< smartlist_len(sl
));
772 p
= smartlist_get(bandwidths
, i
);
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.
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
);
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
);
825 routerlist_sl_remove_unreliable_routers(sl
);
827 choice
= routerlist_sl_choose_by_bandwidth(sl
);
829 choice
= smartlist_choose(sl
);
832 smartlist_free(excludednodes
);
834 warn(LD_CIRC
,"No available nodes when trying to choose node. Failing.");
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. */
843 router_hex_digest_matches(routerinfo_t
*router
, const char *hexdigest
)
845 char digest
[DIGEST_LEN
];
846 tor_assert(hexdigest
);
847 if (hexdigest
[0] == '$')
850 if (strlen(hexdigest
) != HEX_DIGEST_LEN
||
851 base16_decode(digest
, DIGEST_LEN
, hexdigest
, HEX_DIGEST_LEN
)<0)
853 return (!memcmp(digest
, router
->identity_digest
, DIGEST_LEN
));
856 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
857 * (case-insensitive), or if <b>router's</b> identity key digest
858 * matches a hexadecimal value stored in <b>nickname</b>. Return
859 * false otherwise. */
861 router_nickname_matches(routerinfo_t
*router
, const char *nickname
)
863 if (nickname
[0]!='$' && !strcasecmp(router
->nickname
, nickname
))
865 return router_hex_digest_matches(router
, nickname
);
868 /** Return the router in our routerlist whose (case-insensitive)
869 * nickname or (case-sensitive) hexadecimal key digest is
870 * <b>nickname</b>. Return NULL if no such router is known.
873 router_get_by_nickname(const char *nickname
, int warn_if_unnamed
)
876 char digest
[DIGEST_LEN
];
877 routerinfo_t
*best_match
=NULL
;
880 tor_assert(nickname
);
883 if (nickname
[0] == '$')
884 return router_get_by_hexdigest(nickname
);
885 if (server_mode(get_options()) &&
886 !strcasecmp(nickname
, get_options()->Nickname
))
887 return router_get_my_routerinfo();
889 maybedigest
= (strlen(nickname
) == HEX_DIGEST_LEN
) &&
890 (base16_decode(digest
,DIGEST_LEN
,nickname
,HEX_DIGEST_LEN
) == 0);
892 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
894 if (!strcasecmp(router
->nickname
, nickname
)) {
895 if (router
->is_named
)
901 } else if (maybedigest
&&
902 !memcmp(digest
, router
->identity_digest
, DIGEST_LEN
)) {
908 if (warn_if_unnamed
&& n_matches
> 1) {
909 smartlist_t
*fps
= smartlist_create();
910 int any_unwarned
= 0;
911 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
913 local_routerstatus_t
*rs
;
916 char fp
[HEX_DIGEST_LEN
+1];
917 if (strcasecmp(router
->nickname
, nickname
))
919 rs
=router_get_combined_status_by_digest(router
->identity_digest
);
920 if (!rs
->name_lookup_warned
) {
921 rs
->name_lookup_warned
= 1;
924 base16_encode(fp
, sizeof(fp
), router
->identity_digest
, DIGEST_LEN
);
925 dlen
= 32 + HEX_DIGEST_LEN
+ strlen(router
->address
);
926 desc
= tor_malloc(dlen
);
927 tor_snprintf(desc
, dlen
, "\"$%s\" for the one at %s:%d",
928 fp
, router
->address
, router
->or_port
);
929 smartlist_add(fps
, desc
);
932 char *alternatives
= smartlist_join_strings(fps
, "; ",0,NULL
);
933 warn(LD_CONFIG
, "There are multiple matches for the nickname \"%s\","
934 " but none is listed as named by the directory authories. "
935 "Choosing one arbitrarily. If you meant one in particular, "
936 "you should say %s.", nickname
, alternatives
);
937 tor_free(alternatives
);
939 SMARTLIST_FOREACH(fps
, char *, cp
, tor_free(cp
));
941 } else if (warn_if_unnamed
) {
942 local_routerstatus_t
*rs
=
943 router_get_combined_status_by_digest(best_match
->identity_digest
);
944 if (rs
&& !rs
->name_lookup_warned
) {
945 char fp
[HEX_DIGEST_LEN
+1];
946 base16_encode(fp
, sizeof(fp
), best_match
->identity_digest
, DIGEST_LEN
);
947 warn(LD_CONFIG
, "You specified a server \"%s\" by name, but the "
948 "directory authorities do not have a listing for this name. "
949 "To make sure you get the same server in the future, refer to "
950 "it by key, as \"$%s\".", nickname
, fp
);
951 rs
->name_lookup_warned
= 1;
960 /** Return true iff <b>digest</b> is the digest of the identity key of
961 * a trusted directory. */
963 router_digest_is_trusted_dir(const char *digest
)
965 if (!trusted_dir_servers
)
967 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
968 if (!memcmp(digest
, ent
->digest
, DIGEST_LEN
)) return 1);
972 /** Return the router in our routerlist whose hexadecimal key digest
973 * is <b>hexdigest</b>. Return NULL if no such router is known. */
975 router_get_by_hexdigest(const char *hexdigest
)
977 char digest
[DIGEST_LEN
];
979 tor_assert(hexdigest
);
982 if (hexdigest
[0]=='$')
984 if (strlen(hexdigest
) != HEX_DIGEST_LEN
||
985 base16_decode(digest
,DIGEST_LEN
,hexdigest
,HEX_DIGEST_LEN
) < 0)
988 return router_get_by_digest(digest
);
991 /** Return the router in our routerlist whose 20-byte key digest
992 * is <b>digest</b>. Return NULL if no such router is known. */
994 router_get_by_digest(const char *digest
)
998 if (!routerlist
) return NULL
;
1000 // routerlist_assert_ok(routerlist);
1002 return digestmap_get(routerlist
->identity_map
, digest
);
1005 /** Return the router in our routerlist whose 20-byte descriptor
1006 * is <b>digest</b>. Return NULL if no such router is known. */
1008 router_get_by_descriptor_digest(const char *digest
)
1012 if (!routerlist
) return NULL
;
1014 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1016 if (0 == memcmp(router
->signed_descriptor_digest
, digest
, DIGEST_LEN
))
1023 /** Return the current list of all known routers. */
1025 router_get_routerlist(void)
1028 routerlist
= tor_malloc_zero(sizeof(routerlist_t
));
1029 routerlist
->routers
= smartlist_create();
1030 routerlist
->old_routers
= smartlist_create();
1031 routerlist
->identity_map
= digestmap_new();
1032 routerlist
->desc_digest_map
= digestmap_new();
1037 /** Free all storage held by <b>router</b>. */
1039 routerinfo_free(routerinfo_t
*router
)
1044 tor_free(router
->signed_descriptor
);
1045 tor_free(router
->address
);
1046 tor_free(router
->nickname
);
1047 tor_free(router
->platform
);
1048 tor_free(router
->contact_info
);
1049 if (router
->onion_pkey
)
1050 crypto_free_pk_env(router
->onion_pkey
);
1051 if (router
->identity_pkey
)
1052 crypto_free_pk_env(router
->identity_pkey
);
1053 if (router
->declared_family
) {
1054 SMARTLIST_FOREACH(router
->declared_family
, char *, s
, tor_free(s
));
1055 smartlist_free(router
->declared_family
);
1057 addr_policy_free(router
->exit_policy
);
1061 /** Allocate a fresh copy of <b>router</b> */
1063 routerinfo_copy(const routerinfo_t
*router
)
1066 addr_policy_t
**e
, *tmp
;
1068 r
= tor_malloc(sizeof(routerinfo_t
));
1069 memcpy(r
, router
, sizeof(routerinfo_t
));
1071 r
->address
= tor_strdup(r
->address
);
1072 r
->nickname
= tor_strdup(r
->nickname
);
1073 r
->platform
= tor_strdup(r
->platform
);
1074 if (r
->signed_descriptor
)
1075 r
->signed_descriptor
= tor_strdup(r
->signed_descriptor
);
1077 r
->onion_pkey
= crypto_pk_dup_key(r
->onion_pkey
);
1078 if (r
->identity_pkey
)
1079 r
->identity_pkey
= crypto_pk_dup_key(r
->identity_pkey
);
1080 e
= &r
->exit_policy
;
1082 tmp
= tor_malloc(sizeof(addr_policy_t
));
1083 memcpy(tmp
,*e
,sizeof(addr_policy_t
));
1085 (*e
)->string
= tor_strdup((*e
)->string
);
1088 if (r
->declared_family
) {
1089 r
->declared_family
= smartlist_create();
1090 SMARTLIST_FOREACH(router
->declared_family
, const char *, s
,
1091 smartlist_add(r
->declared_family
, tor_strdup(s
)));
1096 /** Free all storage held by a routerlist <b>rl</b> */
1098 routerlist_free(routerlist_t
*rl
)
1101 digestmap_free(rl
->identity_map
, NULL
);
1102 digestmap_free(rl
->desc_digest_map
, NULL
);
1103 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
1104 routerinfo_free(r
));
1105 SMARTLIST_FOREACH(rl
->old_routers
, routerinfo_t
*, r
,
1106 routerinfo_free(r
));
1107 smartlist_free(rl
->routers
);
1108 smartlist_free(rl
->old_routers
);
1113 _routerlist_find_elt(smartlist_t
*sl
, routerinfo_t
*ri
, int idx
)
1115 if (idx
< 0 || smartlist_get(sl
, idx
) != ri
) {
1117 SMARTLIST_FOREACH(sl
, routerinfo_t
*, r
,
1126 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1129 routerlist_insert(routerlist_t
*rl
, routerinfo_t
*ri
)
1131 digestmap_set(rl
->identity_map
, ri
->identity_digest
, ri
);
1132 digestmap_set(rl
->desc_digest_map
, ri
->signed_descriptor_digest
, ri
);
1133 smartlist_add(rl
->routers
, ri
);
1134 // routerlist_assert_ok(rl);
1138 routerlist_insert_old(routerlist_t
*rl
, routerinfo_t
*ri
)
1140 if (get_options()->DirPort
) {
1141 digestmap_set(rl
->desc_digest_map
, ri
->signed_descriptor_digest
, ri
);
1142 smartlist_add(rl
->old_routers
, ri
);
1144 routerinfo_free(ri
);
1146 // routerlist_assert_ok(rl);
1149 /** Remove an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1150 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl->routers,
1151 * idx) == ri, we don't need to do a linear search over the list to decide
1152 * which to remove. We fill the gap in rl->routers with a later element in
1153 * the list, if any exists. <b>ri</b> is freed. */
1155 routerlist_remove(routerlist_t
*rl
, routerinfo_t
*ri
, int idx
, int make_old
)
1157 routerinfo_t
*ri_tmp
;
1158 idx
= _routerlist_find_elt(rl
->routers
, ri
, idx
);
1161 smartlist_del(rl
->routers
, idx
);
1162 ri_tmp
= digestmap_remove(rl
->identity_map
, ri
->identity_digest
);
1163 tor_assert(ri_tmp
== ri
);
1164 if (make_old
&& get_options()->DirPort
) {
1165 smartlist_add(rl
->old_routers
, ri
);
1167 ri_tmp
= digestmap_remove(rl
->desc_digest_map
,
1168 ri
->signed_descriptor_digest
);
1169 tor_assert(ri_tmp
== ri
);
1170 routerinfo_free(ri
);
1172 // routerlist_assert_ok(rl);
1176 routerlist_remove_old(routerlist_t
*rl
, routerinfo_t
*ri
, int idx
)
1178 routerinfo_t
*ri_tmp
;
1179 idx
= _routerlist_find_elt(rl
->old_routers
, ri
, idx
);
1182 smartlist_del(rl
->old_routers
, idx
);
1183 ri_tmp
= digestmap_remove(rl
->desc_digest_map
,
1184 ri
->signed_descriptor_digest
);
1185 tor_assert(ri_tmp
== ri
);
1186 routerinfo_free(ri
);
1187 routerlist_assert_ok(rl
);
1190 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
1191 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
1192 * smartlist_get(rl->routers, idx) == ri, we don't need to do a linear
1193 * search over the list to decide which to remove. We put ri_new in the same
1194 * index as ri_old, if possible. ri is freed as appropriate. */
1196 routerlist_replace(routerlist_t
*rl
, routerinfo_t
*ri_old
,
1197 routerinfo_t
*ri_new
, int idx
, int make_old
)
1199 tor_assert(ri_old
!= ri_new
);
1200 idx
= _routerlist_find_elt(rl
->routers
, ri_old
, idx
);
1202 smartlist_set(rl
->routers
, idx
, ri_new
);
1204 warn(LD_BUG
, "Appending entry from routerlist_replace.");
1205 routerlist_insert(rl
, ri_new
);
1208 if (memcmp(ri_old
->identity_digest
, ri_new
->identity_digest
, DIGEST_LEN
)) {
1209 /* digests don't match; digestmap_set won't replace */
1210 digestmap_remove(rl
->identity_map
, ri_old
->identity_digest
);
1212 digestmap_set(rl
->identity_map
, ri_new
->identity_digest
, ri_new
);
1213 digestmap_set(rl
->desc_digest_map
, ri_new
->signed_descriptor_digest
, ri_new
);
1215 if (make_old
&& get_options()->DirPort
) {
1216 smartlist_add(rl
->old_routers
, ri_old
);
1218 if (memcmp(ri_old
->signed_descriptor_digest
,
1219 ri_new
->signed_descriptor_digest
,
1221 /* digests don't match; digestmap_set didn't replace */
1222 digestmap_remove(rl
->desc_digest_map
, ri_old
->signed_descriptor_digest
);
1224 routerinfo_free(ri_old
);
1226 // routerlist_assert_ok(rl);
1229 /** Free all memory held by the routerlist module. */
1231 routerlist_free_all(void)
1234 routerlist_free(routerlist
);
1236 if (warned_nicknames
) {
1237 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
1238 smartlist_free(warned_nicknames
);
1239 warned_nicknames
= NULL
;
1241 if (warned_conflicts
) {
1242 SMARTLIST_FOREACH(warned_conflicts
, char *, cp
, tor_free(cp
));
1243 smartlist_free(warned_conflicts
);
1244 warned_conflicts
= NULL
;
1246 if (trusted_dir_servers
) {
1247 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
1248 trusted_dir_server_free(ds
));
1249 smartlist_free(trusted_dir_servers
);
1250 trusted_dir_servers
= NULL
;
1252 if (networkstatus_list
) {
1253 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
1254 networkstatus_free(ns
));
1255 smartlist_free(networkstatus_list
);
1256 networkstatus_list
= NULL
;
1258 if (routerstatus_list
) {
1259 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
1260 local_routerstatus_free(rs
));
1261 smartlist_free(routerstatus_list
);
1262 routerstatus_list
= NULL
;
1266 /** Free all storage held by the routerstatus object <b>rs</b>. */
1268 routerstatus_free(routerstatus_t
*rs
)
1273 /** Free all storage held by the local_routerstatus object <b>rs</b>. */
1275 local_routerstatus_free(local_routerstatus_t
*rs
)
1280 /** Free all storage held by the networkstatus object <b>ns</b>. */
1282 networkstatus_free(networkstatus_t
*ns
)
1284 tor_free(ns
->source_address
);
1285 tor_free(ns
->contact
);
1286 if (ns
->signing_key
)
1287 crypto_free_pk_env(ns
->signing_key
);
1288 tor_free(ns
->client_versions
);
1289 tor_free(ns
->server_versions
);
1291 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
*, rs
, routerstatus_free(rs
));
1292 smartlist_free(ns
->entries
);
1297 /** Forget that we have issued any router-related warnings, so that we'll
1298 * warn again if we see the same errors. */
1300 routerlist_reset_warnings(void)
1302 if (!warned_nicknames
)
1303 warned_nicknames
= smartlist_create();
1304 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
1305 smartlist_clear(warned_nicknames
); /* now the list is empty. */
1307 if (!warned_conflicts
)
1308 warned_conflicts
= smartlist_create();
1309 SMARTLIST_FOREACH(warned_conflicts
, char *, cp
, tor_free(cp
));
1310 smartlist_clear(warned_conflicts
); /* now the list is empty. */
1312 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
1313 rs
->name_lookup_warned
= 0);
1315 have_warned_about_unverified_status
= 0;
1316 have_warned_about_old_version
= 0;
1317 have_warned_about_new_version
= 0;
1320 /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
1322 router_mark_as_down(const char *digest
)
1324 routerinfo_t
*router
;
1327 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, d
,
1328 if (!memcmp(d
->digest
, digest
, DIGEST_LEN
))
1331 router
= router_get_by_digest(digest
);
1332 if (!router
) /* we don't seem to know about him in the first place */
1334 debug(LD_DIR
,"Marking router '%s' as down.",router
->nickname
);
1335 if (router_is_me(router
) && !we_are_hibernating())
1336 warn(LD_NET
, "We just marked ourself as down. Are your external addresses reachable?");
1337 router
->is_running
= 0;
1340 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
1341 * older entries (if any) with the same key. Note: Callers should not hold
1342 * their pointers to <b>router</b> if this function fails; <b>router</b>
1343 * will either be inserted into the routerlist or freed.
1345 * Returns >= 0 if the router was added; less than 0 if it was not.
1347 * If we're returning non-zero, then assign to *<b>msg</b> a static string
1348 * describing the reason for not liking the routerinfo.
1350 * If the return value is less than -1, there was a problem with the
1351 * routerinfo. If the return value is equal to -1, then the routerinfo was
1352 * fine, but out-of-date. If the return value is equal to 1, the
1353 * routerinfo was accepted, but we should notify the generator of the
1354 * descriptor using the message *<b>msg</b>.
1356 * This function should be called *after*
1357 * routers_update_status_from_networkstatus; subsequently, you should call
1358 * router_rebuild_store and control_event_descriptors_changed.
1360 * XXXX never replace your own descriptor.
1363 router_add_to_routerlist(routerinfo_t
*router
, const char **msg
,
1367 char id_digest
[DIGEST_LEN
];
1368 int authdir
= get_options()->AuthoritativeDir
;
1369 int authdir_verified
= 0;
1374 router_get_routerlist();
1376 /* XXXX NM If this assert doesn't trigger, we should remove the id_digest
1378 crypto_pk_get_digest(router
->identity_pkey
, id_digest
);
1379 tor_assert(!memcmp(id_digest
, router
->identity_digest
, DIGEST_LEN
));
1381 /* Make sure that we haven't already got this exact descriptor. */
1382 if (digestmap_get(routerlist
->desc_digest_map
,
1383 router
->signed_descriptor_digest
)) {
1384 info(LD_DIR
, "Dropping descriptor that we already have for router '%s'",
1386 *msg
= "Router descriptor was not new.";
1387 routerinfo_free(router
);
1392 if (authdir_wants_to_reject_router(router
, msg
)) {
1393 routerinfo_free(router
);
1396 authdir_verified
= router
->is_verified
;
1399 if (! router->xx_is_recognized && !from_cache) {
1400 log_fn(LOG_WARN, "Dropping unrecognized descriptor for router '%s'",
1402 routerinfo_free(router);
1408 /* If we have a router with this name, and the identity key is the same,
1409 * choose the newer one. If the identity key has changed, drop the router.
1411 for (i
= 0; i
< smartlist_len(routerlist
->routers
); ++i
) {
1412 routerinfo_t
*old_router
= smartlist_get(routerlist
->routers
, i
);
1413 if (!crypto_pk_cmp_keys(router
->identity_pkey
,old_router
->identity_pkey
)) {
1414 if (router
->published_on
<= old_router
->published_on
) {
1415 /* Same key, but old */
1416 debug(LD_DIR
, "Skipping not-new descriptor for router '%s'",
1418 routerlist_insert_old(routerlist
, router
);
1419 *msg
= "Router descriptor was not new.";
1422 /* Same key, new. */
1423 int unreachable
= 0;
1424 debug(LD_DIR
, "Replacing entry for router '%s/%s' [%s]",
1425 router
->nickname
, old_router
->nickname
,
1426 hex_str(id_digest
,DIGEST_LEN
));
1427 if (router
->addr
== old_router
->addr
&&
1428 router
->or_port
== old_router
->or_port
) {
1429 /* these carry over when the address and orport are unchanged.*/
1430 router
->last_reachable
= old_router
->last_reachable
;
1431 router
->testing_since
= old_router
->testing_since
;
1432 router
->num_unreachable_notifications
=
1433 old_router
->num_unreachable_notifications
;
1436 dirserv_thinks_router_is_blatantly_unreachable(router
, time(NULL
))) {
1437 if (router
->num_unreachable_notifications
>= 3) {
1439 notice(LD_DIR
, "Notifying server '%s' that it's unreachable. (ContactInfo '%s', platform '%s').",
1440 router
->nickname
, router
->contact_info
? router
->contact_info
: "",
1441 router
->platform
? router
->platform
: "");
1443 info(LD_DIR
,"'%s' may be unreachable -- the %d previous descriptors were thought to be unreachable.", router
->nickname
, router
->num_unreachable_notifications
);
1444 router
->num_unreachable_notifications
++;
1447 routerlist_replace(routerlist
, old_router
, router
, i
, 1);
1449 router_append_to_journal(router
->signed_descriptor
,
1450 router
->signed_descriptor_len
);
1451 directory_set_dirty();
1452 *msg
= unreachable
? "Dirserver believes your ORPort is unreachable" :
1453 authdir_verified
? "Verified server updated" :
1454 "Unverified server updated. (Have you sent us your key fingerprint?)";
1455 return unreachable
? 1 : 0;
1457 } else if (!strcasecmp(router
->nickname
, old_router
->nickname
)) {
1458 /* nicknames match, keys don't. */
1459 if (router
->is_named
) {
1460 /* The new verified router replaces the old one; remove the
1461 * old one. And carry on to the end of the list, in case
1462 * there are more old unverified routers with this nickname
1464 /* mark-for-close connections using the old key, so we can
1465 * make new ones with the new key.
1468 while ((conn
= connection_get_by_identity_digest(
1469 old_router
->identity_digest
, CONN_TYPE_OR
))) {
1470 // And LD_OR? XXXXNM
1471 info(LD_DIR
,"Closing conn to router '%s'; there is now a named router with that name.",
1472 old_router
->nickname
);
1473 connection_mark_for_close(conn
);
1475 routerlist_remove(routerlist
, old_router
, i
--, 0);
1476 } else if (old_router
->is_named
) {
1477 /* Can't replace a verified router with an unverified one. */
1478 debug(LD_DIR
, "Skipping unverified entry for verified router '%s'",
1480 routerinfo_free(router
);
1481 *msg
= "Already have named router with same nickname and different key.";
1486 /* We haven't seen a router with this name before. Add it to the end of
1488 routerlist_insert(routerlist
, router
);
1490 router_append_to_journal(router
->signed_descriptor
,
1491 router
->signed_descriptor_len
);
1492 directory_set_dirty();
1496 #define MAX_DESCRIPTORS_PER_ROUTER 5
1499 _compare_old_routers_by_identity(const void **_a
, const void **_b
)
1502 const routerinfo_t
*r1
= *_a
, *r2
= *_b
;
1503 if ((i
= memcmp(r1
->identity_digest
, r2
->identity_digest
, DIGEST_LEN
)))
1505 return r1
->published_on
- r2
->published_on
;
1508 struct duration_idx_t
{
1515 _compare_duration_idx(const void *_d1
, const void *_d2
)
1517 const struct duration_idx_t
*d1
= _d1
;
1518 const struct duration_idx_t
*d2
= _d2
;
1519 return d1
->duration
- d2
->duration
;
1522 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
1523 * must contain routerinfo_t with the same identity and with publication time
1524 * in ascending order. Remove members from this range until there are no more
1525 * than MAX_DESCRIPTORS_PER_ROUTER remaining. Start by removing the oldest
1526 * members from before <b>cutoff</b>, then remove members which were current
1527 * for the lowest amount of time. The order of members of old_routers at
1528 * indices <b>lo</b> or higher may be changed.
1531 routerlist_remove_old_cached_routers_with_id(time_t cutoff
, int lo
, int hi
)
1533 int i
, n
= hi
-lo
+1, n_extra
;
1535 struct duration_idx_t
*lifespans
;
1537 smartlist_t
*lst
= routerlist
->old_routers
;
1540 tor_assert(hi
< smartlist_len(lst
));
1541 tor_assert(lo
<= hi
);
1542 ident
= ((routerinfo_t
*)smartlist_get(lst
, lo
))->identity_digest
;
1543 for (i
= lo
+1; i
<= hi
; ++i
) {
1544 routerinfo_t
*r
= smartlist_get(lst
, i
);
1545 tor_assert(!memcmp(ident
, r
->identity_digest
, DIGEST_LEN
));
1549 /* Check whether we need to do anything at all. */
1550 n_extra
= n
- MAX_DESCRIPTORS_PER_ROUTER
;
1555 lifespans
= tor_malloc_zero(sizeof(struct duration_idx_t
)*n
);
1556 rmv
= tor_malloc_zero(sizeof(uint8_t)*n
);
1557 /* Set lifespans to contain the lifespan and index of each server. */
1558 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
1559 for (i
= lo
; i
<= hi
; ++i
) {
1560 routerinfo_t
*r
= smartlist_get(lst
, i
);
1561 routerinfo_t
*r_next
;
1562 lifespans
[i
-lo
].idx
= i
;
1564 r_next
= smartlist_get(lst
, i
+1);
1565 tor_assert(r
->published_on
<= r_next
->published_on
);
1566 lifespans
[i
-lo
].duration
= r_next
->published_on
- r
->published_on
;
1569 lifespans
[i
-lo
].duration
= INT_MAX
;
1571 if (r
->published_on
< cutoff
&& n_rmv
< n_extra
) {
1573 lifespans
[i
-lo
].old
= 1;
1578 if (n_rmv
< n_extra
) {
1580 * We aren't removing enough servers for being old. Sort lifespans by
1581 * the duration of liveness, and remove the ones we're not already going to
1582 * remove based on how long they were alive.
1584 qsort(lifespans
, n
, sizeof(struct duration_idx_t
), _compare_duration_idx
);
1585 for (i
= 0; i
< n
&& n_rmv
< n_extra
; ++i
) {
1586 if (!lifespans
[i
].old
) {
1587 rmv
[lifespans
[i
].idx
-lo
] = 1;
1593 for (i
= hi
; i
>= lo
; --i
) {
1595 routerlist_remove_old(routerlist
, smartlist_get(lst
, i
), i
);
1598 tor_free(lifespans
);
1601 /** Deactivate any routers from the routerlist that are more than <b>age</b>
1602 * seconds old; remove old routers from the list of cached routers if we have
1606 routerlist_remove_old_routers(void)
1609 const char *cur_id
= NULL
;
1611 routerinfo_t
*router
;
1615 cutoff
= time(NULL
) - ROUTER_MAX_AGE
;
1616 /* Remove old members of routerlist->routers. */
1617 for (i
= 0; i
< smartlist_len(routerlist
->routers
); ++i
) {
1618 router
= smartlist_get(routerlist
->routers
, i
);
1619 if (router
->published_on
<= cutoff
) {
1620 /* Too old. Remove it. */
1621 info(LD_DIR
, "Forgetting obsolete (too old) routerinfo for router '%s'",
1623 routerlist_remove(routerlist
, router
, i
--, 1);
1627 /* Now we're looking at routerlist->old_routers. First, check whether
1628 * we have too many router descriptors, total. We're okay with having too
1629 * many for some given router, so long as the total number doesn't approach
1630 * MAX_DESCRIPTORS_PER_ROUTER*len(router).
1632 if (smartlist_len(routerlist
->old_routers
) <
1633 smartlist_len(routerlist
->routers
) * (MAX_DESCRIPTORS_PER_ROUTER
- 1))
1636 smartlist_sort(routerlist
->old_routers
, _compare_old_routers_by_identity
);
1638 /* Iterate through the list from back to front, so when we remove descriptors
1639 * we don't mess up groups we haven't gotten to. */
1640 for (i
= smartlist_len(routerlist
->old_routers
)-1; i
>= 0; --i
) {
1641 routerinfo_t
*r
= smartlist_get(routerlist
->old_routers
, i
);
1643 cur_id
= r
->identity_digest
;
1646 if (memcmp(cur_id
, r
->identity_digest
, DIGEST_LEN
)) {
1647 routerlist_remove_old_cached_routers_with_id(cutoff
, i
+1, hi
);
1652 routerlist_remove_old_cached_routers_with_id(cutoff
, 0, hi
);
1653 routerlist_assert_ok(routerlist
);
1657 * Code to parse a single router descriptor and insert it into the
1658 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
1659 * descriptor was well-formed but could not be added; and 1 if the
1660 * descriptor was added.
1662 * If we don't add it and <b>msg</b> is not NULL, then assign to
1663 * *<b>msg</b> a static string describing the reason for refusing the
1666 * This is used only by the controller.
1669 router_load_single_router(const char *s
, const char **msg
)
1676 if (!(ri
= router_parse_entry_from_string(s
, NULL
))) {
1677 warn(LD_DIR
, "Error parsing router descriptor; dropping.");
1678 *msg
= "Couldn't parse router descriptor.";
1681 if (router_is_me(ri
)) {
1682 warn(LD_DIR
, "Router's identity key matches mine; dropping.");
1683 *msg
= "Router's identity key matches mine.";
1684 routerinfo_free(ri
);
1688 lst
= smartlist_create();
1689 smartlist_add(lst
, ri
);
1690 routers_update_status_from_networkstatus(lst
, 0, 1);
1692 if (router_add_to_routerlist(ri
, msg
, 0)<0) {
1693 warn(LD_DIR
, "Couldn't add router to list: %s Dropping.",
1694 *msg
?*msg
:"(No message).");
1695 /* we've already assigned to *msg now, and ri is already freed */
1696 smartlist_free(lst
);
1699 control_event_descriptors_changed(lst
);
1700 smartlist_free(lst
);
1701 debug(LD_DIR
, "Added router to list");
1706 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
1707 * routers into our directory. If <b>from_cache</b> is false, the routers
1708 * have come from the network: cache them.
1710 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1711 * uppercased identity fingerprints. Do not update any router whose
1712 * fingerprint is not on the list; after updating a router, remove its
1713 * fingerprint from the list.
1716 router_load_routers_from_string(const char *s
, int from_cache
,
1717 smartlist_t
*requested_fingerprints
)
1719 smartlist_t
*routers
= smartlist_create(), *changed
= smartlist_create();
1720 char fp
[HEX_DIGEST_LEN
+1];
1723 router_parse_list_from_string(&s
, routers
);
1725 routers_update_status_from_networkstatus(routers
, !from_cache
, from_cache
);
1727 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
,
1729 base16_encode(fp
, sizeof(fp
), ri
->identity_digest
, DIGEST_LEN
);
1730 if (requested_fingerprints
) {
1731 if (smartlist_string_isin(requested_fingerprints
, fp
)) {
1732 smartlist_string_remove(requested_fingerprints
, fp
);
1735 smartlist_join_strings(requested_fingerprints
," ",0,NULL
);
1736 warn(LD_DIR
, "We received a router descriptor with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp
, requested
);
1737 tor_free(requested
);
1738 routerinfo_free(ri
);
1743 if (router_add_to_routerlist(ri
, &msg
, from_cache
) >= 0)
1744 smartlist_add(changed
, ri
);
1747 if (smartlist_len(changed
))
1748 control_event_descriptors_changed(changed
);
1750 routerlist_assert_ok(routerlist
);
1751 router_rebuild_store(0);
1753 smartlist_free(routers
);
1754 smartlist_free(changed
);
1757 /** Helper: return a newly allocated string containing the name of the filename
1758 * where we plan to cache <b>ns</b>. */
1760 networkstatus_get_cache_filename(const networkstatus_t
*ns
)
1762 const char *datadir
= get_options()->DataDirectory
;
1763 size_t len
= strlen(datadir
)+64;
1764 char fp
[HEX_DIGEST_LEN
+1];
1765 char *fn
= tor_malloc(len
+1);
1766 base16_encode(fp
, HEX_DIGEST_LEN
+1, ns
->identity_digest
, DIGEST_LEN
);
1767 tor_snprintf(fn
, len
, "%s/cached-status/%s",datadir
,fp
);
1771 /** Helper for smartlist_sort: Compare two networkstatus objects by
1772 * publication date. */
1774 _compare_networkstatus_published_on(const void **_a
, const void **_b
)
1776 const networkstatus_t
*a
= *_a
, *b
= *_b
;
1777 if (a
->published_on
< b
->published_on
)
1779 else if (a
->published_on
> b
->published_on
)
1785 /** How far in the future do we allow a network-status to get before removing
1787 #define NETWORKSTATUS_ALLOW_SKEW (48*60*60)
1788 /** Given a string <b>s</b> containing a network status that we received at
1789 * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
1790 * store it, and put it into our cache is necessary.
1792 * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
1793 * own networkstatus_t (if we're a directory server).
1795 * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
1798 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1799 * uppercased identity fingerprints. Do not update any networkstatus whose
1800 * fingerprint is not on the list; after updating a networkstatus, remove its
1801 * fingerprint from the list.
1803 * Return 0 on success, -1 on failure.
1805 * Callers should make sure that routers_update_all_from_networkstatus() is
1806 * invoked after this function succeeds.
1809 router_set_networkstatus(const char *s
, time_t arrived_at
,
1810 networkstatus_source_t source
, smartlist_t
*requested_fingerprints
)
1812 networkstatus_t
*ns
;
1816 trusted_dir_server_t
*trusted_dir
;
1817 char fp
[HEX_DIGEST_LEN
+1];
1818 char published
[ISO_TIME_LEN
+1];
1820 ns
= networkstatus_parse_from_string(s
);
1822 warn(LD_DIR
, "Couldn't parse network status.");
1825 if (!(trusted_dir
=router_get_trusteddirserver_by_digest(ns
->identity_digest
))) {
1826 info(LD_DIR
, "Network status was signed, but not by an authoritative directory we recognize.");
1827 networkstatus_free(ns
);
1831 if (arrived_at
> now
)
1834 ns
->received_on
= arrived_at
;
1836 format_iso_time(published
, ns
->published_on
);
1838 if (ns
->published_on
> now
+ NETWORKSTATUS_ALLOW_SKEW
) {
1839 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
);
1843 if (!networkstatus_list
)
1844 networkstatus_list
= smartlist_create();
1846 if (source
== NS_FROM_DIR
&& router_digest_is_me(ns
->identity_digest
)) {
1847 /* Don't replace our own networkstatus when we get it from somebody else. */
1848 networkstatus_free(ns
);
1852 base16_encode(fp
, HEX_DIGEST_LEN
+1, ns
->identity_digest
, DIGEST_LEN
);
1854 if (requested_fingerprints
) {
1855 if (smartlist_string_isin(requested_fingerprints
, fp
)) {
1856 smartlist_string_remove(requested_fingerprints
, fp
);
1858 char *requested
= smartlist_join_strings(requested_fingerprints
," ",0,NULL
);
1859 warn(LD_DIR
, "We received a network status with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp
, requested
);
1860 tor_free(requested
);
1865 if (source
!= NS_FROM_CACHE
)
1866 trusted_dir
->n_networkstatus_failures
= 0;
1869 for (i
=0; i
< smartlist_len(networkstatus_list
); ++i
) {
1870 networkstatus_t
*old_ns
= smartlist_get(networkstatus_list
, i
);
1872 if (!memcmp(old_ns
->identity_digest
, ns
->identity_digest
, DIGEST_LEN
)) {
1873 if (!memcmp(old_ns
->networkstatus_digest
,
1874 ns
->networkstatus_digest
, DIGEST_LEN
)) {
1875 /* Same one we had before. */
1876 networkstatus_free(ns
);
1878 "Not replacing network-status from %s (published %s); "
1879 "we already have it.",
1880 trusted_dir
->description
, published
);
1881 if (old_ns
->received_on
< arrived_at
) {
1882 if (source
!= NS_FROM_CACHE
) {
1883 char *fn
= networkstatus_get_cache_filename(old_ns
);
1884 /* We use mtime to tell when it arrived, so update that. */
1888 old_ns
->received_on
= arrived_at
;
1891 } else if (old_ns
->published_on
>= ns
->published_on
) {
1892 char old_published
[ISO_TIME_LEN
+1];
1893 format_iso_time(old_published
, old_ns
->published_on
);
1895 "Not replacing network-status from %s (published %s);"
1896 " we have a newer one (published %s) for this authority.",
1897 trusted_dir
->description
, published
,
1899 networkstatus_free(ns
);
1902 networkstatus_free(old_ns
);
1903 smartlist_set(networkstatus_list
, i
, ns
);
1911 smartlist_add(networkstatus_list
, ns
);
1913 info(LD_DIR
, "Setting networkstatus %s %s (published %s)",
1914 source
== NS_FROM_CACHE
?"cached from":
1915 (source
==NS_FROM_DIR
?"downloaded from":"generated for"),
1916 trusted_dir
->description
, published
);
1917 networkstatus_list_has_changed
= 1;
1919 smartlist_sort(networkstatus_list
, _compare_networkstatus_published_on
);
1921 if (source
!= NS_FROM_CACHE
&& !skewed
) {
1922 char *fn
= networkstatus_get_cache_filename(ns
);
1923 if (write_str_to_file(fn
, s
, 0)<0) {
1924 notice(LD_FS
, "Couldn't write cached network status to \"%s\"", fn
);
1929 networkstatus_list_update_recent(now
);
1931 if (get_options()->DirPort
&& !skewed
)
1932 dirserv_set_cached_networkstatus_v2(s
,
1933 ns
->identity_digest
,
1939 /** How old do we allow a network-status to get before removing it completely? */
1940 #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
1941 /** Remove all very-old network_status_t objects from memory and from the
1944 networkstatus_list_clean(time_t now
)
1947 if (!networkstatus_list
)
1950 for (i
= 0; i
< smartlist_len(networkstatus_list
); ++i
) {
1951 networkstatus_t
*ns
= smartlist_get(networkstatus_list
, i
);
1952 char *fname
= NULL
;;
1953 if (ns
->published_on
+ MAX_NETWORKSTATUS_AGE
> now
)
1955 /* Okay, this one is too old. Remove it from the list, and delete it
1956 * from the cache. */
1957 smartlist_del(networkstatus_list
, i
--);
1958 fname
= networkstatus_get_cache_filename(ns
);
1959 if (file_status(fname
) == FN_FILE
) {
1960 info(LD_DIR
, "Removing too-old networkstatus in %s", fname
);
1964 if (get_options()->DirPort
) {
1965 dirserv_set_cached_networkstatus_v2(NULL
, ns
->identity_digest
, 0);
1967 networkstatus_free(ns
);
1971 /** Helper for bsearching a list of routerstatus_t pointers.*/
1973 _compare_digest_to_routerstatus_entry(const void *_key
, const void **_member
)
1975 const char *key
= _key
;
1976 const routerstatus_t
*rs
= *_member
;
1977 return memcmp(key
, rs
->identity_digest
, DIGEST_LEN
);
1980 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
1981 * NULL if none was found. */
1982 static routerstatus_t
*
1983 networkstatus_find_entry(networkstatus_t
*ns
, const char *digest
)
1985 return smartlist_bsearch(ns
->entries
, digest
,
1986 _compare_digest_to_routerstatus_entry
);
1989 /** Return the consensus view of the status of the router whose digest is
1990 * <b>digest</b>, or NULL if we don't know about any such router. */
1991 local_routerstatus_t
*
1992 router_get_combined_status_by_digest(const char *digest
)
1994 if (!routerstatus_list
)
1996 return smartlist_bsearch(routerstatus_list
, digest
,
1997 _compare_digest_to_routerstatus_entry
);
2002 routerdesc_digest_is_recognized(const char *identity
, const char *digest
)
2005 if (!networkstatus_list
)
2008 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
2010 if (!(rs
= networkstatus_find_entry(ns
, identity
)))
2012 if (!memcmp(rs
->descriptor_digest
, digest
, DIGEST_LEN
))
2018 /* XXXX These should be configurable, perhaps? NM */
2019 #define AUTHORITY_NS_CACHE_INTERVAL 10*60
2020 #define NONAUTHORITY_NS_CACHE_INTERVAL 15*60
2021 /** We are a directory server, and so cache network_status documents.
2022 * Initiate downloads as needed to update them. For authorities, this means
2023 * asking each trusted directory for its network-status. For caches, this
2024 * means asking a random authority for all network-statuses.
2027 update_networkstatus_cache_downloads(time_t now
)
2029 int authority
= authdir_mode(get_options());
2031 authority
? AUTHORITY_NS_CACHE_INTERVAL
: NONAUTHORITY_NS_CACHE_INTERVAL
;
2033 if (last_networkstatus_download_attempted
+ interval
>= now
)
2035 if (!trusted_dir_servers
)
2038 last_networkstatus_download_attempted
= now
;
2041 /* An authority launches a separate connection for everybody. */
2042 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
2044 char resource
[HEX_DIGEST_LEN
+6];
2045 if (router_digest_is_me(ds
->digest
))
2047 if (connection_get_by_type_addr_port_purpose(
2048 CONN_TYPE_DIR
, ds
->addr
, ds
->dir_port
,
2049 DIR_PURPOSE_FETCH_NETWORKSTATUS
)) {
2050 /* We are already fetching this one. */
2053 strlcpy(resource
, "fp/", sizeof(resource
));
2054 base16_encode(resource
+3, sizeof(resource
)-3, ds
->digest
, DIGEST_LEN
);
2055 strlcat(resource
, ".z", sizeof(resource
));
2056 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS
,resource
,1);
2059 /* A non-authority cache launches one connection to a random authority. */
2060 /* (Check whether we're currently fetching network-status objects.) */
2061 if (!connection_get_by_type_purpose(CONN_TYPE_DIR
,
2062 DIR_PURPOSE_FETCH_NETWORKSTATUS
))
2063 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS
,"all.z",1);
2067 /*XXXX Should these be configurable? NM*/
2068 /** How old (in seconds) can a network-status be before we try replacing it? */
2069 #define NETWORKSTATUS_MAX_VALIDITY (48*60*60)
2070 /** How long (in seconds) does a client wait after getting a network status
2071 * before downloading the next in sequence? */
2072 #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
2073 /* How many times do we allow a networkstatus download to fail before we
2074 * assume that the authority isn't publishing? */
2075 #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
2076 /** We are not a directory cache or authority. Update our network-status list
2077 * by launching a new directory fetch for enough network-status documents "as
2078 * necessary". See function comments for implementation details.
2081 update_networkstatus_client_downloads(time_t now
)
2083 int n_live
= 0, needed
= 0, n_running_dirservers
, n_dirservers
, i
;
2084 int most_recent_idx
= -1;
2085 trusted_dir_server_t
*most_recent
= NULL
;
2086 time_t most_recent_received
= 0;
2087 char *resource
, *cp
;
2088 size_t resource_len
;
2090 if (connection_get_by_type_purpose(CONN_TYPE_DIR
,
2091 DIR_PURPOSE_FETCH_NETWORKSTATUS
))
2094 /* This is a little tricky. We want to download enough network-status
2095 * objects so that we have at least half of them under
2096 * NETWORKSTATUS_MAX_VALIDITY publication time. We want to download a new
2097 * *one* if the most recent one's publication time is under
2098 * NETWORKSTATUS_CLIENT_DL_INTERVAL.
2100 if (!trusted_dir_servers
|| !smartlist_len(trusted_dir_servers
))
2102 n_dirservers
= n_running_dirservers
= smartlist_len(trusted_dir_servers
);
2103 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
2105 networkstatus_t
*ns
= networkstatus_get_by_digest(ds
->digest
);
2108 if (ds
->n_networkstatus_failures
> NETWORKSTATUS_N_ALLOWABLE_FAILURES
) {
2109 --n_running_dirservers
;
2112 if (ns
->published_on
> now
-NETWORKSTATUS_MAX_VALIDITY
)
2114 if (!most_recent
|| ns
->received_on
> most_recent_received
) {
2115 most_recent_idx
= ds_sl_idx
; /* magic variable from FOREACH */
2117 most_recent_received
= ns
->received_on
;
2121 /* Download enough so we have at least half live, but no more than all the
2122 * trusted dirservers we know.
2124 if (n_live
< (n_dirservers
/2)+1)
2125 needed
= (n_dirservers
/2)+1-n_live
;
2126 if (needed
> n_running_dirservers
)
2127 needed
= n_running_dirservers
;
2130 info(LD_DIR
, "For %d/%d running directory servers, we have %d live"
2131 " network-status documents. Downloading %d.",
2132 n_running_dirservers
, n_dirservers
, n_live
, needed
);
2134 /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
2135 if (n_running_dirservers
&&
2136 most_recent_received
< now
-NETWORKSTATUS_CLIENT_DL_INTERVAL
&& needed
< 1) {
2137 info(LD_DIR
, "Our most recent network-status document (from %s) "
2138 "is %d seconds old; downloading another.",
2139 most_recent
?most_recent
->description
:"nobody",
2140 (int)(now
-most_recent_received
));
2147 /* If no networkstatus was found, choose a dirserver at random as "most
2149 if (most_recent_idx
<0)
2150 most_recent_idx
= crypto_rand_int(n_dirservers
);
2152 /* Build a request string for all the resources we want. */
2153 resource_len
= needed
* (HEX_DIGEST_LEN
+1) + 6;
2154 resource
= tor_malloc(resource_len
);
2155 memcpy(resource
, "fp/", 3);
2157 for (i
= most_recent_idx
+1; needed
; ++i
) {
2158 trusted_dir_server_t
*ds
;
2159 if (i
>= n_dirservers
)
2161 ds
= smartlist_get(trusted_dir_servers
, i
);
2162 if (ds
->n_networkstatus_failures
> NETWORKSTATUS_N_ALLOWABLE_FAILURES
)
2164 base16_encode(cp
, HEX_DIGEST_LEN
+1, ds
->digest
, DIGEST_LEN
);
2165 cp
+= HEX_DIGEST_LEN
;
2170 memcpy(cp
, ".z", 3);
2171 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS
, resource
, 1);
2177 update_networkstatus_downloads(time_t now
)
2179 or_options_t
*options
= get_options();
2180 if (server_mode(options
) && options
->DirPort
)
2181 update_networkstatus_cache_downloads(time(NULL
));
2183 update_networkstatus_client_downloads(time(NULL
));
2186 /** Decide whether a given addr:port is definitely accepted,
2187 * definitely rejected, probably accepted, or probably rejected by a
2188 * given policy. If <b>addr</b> is 0, we don't know the IP of the
2189 * target address. If <b>port</b> is 0, we don't know the port of the
2192 * For now, the algorithm is pretty simple: we look for definite and
2193 * uncertain matches. The first definite match is what we guess; if
2194 * it was preceded by no uncertain matches of the opposite policy,
2195 * then the guess is definite; otherwise it is probable. (If we
2196 * have a known addr and port, all matches are definite; if we have an
2197 * unknown addr/port, any address/port ranges other than "all" are
2200 * We could do better by assuming that some ranges never match typical
2201 * addresses (127.0.0.1, and so on). But we'll try this for now.
2203 addr_policy_result_t
2204 router_compare_addr_to_addr_policy(uint32_t addr
, uint16_t port
,
2205 addr_policy_t
*policy
)
2207 int maybe_reject
= 0;
2208 int maybe_accept
= 0;
2211 addr_policy_t
*tmpe
;
2213 for (tmpe
=policy
; tmpe
; tmpe
=tmpe
->next
) {
2216 /* Address is unknown. */
2217 if ((port
>= tmpe
->prt_min
&& port
<= tmpe
->prt_max
) ||
2218 (!port
&& tmpe
->prt_min
<=1 && tmpe
->prt_max
>=65535)) {
2219 /* The port definitely matches. */
2220 if (tmpe
->msk
== 0) {
2226 /* The port maybe matches. */
2230 /* Address is known */
2231 if ((addr
& tmpe
->msk
) == (tmpe
->addr
& tmpe
->msk
)) {
2232 if (port
>= tmpe
->prt_min
&& port
<= tmpe
->prt_max
) {
2233 /* Exact match for the policy */
2241 if (tmpe
->policy_type
== ADDR_POLICY_REJECT
)
2247 if (tmpe
->policy_type
== ADDR_POLICY_ACCEPT
) {
2248 /* If we already hit a clause that might trigger a 'reject', than we
2249 * can't be sure of this certain 'accept'.*/
2250 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
: ADDR_POLICY_ACCEPTED
;
2252 return maybe_accept
? ADDR_POLICY_PROBABLY_REJECTED
: ADDR_POLICY_REJECTED
;
2256 /* accept all by default. */
2257 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
: ADDR_POLICY_ACCEPTED
;
2260 /** Return 1 if all running sufficiently-stable routers will reject
2261 * addr:port, return 0 if any might accept it. */
2263 router_exit_policy_all_routers_reject(uint32_t addr
, uint16_t port
,
2266 addr_policy_result_t r
;
2267 if (!routerlist
) return 1;
2269 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
2271 if (router
->is_running
&&
2272 !router_is_unreliable(router
, need_uptime
, 0)) {
2273 r
= router_compare_addr_to_addr_policy(addr
, port
, router
->exit_policy
);
2274 if (r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
)
2275 return 0; /* this one could be ok. good enough. */
2278 return 1; /* all will reject. */
2282 * If <b>policy</b> implicitly allows connections to any port in the
2283 * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
2284 * part of the policy that allows it, and return 1. Else return 0.
2286 * A policy allows an IP:Port combination <em>implicitly</em> if
2287 * it is included in a *: pattern, or in a fallback pattern.
2290 policy_includes_addr_mask_implicitly(addr_policy_t
*policy
,
2291 uint32_t addr
, uint32_t mask
,
2292 addr_policy_t
**policy_out
)
2295 tor_assert(policy_out
);
2297 addr2
= addr
| ~mask
;
2298 for (; policy
; policy
=policy
->next
) {
2299 /* Does this policy cover all of the address range we're looking at? */
2300 /* Boolean logic time: range X is contained in range Y if, for
2301 * each bit B, all possible values of B in X are values of B in Y.
2302 * In "addr", we have every fixed bit set to its value, and every
2303 * free bit set to 0. In "addr2", we have every fixed bit set to
2304 * its value, and every free bit set to 1. So if addr and addr2 are
2305 * both in the policy, the range is covered by the policy.
2307 uint32_t p_addr
= policy
->addr
& policy
->msk
;
2308 if (p_addr
== (addr
& policy
->msk
) &&
2309 p_addr
== (addr2
& policy
->msk
) &&
2310 (policy
->prt_min
<= 1 && policy
->prt_max
== 65535)) {
2313 /* Does this policy cover some of the address range we're looking at? */
2314 /* Boolean logic time: range X and range Y intersect if there is
2315 * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
2316 * This is FALSE iff there is some bit b where Xmask == yMask == 1
2317 * and Xaddr != Yaddr. So if X intersects with Y iff at every
2318 * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
2319 * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
2321 if ((policy
->addr
& policy
->msk
& mask
) == (addr
& policy
->msk
) &&
2322 policy
->policy_type
== ADDR_POLICY_ACCEPT
) {
2323 *policy_out
= policy
;
2331 /** If <b>policy</b> implicitly allows connections to any port on
2332 * 127.*, 192.168.*, etc, then warn (if <b>warn</b> is set) and return
2333 * true. Else return false.
2336 exit_policy_implicitly_allows_local_networks(addr_policy_t
*policy
,
2342 uint32_t addr
; uint32_t mask
; const char *network
;
2343 } private_networks
[] = {
2344 { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
2345 { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
2346 { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
2347 { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
2348 { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
2351 for (i
=0; private_networks
[i
].addr
; ++i
) {
2353 /* log_fn(LOG_INFO,"Checking network %s", private_networks[i].network); */
2354 if (policy_includes_addr_mask_implicitly(
2355 policy
, private_networks
[i
].addr
, private_networks
[i
].mask
, &p
)) {
2357 warn(LD_CONFIG
, "Exit policy %s implicitly accepts %s",
2358 p
?p
->string
:"(default)",
2359 private_networks
[i
].network
);
2367 /** Return true iff <b>router</b> does not permit exit streams.
2370 router_exit_policy_rejects_all(routerinfo_t
*router
)
2372 return router_compare_addr_to_addr_policy(0, 0, router
->exit_policy
)
2373 == ADDR_POLICY_REJECTED
;
2376 /** Add to the list of authorized directory servers one at
2377 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
2378 * <b>address</b> is NULL, add ourself. */
2380 add_trusted_dir_server(const char *nickname
, const char *address
,
2381 uint16_t port
, const char *digest
, int supports_v1
)
2383 trusted_dir_server_t
*ent
;
2385 char *hostname
= NULL
;
2387 if (!trusted_dir_servers
)
2388 trusted_dir_servers
= smartlist_create();
2390 if (!address
) { /* The address is us; we should guess. */
2391 if (resolve_my_address(get_options(), &a
, &hostname
) < 0) {
2392 warn(LD_CONFIG
, "Couldn't find a suitable address when adding ourself as a trusted directory server.");
2396 if (tor_lookup_hostname(address
, &a
)) {
2397 warn(LD_CONFIG
, "Unable to lookup address for directory server at %s",
2401 hostname
= tor_strdup(address
);
2405 ent
= tor_malloc_zero(sizeof(trusted_dir_server_t
));
2406 ent
->nickname
= nickname
? tor_strdup(nickname
) : NULL
;
2407 ent
->address
= hostname
;
2409 ent
->dir_port
= port
;
2410 ent
->is_running
= 1;
2411 ent
->supports_v1_protocol
= supports_v1
;
2412 memcpy(ent
->digest
, digest
, DIGEST_LEN
);
2414 dlen
= 64 + strlen(hostname
) + (nickname
?strlen(nickname
):0);
2415 ent
->description
= tor_malloc(dlen
);
2417 tor_snprintf(ent
->description
, dlen
, "directory server \"%s\" at %s:%d",
2418 nickname
, hostname
, (int)port
);
2420 tor_snprintf(ent
->description
, dlen
, "directory server at %s:%d",
2421 hostname
, (int)port
);
2423 smartlist_add(trusted_dir_servers
, ent
);
2426 /** Free storage held in <b>ds</b> */
2428 trusted_dir_server_free(trusted_dir_server_t
*ds
)
2430 tor_free(ds
->nickname
);
2431 tor_free(ds
->description
);
2432 tor_free(ds
->address
);
2436 /** Remove all members from the list of trusted dir servers. */
2438 clear_trusted_dir_servers(void)
2440 if (trusted_dir_servers
) {
2441 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
2442 trusted_dir_server_free(ent
));
2443 smartlist_clear(trusted_dir_servers
);
2445 trusted_dir_servers
= smartlist_create();
2449 /** Return the network status with a given identity digest. */
2451 networkstatus_get_by_digest(const char *digest
)
2453 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
2455 if (!memcmp(ns
->identity_digest
, digest
, DIGEST_LEN
))
2461 /** If the network-status list has changed since the last time we called this
2462 * function, update the status of every router from the network-status list.
2465 routers_update_all_from_networkstatus(void)
2467 #define SELF_OPINION_INTERVAL 90*60
2470 if (!routerlist
|| !networkstatus_list
||
2471 (!networkstatus_list_has_changed
&& !routerstatus_list_has_changed
))
2475 if (networkstatus_list_has_changed
)
2476 routerstatus_list_update_from_networkstatus(now
);
2478 routers_update_status_from_networkstatus(routerlist
->routers
, 0, 0);
2480 me
= router_get_my_routerinfo();
2481 if (me
&& !have_warned_about_unverified_status
) {
2482 int n_recent
= 0, n_listing
= 0, n_valid
= 0, n_named
= 0;
2484 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
2486 if (ns
->received_on
+ SELF_OPINION_INTERVAL
< now
)
2489 if (!(rs
= networkstatus_find_entry(ns
, me
->identity_digest
)))
2498 if (n_recent
>= 2 && n_listing
>= 2) {
2499 if (n_valid
<= n_recent
/2) {
2500 warn(LD_GENERAL
, "%d/%d recent directory servers list us as invalid. Please consider sending your identity fingerprint to the tor-ops.",
2501 n_recent
-n_valid
, n_recent
);
2502 have_warned_about_unverified_status
= 1;
2503 } else if (n_named
<= n_recent
/2) {
2504 warn(LD_GENERAL
, "%d/%d recent directory servers list us as unnamed. Please consider sending your identity fingerprint to the tor-ops.",
2505 n_recent
-n_valid
, n_recent
);
2506 have_warned_about_unverified_status
= 1;
2511 helper_nodes_set_status_from_directory();
2513 if (!have_warned_about_old_version
) {
2515 int n_recommended
= 0;
2516 int is_server
= server_mode(get_options());
2517 version_status_t consensus
= VS_RECOMMENDED
;
2518 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
2520 version_status_t vs
;
2521 if (!ns
->recommends_versions
||
2522 ns
->received_on
+ SELF_OPINION_INTERVAL
< now
)
2524 vs
= tor_version_is_obsolete(
2525 VERSION
, is_server
? ns
->server_versions
: ns
->client_versions
);
2526 if (vs
== VS_RECOMMENDED
)
2528 if (n_recent
++ == 0) {
2530 } else if (consensus
!= vs
) {
2531 consensus
= version_status_join(consensus
, vs
);
2534 if (n_recent
> 2 && n_recommended
< n_recent
/2) {
2535 if (consensus
== VS_NEW
|| consensus
== VS_NEW_IN_SERIES
) {
2536 if (!have_warned_about_new_version
) {
2537 notice(LD_GENERAL
, "This version of Tor (%s) is newer than any recommended version%s, according to %d/%d recent network statuses.",
2538 VERSION
, consensus
== VS_NEW_IN_SERIES
? " in its series" : "",
2539 n_recent
-n_recommended
, n_recent
);
2540 have_warned_about_new_version
= 1;
2543 notice(LD_GENERAL
, "This version of Tor (%s) is %s, according to %d/%d recent network statuses.",
2544 VERSION
, consensus
== VS_OLD
? "obsolete" : "not recommended",
2545 n_recent
-n_recommended
, n_recent
);
2546 have_warned_about_old_version
= 1;
2549 info(LD_GENERAL
, "%d/%d recent directories think my version is ok.",
2550 n_recommended
, n_recent
);
2554 routerstatus_list_has_changed
= 0;
2557 /** Allow any network-status newer than this to influence our view of who's
2559 #define DEFAULT_RUNNING_INTERVAL 60*60
2560 /** If possible, always allow at least this many network-statuses to influence
2561 * our view of who's running. */
2562 #define MIN_TO_INFLUENCE_RUNNING 3
2564 /** Change the is_recent field of each member of networkstatus_list so that
2565 * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
2566 * at least the MIN_TO_INFLUENCE_RUNNING most recent members are resent, and no
2567 * others are recent. Set networkstatus_list_has_changed if anything happeed.
2570 networkstatus_list_update_recent(time_t now
)
2572 int n_statuses
, n_recent
, changed
, i
;
2573 char published
[ISO_TIME_LEN
+1];
2575 if (!networkstatus_list
)
2578 n_statuses
= smartlist_len(networkstatus_list
);
2581 for (i
=n_statuses
-1; i
>= 0; --i
) {
2582 networkstatus_t
*ns
= smartlist_get(networkstatus_list
, i
);
2583 trusted_dir_server_t
*ds
=
2584 router_get_trusteddirserver_by_digest(ns
->identity_digest
);
2585 const char *src
= ds
?ds
->description
:ns
->source_address
;
2586 if (n_recent
< MIN_TO_INFLUENCE_RUNNING
||
2587 ns
->published_on
+ DEFAULT_RUNNING_INTERVAL
> now
) {
2588 if (!ns
->is_recent
) {
2589 format_iso_time(published
, ns
->published_on
);
2591 "Networkstatus from %s (published %s) is now \"recent\"",
2598 if (ns
->is_recent
) {
2599 format_iso_time(published
, ns
->published_on
);
2601 "Networkstatus from %s (published %s) is no longer \"recent\"",
2609 networkstatus_list_has_changed
= 1;
2612 /** Update our view of router status (as stored in routerstatus_list) from
2613 * the current set of network status documents (as stored in networkstatus_list).
2614 * Do nothing unless the network status list has changed since the last time
2615 * this function was called.
2618 routerstatus_list_update_from_networkstatus(time_t now
)
2620 or_options_t
*options
= get_options();
2621 int n_trusted
, n_statuses
, n_recent
=0, n_naming
=0;
2625 networkstatus_t
**networkstatus
;
2626 smartlist_t
*result
;
2628 char conflict
[DIGEST_LEN
];
2630 networkstatus_list_update_recent(now
);
2632 if (!networkstatus_list_has_changed
)
2634 if (!networkstatus_list
)
2635 networkstatus_list
= smartlist_create();
2636 if (!routerstatus_list
)
2637 routerstatus_list
= smartlist_create();
2638 if (!trusted_dir_servers
)
2639 trusted_dir_servers
= smartlist_create();
2640 if (!warned_conflicts
)
2641 warned_conflicts
= smartlist_create();
2643 n_trusted
= smartlist_len(trusted_dir_servers
);
2644 n_statuses
= smartlist_len(networkstatus_list
);
2646 if (n_statuses
< (n_trusted
/2)+1) {
2647 /* Not enough statuses to adjust status. */
2648 notice(LD_DIR
,"Not enough statuses to update router status list. (%d/%d)",
2649 n_statuses
, n_trusted
);
2653 info(LD_DIR
, "Rebuilding router status list.");
2655 index
= tor_malloc(sizeof(int)*n_statuses
);
2656 size
= tor_malloc(sizeof(int)*n_statuses
);
2657 networkstatus
= tor_malloc(sizeof(networkstatus_t
*)*n_statuses
);
2658 for (i
= 0; i
< n_statuses
; ++i
) {
2660 networkstatus
[i
] = smartlist_get(networkstatus_list
, i
);
2661 size
[i
] = smartlist_len(networkstatus
[i
]->entries
);
2662 if (networkstatus
[i
]->binds_names
)
2664 if (networkstatus
[i
]->is_recent
)
2668 name_map
= strmap_new();
2669 memset(conflict
, 0xff, sizeof(conflict
));
2670 for (i
= 0; i
< n_statuses
; ++i
) {
2671 if (!networkstatus
[i
]->binds_names
)
2673 SMARTLIST_FOREACH(networkstatus
[i
]->entries
, routerstatus_t
*, rs
,
2675 const char *other_digest
;
2678 other_digest
= strmap_get_lc(name_map
, rs
->nickname
);
2679 warned
= smartlist_string_isin(warned_conflicts
, rs
->nickname
);
2680 if (!other_digest
) {
2681 strmap_set_lc(name_map
, rs
->nickname
, rs
->identity_digest
);
2683 smartlist_string_remove(warned_conflicts
, rs
->nickname
);
2684 } else if (memcmp(other_digest
, rs
->identity_digest
, DIGEST_LEN
) &&
2685 other_digest
!= conflict
) {
2687 int should_warn
= options
->DirPort
&& options
->AuthoritativeDir
;
2688 char fp1
[HEX_DIGEST_LEN
+1];
2689 char fp2
[HEX_DIGEST_LEN
+1];
2690 base16_encode(fp1
, sizeof(fp1
), other_digest
, DIGEST_LEN
);
2691 base16_encode(fp2
, sizeof(fp2
), rs
->identity_digest
, DIGEST_LEN
);
2692 log_fn(should_warn
? LOG_WARN
: LOG_INFO
, LD_DIR
,
2693 "Naming authorities disagree about which key goes with %s. ($%s vs $%s)",
2694 rs
->nickname
, fp1
, fp2
);
2695 strmap_set_lc(name_map
, rs
->nickname
, conflict
);
2696 smartlist_add(warned_conflicts
, tor_strdup(rs
->nickname
));
2700 smartlist_string_remove(warned_conflicts
, rs
->nickname
);
2705 result
= smartlist_create();
2707 /* Iterate through all of the sorted routerstatus lists in step.
2709 * - For 0 <= i < n_statuses: index[i] is an index into
2710 * networkstatus[i]->entries, which has size[i] elements.
2711 * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
2712 * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
2713 * networkstatus[i2]->entries[index[i2]]->identity_digest.
2715 * (That is, the indices are always advanced past lower digest before
2719 int n_running
=0, n_named
=0, n_valid
=0, n_listing
=0;
2720 const char *the_name
= NULL
;
2721 local_routerstatus_t
*rs_out
, *rs_old
;
2722 routerstatus_t
*rs
, *most_recent
;
2723 networkstatus_t
*ns
;
2724 const char *lowest
= NULL
;
2725 /* Find out which of the digests appears first. */
2726 for (i
= 0; i
< n_statuses
; ++i
) {
2727 if (index
[i
] < size
[i
]) {
2728 rs
= smartlist_get(networkstatus
[i
]->entries
, index
[i
]);
2729 if (!lowest
|| memcmp(rs
->identity_digest
, lowest
, DIGEST_LEN
)<0)
2730 lowest
= rs
->identity_digest
;
2734 /* We're out of routers. Great! */
2737 /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
2738 * match "lowest" are next in order. Iterate over them, incrementing those
2739 * index[i] as we go. */
2742 for (i
= 0; i
< n_statuses
; ++i
) {
2743 if (index
[i
] >= size
[i
])
2745 ns
= networkstatus
[i
];
2746 rs
= smartlist_get(ns
->entries
, index
[i
]);
2747 if (memcmp(rs
->identity_digest
, lowest
, DIGEST_LEN
))
2751 if (!most_recent
|| rs
->published_on
> most_recent
->published_on
)
2753 if (rs
->is_named
&& ns
->binds_names
) {
2755 the_name
= rs
->nickname
;
2756 if (!strcasecmp(rs
->nickname
, the_name
)) {
2758 } else if (strcmp(the_name
,"**mismatch**")) {
2759 char hd
[HEX_DIGEST_LEN
+1];
2760 base16_encode(hd
, HEX_DIGEST_LEN
+1, rs
->identity_digest
, DIGEST_LEN
);
2761 if (! smartlist_string_isin(warned_conflicts
, hd
)) {
2762 warn(LD_DIR
, "Naming authorities disagree about nicknames for $%s (\"%s\" vs \"%s\")",
2763 hd
, the_name
, rs
->nickname
);
2764 smartlist_add(warned_conflicts
, tor_strdup(hd
));
2766 the_name
= "**mismatch**";
2771 if (rs
->is_running
&& ns
->is_recent
)
2774 rs_out
= tor_malloc_zero(sizeof(local_routerstatus_t
));
2775 memcpy(&rs_out
->status
, most_recent
, sizeof(routerstatus_t
));
2776 if ((rs_old
= router_get_combined_status_by_digest(lowest
))) {
2777 rs_out
->n_download_failures
= rs_old
->n_download_failures
;
2778 rs_out
->next_attempt_at
= rs_old
->next_attempt_at
;
2779 rs_out
->name_lookup_warned
= rs_old
->name_lookup_warned
;
2781 smartlist_add(result
, rs_out
);
2782 debug(LD_DIR
, "Router '%s' is listed by %d/%d directories, "
2783 "named by %d/%d, validated by %d/%d, and %d/%d recent directories "
2784 "think it's running.",
2785 rs_out
->status
.nickname
,
2786 n_listing
, n_statuses
, n_named
, n_naming
, n_valid
, n_statuses
,
2787 n_running
, n_recent
);
2788 rs_out
->status
.is_named
= 0;
2789 if (the_name
&& strcmp(the_name
, "**mismatch**") && n_named
> 0) {
2790 const char *d
= strmap_get_lc(name_map
, the_name
);
2791 if (d
&& d
!= conflict
)
2792 rs_out
->status
.is_named
= 1;
2793 if (smartlist_string_isin(warned_conflicts
, rs_out
->status
.nickname
))
2794 smartlist_string_remove(warned_conflicts
, rs_out
->status
.nickname
);
2796 if (rs_out
->status
.is_named
)
2797 strlcpy(rs_out
->status
.nickname
, the_name
, sizeof(rs_out
->status
.nickname
));
2798 rs_out
->status
.is_valid
= n_valid
> n_statuses
/2;
2799 rs_out
->status
.is_running
= n_running
> n_recent
/2;
2801 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
2802 local_routerstatus_free(rs
));
2803 smartlist_free(routerstatus_list
);
2804 routerstatus_list
= result
;
2806 tor_free(networkstatus
);
2809 strmap_free(name_map
, NULL
);
2811 networkstatus_list_has_changed
= 0;
2812 routerstatus_list_has_changed
= 1;
2815 /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
2816 * is_named, is_verified, and is_running fields according to our current
2817 * networkstatus_t documents. */
2819 routers_update_status_from_networkstatus(smartlist_t
*routers
, int reset_failures
, int assume_recognized
)
2821 trusted_dir_server_t
*ds
;
2822 local_routerstatus_t
*rs
;
2823 or_options_t
*options
= get_options();
2824 int authdir
= options
->AuthoritativeDir
;
2825 int namingdir
= options
->AuthoritativeDir
&&
2826 options
->NamingAuthoritativeDir
;
2828 if (!routerstatus_list
)
2831 SMARTLIST_FOREACH(routers
, routerinfo_t
*, router
,
2833 rs
= router_get_combined_status_by_digest(router
->identity_digest
);
2834 ds
= router_get_trusteddirserver_by_digest(router
->identity_digest
);
2840 router
->is_named
= rs
->status
.is_named
;
2843 /* If we're an authdir, don't believe others. */
2844 router
->is_verified
= rs
->status
.is_valid
;
2845 router
->is_running
= rs
->status
.is_running
;
2847 if (router
->is_running
&& ds
) {
2848 ds
->n_networkstatus_failures
= 0;
2850 if (assume_recognized
) {
2851 router
->xx_is_recognized
= 1;
2853 if (!router
->xx_is_recognized
) {
2854 router
->xx_is_recognized
= routerdesc_digest_is_recognized(
2855 router
->identity_digest
, router
->signed_descriptor_digest
);
2857 router
->xx_is_extra_new
= router
->published_on
> rs
->status
.published_on
;
2859 if (reset_failures
&& router
->xx_is_recognized
) {
2860 rs
->n_download_failures
= 0;
2861 rs
->next_attempt_at
= 0;
2866 /** Return new list of ID fingerprints for superseded routers. A router is
2867 * superseded if any network-status has a router with a different digest
2868 * published more recently, or if it is listed in the network-status but not
2869 * in the router list.
2871 static smartlist_t
*
2872 router_list_downloadable(void)
2874 #define MAX_OLD_SERVER_DOWNLOAD_RATE 2*60*60
2875 int n_conns
, i
, n_downloadable
= 0;
2876 connection_t
**carray
;
2877 smartlist_t
*superseded
= smartlist_create();
2878 smartlist_t
*downloading
;
2879 time_t now
= time(NULL
);
2880 int mirror
= server_mode(get_options()) && get_options()->DirPort
;
2881 /* these are just used for logging */
2882 int n_not_ready
= 0, n_in_progress
= 0, n_uptodate
= 0, n_skip_old
= 0,
2883 n_obsolete
= 0, xx_n_unrecognized
= 0, xx_n_extra_new
= 0, xx_n_both
= 0,
2886 if (!routerstatus_list
)
2889 get_connection_array(&carray
, &n_conns
);
2891 routerstatus_list_update_from_networkstatus(now
);
2893 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
2895 if (rs
->status
.published_on
+ ROUTER_MAX_AGE
< now
) {
2896 rs
->should_download
= 0;
2898 } if (rs
->next_attempt_at
< now
) {
2899 rs
->should_download
= 1;
2903 char fp[HEX_DIGEST_LEN+1];
2904 base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
2905 log_fn(LOG_NOTICE, "Not yet ready to download %s (%d more seconds)", fp,
2906 (int)(rs->next_attempt_at-now));
2908 rs
->should_download
= 0;
2913 downloading
= smartlist_create();
2914 for (i
= 0; i
< n_conns
; ++i
) {
2915 connection_t
*conn
= carray
[i
];
2916 if (conn
->type
== CONN_TYPE_DIR
&&
2917 conn
->purpose
== DIR_PURPOSE_FETCH_SERVERDESC
&&
2918 !conn
->marked_for_close
) {
2919 if (!strcmpstart(conn
->requested_resource
, "all"))
2921 dir_split_resource_into_fingerprints(conn
->requested_resource
,
2922 downloading
, NULL
, 1);
2926 if (n_downloadable
) {
2927 SMARTLIST_FOREACH(downloading
, const char *, d
,
2929 local_routerstatus_t
*rs
;
2930 if ((rs
= router_get_combined_status_by_digest(d
)) && rs
->should_download
) {
2931 rs
->should_download
= 0;
2937 SMARTLIST_FOREACH(downloading
, char *, cp
, tor_free(cp
));
2938 smartlist_free(downloading
);
2939 if (!n_downloadable
)
2942 if (routerlist
&& n_downloadable
) {
2943 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
2945 local_routerstatus_t
*rs
;
2946 if (!(rs
= router_get_combined_status_by_digest(ri
->identity_digest
)) ||
2947 !rs
->should_download
) {
2948 // log_fn(LOG_NOTICE, "No status for %s", fp);
2951 if (!ri
->xx_is_recognized
) {
2952 ++xx_n_unrecognized
;
2953 if (ri
->xx_is_extra_new
)
2956 if (ri
->xx_is_extra_new
)
2959 /* Change this "or" to be an "and" once dirs generate hashes right.
2960 * Remove the version check once older versions are uncommon.
2962 if (!memcmp(ri
->signed_descriptor_digest
, rs
->status
.descriptor_digest
,
2964 rs
->status
.published_on
<= ri
->published_on
) {
2966 rs
->should_download
= 0;
2968 } else if (!mirror
&&
2970 !tor_version_as_new_as(ri
->platform
, "0.1.1.6-alpha") &&
2971 ri
->published_on
+ MAX_OLD_SERVER_DOWNLOAD_RATE
> now
) {
2972 /* Same digest, or date is up-to-date, or we have a comparatively recent
2973 * server with an old version.
2974 * No need to download it. */
2975 // log_fn(LOG_NOTICE, "Up-to-date status for %s", fp);
2977 if (!ri
->xx_is_recognized
)
2979 rs
->should_download
= 0;
2982 char t1[ISO_TIME_LEN+1];
2983 char t2[ISO_TIME_LEN+1];
2984 format_iso_time(t1, rs->satus.published_on);
2985 format_iso_time(t2, ri->published_on);
2986 log_fn(LOG_NOTICE, "Out-of-date status for %s %s (%d %d) [%s %s]", fp,
2988 !memcmp(ri->signed_descriptor_digest,rs->status.descriptor_digest,
2990 rs->published_on < ri->published_on,
2996 info(LD_DIR
, "%d router descriptors are downloadable; "
2997 "%d are up to date; %d are in progress; "
2998 "%d are not ready to retry; "
2999 "%d are not published recently enough to be worthwhile; "
3000 "%d are running pre-0.1.1.6 Tors and aren't stale enough to replace. "
3001 "%d have unrecognized descriptor hashes; %d are newer than the dirs "
3002 "have told us about; %d are both unrecognized and newer than any "
3003 "publication date in the networkstatus; %d are both "
3004 "unrecognized and running a pre-0.1.1.6 version.",
3005 n_downloadable
, n_uptodate
, n_in_progress
, n_not_ready
,
3006 n_obsolete
, n_skip_old
, xx_n_unrecognized
, xx_n_extra_new
, xx_n_both
,
3009 if (!n_downloadable
)
3012 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
3014 if (rs
->should_download
) {
3015 char *fp
= tor_malloc(HEX_DIGEST_LEN
+1);
3016 base16_encode(fp
, HEX_DIGEST_LEN
+1, rs
->status
.identity_digest
, DIGEST_LEN
);
3017 smartlist_add(superseded
, fp
);
3024 /** Initiate new router downloads as needed.
3026 * We only allow one router descriptor download at a time.
3027 * If we have less than two network-status documents, we ask
3028 * a directory for "all descriptors."
3029 * Otherwise, we ask for all descriptors that we think are different
3030 * from what we have.
3033 update_router_descriptor_downloads(time_t now
)
3035 #define MAX_DL_PER_REQUEST 128
3036 #define MIN_DL_PER_REQUEST 4
3037 #define MIN_REQUESTS 3
3038 #define MAX_DL_TO_DELAY 16
3039 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST 10*60
3040 #define MAX_SERVER_INTERVAL_WITHOUT_REQUEST 1*60
3041 smartlist_t
*downloadable
= NULL
;
3043 int dirserv
= server_mode(get_options()) && get_options()->DirPort
;
3044 int should_delay
, n_downloadable
;
3045 if (!networkstatus_list
|| smartlist_len(networkstatus_list
)<2)
3049 notice(LD_DIR
, "Launching request for all routers");
3050 last_routerdesc_download_attempted
= now
;
3051 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC
,"all.z",1);
3055 downloadable
= router_list_downloadable();
3056 n_downloadable
= smartlist_len(downloadable
);
3057 if (n_downloadable
>= MAX_DL_TO_DELAY
) {
3059 "There are enough downloadable routerdescs to launch requests.");
3061 } else if (n_downloadable
== 0) {
3062 debug(LD_DIR
, "No routerdescs need to be downloaded.");
3066 should_delay
= (last_routerdesc_download_attempted
+
3067 MAX_SERVER_INTERVAL_WITHOUT_REQUEST
) > now
;
3069 should_delay
= (last_routerdesc_download_attempted
+
3070 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST
) > now
;
3073 debug(LD_DIR
, "There are not many downloadable routerdescs; waiting till we have some more.");
3075 info(LD_DIR
, "There are not many downloadable routerdescs, but we've been waiting long enough (%d seconds). Downloading.",
3076 (int)(now
-last_routerdesc_download_attempted
));
3079 if (! should_delay
) {
3080 int i
, j
, n_per_request
=MAX_DL_PER_REQUEST
;
3081 size_t r_len
= MAX_DL_PER_REQUEST
*(HEX_DIGEST_LEN
+1)+16;
3082 char *resource
= tor_malloc(r_len
);
3085 n_per_request
= (n_downloadable
+MIN_REQUESTS
-1) / MIN_REQUESTS
;
3086 if (n_per_request
> MAX_DL_PER_REQUEST
)
3087 n_per_request
= MAX_DL_PER_REQUEST
;
3088 if (n_per_request
< MIN_DL_PER_REQUEST
)
3089 n_per_request
= MIN_DL_PER_REQUEST
;
3091 info(LD_DIR
, "Launching %d request%s for %d router%s, %d at a time",
3092 (n_downloadable
+n_per_request
-1)/n_per_request
,
3093 n_downloadable
>n_per_request
?"s":"",
3094 n_downloadable
, n_downloadable
>1?"s":"", n_per_request
);
3095 for (i
=0; i
< n_downloadable
; i
+= n_per_request
) {
3096 char *cp
= resource
;
3097 memcpy(resource
, "fp/", 3);
3099 for (j
=i
; j
< i
+n_per_request
&& j
< n_downloadable
; ++j
) {
3100 memcpy(cp
, smartlist_get(downloadable
, j
), HEX_DIGEST_LEN
);
3101 cp
+= HEX_DIGEST_LEN
;
3104 memcpy(cp
-1, ".z", 3);
3105 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC
,resource
,1);
3107 last_routerdesc_download_attempted
= now
;
3110 SMARTLIST_FOREACH(downloadable
, char *, c
, tor_free(c
));
3111 smartlist_free(downloadable
);
3114 /** Return true iff we have enough networkstatus and router information to
3115 * start building circuits. Right now, this means "at least 2 networkstatus
3116 * documents, and at least 1/4 of expected routers." */
3118 router_have_minimum_dir_info(void)
3121 if (!networkstatus_list
|| smartlist_len(networkstatus_list
)<2 ||
3124 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
3125 tot
+= smartlist_len(ns
->entries
));
3126 avg
= tot
/ smartlist_len(networkstatus_list
);
3127 return smartlist_len(routerlist
->routers
) > (avg
/4);
3130 /** Reset the descriptor download failure count on all routers, so that we
3131 * can retry any long-failed routers immediately.
3134 router_reset_descriptor_download_failures(void)
3136 if (!routerstatus_list
)
3138 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
3140 rs
->n_download_failures
= 0;
3141 rs
->next_attempt_at
= 0;
3143 last_routerdesc_download_attempted
= 0;
3146 /** Return true iff the only differences between r1 and r2 are such that
3147 * would not cause a recent (post 0.1.1.6) dirserver to republish.
3150 router_differences_are_cosmetic(routerinfo_t
*r1
, routerinfo_t
*r2
)
3152 tor_assert(r1
&& r2
);
3154 /* post-0.1.1.6 servers know what they're doing. */
3155 if (tor_version_as_new_as(r1
->platform
, "0.1.1.6-alpha") ||
3156 tor_version_as_new_as(r2
->platform
, "0.1.1.6-alpha"))
3159 /* r1 should be the one that was published first. */
3160 if (r1
->published_on
> r2
->published_on
) {
3161 routerinfo_t
*ri_tmp
= r2
;
3166 /* If any key fields differ, they're different. */
3167 if (strcasecmp(r1
->address
, r2
->address
) ||
3168 strcasecmp(r1
->nickname
, r2
->nickname
) ||
3169 r1
->or_port
!= r2
->or_port
||
3170 r1
->dir_port
!= r2
->dir_port
||
3171 crypto_pk_cmp_keys(r1
->onion_pkey
, r2
->onion_pkey
) ||
3172 crypto_pk_cmp_keys(r1
->identity_pkey
, r2
->identity_pkey
) ||
3173 strcasecmp(r1
->platform
, r2
->platform
) ||
3174 (r1
->contact_info
&& !r2
->contact_info
) || /* contact_info is optional */
3175 (!r1
->contact_info
&& r2
->contact_info
) ||
3176 (r1
->contact_info
&& r2
->contact_info
&& strcasecmp(r1
->contact_info
, r2
->contact_info
)) ||
3177 r1
->is_hibernating
!= r2
->is_hibernating
||
3178 config_cmp_addr_policies(r1
->exit_policy
, r2
->exit_policy
))
3180 if ((r1
->declared_family
== NULL
) != (r2
->declared_family
== NULL
))
3182 if (r1
->declared_family
&& r2
->declared_family
) {
3184 if (smartlist_len(r1
->declared_family
)!=smartlist_len(r2
->declared_family
))
3186 n
= smartlist_len(r1
->declared_family
);
3187 for (i
=0; i
< n
; ++i
) {
3188 if (strcasecmp(smartlist_get(r1
->declared_family
, i
),
3189 smartlist_get(r2
->declared_family
, i
)))
3194 /* Did bandwidth change a lot? */
3195 if ((r1
->bandwidthcapacity
< r2
->bandwidthcapacity
/2) ||
3196 (r2
->bandwidthcapacity
< r1
->bandwidthcapacity
/2))
3199 /* Did more than 12 hours pass? */
3200 if (r1
->published_on
+ 12*60*60 < r2
->published_on
)
3203 /* Did uptime fail to increase by approximately the amount we would think,
3204 * give or take 30 minutes? */
3205 if (abs(r2
->uptime
- (r1
->uptime
+ (r2
->published_on
-r1
->published_on
)))>30*60)
3208 /* Otherwise, the difference is cosmetic. */
3213 routerlist_assert_ok(routerlist_t
*rl
)
3215 digestmap_iter_t
*iter
;
3219 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
3221 r2
= digestmap_get(rl
->identity_map
, r
->identity_digest
);
3222 tor_assert(r
== r2
);
3223 r2
= digestmap_get(rl
->desc_digest_map
, r
->signed_descriptor_digest
);
3224 tor_assert(r
== r2
);
3226 SMARTLIST_FOREACH(rl
->old_routers
, routerinfo_t
*, r
,
3228 r2
= digestmap_get(rl
->identity_map
, r
->identity_digest
);
3229 tor_assert(r
!= r2
);
3230 r2
= digestmap_get(rl
->desc_digest_map
, r
->signed_descriptor_digest
);
3231 tor_assert(r
== r2
);
3233 iter
= digestmap_iter_init(rl
->identity_map
);
3234 while (!digestmap_iter_done(iter
)) {
3238 digestmap_iter_get(iter
, &d
, &_r
);
3240 tor_assert(!memcmp(r
->identity_digest
, d
, DIGEST_LEN
));
3241 iter
= digestmap_iter_next(rl
->identity_map
, iter
);
3243 iter
= digestmap_iter_init(rl
->desc_digest_map
);
3244 while (!digestmap_iter_done(iter
)) {
3248 digestmap_iter_get(iter
, &d
, &_r
);
3250 tor_assert(!memcmp(r
->signed_descriptor_digest
, d
, DIGEST_LEN
));
3251 iter
= digestmap_iter_next(rl
->desc_digest_map
, iter
);