1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
6 const char routerlist_c_id
[] =
12 * maintain and access the global list of routerinfos for known
18 /****************************************************************************/
20 /* static function prototypes */
21 static routerstatus_t
*router_pick_directory_server_impl(int requireother
,
23 int for_v2_directory
);
24 static routerstatus_t
*router_pick_trusteddirserver_impl(
25 int need_v1_authority
, int requireother
, int fascistfirewall
);
26 static void mark_all_trusteddirservers_up(void);
27 static int router_nickname_is_in_list(routerinfo_t
*router
, const char *list
);
28 static int router_nickname_matches(routerinfo_t
*router
, const char *nickname
);
29 static void routerstatus_list_update_from_networkstatus(time_t now
);
30 static void local_routerstatus_free(local_routerstatus_t
*rs
);
31 static void trusted_dir_server_free(trusted_dir_server_t
*ds
);
32 static void update_networkstatus_cache_downloads(time_t now
);
33 static void update_networkstatus_client_downloads(time_t now
);
34 static int signed_desc_digest_is_recognized(signed_descriptor_t
*desc
);
35 static void routerlist_assert_ok(routerlist_t
*rl
);
37 #define MAX_DESCRIPTORS_PER_ROUTER 5
39 /****************************************************************************/
41 /** Global list of a trusted_dir_server_t object for each trusted directory
43 static smartlist_t
*trusted_dir_servers
= NULL
;
45 /** Global list of all of the routers that we know about. */
46 static routerlist_t
*routerlist
= NULL
;
48 /** Global list of all of the current network_status documents that we know
49 * about. This list is kept sorted by published_on. */
50 static smartlist_t
*networkstatus_list
= NULL
;
52 /** Global list of local_routerstatus_t for each router, known or unknown. */
53 static smartlist_t
*routerstatus_list
= NULL
;
55 /** True iff any member of networkstatus_list has changed since the last time
56 * we called routerstatus_list_update_from_networkstatus(). */
57 static int networkstatus_list_has_changed
= 0;
59 /** True iff any element of routerstatus_list has changed since the last
60 * time we called routers_update_all_from_networkstatus().*/
61 static int routerstatus_list_has_changed
= 0;
63 /** List of strings for nicknames we've already warned about and that are
64 * still unknown / unavailable. */
65 static smartlist_t
*warned_nicknames
= NULL
;
67 /** List of strings for nicknames or fingerprints we've already warned about
68 * and that are still conflicted. */
69 static smartlist_t
*warned_conflicts
= NULL
;
71 /** The last time we tried to download any routerdesc, or 0 for "never". We
72 * use this to rate-limit download attempts when the number of routerdescs to
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 log_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;
144 /** Total bytes dropped since last rebuild. */
145 static size_t router_bytes_dropped
= 0;
147 /** Helper: return 1 iff the router log is so big we want to rebuild the
150 router_should_rebuild_store(void)
152 if (router_store_len
> (1<<16))
153 return (router_journal_len
> router_store_len
/ 2 ||
154 router_bytes_dropped
> router_store_len
/ 2);
156 return router_journal_len
> (1<<15);
159 /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
162 router_append_to_journal(signed_descriptor_t
*desc
)
164 or_options_t
*options
= get_options();
165 size_t fname_len
= strlen(options
->DataDirectory
)+32;
166 char *fname
= tor_malloc(fname_len
);
167 const char *body
= signed_descriptor_get_body(desc
);
168 size_t len
= desc
->signed_descriptor_len
;
170 tor_snprintf(fname
, fname_len
, "%s/cached-routers.new",
171 options
->DataDirectory
);
173 tor_assert(len
== strlen(body
));
175 if (append_bytes_to_file(fname
, body
, len
, 0)) {
176 log_warn(LD_FS
, "Unable to store router descriptor");
182 router_journal_len
+= len
;
186 /** If the journal is too long, or if <b>force</b> is true, then atomically
187 * replace the router store with the routers currently in our routerlist, and
188 * clear the journal. Return 0 on success, -1 on failure.
191 router_rebuild_store(int force
)
194 or_options_t
*options
;
196 smartlist_t
*chunk_list
= NULL
;
200 if (!force
&& !router_should_rebuild_store())
205 /* Don't save deadweight. */
206 routerlist_remove_old_routers();
208 options
= get_options();
209 fname_len
= strlen(options
->DataDirectory
)+32;
210 fname
= tor_malloc(fname_len
);
211 tor_snprintf(fname
, fname_len
, "%s/cached-routers", options
->DataDirectory
);
212 chunk_list
= smartlist_create();
214 for (i
= 0; i
< 2; ++i
) {
215 smartlist_t
*lst
= (i
== 0) ? routerlist
->old_routers
:
217 SMARTLIST_FOREACH(lst
, void *, ptr
,
219 signed_descriptor_t
*sd
= (i
==0) ?
220 ((signed_descriptor_t
*)ptr
): &((routerinfo_t
*)ptr
)->cache_info
;
222 const char *body
= signed_descriptor_get_body(sd
);
224 log_warn(LD_BUG
, "Bug! No descriptor available for router.");
227 c
= tor_malloc(sizeof(sized_chunk_t
));
229 c
->len
= sd
->signed_descriptor_len
;
230 smartlist_add(chunk_list
, c
);
233 if (write_chunks_to_file(fname
, chunk_list
, 0)<0) {
234 log_warn(LD_FS
, "Error writing router store to disk.");
238 tor_snprintf(fname
, fname_len
, "%s/cached-routers.new",
239 options
->DataDirectory
);
241 write_str_to_file(fname
, "", 0);
244 router_store_len
= len
;
245 router_journal_len
= 0;
246 router_bytes_dropped
= 0;
250 SMARTLIST_FOREACH(chunk_list
, sized_chunk_t
*, c
, tor_free(c
));
251 smartlist_free(chunk_list
);
256 /* Load all cached router descriptors from the store. Return 0 on success and
260 router_reload_router_list(void)
262 or_options_t
*options
= get_options();
263 size_t fname_len
= strlen(options
->DataDirectory
)+32;
264 char *fname
= tor_malloc(fname_len
);
269 router_get_routerlist(); /* mallocs and inits it in place */
271 router_journal_len
= router_store_len
= 0;
273 for (j
= 0; j
< 2; ++j
) {
275 tor_snprintf(fname
, fname_len
,
276 (j
==0)?"%s/cached-routers":"%s/cached-routers.new",
277 options
->DataDirectory
);
278 contents
= read_file_to_str(fname
, 0);
282 router_store_len
= st
.st_size
;
284 router_journal_len
= st
.st_size
;
285 router_load_routers_from_string(contents
, 1, NULL
);
291 if (router_journal_len
) {
292 /* Always clear the journal on startup.*/
293 router_rebuild_store(1);
295 /* Don't cache expired routers. (This is in an else because
296 * router_rebuild_store() also calls remove_old_routers().) */
297 routerlist_remove_old_routers();
303 /** Set *<b>outp</b> to a smartlist containing a list of
304 * trusted_dir_server_t * for all known trusted dirservers. Callers
305 * must not modify the list or its contents.
308 router_get_trusted_dir_servers(smartlist_t
**outp
)
310 if (!trusted_dir_servers
)
311 trusted_dir_servers
= smartlist_create();
313 *outp
= trusted_dir_servers
;
316 /** Try to find a running dirserver. If there are no running dirservers
317 * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
318 * set all the authoritative ones as running again, and pick one;
319 * if there are then no dirservers at all in our routerlist,
320 * reload the routerlist and try one last time. If for_runningrouters is
321 * true, then only pick a dirserver that can answer runningrouters queries
322 * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
323 * Don't pick an authority if any non-authority is viable.
324 * Other args are as in router_pick_directory_server_impl().
327 router_pick_directory_server(int requireother
,
329 int for_v2_directory
,
330 int retry_if_no_servers
)
332 routerstatus_t
*choice
;
337 choice
= router_pick_directory_server_impl(requireother
, fascistfirewall
,
339 if (choice
|| !retry_if_no_servers
)
343 "No reachable router entries for dirservers. "
344 "Trying them all again.");
345 /* mark all authdirservers as up again */
346 mark_all_trusteddirservers_up();
348 choice
= router_pick_directory_server_impl(requireother
, fascistfirewall
,
353 log_info(LD_DIR
,"Still no %s router entries. Reloading and trying again.",
354 fascistfirewall
? "reachable" : "known");
355 if (router_reload_router_list()) {
358 /* give it one last try */
359 choice
= router_pick_directory_server_impl(requireother
, fascistfirewall
,
364 /** Return the trusted_dir_server_t for the directory authority whose identity
365 * key hashes to <b>digest</b>, or NULL if no such authority is known.
367 trusted_dir_server_t
*
368 router_get_trusteddirserver_by_digest(const char *digest
)
370 if (!trusted_dir_servers
)
373 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
375 if (!memcmp(ds
->digest
, digest
, DIGEST_LEN
))
382 /** Try to find a running trusted dirserver. If there are no running
383 * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
384 * set them all as running again, and try again.
385 * If <b>need_v1_authority</b> is set, return only trusted servers
386 * that are authorities for the V1 directory protocol.
387 * Other args are as in router_pick_trusteddirserver_impl().
390 router_pick_trusteddirserver(int need_v1_authority
,
393 int retry_if_no_servers
)
395 routerstatus_t
*choice
;
397 choice
= router_pick_trusteddirserver_impl(need_v1_authority
,
398 requireother
, fascistfirewall
);
399 if (choice
|| !retry_if_no_servers
)
403 "No trusted dirservers are reachable. Trying them all again.");
404 mark_all_trusteddirservers_up();
405 return router_pick_trusteddirserver_impl(need_v1_authority
,
406 requireother
, fascistfirewall
);
409 /** Pick a random running verified directory server/mirror from our
410 * routerlist. Don't pick an authority if any non-authorities are viable.
411 * If <b>fascistfirewall</b>,
412 * make sure the router we pick is allowed by our firewall options.
413 * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
414 * choose a directory server new enough to support the v2 directory
417 static routerstatus_t
*
418 router_pick_directory_server_impl(int requireother
, int fascistfirewall
,
419 int for_v2_directory
)
421 routerstatus_t
*result
;
423 smartlist_t
*trusted
;
425 if (!routerstatus_list
)
428 /* Find all the running dirservers we know about. */
429 sl
= smartlist_create();
430 trusted
= smartlist_create();
431 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, _local_status
,
433 routerstatus_t
*status
= &(_local_status
->status
);
435 if (!status
->is_running
|| !status
->dir_port
|| !status
->is_valid
)
437 if (requireother
&& router_digest_is_me(status
->identity_digest
))
439 if (fascistfirewall
) {
440 if (!fascist_firewall_allows_address_dir(status
->addr
, status
->dir_port
))
443 is_trusted
= router_digest_is_trusted_dir(status
->identity_digest
);
444 if (for_v2_directory
&& !(status
->is_v2_dir
|| is_trusted
))
446 smartlist_add(is_trusted
? trusted
: sl
, status
);
449 if (smartlist_len(sl
))
450 result
= smartlist_choose(sl
);
452 result
= smartlist_choose(trusted
);
454 smartlist_free(trusted
);
458 /** Choose randomly from among the trusted dirservers that are up. If
459 * <b>fascistfirewall</b>, make sure the port we pick is allowed by our
460 * firewall options. If <b>requireother</b>, it cannot be us. If
461 * <b>need_v1_authority</b>, choose a trusted authority for the v1 directory
464 static routerstatus_t
*
465 router_pick_trusteddirserver_impl(int need_v1_authority
,
466 int requireother
, int fascistfirewall
)
471 sl
= smartlist_create();
472 me
= router_get_my_routerinfo();
474 if (!trusted_dir_servers
)
477 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, d
,
479 if (!d
->is_running
) continue;
480 if (need_v1_authority
&& !d
->is_v1_authority
)
482 if (requireother
&& me
&& router_digest_is_me(d
->digest
))
484 if (fascistfirewall
) {
485 if (!fascist_firewall_allows_address_dir(d
->addr
, d
->dir_port
))
488 smartlist_add(sl
, &d
->fake_status
);
491 rs
= smartlist_choose(sl
);
496 /** Go through and mark the authoritative dirservers as up. */
498 mark_all_trusteddirservers_up(void)
501 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
502 if (router_digest_is_trusted_dir(router
->cache_info
.identity_digest
) &&
503 router
->dir_port
> 0) {
504 router
->is_running
= 1;
507 if (trusted_dir_servers
) {
508 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, dir
,
510 local_routerstatus_t
*rs
;
512 dir
->n_networkstatus_failures
= 0;
513 rs
= router_get_combined_status_by_digest(dir
->digest
);
515 rs
->status
.is_running
= 1;
518 last_networkstatus_download_attempted
= 0;
521 /** Reset all internal variables used to count failed downloads of network
524 router_reset_status_download_failures(void)
526 mark_all_trusteddirservers_up();
529 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
530 * This is used to make sure we don't pick siblings in a single path.
533 routerlist_add_family(smartlist_t
*sl
, routerinfo_t
*router
)
538 if (!router
->declared_family
)
541 /* Add every r such that router declares familyness with r, and r
542 * declares familyhood with router. */
543 SMARTLIST_FOREACH(router
->declared_family
, const char *, n
,
545 if (!(r
= router_get_by_nickname(n
, 0)))
547 if (!r
->declared_family
)
549 SMARTLIST_FOREACH(r
->declared_family
, const char *, n2
,
551 if (router_nickname_matches(router
, n2
))
552 smartlist_add(sl
, r
);
556 /* If the user declared any families locally, honor those too. */
557 for (cl
= get_options()->NodeFamilies
; cl
; cl
= cl
->next
) {
558 if (router_nickname_is_in_list(router
, cl
->value
)) {
559 add_nickname_list_to_smartlist(sl
, cl
->value
, 0, 1, 1);
564 /** Given a comma-and-whitespace separated list of nicknames, see which
565 * nicknames in <b>list</b> name routers in our routerlist that are
566 * currently running. Add the routerinfos for those routers to <b>sl</b>.
569 add_nickname_list_to_smartlist(smartlist_t
*sl
, const char *list
,
571 int warn_if_down
, int warn_if_unnamed
)
573 routerinfo_t
*router
;
574 smartlist_t
*nickname_list
;
575 int have_dir_info
= router_have_minimum_dir_info();
578 return; /* nothing to do */
581 nickname_list
= smartlist_create();
582 if (!warned_nicknames
)
583 warned_nicknames
= smartlist_create();
585 smartlist_split_string(nickname_list
, list
, ",",
586 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
588 SMARTLIST_FOREACH(nickname_list
, const char *, nick
, {
590 if (!is_legal_nickname_or_hexdigest(nick
)) {
591 log_warn(LD_CONFIG
, "Nickname '%s' is misformed; skipping", nick
);
594 router
= router_get_by_nickname(nick
, warn_if_unnamed
);
595 warned
= smartlist_string_isin(warned_nicknames
, nick
);
597 if (!must_be_running
|| router
->is_running
) {
598 smartlist_add(sl
,router
);
600 smartlist_string_remove(warned_nicknames
, nick
);
603 log_fn(warn_if_down
? LOG_WARN
: LOG_DEBUG
, LD_CONFIG
,
604 "Nickname list includes '%s' which is known but down.",nick
);
605 smartlist_add(warned_nicknames
, tor_strdup(nick
));
610 log_fn(have_dir_info
? LOG_WARN
: LOG_INFO
, LD_CONFIG
,
611 "Nickname list includes '%s' which isn't a known router.",nick
);
612 smartlist_add(warned_nicknames
, tor_strdup(nick
));
616 SMARTLIST_FOREACH(nickname_list
, char *, nick
, tor_free(nick
));
617 smartlist_free(nickname_list
);
620 /** Return 1 iff any member of the comma-separated list <b>list</b> is an
621 * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
624 router_nickname_is_in_list(routerinfo_t
*router
, const char *list
)
626 smartlist_t
*nickname_list
;
630 return 0; /* definitely not */
633 nickname_list
= smartlist_create();
634 smartlist_split_string(nickname_list
, list
, ",",
635 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
636 SMARTLIST_FOREACH(nickname_list
, const char *, cp
,
637 if (router_nickname_matches(router
, cp
)) {v
=1;break;});
638 SMARTLIST_FOREACH(nickname_list
, char *, cp
, tor_free(cp
));
639 smartlist_free(nickname_list
);
643 /** Add every router from our routerlist that is currently running to
647 router_add_running_routers_to_smartlist(smartlist_t
*sl
, int allow_unverified
,
648 int need_uptime
, int need_capacity
,
654 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
656 if (router
->is_running
&&
657 (router
->is_verified
||
659 !router_is_unreliable(router
, need_uptime
,
660 need_capacity
, need_guard
)))) {
661 /* If it's running, and either it's verified or we're ok picking
662 * unverified routers and this one is suitable.
664 smartlist_add(sl
, router
);
669 /** Look through the routerlist until we find a router that has my key.
672 routerlist_find_my_routerinfo(void)
677 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
679 if (router_is_me(router
))
685 /** Find a router that's up, that has this IP address, and
686 * that allows exit to this address:port, or return NULL if there
690 router_find_exact_exit_enclave(const char *address
, uint16_t port
)
695 if (!tor_inet_aton(address
, &in
))
696 return NULL
; /* it's not an IP already */
697 addr
= ntohl(in
.s_addr
);
699 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
701 if (router
->is_running
&&
702 router
->addr
== addr
&&
703 router_compare_addr_to_addr_policy(addr
, port
, router
->exit_policy
) ==
704 ADDR_POLICY_ACCEPTED
)
710 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
711 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
712 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
716 router_is_unreliable(routerinfo_t
*router
, int need_uptime
,
717 int need_capacity
, int need_guard
)
719 if (need_uptime
&& !router
->is_stable
)
721 if (need_capacity
&& !router
->is_fast
)
723 if (need_guard
&& !router
->is_possible_guard
)
728 /** Remove from routerlist <b>sl</b> all routers that are not
729 * sufficiently stable. */
731 routerlist_sl_remove_unreliable_routers(smartlist_t
*sl
, int need_uptime
,
732 int need_capacity
, int need_guard
)
735 routerinfo_t
*router
;
737 for (i
= 0; i
< smartlist_len(sl
); ++i
) {
738 router
= smartlist_get(sl
, i
);
739 if (router_is_unreliable(router
, need_uptime
,
740 need_capacity
, need_guard
)) {
741 // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
742 // router->nickname);
743 smartlist_del(sl
, i
--);
748 #define MAX_BELIEVABLE_BANDWIDTH 1500000 /* 1.5 MB/sec */
750 /** Choose a random element of router list <b>sl</b>, weighted by
751 * the advertised bandwidth of each router.
754 routerlist_sl_choose_by_bandwidth(smartlist_t
*sl
)
757 routerinfo_t
*router
;
758 smartlist_t
*bandwidths
;
759 uint32_t this_bw
, tmp
, total_bw
=0, rand_bw
;
762 /* First count the total bandwidth weight, and make a smartlist
764 bandwidths
= smartlist_create();
765 for (i
= 0; i
< smartlist_len(sl
); ++i
) {
766 router
= smartlist_get(sl
, i
);
767 this_bw
= (router
->bandwidthcapacity
< router
->bandwidthrate
) ?
768 router
->bandwidthcapacity
: router
->bandwidthrate
;
769 /* if they claim something huge, don't believe it */
770 if (this_bw
> MAX_BELIEVABLE_BANDWIDTH
)
771 this_bw
= MAX_BELIEVABLE_BANDWIDTH
;
772 p
= tor_malloc(sizeof(uint32_t));
774 smartlist_add(bandwidths
, p
);
778 SMARTLIST_FOREACH(bandwidths
, uint32_t*, p
, tor_free(p
));
779 smartlist_free(bandwidths
);
780 return smartlist_choose(sl
);
782 /* Second, choose a random value from the bandwidth weights. */
783 rand_bw
= crypto_rand_int(total_bw
);
784 /* Last, count through sl until we get to the element we picked */
787 tor_assert(i
< smartlist_len(sl
));
788 p
= smartlist_get(bandwidths
, i
);
793 SMARTLIST_FOREACH(bandwidths
, uint32_t*, p
, tor_free(p
));
794 smartlist_free(bandwidths
);
795 return (routerinfo_t
*)smartlist_get(sl
, i
);
798 /** Return a random running router from the routerlist. If any node
799 * named in <b>preferred</b> is available, pick one of those. Never
800 * pick a node named in <b>excluded</b>, or whose routerinfo is in
801 * <b>excludedsmartlist</b>, even if they are the only nodes
802 * available. If <b>strict</b> is true, never pick any node besides
803 * those in <b>preferred</b>.
804 * If <b>need_uptime</b> is non-zero and any router has more than
805 * a minimum uptime, return one of those.
806 * If <b>need_capacity</b> is non-zero, weight your choice by the
807 * advertised capacity of each router.
810 router_choose_random_node(const char *preferred
,
811 const char *excluded
,
812 smartlist_t
*excludedsmartlist
,
813 int need_uptime
, int need_capacity
,
815 int allow_unverified
, int strict
)
817 smartlist_t
*sl
, *excludednodes
;
818 routerinfo_t
*choice
= NULL
;
820 excludednodes
= smartlist_create();
821 add_nickname_list_to_smartlist(excludednodes
,excluded
,0,0,1);
823 /* Try the preferred nodes first. Ignore need_uptime and need_capacity
824 * and need_guard, since the user explicitly asked for these nodes. */
826 sl
= smartlist_create();
827 add_nickname_list_to_smartlist(sl
,preferred
,1,1,1);
828 smartlist_subtract(sl
,excludednodes
);
829 if (excludedsmartlist
)
830 smartlist_subtract(sl
,excludedsmartlist
);
831 choice
= smartlist_choose(sl
);
834 if (!choice
&& !strict
) {
835 /* Then give up on our preferred choices: any node
836 * will do that has the required attributes. */
837 sl
= smartlist_create();
838 router_add_running_routers_to_smartlist(sl
, allow_unverified
,
839 need_uptime
, need_capacity
,
841 smartlist_subtract(sl
,excludednodes
);
842 if (excludedsmartlist
)
843 smartlist_subtract(sl
,excludedsmartlist
);
844 routerlist_sl_remove_unreliable_routers(sl
, need_uptime
,
845 need_capacity
, need_guard
);
847 choice
= routerlist_sl_choose_by_bandwidth(sl
);
849 choice
= smartlist_choose(sl
);
851 if (!choice
&& (need_uptime
|| need_capacity
|| need_guard
)) {
852 /* try once more -- recurse but with fewer restrictions. */
854 "We couldn't find any live%s%s%s routers; falling back "
855 "to list of all routers.",
856 need_capacity
?", fast":"",
857 need_uptime
?", stable":"",
858 need_guard
?", guard":"");
859 choice
= router_choose_random_node(
860 NULL
, excluded
, excludedsmartlist
, 0, 0, 0, allow_unverified
, 0);
863 smartlist_free(excludednodes
);
866 "No available nodes when trying to choose node. Failing.");
870 /** Return true iff the digest of <b>router</b>'s identity key,
871 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
872 * optionally prefixed with a single dollar sign). Return false if
873 * <b>hexdigest</b> is malformed, or it doesn't match. */
875 router_hex_digest_matches(routerinfo_t
*router
, const char *hexdigest
)
877 char digest
[DIGEST_LEN
];
878 tor_assert(hexdigest
);
879 if (hexdigest
[0] == '$')
882 /* XXXXNM Any place that uses this inside a loop could probably do better. */
883 if (strlen(hexdigest
) != HEX_DIGEST_LEN
||
884 base16_decode(digest
, DIGEST_LEN
, hexdigest
, HEX_DIGEST_LEN
)<0)
886 return (!memcmp(digest
, router
->cache_info
.identity_digest
, DIGEST_LEN
));
889 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
890 * (case-insensitive), or if <b>router's</b> identity key digest
891 * matches a hexadecimal value stored in <b>nickname</b>. Return
892 * false otherwise. */
894 router_nickname_matches(routerinfo_t
*router
, const char *nickname
)
896 if (nickname
[0]!='$' && !strcasecmp(router
->nickname
, nickname
))
898 return router_hex_digest_matches(router
, nickname
);
901 /** Return the router in our routerlist whose (case-insensitive)
902 * nickname or (case-sensitive) hexadecimal key digest is
903 * <b>nickname</b>. Return NULL if no such router is known.
906 router_get_by_nickname(const char *nickname
, int warn_if_unnamed
)
909 char digest
[DIGEST_LEN
];
910 routerinfo_t
*best_match
=NULL
;
913 tor_assert(nickname
);
916 if (nickname
[0] == '$')
917 return router_get_by_hexdigest(nickname
);
918 if (server_mode(get_options()) &&
919 !strcasecmp(nickname
, get_options()->Nickname
))
920 return router_get_my_routerinfo();
922 maybedigest
= (strlen(nickname
) == HEX_DIGEST_LEN
) &&
923 (base16_decode(digest
,DIGEST_LEN
,nickname
,HEX_DIGEST_LEN
) == 0);
925 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
927 if (!strcasecmp(router
->nickname
, nickname
)) {
928 if (router
->is_named
)
934 } else if (maybedigest
&&
935 !memcmp(digest
, router
->cache_info
.identity_digest
, DIGEST_LEN
)
942 if (warn_if_unnamed
&& n_matches
> 1) {
943 smartlist_t
*fps
= smartlist_create();
944 int any_unwarned
= 0;
945 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
947 local_routerstatus_t
*rs
;
950 char fp
[HEX_DIGEST_LEN
+1];
951 if (strcasecmp(router
->nickname
, nickname
))
953 rs
= router_get_combined_status_by_digest(
954 router
->cache_info
.identity_digest
);
955 if (!rs
->name_lookup_warned
) {
956 rs
->name_lookup_warned
= 1;
959 base16_encode(fp
, sizeof(fp
),
960 router
->cache_info
.identity_digest
, DIGEST_LEN
);
961 dlen
= 32 + HEX_DIGEST_LEN
+ strlen(router
->address
);
962 desc
= tor_malloc(dlen
);
963 tor_snprintf(desc
, dlen
, "\"$%s\" for the one at %s:%d",
964 fp
, router
->address
, router
->or_port
);
965 smartlist_add(fps
, desc
);
968 char *alternatives
= smartlist_join_strings(fps
, "; ",0,NULL
);
970 "There are multiple matches for the nickname \"%s\","
971 " but none is listed as named by the directory authories. "
972 "Choosing one arbitrarily. If you meant one in particular, "
973 "you should say %s.", nickname
, alternatives
);
974 tor_free(alternatives
);
976 SMARTLIST_FOREACH(fps
, char *, cp
, tor_free(cp
));
978 } else if (warn_if_unnamed
) {
979 local_routerstatus_t
*rs
= router_get_combined_status_by_digest(
980 best_match
->cache_info
.identity_digest
);
981 if (rs
&& !rs
->name_lookup_warned
) {
982 char fp
[HEX_DIGEST_LEN
+1];
983 base16_encode(fp
, sizeof(fp
),
984 best_match
->cache_info
.identity_digest
, DIGEST_LEN
);
985 log_warn(LD_CONFIG
, "You specified a server \"%s\" by name, but the "
986 "directory authorities do not have a listing for this name. "
987 "To make sure you get the same server in the future, refer to "
988 "it by key, as \"$%s\".", nickname
, fp
);
989 rs
->name_lookup_warned
= 1;
998 /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
999 * return 1. If we do, ask tor_version_as_new_as() for the answer.
1002 router_digest_version_as_new_as(const char *digest
, const char *cutoff
)
1004 routerinfo_t
*router
= router_get_by_digest(digest
);
1007 return tor_version_as_new_as(router
->platform
, cutoff
);
1010 /** Return true iff <b>digest</b> is the digest of the identity key of
1011 * a trusted directory. */
1013 router_digest_is_trusted_dir(const char *digest
)
1015 if (!trusted_dir_servers
)
1017 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
1018 if (!memcmp(digest
, ent
->digest
, DIGEST_LEN
)) return 1);
1022 /** Return the router in our routerlist whose hexadecimal key digest
1023 * is <b>hexdigest</b>. Return NULL if no such router is known. */
1025 router_get_by_hexdigest(const char *hexdigest
)
1027 char digest
[DIGEST_LEN
];
1029 tor_assert(hexdigest
);
1032 if (hexdigest
[0]=='$')
1034 if (strlen(hexdigest
) != HEX_DIGEST_LEN
||
1035 base16_decode(digest
,DIGEST_LEN
,hexdigest
,HEX_DIGEST_LEN
) < 0)
1038 return router_get_by_digest(digest
);
1041 /** Return the router in our routerlist whose 20-byte key digest
1042 * is <b>digest</b>. Return NULL if no such router is known. */
1044 router_get_by_digest(const char *digest
)
1048 if (!routerlist
) return NULL
;
1050 // routerlist_assert_ok(routerlist);
1052 return digestmap_get(routerlist
->identity_map
, digest
);
1055 /** Return the router in our routerlist whose 20-byte descriptor
1056 * is <b>digest</b>. Return NULL if no such router is known. */
1057 signed_descriptor_t
*
1058 router_get_by_descriptor_digest(const char *digest
)
1062 if (!routerlist
) return NULL
;
1064 return digestmap_get(routerlist
->desc_digest_map
, digest
);
1068 signed_descriptor_get_body(signed_descriptor_t
*desc
)
1070 return desc
->signed_descriptor_body
;
1073 /** Return the current list of all known routers. */
1075 router_get_routerlist(void)
1078 routerlist
= tor_malloc_zero(sizeof(routerlist_t
));
1079 routerlist
->routers
= smartlist_create();
1080 routerlist
->old_routers
= smartlist_create();
1081 routerlist
->identity_map
= digestmap_new();
1082 routerlist
->desc_digest_map
= digestmap_new();
1087 /** Free all storage held by <b>router</b>. */
1089 routerinfo_free(routerinfo_t
*router
)
1094 tor_free(router
->cache_info
.signed_descriptor_body
);
1095 tor_free(router
->address
);
1096 tor_free(router
->nickname
);
1097 tor_free(router
->platform
);
1098 tor_free(router
->contact_info
);
1099 if (router
->onion_pkey
)
1100 crypto_free_pk_env(router
->onion_pkey
);
1101 if (router
->identity_pkey
)
1102 crypto_free_pk_env(router
->identity_pkey
);
1103 if (router
->declared_family
) {
1104 SMARTLIST_FOREACH(router
->declared_family
, char *, s
, tor_free(s
));
1105 smartlist_free(router
->declared_family
);
1107 addr_policy_free(router
->exit_policy
);
1111 /** Release storage held by <b>sd</b>. */
1113 signed_descriptor_free(signed_descriptor_t
*sd
)
1115 tor_free(sd
->signed_descriptor_body
);
1119 /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
1121 static signed_descriptor_t
*
1122 signed_descriptor_from_routerinfo(routerinfo_t
*ri
)
1124 signed_descriptor_t
*sd
= tor_malloc_zero(sizeof(signed_descriptor_t
));
1125 memcpy(sd
, &(ri
->cache_info
), sizeof(signed_descriptor_t
));
1126 ri
->cache_info
.signed_descriptor_body
= NULL
;
1127 routerinfo_free(ri
);
1131 /** Free all storage held by a routerlist <b>rl</b> */
1133 routerlist_free(routerlist_t
*rl
)
1136 digestmap_free(rl
->identity_map
, NULL
);
1137 digestmap_free(rl
->desc_digest_map
, NULL
);
1138 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
1139 routerinfo_free(r
));
1140 SMARTLIST_FOREACH(rl
->old_routers
, signed_descriptor_t
*, sd
,
1141 signed_descriptor_free(sd
));
1142 smartlist_free(rl
->routers
);
1143 smartlist_free(rl
->old_routers
);
1148 dump_routerlist_mem_usage(int severity
)
1150 uint64_t livedescs
= 0;
1151 uint64_t olddescs
= 0;
1154 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, r
,
1155 livedescs
+= r
->cache_info
.signed_descriptor_len
);
1156 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
,
1157 olddescs
+= sd
->signed_descriptor_len
);
1159 log(severity
, LD_GENERAL
,
1160 "In %d live descriptors: "U64_FORMAT
" bytes. "
1161 "In %d old descriptors: "U64_FORMAT
" bytes.",
1162 smartlist_len(routerlist
->routers
), U64_PRINTF_ARG(livedescs
),
1163 smartlist_len(routerlist
->old_routers
), U64_PRINTF_ARG(olddescs
));
1166 /** Return non-zero if we have a lot of extra descriptors in our
1167 * routerlist, and should get rid of some of them. Else return 0.
1169 * We should be careful to not return true too eagerly, since we
1170 * could churn. By using "+1" below, we make sure this function
1171 * only returns true at most every smartlist_len(rl-\>routers)
1175 routerlist_is_overfull(routerlist_t
*rl
)
1177 return smartlist_len(rl
->old_routers
) >
1178 smartlist_len(rl
->routers
)*(MAX_DESCRIPTORS_PER_ROUTER
+1);
1182 _routerlist_find_elt(smartlist_t
*sl
, void *ri
, int idx
)
1184 if (idx
< 0 || smartlist_get(sl
, idx
) != ri
) {
1186 SMARTLIST_FOREACH(sl
, routerinfo_t
*, r
,
1195 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1198 routerlist_insert(routerlist_t
*rl
, routerinfo_t
*ri
)
1200 digestmap_set(rl
->identity_map
, ri
->cache_info
.identity_digest
, ri
);
1201 digestmap_set(rl
->desc_digest_map
, ri
->cache_info
.signed_descriptor_digest
,
1203 smartlist_add(rl
->routers
, ri
);
1204 // routerlist_assert_ok(rl);
1208 routerlist_insert_old(routerlist_t
*rl
, routerinfo_t
*ri
)
1210 if (get_options()->DirPort
&&
1211 !digestmap_get(rl
->desc_digest_map
,
1212 ri
->cache_info
.signed_descriptor_digest
)) {
1213 signed_descriptor_t
*sd
= signed_descriptor_from_routerinfo(ri
);
1214 digestmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
1215 smartlist_add(rl
->old_routers
, sd
);
1217 routerinfo_free(ri
);
1219 // routerlist_assert_ok(rl);
1222 /** Remove an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1223 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl->routers,
1224 * idx) == ri, we don't need to do a linear search over the list to decide
1225 * which to remove. We fill the gap in rl->routers with a later element in
1226 * the list, if any exists. <b>ri</b> is freed. */
1228 routerlist_remove(routerlist_t
*rl
, routerinfo_t
*ri
, int idx
, int make_old
)
1230 routerinfo_t
*ri_tmp
;
1231 idx
= _routerlist_find_elt(rl
->routers
, ri
, idx
);
1234 smartlist_del(rl
->routers
, idx
);
1235 ri_tmp
= digestmap_remove(rl
->identity_map
, ri
->cache_info
.identity_digest
);
1236 tor_assert(ri_tmp
== ri
);
1237 if (make_old
&& get_options()->DirPort
) {
1238 signed_descriptor_t
*sd
;
1239 sd
= signed_descriptor_from_routerinfo(ri
);
1240 smartlist_add(rl
->old_routers
, sd
);
1241 digestmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
1243 ri_tmp
= digestmap_remove(rl
->desc_digest_map
,
1244 ri
->cache_info
.signed_descriptor_digest
);
1245 tor_assert(ri_tmp
== ri
);
1246 router_bytes_dropped
+= ri
->cache_info
.signed_descriptor_len
;
1247 routerinfo_free(ri
);
1249 // routerlist_assert_ok(rl);
1253 routerlist_remove_old(routerlist_t
*rl
, signed_descriptor_t
*sd
, int idx
)
1255 signed_descriptor_t
*sd_tmp
;
1256 idx
= _routerlist_find_elt(rl
->old_routers
, sd
, idx
);
1259 smartlist_del(rl
->old_routers
, idx
);
1260 sd_tmp
= digestmap_remove(rl
->desc_digest_map
,
1261 sd
->signed_descriptor_digest
);
1262 tor_assert(sd_tmp
== sd
);
1263 router_bytes_dropped
+= sd
->signed_descriptor_len
;
1264 signed_descriptor_free(sd
);
1265 // routerlist_assert_ok(rl);
1268 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
1269 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
1270 * smartlist_get(rl->routers, idx) == ri, we don't need to do a linear
1271 * search over the list to decide which to remove. We put ri_new in the same
1272 * index as ri_old, if possible. ri is freed as appropriate. */
1274 routerlist_replace(routerlist_t
*rl
, routerinfo_t
*ri_old
,
1275 routerinfo_t
*ri_new
, int idx
, int make_old
)
1277 tor_assert(ri_old
!= ri_new
);
1278 idx
= _routerlist_find_elt(rl
->routers
, ri_old
, idx
);
1280 smartlist_set(rl
->routers
, idx
, ri_new
);
1282 log_warn(LD_BUG
, "Appending entry from routerlist_replace.");
1283 routerlist_insert(rl
, ri_new
);
1286 if (memcmp(ri_old
->cache_info
.identity_digest
,
1287 ri_new
->cache_info
.identity_digest
, DIGEST_LEN
)) {
1288 /* digests don't match; digestmap_set won't replace */
1289 digestmap_remove(rl
->identity_map
, ri_old
->cache_info
.identity_digest
);
1291 digestmap_set(rl
->identity_map
, ri_new
->cache_info
.identity_digest
, ri_new
);
1292 digestmap_set(rl
->desc_digest_map
,
1293 ri_new
->cache_info
.signed_descriptor_digest
, &(ri_new
->cache_info
));
1295 if (make_old
&& get_options()->DirPort
) {
1296 signed_descriptor_t
*sd
= signed_descriptor_from_routerinfo(ri_old
);
1297 smartlist_add(rl
->old_routers
, sd
);
1298 digestmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
1300 if (memcmp(ri_old
->cache_info
.signed_descriptor_digest
,
1301 ri_new
->cache_info
.signed_descriptor_digest
,
1303 /* digests don't match; digestmap_set didn't replace */
1304 digestmap_remove(rl
->desc_digest_map
,
1305 ri_old
->cache_info
.signed_descriptor_digest
);
1307 routerinfo_free(ri_old
);
1309 // routerlist_assert_ok(rl);
1312 /** Free all memory held by the routerlist module. */
1314 routerlist_free_all(void)
1317 routerlist_free(routerlist
);
1319 if (warned_nicknames
) {
1320 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
1321 smartlist_free(warned_nicknames
);
1322 warned_nicknames
= NULL
;
1324 if (warned_conflicts
) {
1325 SMARTLIST_FOREACH(warned_conflicts
, char *, cp
, tor_free(cp
));
1326 smartlist_free(warned_conflicts
);
1327 warned_conflicts
= NULL
;
1329 if (trusted_dir_servers
) {
1330 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
1331 trusted_dir_server_free(ds
));
1332 smartlist_free(trusted_dir_servers
);
1333 trusted_dir_servers
= NULL
;
1335 if (networkstatus_list
) {
1336 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
1337 networkstatus_free(ns
));
1338 smartlist_free(networkstatus_list
);
1339 networkstatus_list
= NULL
;
1341 if (routerstatus_list
) {
1342 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
1343 local_routerstatus_free(rs
));
1344 smartlist_free(routerstatus_list
);
1345 routerstatus_list
= NULL
;
1349 /** Free all storage held by the routerstatus object <b>rs</b>. */
1351 routerstatus_free(routerstatus_t
*rs
)
1356 /** Free all storage held by the local_routerstatus object <b>rs</b>. */
1358 local_routerstatus_free(local_routerstatus_t
*rs
)
1363 /** Free all storage held by the networkstatus object <b>ns</b>. */
1365 networkstatus_free(networkstatus_t
*ns
)
1367 tor_free(ns
->source_address
);
1368 tor_free(ns
->contact
);
1369 if (ns
->signing_key
)
1370 crypto_free_pk_env(ns
->signing_key
);
1371 tor_free(ns
->client_versions
);
1372 tor_free(ns
->server_versions
);
1374 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
*, rs
,
1375 routerstatus_free(rs
));
1376 smartlist_free(ns
->entries
);
1381 /** Forget that we have issued any router-related warnings, so that we'll
1382 * warn again if we see the same errors. */
1384 routerlist_reset_warnings(void)
1386 if (!warned_nicknames
)
1387 warned_nicknames
= smartlist_create();
1388 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
1389 smartlist_clear(warned_nicknames
); /* now the list is empty. */
1391 if (!warned_conflicts
)
1392 warned_conflicts
= smartlist_create();
1393 SMARTLIST_FOREACH(warned_conflicts
, char *, cp
, tor_free(cp
));
1394 smartlist_clear(warned_conflicts
); /* now the list is empty. */
1396 if (!routerstatus_list
)
1397 routerstatus_list
= smartlist_create();
1398 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
1399 rs
->name_lookup_warned
= 0);
1401 have_warned_about_unverified_status
= 0;
1402 have_warned_about_old_version
= 0;
1403 have_warned_about_new_version
= 0;
1406 /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
1408 router_mark_as_down(const char *digest
)
1410 routerinfo_t
*router
;
1411 local_routerstatus_t
*status
;
1414 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, d
,
1415 if (!memcmp(d
->digest
, digest
, DIGEST_LEN
))
1418 router
= router_get_by_digest(digest
);
1420 log_debug(LD_DIR
,"Marking router '%s' as down.",router
->nickname
);
1421 if (router_is_me(router
) && !we_are_hibernating())
1422 log_warn(LD_NET
, "We just marked ourself as down. Are your external "
1423 "addresses reachable?");
1424 router
->is_running
= 0;
1426 status
= router_get_combined_status_by_digest(digest
);
1428 status
->status
.is_running
= 0;
1432 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
1433 * older entries (if any) with the same key. Note: Callers should not hold
1434 * their pointers to <b>router</b> if this function fails; <b>router</b>
1435 * will either be inserted into the routerlist or freed.
1437 * Returns >= 0 if the router was added; less than 0 if it was not.
1439 * If we're returning non-zero, then assign to *<b>msg</b> a static string
1440 * describing the reason for not liking the routerinfo.
1442 * If the return value is less than -1, there was a problem with the
1443 * routerinfo. If the return value is equal to -1, then the routerinfo was
1444 * fine, but out-of-date. If the return value is equal to 1, the
1445 * routerinfo was accepted, but we should notify the generator of the
1446 * descriptor using the message *<b>msg</b>.
1448 * If <b>from_cache</b>, this descriptor came from our disk cache. If
1449 * <b>from_fetch</b>, we received it in response to a request we made.
1450 * (If both are false, that means it was uploaded to us as an auth dir
1451 * server or via the controller.)
1453 * This function should be called *after*
1454 * routers_update_status_from_networkstatus; subsequently, you should call
1455 * router_rebuild_store and control_event_descriptors_changed.
1457 * XXXX never replace your own descriptor.
1460 router_add_to_routerlist(routerinfo_t
*router
, const char **msg
,
1461 int from_cache
, int from_fetch
)
1464 char id_digest
[DIGEST_LEN
];
1465 int authdir
= get_options()->AuthoritativeDir
;
1466 int authdir_verified
= 0;
1471 router_get_routerlist();
1473 /* XXXX NM If this assert doesn't trigger, we should remove the id_digest
1475 crypto_pk_get_digest(router
->identity_pkey
, id_digest
);
1476 tor_assert(!memcmp(id_digest
, router
->cache_info
.identity_digest
,
1479 /* Make sure that we haven't already got this exact descriptor. */
1480 if (digestmap_get(routerlist
->desc_digest_map
,
1481 router
->cache_info
.signed_descriptor_digest
)) {
1483 "Dropping descriptor that we already have for router '%s'",
1485 *msg
= "Router descriptor was not new.";
1486 routerinfo_free(router
);
1490 if (routerlist_is_overfull(routerlist
))
1491 routerlist_remove_old_routers();
1494 if (authdir_wants_to_reject_router(router
, msg
,
1495 !from_cache
&& !from_fetch
)) {
1497 routerinfo_free(router
);
1500 authdir_verified
= router
->is_verified
;
1501 } else if (from_fetch
) {
1502 /* Only check the descriptor digest against the network statuses when
1503 * we are receiving in response to a fetch. */
1504 if (!signed_desc_digest_is_recognized(&router
->cache_info
)) {
1505 log_warn(LD_DIR
, "Dropping unrecognized descriptor for router '%s'",
1507 *msg
= "Router descriptor is not referenced by any network-status.";
1508 routerinfo_free(router
);
1513 /* If we have a router with this name, and the identity key is the same,
1514 * choose the newer one. If the identity key has changed, and one of the
1515 * routers is named, drop the unnamed ones. (If more than one are named,
1516 * drop the old ones.)
1518 for (i
= 0; i
< smartlist_len(routerlist
->routers
); ++i
) {
1519 routerinfo_t
*old_router
= smartlist_get(routerlist
->routers
, i
);
1520 if (!crypto_pk_cmp_keys(router
->identity_pkey
,old_router
->identity_pkey
)) {
1521 if (router
->cache_info
.published_on
<=
1522 old_router
->cache_info
.published_on
) {
1523 /* Same key, but old */
1524 log_debug(LD_DIR
, "Skipping not-new descriptor for router '%s'",
1526 routerlist_insert_old(routerlist
, router
);
1527 *msg
= "Router descriptor was not new.";
1530 /* Same key, new. */
1531 int unreachable
= 0;
1532 log_debug(LD_DIR
, "Replacing entry for router '%s/%s' [%s]",
1533 router
->nickname
, old_router
->nickname
,
1534 hex_str(id_digest
,DIGEST_LEN
));
1535 if (router
->addr
== old_router
->addr
&&
1536 router
->or_port
== old_router
->or_port
) {
1537 /* these carry over when the address and orport are unchanged.*/
1538 router
->last_reachable
= old_router
->last_reachable
;
1539 router
->testing_since
= old_router
->testing_since
;
1540 router
->num_unreachable_notifications
=
1541 old_router
->num_unreachable_notifications
;
1544 dirserv_thinks_router_is_blatantly_unreachable(router
,
1546 if (router
->num_unreachable_notifications
>= 3) {
1548 log_notice(LD_DIR
, "Notifying server '%s' that it's unreachable. "
1549 "(ContactInfo '%s', platform '%s').",
1551 router
->contact_info
? router
->contact_info
: "",
1552 router
->platform
? router
->platform
: "");
1554 log_info(LD_DIR
,"'%s' may be unreachable -- the %d previous "
1555 "descriptors were thought to be unreachable.",
1556 router
->nickname
, router
->num_unreachable_notifications
);
1557 router
->num_unreachable_notifications
++;
1560 routerlist_replace(routerlist
, old_router
, router
, i
, 1);
1562 router_append_to_journal(&router
->cache_info
);
1564 directory_set_dirty();
1565 *msg
= unreachable
? "Dirserver believes your ORPort is unreachable" :
1566 authdir_verified
? "Verified server updated" :
1567 ("Unverified server updated. (Have you sent us your key "
1569 return unreachable
? 1 : 0;
1571 } else if (!strcasecmp(router
->nickname
, old_router
->nickname
)) {
1572 /* nicknames match, keys don't. */
1573 if (router
->is_named
) {
1574 /* The new verified router replaces the old one; remove the
1575 * old one. And carry on to the end of the list, in case
1576 * there are more old unverified routers with this nickname
1578 /* mark-for-close connections using the old key, so we can
1579 * make new ones with the new key.
1582 while ((conn
= connection_or_get_by_identity_digest(
1583 old_router
->cache_info
.identity_digest
))) {
1584 // And LD_OR? XXXXNM
1585 log_info(LD_DIR
,"Closing conn to router '%s'; there is now a named "
1586 "router with that name.",
1587 old_router
->nickname
);
1588 connection_mark_for_close(conn
);
1590 routerlist_remove(routerlist
, old_router
, i
--, 0);
1591 } else if (old_router
->is_named
) {
1592 /* Can't replace a verified router with an unverified one. */
1593 log_debug(LD_DIR
, "Skipping unverified entry for verified router '%s'",
1595 routerinfo_free(router
);
1597 "Already have named router with same nickname and different key.";
1602 /* We haven't seen a router with this name before. Add it to the end of
1604 routerlist_insert(routerlist
, router
);
1606 router_append_to_journal(&router
->cache_info
);
1607 directory_set_dirty();
1612 _compare_old_routers_by_identity(const void **_a
, const void **_b
)
1615 const signed_descriptor_t
*r1
= *_a
, *r2
= *_b
;
1616 if ((i
= memcmp(r1
->identity_digest
, r2
->identity_digest
, DIGEST_LEN
)))
1618 return r1
->published_on
- r2
->published_on
;
1621 struct duration_idx_t
{
1628 _compare_duration_idx(const void *_d1
, const void *_d2
)
1630 const struct duration_idx_t
*d1
= _d1
;
1631 const struct duration_idx_t
*d2
= _d2
;
1632 return d1
->duration
- d2
->duration
;
1635 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
1636 * must contain routerinfo_t with the same identity and with publication time
1637 * in ascending order. Remove members from this range until there are no more
1638 * than MAX_DESCRIPTORS_PER_ROUTER remaining. Start by removing the oldest
1639 * members from before <b>cutoff</b>, then remove members which were current
1640 * for the lowest amount of time. The order of members of old_routers at
1641 * indices <b>lo</b> or higher may be changed.
1644 routerlist_remove_old_cached_routers_with_id(time_t cutoff
, int lo
, int hi
,
1645 digestmap_t
*retain
)
1647 int i
, n
= hi
-lo
+1, n_extra
;
1649 struct duration_idx_t
*lifespans
;
1650 uint8_t *rmv
, *must_keep
;
1651 smartlist_t
*lst
= routerlist
->old_routers
;
1654 tor_assert(hi
< smartlist_len(lst
));
1655 tor_assert(lo
<= hi
);
1656 ident
= ((signed_descriptor_t
*)smartlist_get(lst
, lo
))->identity_digest
;
1657 for (i
= lo
+1; i
<= hi
; ++i
) {
1658 signed_descriptor_t
*r
= smartlist_get(lst
, i
);
1659 tor_assert(!memcmp(ident
, r
->identity_digest
, DIGEST_LEN
));
1663 /* Check whether we need to do anything at all. */
1664 n_extra
= n
- MAX_DESCRIPTORS_PER_ROUTER
;
1668 lifespans
= tor_malloc_zero(sizeof(struct duration_idx_t
)*n
);
1669 rmv
= tor_malloc_zero(sizeof(uint8_t)*n
);
1670 must_keep
= tor_malloc_zero(sizeof(uint8_t)*n
);
1671 /* Set lifespans to contain the lifespan and index of each server. */
1672 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
1673 for (i
= lo
; i
<= hi
; ++i
) {
1674 signed_descriptor_t
*r
= smartlist_get(lst
, i
);
1675 signed_descriptor_t
*r_next
;
1676 lifespans
[i
-lo
].idx
= i
;
1677 if (retain
&& digestmap_get(retain
, r
->signed_descriptor_digest
)) {
1678 must_keep
[i
-lo
] = 1;
1681 r_next
= smartlist_get(lst
, i
+1);
1682 tor_assert(r
->published_on
<= r_next
->published_on
);
1683 lifespans
[i
-lo
].duration
= (r_next
->published_on
- r
->published_on
);
1686 lifespans
[i
-lo
].duration
= INT_MAX
;
1688 if (!must_keep
[i
-lo
] && r
->published_on
< cutoff
&& n_rmv
< n_extra
) {
1690 lifespans
[i
-lo
].old
= 1;
1695 if (n_rmv
< n_extra
) {
1697 * We aren't removing enough servers for being old. Sort lifespans by
1698 * the duration of liveness, and remove the ones we're not already going to
1699 * remove based on how long they were alive.
1701 qsort(lifespans
, n
, sizeof(struct duration_idx_t
), _compare_duration_idx
);
1702 for (i
= 0; i
< n
&& n_rmv
< n_extra
; ++i
) {
1703 if (!must_keep
[lifespans
[i
].idx
-lo
] && !lifespans
[i
].old
) {
1704 rmv
[lifespans
[i
].idx
-lo
] = 1;
1710 for (i
= hi
; i
>= lo
; --i
) {
1712 routerlist_remove_old(routerlist
, smartlist_get(lst
, i
), i
);
1714 tor_free(must_keep
);
1716 tor_free(lifespans
);
1719 /** Deactivate any routers from the routerlist that are more than
1720 * ROUTER_MAX_AGE seconds old; remove old routers from the list of
1721 * cached routers if we have too many.
1724 routerlist_remove_old_routers(void)
1727 const char *cur_id
= NULL
;
1728 time_t now
= time(NULL
);
1730 routerinfo_t
*router
;
1731 signed_descriptor_t
*sd
;
1732 digestmap_t
*retain
;
1733 or_options_t
*options
= get_options();
1734 if (!routerlist
|| !networkstatus_list
)
1737 retain
= digestmap_new();
1738 cutoff
= now
- OLD_ROUTER_DESC_MAX_AGE
;
1739 if (server_mode(options
) && options
->DirPort
) {
1740 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
1742 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
*, rs
,
1743 if (rs
->published_on
>= cutoff
)
1744 digestmap_set(retain
, rs
->descriptor_digest
, (void*)1));
1748 cutoff
= now
- ROUTER_MAX_AGE
;
1749 /* Remove too-old members of routerlist->routers. */
1750 for (i
= 0; i
< smartlist_len(routerlist
->routers
); ++i
) {
1751 router
= smartlist_get(routerlist
->routers
, i
);
1752 if (router
->cache_info
.published_on
<= cutoff
&&
1753 !digestmap_get(retain
, router
->cache_info
.signed_descriptor_digest
)) {
1754 /* Too old. Remove it. */
1756 "Forgetting obsolete (too old) routerinfo for router '%s'",
1758 routerlist_remove(routerlist
, router
, i
--, 1);
1762 /* Remove far-too-old members of routerlist->old_routers. */
1763 cutoff
= now
- OLD_ROUTER_DESC_MAX_AGE
;
1764 for (i
= 0; i
< smartlist_len(routerlist
->old_routers
); ++i
) {
1765 sd
= smartlist_get(routerlist
->old_routers
, i
);
1766 if (sd
->published_on
<= cutoff
&&
1767 !digestmap_get(retain
, sd
->signed_descriptor_digest
)) {
1768 /* Too old. Remove it. */
1769 routerlist_remove_old(routerlist
, sd
, i
--);
1773 /* Now we're looking at routerlist->old_routers for extraneous
1774 * members. (We'd keep all the members if we could, but we'd like to save
1775 * space.) First, check whether we have too many router descriptors, total.
1776 * We're okay with having too many for some given router, so long as the
1777 * total number doesn't approach MAX_DESCRIPTORS_PER_ROUTER*len(router).
1779 if (smartlist_len(routerlist
->old_routers
) <
1780 smartlist_len(routerlist
->routers
) * (MAX_DESCRIPTORS_PER_ROUTER
- 1))
1783 smartlist_sort(routerlist
->old_routers
, _compare_old_routers_by_identity
);
1785 /* Iterate through the list from back to front, so when we remove descriptors
1786 * we don't mess up groups we haven't gotten to. */
1787 for (i
= smartlist_len(routerlist
->old_routers
)-1; i
>= 0; --i
) {
1788 signed_descriptor_t
*r
= smartlist_get(routerlist
->old_routers
, i
);
1790 cur_id
= r
->identity_digest
;
1793 if (memcmp(cur_id
, r
->identity_digest
, DIGEST_LEN
)) {
1794 routerlist_remove_old_cached_routers_with_id(cutoff
, i
+1, hi
, retain
);
1795 cur_id
= r
->identity_digest
;
1800 routerlist_remove_old_cached_routers_with_id(cutoff
, 0, hi
, retain
);
1801 routerlist_assert_ok(routerlist
);
1804 digestmap_free(retain
, NULL
);
1808 * Code to parse a single router descriptor and insert it into the
1809 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
1810 * descriptor was well-formed but could not be added; and 1 if the
1811 * descriptor was added.
1813 * If we don't add it and <b>msg</b> is not NULL, then assign to
1814 * *<b>msg</b> a static string describing the reason for refusing the
1817 * This is used only by the controller.
1820 router_load_single_router(const char *s
, const char **msg
)
1828 if (!(ri
= router_parse_entry_from_string(s
, NULL
))) {
1829 log_warn(LD_DIR
, "Error parsing router descriptor; dropping.");
1830 *msg
= "Couldn't parse router descriptor.";
1833 if (router_is_me(ri
)) {
1834 log_warn(LD_DIR
, "Router's identity key matches mine; dropping.");
1835 *msg
= "Router's identity key matches mine.";
1836 routerinfo_free(ri
);
1840 lst
= smartlist_create();
1841 smartlist_add(lst
, ri
);
1842 routers_update_status_from_networkstatus(lst
, 0);
1844 if ((r
=router_add_to_routerlist(ri
, msg
, 0, 0))<0) {
1845 /* we've already assigned to *msg now, and ri is already freed */
1848 log_warn(LD_DIR
, "Couldn't add router to list: %s Dropping.", *msg
);
1849 smartlist_free(lst
);
1852 control_event_descriptors_changed(lst
);
1853 smartlist_free(lst
);
1854 log_debug(LD_DIR
, "Added router to list");
1859 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
1860 * routers into our directory. If <b>from_cache</b> is false, the routers
1861 * are in response to a query to the network: cache them.
1863 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1864 * uppercased identity fingerprints. Do not update any router whose
1865 * fingerprint is not on the list; after updating a router, remove its
1866 * fingerprint from the list.
1869 router_load_routers_from_string(const char *s
, int from_cache
,
1870 smartlist_t
*requested_fingerprints
)
1872 smartlist_t
*routers
= smartlist_create(), *changed
= smartlist_create();
1873 char fp
[HEX_DIGEST_LEN
+1];
1876 router_parse_list_from_string(&s
, routers
);
1878 routers_update_status_from_networkstatus(routers
, !from_cache
);
1880 log_info(LD_DIR
, "%d elements to add", smartlist_len(routers
));
1882 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
,
1884 base16_encode(fp
, sizeof(fp
), ri
->cache_info
.signed_descriptor_digest
,
1886 if (requested_fingerprints
) {
1887 if (smartlist_string_isin(requested_fingerprints
, fp
)) {
1888 smartlist_string_remove(requested_fingerprints
, fp
);
1891 smartlist_join_strings(requested_fingerprints
," ",0,NULL
);
1893 "We received a router descriptor with a fingerprint (%s) "
1894 "that we never requested. (We asked for: %s.) Dropping.",
1896 tor_free(requested
);
1897 routerinfo_free(ri
);
1902 if (router_add_to_routerlist(ri
, &msg
, from_cache
, !from_cache
) >= 0)
1903 smartlist_add(changed
, ri
);
1906 if (smartlist_len(changed
))
1907 control_event_descriptors_changed(changed
);
1909 routerlist_assert_ok(routerlist
);
1910 router_rebuild_store(0);
1912 smartlist_free(routers
);
1913 smartlist_free(changed
);
1916 /** Helper: return a newly allocated string containing the name of the filename
1917 * where we plan to cache <b>ns</b>. */
1919 networkstatus_get_cache_filename(const networkstatus_t
*ns
)
1921 const char *datadir
= get_options()->DataDirectory
;
1922 size_t len
= strlen(datadir
)+64;
1923 char fp
[HEX_DIGEST_LEN
+1];
1924 char *fn
= tor_malloc(len
+1);
1925 base16_encode(fp
, HEX_DIGEST_LEN
+1, ns
->identity_digest
, DIGEST_LEN
);
1926 tor_snprintf(fn
, len
, "%s/cached-status/%s",datadir
,fp
);
1930 /** Helper for smartlist_sort: Compare two networkstatus objects by
1931 * publication date. */
1933 _compare_networkstatus_published_on(const void **_a
, const void **_b
)
1935 const networkstatus_t
*a
= *_a
, *b
= *_b
;
1936 if (a
->published_on
< b
->published_on
)
1938 else if (a
->published_on
> b
->published_on
)
1944 /** Add the parsed neworkstatus in <b>ns</b> (with original document in
1945 * <b>s</b> to the disk cache (and the in-memory directory server cache) as
1948 add_networkstatus_to_cache(const char *s
,
1949 networkstatus_source_t source
,
1950 networkstatus_t
*ns
)
1952 if (source
!= NS_FROM_CACHE
) {
1953 char *fn
= networkstatus_get_cache_filename(ns
);
1954 if (write_str_to_file(fn
, s
, 0)<0) {
1955 log_notice(LD_FS
, "Couldn't write cached network status to \"%s\"", fn
);
1960 if (get_options()->DirPort
)
1961 dirserv_set_cached_networkstatus_v2(s
,
1962 ns
->identity_digest
,
1968 /** How far in the future do we allow a network-status to get before removing
1970 #define NETWORKSTATUS_ALLOW_SKEW (48*60*60)
1971 /** Given a string <b>s</b> containing a network status that we received at
1972 * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
1973 * store it, and put it into our cache is necessary.
1975 * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
1976 * own networkstatus_t (if we're a directory server).
1978 * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
1981 * If <b>requested_fingerprints</b> is provided, it must contain a list of
1982 * uppercased identity fingerprints. Do not update any networkstatus whose
1983 * fingerprint is not on the list; after updating a networkstatus, remove its
1984 * fingerprint from the list.
1986 * Return 0 on success, -1 on failure.
1988 * Callers should make sure that routers_update_all_from_networkstatus() is
1989 * invoked after this function succeeds.
1992 router_set_networkstatus(const char *s
, time_t arrived_at
,
1993 networkstatus_source_t source
, smartlist_t
*requested_fingerprints
)
1995 networkstatus_t
*ns
;
1999 trusted_dir_server_t
*trusted_dir
= NULL
;
2000 const char *source_desc
= NULL
;
2001 char fp
[HEX_DIGEST_LEN
+1];
2002 char published
[ISO_TIME_LEN
+1];
2004 ns
= networkstatus_parse_from_string(s
);
2006 log_warn(LD_DIR
, "Couldn't parse network status.");
2009 base16_encode(fp
, HEX_DIGEST_LEN
+1, ns
->identity_digest
, DIGEST_LEN
);
2011 router_get_trusteddirserver_by_digest(ns
->identity_digest
))) {
2012 log_info(LD_DIR
, "Network status was signed, but not by an authoritative "
2013 "directory we recognize.");
2014 if (!get_options()->DirPort
) {
2015 networkstatus_free(ns
);
2020 source_desc
= trusted_dir
->description
;
2023 if (arrived_at
> now
)
2026 ns
->received_on
= arrived_at
;
2028 format_iso_time(published
, ns
->published_on
);
2030 if (ns
->published_on
> now
+ NETWORKSTATUS_ALLOW_SKEW
) {
2031 log_warn(LD_GENERAL
, "Network status from %s was published in the future "
2032 "(%s GMT). Somebody is skewed here: check your clock. "
2034 source_desc
, published
);
2038 if (!networkstatus_list
)
2039 networkstatus_list
= smartlist_create();
2041 if (source
== NS_FROM_DIR
&& router_digest_is_me(ns
->identity_digest
)) {
2042 /* Don't replace our own networkstatus when we get it from somebody else.*/
2043 networkstatus_free(ns
);
2047 if (requested_fingerprints
) {
2048 if (smartlist_string_isin(requested_fingerprints
, fp
)) {
2049 smartlist_string_remove(requested_fingerprints
, fp
);
2052 smartlist_join_strings(requested_fingerprints
," ",0,NULL
);
2054 "We received a network status with a fingerprint (%s) that we "
2055 "never requested. (We asked for: %s.) Dropping.",
2057 tor_free(requested
);
2063 if (!skewed
&& get_options()->DirPort
) {
2064 add_networkstatus_to_cache(s
, source
, ns
);
2065 networkstatus_free(ns
);
2070 if (source
!= NS_FROM_CACHE
&& trusted_dir
)
2071 trusted_dir
->n_networkstatus_failures
= 0;
2074 for (i
=0; i
< smartlist_len(networkstatus_list
); ++i
) {
2075 networkstatus_t
*old_ns
= smartlist_get(networkstatus_list
, i
);
2077 if (!memcmp(old_ns
->identity_digest
, ns
->identity_digest
, DIGEST_LEN
)) {
2078 if (!memcmp(old_ns
->networkstatus_digest
,
2079 ns
->networkstatus_digest
, DIGEST_LEN
)) {
2080 /* Same one we had before. */
2081 networkstatus_free(ns
);
2083 "Not replacing network-status from %s (published %s); "
2084 "we already have it.",
2085 trusted_dir
->description
, published
);
2086 if (old_ns
->received_on
< arrived_at
) {
2087 if (source
!= NS_FROM_CACHE
) {
2088 char *fn
= networkstatus_get_cache_filename(old_ns
);
2089 /* We use mtime to tell when it arrived, so update that. */
2093 old_ns
->received_on
= arrived_at
;
2096 } else if (old_ns
->published_on
>= ns
->published_on
) {
2097 char old_published
[ISO_TIME_LEN
+1];
2098 format_iso_time(old_published
, old_ns
->published_on
);
2100 "Not replacing network-status from %s (published %s);"
2101 " we have a newer one (published %s) for this authority.",
2102 trusted_dir
->description
, published
,
2104 networkstatus_free(ns
);
2107 networkstatus_free(old_ns
);
2108 smartlist_set(networkstatus_list
, i
, ns
);
2116 smartlist_add(networkstatus_list
, ns
);
2118 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
*, rs
,
2120 if (!router_get_by_descriptor_digest(rs
->descriptor_digest
))
2121 rs
->need_to_mirror
= 1;
2124 log_info(LD_DIR
, "Setting networkstatus %s %s (published %s)",
2125 source
== NS_FROM_CACHE
?"cached from":
2126 (source
==NS_FROM_DIR
?"downloaded from":"generated for"),
2127 trusted_dir
->description
, published
);
2128 networkstatus_list_has_changed
= 1;
2130 smartlist_sort(networkstatus_list
, _compare_networkstatus_published_on
);
2133 add_networkstatus_to_cache(s
, source
, ns
);
2135 networkstatus_list_update_recent(now
);
2140 /** How old do we allow a network-status to get before removing it
2142 #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
2143 /** Remove all very-old network_status_t objects from memory and from the
2146 networkstatus_list_clean(time_t now
)
2149 if (!networkstatus_list
)
2152 for (i
= 0; i
< smartlist_len(networkstatus_list
); ++i
) {
2153 networkstatus_t
*ns
= smartlist_get(networkstatus_list
, i
);
2154 char *fname
= NULL
;;
2155 if (ns
->published_on
+ MAX_NETWORKSTATUS_AGE
> now
)
2157 /* Okay, this one is too old. Remove it from the list, and delete it
2158 * from the cache. */
2159 smartlist_del(networkstatus_list
, i
--);
2160 fname
= networkstatus_get_cache_filename(ns
);
2161 if (file_status(fname
) == FN_FILE
) {
2162 log_info(LD_DIR
, "Removing too-old networkstatus in %s", fname
);
2166 if (get_options()->DirPort
) {
2167 dirserv_set_cached_networkstatus_v2(NULL
, ns
->identity_digest
, 0);
2169 networkstatus_free(ns
);
2173 /** Helper for bsearching a list of routerstatus_t pointers.*/
2175 _compare_digest_to_routerstatus_entry(const void *_key
, const void **_member
)
2177 const char *key
= _key
;
2178 const routerstatus_t
*rs
= *_member
;
2179 return memcmp(key
, rs
->identity_digest
, DIGEST_LEN
);
2182 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
2183 * NULL if none was found. */
2184 static routerstatus_t
*
2185 networkstatus_find_entry(networkstatus_t
*ns
, const char *digest
)
2187 return smartlist_bsearch(ns
->entries
, digest
,
2188 _compare_digest_to_routerstatus_entry
);
2191 /** Return the consensus view of the status of the router whose digest is
2192 * <b>digest</b>, or NULL if we don't know about any such router. */
2193 local_routerstatus_t
*
2194 router_get_combined_status_by_digest(const char *digest
)
2196 if (!routerstatus_list
)
2198 return smartlist_bsearch(routerstatus_list
, digest
,
2199 _compare_digest_to_routerstatus_entry
);
2202 /** Return true iff any networkstatus includes a descriptor whose digest
2203 * is that of <b>desc</b>. */
2205 signed_desc_digest_is_recognized(signed_descriptor_t
*desc
)
2208 if (!networkstatus_list
)
2211 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
2213 if (!(rs
= networkstatus_find_entry(ns
, desc
->identity_digest
)))
2215 if (!memcmp(rs
->descriptor_digest
,
2216 desc
->signed_descriptor_digest
, DIGEST_LEN
))
2222 /* XXXX These should be configurable, perhaps? NM */
2223 #define AUTHORITY_NS_CACHE_INTERVAL 5*60
2224 #define NONAUTHORITY_NS_CACHE_INTERVAL 15*60
2225 /** We are a directory server, and so cache network_status documents.
2226 * Initiate downloads as needed to update them. For authorities, this means
2227 * asking each trusted directory for its network-status. For caches, this
2228 * means asking a random authority for all network-statuses.
2231 update_networkstatus_cache_downloads(time_t now
)
2233 int authority
= authdir_mode(get_options());
2235 authority
? AUTHORITY_NS_CACHE_INTERVAL
: NONAUTHORITY_NS_CACHE_INTERVAL
;
2237 if (last_networkstatus_download_attempted
+ interval
>= now
)
2239 if (!trusted_dir_servers
)
2242 last_networkstatus_download_attempted
= now
;
2245 /* An authority launches a separate connection for everybody. */
2246 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
2248 char resource
[HEX_DIGEST_LEN
+6];
2249 if (router_digest_is_me(ds
->digest
))
2251 if (connection_get_by_type_addr_port_purpose(
2252 CONN_TYPE_DIR
, ds
->addr
, ds
->dir_port
,
2253 DIR_PURPOSE_FETCH_NETWORKSTATUS
)) {
2254 /* We are already fetching this one. */
2257 strlcpy(resource
, "fp/", sizeof(resource
));
2258 base16_encode(resource
+3, sizeof(resource
)-3, ds
->digest
, DIGEST_LEN
);
2259 strlcat(resource
, ".z", sizeof(resource
));
2260 directory_initiate_command_routerstatus(
2261 &ds
->fake_status
, DIR_PURPOSE_FETCH_NETWORKSTATUS
,
2262 0, /* Not private */
2264 NULL
, 0 /* No payload. */);
2267 /* A non-authority cache launches one connection to a random authority. */
2268 /* (Check whether we're currently fetching network-status objects.) */
2269 if (!connection_get_by_type_purpose(CONN_TYPE_DIR
,
2270 DIR_PURPOSE_FETCH_NETWORKSTATUS
))
2271 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS
,"all.z",1);
2275 /*XXXX Should these be configurable? NM*/
2276 /** How old (in seconds) can a network-status be before we try replacing it? */
2277 #define NETWORKSTATUS_MAX_VALIDITY (48*60*60)
2278 /** How long (in seconds) does a client wait after getting a network status
2279 * before downloading the next in sequence? */
2280 #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
2281 /* How many times do we allow a networkstatus download to fail before we
2282 * assume that the authority isn't publishing? */
2283 #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
2284 /** We are not a directory cache or authority. Update our network-status list
2285 * by launching a new directory fetch for enough network-status documents "as
2286 * necessary". See function comments for implementation details.
2289 update_networkstatus_client_downloads(time_t now
)
2291 int n_live
= 0, needed
= 0, n_running_dirservers
, n_dirservers
, i
;
2292 int most_recent_idx
= -1;
2293 trusted_dir_server_t
*most_recent
= NULL
;
2294 time_t most_recent_received
= 0;
2295 char *resource
, *cp
;
2296 size_t resource_len
;
2298 if (connection_get_by_type_purpose(CONN_TYPE_DIR
,
2299 DIR_PURPOSE_FETCH_NETWORKSTATUS
))
2302 /* This is a little tricky. We want to download enough network-status
2303 * objects so that we have at least half of them under
2304 * NETWORKSTATUS_MAX_VALIDITY publication time. We want to download a new
2305 * *one* if the most recent one's publication time is under
2306 * NETWORKSTATUS_CLIENT_DL_INTERVAL.
2308 if (!trusted_dir_servers
|| !smartlist_len(trusted_dir_servers
))
2310 n_dirservers
= n_running_dirservers
= smartlist_len(trusted_dir_servers
);
2311 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
2313 networkstatus_t
*ns
= networkstatus_get_by_digest(ds
->digest
);
2316 if (ds
->n_networkstatus_failures
> NETWORKSTATUS_N_ALLOWABLE_FAILURES
) {
2317 --n_running_dirservers
;
2320 if (ns
->published_on
> now
-NETWORKSTATUS_MAX_VALIDITY
)
2322 if (!most_recent
|| ns
->received_on
> most_recent_received
) {
2323 most_recent_idx
= ds_sl_idx
; /* magic variable from FOREACH */
2325 most_recent_received
= ns
->received_on
;
2329 /* Download enough so we have at least half live, but no more than all the
2330 * trusted dirservers we know.
2332 if (n_live
< (n_dirservers
/2)+1)
2333 needed
= (n_dirservers
/2)+1-n_live
;
2334 if (needed
> n_running_dirservers
)
2335 needed
= n_running_dirservers
;
2338 log_info(LD_DIR
, "For %d/%d running directory servers, we have %d live"
2339 " network-status documents. Downloading %d.",
2340 n_running_dirservers
, n_dirservers
, n_live
, needed
);
2342 /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
2343 if (n_running_dirservers
&&
2344 most_recent_received
< now
-NETWORKSTATUS_CLIENT_DL_INTERVAL
&&
2346 log_info(LD_DIR
, "Our most recent network-status document (from %s) "
2347 "is %d seconds old; downloading another.",
2348 most_recent
?most_recent
->description
:"nobody",
2349 (int)(now
-most_recent_received
));
2356 /* If no networkstatus was found, choose a dirserver at random as "most
2358 if (most_recent_idx
<0)
2359 most_recent_idx
= crypto_rand_int(n_dirservers
);
2361 /* Build a request string for all the resources we want. */
2362 resource_len
= needed
* (HEX_DIGEST_LEN
+1) + 6;
2363 resource
= tor_malloc(resource_len
);
2364 memcpy(resource
, "fp/", 3);
2366 for (i
= most_recent_idx
+1; needed
; ++i
) {
2367 trusted_dir_server_t
*ds
;
2368 if (i
>= n_dirservers
)
2370 ds
= smartlist_get(trusted_dir_servers
, i
);
2371 if (ds
->n_networkstatus_failures
> NETWORKSTATUS_N_ALLOWABLE_FAILURES
)
2373 base16_encode(cp
, HEX_DIGEST_LEN
+1, ds
->digest
, DIGEST_LEN
);
2374 cp
+= HEX_DIGEST_LEN
;
2379 memcpy(cp
, ".z", 3);
2380 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS
, resource
, 1);
2384 /** Launch requests for networkstatus documents as appropriate. */
2386 update_networkstatus_downloads(time_t now
)
2388 or_options_t
*options
= get_options();
2389 if (server_mode(options
) && options
->DirPort
)
2390 update_networkstatus_cache_downloads(time(NULL
));
2392 update_networkstatus_client_downloads(time(NULL
));
2395 /** Decide whether a given addr:port is definitely accepted,
2396 * definitely rejected, probably accepted, or probably rejected by a
2397 * given policy. If <b>addr</b> is 0, we don't know the IP of the
2398 * target address. If <b>port</b> is 0, we don't know the port of the
2401 * For now, the algorithm is pretty simple: we look for definite and
2402 * uncertain matches. The first definite match is what we guess; if
2403 * it was preceded by no uncertain matches of the opposite policy,
2404 * then the guess is definite; otherwise it is probable. (If we
2405 * have a known addr and port, all matches are definite; if we have an
2406 * unknown addr/port, any address/port ranges other than "all" are
2409 * We could do better by assuming that some ranges never match typical
2410 * addresses (127.0.0.1, and so on). But we'll try this for now.
2412 addr_policy_result_t
2413 router_compare_addr_to_addr_policy(uint32_t addr
, uint16_t port
,
2414 addr_policy_t
*policy
)
2416 int maybe_reject
= 0;
2417 int maybe_accept
= 0;
2420 addr_policy_t
*tmpe
;
2422 for (tmpe
=policy
; tmpe
; tmpe
=tmpe
->next
) {
2425 /* Address is unknown. */
2426 if ((port
>= tmpe
->prt_min
&& port
<= tmpe
->prt_max
) ||
2427 (!port
&& tmpe
->prt_min
<=1 && tmpe
->prt_max
>=65535)) {
2428 /* The port definitely matches. */
2429 if (tmpe
->msk
== 0) {
2435 /* The port maybe matches. */
2439 /* Address is known */
2440 if ((addr
& tmpe
->msk
) == (tmpe
->addr
& tmpe
->msk
)) {
2441 if (port
>= tmpe
->prt_min
&& port
<= tmpe
->prt_max
) {
2442 /* Exact match for the policy */
2450 if (tmpe
->policy_type
== ADDR_POLICY_REJECT
)
2456 if (tmpe
->policy_type
== ADDR_POLICY_ACCEPT
) {
2457 /* If we already hit a clause that might trigger a 'reject', than we
2458 * can't be sure of this certain 'accept'.*/
2459 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
:
2460 ADDR_POLICY_ACCEPTED
;
2462 return maybe_accept
? ADDR_POLICY_PROBABLY_REJECTED
:
2463 ADDR_POLICY_REJECTED
;
2467 /* accept all by default. */
2468 return maybe_reject
? ADDR_POLICY_PROBABLY_ACCEPTED
: ADDR_POLICY_ACCEPTED
;
2471 /** Return 1 if all running sufficiently-stable routers will reject
2472 * addr:port, return 0 if any might accept it. */
2474 router_exit_policy_all_routers_reject(uint32_t addr
, uint16_t port
,
2477 addr_policy_result_t r
;
2478 if (!routerlist
) return 1;
2480 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
2482 if (router
->is_running
&&
2483 !router_is_unreliable(router
, need_uptime
, 0, 0)) {
2484 r
= router_compare_addr_to_addr_policy(addr
, port
, router
->exit_policy
);
2485 if (r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
)
2486 return 0; /* this one could be ok. good enough. */
2489 return 1; /* all will reject. */
2494 * If <b>policy</b> implicitly allows connections to any port in the
2495 * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
2496 * part of the policy that allows it, and return 1. Else return 0.
2498 * A policy allows an IP:Port combination <em>implicitly</em> if
2499 * it is included in a *: pattern, or in a fallback pattern.
2502 policy_includes_addr_mask_implicitly(addr_policy_t
*policy
,
2503 uint32_t addr
, uint32_t mask
,
2504 addr_policy_t
**policy_out
)
2507 tor_assert(policy_out
);
2509 addr2
= addr
| ~mask
;
2510 for (; policy
; policy
=policy
->next
) {
2511 /* Does this policy cover all of the address range we're looking at? */
2512 /* Boolean logic time: range X is contained in range Y if, for
2513 * each bit B, all possible values of B in X are values of B in Y.
2514 * In "addr", we have every fixed bit set to its value, and every
2515 * free bit set to 0. In "addr2", we have every fixed bit set to
2516 * its value, and every free bit set to 1. So if addr and addr2 are
2517 * both in the policy, the range is covered by the policy.
2519 uint32_t p_addr
= policy
->addr
& policy
->msk
;
2520 if (p_addr
== (addr
& policy
->msk
) &&
2521 p_addr
== (addr2
& policy
->msk
) &&
2522 (policy
->prt_min
<= 1 && policy
->prt_max
== 65535) &&
2523 policy
->policy_type
== ADDR_POLICY_REJECT
) {
2526 /* Does this policy cover some of the address range we're looking at? */
2527 /* Boolean logic time: range X and range Y intersect if there is
2528 * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
2529 * This is FALSE iff there is some bit b where Xmask == yMask == 1
2530 * and Xaddr != Yaddr. So if X intersects with Y iff at every
2531 * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
2532 * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
2534 if ((policy
->addr
& policy
->msk
& mask
) == (addr
& policy
->msk
) &&
2535 policy
->policy_type
== ADDR_POLICY_ACCEPT
) {
2536 *policy_out
= policy
;
2544 /** If <b>policy</b> implicitly allows connections to any port on
2545 * 127.*, 192.168.*, etc, then warn (if <b>should_warn</b> is set) and return
2546 * true. Else return false.
2549 exit_policy_implicitly_allows_local_networks(addr_policy_t
*policy
,
2555 uint32_t addr
; uint32_t mask
; const char *network
;
2556 } private_networks
[] = {
2557 { 0x00000000, 0xff000000, "\"this\" network (0.0.0.0/8)" },
2558 { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
2559 { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
2560 { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
2561 { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
2562 { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
2565 for (i
=0; private_networks
[i
].mask
; ++i
) {
2567 /* log_info(LD_CONFIG,
2568 "Checking network %s", private_networks[i].network); */
2569 if (policy_includes_addr_mask_implicitly(
2570 policy
, private_networks
[i
].addr
, private_networks
[i
].mask
, &p
)) {
2572 log_warn(LD_CONFIG
, "Exit policy %s implicitly accepts %s",
2573 p
?p
->string
:"(default)",
2574 private_networks
[i
].network
);
2583 /** Return true iff <b>router</b> does not permit exit streams.
2586 router_exit_policy_rejects_all(routerinfo_t
*router
)
2588 return router_compare_addr_to_addr_policy(0, 0, router
->exit_policy
)
2589 == ADDR_POLICY_REJECTED
;
2592 /** Add to the list of authorized directory servers one at
2593 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
2594 * <b>address</b> is NULL, add ourself. */
2596 add_trusted_dir_server(const char *nickname
, const char *address
,
2597 uint16_t port
, const char *digest
, int supports_v1
)
2599 trusted_dir_server_t
*ent
;
2601 char *hostname
= NULL
;
2603 if (!trusted_dir_servers
)
2604 trusted_dir_servers
= smartlist_create();
2606 if (!address
) { /* The address is us; we should guess. */
2607 if (resolve_my_address(get_options(), &a
, &hostname
) < 0) {
2609 "Couldn't find a suitable address when adding ourself as a "
2610 "trusted directory server.");
2614 if (tor_lookup_hostname(address
, &a
)) {
2616 "Unable to lookup address for directory server at '%s'",
2620 hostname
= tor_strdup(address
);
2624 ent
= tor_malloc_zero(sizeof(trusted_dir_server_t
));
2625 ent
->nickname
= nickname
? tor_strdup(nickname
) : NULL
;
2626 ent
->address
= hostname
;
2628 ent
->dir_port
= port
;
2629 ent
->is_running
= 1;
2630 ent
->is_v1_authority
= supports_v1
;
2631 memcpy(ent
->digest
, digest
, DIGEST_LEN
);
2633 dlen
= 64 + strlen(hostname
) + (nickname
?strlen(nickname
):0);
2634 ent
->description
= tor_malloc(dlen
);
2636 tor_snprintf(ent
->description
, dlen
, "directory server \"%s\" at %s:%d",
2637 nickname
, hostname
, (int)port
);
2639 tor_snprintf(ent
->description
, dlen
, "directory server at %s:%d",
2640 hostname
, (int)port
);
2642 ent
->fake_status
.addr
= ent
->addr
;
2643 memcpy(ent
->fake_status
.identity_digest
, digest
, DIGEST_LEN
);
2645 strlcpy(ent
->fake_status
.nickname
, nickname
,
2646 sizeof(ent
->fake_status
.nickname
));
2648 ent
->fake_status
.nickname
[0] = '\0';
2649 ent
->fake_status
.dir_port
= ent
->dir_port
;
2651 smartlist_add(trusted_dir_servers
, ent
);
2654 /** Free storage held in <b>ds</b> */
2656 trusted_dir_server_free(trusted_dir_server_t
*ds
)
2658 tor_free(ds
->nickname
);
2659 tor_free(ds
->description
);
2660 tor_free(ds
->address
);
2664 /** Remove all members from the list of trusted dir servers. */
2666 clear_trusted_dir_servers(void)
2668 if (trusted_dir_servers
) {
2669 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
2670 trusted_dir_server_free(ent
));
2671 smartlist_clear(trusted_dir_servers
);
2673 trusted_dir_servers
= smartlist_create();
2677 /** Return the network status with a given identity digest. */
2679 networkstatus_get_by_digest(const char *digest
)
2681 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
2683 if (!memcmp(ns
->identity_digest
, digest
, DIGEST_LEN
))
2689 /** We believe networkstatuses more recent than this when they tell us that
2690 * our server is broken, invalid, obsolete, etc. */
2691 #define SELF_OPINION_INTERVAL 90*60
2693 /** Return a string naming the versions of Tor recommended by
2694 * at least n_needed versioning networkstatuses */
2696 compute_recommended_versions(time_t now
, int client
)
2700 smartlist_t
*combined
, *recommended
;
2704 if (!networkstatus_list
)
2705 return tor_strdup("<none>");
2707 combined
= smartlist_create();
2709 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
2712 if (! ns
->recommends_versions
)
2714 if (ns
->received_on
+ SELF_OPINION_INTERVAL
< now
)
2717 vers
= client
? ns
->client_versions
: ns
->server_versions
;
2720 smartlist_split_string(combined
, vers
, ",",
2721 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2724 sort_version_list(combined
);
2728 recommended
= smartlist_create();
2729 SMARTLIST_FOREACH(combined
, char *, cp
,
2731 if (current
&& !strcmp(cp
, current
)) {
2734 if (n_seen
>= n_recent
/2 && current
)
2735 smartlist_add(recommended
, current
);
2740 if (n_seen
>= n_recent
/2 && current
)
2741 smartlist_add(recommended
, current
);
2743 result
= smartlist_join_strings(recommended
, ", ", 0, NULL
);
2745 SMARTLIST_FOREACH(combined
, char *, cp
, tor_free(cp
));
2746 smartlist_free(combined
);
2747 smartlist_free(recommended
);
2752 /** If the network-status list has changed since the last time we called this
2753 * function, update the status of every routerinfo from the network-status
2757 routers_update_all_from_networkstatus(void)
2761 if (!routerlist
|| !networkstatus_list
||
2762 (!networkstatus_list_has_changed
&& !routerstatus_list_has_changed
))
2766 if (networkstatus_list_has_changed
)
2767 routerstatus_list_update_from_networkstatus(now
);
2769 routers_update_status_from_networkstatus(routerlist
->routers
, 0);
2771 me
= router_get_my_routerinfo();
2772 if (me
&& !have_warned_about_unverified_status
) {
2773 int n_recent
= 0, n_listing
= 0, n_valid
= 0, n_named
= 0;
2775 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
2777 if (ns
->received_on
+ SELF_OPINION_INTERVAL
< now
)
2780 if (!(rs
= networkstatus_find_entry(ns
, me
->cache_info
.identity_digest
)))
2789 if (n_recent
>= 2 && n_listing
>= 2) {
2790 /* XXX When we have more than 3 dirservers, these warnings
2791 * might become spurious depending on which combination of
2792 * network-statuses we have. Perhaps we should wait until we
2793 * have tried all of them? -RD */
2794 if (n_valid
<= n_recent
/2) {
2795 log_warn(LD_GENERAL
,
2796 "%d/%d recent directory servers list us as invalid. Please "
2797 "consider sending your identity fingerprint to the tor-ops.",
2798 n_recent
-n_valid
, n_recent
);
2799 have_warned_about_unverified_status
= 1;
2800 } else if (!n_named
) { // (n_named <= n_recent/2) {
2801 log_warn(LD_GENERAL
, "0/%d recent directory servers recognize this "
2802 "server. Please consider sending your identity fingerprint "
2805 have_warned_about_unverified_status
= 1;
2810 entry_guards_set_status_from_directory();
2812 if (!have_warned_about_old_version
) {
2814 int n_recommended
= 0;
2815 int is_server
= server_mode(get_options());
2816 version_status_t consensus
= VS_RECOMMENDED
;
2817 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
2819 version_status_t vs
;
2820 if (!ns
->recommends_versions
||
2821 ns
->received_on
+ SELF_OPINION_INTERVAL
< now
)
2823 vs
= tor_version_is_obsolete(
2824 VERSION
, is_server
? ns
->server_versions
: ns
->client_versions
);
2825 if (vs
== VS_RECOMMENDED
)
2827 if (n_recent
++ == 0) {
2829 } else if (consensus
!= vs
) {
2830 consensus
= version_status_join(consensus
, vs
);
2833 if (n_recent
> 2 && n_recommended
< n_recent
/2) {
2834 if (consensus
== VS_NEW
|| consensus
== VS_NEW_IN_SERIES
) {
2835 if (!have_warned_about_new_version
) {
2836 char *rec
= compute_recommended_versions(now
, !is_server
);
2837 log_notice(LD_GENERAL
, "This version of Tor (%s) is newer than any "
2838 "recommended version%s, according to %d/%d recent network "
2839 "statuses. Versions recommended by at least %d recent "
2840 "authorit%s are: %s",
2842 consensus
== VS_NEW_IN_SERIES
? " in its series" : "",
2843 n_recent
-n_recommended
, n_recent
, n_recent
/2,
2844 n_recent
/2 > 1 ? "ies" : "y", rec
);
2845 have_warned_about_new_version
= 1;
2849 char *rec
= compute_recommended_versions(now
, !is_server
);
2850 log_warn(LD_GENERAL
, "Please upgrade! "
2851 "This version of Tor (%s) is %s, according to "
2852 "%d/%d recent network statuses. Versions recommended by "
2853 "at least %d recent authorit%s are: %s",
2854 VERSION
, consensus
== VS_OLD
? "obsolete" : "not recommended",
2855 n_recent
-n_recommended
, n_recent
, n_recent
/2,
2856 n_recent
/2 > 1 ? "ies" : "y", rec
);
2857 have_warned_about_old_version
= 1;
2861 log_info(LD_GENERAL
, "%d/%d recent directories think my version is ok.",
2862 n_recommended
, n_recent
);
2866 routerstatus_list_has_changed
= 0;
2869 /** Allow any network-status newer than this to influence our view of who's
2871 #define DEFAULT_RUNNING_INTERVAL 60*60
2872 /** If possible, always allow at least this many network-statuses to influence
2873 * our view of who's running. */
2874 #define MIN_TO_INFLUENCE_RUNNING 3
2876 /** Change the is_recent field of each member of networkstatus_list so that
2877 * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
2878 * at least the MIN_TO_INFLUENCE_RUNNING most recent members are recent, and no
2879 * others are recent. Set networkstatus_list_has_changed if anything happened.
2882 networkstatus_list_update_recent(time_t now
)
2884 int n_statuses
, n_recent
, changed
, i
;
2885 char published
[ISO_TIME_LEN
+1];
2887 if (!networkstatus_list
)
2890 n_statuses
= smartlist_len(networkstatus_list
);
2893 for (i
=n_statuses
-1; i
>= 0; --i
) {
2894 networkstatus_t
*ns
= smartlist_get(networkstatus_list
, i
);
2895 trusted_dir_server_t
*ds
=
2896 router_get_trusteddirserver_by_digest(ns
->identity_digest
);
2897 const char *src
= ds
?ds
->description
:ns
->source_address
;
2898 if (n_recent
< MIN_TO_INFLUENCE_RUNNING
||
2899 ns
->published_on
+ DEFAULT_RUNNING_INTERVAL
> now
) {
2900 if (!ns
->is_recent
) {
2901 format_iso_time(published
, ns
->published_on
);
2903 "Networkstatus from %s (published %s) is now \"recent\"",
2910 if (ns
->is_recent
) {
2911 format_iso_time(published
, ns
->published_on
);
2913 "Networkstatus from %s (published %s) is "
2914 "no longer \"recent\"",
2922 networkstatus_list_has_changed
= 1;
2925 /** Helper for routerstatus_list_update_from_networkstatus: remember how many
2926 * authorities recommend a given descriptor digest. */
2930 } desc_digest_count_t
;
2932 /** Update our view of router status (as stored in routerstatus_list) from the
2933 * current set of network status documents (as stored in networkstatus_list).
2934 * Do nothing unless the network status list has changed since the last time
2935 * this function was called.
2938 routerstatus_list_update_from_networkstatus(time_t now
)
2940 or_options_t
*options
= get_options();
2941 int n_trusted
, n_statuses
, n_recent
= 0, n_naming
= 0;
2944 networkstatus_t
**networkstatus
;
2945 smartlist_t
*result
;
2947 char conflict
[DIGEST_LEN
]; /* Sentinel value */
2948 desc_digest_count_t
*digest_counts
= NULL
;
2950 /* compute which network statuses will have a vote now */
2951 networkstatus_list_update_recent(now
);
2953 if (!networkstatus_list_has_changed
)
2955 if (!networkstatus_list
)
2956 networkstatus_list
= smartlist_create();
2957 if (!routerstatus_list
)
2958 routerstatus_list
= smartlist_create();
2959 if (!trusted_dir_servers
)
2960 trusted_dir_servers
= smartlist_create();
2961 if (!warned_conflicts
)
2962 warned_conflicts
= smartlist_create();
2964 n_trusted
= smartlist_len(trusted_dir_servers
);
2965 n_statuses
= smartlist_len(networkstatus_list
);
2967 if (n_statuses
< (n_trusted
/2)+1) {
2968 /* Not enough statuses to adjust status. */
2970 "Not enough statuses to update router status list. (%d/%d)",
2971 n_statuses
, n_trusted
);
2975 log_info(LD_DIR
, "Rebuilding router status list.");
2977 index
= tor_malloc(sizeof(int)*n_statuses
);
2978 size
= tor_malloc(sizeof(int)*n_statuses
);
2979 networkstatus
= tor_malloc(sizeof(networkstatus_t
*)*n_statuses
);
2980 for (i
= 0; i
< n_statuses
; ++i
) {
2982 networkstatus
[i
] = smartlist_get(networkstatus_list
, i
);
2983 size
[i
] = smartlist_len(networkstatus
[i
]->entries
);
2984 if (networkstatus
[i
]->binds_names
)
2986 if (networkstatus
[i
]->is_recent
)
2990 /** Iterate over all entries in all networkstatuses, and build
2991 * name_map as a map from lc nickname to identity digest. If there
2992 * is a conflict on that nickname, map the lc nickname to conflict.
2994 name_map
= strmap_new();
2995 memset(conflict
, 0xff, sizeof(conflict
));
2996 for (i
= 0; i
< n_statuses
; ++i
) {
2997 if (!networkstatus
[i
]->binds_names
)
2999 SMARTLIST_FOREACH(networkstatus
[i
]->entries
, routerstatus_t
*, rs
,
3001 const char *other_digest
;
3004 other_digest
= strmap_get_lc(name_map
, rs
->nickname
);
3005 warned
= smartlist_string_isin(warned_conflicts
, rs
->nickname
);
3006 if (!other_digest
) {
3007 strmap_set_lc(name_map
, rs
->nickname
, rs
->identity_digest
);
3009 smartlist_string_remove(warned_conflicts
, rs
->nickname
);
3010 } else if (memcmp(other_digest
, rs
->identity_digest
, DIGEST_LEN
) &&
3011 other_digest
!= conflict
) {
3013 int should_warn
= options
->DirPort
&& options
->AuthoritativeDir
;
3014 char fp1
[HEX_DIGEST_LEN
+1];
3015 char fp2
[HEX_DIGEST_LEN
+1];
3016 base16_encode(fp1
, sizeof(fp1
), other_digest
, DIGEST_LEN
);
3017 base16_encode(fp2
, sizeof(fp2
), rs
->identity_digest
, DIGEST_LEN
);
3018 log_fn(should_warn
? LOG_WARN
: LOG_INFO
, LD_DIR
,
3019 "Naming authorities disagree about which key goes with %s. "
3021 rs
->nickname
, fp1
, fp2
);
3022 strmap_set_lc(name_map
, rs
->nickname
, conflict
);
3023 smartlist_add(warned_conflicts
, tor_strdup(rs
->nickname
));
3027 smartlist_string_remove(warned_conflicts
, rs
->nickname
);
3032 result
= smartlist_create();
3033 digest_counts
= tor_malloc_zero(sizeof(desc_digest_count_t
)*n_statuses
);
3035 /* Iterate through all of the sorted routerstatus lists in lockstep.
3037 * - For 0 <= i < n_statuses: index[i] is an index into
3038 * networkstatus[i]->entries, which has size[i] elements.
3039 * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
3040 * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
3041 * networkstatus[i2]->entries[index[i2]]->identity_digest.
3043 * (That is, the indices are always advanced past lower digest before
3047 int n_running
=0, n_named
=0, n_valid
=0, n_listing
=0;
3048 int n_v2_dir
=0, n_fast
=0, n_stable
=0, n_exit
=0, n_guard
=0;
3049 int n_desc_digests
=0, highest_count
=0;
3050 const char *the_name
= NULL
;
3051 local_routerstatus_t
*rs_out
, *rs_old
;
3052 routerstatus_t
*rs
, *most_recent
;
3053 networkstatus_t
*ns
;
3054 const char *lowest
= NULL
;
3056 /* Find out which of the digests appears first. */
3057 for (i
= 0; i
< n_statuses
; ++i
) {
3058 if (index
[i
] < size
[i
]) {
3059 rs
= smartlist_get(networkstatus
[i
]->entries
, index
[i
]);
3060 if (!lowest
|| memcmp(rs
->identity_digest
, lowest
, DIGEST_LEN
)<0)
3061 lowest
= rs
->identity_digest
;
3065 /* We're out of routers. Great! */
3068 /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
3069 * match "lowest" are next in order. Iterate over them, incrementing those
3070 * index[i] as we go. */
3071 for (i
= 0; i
< n_statuses
; ++i
) {
3072 if (index
[i
] >= size
[i
])
3074 ns
= networkstatus
[i
];
3075 rs
= smartlist_get(ns
->entries
, index
[i
]);
3076 if (memcmp(rs
->identity_digest
, lowest
, DIGEST_LEN
))
3078 /* At this point, we know that we're looking at a routersatus with
3079 * identity "lowest".
3083 /* Should we name this router? Only if all the names from naming
3084 * authorities match. */
3085 if (rs
->is_named
&& ns
->binds_names
) {
3087 the_name
= rs
->nickname
;
3088 if (!strcasecmp(rs
->nickname
, the_name
)) {
3090 } else if (strcmp(the_name
,"**mismatch**")) {
3091 char hd
[HEX_DIGEST_LEN
+1];
3092 base16_encode(hd
, HEX_DIGEST_LEN
+1, rs
->identity_digest
, DIGEST_LEN
);
3093 if (! smartlist_string_isin(warned_conflicts
, hd
)) {
3095 "Naming authorities disagree about nicknames for $%s "
3096 "(\"%s\" vs \"%s\")",
3097 hd
, the_name
, rs
->nickname
);
3098 smartlist_add(warned_conflicts
, tor_strdup(hd
));
3100 the_name
= "**mismatch**";
3103 /* Keep a running count of how often which descriptor digests
3105 for (j
= 0; j
< n_desc_digests
; ++j
) {
3106 if (!memcmp(rs
->descriptor_digest
,
3107 digest_counts
[j
].rs
->descriptor_digest
, DIGEST_LEN
)) {
3108 if (++digest_counts
[j
].count
> highest_count
)
3109 highest_count
= digest_counts
[j
].count
;
3113 digest_counts
[n_desc_digests
].rs
= rs
;
3114 digest_counts
[n_desc_digests
].count
= 1;
3119 /* Now tally up the easily-tallied flags. */
3122 if (rs
->is_running
&& ns
->is_recent
)
3128 if (rs
->is_possible_guard
)
3135 /* Go over the descriptor digests and figure out which descriptor we
3138 for (i
= 0; i
< n_desc_digests
; ++i
) {
3139 /* If any digest appears twice or more, ignore those that don't.*/
3140 if (highest_count
>= 2 && digest_counts
[i
].count
< 2)
3143 digest_counts
[i
].rs
->published_on
> most_recent
->published_on
)
3144 most_recent
= digest_counts
[i
].rs
;
3146 rs_out
= tor_malloc_zero(sizeof(local_routerstatus_t
));
3147 memcpy(&rs_out
->status
, most_recent
, sizeof(routerstatus_t
));
3148 /* Copy status info about this router, if we had any before. */
3149 if ((rs_old
= router_get_combined_status_by_digest(lowest
))) {
3150 if (!memcmp(rs_out
->status
.descriptor_digest
,
3151 most_recent
->descriptor_digest
, DIGEST_LEN
)) {
3152 rs_out
->n_download_failures
= rs_old
->n_download_failures
;
3153 rs_out
->next_attempt_at
= rs_old
->next_attempt_at
;
3155 rs_out
->name_lookup_warned
= rs_old
->name_lookup_warned
;
3157 smartlist_add(result
, rs_out
);
3158 log_debug(LD_DIR
, "Router '%s' is listed by %d/%d directories, "
3159 "named by %d/%d, validated by %d/%d, and %d/%d recent "
3160 "directories think it's running.",
3161 rs_out
->status
.nickname
,
3162 n_listing
, n_statuses
, n_named
, n_naming
, n_valid
, n_statuses
,
3163 n_running
, n_recent
);
3164 rs_out
->status
.is_named
= 0;
3165 if (the_name
&& strcmp(the_name
, "**mismatch**") && n_named
> 0) {
3166 const char *d
= strmap_get_lc(name_map
, the_name
);
3167 if (d
&& d
!= conflict
)
3168 rs_out
->status
.is_named
= 1;
3169 if (smartlist_string_isin(warned_conflicts
, rs_out
->status
.nickname
))
3170 smartlist_string_remove(warned_conflicts
, rs_out
->status
.nickname
);
3172 if (rs_out
->status
.is_named
)
3173 strlcpy(rs_out
->status
.nickname
, the_name
,
3174 sizeof(rs_out
->status
.nickname
));
3175 rs_out
->status
.is_valid
= n_valid
> n_statuses
/2;
3176 rs_out
->status
.is_running
= n_running
> n_recent
/2;
3177 rs_out
->status
.is_exit
= n_exit
> n_statuses
/2;
3178 rs_out
->status
.is_fast
= n_fast
> n_statuses
/2;
3179 rs_out
->status
.is_possible_guard
= n_guard
> n_statuses
/2;
3180 rs_out
->status
.is_stable
= n_stable
> n_statuses
/2;
3181 rs_out
->status
.is_v2_dir
= n_v2_dir
> n_statuses
/2;
3183 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
3184 local_routerstatus_free(rs
));
3185 smartlist_free(routerstatus_list
);
3186 routerstatus_list
= result
;
3188 tor_free(networkstatus
);
3191 tor_free(digest_counts
);
3192 strmap_free(name_map
, NULL
);
3194 networkstatus_list_has_changed
= 0;
3195 routerstatus_list_has_changed
= 1;
3198 /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
3199 * is_named, is_verified, and is_running fields according to our current
3200 * networkstatus_t documents. */
3202 routers_update_status_from_networkstatus(smartlist_t
*routers
,
3205 trusted_dir_server_t
*ds
;
3206 local_routerstatus_t
*rs
;
3207 routerstatus_t
*rs2
;
3208 or_options_t
*options
= get_options();
3209 int authdir
= options
->AuthoritativeDir
;
3210 int namingdir
= options
->AuthoritativeDir
&&
3211 options
->NamingAuthoritativeDir
;
3213 if (!routerstatus_list
)
3216 SMARTLIST_FOREACH(routers
, routerinfo_t
*, router
,
3218 const char *digest
= router
->cache_info
.identity_digest
;
3219 rs
= router_get_combined_status_by_digest(digest
);
3220 ds
= router_get_trusteddirserver_by_digest(digest
);
3226 router
->is_named
= rs
->status
.is_named
;
3229 /* If we're an authdir, don't believe others. */
3230 router
->is_verified
= rs
->status
.is_valid
;
3231 router
->is_running
= rs
->status
.is_running
;
3232 router
->is_fast
= rs
->status
.is_fast
;
3233 router
->is_stable
= rs
->status
.is_stable
;
3234 router
->is_possible_guard
= rs
->status
.is_possible_guard
;
3236 if (router
->is_running
&& ds
) {
3237 ds
->n_networkstatus_failures
= 0;
3239 if (reset_failures
) {
3240 rs
->n_download_failures
= 0;
3241 rs
->next_attempt_at
= 0;
3244 /* Note that we have this descriptor. This may be redundant? */
3245 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
3247 rs2
= networkstatus_find_entry(ns
, router
->cache_info
.identity_digest
);
3248 if (rs2
&& !memcmp(rs2
->descriptor_digest
,
3249 router
->cache_info
.signed_descriptor_digest
,
3251 rs2
->need_to_mirror
= 0;
3256 /** For every router descriptor we are currently downloading by descriptor
3257 * digest, set result[d] to 1. */
3259 list_pending_descriptor_downloads(digestmap_t
*result
)
3261 const char *prefix
= "d/";
3262 size_t p_len
= strlen(prefix
);
3264 connection_t
**carray
;
3265 smartlist_t
*tmp
= smartlist_create();
3268 get_connection_array(&carray
, &n_conns
);
3270 for (i
= 0; i
< n_conns
; ++i
) {
3271 connection_t
*conn
= carray
[i
];
3272 if (conn
->type
== CONN_TYPE_DIR
&&
3273 conn
->purpose
== DIR_PURPOSE_FETCH_SERVERDESC
&&
3274 !conn
->marked_for_close
) {
3275 if (!strcmpstart(conn
->requested_resource
, prefix
))
3276 dir_split_resource_into_fingerprints(conn
->requested_resource
+p_len
,
3280 SMARTLIST_FOREACH(tmp
, char *, d
,
3282 digestmap_set(result
, d
, (void*)1);
3285 smartlist_free(tmp
);
3288 /** Launch downloads for all the descriptors whose digests are listed
3289 * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
3290 * If <b>source</b> is given, download from <b>source</b>; otherwise,
3291 * download from an appropriate random directory server.
3294 initiate_descriptor_downloads(routerstatus_t
*source
,
3295 smartlist_t
*digests
,
3299 char *resource
, *cp
;
3305 if (hi
> smartlist_len(digests
))
3306 hi
= smartlist_len(digests
);
3308 r_len
= 8 + (HEX_DIGEST_LEN
+1)*n
;
3309 cp
= resource
= tor_malloc(r_len
);
3310 memcpy(cp
, "d/", 2);
3312 for (i
= lo
; i
< hi
; ++i
) {
3313 base16_encode(cp
, r_len
-(cp
-resource
),
3314 smartlist_get(digests
,i
), DIGEST_LEN
);
3315 cp
+= HEX_DIGEST_LEN
;
3318 memcpy(cp
-1, ".z", 3);
3321 /* We know which authority we want. */
3322 directory_initiate_command_routerstatus(source
,
3323 DIR_PURPOSE_FETCH_SERVERDESC
,
3324 0, /* not private */
3327 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC
,
3334 /** Return new list of ID fingerprints for routers that we (as a client) would
3337 static smartlist_t
*
3338 router_list_client_downloadable(void)
3340 #define MAX_OLD_SERVER_DOWNLOAD_RATE 2*60*60
3341 #define ESTIMATED_PROPAGATION_TIME 10*60
3342 int n_downloadable
= 0;
3343 smartlist_t
*downloadable
= smartlist_create();
3344 digestmap_t
*downloading
;
3345 time_t now
= time(NULL
);
3346 /* these are just used for logging */
3347 int n_not_ready
= 0, n_in_progress
= 0, n_uptodate
= 0,
3348 n_obsolete
= 0, n_too_young
= 0, n_wouldnt_use
= 0;
3350 if (!routerstatus_list
)
3351 return downloadable
;
3353 downloading
= digestmap_new();
3354 list_pending_descriptor_downloads(downloading
);
3356 routerstatus_list_update_from_networkstatus(now
);
3357 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
3360 if (rs
->status
.published_on
+ ROUTER_MAX_AGE
< now
) {
3361 /* This one is too old to consider. */
3363 } else if (digestmap_get(downloading
, rs
->status
.descriptor_digest
)) {
3364 /* We're downloading this one now. */
3366 } else if (!rs
->status
.is_running
) {
3367 /* If we had this router descriptor, we wouldn't even bother using it. */
3369 } else if (router_get_by_descriptor_digest(rs
->status
.descriptor_digest
)) {
3370 /* We have the 'best' descriptor for this router. */
3372 } else if ((ri
= router_get_by_digest(rs
->status
.identity_digest
)) &&
3373 ri
->cache_info
.published_on
> rs
->status
.published_on
) {
3374 /* Oddly, we have a descriptor more recent than the 'best' one, but it
3375 was once best. So that's okay. */
3377 } else if (rs
->status
.published_on
+ ESTIMATED_PROPAGATION_TIME
> now
) {
3378 /* Most caches probably don't have this descriptor yet. */
3380 } else if (rs
->next_attempt_at
> now
) {
3381 /* We failed too recently to try again. */
3384 /* Okay, time to try it. */
3385 smartlist_add(downloadable
, rs
->status
.descriptor_digest
);
3392 "%d router descriptors are downloadable. %d are too old to consider. "
3393 "%d are in progress. %d are up-to-date. %d are too young to consider. "
3394 "%d are non-useful. %d failed too recently to retry.",
3395 n_downloadable
, n_obsolete
, n_in_progress
, n_uptodate
, n_too_young
,
3396 n_wouldnt_use
, n_not_ready
);
3399 digestmap_free(downloading
, NULL
);
3400 return downloadable
;
3403 /** Initiate new router downloads as needed.
3405 * We only allow one router descriptor download at a time.
3406 * If we have less than two network-status documents, we ask
3407 * a directory for "all descriptors."
3408 * Otherwise, we ask for all descriptors that we think are different
3409 * from what we have.
3412 update_router_descriptor_client_downloads(time_t now
)
3414 /* Max amount of hashes to download per request.
3415 * Since squid does not like URLs >= 4096 bytes we limit it to 96.
3416 * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
3417 * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
3418 * So use 96 because it's a nice number.
3420 #define MAX_DL_PER_REQUEST 96
3421 #define MIN_DL_PER_REQUEST 4
3422 #define MIN_REQUESTS 3
3423 #define MAX_DL_TO_DELAY 16
3424 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST 10*60
3425 #define MAX_SERVER_INTERVAL_WITHOUT_REQUEST 1*60
3426 smartlist_t
*downloadable
= NULL
;
3427 int should_delay
, n_downloadable
;
3428 or_options_t
*options
= get_options();
3430 if (server_mode(options
) && options
->DirPort
) {
3432 "Called router_descriptor_client_downloads() on a mirror?");
3435 if (networkstatus_list
&& smartlist_len(networkstatus_list
) < 2) {
3436 /* XXXX Is this redundant? -NM */
3438 "Not enough networkstatus documents to launch requests.");
3441 downloadable
= router_list_client_downloadable();
3442 n_downloadable
= smartlist_len(downloadable
);
3443 if (n_downloadable
>= MAX_DL_TO_DELAY
) {
3445 "There are enough downloadable routerdescs to launch requests.");
3447 } else if (n_downloadable
== 0) {
3448 // log_debug(LD_DIR, "No routerdescs need to be downloaded.");
3451 should_delay
= (last_routerdesc_download_attempted
+
3452 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST
) > now
;
3453 if (!should_delay
) {
3454 if (last_routerdesc_download_attempted
) {
3456 "There are not many downloadable routerdescs, but we've "
3457 "been waiting long enough (%d seconds). Downloading.",
3458 (int)(now
-last_routerdesc_download_attempted
));
3461 "There are not many downloadable routerdescs, but we've "
3462 "never downloaded descriptors before. Downloading.");
3467 if (! should_delay
) {
3468 int i
, n_per_request
;
3469 n_per_request
= (n_downloadable
+MIN_REQUESTS
-1) / MIN_REQUESTS
;
3470 if (n_per_request
> MAX_DL_PER_REQUEST
)
3471 n_per_request
= MAX_DL_PER_REQUEST
;
3472 if (n_per_request
< MIN_DL_PER_REQUEST
)
3473 n_per_request
= MIN_DL_PER_REQUEST
;
3476 "Launching %d request%s for %d router%s, %d at a time",
3477 (n_downloadable
+n_per_request
-1)/n_per_request
,
3478 n_downloadable
>n_per_request
?"s":"",
3479 n_downloadable
, n_downloadable
>1?"s":"", n_per_request
);
3480 for (i
=0; i
< n_downloadable
; i
+= n_per_request
) {
3481 initiate_descriptor_downloads(NULL
, downloadable
, i
, i
+n_per_request
);
3483 last_routerdesc_download_attempted
= now
;
3485 smartlist_free(downloadable
);
3490 update_router_descriptor_cache_downloads(time_t now
)
3492 smartlist_t
**downloadable
; /* For each authority, what can we dl from it? */
3493 smartlist_t
**download_from
; /* ... and, what will we dl from it? */
3494 digestmap_t
*map
; /* Which descs are in progress, or assigned? */
3497 or_options_t
*options
= get_options();
3499 if (!(server_mode(options
) && options
->DirPort
)) {
3500 log_warn(LD_BUG
, "Called update_router_descriptor_cache_downloads() "
3501 "on a non-mirror?");
3504 if (!networkstatus_list
|| !smartlist_len(networkstatus_list
))
3507 map
= digestmap_new();
3508 n
= smartlist_len(networkstatus_list
);
3510 downloadable
= tor_malloc_zero(sizeof(smartlist_t
*) * n
);
3511 download_from
= tor_malloc_zero(sizeof(smartlist_t
*) * n
);
3513 /* Set map[d]=1 for the digest of every descriptor that we are currently
3515 list_pending_descriptor_downloads(map
);
3517 /* For the digest of every descriptor that we don't have, and that we aren't
3518 * downloading, add d to downloadable[i] if the i'th networkstatus knows
3519 * about that descriptor, and we haven't already failed to get that
3520 * descriptor from the corresponding authority.
3523 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
3525 smartlist_t
*dl
= smartlist_create();
3526 downloadable
[ns_sl_idx
] = dl
;
3527 download_from
[ns_sl_idx
] = smartlist_create();
3528 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
* , rs
,
3530 if (!rs
->need_to_mirror
)
3532 if (router_get_by_descriptor_digest(rs
->descriptor_digest
)) {
3534 "We have a router descriptor, but need_to_mirror=1.");
3535 rs
->need_to_mirror
= 0;
3538 if (options
->AuthoritativeDir
&& dirserv_would_reject_router(rs
)) {
3539 rs
->need_to_mirror
= 0;
3542 if (digestmap_get(map
, rs
->descriptor_digest
)) {
3543 /* We're downloading it already. */
3546 /* We could download it from this guy. */
3547 smartlist_add(dl
, rs
->descriptor_digest
);
3553 /* At random, assign descriptors to authorities such that:
3554 * - if d is a member of some downloadable[x], d is a member of some
3555 * download_from[y]. (Everything we want to download, we try to download
3557 * - If d is a mamber of download_from[y], d is a member of downloadable[y].
3558 * (We only try to download descriptors from authorities who claim to have
3560 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
3561 * (We don't try to download anything from two authorities concurrently.)
3563 while (n_download
) {
3564 int which_ns
= crypto_rand_int(n
);
3565 smartlist_t
*dl
= downloadable
[which_ns
];
3569 if (!smartlist_len(dl
))
3571 idx
= crypto_rand_int(smartlist_len(dl
));
3572 d
= smartlist_get(dl
, idx
);
3573 if (! digestmap_get(map
, d
)) {
3574 smartlist_add(download_from
[which_ns
], d
);
3575 digestmap_set(map
, d
, (void*) 1);
3577 smartlist_del(dl
, idx
);
3581 /* Now, we can actually launch our requests. */
3582 for (i
=0; i
<n
; ++i
) {
3583 networkstatus_t
*ns
= smartlist_get(networkstatus_list
, i
);
3584 trusted_dir_server_t
*ds
=
3585 router_get_trusteddirserver_by_digest(ns
->identity_digest
);
3586 smartlist_t
*dl
= download_from
[i
];
3588 log_warn(LD_BUG
, "Networkstatus with no corresponding authority!");
3591 if (! smartlist_len(dl
))
3593 log_info(LD_DIR
, "Requesting %d descriptors from authority \"%s\"",
3594 smartlist_len(dl
), ds
->nickname
);
3595 for (j
=0; j
< smartlist_len(dl
); j
+= MAX_DL_PER_REQUEST
) {
3596 initiate_descriptor_downloads(&(ds
->fake_status
), dl
, j
,
3597 j
+MAX_DL_PER_REQUEST
);
3601 for (i
=0; i
<n
; ++i
) {
3602 smartlist_free(download_from
[i
]);
3603 smartlist_free(downloadable
[i
]);
3605 tor_free(download_from
);
3606 tor_free(downloadable
);
3607 digestmap_free(map
,NULL
);
3612 update_router_descriptor_downloads(time_t now
)
3614 or_options_t
*options
= get_options();
3615 if (server_mode(options
) && options
->DirPort
) {
3616 update_router_descriptor_cache_downloads(now
);
3618 update_router_descriptor_client_downloads(now
);
3622 /** Return true iff we have enough networkstatus and router information to
3623 * start building circuits. Right now, this means "at least 2 networkstatus
3624 * documents, and at least 1/4 of expected routers." */
3625 //XXX should consider whether we have enough exiting nodes here.
3627 router_have_minimum_dir_info(void)
3629 int tot
= 0, num_running
= 0;
3631 static int have_enough
= 0;
3632 if (!networkstatus_list
|| !routerlist
) {
3636 n_ns
= smartlist_len(networkstatus_list
);
3641 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
3642 tot
+= smartlist_len(ns
->entries
));
3644 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
3646 if (rs
->status
.is_running
)
3649 res
= smartlist_len(routerlist
->routers
) >= (avg
/4) && num_running
> 2;
3651 if (res
&& !have_enough
) {
3652 log(LOG_NOTICE
, LD_DIR
,
3653 "We now have enough directory information to build circuits.");
3655 if (!res
&& have_enough
) {
3656 log(LOG_NOTICE
, LD_DIR
,"Our directory information is no longer up-to-date "
3657 "enough to build circuits.%s",
3658 num_running
> 2 ? "" : " (Not enough servers seem reachable -- "
3659 "is your network connection down?)");
3665 /** Reset the descriptor download failure count on all routers, so that we
3666 * can retry any long-failed routers immediately.
3669 router_reset_descriptor_download_failures(void)
3671 if (!routerstatus_list
)
3673 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
3675 rs
->n_download_failures
= 0;
3676 rs
->next_attempt_at
= 0;
3678 tor_assert(networkstatus_list
);
3679 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
3680 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
*, rs
,
3682 if (!router_get_by_descriptor_digest(rs
->descriptor_digest
))
3683 rs
->need_to_mirror
= 1;
3685 last_routerdesc_download_attempted
= 0;
3688 /** Return true iff the only differences between r1 and r2 are such that
3689 * would not cause a recent (post 0.1.1.6) dirserver to republish.
3692 router_differences_are_cosmetic(routerinfo_t
*r1
, routerinfo_t
*r2
)
3694 time_t r1pub
, r2pub
;
3695 tor_assert(r1
&& r2
);
3697 /* r1 should be the one that was published first. */
3698 if (r1
->cache_info
.published_on
> r2
->cache_info
.published_on
) {
3699 routerinfo_t
*ri_tmp
= r2
;
3704 /* If any key fields differ, they're different. */
3705 if (strcasecmp(r1
->address
, r2
->address
) ||
3706 strcasecmp(r1
->nickname
, r2
->nickname
) ||
3707 r1
->or_port
!= r2
->or_port
||
3708 r1
->dir_port
!= r2
->dir_port
||
3709 crypto_pk_cmp_keys(r1
->onion_pkey
, r2
->onion_pkey
) ||
3710 crypto_pk_cmp_keys(r1
->identity_pkey
, r2
->identity_pkey
) ||
3711 strcasecmp(r1
->platform
, r2
->platform
) ||
3712 (r1
->contact_info
&& !r2
->contact_info
) || /* contact_info is optional */
3713 (!r1
->contact_info
&& r2
->contact_info
) ||
3714 (r1
->contact_info
&& r2
->contact_info
&&
3715 strcasecmp(r1
->contact_info
, r2
->contact_info
)) ||
3716 r1
->is_hibernating
!= r2
->is_hibernating
||
3717 config_cmp_addr_policies(r1
->exit_policy
, r2
->exit_policy
))
3719 if ((r1
->declared_family
== NULL
) != (r2
->declared_family
== NULL
))
3721 if (r1
->declared_family
&& r2
->declared_family
) {
3723 if (smartlist_len(r1
->declared_family
)!=smartlist_len(r2
->declared_family
))
3725 n
= smartlist_len(r1
->declared_family
);
3726 for (i
=0; i
< n
; ++i
) {
3727 if (strcasecmp(smartlist_get(r1
->declared_family
, i
),
3728 smartlist_get(r2
->declared_family
, i
)))
3733 /* Did bandwidth change a lot? */
3734 if ((r1
->bandwidthcapacity
< r2
->bandwidthcapacity
/2) ||
3735 (r2
->bandwidthcapacity
< r1
->bandwidthcapacity
/2))
3738 /* Did more than 12 hours pass? */
3739 if (r1
->cache_info
.published_on
+ 12*60*60 < r2
->cache_info
.published_on
)
3742 /* Did uptime fail to increase by approximately the amount we would think,
3743 * give or take 30 minutes? */
3744 r1pub
= r1
->cache_info
.published_on
;
3745 r2pub
= r2
->cache_info
.published_on
;
3746 if (abs(r2
->uptime
- (r1
->uptime
+ (r2pub
- r1pub
))))
3749 /* Otherwise, the difference is cosmetic. */
3754 routerlist_assert_ok(routerlist_t
*rl
)
3756 digestmap_iter_t
*iter
;
3758 signed_descriptor_t
*sd2
;
3761 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
3763 r2
= digestmap_get(rl
->identity_map
, r
->cache_info
.identity_digest
);
3764 tor_assert(r
== r2
);
3765 sd2
= digestmap_get(rl
->desc_digest_map
,
3766 r
->cache_info
.signed_descriptor_digest
);
3767 tor_assert(&(r
->cache_info
) == sd2
);
3769 SMARTLIST_FOREACH(rl
->old_routers
, signed_descriptor_t
*, sd
,
3771 r2
= digestmap_get(rl
->identity_map
, sd
->identity_digest
);
3772 tor_assert(sd
!= &(r2
->cache_info
));
3773 sd2
= digestmap_get(rl
->desc_digest_map
, sd
->signed_descriptor_digest
);
3774 tor_assert(sd
== sd2
);
3776 iter
= digestmap_iter_init(rl
->identity_map
);
3777 while (!digestmap_iter_done(iter
)) {
3781 digestmap_iter_get(iter
, &d
, &_r
);
3783 tor_assert(!memcmp(r
->cache_info
.identity_digest
, d
, DIGEST_LEN
));
3784 iter
= digestmap_iter_next(rl
->identity_map
, iter
);
3786 iter
= digestmap_iter_init(rl
->desc_digest_map
);
3787 while (!digestmap_iter_done(iter
)) {
3790 signed_descriptor_t
*sd
;
3791 digestmap_iter_get(iter
, &d
, &_sd
);
3793 tor_assert(!memcmp(sd
->signed_descriptor_digest
, d
, DIGEST_LEN
));
3794 iter
= digestmap_iter_next(rl
->desc_digest_map
, iter
);