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-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 const char routerlist_c_id
[] =
13 * maintain and access the global list of routerinfos for known
19 // #define DEBUG_ROUTERLIST
21 /****************************************************************************/
23 /* static function prototypes */
24 static routerstatus_t
*router_pick_directory_server_impl(
25 authority_type_t auth
, int flags
);
26 static routerstatus_t
*router_pick_trusteddirserver_impl(
27 authority_type_t auth
, int flags
);
28 static void mark_all_trusteddirservers_up(void);
29 static int router_nickname_matches(routerinfo_t
*router
, const char *nickname
);
30 static void trusted_dir_server_free(trusted_dir_server_t
*ds
);
31 static void launch_router_descriptor_downloads(smartlist_t
*downloadable
,
33 static void update_consensus_router_descriptor_downloads(time_t now
);
34 static int signed_desc_digest_is_recognized(signed_descriptor_t
*desc
);
35 static void update_router_have_minimum_dir_info(void);
36 static const char *signed_descriptor_get_body_impl(signed_descriptor_t
*desc
,
37 int with_annotations
);
38 static void list_pending_downloads(digestmap_t
*result
,
39 int purpose
, const char *prefix
);
41 DECLARE_TYPED_DIGESTMAP_FNS(sdmap_
, digest_sd_map_t
, signed_descriptor_t
)
42 DECLARE_TYPED_DIGESTMAP_FNS(rimap_
, digest_ri_map_t
, routerinfo_t
)
43 DECLARE_TYPED_DIGESTMAP_FNS(eimap_
, digest_ei_map_t
, extrainfo_t
)
44 #define SDMAP_FOREACH(map, keyvar, valvar) \
45 DIGESTMAP_FOREACH(sdmap_to_digestmap(map), keyvar, signed_descriptor_t *, \
47 #define RIMAP_FOREACH(map, keyvar, valvar) \
48 DIGESTMAP_FOREACH(rimap_to_digestmap(map), keyvar, routerinfo_t *, valvar)
49 #define EIMAP_FOREACH(map, keyvar, valvar) \
50 DIGESTMAP_FOREACH(eimap_to_digestmap(map), keyvar, extrainfo_t *, valvar)
52 /****************************************************************************/
54 /** Global list of a trusted_dir_server_t object for each trusted directory
56 static smartlist_t
*trusted_dir_servers
= NULL
;
58 /** List of for a given authority, and download status for latest certificate.
60 typedef struct cert_list_t
{
61 download_status_t dl_status
;
64 /** Map from v3 identity key digest to cert_list_t. */
65 static digestmap_t
*trusted_dir_certs
= NULL
;
66 /** True iff any key certificate in at least one member of
67 * <b>trusted_dir_certs</b> has changed since we last flushed the
68 * certificates to disk. */
69 static int trusted_dir_servers_certs_changed
= 0;
71 /** Global list of all of the routers that we know about. */
72 static routerlist_t
*routerlist
= NULL
;
74 /** List of strings for nicknames we've already warned about and that are
75 * still unknown / unavailable. */
76 static smartlist_t
*warned_nicknames
= NULL
;
78 /** The last time we tried to download any routerdesc, or 0 for "never". We
79 * use this to rate-limit download attempts when the number of routerdescs to
81 static time_t last_routerdesc_download_attempted
= 0;
83 /* DOCDOC This is a massive massive kludge XXXX021 */
84 static uint64_t sl_last_total_weighted_bw
= 0;
85 static uint64_t sl_last_weighted_bw_of_me
= 0;
87 /** Return the number of directory authorities whose type matches some bit set
90 get_n_authorities(authority_type_t type
)
93 if (!trusted_dir_servers
)
95 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
101 #define get_n_v2_authorities() get_n_authorities(V2_AUTHORITY)
103 /** Helper: Return the cert_list_t for an authority whose authority ID is
104 * <b>id_digest</b>, allocating a new list if necessary. */
106 get_cert_list(const char *id_digest
)
109 if (!trusted_dir_certs
)
110 trusted_dir_certs
= digestmap_new();
111 cl
= digestmap_get(trusted_dir_certs
, id_digest
);
113 cl
= tor_malloc_zero(sizeof(cert_list_t
));
114 cl
->certs
= smartlist_create();
115 digestmap_set(trusted_dir_certs
, id_digest
, cl
);
120 /** Reload the cached v3 key certificates from the cached-certs file in
121 * the data directory. Return 0 on success, -1 on failure. */
123 trusted_dirs_reload_certs(void)
129 filename
= get_datadir_fname("cached-certs");
130 contents
= read_file_to_str(filename
, RFTS_IGNORE_MISSING
, NULL
);
134 r
= trusted_dirs_load_certs_from_string(contents
, 1, 1);
139 /** Helper: return true iff we already have loaded the exact cert
142 already_have_cert(authority_cert_t
*cert
)
144 cert_list_t
*cl
= get_cert_list(cert
->cache_info
.identity_digest
);
146 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, c
,
148 if (!memcmp(c
->cache_info
.signed_descriptor_digest
,
149 cert
->cache_info
.signed_descriptor_digest
,
156 /** Load a bunch of new key certificates from the string <b>contents</b>. If
157 * <b>from_store</b> is true, the certificates are from the cache, and we
158 * don't need to flush them to disk. If <b>from_store</b> is false, we need
159 * to flush any changed certificates to disk. Return 0 on success, -1 on
162 trusted_dirs_load_certs_from_string(const char *contents
, int from_store
,
165 trusted_dir_server_t
*ds
;
168 for (s
= contents
; *s
; s
= eos
) {
169 authority_cert_t
*cert
= authority_cert_parse_from_string(s
, &eos
);
173 ds
= trusteddirserver_get_by_v3_auth_digest(
174 cert
->cache_info
.identity_digest
);
175 log_debug(LD_DIR
, "Parsed certificate for %s",
176 ds
? ds
->nickname
: "unknown authority");
178 if (already_have_cert(cert
)) {
179 /* we already have this one. continue. */
180 log_info(LD_DIR
, "Skipping %s certificate for %s that we "
182 from_store
? "cached" : "downloaded",
183 ds
? ds
->nickname
: "??");
184 authority_cert_free(cert
);
189 log_info(LD_DIR
, "Adding %s certificate for directory authority %s with "
190 "signing key %s", from_store
? "cached" : "downloaded",
191 ds
->nickname
, hex_str(cert
->signing_key_digest
,DIGEST_LEN
));
193 log_info(LD_DIR
, "Adding %s certificate for unrecognized directory "
194 "authority with signing key %s",
195 from_store
? "cached" : "downloaded",
196 hex_str(cert
->signing_key_digest
,DIGEST_LEN
));
199 cl
= get_cert_list(cert
->cache_info
.identity_digest
);
200 smartlist_add(cl
->certs
, cert
);
201 if (ds
&& cert
->cache_info
.published_on
> ds
->addr_current_at
) {
202 /* Check to see whether we should update our view of the authority's
204 if (cert
->addr
&& cert
->dir_port
&&
205 (ds
->addr
!= cert
->addr
||
206 ds
->dir_port
!= cert
->dir_port
)) {
207 char *a
= tor_dup_ip(cert
->addr
);
208 log_notice(LD_DIR
, "Updating address for directory authority %s "
209 "from %s:%d to %s:%d based on in certificate.",
210 ds
->nickname
, ds
->address
, (int)ds
->dir_port
,
213 ds
->addr
= cert
->addr
;
214 ds
->dir_port
= cert
->dir_port
;
216 ds
->addr_current_at
= cert
->cache_info
.published_on
;
220 trusted_dir_servers_certs_changed
= 1;
224 trusted_dirs_flush_certs_to_disk();
226 networkstatus_note_certs_arrived();
230 /** Save all v3 key certificates to the cached-certs file. */
232 trusted_dirs_flush_certs_to_disk(void)
237 if (!trusted_dir_servers_certs_changed
|| !trusted_dir_certs
)
240 chunks
= smartlist_create();
241 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
242 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
244 sized_chunk_t
*c
= tor_malloc(sizeof(sized_chunk_t
));
245 c
->bytes
= cert
->cache_info
.signed_descriptor_body
;
246 c
->len
= cert
->cache_info
.signed_descriptor_len
;
247 smartlist_add(chunks
, c
);
249 } DIGESTMAP_FOREACH_END
;
251 filename
= get_datadir_fname("cached-certs");
252 if (write_chunks_to_file(filename
, chunks
, 0)) {
253 log_warn(LD_FS
, "Error writing certificates to disk.");
256 SMARTLIST_FOREACH(chunks
, sized_chunk_t
*, c
, tor_free(c
));
257 smartlist_free(chunks
);
259 trusted_dir_servers_certs_changed
= 0;
262 /** Remove all v3 authority certificates that have been superseded for more
263 * than 48 hours. (If the most recent cert was published more than 48 hours
264 * ago, then we aren't going to get any consensuses signed with older
267 trusted_dirs_remove_old_certs(void)
269 #define OLD_CERT_LIFETIME (48*60*60)
270 if (!trusted_dir_certs
)
273 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
274 authority_cert_t
*newest
= NULL
;
275 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
276 if (!newest
|| (cert
->cache_info
.published_on
>
277 newest
->cache_info
.published_on
))
279 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
280 if (newest
&& (newest
->cache_info
.published_on
>
281 cert
->cache_info
.published_on
+ OLD_CERT_LIFETIME
)) {
282 SMARTLIST_DEL_CURRENT(cl
->certs
, cert
);
283 authority_cert_free(cert
);
284 trusted_dir_servers_certs_changed
= 1;
286 } DIGESTMAP_FOREACH_END
;
287 #undef OLD_CERT_LIFETIME
289 trusted_dirs_flush_certs_to_disk();
292 /** Return the newest v3 authority certificate whose v3 authority identity key
293 * has digest <b>id_digest</b>. Return NULL if no such authority is known,
294 * or it has no certificate. */
296 authority_cert_get_newest_by_id(const char *id_digest
)
299 authority_cert_t
*best
= NULL
;
300 if (!trusted_dir_certs
||
301 !(cl
= digestmap_get(trusted_dir_certs
, id_digest
)))
304 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
306 if (!best
|| cert
->cache_info
.published_on
> best
->cache_info
.published_on
)
312 /** Return the newest v3 authority certificate whose directory signing key has
313 * giest <sk_digest</b>. Return NULL if no such certificate is known.
316 authority_cert_get_by_sk_digest(const char *sk_digest
)
319 if (!trusted_dir_certs
)
322 if ((c
= get_my_v3_authority_cert()) &&
323 !memcmp(c
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
325 if ((c
= get_my_v3_legacy_cert()) &&
326 !memcmp(c
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
329 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
330 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
332 if (!memcmp(cert
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
335 } DIGESTMAP_FOREACH_END
;
339 /** Return the v3 authority certificate with signing key matching
340 * <b>sk_digest</b>, for the authority with identity digest <b>id_digest</b>.
341 * Return NULL if no such authority is known. */
343 authority_cert_get_by_digests(const char *id_digest
,
344 const char *sk_digest
)
347 if (!trusted_dir_certs
||
348 !(cl
= digestmap_get(trusted_dir_certs
, id_digest
)))
350 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
351 if (!memcmp(cert
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
357 /** Add every known authority_cert_t to <b>certs_out</b>. */
359 authority_cert_get_all(smartlist_t
*certs_out
)
361 tor_assert(certs_out
);
362 if (!trusted_dir_certs
)
365 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
366 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, c
,
367 smartlist_add(certs_out
, c
));
368 } DIGESTMAP_FOREACH_END
;
371 /** Called when an attempt to download a certificate with the authority with
372 * ID <b>id_digest</b> fails with HTTP response code <b>status</b>: remember
373 * the failure, so we don't try again immediately. */
375 authority_cert_dl_failed(const char *id_digest
, int status
)
378 if (!trusted_dir_certs
||
379 !(cl
= digestmap_get(trusted_dir_certs
, id_digest
)))
382 download_status_failed(&cl
->dl_status
, status
);
385 /** How many times will we try to fetch a certificate before giving up? */
386 #define MAX_CERT_DL_FAILURES 8
388 /** Try to download any v3 authority certificates that we may be missing. If
389 * <b>status</b> is provided, try to get all the ones that were used to sign
390 * <b>status</b>. Additionally, try to have a non-expired certificate for
391 * every V3 authority in trusted_dir_servers. Don't fetch certificates we
395 authority_certs_fetch_missing(networkstatus_t
*status
, time_t now
)
397 digestmap_t
*pending
;
398 smartlist_t
*missing_digests
;
399 char *resource
= NULL
;
401 const int cache
= directory_caches_dir_info(get_options());
403 if (should_delay_dir_fetches(get_options()))
406 pending
= digestmap_new();
407 missing_digests
= smartlist_create();
409 list_pending_downloads(pending
, DIR_PURPOSE_FETCH_CERTIFICATE
, "fp/");
411 SMARTLIST_FOREACH(status
->voters
, networkstatus_voter_info_t
*, voter
,
413 if (tor_digest_is_zero(voter
->signing_key_digest
))
414 continue; /* This authority never signed this consensus, so don't
415 * go looking for a cert with key digest 0000000000. */
417 !trusteddirserver_get_by_v3_auth_digest(voter
->identity_digest
))
418 continue; /* We are not a cache, and we don't know this authority.*/
419 cl
= get_cert_list(voter
->identity_digest
);
420 if (authority_cert_get_by_digests(voter
->identity_digest
,
421 voter
->signing_key_digest
)) {
422 download_status_reset(&cl
->dl_status
);
425 if (download_status_is_ready(&cl
->dl_status
, now
,
426 MAX_CERT_DL_FAILURES
)) {
427 log_notice(LD_DIR
, "We're missing a certificate from authority "
428 "with signing key %s: launching request.",
429 hex_str(voter
->signing_key_digest
, DIGEST_LEN
));
430 smartlist_add(missing_digests
, voter
->identity_digest
);
434 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
437 if (!(ds
->type
& V3_AUTHORITY
))
439 if (smartlist_digest_isin(missing_digests
, ds
->v3_identity_digest
))
441 cl
= get_cert_list(ds
->v3_identity_digest
);
442 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
444 if (!ftime_definitely_after(now
, cert
->expires
)) {
445 /* It's not expired, and we weren't looking for something to
446 * verify a consensus with. Call it done. */
447 download_status_reset(&cl
->dl_status
);
452 if (!found
&& download_status_is_ready(&cl
->dl_status
, now
,
453 MAX_CERT_DL_FAILURES
)) {
454 log_notice(LD_DIR
, "No current certificate known for authority %s; "
455 "launching request.", ds
->nickname
);
456 smartlist_add(missing_digests
, ds
->v3_identity_digest
);
460 if (!smartlist_len(missing_digests
)) {
463 smartlist_t
*fps
= smartlist_create();
464 smartlist_add(fps
, tor_strdup("fp/"));
465 SMARTLIST_FOREACH(missing_digests
, const char *, d
, {
467 if (digestmap_get(pending
, d
))
469 fp
= tor_malloc(HEX_DIGEST_LEN
+2);
470 base16_encode(fp
, HEX_DIGEST_LEN
+1, d
, DIGEST_LEN
);
471 fp
[HEX_DIGEST_LEN
] = '+';
472 fp
[HEX_DIGEST_LEN
+1] = '\0';
473 smartlist_add(fps
, fp
);
475 if (smartlist_len(fps
) == 1) {
476 /* we didn't add any: they were all pending */
477 SMARTLIST_FOREACH(fps
, char *, cp
, tor_free(cp
));
481 resource
= smartlist_join_strings(fps
, "", 0, NULL
);
482 resource
[strlen(resource
)-1] = '\0';
483 SMARTLIST_FOREACH(fps
, char *, cp
, tor_free(cp
));
486 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CERTIFICATE
, 0,
491 smartlist_free(missing_digests
);
492 digestmap_free(pending
, NULL
);
495 /* Router descriptor storage.
497 * Routerdescs are stored in a big file, named "cached-descriptors". As new
498 * routerdescs arrive, we append them to a journal file named
499 * "cached-descriptors.new".
501 * From time to time, we replace "cached-descriptors" with a new file
502 * containing only the live, non-superseded descriptors, and clear
503 * cached-routers.new.
505 * On startup, we read both files.
508 /** Helper: return 1 iff the router log is so big we want to rebuild the
511 router_should_rebuild_store(desc_store_t
*store
)
513 if (store
->store_len
> (1<<16))
514 return (store
->journal_len
> store
->store_len
/ 2 ||
515 store
->bytes_dropped
> store
->store_len
/ 2);
517 return store
->journal_len
> (1<<15);
520 static INLINE desc_store_t
*
521 desc_get_store(routerlist_t
*rl
, signed_descriptor_t
*sd
)
523 if (sd
->is_extrainfo
)
524 return &rl
->extrainfo_store
;
526 return &rl
->desc_store
;
529 /** Add the signed_descriptor_t in <b>desc</b> to the router
530 * journal; change its saved_location to SAVED_IN_JOURNAL and set its
531 * offset appropriately. */
533 signed_desc_append_to_journal(signed_descriptor_t
*desc
,
536 char *fname
= get_datadir_fname_suffix(store
->fname_base
, ".new");
537 const char *body
= signed_descriptor_get_body_impl(desc
,1);
538 size_t len
= desc
->signed_descriptor_len
+ desc
->annotations_len
;
540 tor_assert(len
== strlen(body
));
542 if (append_bytes_to_file(fname
, body
, len
, 1)) {
543 log_warn(LD_FS
, "Unable to store router descriptor");
547 desc
->saved_location
= SAVED_IN_JOURNAL
;
550 desc
->saved_offset
= store
->journal_len
;
551 store
->journal_len
+= len
;
556 /** Sorting helper: return <0, 0, or >0 depending on whether the
557 * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
558 * the signed_descriptor_t* in *<b>b</b>. */
560 _compare_signed_descriptors_by_age(const void **_a
, const void **_b
)
562 const signed_descriptor_t
*r1
= *_a
, *r2
= *_b
;
563 return (int)(r1
->published_on
- r2
->published_on
);
567 #define RRS_DONT_REMOVE_OLD 2
569 /** If the journal is too long, or if RRS_FORCE is set in <b>flags</b>, then
570 * atomically replace the router store with the routers currently in our
571 * routerlist, and clear the journal. Return 0 on success, -1 on failure.
573 * If <b>extrainfo</b> is true, rebuild the extrainfo store; else rebuild the
574 * router descriptor store. [XXX021 this sentence refers to bad args]
577 router_rebuild_store(int flags
, desc_store_t
*store
)
579 smartlist_t
*chunk_list
= NULL
;
580 char *fname
= NULL
, *fname_tmp
= NULL
;
583 smartlist_t
*signed_descriptors
= NULL
;
585 size_t total_expected_len
= 0;
587 int force
= flags
& RRS_FORCE
;
589 if (!force
&& !router_should_rebuild_store(store
))
594 if (store
->type
== EXTRAINFO_STORE
)
595 had_any
= !eimap_isempty(routerlist
->extra_info_map
);
597 had_any
= (smartlist_len(routerlist
->routers
)+
598 smartlist_len(routerlist
->old_routers
))>0;
600 /* Don't save deadweight. */
601 if (!(flags
& RRS_DONT_REMOVE_OLD
))
602 routerlist_remove_old_routers();
604 log_info(LD_DIR
, "Rebuilding %s cache", store
->description
);
606 fname
= get_datadir_fname(store
->fname_base
);
607 fname_tmp
= get_datadir_fname_suffix(store
->fname_base
, ".tmp");
609 chunk_list
= smartlist_create();
611 /* We sort the routers by age to enhance locality on disk. */
612 signed_descriptors
= smartlist_create();
613 if (store
->type
== EXTRAINFO_STORE
) {
615 for (iter
= eimap_iter_init(routerlist
->extra_info_map
);
616 !eimap_iter_done(iter
);
617 iter
= eimap_iter_next(routerlist
->extra_info_map
, iter
)) {
620 eimap_iter_get(iter
, &key
, &ei
);
621 smartlist_add(signed_descriptors
, &ei
->cache_info
);
624 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
,
625 smartlist_add(signed_descriptors
, sd
));
626 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
627 smartlist_add(signed_descriptors
, &ri
->cache_info
));
630 smartlist_sort(signed_descriptors
, _compare_signed_descriptors_by_age
);
632 /* Now, add the appropriate members to chunk_list */
633 SMARTLIST_FOREACH(signed_descriptors
, signed_descriptor_t
*, sd
,
636 const char *body
= signed_descriptor_get_body_impl(sd
, 1);
638 log_warn(LD_BUG
, "No descriptor available for router.");
641 if (sd
->do_not_cache
) {
645 c
= tor_malloc(sizeof(sized_chunk_t
));
647 c
->len
= sd
->signed_descriptor_len
+ sd
->annotations_len
;
648 total_expected_len
+= c
->len
;
649 smartlist_add(chunk_list
, c
);
652 if (write_chunks_to_file(fname_tmp
, chunk_list
, 1)<0) {
653 log_warn(LD_FS
, "Error writing router store to disk.");
657 /* Our mmap is now invalid. */
659 tor_munmap_file(store
->mmap
);
663 if (replace_file(fname_tmp
, fname
)<0) {
664 log_warn(LD_FS
, "Error replacing old router store: %s", strerror(errno
));
669 store
->mmap
= tor_mmap_file(fname
);
671 if (errno
== ERANGE
) {
673 if (total_expected_len
) {
674 log_warn(LD_FS
, "We wrote some bytes to a new descriptor file at '%s',"
675 " but when we went to mmap it, it was empty!", fname
);
676 } else if (had_any
) {
677 log_info(LD_FS
, "We just removed every descriptor in '%s'. This is "
678 "okay if we're just starting up after a long time. "
679 "Otherwise, it's a bug.", fname
);
682 log_warn(LD_FS
, "Unable to mmap new descriptor file at '%s'.",fname
);
686 log_info(LD_DIR
, "Reconstructing pointers into cache");
689 SMARTLIST_FOREACH(signed_descriptors
, signed_descriptor_t
*, sd
,
691 if (sd
->do_not_cache
)
693 sd
->saved_location
= SAVED_IN_CACHE
;
695 tor_free(sd
->signed_descriptor_body
); // sets it to null
696 sd
->saved_offset
= offset
;
698 offset
+= sd
->signed_descriptor_len
+ sd
->annotations_len
;
699 signed_descriptor_get_body(sd
); /* reconstruct and assert */
703 fname
= get_datadir_fname_suffix(store
->fname_base
, ".new");
704 write_str_to_file(fname
, "", 1);
707 store
->store_len
= (size_t) offset
;
708 store
->journal_len
= 0;
709 store
->bytes_dropped
= 0;
711 if (signed_descriptors
)
712 smartlist_free(signed_descriptors
);
715 SMARTLIST_FOREACH(chunk_list
, sized_chunk_t
*, c
, tor_free(c
));
716 smartlist_free(chunk_list
);
721 /** Helper: Reload a cache file and its associated journal, setting metadata
722 * appropriately. If <b>extrainfo</b> is true, reload the extrainfo store;
723 * else reload the router descriptor store. */
725 router_reload_router_list_impl(desc_store_t
*store
)
727 char *fname
= NULL
, *altname
= NULL
, *contents
= NULL
;
729 int read_from_old_location
= 0;
730 int extrainfo
= (store
->type
== EXTRAINFO_STORE
);
731 time_t now
= time(NULL
);
732 store
->journal_len
= store
->store_len
= 0;
734 fname
= get_datadir_fname(store
->fname_base
);
735 if (store
->fname_alt_base
)
736 altname
= get_datadir_fname(store
->fname_alt_base
);
738 if (store
->mmap
) /* get rid of it first */
739 tor_munmap_file(store
->mmap
);
742 store
->mmap
= tor_mmap_file(fname
);
743 if (!store
->mmap
&& altname
&& file_status(altname
) == FN_FILE
) {
744 read_from_old_location
= 1;
745 log_notice(LD_DIR
, "Couldn't read %s; trying to load routers from old "
746 "location %s.", fname
, altname
);
747 if ((store
->mmap
= tor_mmap_file(altname
)))
748 read_from_old_location
= 1;
750 if (altname
&& !read_from_old_location
) {
751 remove_file_if_very_old(altname
, now
);
754 store
->store_len
= store
->mmap
->size
;
756 router_load_extrainfo_from_string(store
->mmap
->data
,
757 store
->mmap
->data
+store
->mmap
->size
,
758 SAVED_IN_CACHE
, NULL
, 0);
760 router_load_routers_from_string(store
->mmap
->data
,
761 store
->mmap
->data
+store
->mmap
->size
,
762 SAVED_IN_CACHE
, NULL
, 0, NULL
);
766 fname
= get_datadir_fname_suffix(store
->fname_base
, ".new");
767 if (file_status(fname
) == FN_FILE
)
768 contents
= read_file_to_str(fname
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
769 if (read_from_old_location
) {
771 altname
= get_datadir_fname_suffix(store
->fname_alt_base
, ".new");
773 contents
= read_file_to_str(altname
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
775 remove_file_if_very_old(altname
, now
);
779 router_load_extrainfo_from_string(contents
, NULL
,SAVED_IN_JOURNAL
,
782 router_load_routers_from_string(contents
, NULL
, SAVED_IN_JOURNAL
,
784 store
->journal_len
= (size_t) st
.st_size
;
791 if (store
->journal_len
|| read_from_old_location
) {
792 /* Always clear the journal on startup.*/
793 router_rebuild_store(RRS_FORCE
, store
);
794 } else if (!extrainfo
) {
795 /* Don't cache expired routers. (This is in an else because
796 * router_rebuild_store() also calls remove_old_routers().) */
797 routerlist_remove_old_routers();
803 /** Load all cached router descriptors and extra-info documents from the
804 * store. Return 0 on success and -1 on failure.
807 router_reload_router_list(void)
809 routerlist_t
*rl
= router_get_routerlist();
810 if (router_reload_router_list_impl(&rl
->desc_store
))
812 if (router_reload_router_list_impl(&rl
->extrainfo_store
))
817 /** Return a smartlist containing a list of trusted_dir_server_t * for all
818 * known trusted dirservers. Callers must not modify the list or its
822 router_get_trusted_dir_servers(void)
824 if (!trusted_dir_servers
)
825 trusted_dir_servers
= smartlist_create();
827 return trusted_dir_servers
;
830 /** Try to find a running dirserver that supports operations of <b>type</b>.
832 * If there are no running dirservers in our routerlist and the
833 * <b>PDS_RETRY_IF_NO_SERVERS</b> flag is set, set all the authoritative ones
834 * as running again, and pick one.
836 * If the <b>PDS_IGNORE_FASCISTFIREWALL</b> flag is set, then include
837 * dirservers that we can't reach.
839 * If the <b>PDS_ALLOW_SELF</b> flag is not set, then don't include ourself
840 * (if we're a dirserver).
842 * Don't pick an authority if any non-authority is viable; try to avoid using
843 * servers that have returned 503 recently.
846 router_pick_directory_server(authority_type_t type
, int flags
)
848 routerstatus_t
*choice
;
849 if (get_options()->PreferTunneledDirConns
)
850 flags
|= _PDS_PREFER_TUNNELED_DIR_CONNS
;
855 choice
= router_pick_directory_server_impl(type
, flags
);
856 if (choice
|| !(flags
& PDS_RETRY_IF_NO_SERVERS
))
860 "No reachable router entries for dirservers. "
861 "Trying them all again.");
862 /* mark all authdirservers as up again */
863 mark_all_trusteddirservers_up();
865 choice
= router_pick_directory_server_impl(type
, flags
);
871 router_get_my_share_of_directory_requests(double *v2_share_out
,
872 double *v3_share_out
)
874 routerinfo_t
*me
= router_get_my_routerinfo();
876 const int pds_flags
= PDS_ALLOW_SELF
|PDS_IGNORE_FASCISTFIREWALL
;
877 *v2_share_out
= *v3_share_out
= 0.0;
880 rs
= router_get_consensus_status_by_id(me
->cache_info
.identity_digest
);
884 /* Calling for side effect */
886 sl_last_total_weighted_bw
= 0;
887 router_pick_directory_server(V2_AUTHORITY
, pds_flags
);
888 if (sl_last_total_weighted_bw
!= 0) {
889 *v2_share_out
= U64_TO_DBL(sl_last_weighted_bw_of_me
) /
890 U64_TO_DBL(sl_last_total_weighted_bw
);
894 if (rs
->version_supports_v3_dir
) {
895 sl_last_total_weighted_bw
= 0;
896 router_pick_directory_server(V3_AUTHORITY
, pds_flags
);
897 if (sl_last_total_weighted_bw
!= 0) {
898 *v3_share_out
= U64_TO_DBL(sl_last_weighted_bw_of_me
) /
899 U64_TO_DBL(sl_last_total_weighted_bw
);
906 /** Return the trusted_dir_server_t for the directory authority whose identity
907 * key hashes to <b>digest</b>, or NULL if no such authority is known.
909 trusted_dir_server_t
*
910 router_get_trusteddirserver_by_digest(const char *digest
)
912 if (!trusted_dir_servers
)
915 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
917 if (!memcmp(ds
->digest
, digest
, DIGEST_LEN
))
924 /** Return the trusted_dir_server_t for the directory authority whose identity
925 * key hashes to <b>digest</b>, or NULL if no such authority is known.
927 trusted_dir_server_t
*
928 trusteddirserver_get_by_v3_auth_digest(const char *digest
)
930 if (!trusted_dir_servers
)
933 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
935 if (!memcmp(ds
->v3_identity_digest
, digest
, DIGEST_LEN
) &&
936 (ds
->type
& V3_AUTHORITY
))
943 /** Try to find a running trusted dirserver. Flags are as for
944 * router_pick_directory_server.
947 router_pick_trusteddirserver(authority_type_t type
, int flags
)
949 routerstatus_t
*choice
;
950 if (get_options()->PreferTunneledDirConns
)
951 flags
|= _PDS_PREFER_TUNNELED_DIR_CONNS
;
953 choice
= router_pick_trusteddirserver_impl(type
, flags
);
954 if (choice
|| !(flags
& PDS_RETRY_IF_NO_SERVERS
))
958 "No trusted dirservers are reachable. Trying them all again.");
959 mark_all_trusteddirservers_up();
960 return router_pick_trusteddirserver_impl(type
, flags
);
963 /** How long do we avoid using a directory server after it's given us a 503? */
964 #define DIR_503_TIMEOUT (60*60)
966 /** Pick a random running valid directory server/mirror from our
967 * routerlist. Arguments are as for router_pick_directory_server(), except
968 * that RETRY_IF_NO_SERVERS is ignored, and:
970 * If the _PDS_PREFER_TUNNELED_DIR_CONNS flag is set, prefer directory servers
971 * that we can use with BEGINDIR.
973 static routerstatus_t
*
974 router_pick_directory_server_impl(authority_type_t type
, int flags
)
976 routerstatus_t
*result
;
977 smartlist_t
*direct
, *tunnel
;
978 smartlist_t
*trusted_direct
, *trusted_tunnel
;
979 smartlist_t
*overloaded_direct
, *overloaded_tunnel
;
980 time_t now
= time(NULL
);
981 const networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
982 int requireother
= ! (flags
& PDS_ALLOW_SELF
);
983 int fascistfirewall
= ! (flags
& PDS_IGNORE_FASCISTFIREWALL
);
984 int prefer_tunnel
= (flags
& _PDS_PREFER_TUNNELED_DIR_CONNS
);
989 direct
= smartlist_create();
990 tunnel
= smartlist_create();
991 trusted_direct
= smartlist_create();
992 trusted_tunnel
= smartlist_create();
993 overloaded_direct
= smartlist_create();
994 overloaded_tunnel
= smartlist_create();
996 /* Find all the running dirservers we know about. */
997 SMARTLIST_FOREACH_BEGIN(consensus
->routerstatus_list
, routerstatus_t
*,
1000 int is_overloaded
= status
->last_dir_503_at
+ DIR_503_TIMEOUT
> now
;
1002 if (!status
->is_running
|| !status
->dir_port
|| !status
->is_valid
)
1004 if (status
->is_bad_directory
)
1006 if (requireother
&& router_digest_is_me(status
->identity_digest
))
1008 if (type
& V3_AUTHORITY
) {
1009 if (!(status
->version_supports_v3_dir
||
1010 router_digest_is_trusted_dir_type(status
->identity_digest
,
1014 is_trusted
= router_digest_is_trusted_dir(status
->identity_digest
);
1015 if ((type
& V2_AUTHORITY
) && !(status
->is_v2_dir
|| is_trusted
))
1017 if ((type
& EXTRAINFO_CACHE
) &&
1018 !router_supports_extrainfo(status
->identity_digest
, 0))
1021 /* XXXX021 IP6 proposal 118 */
1022 tor_addr_from_ipv4h(&addr
, status
->addr
);
1024 if (prefer_tunnel
&&
1025 status
->version_supports_begindir
&&
1026 (!fascistfirewall
||
1027 fascist_firewall_allows_address_or(&addr
, status
->or_port
)))
1028 smartlist_add(is_trusted
? trusted_tunnel
:
1029 is_overloaded
? overloaded_tunnel
: tunnel
, status
);
1030 else if (!fascistfirewall
||
1031 fascist_firewall_allows_address_dir(&addr
, status
->dir_port
))
1032 smartlist_add(is_trusted
? trusted_direct
:
1033 is_overloaded
? overloaded_direct
: direct
, status
);
1034 } SMARTLIST_FOREACH_END(status
);
1036 if (smartlist_len(tunnel
)) {
1037 result
= routerstatus_sl_choose_by_bandwidth(tunnel
);
1038 } else if (smartlist_len(overloaded_tunnel
)) {
1039 result
= routerstatus_sl_choose_by_bandwidth(overloaded_tunnel
);
1040 } else if (smartlist_len(trusted_tunnel
)) {
1041 /* FFFF We don't distinguish between trusteds and overloaded trusteds
1042 * yet. Maybe one day we should. */
1043 /* FFFF We also don't load balance over authorities yet. I think this
1044 * is a feature, but it could easily be a bug. -RD */
1045 result
= smartlist_choose(trusted_tunnel
);
1046 } else if (smartlist_len(direct
)) {
1047 result
= routerstatus_sl_choose_by_bandwidth(direct
);
1048 } else if (smartlist_len(overloaded_direct
)) {
1049 result
= routerstatus_sl_choose_by_bandwidth(overloaded_direct
);
1051 result
= smartlist_choose(trusted_direct
);
1053 smartlist_free(direct
);
1054 smartlist_free(tunnel
);
1055 smartlist_free(trusted_direct
);
1056 smartlist_free(trusted_tunnel
);
1057 smartlist_free(overloaded_direct
);
1058 smartlist_free(overloaded_tunnel
);
1062 /** Choose randomly from among the trusted dirservers that are up. Flags
1063 * are as for router_pick_directory_server_impl().
1065 static routerstatus_t
*
1066 router_pick_trusteddirserver_impl(authority_type_t type
, int flags
)
1068 smartlist_t
*direct
, *tunnel
;
1069 smartlist_t
*overloaded_direct
, *overloaded_tunnel
;
1070 routerinfo_t
*me
= router_get_my_routerinfo();
1071 routerstatus_t
*result
;
1072 time_t now
= time(NULL
);
1073 int requireother
= ! (flags
& PDS_ALLOW_SELF
);
1074 int fascistfirewall
= ! (flags
& PDS_IGNORE_FASCISTFIREWALL
);
1075 int prefer_tunnel
= (flags
& _PDS_PREFER_TUNNELED_DIR_CONNS
);
1077 if (!trusted_dir_servers
)
1080 direct
= smartlist_create();
1081 tunnel
= smartlist_create();
1082 overloaded_direct
= smartlist_create();
1083 overloaded_tunnel
= smartlist_create();
1085 SMARTLIST_FOREACH_BEGIN(trusted_dir_servers
, trusted_dir_server_t
*, d
)
1088 d
->fake_status
.last_dir_503_at
+ DIR_503_TIMEOUT
> now
;
1090 if (!d
->is_running
) continue;
1091 if ((type
& d
->type
) == 0)
1093 if ((type
& EXTRAINFO_CACHE
) &&
1094 !router_supports_extrainfo(d
->digest
, 1))
1096 if (requireother
&& me
&& router_digest_is_me(d
->digest
))
1099 /* XXXX021 IP6 proposal 118 */
1100 tor_addr_from_ipv4h(&addr
, d
->addr
);
1102 if (prefer_tunnel
&&
1104 (!fascistfirewall
||
1105 fascist_firewall_allows_address_or(&addr
, d
->or_port
)))
1106 smartlist_add(is_overloaded
? overloaded_tunnel
: tunnel
,
1108 else if (!fascistfirewall
||
1109 fascist_firewall_allows_address_dir(&addr
, d
->dir_port
))
1110 smartlist_add(is_overloaded
? overloaded_direct
: direct
,
1113 SMARTLIST_FOREACH_END(d
);
1115 if (smartlist_len(tunnel
)) {
1116 result
= smartlist_choose(tunnel
);
1117 } else if (smartlist_len(overloaded_tunnel
)) {
1118 result
= smartlist_choose(overloaded_tunnel
);
1119 } else if (smartlist_len(direct
)) {
1120 result
= smartlist_choose(direct
);
1122 result
= smartlist_choose(overloaded_direct
);
1125 smartlist_free(direct
);
1126 smartlist_free(tunnel
);
1127 smartlist_free(overloaded_direct
);
1128 smartlist_free(overloaded_tunnel
);
1132 /** Go through and mark the authoritative dirservers as up. */
1134 mark_all_trusteddirservers_up(void)
1137 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1138 if (router_digest_is_trusted_dir(router
->cache_info
.identity_digest
) &&
1139 router
->dir_port
> 0) {
1140 router
->is_running
= 1;
1143 if (trusted_dir_servers
) {
1144 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, dir
,
1147 dir
->is_running
= 1;
1148 download_status_reset(&dir
->v2_ns_dl_status
);
1149 rs
= router_get_consensus_status_by_id(dir
->digest
);
1150 if (rs
&& !rs
->is_running
) {
1152 rs
->last_dir_503_at
= 0;
1153 control_event_networkstatus_changed_single(rs
);
1157 router_dir_info_changed();
1160 /** Reset all internal variables used to count failed downloads of network
1161 * status objects. */
1163 router_reset_status_download_failures(void)
1165 mark_all_trusteddirservers_up();
1168 /** Return true iff router1 and router2 have the same /16 network. */
1170 routers_in_same_network_family(routerinfo_t
*r1
, routerinfo_t
*r2
)
1172 return (r1
->addr
& 0xffff0000) == (r2
->addr
& 0xffff0000);
1175 /** Look through the routerlist and identify routers that
1176 * advertise the same /16 network address as <b>router</b>.
1177 * Add each of them to <b>sl</b>.
1180 routerlist_add_network_family(smartlist_t
*sl
, routerinfo_t
*router
)
1182 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, r
,
1184 if (router
!= r
&& routers_in_same_network_family(router
, r
))
1185 smartlist_add(sl
, r
);
1189 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
1190 * This is used to make sure we don't pick siblings in a single path.
1193 routerlist_add_family(smartlist_t
*sl
, routerinfo_t
*router
)
1197 or_options_t
*options
= get_options();
1199 /* First, add any routers with similar network addresses. */
1200 if (options
->EnforceDistinctSubnets
)
1201 routerlist_add_network_family(sl
, router
);
1203 if (router
->declared_family
) {
1204 /* Add every r such that router declares familyness with r, and r
1205 * declares familyhood with router. */
1206 SMARTLIST_FOREACH(router
->declared_family
, const char *, n
,
1208 if (!(r
= router_get_by_nickname(n
, 0)))
1210 if (!r
->declared_family
)
1212 SMARTLIST_FOREACH(r
->declared_family
, const char *, n2
,
1214 if (router_nickname_matches(router
, n2
))
1215 smartlist_add(sl
, r
);
1220 /* If the user declared any families locally, honor those too. */
1221 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
1222 if (router_nickname_is_in_list(router
, cl
->value
)) {
1223 add_nickname_list_to_smartlist(sl
, cl
->value
, 0);
1228 /** Return true iff r is named by some nickname in <b>lst</b>. */
1230 router_in_nickname_smartlist(smartlist_t
*lst
, routerinfo_t
*r
)
1233 SMARTLIST_FOREACH(lst
, const char *, name
,
1234 if (router_nickname_matches(r
, name
))
1239 /** Return true iff r1 and r2 are in the same family, but not the same
1242 routers_in_same_family(routerinfo_t
*r1
, routerinfo_t
*r2
)
1244 or_options_t
*options
= get_options();
1247 if (options
->EnforceDistinctSubnets
&& routers_in_same_network_family(r1
,r2
))
1250 if (router_in_nickname_smartlist(r1
->declared_family
, r2
) &&
1251 router_in_nickname_smartlist(r2
->declared_family
, r1
))
1254 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
1255 if (router_nickname_is_in_list(r1
, cl
->value
) &&
1256 router_nickname_is_in_list(r2
, cl
->value
))
1262 /** Given a (possibly NULL) comma-and-whitespace separated list of nicknames,
1263 * see which nicknames in <b>list</b> name routers in our routerlist, and add
1264 * the routerinfos for those routers to <b>sl</b>. If <b>must_be_running</b>,
1265 * only include routers that we think are running.
1266 * Warn if any non-Named routers are specified by nickname.
1269 add_nickname_list_to_smartlist(smartlist_t
*sl
, const char *list
,
1270 int must_be_running
)
1272 routerinfo_t
*router
;
1273 smartlist_t
*nickname_list
;
1274 int have_dir_info
= router_have_minimum_dir_info();
1277 return; /* nothing to do */
1280 nickname_list
= smartlist_create();
1281 if (!warned_nicknames
)
1282 warned_nicknames
= smartlist_create();
1284 smartlist_split_string(nickname_list
, list
, ",",
1285 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1287 SMARTLIST_FOREACH(nickname_list
, const char *, nick
, {
1289 if (!is_legal_nickname_or_hexdigest(nick
)) {
1290 log_warn(LD_CONFIG
, "Nickname '%s' is misformed; skipping", nick
);
1293 router
= router_get_by_nickname(nick
, 1);
1294 warned
= smartlist_string_isin(warned_nicknames
, nick
);
1296 if (!must_be_running
|| router
->is_running
) {
1297 smartlist_add(sl
,router
);
1299 } else if (!router_get_consensus_status_by_nickname(nick
,1)) {
1301 log_fn(have_dir_info
? LOG_WARN
: LOG_INFO
, LD_CONFIG
,
1302 "Nickname list includes '%s' which isn't a known router.",nick
);
1303 smartlist_add(warned_nicknames
, tor_strdup(nick
));
1307 SMARTLIST_FOREACH(nickname_list
, char *, nick
, tor_free(nick
));
1308 smartlist_free(nickname_list
);
1311 /** Return 1 iff any member of the (possibly NULL) comma-separated list
1312 * <b>list</b> is an acceptable nickname or hexdigest for <b>router</b>. Else
1316 router_nickname_is_in_list(routerinfo_t
*router
, const char *list
)
1318 smartlist_t
*nickname_list
;
1322 return 0; /* definitely not */
1325 nickname_list
= smartlist_create();
1326 smartlist_split_string(nickname_list
, list
, ",",
1327 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1328 SMARTLIST_FOREACH(nickname_list
, const char *, cp
,
1329 if (router_nickname_matches(router
, cp
)) {v
=1;break;});
1330 SMARTLIST_FOREACH(nickname_list
, char *, cp
, tor_free(cp
));
1331 smartlist_free(nickname_list
);
1335 /** Add every suitable router from our routerlist to <b>sl</b>, so that
1336 * we can pick a node for a circuit.
1339 router_add_running_routers_to_smartlist(smartlist_t
*sl
, int allow_invalid
,
1340 int need_uptime
, int need_capacity
,
1346 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1348 if (router
->is_running
&&
1349 router
->purpose
== ROUTER_PURPOSE_GENERAL
&&
1350 (router
->is_valid
|| allow_invalid
) &&
1351 !router_is_unreliable(router
, need_uptime
,
1352 need_capacity
, need_guard
)) {
1353 /* If it's running, and it's suitable according to the
1354 * other flags we had in mind */
1355 smartlist_add(sl
, router
);
1360 /** Look through the routerlist until we find a router that has my key.
1363 routerlist_find_my_routerinfo(void)
1368 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1370 if (router_is_me(router
))
1376 /** Find a router that's up, that has this IP address, and
1377 * that allows exit to this address:port, or return NULL if there
1381 router_find_exact_exit_enclave(const char *address
, uint16_t port
)
1386 if (!tor_inet_aton(address
, &in
))
1387 return NULL
; /* it's not an IP already */
1388 addr
= ntohl(in
.s_addr
);
1390 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1392 if (router
->is_running
&&
1393 router
->addr
== addr
&&
1394 compare_addr_to_addr_policy(addr
, port
, router
->exit_policy
) ==
1395 ADDR_POLICY_ACCEPTED
)
1401 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1402 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1403 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1405 * If <b>need_guard</b>, we require that the router is a possible entry guard.
1408 router_is_unreliable(routerinfo_t
*router
, int need_uptime
,
1409 int need_capacity
, int need_guard
)
1411 if (need_uptime
&& !router
->is_stable
)
1413 if (need_capacity
&& !router
->is_fast
)
1415 if (need_guard
&& !router
->is_possible_guard
)
1420 /** Return the smaller of the router's configured BandwidthRate
1421 * and its advertised capacity. */
1423 router_get_advertised_bandwidth(routerinfo_t
*router
)
1425 if (router
->bandwidthcapacity
< router
->bandwidthrate
)
1426 return router
->bandwidthcapacity
;
1427 return router
->bandwidthrate
;
1430 /** Do not weight any declared bandwidth more than this much when picking
1431 * routers by bandwidth. */
1432 #define DEFAULT_MAX_BELIEVABLE_BANDWIDTH 10000000 /* 10 MB/sec */
1434 /** Return the smaller of the router's configured BandwidthRate
1435 * and its advertised capacity, capped by max-believe-bw. */
1437 router_get_advertised_bandwidth_capped(routerinfo_t
*router
)
1439 uint32_t result
= router
->bandwidthcapacity
;
1440 if (result
> router
->bandwidthrate
)
1441 result
= router
->bandwidthrate
;
1442 if (result
> DEFAULT_MAX_BELIEVABLE_BANDWIDTH
)
1443 result
= DEFAULT_MAX_BELIEVABLE_BANDWIDTH
;
1447 /** Eventually, the number we return will come from the directory
1448 * consensus, so clients can dynamically update to better numbers.
1450 * But for now, or in case there is no consensus available, just return
1451 * a sufficient default. */
1453 get_max_believable_bandwidth(void)
1455 return DEFAULT_MAX_BELIEVABLE_BANDWIDTH
;
1458 /** Helper function:
1459 * choose a random element of smartlist <b>sl</b>, weighted by
1460 * the advertised bandwidth of each element.
1462 * If <b>statuses</b> is zero, then <b>sl</b> is a list of
1463 * routerinfo_t's. Otherwise it's a list of routerstatus_t's.
1465 * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
1466 * nodes' bandwidth equally regardless of their Exit status, since there may
1467 * be some in the list because they exit to obscure ports. If
1468 * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
1469 * exit-node's bandwidth less depending on the smallness of the fraction of
1470 * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
1471 * guard node: consider all guard's bandwidth equally. Otherwise, weight
1472 * guards proportionally less.
1475 smartlist_choose_by_bandwidth(smartlist_t
*sl
, bandwidth_weight_rule_t rule
,
1479 routerinfo_t
*router
;
1480 routerstatus_t
*status
=NULL
;
1481 int32_t *bandwidths
;
1484 uint64_t total_nonexit_bw
= 0, total_exit_bw
= 0, total_bw
= 0;
1485 uint64_t total_nonguard_bw
= 0, total_guard_bw
= 0;
1486 uint64_t rand_bw
, tmp
;
1488 double guard_weight
;
1490 bitarray_t
*exit_bits
;
1491 bitarray_t
*guard_bits
;
1492 uint32_t max_believable_bw
= get_max_believable_bandwidth();
1495 /* Can't choose exit and guard at same time */
1496 tor_assert(rule
== NO_WEIGHTING
||
1497 rule
== WEIGHT_FOR_EXIT
||
1498 rule
== WEIGHT_FOR_GUARD
);
1500 /* First count the total bandwidth weight, and make a list
1501 * of each value. <0 means "unknown; no routerinfo." We use the
1502 * bits of negative values to remember whether the router was fast (-x)&1
1503 * and whether it was an exit (-x)&2 or guard (-x)&4. Yes, it's a hack. */
1504 bandwidths
= tor_malloc(sizeof(int32_t)*smartlist_len(sl
));
1505 exit_bits
= bitarray_init_zero(smartlist_len(sl
));
1506 guard_bits
= bitarray_init_zero(smartlist_len(sl
));
1508 /* Iterate over all the routerinfo_t or routerstatus_t, and */
1509 for (i
= 0; i
< (unsigned)smartlist_len(sl
); ++i
) {
1510 /* first, learn what bandwidth we think i has */
1513 uint32_t this_bw
= 0;
1515 /* need to extract router info */
1516 status
= smartlist_get(sl
, i
);
1517 if (router_digest_is_me(status
->identity_digest
))
1519 router
= router_get_by_digest(status
->identity_digest
);
1520 is_exit
= status
->is_exit
;
1521 is_guard
= status
->is_possible_guard
;
1523 this_bw
= router_get_advertised_bandwidth(router
);
1524 } else { /* guess */
1526 flags
= status
->is_fast
? 1 : 0;
1527 flags
|= is_exit
? 2 : 0;
1528 flags
|= is_guard
? 4 : 0;
1531 router
= smartlist_get(sl
, i
);
1532 if (router_digest_is_me(router
->cache_info
.identity_digest
))
1534 is_exit
= router
->is_exit
;
1535 is_guard
= router
->is_possible_guard
;
1536 this_bw
= router_get_advertised_bandwidth(router
);
1539 bitarray_set(exit_bits
, i
);
1541 bitarray_set(guard_bits
, i
);
1542 /* if they claim something huge, don't believe it */
1543 if (this_bw
> max_believable_bw
) {
1544 char fp
[HEX_DIGEST_LEN
+1];
1545 base16_encode(fp
, sizeof(fp
), statuses
?
1546 status
->identity_digest
:
1547 router
->cache_info
.identity_digest
,
1549 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
,
1550 "Bandwidth %d for router %s (%s) exceeds allowed max %d, capping",
1551 this_bw
, router
? router
->nickname
: "(null)",
1552 fp
, max_believable_bw
);
1553 this_bw
= max_believable_bw
;
1556 bandwidths
[i
] = (int32_t) this_bw
; // safe since MAX_BELIEVABLE<INT32_MAX
1558 total_guard_bw
+= this_bw
;
1560 total_nonguard_bw
+= this_bw
;
1562 total_exit_bw
+= this_bw
;
1564 total_nonexit_bw
+= this_bw
;
1567 bandwidths
[i
] = -flags
;
1571 /* Now, fill in the unknown values. */
1573 int32_t avg_fast
, avg_slow
;
1574 if (total_exit_bw
+total_nonexit_bw
) {
1575 /* if there's some bandwidth, there's at least one known router,
1576 * so no worries about div by 0 here */
1577 int n_known
= smartlist_len(sl
)-n_unknown
;
1578 avg_fast
= avg_slow
= (int32_t)
1579 ((total_exit_bw
+total_nonexit_bw
)/((uint64_t) n_known
));
1584 for (i
=0; i
<(unsigned)smartlist_len(sl
); ++i
) {
1585 int32_t bw
= bandwidths
[i
];
1588 is_exit
= ((-bw
)&2);
1589 is_guard
= ((-bw
)&4);
1590 bandwidths
[i
] = ((-bw
)&1) ? avg_fast
: avg_slow
;
1592 total_exit_bw
+= bandwidths
[i
];
1594 total_nonexit_bw
+= bandwidths
[i
];
1596 total_guard_bw
+= bandwidths
[i
];
1598 total_nonguard_bw
+= bandwidths
[i
];
1602 /* If there's no bandwidth at all, pick at random. */
1603 if (!(total_exit_bw
+total_nonexit_bw
)) {
1604 tor_free(bandwidths
);
1605 tor_free(exit_bits
);
1606 tor_free(guard_bits
);
1607 return smartlist_choose(sl
);
1610 /* Figure out how to weight exits and guards */
1612 double all_bw
= U64_TO_DBL(total_exit_bw
+total_nonexit_bw
);
1613 double exit_bw
= U64_TO_DBL(total_exit_bw
);
1614 double guard_bw
= U64_TO_DBL(total_guard_bw
);
1616 * For detailed derivation of this formula, see
1617 * http://archives.seul.org/or/dev/Jul-2007/msg00056.html
1619 if (rule
== WEIGHT_FOR_EXIT
)
1622 exit_weight
= 1.0 - all_bw
/(3.0*exit_bw
);
1624 if (rule
== WEIGHT_FOR_GUARD
)
1627 guard_weight
= 1.0 - all_bw
/(3.0*guard_bw
);
1629 if (exit_weight
<= 0.0)
1632 if (guard_weight
<= 0.0)
1636 sl_last_weighted_bw_of_me
= 0;
1637 for (i
=0; i
< (unsigned)smartlist_len(sl
); i
++) {
1639 is_exit
= bitarray_is_set(exit_bits
, i
);
1640 is_guard
= bitarray_is_set(guard_bits
, i
);
1641 if (is_exit
&& is_guard
)
1642 bw
= ((uint64_t)(bandwidths
[i
] * exit_weight
* guard_weight
));
1644 bw
= ((uint64_t)(bandwidths
[i
] * guard_weight
));
1646 bw
= ((uint64_t)(bandwidths
[i
] * exit_weight
));
1650 if (i
== (unsigned) me_idx
)
1651 sl_last_weighted_bw_of_me
= bw
;
1655 /* XXXX021 this is a kludge to expose these values. */
1656 sl_last_total_weighted_bw
= total_bw
;
1658 log_debug(LD_CIRC
, "Total weighted bw = "U64_FORMAT
1659 ", exit bw = "U64_FORMAT
1660 ", nonexit bw = "U64_FORMAT
", exit weight = %lf "
1662 ", guard bw = "U64_FORMAT
1663 ", nonguard bw = "U64_FORMAT
", guard weight = %lf "
1664 "(for guard == %d)",
1665 U64_PRINTF_ARG(total_bw
),
1666 U64_PRINTF_ARG(total_exit_bw
), U64_PRINTF_ARG(total_nonexit_bw
),
1667 exit_weight
, (int)(rule
== WEIGHT_FOR_EXIT
),
1668 U64_PRINTF_ARG(total_guard_bw
), U64_PRINTF_ARG(total_nonguard_bw
),
1669 guard_weight
, (int)(rule
== WEIGHT_FOR_GUARD
));
1671 /* Almost done: choose a random value from the bandwidth weights. */
1672 rand_bw
= crypto_rand_uint64(total_bw
);
1674 /* Last, count through sl until we get to the element we picked */
1676 for (i
=0; i
< (unsigned)smartlist_len(sl
); i
++) {
1677 is_exit
= bitarray_is_set(exit_bits
, i
);
1678 is_guard
= bitarray_is_set(guard_bits
, i
);
1680 /* Weights can be 0 if not counting guards/exits */
1681 if (is_exit
&& is_guard
)
1682 tmp
+= ((uint64_t)(bandwidths
[i
] * exit_weight
* guard_weight
));
1684 tmp
+= ((uint64_t)(bandwidths
[i
] * guard_weight
));
1686 tmp
+= ((uint64_t)(bandwidths
[i
] * exit_weight
));
1688 tmp
+= bandwidths
[i
];
1693 if (i
== (unsigned)smartlist_len(sl
)) {
1694 /* This was once possible due to round-off error, but shouldn't be able
1695 * to occur any longer. */
1696 tor_fragile_assert();
1698 log_warn(LD_BUG
, "Round-off error in computing bandwidth had an effect on "
1699 " which router we chose. Please tell the developers. "
1700 U64_FORMAT
" " U64_FORMAT
" " U64_FORMAT
, U64_PRINTF_ARG(tmp
),
1701 U64_PRINTF_ARG(rand_bw
), U64_PRINTF_ARG(total_bw
));
1703 tor_free(bandwidths
);
1704 tor_free(exit_bits
);
1705 tor_free(guard_bits
);
1706 return smartlist_get(sl
, i
);
1709 /** Choose a random element of router list <b>sl</b>, weighted by
1710 * the advertised bandwidth of each router.
1713 routerlist_sl_choose_by_bandwidth(smartlist_t
*sl
,
1714 bandwidth_weight_rule_t rule
)
1716 return smartlist_choose_by_bandwidth(sl
, rule
, 0);
1719 /** Choose a random element of status list <b>sl</b>, weighted by
1720 * the advertised bandwidth of each status.
1723 routerstatus_sl_choose_by_bandwidth(smartlist_t
*sl
)
1725 /* We are choosing neither exit nor guard here. Weight accordingly. */
1726 return smartlist_choose_by_bandwidth(sl
, NO_WEIGHTING
, 1);
1729 /** Return a random running router from the routerlist. If any node
1730 * named in <b>preferred</b> is available, pick one of those. Never
1731 * pick a node whose routerinfo is in
1732 * <b>excludedsmartlist</b>, or whose routerinfo matches <b>excludedset</b>,
1733 * even if they are the only nodes
1734 * available. If <b>CRN_STRICT_PREFERRED</b> is set in flags, never pick
1735 * any node besides those in <b>preferred</b>.
1736 * If <b>CRN_NEED_UPTIME</b> is set in flags and any router has more than
1737 * a minimum uptime, return one of those.
1738 * If <b>CRN_NEED_CAPACITY</b> is set in flags, weight your choice by the
1739 * advertised capacity of each router.
1740 * If <b>CRN_ALLOW_INVALID</b> is not set in flags, consider only Valid
1742 * If <b>CRN_NEED_GUARD</b> is set in flags, consider only Guard routers.
1743 * If <b>CRN_WEIGHT_AS_EXIT</b> is set in flags, we weight bandwidths as if
1744 * picking an exit node, otherwise we weight bandwidths for picking a relay
1745 * node (that is, possibly discounting exit nodes).
1748 router_choose_random_node(const char *preferred
,
1749 smartlist_t
*excludedsmartlist
,
1750 routerset_t
*excludedset
,
1751 router_crn_flags_t flags
)
1753 const int need_uptime
= (flags
& CRN_NEED_UPTIME
) != 0;
1754 const int need_capacity
= (flags
& CRN_NEED_CAPACITY
) != 0;
1755 const int need_guard
= (flags
& CRN_NEED_GUARD
) != 0;
1756 const int allow_invalid
= (flags
& CRN_ALLOW_INVALID
) != 0;
1757 const int strict
= (flags
& CRN_STRICT_PREFERRED
) != 0;
1758 const int weight_for_exit
= (flags
& CRN_WEIGHT_AS_EXIT
) != 0;
1760 smartlist_t
*sl
, *excludednodes
;
1761 routerinfo_t
*choice
= NULL
, *r
;
1762 bandwidth_weight_rule_t rule
;
1764 tor_assert(!(weight_for_exit
&& need_guard
));
1765 rule
= weight_for_exit
? WEIGHT_FOR_EXIT
:
1766 (need_guard
? WEIGHT_FOR_GUARD
: NO_WEIGHTING
);
1768 excludednodes
= smartlist_create();
1770 if ((r
= routerlist_find_my_routerinfo())) {
1771 smartlist_add(excludednodes
, r
);
1772 routerlist_add_family(excludednodes
, r
);
1775 /* Try the preferred nodes first. Ignore need_uptime and need_capacity
1776 * and need_guard, since the user explicitly asked for these nodes. */
1778 sl
= smartlist_create();
1779 add_nickname_list_to_smartlist(sl
,preferred
,1);
1780 smartlist_subtract(sl
,excludednodes
);
1781 if (excludedsmartlist
)
1782 smartlist_subtract(sl
,excludedsmartlist
);
1784 routerset_subtract_routers(sl
,excludedset
);
1785 choice
= smartlist_choose(sl
);
1788 if (!choice
&& !strict
) {
1789 /* Then give up on our preferred choices: any node
1790 * will do that has the required attributes. */
1791 sl
= smartlist_create();
1792 router_add_running_routers_to_smartlist(sl
, allow_invalid
,
1793 need_uptime
, need_capacity
,
1795 smartlist_subtract(sl
,excludednodes
);
1796 if (excludedsmartlist
)
1797 smartlist_subtract(sl
,excludedsmartlist
);
1799 routerset_subtract_routers(sl
,excludedset
);
1801 if (need_capacity
|| need_guard
)
1802 choice
= routerlist_sl_choose_by_bandwidth(sl
, rule
);
1804 choice
= smartlist_choose(sl
);
1807 if (!choice
&& (need_uptime
|| need_capacity
|| need_guard
)) {
1808 /* try once more -- recurse but with fewer restrictions. */
1810 "We couldn't find any live%s%s%s routers; falling back "
1811 "to list of all routers.",
1812 need_capacity
?", fast":"",
1813 need_uptime
?", stable":"",
1814 need_guard
?", guard":"");
1815 flags
&= ~ (CRN_NEED_UPTIME
|CRN_NEED_CAPACITY
|CRN_NEED_GUARD
);
1816 choice
= router_choose_random_node(
1817 NULL
, excludedsmartlist
, excludedset
, flags
);
1820 smartlist_free(excludednodes
);
1823 log_warn(LD_CIRC
, "All preferred nodes were down when trying to choose "
1824 "node, and the Strict[...]Nodes option is set. Failing.");
1827 "No available nodes when trying to choose node. Failing.");
1833 /** Helper: Return true iff the <b>identity_digest</b> and <b>nickname</b>
1834 * combination of a router, encoded in hexadecimal, matches <b>hexdigest</b>
1835 * (which is optionally prefixed with a single dollar sign). Return false if
1836 * <b>hexdigest</b> is malformed, or it doesn't match. */
1838 hex_digest_matches(const char *hexdigest
, const char *identity_digest
,
1839 const char *nickname
, int is_named
)
1841 char digest
[DIGEST_LEN
];
1843 tor_assert(hexdigest
);
1844 if (hexdigest
[0] == '$')
1847 len
= strlen(hexdigest
);
1848 if (len
< HEX_DIGEST_LEN
)
1850 else if (len
> HEX_DIGEST_LEN
&&
1851 (hexdigest
[HEX_DIGEST_LEN
] == '=' ||
1852 hexdigest
[HEX_DIGEST_LEN
] == '~')) {
1853 if (strcasecmp(hexdigest
+HEX_DIGEST_LEN
+1, nickname
))
1855 if (hexdigest
[HEX_DIGEST_LEN
] == '=' && !is_named
)
1859 if (base16_decode(digest
, DIGEST_LEN
, hexdigest
, HEX_DIGEST_LEN
)<0)
1861 return (!memcmp(digest
, identity_digest
, DIGEST_LEN
));
1864 /** Return true iff the digest of <b>router</b>'s identity key,
1865 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
1866 * optionally prefixed with a single dollar sign). Return false if
1867 * <b>hexdigest</b> is malformed, or it doesn't match. */
1869 router_hex_digest_matches(routerinfo_t
*router
, const char *hexdigest
)
1871 return hex_digest_matches(hexdigest
, router
->cache_info
.identity_digest
,
1872 router
->nickname
, router
->is_named
);
1875 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
1876 * (case-insensitive), or if <b>router's</b> identity key digest
1877 * matches a hexadecimal value stored in <b>nickname</b>. Return
1878 * false otherwise. */
1880 router_nickname_matches(routerinfo_t
*router
, const char *nickname
)
1882 if (nickname
[0]!='$' && !strcasecmp(router
->nickname
, nickname
))
1884 return router_hex_digest_matches(router
, nickname
);
1887 /** Return the router in our routerlist whose (case-insensitive)
1888 * nickname or (case-sensitive) hexadecimal key digest is
1889 * <b>nickname</b>. Return NULL if no such router is known.
1892 router_get_by_nickname(const char *nickname
, int warn_if_unnamed
)
1895 char digest
[DIGEST_LEN
];
1896 routerinfo_t
*best_match
=NULL
;
1898 const char *named_digest
= NULL
;
1900 tor_assert(nickname
);
1903 if (nickname
[0] == '$')
1904 return router_get_by_hexdigest(nickname
);
1905 if (!strcasecmp(nickname
, UNNAMED_ROUTER_NICKNAME
))
1907 if (server_mode(get_options()) &&
1908 !strcasecmp(nickname
, get_options()->Nickname
))
1909 return router_get_my_routerinfo();
1911 maybedigest
= (strlen(nickname
) >= HEX_DIGEST_LEN
) &&
1912 (base16_decode(digest
,DIGEST_LEN
,nickname
,HEX_DIGEST_LEN
) == 0);
1914 if ((named_digest
= networkstatus_get_router_digest_by_nickname(nickname
))) {
1915 return rimap_get(routerlist
->identity_map
, named_digest
);
1917 if (networkstatus_nickname_is_unnamed(nickname
))
1920 /* If we reach this point, there's no canonical value for the nickname. */
1922 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1924 if (!strcasecmp(router
->nickname
, nickname
)) {
1926 if (n_matches
<= 1 || router
->is_running
)
1927 best_match
= router
;
1928 } else if (maybedigest
&&
1929 !memcmp(digest
, router
->cache_info
.identity_digest
, DIGEST_LEN
)
1931 if (router_hex_digest_matches(router
, nickname
))
1933 /* If we reach this point, we have a ID=name syntax that matches the
1934 * identity but not the name. That isn't an acceptable match. */
1939 if (warn_if_unnamed
&& n_matches
> 1) {
1940 smartlist_t
*fps
= smartlist_create();
1941 int any_unwarned
= 0;
1942 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1947 char fp
[HEX_DIGEST_LEN
+1];
1948 if (strcasecmp(router
->nickname
, nickname
))
1950 rs
= router_get_consensus_status_by_id(
1951 router
->cache_info
.identity_digest
);
1952 if (rs
&& !rs
->name_lookup_warned
) {
1953 rs
->name_lookup_warned
= 1;
1956 base16_encode(fp
, sizeof(fp
),
1957 router
->cache_info
.identity_digest
, DIGEST_LEN
);
1958 dlen
= 32 + HEX_DIGEST_LEN
+ strlen(router
->address
);
1959 desc
= tor_malloc(dlen
);
1960 tor_snprintf(desc
, dlen
, "\"$%s\" for the one at %s:%d",
1961 fp
, router
->address
, router
->or_port
);
1962 smartlist_add(fps
, desc
);
1965 char *alternatives
= smartlist_join_strings(fps
, "; ",0,NULL
);
1967 "There are multiple matches for the nickname \"%s\","
1968 " but none is listed as named by the directory authorities. "
1969 "Choosing one arbitrarily. If you meant one in particular, "
1970 "you should say %s.", nickname
, alternatives
);
1971 tor_free(alternatives
);
1973 SMARTLIST_FOREACH(fps
, char *, cp
, tor_free(cp
));
1974 smartlist_free(fps
);
1975 } else if (warn_if_unnamed
) {
1976 routerstatus_t
*rs
= router_get_consensus_status_by_id(
1977 best_match
->cache_info
.identity_digest
);
1978 if (rs
&& !rs
->name_lookup_warned
) {
1979 char fp
[HEX_DIGEST_LEN
+1];
1980 base16_encode(fp
, sizeof(fp
),
1981 best_match
->cache_info
.identity_digest
, DIGEST_LEN
);
1982 log_warn(LD_CONFIG
, "You specified a server \"%s\" by name, but this "
1983 "name is not registered, so it could be used by any server, "
1984 "not just the one you meant. "
1985 "To make sure you get the same server in the future, refer to "
1986 "it by key, as \"$%s\".", nickname
, fp
);
1987 rs
->name_lookup_warned
= 1;
1996 /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
1997 * return 1. If we do, ask tor_version_as_new_as() for the answer.
2000 router_digest_version_as_new_as(const char *digest
, const char *cutoff
)
2002 routerinfo_t
*router
= router_get_by_digest(digest
);
2005 return tor_version_as_new_as(router
->platform
, cutoff
);
2008 /** Return true iff <b>digest</b> is the digest of the identity key of a
2009 * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
2010 * is zero, any authority is okay. */
2012 router_digest_is_trusted_dir_type(const char *digest
, authority_type_t type
)
2014 if (!trusted_dir_servers
)
2016 if (authdir_mode(get_options()) && router_digest_is_me(digest
))
2018 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
2019 if (!memcmp(digest
, ent
->digest
, DIGEST_LEN
)) {
2020 return (!type
) || ((type
& ent
->type
) != 0);
2025 /** Return true iff <b>addr</b> is the address of one of our trusted
2026 * directory authorities. */
2028 router_addr_is_trusted_dir(uint32_t addr
)
2030 if (!trusted_dir_servers
)
2032 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
2033 if (ent
->addr
== addr
)
2039 /** If hexdigest is correctly formed, base16_decode it into
2040 * digest, which must have DIGEST_LEN space in it.
2041 * Return 0 on success, -1 on failure.
2044 hexdigest_to_digest(const char *hexdigest
, char *digest
)
2046 if (hexdigest
[0]=='$')
2048 if (strlen(hexdigest
) < HEX_DIGEST_LEN
||
2049 base16_decode(digest
,DIGEST_LEN
,hexdigest
,HEX_DIGEST_LEN
) < 0)
2054 /** Return the router in our routerlist whose hexadecimal key digest
2055 * is <b>hexdigest</b>. Return NULL if no such router is known. */
2057 router_get_by_hexdigest(const char *hexdigest
)
2059 char digest
[DIGEST_LEN
];
2063 tor_assert(hexdigest
);
2066 if (hexdigest
[0]=='$')
2068 len
= strlen(hexdigest
);
2069 if (hexdigest_to_digest(hexdigest
, digest
) < 0)
2072 ri
= router_get_by_digest(digest
);
2074 if (ri
&& len
> HEX_DIGEST_LEN
) {
2075 if (hexdigest
[HEX_DIGEST_LEN
] == '=') {
2076 if (strcasecmp(ri
->nickname
, hexdigest
+HEX_DIGEST_LEN
+1) ||
2079 } else if (hexdigest
[HEX_DIGEST_LEN
] == '~') {
2080 if (strcasecmp(ri
->nickname
, hexdigest
+HEX_DIGEST_LEN
+1))
2090 /** Return the router in our routerlist whose 20-byte key digest
2091 * is <b>digest</b>. Return NULL if no such router is known. */
2093 router_get_by_digest(const char *digest
)
2097 if (!routerlist
) return NULL
;
2099 // routerlist_assert_ok(routerlist);
2101 return rimap_get(routerlist
->identity_map
, digest
);
2104 /** Return the router in our routerlist whose 20-byte descriptor
2105 * is <b>digest</b>. Return NULL if no such router is known. */
2106 signed_descriptor_t
*
2107 router_get_by_descriptor_digest(const char *digest
)
2111 if (!routerlist
) return NULL
;
2113 return sdmap_get(routerlist
->desc_digest_map
, digest
);
2116 /** Return the signed descriptor for the router in our routerlist whose
2117 * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
2119 signed_descriptor_t
*
2120 router_get_by_extrainfo_digest(const char *digest
)
2124 if (!routerlist
) return NULL
;
2126 return sdmap_get(routerlist
->desc_by_eid_map
, digest
);
2129 /** Return the signed descriptor for the extrainfo_t in our routerlist whose
2130 * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
2131 * document is known. */
2132 signed_descriptor_t
*
2133 extrainfo_get_by_descriptor_digest(const char *digest
)
2137 if (!routerlist
) return NULL
;
2138 ei
= eimap_get(routerlist
->extra_info_map
, digest
);
2139 return ei
? &ei
->cache_info
: NULL
;
2142 /** Return a pointer to the signed textual representation of a descriptor.
2143 * The returned string is not guaranteed to be NUL-terminated: the string's
2144 * length will be in desc-\>signed_descriptor_len.
2146 * If <b>with_annotations</b> is set, the returned string will include
2148 * (if any) preceding the descriptor. This will increase the length of the
2149 * string by desc-\>annotations_len.
2151 * The caller must not free the string returned.
2154 signed_descriptor_get_body_impl(signed_descriptor_t
*desc
,
2155 int with_annotations
)
2157 const char *r
= NULL
;
2158 size_t len
= desc
->signed_descriptor_len
;
2159 off_t offset
= desc
->saved_offset
;
2160 if (with_annotations
)
2161 len
+= desc
->annotations_len
;
2163 offset
+= desc
->annotations_len
;
2165 tor_assert(len
> 32);
2166 if (desc
->saved_location
== SAVED_IN_CACHE
&& routerlist
) {
2167 desc_store_t
*store
= desc_get_store(router_get_routerlist(), desc
);
2168 if (store
&& store
->mmap
) {
2169 tor_assert(desc
->saved_offset
+ len
<= store
->mmap
->size
);
2170 r
= store
->mmap
->data
+ offset
;
2173 if (!r
) /* no mmap, or not in cache. */
2174 r
= desc
->signed_descriptor_body
+
2175 (with_annotations
? 0 : desc
->annotations_len
);
2178 if (!with_annotations
) {
2179 if (memcmp("router ", r
, 7) && memcmp("extra-info ", r
, 11)) {
2180 char *cp
= tor_strndup(r
, 64);
2181 log_err(LD_DIR
, "descriptor at %p begins with unexpected string %s",
2185 tor_assert(!memcmp("router ", r
, 7) || !memcmp("extra-info ", r
, 11));
2191 /** Return a pointer to the signed textual representation of a descriptor.
2192 * The returned string is not guaranteed to be NUL-terminated: the string's
2193 * length will be in desc-\>signed_descriptor_len.
2195 * The caller must not free the string returned.
2198 signed_descriptor_get_body(signed_descriptor_t
*desc
)
2200 return signed_descriptor_get_body_impl(desc
, 0);
2203 /** As signed_descriptor_get_body(), but points to the beginning of the
2204 * annotations section rather than the beginning of the descriptor. */
2206 signed_descriptor_get_annotations(signed_descriptor_t
*desc
)
2208 return signed_descriptor_get_body_impl(desc
, 1);
2211 /** Return the current list of all known routers. */
2213 router_get_routerlist(void)
2215 if (PREDICT_UNLIKELY(!routerlist
)) {
2216 routerlist
= tor_malloc_zero(sizeof(routerlist_t
));
2217 routerlist
->routers
= smartlist_create();
2218 routerlist
->old_routers
= smartlist_create();
2219 routerlist
->identity_map
= rimap_new();
2220 routerlist
->desc_digest_map
= sdmap_new();
2221 routerlist
->desc_by_eid_map
= sdmap_new();
2222 routerlist
->extra_info_map
= eimap_new();
2224 routerlist
->desc_store
.fname_base
= "cached-descriptors";
2225 routerlist
->desc_store
.fname_alt_base
= "cached-routers";
2226 routerlist
->extrainfo_store
.fname_base
= "cached-extrainfo";
2228 routerlist
->desc_store
.type
= ROUTER_STORE
;
2229 routerlist
->extrainfo_store
.type
= EXTRAINFO_STORE
;
2231 routerlist
->desc_store
.description
= "router descriptors";
2232 routerlist
->extrainfo_store
.description
= "extra-info documents";
2237 /** Free all storage held by <b>router</b>. */
2239 routerinfo_free(routerinfo_t
*router
)
2244 tor_free(router
->cache_info
.signed_descriptor_body
);
2245 tor_free(router
->address
);
2246 tor_free(router
->nickname
);
2247 tor_free(router
->platform
);
2248 tor_free(router
->contact_info
);
2249 if (router
->onion_pkey
)
2250 crypto_free_pk_env(router
->onion_pkey
);
2251 if (router
->identity_pkey
)
2252 crypto_free_pk_env(router
->identity_pkey
);
2253 if (router
->declared_family
) {
2254 SMARTLIST_FOREACH(router
->declared_family
, char *, s
, tor_free(s
));
2255 smartlist_free(router
->declared_family
);
2257 addr_policy_list_free(router
->exit_policy
);
2259 /* XXXX Remove if this turns out to affect performance. */
2260 memset(router
, 77, sizeof(routerinfo_t
));
2265 /** Release all storage held by <b>extrainfo</b> */
2267 extrainfo_free(extrainfo_t
*extrainfo
)
2271 tor_free(extrainfo
->cache_info
.signed_descriptor_body
);
2272 tor_free(extrainfo
->pending_sig
);
2274 /* XXXX remove this if it turns out to slow us down. */
2275 memset(extrainfo
, 88, sizeof(extrainfo_t
)); /* debug bad memory usage */
2276 tor_free(extrainfo
);
2279 /** Release storage held by <b>sd</b>. */
2281 signed_descriptor_free(signed_descriptor_t
*sd
)
2283 tor_free(sd
->signed_descriptor_body
);
2285 /* XXXX remove this once more bugs go away. */
2286 memset(sd
, 99, sizeof(signed_descriptor_t
)); /* Debug bad mem usage */
2290 /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
2292 static signed_descriptor_t
*
2293 signed_descriptor_from_routerinfo(routerinfo_t
*ri
)
2295 signed_descriptor_t
*sd
= tor_malloc_zero(sizeof(signed_descriptor_t
));
2296 memcpy(sd
, &(ri
->cache_info
), sizeof(signed_descriptor_t
));
2297 sd
->routerlist_index
= -1;
2298 ri
->cache_info
.signed_descriptor_body
= NULL
;
2299 routerinfo_free(ri
);
2303 /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
2305 _extrainfo_free(void *e
)
2310 /** Free all storage held by a routerlist <b>rl</b>. */
2312 routerlist_free(routerlist_t
*rl
)
2315 rimap_free(rl
->identity_map
, NULL
);
2316 sdmap_free(rl
->desc_digest_map
, NULL
);
2317 sdmap_free(rl
->desc_by_eid_map
, NULL
);
2318 eimap_free(rl
->extra_info_map
, _extrainfo_free
);
2319 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
2320 routerinfo_free(r
));
2321 SMARTLIST_FOREACH(rl
->old_routers
, signed_descriptor_t
*, sd
,
2322 signed_descriptor_free(sd
));
2323 smartlist_free(rl
->routers
);
2324 smartlist_free(rl
->old_routers
);
2325 if (routerlist
->desc_store
.mmap
)
2326 tor_munmap_file(routerlist
->desc_store
.mmap
);
2327 if (routerlist
->extrainfo_store
.mmap
)
2328 tor_munmap_file(routerlist
->extrainfo_store
.mmap
);
2331 router_dir_info_changed();
2334 /** Log information about how much memory is being used for routerlist,
2335 * at log level <b>severity</b>. */
2337 dump_routerlist_mem_usage(int severity
)
2339 uint64_t livedescs
= 0;
2340 uint64_t olddescs
= 0;
2343 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, r
,
2344 livedescs
+= r
->cache_info
.signed_descriptor_len
);
2345 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
,
2346 olddescs
+= sd
->signed_descriptor_len
);
2348 log(severity
, LD_DIR
,
2349 "In %d live descriptors: "U64_FORMAT
" bytes. "
2350 "In %d old descriptors: "U64_FORMAT
" bytes.",
2351 smartlist_len(routerlist
->routers
), U64_PRINTF_ARG(livedescs
),
2352 smartlist_len(routerlist
->old_routers
), U64_PRINTF_ARG(olddescs
));
2356 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
2357 networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
2358 log(severity
, LD_DIR
, "Now let's look through old_descriptors!");
2359 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
, {
2362 char published
[ISO_TIME_LEN
+1];
2363 char last_valid_until
[ISO_TIME_LEN
+1];
2364 char last_served_at
[ISO_TIME_LEN
+1];
2365 char id
[HEX_DIGEST_LEN
+1];
2367 format_iso_time(published
, sd
->published_on
);
2368 format_iso_time(last_valid_until
, sd
->last_listed_as_valid_until
);
2369 format_iso_time(last_served_at
, sd
->last_served_at
);
2370 base16_encode(id
, sizeof(id
), sd
->identity_digest
, DIGEST_LEN
);
2371 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
2373 rs
= networkstatus_v2_find_entry(ns
, sd
->identity_digest
);
2374 if (rs
&& !memcmp(rs
->descriptor_digest
,
2375 sd
->signed_descriptor_digest
, DIGEST_LEN
)) {
2380 rs
= networkstatus_vote_find_entry(consensus
, sd
->identity_digest
);
2381 if (rs
&& !memcmp(rs
->descriptor_digest
,
2382 sd
->signed_descriptor_digest
, DIGEST_LEN
))
2385 log(severity
, LD_DIR
,
2386 "Old descriptor for %s (published %s) %sin v2 ns, %sin v3 "
2387 "consensus. Last valid until %s; last served at %s.",
2388 id
, published
, in_v2
? "" : "not ", in_v3
? "" : "not ",
2389 last_valid_until
, last_served_at
);
2396 _routerlist_find_elt(smartlist_t
*sl
, void *ri
, int idx
)
2400 SMARTLIST_FOREACH(sl
, routerinfo_t
*, r
,
2406 tor_assert(idx
< smartlist_len(sl
));
2407 tor_assert(smartlist_get(sl
, idx
) == ri
);
2412 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
2413 * as needed. There must be no previous member of <b>rl</b> with the same
2414 * identity digest as <b>ri</b>: If there is, call routerlist_replace
2418 routerlist_insert(routerlist_t
*rl
, routerinfo_t
*ri
)
2420 routerinfo_t
*ri_old
;
2422 /* XXXX Remove if this slows us down. */
2423 routerinfo_t
*ri_generated
= router_get_my_routerinfo();
2424 tor_assert(ri_generated
!= ri
);
2426 tor_assert(ri
->cache_info
.routerlist_index
== -1);
2428 ri_old
= rimap_set(rl
->identity_map
, ri
->cache_info
.identity_digest
, ri
);
2429 tor_assert(!ri_old
);
2430 sdmap_set(rl
->desc_digest_map
, ri
->cache_info
.signed_descriptor_digest
,
2432 if (!tor_digest_is_zero(ri
->cache_info
.extra_info_digest
))
2433 sdmap_set(rl
->desc_by_eid_map
, ri
->cache_info
.extra_info_digest
,
2435 smartlist_add(rl
->routers
, ri
);
2436 ri
->cache_info
.routerlist_index
= smartlist_len(rl
->routers
) - 1;
2437 router_dir_info_changed();
2438 #ifdef DEBUG_ROUTERLIST
2439 routerlist_assert_ok(rl
);
2443 /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
2444 * corresponding router in rl-\>routers or rl-\>old_routers. Return true iff
2445 * we actually inserted <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
2447 extrainfo_insert(routerlist_t
*rl
, extrainfo_t
*ei
)
2450 routerinfo_t
*ri
= rimap_get(rl
->identity_map
,
2451 ei
->cache_info
.identity_digest
);
2452 signed_descriptor_t
*sd
=
2453 sdmap_get(rl
->desc_by_eid_map
, ei
->cache_info
.signed_descriptor_digest
);
2454 extrainfo_t
*ei_tmp
;
2457 /* XXXX remove this code if it slows us down. */
2458 extrainfo_t
*ei_generated
= router_get_my_extrainfo();
2459 tor_assert(ei_generated
!= ei
);
2463 /* This router is unknown; we can't even verify the signature. Give up.*/
2466 if (routerinfo_incompatible_with_extrainfo(ri
, ei
, sd
, NULL
)) {
2470 /* Okay, if we make it here, we definitely have a router corresponding to
2471 * this extrainfo. */
2473 ei_tmp
= eimap_set(rl
->extra_info_map
,
2474 ei
->cache_info
.signed_descriptor_digest
,
2478 rl
->extrainfo_store
.bytes_dropped
+=
2479 ei_tmp
->cache_info
.signed_descriptor_len
;
2480 extrainfo_free(ei_tmp
);
2487 #ifdef DEBUG_ROUTERLIST
2488 routerlist_assert_ok(rl
);
2493 #define should_cache_old_descriptors() \
2494 directory_caches_dir_info(get_options())
2496 /** If we're a directory cache and routerlist <b>rl</b> doesn't have
2497 * a copy of router <b>ri</b> yet, add it to the list of old (not
2498 * recommended but still served) descriptors. Else free it. */
2500 routerlist_insert_old(routerlist_t
*rl
, routerinfo_t
*ri
)
2503 /* XXXX remove this code if it slows us down. */
2504 routerinfo_t
*ri_generated
= router_get_my_routerinfo();
2505 tor_assert(ri_generated
!= ri
);
2507 tor_assert(ri
->cache_info
.routerlist_index
== -1);
2509 if (should_cache_old_descriptors() &&
2510 ri
->purpose
== ROUTER_PURPOSE_GENERAL
&&
2511 !sdmap_get(rl
->desc_digest_map
,
2512 ri
->cache_info
.signed_descriptor_digest
)) {
2513 signed_descriptor_t
*sd
= signed_descriptor_from_routerinfo(ri
);
2514 sdmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
2515 smartlist_add(rl
->old_routers
, sd
);
2516 sd
->routerlist_index
= smartlist_len(rl
->old_routers
)-1;
2517 if (!tor_digest_is_zero(sd
->extra_info_digest
))
2518 sdmap_set(rl
->desc_by_eid_map
, sd
->extra_info_digest
, sd
);
2520 routerinfo_free(ri
);
2522 #ifdef DEBUG_ROUTERLIST
2523 routerlist_assert_ok(rl
);
2527 /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
2528 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl->routers,
2529 * idx) == ri, we don't need to do a linear search over the list to decide
2530 * which to remove. We fill the gap in rl->routers with a later element in
2531 * the list, if any exists. <b>ri</b> is freed.
2533 * If <b>make_old</b> is true, instead of deleting the router, we try adding
2534 * it to rl->old_routers. */
2536 routerlist_remove(routerlist_t
*rl
, routerinfo_t
*ri
, int make_old
)
2538 routerinfo_t
*ri_tmp
;
2539 extrainfo_t
*ei_tmp
;
2540 int idx
= ri
->cache_info
.routerlist_index
;
2541 tor_assert(0 <= idx
&& idx
< smartlist_len(rl
->routers
));
2542 tor_assert(smartlist_get(rl
->routers
, idx
) == ri
);
2544 ri
->cache_info
.routerlist_index
= -1;
2545 smartlist_del(rl
->routers
, idx
);
2546 if (idx
< smartlist_len(rl
->routers
)) {
2547 routerinfo_t
*r
= smartlist_get(rl
->routers
, idx
);
2548 r
->cache_info
.routerlist_index
= idx
;
2551 ri_tmp
= rimap_remove(rl
->identity_map
, ri
->cache_info
.identity_digest
);
2552 router_dir_info_changed();
2553 tor_assert(ri_tmp
== ri
);
2555 if (make_old
&& should_cache_old_descriptors() &&
2556 ri
->purpose
== ROUTER_PURPOSE_GENERAL
) {
2557 signed_descriptor_t
*sd
;
2558 sd
= signed_descriptor_from_routerinfo(ri
);
2559 smartlist_add(rl
->old_routers
, sd
);
2560 sd
->routerlist_index
= smartlist_len(rl
->old_routers
)-1;
2561 sdmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
2562 if (!tor_digest_is_zero(sd
->extra_info_digest
))
2563 sdmap_set(rl
->desc_by_eid_map
, sd
->extra_info_digest
, sd
);
2565 signed_descriptor_t
*sd_tmp
;
2566 sd_tmp
= sdmap_remove(rl
->desc_digest_map
,
2567 ri
->cache_info
.signed_descriptor_digest
);
2568 tor_assert(sd_tmp
== &(ri
->cache_info
));
2569 rl
->desc_store
.bytes_dropped
+= ri
->cache_info
.signed_descriptor_len
;
2570 ei_tmp
= eimap_remove(rl
->extra_info_map
,
2571 ri
->cache_info
.extra_info_digest
);
2573 rl
->extrainfo_store
.bytes_dropped
+=
2574 ei_tmp
->cache_info
.signed_descriptor_len
;
2575 extrainfo_free(ei_tmp
);
2577 if (!tor_digest_is_zero(ri
->cache_info
.extra_info_digest
))
2578 sdmap_remove(rl
->desc_by_eid_map
, ri
->cache_info
.extra_info_digest
);
2579 routerinfo_free(ri
);
2581 #ifdef DEBUG_ROUTERLIST
2582 routerlist_assert_ok(rl
);
2586 /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
2587 * adjust <b>rl</b> as appropriate. <b>idx</i> is -1, or the index of
2590 routerlist_remove_old(routerlist_t
*rl
, signed_descriptor_t
*sd
, int idx
)
2592 signed_descriptor_t
*sd_tmp
;
2593 extrainfo_t
*ei_tmp
;
2594 desc_store_t
*store
;
2596 idx
= sd
->routerlist_index
;
2598 tor_assert(0 <= idx
&& idx
< smartlist_len(rl
->old_routers
));
2599 /* XXXX edmanm's bridge relay triggered the following assert while
2600 * running 0.2.0.12-alpha. If anybody triggers this again, see if we
2601 * can get a backtrace. */
2602 tor_assert(smartlist_get(rl
->old_routers
, idx
) == sd
);
2603 tor_assert(idx
== sd
->routerlist_index
);
2605 sd
->routerlist_index
= -1;
2606 smartlist_del(rl
->old_routers
, idx
);
2607 if (idx
< smartlist_len(rl
->old_routers
)) {
2608 signed_descriptor_t
*d
= smartlist_get(rl
->old_routers
, idx
);
2609 d
->routerlist_index
= idx
;
2611 sd_tmp
= sdmap_remove(rl
->desc_digest_map
,
2612 sd
->signed_descriptor_digest
);
2613 tor_assert(sd_tmp
== sd
);
2614 store
= desc_get_store(rl
, sd
);
2616 store
->bytes_dropped
+= sd
->signed_descriptor_len
;
2618 ei_tmp
= eimap_remove(rl
->extra_info_map
,
2619 sd
->extra_info_digest
);
2621 rl
->extrainfo_store
.bytes_dropped
+=
2622 ei_tmp
->cache_info
.signed_descriptor_len
;
2623 extrainfo_free(ei_tmp
);
2625 if (!tor_digest_is_zero(sd
->extra_info_digest
))
2626 sdmap_remove(rl
->desc_by_eid_map
, sd
->extra_info_digest
);
2628 signed_descriptor_free(sd
);
2629 #ifdef DEBUG_ROUTERLIST
2630 routerlist_assert_ok(rl
);
2634 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
2635 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
2636 * smartlist_get(rl->routers, idx) == ri, we don't need to do a linear
2637 * search over the list to decide which to remove. We put ri_new in the same
2638 * index as ri_old, if possible. ri is freed as appropriate.
2640 * If should_cache_descriptors() is true, instead of deleting the router,
2641 * we add it to rl->old_routers. */
2643 routerlist_replace(routerlist_t
*rl
, routerinfo_t
*ri_old
,
2644 routerinfo_t
*ri_new
)
2648 routerinfo_t
*ri_tmp
;
2649 extrainfo_t
*ei_tmp
;
2651 /* XXXX Remove this if it turns out to slow us down. */
2652 routerinfo_t
*ri_generated
= router_get_my_routerinfo();
2653 tor_assert(ri_generated
!= ri_new
);
2655 tor_assert(ri_old
!= ri_new
);
2656 tor_assert(ri_new
->cache_info
.routerlist_index
== -1);
2658 idx
= ri_old
->cache_info
.routerlist_index
;
2659 tor_assert(0 <= idx
&& idx
< smartlist_len(rl
->routers
));
2660 tor_assert(smartlist_get(rl
->routers
, idx
) == ri_old
);
2662 router_dir_info_changed();
2664 smartlist_set(rl
->routers
, idx
, ri_new
);
2665 ri_old
->cache_info
.routerlist_index
= -1;
2666 ri_new
->cache_info
.routerlist_index
= idx
;
2667 /* Check that ri_old is not in rl->routers anymore: */
2668 tor_assert( _routerlist_find_elt(rl
->routers
, ri_old
, -1) == -1 );
2670 log_warn(LD_BUG
, "Appending entry from routerlist_replace.");
2671 routerlist_insert(rl
, ri_new
);
2674 if (memcmp(ri_old
->cache_info
.identity_digest
,
2675 ri_new
->cache_info
.identity_digest
, DIGEST_LEN
)) {
2676 /* digests don't match; digestmap_set won't replace */
2677 rimap_remove(rl
->identity_map
, ri_old
->cache_info
.identity_digest
);
2679 ri_tmp
= rimap_set(rl
->identity_map
,
2680 ri_new
->cache_info
.identity_digest
, ri_new
);
2681 tor_assert(!ri_tmp
|| ri_tmp
== ri_old
);
2682 sdmap_set(rl
->desc_digest_map
,
2683 ri_new
->cache_info
.signed_descriptor_digest
,
2684 &(ri_new
->cache_info
));
2686 if (!tor_digest_is_zero(ri_new
->cache_info
.extra_info_digest
)) {
2687 sdmap_set(rl
->desc_by_eid_map
, ri_new
->cache_info
.extra_info_digest
,
2688 &ri_new
->cache_info
);
2691 if (should_cache_old_descriptors() &&
2692 ri_old
->purpose
== ROUTER_PURPOSE_GENERAL
) {
2693 signed_descriptor_t
*sd
= signed_descriptor_from_routerinfo(ri_old
);
2694 smartlist_add(rl
->old_routers
, sd
);
2695 sd
->routerlist_index
= smartlist_len(rl
->old_routers
)-1;
2696 sdmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
2697 if (!tor_digest_is_zero(sd
->extra_info_digest
))
2698 sdmap_set(rl
->desc_by_eid_map
, sd
->extra_info_digest
, sd
);
2700 if (memcmp(ri_old
->cache_info
.signed_descriptor_digest
,
2701 ri_new
->cache_info
.signed_descriptor_digest
,
2703 /* digests don't match; digestmap_set didn't replace */
2704 sdmap_remove(rl
->desc_digest_map
,
2705 ri_old
->cache_info
.signed_descriptor_digest
);
2708 ei_tmp
= eimap_remove(rl
->extra_info_map
,
2709 ri_old
->cache_info
.extra_info_digest
);
2711 rl
->extrainfo_store
.bytes_dropped
+=
2712 ei_tmp
->cache_info
.signed_descriptor_len
;
2713 extrainfo_free(ei_tmp
);
2715 if (!tor_digest_is_zero(ri_old
->cache_info
.extra_info_digest
)) {
2716 sdmap_remove(rl
->desc_by_eid_map
,
2717 ri_old
->cache_info
.extra_info_digest
);
2719 rl
->desc_store
.bytes_dropped
+= ri_old
->cache_info
.signed_descriptor_len
;
2720 routerinfo_free(ri_old
);
2722 #ifdef DEBUG_ROUTERLIST
2723 routerlist_assert_ok(rl
);
2727 /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
2728 * it as a fresh routerinfo_t. */
2729 static routerinfo_t
*
2730 routerlist_reparse_old(routerlist_t
*rl
, signed_descriptor_t
*sd
)
2735 body
= signed_descriptor_get_annotations(sd
);
2737 ri
= router_parse_entry_from_string(body
,
2738 body
+sd
->signed_descriptor_len
+sd
->annotations_len
,
2742 memcpy(&ri
->cache_info
, sd
, sizeof(signed_descriptor_t
));
2743 sd
->signed_descriptor_body
= NULL
; /* Steal reference. */
2744 ri
->cache_info
.routerlist_index
= -1;
2746 routerlist_remove_old(rl
, sd
, -1);
2751 /** Free all memory held by the routerlist module. */
2753 routerlist_free_all(void)
2756 routerlist_free(routerlist
);
2758 if (warned_nicknames
) {
2759 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
2760 smartlist_free(warned_nicknames
);
2761 warned_nicknames
= NULL
;
2763 if (trusted_dir_servers
) {
2764 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
2765 trusted_dir_server_free(ds
));
2766 smartlist_free(trusted_dir_servers
);
2767 trusted_dir_servers
= NULL
;
2769 if (trusted_dir_certs
) {
2770 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
2771 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
2772 authority_cert_free(cert
));
2773 smartlist_free(cl
->certs
);
2775 } DIGESTMAP_FOREACH_END
;
2776 digestmap_free(trusted_dir_certs
, NULL
);
2777 trusted_dir_certs
= NULL
;
2781 /** Forget that we have issued any router-related warnings, so that we'll
2782 * warn again if we see the same errors. */
2784 routerlist_reset_warnings(void)
2786 if (!warned_nicknames
)
2787 warned_nicknames
= smartlist_create();
2788 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
2789 smartlist_clear(warned_nicknames
); /* now the list is empty. */
2791 networkstatus_reset_warnings();
2794 /** Mark the router with ID <b>digest</b> as running or non-running
2795 * in our routerlist. */
2797 router_set_status(const char *digest
, int up
)
2799 routerinfo_t
*router
;
2800 routerstatus_t
*status
;
2803 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, d
,
2804 if (!memcmp(d
->digest
, digest
, DIGEST_LEN
))
2805 d
->is_running
= up
);
2807 router
= router_get_by_digest(digest
);
2809 log_debug(LD_DIR
,"Marking router '%s/%s' as %s.",
2810 router
->nickname
, router
->address
, up
? "up" : "down");
2811 if (!up
&& router_is_me(router
) && !we_are_hibernating())
2812 log_warn(LD_NET
, "We just marked ourself as down. Are your external "
2813 "addresses reachable?");
2814 router
->is_running
= up
;
2816 status
= router_get_consensus_status_by_id(digest
);
2817 if (status
&& status
->is_running
!= up
) {
2818 status
->is_running
= up
;
2819 control_event_networkstatus_changed_single(status
);
2821 router_dir_info_changed();
2824 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
2825 * older entries (if any) with the same key. Note: Callers should not hold
2826 * their pointers to <b>router</b> if this function fails; <b>router</b>
2827 * will either be inserted into the routerlist or freed. Similarly, even
2828 * if this call succeeds, they should not hold their pointers to
2829 * <b>router</b> after subsequent calls with other routerinfo's -- they
2830 * might cause the original routerinfo to get freed.
2832 * Returns >= 0 if the router was added; less than 0 if it was not.
2834 * If we're returning non-zero, then assign to *<b>msg</b> a static string
2835 * describing the reason for not liking the routerinfo.
2837 * If the return value is less than -1, there was a problem with the
2838 * routerinfo. If the return value is equal to -1, then the routerinfo was
2839 * fine, but out-of-date. If the return value is equal to 1, the
2840 * routerinfo was accepted, but we should notify the generator of the
2841 * descriptor using the message *<b>msg</b>.
2843 * If <b>from_cache</b>, this descriptor came from our disk cache. If
2844 * <b>from_fetch</b>, we received it in response to a request we made.
2845 * (If both are false, that means it was uploaded to us as an auth dir
2846 * server or via the controller.)
2848 * This function should be called *after*
2849 * routers_update_status_from_consensus_networkstatus; subsequently, you
2850 * should call router_rebuild_store and routerlist_descriptors_added.
2853 router_add_to_routerlist(routerinfo_t
*router
, const char **msg
,
2854 int from_cache
, int from_fetch
)
2856 const char *id_digest
;
2857 int authdir
= authdir_mode_handles_descs(get_options(), router
->purpose
);
2858 int authdir_believes_valid
= 0;
2859 routerinfo_t
*old_router
;
2860 networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
2861 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
2862 int in_consensus
= 0;
2867 router_get_routerlist();
2869 id_digest
= router
->cache_info
.identity_digest
;
2871 /* Make sure that we haven't already got this exact descriptor. */
2872 if (sdmap_get(routerlist
->desc_digest_map
,
2873 router
->cache_info
.signed_descriptor_digest
)) {
2875 "Dropping descriptor that we already have for router '%s'",
2877 *msg
= "Router descriptor was not new.";
2878 routerinfo_free(router
);
2883 if (authdir_wants_to_reject_router(router
, msg
,
2884 !from_cache
&& !from_fetch
)) {
2886 routerinfo_free(router
);
2889 authdir_believes_valid
= router
->is_valid
;
2890 } else if (from_fetch
) {
2891 /* Only check the descriptor digest against the network statuses when
2892 * we are receiving in response to a fetch. */
2894 if (!signed_desc_digest_is_recognized(&router
->cache_info
) &&
2895 !routerinfo_is_a_configured_bridge(router
)) {
2896 /* We asked for it, so some networkstatus must have listed it when we
2897 * did. Save it if we're a cache in case somebody else asks for it. */
2899 "Received a no-longer-recognized descriptor for router '%s'",
2901 *msg
= "Router descriptor is not referenced by any network-status.";
2903 /* Only journal this desc if we'll be serving it. */
2904 if (!from_cache
&& should_cache_old_descriptors())
2905 signed_desc_append_to_journal(&router
->cache_info
,
2906 &routerlist
->desc_store
);
2907 routerlist_insert_old(routerlist
, router
);
2912 /* We no longer need a router with this descriptor digest. */
2913 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
2915 routerstatus_t
*rs
=
2916 networkstatus_v2_find_entry(ns
, router
->cache_info
.identity_digest
);
2917 if (rs
&& !memcmp(rs
->descriptor_digest
,
2918 router
->cache_info
.signed_descriptor_digest
,
2920 rs
->need_to_mirror
= 0;
2923 routerstatus_t
*rs
= networkstatus_vote_find_entry(consensus
,
2924 router
->cache_info
.identity_digest
);
2925 if (rs
&& !memcmp(rs
->descriptor_digest
,
2926 router
->cache_info
.signed_descriptor_digest
,
2929 rs
->need_to_mirror
= 0;
2933 if (router
->purpose
== ROUTER_PURPOSE_GENERAL
&&
2934 consensus
&& !in_consensus
&& !authdir
) {
2935 /* If it's a general router not listed in the consensus, then don't
2936 * consider replacing the latest router with it. */
2937 if (!from_cache
&& should_cache_old_descriptors())
2938 signed_desc_append_to_journal(&router
->cache_info
,
2939 &routerlist
->desc_store
);
2940 routerlist_insert_old(routerlist
, router
);
2941 *msg
= "Skipping router descriptor: not in consensus.";
2945 /* If we have a router with the same identity key, choose the newer one. */
2946 old_router
= rimap_get(routerlist
->identity_map
,
2947 router
->cache_info
.identity_digest
);
2949 if (!in_consensus
&& (router
->cache_info
.published_on
<=
2950 old_router
->cache_info
.published_on
)) {
2951 /* Same key, but old. This one is not listed in the consensus. */
2952 log_debug(LD_DIR
, "Skipping not-new descriptor for router '%s'",
2954 /* Only journal this desc if we'll be serving it. */
2955 if (!from_cache
&& should_cache_old_descriptors())
2956 signed_desc_append_to_journal(&router
->cache_info
,
2957 &routerlist
->desc_store
);
2958 routerlist_insert_old(routerlist
, router
);
2959 *msg
= "Router descriptor was not new.";
2962 /* Same key, and either new, or listed in the consensus. */
2963 log_debug(LD_DIR
, "Replacing entry for router '%s/%s' [%s]",
2964 router
->nickname
, old_router
->nickname
,
2965 hex_str(id_digest
,DIGEST_LEN
));
2966 if (router
->addr
== old_router
->addr
&&
2967 router
->or_port
== old_router
->or_port
) {
2968 /* these carry over when the address and orport are unchanged. */
2969 router
->last_reachable
= old_router
->last_reachable
;
2970 router
->testing_since
= old_router
->testing_since
;
2972 routerlist_replace(routerlist
, old_router
, router
);
2974 signed_desc_append_to_journal(&router
->cache_info
,
2975 &routerlist
->desc_store
);
2977 directory_set_dirty();
2978 *msg
= authdir_believes_valid
? "Valid server updated" :
2979 ("Invalid server updated. (This dirserver is marking your "
2980 "server as unapproved.)");
2985 /* We haven't seen a router with this identity before. Add it to the end of
2987 routerlist_insert(routerlist
, router
);
2989 signed_desc_append_to_journal(&router
->cache_info
,
2990 &routerlist
->desc_store
);
2991 directory_set_dirty();
2995 /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
2996 * as for router_add_to_routerlist(). Return true iff we actually inserted
3000 router_add_extrainfo_to_routerlist(extrainfo_t
*ei
, const char **msg
,
3001 int from_cache
, int from_fetch
)
3005 if (msg
) *msg
= NULL
;
3007 inserted
= extrainfo_insert(router_get_routerlist(), ei
);
3009 if (inserted
&& !from_cache
)
3010 signed_desc_append_to_journal(&ei
->cache_info
,
3011 &routerlist
->extrainfo_store
);
3016 /** Sorting helper: return <0, 0, or >0 depending on whether the
3017 * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
3018 * to, or later than that of *<b>b</b>. */
3020 _compare_old_routers_by_identity(const void **_a
, const void **_b
)
3023 const signed_descriptor_t
*r1
= *_a
, *r2
= *_b
;
3024 if ((i
= memcmp(r1
->identity_digest
, r2
->identity_digest
, DIGEST_LEN
)))
3026 return (int)(r1
->published_on
- r2
->published_on
);
3029 /** Internal type used to represent how long an old descriptor was valid,
3030 * where it appeared in the list of old descriptors, and whether it's extra
3031 * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
3032 struct duration_idx_t
{
3038 /** Sorting helper: compare two duration_idx_t by their duration. */
3040 _compare_duration_idx(const void *_d1
, const void *_d2
)
3042 const struct duration_idx_t
*d1
= _d1
;
3043 const struct duration_idx_t
*d2
= _d2
;
3044 return d1
->duration
- d2
->duration
;
3047 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
3048 * must contain routerinfo_t with the same identity and with publication time
3049 * in ascending order. Remove members from this range until there are no more
3050 * than max_descriptors_per_router() remaining. Start by removing the oldest
3051 * members from before <b>cutoff</b>, then remove members which were current
3052 * for the lowest amount of time. The order of members of old_routers at
3053 * indices <b>lo</b> or higher may be changed.
3056 routerlist_remove_old_cached_routers_with_id(time_t now
,
3057 time_t cutoff
, int lo
, int hi
,
3058 digestset_t
*retain
)
3061 unsigned n_extra
, n_rmv
= 0;
3062 struct duration_idx_t
*lifespans
;
3063 uint8_t *rmv
, *must_keep
;
3064 smartlist_t
*lst
= routerlist
->old_routers
;
3067 tor_assert(hi
< smartlist_len(lst
));
3068 tor_assert(lo
<= hi
);
3069 ident
= ((signed_descriptor_t
*)smartlist_get(lst
, lo
))->identity_digest
;
3070 for (i
= lo
+1; i
<= hi
; ++i
) {
3071 signed_descriptor_t
*r
= smartlist_get(lst
, i
);
3072 tor_assert(!memcmp(ident
, r
->identity_digest
, DIGEST_LEN
));
3075 /* Check whether we need to do anything at all. */
3077 int mdpr
= directory_caches_dir_info(get_options()) ? 2 : 1;
3083 lifespans
= tor_malloc_zero(sizeof(struct duration_idx_t
)*n
);
3084 rmv
= tor_malloc_zero(sizeof(uint8_t)*n
);
3085 must_keep
= tor_malloc_zero(sizeof(uint8_t)*n
);
3086 /* Set lifespans to contain the lifespan and index of each server. */
3087 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
3088 for (i
= lo
; i
<= hi
; ++i
) {
3089 signed_descriptor_t
*r
= smartlist_get(lst
, i
);
3090 signed_descriptor_t
*r_next
;
3091 lifespans
[i
-lo
].idx
= i
;
3092 if (r
->last_listed_as_valid_until
>= now
||
3093 (retain
&& digestset_isin(retain
, r
->signed_descriptor_digest
))) {
3094 must_keep
[i
-lo
] = 1;
3097 r_next
= smartlist_get(lst
, i
+1);
3098 tor_assert(r
->published_on
<= r_next
->published_on
);
3099 lifespans
[i
-lo
].duration
= (int)(r_next
->published_on
- r
->published_on
);
3102 lifespans
[i
-lo
].duration
= INT_MAX
;
3104 if (!must_keep
[i
-lo
] && r
->published_on
< cutoff
&& n_rmv
< n_extra
) {
3106 lifespans
[i
-lo
].old
= 1;
3111 if (n_rmv
< n_extra
) {
3113 * We aren't removing enough servers for being old. Sort lifespans by
3114 * the duration of liveness, and remove the ones we're not already going to
3115 * remove based on how long they were alive.
3117 qsort(lifespans
, n
, sizeof(struct duration_idx_t
), _compare_duration_idx
);
3118 for (i
= 0; i
< n
&& n_rmv
< n_extra
; ++i
) {
3119 if (!must_keep
[lifespans
[i
].idx
-lo
] && !lifespans
[i
].old
) {
3120 rmv
[lifespans
[i
].idx
-lo
] = 1;
3129 routerlist_remove_old(routerlist
, smartlist_get(lst
, i
), i
);
3130 } while (--i
>= lo
);
3131 tor_free(must_keep
);
3133 tor_free(lifespans
);
3136 /** Deactivate any routers from the routerlist that are more than
3137 * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
3138 * remove old routers from the list of cached routers if we have too many.
3141 routerlist_remove_old_routers(void)
3144 const char *cur_id
= NULL
;
3145 time_t now
= time(NULL
);
3147 routerinfo_t
*router
;
3148 signed_descriptor_t
*sd
;
3149 digestset_t
*retain
;
3150 int caches
= directory_caches_dir_info(get_options());
3151 const networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
3152 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
3153 int n_expected_retain
= 0;
3155 trusted_dirs_remove_old_certs();
3157 if (!routerlist
|| !consensus
)
3160 // routerlist_assert_ok(routerlist);
3162 n_expected_retain
= smartlist_len(consensus
->routerstatus_list
);
3164 networkstatus_v2_list
&& smartlist_len(networkstatus_v2_list
)) {
3165 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
3166 n_expected_retain
+= smartlist_len(ns
->entries
));
3167 /*XXXX021 too much magic. */
3168 n_expected_retain
/= (smartlist_len(networkstatus_v2_list
)/2+1);
3170 //log_notice(LD_DIR,"n_expected_retain=%d",n_expected_retain);
3172 retain
= digestset_new(n_expected_retain
);
3174 cutoff
= now
- OLD_ROUTER_DESC_MAX_AGE
;
3175 /* Build a list of all the descriptors that _anybody_ lists. */
3177 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
3179 /* XXXX The inner loop here gets pretty expensive, and actually shows up
3180 * on some profiles. It may be the reason digestmap_set shows up in
3181 * profiles too. If instead we kept a per-descriptor digest count of
3182 * how many networkstatuses recommended each descriptor, and changed
3183 * that only when the networkstatuses changed, that would be a speed
3184 * improvement, possibly 1-4% if it also removes digestmap_set from the
3185 * profile. Not worth it for 0.1.2.x, though. The new directory
3186 * system will obsolete this whole thing in 0.2.0.x. */
3187 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
*, rs
,
3188 if (rs
->published_on
>= cutoff
)
3189 digestset_add(retain
, rs
->descriptor_digest
));
3193 /* Retain anything listed in the consensus. */
3195 SMARTLIST_FOREACH(consensus
->routerstatus_list
, routerstatus_t
*, rs
,
3196 if (rs
->published_on
>= cutoff
)
3197 digestset_add(retain
, rs
->descriptor_digest
));
3200 /* If we have nearly as many networkstatuses as we want, we should consider
3201 * pruning current routers that are too old and that nobody recommends. (If
3202 * we don't have enough networkstatuses, then we should get more before we
3203 * decide to kill routers.) */
3204 /* XXX021 we don't check if we have a v3 consensus, do we? should we? -RD */
3206 smartlist_len(networkstatus_v2_list
) > get_n_v2_authorities() / 2) {
3207 cutoff
= now
- ROUTER_MAX_AGE
;
3208 /* Remove too-old unrecommended members of routerlist->routers. */
3209 for (i
= 0; i
< smartlist_len(routerlist
->routers
); ++i
) {
3210 router
= smartlist_get(routerlist
->routers
, i
);
3211 if (router
->cache_info
.published_on
<= cutoff
&&
3212 router
->cache_info
.last_listed_as_valid_until
< now
&&
3213 !digestset_isin(retain
,
3214 router
->cache_info
.signed_descriptor_digest
)) {
3215 /* Too old: remove it. (If we're a cache, just move it into
3218 "Forgetting obsolete (too old) routerinfo for router '%s'",
3220 routerlist_remove(routerlist
, router
, 1);
3226 //routerlist_assert_ok(routerlist);
3228 /* Remove far-too-old members of routerlist->old_routers. */
3229 cutoff
= now
- OLD_ROUTER_DESC_MAX_AGE
;
3230 for (i
= 0; i
< smartlist_len(routerlist
->old_routers
); ++i
) {
3231 sd
= smartlist_get(routerlist
->old_routers
, i
);
3232 if (sd
->published_on
<= cutoff
&&
3233 sd
->last_listed_as_valid_until
< now
&&
3234 !digestset_isin(retain
, sd
->signed_descriptor_digest
)) {
3235 /* Too old. Remove it. */
3236 routerlist_remove_old(routerlist
, sd
, i
--);
3240 //routerlist_assert_ok(routerlist);
3242 log_info(LD_DIR
, "We have %d live routers and %d old router descriptors.",
3243 smartlist_len(routerlist
->routers
),
3244 smartlist_len(routerlist
->old_routers
));
3246 /* Now we might have to look at routerlist->old_routers for extraneous
3247 * members. (We'd keep all the members if we could, but we need to save
3248 * space.) First, check whether we have too many router descriptors, total.
3249 * We're okay with having too many for some given router, so long as the
3250 * total number doesn't approach max_descriptors_per_router()*len(router).
3252 if (smartlist_len(routerlist
->old_routers
) <
3253 smartlist_len(routerlist
->routers
))
3256 /* Sort by identity, then fix indices. */
3257 smartlist_sort(routerlist
->old_routers
, _compare_old_routers_by_identity
);
3259 for (i
= 0; i
< smartlist_len(routerlist
->old_routers
); ++i
) {
3260 signed_descriptor_t
*r
= smartlist_get(routerlist
->old_routers
, i
);
3261 r
->routerlist_index
= i
;
3264 /* Iterate through the list from back to front, so when we remove descriptors
3265 * we don't mess up groups we haven't gotten to. */
3266 for (i
= smartlist_len(routerlist
->old_routers
)-1; i
>= 0; --i
) {
3267 signed_descriptor_t
*r
= smartlist_get(routerlist
->old_routers
, i
);
3269 cur_id
= r
->identity_digest
;
3272 if (memcmp(cur_id
, r
->identity_digest
, DIGEST_LEN
)) {
3273 routerlist_remove_old_cached_routers_with_id(now
,
3274 cutoff
, i
+1, hi
, retain
);
3275 cur_id
= r
->identity_digest
;
3280 routerlist_remove_old_cached_routers_with_id(now
, cutoff
, 0, hi
, retain
);
3281 //routerlist_assert_ok(routerlist);
3284 digestset_free(retain
);
3285 router_rebuild_store(RRS_DONT_REMOVE_OLD
, &routerlist
->desc_store
);
3286 router_rebuild_store(RRS_DONT_REMOVE_OLD
,&routerlist
->extrainfo_store
);
3289 /** We just added a new set of descriptors. Take whatever extra steps
3292 routerlist_descriptors_added(smartlist_t
*sl
, int from_cache
)
3295 control_event_descriptors_changed(sl
);
3296 SMARTLIST_FOREACH(sl
, routerinfo_t
*, ri
,
3297 if (ri
->purpose
== ROUTER_PURPOSE_BRIDGE
)
3298 learned_bridge_descriptor(ri
, from_cache
);
3303 * Code to parse a single router descriptor and insert it into the
3304 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
3305 * descriptor was well-formed but could not be added; and 1 if the
3306 * descriptor was added.
3308 * If we don't add it and <b>msg</b> is not NULL, then assign to
3309 * *<b>msg</b> a static string describing the reason for refusing the
3312 * This is used only by the controller.
3315 router_load_single_router(const char *s
, uint8_t purpose
, int cache
,
3321 char annotation_buf
[ROUTER_ANNOTATION_BUF_LEN
];
3325 tor_snprintf(annotation_buf
, sizeof(annotation_buf
),
3326 "@source controller\n"
3327 "@purpose %s\n", router_purpose_to_string(purpose
));
3329 if (!(ri
= router_parse_entry_from_string(s
, NULL
, 1, 0, annotation_buf
))) {
3330 log_warn(LD_DIR
, "Error parsing router descriptor; dropping.");
3331 *msg
= "Couldn't parse router descriptor.";
3334 tor_assert(ri
->purpose
== purpose
);
3335 if (router_is_me(ri
)) {
3336 log_warn(LD_DIR
, "Router's identity key matches mine; dropping.");
3337 *msg
= "Router's identity key matches mine.";
3338 routerinfo_free(ri
);
3342 if (!cache
) /* obey the preference of the controller */
3343 ri
->cache_info
.do_not_cache
= 1;
3345 lst
= smartlist_create();
3346 smartlist_add(lst
, ri
);
3347 routers_update_status_from_consensus_networkstatus(lst
, 0);
3349 if ((r
=router_add_to_routerlist(ri
, msg
, 0, 0))<0) {
3350 /* we've already assigned to *msg now, and ri is already freed */
3353 log_warn(LD_DIR
, "Couldn't add router to list: %s Dropping.", *msg
);
3354 smartlist_free(lst
);
3357 routerlist_descriptors_added(lst
, 0);
3358 smartlist_free(lst
);
3359 log_debug(LD_DIR
, "Added router to list");
3364 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
3365 * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
3366 * are in response to a query to the network: cache them by adding them to
3369 * If <b>requested_fingerprints</b> is provided, it must contain a list of
3370 * uppercased fingerprints. Do not update any router whose
3371 * fingerprint is not on the list; after updating a router, remove its
3372 * fingerprint from the list.
3374 * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
3375 * are descriptor digests. Otherwise they are identity digests.
3378 router_load_routers_from_string(const char *s
, const char *eos
,
3379 saved_location_t saved_location
,
3380 smartlist_t
*requested_fingerprints
,
3381 int descriptor_digests
,
3382 const char *prepend_annotations
)
3384 smartlist_t
*routers
= smartlist_create(), *changed
= smartlist_create();
3385 char fp
[HEX_DIGEST_LEN
+1];
3387 int from_cache
= (saved_location
!= SAVED_NOWHERE
);
3388 int allow_annotations
= (saved_location
!= SAVED_NOWHERE
);
3389 int any_changed
= 0;
3391 router_parse_list_from_string(&s
, eos
, routers
, saved_location
, 0,
3392 allow_annotations
, prepend_annotations
);
3394 routers_update_status_from_consensus_networkstatus(routers
, !from_cache
);
3396 log_info(LD_DIR
, "%d elements to add", smartlist_len(routers
));
3398 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
,
3400 if (requested_fingerprints
) {
3401 base16_encode(fp
, sizeof(fp
), descriptor_digests
?
3402 ri
->cache_info
.signed_descriptor_digest
:
3403 ri
->cache_info
.identity_digest
,
3405 if (smartlist_string_isin(requested_fingerprints
, fp
)) {
3406 smartlist_string_remove(requested_fingerprints
, fp
);
3409 smartlist_join_strings(requested_fingerprints
," ",0,NULL
);
3411 "We received a router descriptor with a fingerprint (%s) "
3412 "that we never requested. (We asked for: %s.) Dropping.",
3414 tor_free(requested
);
3415 routerinfo_free(ri
);
3420 if (router_add_to_routerlist(ri
, &msg
, from_cache
, !from_cache
) >= 0) {
3422 smartlist_add(changed
, ri
);
3423 routerlist_descriptors_added(changed
, from_cache
);
3424 smartlist_clear(changed
);
3428 routerlist_assert_ok(routerlist
);
3431 router_rebuild_store(0, &routerlist
->desc_store
);
3433 smartlist_free(routers
);
3434 smartlist_free(changed
);
3437 /** Parse one or more extrainfos from <b>s</b> (ending immediately before
3438 * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
3439 * router_load_routers_from_string(). */
3441 router_load_extrainfo_from_string(const char *s
, const char *eos
,
3442 saved_location_t saved_location
,
3443 smartlist_t
*requested_fingerprints
,
3444 int descriptor_digests
)
3446 smartlist_t
*extrainfo_list
= smartlist_create();
3448 int from_cache
= (saved_location
!= SAVED_NOWHERE
);
3450 router_parse_list_from_string(&s
, eos
, extrainfo_list
, saved_location
, 1, 0,
3453 log_info(LD_DIR
, "%d elements to add", smartlist_len(extrainfo_list
));
3455 SMARTLIST_FOREACH(extrainfo_list
, extrainfo_t
*, ei
, {
3457 router_add_extrainfo_to_routerlist(ei
, &msg
, from_cache
, !from_cache
);
3458 if (added
&& requested_fingerprints
) {
3459 char fp
[HEX_DIGEST_LEN
+1];
3460 base16_encode(fp
, sizeof(fp
), descriptor_digests
?
3461 ei
->cache_info
.signed_descriptor_digest
:
3462 ei
->cache_info
.identity_digest
,
3464 smartlist_string_remove(requested_fingerprints
, fp
);
3465 /* We silently let people stuff us with extrainfos we didn't ask for,
3466 * so long as we would have wanted them anyway. Since we always fetch
3467 * all the extrainfos we want, and we never actually act on them
3468 * inside Tor, this should be harmless. */
3472 routerlist_assert_ok(routerlist
);
3473 router_rebuild_store(0, &router_get_routerlist()->extrainfo_store
);
3475 smartlist_free(extrainfo_list
);
3478 /** Return true iff any networkstatus includes a descriptor whose digest
3479 * is that of <b>desc</b>. */
3481 signed_desc_digest_is_recognized(signed_descriptor_t
*desc
)
3484 networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
3485 int caches
= directory_caches_dir_info(get_options());
3486 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
3489 rs
= networkstatus_vote_find_entry(consensus
, desc
->identity_digest
);
3490 if (rs
&& !memcmp(rs
->descriptor_digest
,
3491 desc
->signed_descriptor_digest
, DIGEST_LEN
))
3494 if (caches
&& networkstatus_v2_list
) {
3495 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
3497 if (!(rs
= networkstatus_v2_find_entry(ns
, desc
->identity_digest
)))
3499 if (!memcmp(rs
->descriptor_digest
,
3500 desc
->signed_descriptor_digest
, DIGEST_LEN
))
3507 /** Clear all our timeouts for fetching v2 and v3 directory stuff, and then
3508 * give it all a try again. */
3510 routerlist_retry_directory_downloads(time_t now
)
3512 router_reset_status_download_failures();
3513 router_reset_descriptor_download_failures();
3514 update_networkstatus_downloads(now
);
3515 update_router_descriptor_downloads(now
);
3518 /** Return 1 if all running sufficiently-stable routers will reject
3519 * addr:port, return 0 if any might accept it. */
3521 router_exit_policy_all_routers_reject(uint32_t addr
, uint16_t port
,
3524 addr_policy_result_t r
;
3525 if (!routerlist
) return 1;
3527 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
3529 if (router
->is_running
&&
3530 !router_is_unreliable(router
, need_uptime
, 0, 0)) {
3531 r
= compare_addr_to_addr_policy(addr
, port
, router
->exit_policy
);
3532 if (r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
)
3533 return 0; /* this one could be ok. good enough. */
3536 return 1; /* all will reject. */
3539 /** Return true iff <b>router</b> does not permit exit streams.
3542 router_exit_policy_rejects_all(routerinfo_t
*router
)
3544 return compare_addr_to_addr_policy(0, 0, router
->exit_policy
)
3545 == ADDR_POLICY_REJECTED
;
3548 /** Add to the list of authorized directory servers one at
3549 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
3550 * <b>address</b> is NULL, add ourself. Return 0 if success, -1 if
3551 * we couldn't add it. */
3552 trusted_dir_server_t
*
3553 add_trusted_dir_server(const char *nickname
, const char *address
,
3554 uint16_t dir_port
, uint16_t or_port
,
3555 const char *digest
, const char *v3_auth_digest
,
3556 authority_type_t type
)
3558 trusted_dir_server_t
*ent
;
3560 char *hostname
= NULL
;
3562 if (!trusted_dir_servers
)
3563 trusted_dir_servers
= smartlist_create();
3565 if (!address
) { /* The address is us; we should guess. */
3566 if (resolve_my_address(LOG_WARN
, get_options(), &a
, &hostname
) < 0) {
3568 "Couldn't find a suitable address when adding ourself as a "
3569 "trusted directory server.");
3573 if (tor_lookup_hostname(address
, &a
)) {
3575 "Unable to lookup address for directory server at '%s'",
3579 hostname
= tor_strdup(address
);
3582 ent
= tor_malloc_zero(sizeof(trusted_dir_server_t
));
3583 ent
->nickname
= nickname
? tor_strdup(nickname
) : NULL
;
3584 ent
->address
= hostname
;
3586 ent
->dir_port
= dir_port
;
3587 ent
->or_port
= or_port
;
3588 ent
->is_running
= 1;
3590 memcpy(ent
->digest
, digest
, DIGEST_LEN
);
3591 if (v3_auth_digest
&& (type
& V3_AUTHORITY
))
3592 memcpy(ent
->v3_identity_digest
, v3_auth_digest
, DIGEST_LEN
);
3594 dlen
= 64 + strlen(hostname
) + (nickname
?strlen(nickname
):0);
3595 ent
->description
= tor_malloc(dlen
);
3597 tor_snprintf(ent
->description
, dlen
, "directory server \"%s\" at %s:%d",
3598 nickname
, hostname
, (int)dir_port
);
3600 tor_snprintf(ent
->description
, dlen
, "directory server at %s:%d",
3601 hostname
, (int)dir_port
);
3603 ent
->fake_status
.addr
= ent
->addr
;
3604 memcpy(ent
->fake_status
.identity_digest
, digest
, DIGEST_LEN
);
3606 strlcpy(ent
->fake_status
.nickname
, nickname
,
3607 sizeof(ent
->fake_status
.nickname
));
3609 ent
->fake_status
.nickname
[0] = '\0';
3610 ent
->fake_status
.dir_port
= ent
->dir_port
;
3611 ent
->fake_status
.or_port
= ent
->or_port
;
3614 ent
->fake_status
.version_supports_begindir
= 1;
3615 /* XX021 - wait until authorities are upgraded */
3617 ent
->fake_status
.version_supports_conditional_consensus
= 1;
3619 ent
->fake_status
.version_supports_conditional_consensus
= 0;
3622 smartlist_add(trusted_dir_servers
, ent
);
3623 router_dir_info_changed();
3627 /** Free storage held in <b>cert</b>. */
3629 authority_cert_free(authority_cert_t
*cert
)
3634 tor_free(cert
->cache_info
.signed_descriptor_body
);
3635 if (cert
->signing_key
)
3636 crypto_free_pk_env(cert
->signing_key
);
3637 if (cert
->identity_key
)
3638 crypto_free_pk_env(cert
->identity_key
);
3643 /** Free storage held in <b>ds</b>. */
3645 trusted_dir_server_free(trusted_dir_server_t
*ds
)
3647 tor_free(ds
->nickname
);
3648 tor_free(ds
->description
);
3649 tor_free(ds
->address
);
3653 /** Remove all members from the list of trusted dir servers. */
3655 clear_trusted_dir_servers(void)
3657 if (trusted_dir_servers
) {
3658 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
3659 trusted_dir_server_free(ent
));
3660 smartlist_clear(trusted_dir_servers
);
3662 trusted_dir_servers
= smartlist_create();
3664 router_dir_info_changed();
3667 /** Return 1 if any trusted dir server supports v1 directories,
3670 any_trusted_dir_is_v1_authority(void)
3672 if (trusted_dir_servers
)
3673 return get_n_authorities(V1_AUTHORITY
) > 0;
3678 /** For every current directory connection whose purpose is <b>purpose</b>,
3679 * and where the resource being downloaded begins with <b>prefix</b>, split
3680 * rest of the resource into base16 fingerprints, decode them, and set the
3681 * corresponding elements of <b>result</b> to a nonzero value. */
3683 list_pending_downloads(digestmap_t
*result
,
3684 int purpose
, const char *prefix
)
3686 const size_t p_len
= strlen(prefix
);
3687 smartlist_t
*tmp
= smartlist_create();
3688 smartlist_t
*conns
= get_connection_array();
3692 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3694 if (conn
->type
== CONN_TYPE_DIR
&&
3695 conn
->purpose
== purpose
&&
3696 !conn
->marked_for_close
) {
3697 const char *resource
= TO_DIR_CONN(conn
)->requested_resource
;
3698 if (!strcmpstart(resource
, prefix
))
3699 dir_split_resource_into_fingerprints(resource
+ p_len
,
3703 SMARTLIST_FOREACH(tmp
, char *, d
,
3705 digestmap_set(result
, d
, (void*)1);
3708 smartlist_free(tmp
);
3711 /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
3712 * true) we are currently downloading by descriptor digest, set result[d] to
3715 list_pending_descriptor_downloads(digestmap_t
*result
, int extrainfo
)
3718 extrainfo
? DIR_PURPOSE_FETCH_EXTRAINFO
: DIR_PURPOSE_FETCH_SERVERDESC
;
3719 list_pending_downloads(result
, purpose
, "d/");
3722 /** Launch downloads for all the descriptors whose digests are listed
3723 * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
3724 * If <b>source</b> is given, download from <b>source</b>; otherwise,
3725 * download from an appropriate random directory server.
3728 initiate_descriptor_downloads(routerstatus_t
*source
,
3730 smartlist_t
*digests
,
3734 char *resource
, *cp
;
3740 if (hi
> smartlist_len(digests
))
3741 hi
= smartlist_len(digests
);
3743 r_len
= 8 + (HEX_DIGEST_LEN
+1)*n
;
3744 cp
= resource
= tor_malloc(r_len
);
3745 memcpy(cp
, "d/", 2);
3747 for (i
= lo
; i
< hi
; ++i
) {
3748 base16_encode(cp
, r_len
-(cp
-resource
),
3749 smartlist_get(digests
,i
), DIGEST_LEN
);
3750 cp
+= HEX_DIGEST_LEN
;
3753 memcpy(cp
-1, ".z", 3);
3756 /* We know which authority we want. */
3757 directory_initiate_command_routerstatus(source
, purpose
,
3758 ROUTER_PURPOSE_GENERAL
,
3759 0, /* not private */
3760 resource
, NULL
, 0, 0);
3762 directory_get_from_dirserver(purpose
, ROUTER_PURPOSE_GENERAL
, resource
, 1);
3767 /** Return 0 if this routerstatus is obsolete, too new, isn't
3768 * running, or otherwise not a descriptor that we would make any
3769 * use of even if we had it. Else return 1. */
3771 client_would_use_router(routerstatus_t
*rs
, time_t now
, or_options_t
*options
)
3773 if (!rs
->is_running
&& !options
->FetchUselessDescriptors
) {
3774 /* If we had this router descriptor, we wouldn't even bother using it.
3775 * But, if we want to have a complete list, fetch it anyway. */
3778 if (rs
->published_on
+ options
->TestingEstimatedDescriptorPropagationTime
3780 /* Most caches probably don't have this descriptor yet. */
3783 if (rs
->published_on
+ OLD_ROUTER_DESC_MAX_AGE
< now
) {
3784 /* We'd drop it immediately for being too old. */
3790 /** Max amount of hashes to download per request.
3791 * Since squid does not like URLs >= 4096 bytes we limit it to 96.
3792 * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
3793 * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
3794 * So use 96 because it's a nice number.
3796 #define MAX_DL_PER_REQUEST 96
3797 /** Don't split our requests so finely that we are requesting fewer than
3798 * this number per server. */
3799 #define MIN_DL_PER_REQUEST 4
3800 /** To prevent a single screwy cache from confusing us by selective reply,
3801 * try to split our requests into at least this this many requests. */
3802 #define MIN_REQUESTS 3
3803 /** If we want fewer than this many descriptors, wait until we
3804 * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
3806 #define MAX_DL_TO_DELAY 16
3807 /** When directory clients have only a few servers to request, they batch
3808 * them until they have more, or until this amount of time has passed. */
3809 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
3811 /** Given a list of router descriptor digests in <b>downloadable</b>, decide
3812 * whether to delay fetching until we have more. If we don't want to delay,
3813 * launch one or more requests to the appropriate directory authorities. */
3815 launch_router_descriptor_downloads(smartlist_t
*downloadable
, time_t now
)
3817 int should_delay
= 0, n_downloadable
;
3818 or_options_t
*options
= get_options();
3820 n_downloadable
= smartlist_len(downloadable
);
3821 if (!directory_fetches_dir_info_early(options
)) {
3822 if (n_downloadable
>= MAX_DL_TO_DELAY
) {
3824 "There are enough downloadable routerdescs to launch requests.");
3827 should_delay
= (last_routerdesc_download_attempted
+
3828 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST
) > now
;
3829 if (!should_delay
&& n_downloadable
) {
3830 if (last_routerdesc_download_attempted
) {
3832 "There are not many downloadable routerdescs, but we've "
3833 "been waiting long enough (%d seconds). Downloading.",
3834 (int)(now
-last_routerdesc_download_attempted
));
3837 "There are not many downloadable routerdescs, but we haven't "
3838 "tried downloading descriptors recently. Downloading.");
3843 /* XXX should we consider having even the dir mirrors delay
3844 * a little bit, so we don't load the authorities as much? -RD
3845 * I don't think so. If we do, clients that want those descriptors may
3846 * not actually find them if the caches haven't got them yet. -NM
3849 if (! should_delay
&& n_downloadable
) {
3850 int i
, n_per_request
;
3851 const char *req_plural
= "", *rtr_plural
= "";
3852 n_per_request
= (n_downloadable
+MIN_REQUESTS
-1) / MIN_REQUESTS
;
3853 if (n_per_request
> MAX_DL_PER_REQUEST
)
3854 n_per_request
= MAX_DL_PER_REQUEST
;
3855 if (n_per_request
< MIN_DL_PER_REQUEST
)
3856 n_per_request
= MIN_DL_PER_REQUEST
;
3858 if (n_downloadable
> n_per_request
)
3859 req_plural
= rtr_plural
= "s";
3860 else if (n_downloadable
> 1)
3864 "Launching %d request%s for %d router%s, %d at a time",
3865 (n_downloadable
+n_per_request
-1)/n_per_request
,
3866 req_plural
, n_downloadable
, rtr_plural
, n_per_request
);
3867 smartlist_sort_digests(downloadable
);
3868 for (i
=0; i
< n_downloadable
; i
+= n_per_request
) {
3869 initiate_descriptor_downloads(NULL
, DIR_PURPOSE_FETCH_SERVERDESC
,
3870 downloadable
, i
, i
+n_per_request
);
3872 last_routerdesc_download_attempted
= now
;
3876 /** Launch downloads for router status as needed, using the strategy used by
3877 * authorities and caches: based on the v2 networkstatuses we have, download
3878 * every descriptor we don't have but would serve, from a random authority
3881 update_router_descriptor_cache_downloads_v2(time_t now
)
3883 smartlist_t
**downloadable
; /* For each authority, what can we dl from it? */
3884 smartlist_t
**download_from
; /* ... and, what will we dl from it? */
3885 digestmap_t
*map
; /* Which descs are in progress, or assigned? */
3888 or_options_t
*options
= get_options();
3889 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
3891 if (! directory_fetches_dir_info_early(options
)) {
3892 log_warn(LD_BUG
, "Called update_router_descriptor_cache_downloads_v2() "
3893 "on a non-dir-mirror?");
3896 if (!networkstatus_v2_list
|| !smartlist_len(networkstatus_v2_list
))
3899 map
= digestmap_new();
3900 n
= smartlist_len(networkstatus_v2_list
);
3902 downloadable
= tor_malloc_zero(sizeof(smartlist_t
*) * n
);
3903 download_from
= tor_malloc_zero(sizeof(smartlist_t
*) * n
);
3905 /* Set map[d]=1 for the digest of every descriptor that we are currently
3907 list_pending_descriptor_downloads(map
, 0);
3909 /* For the digest of every descriptor that we don't have, and that we aren't
3910 * downloading, add d to downloadable[i] if the i'th networkstatus knows
3911 * about that descriptor, and we haven't already failed to get that
3912 * descriptor from the corresponding authority.
3915 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
3917 trusted_dir_server_t
*ds
;
3919 dl
= downloadable
[ns_sl_idx
] = smartlist_create();
3920 download_from
[ns_sl_idx
] = smartlist_create();
3921 if (ns
->published_on
+ MAX_NETWORKSTATUS_AGE
+10*60 < now
) {
3922 /* Don't download if the networkstatus is almost ancient. */
3923 /* Actually, I suspect what's happening here is that we ask
3924 * for the descriptor when we have a given networkstatus,
3925 * and then we get a newer networkstatus, and then we receive
3926 * the descriptor. Having a networkstatus actually expire is
3927 * probably a rare event, and we'll probably be happiest if
3928 * we take this clause out. -RD */
3932 /* Don't try dirservers that we think are down -- we might have
3933 * just tried them and just marked them as down. */
3934 ds
= router_get_trusteddirserver_by_digest(ns
->identity_digest
);
3935 if (ds
&& !ds
->is_running
)
3938 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
* , rs
,
3940 if (!rs
->need_to_mirror
)
3942 if (router_get_by_descriptor_digest(rs
->descriptor_digest
)) {
3944 "We have a router descriptor, but need_to_mirror=1.");
3945 rs
->need_to_mirror
= 0;
3948 if (authdir_mode(options
) && dirserv_would_reject_router(rs
)) {
3949 rs
->need_to_mirror
= 0;
3952 if (digestmap_get(map
, rs
->descriptor_digest
)) {
3953 /* We're downloading it already. */
3956 /* We could download it from this guy. */
3957 smartlist_add(dl
, rs
->descriptor_digest
);
3963 /* At random, assign descriptors to authorities such that:
3964 * - if d is a member of some downloadable[x], d is a member of some
3965 * download_from[y]. (Everything we want to download, we try to download
3967 * - If d is a member of download_from[y], d is a member of downloadable[y].
3968 * (We only try to download descriptors from authorities who claim to have
3970 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
3971 * (We don't try to download anything from two authorities concurrently.)
3973 while (n_download
) {
3974 int which_ns
= crypto_rand_int(n
);
3975 smartlist_t
*dl
= downloadable
[which_ns
];
3978 if (!smartlist_len(dl
))
3980 idx
= crypto_rand_int(smartlist_len(dl
));
3981 d
= smartlist_get(dl
, idx
);
3982 if (! digestmap_get(map
, d
)) {
3983 smartlist_add(download_from
[which_ns
], d
);
3984 digestmap_set(map
, d
, (void*) 1);
3986 smartlist_del(dl
, idx
);
3990 /* Now, we can actually launch our requests. */
3991 for (i
=0; i
<n
; ++i
) {
3992 networkstatus_v2_t
*ns
= smartlist_get(networkstatus_v2_list
, i
);
3993 trusted_dir_server_t
*ds
=
3994 router_get_trusteddirserver_by_digest(ns
->identity_digest
);
3995 smartlist_t
*dl
= download_from
[i
];
3997 log_warn(LD_BUG
, "Networkstatus with no corresponding authority!");
4000 if (! smartlist_len(dl
))
4002 log_info(LD_DIR
, "Requesting %d descriptors from authority \"%s\"",
4003 smartlist_len(dl
), ds
->nickname
);
4004 for (j
=0; j
< smartlist_len(dl
); j
+= MAX_DL_PER_REQUEST
) {
4005 initiate_descriptor_downloads(&(ds
->fake_status
),
4006 DIR_PURPOSE_FETCH_SERVERDESC
, dl
, j
,
4007 j
+MAX_DL_PER_REQUEST
);
4011 for (i
=0; i
<n
; ++i
) {
4012 smartlist_free(download_from
[i
]);
4013 smartlist_free(downloadable
[i
]);
4015 tor_free(download_from
);
4016 tor_free(downloadable
);
4017 digestmap_free(map
,NULL
);
4020 /** For any descriptor that we want that's currently listed in the live
4021 * consensus, download it as appropriate. */
4023 update_consensus_router_descriptor_downloads(time_t now
)
4025 or_options_t
*options
= get_options();
4026 digestmap_t
*map
= NULL
;
4027 smartlist_t
*no_longer_old
= smartlist_create();
4028 smartlist_t
*downloadable
= smartlist_create();
4029 int authdir
= authdir_mode(options
);
4030 networkstatus_t
*consensus
=
4031 networkstatus_get_reasonably_live_consensus(now
);
4032 int n_delayed
=0, n_have
=0, n_would_reject
=0, n_wouldnt_use
=0,
4033 n_inprogress
=0, n_in_oldrouters
=0;
4035 if (directory_too_idle_to_fetch_descriptors(options
, now
))
4040 map
= digestmap_new();
4041 list_pending_descriptor_downloads(map
, 0);
4042 SMARTLIST_FOREACH(consensus
->routerstatus_list
, routerstatus_t
*, rs
,
4044 signed_descriptor_t
*sd
;
4045 if ((sd
= router_get_by_descriptor_digest(rs
->descriptor_digest
))) {
4048 if (!(ri
= router_get_by_digest(rs
->identity_digest
)) ||
4049 memcmp(ri
->cache_info
.signed_descriptor_digest
,
4050 sd
->signed_descriptor_digest
, DIGEST_LEN
)) {
4051 /* We have a descriptor with this digest, but either there is no
4052 * entry in routerlist with the same ID (!ri), or there is one,
4053 * but the identity digest differs (memcmp).
4055 smartlist_add(no_longer_old
, sd
);
4056 ++n_in_oldrouters
; /* We have it in old_routers. */
4058 continue; /* We have it already. */
4060 if (digestmap_get(map
, rs
->descriptor_digest
)) {
4062 continue; /* We have an in-progress download. */
4064 if (!download_status_is_ready(&rs
->dl_status
, now
,
4065 MAX_ROUTERDESC_DOWNLOAD_FAILURES
)) {
4066 ++n_delayed
; /* Not ready for retry. */
4069 if (authdir
&& dirserv_would_reject_router(rs
)) {
4071 continue; /* We would throw it out immediately. */
4073 if (!directory_caches_dir_info(options
) &&
4074 !client_would_use_router(rs
, now
, options
)) {
4076 continue; /* We would never use it ourself. */
4078 smartlist_add(downloadable
, rs
->descriptor_digest
);
4081 if (!authdir_mode_handles_descs(options
, ROUTER_PURPOSE_GENERAL
)
4082 && smartlist_len(no_longer_old
)) {
4083 routerlist_t
*rl
= router_get_routerlist();
4084 log_info(LD_DIR
, "%d router descriptors listed in consensus are "
4085 "currently in old_routers; making them current.",
4086 smartlist_len(no_longer_old
));
4087 SMARTLIST_FOREACH(no_longer_old
, signed_descriptor_t
*, sd
, {
4090 routerinfo_t
*ri
= routerlist_reparse_old(rl
, sd
);
4092 log_warn(LD_BUG
, "Failed to re-parse a router.");
4095 r
= router_add_to_routerlist(ri
, &msg
, 1, 0);
4097 log_warn(LD_DIR
, "Couldn't add re-parsed router: %s",
4101 routerlist_assert_ok(rl
);
4105 "%d router descriptors downloadable. %d delayed; %d present "
4106 "(%d of those were in old_routers); %d would_reject; "
4107 "%d wouldnt_use; %d in progress.",
4108 smartlist_len(downloadable
), n_delayed
, n_have
, n_in_oldrouters
,
4109 n_would_reject
, n_wouldnt_use
, n_inprogress
);
4111 launch_router_descriptor_downloads(downloadable
, now
);
4113 digestmap_free(map
, NULL
);
4115 smartlist_free(downloadable
);
4116 smartlist_free(no_longer_old
);
4119 /** How often should we launch a server/authority request to be sure of getting
4120 * a guess for our IP? */
4121 /*XXXX021 this info should come from netinfo cells or something, or we should
4122 * do this only when we aren't seeing incoming data. see bug 652. */
4123 #define DUMMY_DOWNLOAD_INTERVAL (20*60)
4125 /** Launch downloads for router status as needed. */
4127 update_router_descriptor_downloads(time_t now
)
4129 or_options_t
*options
= get_options();
4130 static time_t last_dummy_download
= 0;
4131 if (should_delay_dir_fetches(options
))
4133 if (directory_fetches_dir_info_early(options
)) {
4134 update_router_descriptor_cache_downloads_v2(now
);
4136 update_consensus_router_descriptor_downloads(now
);
4138 /* XXXX021 we could be smarter here; see notes on bug 652. */
4139 /* If we're a server that doesn't have a configured address, we rely on
4140 * directory fetches to learn when our address changes. So if we haven't
4141 * tried to get any routerdescs in a long time, try a dummy fetch now. */
4142 if (!options
->Address
&&
4143 server_mode(options
) &&
4144 last_routerdesc_download_attempted
+ DUMMY_DOWNLOAD_INTERVAL
< now
&&
4145 last_dummy_download
+ DUMMY_DOWNLOAD_INTERVAL
< now
) {
4146 last_dummy_download
= now
;
4147 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC
,
4148 ROUTER_PURPOSE_GENERAL
, "authority.z", 1);
4152 /** Launch extrainfo downloads as needed. */
4154 update_extrainfo_downloads(time_t now
)
4156 or_options_t
*options
= get_options();
4158 smartlist_t
*wanted
;
4159 digestmap_t
*pending
;
4161 int n_no_ei
= 0, n_pending
= 0, n_have
= 0, n_delay
= 0;
4162 if (! options
->DownloadExtraInfo
)
4164 if (should_delay_dir_fetches(options
))
4166 if (!router_have_minimum_dir_info())
4169 pending
= digestmap_new();
4170 list_pending_descriptor_downloads(pending
, 1);
4171 rl
= router_get_routerlist();
4172 wanted
= smartlist_create();
4173 for (old_routers
= 0; old_routers
< 2; ++old_routers
) {
4174 smartlist_t
*lst
= old_routers
? rl
->old_routers
: rl
->routers
;
4175 for (i
= 0; i
< smartlist_len(lst
); ++i
) {
4176 signed_descriptor_t
*sd
;
4179 sd
= smartlist_get(lst
, i
);
4181 sd
= &((routerinfo_t
*)smartlist_get(lst
, i
))->cache_info
;
4182 if (sd
->is_extrainfo
)
4183 continue; /* This should never happen. */
4184 if (old_routers
&& !router_get_by_digest(sd
->identity_digest
))
4185 continue; /* Couldn't check the signature if we got it. */
4186 if (sd
->extrainfo_is_bogus
)
4188 d
= sd
->extra_info_digest
;
4189 if (tor_digest_is_zero(d
)) {
4193 if (eimap_get(rl
->extra_info_map
, d
)) {
4197 if (!download_status_is_ready(&sd
->ei_dl_status
, now
,
4198 MAX_ROUTERDESC_DOWNLOAD_FAILURES
)) {
4202 if (digestmap_get(pending
, d
)) {
4206 smartlist_add(wanted
, d
);
4209 digestmap_free(pending
, NULL
);
4211 log_info(LD_DIR
, "Extrainfo download status: %d router with no ei, %d "
4212 "with present ei, %d delaying, %d pending, %d downloadable.",
4213 n_no_ei
, n_have
, n_delay
, n_pending
, smartlist_len(wanted
));
4215 smartlist_shuffle(wanted
);
4216 for (i
= 0; i
< smartlist_len(wanted
); i
+= MAX_DL_PER_REQUEST
) {
4217 initiate_descriptor_downloads(NULL
, DIR_PURPOSE_FETCH_EXTRAINFO
,
4218 wanted
, i
, i
+ MAX_DL_PER_REQUEST
);
4221 smartlist_free(wanted
);
4224 /** True iff, the last time we checked whether we had enough directory info
4225 * to build circuits, the answer was "yes". */
4226 static int have_min_dir_info
= 0;
4227 /** True iff enough has changed since the last time we checked whether we had
4228 * enough directory info to build circuits that our old answer can no longer
4230 static int need_to_update_have_min_dir_info
= 1;
4231 /** String describing what we're missing before we have enough directory
4233 static char dir_info_status
[128] = "";
4235 /** Return true iff we have enough networkstatus and router information to
4236 * start building circuits. Right now, this means "more than half the
4237 * networkstatus documents, and at least 1/4 of expected routers." */
4238 //XXX should consider whether we have enough exiting nodes here.
4240 router_have_minimum_dir_info(void)
4242 if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info
)) {
4243 update_router_have_minimum_dir_info();
4244 need_to_update_have_min_dir_info
= 0;
4246 return have_min_dir_info
;
4249 /** Called when our internal view of the directory has changed. This can be
4250 * when the authorities change, networkstatuses change, the list of routerdescs
4251 * changes, or number of running routers changes.
4254 router_dir_info_changed(void)
4256 need_to_update_have_min_dir_info
= 1;
4257 rend_hsdir_routers_changed();
4260 /** Return a string describing what we're missing before we have enough
4261 * directory info. */
4263 get_dir_info_status_string(void)
4265 return dir_info_status
;
4269 count_usable_descriptors(int *num_present
, int *num_usable
,
4270 const networkstatus_t
*consensus
,
4271 or_options_t
*options
, time_t now
)
4273 *num_present
= 0, *num_usable
=0;
4275 SMARTLIST_FOREACH(consensus
->routerstatus_list
, routerstatus_t
*, rs
,
4277 if (client_would_use_router(rs
, now
, options
)) {
4278 ++*num_usable
; /* the consensus says we want it. */
4279 if (router_get_by_descriptor_digest(rs
->descriptor_digest
)) {
4280 /* we have the descriptor listed in the consensus. */
4286 log_debug(LD_DIR
, "%d usable, %d present.", *num_usable
, *num_present
);
4289 /** We just fetched a new set of descriptors. Compute how far through
4290 * the "loading descriptors" bootstrapping phase we are, so we can inform
4291 * the controller of our progress. */
4293 count_loading_descriptors_progress(void)
4295 int num_present
= 0, num_usable
=0;
4296 time_t now
= time(NULL
);
4297 const networkstatus_t
*consensus
=
4298 networkstatus_get_reasonably_live_consensus(now
);
4302 return 0; /* can't count descriptors if we have no list of them */
4304 count_usable_descriptors(&num_present
, &num_usable
,
4305 consensus
, get_options(), now
);
4307 if (num_usable
== 0)
4308 return 0; /* don't div by 0 */
4309 fraction
= num_present
/ (num_usable
/4.);
4311 return 0; /* it's not the number of descriptors holding us back */
4312 return BOOTSTRAP_STATUS_LOADING_DESCRIPTORS
+ (int)
4313 (fraction
*(BOOTSTRAP_STATUS_CONN_OR
-1 -
4314 BOOTSTRAP_STATUS_LOADING_DESCRIPTORS
));
4317 /** Change the value of have_min_dir_info, setting it true iff we have enough
4318 * network and router information to build circuits. Clear the value of
4319 * need_to_update_have_min_dir_info. */
4321 update_router_have_minimum_dir_info(void)
4323 int num_present
= 0, num_usable
=0;
4324 time_t now
= time(NULL
);
4326 or_options_t
*options
= get_options();
4327 const networkstatus_t
*consensus
=
4328 networkstatus_get_reasonably_live_consensus(now
);
4331 if (!networkstatus_get_latest_consensus())
4332 strlcpy(dir_info_status
, "We have no network-status consensus.",
4333 sizeof(dir_info_status
));
4335 strlcpy(dir_info_status
, "We have no recent network-status consensus.",
4336 sizeof(dir_info_status
));
4341 if (should_delay_dir_fetches(get_options())) {
4342 log_notice(LD_DIR
, "no known bridge descriptors running yet; stalling");
4343 strlcpy(dir_info_status
, "No live bridge descriptors.",
4344 sizeof(dir_info_status
));
4349 count_usable_descriptors(&num_present
, &num_usable
, consensus
, options
, now
);
4351 if (num_present
< num_usable
/4) {
4352 tor_snprintf(dir_info_status
, sizeof(dir_info_status
),
4353 "We have only %d/%d usable descriptors.", num_present
, num_usable
);
4355 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS
, 0);
4356 } else if (num_present
< 2) {
4357 tor_snprintf(dir_info_status
, sizeof(dir_info_status
),
4358 "Only %d descriptor%s here and believed reachable!",
4359 num_present
, num_present
? "" : "s");
4366 if (res
&& !have_min_dir_info
) {
4367 log(LOG_NOTICE
, LD_DIR
,
4368 "We now have enough directory information to build circuits.");
4369 control_event_client_status(LOG_NOTICE
, "ENOUGH_DIR_INFO");
4370 control_event_bootstrap(BOOTSTRAP_STATUS_CONN_OR
, 0);
4372 if (!res
&& have_min_dir_info
) {
4373 int quiet
= directory_too_idle_to_fetch_descriptors(options
, now
);
4374 log(quiet
? LOG_INFO
: LOG_NOTICE
, LD_DIR
,
4375 "Our directory information is no longer up-to-date "
4376 "enough to build circuits: %s", dir_info_status
);
4377 control_event_client_status(LOG_NOTICE
, "NOT_ENOUGH_DIR_INFO");
4379 have_min_dir_info
= res
;
4380 need_to_update_have_min_dir_info
= 0;
4383 /** Reset the descriptor download failure count on all routers, so that we
4384 * can retry any long-failed routers immediately.
4387 router_reset_descriptor_download_failures(void)
4389 networkstatus_reset_download_failures();
4390 last_routerdesc_download_attempted
= 0;
4393 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
4395 download_status_reset(&ri
->cache_info
.ei_dl_status
);
4397 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
,
4399 download_status_reset(&sd
->ei_dl_status
);
4403 /** Any changes in a router descriptor's publication time larger than this are
4404 * automatically non-cosmetic. */
4405 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
4407 /** We allow uptime to vary from how much it ought to be by this much. */
4408 #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
4410 /** Return true iff the only differences between r1 and r2 are such that
4411 * would not cause a recent (post 0.1.1.6) dirserver to republish.
4414 router_differences_are_cosmetic(routerinfo_t
*r1
, routerinfo_t
*r2
)
4416 time_t r1pub
, r2pub
;
4417 long time_difference
;
4418 tor_assert(r1
&& r2
);
4420 /* r1 should be the one that was published first. */
4421 if (r1
->cache_info
.published_on
> r2
->cache_info
.published_on
) {
4422 routerinfo_t
*ri_tmp
= r2
;
4427 /* If any key fields differ, they're different. */
4428 if (strcasecmp(r1
->address
, r2
->address
) ||
4429 strcasecmp(r1
->nickname
, r2
->nickname
) ||
4430 r1
->or_port
!= r2
->or_port
||
4431 r1
->dir_port
!= r2
->dir_port
||
4432 r1
->purpose
!= r2
->purpose
||
4433 crypto_pk_cmp_keys(r1
->onion_pkey
, r2
->onion_pkey
) ||
4434 crypto_pk_cmp_keys(r1
->identity_pkey
, r2
->identity_pkey
) ||
4435 strcasecmp(r1
->platform
, r2
->platform
) ||
4436 (r1
->contact_info
&& !r2
->contact_info
) || /* contact_info is optional */
4437 (!r1
->contact_info
&& r2
->contact_info
) ||
4438 (r1
->contact_info
&& r2
->contact_info
&&
4439 strcasecmp(r1
->contact_info
, r2
->contact_info
)) ||
4440 r1
->is_hibernating
!= r2
->is_hibernating
||
4441 r1
->has_old_dnsworkers
!= r2
->has_old_dnsworkers
||
4442 cmp_addr_policies(r1
->exit_policy
, r2
->exit_policy
))
4444 if ((r1
->declared_family
== NULL
) != (r2
->declared_family
== NULL
))
4446 if (r1
->declared_family
&& r2
->declared_family
) {
4448 if (smartlist_len(r1
->declared_family
)!=smartlist_len(r2
->declared_family
))
4450 n
= smartlist_len(r1
->declared_family
);
4451 for (i
=0; i
< n
; ++i
) {
4452 if (strcasecmp(smartlist_get(r1
->declared_family
, i
),
4453 smartlist_get(r2
->declared_family
, i
)))
4458 /* Did bandwidth change a lot? */
4459 if ((r1
->bandwidthcapacity
< r2
->bandwidthcapacity
/2) ||
4460 (r2
->bandwidthcapacity
< r1
->bandwidthcapacity
/2))
4463 /* Did more than 12 hours pass? */
4464 if (r1
->cache_info
.published_on
+ ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
4465 < r2
->cache_info
.published_on
)
4468 /* Did uptime fail to increase by approximately the amount we would think,
4469 * give or take some slop? */
4470 r1pub
= r1
->cache_info
.published_on
;
4471 r2pub
= r2
->cache_info
.published_on
;
4472 time_difference
= labs(r2
->uptime
- (r1
->uptime
+ (r2pub
- r1pub
)));
4473 if (time_difference
> ROUTER_ALLOW_UPTIME_DRIFT
&&
4474 time_difference
> r1
->uptime
* .05 &&
4475 time_difference
> r2
->uptime
* .05)
4478 /* Otherwise, the difference is cosmetic. */
4482 /** Check whether <b>ri</b> (a.k.a. sd) is a router compatible with the
4483 * extrainfo document
4484 * <b>ei</b>. If no router is compatible with <b>ei</b>, <b>ei</b> should be
4485 * dropped. Return 0 for "compatible", return 1 for "reject, and inform
4486 * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
4487 * <b>msg</b> is present, set *<b>msg</b> to a description of the
4488 * incompatibility (if any).
4491 routerinfo_incompatible_with_extrainfo(routerinfo_t
*ri
, extrainfo_t
*ei
,
4492 signed_descriptor_t
*sd
,
4495 int digest_matches
, r
=1;
4499 sd
= &ri
->cache_info
;
4502 if (msg
) *msg
= "Extrainfo signature was bad, or signed with wrong key.";
4506 digest_matches
= !memcmp(ei
->cache_info
.signed_descriptor_digest
,
4507 sd
->extra_info_digest
, DIGEST_LEN
);
4509 /* The identity must match exactly to have been generated at the same time
4510 * by the same router. */
4511 if (memcmp(ri
->cache_info
.identity_digest
, ei
->cache_info
.identity_digest
,
4513 if (msg
) *msg
= "Extrainfo nickname or identity did not match routerinfo";
4514 goto err
; /* different servers */
4517 if (ei
->pending_sig
) {
4518 char signed_digest
[128];
4519 if (crypto_pk_public_checksig(ri
->identity_pkey
, signed_digest
,
4520 ei
->pending_sig
, ei
->pending_sig_len
) != DIGEST_LEN
||
4521 memcmp(signed_digest
, ei
->cache_info
.signed_descriptor_digest
,
4524 tor_free(ei
->pending_sig
);
4525 if (msg
) *msg
= "Extrainfo signature bad, or signed with wrong key";
4526 goto err
; /* Bad signature, or no match. */
4529 ei
->cache_info
.send_unencrypted
= ri
->cache_info
.send_unencrypted
;
4530 tor_free(ei
->pending_sig
);
4533 if (ei
->cache_info
.published_on
< sd
->published_on
) {
4534 if (msg
) *msg
= "Extrainfo published time did not match routerdesc";
4536 } else if (ei
->cache_info
.published_on
> sd
->published_on
) {
4537 if (msg
) *msg
= "Extrainfo published time did not match routerdesc";
4542 if (!digest_matches
) {
4543 if (msg
) *msg
= "Extrainfo digest did not match value from routerdesc";
4544 goto err
; /* Digest doesn't match declared value. */
4549 if (digest_matches
) {
4550 /* This signature was okay, and the digest was right: This is indeed the
4551 * corresponding extrainfo. But insanely, it doesn't match the routerinfo
4552 * that lists it. Don't try to fetch this one again. */
4553 sd
->extrainfo_is_bogus
= 1;
4559 /** Assert that the internal representation of <b>rl</b> is
4560 * self-consistent. */
4562 routerlist_assert_ok(routerlist_t
*rl
)
4565 signed_descriptor_t
*sd2
;
4568 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
4570 r2
= rimap_get(rl
->identity_map
, r
->cache_info
.identity_digest
);
4571 tor_assert(r
== r2
);
4572 sd2
= sdmap_get(rl
->desc_digest_map
,
4573 r
->cache_info
.signed_descriptor_digest
);
4574 tor_assert(&(r
->cache_info
) == sd2
);
4575 tor_assert(r
->cache_info
.routerlist_index
== r_sl_idx
);
4578 * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
4579 * commenting this out is just a band-aid.
4581 * The problem is that, although well-behaved router descriptors
4582 * should never have the same value for their extra_info_digest, it's
4583 * possible for ill-behaved routers to claim whatever they like there.
4585 * The real answer is to trash desc_by_eid_map and instead have
4586 * something that indicates for a given extra-info digest we want,
4587 * what its download status is. We'll do that as a part of routerlist
4588 * refactoring once consensus directories are in. For now,
4589 * this rep violation is probably harmless: an adversary can make us
4590 * reset our retry count for an extrainfo, but that's not the end
4591 * of the world. Changing the representation in 0.2.0.x would just
4592 * destabilize the codebase.
4593 if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
4594 signed_descriptor_t *sd3 =
4595 sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
4596 tor_assert(sd3 == &(r->cache_info));
4600 SMARTLIST_FOREACH(rl
->old_routers
, signed_descriptor_t
*, sd
,
4602 r2
= rimap_get(rl
->identity_map
, sd
->identity_digest
);
4603 tor_assert(sd
!= &(r2
->cache_info
));
4604 sd2
= sdmap_get(rl
->desc_digest_map
, sd
->signed_descriptor_digest
);
4605 tor_assert(sd
== sd2
);
4606 tor_assert(sd
->routerlist_index
== sd_sl_idx
);
4607 /* XXXX021 see above.
4608 if (!tor_digest_is_zero(sd->extra_info_digest)) {
4609 signed_descriptor_t *sd3 =
4610 sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
4611 tor_assert(sd3 == sd);
4616 RIMAP_FOREACH(rl
->identity_map
, d
, r
) {
4617 tor_assert(!memcmp(r
->cache_info
.identity_digest
, d
, DIGEST_LEN
));
4618 } DIGESTMAP_FOREACH_END
;
4619 SDMAP_FOREACH(rl
->desc_digest_map
, d
, sd
) {
4620 tor_assert(!memcmp(sd
->signed_descriptor_digest
, d
, DIGEST_LEN
));
4621 } DIGESTMAP_FOREACH_END
;
4622 SDMAP_FOREACH(rl
->desc_by_eid_map
, d
, sd
) {
4623 tor_assert(!tor_digest_is_zero(d
));
4625 tor_assert(!memcmp(sd
->extra_info_digest
, d
, DIGEST_LEN
));
4626 } DIGESTMAP_FOREACH_END
;
4627 EIMAP_FOREACH(rl
->extra_info_map
, d
, ei
) {
4628 signed_descriptor_t
*sd
;
4629 tor_assert(!memcmp(ei
->cache_info
.signed_descriptor_digest
,
4631 sd
= sdmap_get(rl
->desc_by_eid_map
,
4632 ei
->cache_info
.signed_descriptor_digest
);
4633 // tor_assert(sd); // XXXX021 see above
4635 tor_assert(!memcmp(ei
->cache_info
.signed_descriptor_digest
,
4636 sd
->extra_info_digest
, DIGEST_LEN
));
4638 } DIGESTMAP_FOREACH_END
;
4641 /** Allocate and return a new string representing the contact info
4642 * and platform string for <b>router</b>,
4643 * surrounded by quotes and using standard C escapes.
4645 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
4646 * thread. Also, each call invalidates the last-returned value, so don't
4647 * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
4649 * If <b>router</b> is NULL, it just frees its internal memory and returns.
4652 esc_router_info(routerinfo_t
*router
)
4654 static char *info
=NULL
;
4655 char *esc_contact
, *esc_platform
;
4660 return NULL
; /* we're exiting; just free the memory we use */
4662 esc_contact
= esc_for_log(router
->contact_info
);
4663 esc_platform
= esc_for_log(router
->platform
);
4665 len
= strlen(esc_contact
)+strlen(esc_platform
)+32;
4666 info
= tor_malloc(len
);
4667 tor_snprintf(info
, len
, "Contact %s, Platform %s", esc_contact
,
4669 tor_free(esc_contact
);
4670 tor_free(esc_platform
);
4675 /** Helper for sorting: compare two routerinfos by their identity
4678 _compare_routerinfo_by_id_digest(const void **a
, const void **b
)
4680 routerinfo_t
*first
= *(routerinfo_t
**)a
, *second
= *(routerinfo_t
**)b
;
4681 return memcmp(first
->cache_info
.identity_digest
,
4682 second
->cache_info
.identity_digest
,
4686 /** Sort a list of routerinfo_t in ascending order of identity digest. */
4688 routers_sort_by_identity(smartlist_t
*routers
)
4690 smartlist_sort(routers
, _compare_routerinfo_by_id_digest
);
4693 /** A routerset specifies constraints on a set of possible routerinfos, based
4694 * on their names, identities, or addresses. It is optimized for determining
4695 * whether a router is a member or not, in O(1+P) time, where P is the number
4696 * of address policy constraints. */
4697 struct routerset_t
{
4698 /** A list of strings for the elements of the policy. Each string is either
4699 * a nickname, a hexadecimal identity fingerprint, or an address policy. A
4700 * router belongs to the set if its nickname OR its identity OR its address
4701 * matches an entry here. */
4703 /** A map from lowercase nicknames of routers in the set to (void*)1 */
4705 /** A map from identity digests routers in the set to (void*)1 */
4706 digestmap_t
*digests
;
4707 /** An address policy for routers in the set. For implementation reasons,
4708 * a router belongs to the set if it is _rejected_ by this policy. */
4709 smartlist_t
*policies
;
4712 /** Return a new empty routerset. */
4716 routerset_t
*result
= tor_malloc_zero(sizeof(routerset_t
));
4717 result
->list
= smartlist_create();
4718 result
->names
= strmap_new();
4719 result
->digests
= digestmap_new();
4720 result
->policies
= smartlist_create();
4724 /** Parse the string <b>s</b> to create a set of routerset entries, and add
4725 * them to <b>target</b>. In log messages, refer to the string as
4726 * <b>description</b>. Return 0 on success, -1 on failure.
4728 * Three kinds of elements are allowed in routersets: nicknames, IP address
4729 * patterns, and fingerprints. They may be surrounded by optional space, and
4730 * mst be separated by commas.
4733 routerset_parse(routerset_t
*target
, const char *s
, const char *description
)
4736 smartlist_t
*list
= smartlist_create();
4737 smartlist_split_string(list
, s
, ",",
4738 SPLIT_SKIP_SPACE
| SPLIT_IGNORE_BLANK
, 0);
4739 SMARTLIST_FOREACH(list
, char *, nick
, {
4741 if (is_legal_hexdigest(nick
)) {
4745 log_debug(LD_CONFIG
, "Adding identity %s to %s", nick
, description
);
4746 base16_decode(d
, sizeof(d
), nick
, HEX_DIGEST_LEN
);
4747 digestmap_set(target
->digests
, d
, (void*)1);
4748 } else if (is_legal_nickname(nick
)) {
4749 log_debug(LD_CONFIG
, "Adding nickname %s to %s", nick
, description
);
4750 strmap_set_lc(target
->names
, nick
, (void*)1);
4751 } else if ((strchr(nick
,'.') || strchr(nick
, '*')) &&
4752 (p
= router_parse_addr_policy_item_from_string(
4753 nick
, ADDR_POLICY_REJECT
))) {
4754 log_debug(LD_CONFIG
, "Adding address %s to %s", nick
, description
);
4755 smartlist_add(target
->policies
, p
);
4757 log_warn(LD_CONFIG
, "Nickname '%s' in %s is misformed.", nick
,
4761 SMARTLIST_DEL_CURRENT(list
, nick
);
4764 smartlist_add_all(target
->list
, list
);
4765 smartlist_free(list
);
4769 /** Add all members of the set <b>source</b> to <b>target</b>. */
4771 routerset_union(routerset_t
*target
, const routerset_t
*source
)
4775 if (!source
|| !source
->list
)
4777 s
= routerset_to_string(source
);
4778 routerset_parse(target
, s
, "other routerset");
4782 /** Helper. Return true iff <b>set</b> contains a router based on the other
4783 * provided fields. */
4785 routerset_contains(const routerset_t
*set
, const tor_addr_t
*addr
,
4787 const char *nickname
, const char *id_digest
, int is_named
)
4789 if (!set
|| !set
->list
) return 0;
4790 (void) is_named
; /* not supported */
4791 if (nickname
&& strmap_get_lc(set
->names
, nickname
))
4793 if (id_digest
&& digestmap_get(set
->digests
, id_digest
))
4795 if (addr
&& compare_tor_addr_to_addr_policy(addr
, orport
, set
->policies
)
4796 == ADDR_POLICY_REJECTED
)
4801 /** Return true iff we can tell that <b>ei</b> is a member of <b>set</b>. */
4803 routerset_contains_extendinfo(const routerset_t
*set
, extend_info_t
*ei
)
4805 return routerset_contains(set
,
4809 ei
->identity_digest
,
4813 /** Return true iff <b>ri</b> is in <b>set</b>. */
4815 routerset_contains_router(const routerset_t
*set
, routerinfo_t
*ri
)
4818 tor_addr_from_ipv4h(&addr
, ri
->addr
);
4819 return routerset_contains(set
,
4823 ri
->cache_info
.identity_digest
,
4827 /** Return true iff <b>rs</b> is in <b>set</b>. */
4829 routerset_contains_routerstatus(const routerset_t
*set
, routerstatus_t
*rs
)
4832 tor_addr_from_ipv4h(&addr
, rs
->addr
);
4833 return routerset_contains(set
,
4837 rs
->identity_digest
,
4841 /** Add every known routerinfo_t that is a member of <b>routerset</b> to
4842 * <b>out</b>. If <b>running_only</b>, only add the running ones. */
4844 routerset_get_all_routers(smartlist_t
*out
, const routerset_t
*routerset
,
4848 if (!routerset
|| !routerset
->list
)
4850 if (!warned_nicknames
)
4851 warned_nicknames
= smartlist_create();
4852 SMARTLIST_FOREACH(routerset
->list
, const char *, name
, {
4853 routerinfo_t
*router
= router_get_by_nickname(name
, 1);
4855 if (!running_only
|| router
->is_running
)
4856 smartlist_add(out
, router
);
4859 if (smartlist_len(routerset
->policies
)) {
4860 routerlist_t
*rl
= router_get_routerlist();
4861 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, router
,
4862 if (compare_addr_to_addr_policy(router
->addr
, router
->or_port
,
4863 routerset
->policies
) == ADDR_POLICY_REJECT
) {
4864 if (!running_only
|| router
->is_running
)
4865 smartlist_add(out
, router
);
4870 /** Remove every routerinfo_t from <b>lst</b> that is in <b>routerset</b>. */
4872 routerset_subtract_routers(smartlist_t
*lst
, const routerset_t
*routerset
)
4877 SMARTLIST_FOREACH(lst
, routerinfo_t
*, r
, {
4878 if (routerset_contains_router(routerset
, r
)) {
4879 //log_debug(LD_DIR, "Subtracting %s",r->nickname);
4880 SMARTLIST_DEL_CURRENT(lst
, r
);
4885 /** Return a new string that when parsed by routerset_parse_string() will
4886 * yield <b>set</b>. */
4888 routerset_to_string(const routerset_t
*set
)
4890 if (!set
|| !set
->list
)
4891 return tor_strdup("");
4892 return smartlist_join_strings(set
->list
, ",", 0, NULL
);
4895 /** Free all storage held in <b>routerset</b>. */
4897 routerset_free(routerset_t
*routerset
)
4899 SMARTLIST_FOREACH(routerset
->list
, char *, cp
, tor_free(cp
));
4900 smartlist_free(routerset
->list
);
4901 SMARTLIST_FOREACH(routerset
->policies
, addr_policy_t
*, p
,
4902 addr_policy_free(p
));
4903 smartlist_free(routerset
->policies
);
4905 strmap_free(routerset
->names
, NULL
);
4906 digestmap_free(routerset
->digests
, NULL
);
4908 tor_free(routerset
);
4911 /** Determine the routers that are responsible for <b>id</b> (binary) and
4912 * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
4913 * Return -1 if we're returning an empty smartlist, else return 0.
4916 hid_serv_get_responsible_directories(smartlist_t
*responsible_dirs
,
4919 int start
, found
, n_added
= 0, i
;
4920 networkstatus_t
*c
= networkstatus_get_latest_consensus();
4921 int use_begindir
= get_options()->TunnelDirConns
;
4922 if (!c
|| !smartlist_len(c
->routerstatus_list
)) {
4923 log_warn(LD_REND
, "We don't have a consensus, so we can't perform v2 "
4924 "rendezvous operations.");
4928 start
= networkstatus_vote_find_entry_idx(c
, id
, &found
);
4929 if (start
== smartlist_len(c
->routerstatus_list
)) start
= 0;
4932 routerstatus_t
*r
= smartlist_get(c
->routerstatus_list
, i
);
4934 if (r
->dir_port
|| use_begindir
)
4935 smartlist_add(responsible_dirs
, r
);
4937 log_info(LD_REND
, "Not adding router '%s' to list of responsible "
4938 "hidden service directories, because we have no way of "
4939 "reaching it.", r
->nickname
);
4940 if (++n_added
== REND_NUMBER_OF_CONSECUTIVE_REPLICAS
)
4943 if (++i
== smartlist_len(c
->routerstatus_list
))
4945 } while (i
!= start
);
4947 /* Even though we don't have the desired number of hidden service
4948 * directories, be happy if we got any. */
4949 return smartlist_len(responsible_dirs
) ? 0 : -1;
4952 /** Return true if this node is currently acting as hidden service
4953 * directory, false otherwise. */
4955 hid_serv_acting_as_directory(void)
4957 routerinfo_t
*me
= router_get_my_routerinfo();
4962 if (!get_options()->HidServDirectoryV2
) {
4963 log_info(LD_REND
, "We are not acting as hidden service directory, "
4964 "because we have not been configured as such.");
4967 if (!(c
= networkstatus_get_latest_consensus())) {
4968 log_info(LD_REND
, "There's no consensus, so I can't tell if I'm a hidden "
4969 "service directory");
4972 rs
= networkstatus_vote_find_entry(c
, me
->cache_info
.identity_digest
);
4974 log_info(LD_REND
, "We're not listed in the consensus, so we're not "
4975 "being a hidden service directory.");
4978 if (!rs
->is_hs_dir
) {
4979 log_info(LD_REND
, "We're not listed as a hidden service directory in "
4980 "the consensus, so we won't be one.");
4986 /** Return true if this node is responsible for storing the descriptor ID
4987 * in <b>query</b> and false otherwise. */
4989 hid_serv_responsible_for_desc_id(const char *query
)
4992 routerstatus_t
*last_rs
;
4993 const char *my_id
, *last_id
;
4995 smartlist_t
*responsible
;
4996 if (!hid_serv_acting_as_directory())
4998 if (!(me
= router_get_my_routerinfo()))
4999 return 0; /* This is redundant, but let's be paranoid. */
5000 my_id
= me
->cache_info
.identity_digest
;
5001 responsible
= smartlist_create();
5002 if (hid_serv_get_responsible_directories(responsible
, query
) < 0) {
5003 smartlist_free(responsible
);
5006 last_rs
= smartlist_get(responsible
, smartlist_len(responsible
)-1);
5007 last_id
= last_rs
->identity_digest
;
5008 result
= rend_id_is_in_interval(my_id
, query
, last_id
);
5009 smartlist_free(responsible
);