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
, int *n_busy_out
);
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 XXXX */
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
->dl_status
.schedule
= DL_SCHED_CONSENSUS
;
115 cl
->certs
= smartlist_create();
116 digestmap_set(trusted_dir_certs
, id_digest
, cl
);
121 /** Reload the cached v3 key certificates from the cached-certs file in
122 * the data directory. Return 0 on success, -1 on failure. */
124 trusted_dirs_reload_certs(void)
130 filename
= get_datadir_fname("cached-certs");
131 contents
= read_file_to_str(filename
, RFTS_IGNORE_MISSING
, NULL
);
135 r
= trusted_dirs_load_certs_from_string(contents
, 1, 1);
140 /** Helper: return true iff we already have loaded the exact cert
143 already_have_cert(authority_cert_t
*cert
)
145 cert_list_t
*cl
= get_cert_list(cert
->cache_info
.identity_digest
);
147 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, c
,
149 if (!memcmp(c
->cache_info
.signed_descriptor_digest
,
150 cert
->cache_info
.signed_descriptor_digest
,
157 /** Load a bunch of new key certificates from the string <b>contents</b>. If
158 * <b>from_store</b> is true, the certificates are from the cache, and we
159 * don't need to flush them to disk. If <b>from_store</b> is false, we need
160 * to flush any changed certificates to disk. Return 0 on success, -1 on
163 trusted_dirs_load_certs_from_string(const char *contents
, int from_store
,
166 trusted_dir_server_t
*ds
;
169 for (s
= contents
; *s
; s
= eos
) {
170 authority_cert_t
*cert
= authority_cert_parse_from_string(s
, &eos
);
174 ds
= trusteddirserver_get_by_v3_auth_digest(
175 cert
->cache_info
.identity_digest
);
176 log_debug(LD_DIR
, "Parsed certificate for %s",
177 ds
? ds
->nickname
: "unknown authority");
179 if (already_have_cert(cert
)) {
180 /* we already have this one. continue. */
181 log_info(LD_DIR
, "Skipping %s certificate for %s that we "
183 from_store
? "cached" : "downloaded",
184 ds
? ds
->nickname
: "??");
186 /* a duplicate on a download should be treated as a failure, since it
187 * probably means we wanted a different secret key or we are trying to
188 * replace an expired cert that has not in fact been updated. */
190 log_warn(LD_DIR
, "Got a certificate for %s that we already have. "
191 "Maybe they haven't updated it. Waiting for a while.",
192 ds
? ds
->nickname
: "??");
193 authority_cert_dl_failed(cert
->cache_info
.identity_digest
, 404);
196 authority_cert_free(cert
);
201 log_info(LD_DIR
, "Adding %s certificate for directory authority %s with "
202 "signing key %s", from_store
? "cached" : "downloaded",
203 ds
->nickname
, hex_str(cert
->signing_key_digest
,DIGEST_LEN
));
205 log_info(LD_DIR
, "Adding %s certificate for unrecognized directory "
206 "authority with signing key %s",
207 from_store
? "cached" : "downloaded",
208 hex_str(cert
->signing_key_digest
,DIGEST_LEN
));
211 cl
= get_cert_list(cert
->cache_info
.identity_digest
);
212 smartlist_add(cl
->certs
, cert
);
213 if (ds
&& cert
->cache_info
.published_on
> ds
->addr_current_at
) {
214 /* Check to see whether we should update our view of the authority's
216 if (cert
->addr
&& cert
->dir_port
&&
217 (ds
->addr
!= cert
->addr
||
218 ds
->dir_port
!= cert
->dir_port
)) {
219 char *a
= tor_dup_ip(cert
->addr
);
220 log_notice(LD_DIR
, "Updating address for directory authority %s "
221 "from %s:%d to %s:%d based on in certificate.",
222 ds
->nickname
, ds
->address
, (int)ds
->dir_port
,
225 ds
->addr
= cert
->addr
;
226 ds
->dir_port
= cert
->dir_port
;
228 ds
->addr_current_at
= cert
->cache_info
.published_on
;
232 trusted_dir_servers_certs_changed
= 1;
236 trusted_dirs_flush_certs_to_disk();
238 networkstatus_note_certs_arrived();
242 /** Save all v3 key certificates to the cached-certs file. */
244 trusted_dirs_flush_certs_to_disk(void)
249 if (!trusted_dir_servers_certs_changed
|| !trusted_dir_certs
)
252 chunks
= smartlist_create();
253 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
254 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
256 sized_chunk_t
*c
= tor_malloc(sizeof(sized_chunk_t
));
257 c
->bytes
= cert
->cache_info
.signed_descriptor_body
;
258 c
->len
= cert
->cache_info
.signed_descriptor_len
;
259 smartlist_add(chunks
, c
);
261 } DIGESTMAP_FOREACH_END
;
263 filename
= get_datadir_fname("cached-certs");
264 if (write_chunks_to_file(filename
, chunks
, 0)) {
265 log_warn(LD_FS
, "Error writing certificates to disk.");
268 SMARTLIST_FOREACH(chunks
, sized_chunk_t
*, c
, tor_free(c
));
269 smartlist_free(chunks
);
271 trusted_dir_servers_certs_changed
= 0;
274 /** Remove all v3 authority certificates that have been superseded for more
275 * than 48 hours. (If the most recent cert was published more than 48 hours
276 * ago, then we aren't going to get any consensuses signed with older
279 trusted_dirs_remove_old_certs(void)
281 time_t now
= time(NULL
);
282 #define DEAD_CERT_LIFETIME (2*24*60*60)
283 #define OLD_CERT_LIFETIME (7*24*60*60)
284 if (!trusted_dir_certs
)
287 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
288 authority_cert_t
*newest
= NULL
;
289 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
290 if (!newest
|| (cert
->cache_info
.published_on
>
291 newest
->cache_info
.published_on
))
294 const time_t newest_published
= newest
->cache_info
.published_on
;
295 SMARTLIST_FOREACH_BEGIN(cl
->certs
, authority_cert_t
*, cert
) {
297 time_t cert_published
;
300 expired
= ftime_definitely_after(now
, cert
->expires
);
301 cert_published
= cert
->cache_info
.published_on
;
302 /* Store expired certs for 48 hours after a newer arrives;
305 (newest_published
+ DEAD_CERT_LIFETIME
< now
) :
306 (cert_published
+ OLD_CERT_LIFETIME
< newest_published
)) {
307 SMARTLIST_DEL_CURRENT(cl
->certs
, cert
);
308 authority_cert_free(cert
);
309 trusted_dir_servers_certs_changed
= 1;
311 } SMARTLIST_FOREACH_END(cert
);
313 } DIGESTMAP_FOREACH_END
;
314 #undef OLD_CERT_LIFETIME
316 trusted_dirs_flush_certs_to_disk();
319 /** Return the newest v3 authority certificate whose v3 authority identity key
320 * has digest <b>id_digest</b>. Return NULL if no such authority is known,
321 * or it has no certificate. */
323 authority_cert_get_newest_by_id(const char *id_digest
)
326 authority_cert_t
*best
= NULL
;
327 if (!trusted_dir_certs
||
328 !(cl
= digestmap_get(trusted_dir_certs
, id_digest
)))
331 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
333 if (!best
|| cert
->cache_info
.published_on
> best
->cache_info
.published_on
)
339 /** Return the newest v3 authority certificate whose directory signing key has
340 * digest <b>sk_digest</b>. Return NULL if no such certificate is known.
343 authority_cert_get_by_sk_digest(const char *sk_digest
)
346 if (!trusted_dir_certs
)
349 if ((c
= get_my_v3_authority_cert()) &&
350 !memcmp(c
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
352 if ((c
= get_my_v3_legacy_cert()) &&
353 !memcmp(c
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
356 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
357 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
359 if (!memcmp(cert
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
362 } DIGESTMAP_FOREACH_END
;
366 /** Return the v3 authority certificate with signing key matching
367 * <b>sk_digest</b>, for the authority with identity digest <b>id_digest</b>.
368 * Return NULL if no such authority is known. */
370 authority_cert_get_by_digests(const char *id_digest
,
371 const char *sk_digest
)
374 if (!trusted_dir_certs
||
375 !(cl
= digestmap_get(trusted_dir_certs
, id_digest
)))
377 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
378 if (!memcmp(cert
->signing_key_digest
, sk_digest
, DIGEST_LEN
))
384 /** Add every known authority_cert_t to <b>certs_out</b>. */
386 authority_cert_get_all(smartlist_t
*certs_out
)
388 tor_assert(certs_out
);
389 if (!trusted_dir_certs
)
392 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
393 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, c
,
394 smartlist_add(certs_out
, c
));
395 } DIGESTMAP_FOREACH_END
;
398 /** Called when an attempt to download a certificate with the authority with
399 * ID <b>id_digest</b> fails with HTTP response code <b>status</b>: remember
400 * the failure, so we don't try again immediately. */
402 authority_cert_dl_failed(const char *id_digest
, int status
)
405 if (!trusted_dir_certs
||
406 !(cl
= digestmap_get(trusted_dir_certs
, id_digest
)))
409 download_status_failed(&cl
->dl_status
, status
);
412 /** How many times will we try to fetch a certificate before giving up? */
413 #define MAX_CERT_DL_FAILURES 8
415 /** Try to download any v3 authority certificates that we may be missing. If
416 * <b>status</b> is provided, try to get all the ones that were used to sign
417 * <b>status</b>. Additionally, try to have a non-expired certificate for
418 * every V3 authority in trusted_dir_servers. Don't fetch certificates we
422 authority_certs_fetch_missing(networkstatus_t
*status
, time_t now
)
424 digestmap_t
*pending
;
425 authority_cert_t
*cert
;
426 smartlist_t
*missing_digests
;
427 char *resource
= NULL
;
429 const int cache
= directory_caches_dir_info(get_options());
431 if (should_delay_dir_fetches(get_options()))
434 pending
= digestmap_new();
435 missing_digests
= smartlist_create();
437 list_pending_downloads(pending
, DIR_PURPOSE_FETCH_CERTIFICATE
, "fp/");
439 SMARTLIST_FOREACH(status
->voters
, networkstatus_voter_info_t
*, voter
,
441 if (tor_digest_is_zero(voter
->signing_key_digest
))
442 continue; /* This authority never signed this consensus, so don't
443 * go looking for a cert with key digest 0000000000. */
445 !trusteddirserver_get_by_v3_auth_digest(voter
->identity_digest
))
446 continue; /* We are not a cache, and we don't know this authority.*/
447 cl
= get_cert_list(voter
->identity_digest
);
448 cert
= authority_cert_get_by_digests(voter
->identity_digest
,
449 voter
->signing_key_digest
);
451 if (now
< cert
->expires
)
452 download_status_reset(&cl
->dl_status
);
455 if (download_status_is_ready(&cl
->dl_status
, now
,
456 MAX_CERT_DL_FAILURES
) &&
457 !digestmap_get(pending
, voter
->identity_digest
)) {
458 log_notice(LD_DIR
, "We're missing a certificate from authority "
459 "with signing key %s: launching request.",
460 hex_str(voter
->signing_key_digest
, DIGEST_LEN
));
461 smartlist_add(missing_digests
, voter
->identity_digest
);
465 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
468 if (!(ds
->type
& V3_AUTHORITY
))
470 if (smartlist_digest_isin(missing_digests
, ds
->v3_identity_digest
))
472 cl
= get_cert_list(ds
->v3_identity_digest
);
473 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
475 if (!ftime_definitely_after(now
, cert
->expires
)) {
476 /* It's not expired, and we weren't looking for something to
477 * verify a consensus with. Call it done. */
478 download_status_reset(&cl
->dl_status
);
484 download_status_is_ready(&cl
->dl_status
, now
,MAX_CERT_DL_FAILURES
) &&
485 !digestmap_get(pending
, ds
->v3_identity_digest
)) {
486 log_notice(LD_DIR
, "No current certificate known for authority %s; "
487 "launching request.", ds
->nickname
);
488 smartlist_add(missing_digests
, ds
->v3_identity_digest
);
492 if (!smartlist_len(missing_digests
)) {
495 smartlist_t
*fps
= smartlist_create();
496 smartlist_add(fps
, tor_strdup("fp/"));
497 SMARTLIST_FOREACH(missing_digests
, const char *, d
, {
499 if (digestmap_get(pending
, d
))
501 fp
= tor_malloc(HEX_DIGEST_LEN
+2);
502 base16_encode(fp
, HEX_DIGEST_LEN
+1, d
, DIGEST_LEN
);
503 fp
[HEX_DIGEST_LEN
] = '+';
504 fp
[HEX_DIGEST_LEN
+1] = '\0';
505 smartlist_add(fps
, fp
);
507 if (smartlist_len(fps
) == 1) {
508 /* we didn't add any: they were all pending */
509 SMARTLIST_FOREACH(fps
, char *, cp
, tor_free(cp
));
513 resource
= smartlist_join_strings(fps
, "", 0, NULL
);
514 resource
[strlen(resource
)-1] = '\0';
515 SMARTLIST_FOREACH(fps
, char *, cp
, tor_free(cp
));
518 directory_get_from_dirserver(DIR_PURPOSE_FETCH_CERTIFICATE
, 0,
519 resource
, PDS_RETRY_IF_NO_SERVERS
);
523 smartlist_free(missing_digests
);
524 digestmap_free(pending
, NULL
);
527 /* Router descriptor storage.
529 * Routerdescs are stored in a big file, named "cached-descriptors". As new
530 * routerdescs arrive, we append them to a journal file named
531 * "cached-descriptors.new".
533 * From time to time, we replace "cached-descriptors" with a new file
534 * containing only the live, non-superseded descriptors, and clear
535 * cached-routers.new.
537 * On startup, we read both files.
540 /** Helper: return 1 iff the router log is so big we want to rebuild the
543 router_should_rebuild_store(desc_store_t
*store
)
545 if (store
->store_len
> (1<<16))
546 return (store
->journal_len
> store
->store_len
/ 2 ||
547 store
->bytes_dropped
> store
->store_len
/ 2);
549 return store
->journal_len
> (1<<15);
552 static INLINE desc_store_t
*
553 desc_get_store(routerlist_t
*rl
, signed_descriptor_t
*sd
)
555 if (sd
->is_extrainfo
)
556 return &rl
->extrainfo_store
;
558 return &rl
->desc_store
;
561 /** Add the signed_descriptor_t in <b>desc</b> to the router
562 * journal; change its saved_location to SAVED_IN_JOURNAL and set its
563 * offset appropriately. */
565 signed_desc_append_to_journal(signed_descriptor_t
*desc
,
568 char *fname
= get_datadir_fname_suffix(store
->fname_base
, ".new");
569 const char *body
= signed_descriptor_get_body_impl(desc
,1);
570 size_t len
= desc
->signed_descriptor_len
+ desc
->annotations_len
;
572 tor_assert(len
== strlen(body
));
574 if (append_bytes_to_file(fname
, body
, len
, 1)) {
575 log_warn(LD_FS
, "Unable to store router descriptor");
579 desc
->saved_location
= SAVED_IN_JOURNAL
;
582 desc
->saved_offset
= store
->journal_len
;
583 store
->journal_len
+= len
;
588 /** Sorting helper: return <0, 0, or >0 depending on whether the
589 * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
590 * the signed_descriptor_t* in *<b>b</b>. */
592 _compare_signed_descriptors_by_age(const void **_a
, const void **_b
)
594 const signed_descriptor_t
*r1
= *_a
, *r2
= *_b
;
595 return (int)(r1
->published_on
- r2
->published_on
);
599 #define RRS_DONT_REMOVE_OLD 2
601 /** If the journal of <b>store</b> is too long, or if RRS_FORCE is set in
602 * <b>flags</b>, then atomically replace the saved router store with the
603 * routers currently in our routerlist, and clear the journal. Unless
604 * RRS_DONT_REMOVE_OLD is set in <b>flags</b>, delete expired routers before
605 * rebuilding the store. Return 0 on success, -1 on failure.
608 router_rebuild_store(int flags
, desc_store_t
*store
)
610 smartlist_t
*chunk_list
= NULL
;
611 char *fname
= NULL
, *fname_tmp
= NULL
;
614 smartlist_t
*signed_descriptors
= NULL
;
616 size_t total_expected_len
= 0;
618 int force
= flags
& RRS_FORCE
;
620 if (!force
&& !router_should_rebuild_store(store
))
625 if (store
->type
== EXTRAINFO_STORE
)
626 had_any
= !eimap_isempty(routerlist
->extra_info_map
);
628 had_any
= (smartlist_len(routerlist
->routers
)+
629 smartlist_len(routerlist
->old_routers
))>0;
631 /* Don't save deadweight. */
632 if (!(flags
& RRS_DONT_REMOVE_OLD
))
633 routerlist_remove_old_routers();
635 log_info(LD_DIR
, "Rebuilding %s cache", store
->description
);
637 fname
= get_datadir_fname(store
->fname_base
);
638 fname_tmp
= get_datadir_fname_suffix(store
->fname_base
, ".tmp");
640 chunk_list
= smartlist_create();
642 /* We sort the routers by age to enhance locality on disk. */
643 signed_descriptors
= smartlist_create();
644 if (store
->type
== EXTRAINFO_STORE
) {
646 for (iter
= eimap_iter_init(routerlist
->extra_info_map
);
647 !eimap_iter_done(iter
);
648 iter
= eimap_iter_next(routerlist
->extra_info_map
, iter
)) {
651 eimap_iter_get(iter
, &key
, &ei
);
652 smartlist_add(signed_descriptors
, &ei
->cache_info
);
655 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
,
656 smartlist_add(signed_descriptors
, sd
));
657 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
658 smartlist_add(signed_descriptors
, &ri
->cache_info
));
661 smartlist_sort(signed_descriptors
, _compare_signed_descriptors_by_age
);
663 /* Now, add the appropriate members to chunk_list */
664 SMARTLIST_FOREACH(signed_descriptors
, signed_descriptor_t
*, sd
,
667 const char *body
= signed_descriptor_get_body_impl(sd
, 1);
669 log_warn(LD_BUG
, "No descriptor available for router.");
672 if (sd
->do_not_cache
) {
676 c
= tor_malloc(sizeof(sized_chunk_t
));
678 c
->len
= sd
->signed_descriptor_len
+ sd
->annotations_len
;
679 total_expected_len
+= c
->len
;
680 smartlist_add(chunk_list
, c
);
683 if (write_chunks_to_file(fname_tmp
, chunk_list
, 1)<0) {
684 log_warn(LD_FS
, "Error writing router store to disk.");
688 /* Our mmap is now invalid. */
690 tor_munmap_file(store
->mmap
);
694 if (replace_file(fname_tmp
, fname
)<0) {
695 log_warn(LD_FS
, "Error replacing old router store: %s", strerror(errno
));
700 store
->mmap
= tor_mmap_file(fname
);
702 if (errno
== ERANGE
) {
704 if (total_expected_len
) {
705 log_warn(LD_FS
, "We wrote some bytes to a new descriptor file at '%s',"
706 " but when we went to mmap it, it was empty!", fname
);
707 } else if (had_any
) {
708 log_info(LD_FS
, "We just removed every descriptor in '%s'. This is "
709 "okay if we're just starting up after a long time. "
710 "Otherwise, it's a bug.", fname
);
713 log_warn(LD_FS
, "Unable to mmap new descriptor file at '%s'.",fname
);
717 log_info(LD_DIR
, "Reconstructing pointers into cache");
720 SMARTLIST_FOREACH(signed_descriptors
, signed_descriptor_t
*, sd
,
722 if (sd
->do_not_cache
)
724 sd
->saved_location
= SAVED_IN_CACHE
;
726 tor_free(sd
->signed_descriptor_body
); // sets it to null
727 sd
->saved_offset
= offset
;
729 offset
+= sd
->signed_descriptor_len
+ sd
->annotations_len
;
730 signed_descriptor_get_body(sd
); /* reconstruct and assert */
734 fname
= get_datadir_fname_suffix(store
->fname_base
, ".new");
735 write_str_to_file(fname
, "", 1);
738 store
->store_len
= (size_t) offset
;
739 store
->journal_len
= 0;
740 store
->bytes_dropped
= 0;
742 if (signed_descriptors
)
743 smartlist_free(signed_descriptors
);
746 SMARTLIST_FOREACH(chunk_list
, sized_chunk_t
*, c
, tor_free(c
));
747 smartlist_free(chunk_list
);
752 /** Helper: Reload a cache file and its associated journal, setting metadata
753 * appropriately. If <b>extrainfo</b> is true, reload the extrainfo store;
754 * else reload the router descriptor store. */
756 router_reload_router_list_impl(desc_store_t
*store
)
758 char *fname
= NULL
, *altname
= NULL
, *contents
= NULL
;
760 int read_from_old_location
= 0;
761 int extrainfo
= (store
->type
== EXTRAINFO_STORE
);
762 time_t now
= time(NULL
);
763 store
->journal_len
= store
->store_len
= 0;
765 fname
= get_datadir_fname(store
->fname_base
);
766 if (store
->fname_alt_base
)
767 altname
= get_datadir_fname(store
->fname_alt_base
);
769 if (store
->mmap
) /* get rid of it first */
770 tor_munmap_file(store
->mmap
);
773 store
->mmap
= tor_mmap_file(fname
);
774 if (!store
->mmap
&& altname
&& file_status(altname
) == FN_FILE
) {
775 read_from_old_location
= 1;
776 log_notice(LD_DIR
, "Couldn't read %s; trying to load routers from old "
777 "location %s.", fname
, altname
);
778 if ((store
->mmap
= tor_mmap_file(altname
)))
779 read_from_old_location
= 1;
781 if (altname
&& !read_from_old_location
) {
782 remove_file_if_very_old(altname
, now
);
785 store
->store_len
= store
->mmap
->size
;
787 router_load_extrainfo_from_string(store
->mmap
->data
,
788 store
->mmap
->data
+store
->mmap
->size
,
789 SAVED_IN_CACHE
, NULL
, 0);
791 router_load_routers_from_string(store
->mmap
->data
,
792 store
->mmap
->data
+store
->mmap
->size
,
793 SAVED_IN_CACHE
, NULL
, 0, NULL
);
797 fname
= get_datadir_fname_suffix(store
->fname_base
, ".new");
798 if (file_status(fname
) == FN_FILE
)
799 contents
= read_file_to_str(fname
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
800 if (read_from_old_location
) {
802 altname
= get_datadir_fname_suffix(store
->fname_alt_base
, ".new");
804 contents
= read_file_to_str(altname
, RFTS_BIN
|RFTS_IGNORE_MISSING
, &st
);
806 remove_file_if_very_old(altname
, now
);
810 router_load_extrainfo_from_string(contents
, NULL
,SAVED_IN_JOURNAL
,
813 router_load_routers_from_string(contents
, NULL
, SAVED_IN_JOURNAL
,
815 store
->journal_len
= (size_t) st
.st_size
;
822 if (store
->journal_len
|| read_from_old_location
) {
823 /* Always clear the journal on startup.*/
824 router_rebuild_store(RRS_FORCE
, store
);
825 } else if (!extrainfo
) {
826 /* Don't cache expired routers. (This is in an else because
827 * router_rebuild_store() also calls remove_old_routers().) */
828 routerlist_remove_old_routers();
834 /** Load all cached router descriptors and extra-info documents from the
835 * store. Return 0 on success and -1 on failure.
838 router_reload_router_list(void)
840 routerlist_t
*rl
= router_get_routerlist();
841 if (router_reload_router_list_impl(&rl
->desc_store
))
843 if (router_reload_router_list_impl(&rl
->extrainfo_store
))
848 /** Return a smartlist containing a list of trusted_dir_server_t * for all
849 * known trusted dirservers. Callers must not modify the list or its
853 router_get_trusted_dir_servers(void)
855 if (!trusted_dir_servers
)
856 trusted_dir_servers
= smartlist_create();
858 return trusted_dir_servers
;
861 /** Try to find a running dirserver that supports operations of <b>type</b>.
863 * If there are no running dirservers in our routerlist and the
864 * <b>PDS_RETRY_IF_NO_SERVERS</b> flag is set, set all the authoritative ones
865 * as running again, and pick one.
867 * If the <b>PDS_IGNORE_FASCISTFIREWALL</b> flag is set, then include
868 * dirservers that we can't reach.
870 * If the <b>PDS_ALLOW_SELF</b> flag is not set, then don't include ourself
871 * (if we're a dirserver).
873 * Don't pick an authority if any non-authority is viable; try to avoid using
874 * servers that have returned 503 recently.
877 router_pick_directory_server(authority_type_t type
, int flags
)
879 routerstatus_t
*choice
;
880 if (get_options()->PreferTunneledDirConns
)
881 flags
|= _PDS_PREFER_TUNNELED_DIR_CONNS
;
886 choice
= router_pick_directory_server_impl(type
, flags
);
887 if (choice
|| !(flags
& PDS_RETRY_IF_NO_SERVERS
))
891 "No reachable router entries for dirservers. "
892 "Trying them all again.");
893 /* mark all authdirservers as up again */
894 mark_all_trusteddirservers_up();
896 choice
= router_pick_directory_server_impl(type
, flags
);
902 router_get_my_share_of_directory_requests(double *v2_share_out
,
903 double *v3_share_out
)
905 routerinfo_t
*me
= router_get_my_routerinfo();
907 const int pds_flags
= PDS_ALLOW_SELF
|PDS_IGNORE_FASCISTFIREWALL
;
908 *v2_share_out
= *v3_share_out
= 0.0;
911 rs
= router_get_consensus_status_by_id(me
->cache_info
.identity_digest
);
915 /* Calling for side effect */
917 sl_last_total_weighted_bw
= 0;
918 router_pick_directory_server(V2_AUTHORITY
, pds_flags
);
919 if (sl_last_total_weighted_bw
!= 0) {
920 *v2_share_out
= U64_TO_DBL(sl_last_weighted_bw_of_me
) /
921 U64_TO_DBL(sl_last_total_weighted_bw
);
925 if (rs
->version_supports_v3_dir
) {
926 sl_last_total_weighted_bw
= 0;
927 router_pick_directory_server(V3_AUTHORITY
, pds_flags
);
928 if (sl_last_total_weighted_bw
!= 0) {
929 *v3_share_out
= U64_TO_DBL(sl_last_weighted_bw_of_me
) /
930 U64_TO_DBL(sl_last_total_weighted_bw
);
937 /** Return the trusted_dir_server_t for the directory authority whose identity
938 * key hashes to <b>digest</b>, or NULL if no such authority is known.
940 trusted_dir_server_t
*
941 router_get_trusteddirserver_by_digest(const char *digest
)
943 if (!trusted_dir_servers
)
946 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
948 if (!memcmp(ds
->digest
, digest
, DIGEST_LEN
))
955 /** Return the trusted_dir_server_t for the directory authority whose identity
956 * key hashes to <b>digest</b>, or NULL if no such authority is known.
958 trusted_dir_server_t
*
959 trusteddirserver_get_by_v3_auth_digest(const char *digest
)
961 if (!trusted_dir_servers
)
964 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
966 if (!memcmp(ds
->v3_identity_digest
, digest
, DIGEST_LEN
) &&
967 (ds
->type
& V3_AUTHORITY
))
974 /** Try to find a running trusted dirserver. Flags are as for
975 * router_pick_directory_server.
978 router_pick_trusteddirserver(authority_type_t type
, int flags
)
980 routerstatus_t
*choice
;
982 if (get_options()->PreferTunneledDirConns
)
983 flags
|= _PDS_PREFER_TUNNELED_DIR_CONNS
;
985 choice
= router_pick_trusteddirserver_impl(type
, flags
, &busy
);
986 if (choice
|| !(flags
& PDS_RETRY_IF_NO_SERVERS
))
989 /* If the reason that we got no server is that servers are "busy",
990 * we must be excluding good servers because we already have serverdesc
991 * fetches with them. Do not mark down servers up because of this. */
992 tor_assert((flags
& PDS_NO_EXISTING_SERVERDESC_FETCH
));
997 "No trusted dirservers are reachable. Trying them all again.");
998 mark_all_trusteddirservers_up();
999 return router_pick_trusteddirserver_impl(type
, flags
, NULL
);
1002 /** How long do we avoid using a directory server after it's given us a 503? */
1003 #define DIR_503_TIMEOUT (60*60)
1005 /** Pick a random running valid directory server/mirror from our
1006 * routerlist. Arguments are as for router_pick_directory_server(), except
1007 * that RETRY_IF_NO_SERVERS is ignored, and:
1009 * If the _PDS_PREFER_TUNNELED_DIR_CONNS flag is set, prefer directory servers
1010 * that we can use with BEGINDIR.
1012 static routerstatus_t
*
1013 router_pick_directory_server_impl(authority_type_t type
, int flags
)
1015 routerstatus_t
*result
;
1016 smartlist_t
*direct
, *tunnel
;
1017 smartlist_t
*trusted_direct
, *trusted_tunnel
;
1018 smartlist_t
*overloaded_direct
, *overloaded_tunnel
;
1019 time_t now
= time(NULL
);
1020 const networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
1021 int requireother
= ! (flags
& PDS_ALLOW_SELF
);
1022 int fascistfirewall
= ! (flags
& PDS_IGNORE_FASCISTFIREWALL
);
1023 int prefer_tunnel
= (flags
& _PDS_PREFER_TUNNELED_DIR_CONNS
);
1028 direct
= smartlist_create();
1029 tunnel
= smartlist_create();
1030 trusted_direct
= smartlist_create();
1031 trusted_tunnel
= smartlist_create();
1032 overloaded_direct
= smartlist_create();
1033 overloaded_tunnel
= smartlist_create();
1035 /* Find all the running dirservers we know about. */
1036 SMARTLIST_FOREACH_BEGIN(consensus
->routerstatus_list
, routerstatus_t
*,
1039 int is_overloaded
= status
->last_dir_503_at
+ DIR_503_TIMEOUT
> now
;
1041 if (!status
->is_running
|| !status
->dir_port
|| !status
->is_valid
)
1043 if (status
->is_bad_directory
)
1045 if (requireother
&& router_digest_is_me(status
->identity_digest
))
1047 if (type
& V3_AUTHORITY
) {
1048 if (!(status
->version_supports_v3_dir
||
1049 router_digest_is_trusted_dir_type(status
->identity_digest
,
1053 is_trusted
= router_digest_is_trusted_dir(status
->identity_digest
);
1054 if ((type
& V2_AUTHORITY
) && !(status
->is_v2_dir
|| is_trusted
))
1056 if ((type
& EXTRAINFO_CACHE
) &&
1057 !router_supports_extrainfo(status
->identity_digest
, 0))
1060 /* XXXX IP6 proposal 118 */
1061 tor_addr_from_ipv4h(&addr
, status
->addr
);
1063 if (prefer_tunnel
&&
1064 status
->version_supports_begindir
&&
1065 (!fascistfirewall
||
1066 fascist_firewall_allows_address_or(&addr
, status
->or_port
)))
1067 smartlist_add(is_trusted
? trusted_tunnel
:
1068 is_overloaded
? overloaded_tunnel
: tunnel
, status
);
1069 else if (!fascistfirewall
||
1070 fascist_firewall_allows_address_dir(&addr
, status
->dir_port
))
1071 smartlist_add(is_trusted
? trusted_direct
:
1072 is_overloaded
? overloaded_direct
: direct
, status
);
1073 } SMARTLIST_FOREACH_END(status
);
1075 if (smartlist_len(tunnel
)) {
1076 result
= routerstatus_sl_choose_by_bandwidth(tunnel
);
1077 } else if (smartlist_len(overloaded_tunnel
)) {
1078 result
= routerstatus_sl_choose_by_bandwidth(overloaded_tunnel
);
1079 } else if (smartlist_len(trusted_tunnel
)) {
1080 /* FFFF We don't distinguish between trusteds and overloaded trusteds
1081 * yet. Maybe one day we should. */
1082 /* FFFF We also don't load balance over authorities yet. I think this
1083 * is a feature, but it could easily be a bug. -RD */
1084 result
= smartlist_choose(trusted_tunnel
);
1085 } else if (smartlist_len(direct
)) {
1086 result
= routerstatus_sl_choose_by_bandwidth(direct
);
1087 } else if (smartlist_len(overloaded_direct
)) {
1088 result
= routerstatus_sl_choose_by_bandwidth(overloaded_direct
);
1090 result
= smartlist_choose(trusted_direct
);
1092 smartlist_free(direct
);
1093 smartlist_free(tunnel
);
1094 smartlist_free(trusted_direct
);
1095 smartlist_free(trusted_tunnel
);
1096 smartlist_free(overloaded_direct
);
1097 smartlist_free(overloaded_tunnel
);
1101 /** Choose randomly from among the trusted dirservers that are up. Flags
1102 * are as for router_pick_directory_server_impl().
1104 static routerstatus_t
*
1105 router_pick_trusteddirserver_impl(authority_type_t type
, int flags
,
1108 smartlist_t
*direct
, *tunnel
;
1109 smartlist_t
*overloaded_direct
, *overloaded_tunnel
;
1110 routerinfo_t
*me
= router_get_my_routerinfo();
1111 routerstatus_t
*result
;
1112 time_t now
= time(NULL
);
1113 const int requireother
= ! (flags
& PDS_ALLOW_SELF
);
1114 const int fascistfirewall
= ! (flags
& PDS_IGNORE_FASCISTFIREWALL
);
1115 const int prefer_tunnel
= (flags
& _PDS_PREFER_TUNNELED_DIR_CONNS
);
1116 const int no_serverdesc_fetching
=(flags
& PDS_NO_EXISTING_SERVERDESC_FETCH
);
1119 if (!trusted_dir_servers
)
1122 direct
= smartlist_create();
1123 tunnel
= smartlist_create();
1124 overloaded_direct
= smartlist_create();
1125 overloaded_tunnel
= smartlist_create();
1127 SMARTLIST_FOREACH_BEGIN(trusted_dir_servers
, trusted_dir_server_t
*, d
)
1130 d
->fake_status
.last_dir_503_at
+ DIR_503_TIMEOUT
> now
;
1132 if (!d
->is_running
) continue;
1133 if ((type
& d
->type
) == 0)
1135 if ((type
& EXTRAINFO_CACHE
) &&
1136 !router_supports_extrainfo(d
->digest
, 1))
1138 if (requireother
&& me
&& router_digest_is_me(d
->digest
))
1141 /* XXXX IP6 proposal 118 */
1142 tor_addr_from_ipv4h(&addr
, d
->addr
);
1144 if (no_serverdesc_fetching
) {
1145 if (connection_get_by_type_addr_port_purpose(
1146 CONN_TYPE_DIR
, &addr
, d
->dir_port
, DIR_PURPOSE_FETCH_SERVERDESC
)
1147 || connection_get_by_type_addr_port_purpose(
1148 CONN_TYPE_DIR
, &addr
, d
->dir_port
, DIR_PURPOSE_FETCH_EXTRAINFO
)) {
1149 //log_debug(LD_DIR, "We have an existing connection to fetch "
1150 // "descriptor from %s; delaying",d->description);
1156 if (prefer_tunnel
&&
1158 (!fascistfirewall
||
1159 fascist_firewall_allows_address_or(&addr
, d
->or_port
)))
1160 smartlist_add(is_overloaded
? overloaded_tunnel
: tunnel
,
1162 else if (!fascistfirewall
||
1163 fascist_firewall_allows_address_dir(&addr
, d
->dir_port
))
1164 smartlist_add(is_overloaded
? overloaded_direct
: direct
,
1167 SMARTLIST_FOREACH_END(d
);
1169 if (smartlist_len(tunnel
)) {
1170 result
= smartlist_choose(tunnel
);
1171 } else if (smartlist_len(overloaded_tunnel
)) {
1172 result
= smartlist_choose(overloaded_tunnel
);
1173 } else if (smartlist_len(direct
)) {
1174 result
= smartlist_choose(direct
);
1176 result
= smartlist_choose(overloaded_direct
);
1180 *n_busy_out
= n_busy
;
1182 smartlist_free(direct
);
1183 smartlist_free(tunnel
);
1184 smartlist_free(overloaded_direct
);
1185 smartlist_free(overloaded_tunnel
);
1189 /** Go through and mark the authoritative dirservers as up. */
1191 mark_all_trusteddirservers_up(void)
1194 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1195 if (router_digest_is_trusted_dir(router
->cache_info
.identity_digest
) &&
1196 router
->dir_port
> 0) {
1197 router
->is_running
= 1;
1200 if (trusted_dir_servers
) {
1201 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, dir
,
1204 dir
->is_running
= 1;
1205 download_status_reset(&dir
->v2_ns_dl_status
);
1206 rs
= router_get_consensus_status_by_id(dir
->digest
);
1207 if (rs
&& !rs
->is_running
) {
1209 rs
->last_dir_503_at
= 0;
1210 control_event_networkstatus_changed_single(rs
);
1214 router_dir_info_changed();
1217 /** Reset all internal variables used to count failed downloads of network
1218 * status objects. */
1220 router_reset_status_download_failures(void)
1222 mark_all_trusteddirservers_up();
1225 /** Return true iff router1 and router2 have the same /16 network. */
1227 routers_in_same_network_family(routerinfo_t
*r1
, routerinfo_t
*r2
)
1229 return (r1
->addr
& 0xffff0000) == (r2
->addr
& 0xffff0000);
1232 /** Look through the routerlist and identify routers that
1233 * advertise the same /16 network address as <b>router</b>.
1234 * Add each of them to <b>sl</b>.
1237 routerlist_add_network_family(smartlist_t
*sl
, routerinfo_t
*router
)
1239 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, r
,
1241 if (router
!= r
&& routers_in_same_network_family(router
, r
))
1242 smartlist_add(sl
, r
);
1246 /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
1247 * This is used to make sure we don't pick siblings in a single path,
1248 * or pick more than one relay from a family for our entry guard list.
1251 routerlist_add_family(smartlist_t
*sl
, routerinfo_t
*router
)
1255 or_options_t
*options
= get_options();
1257 /* First, add any routers with similar network addresses. */
1258 if (options
->EnforceDistinctSubnets
)
1259 routerlist_add_network_family(sl
, router
);
1261 if (router
->declared_family
) {
1262 /* Add every r such that router declares familyness with r, and r
1263 * declares familyhood with router. */
1264 SMARTLIST_FOREACH(router
->declared_family
, const char *, n
,
1266 if (!(r
= router_get_by_nickname(n
, 0)))
1268 if (!r
->declared_family
)
1270 SMARTLIST_FOREACH(r
->declared_family
, const char *, n2
,
1272 if (router_nickname_matches(router
, n2
))
1273 smartlist_add(sl
, r
);
1278 /* If the user declared any families locally, honor those too. */
1279 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
1280 if (router_nickname_is_in_list(router
, cl
->value
)) {
1281 add_nickname_list_to_smartlist(sl
, cl
->value
, 0);
1286 /** Return true iff r is named by some nickname in <b>lst</b>. */
1288 router_in_nickname_smartlist(smartlist_t
*lst
, routerinfo_t
*r
)
1291 SMARTLIST_FOREACH(lst
, const char *, name
,
1292 if (router_nickname_matches(r
, name
))
1297 /** Return true iff r1 and r2 are in the same family, but not the same
1300 routers_in_same_family(routerinfo_t
*r1
, routerinfo_t
*r2
)
1302 or_options_t
*options
= get_options();
1305 if (options
->EnforceDistinctSubnets
&& routers_in_same_network_family(r1
,r2
))
1308 if (router_in_nickname_smartlist(r1
->declared_family
, r2
) &&
1309 router_in_nickname_smartlist(r2
->declared_family
, r1
))
1312 for (cl
= options
->NodeFamilies
; cl
; cl
= cl
->next
) {
1313 if (router_nickname_is_in_list(r1
, cl
->value
) &&
1314 router_nickname_is_in_list(r2
, cl
->value
))
1320 /** Given a (possibly NULL) comma-and-whitespace separated list of nicknames,
1321 * see which nicknames in <b>list</b> name routers in our routerlist, and add
1322 * the routerinfos for those routers to <b>sl</b>. If <b>must_be_running</b>,
1323 * only include routers that we think are running.
1324 * Warn if any non-Named routers are specified by nickname.
1327 add_nickname_list_to_smartlist(smartlist_t
*sl
, const char *list
,
1328 int must_be_running
)
1330 routerinfo_t
*router
;
1331 smartlist_t
*nickname_list
;
1332 int have_dir_info
= router_have_minimum_dir_info();
1335 return; /* nothing to do */
1338 nickname_list
= smartlist_create();
1339 if (!warned_nicknames
)
1340 warned_nicknames
= smartlist_create();
1342 smartlist_split_string(nickname_list
, list
, ",",
1343 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1345 SMARTLIST_FOREACH(nickname_list
, const char *, nick
, {
1347 if (!is_legal_nickname_or_hexdigest(nick
)) {
1348 log_warn(LD_CONFIG
, "Nickname '%s' is misformed; skipping", nick
);
1351 router
= router_get_by_nickname(nick
, 1);
1352 warned
= smartlist_string_isin(warned_nicknames
, nick
);
1354 if (!must_be_running
|| router
->is_running
) {
1355 smartlist_add(sl
,router
);
1357 } else if (!router_get_consensus_status_by_nickname(nick
,1)) {
1359 log_fn(have_dir_info
? LOG_WARN
: LOG_INFO
, LD_CONFIG
,
1360 "Nickname list includes '%s' which isn't a known router.",nick
);
1361 smartlist_add(warned_nicknames
, tor_strdup(nick
));
1365 SMARTLIST_FOREACH(nickname_list
, char *, nick
, tor_free(nick
));
1366 smartlist_free(nickname_list
);
1369 /** Return 1 iff any member of the (possibly NULL) comma-separated list
1370 * <b>list</b> is an acceptable nickname or hexdigest for <b>router</b>. Else
1374 router_nickname_is_in_list(routerinfo_t
*router
, const char *list
)
1376 smartlist_t
*nickname_list
;
1380 return 0; /* definitely not */
1383 nickname_list
= smartlist_create();
1384 smartlist_split_string(nickname_list
, list
, ",",
1385 SPLIT_SKIP_SPACE
|SPLIT_STRIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1386 SMARTLIST_FOREACH(nickname_list
, const char *, cp
,
1387 if (router_nickname_matches(router
, cp
)) {v
=1;break;});
1388 SMARTLIST_FOREACH(nickname_list
, char *, cp
, tor_free(cp
));
1389 smartlist_free(nickname_list
);
1393 /** Add every suitable router from our routerlist to <b>sl</b>, so that
1394 * we can pick a node for a circuit.
1397 router_add_running_routers_to_smartlist(smartlist_t
*sl
, int allow_invalid
,
1398 int need_uptime
, int need_capacity
,
1404 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1406 if (router
->is_running
&&
1407 router
->purpose
== ROUTER_PURPOSE_GENERAL
&&
1408 (router
->is_valid
|| allow_invalid
) &&
1409 !router_is_unreliable(router
, need_uptime
,
1410 need_capacity
, need_guard
)) {
1411 /* If it's running, and it's suitable according to the
1412 * other flags we had in mind */
1413 smartlist_add(sl
, router
);
1418 /** Look through the routerlist until we find a router that has my key.
1421 routerlist_find_my_routerinfo(void)
1426 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1428 if (router_is_me(router
))
1434 /** Find a router that's up, that has this IP address, and
1435 * that allows exit to this address:port, or return NULL if there
1439 router_find_exact_exit_enclave(const char *address
, uint16_t port
)
1444 if (!tor_inet_aton(address
, &in
))
1445 return NULL
; /* it's not an IP already */
1446 addr
= ntohl(in
.s_addr
);
1448 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1450 if (router
->is_running
&&
1451 router
->addr
== addr
&&
1452 compare_addr_to_addr_policy(addr
, port
, router
->exit_policy
) ==
1453 ADDR_POLICY_ACCEPTED
)
1459 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1460 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1461 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1463 * If <b>need_guard</b>, we require that the router is a possible entry guard.
1466 router_is_unreliable(routerinfo_t
*router
, int need_uptime
,
1467 int need_capacity
, int need_guard
)
1469 if (need_uptime
&& !router
->is_stable
)
1471 if (need_capacity
&& !router
->is_fast
)
1473 if (need_guard
&& !router
->is_possible_guard
)
1478 /** Return the smaller of the router's configured BandwidthRate
1479 * and its advertised capacity. */
1481 router_get_advertised_bandwidth(routerinfo_t
*router
)
1483 if (router
->bandwidthcapacity
< router
->bandwidthrate
)
1484 return router
->bandwidthcapacity
;
1485 return router
->bandwidthrate
;
1488 /** Do not weight any declared bandwidth more than this much when picking
1489 * routers by bandwidth. */
1490 #define DEFAULT_MAX_BELIEVABLE_BANDWIDTH 10000000 /* 10 MB/sec */
1492 /** Return the smaller of the router's configured BandwidthRate
1493 * and its advertised capacity, capped by max-believe-bw. */
1495 router_get_advertised_bandwidth_capped(routerinfo_t
*router
)
1497 uint32_t result
= router
->bandwidthcapacity
;
1498 if (result
> router
->bandwidthrate
)
1499 result
= router
->bandwidthrate
;
1500 if (result
> DEFAULT_MAX_BELIEVABLE_BANDWIDTH
)
1501 result
= DEFAULT_MAX_BELIEVABLE_BANDWIDTH
;
1505 /** Eventually, the number we return will come from the directory
1506 * consensus, so clients can dynamically update to better numbers.
1508 * But for now, or in case there is no consensus available, just return
1509 * a sufficient default. */
1511 get_max_believable_bandwidth(void)
1513 return DEFAULT_MAX_BELIEVABLE_BANDWIDTH
;
1516 /** Helper function:
1517 * choose a random element of smartlist <b>sl</b>, weighted by
1518 * the advertised bandwidth of each element.
1520 * If <b>statuses</b> is zero, then <b>sl</b> is a list of
1521 * routerinfo_t's. Otherwise it's a list of routerstatus_t's.
1523 * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
1524 * nodes' bandwidth equally regardless of their Exit status, since there may
1525 * be some in the list because they exit to obscure ports. If
1526 * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
1527 * exit-node's bandwidth less depending on the smallness of the fraction of
1528 * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
1529 * guard node: consider all guard's bandwidth equally. Otherwise, weight
1530 * guards proportionally less.
1533 smartlist_choose_by_bandwidth(smartlist_t
*sl
, bandwidth_weight_rule_t rule
,
1537 routerinfo_t
*router
;
1538 routerstatus_t
*status
=NULL
;
1539 int32_t *bandwidths
;
1542 uint64_t total_nonexit_bw
= 0, total_exit_bw
= 0, total_bw
= 0;
1543 uint64_t total_nonguard_bw
= 0, total_guard_bw
= 0;
1544 uint64_t rand_bw
, tmp
;
1546 double guard_weight
;
1548 bitarray_t
*exit_bits
;
1549 bitarray_t
*guard_bits
;
1550 uint32_t max_believable_bw
= get_max_believable_bandwidth();
1553 /* Can't choose exit and guard at same time */
1554 tor_assert(rule
== NO_WEIGHTING
||
1555 rule
== WEIGHT_FOR_EXIT
||
1556 rule
== WEIGHT_FOR_GUARD
);
1558 /* First count the total bandwidth weight, and make a list
1559 * of each value. <0 means "unknown; no routerinfo." We use the
1560 * bits of negative values to remember whether the router was fast (-x)&1
1561 * and whether it was an exit (-x)&2 or guard (-x)&4. Yes, it's a hack. */
1562 bandwidths
= tor_malloc(sizeof(int32_t)*smartlist_len(sl
));
1563 exit_bits
= bitarray_init_zero(smartlist_len(sl
));
1564 guard_bits
= bitarray_init_zero(smartlist_len(sl
));
1566 /* Iterate over all the routerinfo_t or routerstatus_t, and */
1567 for (i
= 0; i
< (unsigned)smartlist_len(sl
); ++i
) {
1568 /* first, learn what bandwidth we think i has */
1571 uint32_t this_bw
= 0;
1573 /* need to extract router info */
1574 status
= smartlist_get(sl
, i
);
1575 if (router_digest_is_me(status
->identity_digest
))
1577 router
= router_get_by_digest(status
->identity_digest
);
1578 is_exit
= status
->is_exit
;
1579 is_guard
= status
->is_possible_guard
;
1581 this_bw
= router_get_advertised_bandwidth(router
);
1582 } else { /* guess */
1584 flags
= status
->is_fast
? 1 : 0;
1585 flags
|= is_exit
? 2 : 0;
1586 flags
|= is_guard
? 4 : 0;
1589 router
= smartlist_get(sl
, i
);
1590 if (router_digest_is_me(router
->cache_info
.identity_digest
))
1592 is_exit
= router
->is_exit
;
1593 is_guard
= router
->is_possible_guard
;
1594 this_bw
= router_get_advertised_bandwidth(router
);
1597 bitarray_set(exit_bits
, i
);
1599 bitarray_set(guard_bits
, i
);
1600 /* if they claim something huge, don't believe it */
1601 if (this_bw
> max_believable_bw
) {
1602 char fp
[HEX_DIGEST_LEN
+1];
1603 base16_encode(fp
, sizeof(fp
), statuses
?
1604 status
->identity_digest
:
1605 router
->cache_info
.identity_digest
,
1607 log_fn(LOG_PROTOCOL_WARN
, LD_DIR
,
1608 "Bandwidth %d for router %s (%s) exceeds allowed max %d, capping",
1609 this_bw
, router
? router
->nickname
: "(null)",
1610 fp
, max_believable_bw
);
1611 this_bw
= max_believable_bw
;
1614 bandwidths
[i
] = (int32_t) this_bw
; // safe since MAX_BELIEVABLE<INT32_MAX
1616 total_guard_bw
+= this_bw
;
1618 total_nonguard_bw
+= this_bw
;
1620 total_exit_bw
+= this_bw
;
1622 total_nonexit_bw
+= this_bw
;
1625 bandwidths
[i
] = -flags
;
1629 /* Now, fill in the unknown values. */
1631 int32_t avg_fast
, avg_slow
;
1632 if (total_exit_bw
+total_nonexit_bw
) {
1633 /* if there's some bandwidth, there's at least one known router,
1634 * so no worries about div by 0 here */
1635 int n_known
= smartlist_len(sl
)-n_unknown
;
1636 avg_fast
= avg_slow
= (int32_t)
1637 ((total_exit_bw
+total_nonexit_bw
)/((uint64_t) n_known
));
1642 for (i
=0; i
<(unsigned)smartlist_len(sl
); ++i
) {
1643 int32_t bw
= bandwidths
[i
];
1646 is_exit
= ((-bw
)&2);
1647 is_guard
= ((-bw
)&4);
1648 bandwidths
[i
] = ((-bw
)&1) ? avg_fast
: avg_slow
;
1650 total_exit_bw
+= bandwidths
[i
];
1652 total_nonexit_bw
+= bandwidths
[i
];
1654 total_guard_bw
+= bandwidths
[i
];
1656 total_nonguard_bw
+= bandwidths
[i
];
1660 /* If there's no bandwidth at all, pick at random. */
1661 if (!(total_exit_bw
+total_nonexit_bw
)) {
1662 tor_free(bandwidths
);
1663 tor_free(exit_bits
);
1664 tor_free(guard_bits
);
1665 return smartlist_choose(sl
);
1668 /* Figure out how to weight exits and guards */
1670 double all_bw
= U64_TO_DBL(total_exit_bw
+total_nonexit_bw
);
1671 double exit_bw
= U64_TO_DBL(total_exit_bw
);
1672 double guard_bw
= U64_TO_DBL(total_guard_bw
);
1674 * For detailed derivation of this formula, see
1675 * http://archives.seul.org/or/dev/Jul-2007/msg00056.html
1677 if (rule
== WEIGHT_FOR_EXIT
)
1680 exit_weight
= 1.0 - all_bw
/(3.0*exit_bw
);
1682 if (rule
== WEIGHT_FOR_GUARD
)
1685 guard_weight
= 1.0 - all_bw
/(3.0*guard_bw
);
1687 if (exit_weight
<= 0.0)
1690 if (guard_weight
<= 0.0)
1694 sl_last_weighted_bw_of_me
= 0;
1695 for (i
=0; i
< (unsigned)smartlist_len(sl
); i
++) {
1697 is_exit
= bitarray_is_set(exit_bits
, i
);
1698 is_guard
= bitarray_is_set(guard_bits
, i
);
1699 if (is_exit
&& is_guard
)
1700 bw
= ((uint64_t)(bandwidths
[i
] * exit_weight
* guard_weight
));
1702 bw
= ((uint64_t)(bandwidths
[i
] * guard_weight
));
1704 bw
= ((uint64_t)(bandwidths
[i
] * exit_weight
));
1708 if (i
== (unsigned) me_idx
)
1709 sl_last_weighted_bw_of_me
= bw
;
1713 /* XXXX021 this is a kludge to expose these values. */
1714 sl_last_total_weighted_bw
= total_bw
;
1716 log_debug(LD_CIRC
, "Total weighted bw = "U64_FORMAT
1717 ", exit bw = "U64_FORMAT
1718 ", nonexit bw = "U64_FORMAT
", exit weight = %lf "
1720 ", guard bw = "U64_FORMAT
1721 ", nonguard bw = "U64_FORMAT
", guard weight = %lf "
1722 "(for guard == %d)",
1723 U64_PRINTF_ARG(total_bw
),
1724 U64_PRINTF_ARG(total_exit_bw
), U64_PRINTF_ARG(total_nonexit_bw
),
1725 exit_weight
, (int)(rule
== WEIGHT_FOR_EXIT
),
1726 U64_PRINTF_ARG(total_guard_bw
), U64_PRINTF_ARG(total_nonguard_bw
),
1727 guard_weight
, (int)(rule
== WEIGHT_FOR_GUARD
));
1729 /* Almost done: choose a random value from the bandwidth weights. */
1730 rand_bw
= crypto_rand_uint64(total_bw
);
1732 /* Last, count through sl until we get to the element we picked */
1734 for (i
=0; i
< (unsigned)smartlist_len(sl
); i
++) {
1735 is_exit
= bitarray_is_set(exit_bits
, i
);
1736 is_guard
= bitarray_is_set(guard_bits
, i
);
1738 /* Weights can be 0 if not counting guards/exits */
1739 if (is_exit
&& is_guard
)
1740 tmp
+= ((uint64_t)(bandwidths
[i
] * exit_weight
* guard_weight
));
1742 tmp
+= ((uint64_t)(bandwidths
[i
] * guard_weight
));
1744 tmp
+= ((uint64_t)(bandwidths
[i
] * exit_weight
));
1746 tmp
+= bandwidths
[i
];
1751 if (i
== (unsigned)smartlist_len(sl
)) {
1752 /* This was once possible due to round-off error, but shouldn't be able
1753 * to occur any longer. */
1754 tor_fragile_assert();
1756 log_warn(LD_BUG
, "Round-off error in computing bandwidth had an effect on "
1757 " which router we chose. Please tell the developers. "
1758 U64_FORMAT
" " U64_FORMAT
" " U64_FORMAT
, U64_PRINTF_ARG(tmp
),
1759 U64_PRINTF_ARG(rand_bw
), U64_PRINTF_ARG(total_bw
));
1761 tor_free(bandwidths
);
1762 tor_free(exit_bits
);
1763 tor_free(guard_bits
);
1764 return smartlist_get(sl
, i
);
1767 /** Choose a random element of router list <b>sl</b>, weighted by
1768 * the advertised bandwidth of each router.
1771 routerlist_sl_choose_by_bandwidth(smartlist_t
*sl
,
1772 bandwidth_weight_rule_t rule
)
1774 return smartlist_choose_by_bandwidth(sl
, rule
, 0);
1777 /** Choose a random element of status list <b>sl</b>, weighted by
1778 * the advertised bandwidth of each status.
1781 routerstatus_sl_choose_by_bandwidth(smartlist_t
*sl
)
1783 /* We are choosing neither exit nor guard here. Weight accordingly. */
1784 return smartlist_choose_by_bandwidth(sl
, NO_WEIGHTING
, 1);
1787 /** Return a random running router from the routerlist. If any node
1788 * named in <b>preferred</b> is available, pick one of those. Never
1789 * pick a node whose routerinfo is in
1790 * <b>excludedsmartlist</b>, or whose routerinfo matches <b>excludedset</b>,
1791 * even if they are the only nodes
1792 * available. If <b>CRN_STRICT_PREFERRED</b> is set in flags, never pick
1793 * any node besides those in <b>preferred</b>.
1794 * If <b>CRN_NEED_UPTIME</b> is set in flags and any router has more than
1795 * a minimum uptime, return one of those.
1796 * If <b>CRN_NEED_CAPACITY</b> is set in flags, weight your choice by the
1797 * advertised capacity of each router.
1798 * If <b>CRN_ALLOW_INVALID</b> is not set in flags, consider only Valid
1800 * If <b>CRN_NEED_GUARD</b> is set in flags, consider only Guard routers.
1801 * If <b>CRN_WEIGHT_AS_EXIT</b> is set in flags, we weight bandwidths as if
1802 * picking an exit node, otherwise we weight bandwidths for picking a relay
1803 * node (that is, possibly discounting exit nodes).
1806 router_choose_random_node(const char *preferred
,
1807 smartlist_t
*excludedsmartlist
,
1808 routerset_t
*excludedset
,
1809 router_crn_flags_t flags
)
1811 const int need_uptime
= (flags
& CRN_NEED_UPTIME
) != 0;
1812 const int need_capacity
= (flags
& CRN_NEED_CAPACITY
) != 0;
1813 const int need_guard
= (flags
& CRN_NEED_GUARD
) != 0;
1814 const int allow_invalid
= (flags
& CRN_ALLOW_INVALID
) != 0;
1815 const int strict
= (flags
& CRN_STRICT_PREFERRED
) != 0;
1816 const int weight_for_exit
= (flags
& CRN_WEIGHT_AS_EXIT
) != 0;
1818 smartlist_t
*sl
, *excludednodes
;
1819 routerinfo_t
*choice
= NULL
, *r
;
1820 bandwidth_weight_rule_t rule
;
1822 tor_assert(!(weight_for_exit
&& need_guard
));
1823 rule
= weight_for_exit
? WEIGHT_FOR_EXIT
:
1824 (need_guard
? WEIGHT_FOR_GUARD
: NO_WEIGHTING
);
1826 excludednodes
= smartlist_create();
1828 /* Exclude relays that allow single hop exit circuits, if the user
1829 * wants to (such relays might be risky) */
1830 if (get_options()->ExcludeSingleHopRelays
) {
1831 routerlist_t
*rl
= router_get_routerlist();
1832 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
1833 if (r
->allow_single_hop_exits
) {
1834 smartlist_add(excludednodes
, r
);
1838 if ((r
= routerlist_find_my_routerinfo())) {
1839 smartlist_add(excludednodes
, r
);
1840 routerlist_add_family(excludednodes
, r
);
1843 /* Try the preferred nodes first. Ignore need_uptime and need_capacity
1844 * and need_guard, since the user explicitly asked for these nodes. */
1846 sl
= smartlist_create();
1847 add_nickname_list_to_smartlist(sl
,preferred
,1);
1848 smartlist_subtract(sl
,excludednodes
);
1849 if (excludedsmartlist
)
1850 smartlist_subtract(sl
,excludedsmartlist
);
1852 routerset_subtract_routers(sl
,excludedset
);
1853 choice
= smartlist_choose(sl
);
1856 if (!choice
&& !strict
) {
1857 /* Then give up on our preferred choices: any node
1858 * will do that has the required attributes. */
1859 sl
= smartlist_create();
1860 router_add_running_routers_to_smartlist(sl
, allow_invalid
,
1861 need_uptime
, need_capacity
,
1863 smartlist_subtract(sl
,excludednodes
);
1864 if (excludedsmartlist
)
1865 smartlist_subtract(sl
,excludedsmartlist
);
1867 routerset_subtract_routers(sl
,excludedset
);
1869 if (need_capacity
|| need_guard
)
1870 choice
= routerlist_sl_choose_by_bandwidth(sl
, rule
);
1872 choice
= smartlist_choose(sl
);
1875 if (!choice
&& (need_uptime
|| need_capacity
|| need_guard
)) {
1876 /* try once more -- recurse but with fewer restrictions. */
1878 "We couldn't find any live%s%s%s routers; falling back "
1879 "to list of all routers.",
1880 need_capacity
?", fast":"",
1881 need_uptime
?", stable":"",
1882 need_guard
?", guard":"");
1883 flags
&= ~ (CRN_NEED_UPTIME
|CRN_NEED_CAPACITY
|CRN_NEED_GUARD
);
1884 choice
= router_choose_random_node(
1885 NULL
, excludedsmartlist
, excludedset
, flags
);
1888 smartlist_free(excludednodes
);
1891 log_warn(LD_CIRC
, "All preferred nodes were down when trying to choose "
1892 "node, and the Strict[...]Nodes option is set. Failing.");
1895 "No available nodes when trying to choose node. Failing.");
1901 /** Helper: Return true iff the <b>identity_digest</b> and <b>nickname</b>
1902 * combination of a router, encoded in hexadecimal, matches <b>hexdigest</b>
1903 * (which is optionally prefixed with a single dollar sign). Return false if
1904 * <b>hexdigest</b> is malformed, or it doesn't match. */
1906 hex_digest_matches(const char *hexdigest
, const char *identity_digest
,
1907 const char *nickname
, int is_named
)
1909 char digest
[DIGEST_LEN
];
1911 tor_assert(hexdigest
);
1912 if (hexdigest
[0] == '$')
1915 len
= strlen(hexdigest
);
1916 if (len
< HEX_DIGEST_LEN
)
1918 else if (len
> HEX_DIGEST_LEN
&&
1919 (hexdigest
[HEX_DIGEST_LEN
] == '=' ||
1920 hexdigest
[HEX_DIGEST_LEN
] == '~')) {
1921 if (strcasecmp(hexdigest
+HEX_DIGEST_LEN
+1, nickname
))
1923 if (hexdigest
[HEX_DIGEST_LEN
] == '=' && !is_named
)
1927 if (base16_decode(digest
, DIGEST_LEN
, hexdigest
, HEX_DIGEST_LEN
)<0)
1929 return (!memcmp(digest
, identity_digest
, DIGEST_LEN
));
1932 /** Return true iff the digest of <b>router</b>'s identity key,
1933 * encoded in hexadecimal, matches <b>hexdigest</b> (which is
1934 * optionally prefixed with a single dollar sign). Return false if
1935 * <b>hexdigest</b> is malformed, or it doesn't match. */
1937 router_hex_digest_matches(routerinfo_t
*router
, const char *hexdigest
)
1939 return hex_digest_matches(hexdigest
, router
->cache_info
.identity_digest
,
1940 router
->nickname
, router
->is_named
);
1943 /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
1944 * (case-insensitive), or if <b>router's</b> identity key digest
1945 * matches a hexadecimal value stored in <b>nickname</b>. Return
1946 * false otherwise. */
1948 router_nickname_matches(routerinfo_t
*router
, const char *nickname
)
1950 if (nickname
[0]!='$' && !strcasecmp(router
->nickname
, nickname
))
1952 return router_hex_digest_matches(router
, nickname
);
1955 /** Return the router in our routerlist whose (case-insensitive)
1956 * nickname or (case-sensitive) hexadecimal key digest is
1957 * <b>nickname</b>. Return NULL if no such router is known.
1960 router_get_by_nickname(const char *nickname
, int warn_if_unnamed
)
1963 char digest
[DIGEST_LEN
];
1964 routerinfo_t
*best_match
=NULL
;
1966 const char *named_digest
= NULL
;
1968 tor_assert(nickname
);
1971 if (nickname
[0] == '$')
1972 return router_get_by_hexdigest(nickname
);
1973 if (!strcasecmp(nickname
, UNNAMED_ROUTER_NICKNAME
))
1975 if (server_mode(get_options()) &&
1976 !strcasecmp(nickname
, get_options()->Nickname
))
1977 return router_get_my_routerinfo();
1979 maybedigest
= (strlen(nickname
) >= HEX_DIGEST_LEN
) &&
1980 (base16_decode(digest
,DIGEST_LEN
,nickname
,HEX_DIGEST_LEN
) == 0);
1982 if ((named_digest
= networkstatus_get_router_digest_by_nickname(nickname
))) {
1983 return rimap_get(routerlist
->identity_map
, named_digest
);
1985 if (networkstatus_nickname_is_unnamed(nickname
))
1988 /* If we reach this point, there's no canonical value for the nickname. */
1990 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
1992 if (!strcasecmp(router
->nickname
, nickname
)) {
1994 if (n_matches
<= 1 || router
->is_running
)
1995 best_match
= router
;
1996 } else if (maybedigest
&&
1997 !memcmp(digest
, router
->cache_info
.identity_digest
, DIGEST_LEN
)
1999 if (router_hex_digest_matches(router
, nickname
))
2001 /* If we reach this point, we have a ID=name syntax that matches the
2002 * identity but not the name. That isn't an acceptable match. */
2007 if (warn_if_unnamed
&& n_matches
> 1) {
2008 smartlist_t
*fps
= smartlist_create();
2009 int any_unwarned
= 0;
2010 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
2015 char fp
[HEX_DIGEST_LEN
+1];
2016 if (strcasecmp(router
->nickname
, nickname
))
2018 rs
= router_get_consensus_status_by_id(
2019 router
->cache_info
.identity_digest
);
2020 if (rs
&& !rs
->name_lookup_warned
) {
2021 rs
->name_lookup_warned
= 1;
2024 base16_encode(fp
, sizeof(fp
),
2025 router
->cache_info
.identity_digest
, DIGEST_LEN
);
2026 dlen
= 32 + HEX_DIGEST_LEN
+ strlen(router
->address
);
2027 desc
= tor_malloc(dlen
);
2028 tor_snprintf(desc
, dlen
, "\"$%s\" for the one at %s:%d",
2029 fp
, router
->address
, router
->or_port
);
2030 smartlist_add(fps
, desc
);
2033 char *alternatives
= smartlist_join_strings(fps
, "; ",0,NULL
);
2035 "There are multiple matches for the nickname \"%s\","
2036 " but none is listed as named by the directory authorities. "
2037 "Choosing one arbitrarily. If you meant one in particular, "
2038 "you should say %s.", nickname
, alternatives
);
2039 tor_free(alternatives
);
2041 SMARTLIST_FOREACH(fps
, char *, cp
, tor_free(cp
));
2042 smartlist_free(fps
);
2043 } else if (warn_if_unnamed
) {
2044 routerstatus_t
*rs
= router_get_consensus_status_by_id(
2045 best_match
->cache_info
.identity_digest
);
2046 if (rs
&& !rs
->name_lookup_warned
) {
2047 char fp
[HEX_DIGEST_LEN
+1];
2048 base16_encode(fp
, sizeof(fp
),
2049 best_match
->cache_info
.identity_digest
, DIGEST_LEN
);
2050 log_warn(LD_CONFIG
, "You specified a server \"%s\" by name, but this "
2051 "name is not registered, so it could be used by any server, "
2052 "not just the one you meant. "
2053 "To make sure you get the same server in the future, refer to "
2054 "it by key, as \"$%s\".", nickname
, fp
);
2055 rs
->name_lookup_warned
= 1;
2064 /** Try to find a routerinfo for <b>digest</b>. If we don't have one,
2065 * return 1. If we do, ask tor_version_as_new_as() for the answer.
2068 router_digest_version_as_new_as(const char *digest
, const char *cutoff
)
2070 routerinfo_t
*router
= router_get_by_digest(digest
);
2073 return tor_version_as_new_as(router
->platform
, cutoff
);
2076 /** Return true iff <b>digest</b> is the digest of the identity key of a
2077 * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
2078 * is zero, any authority is okay. */
2080 router_digest_is_trusted_dir_type(const char *digest
, authority_type_t type
)
2082 if (!trusted_dir_servers
)
2084 if (authdir_mode(get_options()) && router_digest_is_me(digest
))
2086 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
2087 if (!memcmp(digest
, ent
->digest
, DIGEST_LEN
)) {
2088 return (!type
) || ((type
& ent
->type
) != 0);
2093 /** Return true iff <b>addr</b> is the address of one of our trusted
2094 * directory authorities. */
2096 router_addr_is_trusted_dir(uint32_t addr
)
2098 if (!trusted_dir_servers
)
2100 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
2101 if (ent
->addr
== addr
)
2107 /** If hexdigest is correctly formed, base16_decode it into
2108 * digest, which must have DIGEST_LEN space in it.
2109 * Return 0 on success, -1 on failure.
2112 hexdigest_to_digest(const char *hexdigest
, char *digest
)
2114 if (hexdigest
[0]=='$')
2116 if (strlen(hexdigest
) < HEX_DIGEST_LEN
||
2117 base16_decode(digest
,DIGEST_LEN
,hexdigest
,HEX_DIGEST_LEN
) < 0)
2122 /** Return the router in our routerlist whose hexadecimal key digest
2123 * is <b>hexdigest</b>. Return NULL if no such router is known. */
2125 router_get_by_hexdigest(const char *hexdigest
)
2127 char digest
[DIGEST_LEN
];
2131 tor_assert(hexdigest
);
2134 if (hexdigest
[0]=='$')
2136 len
= strlen(hexdigest
);
2137 if (hexdigest_to_digest(hexdigest
, digest
) < 0)
2140 ri
= router_get_by_digest(digest
);
2142 if (ri
&& len
> HEX_DIGEST_LEN
) {
2143 if (hexdigest
[HEX_DIGEST_LEN
] == '=') {
2144 if (strcasecmp(ri
->nickname
, hexdigest
+HEX_DIGEST_LEN
+1) ||
2147 } else if (hexdigest
[HEX_DIGEST_LEN
] == '~') {
2148 if (strcasecmp(ri
->nickname
, hexdigest
+HEX_DIGEST_LEN
+1))
2158 /** Return the router in our routerlist whose 20-byte key digest
2159 * is <b>digest</b>. Return NULL if no such router is known. */
2161 router_get_by_digest(const char *digest
)
2165 if (!routerlist
) return NULL
;
2167 // routerlist_assert_ok(routerlist);
2169 return rimap_get(routerlist
->identity_map
, digest
);
2172 /** Return the router in our routerlist whose 20-byte descriptor
2173 * is <b>digest</b>. Return NULL if no such router is known. */
2174 signed_descriptor_t
*
2175 router_get_by_descriptor_digest(const char *digest
)
2179 if (!routerlist
) return NULL
;
2181 return sdmap_get(routerlist
->desc_digest_map
, digest
);
2184 /** Return the signed descriptor for the router in our routerlist whose
2185 * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
2187 signed_descriptor_t
*
2188 router_get_by_extrainfo_digest(const char *digest
)
2192 if (!routerlist
) return NULL
;
2194 return sdmap_get(routerlist
->desc_by_eid_map
, digest
);
2197 /** Return the signed descriptor for the extrainfo_t in our routerlist whose
2198 * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
2199 * document is known. */
2200 signed_descriptor_t
*
2201 extrainfo_get_by_descriptor_digest(const char *digest
)
2205 if (!routerlist
) return NULL
;
2206 ei
= eimap_get(routerlist
->extra_info_map
, digest
);
2207 return ei
? &ei
->cache_info
: NULL
;
2210 /** Return a pointer to the signed textual representation of a descriptor.
2211 * The returned string is not guaranteed to be NUL-terminated: the string's
2212 * length will be in desc-\>signed_descriptor_len.
2214 * If <b>with_annotations</b> is set, the returned string will include
2216 * (if any) preceding the descriptor. This will increase the length of the
2217 * string by desc-\>annotations_len.
2219 * The caller must not free the string returned.
2222 signed_descriptor_get_body_impl(signed_descriptor_t
*desc
,
2223 int with_annotations
)
2225 const char *r
= NULL
;
2226 size_t len
= desc
->signed_descriptor_len
;
2227 off_t offset
= desc
->saved_offset
;
2228 if (with_annotations
)
2229 len
+= desc
->annotations_len
;
2231 offset
+= desc
->annotations_len
;
2233 tor_assert(len
> 32);
2234 if (desc
->saved_location
== SAVED_IN_CACHE
&& routerlist
) {
2235 desc_store_t
*store
= desc_get_store(router_get_routerlist(), desc
);
2236 if (store
&& store
->mmap
) {
2237 tor_assert(desc
->saved_offset
+ len
<= store
->mmap
->size
);
2238 r
= store
->mmap
->data
+ offset
;
2240 log_err(LD_DIR
, "We couldn't read a descriptor that is supposedly "
2241 "mmaped in our cache. Is another process running in our data "
2242 "directory? Exiting.");
2246 if (!r
) /* no mmap, or not in cache. */
2247 r
= desc
->signed_descriptor_body
+
2248 (with_annotations
? 0 : desc
->annotations_len
);
2251 if (!with_annotations
) {
2252 if (memcmp("router ", r
, 7) && memcmp("extra-info ", r
, 11)) {
2253 char *cp
= tor_strndup(r
, 64);
2254 log_err(LD_DIR
, "descriptor at %p begins with unexpected string %s. "
2255 "Is another process running in our data directory? Exiting.",
2264 /** Return a pointer to the signed textual representation of a descriptor.
2265 * The returned string is not guaranteed to be NUL-terminated: the string's
2266 * length will be in desc-\>signed_descriptor_len.
2268 * The caller must not free the string returned.
2271 signed_descriptor_get_body(signed_descriptor_t
*desc
)
2273 return signed_descriptor_get_body_impl(desc
, 0);
2276 /** As signed_descriptor_get_body(), but points to the beginning of the
2277 * annotations section rather than the beginning of the descriptor. */
2279 signed_descriptor_get_annotations(signed_descriptor_t
*desc
)
2281 return signed_descriptor_get_body_impl(desc
, 1);
2284 /** Return the current list of all known routers. */
2286 router_get_routerlist(void)
2288 if (PREDICT_UNLIKELY(!routerlist
)) {
2289 routerlist
= tor_malloc_zero(sizeof(routerlist_t
));
2290 routerlist
->routers
= smartlist_create();
2291 routerlist
->old_routers
= smartlist_create();
2292 routerlist
->identity_map
= rimap_new();
2293 routerlist
->desc_digest_map
= sdmap_new();
2294 routerlist
->desc_by_eid_map
= sdmap_new();
2295 routerlist
->extra_info_map
= eimap_new();
2297 routerlist
->desc_store
.fname_base
= "cached-descriptors";
2298 routerlist
->desc_store
.fname_alt_base
= "cached-routers";
2299 routerlist
->extrainfo_store
.fname_base
= "cached-extrainfo";
2301 routerlist
->desc_store
.type
= ROUTER_STORE
;
2302 routerlist
->extrainfo_store
.type
= EXTRAINFO_STORE
;
2304 routerlist
->desc_store
.description
= "router descriptors";
2305 routerlist
->extrainfo_store
.description
= "extra-info documents";
2310 /** Free all storage held by <b>router</b>. */
2312 routerinfo_free(routerinfo_t
*router
)
2317 tor_free(router
->cache_info
.signed_descriptor_body
);
2318 tor_free(router
->address
);
2319 tor_free(router
->nickname
);
2320 tor_free(router
->platform
);
2321 tor_free(router
->contact_info
);
2322 if (router
->onion_pkey
)
2323 crypto_free_pk_env(router
->onion_pkey
);
2324 if (router
->identity_pkey
)
2325 crypto_free_pk_env(router
->identity_pkey
);
2326 if (router
->declared_family
) {
2327 SMARTLIST_FOREACH(router
->declared_family
, char *, s
, tor_free(s
));
2328 smartlist_free(router
->declared_family
);
2330 addr_policy_list_free(router
->exit_policy
);
2332 /* XXXX Remove if this turns out to affect performance. */
2333 memset(router
, 77, sizeof(routerinfo_t
));
2338 /** Release all storage held by <b>extrainfo</b> */
2340 extrainfo_free(extrainfo_t
*extrainfo
)
2344 tor_free(extrainfo
->cache_info
.signed_descriptor_body
);
2345 tor_free(extrainfo
->pending_sig
);
2347 /* XXXX remove this if it turns out to slow us down. */
2348 memset(extrainfo
, 88, sizeof(extrainfo_t
)); /* debug bad memory usage */
2349 tor_free(extrainfo
);
2352 /** Release storage held by <b>sd</b>. */
2354 signed_descriptor_free(signed_descriptor_t
*sd
)
2356 tor_free(sd
->signed_descriptor_body
);
2358 /* XXXX remove this once more bugs go away. */
2359 memset(sd
, 99, sizeof(signed_descriptor_t
)); /* Debug bad mem usage */
2363 /** Extract a signed_descriptor_t from a routerinfo, and free the routerinfo.
2365 static signed_descriptor_t
*
2366 signed_descriptor_from_routerinfo(routerinfo_t
*ri
)
2368 signed_descriptor_t
*sd
= tor_malloc_zero(sizeof(signed_descriptor_t
));
2369 memcpy(sd
, &(ri
->cache_info
), sizeof(signed_descriptor_t
));
2370 sd
->routerlist_index
= -1;
2371 ri
->cache_info
.signed_descriptor_body
= NULL
;
2372 routerinfo_free(ri
);
2376 /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
2378 _extrainfo_free(void *e
)
2383 /** Free all storage held by a routerlist <b>rl</b>. */
2385 routerlist_free(routerlist_t
*rl
)
2388 rimap_free(rl
->identity_map
, NULL
);
2389 sdmap_free(rl
->desc_digest_map
, NULL
);
2390 sdmap_free(rl
->desc_by_eid_map
, NULL
);
2391 eimap_free(rl
->extra_info_map
, _extrainfo_free
);
2392 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
2393 routerinfo_free(r
));
2394 SMARTLIST_FOREACH(rl
->old_routers
, signed_descriptor_t
*, sd
,
2395 signed_descriptor_free(sd
));
2396 smartlist_free(rl
->routers
);
2397 smartlist_free(rl
->old_routers
);
2398 if (routerlist
->desc_store
.mmap
)
2399 tor_munmap_file(routerlist
->desc_store
.mmap
);
2400 if (routerlist
->extrainfo_store
.mmap
)
2401 tor_munmap_file(routerlist
->extrainfo_store
.mmap
);
2404 router_dir_info_changed();
2407 /** Log information about how much memory is being used for routerlist,
2408 * at log level <b>severity</b>. */
2410 dump_routerlist_mem_usage(int severity
)
2412 uint64_t livedescs
= 0;
2413 uint64_t olddescs
= 0;
2416 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, r
,
2417 livedescs
+= r
->cache_info
.signed_descriptor_len
);
2418 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
,
2419 olddescs
+= sd
->signed_descriptor_len
);
2421 log(severity
, LD_DIR
,
2422 "In %d live descriptors: "U64_FORMAT
" bytes. "
2423 "In %d old descriptors: "U64_FORMAT
" bytes.",
2424 smartlist_len(routerlist
->routers
), U64_PRINTF_ARG(livedescs
),
2425 smartlist_len(routerlist
->old_routers
), U64_PRINTF_ARG(olddescs
));
2429 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
2430 networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
2431 log(severity
, LD_DIR
, "Now let's look through old_descriptors!");
2432 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
, {
2435 char published
[ISO_TIME_LEN
+1];
2436 char last_valid_until
[ISO_TIME_LEN
+1];
2437 char last_served_at
[ISO_TIME_LEN
+1];
2438 char id
[HEX_DIGEST_LEN
+1];
2440 format_iso_time(published
, sd
->published_on
);
2441 format_iso_time(last_valid_until
, sd
->last_listed_as_valid_until
);
2442 format_iso_time(last_served_at
, sd
->last_served_at
);
2443 base16_encode(id
, sizeof(id
), sd
->identity_digest
, DIGEST_LEN
);
2444 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
2446 rs
= networkstatus_v2_find_entry(ns
, sd
->identity_digest
);
2447 if (rs
&& !memcmp(rs
->descriptor_digest
,
2448 sd
->signed_descriptor_digest
, DIGEST_LEN
)) {
2453 rs
= networkstatus_vote_find_entry(consensus
, sd
->identity_digest
);
2454 if (rs
&& !memcmp(rs
->descriptor_digest
,
2455 sd
->signed_descriptor_digest
, DIGEST_LEN
))
2458 log(severity
, LD_DIR
,
2459 "Old descriptor for %s (published %s) %sin v2 ns, %sin v3 "
2460 "consensus. Last valid until %s; last served at %s.",
2461 id
, published
, in_v2
? "" : "not ", in_v3
? "" : "not ",
2462 last_valid_until
, last_served_at
);
2469 _routerlist_find_elt(smartlist_t
*sl
, void *ri
, int idx
)
2473 SMARTLIST_FOREACH(sl
, routerinfo_t
*, r
,
2479 tor_assert(idx
< smartlist_len(sl
));
2480 tor_assert(smartlist_get(sl
, idx
) == ri
);
2485 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
2486 * as needed. There must be no previous member of <b>rl</b> with the same
2487 * identity digest as <b>ri</b>: If there is, call routerlist_replace
2491 routerlist_insert(routerlist_t
*rl
, routerinfo_t
*ri
)
2493 routerinfo_t
*ri_old
;
2495 /* XXXX Remove if this slows us down. */
2496 routerinfo_t
*ri_generated
= router_get_my_routerinfo();
2497 tor_assert(ri_generated
!= ri
);
2499 tor_assert(ri
->cache_info
.routerlist_index
== -1);
2501 ri_old
= rimap_set(rl
->identity_map
, ri
->cache_info
.identity_digest
, ri
);
2502 tor_assert(!ri_old
);
2503 sdmap_set(rl
->desc_digest_map
, ri
->cache_info
.signed_descriptor_digest
,
2505 if (!tor_digest_is_zero(ri
->cache_info
.extra_info_digest
))
2506 sdmap_set(rl
->desc_by_eid_map
, ri
->cache_info
.extra_info_digest
,
2508 smartlist_add(rl
->routers
, ri
);
2509 ri
->cache_info
.routerlist_index
= smartlist_len(rl
->routers
) - 1;
2510 router_dir_info_changed();
2511 #ifdef DEBUG_ROUTERLIST
2512 routerlist_assert_ok(rl
);
2516 /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
2517 * corresponding router in rl-\>routers or rl-\>old_routers. Return true iff
2518 * we actually inserted <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
2520 extrainfo_insert(routerlist_t
*rl
, extrainfo_t
*ei
)
2523 routerinfo_t
*ri
= rimap_get(rl
->identity_map
,
2524 ei
->cache_info
.identity_digest
);
2525 signed_descriptor_t
*sd
=
2526 sdmap_get(rl
->desc_by_eid_map
, ei
->cache_info
.signed_descriptor_digest
);
2527 extrainfo_t
*ei_tmp
;
2530 /* XXXX remove this code if it slows us down. */
2531 extrainfo_t
*ei_generated
= router_get_my_extrainfo();
2532 tor_assert(ei_generated
!= ei
);
2536 /* This router is unknown; we can't even verify the signature. Give up.*/
2539 if (routerinfo_incompatible_with_extrainfo(ri
, ei
, sd
, NULL
)) {
2543 /* Okay, if we make it here, we definitely have a router corresponding to
2544 * this extrainfo. */
2546 ei_tmp
= eimap_set(rl
->extra_info_map
,
2547 ei
->cache_info
.signed_descriptor_digest
,
2551 rl
->extrainfo_store
.bytes_dropped
+=
2552 ei_tmp
->cache_info
.signed_descriptor_len
;
2553 extrainfo_free(ei_tmp
);
2560 #ifdef DEBUG_ROUTERLIST
2561 routerlist_assert_ok(rl
);
2566 #define should_cache_old_descriptors() \
2567 directory_caches_dir_info(get_options())
2569 /** If we're a directory cache and routerlist <b>rl</b> doesn't have
2570 * a copy of router <b>ri</b> yet, add it to the list of old (not
2571 * recommended but still served) descriptors. Else free it. */
2573 routerlist_insert_old(routerlist_t
*rl
, routerinfo_t
*ri
)
2576 /* XXXX remove this code if it slows us down. */
2577 routerinfo_t
*ri_generated
= router_get_my_routerinfo();
2578 tor_assert(ri_generated
!= ri
);
2580 tor_assert(ri
->cache_info
.routerlist_index
== -1);
2582 if (should_cache_old_descriptors() &&
2583 ri
->purpose
== ROUTER_PURPOSE_GENERAL
&&
2584 !sdmap_get(rl
->desc_digest_map
,
2585 ri
->cache_info
.signed_descriptor_digest
)) {
2586 signed_descriptor_t
*sd
= signed_descriptor_from_routerinfo(ri
);
2587 sdmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
2588 smartlist_add(rl
->old_routers
, sd
);
2589 sd
->routerlist_index
= smartlist_len(rl
->old_routers
)-1;
2590 if (!tor_digest_is_zero(sd
->extra_info_digest
))
2591 sdmap_set(rl
->desc_by_eid_map
, sd
->extra_info_digest
, sd
);
2593 routerinfo_free(ri
);
2595 #ifdef DEBUG_ROUTERLIST
2596 routerlist_assert_ok(rl
);
2600 /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
2601 * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl->routers,
2602 * idx) == ri, we don't need to do a linear search over the list to decide
2603 * which to remove. We fill the gap in rl->routers with a later element in
2604 * the list, if any exists. <b>ri</b> is freed.
2606 * If <b>make_old</b> is true, instead of deleting the router, we try adding
2607 * it to rl->old_routers. */
2609 routerlist_remove(routerlist_t
*rl
, routerinfo_t
*ri
, int make_old
)
2611 routerinfo_t
*ri_tmp
;
2612 extrainfo_t
*ei_tmp
;
2613 int idx
= ri
->cache_info
.routerlist_index
;
2614 tor_assert(0 <= idx
&& idx
< smartlist_len(rl
->routers
));
2615 tor_assert(smartlist_get(rl
->routers
, idx
) == ri
);
2617 ri
->cache_info
.routerlist_index
= -1;
2618 smartlist_del(rl
->routers
, idx
);
2619 if (idx
< smartlist_len(rl
->routers
)) {
2620 routerinfo_t
*r
= smartlist_get(rl
->routers
, idx
);
2621 r
->cache_info
.routerlist_index
= idx
;
2624 ri_tmp
= rimap_remove(rl
->identity_map
, ri
->cache_info
.identity_digest
);
2625 router_dir_info_changed();
2626 tor_assert(ri_tmp
== ri
);
2628 if (make_old
&& should_cache_old_descriptors() &&
2629 ri
->purpose
== ROUTER_PURPOSE_GENERAL
) {
2630 signed_descriptor_t
*sd
;
2631 sd
= signed_descriptor_from_routerinfo(ri
);
2632 smartlist_add(rl
->old_routers
, sd
);
2633 sd
->routerlist_index
= smartlist_len(rl
->old_routers
)-1;
2634 sdmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
2635 if (!tor_digest_is_zero(sd
->extra_info_digest
))
2636 sdmap_set(rl
->desc_by_eid_map
, sd
->extra_info_digest
, sd
);
2638 signed_descriptor_t
*sd_tmp
;
2639 sd_tmp
= sdmap_remove(rl
->desc_digest_map
,
2640 ri
->cache_info
.signed_descriptor_digest
);
2641 tor_assert(sd_tmp
== &(ri
->cache_info
));
2642 rl
->desc_store
.bytes_dropped
+= ri
->cache_info
.signed_descriptor_len
;
2643 ei_tmp
= eimap_remove(rl
->extra_info_map
,
2644 ri
->cache_info
.extra_info_digest
);
2646 rl
->extrainfo_store
.bytes_dropped
+=
2647 ei_tmp
->cache_info
.signed_descriptor_len
;
2648 extrainfo_free(ei_tmp
);
2650 if (!tor_digest_is_zero(ri
->cache_info
.extra_info_digest
))
2651 sdmap_remove(rl
->desc_by_eid_map
, ri
->cache_info
.extra_info_digest
);
2652 routerinfo_free(ri
);
2654 #ifdef DEBUG_ROUTERLIST
2655 routerlist_assert_ok(rl
);
2659 /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
2660 * adjust <b>rl</b> as appropriate. <b>idx</b> is -1, or the index of
2663 routerlist_remove_old(routerlist_t
*rl
, signed_descriptor_t
*sd
, int idx
)
2665 signed_descriptor_t
*sd_tmp
;
2666 extrainfo_t
*ei_tmp
;
2667 desc_store_t
*store
;
2669 idx
= sd
->routerlist_index
;
2671 tor_assert(0 <= idx
&& idx
< smartlist_len(rl
->old_routers
));
2672 /* XXXX edmanm's bridge relay triggered the following assert while
2673 * running 0.2.0.12-alpha. If anybody triggers this again, see if we
2674 * can get a backtrace. */
2675 tor_assert(smartlist_get(rl
->old_routers
, idx
) == sd
);
2676 tor_assert(idx
== sd
->routerlist_index
);
2678 sd
->routerlist_index
= -1;
2679 smartlist_del(rl
->old_routers
, idx
);
2680 if (idx
< smartlist_len(rl
->old_routers
)) {
2681 signed_descriptor_t
*d
= smartlist_get(rl
->old_routers
, idx
);
2682 d
->routerlist_index
= idx
;
2684 sd_tmp
= sdmap_remove(rl
->desc_digest_map
,
2685 sd
->signed_descriptor_digest
);
2686 tor_assert(sd_tmp
== sd
);
2687 store
= desc_get_store(rl
, sd
);
2689 store
->bytes_dropped
+= sd
->signed_descriptor_len
;
2691 ei_tmp
= eimap_remove(rl
->extra_info_map
,
2692 sd
->extra_info_digest
);
2694 rl
->extrainfo_store
.bytes_dropped
+=
2695 ei_tmp
->cache_info
.signed_descriptor_len
;
2696 extrainfo_free(ei_tmp
);
2698 if (!tor_digest_is_zero(sd
->extra_info_digest
))
2699 sdmap_remove(rl
->desc_by_eid_map
, sd
->extra_info_digest
);
2701 signed_descriptor_free(sd
);
2702 #ifdef DEBUG_ROUTERLIST
2703 routerlist_assert_ok(rl
);
2707 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
2708 * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
2709 * smartlist_get(rl->routers, idx) == ri, we don't need to do a linear
2710 * search over the list to decide which to remove. We put ri_new in the same
2711 * index as ri_old, if possible. ri is freed as appropriate.
2713 * If should_cache_descriptors() is true, instead of deleting the router,
2714 * we add it to rl->old_routers. */
2716 routerlist_replace(routerlist_t
*rl
, routerinfo_t
*ri_old
,
2717 routerinfo_t
*ri_new
)
2721 routerinfo_t
*ri_tmp
;
2722 extrainfo_t
*ei_tmp
;
2724 /* XXXX Remove this if it turns out to slow us down. */
2725 routerinfo_t
*ri_generated
= router_get_my_routerinfo();
2726 tor_assert(ri_generated
!= ri_new
);
2728 tor_assert(ri_old
!= ri_new
);
2729 tor_assert(ri_new
->cache_info
.routerlist_index
== -1);
2731 idx
= ri_old
->cache_info
.routerlist_index
;
2732 tor_assert(0 <= idx
&& idx
< smartlist_len(rl
->routers
));
2733 tor_assert(smartlist_get(rl
->routers
, idx
) == ri_old
);
2735 router_dir_info_changed();
2737 smartlist_set(rl
->routers
, idx
, ri_new
);
2738 ri_old
->cache_info
.routerlist_index
= -1;
2739 ri_new
->cache_info
.routerlist_index
= idx
;
2740 /* Check that ri_old is not in rl->routers anymore: */
2741 tor_assert( _routerlist_find_elt(rl
->routers
, ri_old
, -1) == -1 );
2743 log_warn(LD_BUG
, "Appending entry from routerlist_replace.");
2744 routerlist_insert(rl
, ri_new
);
2747 if (memcmp(ri_old
->cache_info
.identity_digest
,
2748 ri_new
->cache_info
.identity_digest
, DIGEST_LEN
)) {
2749 /* digests don't match; digestmap_set won't replace */
2750 rimap_remove(rl
->identity_map
, ri_old
->cache_info
.identity_digest
);
2752 ri_tmp
= rimap_set(rl
->identity_map
,
2753 ri_new
->cache_info
.identity_digest
, ri_new
);
2754 tor_assert(!ri_tmp
|| ri_tmp
== ri_old
);
2755 sdmap_set(rl
->desc_digest_map
,
2756 ri_new
->cache_info
.signed_descriptor_digest
,
2757 &(ri_new
->cache_info
));
2759 if (!tor_digest_is_zero(ri_new
->cache_info
.extra_info_digest
)) {
2760 sdmap_set(rl
->desc_by_eid_map
, ri_new
->cache_info
.extra_info_digest
,
2761 &ri_new
->cache_info
);
2764 if (should_cache_old_descriptors() &&
2765 ri_old
->purpose
== ROUTER_PURPOSE_GENERAL
) {
2766 signed_descriptor_t
*sd
= signed_descriptor_from_routerinfo(ri_old
);
2767 smartlist_add(rl
->old_routers
, sd
);
2768 sd
->routerlist_index
= smartlist_len(rl
->old_routers
)-1;
2769 sdmap_set(rl
->desc_digest_map
, sd
->signed_descriptor_digest
, sd
);
2770 if (!tor_digest_is_zero(sd
->extra_info_digest
))
2771 sdmap_set(rl
->desc_by_eid_map
, sd
->extra_info_digest
, sd
);
2773 if (memcmp(ri_old
->cache_info
.signed_descriptor_digest
,
2774 ri_new
->cache_info
.signed_descriptor_digest
,
2776 /* digests don't match; digestmap_set didn't replace */
2777 sdmap_remove(rl
->desc_digest_map
,
2778 ri_old
->cache_info
.signed_descriptor_digest
);
2781 ei_tmp
= eimap_remove(rl
->extra_info_map
,
2782 ri_old
->cache_info
.extra_info_digest
);
2784 rl
->extrainfo_store
.bytes_dropped
+=
2785 ei_tmp
->cache_info
.signed_descriptor_len
;
2786 extrainfo_free(ei_tmp
);
2788 if (!tor_digest_is_zero(ri_old
->cache_info
.extra_info_digest
)) {
2789 sdmap_remove(rl
->desc_by_eid_map
,
2790 ri_old
->cache_info
.extra_info_digest
);
2792 rl
->desc_store
.bytes_dropped
+= ri_old
->cache_info
.signed_descriptor_len
;
2793 routerinfo_free(ri_old
);
2795 #ifdef DEBUG_ROUTERLIST
2796 routerlist_assert_ok(rl
);
2800 /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
2801 * it as a fresh routerinfo_t. */
2802 static routerinfo_t
*
2803 routerlist_reparse_old(routerlist_t
*rl
, signed_descriptor_t
*sd
)
2808 body
= signed_descriptor_get_annotations(sd
);
2810 ri
= router_parse_entry_from_string(body
,
2811 body
+sd
->signed_descriptor_len
+sd
->annotations_len
,
2815 memcpy(&ri
->cache_info
, sd
, sizeof(signed_descriptor_t
));
2816 sd
->signed_descriptor_body
= NULL
; /* Steal reference. */
2817 ri
->cache_info
.routerlist_index
= -1;
2819 routerlist_remove_old(rl
, sd
, -1);
2824 /** Free all memory held by the routerlist module. */
2826 routerlist_free_all(void)
2829 routerlist_free(routerlist
);
2831 if (warned_nicknames
) {
2832 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
2833 smartlist_free(warned_nicknames
);
2834 warned_nicknames
= NULL
;
2836 if (trusted_dir_servers
) {
2837 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ds
,
2838 trusted_dir_server_free(ds
));
2839 smartlist_free(trusted_dir_servers
);
2840 trusted_dir_servers
= NULL
;
2842 if (trusted_dir_certs
) {
2843 DIGESTMAP_FOREACH(trusted_dir_certs
, key
, cert_list_t
*, cl
) {
2844 SMARTLIST_FOREACH(cl
->certs
, authority_cert_t
*, cert
,
2845 authority_cert_free(cert
));
2846 smartlist_free(cl
->certs
);
2848 } DIGESTMAP_FOREACH_END
;
2849 digestmap_free(trusted_dir_certs
, NULL
);
2850 trusted_dir_certs
= NULL
;
2854 /** Forget that we have issued any router-related warnings, so that we'll
2855 * warn again if we see the same errors. */
2857 routerlist_reset_warnings(void)
2859 if (!warned_nicknames
)
2860 warned_nicknames
= smartlist_create();
2861 SMARTLIST_FOREACH(warned_nicknames
, char *, cp
, tor_free(cp
));
2862 smartlist_clear(warned_nicknames
); /* now the list is empty. */
2864 networkstatus_reset_warnings();
2867 /** Mark the router with ID <b>digest</b> as running or non-running
2868 * in our routerlist. */
2870 router_set_status(const char *digest
, int up
)
2872 routerinfo_t
*router
;
2873 routerstatus_t
*status
;
2876 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, d
,
2877 if (!memcmp(d
->digest
, digest
, DIGEST_LEN
))
2878 d
->is_running
= up
);
2880 router
= router_get_by_digest(digest
);
2882 log_debug(LD_DIR
,"Marking router '%s/%s' as %s.",
2883 router
->nickname
, router
->address
, up
? "up" : "down");
2884 if (!up
&& router_is_me(router
) && !we_are_hibernating())
2885 log_warn(LD_NET
, "We just marked ourself as down. Are your external "
2886 "addresses reachable?");
2887 router
->is_running
= up
;
2889 status
= router_get_consensus_status_by_id(digest
);
2890 if (status
&& status
->is_running
!= up
) {
2891 status
->is_running
= up
;
2892 control_event_networkstatus_changed_single(status
);
2894 router_dir_info_changed();
2897 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
2898 * older entries (if any) with the same key. Note: Callers should not hold
2899 * their pointers to <b>router</b> if this function fails; <b>router</b>
2900 * will either be inserted into the routerlist or freed. Similarly, even
2901 * if this call succeeds, they should not hold their pointers to
2902 * <b>router</b> after subsequent calls with other routerinfo's -- they
2903 * might cause the original routerinfo to get freed.
2905 * Returns >= 0 if the router was added; less than 0 if it was not.
2907 * If we're returning non-zero, then assign to *<b>msg</b> a static string
2908 * describing the reason for not liking the routerinfo.
2910 * If the return value is less than -1, there was a problem with the
2911 * routerinfo. If the return value is equal to -1, then the routerinfo was
2912 * fine, but out-of-date. If the return value is equal to 1, the
2913 * routerinfo was accepted, but we should notify the generator of the
2914 * descriptor using the message *<b>msg</b>.
2916 * If <b>from_cache</b>, this descriptor came from our disk cache. If
2917 * <b>from_fetch</b>, we received it in response to a request we made.
2918 * (If both are false, that means it was uploaded to us as an auth dir
2919 * server or via the controller.)
2921 * This function should be called *after*
2922 * routers_update_status_from_consensus_networkstatus; subsequently, you
2923 * should call router_rebuild_store and routerlist_descriptors_added.
2926 router_add_to_routerlist(routerinfo_t
*router
, const char **msg
,
2927 int from_cache
, int from_fetch
)
2929 const char *id_digest
;
2930 int authdir
= authdir_mode_handles_descs(get_options(), router
->purpose
);
2931 int authdir_believes_valid
= 0;
2932 routerinfo_t
*old_router
;
2933 networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
2934 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
2935 int in_consensus
= 0;
2940 router_get_routerlist();
2942 id_digest
= router
->cache_info
.identity_digest
;
2944 /* Make sure that we haven't already got this exact descriptor. */
2945 if (sdmap_get(routerlist
->desc_digest_map
,
2946 router
->cache_info
.signed_descriptor_digest
)) {
2948 "Dropping descriptor that we already have for router '%s'",
2950 *msg
= "Router descriptor was not new.";
2951 routerinfo_free(router
);
2952 return ROUTER_WAS_NOT_NEW
;
2956 if (authdir_wants_to_reject_router(router
, msg
,
2957 !from_cache
&& !from_fetch
)) {
2959 routerinfo_free(router
);
2960 return ROUTER_AUTHDIR_REJECTS
;
2962 authdir_believes_valid
= router
->is_valid
;
2963 } else if (from_fetch
) {
2964 /* Only check the descriptor digest against the network statuses when
2965 * we are receiving in response to a fetch. */
2967 if (!signed_desc_digest_is_recognized(&router
->cache_info
) &&
2968 !routerinfo_is_a_configured_bridge(router
)) {
2969 /* We asked for it, so some networkstatus must have listed it when we
2970 * did. Save it if we're a cache in case somebody else asks for it. */
2972 "Received a no-longer-recognized descriptor for router '%s'",
2974 *msg
= "Router descriptor is not referenced by any network-status.";
2976 /* Only journal this desc if we'll be serving it. */
2977 if (!from_cache
&& should_cache_old_descriptors())
2978 signed_desc_append_to_journal(&router
->cache_info
,
2979 &routerlist
->desc_store
);
2980 routerlist_insert_old(routerlist
, router
);
2981 return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS
;
2985 /* We no longer need a router with this descriptor digest. */
2986 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
2988 routerstatus_t
*rs
=
2989 networkstatus_v2_find_entry(ns
, router
->cache_info
.identity_digest
);
2990 if (rs
&& !memcmp(rs
->descriptor_digest
,
2991 router
->cache_info
.signed_descriptor_digest
,
2993 rs
->need_to_mirror
= 0;
2996 routerstatus_t
*rs
= networkstatus_vote_find_entry(consensus
,
2997 router
->cache_info
.identity_digest
);
2998 if (rs
&& !memcmp(rs
->descriptor_digest
,
2999 router
->cache_info
.signed_descriptor_digest
,
3002 rs
->need_to_mirror
= 0;
3006 if (router
->purpose
== ROUTER_PURPOSE_GENERAL
&&
3007 consensus
&& !in_consensus
&& !authdir
) {
3008 /* If it's a general router not listed in the consensus, then don't
3009 * consider replacing the latest router with it. */
3010 if (!from_cache
&& should_cache_old_descriptors())
3011 signed_desc_append_to_journal(&router
->cache_info
,
3012 &routerlist
->desc_store
);
3013 routerlist_insert_old(routerlist
, router
);
3014 *msg
= "Skipping router descriptor: not in consensus.";
3015 return ROUTER_NOT_IN_CONSENSUS
;
3018 /* If we have a router with the same identity key, choose the newer one. */
3019 old_router
= rimap_get(routerlist
->identity_map
,
3020 router
->cache_info
.identity_digest
);
3022 if (!in_consensus
&& (router
->cache_info
.published_on
<=
3023 old_router
->cache_info
.published_on
)) {
3024 /* Same key, but old. This one is not listed in the consensus. */
3025 log_debug(LD_DIR
, "Skipping not-new descriptor for router '%s'",
3027 /* Only journal this desc if we'll be serving it. */
3028 if (!from_cache
&& should_cache_old_descriptors())
3029 signed_desc_append_to_journal(&router
->cache_info
,
3030 &routerlist
->desc_store
);
3031 routerlist_insert_old(routerlist
, router
);
3032 *msg
= "Router descriptor was not new.";
3033 return ROUTER_WAS_NOT_NEW
;
3035 /* Same key, and either new, or listed in the consensus. */
3036 log_debug(LD_DIR
, "Replacing entry for router '%s/%s' [%s]",
3037 router
->nickname
, old_router
->nickname
,
3038 hex_str(id_digest
,DIGEST_LEN
));
3039 if (router
->addr
== old_router
->addr
&&
3040 router
->or_port
== old_router
->or_port
) {
3041 /* these carry over when the address and orport are unchanged. */
3042 router
->last_reachable
= old_router
->last_reachable
;
3043 router
->testing_since
= old_router
->testing_since
;
3045 routerlist_replace(routerlist
, old_router
, router
);
3047 signed_desc_append_to_journal(&router
->cache_info
,
3048 &routerlist
->desc_store
);
3050 directory_set_dirty();
3051 *msg
= authdir_believes_valid
? "Valid server updated" :
3052 ("Invalid server updated. (This dirserver is marking your "
3053 "server as unapproved.)");
3054 return ROUTER_ADDED_SUCCESSFULLY
;
3058 /* We haven't seen a router with this identity before. Add it to the end of
3060 routerlist_insert(routerlist
, router
);
3062 signed_desc_append_to_journal(&router
->cache_info
,
3063 &routerlist
->desc_store
);
3064 directory_set_dirty();
3065 return ROUTER_ADDED_SUCCESSFULLY
;
3068 /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
3069 * as for router_add_to_routerlist(). Return true iff we actually inserted
3073 router_add_extrainfo_to_routerlist(extrainfo_t
*ei
, const char **msg
,
3074 int from_cache
, int from_fetch
)
3078 if (msg
) *msg
= NULL
;
3079 /*XXXX021 Do something with msg */
3081 inserted
= extrainfo_insert(router_get_routerlist(), ei
);
3083 if (inserted
&& !from_cache
)
3084 signed_desc_append_to_journal(&ei
->cache_info
,
3085 &routerlist
->extrainfo_store
);
3088 return ROUTER_ADDED_SUCCESSFULLY
;
3090 return ROUTER_BAD_EI
;
3093 /** Sorting helper: return <0, 0, or >0 depending on whether the
3094 * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
3095 * to, or later than that of *<b>b</b>. */
3097 _compare_old_routers_by_identity(const void **_a
, const void **_b
)
3100 const signed_descriptor_t
*r1
= *_a
, *r2
= *_b
;
3101 if ((i
= memcmp(r1
->identity_digest
, r2
->identity_digest
, DIGEST_LEN
)))
3103 return (int)(r1
->published_on
- r2
->published_on
);
3106 /** Internal type used to represent how long an old descriptor was valid,
3107 * where it appeared in the list of old descriptors, and whether it's extra
3108 * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
3109 struct duration_idx_t
{
3115 /** Sorting helper: compare two duration_idx_t by their duration. */
3117 _compare_duration_idx(const void *_d1
, const void *_d2
)
3119 const struct duration_idx_t
*d1
= _d1
;
3120 const struct duration_idx_t
*d2
= _d2
;
3121 return d1
->duration
- d2
->duration
;
3124 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
3125 * must contain routerinfo_t with the same identity and with publication time
3126 * in ascending order. Remove members from this range until there are no more
3127 * than max_descriptors_per_router() remaining. Start by removing the oldest
3128 * members from before <b>cutoff</b>, then remove members which were current
3129 * for the lowest amount of time. The order of members of old_routers at
3130 * indices <b>lo</b> or higher may be changed.
3133 routerlist_remove_old_cached_routers_with_id(time_t now
,
3134 time_t cutoff
, int lo
, int hi
,
3135 digestset_t
*retain
)
3138 unsigned n_extra
, n_rmv
= 0;
3139 struct duration_idx_t
*lifespans
;
3140 uint8_t *rmv
, *must_keep
;
3141 smartlist_t
*lst
= routerlist
->old_routers
;
3144 tor_assert(hi
< smartlist_len(lst
));
3145 tor_assert(lo
<= hi
);
3146 ident
= ((signed_descriptor_t
*)smartlist_get(lst
, lo
))->identity_digest
;
3147 for (i
= lo
+1; i
<= hi
; ++i
) {
3148 signed_descriptor_t
*r
= smartlist_get(lst
, i
);
3149 tor_assert(!memcmp(ident
, r
->identity_digest
, DIGEST_LEN
));
3152 /* Check whether we need to do anything at all. */
3154 int mdpr
= directory_caches_dir_info(get_options()) ? 2 : 1;
3160 lifespans
= tor_malloc_zero(sizeof(struct duration_idx_t
)*n
);
3161 rmv
= tor_malloc_zero(sizeof(uint8_t)*n
);
3162 must_keep
= tor_malloc_zero(sizeof(uint8_t)*n
);
3163 /* Set lifespans to contain the lifespan and index of each server. */
3164 /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
3165 for (i
= lo
; i
<= hi
; ++i
) {
3166 signed_descriptor_t
*r
= smartlist_get(lst
, i
);
3167 signed_descriptor_t
*r_next
;
3168 lifespans
[i
-lo
].idx
= i
;
3169 if (r
->last_listed_as_valid_until
>= now
||
3170 (retain
&& digestset_isin(retain
, r
->signed_descriptor_digest
))) {
3171 must_keep
[i
-lo
] = 1;
3174 r_next
= smartlist_get(lst
, i
+1);
3175 tor_assert(r
->published_on
<= r_next
->published_on
);
3176 lifespans
[i
-lo
].duration
= (int)(r_next
->published_on
- r
->published_on
);
3179 lifespans
[i
-lo
].duration
= INT_MAX
;
3181 if (!must_keep
[i
-lo
] && r
->published_on
< cutoff
&& n_rmv
< n_extra
) {
3183 lifespans
[i
-lo
].old
= 1;
3188 if (n_rmv
< n_extra
) {
3190 * We aren't removing enough servers for being old. Sort lifespans by
3191 * the duration of liveness, and remove the ones we're not already going to
3192 * remove based on how long they were alive.
3194 qsort(lifespans
, n
, sizeof(struct duration_idx_t
), _compare_duration_idx
);
3195 for (i
= 0; i
< n
&& n_rmv
< n_extra
; ++i
) {
3196 if (!must_keep
[lifespans
[i
].idx
-lo
] && !lifespans
[i
].old
) {
3197 rmv
[lifespans
[i
].idx
-lo
] = 1;
3206 routerlist_remove_old(routerlist
, smartlist_get(lst
, i
), i
);
3207 } while (--i
>= lo
);
3208 tor_free(must_keep
);
3210 tor_free(lifespans
);
3213 /** Deactivate any routers from the routerlist that are more than
3214 * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
3215 * remove old routers from the list of cached routers if we have too many.
3218 routerlist_remove_old_routers(void)
3221 const char *cur_id
= NULL
;
3222 time_t now
= time(NULL
);
3224 routerinfo_t
*router
;
3225 signed_descriptor_t
*sd
;
3226 digestset_t
*retain
;
3227 int caches
= directory_caches_dir_info(get_options());
3228 const networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
3229 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
3230 int n_expected_retain
= 0;
3232 trusted_dirs_remove_old_certs();
3234 if (!routerlist
|| !consensus
)
3237 // routerlist_assert_ok(routerlist);
3239 n_expected_retain
= smartlist_len(consensus
->routerstatus_list
);
3241 networkstatus_v2_list
&& smartlist_len(networkstatus_v2_list
)) {
3242 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
3243 n_expected_retain
+= smartlist_len(ns
->entries
));
3244 /* DOCDOC XXX021 too much magic. */
3245 n_expected_retain
/= (smartlist_len(networkstatus_v2_list
)/2+1);
3247 //log_notice(LD_DIR,"n_expected_retain=%d",n_expected_retain);
3249 retain
= digestset_new(n_expected_retain
);
3251 cutoff
= now
- OLD_ROUTER_DESC_MAX_AGE
;
3252 /* Build a list of all the descriptors that _anybody_ lists. */
3254 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
3256 /* XXXX The inner loop here gets pretty expensive, and actually shows up
3257 * on some profiles. It may be the reason digestmap_set shows up in
3258 * profiles too. If instead we kept a per-descriptor digest count of
3259 * how many networkstatuses recommended each descriptor, and changed
3260 * that only when the networkstatuses changed, that would be a speed
3261 * improvement, possibly 1-4% if it also removes digestmap_set from the
3262 * profile. Not worth it for 0.1.2.x, though. The new directory
3263 * system will obsolete this whole thing in 0.2.0.x. */
3264 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
*, rs
,
3265 if (rs
->published_on
>= cutoff
)
3266 digestset_add(retain
, rs
->descriptor_digest
));
3270 /* Retain anything listed in the consensus. */
3272 SMARTLIST_FOREACH(consensus
->routerstatus_list
, routerstatus_t
*, rs
,
3273 if (rs
->published_on
>= cutoff
)
3274 digestset_add(retain
, rs
->descriptor_digest
));
3277 /* If we have nearly as many networkstatuses as we want, we should consider
3278 * pruning current routers that are too old and that nobody recommends. (If
3279 * we don't have enough networkstatuses, then we should get more before we
3280 * decide to kill routers.) */
3281 /* XXX021 we don't check if we have a v3 consensus, do we? should we? -RD */
3283 smartlist_len(networkstatus_v2_list
) > get_n_v2_authorities() / 2) {
3284 cutoff
= now
- ROUTER_MAX_AGE
;
3285 /* Remove too-old unrecommended members of routerlist->routers. */
3286 for (i
= 0; i
< smartlist_len(routerlist
->routers
); ++i
) {
3287 router
= smartlist_get(routerlist
->routers
, i
);
3288 if (router
->cache_info
.published_on
<= cutoff
&&
3289 router
->cache_info
.last_listed_as_valid_until
< now
&&
3290 !digestset_isin(retain
,
3291 router
->cache_info
.signed_descriptor_digest
)) {
3292 /* Too old: remove it. (If we're a cache, just move it into
3295 "Forgetting obsolete (too old) routerinfo for router '%s'",
3297 routerlist_remove(routerlist
, router
, 1);
3303 //routerlist_assert_ok(routerlist);
3305 /* Remove far-too-old members of routerlist->old_routers. */
3306 cutoff
= now
- OLD_ROUTER_DESC_MAX_AGE
;
3307 for (i
= 0; i
< smartlist_len(routerlist
->old_routers
); ++i
) {
3308 sd
= smartlist_get(routerlist
->old_routers
, i
);
3309 if (sd
->published_on
<= cutoff
&&
3310 sd
->last_listed_as_valid_until
< now
&&
3311 !digestset_isin(retain
, sd
->signed_descriptor_digest
)) {
3312 /* Too old. Remove it. */
3313 routerlist_remove_old(routerlist
, sd
, i
--);
3317 //routerlist_assert_ok(routerlist);
3319 log_info(LD_DIR
, "We have %d live routers and %d old router descriptors.",
3320 smartlist_len(routerlist
->routers
),
3321 smartlist_len(routerlist
->old_routers
));
3323 /* Now we might have to look at routerlist->old_routers for extraneous
3324 * members. (We'd keep all the members if we could, but we need to save
3325 * space.) First, check whether we have too many router descriptors, total.
3326 * We're okay with having too many for some given router, so long as the
3327 * total number doesn't approach max_descriptors_per_router()*len(router).
3329 if (smartlist_len(routerlist
->old_routers
) <
3330 smartlist_len(routerlist
->routers
))
3333 /* Sort by identity, then fix indices. */
3334 smartlist_sort(routerlist
->old_routers
, _compare_old_routers_by_identity
);
3336 for (i
= 0; i
< smartlist_len(routerlist
->old_routers
); ++i
) {
3337 signed_descriptor_t
*r
= smartlist_get(routerlist
->old_routers
, i
);
3338 r
->routerlist_index
= i
;
3341 /* Iterate through the list from back to front, so when we remove descriptors
3342 * we don't mess up groups we haven't gotten to. */
3343 for (i
= smartlist_len(routerlist
->old_routers
)-1; i
>= 0; --i
) {
3344 signed_descriptor_t
*r
= smartlist_get(routerlist
->old_routers
, i
);
3346 cur_id
= r
->identity_digest
;
3349 if (memcmp(cur_id
, r
->identity_digest
, DIGEST_LEN
)) {
3350 routerlist_remove_old_cached_routers_with_id(now
,
3351 cutoff
, i
+1, hi
, retain
);
3352 cur_id
= r
->identity_digest
;
3357 routerlist_remove_old_cached_routers_with_id(now
, cutoff
, 0, hi
, retain
);
3358 //routerlist_assert_ok(routerlist);
3361 digestset_free(retain
);
3362 router_rebuild_store(RRS_DONT_REMOVE_OLD
, &routerlist
->desc_store
);
3363 router_rebuild_store(RRS_DONT_REMOVE_OLD
,&routerlist
->extrainfo_store
);
3366 /** We just added a new set of descriptors. Take whatever extra steps
3369 routerlist_descriptors_added(smartlist_t
*sl
, int from_cache
)
3372 control_event_descriptors_changed(sl
);
3373 SMARTLIST_FOREACH(sl
, routerinfo_t
*, ri
,
3374 if (ri
->purpose
== ROUTER_PURPOSE_BRIDGE
)
3375 learned_bridge_descriptor(ri
, from_cache
);
3380 * Code to parse a single router descriptor and insert it into the
3381 * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
3382 * descriptor was well-formed but could not be added; and 1 if the
3383 * descriptor was added.
3385 * If we don't add it and <b>msg</b> is not NULL, then assign to
3386 * *<b>msg</b> a static string describing the reason for refusing the
3389 * This is used only by the controller.
3392 router_load_single_router(const char *s
, uint8_t purpose
, int cache
,
3396 was_router_added_t r
;
3398 char annotation_buf
[ROUTER_ANNOTATION_BUF_LEN
];
3402 tor_snprintf(annotation_buf
, sizeof(annotation_buf
),
3403 "@source controller\n"
3404 "@purpose %s\n", router_purpose_to_string(purpose
));
3406 if (!(ri
= router_parse_entry_from_string(s
, NULL
, 1, 0, annotation_buf
))) {
3407 log_warn(LD_DIR
, "Error parsing router descriptor; dropping.");
3408 *msg
= "Couldn't parse router descriptor.";
3411 tor_assert(ri
->purpose
== purpose
);
3412 if (router_is_me(ri
)) {
3413 log_warn(LD_DIR
, "Router's identity key matches mine; dropping.");
3414 *msg
= "Router's identity key matches mine.";
3415 routerinfo_free(ri
);
3419 if (!cache
) /* obey the preference of the controller */
3420 ri
->cache_info
.do_not_cache
= 1;
3422 lst
= smartlist_create();
3423 smartlist_add(lst
, ri
);
3424 routers_update_status_from_consensus_networkstatus(lst
, 0);
3426 r
= router_add_to_routerlist(ri
, msg
, 0, 0);
3427 if (!WRA_WAS_ADDED(r
)) {
3428 /* we've already assigned to *msg now, and ri is already freed */
3430 if (r
== ROUTER_AUTHDIR_REJECTS
)
3431 log_warn(LD_DIR
, "Couldn't add router to list: %s Dropping.", *msg
);
3432 smartlist_free(lst
);
3435 routerlist_descriptors_added(lst
, 0);
3436 smartlist_free(lst
);
3437 log_debug(LD_DIR
, "Added router to list");
3442 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
3443 * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
3444 * are in response to a query to the network: cache them by adding them to
3447 * If <b>requested_fingerprints</b> is provided, it must contain a list of
3448 * uppercased fingerprints. Do not update any router whose
3449 * fingerprint is not on the list; after updating a router, remove its
3450 * fingerprint from the list.
3452 * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
3453 * are descriptor digests. Otherwise they are identity digests.
3456 router_load_routers_from_string(const char *s
, const char *eos
,
3457 saved_location_t saved_location
,
3458 smartlist_t
*requested_fingerprints
,
3459 int descriptor_digests
,
3460 const char *prepend_annotations
)
3462 smartlist_t
*routers
= smartlist_create(), *changed
= smartlist_create();
3463 char fp
[HEX_DIGEST_LEN
+1];
3465 int from_cache
= (saved_location
!= SAVED_NOWHERE
);
3466 int allow_annotations
= (saved_location
!= SAVED_NOWHERE
);
3467 int any_changed
= 0;
3469 router_parse_list_from_string(&s
, eos
, routers
, saved_location
, 0,
3470 allow_annotations
, prepend_annotations
);
3472 routers_update_status_from_consensus_networkstatus(routers
, !from_cache
);
3474 log_info(LD_DIR
, "%d elements to add", smartlist_len(routers
));
3476 SMARTLIST_FOREACH_BEGIN(routers
, routerinfo_t
*, ri
) {
3477 was_router_added_t r
;
3478 if (requested_fingerprints
) {
3479 base16_encode(fp
, sizeof(fp
), descriptor_digests
?
3480 ri
->cache_info
.signed_descriptor_digest
:
3481 ri
->cache_info
.identity_digest
,
3483 if (smartlist_string_isin(requested_fingerprints
, fp
)) {
3484 smartlist_string_remove(requested_fingerprints
, fp
);
3487 smartlist_join_strings(requested_fingerprints
," ",0,NULL
);
3489 "We received a router descriptor with a fingerprint (%s) "
3490 "that we never requested. (We asked for: %s.) Dropping.",
3492 tor_free(requested
);
3493 routerinfo_free(ri
);
3498 r
= router_add_to_routerlist(ri
, &msg
, from_cache
, !from_cache
);
3499 if (WRA_WAS_ADDED(r
)) {
3501 smartlist_add(changed
, ri
);
3502 routerlist_descriptors_added(changed
, from_cache
);
3503 smartlist_clear(changed
);
3505 } SMARTLIST_FOREACH_END(ri
);
3507 routerlist_assert_ok(routerlist
);
3510 router_rebuild_store(0, &routerlist
->desc_store
);
3512 smartlist_free(routers
);
3513 smartlist_free(changed
);
3516 /** Parse one or more extrainfos from <b>s</b> (ending immediately before
3517 * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
3518 * router_load_routers_from_string(). */
3520 router_load_extrainfo_from_string(const char *s
, const char *eos
,
3521 saved_location_t saved_location
,
3522 smartlist_t
*requested_fingerprints
,
3523 int descriptor_digests
)
3525 smartlist_t
*extrainfo_list
= smartlist_create();
3527 int from_cache
= (saved_location
!= SAVED_NOWHERE
);
3529 router_parse_list_from_string(&s
, eos
, extrainfo_list
, saved_location
, 1, 0,
3532 log_info(LD_DIR
, "%d elements to add", smartlist_len(extrainfo_list
));
3534 SMARTLIST_FOREACH(extrainfo_list
, extrainfo_t
*, ei
, {
3535 was_router_added_t added
=
3536 router_add_extrainfo_to_routerlist(ei
, &msg
, from_cache
, !from_cache
);
3537 if (WRA_WAS_ADDED(added
) && requested_fingerprints
) {
3538 char fp
[HEX_DIGEST_LEN
+1];
3539 base16_encode(fp
, sizeof(fp
), descriptor_digests
?
3540 ei
->cache_info
.signed_descriptor_digest
:
3541 ei
->cache_info
.identity_digest
,
3543 smartlist_string_remove(requested_fingerprints
, fp
);
3544 /* We silently let people stuff us with extrainfos we didn't ask for,
3545 * so long as we would have wanted them anyway. Since we always fetch
3546 * all the extrainfos we want, and we never actually act on them
3547 * inside Tor, this should be harmless. */
3551 routerlist_assert_ok(routerlist
);
3552 router_rebuild_store(0, &router_get_routerlist()->extrainfo_store
);
3554 smartlist_free(extrainfo_list
);
3557 /** Return true iff any networkstatus includes a descriptor whose digest
3558 * is that of <b>desc</b>. */
3560 signed_desc_digest_is_recognized(signed_descriptor_t
*desc
)
3563 networkstatus_t
*consensus
= networkstatus_get_latest_consensus();
3564 int caches
= directory_caches_dir_info(get_options());
3565 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
3568 rs
= networkstatus_vote_find_entry(consensus
, desc
->identity_digest
);
3569 if (rs
&& !memcmp(rs
->descriptor_digest
,
3570 desc
->signed_descriptor_digest
, DIGEST_LEN
))
3573 if (caches
&& networkstatus_v2_list
) {
3574 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
3576 if (!(rs
= networkstatus_v2_find_entry(ns
, desc
->identity_digest
)))
3578 if (!memcmp(rs
->descriptor_digest
,
3579 desc
->signed_descriptor_digest
, DIGEST_LEN
))
3586 /** Clear all our timeouts for fetching v2 and v3 directory stuff, and then
3587 * give it all a try again. */
3589 routerlist_retry_directory_downloads(time_t now
)
3591 router_reset_status_download_failures();
3592 router_reset_descriptor_download_failures();
3593 update_networkstatus_downloads(now
);
3594 update_router_descriptor_downloads(now
);
3597 /** Return 1 if all running sufficiently-stable routers will reject
3598 * addr:port, return 0 if any might accept it. */
3600 router_exit_policy_all_routers_reject(uint32_t addr
, uint16_t port
,
3603 addr_policy_result_t r
;
3604 if (!routerlist
) return 1;
3606 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, router
,
3608 if (router
->is_running
&&
3609 !router_is_unreliable(router
, need_uptime
, 0, 0)) {
3610 r
= compare_addr_to_addr_policy(addr
, port
, router
->exit_policy
);
3611 if (r
!= ADDR_POLICY_REJECTED
&& r
!= ADDR_POLICY_PROBABLY_REJECTED
)
3612 return 0; /* this one could be ok. good enough. */
3615 return 1; /* all will reject. */
3618 /** Return true iff <b>router</b> does not permit exit streams.
3621 router_exit_policy_rejects_all(routerinfo_t
*router
)
3623 return compare_addr_to_addr_policy(0, 0, router
->exit_policy
)
3624 == ADDR_POLICY_REJECTED
;
3627 /** Add to the list of authorized directory servers one at
3628 * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
3629 * <b>address</b> is NULL, add ourself. Return 0 if success, -1 if
3630 * we couldn't add it. */
3631 trusted_dir_server_t
*
3632 add_trusted_dir_server(const char *nickname
, const char *address
,
3633 uint16_t dir_port
, uint16_t or_port
,
3634 const char *digest
, const char *v3_auth_digest
,
3635 authority_type_t type
)
3637 trusted_dir_server_t
*ent
;
3639 char *hostname
= NULL
;
3641 if (!trusted_dir_servers
)
3642 trusted_dir_servers
= smartlist_create();
3644 if (!address
) { /* The address is us; we should guess. */
3645 if (resolve_my_address(LOG_WARN
, get_options(), &a
, &hostname
) < 0) {
3647 "Couldn't find a suitable address when adding ourself as a "
3648 "trusted directory server.");
3652 if (tor_lookup_hostname(address
, &a
)) {
3654 "Unable to lookup address for directory server at '%s'",
3658 hostname
= tor_strdup(address
);
3661 ent
= tor_malloc_zero(sizeof(trusted_dir_server_t
));
3662 ent
->nickname
= nickname
? tor_strdup(nickname
) : NULL
;
3663 ent
->address
= hostname
;
3665 ent
->dir_port
= dir_port
;
3666 ent
->or_port
= or_port
;
3667 ent
->is_running
= 1;
3669 memcpy(ent
->digest
, digest
, DIGEST_LEN
);
3670 if (v3_auth_digest
&& (type
& V3_AUTHORITY
))
3671 memcpy(ent
->v3_identity_digest
, v3_auth_digest
, DIGEST_LEN
);
3673 dlen
= 64 + strlen(hostname
) + (nickname
?strlen(nickname
):0);
3674 ent
->description
= tor_malloc(dlen
);
3676 tor_snprintf(ent
->description
, dlen
, "directory server \"%s\" at %s:%d",
3677 nickname
, hostname
, (int)dir_port
);
3679 tor_snprintf(ent
->description
, dlen
, "directory server at %s:%d",
3680 hostname
, (int)dir_port
);
3682 ent
->fake_status
.addr
= ent
->addr
;
3683 memcpy(ent
->fake_status
.identity_digest
, digest
, DIGEST_LEN
);
3685 strlcpy(ent
->fake_status
.nickname
, nickname
,
3686 sizeof(ent
->fake_status
.nickname
));
3688 ent
->fake_status
.nickname
[0] = '\0';
3689 ent
->fake_status
.dir_port
= ent
->dir_port
;
3690 ent
->fake_status
.or_port
= ent
->or_port
;
3693 ent
->fake_status
.version_supports_begindir
= 1;
3694 /* XX021 - wait until authorities are upgraded */
3696 ent
->fake_status
.version_supports_conditional_consensus
= 1;
3698 ent
->fake_status
.version_supports_conditional_consensus
= 0;
3701 smartlist_add(trusted_dir_servers
, ent
);
3702 router_dir_info_changed();
3706 /** Free storage held in <b>cert</b>. */
3708 authority_cert_free(authority_cert_t
*cert
)
3713 tor_free(cert
->cache_info
.signed_descriptor_body
);
3714 if (cert
->signing_key
)
3715 crypto_free_pk_env(cert
->signing_key
);
3716 if (cert
->identity_key
)
3717 crypto_free_pk_env(cert
->identity_key
);
3722 /** Free storage held in <b>ds</b>. */
3724 trusted_dir_server_free(trusted_dir_server_t
*ds
)
3726 tor_free(ds
->nickname
);
3727 tor_free(ds
->description
);
3728 tor_free(ds
->address
);
3732 /** Remove all members from the list of trusted dir servers. */
3734 clear_trusted_dir_servers(void)
3736 if (trusted_dir_servers
) {
3737 SMARTLIST_FOREACH(trusted_dir_servers
, trusted_dir_server_t
*, ent
,
3738 trusted_dir_server_free(ent
));
3739 smartlist_clear(trusted_dir_servers
);
3741 trusted_dir_servers
= smartlist_create();
3743 router_dir_info_changed();
3746 /** Return 1 if any trusted dir server supports v1 directories,
3749 any_trusted_dir_is_v1_authority(void)
3751 if (trusted_dir_servers
)
3752 return get_n_authorities(V1_AUTHORITY
) > 0;
3757 /** For every current directory connection whose purpose is <b>purpose</b>,
3758 * and where the resource being downloaded begins with <b>prefix</b>, split
3759 * rest of the resource into base16 fingerprints, decode them, and set the
3760 * corresponding elements of <b>result</b> to a nonzero value. */
3762 list_pending_downloads(digestmap_t
*result
,
3763 int purpose
, const char *prefix
)
3765 const size_t p_len
= strlen(prefix
);
3766 smartlist_t
*tmp
= smartlist_create();
3767 smartlist_t
*conns
= get_connection_array();
3771 SMARTLIST_FOREACH(conns
, connection_t
*, conn
,
3773 if (conn
->type
== CONN_TYPE_DIR
&&
3774 conn
->purpose
== purpose
&&
3775 !conn
->marked_for_close
) {
3776 const char *resource
= TO_DIR_CONN(conn
)->requested_resource
;
3777 if (!strcmpstart(resource
, prefix
))
3778 dir_split_resource_into_fingerprints(resource
+ p_len
,
3782 SMARTLIST_FOREACH(tmp
, char *, d
,
3784 digestmap_set(result
, d
, (void*)1);
3787 smartlist_free(tmp
);
3790 /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
3791 * true) we are currently downloading by descriptor digest, set result[d] to
3794 list_pending_descriptor_downloads(digestmap_t
*result
, int extrainfo
)
3797 extrainfo
? DIR_PURPOSE_FETCH_EXTRAINFO
: DIR_PURPOSE_FETCH_SERVERDESC
;
3798 list_pending_downloads(result
, purpose
, "d/");
3801 /** Launch downloads for all the descriptors whose digests are listed
3802 * as digests[i] for lo <= i < hi. (Lo and hi may be out of range.)
3803 * If <b>source</b> is given, download from <b>source</b>; otherwise,
3804 * download from an appropriate random directory server.
3807 initiate_descriptor_downloads(routerstatus_t
*source
,
3809 smartlist_t
*digests
,
3810 int lo
, int hi
, int pds_flags
)
3813 char *resource
, *cp
;
3819 if (hi
> smartlist_len(digests
))
3820 hi
= smartlist_len(digests
);
3822 r_len
= 8 + (HEX_DIGEST_LEN
+1)*n
;
3823 cp
= resource
= tor_malloc(r_len
);
3824 memcpy(cp
, "d/", 2);
3826 for (i
= lo
; i
< hi
; ++i
) {
3827 base16_encode(cp
, r_len
-(cp
-resource
),
3828 smartlist_get(digests
,i
), DIGEST_LEN
);
3829 cp
+= HEX_DIGEST_LEN
;
3832 memcpy(cp
-1, ".z", 3);
3835 /* We know which authority we want. */
3836 directory_initiate_command_routerstatus(source
, purpose
,
3837 ROUTER_PURPOSE_GENERAL
,
3838 0, /* not private */
3839 resource
, NULL
, 0, 0);
3841 directory_get_from_dirserver(purpose
, ROUTER_PURPOSE_GENERAL
, resource
,
3847 /** Return 0 if this routerstatus is obsolete, too new, isn't
3848 * running, or otherwise not a descriptor that we would make any
3849 * use of even if we had it. Else return 1. */
3851 client_would_use_router(routerstatus_t
*rs
, time_t now
, or_options_t
*options
)
3853 if (!rs
->is_running
&& !options
->FetchUselessDescriptors
) {
3854 /* If we had this router descriptor, we wouldn't even bother using it.
3855 * But, if we want to have a complete list, fetch it anyway. */
3858 if (rs
->published_on
+ options
->TestingEstimatedDescriptorPropagationTime
3860 /* Most caches probably don't have this descriptor yet. */
3863 if (rs
->published_on
+ OLD_ROUTER_DESC_MAX_AGE
< now
) {
3864 /* We'd drop it immediately for being too old. */
3870 /** Max amount of hashes to download per request.
3871 * Since squid does not like URLs >= 4096 bytes we limit it to 96.
3872 * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
3873 * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
3874 * So use 96 because it's a nice number.
3876 #define MAX_DL_PER_REQUEST 96
3877 /** Don't split our requests so finely that we are requesting fewer than
3878 * this number per server. */
3879 #define MIN_DL_PER_REQUEST 4
3880 /** To prevent a single screwy cache from confusing us by selective reply,
3881 * try to split our requests into at least this this many requests. */
3882 #define MIN_REQUESTS 3
3883 /** If we want fewer than this many descriptors, wait until we
3884 * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
3886 #define MAX_DL_TO_DELAY 16
3887 /** When directory clients have only a few servers to request, they batch
3888 * them until they have more, or until this amount of time has passed. */
3889 #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
3891 /** Given a list of router descriptor digests in <b>downloadable</b>, decide
3892 * whether to delay fetching until we have more. If we don't want to delay,
3893 * launch one or more requests to the appropriate directory authorities. */
3895 launch_router_descriptor_downloads(smartlist_t
*downloadable
, time_t now
)
3897 int should_delay
= 0, n_downloadable
;
3898 or_options_t
*options
= get_options();
3900 n_downloadable
= smartlist_len(downloadable
);
3901 if (!directory_fetches_dir_info_early(options
)) {
3902 if (n_downloadable
>= MAX_DL_TO_DELAY
) {
3904 "There are enough downloadable routerdescs to launch requests.");
3907 should_delay
= (last_routerdesc_download_attempted
+
3908 MAX_CLIENT_INTERVAL_WITHOUT_REQUEST
) > now
;
3909 if (!should_delay
&& n_downloadable
) {
3910 if (last_routerdesc_download_attempted
) {
3912 "There are not many downloadable routerdescs, but we've "
3913 "been waiting long enough (%d seconds). Downloading.",
3914 (int)(now
-last_routerdesc_download_attempted
));
3917 "There are not many downloadable routerdescs, but we haven't "
3918 "tried downloading descriptors recently. Downloading.");
3923 /* XXX should we consider having even the dir mirrors delay
3924 * a little bit, so we don't load the authorities as much? -RD
3925 * I don't think so. If we do, clients that want those descriptors may
3926 * not actually find them if the caches haven't got them yet. -NM
3929 if (! should_delay
&& n_downloadable
) {
3930 int i
, n_per_request
;
3931 const char *req_plural
= "", *rtr_plural
= "";
3932 int pds_flags
= PDS_RETRY_IF_NO_SERVERS
;
3933 if (! authdir_mode_any_nonhidserv(options
)) {
3934 /* If we wind up going to the authorities, we want to only open one
3935 * connection to each authority at a time, so that we don't overload
3936 * them. We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
3937 * regardless of whether we're a cache or not; it gets ignored if we're
3938 * not calling router_pick_trusteddirserver.
3940 * Setting this flag can make initiate_descriptor_downloads() ignore
3941 * requests. We need to make sure that we do in fact call
3942 * update_router_descriptor_downloads() later on, once the connections
3943 * have succeeded or failed.
3945 pds_flags
|= PDS_NO_EXISTING_SERVERDESC_FETCH
;
3948 n_per_request
= (n_downloadable
+MIN_REQUESTS
-1) / MIN_REQUESTS
;
3949 if (n_per_request
> MAX_DL_PER_REQUEST
)
3950 n_per_request
= MAX_DL_PER_REQUEST
;
3951 if (n_per_request
< MIN_DL_PER_REQUEST
)
3952 n_per_request
= MIN_DL_PER_REQUEST
;
3954 if (n_downloadable
> n_per_request
)
3955 req_plural
= rtr_plural
= "s";
3956 else if (n_downloadable
> 1)
3960 "Launching %d request%s for %d router%s, %d at a time",
3961 (n_downloadable
+n_per_request
-1)/n_per_request
,
3962 req_plural
, n_downloadable
, rtr_plural
, n_per_request
);
3963 smartlist_sort_digests(downloadable
);
3964 for (i
=0; i
< n_downloadable
; i
+= n_per_request
) {
3965 initiate_descriptor_downloads(NULL
, DIR_PURPOSE_FETCH_SERVERDESC
,
3966 downloadable
, i
, i
+n_per_request
,
3969 last_routerdesc_download_attempted
= now
;
3973 /** Launch downloads for router status as needed, using the strategy used by
3974 * authorities and caches: based on the v2 networkstatuses we have, download
3975 * every descriptor we don't have but would serve, from a random authority
3978 update_router_descriptor_cache_downloads_v2(time_t now
)
3980 smartlist_t
**downloadable
; /* For each authority, what can we dl from it? */
3981 smartlist_t
**download_from
; /* ... and, what will we dl from it? */
3982 digestmap_t
*map
; /* Which descs are in progress, or assigned? */
3985 or_options_t
*options
= get_options();
3986 const smartlist_t
*networkstatus_v2_list
= networkstatus_get_v2_list();
3988 if (! directory_fetches_dir_info_early(options
)) {
3989 log_warn(LD_BUG
, "Called update_router_descriptor_cache_downloads_v2() "
3990 "on a non-dir-mirror?");
3993 if (!networkstatus_v2_list
|| !smartlist_len(networkstatus_v2_list
))
3996 map
= digestmap_new();
3997 n
= smartlist_len(networkstatus_v2_list
);
3999 downloadable
= tor_malloc_zero(sizeof(smartlist_t
*) * n
);
4000 download_from
= tor_malloc_zero(sizeof(smartlist_t
*) * n
);
4002 /* Set map[d]=1 for the digest of every descriptor that we are currently
4004 list_pending_descriptor_downloads(map
, 0);
4006 /* For the digest of every descriptor that we don't have, and that we aren't
4007 * downloading, add d to downloadable[i] if the i'th networkstatus knows
4008 * about that descriptor, and we haven't already failed to get that
4009 * descriptor from the corresponding authority.
4012 SMARTLIST_FOREACH(networkstatus_v2_list
, networkstatus_v2_t
*, ns
,
4014 trusted_dir_server_t
*ds
;
4016 dl
= downloadable
[ns_sl_idx
] = smartlist_create();
4017 download_from
[ns_sl_idx
] = smartlist_create();
4018 if (ns
->published_on
+ MAX_NETWORKSTATUS_AGE
+10*60 < now
) {
4019 /* Don't download if the networkstatus is almost ancient. */
4020 /* Actually, I suspect what's happening here is that we ask
4021 * for the descriptor when we have a given networkstatus,
4022 * and then we get a newer networkstatus, and then we receive
4023 * the descriptor. Having a networkstatus actually expire is
4024 * probably a rare event, and we'll probably be happiest if
4025 * we take this clause out. -RD */
4029 /* Don't try dirservers that we think are down -- we might have
4030 * just tried them and just marked them as down. */
4031 ds
= router_get_trusteddirserver_by_digest(ns
->identity_digest
);
4032 if (ds
&& !ds
->is_running
)
4035 SMARTLIST_FOREACH(ns
->entries
, routerstatus_t
* , rs
,
4037 if (!rs
->need_to_mirror
)
4039 if (router_get_by_descriptor_digest(rs
->descriptor_digest
)) {
4041 "We have a router descriptor, but need_to_mirror=1.");
4042 rs
->need_to_mirror
= 0;
4045 if (authdir_mode(options
) && dirserv_would_reject_router(rs
)) {
4046 rs
->need_to_mirror
= 0;
4049 if (digestmap_get(map
, rs
->descriptor_digest
)) {
4050 /* We're downloading it already. */
4053 /* We could download it from this guy. */
4054 smartlist_add(dl
, rs
->descriptor_digest
);
4060 /* At random, assign descriptors to authorities such that:
4061 * - if d is a member of some downloadable[x], d is a member of some
4062 * download_from[y]. (Everything we want to download, we try to download
4064 * - If d is a member of download_from[y], d is a member of downloadable[y].
4065 * (We only try to download descriptors from authorities who claim to have
4067 * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
4068 * (We don't try to download anything from two authorities concurrently.)
4070 while (n_download
) {
4071 int which_ns
= crypto_rand_int(n
);
4072 smartlist_t
*dl
= downloadable
[which_ns
];
4075 if (!smartlist_len(dl
))
4077 idx
= crypto_rand_int(smartlist_len(dl
));
4078 d
= smartlist_get(dl
, idx
);
4079 if (! digestmap_get(map
, d
)) {
4080 smartlist_add(download_from
[which_ns
], d
);
4081 digestmap_set(map
, d
, (void*) 1);
4083 smartlist_del(dl
, idx
);
4087 /* Now, we can actually launch our requests. */
4088 for (i
=0; i
<n
; ++i
) {
4089 networkstatus_v2_t
*ns
= smartlist_get(networkstatus_v2_list
, i
);
4090 trusted_dir_server_t
*ds
=
4091 router_get_trusteddirserver_by_digest(ns
->identity_digest
);
4092 smartlist_t
*dl
= download_from
[i
];
4093 int pds_flags
= PDS_RETRY_IF_NO_SERVERS
;
4094 if (! authdir_mode_any_nonhidserv(options
))
4095 pds_flags
|= PDS_NO_EXISTING_SERVERDESC_FETCH
; /* XXXX ignored*/
4098 log_warn(LD_BUG
, "Networkstatus with no corresponding authority!");
4101 if (! smartlist_len(dl
))
4103 log_info(LD_DIR
, "Requesting %d descriptors from authority \"%s\"",
4104 smartlist_len(dl
), ds
->nickname
);
4105 for (j
=0; j
< smartlist_len(dl
); j
+= MAX_DL_PER_REQUEST
) {
4106 initiate_descriptor_downloads(&(ds
->fake_status
),
4107 DIR_PURPOSE_FETCH_SERVERDESC
, dl
, j
,
4108 j
+MAX_DL_PER_REQUEST
, pds_flags
);
4112 for (i
=0; i
<n
; ++i
) {
4113 smartlist_free(download_from
[i
]);
4114 smartlist_free(downloadable
[i
]);
4116 tor_free(download_from
);
4117 tor_free(downloadable
);
4118 digestmap_free(map
,NULL
);
4121 /** For any descriptor that we want that's currently listed in the live
4122 * consensus, download it as appropriate. */
4124 update_consensus_router_descriptor_downloads(time_t now
)
4126 or_options_t
*options
= get_options();
4127 digestmap_t
*map
= NULL
;
4128 smartlist_t
*no_longer_old
= smartlist_create();
4129 smartlist_t
*downloadable
= smartlist_create();
4130 int authdir
= authdir_mode(options
);
4131 networkstatus_t
*consensus
=
4132 networkstatus_get_reasonably_live_consensus(now
);
4133 int n_delayed
=0, n_have
=0, n_would_reject
=0, n_wouldnt_use
=0,
4134 n_inprogress
=0, n_in_oldrouters
=0;
4136 if (directory_too_idle_to_fetch_descriptors(options
, now
))
4141 map
= digestmap_new();
4142 list_pending_descriptor_downloads(map
, 0);
4143 SMARTLIST_FOREACH(consensus
->routerstatus_list
, routerstatus_t
*, rs
,
4145 signed_descriptor_t
*sd
;
4146 if ((sd
= router_get_by_descriptor_digest(rs
->descriptor_digest
))) {
4149 if (!(ri
= router_get_by_digest(rs
->identity_digest
)) ||
4150 memcmp(ri
->cache_info
.signed_descriptor_digest
,
4151 sd
->signed_descriptor_digest
, DIGEST_LEN
)) {
4152 /* We have a descriptor with this digest, but either there is no
4153 * entry in routerlist with the same ID (!ri), or there is one,
4154 * but the identity digest differs (memcmp).
4156 smartlist_add(no_longer_old
, sd
);
4157 ++n_in_oldrouters
; /* We have it in old_routers. */
4159 continue; /* We have it already. */
4161 if (digestmap_get(map
, rs
->descriptor_digest
)) {
4163 continue; /* We have an in-progress download. */
4165 if (!download_status_is_ready(&rs
->dl_status
, now
,
4166 MAX_ROUTERDESC_DOWNLOAD_FAILURES
)) {
4167 ++n_delayed
; /* Not ready for retry. */
4170 if (authdir
&& dirserv_would_reject_router(rs
)) {
4172 continue; /* We would throw it out immediately. */
4174 if (!directory_caches_dir_info(options
) &&
4175 !client_would_use_router(rs
, now
, options
)) {
4177 continue; /* We would never use it ourself. */
4179 smartlist_add(downloadable
, rs
->descriptor_digest
);
4182 if (!authdir_mode_handles_descs(options
, ROUTER_PURPOSE_GENERAL
)
4183 && smartlist_len(no_longer_old
)) {
4184 routerlist_t
*rl
= router_get_routerlist();
4185 log_info(LD_DIR
, "%d router descriptors listed in consensus are "
4186 "currently in old_routers; making them current.",
4187 smartlist_len(no_longer_old
));
4188 SMARTLIST_FOREACH(no_longer_old
, signed_descriptor_t
*, sd
, {
4190 was_router_added_t r
;
4191 routerinfo_t
*ri
= routerlist_reparse_old(rl
, sd
);
4193 log_warn(LD_BUG
, "Failed to re-parse a router.");
4196 r
= router_add_to_routerlist(ri
, &msg
, 1, 0);
4197 if (WRA_WAS_OUTDATED(r
)) {
4198 log_warn(LD_DIR
, "Couldn't add re-parsed router: %s",
4202 routerlist_assert_ok(rl
);
4206 "%d router descriptors downloadable. %d delayed; %d present "
4207 "(%d of those were in old_routers); %d would_reject; "
4208 "%d wouldnt_use; %d in progress.",
4209 smartlist_len(downloadable
), n_delayed
, n_have
, n_in_oldrouters
,
4210 n_would_reject
, n_wouldnt_use
, n_inprogress
);
4212 launch_router_descriptor_downloads(downloadable
, now
);
4214 digestmap_free(map
, NULL
);
4216 smartlist_free(downloadable
);
4217 smartlist_free(no_longer_old
);
4220 /** How often should we launch a server/authority request to be sure of getting
4221 * a guess for our IP? */
4222 /*XXXX021 this info should come from netinfo cells or something, or we should
4223 * do this only when we aren't seeing incoming data. see bug 652. */
4224 #define DUMMY_DOWNLOAD_INTERVAL (20*60)
4226 /** Launch downloads for router status as needed. */
4228 update_router_descriptor_downloads(time_t now
)
4230 or_options_t
*options
= get_options();
4231 static time_t last_dummy_download
= 0;
4232 if (should_delay_dir_fetches(options
))
4234 if (directory_fetches_dir_info_early(options
)) {
4235 update_router_descriptor_cache_downloads_v2(now
);
4237 update_consensus_router_descriptor_downloads(now
);
4239 /* XXXX021 we could be smarter here; see notes on bug 652. */
4240 /* If we're a server that doesn't have a configured address, we rely on
4241 * directory fetches to learn when our address changes. So if we haven't
4242 * tried to get any routerdescs in a long time, try a dummy fetch now. */
4243 if (!options
->Address
&&
4244 server_mode(options
) &&
4245 last_routerdesc_download_attempted
+ DUMMY_DOWNLOAD_INTERVAL
< now
&&
4246 last_dummy_download
+ DUMMY_DOWNLOAD_INTERVAL
< now
) {
4247 last_dummy_download
= now
;
4248 directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC
,
4249 ROUTER_PURPOSE_GENERAL
, "authority.z",
4250 PDS_RETRY_IF_NO_SERVERS
);
4254 /** Launch extrainfo downloads as needed. */
4256 update_extrainfo_downloads(time_t now
)
4258 or_options_t
*options
= get_options();
4260 smartlist_t
*wanted
;
4261 digestmap_t
*pending
;
4263 int n_no_ei
= 0, n_pending
= 0, n_have
= 0, n_delay
= 0;
4264 if (! options
->DownloadExtraInfo
)
4266 if (should_delay_dir_fetches(options
))
4268 if (!router_have_minimum_dir_info())
4271 pending
= digestmap_new();
4272 list_pending_descriptor_downloads(pending
, 1);
4273 rl
= router_get_routerlist();
4274 wanted
= smartlist_create();
4275 for (old_routers
= 0; old_routers
< 2; ++old_routers
) {
4276 smartlist_t
*lst
= old_routers
? rl
->old_routers
: rl
->routers
;
4277 for (i
= 0; i
< smartlist_len(lst
); ++i
) {
4278 signed_descriptor_t
*sd
;
4281 sd
= smartlist_get(lst
, i
);
4283 sd
= &((routerinfo_t
*)smartlist_get(lst
, i
))->cache_info
;
4284 if (sd
->is_extrainfo
)
4285 continue; /* This should never happen. */
4286 if (old_routers
&& !router_get_by_digest(sd
->identity_digest
))
4287 continue; /* Couldn't check the signature if we got it. */
4288 if (sd
->extrainfo_is_bogus
)
4290 d
= sd
->extra_info_digest
;
4291 if (tor_digest_is_zero(d
)) {
4295 if (eimap_get(rl
->extra_info_map
, d
)) {
4299 if (!download_status_is_ready(&sd
->ei_dl_status
, now
,
4300 MAX_ROUTERDESC_DOWNLOAD_FAILURES
)) {
4304 if (digestmap_get(pending
, d
)) {
4308 smartlist_add(wanted
, d
);
4311 digestmap_free(pending
, NULL
);
4313 log_info(LD_DIR
, "Extrainfo download status: %d router with no ei, %d "
4314 "with present ei, %d delaying, %d pending, %d downloadable.",
4315 n_no_ei
, n_have
, n_delay
, n_pending
, smartlist_len(wanted
));
4317 smartlist_shuffle(wanted
);
4318 for (i
= 0; i
< smartlist_len(wanted
); i
+= MAX_DL_PER_REQUEST
) {
4319 initiate_descriptor_downloads(NULL
, DIR_PURPOSE_FETCH_EXTRAINFO
,
4320 wanted
, i
, i
+ MAX_DL_PER_REQUEST
,
4321 PDS_RETRY_IF_NO_SERVERS
|PDS_NO_EXISTING_SERVERDESC_FETCH
);
4324 smartlist_free(wanted
);
4327 /** True iff, the last time we checked whether we had enough directory info
4328 * to build circuits, the answer was "yes". */
4329 static int have_min_dir_info
= 0;
4330 /** True iff enough has changed since the last time we checked whether we had
4331 * enough directory info to build circuits that our old answer can no longer
4333 static int need_to_update_have_min_dir_info
= 1;
4334 /** String describing what we're missing before we have enough directory
4336 static char dir_info_status
[128] = "";
4338 /** Return true iff we have enough networkstatus and router information to
4339 * start building circuits. Right now, this means "more than half the
4340 * networkstatus documents, and at least 1/4 of expected routers." */
4341 //XXX should consider whether we have enough exiting nodes here.
4343 router_have_minimum_dir_info(void)
4345 if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info
)) {
4346 update_router_have_minimum_dir_info();
4347 need_to_update_have_min_dir_info
= 0;
4349 return have_min_dir_info
;
4352 /** Called when our internal view of the directory has changed. This can be
4353 * when the authorities change, networkstatuses change, the list of routerdescs
4354 * changes, or number of running routers changes.
4357 router_dir_info_changed(void)
4359 need_to_update_have_min_dir_info
= 1;
4360 rend_hsdir_routers_changed();
4363 /** Return a string describing what we're missing before we have enough
4364 * directory info. */
4366 get_dir_info_status_string(void)
4368 return dir_info_status
;
4372 count_usable_descriptors(int *num_present
, int *num_usable
,
4373 const networkstatus_t
*consensus
,
4374 or_options_t
*options
, time_t now
)
4376 *num_present
= 0, *num_usable
=0;
4378 SMARTLIST_FOREACH(consensus
->routerstatus_list
, routerstatus_t
*, rs
,
4380 if (client_would_use_router(rs
, now
, options
)) {
4381 ++*num_usable
; /* the consensus says we want it. */
4382 if (router_get_by_descriptor_digest(rs
->descriptor_digest
)) {
4383 /* we have the descriptor listed in the consensus. */
4389 log_debug(LD_DIR
, "%d usable, %d present.", *num_usable
, *num_present
);
4392 /** We just fetched a new set of descriptors. Compute how far through
4393 * the "loading descriptors" bootstrapping phase we are, so we can inform
4394 * the controller of our progress. */
4396 count_loading_descriptors_progress(void)
4398 int num_present
= 0, num_usable
=0;
4399 time_t now
= time(NULL
);
4400 const networkstatus_t
*consensus
=
4401 networkstatus_get_reasonably_live_consensus(now
);
4405 return 0; /* can't count descriptors if we have no list of them */
4407 count_usable_descriptors(&num_present
, &num_usable
,
4408 consensus
, get_options(), now
);
4410 if (num_usable
== 0)
4411 return 0; /* don't div by 0 */
4412 fraction
= num_present
/ (num_usable
/4.);
4414 return 0; /* it's not the number of descriptors holding us back */
4415 return BOOTSTRAP_STATUS_LOADING_DESCRIPTORS
+ (int)
4416 (fraction
*(BOOTSTRAP_STATUS_CONN_OR
-1 -
4417 BOOTSTRAP_STATUS_LOADING_DESCRIPTORS
));
4420 /** Change the value of have_min_dir_info, setting it true iff we have enough
4421 * network and router information to build circuits. Clear the value of
4422 * need_to_update_have_min_dir_info. */
4424 update_router_have_minimum_dir_info(void)
4426 int num_present
= 0, num_usable
=0;
4427 time_t now
= time(NULL
);
4429 or_options_t
*options
= get_options();
4430 const networkstatus_t
*consensus
=
4431 networkstatus_get_reasonably_live_consensus(now
);
4434 if (!networkstatus_get_latest_consensus())
4435 strlcpy(dir_info_status
, "We have no network-status consensus.",
4436 sizeof(dir_info_status
));
4438 strlcpy(dir_info_status
, "We have no recent network-status consensus.",
4439 sizeof(dir_info_status
));
4444 if (should_delay_dir_fetches(get_options())) {
4445 log_notice(LD_DIR
, "no known bridge descriptors running yet; stalling");
4446 strlcpy(dir_info_status
, "No live bridge descriptors.",
4447 sizeof(dir_info_status
));
4452 count_usable_descriptors(&num_present
, &num_usable
, consensus
, options
, now
);
4454 if (num_present
< num_usable
/4) {
4455 tor_snprintf(dir_info_status
, sizeof(dir_info_status
),
4456 "We have only %d/%d usable descriptors.", num_present
, num_usable
);
4458 control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS
, 0);
4459 } else if (num_present
< 2) {
4460 tor_snprintf(dir_info_status
, sizeof(dir_info_status
),
4461 "Only %d descriptor%s here and believed reachable!",
4462 num_present
, num_present
? "" : "s");
4469 if (res
&& !have_min_dir_info
) {
4470 log(LOG_NOTICE
, LD_DIR
,
4471 "We now have enough directory information to build circuits.");
4472 control_event_client_status(LOG_NOTICE
, "ENOUGH_DIR_INFO");
4473 control_event_bootstrap(BOOTSTRAP_STATUS_CONN_OR
, 0);
4475 if (!res
&& have_min_dir_info
) {
4476 int quiet
= directory_too_idle_to_fetch_descriptors(options
, now
);
4477 log(quiet
? LOG_INFO
: LOG_NOTICE
, LD_DIR
,
4478 "Our directory information is no longer up-to-date "
4479 "enough to build circuits: %s", dir_info_status
);
4480 control_event_client_status(LOG_NOTICE
, "NOT_ENOUGH_DIR_INFO");
4482 have_min_dir_info
= res
;
4483 need_to_update_have_min_dir_info
= 0;
4486 /** Reset the descriptor download failure count on all routers, so that we
4487 * can retry any long-failed routers immediately.
4490 router_reset_descriptor_download_failures(void)
4492 networkstatus_reset_download_failures();
4493 last_routerdesc_download_attempted
= 0;
4496 SMARTLIST_FOREACH(routerlist
->routers
, routerinfo_t
*, ri
,
4498 download_status_reset(&ri
->cache_info
.ei_dl_status
);
4500 SMARTLIST_FOREACH(routerlist
->old_routers
, signed_descriptor_t
*, sd
,
4502 download_status_reset(&sd
->ei_dl_status
);
4506 /** Any changes in a router descriptor's publication time larger than this are
4507 * automatically non-cosmetic. */
4508 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (12*60*60)
4510 /** We allow uptime to vary from how much it ought to be by this much. */
4511 #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
4513 /** Return true iff the only differences between r1 and r2 are such that
4514 * would not cause a recent (post 0.1.1.6) dirserver to republish.
4517 router_differences_are_cosmetic(routerinfo_t
*r1
, routerinfo_t
*r2
)
4519 time_t r1pub
, r2pub
;
4520 long time_difference
;
4521 tor_assert(r1
&& r2
);
4523 /* r1 should be the one that was published first. */
4524 if (r1
->cache_info
.published_on
> r2
->cache_info
.published_on
) {
4525 routerinfo_t
*ri_tmp
= r2
;
4530 /* If any key fields differ, they're different. */
4531 if (strcasecmp(r1
->address
, r2
->address
) ||
4532 strcasecmp(r1
->nickname
, r2
->nickname
) ||
4533 r1
->or_port
!= r2
->or_port
||
4534 r1
->dir_port
!= r2
->dir_port
||
4535 r1
->purpose
!= r2
->purpose
||
4536 crypto_pk_cmp_keys(r1
->onion_pkey
, r2
->onion_pkey
) ||
4537 crypto_pk_cmp_keys(r1
->identity_pkey
, r2
->identity_pkey
) ||
4538 strcasecmp(r1
->platform
, r2
->platform
) ||
4539 (r1
->contact_info
&& !r2
->contact_info
) || /* contact_info is optional */
4540 (!r1
->contact_info
&& r2
->contact_info
) ||
4541 (r1
->contact_info
&& r2
->contact_info
&&
4542 strcasecmp(r1
->contact_info
, r2
->contact_info
)) ||
4543 r1
->is_hibernating
!= r2
->is_hibernating
||
4544 r1
->has_old_dnsworkers
!= r2
->has_old_dnsworkers
||
4545 cmp_addr_policies(r1
->exit_policy
, r2
->exit_policy
))
4547 if ((r1
->declared_family
== NULL
) != (r2
->declared_family
== NULL
))
4549 if (r1
->declared_family
&& r2
->declared_family
) {
4551 if (smartlist_len(r1
->declared_family
)!=smartlist_len(r2
->declared_family
))
4553 n
= smartlist_len(r1
->declared_family
);
4554 for (i
=0; i
< n
; ++i
) {
4555 if (strcasecmp(smartlist_get(r1
->declared_family
, i
),
4556 smartlist_get(r2
->declared_family
, i
)))
4561 /* Did bandwidth change a lot? */
4562 if ((r1
->bandwidthcapacity
< r2
->bandwidthcapacity
/2) ||
4563 (r2
->bandwidthcapacity
< r1
->bandwidthcapacity
/2))
4566 /* Did more than 12 hours pass? */
4567 if (r1
->cache_info
.published_on
+ ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
4568 < r2
->cache_info
.published_on
)
4571 /* Did uptime fail to increase by approximately the amount we would think,
4572 * give or take some slop? */
4573 r1pub
= r1
->cache_info
.published_on
;
4574 r2pub
= r2
->cache_info
.published_on
;
4575 time_difference
= labs(r2
->uptime
- (r1
->uptime
+ (r2pub
- r1pub
)));
4576 if (time_difference
> ROUTER_ALLOW_UPTIME_DRIFT
&&
4577 time_difference
> r1
->uptime
* .05 &&
4578 time_difference
> r2
->uptime
* .05)
4581 /* Otherwise, the difference is cosmetic. */
4585 /** Check whether <b>ri</b> (a.k.a. sd) is a router compatible with the
4586 * extrainfo document
4587 * <b>ei</b>. If no router is compatible with <b>ei</b>, <b>ei</b> should be
4588 * dropped. Return 0 for "compatible", return 1 for "reject, and inform
4589 * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
4590 * <b>msg</b> is present, set *<b>msg</b> to a description of the
4591 * incompatibility (if any).
4594 routerinfo_incompatible_with_extrainfo(routerinfo_t
*ri
, extrainfo_t
*ei
,
4595 signed_descriptor_t
*sd
,
4598 int digest_matches
, r
=1;
4602 sd
= &ri
->cache_info
;
4605 if (msg
) *msg
= "Extrainfo signature was bad, or signed with wrong key.";
4609 digest_matches
= !memcmp(ei
->cache_info
.signed_descriptor_digest
,
4610 sd
->extra_info_digest
, DIGEST_LEN
);
4612 /* The identity must match exactly to have been generated at the same time
4613 * by the same router. */
4614 if (memcmp(ri
->cache_info
.identity_digest
, ei
->cache_info
.identity_digest
,
4616 if (msg
) *msg
= "Extrainfo nickname or identity did not match routerinfo";
4617 goto err
; /* different servers */
4620 if (ei
->pending_sig
) {
4621 char signed_digest
[128];
4622 if (crypto_pk_public_checksig(ri
->identity_pkey
, signed_digest
,
4623 ei
->pending_sig
, ei
->pending_sig_len
) != DIGEST_LEN
||
4624 memcmp(signed_digest
, ei
->cache_info
.signed_descriptor_digest
,
4627 tor_free(ei
->pending_sig
);
4628 if (msg
) *msg
= "Extrainfo signature bad, or signed with wrong key";
4629 goto err
; /* Bad signature, or no match. */
4632 ei
->cache_info
.send_unencrypted
= ri
->cache_info
.send_unencrypted
;
4633 tor_free(ei
->pending_sig
);
4636 if (ei
->cache_info
.published_on
< sd
->published_on
) {
4637 if (msg
) *msg
= "Extrainfo published time did not match routerdesc";
4639 } else if (ei
->cache_info
.published_on
> sd
->published_on
) {
4640 if (msg
) *msg
= "Extrainfo published time did not match routerdesc";
4645 if (!digest_matches
) {
4646 if (msg
) *msg
= "Extrainfo digest did not match value from routerdesc";
4647 goto err
; /* Digest doesn't match declared value. */
4652 if (digest_matches
) {
4653 /* This signature was okay, and the digest was right: This is indeed the
4654 * corresponding extrainfo. But insanely, it doesn't match the routerinfo
4655 * that lists it. Don't try to fetch this one again. */
4656 sd
->extrainfo_is_bogus
= 1;
4662 /** Assert that the internal representation of <b>rl</b> is
4663 * self-consistent. */
4665 routerlist_assert_ok(routerlist_t
*rl
)
4668 signed_descriptor_t
*sd2
;
4671 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
4673 r2
= rimap_get(rl
->identity_map
, r
->cache_info
.identity_digest
);
4674 tor_assert(r
== r2
);
4675 sd2
= sdmap_get(rl
->desc_digest_map
,
4676 r
->cache_info
.signed_descriptor_digest
);
4677 tor_assert(&(r
->cache_info
) == sd2
);
4678 tor_assert(r
->cache_info
.routerlist_index
== r_sl_idx
);
4681 * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
4682 * commenting this out is just a band-aid.
4684 * The problem is that, although well-behaved router descriptors
4685 * should never have the same value for their extra_info_digest, it's
4686 * possible for ill-behaved routers to claim whatever they like there.
4688 * The real answer is to trash desc_by_eid_map and instead have
4689 * something that indicates for a given extra-info digest we want,
4690 * what its download status is. We'll do that as a part of routerlist
4691 * refactoring once consensus directories are in. For now,
4692 * this rep violation is probably harmless: an adversary can make us
4693 * reset our retry count for an extrainfo, but that's not the end
4694 * of the world. Changing the representation in 0.2.0.x would just
4695 * destabilize the codebase.
4696 if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
4697 signed_descriptor_t *sd3 =
4698 sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
4699 tor_assert(sd3 == &(r->cache_info));
4703 SMARTLIST_FOREACH(rl
->old_routers
, signed_descriptor_t
*, sd
,
4705 r2
= rimap_get(rl
->identity_map
, sd
->identity_digest
);
4706 tor_assert(sd
!= &(r2
->cache_info
));
4707 sd2
= sdmap_get(rl
->desc_digest_map
, sd
->signed_descriptor_digest
);
4708 tor_assert(sd
== sd2
);
4709 tor_assert(sd
->routerlist_index
== sd_sl_idx
);
4711 if (!tor_digest_is_zero(sd->extra_info_digest)) {
4712 signed_descriptor_t *sd3 =
4713 sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
4714 tor_assert(sd3 == sd);
4719 RIMAP_FOREACH(rl
->identity_map
, d
, r
) {
4720 tor_assert(!memcmp(r
->cache_info
.identity_digest
, d
, DIGEST_LEN
));
4721 } DIGESTMAP_FOREACH_END
;
4722 SDMAP_FOREACH(rl
->desc_digest_map
, d
, sd
) {
4723 tor_assert(!memcmp(sd
->signed_descriptor_digest
, d
, DIGEST_LEN
));
4724 } DIGESTMAP_FOREACH_END
;
4725 SDMAP_FOREACH(rl
->desc_by_eid_map
, d
, sd
) {
4726 tor_assert(!tor_digest_is_zero(d
));
4728 tor_assert(!memcmp(sd
->extra_info_digest
, d
, DIGEST_LEN
));
4729 } DIGESTMAP_FOREACH_END
;
4730 EIMAP_FOREACH(rl
->extra_info_map
, d
, ei
) {
4731 signed_descriptor_t
*sd
;
4732 tor_assert(!memcmp(ei
->cache_info
.signed_descriptor_digest
,
4734 sd
= sdmap_get(rl
->desc_by_eid_map
,
4735 ei
->cache_info
.signed_descriptor_digest
);
4736 // tor_assert(sd); // XXXX see above
4738 tor_assert(!memcmp(ei
->cache_info
.signed_descriptor_digest
,
4739 sd
->extra_info_digest
, DIGEST_LEN
));
4741 } DIGESTMAP_FOREACH_END
;
4744 /** Allocate and return a new string representing the contact info
4745 * and platform string for <b>router</b>,
4746 * surrounded by quotes and using standard C escapes.
4748 * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
4749 * thread. Also, each call invalidates the last-returned value, so don't
4750 * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
4752 * If <b>router</b> is NULL, it just frees its internal memory and returns.
4755 esc_router_info(routerinfo_t
*router
)
4757 static char *info
=NULL
;
4758 char *esc_contact
, *esc_platform
;
4763 return NULL
; /* we're exiting; just free the memory we use */
4765 esc_contact
= esc_for_log(router
->contact_info
);
4766 esc_platform
= esc_for_log(router
->platform
);
4768 len
= strlen(esc_contact
)+strlen(esc_platform
)+32;
4769 info
= tor_malloc(len
);
4770 tor_snprintf(info
, len
, "Contact %s, Platform %s", esc_contact
,
4772 tor_free(esc_contact
);
4773 tor_free(esc_platform
);
4778 /** Helper for sorting: compare two routerinfos by their identity
4781 _compare_routerinfo_by_id_digest(const void **a
, const void **b
)
4783 routerinfo_t
*first
= *(routerinfo_t
**)a
, *second
= *(routerinfo_t
**)b
;
4784 return memcmp(first
->cache_info
.identity_digest
,
4785 second
->cache_info
.identity_digest
,
4789 /** Sort a list of routerinfo_t in ascending order of identity digest. */
4791 routers_sort_by_identity(smartlist_t
*routers
)
4793 smartlist_sort(routers
, _compare_routerinfo_by_id_digest
);
4796 /** A routerset specifies constraints on a set of possible routerinfos, based
4797 * on their names, identities, or addresses. It is optimized for determining
4798 * whether a router is a member or not, in O(1+P) time, where P is the number
4799 * of address policy constraints. */
4800 struct routerset_t
{
4801 /** A list of strings for the elements of the policy. Each string is either
4802 * a nickname, a hexadecimal identity fingerprint, or an address policy. A
4803 * router belongs to the set if its nickname OR its identity OR its address
4804 * matches an entry here. */
4806 /** A map from lowercase nicknames of routers in the set to (void*)1 */
4808 /** A map from identity digests routers in the set to (void*)1 */
4809 digestmap_t
*digests
;
4810 /** An address policy for routers in the set. For implementation reasons,
4811 * a router belongs to the set if it is _rejected_ by this policy. */
4812 smartlist_t
*policies
;
4814 /** A human-readable description of what this routerset is for. Used in
4818 /** A list of the country codes in this set. */
4819 smartlist_t
*country_names
;
4820 /** Total number of countries we knew about when we built <b>countries</b>.*/
4822 /** Bit array mapping the return value of geoip_get_country() to 1 iff the
4823 * country is a member of this routerset. Note that we MUST call
4824 * routerset_refresh_countries() whenever the geoip country list is
4826 bitarray_t
*countries
;
4829 /** Return a new empty routerset. */
4833 routerset_t
*result
= tor_malloc_zero(sizeof(routerset_t
));
4834 result
->list
= smartlist_create();
4835 result
->names
= strmap_new();
4836 result
->digests
= digestmap_new();
4837 result
->policies
= smartlist_create();
4838 result
->country_names
= smartlist_create();
4842 /** If <b>c</b> is a country code in the form {cc}, return a newly allocated
4843 * string holding the "cc" part. Else, return NULL. */
4845 routerset_get_countryname(const char *c
)
4849 if (strlen(c
) < 4 || c
[0] !='{' || c
[3] !='}')
4852 country
= tor_strndup(c
+1, 2);
4853 tor_strlower(country
);
4858 /** Add the GeoIP database's integer index (+1) of a valid two-character
4859 * country code to the routerset's <b>countries</b> bitarray. Return the
4860 * integer index if the country code is valid, -1 otherwise.*/
4862 routerset_add_country(const char *c
)
4867 /* XXXX: Country codes must be of the form \{[a-z\?]{2}\} but this accepts
4868 \{[.]{2}\}. Do we need to be strict? -RH */
4869 /* Nope; if the country code is bad, we'll get 0 when we look it up. */
4871 if (!geoip_is_loaded()) {
4872 log(LOG_WARN
, LD_CONFIG
, "GeoIP database not loaded: Cannot add country"
4873 "entry %s, ignoring.", c
);
4877 memcpy(country
, c
+1, 2);
4879 tor_strlower(country
);
4881 if ((cc
=geoip_get_country(country
))==-1) {
4882 log(LOG_WARN
, LD_CONFIG
, "Country code '%s' is not valid, ignoring.",
4889 /** Update the routerset's <b>countries</b> bitarray_t. Called whenever
4890 * the GeoIP database is reloaded.
4893 routerset_refresh_countries(routerset_t
*target
)
4896 if (target
->countries
) {
4897 bitarray_free(target
->countries
);
4899 if (!geoip_is_loaded()) {
4900 target
->countries
= NULL
;
4901 target
->n_countries
= 0;
4904 target
->n_countries
= geoip_get_n_countries();
4905 target
->countries
= bitarray_init_zero(target
->n_countries
);
4906 SMARTLIST_FOREACH_BEGIN(target
->country_names
, const char *, country
) {
4907 cc
= geoip_get_country(country
);
4909 tor_assert(cc
< target
->n_countries
);
4910 bitarray_set(target
->countries
, cc
);
4912 log(LOG_WARN
, LD_CONFIG
, "Country code '%s' is not recognized.",
4915 } SMARTLIST_FOREACH_END(country
);
4918 /** Parse the string <b>s</b> to create a set of routerset entries, and add
4919 * them to <b>target</b>. In log messages, refer to the string as
4920 * <b>description</b>. Return 0 on success, -1 on failure.
4922 * Three kinds of elements are allowed in routersets: nicknames, IP address
4923 * patterns, and fingerprints. They may be surrounded by optional space, and
4924 * mst be separated by commas.
4927 routerset_parse(routerset_t
*target
, const char *s
, const char *description
)
4930 int added_countries
= 0;
4932 smartlist_t
*list
= smartlist_create();
4933 smartlist_split_string(list
, s
, ",",
4934 SPLIT_SKIP_SPACE
| SPLIT_IGNORE_BLANK
, 0);
4935 SMARTLIST_FOREACH_BEGIN(list
, char *, nick
) {
4937 if (is_legal_hexdigest(nick
)) {
4941 log_debug(LD_CONFIG
, "Adding identity %s to %s", nick
, description
);
4942 base16_decode(d
, sizeof(d
), nick
, HEX_DIGEST_LEN
);
4943 digestmap_set(target
->digests
, d
, (void*)1);
4944 } else if (is_legal_nickname(nick
)) {
4945 log_debug(LD_CONFIG
, "Adding nickname %s to %s", nick
, description
);
4946 strmap_set_lc(target
->names
, nick
, (void*)1);
4947 } else if ((countryname
= routerset_get_countryname(nick
)) != NULL
) {
4948 log_debug(LD_CONFIG
, "Adding country %s to %s", nick
,
4950 smartlist_add(target
->country_names
, countryname
);
4951 added_countries
= 1;
4952 } else if ((strchr(nick
,'.') || strchr(nick
, '*')) &&
4953 (p
= router_parse_addr_policy_item_from_string(
4954 nick
, ADDR_POLICY_REJECT
))) {
4955 log_debug(LD_CONFIG
, "Adding address %s to %s", nick
, description
);
4956 smartlist_add(target
->policies
, p
);
4958 log_warn(LD_CONFIG
, "Entry '%s' in %s is misformed.", nick
,
4962 SMARTLIST_DEL_CURRENT(list
, nick
);
4964 } SMARTLIST_FOREACH_END(nick
);
4965 smartlist_add_all(target
->list
, list
);
4966 smartlist_free(list
);
4967 if (added_countries
)
4968 routerset_refresh_countries(target
);
4972 /** Add all members of the set <b>source</b> to <b>target</b>. */
4974 routerset_union(routerset_t
*target
, const routerset_t
*source
)
4978 if (!source
|| !source
->list
)
4980 s
= routerset_to_string(source
);
4981 routerset_parse(target
, s
, "other routerset");
4985 /** Return true iff <b>set</b> lists only nicknames and digests, and includes
4986 * no IP ranges or countries. */
4988 routerset_is_list(const routerset_t
*set
)
4990 return smartlist_len(set
->country_names
) == 0 &&
4991 smartlist_len(set
->policies
) == 0;
4994 /** Return true iff we need a GeoIP IP-to-country database to make sense of
4997 routerset_needs_geoip(const routerset_t
*set
)
4999 return set
&& smartlist_len(set
->country_names
);
5002 /** Return true iff there are no entries in <b>set</b>. */
5004 routerset_is_empty(const routerset_t
*set
)
5006 return !set
|| smartlist_len(set
->list
) == 0;
5009 /** Helper. Return true iff <b>set</b> contains a router based on the other
5010 * provided fields. Return higher values for more specific subentries: a
5011 * single router is more specific than an address range of routers, which is
5012 * more specific in turn than a country code.
5014 * (If country is -1, then we take the country
5017 routerset_contains(const routerset_t
*set
, const tor_addr_t
*addr
,
5019 const char *nickname
, const char *id_digest
, int is_named
,
5022 if (!set
|| !set
->list
) return 0;
5023 (void) is_named
; /* not supported */
5024 if (nickname
&& strmap_get_lc(set
->names
, nickname
))
5026 if (id_digest
&& digestmap_get(set
->digests
, id_digest
))
5028 if (addr
&& compare_tor_addr_to_addr_policy(addr
, orport
, set
->policies
)
5029 == ADDR_POLICY_REJECTED
)
5031 if (set
->countries
) {
5032 if (country
< 0 && addr
)
5033 country
= geoip_get_country_by_ip(tor_addr_to_ipv4h(addr
));
5035 if (country
>= 0 && country
< set
->n_countries
&&
5036 bitarray_is_set(set
->countries
, country
))
5042 /** Return true iff we can tell that <b>ei</b> is a member of <b>set</b>. */
5044 routerset_contains_extendinfo(const routerset_t
*set
, extend_info_t
*ei
)
5046 return routerset_contains(set
,
5050 ei
->identity_digest
,
5055 /** Return true iff <b>ri</b> is in <b>set</b>. */
5057 routerset_contains_router(const routerset_t
*set
, routerinfo_t
*ri
)
5060 tor_addr_from_ipv4h(&addr
, ri
->addr
);
5061 return routerset_contains(set
,
5065 ri
->cache_info
.identity_digest
,
5070 /** Return true iff <b>rs</b> is in <b>set</b>. */
5072 routerset_contains_routerstatus(const routerset_t
*set
, routerstatus_t
*rs
)
5075 tor_addr_from_ipv4h(&addr
, rs
->addr
);
5076 return routerset_contains(set
,
5080 rs
->identity_digest
,
5085 /** Add every known routerinfo_t that is a member of <b>routerset</b> to
5086 * <b>out</b>. If <b>running_only</b>, only add the running ones. */
5088 routerset_get_all_routers(smartlist_t
*out
, const routerset_t
*routerset
,
5092 if (!routerset
|| !routerset
->list
)
5094 if (!warned_nicknames
)
5095 warned_nicknames
= smartlist_create();
5096 if (routerset_is_list(routerset
)) {
5098 /* No routers are specified by type; all are given by name or digest.
5099 * we can do a lookup in O(len(list)). */
5100 SMARTLIST_FOREACH(routerset
->list
, const char *, name
, {
5101 routerinfo_t
*router
= router_get_by_nickname(name
, 1);
5103 if (!running_only
|| router
->is_running
)
5104 smartlist_add(out
, router
);
5108 /* We need to iterate over the routerlist to get all the ones of the
5110 routerlist_t
*rl
= router_get_routerlist();
5111 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, router
, {
5112 if (running_only
&& !router
->is_running
)
5114 if (routerset_contains_router(routerset
, router
))
5115 smartlist_add(out
, router
);
5120 /** Add to <b>target</b> every routerinfo_t from <b>source</b> that is in
5121 * <b>include</b>, but not excluded in a more specific fashion by
5122 * <b>exclude</b>. If <b>running_only</b>, only include running routers.
5125 routersets_get_disjunction(smartlist_t
*target
,
5126 const smartlist_t
*source
,
5127 const routerset_t
*include
,
5128 const routerset_t
*exclude
, int running_only
)
5130 SMARTLIST_FOREACH(source
, routerinfo_t
*, router
, {
5132 if (running_only
&& !router
->is_running
)
5134 if (!routerset_is_empty(include
))
5135 include_result
= routerset_contains_router(include
, router
);
5139 if (include_result
) {
5140 int exclude_result
= routerset_contains_router(exclude
, router
);
5141 if (include_result
>= exclude_result
)
5142 smartlist_add(target
, router
);
5147 /** Remove every routerinfo_t from <b>lst</b> that is in <b>routerset</b>. */
5149 routerset_subtract_routers(smartlist_t
*lst
, const routerset_t
*routerset
)
5154 SMARTLIST_FOREACH(lst
, routerinfo_t
*, r
, {
5155 if (routerset_contains_router(routerset
, r
)) {
5156 //log_debug(LD_DIR, "Subtracting %s",r->nickname);
5157 SMARTLIST_DEL_CURRENT(lst
, r
);
5162 /** Return a new string that when parsed by routerset_parse_string() will
5163 * yield <b>set</b>. */
5165 routerset_to_string(const routerset_t
*set
)
5167 if (!set
|| !set
->list
)
5168 return tor_strdup("");
5169 return smartlist_join_strings(set
->list
, ",", 0, NULL
);
5172 /** Helper: return true iff old and new are both NULL, or both non-NULL
5173 * equal routersets. */
5175 routerset_equal(const routerset_t
*old
, const routerset_t
*new)
5177 if (old
== NULL
&& new == NULL
)
5179 else if (old
== NULL
|| new == NULL
)
5182 if (smartlist_len(old
->list
) != smartlist_len(new->list
))
5185 SMARTLIST_FOREACH(old
->list
, const char *, cp1
, {
5186 const char *cp2
= smartlist_get(new->list
, cp1_sl_idx
);
5187 if (strcmp(cp1
, cp2
))
5194 /* XXXX: This won't work if the names/digests are identical but in a
5195 different order. Checking for exact equality would be heavy going,
5196 is it worth it? -RH*/
5197 /* This code is totally bogus; sizeof doesn't work even remotely like this
5198 * code seems to think. Let's revert to a string-based comparison for
5200 if (sizeof(old
->names
) != sizeof(new->names
))
5203 if (memcmp(old
->names
,new->names
,sizeof(new->names
)))
5205 if (sizeof(old
->digests
) != sizeof(new->digests
))
5207 if (memcmp(old
->digests
,new->digests
,sizeof(new->digests
)))
5209 if (sizeof(old
->countries
) != sizeof(new->countries
))
5211 if (memcmp(old
->countries
,new->countries
,sizeof(new->countries
)))
5217 /** Free all storage held in <b>routerset</b>. */
5219 routerset_free(routerset_t
*routerset
)
5221 SMARTLIST_FOREACH(routerset
->list
, char *, cp
, tor_free(cp
));
5222 smartlist_free(routerset
->list
);
5223 SMARTLIST_FOREACH(routerset
->policies
, addr_policy_t
*, p
,
5224 addr_policy_free(p
));
5225 smartlist_free(routerset
->policies
);
5226 SMARTLIST_FOREACH(routerset
->country_names
, char *, cp
, tor_free(cp
));
5227 smartlist_free(routerset
->country_names
);
5229 strmap_free(routerset
->names
, NULL
);
5230 digestmap_free(routerset
->digests
, NULL
);
5231 if (routerset
->countries
)
5232 bitarray_free(routerset
->countries
);
5233 tor_free(routerset
);
5236 /** Refresh the country code of <b>ri</b>. This function MUST be called on
5237 * each router when the GeoIP database is reloaded, and on all new routers. */
5239 routerinfo_set_country(routerinfo_t
*ri
)
5241 ri
->country
= geoip_get_country_by_ip(ri
->addr
);
5244 /** Set the country code of all routers in the routerlist. */
5246 routerlist_refresh_countries(void)
5248 routerlist_t
*rl
= router_get_routerlist();
5249 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, ri
,
5250 routerinfo_set_country(ri
));
5253 /** Determine the routers that are responsible for <b>id</b> (binary) and
5254 * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
5255 * Return -1 if we're returning an empty smartlist, else return 0.
5258 hid_serv_get_responsible_directories(smartlist_t
*responsible_dirs
,
5261 int start
, found
, n_added
= 0, i
;
5262 networkstatus_t
*c
= networkstatus_get_latest_consensus();
5263 int use_begindir
= get_options()->TunnelDirConns
;
5264 if (!c
|| !smartlist_len(c
->routerstatus_list
)) {
5265 log_warn(LD_REND
, "We don't have a consensus, so we can't perform v2 "
5266 "rendezvous operations.");
5270 start
= networkstatus_vote_find_entry_idx(c
, id
, &found
);
5271 if (start
== smartlist_len(c
->routerstatus_list
)) start
= 0;
5274 routerstatus_t
*r
= smartlist_get(c
->routerstatus_list
, i
);
5276 if (r
->dir_port
|| use_begindir
)
5277 smartlist_add(responsible_dirs
, r
);
5279 log_info(LD_REND
, "Not adding router '%s' to list of responsible "
5280 "hidden service directories, because we have no way of "
5281 "reaching it.", r
->nickname
);
5282 if (++n_added
== REND_NUMBER_OF_CONSECUTIVE_REPLICAS
)
5285 if (++i
== smartlist_len(c
->routerstatus_list
))
5287 } while (i
!= start
);
5289 /* Even though we don't have the desired number of hidden service
5290 * directories, be happy if we got any. */
5291 return smartlist_len(responsible_dirs
) ? 0 : -1;
5294 /** Return true if this node is currently acting as hidden service
5295 * directory, false otherwise. */
5297 hid_serv_acting_as_directory(void)
5299 routerinfo_t
*me
= router_get_my_routerinfo();
5304 if (!get_options()->HidServDirectoryV2
) {
5305 log_info(LD_REND
, "We are not acting as hidden service directory, "
5306 "because we have not been configured as such.");
5309 if (!(c
= networkstatus_get_latest_consensus())) {
5310 log_info(LD_REND
, "There's no consensus, so I can't tell if I'm a hidden "
5311 "service directory");
5314 rs
= networkstatus_vote_find_entry(c
, me
->cache_info
.identity_digest
);
5316 log_info(LD_REND
, "We're not listed in the consensus, so we're not "
5317 "being a hidden service directory.");
5320 if (!rs
->is_hs_dir
) {
5321 log_info(LD_REND
, "We're not listed as a hidden service directory in "
5322 "the consensus, so we won't be one.");
5328 /** Return true if this node is responsible for storing the descriptor ID
5329 * in <b>query</b> and false otherwise. */
5331 hid_serv_responsible_for_desc_id(const char *query
)
5334 routerstatus_t
*last_rs
;
5335 const char *my_id
, *last_id
;
5337 smartlist_t
*responsible
;
5338 if (!hid_serv_acting_as_directory())
5340 if (!(me
= router_get_my_routerinfo()))
5341 return 0; /* This is redundant, but let's be paranoid. */
5342 my_id
= me
->cache_info
.identity_digest
;
5343 responsible
= smartlist_create();
5344 if (hid_serv_get_responsible_directories(responsible
, query
) < 0) {
5345 smartlist_free(responsible
);
5348 last_rs
= smartlist_get(responsible
, smartlist_len(responsible
)-1);
5349 last_id
= last_rs
->identity_digest
;
5350 result
= rend_id_is_in_interval(my_id
, query
, last_id
);
5351 smartlist_free(responsible
);