1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
10 * maintain and access the global list of routerinfos for known
14 #define ROUTERLIST_PRIVATE
16 #include "circuitstats.h"
18 #include "connection.h"
20 #include "directory.h"
23 #include "entrynodes.h"
25 #include "hibernate.h"
27 #include "microdesc.h"
28 #include "networkstatus.h"
32 #include "rendcommon.h"
33 #include "rendservice.h"
36 #include "routerlist.h"
37 #include "routerparse.h"
38 #include "routerset.h"
40 // #define DEBUG_ROUTERLIST
42 /****************************************************************************/
44 /* static function prototypes */
45 static int compute_weighted_bandwidths(const smartlist_t
*sl
,
46 bandwidth_weight_rule_t rule
,
47 u64_dbl_t
**bandwidths_out
);
48 static const routerstatus_t
*router_pick_directory_server_impl(
49 dirinfo_type_t auth
, int flags
);
50 static const routerstatus_t
*router_pick_trusteddirserver_impl(
51 const smartlist_t
*sourcelist
, dirinfo_type_t auth
,
52 int flags
, int *n_busy_out
);
53 static const routerstatus_t
*router_pick_dirserver_generic(
54 smartlist_t
*sourcelist
,
55 dirinfo_type_t type
, int flags
);
56 static void mark_all_dirservers_up(smartlist_t
*server_list
);
57 static void dir_server_free(dir_server_t
*ds
);
58 static int signed_desc_digest_is_recognized(signed_descriptor_t
*desc
);
59 static const char *signed_descriptor_get_body_impl(
60 const signed_descriptor_t
*desc
,
61 int with_annotations
);
62 static void list_pending_downloads(digestmap_t
*result
,
63 int purpose
, const char *prefix
);
64 static void launch_dummy_descriptor_download_as_needed(time_t now
,
65 const or_options_t
*options
);
67 DECLARE_TYPED_DIGESTMAP_FNS(sdmap_
, digest_sd_map_t
, signed_descriptor_t
)
68 DECLARE_TYPED_DIGESTMAP_FNS(rimap_
, digest_ri_map_t
, routerinfo_t
)
69 DECLARE_TYPED_DIGESTMAP_FNS(eimap_
, digest_ei_map_t
, extrainfo_t
)
70 #define SDMAP_FOREACH(map, keyvar, valvar) \
71 DIGESTMAP_FOREACH(sdmap_to_digestmap(map), keyvar, signed_descriptor_t *, \
73 #define RIMAP_FOREACH(map, keyvar, valvar) \
74 DIGESTMAP_FOREACH(rimap_to_digestmap(map), keyvar, routerinfo_t *, valvar)
75 #define EIMAP_FOREACH(map, keyvar, valvar) \
76 DIGESTMAP_FOREACH(eimap_to_digestmap(map), keyvar, extrainfo_t *, valvar)
78 /****************************************************************************/
80 /** Global list of a dir_server_t object for each directory
82 static smartlist_t
*trusted_dir_servers
= NULL
;
83 /** Global list of dir_server_t objects for all directory authorities
84 * and all fallback directory servers. */
85 static smartlist_t
*fallback_dir_servers
= NULL
;
87 /** List of for a given authority, and download status for latest certificate.
89 typedef struct cert_list_t
{
90 download_status_t dl_status
;
93 /** Map from v3 identity key digest to cert_list_t. */
94 static digestmap_t
*trusted_dir_certs
= NULL
;
95 /** True iff any key certificate in at least one member of
96 * <b>trusted_dir_certs</b> has changed since we last flushed the
97 * certificates to disk. */
98 static int trusted_dir_servers_certs_changed
= 0;
100 /** Global list of all of the routers that we know about. */
101 static routerlist_t
*routerlist
= NULL
;
103 /** List of strings for nicknames we've already warned about and that are
104 * still unknown / unavailable. */
105 static smartlist_t
*warned_nicknames
= NULL
;
107 /** The last time we tried to download any routerdesc, or 0 for "never". We
108 * use this to rate-limit download attempts when the number of routerdescs to
109 * download is low. */
110 static time_t last_descriptor_download_attempted
= 0;
112 /** When we last computed the weights to use for bandwidths on directory
113 * requests, what were the total weighted bandwidth, and our share of that
114 * bandwidth? Used to determine what fraction of directory requests we should
118 static uint64_t sl_last_total_weighted_bw
= 0,
119 sl_last_weighted_bw_of_me
= 0;
122 /** Return the number of directory authorities whose type matches some bit set
125 get_n_authorities(dirinfo_type_t type
)
128 if (!trusted_dir_servers
)
130 SMARTLIST_FOREACH(trusted_dir_servers
, dir_server_t
*, ds
,
136 #define get_n_v2_authorities() get_n_authorities(V2_DIRINFO)
138 /** Helper: Return the cert_list_t for an authority whose authority ID is
139 * <b>id_digest</b>, allocating a new list if necessary. */
141 get_cert_list(const char *id_digest
)
144 if (!trusted_dir_certs
)
145 trusted_dir_certs
= digestmap_new();
146 cl
= digestmap_get(trusted_dir_certs
, id_digest
);
148 cl
= tor_malloc_zero(sizeof(cert_list_t
));
149 cl
->dl_status
.schedule
= DL_SCHED_CONSENSUS
;
150 cl
->certs
= smartlist_new();
151 digestmap_set(trusted_dir_certs
, id_digest
, cl
);
156 /** Reload the cached v3 key certificates from the cached-certs file in
157 * the data directory. Return 0 on success, -1 on failure. */
159 trusted_dirs_reload_certs(void)
165 filename
= get_datadir_fname("cached-certs");
166 contents
= read_file_to_str(filename
, RFTS_IGNORE_MISSING
, NULL
);
170 r
= trusted_dirs_load_certs_from_string(contents
, 1, 1);
175 /** Helper: return true iff we already have loaded the exact cert
178 already_have_cert(authority_cert_t
*cert
)
180 cert_list_t
*cl
= get_cert_list(cert
->cache_info
.identity_digest
);
182 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, c
,
184 if (tor_memeq(c
->cache_info
.signed_descriptor_digest
,
185 cert
->cache_info
.signed_descriptor_digest
,
192 /** Load a bunch of new key certificates from the string <b>contents</b>. If
193 * <b>from_store</b> is true, the certificates are from the cache, and we
194 * don't need to flush them to disk. If <b>flush</b> is true, we need
195 * to flush any changed certificates to disk now. Return 0 on success, -1
196 * if any certs fail to parse. */
198 trusted_dirs_load_certs_from_string(const char *contents
, int from_store
,
203 int failure_code
= 0;
205 for (s
= contents
; *s
; s
= eos
) {
206 authority_cert_t
*cert
= authority_cert_parse_from_string(s
, &eos
);
212 ds
= trusteddirserver_get_by_v3_auth_digest(
213 cert
->cache_info
.identity_digest
);
214 log_debug(LD_DIR
, "Parsed certificate for %s",
215 ds
? ds
->nickname
: "unknown authority");
217 if (already_have_cert(cert
)) {
218 /* we already have this one. continue. */
219 log_info(LD_DIR
, "Skipping %s certificate for %s that we "
221 from_store
? "cached" : "downloaded",
222 ds
? ds
->nickname
: "an old or new authority");
224 /* a duplicate on a download should be treated as a failure, since it
225 * probably means we wanted a different secret key or we are trying to
226 * replace an expired cert that has not in fact been updated. */
228 if (authdir_mode(get_options())) {
230 "Got a certificate for %s, but we already have it. "
231 "Maybe they haven't updated it. Waiting for a while.",
232 ds
? ds
->nickname
: "an old or new authority");
235 "Got a certificate for %s, but we already have it. "
236 "Maybe they haven't updated it. Waiting for a while.",
237 ds
? ds
->nickname
: "an old or new authority");
240 authority_cert_dl_failed(cert
->cache_info
.identity_digest
, 404);
243 authority_cert_free(cert
);
248 log_info(LD_DIR
, "Adding %s certificate for directory authority %s with "
249 "signing key %s", from_store
? "cached" : "downloaded",
250 ds
->nickname
, hex_str(cert
->signing_key_digest
,DIGEST_LEN
));
252 int adding
= directory_caches_unknown_auth_certs(get_options());
253 log_info(LD_DIR
, "%s %s certificate for unrecognized directory "
254 "authority with signing key %s",
255 adding
? "Adding" : "Not adding",
256 from_store
? "cached" : "downloaded",
257 hex_str(cert
->signing_key_digest
,DIGEST_LEN
));
259 authority_cert_free(cert
);
264 cl
= get_cert_list(cert
->cache_info
.identity_digest
);
265 smartlist_add(cl
->certs
, cert
);
266 if (ds
&& cert
->cache_info
.published_on
> ds
->addr_current_at
) {
267 /* Check to see whether we should update our view of the authority's
269 if (cert
->addr
&& cert
->dir_port
&&
270 (ds
->addr
!= cert
->addr
||
271 ds
->dir_port
!= cert
->dir_port
)) {
272 char *a
= tor_dup_ip(cert
->addr
);
273 log_notice(LD_DIR
, "Updating address for directory authority %s "
274 "from %s:%d to %s:%d based on certificate.",
275 ds
->nickname
, ds
->address
, (int)ds
->dir_port
,
278 ds
->addr
= cert
->addr
;
279 ds
->dir_port
= cert
->dir_port
;
281 ds
->addr_current_at
= cert
->cache_info
.published_on
;
285 trusted_dir_servers_certs_changed
= 1;
289 trusted_dirs_flush_certs_to_disk();
291 /* call this even if failure_code is <0, since some certs might have
293 networkstatus_note_certs_arrived();
298 /** Save all v3 key certificates to the cached-certs file. */
300 trusted_dirs_flush_certs_to_disk(void)
305 if (!trusted_dir_servers_certs_changed
|| !trusted_dir_certs
)
308 chunks
= smartlist_new();
309 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
310 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
312 sized_chunk_t
*c
= tor_malloc(sizeof(sized_chunk_t
));
313 c
->bytes
= cert
->cache_info
.signed_descriptor_body
;
314 c
->len
= cert
->cache_info
.signed_descriptor_len
;
315 smartlist_add(chunks
, c
);
317 } DIGESTMAP_FOREACH_END
;
319 filename
= get_datadir_fname("cached-certs");
320 if (write_chunks_to_file(filename
, chunks
, 0)) {
321 log_warn(LD_FS
, "Error writing certificates to disk.");
324 SMARTLIST_FOREACH(chunks
, sized_chunk_t
*, c
, tor_free(c
));
325 smartlist_free(chunks
);
327 trusted_dir_servers_certs_changed
= 0;
330 /** Remove all v3 authority certificates that have been superseded for more
331 * than 48 hours. (If the most recent cert was published more than 48 hours
332 * ago, then we aren't going to get any consensuses signed with older
335 trusted_dirs_remove_old_certs(void)
337 time_t now
= time(NULL
);
338 #define DEAD_CERT_LIFETIME (2*24*60*60)
339 #define OLD_CERT_LIFETIME (7*24*60*60)
340 if (!trusted_dir_certs
)
343 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
344 authority_cert_t
*newest
= NULL
;
345 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
346 if (!newest
|| (cert
->cache_info
.published_on
>
347 newest
->cache_info
.published_on
))
350 const time_t newest_published
= newest
->cache_info
.published_on
;
351 SMARTLIST_FOREACH_BEGIN(cl
->certs
, authority_cert_t
*, cert
) {
353 time_t cert_published
;
356 expired
= now
> cert
->expires
;
357 cert_published
= cert
->cache_info
.published_on
;
358 /* Store expired certs for 48 hours after a newer arrives;
361 (newest_published
+ DEAD_CERT_LIFETIME
< now
) :
362 (cert_published
+ OLD_CERT_LIFETIME
< newest_published
)) {
363 SMARTLIST_DEL_CURRENT(cl
->certs
, cert
);
364 authority_cert_free(cert
);
365 trusted_dir_servers_certs_changed
= 1;
367 } SMARTLIST_FOREACH_END(cert
);
369 } DIGESTMAP_FOREACH_END
;
370 #undef OLD_CERT_LIFETIME
372 trusted_dirs_flush_certs_to_disk();
375 /** Return the newest v3 authority certificate whose v3 authority identity key
376 * has digest <b>id_digest</b>. Return NULL if no such authority is known,
377 * or it has no certificate. */
379 authority_cert_get_newest_by_id(const char *id_digest
)
382 authority_cert_t
*best
= NULL
;
383 if (!trusted_dir_certs
||
384 !(cl
= digestmap_get(trusted_dir_certs
, id_digest
)))
387 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
389 if (!best
|| cert
->cache_info
.published_on
> best
->cache_info
.published_on
)
395 /** Return the newest v3 authority certificate whose directory signing key has
396 * digest <b>sk_digest</b>. Return NULL if no such certificate is known.
399 authority_cert_get_by_sk_digest(const char *sk_digest
)
402 if (!trusted_dir_certs
)
405 if ((c
= get_my_v3_authority_cert()) &&
406 tor_memeq(c
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
408 if ((c
= get_my_v3_legacy_cert()) &&
409 tor_memeq(c
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
412 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
413 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
415 if (tor_memeq(cert
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
418 } DIGESTMAP_FOREACH_END
;
422 /** Return the v3 authority certificate with signing key matching
423 * <b>sk_digest</b>, for the authority with identity digest <b>id_digest</b>.
424 * Return NULL if no such authority is known. */
426 authority_cert_get_by_digests(const char *id_digest
,
427 const char *sk_digest
)
430 if (!trusted_dir_certs
||
431 !(cl
= digestmap_get(trusted_dir_certs
, id_digest
)))
433 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
434 if (tor_memeq(cert
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
440 /** Add every known authority_cert_t to <b>certs_out</b>. */
442 authority_cert_get_all(smartlist_t
*certs_out
)
444 tor_assert(certs_out
);
445 if (!trusted_dir_certs
)
448 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
449 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, c
,
450 smartlist_add(certs_out
, c
));
451 } DIGESTMAP_FOREACH_END
;
454 /** Called when an attempt to download a certificate with the authority with
455 * ID <b>id_digest</b> fails with HTTP response code <b>status</b>: remember
456 * the failure, so we don't try again immediately. */
458 authority_cert_dl_failed(const char *id_digest
, int status
)
461 if (!trusted_dir_certs
||
462 !(cl
= digestmap_get(trusted_dir_certs
, id_digest
)))
465 download_status_failed(&cl
->dl_status
, status
);
468 /** Return true iff when we've been getting enough failures when trying to
469 * download the certificate with ID digest <b>id_digest</b> that we're willing
470 * to start bugging the user about it. */
472 authority_cert_dl_looks_uncertain(const char *id_digest
)
474 #define N_AUTH_CERT_DL_FAILURES_TO_BUG_USER 2
477 if (!trusted_dir_certs
||
478 !(cl
= digestmap_get(trusted_dir_certs
, id_digest
)))
481 n_failures
= download_status_get_n_failures(&cl
->dl_status
);
482 return n_failures
>= N_AUTH_CERT_DL_FAILURES_TO_BUG_USER
;
485 /** How many times will we try to fetch a certificate before giving up? */
486 #define MAX_CERT_DL_FAILURES 8
488 /** Try to download any v3 authority certificates that we may be missing. If
489 * <b>status</b> is provided, try to get all the ones that were used to sign
490 * <b>status</b>. Additionally, try to have a non-expired certificate for
491 * every V3 authority in trusted_dir_servers. Don't fetch certificates we
495 authority_certs_fetch_missing(networkstatus_t
*status
, time_t now
)
497 digestmap_t
*pending
;
498 authority_cert_t
*cert
;
499 smartlist_t
*missing_digests
;
500 char *resource
= NULL
;
502 const int cache
= directory_caches_unknown_auth_certs(get_options());
504 if (should_delay_dir_fetches(get_options()))
507 pending
= digestmap_new();
508 missing_digests
= smartlist_new();
510 list_pending_downloads(pending
, DIR_PURPOSE_FETCH_CERTIFICATE
, "fp/");
512 SMARTLIST_FOREACH_BEGIN(status
->voters
, networkstatus_voter_info_t
*,
514 if (!smartlist_len(voter
->sigs
))
515 continue; /* This authority never signed this consensus, so don't
516 * go looking for a cert with key digest 0000000000. */
518 !trusteddirserver_get_by_v3_auth_digest(voter
->identity_digest
))
519 continue; /* We are not a cache, and we don't know this authority.*/
520 cl
= get_cert_list(voter
->identity_digest
);
521 SMARTLIST_FOREACH_BEGIN(voter
->sigs
, document_signature_t
*, sig
) {
522 cert
= authority_cert_get_by_digests(voter
->identity_digest
,
523 sig
->signing_key_digest
);
525 if (now
< cert
->expires
)
526 download_status_reset(&cl
->dl_status
);
529 if (download_status_is_ready(&cl
->dl_status
, now
,
530 MAX_CERT_DL_FAILURES
) &&
531 !digestmap_get(pending
, voter
->identity_digest
)) {
532 log_info(LD_DIR
, "We're missing a certificate from authority "
533 "with signing key %s: launching request.",
534 hex_str(sig
->signing_key_digest
, DIGEST_LEN
));
535 smartlist_add(missing_digests
, sig
->identity_digest
);
537 } SMARTLIST_FOREACH_END(sig
);
538 } SMARTLIST_FOREACH_END(voter
);
540 SMARTLIST_FOREACH_BEGIN(trusted_dir_servers
, dir_server_t
*, ds
) {
542 if (!(ds
->type
& V3_DIRINFO
))
544 if (smartlist_contains_digest(missing_digests
, ds
->v3_identity_digest
))
546 cl
= get_cert_list(ds
->v3_identity_digest
);
547 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
, {
548 if (now
< cert
->expires
) {
549 /* It's not expired, and we weren't looking for something to
550 * verify a consensus with. Call it done. */
551 download_status_reset(&cl
->dl_status
);
557 download_status_is_ready(&cl
->dl_status
, now
,MAX_CERT_DL_FAILURES
) &&
558 !digestmap_get(pending
, ds
->v3_identity_digest
)) {
559 log_info(LD_DIR
, "No current certificate known for authority %s; "
560 "launching request.", ds
->nickname
);
561 smartlist_add(missing_digests
, ds
->v3_identity_digest
);
563 } SMARTLIST_FOREACH_END(ds
);
565 if (!smartlist_len(missing_digests
)) {
568 smartlist_t
*fps
= smartlist_new();
569 smartlist_add(fps
, tor_strdup("fp/"));
570 SMARTLIST_FOREACH(missing_digests
, const char *, d
, {
572 if (digestmap_get(pending
, d
))
574 fp
= tor_malloc(HEX_DIGEST_LEN
+2);
575 base16_encode(fp
, HEX_DIGEST_LEN
+1, d
, DIGEST_LEN
);
576 fp
[HEX_DIGEST_LEN
] = '+';
577 fp
[HEX_DIGEST_LEN
+1] = '\0';
578 smartlist_add(fps
, fp
);
580 if (smartlist_len(fps
) == 1) {
581 /* we didn't add any: they were all pending */
582 SMARTLIST_FOREACH(fps
, char *, cp
, tor_free(cp
));
586 resource
= smartlist_join_strings(fps
, "", 0, NULL
);
587 resource
[strlen(resource
)-1] = '\0';
588 SMARTLIST_FOREACH(fps
, char *, cp
, tor_free(cp
));
591 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CERTIFICATE
, 0,
592 resource
, PDS_RETRY_IF_NO_SERVERS
);
596 smartlist_free(missing_digests
);
597 digestmap_free(pending
, NULL
);
600 /* Router descriptor storage.
602 * Routerdescs are stored in a big file, named "cached-descriptors". As new
603 * routerdescs arrive, we append them to a journal file named
604 * "cached-descriptors.new".
606 * From time to time, we replace "cached-descriptors" with a new file
607 * containing only the live, non-superseded descriptors, and clear
608 * cached-routers.new.
610 * On startup, we read both files.
613 /** Helper: return 1 iff the router log is so big we want to rebuild the
616 router_should_rebuild_store(desc_store_t
*store
)
618 if (store
->store_len
> (1<<16))
619 return (store
->journal_len
> store
->store_len
/ 2 ||
620 store
->bytes_dropped
> store
->store_len
/ 2);
622 return store
->journal_len
> (1<<15);
625 /** Return the desc_store_t in <b>rl</b> that should be used to store
627 static INLINE desc_store_t
*
628 desc_get_store(routerlist_t
*rl
, const signed_descriptor_t
*sd
)
630 if (sd
->is_extrainfo
)
631 return &rl
->extrainfo_store
;
633 return &rl
->desc_store
;
636 /** Add the signed_descriptor_t in <b>desc</b> to the router
637 * journal; change its saved_location to SAVED_IN_JOURNAL and set its
638 * offset appropriately. */
640 signed_desc_append_to_journal(signed_descriptor_t
*desc
,
643 char *fname
= get_datadir_fname_suffix(store
->fname_base
, ".new");
644 const char *body
= signed_descriptor_get_body_impl(desc
,1);
645 size_t len
= desc
->signed_descriptor_len
+ desc
->annotations_len
;
647 if (append_bytes_to_file(fname
, body
, len
, 1)) {
648 log_warn(LD_FS
, "Unable to store router descriptor");
652 desc
->saved_location
= SAVED_IN_JOURNAL
;
655 desc
->saved_offset
= store
->journal_len
;
656 store
->journal_len
+= len
;
661 /** Sorting helper: return <0, 0, or >0 depending on whether the
662 * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
663 * the signed_descriptor_t* in *<b>b</b>. */
665 compare_signed_descriptors_by_age_(const void **_a
, const void **_b
)
667 const signed_descriptor_t
*r1
= *_a
, *r2
= *_b
;
668 return (int)(r1
->published_on
- r2
->published_on
);
672 #define RRS_DONT_REMOVE_OLD 2
674 /** If the journal of <b>store</b> is too long, or if RRS_FORCE is set in
675 * <b>flags</b>, then atomically replace the saved router store with the
676 * routers currently in our routerlist, and clear the journal. Unless
677 * RRS_DONT_REMOVE_OLD is set in <b>flags</b>, delete expired routers before
678 * rebuilding the store. Return 0 on success, -1 on failure.
681 router_rebuild_store(int flags
, desc_store_t
*store
)
683 smartlist_t
*chunk_list
= NULL
;
684 char *fname
= NULL
, *fname_tmp
= NULL
;
687 smartlist_t
*signed_descriptors
= NULL
;
689 size_t total_expected_len
= 0;
691 int force
= flags
& RRS_FORCE
;
693 if (!force
&& !router_should_rebuild_store(store
)) {
702 if (store
->type
== EXTRAINFO_STORE
)
703 had_any
= !eimap_isempty(routerlist
->extra_info_map
);
705 had_any
= (smartlist_len(routerlist
->routers
)+
706 smartlist_len(routerlist
->old_routers
))>0;
708 /* Don't save deadweight. */
709 if (!(flags
& RRS_DONT_REMOVE_OLD
))
710 routerlist_remove_old_routers();
712 log_info(LD_DIR
, "Rebuilding %s cache", store
->description
);
714 fname
= get_datadir_fname(store
->fname_base
);
715 fname_tmp
= get_datadir_fname_suffix(store
->fname_base
, ".tmp");
717 chunk_list
= smartlist_new();
719 /* We sort the routers by age to enhance locality on disk. */
720 signed_descriptors
= smartlist_new();
721 if (store
->type
== EXTRAINFO_STORE
) {
723 for (iter
= eimap_iter_init(routerlist
->extra_info_map
);
724 !eimap_iter_done(iter
);
725 iter
= eimap_iter_next(routerlist
->extra_info_map
, iter
)) {
728 eimap_iter_get(iter
, &key
, &ei
);
729 smartlist_add(signed_descriptors
, &ei
->cache_info
);
732 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
,
733 smartlist_add(signed_descriptors
, sd
));
734 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
735 smartlist_add(signed_descriptors
, &ri
->cache_info
));
738 smartlist_sort(signed_descriptors
, compare_signed_descriptors_by_age_
);
740 /* Now, add the appropriate members to chunk_list */
741 SMARTLIST_FOREACH_BEGIN(signed_descriptors
, signed_descriptor_t
*, sd
) {
743 const char *body
= signed_descriptor_get_body_impl(sd
, 1);
745 log_warn(LD_BUG
, "No descriptor available for router.");
748 if (sd
->do_not_cache
) {
752 c
= tor_malloc(sizeof(sized_chunk_t
));
754 c
->len
= sd
->signed_descriptor_len
+ sd
->annotations_len
;
755 total_expected_len
+= c
->len
;
756 smartlist_add(chunk_list
, c
);
757 } SMARTLIST_FOREACH_END(sd
);
759 if (write_chunks_to_file(fname_tmp
, chunk_list
, 1)<0) {
760 log_warn(LD_FS
, "Error writing router store to disk.");
764 /* Our mmap is now invalid. */
766 tor_munmap_file(store
->mmap
);
770 if (replace_file(fname_tmp
, fname
)<0) {
771 log_warn(LD_FS
, "Error replacing old router store: %s", strerror(errno
));
776 store
->mmap
= tor_mmap_file(fname
);
778 if (errno
== ERANGE
) {
780 if (total_expected_len
) {
781 log_warn(LD_FS
, "We wrote some bytes to a new descriptor file at '%s',"
782 " but when we went to mmap it, it was empty!", fname
);
783 } else if (had_any
) {
784 log_info(LD_FS
, "We just removed every descriptor in '%s'. This is "
785 "okay if we're just starting up after a long time. "
786 "Otherwise, it's a bug.", fname
);
789 log_warn(LD_FS
, "Unable to mmap new descriptor file at '%s'.",fname
);
793 log_info(LD_DIR
, "Reconstructing pointers into cache");
796 SMARTLIST_FOREACH_BEGIN(signed_descriptors
, signed_descriptor_t
*, sd
) {
797 if (sd
->do_not_cache
)
799 sd
->saved_location
= SAVED_IN_CACHE
;
801 tor_free(sd
->signed_descriptor_body
); // sets it to null
802 sd
->saved_offset
= offset
;
804 offset
+= sd
->signed_descriptor_len
+ sd
->annotations_len
;
805 signed_descriptor_get_body(sd
); /* reconstruct and assert */
806 } SMARTLIST_FOREACH_END(sd
);
809 fname
= get_datadir_fname_suffix(store
->fname_base
, ".new");
810 write_str_to_file(fname
, "", 1);
813 store
->store_len
= (size_t) offset
;
814 store
->journal_len
= 0;
815 store
->bytes_dropped
= 0;
817 smartlist_free(signed_descriptors
);
821 SMARTLIST_FOREACH(chunk_list
, sized_chunk_t
*, c
, tor_free(c
));
822 smartlist_free(chunk_list
);
828 /** Helper: Reload a cache file and its associated journal, setting metadata
829 * appropriately. If <b>extrainfo</b> is true, reload the extrainfo store;
830 * else reload the router descriptor store. */
832 router_reload_router_list_impl(desc_store_t
*store
)
834 char *fname
= NULL
, *altname
= NULL
, *contents
= NULL
;
836 int read_from_old_location
= 0;
837 int extrainfo
= (store
->type
== EXTRAINFO_STORE
);
838 time_t now
= time(NULL
);
839 store
->journal_len
= store
->store_len
= 0;
841 fname
= get_datadir_fname(store
->fname_base
);
842 if (store
->fname_alt_base
)
843 altname
= get_datadir_fname(store
->fname_alt_base
);
845 if (store
->mmap
) /* get rid of it first */
846 tor_munmap_file(store
->mmap
);
849 store
->mmap
= tor_mmap_file(fname
);
850 if (!store
->mmap
&& altname
&& file_status(altname
) == FN_FILE
) {
851 read_from_old_location
= 1;
852 log_notice(LD_DIR
, "Couldn't read %s; trying to load routers from old "
853 "location %s.", fname
, altname
);
854 if ((store
->mmap
= tor_mmap_file(altname
)))
855 read_from_old_location
= 1;
857 if (altname
&& !read_from_old_location
) {
858 remove_file_if_very_old(altname
, now
);
861 store
->store_len
= store
->mmap
->size
;
863 router_load_extrainfo_from_string(store
->mmap
->data
,
864 store
->mmap
->data
+store
->mmap
->size
,
865 SAVED_IN_CACHE
, NULL
, 0);
867 router_load_routers_from_string(store
->mmap
->data
,
868 store
->mmap
->data
+store
->mmap
->size
,
869 SAVED_IN_CACHE
, NULL
, 0, NULL
);
873 fname
= get_datadir_fname_suffix(store
->fname_base
, ".new");
874 if (file_status(fname
) == FN_FILE
)
875 contents
= read_file_to_str(fname
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
876 if (read_from_old_location
) {
878 altname
= get_datadir_fname_suffix(store
->fname_alt_base
, ".new");
880 contents
= read_file_to_str(altname
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
882 remove_file_if_very_old(altname
, now
);
886 router_load_extrainfo_from_string(contents
, NULL
,SAVED_IN_JOURNAL
,
889 router_load_routers_from_string(contents
, NULL
, SAVED_IN_JOURNAL
,
891 store
->journal_len
= (size_t) st
.st_size
;
898 if (store
->journal_len
|| read_from_old_location
) {
899 /* Always clear the journal on startup.*/
900 router_rebuild_store(RRS_FORCE
, store
);
901 } else if (!extrainfo
) {
902 /* Don't cache expired routers. (This is in an else because
903 * router_rebuild_store() also calls remove_old_routers().) */
904 routerlist_remove_old_routers();
910 /** Load all cached router descriptors and extra-info documents from the
911 * store. Return 0 on success and -1 on failure.
914 router_reload_router_list(void)
916 routerlist_t
*rl
= router_get_routerlist();
917 if (router_reload_router_list_impl(&rl
->desc_store
))
919 if (router_reload_router_list_impl(&rl
->extrainfo_store
))
924 /** Return a smartlist containing a list of dir_server_t * for all
925 * known trusted dirservers. Callers must not modify the list or its
929 router_get_trusted_dir_servers(void)
931 if (!trusted_dir_servers
)
932 trusted_dir_servers
= smartlist_new();
934 return trusted_dir_servers
;
938 router_get_fallback_dir_servers(void)
940 if (!fallback_dir_servers
)
941 fallback_dir_servers
= smartlist_new();
943 return fallback_dir_servers
;
946 /** Try to find a running dirserver that supports operations of <b>type</b>.
948 * If there are no running dirservers in our routerlist and the
949 * <b>PDS_RETRY_IF_NO_SERVERS</b> flag is set, set all the authoritative ones
950 * as running again, and pick one.
952 * If the <b>PDS_IGNORE_FASCISTFIREWALL</b> flag is set, then include
953 * dirservers that we can't reach.
955 * If the <b>PDS_ALLOW_SELF</b> flag is not set, then don't include ourself
956 * (if we're a dirserver).
958 * Don't pick an authority if any non-authority is viable; try to avoid using
959 * servers that have returned 503 recently.
961 const routerstatus_t
*
962 router_pick_directory_server(dirinfo_type_t type
, int flags
)
964 const routerstatus_t
*choice
;
965 if (get_options()->PreferTunneledDirConns
)
966 flags
|= PDS_PREFER_TUNNELED_DIR_CONNS_
;
971 choice
= router_pick_directory_server_impl(type
, flags
);
972 if (choice
|| !(flags
& PDS_RETRY_IF_NO_SERVERS
))
976 "No reachable router entries for dirservers. "
977 "Trying them all again.");
978 /* mark all authdirservers as up again */
979 mark_all_dirservers_up(fallback_dir_servers
);
981 choice
= router_pick_directory_server_impl(type
, flags
);
985 /** Try to determine which fraction of v2 and v3 directory requests aimed at
986 * caches will be sent to us. Set *<b>v2_share_out</b> and
987 * *<b>v3_share_out</b> to the fractions of v2 and v3 protocol shares we
988 * expect to see, respectively. Return 0 on success, negative on failure. */
990 router_get_my_share_of_directory_requests(double *v2_share_out
,
991 double *v3_share_out
)
993 const routerinfo_t
*me
= router_get_my_routerinfo();
994 const routerstatus_t
*rs
;
995 const int pds_flags
= PDS_ALLOW_SELF
|PDS_IGNORE_FASCISTFIREWALL
;
996 *v2_share_out
= *v3_share_out
= 0.0;
999 rs
= router_get_consensus_status_by_id(me
->cache_info
.identity_digest
);
1003 /* Calling for side effect */
1004 /* XXXX This is a bit of a kludge */
1005 if (rs
->is_v2_dir
) {
1006 sl_last_total_weighted_bw
= 0;
1007 router_pick_directory_server(V2_DIRINFO
, pds_flags
);
1008 if (sl_last_total_weighted_bw
!= 0) {
1009 *v2_share_out
= U64_TO_DBL(sl_last_weighted_bw_of_me
) /
1010 U64_TO_DBL(sl_last_total_weighted_bw
);
1015 sl_last_total_weighted_bw
= 0;
1016 router_pick_directory_server(V3_DIRINFO
, pds_flags
);
1017 if (sl_last_total_weighted_bw
!= 0) {
1018 *v3_share_out
= U64_TO_DBL(sl_last_weighted_bw_of_me
) /
1019 U64_TO_DBL(sl_last_total_weighted_bw
);
1026 /** Return the dir_server_t for the directory authority whose identity
1027 * key hashes to <b>digest</b>, or NULL if no such authority is known.
1030 router_get_trusteddirserver_by_digest(const char *digest
)
1032 if (!trusted_dir_servers
)
1035 SMARTLIST_FOREACH(trusted_dir_servers
, dir_server_t
*, ds
,
1037 if (tor_memeq(ds
->digest
, digest
, DIGEST_LEN
))
1044 /** Return the dir_server_t for the fallback dirserver whose identity
1045 * key hashes to <b>digest</b>, or NULL if no such authority is known.
1048 router_get_fallback_dirserver_by_digest(const char *digest
)
1050 if (!trusted_dir_servers
)
1053 SMARTLIST_FOREACH(trusted_dir_servers
, dir_server_t
*, ds
,
1055 if (tor_memeq(ds
->digest
, digest
, DIGEST_LEN
))
1062 /** Return the dir_server_t for the directory authority whose
1063 * v3 identity key hashes to <b>digest</b>, or NULL if no such authority
1067 trusteddirserver_get_by_v3_auth_digest(const char *digest
)
1069 if (!trusted_dir_servers
)
1072 SMARTLIST_FOREACH(trusted_dir_servers
, dir_server_t
*, ds
,
1074 if (tor_memeq(ds
->v3_identity_digest
, digest
, DIGEST_LEN
) &&
1075 (ds
->type
& V3_DIRINFO
))
1082 /** Try to find a running directory authority. Flags are as for
1083 * router_pick_directory_server.
1085 const routerstatus_t
*
1086 router_pick_trusteddirserver(dirinfo_type_t type
, int flags
)
1088 return router_pick_dirserver_generic(trusted_dir_servers
, type
, flags
);
1091 /** Try to find a running fallback directory Flags are as for
1092 * router_pick_directory_server.
1094 const routerstatus_t
*
1095 router_pick_fallback_dirserver(dirinfo_type_t type
, int flags
)
1097 return router_pick_dirserver_generic(fallback_dir_servers
, type
, flags
);
1100 /** Try to find a running fallback directory Flags are as for
1101 * router_pick_directory_server.
1103 static const routerstatus_t
*
1104 router_pick_dirserver_generic(smartlist_t
*sourcelist
,
1105 dirinfo_type_t type
, int flags
)
1107 const routerstatus_t
*choice
;
1109 if (get_options()->PreferTunneledDirConns
)
1110 flags
|= PDS_PREFER_TUNNELED_DIR_CONNS_
;
1112 choice
= router_pick_trusteddirserver_impl(sourcelist
, type
, flags
, &busy
);
1113 if (choice
|| !(flags
& PDS_RETRY_IF_NO_SERVERS
))
1116 /* If the reason that we got no server is that servers are "busy",
1117 * we must be excluding good servers because we already have serverdesc
1118 * fetches with them. Do not mark down servers up because of this. */
1119 tor_assert((flags
& (PDS_NO_EXISTING_SERVERDESC_FETCH
|
1120 PDS_NO_EXISTING_MICRODESC_FETCH
)));
1125 "No dirservers are reachable. Trying them all again.");
1126 mark_all_dirservers_up(sourcelist
);
1127 return router_pick_trusteddirserver_impl(sourcelist
, type
, flags
, NULL
);
1130 /** How long do we avoid using a directory server after it's given us a 503? */
1131 #define DIR_503_TIMEOUT (60*60)
1133 /** Pick a random running valid directory server/mirror from our
1134 * routerlist. Arguments are as for router_pick_directory_server(), except
1135 * that RETRY_IF_NO_SERVERS is ignored, and:
1137 * If the PDS_PREFER_TUNNELED_DIR_CONNS_ flag is set, prefer directory servers
1138 * that we can use with BEGINDIR.
1140 static const routerstatus_t
*
1141 router_pick_directory_server_impl(dirinfo_type_t type
, int flags
)
1143 const or_options_t
*options
= get_options();
1144 const node_t
*result
;
1145 smartlist_t
*direct
, *tunnel
;
1146 smartlist_t
*trusted_direct
, *trusted_tunnel
;
1147 smartlist_t
*overloaded_direct
, *overloaded_tunnel
;
1148 time_t now
= time(NULL
);
1149 const networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
1150 int requireother
= ! (flags
& PDS_ALLOW_SELF
);
1151 int fascistfirewall
= ! (flags
& PDS_IGNORE_FASCISTFIREWALL
);
1152 int prefer_tunnel
= (flags
& PDS_PREFER_TUNNELED_DIR_CONNS_
);
1153 int try_excluding
= 1, n_excluded
= 0;
1158 retry_without_exclude
:
1160 direct
= smartlist_new();
1161 tunnel
= smartlist_new();
1162 trusted_direct
= smartlist_new();
1163 trusted_tunnel
= smartlist_new();
1164 overloaded_direct
= smartlist_new();
1165 overloaded_tunnel
= smartlist_new();
1167 /* Find all the running dirservers we know about. */
1168 SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t
*, node
) {
1172 const routerstatus_t
*status
= node
->rs
;
1173 const country_t country
= node
->country
;
1177 if (!node
->is_running
|| !status
->dir_port
|| !node
->is_valid
)
1179 if (node
->is_bad_directory
)
1181 if (requireother
&& router_digest_is_me(node
->identity
))
1183 is_trusted
= router_digest_is_trusted_dir(node
->identity
);
1184 if ((type
& V2_DIRINFO
) && !(node
->rs
->is_v2_dir
|| is_trusted
))
1186 if ((type
& EXTRAINFO_DIRINFO
) &&
1187 !router_supports_extrainfo(node
->identity
, 0))
1189 if ((type
& MICRODESC_DIRINFO
) && !is_trusted
&&
1190 !node
->rs
->version_supports_microdesc_cache
)
1192 if (try_excluding
&&
1193 routerset_contains_routerstatus(options
->ExcludeNodes
, status
,
1199 /* XXXX IP6 proposal 118 */
1200 tor_addr_from_ipv4h(&addr
, node
->rs
->addr
);
1202 is_overloaded
= status
->last_dir_503_at
+ DIR_503_TIMEOUT
> now
;
1204 if (prefer_tunnel
&&
1205 (!fascistfirewall
||
1206 fascist_firewall_allows_address_or(&addr
, status
->or_port
)))
1207 smartlist_add(is_trusted
? trusted_tunnel
:
1208 is_overloaded
? overloaded_tunnel
: tunnel
, (void*)node
);
1209 else if (!fascistfirewall
||
1210 fascist_firewall_allows_address_dir(&addr
, status
->dir_port
))
1211 smartlist_add(is_trusted
? trusted_direct
:
1212 is_overloaded
? overloaded_direct
: direct
, (void*)node
);
1213 } SMARTLIST_FOREACH_END(node
);
1215 if (smartlist_len(tunnel
)) {
1216 result
= node_sl_choose_by_bandwidth(tunnel
, WEIGHT_FOR_DIR
);
1217 } else if (smartlist_len(overloaded_tunnel
)) {
1218 result
= node_sl_choose_by_bandwidth(overloaded_tunnel
,
1220 } else if (smartlist_len(trusted_tunnel
)) {
1221 /* FFFF We don't distinguish between trusteds and overloaded trusteds
1222 * yet. Maybe one day we should. */
1223 /* FFFF We also don't load balance over authorities yet. I think this
1224 * is a feature, but it could easily be a bug. -RD */
1225 result
= smartlist_choose(trusted_tunnel
);
1226 } else if (smartlist_len(direct
)) {
1227 result
= node_sl_choose_by_bandwidth(direct
, WEIGHT_FOR_DIR
);
1228 } else if (smartlist_len(overloaded_direct
)) {
1229 result
= node_sl_choose_by_bandwidth(overloaded_direct
,
1232 result
= smartlist_choose(trusted_direct
);
1234 smartlist_free(direct
);
1235 smartlist_free(tunnel
);
1236 smartlist_free(trusted_direct
);
1237 smartlist_free(trusted_tunnel
);
1238 smartlist_free(overloaded_direct
);
1239 smartlist_free(overloaded_tunnel
);
1241 if (result
== NULL
&& try_excluding
&& !options
->StrictNodes
&& n_excluded
) {
1242 /* If we got no result, and we are excluding nodes, and StrictNodes is
1243 * not set, try again without excluding nodes. */
1246 goto retry_without_exclude
;
1249 return result
? result
->rs
: NULL
;
1252 /** Pick a random element from a list of dir_server_t, weighting by their
1253 * <b>weight</b> field. */
1254 static const dir_server_t
*
1255 dirserver_choose_by_weight(const smartlist_t
*servers
, double authority_weight
)
1257 int n
= smartlist_len(servers
);
1260 const dir_server_t
*ds
;
1262 weights
= tor_malloc(sizeof(u64_dbl_t
) * n
);
1263 for (i
= 0; i
< n
; ++i
) {
1264 ds
= smartlist_get(servers
, i
);
1265 weights
[i
].dbl
= ds
->weight
;
1266 if (ds
->is_authority
)
1267 weights
[i
].dbl
*= authority_weight
;
1270 scale_array_elements_to_u64(weights
, n
, NULL
);
1271 i
= choose_array_element_by_weight(weights
, n
);
1273 return (i
< 0) ? NULL
: smartlist_get(servers
, i
);
1276 /** Choose randomly from among the dir_server_ts in sourcelist that
1277 * are up. Flags are as for router_pick_directory_server_impl().
1279 static const routerstatus_t
*
1280 router_pick_trusteddirserver_impl(const smartlist_t
*sourcelist
,
1281 dirinfo_type_t type
, int flags
,
1284 const or_options_t
*options
= get_options();
1285 smartlist_t
*direct
, *tunnel
;
1286 smartlist_t
*overloaded_direct
, *overloaded_tunnel
;
1287 const routerinfo_t
*me
= router_get_my_routerinfo();
1288 const routerstatus_t
*result
= NULL
;
1289 time_t now
= time(NULL
);
1290 const int requireother
= ! (flags
& PDS_ALLOW_SELF
);
1291 const int fascistfirewall
= ! (flags
& PDS_IGNORE_FASCISTFIREWALL
);
1292 const int prefer_tunnel
= (flags
& PDS_PREFER_TUNNELED_DIR_CONNS_
);
1293 const int no_serverdesc_fetching
=(flags
& PDS_NO_EXISTING_SERVERDESC_FETCH
);
1294 const int no_microdesc_fetching
=(flags
& PDS_NO_EXISTING_MICRODESC_FETCH
);
1295 const double auth_weight
= (sourcelist
== fallback_dir_servers
) ?
1296 options
->DirAuthorityFallbackRate
: 1.0;
1297 smartlist_t
*pick_from
;
1299 int try_excluding
= 1, n_excluded
= 0;
1304 retry_without_exclude
:
1306 direct
= smartlist_new();
1307 tunnel
= smartlist_new();
1308 overloaded_direct
= smartlist_new();
1309 overloaded_tunnel
= smartlist_new();
1311 SMARTLIST_FOREACH_BEGIN(sourcelist
, const dir_server_t
*, d
)
1314 d
->fake_status
.last_dir_503_at
+ DIR_503_TIMEOUT
> now
;
1316 if (!d
->is_running
) continue;
1317 if ((type
& d
->type
) == 0)
1319 if ((type
& EXTRAINFO_DIRINFO
) &&
1320 !router_supports_extrainfo(d
->digest
, 1))
1322 if (requireother
&& me
&& router_digest_is_me(d
->digest
))
1324 if (try_excluding
&&
1325 routerset_contains_routerstatus(options
->ExcludeNodes
,
1326 &d
->fake_status
, -1)) {
1331 /* XXXX IP6 proposal 118 */
1332 tor_addr_from_ipv4h(&addr
, d
->addr
);
1334 if (no_serverdesc_fetching
) {
1335 if (connection_get_by_type_addr_port_purpose(
1336 CONN_TYPE_DIR
, &addr
, d
->dir_port
, DIR_PURPOSE_FETCH_SERVERDESC
)
1337 || connection_get_by_type_addr_port_purpose(
1338 CONN_TYPE_DIR
, &addr
, d
->dir_port
, DIR_PURPOSE_FETCH_EXTRAINFO
)) {
1339 //log_debug(LD_DIR, "We have an existing connection to fetch "
1340 // "descriptor from %s; delaying",d->description);
1345 if (no_microdesc_fetching
) {
1346 if (connection_get_by_type_addr_port_purpose(
1347 CONN_TYPE_DIR
, &addr
, d
->dir_port
, DIR_PURPOSE_FETCH_MICRODESC
)) {
1353 if (prefer_tunnel
&&
1355 (!fascistfirewall
||
1356 fascist_firewall_allows_address_or(&addr
, d
->or_port
)))
1357 smartlist_add(is_overloaded
? overloaded_tunnel
: tunnel
, (void*)d
);
1358 else if (!fascistfirewall
||
1359 fascist_firewall_allows_address_dir(&addr
, d
->dir_port
))
1360 smartlist_add(is_overloaded
? overloaded_direct
: direct
, (void*)d
);
1362 SMARTLIST_FOREACH_END(d
);
1364 if (smartlist_len(tunnel
)) {
1366 } else if (smartlist_len(overloaded_tunnel
)) {
1367 pick_from
= overloaded_tunnel
;
1368 } else if (smartlist_len(direct
)) {
1371 pick_from
= overloaded_direct
;
1375 const dir_server_t
*selection
=
1376 dirserver_choose_by_weight(pick_from
, auth_weight
);
1379 result
= &selection
->fake_status
;
1383 *n_busy_out
= n_busy
;
1385 smartlist_free(direct
);
1386 smartlist_free(tunnel
);
1387 smartlist_free(overloaded_direct
);
1388 smartlist_free(overloaded_tunnel
);
1390 if (result
== NULL
&& try_excluding
&& !options
->StrictNodes
&& n_excluded
) {
1391 /* If we got no result, and we are excluding nodes, and StrictNodes is
1392 * not set, try again without excluding nodes. */
1395 goto retry_without_exclude
;
1401 /** Mark as running every dir_server_t in <b>server_list</b>. */
1403 mark_all_dirservers_up(smartlist_t
*server_list
)
1406 SMARTLIST_FOREACH_BEGIN(server_list
, dir_server_t
*, dir
) {
1409 dir
->is_running
= 1;
1410 download_status_reset(&dir
->v2_ns_dl_status
);
1411 node
= node_get_mutable_by_id(dir
->digest
);
1413 node
->is_running
= 1;
1414 rs
= router_get_mutable_consensus_status_by_id(dir
->digest
);
1416 rs
->last_dir_503_at
= 0;
1417 control_event_networkstatus_changed_single(rs
);
1419 } SMARTLIST_FOREACH_END(dir
);
1421 router_dir_info_changed();
1424 /** Return true iff r1 and r2 have the same address and OR port. */
1426 routers_have_same_or_addrs(const routerinfo_t
*r1
, const routerinfo_t
*r2
)
1428 return r1
->addr
== r2
->addr
&& r1
->or_port
== r2
->or_port
&&
1429 tor_addr_eq(&r1
->ipv6_addr
, &r2
->ipv6_addr
) &&
1430 r1
->ipv6_orport
== r2
->ipv6_orport
;
1433 /** Reset all internal variables used to count failed downloads of network
1434 * status objects. */
1436 router_reset_status_download_failures(void)
1438 mark_all_dirservers_up(fallback_dir_servers
);
1441 /** Given a <b>router</b>, add every node_t in its family (including the
1442 * node itself!) to <b>sl</b>.
1444 * Note the type mismatch: This function takes a routerinfo, but adds nodes
1448 routerlist_add_node_and_family(smartlist_t
*sl
, const routerinfo_t
*router
)
1452 const node_t
*node
= node_get_by_id(router
->cache_info
.identity_digest
);;
1454 memset(&fake_node
, 0, sizeof(fake_node
));
1455 fake_node
.ri
= (routerinfo_t
*)router
;
1456 memcpy(fake_node
.identity
, router
->cache_info
.identity_digest
, DIGEST_LEN
);
1459 nodelist_add_node_and_family(sl
, node
);
1462 /** Add every suitable node from our nodelist to <b>sl</b>, so that
1463 * we can pick a node for a circuit.
1466 router_add_running_nodes_to_smartlist(smartlist_t
*sl
, int allow_invalid
,
1467 int need_uptime
, int need_capacity
,
1468 int need_guard
, int need_desc
)
1470 SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t
*, node
) {
1471 if (!node
->is_running
||
1472 (!node
->is_valid
&& !allow_invalid
))
1474 if (need_desc
&& !(node
->ri
|| (node
->rs
&& node
->md
)))
1476 if (node
->ri
&& node
->ri
->purpose
!= ROUTER_PURPOSE_GENERAL
)
1478 if (node_is_unreliable(node
, need_uptime
, need_capacity
, need_guard
))
1481 smartlist_add(sl
, (void *)node
);
1482 } SMARTLIST_FOREACH_END(node
);
1485 /** Look through the routerlist until we find a router that has my key.
1487 const routerinfo_t
*
1488 routerlist_find_my_routerinfo(void)
1493 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1495 if (router_is_me(router
))
1501 /** Return the smaller of the router's configured BandwidthRate
1502 * and its advertised capacity. */
1504 router_get_advertised_bandwidth(const routerinfo_t
*router
)
1506 if (router
->bandwidthcapacity
< router
->bandwidthrate
)
1507 return router
->bandwidthcapacity
;
1508 return router
->bandwidthrate
;
1511 /** Do not weight any declared bandwidth more than this much when picking
1512 * routers by bandwidth. */
1513 #define DEFAULT_MAX_BELIEVABLE_BANDWIDTH 10000000 /* 10 MB/sec */
1515 /** Return the smaller of the router's configured BandwidthRate
1516 * and its advertised capacity, capped by max-believe-bw. */
1518 router_get_advertised_bandwidth_capped(const routerinfo_t
*router
)
1520 uint32_t result
= router
->bandwidthcapacity
;
1521 if (result
> router
->bandwidthrate
)
1522 result
= router
->bandwidthrate
;
1523 if (result
> DEFAULT_MAX_BELIEVABLE_BANDWIDTH
)
1524 result
= DEFAULT_MAX_BELIEVABLE_BANDWIDTH
;
1528 /** Given an array of double/uint64_t unions that are currently being used as
1529 * doubles, convert them to uint64_t, and try to scale them linearly so as to
1530 * much of the range of uint64_t. If <b>total_out</b> is provided, set it to
1531 * the sum of all elements in the array _before_ scaling. */
1533 scale_array_elements_to_u64(u64_dbl_t
*entries
, int n_entries
,
1534 uint64_t *total_out
)
1537 double scale_factor
;
1539 /* big, but far away from overflowing an int64_t */
1540 #define SCALE_TO_U64_MAX (INT64_MAX / 4)
1542 for (i
= 0; i
< n_entries
; ++i
)
1543 total
+= entries
[i
].dbl
;
1545 scale_factor
= SCALE_TO_U64_MAX
/ total
;
1547 for (i
= 0; i
< n_entries
; ++i
)
1548 entries
[i
].u64
= tor_llround(entries
[i
].dbl
* scale_factor
);
1551 *total_out
= (uint64_t) total
;
1553 #undef SCALE_TO_U64_MAX
1556 /** Time-invariant 64-bit greater-than; works on two integers in the range
1558 #if SIZEOF_VOID_P == 8
1559 #define gt_i64_timei(a,b) ((a) > (b))
1562 gt_i64_timei(uint64_t a
, uint64_t b
)
1564 int64_t diff
= (int64_t) (b
- a
);
1565 int res
= diff
>> 63;
1570 /** Pick a random element of <b>n_entries</b>-element array <b>entries</b>,
1571 * choosing each element with a probability proportional to its (uint64_t)
1572 * value, and return the index of that element. If all elements are 0, choose
1573 * an index at random. Return -1 on error.
1576 choose_array_element_by_weight(const u64_dbl_t
*entries
, int n_entries
)
1578 int i
, i_chosen
=-1, n_chosen
=0;
1579 uint64_t total_so_far
= 0;
1583 for (i
= 0; i
< n_entries
; ++i
)
1584 total
+= entries
[i
].u64
;
1590 return crypto_rand_int(n_entries
);
1592 tor_assert(total
< INT64_MAX
);
1594 rand_val
= crypto_rand_uint64(total
);
1596 for (i
= 0; i
< n_entries
; ++i
) {
1597 total_so_far
+= entries
[i
].u64
;
1598 if (gt_i64_timei(total_so_far
, rand_val
)) {
1601 /* Set rand_val to INT64_MAX rather than stopping the loop. This way,
1602 * the time we spend in the loop does not leak which element we chose. */
1603 rand_val
= INT64_MAX
;
1606 tor_assert(total_so_far
== total
);
1607 tor_assert(n_chosen
== 1);
1608 tor_assert(i_chosen
>= 0);
1609 tor_assert(i_chosen
< n_entries
);
1614 /** When weighting bridges, enforce these values as lower and upper
1615 * bound for believable bandwidth, because there is no way for us
1616 * to verify a bridge's bandwidth currently. */
1617 #define BRIDGE_MIN_BELIEVABLE_BANDWIDTH 20000 /* 20 kB/sec */
1618 #define BRIDGE_MAX_BELIEVABLE_BANDWIDTH 100000 /* 100 kB/sec */
1620 /** Return the smaller of the router's configured BandwidthRate
1621 * and its advertised capacity, making sure to stay within the
1622 * interval between bridge-min-believe-bw and
1623 * bridge-max-believe-bw. */
1625 bridge_get_advertised_bandwidth_bounded(routerinfo_t
*router
)
1627 uint32_t result
= router
->bandwidthcapacity
;
1628 if (result
> router
->bandwidthrate
)
1629 result
= router
->bandwidthrate
;
1630 if (result
> BRIDGE_MAX_BELIEVABLE_BANDWIDTH
)
1631 result
= BRIDGE_MAX_BELIEVABLE_BANDWIDTH
;
1632 else if (result
< BRIDGE_MIN_BELIEVABLE_BANDWIDTH
)
1633 result
= BRIDGE_MIN_BELIEVABLE_BANDWIDTH
;
1637 /** Return bw*1000, unless bw*1000 would overflow, in which case return
1639 static INLINE
int32_t
1640 kb_to_bytes(uint32_t bw
)
1642 return (bw
> (INT32_MAX
/1000)) ? INT32_MAX
: bw
*1000;
1645 /** Helper function:
1646 * choose a random element of smartlist <b>sl</b> of nodes, weighted by
1647 * the advertised bandwidth of each element using the consensus
1648 * bandwidth weights.
1650 * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
1651 * nodes' bandwidth equally regardless of their Exit status, since there may
1652 * be some in the list because they exit to obscure ports. If
1653 * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
1654 * exit-node's bandwidth less depending on the smallness of the fraction of
1655 * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
1656 * guard node: consider all guard's bandwidth equally. Otherwise, weight
1657 * guards proportionally less.
1659 static const node_t
*
1660 smartlist_choose_node_by_bandwidth_weights(const smartlist_t
*sl
,
1661 bandwidth_weight_rule_t rule
)
1663 u64_dbl_t
*bandwidths
=NULL
;
1665 if (compute_weighted_bandwidths(sl
, rule
, &bandwidths
) < 0)
1668 scale_array_elements_to_u64(bandwidths
, smartlist_len(sl
),
1669 &sl_last_total_weighted_bw
);
1672 int idx
= choose_array_element_by_weight(bandwidths
,
1674 tor_free(bandwidths
);
1675 return idx
< 0 ? NULL
: smartlist_get(sl
, idx
);
1679 /** Given a list of routers and a weighting rule as in
1680 * smartlist_choose_node_by_bandwidth_weights, compute weighted bandwidth
1681 * values for each node and store them in a freshly allocated
1682 * *<b>bandwidths_out</b> of the same length as <b>sl</b>, and holding results
1683 * as doubles. Return 0 on success, -1 on failure. */
1685 compute_weighted_bandwidths(const smartlist_t
*sl
,
1686 bandwidth_weight_rule_t rule
,
1687 u64_dbl_t
**bandwidths_out
)
1689 int64_t weight_scale
;
1690 double Wg
= -1, Wm
= -1, We
= -1, Wd
= -1;
1691 double Wgb
= -1, Wmb
= -1, Web
= -1, Wdb
= -1;
1692 uint64_t weighted_bw
= 0;
1693 u64_dbl_t
*bandwidths
;
1695 /* Can't choose exit and guard at same time */
1696 tor_assert(rule
== NO_WEIGHTING
||
1697 rule
== WEIGHT_FOR_EXIT
||
1698 rule
== WEIGHT_FOR_GUARD
||
1699 rule
== WEIGHT_FOR_MID
||
1700 rule
== WEIGHT_FOR_DIR
);
1702 if (smartlist_len(sl
) == 0) {
1704 "Empty routerlist passed in to consensus weight node "
1705 "selection for rule %s",
1706 bandwidth_weight_rule_to_string(rule
));
1710 weight_scale
= networkstatus_get_weight_scale_param(NULL
);
1712 if (rule
== WEIGHT_FOR_GUARD
) {
1713 Wg
= networkstatus_get_bw_weight(NULL
, "Wgg", -1);
1714 Wm
= networkstatus_get_bw_weight(NULL
, "Wgm", -1); /* Bridges */
1716 Wd
= networkstatus_get_bw_weight(NULL
, "Wgd", -1);
1718 Wgb
= networkstatus_get_bw_weight(NULL
, "Wgb", -1);
1719 Wmb
= networkstatus_get_bw_weight(NULL
, "Wmb", -1);
1720 Web
= networkstatus_get_bw_weight(NULL
, "Web", -1);
1721 Wdb
= networkstatus_get_bw_weight(NULL
, "Wdb", -1);
1722 } else if (rule
== WEIGHT_FOR_MID
) {
1723 Wg
= networkstatus_get_bw_weight(NULL
, "Wmg", -1);
1724 Wm
= networkstatus_get_bw_weight(NULL
, "Wmm", -1);
1725 We
= networkstatus_get_bw_weight(NULL
, "Wme", -1);
1726 Wd
= networkstatus_get_bw_weight(NULL
, "Wmd", -1);
1728 Wgb
= networkstatus_get_bw_weight(NULL
, "Wgb", -1);
1729 Wmb
= networkstatus_get_bw_weight(NULL
, "Wmb", -1);
1730 Web
= networkstatus_get_bw_weight(NULL
, "Web", -1);
1731 Wdb
= networkstatus_get_bw_weight(NULL
, "Wdb", -1);
1732 } else if (rule
== WEIGHT_FOR_EXIT
) {
1733 // Guards CAN be exits if they have weird exit policies
1734 // They are d then I guess...
1735 We
= networkstatus_get_bw_weight(NULL
, "Wee", -1);
1736 Wm
= networkstatus_get_bw_weight(NULL
, "Wem", -1); /* Odd exit policies */
1737 Wd
= networkstatus_get_bw_weight(NULL
, "Wed", -1);
1738 Wg
= networkstatus_get_bw_weight(NULL
, "Weg", -1); /* Odd exit policies */
1740 Wgb
= networkstatus_get_bw_weight(NULL
, "Wgb", -1);
1741 Wmb
= networkstatus_get_bw_weight(NULL
, "Wmb", -1);
1742 Web
= networkstatus_get_bw_weight(NULL
, "Web", -1);
1743 Wdb
= networkstatus_get_bw_weight(NULL
, "Wdb", -1);
1744 } else if (rule
== WEIGHT_FOR_DIR
) {
1745 We
= networkstatus_get_bw_weight(NULL
, "Wbe", -1);
1746 Wm
= networkstatus_get_bw_weight(NULL
, "Wbm", -1);
1747 Wd
= networkstatus_get_bw_weight(NULL
, "Wbd", -1);
1748 Wg
= networkstatus_get_bw_weight(NULL
, "Wbg", -1);
1750 Wgb
= Wmb
= Web
= Wdb
= weight_scale
;
1751 } else if (rule
== NO_WEIGHTING
) {
1752 Wg
= Wm
= We
= Wd
= weight_scale
;
1753 Wgb
= Wmb
= Web
= Wdb
= weight_scale
;
1756 if (Wg
< 0 || Wm
< 0 || We
< 0 || Wd
< 0 || Wgb
< 0 || Wmb
< 0 || Wdb
< 0
1759 "Got negative bandwidth weights. Defaulting to old selection"
1761 return -1; // Use old algorithm.
1769 Wgb
/= weight_scale
;
1770 Wmb
/= weight_scale
;
1771 Web
/= weight_scale
;
1772 Wdb
/= weight_scale
;
1774 bandwidths
= tor_malloc_zero(sizeof(u64_dbl_t
)*smartlist_len(sl
));
1776 // Cycle through smartlist and total the bandwidth.
1777 SMARTLIST_FOREACH_BEGIN(sl
, const node_t
*, node
) {
1778 int is_exit
= 0, is_guard
= 0, is_dir
= 0, this_bw
= 0, is_me
= 0;
1780 is_exit
= node
->is_exit
&& ! node
->is_bad_exit
;
1781 is_guard
= node
->is_possible_guard
;
1782 is_dir
= node_is_dir(node
);
1784 if (!node
->rs
->has_bandwidth
) {
1785 tor_free(bandwidths
);
1786 /* This should never happen, unless all the authorites downgrade
1787 * to 0.2.0 or rogue routerstatuses get inserted into our consensus. */
1789 "Consensus is not listing bandwidths. Defaulting back to "
1790 "old router selection algorithm.");
1793 this_bw
= kb_to_bytes(node
->rs
->bandwidth
);
1794 } else if (node
->ri
) {
1795 /* bridge or other descriptor not in our consensus */
1796 this_bw
= bridge_get_advertised_bandwidth_bounded(node
->ri
);
1798 /* We can't use this one. */
1801 is_me
= router_digest_is_me(node
->identity
);
1803 if (is_guard
&& is_exit
) {
1804 weight
= (is_dir
? Wdb
*Wd
: Wd
);
1805 } else if (is_guard
) {
1806 weight
= (is_dir
? Wgb
*Wg
: Wg
);
1807 } else if (is_exit
) {
1808 weight
= (is_dir
? Web
*We
: We
);
1810 weight
= (is_dir
? Wmb
*Wm
: Wm
);
1812 /* These should be impossible; but overflows here would be bad, so let's
1819 bandwidths
[node_sl_idx
].dbl
= weight
*this_bw
+ 0.5;
1821 sl_last_weighted_bw_of_me
= (uint64_t) bandwidths
[node_sl_idx
].dbl
;
1822 } SMARTLIST_FOREACH_END(node
);
1824 log_debug(LD_CIRC
, "Generated weighted bandwidths for rule %s based "
1826 "Wg=%f Wm=%f We=%f Wd=%f with total bw "U64_FORMAT
,
1827 bandwidth_weight_rule_to_string(rule
),
1828 Wg
, Wm
, We
, Wd
, U64_PRINTF_ARG(weighted_bw
));
1830 *bandwidths_out
= bandwidths
;
1835 /** For all nodes in <b>sl</b>, return the fraction of those nodes, weighted
1836 * by their weighted bandwidths with rule <b>rule</b>, for which we have
1839 frac_nodes_with_descriptors(const smartlist_t
*sl
,
1840 bandwidth_weight_rule_t rule
)
1842 u64_dbl_t
*bandwidths
= NULL
;
1843 double total
, present
;
1845 if (smartlist_len(sl
) == 0)
1848 if (compute_weighted_bandwidths(sl
, rule
, &bandwidths
) < 0) {
1849 int n_with_descs
= 0;
1850 SMARTLIST_FOREACH(sl
, const node_t
*, node
, {
1851 if (node_has_descriptor(node
))
1854 return ((double)n_with_descs
) / (double)smartlist_len(sl
);
1857 total
= present
= 0.0;
1858 SMARTLIST_FOREACH_BEGIN(sl
, const node_t
*, node
) {
1859 const double bw
= bandwidths
[node_sl_idx
].dbl
;
1861 if (node_has_descriptor(node
))
1863 } SMARTLIST_FOREACH_END(node
);
1865 tor_free(bandwidths
);
1870 return present
/ total
;
1873 /** Helper function:
1874 * choose a random node_t element of smartlist <b>sl</b>, weighted by
1875 * the advertised bandwidth of each element.
1877 * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
1878 * nodes' bandwidth equally regardless of their Exit status, since there may
1879 * be some in the list because they exit to obscure ports. If
1880 * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
1881 * exit-node's bandwidth less depending on the smallness of the fraction of
1882 * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
1883 * guard node: consider all guard's bandwidth equally. Otherwise, weight
1884 * guards proportionally less.
1886 static const node_t
*
1887 smartlist_choose_node_by_bandwidth(const smartlist_t
*sl
,
1888 bandwidth_weight_rule_t rule
)
1891 u64_dbl_t
*bandwidths
;
1895 double total_nonexit_bw
= 0, total_exit_bw
= 0;
1896 double total_nonguard_bw
= 0, total_guard_bw
= 0;
1898 double guard_weight
;
1900 bitarray_t
*fast_bits
;
1901 bitarray_t
*exit_bits
;
1902 bitarray_t
*guard_bits
;
1905 // This function does not support WEIGHT_FOR_DIR
1906 // or WEIGHT_FOR_MID
1907 if (rule
== WEIGHT_FOR_DIR
|| rule
== WEIGHT_FOR_MID
) {
1908 rule
= NO_WEIGHTING
;
1911 /* Can't choose exit and guard at same time */
1912 tor_assert(rule
== NO_WEIGHTING
||
1913 rule
== WEIGHT_FOR_EXIT
||
1914 rule
== WEIGHT_FOR_GUARD
);
1916 if (smartlist_len(sl
) == 0) {
1918 "Empty routerlist passed in to old node selection for rule %s",
1919 bandwidth_weight_rule_to_string(rule
));
1923 /* First count the total bandwidth weight, and make a list
1924 * of each value. We use UINT64_MAX to indicate "unknown". */
1925 bandwidths
= tor_malloc_zero(sizeof(u64_dbl_t
)*smartlist_len(sl
));
1926 fast_bits
= bitarray_init_zero(smartlist_len(sl
));
1927 exit_bits
= bitarray_init_zero(smartlist_len(sl
));
1928 guard_bits
= bitarray_init_zero(smartlist_len(sl
));
1930 /* Iterate over all the routerinfo_t or routerstatus_t, and */
1931 SMARTLIST_FOREACH_BEGIN(sl
, const node_t
*, node
) {
1932 /* first, learn what bandwidth we think i has */
1934 uint32_t this_bw
= 0;
1937 if (router_digest_is_me(node
->identity
))
1938 me_idx
= node_sl_idx
;
1940 is_exit
= node
->is_exit
;
1941 is_guard
= node
->is_possible_guard
;
1943 if (node
->rs
->has_bandwidth
) {
1944 this_bw
= kb_to_bytes(node
->rs
->bandwidth
);
1945 } else { /* guess */
1948 } else if (node
->ri
) {
1949 /* Must be a bridge if we're willing to use it */
1950 this_bw
= bridge_get_advertised_bandwidth_bounded(node
->ri
);
1954 bitarray_set(exit_bits
, i
);
1956 bitarray_set(guard_bits
, i
);
1958 bitarray_set(fast_bits
, i
);
1961 bandwidths
[i
].dbl
= this_bw
;
1963 total_guard_bw
+= this_bw
;
1965 total_nonguard_bw
+= this_bw
;
1967 total_exit_bw
+= this_bw
;
1969 total_nonexit_bw
+= this_bw
;
1972 bandwidths
[i
].dbl
= -1.0;
1974 } SMARTLIST_FOREACH_END(node
);
1978 /* Now, fill in the unknown values. */
1980 int32_t avg_fast
, avg_slow
;
1981 if (total_exit_bw
+total_nonexit_bw
< EPSILON
) {
1982 /* if there's some bandwidth, there's at least one known router,
1983 * so no worries about div by 0 here */
1984 int n_known
= smartlist_len(sl
)-n_unknown
;
1985 avg_fast
= avg_slow
= (int32_t)
1986 ((total_exit_bw
+total_nonexit_bw
)/((uint64_t) n_known
));
1991 for (i
=0; i
<(unsigned)smartlist_len(sl
); ++i
) {
1992 if (bandwidths
[i
].dbl
>= 0.0)
1994 is_fast
= bitarray_is_set(fast_bits
, i
);
1995 is_exit
= bitarray_is_set(exit_bits
, i
);
1996 is_guard
= bitarray_is_set(guard_bits
, i
);
1997 bandwidths
[i
].dbl
= is_fast
? avg_fast
: avg_slow
;
1999 total_exit_bw
+= bandwidths
[i
].dbl
;
2001 total_nonexit_bw
+= bandwidths
[i
].dbl
;
2003 total_guard_bw
+= bandwidths
[i
].dbl
;
2005 total_nonguard_bw
+= bandwidths
[i
].dbl
;
2009 /* If there's no bandwidth at all, pick at random. */
2010 if (total_exit_bw
+total_nonexit_bw
< EPSILON
) {
2011 tor_free(bandwidths
);
2012 tor_free(fast_bits
);
2013 tor_free(exit_bits
);
2014 tor_free(guard_bits
);
2015 return smartlist_choose(sl
);
2018 /* Figure out how to weight exits and guards */
2020 double all_bw
= U64_TO_DBL(total_exit_bw
+total_nonexit_bw
);
2021 double exit_bw
= U64_TO_DBL(total_exit_bw
);
2022 double guard_bw
= U64_TO_DBL(total_guard_bw
);
2024 * For detailed derivation of this formula, see
2025 * http://archives.seul.org/or/dev/Jul-2007/msg00056.html
2027 if (rule
== WEIGHT_FOR_EXIT
|| total_exit_bw
<EPSILON
)
2030 exit_weight
= 1.0 - all_bw
/(3.0*exit_bw
);
2032 if (rule
== WEIGHT_FOR_GUARD
|| total_guard_bw
<EPSILON
)
2035 guard_weight
= 1.0 - all_bw
/(3.0*guard_bw
);
2037 if (exit_weight
<= 0.0)
2040 if (guard_weight
<= 0.0)
2043 sl_last_weighted_bw_of_me
= 0;
2044 for (i
=0; i
< (unsigned)smartlist_len(sl
); i
++) {
2045 tor_assert(bandwidths
[i
].dbl
>= 0.0);
2047 is_exit
= bitarray_is_set(exit_bits
, i
);
2048 is_guard
= bitarray_is_set(guard_bits
, i
);
2049 if (is_exit
&& is_guard
)
2050 bandwidths
[i
].dbl
*= exit_weight
* guard_weight
;
2052 bandwidths
[i
].dbl
*= guard_weight
;
2054 bandwidths
[i
].dbl
*= exit_weight
;
2056 if (i
== (unsigned) me_idx
)
2057 sl_last_weighted_bw_of_me
= (uint64_t) bandwidths
[i
].dbl
;
2062 log_debug(LD_CIRC
, "Total weighted bw = "U64_FORMAT
2063 ", exit bw = "U64_FORMAT
2064 ", nonexit bw = "U64_FORMAT
", exit weight = %f "
2066 ", guard bw = "U64_FORMAT
2067 ", nonguard bw = "U64_FORMAT
", guard weight = %f "
2068 "(for guard == %d)",
2069 U64_PRINTF_ARG(total_bw
),
2070 U64_PRINTF_ARG(total_exit_bw
), U64_PRINTF_ARG(total_nonexit_bw
),
2071 exit_weight
, (int)(rule
== WEIGHT_FOR_EXIT
),
2072 U64_PRINTF_ARG(total_guard_bw
), U64_PRINTF_ARG(total_nonguard_bw
),
2073 guard_weight
, (int)(rule
== WEIGHT_FOR_GUARD
));
2076 scale_array_elements_to_u64(bandwidths
, smartlist_len(sl
),
2077 &sl_last_total_weighted_bw
);
2080 int idx
= choose_array_element_by_weight(bandwidths
,
2082 tor_free(bandwidths
);
2083 tor_free(fast_bits
);
2084 tor_free(exit_bits
);
2085 tor_free(guard_bits
);
2086 return idx
< 0 ? NULL
: smartlist_get(sl
, idx
);
2090 /** Choose a random element of status list <b>sl</b>, weighted by
2091 * the advertised bandwidth of each node */
2093 node_sl_choose_by_bandwidth(const smartlist_t
*sl
,
2094 bandwidth_weight_rule_t rule
)
2097 if ((ret
= smartlist_choose_node_by_bandwidth_weights(sl
, rule
))) {
2100 return smartlist_choose_node_by_bandwidth(sl
, rule
);
2104 /** Return a random running node from the nodelist. Never
2105 * pick a node that is in
2106 * <b>excludedsmartlist</b>, or which matches <b>excludedset</b>,
2107 * even if they are the only nodes available.
2108 * If <b>CRN_NEED_UPTIME</b> is set in flags and any router has more than
2109 * a minimum uptime, return one of those.
2110 * If <b>CRN_NEED_CAPACITY</b> is set in flags, weight your choice by the
2111 * advertised capacity of each router.
2112 * If <b>CRN_ALLOW_INVALID</b> is not set in flags, consider only Valid
2114 * If <b>CRN_NEED_GUARD</b> is set in flags, consider only Guard routers.
2115 * If <b>CRN_WEIGHT_AS_EXIT</b> is set in flags, we weight bandwidths as if
2116 * picking an exit node, otherwise we weight bandwidths for picking a relay
2117 * node (that is, possibly discounting exit nodes).
2118 * If <b>CRN_NEED_DESC</b> is set in flags, we only consider nodes that
2119 * have a routerinfo or microdescriptor -- that is, enough info to be
2120 * used to build a circuit.
2123 router_choose_random_node(smartlist_t
*excludedsmartlist
,
2124 routerset_t
*excludedset
,
2125 router_crn_flags_t flags
)
2127 const int need_uptime
= (flags
& CRN_NEED_UPTIME
) != 0;
2128 const int need_capacity
= (flags
& CRN_NEED_CAPACITY
) != 0;
2129 const int need_guard
= (flags
& CRN_NEED_GUARD
) != 0;
2130 const int allow_invalid
= (flags
& CRN_ALLOW_INVALID
) != 0;
2131 const int weight_for_exit
= (flags
& CRN_WEIGHT_AS_EXIT
) != 0;
2132 const int need_desc
= (flags
& CRN_NEED_DESC
) != 0;
2134 smartlist_t
*sl
=smartlist_new(),
2135 *excludednodes
=smartlist_new();
2136 const node_t
*choice
= NULL
;
2137 const routerinfo_t
*r
;
2138 bandwidth_weight_rule_t rule
;
2140 tor_assert(!(weight_for_exit
&& need_guard
));
2141 rule
= weight_for_exit
? WEIGHT_FOR_EXIT
:
2142 (need_guard
? WEIGHT_FOR_GUARD
: WEIGHT_FOR_MID
);
2144 /* Exclude relays that allow single hop exit circuits, if the user
2145 * wants to (such relays might be risky) */
2146 if (get_options()->ExcludeSingleHopRelays
) {
2147 SMARTLIST_FOREACH(nodelist_get_list(), node_t
*, node
,
2148 if (node_allows_single_hop_exits(node
)) {
2149 smartlist_add(excludednodes
, node
);
2153 if ((r
= routerlist_find_my_routerinfo()))
2154 routerlist_add_node_and_family(excludednodes
, r
);
2156 router_add_running_nodes_to_smartlist(sl
, allow_invalid
,
2157 need_uptime
, need_capacity
,
2158 need_guard
, need_desc
);
2159 smartlist_subtract(sl
,excludednodes
);
2160 if (excludedsmartlist
)
2161 smartlist_subtract(sl
,excludedsmartlist
);
2163 routerset_subtract_nodes(sl
,excludedset
);
2165 // Always weight by bandwidth
2166 choice
= node_sl_choose_by_bandwidth(sl
, rule
);
2169 if (!choice
&& (need_uptime
|| need_capacity
|| need_guard
)) {
2170 /* try once more -- recurse but with fewer restrictions. */
2172 "We couldn't find any live%s%s%s routers; falling back "
2173 "to list of all routers.",
2174 need_capacity
?", fast":"",
2175 need_uptime
?", stable":"",
2176 need_guard
?", guard":"");
2177 flags
&= ~ (CRN_NEED_UPTIME
|CRN_NEED_CAPACITY
|CRN_NEED_GUARD
);
2178 choice
= router_choose_random_node(
2179 excludedsmartlist
, excludedset
, flags
);
2181 smartlist_free(excludednodes
);
2184 "No available nodes when trying to choose node. Failing.");
2189 /** Helper: given an extended nickname in <b>hexdigest</b> try to decode it.
2190 * Return 0 on success, -1 on failure. Store the result into the
2191 * DIGEST_LEN-byte buffer at <b>digest_out</b>, the single character at
2192 * <b>nickname_qualifier_char_out</b>, and the MAXNICKNAME_LEN+1-byte buffer
2193 * at <b>nickname_out</b>.
2195 * The recognized format is:
2196 * HexName = Dollar? HexDigest NamePart?
2198 * HexDigest = HexChar*20
2199 * HexChar = 'a'..'f' | 'A'..'F' | '0'..'9'
2200 * NamePart = QualChar Name
2201 * QualChar = '=' | '~'
2202 * Name = NameChar*(1..MAX_NICKNAME_LEN)
2203 * NameChar = Any ASCII alphanumeric character
2206 hex_digest_nickname_decode(const char *hexdigest
,
2208 char *nickname_qualifier_char_out
,
2213 tor_assert(hexdigest
);
2214 if (hexdigest
[0] == '$')
2217 len
= strlen(hexdigest
);
2218 if (len
< HEX_DIGEST_LEN
) {
2220 } else if (len
> HEX_DIGEST_LEN
&& (hexdigest
[HEX_DIGEST_LEN
] == '=' ||
2221 hexdigest
[HEX_DIGEST_LEN
] == '~') &&
2222 len
<= HEX_DIGEST_LEN
+1+MAX_NICKNAME_LEN
) {
2223 *nickname_qualifier_char_out
= hexdigest
[HEX_DIGEST_LEN
];
2224 strlcpy(nickname_out
, hexdigest
+HEX_DIGEST_LEN
+1 , MAX_NICKNAME_LEN
+1);
2225 } else if (len
== HEX_DIGEST_LEN
) {
2231 if (base16_decode(digest_out
, DIGEST_LEN
, hexdigest
, HEX_DIGEST_LEN
)<0)
2236 /** Helper: Return true iff the <b>identity_digest</b> and <b>nickname</b>
2237 * combination of a router, encoded in hexadecimal, matches <b>hexdigest</b>
2238 * (which is optionally prefixed with a single dollar sign). Return false if
2239 * <b>hexdigest</b> is malformed, or it doesn't match. */
2241 hex_digest_nickname_matches(const char *hexdigest
, const char *identity_digest
,
2242 const char *nickname
, int is_named
)
2244 char digest
[DIGEST_LEN
];
2246 char nn_buf
[MAX_NICKNAME_LEN
+1];
2248 if (hex_digest_nickname_decode(hexdigest
, digest
, &nn_char
, nn_buf
) == -1)
2251 if (nn_char
== '=' || nn_char
== '~') {
2254 if (strcasecmp(nn_buf
, nickname
))
2256 if (nn_char
== '=' && !is_named
)
2260 return tor_memeq(digest
, identity_digest
, DIGEST_LEN
);
2263 /** Return true iff <b>router</b> is listed as named in the current
2266 router_is_named(const routerinfo_t
*router
)
2268 const char *digest
=
2269 networkstatus_get_router_digest_by_nickname(router
->nickname
);
2272 tor_memeq(digest
, router
->cache_info
.identity_digest
, DIGEST_LEN
));
2275 /** Return true iff the digest of <b>router</b>'s identity key,
2276 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
2277 * optionally prefixed with a single dollar sign). Return false if
2278 * <b>hexdigest</b> is malformed, or it doesn't match. */
2280 router_hex_digest_matches(const routerinfo_t
*router
, const char *hexdigest
)
2282 return hex_digest_nickname_matches(hexdigest
,
2283 router
->cache_info
.identity_digest
,
2285 router_is_named(router
));
2288 /** Return true iff <b>digest</b> is the digest of the identity key of a
2289 * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
2290 * is zero, any authority is okay. */
2292 router_digest_is_trusted_dir_type(const char *digest
, dirinfo_type_t type
)
2294 if (!trusted_dir_servers
)
2296 if (authdir_mode(get_options()) && router_digest_is_me(digest
))
2298 SMARTLIST_FOREACH(trusted_dir_servers
, dir_server_t
*, ent
,
2299 if (tor_memeq(digest
, ent
->digest
, DIGEST_LEN
)) {
2300 return (!type
) || ((type
& ent
->type
) != 0);
2305 /** Return true iff <b>addr</b> is the address of one of our trusted
2306 * directory authorities. */
2308 router_addr_is_trusted_dir(uint32_t addr
)
2310 if (!trusted_dir_servers
)
2312 SMARTLIST_FOREACH(trusted_dir_servers
, dir_server_t
*, ent
,
2313 if (ent
->addr
== addr
)
2319 /** If hexdigest is correctly formed, base16_decode it into
2320 * digest, which must have DIGEST_LEN space in it.
2321 * Return 0 on success, -1 on failure.
2324 hexdigest_to_digest(const char *hexdigest
, char *digest
)
2326 if (hexdigest
[0]=='$')
2328 if (strlen(hexdigest
) < HEX_DIGEST_LEN
||
2329 base16_decode(digest
,DIGEST_LEN
,hexdigest
,HEX_DIGEST_LEN
) < 0)
2334 /** As router_get_by_id_digest,but return a pointer that you're allowed to
2337 router_get_mutable_by_digest(const char *digest
)
2341 if (!routerlist
) return NULL
;
2343 // routerlist_assert_ok(routerlist);
2345 return rimap_get(routerlist
->identity_map
, digest
);
2348 /** Return the router in our routerlist whose 20-byte key digest
2349 * is <b>digest</b>. Return NULL if no such router is known. */
2350 const routerinfo_t
*
2351 router_get_by_id_digest(const char *digest
)
2353 return router_get_mutable_by_digest(digest
);
2356 /** Return the router in our routerlist whose 20-byte descriptor
2357 * is <b>digest</b>. Return NULL if no such router is known. */
2358 signed_descriptor_t
*
2359 router_get_by_descriptor_digest(const char *digest
)
2363 if (!routerlist
) return NULL
;
2365 return sdmap_get(routerlist
->desc_digest_map
, digest
);
2368 /** Return the signed descriptor for the router in our routerlist whose
2369 * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
2371 signed_descriptor_t
*
2372 router_get_by_extrainfo_digest(const char *digest
)
2376 if (!routerlist
) return NULL
;
2378 return sdmap_get(routerlist
->desc_by_eid_map
, digest
);
2381 /** Return the signed descriptor for the extrainfo_t in our routerlist whose
2382 * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
2383 * document is known. */
2384 signed_descriptor_t
*
2385 extrainfo_get_by_descriptor_digest(const char *digest
)
2389 if (!routerlist
) return NULL
;
2390 ei
= eimap_get(routerlist
->extra_info_map
, digest
);
2391 return ei
? &ei
->cache_info
: NULL
;
2394 /** Return a pointer to the signed textual representation of a descriptor.
2395 * The returned string is not guaranteed to be NUL-terminated: the string's
2396 * length will be in desc-\>signed_descriptor_len.
2398 * If <b>with_annotations</b> is set, the returned string will include
2400 * (if any) preceding the descriptor. This will increase the length of the
2401 * string by desc-\>annotations_len.
2403 * The caller must not free the string returned.
2406 signed_descriptor_get_body_impl(const signed_descriptor_t
*desc
,
2407 int with_annotations
)
2409 const char *r
= NULL
;
2410 size_t len
= desc
->signed_descriptor_len
;
2411 off_t offset
= desc
->saved_offset
;
2412 if (with_annotations
)
2413 len
+= desc
->annotations_len
;
2415 offset
+= desc
->annotations_len
;
2417 tor_assert(len
> 32);
2418 if (desc
->saved_location
== SAVED_IN_CACHE
&& routerlist
) {
2419 desc_store_t
*store
= desc_get_store(router_get_routerlist(), desc
);
2420 if (store
&& store
->mmap
) {
2421 tor_assert(desc
->saved_offset
+ len
<= store
->mmap
->size
);
2422 r
= store
->mmap
->data
+ offset
;
2424 log_err(LD_DIR
, "We couldn't read a descriptor that is supposedly "
2425 "mmaped in our cache. Is another process running in our data "
2426 "directory? Exiting.");
2430 if (!r
) /* no mmap, or not in cache. */
2431 r
= desc
->signed_descriptor_body
+
2432 (with_annotations
? 0 : desc
->annotations_len
);
2435 if (!with_annotations
) {
2436 if (fast_memcmp("router ", r
, 7) && fast_memcmp("extra-info ", r
, 11)) {
2437 char *cp
= tor_strndup(r
, 64);
2438 log_err(LD_DIR
, "descriptor at %p begins with unexpected string %s. "
2439 "Is another process running in our data directory? Exiting.",
2448 /** Return a pointer to the signed textual representation of a descriptor.
2449 * The returned string is not guaranteed to be NUL-terminated: the string's
2450 * length will be in desc-\>signed_descriptor_len.
2452 * The caller must not free the string returned.
2455 signed_descriptor_get_body(const signed_descriptor_t
*desc
)
2457 return signed_descriptor_get_body_impl(desc
, 0);
2460 /** As signed_descriptor_get_body(), but points to the beginning of the
2461 * annotations section rather than the beginning of the descriptor. */
2463 signed_descriptor_get_annotations(const signed_descriptor_t
*desc
)
2465 return signed_descriptor_get_body_impl(desc
, 1);
2468 /** Return the current list of all known routers. */
2470 router_get_routerlist(void)
2472 if (PREDICT_UNLIKELY(!routerlist
)) {
2473 routerlist
= tor_malloc_zero(sizeof(routerlist_t
));
2474 routerlist
->routers
= smartlist_new();
2475 routerlist
->old_routers
= smartlist_new();
2476 routerlist
->identity_map
= rimap_new();
2477 routerlist
->desc_digest_map
= sdmap_new();
2478 routerlist
->desc_by_eid_map
= sdmap_new();
2479 routerlist
->extra_info_map
= eimap_new();
2481 routerlist
->desc_store
.fname_base
= "cached-descriptors";
2482 routerlist
->desc_store
.fname_alt_base
= "cached-routers";
2483 routerlist
->extrainfo_store
.fname_base
= "cached-extrainfo";
2485 routerlist
->desc_store
.type
= ROUTER_STORE
;
2486 routerlist
->extrainfo_store
.type
= EXTRAINFO_STORE
;
2488 routerlist
->desc_store
.description
= "router descriptors";
2489 routerlist
->extrainfo_store
.description
= "extra-info documents";
2494 /** Free all storage held by <b>router</b>. */
2496 routerinfo_free(routerinfo_t
*router
)
2501 tor_free(router
->cache_info
.signed_descriptor_body
);
2502 tor_free(router
->address
);
2503 tor_free(router
->nickname
);
2504 tor_free(router
->platform
);
2505 tor_free(router
->contact_info
);
2506 if (router
->onion_pkey
)
2507 crypto_pk_free(router
->onion_pkey
);
2508 tor_free(router
->onion_curve25519_pkey
);
2509 if (router
->identity_pkey
)
2510 crypto_pk_free(router
->identity_pkey
);
2511 if (router
->declared_family
) {
2512 SMARTLIST_FOREACH(router
->declared_family
, char *, s
, tor_free(s
));
2513 smartlist_free(router
->declared_family
);
2515 addr_policy_list_free(router
->exit_policy
);
2516 short_policy_free(router
->ipv6_exit_policy
);
2518 memset(router
, 77, sizeof(routerinfo_t
));
2523 /** Release all storage held by <b>extrainfo</b> */
2525 extrainfo_free(extrainfo_t
*extrainfo
)
2529 tor_free(extrainfo
->cache_info
.signed_descriptor_body
);
2530 tor_free(extrainfo
->pending_sig
);
2532 memset(extrainfo
, 88, sizeof(extrainfo_t
)); /* debug bad memory usage */
2533 tor_free(extrainfo
);
2536 /** Release storage held by <b>sd</b>. */
2538 signed_descriptor_free(signed_descriptor_t
*sd
)
2543 tor_free(sd
->signed_descriptor_body
);
2545 memset(sd
, 99, sizeof(signed_descriptor_t
)); /* Debug bad mem usage */
2549 /** Extract a signed_descriptor_t from a general routerinfo, and free the
2552 static signed_descriptor_t
*
2553 signed_descriptor_from_routerinfo(routerinfo_t
*ri
)
2555 signed_descriptor_t
*sd
;
2556 tor_assert(ri
->purpose
== ROUTER_PURPOSE_GENERAL
);
2557 sd
= tor_malloc_zero(sizeof(signed_descriptor_t
));
2558 memcpy(sd
, &(ri
->cache_info
), sizeof(signed_descriptor_t
));
2559 sd
->routerlist_index
= -1;
2560 ri
->cache_info
.signed_descriptor_body
= NULL
;
2561 routerinfo_free(ri
);
2565 /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
2567 extrainfo_free_(void *e
)
2572 /** Free all storage held by a routerlist <b>rl</b>. */
2574 routerlist_free(routerlist_t
*rl
)
2578 rimap_free(rl
->identity_map
, NULL
);
2579 sdmap_free(rl
->desc_digest_map
, NULL
);
2580 sdmap_free(rl
->desc_by_eid_map
, NULL
);
2581 eimap_free(rl
->extra_info_map
, extrainfo_free_
);
2582 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
2583 routerinfo_free(r
));
2584 SMARTLIST_FOREACH(rl
->old_routers
, signed_descriptor_t
*, sd
,
2585 signed_descriptor_free(sd
));
2586 smartlist_free(rl
->routers
);
2587 smartlist_free(rl
->old_routers
);
2588 if (routerlist
->desc_store
.mmap
)
2589 tor_munmap_file(routerlist
->desc_store
.mmap
);
2590 if (routerlist
->extrainfo_store
.mmap
)
2591 tor_munmap_file(routerlist
->extrainfo_store
.mmap
);
2594 router_dir_info_changed();
2597 /** Log information about how much memory is being used for routerlist,
2598 * at log level <b>severity</b>. */
2600 dump_routerlist_mem_usage(int severity
)
2602 uint64_t livedescs
= 0;
2603 uint64_t olddescs
= 0;
2606 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, r
,
2607 livedescs
+= r
->cache_info
.signed_descriptor_len
);
2608 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
,
2609 olddescs
+= sd
->signed_descriptor_len
);
2611 tor_log(severity
, LD_DIR
,
2612 "In %d live descriptors: "U64_FORMAT
" bytes. "
2613 "In %d old descriptors: "U64_FORMAT
" bytes.",
2614 smartlist_len(routerlist
->routers
), U64_PRINTF_ARG(livedescs
),
2615 smartlist_len(routerlist
->old_routers
), U64_PRINTF_ARG(olddescs
));
2618 /** Debugging helper: If <b>idx</b> is nonnegative, assert that <b>ri</b> is
2619 * in <b>sl</b> at position <b>idx</b>. Otherwise, search <b>sl</b> for
2620 * <b>ri</b>. Return the index of <b>ri</b> in <b>sl</b>, or -1 if <b>ri</b>
2621 * is not in <b>sl</b>. */
2623 routerlist_find_elt_(smartlist_t
*sl
, void *ri
, int idx
)
2627 SMARTLIST_FOREACH(sl
, routerinfo_t
*, r
,
2633 tor_assert(idx
< smartlist_len(sl
));
2634 tor_assert(smartlist_get(sl
, idx
) == ri
);
2639 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
2640 * as needed. There must be no previous member of <b>rl</b> with the same
2641 * identity digest as <b>ri</b>: If there is, call routerlist_replace
2645 routerlist_insert(routerlist_t
*rl
, routerinfo_t
*ri
)
2647 routerinfo_t
*ri_old
;
2648 signed_descriptor_t
*sd_old
;
2650 const routerinfo_t
*ri_generated
= router_get_my_routerinfo();
2651 tor_assert(ri_generated
!= ri
);
2653 tor_assert(ri
->cache_info
.routerlist_index
== -1);
2655 ri_old
= rimap_set(rl
->identity_map
, ri
->cache_info
.identity_digest
, ri
);
2656 tor_assert(!ri_old
);
2658 sd_old
= sdmap_set(rl
->desc_digest_map
,
2659 ri
->cache_info
.signed_descriptor_digest
,
2662 int idx
= sd_old
->routerlist_index
;
2663 sd_old
->routerlist_index
= -1;
2664 smartlist_del(rl
->old_routers
, idx
);
2665 if (idx
< smartlist_len(rl
->old_routers
)) {
2666 signed_descriptor_t
*d
= smartlist_get(rl
->old_routers
, idx
);
2667 d
->routerlist_index
= idx
;
2669 rl
->desc_store
.bytes_dropped
+= sd_old
->signed_descriptor_len
;
2670 sdmap_remove(rl
->desc_by_eid_map
, sd_old
->extra_info_digest
);
2671 signed_descriptor_free(sd_old
);
2674 if (!tor_digest_is_zero(ri
->cache_info
.extra_info_digest
))
2675 sdmap_set(rl
->desc_by_eid_map
, ri
->cache_info
.extra_info_digest
,
2677 smartlist_add(rl
->routers
, ri
);
2678 ri
->cache_info
.routerlist_index
= smartlist_len(rl
->routers
) - 1;
2679 nodelist_set_routerinfo(ri
, NULL
);
2680 router_dir_info_changed();
2681 #ifdef DEBUG_ROUTERLIST
2682 routerlist_assert_ok(rl
);
2686 /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
2687 * corresponding router in rl-\>routers or rl-\>old_routers. Return true iff
2688 * we actually inserted <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
2690 extrainfo_insert(routerlist_t
*rl
, extrainfo_t
*ei
)
2693 routerinfo_t
*ri
= rimap_get(rl
->identity_map
,
2694 ei
->cache_info
.identity_digest
);
2695 signed_descriptor_t
*sd
=
2696 sdmap_get(rl
->desc_by_eid_map
, ei
->cache_info
.signed_descriptor_digest
);
2697 extrainfo_t
*ei_tmp
;
2700 extrainfo_t
*ei_generated
= router_get_my_extrainfo();
2701 tor_assert(ei_generated
!= ei
);
2705 /* This router is unknown; we can't even verify the signature. Give up.*/
2708 if (routerinfo_incompatible_with_extrainfo(ri
, ei
, sd
, NULL
)) {
2712 /* Okay, if we make it here, we definitely have a router corresponding to
2713 * this extrainfo. */
2715 ei_tmp
= eimap_set(rl
->extra_info_map
,
2716 ei
->cache_info
.signed_descriptor_digest
,
2720 rl
->extrainfo_store
.bytes_dropped
+=
2721 ei_tmp
->cache_info
.signed_descriptor_len
;
2722 extrainfo_free(ei_tmp
);
2729 #ifdef DEBUG_ROUTERLIST
2730 routerlist_assert_ok(rl
);
2735 #define should_cache_old_descriptors() \
2736 directory_caches_dir_info(get_options())
2738 /** If we're a directory cache and routerlist <b>rl</b> doesn't have
2739 * a copy of router <b>ri</b> yet, add it to the list of old (not
2740 * recommended but still served) descriptors. Else free it. */
2742 routerlist_insert_old(routerlist_t
*rl
, routerinfo_t
*ri
)
2745 const routerinfo_t
*ri_generated
= router_get_my_routerinfo();
2746 tor_assert(ri_generated
!= ri
);
2748 tor_assert(ri
->cache_info
.routerlist_index
== -1);
2750 if (should_cache_old_descriptors() &&
2751 ri
->purpose
== ROUTER_PURPOSE_GENERAL
&&
2752 !sdmap_get(rl
->desc_digest_map
,
2753 ri
->cache_info
.signed_descriptor_digest
)) {
2754 signed_descriptor_t
*sd
= signed_descriptor_from_routerinfo(ri
);
2755 sdmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
2756 smartlist_add(rl
->old_routers
, sd
);
2757 sd
->routerlist_index
= smartlist_len(rl
->old_routers
)-1;
2758 if (!tor_digest_is_zero(sd
->extra_info_digest
))
2759 sdmap_set(rl
->desc_by_eid_map
, sd
->extra_info_digest
, sd
);
2761 routerinfo_free(ri
);
2763 #ifdef DEBUG_ROUTERLIST
2764 routerlist_assert_ok(rl
);
2768 /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
2769 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl->routers,
2770 * idx) == ri, we don't need to do a linear search over the list to decide
2771 * which to remove. We fill the gap in rl->routers with a later element in
2772 * the list, if any exists. <b>ri</b> is freed.
2774 * If <b>make_old</b> is true, instead of deleting the router, we try adding
2775 * it to rl->old_routers. */
2777 routerlist_remove(routerlist_t
*rl
, routerinfo_t
*ri
, int make_old
, time_t now
)
2779 routerinfo_t
*ri_tmp
;
2780 extrainfo_t
*ei_tmp
;
2781 int idx
= ri
->cache_info
.routerlist_index
;
2782 tor_assert(0 <= idx
&& idx
< smartlist_len(rl
->routers
));
2783 tor_assert(smartlist_get(rl
->routers
, idx
) == ri
);
2785 nodelist_remove_routerinfo(ri
);
2787 /* make sure the rephist module knows that it's not running */
2788 rep_hist_note_router_unreachable(ri
->cache_info
.identity_digest
, now
);
2790 ri
->cache_info
.routerlist_index
= -1;
2791 smartlist_del(rl
->routers
, idx
);
2792 if (idx
< smartlist_len(rl
->routers
)) {
2793 routerinfo_t
*r
= smartlist_get(rl
->routers
, idx
);
2794 r
->cache_info
.routerlist_index
= idx
;
2797 ri_tmp
= rimap_remove(rl
->identity_map
, ri
->cache_info
.identity_digest
);
2798 router_dir_info_changed();
2799 tor_assert(ri_tmp
== ri
);
2801 if (make_old
&& should_cache_old_descriptors() &&
2802 ri
->purpose
== ROUTER_PURPOSE_GENERAL
) {
2803 signed_descriptor_t
*sd
;
2804 sd
= signed_descriptor_from_routerinfo(ri
);
2805 smartlist_add(rl
->old_routers
, sd
);
2806 sd
->routerlist_index
= smartlist_len(rl
->old_routers
)-1;
2807 sdmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
2808 if (!tor_digest_is_zero(sd
->extra_info_digest
))
2809 sdmap_set(rl
->desc_by_eid_map
, sd
->extra_info_digest
, sd
);
2811 signed_descriptor_t
*sd_tmp
;
2812 sd_tmp
= sdmap_remove(rl
->desc_digest_map
,
2813 ri
->cache_info
.signed_descriptor_digest
);
2814 tor_assert(sd_tmp
== &(ri
->cache_info
));
2815 rl
->desc_store
.bytes_dropped
+= ri
->cache_info
.signed_descriptor_len
;
2816 ei_tmp
= eimap_remove(rl
->extra_info_map
,
2817 ri
->cache_info
.extra_info_digest
);
2819 rl
->extrainfo_store
.bytes_dropped
+=
2820 ei_tmp
->cache_info
.signed_descriptor_len
;
2821 extrainfo_free(ei_tmp
);
2823 if (!tor_digest_is_zero(ri
->cache_info
.extra_info_digest
))
2824 sdmap_remove(rl
->desc_by_eid_map
, ri
->cache_info
.extra_info_digest
);
2825 routerinfo_free(ri
);
2827 #ifdef DEBUG_ROUTERLIST
2828 routerlist_assert_ok(rl
);
2832 /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
2833 * adjust <b>rl</b> as appropriate. <b>idx</b> is -1, or the index of
2836 routerlist_remove_old(routerlist_t
*rl
, signed_descriptor_t
*sd
, int idx
)
2838 signed_descriptor_t
*sd_tmp
;
2839 extrainfo_t
*ei_tmp
;
2840 desc_store_t
*store
;
2842 idx
= sd
->routerlist_index
;
2844 tor_assert(0 <= idx
&& idx
< smartlist_len(rl
->old_routers
));
2845 /* XXXX edmanm's bridge relay triggered the following assert while
2846 * running 0.2.0.12-alpha. If anybody triggers this again, see if we
2847 * can get a backtrace. */
2848 tor_assert(smartlist_get(rl
->old_routers
, idx
) == sd
);
2849 tor_assert(idx
== sd
->routerlist_index
);
2851 sd
->routerlist_index
= -1;
2852 smartlist_del(rl
->old_routers
, idx
);
2853 if (idx
< smartlist_len(rl
->old_routers
)) {
2854 signed_descriptor_t
*d
= smartlist_get(rl
->old_routers
, idx
);
2855 d
->routerlist_index
= idx
;
2857 sd_tmp
= sdmap_remove(rl
->desc_digest_map
,
2858 sd
->signed_descriptor_digest
);
2859 tor_assert(sd_tmp
== sd
);
2860 store
= desc_get_store(rl
, sd
);
2862 store
->bytes_dropped
+= sd
->signed_descriptor_len
;
2864 ei_tmp
= eimap_remove(rl
->extra_info_map
,
2865 sd
->extra_info_digest
);
2867 rl
->extrainfo_store
.bytes_dropped
+=
2868 ei_tmp
->cache_info
.signed_descriptor_len
;
2869 extrainfo_free(ei_tmp
);
2871 if (!tor_digest_is_zero(sd
->extra_info_digest
))
2872 sdmap_remove(rl
->desc_by_eid_map
, sd
->extra_info_digest
);
2874 signed_descriptor_free(sd
);
2875 #ifdef DEBUG_ROUTERLIST
2876 routerlist_assert_ok(rl
);
2880 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
2881 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
2882 * smartlist_get(rl->routers, idx) == ri, we don't need to do a linear
2883 * search over the list to decide which to remove. We put ri_new in the same
2884 * index as ri_old, if possible. ri is freed as appropriate.
2886 * If should_cache_descriptors() is true, instead of deleting the router,
2887 * we add it to rl->old_routers. */
2889 routerlist_replace(routerlist_t
*rl
, routerinfo_t
*ri_old
,
2890 routerinfo_t
*ri_new
)
2893 int same_descriptors
;
2895 routerinfo_t
*ri_tmp
;
2896 extrainfo_t
*ei_tmp
;
2898 const routerinfo_t
*ri_generated
= router_get_my_routerinfo();
2899 tor_assert(ri_generated
!= ri_new
);
2901 tor_assert(ri_old
!= ri_new
);
2902 tor_assert(ri_new
->cache_info
.routerlist_index
== -1);
2904 idx
= ri_old
->cache_info
.routerlist_index
;
2905 tor_assert(0 <= idx
&& idx
< smartlist_len(rl
->routers
));
2906 tor_assert(smartlist_get(rl
->routers
, idx
) == ri_old
);
2909 routerinfo_t
*ri_old_tmp
=NULL
;
2910 nodelist_set_routerinfo(ri_new
, &ri_old_tmp
);
2911 tor_assert(ri_old
== ri_old_tmp
);
2914 router_dir_info_changed();
2916 smartlist_set(rl
->routers
, idx
, ri_new
);
2917 ri_old
->cache_info
.routerlist_index
= -1;
2918 ri_new
->cache_info
.routerlist_index
= idx
;
2919 /* Check that ri_old is not in rl->routers anymore: */
2920 tor_assert( routerlist_find_elt_(rl
->routers
, ri_old
, -1) == -1 );
2922 log_warn(LD_BUG
, "Appending entry from routerlist_replace.");
2923 routerlist_insert(rl
, ri_new
);
2926 if (tor_memneq(ri_old
->cache_info
.identity_digest
,
2927 ri_new
->cache_info
.identity_digest
, DIGEST_LEN
)) {
2928 /* digests don't match; digestmap_set won't replace */
2929 rimap_remove(rl
->identity_map
, ri_old
->cache_info
.identity_digest
);
2931 ri_tmp
= rimap_set(rl
->identity_map
,
2932 ri_new
->cache_info
.identity_digest
, ri_new
);
2933 tor_assert(!ri_tmp
|| ri_tmp
== ri_old
);
2934 sdmap_set(rl
->desc_digest_map
,
2935 ri_new
->cache_info
.signed_descriptor_digest
,
2936 &(ri_new
->cache_info
));
2938 if (!tor_digest_is_zero(ri_new
->cache_info
.extra_info_digest
)) {
2939 sdmap_set(rl
->desc_by_eid_map
, ri_new
->cache_info
.extra_info_digest
,
2940 &ri_new
->cache_info
);
2943 same_descriptors
= tor_memeq(ri_old
->cache_info
.signed_descriptor_digest
,
2944 ri_new
->cache_info
.signed_descriptor_digest
,
2947 if (should_cache_old_descriptors() &&
2948 ri_old
->purpose
== ROUTER_PURPOSE_GENERAL
&&
2949 !same_descriptors
) {
2950 /* ri_old is going to become a signed_descriptor_t and go into
2952 signed_descriptor_t
*sd
= signed_descriptor_from_routerinfo(ri_old
);
2953 smartlist_add(rl
->old_routers
, sd
);
2954 sd
->routerlist_index
= smartlist_len(rl
->old_routers
)-1;
2955 sdmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
2956 if (!tor_digest_is_zero(sd
->extra_info_digest
))
2957 sdmap_set(rl
->desc_by_eid_map
, sd
->extra_info_digest
, sd
);
2959 /* We're dropping ri_old. */
2960 if (!same_descriptors
) {
2961 /* digests don't match; The sdmap_set above didn't replace */
2962 sdmap_remove(rl
->desc_digest_map
,
2963 ri_old
->cache_info
.signed_descriptor_digest
);
2965 if (tor_memneq(ri_old
->cache_info
.extra_info_digest
,
2966 ri_new
->cache_info
.extra_info_digest
, DIGEST_LEN
)) {
2967 ei_tmp
= eimap_remove(rl
->extra_info_map
,
2968 ri_old
->cache_info
.extra_info_digest
);
2970 rl
->extrainfo_store
.bytes_dropped
+=
2971 ei_tmp
->cache_info
.signed_descriptor_len
;
2972 extrainfo_free(ei_tmp
);
2976 if (!tor_digest_is_zero(ri_old
->cache_info
.extra_info_digest
)) {
2977 sdmap_remove(rl
->desc_by_eid_map
,
2978 ri_old
->cache_info
.extra_info_digest
);
2981 rl
->desc_store
.bytes_dropped
+= ri_old
->cache_info
.signed_descriptor_len
;
2982 routerinfo_free(ri_old
);
2984 #ifdef DEBUG_ROUTERLIST
2985 routerlist_assert_ok(rl
);
2989 /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
2990 * it as a fresh routerinfo_t. */
2991 static routerinfo_t
*
2992 routerlist_reparse_old(routerlist_t
*rl
, signed_descriptor_t
*sd
)
2997 body
= signed_descriptor_get_annotations(sd
);
2999 ri
= router_parse_entry_from_string(body
,
3000 body
+sd
->signed_descriptor_len
+sd
->annotations_len
,
3004 memcpy(&ri
->cache_info
, sd
, sizeof(signed_descriptor_t
));
3005 sd
->signed_descriptor_body
= NULL
; /* Steal reference. */
3006 ri
->cache_info
.routerlist_index
= -1;
3008 routerlist_remove_old(rl
, sd
, -1);
3013 /** Free all memory held by the routerlist module. */
3015 routerlist_free_all(void)
3017 routerlist_free(routerlist
);
3019 if (warned_nicknames
) {
3020 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
3021 smartlist_free(warned_nicknames
);
3022 warned_nicknames
= NULL
;
3024 clear_dir_servers();
3025 smartlist_free(trusted_dir_servers
);
3026 smartlist_free(fallback_dir_servers
);
3027 trusted_dir_servers
= fallback_dir_servers
= NULL
;
3028 if (trusted_dir_certs
) {
3029 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
3030 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
3031 authority_cert_free(cert
));
3032 smartlist_free(cl
->certs
);
3034 } DIGESTMAP_FOREACH_END
;
3035 digestmap_free(trusted_dir_certs
, NULL
);
3036 trusted_dir_certs
= NULL
;
3040 /** Forget that we have issued any router-related warnings, so that we'll
3041 * warn again if we see the same errors. */
3043 routerlist_reset_warnings(void)
3045 if (!warned_nicknames
)
3046 warned_nicknames
= smartlist_new();
3047 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
3048 smartlist_clear(warned_nicknames
); /* now the list is empty. */
3050 networkstatus_reset_warnings();
3053 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
3054 * older entries (if any) with the same key. Note: Callers should not hold
3055 * their pointers to <b>router</b> if this function fails; <b>router</b>
3056 * will either be inserted into the routerlist or freed. Similarly, even
3057 * if this call succeeds, they should not hold their pointers to
3058 * <b>router</b> after subsequent calls with other routerinfo's -- they
3059 * might cause the original routerinfo to get freed.
3061 * Returns the status for the operation. Might set *<b>msg</b> if it wants
3062 * the poster of the router to know something.
3064 * If <b>from_cache</b>, this descriptor came from our disk cache. If
3065 * <b>from_fetch</b>, we received it in response to a request we made.
3066 * (If both are false, that means it was uploaded to us as an auth dir
3067 * server or via the controller.)
3069 * This function should be called *after*
3070 * routers_update_status_from_consensus_networkstatus; subsequently, you
3071 * should call router_rebuild_store and routerlist_descriptors_added.
3074 router_add_to_routerlist(routerinfo_t
*router
, const char **msg
,
3075 int from_cache
, int from_fetch
)
3077 const char *id_digest
;
3078 const or_options_t
*options
= get_options();
3079 int authdir
= authdir_mode_handles_descs(options
, router
->purpose
);
3080 int authdir_believes_valid
= 0;
3081 routerinfo_t
*old_router
;
3082 networkstatus_t
*consensus
=
3083 networkstatus_get_latest_consensus_by_flavor(FLAV_NS
);
3084 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
3085 int in_consensus
= 0;
3090 router_get_routerlist();
3092 id_digest
= router
->cache_info
.identity_digest
;
3094 old_router
= router_get_mutable_by_digest(id_digest
);
3096 /* Make sure that we haven't already got this exact descriptor. */
3097 if (sdmap_get(routerlist
->desc_digest_map
,
3098 router
->cache_info
.signed_descriptor_digest
)) {
3099 /* If we have this descriptor already and the new descriptor is a bridge
3100 * descriptor, replace it. If we had a bridge descriptor before and the
3101 * new one is not a bridge descriptor, don't replace it. */
3103 /* Only members of routerlist->identity_map can be bridges; we don't
3104 * put bridges in old_routers. */
3105 const int was_bridge
= old_router
&&
3106 old_router
->purpose
== ROUTER_PURPOSE_BRIDGE
;
3108 if (routerinfo_is_a_configured_bridge(router
) &&
3109 router
->purpose
== ROUTER_PURPOSE_BRIDGE
&&
3111 log_info(LD_DIR
, "Replacing non-bridge descriptor with bridge "
3112 "descriptor for router %s",
3113 router_describe(router
));
3116 "Dropping descriptor that we already have for router %s",
3117 router_describe(router
));
3118 *msg
= "Router descriptor was not new.";
3119 routerinfo_free(router
);
3120 return ROUTER_WAS_NOT_NEW
;
3125 if (authdir_wants_to_reject_router(router
, msg
,
3126 !from_cache
&& !from_fetch
,
3127 &authdir_believes_valid
)) {
3129 routerinfo_free(router
);
3130 return ROUTER_AUTHDIR_REJECTS
;
3132 } else if (from_fetch
) {
3133 /* Only check the descriptor digest against the network statuses when
3134 * we are receiving in response to a fetch. */
3136 if (!signed_desc_digest_is_recognized(&router
->cache_info
) &&
3137 !routerinfo_is_a_configured_bridge(router
)) {
3138 /* We asked for it, so some networkstatus must have listed it when we
3139 * did. Save it if we're a cache in case somebody else asks for it. */
3141 "Received a no-longer-recognized descriptor for router %s",
3142 router_describe(router
));
3143 *msg
= "Router descriptor is not referenced by any network-status.";
3145 /* Only journal this desc if we'll be serving it. */
3146 if (!from_cache
&& should_cache_old_descriptors())
3147 signed_desc_append_to_journal(&router
->cache_info
,
3148 &routerlist
->desc_store
);
3149 routerlist_insert_old(routerlist
, router
);
3150 return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS
;
3154 /* We no longer need a router with this descriptor digest. */
3155 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
3157 routerstatus_t
*rs
=
3158 networkstatus_v2_find_mutable_entry(ns
, id_digest
);
3159 if (rs
&& tor_memeq(rs
->descriptor_digest
,
3160 router
->cache_info
.signed_descriptor_digest
,
3162 rs
->need_to_mirror
= 0;
3165 routerstatus_t
*rs
= networkstatus_vote_find_mutable_entry(
3166 consensus
, id_digest
);
3167 if (rs
&& tor_memeq(rs
->descriptor_digest
,
3168 router
->cache_info
.signed_descriptor_digest
,
3171 rs
->need_to_mirror
= 0;
3175 if (router
->purpose
== ROUTER_PURPOSE_GENERAL
&&
3176 consensus
&& !in_consensus
&& !authdir
) {
3177 /* If it's a general router not listed in the consensus, then don't
3178 * consider replacing the latest router with it. */
3179 if (!from_cache
&& should_cache_old_descriptors())
3180 signed_desc_append_to_journal(&router
->cache_info
,
3181 &routerlist
->desc_store
);
3182 routerlist_insert_old(routerlist
, router
);
3183 *msg
= "Skipping router descriptor: not in consensus.";
3184 return ROUTER_NOT_IN_CONSENSUS
;
3187 /* If we're reading a bridge descriptor from our cache, and we don't
3188 * recognize it as one of our currently configured bridges, drop the
3189 * descriptor. Otherwise we could end up using it as one of our entry
3190 * guards even if it isn't in our Bridge config lines. */
3191 if (router
->purpose
== ROUTER_PURPOSE_BRIDGE
&& from_cache
&&
3192 !authdir_mode_bridge(options
) &&
3193 !routerinfo_is_a_configured_bridge(router
)) {
3194 log_info(LD_DIR
, "Dropping bridge descriptor for %s because we have "
3195 "no bridge configured at that address.",
3196 safe_str_client(router_describe(router
)));
3197 *msg
= "Router descriptor was not a configured bridge.";
3198 routerinfo_free(router
);
3199 return ROUTER_WAS_NOT_WANTED
;
3202 /* If we have a router with the same identity key, choose the newer one. */
3204 if (!in_consensus
&& (router
->cache_info
.published_on
<=
3205 old_router
->cache_info
.published_on
)) {
3206 /* Same key, but old. This one is not listed in the consensus. */
3207 log_debug(LD_DIR
, "Not-new descriptor for router %s",
3208 router_describe(router
));
3209 /* Only journal this desc if we'll be serving it. */
3210 if (!from_cache
&& should_cache_old_descriptors())
3211 signed_desc_append_to_journal(&router
->cache_info
,
3212 &routerlist
->desc_store
);
3213 routerlist_insert_old(routerlist
, router
);
3214 *msg
= "Router descriptor was not new.";
3215 return ROUTER_WAS_NOT_NEW
;
3217 /* Same key, and either new, or listed in the consensus. */
3218 log_debug(LD_DIR
, "Replacing entry for router %s",
3219 router_describe(router
));
3220 routerlist_replace(routerlist
, old_router
, router
);
3222 signed_desc_append_to_journal(&router
->cache_info
,
3223 &routerlist
->desc_store
);
3225 directory_set_dirty();
3226 *msg
= authdir_believes_valid
? "Valid server updated" :
3227 ("Invalid server updated. (This dirserver is marking your "
3228 "server as unapproved.)");
3229 return ROUTER_ADDED_SUCCESSFULLY
;
3233 if (!in_consensus
&& from_cache
&&
3234 router
->cache_info
.published_on
< time(NULL
) - OLD_ROUTER_DESC_MAX_AGE
) {
3235 *msg
= "Router descriptor was really old.";
3236 routerinfo_free(router
);
3237 return ROUTER_WAS_NOT_NEW
;
3240 /* We haven't seen a router with this identity before. Add it to the end of
3242 routerlist_insert(routerlist
, router
);
3244 signed_desc_append_to_journal(&router
->cache_info
,
3245 &routerlist
->desc_store
);
3247 directory_set_dirty();
3248 return ROUTER_ADDED_SUCCESSFULLY
;
3251 /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
3252 * as for router_add_to_routerlist(). Return ROUTER_ADDED_SUCCESSFULLY iff
3253 * we actually inserted it, ROUTER_BAD_EI otherwise.
3256 router_add_extrainfo_to_routerlist(extrainfo_t
*ei
, const char **msg
,
3257 int from_cache
, int from_fetch
)
3261 if (msg
) *msg
= NULL
;
3262 /*XXXX023 Do something with msg */
3264 inserted
= extrainfo_insert(router_get_routerlist(), ei
);
3266 if (inserted
&& !from_cache
)
3267 signed_desc_append_to_journal(&ei
->cache_info
,
3268 &routerlist
->extrainfo_store
);
3271 return ROUTER_ADDED_SUCCESSFULLY
;
3273 return ROUTER_BAD_EI
;
3276 /** Sorting helper: return <0, 0, or >0 depending on whether the
3277 * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
3278 * to, or later than that of *<b>b</b>. */
3280 compare_old_routers_by_identity_(const void **_a
, const void **_b
)
3283 const signed_descriptor_t
*r1
= *_a
, *r2
= *_b
;
3284 if ((i
= fast_memcmp(r1
->identity_digest
, r2
->identity_digest
, DIGEST_LEN
)))
3286 return (int)(r1
->published_on
- r2
->published_on
);
3289 /** Internal type used to represent how long an old descriptor was valid,
3290 * where it appeared in the list of old descriptors, and whether it's extra
3291 * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
3292 struct duration_idx_t
{
3298 /** Sorting helper: compare two duration_idx_t by their duration. */
3300 compare_duration_idx_(const void *_d1
, const void *_d2
)
3302 const struct duration_idx_t
*d1
= _d1
;
3303 const struct duration_idx_t
*d2
= _d2
;
3304 return d1
->duration
- d2
->duration
;
3307 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
3308 * must contain routerinfo_t with the same identity and with publication time
3309 * in ascending order. Remove members from this range until there are no more
3310 * than max_descriptors_per_router() remaining. Start by removing the oldest
3311 * members from before <b>cutoff</b>, then remove members which were current
3312 * for the lowest amount of time. The order of members of old_routers at
3313 * indices <b>lo</b> or higher may be changed.
3316 routerlist_remove_old_cached_routers_with_id(time_t now
,
3317 time_t cutoff
, int lo
, int hi
,
3318 digestset_t
*retain
)
3321 unsigned n_extra
, n_rmv
= 0;
3322 struct duration_idx_t
*lifespans
;
3323 uint8_t *rmv
, *must_keep
;
3324 smartlist_t
*lst
= routerlist
->old_routers
;
3327 tor_assert(hi
< smartlist_len(lst
));
3328 tor_assert(lo
<= hi
);
3329 ident
= ((signed_descriptor_t
*)smartlist_get(lst
, lo
))->identity_digest
;
3330 for (i
= lo
+1; i
<= hi
; ++i
) {
3331 signed_descriptor_t
*r
= smartlist_get(lst
, i
);
3332 tor_assert(tor_memeq(ident
, r
->identity_digest
, DIGEST_LEN
));
3335 /* Check whether we need to do anything at all. */
3337 int mdpr
= directory_caches_dir_info(get_options()) ? 2 : 1;
3343 lifespans
= tor_malloc_zero(sizeof(struct duration_idx_t
)*n
);
3344 rmv
= tor_malloc_zero(sizeof(uint8_t)*n
);
3345 must_keep
= tor_malloc_zero(sizeof(uint8_t)*n
);
3346 /* Set lifespans to contain the lifespan and index of each server. */
3347 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
3348 for (i
= lo
; i
<= hi
; ++i
) {
3349 signed_descriptor_t
*r
= smartlist_get(lst
, i
);
3350 signed_descriptor_t
*r_next
;
3351 lifespans
[i
-lo
].idx
= i
;
3352 if (r
->last_listed_as_valid_until
>= now
||
3353 (retain
&& digestset_contains(retain
, r
->signed_descriptor_digest
))) {
3354 must_keep
[i
-lo
] = 1;
3357 r_next
= smartlist_get(lst
, i
+1);
3358 tor_assert(r
->published_on
<= r_next
->published_on
);
3359 lifespans
[i
-lo
].duration
= (int)(r_next
->published_on
- r
->published_on
);
3362 lifespans
[i
-lo
].duration
= INT_MAX
;
3364 if (!must_keep
[i
-lo
] && r
->published_on
< cutoff
&& n_rmv
< n_extra
) {
3366 lifespans
[i
-lo
].old
= 1;
3371 if (n_rmv
< n_extra
) {
3373 * We aren't removing enough servers for being old. Sort lifespans by
3374 * the duration of liveness, and remove the ones we're not already going to
3375 * remove based on how long they were alive.
3377 qsort(lifespans
, n
, sizeof(struct duration_idx_t
), compare_duration_idx_
);
3378 for (i
= 0; i
< n
&& n_rmv
< n_extra
; ++i
) {
3379 if (!must_keep
[lifespans
[i
].idx
-lo
] && !lifespans
[i
].old
) {
3380 rmv
[lifespans
[i
].idx
-lo
] = 1;
3389 routerlist_remove_old(routerlist
, smartlist_get(lst
, i
), i
);
3390 } while (--i
>= lo
);
3391 tor_free(must_keep
);
3393 tor_free(lifespans
);
3396 /** Deactivate any routers from the routerlist that are more than
3397 * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
3398 * remove old routers from the list of cached routers if we have too many.
3401 routerlist_remove_old_routers(void)
3404 const char *cur_id
= NULL
;
3405 time_t now
= time(NULL
);
3407 routerinfo_t
*router
;
3408 signed_descriptor_t
*sd
;
3409 digestset_t
*retain
;
3410 int caches
= directory_caches_dir_info(get_options());
3411 const networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
3412 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
3414 const or_options_t
*options
= get_options();
3416 trusted_dirs_remove_old_certs();
3418 if (!routerlist
|| !consensus
)
3421 // routerlist_assert_ok(routerlist);
3423 /* We need to guess how many router descriptors we will wind up wanting to
3424 retain, so that we can be sure to allocate a large enough Bloom filter
3425 to hold the digest set. Overestimating is fine; underestimating is bad.
3428 /* We'll probably retain everything in the consensus. */
3429 int n_max_retain
= smartlist_len(consensus
->routerstatus_list
);
3430 if (caches
&& networkstatus_v2_list
) {
3431 /* If we care about v2 statuses, we'll retain at most as many as are
3432 listed any of the v2 statues. This will be at least the length of
3433 the largest v2 networkstatus, and in the worst case, this set will be
3434 equal to the sum of the lengths of all v2 consensuses. Take the
3437 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
3438 n_max_retain
+= smartlist_len(ns
->entries
));
3440 retain
= digestset_new(n_max_retain
);
3443 cutoff
= now
- OLD_ROUTER_DESC_MAX_AGE
;
3444 /* Build a list of all the descriptors that _anybody_ lists. */
3445 if (caches
&& networkstatus_v2_list
) {
3446 SMARTLIST_FOREACH_BEGIN(networkstatus_v2_list
, networkstatus_v2_t
*, ns
) {
3447 /* XXXX The inner loop here gets pretty expensive, and actually shows up
3448 * on some profiles. It may be the reason digestmap_set shows up in
3449 * profiles too. If instead we kept a per-descriptor digest count of
3450 * how many networkstatuses recommended each descriptor, and changed
3451 * that only when the networkstatuses changed, that would be a speed
3452 * improvement, possibly 1-4% if it also removes digestmap_set from the
3453 * profile. Not worth it for 0.1.2.x, though. The new directory
3454 * system will obsolete this whole thing in 0.2.0.x. */
3455 SMARTLIST_FOREACH_BEGIN(ns
->entries
, routerstatus_t
*, rs
) {
3456 if (rs
->published_on
>= cutoff
)
3457 digestset_add(retain
, rs
->descriptor_digest
);
3458 } SMARTLIST_FOREACH_END(rs
);
3459 } SMARTLIST_FOREACH_END(ns
);
3462 /* Retain anything listed in the consensus. */
3464 SMARTLIST_FOREACH(consensus
->routerstatus_list
, routerstatus_t
*, rs
,
3465 if (rs
->published_on
>= cutoff
)
3466 digestset_add(retain
, rs
->descriptor_digest
));
3469 /* If we have a consensus, and nearly as many v2 networkstatuses as we want,
3470 * we should consider pruning current routers that are too old and that
3471 * nobody recommends. (If we don't have a consensus or enough v2
3472 * networkstatuses, then we should get more before we decide to kill
3474 /* we set this to true iff we don't care about v2 info, or we have enough. */
3475 have_enough_v2
= !caches
||
3476 !(authdir_mode_any_main(options
) || options
->FetchV2Networkstatus
) ||
3477 (networkstatus_v2_list
&&
3478 smartlist_len(networkstatus_v2_list
) > get_n_v2_authorities() / 2);
3480 if (have_enough_v2
&& consensus
) {
3481 cutoff
= now
- ROUTER_MAX_AGE
;
3482 /* Remove too-old unrecommended members of routerlist->routers. */
3483 for (i
= 0; i
< smartlist_len(routerlist
->routers
); ++i
) {
3484 router
= smartlist_get(routerlist
->routers
, i
);
3485 if (router
->cache_info
.published_on
<= cutoff
&&
3486 router
->cache_info
.last_listed_as_valid_until
< now
&&
3487 !digestset_contains(retain
,
3488 router
->cache_info
.signed_descriptor_digest
)) {
3489 /* Too old: remove it. (If we're a cache, just move it into
3492 "Forgetting obsolete (too old) routerinfo for router %s",
3493 router_describe(router
));
3494 routerlist_remove(routerlist
, router
, 1, now
);
3500 //routerlist_assert_ok(routerlist);
3502 /* Remove far-too-old members of routerlist->old_routers. */
3503 cutoff
= now
- OLD_ROUTER_DESC_MAX_AGE
;
3504 for (i
= 0; i
< smartlist_len(routerlist
->old_routers
); ++i
) {
3505 sd
= smartlist_get(routerlist
->old_routers
, i
);
3506 if (sd
->published_on
<= cutoff
&&
3507 sd
->last_listed_as_valid_until
< now
&&
3508 !digestset_contains(retain
, sd
->signed_descriptor_digest
)) {
3509 /* Too old. Remove it. */
3510 routerlist_remove_old(routerlist
, sd
, i
--);
3514 //routerlist_assert_ok(routerlist);
3516 log_info(LD_DIR
, "We have %d live routers and %d old router descriptors.",
3517 smartlist_len(routerlist
->routers
),
3518 smartlist_len(routerlist
->old_routers
));
3520 /* Now we might have to look at routerlist->old_routers for extraneous
3521 * members. (We'd keep all the members if we could, but we need to save
3522 * space.) First, check whether we have too many router descriptors, total.
3523 * We're okay with having too many for some given router, so long as the
3524 * total number doesn't approach max_descriptors_per_router()*len(router).
3526 if (smartlist_len(routerlist
->old_routers
) <
3527 smartlist_len(routerlist
->routers
))
3530 /* Sort by identity, then fix indices. */
3531 smartlist_sort(routerlist
->old_routers
, compare_old_routers_by_identity_
);
3533 for (i
= 0; i
< smartlist_len(routerlist
->old_routers
); ++i
) {
3534 signed_descriptor_t
*r
= smartlist_get(routerlist
->old_routers
, i
);
3535 r
->routerlist_index
= i
;
3538 /* Iterate through the list from back to front, so when we remove descriptors
3539 * we don't mess up groups we haven't gotten to. */
3540 for (i
= smartlist_len(routerlist
->old_routers
)-1; i
>= 0; --i
) {
3541 signed_descriptor_t
*r
= smartlist_get(routerlist
->old_routers
, i
);
3543 cur_id
= r
->identity_digest
;
3546 if (tor_memneq(cur_id
, r
->identity_digest
, DIGEST_LEN
)) {
3547 routerlist_remove_old_cached_routers_with_id(now
,
3548 cutoff
, i
+1, hi
, retain
);
3549 cur_id
= r
->identity_digest
;
3554 routerlist_remove_old_cached_routers_with_id(now
, cutoff
, 0, hi
, retain
);
3555 //routerlist_assert_ok(routerlist);
3558 digestset_free(retain
);
3559 router_rebuild_store(RRS_DONT_REMOVE_OLD
, &routerlist
->desc_store
);
3560 router_rebuild_store(RRS_DONT_REMOVE_OLD
,&routerlist
->extrainfo_store
);
3563 /** We just added a new set of descriptors. Take whatever extra steps
3566 routerlist_descriptors_added(smartlist_t
*sl
, int from_cache
)
3569 control_event_descriptors_changed(sl
);
3570 SMARTLIST_FOREACH_BEGIN(sl
, routerinfo_t
*, ri
) {
3571 if (ri
->purpose
== ROUTER_PURPOSE_BRIDGE
)
3572 learned_bridge_descriptor(ri
, from_cache
);
3573 if (ri
->needs_retest_if_added
) {
3574 ri
->needs_retest_if_added
= 0;
3575 dirserv_single_reachability_test(approx_time(), ri
);
3577 } SMARTLIST_FOREACH_END(ri
);
3581 * Code to parse a single router descriptor and insert it into the
3582 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
3583 * descriptor was well-formed but could not be added; and 1 if the
3584 * descriptor was added.
3586 * If we don't add it and <b>msg</b> is not NULL, then assign to
3587 * *<b>msg</b> a static string describing the reason for refusing the
3590 * This is used only by the controller.
3593 router_load_single_router(const char *s
, uint8_t purpose
, int cache
,
3597 was_router_added_t r
;
3599 char annotation_buf
[ROUTER_ANNOTATION_BUF_LEN
];
3603 tor_snprintf(annotation_buf
, sizeof(annotation_buf
),
3604 "@source controller\n"
3605 "@purpose %s\n", router_purpose_to_string(purpose
));
3607 if (!(ri
= router_parse_entry_from_string(s
, NULL
, 1, 0, annotation_buf
))) {
3608 log_warn(LD_DIR
, "Error parsing router descriptor; dropping.");
3609 *msg
= "Couldn't parse router descriptor.";
3612 tor_assert(ri
->purpose
== purpose
);
3613 if (router_is_me(ri
)) {
3614 log_warn(LD_DIR
, "Router's identity key matches mine; dropping.");
3615 *msg
= "Router's identity key matches mine.";
3616 routerinfo_free(ri
);
3620 if (!cache
) /* obey the preference of the controller */
3621 ri
->cache_info
.do_not_cache
= 1;
3623 lst
= smartlist_new();
3624 smartlist_add(lst
, ri
);
3625 routers_update_status_from_consensus_networkstatus(lst
, 0);
3627 r
= router_add_to_routerlist(ri
, msg
, 0, 0);
3628 if (!WRA_WAS_ADDED(r
)) {
3629 /* we've already assigned to *msg now, and ri is already freed */
3631 if (r
== ROUTER_AUTHDIR_REJECTS
)
3632 log_warn(LD_DIR
, "Couldn't add router to list: %s Dropping.", *msg
);
3633 smartlist_free(lst
);
3636 routerlist_descriptors_added(lst
, 0);
3637 smartlist_free(lst
);
3638 log_debug(LD_DIR
, "Added router to list");
3643 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
3644 * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
3645 * are in response to a query to the network: cache them by adding them to
3648 * Return the number of routers actually added.
3650 * If <b>requested_fingerprints</b> is provided, it must contain a list of
3651 * uppercased fingerprints. Do not update any router whose
3652 * fingerprint is not on the list; after updating a router, remove its
3653 * fingerprint from the list.
3655 * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
3656 * are descriptor digests. Otherwise they are identity digests.
3659 router_load_routers_from_string(const char *s
, const char *eos
,
3660 saved_location_t saved_location
,
3661 smartlist_t
*requested_fingerprints
,
3662 int descriptor_digests
,
3663 const char *prepend_annotations
)
3665 smartlist_t
*routers
= smartlist_new(), *changed
= smartlist_new();
3666 char fp
[HEX_DIGEST_LEN
+1];
3668 int from_cache
= (saved_location
!= SAVED_NOWHERE
);
3669 int allow_annotations
= (saved_location
!= SAVED_NOWHERE
);
3670 int any_changed
= 0;
3672 router_parse_list_from_string(&s
, eos
, routers
, saved_location
, 0,
3673 allow_annotations
, prepend_annotations
);
3675 routers_update_status_from_consensus_networkstatus(routers
, !from_cache
);
3677 log_info(LD_DIR
, "%d elements to add", smartlist_len(routers
));
3679 SMARTLIST_FOREACH_BEGIN(routers
, routerinfo_t
*, ri
) {
3680 was_router_added_t r
;
3682 if (requested_fingerprints
) {
3683 base16_encode(fp
, sizeof(fp
), descriptor_digests
?
3684 ri
->cache_info
.signed_descriptor_digest
:
3685 ri
->cache_info
.identity_digest
,
3687 if (smartlist_contains_string(requested_fingerprints
, fp
)) {
3688 smartlist_string_remove(requested_fingerprints
, fp
);
3691 smartlist_join_strings(requested_fingerprints
," ",0,NULL
);
3693 "We received a router descriptor with a fingerprint (%s) "
3694 "that we never requested. (We asked for: %s.) Dropping.",
3696 tor_free(requested
);
3697 routerinfo_free(ri
);
3702 memcpy(d
, ri
->cache_info
.signed_descriptor_digest
, DIGEST_LEN
);
3703 r
= router_add_to_routerlist(ri
, &msg
, from_cache
, !from_cache
);
3704 if (WRA_WAS_ADDED(r
)) {
3706 smartlist_add(changed
, ri
);
3707 routerlist_descriptors_added(changed
, from_cache
);
3708 smartlist_clear(changed
);
3709 } else if (WRA_WAS_REJECTED(r
)) {
3710 download_status_t
*dl_status
;
3711 dl_status
= router_get_dl_status_by_descriptor_digest(d
);
3713 log_info(LD_GENERAL
, "Marking router %s as never downloadable",
3714 hex_str(d
, DIGEST_LEN
));
3715 download_status_mark_impossible(dl_status
);
3718 } SMARTLIST_FOREACH_END(ri
);
3720 routerlist_assert_ok(routerlist
);
3723 router_rebuild_store(0, &routerlist
->desc_store
);
3725 smartlist_free(routers
);
3726 smartlist_free(changed
);
3731 /** Parse one or more extrainfos from <b>s</b> (ending immediately before
3732 * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
3733 * router_load_routers_from_string(). */
3735 router_load_extrainfo_from_string(const char *s
, const char *eos
,
3736 saved_location_t saved_location
,
3737 smartlist_t
*requested_fingerprints
,
3738 int descriptor_digests
)
3740 smartlist_t
*extrainfo_list
= smartlist_new();
3742 int from_cache
= (saved_location
!= SAVED_NOWHERE
);
3744 router_parse_list_from_string(&s
, eos
, extrainfo_list
, saved_location
, 1, 0,
3747 log_info(LD_DIR
, "%d elements to add", smartlist_len(extrainfo_list
));
3749 SMARTLIST_FOREACH_BEGIN(extrainfo_list
, extrainfo_t
*, ei
) {
3750 was_router_added_t added
=
3751 router_add_extrainfo_to_routerlist(ei
, &msg
, from_cache
, !from_cache
);
3752 if (WRA_WAS_ADDED(added
) && requested_fingerprints
) {
3753 char fp
[HEX_DIGEST_LEN
+1];
3754 base16_encode(fp
, sizeof(fp
), descriptor_digests
?
3755 ei
->cache_info
.signed_descriptor_digest
:
3756 ei
->cache_info
.identity_digest
,
3758 smartlist_string_remove(requested_fingerprints
, fp
);
3759 /* We silently let people stuff us with extrainfos we didn't ask for,
3760 * so long as we would have wanted them anyway. Since we always fetch
3761 * all the extrainfos we want, and we never actually act on them
3762 * inside Tor, this should be harmless. */
3764 } SMARTLIST_FOREACH_END(ei
);
3766 routerlist_assert_ok(routerlist
);
3767 router_rebuild_store(0, &router_get_routerlist()->extrainfo_store
);
3769 smartlist_free(extrainfo_list
);
3772 /** Return true iff any networkstatus includes a descriptor whose digest
3773 * is that of <b>desc</b>. */
3775 signed_desc_digest_is_recognized(signed_descriptor_t
*desc
)
3777 const routerstatus_t
*rs
;
3778 networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
3779 int caches
= directory_caches_dir_info(get_options());
3780 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
3783 rs
= networkstatus_vote_find_entry(consensus
, desc
->identity_digest
);
3784 if (rs
&& tor_memeq(rs
->descriptor_digest
,
3785 desc
->signed_descriptor_digest
, DIGEST_LEN
))
3788 if (caches
&& networkstatus_v2_list
) {
3789 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
3791 if (!(rs
= networkstatus_v2_find_entry(ns
, desc
->identity_digest
)))
3793 if (tor_memeq(rs
->descriptor_digest
,
3794 desc
->signed_descriptor_digest
, DIGEST_LEN
))
3801 /** Update downloads for router descriptors and/or microdescriptors as
3804 update_all_descriptor_downloads(time_t now
)
3806 if (get_options()->DisableNetwork
)
3808 update_router_descriptor_downloads(now
);
3809 update_microdesc_downloads(now
);
3810 launch_dummy_descriptor_download_as_needed(now
, get_options());
3813 /** Clear all our timeouts for fetching v2 and v3 directory stuff, and then
3814 * give it all a try again. */
3816 routerlist_retry_directory_downloads(time_t now
)
3818 router_reset_status_download_failures();
3819 router_reset_descriptor_download_failures();
3820 if (get_options()->DisableNetwork
)
3822 update_networkstatus_downloads(now
);
3823 update_all_descriptor_downloads(now
);
3826 /** Return true iff <b>router</b> does not permit exit streams.
3829 router_exit_policy_rejects_all(const routerinfo_t
*router
)
3831 return router
->policy_is_reject_star
;
3834 /** Create an directory server at <b>address</b>:<b>port</b>, with OR identity
3835 * key <b>digest</b>. If <b>address</b> is NULL, add ourself. If
3836 * <b>is_authority</b>, this is a directory authority. Return the new
3837 * directory server entry on success or NULL on failure. */
3838 static dir_server_t
*
3839 dir_server_new(int is_authority
,
3840 const char *nickname
,
3841 const tor_addr_t
*addr
,
3842 const char *hostname
,
3843 uint16_t dir_port
, uint16_t or_port
,
3844 const char *digest
, const char *v3_auth_digest
,
3845 dirinfo_type_t type
,
3850 char *hostname_
= NULL
;
3855 if (tor_addr_family(addr
) == AF_INET
)
3856 a
= tor_addr_to_ipv4h(addr
);
3858 return NULL
; /*XXXX Support IPv6 */
3861 hostname_
= tor_dup_addr(addr
);
3863 hostname_
= tor_strdup(hostname
);
3865 ent
= tor_malloc_zero(sizeof(dir_server_t
));
3866 ent
->nickname
= nickname
? tor_strdup(nickname
) : NULL
;
3867 ent
->address
= hostname_
;
3869 ent
->dir_port
= dir_port
;
3870 ent
->or_port
= or_port
;
3871 ent
->is_running
= 1;
3872 ent
->is_authority
= is_authority
;
3874 ent
->weight
= weight
;
3875 memcpy(ent
->digest
, digest
, DIGEST_LEN
);
3876 if (v3_auth_digest
&& (type
& V3_DIRINFO
))
3877 memcpy(ent
->v3_identity_digest
, v3_auth_digest
, DIGEST_LEN
);
3880 tor_asprintf(&ent
->description
, "directory server \"%s\" at %s:%d",
3881 nickname
, hostname
, (int)dir_port
);
3883 tor_asprintf(&ent
->description
, "directory server at %s:%d",
3884 hostname
, (int)dir_port
);
3886 ent
->fake_status
.addr
= ent
->addr
;
3887 memcpy(ent
->fake_status
.identity_digest
, digest
, DIGEST_LEN
);
3889 strlcpy(ent
->fake_status
.nickname
, nickname
,
3890 sizeof(ent
->fake_status
.nickname
));
3892 ent
->fake_status
.nickname
[0] = '\0';
3893 ent
->fake_status
.dir_port
= ent
->dir_port
;
3894 ent
->fake_status
.or_port
= ent
->or_port
;
3899 /** Create an authoritative directory server at
3900 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
3901 * <b>address</b> is NULL, add ourself. Return the new trusted directory
3902 * server entry on success or NULL if we couldn't add it. */
3904 trusted_dir_server_new(const char *nickname
, const char *address
,
3905 uint16_t dir_port
, uint16_t or_port
,
3906 const char *digest
, const char *v3_auth_digest
,
3907 dirinfo_type_t type
, double weight
)
3911 char *hostname
=NULL
;
3912 dir_server_t
*result
;
3914 if (!address
) { /* The address is us; we should guess. */
3915 if (resolve_my_address(LOG_WARN
, get_options(),
3916 &a
, NULL
, &hostname
) < 0) {
3918 "Couldn't find a suitable address when adding ourself as a "
3919 "trusted directory server.");
3923 hostname
= tor_dup_ip(a
);
3925 if (tor_lookup_hostname(address
, &a
)) {
3927 "Unable to lookup address for directory server at '%s'",
3931 hostname
= tor_strdup(address
);
3933 tor_addr_from_ipv4h(&addr
, a
);
3935 result
= dir_server_new(1, nickname
, &addr
, hostname
,
3936 dir_port
, or_port
, digest
,
3937 v3_auth_digest
, type
, weight
);
3942 /** Return a new dir_server_t for a fallback directory server at
3943 * <b>addr</b>:<b>or_port</b>/<b>dir_port</b>, with identity key digest
3944 * <b>id_digest</b> */
3946 fallback_dir_server_new(const tor_addr_t
*addr
,
3947 uint16_t dir_port
, uint16_t or_port
,
3948 const char *id_digest
, double weight
)
3950 return dir_server_new(0, NULL
, addr
, NULL
, dir_port
, or_port
, id_digest
,
3951 NULL
, ALL_DIRINFO
, weight
);
3954 /** Add a directory server to the global list(s). */
3956 dir_server_add(dir_server_t
*ent
)
3958 if (!trusted_dir_servers
)
3959 trusted_dir_servers
= smartlist_new();
3960 if (!fallback_dir_servers
)
3961 fallback_dir_servers
= smartlist_new();
3963 if (ent
->is_authority
)
3964 smartlist_add(trusted_dir_servers
, ent
);
3966 smartlist_add(fallback_dir_servers
, ent
);
3967 router_dir_info_changed();
3970 /** Free storage held in <b>cert</b>. */
3972 authority_cert_free(authority_cert_t
*cert
)
3977 tor_free(cert
->cache_info
.signed_descriptor_body
);
3978 crypto_pk_free(cert
->signing_key
);
3979 crypto_pk_free(cert
->identity_key
);
3984 /** Free storage held in <b>ds</b>. */
3986 dir_server_free(dir_server_t
*ds
)
3991 tor_free(ds
->nickname
);
3992 tor_free(ds
->description
);
3993 tor_free(ds
->address
);
3997 /** Remove all members from the list of dir servers. */
3999 clear_dir_servers(void)
4001 if (fallback_dir_servers
) {
4002 SMARTLIST_FOREACH(fallback_dir_servers
, dir_server_t
*, ent
,
4003 dir_server_free(ent
));
4004 smartlist_clear(fallback_dir_servers
);
4006 fallback_dir_servers
= smartlist_new();
4008 if (trusted_dir_servers
) {
4009 smartlist_clear(trusted_dir_servers
);
4011 trusted_dir_servers
= smartlist_new();
4013 router_dir_info_changed();
4016 /** For every current directory connection whose purpose is <b>purpose</b>,
4017 * and where the resource being downloaded begins with <b>prefix</b>, split
4018 * rest of the resource into base16 fingerprints (or base64 fingerprints if
4019 * purpose==DIR_PURPPOSE_FETCH_MICRODESC), decode them, and set the
4020 * corresponding elements of <b>result</b> to a nonzero value.
4023 list_pending_downloads(digestmap_t
*result
,
4024 int purpose
, const char *prefix
)
4026 const size_t p_len
= strlen(prefix
);
4027 smartlist_t
*tmp
= smartlist_new();
4028 smartlist_t
*conns
= get_connection_array();
4029 int flags
= DSR_HEX
;
4030 if (purpose
== DIR_PURPOSE_FETCH_MICRODESC
)
4031 flags
= DSR_DIGEST256
|DSR_BASE64
;
4035 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
4036 if (conn
->type
== CONN_TYPE_DIR
&&
4037 conn
->purpose
== purpose
&&
4038 !conn
->marked_for_close
) {
4039 const char *resource
= TO_DIR_CONN(conn
)->requested_resource
;
4040 if (!strcmpstart(resource
, prefix
))
4041 dir_split_resource_into_fingerprints(resource
+ p_len
,
4044 } SMARTLIST_FOREACH_END(conn
);
4046 SMARTLIST_FOREACH(tmp
, char *, d
,
4048 digestmap_set(result
, d
, (void*)1);
4051 smartlist_free(tmp
);
4054 /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
4055 * true) we are currently downloading by descriptor digest, set result[d] to
4058 list_pending_descriptor_downloads(digestmap_t
*result
, int extrainfo
)
4061 extrainfo
? DIR_PURPOSE_FETCH_EXTRAINFO
: DIR_PURPOSE_FETCH_SERVERDESC
;
4062 list_pending_downloads(result
, purpose
, "d/");
4065 /** For every microdescriptor we are currently downloading by descriptor
4066 * digest, set result[d] to (void*)1. (Note that microdescriptor digests
4067 * are 256-bit, and digestmap_t only holds 160-bit digests, so we're only
4068 * getting the first 20 bytes of each digest here.)
4070 * XXXX Let there be a digestmap256_t, and use that instead.
4073 list_pending_microdesc_downloads(digestmap_t
*result
)
4075 list_pending_downloads(result
, DIR_PURPOSE_FETCH_MICRODESC
, "d/");
4078 /** Launch downloads for all the descriptors whose digests or digests256
4079 * are listed as digests[i] for lo <= i < hi. (Lo and hi may be out of
4080 * range.) If <b>source</b> is given, download from <b>source</b>;
4081 * otherwise, download from an appropriate random directory server.
4084 initiate_descriptor_downloads(const routerstatus_t
*source
,
4086 smartlist_t
*digests
,
4087 int lo
, int hi
, int pds_flags
)
4090 char *resource
, *cp
;
4093 int digest_len
= DIGEST_LEN
, enc_digest_len
= HEX_DIGEST_LEN
;
4097 if (purpose
== DIR_PURPOSE_FETCH_MICRODESC
) {
4098 /* Microdescriptors are downloaded by "-"-separated base64-encoded
4099 * 256-bit digests. */
4100 digest_len
= DIGEST256_LEN
;
4101 enc_digest_len
= BASE64_DIGEST256_LEN
;
4110 if (hi
> smartlist_len(digests
))
4111 hi
= smartlist_len(digests
);
4113 r_len
= 8 + (enc_digest_len
+1)*n
;
4114 cp
= resource
= tor_malloc(r_len
);
4115 memcpy(cp
, "d/", 2);
4117 for (i
= lo
; i
< hi
; ++i
) {
4119 digest256_to_base64(cp
, smartlist_get(digests
, i
));
4121 base16_encode(cp
, r_len
-(cp
-resource
),
4122 smartlist_get(digests
,i
), digest_len
);
4124 cp
+= enc_digest_len
;
4127 memcpy(cp
-1, ".z", 3);
4130 /* We know which authority we want. */
4131 directory_initiate_command_routerstatus(source
, purpose
,
4132 ROUTER_PURPOSE_GENERAL
,
4134 resource
, NULL
, 0, 0);
4136 directory_get_from_dirserver(purpose
, ROUTER_PURPOSE_GENERAL
, resource
,
4142 /** Max amount of hashes to download per request.
4143 * Since squid does not like URLs >= 4096 bytes we limit it to 96.
4144 * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
4145 * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
4146 * So use 96 because it's a nice number.
4148 #define MAX_DL_PER_REQUEST 96
4149 #define MAX_MICRODESC_DL_PER_REQUEST 92
4150 /** Don't split our requests so finely that we are requesting fewer than
4151 * this number per server. */
4152 #define MIN_DL_PER_REQUEST 4
4153 /** To prevent a single screwy cache from confusing us by selective reply,
4154 * try to split our requests into at least this many requests. */
4155 #define MIN_REQUESTS 3
4156 /** If we want fewer than this many descriptors, wait until we
4157 * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
4159 #define MAX_DL_TO_DELAY 16
4160 /** When directory clients have only a few servers to request, they batch
4161 * them until they have more, or until this amount of time has passed. */
4162 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
4164 /** Given a <b>purpose</b> (FETCH_MICRODESC or FETCH_SERVERDESC) and a list of
4165 * router descriptor digests or microdescriptor digest256s in
4166 * <b>downloadable</b>, decide whether to delay fetching until we have more.
4167 * If we don't want to delay, launch one or more requests to the appropriate
4168 * directory authorities.
4171 launch_descriptor_downloads(int purpose
,
4172 smartlist_t
*downloadable
,
4173 const routerstatus_t
*source
, time_t now
)
4175 int should_delay
= 0, n_downloadable
;
4176 const or_options_t
*options
= get_options();
4177 const char *descname
;
4179 tor_assert(purpose
== DIR_PURPOSE_FETCH_SERVERDESC
||
4180 purpose
== DIR_PURPOSE_FETCH_MICRODESC
);
4182 descname
= (purpose
== DIR_PURPOSE_FETCH_SERVERDESC
) ?
4183 "routerdesc" : "microdesc";
4185 n_downloadable
= smartlist_len(downloadable
);
4186 if (!directory_fetches_dir_info_early(options
)) {
4187 if (n_downloadable
>= MAX_DL_TO_DELAY
) {
4189 "There are enough downloadable %ss to launch requests.",
4193 should_delay
= (last_descriptor_download_attempted
+
4194 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST
) > now
;
4195 if (!should_delay
&& n_downloadable
) {
4196 if (last_descriptor_download_attempted
) {
4198 "There are not many downloadable %ss, but we've "
4199 "been waiting long enough (%d seconds). Downloading.",
4201 (int)(now
-last_descriptor_download_attempted
));
4204 "There are not many downloadable %ss, but we haven't "
4205 "tried downloading descriptors recently. Downloading.",
4212 if (! should_delay
&& n_downloadable
) {
4213 int i
, n_per_request
;
4214 const char *req_plural
= "", *rtr_plural
= "";
4215 int pds_flags
= PDS_RETRY_IF_NO_SERVERS
;
4216 if (! authdir_mode_any_nonhidserv(options
)) {
4217 /* If we wind up going to the authorities, we want to only open one
4218 * connection to each authority at a time, so that we don't overload
4219 * them. We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
4220 * regardless of whether we're a cache or not; it gets ignored if we're
4221 * not calling router_pick_trusteddirserver.
4223 * Setting this flag can make initiate_descriptor_downloads() ignore
4224 * requests. We need to make sure that we do in fact call
4225 * update_router_descriptor_downloads() later on, once the connections
4226 * have succeeded or failed.
4228 pds_flags
|= (purpose
== DIR_PURPOSE_FETCH_MICRODESC
) ?
4229 PDS_NO_EXISTING_MICRODESC_FETCH
:
4230 PDS_NO_EXISTING_SERVERDESC_FETCH
;
4233 n_per_request
= CEIL_DIV(n_downloadable
, MIN_REQUESTS
);
4234 if (purpose
== DIR_PURPOSE_FETCH_MICRODESC
) {
4235 if (n_per_request
> MAX_MICRODESC_DL_PER_REQUEST
)
4236 n_per_request
= MAX_MICRODESC_DL_PER_REQUEST
;
4238 if (n_per_request
> MAX_DL_PER_REQUEST
)
4239 n_per_request
= MAX_DL_PER_REQUEST
;
4241 if (n_per_request
< MIN_DL_PER_REQUEST
)
4242 n_per_request
= MIN_DL_PER_REQUEST
;
4244 if (n_downloadable
> n_per_request
)
4245 req_plural
= rtr_plural
= "s";
4246 else if (n_downloadable
> 1)
4250 "Launching %d request%s for %d %s%s, %d at a time",
4251 CEIL_DIV(n_downloadable
, n_per_request
), req_plural
,
4252 n_downloadable
, descname
, rtr_plural
, n_per_request
);
4253 smartlist_sort_digests(downloadable
);
4254 for (i
=0; i
< n_downloadable
; i
+= n_per_request
) {
4255 initiate_descriptor_downloads(source
, purpose
,
4256 downloadable
, i
, i
+n_per_request
,
4259 last_descriptor_download_attempted
= now
;
4263 /** Launch downloads for router status as needed, using the strategy used by
4264 * authorities and caches: based on the v2 networkstatuses we have, download
4265 * every descriptor we don't have but would serve, from a random authority
4268 update_router_descriptor_cache_downloads_v2(time_t now
)
4270 smartlist_t
**downloadable
; /* For each authority, what can we dl from it? */
4271 smartlist_t
**download_from
; /* ... and, what will we dl from it? */
4272 digestmap_t
*map
; /* Which descs are in progress, or assigned? */
4275 const or_options_t
*options
= get_options();
4276 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
4278 if (! directory_fetches_dir_info_early(options
)) {
4279 log_warn(LD_BUG
, "Called update_router_descriptor_cache_downloads_v2() "
4280 "on a non-dir-mirror?");
4283 if (!networkstatus_v2_list
|| !smartlist_len(networkstatus_v2_list
))
4286 map
= digestmap_new();
4287 n
= smartlist_len(networkstatus_v2_list
);
4289 downloadable
= tor_malloc_zero(sizeof(smartlist_t
*) * n
);
4290 download_from
= tor_malloc_zero(sizeof(smartlist_t
*) * n
);
4292 /* Set map[d]=1 for the digest of every descriptor that we are currently
4294 list_pending_descriptor_downloads(map
, 0);
4296 /* For the digest of every descriptor that we don't have, and that we aren't
4297 * downloading, add d to downloadable[i] if the i'th networkstatus knows
4298 * about that descriptor, and we haven't already failed to get that
4299 * descriptor from the corresponding authority.
4302 SMARTLIST_FOREACH_BEGIN(networkstatus_v2_list
, networkstatus_v2_t
*, ns
) {
4305 dl
= downloadable
[ns_sl_idx
] = smartlist_new();
4306 download_from
[ns_sl_idx
] = smartlist_new();
4307 if (ns
->published_on
+ MAX_NETWORKSTATUS_AGE
+10*60 < now
) {
4308 /* Don't download if the networkstatus is almost ancient. */
4309 /* Actually, I suspect what's happening here is that we ask
4310 * for the descriptor when we have a given networkstatus,
4311 * and then we get a newer networkstatus, and then we receive
4312 * the descriptor. Having a networkstatus actually expire is
4313 * probably a rare event, and we'll probably be happiest if
4314 * we take this clause out. -RD */
4318 /* Don't try dirservers that we think are down -- we might have
4319 * just tried them and just marked them as down. */
4320 ds
= router_get_trusteddirserver_by_digest(ns
->identity_digest
);
4321 if (ds
&& !ds
->is_running
)
4324 SMARTLIST_FOREACH_BEGIN(ns
->entries
, routerstatus_t
* , rs
) {
4325 if (!rs
->need_to_mirror
)
4327 if (router_get_by_descriptor_digest(rs
->descriptor_digest
)) {
4329 "We have a router descriptor, but need_to_mirror=1.");
4330 rs
->need_to_mirror
= 0;
4333 if (authdir_mode(options
) && dirserv_would_reject_router(rs
)) {
4334 rs
->need_to_mirror
= 0;
4337 if (digestmap_get(map
, rs
->descriptor_digest
)) {
4338 /* We're downloading it already. */
4341 /* We could download it from this guy. */
4342 smartlist_add(dl
, rs
->descriptor_digest
);
4345 } SMARTLIST_FOREACH_END(rs
);
4346 } SMARTLIST_FOREACH_END(ns
);
4348 /* At random, assign descriptors to authorities such that:
4349 * - if d is a member of some downloadable[x], d is a member of some
4350 * download_from[y]. (Everything we want to download, we try to download
4352 * - If d is a member of download_from[y], d is a member of downloadable[y].
4353 * (We only try to download descriptors from authorities who claim to have
4355 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
4356 * (We don't try to download anything from two authorities concurrently.)
4358 while (n_download
) {
4359 int which_ns
= crypto_rand_int(n
);
4360 smartlist_t
*dl
= downloadable
[which_ns
];
4363 if (!smartlist_len(dl
))
4365 idx
= crypto_rand_int(smartlist_len(dl
));
4366 d
= smartlist_get(dl
, idx
);
4367 if (! digestmap_get(map
, d
)) {
4368 smartlist_add(download_from
[which_ns
], d
);
4369 digestmap_set(map
, d
, (void*) 1);
4371 smartlist_del(dl
, idx
);
4375 /* Now, we can actually launch our requests. */
4376 for (i
=0; i
<n
; ++i
) {
4377 networkstatus_v2_t
*ns
= smartlist_get(networkstatus_v2_list
, i
);
4379 router_get_trusteddirserver_by_digest(ns
->identity_digest
);
4380 smartlist_t
*dl
= download_from
[i
];
4381 int pds_flags
= PDS_RETRY_IF_NO_SERVERS
;
4382 if (! authdir_mode_any_nonhidserv(options
))
4383 pds_flags
|= PDS_NO_EXISTING_SERVERDESC_FETCH
; /* XXXX ignored*/
4386 log_info(LD_DIR
, "Networkstatus with no corresponding authority!");
4389 if (! smartlist_len(dl
))
4391 log_info(LD_DIR
, "Requesting %d descriptors from authority \"%s\"",
4392 smartlist_len(dl
), ds
->nickname
);
4393 for (j
=0; j
< smartlist_len(dl
); j
+= MAX_DL_PER_REQUEST
) {
4394 initiate_descriptor_downloads(&(ds
->fake_status
),
4395 DIR_PURPOSE_FETCH_SERVERDESC
, dl
, j
,
4396 j
+MAX_DL_PER_REQUEST
, pds_flags
);
4400 for (i
=0; i
<n
; ++i
) {
4401 smartlist_free(download_from
[i
]);
4402 smartlist_free(downloadable
[i
]);
4404 tor_free(download_from
);
4405 tor_free(downloadable
);
4406 digestmap_free(map
,NULL
);
4409 /** For any descriptor that we want that's currently listed in
4410 * <b>consensus</b>, download it as appropriate. */
4412 update_consensus_router_descriptor_downloads(time_t now
, int is_vote
,
4413 networkstatus_t
*consensus
)
4415 const or_options_t
*options
= get_options();
4416 digestmap_t
*map
= NULL
;
4417 smartlist_t
*no_longer_old
= smartlist_new();
4418 smartlist_t
*downloadable
= smartlist_new();
4419 routerstatus_t
*source
= NULL
;
4420 int authdir
= authdir_mode(options
);
4421 int n_delayed
=0, n_have
=0, n_would_reject
=0, n_wouldnt_use
=0,
4422 n_inprogress
=0, n_in_oldrouters
=0;
4424 if (directory_too_idle_to_fetch_descriptors(options
, now
))
4430 /* where's it from, so we know whom to ask for descriptors */
4432 networkstatus_voter_info_t
*voter
= smartlist_get(consensus
->voters
, 0);
4434 ds
= trusteddirserver_get_by_v3_auth_digest(voter
->identity_digest
);
4436 source
= &(ds
->fake_status
);
4438 log_warn(LD_DIR
, "couldn't lookup source from vote?");
4441 map
= digestmap_new();
4442 list_pending_descriptor_downloads(map
, 0);
4443 SMARTLIST_FOREACH_BEGIN(consensus
->routerstatus_list
, void *, rsp
) {
4444 routerstatus_t
*rs
=
4445 is_vote
? &(((vote_routerstatus_t
*)rsp
)->status
) : rsp
;
4446 signed_descriptor_t
*sd
;
4447 if ((sd
= router_get_by_descriptor_digest(rs
->descriptor_digest
))) {
4448 const routerinfo_t
*ri
;
4450 if (!(ri
= router_get_by_id_digest(rs
->identity_digest
)) ||
4451 tor_memneq(ri
->cache_info
.signed_descriptor_digest
,
4452 sd
->signed_descriptor_digest
, DIGEST_LEN
)) {
4453 /* We have a descriptor with this digest, but either there is no
4454 * entry in routerlist with the same ID (!ri), or there is one,
4455 * but the identity digest differs (memneq).
4457 smartlist_add(no_longer_old
, sd
);
4458 ++n_in_oldrouters
; /* We have it in old_routers. */
4460 continue; /* We have it already. */
4462 if (digestmap_get(map
, rs
->descriptor_digest
)) {
4464 continue; /* We have an in-progress download. */
4466 if (!download_status_is_ready(&rs
->dl_status
, now
,
4467 MAX_ROUTERDESC_DOWNLOAD_FAILURES
)) {
4468 ++n_delayed
; /* Not ready for retry. */
4471 if (authdir
&& dirserv_would_reject_router(rs
)) {
4473 continue; /* We would throw it out immediately. */
4475 if (!directory_caches_dir_info(options
) &&
4476 !client_would_use_router(rs
, now
, options
)) {
4478 continue; /* We would never use it ourself. */
4480 if (is_vote
&& source
) {
4481 char time_bufnew
[ISO_TIME_LEN
+1];
4482 char time_bufold
[ISO_TIME_LEN
+1];
4483 const routerinfo_t
*oldrouter
;
4484 oldrouter
= router_get_by_id_digest(rs
->identity_digest
);
4485 format_iso_time(time_bufnew
, rs
->published_on
);
4487 format_iso_time(time_bufold
, oldrouter
->cache_info
.published_on
);
4488 log_info(LD_DIR
, "Learned about %s (%s vs %s) from %s's vote (%s)",
4489 routerstatus_describe(rs
),
4491 oldrouter
? time_bufold
: "none",
4492 source
->nickname
, oldrouter
? "known" : "unknown");
4494 smartlist_add(downloadable
, rs
->descriptor_digest
);
4495 } SMARTLIST_FOREACH_END(rsp
);
4497 if (!authdir_mode_handles_descs(options
, ROUTER_PURPOSE_GENERAL
)
4498 && smartlist_len(no_longer_old
)) {
4499 routerlist_t
*rl
= router_get_routerlist();
4500 log_info(LD_DIR
, "%d router descriptors listed in consensus are "
4501 "currently in old_routers; making them current.",
4502 smartlist_len(no_longer_old
));
4503 SMARTLIST_FOREACH_BEGIN(no_longer_old
, signed_descriptor_t
*, sd
) {
4505 was_router_added_t r
;
4506 routerinfo_t
*ri
= routerlist_reparse_old(rl
, sd
);
4508 log_warn(LD_BUG
, "Failed to re-parse a router.");
4511 r
= router_add_to_routerlist(ri
, &msg
, 1, 0);
4512 if (WRA_WAS_OUTDATED(r
)) {
4513 log_warn(LD_DIR
, "Couldn't add re-parsed router: %s",
4516 } SMARTLIST_FOREACH_END(sd
);
4517 routerlist_assert_ok(rl
);
4521 "%d router descriptors downloadable. %d delayed; %d present "
4522 "(%d of those were in old_routers); %d would_reject; "
4523 "%d wouldnt_use; %d in progress.",
4524 smartlist_len(downloadable
), n_delayed
, n_have
, n_in_oldrouters
,
4525 n_would_reject
, n_wouldnt_use
, n_inprogress
);
4527 launch_descriptor_downloads(DIR_PURPOSE_FETCH_SERVERDESC
,
4528 downloadable
, source
, now
);
4530 digestmap_free(map
, NULL
);
4532 smartlist_free(downloadable
);
4533 smartlist_free(no_longer_old
);
4536 /** How often should we launch a server/authority request to be sure of getting
4537 * a guess for our IP? */
4538 /*XXXX024 this info should come from netinfo cells or something, or we should
4539 * do this only when we aren't seeing incoming data. see bug 652. */
4540 #define DUMMY_DOWNLOAD_INTERVAL (20*60)
4542 /** As needed, launch a dummy router descriptor fetch to see if our
4543 * address has changed. */
4545 launch_dummy_descriptor_download_as_needed(time_t now
,
4546 const or_options_t
*options
)
4548 static time_t last_dummy_download
= 0;
4549 /* XXXX024 we could be smarter here; see notes on bug 652. */
4550 /* If we're a server that doesn't have a configured address, we rely on
4551 * directory fetches to learn when our address changes. So if we haven't
4552 * tried to get any routerdescs in a long time, try a dummy fetch now. */
4553 if (!options
->Address
&&
4554 server_mode(options
) &&
4555 last_descriptor_download_attempted
+ DUMMY_DOWNLOAD_INTERVAL
< now
&&
4556 last_dummy_download
+ DUMMY_DOWNLOAD_INTERVAL
< now
) {
4557 last_dummy_download
= now
;
4558 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC
,
4559 ROUTER_PURPOSE_GENERAL
, "authority.z",
4560 PDS_RETRY_IF_NO_SERVERS
);
4564 /** Launch downloads for router status as needed. */
4566 update_router_descriptor_downloads(time_t now
)
4568 const or_options_t
*options
= get_options();
4569 if (should_delay_dir_fetches(options
))
4571 if (!we_fetch_router_descriptors(options
))
4573 if (directory_fetches_dir_info_early(options
)) {
4574 update_router_descriptor_cache_downloads_v2(now
);
4577 update_consensus_router_descriptor_downloads(now
, 0,
4578 networkstatus_get_reasonably_live_consensus(now
, FLAV_NS
));
4581 /** Launch extrainfo downloads as needed. */
4583 update_extrainfo_downloads(time_t now
)
4585 const or_options_t
*options
= get_options();
4587 smartlist_t
*wanted
;
4588 digestmap_t
*pending
;
4590 int n_no_ei
= 0, n_pending
= 0, n_have
= 0, n_delay
= 0;
4591 if (! options
->DownloadExtraInfo
)
4593 if (should_delay_dir_fetches(options
))
4595 if (!router_have_minimum_dir_info())
4598 pending
= digestmap_new();
4599 list_pending_descriptor_downloads(pending
, 1);
4600 rl
= router_get_routerlist();
4601 wanted
= smartlist_new();
4602 for (old_routers
= 0; old_routers
< 2; ++old_routers
) {
4603 smartlist_t
*lst
= old_routers
? rl
->old_routers
: rl
->routers
;
4604 for (i
= 0; i
< smartlist_len(lst
); ++i
) {
4605 signed_descriptor_t
*sd
;
4608 sd
= smartlist_get(lst
, i
);
4610 sd
= &((routerinfo_t
*)smartlist_get(lst
, i
))->cache_info
;
4611 if (sd
->is_extrainfo
)
4612 continue; /* This should never happen. */
4613 if (old_routers
&& !router_get_by_id_digest(sd
->identity_digest
))
4614 continue; /* Couldn't check the signature if we got it. */
4615 if (sd
->extrainfo_is_bogus
)
4617 d
= sd
->extra_info_digest
;
4618 if (tor_digest_is_zero(d
)) {
4622 if (eimap_get(rl
->extra_info_map
, d
)) {
4626 if (!download_status_is_ready(&sd
->ei_dl_status
, now
,
4627 MAX_ROUTERDESC_DOWNLOAD_FAILURES
)) {
4631 if (digestmap_get(pending
, d
)) {
4635 smartlist_add(wanted
, d
);
4638 digestmap_free(pending
, NULL
);
4640 log_info(LD_DIR
, "Extrainfo download status: %d router with no ei, %d "
4641 "with present ei, %d delaying, %d pending, %d downloadable.",
4642 n_no_ei
, n_have
, n_delay
, n_pending
, smartlist_len(wanted
));
4644 smartlist_shuffle(wanted
);
4645 for (i
= 0; i
< smartlist_len(wanted
); i
+= MAX_DL_PER_REQUEST
) {
4646 initiate_descriptor_downloads(NULL
, DIR_PURPOSE_FETCH_EXTRAINFO
,
4647 wanted
, i
, i
+ MAX_DL_PER_REQUEST
,
4648 PDS_RETRY_IF_NO_SERVERS
|PDS_NO_EXISTING_SERVERDESC_FETCH
);
4651 smartlist_free(wanted
);
4654 /** Reset the descriptor download failure count on all routers, so that we
4655 * can retry any long-failed routers immediately.
4658 router_reset_descriptor_download_failures(void)
4660 networkstatus_reset_download_failures();
4661 last_descriptor_download_attempted
= 0;
4664 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
4666 download_status_reset(&ri
->cache_info
.ei_dl_status
);
4668 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
,
4670 download_status_reset(&sd
->ei_dl_status
);
4674 /** Any changes in a router descriptor's publication time larger than this are
4675 * automatically non-cosmetic. */
4676 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (2*60*60)
4678 /** We allow uptime to vary from how much it ought to be by this much. */
4679 #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
4681 /** Return true iff the only differences between r1 and r2 are such that
4682 * would not cause a recent (post 0.1.1.6) dirserver to republish.
4685 router_differences_are_cosmetic(const routerinfo_t
*r1
, const routerinfo_t
*r2
)
4687 time_t r1pub
, r2pub
;
4688 long time_difference
;
4689 tor_assert(r1
&& r2
);
4691 /* r1 should be the one that was published first. */
4692 if (r1
->cache_info
.published_on
> r2
->cache_info
.published_on
) {
4693 const routerinfo_t
*ri_tmp
= r2
;
4698 /* If any key fields differ, they're different. */
4699 if (strcasecmp(r1
->address
, r2
->address
) ||
4700 strcasecmp(r1
->nickname
, r2
->nickname
) ||
4701 r1
->or_port
!= r2
->or_port
||
4702 !tor_addr_eq(&r1
->ipv6_addr
, &r2
->ipv6_addr
) ||
4703 r1
->ipv6_orport
!= r2
->ipv6_orport
||
4704 r1
->dir_port
!= r2
->dir_port
||
4705 r1
->purpose
!= r2
->purpose
||
4706 !crypto_pk_eq_keys(r1
->onion_pkey
, r2
->onion_pkey
) ||
4707 !crypto_pk_eq_keys(r1
->identity_pkey
, r2
->identity_pkey
) ||
4708 strcasecmp(r1
->platform
, r2
->platform
) ||
4709 (r1
->contact_info
&& !r2
->contact_info
) || /* contact_info is optional */
4710 (!r1
->contact_info
&& r2
->contact_info
) ||
4711 (r1
->contact_info
&& r2
->contact_info
&&
4712 strcasecmp(r1
->contact_info
, r2
->contact_info
)) ||
4713 r1
->is_hibernating
!= r2
->is_hibernating
||
4714 cmp_addr_policies(r1
->exit_policy
, r2
->exit_policy
))
4716 if ((r1
->declared_family
== NULL
) != (r2
->declared_family
== NULL
))
4718 if (r1
->declared_family
&& r2
->declared_family
) {
4720 if (smartlist_len(r1
->declared_family
)!=smartlist_len(r2
->declared_family
))
4722 n
= smartlist_len(r1
->declared_family
);
4723 for (i
=0; i
< n
; ++i
) {
4724 if (strcasecmp(smartlist_get(r1
->declared_family
, i
),
4725 smartlist_get(r2
->declared_family
, i
)))
4730 /* Did bandwidth change a lot? */
4731 if ((r1
->bandwidthcapacity
< r2
->bandwidthcapacity
/2) ||
4732 (r2
->bandwidthcapacity
< r1
->bandwidthcapacity
/2))
4735 /* Did the bandwidthrate or bandwidthburst change? */
4736 if ((r1
->bandwidthrate
!= r2
->bandwidthrate
) ||
4737 (r1
->bandwidthburst
!= r2
->bandwidthburst
))
4740 /* Did more than 12 hours pass? */
4741 if (r1
->cache_info
.published_on
+ ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
4742 < r2
->cache_info
.published_on
)
4745 /* Did uptime fail to increase by approximately the amount we would think,
4746 * give or take some slop? */
4747 r1pub
= r1
->cache_info
.published_on
;
4748 r2pub
= r2
->cache_info
.published_on
;
4749 time_difference
= labs(r2
->uptime
- (r1
->uptime
+ (r2pub
- r1pub
)));
4750 if (time_difference
> ROUTER_ALLOW_UPTIME_DRIFT
&&
4751 time_difference
> r1
->uptime
* .05 &&
4752 time_difference
> r2
->uptime
* .05)
4755 /* Otherwise, the difference is cosmetic. */
4759 /** Check whether <b>ri</b> (a.k.a. sd) is a router compatible with the
4760 * extrainfo document
4761 * <b>ei</b>. If no router is compatible with <b>ei</b>, <b>ei</b> should be
4762 * dropped. Return 0 for "compatible", return 1 for "reject, and inform
4763 * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
4764 * <b>msg</b> is present, set *<b>msg</b> to a description of the
4765 * incompatibility (if any).
4768 routerinfo_incompatible_with_extrainfo(const routerinfo_t
*ri
,
4770 signed_descriptor_t
*sd
,
4773 int digest_matches
, r
=1;
4777 sd
= (signed_descriptor_t
*)&ri
->cache_info
;
4780 if (msg
) *msg
= "Extrainfo signature was bad, or signed with wrong key.";
4784 digest_matches
= tor_memeq(ei
->cache_info
.signed_descriptor_digest
,
4785 sd
->extra_info_digest
, DIGEST_LEN
);
4787 /* The identity must match exactly to have been generated at the same time
4788 * by the same router. */
4789 if (tor_memneq(ri
->cache_info
.identity_digest
,
4790 ei
->cache_info
.identity_digest
,
4792 if (msg
) *msg
= "Extrainfo nickname or identity did not match routerinfo";
4793 goto err
; /* different servers */
4796 if (ei
->pending_sig
) {
4797 char signed_digest
[128];
4798 if (crypto_pk_public_checksig(ri
->identity_pkey
,
4799 signed_digest
, sizeof(signed_digest
),
4800 ei
->pending_sig
, ei
->pending_sig_len
) != DIGEST_LEN
||
4801 tor_memneq(signed_digest
, ei
->cache_info
.signed_descriptor_digest
,
4804 tor_free(ei
->pending_sig
);
4805 if (msg
) *msg
= "Extrainfo signature bad, or signed with wrong key";
4806 goto err
; /* Bad signature, or no match. */
4809 ei
->cache_info
.send_unencrypted
= ri
->cache_info
.send_unencrypted
;
4810 tor_free(ei
->pending_sig
);
4813 if (ei
->cache_info
.published_on
< sd
->published_on
) {
4814 if (msg
) *msg
= "Extrainfo published time did not match routerdesc";
4816 } else if (ei
->cache_info
.published_on
> sd
->published_on
) {
4817 if (msg
) *msg
= "Extrainfo published time did not match routerdesc";
4822 if (!digest_matches
) {
4823 if (msg
) *msg
= "Extrainfo digest did not match value from routerdesc";
4824 goto err
; /* Digest doesn't match declared value. */
4829 if (digest_matches
) {
4830 /* This signature was okay, and the digest was right: This is indeed the
4831 * corresponding extrainfo. But insanely, it doesn't match the routerinfo
4832 * that lists it. Don't try to fetch this one again. */
4833 sd
->extrainfo_is_bogus
= 1;
4839 /** Assert that the internal representation of <b>rl</b> is
4840 * self-consistent. */
4842 routerlist_assert_ok(const routerlist_t
*rl
)
4845 signed_descriptor_t
*sd2
;
4848 SMARTLIST_FOREACH_BEGIN(rl
->routers
, routerinfo_t
*, r
) {
4849 r2
= rimap_get(rl
->identity_map
, r
->cache_info
.identity_digest
);
4850 tor_assert(r
== r2
);
4851 sd2
= sdmap_get(rl
->desc_digest_map
,
4852 r
->cache_info
.signed_descriptor_digest
);
4853 tor_assert(&(r
->cache_info
) == sd2
);
4854 tor_assert(r
->cache_info
.routerlist_index
== r_sl_idx
);
4857 * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
4858 * commenting this out is just a band-aid.
4860 * The problem is that, although well-behaved router descriptors
4861 * should never have the same value for their extra_info_digest, it's
4862 * possible for ill-behaved routers to claim whatever they like there.
4864 * The real answer is to trash desc_by_eid_map and instead have
4865 * something that indicates for a given extra-info digest we want,
4866 * what its download status is. We'll do that as a part of routerlist
4867 * refactoring once consensus directories are in. For now,
4868 * this rep violation is probably harmless: an adversary can make us
4869 * reset our retry count for an extrainfo, but that's not the end
4870 * of the world. Changing the representation in 0.2.0.x would just
4871 * destabilize the codebase.
4872 if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
4873 signed_descriptor_t *sd3 =
4874 sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
4875 tor_assert(sd3 == &(r->cache_info));
4878 } SMARTLIST_FOREACH_END(r
);
4879 SMARTLIST_FOREACH_BEGIN(rl
->old_routers
, signed_descriptor_t
*, sd
) {
4880 r2
= rimap_get(rl
->identity_map
, sd
->identity_digest
);
4881 tor_assert(sd
!= &(r2
->cache_info
));
4882 sd2
= sdmap_get(rl
->desc_digest_map
, sd
->signed_descriptor_digest
);
4883 tor_assert(sd
== sd2
);
4884 tor_assert(sd
->routerlist_index
== sd_sl_idx
);
4886 if (!tor_digest_is_zero(sd->extra_info_digest)) {
4887 signed_descriptor_t *sd3 =
4888 sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
4889 tor_assert(sd3 == sd);
4892 } SMARTLIST_FOREACH_END(sd
);
4894 RIMAP_FOREACH(rl
->identity_map
, d
, r
) {
4895 tor_assert(tor_memeq(r
->cache_info
.identity_digest
, d
, DIGEST_LEN
));
4896 } DIGESTMAP_FOREACH_END
;
4897 SDMAP_FOREACH(rl
->desc_digest_map
, d
, sd
) {
4898 tor_assert(tor_memeq(sd
->signed_descriptor_digest
, d
, DIGEST_LEN
));
4899 } DIGESTMAP_FOREACH_END
;
4900 SDMAP_FOREACH(rl
->desc_by_eid_map
, d
, sd
) {
4901 tor_assert(!tor_digest_is_zero(d
));
4903 tor_assert(tor_memeq(sd
->extra_info_digest
, d
, DIGEST_LEN
));
4904 } DIGESTMAP_FOREACH_END
;
4905 EIMAP_FOREACH(rl
->extra_info_map
, d
, ei
) {
4906 signed_descriptor_t
*sd
;
4907 tor_assert(tor_memeq(ei
->cache_info
.signed_descriptor_digest
,
4909 sd
= sdmap_get(rl
->desc_by_eid_map
,
4910 ei
->cache_info
.signed_descriptor_digest
);
4911 // tor_assert(sd); // XXXX see above
4913 tor_assert(tor_memeq(ei
->cache_info
.signed_descriptor_digest
,
4914 sd
->extra_info_digest
, DIGEST_LEN
));
4916 } DIGESTMAP_FOREACH_END
;
4919 /** Allocate and return a new string representing the contact info
4920 * and platform string for <b>router</b>,
4921 * surrounded by quotes and using standard C escapes.
4923 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
4924 * thread. Also, each call invalidates the last-returned value, so don't
4925 * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
4927 * If <b>router</b> is NULL, it just frees its internal memory and returns.
4930 esc_router_info(const routerinfo_t
*router
)
4932 static char *info
=NULL
;
4933 char *esc_contact
, *esc_platform
;
4937 return NULL
; /* we're exiting; just free the memory we use */
4939 esc_contact
= esc_for_log(router
->contact_info
);
4940 esc_platform
= esc_for_log(router
->platform
);
4942 tor_asprintf(&info
, "Contact %s, Platform %s", esc_contact
, esc_platform
);
4943 tor_free(esc_contact
);
4944 tor_free(esc_platform
);
4949 /** Helper for sorting: compare two routerinfos by their identity
4952 compare_routerinfo_by_id_digest_(const void **a
, const void **b
)
4954 routerinfo_t
*first
= *(routerinfo_t
**)a
, *second
= *(routerinfo_t
**)b
;
4955 return fast_memcmp(first
->cache_info
.identity_digest
,
4956 second
->cache_info
.identity_digest
,
4960 /** Sort a list of routerinfo_t in ascending order of identity digest. */
4962 routers_sort_by_identity(smartlist_t
*routers
)
4964 smartlist_sort(routers
, compare_routerinfo_by_id_digest_
);
4967 /** Called when we change a node set, or when we reload the geoip IPv4 list:
4968 * recompute all country info in all configuration node sets and in the
4971 refresh_all_country_info(void)
4973 const or_options_t
*options
= get_options();
4975 if (options
->EntryNodes
)
4976 routerset_refresh_countries(options
->EntryNodes
);
4977 if (options
->ExitNodes
)
4978 routerset_refresh_countries(options
->ExitNodes
);
4979 if (options
->ExcludeNodes
)
4980 routerset_refresh_countries(options
->ExcludeNodes
);
4981 if (options
->ExcludeExitNodes
)
4982 routerset_refresh_countries(options
->ExcludeExitNodes
);
4983 if (options
->ExcludeExitNodesUnion_
)
4984 routerset_refresh_countries(options
->ExcludeExitNodesUnion_
);
4986 nodelist_refresh_countries();
4989 /** Determine the routers that are responsible for <b>id</b> (binary) and
4990 * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
4991 * Return -1 if we're returning an empty smartlist, else return 0.
4994 hid_serv_get_responsible_directories(smartlist_t
*responsible_dirs
,
4997 int start
, found
, n_added
= 0, i
;
4998 networkstatus_t
*c
= networkstatus_get_latest_consensus();
4999 if (!c
|| !smartlist_len(c
->routerstatus_list
)) {
5000 log_warn(LD_REND
, "We don't have a consensus, so we can't perform v2 "
5001 "rendezvous operations.");
5005 start
= networkstatus_vote_find_entry_idx(c
, id
, &found
);
5006 if (start
== smartlist_len(c
->routerstatus_list
)) start
= 0;
5009 routerstatus_t
*r
= smartlist_get(c
->routerstatus_list
, i
);
5011 smartlist_add(responsible_dirs
, r
);
5012 if (++n_added
== REND_NUMBER_OF_CONSECUTIVE_REPLICAS
)
5015 if (++i
== smartlist_len(c
->routerstatus_list
))
5017 } while (i
!= start
);
5019 /* Even though we don't have the desired number of hidden service
5020 * directories, be happy if we got any. */
5021 return smartlist_len(responsible_dirs
) ? 0 : -1;
5024 /** Return true if this node is currently acting as hidden service
5025 * directory, false otherwise. */
5027 hid_serv_acting_as_directory(void)
5029 const routerinfo_t
*me
= router_get_my_routerinfo();
5032 if (!get_options()->HidServDirectoryV2
) {
5033 log_info(LD_REND
, "We are not acting as hidden service directory, "
5034 "because we have not been configured as such.");
5040 /** Return true if this node is responsible for storing the descriptor ID
5041 * in <b>query</b> and false otherwise. */
5043 hid_serv_responsible_for_desc_id(const char *query
)
5045 const routerinfo_t
*me
;
5046 routerstatus_t
*last_rs
;
5047 const char *my_id
, *last_id
;
5049 smartlist_t
*responsible
;
5050 if (!hid_serv_acting_as_directory())
5052 if (!(me
= router_get_my_routerinfo()))
5053 return 0; /* This is redundant, but let's be paranoid. */
5054 my_id
= me
->cache_info
.identity_digest
;
5055 responsible
= smartlist_new();
5056 if (hid_serv_get_responsible_directories(responsible
, query
) < 0) {
5057 smartlist_free(responsible
);
5060 last_rs
= smartlist_get(responsible
, smartlist_len(responsible
)-1);
5061 last_id
= last_rs
->identity_digest
;
5062 result
= rend_id_is_in_interval(my_id
, query
, last_id
);
5063 smartlist_free(responsible
);