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"
26 #include "hibernate.h"
28 #include "microdesc.h"
29 #include "networkstatus.h"
33 #include "rendcommon.h"
34 #include "rendservice.h"
37 #include "routerlist.h"
38 #include "routerparse.h"
39 #include "routerset.h"
41 // #define DEBUG_ROUTERLIST
43 /****************************************************************************/
45 DECLARE_TYPED_DIGESTMAP_FNS(sdmap_
, digest_sd_map_t
, signed_descriptor_t
)
46 DECLARE_TYPED_DIGESTMAP_FNS(rimap_
, digest_ri_map_t
, routerinfo_t
)
47 DECLARE_TYPED_DIGESTMAP_FNS(eimap_
, digest_ei_map_t
, extrainfo_t
)
48 DECLARE_TYPED_DIGESTMAP_FNS(dsmap_
, digest_ds_map_t
, download_status_t
)
49 #define SDMAP_FOREACH(map, keyvar, valvar) \
50 DIGESTMAP_FOREACH(sdmap_to_digestmap(map), keyvar, signed_descriptor_t *, \
52 #define RIMAP_FOREACH(map, keyvar, valvar) \
53 DIGESTMAP_FOREACH(rimap_to_digestmap(map), keyvar, routerinfo_t *, valvar)
54 #define EIMAP_FOREACH(map, keyvar, valvar) \
55 DIGESTMAP_FOREACH(eimap_to_digestmap(map), keyvar, extrainfo_t *, valvar)
56 #define DSMAP_FOREACH(map, keyvar, valvar) \
57 DIGESTMAP_FOREACH(dsmap_to_digestmap(map), keyvar, download_status_t *, \
60 /* Forward declaration for cert_list_t */
61 typedef struct cert_list_t cert_list_t
;
63 /* static function prototypes */
64 static int compute_weighted_bandwidths(const smartlist_t
*sl
,
65 bandwidth_weight_rule_t rule
,
66 u64_dbl_t
**bandwidths_out
);
67 static const routerstatus_t
*router_pick_directory_server_impl(
68 dirinfo_type_t auth
, int flags
);
69 static const routerstatus_t
*router_pick_trusteddirserver_impl(
70 const smartlist_t
*sourcelist
, dirinfo_type_t auth
,
71 int flags
, int *n_busy_out
);
72 static const routerstatus_t
*router_pick_dirserver_generic(
73 smartlist_t
*sourcelist
,
74 dirinfo_type_t type
, int flags
);
75 static void mark_all_dirservers_up(smartlist_t
*server_list
);
76 static void dir_server_free(dir_server_t
*ds
);
77 static int signed_desc_digest_is_recognized(signed_descriptor_t
*desc
);
78 static const char *signed_descriptor_get_body_impl(
79 const signed_descriptor_t
*desc
,
80 int with_annotations
);
81 static void list_pending_downloads(digestmap_t
*result
,
82 int purpose
, const char *prefix
);
83 static void list_pending_fpsk_downloads(fp_pair_map_t
*result
);
84 static void launch_dummy_descriptor_download_as_needed(time_t now
,
85 const or_options_t
*options
);
86 static void download_status_reset_by_sk_in_cl(cert_list_t
*cl
,
88 static int download_status_is_ready_by_sk_in_cl(cert_list_t
*cl
,
90 time_t now
, int max_failures
);
92 /****************************************************************************/
94 /** Global list of a dir_server_t object for each directory
96 static smartlist_t
*trusted_dir_servers
= NULL
;
97 /** Global list of dir_server_t objects for all directory authorities
98 * and all fallback directory servers. */
99 static smartlist_t
*fallback_dir_servers
= NULL
;
101 /** List of for a given authority, and download status for latest certificate.
105 * The keys of download status map are cert->signing_key_digest for pending
106 * downloads by (identity digest/signing key digest) pair; functions such
107 * as authority_cert_get_by_digest() already assume these are unique.
109 struct digest_ds_map_t
*dl_status_map
;
110 /* There is also a dlstatus for the download by identity key only */
111 download_status_t dl_status_by_id
;
114 /** Map from v3 identity key digest to cert_list_t. */
115 static digestmap_t
*trusted_dir_certs
= NULL
;
116 /** True iff any key certificate in at least one member of
117 * <b>trusted_dir_certs</b> has changed since we last flushed the
118 * certificates to disk. */
119 static int trusted_dir_servers_certs_changed
= 0;
121 /** Global list of all of the routers that we know about. */
122 static routerlist_t
*routerlist
= NULL
;
124 /** List of strings for nicknames we've already warned about and that are
125 * still unknown / unavailable. */
126 static smartlist_t
*warned_nicknames
= NULL
;
128 /** The last time we tried to download any routerdesc, or 0 for "never". We
129 * use this to rate-limit download attempts when the number of routerdescs to
130 * download is low. */
131 static time_t last_descriptor_download_attempted
= 0;
133 /** When we last computed the weights to use for bandwidths on directory
134 * requests, what were the total weighted bandwidth, and our share of that
135 * bandwidth? Used to determine what fraction of directory requests we should
139 static uint64_t sl_last_total_weighted_bw
= 0,
140 sl_last_weighted_bw_of_me
= 0;
143 /** Return the number of directory authorities whose type matches some bit set
146 get_n_authorities(dirinfo_type_t type
)
149 if (!trusted_dir_servers
)
151 SMARTLIST_FOREACH(trusted_dir_servers
, dir_server_t
*, ds
,
157 /** Reset the download status of a specified element in a dsmap */
159 download_status_reset_by_sk_in_cl(cert_list_t
*cl
, const char *digest
)
161 download_status_t
*dlstatus
= NULL
;
166 /* Make sure we have a dsmap */
167 if (!(cl
->dl_status_map
)) {
168 cl
->dl_status_map
= dsmap_new();
170 /* Look for a download_status_t in the map with this digest */
171 dlstatus
= dsmap_get(cl
->dl_status_map
, digest
);
174 /* Insert before we reset */
175 dlstatus
= tor_malloc_zero(sizeof(*dlstatus
));
176 dsmap_set(cl
->dl_status_map
, digest
, dlstatus
);
178 tor_assert(dlstatus
);
179 /* Go ahead and reset it */
180 download_status_reset(dlstatus
);
184 * Return true if the download for this signing key digest in cl is ready
185 * to be re-attempted.
188 download_status_is_ready_by_sk_in_cl(cert_list_t
*cl
,
190 time_t now
, int max_failures
)
193 download_status_t
*dlstatus
= NULL
;
198 /* Make sure we have a dsmap */
199 if (!(cl
->dl_status_map
)) {
200 cl
->dl_status_map
= dsmap_new();
202 /* Look for a download_status_t in the map with this digest */
203 dlstatus
= dsmap_get(cl
->dl_status_map
, digest
);
206 /* Use download_status_is_ready() */
207 rv
= download_status_is_ready(dlstatus
, now
, max_failures
);
210 * If we don't know anything about it, return 1, since we haven't
211 * tried this one before. We need to create a new entry here,
214 dlstatus
= tor_malloc_zero(sizeof(*dlstatus
));
215 download_status_reset(dlstatus
);
216 dsmap_set(cl
->dl_status_map
, digest
, dlstatus
);
223 #define get_n_v2_authorities() get_n_authorities(V2_DIRINFO)
225 /** Helper: Return the cert_list_t for an authority whose authority ID is
226 * <b>id_digest</b>, allocating a new list if necessary. */
228 get_cert_list(const char *id_digest
)
231 if (!trusted_dir_certs
)
232 trusted_dir_certs
= digestmap_new();
233 cl
= digestmap_get(trusted_dir_certs
, id_digest
);
235 cl
= tor_malloc_zero(sizeof(cert_list_t
));
236 cl
->dl_status_by_id
.schedule
= DL_SCHED_CONSENSUS
;
237 cl
->certs
= smartlist_new();
238 cl
->dl_status_map
= dsmap_new();
239 digestmap_set(trusted_dir_certs
, id_digest
, cl
);
244 /** Release all space held by a cert_list_t */
246 cert_list_free(cert_list_t
*cl
)
251 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
252 authority_cert_free(cert
));
253 smartlist_free(cl
->certs
);
254 dsmap_free(cl
->dl_status_map
, tor_free_
);
258 /** Wrapper for cert_list_free so we can pass it to digestmap_free */
260 cert_list_free_(void *cl
)
265 /** Reload the cached v3 key certificates from the cached-certs file in
266 * the data directory. Return 0 on success, -1 on failure. */
268 trusted_dirs_reload_certs(void)
274 filename
= get_datadir_fname("cached-certs");
275 contents
= read_file_to_str(filename
, RFTS_IGNORE_MISSING
, NULL
);
279 r
= trusted_dirs_load_certs_from_string(
281 TRUSTED_DIRS_CERTS_SRC_FROM_STORE
, 1);
286 /** Helper: return true iff we already have loaded the exact cert
289 already_have_cert(authority_cert_t
*cert
)
291 cert_list_t
*cl
= get_cert_list(cert
->cache_info
.identity_digest
);
293 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, c
,
295 if (tor_memeq(c
->cache_info
.signed_descriptor_digest
,
296 cert
->cache_info
.signed_descriptor_digest
,
303 /** Load a bunch of new key certificates from the string <b>contents</b>. If
304 * <b>source</b> is TRUSTED_DIRS_CERTS_SRC_FROM_STORE, the certificates are
305 * from the cache, and we don't need to flush them to disk. If we are a
306 * dirauth loading our own cert, source is TRUSTED_DIRS_CERTS_SRC_SELF.
307 * Otherwise, source is download type: TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST
308 * or TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_SK_DIGEST. If <b>flush</b> is true, we
309 * need to flush any changed certificates to disk now. Return 0 on success,
310 * -1 if any certs fail to parse.
314 trusted_dirs_load_certs_from_string(const char *contents
, int source
,
319 int failure_code
= 0;
320 int from_store
= (source
== TRUSTED_DIRS_CERTS_SRC_FROM_STORE
);
322 for (s
= contents
; *s
; s
= eos
) {
323 authority_cert_t
*cert
= authority_cert_parse_from_string(s
, &eos
);
329 ds
= trusteddirserver_get_by_v3_auth_digest(
330 cert
->cache_info
.identity_digest
);
331 log_debug(LD_DIR
, "Parsed certificate for %s",
332 ds
? ds
->nickname
: "unknown authority");
334 if (already_have_cert(cert
)) {
335 /* we already have this one. continue. */
336 log_info(LD_DIR
, "Skipping %s certificate for %s that we "
338 from_store
? "cached" : "downloaded",
339 ds
? ds
->nickname
: "an old or new authority");
342 * A duplicate on download should be treated as a failure, so we call
343 * authority_cert_dl_failed() to reset the download status to make sure
344 * we can't try again. Since we've implemented the fp-sk mechanism
345 * to download certs by signing key, this should be much rarer than it
346 * was and is perhaps cause for concern.
349 if (authdir_mode(get_options())) {
351 "Got a certificate for %s, but we already have it. "
352 "Maybe they haven't updated it. Waiting for a while.",
353 ds
? ds
->nickname
: "an old or new authority");
356 "Got a certificate for %s, but we already have it. "
357 "Maybe they haven't updated it. Waiting for a while.",
358 ds
? ds
->nickname
: "an old or new authority");
362 * This is where we care about the source; authority_cert_dl_failed()
363 * needs to know whether the download was by fp or (fp,sk) pair to
364 * twiddle the right bit in the download map.
366 if (source
== TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_DIGEST
) {
367 authority_cert_dl_failed(cert
->cache_info
.identity_digest
,
369 } else if (source
== TRUSTED_DIRS_CERTS_SRC_DL_BY_ID_SK_DIGEST
) {
370 authority_cert_dl_failed(cert
->cache_info
.identity_digest
,
371 cert
->signing_key_digest
, 404);
375 authority_cert_free(cert
);
380 log_info(LD_DIR
, "Adding %s certificate for directory authority %s with "
381 "signing key %s", from_store
? "cached" : "downloaded",
382 ds
->nickname
, hex_str(cert
->signing_key_digest
,DIGEST_LEN
));
384 int adding
= directory_caches_unknown_auth_certs(get_options());
385 log_info(LD_DIR
, "%s %s certificate for unrecognized directory "
386 "authority with signing key %s",
387 adding
? "Adding" : "Not adding",
388 from_store
? "cached" : "downloaded",
389 hex_str(cert
->signing_key_digest
,DIGEST_LEN
));
391 authority_cert_free(cert
);
396 cl
= get_cert_list(cert
->cache_info
.identity_digest
);
397 smartlist_add(cl
->certs
, cert
);
398 if (ds
&& cert
->cache_info
.published_on
> ds
->addr_current_at
) {
399 /* Check to see whether we should update our view of the authority's
401 if (cert
->addr
&& cert
->dir_port
&&
402 (ds
->addr
!= cert
->addr
||
403 ds
->dir_port
!= cert
->dir_port
)) {
404 char *a
= tor_dup_ip(cert
->addr
);
405 log_notice(LD_DIR
, "Updating address for directory authority %s "
406 "from %s:%d to %s:%d based on certificate.",
407 ds
->nickname
, ds
->address
, (int)ds
->dir_port
,
410 ds
->addr
= cert
->addr
;
411 ds
->dir_port
= cert
->dir_port
;
413 ds
->addr_current_at
= cert
->cache_info
.published_on
;
417 trusted_dir_servers_certs_changed
= 1;
421 trusted_dirs_flush_certs_to_disk();
423 /* call this even if failure_code is <0, since some certs might have
425 networkstatus_note_certs_arrived();
430 /** Save all v3 key certificates to the cached-certs file. */
432 trusted_dirs_flush_certs_to_disk(void)
437 if (!trusted_dir_servers_certs_changed
|| !trusted_dir_certs
)
440 chunks
= smartlist_new();
441 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
442 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
444 sized_chunk_t
*c
= tor_malloc(sizeof(sized_chunk_t
));
445 c
->bytes
= cert
->cache_info
.signed_descriptor_body
;
446 c
->len
= cert
->cache_info
.signed_descriptor_len
;
447 smartlist_add(chunks
, c
);
449 } DIGESTMAP_FOREACH_END
;
451 filename
= get_datadir_fname("cached-certs");
452 if (write_chunks_to_file(filename
, chunks
, 0)) {
453 log_warn(LD_FS
, "Error writing certificates to disk.");
456 SMARTLIST_FOREACH(chunks
, sized_chunk_t
*, c
, tor_free(c
));
457 smartlist_free(chunks
);
459 trusted_dir_servers_certs_changed
= 0;
462 /** Remove all v3 authority certificates that have been superseded for more
463 * than 48 hours. (If the most recent cert was published more than 48 hours
464 * ago, then we aren't going to get any consensuses signed with older
467 trusted_dirs_remove_old_certs(void)
469 time_t now
= time(NULL
);
470 #define DEAD_CERT_LIFETIME (2*24*60*60)
471 #define OLD_CERT_LIFETIME (7*24*60*60)
472 if (!trusted_dir_certs
)
475 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
476 authority_cert_t
*newest
= NULL
;
477 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
478 if (!newest
|| (cert
->cache_info
.published_on
>
479 newest
->cache_info
.published_on
))
482 const time_t newest_published
= newest
->cache_info
.published_on
;
483 SMARTLIST_FOREACH_BEGIN(cl
->certs
, authority_cert_t
*, cert
) {
485 time_t cert_published
;
488 expired
= now
> cert
->expires
;
489 cert_published
= cert
->cache_info
.published_on
;
490 /* Store expired certs for 48 hours after a newer arrives;
493 (newest_published
+ DEAD_CERT_LIFETIME
< now
) :
494 (cert_published
+ OLD_CERT_LIFETIME
< newest_published
)) {
495 SMARTLIST_DEL_CURRENT(cl
->certs
, cert
);
496 authority_cert_free(cert
);
497 trusted_dir_servers_certs_changed
= 1;
499 } SMARTLIST_FOREACH_END(cert
);
501 } DIGESTMAP_FOREACH_END
;
502 #undef OLD_CERT_LIFETIME
504 trusted_dirs_flush_certs_to_disk();
507 /** Return the newest v3 authority certificate whose v3 authority identity key
508 * has digest <b>id_digest</b>. Return NULL if no such authority is known,
509 * or it has no certificate. */
511 authority_cert_get_newest_by_id(const char *id_digest
)
514 authority_cert_t
*best
= NULL
;
515 if (!trusted_dir_certs
||
516 !(cl
= digestmap_get(trusted_dir_certs
, id_digest
)))
519 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
521 if (!best
|| cert
->cache_info
.published_on
> best
->cache_info
.published_on
)
527 /** Return the newest v3 authority certificate whose directory signing key has
528 * digest <b>sk_digest</b>. Return NULL if no such certificate is known.
531 authority_cert_get_by_sk_digest(const char *sk_digest
)
534 if (!trusted_dir_certs
)
537 if ((c
= get_my_v3_authority_cert()) &&
538 tor_memeq(c
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
540 if ((c
= get_my_v3_legacy_cert()) &&
541 tor_memeq(c
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
544 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
545 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
547 if (tor_memeq(cert
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
550 } DIGESTMAP_FOREACH_END
;
554 /** Return the v3 authority certificate with signing key matching
555 * <b>sk_digest</b>, for the authority with identity digest <b>id_digest</b>.
556 * Return NULL if no such authority is known. */
558 authority_cert_get_by_digests(const char *id_digest
,
559 const char *sk_digest
)
562 if (!trusted_dir_certs
||
563 !(cl
= digestmap_get(trusted_dir_certs
, id_digest
)))
565 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
566 if (tor_memeq(cert
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
572 /** Add every known authority_cert_t to <b>certs_out</b>. */
574 authority_cert_get_all(smartlist_t
*certs_out
)
576 tor_assert(certs_out
);
577 if (!trusted_dir_certs
)
580 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
581 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, c
,
582 smartlist_add(certs_out
, c
));
583 } DIGESTMAP_FOREACH_END
;
586 /** Called when an attempt to download a certificate with the authority with
587 * ID <b>id_digest</b> and, if not NULL, signed with key signing_key_digest
588 * fails with HTTP response code <b>status</b>: remember the failure, so we
589 * don't try again immediately. */
591 authority_cert_dl_failed(const char *id_digest
,
592 const char *signing_key_digest
, int status
)
595 download_status_t
*dlstatus
= NULL
;
596 char id_digest_str
[2*DIGEST_LEN
+1];
597 char sk_digest_str
[2*DIGEST_LEN
+1];
599 if (!trusted_dir_certs
||
600 !(cl
= digestmap_get(trusted_dir_certs
, id_digest
)))
604 * Are we noting a failed download of the latest cert for the id digest,
605 * or of a download by (id, signing key) digest pair?
607 if (!signing_key_digest
) {
608 /* Just by id digest */
609 download_status_failed(&cl
->dl_status_by_id
, status
);
611 /* Reset by (id, signing key) digest pair
613 * Look for a download_status_t in the map with this digest
615 dlstatus
= dsmap_get(cl
->dl_status_map
, signing_key_digest
);
618 download_status_failed(dlstatus
, status
);
621 * Do this rather than hex_str(), since hex_str clobbers
622 * old results and we call twice in the param list.
624 base16_encode(id_digest_str
, sizeof(id_digest_str
),
625 id_digest
, DIGEST_LEN
);
626 base16_encode(sk_digest_str
, sizeof(sk_digest_str
),
627 signing_key_digest
, DIGEST_LEN
);
629 "Got failure for cert fetch with (fp,sk) = (%s,%s), with "
630 "status %d, but knew nothing about the download.",
631 id_digest_str
, sk_digest_str
, status
);
636 /** Return true iff when we've been getting enough failures when trying to
637 * download the certificate with ID digest <b>id_digest</b> that we're willing
638 * to start bugging the user about it. */
640 authority_cert_dl_looks_uncertain(const char *id_digest
)
642 #define N_AUTH_CERT_DL_FAILURES_TO_BUG_USER 2
645 if (!trusted_dir_certs
||
646 !(cl
= digestmap_get(trusted_dir_certs
, id_digest
)))
649 n_failures
= download_status_get_n_failures(&cl
->dl_status_by_id
);
650 return n_failures
>= N_AUTH_CERT_DL_FAILURES_TO_BUG_USER
;
653 /** How many times will we try to fetch a certificate before giving up? */
654 #define MAX_CERT_DL_FAILURES 8
656 /** Try to download any v3 authority certificates that we may be missing. If
657 * <b>status</b> is provided, try to get all the ones that were used to sign
658 * <b>status</b>. Additionally, try to have a non-expired certificate for
659 * every V3 authority in trusted_dir_servers. Don't fetch certificates we
663 authority_certs_fetch_missing(networkstatus_t
*status
, time_t now
)
666 * The pending_id digestmap tracks pending certificate downloads by
667 * identity digest; the pending_cert digestmap tracks pending downloads
668 * by (identity digest, signing key digest) pairs.
670 digestmap_t
*pending_id
;
671 fp_pair_map_t
*pending_cert
;
672 authority_cert_t
*cert
;
674 * The missing_id_digests smartlist will hold a list of id digests
675 * we want to fetch the newest cert for; the missing_cert_digests
676 * smartlist will hold a list of fp_pair_t with an identity and
677 * signing key digest.
679 smartlist_t
*missing_cert_digests
, *missing_id_digests
;
680 char *resource
= NULL
;
682 const int cache
= directory_caches_unknown_auth_certs(get_options());
683 fp_pair_t
*fp_tmp
= NULL
;
684 char id_digest_str
[2*DIGEST_LEN
+1];
685 char sk_digest_str
[2*DIGEST_LEN
+1];
687 if (should_delay_dir_fetches(get_options()))
690 pending_cert
= fp_pair_map_new();
691 pending_id
= digestmap_new();
692 missing_cert_digests
= smartlist_new();
693 missing_id_digests
= smartlist_new();
696 * First, we get the lists of already pending downloads so we don't
699 list_pending_downloads(pending_id
, DIR_PURPOSE_FETCH_CERTIFICATE
, "fp/");
700 list_pending_fpsk_downloads(pending_cert
);
703 * Now, we download any trusted authority certs we don't have by
704 * identity digest only. This gets the latest cert for that authority.
706 SMARTLIST_FOREACH_BEGIN(trusted_dir_servers
, dir_server_t
*, ds
) {
708 if (!(ds
->type
& V3_DIRINFO
))
710 if (smartlist_contains_digest(missing_id_digests
,
711 ds
->v3_identity_digest
))
713 cl
= get_cert_list(ds
->v3_identity_digest
);
714 SMARTLIST_FOREACH_BEGIN(cl
->certs
, authority_cert_t
*, cert
) {
715 if (now
< cert
->expires
) {
716 /* It's not expired, and we weren't looking for something to
717 * verify a consensus with. Call it done. */
718 download_status_reset(&(cl
->dl_status_by_id
));
719 /* No sense trying to download it specifically by signing key hash */
720 download_status_reset_by_sk_in_cl(cl
, cert
->signing_key_digest
);
724 } SMARTLIST_FOREACH_END(cert
);
726 download_status_is_ready(&(cl
->dl_status_by_id
), now
,
727 MAX_CERT_DL_FAILURES
) &&
728 !digestmap_get(pending_id
, ds
->v3_identity_digest
)) {
730 "No current certificate known for authority %s "
731 "(ID digest %s); launching request.",
732 ds
->nickname
, hex_str(ds
->v3_identity_digest
, DIGEST_LEN
));
733 smartlist_add(missing_id_digests
, ds
->v3_identity_digest
);
735 } SMARTLIST_FOREACH_END(ds
);
738 * Next, if we have a consensus, scan through it and look for anything
739 * signed with a key from a cert we don't have. Those get downloaded
740 * by (fp,sk) pair, but if we don't know any certs at all for the fp
741 * (identity digest), and it's one of the trusted dir server certs
742 * we started off above or a pending download in pending_id, don't
743 * try to get it yet. Most likely, the one we'll get for that will
744 * have the right signing key too, and we'd just be downloading
748 SMARTLIST_FOREACH_BEGIN(status
->voters
, networkstatus_voter_info_t
*,
750 if (!smartlist_len(voter
->sigs
))
751 continue; /* This authority never signed this consensus, so don't
752 * go looking for a cert with key digest 0000000000. */
754 !trusteddirserver_get_by_v3_auth_digest(voter
->identity_digest
))
755 continue; /* We are not a cache, and we don't know this authority.*/
758 * If we don't know *any* cert for this authority, and a download by ID
759 * is pending or we added it to missing_id_digests above, skip this
760 * one for now to avoid duplicate downloads.
762 cl
= get_cert_list(voter
->identity_digest
);
763 if (smartlist_len(cl
->certs
) == 0) {
764 /* We have no certs at all for this one */
766 /* Do we have a download of one pending? */
767 if (digestmap_get(pending_id
, voter
->identity_digest
))
771 * Are we about to launch a download of one due to the trusted
772 * dir server check above?
774 if (smartlist_contains_digest(missing_id_digests
,
775 voter
->identity_digest
))
779 SMARTLIST_FOREACH_BEGIN(voter
->sigs
, document_signature_t
*, sig
) {
780 cert
= authority_cert_get_by_digests(voter
->identity_digest
,
781 sig
->signing_key_digest
);
783 if (now
< cert
->expires
)
784 download_status_reset_by_sk_in_cl(cl
, sig
->signing_key_digest
);
787 if (download_status_is_ready_by_sk_in_cl(
788 cl
, sig
->signing_key_digest
,
789 now
, MAX_CERT_DL_FAILURES
) &&
790 !fp_pair_map_get_by_digests(pending_cert
,
791 voter
->identity_digest
,
792 sig
->signing_key_digest
)) {
794 * Do this rather than hex_str(), since hex_str clobbers
795 * old results and we call twice in the param list.
797 base16_encode(id_digest_str
, sizeof(id_digest_str
),
798 voter
->identity_digest
, DIGEST_LEN
);
799 base16_encode(sk_digest_str
, sizeof(sk_digest_str
),
800 sig
->signing_key_digest
, DIGEST_LEN
);
802 if (voter
->nickname
) {
804 "We're missing a certificate from authority %s "
805 "(ID digest %s) with signing key %s: "
806 "launching request.",
807 voter
->nickname
, id_digest_str
, sk_digest_str
);
810 "We're missing a certificate from authority ID digest "
811 "%s with signing key %s: launching request.",
812 id_digest_str
, sk_digest_str
);
815 /* Allocate a new fp_pair_t to append */
816 fp_tmp
= tor_malloc(sizeof(*fp_tmp
));
817 memcpy(fp_tmp
->first
, voter
->identity_digest
, sizeof(fp_tmp
->first
));
818 memcpy(fp_tmp
->second
, sig
->signing_key_digest
,
819 sizeof(fp_tmp
->second
));
820 smartlist_add(missing_cert_digests
, fp_tmp
);
822 } SMARTLIST_FOREACH_END(sig
);
823 } SMARTLIST_FOREACH_END(voter
);
826 /* Do downloads by identity digest */
827 if (smartlist_len(missing_id_digests
) > 0) {
829 smartlist_t
*fps
= smartlist_new();
831 smartlist_add(fps
, tor_strdup("fp/"));
833 SMARTLIST_FOREACH_BEGIN(missing_id_digests
, const char *, d
) {
836 if (digestmap_get(pending_id
, d
))
839 base16_encode(id_digest_str
, sizeof(id_digest_str
),
843 tor_asprintf(&fp
, "+%s", id_digest_str
);
845 /* No need for tor_asprintf() in this case; first one gets no '+' */
846 fp
= tor_strdup(id_digest_str
);
850 smartlist_add(fps
, fp
);
851 } SMARTLIST_FOREACH_END(d
);
853 if (smartlist_len(fps
) > 1) {
854 resource
= smartlist_join_strings(fps
, "", 0, NULL
);
855 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CERTIFICATE
, 0,
856 resource
, PDS_RETRY_IF_NO_SERVERS
);
859 /* else we didn't add any: they were all pending */
861 SMARTLIST_FOREACH(fps
, char *, cp
, tor_free(cp
));
865 /* Do downloads by identity digest/signing key pair */
866 if (smartlist_len(missing_cert_digests
) > 0) {
868 smartlist_t
*fp_pairs
= smartlist_new();
870 smartlist_add(fp_pairs
, tor_strdup("fp-sk/"));
872 SMARTLIST_FOREACH_BEGIN(missing_cert_digests
, const fp_pair_t
*, d
) {
873 char *fp_pair
= NULL
;
875 if (fp_pair_map_get(pending_cert
, d
))
878 /* Construct string encodings of the digests */
879 base16_encode(id_digest_str
, sizeof(id_digest_str
),
880 d
->first
, DIGEST_LEN
);
881 base16_encode(sk_digest_str
, sizeof(sk_digest_str
),
882 d
->second
, DIGEST_LEN
);
884 /* Now tor_asprintf() */
886 tor_asprintf(&fp_pair
, "+%s-%s", id_digest_str
, sk_digest_str
);
888 /* First one in the list doesn't get a '+' */
889 tor_asprintf(&fp_pair
, "%s-%s", id_digest_str
, sk_digest_str
);
893 /* Add it to the list of pairs to request */
894 smartlist_add(fp_pairs
, fp_pair
);
895 } SMARTLIST_FOREACH_END(d
);
897 if (smartlist_len(fp_pairs
) > 1) {
898 resource
= smartlist_join_strings(fp_pairs
, "", 0, NULL
);
899 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CERTIFICATE
, 0,
900 resource
, PDS_RETRY_IF_NO_SERVERS
);
903 /* else they were all pending */
905 SMARTLIST_FOREACH(fp_pairs
, char *, p
, tor_free(p
));
906 smartlist_free(fp_pairs
);
909 smartlist_free(missing_id_digests
);
910 SMARTLIST_FOREACH(missing_cert_digests
, fp_pair_t
*, p
, tor_free(p
));
911 smartlist_free(missing_cert_digests
);
912 digestmap_free(pending_id
, NULL
);
913 fp_pair_map_free(pending_cert
, NULL
);
916 /* Router descriptor storage.
918 * Routerdescs are stored in a big file, named "cached-descriptors". As new
919 * routerdescs arrive, we append them to a journal file named
920 * "cached-descriptors.new".
922 * From time to time, we replace "cached-descriptors" with a new file
923 * containing only the live, non-superseded descriptors, and clear
924 * cached-routers.new.
926 * On startup, we read both files.
929 /** Helper: return 1 iff the router log is so big we want to rebuild the
932 router_should_rebuild_store(desc_store_t
*store
)
934 if (store
->store_len
> (1<<16))
935 return (store
->journal_len
> store
->store_len
/ 2 ||
936 store
->bytes_dropped
> store
->store_len
/ 2);
938 return store
->journal_len
> (1<<15);
941 /** Return the desc_store_t in <b>rl</b> that should be used to store
943 static INLINE desc_store_t
*
944 desc_get_store(routerlist_t
*rl
, const signed_descriptor_t
*sd
)
946 if (sd
->is_extrainfo
)
947 return &rl
->extrainfo_store
;
949 return &rl
->desc_store
;
952 /** Add the signed_descriptor_t in <b>desc</b> to the router
953 * journal; change its saved_location to SAVED_IN_JOURNAL and set its
954 * offset appropriately. */
956 signed_desc_append_to_journal(signed_descriptor_t
*desc
,
959 char *fname
= get_datadir_fname_suffix(store
->fname_base
, ".new");
960 const char *body
= signed_descriptor_get_body_impl(desc
,1);
961 size_t len
= desc
->signed_descriptor_len
+ desc
->annotations_len
;
963 if (append_bytes_to_file(fname
, body
, len
, 1)) {
964 log_warn(LD_FS
, "Unable to store router descriptor");
968 desc
->saved_location
= SAVED_IN_JOURNAL
;
971 desc
->saved_offset
= store
->journal_len
;
972 store
->journal_len
+= len
;
977 /** Sorting helper: return <0, 0, or >0 depending on whether the
978 * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
979 * the signed_descriptor_t* in *<b>b</b>. */
981 compare_signed_descriptors_by_age_(const void **_a
, const void **_b
)
983 const signed_descriptor_t
*r1
= *_a
, *r2
= *_b
;
984 return (int)(r1
->published_on
- r2
->published_on
);
988 #define RRS_DONT_REMOVE_OLD 2
990 /** If the journal of <b>store</b> is too long, or if RRS_FORCE is set in
991 * <b>flags</b>, then atomically replace the saved router store with the
992 * routers currently in our routerlist, and clear the journal. Unless
993 * RRS_DONT_REMOVE_OLD is set in <b>flags</b>, delete expired routers before
994 * rebuilding the store. Return 0 on success, -1 on failure.
997 router_rebuild_store(int flags
, desc_store_t
*store
)
999 smartlist_t
*chunk_list
= NULL
;
1000 char *fname
= NULL
, *fname_tmp
= NULL
;
1003 smartlist_t
*signed_descriptors
= NULL
;
1005 size_t total_expected_len
= 0;
1007 int force
= flags
& RRS_FORCE
;
1009 if (!force
&& !router_should_rebuild_store(store
)) {
1018 if (store
->type
== EXTRAINFO_STORE
)
1019 had_any
= !eimap_isempty(routerlist
->extra_info_map
);
1021 had_any
= (smartlist_len(routerlist
->routers
)+
1022 smartlist_len(routerlist
->old_routers
))>0;
1024 /* Don't save deadweight. */
1025 if (!(flags
& RRS_DONT_REMOVE_OLD
))
1026 routerlist_remove_old_routers();
1028 log_info(LD_DIR
, "Rebuilding %s cache", store
->description
);
1030 fname
= get_datadir_fname(store
->fname_base
);
1031 fname_tmp
= get_datadir_fname_suffix(store
->fname_base
, ".tmp");
1033 chunk_list
= smartlist_new();
1035 /* We sort the routers by age to enhance locality on disk. */
1036 signed_descriptors
= smartlist_new();
1037 if (store
->type
== EXTRAINFO_STORE
) {
1039 for (iter
= eimap_iter_init(routerlist
->extra_info_map
);
1040 !eimap_iter_done(iter
);
1041 iter
= eimap_iter_next(routerlist
->extra_info_map
, iter
)) {
1044 eimap_iter_get(iter
, &key
, &ei
);
1045 smartlist_add(signed_descriptors
, &ei
->cache_info
);
1048 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
,
1049 smartlist_add(signed_descriptors
, sd
));
1050 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
1051 smartlist_add(signed_descriptors
, &ri
->cache_info
));
1054 smartlist_sort(signed_descriptors
, compare_signed_descriptors_by_age_
);
1056 /* Now, add the appropriate members to chunk_list */
1057 SMARTLIST_FOREACH_BEGIN(signed_descriptors
, signed_descriptor_t
*, sd
) {
1059 const char *body
= signed_descriptor_get_body_impl(sd
, 1);
1061 log_warn(LD_BUG
, "No descriptor available for router.");
1064 if (sd
->do_not_cache
) {
1068 c
= tor_malloc(sizeof(sized_chunk_t
));
1070 c
->len
= sd
->signed_descriptor_len
+ sd
->annotations_len
;
1071 total_expected_len
+= c
->len
;
1072 smartlist_add(chunk_list
, c
);
1073 } SMARTLIST_FOREACH_END(sd
);
1075 if (write_chunks_to_file(fname_tmp
, chunk_list
, 1)<0) {
1076 log_warn(LD_FS
, "Error writing router store to disk.");
1080 /* Our mmap is now invalid. */
1082 tor_munmap_file(store
->mmap
);
1086 if (replace_file(fname_tmp
, fname
)<0) {
1087 log_warn(LD_FS
, "Error replacing old router store: %s", strerror(errno
));
1092 store
->mmap
= tor_mmap_file(fname
);
1093 if (! store
->mmap
) {
1094 if (errno
== ERANGE
) {
1096 if (total_expected_len
) {
1097 log_warn(LD_FS
, "We wrote some bytes to a new descriptor file at '%s',"
1098 " but when we went to mmap it, it was empty!", fname
);
1099 } else if (had_any
) {
1100 log_info(LD_FS
, "We just removed every descriptor in '%s'. This is "
1101 "okay if we're just starting up after a long time. "
1102 "Otherwise, it's a bug.", fname
);
1105 log_warn(LD_FS
, "Unable to mmap new descriptor file at '%s'.",fname
);
1109 log_info(LD_DIR
, "Reconstructing pointers into cache");
1112 SMARTLIST_FOREACH_BEGIN(signed_descriptors
, signed_descriptor_t
*, sd
) {
1113 if (sd
->do_not_cache
)
1115 sd
->saved_location
= SAVED_IN_CACHE
;
1117 tor_free(sd
->signed_descriptor_body
); // sets it to null
1118 sd
->saved_offset
= offset
;
1120 offset
+= sd
->signed_descriptor_len
+ sd
->annotations_len
;
1121 signed_descriptor_get_body(sd
); /* reconstruct and assert */
1122 } SMARTLIST_FOREACH_END(sd
);
1125 fname
= get_datadir_fname_suffix(store
->fname_base
, ".new");
1126 write_str_to_file(fname
, "", 1);
1129 store
->store_len
= (size_t) offset
;
1130 store
->journal_len
= 0;
1131 store
->bytes_dropped
= 0;
1133 smartlist_free(signed_descriptors
);
1135 tor_free(fname_tmp
);
1137 SMARTLIST_FOREACH(chunk_list
, sized_chunk_t
*, c
, tor_free(c
));
1138 smartlist_free(chunk_list
);
1144 /** Helper: Reload a cache file and its associated journal, setting metadata
1145 * appropriately. If <b>extrainfo</b> is true, reload the extrainfo store;
1146 * else reload the router descriptor store. */
1148 router_reload_router_list_impl(desc_store_t
*store
)
1150 char *fname
= NULL
, *altname
= NULL
, *contents
= NULL
;
1152 int read_from_old_location
= 0;
1153 int extrainfo
= (store
->type
== EXTRAINFO_STORE
);
1154 time_t now
= time(NULL
);
1155 store
->journal_len
= store
->store_len
= 0;
1157 fname
= get_datadir_fname(store
->fname_base
);
1158 if (store
->fname_alt_base
)
1159 altname
= get_datadir_fname(store
->fname_alt_base
);
1161 if (store
->mmap
) /* get rid of it first */
1162 tor_munmap_file(store
->mmap
);
1165 store
->mmap
= tor_mmap_file(fname
);
1166 if (!store
->mmap
&& altname
&& file_status(altname
) == FN_FILE
) {
1167 read_from_old_location
= 1;
1168 log_notice(LD_DIR
, "Couldn't read %s; trying to load routers from old "
1169 "location %s.", fname
, altname
);
1170 if ((store
->mmap
= tor_mmap_file(altname
)))
1171 read_from_old_location
= 1;
1173 if (altname
&& !read_from_old_location
) {
1174 remove_file_if_very_old(altname
, now
);
1177 store
->store_len
= store
->mmap
->size
;
1179 router_load_extrainfo_from_string(store
->mmap
->data
,
1180 store
->mmap
->data
+store
->mmap
->size
,
1181 SAVED_IN_CACHE
, NULL
, 0);
1183 router_load_routers_from_string(store
->mmap
->data
,
1184 store
->mmap
->data
+store
->mmap
->size
,
1185 SAVED_IN_CACHE
, NULL
, 0, NULL
);
1189 fname
= get_datadir_fname_suffix(store
->fname_base
, ".new");
1190 if (file_status(fname
) == FN_FILE
)
1191 contents
= read_file_to_str(fname
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
1192 if (read_from_old_location
) {
1194 altname
= get_datadir_fname_suffix(store
->fname_alt_base
, ".new");
1196 contents
= read_file_to_str(altname
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
1198 remove_file_if_very_old(altname
, now
);
1202 router_load_extrainfo_from_string(contents
, NULL
,SAVED_IN_JOURNAL
,
1205 router_load_routers_from_string(contents
, NULL
, SAVED_IN_JOURNAL
,
1207 store
->journal_len
= (size_t) st
.st_size
;
1214 if (store
->journal_len
|| read_from_old_location
) {
1215 /* Always clear the journal on startup.*/
1216 router_rebuild_store(RRS_FORCE
, store
);
1217 } else if (!extrainfo
) {
1218 /* Don't cache expired routers. (This is in an else because
1219 * router_rebuild_store() also calls remove_old_routers().) */
1220 routerlist_remove_old_routers();
1226 /** Load all cached router descriptors and extra-info documents from the
1227 * store. Return 0 on success and -1 on failure.
1230 router_reload_router_list(void)
1232 routerlist_t
*rl
= router_get_routerlist();
1233 if (router_reload_router_list_impl(&rl
->desc_store
))
1235 if (router_reload_router_list_impl(&rl
->extrainfo_store
))
1240 /** Return a smartlist containing a list of dir_server_t * for all
1241 * known trusted dirservers. Callers must not modify the list or its
1245 router_get_trusted_dir_servers(void)
1247 if (!trusted_dir_servers
)
1248 trusted_dir_servers
= smartlist_new();
1250 return trusted_dir_servers
;
1254 router_get_fallback_dir_servers(void)
1256 if (!fallback_dir_servers
)
1257 fallback_dir_servers
= smartlist_new();
1259 return fallback_dir_servers
;
1262 /** Try to find a running dirserver that supports operations of <b>type</b>.
1264 * If there are no running dirservers in our routerlist and the
1265 * <b>PDS_RETRY_IF_NO_SERVERS</b> flag is set, set all the authoritative ones
1266 * as running again, and pick one.
1268 * If the <b>PDS_IGNORE_FASCISTFIREWALL</b> flag is set, then include
1269 * dirservers that we can't reach.
1271 * If the <b>PDS_ALLOW_SELF</b> flag is not set, then don't include ourself
1272 * (if we're a dirserver).
1274 * Don't pick an authority if any non-authority is viable; try to avoid using
1275 * servers that have returned 503 recently.
1277 const routerstatus_t
*
1278 router_pick_directory_server(dirinfo_type_t type
, int flags
)
1280 const routerstatus_t
*choice
;
1281 if (get_options()->PreferTunneledDirConns
)
1282 flags
|= PDS_PREFER_TUNNELED_DIR_CONNS_
;
1287 choice
= router_pick_directory_server_impl(type
, flags
);
1288 if (choice
|| !(flags
& PDS_RETRY_IF_NO_SERVERS
))
1292 "No reachable router entries for dirservers. "
1293 "Trying them all again.");
1294 /* mark all authdirservers as up again */
1295 mark_all_dirservers_up(fallback_dir_servers
);
1297 choice
= router_pick_directory_server_impl(type
, flags
);
1301 /** Try to determine which fraction of v2 and v3 directory requests aimed at
1302 * caches will be sent to us. Set *<b>v2_share_out</b> and
1303 * *<b>v3_share_out</b> to the fractions of v2 and v3 protocol shares we
1304 * expect to see, respectively. Return 0 on success, negative on failure. */
1306 router_get_my_share_of_directory_requests(double *v2_share_out
,
1307 double *v3_share_out
)
1309 const routerinfo_t
*me
= router_get_my_routerinfo();
1310 const routerstatus_t
*rs
;
1311 const int pds_flags
= PDS_ALLOW_SELF
|PDS_IGNORE_FASCISTFIREWALL
;
1312 *v2_share_out
= *v3_share_out
= 0.0;
1315 rs
= router_get_consensus_status_by_id(me
->cache_info
.identity_digest
);
1319 /* Calling for side effect */
1320 /* XXXX This is a bit of a kludge */
1321 if (rs
->is_v2_dir
) {
1322 sl_last_total_weighted_bw
= 0;
1323 router_pick_directory_server(V2_DIRINFO
, pds_flags
);
1324 if (sl_last_total_weighted_bw
!= 0) {
1325 *v2_share_out
= U64_TO_DBL(sl_last_weighted_bw_of_me
) /
1326 U64_TO_DBL(sl_last_total_weighted_bw
);
1331 sl_last_total_weighted_bw
= 0;
1332 router_pick_directory_server(V3_DIRINFO
, pds_flags
);
1333 if (sl_last_total_weighted_bw
!= 0) {
1334 *v3_share_out
= U64_TO_DBL(sl_last_weighted_bw_of_me
) /
1335 U64_TO_DBL(sl_last_total_weighted_bw
);
1342 /** Return the dir_server_t for the directory authority whose identity
1343 * key hashes to <b>digest</b>, or NULL if no such authority is known.
1346 router_get_trusteddirserver_by_digest(const char *digest
)
1348 if (!trusted_dir_servers
)
1351 SMARTLIST_FOREACH(trusted_dir_servers
, dir_server_t
*, ds
,
1353 if (tor_memeq(ds
->digest
, digest
, DIGEST_LEN
))
1360 /** Return the dir_server_t for the fallback dirserver whose identity
1361 * key hashes to <b>digest</b>, or NULL if no such authority is known.
1364 router_get_fallback_dirserver_by_digest(const char *digest
)
1366 if (!trusted_dir_servers
)
1369 SMARTLIST_FOREACH(trusted_dir_servers
, dir_server_t
*, ds
,
1371 if (tor_memeq(ds
->digest
, digest
, DIGEST_LEN
))
1378 /** Return the dir_server_t for the directory authority whose
1379 * v3 identity key hashes to <b>digest</b>, or NULL if no such authority
1383 trusteddirserver_get_by_v3_auth_digest(const char *digest
)
1385 if (!trusted_dir_servers
)
1388 SMARTLIST_FOREACH(trusted_dir_servers
, dir_server_t
*, ds
,
1390 if (tor_memeq(ds
->v3_identity_digest
, digest
, DIGEST_LEN
) &&
1391 (ds
->type
& V3_DIRINFO
))
1398 /** Try to find a running directory authority. Flags are as for
1399 * router_pick_directory_server.
1401 const routerstatus_t
*
1402 router_pick_trusteddirserver(dirinfo_type_t type
, int flags
)
1404 return router_pick_dirserver_generic(trusted_dir_servers
, type
, flags
);
1407 /** Try to find a running fallback directory Flags are as for
1408 * router_pick_directory_server.
1410 const routerstatus_t
*
1411 router_pick_fallback_dirserver(dirinfo_type_t type
, int flags
)
1413 return router_pick_dirserver_generic(fallback_dir_servers
, type
, flags
);
1416 /** Try to find a running fallback directory Flags are as for
1417 * router_pick_directory_server.
1419 static const routerstatus_t
*
1420 router_pick_dirserver_generic(smartlist_t
*sourcelist
,
1421 dirinfo_type_t type
, int flags
)
1423 const routerstatus_t
*choice
;
1425 if (get_options()->PreferTunneledDirConns
)
1426 flags
|= PDS_PREFER_TUNNELED_DIR_CONNS_
;
1428 choice
= router_pick_trusteddirserver_impl(sourcelist
, type
, flags
, &busy
);
1429 if (choice
|| !(flags
& PDS_RETRY_IF_NO_SERVERS
))
1432 /* If the reason that we got no server is that servers are "busy",
1433 * we must be excluding good servers because we already have serverdesc
1434 * fetches with them. Do not mark down servers up because of this. */
1435 tor_assert((flags
& (PDS_NO_EXISTING_SERVERDESC_FETCH
|
1436 PDS_NO_EXISTING_MICRODESC_FETCH
)));
1441 "No dirservers are reachable. Trying them all again.");
1442 mark_all_dirservers_up(sourcelist
);
1443 return router_pick_trusteddirserver_impl(sourcelist
, type
, flags
, NULL
);
1446 /** How long do we avoid using a directory server after it's given us a 503? */
1447 #define DIR_503_TIMEOUT (60*60)
1449 /** Pick a random running valid directory server/mirror from our
1450 * routerlist. Arguments are as for router_pick_directory_server(), except
1451 * that RETRY_IF_NO_SERVERS is ignored, and:
1453 * If the PDS_PREFER_TUNNELED_DIR_CONNS_ flag is set, prefer directory servers
1454 * that we can use with BEGINDIR.
1456 static const routerstatus_t
*
1457 router_pick_directory_server_impl(dirinfo_type_t type
, int flags
)
1459 const or_options_t
*options
= get_options();
1460 const node_t
*result
;
1461 smartlist_t
*direct
, *tunnel
;
1462 smartlist_t
*trusted_direct
, *trusted_tunnel
;
1463 smartlist_t
*overloaded_direct
, *overloaded_tunnel
;
1464 time_t now
= time(NULL
);
1465 const networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
1466 int requireother
= ! (flags
& PDS_ALLOW_SELF
);
1467 int fascistfirewall
= ! (flags
& PDS_IGNORE_FASCISTFIREWALL
);
1468 int prefer_tunnel
= (flags
& PDS_PREFER_TUNNELED_DIR_CONNS_
);
1469 int for_guard
= (flags
& PDS_FOR_GUARD
);
1470 int try_excluding
= 1, n_excluded
= 0;
1475 retry_without_exclude
:
1477 direct
= smartlist_new();
1478 tunnel
= smartlist_new();
1479 trusted_direct
= smartlist_new();
1480 trusted_tunnel
= smartlist_new();
1481 overloaded_direct
= smartlist_new();
1482 overloaded_tunnel
= smartlist_new();
1484 /* Find all the running dirservers we know about. */
1485 SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t
*, node
) {
1489 const routerstatus_t
*status
= node
->rs
;
1490 const country_t country
= node
->country
;
1494 if (!node
->is_running
|| !status
->dir_port
|| !node
->is_valid
)
1496 if (node
->is_bad_directory
)
1498 if (requireother
&& router_digest_is_me(node
->identity
))
1500 is_trusted
= router_digest_is_trusted_dir(node
->identity
);
1501 if ((type
& V2_DIRINFO
) && !(node
->rs
->is_v2_dir
|| is_trusted
))
1503 if ((type
& EXTRAINFO_DIRINFO
) &&
1504 !router_supports_extrainfo(node
->identity
, 0))
1506 if ((type
& MICRODESC_DIRINFO
) && !is_trusted
&&
1507 !node
->rs
->version_supports_microdesc_cache
)
1509 if (for_guard
&& node
->using_as_guard
)
1510 continue; /* Don't make the same node a guard twice. */
1511 if (try_excluding
&&
1512 routerset_contains_routerstatus(options
->ExcludeNodes
, status
,
1518 /* XXXX IP6 proposal 118 */
1519 tor_addr_from_ipv4h(&addr
, node
->rs
->addr
);
1521 is_overloaded
= status
->last_dir_503_at
+ DIR_503_TIMEOUT
> now
;
1523 if (prefer_tunnel
&&
1524 (!fascistfirewall
||
1525 fascist_firewall_allows_address_or(&addr
, status
->or_port
)))
1526 smartlist_add(is_trusted
? trusted_tunnel
:
1527 is_overloaded
? overloaded_tunnel
: tunnel
, (void*)node
);
1528 else if (!fascistfirewall
||
1529 fascist_firewall_allows_address_dir(&addr
, status
->dir_port
))
1530 smartlist_add(is_trusted
? trusted_direct
:
1531 is_overloaded
? overloaded_direct
: direct
, (void*)node
);
1532 } SMARTLIST_FOREACH_END(node
);
1534 if (smartlist_len(tunnel
)) {
1535 result
= node_sl_choose_by_bandwidth(tunnel
, WEIGHT_FOR_DIR
);
1536 } else if (smartlist_len(overloaded_tunnel
)) {
1537 result
= node_sl_choose_by_bandwidth(overloaded_tunnel
,
1539 } else if (smartlist_len(trusted_tunnel
)) {
1540 /* FFFF We don't distinguish between trusteds and overloaded trusteds
1541 * yet. Maybe one day we should. */
1542 /* FFFF We also don't load balance over authorities yet. I think this
1543 * is a feature, but it could easily be a bug. -RD */
1544 result
= smartlist_choose(trusted_tunnel
);
1545 } else if (smartlist_len(direct
)) {
1546 result
= node_sl_choose_by_bandwidth(direct
, WEIGHT_FOR_DIR
);
1547 } else if (smartlist_len(overloaded_direct
)) {
1548 result
= node_sl_choose_by_bandwidth(overloaded_direct
,
1551 result
= smartlist_choose(trusted_direct
);
1553 smartlist_free(direct
);
1554 smartlist_free(tunnel
);
1555 smartlist_free(trusted_direct
);
1556 smartlist_free(trusted_tunnel
);
1557 smartlist_free(overloaded_direct
);
1558 smartlist_free(overloaded_tunnel
);
1560 if (result
== NULL
&& try_excluding
&& !options
->StrictNodes
&& n_excluded
) {
1561 /* If we got no result, and we are excluding nodes, and StrictNodes is
1562 * not set, try again without excluding nodes. */
1565 goto retry_without_exclude
;
1568 return result
? result
->rs
: NULL
;
1571 /** Pick a random element from a list of dir_server_t, weighting by their
1572 * <b>weight</b> field. */
1573 static const dir_server_t
*
1574 dirserver_choose_by_weight(const smartlist_t
*servers
, double authority_weight
)
1576 int n
= smartlist_len(servers
);
1579 const dir_server_t
*ds
;
1581 weights
= tor_malloc(sizeof(u64_dbl_t
) * n
);
1582 for (i
= 0; i
< n
; ++i
) {
1583 ds
= smartlist_get(servers
, i
);
1584 weights
[i
].dbl
= ds
->weight
;
1585 if (ds
->is_authority
)
1586 weights
[i
].dbl
*= authority_weight
;
1589 scale_array_elements_to_u64(weights
, n
, NULL
);
1590 i
= choose_array_element_by_weight(weights
, n
);
1592 return (i
< 0) ? NULL
: smartlist_get(servers
, i
);
1595 /** Choose randomly from among the dir_server_ts in sourcelist that
1596 * are up. Flags are as for router_pick_directory_server_impl().
1598 static const routerstatus_t
*
1599 router_pick_trusteddirserver_impl(const smartlist_t
*sourcelist
,
1600 dirinfo_type_t type
, int flags
,
1603 const or_options_t
*options
= get_options();
1604 smartlist_t
*direct
, *tunnel
;
1605 smartlist_t
*overloaded_direct
, *overloaded_tunnel
;
1606 const routerinfo_t
*me
= router_get_my_routerinfo();
1607 const routerstatus_t
*result
= NULL
;
1608 time_t now
= time(NULL
);
1609 const int requireother
= ! (flags
& PDS_ALLOW_SELF
);
1610 const int fascistfirewall
= ! (flags
& PDS_IGNORE_FASCISTFIREWALL
);
1611 const int prefer_tunnel
= (flags
& PDS_PREFER_TUNNELED_DIR_CONNS_
);
1612 const int no_serverdesc_fetching
=(flags
& PDS_NO_EXISTING_SERVERDESC_FETCH
);
1613 const int no_microdesc_fetching
=(flags
& PDS_NO_EXISTING_MICRODESC_FETCH
);
1614 const double auth_weight
= (sourcelist
== fallback_dir_servers
) ?
1615 options
->DirAuthorityFallbackRate
: 1.0;
1616 smartlist_t
*pick_from
;
1618 int try_excluding
= 1, n_excluded
= 0;
1623 retry_without_exclude
:
1625 direct
= smartlist_new();
1626 tunnel
= smartlist_new();
1627 overloaded_direct
= smartlist_new();
1628 overloaded_tunnel
= smartlist_new();
1630 SMARTLIST_FOREACH_BEGIN(sourcelist
, const dir_server_t
*, d
)
1633 d
->fake_status
.last_dir_503_at
+ DIR_503_TIMEOUT
> now
;
1635 if (!d
->is_running
) continue;
1636 if ((type
& d
->type
) == 0)
1638 if ((type
& EXTRAINFO_DIRINFO
) &&
1639 !router_supports_extrainfo(d
->digest
, 1))
1641 if (requireother
&& me
&& router_digest_is_me(d
->digest
))
1643 if (try_excluding
&&
1644 routerset_contains_routerstatus(options
->ExcludeNodes
,
1645 &d
->fake_status
, -1)) {
1650 /* XXXX IP6 proposal 118 */
1651 tor_addr_from_ipv4h(&addr
, d
->addr
);
1653 if (no_serverdesc_fetching
) {
1654 if (connection_get_by_type_addr_port_purpose(
1655 CONN_TYPE_DIR
, &addr
, d
->dir_port
, DIR_PURPOSE_FETCH_SERVERDESC
)
1656 || connection_get_by_type_addr_port_purpose(
1657 CONN_TYPE_DIR
, &addr
, d
->dir_port
, DIR_PURPOSE_FETCH_EXTRAINFO
)) {
1658 //log_debug(LD_DIR, "We have an existing connection to fetch "
1659 // "descriptor from %s; delaying",d->description);
1664 if (no_microdesc_fetching
) {
1665 if (connection_get_by_type_addr_port_purpose(
1666 CONN_TYPE_DIR
, &addr
, d
->dir_port
, DIR_PURPOSE_FETCH_MICRODESC
)) {
1672 if (prefer_tunnel
&&
1674 (!fascistfirewall
||
1675 fascist_firewall_allows_address_or(&addr
, d
->or_port
)))
1676 smartlist_add(is_overloaded
? overloaded_tunnel
: tunnel
, (void*)d
);
1677 else if (!fascistfirewall
||
1678 fascist_firewall_allows_address_dir(&addr
, d
->dir_port
))
1679 smartlist_add(is_overloaded
? overloaded_direct
: direct
, (void*)d
);
1681 SMARTLIST_FOREACH_END(d
);
1683 if (smartlist_len(tunnel
)) {
1685 } else if (smartlist_len(overloaded_tunnel
)) {
1686 pick_from
= overloaded_tunnel
;
1687 } else if (smartlist_len(direct
)) {
1690 pick_from
= overloaded_direct
;
1694 const dir_server_t
*selection
=
1695 dirserver_choose_by_weight(pick_from
, auth_weight
);
1698 result
= &selection
->fake_status
;
1702 *n_busy_out
= n_busy
;
1704 smartlist_free(direct
);
1705 smartlist_free(tunnel
);
1706 smartlist_free(overloaded_direct
);
1707 smartlist_free(overloaded_tunnel
);
1709 if (result
== NULL
&& try_excluding
&& !options
->StrictNodes
&& n_excluded
) {
1710 /* If we got no result, and we are excluding nodes, and StrictNodes is
1711 * not set, try again without excluding nodes. */
1714 goto retry_without_exclude
;
1720 /** Mark as running every dir_server_t in <b>server_list</b>. */
1722 mark_all_dirservers_up(smartlist_t
*server_list
)
1725 SMARTLIST_FOREACH_BEGIN(server_list
, dir_server_t
*, dir
) {
1728 dir
->is_running
= 1;
1729 download_status_reset(&dir
->v2_ns_dl_status
);
1730 node
= node_get_mutable_by_id(dir
->digest
);
1732 node
->is_running
= 1;
1733 rs
= router_get_mutable_consensus_status_by_id(dir
->digest
);
1735 rs
->last_dir_503_at
= 0;
1736 control_event_networkstatus_changed_single(rs
);
1738 } SMARTLIST_FOREACH_END(dir
);
1740 router_dir_info_changed();
1743 /** Return true iff r1 and r2 have the same address and OR port. */
1745 routers_have_same_or_addrs(const routerinfo_t
*r1
, const routerinfo_t
*r2
)
1747 return r1
->addr
== r2
->addr
&& r1
->or_port
== r2
->or_port
&&
1748 tor_addr_eq(&r1
->ipv6_addr
, &r2
->ipv6_addr
) &&
1749 r1
->ipv6_orport
== r2
->ipv6_orport
;
1752 /** Reset all internal variables used to count failed downloads of network
1753 * status objects. */
1755 router_reset_status_download_failures(void)
1757 mark_all_dirservers_up(fallback_dir_servers
);
1760 /** Given a <b>router</b>, add every node_t in its family (including the
1761 * node itself!) to <b>sl</b>.
1763 * Note the type mismatch: This function takes a routerinfo, but adds nodes
1767 routerlist_add_node_and_family(smartlist_t
*sl
, const routerinfo_t
*router
)
1771 const node_t
*node
= node_get_by_id(router
->cache_info
.identity_digest
);;
1773 memset(&fake_node
, 0, sizeof(fake_node
));
1774 fake_node
.ri
= (routerinfo_t
*)router
;
1775 memcpy(fake_node
.identity
, router
->cache_info
.identity_digest
, DIGEST_LEN
);
1778 nodelist_add_node_and_family(sl
, node
);
1781 /** Add every suitable node from our nodelist to <b>sl</b>, so that
1782 * we can pick a node for a circuit.
1785 router_add_running_nodes_to_smartlist(smartlist_t
*sl
, int allow_invalid
,
1786 int need_uptime
, int need_capacity
,
1787 int need_guard
, int need_desc
)
1789 SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t
*, node
) {
1790 if (!node
->is_running
||
1791 (!node
->is_valid
&& !allow_invalid
))
1793 if (need_desc
&& !(node
->ri
|| (node
->rs
&& node
->md
)))
1795 if (node
->ri
&& node
->ri
->purpose
!= ROUTER_PURPOSE_GENERAL
)
1797 if (node_is_unreliable(node
, need_uptime
, need_capacity
, need_guard
))
1800 smartlist_add(sl
, (void *)node
);
1801 } SMARTLIST_FOREACH_END(node
);
1804 /** Look through the routerlist until we find a router that has my key.
1806 const routerinfo_t
*
1807 routerlist_find_my_routerinfo(void)
1812 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1814 if (router_is_me(router
))
1820 /** Return the smaller of the router's configured BandwidthRate
1821 * and its advertised capacity. */
1823 router_get_advertised_bandwidth(const routerinfo_t
*router
)
1825 if (router
->bandwidthcapacity
< router
->bandwidthrate
)
1826 return router
->bandwidthcapacity
;
1827 return router
->bandwidthrate
;
1830 /** Do not weight any declared bandwidth more than this much when picking
1831 * routers by bandwidth. */
1832 #define DEFAULT_MAX_BELIEVABLE_BANDWIDTH 10000000 /* 10 MB/sec */
1834 /** Return the smaller of the router's configured BandwidthRate
1835 * and its advertised capacity, capped by max-believe-bw. */
1837 router_get_advertised_bandwidth_capped(const routerinfo_t
*router
)
1839 uint32_t result
= router
->bandwidthcapacity
;
1840 if (result
> router
->bandwidthrate
)
1841 result
= router
->bandwidthrate
;
1842 if (result
> DEFAULT_MAX_BELIEVABLE_BANDWIDTH
)
1843 result
= DEFAULT_MAX_BELIEVABLE_BANDWIDTH
;
1847 /** Given an array of double/uint64_t unions that are currently being used as
1848 * doubles, convert them to uint64_t, and try to scale them linearly so as to
1849 * much of the range of uint64_t. If <b>total_out</b> is provided, set it to
1850 * the sum of all elements in the array _before_ scaling. */
1852 scale_array_elements_to_u64(u64_dbl_t
*entries
, int n_entries
,
1853 uint64_t *total_out
)
1856 double scale_factor
;
1858 /* big, but far away from overflowing an int64_t */
1859 #define SCALE_TO_U64_MAX (INT64_MAX / 4)
1861 for (i
= 0; i
< n_entries
; ++i
)
1862 total
+= entries
[i
].dbl
;
1864 scale_factor
= SCALE_TO_U64_MAX
/ total
;
1866 for (i
= 0; i
< n_entries
; ++i
)
1867 entries
[i
].u64
= tor_llround(entries
[i
].dbl
* scale_factor
);
1870 *total_out
= (uint64_t) total
;
1872 #undef SCALE_TO_U64_MAX
1875 /** Time-invariant 64-bit greater-than; works on two integers in the range
1877 #if SIZEOF_VOID_P == 8
1878 #define gt_i64_timei(a,b) ((a) > (b))
1881 gt_i64_timei(uint64_t a
, uint64_t b
)
1883 int64_t diff
= (int64_t) (b
- a
);
1884 int res
= diff
>> 63;
1889 /** Pick a random element of <b>n_entries</b>-element array <b>entries</b>,
1890 * choosing each element with a probability proportional to its (uint64_t)
1891 * value, and return the index of that element. If all elements are 0, choose
1892 * an index at random. Return -1 on error.
1895 choose_array_element_by_weight(const u64_dbl_t
*entries
, int n_entries
)
1897 int i
, i_chosen
=-1, n_chosen
=0;
1898 uint64_t total_so_far
= 0;
1902 for (i
= 0; i
< n_entries
; ++i
)
1903 total
+= entries
[i
].u64
;
1909 return crypto_rand_int(n_entries
);
1911 tor_assert(total
< INT64_MAX
);
1913 rand_val
= crypto_rand_uint64(total
);
1915 for (i
= 0; i
< n_entries
; ++i
) {
1916 total_so_far
+= entries
[i
].u64
;
1917 if (gt_i64_timei(total_so_far
, rand_val
)) {
1920 /* Set rand_val to INT64_MAX rather than stopping the loop. This way,
1921 * the time we spend in the loop does not leak which element we chose. */
1922 rand_val
= INT64_MAX
;
1925 tor_assert(total_so_far
== total
);
1926 tor_assert(n_chosen
== 1);
1927 tor_assert(i_chosen
>= 0);
1928 tor_assert(i_chosen
< n_entries
);
1933 /** When weighting bridges, enforce these values as lower and upper
1934 * bound for believable bandwidth, because there is no way for us
1935 * to verify a bridge's bandwidth currently. */
1936 #define BRIDGE_MIN_BELIEVABLE_BANDWIDTH 20000 /* 20 kB/sec */
1937 #define BRIDGE_MAX_BELIEVABLE_BANDWIDTH 100000 /* 100 kB/sec */
1939 /** Return the smaller of the router's configured BandwidthRate
1940 * and its advertised capacity, making sure to stay within the
1941 * interval between bridge-min-believe-bw and
1942 * bridge-max-believe-bw. */
1944 bridge_get_advertised_bandwidth_bounded(routerinfo_t
*router
)
1946 uint32_t result
= router
->bandwidthcapacity
;
1947 if (result
> router
->bandwidthrate
)
1948 result
= router
->bandwidthrate
;
1949 if (result
> BRIDGE_MAX_BELIEVABLE_BANDWIDTH
)
1950 result
= BRIDGE_MAX_BELIEVABLE_BANDWIDTH
;
1951 else if (result
< BRIDGE_MIN_BELIEVABLE_BANDWIDTH
)
1952 result
= BRIDGE_MIN_BELIEVABLE_BANDWIDTH
;
1956 /** Return bw*1000, unless bw*1000 would overflow, in which case return
1958 static INLINE
int32_t
1959 kb_to_bytes(uint32_t bw
)
1961 return (bw
> (INT32_MAX
/1000)) ? INT32_MAX
: bw
*1000;
1964 /** Helper function:
1965 * choose a random element of smartlist <b>sl</b> of nodes, weighted by
1966 * the advertised bandwidth of each element using the consensus
1967 * bandwidth weights.
1969 * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
1970 * nodes' bandwidth equally regardless of their Exit status, since there may
1971 * be some in the list because they exit to obscure ports. If
1972 * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
1973 * exit-node's bandwidth less depending on the smallness of the fraction of
1974 * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
1975 * guard node: consider all guard's bandwidth equally. Otherwise, weight
1976 * guards proportionally less.
1978 static const node_t
*
1979 smartlist_choose_node_by_bandwidth_weights(const smartlist_t
*sl
,
1980 bandwidth_weight_rule_t rule
)
1982 u64_dbl_t
*bandwidths
=NULL
;
1984 if (compute_weighted_bandwidths(sl
, rule
, &bandwidths
) < 0)
1987 scale_array_elements_to_u64(bandwidths
, smartlist_len(sl
),
1988 &sl_last_total_weighted_bw
);
1991 int idx
= choose_array_element_by_weight(bandwidths
,
1993 tor_free(bandwidths
);
1994 return idx
< 0 ? NULL
: smartlist_get(sl
, idx
);
1998 /** Given a list of routers and a weighting rule as in
1999 * smartlist_choose_node_by_bandwidth_weights, compute weighted bandwidth
2000 * values for each node and store them in a freshly allocated
2001 * *<b>bandwidths_out</b> of the same length as <b>sl</b>, and holding results
2002 * as doubles. Return 0 on success, -1 on failure. */
2004 compute_weighted_bandwidths(const smartlist_t
*sl
,
2005 bandwidth_weight_rule_t rule
,
2006 u64_dbl_t
**bandwidths_out
)
2008 int64_t weight_scale
;
2009 double Wg
= -1, Wm
= -1, We
= -1, Wd
= -1;
2010 double Wgb
= -1, Wmb
= -1, Web
= -1, Wdb
= -1;
2011 uint64_t weighted_bw
= 0;
2012 u64_dbl_t
*bandwidths
;
2014 /* Can't choose exit and guard at same time */
2015 tor_assert(rule
== NO_WEIGHTING
||
2016 rule
== WEIGHT_FOR_EXIT
||
2017 rule
== WEIGHT_FOR_GUARD
||
2018 rule
== WEIGHT_FOR_MID
||
2019 rule
== WEIGHT_FOR_DIR
);
2021 if (smartlist_len(sl
) == 0) {
2023 "Empty routerlist passed in to consensus weight node "
2024 "selection for rule %s",
2025 bandwidth_weight_rule_to_string(rule
));
2029 weight_scale
= networkstatus_get_weight_scale_param(NULL
);
2031 if (rule
== WEIGHT_FOR_GUARD
) {
2032 Wg
= networkstatus_get_bw_weight(NULL
, "Wgg", -1);
2033 Wm
= networkstatus_get_bw_weight(NULL
, "Wgm", -1); /* Bridges */
2035 Wd
= networkstatus_get_bw_weight(NULL
, "Wgd", -1);
2037 Wgb
= networkstatus_get_bw_weight(NULL
, "Wgb", -1);
2038 Wmb
= networkstatus_get_bw_weight(NULL
, "Wmb", -1);
2039 Web
= networkstatus_get_bw_weight(NULL
, "Web", -1);
2040 Wdb
= networkstatus_get_bw_weight(NULL
, "Wdb", -1);
2041 } else if (rule
== WEIGHT_FOR_MID
) {
2042 Wg
= networkstatus_get_bw_weight(NULL
, "Wmg", -1);
2043 Wm
= networkstatus_get_bw_weight(NULL
, "Wmm", -1);
2044 We
= networkstatus_get_bw_weight(NULL
, "Wme", -1);
2045 Wd
= networkstatus_get_bw_weight(NULL
, "Wmd", -1);
2047 Wgb
= networkstatus_get_bw_weight(NULL
, "Wgb", -1);
2048 Wmb
= networkstatus_get_bw_weight(NULL
, "Wmb", -1);
2049 Web
= networkstatus_get_bw_weight(NULL
, "Web", -1);
2050 Wdb
= networkstatus_get_bw_weight(NULL
, "Wdb", -1);
2051 } else if (rule
== WEIGHT_FOR_EXIT
) {
2052 // Guards CAN be exits if they have weird exit policies
2053 // They are d then I guess...
2054 We
= networkstatus_get_bw_weight(NULL
, "Wee", -1);
2055 Wm
= networkstatus_get_bw_weight(NULL
, "Wem", -1); /* Odd exit policies */
2056 Wd
= networkstatus_get_bw_weight(NULL
, "Wed", -1);
2057 Wg
= networkstatus_get_bw_weight(NULL
, "Weg", -1); /* Odd exit policies */
2059 Wgb
= networkstatus_get_bw_weight(NULL
, "Wgb", -1);
2060 Wmb
= networkstatus_get_bw_weight(NULL
, "Wmb", -1);
2061 Web
= networkstatus_get_bw_weight(NULL
, "Web", -1);
2062 Wdb
= networkstatus_get_bw_weight(NULL
, "Wdb", -1);
2063 } else if (rule
== WEIGHT_FOR_DIR
) {
2064 We
= networkstatus_get_bw_weight(NULL
, "Wbe", -1);
2065 Wm
= networkstatus_get_bw_weight(NULL
, "Wbm", -1);
2066 Wd
= networkstatus_get_bw_weight(NULL
, "Wbd", -1);
2067 Wg
= networkstatus_get_bw_weight(NULL
, "Wbg", -1);
2069 Wgb
= Wmb
= Web
= Wdb
= weight_scale
;
2070 } else if (rule
== NO_WEIGHTING
) {
2071 Wg
= Wm
= We
= Wd
= weight_scale
;
2072 Wgb
= Wmb
= Web
= Wdb
= weight_scale
;
2075 if (Wg
< 0 || Wm
< 0 || We
< 0 || Wd
< 0 || Wgb
< 0 || Wmb
< 0 || Wdb
< 0
2078 "Got negative bandwidth weights. Defaulting to old selection"
2080 return -1; // Use old algorithm.
2088 Wgb
/= weight_scale
;
2089 Wmb
/= weight_scale
;
2090 Web
/= weight_scale
;
2091 Wdb
/= weight_scale
;
2093 bandwidths
= tor_malloc_zero(sizeof(u64_dbl_t
)*smartlist_len(sl
));
2095 // Cycle through smartlist and total the bandwidth.
2096 SMARTLIST_FOREACH_BEGIN(sl
, const node_t
*, node
) {
2097 int is_exit
= 0, is_guard
= 0, is_dir
= 0, this_bw
= 0, is_me
= 0;
2099 is_exit
= node
->is_exit
&& ! node
->is_bad_exit
;
2100 is_guard
= node
->is_possible_guard
;
2101 is_dir
= node_is_dir(node
);
2103 if (!node
->rs
->has_bandwidth
) {
2104 tor_free(bandwidths
);
2105 /* This should never happen, unless all the authorites downgrade
2106 * to 0.2.0 or rogue routerstatuses get inserted into our consensus. */
2108 "Consensus is not listing bandwidths. Defaulting back to "
2109 "old router selection algorithm.");
2112 this_bw
= kb_to_bytes(node
->rs
->bandwidth_kb
);
2113 } else if (node
->ri
) {
2114 /* bridge or other descriptor not in our consensus */
2115 this_bw
= bridge_get_advertised_bandwidth_bounded(node
->ri
);
2117 /* We can't use this one. */
2120 is_me
= router_digest_is_me(node
->identity
);
2122 if (is_guard
&& is_exit
) {
2123 weight
= (is_dir
? Wdb
*Wd
: Wd
);
2124 } else if (is_guard
) {
2125 weight
= (is_dir
? Wgb
*Wg
: Wg
);
2126 } else if (is_exit
) {
2127 weight
= (is_dir
? Web
*We
: We
);
2129 weight
= (is_dir
? Wmb
*Wm
: Wm
);
2131 /* These should be impossible; but overflows here would be bad, so let's
2138 bandwidths
[node_sl_idx
].dbl
= weight
*this_bw
+ 0.5;
2140 sl_last_weighted_bw_of_me
= (uint64_t) bandwidths
[node_sl_idx
].dbl
;
2141 } SMARTLIST_FOREACH_END(node
);
2143 log_debug(LD_CIRC
, "Generated weighted bandwidths for rule %s based "
2145 "Wg=%f Wm=%f We=%f Wd=%f with total bw "U64_FORMAT
,
2146 bandwidth_weight_rule_to_string(rule
),
2147 Wg
, Wm
, We
, Wd
, U64_PRINTF_ARG(weighted_bw
));
2149 *bandwidths_out
= bandwidths
;
2154 /** For all nodes in <b>sl</b>, return the fraction of those nodes, weighted
2155 * by their weighted bandwidths with rule <b>rule</b>, for which we have
2158 frac_nodes_with_descriptors(const smartlist_t
*sl
,
2159 bandwidth_weight_rule_t rule
)
2161 u64_dbl_t
*bandwidths
= NULL
;
2162 double total
, present
;
2164 if (smartlist_len(sl
) == 0)
2167 if (compute_weighted_bandwidths(sl
, rule
, &bandwidths
) < 0) {
2168 int n_with_descs
= 0;
2169 SMARTLIST_FOREACH(sl
, const node_t
*, node
, {
2170 if (node_has_descriptor(node
))
2173 return ((double)n_with_descs
) / (double)smartlist_len(sl
);
2176 total
= present
= 0.0;
2177 SMARTLIST_FOREACH_BEGIN(sl
, const node_t
*, node
) {
2178 const double bw
= bandwidths
[node_sl_idx
].dbl
;
2180 if (node_has_descriptor(node
))
2182 } SMARTLIST_FOREACH_END(node
);
2184 tor_free(bandwidths
);
2189 return present
/ total
;
2192 /** Helper function:
2193 * choose a random node_t element of smartlist <b>sl</b>, weighted by
2194 * the advertised bandwidth of each element.
2196 * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
2197 * nodes' bandwidth equally regardless of their Exit status, since there may
2198 * be some in the list because they exit to obscure ports. If
2199 * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
2200 * exit-node's bandwidth less depending on the smallness of the fraction of
2201 * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
2202 * guard node: consider all guard's bandwidth equally. Otherwise, weight
2203 * guards proportionally less.
2205 static const node_t
*
2206 smartlist_choose_node_by_bandwidth(const smartlist_t
*sl
,
2207 bandwidth_weight_rule_t rule
)
2210 u64_dbl_t
*bandwidths
;
2214 double total_nonexit_bw
= 0, total_exit_bw
= 0;
2215 double total_nonguard_bw
= 0, total_guard_bw
= 0;
2217 double guard_weight
;
2219 bitarray_t
*fast_bits
;
2220 bitarray_t
*exit_bits
;
2221 bitarray_t
*guard_bits
;
2224 // This function does not support WEIGHT_FOR_DIR
2225 // or WEIGHT_FOR_MID
2226 if (rule
== WEIGHT_FOR_DIR
|| rule
== WEIGHT_FOR_MID
) {
2227 rule
= NO_WEIGHTING
;
2230 /* Can't choose exit and guard at same time */
2231 tor_assert(rule
== NO_WEIGHTING
||
2232 rule
== WEIGHT_FOR_EXIT
||
2233 rule
== WEIGHT_FOR_GUARD
);
2235 if (smartlist_len(sl
) == 0) {
2237 "Empty routerlist passed in to old node selection for rule %s",
2238 bandwidth_weight_rule_to_string(rule
));
2242 /* First count the total bandwidth weight, and make a list
2243 * of each value. We use UINT64_MAX to indicate "unknown". */
2244 bandwidths
= tor_malloc_zero(sizeof(u64_dbl_t
)*smartlist_len(sl
));
2245 fast_bits
= bitarray_init_zero(smartlist_len(sl
));
2246 exit_bits
= bitarray_init_zero(smartlist_len(sl
));
2247 guard_bits
= bitarray_init_zero(smartlist_len(sl
));
2249 /* Iterate over all the routerinfo_t or routerstatus_t, and */
2250 SMARTLIST_FOREACH_BEGIN(sl
, const node_t
*, node
) {
2251 /* first, learn what bandwidth we think i has */
2253 uint32_t this_bw
= 0;
2256 if (router_digest_is_me(node
->identity
))
2257 me_idx
= node_sl_idx
;
2259 is_exit
= node
->is_exit
;
2260 is_guard
= node
->is_possible_guard
;
2262 if (node
->rs
->has_bandwidth
) {
2263 this_bw
= kb_to_bytes(node
->rs
->bandwidth_kb
);
2264 } else { /* guess */
2267 } else if (node
->ri
) {
2268 /* Must be a bridge if we're willing to use it */
2269 this_bw
= bridge_get_advertised_bandwidth_bounded(node
->ri
);
2273 bitarray_set(exit_bits
, i
);
2275 bitarray_set(guard_bits
, i
);
2277 bitarray_set(fast_bits
, i
);
2280 bandwidths
[i
].dbl
= this_bw
;
2282 total_guard_bw
+= this_bw
;
2284 total_nonguard_bw
+= this_bw
;
2286 total_exit_bw
+= this_bw
;
2288 total_nonexit_bw
+= this_bw
;
2291 bandwidths
[i
].dbl
= -1.0;
2293 } SMARTLIST_FOREACH_END(node
);
2297 /* Now, fill in the unknown values. */
2299 int32_t avg_fast
, avg_slow
;
2300 if (total_exit_bw
+total_nonexit_bw
< EPSILON
) {
2301 /* if there's some bandwidth, there's at least one known router,
2302 * so no worries about div by 0 here */
2303 int n_known
= smartlist_len(sl
)-n_unknown
;
2304 avg_fast
= avg_slow
= (int32_t)
2305 ((total_exit_bw
+total_nonexit_bw
)/((uint64_t) n_known
));
2310 for (i
=0; i
<(unsigned)smartlist_len(sl
); ++i
) {
2311 if (bandwidths
[i
].dbl
>= 0.0)
2313 is_fast
= bitarray_is_set(fast_bits
, i
);
2314 is_exit
= bitarray_is_set(exit_bits
, i
);
2315 is_guard
= bitarray_is_set(guard_bits
, i
);
2316 bandwidths
[i
].dbl
= is_fast
? avg_fast
: avg_slow
;
2318 total_exit_bw
+= bandwidths
[i
].dbl
;
2320 total_nonexit_bw
+= bandwidths
[i
].dbl
;
2322 total_guard_bw
+= bandwidths
[i
].dbl
;
2324 total_nonguard_bw
+= bandwidths
[i
].dbl
;
2328 /* If there's no bandwidth at all, pick at random. */
2329 if (total_exit_bw
+total_nonexit_bw
< EPSILON
) {
2330 tor_free(bandwidths
);
2331 tor_free(fast_bits
);
2332 tor_free(exit_bits
);
2333 tor_free(guard_bits
);
2334 return smartlist_choose(sl
);
2337 /* Figure out how to weight exits and guards */
2339 double all_bw
= U64_TO_DBL(total_exit_bw
+total_nonexit_bw
);
2340 double exit_bw
= U64_TO_DBL(total_exit_bw
);
2341 double guard_bw
= U64_TO_DBL(total_guard_bw
);
2343 * For detailed derivation of this formula, see
2344 * http://archives.seul.org/or/dev/Jul-2007/msg00056.html
2346 if (rule
== WEIGHT_FOR_EXIT
|| total_exit_bw
<EPSILON
)
2349 exit_weight
= 1.0 - all_bw
/(3.0*exit_bw
);
2351 if (rule
== WEIGHT_FOR_GUARD
|| total_guard_bw
<EPSILON
)
2354 guard_weight
= 1.0 - all_bw
/(3.0*guard_bw
);
2356 if (exit_weight
<= 0.0)
2359 if (guard_weight
<= 0.0)
2362 sl_last_weighted_bw_of_me
= 0;
2363 for (i
=0; i
< (unsigned)smartlist_len(sl
); i
++) {
2364 tor_assert(bandwidths
[i
].dbl
>= 0.0);
2366 is_exit
= bitarray_is_set(exit_bits
, i
);
2367 is_guard
= bitarray_is_set(guard_bits
, i
);
2368 if (is_exit
&& is_guard
)
2369 bandwidths
[i
].dbl
*= exit_weight
* guard_weight
;
2371 bandwidths
[i
].dbl
*= guard_weight
;
2373 bandwidths
[i
].dbl
*= exit_weight
;
2375 if (i
== (unsigned) me_idx
)
2376 sl_last_weighted_bw_of_me
= (uint64_t) bandwidths
[i
].dbl
;
2381 log_debug(LD_CIRC
, "Total weighted bw = "U64_FORMAT
2382 ", exit bw = "U64_FORMAT
2383 ", nonexit bw = "U64_FORMAT
", exit weight = %f "
2385 ", guard bw = "U64_FORMAT
2386 ", nonguard bw = "U64_FORMAT
", guard weight = %f "
2387 "(for guard == %d)",
2388 U64_PRINTF_ARG(total_bw
),
2389 U64_PRINTF_ARG(total_exit_bw
), U64_PRINTF_ARG(total_nonexit_bw
),
2390 exit_weight
, (int)(rule
== WEIGHT_FOR_EXIT
),
2391 U64_PRINTF_ARG(total_guard_bw
), U64_PRINTF_ARG(total_nonguard_bw
),
2392 guard_weight
, (int)(rule
== WEIGHT_FOR_GUARD
));
2395 scale_array_elements_to_u64(bandwidths
, smartlist_len(sl
),
2396 &sl_last_total_weighted_bw
);
2399 int idx
= choose_array_element_by_weight(bandwidths
,
2401 tor_free(bandwidths
);
2402 tor_free(fast_bits
);
2403 tor_free(exit_bits
);
2404 tor_free(guard_bits
);
2405 return idx
< 0 ? NULL
: smartlist_get(sl
, idx
);
2409 /** Choose a random element of status list <b>sl</b>, weighted by
2410 * the advertised bandwidth of each node */
2412 node_sl_choose_by_bandwidth(const smartlist_t
*sl
,
2413 bandwidth_weight_rule_t rule
)
2416 if ((ret
= smartlist_choose_node_by_bandwidth_weights(sl
, rule
))) {
2419 return smartlist_choose_node_by_bandwidth(sl
, rule
);
2423 /** Return a random running node from the nodelist. Never
2424 * pick a node that is in
2425 * <b>excludedsmartlist</b>, or which matches <b>excludedset</b>,
2426 * even if they are the only nodes available.
2427 * If <b>CRN_NEED_UPTIME</b> is set in flags and any router has more than
2428 * a minimum uptime, return one of those.
2429 * If <b>CRN_NEED_CAPACITY</b> is set in flags, weight your choice by the
2430 * advertised capacity of each router.
2431 * If <b>CRN_ALLOW_INVALID</b> is not set in flags, consider only Valid
2433 * If <b>CRN_NEED_GUARD</b> is set in flags, consider only Guard routers.
2434 * If <b>CRN_WEIGHT_AS_EXIT</b> is set in flags, we weight bandwidths as if
2435 * picking an exit node, otherwise we weight bandwidths for picking a relay
2436 * node (that is, possibly discounting exit nodes).
2437 * If <b>CRN_NEED_DESC</b> is set in flags, we only consider nodes that
2438 * have a routerinfo or microdescriptor -- that is, enough info to be
2439 * used to build a circuit.
2442 router_choose_random_node(smartlist_t
*excludedsmartlist
,
2443 routerset_t
*excludedset
,
2444 router_crn_flags_t flags
)
2446 const int need_uptime
= (flags
& CRN_NEED_UPTIME
) != 0;
2447 const int need_capacity
= (flags
& CRN_NEED_CAPACITY
) != 0;
2448 const int need_guard
= (flags
& CRN_NEED_GUARD
) != 0;
2449 const int allow_invalid
= (flags
& CRN_ALLOW_INVALID
) != 0;
2450 const int weight_for_exit
= (flags
& CRN_WEIGHT_AS_EXIT
) != 0;
2451 const int need_desc
= (flags
& CRN_NEED_DESC
) != 0;
2453 smartlist_t
*sl
=smartlist_new(),
2454 *excludednodes
=smartlist_new();
2455 const node_t
*choice
= NULL
;
2456 const routerinfo_t
*r
;
2457 bandwidth_weight_rule_t rule
;
2459 tor_assert(!(weight_for_exit
&& need_guard
));
2460 rule
= weight_for_exit
? WEIGHT_FOR_EXIT
:
2461 (need_guard
? WEIGHT_FOR_GUARD
: WEIGHT_FOR_MID
);
2463 /* Exclude relays that allow single hop exit circuits, if the user
2464 * wants to (such relays might be risky) */
2465 if (get_options()->ExcludeSingleHopRelays
) {
2466 SMARTLIST_FOREACH(nodelist_get_list(), node_t
*, node
,
2467 if (node_allows_single_hop_exits(node
)) {
2468 smartlist_add(excludednodes
, node
);
2472 if ((r
= routerlist_find_my_routerinfo()))
2473 routerlist_add_node_and_family(excludednodes
, r
);
2475 router_add_running_nodes_to_smartlist(sl
, allow_invalid
,
2476 need_uptime
, need_capacity
,
2477 need_guard
, need_desc
);
2478 smartlist_subtract(sl
,excludednodes
);
2479 if (excludedsmartlist
)
2480 smartlist_subtract(sl
,excludedsmartlist
);
2482 routerset_subtract_nodes(sl
,excludedset
);
2484 // Always weight by bandwidth
2485 choice
= node_sl_choose_by_bandwidth(sl
, rule
);
2488 if (!choice
&& (need_uptime
|| need_capacity
|| need_guard
)) {
2489 /* try once more -- recurse but with fewer restrictions. */
2491 "We couldn't find any live%s%s%s routers; falling back "
2492 "to list of all routers.",
2493 need_capacity
?", fast":"",
2494 need_uptime
?", stable":"",
2495 need_guard
?", guard":"");
2496 flags
&= ~ (CRN_NEED_UPTIME
|CRN_NEED_CAPACITY
|CRN_NEED_GUARD
);
2497 choice
= router_choose_random_node(
2498 excludedsmartlist
, excludedset
, flags
);
2500 smartlist_free(excludednodes
);
2503 "No available nodes when trying to choose node. Failing.");
2508 /** Helper: given an extended nickname in <b>hexdigest</b> try to decode it.
2509 * Return 0 on success, -1 on failure. Store the result into the
2510 * DIGEST_LEN-byte buffer at <b>digest_out</b>, the single character at
2511 * <b>nickname_qualifier_char_out</b>, and the MAXNICKNAME_LEN+1-byte buffer
2512 * at <b>nickname_out</b>.
2514 * The recognized format is:
2515 * HexName = Dollar? HexDigest NamePart?
2517 * HexDigest = HexChar*20
2518 * HexChar = 'a'..'f' | 'A'..'F' | '0'..'9'
2519 * NamePart = QualChar Name
2520 * QualChar = '=' | '~'
2521 * Name = NameChar*(1..MAX_NICKNAME_LEN)
2522 * NameChar = Any ASCII alphanumeric character
2525 hex_digest_nickname_decode(const char *hexdigest
,
2527 char *nickname_qualifier_char_out
,
2532 tor_assert(hexdigest
);
2533 if (hexdigest
[0] == '$')
2536 len
= strlen(hexdigest
);
2537 if (len
< HEX_DIGEST_LEN
) {
2539 } else if (len
> HEX_DIGEST_LEN
&& (hexdigest
[HEX_DIGEST_LEN
] == '=' ||
2540 hexdigest
[HEX_DIGEST_LEN
] == '~') &&
2541 len
<= HEX_DIGEST_LEN
+1+MAX_NICKNAME_LEN
) {
2542 *nickname_qualifier_char_out
= hexdigest
[HEX_DIGEST_LEN
];
2543 strlcpy(nickname_out
, hexdigest
+HEX_DIGEST_LEN
+1 , MAX_NICKNAME_LEN
+1);
2544 } else if (len
== HEX_DIGEST_LEN
) {
2550 if (base16_decode(digest_out
, DIGEST_LEN
, hexdigest
, HEX_DIGEST_LEN
)<0)
2555 /** Helper: Return true iff the <b>identity_digest</b> and <b>nickname</b>
2556 * combination of a router, encoded in hexadecimal, matches <b>hexdigest</b>
2557 * (which is optionally prefixed with a single dollar sign). Return false if
2558 * <b>hexdigest</b> is malformed, or it doesn't match. */
2560 hex_digest_nickname_matches(const char *hexdigest
, const char *identity_digest
,
2561 const char *nickname
, int is_named
)
2563 char digest
[DIGEST_LEN
];
2565 char nn_buf
[MAX_NICKNAME_LEN
+1];
2567 if (hex_digest_nickname_decode(hexdigest
, digest
, &nn_char
, nn_buf
) == -1)
2570 if (nn_char
== '=' || nn_char
== '~') {
2573 if (strcasecmp(nn_buf
, nickname
))
2575 if (nn_char
== '=' && !is_named
)
2579 return tor_memeq(digest
, identity_digest
, DIGEST_LEN
);
2582 /** Return true iff <b>router</b> is listed as named in the current
2585 router_is_named(const routerinfo_t
*router
)
2587 const char *digest
=
2588 networkstatus_get_router_digest_by_nickname(router
->nickname
);
2591 tor_memeq(digest
, router
->cache_info
.identity_digest
, DIGEST_LEN
));
2594 /** Return true iff <b>digest</b> is the digest of the identity key of a
2595 * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
2596 * is zero, any authority is okay. */
2598 router_digest_is_trusted_dir_type(const char *digest
, dirinfo_type_t type
)
2600 if (!trusted_dir_servers
)
2602 if (authdir_mode(get_options()) && router_digest_is_me(digest
))
2604 SMARTLIST_FOREACH(trusted_dir_servers
, dir_server_t
*, ent
,
2605 if (tor_memeq(digest
, ent
->digest
, DIGEST_LEN
)) {
2606 return (!type
) || ((type
& ent
->type
) != 0);
2611 /** Return true iff <b>addr</b> is the address of one of our trusted
2612 * directory authorities. */
2614 router_addr_is_trusted_dir(uint32_t addr
)
2616 if (!trusted_dir_servers
)
2618 SMARTLIST_FOREACH(trusted_dir_servers
, dir_server_t
*, ent
,
2619 if (ent
->addr
== addr
)
2625 /** If hexdigest is correctly formed, base16_decode it into
2626 * digest, which must have DIGEST_LEN space in it.
2627 * Return 0 on success, -1 on failure.
2630 hexdigest_to_digest(const char *hexdigest
, char *digest
)
2632 if (hexdigest
[0]=='$')
2634 if (strlen(hexdigest
) < HEX_DIGEST_LEN
||
2635 base16_decode(digest
,DIGEST_LEN
,hexdigest
,HEX_DIGEST_LEN
) < 0)
2640 /** As router_get_by_id_digest,but return a pointer that you're allowed to
2643 router_get_mutable_by_digest(const char *digest
)
2647 if (!routerlist
) return NULL
;
2649 // routerlist_assert_ok(routerlist);
2651 return rimap_get(routerlist
->identity_map
, digest
);
2654 /** Return the router in our routerlist whose 20-byte key digest
2655 * is <b>digest</b>. Return NULL if no such router is known. */
2656 const routerinfo_t
*
2657 router_get_by_id_digest(const char *digest
)
2659 return router_get_mutable_by_digest(digest
);
2662 /** Return the router in our routerlist whose 20-byte descriptor
2663 * is <b>digest</b>. Return NULL if no such router is known. */
2664 signed_descriptor_t
*
2665 router_get_by_descriptor_digest(const char *digest
)
2669 if (!routerlist
) return NULL
;
2671 return sdmap_get(routerlist
->desc_digest_map
, digest
);
2674 /** Return the signed descriptor for the router in our routerlist whose
2675 * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
2677 signed_descriptor_t
*
2678 router_get_by_extrainfo_digest(const char *digest
)
2682 if (!routerlist
) return NULL
;
2684 return sdmap_get(routerlist
->desc_by_eid_map
, digest
);
2687 /** Return the signed descriptor for the extrainfo_t in our routerlist whose
2688 * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
2689 * document is known. */
2690 signed_descriptor_t
*
2691 extrainfo_get_by_descriptor_digest(const char *digest
)
2695 if (!routerlist
) return NULL
;
2696 ei
= eimap_get(routerlist
->extra_info_map
, digest
);
2697 return ei
? &ei
->cache_info
: NULL
;
2700 /** Return a pointer to the signed textual representation of a descriptor.
2701 * The returned string is not guaranteed to be NUL-terminated: the string's
2702 * length will be in desc-\>signed_descriptor_len.
2704 * If <b>with_annotations</b> is set, the returned string will include
2706 * (if any) preceding the descriptor. This will increase the length of the
2707 * string by desc-\>annotations_len.
2709 * The caller must not free the string returned.
2712 signed_descriptor_get_body_impl(const signed_descriptor_t
*desc
,
2713 int with_annotations
)
2715 const char *r
= NULL
;
2716 size_t len
= desc
->signed_descriptor_len
;
2717 off_t offset
= desc
->saved_offset
;
2718 if (with_annotations
)
2719 len
+= desc
->annotations_len
;
2721 offset
+= desc
->annotations_len
;
2723 tor_assert(len
> 32);
2724 if (desc
->saved_location
== SAVED_IN_CACHE
&& routerlist
) {
2725 desc_store_t
*store
= desc_get_store(router_get_routerlist(), desc
);
2726 if (store
&& store
->mmap
) {
2727 tor_assert(desc
->saved_offset
+ len
<= store
->mmap
->size
);
2728 r
= store
->mmap
->data
+ offset
;
2730 log_err(LD_DIR
, "We couldn't read a descriptor that is supposedly "
2731 "mmaped in our cache. Is another process running in our data "
2732 "directory? Exiting.");
2736 if (!r
) /* no mmap, or not in cache. */
2737 r
= desc
->signed_descriptor_body
+
2738 (with_annotations
? 0 : desc
->annotations_len
);
2741 if (!with_annotations
) {
2742 if (fast_memcmp("router ", r
, 7) && fast_memcmp("extra-info ", r
, 11)) {
2743 char *cp
= tor_strndup(r
, 64);
2744 log_err(LD_DIR
, "descriptor at %p begins with unexpected string %s. "
2745 "Is another process running in our data directory? Exiting.",
2754 /** Return a pointer to the signed textual representation of a descriptor.
2755 * The returned string is not guaranteed to be NUL-terminated: the string's
2756 * length will be in desc-\>signed_descriptor_len.
2758 * The caller must not free the string returned.
2761 signed_descriptor_get_body(const signed_descriptor_t
*desc
)
2763 return signed_descriptor_get_body_impl(desc
, 0);
2766 /** As signed_descriptor_get_body(), but points to the beginning of the
2767 * annotations section rather than the beginning of the descriptor. */
2769 signed_descriptor_get_annotations(const signed_descriptor_t
*desc
)
2771 return signed_descriptor_get_body_impl(desc
, 1);
2774 /** Return the current list of all known routers. */
2776 router_get_routerlist(void)
2778 if (PREDICT_UNLIKELY(!routerlist
)) {
2779 routerlist
= tor_malloc_zero(sizeof(routerlist_t
));
2780 routerlist
->routers
= smartlist_new();
2781 routerlist
->old_routers
= smartlist_new();
2782 routerlist
->identity_map
= rimap_new();
2783 routerlist
->desc_digest_map
= sdmap_new();
2784 routerlist
->desc_by_eid_map
= sdmap_new();
2785 routerlist
->extra_info_map
= eimap_new();
2787 routerlist
->desc_store
.fname_base
= "cached-descriptors";
2788 routerlist
->desc_store
.fname_alt_base
= "cached-routers";
2789 routerlist
->extrainfo_store
.fname_base
= "cached-extrainfo";
2791 routerlist
->desc_store
.type
= ROUTER_STORE
;
2792 routerlist
->extrainfo_store
.type
= EXTRAINFO_STORE
;
2794 routerlist
->desc_store
.description
= "router descriptors";
2795 routerlist
->extrainfo_store
.description
= "extra-info documents";
2800 /** Free all storage held by <b>router</b>. */
2802 routerinfo_free(routerinfo_t
*router
)
2807 tor_free(router
->cache_info
.signed_descriptor_body
);
2808 tor_free(router
->address
);
2809 tor_free(router
->nickname
);
2810 tor_free(router
->platform
);
2811 tor_free(router
->contact_info
);
2812 if (router
->onion_pkey
)
2813 crypto_pk_free(router
->onion_pkey
);
2814 tor_free(router
->onion_curve25519_pkey
);
2815 if (router
->identity_pkey
)
2816 crypto_pk_free(router
->identity_pkey
);
2817 if (router
->declared_family
) {
2818 SMARTLIST_FOREACH(router
->declared_family
, char *, s
, tor_free(s
));
2819 smartlist_free(router
->declared_family
);
2821 addr_policy_list_free(router
->exit_policy
);
2822 short_policy_free(router
->ipv6_exit_policy
);
2824 memset(router
, 77, sizeof(routerinfo_t
));
2829 /** Release all storage held by <b>extrainfo</b> */
2831 extrainfo_free(extrainfo_t
*extrainfo
)
2835 tor_free(extrainfo
->cache_info
.signed_descriptor_body
);
2836 tor_free(extrainfo
->pending_sig
);
2838 memset(extrainfo
, 88, sizeof(extrainfo_t
)); /* debug bad memory usage */
2839 tor_free(extrainfo
);
2842 /** Release storage held by <b>sd</b>. */
2844 signed_descriptor_free(signed_descriptor_t
*sd
)
2849 tor_free(sd
->signed_descriptor_body
);
2851 memset(sd
, 99, sizeof(signed_descriptor_t
)); /* Debug bad mem usage */
2855 /** Extract a signed_descriptor_t from a general routerinfo, and free the
2858 static signed_descriptor_t
*
2859 signed_descriptor_from_routerinfo(routerinfo_t
*ri
)
2861 signed_descriptor_t
*sd
;
2862 tor_assert(ri
->purpose
== ROUTER_PURPOSE_GENERAL
);
2863 sd
= tor_malloc_zero(sizeof(signed_descriptor_t
));
2864 memcpy(sd
, &(ri
->cache_info
), sizeof(signed_descriptor_t
));
2865 sd
->routerlist_index
= -1;
2866 ri
->cache_info
.signed_descriptor_body
= NULL
;
2867 routerinfo_free(ri
);
2871 /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
2873 extrainfo_free_(void *e
)
2878 /** Free all storage held by a routerlist <b>rl</b>. */
2880 routerlist_free(routerlist_t
*rl
)
2884 rimap_free(rl
->identity_map
, NULL
);
2885 sdmap_free(rl
->desc_digest_map
, NULL
);
2886 sdmap_free(rl
->desc_by_eid_map
, NULL
);
2887 eimap_free(rl
->extra_info_map
, extrainfo_free_
);
2888 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
2889 routerinfo_free(r
));
2890 SMARTLIST_FOREACH(rl
->old_routers
, signed_descriptor_t
*, sd
,
2891 signed_descriptor_free(sd
));
2892 smartlist_free(rl
->routers
);
2893 smartlist_free(rl
->old_routers
);
2894 if (routerlist
->desc_store
.mmap
)
2895 tor_munmap_file(routerlist
->desc_store
.mmap
);
2896 if (routerlist
->extrainfo_store
.mmap
)
2897 tor_munmap_file(routerlist
->extrainfo_store
.mmap
);
2900 router_dir_info_changed();
2903 /** Log information about how much memory is being used for routerlist,
2904 * at log level <b>severity</b>. */
2906 dump_routerlist_mem_usage(int severity
)
2908 uint64_t livedescs
= 0;
2909 uint64_t olddescs
= 0;
2912 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, r
,
2913 livedescs
+= r
->cache_info
.signed_descriptor_len
);
2914 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
,
2915 olddescs
+= sd
->signed_descriptor_len
);
2917 tor_log(severity
, LD_DIR
,
2918 "In %d live descriptors: "U64_FORMAT
" bytes. "
2919 "In %d old descriptors: "U64_FORMAT
" bytes.",
2920 smartlist_len(routerlist
->routers
), U64_PRINTF_ARG(livedescs
),
2921 smartlist_len(routerlist
->old_routers
), U64_PRINTF_ARG(olddescs
));
2924 /** Debugging helper: If <b>idx</b> is nonnegative, assert that <b>ri</b> is
2925 * in <b>sl</b> at position <b>idx</b>. Otherwise, search <b>sl</b> for
2926 * <b>ri</b>. Return the index of <b>ri</b> in <b>sl</b>, or -1 if <b>ri</b>
2927 * is not in <b>sl</b>. */
2929 routerlist_find_elt_(smartlist_t
*sl
, void *ri
, int idx
)
2933 SMARTLIST_FOREACH(sl
, routerinfo_t
*, r
,
2939 tor_assert(idx
< smartlist_len(sl
));
2940 tor_assert(smartlist_get(sl
, idx
) == ri
);
2945 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
2946 * as needed. There must be no previous member of <b>rl</b> with the same
2947 * identity digest as <b>ri</b>: If there is, call routerlist_replace
2951 routerlist_insert(routerlist_t
*rl
, routerinfo_t
*ri
)
2953 routerinfo_t
*ri_old
;
2954 signed_descriptor_t
*sd_old
;
2956 const routerinfo_t
*ri_generated
= router_get_my_routerinfo();
2957 tor_assert(ri_generated
!= ri
);
2959 tor_assert(ri
->cache_info
.routerlist_index
== -1);
2961 ri_old
= rimap_set(rl
->identity_map
, ri
->cache_info
.identity_digest
, ri
);
2962 tor_assert(!ri_old
);
2964 sd_old
= sdmap_set(rl
->desc_digest_map
,
2965 ri
->cache_info
.signed_descriptor_digest
,
2968 int idx
= sd_old
->routerlist_index
;
2969 sd_old
->routerlist_index
= -1;
2970 smartlist_del(rl
->old_routers
, idx
);
2971 if (idx
< smartlist_len(rl
->old_routers
)) {
2972 signed_descriptor_t
*d
= smartlist_get(rl
->old_routers
, idx
);
2973 d
->routerlist_index
= idx
;
2975 rl
->desc_store
.bytes_dropped
+= sd_old
->signed_descriptor_len
;
2976 sdmap_remove(rl
->desc_by_eid_map
, sd_old
->extra_info_digest
);
2977 signed_descriptor_free(sd_old
);
2980 if (!tor_digest_is_zero(ri
->cache_info
.extra_info_digest
))
2981 sdmap_set(rl
->desc_by_eid_map
, ri
->cache_info
.extra_info_digest
,
2983 smartlist_add(rl
->routers
, ri
);
2984 ri
->cache_info
.routerlist_index
= smartlist_len(rl
->routers
) - 1;
2985 nodelist_set_routerinfo(ri
, NULL
);
2986 router_dir_info_changed();
2987 #ifdef DEBUG_ROUTERLIST
2988 routerlist_assert_ok(rl
);
2992 /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
2993 * corresponding router in rl-\>routers or rl-\>old_routers. Return true iff
2994 * we actually inserted <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
2996 extrainfo_insert(routerlist_t
*rl
, extrainfo_t
*ei
)
2999 routerinfo_t
*ri
= rimap_get(rl
->identity_map
,
3000 ei
->cache_info
.identity_digest
);
3001 signed_descriptor_t
*sd
=
3002 sdmap_get(rl
->desc_by_eid_map
, ei
->cache_info
.signed_descriptor_digest
);
3003 extrainfo_t
*ei_tmp
;
3006 extrainfo_t
*ei_generated
= router_get_my_extrainfo();
3007 tor_assert(ei_generated
!= ei
);
3011 /* This router is unknown; we can't even verify the signature. Give up.*/
3014 if (routerinfo_incompatible_with_extrainfo(ri
, ei
, sd
, NULL
)) {
3018 /* Okay, if we make it here, we definitely have a router corresponding to
3019 * this extrainfo. */
3021 ei_tmp
= eimap_set(rl
->extra_info_map
,
3022 ei
->cache_info
.signed_descriptor_digest
,
3026 rl
->extrainfo_store
.bytes_dropped
+=
3027 ei_tmp
->cache_info
.signed_descriptor_len
;
3028 extrainfo_free(ei_tmp
);
3035 #ifdef DEBUG_ROUTERLIST
3036 routerlist_assert_ok(rl
);
3041 #define should_cache_old_descriptors() \
3042 directory_caches_dir_info(get_options())
3044 /** If we're a directory cache and routerlist <b>rl</b> doesn't have
3045 * a copy of router <b>ri</b> yet, add it to the list of old (not
3046 * recommended but still served) descriptors. Else free it. */
3048 routerlist_insert_old(routerlist_t
*rl
, routerinfo_t
*ri
)
3051 const routerinfo_t
*ri_generated
= router_get_my_routerinfo();
3052 tor_assert(ri_generated
!= ri
);
3054 tor_assert(ri
->cache_info
.routerlist_index
== -1);
3056 if (should_cache_old_descriptors() &&
3057 ri
->purpose
== ROUTER_PURPOSE_GENERAL
&&
3058 !sdmap_get(rl
->desc_digest_map
,
3059 ri
->cache_info
.signed_descriptor_digest
)) {
3060 signed_descriptor_t
*sd
= signed_descriptor_from_routerinfo(ri
);
3061 sdmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
3062 smartlist_add(rl
->old_routers
, sd
);
3063 sd
->routerlist_index
= smartlist_len(rl
->old_routers
)-1;
3064 if (!tor_digest_is_zero(sd
->extra_info_digest
))
3065 sdmap_set(rl
->desc_by_eid_map
, sd
->extra_info_digest
, sd
);
3067 routerinfo_free(ri
);
3069 #ifdef DEBUG_ROUTERLIST
3070 routerlist_assert_ok(rl
);
3074 /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
3075 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl->routers,
3076 * idx) == ri, we don't need to do a linear search over the list to decide
3077 * which to remove. We fill the gap in rl->routers with a later element in
3078 * the list, if any exists. <b>ri</b> is freed.
3080 * If <b>make_old</b> is true, instead of deleting the router, we try adding
3081 * it to rl->old_routers. */
3083 routerlist_remove(routerlist_t
*rl
, routerinfo_t
*ri
, int make_old
, time_t now
)
3085 routerinfo_t
*ri_tmp
;
3086 extrainfo_t
*ei_tmp
;
3087 int idx
= ri
->cache_info
.routerlist_index
;
3088 tor_assert(0 <= idx
&& idx
< smartlist_len(rl
->routers
));
3089 tor_assert(smartlist_get(rl
->routers
, idx
) == ri
);
3091 nodelist_remove_routerinfo(ri
);
3093 /* make sure the rephist module knows that it's not running */
3094 rep_hist_note_router_unreachable(ri
->cache_info
.identity_digest
, now
);
3096 ri
->cache_info
.routerlist_index
= -1;
3097 smartlist_del(rl
->routers
, idx
);
3098 if (idx
< smartlist_len(rl
->routers
)) {
3099 routerinfo_t
*r
= smartlist_get(rl
->routers
, idx
);
3100 r
->cache_info
.routerlist_index
= idx
;
3103 ri_tmp
= rimap_remove(rl
->identity_map
, ri
->cache_info
.identity_digest
);
3104 router_dir_info_changed();
3105 tor_assert(ri_tmp
== ri
);
3107 if (make_old
&& should_cache_old_descriptors() &&
3108 ri
->purpose
== ROUTER_PURPOSE_GENERAL
) {
3109 signed_descriptor_t
*sd
;
3110 sd
= signed_descriptor_from_routerinfo(ri
);
3111 smartlist_add(rl
->old_routers
, sd
);
3112 sd
->routerlist_index
= smartlist_len(rl
->old_routers
)-1;
3113 sdmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
3114 if (!tor_digest_is_zero(sd
->extra_info_digest
))
3115 sdmap_set(rl
->desc_by_eid_map
, sd
->extra_info_digest
, sd
);
3117 signed_descriptor_t
*sd_tmp
;
3118 sd_tmp
= sdmap_remove(rl
->desc_digest_map
,
3119 ri
->cache_info
.signed_descriptor_digest
);
3120 tor_assert(sd_tmp
== &(ri
->cache_info
));
3121 rl
->desc_store
.bytes_dropped
+= ri
->cache_info
.signed_descriptor_len
;
3122 ei_tmp
= eimap_remove(rl
->extra_info_map
,
3123 ri
->cache_info
.extra_info_digest
);
3125 rl
->extrainfo_store
.bytes_dropped
+=
3126 ei_tmp
->cache_info
.signed_descriptor_len
;
3127 extrainfo_free(ei_tmp
);
3129 if (!tor_digest_is_zero(ri
->cache_info
.extra_info_digest
))
3130 sdmap_remove(rl
->desc_by_eid_map
, ri
->cache_info
.extra_info_digest
);
3131 routerinfo_free(ri
);
3133 #ifdef DEBUG_ROUTERLIST
3134 routerlist_assert_ok(rl
);
3138 /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
3139 * adjust <b>rl</b> as appropriate. <b>idx</b> is -1, or the index of
3142 routerlist_remove_old(routerlist_t
*rl
, signed_descriptor_t
*sd
, int idx
)
3144 signed_descriptor_t
*sd_tmp
;
3145 extrainfo_t
*ei_tmp
;
3146 desc_store_t
*store
;
3148 idx
= sd
->routerlist_index
;
3150 tor_assert(0 <= idx
&& idx
< smartlist_len(rl
->old_routers
));
3151 /* XXXX edmanm's bridge relay triggered the following assert while
3152 * running 0.2.0.12-alpha. If anybody triggers this again, see if we
3153 * can get a backtrace. */
3154 tor_assert(smartlist_get(rl
->old_routers
, idx
) == sd
);
3155 tor_assert(idx
== sd
->routerlist_index
);
3157 sd
->routerlist_index
= -1;
3158 smartlist_del(rl
->old_routers
, idx
);
3159 if (idx
< smartlist_len(rl
->old_routers
)) {
3160 signed_descriptor_t
*d
= smartlist_get(rl
->old_routers
, idx
);
3161 d
->routerlist_index
= idx
;
3163 sd_tmp
= sdmap_remove(rl
->desc_digest_map
,
3164 sd
->signed_descriptor_digest
);
3165 tor_assert(sd_tmp
== sd
);
3166 store
= desc_get_store(rl
, sd
);
3168 store
->bytes_dropped
+= sd
->signed_descriptor_len
;
3170 ei_tmp
= eimap_remove(rl
->extra_info_map
,
3171 sd
->extra_info_digest
);
3173 rl
->extrainfo_store
.bytes_dropped
+=
3174 ei_tmp
->cache_info
.signed_descriptor_len
;
3175 extrainfo_free(ei_tmp
);
3177 if (!tor_digest_is_zero(sd
->extra_info_digest
))
3178 sdmap_remove(rl
->desc_by_eid_map
, sd
->extra_info_digest
);
3180 signed_descriptor_free(sd
);
3181 #ifdef DEBUG_ROUTERLIST
3182 routerlist_assert_ok(rl
);
3186 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
3187 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
3188 * smartlist_get(rl->routers, idx) == ri, we don't need to do a linear
3189 * search over the list to decide which to remove. We put ri_new in the same
3190 * index as ri_old, if possible. ri is freed as appropriate.
3192 * If should_cache_descriptors() is true, instead of deleting the router,
3193 * we add it to rl->old_routers. */
3195 routerlist_replace(routerlist_t
*rl
, routerinfo_t
*ri_old
,
3196 routerinfo_t
*ri_new
)
3199 int same_descriptors
;
3201 routerinfo_t
*ri_tmp
;
3202 extrainfo_t
*ei_tmp
;
3204 const routerinfo_t
*ri_generated
= router_get_my_routerinfo();
3205 tor_assert(ri_generated
!= ri_new
);
3207 tor_assert(ri_old
!= ri_new
);
3208 tor_assert(ri_new
->cache_info
.routerlist_index
== -1);
3210 idx
= ri_old
->cache_info
.routerlist_index
;
3211 tor_assert(0 <= idx
&& idx
< smartlist_len(rl
->routers
));
3212 tor_assert(smartlist_get(rl
->routers
, idx
) == ri_old
);
3215 routerinfo_t
*ri_old_tmp
=NULL
;
3216 nodelist_set_routerinfo(ri_new
, &ri_old_tmp
);
3217 tor_assert(ri_old
== ri_old_tmp
);
3220 router_dir_info_changed();
3222 smartlist_set(rl
->routers
, idx
, ri_new
);
3223 ri_old
->cache_info
.routerlist_index
= -1;
3224 ri_new
->cache_info
.routerlist_index
= idx
;
3225 /* Check that ri_old is not in rl->routers anymore: */
3226 tor_assert( routerlist_find_elt_(rl
->routers
, ri_old
, -1) == -1 );
3228 log_warn(LD_BUG
, "Appending entry from routerlist_replace.");
3229 routerlist_insert(rl
, ri_new
);
3232 if (tor_memneq(ri_old
->cache_info
.identity_digest
,
3233 ri_new
->cache_info
.identity_digest
, DIGEST_LEN
)) {
3234 /* digests don't match; digestmap_set won't replace */
3235 rimap_remove(rl
->identity_map
, ri_old
->cache_info
.identity_digest
);
3237 ri_tmp
= rimap_set(rl
->identity_map
,
3238 ri_new
->cache_info
.identity_digest
, ri_new
);
3239 tor_assert(!ri_tmp
|| ri_tmp
== ri_old
);
3240 sdmap_set(rl
->desc_digest_map
,
3241 ri_new
->cache_info
.signed_descriptor_digest
,
3242 &(ri_new
->cache_info
));
3244 if (!tor_digest_is_zero(ri_new
->cache_info
.extra_info_digest
)) {
3245 sdmap_set(rl
->desc_by_eid_map
, ri_new
->cache_info
.extra_info_digest
,
3246 &ri_new
->cache_info
);
3249 same_descriptors
= tor_memeq(ri_old
->cache_info
.signed_descriptor_digest
,
3250 ri_new
->cache_info
.signed_descriptor_digest
,
3253 if (should_cache_old_descriptors() &&
3254 ri_old
->purpose
== ROUTER_PURPOSE_GENERAL
&&
3255 !same_descriptors
) {
3256 /* ri_old is going to become a signed_descriptor_t and go into
3258 signed_descriptor_t
*sd
= signed_descriptor_from_routerinfo(ri_old
);
3259 smartlist_add(rl
->old_routers
, sd
);
3260 sd
->routerlist_index
= smartlist_len(rl
->old_routers
)-1;
3261 sdmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
3262 if (!tor_digest_is_zero(sd
->extra_info_digest
))
3263 sdmap_set(rl
->desc_by_eid_map
, sd
->extra_info_digest
, sd
);
3265 /* We're dropping ri_old. */
3266 if (!same_descriptors
) {
3267 /* digests don't match; The sdmap_set above didn't replace */
3268 sdmap_remove(rl
->desc_digest_map
,
3269 ri_old
->cache_info
.signed_descriptor_digest
);
3271 if (tor_memneq(ri_old
->cache_info
.extra_info_digest
,
3272 ri_new
->cache_info
.extra_info_digest
, DIGEST_LEN
)) {
3273 ei_tmp
= eimap_remove(rl
->extra_info_map
,
3274 ri_old
->cache_info
.extra_info_digest
);
3276 rl
->extrainfo_store
.bytes_dropped
+=
3277 ei_tmp
->cache_info
.signed_descriptor_len
;
3278 extrainfo_free(ei_tmp
);
3282 if (!tor_digest_is_zero(ri_old
->cache_info
.extra_info_digest
)) {
3283 sdmap_remove(rl
->desc_by_eid_map
,
3284 ri_old
->cache_info
.extra_info_digest
);
3287 rl
->desc_store
.bytes_dropped
+= ri_old
->cache_info
.signed_descriptor_len
;
3288 routerinfo_free(ri_old
);
3290 #ifdef DEBUG_ROUTERLIST
3291 routerlist_assert_ok(rl
);
3295 /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
3296 * it as a fresh routerinfo_t. */
3297 static routerinfo_t
*
3298 routerlist_reparse_old(routerlist_t
*rl
, signed_descriptor_t
*sd
)
3303 body
= signed_descriptor_get_annotations(sd
);
3305 ri
= router_parse_entry_from_string(body
,
3306 body
+sd
->signed_descriptor_len
+sd
->annotations_len
,
3310 memcpy(&ri
->cache_info
, sd
, sizeof(signed_descriptor_t
));
3311 sd
->signed_descriptor_body
= NULL
; /* Steal reference. */
3312 ri
->cache_info
.routerlist_index
= -1;
3314 routerlist_remove_old(rl
, sd
, -1);
3319 /** Free all memory held by the routerlist module. */
3321 routerlist_free_all(void)
3323 routerlist_free(routerlist
);
3325 if (warned_nicknames
) {
3326 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
3327 smartlist_free(warned_nicknames
);
3328 warned_nicknames
= NULL
;
3330 clear_dir_servers();
3331 smartlist_free(trusted_dir_servers
);
3332 smartlist_free(fallback_dir_servers
);
3333 trusted_dir_servers
= fallback_dir_servers
= NULL
;
3334 if (trusted_dir_certs
) {
3335 digestmap_free(trusted_dir_certs
, cert_list_free_
);
3336 trusted_dir_certs
= NULL
;
3340 /** Forget that we have issued any router-related warnings, so that we'll
3341 * warn again if we see the same errors. */
3343 routerlist_reset_warnings(void)
3345 if (!warned_nicknames
)
3346 warned_nicknames
= smartlist_new();
3347 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
3348 smartlist_clear(warned_nicknames
); /* now the list is empty. */
3350 networkstatus_reset_warnings();
3353 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
3354 * older entries (if any) with the same key. Note: Callers should not hold
3355 * their pointers to <b>router</b> if this function fails; <b>router</b>
3356 * will either be inserted into the routerlist or freed. Similarly, even
3357 * if this call succeeds, they should not hold their pointers to
3358 * <b>router</b> after subsequent calls with other routerinfo's -- they
3359 * might cause the original routerinfo to get freed.
3361 * Returns the status for the operation. Might set *<b>msg</b> if it wants
3362 * the poster of the router to know something.
3364 * If <b>from_cache</b>, this descriptor came from our disk cache. If
3365 * <b>from_fetch</b>, we received it in response to a request we made.
3366 * (If both are false, that means it was uploaded to us as an auth dir
3367 * server or via the controller.)
3369 * This function should be called *after*
3370 * routers_update_status_from_consensus_networkstatus; subsequently, you
3371 * should call router_rebuild_store and routerlist_descriptors_added.
3374 router_add_to_routerlist(routerinfo_t
*router
, const char **msg
,
3375 int from_cache
, int from_fetch
)
3377 const char *id_digest
;
3378 const or_options_t
*options
= get_options();
3379 int authdir
= authdir_mode_handles_descs(options
, router
->purpose
);
3380 int authdir_believes_valid
= 0;
3381 routerinfo_t
*old_router
;
3382 networkstatus_t
*consensus
=
3383 networkstatus_get_latest_consensus_by_flavor(FLAV_NS
);
3384 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
3385 int in_consensus
= 0;
3390 router_get_routerlist();
3392 id_digest
= router
->cache_info
.identity_digest
;
3394 old_router
= router_get_mutable_by_digest(id_digest
);
3396 /* Make sure that we haven't already got this exact descriptor. */
3397 if (sdmap_get(routerlist
->desc_digest_map
,
3398 router
->cache_info
.signed_descriptor_digest
)) {
3399 /* If we have this descriptor already and the new descriptor is a bridge
3400 * descriptor, replace it. If we had a bridge descriptor before and the
3401 * new one is not a bridge descriptor, don't replace it. */
3403 /* Only members of routerlist->identity_map can be bridges; we don't
3404 * put bridges in old_routers. */
3405 const int was_bridge
= old_router
&&
3406 old_router
->purpose
== ROUTER_PURPOSE_BRIDGE
;
3408 if (routerinfo_is_a_configured_bridge(router
) &&
3409 router
->purpose
== ROUTER_PURPOSE_BRIDGE
&&
3411 log_info(LD_DIR
, "Replacing non-bridge descriptor with bridge "
3412 "descriptor for router %s",
3413 router_describe(router
));
3416 "Dropping descriptor that we already have for router %s",
3417 router_describe(router
));
3418 *msg
= "Router descriptor was not new.";
3419 routerinfo_free(router
);
3420 return ROUTER_WAS_NOT_NEW
;
3425 if (authdir_wants_to_reject_router(router
, msg
,
3426 !from_cache
&& !from_fetch
,
3427 &authdir_believes_valid
)) {
3429 routerinfo_free(router
);
3430 return ROUTER_AUTHDIR_REJECTS
;
3432 } else if (from_fetch
) {
3433 /* Only check the descriptor digest against the network statuses when
3434 * we are receiving in response to a fetch. */
3436 if (!signed_desc_digest_is_recognized(&router
->cache_info
) &&
3437 !routerinfo_is_a_configured_bridge(router
)) {
3438 /* We asked for it, so some networkstatus must have listed it when we
3439 * did. Save it if we're a cache in case somebody else asks for it. */
3441 "Received a no-longer-recognized descriptor for router %s",
3442 router_describe(router
));
3443 *msg
= "Router descriptor is not referenced by any network-status.";
3445 /* Only journal this desc if we'll be serving it. */
3446 if (!from_cache
&& should_cache_old_descriptors())
3447 signed_desc_append_to_journal(&router
->cache_info
,
3448 &routerlist
->desc_store
);
3449 routerlist_insert_old(routerlist
, router
);
3450 return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS
;
3454 /* We no longer need a router with this descriptor digest. */
3455 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
3457 routerstatus_t
*rs
=
3458 networkstatus_v2_find_mutable_entry(ns
, id_digest
);
3459 if (rs
&& tor_memeq(rs
->descriptor_digest
,
3460 router
->cache_info
.signed_descriptor_digest
,
3462 rs
->need_to_mirror
= 0;
3465 routerstatus_t
*rs
= networkstatus_vote_find_mutable_entry(
3466 consensus
, id_digest
);
3467 if (rs
&& tor_memeq(rs
->descriptor_digest
,
3468 router
->cache_info
.signed_descriptor_digest
,
3471 rs
->need_to_mirror
= 0;
3475 if (router
->purpose
== ROUTER_PURPOSE_GENERAL
&&
3476 consensus
&& !in_consensus
&& !authdir
) {
3477 /* If it's a general router not listed in the consensus, then don't
3478 * consider replacing the latest router with it. */
3479 if (!from_cache
&& should_cache_old_descriptors())
3480 signed_desc_append_to_journal(&router
->cache_info
,
3481 &routerlist
->desc_store
);
3482 routerlist_insert_old(routerlist
, router
);
3483 *msg
= "Skipping router descriptor: not in consensus.";
3484 return ROUTER_NOT_IN_CONSENSUS
;
3487 /* If we're reading a bridge descriptor from our cache, and we don't
3488 * recognize it as one of our currently configured bridges, drop the
3489 * descriptor. Otherwise we could end up using it as one of our entry
3490 * guards even if it isn't in our Bridge config lines. */
3491 if (router
->purpose
== ROUTER_PURPOSE_BRIDGE
&& from_cache
&&
3492 !authdir_mode_bridge(options
) &&
3493 !routerinfo_is_a_configured_bridge(router
)) {
3494 log_info(LD_DIR
, "Dropping bridge descriptor for %s because we have "
3495 "no bridge configured at that address.",
3496 safe_str_client(router_describe(router
)));
3497 *msg
= "Router descriptor was not a configured bridge.";
3498 routerinfo_free(router
);
3499 return ROUTER_WAS_NOT_WANTED
;
3502 /* If we have a router with the same identity key, choose the newer one. */
3504 if (!in_consensus
&& (router
->cache_info
.published_on
<=
3505 old_router
->cache_info
.published_on
)) {
3506 /* Same key, but old. This one is not listed in the consensus. */
3507 log_debug(LD_DIR
, "Not-new descriptor for router %s",
3508 router_describe(router
));
3509 /* Only journal this desc if we'll be serving it. */
3510 if (!from_cache
&& should_cache_old_descriptors())
3511 signed_desc_append_to_journal(&router
->cache_info
,
3512 &routerlist
->desc_store
);
3513 routerlist_insert_old(routerlist
, router
);
3514 *msg
= "Router descriptor was not new.";
3515 return ROUTER_WAS_NOT_NEW
;
3517 /* Same key, and either new, or listed in the consensus. */
3518 log_debug(LD_DIR
, "Replacing entry for router %s",
3519 router_describe(router
));
3520 routerlist_replace(routerlist
, old_router
, router
);
3522 signed_desc_append_to_journal(&router
->cache_info
,
3523 &routerlist
->desc_store
);
3525 directory_set_dirty();
3526 *msg
= authdir_believes_valid
? "Valid server updated" :
3527 ("Invalid server updated. (This dirserver is marking your "
3528 "server as unapproved.)");
3529 return ROUTER_ADDED_SUCCESSFULLY
;
3533 if (!in_consensus
&& from_cache
&&
3534 router
->cache_info
.published_on
< time(NULL
) - OLD_ROUTER_DESC_MAX_AGE
) {
3535 *msg
= "Router descriptor was really old.";
3536 routerinfo_free(router
);
3537 return ROUTER_WAS_NOT_NEW
;
3540 /* We haven't seen a router with this identity before. Add it to the end of
3542 routerlist_insert(routerlist
, router
);
3544 signed_desc_append_to_journal(&router
->cache_info
,
3545 &routerlist
->desc_store
);
3547 directory_set_dirty();
3548 return ROUTER_ADDED_SUCCESSFULLY
;
3551 /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
3552 * as for router_add_to_routerlist(). Return ROUTER_ADDED_SUCCESSFULLY iff
3553 * we actually inserted it, ROUTER_BAD_EI otherwise.
3556 router_add_extrainfo_to_routerlist(extrainfo_t
*ei
, const char **msg
,
3557 int from_cache
, int from_fetch
)
3561 if (msg
) *msg
= NULL
;
3562 /*XXXX023 Do something with msg */
3564 inserted
= extrainfo_insert(router_get_routerlist(), ei
);
3566 if (inserted
&& !from_cache
)
3567 signed_desc_append_to_journal(&ei
->cache_info
,
3568 &routerlist
->extrainfo_store
);
3571 return ROUTER_ADDED_SUCCESSFULLY
;
3573 return ROUTER_BAD_EI
;
3576 /** Sorting helper: return <0, 0, or >0 depending on whether the
3577 * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
3578 * to, or later than that of *<b>b</b>. */
3580 compare_old_routers_by_identity_(const void **_a
, const void **_b
)
3583 const signed_descriptor_t
*r1
= *_a
, *r2
= *_b
;
3584 if ((i
= fast_memcmp(r1
->identity_digest
, r2
->identity_digest
, DIGEST_LEN
)))
3586 return (int)(r1
->published_on
- r2
->published_on
);
3589 /** Internal type used to represent how long an old descriptor was valid,
3590 * where it appeared in the list of old descriptors, and whether it's extra
3591 * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
3592 struct duration_idx_t
{
3598 /** Sorting helper: compare two duration_idx_t by their duration. */
3600 compare_duration_idx_(const void *_d1
, const void *_d2
)
3602 const struct duration_idx_t
*d1
= _d1
;
3603 const struct duration_idx_t
*d2
= _d2
;
3604 return d1
->duration
- d2
->duration
;
3607 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
3608 * must contain routerinfo_t with the same identity and with publication time
3609 * in ascending order. Remove members from this range until there are no more
3610 * than max_descriptors_per_router() remaining. Start by removing the oldest
3611 * members from before <b>cutoff</b>, then remove members which were current
3612 * for the lowest amount of time. The order of members of old_routers at
3613 * indices <b>lo</b> or higher may be changed.
3616 routerlist_remove_old_cached_routers_with_id(time_t now
,
3617 time_t cutoff
, int lo
, int hi
,
3618 digestset_t
*retain
)
3621 unsigned n_extra
, n_rmv
= 0;
3622 struct duration_idx_t
*lifespans
;
3623 uint8_t *rmv
, *must_keep
;
3624 smartlist_t
*lst
= routerlist
->old_routers
;
3627 tor_assert(hi
< smartlist_len(lst
));
3628 tor_assert(lo
<= hi
);
3629 ident
= ((signed_descriptor_t
*)smartlist_get(lst
, lo
))->identity_digest
;
3630 for (i
= lo
+1; i
<= hi
; ++i
) {
3631 signed_descriptor_t
*r
= smartlist_get(lst
, i
);
3632 tor_assert(tor_memeq(ident
, r
->identity_digest
, DIGEST_LEN
));
3635 /* Check whether we need to do anything at all. */
3637 int mdpr
= directory_caches_dir_info(get_options()) ? 2 : 1;
3643 lifespans
= tor_malloc_zero(sizeof(struct duration_idx_t
)*n
);
3644 rmv
= tor_malloc_zero(sizeof(uint8_t)*n
);
3645 must_keep
= tor_malloc_zero(sizeof(uint8_t)*n
);
3646 /* Set lifespans to contain the lifespan and index of each server. */
3647 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
3648 for (i
= lo
; i
<= hi
; ++i
) {
3649 signed_descriptor_t
*r
= smartlist_get(lst
, i
);
3650 signed_descriptor_t
*r_next
;
3651 lifespans
[i
-lo
].idx
= i
;
3652 if (r
->last_listed_as_valid_until
>= now
||
3653 (retain
&& digestset_contains(retain
, r
->signed_descriptor_digest
))) {
3654 must_keep
[i
-lo
] = 1;
3657 r_next
= smartlist_get(lst
, i
+1);
3658 tor_assert(r
->published_on
<= r_next
->published_on
);
3659 lifespans
[i
-lo
].duration
= (int)(r_next
->published_on
- r
->published_on
);
3662 lifespans
[i
-lo
].duration
= INT_MAX
;
3664 if (!must_keep
[i
-lo
] && r
->published_on
< cutoff
&& n_rmv
< n_extra
) {
3666 lifespans
[i
-lo
].old
= 1;
3671 if (n_rmv
< n_extra
) {
3673 * We aren't removing enough servers for being old. Sort lifespans by
3674 * the duration of liveness, and remove the ones we're not already going to
3675 * remove based on how long they were alive.
3677 qsort(lifespans
, n
, sizeof(struct duration_idx_t
), compare_duration_idx_
);
3678 for (i
= 0; i
< n
&& n_rmv
< n_extra
; ++i
) {
3679 if (!must_keep
[lifespans
[i
].idx
-lo
] && !lifespans
[i
].old
) {
3680 rmv
[lifespans
[i
].idx
-lo
] = 1;
3689 routerlist_remove_old(routerlist
, smartlist_get(lst
, i
), i
);
3690 } while (--i
>= lo
);
3691 tor_free(must_keep
);
3693 tor_free(lifespans
);
3696 /** Deactivate any routers from the routerlist that are more than
3697 * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
3698 * remove old routers from the list of cached routers if we have too many.
3701 routerlist_remove_old_routers(void)
3704 const char *cur_id
= NULL
;
3705 time_t now
= time(NULL
);
3707 routerinfo_t
*router
;
3708 signed_descriptor_t
*sd
;
3709 digestset_t
*retain
;
3710 int caches
= directory_caches_dir_info(get_options());
3711 const networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
3712 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
3714 const or_options_t
*options
= get_options();
3716 trusted_dirs_remove_old_certs();
3718 if (!routerlist
|| !consensus
)
3721 // routerlist_assert_ok(routerlist);
3723 /* We need to guess how many router descriptors we will wind up wanting to
3724 retain, so that we can be sure to allocate a large enough Bloom filter
3725 to hold the digest set. Overestimating is fine; underestimating is bad.
3728 /* We'll probably retain everything in the consensus. */
3729 int n_max_retain
= smartlist_len(consensus
->routerstatus_list
);
3730 if (caches
&& networkstatus_v2_list
) {
3731 /* If we care about v2 statuses, we'll retain at most as many as are
3732 listed any of the v2 statues. This will be at least the length of
3733 the largest v2 networkstatus, and in the worst case, this set will be
3734 equal to the sum of the lengths of all v2 consensuses. Take the
3737 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
3738 n_max_retain
+= smartlist_len(ns
->entries
));
3740 retain
= digestset_new(n_max_retain
);
3743 cutoff
= now
- OLD_ROUTER_DESC_MAX_AGE
;
3744 /* Build a list of all the descriptors that _anybody_ lists. */
3745 if (caches
&& networkstatus_v2_list
) {
3746 SMARTLIST_FOREACH_BEGIN(networkstatus_v2_list
, networkstatus_v2_t
*, ns
) {
3747 /* XXXX The inner loop here gets pretty expensive, and actually shows up
3748 * on some profiles. It may be the reason digestmap_set shows up in
3749 * profiles too. If instead we kept a per-descriptor digest count of
3750 * how many networkstatuses recommended each descriptor, and changed
3751 * that only when the networkstatuses changed, that would be a speed
3752 * improvement, possibly 1-4% if it also removes digestmap_set from the
3753 * profile. Not worth it for 0.1.2.x, though. The new directory
3754 * system will obsolete this whole thing in 0.2.0.x. */
3755 SMARTLIST_FOREACH_BEGIN(ns
->entries
, routerstatus_t
*, rs
) {
3756 if (rs
->published_on
>= cutoff
)
3757 digestset_add(retain
, rs
->descriptor_digest
);
3758 } SMARTLIST_FOREACH_END(rs
);
3759 } SMARTLIST_FOREACH_END(ns
);
3762 /* Retain anything listed in the consensus. */
3764 SMARTLIST_FOREACH(consensus
->routerstatus_list
, routerstatus_t
*, rs
,
3765 if (rs
->published_on
>= cutoff
)
3766 digestset_add(retain
, rs
->descriptor_digest
));
3769 /* If we have a consensus, and nearly as many v2 networkstatuses as we want,
3770 * we should consider pruning current routers that are too old and that
3771 * nobody recommends. (If we don't have a consensus or enough v2
3772 * networkstatuses, then we should get more before we decide to kill
3774 /* we set this to true iff we don't care about v2 info, or we have enough. */
3775 have_enough_v2
= !caches
||
3776 !(authdir_mode_any_main(options
) || options
->FetchV2Networkstatus
) ||
3777 (networkstatus_v2_list
&&
3778 smartlist_len(networkstatus_v2_list
) > get_n_v2_authorities() / 2);
3780 if (have_enough_v2
&& consensus
) {
3781 cutoff
= now
- ROUTER_MAX_AGE
;
3782 /* Remove too-old unrecommended members of routerlist->routers. */
3783 for (i
= 0; i
< smartlist_len(routerlist
->routers
); ++i
) {
3784 router
= smartlist_get(routerlist
->routers
, i
);
3785 if (router
->cache_info
.published_on
<= cutoff
&&
3786 router
->cache_info
.last_listed_as_valid_until
< now
&&
3787 !digestset_contains(retain
,
3788 router
->cache_info
.signed_descriptor_digest
)) {
3789 /* Too old: remove it. (If we're a cache, just move it into
3792 "Forgetting obsolete (too old) routerinfo for router %s",
3793 router_describe(router
));
3794 routerlist_remove(routerlist
, router
, 1, now
);
3800 //routerlist_assert_ok(routerlist);
3802 /* Remove far-too-old members of routerlist->old_routers. */
3803 cutoff
= now
- OLD_ROUTER_DESC_MAX_AGE
;
3804 for (i
= 0; i
< smartlist_len(routerlist
->old_routers
); ++i
) {
3805 sd
= smartlist_get(routerlist
->old_routers
, i
);
3806 if (sd
->published_on
<= cutoff
&&
3807 sd
->last_listed_as_valid_until
< now
&&
3808 !digestset_contains(retain
, sd
->signed_descriptor_digest
)) {
3809 /* Too old. Remove it. */
3810 routerlist_remove_old(routerlist
, sd
, i
--);
3814 //routerlist_assert_ok(routerlist);
3816 log_info(LD_DIR
, "We have %d live routers and %d old router descriptors.",
3817 smartlist_len(routerlist
->routers
),
3818 smartlist_len(routerlist
->old_routers
));
3820 /* Now we might have to look at routerlist->old_routers for extraneous
3821 * members. (We'd keep all the members if we could, but we need to save
3822 * space.) First, check whether we have too many router descriptors, total.
3823 * We're okay with having too many for some given router, so long as the
3824 * total number doesn't approach max_descriptors_per_router()*len(router).
3826 if (smartlist_len(routerlist
->old_routers
) <
3827 smartlist_len(routerlist
->routers
))
3830 /* Sort by identity, then fix indices. */
3831 smartlist_sort(routerlist
->old_routers
, compare_old_routers_by_identity_
);
3833 for (i
= 0; i
< smartlist_len(routerlist
->old_routers
); ++i
) {
3834 signed_descriptor_t
*r
= smartlist_get(routerlist
->old_routers
, i
);
3835 r
->routerlist_index
= i
;
3838 /* Iterate through the list from back to front, so when we remove descriptors
3839 * we don't mess up groups we haven't gotten to. */
3840 for (i
= smartlist_len(routerlist
->old_routers
)-1; i
>= 0; --i
) {
3841 signed_descriptor_t
*r
= smartlist_get(routerlist
->old_routers
, i
);
3843 cur_id
= r
->identity_digest
;
3846 if (tor_memneq(cur_id
, r
->identity_digest
, DIGEST_LEN
)) {
3847 routerlist_remove_old_cached_routers_with_id(now
,
3848 cutoff
, i
+1, hi
, retain
);
3849 cur_id
= r
->identity_digest
;
3854 routerlist_remove_old_cached_routers_with_id(now
, cutoff
, 0, hi
, retain
);
3855 //routerlist_assert_ok(routerlist);
3858 digestset_free(retain
);
3859 router_rebuild_store(RRS_DONT_REMOVE_OLD
, &routerlist
->desc_store
);
3860 router_rebuild_store(RRS_DONT_REMOVE_OLD
,&routerlist
->extrainfo_store
);
3863 /** We just added a new set of descriptors. Take whatever extra steps
3866 routerlist_descriptors_added(smartlist_t
*sl
, int from_cache
)
3869 control_event_descriptors_changed(sl
);
3870 SMARTLIST_FOREACH_BEGIN(sl
, routerinfo_t
*, ri
) {
3871 if (ri
->purpose
== ROUTER_PURPOSE_BRIDGE
)
3872 learned_bridge_descriptor(ri
, from_cache
);
3873 if (ri
->needs_retest_if_added
) {
3874 ri
->needs_retest_if_added
= 0;
3875 dirserv_single_reachability_test(approx_time(), ri
);
3877 } SMARTLIST_FOREACH_END(ri
);
3881 * Code to parse a single router descriptor and insert it into the
3882 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
3883 * descriptor was well-formed but could not be added; and 1 if the
3884 * descriptor was added.
3886 * If we don't add it and <b>msg</b> is not NULL, then assign to
3887 * *<b>msg</b> a static string describing the reason for refusing the
3890 * This is used only by the controller.
3893 router_load_single_router(const char *s
, uint8_t purpose
, int cache
,
3897 was_router_added_t r
;
3899 char annotation_buf
[ROUTER_ANNOTATION_BUF_LEN
];
3903 tor_snprintf(annotation_buf
, sizeof(annotation_buf
),
3904 "@source controller\n"
3905 "@purpose %s\n", router_purpose_to_string(purpose
));
3907 if (!(ri
= router_parse_entry_from_string(s
, NULL
, 1, 0, annotation_buf
))) {
3908 log_warn(LD_DIR
, "Error parsing router descriptor; dropping.");
3909 *msg
= "Couldn't parse router descriptor.";
3912 tor_assert(ri
->purpose
== purpose
);
3913 if (router_is_me(ri
)) {
3914 log_warn(LD_DIR
, "Router's identity key matches mine; dropping.");
3915 *msg
= "Router's identity key matches mine.";
3916 routerinfo_free(ri
);
3920 if (!cache
) /* obey the preference of the controller */
3921 ri
->cache_info
.do_not_cache
= 1;
3923 lst
= smartlist_new();
3924 smartlist_add(lst
, ri
);
3925 routers_update_status_from_consensus_networkstatus(lst
, 0);
3927 r
= router_add_to_routerlist(ri
, msg
, 0, 0);
3928 if (!WRA_WAS_ADDED(r
)) {
3929 /* we've already assigned to *msg now, and ri is already freed */
3931 if (r
== ROUTER_AUTHDIR_REJECTS
)
3932 log_warn(LD_DIR
, "Couldn't add router to list: %s Dropping.", *msg
);
3933 smartlist_free(lst
);
3936 routerlist_descriptors_added(lst
, 0);
3937 smartlist_free(lst
);
3938 log_debug(LD_DIR
, "Added router to list");
3943 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
3944 * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
3945 * are in response to a query to the network: cache them by adding them to
3948 * Return the number of routers actually added.
3950 * If <b>requested_fingerprints</b> is provided, it must contain a list of
3951 * uppercased fingerprints. Do not update any router whose
3952 * fingerprint is not on the list; after updating a router, remove its
3953 * fingerprint from the list.
3955 * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
3956 * are descriptor digests. Otherwise they are identity digests.
3959 router_load_routers_from_string(const char *s
, const char *eos
,
3960 saved_location_t saved_location
,
3961 smartlist_t
*requested_fingerprints
,
3962 int descriptor_digests
,
3963 const char *prepend_annotations
)
3965 smartlist_t
*routers
= smartlist_new(), *changed
= smartlist_new();
3966 char fp
[HEX_DIGEST_LEN
+1];
3968 int from_cache
= (saved_location
!= SAVED_NOWHERE
);
3969 int allow_annotations
= (saved_location
!= SAVED_NOWHERE
);
3970 int any_changed
= 0;
3972 router_parse_list_from_string(&s
, eos
, routers
, saved_location
, 0,
3973 allow_annotations
, prepend_annotations
);
3975 routers_update_status_from_consensus_networkstatus(routers
, !from_cache
);
3977 log_info(LD_DIR
, "%d elements to add", smartlist_len(routers
));
3979 SMARTLIST_FOREACH_BEGIN(routers
, routerinfo_t
*, ri
) {
3980 was_router_added_t r
;
3982 if (requested_fingerprints
) {
3983 base16_encode(fp
, sizeof(fp
), descriptor_digests
?
3984 ri
->cache_info
.signed_descriptor_digest
:
3985 ri
->cache_info
.identity_digest
,
3987 if (smartlist_contains_string(requested_fingerprints
, fp
)) {
3988 smartlist_string_remove(requested_fingerprints
, fp
);
3991 smartlist_join_strings(requested_fingerprints
," ",0,NULL
);
3993 "We received a router descriptor with a fingerprint (%s) "
3994 "that we never requested. (We asked for: %s.) Dropping.",
3996 tor_free(requested
);
3997 routerinfo_free(ri
);
4002 memcpy(d
, ri
->cache_info
.signed_descriptor_digest
, DIGEST_LEN
);
4003 r
= router_add_to_routerlist(ri
, &msg
, from_cache
, !from_cache
);
4004 if (WRA_WAS_ADDED(r
)) {
4006 smartlist_add(changed
, ri
);
4007 routerlist_descriptors_added(changed
, from_cache
);
4008 smartlist_clear(changed
);
4009 } else if (WRA_WAS_REJECTED(r
)) {
4010 download_status_t
*dl_status
;
4011 dl_status
= router_get_dl_status_by_descriptor_digest(d
);
4013 log_info(LD_GENERAL
, "Marking router %s as never downloadable",
4014 hex_str(d
, DIGEST_LEN
));
4015 download_status_mark_impossible(dl_status
);
4018 } SMARTLIST_FOREACH_END(ri
);
4020 routerlist_assert_ok(routerlist
);
4023 router_rebuild_store(0, &routerlist
->desc_store
);
4025 smartlist_free(routers
);
4026 smartlist_free(changed
);
4031 /** Parse one or more extrainfos from <b>s</b> (ending immediately before
4032 * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
4033 * router_load_routers_from_string(). */
4035 router_load_extrainfo_from_string(const char *s
, const char *eos
,
4036 saved_location_t saved_location
,
4037 smartlist_t
*requested_fingerprints
,
4038 int descriptor_digests
)
4040 smartlist_t
*extrainfo_list
= smartlist_new();
4042 int from_cache
= (saved_location
!= SAVED_NOWHERE
);
4044 router_parse_list_from_string(&s
, eos
, extrainfo_list
, saved_location
, 1, 0,
4047 log_info(LD_DIR
, "%d elements to add", smartlist_len(extrainfo_list
));
4049 SMARTLIST_FOREACH_BEGIN(extrainfo_list
, extrainfo_t
*, ei
) {
4050 was_router_added_t added
=
4051 router_add_extrainfo_to_routerlist(ei
, &msg
, from_cache
, !from_cache
);
4052 if (WRA_WAS_ADDED(added
) && requested_fingerprints
) {
4053 char fp
[HEX_DIGEST_LEN
+1];
4054 base16_encode(fp
, sizeof(fp
), descriptor_digests
?
4055 ei
->cache_info
.signed_descriptor_digest
:
4056 ei
->cache_info
.identity_digest
,
4058 smartlist_string_remove(requested_fingerprints
, fp
);
4059 /* We silently let people stuff us with extrainfos we didn't ask for,
4060 * so long as we would have wanted them anyway. Since we always fetch
4061 * all the extrainfos we want, and we never actually act on them
4062 * inside Tor, this should be harmless. */
4064 } SMARTLIST_FOREACH_END(ei
);
4066 routerlist_assert_ok(routerlist
);
4067 router_rebuild_store(0, &router_get_routerlist()->extrainfo_store
);
4069 smartlist_free(extrainfo_list
);
4072 /** Return true iff any networkstatus includes a descriptor whose digest
4073 * is that of <b>desc</b>. */
4075 signed_desc_digest_is_recognized(signed_descriptor_t
*desc
)
4077 const routerstatus_t
*rs
;
4078 networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
4079 int caches
= directory_caches_dir_info(get_options());
4080 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
4083 rs
= networkstatus_vote_find_entry(consensus
, desc
->identity_digest
);
4084 if (rs
&& tor_memeq(rs
->descriptor_digest
,
4085 desc
->signed_descriptor_digest
, DIGEST_LEN
))
4088 if (caches
&& networkstatus_v2_list
) {
4089 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
4091 if (!(rs
= networkstatus_v2_find_entry(ns
, desc
->identity_digest
)))
4093 if (tor_memeq(rs
->descriptor_digest
,
4094 desc
->signed_descriptor_digest
, DIGEST_LEN
))
4101 /** Update downloads for router descriptors and/or microdescriptors as
4104 update_all_descriptor_downloads(time_t now
)
4106 if (get_options()->DisableNetwork
)
4108 update_router_descriptor_downloads(now
);
4109 update_microdesc_downloads(now
);
4110 launch_dummy_descriptor_download_as_needed(now
, get_options());
4113 /** Clear all our timeouts for fetching v2 and v3 directory stuff, and then
4114 * give it all a try again. */
4116 routerlist_retry_directory_downloads(time_t now
)
4118 router_reset_status_download_failures();
4119 router_reset_descriptor_download_failures();
4120 if (get_options()->DisableNetwork
)
4122 update_networkstatus_downloads(now
);
4123 update_all_descriptor_downloads(now
);
4126 /** Return true iff <b>router</b> does not permit exit streams.
4129 router_exit_policy_rejects_all(const routerinfo_t
*router
)
4131 return router
->policy_is_reject_star
;
4134 /** Create an directory server at <b>address</b>:<b>port</b>, with OR identity
4135 * key <b>digest</b>. If <b>address</b> is NULL, add ourself. If
4136 * <b>is_authority</b>, this is a directory authority. Return the new
4137 * directory server entry on success or NULL on failure. */
4138 static dir_server_t
*
4139 dir_server_new(int is_authority
,
4140 const char *nickname
,
4141 const tor_addr_t
*addr
,
4142 const char *hostname
,
4143 uint16_t dir_port
, uint16_t or_port
,
4144 const char *digest
, const char *v3_auth_digest
,
4145 dirinfo_type_t type
,
4150 char *hostname_
= NULL
;
4155 if (tor_addr_family(addr
) == AF_INET
)
4156 a
= tor_addr_to_ipv4h(addr
);
4158 return NULL
; /*XXXX Support IPv6 */
4161 hostname_
= tor_dup_addr(addr
);
4163 hostname_
= tor_strdup(hostname
);
4165 ent
= tor_malloc_zero(sizeof(dir_server_t
));
4166 ent
->nickname
= nickname
? tor_strdup(nickname
) : NULL
;
4167 ent
->address
= hostname_
;
4169 ent
->dir_port
= dir_port
;
4170 ent
->or_port
= or_port
;
4171 ent
->is_running
= 1;
4172 ent
->is_authority
= is_authority
;
4174 ent
->weight
= weight
;
4175 memcpy(ent
->digest
, digest
, DIGEST_LEN
);
4176 if (v3_auth_digest
&& (type
& V3_DIRINFO
))
4177 memcpy(ent
->v3_identity_digest
, v3_auth_digest
, DIGEST_LEN
);
4180 tor_asprintf(&ent
->description
, "directory server \"%s\" at %s:%d",
4181 nickname
, hostname
, (int)dir_port
);
4183 tor_asprintf(&ent
->description
, "directory server at %s:%d",
4184 hostname
, (int)dir_port
);
4186 ent
->fake_status
.addr
= ent
->addr
;
4187 memcpy(ent
->fake_status
.identity_digest
, digest
, DIGEST_LEN
);
4189 strlcpy(ent
->fake_status
.nickname
, nickname
,
4190 sizeof(ent
->fake_status
.nickname
));
4192 ent
->fake_status
.nickname
[0] = '\0';
4193 ent
->fake_status
.dir_port
= ent
->dir_port
;
4194 ent
->fake_status
.or_port
= ent
->or_port
;
4199 /** Create an authoritative directory server at
4200 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
4201 * <b>address</b> is NULL, add ourself. Return the new trusted directory
4202 * server entry on success or NULL if we couldn't add it. */
4204 trusted_dir_server_new(const char *nickname
, const char *address
,
4205 uint16_t dir_port
, uint16_t or_port
,
4206 const char *digest
, const char *v3_auth_digest
,
4207 dirinfo_type_t type
, double weight
)
4211 char *hostname
=NULL
;
4212 dir_server_t
*result
;
4214 if (!address
) { /* The address is us; we should guess. */
4215 if (resolve_my_address(LOG_WARN
, get_options(),
4216 &a
, NULL
, &hostname
) < 0) {
4218 "Couldn't find a suitable address when adding ourself as a "
4219 "trusted directory server.");
4223 hostname
= tor_dup_ip(a
);
4225 if (tor_lookup_hostname(address
, &a
)) {
4227 "Unable to lookup address for directory server at '%s'",
4231 hostname
= tor_strdup(address
);
4233 tor_addr_from_ipv4h(&addr
, a
);
4235 result
= dir_server_new(1, nickname
, &addr
, hostname
,
4236 dir_port
, or_port
, digest
,
4237 v3_auth_digest
, type
, weight
);
4242 /** Return a new dir_server_t for a fallback directory server at
4243 * <b>addr</b>:<b>or_port</b>/<b>dir_port</b>, with identity key digest
4244 * <b>id_digest</b> */
4246 fallback_dir_server_new(const tor_addr_t
*addr
,
4247 uint16_t dir_port
, uint16_t or_port
,
4248 const char *id_digest
, double weight
)
4250 return dir_server_new(0, NULL
, addr
, NULL
, dir_port
, or_port
, id_digest
,
4251 NULL
, ALL_DIRINFO
, weight
);
4254 /** Add a directory server to the global list(s). */
4256 dir_server_add(dir_server_t
*ent
)
4258 if (!trusted_dir_servers
)
4259 trusted_dir_servers
= smartlist_new();
4260 if (!fallback_dir_servers
)
4261 fallback_dir_servers
= smartlist_new();
4263 if (ent
->is_authority
)
4264 smartlist_add(trusted_dir_servers
, ent
);
4266 smartlist_add(fallback_dir_servers
, ent
);
4267 router_dir_info_changed();
4270 /** Free storage held in <b>cert</b>. */
4272 authority_cert_free(authority_cert_t
*cert
)
4277 tor_free(cert
->cache_info
.signed_descriptor_body
);
4278 crypto_pk_free(cert
->signing_key
);
4279 crypto_pk_free(cert
->identity_key
);
4284 /** Free storage held in <b>ds</b>. */
4286 dir_server_free(dir_server_t
*ds
)
4291 tor_free(ds
->nickname
);
4292 tor_free(ds
->description
);
4293 tor_free(ds
->address
);
4297 /** Remove all members from the list of dir servers. */
4299 clear_dir_servers(void)
4301 if (fallback_dir_servers
) {
4302 SMARTLIST_FOREACH(fallback_dir_servers
, dir_server_t
*, ent
,
4303 dir_server_free(ent
));
4304 smartlist_clear(fallback_dir_servers
);
4306 fallback_dir_servers
= smartlist_new();
4308 if (trusted_dir_servers
) {
4309 smartlist_clear(trusted_dir_servers
);
4311 trusted_dir_servers
= smartlist_new();
4313 router_dir_info_changed();
4316 /** For every current directory connection whose purpose is <b>purpose</b>,
4317 * and where the resource being downloaded begins with <b>prefix</b>, split
4318 * rest of the resource into base16 fingerprints (or base64 fingerprints if
4319 * purpose==DIR_PURPPOSE_FETCH_MICRODESC), decode them, and set the
4320 * corresponding elements of <b>result</b> to a nonzero value.
4323 list_pending_downloads(digestmap_t
*result
,
4324 int purpose
, const char *prefix
)
4326 const size_t p_len
= strlen(prefix
);
4327 smartlist_t
*tmp
= smartlist_new();
4328 smartlist_t
*conns
= get_connection_array();
4329 int flags
= DSR_HEX
;
4330 if (purpose
== DIR_PURPOSE_FETCH_MICRODESC
)
4331 flags
= DSR_DIGEST256
|DSR_BASE64
;
4335 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
4336 if (conn
->type
== CONN_TYPE_DIR
&&
4337 conn
->purpose
== purpose
&&
4338 !conn
->marked_for_close
) {
4339 const char *resource
= TO_DIR_CONN(conn
)->requested_resource
;
4340 if (!strcmpstart(resource
, prefix
))
4341 dir_split_resource_into_fingerprints(resource
+ p_len
,
4344 } SMARTLIST_FOREACH_END(conn
);
4346 SMARTLIST_FOREACH(tmp
, char *, d
,
4348 digestmap_set(result
, d
, (void*)1);
4351 smartlist_free(tmp
);
4354 /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
4355 * true) we are currently downloading by descriptor digest, set result[d] to
4358 list_pending_descriptor_downloads(digestmap_t
*result
, int extrainfo
)
4361 extrainfo
? DIR_PURPOSE_FETCH_EXTRAINFO
: DIR_PURPOSE_FETCH_SERVERDESC
;
4362 list_pending_downloads(result
, purpose
, "d/");
4365 /** For every microdescriptor we are currently downloading by descriptor
4366 * digest, set result[d] to (void*)1. (Note that microdescriptor digests
4367 * are 256-bit, and digestmap_t only holds 160-bit digests, so we're only
4368 * getting the first 20 bytes of each digest here.)
4370 * XXXX Let there be a digestmap256_t, and use that instead.
4373 list_pending_microdesc_downloads(digestmap_t
*result
)
4375 list_pending_downloads(result
, DIR_PURPOSE_FETCH_MICRODESC
, "d/");
4378 /** For every certificate we are currently downloading by (identity digest,
4379 * signing key digest) pair, set result[fp_pair] to (void *1).
4382 list_pending_fpsk_downloads(fp_pair_map_t
*result
)
4384 const char *pfx
= "fp-sk/";
4387 const char *resource
;
4391 tmp
= smartlist_new();
4392 conns
= get_connection_array();
4394 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
4395 if (conn
->type
== CONN_TYPE_DIR
&&
4396 conn
->purpose
== DIR_PURPOSE_FETCH_CERTIFICATE
&&
4397 !conn
->marked_for_close
) {
4398 resource
= TO_DIR_CONN(conn
)->requested_resource
;
4399 if (!strcmpstart(resource
, pfx
))
4400 dir_split_resource_into_fingerprint_pairs(resource
+ strlen(pfx
),
4403 } SMARTLIST_FOREACH_END(conn
);
4405 SMARTLIST_FOREACH_BEGIN(tmp
, fp_pair_t
*, fp
) {
4406 fp_pair_map_set(result
, fp
, (void*)1);
4408 } SMARTLIST_FOREACH_END(fp
);
4410 smartlist_free(tmp
);
4413 /** Launch downloads for all the descriptors whose digests or digests256
4414 * are listed as digests[i] for lo <= i < hi. (Lo and hi may be out of
4415 * range.) If <b>source</b> is given, download from <b>source</b>;
4416 * otherwise, download from an appropriate random directory server.
4419 initiate_descriptor_downloads(const routerstatus_t
*source
,
4421 smartlist_t
*digests
,
4422 int lo
, int hi
, int pds_flags
)
4425 char *resource
, *cp
;
4428 int digest_len
= DIGEST_LEN
, enc_digest_len
= HEX_DIGEST_LEN
;
4432 if (purpose
== DIR_PURPOSE_FETCH_MICRODESC
) {
4433 /* Microdescriptors are downloaded by "-"-separated base64-encoded
4434 * 256-bit digests. */
4435 digest_len
= DIGEST256_LEN
;
4436 enc_digest_len
= BASE64_DIGEST256_LEN
;
4445 if (hi
> smartlist_len(digests
))
4446 hi
= smartlist_len(digests
);
4448 r_len
= 8 + (enc_digest_len
+1)*n
;
4449 cp
= resource
= tor_malloc(r_len
);
4450 memcpy(cp
, "d/", 2);
4452 for (i
= lo
; i
< hi
; ++i
) {
4454 digest256_to_base64(cp
, smartlist_get(digests
, i
));
4456 base16_encode(cp
, r_len
-(cp
-resource
),
4457 smartlist_get(digests
,i
), digest_len
);
4459 cp
+= enc_digest_len
;
4462 memcpy(cp
-1, ".z", 3);
4465 /* We know which authority we want. */
4466 directory_initiate_command_routerstatus(source
, purpose
,
4467 ROUTER_PURPOSE_GENERAL
,
4469 resource
, NULL
, 0, 0);
4471 directory_get_from_dirserver(purpose
, ROUTER_PURPOSE_GENERAL
, resource
,
4477 /** Max amount of hashes to download per request.
4478 * Since squid does not like URLs >= 4096 bytes we limit it to 96.
4479 * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
4480 * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
4481 * So use 96 because it's a nice number.
4483 #define MAX_DL_PER_REQUEST 96
4484 #define MAX_MICRODESC_DL_PER_REQUEST 92
4485 /** Don't split our requests so finely that we are requesting fewer than
4486 * this number per server. */
4487 #define MIN_DL_PER_REQUEST 4
4488 /** To prevent a single screwy cache from confusing us by selective reply,
4489 * try to split our requests into at least this many requests. */
4490 #define MIN_REQUESTS 3
4491 /** If we want fewer than this many descriptors, wait until we
4492 * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
4494 #define MAX_DL_TO_DELAY 16
4495 /** When directory clients have only a few servers to request, they batch
4496 * them until they have more, or until this amount of time has passed. */
4497 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
4499 /** Given a <b>purpose</b> (FETCH_MICRODESC or FETCH_SERVERDESC) and a list of
4500 * router descriptor digests or microdescriptor digest256s in
4501 * <b>downloadable</b>, decide whether to delay fetching until we have more.
4502 * If we don't want to delay, launch one or more requests to the appropriate
4503 * directory authorities.
4506 launch_descriptor_downloads(int purpose
,
4507 smartlist_t
*downloadable
,
4508 const routerstatus_t
*source
, time_t now
)
4510 int should_delay
= 0, n_downloadable
;
4511 const or_options_t
*options
= get_options();
4512 const char *descname
;
4514 tor_assert(purpose
== DIR_PURPOSE_FETCH_SERVERDESC
||
4515 purpose
== DIR_PURPOSE_FETCH_MICRODESC
);
4517 descname
= (purpose
== DIR_PURPOSE_FETCH_SERVERDESC
) ?
4518 "routerdesc" : "microdesc";
4520 n_downloadable
= smartlist_len(downloadable
);
4521 if (!directory_fetches_dir_info_early(options
)) {
4522 if (n_downloadable
>= MAX_DL_TO_DELAY
) {
4524 "There are enough downloadable %ss to launch requests.",
4528 should_delay
= (last_descriptor_download_attempted
+
4529 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST
) > now
;
4530 if (!should_delay
&& n_downloadable
) {
4531 if (last_descriptor_download_attempted
) {
4533 "There are not many downloadable %ss, but we've "
4534 "been waiting long enough (%d seconds). Downloading.",
4536 (int)(now
-last_descriptor_download_attempted
));
4539 "There are not many downloadable %ss, but we haven't "
4540 "tried downloading descriptors recently. Downloading.",
4547 if (! should_delay
&& n_downloadable
) {
4548 int i
, n_per_request
;
4549 const char *req_plural
= "", *rtr_plural
= "";
4550 int pds_flags
= PDS_RETRY_IF_NO_SERVERS
;
4551 if (! authdir_mode_any_nonhidserv(options
)) {
4552 /* If we wind up going to the authorities, we want to only open one
4553 * connection to each authority at a time, so that we don't overload
4554 * them. We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
4555 * regardless of whether we're a cache or not; it gets ignored if we're
4556 * not calling router_pick_trusteddirserver.
4558 * Setting this flag can make initiate_descriptor_downloads() ignore
4559 * requests. We need to make sure that we do in fact call
4560 * update_router_descriptor_downloads() later on, once the connections
4561 * have succeeded or failed.
4563 pds_flags
|= (purpose
== DIR_PURPOSE_FETCH_MICRODESC
) ?
4564 PDS_NO_EXISTING_MICRODESC_FETCH
:
4565 PDS_NO_EXISTING_SERVERDESC_FETCH
;
4568 n_per_request
= CEIL_DIV(n_downloadable
, MIN_REQUESTS
);
4569 if (purpose
== DIR_PURPOSE_FETCH_MICRODESC
) {
4570 if (n_per_request
> MAX_MICRODESC_DL_PER_REQUEST
)
4571 n_per_request
= MAX_MICRODESC_DL_PER_REQUEST
;
4573 if (n_per_request
> MAX_DL_PER_REQUEST
)
4574 n_per_request
= MAX_DL_PER_REQUEST
;
4576 if (n_per_request
< MIN_DL_PER_REQUEST
)
4577 n_per_request
= MIN_DL_PER_REQUEST
;
4579 if (n_downloadable
> n_per_request
)
4580 req_plural
= rtr_plural
= "s";
4581 else if (n_downloadable
> 1)
4585 "Launching %d request%s for %d %s%s, %d at a time",
4586 CEIL_DIV(n_downloadable
, n_per_request
), req_plural
,
4587 n_downloadable
, descname
, rtr_plural
, n_per_request
);
4588 smartlist_sort_digests(downloadable
);
4589 for (i
=0; i
< n_downloadable
; i
+= n_per_request
) {
4590 initiate_descriptor_downloads(source
, purpose
,
4591 downloadable
, i
, i
+n_per_request
,
4594 last_descriptor_download_attempted
= now
;
4598 /** Launch downloads for router status as needed, using the strategy used by
4599 * authorities and caches: based on the v2 networkstatuses we have, download
4600 * every descriptor we don't have but would serve, from a random authority
4603 update_router_descriptor_cache_downloads_v2(time_t now
)
4605 smartlist_t
**downloadable
; /* For each authority, what can we dl from it? */
4606 smartlist_t
**download_from
; /* ... and, what will we dl from it? */
4607 digestmap_t
*map
; /* Which descs are in progress, or assigned? */
4610 const or_options_t
*options
= get_options();
4611 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
4613 if (! directory_fetches_dir_info_early(options
)) {
4614 log_warn(LD_BUG
, "Called update_router_descriptor_cache_downloads_v2() "
4615 "on a non-dir-mirror?");
4618 if (!networkstatus_v2_list
|| !smartlist_len(networkstatus_v2_list
))
4621 map
= digestmap_new();
4622 n
= smartlist_len(networkstatus_v2_list
);
4624 downloadable
= tor_malloc_zero(sizeof(smartlist_t
*) * n
);
4625 download_from
= tor_malloc_zero(sizeof(smartlist_t
*) * n
);
4627 /* Set map[d]=1 for the digest of every descriptor that we are currently
4629 list_pending_descriptor_downloads(map
, 0);
4631 /* For the digest of every descriptor that we don't have, and that we aren't
4632 * downloading, add d to downloadable[i] if the i'th networkstatus knows
4633 * about that descriptor, and we haven't already failed to get that
4634 * descriptor from the corresponding authority.
4637 SMARTLIST_FOREACH_BEGIN(networkstatus_v2_list
, networkstatus_v2_t
*, ns
) {
4640 dl
= downloadable
[ns_sl_idx
] = smartlist_new();
4641 download_from
[ns_sl_idx
] = smartlist_new();
4642 if (ns
->published_on
+ MAX_NETWORKSTATUS_AGE
+10*60 < now
) {
4643 /* Don't download if the networkstatus is almost ancient. */
4644 /* Actually, I suspect what's happening here is that we ask
4645 * for the descriptor when we have a given networkstatus,
4646 * and then we get a newer networkstatus, and then we receive
4647 * the descriptor. Having a networkstatus actually expire is
4648 * probably a rare event, and we'll probably be happiest if
4649 * we take this clause out. -RD */
4653 /* Don't try dirservers that we think are down -- we might have
4654 * just tried them and just marked them as down. */
4655 ds
= router_get_trusteddirserver_by_digest(ns
->identity_digest
);
4656 if (ds
&& !ds
->is_running
)
4659 SMARTLIST_FOREACH_BEGIN(ns
->entries
, routerstatus_t
* , rs
) {
4660 if (!rs
->need_to_mirror
)
4662 if (router_get_by_descriptor_digest(rs
->descriptor_digest
)) {
4664 "We have a router descriptor, but need_to_mirror=1.");
4665 rs
->need_to_mirror
= 0;
4668 if (authdir_mode(options
) && dirserv_would_reject_router(rs
)) {
4669 rs
->need_to_mirror
= 0;
4672 if (digestmap_get(map
, rs
->descriptor_digest
)) {
4673 /* We're downloading it already. */
4676 /* We could download it from this guy. */
4677 smartlist_add(dl
, rs
->descriptor_digest
);
4680 } SMARTLIST_FOREACH_END(rs
);
4681 } SMARTLIST_FOREACH_END(ns
);
4683 /* At random, assign descriptors to authorities such that:
4684 * - if d is a member of some downloadable[x], d is a member of some
4685 * download_from[y]. (Everything we want to download, we try to download
4687 * - If d is a member of download_from[y], d is a member of downloadable[y].
4688 * (We only try to download descriptors from authorities who claim to have
4690 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
4691 * (We don't try to download anything from two authorities concurrently.)
4693 while (n_download
) {
4694 int which_ns
= crypto_rand_int(n
);
4695 smartlist_t
*dl
= downloadable
[which_ns
];
4698 if (!smartlist_len(dl
))
4700 idx
= crypto_rand_int(smartlist_len(dl
));
4701 d
= smartlist_get(dl
, idx
);
4702 if (! digestmap_get(map
, d
)) {
4703 smartlist_add(download_from
[which_ns
], d
);
4704 digestmap_set(map
, d
, (void*) 1);
4706 smartlist_del(dl
, idx
);
4710 /* Now, we can actually launch our requests. */
4711 for (i
=0; i
<n
; ++i
) {
4712 networkstatus_v2_t
*ns
= smartlist_get(networkstatus_v2_list
, i
);
4714 router_get_trusteddirserver_by_digest(ns
->identity_digest
);
4715 smartlist_t
*dl
= download_from
[i
];
4716 int pds_flags
= PDS_RETRY_IF_NO_SERVERS
;
4717 if (! authdir_mode_any_nonhidserv(options
))
4718 pds_flags
|= PDS_NO_EXISTING_SERVERDESC_FETCH
; /* XXXX ignored*/
4721 log_info(LD_DIR
, "Networkstatus with no corresponding authority!");
4724 if (! smartlist_len(dl
))
4726 log_info(LD_DIR
, "Requesting %d descriptors from authority \"%s\"",
4727 smartlist_len(dl
), ds
->nickname
);
4728 for (j
=0; j
< smartlist_len(dl
); j
+= MAX_DL_PER_REQUEST
) {
4729 initiate_descriptor_downloads(&(ds
->fake_status
),
4730 DIR_PURPOSE_FETCH_SERVERDESC
, dl
, j
,
4731 j
+MAX_DL_PER_REQUEST
, pds_flags
);
4735 for (i
=0; i
<n
; ++i
) {
4736 smartlist_free(download_from
[i
]);
4737 smartlist_free(downloadable
[i
]);
4739 tor_free(download_from
);
4740 tor_free(downloadable
);
4741 digestmap_free(map
,NULL
);
4744 /** For any descriptor that we want that's currently listed in
4745 * <b>consensus</b>, download it as appropriate. */
4747 update_consensus_router_descriptor_downloads(time_t now
, int is_vote
,
4748 networkstatus_t
*consensus
)
4750 const or_options_t
*options
= get_options();
4751 digestmap_t
*map
= NULL
;
4752 smartlist_t
*no_longer_old
= smartlist_new();
4753 smartlist_t
*downloadable
= smartlist_new();
4754 routerstatus_t
*source
= NULL
;
4755 int authdir
= authdir_mode(options
);
4756 int n_delayed
=0, n_have
=0, n_would_reject
=0, n_wouldnt_use
=0,
4757 n_inprogress
=0, n_in_oldrouters
=0;
4759 if (directory_too_idle_to_fetch_descriptors(options
, now
))
4765 /* where's it from, so we know whom to ask for descriptors */
4767 networkstatus_voter_info_t
*voter
= smartlist_get(consensus
->voters
, 0);
4769 ds
= trusteddirserver_get_by_v3_auth_digest(voter
->identity_digest
);
4771 source
= &(ds
->fake_status
);
4773 log_warn(LD_DIR
, "couldn't lookup source from vote?");
4776 map
= digestmap_new();
4777 list_pending_descriptor_downloads(map
, 0);
4778 SMARTLIST_FOREACH_BEGIN(consensus
->routerstatus_list
, void *, rsp
) {
4779 routerstatus_t
*rs
=
4780 is_vote
? &(((vote_routerstatus_t
*)rsp
)->status
) : rsp
;
4781 signed_descriptor_t
*sd
;
4782 if ((sd
= router_get_by_descriptor_digest(rs
->descriptor_digest
))) {
4783 const routerinfo_t
*ri
;
4785 if (!(ri
= router_get_by_id_digest(rs
->identity_digest
)) ||
4786 tor_memneq(ri
->cache_info
.signed_descriptor_digest
,
4787 sd
->signed_descriptor_digest
, DIGEST_LEN
)) {
4788 /* We have a descriptor with this digest, but either there is no
4789 * entry in routerlist with the same ID (!ri), or there is one,
4790 * but the identity digest differs (memneq).
4792 smartlist_add(no_longer_old
, sd
);
4793 ++n_in_oldrouters
; /* We have it in old_routers. */
4795 continue; /* We have it already. */
4797 if (digestmap_get(map
, rs
->descriptor_digest
)) {
4799 continue; /* We have an in-progress download. */
4801 if (!download_status_is_ready(&rs
->dl_status
, now
,
4802 MAX_ROUTERDESC_DOWNLOAD_FAILURES
)) {
4803 ++n_delayed
; /* Not ready for retry. */
4806 if (authdir
&& dirserv_would_reject_router(rs
)) {
4808 continue; /* We would throw it out immediately. */
4810 if (!directory_caches_dir_info(options
) &&
4811 !client_would_use_router(rs
, now
, options
)) {
4813 continue; /* We would never use it ourself. */
4815 if (is_vote
&& source
) {
4816 char time_bufnew
[ISO_TIME_LEN
+1];
4817 char time_bufold
[ISO_TIME_LEN
+1];
4818 const routerinfo_t
*oldrouter
;
4819 oldrouter
= router_get_by_id_digest(rs
->identity_digest
);
4820 format_iso_time(time_bufnew
, rs
->published_on
);
4822 format_iso_time(time_bufold
, oldrouter
->cache_info
.published_on
);
4823 log_info(LD_DIR
, "Learned about %s (%s vs %s) from %s's vote (%s)",
4824 routerstatus_describe(rs
),
4826 oldrouter
? time_bufold
: "none",
4827 source
->nickname
, oldrouter
? "known" : "unknown");
4829 smartlist_add(downloadable
, rs
->descriptor_digest
);
4830 } SMARTLIST_FOREACH_END(rsp
);
4832 if (!authdir_mode_handles_descs(options
, ROUTER_PURPOSE_GENERAL
)
4833 && smartlist_len(no_longer_old
)) {
4834 routerlist_t
*rl
= router_get_routerlist();
4835 log_info(LD_DIR
, "%d router descriptors listed in consensus are "
4836 "currently in old_routers; making them current.",
4837 smartlist_len(no_longer_old
));
4838 SMARTLIST_FOREACH_BEGIN(no_longer_old
, signed_descriptor_t
*, sd
) {
4840 was_router_added_t r
;
4841 routerinfo_t
*ri
= routerlist_reparse_old(rl
, sd
);
4843 log_warn(LD_BUG
, "Failed to re-parse a router.");
4846 r
= router_add_to_routerlist(ri
, &msg
, 1, 0);
4847 if (WRA_WAS_OUTDATED(r
)) {
4848 log_warn(LD_DIR
, "Couldn't add re-parsed router: %s",
4851 } SMARTLIST_FOREACH_END(sd
);
4852 routerlist_assert_ok(rl
);
4856 "%d router descriptors downloadable. %d delayed; %d present "
4857 "(%d of those were in old_routers); %d would_reject; "
4858 "%d wouldnt_use; %d in progress.",
4859 smartlist_len(downloadable
), n_delayed
, n_have
, n_in_oldrouters
,
4860 n_would_reject
, n_wouldnt_use
, n_inprogress
);
4862 launch_descriptor_downloads(DIR_PURPOSE_FETCH_SERVERDESC
,
4863 downloadable
, source
, now
);
4865 digestmap_free(map
, NULL
);
4867 smartlist_free(downloadable
);
4868 smartlist_free(no_longer_old
);
4871 /** How often should we launch a server/authority request to be sure of getting
4872 * a guess for our IP? */
4873 /*XXXX024 this info should come from netinfo cells or something, or we should
4874 * do this only when we aren't seeing incoming data. see bug 652. */
4875 #define DUMMY_DOWNLOAD_INTERVAL (20*60)
4877 /** As needed, launch a dummy router descriptor fetch to see if our
4878 * address has changed. */
4880 launch_dummy_descriptor_download_as_needed(time_t now
,
4881 const or_options_t
*options
)
4883 static time_t last_dummy_download
= 0;
4884 /* XXXX024 we could be smarter here; see notes on bug 652. */
4885 /* If we're a server that doesn't have a configured address, we rely on
4886 * directory fetches to learn when our address changes. So if we haven't
4887 * tried to get any routerdescs in a long time, try a dummy fetch now. */
4888 if (!options
->Address
&&
4889 server_mode(options
) &&
4890 last_descriptor_download_attempted
+ DUMMY_DOWNLOAD_INTERVAL
< now
&&
4891 last_dummy_download
+ DUMMY_DOWNLOAD_INTERVAL
< now
) {
4892 last_dummy_download
= now
;
4893 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC
,
4894 ROUTER_PURPOSE_GENERAL
, "authority.z",
4895 PDS_RETRY_IF_NO_SERVERS
);
4899 /** Launch downloads for router status as needed. */
4901 update_router_descriptor_downloads(time_t now
)
4903 const or_options_t
*options
= get_options();
4904 if (should_delay_dir_fetches(options
))
4906 if (!we_fetch_router_descriptors(options
))
4908 if (directory_fetches_dir_info_early(options
)) {
4909 update_router_descriptor_cache_downloads_v2(now
);
4912 update_consensus_router_descriptor_downloads(now
, 0,
4913 networkstatus_get_reasonably_live_consensus(now
, FLAV_NS
));
4916 /** Launch extrainfo downloads as needed. */
4918 update_extrainfo_downloads(time_t now
)
4920 const or_options_t
*options
= get_options();
4922 smartlist_t
*wanted
;
4923 digestmap_t
*pending
;
4925 int n_no_ei
= 0, n_pending
= 0, n_have
= 0, n_delay
= 0;
4926 if (! options
->DownloadExtraInfo
)
4928 if (should_delay_dir_fetches(options
))
4930 if (!router_have_minimum_dir_info())
4933 pending
= digestmap_new();
4934 list_pending_descriptor_downloads(pending
, 1);
4935 rl
= router_get_routerlist();
4936 wanted
= smartlist_new();
4937 for (old_routers
= 0; old_routers
< 2; ++old_routers
) {
4938 smartlist_t
*lst
= old_routers
? rl
->old_routers
: rl
->routers
;
4939 for (i
= 0; i
< smartlist_len(lst
); ++i
) {
4940 signed_descriptor_t
*sd
;
4943 sd
= smartlist_get(lst
, i
);
4945 sd
= &((routerinfo_t
*)smartlist_get(lst
, i
))->cache_info
;
4946 if (sd
->is_extrainfo
)
4947 continue; /* This should never happen. */
4948 if (old_routers
&& !router_get_by_id_digest(sd
->identity_digest
))
4949 continue; /* Couldn't check the signature if we got it. */
4950 if (sd
->extrainfo_is_bogus
)
4952 d
= sd
->extra_info_digest
;
4953 if (tor_digest_is_zero(d
)) {
4957 if (eimap_get(rl
->extra_info_map
, d
)) {
4961 if (!download_status_is_ready(&sd
->ei_dl_status
, now
,
4962 MAX_ROUTERDESC_DOWNLOAD_FAILURES
)) {
4966 if (digestmap_get(pending
, d
)) {
4970 smartlist_add(wanted
, d
);
4973 digestmap_free(pending
, NULL
);
4975 log_info(LD_DIR
, "Extrainfo download status: %d router with no ei, %d "
4976 "with present ei, %d delaying, %d pending, %d downloadable.",
4977 n_no_ei
, n_have
, n_delay
, n_pending
, smartlist_len(wanted
));
4979 smartlist_shuffle(wanted
);
4980 for (i
= 0; i
< smartlist_len(wanted
); i
+= MAX_DL_PER_REQUEST
) {
4981 initiate_descriptor_downloads(NULL
, DIR_PURPOSE_FETCH_EXTRAINFO
,
4982 wanted
, i
, i
+ MAX_DL_PER_REQUEST
,
4983 PDS_RETRY_IF_NO_SERVERS
|PDS_NO_EXISTING_SERVERDESC_FETCH
);
4986 smartlist_free(wanted
);
4989 /** Reset the descriptor download failure count on all routers, so that we
4990 * can retry any long-failed routers immediately.
4993 router_reset_descriptor_download_failures(void)
4995 networkstatus_reset_download_failures();
4996 last_descriptor_download_attempted
= 0;
4999 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
5001 download_status_reset(&ri
->cache_info
.ei_dl_status
);
5003 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
,
5005 download_status_reset(&sd
->ei_dl_status
);
5009 /** Any changes in a router descriptor's publication time larger than this are
5010 * automatically non-cosmetic. */
5011 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (2*60*60)
5013 /** We allow uptime to vary from how much it ought to be by this much. */
5014 #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
5016 /** Return true iff the only differences between r1 and r2 are such that
5017 * would not cause a recent (post 0.1.1.6) dirserver to republish.
5020 router_differences_are_cosmetic(const routerinfo_t
*r1
, const routerinfo_t
*r2
)
5022 time_t r1pub
, r2pub
;
5023 long time_difference
;
5024 tor_assert(r1
&& r2
);
5026 /* r1 should be the one that was published first. */
5027 if (r1
->cache_info
.published_on
> r2
->cache_info
.published_on
) {
5028 const routerinfo_t
*ri_tmp
= r2
;
5033 /* If any key fields differ, they're different. */
5034 if (strcasecmp(r1
->address
, r2
->address
) ||
5035 strcasecmp(r1
->nickname
, r2
->nickname
) ||
5036 r1
->or_port
!= r2
->or_port
||
5037 !tor_addr_eq(&r1
->ipv6_addr
, &r2
->ipv6_addr
) ||
5038 r1
->ipv6_orport
!= r2
->ipv6_orport
||
5039 r1
->dir_port
!= r2
->dir_port
||
5040 r1
->purpose
!= r2
->purpose
||
5041 !crypto_pk_eq_keys(r1
->onion_pkey
, r2
->onion_pkey
) ||
5042 !crypto_pk_eq_keys(r1
->identity_pkey
, r2
->identity_pkey
) ||
5043 strcasecmp(r1
->platform
, r2
->platform
) ||
5044 (r1
->contact_info
&& !r2
->contact_info
) || /* contact_info is optional */
5045 (!r1
->contact_info
&& r2
->contact_info
) ||
5046 (r1
->contact_info
&& r2
->contact_info
&&
5047 strcasecmp(r1
->contact_info
, r2
->contact_info
)) ||
5048 r1
->is_hibernating
!= r2
->is_hibernating
||
5049 cmp_addr_policies(r1
->exit_policy
, r2
->exit_policy
))
5051 if ((r1
->declared_family
== NULL
) != (r2
->declared_family
== NULL
))
5053 if (r1
->declared_family
&& r2
->declared_family
) {
5055 if (smartlist_len(r1
->declared_family
)!=smartlist_len(r2
->declared_family
))
5057 n
= smartlist_len(r1
->declared_family
);
5058 for (i
=0; i
< n
; ++i
) {
5059 if (strcasecmp(smartlist_get(r1
->declared_family
, i
),
5060 smartlist_get(r2
->declared_family
, i
)))
5065 /* Did bandwidth change a lot? */
5066 if ((r1
->bandwidthcapacity
< r2
->bandwidthcapacity
/2) ||
5067 (r2
->bandwidthcapacity
< r1
->bandwidthcapacity
/2))
5070 /* Did the bandwidthrate or bandwidthburst change? */
5071 if ((r1
->bandwidthrate
!= r2
->bandwidthrate
) ||
5072 (r1
->bandwidthburst
!= r2
->bandwidthburst
))
5075 /* Did more than 12 hours pass? */
5076 if (r1
->cache_info
.published_on
+ ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
5077 < r2
->cache_info
.published_on
)
5080 /* Did uptime fail to increase by approximately the amount we would think,
5081 * give or take some slop? */
5082 r1pub
= r1
->cache_info
.published_on
;
5083 r2pub
= r2
->cache_info
.published_on
;
5084 time_difference
= labs(r2
->uptime
- (r1
->uptime
+ (r2pub
- r1pub
)));
5085 if (time_difference
> ROUTER_ALLOW_UPTIME_DRIFT
&&
5086 time_difference
> r1
->uptime
* .05 &&
5087 time_difference
> r2
->uptime
* .05)
5090 /* Otherwise, the difference is cosmetic. */
5094 /** Check whether <b>ri</b> (a.k.a. sd) is a router compatible with the
5095 * extrainfo document
5096 * <b>ei</b>. If no router is compatible with <b>ei</b>, <b>ei</b> should be
5097 * dropped. Return 0 for "compatible", return 1 for "reject, and inform
5098 * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
5099 * <b>msg</b> is present, set *<b>msg</b> to a description of the
5100 * incompatibility (if any).
5103 routerinfo_incompatible_with_extrainfo(const routerinfo_t
*ri
,
5105 signed_descriptor_t
*sd
,
5108 int digest_matches
, r
=1;
5112 sd
= (signed_descriptor_t
*)&ri
->cache_info
;
5115 if (msg
) *msg
= "Extrainfo signature was bad, or signed with wrong key.";
5119 digest_matches
= tor_memeq(ei
->cache_info
.signed_descriptor_digest
,
5120 sd
->extra_info_digest
, DIGEST_LEN
);
5122 /* The identity must match exactly to have been generated at the same time
5123 * by the same router. */
5124 if (tor_memneq(ri
->cache_info
.identity_digest
,
5125 ei
->cache_info
.identity_digest
,
5127 if (msg
) *msg
= "Extrainfo nickname or identity did not match routerinfo";
5128 goto err
; /* different servers */
5131 if (ei
->pending_sig
) {
5132 char signed_digest
[128];
5133 if (crypto_pk_public_checksig(ri
->identity_pkey
,
5134 signed_digest
, sizeof(signed_digest
),
5135 ei
->pending_sig
, ei
->pending_sig_len
) != DIGEST_LEN
||
5136 tor_memneq(signed_digest
, ei
->cache_info
.signed_descriptor_digest
,
5139 tor_free(ei
->pending_sig
);
5140 if (msg
) *msg
= "Extrainfo signature bad, or signed with wrong key";
5141 goto err
; /* Bad signature, or no match. */
5144 ei
->cache_info
.send_unencrypted
= ri
->cache_info
.send_unencrypted
;
5145 tor_free(ei
->pending_sig
);
5148 if (ei
->cache_info
.published_on
< sd
->published_on
) {
5149 if (msg
) *msg
= "Extrainfo published time did not match routerdesc";
5151 } else if (ei
->cache_info
.published_on
> sd
->published_on
) {
5152 if (msg
) *msg
= "Extrainfo published time did not match routerdesc";
5157 if (!digest_matches
) {
5158 if (msg
) *msg
= "Extrainfo digest did not match value from routerdesc";
5159 goto err
; /* Digest doesn't match declared value. */
5164 if (digest_matches
) {
5165 /* This signature was okay, and the digest was right: This is indeed the
5166 * corresponding extrainfo. But insanely, it doesn't match the routerinfo
5167 * that lists it. Don't try to fetch this one again. */
5168 sd
->extrainfo_is_bogus
= 1;
5174 /** Assert that the internal representation of <b>rl</b> is
5175 * self-consistent. */
5177 routerlist_assert_ok(const routerlist_t
*rl
)
5180 signed_descriptor_t
*sd2
;
5183 SMARTLIST_FOREACH_BEGIN(rl
->routers
, routerinfo_t
*, r
) {
5184 r2
= rimap_get(rl
->identity_map
, r
->cache_info
.identity_digest
);
5185 tor_assert(r
== r2
);
5186 sd2
= sdmap_get(rl
->desc_digest_map
,
5187 r
->cache_info
.signed_descriptor_digest
);
5188 tor_assert(&(r
->cache_info
) == sd2
);
5189 tor_assert(r
->cache_info
.routerlist_index
== r_sl_idx
);
5192 * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
5193 * commenting this out is just a band-aid.
5195 * The problem is that, although well-behaved router descriptors
5196 * should never have the same value for their extra_info_digest, it's
5197 * possible for ill-behaved routers to claim whatever they like there.
5199 * The real answer is to trash desc_by_eid_map and instead have
5200 * something that indicates for a given extra-info digest we want,
5201 * what its download status is. We'll do that as a part of routerlist
5202 * refactoring once consensus directories are in. For now,
5203 * this rep violation is probably harmless: an adversary can make us
5204 * reset our retry count for an extrainfo, but that's not the end
5205 * of the world. Changing the representation in 0.2.0.x would just
5206 * destabilize the codebase.
5207 if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
5208 signed_descriptor_t *sd3 =
5209 sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
5210 tor_assert(sd3 == &(r->cache_info));
5213 } SMARTLIST_FOREACH_END(r
);
5214 SMARTLIST_FOREACH_BEGIN(rl
->old_routers
, signed_descriptor_t
*, sd
) {
5215 r2
= rimap_get(rl
->identity_map
, sd
->identity_digest
);
5216 tor_assert(sd
!= &(r2
->cache_info
));
5217 sd2
= sdmap_get(rl
->desc_digest_map
, sd
->signed_descriptor_digest
);
5218 tor_assert(sd
== sd2
);
5219 tor_assert(sd
->routerlist_index
== sd_sl_idx
);
5221 if (!tor_digest_is_zero(sd->extra_info_digest)) {
5222 signed_descriptor_t *sd3 =
5223 sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
5224 tor_assert(sd3 == sd);
5227 } SMARTLIST_FOREACH_END(sd
);
5229 RIMAP_FOREACH(rl
->identity_map
, d
, r
) {
5230 tor_assert(tor_memeq(r
->cache_info
.identity_digest
, d
, DIGEST_LEN
));
5231 } DIGESTMAP_FOREACH_END
;
5232 SDMAP_FOREACH(rl
->desc_digest_map
, d
, sd
) {
5233 tor_assert(tor_memeq(sd
->signed_descriptor_digest
, d
, DIGEST_LEN
));
5234 } DIGESTMAP_FOREACH_END
;
5235 SDMAP_FOREACH(rl
->desc_by_eid_map
, d
, sd
) {
5236 tor_assert(!tor_digest_is_zero(d
));
5238 tor_assert(tor_memeq(sd
->extra_info_digest
, d
, DIGEST_LEN
));
5239 } DIGESTMAP_FOREACH_END
;
5240 EIMAP_FOREACH(rl
->extra_info_map
, d
, ei
) {
5241 signed_descriptor_t
*sd
;
5242 tor_assert(tor_memeq(ei
->cache_info
.signed_descriptor_digest
,
5244 sd
= sdmap_get(rl
->desc_by_eid_map
,
5245 ei
->cache_info
.signed_descriptor_digest
);
5246 // tor_assert(sd); // XXXX see above
5248 tor_assert(tor_memeq(ei
->cache_info
.signed_descriptor_digest
,
5249 sd
->extra_info_digest
, DIGEST_LEN
));
5251 } DIGESTMAP_FOREACH_END
;
5254 /** Allocate and return a new string representing the contact info
5255 * and platform string for <b>router</b>,
5256 * surrounded by quotes and using standard C escapes.
5258 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
5259 * thread. Also, each call invalidates the last-returned value, so don't
5260 * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
5262 * If <b>router</b> is NULL, it just frees its internal memory and returns.
5265 esc_router_info(const routerinfo_t
*router
)
5267 static char *info
=NULL
;
5268 char *esc_contact
, *esc_platform
;
5272 return NULL
; /* we're exiting; just free the memory we use */
5274 esc_contact
= esc_for_log(router
->contact_info
);
5275 esc_platform
= esc_for_log(router
->platform
);
5277 tor_asprintf(&info
, "Contact %s, Platform %s", esc_contact
, esc_platform
);
5278 tor_free(esc_contact
);
5279 tor_free(esc_platform
);
5284 /** Helper for sorting: compare two routerinfos by their identity
5287 compare_routerinfo_by_id_digest_(const void **a
, const void **b
)
5289 routerinfo_t
*first
= *(routerinfo_t
**)a
, *second
= *(routerinfo_t
**)b
;
5290 return fast_memcmp(first
->cache_info
.identity_digest
,
5291 second
->cache_info
.identity_digest
,
5295 /** Sort a list of routerinfo_t in ascending order of identity digest. */
5297 routers_sort_by_identity(smartlist_t
*routers
)
5299 smartlist_sort(routers
, compare_routerinfo_by_id_digest_
);
5302 /** Called when we change a node set, or when we reload the geoip IPv4 list:
5303 * recompute all country info in all configuration node sets and in the
5306 refresh_all_country_info(void)
5308 const or_options_t
*options
= get_options();
5310 if (options
->EntryNodes
)
5311 routerset_refresh_countries(options
->EntryNodes
);
5312 if (options
->ExitNodes
)
5313 routerset_refresh_countries(options
->ExitNodes
);
5314 if (options
->ExcludeNodes
)
5315 routerset_refresh_countries(options
->ExcludeNodes
);
5316 if (options
->ExcludeExitNodes
)
5317 routerset_refresh_countries(options
->ExcludeExitNodes
);
5318 if (options
->ExcludeExitNodesUnion_
)
5319 routerset_refresh_countries(options
->ExcludeExitNodesUnion_
);
5321 nodelist_refresh_countries();
5324 /** Determine the routers that are responsible for <b>id</b> (binary) and
5325 * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
5326 * Return -1 if we're returning an empty smartlist, else return 0.
5329 hid_serv_get_responsible_directories(smartlist_t
*responsible_dirs
,
5332 int start
, found
, n_added
= 0, i
;
5333 networkstatus_t
*c
= networkstatus_get_latest_consensus();
5334 if (!c
|| !smartlist_len(c
->routerstatus_list
)) {
5335 log_warn(LD_REND
, "We don't have a consensus, so we can't perform v2 "
5336 "rendezvous operations.");
5340 start
= networkstatus_vote_find_entry_idx(c
, id
, &found
);
5341 if (start
== smartlist_len(c
->routerstatus_list
)) start
= 0;
5344 routerstatus_t
*r
= smartlist_get(c
->routerstatus_list
, i
);
5346 smartlist_add(responsible_dirs
, r
);
5347 if (++n_added
== REND_NUMBER_OF_CONSECUTIVE_REPLICAS
)
5350 if (++i
== smartlist_len(c
->routerstatus_list
))
5352 } while (i
!= start
);
5354 /* Even though we don't have the desired number of hidden service
5355 * directories, be happy if we got any. */
5356 return smartlist_len(responsible_dirs
) ? 0 : -1;
5359 /** Return true if this node is currently acting as hidden service
5360 * directory, false otherwise. */
5362 hid_serv_acting_as_directory(void)
5364 const routerinfo_t
*me
= router_get_my_routerinfo();
5367 if (!get_options()->HidServDirectoryV2
) {
5368 log_info(LD_REND
, "We are not acting as hidden service directory, "
5369 "because we have not been configured as such.");
5375 /** Return true if this node is responsible for storing the descriptor ID
5376 * in <b>query</b> and false otherwise. */
5378 hid_serv_responsible_for_desc_id(const char *query
)
5380 const routerinfo_t
*me
;
5381 routerstatus_t
*last_rs
;
5382 const char *my_id
, *last_id
;
5384 smartlist_t
*responsible
;
5385 if (!hid_serv_acting_as_directory())
5387 if (!(me
= router_get_my_routerinfo()))
5388 return 0; /* This is redundant, but let's be paranoid. */
5389 my_id
= me
->cache_info
.identity_digest
;
5390 responsible
= smartlist_new();
5391 if (hid_serv_get_responsible_directories(responsible
, query
) < 0) {
5392 smartlist_free(responsible
);
5395 last_rs
= smartlist_get(responsible
, smartlist_len(responsible
)-1);
5396 last_id
= last_rs
->identity_digest
;
5397 result
= rend_id_is_in_interval(my_id
, query
, last_id
);
5398 smartlist_free(responsible
);