1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2013, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 #define DIRSERV_PRIVATE
10 #include "confparse.h"
12 #include "channeltls.h"
14 #include "connection.h"
15 #include "connection_or.h"
17 #include "directory.h"
20 #include "hibernate.h"
21 #include "microdesc.h"
22 #include "networkstatus.h"
27 #include "routerlist.h"
28 #include "routerparse.h"
32 * \brief Directory server core implementation. Manages directory
33 * contents and generates directories.
36 /** How far in the future do we allow a router to get? (seconds) */
37 #define ROUTER_ALLOW_SKEW (60*60*12)
38 /** How many seconds do we wait before regenerating the directory? */
39 #define DIR_REGEN_SLACK_TIME 30
40 /** If we're a cache, keep this many networkstatuses around from non-trusted
41 * directory authorities. */
42 #define MAX_UNTRUSTED_NETWORKSTATUSES 16
44 /** If a v1 directory is older than this, discard it. */
45 #define MAX_V1_DIRECTORY_AGE (30*24*60*60)
46 /** If a v1 running-routers is older than this, discard it. */
47 #define MAX_V1_RR_AGE (7*24*60*60)
49 extern time_t time_of_process_start
; /* from main.c */
51 extern long stats_n_seconds_working
; /* from main.c */
53 /** Do we need to regenerate the v1 directory when someone asks for it? */
54 static time_t the_directory_is_dirty
= 1;
55 /** Do we need to regenerate the v1 runningrouters document when somebody
57 static time_t runningrouters_is_dirty
= 1;
58 /** Do we need to regenerate our v2 networkstatus document when somebody asks
60 static time_t the_v2_networkstatus_is_dirty
= 1;
62 /** Most recently generated encoded signed v1 directory. (v1 auth dirservers
64 static cached_dir_t
*the_directory
= NULL
;
66 /** For authoritative directories: the current (v1) network status. */
67 static cached_dir_t the_runningrouters
;
69 /** Array of start and end of consensus methods used for supported
70 microdescriptor formats. */
71 static const struct consensus_method_range_t
{
74 } microdesc_consensus_methods
[] = {
75 {MIN_METHOD_FOR_MICRODESC
, MIN_METHOD_FOR_A_LINES
- 1},
76 {MIN_METHOD_FOR_A_LINES
, MIN_METHOD_FOR_P6_LINES
- 1},
77 {MIN_METHOD_FOR_P6_LINES
, MIN_METHOD_FOR_NTOR_KEY
- 1},
78 {MIN_METHOD_FOR_NTOR_KEY
, MAX_SUPPORTED_CONSENSUS_METHOD
},
82 static void directory_remove_invalid(void);
83 static cached_dir_t
*dirserv_regenerate_directory(void);
84 static char *format_versions_list(config_line_t
*ln
);
85 struct authdir_config_t
;
86 static int add_fingerprint_to_dir(const char *nickname
, const char *fp
,
87 struct authdir_config_t
*list
);
89 dirserv_get_status_impl(const char *fp
, const char *nickname
,
91 uint32_t addr
, uint16_t or_port
,
92 const char *platform
, const char *contact
,
93 const char **msg
, int should_log
);
94 static void clear_cached_dir(cached_dir_t
*d
);
95 static const signed_descriptor_t
*get_signed_descriptor_by_fp(
98 time_t publish_cutoff
);
99 static was_router_added_t
dirserv_add_extrainfo(extrainfo_t
*ei
,
102 /************** Measured Bandwidth parsing code ******/
103 #define MAX_MEASUREMENT_AGE (3*24*60*60) /* 3 days */
105 /************** Fingerprint handling code ************/
107 #define FP_NAMED 1 /**< Listed in fingerprint file. */
108 #define FP_INVALID 2 /**< Believed invalid. */
109 #define FP_REJECT 4 /**< We will not publish this router. */
110 #define FP_BADDIR 8 /**< We'll tell clients to avoid using this as a dir. */
111 #define FP_BADEXIT 16 /**< We'll tell clients not to use this as an exit. */
112 #define FP_UNNAMED 32 /**< Another router has this name in fingerprint file. */
114 /** Encapsulate a nickname and an FP_* status; target of status_by_digest
116 typedef struct router_status_t
{
117 char nickname
[MAX_NICKNAME_LEN
+1];
121 /** List of nickname-\>identity fingerprint mappings for all the routers
122 * that we name. Used to prevent router impersonation. */
123 typedef struct authdir_config_t
{
124 strmap_t
*fp_by_name
; /**< Map from lc nickname to fingerprint. */
125 digestmap_t
*status_by_digest
; /**< Map from digest to router_status_t. */
128 /** Should be static; exposed for testing. */
129 static authdir_config_t
*fingerprint_list
= NULL
;
131 /** Allocate and return a new, empty, authdir_config_t. */
132 static authdir_config_t
*
133 authdir_config_new(void)
135 authdir_config_t
*list
= tor_malloc_zero(sizeof(authdir_config_t
));
136 list
->fp_by_name
= strmap_new();
137 list
->status_by_digest
= digestmap_new();
141 /** Add the fingerprint <b>fp</b> for <b>nickname</b> to
142 * the smartlist of fingerprint_entry_t's <b>list</b>. Return 0 if it's
143 * new, or 1 if we replaced the old value.
146 add_fingerprint_to_dir(const char *nickname
, const char *fp
,
147 authdir_config_t
*list
)
151 router_status_t
*status
;
152 tor_assert(nickname
);
156 fingerprint
= tor_strdup(fp
);
157 tor_strstrip(fingerprint
, " ");
158 if (base16_decode(d
, DIGEST_LEN
, fingerprint
, strlen(fingerprint
))) {
159 log_warn(LD_DIRSERV
, "Couldn't decode fingerprint \"%s\"",
161 tor_free(fingerprint
);
165 if (!strcasecmp(nickname
, UNNAMED_ROUTER_NICKNAME
)) {
166 log_warn(LD_DIRSERV
, "Tried to add a mapping for reserved nickname %s",
167 UNNAMED_ROUTER_NICKNAME
);
168 tor_free(fingerprint
);
172 status
= digestmap_get(list
->status_by_digest
, d
);
174 status
= tor_malloc_zero(sizeof(router_status_t
));
175 digestmap_set(list
->status_by_digest
, d
, status
);
178 if (nickname
[0] != '!') {
179 char *old_fp
= strmap_get_lc(list
->fp_by_name
, nickname
);
180 if (old_fp
&& !strcasecmp(fingerprint
, old_fp
)) {
181 tor_free(fingerprint
);
184 strmap_set_lc(list
->fp_by_name
, nickname
, fingerprint
);
186 status
->status
|= FP_NAMED
;
187 strlcpy(status
->nickname
, nickname
, sizeof(status
->nickname
));
189 tor_free(fingerprint
);
190 if (!strcasecmp(nickname
, "!reject")) {
191 status
->status
|= FP_REJECT
;
192 } else if (!strcasecmp(nickname
, "!invalid")) {
193 status
->status
|= FP_INVALID
;
194 } else if (!strcasecmp(nickname
, "!baddir")) {
195 status
->status
|= FP_BADDIR
;
196 } else if (!strcasecmp(nickname
, "!badexit")) {
197 status
->status
|= FP_BADEXIT
;
203 /** Add the nickname and fingerprint for this OR to the
204 * global list of recognized identity key fingerprints. */
206 dirserv_add_own_fingerprint(const char *nickname
, crypto_pk_t
*pk
)
208 char fp
[FINGERPRINT_LEN
+1];
209 if (crypto_pk_get_fingerprint(pk
, fp
, 0)<0) {
210 log_err(LD_BUG
, "Error computing fingerprint");
213 if (!fingerprint_list
)
214 fingerprint_list
= authdir_config_new();
215 add_fingerprint_to_dir(nickname
, fp
, fingerprint_list
);
219 /** Load the nickname-\>fingerprint mappings stored in the approved-routers
220 * file. The file format is line-based, with each non-blank holding one
221 * nickname, some space, and a fingerprint for that nickname. On success,
222 * replace the current fingerprint list with the new list and return 0. On
223 * failure, leave the current fingerprint list untouched, and return -1. */
225 dirserv_load_fingerprint_file(void)
229 char *nickname
, *fingerprint
;
230 authdir_config_t
*fingerprint_list_new
;
232 config_line_t
*front
=NULL
, *list
;
233 const or_options_t
*options
= get_options();
235 fname
= get_datadir_fname("approved-routers");
237 "Reloading approved fingerprints from \"%s\"...", fname
);
239 cf
= read_file_to_str(fname
, RFTS_IGNORE_MISSING
, NULL
);
241 if (options
->NamingAuthoritativeDir
) {
242 log_warn(LD_FS
, "Cannot open fingerprint file '%s'. Failing.", fname
);
246 log_info(LD_FS
, "Cannot open fingerprint file '%s'. That's ok.", fname
);
253 result
= config_get_lines(cf
, &front
, 0);
256 log_warn(LD_CONFIG
, "Error reading from fingerprint file");
260 fingerprint_list_new
= authdir_config_new();
262 for (list
=front
; list
; list
=list
->next
) {
263 char digest_tmp
[DIGEST_LEN
];
264 nickname
= list
->key
; fingerprint
= list
->value
;
265 if (strlen(nickname
) > MAX_NICKNAME_LEN
) {
266 log_notice(LD_CONFIG
,
267 "Nickname '%s' too long in fingerprint file. Skipping.",
271 if (!is_legal_nickname(nickname
) &&
272 strcasecmp(nickname
, "!reject") &&
273 strcasecmp(nickname
, "!invalid") &&
274 strcasecmp(nickname
, "!badexit")) {
275 log_notice(LD_CONFIG
,
276 "Invalid nickname '%s' in fingerprint file. Skipping.",
280 tor_strstrip(fingerprint
, " "); /* remove spaces */
281 if (strlen(fingerprint
) != HEX_DIGEST_LEN
||
282 base16_decode(digest_tmp
, sizeof(digest_tmp
),
283 fingerprint
, HEX_DIGEST_LEN
) < 0) {
284 log_notice(LD_CONFIG
,
285 "Invalid fingerprint (nickname '%s', "
286 "fingerprint %s). Skipping.",
287 nickname
, fingerprint
);
290 if (0==strcasecmp(nickname
, DEFAULT_CLIENT_NICKNAME
)) {
291 /* If you approved an OR called "client", then clients who use
292 * the default nickname could all be rejected. That's no good. */
293 log_notice(LD_CONFIG
,
294 "Authorizing nickname '%s' would break "
295 "many clients; skipping.",
296 DEFAULT_CLIENT_NICKNAME
);
299 if (0==strcasecmp(nickname
, UNNAMED_ROUTER_NICKNAME
)) {
300 /* If you approved an OR called "unnamed", then clients will be
302 log_notice(LD_CONFIG
,
303 "Authorizing nickname '%s' is not allowed; skipping.",
304 UNNAMED_ROUTER_NICKNAME
);
307 if (add_fingerprint_to_dir(nickname
, fingerprint
, fingerprint_list_new
)
309 log_notice(LD_CONFIG
, "Duplicate nickname '%s'.", nickname
);
312 config_free_lines(front
);
313 dirserv_free_fingerprint_list();
314 fingerprint_list
= fingerprint_list_new
;
315 /* Delete any routers whose fingerprints we no longer recognize */
316 directory_remove_invalid();
320 /** Check whether <b>router</b> has a nickname/identity key combination that
321 * we recognize from the fingerprint list, or an IP we automatically act on
322 * according to our configuration. Return the appropriate router status.
324 * If the status is 'FP_REJECT' and <b>msg</b> is provided, set
325 * *<b>msg</b> to an explanation of why. */
327 dirserv_router_get_status(const routerinfo_t
*router
, const char **msg
)
331 if (crypto_pk_get_digest(router
->identity_pkey
, d
)) {
332 log_warn(LD_BUG
,"Error computing fingerprint");
334 *msg
= "Bug: Error computing fingerprint";
338 return dirserv_get_status_impl(d
, router
->nickname
,
340 router
->addr
, router
->or_port
,
341 router
->platform
, router
->contact_info
,
345 /** Return true if there is no point in downloading the router described by
346 * <b>rs</b> because this directory would reject it. */
348 dirserv_would_reject_router(const routerstatus_t
*rs
)
352 res
= dirserv_get_status_impl(rs
->identity_digest
, rs
->nickname
,
353 "", /* address is only used in logs */
354 rs
->addr
, rs
->or_port
,
358 return (res
& FP_REJECT
) != 0;
361 /** Helper: Based only on the ID/Nickname combination,
362 * return FP_UNNAMED (unnamed), FP_NAMED (named), or 0 (neither).
365 dirserv_get_name_status(const char *id_digest
, const char *nickname
)
367 char fp
[HEX_DIGEST_LEN
+1];
370 base16_encode(fp
, sizeof(fp
), id_digest
, DIGEST_LEN
);
373 strmap_get_lc(fingerprint_list
->fp_by_name
, nickname
))) {
374 if (!strcasecmp(fp
, fp_by_name
)) {
377 return FP_UNNAMED
; /* Wrong fingerprint. */
383 /** Helper: As dirserv_router_get_status, but takes the router fingerprint
384 * (hex, no spaces), nickname, address (used for logging only), IP address, OR
385 * port, platform (logging only) and contact info (logging only) as arguments.
387 * If should_log is false, do not log messages. (There's not much point in
388 * logging that we're rejecting servers we'll not download.)
391 dirserv_get_status_impl(const char *id_digest
, const char *nickname
,
393 uint32_t addr
, uint16_t or_port
,
394 const char *platform
, const char *contact
,
395 const char **msg
, int should_log
)
397 int reject_unlisted
= get_options()->AuthDirRejectUnlisted
;
399 router_status_t
*status_by_digest
;
401 if (!fingerprint_list
)
402 fingerprint_list
= authdir_config_new();
405 log_debug(LD_DIRSERV
, "%d fingerprints, %d digests known.",
406 strmap_size(fingerprint_list
->fp_by_name
),
407 digestmap_size(fingerprint_list
->status_by_digest
));
409 /* Versions before Tor 0.2.2.35 have known security issues that
410 * make them unsuitable for the current network. */
411 if (platform
&& !tor_version_as_new_as(platform
,"0.2.2.35")) {
413 *msg
= "Tor version is insecure or unsupported. Please upgrade!";
415 } else if (platform
&& tor_version_as_new_as(platform
,"0.2.3.0-alpha")) {
416 /* Versions from 0.2.3-alpha...0.2.3.9-alpha have known security
417 * issues that make them unusable for the current network */
418 if (!tor_version_as_new_as(platform
, "0.2.3.10-alpha")) {
420 *msg
= "Tor version is insecure or unsupported. Please upgrade!";
425 result
= dirserv_get_name_status(id_digest
, nickname
);
426 if (result
& FP_NAMED
) {
428 log_debug(LD_DIRSERV
,"Good fingerprint for '%s'",nickname
);
430 if (result
& FP_UNNAMED
) {
432 char *esc_contact
= esc_for_log(contact
);
434 "Mismatched fingerprint for '%s'. "
435 "ContactInfo '%s', platform '%s'.)",
438 platform
? escaped(platform
) : "");
439 tor_free(esc_contact
);
442 *msg
= "Rejected: There is already a named server with this nickname "
443 "and a different fingerprint.";
446 status_by_digest
= digestmap_get(fingerprint_list
->status_by_digest
,
448 if (status_by_digest
)
449 result
|= (status_by_digest
->status
& ~FP_NAMED
);
451 if (result
& FP_REJECT
) {
453 *msg
= "Fingerprint is marked rejected";
455 } else if (result
& FP_INVALID
) {
457 *msg
= "Fingerprint is marked invalid";
460 if (authdir_policy_baddir_address(addr
, or_port
)) {
463 "Marking '%s' as bad directory because of address '%s'",
468 if (authdir_policy_badexit_address(addr
, or_port
)) {
470 log_info(LD_DIRSERV
, "Marking '%s' as bad exit because of address '%s'",
472 result
|= FP_BADEXIT
;
475 if (!(result
& FP_NAMED
)) {
476 if (!authdir_policy_permits_address(addr
, or_port
)) {
478 log_info(LD_DIRSERV
, "Rejecting '%s' because of address '%s'",
481 *msg
= "Authdir is rejecting routers in this range.";
484 if (!authdir_policy_valid_address(addr
, or_port
)) {
486 log_info(LD_DIRSERV
, "Not marking '%s' valid because of address '%s'",
488 result
|= FP_INVALID
;
490 if (reject_unlisted
) {
492 *msg
= "Authdir rejects unknown routers.";
500 /** If we are an authoritative dirserver, and the list of approved
501 * servers contains one whose identity key digest is <b>digest</b>,
502 * return that router's nickname. Otherwise return NULL. */
504 dirserv_get_nickname_by_digest(const char *digest
)
506 router_status_t
*status
;
507 if (!fingerprint_list
)
511 status
= digestmap_get(fingerprint_list
->status_by_digest
, digest
);
512 return status
? status
->nickname
: NULL
;
515 /** Clear the current fingerprint list. */
517 dirserv_free_fingerprint_list(void)
519 if (!fingerprint_list
)
522 strmap_free(fingerprint_list
->fp_by_name
, tor_free_
);
523 digestmap_free(fingerprint_list
->status_by_digest
, tor_free_
);
524 tor_free(fingerprint_list
);
531 /** Return -1 if <b>ri</b> has a private or otherwise bad address,
532 * unless we're configured to not care. Return 0 if all ok. */
534 dirserv_router_has_valid_address(routerinfo_t
*ri
)
536 struct in_addr iaddr
;
537 if (get_options()->DirAllowPrivateAddresses
)
538 return 0; /* whatever it is, we're fine with it */
539 if (!tor_inet_aton(ri
->address
, &iaddr
)) {
540 log_info(LD_DIRSERV
,"Router %s published non-IP address '%s'. Refusing.",
545 if (is_internal_IP(ntohl(iaddr
.s_addr
), 0)) {
547 "Router %s published internal IP address '%s'. Refusing.",
548 router_describe(ri
), ri
->address
);
549 return -1; /* it's a private IP, we should reject it */
554 /** Check whether we, as a directory server, want to accept <b>ri</b>. If so,
555 * set its is_valid,named,running fields and return 0. Otherwise, return -1.
557 * If the router is rejected, set *<b>msg</b> to an explanation of why.
559 * If <b>complain</b> then explain at log-level 'notice' why we refused
560 * a descriptor; else explain at log-level 'info'.
563 authdir_wants_to_reject_router(routerinfo_t
*ri
, const char **msg
,
564 int complain
, int *valid_out
)
566 /* Okay. Now check whether the fingerprint is recognized. */
567 uint32_t status
= dirserv_router_get_status(ri
, msg
);
569 int severity
= (complain
&& ri
->contact_info
) ? LOG_NOTICE
: LOG_INFO
;
571 if (status
& FP_REJECT
)
572 return -1; /* msg is already set. */
574 /* Is there too much clock skew? */
576 if (ri
->cache_info
.published_on
> now
+ROUTER_ALLOW_SKEW
) {
577 log_fn(severity
, LD_DIRSERV
, "Publication time for %s is too "
578 "far (%d minutes) in the future; possible clock skew. Not adding "
581 (int)((ri
->cache_info
.published_on
-now
)/60),
582 esc_router_info(ri
));
583 *msg
= "Rejected: Your clock is set too far in the future, or your "
584 "timezone is not correct.";
587 if (ri
->cache_info
.published_on
< now
-ROUTER_MAX_AGE_TO_PUBLISH
) {
588 log_fn(severity
, LD_DIRSERV
,
589 "Publication time for %s is too far "
590 "(%d minutes) in the past. Not adding (%s)",
592 (int)((now
-ri
->cache_info
.published_on
)/60),
593 esc_router_info(ri
));
594 *msg
= "Rejected: Server is expired, or your clock is too far in the past,"
595 " or your timezone is not correct.";
598 if (dirserv_router_has_valid_address(ri
) < 0) {
599 log_fn(severity
, LD_DIRSERV
,
600 "Router %s has invalid address '%s'. "
604 esc_router_info(ri
));
605 *msg
= "Rejected: Address is not an IP, or IP is a private address.";
609 *valid_out
= ! (status
& FP_INVALID
);
614 /** Update the relevant flags of <b>node</b> based on our opinion as a
615 * directory authority in <b>authstatus</b>, as returned by
616 * dirserv_router_get_status or equivalent. */
618 dirserv_set_node_flags_from_authoritative_status(node_t
*node
,
621 node
->is_valid
= (authstatus
& FP_INVALID
) ? 0 : 1;
622 node
->is_bad_directory
= (authstatus
& FP_BADDIR
) ? 1 : 0;
623 node
->is_bad_exit
= (authstatus
& FP_BADEXIT
) ? 1 : 0;
626 /** True iff <b>a</b> is more severe than <b>b</b>. */
628 WRA_MORE_SEVERE(was_router_added_t a
, was_router_added_t b
)
633 /** As for dirserv_add_descriptor(), but accepts multiple documents, and
634 * returns the most severe error that occurred for any one of them. */
636 dirserv_add_multiple_descriptors(const char *desc
, uint8_t purpose
,
640 was_router_added_t r
, r_tmp
;
645 time_t now
= time(NULL
);
646 char annotation_buf
[ROUTER_ANNOTATION_BUF_LEN
];
647 char time_buf
[ISO_TIME_LEN
+1];
648 int general
= purpose
== ROUTER_PURPOSE_GENERAL
;
651 r
=ROUTER_ADDED_SUCCESSFULLY
; /*Least severe return value. */
653 format_iso_time(time_buf
, now
);
654 if (tor_snprintf(annotation_buf
, sizeof(annotation_buf
),
657 "%s%s%s", time_buf
, escaped(source
),
658 !general
? "@purpose " : "",
659 !general
? router_purpose_to_string(purpose
) : "",
660 !general
? "\n" : "")<0) {
661 *msg
= "Couldn't format annotations";
666 list
= smartlist_new();
667 if (!router_parse_list_from_string(&s
, NULL
, list
, SAVED_NOWHERE
, 0, 0,
669 SMARTLIST_FOREACH(list
, routerinfo_t
*, ri
, {
671 tor_assert(ri
->purpose
== purpose
);
672 r_tmp
= dirserv_add_descriptor(ri
, &msg_out
, source
);
673 if (WRA_MORE_SEVERE(r_tmp
, r
)) {
679 n_parsed
+= smartlist_len(list
);
680 smartlist_clear(list
);
683 if (!router_parse_list_from_string(&s
, NULL
, list
, SAVED_NOWHERE
, 1, 0,
685 SMARTLIST_FOREACH(list
, extrainfo_t
*, ei
, {
688 r_tmp
= dirserv_add_extrainfo(ei
, &msg_out
);
689 if (WRA_MORE_SEVERE(r_tmp
, r
)) {
695 n_parsed
+= smartlist_len(list
);
696 smartlist_free(list
);
700 *msg
= "No descriptors found in your POST.";
701 if (WRA_WAS_ADDED(r
))
702 r
= ROUTER_WAS_NOT_NEW
;
704 *msg
= "(no message)";
711 /** Examine the parsed server descriptor in <b>ri</b> and maybe insert it into
712 * the list of server descriptors. Set *<b>msg</b> to a message that should be
713 * passed back to the origin of this descriptor, or NULL if there is no such
714 * message. Use <b>source</b> to produce better log messages.
716 * Return the status of the operation
718 * This function is only called when fresh descriptors are posted, not when
719 * we re-load the cache.
722 dirserv_add_descriptor(routerinfo_t
*ri
, const char **msg
, const char *source
)
724 was_router_added_t r
;
725 routerinfo_t
*ri_old
;
726 char *desc
, *nickname
;
730 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
731 * network and it'll clog everything up. */
732 if (ri
->cache_info
.signed_descriptor_len
> MAX_DESCRIPTOR_UPLOAD_SIZE
) {
733 log_notice(LD_DIR
, "Somebody attempted to publish a router descriptor '%s'"
734 " (source: %s) with size %d. Either this is an attack, or the "
735 "MAX_DESCRIPTOR_UPLOAD_SIZE (%d) constant is too low.",
736 ri
->nickname
, source
, (int)ri
->cache_info
.signed_descriptor_len
,
737 MAX_DESCRIPTOR_UPLOAD_SIZE
);
738 *msg
= "Router descriptor was too large.";
739 control_event_or_authdir_new_descriptor("REJECTED",
740 ri
->cache_info
.signed_descriptor_body
,
741 ri
->cache_info
.signed_descriptor_len
, *msg
);
743 return ROUTER_AUTHDIR_REJECTS
;
746 /* Check whether this descriptor is semantically identical to the last one
747 * from this server. (We do this here and not in router_add_to_routerlist
748 * because we want to be able to accept the newest router descriptor that
749 * another authority has, so we all converge on the same one.) */
750 ri_old
= router_get_mutable_by_digest(ri
->cache_info
.identity_digest
);
751 if (ri_old
&& ri_old
->cache_info
.published_on
< ri
->cache_info
.published_on
752 && router_differences_are_cosmetic(ri_old
, ri
)
753 && !router_is_me(ri
)) {
755 "Not replacing descriptor from %s (source: %s); "
756 "differences are cosmetic.",
757 router_describe(ri
), source
);
758 *msg
= "Not replacing router descriptor; no information has changed since "
759 "the last one with this identity.";
760 control_event_or_authdir_new_descriptor("DROPPED",
761 ri
->cache_info
.signed_descriptor_body
,
762 ri
->cache_info
.signed_descriptor_len
, *msg
);
764 return ROUTER_WAS_NOT_NEW
;
767 /* Make a copy of desc, since router_add_to_routerlist might free
768 * ri and its associated signed_descriptor_t. */
769 desclen
= ri
->cache_info
.signed_descriptor_len
;
770 desc
= tor_strndup(ri
->cache_info
.signed_descriptor_body
, desclen
);
771 nickname
= tor_strdup(ri
->nickname
);
773 /* Tell if we're about to need to launch a test if we add this. */
774 ri
->needs_retest_if_added
=
775 dirserv_should_launch_reachability_test(ri
, ri_old
);
777 r
= router_add_to_routerlist(ri
, msg
, 0, 0);
778 if (!WRA_WAS_ADDED(r
)) {
779 /* unless the routerinfo was fine, just out-of-date */
780 if (WRA_WAS_REJECTED(r
))
781 control_event_or_authdir_new_descriptor("REJECTED", desc
, desclen
, *msg
);
783 "Did not add descriptor from '%s' (source: %s): %s.",
784 nickname
, source
, *msg
? *msg
: "(no message)");
786 smartlist_t
*changed
;
787 control_event_or_authdir_new_descriptor("ACCEPTED", desc
, desclen
, *msg
);
789 changed
= smartlist_new();
790 smartlist_add(changed
, ri
);
791 routerlist_descriptors_added(changed
, 0);
792 smartlist_free(changed
);
794 *msg
= "Descriptor accepted";
797 "Added descriptor from '%s' (source: %s): %s.",
798 nickname
, source
, *msg
);
805 /** As dirserv_add_descriptor, but for an extrainfo_t <b>ei</b>. */
806 static was_router_added_t
807 dirserv_add_extrainfo(extrainfo_t
*ei
, const char **msg
)
809 const routerinfo_t
*ri
;
814 ri
= router_get_by_id_digest(ei
->cache_info
.identity_digest
);
816 *msg
= "No corresponding router descriptor for extra-info descriptor";
818 return ROUTER_BAD_EI
;
821 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
822 * network and it'll clog everything up. */
823 if (ei
->cache_info
.signed_descriptor_len
> MAX_EXTRAINFO_UPLOAD_SIZE
) {
824 log_notice(LD_DIR
, "Somebody attempted to publish an extrainfo "
825 "with size %d. Either this is an attack, or the "
826 "MAX_EXTRAINFO_UPLOAD_SIZE (%d) constant is too low.",
827 (int)ei
->cache_info
.signed_descriptor_len
,
828 MAX_EXTRAINFO_UPLOAD_SIZE
);
829 *msg
= "Extrainfo document was too large";
831 return ROUTER_BAD_EI
;
834 if ((r
= routerinfo_incompatible_with_extrainfo(ri
, ei
, NULL
, msg
))) {
836 return r
< 0 ? ROUTER_WAS_NOT_NEW
: ROUTER_BAD_EI
;
838 router_add_extrainfo_to_routerlist(ei
, msg
, 0, 0);
839 return ROUTER_ADDED_SUCCESSFULLY
;
842 /** Remove all descriptors whose nicknames or fingerprints no longer
843 * are allowed by our fingerprint list. (Descriptors that used to be
844 * good can become bad when we reload the fingerprint list.)
847 directory_remove_invalid(void)
850 routerlist_t
*rl
= router_get_routerlist();
851 smartlist_t
*nodes
= smartlist_new();
852 smartlist_add_all(nodes
, nodelist_get_list());
854 SMARTLIST_FOREACH_BEGIN(nodes
, node_t
*, node
) {
856 routerinfo_t
*ent
= node
->ri
;
857 char description
[NODE_DESC_BUF_LEN
];
861 r
= dirserv_router_get_status(ent
, &msg
);
862 router_get_description(description
, ent
);
864 log_info(LD_DIRSERV
, "Router %s is now rejected: %s",
865 description
, msg
?msg
:"");
866 routerlist_remove(rl
, ent
, 0, time(NULL
));
871 if (bool_neq((r
& FP_NAMED
), ent
->auth_says_is_named
)) {
873 "Router %s is now %snamed.", description
,
874 (r
&FP_NAMED
)?"":"un");
875 ent
->is_named
= (r
&FP_NAMED
)?1:0;
878 if (bool_neq((r
& FP_UNNAMED
), ent
->auth_says_is_unnamed
)) {
880 "Router '%s' is now %snamed. (FP_UNNAMED)", description
,
881 (r
&FP_NAMED
)?"":"un");
882 ent
->is_named
= (r
&FP_NUNAMED
)?0:1;
886 if (bool_neq((r
& FP_INVALID
), !node
->is_valid
)) {
887 log_info(LD_DIRSERV
, "Router '%s' is now %svalid.", description
,
888 (r
&FP_INVALID
) ? "in" : "");
889 node
->is_valid
= (r
&FP_INVALID
)?0:1;
892 if (bool_neq((r
& FP_BADDIR
), node
->is_bad_directory
)) {
893 log_info(LD_DIRSERV
, "Router '%s' is now a %s directory", description
,
894 (r
& FP_BADDIR
) ? "bad" : "good");
895 node
->is_bad_directory
= (r
&FP_BADDIR
) ? 1: 0;
898 if (bool_neq((r
& FP_BADEXIT
), node
->is_bad_exit
)) {
899 log_info(LD_DIRSERV
, "Router '%s' is now a %s exit", description
,
900 (r
& FP_BADEXIT
) ? "bad" : "good");
901 node
->is_bad_exit
= (r
&FP_BADEXIT
) ? 1: 0;
904 } SMARTLIST_FOREACH_END(node
);
906 directory_set_dirty();
908 routerlist_assert_ok(rl
);
909 smartlist_free(nodes
);
912 /** Mark the directory as <b>dirty</b> -- when we're next asked for a
913 * directory, we will rebuild it instead of reusing the most recently
917 directory_set_dirty(void)
919 time_t now
= time(NULL
);
922 /* Regenerate stubs only every 8 hours.
923 * XXXX It would be nice to generate less often, but these are just
924 * stubs: it doesn't matter. */
925 #define STUB_REGENERATE_INTERVAL (8*60*60)
926 if (!the_directory
|| !the_runningrouters
.dir
)
928 else if (the_directory
->published
< now
- STUB_REGENERATE_INTERVAL
||
929 the_runningrouters
.published
< now
- STUB_REGENERATE_INTERVAL
)
933 if (!the_directory_is_dirty
)
934 the_directory_is_dirty
= now
;
935 if (!runningrouters_is_dirty
)
936 runningrouters_is_dirty
= now
;
938 if (!the_v2_networkstatus_is_dirty
)
939 the_v2_networkstatus_is_dirty
= now
;
943 * Allocate and return a description of the status of the server <b>desc</b>,
944 * for use in a v1-style router-status line. The server is listed
945 * as running iff <b>is_live</b> is true.
948 list_single_server_status(const routerinfo_t
*desc
, int is_live
)
950 char buf
[MAX_NICKNAME_LEN
+HEX_DIGEST_LEN
+4]; /* !nickname=$hexdigest\0 */
960 node
= node_get_by_id(desc
->cache_info
.identity_digest
);
961 if (node
&& node
->is_valid
) {
962 strlcpy(cp
, desc
->nickname
, sizeof(buf
)-(cp
-buf
));
967 base16_encode(cp
, HEX_DIGEST_LEN
+1, desc
->cache_info
.identity_digest
,
969 return tor_strdup(buf
);
972 /* DOCDOC running_long_enough_to_decide_unreachable */
974 running_long_enough_to_decide_unreachable(void)
976 return time_of_process_start
977 + get_options()->TestingAuthDirTimeToLearnReachability
< approx_time();
980 /** Each server needs to have passed a reachability test no more
981 * than this number of seconds ago, or he is listed as down in
983 #define REACHABLE_TIMEOUT (45*60)
985 /** If we tested a router and found it reachable _at least this long_ after it
986 * declared itself hibernating, it is probably done hibernating and we just
987 * missed a descriptor from it. */
988 #define HIBERNATION_PUBLICATION_SKEW (60*60)
990 /** Treat a router as alive if
991 * - It's me, and I'm not hibernating.
992 * or - We've found it reachable recently. */
994 dirserv_set_router_is_running(routerinfo_t
*router
, time_t now
)
996 /*XXXX024 This function is a mess. Separate out the part that calculates
997 whether it's reachable and the part that tells rephist that the router was
1001 const or_options_t
*options
= get_options();
1002 node_t
*node
= node_get_mutable_by_id(router
->cache_info
.identity_digest
);
1005 if (router_is_me(router
)) {
1006 /* We always know if we are down ourselves. */
1007 answer
= ! we_are_hibernating();
1008 } else if (router
->is_hibernating
&&
1009 (router
->cache_info
.published_on
+
1010 HIBERNATION_PUBLICATION_SKEW
) > node
->last_reachable
) {
1011 /* A hibernating router is down unless we (somehow) had contact with it
1012 * since it declared itself to be hibernating. */
1014 } else if (options
->AssumeReachable
) {
1015 /* If AssumeReachable, everybody is up unless they say they are down! */
1018 /* Otherwise, a router counts as up if we found all announced OR
1019 ports reachable in the last REACHABLE_TIMEOUT seconds.
1021 XXX prop186 For now there's always one IPv4 and at most one
1024 If we're not on IPv6, don't consider reachability of potential
1025 IPv6 OR port since that'd kill all dual stack relays until a
1026 majority of the dir auths have IPv6 connectivity. */
1027 answer
= (now
< node
->last_reachable
+ REACHABLE_TIMEOUT
&&
1028 (options
->AuthDirHasIPv6Connectivity
!= 1 ||
1029 tor_addr_is_null(&router
->ipv6_addr
) ||
1030 now
< node
->last_reachable6
+ REACHABLE_TIMEOUT
));
1033 if (!answer
&& running_long_enough_to_decide_unreachable()) {
1034 /* Not considered reachable. tell rephist about that.
1036 Because we launch a reachability test for each router every
1037 REACHABILITY_TEST_CYCLE_PERIOD seconds, then the router has probably
1038 been down since at least that time after we last successfully reached
1044 if (node
->last_reachable
&&
1045 node
->last_reachable
+ REACHABILITY_TEST_CYCLE_PERIOD
< now
)
1046 when
= node
->last_reachable
+ REACHABILITY_TEST_CYCLE_PERIOD
;
1047 rep_hist_note_router_unreachable(router
->cache_info
.identity_digest
, when
);
1050 node
->is_running
= answer
;
1053 /** Based on the routerinfo_ts in <b>routers</b>, allocate the
1054 * contents of a v1-style router-status line, and store it in
1055 * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
1057 * If for_controller is true, include the routers with very old descriptors.
1060 list_server_status_v1(smartlist_t
*routers
, char **router_status_out
,
1063 /* List of entries in a router-status style: An optional !, then an optional
1064 * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
1065 smartlist_t
*rs_entries
;
1066 time_t now
= time(NULL
);
1067 time_t cutoff
= now
- ROUTER_MAX_AGE_TO_PUBLISH
;
1068 const or_options_t
*options
= get_options();
1069 /* We include v2 dir auths here too, because they need to answer
1070 * controllers. Eventually we'll deprecate this whole function;
1071 * see also networkstatus_getinfo_by_purpose(). */
1072 int authdir
= authdir_mode_publishes_statuses(options
);
1073 tor_assert(router_status_out
);
1075 rs_entries
= smartlist_new();
1077 SMARTLIST_FOREACH_BEGIN(routers
, routerinfo_t
*, ri
) {
1078 const node_t
*node
= node_get_by_id(ri
->cache_info
.identity_digest
);
1081 /* Update router status in routerinfo_t. */
1082 dirserv_set_router_is_running(ri
, now
);
1084 if (for_controller
) {
1085 char name_buf
[MAX_VERBOSE_NICKNAME_LEN
+2];
1086 char *cp
= name_buf
;
1087 if (!node
->is_running
)
1089 router_get_verbose_nickname(cp
, ri
);
1090 smartlist_add(rs_entries
, tor_strdup(name_buf
));
1091 } else if (ri
->cache_info
.published_on
>= cutoff
) {
1092 smartlist_add(rs_entries
, list_single_server_status(ri
,
1095 } SMARTLIST_FOREACH_END(ri
);
1097 *router_status_out
= smartlist_join_strings(rs_entries
, " ", 0, NULL
);
1099 SMARTLIST_FOREACH(rs_entries
, char *, cp
, tor_free(cp
));
1100 smartlist_free(rs_entries
);
1105 /** Given a (possibly empty) list of config_line_t, each line of which contains
1106 * a list of comma-separated version numbers surrounded by optional space,
1107 * allocate and return a new string containing the version numbers, in order,
1108 * separated by commas. Used to generate Recommended(Client|Server)?Versions
1111 format_versions_list(config_line_t
*ln
)
1113 smartlist_t
*versions
;
1115 versions
= smartlist_new();
1116 for ( ; ln
; ln
= ln
->next
) {
1117 smartlist_split_string(versions
, ln
->value
, ",",
1118 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1120 sort_version_list(versions
, 1);
1121 result
= smartlist_join_strings(versions
,",",0,NULL
);
1122 SMARTLIST_FOREACH(versions
,char *,s
,tor_free(s
));
1123 smartlist_free(versions
);
1127 /** Return 1 if <b>ri</b>'s descriptor is "active" -- running, valid,
1128 * not hibernating, and not too old. Else return 0.
1131 router_is_active(const routerinfo_t
*ri
, const node_t
*node
, time_t now
)
1133 time_t cutoff
= now
- ROUTER_MAX_AGE_TO_PUBLISH
;
1134 if (ri
->cache_info
.published_on
< cutoff
)
1136 if (!node
->is_running
|| !node
->is_valid
|| ri
->is_hibernating
)
1141 /** Generate a new v1 directory and write it into a newly allocated string.
1142 * Point *<b>dir_out</b> to the allocated string. Sign the
1143 * directory with <b>private_key</b>. Return 0 on success, -1 on
1144 * failure. If <b>complete</b> is set, give us all the descriptors;
1145 * otherwise leave out non-running and non-valid ones.
1148 dirserv_dump_directory_to_string(char **dir_out
,
1149 crypto_pk_t
*private_key
)
1151 /* XXXX 024 Get rid of this function if we can confirm that nobody's
1152 * fetching these any longer */
1154 char *identity_pkey
; /* Identity key, DER64-encoded. */
1155 char *recommended_versions
;
1156 char digest
[DIGEST_LEN
];
1157 char published
[ISO_TIME_LEN
+1];
1160 size_t identity_pkey_len
;
1161 time_t now
= time(NULL
);
1163 tor_assert(dir_out
);
1166 if (crypto_pk_write_public_key_to_string(private_key
,&identity_pkey
,
1167 &identity_pkey_len
)<0) {
1168 log_warn(LD_BUG
,"write identity_pkey to string failed!");
1172 recommended_versions
=
1173 format_versions_list(get_options()->RecommendedVersions
);
1175 format_iso_time(published
, now
);
1177 buf_len
= 2048+strlen(recommended_versions
);
1179 buf
= tor_malloc(buf_len
);
1180 /* We'll be comparing against buf_len throughout the rest of the
1181 function, though strictly speaking we shouldn't be able to exceed
1182 it. This is C, after all, so we may as well check for buffer
1185 tor_snprintf(buf
, buf_len
,
1186 "signed-directory\n"
1188 "recommended-software %s\n"
1189 "router-status %s\n"
1190 "dir-signing-key\n%s\n",
1191 published
, recommended_versions
, "",
1194 tor_free(recommended_versions
);
1195 tor_free(identity_pkey
);
1197 cp
= buf
+ strlen(buf
);
1200 /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
1202 if (strlcat(buf
, "directory-signature ", buf_len
) >= buf_len
)
1204 if (strlcat(buf
, get_options()->Nickname
, buf_len
) >= buf_len
)
1206 if (strlcat(buf
, "\n", buf_len
) >= buf_len
)
1209 if (router_get_dir_hash(buf
,digest
)) {
1210 log_warn(LD_BUG
,"couldn't compute digest");
1214 note_crypto_pk_op(SIGN_DIR
);
1215 if (router_append_dirobj_signature(buf
,buf_len
,digest
,DIGEST_LEN
,
1224 log_warn(LD_BUG
,"tried to exceed string length.");
1229 /********************************************************************/
1231 /* A set of functions to answer questions about how we'd like to behave
1232 * as a directory mirror/client. */
1234 /** Return 1 if we fetch our directory material directly from the
1235 * authorities, rather than from a mirror. */
1237 directory_fetches_from_authorities(const or_options_t
*options
)
1239 const routerinfo_t
*me
;
1242 if (options
->FetchDirInfoEarly
)
1244 if (options
->BridgeRelay
== 1)
1246 if (server_mode(options
) && router_pick_published_address(options
, &addr
)<0)
1247 return 1; /* we don't know our IP address; ask an authority. */
1248 refuseunknown
= ! router_my_exit_policy_is_reject_star() &&
1249 should_refuse_unknown_exits(options
);
1250 if (!options
->DirPort_set
&& !refuseunknown
)
1252 if (!server_mode(options
) || !advertised_server_mode())
1254 me
= router_get_my_routerinfo();
1255 if (!me
|| (!me
->dir_port
&& !refuseunknown
))
1256 return 0; /* if dirport not advertised, return 0 too */
1260 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1261 * on the "mirror" schedule rather than the "client" schedule.
1264 directory_fetches_dir_info_early(const or_options_t
*options
)
1266 return directory_fetches_from_authorities(options
);
1269 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1270 * on a very passive schedule -- waiting long enough for ordinary clients
1271 * to probably have the info we want. These would include bridge users,
1272 * and maybe others in the future e.g. if a Tor client uses another Tor
1273 * client as a directory guard.
1276 directory_fetches_dir_info_later(const or_options_t
*options
)
1278 return options
->UseBridges
!= 0;
1281 /** Return 1 if we want to cache v2 dir info (each status file).
1284 directory_caches_v2_dir_info(const or_options_t
*options
)
1286 return options
->DirPort_set
;
1289 /** Return true iff we want to fetch and keep certificates for authorities
1290 * that we don't acknowledge as aurthorities ourself.
1293 directory_caches_unknown_auth_certs(const or_options_t
*options
)
1295 return options
->DirPort_set
|| options
->BridgeRelay
;
1298 /** Return 1 if we want to keep descriptors, networkstatuses, etc around
1299 * and we're willing to serve them to others. Else return 0.
1302 directory_caches_dir_info(const or_options_t
*options
)
1304 if (options
->BridgeRelay
|| options
->DirPort_set
)
1306 if (!server_mode(options
) || !advertised_server_mode())
1308 /* We need an up-to-date view of network info if we're going to try to
1309 * block exit attempts from unknown relays. */
1310 return ! router_my_exit_policy_is_reject_star() &&
1311 should_refuse_unknown_exits(options
);
1314 /** Return 1 if we want to allow remote people to ask us directory
1315 * requests via the "begin_dir" interface, which doesn't require
1316 * having any separate port open. */
1318 directory_permits_begindir_requests(const or_options_t
*options
)
1320 return options
->BridgeRelay
!= 0 || options
->DirPort_set
;
1323 /** Return 1 if we want to allow controllers to ask us directory
1324 * requests via the controller interface, which doesn't require
1325 * having any separate port open. */
1327 directory_permits_controller_requests(const or_options_t
*options
)
1329 return options
->DirPort_set
;
1332 /** Return 1 if we have no need to fetch new descriptors. This generally
1333 * happens when we're not a dir cache and we haven't built any circuits
1337 directory_too_idle_to_fetch_descriptors(const or_options_t
*options
,
1340 return !directory_caches_dir_info(options
) &&
1341 !options
->FetchUselessDescriptors
&&
1342 rep_hist_circbuilding_dormant(now
);
1345 /********************************************************************/
1347 /* Used only by non-v1-auth dirservers: The v1 directory and
1348 * runningrouters we'll serve when requested. */
1350 /** The v1 directory we'll serve (as a cache or as an authority) if
1352 static cached_dir_t
*cached_directory
= NULL
;
1353 /** The v1 runningrouters document we'll serve (as a cache or as an authority)
1355 static cached_dir_t cached_runningrouters
;
1357 /** Used for other dirservers' v2 network statuses. Map from hexdigest to
1359 static digestmap_t
*cached_v2_networkstatus
= NULL
;
1361 /** Map from flavor name to the cached_dir_t for the v3 consensuses that we're
1362 * currently serving. */
1363 static strmap_t
*cached_consensuses
= NULL
;
1365 /** Possibly replace the contents of <b>d</b> with the value of
1366 * <b>directory</b> published on <b>when</b>, unless <b>when</b> is older than
1367 * the last value, or too far in the future.
1369 * Does not copy <b>directory</b>; frees it if it isn't used.
1372 set_cached_dir(cached_dir_t
*d
, char *directory
, time_t when
)
1374 time_t now
= time(NULL
);
1375 if (when
<=d
->published
) {
1376 log_info(LD_DIRSERV
, "Ignoring old directory; not caching.");
1377 tor_free(directory
);
1378 } else if (when
>=now
+ROUTER_MAX_AGE_TO_PUBLISH
) {
1379 log_info(LD_DIRSERV
, "Ignoring future directory; not caching.");
1380 tor_free(directory
);
1382 /* if (when>d->published && when<now+ROUTER_MAX_AGE) */
1383 log_debug(LD_DIRSERV
, "Caching directory.");
1386 d
->dir_len
= strlen(directory
);
1388 if (tor_gzip_compress(&(d
->dir_z
), &(d
->dir_z_len
), d
->dir
, d
->dir_len
,
1390 log_warn(LD_BUG
,"Error compressing cached directory");
1392 d
->published
= when
;
1396 /** Decrement the reference count on <b>d</b>, and free it if it no longer has
1397 * any references. */
1399 cached_dir_decref(cached_dir_t
*d
)
1401 if (!d
|| --d
->refcnt
> 0)
1403 clear_cached_dir(d
);
1407 /** Allocate and return a new cached_dir_t containing the string <b>s</b>,
1408 * published at <b>published</b>. */
1410 new_cached_dir(char *s
, time_t published
)
1412 cached_dir_t
*d
= tor_malloc_zero(sizeof(cached_dir_t
));
1415 d
->dir_len
= strlen(s
);
1416 d
->published
= published
;
1417 if (tor_gzip_compress(&(d
->dir_z
), &(d
->dir_z_len
), d
->dir
, d
->dir_len
,
1419 log_warn(LD_BUG
, "Error compressing directory");
1424 /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
1426 clear_cached_dir(cached_dir_t
*d
)
1430 memset(d
, 0, sizeof(cached_dir_t
));
1433 /** Free all storage held by the cached_dir_t in <b>d</b>. */
1435 free_cached_dir_(void *_d
)
1441 d
= (cached_dir_t
*)_d
;
1442 cached_dir_decref(d
);
1445 /** If we have no cached v1 directory, or it is older than <b>published</b>,
1446 * then replace it with <b>directory</b>, published at <b>published</b>.
1448 * If <b>published</b> is too old, do nothing.
1450 * If <b>is_running_routers</b>, this is really a v1 running_routers
1451 * document rather than a v1 directory.
1454 dirserv_set_cached_directory(const char *directory
, time_t published
)
1457 cached_dir_decref(cached_directory
);
1458 cached_directory
= new_cached_dir(tor_strdup(directory
), published
);
1461 /** If <b>networkstatus</b> is non-NULL, we've just received a v2
1462 * network-status for an authoritative directory with identity digest
1463 * <b>identity</b> published at <b>published</b> -- store it so we can
1464 * serve it to others.
1466 * If <b>networkstatus</b> is NULL, remove the entry with the given
1467 * identity fingerprint from the v2 cache.
1470 dirserv_set_cached_networkstatus_v2(const char *networkstatus
,
1471 const char *identity
,
1474 cached_dir_t
*d
, *old_d
;
1475 if (!cached_v2_networkstatus
)
1476 cached_v2_networkstatus
= digestmap_new();
1478 old_d
= digestmap_get(cached_v2_networkstatus
, identity
);
1479 if (!old_d
&& !networkstatus
)
1482 if (networkstatus
) {
1483 if (!old_d
|| published
> old_d
->published
) {
1484 d
= new_cached_dir(tor_strdup(networkstatus
), published
);
1485 digestmap_set(cached_v2_networkstatus
, identity
, d
);
1487 cached_dir_decref(old_d
);
1491 digestmap_remove(cached_v2_networkstatus
, identity
);
1492 cached_dir_decref(old_d
);
1496 /* Now purge old entries. */
1498 if (digestmap_size(cached_v2_networkstatus
) >
1499 get_n_authorities(V2_DIRINFO
) + MAX_UNTRUSTED_NETWORKSTATUSES
) {
1500 /* We need to remove the oldest untrusted networkstatus. */
1501 const char *oldest
= NULL
;
1502 time_t oldest_published
= TIME_MAX
;
1503 digestmap_iter_t
*iter
;
1505 for (iter
= digestmap_iter_init(cached_v2_networkstatus
);
1506 !digestmap_iter_done(iter
);
1507 iter
= digestmap_iter_next(cached_v2_networkstatus
, iter
)) {
1510 digestmap_iter_get(iter
, &ident
, &val
);
1512 if (d
->published
< oldest_published
&&
1513 !router_digest_is_trusted_dir(ident
)) {
1515 oldest_published
= d
->published
;
1519 d
= digestmap_remove(cached_v2_networkstatus
, oldest
);
1521 cached_dir_decref(d
);
1525 /** Replace the v3 consensus networkstatus of type <b>flavor_name</b> that
1526 * we're serving with <b>networkstatus</b>, published at <b>published</b>. No
1527 * validation is performed. */
1529 dirserv_set_cached_consensus_networkstatus(const char *networkstatus
,
1530 const char *flavor_name
,
1531 const digests_t
*digests
,
1534 cached_dir_t
*new_networkstatus
;
1535 cached_dir_t
*old_networkstatus
;
1536 if (!cached_consensuses
)
1537 cached_consensuses
= strmap_new();
1539 new_networkstatus
= new_cached_dir(tor_strdup(networkstatus
), published
);
1540 memcpy(&new_networkstatus
->digests
, digests
, sizeof(digests_t
));
1541 old_networkstatus
= strmap_set(cached_consensuses
, flavor_name
,
1543 if (old_networkstatus
)
1544 cached_dir_decref(old_networkstatus
);
1547 /** Remove any v2 networkstatus from the directory cache that was published
1548 * before <b>cutoff</b>. */
1550 dirserv_clear_old_networkstatuses(time_t cutoff
)
1552 if (!cached_v2_networkstatus
)
1555 DIGESTMAP_FOREACH_MODIFY(cached_v2_networkstatus
, id
, cached_dir_t
*, dir
) {
1556 if (dir
->published
< cutoff
) {
1558 fname
= networkstatus_get_cache_filename(id
);
1559 if (file_status(fname
) == FN_FILE
) {
1560 log_info(LD_DIR
, "Removing too-old untrusted networkstatus in %s",
1565 cached_dir_decref(dir
);
1566 MAP_DEL_CURRENT(id
);
1568 } DIGESTMAP_FOREACH_END
1571 /** Remove any v1 info from the directory cache that was published
1574 dirserv_clear_old_v1_info(time_t now
)
1576 if (cached_directory
&&
1577 cached_directory
->published
< (now
- MAX_V1_DIRECTORY_AGE
)) {
1578 cached_dir_decref(cached_directory
);
1579 cached_directory
= NULL
;
1581 if (cached_runningrouters
.published
< (now
- MAX_V1_RR_AGE
)) {
1582 clear_cached_dir(&cached_runningrouters
);
1586 /** Helper: If we're an authority for the right directory version (v1 or v2)
1587 * (based on <b>auth_type</b>), try to regenerate
1588 * auth_src as appropriate and return it, falling back to cache_src on
1589 * failure. If we're a cache, simply return cache_src.
1591 static cached_dir_t
*
1592 dirserv_pick_cached_dir_obj(cached_dir_t
*cache_src
,
1593 cached_dir_t
*auth_src
,
1594 time_t dirty
, cached_dir_t
*(*regenerate
)(void),
1596 dirinfo_type_t auth_type
)
1598 const or_options_t
*options
= get_options();
1599 int authority
= (auth_type
== V1_DIRINFO
&& authdir_mode_v1(options
)) ||
1600 (auth_type
== V2_DIRINFO
&& authdir_mode_v2(options
));
1602 if (!authority
|| authdir_mode_bridge(options
)) {
1605 /* We're authoritative. */
1606 if (regenerate
!= NULL
) {
1607 if (dirty
&& dirty
+ DIR_REGEN_SLACK_TIME
< time(NULL
)) {
1608 if (!(auth_src
= regenerate())) {
1609 log_err(LD_BUG
, "Couldn't generate %s?", name
);
1613 log_info(LD_DIRSERV
, "The %s is still clean; reusing.", name
);
1616 return auth_src
? auth_src
: cache_src
;
1620 /** Return the most recently generated encoded signed v1 directory,
1621 * generating a new one as necessary. If not a v1 authoritative directory
1622 * may return NULL if no directory is yet cached. */
1624 dirserv_get_directory(void)
1626 return dirserv_pick_cached_dir_obj(cached_directory
, the_directory
,
1627 the_directory_is_dirty
,
1628 dirserv_regenerate_directory
,
1629 "v1 server directory", V1_DIRINFO
);
1632 /** Only called by v1 auth dirservers.
1633 * Generate a fresh v1 directory; set the_directory and return a pointer
1636 static cached_dir_t
*
1637 dirserv_regenerate_directory(void)
1639 /* XXXX 024 Get rid of this function if we can confirm that nobody's
1640 * fetching these any longer */
1641 char *new_directory
=NULL
;
1643 if (dirserv_dump_directory_to_string(&new_directory
,
1644 get_server_identity_key())) {
1645 log_warn(LD_BUG
, "Error creating directory.");
1646 tor_free(new_directory
);
1649 cached_dir_decref(the_directory
);
1650 the_directory
= new_cached_dir(new_directory
, time(NULL
));
1651 log_info(LD_DIRSERV
,"New directory (size %d) has been built.",
1652 (int)the_directory
->dir_len
);
1653 log_debug(LD_DIRSERV
,"New directory (size %d):\n%s",
1654 (int)the_directory
->dir_len
, the_directory
->dir
);
1656 the_directory_is_dirty
= 0;
1658 /* Save the directory to disk so we re-load it quickly on startup.
1660 dirserv_set_cached_directory(the_directory
->dir
, time(NULL
));
1662 return the_directory
;
1665 /** Only called by v1 auth dirservers.
1666 * Replace the current running-routers list with a newly generated one. */
1667 static cached_dir_t
*
1668 generate_runningrouters(void)
1671 char digest
[DIGEST_LEN
];
1672 char published
[ISO_TIME_LEN
+1];
1674 crypto_pk_t
*private_key
= get_server_identity_key();
1675 char *identity_pkey
; /* Identity key, DER64-encoded. */
1676 size_t identity_pkey_len
;
1678 if (crypto_pk_write_public_key_to_string(private_key
,&identity_pkey
,
1679 &identity_pkey_len
)<0) {
1680 log_warn(LD_BUG
,"write identity_pkey to string failed!");
1683 format_iso_time(published
, time(NULL
));
1686 s
= tor_malloc_zero(len
);
1687 tor_snprintf(s
, len
,
1690 "router-status %s\n"
1691 "dir-signing-key\n%s"
1692 "directory-signature %s\n",
1693 published
, "", identity_pkey
,
1694 get_options()->Nickname
);
1695 tor_free(identity_pkey
);
1696 if (router_get_runningrouters_hash(s
,digest
)) {
1697 log_warn(LD_BUG
,"couldn't compute digest");
1700 note_crypto_pk_op(SIGN_DIR
);
1701 if (router_append_dirobj_signature(s
, len
, digest
, DIGEST_LEN
,
1705 set_cached_dir(&the_runningrouters
, s
, time(NULL
));
1706 runningrouters_is_dirty
= 0;
1708 return &the_runningrouters
;
1714 /** Set *<b>rr</b> to the most recently generated encoded signed
1715 * running-routers list, generating a new one as necessary. Return the
1716 * size of the directory on success, and 0 on failure. */
1718 dirserv_get_runningrouters(void)
1720 return dirserv_pick_cached_dir_obj(
1721 &cached_runningrouters
, &the_runningrouters
,
1722 runningrouters_is_dirty
,
1723 generate_runningrouters
,
1724 "v1 network status list", V1_DIRINFO
);
1727 /** Return the latest downloaded consensus networkstatus in encoded, signed,
1728 * optionally compressed format, suitable for sending to clients. */
1730 dirserv_get_consensus(const char *flavor_name
)
1732 if (!cached_consensuses
)
1734 return strmap_get(cached_consensuses
, flavor_name
);
1737 /** For authoritative directories: the current (v2) network status. */
1738 static cached_dir_t
*the_v2_networkstatus
= NULL
;
1740 /** Return true iff our opinion of the routers has been stale for long
1741 * enough that we should generate a new v2 network status doc. */
1743 should_generate_v2_networkstatus(void)
1745 return authdir_mode_v2(get_options()) &&
1746 the_v2_networkstatus_is_dirty
&&
1747 the_v2_networkstatus_is_dirty
+ DIR_REGEN_SLACK_TIME
< time(NULL
);
1750 /** If a router's uptime is at least this value, then it is always
1751 * considered stable, regardless of the rest of the network. This
1752 * way we resist attacks where an attacker doubles the size of the
1753 * network using allegedly high-uptime nodes, displacing all the
1754 * current guards. */
1755 #define UPTIME_TO_GUARANTEE_STABLE (3600*24*30)
1756 /** If a router's MTBF is at least this value, then it is always stable.
1757 * See above. (Corresponds to about 7 days for current decay rates.) */
1758 #define MTBF_TO_GUARANTEE_STABLE (60*60*24*5)
1759 /** Similarly, every node with at least this much weighted time known can be
1760 * considered familiar enough to be a guard. Corresponds to about 20 days for
1761 * current decay rates.
1763 #define TIME_KNOWN_TO_GUARANTEE_FAMILIAR (8*24*60*60)
1764 /** Similarly, every node with sufficient WFU is around enough to be a guard.
1766 #define WFU_TO_GUARANTEE_GUARD (0.98)
1768 /* Thresholds for server performance: set by
1769 * dirserv_compute_performance_thresholds, and used by
1770 * generate_v2_networkstatus */
1772 /** Any router with an uptime of at least this value is stable. */
1773 static uint32_t stable_uptime
= 0; /* start at a safe value */
1774 /** Any router with an mtbf of at least this value is stable. */
1775 static double stable_mtbf
= 0.0;
1776 /** If true, we have measured enough mtbf info to look at stable_mtbf rather
1777 * than stable_uptime. */
1778 static int enough_mtbf_info
= 0;
1779 /** Any router with a weighted fractional uptime of at least this much might
1780 * be good as a guard. */
1781 static double guard_wfu
= 0.0;
1782 /** Don't call a router a guard unless we've known about it for at least this
1784 static long guard_tk
= 0;
1785 /** Any router with a bandwidth at least this high is "Fast" */
1786 static uint32_t fast_bandwidth
= 0;
1787 /** If exits can be guards, then all guards must have a bandwidth this
1789 static uint32_t guard_bandwidth_including_exits
= 0;
1790 /** If exits can't be guards, then all guards must have a bandwidth this
1792 static uint32_t guard_bandwidth_excluding_exits
= 0;
1793 /** Total bandwidth of all the routers we're considering. */
1794 static uint64_t total_bandwidth
= 0;
1795 /** Total bandwidth of all the exit routers we're considering. */
1796 static uint64_t total_exit_bandwidth
= 0;
1798 /** Helper: estimate the uptime of a router given its stated uptime and the
1799 * amount of time since it last stated its stated uptime. */
1801 real_uptime(const routerinfo_t
*router
, time_t now
)
1803 if (now
< router
->cache_info
.published_on
)
1804 return router
->uptime
;
1806 return router
->uptime
+ (now
- router
->cache_info
.published_on
);
1809 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1810 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1811 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1815 dirserv_thinks_router_is_unreliable(time_t now
,
1816 routerinfo_t
*router
,
1817 int need_uptime
, int need_capacity
)
1820 if (!enough_mtbf_info
) {
1821 /* XXX024 Once most authorities are on v3, we should change the rule from
1822 * "use uptime if we don't have mtbf data" to "don't advertise Stable on
1823 * v3 if we don't have enough mtbf data." Or maybe not, since if we ever
1824 * hit a point where we need to reset a lot of authorities at once,
1825 * none of them would be in a position to declare Stable.
1827 long uptime
= real_uptime(router
, now
);
1828 if ((unsigned)uptime
< stable_uptime
&&
1829 (unsigned)uptime
< UPTIME_TO_GUARANTEE_STABLE
)
1833 rep_hist_get_stability(router
->cache_info
.identity_digest
, now
);
1834 if (mtbf
< stable_mtbf
&&
1835 mtbf
< MTBF_TO_GUARANTEE_STABLE
)
1839 if (need_capacity
) {
1840 uint32_t bw
= router_get_advertised_bandwidth(router
);
1841 if (bw
< fast_bandwidth
)
1847 /** Return true iff <b>router</b> should be assigned the "HSDir" flag.
1848 * Right now this means it advertises support for it, it has a high
1849 * uptime, it has a DirPort open, and it's currently considered Running.
1851 * This function needs to be called after router-\>is_running has
1855 dirserv_thinks_router_is_hs_dir(const routerinfo_t
*router
,
1856 const node_t
*node
, time_t now
)
1861 /* If we haven't been running for at least
1862 * get_options()->MinUptimeHidServDirectoryV2 seconds, we can't
1863 * have accurate data telling us a relay has been up for at least
1864 * that long. We also want to allow a bit of slack: Reachability
1865 * tests aren't instant. If we haven't been running long enough,
1866 * trust the relay. */
1868 if (stats_n_seconds_working
>
1869 get_options()->MinUptimeHidServDirectoryV2
* 1.1)
1870 uptime
= MIN(rep_hist_get_uptime(router
->cache_info
.identity_digest
, now
),
1871 real_uptime(router
, now
));
1873 uptime
= real_uptime(router
, now
);
1875 /* XXX We shouldn't need to check dir_port, but we do because of
1876 * bug 1693. In the future, once relays set wants_to_be_hs_dir
1877 * correctly, we can revert to only checking dir_port if router's
1878 * version is too old. */
1879 /* XXX Unfortunately, we need to keep checking dir_port until all
1880 * *clients* suffering from bug 2722 are obsolete. The first version
1881 * to fix the bug was 0.2.2.25-alpha. */
1882 return (router
->wants_to_be_hs_dir
&& router
->dir_port
&&
1883 uptime
>= get_options()->MinUptimeHidServDirectoryV2
&&
1887 /** Don't consider routers with less bandwidth than this when computing
1889 #define ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER 4096
1891 /** Helper for dirserv_compute_performance_thresholds(): Decide whether to
1892 * include a router in our calculations, and return true iff we should. */
1894 router_counts_toward_thresholds(const node_t
*node
, time_t now
,
1895 const digestmap_t
*omit_as_sybil
)
1897 return node
->ri
&& router_is_active(node
->ri
, node
, now
) &&
1898 !digestmap_get(omit_as_sybil
, node
->ri
->cache_info
.identity_digest
) &&
1899 (router_get_advertised_bandwidth(node
->ri
) >=
1900 ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER
);
1903 /** Look through the routerlist, the Mean Time Between Failure history, and
1904 * the Weighted Fractional Uptime history, and use them to set thresholds for
1905 * the Stable, Fast, and Guard flags. Update the fields stable_uptime,
1906 * stable_mtbf, enough_mtbf_info, guard_wfu, guard_tk, fast_bandwidth,
1907 * guard_bandwidh_including_exits, guard_bandwidth_excluding_exits,
1908 * total_bandwidth, and total_exit_bandwidth.
1910 * Also, set the is_exit flag of each router appropriately. */
1912 dirserv_compute_performance_thresholds(routerlist_t
*rl
,
1913 digestmap_t
*omit_as_sybil
)
1915 int n_active
, n_active_nonexit
, n_familiar
;
1916 uint32_t *uptimes
, *bandwidths
, *bandwidths_excluding_exits
;
1918 double *mtbfs
, *wfus
;
1919 time_t now
= time(NULL
);
1920 const or_options_t
*options
= get_options();
1922 /* initialize these all here, in case there are no routers */
1926 guard_bandwidth_including_exits
= 0;
1927 guard_bandwidth_excluding_exits
= 0;
1930 total_bandwidth
= 0;
1931 total_exit_bandwidth
= 0;
1933 /* Initialize arrays that will hold values for each router. We'll
1934 * sort them and use that to compute thresholds. */
1935 n_active
= n_active_nonexit
= 0;
1936 /* Uptime for every active router. */
1937 uptimes
= tor_malloc(sizeof(uint32_t)*smartlist_len(rl
->routers
));
1938 /* Bandwidth for every active router. */
1939 bandwidths
= tor_malloc(sizeof(uint32_t)*smartlist_len(rl
->routers
));
1940 /* Bandwidth for every active non-exit router. */
1941 bandwidths_excluding_exits
=
1942 tor_malloc(sizeof(uint32_t)*smartlist_len(rl
->routers
));
1943 /* Weighted mean time between failure for each active router. */
1944 mtbfs
= tor_malloc(sizeof(double)*smartlist_len(rl
->routers
));
1945 /* Time-known for each active router. */
1946 tks
= tor_malloc(sizeof(long)*smartlist_len(rl
->routers
));
1947 /* Weighted fractional uptime for each active router. */
1948 wfus
= tor_malloc(sizeof(double)*smartlist_len(rl
->routers
));
1950 nodelist_assert_ok();
1952 /* Now, fill in the arrays. */
1953 SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), node_t
*, node
) {
1954 if (router_counts_toward_thresholds(node
, now
, omit_as_sybil
)) {
1955 routerinfo_t
*ri
= node
->ri
;
1956 const char *id
= ri
->cache_info
.identity_digest
;
1958 node
->is_exit
= (!router_exit_policy_rejects_all(ri
) &&
1959 exit_policy_is_general_exit(ri
->exit_policy
));
1960 uptimes
[n_active
] = (uint32_t)real_uptime(ri
, now
);
1961 mtbfs
[n_active
] = rep_hist_get_stability(id
, now
);
1962 tks
[n_active
] = rep_hist_get_weighted_time_known(id
, now
);
1963 bandwidths
[n_active
] = bw
= router_get_advertised_bandwidth(ri
);
1964 total_bandwidth
+= bw
;
1965 if (node
->is_exit
&& !node
->is_bad_exit
) {
1966 total_exit_bandwidth
+= bw
;
1968 bandwidths_excluding_exits
[n_active_nonexit
] = bw
;
1973 } SMARTLIST_FOREACH_END(node
);
1975 /* Now, compute thresholds. */
1977 /* The median uptime is stable. */
1978 stable_uptime
= median_uint32(uptimes
, n_active
);
1979 /* The median mtbf is stable, if we have enough mtbf info */
1980 stable_mtbf
= median_double(mtbfs
, n_active
);
1981 /* The 12.5th percentile bandwidth is fast. */
1982 fast_bandwidth
= find_nth_uint32(bandwidths
, n_active
, n_active
/8);
1983 /* (Now bandwidths is sorted.) */
1984 if (fast_bandwidth
< ROUTER_REQUIRED_MIN_BANDWIDTH
/2)
1985 fast_bandwidth
= bandwidths
[n_active
/4];
1986 guard_bandwidth_including_exits
= bandwidths
[(n_active
-1)/2];
1987 guard_tk
= find_nth_long(tks
, n_active
, n_active
/8);
1990 if (guard_tk
> TIME_KNOWN_TO_GUARANTEE_FAMILIAR
)
1991 guard_tk
= TIME_KNOWN_TO_GUARANTEE_FAMILIAR
;
1994 /* We can vote on a parameter for the minimum and maximum. */
1995 #define ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG 4096
1996 int32_t min_fast
, max_fast
;
1997 min_fast
= networkstatus_get_param(NULL
, "FastFlagMinThreshold",
1998 ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG
,
1999 ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG
,
2001 max_fast
= networkstatus_get_param(NULL
, "FastFlagMaxThreshold",
2002 INT32_MAX
, min_fast
, INT32_MAX
);
2003 if (fast_bandwidth
< (uint32_t)min_fast
)
2004 fast_bandwidth
= min_fast
;
2005 if (fast_bandwidth
> (uint32_t)max_fast
)
2006 fast_bandwidth
= max_fast
;
2008 /* Protect sufficiently fast nodes from being pushed out of the set
2010 if (options
->AuthDirFastGuarantee
&&
2011 fast_bandwidth
> options
->AuthDirFastGuarantee
)
2012 fast_bandwidth
= (uint32_t)options
->AuthDirFastGuarantee
;
2014 /* Now that we have a time-known that 7/8 routers are known longer than,
2015 * fill wfus with the wfu of every such "familiar" router. */
2018 SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), node_t
*, node
) {
2019 if (router_counts_toward_thresholds(node
, now
, omit_as_sybil
)) {
2020 routerinfo_t
*ri
= node
->ri
;
2021 const char *id
= ri
->cache_info
.identity_digest
;
2022 long tk
= rep_hist_get_weighted_time_known(id
, now
);
2025 wfus
[n_familiar
++] = rep_hist_get_weighted_fractional_uptime(id
, now
);
2027 } SMARTLIST_FOREACH_END(node
);
2029 guard_wfu
= median_double(wfus
, n_familiar
);
2030 if (guard_wfu
> WFU_TO_GUARANTEE_GUARD
)
2031 guard_wfu
= WFU_TO_GUARANTEE_GUARD
;
2033 enough_mtbf_info
= rep_hist_have_measured_enough_stability();
2035 if (n_active_nonexit
) {
2036 guard_bandwidth_excluding_exits
=
2037 median_uint32(bandwidths_excluding_exits
, n_active_nonexit
);
2040 log_info(LD_DIRSERV
,
2041 "Cutoffs: For Stable, %lu sec uptime, %lu sec MTBF. "
2042 "For Fast: %lu bytes/sec. "
2043 "For Guard: WFU %.03f%%, time-known %lu sec, "
2044 "and bandwidth %lu or %lu bytes/sec. We%s have enough stability data.",
2045 (unsigned long)stable_uptime
,
2046 (unsigned long)stable_mtbf
,
2047 (unsigned long)fast_bandwidth
,
2049 (unsigned long)guard_tk
,
2050 (unsigned long)guard_bandwidth_including_exits
,
2051 (unsigned long)guard_bandwidth_excluding_exits
,
2052 enough_mtbf_info
? "" : " don't ");
2056 tor_free(bandwidths
);
2057 tor_free(bandwidths_excluding_exits
);
2062 /** Give a statement of our current performance thresholds for inclusion
2063 * in a vote document. */
2065 dirserv_get_flag_thresholds_line(void)
2068 tor_asprintf(&result
,
2069 "stable-uptime=%lu stable-mtbf=%lu "
2071 "guard-wfu=%.03f%% guard-tk=%lu "
2072 "guard-bw-inc-exits=%lu guard-bw-exc-exits=%lu "
2074 (unsigned long)stable_uptime
,
2075 (unsigned long)stable_mtbf
,
2076 (unsigned long)fast_bandwidth
,
2078 (unsigned long)guard_tk
,
2079 (unsigned long)guard_bandwidth_including_exits
,
2080 (unsigned long)guard_bandwidth_excluding_exits
,
2081 enough_mtbf_info
? 1 : 0);
2086 /** Given a platform string as in a routerinfo_t (possibly null), return a
2087 * newly allocated version string for a networkstatus document, or NULL if the
2088 * platform doesn't give a Tor version. */
2090 version_from_platform(const char *platform
)
2092 if (platform
&& !strcmpstart(platform
, "Tor ")) {
2093 const char *eos
= find_whitespace(platform
+4);
2094 if (eos
&& !strcmpstart(eos
, " (r")) {
2095 /* XXXX Unify this logic with the other version extraction
2096 * logic in routerparse.c. */
2097 eos
= find_whitespace(eos
+1);
2100 return tor_strndup(platform
, eos
-platform
);
2106 /** Helper: write the router-status information in <b>rs</b> into <b>buf</b>,
2107 * which has at least <b>buf_len</b> free characters. Do NUL-termination.
2108 * Use the same format as in network-status documents. If <b>version</b> is
2109 * non-NULL, add a "v" line for the platform. Return 0 on success, -1 on
2112 * The format argument has one of the following values:
2113 * NS_V2 - Output an entry suitable for a V2 NS opinion document
2114 * NS_V3_CONSENSUS - Output the first portion of a V3 NS consensus entry
2115 * NS_V3_CONSENSUS_MICRODESC - Output the first portion of a V3 microdesc
2117 * NS_V3_VOTE - Output a complete V3 NS vote
2118 * NS_CONTROL_PORT - Output a NS document for the control port
2121 routerstatus_format_entry(char *buf
, size_t buf_len
,
2122 const routerstatus_t
*rs
, const char *version
,
2123 routerstatus_format_type_t format
)
2129 char published
[ISO_TIME_LEN
+1];
2130 char identity64
[BASE64_DIGEST_LEN
+1];
2131 char digest64
[BASE64_DIGEST_LEN
+1];
2133 format_iso_time(published
, rs
->published_on
);
2134 digest_to_base64(identity64
, rs
->identity_digest
);
2135 digest_to_base64(digest64
, rs
->descriptor_digest
);
2137 r
= tor_snprintf(buf
, buf_len
,
2138 "r %s %s %s%s%s %s %d %d\n",
2141 (format
==NS_V3_CONSENSUS_MICRODESC
)?"":digest64
,
2142 (format
==NS_V3_CONSENSUS_MICRODESC
)?"":" ",
2144 fmt_addr32(rs
->addr
),
2148 log_warn(LD_BUG
, "Not enough space in buffer.");
2151 cp
= buf
+ strlen(buf
);
2153 /* TODO: Maybe we want to pass in what we need to build the rest of
2154 * this here, instead of in the caller. Then we could use the
2155 * networkstatus_type_t values, with an additional control port value
2158 /* V3 microdesc consensuses don't have "a" lines. */
2159 if (format
== NS_V3_CONSENSUS_MICRODESC
)
2162 /* Possible "a" line. At most one for now. */
2163 if (!tor_addr_is_null(&rs
->ipv6_addr
)) {
2164 r
= tor_snprintf(cp
, buf_len
- (cp
-buf
),
2166 fmt_addrport(&rs
->ipv6_addr
, rs
->ipv6_orport
));
2168 log_warn(LD_BUG
, "Not enough space in buffer.");
2174 if (format
== NS_V3_CONSENSUS
)
2177 /* NOTE: Whenever this list expands, be sure to increase MAX_FLAG_LINE_LEN*/
2178 r
= tor_snprintf(cp
, buf_len
- (cp
-buf
),
2179 "s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
2180 /* These must stay in alphabetical order. */
2181 rs
->is_authority
?" Authority":"",
2182 rs
->is_bad_directory
?" BadDirectory":"",
2183 rs
->is_bad_exit
?" BadExit":"",
2184 rs
->is_exit
?" Exit":"",
2185 rs
->is_fast
?" Fast":"",
2186 rs
->is_possible_guard
?" Guard":"",
2187 rs
->is_hs_dir
?" HSDir":"",
2188 rs
->is_named
?" Named":"",
2189 rs
->is_flagged_running
?" Running":"",
2190 rs
->is_stable
?" Stable":"",
2191 rs
->is_unnamed
?" Unnamed":"",
2192 rs
->is_v2_dir
?" V2Dir":"",
2193 rs
->is_valid
?" Valid":"");
2195 log_warn(LD_BUG
, "Not enough space in buffer.");
2200 /* length of "opt v \n" */
2201 #define V_LINE_OVERHEAD 7
2202 if (version
&& strlen(version
) < MAX_V_LINE_LEN
- V_LINE_OVERHEAD
) {
2203 if (tor_snprintf(cp
, buf_len
- (cp
-buf
), "v %s\n", version
)<0) {
2204 log_warn(LD_BUG
, "Unable to print router version.");
2210 if (format
!= NS_V2
) {
2211 const routerinfo_t
* desc
= router_get_by_id_digest(rs
->identity_digest
);
2214 if (format
!= NS_CONTROL_PORT
) {
2215 /* Blow up more or less nicely if we didn't get anything or not the
2216 * thing we expected.
2219 char id
[HEX_DIGEST_LEN
+1];
2220 char dd
[HEX_DIGEST_LEN
+1];
2222 base16_encode(id
, sizeof(id
), rs
->identity_digest
, DIGEST_LEN
);
2223 base16_encode(dd
, sizeof(dd
), rs
->descriptor_digest
, DIGEST_LEN
);
2224 log_warn(LD_BUG
, "Cannot get any descriptor for %s "
2225 "(wanted descriptor %s).",
2230 /* This assert can fire for the control port, because
2231 * it can request NS documents before all descriptors
2232 * have been fetched. */
2233 if (tor_memneq(desc
->cache_info
.signed_descriptor_digest
,
2234 rs
->descriptor_digest
,
2236 char rl_d
[HEX_DIGEST_LEN
+1];
2237 char rs_d
[HEX_DIGEST_LEN
+1];
2238 char id
[HEX_DIGEST_LEN
+1];
2240 base16_encode(rl_d
, sizeof(rl_d
),
2241 desc
->cache_info
.signed_descriptor_digest
, DIGEST_LEN
);
2242 base16_encode(rs_d
, sizeof(rs_d
), rs
->descriptor_digest
, DIGEST_LEN
);
2243 base16_encode(id
, sizeof(id
), rs
->identity_digest
, DIGEST_LEN
);
2244 log_err(LD_BUG
, "descriptor digest in routerlist does not match "
2245 "the one in routerstatus: %s vs %s "
2249 tor_assert(tor_memeq(desc
->cache_info
.signed_descriptor_digest
,
2250 rs
->descriptor_digest
,
2255 if (format
== NS_CONTROL_PORT
&& rs
->has_bandwidth
) {
2259 bw
= router_get_advertised_bandwidth_capped(desc
) / 1000;
2261 r
= tor_snprintf(cp
, buf_len
- (cp
-buf
),
2262 "w Bandwidth=%d\n", bw
);
2265 log_warn(LD_BUG
, "Not enough space in buffer.");
2269 if (format
== NS_V3_VOTE
&& rs
->has_measured_bw
) {
2270 *--cp
= '\0'; /* Kill "\n" */
2271 r
= tor_snprintf(cp
, buf_len
- (cp
-buf
),
2272 " Measured=%d\n", rs
->measured_bw
);
2274 log_warn(LD_BUG
, "Not enough space in buffer for weight line.");
2281 summary
= policy_summarize(desc
->exit_policy
, AF_INET
);
2282 r
= tor_snprintf(cp
, buf_len
- (cp
-buf
), "p %s\n", summary
);
2284 log_warn(LD_BUG
, "Not enough space in buffer.");
2296 /** Helper for sorting: compares two routerinfos first by address, and then by
2297 * descending order of "usefulness". (An authority is more useful than a
2298 * non-authority; a running router is more useful than a non-running router;
2299 * and a router with more bandwidth is more useful than one with less.)
2302 compare_routerinfo_by_ip_and_bw_(const void **a
, const void **b
)
2304 routerinfo_t
*first
= *(routerinfo_t
**)a
, *second
= *(routerinfo_t
**)b
;
2305 int first_is_auth
, second_is_auth
;
2306 uint32_t bw_first
, bw_second
;
2307 const node_t
*node_first
, *node_second
;
2308 int first_is_running
, second_is_running
;
2310 /* we return -1 if first should appear before second... that is,
2311 * if first is a better router. */
2312 if (first
->addr
< second
->addr
)
2314 else if (first
->addr
> second
->addr
)
2317 /* Potentially, this next bit could cause k n lg n memeq calls. But in
2318 * reality, we will almost never get here, since addresses will usually be
2322 router_digest_is_trusted_dir(first
->cache_info
.identity_digest
);
2324 router_digest_is_trusted_dir(second
->cache_info
.identity_digest
);
2326 if (first_is_auth
&& !second_is_auth
)
2328 else if (!first_is_auth
&& second_is_auth
)
2331 node_first
= node_get_by_id(first
->cache_info
.identity_digest
);
2332 node_second
= node_get_by_id(second
->cache_info
.identity_digest
);
2333 first_is_running
= node_first
&& node_first
->is_running
;
2334 second_is_running
= node_second
&& node_second
->is_running
;
2336 if (first_is_running
&& !second_is_running
)
2338 else if (!first_is_running
&& second_is_running
)
2341 bw_first
= router_get_advertised_bandwidth(first
);
2342 bw_second
= router_get_advertised_bandwidth(second
);
2344 if (bw_first
> bw_second
)
2346 else if (bw_first
< bw_second
)
2349 /* They're equal! Compare by identity digest, so there's a
2350 * deterministic order and we avoid flapping. */
2351 return fast_memcmp(first
->cache_info
.identity_digest
,
2352 second
->cache_info
.identity_digest
,
2356 /** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
2357 * whose keys are the identity digests of those routers that we're going to
2358 * exclude for Sybil-like appearance. */
2359 static digestmap_t
*
2360 get_possible_sybil_list(const smartlist_t
*routers
)
2362 const or_options_t
*options
= get_options();
2363 digestmap_t
*omit_as_sybil
;
2364 smartlist_t
*routers_by_ip
= smartlist_new();
2367 /* Allow at most this number of Tor servers on a single IP address, ... */
2368 int max_with_same_addr
= options
->AuthDirMaxServersPerAddr
;
2369 /* ... unless it's a directory authority, in which case allow more. */
2370 int max_with_same_addr_on_authority
= options
->AuthDirMaxServersPerAuthAddr
;
2371 if (max_with_same_addr
<= 0)
2372 max_with_same_addr
= INT_MAX
;
2373 if (max_with_same_addr_on_authority
<= 0)
2374 max_with_same_addr_on_authority
= INT_MAX
;
2376 smartlist_add_all(routers_by_ip
, routers
);
2377 smartlist_sort(routers_by_ip
, compare_routerinfo_by_ip_and_bw_
);
2378 omit_as_sybil
= digestmap_new();
2382 SMARTLIST_FOREACH_BEGIN(routers_by_ip
, routerinfo_t
*, ri
) {
2383 if (last_addr
!= ri
->addr
) {
2384 last_addr
= ri
->addr
;
2386 } else if (++addr_count
> max_with_same_addr
) {
2387 if (!router_addr_is_trusted_dir(ri
->addr
) ||
2388 addr_count
> max_with_same_addr_on_authority
)
2389 digestmap_set(omit_as_sybil
, ri
->cache_info
.identity_digest
, ri
);
2391 } SMARTLIST_FOREACH_END(ri
);
2393 smartlist_free(routers_by_ip
);
2394 return omit_as_sybil
;
2397 /** Return non-zero iff a relay running the Tor version specified in
2398 * <b>platform</b> is suitable for use as a potential entry guard. */
2400 is_router_version_good_for_possible_guard(const char *platform
)
2402 static int parsed_versions_initialized
= 0;
2403 static tor_version_t first_good_0_2_1_guard_version
;
2404 static tor_version_t first_good_0_2_2_guard_version
;
2405 static tor_version_t first_good_later_guard_version
;
2407 tor_version_t router_version
;
2409 /* XXX024 This block should be extracted into its own function. */
2410 /* XXXX Begin code copied from tor_version_as_new_as (in routerparse.c) */
2412 char *s
, *s2
, *start
;
2415 tor_assert(platform
);
2417 /* nonstandard Tor; be safe and say yes */
2418 if (strcmpstart(platform
,"Tor "))
2421 start
= (char *)eat_whitespace(platform
+3);
2422 if (!*start
) return 0;
2423 s
= (char *)find_whitespace(start
); /* also finds '\0', which is fine */
2424 s2
= (char*)eat_whitespace(s
);
2425 if (!strcmpstart(s2
, "(r") || !strcmpstart(s2
, "(git-"))
2426 s
= (char*)find_whitespace(s2
);
2428 if ((size_t)(s
-start
+1) >= sizeof(tmp
)) /* too big, no */
2430 strlcpy(tmp
, start
, s
-start
+1);
2432 if (tor_version_parse(tmp
, &router_version
)<0) {
2433 log_info(LD_DIR
,"Router version '%s' unparseable.",tmp
);
2434 return 1; /* be safe and say yes */
2437 /* XXXX End code copied from tor_version_as_new_as (in routerparse.c) */
2439 if (!parsed_versions_initialized
) {
2440 /* CVE-2011-2769 was fixed on the relay side in Tor versions
2441 * 0.2.1.31, 0.2.2.34, and 0.2.3.6-alpha. */
2442 tor_assert(tor_version_parse("0.2.1.31",
2443 &first_good_0_2_1_guard_version
)>=0);
2444 tor_assert(tor_version_parse("0.2.2.34",
2445 &first_good_0_2_2_guard_version
)>=0);
2446 tor_assert(tor_version_parse("0.2.3.6-alpha",
2447 &first_good_later_guard_version
)>=0);
2449 /* Don't parse these constant version strings once for every relay
2450 * for every vote. */
2451 parsed_versions_initialized
= 1;
2454 return ((tor_version_same_series(&first_good_0_2_1_guard_version
,
2456 tor_version_compare(&first_good_0_2_1_guard_version
,
2457 &router_version
) <= 0) ||
2458 (tor_version_same_series(&first_good_0_2_2_guard_version
,
2460 tor_version_compare(&first_good_0_2_2_guard_version
,
2461 &router_version
) <= 0) ||
2462 (tor_version_compare(&first_good_later_guard_version
,
2463 &router_version
) <= 0));
2466 /** Extract status information from <b>ri</b> and from other authority
2467 * functions and store it in <b>rs</b>>. If <b>naming</b>, consider setting
2468 * the named flag in <b>rs</b>.
2470 * We assume that ri-\>is_running has already been set, e.g. by
2471 * dirserv_set_router_is_running(ri, now);
2474 set_routerstatus_from_routerinfo(routerstatus_t
*rs
,
2478 int naming
, int listbadexits
,
2479 int listbaddirs
, int vote_on_hsdirs
)
2481 const or_options_t
*options
= get_options();
2482 uint32_t routerbw
= router_get_advertised_bandwidth(ri
);
2484 memset(rs
, 0, sizeof(routerstatus_t
));
2487 router_digest_is_trusted_dir(ri
->cache_info
.identity_digest
);
2489 /* Already set by compute_performance_thresholds. */
2490 rs
->is_exit
= node
->is_exit
;
2491 rs
->is_stable
= node
->is_stable
=
2492 router_is_active(ri
, node
, now
) &&
2493 !dirserv_thinks_router_is_unreliable(now
, ri
, 1, 0);
2494 rs
->is_fast
= node
->is_fast
=
2495 router_is_active(ri
, node
, now
) &&
2496 !dirserv_thinks_router_is_unreliable(now
, ri
, 0, 1);
2497 rs
->is_flagged_running
= node
->is_running
; /* computed above */
2500 uint32_t name_status
= dirserv_get_name_status(
2501 node
->identity
, ri
->nickname
);
2502 rs
->is_named
= (naming
&& (name_status
& FP_NAMED
)) ? 1 : 0;
2503 rs
->is_unnamed
= (naming
&& (name_status
& FP_UNNAMED
)) ? 1 : 0;
2505 rs
->is_valid
= node
->is_valid
;
2507 if (node
->is_fast
&&
2508 ((options
->AuthDirGuardBWGuarantee
&&
2509 routerbw
>= options
->AuthDirGuardBWGuarantee
) ||
2510 routerbw
>= MIN(guard_bandwidth_including_exits
,
2511 guard_bandwidth_excluding_exits
)) &&
2512 is_router_version_good_for_possible_guard(ri
->platform
)) {
2513 long tk
= rep_hist_get_weighted_time_known(
2514 node
->identity
, now
);
2515 double wfu
= rep_hist_get_weighted_fractional_uptime(
2516 node
->identity
, now
);
2517 rs
->is_possible_guard
= (wfu
>= guard_wfu
&& tk
>= guard_tk
) ? 1 : 0;
2519 rs
->is_possible_guard
= 0;
2522 rs
->is_bad_directory
= listbaddirs
&& node
->is_bad_directory
;
2523 rs
->is_bad_exit
= listbadexits
&& node
->is_bad_exit
;
2524 node
->is_hs_dir
= dirserv_thinks_router_is_hs_dir(ri
, node
, now
);
2525 rs
->is_hs_dir
= vote_on_hsdirs
&& node
->is_hs_dir
;
2526 rs
->is_v2_dir
= ri
->dir_port
!= 0;
2528 if (!strcasecmp(ri
->nickname
, UNNAMED_ROUTER_NICKNAME
))
2529 rs
->is_named
= rs
->is_unnamed
= 0;
2531 rs
->published_on
= ri
->cache_info
.published_on
;
2532 memcpy(rs
->identity_digest
, node
->identity
, DIGEST_LEN
);
2533 memcpy(rs
->descriptor_digest
, ri
->cache_info
.signed_descriptor_digest
,
2535 rs
->addr
= ri
->addr
;
2536 strlcpy(rs
->nickname
, ri
->nickname
, sizeof(rs
->nickname
));
2537 rs
->or_port
= ri
->or_port
;
2538 rs
->dir_port
= ri
->dir_port
;
2539 if (options
->AuthDirHasIPv6Connectivity
== 1 &&
2540 !tor_addr_is_null(&ri
->ipv6_addr
) &&
2541 node
->last_reachable6
>= now
- REACHABLE_TIMEOUT
) {
2542 /* We're configured as having IPv6 connectivity. There's an IPv6
2543 OR port and it's reachable so copy it to the routerstatus. */
2544 tor_addr_copy(&rs
->ipv6_addr
, &ri
->ipv6_addr
);
2545 rs
->ipv6_orport
= ri
->ipv6_orport
;
2549 /** Routerstatus <b>rs</b> is part of a group of routers that are on
2550 * too narrow an IP-space. Clear out its flags: we don't want people
2554 clear_status_flags_on_sybil(routerstatus_t
*rs
)
2556 rs
->is_authority
= rs
->is_exit
= rs
->is_stable
= rs
->is_fast
=
2557 rs
->is_flagged_running
= rs
->is_named
= rs
->is_valid
= rs
->is_v2_dir
=
2558 rs
->is_hs_dir
= rs
->is_possible_guard
= rs
->is_bad_exit
=
2559 rs
->is_bad_directory
= 0;
2560 /* FFFF we might want some mechanism to check later on if we
2561 * missed zeroing any flags: it's easy to add a new flag but
2562 * forget to add it to this clause. */
2566 * Helper function to parse out a line in the measured bandwidth file
2567 * into a measured_bw_line_t output structure. Returns -1 on failure
2571 measured_bw_line_parse(measured_bw_line_t
*out
, const char *orig_line
)
2573 char *line
= tor_strdup(orig_line
);
2576 int got_node_id
= 0;
2577 char *strtok_state
; /* lame sauce d'jour */
2578 cp
= tor_strtok_r(cp
, " \t", &strtok_state
);
2581 log_warn(LD_DIRSERV
, "Invalid line in bandwidth file: %s",
2582 escaped(orig_line
));
2587 if (orig_line
[strlen(orig_line
)-1] != '\n') {
2588 log_warn(LD_DIRSERV
, "Incomplete line in bandwidth file: %s",
2589 escaped(orig_line
));
2595 if (strcmpstart(cp
, "bw=") == 0) {
2599 log_warn(LD_DIRSERV
, "Double bw= in bandwidth file line: %s",
2600 escaped(orig_line
));
2606 out
->bw
= tor_parse_long(cp
, 0, 0, LONG_MAX
, &parse_ok
, &endptr
);
2607 if (!parse_ok
|| (*endptr
&& !TOR_ISSPACE(*endptr
))) {
2608 log_warn(LD_DIRSERV
, "Invalid bandwidth in bandwidth file line: %s",
2609 escaped(orig_line
));
2614 } else if (strcmpstart(cp
, "node_id=$") == 0) {
2616 log_warn(LD_DIRSERV
, "Double node_id= in bandwidth file line: %s",
2617 escaped(orig_line
));
2621 cp
+=strlen("node_id=$");
2623 if (strlen(cp
) != HEX_DIGEST_LEN
||
2624 base16_decode(out
->node_id
, DIGEST_LEN
, cp
, HEX_DIGEST_LEN
)) {
2625 log_warn(LD_DIRSERV
, "Invalid node_id in bandwidth file line: %s",
2626 escaped(orig_line
));
2630 strlcpy(out
->node_hex
, cp
, sizeof(out
->node_hex
));
2633 } while ((cp
= tor_strtok_r(NULL
, " \t", &strtok_state
)));
2635 if (got_bw
&& got_node_id
) {
2639 log_warn(LD_DIRSERV
, "Incomplete line in bandwidth file: %s",
2640 escaped(orig_line
));
2647 * Helper function to apply a parsed measurement line to a list
2648 * of bandwidth statuses. Returns true if a line is found,
2652 measured_bw_line_apply(measured_bw_line_t
*parsed_line
,
2653 smartlist_t
*routerstatuses
)
2655 routerstatus_t
*rs
= NULL
;
2656 if (!routerstatuses
)
2659 rs
= smartlist_bsearch(routerstatuses
, parsed_line
->node_id
,
2660 compare_digest_to_routerstatus_entry
);
2663 rs
->has_measured_bw
= 1;
2664 rs
->measured_bw
= (uint32_t)parsed_line
->bw
;
2666 log_info(LD_DIRSERV
, "Node ID %s not found in routerstatus list",
2667 parsed_line
->node_hex
);
2674 * Read the measured bandwidth file and apply it to the list of
2675 * routerstatuses. Returns -1 on error, 0 otherwise.
2678 dirserv_read_measured_bandwidths(const char *from_file
,
2679 smartlist_t
*routerstatuses
)
2682 FILE *fp
= tor_fopen_cloexec(from_file
, "r");
2683 int applied_lines
= 0;
2687 log_warn(LD_CONFIG
, "Can't open bandwidth file at configured location: %s",
2692 if (!fgets(line
, sizeof(line
), fp
)
2693 || !strlen(line
) || line
[strlen(line
)-1] != '\n') {
2694 log_warn(LD_DIRSERV
, "Long or truncated time in bandwidth file: %s",
2700 line
[strlen(line
)-1] = '\0';
2701 file_time
= tor_parse_ulong(line
, 10, 0, ULONG_MAX
, &ok
, NULL
);
2703 log_warn(LD_DIRSERV
, "Non-integer time in bandwidth file: %s",
2709 if ((time(NULL
) - file_time
) > MAX_MEASUREMENT_AGE
) {
2710 log_warn(LD_DIRSERV
, "Bandwidth measurement file stale. Age: %u",
2711 (unsigned)(time(NULL
) - file_time
));
2717 smartlist_sort(routerstatuses
, compare_routerstatus_entries
);
2720 measured_bw_line_t parsed_line
;
2721 if (fgets(line
, sizeof(line
), fp
) && strlen(line
)) {
2722 if (measured_bw_line_parse(&parsed_line
, line
) != -1) {
2723 if (measured_bw_line_apply(&parsed_line
, routerstatuses
) > 0)
2730 log_info(LD_DIRSERV
,
2731 "Bandwidth measurement file successfully read. "
2732 "Applied %d measurements.", applied_lines
);
2736 /** Return a new networkstatus_t* containing our current opinion. (For v3
2739 dirserv_generate_networkstatus_vote_obj(crypto_pk_t
*private_key
,
2740 authority_cert_t
*cert
)
2742 const or_options_t
*options
= get_options();
2743 networkstatus_t
*v3_out
= NULL
;
2745 char *hostname
= NULL
, *client_versions
= NULL
, *server_versions
= NULL
;
2746 const char *contact
;
2747 smartlist_t
*routers
, *routerstatuses
;
2748 char identity_digest
[DIGEST_LEN
];
2749 char signing_key_digest
[DIGEST_LEN
];
2750 int naming
= options
->NamingAuthoritativeDir
;
2751 int listbadexits
= options
->AuthDirListBadExits
;
2752 int listbaddirs
= options
->AuthDirListBadDirs
;
2753 int vote_on_hsdirs
= options
->VoteOnHidServDirectoriesV2
;
2754 routerlist_t
*rl
= router_get_routerlist();
2755 time_t now
= time(NULL
);
2756 time_t cutoff
= now
- ROUTER_MAX_AGE_TO_PUBLISH
;
2757 networkstatus_voter_info_t
*voter
= NULL
;
2758 vote_timing_t timing
;
2759 digestmap_t
*omit_as_sybil
= NULL
;
2760 const int vote_on_reachability
= running_long_enough_to_decide_unreachable();
2761 smartlist_t
*microdescriptors
= NULL
;
2763 tor_assert(private_key
);
2766 if (resolve_my_address(LOG_WARN
, options
, &addr
, &hostname
)<0) {
2767 log_warn(LD_NET
, "Couldn't resolve my hostname");
2770 if (!strchr(hostname
, '.')) {
2772 hostname
= tor_dup_ip(addr
);
2774 if (crypto_pk_get_digest(private_key
, signing_key_digest
)<0) {
2775 log_err(LD_BUG
, "Error computing signing key digest");
2778 if (crypto_pk_get_digest(cert
->identity_key
, identity_digest
)<0) {
2779 log_err(LD_BUG
, "Error computing identity key digest");
2783 if (options
->VersioningAuthoritativeDir
) {
2784 client_versions
= format_versions_list(options
->RecommendedClientVersions
);
2785 server_versions
= format_versions_list(options
->RecommendedServerVersions
);
2788 contact
= get_options()->ContactInfo
;
2792 /* precompute this part, since we need it to decide what "stable"
2794 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, ri
, {
2795 dirserv_set_router_is_running(ri
, now
);
2798 routers
= smartlist_new();
2799 smartlist_add_all(routers
, rl
->routers
);
2800 routers_sort_by_identity(routers
);
2801 omit_as_sybil
= get_possible_sybil_list(routers
);
2803 DIGESTMAP_FOREACH(omit_as_sybil
, sybil_id
, void *, ignore
) {
2805 rep_hist_make_router_pessimal(sybil_id
, now
);
2806 } DIGESTMAP_FOREACH_END
;
2808 dirserv_compute_performance_thresholds(rl
, omit_as_sybil
);
2810 routerstatuses
= smartlist_new();
2811 microdescriptors
= smartlist_new();
2813 SMARTLIST_FOREACH_BEGIN(routers
, routerinfo_t
*, ri
) {
2814 const struct consensus_method_range_t
*cmr
= NULL
;
2815 if (ri
->cache_info
.published_on
>= cutoff
) {
2817 vote_routerstatus_t
*vrs
;
2819 node_t
*node
= node_get_mutable_by_id(ri
->cache_info
.identity_digest
);
2823 vrs
= tor_malloc_zero(sizeof(vote_routerstatus_t
));
2825 set_routerstatus_from_routerinfo(rs
, node
, ri
, now
,
2826 naming
, listbadexits
, listbaddirs
,
2829 if (digestmap_get(omit_as_sybil
, ri
->cache_info
.identity_digest
))
2830 clear_status_flags_on_sybil(rs
);
2832 if (!vote_on_reachability
)
2833 rs
->is_flagged_running
= 0;
2835 vrs
->version
= version_from_platform(ri
->platform
);
2836 for (cmr
= microdesc_consensus_methods
;
2837 cmr
->low
!= -1 && cmr
->high
!= -1;
2839 md
= dirvote_create_microdescriptor(ri
, cmr
->low
);
2842 vote_microdesc_hash_t
*h
;
2843 dirvote_format_microdesc_vote_line(buf
, sizeof(buf
), md
,
2844 cmr
->low
, cmr
->high
);
2845 h
= tor_malloc_zero(sizeof(vote_microdesc_hash_t
));
2846 h
->microdesc_hash_line
= tor_strdup(buf
);
2847 h
->next
= vrs
->microdesc
;
2849 md
->last_listed
= now
;
2850 smartlist_add(microdescriptors
, md
);
2854 smartlist_add(routerstatuses
, vrs
);
2856 } SMARTLIST_FOREACH_END(ri
);
2859 smartlist_t
*added
=
2860 microdescs_add_list_to_cache(get_microdesc_cache(),
2861 microdescriptors
, SAVED_NOWHERE
, 0);
2862 smartlist_free(added
);
2863 smartlist_free(microdescriptors
);
2866 smartlist_free(routers
);
2867 digestmap_free(omit_as_sybil
, NULL
);
2869 if (options
->V3BandwidthsFile
) {
2870 dirserv_read_measured_bandwidths(options
->V3BandwidthsFile
,
2874 v3_out
= tor_malloc_zero(sizeof(networkstatus_t
));
2876 v3_out
->type
= NS_TYPE_VOTE
;
2877 dirvote_get_preferred_voting_intervals(&timing
);
2878 v3_out
->published
= now
;
2880 char tbuf
[ISO_TIME_LEN
+1];
2881 networkstatus_t
*current_consensus
=
2882 networkstatus_get_live_consensus(now
);
2883 long last_consensus_interval
; /* only used to pick a valid_after */
2884 if (current_consensus
)
2885 last_consensus_interval
= current_consensus
->fresh_until
-
2886 current_consensus
->valid_after
;
2888 last_consensus_interval
= options
->TestingV3AuthInitialVotingInterval
;
2889 v3_out
->valid_after
=
2890 dirvote_get_start_of_next_interval(now
, (int)last_consensus_interval
);
2891 format_iso_time(tbuf
, v3_out
->valid_after
);
2892 log_notice(LD_DIR
,"Choosing valid-after time in vote as %s: "
2893 "consensus_set=%d, last_interval=%d",
2894 tbuf
, current_consensus
?1:0, (int)last_consensus_interval
);
2896 v3_out
->fresh_until
= v3_out
->valid_after
+ timing
.vote_interval
;
2897 v3_out
->valid_until
= v3_out
->valid_after
+
2898 (timing
.vote_interval
* timing
.n_intervals_valid
);
2899 v3_out
->vote_seconds
= timing
.vote_delay
;
2900 v3_out
->dist_seconds
= timing
.dist_delay
;
2901 tor_assert(v3_out
->vote_seconds
> 0);
2902 tor_assert(v3_out
->dist_seconds
> 0);
2903 tor_assert(timing
.n_intervals_valid
> 0);
2905 v3_out
->client_versions
= client_versions
;
2906 v3_out
->server_versions
= server_versions
;
2907 v3_out
->known_flags
= smartlist_new();
2908 smartlist_split_string(v3_out
->known_flags
,
2909 "Authority Exit Fast Guard Stable V2Dir Valid",
2910 0, SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2911 if (vote_on_reachability
)
2912 smartlist_add(v3_out
->known_flags
, tor_strdup("Running"));
2914 smartlist_add(v3_out
->known_flags
, tor_strdup("BadDirectory"));
2916 smartlist_add(v3_out
->known_flags
, tor_strdup("BadExit"));
2918 smartlist_add(v3_out
->known_flags
, tor_strdup("Named"));
2919 smartlist_add(v3_out
->known_flags
, tor_strdup("Unnamed"));
2922 smartlist_add(v3_out
->known_flags
, tor_strdup("HSDir"));
2923 smartlist_sort_strings(v3_out
->known_flags
);
2925 if (options
->ConsensusParams
) {
2926 v3_out
->net_params
= smartlist_new();
2927 smartlist_split_string(v3_out
->net_params
,
2928 options
->ConsensusParams
, NULL
, 0, 0);
2929 smartlist_sort_strings(v3_out
->net_params
);
2932 voter
= tor_malloc_zero(sizeof(networkstatus_voter_info_t
));
2933 voter
->nickname
= tor_strdup(options
->Nickname
);
2934 memcpy(voter
->identity_digest
, identity_digest
, DIGEST_LEN
);
2935 voter
->sigs
= smartlist_new();
2936 voter
->address
= hostname
;
2938 voter
->dir_port
= router_get_advertised_dir_port(options
, 0);
2939 voter
->or_port
= router_get_advertised_or_port(options
);
2940 voter
->contact
= tor_strdup(contact
);
2941 if (options
->V3AuthUseLegacyKey
) {
2942 authority_cert_t
*c
= get_my_v3_legacy_cert();
2944 if (crypto_pk_get_digest(c
->identity_key
, voter
->legacy_id_digest
)) {
2945 log_warn(LD_BUG
, "Unable to compute digest of legacy v3 identity key");
2946 memset(voter
->legacy_id_digest
, 0, DIGEST_LEN
);
2951 v3_out
->voters
= smartlist_new();
2952 smartlist_add(v3_out
->voters
, voter
);
2953 v3_out
->cert
= authority_cert_dup(cert
);
2954 v3_out
->routerstatus_list
= routerstatuses
;
2955 /* Note: networkstatus_digest is unset; it won't get set until we actually
2956 * format the vote. */
2961 /** For v2 authoritative directories only: Replace the contents of
2962 * <b>the_v2_networkstatus</b> with a newly generated network status
2964 static cached_dir_t
*
2965 generate_v2_networkstatus_opinion(void)
2967 cached_dir_t
*r
= NULL
;
2968 size_t len
, identity_pkey_len
;
2969 char *status
= NULL
, *client_versions
= NULL
, *server_versions
= NULL
,
2970 *identity_pkey
= NULL
, *hostname
= NULL
;
2972 const or_options_t
*options
= get_options();
2973 char fingerprint
[FINGERPRINT_LEN
+1];
2974 char published
[ISO_TIME_LEN
+1];
2975 char digest
[DIGEST_LEN
];
2977 crypto_pk_t
*private_key
;
2978 routerlist_t
*rl
= router_get_routerlist();
2979 time_t now
= time(NULL
);
2980 time_t cutoff
= now
- ROUTER_MAX_AGE_TO_PUBLISH
;
2981 int naming
= options
->NamingAuthoritativeDir
;
2982 int versioning
= options
->VersioningAuthoritativeDir
;
2983 int listbaddirs
= options
->AuthDirListBadDirs
;
2984 int listbadexits
= options
->AuthDirListBadExits
;
2985 int vote_on_hsdirs
= options
->VoteOnHidServDirectoriesV2
;
2986 const char *contact
;
2987 char *version_lines
= NULL
;
2988 smartlist_t
*routers
= NULL
;
2989 digestmap_t
*omit_as_sybil
= NULL
;
2991 private_key
= get_server_identity_key();
2993 if (resolve_my_address(LOG_WARN
, options
, &addr
, &hostname
)<0) {
2994 log_warn(LD_NET
, "Couldn't resolve my hostname");
2998 format_iso_time(published
, now
);
3000 client_versions
= format_versions_list(options
->RecommendedClientVersions
);
3001 server_versions
= format_versions_list(options
->RecommendedServerVersions
);
3003 if (crypto_pk_write_public_key_to_string(private_key
, &identity_pkey
,
3004 &identity_pkey_len
)<0) {
3005 log_warn(LD_BUG
,"Writing public key to string failed.");
3009 if (crypto_pk_get_fingerprint(private_key
, fingerprint
, 0)<0) {
3010 log_err(LD_BUG
, "Error computing fingerprint");
3014 contact
= options
->ContactInfo
;
3019 tor_asprintf(&version_lines
,
3020 "client-versions %s\nserver-versions %s\n",
3021 client_versions
, server_versions
);
3023 version_lines
= tor_strdup("");
3026 len
= 4096+strlen(client_versions
)+strlen(server_versions
);
3027 len
+= identity_pkey_len
*2;
3028 len
+= (RS_ENTRY_LEN
)*smartlist_len(rl
->routers
);
3030 status
= tor_malloc(len
);
3031 tor_snprintf(status
, len
,
3032 "network-status-version 2\n"
3033 "dir-source %s %s %d\n"
3037 "dir-options%s%s%s%s\n"
3038 "%s" /* client version line, server version line. */
3039 "dir-signing-key\n%s",
3040 hostname
, fmt_addr32(addr
),
3041 (int)router_get_advertised_dir_port(options
, 0),
3045 naming
? " Names" : "",
3046 listbaddirs
? " BadDirectories" : "",
3047 listbadexits
? " BadExits" : "",
3048 versioning
? " Versions" : "",
3051 outp
= status
+ strlen(status
);
3052 endp
= status
+ len
;
3054 /* precompute this part, since we need it to decide what "stable"
3056 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, ri
, {
3057 dirserv_set_router_is_running(ri
, now
);
3060 routers
= smartlist_new();
3061 smartlist_add_all(routers
, rl
->routers
);
3062 routers_sort_by_identity(routers
);
3063 omit_as_sybil
= get_possible_sybil_list(routers
);
3065 dirserv_compute_performance_thresholds(rl
, omit_as_sybil
);
3067 SMARTLIST_FOREACH_BEGIN(routers
, routerinfo_t
*, ri
) {
3068 if (ri
->cache_info
.published_on
>= cutoff
) {
3070 char *version
= version_from_platform(ri
->platform
);
3071 node_t
*node
= node_get_mutable_by_id(ri
->cache_info
.identity_digest
);
3076 set_routerstatus_from_routerinfo(&rs
, node
, ri
, now
,
3077 naming
, listbadexits
, listbaddirs
,
3080 if (digestmap_get(omit_as_sybil
, ri
->cache_info
.identity_digest
))
3081 clear_status_flags_on_sybil(&rs
);
3083 if (routerstatus_format_entry(outp
, endp
-outp
, &rs
, version
, NS_V2
)) {
3084 log_warn(LD_BUG
, "Unable to print router status.");
3089 outp
+= strlen(outp
);
3091 } SMARTLIST_FOREACH_END(ri
);
3093 if (tor_snprintf(outp
, endp
-outp
, "directory-signature %s\n",
3094 options
->Nickname
)<0) {
3095 log_warn(LD_BUG
, "Unable to write signature line.");
3098 if (router_get_networkstatus_v2_hash(status
, digest
)<0) {
3099 log_warn(LD_BUG
, "Unable to hash network status");
3102 outp
+= strlen(outp
);
3104 note_crypto_pk_op(SIGN_DIR
);
3105 if (router_append_dirobj_signature(outp
,endp
-outp
,digest
,DIGEST_LEN
,
3107 log_warn(LD_BUG
, "Unable to sign router status.");
3112 networkstatus_v2_t
*ns
;
3113 if (!(ns
= networkstatus_v2_parse_from_string(status
))) {
3114 log_err(LD_BUG
,"Generated a networkstatus we couldn't parse.");
3117 networkstatus_v2_free(ns
);
3121 cached_dir_t
**ns_ptr
= &the_v2_networkstatus
;
3123 cached_dir_decref(*ns_ptr
);
3124 *ns_ptr
= new_cached_dir(status
, now
);
3125 status
= NULL
; /* So it doesn't get double-freed. */
3126 the_v2_networkstatus_is_dirty
= 0;
3127 router_set_networkstatus_v2((*ns_ptr
)->dir
, now
, NS_GENERATED
, NULL
);
3132 tor_free(client_versions
);
3133 tor_free(server_versions
);
3134 tor_free(version_lines
);
3137 tor_free(identity_pkey
);
3138 smartlist_free(routers
);
3139 digestmap_free(omit_as_sybil
, NULL
);
3143 /** Given the portion of a networkstatus request URL after "tor/status/" in
3144 * <b>key</b>, append to <b>result</b> the digests of the identity keys of the
3145 * networkstatus objects that the client has requested. */
3147 dirserv_get_networkstatus_v2_fingerprints(smartlist_t
*result
,
3152 if (!cached_v2_networkstatus
)
3153 cached_v2_networkstatus
= digestmap_new();
3155 if (should_generate_v2_networkstatus())
3156 generate_v2_networkstatus_opinion();
3158 if (!strcmp(key
,"authority")) {
3159 if (authdir_mode_v2(get_options())) {
3160 const routerinfo_t
*me
= router_get_my_routerinfo();
3162 smartlist_add(result
,
3163 tor_memdup(me
->cache_info
.identity_digest
, DIGEST_LEN
));
3165 } else if (!strcmp(key
, "all")) {
3166 if (digestmap_size(cached_v2_networkstatus
)) {
3167 digestmap_iter_t
*iter
;
3168 iter
= digestmap_iter_init(cached_v2_networkstatus
);
3169 while (!digestmap_iter_done(iter
)) {
3172 digestmap_iter_get(iter
, &ident
, &val
);
3173 smartlist_add(result
, tor_memdup(ident
, DIGEST_LEN
));
3174 iter
= digestmap_iter_next(cached_v2_networkstatus
, iter
);
3177 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
3179 if (ds
->type
& V2_DIRINFO
)
3180 smartlist_add(result
, tor_memdup(ds
->digest
, DIGEST_LEN
)));
3182 smartlist_sort_digests(result
);
3183 if (smartlist_len(result
) == 0)
3184 log_info(LD_DIRSERV
,
3185 "Client requested 'all' network status objects; we have none.");
3186 } else if (!strcmpstart(key
, "fp/")) {
3187 dir_split_resource_into_fingerprints(key
+3, result
, NULL
,
3188 DSR_HEX
|DSR_SORT_UNIQ
);
3192 /** Look for a network status object as specified by <b>key</b>, which should
3193 * be either "authority" (to find a network status generated by us), a hex
3194 * identity digest (to find a network status generated by given directory), or
3195 * "all" (to return all the v2 network status objects we have).
3198 dirserv_get_networkstatus_v2(smartlist_t
*result
,
3201 cached_dir_t
*cached
;
3202 smartlist_t
*fingerprints
= smartlist_new();
3205 if (!cached_v2_networkstatus
)
3206 cached_v2_networkstatus
= digestmap_new();
3208 dirserv_get_networkstatus_v2_fingerprints(fingerprints
, key
);
3209 SMARTLIST_FOREACH_BEGIN(fingerprints
, const char *, fp
) {
3210 if (router_digest_is_me(fp
) && should_generate_v2_networkstatus())
3211 generate_v2_networkstatus_opinion();
3212 cached
= digestmap_get(cached_v2_networkstatus
, fp
);
3214 smartlist_add(result
, cached
);
3216 char hexbuf
[HEX_DIGEST_LEN
+1];
3217 base16_encode(hexbuf
, sizeof(hexbuf
), fp
, DIGEST_LEN
);
3218 log_info(LD_DIRSERV
, "Don't know about any network status with "
3219 "fingerprint '%s'", hexbuf
);
3221 } SMARTLIST_FOREACH_END(fp
);
3222 SMARTLIST_FOREACH(fingerprints
, char *, cp
, tor_free(cp
));
3223 smartlist_free(fingerprints
);
3226 /** As dirserv_get_routerdescs(), but instead of getting signed_descriptor_t
3227 * pointers, adds copies of digests to fps_out, and doesn't use the
3228 * /tor/server/ prefix. For a /d/ request, adds descriptor digests; for other
3229 * requests, adds identity digests.
3232 dirserv_get_routerdesc_fingerprints(smartlist_t
*fps_out
, const char *key
,
3233 const char **msg
, int for_unencrypted_conn
,
3239 if (!strcmp(key
, "all")) {
3240 routerlist_t
*rl
= router_get_routerlist();
3241 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
3242 smartlist_add(fps_out
,
3243 tor_memdup(r
->cache_info
.identity_digest
, DIGEST_LEN
)));
3244 /* Treat "all" requests as if they were unencrypted */
3245 for_unencrypted_conn
= 1;
3246 } else if (!strcmp(key
, "authority")) {
3247 const routerinfo_t
*ri
= router_get_my_routerinfo();
3249 smartlist_add(fps_out
,
3250 tor_memdup(ri
->cache_info
.identity_digest
, DIGEST_LEN
));
3251 } else if (!strcmpstart(key
, "d/")) {
3253 key
+= strlen("d/");
3254 dir_split_resource_into_fingerprints(key
, fps_out
, NULL
,
3255 DSR_HEX
|DSR_SORT_UNIQ
);
3256 } else if (!strcmpstart(key
, "fp/")) {
3257 key
+= strlen("fp/");
3258 dir_split_resource_into_fingerprints(key
, fps_out
, NULL
,
3259 DSR_HEX
|DSR_SORT_UNIQ
);
3261 *msg
= "Key not recognized";
3265 if (for_unencrypted_conn
) {
3266 /* Remove anything that insists it not be sent unencrypted. */
3267 SMARTLIST_FOREACH_BEGIN(fps_out
, char *, cp
) {
3268 const signed_descriptor_t
*sd
;
3270 sd
= get_signed_descriptor_by_fp(cp
,is_extrainfo
,0);
3271 else if (is_extrainfo
)
3272 sd
= extrainfo_get_by_descriptor_digest(cp
);
3274 sd
= router_get_by_descriptor_digest(cp
);
3275 if (sd
&& !sd
->send_unencrypted
) {
3277 SMARTLIST_DEL_CURRENT(fps_out
, cp
);
3279 } SMARTLIST_FOREACH_END(cp
);
3282 if (!smartlist_len(fps_out
)) {
3283 *msg
= "Servers unavailable";
3289 /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
3290 * <b>key</b>. The key should be either
3291 * - "/tor/server/authority" for our own routerinfo;
3292 * - "/tor/server/all" for all the routerinfos we have, concatenated;
3293 * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
3294 * hex identity digests; or
3295 * - "/tor/server/d/D" where D is a plus-separated sequence
3296 * of server descriptor digests, in hex.
3298 * Return 0 if we found some matching descriptors, or -1 if we do not
3299 * have any descriptors, no matching descriptors, or if we did not
3300 * recognize the key (URL).
3301 * If -1 is returned *<b>msg</b> will be set to an appropriate error
3304 * XXXX rename this function. It's only called from the controller.
3305 * XXXX in fact, refactor this function, merging as much as possible.
3308 dirserv_get_routerdescs(smartlist_t
*descs_out
, const char *key
,
3313 if (!strcmp(key
, "/tor/server/all")) {
3314 routerlist_t
*rl
= router_get_routerlist();
3315 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
3316 smartlist_add(descs_out
, &(r
->cache_info
)));
3317 } else if (!strcmp(key
, "/tor/server/authority")) {
3318 const routerinfo_t
*ri
= router_get_my_routerinfo();
3320 smartlist_add(descs_out
, (void*) &(ri
->cache_info
));
3321 } else if (!strcmpstart(key
, "/tor/server/d/")) {
3322 smartlist_t
*digests
= smartlist_new();
3323 key
+= strlen("/tor/server/d/");
3324 dir_split_resource_into_fingerprints(key
, digests
, NULL
,
3325 DSR_HEX
|DSR_SORT_UNIQ
);
3326 SMARTLIST_FOREACH(digests
, const char *, d
,
3328 signed_descriptor_t
*sd
= router_get_by_descriptor_digest(d
);
3330 smartlist_add(descs_out
,sd
);
3332 SMARTLIST_FOREACH(digests
, char *, d
, tor_free(d
));
3333 smartlist_free(digests
);
3334 } else if (!strcmpstart(key
, "/tor/server/fp/")) {
3335 smartlist_t
*digests
= smartlist_new();
3336 time_t cutoff
= time(NULL
) - ROUTER_MAX_AGE_TO_PUBLISH
;
3337 key
+= strlen("/tor/server/fp/");
3338 dir_split_resource_into_fingerprints(key
, digests
, NULL
,
3339 DSR_HEX
|DSR_SORT_UNIQ
);
3340 SMARTLIST_FOREACH_BEGIN(digests
, const char *, d
) {
3341 if (router_digest_is_me(d
)) {
3342 /* make sure desc_routerinfo exists */
3343 const routerinfo_t
*ri
= router_get_my_routerinfo();
3345 smartlist_add(descs_out
, (void*) &(ri
->cache_info
));
3347 const routerinfo_t
*ri
= router_get_by_id_digest(d
);
3348 /* Don't actually serve a descriptor that everyone will think is
3349 * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
3350 * Tors from downloading descriptors that they will throw away.
3352 if (ri
&& ri
->cache_info
.published_on
> cutoff
)
3353 smartlist_add(descs_out
, (void*) &(ri
->cache_info
));
3355 } SMARTLIST_FOREACH_END(d
);
3356 SMARTLIST_FOREACH(digests
, char *, d
, tor_free(d
));
3357 smartlist_free(digests
);
3359 *msg
= "Key not recognized";
3363 if (!smartlist_len(descs_out
)) {
3364 *msg
= "Servers unavailable";
3370 /** Called when a TLS handshake has completed successfully with a
3371 * router listening at <b>address</b>:<b>or_port</b>, and has yielded
3372 * a certificate with digest <b>digest_rcvd</b>.
3374 * Inform the reachability checker that we could get to this guy.
3377 dirserv_orconn_tls_done(const tor_addr_t
*addr
,
3379 const char *digest_rcvd
)
3381 node_t
*node
= NULL
;
3382 tor_addr_port_t orport
;
3383 routerinfo_t
*ri
= NULL
;
3384 time_t now
= time(NULL
);
3386 tor_assert(digest_rcvd
);
3388 node
= node_get_mutable_by_id(digest_rcvd
);
3389 if (node
== NULL
|| node
->ri
== NULL
)
3393 tor_addr_copy(&orport
.addr
, addr
);
3394 orport
.port
= or_port
;
3395 if (router_has_orport(ri
, &orport
)) {
3396 /* Found the right router. */
3397 if (!authdir_mode_bridge(get_options()) ||
3398 ri
->purpose
== ROUTER_PURPOSE_BRIDGE
) {
3399 char addrstr
[TOR_ADDR_BUF_LEN
];
3400 /* This is a bridge or we're not a bridge authorititative --
3401 mark it as reachable. */
3402 log_info(LD_DIRSERV
, "Found router %s to be reachable at %s:%d. Yay.",
3403 router_describe(ri
),
3404 tor_addr_to_str(addrstr
, addr
, sizeof(addrstr
), 1),
3406 if (tor_addr_family(addr
) == AF_INET
) {
3407 rep_hist_note_router_reachable(digest_rcvd
, addr
, or_port
, now
);
3408 node
->last_reachable
= now
;
3409 } else if (tor_addr_family(addr
) == AF_INET6
) {
3410 /* No rephist for IPv6. */
3411 node
->last_reachable6
= now
;
3417 /** Called when we, as an authority, receive a new router descriptor either as
3418 * an upload or a download. Used to decide whether to relaunch reachability
3419 * testing for the server. */
3421 dirserv_should_launch_reachability_test(const routerinfo_t
*ri
,
3422 const routerinfo_t
*ri_old
)
3424 if (!authdir_mode_handles_descs(get_options(), ri
->purpose
))
3427 /* New router: Launch an immediate reachability test, so we will have an
3428 * opinion soon in case we're generating a consensus soon */
3431 if (ri_old
->is_hibernating
&& !ri
->is_hibernating
) {
3432 /* It just came out of hibernation; launch a reachability test */
3435 if (! routers_have_same_or_addrs(ri
, ri_old
)) {
3436 /* Address or port changed; launch a reachability test */
3442 /** Helper function for dirserv_test_reachability(). Start a TLS
3443 * connection to <b>router</b>, and annotate it with when we started
3446 dirserv_single_reachability_test(time_t now
, routerinfo_t
*router
)
3448 channel_t
*chan
= NULL
;
3449 node_t
*node
= NULL
;
3450 tor_addr_t router_addr
;
3454 node
= node_get_mutable_by_id(router
->cache_info
.identity_digest
);
3458 log_debug(LD_OR
,"Testing reachability of %s at %s:%u.",
3459 router
->nickname
, router
->address
, router
->or_port
);
3460 tor_addr_from_ipv4h(&router_addr
, router
->addr
);
3461 chan
= channel_tls_connect(&router_addr
, router
->or_port
,
3462 router
->cache_info
.identity_digest
);
3463 if (chan
) command_setup_channel(chan
);
3465 /* Possible IPv6. */
3466 if (get_options()->AuthDirHasIPv6Connectivity
== 1 &&
3467 !tor_addr_is_null(&router
->ipv6_addr
)) {
3468 char addrstr
[TOR_ADDR_BUF_LEN
];
3469 log_debug(LD_OR
, "Testing reachability of %s at %s:%u.",
3471 tor_addr_to_str(addrstr
, &router
->ipv6_addr
, sizeof(addrstr
), 1),
3472 router
->ipv6_orport
);
3473 chan
= channel_tls_connect(&router
->ipv6_addr
, router
->ipv6_orport
,
3474 router
->cache_info
.identity_digest
);
3475 if (chan
) command_setup_channel(chan
);
3479 /** Auth dir server only: load balance such that we only
3480 * try a few connections per call.
3482 * The load balancing is such that if we get called once every ten
3483 * seconds, we will cycle through all the tests in
3484 * REACHABILITY_TEST_CYCLE_PERIOD seconds (a bit over 20 minutes).
3487 dirserv_test_reachability(time_t now
)
3489 /* XXX decide what to do here; see or-talk thread "purging old router
3490 * information, revocation." -NM
3491 * We can't afford to mess with this in 0.1.2.x. The reason is that
3492 * if we stop doing reachability tests on some of routerlist, then
3493 * we'll for-sure think they're down, which may have unexpected
3494 * effects in other parts of the code. It doesn't hurt much to do
3495 * the testing, and directory authorities are easy to upgrade. Let's
3496 * wait til 0.2.0. -RD */
3497 // time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
3498 routerlist_t
*rl
= router_get_routerlist();
3499 static char ctr
= 0;
3500 int bridge_auth
= authdir_mode_bridge(get_options());
3502 SMARTLIST_FOREACH_BEGIN(rl
->routers
, routerinfo_t
*, router
) {
3503 const char *id_digest
= router
->cache_info
.identity_digest
;
3504 if (router_is_me(router
))
3506 if (bridge_auth
&& router
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
3507 continue; /* bridge authorities only test reachability on bridges */
3508 // if (router->cache_info.published_on > cutoff)
3510 if ((((uint8_t)id_digest
[0]) % REACHABILITY_MODULO_PER_TEST
) == ctr
) {
3511 dirserv_single_reachability_test(now
, router
);
3513 } SMARTLIST_FOREACH_END(router
);
3514 ctr
= (ctr
+ 1) % REACHABILITY_MODULO_PER_TEST
; /* increment ctr */
3517 /** Given a fingerprint <b>fp</b> which is either set if we're looking for a
3518 * v2 status, or zeroes if we're looking for a v3 status, or a NUL-padded
3519 * flavor name if we want a flavored v3 status, return a pointer to the
3520 * appropriate cached dir object, or NULL if there isn't one available. */
3521 static cached_dir_t
*
3522 lookup_cached_dir_by_fp(const char *fp
)
3524 cached_dir_t
*d
= NULL
;
3525 if (tor_digest_is_zero(fp
) && cached_consensuses
)
3526 d
= strmap_get(cached_consensuses
, "ns");
3527 else if (memchr(fp
, '\0', DIGEST_LEN
) && cached_consensuses
&&
3528 (d
= strmap_get(cached_consensuses
, fp
))) {
3529 /* this here interface is a nasty hack XXXX024 */;
3530 } else if (router_digest_is_me(fp
) && the_v2_networkstatus
)
3531 d
= the_v2_networkstatus
;
3532 else if (cached_v2_networkstatus
)
3533 d
= digestmap_get(cached_v2_networkstatus
, fp
);
3537 /** Remove from <b>fps</b> every networkstatus key where both
3538 * a) we have a networkstatus document and
3539 * b) it is not newer than <b>cutoff</b>.
3541 * Return 1 if any items were present at all; else return 0.
3544 dirserv_remove_old_statuses(smartlist_t
*fps
, time_t cutoff
)
3547 SMARTLIST_FOREACH_BEGIN(fps
, char *, digest
) {
3548 cached_dir_t
*d
= lookup_cached_dir_by_fp(digest
);
3552 if (d
->published
<= cutoff
) {
3554 SMARTLIST_DEL_CURRENT(fps
, digest
);
3556 } SMARTLIST_FOREACH_END(digest
);
3561 /** Return the cache-info for identity fingerprint <b>fp</b>, or
3562 * its extra-info document if <b>extrainfo</b> is true. Return
3563 * NULL if not found or if the descriptor is older than
3564 * <b>publish_cutoff</b>. */
3565 static const signed_descriptor_t
*
3566 get_signed_descriptor_by_fp(const char *fp
, int extrainfo
,
3567 time_t publish_cutoff
)
3569 if (router_digest_is_me(fp
)) {
3571 return &(router_get_my_extrainfo()->cache_info
);
3573 return &(router_get_my_routerinfo()->cache_info
);
3575 const routerinfo_t
*ri
= router_get_by_id_digest(fp
);
3577 ri
->cache_info
.published_on
> publish_cutoff
) {
3579 return extrainfo_get_by_descriptor_digest(
3580 ri
->cache_info
.extra_info_digest
);
3582 return &ri
->cache_info
;
3588 /** Return true iff we have any of the documents (extrainfo or routerdesc)
3589 * specified by the fingerprints in <b>fps</b> and <b>spool_src</b>. Used to
3590 * decide whether to send a 404. */
3592 dirserv_have_any_serverdesc(smartlist_t
*fps
, int spool_src
)
3594 time_t publish_cutoff
= time(NULL
)-ROUTER_MAX_AGE_TO_PUBLISH
;
3595 SMARTLIST_FOREACH_BEGIN(fps
, const char *, fp
) {
3598 case DIR_SPOOL_EXTRA_BY_DIGEST
:
3599 if (extrainfo_get_by_descriptor_digest(fp
)) return 1;
3601 case DIR_SPOOL_SERVER_BY_DIGEST
:
3602 if (router_get_by_descriptor_digest(fp
)) return 1;
3604 case DIR_SPOOL_EXTRA_BY_FP
:
3605 case DIR_SPOOL_SERVER_BY_FP
:
3606 if (get_signed_descriptor_by_fp(fp
,
3607 spool_src
== DIR_SPOOL_EXTRA_BY_FP
, publish_cutoff
))
3611 } SMARTLIST_FOREACH_END(fp
);
3615 /** Return true iff any of the 256-bit elements in <b>fps</b> is the digest of
3616 * a microdescriptor we have. */
3618 dirserv_have_any_microdesc(const smartlist_t
*fps
)
3620 microdesc_cache_t
*cache
= get_microdesc_cache();
3621 SMARTLIST_FOREACH(fps
, const char *, fp
,
3622 if (microdesc_cache_lookup_by_digest256(cache
, fp
))
3627 /** Return an approximate estimate of the number of bytes that will
3628 * be needed to transmit the server descriptors (if is_serverdescs --
3629 * they can be either d/ or fp/ queries) or networkstatus objects (if
3630 * !is_serverdescs) listed in <b>fps</b>. If <b>compressed</b> is set,
3631 * we guess how large the data will be after compression.
3633 * The return value is an estimate; it might be larger or smaller.
3636 dirserv_estimate_data_size(smartlist_t
*fps
, int is_serverdescs
,
3641 if (is_serverdescs
) {
3642 int n
= smartlist_len(fps
);
3643 const routerinfo_t
*me
= router_get_my_routerinfo();
3644 result
= (me
?me
->cache_info
.signed_descriptor_len
:2048) * n
;
3646 result
/= 2; /* observed compressibility is between 35 and 55%. */
3649 SMARTLIST_FOREACH(fps
, const char *, digest
, {
3650 cached_dir_t
*dir
= lookup_cached_dir_by_fp(digest
);
3652 result
+= compressed
? dir
->dir_z_len
: dir
->dir_len
;
3658 /** Given a list of microdescriptor hashes, guess how many bytes will be
3659 * needed to transmit them, and return the guess. */
3661 dirserv_estimate_microdesc_size(const smartlist_t
*fps
, int compressed
)
3663 size_t result
= smartlist_len(fps
) * microdesc_average_size(NULL
);
3669 /** When we're spooling data onto our outbuf, add more whenever we dip
3670 * below this threshold. */
3671 #define DIRSERV_BUFFER_MIN 16384
3673 /** Spooling helper: called when we have no more data to spool to <b>conn</b>.
3674 * Flushes any remaining data to be (un)compressed, and changes the spool
3675 * source to NONE. Returns 0 on success, negative on failure. */
3677 connection_dirserv_finish_spooling(dir_connection_t
*conn
)
3679 if (conn
->zlib_state
) {
3680 connection_write_to_buf_zlib("", 0, conn
, 1);
3681 tor_zlib_free(conn
->zlib_state
);
3682 conn
->zlib_state
= NULL
;
3684 conn
->dir_spool_src
= DIR_SPOOL_NONE
;
3688 /** Spooling helper: called when we're sending a bunch of server descriptors,
3689 * and the outbuf has become too empty. Pulls some entries from
3690 * fingerprint_stack, and writes the corresponding servers onto outbuf. If we
3691 * run out of entries, flushes the zlib state and sets the spool source to
3692 * NONE. Returns 0 on success, negative on failure.
3695 connection_dirserv_add_servers_to_outbuf(dir_connection_t
*conn
)
3697 int by_fp
= (conn
->dir_spool_src
== DIR_SPOOL_SERVER_BY_FP
||
3698 conn
->dir_spool_src
== DIR_SPOOL_EXTRA_BY_FP
);
3699 int extra
= (conn
->dir_spool_src
== DIR_SPOOL_EXTRA_BY_FP
||
3700 conn
->dir_spool_src
== DIR_SPOOL_EXTRA_BY_DIGEST
);
3701 time_t publish_cutoff
= time(NULL
)-ROUTER_MAX_AGE_TO_PUBLISH
;
3703 const or_options_t
*options
= get_options();
3705 while (smartlist_len(conn
->fingerprint_stack
) &&
3706 connection_get_outbuf_len(TO_CONN(conn
)) < DIRSERV_BUFFER_MIN
) {
3708 char *fp
= smartlist_pop_last(conn
->fingerprint_stack
);
3709 const signed_descriptor_t
*sd
= NULL
;
3711 sd
= get_signed_descriptor_by_fp(fp
, extra
, publish_cutoff
);
3713 sd
= extra
? extrainfo_get_by_descriptor_digest(fp
)
3714 : router_get_by_descriptor_digest(fp
);
3719 if (!connection_dir_is_encrypted(conn
) && !sd
->send_unencrypted
) {
3720 /* we did this check once before (so we could have an accurate size
3721 * estimate and maybe send a 404 if somebody asked for only bridges on a
3722 * connection), but we need to do it again in case a previously
3723 * unknown bridge descriptor has shown up between then and now. */
3727 /** If we are the bridge authority and the descriptor is a bridge
3728 * descriptor, remember that we served this descriptor for desc stats. */
3729 if (options
->BridgeAuthoritativeDir
&& by_fp
) {
3730 const routerinfo_t
*router
=
3731 router_get_by_id_digest(sd
->identity_digest
);
3732 /* router can be NULL here when the bridge auth is asked for its own
3734 if (router
&& router
->purpose
== ROUTER_PURPOSE_BRIDGE
)
3735 rep_hist_note_desc_served(sd
->identity_digest
);
3737 body
= signed_descriptor_get_body(sd
);
3738 if (conn
->zlib_state
) {
3739 /* XXXX024 This 'last' business should actually happen on the last
3740 * routerinfo, not on the last fingerprint. */
3741 int last
= ! smartlist_len(conn
->fingerprint_stack
);
3742 connection_write_to_buf_zlib(body
, sd
->signed_descriptor_len
, conn
,
3745 tor_zlib_free(conn
->zlib_state
);
3746 conn
->zlib_state
= NULL
;
3749 connection_write_to_buf(body
,
3750 sd
->signed_descriptor_len
,
3755 if (!smartlist_len(conn
->fingerprint_stack
)) {
3756 /* We just wrote the last one; finish up. */
3757 conn
->dir_spool_src
= DIR_SPOOL_NONE
;
3758 smartlist_free(conn
->fingerprint_stack
);
3759 conn
->fingerprint_stack
= NULL
;
3764 /** Spooling helper: called when we're sending a bunch of microdescriptors,
3765 * and the outbuf has become too empty. Pulls some entries from
3766 * fingerprint_stack, and writes the corresponding microdescs onto outbuf. If
3767 * we run out of entries, flushes the zlib state and sets the spool source to
3768 * NONE. Returns 0 on success, negative on failure.
3771 connection_dirserv_add_microdescs_to_outbuf(dir_connection_t
*conn
)
3773 microdesc_cache_t
*cache
= get_microdesc_cache();
3774 while (smartlist_len(conn
->fingerprint_stack
) &&
3775 connection_get_outbuf_len(TO_CONN(conn
)) < DIRSERV_BUFFER_MIN
) {
3776 char *fp256
= smartlist_pop_last(conn
->fingerprint_stack
);
3777 microdesc_t
*md
= microdesc_cache_lookup_by_digest256(cache
, fp256
);
3781 if (conn
->zlib_state
) {
3782 /* XXXX024 This 'last' business should actually happen on the last
3783 * routerinfo, not on the last fingerprint. */
3784 int last
= !smartlist_len(conn
->fingerprint_stack
);
3785 connection_write_to_buf_zlib(md
->body
, md
->bodylen
, conn
, last
);
3787 tor_zlib_free(conn
->zlib_state
);
3788 conn
->zlib_state
= NULL
;
3791 connection_write_to_buf(md
->body
, md
->bodylen
, TO_CONN(conn
));
3794 if (!smartlist_len(conn
->fingerprint_stack
)) {
3795 conn
->dir_spool_src
= DIR_SPOOL_NONE
;
3796 smartlist_free(conn
->fingerprint_stack
);
3797 conn
->fingerprint_stack
= NULL
;
3802 /** Spooling helper: Called when we're sending a directory or networkstatus,
3803 * and the outbuf has become too empty. Pulls some bytes from
3804 * <b>conn</b>-\>cached_dir-\>dir_z, uncompresses them if appropriate, and
3805 * puts them on the outbuf. If we run out of entries, flushes the zlib state
3806 * and sets the spool source to NONE. Returns 0 on success, negative on
3809 connection_dirserv_add_dir_bytes_to_outbuf(dir_connection_t
*conn
)
3814 bytes
= DIRSERV_BUFFER_MIN
- connection_get_outbuf_len(TO_CONN(conn
));
3815 tor_assert(bytes
> 0);
3816 tor_assert(conn
->cached_dir
);
3819 remaining
= conn
->cached_dir
->dir_z_len
- conn
->cached_dir_offset
;
3820 if (bytes
> remaining
)
3821 bytes
= (ssize_t
) remaining
;
3823 if (conn
->zlib_state
) {
3824 connection_write_to_buf_zlib(
3825 conn
->cached_dir
->dir_z
+ conn
->cached_dir_offset
,
3826 bytes
, conn
, bytes
== remaining
);
3828 connection_write_to_buf(conn
->cached_dir
->dir_z
+ conn
->cached_dir_offset
,
3829 bytes
, TO_CONN(conn
));
3831 conn
->cached_dir_offset
+= bytes
;
3832 if (conn
->cached_dir_offset
== (int)conn
->cached_dir
->dir_z_len
) {
3833 /* We just wrote the last one; finish up. */
3834 connection_dirserv_finish_spooling(conn
);
3835 cached_dir_decref(conn
->cached_dir
);
3836 conn
->cached_dir
= NULL
;
3841 /** Spooling helper: Called when we're spooling networkstatus objects on
3842 * <b>conn</b>, and the outbuf has become too empty. If the current
3843 * networkstatus object (in <b>conn</b>-\>cached_dir) has more data, pull data
3844 * from there. Otherwise, pop the next fingerprint from fingerprint_stack,
3845 * and start spooling the next networkstatus. (A digest of all 0 bytes is
3846 * treated as a request for the current consensus.) If we run out of entries,
3847 * flushes the zlib state and sets the spool source to NONE. Returns 0 on
3848 * success, negative on failure. */
3850 connection_dirserv_add_networkstatus_bytes_to_outbuf(dir_connection_t
*conn
)
3853 while (connection_get_outbuf_len(TO_CONN(conn
)) < DIRSERV_BUFFER_MIN
) {
3854 if (conn
->cached_dir
) {
3855 int uncompressing
= (conn
->zlib_state
!= NULL
);
3856 int r
= connection_dirserv_add_dir_bytes_to_outbuf(conn
);
3857 if (conn
->dir_spool_src
== DIR_SPOOL_NONE
) {
3858 /* add_dir_bytes thinks we're done with the cached_dir. But we
3859 * may have more cached_dirs! */
3860 conn
->dir_spool_src
= DIR_SPOOL_NETWORKSTATUS
;
3861 /* This bit is tricky. If we were uncompressing the last
3862 * networkstatus, we may need to make a new zlib object to
3863 * uncompress the next one. */
3864 if (uncompressing
&& ! conn
->zlib_state
&&
3865 conn
->fingerprint_stack
&&
3866 smartlist_len(conn
->fingerprint_stack
)) {
3867 conn
->zlib_state
= tor_zlib_new(0, ZLIB_METHOD
);
3871 } else if (conn
->fingerprint_stack
&&
3872 smartlist_len(conn
->fingerprint_stack
)) {
3873 /* Add another networkstatus; start serving it. */
3874 char *fp
= smartlist_pop_last(conn
->fingerprint_stack
);
3875 cached_dir_t
*d
= lookup_cached_dir_by_fp(fp
);
3879 conn
->cached_dir
= d
;
3880 conn
->cached_dir_offset
= 0;
3883 connection_dirserv_finish_spooling(conn
);
3884 smartlist_free(conn
->fingerprint_stack
);
3885 conn
->fingerprint_stack
= NULL
;
3892 /** Called whenever we have flushed some directory data in state
3893 * SERVER_WRITING. */
3895 connection_dirserv_flushed_some(dir_connection_t
*conn
)
3897 tor_assert(conn
->base_
.state
== DIR_CONN_STATE_SERVER_WRITING
);
3899 if (connection_get_outbuf_len(TO_CONN(conn
)) >= DIRSERV_BUFFER_MIN
)
3902 switch (conn
->dir_spool_src
) {
3903 case DIR_SPOOL_EXTRA_BY_DIGEST
:
3904 case DIR_SPOOL_EXTRA_BY_FP
:
3905 case DIR_SPOOL_SERVER_BY_DIGEST
:
3906 case DIR_SPOOL_SERVER_BY_FP
:
3907 return connection_dirserv_add_servers_to_outbuf(conn
);
3908 case DIR_SPOOL_MICRODESC
:
3909 return connection_dirserv_add_microdescs_to_outbuf(conn
);
3910 case DIR_SPOOL_CACHED_DIR
:
3911 return connection_dirserv_add_dir_bytes_to_outbuf(conn
);
3912 case DIR_SPOOL_NETWORKSTATUS
:
3913 return connection_dirserv_add_networkstatus_bytes_to_outbuf(conn
);
3914 case DIR_SPOOL_NONE
:
3920 /** Release all storage used by the directory server. */
3922 dirserv_free_all(void)
3924 dirserv_free_fingerprint_list();
3926 cached_dir_decref(the_directory
);
3927 clear_cached_dir(&the_runningrouters
);
3928 cached_dir_decref(the_v2_networkstatus
);
3929 cached_dir_decref(cached_directory
);
3930 clear_cached_dir(&cached_runningrouters
);
3932 digestmap_free(cached_v2_networkstatus
, free_cached_dir_
);
3933 cached_v2_networkstatus
= NULL
;
3934 strmap_free(cached_consensuses
, free_cached_dir_
);
3935 cached_consensuses
= NULL
;