1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
6 const char routerlist_c_id
[] =
12 * maintain and access the global list of routerinfos for known
18 /****************************************************************************/
20 /* static function prototypes */
21 static routerstatus_t
*router_pick_directory_server_impl(int requireother
,
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)
122 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, NULL
);
144 if (router_set_networkstatus(s
, st
.st_mtime
, NS_FROM_CACHE
, NULL
)<0) {
145 log_warn(LD_FS
, "Couldn't load networkstatus from \"%s\"",filename
);
150 SMARTLIST_FOREACH(entries
, char *, fn
, tor_free(fn
));
151 smartlist_free(entries
);
152 networkstatus_list_clean(time(NULL
));
153 routers_update_all_from_networkstatus();
157 /* Router descriptor storage.
159 * Routerdescs are stored in a big file, named "cached-routers". As new
160 * routerdescs arrive, we append them to a journal file named
161 * "cached-routers.new".
163 * From time to time, we replace "cached-routers" with a new file containing
164 * only the live, non-superseded descriptors, and clear cached-routers.new.
166 * On startup, we read both files.
169 /** The size of the router log, in bytes. */
170 static size_t router_journal_len
= 0;
171 /** The size of the router store, in bytes. */
172 static size_t router_store_len
= 0;
173 /** Total bytes dropped since last rebuild. */
174 static size_t router_bytes_dropped
= 0;
176 /** Helper: return 1 iff the router log is so big we want to rebuild the
179 router_should_rebuild_store(void)
181 if (router_store_len
> (1<<16))
182 return (router_journal_len
> router_store_len
/ 2 ||
183 router_bytes_dropped
> router_store_len
/ 2);
185 return router_journal_len
> (1<<15);
188 /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
189 * journal; change its saved_location to SAVED_IN_JOURNAL and set its
190 * offset appropriately. */
192 router_append_to_journal(signed_descriptor_t
*desc
)
194 or_options_t
*options
= get_options();
195 size_t fname_len
= strlen(options
->DataDirectory
)+32;
196 char *fname
= tor_malloc(fname_len
);
197 const char *body
= signed_descriptor_get_body(desc
);
198 size_t len
= desc
->signed_descriptor_len
;
200 tor_snprintf(fname
, fname_len
, "%s/cached-routers.new",
201 options
->DataDirectory
);
203 tor_assert(len
== strlen(body
));
205 if (append_bytes_to_file(fname
, body
, len
, 1)) {
206 log_warn(LD_FS
, "Unable to store router descriptor");
210 desc
->saved_location
= SAVED_IN_JOURNAL
;
211 desc
->saved_offset
= router_journal_len
;
214 router_journal_len
+= len
;
219 _compare_old_routers_by_age(const void **_a
, const void **_b
)
221 const signed_descriptor_t
*r1
= *_a
, *r2
= *_b
;
222 return r1
->published_on
- r2
->published_on
;
226 _compare_routers_by_age(const void **_a
, const void **_b
)
228 const routerinfo_t
*r1
= *_a
, *r2
= *_b
;
229 return r1
->cache_info
.published_on
- r2
->cache_info
.published_on
;
232 /** If the journal is too long, or if <b>force</b> is true, then atomically
233 * replace the router store with the routers currently in our routerlist, and
234 * clear the journal. Return 0 on success, -1 on failure.
237 router_rebuild_store(int force
)
240 or_options_t
*options
;
242 smartlist_t
*chunk_list
= NULL
;
243 char *fname
= NULL
, *fname_tmp
= NULL
;
246 smartlist_t
*old_routers
, *routers
;
248 if (!force
&& !router_should_rebuild_store())
253 /* Don't save deadweight. */
254 routerlist_remove_old_routers();
256 log_info(LD_DIR
, "Rebuilding router descriptor cache");
258 options
= get_options();
259 fname_len
= strlen(options
->DataDirectory
)+32;
260 fname
= tor_malloc(fname_len
);
261 fname_tmp
= tor_malloc(fname_len
);
262 tor_snprintf(fname
, fname_len
, "%s/cached-routers", options
->DataDirectory
);
263 tor_snprintf(fname_tmp
, fname_len
, "%s/cached-routers.tmp",
264 options
->DataDirectory
);
266 chunk_list
= smartlist_create();
268 old_routers
= smartlist_create();
269 smartlist_add_all(old_routers
, routerlist
->old_routers
);
270 smartlist_sort(old_routers
, _compare_old_routers_by_age
);
271 routers
= smartlist_create();
272 smartlist_add_all(routers
, routerlist
->routers
);
273 smartlist_sort(routers
, _compare_routers_by_age
);
274 for (i
= 0; i
< 2; ++i
) {
275 /* We sort the routers by age to enhance locality on disk. */
276 smartlist_t
*lst
= (i
== 0) ? old_routers
: routers
;
277 /* Now, add the appropriate members to chunk_list */
278 SMARTLIST_FOREACH(lst
, void *, ptr
,
280 signed_descriptor_t
*sd
= (i
==0) ?
281 ((signed_descriptor_t
*)ptr
): &((routerinfo_t
*)ptr
)->cache_info
;
283 const char *body
= signed_descriptor_get_body(sd
);
285 log_warn(LD_BUG
, "Bug! No descriptor available for router.");
288 c
= tor_malloc(sizeof(sized_chunk_t
));
290 c
->len
= sd
->signed_descriptor_len
;
291 smartlist_add(chunk_list
, c
);
294 if (write_chunks_to_file(fname_tmp
, chunk_list
, 1)<0) {
295 log_warn(LD_FS
, "Error writing router store to disk.");
298 /* Our mmap is now invalid. */
299 if (routerlist
->mmap_descriptors
) {
300 tor_munmap_file(routerlist
->mmap_descriptors
);
302 if (replace_file(fname_tmp
, fname
)<0) {
303 log_warn(LD_FS
, "Error replacing old router store.");
307 routerlist
->mmap_descriptors
= tor_mmap_file(fname
);
308 if (! routerlist
->mmap_descriptors
)
309 log_warn(LD_FS
, "Unable to mmap new descriptor file at '%s'.",fname
);
312 for (i
= 0; i
< 2; ++i
) {
313 smartlist_t
*lst
= (i
== 0) ? old_routers
: routers
;
314 SMARTLIST_FOREACH(lst
, void *, ptr
,
316 signed_descriptor_t
*sd
= (i
==0) ?
317 ((signed_descriptor_t
*)ptr
): &((routerinfo_t
*)ptr
)->cache_info
;
319 sd
->saved_location
= SAVED_IN_CACHE
;
320 if (routerlist
->mmap_descriptors
) {
321 tor_free(sd
->signed_descriptor_body
); // sets it to null
322 sd
->saved_offset
= offset
;
324 offset
+= sd
->signed_descriptor_len
;
325 signed_descriptor_get_body(sd
);
329 tor_snprintf(fname
, fname_len
, "%s/cached-routers.new",
330 options
->DataDirectory
);
332 write_str_to_file(fname
, "", 1);
335 router_store_len
= len
;
336 router_journal_len
= 0;
337 router_bytes_dropped
= 0;
339 smartlist_free(old_routers
);
340 smartlist_free(routers
);
342 SMARTLIST_FOREACH(chunk_list
, sized_chunk_t
*, c
, tor_free(c
));
343 smartlist_free(chunk_list
);
347 /* Load all cached router descriptors from the store. Return 0 on success and
351 router_reload_router_list(void)
353 or_options_t
*options
= get_options();
354 size_t fname_len
= strlen(options
->DataDirectory
)+32;
355 char *fname
= tor_malloc(fname_len
), *contents
;
359 router_get_routerlist(); /* mallocs and inits it in place */
361 router_journal_len
= router_store_len
= 0;
363 tor_snprintf(fname
, fname_len
, "%s/cached-routers", options
->DataDirectory
);
365 if (routerlist
->mmap_descriptors
) /* get rid of it first */
366 tor_munmap_file(routerlist
->mmap_descriptors
);
368 routerlist
->mmap_descriptors
= tor_mmap_file(fname
);
369 if (routerlist
->mmap_descriptors
) {
370 router_store_len
= routerlist
->mmap_descriptors
->size
;
371 router_load_routers_from_string(routerlist
->mmap_descriptors
->data
,
372 SAVED_IN_CACHE
, NULL
);
375 tor_snprintf(fname
, fname_len
, "%s/cached-routers.new",
376 options
->DataDirectory
);
377 contents
= read_file_to_str(fname
, 1, NULL
);
380 router_load_routers_from_string(contents
,
381 SAVED_IN_JOURNAL
, NULL
);
387 if (router_journal_len
) {
388 /* Always clear the journal on startup.*/
389 router_rebuild_store(1);
391 /* Don't cache expired routers. (This is in an else because
392 * router_rebuild_store() also calls remove_old_routers().) */
393 routerlist_remove_old_routers();
399 /** Return a smartlist containing a list of trusted_dir_server_t * for all
400 * known trusted dirservers. Callers must not modify the list or its
404 router_get_trusted_dir_servers(void)
406 if (!trusted_dir_servers
)
407 trusted_dir_servers
= smartlist_create();
409 return trusted_dir_servers
;
412 /** Try to find a running dirserver. If there are no running dirservers
413 * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
414 * set all the authoritative ones as running again, and pick one;
415 * if there are then no dirservers at all in our routerlist,
416 * reload the routerlist and try one last time. If for_runningrouters is
417 * true, then only pick a dirserver that can answer runningrouters queries
418 * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
419 * Don't pick an authority if any non-authority is viable.
420 * Other args are as in router_pick_directory_server_impl().
423 router_pick_directory_server(int requireother
,
425 int for_v2_directory
,
426 int retry_if_no_servers
)
428 routerstatus_t
*choice
;
429 int prefer_tunnel
= get_options()->PreferTunneledDirConns
;
434 choice
= router_pick_directory_server_impl(requireother
, fascistfirewall
,
435 prefer_tunnel
, for_v2_directory
);
436 if (choice
|| !retry_if_no_servers
)
440 "No reachable router entries for dirservers. "
441 "Trying them all again.");
442 /* mark all authdirservers as up again */
443 mark_all_trusteddirservers_up();
445 choice
= router_pick_directory_server_impl(requireother
, fascistfirewall
,
446 prefer_tunnel
, for_v2_directory
);
450 log_info(LD_DIR
,"Still no %s router entries. Reloading and trying again.",
451 fascistfirewall
? "reachable" : "known");
452 if (router_reload_router_list()) {
455 /* give it one last try */
456 choice
= router_pick_directory_server_impl(requireother
, fascistfirewall
,
457 prefer_tunnel
, for_v2_directory
);
461 /** Return the trusted_dir_server_t for the directory authority whose identity
462 * key hashes to <b>digest</b>, or NULL if no such authority is known.
464 trusted_dir_server_t
*
465 router_get_trusteddirserver_by_digest(const char *digest
)
467 if (!trusted_dir_servers
)
470 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
472 if (!memcmp(ds
->digest
, digest
, DIGEST_LEN
))
479 /** Try to find a running trusted dirserver. If there are no running
480 * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
481 * set them all as running again, and try again.
482 * If <b>need_v1_authority</b> is set, return only trusted servers
483 * that are authorities for the V1 directory protocol.
484 * Other args are as in router_pick_trusteddirserver_impl().
487 router_pick_trusteddirserver(authority_type_t type
,
490 int retry_if_no_servers
)
492 routerstatus_t
*choice
;
493 int prefer_tunnel
= get_options()->PreferTunneledDirConns
;
495 choice
= router_pick_trusteddirserver_impl(type
, requireother
,
496 fascistfirewall
, prefer_tunnel
);
497 if (choice
|| !retry_if_no_servers
)
501 "No trusted dirservers are reachable. Trying them all again.");
502 mark_all_trusteddirservers_up();
503 return router_pick_trusteddirserver_impl(type
, requireother
,
504 fascistfirewall
, prefer_tunnel
);
507 /** How long do we avoid using a directory server after it's given us a 503? */
508 #define DIR_503_TIMEOUT (60*60)
510 /** Pick a random running valid directory server/mirror from our
511 * routerlist. Don't pick an authority if any non-authorities are viable.
512 * If <b>fascistfirewall</b>, make sure the router we pick is allowed
513 * by our firewall options.
514 * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
515 * choose a directory server new enough to support the v2 directory
517 * If <b>prefer_tunnel</b>, choose a directory server that is reachable
518 * and supports BEGIN_DIR cells, if possible.
519 * Try to avoid using servers that are overloaded (have returned 503
522 static routerstatus_t
*
523 router_pick_directory_server_impl(int requireother
, int fascistfirewall
,
524 int prefer_tunnel
, int for_v2_directory
)
526 routerstatus_t
*result
;
527 smartlist_t
*direct
, *tunnel
;
528 smartlist_t
*trusted_direct
, *trusted_tunnel
;
529 smartlist_t
*overloaded_direct
, *overloaded_tunnel
;
530 time_t now
= time(NULL
);
532 if (!routerstatus_list
)
535 direct
= smartlist_create();
536 tunnel
= smartlist_create();
537 trusted_direct
= smartlist_create();
538 trusted_tunnel
= smartlist_create();
539 overloaded_direct
= smartlist_create();
540 overloaded_tunnel
= smartlist_create();
542 /* Find all the running dirservers we know about. */
543 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, _local_status
,
545 routerstatus_t
*status
= &(_local_status
->status
);
547 int is_overloaded
= _local_status
->last_dir_503_at
+ DIR_503_TIMEOUT
> now
;
548 if (!status
->is_running
|| !status
->dir_port
|| !status
->is_valid
)
550 if (status
->is_bad_directory
)
552 if (requireother
&& router_digest_is_me(status
->identity_digest
))
554 is_trusted
= router_digest_is_trusted_dir(status
->identity_digest
);
555 if (for_v2_directory
&& !(status
->is_v2_dir
|| is_trusted
))
557 if (fascistfirewall
&&
559 status
->version_supports_begindir
&&
560 fascist_firewall_allows_address_or(status
->addr
, status
->or_port
))
561 smartlist_add(is_trusted
? trusted_tunnel
:
562 is_overloaded
? overloaded_tunnel
: tunnel
, status
);
563 else if (!fascistfirewall
|| (fascistfirewall
&&
564 fascist_firewall_allows_address_dir(status
->addr
,
566 smartlist_add(is_trusted
? trusted_direct
:
567 is_overloaded
? overloaded_direct
: direct
, status
);
570 if (smartlist_len(tunnel
)) {
571 result
= smartlist_choose(tunnel
);
572 } else if (smartlist_len(overloaded_tunnel
)) {
573 result
= smartlist_choose(overloaded_tunnel
);
574 } else if (smartlist_len(trusted_tunnel
)) {
575 /* FFFF We don't distinguish between trusteds and overloaded trusteds
576 * yet. Maybe one day we should. */
577 result
= smartlist_choose(trusted_tunnel
);
578 } else if (smartlist_len(direct
)) {
579 result
= smartlist_choose(direct
);
580 } else if (smartlist_len(overloaded_direct
)) {
581 result
= smartlist_choose(overloaded_direct
);
583 result
= smartlist_choose(trusted_direct
);
585 smartlist_free(direct
);
586 smartlist_free(tunnel
);
587 smartlist_free(trusted_direct
);
588 smartlist_free(trusted_tunnel
);
589 smartlist_free(overloaded_direct
);
590 smartlist_free(overloaded_tunnel
);
594 /** Choose randomly from among the trusted dirservers that are up. If
595 * <b>fascistfirewall</b>, make sure the port we pick is allowed by our
596 * firewall options. If <b>requireother</b>, it cannot be us. If
597 * <b>need_v1_authority</b>, choose a trusted authority for the v1 directory
600 static routerstatus_t
*
601 router_pick_trusteddirserver_impl(authority_type_t type
,
602 int requireother
, int fascistfirewall
,
605 smartlist_t
*direct
, *tunnel
;
606 smartlist_t
*overloaded_direct
, *overloaded_tunnel
;
607 routerinfo_t
*me
= router_get_my_routerinfo();
608 routerstatus_t
*result
;
609 time_t now
= time(NULL
);
611 direct
= smartlist_create();
612 tunnel
= smartlist_create();
613 overloaded_direct
= smartlist_create();
614 overloaded_tunnel
= smartlist_create();
616 if (!trusted_dir_servers
)
619 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, d
,
622 d
->fake_status
.last_dir_503_at
+ DIR_503_TIMEOUT
> now
;
623 if (!d
->is_running
) continue;
624 if (type
== V1_AUTHORITY
&& !d
->is_v1_authority
)
626 if (type
== V2_AUTHORITY
&& !d
->is_v2_authority
)
628 if (type
== HIDSERV_AUTHORITY
&& !d
->is_hidserv_authority
)
630 if (requireother
&& me
&& router_digest_is_me(d
->digest
))
633 if (fascistfirewall
&&
636 fascist_firewall_allows_address_or(d
->addr
, d
->or_port
))
637 smartlist_add(is_overloaded
? overloaded_tunnel
: tunnel
,
638 &d
->fake_status
.status
);
639 else if (!fascistfirewall
|| (fascistfirewall
&&
640 fascist_firewall_allows_address_dir(d
->addr
,
642 smartlist_add(is_overloaded
? overloaded_direct
: direct
,
643 &d
->fake_status
.status
);
646 if (smartlist_len(tunnel
)) {
647 result
= smartlist_choose(tunnel
);
648 } else if (smartlist_len(overloaded_tunnel
)) {
649 result
= smartlist_choose(overloaded_tunnel
);
650 } else if (smartlist_len(direct
)) {
651 result
= smartlist_choose(direct
);
653 result
= smartlist_choose(overloaded_direct
);
656 smartlist_free(direct
);
657 smartlist_free(tunnel
);
658 smartlist_free(overloaded_direct
);
659 smartlist_free(overloaded_tunnel
);
663 /** Go through and mark the authoritative dirservers as up. */
665 mark_all_trusteddirservers_up(void)
668 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
669 if (router_digest_is_trusted_dir(router
->cache_info
.identity_digest
) &&
670 router
->dir_port
> 0) {
671 router
->is_running
= 1;
674 if (trusted_dir_servers
) {
675 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, dir
,
677 local_routerstatus_t
*rs
;
679 dir
->n_networkstatus_failures
= 0;
680 dir
->fake_status
.last_dir_503_at
= 0;
681 rs
= router_get_combined_status_by_digest(dir
->digest
);
682 if (rs
&& !rs
->status
.is_running
) {
683 rs
->status
.is_running
= 1;
684 rs
->last_dir_503_at
= 0;
685 control_event_networkstatus_changed_single(rs
);
689 last_networkstatus_download_attempted
= 0;
690 router_dir_info_changed();
693 /** Reset all internal variables used to count failed downloads of network
696 router_reset_status_download_failures(void)
698 mark_all_trusteddirservers_up();
701 /** Look through the routerlist and identify routers that
702 * advertise the same /16 network address as <b>router</b>.
703 * Add each of them to <b>sl</b>.
706 routerlist_add_network_family(smartlist_t
*sl
, routerinfo_t
*router
)
708 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, r
,
711 (router
->addr
& 0xffff0000) == (r
->addr
& 0xffff0000))
712 smartlist_add(sl
, r
);
716 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
717 * This is used to make sure we don't pick siblings in a single path.
720 routerlist_add_family(smartlist_t
*sl
, routerinfo_t
*router
)
724 or_options_t
*options
= get_options();
726 /* First, add any routers with similar network addresses.
727 * XXXX012 It's possible this will be really expensive; we'll see. */
728 if (options
->EnforceDistinctSubnets
)
729 routerlist_add_network_family(sl
, router
);
731 if (!router
->declared_family
)
734 /* Add every r such that router declares familyness with r, and r
735 * declares familyhood with router. */
736 SMARTLIST_FOREACH(router
->declared_family
, const char *, n
,
738 if (!(r
= router_get_by_nickname(n
, 0)))
740 if (!r
->declared_family
)
742 SMARTLIST_FOREACH(r
->declared_family
, const char *, n2
,
744 if (router_nickname_matches(router
, n2
))
745 smartlist_add(sl
, r
);
749 /* If the user declared any families locally, honor those too. */
750 for (cl
= get_options()->NodeFamilies
; cl
; cl
= cl
->next
) {
751 if (router_nickname_is_in_list(router
, cl
->value
)) {
752 add_nickname_list_to_smartlist(sl
, cl
->value
, 0, 1, 1);
757 /** Given a (possibly NULL) comma-and-whitespace separated list of nicknames,
758 * see which nicknames in <b>list</b> name routers in our routerlist, and add
759 * the routerinfos for those routers to <b>sl</b>. If <b>must_be_running</b>,
760 * only include routers that we think are running. If <b>warn_if_down</b>,
761 * warn if some included routers aren't running. If <b>warn_if_unnamed</b>,
762 * warn if any non-Named routers are specified by nickname.
765 add_nickname_list_to_smartlist(smartlist_t
*sl
, const char *list
,
767 int warn_if_down
, int warn_if_unnamed
)
769 routerinfo_t
*router
;
770 smartlist_t
*nickname_list
;
771 int have_dir_info
= router_have_minimum_dir_info();
774 return; /* nothing to do */
777 nickname_list
= smartlist_create();
778 if (!warned_nicknames
)
779 warned_nicknames
= smartlist_create();
781 smartlist_split_string(nickname_list
, list
, ",",
782 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
784 SMARTLIST_FOREACH(nickname_list
, const char *, nick
, {
786 if (!is_legal_nickname_or_hexdigest(nick
)) {
787 log_warn(LD_CONFIG
, "Nickname '%s' is misformed; skipping", nick
);
790 router
= router_get_by_nickname(nick
, warn_if_unnamed
);
791 warned
= smartlist_string_isin(warned_nicknames
, nick
);
793 if (!must_be_running
|| router
->is_running
) {
794 smartlist_add(sl
,router
);
796 smartlist_string_remove(warned_nicknames
, nick
);
799 log_fn(warn_if_down
? LOG_WARN
: LOG_DEBUG
, LD_CONFIG
,
800 "Nickname list includes '%s' which is known but down.",nick
);
801 smartlist_add(warned_nicknames
, tor_strdup(nick
));
804 } else if (!router_get_combined_status_by_nickname(nick
,warn_if_unnamed
)) {
806 log_fn(have_dir_info
? LOG_WARN
: LOG_INFO
, LD_CONFIG
,
807 "Nickname list includes '%s' which isn't a known router.",nick
);
808 smartlist_add(warned_nicknames
, tor_strdup(nick
));
812 SMARTLIST_FOREACH(nickname_list
, char *, nick
, tor_free(nick
));
813 smartlist_free(nickname_list
);
816 /** Return 1 iff any member of the (possibly NULL) comma-separated list
817 * <b>list</b> is an acceptable nickname or hexdigest for <b>router</b>. Else
821 router_nickname_is_in_list(routerinfo_t
*router
, const char *list
)
823 smartlist_t
*nickname_list
;
827 return 0; /* definitely not */
830 nickname_list
= smartlist_create();
831 smartlist_split_string(nickname_list
, list
, ",",
832 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
833 SMARTLIST_FOREACH(nickname_list
, const char *, cp
,
834 if (router_nickname_matches(router
, cp
)) {v
=1;break;});
835 SMARTLIST_FOREACH(nickname_list
, char *, cp
, tor_free(cp
));
836 smartlist_free(nickname_list
);
840 /** Add every suitable router from our routerlist to <b>sl</b>, so that
841 * we can pick a node for a circuit.
844 router_add_running_routers_to_smartlist(smartlist_t
*sl
, int allow_invalid
,
845 int need_uptime
, int need_capacity
,
851 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
853 if (router
->is_running
&&
854 router
->purpose
== ROUTER_PURPOSE_GENERAL
&&
855 (router
->is_valid
|| allow_invalid
) &&
856 !router_is_unreliable(router
, need_uptime
,
857 need_capacity
, need_guard
)) {
858 /* If it's running, and it's suitable according to the
859 * other flags we had in mind */
860 smartlist_add(sl
, router
);
865 /** Look through the routerlist until we find a router that has my key.
868 routerlist_find_my_routerinfo(void)
873 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
875 if (router_is_me(router
))
881 /** Find a router that's up, that has this IP address, and
882 * that allows exit to this address:port, or return NULL if there
886 router_find_exact_exit_enclave(const char *address
, uint16_t port
)
891 if (!tor_inet_aton(address
, &in
))
892 return NULL
; /* it's not an IP already */
893 addr
= ntohl(in
.s_addr
);
895 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
897 if (router
->is_running
&&
898 router
->addr
== addr
&&
899 compare_addr_to_addr_policy(addr
, port
, router
->exit_policy
) ==
900 ADDR_POLICY_ACCEPTED
)
906 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
907 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
908 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
912 router_is_unreliable(routerinfo_t
*router
, int need_uptime
,
913 int need_capacity
, int need_guard
)
915 if (need_uptime
&& !router
->is_stable
)
917 if (need_capacity
&& !router
->is_fast
)
919 if (need_guard
&& !router
->is_possible_guard
)
924 /** Return the smaller of the router's configured BandwidthRate
925 * and its advertised capacity. */
927 router_get_advertised_bandwidth(routerinfo_t
*router
)
929 if (router
->bandwidthcapacity
< router
->bandwidthrate
)
930 return router
->bandwidthcapacity
;
931 return router
->bandwidthrate
;
934 #define MAX_BELIEVABLE_BANDWIDTH 1500000 /* 1.5 MB/sec */
936 /** Choose a random element of router list <b>sl</b>, weighted by
937 * the advertised bandwidth of each router.
940 routerlist_sl_choose_by_bandwidth(smartlist_t
*sl
, int for_exit
)
943 routerinfo_t
*router
;
944 uint32_t *bandwidths
;
946 uint64_t total_nonexit_bw
= 0, total_exit_bw
= 0, total_bw
= 0;
947 uint64_t rand_bw
, tmp
;
950 /* First count the total bandwidth weight, and make a list
952 bandwidths
= tor_malloc(sizeof(uint32_t)*smartlist_len(sl
));
953 for (i
= 0; i
< smartlist_len(sl
); ++i
) {
954 router
= smartlist_get(sl
, i
);
955 this_bw
= router_get_advertised_bandwidth(router
);
956 /* if they claim something huge, don't believe it */
957 if (this_bw
> MAX_BELIEVABLE_BANDWIDTH
)
958 this_bw
= MAX_BELIEVABLE_BANDWIDTH
;
959 bandwidths
[i
] = this_bw
;
961 total_exit_bw
+= this_bw
;
963 total_nonexit_bw
+= this_bw
;
965 if (!(total_exit_bw
+total_nonexit_bw
)) {
966 tor_free(bandwidths
);
967 return smartlist_choose(sl
);
971 total_bw
= total_exit_bw
+ total_nonexit_bw
;
972 } else if (total_exit_bw
< total_nonexit_bw
/ 2) {
974 total_bw
= total_nonexit_bw
;
976 uint64_t leftover
= (total_exit_bw
- total_nonexit_bw
/ 2);
977 exit_weight
= U64_TO_DBL(leftover
) /
978 U64_TO_DBL(leftover
+ total_nonexit_bw
);
979 total_bw
= total_nonexit_bw
+
980 DBL_TO_U64(exit_weight
* U64_TO_DBL(total_exit_bw
));
983 log_debug(LD_CIRC, "Total bw = "U64_FORMAT", total exit bw = "U64_FORMAT
984 ", total nonexit bw = "U64_FORMAT", exit weight = %lf "
986 U64_PRINTF_ARG(total_bw), U64_PRINTF_ARG(total_exit_bw),
987 U64_PRINTF_ARG(total_nonexit_bw), exit_weight, for_exit);
990 /* Second, choose a random value from the bandwidth weights. */
991 rand_bw
= crypto_rand_uint64(total_bw
);
992 /* Last, count through sl until we get to the element we picked */
994 for (i
=0; i
< smartlist_len(sl
); i
++) {
995 router
= smartlist_get(sl
, i
);
997 tmp
+= ((uint64_t)(bandwidths
[i
] * exit_weight
));
999 tmp
+= bandwidths
[i
];
1003 tor_free(bandwidths
);
1004 return (routerinfo_t
*)smartlist_get(sl
, i
);
1007 /** Return a random running router from the routerlist. If any node
1008 * named in <b>preferred</b> is available, pick one of those. Never
1009 * pick a node named in <b>excluded</b>, or whose routerinfo is in
1010 * <b>excludedsmartlist</b>, even if they are the only nodes
1011 * available. If <b>strict</b> is true, never pick any node besides
1012 * those in <b>preferred</b>.
1013 * If <b>need_uptime</b> is non-zero and any router has more than
1014 * a minimum uptime, return one of those.
1015 * If <b>need_capacity</b> is non-zero, weight your choice by the
1016 * advertised capacity of each router.
1018 * DOCDOC allow_invalid, need_guard, weight_for_exit
1021 router_choose_random_node(const char *preferred
,
1022 const char *excluded
,
1023 smartlist_t
*excludedsmartlist
,
1024 int need_uptime
, int need_capacity
,
1026 int allow_invalid
, int strict
,
1027 int weight_for_exit
)
1029 smartlist_t
*sl
, *excludednodes
;
1030 routerinfo_t
*choice
= NULL
;
1032 excludednodes
= smartlist_create();
1033 add_nickname_list_to_smartlist(excludednodes
,excluded
,0,0,1);
1035 /* Try the preferred nodes first. Ignore need_uptime and need_capacity
1036 * and need_guard, since the user explicitly asked for these nodes. */
1038 sl
= smartlist_create();
1039 add_nickname_list_to_smartlist(sl
,preferred
,1,1,1);
1040 smartlist_subtract(sl
,excludednodes
);
1041 if (excludedsmartlist
)
1042 smartlist_subtract(sl
,excludedsmartlist
);
1043 choice
= smartlist_choose(sl
);
1046 if (!choice
&& !strict
) {
1047 /* Then give up on our preferred choices: any node
1048 * will do that has the required attributes. */
1049 sl
= smartlist_create();
1050 router_add_running_routers_to_smartlist(sl
, allow_invalid
,
1051 need_uptime
, need_capacity
,
1053 smartlist_subtract(sl
,excludednodes
);
1054 if (excludedsmartlist
)
1055 smartlist_subtract(sl
,excludedsmartlist
);
1058 choice
= routerlist_sl_choose_by_bandwidth(sl
, weight_for_exit
);
1060 choice
= smartlist_choose(sl
);
1063 if (!choice
&& (need_uptime
|| need_capacity
|| need_guard
)) {
1064 /* try once more -- recurse but with fewer restrictions. */
1066 "We couldn't find any live%s%s%s routers; falling back "
1067 "to list of all routers.",
1068 need_capacity
?", fast":"",
1069 need_uptime
?", stable":"",
1070 need_guard
?", guard":"");
1071 choice
= router_choose_random_node(
1072 NULL
, excluded
, excludedsmartlist
,
1073 0, 0, 0, allow_invalid
, 0, weight_for_exit
);
1076 smartlist_free(excludednodes
);
1079 "No available nodes when trying to choose node. Failing.");
1083 /** Return true iff the digest of <b>router</b>'s identity key,
1084 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
1085 * optionally prefixed with a single dollar sign). Return false if
1086 * <b>hexdigest</b> is malformed, or it doesn't match. */
1088 router_hex_digest_matches(routerinfo_t
*router
, const char *hexdigest
)
1090 char digest
[DIGEST_LEN
];
1092 tor_assert(hexdigest
);
1093 if (hexdigest
[0] == '$')
1096 len
= strlen(hexdigest
);
1097 if (len
< HEX_DIGEST_LEN
)
1099 else if (len
> HEX_DIGEST_LEN
&&
1100 (hexdigest
[HEX_DIGEST_LEN
] == '=' ||
1101 hexdigest
[HEX_DIGEST_LEN
] == '~')) {
1102 if (strcasecmp(hexdigest
+HEX_DIGEST_LEN
+1, router
->nickname
))
1104 if (hexdigest
[HEX_DIGEST_LEN
] == '=' && !router
->is_named
)
1108 if (base16_decode(digest
, DIGEST_LEN
, hexdigest
, HEX_DIGEST_LEN
)<0)
1110 return (!memcmp(digest
, router
->cache_info
.identity_digest
, DIGEST_LEN
));
1113 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
1114 * (case-insensitive), or if <b>router's</b> identity key digest
1115 * matches a hexadecimal value stored in <b>nickname</b>. Return
1116 * false otherwise. */
1118 router_nickname_matches(routerinfo_t
*router
, const char *nickname
)
1120 if (nickname
[0]!='$' && !strcasecmp(router
->nickname
, nickname
))
1122 return router_hex_digest_matches(router
, nickname
);
1125 /** Return the router in our routerlist whose (case-insensitive)
1126 * nickname or (case-sensitive) hexadecimal key digest is
1127 * <b>nickname</b>. Return NULL if no such router is known.
1130 router_get_by_nickname(const char *nickname
, int warn_if_unnamed
)
1133 char digest
[DIGEST_LEN
];
1134 routerinfo_t
*best_match
=NULL
;
1136 char *named_digest
= NULL
;
1138 tor_assert(nickname
);
1141 if (nickname
[0] == '$')
1142 return router_get_by_hexdigest(nickname
);
1143 if (!strcasecmp(nickname
, UNNAMED_ROUTER_NICKNAME
))
1145 if (server_mode(get_options()) &&
1146 !strcasecmp(nickname
, get_options()->Nickname
))
1147 return router_get_my_routerinfo();
1149 maybedigest
= (strlen(nickname
) >= HEX_DIGEST_LEN
) &&
1150 (base16_decode(digest
,DIGEST_LEN
,nickname
,HEX_DIGEST_LEN
) == 0);
1152 if (named_server_map
&&
1153 (named_digest
= strmap_get_lc(named_server_map
, nickname
))) {
1154 return digestmap_get(routerlist
->identity_map
, named_digest
);
1157 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1159 if (!strcasecmp(router
->nickname
, nickname
)) {
1161 if (n_matches
<= 1 || router
->is_running
)
1162 best_match
= router
;
1163 } else if (maybedigest
&&
1164 !memcmp(digest
, router
->cache_info
.identity_digest
, DIGEST_LEN
)
1166 if (router_hex_digest_matches(router
, nickname
))
1169 best_match
= router
; // XXXX NM not exactly right.
1174 if (warn_if_unnamed
&& n_matches
> 1) {
1175 smartlist_t
*fps
= smartlist_create();
1176 int any_unwarned
= 0;
1177 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1179 local_routerstatus_t
*rs
;
1182 char fp
[HEX_DIGEST_LEN
+1];
1183 if (strcasecmp(router
->nickname
, nickname
))
1185 rs
= router_get_combined_status_by_digest(
1186 router
->cache_info
.identity_digest
);
1187 if (rs
&& !rs
->name_lookup_warned
) {
1188 rs
->name_lookup_warned
= 1;
1191 base16_encode(fp
, sizeof(fp
),
1192 router
->cache_info
.identity_digest
, DIGEST_LEN
);
1193 dlen
= 32 + HEX_DIGEST_LEN
+ strlen(router
->address
);
1194 desc
= tor_malloc(dlen
);
1195 tor_snprintf(desc
, dlen
, "\"$%s\" for the one at %s:%d",
1196 fp
, router
->address
, router
->or_port
);
1197 smartlist_add(fps
, desc
);
1200 char *alternatives
= smartlist_join_strings(fps
, "; ",0,NULL
);
1202 "There are multiple matches for the nickname \"%s\","
1203 " but none is listed as named by the directory authorities. "
1204 "Choosing one arbitrarily. If you meant one in particular, "
1205 "you should say %s.", nickname
, alternatives
);
1206 tor_free(alternatives
);
1208 SMARTLIST_FOREACH(fps
, char *, cp
, tor_free(cp
));
1209 smartlist_free(fps
);
1210 } else if (warn_if_unnamed
) {
1211 local_routerstatus_t
*rs
= router_get_combined_status_by_digest(
1212 best_match
->cache_info
.identity_digest
);
1213 if (rs
&& !rs
->name_lookup_warned
) {
1214 char fp
[HEX_DIGEST_LEN
+1];
1215 base16_encode(fp
, sizeof(fp
),
1216 best_match
->cache_info
.identity_digest
, DIGEST_LEN
);
1217 log_warn(LD_CONFIG
, "You specified a server \"%s\" by name, but the "
1218 "directory authorities do not have a binding for this nickname. "
1219 "To make sure you get the same server in the future, refer to "
1220 "it by key, as \"$%s\".", nickname
, fp
);
1221 rs
->name_lookup_warned
= 1;
1230 /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
1231 * return 1. If we do, ask tor_version_as_new_as() for the answer.
1234 router_digest_version_as_new_as(const char *digest
, const char *cutoff
)
1236 routerinfo_t
*router
= router_get_by_digest(digest
);
1239 return tor_version_as_new_as(router
->platform
, cutoff
);
1242 /** Return true iff <b>digest</b> is the digest of the identity key of
1243 * a trusted directory. */
1245 router_digest_is_trusted_dir(const char *digest
)
1247 if (!trusted_dir_servers
)
1249 if (get_options()->AuthoritativeDir
&&
1250 router_digest_is_me(digest
))
1252 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
1253 if (!memcmp(digest
, ent
->digest
, DIGEST_LEN
)) return 1);
1257 /** Return the router in our routerlist whose hexadecimal key digest
1258 * is <b>hexdigest</b>. Return NULL if no such router is known. */
1260 router_get_by_hexdigest(const char *hexdigest
)
1262 char digest
[DIGEST_LEN
];
1266 tor_assert(hexdigest
);
1269 if (hexdigest
[0]=='$')
1271 len
= strlen(hexdigest
);
1272 if (len
< HEX_DIGEST_LEN
||
1273 base16_decode(digest
,DIGEST_LEN
,hexdigest
,HEX_DIGEST_LEN
) < 0)
1276 ri
= router_get_by_digest(digest
);
1278 if (len
> HEX_DIGEST_LEN
) {
1279 if (hexdigest
[HEX_DIGEST_LEN
] == '=') {
1280 if (strcasecmp(ri
->nickname
, hexdigest
+HEX_DIGEST_LEN
+1) ||
1283 } else if (hexdigest
[HEX_DIGEST_LEN
] == '~') {
1284 if (strcasecmp(ri
->nickname
, hexdigest
+HEX_DIGEST_LEN
+1))
1294 /** Return the router in our routerlist whose 20-byte key digest
1295 * is <b>digest</b>. Return NULL if no such router is known. */
1297 router_get_by_digest(const char *digest
)
1301 if (!routerlist
) return NULL
;
1303 // routerlist_assert_ok(routerlist);
1305 return digestmap_get(routerlist
->identity_map
, digest
);
1308 /** Return the router in our routerlist whose 20-byte descriptor
1309 * is <b>digest</b>. Return NULL if no such router is known. */
1310 signed_descriptor_t
*
1311 router_get_by_descriptor_digest(const char *digest
)
1315 if (!routerlist
) return NULL
;
1317 return digestmap_get(routerlist
->desc_digest_map
, digest
);
1320 /** Return a pointer to the signed textual representation of a descriptor.
1321 * The returned string is not guaranteed to be NUL-terminated: the string's
1322 * length will be in desc-\>signed_descriptor_len. */
1324 signed_descriptor_get_body(signed_descriptor_t
*desc
)
1327 size_t len
= desc
->signed_descriptor_len
;
1328 tor_assert(len
> 32);
1329 if (desc
->saved_location
== SAVED_IN_CACHE
&& routerlist
&&
1330 routerlist
->mmap_descriptors
) {
1331 tor_assert(desc
->saved_offset
+ len
<= routerlist
->mmap_descriptors
->size
);
1332 r
= routerlist
->mmap_descriptors
->data
+ desc
->saved_offset
;
1334 r
= desc
->signed_descriptor_body
;
1337 tor_assert(!memcmp("router ", r
, 7));
1339 tor_assert(!memcmp("\n-----END SIGNATURE-----\n",
1346 /** Return the current list of all known routers. */
1348 router_get_routerlist(void)
1351 routerlist
= tor_malloc_zero(sizeof(routerlist_t
));
1352 routerlist
->routers
= smartlist_create();
1353 routerlist
->old_routers
= smartlist_create();
1354 routerlist
->identity_map
= digestmap_new();
1355 routerlist
->desc_digest_map
= digestmap_new();
1360 /** Free all storage held by <b>router</b>. */
1362 routerinfo_free(routerinfo_t
*router
)
1367 tor_free(router
->cache_info
.signed_descriptor_body
);
1368 tor_free(router
->address
);
1369 tor_free(router
->nickname
);
1370 tor_free(router
->platform
);
1371 tor_free(router
->contact_info
);
1372 if (router
->onion_pkey
)
1373 crypto_free_pk_env(router
->onion_pkey
);
1374 if (router
->identity_pkey
)
1375 crypto_free_pk_env(router
->identity_pkey
);
1376 if (router
->declared_family
) {
1377 SMARTLIST_FOREACH(router
->declared_family
, char *, s
, tor_free(s
));
1378 smartlist_free(router
->declared_family
);
1380 addr_policy_free(router
->exit_policy
);
1384 /** Release storage held by <b>sd</b>. */
1386 signed_descriptor_free(signed_descriptor_t
*sd
)
1388 tor_free(sd
->signed_descriptor_body
);
1392 /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
1394 static signed_descriptor_t
*
1395 signed_descriptor_from_routerinfo(routerinfo_t
*ri
)
1397 signed_descriptor_t
*sd
= tor_malloc_zero(sizeof(signed_descriptor_t
));
1398 memcpy(sd
, &(ri
->cache_info
), sizeof(signed_descriptor_t
));
1399 ri
->cache_info
.signed_descriptor_body
= NULL
;
1400 routerinfo_free(ri
);
1404 /** Free all storage held by a routerlist <b>rl</b> */
1406 routerlist_free(routerlist_t
*rl
)
1409 digestmap_free(rl
->identity_map
, NULL
);
1410 digestmap_free(rl
->desc_digest_map
, NULL
);
1411 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
1412 routerinfo_free(r
));
1413 SMARTLIST_FOREACH(rl
->old_routers
, signed_descriptor_t
*, sd
,
1414 signed_descriptor_free(sd
));
1415 smartlist_free(rl
->routers
);
1416 smartlist_free(rl
->old_routers
);
1417 if (routerlist
->mmap_descriptors
)
1418 tor_munmap_file(routerlist
->mmap_descriptors
);
1421 router_dir_info_changed();
1425 dump_routerlist_mem_usage(int severity
)
1427 uint64_t livedescs
= 0;
1428 uint64_t olddescs
= 0;
1431 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, r
,
1432 livedescs
+= r
->cache_info
.signed_descriptor_len
);
1433 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
,
1434 olddescs
+= sd
->signed_descriptor_len
);
1436 log(severity
, LD_GENERAL
,
1437 "In %d live descriptors: "U64_FORMAT
" bytes. "
1438 "In %d old descriptors: "U64_FORMAT
" bytes.",
1439 smartlist_len(routerlist
->routers
), U64_PRINTF_ARG(livedescs
),
1440 smartlist_len(routerlist
->old_routers
), U64_PRINTF_ARG(olddescs
));
1443 /** Return the greatest number of routerdescs we'll hold for any given router.
1446 max_descriptors_per_router(void)
1448 int n_authorities
= get_n_v2_authorities();
1449 return (n_authorities
< 5) ? 5 : n_authorities
;
1452 /** Return non-zero if we have a lot of extra descriptors in our
1453 * routerlist, and should get rid of some of them. Else return 0.
1455 * We should be careful to not return true too eagerly, since we
1456 * could churn. By using "+1" below, we make sure this function
1457 * only returns true at most every smartlist_len(rl-\>routers)
1461 routerlist_is_overfull(routerlist_t
*rl
)
1463 return smartlist_len(rl
->old_routers
) >
1464 smartlist_len(rl
->routers
)*(max_descriptors_per_router()+1);
1468 _routerlist_find_elt(smartlist_t
*sl
, void *ri
, int idx
)
1470 if (idx
< 0 || smartlist_get(sl
, idx
) != ri
) {
1472 SMARTLIST_FOREACH(sl
, routerinfo_t
*, r
,
1481 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1484 routerlist_insert(routerlist_t
*rl
, routerinfo_t
*ri
)
1486 digestmap_set(rl
->identity_map
, ri
->cache_info
.identity_digest
, ri
);
1487 digestmap_set(rl
->desc_digest_map
, ri
->cache_info
.signed_descriptor_digest
,
1489 smartlist_add(rl
->routers
, ri
);
1490 ri
->routerlist_index
= smartlist_len(rl
->routers
) - 1;
1491 router_dir_info_changed();
1492 // routerlist_assert_ok(rl);
1496 routerlist_insert_old(routerlist_t
*rl
, routerinfo_t
*ri
)
1498 if (get_options()->DirPort
&&
1499 !digestmap_get(rl
->desc_digest_map
,
1500 ri
->cache_info
.signed_descriptor_digest
)) {
1501 signed_descriptor_t
*sd
= signed_descriptor_from_routerinfo(ri
);
1502 digestmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
1503 smartlist_add(rl
->old_routers
, sd
);
1505 routerinfo_free(ri
);
1507 // routerlist_assert_ok(rl);
1510 /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
1511 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl->routers,
1512 * idx) == ri, we don't need to do a linear search over the list to decide
1513 * which to remove. We fill the gap in rl->routers with a later element in
1514 * the list, if any exists. <b>ri</b> is freed. */
1516 routerlist_remove(routerlist_t
*rl
, routerinfo_t
*ri
, int idx
, int make_old
)
1518 routerinfo_t
*ri_tmp
;
1519 idx
= _routerlist_find_elt(rl
->routers
, ri
, idx
);
1522 ri
->routerlist_index
= -1;
1523 smartlist_del(rl
->routers
, idx
);
1524 if (idx
< smartlist_len(rl
->routers
)) {
1525 routerinfo_t
*r
= smartlist_get(rl
->routers
, idx
);
1526 r
->routerlist_index
= idx
;
1529 ri_tmp
= digestmap_remove(rl
->identity_map
, ri
->cache_info
.identity_digest
);
1530 router_dir_info_changed();
1531 tor_assert(ri_tmp
== ri
);
1532 if (make_old
&& get_options()->DirPort
) {
1533 signed_descriptor_t
*sd
;
1534 sd
= signed_descriptor_from_routerinfo(ri
);
1535 smartlist_add(rl
->old_routers
, sd
);
1536 digestmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
1538 ri_tmp
= digestmap_remove(rl
->desc_digest_map
,
1539 ri
->cache_info
.signed_descriptor_digest
);
1540 tor_assert(ri_tmp
== ri
);
1541 router_bytes_dropped
+= ri
->cache_info
.signed_descriptor_len
;
1542 routerinfo_free(ri
);
1544 // routerlist_assert_ok(rl);
1548 routerlist_remove_old(routerlist_t
*rl
, signed_descriptor_t
*sd
, int idx
)
1550 signed_descriptor_t
*sd_tmp
;
1551 idx
= _routerlist_find_elt(rl
->old_routers
, sd
, idx
);
1554 smartlist_del(rl
->old_routers
, idx
);
1555 sd_tmp
= digestmap_remove(rl
->desc_digest_map
,
1556 sd
->signed_descriptor_digest
);
1557 tor_assert(sd_tmp
== sd
);
1558 router_bytes_dropped
+= sd
->signed_descriptor_len
;
1559 signed_descriptor_free(sd
);
1560 // routerlist_assert_ok(rl);
1563 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
1564 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
1565 * smartlist_get(rl->routers, idx) == ri, we don't need to do a linear
1566 * search over the list to decide which to remove. We put ri_new in the same
1567 * index as ri_old, if possible. ri is freed as appropriate. */
1569 routerlist_replace(routerlist_t
*rl
, routerinfo_t
*ri_old
,
1570 routerinfo_t
*ri_new
, int idx
, int make_old
)
1572 tor_assert(ri_old
!= ri_new
);
1573 idx
= _routerlist_find_elt(rl
->routers
, ri_old
, idx
);
1574 router_dir_info_changed();
1576 smartlist_set(rl
->routers
, idx
, ri_new
);
1577 ri_old
->routerlist_index
= -1;
1578 ri_new
->routerlist_index
= idx
;
1580 log_warn(LD_BUG
, "Appending entry from routerlist_replace.");
1581 routerlist_insert(rl
, ri_new
);
1584 if (memcmp(ri_old
->cache_info
.identity_digest
,
1585 ri_new
->cache_info
.identity_digest
, DIGEST_LEN
)) {
1586 /* digests don't match; digestmap_set won't replace */
1587 digestmap_remove(rl
->identity_map
, ri_old
->cache_info
.identity_digest
);
1589 digestmap_set(rl
->identity_map
, ri_new
->cache_info
.identity_digest
, ri_new
);
1590 digestmap_set(rl
->desc_digest_map
,
1591 ri_new
->cache_info
.signed_descriptor_digest
, &(ri_new
->cache_info
));
1593 if (make_old
&& get_options()->DirPort
) {
1594 signed_descriptor_t
*sd
= signed_descriptor_from_routerinfo(ri_old
);
1595 smartlist_add(rl
->old_routers
, sd
);
1596 digestmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
1598 if (memcmp(ri_old
->cache_info
.signed_descriptor_digest
,
1599 ri_new
->cache_info
.signed_descriptor_digest
,
1601 /* digests don't match; digestmap_set didn't replace */
1602 digestmap_remove(rl
->desc_digest_map
,
1603 ri_old
->cache_info
.signed_descriptor_digest
);
1605 routerinfo_free(ri_old
);
1607 // routerlist_assert_ok(rl);
1610 /** Free all memory held by the routerlist module. */
1612 routerlist_free_all(void)
1615 routerlist_free(routerlist
);
1617 if (warned_nicknames
) {
1618 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
1619 smartlist_free(warned_nicknames
);
1620 warned_nicknames
= NULL
;
1622 if (warned_conflicts
) {
1623 SMARTLIST_FOREACH(warned_conflicts
, char *, cp
, tor_free(cp
));
1624 smartlist_free(warned_conflicts
);
1625 warned_conflicts
= NULL
;
1627 if (trusted_dir_servers
) {
1628 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
1629 trusted_dir_server_free(ds
));
1630 smartlist_free(trusted_dir_servers
);
1631 trusted_dir_servers
= NULL
;
1633 if (networkstatus_list
) {
1634 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
1635 networkstatus_free(ns
));
1636 smartlist_free(networkstatus_list
);
1637 networkstatus_list
= NULL
;
1639 if (routerstatus_list
) {
1640 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
1641 local_routerstatus_free(rs
));
1642 smartlist_free(routerstatus_list
);
1643 routerstatus_list
= NULL
;
1645 if (named_server_map
) {
1646 strmap_free(named_server_map
, _tor_free
);
1650 /** Free all storage held by the routerstatus object <b>rs</b>. */
1652 routerstatus_free(routerstatus_t
*rs
)
1657 /** Free all storage held by the local_routerstatus object <b>rs</b>. */
1659 local_routerstatus_free(local_routerstatus_t
*rs
)
1664 /** Free all storage held by the networkstatus object <b>ns</b>. */
1666 networkstatus_free(networkstatus_t
*ns
)
1668 tor_free(ns
->source_address
);
1669 tor_free(ns
->contact
);
1670 if (ns
->signing_key
)
1671 crypto_free_pk_env(ns
->signing_key
);
1672 tor_free(ns
->client_versions
);
1673 tor_free(ns
->server_versions
);
1675 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
*, rs
,
1676 routerstatus_free(rs
));
1677 smartlist_free(ns
->entries
);
1682 /** Forget that we have issued any router-related warnings, so that we'll
1683 * warn again if we see the same errors. */
1685 routerlist_reset_warnings(void)
1687 if (!warned_nicknames
)
1688 warned_nicknames
= smartlist_create();
1689 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
1690 smartlist_clear(warned_nicknames
); /* now the list is empty. */
1692 if (!warned_conflicts
)
1693 warned_conflicts
= smartlist_create();
1694 SMARTLIST_FOREACH(warned_conflicts
, char *, cp
, tor_free(cp
));
1695 smartlist_clear(warned_conflicts
); /* now the list is empty. */
1697 if (!routerstatus_list
)
1698 routerstatus_list
= smartlist_create();
1699 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
1700 rs
->name_lookup_warned
= 0);
1702 have_warned_about_invalid_status
= 0;
1703 have_warned_about_old_version
= 0;
1704 have_warned_about_new_version
= 0;
1707 /** Mark the router with ID <b>digest</b> as running or non-running
1708 * in our routerlist. */
1710 router_set_status(const char *digest
, int up
)
1712 routerinfo_t
*router
;
1713 local_routerstatus_t
*status
;
1716 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, d
,
1717 if (!memcmp(d
->digest
, digest
, DIGEST_LEN
))
1718 d
->is_running
= up
);
1720 router
= router_get_by_digest(digest
);
1722 log_debug(LD_DIR
,"Marking router '%s' as %s.",
1723 router
->nickname
, up
? "up" : "down");
1724 if (!up
&& router_is_me(router
) && !we_are_hibernating())
1725 log_warn(LD_NET
, "We just marked ourself as down. Are your external "
1726 "addresses reachable?");
1727 router
->is_running
= up
;
1729 status
= router_get_combined_status_by_digest(digest
);
1730 if (status
&& status
->status
.is_running
!= up
) {
1731 status
->status
.is_running
= up
;
1732 control_event_networkstatus_changed_single(status
);
1734 router_dir_info_changed();
1737 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
1738 * older entries (if any) with the same key. Note: Callers should not hold
1739 * their pointers to <b>router</b> if this function fails; <b>router</b>
1740 * will either be inserted into the routerlist or freed.
1742 * Returns >= 0 if the router was added; less than 0 if it was not.
1744 * If we're returning non-zero, then assign to *<b>msg</b> a static string
1745 * describing the reason for not liking the routerinfo.
1747 * If the return value is less than -1, there was a problem with the
1748 * routerinfo. If the return value is equal to -1, then the routerinfo was
1749 * fine, but out-of-date. If the return value is equal to 1, the
1750 * routerinfo was accepted, but we should notify the generator of the
1751 * descriptor using the message *<b>msg</b>.
1753 * If <b>from_cache</b>, this descriptor came from our disk cache. If
1754 * <b>from_fetch</b>, we received it in response to a request we made.
1755 * (If both are false, that means it was uploaded to us as an auth dir
1756 * server or via the controller.)
1758 * This function should be called *after*
1759 * routers_update_status_from_networkstatus; subsequently, you should call
1760 * router_rebuild_store and control_event_descriptors_changed.
1763 router_add_to_routerlist(routerinfo_t
*router
, const char **msg
,
1764 int from_cache
, int from_fetch
)
1766 const char *id_digest
;
1767 int authdir
= get_options()->AuthoritativeDir
;
1768 int authdir_believes_valid
= 0;
1769 routerinfo_t
*old_router
;
1774 router_get_routerlist();
1775 if (!networkstatus_list
)
1776 networkstatus_list
= smartlist_create();
1778 id_digest
= router
->cache_info
.identity_digest
;
1780 /* Make sure that we haven't already got this exact descriptor. */
1781 if (digestmap_get(routerlist
->desc_digest_map
,
1782 router
->cache_info
.signed_descriptor_digest
)) {
1784 "Dropping descriptor that we already have for router '%s'",
1786 *msg
= "Router descriptor was not new.";
1787 routerinfo_free(router
);
1791 if (routerlist_is_overfull(routerlist
))
1792 routerlist_remove_old_routers();
1795 if (authdir_wants_to_reject_router(router
, msg
,
1796 !from_cache
&& !from_fetch
)) {
1798 routerinfo_free(router
);
1801 authdir_believes_valid
= router
->is_valid
;
1802 } else if (from_fetch
) {
1803 /* Only check the descriptor digest against the network statuses when
1804 * we are receiving in response to a fetch. */
1805 if (!signed_desc_digest_is_recognized(&router
->cache_info
)) {
1806 log_warn(LD_DIR
, "Dropping unrecognized descriptor for router '%s'",
1808 *msg
= "Router descriptor is not referenced by any network-status.";
1809 routerinfo_free(router
);
1814 /* We no longer need a router with this descriptor digest. */
1815 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
1817 routerstatus_t
*rs
=
1818 networkstatus_find_entry(ns
, router
->cache_info
.identity_digest
);
1819 if (rs
&& !memcmp(rs
->descriptor_digest
,
1820 router
->cache_info
.signed_descriptor_digest
,
1822 rs
->need_to_mirror
= 0;
1825 /* If we have a router with the same identity key, choose the newer one. */
1826 old_router
= digestmap_get(routerlist
->identity_map
,
1827 router
->cache_info
.identity_digest
);
1829 int pos
= old_router
->routerlist_index
;
1830 tor_assert(smartlist_get(routerlist
->routers
, pos
) == old_router
);
1832 if (router
->cache_info
.published_on
<=
1833 old_router
->cache_info
.published_on
) {
1834 /* Same key, but old */
1835 log_debug(LD_DIR
, "Skipping not-new descriptor for router '%s'",
1837 /* Only journal this desc if we'll be serving it. */
1838 if (!from_cache
&& get_options()->DirPort
)
1839 router_append_to_journal(&router
->cache_info
);
1840 routerlist_insert_old(routerlist
, router
);
1841 *msg
= "Router descriptor was not new.";
1844 /* Same key, new. */
1845 int unreachable
= 0;
1846 log_debug(LD_DIR
, "Replacing entry for router '%s/%s' [%s]",
1847 router
->nickname
, old_router
->nickname
,
1848 hex_str(id_digest
,DIGEST_LEN
));
1849 if (router
->addr
== old_router
->addr
&&
1850 router
->or_port
== old_router
->or_port
) {
1851 /* these carry over when the address and orport are unchanged.*/
1852 router
->last_reachable
= old_router
->last_reachable
;
1853 router
->testing_since
= old_router
->testing_since
;
1854 router
->num_unreachable_notifications
=
1855 old_router
->num_unreachable_notifications
;
1857 if (authdir
&& !from_cache
&& !from_fetch
&&
1858 router_have_minimum_dir_info() &&
1859 dirserv_thinks_router_is_blatantly_unreachable(router
,
1861 if (router
->num_unreachable_notifications
>= 3) {
1863 log_notice(LD_DIR
, "Notifying server '%s' that it's unreachable. "
1864 "(ContactInfo '%s', platform '%s').",
1866 router
->contact_info
? router
->contact_info
: "",
1867 router
->platform
? router
->platform
: "");
1869 log_info(LD_DIR
,"'%s' may be unreachable -- the %d previous "
1870 "descriptors were thought to be unreachable.",
1871 router
->nickname
, router
->num_unreachable_notifications
);
1872 router
->num_unreachable_notifications
++;
1875 routerlist_replace(routerlist
, old_router
, router
, pos
, 1);
1877 router_append_to_journal(&router
->cache_info
);
1879 directory_set_dirty();
1880 *msg
= unreachable
? "Dirserver believes your ORPort is unreachable" :
1881 authdir_believes_valid
? "Valid server updated" :
1882 ("Invalid server updated. (This dirserver is marking your "
1883 "server as unapproved.)");
1884 return unreachable
? 1 : 0;
1888 /* We haven't seen a router with this name before. Add it to the end of
1890 routerlist_insert(routerlist
, router
);
1892 router_append_to_journal(&router
->cache_info
);
1893 directory_set_dirty();
1898 _compare_old_routers_by_identity(const void **_a
, const void **_b
)
1901 const signed_descriptor_t
*r1
= *_a
, *r2
= *_b
;
1902 if ((i
= memcmp(r1
->identity_digest
, r2
->identity_digest
, DIGEST_LEN
)))
1904 return r1
->published_on
- r2
->published_on
;
1907 struct duration_idx_t
{
1914 _compare_duration_idx(const void *_d1
, const void *_d2
)
1916 const struct duration_idx_t
*d1
= _d1
;
1917 const struct duration_idx_t
*d2
= _d2
;
1918 return d1
->duration
- d2
->duration
;
1921 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
1922 * must contain routerinfo_t with the same identity and with publication time
1923 * in ascending order. Remove members from this range until there are no more
1924 * than max_descriptors_per_router() remaining. Start by removing the oldest
1925 * members from before <b>cutoff</b>, then remove members which were current
1926 * for the lowest amount of time. The order of members of old_routers at
1927 * indices <b>lo</b> or higher may be changed.
1930 routerlist_remove_old_cached_routers_with_id(time_t cutoff
, int lo
, int hi
,
1931 digestmap_t
*retain
)
1933 int i
, n
= hi
-lo
+1, n_extra
;
1935 struct duration_idx_t
*lifespans
;
1936 uint8_t *rmv
, *must_keep
;
1937 smartlist_t
*lst
= routerlist
->old_routers
;
1940 tor_assert(hi
< smartlist_len(lst
));
1941 tor_assert(lo
<= hi
);
1942 ident
= ((signed_descriptor_t
*)smartlist_get(lst
, lo
))->identity_digest
;
1943 for (i
= lo
+1; i
<= hi
; ++i
) {
1944 signed_descriptor_t
*r
= smartlist_get(lst
, i
);
1945 tor_assert(!memcmp(ident
, r
->identity_digest
, DIGEST_LEN
));
1949 /* Check whether we need to do anything at all. */
1950 n_extra
= n
- max_descriptors_per_router();
1954 lifespans
= tor_malloc_zero(sizeof(struct duration_idx_t
)*n
);
1955 rmv
= tor_malloc_zero(sizeof(uint8_t)*n
);
1956 must_keep
= tor_malloc_zero(sizeof(uint8_t)*n
);
1957 /* Set lifespans to contain the lifespan and index of each server. */
1958 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
1959 for (i
= lo
; i
<= hi
; ++i
) {
1960 signed_descriptor_t
*r
= smartlist_get(lst
, i
);
1961 signed_descriptor_t
*r_next
;
1962 lifespans
[i
-lo
].idx
= i
;
1963 if (retain
&& digestmap_get(retain
, r
->signed_descriptor_digest
)) {
1964 must_keep
[i
-lo
] = 1;
1967 r_next
= smartlist_get(lst
, i
+1);
1968 tor_assert(r
->published_on
<= r_next
->published_on
);
1969 lifespans
[i
-lo
].duration
= (r_next
->published_on
- r
->published_on
);
1972 lifespans
[i
-lo
].duration
= INT_MAX
;
1974 if (!must_keep
[i
-lo
] && r
->published_on
< cutoff
&& n_rmv
< n_extra
) {
1976 lifespans
[i
-lo
].old
= 1;
1981 if (n_rmv
< n_extra
) {
1983 * We aren't removing enough servers for being old. Sort lifespans by
1984 * the duration of liveness, and remove the ones we're not already going to
1985 * remove based on how long they were alive.
1987 qsort(lifespans
, n
, sizeof(struct duration_idx_t
), _compare_duration_idx
);
1988 for (i
= 0; i
< n
&& n_rmv
< n_extra
; ++i
) {
1989 if (!must_keep
[lifespans
[i
].idx
-lo
] && !lifespans
[i
].old
) {
1990 rmv
[lifespans
[i
].idx
-lo
] = 1;
1996 for (i
= hi
; i
>= lo
; --i
) {
1998 routerlist_remove_old(routerlist
, smartlist_get(lst
, i
), i
);
2000 tor_free(must_keep
);
2002 tor_free(lifespans
);
2005 /** Deactivate any routers from the routerlist that are more than
2006 * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
2007 * remove old routers from the list of cached routers if we have too many.
2010 routerlist_remove_old_routers(void)
2013 const char *cur_id
= NULL
;
2014 time_t now
= time(NULL
);
2016 routerinfo_t
*router
;
2017 signed_descriptor_t
*sd
;
2018 digestmap_t
*retain
;
2019 if (!routerlist
|| !networkstatus_list
)
2022 retain
= digestmap_new();
2023 cutoff
= now
- OLD_ROUTER_DESC_MAX_AGE
;
2024 /* Build a list of all the descriptors that _anybody_ recommends. */
2025 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
2027 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
*, rs
,
2028 if (rs
->published_on
>= cutoff
)
2029 digestmap_set(retain
, rs
->descriptor_digest
, (void*)1));
2032 /* If we have a bunch of networkstatuses, we should consider pruning current
2033 * routers that are too old and that nobody recommends. (If we don't have
2034 * enough networkstatuses, then we should get more before we decide to kill
2036 if (smartlist_len(networkstatus_list
) > get_n_v2_authorities() / 2) {
2037 cutoff
= now
- ROUTER_MAX_AGE
;
2038 /* Remove too-old unrecommended members of routerlist->routers. */
2039 for (i
= 0; i
< smartlist_len(routerlist
->routers
); ++i
) {
2040 router
= smartlist_get(routerlist
->routers
, i
);
2041 if (router
->cache_info
.published_on
<= cutoff
&&
2042 !digestmap_get(retain
,router
->cache_info
.signed_descriptor_digest
)) {
2043 /* Too old: remove it. (If we're a cache, just move it into
2046 "Forgetting obsolete (too old) routerinfo for router '%s'",
2048 routerlist_remove(routerlist
, router
, i
--, 1);
2053 /* Remove far-too-old members of routerlist->old_routers. */
2054 cutoff
= now
- OLD_ROUTER_DESC_MAX_AGE
;
2055 for (i
= 0; i
< smartlist_len(routerlist
->old_routers
); ++i
) {
2056 sd
= smartlist_get(routerlist
->old_routers
, i
);
2057 if (sd
->published_on
<= cutoff
&&
2058 !digestmap_get(retain
, sd
->signed_descriptor_digest
)) {
2059 /* Too old. Remove it. */
2060 routerlist_remove_old(routerlist
, sd
, i
--);
2064 /* Now we might have to look at routerlist->old_routers for extraneous
2065 * members. (We'd keep all the members if we could, but we need to save
2066 * space.) First, check whether we have too many router descriptors, total.
2067 * We're okay with having too many for some given router, so long as the
2068 * total number doesn't approach max_descriptors_per_router()*len(router).
2070 if (smartlist_len(routerlist
->old_routers
) <
2071 smartlist_len(routerlist
->routers
) * (max_descriptors_per_router() - 1))
2074 smartlist_sort(routerlist
->old_routers
, _compare_old_routers_by_identity
);
2076 /* Iterate through the list from back to front, so when we remove descriptors
2077 * we don't mess up groups we haven't gotten to. */
2078 for (i
= smartlist_len(routerlist
->old_routers
)-1; i
>= 0; --i
) {
2079 signed_descriptor_t
*r
= smartlist_get(routerlist
->old_routers
, i
);
2081 cur_id
= r
->identity_digest
;
2084 if (memcmp(cur_id
, r
->identity_digest
, DIGEST_LEN
)) {
2085 routerlist_remove_old_cached_routers_with_id(cutoff
, i
+1, hi
, retain
);
2086 cur_id
= r
->identity_digest
;
2091 routerlist_remove_old_cached_routers_with_id(cutoff
, 0, hi
, retain
);
2092 routerlist_assert_ok(routerlist
);
2095 digestmap_free(retain
, NULL
);
2099 * Code to parse a single router descriptor and insert it into the
2100 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
2101 * descriptor was well-formed but could not be added; and 1 if the
2102 * descriptor was added.
2104 * If we don't add it and <b>msg</b> is not NULL, then assign to
2105 * *<b>msg</b> a static string describing the reason for refusing the
2108 * This is used only by the controller.
2111 router_load_single_router(const char *s
, uint8_t purpose
, const char **msg
)
2119 if (!(ri
= router_parse_entry_from_string(s
, NULL
, 1))) {
2120 log_warn(LD_DIR
, "Error parsing router descriptor; dropping.");
2121 *msg
= "Couldn't parse router descriptor.";
2124 ri
->purpose
= purpose
;
2125 if (router_is_me(ri
)) {
2126 log_warn(LD_DIR
, "Router's identity key matches mine; dropping.");
2127 *msg
= "Router's identity key matches mine.";
2128 routerinfo_free(ri
);
2132 lst
= smartlist_create();
2133 smartlist_add(lst
, ri
);
2134 routers_update_status_from_networkstatus(lst
, 0);
2136 if ((r
=router_add_to_routerlist(ri
, msg
, 0, 0))<0) {
2137 /* we've already assigned to *msg now, and ri is already freed */
2140 log_warn(LD_DIR
, "Couldn't add router to list: %s Dropping.", *msg
);
2141 smartlist_free(lst
);
2144 control_event_descriptors_changed(lst
);
2145 smartlist_free(lst
);
2146 log_debug(LD_DIR
, "Added router to list");
2151 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
2152 * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
2153 * are in response to a query to the network: cache them by adding them to
2156 * If <b>requested_fingerprints</b> is provided, it must contain a list of
2157 * uppercased identity fingerprints. Do not update any router whose
2158 * fingerprint is not on the list; after updating a router, remove its
2159 * fingerprint from the list.
2162 router_load_routers_from_string(const char *s
, saved_location_t saved_location
,
2163 smartlist_t
*requested_fingerprints
)
2165 smartlist_t
*routers
= smartlist_create(), *changed
= smartlist_create();
2166 char fp
[HEX_DIGEST_LEN
+1];
2168 int from_cache
= (saved_location
!= SAVED_NOWHERE
);
2170 router_parse_list_from_string(&s
, routers
, saved_location
);
2172 routers_update_status_from_networkstatus(routers
, !from_cache
);
2174 log_info(LD_DIR
, "%d elements to add", smartlist_len(routers
));
2176 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
,
2178 base16_encode(fp
, sizeof(fp
), ri
->cache_info
.signed_descriptor_digest
,
2180 if (requested_fingerprints
) {
2181 if (smartlist_string_isin(requested_fingerprints
, fp
)) {
2182 smartlist_string_remove(requested_fingerprints
, fp
);
2185 smartlist_join_strings(requested_fingerprints
," ",0,NULL
);
2187 "We received a router descriptor with a fingerprint (%s) "
2188 "that we never requested. (We asked for: %s.) Dropping.",
2190 tor_free(requested
);
2191 routerinfo_free(ri
);
2196 if (router_add_to_routerlist(ri
, &msg
, from_cache
, !from_cache
) >= 0)
2197 smartlist_add(changed
, ri
);
2200 if (smartlist_len(changed
))
2201 control_event_descriptors_changed(changed
);
2203 routerlist_assert_ok(routerlist
);
2204 router_rebuild_store(0);
2206 smartlist_free(routers
);
2207 smartlist_free(changed
);
2210 /** Helper: return a newly allocated string containing the name of the filename
2211 * where we plan to cache the network status with the given identity digest. */
2213 networkstatus_get_cache_filename(const char *identity_digest
)
2215 const char *datadir
= get_options()->DataDirectory
;
2216 size_t len
= strlen(datadir
)+64;
2217 char fp
[HEX_DIGEST_LEN
+1];
2218 char *fn
= tor_malloc(len
+1);
2219 base16_encode(fp
, HEX_DIGEST_LEN
+1, identity_digest
, DIGEST_LEN
);
2220 tor_snprintf(fn
, len
, "%s/cached-status/%s",datadir
,fp
);
2224 /** Helper for smartlist_sort: Compare two networkstatus objects by
2225 * publication date. */
2227 _compare_networkstatus_published_on(const void **_a
, const void **_b
)
2229 const networkstatus_t
*a
= *_a
, *b
= *_b
;
2230 if (a
->published_on
< b
->published_on
)
2232 else if (a
->published_on
> b
->published_on
)
2238 /** Add the parsed neworkstatus in <b>ns</b> (with original document in
2239 * <b>s</b> to the disk cache (and the in-memory directory server cache) as
2242 add_networkstatus_to_cache(const char *s
,
2243 networkstatus_source_t source
,
2244 networkstatus_t
*ns
)
2246 if (source
!= NS_FROM_CACHE
) {
2247 char *fn
= networkstatus_get_cache_filename(ns
->identity_digest
);
2248 if (write_str_to_file(fn
, s
, 0)<0) {
2249 log_notice(LD_FS
, "Couldn't write cached network status to \"%s\"", fn
);
2254 if (get_options()->DirPort
)
2255 dirserv_set_cached_networkstatus_v2(s
,
2256 ns
->identity_digest
,
2262 /** How far in the future do we allow a network-status to get before removing
2264 #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
2266 /** Given a string <b>s</b> containing a network status that we received at
2267 * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
2268 * store it, and put it into our cache as necessary.
2270 * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
2271 * own networkstatus_t (if we're an authoritative directory server).
2273 * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
2276 * If <b>requested_fingerprints</b> is provided, it must contain a list of
2277 * uppercased identity fingerprints. Do not update any networkstatus whose
2278 * fingerprint is not on the list; after updating a networkstatus, remove its
2279 * fingerprint from the list.
2281 * Return 0 on success, -1 on failure.
2283 * Callers should make sure that routers_update_all_from_networkstatus() is
2284 * invoked after this function succeeds.
2287 router_set_networkstatus(const char *s
, time_t arrived_at
,
2288 networkstatus_source_t source
, smartlist_t
*requested_fingerprints
)
2290 networkstatus_t
*ns
;
2294 trusted_dir_server_t
*trusted_dir
= NULL
;
2295 const char *source_desc
= NULL
;
2296 char fp
[HEX_DIGEST_LEN
+1];
2297 char published
[ISO_TIME_LEN
+1];
2299 ns
= networkstatus_parse_from_string(s
);
2301 log_warn(LD_DIR
, "Couldn't parse network status.");
2304 base16_encode(fp
, HEX_DIGEST_LEN
+1, ns
->identity_digest
, DIGEST_LEN
);
2306 router_get_trusteddirserver_by_digest(ns
->identity_digest
)) ||
2307 !trusted_dir
->is_v2_authority
) {
2308 log_info(LD_DIR
, "Network status was signed, but not by an authoritative "
2309 "directory we recognize.");
2310 if (!get_options()->DirPort
) {
2311 networkstatus_free(ns
);
2316 source_desc
= trusted_dir
->description
;
2319 if (arrived_at
> now
)
2322 ns
->received_on
= arrived_at
;
2324 format_iso_time(published
, ns
->published_on
);
2326 if (ns
->published_on
> now
+ NETWORKSTATUS_ALLOW_SKEW
) {
2327 log_warn(LD_GENERAL
, "Network status from %s was published in the future "
2328 "(%s GMT). Somebody is skewed here: check your clock. "
2330 source_desc
, published
);
2331 control_event_general_status(LOG_WARN
,
2332 "CLOCK_SKEW SOURCE=NETWORKSTATUS:%s:%d",
2333 ns
->source_address
, ns
->source_dirport
);
2337 if (!networkstatus_list
)
2338 networkstatus_list
= smartlist_create();
2340 if ( (source
== NS_FROM_DIR_BY_FP
|| source
== NS_FROM_DIR_ALL
) &&
2341 router_digest_is_me(ns
->identity_digest
)) {
2342 /* Don't replace our own networkstatus when we get it from somebody else.*/
2343 networkstatus_free(ns
);
2347 if (requested_fingerprints
) {
2348 if (smartlist_string_isin(requested_fingerprints
, fp
)) {
2349 smartlist_string_remove(requested_fingerprints
, fp
);
2352 smartlist_join_strings(requested_fingerprints
," ",0,NULL
);
2353 if (source
!= NS_FROM_DIR_ALL
) {
2355 "We received a network status with a fingerprint (%s) that we "
2356 "never requested. (We asked for: %s.) Dropping.",
2358 tor_free(requested
);
2365 if (!skewed
&& get_options()->DirPort
) {
2366 /* We got a non-trusted networkstatus, and we're a directory cache.
2367 * This means that we asked an authority, and it told us about another
2368 * authority we didn't recognize. */
2370 "We do not recognize authority (%s) but we are willing "
2372 add_networkstatus_to_cache(s
, source
, ns
);
2373 networkstatus_free(ns
);
2378 if (source
!= NS_FROM_CACHE
&& trusted_dir
)
2379 trusted_dir
->n_networkstatus_failures
= 0;
2382 for (i
=0; i
< smartlist_len(networkstatus_list
); ++i
) {
2383 networkstatus_t
*old_ns
= smartlist_get(networkstatus_list
, i
);
2385 if (!memcmp(old_ns
->identity_digest
, ns
->identity_digest
, DIGEST_LEN
)) {
2386 if (!memcmp(old_ns
->networkstatus_digest
,
2387 ns
->networkstatus_digest
, DIGEST_LEN
)) {
2388 /* Same one we had before. */
2389 networkstatus_free(ns
);
2391 "Not replacing network-status from %s (published %s); "
2392 "we already have it.",
2393 trusted_dir
->description
, published
);
2394 if (old_ns
->received_on
< arrived_at
) {
2395 if (source
!= NS_FROM_CACHE
) {
2397 fn
= networkstatus_get_cache_filename(old_ns
->identity_digest
);
2398 /* We use mtime to tell when it arrived, so update that. */
2402 old_ns
->received_on
= arrived_at
;
2405 } else if (old_ns
->published_on
>= ns
->published_on
) {
2406 char old_published
[ISO_TIME_LEN
+1];
2407 format_iso_time(old_published
, old_ns
->published_on
);
2409 "Not replacing network-status from %s (published %s);"
2410 " we have a newer one (published %s) for this authority.",
2411 trusted_dir
->description
, published
,
2413 networkstatus_free(ns
);
2416 networkstatus_free(old_ns
);
2417 smartlist_set(networkstatus_list
, i
, ns
);
2425 smartlist_add(networkstatus_list
, ns
);
2427 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
*, rs
,
2429 if (!router_get_by_descriptor_digest(rs
->descriptor_digest
))
2430 rs
->need_to_mirror
= 1;
2433 log_info(LD_DIR
, "Setting networkstatus %s %s (published %s)",
2434 source
== NS_FROM_CACHE
?"cached from":
2435 ((source
== NS_FROM_DIR_BY_FP
|| source
== NS_FROM_DIR_ALL
) ?
2436 "downloaded from":"generated for"),
2437 trusted_dir
->description
, published
);
2438 networkstatus_list_has_changed
= 1;
2439 router_dir_info_changed();
2441 smartlist_sort(networkstatus_list
, _compare_networkstatus_published_on
);
2444 add_networkstatus_to_cache(s
, source
, ns
);
2446 networkstatus_list_update_recent(now
);
2451 /** How old do we allow a network-status to get before removing it
2453 #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
2454 /** Remove all very-old network_status_t objects from memory and from the
2457 networkstatus_list_clean(time_t now
)
2460 if (!networkstatus_list
)
2463 for (i
= 0; i
< smartlist_len(networkstatus_list
); ++i
) {
2464 networkstatus_t
*ns
= smartlist_get(networkstatus_list
, i
);
2466 if (ns
->published_on
+ MAX_NETWORKSTATUS_AGE
> now
)
2468 /* Okay, this one is too old. Remove it from the list, and delete it
2469 * from the cache. */
2470 smartlist_del(networkstatus_list
, i
--);
2471 fname
= networkstatus_get_cache_filename(ns
->identity_digest
);
2472 if (file_status(fname
) == FN_FILE
) {
2473 log_info(LD_DIR
, "Removing too-old networkstatus in %s", fname
);
2477 if (get_options()->DirPort
) {
2478 dirserv_set_cached_networkstatus_v2(NULL
, ns
->identity_digest
, 0);
2480 networkstatus_free(ns
);
2481 router_dir_info_changed();
2484 /* And now go through the directory cache for any cached untrusted
2485 * networkstatuses. */
2486 dirserv_clear_old_networkstatuses(now
- MAX_NETWORKSTATUS_AGE
);
2489 /** Helper for bsearching a list of routerstatus_t pointers.*/
2491 _compare_digest_to_routerstatus_entry(const void *_key
, const void **_member
)
2493 const char *key
= _key
;
2494 const routerstatus_t
*rs
= *_member
;
2495 return memcmp(key
, rs
->identity_digest
, DIGEST_LEN
);
2498 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
2499 * NULL if none was found. */
2500 static routerstatus_t
*
2501 networkstatus_find_entry(networkstatus_t
*ns
, const char *digest
)
2503 return smartlist_bsearch(ns
->entries
, digest
,
2504 _compare_digest_to_routerstatus_entry
);
2507 /** Return the consensus view of the status of the router whose digest is
2508 * <b>digest</b>, or NULL if we don't know about any such router. */
2509 local_routerstatus_t
*
2510 router_get_combined_status_by_digest(const char *digest
)
2512 if (!routerstatus_list
)
2514 return smartlist_bsearch(routerstatus_list
, digest
,
2515 _compare_digest_to_routerstatus_entry
);
2518 static local_routerstatus_t
*
2519 router_get_combined_status_by_nickname(const char *nickname
,
2520 int warn_if_unnamed
)
2522 char digest
[DIGEST_LEN
];
2523 local_routerstatus_t
*best
=NULL
;
2524 smartlist_t
*matches
=NULL
;
2526 if (!routerstatus_list
|| !nickname
)
2529 if (nickname
[0] == '$') {
2530 if (base16_decode(digest
, DIGEST_LEN
, nickname
+1, strlen(nickname
))<0)
2532 return router_get_combined_status_by_digest(digest
);
2533 } else if (strlen(nickname
) == HEX_DIGEST_LEN
&&
2534 (base16_decode(digest
, DIGEST_LEN
, nickname
+1, strlen(nickname
))==0)) {
2535 return router_get_combined_status_by_digest(digest
);
2538 matches
= smartlist_create();
2539 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, lrs
,
2541 if (!strcasecmp(lrs
->status
.nickname
, nickname
)) {
2542 if (lrs
->status
.is_named
) {
2543 smartlist_free(matches
);
2546 smartlist_add(matches
, lrs
);
2552 if (smartlist_len(matches
)>1 && warn_if_unnamed
) {
2554 SMARTLIST_FOREACH(matches
, local_routerstatus_t
*, lrs
,
2556 if (! lrs
->name_lookup_warned
) {
2557 lrs
->name_lookup_warned
=1;
2562 log_warn(LD_CONFIG
,"There are multiple matches for the nickname \"%s\",",
2563 " but none is listed as named by the directory authorites. "
2564 "Choosing one arbitrarily.");
2566 } else if (warn_if_unnamed
&& best
&& !best
->name_lookup_warned
) {
2567 char fp
[HEX_DIGEST_LEN
+1];
2568 base16_encode(fp
, sizeof(fp
),
2569 best
->status
.identity_digest
, DIGEST_LEN
);
2571 "To look up a status, you specified a server \"%s\" by name, but the "
2572 "directory authorities do not have a binding for this nickname. "
2573 "To make sure you get the same server in the future, refer to "
2574 "it by key, as \"$%s\".", nickname
, fp
);
2575 best
->name_lookup_warned
= 1;
2577 smartlist_free(matches
);
2581 /** Return true iff any networkstatus includes a descriptor whose digest
2582 * is that of <b>desc</b>. */
2584 signed_desc_digest_is_recognized(signed_descriptor_t
*desc
)
2587 if (!networkstatus_list
)
2590 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
2592 if (!(rs
= networkstatus_find_entry(ns
, desc
->identity_digest
)))
2594 if (!memcmp(rs
->descriptor_digest
,
2595 desc
->signed_descriptor_digest
, DIGEST_LEN
))
2601 /** How frequently do directory authorities re-download fresh networkstatus
2603 #define AUTHORITY_NS_CACHE_INTERVAL (5*60)
2605 /** How frequently do non-authority directory caches re-download fresh
2606 * networkstatus documents? */
2607 #define NONAUTHORITY_NS_CACHE_INTERVAL (15*60)
2609 /** We are a directory server, and so cache network_status documents.
2610 * Initiate downloads as needed to update them. For authorities, this means
2611 * asking each trusted directory for its network-status. For caches, this
2612 * means asking a random authority for all network-statuses.
2615 update_networkstatus_cache_downloads(time_t now
)
2617 int authority
= authdir_mode(get_options());
2619 authority
? AUTHORITY_NS_CACHE_INTERVAL
: NONAUTHORITY_NS_CACHE_INTERVAL
;
2621 if (last_networkstatus_download_attempted
+ interval
>= now
)
2623 if (!trusted_dir_servers
)
2626 last_networkstatus_download_attempted
= now
;
2629 /* An authority launches a separate connection for everybody. */
2630 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
2632 char resource
[HEX_DIGEST_LEN
+6]; /* fp/hexdigit.z\0 */
2633 if (!ds
->is_v2_authority
)
2635 if (router_digest_is_me(ds
->digest
))
2637 if (connection_get_by_type_addr_port_purpose(
2638 CONN_TYPE_DIR
, ds
->addr
, ds
->dir_port
,
2639 DIR_PURPOSE_FETCH_NETWORKSTATUS
)) {
2640 /* We are already fetching this one. */
2643 strlcpy(resource
, "fp/", sizeof(resource
));
2644 base16_encode(resource
+3, sizeof(resource
)-3, ds
->digest
, DIGEST_LEN
);
2645 strlcat(resource
, ".z", sizeof(resource
));
2646 directory_initiate_command_routerstatus(
2647 &ds
->fake_status
.status
, DIR_PURPOSE_FETCH_NETWORKSTATUS
,
2648 0, /* Not private */
2650 NULL
, 0 /* No payload. */);
2653 /* A non-authority cache launches one connection to a random authority. */
2654 /* (Check whether we're currently fetching network-status objects.) */
2655 if (!connection_get_by_type_purpose(CONN_TYPE_DIR
,
2656 DIR_PURPOSE_FETCH_NETWORKSTATUS
))
2657 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS
,"all.z",1);
2661 /** How long (in seconds) does a client wait after getting a network status
2662 * before downloading the next in sequence? */
2663 #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
2664 /* How many times do we allow a networkstatus download to fail before we
2665 * assume that the authority isn't publishing? */
2666 #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
2667 /** We are not a directory cache or authority. Update our network-status list
2668 * by launching a new directory fetch for enough network-status documents "as
2669 * necessary". See function comments for implementation details.
2672 update_networkstatus_client_downloads(time_t now
)
2674 int n_live
= 0, n_dirservers
, n_running_dirservers
, needed
= 0;
2675 int fetch_latest
= 0;
2676 int most_recent_idx
= -1;
2677 trusted_dir_server_t
*most_recent
= NULL
;
2678 time_t most_recent_received
= 0;
2679 char *resource
, *cp
;
2680 size_t resource_len
;
2681 smartlist_t
*missing
;
2683 if (connection_get_by_type_purpose(CONN_TYPE_DIR
,
2684 DIR_PURPOSE_FETCH_NETWORKSTATUS
))
2687 /* This is a little tricky. We want to download enough network-status
2688 * objects so that we have all of them under
2689 * NETWORKSTATUS_MAX_AGE publication time. We want to download a new
2690 * *one* if the most recent one's publication time is under
2691 * NETWORKSTATUS_CLIENT_DL_INTERVAL.
2693 if (!get_n_v2_authorities())
2695 n_dirservers
= n_running_dirservers
= 0;
2696 missing
= smartlist_create();
2697 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
2699 networkstatus_t
*ns
= networkstatus_get_by_digest(ds
->digest
);
2700 if (!ds
->is_v2_authority
)
2703 if (ds
->n_networkstatus_failures
> NETWORKSTATUS_N_ALLOWABLE_FAILURES
)
2705 ++n_running_dirservers
;
2706 if (ns
&& ns
->published_on
> now
-NETWORKSTATUS_MAX_AGE
)
2709 smartlist_add(missing
, ds
->digest
);
2710 if (ns
&& (!most_recent
|| ns
->received_on
> most_recent_received
)) {
2711 most_recent_idx
= ds_sl_idx
; /* magic variable from FOREACH */
2713 most_recent_received
= ns
->received_on
;
2717 /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
2718 if (!smartlist_len(missing
) &&
2719 most_recent_received
< now
-NETWORKSTATUS_CLIENT_DL_INTERVAL
) {
2720 log_info(LD_DIR
, "Our most recent network-status document (from %s) "
2721 "is %d seconds old; downloading another.",
2722 most_recent
?most_recent
->description
:"nobody",
2723 (int)(now
-most_recent_received
));
2726 } else if (smartlist_len(missing
)) {
2727 log_info(LD_DIR
, "For %d/%d running directory servers, we have %d live"
2728 " network-status documents. Downloading %d.",
2729 n_running_dirservers
, n_dirservers
, n_live
,
2730 smartlist_len(missing
));
2731 needed
= smartlist_len(missing
);
2733 smartlist_free(missing
);
2737 /* If no networkstatus was found, choose a dirserver at random as "most
2739 if (most_recent_idx
<0)
2740 most_recent_idx
= crypto_rand_int(n_dirservers
);
2745 for (i
= most_recent_idx
+ 1; 1; ++i
) {
2746 trusted_dir_server_t
*ds
;
2747 if (i
>= n_dirservers
)
2749 ds
= smartlist_get(trusted_dir_servers
, i
);
2750 if (! ds
->is_v2_authority
)
2752 if (n_failed
< n_dirservers
&&
2753 ds
->n_networkstatus_failures
> NETWORKSTATUS_N_ALLOWABLE_FAILURES
) {
2757 smartlist_add(missing
, ds
->digest
);
2762 /* Build a request string for all the resources we want. */
2763 resource_len
= smartlist_len(missing
) * (HEX_DIGEST_LEN
+1) + 6;
2764 resource
= tor_malloc(resource_len
);
2765 memcpy(resource
, "fp/", 3);
2767 smartlist_sort_digests(missing
);
2768 needed
= smartlist_len(missing
);
2769 SMARTLIST_FOREACH(missing
, const char *, d
,
2771 base16_encode(cp
, HEX_DIGEST_LEN
+1, d
, DIGEST_LEN
);
2772 cp
+= HEX_DIGEST_LEN
;
2777 memcpy(cp
, ".z", 3);
2778 directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS
, resource
, 1);
2780 smartlist_free(missing
);
2783 /** Launch requests for networkstatus documents as appropriate. */
2785 update_networkstatus_downloads(time_t now
)
2787 or_options_t
*options
= get_options();
2788 if (options
->DirPort
)
2789 update_networkstatus_cache_downloads(now
);
2791 update_networkstatus_client_downloads(now
);
2794 /** Return 1 if all running sufficiently-stable routers will reject
2795 * addr:port, return 0 if any might accept it. */
2797 router_exit_policy_all_routers_reject(uint32_t addr
, uint16_t port
,
2800 addr_policy_result_t r
;
2801 if (!routerlist
) return 1;
2803 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
2805 if (router
->is_running
&&
2806 !router_is_unreliable(router
, need_uptime
, 0, 0)) {
2807 r
= compare_addr_to_addr_policy(addr
, port
, router
->exit_policy
);
2808 if (r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
)
2809 return 0; /* this one could be ok. good enough. */
2812 return 1; /* all will reject. */
2815 /** Return true iff <b>router</b> does not permit exit streams.
2818 router_exit_policy_rejects_all(routerinfo_t
*router
)
2820 return compare_addr_to_addr_policy(0, 0, router
->exit_policy
)
2821 == ADDR_POLICY_REJECTED
;
2824 /** Add to the list of authorized directory servers one at
2825 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
2826 * <b>address</b> is NULL, add ourself. */
2828 add_trusted_dir_server(const char *nickname
, const char *address
,
2829 uint16_t dir_port
, uint16_t or_port
,
2830 const char *digest
, int is_v1_authority
,
2831 int is_v2_authority
, int is_hidserv_authority
)
2833 trusted_dir_server_t
*ent
;
2835 char *hostname
= NULL
;
2837 if (!trusted_dir_servers
)
2838 trusted_dir_servers
= smartlist_create();
2840 if (!address
) { /* The address is us; we should guess. */
2841 if (resolve_my_address(LOG_WARN
, get_options(), &a
, &hostname
) < 0) {
2843 "Couldn't find a suitable address when adding ourself as a "
2844 "trusted directory server.");
2848 if (tor_lookup_hostname(address
, &a
)) {
2850 "Unable to lookup address for directory server at '%s'",
2854 hostname
= tor_strdup(address
);
2858 ent
= tor_malloc_zero(sizeof(trusted_dir_server_t
));
2859 ent
->nickname
= nickname
? tor_strdup(nickname
) : NULL
;
2860 ent
->address
= hostname
;
2862 ent
->dir_port
= dir_port
;
2863 ent
->or_port
= or_port
;
2864 ent
->is_running
= 1;
2865 ent
->is_v1_authority
= is_v1_authority
;
2866 ent
->is_v2_authority
= is_v2_authority
;
2867 ent
->is_hidserv_authority
= is_hidserv_authority
;
2868 memcpy(ent
->digest
, digest
, DIGEST_LEN
);
2870 dlen
= 64 + strlen(hostname
) + (nickname
?strlen(nickname
):0);
2871 ent
->description
= tor_malloc(dlen
);
2873 tor_snprintf(ent
->description
, dlen
, "directory server \"%s\" at %s:%d",
2874 nickname
, hostname
, (int)dir_port
);
2876 tor_snprintf(ent
->description
, dlen
, "directory server at %s:%d",
2877 hostname
, (int)dir_port
);
2879 ent
->fake_status
.status
.addr
= ent
->addr
;
2880 memcpy(ent
->fake_status
.status
.identity_digest
, digest
, DIGEST_LEN
);
2882 strlcpy(ent
->fake_status
.status
.nickname
, nickname
,
2883 sizeof(ent
->fake_status
.status
.nickname
));
2885 ent
->fake_status
.status
.nickname
[0] = '\0';
2886 ent
->fake_status
.status
.dir_port
= ent
->dir_port
;
2887 ent
->fake_status
.status
.or_port
= ent
->or_port
;
2889 smartlist_add(trusted_dir_servers
, ent
);
2890 router_dir_info_changed();
2893 /** Free storage held in <b>ds</b> */
2895 trusted_dir_server_free(trusted_dir_server_t
*ds
)
2897 tor_free(ds
->nickname
);
2898 tor_free(ds
->description
);
2899 tor_free(ds
->address
);
2903 /** Remove all members from the list of trusted dir servers. */
2905 clear_trusted_dir_servers(void)
2907 if (trusted_dir_servers
) {
2908 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
2909 trusted_dir_server_free(ent
));
2910 smartlist_clear(trusted_dir_servers
);
2912 trusted_dir_servers
= smartlist_create();
2914 router_dir_info_changed();
2917 /** Return 1 if any trusted dir server supports v1 directories,
2920 any_trusted_dir_is_v1_authority(void)
2922 if (trusted_dir_servers
)
2923 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
2924 if (ent
->is_v1_authority
) return 1);
2928 /** Return the network status with a given identity digest. */
2930 networkstatus_get_by_digest(const char *digest
)
2932 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
2934 if (!memcmp(ns
->identity_digest
, digest
, DIGEST_LEN
))
2940 /** We believe networkstatuses more recent than this when they tell us that
2941 * our server is broken, invalid, obsolete, etc. */
2942 #define SELF_OPINION_INTERVAL (90*60)
2944 /** Return a string naming the versions of Tor recommended by
2945 * more than half the versioning networkstatuses. */
2947 compute_recommended_versions(time_t now
, int client
)
2951 smartlist_t
*combined
, *recommended
;
2954 (void) now
; /* right now, we consider *all* ors. */
2956 if (!networkstatus_list
)
2957 return tor_strdup("<none>");
2959 combined
= smartlist_create();
2961 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
2964 smartlist_t
*versions
;
2965 if (! ns
->recommends_versions
)
2968 vers
= client
? ns
->client_versions
: ns
->server_versions
;
2971 versions
= smartlist_create();
2972 smartlist_split_string(versions
, vers
, ",",
2973 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2974 sort_version_list(versions
, 1);
2975 smartlist_add_all(combined
, versions
);
2976 smartlist_free(versions
);
2979 sort_version_list(combined
, 0);
2983 recommended
= smartlist_create();
2984 SMARTLIST_FOREACH(combined
, char *, cp
,
2986 if (current
&& !strcmp(cp
, current
)) {
2989 if (n_seen
>= n_versioning
/2 && current
)
2990 smartlist_add(recommended
, current
);
2995 if (n_seen
>= n_versioning
/2 && current
)
2996 smartlist_add(recommended
, current
);
2998 result
= smartlist_join_strings(recommended
, ", ", 0, NULL
);
3000 SMARTLIST_FOREACH(combined
, char *, cp
, tor_free(cp
));
3001 smartlist_free(combined
);
3002 smartlist_free(recommended
);
3007 /** If the network-status list has changed since the last time we called this
3008 * function, update the status of every routerinfo from the network-status
3012 routers_update_all_from_networkstatus(void)
3016 if (!routerlist
|| !networkstatus_list
||
3017 (!networkstatus_list_has_changed
&& !routerstatus_list_has_changed
))
3020 router_dir_info_changed();
3023 if (networkstatus_list_has_changed
)
3024 routerstatus_list_update_from_networkstatus(now
);
3026 routers_update_status_from_networkstatus(routerlist
->routers
, 0);
3028 me
= router_get_my_routerinfo();
3029 if (me
&& !have_warned_about_invalid_status
&&
3030 have_tried_downloading_all_statuses(4)) {
3031 int n_recent
= 0, n_listing
= 0, n_valid
= 0, n_named
= 0, n_naming
= 0;
3033 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
3035 if (ns
->received_on
+ SELF_OPINION_INTERVAL
< now
)
3038 if (ns
->binds_names
)
3040 if (!(rs
= networkstatus_find_entry(ns
, me
->cache_info
.identity_digest
)))
3050 if (n_valid
<= n_listing
/2) {
3051 log_info(LD_GENERAL
,
3052 "%d/%d recent statements from directory authorities list us "
3053 "as unapproved. Are you misconfigured?",
3054 n_listing
-n_valid
, n_listing
);
3055 have_warned_about_invalid_status
= 1;
3056 } else if (n_naming
&& !n_named
) {
3057 log_info(LD_GENERAL
, "0/%d name-binding directory authorities "
3058 "recognize your nickname. Please consider sending your "
3059 "nickname and identity fingerprint to the tor-ops.",
3061 have_warned_about_invalid_status
= 1;
3066 entry_guards_compute_status();
3068 if (!have_warned_about_old_version
&&
3069 have_tried_downloading_all_statuses(4)) {
3070 int n_versioning
= 0;
3071 int n_recommended
= 0;
3072 int is_server
= server_mode(get_options());
3073 version_status_t consensus
= VS_RECOMMENDED
;
3074 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
3076 version_status_t vs
;
3077 if (!ns
->recommends_versions
)
3079 vs
= tor_version_is_obsolete(
3080 VERSION
, is_server
? ns
->server_versions
: ns
->client_versions
);
3081 if (vs
== VS_RECOMMENDED
)
3083 if (n_versioning
++ == 0) {
3085 } else if (consensus
!= vs
) {
3086 consensus
= version_status_join(consensus
, vs
);
3089 if (n_versioning
&& n_recommended
<= n_versioning
/2) {
3090 if (consensus
== VS_NEW
|| consensus
== VS_NEW_IN_SERIES
) {
3091 if (!have_warned_about_new_version
) {
3092 char *rec
= compute_recommended_versions(now
, !is_server
);
3093 log_notice(LD_GENERAL
, "This version of Tor (%s) is newer than any "
3094 "recommended version%s, according to %d/%d network "
3095 "statuses. Versions recommended by more than %d "
3096 "authorit%s are: %s",
3098 consensus
== VS_NEW_IN_SERIES
? " in its series" : "",
3099 n_versioning
-n_recommended
, n_versioning
, n_versioning
/2,
3100 n_versioning
/2 > 1 ? "ies" : "y", rec
);
3101 have_warned_about_new_version
= 1;
3102 control_event_general_status(LOG_WARN
, "DANGEROUS_VERSION "
3103 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
3104 VERSION
, "NEW", rec
);
3108 char *rec
= compute_recommended_versions(now
, !is_server
);
3109 log_warn(LD_GENERAL
, "Please upgrade! "
3110 "This version of Tor (%s) is %s, according to "
3111 "%d/%d network statuses. Versions recommended by "
3112 "at least %d authorit%s are: %s",
3113 VERSION
, consensus
== VS_OLD
? "obsolete" : "not recommended",
3114 n_versioning
-n_recommended
, n_versioning
, n_versioning
/2,
3115 n_versioning
/2 > 1 ? "ies" : "y", rec
);
3116 have_warned_about_old_version
= 1;
3117 control_event_general_status(LOG_WARN
, "DANGEROUS_VERSION "
3118 "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
3119 VERSION
, consensus
== VS_OLD
? "OLD" : "UNRECOMMENDED", rec
);
3123 log_info(LD_GENERAL
, "%d/%d statements from "
3124 "directory authorities say my version is ok.",
3125 n_recommended
, n_versioning
);
3129 routerstatus_list_has_changed
= 0;
3132 /** Allow any network-status newer than this to influence our view of who's
3134 #define DEFAULT_RUNNING_INTERVAL (60*60)
3135 /** If possible, always allow at least this many network-statuses to influence
3136 * our view of who's running. */
3137 #define MIN_TO_INFLUENCE_RUNNING 3
3139 /** Change the is_recent field of each member of networkstatus_list so that
3140 * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
3141 * at least the MIN_TO_INFLUENCE_RUNNING most recent members are recent, and no
3142 * others are recent. Set networkstatus_list_has_changed if anything happened.
3145 networkstatus_list_update_recent(time_t now
)
3147 int n_statuses
, n_recent
, changed
, i
;
3148 char published
[ISO_TIME_LEN
+1];
3150 if (!networkstatus_list
)
3153 n_statuses
= smartlist_len(networkstatus_list
);
3156 for (i
=n_statuses
-1; i
>= 0; --i
) {
3157 networkstatus_t
*ns
= smartlist_get(networkstatus_list
, i
);
3158 trusted_dir_server_t
*ds
=
3159 router_get_trusteddirserver_by_digest(ns
->identity_digest
);
3160 const char *src
= ds
?ds
->description
:ns
->source_address
;
3161 if (n_recent
< MIN_TO_INFLUENCE_RUNNING
||
3162 ns
->published_on
+ DEFAULT_RUNNING_INTERVAL
> now
) {
3163 if (!ns
->is_recent
) {
3164 format_iso_time(published
, ns
->published_on
);
3166 "Networkstatus from %s (published %s) is now \"recent\"",
3173 if (ns
->is_recent
) {
3174 format_iso_time(published
, ns
->published_on
);
3176 "Networkstatus from %s (published %s) is "
3177 "no longer \"recent\"",
3185 networkstatus_list_has_changed
= 1;
3186 router_dir_info_changed();
3190 /** Helper for routerstatus_list_update_from_networkstatus: remember how many
3191 * authorities recommend a given descriptor digest. */
3195 } desc_digest_count_t
;
3197 /** Update our view of router status (as stored in routerstatus_list) from the
3198 * current set of network status documents (as stored in networkstatus_list).
3199 * Do nothing unless the network status list has changed since the last time
3200 * this function was called.
3203 routerstatus_list_update_from_networkstatus(time_t now
)
3205 or_options_t
*options
= get_options();
3206 int n_trusted
, n_statuses
, n_recent
= 0, n_naming
= 0;
3207 int n_listing_bad_exits
= 0, n_listing_bad_directories
= 0;
3210 networkstatus_t
**networkstatus
;
3211 smartlist_t
*result
, *changed_list
;
3213 char conflict
[DIGEST_LEN
]; /* Sentinel value */
3214 desc_digest_count_t
*digest_counts
= NULL
;
3216 /* compute which network statuses will have a vote now */
3217 networkstatus_list_update_recent(now
);
3218 router_dir_info_changed();
3220 if (!networkstatus_list_has_changed
)
3222 if (!networkstatus_list
)
3223 networkstatus_list
= smartlist_create();
3224 if (!routerstatus_list
)
3225 routerstatus_list
= smartlist_create();
3226 if (!trusted_dir_servers
)
3227 trusted_dir_servers
= smartlist_create();
3228 if (!warned_conflicts
)
3229 warned_conflicts
= smartlist_create();
3231 n_statuses
= smartlist_len(networkstatus_list
);
3232 n_trusted
= get_n_v2_authorities();
3234 if (n_statuses
<= n_trusted
/2) {
3235 /* Not enough statuses to adjust status. */
3237 "Not enough statuses to update router status list. (%d/%d)",
3238 n_statuses
, n_trusted
);
3242 log_info(LD_DIR
, "Rebuilding router status list.");
3244 index
= tor_malloc(sizeof(int)*n_statuses
);
3245 size
= tor_malloc(sizeof(int)*n_statuses
);
3246 networkstatus
= tor_malloc(sizeof(networkstatus_t
*)*n_statuses
);
3247 for (i
= 0; i
< n_statuses
; ++i
) {
3249 networkstatus
[i
] = smartlist_get(networkstatus_list
, i
);
3250 size
[i
] = smartlist_len(networkstatus
[i
]->entries
);
3251 if (networkstatus
[i
]->binds_names
)
3253 if (networkstatus
[i
]->is_recent
)
3255 if (networkstatus
[i
]->lists_bad_exits
)
3256 ++n_listing_bad_exits
;
3257 if (networkstatus
[i
]->lists_bad_directories
)
3258 ++n_listing_bad_directories
;
3261 /** Iterate over all entries in all networkstatuses, and build
3262 * name_map as a map from lc nickname to identity digest. If there
3263 * is a conflict on that nickname, map the lc nickname to conflict.
3265 name_map
= strmap_new();
3266 /* Clear the global map... */
3267 if (named_server_map
)
3268 strmap_free(named_server_map
, _tor_free
);
3269 named_server_map
= strmap_new();
3270 memset(conflict
, 0xff, sizeof(conflict
));
3271 for (i
= 0; i
< n_statuses
; ++i
) {
3272 if (!networkstatus
[i
]->binds_names
)
3274 SMARTLIST_FOREACH(networkstatus
[i
]->entries
, routerstatus_t
*, rs
,
3276 const char *other_digest
;
3279 other_digest
= strmap_get_lc(name_map
, rs
->nickname
);
3280 warned
= smartlist_string_isin(warned_conflicts
, rs
->nickname
);
3281 if (!other_digest
) {
3282 strmap_set_lc(name_map
, rs
->nickname
, rs
->identity_digest
);
3283 strmap_set_lc(named_server_map
, rs
->nickname
,
3284 tor_memdup(rs
->identity_digest
, DIGEST_LEN
));
3286 smartlist_string_remove(warned_conflicts
, rs
->nickname
);
3287 } else if (memcmp(other_digest
, rs
->identity_digest
, DIGEST_LEN
) &&
3288 other_digest
!= conflict
) {
3291 int should_warn
= options
->DirPort
&& options
->AuthoritativeDir
;
3292 char fp1
[HEX_DIGEST_LEN
+1];
3293 char fp2
[HEX_DIGEST_LEN
+1];
3294 base16_encode(fp1
, sizeof(fp1
), other_digest
, DIGEST_LEN
);
3295 base16_encode(fp2
, sizeof(fp2
), rs
->identity_digest
, DIGEST_LEN
);
3296 log_fn(should_warn
? LOG_WARN
: LOG_INFO
, LD_DIR
,
3297 "Naming authorities disagree about which key goes with %s. "
3299 rs
->nickname
, fp1
, fp2
);
3300 strmap_set_lc(name_map
, rs
->nickname
, conflict
);
3301 d
= strmap_remove_lc(named_server_map
, rs
->nickname
);
3303 smartlist_add(warned_conflicts
, tor_strdup(rs
->nickname
));
3307 smartlist_string_remove(warned_conflicts
, rs
->nickname
);
3312 result
= smartlist_create();
3313 changed_list
= smartlist_create();
3314 digest_counts
= tor_malloc_zero(sizeof(desc_digest_count_t
)*n_statuses
);
3316 /* Iterate through all of the sorted routerstatus lists in lockstep.
3318 * - For 0 <= i < n_statuses: index[i] is an index into
3319 * networkstatus[i]->entries, which has size[i] elements.
3320 * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
3321 * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
3322 * networkstatus[i2]->entries[index[i2]]->identity_digest.
3324 * (That is, the indices are always advanced past lower digest before
3328 int n_running
=0, n_named
=0, n_valid
=0, n_listing
=0;
3329 int n_v2_dir
=0, n_fast
=0, n_stable
=0, n_exit
=0, n_guard
=0, n_bad_exit
=0;
3330 int n_bad_directory
=0;
3331 int n_version_known
=0, n_supports_begindir
=0;
3332 int n_desc_digests
=0, highest_count
=0;
3333 const char *the_name
= NULL
;
3334 local_routerstatus_t
*rs_out
, *rs_old
;
3335 routerstatus_t
*rs
, *most_recent
;
3336 networkstatus_t
*ns
;
3337 const char *lowest
= NULL
;
3339 /* Find out which of the digests appears first. */
3340 for (i
= 0; i
< n_statuses
; ++i
) {
3341 if (index
[i
] < size
[i
]) {
3342 rs
= smartlist_get(networkstatus
[i
]->entries
, index
[i
]);
3343 if (!lowest
|| memcmp(rs
->identity_digest
, lowest
, DIGEST_LEN
)<0)
3344 lowest
= rs
->identity_digest
;
3348 /* We're out of routers. Great! */
3351 /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
3352 * match "lowest" are next in order. Iterate over them, incrementing those
3353 * index[i] as we go. */
3354 for (i
= 0; i
< n_statuses
; ++i
) {
3355 if (index
[i
] >= size
[i
])
3357 ns
= networkstatus
[i
];
3358 rs
= smartlist_get(ns
->entries
, index
[i
]);
3359 if (memcmp(rs
->identity_digest
, lowest
, DIGEST_LEN
))
3361 /* At this point, we know that we're looking at a routersatus with
3362 * identity "lowest".
3366 /* Should we name this router? Only if all the names from naming
3367 * authorities match. */
3368 if (rs
->is_named
&& ns
->binds_names
) {
3370 the_name
= rs
->nickname
;
3371 if (!strcasecmp(rs
->nickname
, the_name
)) {
3373 } else if (strcmp(the_name
,"**mismatch**")) {
3374 char hd
[HEX_DIGEST_LEN
+1];
3375 base16_encode(hd
, HEX_DIGEST_LEN
+1, rs
->identity_digest
, DIGEST_LEN
);
3376 if (! smartlist_string_isin(warned_conflicts
, hd
)) {
3378 "Naming authorities disagree about nicknames for $%s "
3379 "(\"%s\" vs \"%s\")",
3380 hd
, the_name
, rs
->nickname
);
3381 smartlist_add(warned_conflicts
, tor_strdup(hd
));
3383 the_name
= "**mismatch**";
3386 /* Keep a running count of how often which descriptor digests
3388 for (j
= 0; j
< n_desc_digests
; ++j
) {
3389 if (!memcmp(rs
->descriptor_digest
,
3390 digest_counts
[j
].rs
->descriptor_digest
, DIGEST_LEN
)) {
3391 if (++digest_counts
[j
].count
> highest_count
)
3392 highest_count
= digest_counts
[j
].count
;
3396 digest_counts
[n_desc_digests
].rs
= rs
;
3397 digest_counts
[n_desc_digests
].count
= 1;
3402 /* Now tally up the easily-tallied flags. */
3405 if (rs
->is_running
&& ns
->is_recent
)
3411 if (rs
->is_possible_guard
)
3417 if (rs
->is_bad_exit
)
3419 if (rs
->is_bad_directory
)
3421 if (rs
->version_known
)
3423 if (rs
->version_supports_begindir
)
3424 ++n_supports_begindir
;
3426 /* Go over the descriptor digests and figure out which descriptor we
3429 for (i
= 0; i
< n_desc_digests
; ++i
) {
3430 /* If any digest appears twice or more, ignore those that don't.*/
3431 if (highest_count
>= 2 && digest_counts
[i
].count
< 2)
3434 digest_counts
[i
].rs
->published_on
> most_recent
->published_on
)
3435 most_recent
= digest_counts
[i
].rs
;
3437 rs_out
= tor_malloc_zero(sizeof(local_routerstatus_t
));
3438 memcpy(&rs_out
->status
, most_recent
, sizeof(routerstatus_t
));
3439 /* Copy status info about this router, if we had any before. */
3440 if ((rs_old
= router_get_combined_status_by_digest(lowest
))) {
3441 if (!memcmp(rs_out
->status
.descriptor_digest
,
3442 most_recent
->descriptor_digest
, DIGEST_LEN
)) {
3443 rs_out
->n_download_failures
= rs_old
->n_download_failures
;
3444 rs_out
->next_attempt_at
= rs_old
->next_attempt_at
;
3446 rs_out
->name_lookup_warned
= rs_old
->name_lookup_warned
;
3447 rs_out
->last_dir_503_at
= rs_old
->last_dir_503_at
;
3449 smartlist_add(result
, rs_out
);
3450 log_debug(LD_DIR
, "Router '%s' is listed by %d/%d directories, "
3451 "named by %d/%d, validated by %d/%d, and %d/%d recent "
3452 "directories think it's running.",
3453 rs_out
->status
.nickname
,
3454 n_listing
, n_statuses
, n_named
, n_naming
, n_valid
, n_statuses
,
3455 n_running
, n_recent
);
3456 rs_out
->status
.is_named
= 0;
3457 if (the_name
&& strcmp(the_name
, "**mismatch**") && n_named
> 0) {
3458 const char *d
= strmap_get_lc(name_map
, the_name
);
3459 if (d
&& d
!= conflict
)
3460 rs_out
->status
.is_named
= 1;
3461 if (smartlist_string_isin(warned_conflicts
, rs_out
->status
.nickname
))
3462 smartlist_string_remove(warned_conflicts
, rs_out
->status
.nickname
);
3464 if (rs_out
->status
.is_named
)
3465 strlcpy(rs_out
->status
.nickname
, the_name
,
3466 sizeof(rs_out
->status
.nickname
));
3467 rs_out
->status
.is_valid
= n_valid
> n_statuses
/2;
3468 rs_out
->status
.is_running
= n_running
> n_recent
/2;
3469 rs_out
->status
.is_exit
= n_exit
> n_statuses
/2;
3470 rs_out
->status
.is_fast
= n_fast
> n_statuses
/2;
3471 rs_out
->status
.is_possible_guard
= n_guard
> n_statuses
/2;
3472 rs_out
->status
.is_stable
= n_stable
> n_statuses
/2;
3473 rs_out
->status
.is_v2_dir
= n_v2_dir
> n_statuses
/2;
3474 rs_out
->status
.is_bad_exit
= n_bad_exit
> n_listing_bad_exits
/2;
3475 rs_out
->status
.is_bad_directory
=
3476 n_bad_directory
> n_listing_bad_directories
/2;
3477 rs_out
->status
.version_known
= n_version_known
> 0;
3478 rs_out
->status
.version_supports_begindir
=
3479 n_supports_begindir
> n_version_known
/2;
3480 if (!rs_old
|| memcmp(rs_old
, rs_out
, sizeof(local_routerstatus_t
)))
3481 smartlist_add(changed_list
, rs_out
);
3483 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
3484 local_routerstatus_free(rs
));
3486 smartlist_free(routerstatus_list
);
3487 routerstatus_list
= result
;
3489 tor_free(networkstatus
);
3492 tor_free(digest_counts
);
3493 strmap_free(name_map
, NULL
);
3495 networkstatus_list_has_changed
= 0;
3496 routerstatus_list_has_changed
= 1;
3498 control_event_networkstatus_changed(changed_list
);
3499 smartlist_free(changed_list
);
3502 /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
3503 * is_named, is_valid, and is_running fields according to our current
3504 * networkstatus_t documents. */
3506 routers_update_status_from_networkstatus(smartlist_t
*routers
,
3509 trusted_dir_server_t
*ds
;
3510 local_routerstatus_t
*rs
;
3511 or_options_t
*options
= get_options();
3512 int authdir
= options
->AuthoritativeDir
;
3513 int namingdir
= options
->AuthoritativeDir
&&
3514 options
->NamingAuthoritativeDir
;
3516 if (!routerstatus_list
)
3519 SMARTLIST_FOREACH(routers
, routerinfo_t
*, router
,
3521 const char *digest
= router
->cache_info
.identity_digest
;
3522 rs
= router_get_combined_status_by_digest(digest
);
3523 ds
= router_get_trusteddirserver_by_digest(digest
);
3529 router
->is_named
= rs
->status
.is_named
;
3532 /* If we're not an authdir, believe others. */
3533 router
->is_valid
= rs
->status
.is_valid
;
3534 router
->is_running
= rs
->status
.is_running
;
3535 router
->is_fast
= rs
->status
.is_fast
;
3536 router
->is_stable
= rs
->status
.is_stable
;
3537 router
->is_possible_guard
= rs
->status
.is_possible_guard
;
3538 router
->is_exit
= rs
->status
.is_exit
;
3539 router
->is_bad_exit
= rs
->status
.is_bad_exit
;
3541 if (router
->is_running
&& ds
) {
3542 ds
->n_networkstatus_failures
= 0;
3544 if (reset_failures
) {
3545 rs
->n_download_failures
= 0;
3546 rs
->next_attempt_at
= 0;
3549 router_dir_info_changed();
3552 /** For every router descriptor we are currently downloading by descriptor
3553 * digest, set result[d] to 1. */
3555 list_pending_descriptor_downloads(digestmap_t
*result
)
3557 const char *prefix
= "d/";
3558 size_t p_len
= strlen(prefix
);
3560 connection_t
**carray
;
3561 smartlist_t
*tmp
= smartlist_create();
3564 get_connection_array(&carray
, &n_conns
);
3566 for (i
= 0; i
< n_conns
; ++i
) {
3567 connection_t
*conn
= carray
[i
];
3568 if (conn
->type
== CONN_TYPE_DIR
&&
3569 conn
->purpose
== DIR_PURPOSE_FETCH_SERVERDESC
&&
3570 !conn
->marked_for_close
) {
3571 const char *resource
= TO_DIR_CONN(conn
)->requested_resource
;
3572 if (!strcmpstart(resource
, prefix
))
3573 dir_split_resource_into_fingerprints(resource
+ p_len
,
3577 SMARTLIST_FOREACH(tmp
, char *, d
,
3579 digestmap_set(result
, d
, (void*)1);
3582 smartlist_free(tmp
);
3585 /** Launch downloads for all the descriptors whose digests are listed
3586 * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
3587 * If <b>source</b> is given, download from <b>source</b>; otherwise,
3588 * download from an appropriate random directory server.
3591 initiate_descriptor_downloads(routerstatus_t
*source
,
3592 smartlist_t
*digests
,
3596 char *resource
, *cp
;
3602 if (hi
> smartlist_len(digests
))
3603 hi
= smartlist_len(digests
);
3605 r_len
= 8 + (HEX_DIGEST_LEN
+1)*n
;
3606 cp
= resource
= tor_malloc(r_len
);
3607 memcpy(cp
, "d/", 2);
3609 for (i
= lo
; i
< hi
; ++i
) {
3610 base16_encode(cp
, r_len
-(cp
-resource
),
3611 smartlist_get(digests
,i
), DIGEST_LEN
);
3612 cp
+= HEX_DIGEST_LEN
;
3615 memcpy(cp
-1, ".z", 3);
3618 /* We know which authority we want. */
3619 directory_initiate_command_routerstatus(source
,
3620 DIR_PURPOSE_FETCH_SERVERDESC
,
3621 0, /* not private */
3624 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC
,
3631 /** Clients don't download any descriptor this recent, since it will probably
3632 * not have propageted to enough caches. */
3633 #define ESTIMATED_PROPAGATION_TIME (10*60)
3635 /** Return 0 if this routerstatus is obsolete, too new, isn't
3636 * running, or otherwise not a descriptor that we would make any
3637 * use of even if we had it. Else return 1. */
3639 client_would_use_router(routerstatus_t
*rs
, time_t now
, or_options_t
*options
)
3641 if (!rs
->is_running
&& !options
->FetchUselessDescriptors
) {
3642 /* If we had this router descriptor, we wouldn't even bother using it.
3643 * But, if we want to have a complete list, fetch it anyway. */
3646 if (rs
->published_on
+ ESTIMATED_PROPAGATION_TIME
> now
) {
3647 /* Most caches probably don't have this descriptor yet. */
3653 /** Return new list of ID fingerprints for routers that we (as a client) would
3656 static smartlist_t
*
3657 router_list_client_downloadable(void)
3659 int n_downloadable
= 0;
3660 smartlist_t
*downloadable
= smartlist_create();
3661 digestmap_t
*downloading
;
3662 time_t now
= time(NULL
);
3663 /* these are just used for logging */
3664 int n_not_ready
= 0, n_in_progress
= 0, n_uptodate
= 0, n_wouldnt_use
= 0;
3665 or_options_t
*options
= get_options();
3667 if (!routerstatus_list
)
3668 return downloadable
;
3670 downloading
= digestmap_new();
3671 list_pending_descriptor_downloads(downloading
);
3673 routerstatus_list_update_from_networkstatus(now
);
3674 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
3677 if (router_get_by_descriptor_digest(rs
->status
.descriptor_digest
)) {
3678 /* We have the 'best' descriptor for this router. */
3680 } else if (!client_would_use_router(&rs
->status
, now
, options
)) {
3681 /* We wouldn't want this descriptor even if we got it. */
3683 } else if (digestmap_get(downloading
, rs
->status
.descriptor_digest
)) {
3684 /* We're downloading this one now. */
3686 } else if ((ri
= router_get_by_digest(rs
->status
.identity_digest
)) &&
3687 ri
->cache_info
.published_on
> rs
->status
.published_on
) {
3688 /* Oddly, we have a descriptor more recent than the 'best' one, but it
3689 was once best. So that's okay. */
3691 } else if (rs
->next_attempt_at
> now
) {
3692 /* We failed too recently to try again. */
3695 /* Okay, time to try it. */
3696 smartlist_add(downloadable
, rs
->status
.descriptor_digest
);
3703 "%d router descriptors are downloadable. "
3704 "%d are in progress. %d are up-to-date. "
3705 "%d are non-useful. %d failed too recently to retry.",
3706 n_downloadable
, n_in_progress
, n_uptodate
,
3707 n_wouldnt_use
, n_not_ready
);
3710 digestmap_free(downloading
, NULL
);
3711 return downloadable
;
3714 /** Initiate new router downloads as needed, using the strategy for
3715 * non-directory-servers.
3717 * We only allow one router descriptor download at a time.
3718 * If we have less than two network-status documents, we ask
3719 * a directory for "all descriptors."
3720 * Otherwise, we ask for all descriptors that we think are different
3721 * from what we have.
3723 * DOCDOC The above comment doesn't match the behavior of the function.
3724 * I guess one of them is wrong, and I guess it's the comment. -RD
3727 update_router_descriptor_client_downloads(time_t now
)
3729 /* Max amount of hashes to download per request.
3730 * Since squid does not like URLs >= 4096 bytes we limit it to 96.
3731 * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
3732 * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
3733 * So use 96 because it's a nice number.
3735 #define MAX_DL_PER_REQUEST 96
3736 /** Don't split our requests so finely that we are requesting fewer than
3737 * this number per server. */
3738 #define MIN_DL_PER_REQUEST 4
3739 /** To prevent a single screwy cache from confusing us by selective reply,
3740 * try to split our requests into at least this this many requests. */
3741 #define MIN_REQUESTS 3
3742 /** If we want fewer than this many descriptors, wait until we
3743 * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
3745 #define MAX_DL_TO_DELAY 16
3746 /** When directory clients have only a few servers to request, they batch
3747 * them until they have more, or until this amount of time has passed. */
3748 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
3749 smartlist_t
*downloadable
= NULL
;
3750 int should_delay
, n_downloadable
;
3751 or_options_t
*options
= get_options();
3753 if (options
->DirPort
) {
3755 "Called router_descriptor_client_downloads() on a dir mirror?");
3758 if (rep_hist_circbuilding_dormant(now
)) {
3759 log_info(LD_CIRC
, "Skipping descriptor downloads: we haven't needed "
3760 "any circuits lately.");
3764 if (networkstatus_list
&&
3765 smartlist_len(networkstatus_list
) <= get_n_v2_authorities()/2) {
3767 "Not enough networkstatus documents to launch requests.");
3771 downloadable
= router_list_client_downloadable();
3772 n_downloadable
= smartlist_len(downloadable
);
3773 if (n_downloadable
>= MAX_DL_TO_DELAY
) {
3775 "There are enough downloadable routerdescs to launch requests.");
3777 } else if (n_downloadable
== 0) {
3778 // log_debug(LD_DIR, "No routerdescs need to be downloaded.");
3781 should_delay
= (last_routerdesc_download_attempted
+
3782 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST
) > now
;
3783 if (!should_delay
) {
3784 if (last_routerdesc_download_attempted
) {
3786 "There are not many downloadable routerdescs, but we've "
3787 "been waiting long enough (%d seconds). Downloading.",
3788 (int)(now
-last_routerdesc_download_attempted
));
3791 "There are not many downloadable routerdescs, but we haven't "
3792 "tried downloading descriptors recently. Downloading.");
3797 if (! should_delay
) {
3798 int i
, n_per_request
;
3799 n_per_request
= (n_downloadable
+MIN_REQUESTS
-1) / MIN_REQUESTS
;
3800 if (n_per_request
> MAX_DL_PER_REQUEST
)
3801 n_per_request
= MAX_DL_PER_REQUEST
;
3802 if (n_per_request
< MIN_DL_PER_REQUEST
)
3803 n_per_request
= MIN_DL_PER_REQUEST
;
3806 "Launching %d request%s for %d router%s, %d at a time",
3807 (n_downloadable
+n_per_request
-1)/n_per_request
,
3808 n_downloadable
>n_per_request
?"s":"",
3809 n_downloadable
, n_downloadable
>1?"s":"", n_per_request
);
3810 smartlist_sort_digests(downloadable
);
3811 for (i
=0; i
< n_downloadable
; i
+= n_per_request
) {
3812 initiate_descriptor_downloads(NULL
, downloadable
, i
, i
+n_per_request
);
3814 last_routerdesc_download_attempted
= now
;
3816 smartlist_free(downloadable
);
3819 /** Launch downloads for router status as needed, using the strategy used by
3820 * authorities and caches: download every descriptor we don't have but would
3821 * serve, from a random authority that lists it. */
3823 update_router_descriptor_cache_downloads(time_t now
)
3825 smartlist_t
**downloadable
; /* For each authority, what can we dl from it? */
3826 smartlist_t
**download_from
; /* ... and, what will we dl from it? */
3827 digestmap_t
*map
; /* Which descs are in progress, or assigned? */
3830 or_options_t
*options
= get_options();
3833 if (!options
->DirPort
) {
3834 log_warn(LD_BUG
, "Called update_router_descriptor_cache_downloads() "
3835 "on a non-dir-mirror?");
3838 if (!networkstatus_list
|| !smartlist_len(networkstatus_list
))
3841 map
= digestmap_new();
3842 n
= smartlist_len(networkstatus_list
);
3844 downloadable
= tor_malloc_zero(sizeof(smartlist_t
*) * n
);
3845 download_from
= tor_malloc_zero(sizeof(smartlist_t
*) * n
);
3847 /* Set map[d]=1 for the digest of every descriptor that we are currently
3849 list_pending_descriptor_downloads(map
);
3851 /* For the digest of every descriptor that we don't have, and that we aren't
3852 * downloading, add d to downloadable[i] if the i'th networkstatus knows
3853 * about that descriptor, and we haven't already failed to get that
3854 * descriptor from the corresponding authority.
3857 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
3859 smartlist_t
*dl
= smartlist_create();
3860 downloadable
[ns_sl_idx
] = dl
;
3861 download_from
[ns_sl_idx
] = smartlist_create();
3862 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
* , rs
,
3864 if (!rs
->need_to_mirror
)
3866 if (router_get_by_descriptor_digest(rs
->descriptor_digest
)) {
3868 "Bug: We have a router descriptor, but need_to_mirror=1.");
3869 rs
->need_to_mirror
= 0;
3872 if (options
->AuthoritativeDir
&& dirserv_would_reject_router(rs
)) {
3873 rs
->need_to_mirror
= 0;
3876 if (digestmap_get(map
, rs
->descriptor_digest
)) {
3877 /* We're downloading it already. */
3880 /* We could download it from this guy. */
3881 smartlist_add(dl
, rs
->descriptor_digest
);
3887 /* At random, assign descriptors to authorities such that:
3888 * - if d is a member of some downloadable[x], d is a member of some
3889 * download_from[y]. (Everything we want to download, we try to download
3891 * - If d is a member of download_from[y], d is a member of downloadable[y].
3892 * (We only try to download descriptors from authorities who claim to have
3894 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
3895 * (We don't try to download anything from two authorities concurrently.)
3897 while (n_download
) {
3898 int which_ns
= crypto_rand_int(n
);
3899 smartlist_t
*dl
= downloadable
[which_ns
];
3903 if (!smartlist_len(dl
))
3905 idx
= crypto_rand_int(smartlist_len(dl
));
3906 d
= smartlist_get(dl
, idx
);
3907 if (! digestmap_get(map
, d
)) {
3908 smartlist_add(download_from
[which_ns
], d
);
3909 digestmap_set(map
, d
, (void*) 1);
3911 smartlist_del(dl
, idx
);
3915 /* Now, we can actually launch our requests. */
3916 for (i
=0; i
<n
; ++i
) {
3917 networkstatus_t
*ns
= smartlist_get(networkstatus_list
, i
);
3918 trusted_dir_server_t
*ds
=
3919 router_get_trusteddirserver_by_digest(ns
->identity_digest
);
3920 smartlist_t
*dl
= download_from
[i
];
3922 log_warn(LD_BUG
, "Networkstatus with no corresponding authority!");
3925 if (! smartlist_len(dl
))
3927 log_info(LD_DIR
, "Requesting %d descriptors from authority \"%s\"",
3928 smartlist_len(dl
), ds
->nickname
);
3929 for (j
=0; j
< smartlist_len(dl
); j
+= MAX_DL_PER_REQUEST
) {
3930 initiate_descriptor_downloads(&(ds
->fake_status
.status
), dl
, j
,
3931 j
+MAX_DL_PER_REQUEST
);
3935 for (i
=0; i
<n
; ++i
) {
3936 smartlist_free(download_from
[i
]);
3937 smartlist_free(downloadable
[i
]);
3939 tor_free(download_from
);
3940 tor_free(downloadable
);
3941 digestmap_free(map
,NULL
);
3944 /** Launch downloads for router status as needed. */
3946 update_router_descriptor_downloads(time_t now
)
3948 or_options_t
*options
= get_options();
3949 if (options
->DirPort
) {
3950 update_router_descriptor_cache_downloads(now
);
3952 update_router_descriptor_client_downloads(now
);
3957 routerstatus_count_usable_entries(smartlist_t
*entries
)
3960 time_t now
= time(NULL
);
3961 or_options_t
*options
= get_options();
3962 SMARTLIST_FOREACH(entries
, routerstatus_t
*, rs
,
3963 if (client_would_use_router(rs
, now
, options
)) count
++);
3967 static int have_min_dir_info
= 0;
3968 static int need_to_update_have_min_dir_info
= 1;
3970 /** Return true iff we have enough networkstatus and router information to
3971 * start building circuits. Right now, this means "more than half the
3972 * networkstatus documents, and at least 1/4 of expected routers." */
3973 //XXX should consider whether we have enough exiting nodes here.
3975 router_have_minimum_dir_info(void)
3977 if (need_to_update_have_min_dir_info
) {
3978 update_router_have_minimum_dir_info();
3979 need_to_update_have_min_dir_info
= 0;
3981 return have_min_dir_info
;
3984 /** Called when our internal view of the directory has changed. This can be
3985 * when the authorities change, networkstatuses change, the list of routerdescs
3986 * changes, or number of running routers changes.
3989 router_dir_info_changed(void)
3991 need_to_update_have_min_dir_info
= 1;
3994 /** Change the value of have_min_dir_info, setting it true iff we have enough
3995 * network and router information to build circuits. Clear the value of
3996 * need_to_update_have_min_dir_info. */
3998 update_router_have_minimum_dir_info(void)
4000 int tot
= 0, num_running
= 0;
4001 int n_ns
, n_authorities
, res
, avg
;
4002 if (!networkstatus_list
|| !routerlist
) {
4006 n_authorities
= get_n_v2_authorities();
4007 n_ns
= smartlist_len(networkstatus_list
);
4008 if (n_ns
<=n_authorities
/2) {
4010 "We have %d of %d network statuses, and we want "
4011 "more than %d.", n_ns
, n_authorities
, n_authorities
/2);
4015 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
4016 tot
+= routerstatus_count_usable_entries(ns
->entries
));
4018 if (!routerstatus_list
)
4019 routerstatus_list
= smartlist_create();
4020 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
4022 if (rs
->status
.is_running
)
4025 res
= smartlist_len(routerlist
->routers
) >= (avg
/4) && num_running
> 2;
4027 if (res
&& !have_min_dir_info
) {
4028 log(LOG_NOTICE
, LD_DIR
,
4029 "We now have enough directory information to build circuits.");
4030 control_event_client_status(LOG_NOTICE
, "ENOUGH_DIR_INFO");
4032 if (!res
&& have_min_dir_info
) {
4033 log(LOG_NOTICE
, LD_DIR
,"Our directory information is no longer up-to-date "
4034 "enough to build circuits.%s",
4035 num_running
> 2 ? "" : " (Not enough servers seem reachable -- "
4036 "is your network connection down?)");
4037 control_event_client_status(LOG_NOTICE
, "NOT_ENOUGH_DIR_INFO");
4039 have_min_dir_info
= res
;
4042 /** Return true iff we have downloaded, or attempted to download at least
4043 * n_failures times, a network status for each authority. */
4045 have_tried_downloading_all_statuses(int n_failures
)
4047 if (!trusted_dir_servers
)
4050 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
4052 if (!ds
->is_v2_authority
)
4054 /* If we don't have the status, and we haven't failed to get the status,
4055 * we haven't tried to get the status. */
4056 if (!networkstatus_get_by_digest(ds
->digest
) &&
4057 ds
->n_networkstatus_failures
<= n_failures
)
4064 /** Reset the descriptor download failure count on all routers, so that we
4065 * can retry any long-failed routers immediately.
4068 router_reset_descriptor_download_failures(void)
4070 if (!routerstatus_list
)
4072 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, rs
,
4074 rs
->n_download_failures
= 0;
4075 rs
->next_attempt_at
= 0;
4077 tor_assert(networkstatus_list
);
4078 SMARTLIST_FOREACH(networkstatus_list
, networkstatus_t
*, ns
,
4079 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
*, rs
,
4081 if (!router_get_by_descriptor_digest(rs
->descriptor_digest
))
4082 rs
->need_to_mirror
= 1;
4084 last_routerdesc_download_attempted
= 0;
4087 /** Any changes in a router descriptor's publication time larger than this are
4088 * automatically non-cosmetic. */
4089 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
4091 /** We allow uptime to vary from how much it ought to be by this much. */
4092 #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
4094 /** Return true iff the only differences between r1 and r2 are such that
4095 * would not cause a recent (post 0.1.1.6) dirserver to republish.
4098 router_differences_are_cosmetic(routerinfo_t
*r1
, routerinfo_t
*r2
)
4100 time_t r1pub
, r2pub
;
4101 int time_difference
;
4102 tor_assert(r1
&& r2
);
4104 /* r1 should be the one that was published first. */
4105 if (r1
->cache_info
.published_on
> r2
->cache_info
.published_on
) {
4106 routerinfo_t
*ri_tmp
= r2
;
4111 /* If any key fields differ, they're different. */
4112 if (strcasecmp(r1
->address
, r2
->address
) ||
4113 strcasecmp(r1
->nickname
, r2
->nickname
) ||
4114 r1
->or_port
!= r2
->or_port
||
4115 r1
->dir_port
!= r2
->dir_port
||
4116 crypto_pk_cmp_keys(r1
->onion_pkey
, r2
->onion_pkey
) ||
4117 crypto_pk_cmp_keys(r1
->identity_pkey
, r2
->identity_pkey
) ||
4118 strcasecmp(r1
->platform
, r2
->platform
) ||
4119 (r1
->contact_info
&& !r2
->contact_info
) || /* contact_info is optional */
4120 (!r1
->contact_info
&& r2
->contact_info
) ||
4121 (r1
->contact_info
&& r2
->contact_info
&&
4122 strcasecmp(r1
->contact_info
, r2
->contact_info
)) ||
4123 r1
->is_hibernating
!= r2
->is_hibernating
||
4124 r1
->has_old_dnsworkers
!= r2
->has_old_dnsworkers
||
4125 cmp_addr_policies(r1
->exit_policy
, r2
->exit_policy
))
4127 if ((r1
->declared_family
== NULL
) != (r2
->declared_family
== NULL
))
4129 if (r1
->declared_family
&& r2
->declared_family
) {
4131 if (smartlist_len(r1
->declared_family
)!=smartlist_len(r2
->declared_family
))
4133 n
= smartlist_len(r1
->declared_family
);
4134 for (i
=0; i
< n
; ++i
) {
4135 if (strcasecmp(smartlist_get(r1
->declared_family
, i
),
4136 smartlist_get(r2
->declared_family
, i
)))
4141 /* Did bandwidth change a lot? */
4142 if ((r1
->bandwidthcapacity
< r2
->bandwidthcapacity
/2) ||
4143 (r2
->bandwidthcapacity
< r1
->bandwidthcapacity
/2))
4146 /* Did more than 12 hours pass? */
4147 if (r1
->cache_info
.published_on
+ ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
4148 < r2
->cache_info
.published_on
)
4151 /* Did uptime fail to increase by approximately the amount we would think,
4152 * give or take some slop? */
4153 r1pub
= r1
->cache_info
.published_on
;
4154 r2pub
= r2
->cache_info
.published_on
;
4155 time_difference
= abs(r2
->uptime
- (r1
->uptime
+ (r2pub
- r1pub
)));
4156 if (time_difference
> ROUTER_ALLOW_UPTIME_DRIFT
&&
4157 time_difference
> r1
->uptime
* .05 &&
4158 time_difference
> r2
->uptime
* .05)
4161 /* Otherwise, the difference is cosmetic. */
4165 /** Generate networkstatus lines for a single routerstatus_t object, and
4166 * return the result in a newly allocated string. Used only by controller
4167 * interface (for now.) */
4168 /* XXXX This should eventually merge into generate_v2_networkstatus() */
4170 networkstatus_getinfo_helper_single(routerstatus_t
*rs
)
4177 char published
[ISO_TIME_LEN
+1];
4178 char ipaddr
[INET_NTOA_BUF_LEN
];
4179 char identity64
[BASE64_DIGEST_LEN
+1];
4180 char digest64
[BASE64_DIGEST_LEN
+1];
4182 format_iso_time(published
, rs
->published_on
);
4183 digest_to_base64(identity64
, rs
->identity_digest
);
4184 digest_to_base64(digest64
, rs
->descriptor_digest
);
4185 in
.s_addr
= htonl(rs
->addr
);
4186 tor_inet_ntoa(&in
, ipaddr
, sizeof(ipaddr
));
4188 f_authority
= router_digest_is_trusted_dir(rs
->identity_digest
);
4190 r
= tor_snprintf(buf
, sizeof(buf
),
4191 "r %s %s %s %s %s %d %d\n"
4192 "s%s%s%s%s%s%s%s%s%s%s\n",
4201 f_authority
?" Authority":"",
4202 rs
->is_bad_exit
?" BadExit":"",
4203 rs
->is_exit
?" Exit":"",
4204 rs
->is_fast
?" Fast":"",
4205 rs
->is_possible_guard
?" Guard":"",
4206 rs
->is_named
?" Named":"",
4207 rs
->is_stable
?" Stable":"",
4208 rs
->is_running
?" Running":"",
4209 rs
->is_valid
?" Valid":"",
4210 rs
->is_v2_dir
?" V2Dir":"");
4212 log_warn(LD_BUG
, "Not enough space in buffer.");
4214 return tor_strdup(buf
);
4217 /** If <b>question</b> is a string beginning with "ns/" in a format the
4218 * control interface expects for a GETINFO question, set *<b>answer</b> to a
4219 * newly-allocated string containing networkstatus lines for the appropriate
4220 * ORs. Return 0 on success, -1 on unrecognized question format. */
4222 getinfo_helper_networkstatus(control_connection_t
*conn
,
4223 const char *question
, char **answer
)
4225 local_routerstatus_t
*status
;
4228 if (!routerstatus_list
) {
4229 *answer
= tor_strdup("");
4233 if (!strcmp(question
, "ns/all")) {
4234 smartlist_t
*statuses
= smartlist_create();
4235 SMARTLIST_FOREACH(routerstatus_list
, local_routerstatus_t
*, lrs
,
4237 routerstatus_t
*rs
= &(lrs
->status
);
4238 smartlist_add(statuses
, networkstatus_getinfo_helper_single(rs
));
4240 *answer
= smartlist_join_strings(statuses
, "", 0, NULL
);
4241 SMARTLIST_FOREACH(statuses
, char *, cp
, tor_free(cp
));
4242 smartlist_free(statuses
);
4244 } else if (!strcmpstart(question
, "ns/id/")) {
4247 if (base16_decode(d
, DIGEST_LEN
, question
+6, strlen(question
+6)))
4249 status
= router_get_combined_status_by_digest(d
);
4250 } else if (!strcmpstart(question
, "ns/name/")) {
4251 status
= router_get_combined_status_by_nickname(question
+8, 0);
4257 *answer
= networkstatus_getinfo_helper_single(&status
->status
);
4262 /** Assert that the internal representation of <b>rl</b> is
4263 * self-consistent. */
4265 routerlist_assert_ok(routerlist_t
*rl
)
4267 digestmap_iter_t
*iter
;
4269 signed_descriptor_t
*sd2
;
4272 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
4274 r2
= digestmap_get(rl
->identity_map
, r
->cache_info
.identity_digest
);
4275 tor_assert(r
== r2
);
4276 sd2
= digestmap_get(rl
->desc_digest_map
,
4277 r
->cache_info
.signed_descriptor_digest
);
4278 tor_assert(&(r
->cache_info
) == sd2
);
4279 tor_assert(r
->routerlist_index
== r_sl_idx
);
4281 SMARTLIST_FOREACH(rl
->old_routers
, signed_descriptor_t
*, sd
,
4283 r2
= digestmap_get(rl
->identity_map
, sd
->identity_digest
);
4284 tor_assert(sd
!= &(r2
->cache_info
));
4285 sd2
= digestmap_get(rl
->desc_digest_map
, sd
->signed_descriptor_digest
);
4286 tor_assert(sd
== sd2
);
4288 iter
= digestmap_iter_init(rl
->identity_map
);
4289 while (!digestmap_iter_done(iter
)) {
4293 digestmap_iter_get(iter
, &d
, &_r
);
4295 tor_assert(!memcmp(r
->cache_info
.identity_digest
, d
, DIGEST_LEN
));
4296 iter
= digestmap_iter_next(rl
->identity_map
, iter
);
4298 iter
= digestmap_iter_init(rl
->desc_digest_map
);
4299 while (!digestmap_iter_done(iter
)) {
4302 signed_descriptor_t
*sd
;
4303 digestmap_iter_get(iter
, &d
, &_sd
);
4305 tor_assert(!memcmp(sd
->signed_descriptor_digest
, d
, DIGEST_LEN
));
4306 iter
= digestmap_iter_next(rl
->desc_digest_map
, iter
);
4310 /** Allocate and return a new string representing the contact info
4311 * and platform string for <b>router</b>,
4312 * surrounded by quotes and using standard C escapes.
4314 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
4315 * thread. Also, each call invalidates the last-returned value, so don't
4316 * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
4319 esc_router_info(routerinfo_t
*router
)
4322 char *esc_contact
, *esc_platform
;
4327 esc_contact
= esc_for_log(router
->contact_info
);
4328 esc_platform
= esc_for_log(router
->platform
);
4330 len
= strlen(esc_contact
)+strlen(esc_platform
)+32;
4331 info
= tor_malloc(len
);
4332 tor_snprintf(info
, len
, "Contact %s, Platform %s", esc_contact
,
4334 tor_free(esc_contact
);
4335 tor_free(esc_platform
);