Fix grammar in comment on running_long_enough_to_decide_unreachable
[tor.git] / src / or / dirserv.c
blob45d12ed3b17b89db11c8cb78e51024cd737c3979
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2014, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 #define DIRSERV_PRIVATE
7 #include "or.h"
8 #include "buffers.h"
9 #include "config.h"
10 #include "confparse.h"
11 #include "channel.h"
12 #include "channeltls.h"
13 #include "command.h"
14 #include "connection.h"
15 #include "connection_or.h"
16 #include "control.h"
17 #include "directory.h"
18 #include "dirserv.h"
19 #include "dirvote.h"
20 #include "hibernate.h"
21 #include "microdesc.h"
22 #include "networkstatus.h"
23 #include "nodelist.h"
24 #include "policies.h"
25 #include "rephist.h"
26 #include "router.h"
27 #include "routerlist.h"
28 #include "routerparse.h"
29 #include "routerset.h"
31 /**
32 * \file dirserv.c
33 * \brief Directory server core implementation. Manages directory
34 * contents and generates directories.
37 /** How far in the future do we allow a router to get? (seconds) */
38 #define ROUTER_ALLOW_SKEW (60*60*12)
39 /** How many seconds do we wait before regenerating the directory? */
40 #define DIR_REGEN_SLACK_TIME 30
41 /** If we're a cache, keep this many networkstatuses around from non-trusted
42 * directory authorities. */
43 #define MAX_UNTRUSTED_NETWORKSTATUSES 16
45 extern time_t time_of_process_start; /* from main.c */
47 extern long stats_n_seconds_working; /* from main.c */
49 /** Total number of routers with measured bandwidth; this is set by
50 * dirserv_count_measured_bws() before the loop in
51 * dirserv_generate_networkstatus_vote_obj() and checked by
52 * dirserv_get_credible_bandwidth() and
53 * dirserv_compute_performance_thresholds() */
54 static int routers_with_measured_bw = 0;
56 static void directory_remove_invalid(void);
57 static char *format_versions_list(config_line_t *ln);
58 struct authdir_config_t;
59 static uint32_t
60 dirserv_get_status_impl(const char *fp, const char *nickname,
61 uint32_t addr, uint16_t or_port,
62 const char *platform, const char **msg,
63 int should_log);
64 static void clear_cached_dir(cached_dir_t *d);
65 static const signed_descriptor_t *get_signed_descriptor_by_fp(
66 const char *fp,
67 int extrainfo,
68 time_t publish_cutoff);
69 static was_router_added_t dirserv_add_extrainfo(extrainfo_t *ei,
70 const char **msg);
71 static uint32_t dirserv_get_bandwidth_for_router_kb(const routerinfo_t *ri);
72 static uint32_t dirserv_get_credible_bandwidth_kb(const routerinfo_t *ri);
74 /************** Fingerprint handling code ************/
76 /* 1 Historically used to indicate Named */
77 #define FP_INVALID 2 /**< Believed invalid. */
78 #define FP_REJECT 4 /**< We will not publish this router. */
79 /* 8 Historically used to avoid using this as a dir. */
80 #define FP_BADEXIT 16 /**< We'll tell clients not to use this as an exit. */
81 /* 32 Historically used to indicade Unnamed */
83 /** Target of status_by_digest map. */
84 typedef uint32_t router_status_t;
86 static void add_fingerprint_to_dir(const char *fp,
87 struct authdir_config_t *list,
88 router_status_t add_status);
90 /** List of nickname-\>identity fingerprint mappings for all the routers
91 * that we name. Used to prevent router impersonation. */
92 typedef struct authdir_config_t {
93 strmap_t *fp_by_name; /**< Map from lc nickname to fingerprint. */
94 digestmap_t *status_by_digest; /**< Map from digest to router_status_t. */
95 } authdir_config_t;
97 /** Should be static; exposed for testing. */
98 static authdir_config_t *fingerprint_list = NULL;
100 /** Allocate and return a new, empty, authdir_config_t. */
101 static authdir_config_t *
102 authdir_config_new(void)
104 authdir_config_t *list = tor_malloc_zero(sizeof(authdir_config_t));
105 list->fp_by_name = strmap_new();
106 list->status_by_digest = digestmap_new();
107 return list;
110 /** Add the fingerprint <b>fp</b> to the smartlist of fingerprint_entry_t's
111 * <b>list</b>, or-ing the currently set status flags with
112 * <b>add_status</b>.
114 /* static */ void
115 add_fingerprint_to_dir(const char *fp, authdir_config_t *list,
116 router_status_t add_status)
118 char *fingerprint;
119 char d[DIGEST_LEN];
120 router_status_t *status;
121 tor_assert(fp);
122 tor_assert(list);
124 fingerprint = tor_strdup(fp);
125 tor_strstrip(fingerprint, " ");
126 if (base16_decode(d, DIGEST_LEN, fingerprint, strlen(fingerprint))) {
127 log_warn(LD_DIRSERV, "Couldn't decode fingerprint \"%s\"",
128 escaped(fp));
129 tor_free(fingerprint);
130 return;
133 status = digestmap_get(list->status_by_digest, d);
134 if (!status) {
135 status = tor_malloc_zero(sizeof(router_status_t));
136 digestmap_set(list->status_by_digest, d, status);
139 tor_free(fingerprint);
140 *status |= add_status;
141 return;
144 /** Add the fingerprint for this OR to the global list of recognized
145 * identity key fingerprints. */
147 dirserv_add_own_fingerprint(crypto_pk_t *pk)
149 char fp[FINGERPRINT_LEN+1];
150 if (crypto_pk_get_fingerprint(pk, fp, 0)<0) {
151 log_err(LD_BUG, "Error computing fingerprint");
152 return -1;
154 if (!fingerprint_list)
155 fingerprint_list = authdir_config_new();
156 add_fingerprint_to_dir(fp, fingerprint_list, 0);
157 return 0;
160 /** Load the nickname-\>fingerprint mappings stored in the approved-routers
161 * file. The file format is line-based, with each non-blank holding one
162 * nickname, some space, and a fingerprint for that nickname. On success,
163 * replace the current fingerprint list with the new list and return 0. On
164 * failure, leave the current fingerprint list untouched, and return -1. */
166 dirserv_load_fingerprint_file(void)
168 char *fname;
169 char *cf;
170 char *nickname, *fingerprint;
171 authdir_config_t *fingerprint_list_new;
172 int result;
173 config_line_t *front=NULL, *list;
175 fname = get_datadir_fname("approved-routers");
176 log_info(LD_GENERAL,
177 "Reloading approved fingerprints from \"%s\"...", fname);
179 cf = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
180 if (!cf) {
181 log_warn(LD_FS, "Cannot open fingerprint file '%s'. That's ok.", fname);
182 tor_free(fname);
183 return 0;
185 tor_free(fname);
187 result = config_get_lines(cf, &front, 0);
188 tor_free(cf);
189 if (result < 0) {
190 log_warn(LD_CONFIG, "Error reading from fingerprint file");
191 return -1;
194 fingerprint_list_new = authdir_config_new();
196 for (list=front; list; list=list->next) {
197 char digest_tmp[DIGEST_LEN];
198 router_status_t add_status = 0;
199 nickname = list->key; fingerprint = list->value;
200 tor_strstrip(fingerprint, " "); /* remove spaces */
201 if (strlen(fingerprint) != HEX_DIGEST_LEN ||
202 base16_decode(digest_tmp, sizeof(digest_tmp),
203 fingerprint, HEX_DIGEST_LEN) < 0) {
204 log_notice(LD_CONFIG,
205 "Invalid fingerprint (nickname '%s', "
206 "fingerprint %s). Skipping.",
207 nickname, fingerprint);
208 continue;
210 if (!strcasecmp(nickname, "!reject")) {
211 add_status = FP_REJECT;
212 } else if (!strcasecmp(nickname, "!badexit")) {
213 add_status = FP_BADEXIT;
214 } else if (!strcasecmp(nickname, "!invalid")) {
215 add_status = FP_INVALID;
217 add_fingerprint_to_dir(fingerprint, fingerprint_list_new, add_status);
220 config_free_lines(front);
221 dirserv_free_fingerprint_list();
222 fingerprint_list = fingerprint_list_new;
223 /* Delete any routers whose fingerprints we no longer recognize */
224 directory_remove_invalid();
225 return 0;
228 /** Check whether <b>router</b> has a nickname/identity key combination that
229 * we recognize from the fingerprint list, or an IP we automatically act on
230 * according to our configuration. Return the appropriate router status.
232 * If the status is 'FP_REJECT' and <b>msg</b> is provided, set
233 * *<b>msg</b> to an explanation of why. */
234 uint32_t
235 dirserv_router_get_status(const routerinfo_t *router, const char **msg)
237 char d[DIGEST_LEN];
239 if (crypto_pk_get_digest(router->identity_pkey, d)) {
240 log_warn(LD_BUG,"Error computing fingerprint");
241 if (msg)
242 *msg = "Bug: Error computing fingerprint";
243 return FP_REJECT;
246 return dirserv_get_status_impl(d, router->nickname,
247 router->addr, router->or_port,
248 router->platform, msg, 1);
251 /** Return true if there is no point in downloading the router described by
252 * <b>rs</b> because this directory would reject it. */
254 dirserv_would_reject_router(const routerstatus_t *rs)
256 uint32_t res;
258 res = dirserv_get_status_impl(rs->identity_digest, rs->nickname,
259 rs->addr, rs->or_port,
260 NULL, NULL, 0);
262 return (res & FP_REJECT) != 0;
265 /** Helper: As dirserv_router_get_status, but takes the router fingerprint
266 * (hex, no spaces), nickname, address (used for logging only), IP address, OR
267 * port and platform (logging only) as arguments.
269 * If should_log is false, do not log messages. (There's not much point in
270 * logging that we're rejecting servers we'll not download.)
272 static uint32_t
273 dirserv_get_status_impl(const char *id_digest, const char *nickname,
274 uint32_t addr, uint16_t or_port,
275 const char *platform, const char **msg, int should_log)
277 uint32_t result = 0;
278 router_status_t *status_by_digest;
280 if (!fingerprint_list)
281 fingerprint_list = authdir_config_new();
283 if (should_log)
284 log_debug(LD_DIRSERV, "%d fingerprints, %d digests known.",
285 strmap_size(fingerprint_list->fp_by_name),
286 digestmap_size(fingerprint_list->status_by_digest));
288 /* Versions before Tor 0.2.3.16-alpha are too old to support, and are
289 * missing some important security fixes too. Disable them. */
290 if (platform && !tor_version_as_new_as(platform,"0.2.3.16-alpha")) {
291 if (msg)
292 *msg = "Tor version is insecure or unsupported. Please upgrade!";
293 return FP_REJECT;
296 status_by_digest = digestmap_get(fingerprint_list->status_by_digest,
297 id_digest);
298 if (status_by_digest)
299 result |= *status_by_digest;
301 if (result & FP_REJECT) {
302 if (msg)
303 *msg = "Fingerprint is marked rejected";
304 return FP_REJECT;
305 } else if (result & FP_INVALID) {
306 if (msg)
307 *msg = "Fingerprint is marked invalid";
310 if (authdir_policy_badexit_address(addr, or_port)) {
311 if (should_log)
312 log_info(LD_DIRSERV, "Marking '%s' as bad exit because of address '%s'",
313 nickname, fmt_addr32(addr));
314 result |= FP_BADEXIT;
317 if (!authdir_policy_permits_address(addr, or_port)) {
318 if (should_log)
319 log_info(LD_DIRSERV, "Rejecting '%s' because of address '%s'",
320 nickname, fmt_addr32(addr));
321 if (msg)
322 *msg = "Authdir is rejecting routers in this range.";
323 return FP_REJECT;
325 if (!authdir_policy_valid_address(addr, or_port)) {
326 if (should_log)
327 log_info(LD_DIRSERV, "Not marking '%s' valid because of address '%s'",
328 nickname, fmt_addr32(addr));
329 result |= FP_INVALID;
332 return result;
335 /** Clear the current fingerprint list. */
336 void
337 dirserv_free_fingerprint_list(void)
339 if (!fingerprint_list)
340 return;
342 strmap_free(fingerprint_list->fp_by_name, tor_free_);
343 digestmap_free(fingerprint_list->status_by_digest, tor_free_);
344 tor_free(fingerprint_list);
348 * Descriptor list
351 /** Return -1 if <b>ri</b> has a private or otherwise bad address,
352 * unless we're configured to not care. Return 0 if all ok. */
353 static int
354 dirserv_router_has_valid_address(routerinfo_t *ri)
356 tor_addr_t addr;
357 if (get_options()->DirAllowPrivateAddresses)
358 return 0; /* whatever it is, we're fine with it */
359 tor_addr_from_ipv4h(&addr, ri->addr);
361 if (tor_addr_is_internal(&addr, 0)) {
362 log_info(LD_DIRSERV,
363 "Router %s published internal IP address. Refusing.",
364 router_describe(ri));
365 return -1; /* it's a private IP, we should reject it */
367 return 0;
370 /** Check whether we, as a directory server, want to accept <b>ri</b>. If so,
371 * set its is_valid,running fields and return 0. Otherwise, return -1.
373 * If the router is rejected, set *<b>msg</b> to an explanation of why.
375 * If <b>complain</b> then explain at log-level 'notice' why we refused
376 * a descriptor; else explain at log-level 'info'.
379 authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
380 int complain, int *valid_out)
382 /* Okay. Now check whether the fingerprint is recognized. */
383 uint32_t status = dirserv_router_get_status(ri, msg);
384 time_t now;
385 int severity = (complain && ri->contact_info) ? LOG_NOTICE : LOG_INFO;
386 tor_assert(msg);
387 if (status & FP_REJECT)
388 return -1; /* msg is already set. */
390 /* Is there too much clock skew? */
391 now = time(NULL);
392 if (ri->cache_info.published_on > now+ROUTER_ALLOW_SKEW) {
393 log_fn(severity, LD_DIRSERV, "Publication time for %s is too "
394 "far (%d minutes) in the future; possible clock skew. Not adding "
395 "(%s)",
396 router_describe(ri),
397 (int)((ri->cache_info.published_on-now)/60),
398 esc_router_info(ri));
399 *msg = "Rejected: Your clock is set too far in the future, or your "
400 "timezone is not correct.";
401 return -1;
403 if (ri->cache_info.published_on < now-ROUTER_MAX_AGE_TO_PUBLISH) {
404 log_fn(severity, LD_DIRSERV,
405 "Publication time for %s is too far "
406 "(%d minutes) in the past. Not adding (%s)",
407 router_describe(ri),
408 (int)((now-ri->cache_info.published_on)/60),
409 esc_router_info(ri));
410 *msg = "Rejected: Server is expired, or your clock is too far in the past,"
411 " or your timezone is not correct.";
412 return -1;
414 if (dirserv_router_has_valid_address(ri) < 0) {
415 log_fn(severity, LD_DIRSERV,
416 "Router %s has invalid address. Not adding (%s).",
417 router_describe(ri),
418 esc_router_info(ri));
419 *msg = "Rejected: Address is a private address.";
420 return -1;
423 *valid_out = ! (status & FP_INVALID);
425 return 0;
428 /** Update the relevant flags of <b>node</b> based on our opinion as a
429 * directory authority in <b>authstatus</b>, as returned by
430 * dirserv_router_get_status or equivalent. */
431 void
432 dirserv_set_node_flags_from_authoritative_status(node_t *node,
433 uint32_t authstatus)
435 node->is_valid = (authstatus & FP_INVALID) ? 0 : 1;
436 node->is_bad_exit = (authstatus & FP_BADEXIT) ? 1 : 0;
439 /** True iff <b>a</b> is more severe than <b>b</b>. */
440 static int
441 WRA_MORE_SEVERE(was_router_added_t a, was_router_added_t b)
443 return a < b;
446 /** As for dirserv_add_descriptor(), but accepts multiple documents, and
447 * returns the most severe error that occurred for any one of them. */
448 was_router_added_t
449 dirserv_add_multiple_descriptors(const char *desc, uint8_t purpose,
450 const char *source,
451 const char **msg)
453 was_router_added_t r, r_tmp;
454 const char *msg_out;
455 smartlist_t *list;
456 const char *s;
457 int n_parsed = 0;
458 time_t now = time(NULL);
459 char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
460 char time_buf[ISO_TIME_LEN+1];
461 int general = purpose == ROUTER_PURPOSE_GENERAL;
462 tor_assert(msg);
464 r=ROUTER_ADDED_SUCCESSFULLY; /*Least severe return value. */
466 format_iso_time(time_buf, now);
467 if (tor_snprintf(annotation_buf, sizeof(annotation_buf),
468 "@uploaded-at %s\n"
469 "@source %s\n"
470 "%s%s%s", time_buf, escaped(source),
471 !general ? "@purpose " : "",
472 !general ? router_purpose_to_string(purpose) : "",
473 !general ? "\n" : "")<0) {
474 *msg = "Couldn't format annotations";
475 return -1;
478 s = desc;
479 list = smartlist_new();
480 if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 0, 0,
481 annotation_buf, NULL)) {
482 SMARTLIST_FOREACH(list, routerinfo_t *, ri, {
483 msg_out = NULL;
484 tor_assert(ri->purpose == purpose);
485 r_tmp = dirserv_add_descriptor(ri, &msg_out, source);
486 if (WRA_MORE_SEVERE(r_tmp, r)) {
487 r = r_tmp;
488 *msg = msg_out;
492 n_parsed += smartlist_len(list);
493 smartlist_clear(list);
495 s = desc;
496 if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 1, 0,
497 NULL, NULL)) {
498 SMARTLIST_FOREACH(list, extrainfo_t *, ei, {
499 msg_out = NULL;
501 r_tmp = dirserv_add_extrainfo(ei, &msg_out);
502 if (WRA_MORE_SEVERE(r_tmp, r)) {
503 r = r_tmp;
504 *msg = msg_out;
508 n_parsed += smartlist_len(list);
509 smartlist_free(list);
511 if (! *msg) {
512 if (!n_parsed) {
513 *msg = "No descriptors found in your POST.";
514 if (WRA_WAS_ADDED(r))
515 r = ROUTER_IS_ALREADY_KNOWN;
516 } else {
517 *msg = "(no message)";
521 return r;
524 /** Examine the parsed server descriptor in <b>ri</b> and maybe insert it into
525 * the list of server descriptors. Set *<b>msg</b> to a message that should be
526 * passed back to the origin of this descriptor, or NULL if there is no such
527 * message. Use <b>source</b> to produce better log messages.
529 * Return the status of the operation
531 * This function is only called when fresh descriptors are posted, not when
532 * we re-load the cache.
534 was_router_added_t
535 dirserv_add_descriptor(routerinfo_t *ri, const char **msg, const char *source)
537 was_router_added_t r;
538 routerinfo_t *ri_old;
539 char *desc, *nickname;
540 size_t desclen = 0;
541 *msg = NULL;
543 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
544 * network and it'll clog everything up. */
545 if (ri->cache_info.signed_descriptor_len > MAX_DESCRIPTOR_UPLOAD_SIZE) {
546 log_notice(LD_DIR, "Somebody attempted to publish a router descriptor '%s'"
547 " (source: %s) with size %d. Either this is an attack, or the "
548 "MAX_DESCRIPTOR_UPLOAD_SIZE (%d) constant is too low.",
549 ri->nickname, source, (int)ri->cache_info.signed_descriptor_len,
550 MAX_DESCRIPTOR_UPLOAD_SIZE);
551 *msg = "Router descriptor was too large.";
552 control_event_or_authdir_new_descriptor("REJECTED",
553 ri->cache_info.signed_descriptor_body,
554 ri->cache_info.signed_descriptor_len, *msg);
555 routerinfo_free(ri);
556 return ROUTER_AUTHDIR_REJECTS;
559 /* Check whether this descriptor is semantically identical to the last one
560 * from this server. (We do this here and not in router_add_to_routerlist
561 * because we want to be able to accept the newest router descriptor that
562 * another authority has, so we all converge on the same one.) */
563 ri_old = router_get_mutable_by_digest(ri->cache_info.identity_digest);
564 if (ri_old && ri_old->cache_info.published_on < ri->cache_info.published_on
565 && router_differences_are_cosmetic(ri_old, ri)
566 && !router_is_me(ri)) {
567 log_info(LD_DIRSERV,
568 "Not replacing descriptor from %s (source: %s); "
569 "differences are cosmetic.",
570 router_describe(ri), source);
571 *msg = "Not replacing router descriptor; no information has changed since "
572 "the last one with this identity.";
573 control_event_or_authdir_new_descriptor("DROPPED",
574 ri->cache_info.signed_descriptor_body,
575 ri->cache_info.signed_descriptor_len, *msg);
576 routerinfo_free(ri);
577 return ROUTER_IS_ALREADY_KNOWN;
580 /* Make a copy of desc, since router_add_to_routerlist might free
581 * ri and its associated signed_descriptor_t. */
582 desclen = ri->cache_info.signed_descriptor_len;
583 desc = tor_strndup(ri->cache_info.signed_descriptor_body, desclen);
584 nickname = tor_strdup(ri->nickname);
586 /* Tell if we're about to need to launch a test if we add this. */
587 ri->needs_retest_if_added =
588 dirserv_should_launch_reachability_test(ri, ri_old);
590 r = router_add_to_routerlist(ri, msg, 0, 0);
591 if (!WRA_WAS_ADDED(r)) {
592 /* unless the routerinfo was fine, just out-of-date */
593 if (WRA_WAS_REJECTED(r))
594 control_event_or_authdir_new_descriptor("REJECTED", desc, desclen, *msg);
595 log_info(LD_DIRSERV,
596 "Did not add descriptor from '%s' (source: %s): %s.",
597 nickname, source, *msg ? *msg : "(no message)");
598 } else {
599 smartlist_t *changed;
600 control_event_or_authdir_new_descriptor("ACCEPTED", desc, desclen, *msg);
602 changed = smartlist_new();
603 smartlist_add(changed, ri);
604 routerlist_descriptors_added(changed, 0);
605 smartlist_free(changed);
606 if (!*msg) {
607 *msg = "Descriptor accepted";
609 log_info(LD_DIRSERV,
610 "Added descriptor from '%s' (source: %s): %s.",
611 nickname, source, *msg);
613 tor_free(desc);
614 tor_free(nickname);
615 return r;
618 /** As dirserv_add_descriptor, but for an extrainfo_t <b>ei</b>. */
619 static was_router_added_t
620 dirserv_add_extrainfo(extrainfo_t *ei, const char **msg)
622 const routerinfo_t *ri;
623 int r;
624 tor_assert(msg);
625 *msg = NULL;
627 ri = router_get_by_id_digest(ei->cache_info.identity_digest);
628 if (!ri) {
629 *msg = "No corresponding router descriptor for extra-info descriptor";
630 extrainfo_free(ei);
631 return ROUTER_BAD_EI;
634 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
635 * network and it'll clog everything up. */
636 if (ei->cache_info.signed_descriptor_len > MAX_EXTRAINFO_UPLOAD_SIZE) {
637 log_notice(LD_DIR, "Somebody attempted to publish an extrainfo "
638 "with size %d. Either this is an attack, or the "
639 "MAX_EXTRAINFO_UPLOAD_SIZE (%d) constant is too low.",
640 (int)ei->cache_info.signed_descriptor_len,
641 MAX_EXTRAINFO_UPLOAD_SIZE);
642 *msg = "Extrainfo document was too large";
643 extrainfo_free(ei);
644 return ROUTER_BAD_EI;
647 if ((r = routerinfo_incompatible_with_extrainfo(ri, ei, NULL, msg))) {
648 extrainfo_free(ei);
649 return r < 0 ? ROUTER_IS_ALREADY_KNOWN : ROUTER_BAD_EI;
651 router_add_extrainfo_to_routerlist(ei, msg, 0, 0);
652 return ROUTER_ADDED_SUCCESSFULLY;
655 /** Remove all descriptors whose nicknames or fingerprints no longer
656 * are allowed by our fingerprint list. (Descriptors that used to be
657 * good can become bad when we reload the fingerprint list.)
659 static void
660 directory_remove_invalid(void)
662 routerlist_t *rl = router_get_routerlist();
663 smartlist_t *nodes = smartlist_new();
664 smartlist_add_all(nodes, nodelist_get_list());
666 SMARTLIST_FOREACH_BEGIN(nodes, node_t *, node) {
667 const char *msg = NULL;
668 routerinfo_t *ent = node->ri;
669 char description[NODE_DESC_BUF_LEN];
670 uint32_t r;
671 if (!ent)
672 continue;
673 r = dirserv_router_get_status(ent, &msg);
674 router_get_description(description, ent);
675 if (r & FP_REJECT) {
676 log_info(LD_DIRSERV, "Router %s is now rejected: %s",
677 description, msg?msg:"");
678 routerlist_remove(rl, ent, 0, time(NULL));
679 continue;
681 if (bool_neq((r & FP_INVALID), !node->is_valid)) {
682 log_info(LD_DIRSERV, "Router '%s' is now %svalid.", description,
683 (r&FP_INVALID) ? "in" : "");
684 node->is_valid = (r&FP_INVALID)?0:1;
686 if (bool_neq((r & FP_BADEXIT), node->is_bad_exit)) {
687 log_info(LD_DIRSERV, "Router '%s' is now a %s exit", description,
688 (r & FP_BADEXIT) ? "bad" : "good");
689 node->is_bad_exit = (r&FP_BADEXIT) ? 1: 0;
691 } SMARTLIST_FOREACH_END(node);
693 routerlist_assert_ok(rl);
694 smartlist_free(nodes);
698 * Allocate and return a description of the status of the server <b>desc</b>,
699 * for use in a v1-style router-status line. The server is listed
700 * as running iff <b>is_live</b> is true.
702 static char *
703 list_single_server_status(const routerinfo_t *desc, int is_live)
705 char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
706 char *cp;
707 const node_t *node;
709 tor_assert(desc);
711 cp = buf;
712 if (!is_live) {
713 *cp++ = '!';
715 node = node_get_by_id(desc->cache_info.identity_digest);
716 if (node && node->is_valid) {
717 strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
718 cp += strlen(cp);
719 *cp++ = '=';
721 *cp++ = '$';
722 base16_encode(cp, HEX_DIGEST_LEN+1, desc->cache_info.identity_digest,
723 DIGEST_LEN);
724 return tor_strdup(buf);
727 /* DOCDOC running_long_enough_to_decide_unreachable */
728 static INLINE int
729 running_long_enough_to_decide_unreachable(void)
731 return time_of_process_start
732 + get_options()->TestingAuthDirTimeToLearnReachability < approx_time();
735 /** Each server needs to have passed a reachability test no more
736 * than this number of seconds ago, or it is listed as down in
737 * the directory. */
738 #define REACHABLE_TIMEOUT (45*60)
740 /** If we tested a router and found it reachable _at least this long_ after it
741 * declared itself hibernating, it is probably done hibernating and we just
742 * missed a descriptor from it. */
743 #define HIBERNATION_PUBLICATION_SKEW (60*60)
745 /** Treat a router as alive if
746 * - It's me, and I'm not hibernating.
747 * or - We've found it reachable recently. */
748 void
749 dirserv_set_router_is_running(routerinfo_t *router, time_t now)
751 /*XXXX024 This function is a mess. Separate out the part that calculates
752 whether it's reachable and the part that tells rephist that the router was
753 unreachable.
755 int answer;
756 const or_options_t *options = get_options();
757 node_t *node = node_get_mutable_by_id(router->cache_info.identity_digest);
758 tor_assert(node);
760 if (router_is_me(router)) {
761 /* We always know if we are down ourselves. */
762 answer = ! we_are_hibernating();
763 } else if (router->is_hibernating &&
764 (router->cache_info.published_on +
765 HIBERNATION_PUBLICATION_SKEW) > node->last_reachable) {
766 /* A hibernating router is down unless we (somehow) had contact with it
767 * since it declared itself to be hibernating. */
768 answer = 0;
769 } else if (options->AssumeReachable) {
770 /* If AssumeReachable, everybody is up unless they say they are down! */
771 answer = 1;
772 } else {
773 /* Otherwise, a router counts as up if we found all announced OR
774 ports reachable in the last REACHABLE_TIMEOUT seconds.
776 XXX prop186 For now there's always one IPv4 and at most one
777 IPv6 OR port.
779 If we're not on IPv6, don't consider reachability of potential
780 IPv6 OR port since that'd kill all dual stack relays until a
781 majority of the dir auths have IPv6 connectivity. */
782 answer = (now < node->last_reachable + REACHABLE_TIMEOUT &&
783 (options->AuthDirHasIPv6Connectivity != 1 ||
784 tor_addr_is_null(&router->ipv6_addr) ||
785 now < node->last_reachable6 + REACHABLE_TIMEOUT));
788 if (!answer && running_long_enough_to_decide_unreachable()) {
789 /* Not considered reachable. tell rephist about that.
791 Because we launch a reachability test for each router every
792 REACHABILITY_TEST_CYCLE_PERIOD seconds, then the router has probably
793 been down since at least that time after we last successfully reached
796 XXX ipv6
798 time_t when = now;
799 if (node->last_reachable &&
800 node->last_reachable + REACHABILITY_TEST_CYCLE_PERIOD < now)
801 when = node->last_reachable + REACHABILITY_TEST_CYCLE_PERIOD;
802 rep_hist_note_router_unreachable(router->cache_info.identity_digest, when);
805 node->is_running = answer;
808 /** Based on the routerinfo_ts in <b>routers</b>, allocate the
809 * contents of a v1-style router-status line, and store it in
810 * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
812 * If for_controller is true, include the routers with very old descriptors.
815 list_server_status_v1(smartlist_t *routers, char **router_status_out,
816 int for_controller)
818 /* List of entries in a router-status style: An optional !, then an optional
819 * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
820 smartlist_t *rs_entries;
821 time_t now = time(NULL);
822 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
823 const or_options_t *options = get_options();
824 /* We include v2 dir auths here too, because they need to answer
825 * controllers. Eventually we'll deprecate this whole function;
826 * see also networkstatus_getinfo_by_purpose(). */
827 int authdir = authdir_mode_publishes_statuses(options);
828 tor_assert(router_status_out);
830 rs_entries = smartlist_new();
832 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
833 const node_t *node = node_get_by_id(ri->cache_info.identity_digest);
834 tor_assert(node);
835 if (authdir) {
836 /* Update router status in routerinfo_t. */
837 dirserv_set_router_is_running(ri, now);
839 if (for_controller) {
840 char name_buf[MAX_VERBOSE_NICKNAME_LEN+2];
841 char *cp = name_buf;
842 if (!node->is_running)
843 *cp++ = '!';
844 router_get_verbose_nickname(cp, ri);
845 smartlist_add(rs_entries, tor_strdup(name_buf));
846 } else if (ri->cache_info.published_on >= cutoff) {
847 smartlist_add(rs_entries, list_single_server_status(ri,
848 node->is_running));
850 } SMARTLIST_FOREACH_END(ri);
852 *router_status_out = smartlist_join_strings(rs_entries, " ", 0, NULL);
854 SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
855 smartlist_free(rs_entries);
857 return 0;
860 /** Given a (possibly empty) list of config_line_t, each line of which contains
861 * a list of comma-separated version numbers surrounded by optional space,
862 * allocate and return a new string containing the version numbers, in order,
863 * separated by commas. Used to generate Recommended(Client|Server)?Versions
865 static char *
866 format_versions_list(config_line_t *ln)
868 smartlist_t *versions;
869 char *result;
870 versions = smartlist_new();
871 for ( ; ln; ln = ln->next) {
872 smartlist_split_string(versions, ln->value, ",",
873 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
875 sort_version_list(versions, 1);
876 result = smartlist_join_strings(versions,",",0,NULL);
877 SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
878 smartlist_free(versions);
879 return result;
882 /** Return 1 if <b>ri</b>'s descriptor is "active" -- running, valid,
883 * not hibernating, having observed bw greater 0, and not too old. Else
884 * return 0.
886 static int
887 router_is_active(const routerinfo_t *ri, const node_t *node, time_t now)
889 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
890 if (ri->cache_info.published_on < cutoff) {
891 return 0;
893 if (!node->is_running || !node->is_valid || ri->is_hibernating) {
894 return 0;
896 /* Only require bandwith capacity in non-test networks, or
897 * if TestingTorNetwork, and TestingMinExitFlagThreshold is non-zero */
898 if (!ri->bandwidthcapacity) {
899 if (get_options()->TestingTorNetwork) {
900 if (get_options()->TestingMinExitFlagThreshold > 0) {
901 /* If we're in a TestingTorNetwork, and TestingMinExitFlagThreshold is,
902 * then require bandwidthcapacity */
903 return 0;
905 } else {
906 /* If we're not in a TestingTorNetwork, then require bandwidthcapacity */
907 return 0;
910 return 1;
913 /** Generate a new v1 directory and write it into a newly allocated string.
914 * Point *<b>dir_out</b> to the allocated string. Sign the
915 * directory with <b>private_key</b>. Return 0 on success, -1 on
916 * failure. If <b>complete</b> is set, give us all the descriptors;
917 * otherwise leave out non-running and non-valid ones.
920 dirserv_dump_directory_to_string(char **dir_out,
921 crypto_pk_t *private_key)
923 /* XXXX 024 Get rid of this function if we can confirm that nobody's
924 * fetching these any longer */
925 char *cp;
926 char *identity_pkey; /* Identity key, DER64-encoded. */
927 char *recommended_versions;
928 char digest[DIGEST_LEN];
929 char published[ISO_TIME_LEN+1];
930 char *buf = NULL;
931 size_t buf_len;
932 size_t identity_pkey_len;
933 time_t now = time(NULL);
935 tor_assert(dir_out);
936 *dir_out = NULL;
938 if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
939 &identity_pkey_len)<0) {
940 log_warn(LD_BUG,"write identity_pkey to string failed!");
941 return -1;
944 recommended_versions =
945 format_versions_list(get_options()->RecommendedVersions);
947 format_iso_time(published, now);
949 buf_len = 2048+strlen(recommended_versions);
951 buf = tor_malloc(buf_len);
952 /* We'll be comparing against buf_len throughout the rest of the
953 function, though strictly speaking we shouldn't be able to exceed
954 it. This is C, after all, so we may as well check for buffer
955 overruns.*/
957 tor_snprintf(buf, buf_len,
958 "signed-directory\n"
959 "published %s\n"
960 "recommended-software %s\n"
961 "router-status %s\n"
962 "dir-signing-key\n%s\n",
963 published, recommended_versions, "",
964 identity_pkey);
966 tor_free(recommended_versions);
967 tor_free(identity_pkey);
969 cp = buf + strlen(buf);
970 *cp = '\0';
972 /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
973 signature. */
974 if (strlcat(buf, "directory-signature ", buf_len) >= buf_len)
975 goto truncated;
976 if (strlcat(buf, get_options()->Nickname, buf_len) >= buf_len)
977 goto truncated;
978 if (strlcat(buf, "\n", buf_len) >= buf_len)
979 goto truncated;
981 if (router_get_dir_hash(buf,digest)) {
982 log_warn(LD_BUG,"couldn't compute digest");
983 tor_free(buf);
984 return -1;
986 note_crypto_pk_op(SIGN_DIR);
987 if (router_append_dirobj_signature(buf,buf_len,digest,DIGEST_LEN,
988 private_key)<0) {
989 tor_free(buf);
990 return -1;
993 *dir_out = buf;
994 return 0;
995 truncated:
996 log_warn(LD_BUG,"tried to exceed string length.");
997 tor_free(buf);
998 return -1;
1001 /********************************************************************/
1003 /* A set of functions to answer questions about how we'd like to behave
1004 * as a directory mirror/client. */
1006 /** Return 1 if we fetch our directory material directly from the
1007 * authorities, rather than from a mirror. */
1009 directory_fetches_from_authorities(const or_options_t *options)
1011 const routerinfo_t *me;
1012 uint32_t addr;
1013 int refuseunknown;
1014 if (options->FetchDirInfoEarly)
1015 return 1;
1016 if (options->BridgeRelay == 1)
1017 return 0;
1018 if (server_mode(options) && router_pick_published_address(options, &addr)<0)
1019 return 1; /* we don't know our IP address; ask an authority. */
1020 refuseunknown = ! router_my_exit_policy_is_reject_star() &&
1021 should_refuse_unknown_exits(options);
1022 if (!options->DirPort_set && !refuseunknown)
1023 return 0;
1024 if (!server_mode(options) || !advertised_server_mode())
1025 return 0;
1026 me = router_get_my_routerinfo();
1027 if (!me || (!me->dir_port && !refuseunknown))
1028 return 0; /* if dirport not advertised, return 0 too */
1029 return 1;
1032 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1033 * on the "mirror" schedule rather than the "client" schedule.
1036 directory_fetches_dir_info_early(const or_options_t *options)
1038 return directory_fetches_from_authorities(options);
1041 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1042 * on a very passive schedule -- waiting long enough for ordinary clients
1043 * to probably have the info we want. These would include bridge users,
1044 * and maybe others in the future e.g. if a Tor client uses another Tor
1045 * client as a directory guard.
1048 directory_fetches_dir_info_later(const or_options_t *options)
1050 return options->UseBridges != 0;
1053 /** Return true iff we want to fetch and keep certificates for authorities
1054 * that we don't acknowledge as authorities ourself.
1057 directory_caches_unknown_auth_certs(const or_options_t *options)
1059 return options->DirPort_set || options->BridgeRelay;
1062 /** Return 1 if we want to keep descriptors, networkstatuses, etc around
1063 * and we're willing to serve them to others. Else return 0.
1066 directory_caches_dir_info(const or_options_t *options)
1068 if (options->BridgeRelay || options->DirPort_set)
1069 return 1;
1070 if (!server_mode(options) || !advertised_server_mode())
1071 return 0;
1072 /* We need an up-to-date view of network info if we're going to try to
1073 * block exit attempts from unknown relays. */
1074 return ! router_my_exit_policy_is_reject_star() &&
1075 should_refuse_unknown_exits(options);
1078 /** Return 1 if we want to allow remote people to ask us directory
1079 * requests via the "begin_dir" interface, which doesn't require
1080 * having any separate port open. */
1082 directory_permits_begindir_requests(const or_options_t *options)
1084 return options->BridgeRelay != 0 || options->DirPort_set;
1087 /** Return 1 if we have no need to fetch new descriptors. This generally
1088 * happens when we're not a dir cache and we haven't built any circuits
1089 * lately.
1092 directory_too_idle_to_fetch_descriptors(const or_options_t *options,
1093 time_t now)
1095 return !directory_caches_dir_info(options) &&
1096 !options->FetchUselessDescriptors &&
1097 rep_hist_circbuilding_dormant(now);
1100 /********************************************************************/
1102 /** Map from flavor name to the cached_dir_t for the v3 consensuses that we're
1103 * currently serving. */
1104 static strmap_t *cached_consensuses = NULL;
1106 /** Decrement the reference count on <b>d</b>, and free it if it no longer has
1107 * any references. */
1108 void
1109 cached_dir_decref(cached_dir_t *d)
1111 if (!d || --d->refcnt > 0)
1112 return;
1113 clear_cached_dir(d);
1114 tor_free(d);
1117 /** Allocate and return a new cached_dir_t containing the string <b>s</b>,
1118 * published at <b>published</b>. */
1119 cached_dir_t *
1120 new_cached_dir(char *s, time_t published)
1122 cached_dir_t *d = tor_malloc_zero(sizeof(cached_dir_t));
1123 d->refcnt = 1;
1124 d->dir = s;
1125 d->dir_len = strlen(s);
1126 d->published = published;
1127 if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
1128 ZLIB_METHOD)) {
1129 log_warn(LD_BUG, "Error compressing directory");
1131 return d;
1134 /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
1135 static void
1136 clear_cached_dir(cached_dir_t *d)
1138 tor_free(d->dir);
1139 tor_free(d->dir_z);
1140 memset(d, 0, sizeof(cached_dir_t));
1143 /** Free all storage held by the cached_dir_t in <b>d</b>. */
1144 static void
1145 free_cached_dir_(void *_d)
1147 cached_dir_t *d;
1148 if (!_d)
1149 return;
1151 d = (cached_dir_t *)_d;
1152 cached_dir_decref(d);
1155 /** Replace the v3 consensus networkstatus of type <b>flavor_name</b> that
1156 * we're serving with <b>networkstatus</b>, published at <b>published</b>. No
1157 * validation is performed. */
1158 void
1159 dirserv_set_cached_consensus_networkstatus(const char *networkstatus,
1160 const char *flavor_name,
1161 const digests_t *digests,
1162 time_t published)
1164 cached_dir_t *new_networkstatus;
1165 cached_dir_t *old_networkstatus;
1166 if (!cached_consensuses)
1167 cached_consensuses = strmap_new();
1169 new_networkstatus = new_cached_dir(tor_strdup(networkstatus), published);
1170 memcpy(&new_networkstatus->digests, digests, sizeof(digests_t));
1171 old_networkstatus = strmap_set(cached_consensuses, flavor_name,
1172 new_networkstatus);
1173 if (old_networkstatus)
1174 cached_dir_decref(old_networkstatus);
1177 /** Return the latest downloaded consensus networkstatus in encoded, signed,
1178 * optionally compressed format, suitable for sending to clients. */
1179 cached_dir_t *
1180 dirserv_get_consensus(const char *flavor_name)
1182 if (!cached_consensuses)
1183 return NULL;
1184 return strmap_get(cached_consensuses, flavor_name);
1187 /** If a router's uptime is at least this value, then it is always
1188 * considered stable, regardless of the rest of the network. This
1189 * way we resist attacks where an attacker doubles the size of the
1190 * network using allegedly high-uptime nodes, displacing all the
1191 * current guards. */
1192 #define UPTIME_TO_GUARANTEE_STABLE (3600*24*30)
1193 /** If a router's MTBF is at least this value, then it is always stable.
1194 * See above. (Corresponds to about 7 days for current decay rates.) */
1195 #define MTBF_TO_GUARANTEE_STABLE (60*60*24*5)
1196 /** Similarly, every node with at least this much weighted time known can be
1197 * considered familiar enough to be a guard. Corresponds to about 20 days for
1198 * current decay rates.
1200 #define TIME_KNOWN_TO_GUARANTEE_FAMILIAR (8*24*60*60)
1201 /** Similarly, every node with sufficient WFU is around enough to be a guard.
1203 #define WFU_TO_GUARANTEE_GUARD (0.98)
1205 /* Thresholds for server performance: set by
1206 * dirserv_compute_performance_thresholds, and used by
1207 * generate_v2_networkstatus */
1209 /** Any router with an uptime of at least this value is stable. */
1210 static uint32_t stable_uptime = 0; /* start at a safe value */
1211 /** Any router with an mtbf of at least this value is stable. */
1212 static double stable_mtbf = 0.0;
1213 /** If true, we have measured enough mtbf info to look at stable_mtbf rather
1214 * than stable_uptime. */
1215 static int enough_mtbf_info = 0;
1216 /** Any router with a weighted fractional uptime of at least this much might
1217 * be good as a guard. */
1218 static double guard_wfu = 0.0;
1219 /** Don't call a router a guard unless we've known about it for at least this
1220 * many seconds. */
1221 static long guard_tk = 0;
1222 /** Any router with a bandwidth at least this high is "Fast" */
1223 static uint32_t fast_bandwidth_kb = 0;
1224 /** If exits can be guards, then all guards must have a bandwidth this
1225 * high. */
1226 static uint32_t guard_bandwidth_including_exits_kb = 0;
1227 /** If exits can't be guards, then all guards must have a bandwidth this
1228 * high. */
1229 static uint32_t guard_bandwidth_excluding_exits_kb = 0;
1231 /** Helper: estimate the uptime of a router given its stated uptime and the
1232 * amount of time since it last stated its stated uptime. */
1233 static INLINE long
1234 real_uptime(const routerinfo_t *router, time_t now)
1236 if (now < router->cache_info.published_on)
1237 return router->uptime;
1238 else
1239 return router->uptime + (now - router->cache_info.published_on);
1242 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1243 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1244 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1245 * bandwidth.
1247 static int
1248 dirserv_thinks_router_is_unreliable(time_t now,
1249 routerinfo_t *router,
1250 int need_uptime, int need_capacity)
1252 if (need_uptime) {
1253 if (!enough_mtbf_info) {
1254 /* XXX024 Once most authorities are on v3, we should change the rule from
1255 * "use uptime if we don't have mtbf data" to "don't advertise Stable on
1256 * v3 if we don't have enough mtbf data." Or maybe not, since if we ever
1257 * hit a point where we need to reset a lot of authorities at once,
1258 * none of them would be in a position to declare Stable.
1260 long uptime = real_uptime(router, now);
1261 if ((unsigned)uptime < stable_uptime &&
1262 (unsigned)uptime < UPTIME_TO_GUARANTEE_STABLE)
1263 return 1;
1264 } else {
1265 double mtbf =
1266 rep_hist_get_stability(router->cache_info.identity_digest, now);
1267 if (mtbf < stable_mtbf &&
1268 mtbf < MTBF_TO_GUARANTEE_STABLE)
1269 return 1;
1272 if (need_capacity) {
1273 uint32_t bw_kb = dirserv_get_credible_bandwidth_kb(router);
1274 if (bw_kb < fast_bandwidth_kb)
1275 return 1;
1277 return 0;
1280 /** Return true iff <b>router</b> should be assigned the "HSDir" flag.
1281 * Right now this means it advertises support for it, it has a high
1282 * uptime, it has a DirPort open, and it's currently considered Running.
1284 * This function needs to be called after router-\>is_running has
1285 * been set.
1287 static int
1288 dirserv_thinks_router_is_hs_dir(const routerinfo_t *router,
1289 const node_t *node, time_t now)
1292 long uptime;
1294 /* If we haven't been running for at least
1295 * get_options()->MinUptimeHidServDirectoryV2 seconds, we can't
1296 * have accurate data telling us a relay has been up for at least
1297 * that long. We also want to allow a bit of slack: Reachability
1298 * tests aren't instant. If we haven't been running long enough,
1299 * trust the relay. */
1301 if (stats_n_seconds_working >
1302 get_options()->MinUptimeHidServDirectoryV2 * 1.1)
1303 uptime = MIN(rep_hist_get_uptime(router->cache_info.identity_digest, now),
1304 real_uptime(router, now));
1305 else
1306 uptime = real_uptime(router, now);
1308 /* XXX We shouldn't need to check dir_port, but we do because of
1309 * bug 1693. In the future, once relays set wants_to_be_hs_dir
1310 * correctly, we can revert to only checking dir_port if router's
1311 * version is too old. */
1312 /* XXX Unfortunately, we need to keep checking dir_port until all
1313 * *clients* suffering from bug 2722 are obsolete. The first version
1314 * to fix the bug was 0.2.2.25-alpha. */
1315 return (router->wants_to_be_hs_dir && router->dir_port &&
1316 uptime >= get_options()->MinUptimeHidServDirectoryV2 &&
1317 router_is_active(router, node, now));
1320 /** Don't consider routers with less bandwidth than this when computing
1321 * thresholds. */
1322 #define ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER_KB 4
1324 /** Helper for dirserv_compute_performance_thresholds(): Decide whether to
1325 * include a router in our calculations, and return true iff we should; the
1326 * require_mbw parameter is passed in by
1327 * dirserv_compute_performance_thresholds() and controls whether we ever
1328 * count routers with only advertised bandwidths */
1329 static int
1330 router_counts_toward_thresholds(const node_t *node, time_t now,
1331 const digestmap_t *omit_as_sybil,
1332 int require_mbw)
1334 /* Have measured bw? */
1335 int have_mbw =
1336 dirserv_has_measured_bw(node->identity);
1337 uint64_t min_bw_kb = ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER_KB;
1338 const or_options_t *options = get_options();
1340 if (options->TestingTorNetwork) {
1341 min_bw_kb = (int64_t)options->TestingMinExitFlagThreshold / 1000;
1344 return node->ri && router_is_active(node->ri, node, now) &&
1345 !digestmap_get(omit_as_sybil, node->identity) &&
1346 (dirserv_get_credible_bandwidth_kb(node->ri) >= min_bw_kb) &&
1347 (have_mbw || !require_mbw);
1350 /** Look through the routerlist, the Mean Time Between Failure history, and
1351 * the Weighted Fractional Uptime history, and use them to set thresholds for
1352 * the Stable, Fast, and Guard flags. Update the fields stable_uptime,
1353 * stable_mtbf, enough_mtbf_info, guard_wfu, guard_tk, fast_bandwidth,
1354 * guard_bandwidth_including_exits, and guard_bandwidth_excluding_exits.
1356 * Also, set the is_exit flag of each router appropriately. */
1357 static void
1358 dirserv_compute_performance_thresholds(routerlist_t *rl,
1359 digestmap_t *omit_as_sybil)
1361 int n_active, n_active_nonexit, n_familiar;
1362 uint32_t *uptimes, *bandwidths_kb, *bandwidths_excluding_exits_kb;
1363 long *tks;
1364 double *mtbfs, *wfus;
1365 time_t now = time(NULL);
1366 const or_options_t *options = get_options();
1368 /* Require mbw? */
1369 int require_mbw =
1370 (routers_with_measured_bw >
1371 options->MinMeasuredBWsForAuthToIgnoreAdvertised) ? 1 : 0;
1373 /* initialize these all here, in case there are no routers */
1374 stable_uptime = 0;
1375 stable_mtbf = 0;
1376 fast_bandwidth_kb = 0;
1377 guard_bandwidth_including_exits_kb = 0;
1378 guard_bandwidth_excluding_exits_kb = 0;
1379 guard_tk = 0;
1380 guard_wfu = 0;
1382 /* Initialize arrays that will hold values for each router. We'll
1383 * sort them and use that to compute thresholds. */
1384 n_active = n_active_nonexit = 0;
1385 /* Uptime for every active router. */
1386 uptimes = tor_calloc(smartlist_len(rl->routers), sizeof(uint32_t));
1387 /* Bandwidth for every active router. */
1388 bandwidths_kb = tor_calloc(smartlist_len(rl->routers), sizeof(uint32_t));
1389 /* Bandwidth for every active non-exit router. */
1390 bandwidths_excluding_exits_kb =
1391 tor_calloc(smartlist_len(rl->routers), sizeof(uint32_t));
1392 /* Weighted mean time between failure for each active router. */
1393 mtbfs = tor_calloc(smartlist_len(rl->routers), sizeof(double));
1394 /* Time-known for each active router. */
1395 tks = tor_calloc(smartlist_len(rl->routers), sizeof(long));
1396 /* Weighted fractional uptime for each active router. */
1397 wfus = tor_calloc(smartlist_len(rl->routers), sizeof(double));
1399 nodelist_assert_ok();
1401 /* Now, fill in the arrays. */
1402 SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), node_t *, node) {
1403 if (options->BridgeAuthoritativeDir &&
1404 node->ri &&
1405 node->ri->purpose != ROUTER_PURPOSE_BRIDGE)
1406 continue;
1407 if (router_counts_toward_thresholds(node, now, omit_as_sybil,
1408 require_mbw)) {
1409 routerinfo_t *ri = node->ri;
1410 const char *id = node->identity;
1411 uint32_t bw_kb;
1412 /* resolve spurious clang shallow analysis null pointer errors */
1413 tor_assert(ri);
1414 node->is_exit = (!router_exit_policy_rejects_all(ri) &&
1415 exit_policy_is_general_exit(ri->exit_policy));
1416 uptimes[n_active] = (uint32_t)real_uptime(ri, now);
1417 mtbfs[n_active] = rep_hist_get_stability(id, now);
1418 tks [n_active] = rep_hist_get_weighted_time_known(id, now);
1419 bandwidths_kb[n_active] = bw_kb = dirserv_get_credible_bandwidth_kb(ri);
1420 if (!node->is_exit || node->is_bad_exit) {
1421 bandwidths_excluding_exits_kb[n_active_nonexit] = bw_kb;
1422 ++n_active_nonexit;
1424 ++n_active;
1426 } SMARTLIST_FOREACH_END(node);
1428 /* Now, compute thresholds. */
1429 if (n_active) {
1430 /* The median uptime is stable. */
1431 stable_uptime = median_uint32(uptimes, n_active);
1432 /* The median mtbf is stable, if we have enough mtbf info */
1433 stable_mtbf = median_double(mtbfs, n_active);
1434 /* The 12.5th percentile bandwidth is fast. */
1435 fast_bandwidth_kb = find_nth_uint32(bandwidths_kb, n_active, n_active/8);
1436 /* (Now bandwidths is sorted.) */
1437 if (fast_bandwidth_kb < ROUTER_REQUIRED_MIN_BANDWIDTH/(2 * 1000))
1438 fast_bandwidth_kb = bandwidths_kb[n_active/4];
1439 guard_bandwidth_including_exits_kb =
1440 third_quartile_uint32(bandwidths_kb, n_active);
1441 guard_tk = find_nth_long(tks, n_active, n_active/8);
1444 if (guard_tk > TIME_KNOWN_TO_GUARANTEE_FAMILIAR)
1445 guard_tk = TIME_KNOWN_TO_GUARANTEE_FAMILIAR;
1448 /* We can vote on a parameter for the minimum and maximum. */
1449 #define ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG 4
1450 int32_t min_fast_kb, max_fast_kb, min_fast, max_fast;
1451 min_fast = networkstatus_get_param(NULL, "FastFlagMinThreshold",
1452 ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG,
1453 ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG,
1454 INT32_MAX);
1455 if (options->TestingTorNetwork) {
1456 min_fast = (int32_t)options->TestingMinFastFlagThreshold;
1458 max_fast = networkstatus_get_param(NULL, "FastFlagMaxThreshold",
1459 INT32_MAX, min_fast, INT32_MAX);
1460 min_fast_kb = min_fast / 1000;
1461 max_fast_kb = max_fast / 1000;
1463 if (fast_bandwidth_kb < (uint32_t)min_fast_kb)
1464 fast_bandwidth_kb = min_fast_kb;
1465 if (fast_bandwidth_kb > (uint32_t)max_fast_kb)
1466 fast_bandwidth_kb = max_fast_kb;
1468 /* Protect sufficiently fast nodes from being pushed out of the set
1469 * of Fast nodes. */
1470 if (options->AuthDirFastGuarantee &&
1471 fast_bandwidth_kb > options->AuthDirFastGuarantee/1000)
1472 fast_bandwidth_kb = (uint32_t)options->AuthDirFastGuarantee/1000;
1474 /* Now that we have a time-known that 7/8 routers are known longer than,
1475 * fill wfus with the wfu of every such "familiar" router. */
1476 n_familiar = 0;
1478 SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), node_t *, node) {
1479 if (router_counts_toward_thresholds(node, now,
1480 omit_as_sybil, require_mbw)) {
1481 routerinfo_t *ri = node->ri;
1482 const char *id = ri->cache_info.identity_digest;
1483 long tk = rep_hist_get_weighted_time_known(id, now);
1484 if (tk < guard_tk)
1485 continue;
1486 wfus[n_familiar++] = rep_hist_get_weighted_fractional_uptime(id, now);
1488 } SMARTLIST_FOREACH_END(node);
1489 if (n_familiar)
1490 guard_wfu = median_double(wfus, n_familiar);
1491 if (guard_wfu > WFU_TO_GUARANTEE_GUARD)
1492 guard_wfu = WFU_TO_GUARANTEE_GUARD;
1494 enough_mtbf_info = rep_hist_have_measured_enough_stability();
1496 if (n_active_nonexit) {
1497 guard_bandwidth_excluding_exits_kb =
1498 find_nth_uint32(bandwidths_excluding_exits_kb,
1499 n_active_nonexit, n_active_nonexit*3/4);
1502 log_info(LD_DIRSERV,
1503 "Cutoffs: For Stable, %lu sec uptime, %lu sec MTBF. "
1504 "For Fast: %lu kilobytes/sec. "
1505 "For Guard: WFU %.03f%%, time-known %lu sec, "
1506 "and bandwidth %lu or %lu kilobytes/sec. "
1507 "We%s have enough stability data.",
1508 (unsigned long)stable_uptime,
1509 (unsigned long)stable_mtbf,
1510 (unsigned long)fast_bandwidth_kb,
1511 guard_wfu*100,
1512 (unsigned long)guard_tk,
1513 (unsigned long)guard_bandwidth_including_exits_kb,
1514 (unsigned long)guard_bandwidth_excluding_exits_kb,
1515 enough_mtbf_info ? "" : " don't");
1517 tor_free(uptimes);
1518 tor_free(mtbfs);
1519 tor_free(bandwidths_kb);
1520 tor_free(bandwidths_excluding_exits_kb);
1521 tor_free(tks);
1522 tor_free(wfus);
1525 /* Use dirserv_compute_performance_thresholds() to compute the thresholds
1526 * for the status flags, specifically for bridges.
1528 * This is only called by a Bridge Authority from
1529 * networkstatus_getinfo_by_purpose().
1531 void
1532 dirserv_compute_bridge_flag_thresholds(routerlist_t *rl)
1535 digestmap_t *omit_as_sybil = digestmap_new();
1536 dirserv_compute_performance_thresholds(rl, omit_as_sybil);
1537 digestmap_free(omit_as_sybil, NULL);
1540 /** Measured bandwidth cache entry */
1541 typedef struct mbw_cache_entry_s {
1542 long mbw_kb;
1543 time_t as_of;
1544 } mbw_cache_entry_t;
1546 /** Measured bandwidth cache - keys are identity_digests, values are
1547 * mbw_cache_entry_t *. */
1548 static digestmap_t *mbw_cache = NULL;
1550 /** Store a measured bandwidth cache entry when reading the measured
1551 * bandwidths file. */
1552 STATIC void
1553 dirserv_cache_measured_bw(const measured_bw_line_t *parsed_line,
1554 time_t as_of)
1556 mbw_cache_entry_t *e = NULL;
1558 tor_assert(parsed_line);
1560 /* Allocate a cache if we need */
1561 if (!mbw_cache) mbw_cache = digestmap_new();
1563 /* Check if we have an existing entry */
1564 e = digestmap_get(mbw_cache, parsed_line->node_id);
1565 /* If we do, we can re-use it */
1566 if (e) {
1567 /* Check that we really are newer, and update */
1568 if (as_of > e->as_of) {
1569 e->mbw_kb = parsed_line->bw_kb;
1570 e->as_of = as_of;
1572 } else {
1573 /* We'll have to insert a new entry */
1574 e = tor_malloc(sizeof(*e));
1575 e->mbw_kb = parsed_line->bw_kb;
1576 e->as_of = as_of;
1577 digestmap_set(mbw_cache, parsed_line->node_id, e);
1581 /** Clear and free the measured bandwidth cache */
1582 STATIC void
1583 dirserv_clear_measured_bw_cache(void)
1585 if (mbw_cache) {
1586 /* Free the map and all entries */
1587 digestmap_free(mbw_cache, tor_free_);
1588 mbw_cache = NULL;
1592 /** Scan the measured bandwidth cache and remove expired entries */
1593 STATIC void
1594 dirserv_expire_measured_bw_cache(time_t now)
1597 if (mbw_cache) {
1598 /* Iterate through the cache and check each entry */
1599 DIGESTMAP_FOREACH_MODIFY(mbw_cache, k, mbw_cache_entry_t *, e) {
1600 if (now > e->as_of + MAX_MEASUREMENT_AGE) {
1601 tor_free(e);
1602 MAP_DEL_CURRENT(k);
1604 } DIGESTMAP_FOREACH_END;
1606 /* Check if we cleared the whole thing and free if so */
1607 if (digestmap_size(mbw_cache) == 0) {
1608 digestmap_free(mbw_cache, tor_free_);
1609 mbw_cache = 0;
1614 /** Get the current size of the measured bandwidth cache */
1615 STATIC int
1616 dirserv_get_measured_bw_cache_size(void)
1618 if (mbw_cache) return digestmap_size(mbw_cache);
1619 else return 0;
1622 /** Query the cache by identity digest, return value indicates whether
1623 * we found it. The bw_out and as_of_out pointers receive the cached
1624 * bandwidth value and the time it was cached if not NULL. */
1625 STATIC int
1626 dirserv_query_measured_bw_cache_kb(const char *node_id, long *bw_kb_out,
1627 time_t *as_of_out)
1629 mbw_cache_entry_t *v = NULL;
1630 int rv = 0;
1632 if (mbw_cache && node_id) {
1633 v = digestmap_get(mbw_cache, node_id);
1634 if (v) {
1635 /* Found something */
1636 rv = 1;
1637 if (bw_kb_out) *bw_kb_out = v->mbw_kb;
1638 if (as_of_out) *as_of_out = v->as_of;
1642 return rv;
1645 /** Predicate wrapper for dirserv_query_measured_bw_cache() */
1646 STATIC int
1647 dirserv_has_measured_bw(const char *node_id)
1649 return dirserv_query_measured_bw_cache_kb(node_id, NULL, NULL);
1652 /** Get the best estimate of a router's bandwidth for dirauth purposes,
1653 * preferring measured to advertised values if available. */
1655 static uint32_t
1656 dirserv_get_bandwidth_for_router_kb(const routerinfo_t *ri)
1658 uint32_t bw_kb = 0;
1660 * Yeah, measured bandwidths in measured_bw_line_t are (implicitly
1661 * signed) longs and the ones router_get_advertised_bandwidth() returns
1662 * are uint32_t.
1664 long mbw_kb = 0;
1666 if (ri) {
1668 * * First try to see if we have a measured bandwidth; don't bother with
1669 * as_of_out here, on the theory that a stale measured bandwidth is still
1670 * better to trust than an advertised one.
1672 if (dirserv_query_measured_bw_cache_kb(ri->cache_info.identity_digest,
1673 &mbw_kb, NULL)) {
1674 /* Got one! */
1675 bw_kb = (uint32_t)mbw_kb;
1676 } else {
1677 /* If not, fall back to advertised */
1678 bw_kb = router_get_advertised_bandwidth(ri) / 1000;
1682 return bw_kb;
1685 /** Look through the routerlist, and using the measured bandwidth cache count
1686 * how many measured bandwidths we know. This is used to decide whether we
1687 * ever trust advertised bandwidths for purposes of assigning flags. */
1688 static void
1689 dirserv_count_measured_bws(routerlist_t *rl)
1691 /* Initialize this first */
1692 routers_with_measured_bw = 0;
1694 tor_assert(rl);
1695 tor_assert(rl->routers);
1697 /* Iterate over the routerlist and count measured bandwidths */
1698 SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) {
1699 /* Check if we know a measured bandwidth for this one */
1700 if (dirserv_has_measured_bw(ri->cache_info.identity_digest)) {
1701 ++routers_with_measured_bw;
1703 } SMARTLIST_FOREACH_END(ri);
1706 /** Return the bandwidth we believe for assigning flags; prefer measured
1707 * over advertised, and if we have above a threshold quantity of measured
1708 * bandwidths, we don't want to ever give flags to unmeasured routers, so
1709 * return 0. */
1710 static uint32_t
1711 dirserv_get_credible_bandwidth_kb(const routerinfo_t *ri)
1713 int threshold;
1714 uint32_t bw_kb = 0;
1715 long mbw_kb;
1717 tor_assert(ri);
1718 /* Check if we have a measured bandwidth, and check the threshold if not */
1719 if (!(dirserv_query_measured_bw_cache_kb(ri->cache_info.identity_digest,
1720 &mbw_kb, NULL))) {
1721 threshold = get_options()->MinMeasuredBWsForAuthToIgnoreAdvertised;
1722 if (routers_with_measured_bw > threshold) {
1723 /* Return zero for unmeasured bandwidth if we are above threshold */
1724 bw_kb = 0;
1725 } else {
1726 /* Return an advertised bandwidth otherwise */
1727 bw_kb = router_get_advertised_bandwidth_capped(ri) / 1000;
1729 } else {
1730 /* We have the measured bandwidth in mbw */
1731 bw_kb = (uint32_t)mbw_kb;
1734 return bw_kb;
1737 /** Give a statement of our current performance thresholds for inclusion
1738 * in a vote document. */
1739 char *
1740 dirserv_get_flag_thresholds_line(void)
1742 char *result=NULL;
1743 const int measured_threshold =
1744 get_options()->MinMeasuredBWsForAuthToIgnoreAdvertised;
1745 const int enough_measured_bw = routers_with_measured_bw > measured_threshold;
1747 tor_asprintf(&result,
1748 "stable-uptime=%lu stable-mtbf=%lu "
1749 "fast-speed=%lu "
1750 "guard-wfu=%.03f%% guard-tk=%lu "
1751 "guard-bw-inc-exits=%lu guard-bw-exc-exits=%lu "
1752 "enough-mtbf=%d ignoring-advertised-bws=%d",
1753 (unsigned long)stable_uptime,
1754 (unsigned long)stable_mtbf,
1755 (unsigned long)fast_bandwidth_kb*1000,
1756 guard_wfu*100,
1757 (unsigned long)guard_tk,
1758 (unsigned long)guard_bandwidth_including_exits_kb*1000,
1759 (unsigned long)guard_bandwidth_excluding_exits_kb*1000,
1760 enough_mtbf_info ? 1 : 0,
1761 enough_measured_bw ? 1 : 0);
1763 return result;
1766 /** Given a platform string as in a routerinfo_t (possibly null), return a
1767 * newly allocated version string for a networkstatus document, or NULL if the
1768 * platform doesn't give a Tor version. */
1769 static char *
1770 version_from_platform(const char *platform)
1772 if (platform && !strcmpstart(platform, "Tor ")) {
1773 const char *eos = find_whitespace(platform+4);
1774 if (eos && !strcmpstart(eos, " (r")) {
1775 /* XXXX Unify this logic with the other version extraction
1776 * logic in routerparse.c. */
1777 eos = find_whitespace(eos+1);
1779 if (eos) {
1780 return tor_strndup(platform, eos-platform);
1783 return NULL;
1786 /** Helper: write the router-status information in <b>rs</b> into a newly
1787 * allocated character buffer. Use the same format as in network-status
1788 * documents. If <b>version</b> is non-NULL, add a "v" line for the platform.
1789 * Return 0 on success, -1 on failure.
1791 * The format argument has one of the following values:
1792 * NS_V2 - Output an entry suitable for a V2 NS opinion document
1793 * NS_V3_CONSENSUS - Output the first portion of a V3 NS consensus entry
1794 * NS_V3_CONSENSUS_MICRODESC - Output the first portion of a V3 microdesc
1795 * consensus entry.
1796 * NS_V3_VOTE - Output a complete V3 NS vote. If <b>vrs</b> is present,
1797 * it contains additional information for the vote.
1798 * NS_CONTROL_PORT - Output a NS document for the control port
1800 char *
1801 routerstatus_format_entry(const routerstatus_t *rs, const char *version,
1802 routerstatus_format_type_t format,
1803 const vote_routerstatus_t *vrs)
1805 char *summary;
1806 char *result = NULL;
1808 char published[ISO_TIME_LEN+1];
1809 char identity64[BASE64_DIGEST_LEN+1];
1810 char digest64[BASE64_DIGEST_LEN+1];
1811 smartlist_t *chunks = smartlist_new();
1813 format_iso_time(published, rs->published_on);
1814 digest_to_base64(identity64, rs->identity_digest);
1815 digest_to_base64(digest64, rs->descriptor_digest);
1817 smartlist_add_asprintf(chunks,
1818 "r %s %s %s%s%s %s %d %d\n",
1819 rs->nickname,
1820 identity64,
1821 (format==NS_V3_CONSENSUS_MICRODESC)?"":digest64,
1822 (format==NS_V3_CONSENSUS_MICRODESC)?"":" ",
1823 published,
1824 fmt_addr32(rs->addr),
1825 (int)rs->or_port,
1826 (int)rs->dir_port);
1828 /* TODO: Maybe we want to pass in what we need to build the rest of
1829 * this here, instead of in the caller. Then we could use the
1830 * networkstatus_type_t values, with an additional control port value
1831 * added -MP */
1833 /* V3 microdesc consensuses don't have "a" lines. */
1834 if (format == NS_V3_CONSENSUS_MICRODESC)
1835 goto done;
1837 /* Possible "a" line. At most one for now. */
1838 if (!tor_addr_is_null(&rs->ipv6_addr)) {
1839 smartlist_add_asprintf(chunks, "a %s\n",
1840 fmt_addrport(&rs->ipv6_addr, rs->ipv6_orport));
1843 if (format == NS_V3_CONSENSUS)
1844 goto done;
1846 smartlist_add_asprintf(chunks,
1847 "s%s%s%s%s%s%s%s%s%s%s\n",
1848 /* These must stay in alphabetical order. */
1849 rs->is_authority?" Authority":"",
1850 rs->is_bad_exit?" BadExit":"",
1851 rs->is_exit?" Exit":"",
1852 rs->is_fast?" Fast":"",
1853 rs->is_possible_guard?" Guard":"",
1854 rs->is_hs_dir?" HSDir":"",
1855 rs->is_flagged_running?" Running":"",
1856 rs->is_stable?" Stable":"",
1857 (rs->dir_port!=0)?" V2Dir":"",
1858 rs->is_valid?" Valid":"");
1860 /* length of "opt v \n" */
1861 #define V_LINE_OVERHEAD 7
1862 if (version && strlen(version) < MAX_V_LINE_LEN - V_LINE_OVERHEAD) {
1863 smartlist_add_asprintf(chunks, "v %s\n", version);
1866 if (format != NS_V2) {
1867 const routerinfo_t* desc = router_get_by_id_digest(rs->identity_digest);
1868 uint32_t bw_kb;
1870 if (format != NS_CONTROL_PORT) {
1871 /* Blow up more or less nicely if we didn't get anything or not the
1872 * thing we expected.
1874 if (!desc) {
1875 char id[HEX_DIGEST_LEN+1];
1876 char dd[HEX_DIGEST_LEN+1];
1878 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
1879 base16_encode(dd, sizeof(dd), rs->descriptor_digest, DIGEST_LEN);
1880 log_warn(LD_BUG, "Cannot get any descriptor for %s "
1881 "(wanted descriptor %s).",
1882 id, dd);
1883 goto err;
1886 /* This assert could fire for the control port, because
1887 * it can request NS documents before all descriptors
1888 * have been fetched. Therefore, we only do this test when
1889 * format != NS_CONTROL_PORT. */
1890 if (tor_memneq(desc->cache_info.signed_descriptor_digest,
1891 rs->descriptor_digest,
1892 DIGEST_LEN)) {
1893 char rl_d[HEX_DIGEST_LEN+1];
1894 char rs_d[HEX_DIGEST_LEN+1];
1895 char id[HEX_DIGEST_LEN+1];
1897 base16_encode(rl_d, sizeof(rl_d),
1898 desc->cache_info.signed_descriptor_digest, DIGEST_LEN);
1899 base16_encode(rs_d, sizeof(rs_d), rs->descriptor_digest, DIGEST_LEN);
1900 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
1901 log_err(LD_BUG, "descriptor digest in routerlist does not match "
1902 "the one in routerstatus: %s vs %s "
1903 "(router %s)\n",
1904 rl_d, rs_d, id);
1906 tor_assert(tor_memeq(desc->cache_info.signed_descriptor_digest,
1907 rs->descriptor_digest,
1908 DIGEST_LEN));
1912 if (format == NS_CONTROL_PORT && rs->has_bandwidth) {
1913 bw_kb = rs->bandwidth_kb;
1914 } else {
1915 tor_assert(desc);
1916 bw_kb = router_get_advertised_bandwidth_capped(desc) / 1000;
1918 smartlist_add_asprintf(chunks,
1919 "w Bandwidth=%d", bw_kb);
1921 if (format == NS_V3_VOTE && vrs && vrs->has_measured_bw) {
1922 smartlist_add_asprintf(chunks,
1923 " Measured=%d", vrs->measured_bw_kb);
1925 smartlist_add(chunks, tor_strdup("\n"));
1927 if (desc) {
1928 summary = policy_summarize(desc->exit_policy, AF_INET);
1929 smartlist_add_asprintf(chunks, "p %s\n", summary);
1930 tor_free(summary);
1934 done:
1935 result = smartlist_join_strings(chunks, "", 0, NULL);
1937 err:
1938 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
1939 smartlist_free(chunks);
1941 return result;
1944 /** Helper for sorting: compares two routerinfos first by address, and then by
1945 * descending order of "usefulness". (An authority is more useful than a
1946 * non-authority; a running router is more useful than a non-running router;
1947 * and a router with more bandwidth is more useful than one with less.)
1949 static int
1950 compare_routerinfo_by_ip_and_bw_(const void **a, const void **b)
1952 routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
1953 int first_is_auth, second_is_auth;
1954 uint32_t bw_kb_first, bw_kb_second;
1955 const node_t *node_first, *node_second;
1956 int first_is_running, second_is_running;
1958 /* we return -1 if first should appear before second... that is,
1959 * if first is a better router. */
1960 if (first->addr < second->addr)
1961 return -1;
1962 else if (first->addr > second->addr)
1963 return 1;
1965 /* Potentially, this next bit could cause k n lg n memeq calls. But in
1966 * reality, we will almost never get here, since addresses will usually be
1967 * different. */
1969 first_is_auth =
1970 router_digest_is_trusted_dir(first->cache_info.identity_digest);
1971 second_is_auth =
1972 router_digest_is_trusted_dir(second->cache_info.identity_digest);
1974 if (first_is_auth && !second_is_auth)
1975 return -1;
1976 else if (!first_is_auth && second_is_auth)
1977 return 1;
1979 node_first = node_get_by_id(first->cache_info.identity_digest);
1980 node_second = node_get_by_id(second->cache_info.identity_digest);
1981 first_is_running = node_first && node_first->is_running;
1982 second_is_running = node_second && node_second->is_running;
1984 if (first_is_running && !second_is_running)
1985 return -1;
1986 else if (!first_is_running && second_is_running)
1987 return 1;
1989 bw_kb_first = dirserv_get_bandwidth_for_router_kb(first);
1990 bw_kb_second = dirserv_get_bandwidth_for_router_kb(second);
1992 if (bw_kb_first > bw_kb_second)
1993 return -1;
1994 else if (bw_kb_first < bw_kb_second)
1995 return 1;
1997 /* They're equal! Compare by identity digest, so there's a
1998 * deterministic order and we avoid flapping. */
1999 return fast_memcmp(first->cache_info.identity_digest,
2000 second->cache_info.identity_digest,
2001 DIGEST_LEN);
2004 /** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
2005 * whose keys are the identity digests of those routers that we're going to
2006 * exclude for Sybil-like appearance. */
2007 static digestmap_t *
2008 get_possible_sybil_list(const smartlist_t *routers)
2010 const or_options_t *options = get_options();
2011 digestmap_t *omit_as_sybil;
2012 smartlist_t *routers_by_ip = smartlist_new();
2013 uint32_t last_addr;
2014 int addr_count;
2015 /* Allow at most this number of Tor servers on a single IP address, ... */
2016 int max_with_same_addr = options->AuthDirMaxServersPerAddr;
2017 /* ... unless it's a directory authority, in which case allow more. */
2018 int max_with_same_addr_on_authority = options->AuthDirMaxServersPerAuthAddr;
2019 if (max_with_same_addr <= 0)
2020 max_with_same_addr = INT_MAX;
2021 if (max_with_same_addr_on_authority <= 0)
2022 max_with_same_addr_on_authority = INT_MAX;
2024 smartlist_add_all(routers_by_ip, routers);
2025 smartlist_sort(routers_by_ip, compare_routerinfo_by_ip_and_bw_);
2026 omit_as_sybil = digestmap_new();
2028 last_addr = 0;
2029 addr_count = 0;
2030 SMARTLIST_FOREACH_BEGIN(routers_by_ip, routerinfo_t *, ri) {
2031 if (last_addr != ri->addr) {
2032 last_addr = ri->addr;
2033 addr_count = 1;
2034 } else if (++addr_count > max_with_same_addr) {
2035 if (!router_addr_is_trusted_dir(ri->addr) ||
2036 addr_count > max_with_same_addr_on_authority)
2037 digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
2039 } SMARTLIST_FOREACH_END(ri);
2041 smartlist_free(routers_by_ip);
2042 return omit_as_sybil;
2045 /** Extract status information from <b>ri</b> and from other authority
2046 * functions and store it in <b>rs</b>>.
2048 * We assume that ri-\>is_running has already been set, e.g. by
2049 * dirserv_set_router_is_running(ri, now);
2051 void
2052 set_routerstatus_from_routerinfo(routerstatus_t *rs,
2053 node_t *node,
2054 routerinfo_t *ri,
2055 time_t now,
2056 int listbadexits,
2057 int vote_on_hsdirs)
2059 const or_options_t *options = get_options();
2060 uint32_t routerbw_kb = dirserv_get_credible_bandwidth_kb(ri);
2062 memset(rs, 0, sizeof(routerstatus_t));
2064 rs->is_authority =
2065 router_digest_is_trusted_dir(ri->cache_info.identity_digest);
2067 /* Already set by compute_performance_thresholds. */
2068 rs->is_exit = node->is_exit;
2069 rs->is_stable = node->is_stable =
2070 router_is_active(ri, node, now) &&
2071 !dirserv_thinks_router_is_unreliable(now, ri, 1, 0);
2072 rs->is_fast = node->is_fast =
2073 router_is_active(ri, node, now) &&
2074 !dirserv_thinks_router_is_unreliable(now, ri, 0, 1);
2075 rs->is_flagged_running = node->is_running; /* computed above */
2077 rs->is_valid = node->is_valid;
2079 if (node->is_fast &&
2080 ((options->AuthDirGuardBWGuarantee &&
2081 routerbw_kb >= options->AuthDirGuardBWGuarantee/1000) ||
2082 routerbw_kb >= MIN(guard_bandwidth_including_exits_kb,
2083 guard_bandwidth_excluding_exits_kb))) {
2084 long tk = rep_hist_get_weighted_time_known(
2085 node->identity, now);
2086 double wfu = rep_hist_get_weighted_fractional_uptime(
2087 node->identity, now);
2088 rs->is_possible_guard = (wfu >= guard_wfu && tk >= guard_tk) ? 1 : 0;
2089 } else {
2090 rs->is_possible_guard = 0;
2093 rs->is_bad_exit = listbadexits && node->is_bad_exit;
2094 node->is_hs_dir = dirserv_thinks_router_is_hs_dir(ri, node, now);
2095 rs->is_hs_dir = vote_on_hsdirs && node->is_hs_dir;
2097 rs->is_named = rs->is_unnamed = 0;
2099 rs->published_on = ri->cache_info.published_on;
2100 memcpy(rs->identity_digest, node->identity, DIGEST_LEN);
2101 memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest,
2102 DIGEST_LEN);
2103 rs->addr = ri->addr;
2104 strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname));
2105 rs->or_port = ri->or_port;
2106 rs->dir_port = ri->dir_port;
2107 if (options->AuthDirHasIPv6Connectivity == 1 &&
2108 !tor_addr_is_null(&ri->ipv6_addr) &&
2109 node->last_reachable6 >= now - REACHABLE_TIMEOUT) {
2110 /* We're configured as having IPv6 connectivity. There's an IPv6
2111 OR port and it's reachable so copy it to the routerstatus. */
2112 tor_addr_copy(&rs->ipv6_addr, &ri->ipv6_addr);
2113 rs->ipv6_orport = ri->ipv6_orport;
2116 /* Iff we are in a testing network, use TestingDirAuthVoteExit to
2117 give out Exit flags, and TestingDirAuthVoteGuard to
2118 give out Guard flags. */
2119 if (options->TestingTorNetwork) {
2120 if (routerset_contains_routerstatus(options->TestingDirAuthVoteExit,
2121 rs, 0)) {
2122 rs->is_exit = 1;
2125 if (routerset_contains_routerstatus(options->TestingDirAuthVoteGuard,
2126 rs, 0)) {
2127 rs->is_possible_guard = 1;
2132 /** Routerstatus <b>rs</b> is part of a group of routers that are on
2133 * too narrow an IP-space. Clear out its flags: we don't want people
2134 * using it.
2136 static void
2137 clear_status_flags_on_sybil(routerstatus_t *rs)
2139 rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
2140 rs->is_flagged_running = rs->is_named = rs->is_valid =
2141 rs->is_hs_dir = rs->is_possible_guard = rs->is_bad_exit = 0;
2142 /* FFFF we might want some mechanism to check later on if we
2143 * missed zeroing any flags: it's easy to add a new flag but
2144 * forget to add it to this clause. */
2148 * Helper function to parse out a line in the measured bandwidth file
2149 * into a measured_bw_line_t output structure. Returns -1 on failure
2150 * or 0 on success.
2152 STATIC int
2153 measured_bw_line_parse(measured_bw_line_t *out, const char *orig_line)
2155 char *line = tor_strdup(orig_line);
2156 char *cp = line;
2157 int got_bw = 0;
2158 int got_node_id = 0;
2159 char *strtok_state; /* lame sauce d'jour */
2160 cp = tor_strtok_r(cp, " \t", &strtok_state);
2162 if (!cp) {
2163 log_warn(LD_DIRSERV, "Invalid line in bandwidth file: %s",
2164 escaped(orig_line));
2165 tor_free(line);
2166 return -1;
2169 if (orig_line[strlen(orig_line)-1] != '\n') {
2170 log_warn(LD_DIRSERV, "Incomplete line in bandwidth file: %s",
2171 escaped(orig_line));
2172 tor_free(line);
2173 return -1;
2176 do {
2177 if (strcmpstart(cp, "bw=") == 0) {
2178 int parse_ok = 0;
2179 char *endptr;
2180 if (got_bw) {
2181 log_warn(LD_DIRSERV, "Double bw= in bandwidth file line: %s",
2182 escaped(orig_line));
2183 tor_free(line);
2184 return -1;
2186 cp+=strlen("bw=");
2188 out->bw_kb = tor_parse_long(cp, 0, 0, LONG_MAX, &parse_ok, &endptr);
2189 if (!parse_ok || (*endptr && !TOR_ISSPACE(*endptr))) {
2190 log_warn(LD_DIRSERV, "Invalid bandwidth in bandwidth file line: %s",
2191 escaped(orig_line));
2192 tor_free(line);
2193 return -1;
2195 got_bw=1;
2196 } else if (strcmpstart(cp, "node_id=$") == 0) {
2197 if (got_node_id) {
2198 log_warn(LD_DIRSERV, "Double node_id= in bandwidth file line: %s",
2199 escaped(orig_line));
2200 tor_free(line);
2201 return -1;
2203 cp+=strlen("node_id=$");
2205 if (strlen(cp) != HEX_DIGEST_LEN ||
2206 base16_decode(out->node_id, DIGEST_LEN, cp, HEX_DIGEST_LEN)) {
2207 log_warn(LD_DIRSERV, "Invalid node_id in bandwidth file line: %s",
2208 escaped(orig_line));
2209 tor_free(line);
2210 return -1;
2212 strlcpy(out->node_hex, cp, sizeof(out->node_hex));
2213 got_node_id=1;
2215 } while ((cp = tor_strtok_r(NULL, " \t", &strtok_state)));
2217 if (got_bw && got_node_id) {
2218 tor_free(line);
2219 return 0;
2220 } else {
2221 log_warn(LD_DIRSERV, "Incomplete line in bandwidth file: %s",
2222 escaped(orig_line));
2223 tor_free(line);
2224 return -1;
2229 * Helper function to apply a parsed measurement line to a list
2230 * of bandwidth statuses. Returns true if a line is found,
2231 * false otherwise.
2233 STATIC int
2234 measured_bw_line_apply(measured_bw_line_t *parsed_line,
2235 smartlist_t *routerstatuses)
2237 vote_routerstatus_t *rs = NULL;
2238 if (!routerstatuses)
2239 return 0;
2241 rs = smartlist_bsearch(routerstatuses, parsed_line->node_id,
2242 compare_digest_to_vote_routerstatus_entry);
2244 if (rs) {
2245 rs->has_measured_bw = 1;
2246 rs->measured_bw_kb = (uint32_t)parsed_line->bw_kb;
2247 } else {
2248 log_info(LD_DIRSERV, "Node ID %s not found in routerstatus list",
2249 parsed_line->node_hex);
2252 return rs != NULL;
2256 * Read the measured bandwidth file and apply it to the list of
2257 * vote_routerstatus_t. Returns -1 on error, 0 otherwise.
2260 dirserv_read_measured_bandwidths(const char *from_file,
2261 smartlist_t *routerstatuses)
2263 char line[256];
2264 FILE *fp = tor_fopen_cloexec(from_file, "r");
2265 int applied_lines = 0;
2266 time_t file_time, now;
2267 int ok;
2269 if (fp == NULL) {
2270 log_warn(LD_CONFIG, "Can't open bandwidth file at configured location: %s",
2271 from_file);
2272 return -1;
2275 if (!fgets(line, sizeof(line), fp)
2276 || !strlen(line) || line[strlen(line)-1] != '\n') {
2277 log_warn(LD_DIRSERV, "Long or truncated time in bandwidth file: %s",
2278 escaped(line));
2279 fclose(fp);
2280 return -1;
2283 line[strlen(line)-1] = '\0';
2284 file_time = (time_t)tor_parse_ulong(line, 10, 0, ULONG_MAX, &ok, NULL);
2285 if (!ok) {
2286 log_warn(LD_DIRSERV, "Non-integer time in bandwidth file: %s",
2287 escaped(line));
2288 fclose(fp);
2289 return -1;
2292 now = time(NULL);
2293 if ((now - file_time) > MAX_MEASUREMENT_AGE) {
2294 log_warn(LD_DIRSERV, "Bandwidth measurement file stale. Age: %u",
2295 (unsigned)(time(NULL) - file_time));
2296 fclose(fp);
2297 return -1;
2300 if (routerstatuses)
2301 smartlist_sort(routerstatuses, compare_vote_routerstatus_entries);
2303 while (!feof(fp)) {
2304 measured_bw_line_t parsed_line;
2305 if (fgets(line, sizeof(line), fp) && strlen(line)) {
2306 if (measured_bw_line_parse(&parsed_line, line) != -1) {
2307 /* Also cache the line for dirserv_get_bandwidth_for_router() */
2308 dirserv_cache_measured_bw(&parsed_line, file_time);
2309 if (measured_bw_line_apply(&parsed_line, routerstatuses) > 0)
2310 applied_lines++;
2315 /* Now would be a nice time to clean the cache, too */
2316 dirserv_expire_measured_bw_cache(now);
2318 fclose(fp);
2319 log_info(LD_DIRSERV,
2320 "Bandwidth measurement file successfully read. "
2321 "Applied %d measurements.", applied_lines);
2322 return 0;
2325 /** Return a new networkstatus_t* containing our current opinion. (For v3
2326 * authorities) */
2327 networkstatus_t *
2328 dirserv_generate_networkstatus_vote_obj(crypto_pk_t *private_key,
2329 authority_cert_t *cert)
2331 const or_options_t *options = get_options();
2332 networkstatus_t *v3_out = NULL;
2333 uint32_t addr;
2334 char *hostname = NULL, *client_versions = NULL, *server_versions = NULL;
2335 const char *contact;
2336 smartlist_t *routers, *routerstatuses;
2337 char identity_digest[DIGEST_LEN];
2338 char signing_key_digest[DIGEST_LEN];
2339 int listbadexits = options->AuthDirListBadExits;
2340 int vote_on_hsdirs = options->VoteOnHidServDirectoriesV2;
2341 routerlist_t *rl = router_get_routerlist();
2342 time_t now = time(NULL);
2343 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2344 networkstatus_voter_info_t *voter = NULL;
2345 vote_timing_t timing;
2346 digestmap_t *omit_as_sybil = NULL;
2347 const int vote_on_reachability = running_long_enough_to_decide_unreachable();
2348 smartlist_t *microdescriptors = NULL;
2350 tor_assert(private_key);
2351 tor_assert(cert);
2353 if (crypto_pk_get_digest(private_key, signing_key_digest)<0) {
2354 log_err(LD_BUG, "Error computing signing key digest");
2355 return NULL;
2357 if (crypto_pk_get_digest(cert->identity_key, identity_digest)<0) {
2358 log_err(LD_BUG, "Error computing identity key digest");
2359 return NULL;
2361 if (resolve_my_address(LOG_WARN, options, &addr, NULL, &hostname)<0) {
2362 log_warn(LD_NET, "Couldn't resolve my hostname");
2363 return NULL;
2365 if (!hostname || !strchr(hostname, '.')) {
2366 tor_free(hostname);
2367 hostname = tor_dup_ip(addr);
2370 if (options->VersioningAuthoritativeDir) {
2371 client_versions = format_versions_list(options->RecommendedClientVersions);
2372 server_versions = format_versions_list(options->RecommendedServerVersions);
2375 contact = get_options()->ContactInfo;
2376 if (!contact)
2377 contact = "(none)";
2380 * Do this so dirserv_compute_performance_thresholds() and
2381 * set_routerstatus_from_routerinfo() see up-to-date bandwidth info.
2383 if (options->V3BandwidthsFile) {
2384 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
2385 } else {
2387 * No bandwidths file; clear the measured bandwidth cache in case we had
2388 * one last time around.
2390 if (dirserv_get_measured_bw_cache_size() > 0) {
2391 dirserv_clear_measured_bw_cache();
2395 /* precompute this part, since we need it to decide what "stable"
2396 * means. */
2397 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2398 dirserv_set_router_is_running(ri, now);
2401 routers = smartlist_new();
2402 smartlist_add_all(routers, rl->routers);
2403 routers_sort_by_identity(routers);
2404 omit_as_sybil = get_possible_sybil_list(routers);
2406 DIGESTMAP_FOREACH(omit_as_sybil, sybil_id, void *, ignore) {
2407 (void) ignore;
2408 rep_hist_make_router_pessimal(sybil_id, now);
2409 } DIGESTMAP_FOREACH_END;
2411 /* Count how many have measured bandwidths so we know how to assign flags;
2412 * this must come before dirserv_compute_performance_thresholds() */
2413 dirserv_count_measured_bws(rl);
2415 dirserv_compute_performance_thresholds(rl, omit_as_sybil);
2417 routerstatuses = smartlist_new();
2418 microdescriptors = smartlist_new();
2420 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
2421 if (ri->cache_info.published_on >= cutoff) {
2422 routerstatus_t *rs;
2423 vote_routerstatus_t *vrs;
2424 node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
2425 if (!node)
2426 continue;
2428 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
2429 rs = &vrs->status;
2430 set_routerstatus_from_routerinfo(rs, node, ri, now,
2431 listbadexits,
2432 vote_on_hsdirs);
2434 if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
2435 clear_status_flags_on_sybil(rs);
2437 if (!vote_on_reachability)
2438 rs->is_flagged_running = 0;
2440 vrs->version = version_from_platform(ri->platform);
2441 vrs->microdesc = dirvote_format_all_microdesc_vote_lines(ri, now,
2442 microdescriptors);
2444 smartlist_add(routerstatuses, vrs);
2446 } SMARTLIST_FOREACH_END(ri);
2449 smartlist_t *added =
2450 microdescs_add_list_to_cache(get_microdesc_cache(),
2451 microdescriptors, SAVED_NOWHERE, 0);
2452 smartlist_free(added);
2453 smartlist_free(microdescriptors);
2456 smartlist_free(routers);
2457 digestmap_free(omit_as_sybil, NULL);
2459 /* This pass through applies the measured bw lines to the routerstatuses */
2460 if (options->V3BandwidthsFile) {
2461 dirserv_read_measured_bandwidths(options->V3BandwidthsFile,
2462 routerstatuses);
2463 } else {
2465 * No bandwidths file; clear the measured bandwidth cache in case we had
2466 * one last time around.
2468 if (dirserv_get_measured_bw_cache_size() > 0) {
2469 dirserv_clear_measured_bw_cache();
2473 v3_out = tor_malloc_zero(sizeof(networkstatus_t));
2475 v3_out->type = NS_TYPE_VOTE;
2476 dirvote_get_preferred_voting_intervals(&timing);
2477 v3_out->published = now;
2479 char tbuf[ISO_TIME_LEN+1];
2480 networkstatus_t *current_consensus =
2481 networkstatus_get_live_consensus(now);
2482 long last_consensus_interval; /* only used to pick a valid_after */
2483 if (current_consensus)
2484 last_consensus_interval = current_consensus->fresh_until -
2485 current_consensus->valid_after;
2486 else
2487 last_consensus_interval = options->TestingV3AuthInitialVotingInterval;
2488 v3_out->valid_after =
2489 dirvote_get_start_of_next_interval(now, (int)last_consensus_interval,
2490 options->TestingV3AuthVotingStartOffset);
2491 format_iso_time(tbuf, v3_out->valid_after);
2492 log_notice(LD_DIR,"Choosing valid-after time in vote as %s: "
2493 "consensus_set=%d, last_interval=%d",
2494 tbuf, current_consensus?1:0, (int)last_consensus_interval);
2496 v3_out->fresh_until = v3_out->valid_after + timing.vote_interval;
2497 v3_out->valid_until = v3_out->valid_after +
2498 (timing.vote_interval * timing.n_intervals_valid);
2499 v3_out->vote_seconds = timing.vote_delay;
2500 v3_out->dist_seconds = timing.dist_delay;
2501 tor_assert(v3_out->vote_seconds > 0);
2502 tor_assert(v3_out->dist_seconds > 0);
2503 tor_assert(timing.n_intervals_valid > 0);
2505 v3_out->client_versions = client_versions;
2506 v3_out->server_versions = server_versions;
2507 v3_out->known_flags = smartlist_new();
2508 smartlist_split_string(v3_out->known_flags,
2509 "Authority Exit Fast Guard Stable V2Dir Valid",
2510 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2511 if (vote_on_reachability)
2512 smartlist_add(v3_out->known_flags, tor_strdup("Running"));
2513 if (listbadexits)
2514 smartlist_add(v3_out->known_flags, tor_strdup("BadExit"));
2515 if (vote_on_hsdirs)
2516 smartlist_add(v3_out->known_flags, tor_strdup("HSDir"));
2517 smartlist_sort_strings(v3_out->known_flags);
2519 if (options->ConsensusParams) {
2520 v3_out->net_params = smartlist_new();
2521 smartlist_split_string(v3_out->net_params,
2522 options->ConsensusParams, NULL, 0, 0);
2523 smartlist_sort_strings(v3_out->net_params);
2526 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
2527 voter->nickname = tor_strdup(options->Nickname);
2528 memcpy(voter->identity_digest, identity_digest, DIGEST_LEN);
2529 voter->sigs = smartlist_new();
2530 voter->address = hostname;
2531 voter->addr = addr;
2532 voter->dir_port = router_get_advertised_dir_port(options, 0);
2533 voter->or_port = router_get_advertised_or_port(options);
2534 voter->contact = tor_strdup(contact);
2535 if (options->V3AuthUseLegacyKey) {
2536 authority_cert_t *c = get_my_v3_legacy_cert();
2537 if (c) {
2538 if (crypto_pk_get_digest(c->identity_key, voter->legacy_id_digest)) {
2539 log_warn(LD_BUG, "Unable to compute digest of legacy v3 identity key");
2540 memset(voter->legacy_id_digest, 0, DIGEST_LEN);
2545 v3_out->voters = smartlist_new();
2546 smartlist_add(v3_out->voters, voter);
2547 v3_out->cert = authority_cert_dup(cert);
2548 v3_out->routerstatus_list = routerstatuses;
2549 /* Note: networkstatus_digest is unset; it won't get set until we actually
2550 * format the vote. */
2552 return v3_out;
2555 /** As dirserv_get_routerdescs(), but instead of getting signed_descriptor_t
2556 * pointers, adds copies of digests to fps_out, and doesn't use the
2557 * /tor/server/ prefix. For a /d/ request, adds descriptor digests; for other
2558 * requests, adds identity digests.
2561 dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
2562 const char **msg, int for_unencrypted_conn,
2563 int is_extrainfo)
2565 int by_id = 1;
2566 *msg = NULL;
2568 if (!strcmp(key, "all")) {
2569 routerlist_t *rl = router_get_routerlist();
2570 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2571 smartlist_add(fps_out,
2572 tor_memdup(r->cache_info.identity_digest, DIGEST_LEN)));
2573 /* Treat "all" requests as if they were unencrypted */
2574 for_unencrypted_conn = 1;
2575 } else if (!strcmp(key, "authority")) {
2576 const routerinfo_t *ri = router_get_my_routerinfo();
2577 if (ri)
2578 smartlist_add(fps_out,
2579 tor_memdup(ri->cache_info.identity_digest, DIGEST_LEN));
2580 } else if (!strcmpstart(key, "d/")) {
2581 by_id = 0;
2582 key += strlen("d/");
2583 dir_split_resource_into_fingerprints(key, fps_out, NULL,
2584 DSR_HEX|DSR_SORT_UNIQ);
2585 } else if (!strcmpstart(key, "fp/")) {
2586 key += strlen("fp/");
2587 dir_split_resource_into_fingerprints(key, fps_out, NULL,
2588 DSR_HEX|DSR_SORT_UNIQ);
2589 } else {
2590 *msg = "Key not recognized";
2591 return -1;
2594 if (for_unencrypted_conn) {
2595 /* Remove anything that insists it not be sent unencrypted. */
2596 SMARTLIST_FOREACH_BEGIN(fps_out, char *, cp) {
2597 const signed_descriptor_t *sd;
2598 if (by_id)
2599 sd = get_signed_descriptor_by_fp(cp,is_extrainfo,0);
2600 else if (is_extrainfo)
2601 sd = extrainfo_get_by_descriptor_digest(cp);
2602 else
2603 sd = router_get_by_descriptor_digest(cp);
2604 if (sd && !sd->send_unencrypted) {
2605 tor_free(cp);
2606 SMARTLIST_DEL_CURRENT(fps_out, cp);
2608 } SMARTLIST_FOREACH_END(cp);
2611 if (!smartlist_len(fps_out)) {
2612 *msg = "Servers unavailable";
2613 return -1;
2615 return 0;
2618 /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
2619 * <b>key</b>. The key should be either
2620 * - "/tor/server/authority" for our own routerinfo;
2621 * - "/tor/server/all" for all the routerinfos we have, concatenated;
2622 * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
2623 * hex identity digests; or
2624 * - "/tor/server/d/D" where D is a plus-separated sequence
2625 * of server descriptor digests, in hex.
2627 * Return 0 if we found some matching descriptors, or -1 if we do not
2628 * have any descriptors, no matching descriptors, or if we did not
2629 * recognize the key (URL).
2630 * If -1 is returned *<b>msg</b> will be set to an appropriate error
2631 * message.
2633 * XXXX rename this function. It's only called from the controller.
2634 * XXXX in fact, refactor this function, merging as much as possible.
2637 dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
2638 const char **msg)
2640 *msg = NULL;
2642 if (!strcmp(key, "/tor/server/all")) {
2643 routerlist_t *rl = router_get_routerlist();
2644 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2645 smartlist_add(descs_out, &(r->cache_info)));
2646 } else if (!strcmp(key, "/tor/server/authority")) {
2647 const routerinfo_t *ri = router_get_my_routerinfo();
2648 if (ri)
2649 smartlist_add(descs_out, (void*) &(ri->cache_info));
2650 } else if (!strcmpstart(key, "/tor/server/d/")) {
2651 smartlist_t *digests = smartlist_new();
2652 key += strlen("/tor/server/d/");
2653 dir_split_resource_into_fingerprints(key, digests, NULL,
2654 DSR_HEX|DSR_SORT_UNIQ);
2655 SMARTLIST_FOREACH(digests, const char *, d,
2657 signed_descriptor_t *sd = router_get_by_descriptor_digest(d);
2658 if (sd)
2659 smartlist_add(descs_out,sd);
2661 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
2662 smartlist_free(digests);
2663 } else if (!strcmpstart(key, "/tor/server/fp/")) {
2664 smartlist_t *digests = smartlist_new();
2665 time_t cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
2666 key += strlen("/tor/server/fp/");
2667 dir_split_resource_into_fingerprints(key, digests, NULL,
2668 DSR_HEX|DSR_SORT_UNIQ);
2669 SMARTLIST_FOREACH_BEGIN(digests, const char *, d) {
2670 if (router_digest_is_me(d)) {
2671 /* make sure desc_routerinfo exists */
2672 const routerinfo_t *ri = router_get_my_routerinfo();
2673 if (ri)
2674 smartlist_add(descs_out, (void*) &(ri->cache_info));
2675 } else {
2676 const routerinfo_t *ri = router_get_by_id_digest(d);
2677 /* Don't actually serve a descriptor that everyone will think is
2678 * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
2679 * Tors from downloading descriptors that they will throw away.
2681 if (ri && ri->cache_info.published_on > cutoff)
2682 smartlist_add(descs_out, (void*) &(ri->cache_info));
2684 } SMARTLIST_FOREACH_END(d);
2685 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
2686 smartlist_free(digests);
2687 } else {
2688 *msg = "Key not recognized";
2689 return -1;
2692 if (!smartlist_len(descs_out)) {
2693 *msg = "Servers unavailable";
2694 return -1;
2696 return 0;
2699 /** Called when a TLS handshake has completed successfully with a
2700 * router listening at <b>address</b>:<b>or_port</b>, and has yielded
2701 * a certificate with digest <b>digest_rcvd</b>.
2703 * Inform the reachability checker that we could get to this guy.
2705 void
2706 dirserv_orconn_tls_done(const tor_addr_t *addr,
2707 uint16_t or_port,
2708 const char *digest_rcvd)
2710 node_t *node = NULL;
2711 tor_addr_port_t orport;
2712 routerinfo_t *ri = NULL;
2713 time_t now = time(NULL);
2714 tor_assert(addr);
2715 tor_assert(digest_rcvd);
2717 node = node_get_mutable_by_id(digest_rcvd);
2718 if (node == NULL || node->ri == NULL)
2719 return;
2720 ri = node->ri;
2722 tor_addr_copy(&orport.addr, addr);
2723 orport.port = or_port;
2724 if (router_has_orport(ri, &orport)) {
2725 /* Found the right router. */
2726 if (!authdir_mode_bridge(get_options()) ||
2727 ri->purpose == ROUTER_PURPOSE_BRIDGE) {
2728 char addrstr[TOR_ADDR_BUF_LEN];
2729 /* This is a bridge or we're not a bridge authorititative --
2730 mark it as reachable. */
2731 log_info(LD_DIRSERV, "Found router %s to be reachable at %s:%d. Yay.",
2732 router_describe(ri),
2733 tor_addr_to_str(addrstr, addr, sizeof(addrstr), 1),
2734 ri->or_port);
2735 if (tor_addr_family(addr) == AF_INET) {
2736 rep_hist_note_router_reachable(digest_rcvd, addr, or_port, now);
2737 node->last_reachable = now;
2738 } else if (tor_addr_family(addr) == AF_INET6) {
2739 /* No rephist for IPv6. */
2740 node->last_reachable6 = now;
2746 /** Called when we, as an authority, receive a new router descriptor either as
2747 * an upload or a download. Used to decide whether to relaunch reachability
2748 * testing for the server. */
2750 dirserv_should_launch_reachability_test(const routerinfo_t *ri,
2751 const routerinfo_t *ri_old)
2753 if (!authdir_mode_handles_descs(get_options(), ri->purpose))
2754 return 0;
2755 if (!ri_old) {
2756 /* New router: Launch an immediate reachability test, so we will have an
2757 * opinion soon in case we're generating a consensus soon */
2758 return 1;
2760 if (ri_old->is_hibernating && !ri->is_hibernating) {
2761 /* It just came out of hibernation; launch a reachability test */
2762 return 1;
2764 if (! routers_have_same_or_addrs(ri, ri_old)) {
2765 /* Address or port changed; launch a reachability test */
2766 return 1;
2768 return 0;
2771 /** Helper function for dirserv_test_reachability(). Start a TLS
2772 * connection to <b>router</b>, and annotate it with when we started
2773 * the test. */
2774 void
2775 dirserv_single_reachability_test(time_t now, routerinfo_t *router)
2777 channel_t *chan = NULL;
2778 node_t *node = NULL;
2779 tor_addr_t router_addr;
2780 (void) now;
2782 tor_assert(router);
2783 node = node_get_mutable_by_id(router->cache_info.identity_digest);
2784 tor_assert(node);
2786 /* IPv4. */
2787 log_debug(LD_OR,"Testing reachability of %s at %s:%u.",
2788 router->nickname, fmt_addr32(router->addr), router->or_port);
2789 tor_addr_from_ipv4h(&router_addr, router->addr);
2790 chan = channel_tls_connect(&router_addr, router->or_port,
2791 router->cache_info.identity_digest);
2792 if (chan) command_setup_channel(chan);
2794 /* Possible IPv6. */
2795 if (get_options()->AuthDirHasIPv6Connectivity == 1 &&
2796 !tor_addr_is_null(&router->ipv6_addr)) {
2797 char addrstr[TOR_ADDR_BUF_LEN];
2798 log_debug(LD_OR, "Testing reachability of %s at %s:%u.",
2799 router->nickname,
2800 tor_addr_to_str(addrstr, &router->ipv6_addr, sizeof(addrstr), 1),
2801 router->ipv6_orport);
2802 chan = channel_tls_connect(&router->ipv6_addr, router->ipv6_orport,
2803 router->cache_info.identity_digest);
2804 if (chan) command_setup_channel(chan);
2808 /** Auth dir server only: load balance such that we only
2809 * try a few connections per call.
2811 * The load balancing is such that if we get called once every ten
2812 * seconds, we will cycle through all the tests in
2813 * REACHABILITY_TEST_CYCLE_PERIOD seconds (a bit over 20 minutes).
2815 void
2816 dirserv_test_reachability(time_t now)
2818 /* XXX decide what to do here; see or-talk thread "purging old router
2819 * information, revocation." -NM
2820 * We can't afford to mess with this in 0.1.2.x. The reason is that
2821 * if we stop doing reachability tests on some of routerlist, then
2822 * we'll for-sure think they're down, which may have unexpected
2823 * effects in other parts of the code. It doesn't hurt much to do
2824 * the testing, and directory authorities are easy to upgrade. Let's
2825 * wait til 0.2.0. -RD */
2826 // time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2827 routerlist_t *rl = router_get_routerlist();
2828 static char ctr = 0;
2829 int bridge_auth = authdir_mode_bridge(get_options());
2831 SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, router) {
2832 const char *id_digest = router->cache_info.identity_digest;
2833 if (router_is_me(router))
2834 continue;
2835 if (bridge_auth && router->purpose != ROUTER_PURPOSE_BRIDGE)
2836 continue; /* bridge authorities only test reachability on bridges */
2837 // if (router->cache_info.published_on > cutoff)
2838 // continue;
2839 if ((((uint8_t)id_digest[0]) % REACHABILITY_MODULO_PER_TEST) == ctr) {
2840 dirserv_single_reachability_test(now, router);
2842 } SMARTLIST_FOREACH_END(router);
2843 ctr = (ctr + 1) % REACHABILITY_MODULO_PER_TEST; /* increment ctr */
2846 /** Given a fingerprint <b>fp</b> which is either set if we're looking for a
2847 * v2 status, or zeroes if we're looking for a v3 status, or a NUL-padded
2848 * flavor name if we want a flavored v3 status, return a pointer to the
2849 * appropriate cached dir object, or NULL if there isn't one available. */
2850 static cached_dir_t *
2851 lookup_cached_dir_by_fp(const char *fp)
2853 cached_dir_t *d = NULL;
2854 if (tor_digest_is_zero(fp) && cached_consensuses) {
2855 d = strmap_get(cached_consensuses, "ns");
2856 } else if (memchr(fp, '\0', DIGEST_LEN) && cached_consensuses &&
2857 (d = strmap_get(cached_consensuses, fp))) {
2858 /* this here interface is a nasty hack XXXX024 */;
2860 return d;
2863 /** Remove from <b>fps</b> every networkstatus key where both
2864 * a) we have a networkstatus document and
2865 * b) it is not newer than <b>cutoff</b>.
2867 * Return 1 if any items were present at all; else return 0.
2870 dirserv_remove_old_statuses(smartlist_t *fps, time_t cutoff)
2872 int found_any = 0;
2873 SMARTLIST_FOREACH_BEGIN(fps, char *, digest) {
2874 cached_dir_t *d = lookup_cached_dir_by_fp(digest);
2875 if (!d)
2876 continue;
2877 found_any = 1;
2878 if (d->published <= cutoff) {
2879 tor_free(digest);
2880 SMARTLIST_DEL_CURRENT(fps, digest);
2882 } SMARTLIST_FOREACH_END(digest);
2884 return found_any;
2887 /** Return the cache-info for identity fingerprint <b>fp</b>, or
2888 * its extra-info document if <b>extrainfo</b> is true. Return
2889 * NULL if not found or if the descriptor is older than
2890 * <b>publish_cutoff</b>. */
2891 static const signed_descriptor_t *
2892 get_signed_descriptor_by_fp(const char *fp, int extrainfo,
2893 time_t publish_cutoff)
2895 if (router_digest_is_me(fp)) {
2896 if (extrainfo)
2897 return &(router_get_my_extrainfo()->cache_info);
2898 else
2899 return &(router_get_my_routerinfo()->cache_info);
2900 } else {
2901 const routerinfo_t *ri = router_get_by_id_digest(fp);
2902 if (ri &&
2903 ri->cache_info.published_on > publish_cutoff) {
2904 if (extrainfo)
2905 return extrainfo_get_by_descriptor_digest(
2906 ri->cache_info.extra_info_digest);
2907 else
2908 return &ri->cache_info;
2911 return NULL;
2914 /** Return true iff we have any of the documents (extrainfo or routerdesc)
2915 * specified by the fingerprints in <b>fps</b> and <b>spool_src</b>. Used to
2916 * decide whether to send a 404. */
2918 dirserv_have_any_serverdesc(smartlist_t *fps, int spool_src)
2920 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
2921 SMARTLIST_FOREACH_BEGIN(fps, const char *, fp) {
2922 switch (spool_src)
2924 case DIR_SPOOL_EXTRA_BY_DIGEST:
2925 if (extrainfo_get_by_descriptor_digest(fp)) return 1;
2926 break;
2927 case DIR_SPOOL_SERVER_BY_DIGEST:
2928 if (router_get_by_descriptor_digest(fp)) return 1;
2929 break;
2930 case DIR_SPOOL_EXTRA_BY_FP:
2931 case DIR_SPOOL_SERVER_BY_FP:
2932 if (get_signed_descriptor_by_fp(fp,
2933 spool_src == DIR_SPOOL_EXTRA_BY_FP, publish_cutoff))
2934 return 1;
2935 break;
2937 } SMARTLIST_FOREACH_END(fp);
2938 return 0;
2941 /** Return true iff any of the 256-bit elements in <b>fps</b> is the digest of
2942 * a microdescriptor we have. */
2944 dirserv_have_any_microdesc(const smartlist_t *fps)
2946 microdesc_cache_t *cache = get_microdesc_cache();
2947 SMARTLIST_FOREACH(fps, const char *, fp,
2948 if (microdesc_cache_lookup_by_digest256(cache, fp))
2949 return 1);
2950 return 0;
2953 /** Return an approximate estimate of the number of bytes that will
2954 * be needed to transmit the server descriptors (if is_serverdescs --
2955 * they can be either d/ or fp/ queries) or networkstatus objects (if
2956 * !is_serverdescs) listed in <b>fps</b>. If <b>compressed</b> is set,
2957 * we guess how large the data will be after compression.
2959 * The return value is an estimate; it might be larger or smaller.
2961 size_t
2962 dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
2963 int compressed)
2965 size_t result;
2966 tor_assert(fps);
2967 if (is_serverdescs) {
2968 int n = smartlist_len(fps);
2969 const routerinfo_t *me = router_get_my_routerinfo();
2970 result = (me?me->cache_info.signed_descriptor_len:2048) * n;
2971 if (compressed)
2972 result /= 2; /* observed compressibility is between 35 and 55%. */
2973 } else {
2974 result = 0;
2975 SMARTLIST_FOREACH(fps, const char *, digest, {
2976 cached_dir_t *dir = lookup_cached_dir_by_fp(digest);
2977 if (dir)
2978 result += compressed ? dir->dir_z_len : dir->dir_len;
2981 return result;
2984 /** Given a list of microdescriptor hashes, guess how many bytes will be
2985 * needed to transmit them, and return the guess. */
2986 size_t
2987 dirserv_estimate_microdesc_size(const smartlist_t *fps, int compressed)
2989 size_t result = smartlist_len(fps) * microdesc_average_size(NULL);
2990 if (compressed)
2991 result /= 2;
2992 return result;
2995 /** When we're spooling data onto our outbuf, add more whenever we dip
2996 * below this threshold. */
2997 #define DIRSERV_BUFFER_MIN 16384
2999 /** Spooling helper: called when we have no more data to spool to <b>conn</b>.
3000 * Flushes any remaining data to be (un)compressed, and changes the spool
3001 * source to NONE. Returns 0 on success, negative on failure. */
3002 static int
3003 connection_dirserv_finish_spooling(dir_connection_t *conn)
3005 if (conn->zlib_state) {
3006 connection_write_to_buf_zlib("", 0, conn, 1);
3007 tor_zlib_free(conn->zlib_state);
3008 conn->zlib_state = NULL;
3010 conn->dir_spool_src = DIR_SPOOL_NONE;
3011 return 0;
3014 /** Spooling helper: called when we're sending a bunch of server descriptors,
3015 * and the outbuf has become too empty. Pulls some entries from
3016 * fingerprint_stack, and writes the corresponding servers onto outbuf. If we
3017 * run out of entries, flushes the zlib state and sets the spool source to
3018 * NONE. Returns 0 on success, negative on failure.
3020 static int
3021 connection_dirserv_add_servers_to_outbuf(dir_connection_t *conn)
3023 int by_fp = (conn->dir_spool_src == DIR_SPOOL_SERVER_BY_FP ||
3024 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP);
3025 int extra = (conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP ||
3026 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_DIGEST);
3027 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
3029 const or_options_t *options = get_options();
3031 while (smartlist_len(conn->fingerprint_stack) &&
3032 connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
3033 const char *body;
3034 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3035 const signed_descriptor_t *sd = NULL;
3036 if (by_fp) {
3037 sd = get_signed_descriptor_by_fp(fp, extra, publish_cutoff);
3038 } else {
3039 sd = extra ? extrainfo_get_by_descriptor_digest(fp)
3040 : router_get_by_descriptor_digest(fp);
3042 tor_free(fp);
3043 if (!sd)
3044 continue;
3045 if (!connection_dir_is_encrypted(conn) && !sd->send_unencrypted) {
3046 /* we did this check once before (so we could have an accurate size
3047 * estimate and maybe send a 404 if somebody asked for only bridges on a
3048 * connection), but we need to do it again in case a previously
3049 * unknown bridge descriptor has shown up between then and now. */
3050 continue;
3053 /** If we are the bridge authority and the descriptor is a bridge
3054 * descriptor, remember that we served this descriptor for desc stats. */
3055 if (options->BridgeAuthoritativeDir && by_fp) {
3056 const routerinfo_t *router =
3057 router_get_by_id_digest(sd->identity_digest);
3058 /* router can be NULL here when the bridge auth is asked for its own
3059 * descriptor. */
3060 if (router && router->purpose == ROUTER_PURPOSE_BRIDGE)
3061 rep_hist_note_desc_served(sd->identity_digest);
3063 body = signed_descriptor_get_body(sd);
3064 if (conn->zlib_state) {
3065 int last = ! smartlist_len(conn->fingerprint_stack);
3066 connection_write_to_buf_zlib(body, sd->signed_descriptor_len, conn,
3067 last);
3068 if (last) {
3069 tor_zlib_free(conn->zlib_state);
3070 conn->zlib_state = NULL;
3072 } else {
3073 connection_write_to_buf(body,
3074 sd->signed_descriptor_len,
3075 TO_CONN(conn));
3079 if (!smartlist_len(conn->fingerprint_stack)) {
3080 /* We just wrote the last one; finish up. */
3081 if (conn->zlib_state) {
3082 connection_write_to_buf_zlib("", 0, conn, 1);
3083 tor_zlib_free(conn->zlib_state);
3084 conn->zlib_state = NULL;
3086 conn->dir_spool_src = DIR_SPOOL_NONE;
3087 smartlist_free(conn->fingerprint_stack);
3088 conn->fingerprint_stack = NULL;
3090 return 0;
3093 /** Spooling helper: called when we're sending a bunch of microdescriptors,
3094 * and the outbuf has become too empty. Pulls some entries from
3095 * fingerprint_stack, and writes the corresponding microdescs onto outbuf. If
3096 * we run out of entries, flushes the zlib state and sets the spool source to
3097 * NONE. Returns 0 on success, negative on failure.
3099 static int
3100 connection_dirserv_add_microdescs_to_outbuf(dir_connection_t *conn)
3102 microdesc_cache_t *cache = get_microdesc_cache();
3103 while (smartlist_len(conn->fingerprint_stack) &&
3104 connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
3105 char *fp256 = smartlist_pop_last(conn->fingerprint_stack);
3106 microdesc_t *md = microdesc_cache_lookup_by_digest256(cache, fp256);
3107 tor_free(fp256);
3108 if (!md || !md->body)
3109 continue;
3110 if (conn->zlib_state) {
3111 int last = !smartlist_len(conn->fingerprint_stack);
3112 connection_write_to_buf_zlib(md->body, md->bodylen, conn, last);
3113 if (last) {
3114 tor_zlib_free(conn->zlib_state);
3115 conn->zlib_state = NULL;
3117 } else {
3118 connection_write_to_buf(md->body, md->bodylen, TO_CONN(conn));
3121 if (!smartlist_len(conn->fingerprint_stack)) {
3122 if (conn->zlib_state) {
3123 connection_write_to_buf_zlib("", 0, conn, 1);
3124 tor_zlib_free(conn->zlib_state);
3125 conn->zlib_state = NULL;
3127 conn->dir_spool_src = DIR_SPOOL_NONE;
3128 smartlist_free(conn->fingerprint_stack);
3129 conn->fingerprint_stack = NULL;
3131 return 0;
3134 /** Spooling helper: Called when we're sending a directory or networkstatus,
3135 * and the outbuf has become too empty. Pulls some bytes from
3136 * <b>conn</b>-\>cached_dir-\>dir_z, uncompresses them if appropriate, and
3137 * puts them on the outbuf. If we run out of entries, flushes the zlib state
3138 * and sets the spool source to NONE. Returns 0 on success, negative on
3139 * failure. */
3140 static int
3141 connection_dirserv_add_dir_bytes_to_outbuf(dir_connection_t *conn)
3143 ssize_t bytes;
3144 int64_t remaining;
3146 bytes = DIRSERV_BUFFER_MIN - connection_get_outbuf_len(TO_CONN(conn));
3147 tor_assert(bytes > 0);
3148 tor_assert(conn->cached_dir);
3149 if (bytes < 8192)
3150 bytes = 8192;
3151 remaining = conn->cached_dir->dir_z_len - conn->cached_dir_offset;
3152 if (bytes > remaining)
3153 bytes = (ssize_t) remaining;
3155 if (conn->zlib_state) {
3156 connection_write_to_buf_zlib(
3157 conn->cached_dir->dir_z + conn->cached_dir_offset,
3158 bytes, conn, bytes == remaining);
3159 } else {
3160 connection_write_to_buf(conn->cached_dir->dir_z + conn->cached_dir_offset,
3161 bytes, TO_CONN(conn));
3163 conn->cached_dir_offset += bytes;
3164 if (conn->cached_dir_offset == (int)conn->cached_dir->dir_z_len) {
3165 /* We just wrote the last one; finish up. */
3166 connection_dirserv_finish_spooling(conn);
3167 cached_dir_decref(conn->cached_dir);
3168 conn->cached_dir = NULL;
3170 return 0;
3173 /** Spooling helper: Called when we're spooling networkstatus objects on
3174 * <b>conn</b>, and the outbuf has become too empty. If the current
3175 * networkstatus object (in <b>conn</b>-\>cached_dir) has more data, pull data
3176 * from there. Otherwise, pop the next fingerprint from fingerprint_stack,
3177 * and start spooling the next networkstatus. (A digest of all 0 bytes is
3178 * treated as a request for the current consensus.) If we run out of entries,
3179 * flushes the zlib state and sets the spool source to NONE. Returns 0 on
3180 * success, negative on failure. */
3181 static int
3182 connection_dirserv_add_networkstatus_bytes_to_outbuf(dir_connection_t *conn)
3185 while (connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
3186 if (conn->cached_dir) {
3187 int uncompressing = (conn->zlib_state != NULL);
3188 int r = connection_dirserv_add_dir_bytes_to_outbuf(conn);
3189 if (conn->dir_spool_src == DIR_SPOOL_NONE) {
3190 /* add_dir_bytes thinks we're done with the cached_dir. But we
3191 * may have more cached_dirs! */
3192 conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
3193 /* This bit is tricky. If we were uncompressing the last
3194 * networkstatus, we may need to make a new zlib object to
3195 * uncompress the next one. */
3196 if (uncompressing && ! conn->zlib_state &&
3197 conn->fingerprint_stack &&
3198 smartlist_len(conn->fingerprint_stack)) {
3199 conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
3202 if (r) return r;
3203 } else if (conn->fingerprint_stack &&
3204 smartlist_len(conn->fingerprint_stack)) {
3205 /* Add another networkstatus; start serving it. */
3206 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3207 cached_dir_t *d = lookup_cached_dir_by_fp(fp);
3208 tor_free(fp);
3209 if (d) {
3210 ++d->refcnt;
3211 conn->cached_dir = d;
3212 conn->cached_dir_offset = 0;
3214 } else {
3215 connection_dirserv_finish_spooling(conn);
3216 smartlist_free(conn->fingerprint_stack);
3217 conn->fingerprint_stack = NULL;
3218 return 0;
3221 return 0;
3224 /** Called whenever we have flushed some directory data in state
3225 * SERVER_WRITING. */
3227 connection_dirserv_flushed_some(dir_connection_t *conn)
3229 tor_assert(conn->base_.state == DIR_CONN_STATE_SERVER_WRITING);
3231 if (connection_get_outbuf_len(TO_CONN(conn)) >= DIRSERV_BUFFER_MIN)
3232 return 0;
3234 switch (conn->dir_spool_src) {
3235 case DIR_SPOOL_EXTRA_BY_DIGEST:
3236 case DIR_SPOOL_EXTRA_BY_FP:
3237 case DIR_SPOOL_SERVER_BY_DIGEST:
3238 case DIR_SPOOL_SERVER_BY_FP:
3239 return connection_dirserv_add_servers_to_outbuf(conn);
3240 case DIR_SPOOL_MICRODESC:
3241 return connection_dirserv_add_microdescs_to_outbuf(conn);
3242 case DIR_SPOOL_CACHED_DIR:
3243 return connection_dirserv_add_dir_bytes_to_outbuf(conn);
3244 case DIR_SPOOL_NETWORKSTATUS:
3245 return connection_dirserv_add_networkstatus_bytes_to_outbuf(conn);
3246 case DIR_SPOOL_NONE:
3247 default:
3248 return 0;
3252 /** Release all storage used by the directory server. */
3253 void
3254 dirserv_free_all(void)
3256 dirserv_free_fingerprint_list();
3258 strmap_free(cached_consensuses, free_cached_dir_);
3259 cached_consensuses = NULL;
3261 dirserv_clear_measured_bw_cache();