1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, 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
,
24 int for_v2_directory
);
25 static routerstatus_t
*router_pick_trusteddirserver_impl(
26 authority_type_t type
, int requireother
,
27 int fascistfirewall
, int prefer_tunnel
);
28 static void mark_all_trusteddirservers_up(void);
29 static int router_nickname_matches(routerinfo_t
*router
, const char *nickname
);
30 static void routerstatus_list_update_from_networkstatus(time_t now
);
31 static void local_routerstatus_free(local_routerstatus_t
*rs
);
32 static void trusted_dir_server_free(trusted_dir_server_t
*ds
);
33 static void update_networkstatus_cache_downloads(time_t now
);
34 static void update_networkstatus_client_downloads(time_t now
);
35 static int signed_desc_digest_is_recognized(signed_descriptor_t
*desc
);
36 static void routerlist_assert_ok(routerlist_t
*rl
);
37 static int have_tried_downloading_all_statuses(int n_failures
);
38 static routerstatus_t
*networkstatus_find_entry(networkstatus_t
*ns
,
40 static local_routerstatus_t
*router_get_combined_status_by_nickname(
43 static void update_router_have_minimum_dir_info(void);
44 static void router_dir_info_changed(void);
46 /****************************************************************************/
48 /** Global list of a trusted_dir_server_t object for each trusted directory
50 static smartlist_t
*trusted_dir_servers
= NULL
;
52 /** Global list of all of the routers that we know about. */
53 static routerlist_t
*routerlist
= NULL
;
55 /** Global list of all of the current network_status documents that we know
56 * about. This list is kept sorted by published_on. */
57 static smartlist_t
*networkstatus_list
= NULL
;
59 /** Global list of local_routerstatus_t for each router, known or unknown.
60 * Kept sorted by digest. */
61 static smartlist_t
*routerstatus_list
= NULL
;
63 /** Map from lowercase nickname to digest of named server, if any. */
64 static strmap_t
*named_server_map
= NULL
;
66 /** True iff any member of networkstatus_list has changed since the last time
67 * we called routerstatus_list_update_from_networkstatus(). */
68 static int networkstatus_list_has_changed
= 0;
70 /** True iff any element of routerstatus_list has changed since the last
71 * time we called routers_update_all_from_networkstatus().*/
72 static int routerstatus_list_has_changed
= 0;
74 /** List of strings for nicknames we've already warned about and that are
75 * still unknown / unavailable. */
76 static smartlist_t
*warned_nicknames
= NULL
;
78 /** List of strings for nicknames or fingerprints we've already warned about
79 * and that are still conflicted. */
80 static smartlist_t
*warned_conflicts
= NULL
;
82 /** The last time we tried to download any routerdesc, or 0 for "never". We
83 * use this to rate-limit download attempts when the number of routerdescs to
85 static time_t last_routerdesc_download_attempted
= 0;
87 /** The last time we tried to download a networkstatus, or 0 for "never". We
88 * use this to rate-limit download attempts for directory caches (including
89 * mirrors). Clients don't use this now. */
90 static time_t last_networkstatus_download_attempted
= 0;
92 /** True iff we have logged a warning about this OR not being valid or
94 static int have_warned_about_invalid_status
= 0;
95 /** True iff we have logged a warning about this OR's version being older than
96 * listed by the authorities */
97 static int have_warned_about_old_version
= 0;
98 /** True iff we have logged a warning about this OR's version being newer than
99 * listed by the authorities */
100 static int have_warned_about_new_version
= 0;
102 /** Return the number of v2 directory authorities */
104 get_n_v2_authorities(void)
107 if (!trusted_dir_servers
)
109 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
110 if (ds
->is_v2_authority
)
115 /** Repopulate our list of network_status_t objects from the list cached on
116 * disk. Return 0 on success, -1 on failure. */
118 router_reload_networkstatus(void)
121 smartlist_t
*entries
;
124 tor_assert(get_options()->DataDirectory
);
125 if (!networkstatus_list
)
126 networkstatus_list
= smartlist_create();
128 tor_snprintf(filename
,sizeof(filename
),"%s/cached-status",
129 get_options()->DataDirectory
);
130 entries
= tor_listdir(filename
);
131 SMARTLIST_FOREACH(entries
, const char *, fn
, {
132 char buf
[DIGEST_LEN
];
133 if (strlen(fn
) != HEX_DIGEST_LEN
||
134 base16_decode(buf
, sizeof(buf
), fn
, strlen(fn
))) {
136 "Skipping cached-status file with unexpected name \"%s\"",fn
);
139 tor_snprintf(filename
,sizeof(filename
),"%s/cached-status/%s",
140 get_options()->DataDirectory
, fn
);
141 s
= read_file_to_str(filename
, 0, &st
);
143 if (router_set_networkstatus(s
, st
.st_mtime
, NS_FROM_CACHE
, NULL
)<0) {
144 log_warn(LD_FS
, "Couldn't load networkstatus from \"%s\"",filename
);
149 SMARTLIST_FOREACH(entries
, char *, fn
, tor_free(fn
));
150 smartlist_free(entries
);
151 networkstatus_list_clean(time(NULL
));
152 routers_update_all_from_networkstatus();
156 /* Router descriptor storage.
158 * Routerdescs are stored in a big file, named "cached-routers". As new
159 * routerdescs arrive, we append them to a journal file named
160 * "cached-routers.new".
162 * From time to time, we replace "cached-routers" with a new file containing
163 * only the live, non-superseded descriptors, and clear cached-routers.new.
165 * On startup, we read both files.
168 /** The size of the router log, in bytes. */
169 static size_t router_journal_len
= 0;
170 /** The size of the router store, in bytes. */
171 static size_t router_store_len
= 0;
172 /** Total bytes dropped since last rebuild. */
173 static size_t router_bytes_dropped
= 0;
175 /** Helper: return 1 iff the router log is so big we want to rebuild the
178 router_should_rebuild_store(void)
180 if (router_store_len
> (1<<16))
181 return (router_journal_len
> router_store_len
/ 2 ||
182 router_bytes_dropped
> router_store_len
/ 2);
184 return router_journal_len
> (1<<15);
187 /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
188 * journal; change its saved_location to SAVED_IN_JOURNAL and set its
189 * offset appropriately. */
191 router_append_to_journal(signed_descriptor_t
*desc
)
193 or_options_t
*options
= get_options();
194 size_t fname_len
= strlen(options
->DataDirectory
)+32;
195 char *fname
= tor_malloc(fname_len
);
196 const char *body
= signed_descriptor_get_body(desc
);
197 size_t len
= desc
->signed_descriptor_len
;
199 tor_snprintf(fname
, fname_len
, "%s/cached-routers.new",
200 options
->DataDirectory
);
202 tor_assert(len
== strlen(body
));
204 if (append_bytes_to_file(fname
, body
, len
, 1)) {
205 log_warn(LD_FS
, "Unable to store router descriptor");
209 desc
->saved_location
= SAVED_IN_JOURNAL
;
210 desc
->saved_offset
= router_journal_len
;
213 router_journal_len
+= len
;
217 /** Sorting helper: return <0, 0, or >0 depending on whether the
218 * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
219 * the signed_descriptor_t* in *<b>b</b>. */
221 _compare_old_routers_by_age(const void **_a
, const void **_b
)
223 const signed_descriptor_t
*r1
= *_a
, *r2
= *_b
;
224 return r1
->published_on
- r2
->published_on
;
227 /** Sorting helper: return <0, 0, or >0 depending on whether the
228 * routerinfo_t* in *<b>a</b> is older, the same age as, or newer than
229 * the routerinfo_t* in *<b>b</b>. */
231 _compare_routers_by_age(const void **_a
, const void **_b
)
233 const routerinfo_t
*r1
= *_a
, *r2
= *_b
;
234 return r1
->cache_info
.published_on
- r2
->cache_info
.published_on
;
237 /** If the journal is too long, or if <b>force</b> is true, then atomically
238 * replace the router store with the routers currently in our routerlist, and
239 * clear the journal. Return 0 on success, -1 on failure.
242 router_rebuild_store(int force
)
245 or_options_t
*options
;
247 smartlist_t
*chunk_list
= NULL
;
248 char *fname
= NULL
, *fname_tmp
= NULL
;
251 smartlist_t
*old_routers
, *routers
;
253 if (!force
&& !router_should_rebuild_store())
258 /* Don't save deadweight. */
259 routerlist_remove_old_routers();
261 log_info(LD_DIR
, "Rebuilding router descriptor cache");
263 options
= get_options();
264 fname_len
= strlen(options
->DataDirectory
)+32;
265 fname
= tor_malloc(fname_len
);
266 fname_tmp
= tor_malloc(fname_len
);
267 tor_snprintf(fname
, fname_len
, "%s/cached-routers", options
->DataDirectory
);
268 tor_snprintf(fname_tmp
, fname_len
, "%s/cached-routers.tmp",
269 options
->DataDirectory
);
271 chunk_list
= smartlist_create();
273 old_routers
= smartlist_create();
274 smartlist_add_all(old_routers
, routerlist
->old_routers
);
275 smartlist_sort(old_routers
, _compare_old_routers_by_age
);
276 routers
= smartlist_create();
277 smartlist_add_all(routers
, routerlist
->routers
);
278 smartlist_sort(routers
, _compare_routers_by_age
);
279 for (i
= 0; i
< 2; ++i
) {
280 /* We sort the routers by age to enhance locality on disk. */
281 smartlist_t
*lst
= (i
== 0) ? old_routers
: routers
;
282 /* Now, add the appropriate members to chunk_list */
283 SMARTLIST_FOREACH(lst
, void *, ptr
,
285 signed_descriptor_t
*sd
= (i
==0) ?
286 ((signed_descriptor_t
*)ptr
): &((routerinfo_t
*)ptr
)->cache_info
;
288 const char *body
= signed_descriptor_get_body(sd
);
290 log_warn(LD_BUG
, "Bug! No descriptor available for router.");
293 c
= tor_malloc(sizeof(sized_chunk_t
));
295 c
->len
= sd
->signed_descriptor_len
;
296 smartlist_add(chunk_list
, c
);
299 if (write_chunks_to_file(fname_tmp
, chunk_list
, 1)<0) {
300 log_warn(LD_FS
, "Error writing router store to disk.");
303 /* Our mmap is now invalid. */
304 if (routerlist
->mmap_descriptors
) {
305 tor_munmap_file(routerlist
->mmap_descriptors
);
307 if (replace_file(fname_tmp
, fname
)<0) {
308 log_warn(LD_FS
, "Error replacing old router store.");
312 routerlist
->mmap_descriptors
= tor_mmap_file(fname
);
313 if (! routerlist
->mmap_descriptors
)
314 log_warn(LD_FS
, "Unable to mmap new descriptor file at '%s'.",fname
);
317 for (i
= 0; i
< 2; ++i
) {
318 smartlist_t
*lst
= (i
== 0) ? old_routers
: routers
;
319 SMARTLIST_FOREACH(lst
, void *, ptr
,
321 signed_descriptor_t
*sd
= (i
==0) ?
322 ((signed_descriptor_t
*)ptr
): &((routerinfo_t
*)ptr
)->cache_info
;
324 sd
->saved_location
= SAVED_IN_CACHE
;
325 if (routerlist
->mmap_descriptors
) {
326 tor_free(sd
->signed_descriptor_body
); // sets it to null
327 sd
->saved_offset
= offset
;
329 offset
+= sd
->signed_descriptor_len
;
330 signed_descriptor_get_body(sd
);
334 tor_snprintf(fname
, fname_len
, "%s/cached-routers.new",
335 options
->DataDirectory
);
337 write_str_to_file(fname
, "", 1);
340 router_store_len
= len
;
341 router_journal_len
= 0;
342 router_bytes_dropped
= 0;
344 smartlist_free(old_routers
);
345 smartlist_free(routers
);
347 SMARTLIST_FOREACH(chunk_list
, sized_chunk_t
*, c
, tor_free(c
));
348 smartlist_free(chunk_list
);
352 /** Load all cached router descriptors from the store. Return 0 on success and
356 router_reload_router_list(void)
358 or_options_t
*options
= get_options();
359 size_t fname_len
= strlen(options
->DataDirectory
)+32;
360 char *fname
= tor_malloc(fname_len
), *contents
= NULL
;
363 router_get_routerlist(); /* mallocs and inits it in place */
365 router_journal_len
= router_store_len
= 0;
367 tor_snprintf(fname
, fname_len
, "%s/cached-routers", options
->DataDirectory
);
369 if (routerlist
->mmap_descriptors
) /* get rid of it first */
370 tor_munmap_file(routerlist
->mmap_descriptors
);
372 routerlist
->mmap_descriptors
= tor_mmap_file(fname
);
373 if (routerlist
->mmap_descriptors
) {
374 router_store_len
= routerlist
->mmap_descriptors
->size
;
375 router_load_routers_from_string(routerlist
->mmap_descriptors
->data
,
376 SAVED_IN_CACHE
, NULL
);
379 tor_snprintf(fname
, fname_len
, "%s/cached-routers.new",
380 options
->DataDirectory
);
381 if (file_status(fname
) == FN_FILE
)
382 contents
= read_file_to_str(fname
, RFTS_BIN
|RFTS_IGNORE_MISSING
, NULL
);
384 router_load_routers_from_string(contents
,
385 SAVED_IN_JOURNAL
, NULL
);
391 if (router_journal_len
) {
392 /* Always clear the journal on startup.*/
393 router_rebuild_store(1);
395 /* Don't cache expired routers. (This is in an else because
396 * router_rebuild_store() also calls remove_old_routers().) */
397 routerlist_remove_old_routers();
403 /** Return a smartlist containing a list of trusted_dir_server_t * for all
404 * known trusted dirservers. Callers must not modify the list or its
408 router_get_trusted_dir_servers(void)
410 if (!trusted_dir_servers
)
411 trusted_dir_servers
= smartlist_create();
413 return trusted_dir_servers
;
416 /** Try to find a running dirserver. If there are no running dirservers
417 * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
418 * set all the authoritative ones as running again, and pick one;
419 * if there are then no dirservers at all in our routerlist,
420 * reload the routerlist and try one last time. If for_runningrouters is
421 * true, then only pick a dirserver that can answer runningrouters queries
422 * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
423 * Don't pick an authority if any non-authority is viable.
424 * Other args are as in router_pick_directory_server_impl().
427 router_pick_directory_server(int requireother
,
429 int for_v2_directory
,
430 int retry_if_no_servers
)
432 routerstatus_t
*choice
;
433 int prefer_tunnel
= get_options()->PreferTunneledDirConns
;
438 choice
= router_pick_directory_server_impl(requireother
, fascistfirewall
,
439 prefer_tunnel
, for_v2_directory
);
440 if (choice
|| !retry_if_no_servers
)
444 "No reachable router entries for dirservers. "
445 "Trying them all again.");
446 /* mark all authdirservers as up again */
447 mark_all_trusteddirservers_up();
449 choice
= router_pick_directory_server_impl(requireother
, fascistfirewall
,
450 prefer_tunnel
, for_v2_directory
);
454 log_info(LD_DIR
,"Still no %s router entries. Reloading and trying again.",
455 fascistfirewall
? "reachable" : "known");
456 if (router_reload_router_list()) {
459 /* give it one last try */
460 choice
= router_pick_directory_server_impl(requireother
, fascistfirewall
,
461 prefer_tunnel
, for_v2_directory
);
465 /** Return the trusted_dir_server_t for the directory authority whose identity
466 * key hashes to <b>digest</b>, or NULL if no such authority is known.
468 trusted_dir_server_t
*
469 router_get_trusteddirserver_by_digest(const char *digest
)
471 if (!trusted_dir_servers
)
474 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
476 if (!memcmp(ds
->digest
, digest
, DIGEST_LEN
))
483 /** Try to find a running trusted dirserver. If there are no running
484 * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
485 * set them all as running again, and try again.
486 * If <b>need_v1_authority</b> is set, return only trusted servers
487 * that are authorities for the V1 directory protocol.
488 * Other args are as in router_pick_trusteddirserver_impl().
491 router_pick_trusteddirserver(authority_type_t type
,
494 int retry_if_no_servers
)
496 routerstatus_t
*choice
;
497 int prefer_tunnel
= get_options()->PreferTunneledDirConns
;
499 choice
= router_pick_trusteddirserver_impl(type
, requireother
,
500 fascistfirewall
, prefer_tunnel
);
501 if (choice
|| !retry_if_no_servers
)
505 "No trusted dirservers are reachable. Trying them all again.");
506 mark_all_trusteddirservers_up();
507 return router_pick_trusteddirserver_impl(type
, requireother
,
508 fascistfirewall
, prefer_tunnel
);
511 /** How long do we avoid using a directory server after it's given us a 503? */
512 #define DIR_503_TIMEOUT (60*60)
514 /** Pick a random running valid directory server/mirror from our
515 * routerlist. Don't pick an authority if any non-authorities are viable.
516 * If <b>fascistfirewall</b>, make sure the router we pick is allowed
517 * by our firewall options.
518 * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
519 * choose a directory server new enough to support the v2 directory
521 * If <b>prefer_tunnel</b>, choose a directory server that is reachable
522 * and supports BEGIN_DIR cells, if possible.
523 * Try to avoid using servers that are overloaded (have returned 503
526 static routerstatus_t
*
527 router_pick_directory_server_impl(int requireother
, int fascistfirewall
,
528 int prefer_tunnel
, int for_v2_directory
)
530 routerstatus_t
*result
;
531 smartlist_t
*direct
, *tunnel
;
532 smartlist_t
*trusted_direct
, *trusted_tunnel
;
533 smartlist_t
*overloaded_direct
, *overloaded_tunnel
;
534 time_t now
= time(NULL
);
536 if (!routerstatus_list
)
539 direct
= smartlist_create();
540 tunnel
= smartlist_create();
541 trusted_direct
= smartlist_create();
542 trusted_tunnel
= smartlist_create();
543 overloaded_direct
= smartlist_create();
544 overloaded_tunnel
= smartlist_create();
546 /* Find all the running dirservers we know about. */
547 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, _local_status
,
549 routerstatus_t
*status
= &(_local_status
->status
);
551 int is_overloaded
= _local_status
->last_dir_503_at
+ DIR_503_TIMEOUT
> now
;
552 if (!status
->is_running
|| !status
->dir_port
|| !status
->is_valid
)
554 if (status
->is_bad_directory
)
556 if (requireother
&& router_digest_is_me(status
->identity_digest
))
558 is_trusted
= router_digest_is_trusted_dir(status
->identity_digest
);
559 if (for_v2_directory
&& !(status
->is_v2_dir
|| is_trusted
))
561 if (fascistfirewall
&&
563 status
->version_supports_begindir
&&
564 fascist_firewall_allows_address_or(status
->addr
, status
->or_port
))
565 smartlist_add(is_trusted
? trusted_tunnel
:
566 is_overloaded
? overloaded_tunnel
: tunnel
, status
);
567 else if (!fascistfirewall
|| (fascistfirewall
&&
568 fascist_firewall_allows_address_dir(status
->addr
,
570 smartlist_add(is_trusted
? trusted_direct
:
571 is_overloaded
? overloaded_direct
: direct
, status
);
574 if (smartlist_len(tunnel
)) {
575 result
= routerstatus_sl_choose_by_bandwidth(tunnel
);
576 } else if (smartlist_len(overloaded_tunnel
)) {
577 result
= routerstatus_sl_choose_by_bandwidth(overloaded_tunnel
);
578 } else if (smartlist_len(trusted_tunnel
)) {
579 /* FFFF We don't distinguish between trusteds and overloaded trusteds
580 * yet. Maybe one day we should. */
581 /* FFFF We also don't load balance over authorities yet. I think this
582 * is a feature, but it could easily be a bug. -RD */
583 result
= smartlist_choose(trusted_tunnel
);
584 } else if (smartlist_len(direct
)) {
585 result
= routerstatus_sl_choose_by_bandwidth(direct
);
586 } else if (smartlist_len(overloaded_direct
)) {
587 result
= routerstatus_sl_choose_by_bandwidth(overloaded_direct
);
589 result
= smartlist_choose(trusted_direct
);
591 smartlist_free(direct
);
592 smartlist_free(tunnel
);
593 smartlist_free(trusted_direct
);
594 smartlist_free(trusted_tunnel
);
595 smartlist_free(overloaded_direct
);
596 smartlist_free(overloaded_tunnel
);
600 /** Choose randomly from among the trusted dirservers that are up. If
601 * <b>fascistfirewall</b>, make sure the port we pick is allowed by our
602 * firewall options. If <b>requireother</b>, it cannot be us. If
603 * <b>need_v1_authority</b>, choose a trusted authority for the v1 directory
606 static routerstatus_t
*
607 router_pick_trusteddirserver_impl(authority_type_t type
,
608 int requireother
, int fascistfirewall
,
611 smartlist_t
*direct
, *tunnel
;
612 smartlist_t
*overloaded_direct
, *overloaded_tunnel
;
613 routerinfo_t
*me
= router_get_my_routerinfo();
614 routerstatus_t
*result
;
615 time_t now
= time(NULL
);
617 direct
= smartlist_create();
618 tunnel
= smartlist_create();
619 overloaded_direct
= smartlist_create();
620 overloaded_tunnel
= smartlist_create();
622 if (!trusted_dir_servers
)
625 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, d
,
628 d
->fake_status
.last_dir_503_at
+ DIR_503_TIMEOUT
> now
;
629 if (!d
->is_running
) continue;
630 if (type
== V1_AUTHORITY
&& !d
->is_v1_authority
)
632 if (type
== V2_AUTHORITY
&& !d
->is_v2_authority
)
634 if (type
== HIDSERV_AUTHORITY
&& !d
->is_hidserv_authority
)
636 if (requireother
&& me
&& router_digest_is_me(d
->digest
))
639 if (fascistfirewall
&&
642 fascist_firewall_allows_address_or(d
->addr
, d
->or_port
))
643 smartlist_add(is_overloaded
? overloaded_tunnel
: tunnel
,
644 &d
->fake_status
.status
);
645 else if (!fascistfirewall
|| (fascistfirewall
&&
646 fascist_firewall_allows_address_dir(d
->addr
,
648 smartlist_add(is_overloaded
? overloaded_direct
: direct
,
649 &d
->fake_status
.status
);
652 if (smartlist_len(tunnel
)) {
653 result
= smartlist_choose(tunnel
);
654 } else if (smartlist_len(overloaded_tunnel
)) {
655 result
= smartlist_choose(overloaded_tunnel
);
656 } else if (smartlist_len(direct
)) {
657 result
= smartlist_choose(direct
);
659 result
= smartlist_choose(overloaded_direct
);
662 smartlist_free(direct
);
663 smartlist_free(tunnel
);
664 smartlist_free(overloaded_direct
);
665 smartlist_free(overloaded_tunnel
);
669 /** Go through and mark the authoritative dirservers as up. */
671 mark_all_trusteddirservers_up(void)
674 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
675 if (router_digest_is_trusted_dir(router
->cache_info
.identity_digest
) &&
676 router
->dir_port
> 0) {
677 router
->is_running
= 1;
680 if (trusted_dir_servers
) {
681 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, dir
,
683 local_routerstatus_t
*rs
;
685 dir
->n_networkstatus_failures
= 0;
686 dir
->fake_status
.last_dir_503_at
= 0;
687 rs
= router_get_combined_status_by_digest(dir
->digest
);
688 if (rs
&& !rs
->status
.is_running
) {
689 rs
->status
.is_running
= 1;
690 rs
->last_dir_503_at
= 0;
691 control_event_networkstatus_changed_single(rs
);
695 last_networkstatus_download_attempted
= 0;
696 router_dir_info_changed();
699 /** Reset all internal variables used to count failed downloads of network
702 router_reset_status_download_failures(void)
704 mark_all_trusteddirservers_up();
707 /** Look through the routerlist and identify routers that
708 * advertise the same /16 network address as <b>router</b>.
709 * Add each of them to <b>sl</b>.
712 routerlist_add_network_family(smartlist_t
*sl
, routerinfo_t
*router
)
714 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, r
,
717 (router
->addr
& 0xffff0000) == (r
->addr
& 0xffff0000))
718 smartlist_add(sl
, r
);
722 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
723 * This is used to make sure we don't pick siblings in a single path.
726 routerlist_add_family(smartlist_t
*sl
, routerinfo_t
*router
)
730 or_options_t
*options
= get_options();
732 /* First, add any routers with similar network addresses. */
733 if (options
->EnforceDistinctSubnets
)
734 routerlist_add_network_family(sl
, router
);
736 if (!router
->declared_family
)
739 /* Add every r such that router declares familyness with r, and r
740 * declares familyhood with router. */
741 SMARTLIST_FOREACH(router
->declared_family
, const char *, n
,
743 if (!(r
= router_get_by_nickname(n
, 0)))
745 if (!r
->declared_family
)
747 SMARTLIST_FOREACH(r
->declared_family
, const char *, n2
,
749 if (router_nickname_matches(router
, n2
))
750 smartlist_add(sl
, r
);
754 /* If the user declared any families locally, honor those too. */
755 for (cl
= get_options()->NodeFamilies
; cl
; cl
= cl
->next
) {
756 if (router_nickname_is_in_list(router
, cl
->value
)) {
757 add_nickname_list_to_smartlist(sl
, cl
->value
, 0);
762 /** Given a (possibly NULL) comma-and-whitespace separated list of nicknames,
763 * see which nicknames in <b>list</b> name routers in our routerlist, and add
764 * the routerinfos for those routers to <b>sl</b>. If <b>must_be_running</b>,
765 * only include routers that we think are running.
766 * Warn if any non-Named routers are specified by nickname.
769 add_nickname_list_to_smartlist(smartlist_t
*sl
, const char *list
,
772 routerinfo_t
*router
;
773 smartlist_t
*nickname_list
;
774 int have_dir_info
= router_have_minimum_dir_info();
777 return; /* nothing to do */
780 nickname_list
= smartlist_create();
781 if (!warned_nicknames
)
782 warned_nicknames
= smartlist_create();
784 smartlist_split_string(nickname_list
, list
, ",",
785 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
787 SMARTLIST_FOREACH(nickname_list
, const char *, nick
, {
789 if (!is_legal_nickname_or_hexdigest(nick
)) {
790 log_warn(LD_CONFIG
, "Nickname '%s' is misformed; skipping", nick
);
793 router
= router_get_by_nickname(nick
, 1);
794 warned
= smartlist_string_isin(warned_nicknames
, nick
);
796 if (!must_be_running
|| router
->is_running
) {
797 smartlist_add(sl
,router
);
799 } else if (!router_get_combined_status_by_nickname(nick
,1)) {
801 log_fn(have_dir_info
? LOG_WARN
: LOG_INFO
, LD_CONFIG
,
802 "Nickname list includes '%s' which isn't a known router.",nick
);
803 smartlist_add(warned_nicknames
, tor_strdup(nick
));
807 SMARTLIST_FOREACH(nickname_list
, char *, nick
, tor_free(nick
));
808 smartlist_free(nickname_list
);
811 /** Return 1 iff any member of the (possibly NULL) comma-separated list
812 * <b>list</b> is an acceptable nickname or hexdigest for <b>router</b>. Else
816 router_nickname_is_in_list(routerinfo_t
*router
, const char *list
)
818 smartlist_t
*nickname_list
;
822 return 0; /* definitely not */
825 nickname_list
= smartlist_create();
826 smartlist_split_string(nickname_list
, list
, ",",
827 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
828 SMARTLIST_FOREACH(nickname_list
, const char *, cp
,
829 if (router_nickname_matches(router
, cp
)) {v
=1;break;});
830 SMARTLIST_FOREACH(nickname_list
, char *, cp
, tor_free(cp
));
831 smartlist_free(nickname_list
);
835 /** Add every suitable router from our routerlist to <b>sl</b>, so that
836 * we can pick a node for a circuit.
839 router_add_running_routers_to_smartlist(smartlist_t
*sl
, int allow_invalid
,
840 int need_uptime
, int need_capacity
,
846 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
848 if (router
->is_running
&&
849 router
->purpose
== ROUTER_PURPOSE_GENERAL
&&
850 (router
->is_valid
|| allow_invalid
) &&
851 !router_is_unreliable(router
, need_uptime
,
852 need_capacity
, need_guard
)) {
853 /* If it's running, and it's suitable according to the
854 * other flags we had in mind */
855 smartlist_add(sl
, router
);
860 /** Look through the routerlist until we find a router that has my key.
863 routerlist_find_my_routerinfo(void)
868 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
870 if (router_is_me(router
))
876 /** Find a router that's up, that has this IP address, and
877 * that allows exit to this address:port, or return NULL if there
881 router_find_exact_exit_enclave(const char *address
, uint16_t port
)
886 if (!tor_inet_aton(address
, &in
))
887 return NULL
; /* it's not an IP already */
888 addr
= ntohl(in
.s_addr
);
890 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
892 if (router
->is_running
&&
893 router
->addr
== addr
&&
894 compare_addr_to_addr_policy(addr
, port
, router
->exit_policy
) ==
895 ADDR_POLICY_ACCEPTED
)
901 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
902 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
903 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
905 * If <b>need_guard</b>, we require that the router is a possible entry guard.
908 router_is_unreliable(routerinfo_t
*router
, int need_uptime
,
909 int need_capacity
, int need_guard
)
911 if (need_uptime
&& !router
->is_stable
)
913 if (need_capacity
&& !router
->is_fast
)
915 if (need_guard
&& !router
->is_possible_guard
)
920 /** Return the smaller of the router's configured BandwidthRate
921 * and its advertised capacity. */
923 router_get_advertised_bandwidth(routerinfo_t
*router
)
925 if (router
->bandwidthcapacity
< router
->bandwidthrate
)
926 return router
->bandwidthcapacity
;
927 return router
->bandwidthrate
;
930 /** Do not weight any declared bandwidth more than this much when picking
931 * routers by bandwidth. */
932 #define MAX_BELIEVABLE_BANDWIDTH 1500000 /* 1.5 MB/sec */
935 * choose a random element of smartlist <b>sl</b>, weighted by
936 * the advertised bandwidth of each element.
938 * If <b>statuses</b> is zero, then <b>sl</b> is a list of
939 * routerinfo_t's. Otherwise it's a list of routerstatus_t's.
941 * If <b>for_exit</b>, we're picking an exit node: consider all nodes'
942 * bandwidth equally regardless of their Exit status. If not <b>for_exit</b>,
943 * we're picking a non-exit node: weight exit-node's bandwidth downwards
944 * depending on the smallness of the fraction of Exit-to-total bandwidth.
947 smartlist_choose_by_bandwidth(smartlist_t
*sl
, int for_exit
, int statuses
)
950 routerinfo_t
*router
;
951 routerstatus_t
*status
;
954 uint64_t total_nonexit_bw
= 0, total_exit_bw
= 0, total_bw
= 0;
955 uint64_t rand_bw
, tmp
;
959 /* First count the total bandwidth weight, and make a list
960 * of each value. <0 means "unknown; no routerinfo." We use the
961 * bits of negative values to remember whether the router was fast (-x)&1
962 * and whether it was an exit (-x)&2. Yes, it's a hack. */
963 bandwidths
= tor_malloc(sizeof(int32_t)*smartlist_len(sl
));
965 /* Iterate over all the routerinfo_t or routerstatus_t, and */
966 for (i
= 0; i
< smartlist_len(sl
); ++i
) {
967 /* first, learn what bandwidth we think i has */
970 uint32_t this_bw
= 0;
972 /* need to extract router info */
973 status
= smartlist_get(sl
, i
);
974 router
= router_get_by_digest(status
->identity_digest
);
975 is_exit
= status
->is_exit
;
977 this_bw
= router_get_advertised_bandwidth(router
);
980 flags
= status
->is_fast
? 1 : 0;
981 flags
|= is_exit
? 2 : 0;
984 router
= smartlist_get(sl
, i
);
985 is_exit
= router
->is_exit
;
986 this_bw
= router_get_advertised_bandwidth(router
);
988 /* if they claim something huge, don't believe it */
989 if (this_bw
> MAX_BELIEVABLE_BANDWIDTH
)
990 this_bw
= MAX_BELIEVABLE_BANDWIDTH
;
992 bandwidths
[i
] = (int32_t) this_bw
; // safe since MAX_BELIEVABLE<INT32_MAX
994 total_exit_bw
+= this_bw
;
996 total_nonexit_bw
+= this_bw
;
999 bandwidths
[i
] = -flags
;
1003 /* Now, fill in the unknown values. */
1005 int32_t avg_fast
, avg_slow
;
1006 if (total_exit_bw
+total_nonexit_bw
) {
1007 /* if there's some bandwidth, there's at least one known router,
1008 * so no worries about div by 0 here */
1009 int n_known
= smartlist_len(sl
)-n_unknown
;
1010 avg_fast
= avg_slow
= (int32_t)
1011 ((total_exit_bw
+total_nonexit_bw
)/((uint64_t) n_known
));
1016 for (i
=0; i
<smartlist_len(sl
); ++i
) {
1017 int32_t bw
= bandwidths
[i
];
1020 is_exit
= ((-bw
)&2);
1021 bandwidths
[i
] = ((-bw
)&1) ? avg_fast
: avg_slow
;
1023 total_exit_bw
+= bandwidths
[i
];
1025 total_nonexit_bw
+= bandwidths
[i
];
1029 /* If there's no bandwidth at all, pick at random. */
1030 if (!(total_exit_bw
+total_nonexit_bw
)) {
1031 tor_free(bandwidths
);
1032 return smartlist_choose(sl
);
1035 /* Figure out how to weight exits. */
1037 /* If we're choosing an exit node, exit bandwidth counts fully. */
1039 total_bw
= total_exit_bw
+ total_nonexit_bw
;
1040 } else if (total_exit_bw
< total_nonexit_bw
/ 2) {
1041 /* If we're choosing a relay and exits are greatly outnumbered, ignore
1044 total_bw
= total_nonexit_bw
;
1046 /* If we're choosing a relay and exits aren't outnumbered use the formula
1047 * from path-spec. */
1048 uint64_t leftover
= (total_exit_bw
- total_nonexit_bw
/ 2);
1049 exit_weight
= U64_TO_DBL(leftover
) /
1050 U64_TO_DBL(leftover
+ total_nonexit_bw
);
1051 total_bw
= total_nonexit_bw
+
1052 DBL_TO_U64(exit_weight
* U64_TO_DBL(total_exit_bw
));
1055 log_debug(LD_CIRC, "Total bw = "U64_FORMAT", total exit bw = "U64_FORMAT
1056 ", total nonexit bw = "U64_FORMAT", exit weight = %lf "
1058 U64_PRINTF_ARG(total_bw), U64_PRINTF_ARG(total_exit_bw),
1059 U64_PRINTF_ARG(total_nonexit_bw), exit_weight, for_exit);
1062 /* Almost done: choose a random value from the bandwidth weights. */
1063 rand_bw
= crypto_rand_uint64(total_bw
);
1065 /* Last, count through sl until we get to the element we picked */
1067 for (i
=0; i
< smartlist_len(sl
); i
++) {
1069 status
= smartlist_get(sl
, i
);
1070 is_exit
= status
->is_exit
;
1072 router
= smartlist_get(sl
, i
);
1073 is_exit
= router
->is_exit
;
1076 tmp
+= ((uint64_t)(bandwidths
[i
] * exit_weight
));
1078 tmp
+= bandwidths
[i
];
1082 tor_free(bandwidths
);
1083 return smartlist_get(sl
, i
);
1086 /** Choose a random element of router list <b>sl</b>, weighted by
1087 * the advertised bandwidth of each router.
1090 routerlist_sl_choose_by_bandwidth(smartlist_t
*sl
, int for_exit
)
1092 return smartlist_choose_by_bandwidth(sl
, for_exit
, 0);
1095 /** Choose a random element of status list <b>sl</b>, weighted by
1096 * the advertised bandwidth of each status.
1099 routerstatus_sl_choose_by_bandwidth(smartlist_t
*sl
)
1101 return smartlist_choose_by_bandwidth(sl
, 1, 1);
1104 /** Return a random running router from the routerlist. If any node
1105 * named in <b>preferred</b> is available, pick one of those. Never
1106 * pick a node named in <b>excluded</b>, or whose routerinfo is in
1107 * <b>excludedsmartlist</b>, even if they are the only nodes
1108 * available. If <b>strict</b> is true, never pick any node besides
1109 * those in <b>preferred</b>.
1110 * If <b>need_uptime</b> is non-zero and any router has more than
1111 * a minimum uptime, return one of those.
1112 * If <b>need_capacity</b> is non-zero, weight your choice by the
1113 * advertised capacity of each router.
1114 * If ! <b>allow_invalid</b>, consider only Valid routers.
1115 * If <b>need_guard</b>, consider only Guard routers.
1116 * If <b>weight_for_exit</b>, we weight bandwidths as if picking an exit node,
1117 * otherwise we weight bandwidths for picking a relay node (that is, possibly
1118 * discounting exit nodes).
1121 router_choose_random_node(const char *preferred
,
1122 const char *excluded
,
1123 smartlist_t
*excludedsmartlist
,
1124 int need_uptime
, int need_capacity
,
1126 int allow_invalid
, int strict
,
1127 int weight_for_exit
)
1129 smartlist_t
*sl
, *excludednodes
;
1130 routerinfo_t
*choice
= NULL
;
1132 excludednodes
= smartlist_create();
1133 add_nickname_list_to_smartlist(excludednodes
,excluded
,0);
1135 /* Try the preferred nodes first. Ignore need_uptime and need_capacity
1136 * and need_guard, since the user explicitly asked for these nodes. */
1138 sl
= smartlist_create();
1139 add_nickname_list_to_smartlist(sl
,preferred
,1);
1140 smartlist_subtract(sl
,excludednodes
);
1141 if (excludedsmartlist
)
1142 smartlist_subtract(sl
,excludedsmartlist
);
1143 choice
= smartlist_choose(sl
);
1146 if (!choice
&& !strict
) {
1147 /* Then give up on our preferred choices: any node
1148 * will do that has the required attributes. */
1149 sl
= smartlist_create();
1150 router_add_running_routers_to_smartlist(sl
, allow_invalid
,
1151 need_uptime
, need_capacity
,
1153 smartlist_subtract(sl
,excludednodes
);
1154 if (excludedsmartlist
)
1155 smartlist_subtract(sl
,excludedsmartlist
);
1158 choice
= routerlist_sl_choose_by_bandwidth(sl
, weight_for_exit
);
1160 choice
= smartlist_choose(sl
);
1163 if (!choice
&& (need_uptime
|| need_capacity
|| need_guard
)) {
1164 /* try once more -- recurse but with fewer restrictions. */
1166 "We couldn't find any live%s%s%s routers; falling back "
1167 "to list of all routers.",
1168 need_capacity
?", fast":"",
1169 need_uptime
?", stable":"",
1170 need_guard
?", guard":"");
1171 choice
= router_choose_random_node(
1172 NULL
, excluded
, excludedsmartlist
,
1173 0, 0, 0, allow_invalid
, 0, weight_for_exit
);
1176 smartlist_free(excludednodes
);
1179 log_warn(LD_CIRC
, "All preferred nodes were down when trying to choose "
1180 "node, and the Strict[...]Nodes option is set. Failing.");
1183 "No available nodes when trying to choose node. Failing.");
1189 /** Return true iff the digest of <b>router</b>'s identity key,
1190 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
1191 * optionally prefixed with a single dollar sign). Return false if
1192 * <b>hexdigest</b> is malformed, or it doesn't match. */
1194 router_hex_digest_matches(routerinfo_t
*router
, const char *hexdigest
)
1196 char digest
[DIGEST_LEN
];
1198 tor_assert(hexdigest
);
1199 if (hexdigest
[0] == '$')
1202 len
= strlen(hexdigest
);
1203 if (len
< HEX_DIGEST_LEN
)
1205 else if (len
> HEX_DIGEST_LEN
&&
1206 (hexdigest
[HEX_DIGEST_LEN
] == '=' ||
1207 hexdigest
[HEX_DIGEST_LEN
] == '~')) {
1208 if (strcasecmp(hexdigest
+HEX_DIGEST_LEN
+1, router
->nickname
))
1210 if (hexdigest
[HEX_DIGEST_LEN
] == '=' && !router
->is_named
)
1214 if (base16_decode(digest
, DIGEST_LEN
, hexdigest
, HEX_DIGEST_LEN
)<0)
1216 return (!memcmp(digest
, router
->cache_info
.identity_digest
, DIGEST_LEN
));
1219 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
1220 * (case-insensitive), or if <b>router's</b> identity key digest
1221 * matches a hexadecimal value stored in <b>nickname</b>. Return
1222 * false otherwise. */
1224 router_nickname_matches(routerinfo_t
*router
, const char *nickname
)
1226 if (nickname
[0]!='$' && !strcasecmp(router
->nickname
, nickname
))
1228 return router_hex_digest_matches(router
, nickname
);
1231 /** Return the router in our routerlist whose (case-insensitive)
1232 * nickname or (case-sensitive) hexadecimal key digest is
1233 * <b>nickname</b>. Return NULL if no such router is known.
1236 router_get_by_nickname(const char *nickname
, int warn_if_unnamed
)
1239 char digest
[DIGEST_LEN
];
1240 routerinfo_t
*best_match
=NULL
;
1242 char *named_digest
= NULL
;
1244 tor_assert(nickname
);
1247 if (nickname
[0] == '$')
1248 return router_get_by_hexdigest(nickname
);
1249 if (!strcasecmp(nickname
, UNNAMED_ROUTER_NICKNAME
))
1251 if (server_mode(get_options()) &&
1252 !strcasecmp(nickname
, get_options()->Nickname
))
1253 return router_get_my_routerinfo();
1255 maybedigest
= (strlen(nickname
) >= HEX_DIGEST_LEN
) &&
1256 (base16_decode(digest
,DIGEST_LEN
,nickname
,HEX_DIGEST_LEN
) == 0);
1258 if (named_server_map
&&
1259 (named_digest
= strmap_get_lc(named_server_map
, nickname
))) {
1260 return digestmap_get(routerlist
->identity_map
, named_digest
);
1263 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1265 if (!strcasecmp(router
->nickname
, nickname
)) {
1267 if (n_matches
<= 1 || router
->is_running
)
1268 best_match
= router
;
1269 } else if (maybedigest
&&
1270 !memcmp(digest
, router
->cache_info
.identity_digest
, DIGEST_LEN
)
1272 if (router_hex_digest_matches(router
, nickname
))
1275 best_match
= router
; // XXXX NM not exactly right.
1280 if (warn_if_unnamed
&& n_matches
> 1) {
1281 smartlist_t
*fps
= smartlist_create();
1282 int any_unwarned
= 0;
1283 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1285 local_routerstatus_t
*rs
;
1288 char fp
[HEX_DIGEST_LEN
+1];
1289 if (strcasecmp(router
->nickname
, nickname
))
1291 rs
= router_get_combined_status_by_digest(
1292 router
->cache_info
.identity_digest
);
1293 if (rs
&& !rs
->name_lookup_warned
) {
1294 rs
->name_lookup_warned
= 1;
1297 base16_encode(fp
, sizeof(fp
),
1298 router
->cache_info
.identity_digest
, DIGEST_LEN
);
1299 dlen
= 32 + HEX_DIGEST_LEN
+ strlen(router
->address
);
1300 desc
= tor_malloc(dlen
);
1301 tor_snprintf(desc
, dlen
, "\"$%s\" for the one at %s:%d",
1302 fp
, router
->address
, router
->or_port
);
1303 smartlist_add(fps
, desc
);
1306 char *alternatives
= smartlist_join_strings(fps
, "; ",0,NULL
);
1308 "There are multiple matches for the nickname \"%s\","
1309 " but none is listed as named by the directory authorities. "
1310 "Choosing one arbitrarily. If you meant one in particular, "
1311 "you should say %s.", nickname
, alternatives
);
1312 tor_free(alternatives
);
1314 SMARTLIST_FOREACH(fps
, char *, cp
, tor_free(cp
));
1315 smartlist_free(fps
);
1316 } else if (warn_if_unnamed
) {
1317 local_routerstatus_t
*rs
= router_get_combined_status_by_digest(
1318 best_match
->cache_info
.identity_digest
);
1319 if (rs
&& !rs
->name_lookup_warned
) {
1320 char fp
[HEX_DIGEST_LEN
+1];
1321 base16_encode(fp
, sizeof(fp
),
1322 best_match
->cache_info
.identity_digest
, DIGEST_LEN
);
1323 log_warn(LD_CONFIG
, "You specified a server \"%s\" by name, but the "
1324 "directory authorities do not have a binding for this nickname. "
1325 "To make sure you get the same server in the future, refer to "
1326 "it by key, as \"$%s\".", nickname
, fp
);
1327 rs
->name_lookup_warned
= 1;
1336 /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
1337 * return 1. If we do, ask tor_version_as_new_as() for the answer.
1340 router_digest_version_as_new_as(const char *digest
, const char *cutoff
)
1342 routerinfo_t
*router
= router_get_by_digest(digest
);
1345 return tor_version_as_new_as(router
->platform
, cutoff
);
1348 /** Return true iff <b>digest</b> is the digest of the identity key of
1349 * a trusted directory. */
1351 router_digest_is_trusted_dir(const char *digest
)
1353 if (!trusted_dir_servers
)
1355 if (get_options()->AuthoritativeDir
&&
1356 router_digest_is_me(digest
))
1358 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
1359 if (!memcmp(digest
, ent
->digest
, DIGEST_LEN
)) return 1);
1363 /** Return the router in our routerlist whose hexadecimal key digest
1364 * is <b>hexdigest</b>. Return NULL if no such router is known. */
1366 router_get_by_hexdigest(const char *hexdigest
)
1368 char digest
[DIGEST_LEN
];
1372 tor_assert(hexdigest
);
1375 if (hexdigest
[0]=='$')
1377 len
= strlen(hexdigest
);
1378 if (len
< HEX_DIGEST_LEN
||
1379 base16_decode(digest
,DIGEST_LEN
,hexdigest
,HEX_DIGEST_LEN
) < 0)
1382 ri
= router_get_by_digest(digest
);
1384 if (len
> HEX_DIGEST_LEN
) {
1385 if (hexdigest
[HEX_DIGEST_LEN
] == '=') {
1386 if (strcasecmp(ri
->nickname
, hexdigest
+HEX_DIGEST_LEN
+1) ||
1389 } else if (hexdigest
[HEX_DIGEST_LEN
] == '~') {
1390 if (strcasecmp(ri
->nickname
, hexdigest
+HEX_DIGEST_LEN
+1))
1400 /** Return the router in our routerlist whose 20-byte key digest
1401 * is <b>digest</b>. Return NULL if no such router is known. */
1403 router_get_by_digest(const char *digest
)
1407 if (!routerlist
) return NULL
;
1409 // routerlist_assert_ok(routerlist);
1411 return digestmap_get(routerlist
->identity_map
, digest
);
1414 /** Return the router in our routerlist whose 20-byte descriptor
1415 * is <b>digest</b>. Return NULL if no such router is known. */
1416 signed_descriptor_t
*
1417 router_get_by_descriptor_digest(const char *digest
)
1421 if (!routerlist
) return NULL
;
1423 return digestmap_get(routerlist
->desc_digest_map
, digest
);
1426 /** Return a pointer to the signed textual representation of a descriptor.
1427 * The returned string is not guaranteed to be NUL-terminated: the string's
1428 * length will be in desc-\>signed_descriptor_len. */
1430 signed_descriptor_get_body(signed_descriptor_t
*desc
)
1433 size_t len
= desc
->signed_descriptor_len
;
1434 tor_assert(len
> 32);
1435 if (desc
->saved_location
== SAVED_IN_CACHE
&& routerlist
&&
1436 routerlist
->mmap_descriptors
) {
1437 tor_assert(desc
->saved_offset
+ len
<= routerlist
->mmap_descriptors
->size
);
1438 r
= routerlist
->mmap_descriptors
->data
+ desc
->saved_offset
;
1440 r
= desc
->signed_descriptor_body
;
1443 tor_assert(!memcmp("router ", r
, 7));
1445 tor_assert(!memcmp("\n-----END SIGNATURE-----\n",
1452 /** Return the current list of all known routers. */
1454 router_get_routerlist(void)
1457 routerlist
= tor_malloc_zero(sizeof(routerlist_t
));
1458 routerlist
->routers
= smartlist_create();
1459 routerlist
->old_routers
= smartlist_create();
1460 routerlist
->identity_map
= digestmap_new();
1461 routerlist
->desc_digest_map
= digestmap_new();
1466 /** Free all storage held by <b>router</b>. */
1468 routerinfo_free(routerinfo_t
*router
)
1473 tor_free(router
->cache_info
.signed_descriptor_body
);
1474 tor_free(router
->address
);
1475 tor_free(router
->nickname
);
1476 tor_free(router
->platform
);
1477 tor_free(router
->contact_info
);
1478 if (router
->onion_pkey
)
1479 crypto_free_pk_env(router
->onion_pkey
);
1480 if (router
->identity_pkey
)
1481 crypto_free_pk_env(router
->identity_pkey
);
1482 if (router
->declared_family
) {
1483 SMARTLIST_FOREACH(router
->declared_family
, char *, s
, tor_free(s
));
1484 smartlist_free(router
->declared_family
);
1486 addr_policy_free(router
->exit_policy
);
1490 /** Release storage held by <b>sd</b>. */
1492 signed_descriptor_free(signed_descriptor_t
*sd
)
1494 tor_free(sd
->signed_descriptor_body
);
1498 /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
1500 static signed_descriptor_t
*
1501 signed_descriptor_from_routerinfo(routerinfo_t
*ri
)
1503 signed_descriptor_t
*sd
= tor_malloc_zero(sizeof(signed_descriptor_t
));
1504 memcpy(sd
, &(ri
->cache_info
), sizeof(signed_descriptor_t
));
1505 ri
->cache_info
.signed_descriptor_body
= NULL
;
1506 routerinfo_free(ri
);
1510 /** Free all storage held by a routerlist <b>rl</b> */
1512 routerlist_free(routerlist_t
*rl
)
1515 digestmap_free(rl
->identity_map
, NULL
);
1516 digestmap_free(rl
->desc_digest_map
, NULL
);
1517 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
1518 routerinfo_free(r
));
1519 SMARTLIST_FOREACH(rl
->old_routers
, signed_descriptor_t
*, sd
,
1520 signed_descriptor_free(sd
));
1521 smartlist_free(rl
->routers
);
1522 smartlist_free(rl
->old_routers
);
1523 if (routerlist
->mmap_descriptors
)
1524 tor_munmap_file(routerlist
->mmap_descriptors
);
1527 router_dir_info_changed();
1531 dump_routerlist_mem_usage(int severity
)
1533 uint64_t livedescs
= 0;
1534 uint64_t olddescs
= 0;
1537 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, r
,
1538 livedescs
+= r
->cache_info
.signed_descriptor_len
);
1539 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
,
1540 olddescs
+= sd
->signed_descriptor_len
);
1542 log(severity
, LD_GENERAL
,
1543 "In %d live descriptors: "U64_FORMAT
" bytes. "
1544 "In %d old descriptors: "U64_FORMAT
" bytes.",
1545 smartlist_len(routerlist
->routers
), U64_PRINTF_ARG(livedescs
),
1546 smartlist_len(routerlist
->old_routers
), U64_PRINTF_ARG(olddescs
));
1549 /** Return the greatest number of routerdescs we'll hold for any given router.
1552 max_descriptors_per_router(void)
1554 int n_authorities
= get_n_v2_authorities();
1555 return (n_authorities
< 5) ? 5 : n_authorities
;
1558 /** Return non-zero if we have a lot of extra descriptors in our
1559 * routerlist, and should get rid of some of them. Else return 0.
1561 * We should be careful to not return true too eagerly, since we
1562 * could churn. By using "+1" below, we make sure this function
1563 * only returns true at most every smartlist_len(rl-\>routers)
1567 routerlist_is_overfull(routerlist_t
*rl
)
1569 return smartlist_len(rl
->old_routers
) >
1570 smartlist_len(rl
->routers
)*(max_descriptors_per_router()+1);
1574 _routerlist_find_elt(smartlist_t
*sl
, void *ri
, int idx
)
1576 if (idx
< 0 || smartlist_get(sl
, idx
) != ri
) {
1578 SMARTLIST_FOREACH(sl
, routerinfo_t
*, r
,
1587 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1590 routerlist_insert(routerlist_t
*rl
, routerinfo_t
*ri
)
1592 digestmap_set(rl
->identity_map
, ri
->cache_info
.identity_digest
, ri
);
1593 digestmap_set(rl
->desc_digest_map
, ri
->cache_info
.signed_descriptor_digest
,
1595 smartlist_add(rl
->routers
, ri
);
1596 ri
->routerlist_index
= smartlist_len(rl
->routers
) - 1;
1597 router_dir_info_changed();
1598 // routerlist_assert_ok(rl);
1601 /** If we're a directory cache and routerlist <b>rl</b> doesn't have
1602 * a copy of router <b>ri</b> yet, add it to the list of old (not
1603 * recommended but still served) descriptors. Else free it. */
1605 routerlist_insert_old(routerlist_t
*rl
, routerinfo_t
*ri
)
1607 if (get_options()->DirPort
&&
1608 !digestmap_get(rl
->desc_digest_map
,
1609 ri
->cache_info
.signed_descriptor_digest
)) {
1610 signed_descriptor_t
*sd
= signed_descriptor_from_routerinfo(ri
);
1611 digestmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
1612 smartlist_add(rl
->old_routers
, sd
);
1614 routerinfo_free(ri
);
1616 // routerlist_assert_ok(rl);
1619 /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
1620 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl->routers,
1621 * idx) == ri, we don't need to do a linear search over the list to decide
1622 * which to remove. We fill the gap in rl->routers with a later element in
1623 * the list, if any exists. <b>ri</b> is freed. */
1625 routerlist_remove(routerlist_t
*rl
, routerinfo_t
*ri
, int idx
, int make_old
)
1627 routerinfo_t
*ri_tmp
;
1628 idx
= _routerlist_find_elt(rl
->routers
, ri
, idx
);
1631 ri
->routerlist_index
= -1;
1632 smartlist_del(rl
->routers
, idx
);
1633 if (idx
< smartlist_len(rl
->routers
)) {
1634 routerinfo_t
*r
= smartlist_get(rl
->routers
, idx
);
1635 r
->routerlist_index
= idx
;
1638 ri_tmp
= digestmap_remove(rl
->identity_map
, ri
->cache_info
.identity_digest
);
1639 router_dir_info_changed();
1640 tor_assert(ri_tmp
== ri
);
1641 if (make_old
&& get_options()->DirPort
) {
1642 signed_descriptor_t
*sd
;
1643 sd
= signed_descriptor_from_routerinfo(ri
);
1644 smartlist_add(rl
->old_routers
, sd
);
1645 digestmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
1647 ri_tmp
= digestmap_remove(rl
->desc_digest_map
,
1648 ri
->cache_info
.signed_descriptor_digest
);
1649 tor_assert(ri_tmp
== ri
);
1650 router_bytes_dropped
+= ri
->cache_info
.signed_descriptor_len
;
1651 routerinfo_free(ri
);
1653 // routerlist_assert_ok(rl);
1657 routerlist_remove_old(routerlist_t
*rl
, signed_descriptor_t
*sd
, int idx
)
1659 signed_descriptor_t
*sd_tmp
;
1660 idx
= _routerlist_find_elt(rl
->old_routers
, sd
, idx
);
1663 smartlist_del(rl
->old_routers
, idx
);
1664 sd_tmp
= digestmap_remove(rl
->desc_digest_map
,
1665 sd
->signed_descriptor_digest
);
1666 tor_assert(sd_tmp
== sd
);
1667 router_bytes_dropped
+= sd
->signed_descriptor_len
;
1668 signed_descriptor_free(sd
);
1669 // routerlist_assert_ok(rl);
1672 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
1673 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
1674 * smartlist_get(rl->routers, idx) == ri, we don't need to do a linear
1675 * search over the list to decide which to remove. We put ri_new in the same
1676 * index as ri_old, if possible. ri is freed as appropriate. */
1678 routerlist_replace(routerlist_t
*rl
, routerinfo_t
*ri_old
,
1679 routerinfo_t
*ri_new
, int idx
, int make_old
)
1681 tor_assert(ri_old
!= ri_new
);
1682 idx
= _routerlist_find_elt(rl
->routers
, ri_old
, idx
);
1683 router_dir_info_changed();
1685 smartlist_set(rl
->routers
, idx
, ri_new
);
1686 ri_old
->routerlist_index
= -1;
1687 ri_new
->routerlist_index
= idx
;
1689 log_warn(LD_BUG
, "Appending entry from routerlist_replace.");
1690 routerlist_insert(rl
, ri_new
);
1693 if (memcmp(ri_old
->cache_info
.identity_digest
,
1694 ri_new
->cache_info
.identity_digest
, DIGEST_LEN
)) {
1695 /* digests don't match; digestmap_set won't replace */
1696 digestmap_remove(rl
->identity_map
, ri_old
->cache_info
.identity_digest
);
1698 digestmap_set(rl
->identity_map
, ri_new
->cache_info
.identity_digest
, ri_new
);
1699 digestmap_set(rl
->desc_digest_map
,
1700 ri_new
->cache_info
.signed_descriptor_digest
, &(ri_new
->cache_info
));
1702 if (make_old
&& get_options()->DirPort
) {
1703 signed_descriptor_t
*sd
= signed_descriptor_from_routerinfo(ri_old
);
1704 smartlist_add(rl
->old_routers
, sd
);
1705 digestmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
1707 if (memcmp(ri_old
->cache_info
.signed_descriptor_digest
,
1708 ri_new
->cache_info
.signed_descriptor_digest
,
1710 /* digests don't match; digestmap_set didn't replace */
1711 digestmap_remove(rl
->desc_digest_map
,
1712 ri_old
->cache_info
.signed_descriptor_digest
);
1714 routerinfo_free(ri_old
);
1716 // routerlist_assert_ok(rl);
1719 /** Free all memory held by the routerlist module. */
1721 routerlist_free_all(void)
1724 routerlist_free(routerlist
);
1726 if (warned_nicknames
) {
1727 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
1728 smartlist_free(warned_nicknames
);
1729 warned_nicknames
= NULL
;
1731 if (warned_conflicts
) {
1732 SMARTLIST_FOREACH(warned_conflicts
, char *, cp
, tor_free(cp
));
1733 smartlist_free(warned_conflicts
);
1734 warned_conflicts
= NULL
;
1736 if (trusted_dir_servers
) {
1737 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
1738 trusted_dir_server_free(ds
));
1739 smartlist_free(trusted_dir_servers
);
1740 trusted_dir_servers
= NULL
;
1742 if (networkstatus_list
) {
1743 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
1744 networkstatus_free(ns
));
1745 smartlist_free(networkstatus_list
);
1746 networkstatus_list
= NULL
;
1748 if (routerstatus_list
) {
1749 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
1750 local_routerstatus_free(rs
));
1751 smartlist_free(routerstatus_list
);
1752 routerstatus_list
= NULL
;
1754 if (named_server_map
) {
1755 strmap_free(named_server_map
, _tor_free
);
1759 /** Free all storage held by the routerstatus object <b>rs</b>. */
1761 routerstatus_free(routerstatus_t
*rs
)
1766 /** Free all storage held by the local_routerstatus object <b>rs</b>. */
1768 local_routerstatus_free(local_routerstatus_t
*rs
)
1773 /** Free all storage held by the networkstatus object <b>ns</b>. */
1775 networkstatus_free(networkstatus_t
*ns
)
1777 tor_free(ns
->source_address
);
1778 tor_free(ns
->contact
);
1779 if (ns
->signing_key
)
1780 crypto_free_pk_env(ns
->signing_key
);
1781 tor_free(ns
->client_versions
);
1782 tor_free(ns
->server_versions
);
1784 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
*, rs
,
1785 routerstatus_free(rs
));
1786 smartlist_free(ns
->entries
);
1791 /** Forget that we have issued any router-related warnings, so that we'll
1792 * warn again if we see the same errors. */
1794 routerlist_reset_warnings(void)
1796 if (!warned_nicknames
)
1797 warned_nicknames
= smartlist_create();
1798 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
1799 smartlist_clear(warned_nicknames
); /* now the list is empty. */
1801 if (!warned_conflicts
)
1802 warned_conflicts
= smartlist_create();
1803 SMARTLIST_FOREACH(warned_conflicts
, char *, cp
, tor_free(cp
));
1804 smartlist_clear(warned_conflicts
); /* now the list is empty. */
1806 if (!routerstatus_list
)
1807 routerstatus_list
= smartlist_create();
1808 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
1809 rs
->name_lookup_warned
= 0);
1811 have_warned_about_invalid_status
= 0;
1812 have_warned_about_old_version
= 0;
1813 have_warned_about_new_version
= 0;
1816 /** Mark the router with ID <b>digest</b> as running or non-running
1817 * in our routerlist. */
1819 router_set_status(const char *digest
, int up
)
1821 routerinfo_t
*router
;
1822 local_routerstatus_t
*status
;
1825 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, d
,
1826 if (!memcmp(d
->digest
, digest
, DIGEST_LEN
))
1827 d
->is_running
= up
);
1829 router
= router_get_by_digest(digest
);
1831 log_debug(LD_DIR
,"Marking router '%s' as %s.",
1832 router
->nickname
, up
? "up" : "down");
1833 if (!up
&& router_is_me(router
) && !we_are_hibernating())
1834 log_warn(LD_NET
, "We just marked ourself as down. Are your external "
1835 "addresses reachable?");
1836 router
->is_running
= up
;
1838 status
= router_get_combined_status_by_digest(digest
);
1839 if (status
&& status
->status
.is_running
!= up
) {
1840 status
->status
.is_running
= up
;
1841 control_event_networkstatus_changed_single(status
);
1843 router_dir_info_changed();
1846 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
1847 * older entries (if any) with the same key. Note: Callers should not hold
1848 * their pointers to <b>router</b> if this function fails; <b>router</b>
1849 * will either be inserted into the routerlist or freed.
1851 * Returns >= 0 if the router was added; less than 0 if it was not.
1853 * If we're returning non-zero, then assign to *<b>msg</b> a static string
1854 * describing the reason for not liking the routerinfo.
1856 * If the return value is less than -1, there was a problem with the
1857 * routerinfo. If the return value is equal to -1, then the routerinfo was
1858 * fine, but out-of-date. If the return value is equal to 1, the
1859 * routerinfo was accepted, but we should notify the generator of the
1860 * descriptor using the message *<b>msg</b>.
1862 * If <b>from_cache</b>, this descriptor came from our disk cache. If
1863 * <b>from_fetch</b>, we received it in response to a request we made.
1864 * (If both are false, that means it was uploaded to us as an auth dir
1865 * server or via the controller.)
1867 * This function should be called *after*
1868 * routers_update_status_from_networkstatus; subsequently, you should call
1869 * router_rebuild_store and control_event_descriptors_changed.
1872 router_add_to_routerlist(routerinfo_t
*router
, const char **msg
,
1873 int from_cache
, int from_fetch
)
1875 const char *id_digest
;
1876 int authdir
= get_options()->AuthoritativeDir
;
1877 int authdir_believes_valid
= 0;
1878 routerinfo_t
*old_router
;
1883 router_get_routerlist();
1884 if (!networkstatus_list
)
1885 networkstatus_list
= smartlist_create();
1887 id_digest
= router
->cache_info
.identity_digest
;
1889 /* Make sure that we haven't already got this exact descriptor. */
1890 if (digestmap_get(routerlist
->desc_digest_map
,
1891 router
->cache_info
.signed_descriptor_digest
)) {
1893 "Dropping descriptor that we already have for router '%s'",
1895 *msg
= "Router descriptor was not new.";
1896 routerinfo_free(router
);
1900 if (routerlist_is_overfull(routerlist
))
1901 routerlist_remove_old_routers();
1904 if (authdir_wants_to_reject_router(router
, msg
,
1905 !from_cache
&& !from_fetch
)) {
1907 routerinfo_free(router
);
1910 authdir_believes_valid
= router
->is_valid
;
1911 } else if (from_fetch
) {
1912 /* Only check the descriptor digest against the network statuses when
1913 * we are receiving in response to a fetch. */
1915 if (!signed_desc_digest_is_recognized(&router
->cache_info
)) {
1916 /* We asked for it, so some networkstatus must have listed it when we
1917 * did. Save it if we're a cache in case somebody else asks for it. */
1919 "Received a no-longer-recognized descriptor for router '%s'",
1921 *msg
= "Router descriptor is not referenced by any network-status.";
1923 /* Only journal this desc if we'll be serving it. */
1924 if (!from_cache
&& get_options()->DirPort
)
1925 router_append_to_journal(&router
->cache_info
);
1926 routerlist_insert_old(routerlist
, router
);
1931 /* We no longer need a router with this descriptor digest. */
1932 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
1934 routerstatus_t
*rs
=
1935 networkstatus_find_entry(ns
, router
->cache_info
.identity_digest
);
1936 if (rs
&& !memcmp(rs
->descriptor_digest
,
1937 router
->cache_info
.signed_descriptor_digest
,
1939 rs
->need_to_mirror
= 0;
1942 /* If we have a router with the same identity key, choose the newer one. */
1943 old_router
= digestmap_get(routerlist
->identity_map
,
1944 router
->cache_info
.identity_digest
);
1946 int pos
= old_router
->routerlist_index
;
1947 tor_assert(smartlist_get(routerlist
->routers
, pos
) == old_router
);
1949 if (router
->cache_info
.published_on
<=
1950 old_router
->cache_info
.published_on
) {
1951 /* Same key, but old */
1952 log_debug(LD_DIR
, "Skipping not-new descriptor for router '%s'",
1954 /* Only journal this desc if we'll be serving it. */
1955 if (!from_cache
&& get_options()->DirPort
)
1956 router_append_to_journal(&router
->cache_info
);
1957 routerlist_insert_old(routerlist
, router
);
1958 *msg
= "Router descriptor was not new.";
1961 /* Same key, new. */
1962 int unreachable
= 0;
1963 log_debug(LD_DIR
, "Replacing entry for router '%s/%s' [%s]",
1964 router
->nickname
, old_router
->nickname
,
1965 hex_str(id_digest
,DIGEST_LEN
));
1966 if (router
->addr
== old_router
->addr
&&
1967 router
->or_port
== old_router
->or_port
) {
1968 /* these carry over when the address and orport are unchanged.*/
1969 router
->last_reachable
= old_router
->last_reachable
;
1970 router
->testing_since
= old_router
->testing_since
;
1971 router
->num_unreachable_notifications
=
1972 old_router
->num_unreachable_notifications
;
1974 if (authdir
&& !from_cache
&& !from_fetch
&&
1975 router_have_minimum_dir_info() &&
1976 dirserv_thinks_router_is_blatantly_unreachable(router
,
1978 if (router
->num_unreachable_notifications
>= 3) {
1980 log_notice(LD_DIR
, "Notifying server '%s' that it's unreachable. "
1981 "(ContactInfo '%s', platform '%s').",
1983 router
->contact_info
? router
->contact_info
: "",
1984 router
->platform
? router
->platform
: "");
1986 log_info(LD_DIR
,"'%s' may be unreachable -- the %d previous "
1987 "descriptors were thought to be unreachable.",
1988 router
->nickname
, router
->num_unreachable_notifications
);
1989 router
->num_unreachable_notifications
++;
1992 routerlist_replace(routerlist
, old_router
, router
, pos
, 1);
1994 router_append_to_journal(&router
->cache_info
);
1996 directory_set_dirty();
1997 *msg
= unreachable
? "Dirserver believes your ORPort is unreachable" :
1998 authdir_believes_valid
? "Valid server updated" :
1999 ("Invalid server updated. (This dirserver is marking your "
2000 "server as unapproved.)");
2001 return unreachable
? 1 : 0;
2005 /* We haven't seen a router with this identity before. Add it to the end of
2007 routerlist_insert(routerlist
, router
);
2009 router_append_to_journal(&router
->cache_info
);
2010 directory_set_dirty();
2014 /** Sorting helper: return <0, 0, or >0 depending on whether the
2015 * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
2016 * to, or later than that of *<b>b</b>. */
2018 _compare_old_routers_by_identity(const void **_a
, const void **_b
)
2021 const signed_descriptor_t
*r1
= *_a
, *r2
= *_b
;
2022 if ((i
= memcmp(r1
->identity_digest
, r2
->identity_digest
, DIGEST_LEN
)))
2024 return r1
->published_on
- r2
->published_on
;
2027 /** Internal type used to represent how long an old descriptor was valid,
2028 * where it appeared in the list of old descriptors, and whether it's extra
2029 * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
2030 struct duration_idx_t
{
2036 /** Sorting helper: compare two duration_idx_t by their duration. */
2038 _compare_duration_idx(const void *_d1
, const void *_d2
)
2040 const struct duration_idx_t
*d1
= _d1
;
2041 const struct duration_idx_t
*d2
= _d2
;
2042 return d1
->duration
- d2
->duration
;
2045 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
2046 * must contain routerinfo_t with the same identity and with publication time
2047 * in ascending order. Remove members from this range until there are no more
2048 * than max_descriptors_per_router() remaining. Start by removing the oldest
2049 * members from before <b>cutoff</b>, then remove members which were current
2050 * for the lowest amount of time. The order of members of old_routers at
2051 * indices <b>lo</b> or higher may be changed.
2054 routerlist_remove_old_cached_routers_with_id(time_t cutoff
, int lo
, int hi
,
2055 digestmap_t
*retain
)
2057 int i
, n
= hi
-lo
+1, n_extra
;
2059 struct duration_idx_t
*lifespans
;
2060 uint8_t *rmv
, *must_keep
;
2061 smartlist_t
*lst
= routerlist
->old_routers
;
2064 tor_assert(hi
< smartlist_len(lst
));
2065 tor_assert(lo
<= hi
);
2066 ident
= ((signed_descriptor_t
*)smartlist_get(lst
, lo
))->identity_digest
;
2067 for (i
= lo
+1; i
<= hi
; ++i
) {
2068 signed_descriptor_t
*r
= smartlist_get(lst
, i
);
2069 tor_assert(!memcmp(ident
, r
->identity_digest
, DIGEST_LEN
));
2073 /* Check whether we need to do anything at all. */
2074 n_extra
= n
- max_descriptors_per_router();
2078 lifespans
= tor_malloc_zero(sizeof(struct duration_idx_t
)*n
);
2079 rmv
= tor_malloc_zero(sizeof(uint8_t)*n
);
2080 must_keep
= tor_malloc_zero(sizeof(uint8_t)*n
);
2081 /* Set lifespans to contain the lifespan and index of each server. */
2082 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
2083 for (i
= lo
; i
<= hi
; ++i
) {
2084 signed_descriptor_t
*r
= smartlist_get(lst
, i
);
2085 signed_descriptor_t
*r_next
;
2086 lifespans
[i
-lo
].idx
= i
;
2087 if (retain
&& digestmap_get(retain
, r
->signed_descriptor_digest
)) {
2088 must_keep
[i
-lo
] = 1;
2091 r_next
= smartlist_get(lst
, i
+1);
2092 tor_assert(r
->published_on
<= r_next
->published_on
);
2093 lifespans
[i
-lo
].duration
= (r_next
->published_on
- r
->published_on
);
2096 lifespans
[i
-lo
].duration
= INT_MAX
;
2098 if (!must_keep
[i
-lo
] && r
->published_on
< cutoff
&& n_rmv
< n_extra
) {
2100 lifespans
[i
-lo
].old
= 1;
2105 if (n_rmv
< n_extra
) {
2107 * We aren't removing enough servers for being old. Sort lifespans by
2108 * the duration of liveness, and remove the ones we're not already going to
2109 * remove based on how long they were alive.
2111 qsort(lifespans
, n
, sizeof(struct duration_idx_t
), _compare_duration_idx
);
2112 for (i
= 0; i
< n
&& n_rmv
< n_extra
; ++i
) {
2113 if (!must_keep
[lifespans
[i
].idx
-lo
] && !lifespans
[i
].old
) {
2114 rmv
[lifespans
[i
].idx
-lo
] = 1;
2120 for (i
= hi
; i
>= lo
; --i
) {
2122 routerlist_remove_old(routerlist
, smartlist_get(lst
, i
), i
);
2124 tor_free(must_keep
);
2126 tor_free(lifespans
);
2129 /** Deactivate any routers from the routerlist that are more than
2130 * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
2131 * remove old routers from the list of cached routers if we have too many.
2134 routerlist_remove_old_routers(void)
2137 const char *cur_id
= NULL
;
2138 time_t now
= time(NULL
);
2140 routerinfo_t
*router
;
2141 signed_descriptor_t
*sd
;
2142 digestmap_t
*retain
;
2143 if (!routerlist
|| !networkstatus_list
)
2146 retain
= digestmap_new();
2147 cutoff
= now
- OLD_ROUTER_DESC_MAX_AGE
;
2148 /* Build a list of all the descriptors that _anybody_ recommends. */
2149 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
2151 /* XXXX The inner loop here gets pretty expensive, and actually shows up
2152 * on some profiles. It may be the reason digestmap_set shows up in
2153 * profiles too. If instead we kept a per-descriptor digest count of
2154 * how many networkstatuses recommended each descriptor, and changed
2155 * that only when the networkstatuses changed, that would be a speed
2156 * improvement, possibly 1-4% if it also removes digestmap_set from the
2157 * profile. Not worth it for 0.1.2.x, though. The new directory
2158 * system will obsolete this whole thing in 0.2.0.x. */
2159 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
*, rs
,
2160 if (rs
->published_on
>= cutoff
)
2161 digestmap_set(retain
, rs
->descriptor_digest
, (void*)1));
2164 /* If we have a bunch of networkstatuses, we should consider pruning current
2165 * routers that are too old and that nobody recommends. (If we don't have
2166 * enough networkstatuses, then we should get more before we decide to kill
2168 if (smartlist_len(networkstatus_list
) > get_n_v2_authorities() / 2) {
2169 cutoff
= now
- ROUTER_MAX_AGE
;
2170 /* Remove too-old unrecommended members of routerlist->routers. */
2171 for (i
= 0; i
< smartlist_len(routerlist
->routers
); ++i
) {
2172 router
= smartlist_get(routerlist
->routers
, i
);
2173 if (router
->cache_info
.published_on
<= cutoff
&&
2174 !digestmap_get(retain
,router
->cache_info
.signed_descriptor_digest
)) {
2175 /* Too old: remove it. (If we're a cache, just move it into
2178 "Forgetting obsolete (too old) routerinfo for router '%s'",
2180 routerlist_remove(routerlist
, router
, i
--, 1);
2185 /* Remove far-too-old members of routerlist->old_routers. */
2186 cutoff
= now
- OLD_ROUTER_DESC_MAX_AGE
;
2187 for (i
= 0; i
< smartlist_len(routerlist
->old_routers
); ++i
) {
2188 sd
= smartlist_get(routerlist
->old_routers
, i
);
2189 if (sd
->published_on
<= cutoff
&&
2190 !digestmap_get(retain
, sd
->signed_descriptor_digest
)) {
2191 /* Too old. Remove it. */
2192 routerlist_remove_old(routerlist
, sd
, i
--);
2196 /* Now we might have to look at routerlist->old_routers for extraneous
2197 * members. (We'd keep all the members if we could, but we need to save
2198 * space.) First, check whether we have too many router descriptors, total.
2199 * We're okay with having too many for some given router, so long as the
2200 * total number doesn't approach max_descriptors_per_router()*len(router).
2202 if (smartlist_len(routerlist
->old_routers
) <
2203 smartlist_len(routerlist
->routers
) * (max_descriptors_per_router() - 1))
2206 smartlist_sort(routerlist
->old_routers
, _compare_old_routers_by_identity
);
2208 /* Iterate through the list from back to front, so when we remove descriptors
2209 * we don't mess up groups we haven't gotten to. */
2210 for (i
= smartlist_len(routerlist
->old_routers
)-1; i
>= 0; --i
) {
2211 signed_descriptor_t
*r
= smartlist_get(routerlist
->old_routers
, i
);
2213 cur_id
= r
->identity_digest
;
2216 if (memcmp(cur_id
, r
->identity_digest
, DIGEST_LEN
)) {
2217 routerlist_remove_old_cached_routers_with_id(cutoff
, i
+1, hi
, retain
);
2218 cur_id
= r
->identity_digest
;
2223 routerlist_remove_old_cached_routers_with_id(cutoff
, 0, hi
, retain
);
2224 routerlist_assert_ok(routerlist
);
2227 digestmap_free(retain
, NULL
);
2231 * Code to parse a single router descriptor and insert it into the
2232 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
2233 * descriptor was well-formed but could not be added; and 1 if the
2234 * descriptor was added.
2236 * If we don't add it and <b>msg</b> is not NULL, then assign to
2237 * *<b>msg</b> a static string describing the reason for refusing the
2240 * This is used only by the controller.
2243 router_load_single_router(const char *s
, uint8_t purpose
, const char **msg
)
2251 if (!(ri
= router_parse_entry_from_string(s
, NULL
, 1))) {
2252 log_warn(LD_DIR
, "Error parsing router descriptor; dropping.");
2253 *msg
= "Couldn't parse router descriptor.";
2256 ri
->purpose
= purpose
;
2257 if (router_is_me(ri
)) {
2258 log_warn(LD_DIR
, "Router's identity key matches mine; dropping.");
2259 *msg
= "Router's identity key matches mine.";
2260 routerinfo_free(ri
);
2264 lst
= smartlist_create();
2265 smartlist_add(lst
, ri
);
2266 routers_update_status_from_networkstatus(lst
, 0);
2268 if ((r
=router_add_to_routerlist(ri
, msg
, 0, 0))<0) {
2269 /* we've already assigned to *msg now, and ri is already freed */
2272 log_warn(LD_DIR
, "Couldn't add router to list: %s Dropping.", *msg
);
2273 smartlist_free(lst
);
2276 control_event_descriptors_changed(lst
);
2277 smartlist_free(lst
);
2278 log_debug(LD_DIR
, "Added router to list");
2283 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
2284 * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
2285 * are in response to a query to the network: cache them by adding them to
2288 * If <b>requested_fingerprints</b> is provided, it must contain a list of
2289 * uppercased identity fingerprints. Do not update any router whose
2290 * fingerprint is not on the list; after updating a router, remove its
2291 * fingerprint from the list.
2294 router_load_routers_from_string(const char *s
, saved_location_t saved_location
,
2295 smartlist_t
*requested_fingerprints
)
2297 smartlist_t
*routers
= smartlist_create(), *changed
= smartlist_create();
2298 char fp
[HEX_DIGEST_LEN
+1];
2300 int from_cache
= (saved_location
!= SAVED_NOWHERE
);
2302 router_parse_list_from_string(&s
, routers
, saved_location
);
2304 routers_update_status_from_networkstatus(routers
, !from_cache
);
2306 log_info(LD_DIR
, "%d elements to add", smartlist_len(routers
));
2308 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
,
2310 base16_encode(fp
, sizeof(fp
), ri
->cache_info
.signed_descriptor_digest
,
2312 if (requested_fingerprints
) {
2313 if (smartlist_string_isin(requested_fingerprints
, fp
)) {
2314 smartlist_string_remove(requested_fingerprints
, fp
);
2317 smartlist_join_strings(requested_fingerprints
," ",0,NULL
);
2319 "We received a router descriptor with a fingerprint (%s) "
2320 "that we never requested. (We asked for: %s.) Dropping.",
2322 tor_free(requested
);
2323 routerinfo_free(ri
);
2328 if (router_add_to_routerlist(ri
, &msg
, from_cache
, !from_cache
) >= 0)
2329 smartlist_add(changed
, ri
);
2332 if (smartlist_len(changed
))
2333 control_event_descriptors_changed(changed
);
2335 routerlist_assert_ok(routerlist
);
2336 router_rebuild_store(0);
2338 smartlist_free(routers
);
2339 smartlist_free(changed
);
2342 /** Helper: return a newly allocated string containing the name of the filename
2343 * where we plan to cache the network status with the given identity digest. */
2345 networkstatus_get_cache_filename(const char *identity_digest
)
2347 const char *datadir
= get_options()->DataDirectory
;
2348 size_t len
= strlen(datadir
)+64;
2349 char fp
[HEX_DIGEST_LEN
+1];
2350 char *fn
= tor_malloc(len
+1);
2351 base16_encode(fp
, HEX_DIGEST_LEN
+1, identity_digest
, DIGEST_LEN
);
2352 tor_snprintf(fn
, len
, "%s/cached-status/%s",datadir
,fp
);
2356 /** Helper for smartlist_sort: Compare two networkstatus objects by
2357 * publication date. */
2359 _compare_networkstatus_published_on(const void **_a
, const void **_b
)
2361 const networkstatus_t
*a
= *_a
, *b
= *_b
;
2362 if (a
->published_on
< b
->published_on
)
2364 else if (a
->published_on
> b
->published_on
)
2370 /** Add the parsed neworkstatus in <b>ns</b> (with original document in
2371 * <b>s</b> to the disk cache (and the in-memory directory server cache) as
2374 add_networkstatus_to_cache(const char *s
,
2375 networkstatus_source_t source
,
2376 networkstatus_t
*ns
)
2378 if (source
!= NS_FROM_CACHE
) {
2379 char *fn
= networkstatus_get_cache_filename(ns
->identity_digest
);
2380 if (write_str_to_file(fn
, s
, 0)<0) {
2381 log_notice(LD_FS
, "Couldn't write cached network status to \"%s\"", fn
);
2386 if (get_options()->DirPort
)
2387 dirserv_set_cached_networkstatus_v2(s
,
2388 ns
->identity_digest
,
2394 /** How far in the future do we allow a network-status to get before removing
2396 #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
2398 /** Given a string <b>s</b> containing a network status that we received at
2399 * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
2400 * store it, and put it into our cache as necessary.
2402 * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
2403 * own networkstatus_t (if we're an authoritative directory server).
2405 * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
2408 * If <b>requested_fingerprints</b> is provided, it must contain a list of
2409 * uppercased identity fingerprints. Do not update any networkstatus whose
2410 * fingerprint is not on the list; after updating a networkstatus, remove its
2411 * fingerprint from the list.
2413 * Return 0 on success, -1 on failure.
2415 * Callers should make sure that routers_update_all_from_networkstatus() is
2416 * invoked after this function succeeds.
2419 router_set_networkstatus(const char *s
, time_t arrived_at
,
2420 networkstatus_source_t source
, smartlist_t
*requested_fingerprints
)
2422 networkstatus_t
*ns
;
2426 trusted_dir_server_t
*trusted_dir
= NULL
;
2427 const char *source_desc
= NULL
;
2428 char fp
[HEX_DIGEST_LEN
+1];
2429 char published
[ISO_TIME_LEN
+1];
2431 ns
= networkstatus_parse_from_string(s
);
2433 log_warn(LD_DIR
, "Couldn't parse network status.");
2436 base16_encode(fp
, HEX_DIGEST_LEN
+1, ns
->identity_digest
, DIGEST_LEN
);
2438 router_get_trusteddirserver_by_digest(ns
->identity_digest
)) ||
2439 !trusted_dir
->is_v2_authority
) {
2440 log_info(LD_DIR
, "Network status was signed, but not by an authoritative "
2441 "directory we recognize.");
2442 if (!get_options()->DirPort
) {
2443 networkstatus_free(ns
);
2448 source_desc
= trusted_dir
->description
;
2451 if (arrived_at
> now
)
2454 ns
->received_on
= arrived_at
;
2456 format_iso_time(published
, ns
->published_on
);
2458 if (ns
->published_on
> now
+ NETWORKSTATUS_ALLOW_SKEW
) {
2459 log_warn(LD_GENERAL
, "Network status from %s was published in the future "
2460 "(%s GMT). Somebody is skewed here: check your clock. "
2462 source_desc
, published
);
2463 control_event_general_status(LOG_WARN
,
2464 "CLOCK_SKEW SOURCE=NETWORKSTATUS:%s:%d",
2465 ns
->source_address
, ns
->source_dirport
);
2469 if (!networkstatus_list
)
2470 networkstatus_list
= smartlist_create();
2472 if ( (source
== NS_FROM_DIR_BY_FP
|| source
== NS_FROM_DIR_ALL
) &&
2473 router_digest_is_me(ns
->identity_digest
)) {
2474 /* Don't replace our own networkstatus when we get it from somebody else.*/
2475 networkstatus_free(ns
);
2479 if (requested_fingerprints
) {
2480 if (smartlist_string_isin(requested_fingerprints
, fp
)) {
2481 smartlist_string_remove(requested_fingerprints
, fp
);
2484 smartlist_join_strings(requested_fingerprints
," ",0,NULL
);
2485 if (source
!= NS_FROM_DIR_ALL
) {
2487 "We received a network status with a fingerprint (%s) that we "
2488 "never requested. (We asked for: %s.) Dropping.",
2490 tor_free(requested
);
2497 if (!skewed
&& get_options()->DirPort
) {
2498 /* We got a non-trusted networkstatus, and we're a directory cache.
2499 * This means that we asked an authority, and it told us about another
2500 * authority we didn't recognize. */
2502 "We do not recognize authority (%s) but we are willing "
2504 add_networkstatus_to_cache(s
, source
, ns
);
2505 networkstatus_free(ns
);
2510 if (source
!= NS_FROM_CACHE
&& trusted_dir
)
2511 trusted_dir
->n_networkstatus_failures
= 0;
2514 for (i
=0; i
< smartlist_len(networkstatus_list
); ++i
) {
2515 networkstatus_t
*old_ns
= smartlist_get(networkstatus_list
, i
);
2517 if (!memcmp(old_ns
->identity_digest
, ns
->identity_digest
, DIGEST_LEN
)) {
2518 if (!memcmp(old_ns
->networkstatus_digest
,
2519 ns
->networkstatus_digest
, DIGEST_LEN
)) {
2520 /* Same one we had before. */
2521 networkstatus_free(ns
);
2523 "Not replacing network-status from %s (published %s); "
2524 "we already have it.",
2525 trusted_dir
->description
, published
);
2526 if (old_ns
->received_on
< arrived_at
) {
2527 if (source
!= NS_FROM_CACHE
) {
2529 fn
= networkstatus_get_cache_filename(old_ns
->identity_digest
);
2530 /* We use mtime to tell when it arrived, so update that. */
2534 old_ns
->received_on
= arrived_at
;
2537 } else if (old_ns
->published_on
>= ns
->published_on
) {
2538 char old_published
[ISO_TIME_LEN
+1];
2539 format_iso_time(old_published
, old_ns
->published_on
);
2541 "Not replacing network-status from %s (published %s);"
2542 " we have a newer one (published %s) for this authority.",
2543 trusted_dir
->description
, published
,
2545 networkstatus_free(ns
);
2548 networkstatus_free(old_ns
);
2549 smartlist_set(networkstatus_list
, i
, ns
);
2557 smartlist_add(networkstatus_list
, ns
);
2559 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
*, rs
,
2561 if (!router_get_by_descriptor_digest(rs
->descriptor_digest
))
2562 rs
->need_to_mirror
= 1;
2565 log_info(LD_DIR
, "Setting networkstatus %s %s (published %s)",
2566 source
== NS_FROM_CACHE
?"cached from":
2567 ((source
== NS_FROM_DIR_BY_FP
|| source
== NS_FROM_DIR_ALL
) ?
2568 "downloaded from":"generated for"),
2569 trusted_dir
->description
, published
);
2570 networkstatus_list_has_changed
= 1;
2571 router_dir_info_changed();
2573 smartlist_sort(networkstatus_list
, _compare_networkstatus_published_on
);
2576 add_networkstatus_to_cache(s
, source
, ns
);
2578 networkstatus_list_update_recent(now
);
2583 /** How old do we allow a network-status to get before removing it
2585 #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
2586 /** Remove all very-old network_status_t objects from memory and from the
2589 networkstatus_list_clean(time_t now
)
2592 if (!networkstatus_list
)
2595 for (i
= 0; i
< smartlist_len(networkstatus_list
); ++i
) {
2596 networkstatus_t
*ns
= smartlist_get(networkstatus_list
, i
);
2598 if (ns
->published_on
+ MAX_NETWORKSTATUS_AGE
> now
)
2600 /* Okay, this one is too old. Remove it from the list, and delete it
2601 * from the cache. */
2602 smartlist_del(networkstatus_list
, i
--);
2603 fname
= networkstatus_get_cache_filename(ns
->identity_digest
);
2604 if (file_status(fname
) == FN_FILE
) {
2605 log_info(LD_DIR
, "Removing too-old networkstatus in %s", fname
);
2609 if (get_options()->DirPort
) {
2610 dirserv_set_cached_networkstatus_v2(NULL
, ns
->identity_digest
, 0);
2612 networkstatus_free(ns
);
2613 router_dir_info_changed();
2616 /* And now go through the directory cache for any cached untrusted
2617 * networkstatuses and other network info. */
2618 dirserv_clear_old_networkstatuses(now
- MAX_NETWORKSTATUS_AGE
);
2619 dirserv_clear_old_v1_info(now
);
2622 /** Helper for bsearching a list of routerstatus_t pointers.*/
2624 _compare_digest_to_routerstatus_entry(const void *_key
, const void **_member
)
2626 const char *key
= _key
;
2627 const routerstatus_t
*rs
= *_member
;
2628 return memcmp(key
, rs
->identity_digest
, DIGEST_LEN
);
2631 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
2632 * NULL if none was found. */
2633 static routerstatus_t
*
2634 networkstatus_find_entry(networkstatus_t
*ns
, const char *digest
)
2636 return smartlist_bsearch(ns
->entries
, digest
,
2637 _compare_digest_to_routerstatus_entry
);
2640 /** Return the consensus view of the status of the router whose digest is
2641 * <b>digest</b>, or NULL if we don't know about any such router. */
2642 local_routerstatus_t
*
2643 router_get_combined_status_by_digest(const char *digest
)
2645 if (!routerstatus_list
)
2647 return smartlist_bsearch(routerstatus_list
, digest
,
2648 _compare_digest_to_routerstatus_entry
);
2651 /** Given a nickname (possibly verbose, possibly a hexadecimal digest), return
2652 * the corresponding local_routerstatus_t, or NULL if none exists. Warn the
2653 * user if <b>warn_if_unnamed</b> is set, and they have specified a router by
2654 * nickname, but the Named flag isn't set for that router. */
2655 static local_routerstatus_t
*
2656 router_get_combined_status_by_nickname(const char *nickname
,
2657 int warn_if_unnamed
)
2659 char digest
[DIGEST_LEN
];
2660 local_routerstatus_t
*best
=NULL
;
2661 smartlist_t
*matches
=NULL
;
2663 if (!routerstatus_list
|| !nickname
)
2666 if (nickname
[0] == '$') {
2667 if (base16_decode(digest
, DIGEST_LEN
, nickname
+1, strlen(nickname
))<0)
2669 return router_get_combined_status_by_digest(digest
);
2670 } else if (strlen(nickname
) == HEX_DIGEST_LEN
&&
2671 (base16_decode(digest
, DIGEST_LEN
, nickname
+1, strlen(nickname
))==0)) {
2672 return router_get_combined_status_by_digest(digest
);
2675 matches
= smartlist_create();
2676 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, lrs
,
2678 if (!strcasecmp(lrs
->status
.nickname
, nickname
)) {
2679 if (lrs
->status
.is_named
) {
2680 smartlist_free(matches
);
2683 smartlist_add(matches
, lrs
);
2689 if (smartlist_len(matches
)>1 && warn_if_unnamed
) {
2691 SMARTLIST_FOREACH(matches
, local_routerstatus_t
*, lrs
,
2693 if (! lrs
->name_lookup_warned
) {
2694 lrs
->name_lookup_warned
=1;
2699 log_warn(LD_CONFIG
,"There are multiple matches for the nickname \"%s\","
2700 " but none is listed as named by the directory authorites. "
2701 "Choosing one arbitrarily.", nickname
);
2703 } else if (warn_if_unnamed
&& best
&& !best
->name_lookup_warned
) {
2704 char fp
[HEX_DIGEST_LEN
+1];
2705 base16_encode(fp
, sizeof(fp
),
2706 best
->status
.identity_digest
, DIGEST_LEN
);
2708 "To look up a status, you specified a server \"%s\" by name, but the "
2709 "directory authorities do not have a binding for this nickname. "
2710 "To make sure you get the same server in the future, refer to "
2711 "it by key, as \"$%s\".", nickname
, fp
);
2712 best
->name_lookup_warned
= 1;
2714 smartlist_free(matches
);
2718 /** Find a routerstatus_t that corresponds to <b>hexdigest</b>, if
2719 * any. Prefer ones that belong to authorities. */
2721 routerstatus_get_by_hexdigest(const char *hexdigest
)
2723 char digest
[DIGEST_LEN
];
2724 local_routerstatus_t
*rs
;
2725 trusted_dir_server_t
*ds
;
2727 if (strlen(hexdigest
) < HEX_DIGEST_LEN
||
2728 base16_decode(digest
,DIGEST_LEN
,hexdigest
,HEX_DIGEST_LEN
) < 0)
2730 if ((ds
= router_get_trusteddirserver_by_digest(digest
)))
2731 return &(ds
->fake_status
.status
);
2732 if ((rs
= router_get_combined_status_by_digest(digest
)))
2733 return &(rs
->status
);
2737 /** Return true iff any networkstatus includes a descriptor whose digest
2738 * is that of <b>desc</b>. */
2740 signed_desc_digest_is_recognized(signed_descriptor_t
*desc
)
2743 if (!networkstatus_list
)
2746 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
2748 if (!(rs
= networkstatus_find_entry(ns
, desc
->identity_digest
)))
2750 if (!memcmp(rs
->descriptor_digest
,
2751 desc
->signed_descriptor_digest
, DIGEST_LEN
))
2757 /** How frequently do directory authorities re-download fresh networkstatus
2759 #define AUTHORITY_NS_CACHE_INTERVAL (5*60)
2761 /** How frequently do non-authority directory caches re-download fresh
2762 * networkstatus documents? */
2763 #define NONAUTHORITY_NS_CACHE_INTERVAL (15*60)
2765 /** We are a directory server, and so cache network_status documents.
2766 * Initiate downloads as needed to update them. For authorities, this means
2767 * asking each trusted directory for its network-status. For caches, this
2768 * means asking a random authority for all network-statuses.
2771 update_networkstatus_cache_downloads(time_t now
)
2773 int authority
= authdir_mode(get_options());
2775 authority
? AUTHORITY_NS_CACHE_INTERVAL
: NONAUTHORITY_NS_CACHE_INTERVAL
;
2777 if (last_networkstatus_download_attempted
+ interval
>= now
)
2779 if (!trusted_dir_servers
)
2782 last_networkstatus_download_attempted
= now
;
2785 /* An authority launches a separate connection for everybody. */
2786 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
2788 char resource
[HEX_DIGEST_LEN
+6]; /* fp/hexdigit.z\0 */
2789 if (!ds
->is_v2_authority
)
2791 if (router_digest_is_me(ds
->digest
))
2793 if (connection_get_by_type_addr_port_purpose(
2794 CONN_TYPE_DIR
, ds
->addr
, ds
->dir_port
,
2795 DIR_PURPOSE_FETCH_NETWORKSTATUS
)) {
2796 /* We are already fetching this one. */
2799 strlcpy(resource
, "fp/", sizeof(resource
));
2800 base16_encode(resource
+3, sizeof(resource
)-3, ds
->digest
, DIGEST_LEN
);
2801 strlcat(resource
, ".z", sizeof(resource
));
2802 directory_initiate_command_routerstatus(
2803 &ds
->fake_status
.status
, DIR_PURPOSE_FETCH_NETWORKSTATUS
,
2804 0, /* Not private */
2806 NULL
, 0 /* No payload. */);
2809 /* A non-authority cache launches one connection to a random authority. */
2810 /* (Check whether we're currently fetching network-status objects.) */
2811 if (!connection_get_by_type_purpose(CONN_TYPE_DIR
,
2812 DIR_PURPOSE_FETCH_NETWORKSTATUS
))
2813 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS
,"all.z",1);
2817 /** How long (in seconds) does a client wait after getting a network status
2818 * before downloading the next in sequence? */
2819 #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
2820 /** How many times do we allow a networkstatus download to fail before we
2821 * assume that the authority isn't publishing? */
2822 #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
2823 /** We are not a directory cache or authority. Update our network-status list
2824 * by launching a new directory fetch for enough network-status documents "as
2825 * necessary". See function comments for implementation details.
2828 update_networkstatus_client_downloads(time_t now
)
2830 int n_live
= 0, n_dirservers
, n_running_dirservers
, needed
= 0;
2831 int fetch_latest
= 0;
2832 int most_recent_idx
= -1;
2833 trusted_dir_server_t
*most_recent
= NULL
;
2834 time_t most_recent_received
= 0;
2835 char *resource
, *cp
;
2836 size_t resource_len
;
2837 smartlist_t
*missing
;
2839 if (connection_get_by_type_purpose(CONN_TYPE_DIR
,
2840 DIR_PURPOSE_FETCH_NETWORKSTATUS
))
2843 /* This is a little tricky. We want to download enough network-status
2844 * objects so that we have all of them under
2845 * NETWORKSTATUS_MAX_AGE publication time. We want to download a new
2846 * *one* if the most recent one's publication time is under
2847 * NETWORKSTATUS_CLIENT_DL_INTERVAL.
2849 if (!get_n_v2_authorities())
2851 n_dirservers
= n_running_dirservers
= 0;
2852 missing
= smartlist_create();
2853 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
2855 networkstatus_t
*ns
= networkstatus_get_by_digest(ds
->digest
);
2856 if (!ds
->is_v2_authority
)
2859 if (ds
->n_networkstatus_failures
> NETWORKSTATUS_N_ALLOWABLE_FAILURES
)
2861 ++n_running_dirservers
;
2862 if (ns
&& ns
->published_on
> now
-NETWORKSTATUS_MAX_AGE
)
2865 smartlist_add(missing
, ds
->digest
);
2866 if (ns
&& (!most_recent
|| ns
->received_on
> most_recent_received
)) {
2867 most_recent_idx
= ds_sl_idx
; /* magic variable from FOREACH */
2869 most_recent_received
= ns
->received_on
;
2873 /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
2874 if (!smartlist_len(missing
) &&
2875 most_recent_received
< now
-NETWORKSTATUS_CLIENT_DL_INTERVAL
) {
2876 log_info(LD_DIR
, "Our most recent network-status document (from %s) "
2877 "is %d seconds old; downloading another.",
2878 most_recent
?most_recent
->description
:"nobody",
2879 (int)(now
-most_recent_received
));
2882 } else if (smartlist_len(missing
)) {
2883 log_info(LD_DIR
, "For %d/%d running directory servers, we have %d live"
2884 " network-status documents. Downloading %d.",
2885 n_running_dirservers
, n_dirservers
, n_live
,
2886 smartlist_len(missing
));
2887 needed
= smartlist_len(missing
);
2889 smartlist_free(missing
);
2893 /* If no networkstatus was found, choose a dirserver at random as "most
2895 if (most_recent_idx
<0)
2896 most_recent_idx
= crypto_rand_int(n_dirservers
);
2901 for (i
= most_recent_idx
+ 1; 1; ++i
) {
2902 trusted_dir_server_t
*ds
;
2903 if (i
>= n_dirservers
)
2905 ds
= smartlist_get(trusted_dir_servers
, i
);
2906 if (! ds
->is_v2_authority
)
2908 if (n_failed
< n_dirservers
&&
2909 ds
->n_networkstatus_failures
> NETWORKSTATUS_N_ALLOWABLE_FAILURES
) {
2913 smartlist_add(missing
, ds
->digest
);
2918 /* Build a request string for all the resources we want. */
2919 resource_len
= smartlist_len(missing
) * (HEX_DIGEST_LEN
+1) + 6;
2920 resource
= tor_malloc(resource_len
);
2921 memcpy(resource
, "fp/", 3);
2923 smartlist_sort_digests(missing
);
2924 needed
= smartlist_len(missing
);
2925 SMARTLIST_FOREACH(missing
, const char *, d
,
2927 base16_encode(cp
, HEX_DIGEST_LEN
+1, d
, DIGEST_LEN
);
2928 cp
+= HEX_DIGEST_LEN
;
2933 memcpy(cp
, ".z", 3);
2934 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS
, resource
, 1);
2936 smartlist_free(missing
);
2939 /** Launch requests for networkstatus documents as appropriate. */
2941 update_networkstatus_downloads(time_t now
)
2943 or_options_t
*options
= get_options();
2944 if (options
->DirPort
)
2945 update_networkstatus_cache_downloads(now
);
2947 update_networkstatus_client_downloads(now
);
2950 /** Return 1 if all running sufficiently-stable routers will reject
2951 * addr:port, return 0 if any might accept it. */
2953 router_exit_policy_all_routers_reject(uint32_t addr
, uint16_t port
,
2956 addr_policy_result_t r
;
2957 if (!routerlist
) return 1;
2959 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
2961 if (router
->is_running
&&
2962 !router_is_unreliable(router
, need_uptime
, 0, 0)) {
2963 r
= compare_addr_to_addr_policy(addr
, port
, router
->exit_policy
);
2964 if (r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
)
2965 return 0; /* this one could be ok. good enough. */
2968 return 1; /* all will reject. */
2971 /** Return true iff <b>router</b> does not permit exit streams.
2974 router_exit_policy_rejects_all(routerinfo_t
*router
)
2976 return compare_addr_to_addr_policy(0, 0, router
->exit_policy
)
2977 == ADDR_POLICY_REJECTED
;
2980 /** Add to the list of authorized directory servers one at
2981 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
2982 * <b>address</b> is NULL, add ourself. */
2984 add_trusted_dir_server(const char *nickname
, const char *address
,
2985 uint16_t dir_port
, uint16_t or_port
,
2986 const char *digest
, int is_v1_authority
,
2987 int is_v2_authority
, int is_hidserv_authority
)
2989 trusted_dir_server_t
*ent
;
2991 char *hostname
= NULL
;
2993 if (!trusted_dir_servers
)
2994 trusted_dir_servers
= smartlist_create();
2996 if (!address
) { /* The address is us; we should guess. */
2997 if (resolve_my_address(LOG_WARN
, get_options(), &a
, &hostname
) < 0) {
2999 "Couldn't find a suitable address when adding ourself as a "
3000 "trusted directory server.");
3004 if (tor_lookup_hostname(address
, &a
)) {
3006 "Unable to lookup address for directory server at '%s'",
3010 hostname
= tor_strdup(address
);
3014 ent
= tor_malloc_zero(sizeof(trusted_dir_server_t
));
3015 ent
->nickname
= nickname
? tor_strdup(nickname
) : NULL
;
3016 ent
->address
= hostname
;
3018 ent
->dir_port
= dir_port
;
3019 ent
->or_port
= or_port
;
3020 ent
->is_running
= 1;
3021 ent
->is_v1_authority
= is_v1_authority
;
3022 ent
->is_v2_authority
= is_v2_authority
;
3023 ent
->is_hidserv_authority
= is_hidserv_authority
;
3024 memcpy(ent
->digest
, digest
, DIGEST_LEN
);
3026 dlen
= 64 + strlen(hostname
) + (nickname
?strlen(nickname
):0);
3027 ent
->description
= tor_malloc(dlen
);
3029 tor_snprintf(ent
->description
, dlen
, "directory server \"%s\" at %s:%d",
3030 nickname
, hostname
, (int)dir_port
);
3032 tor_snprintf(ent
->description
, dlen
, "directory server at %s:%d",
3033 hostname
, (int)dir_port
);
3035 ent
->fake_status
.status
.addr
= ent
->addr
;
3036 memcpy(ent
->fake_status
.status
.identity_digest
, digest
, DIGEST_LEN
);
3038 strlcpy(ent
->fake_status
.status
.nickname
, nickname
,
3039 sizeof(ent
->fake_status
.status
.nickname
));
3041 ent
->fake_status
.status
.nickname
[0] = '\0';
3042 ent
->fake_status
.status
.dir_port
= ent
->dir_port
;
3043 ent
->fake_status
.status
.or_port
= ent
->or_port
;
3045 smartlist_add(trusted_dir_servers
, ent
);
3046 router_dir_info_changed();
3049 /** Free storage held in <b>ds</b> */
3051 trusted_dir_server_free(trusted_dir_server_t
*ds
)
3053 tor_free(ds
->nickname
);
3054 tor_free(ds
->description
);
3055 tor_free(ds
->address
);
3059 /** Remove all members from the list of trusted dir servers. */
3061 clear_trusted_dir_servers(void)
3063 if (trusted_dir_servers
) {
3064 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
3065 trusted_dir_server_free(ent
));
3066 smartlist_clear(trusted_dir_servers
);
3068 trusted_dir_servers
= smartlist_create();
3070 router_dir_info_changed();
3073 /** Return 1 if any trusted dir server supports v1 directories,
3076 any_trusted_dir_is_v1_authority(void)
3078 if (trusted_dir_servers
)
3079 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
3080 if (ent
->is_v1_authority
) return 1);
3084 /** Return the network status with a given identity digest. */
3086 networkstatus_get_by_digest(const char *digest
)
3088 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
3090 if (!memcmp(ns
->identity_digest
, digest
, DIGEST_LEN
))
3096 /** We believe networkstatuses more recent than this when they tell us that
3097 * our server is broken, invalid, obsolete, etc. */
3098 #define SELF_OPINION_INTERVAL (90*60)
3100 /** Result of checking whether a version is recommended. */
3101 typedef struct combined_version_status_t
{
3102 /** How many networkstatuses claim to know about versions? */
3104 /** What do the majority of networkstatuses believe about this version? */
3105 version_status_t consensus
;
3106 /** How many networkstatuses constitute the majority? */
3108 } combined_version_status_t
;
3110 /** Return a string naming the versions of Tor recommended by
3111 * more than half the versioning networkstatuses. */
3113 compute_recommended_versions(time_t now
, int client
,
3114 const char *my_version
,
3115 combined_version_status_t
*status_out
)
3119 smartlist_t
*combined
, *recommended
;
3120 int n_versioning
, n_recommending
;
3122 /** holds the compromise status taken among all non-recommending
3124 version_status_t consensus
= VS_RECOMMENDED
;
3125 (void) now
; /* right now, we consider *all* statuses, regardless of age. */
3127 tor_assert(my_version
);
3128 tor_assert(status_out
);
3130 memset(status_out
, 0, sizeof(combined_version_status_t
));
3132 if (!networkstatus_list
)
3133 return tor_strdup("<none>");
3135 combined
= smartlist_create();
3136 n_versioning
= n_recommending
= 0;
3137 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
3140 smartlist_t
*versions
;
3141 version_status_t status
;
3142 if (! ns
->recommends_versions
)
3145 vers
= client
? ns
->client_versions
: ns
->server_versions
;
3148 versions
= smartlist_create();
3149 smartlist_split_string(versions
, vers
, ",",
3150 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3151 sort_version_list(versions
, 1);
3152 smartlist_add_all(combined
, versions
);
3153 smartlist_free(versions
);
3155 /* now, check _our_ version */
3156 status
= tor_version_is_obsolete(my_version
, vers
);
3157 if (status
== VS_RECOMMENDED
)
3159 consensus
= version_status_join(status
, consensus
);
3162 sort_version_list(combined
, 0);
3166 recommended
= smartlist_create();
3167 SMARTLIST_FOREACH(combined
, char *, cp
,
3169 if (current
&& !strcmp(cp
, current
)) {
3172 if (n_seen
> n_versioning
/2 && current
)
3173 smartlist_add(recommended
, current
);
3178 if (n_seen
> n_versioning
/2 && current
)
3179 smartlist_add(recommended
, current
);
3181 result
= smartlist_join_strings(recommended
, ", ", 0, NULL
);
3183 SMARTLIST_FOREACH(combined
, char *, cp
, tor_free(cp
));
3184 smartlist_free(combined
);
3185 smartlist_free(recommended
);
3187 status_out
->n_versioning
= n_versioning
;
3188 if (n_recommending
> n_versioning
/2) {
3189 status_out
->consensus
= VS_RECOMMENDED
;
3190 status_out
->n_concurring
= n_recommending
;
3192 status_out
->consensus
= consensus
;
3193 status_out
->n_concurring
= n_versioning
- n_recommending
;
3199 /** How many times do we have to fail at getting a networkstatus we can't find
3200 * before we're willing to believe it's okay to set up router statuses? */
3201 #define N_NS_ATTEMPTS_TO_SET_ROUTERS 4
3202 /** How many times do we have to fail at getting a networkstatus we can't find
3203 * before we're willing to believe it's okay to check our version? */
3204 #define N_NS_ATTEMPTS_TO_CHECK_VERSION 4
3206 /** If the network-status list has changed since the last time we called this
3207 * function, update the status of every routerinfo from the network-status
3211 routers_update_all_from_networkstatus(void)
3215 if (!routerlist
|| !networkstatus_list
||
3216 (!networkstatus_list_has_changed
&& !routerstatus_list_has_changed
))
3219 router_dir_info_changed();
3222 if (networkstatus_list_has_changed
)
3223 routerstatus_list_update_from_networkstatus(now
);
3225 routers_update_status_from_networkstatus(routerlist
->routers
, 0);
3227 me
= router_get_my_routerinfo();
3228 if (me
&& !have_warned_about_invalid_status
&&
3229 have_tried_downloading_all_statuses(N_NS_ATTEMPTS_TO_SET_ROUTERS
)) {
3230 int n_recent
= 0, n_listing
= 0, n_valid
= 0, n_named
= 0, n_naming
= 0;
3232 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
3234 if (ns
->received_on
+ SELF_OPINION_INTERVAL
< now
)
3237 if (ns
->binds_names
)
3239 if (!(rs
= networkstatus_find_entry(ns
, me
->cache_info
.identity_digest
)))
3249 if (n_valid
<= n_listing
/2) {
3250 log_info(LD_GENERAL
,
3251 "%d/%d recent statements from directory authorities list us "
3252 "as unapproved. Are you misconfigured?",
3253 n_listing
-n_valid
, n_listing
);
3254 have_warned_about_invalid_status
= 1;
3255 } else if (n_naming
&& !n_named
) {
3256 log_info(LD_GENERAL
, "0/%d name-binding directory authorities "
3257 "recognize your nickname. Please consider sending your "
3258 "nickname and identity fingerprint to the tor-ops.",
3260 have_warned_about_invalid_status
= 1;
3265 entry_guards_compute_status();
3267 if (!have_warned_about_old_version
&&
3268 have_tried_downloading_all_statuses(N_NS_ATTEMPTS_TO_CHECK_VERSION
)) {
3269 combined_version_status_t st
;
3270 int is_server
= server_mode(get_options());
3273 recommended
= compute_recommended_versions(now
, !is_server
, VERSION
, &st
);
3275 if (st
.n_versioning
) {
3276 if (st
.consensus
== VS_RECOMMENDED
) {
3277 log_info(LD_GENERAL
, "%d/%d statements from version-listing "
3278 "directory authorities say my version is ok.",
3279 st
.n_concurring
, st
.n_versioning
);
3280 } else if (st
.consensus
== VS_NEW
|| st
.consensus
== VS_NEW_IN_SERIES
) {
3281 if (!have_warned_about_new_version
) {
3282 log_notice(LD_GENERAL
, "This version of Tor (%s) is newer than any "
3283 "recommended version%s, according to %d/%d version-listing "
3284 "network statuses. Versions recommended by more than %d "
3285 "authorit%s are: %s",
3287 st
.consensus
== VS_NEW_IN_SERIES
? " in its series" : "",
3288 st
.n_concurring
, st
.n_versioning
, st
.n_versioning
/2,
3289 st
.n_versioning
/2 > 1 ? "ies" : "y", recommended
);
3290 have_warned_about_new_version
= 1;
3291 control_event_general_status(LOG_WARN
, "DANGEROUS_VERSION "
3292 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
3293 VERSION
, "NEW", recommended
);
3296 log_warn(LD_GENERAL
, "Please upgrade! "
3297 "This version of Tor (%s) is %s, according to %d/%d version-"
3298 "listing network statuses. Versions recommended by "
3299 "at least %d authorit%s are: %s",
3301 st
.consensus
== VS_OLD
? "obsolete" : "not recommended",
3302 st
.n_concurring
, st
.n_versioning
, st
.n_versioning
/2,
3303 st
.n_versioning
/2 > 1 ? "ies" : "y", recommended
);
3304 have_warned_about_old_version
= 1;
3305 control_event_general_status(LOG_WARN
, "DANGEROUS_VERSION "
3306 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
3307 VERSION
, st
.consensus
== VS_OLD
? "OLD" : "UNRECOMMENDED",
3311 tor_free(recommended
);
3314 routerstatus_list_has_changed
= 0;
3317 /** Allow any network-status newer than this to influence our view of who's
3319 #define DEFAULT_RUNNING_INTERVAL (60*60)
3320 /** If possible, always allow at least this many network-statuses to influence
3321 * our view of who's running. */
3322 #define MIN_TO_INFLUENCE_RUNNING 3
3324 /** Change the is_recent field of each member of networkstatus_list so that
3325 * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
3326 * at least the MIN_TO_INFLUENCE_RUNNING most recent members are recent, and no
3327 * others are recent. Set networkstatus_list_has_changed if anything happened.
3330 networkstatus_list_update_recent(time_t now
)
3332 int n_statuses
, n_recent
, changed
, i
;
3333 char published
[ISO_TIME_LEN
+1];
3335 if (!networkstatus_list
)
3338 n_statuses
= smartlist_len(networkstatus_list
);
3341 for (i
=n_statuses
-1; i
>= 0; --i
) {
3342 networkstatus_t
*ns
= smartlist_get(networkstatus_list
, i
);
3343 trusted_dir_server_t
*ds
=
3344 router_get_trusteddirserver_by_digest(ns
->identity_digest
);
3345 const char *src
= ds
?ds
->description
:ns
->source_address
;
3346 if (n_recent
< MIN_TO_INFLUENCE_RUNNING
||
3347 ns
->published_on
+ DEFAULT_RUNNING_INTERVAL
> now
) {
3348 if (!ns
->is_recent
) {
3349 format_iso_time(published
, ns
->published_on
);
3351 "Networkstatus from %s (published %s) is now \"recent\"",
3358 if (ns
->is_recent
) {
3359 format_iso_time(published
, ns
->published_on
);
3361 "Networkstatus from %s (published %s) is "
3362 "no longer \"recent\"",
3370 networkstatus_list_has_changed
= 1;
3371 router_dir_info_changed();
3375 /** Helper for routerstatus_list_update_from_networkstatus: remember how many
3376 * authorities recommend a given descriptor digest. */
3380 } desc_digest_count_t
;
3382 /** Update our view of router status (as stored in routerstatus_list) from the
3383 * current set of network status documents (as stored in networkstatus_list).
3384 * Do nothing unless the network status list has changed since the last time
3385 * this function was called.
3388 routerstatus_list_update_from_networkstatus(time_t now
)
3390 or_options_t
*options
= get_options();
3391 int n_trusted
, n_statuses
, n_recent
= 0, n_naming
= 0;
3392 int n_listing_bad_exits
= 0, n_listing_bad_directories
= 0;
3395 networkstatus_t
**networkstatus
;
3396 smartlist_t
*result
, *changed_list
;
3398 char conflict
[DIGEST_LEN
]; /* Sentinel value */
3399 desc_digest_count_t
*digest_counts
= NULL
;
3401 /* compute which network statuses will have a vote now */
3402 networkstatus_list_update_recent(now
);
3403 router_dir_info_changed();
3405 if (!networkstatus_list_has_changed
)
3407 if (!networkstatus_list
)
3408 networkstatus_list
= smartlist_create();
3409 if (!routerstatus_list
)
3410 routerstatus_list
= smartlist_create();
3411 if (!trusted_dir_servers
)
3412 trusted_dir_servers
= smartlist_create();
3413 if (!warned_conflicts
)
3414 warned_conflicts
= smartlist_create();
3416 n_statuses
= smartlist_len(networkstatus_list
);
3417 n_trusted
= get_n_v2_authorities();
3419 if (n_statuses
<= n_trusted
/2) {
3420 /* Not enough statuses to adjust status. */
3422 "Not enough statuses to update router status list. (%d/%d)",
3423 n_statuses
, n_trusted
);
3427 log_info(LD_DIR
, "Rebuilding router status list.");
3429 index
= tor_malloc(sizeof(int)*n_statuses
);
3430 size
= tor_malloc(sizeof(int)*n_statuses
);
3431 networkstatus
= tor_malloc(sizeof(networkstatus_t
*)*n_statuses
);
3432 for (i
= 0; i
< n_statuses
; ++i
) {
3434 networkstatus
[i
] = smartlist_get(networkstatus_list
, i
);
3435 size
[i
] = smartlist_len(networkstatus
[i
]->entries
);
3436 if (networkstatus
[i
]->binds_names
)
3438 if (networkstatus
[i
]->is_recent
)
3440 if (networkstatus
[i
]->lists_bad_exits
)
3441 ++n_listing_bad_exits
;
3442 if (networkstatus
[i
]->lists_bad_directories
)
3443 ++n_listing_bad_directories
;
3446 /** Iterate over all entries in all networkstatuses, and build
3447 * name_map as a map from lc nickname to identity digest. If there
3448 * is a conflict on that nickname, map the lc nickname to conflict.
3450 name_map
= strmap_new();
3451 /* Clear the global map... */
3452 if (named_server_map
)
3453 strmap_free(named_server_map
, _tor_free
);
3454 named_server_map
= strmap_new();
3455 memset(conflict
, 0xff, sizeof(conflict
));
3456 for (i
= 0; i
< n_statuses
; ++i
) {
3457 if (!networkstatus
[i
]->binds_names
)
3459 SMARTLIST_FOREACH(networkstatus
[i
]->entries
, routerstatus_t
*, rs
,
3461 const char *other_digest
;
3464 other_digest
= strmap_get_lc(name_map
, rs
->nickname
);
3465 warned
= smartlist_string_isin(warned_conflicts
, rs
->nickname
);
3466 if (!other_digest
) {
3467 strmap_set_lc(name_map
, rs
->nickname
, rs
->identity_digest
);
3468 strmap_set_lc(named_server_map
, rs
->nickname
,
3469 tor_memdup(rs
->identity_digest
, DIGEST_LEN
));
3471 smartlist_string_remove(warned_conflicts
, rs
->nickname
);
3472 } else if (memcmp(other_digest
, rs
->identity_digest
, DIGEST_LEN
) &&
3473 other_digest
!= conflict
) {
3476 int should_warn
= options
->DirPort
&& options
->AuthoritativeDir
;
3477 char fp1
[HEX_DIGEST_LEN
+1];
3478 char fp2
[HEX_DIGEST_LEN
+1];
3479 base16_encode(fp1
, sizeof(fp1
), other_digest
, DIGEST_LEN
);
3480 base16_encode(fp2
, sizeof(fp2
), rs
->identity_digest
, DIGEST_LEN
);
3481 log_fn(should_warn
? LOG_WARN
: LOG_INFO
, LD_DIR
,
3482 "Naming authorities disagree about which key goes with %s. "
3484 rs
->nickname
, fp1
, fp2
);
3485 strmap_set_lc(name_map
, rs
->nickname
, conflict
);
3486 d
= strmap_remove_lc(named_server_map
, rs
->nickname
);
3488 smartlist_add(warned_conflicts
, tor_strdup(rs
->nickname
));
3492 smartlist_string_remove(warned_conflicts
, rs
->nickname
);
3497 result
= smartlist_create();
3498 changed_list
= smartlist_create();
3499 digest_counts
= tor_malloc_zero(sizeof(desc_digest_count_t
)*n_statuses
);
3501 /* Iterate through all of the sorted routerstatus lists in lockstep.
3503 * - For 0 <= i < n_statuses: index[i] is an index into
3504 * networkstatus[i]->entries, which has size[i] elements.
3505 * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
3506 * j < index[i1]: networkstatus[i1]->entries[j]->identity_digest <
3507 * networkstatus[i2]->entries[index[i2]]->identity_digest.
3509 * (That is, the indices are always advanced past lower digest before
3513 int n_running
=0, n_named
=0, n_valid
=0, n_listing
=0;
3514 int n_v2_dir
=0, n_fast
=0, n_stable
=0, n_exit
=0, n_guard
=0, n_bad_exit
=0;
3515 int n_bad_directory
=0;
3516 int n_version_known
=0, n_supports_begindir
=0;
3517 int n_desc_digests
=0, highest_count
=0;
3518 const char *the_name
= NULL
;
3519 local_routerstatus_t
*rs_out
, *rs_old
;
3520 routerstatus_t
*rs
, *most_recent
;
3521 networkstatus_t
*ns
;
3522 const char *lowest
= NULL
;
3524 /* Find out which of the digests appears first. */
3525 for (i
= 0; i
< n_statuses
; ++i
) {
3526 if (index
[i
] < size
[i
]) {
3527 rs
= smartlist_get(networkstatus
[i
]->entries
, index
[i
]);
3528 if (!lowest
|| memcmp(rs
->identity_digest
, lowest
, DIGEST_LEN
)<0)
3529 lowest
= rs
->identity_digest
;
3533 /* We're out of routers. Great! */
3536 /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
3537 * match "lowest" are next in order. Iterate over them, incrementing those
3538 * index[i] as we go. */
3539 for (i
= 0; i
< n_statuses
; ++i
) {
3540 if (index
[i
] >= size
[i
])
3542 ns
= networkstatus
[i
];
3543 rs
= smartlist_get(ns
->entries
, index
[i
]);
3544 if (memcmp(rs
->identity_digest
, lowest
, DIGEST_LEN
))
3546 /* At this point, we know that we're looking at a routersatus with
3547 * identity "lowest".
3551 /* Should we name this router? Only if all the names from naming
3552 * authorities match. */
3553 if (rs
->is_named
&& ns
->binds_names
) {
3555 the_name
= rs
->nickname
;
3556 if (!strcasecmp(rs
->nickname
, the_name
)) {
3558 } else if (strcmp(the_name
,"**mismatch**")) {
3559 char hd
[HEX_DIGEST_LEN
+1];
3560 base16_encode(hd
, HEX_DIGEST_LEN
+1, rs
->identity_digest
, DIGEST_LEN
);
3561 if (! smartlist_string_isin(warned_conflicts
, hd
)) {
3563 "Naming authorities disagree about nicknames for $%s "
3564 "(\"%s\" vs \"%s\")",
3565 hd
, the_name
, rs
->nickname
);
3566 smartlist_add(warned_conflicts
, tor_strdup(hd
));
3568 the_name
= "**mismatch**";
3571 /* Keep a running count of how often which descriptor digests
3573 for (j
= 0; j
< n_desc_digests
; ++j
) {
3574 if (!memcmp(rs
->descriptor_digest
,
3575 digest_counts
[j
].rs
->descriptor_digest
, DIGEST_LEN
)) {
3576 if (++digest_counts
[j
].count
> highest_count
)
3577 highest_count
= digest_counts
[j
].count
;
3581 digest_counts
[n_desc_digests
].rs
= rs
;
3582 digest_counts
[n_desc_digests
].count
= 1;
3587 /* Now tally up the easily-tallied flags. */
3590 if (rs
->is_running
&& ns
->is_recent
)
3596 if (rs
->is_possible_guard
)
3602 if (rs
->is_bad_exit
)
3604 if (rs
->is_bad_directory
)
3606 if (rs
->version_known
)
3608 if (rs
->version_supports_begindir
)
3609 ++n_supports_begindir
;
3611 /* Go over the descriptor digests and figure out which descriptor we
3614 for (i
= 0; i
< n_desc_digests
; ++i
) {
3615 /* If any digest appears twice or more, ignore those that don't.*/
3616 if (highest_count
>= 2 && digest_counts
[i
].count
< 2)
3619 digest_counts
[i
].rs
->published_on
> most_recent
->published_on
)
3620 most_recent
= digest_counts
[i
].rs
;
3622 rs_out
= tor_malloc_zero(sizeof(local_routerstatus_t
));
3623 memcpy(&rs_out
->status
, most_recent
, sizeof(routerstatus_t
));
3624 /* Copy status info about this router, if we had any before. */
3625 if ((rs_old
= router_get_combined_status_by_digest(lowest
))) {
3626 if (!memcmp(rs_out
->status
.descriptor_digest
,
3627 most_recent
->descriptor_digest
, DIGEST_LEN
)) {
3628 rs_out
->n_download_failures
= rs_old
->n_download_failures
;
3629 rs_out
->next_attempt_at
= rs_old
->next_attempt_at
;
3631 rs_out
->name_lookup_warned
= rs_old
->name_lookup_warned
;
3632 rs_out
->last_dir_503_at
= rs_old
->last_dir_503_at
;
3634 smartlist_add(result
, rs_out
);
3635 log_debug(LD_DIR
, "Router '%s' is listed by %d/%d directories, "
3636 "named by %d/%d, validated by %d/%d, and %d/%d recent "
3637 "directories think it's running.",
3638 rs_out
->status
.nickname
,
3639 n_listing
, n_statuses
, n_named
, n_naming
, n_valid
, n_statuses
,
3640 n_running
, n_recent
);
3641 rs_out
->status
.is_named
= 0;
3642 if (the_name
&& strcmp(the_name
, "**mismatch**") && n_named
> 0) {
3643 const char *d
= strmap_get_lc(name_map
, the_name
);
3644 if (d
&& d
!= conflict
)
3645 rs_out
->status
.is_named
= 1;
3646 if (smartlist_string_isin(warned_conflicts
, rs_out
->status
.nickname
))
3647 smartlist_string_remove(warned_conflicts
, rs_out
->status
.nickname
);
3649 if (rs_out
->status
.is_named
)
3650 strlcpy(rs_out
->status
.nickname
, the_name
,
3651 sizeof(rs_out
->status
.nickname
));
3652 rs_out
->status
.is_valid
= n_valid
> n_statuses
/2;
3653 rs_out
->status
.is_running
= n_running
> n_recent
/2;
3654 rs_out
->status
.is_exit
= n_exit
> n_statuses
/2;
3655 rs_out
->status
.is_fast
= n_fast
> n_statuses
/2;
3656 rs_out
->status
.is_possible_guard
= n_guard
> n_statuses
/2;
3657 rs_out
->status
.is_stable
= n_stable
> n_statuses
/2;
3658 rs_out
->status
.is_v2_dir
= n_v2_dir
> n_statuses
/2;
3659 rs_out
->status
.is_bad_exit
= n_bad_exit
> n_listing_bad_exits
/2;
3660 rs_out
->status
.is_bad_directory
=
3661 n_bad_directory
> n_listing_bad_directories
/2;
3662 rs_out
->status
.version_known
= n_version_known
> 0;
3663 rs_out
->status
.version_supports_begindir
=
3664 n_supports_begindir
> n_version_known
/2;
3665 if (!rs_old
|| memcmp(rs_old
, rs_out
, sizeof(local_routerstatus_t
)))
3666 smartlist_add(changed_list
, rs_out
);
3668 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
3669 local_routerstatus_free(rs
));
3671 smartlist_free(routerstatus_list
);
3672 routerstatus_list
= result
;
3674 tor_free(networkstatus
);
3677 tor_free(digest_counts
);
3678 strmap_free(name_map
, NULL
);
3680 networkstatus_list_has_changed
= 0;
3681 routerstatus_list_has_changed
= 1;
3683 control_event_networkstatus_changed(changed_list
);
3684 smartlist_free(changed_list
);
3687 /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
3688 * is_named, is_valid, and is_running fields according to our current
3689 * networkstatus_t documents. */
3691 routers_update_status_from_networkstatus(smartlist_t
*routers
,
3694 trusted_dir_server_t
*ds
;
3695 local_routerstatus_t
*rs
;
3696 or_options_t
*options
= get_options();
3697 int authdir
= options
->AuthoritativeDir
;
3698 int namingdir
= options
->AuthoritativeDir
&&
3699 options
->NamingAuthoritativeDir
;
3701 if (!routerstatus_list
)
3704 SMARTLIST_FOREACH(routers
, routerinfo_t
*, router
,
3706 const char *digest
= router
->cache_info
.identity_digest
;
3707 rs
= router_get_combined_status_by_digest(digest
);
3708 ds
= router_get_trusteddirserver_by_digest(digest
);
3714 router
->is_named
= rs
->status
.is_named
;
3717 /* If we're not an authdir, believe others. */
3718 router
->is_valid
= rs
->status
.is_valid
;
3719 router
->is_running
= rs
->status
.is_running
;
3720 router
->is_fast
= rs
->status
.is_fast
;
3721 router
->is_stable
= rs
->status
.is_stable
;
3722 router
->is_possible_guard
= rs
->status
.is_possible_guard
;
3723 router
->is_exit
= rs
->status
.is_exit
;
3724 router
->is_bad_exit
= rs
->status
.is_bad_exit
;
3726 if (router
->is_running
&& ds
) {
3727 ds
->n_networkstatus_failures
= 0;
3729 if (reset_failures
) {
3730 rs
->n_download_failures
= 0;
3731 rs
->next_attempt_at
= 0;
3734 router_dir_info_changed();
3737 /** For every router descriptor we are currently downloading by descriptor
3738 * digest, set result[d] to 1. */
3740 list_pending_descriptor_downloads(digestmap_t
*result
)
3742 const char *prefix
= "d/";
3743 size_t p_len
= strlen(prefix
);
3745 connection_t
**carray
;
3746 smartlist_t
*tmp
= smartlist_create();
3749 get_connection_array(&carray
, &n_conns
);
3751 for (i
= 0; i
< n_conns
; ++i
) {
3752 connection_t
*conn
= carray
[i
];
3753 if (conn
->type
== CONN_TYPE_DIR
&&
3754 conn
->purpose
== DIR_PURPOSE_FETCH_SERVERDESC
&&
3755 !conn
->marked_for_close
) {
3756 const char *resource
= TO_DIR_CONN(conn
)->requested_resource
;
3757 if (!strcmpstart(resource
, prefix
))
3758 dir_split_resource_into_fingerprints(resource
+ p_len
,
3762 SMARTLIST_FOREACH(tmp
, char *, d
,
3764 digestmap_set(result
, d
, (void*)1);
3767 smartlist_free(tmp
);
3770 /** Launch downloads for all the descriptors whose digests are listed
3771 * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
3772 * If <b>source</b> is given, download from <b>source</b>; otherwise,
3773 * download from an appropriate random directory server.
3776 initiate_descriptor_downloads(routerstatus_t
*source
,
3777 smartlist_t
*digests
,
3781 char *resource
, *cp
;
3787 if (hi
> smartlist_len(digests
))
3788 hi
= smartlist_len(digests
);
3790 r_len
= 8 + (HEX_DIGEST_LEN
+1)*n
;
3791 cp
= resource
= tor_malloc(r_len
);
3792 memcpy(cp
, "d/", 2);
3794 for (i
= lo
; i
< hi
; ++i
) {
3795 base16_encode(cp
, r_len
-(cp
-resource
),
3796 smartlist_get(digests
,i
), DIGEST_LEN
);
3797 cp
+= HEX_DIGEST_LEN
;
3800 memcpy(cp
-1, ".z", 3);
3803 /* We know which authority we want. */
3804 directory_initiate_command_routerstatus(source
,
3805 DIR_PURPOSE_FETCH_SERVERDESC
,
3806 0, /* not private */
3809 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC
,
3816 /** Clients don't download any descriptor this recent, since it will probably
3817 * not have propageted to enough caches. */
3818 #define ESTIMATED_PROPAGATION_TIME (10*60)
3820 /** Return 0 if this routerstatus is obsolete, too new, isn't
3821 * running, or otherwise not a descriptor that we would make any
3822 * use of even if we had it. Else return 1. */
3824 client_would_use_router(routerstatus_t
*rs
, time_t now
, or_options_t
*options
)
3826 if (!rs
->is_running
&& !options
->FetchUselessDescriptors
) {
3827 /* If we had this router descriptor, we wouldn't even bother using it.
3828 * But, if we want to have a complete list, fetch it anyway. */
3831 if (rs
->published_on
+ ESTIMATED_PROPAGATION_TIME
> now
) {
3832 /* Most caches probably don't have this descriptor yet. */
3838 /** Return new list of ID fingerprints for routers that we (as a client) would
3841 static smartlist_t
*
3842 router_list_client_downloadable(void)
3844 int n_downloadable
= 0;
3845 smartlist_t
*downloadable
= smartlist_create();
3846 digestmap_t
*downloading
;
3847 time_t now
= time(NULL
);
3848 /* these are just used for logging */
3849 int n_not_ready
= 0, n_in_progress
= 0, n_uptodate
= 0, n_wouldnt_use
= 0;
3850 or_options_t
*options
= get_options();
3852 if (!routerstatus_list
)
3853 return downloadable
;
3855 downloading
= digestmap_new();
3856 list_pending_descriptor_downloads(downloading
);
3858 routerstatus_list_update_from_networkstatus(now
);
3859 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
3862 if (router_get_by_descriptor_digest(rs
->status
.descriptor_digest
)) {
3863 /* We have the 'best' descriptor for this router. */
3865 } else if (!client_would_use_router(&rs
->status
, now
, options
)) {
3866 /* We wouldn't want this descriptor even if we got it. */
3868 } else if (digestmap_get(downloading
, rs
->status
.descriptor_digest
)) {
3869 /* We're downloading this one now. */
3871 } else if ((ri
= router_get_by_digest(rs
->status
.identity_digest
)) &&
3872 ri
->cache_info
.published_on
> rs
->status
.published_on
) {
3873 /* Oddly, we have a descriptor more recent than the 'best' one, but it
3874 was once best. So that's okay. */
3876 } else if (rs
->next_attempt_at
> now
) {
3877 /* We failed too recently to try again. */
3880 /* Okay, time to try it. */
3881 smartlist_add(downloadable
, rs
->status
.descriptor_digest
);
3888 "%d router descriptors are downloadable. "
3889 "%d are in progress. %d are up-to-date. "
3890 "%d are non-useful. %d failed too recently to retry.",
3891 n_downloadable
, n_in_progress
, n_uptodate
,
3892 n_wouldnt_use
, n_not_ready
);
3895 digestmap_free(downloading
, NULL
);
3896 return downloadable
;
3899 /** Initiate new router downloads as needed, using the strategy for
3900 * non-directory-servers.
3902 * We don't launch any downloads if there are fewer than MAX_DL_TO_DELAY
3903 * descriptors to get and less than MAX_CLIENT_INTERVAL_WITHOUT_REQUEST
3904 * seconds have passed.
3906 * Otherwise, we ask for all descriptors that we think are different from what
3907 * we have, and that we don't currently have an in-progress download attempt
3910 update_router_descriptor_client_downloads(time_t now
)
3912 /** Max amount of hashes to download per request.
3913 * Since squid does not like URLs >= 4096 bytes we limit it to 96.
3914 * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
3915 * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
3916 * So use 96 because it's a nice number.
3918 #define MAX_DL_PER_REQUEST 96
3919 /** Don't split our requests so finely that we are requesting fewer than
3920 * this number per server. */
3921 #define MIN_DL_PER_REQUEST 4
3922 /** To prevent a single screwy cache from confusing us by selective reply,
3923 * try to split our requests into at least this this many requests. */
3924 #define MIN_REQUESTS 3
3925 /** If we want fewer than this many descriptors, wait until we
3926 * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
3928 #define MAX_DL_TO_DELAY 16
3929 /** When directory clients have only a few servers to request, they batch
3930 * them until they have more, or until this amount of time has passed. */
3931 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
3932 smartlist_t
*downloadable
= NULL
;
3933 int should_delay
, n_downloadable
;
3934 or_options_t
*options
= get_options();
3936 if (options
->DirPort
) {
3938 "Called router_descriptor_client_downloads() on a dir mirror?");
3941 if (rep_hist_circbuilding_dormant(now
)) {
3942 log_info(LD_CIRC
, "Skipping descriptor downloads: we haven't needed "
3943 "any circuits lately.");
3947 if (networkstatus_list
&&
3948 smartlist_len(networkstatus_list
) <= get_n_v2_authorities()/2) {
3950 "Not enough networkstatus documents to launch requests.");
3954 downloadable
= router_list_client_downloadable();
3955 n_downloadable
= smartlist_len(downloadable
);
3956 if (n_downloadable
>= MAX_DL_TO_DELAY
) {
3958 "There are enough downloadable routerdescs to launch requests.");
3960 } else if (n_downloadable
== 0) {
3961 // log_debug(LD_DIR, "No routerdescs need to be downloaded.");
3964 should_delay
= (last_routerdesc_download_attempted
+
3965 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST
) > now
;
3966 if (!should_delay
) {
3967 if (last_routerdesc_download_attempted
) {
3969 "There are not many downloadable routerdescs, but we've "
3970 "been waiting long enough (%d seconds). Downloading.",
3971 (int)(now
-last_routerdesc_download_attempted
));
3974 "There are not many downloadable routerdescs, but we haven't "
3975 "tried downloading descriptors recently. Downloading.");
3980 if (! should_delay
) {
3981 int i
, n_per_request
;
3982 n_per_request
= (n_downloadable
+MIN_REQUESTS
-1) / MIN_REQUESTS
;
3983 if (n_per_request
> MAX_DL_PER_REQUEST
)
3984 n_per_request
= MAX_DL_PER_REQUEST
;
3985 if (n_per_request
< MIN_DL_PER_REQUEST
)
3986 n_per_request
= MIN_DL_PER_REQUEST
;
3989 "Launching %d request%s for %d router%s, %d at a time",
3990 (n_downloadable
+n_per_request
-1)/n_per_request
,
3991 n_downloadable
>n_per_request
?"s":"",
3992 n_downloadable
, n_downloadable
>1?"s":"", n_per_request
);
3993 smartlist_sort_digests(downloadable
);
3994 for (i
=0; i
< n_downloadable
; i
+= n_per_request
) {
3995 initiate_descriptor_downloads(NULL
, downloadable
, i
, i
+n_per_request
);
3997 last_routerdesc_download_attempted
= now
;
3999 smartlist_free(downloadable
);
4002 /** Launch downloads for router status as needed, using the strategy used by
4003 * authorities and caches: download every descriptor we don't have but would
4004 * serve, from a random authority that lists it. */
4006 update_router_descriptor_cache_downloads(time_t now
)
4008 smartlist_t
**downloadable
; /* For each authority, what can we dl from it? */
4009 smartlist_t
**download_from
; /* ... and, what will we dl from it? */
4010 digestmap_t
*map
; /* Which descs are in progress, or assigned? */
4013 or_options_t
*options
= get_options();
4016 if (!options
->DirPort
) {
4017 log_warn(LD_BUG
, "Called update_router_descriptor_cache_downloads() "
4018 "on a non-dir-mirror?");
4021 if (!networkstatus_list
|| !smartlist_len(networkstatus_list
))
4024 map
= digestmap_new();
4025 n
= smartlist_len(networkstatus_list
);
4027 downloadable
= tor_malloc_zero(sizeof(smartlist_t
*) * n
);
4028 download_from
= tor_malloc_zero(sizeof(smartlist_t
*) * n
);
4030 /* Set map[d]=1 for the digest of every descriptor that we are currently
4032 list_pending_descriptor_downloads(map
);
4034 /* For the digest of every descriptor that we don't have, and that we aren't
4035 * downloading, add d to downloadable[i] if the i'th networkstatus knows
4036 * about that descriptor, and we haven't already failed to get that
4037 * descriptor from the corresponding authority.
4040 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
4043 dl
= downloadable
[ns_sl_idx
] = smartlist_create();
4044 download_from
[ns_sl_idx
] = smartlist_create();
4045 if (ns
->published_on
+ MAX_NETWORKSTATUS_AGE
+10*60 < now
) {
4046 /* Don't download if the networkstatus is almost ancient. */
4047 /* Actually, I suspect what's happening here is that we ask
4048 * for the descriptor when we have a given networkstatus,
4049 * and then we get a newer networkstatus, and then we receive
4050 * the descriptor. Having a networkstatus actually expire is
4051 * probably a rare event, and we'll probably be happiest if
4052 * we take this clause out. -RD */
4055 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
* , rs
,
4057 if (!rs
->need_to_mirror
)
4059 if (router_get_by_descriptor_digest(rs
->descriptor_digest
)) {
4061 "Bug: We have a router descriptor, but need_to_mirror=1.");
4062 rs
->need_to_mirror
= 0;
4065 if (options
->AuthoritativeDir
&& dirserv_would_reject_router(rs
)) {
4066 rs
->need_to_mirror
= 0;
4069 if (digestmap_get(map
, rs
->descriptor_digest
)) {
4070 /* We're downloading it already. */
4073 /* We could download it from this guy. */
4074 smartlist_add(dl
, rs
->descriptor_digest
);
4080 /* At random, assign descriptors to authorities such that:
4081 * - if d is a member of some downloadable[x], d is a member of some
4082 * download_from[y]. (Everything we want to download, we try to download
4084 * - If d is a member of download_from[y], d is a member of downloadable[y].
4085 * (We only try to download descriptors from authorities who claim to have
4087 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
4088 * (We don't try to download anything from two authorities concurrently.)
4090 while (n_download
) {
4091 int which_ns
= crypto_rand_int(n
);
4092 smartlist_t
*dl
= downloadable
[which_ns
];
4095 if (!smartlist_len(dl
))
4097 idx
= crypto_rand_int(smartlist_len(dl
));
4098 d
= smartlist_get(dl
, idx
);
4099 if (! digestmap_get(map
, d
)) {
4100 smartlist_add(download_from
[which_ns
], d
);
4101 digestmap_set(map
, d
, (void*) 1);
4103 smartlist_del(dl
, idx
);
4107 /* Now, we can actually launch our requests. */
4108 for (i
=0; i
<n
; ++i
) {
4109 networkstatus_t
*ns
= smartlist_get(networkstatus_list
, i
);
4110 trusted_dir_server_t
*ds
=
4111 router_get_trusteddirserver_by_digest(ns
->identity_digest
);
4112 smartlist_t
*dl
= download_from
[i
];
4114 log_warn(LD_BUG
, "Networkstatus with no corresponding authority!");
4117 if (! smartlist_len(dl
))
4119 log_info(LD_DIR
, "Requesting %d descriptors from authority \"%s\"",
4120 smartlist_len(dl
), ds
->nickname
);
4121 for (j
=0; j
< smartlist_len(dl
); j
+= MAX_DL_PER_REQUEST
) {
4122 initiate_descriptor_downloads(&(ds
->fake_status
.status
), dl
, j
,
4123 j
+MAX_DL_PER_REQUEST
);
4127 for (i
=0; i
<n
; ++i
) {
4128 smartlist_free(download_from
[i
]);
4129 smartlist_free(downloadable
[i
]);
4131 tor_free(download_from
);
4132 tor_free(downloadable
);
4133 digestmap_free(map
,NULL
);
4136 /** Launch downloads for router status as needed. */
4138 update_router_descriptor_downloads(time_t now
)
4140 or_options_t
*options
= get_options();
4141 if (options
->DirPort
) {
4142 update_router_descriptor_cache_downloads(now
);
4144 update_router_descriptor_client_downloads(now
);
4148 /** Return the number of routerstatus_t in <b>entries</b> that we'd actually
4151 routerstatus_count_usable_entries(smartlist_t
*entries
)
4154 time_t now
= time(NULL
);
4155 or_options_t
*options
= get_options();
4156 SMARTLIST_FOREACH(entries
, routerstatus_t
*, rs
,
4157 if (client_would_use_router(rs
, now
, options
)) count
++);
4161 /** True iff, the last time we checked whether we had enough directory info
4162 * to build circuits, the answer was "yes". */
4163 static int have_min_dir_info
= 0;
4164 /** True iff enough has changed since the last time we checked whether we had
4165 * enough directory info to build circuits that our old answer can no longer
4167 static int need_to_update_have_min_dir_info
= 1;
4169 /** Return true iff we have enough networkstatus and router information to
4170 * start building circuits. Right now, this means "more than half the
4171 * networkstatus documents, and at least 1/4 of expected routers." */
4172 //XXX should consider whether we have enough exiting nodes here.
4174 router_have_minimum_dir_info(void)
4176 if (PREDICT(need_to_update_have_min_dir_info
, 0)) {
4177 update_router_have_minimum_dir_info();
4178 need_to_update_have_min_dir_info
= 0;
4180 return have_min_dir_info
;
4183 /** Called when our internal view of the directory has changed. This can be
4184 * when the authorities change, networkstatuses change, the list of routerdescs
4185 * changes, or number of running routers changes.
4188 router_dir_info_changed(void)
4190 need_to_update_have_min_dir_info
= 1;
4193 /** Change the value of have_min_dir_info, setting it true iff we have enough
4194 * network and router information to build circuits. Clear the value of
4195 * need_to_update_have_min_dir_info. */
4197 update_router_have_minimum_dir_info(void)
4199 int tot
= 0, num_running
= 0;
4200 int n_ns
, n_authorities
, res
, avg
;
4201 time_t now
= time(NULL
);
4202 if (!networkstatus_list
|| !routerlist
) {
4206 routerlist_remove_old_routers();
4207 networkstatus_list_clean(now
);
4209 n_authorities
= get_n_v2_authorities();
4210 n_ns
= smartlist_len(networkstatus_list
);
4211 if (n_ns
<=n_authorities
/2) {
4213 "We have %d of %d network statuses, and we want "
4214 "more than %d.", n_ns
, n_authorities
, n_authorities
/2);
4218 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
4219 tot
+= routerstatus_count_usable_entries(ns
->entries
));
4221 if (!routerstatus_list
)
4222 routerstatus_list
= smartlist_create();
4223 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
4225 if (rs
->status
.is_running
)
4228 res
= smartlist_len(routerlist
->routers
) >= (avg
/4) && num_running
> 2;
4230 if (res
&& !have_min_dir_info
) {
4231 log(LOG_NOTICE
, LD_DIR
,
4232 "We now have enough directory information to build circuits.");
4233 control_event_client_status(LOG_NOTICE
, "ENOUGH_DIR_INFO");
4235 if (!res
&& have_min_dir_info
) {
4236 log(LOG_NOTICE
, LD_DIR
,"Our directory information is no longer up-to-date "
4237 "enough to build circuits.%s",
4238 num_running
> 2 ? "" : " (Not enough servers seem reachable -- "
4239 "is your network connection down?)");
4240 control_event_client_status(LOG_NOTICE
, "NOT_ENOUGH_DIR_INFO");
4242 have_min_dir_info
= res
;
4245 /** Return true iff we have downloaded, or attempted to download at least
4246 * n_failures times, a network status for each authority. */
4248 have_tried_downloading_all_statuses(int n_failures
)
4250 if (!trusted_dir_servers
)
4253 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
4255 if (!ds
->is_v2_authority
)
4257 /* If we don't have the status, and we haven't failed to get the status,
4258 * we haven't tried to get the status. */
4259 if (!networkstatus_get_by_digest(ds
->digest
) &&
4260 ds
->n_networkstatus_failures
<= n_failures
)
4267 /** Reset the descriptor download failure count on all routers, so that we
4268 * can retry any long-failed routers immediately.
4271 router_reset_descriptor_download_failures(void)
4273 if (!routerstatus_list
)
4275 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
4277 rs
->n_download_failures
= 0;
4278 rs
->next_attempt_at
= 0;
4280 tor_assert(networkstatus_list
);
4281 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
4282 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
*, rs
,
4284 if (!router_get_by_descriptor_digest(rs
->descriptor_digest
))
4285 rs
->need_to_mirror
= 1;
4287 last_routerdesc_download_attempted
= 0;
4290 /** Any changes in a router descriptor's publication time larger than this are
4291 * automatically non-cosmetic. */
4292 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
4294 /** We allow uptime to vary from how much it ought to be by this much. */
4295 #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
4297 /** Return true iff the only differences between r1 and r2 are such that
4298 * would not cause a recent (post 0.1.1.6) dirserver to republish.
4301 router_differences_are_cosmetic(routerinfo_t
*r1
, routerinfo_t
*r2
)
4303 time_t r1pub
, r2pub
;
4304 int time_difference
;
4305 tor_assert(r1
&& r2
);
4307 /* r1 should be the one that was published first. */
4308 if (r1
->cache_info
.published_on
> r2
->cache_info
.published_on
) {
4309 routerinfo_t
*ri_tmp
= r2
;
4314 /* If any key fields differ, they're different. */
4315 if (strcasecmp(r1
->address
, r2
->address
) ||
4316 strcasecmp(r1
->nickname
, r2
->nickname
) ||
4317 r1
->or_port
!= r2
->or_port
||
4318 r1
->dir_port
!= r2
->dir_port
||
4319 crypto_pk_cmp_keys(r1
->onion_pkey
, r2
->onion_pkey
) ||
4320 crypto_pk_cmp_keys(r1
->identity_pkey
, r2
->identity_pkey
) ||
4321 strcasecmp(r1
->platform
, r2
->platform
) ||
4322 (r1
->contact_info
&& !r2
->contact_info
) || /* contact_info is optional */
4323 (!r1
->contact_info
&& r2
->contact_info
) ||
4324 (r1
->contact_info
&& r2
->contact_info
&&
4325 strcasecmp(r1
->contact_info
, r2
->contact_info
)) ||
4326 r1
->is_hibernating
!= r2
->is_hibernating
||
4327 r1
->has_old_dnsworkers
!= r2
->has_old_dnsworkers
||
4328 cmp_addr_policies(r1
->exit_policy
, r2
->exit_policy
))
4330 if ((r1
->declared_family
== NULL
) != (r2
->declared_family
== NULL
))
4332 if (r1
->declared_family
&& r2
->declared_family
) {
4334 if (smartlist_len(r1
->declared_family
)!=smartlist_len(r2
->declared_family
))
4336 n
= smartlist_len(r1
->declared_family
);
4337 for (i
=0; i
< n
; ++i
) {
4338 if (strcasecmp(smartlist_get(r1
->declared_family
, i
),
4339 smartlist_get(r2
->declared_family
, i
)))
4344 /* Did bandwidth change a lot? */
4345 if ((r1
->bandwidthcapacity
< r2
->bandwidthcapacity
/2) ||
4346 (r2
->bandwidthcapacity
< r1
->bandwidthcapacity
/2))
4349 /* Did more than 12 hours pass? */
4350 if (r1
->cache_info
.published_on
+ ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
4351 < r2
->cache_info
.published_on
)
4354 /* Did uptime fail to increase by approximately the amount we would think,
4355 * give or take some slop? */
4356 r1pub
= r1
->cache_info
.published_on
;
4357 r2pub
= r2
->cache_info
.published_on
;
4358 time_difference
= abs(r2
->uptime
- (r1
->uptime
+ (r2pub
- r1pub
)));
4359 if (time_difference
> ROUTER_ALLOW_UPTIME_DRIFT
&&
4360 time_difference
> r1
->uptime
* .05 &&
4361 time_difference
> r2
->uptime
* .05)
4364 /* Otherwise, the difference is cosmetic. */
4368 /** Generate networkstatus lines for a single routerstatus_t object, and
4369 * return the result in a newly allocated string. Used only by controller
4370 * interface (for now.) */
4371 /* XXXX This should eventually merge into generate_v2_networkstatus() */
4373 networkstatus_getinfo_helper_single(routerstatus_t
*rs
)
4380 char published
[ISO_TIME_LEN
+1];
4381 char ipaddr
[INET_NTOA_BUF_LEN
];
4382 char identity64
[BASE64_DIGEST_LEN
+1];
4383 char digest64
[BASE64_DIGEST_LEN
+1];
4385 format_iso_time(published
, rs
->published_on
);
4386 digest_to_base64(identity64
, rs
->identity_digest
);
4387 digest_to_base64(digest64
, rs
->descriptor_digest
);
4388 in
.s_addr
= htonl(rs
->addr
);
4389 tor_inet_ntoa(&in
, ipaddr
, sizeof(ipaddr
));
4391 f_authority
= router_digest_is_trusted_dir(rs
->identity_digest
);
4393 r
= tor_snprintf(buf
, sizeof(buf
),
4394 "r %s %s %s %s %s %d %d\n"
4395 "s%s%s%s%s%s%s%s%s%s%s\n",
4404 f_authority
?" Authority":"",
4405 rs
->is_bad_exit
?" BadExit":"",
4406 rs
->is_exit
?" Exit":"",
4407 rs
->is_fast
?" Fast":"",
4408 rs
->is_possible_guard
?" Guard":"",
4409 rs
->is_named
?" Named":"",
4410 rs
->is_stable
?" Stable":"",
4411 rs
->is_running
?" Running":"",
4412 rs
->is_valid
?" Valid":"",
4413 rs
->is_v2_dir
?" V2Dir":"");
4415 log_warn(LD_BUG
, "Not enough space in buffer.");
4417 return tor_strdup(buf
);
4420 /** If <b>question</b> is a string beginning with "ns/" in a format the
4421 * control interface expects for a GETINFO question, set *<b>answer</b> to a
4422 * newly-allocated string containing networkstatus lines for the appropriate
4423 * ORs. Return 0 on success, -1 on unrecognized question format. */
4425 getinfo_helper_networkstatus(control_connection_t
*conn
,
4426 const char *question
, char **answer
)
4428 local_routerstatus_t
*status
;
4431 if (!routerstatus_list
) {
4432 *answer
= tor_strdup("");
4436 if (!strcmp(question
, "ns/all")) {
4437 smartlist_t
*statuses
= smartlist_create();
4438 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, lrs
,
4440 routerstatus_t
*rs
= &(lrs
->status
);
4441 smartlist_add(statuses
, networkstatus_getinfo_helper_single(rs
));
4443 *answer
= smartlist_join_strings(statuses
, "", 0, NULL
);
4444 SMARTLIST_FOREACH(statuses
, char *, cp
, tor_free(cp
));
4445 smartlist_free(statuses
);
4447 } else if (!strcmpstart(question
, "ns/id/")) {
4450 if (base16_decode(d
, DIGEST_LEN
, question
+6, strlen(question
+6)))
4452 status
= router_get_combined_status_by_digest(d
);
4453 } else if (!strcmpstart(question
, "ns/name/")) {
4454 status
= router_get_combined_status_by_nickname(question
+8, 0);
4460 *answer
= networkstatus_getinfo_helper_single(&status
->status
);
4465 /** Assert that the internal representation of <b>rl</b> is
4466 * self-consistent. */
4468 routerlist_assert_ok(routerlist_t
*rl
)
4470 digestmap_iter_t
*iter
;
4472 signed_descriptor_t
*sd2
;
4475 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
4477 r2
= digestmap_get(rl
->identity_map
, r
->cache_info
.identity_digest
);
4478 tor_assert(r
== r2
);
4479 sd2
= digestmap_get(rl
->desc_digest_map
,
4480 r
->cache_info
.signed_descriptor_digest
);
4481 tor_assert(&(r
->cache_info
) == sd2
);
4482 tor_assert(r
->routerlist_index
== r_sl_idx
);
4484 SMARTLIST_FOREACH(rl
->old_routers
, signed_descriptor_t
*, sd
,
4486 r2
= digestmap_get(rl
->identity_map
, sd
->identity_digest
);
4487 tor_assert(sd
!= &(r2
->cache_info
));
4488 sd2
= digestmap_get(rl
->desc_digest_map
, sd
->signed_descriptor_digest
);
4489 tor_assert(sd
== sd2
);
4491 iter
= digestmap_iter_init(rl
->identity_map
);
4492 while (!digestmap_iter_done(iter
)) {
4496 digestmap_iter_get(iter
, &d
, &_r
);
4498 tor_assert(!memcmp(r
->cache_info
.identity_digest
, d
, DIGEST_LEN
));
4499 iter
= digestmap_iter_next(rl
->identity_map
, iter
);
4501 iter
= digestmap_iter_init(rl
->desc_digest_map
);
4502 while (!digestmap_iter_done(iter
)) {
4505 signed_descriptor_t
*sd
;
4506 digestmap_iter_get(iter
, &d
, &_sd
);
4508 tor_assert(!memcmp(sd
->signed_descriptor_digest
, d
, DIGEST_LEN
));
4509 iter
= digestmap_iter_next(rl
->desc_digest_map
, iter
);
4513 /** Allocate and return a new string representing the contact info
4514 * and platform string for <b>router</b>,
4515 * surrounded by quotes and using standard C escapes.
4517 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
4518 * thread. Also, each call invalidates the last-returned value, so don't
4519 * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
4522 esc_router_info(routerinfo_t
*router
)
4525 char *esc_contact
, *esc_platform
;
4530 esc_contact
= esc_for_log(router
->contact_info
);
4531 esc_platform
= esc_for_log(router
->platform
);
4533 len
= strlen(esc_contact
)+strlen(esc_platform
)+32;
4534 info
= tor_malloc(len
);
4535 tor_snprintf(info
, len
, "Contact %s, Platform %s", esc_contact
,
4537 tor_free(esc_contact
);
4538 tor_free(esc_platform
);