1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2010, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 #define DIRSERV_PRIVATE
10 #include "connection.h"
11 #include "connection_or.h"
13 #include "directory.h"
16 #include "hibernate.h"
17 #include "microdesc.h"
18 #include "networkstatus.h"
22 #include "routerlist.h"
23 #include "routerparse.h"
27 * \brief Directory server core implementation. Manages directory
28 * contents and generates directories.
31 /** How far in the future do we allow a router to get? (seconds) */
32 #define ROUTER_ALLOW_SKEW (60*60*12)
33 /** How many seconds do we wait before regenerating the directory? */
34 #define DIR_REGEN_SLACK_TIME 30
35 /** If we're a cache, keep this many networkstatuses around from non-trusted
36 * directory authorities. */
37 #define MAX_UNTRUSTED_NETWORKSTATUSES 16
39 /** If a v1 directory is older than this, discard it. */
40 #define MAX_V1_DIRECTORY_AGE (30*24*60*60)
41 /** If a v1 running-routers is older than this, discard it. */
42 #define MAX_V1_RR_AGE (7*24*60*60)
44 extern time_t time_of_process_start
; /* from main.c */
46 /** Do we need to regenerate the v1 directory when someone asks for it? */
47 static time_t the_directory_is_dirty
= 1;
48 /** Do we need to regenerate the v1 runningrouters document when somebody
50 static time_t runningrouters_is_dirty
= 1;
51 /** Do we need to regenerate our v2 networkstatus document when somebody asks
53 static time_t the_v2_networkstatus_is_dirty
= 1;
55 /** Most recently generated encoded signed v1 directory. (v1 auth dirservers
57 static cached_dir_t
*the_directory
= NULL
;
59 /** For authoritative directories: the current (v1) network status. */
60 static cached_dir_t the_runningrouters
;
62 static void directory_remove_invalid(void);
63 static cached_dir_t
*dirserv_regenerate_directory(void);
64 static char *format_versions_list(config_line_t
*ln
);
65 struct authdir_config_t
;
66 static int add_fingerprint_to_dir(const char *nickname
, const char *fp
,
67 struct authdir_config_t
*list
);
68 static uint32_t dirserv_router_get_status(const routerinfo_t
*router
,
71 dirserv_get_status_impl(const char *fp
, const char *nickname
,
73 uint32_t addr
, uint16_t or_port
,
74 const char *platform
, const char *contact
,
75 const char **msg
, int should_log
);
76 static void clear_cached_dir(cached_dir_t
*d
);
77 static signed_descriptor_t
*get_signed_descriptor_by_fp(const char *fp
,
79 time_t publish_cutoff
);
80 static int dirserv_add_extrainfo(extrainfo_t
*ei
, const char **msg
);
82 /************** Measured Bandwidth parsing code ******/
83 #define MAX_MEASUREMENT_AGE (3*24*60*60) /* 3 days */
85 /************** Fingerprint handling code ************/
87 #define FP_NAMED 1 /**< Listed in fingerprint file. */
88 #define FP_INVALID 2 /**< Believed invalid. */
89 #define FP_REJECT 4 /**< We will not publish this router. */
90 #define FP_BADDIR 8 /**< We'll tell clients to avoid using this as a dir. */
91 #define FP_BADEXIT 16 /**< We'll tell clients not to use this as an exit. */
92 #define FP_UNNAMED 32 /**< Another router has this name in fingerprint file. */
94 /** Encapsulate a nickname and an FP_* status; target of status_by_digest
96 typedef struct router_status_t
{
97 char nickname
[MAX_NICKNAME_LEN
+1];
101 /** List of nickname-\>identity fingerprint mappings for all the routers
102 * that we name. Used to prevent router impersonation. */
103 typedef struct authdir_config_t
{
104 strmap_t
*fp_by_name
; /**< Map from lc nickname to fingerprint. */
105 digestmap_t
*status_by_digest
; /**< Map from digest to router_status_t. */
108 /** Should be static; exposed for testing. */
109 static authdir_config_t
*fingerprint_list
= NULL
;
111 /** Allocate and return a new, empty, authdir_config_t. */
112 static authdir_config_t
*
113 authdir_config_new(void)
115 authdir_config_t
*list
= tor_malloc_zero(sizeof(authdir_config_t
));
116 list
->fp_by_name
= strmap_new();
117 list
->status_by_digest
= digestmap_new();
121 /** Add the fingerprint <b>fp</b> for <b>nickname</b> to
122 * the smartlist of fingerprint_entry_t's <b>list</b>. Return 0 if it's
123 * new, or 1 if we replaced the old value.
126 add_fingerprint_to_dir(const char *nickname
, const char *fp
,
127 authdir_config_t
*list
)
131 router_status_t
*status
;
132 tor_assert(nickname
);
136 fingerprint
= tor_strdup(fp
);
137 tor_strstrip(fingerprint
, " ");
138 if (base16_decode(d
, DIGEST_LEN
, fingerprint
, strlen(fingerprint
))) {
139 log_warn(LD_DIRSERV
, "Couldn't decode fingerprint \"%s\"",
141 tor_free(fingerprint
);
145 if (!strcasecmp(nickname
, UNNAMED_ROUTER_NICKNAME
)) {
146 log_warn(LD_DIRSERV
, "Tried to add a mapping for reserved nickname %s",
147 UNNAMED_ROUTER_NICKNAME
);
148 tor_free(fingerprint
);
152 status
= digestmap_get(list
->status_by_digest
, d
);
154 status
= tor_malloc_zero(sizeof(router_status_t
));
155 digestmap_set(list
->status_by_digest
, d
, status
);
158 if (nickname
[0] != '!') {
159 char *old_fp
= strmap_get_lc(list
->fp_by_name
, nickname
);
160 if (old_fp
&& !strcasecmp(fingerprint
, old_fp
)) {
161 tor_free(fingerprint
);
164 strmap_set_lc(list
->fp_by_name
, nickname
, fingerprint
);
166 status
->status
|= FP_NAMED
;
167 strlcpy(status
->nickname
, nickname
, sizeof(status
->nickname
));
169 tor_free(fingerprint
);
170 if (!strcasecmp(nickname
, "!reject")) {
171 status
->status
|= FP_REJECT
;
172 } else if (!strcasecmp(nickname
, "!invalid")) {
173 status
->status
|= FP_INVALID
;
174 } else if (!strcasecmp(nickname
, "!baddir")) {
175 status
->status
|= FP_BADDIR
;
176 } else if (!strcasecmp(nickname
, "!badexit")) {
177 status
->status
|= FP_BADEXIT
;
183 /** Add the nickname and fingerprint for this OR to the
184 * global list of recognized identity key fingerprints. */
186 dirserv_add_own_fingerprint(const char *nickname
, crypto_pk_env_t
*pk
)
188 char fp
[FINGERPRINT_LEN
+1];
189 if (crypto_pk_get_fingerprint(pk
, fp
, 0)<0) {
190 log_err(LD_BUG
, "Error computing fingerprint");
193 if (!fingerprint_list
)
194 fingerprint_list
= authdir_config_new();
195 add_fingerprint_to_dir(nickname
, fp
, fingerprint_list
);
199 /** Load the nickname-\>fingerprint mappings stored in the approved-routers
200 * file. The file format is line-based, with each non-blank holding one
201 * nickname, some space, and a fingerprint for that nickname. On success,
202 * replace the current fingerprint list with the new list and return 0. On
203 * failure, leave the current fingerprint list untouched, and return -1. */
205 dirserv_load_fingerprint_file(void)
209 char *nickname
, *fingerprint
;
210 authdir_config_t
*fingerprint_list_new
;
212 config_line_t
*front
=NULL
, *list
;
213 or_options_t
*options
= get_options();
215 fname
= get_datadir_fname("approved-routers");
217 "Reloading approved fingerprints from \"%s\"...", fname
);
219 cf
= read_file_to_str(fname
, RFTS_IGNORE_MISSING
, NULL
);
221 if (options
->NamingAuthoritativeDir
) {
222 log_warn(LD_FS
, "Cannot open fingerprint file '%s'. Failing.", fname
);
226 log_info(LD_FS
, "Cannot open fingerprint file '%s'. That's ok.", fname
);
233 result
= config_get_lines(cf
, &front
);
236 log_warn(LD_CONFIG
, "Error reading from fingerprint file");
240 fingerprint_list_new
= authdir_config_new();
242 for (list
=front
; list
; list
=list
->next
) {
243 char digest_tmp
[DIGEST_LEN
];
244 nickname
= list
->key
; fingerprint
= list
->value
;
245 if (strlen(nickname
) > MAX_NICKNAME_LEN
) {
246 log_notice(LD_CONFIG
,
247 "Nickname '%s' too long in fingerprint file. Skipping.",
251 if (!is_legal_nickname(nickname
) &&
252 strcasecmp(nickname
, "!reject") &&
253 strcasecmp(nickname
, "!invalid") &&
254 strcasecmp(nickname
, "!badexit")) {
255 log_notice(LD_CONFIG
,
256 "Invalid nickname '%s' in fingerprint file. Skipping.",
260 tor_strstrip(fingerprint
, " "); /* remove spaces */
261 if (strlen(fingerprint
) != HEX_DIGEST_LEN
||
262 base16_decode(digest_tmp
, sizeof(digest_tmp
),
263 fingerprint
, HEX_DIGEST_LEN
) < 0) {
264 log_notice(LD_CONFIG
,
265 "Invalid fingerprint (nickname '%s', "
266 "fingerprint %s). Skipping.",
267 nickname
, fingerprint
);
270 if (0==strcasecmp(nickname
, DEFAULT_CLIENT_NICKNAME
)) {
271 /* If you approved an OR called "client", then clients who use
272 * the default nickname could all be rejected. That's no good. */
273 log_notice(LD_CONFIG
,
274 "Authorizing nickname '%s' would break "
275 "many clients; skipping.",
276 DEFAULT_CLIENT_NICKNAME
);
279 if (0==strcasecmp(nickname
, UNNAMED_ROUTER_NICKNAME
)) {
280 /* If you approved an OR called "unnamed", then clients will be
282 log_notice(LD_CONFIG
,
283 "Authorizing nickname '%s' is not allowed; skipping.",
284 UNNAMED_ROUTER_NICKNAME
);
287 if (add_fingerprint_to_dir(nickname
, fingerprint
, fingerprint_list_new
)
289 log_notice(LD_CONFIG
, "Duplicate nickname '%s'.", nickname
);
292 config_free_lines(front
);
293 dirserv_free_fingerprint_list();
294 fingerprint_list
= fingerprint_list_new
;
295 /* Delete any routers whose fingerprints we no longer recognize */
296 directory_remove_invalid();
300 /** Check whether <b>router</b> has a nickname/identity key combination that
301 * we recognize from the fingerprint list, or an IP we automatically act on
302 * according to our configuration. Return the appropriate router status.
304 * If the status is 'FP_REJECT' and <b>msg</b> is provided, set
305 * *<b>msg</b> to an explanation of why. */
307 dirserv_router_get_status(const routerinfo_t
*router
, const char **msg
)
311 if (crypto_pk_get_digest(router
->identity_pkey
, d
)) {
312 log_warn(LD_BUG
,"Error computing fingerprint");
314 *msg
= "Bug: Error computing fingerprint";
318 return dirserv_get_status_impl(d
, router
->nickname
,
320 router
->addr
, router
->or_port
,
321 router
->platform
, router
->contact_info
,
325 /** Return true if there is no point in downloading the router described by
326 * <b>rs</b> because this directory would reject it. */
328 dirserv_would_reject_router(routerstatus_t
*rs
)
332 res
= dirserv_get_status_impl(rs
->identity_digest
, rs
->nickname
,
333 "", /* address is only used in logs */
334 rs
->addr
, rs
->or_port
,
338 return (res
& FP_REJECT
) != 0;
341 /** Helper: Based only on the ID/Nickname combination,
342 * return FP_UNNAMED (unnamed), FP_NAMED (named), or 0 (neither).
345 dirserv_get_name_status(const char *id_digest
, const char *nickname
)
347 char fp
[HEX_DIGEST_LEN
+1];
350 base16_encode(fp
, sizeof(fp
), id_digest
, DIGEST_LEN
);
353 strmap_get_lc(fingerprint_list
->fp_by_name
, nickname
))) {
354 if (!strcasecmp(fp
, fp_by_name
)) {
357 return FP_UNNAMED
; /* Wrong fingerprint. */
363 /** Helper: As dirserv_get_router_status, but takes the router fingerprint
364 * (hex, no spaces), nickname, address (used for logging only), IP address, OR
365 * port, platform (logging only) and contact info (logging only) as arguments.
367 * If should_log is false, do not log messages. (There's not much point in
368 * logging that we're rejecting servers we'll not download.)
371 dirserv_get_status_impl(const char *id_digest
, const char *nickname
,
373 uint32_t addr
, uint16_t or_port
,
374 const char *platform
, const char *contact
,
375 const char **msg
, int should_log
)
377 int reject_unlisted
= get_options()->AuthDirRejectUnlisted
;
379 router_status_t
*status_by_digest
;
381 if (!fingerprint_list
)
382 fingerprint_list
= authdir_config_new();
385 log_debug(LD_DIRSERV
, "%d fingerprints, %d digests known.",
386 strmap_size(fingerprint_list
->fp_by_name
),
387 digestmap_size(fingerprint_list
->status_by_digest
));
389 /* Tor 0.1.2.x is pretty old, but there are a lot of them running still,
390 * and there aren't any critical relay-side vulnerabilities. Once more
391 * of them die off, we should raise this minimum to 0.2.0.x. */
392 if (platform
&& !tor_version_as_new_as(platform
,"0.1.2.14")) {
394 *msg
= "Tor version is far too old to work.";
398 result
= dirserv_get_name_status(id_digest
, nickname
);
399 if (result
& FP_NAMED
) {
401 log_debug(LD_DIRSERV
,"Good fingerprint for '%s'",nickname
);
403 if (result
& FP_UNNAMED
) {
405 char *esc_contact
= esc_for_log(contact
);
407 "Mismatched fingerprint for '%s'. "
408 "ContactInfo '%s', platform '%s'.)",
411 platform
? escaped(platform
) : "");
412 tor_free(esc_contact
);
415 *msg
= "Rejected: There is already a named server with this nickname "
416 "and a different fingerprint.";
419 status_by_digest
= digestmap_get(fingerprint_list
->status_by_digest
,
421 if (status_by_digest
)
422 result
|= (status_by_digest
->status
& ~FP_NAMED
);
424 if (result
& FP_REJECT
) {
426 *msg
= "Fingerprint is marked rejected";
428 } else if (result
& FP_INVALID
) {
430 *msg
= "Fingerprint is marked invalid";
433 if (authdir_policy_baddir_address(addr
, or_port
)) {
436 "Marking '%s' as bad directory because of address '%s'",
441 if (authdir_policy_badexit_address(addr
, or_port
)) {
443 log_info(LD_DIRSERV
, "Marking '%s' as bad exit because of address '%s'",
445 result
|= FP_BADEXIT
;
448 if (!(result
& FP_NAMED
)) {
449 if (!authdir_policy_permits_address(addr
, or_port
)) {
451 log_info(LD_DIRSERV
, "Rejecting '%s' because of address '%s'",
454 *msg
= "Authdir is rejecting routers in this range.";
457 if (!authdir_policy_valid_address(addr
, or_port
)) {
459 log_info(LD_DIRSERV
, "Not marking '%s' valid because of address '%s'",
461 result
|= FP_INVALID
;
463 if (reject_unlisted
) {
465 *msg
= "Authdir rejects unknown routers.";
473 /** If we are an authoritative dirserver, and the list of approved
474 * servers contains one whose identity key digest is <b>digest</b>,
475 * return that router's nickname. Otherwise return NULL. */
477 dirserv_get_nickname_by_digest(const char *digest
)
479 router_status_t
*status
;
480 if (!fingerprint_list
)
484 status
= digestmap_get(fingerprint_list
->status_by_digest
, digest
);
485 return status
? status
->nickname
: NULL
;
488 /** Clear the current fingerprint list. */
490 dirserv_free_fingerprint_list(void)
492 if (!fingerprint_list
)
495 strmap_free(fingerprint_list
->fp_by_name
, _tor_free
);
496 digestmap_free(fingerprint_list
->status_by_digest
, _tor_free
);
497 tor_free(fingerprint_list
);
504 /** Return -1 if <b>ri</b> has a private or otherwise bad address,
505 * unless we're configured to not care. Return 0 if all ok. */
507 dirserv_router_has_valid_address(routerinfo_t
*ri
)
509 struct in_addr iaddr
;
510 if (get_options()->DirAllowPrivateAddresses
)
511 return 0; /* whatever it is, we're fine with it */
512 if (!tor_inet_aton(ri
->address
, &iaddr
)) {
513 log_info(LD_DIRSERV
,"Router '%s' published non-IP address '%s'. Refusing.",
514 ri
->nickname
, ri
->address
);
517 if (is_internal_IP(ntohl(iaddr
.s_addr
), 0)) {
519 "Router '%s' published internal IP address '%s'. Refusing.",
520 ri
->nickname
, ri
->address
);
521 return -1; /* it's a private IP, we should reject it */
526 /** Check whether we, as a directory server, want to accept <b>ri</b>. If so,
527 * set its is_valid,named,running fields and return 0. Otherwise, return -1.
529 * If the router is rejected, set *<b>msg</b> to an explanation of why.
531 * If <b>complain</b> then explain at log-level 'notice' why we refused
532 * a descriptor; else explain at log-level 'info'.
535 authdir_wants_to_reject_router(routerinfo_t
*ri
, const char **msg
,
538 /* Okay. Now check whether the fingerprint is recognized. */
539 uint32_t status
= dirserv_router_get_status(ri
, msg
);
541 int severity
= (complain
&& ri
->contact_info
) ? LOG_NOTICE
: LOG_INFO
;
543 if (status
& FP_REJECT
)
544 return -1; /* msg is already set. */
546 /* Is there too much clock skew? */
548 if (ri
->cache_info
.published_on
> now
+ROUTER_ALLOW_SKEW
) {
549 log_fn(severity
, LD_DIRSERV
, "Publication time for nickname '%s' is too "
550 "far (%d minutes) in the future; possible clock skew. Not adding "
552 ri
->nickname
, (int)((ri
->cache_info
.published_on
-now
)/60),
553 esc_router_info(ri
));
554 *msg
= "Rejected: Your clock is set too far in the future, or your "
555 "timezone is not correct.";
558 if (ri
->cache_info
.published_on
< now
-ROUTER_MAX_AGE_TO_PUBLISH
) {
559 log_fn(severity
, LD_DIRSERV
,
560 "Publication time for router with nickname '%s' is too far "
561 "(%d minutes) in the past. Not adding (%s)",
562 ri
->nickname
, (int)((now
-ri
->cache_info
.published_on
)/60),
563 esc_router_info(ri
));
564 *msg
= "Rejected: Server is expired, or your clock is too far in the past,"
565 " or your timezone is not correct.";
568 if (dirserv_router_has_valid_address(ri
) < 0) {
569 log_fn(severity
, LD_DIRSERV
,
570 "Router with nickname '%s' has invalid address '%s'. "
572 ri
->nickname
, ri
->address
,
573 esc_router_info(ri
));
574 *msg
= "Rejected: Address is not an IP, or IP is a private address.";
577 /* Okay, looks like we're willing to accept this one. */
578 ri
->is_named
= (status
& FP_NAMED
) ? 1 : 0;
579 ri
->is_valid
= (status
& FP_INVALID
) ? 0 : 1;
580 ri
->is_bad_directory
= (status
& FP_BADDIR
) ? 1 : 0;
581 ri
->is_bad_exit
= (status
& FP_BADEXIT
) ? 1 : 0;
586 /** True iff <b>a</b> is more severe than <b>b</b>. */
588 WRA_MORE_SEVERE(was_router_added_t a
, was_router_added_t b
)
593 /** As for dirserv_add_descriptor(), but accepts multiple documents, and
594 * returns the most severe error that occurred for any one of them. */
596 dirserv_add_multiple_descriptors(const char *desc
, uint8_t purpose
,
600 was_router_added_t r
, r_tmp
;
605 time_t now
= time(NULL
);
606 char annotation_buf
[ROUTER_ANNOTATION_BUF_LEN
];
607 char time_buf
[ISO_TIME_LEN
+1];
608 int general
= purpose
== ROUTER_PURPOSE_GENERAL
;
611 r
=ROUTER_ADDED_SUCCESSFULLY
; /*Least severe return value. */
613 format_iso_time(time_buf
, now
);
614 if (tor_snprintf(annotation_buf
, sizeof(annotation_buf
),
617 "%s%s%s", time_buf
, escaped(source
),
618 !general
? "@purpose " : "",
619 !general
? router_purpose_to_string(purpose
) : "",
620 !general
? "\n" : "")<0) {
621 *msg
= "Couldn't format annotations";
626 list
= smartlist_create();
627 if (!router_parse_list_from_string(&s
, NULL
, list
, SAVED_NOWHERE
, 0, 0,
629 SMARTLIST_FOREACH(list
, routerinfo_t
*, ri
, {
631 tor_assert(ri
->purpose
== purpose
);
632 r_tmp
= dirserv_add_descriptor(ri
, &msg_out
, source
);
633 if (WRA_MORE_SEVERE(r_tmp
, r
)) {
639 n_parsed
+= smartlist_len(list
);
640 smartlist_clear(list
);
643 if (!router_parse_list_from_string(&s
, NULL
, list
, SAVED_NOWHERE
, 1, 0,
645 SMARTLIST_FOREACH(list
, extrainfo_t
*, ei
, {
648 r_tmp
= dirserv_add_extrainfo(ei
, &msg_out
);
649 if (WRA_MORE_SEVERE(r_tmp
, r
)) {
655 n_parsed
+= smartlist_len(list
);
656 smartlist_free(list
);
660 *msg
= "No descriptors found in your POST.";
661 if (WRA_WAS_ADDED(r
))
662 r
= ROUTER_WAS_NOT_NEW
;
664 *msg
= "(no message)";
671 /** Examine the parsed server descriptor in <b>ri</b> and maybe insert it into
672 * the list of server descriptors. Set *<b>msg</b> to a message that should be
673 * passed back to the origin of this descriptor, or NULL if there is no such
674 * message. Use <b>source</b> to produce better log messages.
676 * Return the status of the operation
678 * This function is only called when fresh descriptors are posted, not when
679 * we re-load the cache.
682 dirserv_add_descriptor(routerinfo_t
*ri
, const char **msg
, const char *source
)
684 was_router_added_t r
;
685 routerinfo_t
*ri_old
;
686 char *desc
, *nickname
;
690 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
691 * network and it'll clog everything up. */
692 if (ri
->cache_info
.signed_descriptor_len
> MAX_DESCRIPTOR_UPLOAD_SIZE
) {
693 log_notice(LD_DIR
, "Somebody attempted to publish a router descriptor '%s'"
694 " (source: %s) with size %d. Either this is an attack, or the "
695 "MAX_DESCRIPTOR_UPLOAD_SIZE (%d) constant is too low.",
696 ri
->nickname
, source
, (int)ri
->cache_info
.signed_descriptor_len
,
697 MAX_DESCRIPTOR_UPLOAD_SIZE
);
698 *msg
= "Router descriptor was too large";
699 control_event_or_authdir_new_descriptor("REJECTED",
700 ri
->cache_info
.signed_descriptor_body
,
701 ri
->cache_info
.signed_descriptor_len
, *msg
);
703 return ROUTER_AUTHDIR_REJECTS
;
706 /* Check whether this descriptor is semantically identical to the last one
707 * from this server. (We do this here and not in router_add_to_routerlist
708 * because we want to be able to accept the newest router descriptor that
709 * another authority has, so we all converge on the same one.) */
710 ri_old
= router_get_by_digest(ri
->cache_info
.identity_digest
);
711 if (ri_old
&& ri_old
->cache_info
.published_on
< ri
->cache_info
.published_on
712 && router_differences_are_cosmetic(ri_old
, ri
)
713 && !router_is_me(ri
)) {
715 "Not replacing descriptor from '%s' (source: %s); "
716 "differences are cosmetic.",
717 ri
->nickname
, source
);
718 *msg
= "Not replacing router descriptor; no information has changed since "
719 "the last one with this identity.";
720 control_event_or_authdir_new_descriptor("DROPPED",
721 ri
->cache_info
.signed_descriptor_body
,
722 ri
->cache_info
.signed_descriptor_len
, *msg
);
724 return ROUTER_WAS_NOT_NEW
;
727 /* Make a copy of desc, since router_add_to_routerlist might free
728 * ri and its associated signed_descriptor_t. */
729 desclen
= ri
->cache_info
.signed_descriptor_len
;
730 desc
= tor_strndup(ri
->cache_info
.signed_descriptor_body
, desclen
);
731 nickname
= tor_strdup(ri
->nickname
);
733 /* Tell if we're about to need to launch a test if we add this. */
734 ri
->needs_retest_if_added
=
735 dirserv_should_launch_reachability_test(ri
, ri_old
);
737 r
= router_add_to_routerlist(ri
, msg
, 0, 0);
738 if (!WRA_WAS_ADDED(r
)) {
739 /* unless the routerinfo was fine, just out-of-date */
740 if (WRA_WAS_REJECTED(r
))
741 control_event_or_authdir_new_descriptor("REJECTED", desc
, desclen
, *msg
);
743 "Did not add descriptor from '%s' (source: %s): %s.",
744 nickname
, source
, *msg
? *msg
: "(no message)");
746 smartlist_t
*changed
;
747 control_event_or_authdir_new_descriptor("ACCEPTED", desc
, desclen
, *msg
);
749 changed
= smartlist_create();
750 smartlist_add(changed
, ri
);
751 routerlist_descriptors_added(changed
, 0);
752 smartlist_free(changed
);
754 *msg
= ri
->is_valid
? "Descriptor for valid server accepted" :
755 "Descriptor for invalid server accepted";
758 "Added descriptor from '%s' (source: %s): %s.",
759 nickname
, source
, *msg
);
766 /** As dirserv_add_descriptor, but for an extrainfo_t <b>ei</b>. */
767 static was_router_added_t
768 dirserv_add_extrainfo(extrainfo_t
*ei
, const char **msg
)
775 ri
= router_get_by_digest(ei
->cache_info
.identity_digest
);
777 *msg
= "No corresponding router descriptor for extra-info descriptor";
779 return ROUTER_BAD_EI
;
782 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
783 * network and it'll clog everything up. */
784 if (ei
->cache_info
.signed_descriptor_len
> MAX_EXTRAINFO_UPLOAD_SIZE
) {
785 log_notice(LD_DIR
, "Somebody attempted to publish an extrainfo "
786 "with size %d. Either this is an attack, or the "
787 "MAX_EXTRAINFO_UPLOAD_SIZE (%d) constant is too low.",
788 (int)ei
->cache_info
.signed_descriptor_len
,
789 MAX_EXTRAINFO_UPLOAD_SIZE
);
790 *msg
= "Extrainfo document was too large";
792 return ROUTER_BAD_EI
;
795 if ((r
= routerinfo_incompatible_with_extrainfo(ri
, ei
, NULL
, msg
))) {
797 return r
< 0 ? ROUTER_WAS_NOT_NEW
: ROUTER_BAD_EI
;
799 router_add_extrainfo_to_routerlist(ei
, msg
, 0, 0);
800 return ROUTER_ADDED_SUCCESSFULLY
;
803 /** Remove all descriptors whose nicknames or fingerprints no longer
804 * are allowed by our fingerprint list. (Descriptors that used to be
805 * good can become bad when we reload the fingerprint list.)
808 directory_remove_invalid(void)
812 routerlist_t
*rl
= router_get_routerlist();
814 routerlist_assert_ok(rl
);
816 for (i
= 0; i
< smartlist_len(rl
->routers
); ++i
) {
818 routerinfo_t
*ent
= smartlist_get(rl
->routers
, i
);
819 uint32_t r
= dirserv_router_get_status(ent
, &msg
);
821 log_info(LD_DIRSERV
, "Router '%s' is now rejected: %s",
822 ent
->nickname
, msg
?msg
:"");
823 routerlist_remove(rl
, ent
, 0, time(NULL
));
828 if (bool_neq((r
& FP_NAMED
), ent
->is_named
)) {
830 "Router '%s' is now %snamed.", ent
->nickname
,
831 (r
&FP_NAMED
)?"":"un");
832 ent
->is_named
= (r
&FP_NAMED
)?1:0;
835 if (bool_neq((r
& FP_INVALID
), !ent
->is_valid
)) {
836 log_info(LD_DIRSERV
, "Router '%s' is now %svalid.", ent
->nickname
,
837 (r
&FP_INVALID
) ? "in" : "");
838 ent
->is_valid
= (r
&FP_INVALID
)?0:1;
841 if (bool_neq((r
& FP_BADDIR
), ent
->is_bad_directory
)) {
842 log_info(LD_DIRSERV
, "Router '%s' is now a %s directory", ent
->nickname
,
843 (r
& FP_BADDIR
) ? "bad" : "good");
844 ent
->is_bad_directory
= (r
&FP_BADDIR
) ? 1: 0;
847 if (bool_neq((r
& FP_BADEXIT
), ent
->is_bad_exit
)) {
848 log_info(LD_DIRSERV
, "Router '%s' is now a %s exit", ent
->nickname
,
849 (r
& FP_BADEXIT
) ? "bad" : "good");
850 ent
->is_bad_exit
= (r
&FP_BADEXIT
) ? 1: 0;
855 directory_set_dirty();
857 routerlist_assert_ok(rl
);
860 /** Mark the directory as <b>dirty</b> -- when we're next asked for a
861 * directory, we will rebuild it instead of reusing the most recently
865 directory_set_dirty(void)
867 time_t now
= time(NULL
);
870 /* Regenerate stubs only every 8 hours.
871 * XXXX It would be nice to generate less often, but these are just
872 * stubs: it doesn't matter. */
873 #define STUB_REGENERATE_INTERVAL (8*60*60)
874 if (!the_directory
|| !the_runningrouters
.dir
)
876 else if (the_directory
->published
< now
- STUB_REGENERATE_INTERVAL
||
877 the_runningrouters
.published
< now
- STUB_REGENERATE_INTERVAL
)
881 if (!the_directory_is_dirty
)
882 the_directory_is_dirty
= now
;
883 if (!runningrouters_is_dirty
)
884 runningrouters_is_dirty
= now
;
886 if (!the_v2_networkstatus_is_dirty
)
887 the_v2_networkstatus_is_dirty
= now
;
891 * Allocate and return a description of the status of the server <b>desc</b>,
892 * for use in a v1-style router-status line. The server is listed
893 * as running iff <b>is_live</b> is true.
896 list_single_server_status(routerinfo_t
*desc
, int is_live
)
898 char buf
[MAX_NICKNAME_LEN
+HEX_DIGEST_LEN
+4]; /* !nickname=$hexdigest\0 */
907 if (desc
->is_valid
) {
908 strlcpy(cp
, desc
->nickname
, sizeof(buf
)-(cp
-buf
));
913 base16_encode(cp
, HEX_DIGEST_LEN
+1, desc
->cache_info
.identity_digest
,
915 return tor_strdup(buf
);
919 running_long_enough_to_decide_unreachable(void)
921 return time_of_process_start
922 + get_options()->TestingAuthDirTimeToLearnReachability
< approx_time();
925 /** Each server needs to have passed a reachability test no more
926 * than this number of seconds ago, or he is listed as down in
928 #define REACHABLE_TIMEOUT (45*60)
930 /** If we tested a router and found it reachable _at least this long_ after it
931 * declared itself hibernating, it is probably done hibernating and we just
932 * missed a descriptor from it. */
933 #define HIBERNATION_PUBLICATION_SKEW (60*60)
935 /** Treat a router as alive if
936 * - It's me, and I'm not hibernating.
937 * or - We've found it reachable recently. */
939 dirserv_set_router_is_running(routerinfo_t
*router
, time_t now
)
941 /*XXXX022 This function is a mess. Separate out the part that calculates
942 whether it's reachable and the part that tells rephist that the router was
947 if (router_is_me(router
)) {
948 /* We always know if we are down ourselves. */
949 answer
= ! we_are_hibernating();
950 } else if (router
->is_hibernating
&&
951 (router
->cache_info
.published_on
+
952 HIBERNATION_PUBLICATION_SKEW
) > router
->last_reachable
) {
953 /* A hibernating router is down unless we (somehow) had contact with it
954 * since it declared itself to be hibernating. */
956 } else if (get_options()->AssumeReachable
) {
957 /* If AssumeReachable, everybody is up unless they say they are down! */
960 /* Otherwise, a router counts as up if we found it reachable in the last
961 REACHABLE_TIMEOUT seconds. */
962 answer
= (now
< router
->last_reachable
+ REACHABLE_TIMEOUT
);
965 if (!answer
&& running_long_enough_to_decide_unreachable()) {
966 /* not considered reachable. tell rephist. */
967 rep_hist_note_router_unreachable(router
->cache_info
.identity_digest
, now
);
970 router
->is_running
= answer
;
973 /** Based on the routerinfo_ts in <b>routers</b>, allocate the
974 * contents of a v1-style router-status line, and store it in
975 * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
977 * If for_controller is true, include the routers with very old descriptors.
980 list_server_status_v1(smartlist_t
*routers
, char **router_status_out
,
983 /* List of entries in a router-status style: An optional !, then an optional
984 * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
985 smartlist_t
*rs_entries
;
986 time_t now
= time(NULL
);
987 time_t cutoff
= now
- ROUTER_MAX_AGE_TO_PUBLISH
;
988 or_options_t
*options
= get_options();
989 /* We include v2 dir auths here too, because they need to answer
990 * controllers. Eventually we'll deprecate this whole function;
991 * see also networkstatus_getinfo_by_purpose(). */
992 int authdir
= authdir_mode_publishes_statuses(options
);
993 tor_assert(router_status_out
);
995 rs_entries
= smartlist_create();
997 SMARTLIST_FOREACH_BEGIN(routers
, routerinfo_t
*, ri
) {
999 /* Update router status in routerinfo_t. */
1000 dirserv_set_router_is_running(ri
, now
);
1002 if (for_controller
) {
1003 char name_buf
[MAX_VERBOSE_NICKNAME_LEN
+2];
1004 char *cp
= name_buf
;
1005 if (!ri
->is_running
)
1007 router_get_verbose_nickname(cp
, ri
);
1008 smartlist_add(rs_entries
, tor_strdup(name_buf
));
1009 } else if (ri
->cache_info
.published_on
>= cutoff
) {
1010 smartlist_add(rs_entries
, list_single_server_status(ri
, ri
->is_running
));
1012 } SMARTLIST_FOREACH_END(ri
);
1014 *router_status_out
= smartlist_join_strings(rs_entries
, " ", 0, NULL
);
1016 SMARTLIST_FOREACH(rs_entries
, char *, cp
, tor_free(cp
));
1017 smartlist_free(rs_entries
);
1022 /** Given a (possibly empty) list of config_line_t, each line of which contains
1023 * a list of comma-separated version numbers surrounded by optional space,
1024 * allocate and return a new string containing the version numbers, in order,
1025 * separated by commas. Used to generate Recommended(Client|Server)?Versions
1028 format_versions_list(config_line_t
*ln
)
1030 smartlist_t
*versions
;
1032 versions
= smartlist_create();
1033 for ( ; ln
; ln
= ln
->next
) {
1034 smartlist_split_string(versions
, ln
->value
, ",",
1035 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1037 sort_version_list(versions
, 1);
1038 result
= smartlist_join_strings(versions
,",",0,NULL
);
1039 SMARTLIST_FOREACH(versions
,char *,s
,tor_free(s
));
1040 smartlist_free(versions
);
1044 /** Return 1 if <b>ri</b>'s descriptor is "active" -- running, valid,
1045 * not hibernating, and not too old. Else return 0.
1048 router_is_active(routerinfo_t
*ri
, time_t now
)
1050 time_t cutoff
= now
- ROUTER_MAX_AGE_TO_PUBLISH
;
1051 if (ri
->cache_info
.published_on
< cutoff
)
1053 if (!ri
->is_running
|| !ri
->is_valid
|| ri
->is_hibernating
)
1058 /** Generate a new v1 directory and write it into a newly allocated string.
1059 * Point *<b>dir_out</b> to the allocated string. Sign the
1060 * directory with <b>private_key</b>. Return 0 on success, -1 on
1061 * failure. If <b>complete</b> is set, give us all the descriptors;
1062 * otherwise leave out non-running and non-valid ones.
1065 dirserv_dump_directory_to_string(char **dir_out
,
1066 crypto_pk_env_t
*private_key
)
1069 char *identity_pkey
; /* Identity key, DER64-encoded. */
1070 char *recommended_versions
;
1071 char digest
[DIGEST_LEN
];
1072 char published
[ISO_TIME_LEN
+1];
1075 size_t identity_pkey_len
;
1076 time_t now
= time(NULL
);
1078 tor_assert(dir_out
);
1081 if (crypto_pk_write_public_key_to_string(private_key
,&identity_pkey
,
1082 &identity_pkey_len
)<0) {
1083 log_warn(LD_BUG
,"write identity_pkey to string failed!");
1087 recommended_versions
=
1088 format_versions_list(get_options()->RecommendedVersions
);
1090 format_iso_time(published
, now
);
1092 buf_len
= 2048+strlen(recommended_versions
);
1094 buf
= tor_malloc(buf_len
);
1095 /* We'll be comparing against buf_len throughout the rest of the
1096 function, though strictly speaking we shouldn't be able to exceed
1097 it. This is C, after all, so we may as well check for buffer
1100 tor_snprintf(buf
, buf_len
,
1101 "signed-directory\n"
1103 "recommended-software %s\n"
1104 "router-status %s\n"
1105 "dir-signing-key\n%s\n",
1106 published
, recommended_versions
, "",
1109 tor_free(recommended_versions
);
1110 tor_free(identity_pkey
);
1112 cp
= buf
+ strlen(buf
);
1115 /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
1117 if (strlcat(buf
, "directory-signature ", buf_len
) >= buf_len
)
1119 if (strlcat(buf
, get_options()->Nickname
, buf_len
) >= buf_len
)
1121 if (strlcat(buf
, "\n", buf_len
) >= buf_len
)
1124 if (router_get_dir_hash(buf
,digest
)) {
1125 log_warn(LD_BUG
,"couldn't compute digest");
1129 note_crypto_pk_op(SIGN_DIR
);
1130 if (router_append_dirobj_signature(buf
,buf_len
,digest
,DIGEST_LEN
,
1139 log_warn(LD_BUG
,"tried to exceed string length.");
1144 /********************************************************************/
1146 /* A set of functions to answer questions about how we'd like to behave
1147 * as a directory mirror/client. */
1149 /** Return 1 if we fetch our directory material directly from the
1150 * authorities, rather than from a mirror. */
1152 directory_fetches_from_authorities(or_options_t
*options
)
1157 if (options
->FetchDirInfoEarly
)
1159 if (options
->BridgeRelay
== 1)
1161 if (server_mode(options
) && router_pick_published_address(options
, &addr
)<0)
1162 return 1; /* we don't know our IP address; ask an authority. */
1163 refuseunknown
= router_my_exit_policy_is_reject_star() &&
1164 should_refuse_unknown_exits(options
);
1165 if (options
->DirPort
== 0 && !refuseunknown
)
1167 if (!server_mode(options
) || !advertised_server_mode())
1169 me
= router_get_my_routerinfo();
1170 if (!me
|| (!me
->dir_port
&& !refuseunknown
))
1171 return 0; /* if dirport not advertised, return 0 too */
1175 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1176 * on the "mirror" schedule rather than the "client" schedule.
1179 directory_fetches_dir_info_early(or_options_t
*options
)
1181 return directory_fetches_from_authorities(options
);
1184 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1185 * on a very passive schedule -- waiting long enough for ordinary clients
1186 * to probably have the info we want. These would include bridge users,
1187 * and maybe others in the future e.g. if a Tor client uses another Tor
1188 * client as a directory guard.
1191 directory_fetches_dir_info_later(or_options_t
*options
)
1193 return options
->UseBridges
!= 0;
1196 /** Return 1 if we want to cache v2 dir info (each status file).
1199 directory_caches_v2_dir_info(or_options_t
*options
)
1201 return options
->DirPort
!= 0;
1204 /** Return 1 if we want to keep descriptors, networkstatuses, etc around
1205 * and we're willing to serve them to others. Else return 0.
1208 directory_caches_dir_info(or_options_t
*options
)
1210 if (options
->BridgeRelay
|| options
->DirPort
)
1212 if (!server_mode(options
) || !advertised_server_mode())
1214 /* We need an up-to-date view of network info if we're going to try to
1215 * block exit attempts from unknown relays. */
1216 return ! router_my_exit_policy_is_reject_star() &&
1217 should_refuse_unknown_exits(options
);
1220 /** Return 1 if we want to allow remote people to ask us directory
1221 * requests via the "begin_dir" interface, which doesn't require
1222 * having any separate port open. */
1224 directory_permits_begindir_requests(or_options_t
*options
)
1226 return options
->BridgeRelay
!= 0 || options
->DirPort
!= 0;
1229 /** Return 1 if we want to allow controllers to ask us directory
1230 * requests via the controller interface, which doesn't require
1231 * having any separate port open. */
1233 directory_permits_controller_requests(or_options_t
*options
)
1235 return options
->DirPort
!= 0;
1238 /** Return 1 if we have no need to fetch new descriptors. This generally
1239 * happens when we're not a dir cache and we haven't built any circuits
1243 directory_too_idle_to_fetch_descriptors(or_options_t
*options
, time_t now
)
1245 return !directory_caches_dir_info(options
) &&
1246 !options
->FetchUselessDescriptors
&&
1247 rep_hist_circbuilding_dormant(now
);
1250 /********************************************************************/
1252 /* Used only by non-v1-auth dirservers: The v1 directory and
1253 * runningrouters we'll serve when requested. */
1255 /** The v1 directory we'll serve (as a cache or as an authority) if
1257 static cached_dir_t
*cached_directory
= NULL
;
1258 /** The v1 runningrouters document we'll serve (as a cache or as an authority)
1260 static cached_dir_t cached_runningrouters
;
1262 /** Used for other dirservers' v2 network statuses. Map from hexdigest to
1264 static digestmap_t
*cached_v2_networkstatus
= NULL
;
1266 /** Map from flavor name to the v3 consensuses that we're currently serving. */
1267 static strmap_t
*cached_consensuses
= NULL
;
1269 /** Possibly replace the contents of <b>d</b> with the value of
1270 * <b>directory</b> published on <b>when</b>, unless <b>when</b> is older than
1271 * the last value, or too far in the future.
1273 * Does not copy <b>directory</b>; frees it if it isn't used.
1276 set_cached_dir(cached_dir_t
*d
, char *directory
, time_t when
)
1278 time_t now
= time(NULL
);
1279 if (when
<=d
->published
) {
1280 log_info(LD_DIRSERV
, "Ignoring old directory; not caching.");
1281 tor_free(directory
);
1282 } else if (when
>=now
+ROUTER_MAX_AGE_TO_PUBLISH
) {
1283 log_info(LD_DIRSERV
, "Ignoring future directory; not caching.");
1284 tor_free(directory
);
1286 /* if (when>d->published && when<now+ROUTER_MAX_AGE) */
1287 log_debug(LD_DIRSERV
, "Caching directory.");
1290 d
->dir_len
= strlen(directory
);
1292 if (tor_gzip_compress(&(d
->dir_z
), &(d
->dir_z_len
), d
->dir
, d
->dir_len
,
1294 log_warn(LD_BUG
,"Error compressing cached directory");
1296 d
->published
= when
;
1300 /** Decrement the reference count on <b>d</b>, and free it if it no longer has
1301 * any references. */
1303 cached_dir_decref(cached_dir_t
*d
)
1305 if (!d
|| --d
->refcnt
> 0)
1307 clear_cached_dir(d
);
1311 /** Allocate and return a new cached_dir_t containing the string <b>s</b>,
1312 * published at <b>published</b>. */
1314 new_cached_dir(char *s
, time_t published
)
1316 cached_dir_t
*d
= tor_malloc_zero(sizeof(cached_dir_t
));
1319 d
->dir_len
= strlen(s
);
1320 d
->published
= published
;
1321 if (tor_gzip_compress(&(d
->dir_z
), &(d
->dir_z_len
), d
->dir
, d
->dir_len
,
1323 log_warn(LD_BUG
, "Error compressing directory");
1328 /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
1330 clear_cached_dir(cached_dir_t
*d
)
1334 memset(d
, 0, sizeof(cached_dir_t
));
1337 /** Free all storage held by the cached_dir_t in <b>d</b>. */
1339 _free_cached_dir(void *_d
)
1345 d
= (cached_dir_t
*)_d
;
1346 cached_dir_decref(d
);
1349 /** If we have no cached v1 directory, or it is older than <b>published</b>,
1350 * then replace it with <b>directory</b>, published at <b>published</b>.
1352 * If <b>published</b> is too old, do nothing.
1354 * If <b>is_running_routers</b>, this is really a v1 running_routers
1355 * document rather than a v1 directory.
1358 dirserv_set_cached_directory(const char *directory
, time_t published
,
1359 int is_running_routers
)
1361 time_t now
= time(NULL
);
1363 if (is_running_routers
) {
1364 if (published
>= now
- MAX_V1_RR_AGE
)
1365 set_cached_dir(&cached_runningrouters
, tor_strdup(directory
), published
);
1367 if (published
>= now
- MAX_V1_DIRECTORY_AGE
) {
1368 cached_dir_decref(cached_directory
);
1369 cached_directory
= new_cached_dir(tor_strdup(directory
), published
);
1374 /** If <b>networkstatus</b> is non-NULL, we've just received a v2
1375 * network-status for an authoritative directory with identity digest
1376 * <b>identity</b> published at <b>published</b> -- store it so we can
1377 * serve it to others.
1379 * If <b>networkstatus</b> is NULL, remove the entry with the given
1380 * identity fingerprint from the v2 cache.
1383 dirserv_set_cached_networkstatus_v2(const char *networkstatus
,
1384 const char *identity
,
1387 cached_dir_t
*d
, *old_d
;
1388 smartlist_t
*trusted_dirs
;
1389 if (!cached_v2_networkstatus
)
1390 cached_v2_networkstatus
= digestmap_new();
1392 old_d
= digestmap_get(cached_v2_networkstatus
, identity
);
1393 if (!old_d
&& !networkstatus
)
1396 if (networkstatus
) {
1397 if (!old_d
|| published
> old_d
->published
) {
1398 d
= new_cached_dir(tor_strdup(networkstatus
), published
);
1399 digestmap_set(cached_v2_networkstatus
, identity
, d
);
1401 cached_dir_decref(old_d
);
1405 digestmap_remove(cached_v2_networkstatus
, identity
);
1406 cached_dir_decref(old_d
);
1410 /* Now purge old entries. */
1411 trusted_dirs
= router_get_trusted_dir_servers();
1412 if (digestmap_size(cached_v2_networkstatus
) >
1413 smartlist_len(trusted_dirs
) + MAX_UNTRUSTED_NETWORKSTATUSES
) {
1414 /* We need to remove the oldest untrusted networkstatus. */
1415 const char *oldest
= NULL
;
1416 time_t oldest_published
= TIME_MAX
;
1417 digestmap_iter_t
*iter
;
1419 for (iter
= digestmap_iter_init(cached_v2_networkstatus
);
1420 !digestmap_iter_done(iter
);
1421 iter
= digestmap_iter_next(cached_v2_networkstatus
, iter
)) {
1424 digestmap_iter_get(iter
, &ident
, &val
);
1426 if (d
->published
< oldest_published
&&
1427 !router_digest_is_trusted_dir(ident
)) {
1429 oldest_published
= d
->published
;
1433 d
= digestmap_remove(cached_v2_networkstatus
, oldest
);
1435 cached_dir_decref(d
);
1439 /** Replace the v3 consensus networkstatus of type <b>flavor_name</b> that
1440 * we're serving with <b>networkstatus</b>, published at <b>published</b>. No
1441 * validation is performed. */
1443 dirserv_set_cached_consensus_networkstatus(const char *networkstatus
,
1444 const char *flavor_name
,
1445 const digests_t
*digests
,
1448 cached_dir_t
*new_networkstatus
;
1449 cached_dir_t
*old_networkstatus
;
1450 if (!cached_consensuses
)
1451 cached_consensuses
= strmap_new();
1453 new_networkstatus
= new_cached_dir(tor_strdup(networkstatus
), published
);
1454 memcpy(&new_networkstatus
->digests
, digests
, sizeof(digests_t
));
1455 old_networkstatus
= strmap_set(cached_consensuses
, flavor_name
,
1457 if (old_networkstatus
)
1458 cached_dir_decref(old_networkstatus
);
1461 /** Remove any v2 networkstatus from the directory cache that was published
1462 * before <b>cutoff</b>. */
1464 dirserv_clear_old_networkstatuses(time_t cutoff
)
1466 if (!cached_v2_networkstatus
)
1469 DIGESTMAP_FOREACH_MODIFY(cached_v2_networkstatus
, id
, cached_dir_t
*, dir
) {
1470 if (dir
->published
< cutoff
) {
1472 fname
= networkstatus_get_cache_filename(id
);
1473 if (file_status(fname
) == FN_FILE
) {
1474 log_info(LD_DIR
, "Removing too-old untrusted networkstatus in %s",
1479 cached_dir_decref(dir
);
1480 MAP_DEL_CURRENT(id
);
1482 } DIGESTMAP_FOREACH_END
1485 /** Remove any v1 info from the directory cache that was published
1488 dirserv_clear_old_v1_info(time_t now
)
1490 if (cached_directory
&&
1491 cached_directory
->published
< (now
- MAX_V1_DIRECTORY_AGE
)) {
1492 cached_dir_decref(cached_directory
);
1493 cached_directory
= NULL
;
1495 if (cached_runningrouters
.published
< (now
- MAX_V1_RR_AGE
)) {
1496 clear_cached_dir(&cached_runningrouters
);
1500 /** Helper: If we're an authority for the right directory version (v1 or v2)
1501 * (based on <b>auth_type</b>), try to regenerate
1502 * auth_src as appropriate and return it, falling back to cache_src on
1503 * failure. If we're a cache, simply return cache_src.
1505 static cached_dir_t
*
1506 dirserv_pick_cached_dir_obj(cached_dir_t
*cache_src
,
1507 cached_dir_t
*auth_src
,
1508 time_t dirty
, cached_dir_t
*(*regenerate
)(void),
1510 authority_type_t auth_type
)
1512 or_options_t
*options
= get_options();
1513 int authority
= (auth_type
== V1_AUTHORITY
&& authdir_mode_v1(options
)) ||
1514 (auth_type
== V2_AUTHORITY
&& authdir_mode_v2(options
));
1516 if (!authority
|| authdir_mode_bridge(options
)) {
1519 /* We're authoritative. */
1520 if (regenerate
!= NULL
) {
1521 if (dirty
&& dirty
+ DIR_REGEN_SLACK_TIME
< time(NULL
)) {
1522 if (!(auth_src
= regenerate())) {
1523 log_err(LD_BUG
, "Couldn't generate %s?", name
);
1527 log_info(LD_DIRSERV
, "The %s is still clean; reusing.", name
);
1530 return auth_src
? auth_src
: cache_src
;
1534 /** Return the most recently generated encoded signed v1 directory,
1535 * generating a new one as necessary. If not a v1 authoritative directory
1536 * may return NULL if no directory is yet cached. */
1538 dirserv_get_directory(void)
1540 return dirserv_pick_cached_dir_obj(cached_directory
, the_directory
,
1541 the_directory_is_dirty
,
1542 dirserv_regenerate_directory
,
1543 "v1 server directory", V1_AUTHORITY
);
1546 /** Only called by v1 auth dirservers.
1547 * Generate a fresh v1 directory; set the_directory and return a pointer
1550 static cached_dir_t
*
1551 dirserv_regenerate_directory(void)
1553 char *new_directory
=NULL
;
1555 if (dirserv_dump_directory_to_string(&new_directory
,
1556 get_server_identity_key())) {
1557 log_warn(LD_BUG
, "Error creating directory.");
1558 tor_free(new_directory
);
1561 cached_dir_decref(the_directory
);
1562 the_directory
= new_cached_dir(new_directory
, time(NULL
));
1563 log_info(LD_DIRSERV
,"New directory (size %d) has been built.",
1564 (int)the_directory
->dir_len
);
1565 log_debug(LD_DIRSERV
,"New directory (size %d):\n%s",
1566 (int)the_directory
->dir_len
, the_directory
->dir
);
1568 the_directory_is_dirty
= 0;
1570 /* Save the directory to disk so we re-load it quickly on startup.
1572 dirserv_set_cached_directory(the_directory
->dir
, time(NULL
), 0);
1574 return the_directory
;
1577 /** Only called by v1 auth dirservers.
1578 * Replace the current running-routers list with a newly generated one. */
1579 static cached_dir_t
*
1580 generate_runningrouters(void)
1583 char digest
[DIGEST_LEN
];
1584 char published
[ISO_TIME_LEN
+1];
1586 crypto_pk_env_t
*private_key
= get_server_identity_key();
1587 char *identity_pkey
; /* Identity key, DER64-encoded. */
1588 size_t identity_pkey_len
;
1590 if (crypto_pk_write_public_key_to_string(private_key
,&identity_pkey
,
1591 &identity_pkey_len
)<0) {
1592 log_warn(LD_BUG
,"write identity_pkey to string failed!");
1595 format_iso_time(published
, time(NULL
));
1598 s
= tor_malloc_zero(len
);
1599 tor_snprintf(s
, len
,
1602 "router-status %s\n"
1603 "dir-signing-key\n%s"
1604 "directory-signature %s\n",
1605 published
, "", identity_pkey
,
1606 get_options()->Nickname
);
1607 tor_free(identity_pkey
);
1608 if (router_get_runningrouters_hash(s
,digest
)) {
1609 log_warn(LD_BUG
,"couldn't compute digest");
1612 note_crypto_pk_op(SIGN_DIR
);
1613 if (router_append_dirobj_signature(s
, len
, digest
, DIGEST_LEN
,
1617 set_cached_dir(&the_runningrouters
, s
, time(NULL
));
1618 runningrouters_is_dirty
= 0;
1620 return &the_runningrouters
;
1626 /** Set *<b>rr</b> to the most recently generated encoded signed
1627 * running-routers list, generating a new one as necessary. Return the
1628 * size of the directory on success, and 0 on failure. */
1630 dirserv_get_runningrouters(void)
1632 return dirserv_pick_cached_dir_obj(
1633 &cached_runningrouters
, &the_runningrouters
,
1634 runningrouters_is_dirty
,
1635 generate_runningrouters
,
1636 "v1 network status list", V1_AUTHORITY
);
1639 /** Return the latest downloaded consensus networkstatus in encoded, signed,
1640 * optionally compressed format, suitable for sending to clients. */
1642 dirserv_get_consensus(const char *flavor_name
)
1644 if (!cached_consensuses
)
1646 return strmap_get(cached_consensuses
, flavor_name
);
1649 /** For authoritative directories: the current (v2) network status. */
1650 static cached_dir_t
*the_v2_networkstatus
= NULL
;
1652 /** Return true iff our opinion of the routers has been stale for long
1653 * enough that we should generate a new v2 network status doc. */
1655 should_generate_v2_networkstatus(void)
1657 return authdir_mode_v2(get_options()) &&
1658 the_v2_networkstatus_is_dirty
&&
1659 the_v2_networkstatus_is_dirty
+ DIR_REGEN_SLACK_TIME
< time(NULL
);
1662 /** If a router's uptime is at least this value, then it is always
1663 * considered stable, regardless of the rest of the network. This
1664 * way we resist attacks where an attacker doubles the size of the
1665 * network using allegedly high-uptime nodes, displacing all the
1666 * current guards. */
1667 #define UPTIME_TO_GUARANTEE_STABLE (3600*24*30)
1668 /** If a router's MTBF is at least this value, then it is always stable.
1669 * See above. (Corresponds to about 7 days for current decay rates.) */
1670 #define MTBF_TO_GUARANTEE_STABLE (60*60*24*5)
1671 /** Similarly, we protect sufficiently fast nodes from being pushed
1672 * out of the set of Fast nodes. */
1673 #define BANDWIDTH_TO_GUARANTEE_FAST ROUTER_REQUIRED_MIN_BANDWIDTH
1674 /** Similarly, every node with sufficient bandwidth can be considered
1675 * for Guard status. */
1676 #define BANDWIDTH_TO_GUARANTEE_GUARD (250*1024)
1677 /** Similarly, every node with at least this much weighted time known can be
1678 * considered familiar enough to be a guard. Corresponds to about 20 days for
1679 * current decay rates.
1681 #define TIME_KNOWN_TO_GUARANTEE_FAMILIAR (8*24*60*60)
1682 /** Similarly, every node with sufficient WFU is around enough to be a guard.
1684 #define WFU_TO_GUARANTEE_GUARD (0.98)
1686 /* Thresholds for server performance: set by
1687 * dirserv_compute_performance_thresholds, and used by
1688 * generate_v2_networkstatus */
1690 /** Any router with an uptime of at least this value is stable. */
1691 static uint32_t stable_uptime
= 0; /* start at a safe value */
1692 /** Any router with an mtbf of at least this value is stable. */
1693 static double stable_mtbf
= 0.0;
1694 /** If true, we have measured enough mtbf info to look at stable_mtbf rather
1695 * than stable_uptime. */
1696 static int enough_mtbf_info
= 0;
1697 /** Any router with a weighted fractional uptime of at least this much might
1698 * be good as a guard. */
1699 static double guard_wfu
= 0.0;
1700 /** Don't call a router a guard unless we've known about it for at least this
1702 static long guard_tk
= 0;
1703 /** Any router with a bandwidth at least this high is "Fast" */
1704 static uint32_t fast_bandwidth
= 0;
1705 /** If exits can be guards, then all guards must have a bandwidth this
1707 static uint32_t guard_bandwidth_including_exits
= 0;
1708 /** If exits can't be guards, then all guards must have a bandwidth this
1710 static uint32_t guard_bandwidth_excluding_exits
= 0;
1711 /** Total bandwidth of all the routers we're considering. */
1712 static uint64_t total_bandwidth
= 0;
1713 /** Total bandwidth of all the exit routers we're considering. */
1714 static uint64_t total_exit_bandwidth
= 0;
1716 /** Helper: estimate the uptime of a router given its stated uptime and the
1717 * amount of time since it last stated its stated uptime. */
1719 real_uptime(routerinfo_t
*router
, time_t now
)
1721 if (now
< router
->cache_info
.published_on
)
1722 return router
->uptime
;
1724 return router
->uptime
+ (now
- router
->cache_info
.published_on
);
1727 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1728 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1729 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1733 dirserv_thinks_router_is_unreliable(time_t now
,
1734 routerinfo_t
*router
,
1735 int need_uptime
, int need_capacity
)
1738 if (!enough_mtbf_info
) {
1739 /* XXX022 Once most authorities are on v3, we should change the rule from
1740 * "use uptime if we don't have mtbf data" to "don't advertise Stable on
1741 * v3 if we don't have enough mtbf data." */
1742 long uptime
= real_uptime(router
, now
);
1743 if ((unsigned)uptime
< stable_uptime
&&
1744 (unsigned)uptime
< UPTIME_TO_GUARANTEE_STABLE
)
1748 rep_hist_get_stability(router
->cache_info
.identity_digest
, now
);
1749 if (mtbf
< stable_mtbf
&&
1750 mtbf
< MTBF_TO_GUARANTEE_STABLE
)
1754 if (need_capacity
) {
1755 uint32_t bw
= router_get_advertised_bandwidth(router
);
1756 if (bw
< fast_bandwidth
)
1762 /** Return true iff <b>router</b> should be assigned the "HSDir" flag.
1763 * Right now this means it advertises support for it, it has a high
1764 * uptime, it has a DirPort open, and it's currently considered Running.
1766 * This function needs to be called after router-\>is_running has
1770 dirserv_thinks_router_is_hs_dir(routerinfo_t
*router
, time_t now
)
1772 long uptime
= real_uptime(router
, now
);
1774 /* XXX We shouldn't need to check dir_port, but we do because of
1775 * bug 1693. In the future, once relays set wants_to_be_hs_dir
1776 * correctly, we can revert to only checking dir_port if router's
1777 * version is too old. */
1778 return (router
->wants_to_be_hs_dir
&& router
->dir_port
&&
1779 uptime
> get_options()->MinUptimeHidServDirectoryV2
&&
1780 router
->is_running
);
1783 /** Look through the routerlist, the Mean Time Between Failure history, and
1784 * the Weighted Fractional Uptime history, and use them to set thresholds for
1785 * the Stable, Fast, and Guard flags. Update the fields stable_uptime,
1786 * stable_mtbf, enough_mtbf_info, guard_wfu, guard_tk, fast_bandwidth,
1787 * guard_bandwidh_including_exits, guard_bandwidth_excluding_exits,
1788 * total_bandwidth, and total_exit_bandwidth.
1790 * Also, set the is_exit flag of each router appropriately. */
1792 dirserv_compute_performance_thresholds(routerlist_t
*rl
)
1794 int n_active
, n_active_nonexit
, n_familiar
;
1795 uint32_t *uptimes
, *bandwidths
, *bandwidths_excluding_exits
;
1797 double *mtbfs
, *wfus
;
1798 time_t now
= time(NULL
);
1800 /* initialize these all here, in case there are no routers */
1804 guard_bandwidth_including_exits
= 0;
1805 guard_bandwidth_excluding_exits
= 0;
1808 total_bandwidth
= 0;
1809 total_exit_bandwidth
= 0;
1811 /* Initialize arrays that will hold values for each router. We'll
1812 * sort them and use that to compute thresholds. */
1813 n_active
= n_active_nonexit
= 0;
1814 /* Uptime for every active router. */
1815 uptimes
= tor_malloc(sizeof(uint32_t)*smartlist_len(rl
->routers
));
1816 /* Bandwidth for every active router. */
1817 bandwidths
= tor_malloc(sizeof(uint32_t)*smartlist_len(rl
->routers
));
1818 /* Bandwidth for every active non-exit router. */
1819 bandwidths_excluding_exits
=
1820 tor_malloc(sizeof(uint32_t)*smartlist_len(rl
->routers
));
1821 /* Weighted mean time between failure for each active router. */
1822 mtbfs
= tor_malloc(sizeof(double)*smartlist_len(rl
->routers
));
1823 /* Time-known for each active router. */
1824 tks
= tor_malloc(sizeof(long)*smartlist_len(rl
->routers
));
1825 /* Weighted fractional uptime for each active router. */
1826 wfus
= tor_malloc(sizeof(double)*smartlist_len(rl
->routers
));
1828 /* Now, fill in the arrays. */
1829 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, ri
, {
1830 if (router_is_active(ri
, now
)) {
1831 const char *id
= ri
->cache_info
.identity_digest
;
1833 ri
->is_exit
= (!router_exit_policy_rejects_all(ri
) &&
1834 exit_policy_is_general_exit(ri
->exit_policy
));
1835 uptimes
[n_active
] = (uint32_t)real_uptime(ri
, now
);
1836 mtbfs
[n_active
] = rep_hist_get_stability(id
, now
);
1837 tks
[n_active
] = rep_hist_get_weighted_time_known(id
, now
);
1838 bandwidths
[n_active
] = bw
= router_get_advertised_bandwidth(ri
);
1839 total_bandwidth
+= bw
;
1840 if (ri
->is_exit
&& !ri
->is_bad_exit
) {
1841 total_exit_bandwidth
+= bw
;
1843 bandwidths_excluding_exits
[n_active_nonexit
] = bw
;
1850 /* Now, compute thresholds. */
1852 /* The median uptime is stable. */
1853 stable_uptime
= median_uint32(uptimes
, n_active
);
1854 /* The median mtbf is stable, if we have enough mtbf info */
1855 stable_mtbf
= median_double(mtbfs
, n_active
);
1856 /* The 12.5th percentile bandwidth is fast. */
1857 fast_bandwidth
= find_nth_uint32(bandwidths
, n_active
, n_active
/8);
1858 /* (Now bandwidths is sorted.) */
1859 if (fast_bandwidth
< ROUTER_REQUIRED_MIN_BANDWIDTH
/2)
1860 fast_bandwidth
= bandwidths
[n_active
/4];
1861 guard_bandwidth_including_exits
= bandwidths
[(n_active
-1)/2];
1862 guard_tk
= find_nth_long(tks
, n_active
, n_active
/8);
1865 if (guard_tk
> TIME_KNOWN_TO_GUARANTEE_FAMILIAR
)
1866 guard_tk
= TIME_KNOWN_TO_GUARANTEE_FAMILIAR
;
1868 if (fast_bandwidth
> BANDWIDTH_TO_GUARANTEE_FAST
)
1869 fast_bandwidth
= BANDWIDTH_TO_GUARANTEE_FAST
;
1871 /* Now that we have a time-known that 7/8 routers are known longer than,
1872 * fill wfus with the wfu of every such "familiar" router. */
1874 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, ri
, {
1875 if (router_is_active(ri
, now
)) {
1876 const char *id
= ri
->cache_info
.identity_digest
;
1877 long tk
= rep_hist_get_weighted_time_known(id
, now
);
1880 wfus
[n_familiar
++] = rep_hist_get_weighted_fractional_uptime(id
, now
);
1884 guard_wfu
= median_double(wfus
, n_familiar
);
1885 if (guard_wfu
> WFU_TO_GUARANTEE_GUARD
)
1886 guard_wfu
= WFU_TO_GUARANTEE_GUARD
;
1888 enough_mtbf_info
= rep_hist_have_measured_enough_stability();
1890 if (n_active_nonexit
) {
1891 guard_bandwidth_excluding_exits
=
1892 median_uint32(bandwidths_excluding_exits
, n_active_nonexit
);
1895 log(LOG_INFO
, LD_DIRSERV
,
1896 "Cutoffs: For Stable, %lu sec uptime, %lu sec MTBF. "
1897 "For Fast: %lu bytes/sec. "
1898 "For Guard: WFU %.03lf%%, time-known %lu sec, "
1899 "and bandwidth %lu or %lu bytes/sec. We%s have enough stability data.",
1900 (unsigned long)stable_uptime
,
1901 (unsigned long)stable_mtbf
,
1902 (unsigned long)fast_bandwidth
,
1904 (unsigned long)guard_tk
,
1905 (unsigned long)guard_bandwidth_including_exits
,
1906 (unsigned long)guard_bandwidth_excluding_exits
,
1907 enough_mtbf_info
? "" : " don't ");
1911 tor_free(bandwidths
);
1912 tor_free(bandwidths_excluding_exits
);
1917 /** Given a platform string as in a routerinfo_t (possibly null), return a
1918 * newly allocated version string for a networkstatus document, or NULL if the
1919 * platform doesn't give a Tor version. */
1921 version_from_platform(const char *platform
)
1923 if (platform
&& !strcmpstart(platform
, "Tor ")) {
1924 const char *eos
= find_whitespace(platform
+4);
1925 if (eos
&& !strcmpstart(eos
, " (r")) {
1926 /* XXXX Unify this logic with the other version extraction
1927 * logic in routerparse.c. */
1928 eos
= find_whitespace(eos
+1);
1931 return tor_strndup(platform
, eos
-platform
);
1937 /** Helper: write the router-status information in <b>rs</b> into <b>buf</b>,
1938 * which has at least <b>buf_len</b> free characters. Do NUL-termination.
1939 * Use the same format as in network-status documents. If <b>version</b> is
1940 * non-NULL, add a "v" line for the platform. Return 0 on success, -1 on
1943 * The format argument has three possible values:
1944 * NS_V2 - Output an entry suitable for a V2 NS opinion document
1945 * NS_V3_CONSENSUS - Output the first portion of a V3 NS consensus entry
1946 * NS_V3_CONSENSUS_MICRODESC - Output the first portion of a V3 microdesc
1948 * NS_V3_VOTE - Output a complete V3 NS vote
1949 * NS_CONTROL_PORT - Output a NS document for the control port
1952 routerstatus_format_entry(char *buf
, size_t buf_len
,
1953 routerstatus_t
*rs
, const char *version
,
1954 routerstatus_format_type_t format
)
1961 char published
[ISO_TIME_LEN
+1];
1962 char ipaddr
[INET_NTOA_BUF_LEN
];
1963 char identity64
[BASE64_DIGEST_LEN
+1];
1964 char digest64
[BASE64_DIGEST_LEN
+1];
1966 format_iso_time(published
, rs
->published_on
);
1967 digest_to_base64(identity64
, rs
->identity_digest
);
1968 digest_to_base64(digest64
, rs
->descriptor_digest
);
1969 in
.s_addr
= htonl(rs
->addr
);
1970 tor_inet_ntoa(&in
, ipaddr
, sizeof(ipaddr
));
1972 r
= tor_snprintf(buf
, buf_len
,
1973 "r %s %s %s%s%s %s %d %d\n",
1976 (format
==NS_V3_CONSENSUS_MICRODESC
)?"":digest64
,
1977 (format
==NS_V3_CONSENSUS_MICRODESC
)?"":" ",
1983 log_warn(LD_BUG
, "Not enough space in buffer.");
1987 /* TODO: Maybe we want to pass in what we need to build the rest of
1988 * this here, instead of in the caller. Then we could use the
1989 * networkstatus_type_t values, with an additional control port value
1991 if (format
== NS_V3_CONSENSUS
|| format
== NS_V3_CONSENSUS_MICRODESC
)
1994 cp
= buf
+ strlen(buf
);
1995 /* NOTE: Whenever this list expands, be sure to increase MAX_FLAG_LINE_LEN*/
1996 r
= tor_snprintf(cp
, buf_len
- (cp
-buf
),
1997 "s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
1998 /* These must stay in alphabetical order. */
1999 rs
->is_authority
?" Authority":"",
2000 rs
->is_bad_directory
?" BadDirectory":"",
2001 rs
->is_bad_exit
?" BadExit":"",
2002 rs
->is_exit
?" Exit":"",
2003 rs
->is_fast
?" Fast":"",
2004 rs
->is_possible_guard
?" Guard":"",
2005 rs
->is_hs_dir
?" HSDir":"",
2006 rs
->is_named
?" Named":"",
2007 rs
->is_running
?" Running":"",
2008 rs
->is_stable
?" Stable":"",
2009 rs
->is_unnamed
?" Unnamed":"",
2010 rs
->is_v2_dir
?" V2Dir":"",
2011 rs
->is_valid
?" Valid":"");
2013 log_warn(LD_BUG
, "Not enough space in buffer.");
2018 /* length of "opt v \n" */
2019 #define V_LINE_OVERHEAD 7
2020 if (version
&& strlen(version
) < MAX_V_LINE_LEN
- V_LINE_OVERHEAD
) {
2021 if (tor_snprintf(cp
, buf_len
- (cp
-buf
), "opt v %s\n", version
)<0) {
2022 log_warn(LD_BUG
, "Unable to print router version.");
2028 if (format
!= NS_V2
) {
2029 routerinfo_t
* desc
= router_get_by_digest(rs
->identity_digest
);
2032 if (format
!= NS_CONTROL_PORT
) {
2033 /* Blow up more or less nicely if we didn't get anything or not the
2034 * thing we expected.
2037 char id
[HEX_DIGEST_LEN
+1];
2038 char dd
[HEX_DIGEST_LEN
+1];
2040 base16_encode(id
, sizeof(id
), rs
->identity_digest
, DIGEST_LEN
);
2041 base16_encode(dd
, sizeof(dd
), rs
->descriptor_digest
, DIGEST_LEN
);
2042 log_warn(LD_BUG
, "Cannot get any descriptor for %s "
2043 "(wanted descriptor %s).",
2048 /* This assert can fire for the control port, because
2049 * it can request NS documents before all descriptors
2050 * have been fetched. */
2051 if (memcmp(desc
->cache_info
.signed_descriptor_digest
,
2052 rs
->descriptor_digest
,
2054 char rl_d
[HEX_DIGEST_LEN
+1];
2055 char rs_d
[HEX_DIGEST_LEN
+1];
2056 char id
[HEX_DIGEST_LEN
+1];
2058 base16_encode(rl_d
, sizeof(rl_d
),
2059 desc
->cache_info
.signed_descriptor_digest
, DIGEST_LEN
);
2060 base16_encode(rs_d
, sizeof(rs_d
), rs
->descriptor_digest
, DIGEST_LEN
);
2061 base16_encode(id
, sizeof(id
), rs
->identity_digest
, DIGEST_LEN
);
2062 log_err(LD_BUG
, "descriptor digest in routerlist does not match "
2063 "the one in routerstatus: %s vs %s "
2067 tor_assert(!memcmp(desc
->cache_info
.signed_descriptor_digest
,
2068 rs
->descriptor_digest
,
2073 if (format
== NS_CONTROL_PORT
&& rs
->has_bandwidth
) {
2077 bw
= router_get_advertised_bandwidth_capped(desc
) / 1000;
2079 r
= tor_snprintf(cp
, buf_len
- (cp
-buf
),
2080 "w Bandwidth=%d\n", bw
);
2083 log_warn(LD_BUG
, "Not enough space in buffer.");
2087 if (format
== NS_V3_VOTE
&& rs
->has_measured_bw
) {
2088 *--cp
= '\0'; /* Kill "\n" */
2089 r
= tor_snprintf(cp
, buf_len
- (cp
-buf
),
2090 " Measured=%d\n", rs
->measured_bw
);
2092 log_warn(LD_BUG
, "Not enough space in buffer for weight line.");
2099 summary
= policy_summarize(desc
->exit_policy
);
2100 r
= tor_snprintf(cp
, buf_len
- (cp
-buf
), "p %s\n", summary
);
2102 log_warn(LD_BUG
, "Not enough space in buffer.");
2114 /** Helper for sorting: compares two routerinfos first by address, and then by
2115 * descending order of "usefulness". (An authority is more useful than a
2116 * non-authority; a running router is more useful than a non-running router;
2117 * and a router with more bandwidth is more useful than one with less.)
2120 _compare_routerinfo_by_ip_and_bw(const void **a
, const void **b
)
2122 routerinfo_t
*first
= *(routerinfo_t
**)a
, *second
= *(routerinfo_t
**)b
;
2123 int first_is_auth
, second_is_auth
;
2124 uint32_t bw_first
, bw_second
;
2126 /* we return -1 if first should appear before second... that is,
2127 * if first is a better router. */
2128 if (first
->addr
< second
->addr
)
2130 else if (first
->addr
> second
->addr
)
2133 /* Potentially, this next bit could cause k n lg n memcmp calls. But in
2134 * reality, we will almost never get here, since addresses will usually be
2138 router_digest_is_trusted_dir(first
->cache_info
.identity_digest
);
2140 router_digest_is_trusted_dir(second
->cache_info
.identity_digest
);
2142 if (first_is_auth
&& !second_is_auth
)
2144 else if (!first_is_auth
&& second_is_auth
)
2147 else if (first
->is_running
&& !second
->is_running
)
2149 else if (!first
->is_running
&& second
->is_running
)
2152 bw_first
= router_get_advertised_bandwidth(first
);
2153 bw_second
= router_get_advertised_bandwidth(second
);
2155 if (bw_first
> bw_second
)
2157 else if (bw_first
< bw_second
)
2160 /* They're equal! Compare by identity digest, so there's a
2161 * deterministic order and we avoid flapping. */
2162 return memcmp(first
->cache_info
.identity_digest
,
2163 second
->cache_info
.identity_digest
,
2167 /** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
2168 * whose keys are the identity digests of those routers that we're going to
2169 * exclude for Sybil-like appearance. */
2170 static digestmap_t
*
2171 get_possible_sybil_list(const smartlist_t
*routers
)
2173 or_options_t
*options
= get_options();
2174 digestmap_t
*omit_as_sybil
;
2175 smartlist_t
*routers_by_ip
= smartlist_create();
2178 /* Allow at most this number of Tor servers on a single IP address, ... */
2179 int max_with_same_addr
= options
->AuthDirMaxServersPerAddr
;
2180 /* ... unless it's a directory authority, in which case allow more. */
2181 int max_with_same_addr_on_authority
= options
->AuthDirMaxServersPerAuthAddr
;
2182 if (max_with_same_addr
<= 0)
2183 max_with_same_addr
= INT_MAX
;
2184 if (max_with_same_addr_on_authority
<= 0)
2185 max_with_same_addr_on_authority
= INT_MAX
;
2187 smartlist_add_all(routers_by_ip
, routers
);
2188 smartlist_sort(routers_by_ip
, _compare_routerinfo_by_ip_and_bw
);
2189 omit_as_sybil
= digestmap_new();
2193 SMARTLIST_FOREACH(routers_by_ip
, routerinfo_t
*, ri
,
2195 if (last_addr
!= ri
->addr
) {
2196 last_addr
= ri
->addr
;
2198 } else if (++addr_count
> max_with_same_addr
) {
2199 if (!router_addr_is_trusted_dir(ri
->addr
) ||
2200 addr_count
> max_with_same_addr_on_authority
)
2201 digestmap_set(omit_as_sybil
, ri
->cache_info
.identity_digest
, ri
);
2205 smartlist_free(routers_by_ip
);
2206 return omit_as_sybil
;
2209 /** Extract status information from <b>ri</b> and from other authority
2210 * functions and store it in <b>rs</b>>. If <b>naming</b>, consider setting
2211 * the named flag in <b>rs</b>.
2213 * We assume that ri-\>is_running has already been set, e.g. by
2214 * dirserv_set_router_is_running(ri, now);
2217 set_routerstatus_from_routerinfo(routerstatus_t
*rs
,
2218 routerinfo_t
*ri
, time_t now
,
2219 int naming
, int listbadexits
,
2222 int unstable_version
=
2223 !tor_version_as_new_as(ri
->platform
,"0.1.1.16-rc-cvs");
2224 memset(rs
, 0, sizeof(routerstatus_t
));
2227 router_digest_is_trusted_dir(ri
->cache_info
.identity_digest
);
2229 /* Already set by compute_performance_thresholds. */
2230 rs
->is_exit
= ri
->is_exit
;
2231 rs
->is_stable
= ri
->is_stable
=
2232 router_is_active(ri
, now
) &&
2233 !dirserv_thinks_router_is_unreliable(now
, ri
, 1, 0) &&
2235 rs
->is_fast
= ri
->is_fast
=
2236 router_is_active(ri
, now
) &&
2237 !dirserv_thinks_router_is_unreliable(now
, ri
, 0, 1);
2238 rs
->is_running
= ri
->is_running
; /* computed above */
2241 uint32_t name_status
= dirserv_get_name_status(
2242 ri
->cache_info
.identity_digest
, ri
->nickname
);
2243 rs
->is_named
= (naming
&& (name_status
& FP_NAMED
)) ? 1 : 0;
2244 rs
->is_unnamed
= (naming
&& (name_status
& FP_UNNAMED
)) ? 1 : 0;
2246 rs
->is_valid
= ri
->is_valid
;
2249 (router_get_advertised_bandwidth(ri
) >= BANDWIDTH_TO_GUARANTEE_GUARD
||
2250 router_get_advertised_bandwidth(ri
) >=
2251 MIN(guard_bandwidth_including_exits
,
2252 guard_bandwidth_excluding_exits
))) {
2253 long tk
= rep_hist_get_weighted_time_known(
2254 ri
->cache_info
.identity_digest
, now
);
2255 double wfu
= rep_hist_get_weighted_fractional_uptime(
2256 ri
->cache_info
.identity_digest
, now
);
2257 rs
->is_possible_guard
= (wfu
>= guard_wfu
&& tk
>= guard_tk
) ? 1 : 0;
2259 rs
->is_possible_guard
= 0;
2261 rs
->is_bad_directory
= listbaddirs
&& ri
->is_bad_directory
;
2262 rs
->is_bad_exit
= listbadexits
&& ri
->is_bad_exit
;
2263 ri
->is_hs_dir
= dirserv_thinks_router_is_hs_dir(ri
, now
);
2264 rs
->is_hs_dir
= ri
->is_hs_dir
;
2265 rs
->is_v2_dir
= ri
->dir_port
!= 0;
2267 if (!strcasecmp(ri
->nickname
, UNNAMED_ROUTER_NICKNAME
))
2268 rs
->is_named
= rs
->is_unnamed
= 0;
2270 rs
->published_on
= ri
->cache_info
.published_on
;
2271 memcpy(rs
->identity_digest
, ri
->cache_info
.identity_digest
, DIGEST_LEN
);
2272 memcpy(rs
->descriptor_digest
, ri
->cache_info
.signed_descriptor_digest
,
2274 rs
->addr
= ri
->addr
;
2275 strlcpy(rs
->nickname
, ri
->nickname
, sizeof(rs
->nickname
));
2276 rs
->or_port
= ri
->or_port
;
2277 rs
->dir_port
= ri
->dir_port
;
2280 /** Routerstatus <b>rs</b> is part of a group of routers that are on
2281 * too narrow an IP-space. Clear out its flags: we don't want people
2285 clear_status_flags_on_sybil(routerstatus_t
*rs
)
2287 rs
->is_authority
= rs
->is_exit
= rs
->is_stable
= rs
->is_fast
=
2288 rs
->is_running
= rs
->is_named
= rs
->is_valid
= rs
->is_v2_dir
=
2289 rs
->is_hs_dir
= rs
->is_possible_guard
= rs
->is_bad_exit
=
2290 rs
->is_bad_directory
= 0;
2291 /* FFFF we might want some mechanism to check later on if we
2292 * missed zeroing any flags: it's easy to add a new flag but
2293 * forget to add it to this clause. */
2296 /** Clear all the status flags in routerinfo <b>router</b>. We put this
2297 * function here because it's eerily similar to
2298 * clear_status_flags_on_sybil() above. One day we should merge them. */
2300 router_clear_status_flags(routerinfo_t
*router
)
2302 router
->is_valid
= router
->is_running
= router
->is_hs_dir
=
2303 router
->is_fast
= router
->is_stable
=
2304 router
->is_possible_guard
= router
->is_exit
=
2305 router
->is_bad_exit
= router
->is_bad_directory
= 0;
2309 * Helper function to parse out a line in the measured bandwidth file
2310 * into a measured_bw_line_t output structure. Returns -1 on failure
2314 measured_bw_line_parse(measured_bw_line_t
*out
, const char *orig_line
)
2316 char *line
= tor_strdup(orig_line
);
2319 int got_node_id
= 0;
2320 char *strtok_state
; /* lame sauce d'jour */
2321 cp
= tor_strtok_r(cp
, " \t", &strtok_state
);
2324 log_warn(LD_DIRSERV
, "Invalid line in bandwidth file: %s",
2325 escaped(orig_line
));
2330 if (orig_line
[strlen(orig_line
)-1] != '\n') {
2331 log_warn(LD_DIRSERV
, "Incomplete line in bandwidth file: %s",
2332 escaped(orig_line
));
2338 if (strcmpstart(cp
, "bw=") == 0) {
2342 log_warn(LD_DIRSERV
, "Double bw= in bandwidth file line: %s",
2343 escaped(orig_line
));
2349 out
->bw
= tor_parse_long(cp
, 0, 0, LONG_MAX
, &parse_ok
, &endptr
);
2350 if (!parse_ok
|| (*endptr
&& !TOR_ISSPACE(*endptr
))) {
2351 log_warn(LD_DIRSERV
, "Invalid bandwidth in bandwidth file line: %s",
2352 escaped(orig_line
));
2357 } else if (strcmpstart(cp
, "node_id=$") == 0) {
2359 log_warn(LD_DIRSERV
, "Double node_id= in bandwidth file line: %s",
2360 escaped(orig_line
));
2364 cp
+=strlen("node_id=$");
2366 if (strlen(cp
) != HEX_DIGEST_LEN
||
2367 base16_decode(out
->node_id
, DIGEST_LEN
, cp
, HEX_DIGEST_LEN
)) {
2368 log_warn(LD_DIRSERV
, "Invalid node_id in bandwidth file line: %s",
2369 escaped(orig_line
));
2373 strncpy(out
->node_hex
, cp
, sizeof(out
->node_hex
));
2376 } while ((cp
= tor_strtok_r(NULL
, " \t", &strtok_state
)));
2378 if (got_bw
&& got_node_id
) {
2382 log_warn(LD_DIRSERV
, "Incomplete line in bandwidth file: %s",
2383 escaped(orig_line
));
2390 * Helper function to apply a parsed measurement line to a list
2391 * of bandwidth statuses. Returns true if a line is found,
2395 measured_bw_line_apply(measured_bw_line_t
*parsed_line
,
2396 smartlist_t
*routerstatuses
)
2398 routerstatus_t
*rs
= NULL
;
2399 if (!routerstatuses
)
2402 rs
= smartlist_bsearch(routerstatuses
, parsed_line
->node_id
,
2403 compare_digest_to_routerstatus_entry
);
2406 rs
->has_measured_bw
= 1;
2407 rs
->measured_bw
= (uint32_t)parsed_line
->bw
;
2409 log_info(LD_DIRSERV
, "Node ID %s not found in routerstatus list",
2410 parsed_line
->node_hex
);
2417 * Read the measured bandwidth file and apply it to the list of
2418 * routerstatuses. Returns -1 on error, 0 otherwise.
2421 dirserv_read_measured_bandwidths(const char *from_file
,
2422 smartlist_t
*routerstatuses
)
2425 FILE *fp
= fopen(from_file
, "r");
2426 int applied_lines
= 0;
2430 log_warn(LD_CONFIG
, "Can't open bandwidth file at configured location: %s",
2435 if (!fgets(line
, sizeof(line
), fp
)
2436 || !strlen(line
) || line
[strlen(line
)-1] != '\n') {
2437 log_warn(LD_DIRSERV
, "Long or truncated time in bandwidth file: %s",
2443 line
[strlen(line
)-1] = '\0';
2444 file_time
= tor_parse_ulong(line
, 10, 0, ULONG_MAX
, &ok
, NULL
);
2446 log_warn(LD_DIRSERV
, "Non-integer time in bandwidth file: %s",
2452 if ((time(NULL
) - file_time
) > MAX_MEASUREMENT_AGE
) {
2453 log_warn(LD_DIRSERV
, "Bandwidth measurement file stale. Age: %u",
2454 (unsigned)(time(NULL
) - file_time
));
2460 smartlist_sort(routerstatuses
, compare_routerstatus_entries
);
2463 measured_bw_line_t parsed_line
;
2464 if (fgets(line
, sizeof(line
), fp
) && strlen(line
)) {
2465 if (measured_bw_line_parse(&parsed_line
, line
) != -1) {
2466 if (measured_bw_line_apply(&parsed_line
, routerstatuses
) > 0)
2473 log_info(LD_DIRSERV
,
2474 "Bandwidth measurement file successfully read. "
2475 "Applied %d measurements.", applied_lines
);
2479 /** Return a new networkstatus_t* containing our current opinion. (For v3
2482 dirserv_generate_networkstatus_vote_obj(crypto_pk_env_t
*private_key
,
2483 authority_cert_t
*cert
)
2485 or_options_t
*options
= get_options();
2486 networkstatus_t
*v3_out
= NULL
;
2488 char *hostname
= NULL
, *client_versions
= NULL
, *server_versions
= NULL
;
2489 const char *contact
;
2490 smartlist_t
*routers
, *routerstatuses
;
2491 char identity_digest
[DIGEST_LEN
];
2492 char signing_key_digest
[DIGEST_LEN
];
2493 int naming
= options
->NamingAuthoritativeDir
;
2494 int listbadexits
= options
->AuthDirListBadExits
;
2495 int listbaddirs
= options
->AuthDirListBadDirs
;
2496 routerlist_t
*rl
= router_get_routerlist();
2497 time_t now
= time(NULL
);
2498 time_t cutoff
= now
- ROUTER_MAX_AGE_TO_PUBLISH
;
2499 networkstatus_voter_info_t
*voter
= NULL
;
2500 vote_timing_t timing
;
2501 digestmap_t
*omit_as_sybil
= NULL
;
2502 const int vote_on_reachability
= running_long_enough_to_decide_unreachable();
2503 smartlist_t
*microdescriptors
= NULL
;
2505 tor_assert(private_key
);
2508 if (resolve_my_address(LOG_WARN
, options
, &addr
, &hostname
)<0) {
2509 log_warn(LD_NET
, "Couldn't resolve my hostname");
2512 if (!strchr(hostname
, '.')) {
2514 hostname
= tor_dup_ip(addr
);
2516 if (crypto_pk_get_digest(private_key
, signing_key_digest
)<0) {
2517 log_err(LD_BUG
, "Error computing signing key digest");
2520 if (crypto_pk_get_digest(cert
->identity_key
, identity_digest
)<0) {
2521 log_err(LD_BUG
, "Error computing identity key digest");
2525 if (options
->VersioningAuthoritativeDir
) {
2526 client_versions
= format_versions_list(options
->RecommendedClientVersions
);
2527 server_versions
= format_versions_list(options
->RecommendedServerVersions
);
2530 contact
= get_options()->ContactInfo
;
2534 /* precompute this part, since we need it to decide what "stable"
2536 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, ri
, {
2537 dirserv_set_router_is_running(ri
, now
);
2540 dirserv_compute_performance_thresholds(rl
);
2542 routers
= smartlist_create();
2543 smartlist_add_all(routers
, rl
->routers
);
2544 routers_sort_by_identity(routers
);
2545 omit_as_sybil
= get_possible_sybil_list(routers
);
2547 routerstatuses
= smartlist_create();
2548 microdescriptors
= smartlist_create();
2550 SMARTLIST_FOREACH_BEGIN(routers
, routerinfo_t
*, ri
) {
2551 if (ri
->cache_info
.published_on
>= cutoff
) {
2553 vote_routerstatus_t
*vrs
;
2556 vrs
= tor_malloc_zero(sizeof(vote_routerstatus_t
));
2558 set_routerstatus_from_routerinfo(rs
, ri
, now
,
2559 naming
, listbadexits
, listbaddirs
);
2561 if (digestmap_get(omit_as_sybil
, ri
->cache_info
.identity_digest
))
2562 clear_status_flags_on_sybil(rs
);
2564 if (!vote_on_reachability
)
2567 vrs
->version
= version_from_platform(ri
->platform
);
2568 md
= dirvote_create_microdescriptor(ri
);
2571 vote_microdesc_hash_t
*h
;
2572 dirvote_format_microdesc_vote_line(buf
, sizeof(buf
), md
);
2573 h
= tor_malloc(sizeof(vote_microdesc_hash_t
));
2574 h
->microdesc_hash_line
= tor_strdup(buf
);
2577 md
->last_listed
= now
;
2578 smartlist_add(microdescriptors
, md
);
2581 smartlist_add(routerstatuses
, vrs
);
2583 } SMARTLIST_FOREACH_END(ri
);
2586 smartlist_t
*added
=
2587 microdescs_add_list_to_cache(get_microdesc_cache(),
2588 microdescriptors
, SAVED_NOWHERE
, 0);
2589 smartlist_free(added
);
2590 smartlist_free(microdescriptors
);
2593 smartlist_free(routers
);
2594 digestmap_free(omit_as_sybil
, NULL
);
2596 if (options
->V3BandwidthsFile
) {
2597 dirserv_read_measured_bandwidths(options
->V3BandwidthsFile
,
2601 v3_out
= tor_malloc_zero(sizeof(networkstatus_t
));
2603 v3_out
->type
= NS_TYPE_VOTE
;
2604 dirvote_get_preferred_voting_intervals(&timing
);
2605 v3_out
->published
= now
;
2607 char tbuf
[ISO_TIME_LEN
+1];
2608 networkstatus_t
*current_consensus
=
2609 networkstatus_get_live_consensus(now
);
2610 long last_consensus_interval
; /* only used to pick a valid_after */
2611 if (current_consensus
)
2612 last_consensus_interval
= current_consensus
->fresh_until
-
2613 current_consensus
->valid_after
;
2615 last_consensus_interval
= options
->TestingV3AuthInitialVotingInterval
;
2616 v3_out
->valid_after
=
2617 dirvote_get_start_of_next_interval(now
, (int)last_consensus_interval
);
2618 format_iso_time(tbuf
, v3_out
->valid_after
);
2619 log_notice(LD_DIR
,"Choosing valid-after time in vote as %s: "
2620 "consensus_set=%d, last_interval=%d",
2621 tbuf
, current_consensus
?1:0, (int)last_consensus_interval
);
2623 v3_out
->fresh_until
= v3_out
->valid_after
+ timing
.vote_interval
;
2624 v3_out
->valid_until
= v3_out
->valid_after
+
2625 (timing
.vote_interval
* timing
.n_intervals_valid
);
2626 v3_out
->vote_seconds
= timing
.vote_delay
;
2627 v3_out
->dist_seconds
= timing
.dist_delay
;
2628 tor_assert(v3_out
->vote_seconds
> 0);
2629 tor_assert(v3_out
->dist_seconds
> 0);
2630 tor_assert(timing
.n_intervals_valid
> 0);
2632 v3_out
->client_versions
= client_versions
;
2633 v3_out
->server_versions
= server_versions
;
2634 v3_out
->known_flags
= smartlist_create();
2635 smartlist_split_string(v3_out
->known_flags
,
2636 "Authority Exit Fast Guard HSDir Stable V2Dir Valid",
2637 0, SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
2638 if (vote_on_reachability
)
2639 smartlist_add(v3_out
->known_flags
, tor_strdup("Running"));
2641 smartlist_add(v3_out
->known_flags
, tor_strdup("BadDirectory"));
2643 smartlist_add(v3_out
->known_flags
, tor_strdup("BadExit"));
2645 smartlist_add(v3_out
->known_flags
, tor_strdup("Named"));
2646 smartlist_add(v3_out
->known_flags
, tor_strdup("Unnamed"));
2648 smartlist_sort_strings(v3_out
->known_flags
);
2650 if (options
->ConsensusParams
) {
2651 v3_out
->net_params
= smartlist_create();
2652 smartlist_split_string(v3_out
->net_params
,
2653 options
->ConsensusParams
, NULL
, 0, 0);
2654 smartlist_sort_strings(v3_out
->net_params
);
2657 voter
= tor_malloc_zero(sizeof(networkstatus_voter_info_t
));
2658 voter
->nickname
= tor_strdup(options
->Nickname
);
2659 memcpy(voter
->identity_digest
, identity_digest
, DIGEST_LEN
);
2660 voter
->sigs
= smartlist_create();
2661 voter
->address
= hostname
;
2663 voter
->dir_port
= options
->DirPort
;
2664 voter
->or_port
= options
->ORPort
;
2665 voter
->contact
= tor_strdup(contact
);
2666 if (options
->V3AuthUseLegacyKey
) {
2667 authority_cert_t
*c
= get_my_v3_legacy_cert();
2669 crypto_pk_get_digest(c
->identity_key
, voter
->legacy_id_digest
);
2673 v3_out
->voters
= smartlist_create();
2674 smartlist_add(v3_out
->voters
, voter
);
2675 v3_out
->cert
= authority_cert_dup(cert
);
2676 v3_out
->routerstatus_list
= routerstatuses
;
2677 /* Note: networkstatus_digest is unset; it won't get set until we actually
2678 * format the vote. */
2683 /** For v2 authoritative directories only: Replace the contents of
2684 * <b>the_v2_networkstatus</b> with a newly generated network status
2686 static cached_dir_t
*
2687 generate_v2_networkstatus_opinion(void)
2689 cached_dir_t
*r
= NULL
;
2690 size_t len
, identity_pkey_len
;
2691 char *status
= NULL
, *client_versions
= NULL
, *server_versions
= NULL
,
2692 *identity_pkey
= NULL
, *hostname
= NULL
;
2694 or_options_t
*options
= get_options();
2695 char fingerprint
[FINGERPRINT_LEN
+1];
2696 char ipaddr
[INET_NTOA_BUF_LEN
];
2697 char published
[ISO_TIME_LEN
+1];
2698 char digest
[DIGEST_LEN
];
2701 crypto_pk_env_t
*private_key
;
2702 routerlist_t
*rl
= router_get_routerlist();
2703 time_t now
= time(NULL
);
2704 time_t cutoff
= now
- ROUTER_MAX_AGE_TO_PUBLISH
;
2705 int naming
= options
->NamingAuthoritativeDir
;
2706 int versioning
= options
->VersioningAuthoritativeDir
;
2707 int listbaddirs
= options
->AuthDirListBadDirs
;
2708 int listbadexits
= options
->AuthDirListBadExits
;
2709 const char *contact
;
2710 char *version_lines
= NULL
;
2711 smartlist_t
*routers
= NULL
;
2712 digestmap_t
*omit_as_sybil
= NULL
;
2714 private_key
= get_server_identity_key();
2716 if (resolve_my_address(LOG_WARN
, options
, &addr
, &hostname
)<0) {
2717 log_warn(LD_NET
, "Couldn't resolve my hostname");
2720 in
.s_addr
= htonl(addr
);
2721 tor_inet_ntoa(&in
, ipaddr
, sizeof(ipaddr
));
2723 format_iso_time(published
, now
);
2725 client_versions
= format_versions_list(options
->RecommendedClientVersions
);
2726 server_versions
= format_versions_list(options
->RecommendedServerVersions
);
2728 if (crypto_pk_write_public_key_to_string(private_key
, &identity_pkey
,
2729 &identity_pkey_len
)<0) {
2730 log_warn(LD_BUG
,"Writing public key to string failed.");
2734 if (crypto_pk_get_fingerprint(private_key
, fingerprint
, 0)<0) {
2735 log_err(LD_BUG
, "Error computing fingerprint");
2739 contact
= get_options()->ContactInfo
;
2744 size_t v_len
= 64+strlen(client_versions
)+strlen(server_versions
);
2745 version_lines
= tor_malloc(v_len
);
2746 tor_snprintf(version_lines
, v_len
,
2747 "client-versions %s\nserver-versions %s\n",
2748 client_versions
, server_versions
);
2750 version_lines
= tor_strdup("");
2753 len
= 4096+strlen(client_versions
)+strlen(server_versions
);
2754 len
+= identity_pkey_len
*2;
2755 len
+= (RS_ENTRY_LEN
)*smartlist_len(rl
->routers
);
2757 status
= tor_malloc(len
);
2758 tor_snprintf(status
, len
,
2759 "network-status-version 2\n"
2760 "dir-source %s %s %d\n"
2764 "dir-options%s%s%s%s\n"
2765 "%s" /* client version line, server version line. */
2766 "dir-signing-key\n%s",
2767 hostname
, ipaddr
, (int)options
->DirPort
,
2771 naming
? " Names" : "",
2772 listbaddirs
? " BadDirectories" : "",
2773 listbadexits
? " BadExits" : "",
2774 versioning
? " Versions" : "",
2777 outp
= status
+ strlen(status
);
2778 endp
= status
+ len
;
2780 /* precompute this part, since we need it to decide what "stable"
2782 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, ri
, {
2783 dirserv_set_router_is_running(ri
, now
);
2786 dirserv_compute_performance_thresholds(rl
);
2788 routers
= smartlist_create();
2789 smartlist_add_all(routers
, rl
->routers
);
2790 routers_sort_by_identity(routers
);
2792 omit_as_sybil
= get_possible_sybil_list(routers
);
2794 SMARTLIST_FOREACH(routers
, routerinfo_t
*, ri
, {
2795 if (ri
->cache_info
.published_on
>= cutoff
) {
2797 char *version
= version_from_platform(ri
->platform
);
2799 set_routerstatus_from_routerinfo(&rs
, ri
, now
,
2800 naming
, listbadexits
, listbaddirs
);
2802 if (digestmap_get(omit_as_sybil
, ri
->cache_info
.identity_digest
))
2803 clear_status_flags_on_sybil(&rs
);
2805 if (routerstatus_format_entry(outp
, endp
-outp
, &rs
, version
, NS_V2
)) {
2806 log_warn(LD_BUG
, "Unable to print router status.");
2811 outp
+= strlen(outp
);
2815 if (tor_snprintf(outp
, endp
-outp
, "directory-signature %s\n",
2816 get_options()->Nickname
)<0) {
2817 log_warn(LD_BUG
, "Unable to write signature line.");
2820 if (router_get_networkstatus_v2_hash(status
, digest
)<0) {
2821 log_warn(LD_BUG
, "Unable to hash network status");
2824 outp
+= strlen(outp
);
2826 note_crypto_pk_op(SIGN_DIR
);
2827 if (router_append_dirobj_signature(outp
,endp
-outp
,digest
,DIGEST_LEN
,
2829 log_warn(LD_BUG
, "Unable to sign router status.");
2834 networkstatus_v2_t
*ns
;
2835 if (!(ns
= networkstatus_v2_parse_from_string(status
))) {
2836 log_err(LD_BUG
,"Generated a networkstatus we couldn't parse.");
2839 networkstatus_v2_free(ns
);
2843 cached_dir_t
**ns_ptr
= &the_v2_networkstatus
;
2845 cached_dir_decref(*ns_ptr
);
2846 *ns_ptr
= new_cached_dir(status
, now
);
2847 status
= NULL
; /* So it doesn't get double-freed. */
2848 the_v2_networkstatus_is_dirty
= 0;
2849 router_set_networkstatus_v2((*ns_ptr
)->dir
, now
, NS_GENERATED
, NULL
);
2854 tor_free(client_versions
);
2855 tor_free(server_versions
);
2856 tor_free(version_lines
);
2859 tor_free(identity_pkey
);
2860 smartlist_free(routers
);
2861 digestmap_free(omit_as_sybil
, NULL
);
2865 /** Given the portion of a networkstatus request URL after "tor/status/" in
2866 * <b>key</b>, append to <b>result</b> the digests of the identity keys of the
2867 * networkstatus objects that the client has requested. */
2869 dirserv_get_networkstatus_v2_fingerprints(smartlist_t
*result
,
2874 if (!cached_v2_networkstatus
)
2875 cached_v2_networkstatus
= digestmap_new();
2877 if (should_generate_v2_networkstatus())
2878 generate_v2_networkstatus_opinion();
2880 if (!strcmp(key
,"authority")) {
2881 if (authdir_mode_v2(get_options())) {
2882 routerinfo_t
*me
= router_get_my_routerinfo();
2884 smartlist_add(result
,
2885 tor_memdup(me
->cache_info
.identity_digest
, DIGEST_LEN
));
2887 } else if (!strcmp(key
, "all")) {
2888 if (digestmap_size(cached_v2_networkstatus
)) {
2889 digestmap_iter_t
*iter
;
2890 iter
= digestmap_iter_init(cached_v2_networkstatus
);
2891 while (!digestmap_iter_done(iter
)) {
2894 digestmap_iter_get(iter
, &ident
, &val
);
2895 smartlist_add(result
, tor_memdup(ident
, DIGEST_LEN
));
2896 iter
= digestmap_iter_next(cached_v2_networkstatus
, iter
);
2899 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
2900 trusted_dir_server_t
*, ds
,
2901 if (ds
->type
& V2_AUTHORITY
)
2902 smartlist_add(result
, tor_memdup(ds
->digest
, DIGEST_LEN
)));
2904 smartlist_sort_digests(result
);
2905 if (smartlist_len(result
) == 0)
2906 log_info(LD_DIRSERV
,
2907 "Client requested 'all' network status objects; we have none.");
2908 } else if (!strcmpstart(key
, "fp/")) {
2909 dir_split_resource_into_fingerprints(key
+3, result
, NULL
,
2910 DSR_HEX
|DSR_SORT_UNIQ
);
2914 /** Look for a network status object as specified by <b>key</b>, which should
2915 * be either "authority" (to find a network status generated by us), a hex
2916 * identity digest (to find a network status generated by given directory), or
2917 * "all" (to return all the v2 network status objects we have).
2920 dirserv_get_networkstatus_v2(smartlist_t
*result
,
2923 cached_dir_t
*cached
;
2924 smartlist_t
*fingerprints
= smartlist_create();
2927 if (!cached_v2_networkstatus
)
2928 cached_v2_networkstatus
= digestmap_new();
2930 dirserv_get_networkstatus_v2_fingerprints(fingerprints
, key
);
2931 SMARTLIST_FOREACH(fingerprints
, const char *, fp
,
2933 if (router_digest_is_me(fp
) && should_generate_v2_networkstatus())
2934 generate_v2_networkstatus_opinion();
2935 cached
= digestmap_get(cached_v2_networkstatus
, fp
);
2937 smartlist_add(result
, cached
);
2939 char hexbuf
[HEX_DIGEST_LEN
+1];
2940 base16_encode(hexbuf
, sizeof(hexbuf
), fp
, DIGEST_LEN
);
2941 log_info(LD_DIRSERV
, "Don't know about any network status with "
2942 "fingerprint '%s'", hexbuf
);
2945 SMARTLIST_FOREACH(fingerprints
, char *, cp
, tor_free(cp
));
2946 smartlist_free(fingerprints
);
2949 /** As dirserv_get_routerdescs(), but instead of getting signed_descriptor_t
2950 * pointers, adds copies of digests to fps_out, and doesn't use the
2951 * /tor/server/ prefix. For a /d/ request, adds descriptor digests; for other
2952 * requests, adds identity digests.
2955 dirserv_get_routerdesc_fingerprints(smartlist_t
*fps_out
, const char *key
,
2956 const char **msg
, int for_unencrypted_conn
,
2962 if (!strcmp(key
, "all")) {
2963 routerlist_t
*rl
= router_get_routerlist();
2964 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
2965 smartlist_add(fps_out
,
2966 tor_memdup(r
->cache_info
.identity_digest
, DIGEST_LEN
)));
2967 } else if (!strcmp(key
, "authority")) {
2968 routerinfo_t
*ri
= router_get_my_routerinfo();
2970 smartlist_add(fps_out
,
2971 tor_memdup(ri
->cache_info
.identity_digest
, DIGEST_LEN
));
2972 } else if (!strcmpstart(key
, "d/")) {
2974 key
+= strlen("d/");
2975 dir_split_resource_into_fingerprints(key
, fps_out
, NULL
,
2976 DSR_HEX
|DSR_SORT_UNIQ
);
2977 } else if (!strcmpstart(key
, "fp/")) {
2978 key
+= strlen("fp/");
2979 dir_split_resource_into_fingerprints(key
, fps_out
, NULL
,
2980 DSR_HEX
|DSR_SORT_UNIQ
);
2982 *msg
= "Key not recognized";
2986 if (for_unencrypted_conn
) {
2987 /* Remove anything that insists it not be sent unencrypted. */
2988 SMARTLIST_FOREACH(fps_out
, char *, cp
, {
2989 signed_descriptor_t
*sd
;
2991 sd
= get_signed_descriptor_by_fp(cp
,is_extrainfo
,0);
2992 else if (is_extrainfo
)
2993 sd
= extrainfo_get_by_descriptor_digest(cp
);
2995 sd
= router_get_by_descriptor_digest(cp
);
2996 if (sd
&& !sd
->send_unencrypted
) {
2998 SMARTLIST_DEL_CURRENT(fps_out
, cp
);
3003 if (!smartlist_len(fps_out
)) {
3004 *msg
= "Servers unavailable";
3010 /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
3011 * <b>key</b>. The key should be either
3012 * - "/tor/server/authority" for our own routerinfo;
3013 * - "/tor/server/all" for all the routerinfos we have, concatenated;
3014 * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
3015 * hex identity digests; or
3016 * - "/tor/server/d/D" where D is a plus-separated sequence
3017 * of server descriptor digests, in hex.
3019 * Return 0 if we found some matching descriptors, or -1 if we do not
3020 * have any descriptors, no matching descriptors, or if we did not
3021 * recognize the key (URL).
3022 * If -1 is returned *<b>msg</b> will be set to an appropriate error
3025 * XXXX rename this function. It's only called from the controller.
3026 * XXXX in fact, refactor this function, merging as much as possible.
3029 dirserv_get_routerdescs(smartlist_t
*descs_out
, const char *key
,
3034 if (!strcmp(key
, "/tor/server/all")) {
3035 routerlist_t
*rl
= router_get_routerlist();
3036 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, r
,
3037 smartlist_add(descs_out
, &(r
->cache_info
)));
3038 } else if (!strcmp(key
, "/tor/server/authority")) {
3039 routerinfo_t
*ri
= router_get_my_routerinfo();
3041 smartlist_add(descs_out
, &(ri
->cache_info
));
3042 } else if (!strcmpstart(key
, "/tor/server/d/")) {
3043 smartlist_t
*digests
= smartlist_create();
3044 key
+= strlen("/tor/server/d/");
3045 dir_split_resource_into_fingerprints(key
, digests
, NULL
,
3046 DSR_HEX
|DSR_SORT_UNIQ
);
3047 SMARTLIST_FOREACH(digests
, const char *, d
,
3049 signed_descriptor_t
*sd
= router_get_by_descriptor_digest(d
);
3051 smartlist_add(descs_out
,sd
);
3053 SMARTLIST_FOREACH(digests
, char *, d
, tor_free(d
));
3054 smartlist_free(digests
);
3055 } else if (!strcmpstart(key
, "/tor/server/fp/")) {
3056 smartlist_t
*digests
= smartlist_create();
3057 time_t cutoff
= time(NULL
) - ROUTER_MAX_AGE_TO_PUBLISH
;
3058 key
+= strlen("/tor/server/fp/");
3059 dir_split_resource_into_fingerprints(key
, digests
, NULL
,
3060 DSR_HEX
|DSR_SORT_UNIQ
);
3061 SMARTLIST_FOREACH(digests
, const char *, d
,
3063 if (router_digest_is_me(d
)) {
3064 /* make sure desc_routerinfo exists */
3065 routerinfo_t
*ri
= router_get_my_routerinfo();
3067 smartlist_add(descs_out
, &(ri
->cache_info
));
3069 routerinfo_t
*ri
= router_get_by_digest(d
);
3070 /* Don't actually serve a descriptor that everyone will think is
3071 * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
3072 * Tors from downloading descriptors that they will throw away.
3074 if (ri
&& ri
->cache_info
.published_on
> cutoff
)
3075 smartlist_add(descs_out
, &(ri
->cache_info
));
3078 SMARTLIST_FOREACH(digests
, char *, d
, tor_free(d
));
3079 smartlist_free(digests
);
3081 *msg
= "Key not recognized";
3085 if (!smartlist_len(descs_out
)) {
3086 *msg
= "Servers unavailable";
3092 /** Called when a TLS handshake has completed successfully with a
3093 * router listening at <b>address</b>:<b>or_port</b>, and has yielded
3094 * a certificate with digest <b>digest_rcvd</b>.
3096 * Also, if as_advertised is 1, then inform the reachability checker
3097 * that we could get to this guy.
3100 dirserv_orconn_tls_done(const char *address
,
3102 const char *digest_rcvd
,
3105 routerlist_t
*rl
= router_get_routerlist();
3106 time_t now
= time(NULL
);
3107 int bridge_auth
= authdir_mode_bridge(get_options());
3108 tor_assert(address
);
3109 tor_assert(digest_rcvd
);
3111 SMARTLIST_FOREACH(rl
->routers
, routerinfo_t
*, ri
, {
3112 if (!strcasecmp(address
, ri
->address
) && or_port
== ri
->or_port
&&
3114 !memcmp(ri
->cache_info
.identity_digest
, digest_rcvd
, DIGEST_LEN
)) {
3115 /* correct digest. mark this router reachable! */
3116 if (!bridge_auth
|| ri
->purpose
== ROUTER_PURPOSE_BRIDGE
) {
3117 log_info(LD_DIRSERV
, "Found router %s to be reachable. Yay.",
3119 rep_hist_note_router_reachable(digest_rcvd
, now
);
3120 ri
->last_reachable
= now
;
3124 /* FFFF Maybe we should reinstate the code that dumps routers with the same
3125 * addr/port but with nonmatching keys, but instead of dumping, we should
3129 /** Called when we, as an authority, receive a new router descriptor either as
3130 * an upload or a download. Used to decide whether to relaunch reachability
3131 * testing for the server. */
3133 dirserv_should_launch_reachability_test(routerinfo_t
*ri
, routerinfo_t
*ri_old
)
3135 if (!authdir_mode_handles_descs(get_options(), ri
->purpose
))
3138 /* New router: Launch an immediate reachability test, so we will have an
3139 * opinion soon in case we're generating a consensus soon */
3142 if (ri_old
->is_hibernating
&& !ri
->is_hibernating
) {
3143 /* It just came out of hibernation; launch a reachability test */
3146 if (! routers_have_same_or_addr(ri
, ri_old
)) {
3147 /* Address or port changed; launch a reachability test */
3153 /** Helper function for dirserv_test_reachability(). Start a TLS
3154 * connection to <b>router</b>, and annotate it with when we started
3157 dirserv_single_reachability_test(time_t now
, routerinfo_t
*router
)
3159 tor_addr_t router_addr
;
3160 log_debug(LD_OR
,"Testing reachability of %s at %s:%u.",
3161 router
->nickname
, router
->address
, router
->or_port
);
3162 /* Remember when we started trying to determine reachability */
3163 if (!router
->testing_since
)
3164 router
->testing_since
= now
;
3165 tor_addr_from_ipv4h(&router_addr
, router
->addr
);
3166 connection_or_connect(&router_addr
, router
->or_port
,
3167 router
->cache_info
.identity_digest
);
3170 /** Auth dir server only: load balance such that we only
3171 * try a few connections per call.
3173 * The load balancing is such that if we get called once every ten
3174 * seconds, we will cycle through all the tests in 1280 seconds (a
3175 * bit over 20 minutes).
3178 dirserv_test_reachability(time_t now
)
3180 /* XXX decide what to do here; see or-talk thread "purging old router
3181 * information, revocation." -NM
3182 * We can't afford to mess with this in 0.1.2.x. The reason is that
3183 * if we stop doing reachability tests on some of routerlist, then
3184 * we'll for-sure think they're down, which may have unexpected
3185 * effects in other parts of the code. It doesn't hurt much to do
3186 * the testing, and directory authorities are easy to upgrade. Let's
3187 * wait til 0.2.0. -RD */
3188 // time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
3189 routerlist_t
*rl
= router_get_routerlist();
3190 static char ctr
= 0;
3191 int bridge_auth
= authdir_mode_bridge(get_options());
3193 SMARTLIST_FOREACH_BEGIN(rl
->routers
, routerinfo_t
*, router
) {
3194 const char *id_digest
= router
->cache_info
.identity_digest
;
3195 if (router_is_me(router
))
3197 if (bridge_auth
&& router
->purpose
!= ROUTER_PURPOSE_BRIDGE
)
3198 continue; /* bridge authorities only test reachability on bridges */
3199 // if (router->cache_info.published_on > cutoff)
3201 if ((((uint8_t)id_digest
[0]) % 128) == ctr
) {
3202 dirserv_single_reachability_test(now
, router
);
3204 } SMARTLIST_FOREACH_END(router
);
3205 ctr
= (ctr
+ 1) % 128; /* increment ctr */
3208 /** Given a fingerprint <b>fp</b> which is either set if we're looking for a
3209 * v2 status, or zeroes if we're looking for a v3 status, or a NUL-padded
3210 * flavor name if we want a flavored v3 status, return a pointer to the
3211 * appropriate cached dir object, or NULL if there isn't one available. */
3212 static cached_dir_t
*
3213 lookup_cached_dir_by_fp(const char *fp
)
3215 cached_dir_t
*d
= NULL
;
3216 if (tor_digest_is_zero(fp
) && cached_consensuses
)
3217 d
= strmap_get(cached_consensuses
, "ns");
3218 else if (memchr(fp
, '\0', DIGEST_LEN
) && cached_consensuses
&&
3219 (d
= strmap_get(cached_consensuses
, fp
))) {
3220 /* this here interface is a nasty hack XXXX022 */;
3221 } else if (router_digest_is_me(fp
) && the_v2_networkstatus
)
3222 d
= the_v2_networkstatus
;
3223 else if (cached_v2_networkstatus
)
3224 d
= digestmap_get(cached_v2_networkstatus
, fp
);
3228 /** Remove from <b>fps</b> every networkstatus key where both
3229 * a) we have a networkstatus document and
3230 * b) it is not newer than <b>cutoff</b>.
3232 * Return 1 if any items were present at all; else return 0.
3235 dirserv_remove_old_statuses(smartlist_t
*fps
, time_t cutoff
)
3238 SMARTLIST_FOREACH(fps
, char *, digest
,
3240 cached_dir_t
*d
= lookup_cached_dir_by_fp(digest
);
3244 if (d
->published
<= cutoff
) {
3246 SMARTLIST_DEL_CURRENT(fps
, digest
);
3253 /** Return the cache-info for identity fingerprint <b>fp</b>, or
3254 * its extra-info document if <b>extrainfo</b> is true. Return
3255 * NULL if not found or if the descriptor is older than
3256 * <b>publish_cutoff</b>. */
3257 static signed_descriptor_t
*
3258 get_signed_descriptor_by_fp(const char *fp
, int extrainfo
,
3259 time_t publish_cutoff
)
3261 if (router_digest_is_me(fp
)) {
3263 return &(router_get_my_extrainfo()->cache_info
);
3265 return &(router_get_my_routerinfo()->cache_info
);
3267 routerinfo_t
*ri
= router_get_by_digest(fp
);
3269 ri
->cache_info
.published_on
> publish_cutoff
) {
3271 return extrainfo_get_by_descriptor_digest(
3272 ri
->cache_info
.extra_info_digest
);
3274 return &ri
->cache_info
;
3280 /** Return true iff we have any of the documents (extrainfo or routerdesc)
3281 * specified by the fingerprints in <b>fps</b> and <b>spool_src</b>. Used to
3282 * decide whether to send a 404. */
3284 dirserv_have_any_serverdesc(smartlist_t
*fps
, int spool_src
)
3286 time_t publish_cutoff
= time(NULL
)-ROUTER_MAX_AGE_TO_PUBLISH
;
3287 SMARTLIST_FOREACH(fps
, const char *, fp
, {
3290 case DIR_SPOOL_EXTRA_BY_DIGEST
:
3291 if (extrainfo_get_by_descriptor_digest(fp
)) return 1;
3293 case DIR_SPOOL_SERVER_BY_DIGEST
:
3294 if (router_get_by_descriptor_digest(fp
)) return 1;
3296 case DIR_SPOOL_EXTRA_BY_FP
:
3297 case DIR_SPOOL_SERVER_BY_FP
:
3298 if (get_signed_descriptor_by_fp(fp
,
3299 spool_src
== DIR_SPOOL_EXTRA_BY_FP
, publish_cutoff
))
3307 /** Return true iff any of the 256-bit elements in <b>fps</b> is the digest of
3308 * a microdescriptor we have. */
3310 dirserv_have_any_microdesc(const smartlist_t
*fps
)
3312 microdesc_cache_t
*cache
= get_microdesc_cache();
3313 SMARTLIST_FOREACH(fps
, const char *, fp
,
3314 if (microdesc_cache_lookup_by_digest256(cache
, fp
))
3319 /** Return an approximate estimate of the number of bytes that will
3320 * be needed to transmit the server descriptors (if is_serverdescs --
3321 * they can be either d/ or fp/ queries) or networkstatus objects (if
3322 * !is_serverdescs) listed in <b>fps</b>. If <b>compressed</b> is set,
3323 * we guess how large the data will be after compression.
3325 * The return value is an estimate; it might be larger or smaller.
3328 dirserv_estimate_data_size(smartlist_t
*fps
, int is_serverdescs
,
3333 if (is_serverdescs
) {
3334 int n
= smartlist_len(fps
);
3335 routerinfo_t
*me
= router_get_my_routerinfo();
3336 result
= (me
?me
->cache_info
.signed_descriptor_len
:2048) * n
;
3338 result
/= 2; /* observed compressibility is between 35 and 55%. */
3341 SMARTLIST_FOREACH(fps
, const char *, digest
, {
3342 cached_dir_t
*dir
= lookup_cached_dir_by_fp(digest
);
3344 result
+= compressed
? dir
->dir_z_len
: dir
->dir_len
;
3350 /** Given a list of microdescriptor hashes, guess how many bytes will be
3351 * needed to transmit them, and return the guess. */
3353 dirserv_estimate_microdesc_size(const smartlist_t
*fps
, int compressed
)
3355 size_t result
= smartlist_len(fps
) * microdesc_average_size(NULL
);
3361 /** When we're spooling data onto our outbuf, add more whenever we dip
3362 * below this threshold. */
3363 #define DIRSERV_BUFFER_MIN 16384
3365 /** Spooling helper: called when we have no more data to spool to <b>conn</b>.
3366 * Flushes any remaining data to be (un)compressed, and changes the spool
3367 * source to NONE. Returns 0 on success, negative on failure. */
3369 connection_dirserv_finish_spooling(dir_connection_t
*conn
)
3371 if (conn
->zlib_state
) {
3372 connection_write_to_buf_zlib("", 0, conn
, 1);
3373 tor_zlib_free(conn
->zlib_state
);
3374 conn
->zlib_state
= NULL
;
3376 conn
->dir_spool_src
= DIR_SPOOL_NONE
;
3380 /** Spooling helper: called when we're sending a bunch of server descriptors,
3381 * and the outbuf has become too empty. Pulls some entries from
3382 * fingerprint_stack, and writes the corresponding servers onto outbuf. If we
3383 * run out of entries, flushes the zlib state and sets the spool source to
3384 * NONE. Returns 0 on success, negative on failure.
3387 connection_dirserv_add_servers_to_outbuf(dir_connection_t
*conn
)
3389 #ifdef TRACK_SERVED_TIME
3390 time_t now
= time(NULL
);
3392 int by_fp
= (conn
->dir_spool_src
== DIR_SPOOL_SERVER_BY_FP
||
3393 conn
->dir_spool_src
== DIR_SPOOL_EXTRA_BY_FP
);
3394 int extra
= (conn
->dir_spool_src
== DIR_SPOOL_EXTRA_BY_FP
||
3395 conn
->dir_spool_src
== DIR_SPOOL_EXTRA_BY_DIGEST
);
3396 time_t publish_cutoff
= time(NULL
)-ROUTER_MAX_AGE_TO_PUBLISH
;
3398 while (smartlist_len(conn
->fingerprint_stack
) &&
3399 buf_datalen(conn
->_base
.outbuf
) < DIRSERV_BUFFER_MIN
) {
3401 char *fp
= smartlist_pop_last(conn
->fingerprint_stack
);
3402 signed_descriptor_t
*sd
= NULL
;
3404 sd
= get_signed_descriptor_by_fp(fp
, extra
, publish_cutoff
);
3406 sd
= extra
? extrainfo_get_by_descriptor_digest(fp
)
3407 : router_get_by_descriptor_digest(fp
);
3412 if (!connection_dir_is_encrypted(conn
) && !sd
->send_unencrypted
) {
3413 /* we did this check once before (so we could have an accurate size
3414 * estimate and maybe send a 404 if somebody asked for only bridges on a
3415 * connection), but we need to do it again in case a previously
3416 * unknown bridge descriptor has shown up between then and now. */
3419 #ifdef TRACK_SERVED_TIME
3420 sd
->last_served_at
= now
;
3422 body
= signed_descriptor_get_body(sd
);
3423 if (conn
->zlib_state
) {
3424 /* XXXX022 This 'last' business should actually happen on the last
3425 * routerinfo, not on the last fingerprint. */
3426 int last
= ! smartlist_len(conn
->fingerprint_stack
);
3427 connection_write_to_buf_zlib(body
, sd
->signed_descriptor_len
, conn
,
3430 tor_zlib_free(conn
->zlib_state
);
3431 conn
->zlib_state
= NULL
;
3434 connection_write_to_buf(body
,
3435 sd
->signed_descriptor_len
,
3440 if (!smartlist_len(conn
->fingerprint_stack
)) {
3441 /* We just wrote the last one; finish up. */
3442 conn
->dir_spool_src
= DIR_SPOOL_NONE
;
3443 smartlist_free(conn
->fingerprint_stack
);
3444 conn
->fingerprint_stack
= NULL
;
3449 /** Spooling helper: called when we're sending a bunch of microdescriptors,
3450 * and the outbuf has become too empty. Pulls some entries from
3451 * fingerprint_stack, and writes the corresponding microdescs onto outbuf. If
3452 * we run out of entries, flushes the zlib state and sets the spool source to
3453 * NONE. Returns 0 on success, negative on failure.
3456 connection_dirserv_add_microdescs_to_outbuf(dir_connection_t
*conn
)
3458 microdesc_cache_t
*cache
= get_microdesc_cache();
3459 while (smartlist_len(conn
->fingerprint_stack
) &&
3460 buf_datalen(conn
->_base
.outbuf
) < DIRSERV_BUFFER_MIN
) {
3461 char *fp256
= smartlist_pop_last(conn
->fingerprint_stack
);
3462 microdesc_t
*md
= microdesc_cache_lookup_by_digest256(cache
, fp256
);
3466 if (conn
->zlib_state
) {
3467 /* XXXX022 This 'last' business should actually happen on the last
3468 * routerinfo, not on the last fingerprint. */
3469 int last
= !smartlist_len(conn
->fingerprint_stack
);
3470 connection_write_to_buf_zlib(md
->body
, md
->bodylen
, conn
, last
);
3472 tor_zlib_free(conn
->zlib_state
);
3473 conn
->zlib_state
= NULL
;
3476 connection_write_to_buf(md
->body
, md
->bodylen
, TO_CONN(conn
));
3479 if (!smartlist_len(conn
->fingerprint_stack
)) {
3480 conn
->dir_spool_src
= DIR_SPOOL_NONE
;
3481 smartlist_free(conn
->fingerprint_stack
);
3482 conn
->fingerprint_stack
= NULL
;
3487 /** Spooling helper: Called when we're sending a directory or networkstatus,
3488 * and the outbuf has become too empty. Pulls some bytes from
3489 * <b>conn</b>-\>cached_dir-\>dir_z, uncompresses them if appropriate, and
3490 * puts them on the outbuf. If we run out of entries, flushes the zlib state
3491 * and sets the spool source to NONE. Returns 0 on success, negative on
3494 connection_dirserv_add_dir_bytes_to_outbuf(dir_connection_t
*conn
)
3499 bytes
= DIRSERV_BUFFER_MIN
- buf_datalen(conn
->_base
.outbuf
);
3500 tor_assert(bytes
> 0);
3501 tor_assert(conn
->cached_dir
);
3504 remaining
= conn
->cached_dir
->dir_z_len
- conn
->cached_dir_offset
;
3505 if (bytes
> remaining
)
3506 bytes
= (ssize_t
) remaining
;
3508 if (conn
->zlib_state
) {
3509 connection_write_to_buf_zlib(
3510 conn
->cached_dir
->dir_z
+ conn
->cached_dir_offset
,
3511 bytes
, conn
, bytes
== remaining
);
3513 connection_write_to_buf(conn
->cached_dir
->dir_z
+ conn
->cached_dir_offset
,
3514 bytes
, TO_CONN(conn
));
3516 conn
->cached_dir_offset
+= bytes
;
3517 if (conn
->cached_dir_offset
== (int)conn
->cached_dir
->dir_z_len
) {
3518 /* We just wrote the last one; finish up. */
3519 connection_dirserv_finish_spooling(conn
);
3520 cached_dir_decref(conn
->cached_dir
);
3521 conn
->cached_dir
= NULL
;
3526 /** Spooling helper: Called when we're spooling networkstatus objects on
3527 * <b>conn</b>, and the outbuf has become too empty. If the current
3528 * networkstatus object (in <b>conn</b>-\>cached_dir) has more data, pull data
3529 * from there. Otherwise, pop the next fingerprint from fingerprint_stack,
3530 * and start spooling the next networkstatus. (A digest of all 0 bytes is
3531 * treated as a request for the current consensus.) If we run out of entries,
3532 * flushes the zlib state and sets the spool source to NONE. Returns 0 on
3533 * success, negative on failure. */
3535 connection_dirserv_add_networkstatus_bytes_to_outbuf(dir_connection_t
*conn
)
3538 while (buf_datalen(conn
->_base
.outbuf
) < DIRSERV_BUFFER_MIN
) {
3539 if (conn
->cached_dir
) {
3540 int uncompressing
= (conn
->zlib_state
!= NULL
);
3541 int r
= connection_dirserv_add_dir_bytes_to_outbuf(conn
);
3542 if (conn
->dir_spool_src
== DIR_SPOOL_NONE
) {
3543 /* add_dir_bytes thinks we're done with the cached_dir. But we
3544 * may have more cached_dirs! */
3545 conn
->dir_spool_src
= DIR_SPOOL_NETWORKSTATUS
;
3546 /* This bit is tricky. If we were uncompressing the last
3547 * networkstatus, we may need to make a new zlib object to
3548 * uncompress the next one. */
3549 if (uncompressing
&& ! conn
->zlib_state
&&
3550 conn
->fingerprint_stack
&&
3551 smartlist_len(conn
->fingerprint_stack
)) {
3552 conn
->zlib_state
= tor_zlib_new(0, ZLIB_METHOD
);
3556 } else if (conn
->fingerprint_stack
&&
3557 smartlist_len(conn
->fingerprint_stack
)) {
3558 /* Add another networkstatus; start serving it. */
3559 char *fp
= smartlist_pop_last(conn
->fingerprint_stack
);
3560 cached_dir_t
*d
= lookup_cached_dir_by_fp(fp
);
3564 conn
->cached_dir
= d
;
3565 conn
->cached_dir_offset
= 0;
3568 connection_dirserv_finish_spooling(conn
);
3569 smartlist_free(conn
->fingerprint_stack
);
3570 conn
->fingerprint_stack
= NULL
;
3577 /** Called whenever we have flushed some directory data in state
3578 * SERVER_WRITING. */
3580 connection_dirserv_flushed_some(dir_connection_t
*conn
)
3582 tor_assert(conn
->_base
.state
== DIR_CONN_STATE_SERVER_WRITING
);
3584 if (buf_datalen(conn
->_base
.outbuf
) >= DIRSERV_BUFFER_MIN
)
3587 switch (conn
->dir_spool_src
) {
3588 case DIR_SPOOL_EXTRA_BY_DIGEST
:
3589 case DIR_SPOOL_EXTRA_BY_FP
:
3590 case DIR_SPOOL_SERVER_BY_DIGEST
:
3591 case DIR_SPOOL_SERVER_BY_FP
:
3592 return connection_dirserv_add_servers_to_outbuf(conn
);
3593 case DIR_SPOOL_MICRODESC
:
3594 return connection_dirserv_add_microdescs_to_outbuf(conn
);
3595 case DIR_SPOOL_CACHED_DIR
:
3596 return connection_dirserv_add_dir_bytes_to_outbuf(conn
);
3597 case DIR_SPOOL_NETWORKSTATUS
:
3598 return connection_dirserv_add_networkstatus_bytes_to_outbuf(conn
);
3599 case DIR_SPOOL_NONE
:
3605 /** Release all storage used by the directory server. */
3607 dirserv_free_all(void)
3609 dirserv_free_fingerprint_list();
3611 cached_dir_decref(the_directory
);
3612 clear_cached_dir(&the_runningrouters
);
3613 cached_dir_decref(the_v2_networkstatus
);
3614 cached_dir_decref(cached_directory
);
3615 clear_cached_dir(&cached_runningrouters
);
3617 digestmap_free(cached_v2_networkstatus
, _free_cached_dir
);
3618 cached_v2_networkstatus
= NULL
;
3619 strmap_free(cached_consensuses
, _free_cached_dir
);
3620 cached_consensuses
= NULL
;