Remove dirauth support for the BadDirectory flag
[tor.git] / src / or / dirserv.c
blobd96867b2c2212d9f3f530206f7ac2dc79f454514
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2013, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 #define DIRSERV_PRIVATE
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)) {
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)) {
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_WAS_NOT_NEW;
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_WAS_NOT_NEW;
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_WAS_NOT_NEW : 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;
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 he 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;
892 if (!node->is_running || !node->is_valid || ri->is_hibernating)
893 return 0;
894 if (!ri->bandwidthcapacity)
895 return 0;
896 return 1;
899 /** Generate a new v1 directory and write it into a newly allocated string.
900 * Point *<b>dir_out</b> to the allocated string. Sign the
901 * directory with <b>private_key</b>. Return 0 on success, -1 on
902 * failure. If <b>complete</b> is set, give us all the descriptors;
903 * otherwise leave out non-running and non-valid ones.
906 dirserv_dump_directory_to_string(char **dir_out,
907 crypto_pk_t *private_key)
909 /* XXXX 024 Get rid of this function if we can confirm that nobody's
910 * fetching these any longer */
911 char *cp;
912 char *identity_pkey; /* Identity key, DER64-encoded. */
913 char *recommended_versions;
914 char digest[DIGEST_LEN];
915 char published[ISO_TIME_LEN+1];
916 char *buf = NULL;
917 size_t buf_len;
918 size_t identity_pkey_len;
919 time_t now = time(NULL);
921 tor_assert(dir_out);
922 *dir_out = NULL;
924 if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
925 &identity_pkey_len)<0) {
926 log_warn(LD_BUG,"write identity_pkey to string failed!");
927 return -1;
930 recommended_versions =
931 format_versions_list(get_options()->RecommendedVersions);
933 format_iso_time(published, now);
935 buf_len = 2048+strlen(recommended_versions);
937 buf = tor_malloc(buf_len);
938 /* We'll be comparing against buf_len throughout the rest of the
939 function, though strictly speaking we shouldn't be able to exceed
940 it. This is C, after all, so we may as well check for buffer
941 overruns.*/
943 tor_snprintf(buf, buf_len,
944 "signed-directory\n"
945 "published %s\n"
946 "recommended-software %s\n"
947 "router-status %s\n"
948 "dir-signing-key\n%s\n",
949 published, recommended_versions, "",
950 identity_pkey);
952 tor_free(recommended_versions);
953 tor_free(identity_pkey);
955 cp = buf + strlen(buf);
956 *cp = '\0';
958 /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
959 signature. */
960 if (strlcat(buf, "directory-signature ", buf_len) >= buf_len)
961 goto truncated;
962 if (strlcat(buf, get_options()->Nickname, buf_len) >= buf_len)
963 goto truncated;
964 if (strlcat(buf, "\n", buf_len) >= buf_len)
965 goto truncated;
967 if (router_get_dir_hash(buf,digest)) {
968 log_warn(LD_BUG,"couldn't compute digest");
969 tor_free(buf);
970 return -1;
972 note_crypto_pk_op(SIGN_DIR);
973 if (router_append_dirobj_signature(buf,buf_len,digest,DIGEST_LEN,
974 private_key)<0) {
975 tor_free(buf);
976 return -1;
979 *dir_out = buf;
980 return 0;
981 truncated:
982 log_warn(LD_BUG,"tried to exceed string length.");
983 tor_free(buf);
984 return -1;
987 /********************************************************************/
989 /* A set of functions to answer questions about how we'd like to behave
990 * as a directory mirror/client. */
992 /** Return 1 if we fetch our directory material directly from the
993 * authorities, rather than from a mirror. */
995 directory_fetches_from_authorities(const or_options_t *options)
997 const routerinfo_t *me;
998 uint32_t addr;
999 int refuseunknown;
1000 if (options->FetchDirInfoEarly)
1001 return 1;
1002 if (options->BridgeRelay == 1)
1003 return 0;
1004 if (server_mode(options) && router_pick_published_address(options, &addr)<0)
1005 return 1; /* we don't know our IP address; ask an authority. */
1006 refuseunknown = ! router_my_exit_policy_is_reject_star() &&
1007 should_refuse_unknown_exits(options);
1008 if (!options->DirPort_set && !refuseunknown)
1009 return 0;
1010 if (!server_mode(options) || !advertised_server_mode())
1011 return 0;
1012 me = router_get_my_routerinfo();
1013 if (!me || (!me->dir_port && !refuseunknown))
1014 return 0; /* if dirport not advertised, return 0 too */
1015 return 1;
1018 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1019 * on the "mirror" schedule rather than the "client" schedule.
1022 directory_fetches_dir_info_early(const or_options_t *options)
1024 return directory_fetches_from_authorities(options);
1027 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1028 * on a very passive schedule -- waiting long enough for ordinary clients
1029 * to probably have the info we want. These would include bridge users,
1030 * and maybe others in the future e.g. if a Tor client uses another Tor
1031 * client as a directory guard.
1034 directory_fetches_dir_info_later(const or_options_t *options)
1036 return options->UseBridges != 0;
1039 /** Return true iff we want to fetch and keep certificates for authorities
1040 * that we don't acknowledge as aurthorities ourself.
1043 directory_caches_unknown_auth_certs(const or_options_t *options)
1045 return options->DirPort_set || options->BridgeRelay;
1048 /** Return 1 if we want to keep descriptors, networkstatuses, etc around
1049 * and we're willing to serve them to others. Else return 0.
1052 directory_caches_dir_info(const or_options_t *options)
1054 if (options->BridgeRelay || options->DirPort_set)
1055 return 1;
1056 if (!server_mode(options) || !advertised_server_mode())
1057 return 0;
1058 /* We need an up-to-date view of network info if we're going to try to
1059 * block exit attempts from unknown relays. */
1060 return ! router_my_exit_policy_is_reject_star() &&
1061 should_refuse_unknown_exits(options);
1064 /** Return 1 if we want to allow remote people to ask us directory
1065 * requests via the "begin_dir" interface, which doesn't require
1066 * having any separate port open. */
1068 directory_permits_begindir_requests(const or_options_t *options)
1070 return options->BridgeRelay != 0 || options->DirPort_set;
1073 /** Return 1 if we have no need to fetch new descriptors. This generally
1074 * happens when we're not a dir cache and we haven't built any circuits
1075 * lately.
1078 directory_too_idle_to_fetch_descriptors(const or_options_t *options,
1079 time_t now)
1081 return !directory_caches_dir_info(options) &&
1082 !options->FetchUselessDescriptors &&
1083 rep_hist_circbuilding_dormant(now);
1086 /********************************************************************/
1088 /** Map from flavor name to the cached_dir_t for the v3 consensuses that we're
1089 * currently serving. */
1090 static strmap_t *cached_consensuses = NULL;
1092 /** Decrement the reference count on <b>d</b>, and free it if it no longer has
1093 * any references. */
1094 void
1095 cached_dir_decref(cached_dir_t *d)
1097 if (!d || --d->refcnt > 0)
1098 return;
1099 clear_cached_dir(d);
1100 tor_free(d);
1103 /** Allocate and return a new cached_dir_t containing the string <b>s</b>,
1104 * published at <b>published</b>. */
1105 cached_dir_t *
1106 new_cached_dir(char *s, time_t published)
1108 cached_dir_t *d = tor_malloc_zero(sizeof(cached_dir_t));
1109 d->refcnt = 1;
1110 d->dir = s;
1111 d->dir_len = strlen(s);
1112 d->published = published;
1113 if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
1114 ZLIB_METHOD)) {
1115 log_warn(LD_BUG, "Error compressing directory");
1117 return d;
1120 /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
1121 static void
1122 clear_cached_dir(cached_dir_t *d)
1124 tor_free(d->dir);
1125 tor_free(d->dir_z);
1126 memset(d, 0, sizeof(cached_dir_t));
1129 /** Free all storage held by the cached_dir_t in <b>d</b>. */
1130 static void
1131 free_cached_dir_(void *_d)
1133 cached_dir_t *d;
1134 if (!_d)
1135 return;
1137 d = (cached_dir_t *)_d;
1138 cached_dir_decref(d);
1141 /** Replace the v3 consensus networkstatus of type <b>flavor_name</b> that
1142 * we're serving with <b>networkstatus</b>, published at <b>published</b>. No
1143 * validation is performed. */
1144 void
1145 dirserv_set_cached_consensus_networkstatus(const char *networkstatus,
1146 const char *flavor_name,
1147 const digests_t *digests,
1148 time_t published)
1150 cached_dir_t *new_networkstatus;
1151 cached_dir_t *old_networkstatus;
1152 if (!cached_consensuses)
1153 cached_consensuses = strmap_new();
1155 new_networkstatus = new_cached_dir(tor_strdup(networkstatus), published);
1156 memcpy(&new_networkstatus->digests, digests, sizeof(digests_t));
1157 old_networkstatus = strmap_set(cached_consensuses, flavor_name,
1158 new_networkstatus);
1159 if (old_networkstatus)
1160 cached_dir_decref(old_networkstatus);
1163 /** Return the latest downloaded consensus networkstatus in encoded, signed,
1164 * optionally compressed format, suitable for sending to clients. */
1165 cached_dir_t *
1166 dirserv_get_consensus(const char *flavor_name)
1168 if (!cached_consensuses)
1169 return NULL;
1170 return strmap_get(cached_consensuses, flavor_name);
1173 /** If a router's uptime is at least this value, then it is always
1174 * considered stable, regardless of the rest of the network. This
1175 * way we resist attacks where an attacker doubles the size of the
1176 * network using allegedly high-uptime nodes, displacing all the
1177 * current guards. */
1178 #define UPTIME_TO_GUARANTEE_STABLE (3600*24*30)
1179 /** If a router's MTBF is at least this value, then it is always stable.
1180 * See above. (Corresponds to about 7 days for current decay rates.) */
1181 #define MTBF_TO_GUARANTEE_STABLE (60*60*24*5)
1182 /** Similarly, every node with at least this much weighted time known can be
1183 * considered familiar enough to be a guard. Corresponds to about 20 days for
1184 * current decay rates.
1186 #define TIME_KNOWN_TO_GUARANTEE_FAMILIAR (8*24*60*60)
1187 /** Similarly, every node with sufficient WFU is around enough to be a guard.
1189 #define WFU_TO_GUARANTEE_GUARD (0.98)
1191 /* Thresholds for server performance: set by
1192 * dirserv_compute_performance_thresholds, and used by
1193 * generate_v2_networkstatus */
1195 /** Any router with an uptime of at least this value is stable. */
1196 static uint32_t stable_uptime = 0; /* start at a safe value */
1197 /** Any router with an mtbf of at least this value is stable. */
1198 static double stable_mtbf = 0.0;
1199 /** If true, we have measured enough mtbf info to look at stable_mtbf rather
1200 * than stable_uptime. */
1201 static int enough_mtbf_info = 0;
1202 /** Any router with a weighted fractional uptime of at least this much might
1203 * be good as a guard. */
1204 static double guard_wfu = 0.0;
1205 /** Don't call a router a guard unless we've known about it for at least this
1206 * many seconds. */
1207 static long guard_tk = 0;
1208 /** Any router with a bandwidth at least this high is "Fast" */
1209 static uint32_t fast_bandwidth_kb = 0;
1210 /** If exits can be guards, then all guards must have a bandwidth this
1211 * high. */
1212 static uint32_t guard_bandwidth_including_exits_kb = 0;
1213 /** If exits can't be guards, then all guards must have a bandwidth this
1214 * high. */
1215 static uint32_t guard_bandwidth_excluding_exits_kb = 0;
1217 /** Helper: estimate the uptime of a router given its stated uptime and the
1218 * amount of time since it last stated its stated uptime. */
1219 static INLINE long
1220 real_uptime(const routerinfo_t *router, time_t now)
1222 if (now < router->cache_info.published_on)
1223 return router->uptime;
1224 else
1225 return router->uptime + (now - router->cache_info.published_on);
1228 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1229 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1230 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1231 * bandwidth.
1233 static int
1234 dirserv_thinks_router_is_unreliable(time_t now,
1235 routerinfo_t *router,
1236 int need_uptime, int need_capacity)
1238 if (need_uptime) {
1239 if (!enough_mtbf_info) {
1240 /* XXX024 Once most authorities are on v3, we should change the rule from
1241 * "use uptime if we don't have mtbf data" to "don't advertise Stable on
1242 * v3 if we don't have enough mtbf data." Or maybe not, since if we ever
1243 * hit a point where we need to reset a lot of authorities at once,
1244 * none of them would be in a position to declare Stable.
1246 long uptime = real_uptime(router, now);
1247 if ((unsigned)uptime < stable_uptime &&
1248 (unsigned)uptime < UPTIME_TO_GUARANTEE_STABLE)
1249 return 1;
1250 } else {
1251 double mtbf =
1252 rep_hist_get_stability(router->cache_info.identity_digest, now);
1253 if (mtbf < stable_mtbf &&
1254 mtbf < MTBF_TO_GUARANTEE_STABLE)
1255 return 1;
1258 if (need_capacity) {
1259 uint32_t bw_kb = dirserv_get_credible_bandwidth_kb(router);
1260 if (bw_kb < fast_bandwidth_kb)
1261 return 1;
1263 return 0;
1266 /** Return true iff <b>router</b> should be assigned the "HSDir" flag.
1267 * Right now this means it advertises support for it, it has a high
1268 * uptime, it has a DirPort open, and it's currently considered Running.
1270 * This function needs to be called after router-\>is_running has
1271 * been set.
1273 static int
1274 dirserv_thinks_router_is_hs_dir(const routerinfo_t *router,
1275 const node_t *node, time_t now)
1278 long uptime;
1280 /* If we haven't been running for at least
1281 * get_options()->MinUptimeHidServDirectoryV2 seconds, we can't
1282 * have accurate data telling us a relay has been up for at least
1283 * that long. We also want to allow a bit of slack: Reachability
1284 * tests aren't instant. If we haven't been running long enough,
1285 * trust the relay. */
1287 if (stats_n_seconds_working >
1288 get_options()->MinUptimeHidServDirectoryV2 * 1.1)
1289 uptime = MIN(rep_hist_get_uptime(router->cache_info.identity_digest, now),
1290 real_uptime(router, now));
1291 else
1292 uptime = real_uptime(router, now);
1294 /* XXX We shouldn't need to check dir_port, but we do because of
1295 * bug 1693. In the future, once relays set wants_to_be_hs_dir
1296 * correctly, we can revert to only checking dir_port if router's
1297 * version is too old. */
1298 /* XXX Unfortunately, we need to keep checking dir_port until all
1299 * *clients* suffering from bug 2722 are obsolete. The first version
1300 * to fix the bug was 0.2.2.25-alpha. */
1301 return (router->wants_to_be_hs_dir && router->dir_port &&
1302 uptime >= get_options()->MinUptimeHidServDirectoryV2 &&
1303 router_is_active(router, node, now));
1306 /** Don't consider routers with less bandwidth than this when computing
1307 * thresholds. */
1308 #define ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER_KB 4
1310 /** Helper for dirserv_compute_performance_thresholds(): Decide whether to
1311 * include a router in our calculations, and return true iff we should; the
1312 * require_mbw parameter is passed in by
1313 * dirserv_compute_performance_thresholds() and controls whether we ever
1314 * count routers with only advertised bandwidths */
1315 static int
1316 router_counts_toward_thresholds(const node_t *node, time_t now,
1317 const digestmap_t *omit_as_sybil,
1318 int require_mbw)
1320 /* Have measured bw? */
1321 int have_mbw =
1322 dirserv_has_measured_bw(node->identity);
1323 uint64_t min_bw_kb = ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER_KB;
1324 const or_options_t *options = get_options();
1326 if (options->TestingTorNetwork) {
1327 min_bw_kb = (int64_t)options->TestingMinExitFlagThreshold / 1000;
1330 return node->ri && router_is_active(node->ri, node, now) &&
1331 !digestmap_get(omit_as_sybil, node->identity) &&
1332 (dirserv_get_credible_bandwidth_kb(node->ri) >= min_bw_kb) &&
1333 (have_mbw || !require_mbw);
1336 /** Look through the routerlist, the Mean Time Between Failure history, and
1337 * the Weighted Fractional Uptime history, and use them to set thresholds for
1338 * the Stable, Fast, and Guard flags. Update the fields stable_uptime,
1339 * stable_mtbf, enough_mtbf_info, guard_wfu, guard_tk, fast_bandwidth,
1340 * guard_bandwidth_including_exits, and guard_bandwidth_excluding_exits.
1342 * Also, set the is_exit flag of each router appropriately. */
1343 static void
1344 dirserv_compute_performance_thresholds(routerlist_t *rl,
1345 digestmap_t *omit_as_sybil)
1347 int n_active, n_active_nonexit, n_familiar;
1348 uint32_t *uptimes, *bandwidths_kb, *bandwidths_excluding_exits_kb;
1349 long *tks;
1350 double *mtbfs, *wfus;
1351 time_t now = time(NULL);
1352 const or_options_t *options = get_options();
1354 /* Require mbw? */
1355 int require_mbw =
1356 (routers_with_measured_bw >
1357 options->MinMeasuredBWsForAuthToIgnoreAdvertised) ? 1 : 0;
1359 /* initialize these all here, in case there are no routers */
1360 stable_uptime = 0;
1361 stable_mtbf = 0;
1362 fast_bandwidth_kb = 0;
1363 guard_bandwidth_including_exits_kb = 0;
1364 guard_bandwidth_excluding_exits_kb = 0;
1365 guard_tk = 0;
1366 guard_wfu = 0;
1368 /* Initialize arrays that will hold values for each router. We'll
1369 * sort them and use that to compute thresholds. */
1370 n_active = n_active_nonexit = 0;
1371 /* Uptime for every active router. */
1372 uptimes = tor_calloc(sizeof(uint32_t), smartlist_len(rl->routers));
1373 /* Bandwidth for every active router. */
1374 bandwidths_kb = tor_calloc(sizeof(uint32_t), smartlist_len(rl->routers));
1375 /* Bandwidth for every active non-exit router. */
1376 bandwidths_excluding_exits_kb =
1377 tor_calloc(sizeof(uint32_t), smartlist_len(rl->routers));
1378 /* Weighted mean time between failure for each active router. */
1379 mtbfs = tor_calloc(sizeof(double), smartlist_len(rl->routers));
1380 /* Time-known for each active router. */
1381 tks = tor_calloc(sizeof(long), smartlist_len(rl->routers));
1382 /* Weighted fractional uptime for each active router. */
1383 wfus = tor_calloc(sizeof(double), smartlist_len(rl->routers));
1385 nodelist_assert_ok();
1387 /* Now, fill in the arrays. */
1388 SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), node_t *, node) {
1389 if (options->BridgeAuthoritativeDir &&
1390 node->ri &&
1391 node->ri->purpose != ROUTER_PURPOSE_BRIDGE)
1392 continue;
1393 if (router_counts_toward_thresholds(node, now, omit_as_sybil,
1394 require_mbw)) {
1395 routerinfo_t *ri = node->ri;
1396 const char *id = node->identity;
1397 uint32_t bw_kb;
1398 node->is_exit = (!router_exit_policy_rejects_all(ri) &&
1399 exit_policy_is_general_exit(ri->exit_policy));
1400 uptimes[n_active] = (uint32_t)real_uptime(ri, now);
1401 mtbfs[n_active] = rep_hist_get_stability(id, now);
1402 tks [n_active] = rep_hist_get_weighted_time_known(id, now);
1403 bandwidths_kb[n_active] = bw_kb = dirserv_get_credible_bandwidth_kb(ri);
1404 if (!node->is_exit || node->is_bad_exit) {
1405 bandwidths_excluding_exits_kb[n_active_nonexit] = bw_kb;
1406 ++n_active_nonexit;
1408 ++n_active;
1410 } SMARTLIST_FOREACH_END(node);
1412 /* Now, compute thresholds. */
1413 if (n_active) {
1414 /* The median uptime is stable. */
1415 stable_uptime = median_uint32(uptimes, n_active);
1416 /* The median mtbf is stable, if we have enough mtbf info */
1417 stable_mtbf = median_double(mtbfs, n_active);
1418 /* The 12.5th percentile bandwidth is fast. */
1419 fast_bandwidth_kb = find_nth_uint32(bandwidths_kb, n_active, n_active/8);
1420 /* (Now bandwidths is sorted.) */
1421 if (fast_bandwidth_kb < ROUTER_REQUIRED_MIN_BANDWIDTH/(2 * 1000))
1422 fast_bandwidth_kb = bandwidths_kb[n_active/4];
1423 guard_bandwidth_including_exits_kb = bandwidths_kb[n_active*3/4];
1424 guard_tk = find_nth_long(tks, n_active, n_active/8);
1427 if (guard_tk > TIME_KNOWN_TO_GUARANTEE_FAMILIAR)
1428 guard_tk = TIME_KNOWN_TO_GUARANTEE_FAMILIAR;
1431 /* We can vote on a parameter for the minimum and maximum. */
1432 #define ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG 4
1433 int32_t min_fast_kb, max_fast_kb, min_fast, max_fast;
1434 min_fast = networkstatus_get_param(NULL, "FastFlagMinThreshold",
1435 ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG,
1436 ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG,
1437 INT32_MAX);
1438 if (options->TestingTorNetwork) {
1439 min_fast = (int32_t)options->TestingMinFastFlagThreshold;
1441 max_fast = networkstatus_get_param(NULL, "FastFlagMaxThreshold",
1442 INT32_MAX, min_fast, INT32_MAX);
1443 min_fast_kb = min_fast / 1000;
1444 max_fast_kb = max_fast / 1000;
1446 if (fast_bandwidth_kb < (uint32_t)min_fast_kb)
1447 fast_bandwidth_kb = min_fast_kb;
1448 if (fast_bandwidth_kb > (uint32_t)max_fast_kb)
1449 fast_bandwidth_kb = max_fast_kb;
1451 /* Protect sufficiently fast nodes from being pushed out of the set
1452 * of Fast nodes. */
1453 if (options->AuthDirFastGuarantee &&
1454 fast_bandwidth_kb > options->AuthDirFastGuarantee/1000)
1455 fast_bandwidth_kb = (uint32_t)options->AuthDirFastGuarantee/1000;
1457 /* Now that we have a time-known that 7/8 routers are known longer than,
1458 * fill wfus with the wfu of every such "familiar" router. */
1459 n_familiar = 0;
1461 SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), node_t *, node) {
1462 if (router_counts_toward_thresholds(node, now,
1463 omit_as_sybil, require_mbw)) {
1464 routerinfo_t *ri = node->ri;
1465 const char *id = ri->cache_info.identity_digest;
1466 long tk = rep_hist_get_weighted_time_known(id, now);
1467 if (tk < guard_tk)
1468 continue;
1469 wfus[n_familiar++] = rep_hist_get_weighted_fractional_uptime(id, now);
1471 } SMARTLIST_FOREACH_END(node);
1472 if (n_familiar)
1473 guard_wfu = median_double(wfus, n_familiar);
1474 if (guard_wfu > WFU_TO_GUARANTEE_GUARD)
1475 guard_wfu = WFU_TO_GUARANTEE_GUARD;
1477 enough_mtbf_info = rep_hist_have_measured_enough_stability();
1479 if (n_active_nonexit) {
1480 guard_bandwidth_excluding_exits_kb =
1481 find_nth_uint32(bandwidths_excluding_exits_kb,
1482 n_active_nonexit, n_active_nonexit*3/4);
1485 log_info(LD_DIRSERV,
1486 "Cutoffs: For Stable, %lu sec uptime, %lu sec MTBF. "
1487 "For Fast: %lu kilobytes/sec. "
1488 "For Guard: WFU %.03f%%, time-known %lu sec, "
1489 "and bandwidth %lu or %lu kilobytes/sec. "
1490 "We%s have enough stability data.",
1491 (unsigned long)stable_uptime,
1492 (unsigned long)stable_mtbf,
1493 (unsigned long)fast_bandwidth_kb,
1494 guard_wfu*100,
1495 (unsigned long)guard_tk,
1496 (unsigned long)guard_bandwidth_including_exits_kb,
1497 (unsigned long)guard_bandwidth_excluding_exits_kb,
1498 enough_mtbf_info ? "" : " don't ");
1500 tor_free(uptimes);
1501 tor_free(mtbfs);
1502 tor_free(bandwidths_kb);
1503 tor_free(bandwidths_excluding_exits_kb);
1504 tor_free(tks);
1505 tor_free(wfus);
1508 /* Use dirserv_compute_performance_thresholds() to compute the thresholds
1509 * for the status flags, specifically for bridges.
1511 * This is only called by a Bridge Authority from
1512 * networkstatus_getinfo_by_purpose().
1514 void
1515 dirserv_compute_bridge_flag_thresholds(routerlist_t *rl)
1518 digestmap_t *omit_as_sybil = digestmap_new();
1519 dirserv_compute_performance_thresholds(rl, omit_as_sybil);
1520 digestmap_free(omit_as_sybil, NULL);
1523 /** Measured bandwidth cache entry */
1524 typedef struct mbw_cache_entry_s {
1525 long mbw_kb;
1526 time_t as_of;
1527 } mbw_cache_entry_t;
1529 /** Measured bandwidth cache - keys are identity_digests, values are
1530 * mbw_cache_entry_t *. */
1531 static digestmap_t *mbw_cache = NULL;
1533 /** Store a measured bandwidth cache entry when reading the measured
1534 * bandwidths file. */
1535 STATIC void
1536 dirserv_cache_measured_bw(const measured_bw_line_t *parsed_line,
1537 time_t as_of)
1539 mbw_cache_entry_t *e = NULL;
1541 tor_assert(parsed_line);
1543 /* Allocate a cache if we need */
1544 if (!mbw_cache) mbw_cache = digestmap_new();
1546 /* Check if we have an existing entry */
1547 e = digestmap_get(mbw_cache, parsed_line->node_id);
1548 /* If we do, we can re-use it */
1549 if (e) {
1550 /* Check that we really are newer, and update */
1551 if (as_of > e->as_of) {
1552 e->mbw_kb = parsed_line->bw_kb;
1553 e->as_of = as_of;
1555 } else {
1556 /* We'll have to insert a new entry */
1557 e = tor_malloc(sizeof(*e));
1558 e->mbw_kb = parsed_line->bw_kb;
1559 e->as_of = as_of;
1560 digestmap_set(mbw_cache, parsed_line->node_id, e);
1564 /** Clear and free the measured bandwidth cache */
1565 STATIC void
1566 dirserv_clear_measured_bw_cache(void)
1568 if (mbw_cache) {
1569 /* Free the map and all entries */
1570 digestmap_free(mbw_cache, tor_free_);
1571 mbw_cache = NULL;
1575 /** Scan the measured bandwidth cache and remove expired entries */
1576 STATIC void
1577 dirserv_expire_measured_bw_cache(time_t now)
1580 if (mbw_cache) {
1581 /* Iterate through the cache and check each entry */
1582 DIGESTMAP_FOREACH_MODIFY(mbw_cache, k, mbw_cache_entry_t *, e) {
1583 if (now > e->as_of + MAX_MEASUREMENT_AGE) {
1584 tor_free(e);
1585 MAP_DEL_CURRENT(k);
1587 } DIGESTMAP_FOREACH_END;
1589 /* Check if we cleared the whole thing and free if so */
1590 if (digestmap_size(mbw_cache) == 0) {
1591 digestmap_free(mbw_cache, tor_free_);
1592 mbw_cache = 0;
1597 /** Get the current size of the measured bandwidth cache */
1598 STATIC int
1599 dirserv_get_measured_bw_cache_size(void)
1601 if (mbw_cache) return digestmap_size(mbw_cache);
1602 else return 0;
1605 /** Query the cache by identity digest, return value indicates whether
1606 * we found it. The bw_out and as_of_out pointers receive the cached
1607 * bandwidth value and the time it was cached if not NULL. */
1608 STATIC int
1609 dirserv_query_measured_bw_cache_kb(const char *node_id, long *bw_kb_out,
1610 time_t *as_of_out)
1612 mbw_cache_entry_t *v = NULL;
1613 int rv = 0;
1615 if (mbw_cache && node_id) {
1616 v = digestmap_get(mbw_cache, node_id);
1617 if (v) {
1618 /* Found something */
1619 rv = 1;
1620 if (bw_kb_out) *bw_kb_out = v->mbw_kb;
1621 if (as_of_out) *as_of_out = v->as_of;
1625 return rv;
1628 /** Predicate wrapper for dirserv_query_measured_bw_cache() */
1629 STATIC int
1630 dirserv_has_measured_bw(const char *node_id)
1632 return dirserv_query_measured_bw_cache_kb(node_id, NULL, NULL);
1635 /** Get the best estimate of a router's bandwidth for dirauth purposes,
1636 * preferring measured to advertised values if available. */
1638 static uint32_t
1639 dirserv_get_bandwidth_for_router_kb(const routerinfo_t *ri)
1641 uint32_t bw_kb = 0;
1643 * Yeah, measured bandwidths in measured_bw_line_t are (implicitly
1644 * signed) longs and the ones router_get_advertised_bandwidth() returns
1645 * are uint32_t.
1647 long mbw_kb = 0;
1649 if (ri) {
1651 * * First try to see if we have a measured bandwidth; don't bother with
1652 * as_of_out here, on the theory that a stale measured bandwidth is still
1653 * better to trust than an advertised one.
1655 if (dirserv_query_measured_bw_cache_kb(ri->cache_info.identity_digest,
1656 &mbw_kb, NULL)) {
1657 /* Got one! */
1658 bw_kb = (uint32_t)mbw_kb;
1659 } else {
1660 /* If not, fall back to advertised */
1661 bw_kb = router_get_advertised_bandwidth(ri) / 1000;
1665 return bw_kb;
1668 /** Look through the routerlist, and using the measured bandwidth cache count
1669 * how many measured bandwidths we know. This is used to decide whether we
1670 * ever trust advertised bandwidths for purposes of assigning flags. */
1671 static void
1672 dirserv_count_measured_bws(routerlist_t *rl)
1674 /* Initialize this first */
1675 routers_with_measured_bw = 0;
1677 tor_assert(rl);
1678 tor_assert(rl->routers);
1680 /* Iterate over the routerlist and count measured bandwidths */
1681 SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) {
1682 /* Check if we know a measured bandwidth for this one */
1683 if (dirserv_has_measured_bw(ri->cache_info.identity_digest)) {
1684 ++routers_with_measured_bw;
1686 } SMARTLIST_FOREACH_END(ri);
1689 /** Return the bandwidth we believe for assigning flags; prefer measured
1690 * over advertised, and if we have above a threshold quantity of measured
1691 * bandwidths, we don't want to ever give flags to unmeasured routers, so
1692 * return 0. */
1693 static uint32_t
1694 dirserv_get_credible_bandwidth_kb(const routerinfo_t *ri)
1696 int threshold;
1697 uint32_t bw_kb = 0;
1698 long mbw_kb;
1700 tor_assert(ri);
1701 /* Check if we have a measured bandwidth, and check the threshold if not */
1702 if (!(dirserv_query_measured_bw_cache_kb(ri->cache_info.identity_digest,
1703 &mbw_kb, NULL))) {
1704 threshold = get_options()->MinMeasuredBWsForAuthToIgnoreAdvertised;
1705 if (routers_with_measured_bw > threshold) {
1706 /* Return zero for unmeasured bandwidth if we are above threshold */
1707 bw_kb = 0;
1708 } else {
1709 /* Return an advertised bandwidth otherwise */
1710 bw_kb = router_get_advertised_bandwidth_capped(ri) / 1000;
1712 } else {
1713 /* We have the measured bandwidth in mbw */
1714 bw_kb = (uint32_t)mbw_kb;
1717 return bw_kb;
1720 /** Give a statement of our current performance thresholds for inclusion
1721 * in a vote document. */
1722 char *
1723 dirserv_get_flag_thresholds_line(void)
1725 char *result=NULL;
1726 const int measured_threshold =
1727 get_options()->MinMeasuredBWsForAuthToIgnoreAdvertised;
1728 const int enough_measured_bw = routers_with_measured_bw > measured_threshold;
1730 tor_asprintf(&result,
1731 "stable-uptime=%lu stable-mtbf=%lu "
1732 "fast-speed=%lu "
1733 "guard-wfu=%.03f%% guard-tk=%lu "
1734 "guard-bw-inc-exits=%lu guard-bw-exc-exits=%lu "
1735 "enough-mtbf=%d ignoring-advertised-bws=%d",
1736 (unsigned long)stable_uptime,
1737 (unsigned long)stable_mtbf,
1738 (unsigned long)fast_bandwidth_kb*1000,
1739 guard_wfu*100,
1740 (unsigned long)guard_tk,
1741 (unsigned long)guard_bandwidth_including_exits_kb*1000,
1742 (unsigned long)guard_bandwidth_excluding_exits_kb*1000,
1743 enough_mtbf_info ? 1 : 0,
1744 enough_measured_bw ? 1 : 0);
1746 return result;
1749 /** Given a platform string as in a routerinfo_t (possibly null), return a
1750 * newly allocated version string for a networkstatus document, or NULL if the
1751 * platform doesn't give a Tor version. */
1752 static char *
1753 version_from_platform(const char *platform)
1755 if (platform && !strcmpstart(platform, "Tor ")) {
1756 const char *eos = find_whitespace(platform+4);
1757 if (eos && !strcmpstart(eos, " (r")) {
1758 /* XXXX Unify this logic with the other version extraction
1759 * logic in routerparse.c. */
1760 eos = find_whitespace(eos+1);
1762 if (eos) {
1763 return tor_strndup(platform, eos-platform);
1766 return NULL;
1769 /** Helper: write the router-status information in <b>rs</b> into a newly
1770 * allocated character buffer. Use the same format as in network-status
1771 * documents. If <b>version</b> is non-NULL, add a "v" line for the platform.
1772 * Return 0 on success, -1 on failure.
1774 * The format argument has one of the following values:
1775 * NS_V2 - Output an entry suitable for a V2 NS opinion document
1776 * NS_V3_CONSENSUS - Output the first portion of a V3 NS consensus entry
1777 * NS_V3_CONSENSUS_MICRODESC - Output the first portion of a V3 microdesc
1778 * consensus entry.
1779 * NS_V3_VOTE - Output a complete V3 NS vote. If <b>vrs</b> is present,
1780 * it contains additional information for the vote.
1781 * NS_CONTROL_PORT - Output a NS document for the control port
1783 char *
1784 routerstatus_format_entry(const routerstatus_t *rs, const char *version,
1785 routerstatus_format_type_t format,
1786 const vote_routerstatus_t *vrs)
1788 char *summary;
1789 char *result = NULL;
1791 char published[ISO_TIME_LEN+1];
1792 char identity64[BASE64_DIGEST_LEN+1];
1793 char digest64[BASE64_DIGEST_LEN+1];
1794 smartlist_t *chunks = smartlist_new();
1796 format_iso_time(published, rs->published_on);
1797 digest_to_base64(identity64, rs->identity_digest);
1798 digest_to_base64(digest64, rs->descriptor_digest);
1800 smartlist_add_asprintf(chunks,
1801 "r %s %s %s%s%s %s %d %d\n",
1802 rs->nickname,
1803 identity64,
1804 (format==NS_V3_CONSENSUS_MICRODESC)?"":digest64,
1805 (format==NS_V3_CONSENSUS_MICRODESC)?"":" ",
1806 published,
1807 fmt_addr32(rs->addr),
1808 (int)rs->or_port,
1809 (int)rs->dir_port);
1811 /* TODO: Maybe we want to pass in what we need to build the rest of
1812 * this here, instead of in the caller. Then we could use the
1813 * networkstatus_type_t values, with an additional control port value
1814 * added -MP */
1816 /* V3 microdesc consensuses don't have "a" lines. */
1817 if (format == NS_V3_CONSENSUS_MICRODESC)
1818 goto done;
1820 /* Possible "a" line. At most one for now. */
1821 if (!tor_addr_is_null(&rs->ipv6_addr)) {
1822 smartlist_add_asprintf(chunks, "a %s\n",
1823 fmt_addrport(&rs->ipv6_addr, rs->ipv6_orport));
1826 if (format == NS_V3_CONSENSUS)
1827 goto done;
1829 smartlist_add_asprintf(chunks,
1830 "s%s%s%s%s%s%s%s%s%s%s\n",
1831 /* These must stay in alphabetical order. */
1832 rs->is_authority?" Authority":"",
1833 rs->is_bad_exit?" BadExit":"",
1834 rs->is_exit?" Exit":"",
1835 rs->is_fast?" Fast":"",
1836 rs->is_possible_guard?" Guard":"",
1837 rs->is_hs_dir?" HSDir":"",
1838 rs->is_flagged_running?" Running":"",
1839 rs->is_stable?" Stable":"",
1840 (rs->dir_port!=0)?" V2Dir":"",
1841 rs->is_valid?" Valid":"");
1843 /* length of "opt v \n" */
1844 #define V_LINE_OVERHEAD 7
1845 if (version && strlen(version) < MAX_V_LINE_LEN - V_LINE_OVERHEAD) {
1846 smartlist_add_asprintf(chunks, "v %s\n", version);
1849 if (format != NS_V2) {
1850 const routerinfo_t* desc = router_get_by_id_digest(rs->identity_digest);
1851 uint32_t bw_kb;
1853 if (format != NS_CONTROL_PORT) {
1854 /* Blow up more or less nicely if we didn't get anything or not the
1855 * thing we expected.
1857 if (!desc) {
1858 char id[HEX_DIGEST_LEN+1];
1859 char dd[HEX_DIGEST_LEN+1];
1861 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
1862 base16_encode(dd, sizeof(dd), rs->descriptor_digest, DIGEST_LEN);
1863 log_warn(LD_BUG, "Cannot get any descriptor for %s "
1864 "(wanted descriptor %s).",
1865 id, dd);
1866 goto err;
1869 /* This assert could fire for the control port, because
1870 * it can request NS documents before all descriptors
1871 * have been fetched. Therefore, we only do this test when
1872 * format != NS_CONTROL_PORT. */
1873 if (tor_memneq(desc->cache_info.signed_descriptor_digest,
1874 rs->descriptor_digest,
1875 DIGEST_LEN)) {
1876 char rl_d[HEX_DIGEST_LEN+1];
1877 char rs_d[HEX_DIGEST_LEN+1];
1878 char id[HEX_DIGEST_LEN+1];
1880 base16_encode(rl_d, sizeof(rl_d),
1881 desc->cache_info.signed_descriptor_digest, DIGEST_LEN);
1882 base16_encode(rs_d, sizeof(rs_d), rs->descriptor_digest, DIGEST_LEN);
1883 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
1884 log_err(LD_BUG, "descriptor digest in routerlist does not match "
1885 "the one in routerstatus: %s vs %s "
1886 "(router %s)\n",
1887 rl_d, rs_d, id);
1889 tor_assert(tor_memeq(desc->cache_info.signed_descriptor_digest,
1890 rs->descriptor_digest,
1891 DIGEST_LEN));
1895 if (format == NS_CONTROL_PORT && rs->has_bandwidth) {
1896 bw_kb = rs->bandwidth_kb;
1897 } else {
1898 tor_assert(desc);
1899 bw_kb = router_get_advertised_bandwidth_capped(desc) / 1000;
1901 smartlist_add_asprintf(chunks,
1902 "w Bandwidth=%d", bw_kb);
1904 if (format == NS_V3_VOTE && vrs && vrs->has_measured_bw) {
1905 smartlist_add_asprintf(chunks,
1906 " Measured=%d", vrs->measured_bw_kb);
1908 smartlist_add(chunks, tor_strdup("\n"));
1910 if (desc) {
1911 summary = policy_summarize(desc->exit_policy, AF_INET);
1912 smartlist_add_asprintf(chunks, "p %s\n", summary);
1913 tor_free(summary);
1917 done:
1918 result = smartlist_join_strings(chunks, "", 0, NULL);
1920 err:
1921 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
1922 smartlist_free(chunks);
1924 return result;
1927 /** Helper for sorting: compares two routerinfos first by address, and then by
1928 * descending order of "usefulness". (An authority is more useful than a
1929 * non-authority; a running router is more useful than a non-running router;
1930 * and a router with more bandwidth is more useful than one with less.)
1932 static int
1933 compare_routerinfo_by_ip_and_bw_(const void **a, const void **b)
1935 routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
1936 int first_is_auth, second_is_auth;
1937 uint32_t bw_kb_first, bw_kb_second;
1938 const node_t *node_first, *node_second;
1939 int first_is_running, second_is_running;
1941 /* we return -1 if first should appear before second... that is,
1942 * if first is a better router. */
1943 if (first->addr < second->addr)
1944 return -1;
1945 else if (first->addr > second->addr)
1946 return 1;
1948 /* Potentially, this next bit could cause k n lg n memeq calls. But in
1949 * reality, we will almost never get here, since addresses will usually be
1950 * different. */
1952 first_is_auth =
1953 router_digest_is_trusted_dir(first->cache_info.identity_digest);
1954 second_is_auth =
1955 router_digest_is_trusted_dir(second->cache_info.identity_digest);
1957 if (first_is_auth && !second_is_auth)
1958 return -1;
1959 else if (!first_is_auth && second_is_auth)
1960 return 1;
1962 node_first = node_get_by_id(first->cache_info.identity_digest);
1963 node_second = node_get_by_id(second->cache_info.identity_digest);
1964 first_is_running = node_first && node_first->is_running;
1965 second_is_running = node_second && node_second->is_running;
1967 if (first_is_running && !second_is_running)
1968 return -1;
1969 else if (!first_is_running && second_is_running)
1970 return 1;
1972 bw_kb_first = dirserv_get_bandwidth_for_router_kb(first);
1973 bw_kb_second = dirserv_get_bandwidth_for_router_kb(second);
1975 if (bw_kb_first > bw_kb_second)
1976 return -1;
1977 else if (bw_kb_first < bw_kb_second)
1978 return 1;
1980 /* They're equal! Compare by identity digest, so there's a
1981 * deterministic order and we avoid flapping. */
1982 return fast_memcmp(first->cache_info.identity_digest,
1983 second->cache_info.identity_digest,
1984 DIGEST_LEN);
1987 /** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
1988 * whose keys are the identity digests of those routers that we're going to
1989 * exclude for Sybil-like appearance. */
1990 static digestmap_t *
1991 get_possible_sybil_list(const smartlist_t *routers)
1993 const or_options_t *options = get_options();
1994 digestmap_t *omit_as_sybil;
1995 smartlist_t *routers_by_ip = smartlist_new();
1996 uint32_t last_addr;
1997 int addr_count;
1998 /* Allow at most this number of Tor servers on a single IP address, ... */
1999 int max_with_same_addr = options->AuthDirMaxServersPerAddr;
2000 /* ... unless it's a directory authority, in which case allow more. */
2001 int max_with_same_addr_on_authority = options->AuthDirMaxServersPerAuthAddr;
2002 if (max_with_same_addr <= 0)
2003 max_with_same_addr = INT_MAX;
2004 if (max_with_same_addr_on_authority <= 0)
2005 max_with_same_addr_on_authority = INT_MAX;
2007 smartlist_add_all(routers_by_ip, routers);
2008 smartlist_sort(routers_by_ip, compare_routerinfo_by_ip_and_bw_);
2009 omit_as_sybil = digestmap_new();
2011 last_addr = 0;
2012 addr_count = 0;
2013 SMARTLIST_FOREACH_BEGIN(routers_by_ip, routerinfo_t *, ri) {
2014 if (last_addr != ri->addr) {
2015 last_addr = ri->addr;
2016 addr_count = 1;
2017 } else if (++addr_count > max_with_same_addr) {
2018 if (!router_addr_is_trusted_dir(ri->addr) ||
2019 addr_count > max_with_same_addr_on_authority)
2020 digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
2022 } SMARTLIST_FOREACH_END(ri);
2024 smartlist_free(routers_by_ip);
2025 return omit_as_sybil;
2028 /** Return non-zero iff a relay running the Tor version specified in
2029 * <b>platform</b> is suitable for use as a potential entry guard. */
2030 static int
2031 is_router_version_good_for_possible_guard(const char *platform)
2033 static int parsed_versions_initialized = 0;
2034 static tor_version_t first_good_0_2_1_guard_version;
2035 static tor_version_t first_good_0_2_2_guard_version;
2036 static tor_version_t first_good_later_guard_version;
2038 tor_version_t router_version;
2040 /* XXX024 This block should be extracted into its own function. */
2041 /* XXXX Begin code copied from tor_version_as_new_as (in routerparse.c) */
2043 char *s, *s2, *start;
2044 char tmp[128];
2046 tor_assert(platform);
2048 /* nonstandard Tor; be safe and say yes */
2049 if (strcmpstart(platform,"Tor "))
2050 return 1;
2052 start = (char *)eat_whitespace(platform+3);
2053 if (!*start) return 0;
2054 s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
2055 s2 = (char*)eat_whitespace(s);
2056 if (!strcmpstart(s2, "(r") || !strcmpstart(s2, "(git-"))
2057 s = (char*)find_whitespace(s2);
2059 if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
2060 return 0;
2061 strlcpy(tmp, start, s-start+1);
2063 if (tor_version_parse(tmp, &router_version)<0) {
2064 log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
2065 return 1; /* be safe and say yes */
2068 /* XXXX End code copied from tor_version_as_new_as (in routerparse.c) */
2070 if (!parsed_versions_initialized) {
2071 /* CVE-2011-2769 was fixed on the relay side in Tor versions
2072 * 0.2.1.31, 0.2.2.34, and 0.2.3.6-alpha. */
2073 tor_assert(tor_version_parse("0.2.1.31",
2074 &first_good_0_2_1_guard_version)>=0);
2075 tor_assert(tor_version_parse("0.2.2.34",
2076 &first_good_0_2_2_guard_version)>=0);
2077 tor_assert(tor_version_parse("0.2.3.6-alpha",
2078 &first_good_later_guard_version)>=0);
2080 /* Don't parse these constant version strings once for every relay
2081 * for every vote. */
2082 parsed_versions_initialized = 1;
2085 return ((tor_version_same_series(&first_good_0_2_1_guard_version,
2086 &router_version) &&
2087 tor_version_compare(&first_good_0_2_1_guard_version,
2088 &router_version) <= 0) ||
2089 (tor_version_same_series(&first_good_0_2_2_guard_version,
2090 &router_version) &&
2091 tor_version_compare(&first_good_0_2_2_guard_version,
2092 &router_version) <= 0) ||
2093 (tor_version_compare(&first_good_later_guard_version,
2094 &router_version) <= 0));
2097 /** Extract status information from <b>ri</b> and from other authority
2098 * functions and store it in <b>rs</b>>.
2100 * We assume that ri-\>is_running has already been set, e.g. by
2101 * dirserv_set_router_is_running(ri, now);
2103 void
2104 set_routerstatus_from_routerinfo(routerstatus_t *rs,
2105 node_t *node,
2106 routerinfo_t *ri,
2107 time_t now,
2108 int listbadexits,
2109 int vote_on_hsdirs)
2111 const or_options_t *options = get_options();
2112 uint32_t routerbw_kb = dirserv_get_credible_bandwidth_kb(ri);
2114 memset(rs, 0, sizeof(routerstatus_t));
2116 rs->is_authority =
2117 router_digest_is_trusted_dir(ri->cache_info.identity_digest);
2119 /* Already set by compute_performance_thresholds. */
2120 rs->is_exit = node->is_exit;
2121 rs->is_stable = node->is_stable =
2122 router_is_active(ri, node, now) &&
2123 !dirserv_thinks_router_is_unreliable(now, ri, 1, 0);
2124 rs->is_fast = node->is_fast =
2125 router_is_active(ri, node, now) &&
2126 !dirserv_thinks_router_is_unreliable(now, ri, 0, 1);
2127 rs->is_flagged_running = node->is_running; /* computed above */
2129 rs->is_valid = node->is_valid;
2131 if (node->is_fast &&
2132 ((options->AuthDirGuardBWGuarantee &&
2133 routerbw_kb >= options->AuthDirGuardBWGuarantee/1000) ||
2134 routerbw_kb >= MIN(guard_bandwidth_including_exits_kb,
2135 guard_bandwidth_excluding_exits_kb)) &&
2136 is_router_version_good_for_possible_guard(ri->platform)) {
2137 long tk = rep_hist_get_weighted_time_known(
2138 node->identity, now);
2139 double wfu = rep_hist_get_weighted_fractional_uptime(
2140 node->identity, now);
2141 rs->is_possible_guard = (wfu >= guard_wfu && tk >= guard_tk) ? 1 : 0;
2142 } else {
2143 rs->is_possible_guard = 0;
2145 if (options->TestingTorNetwork &&
2146 routerset_contains_routerstatus(options->TestingDirAuthVoteGuard,
2147 rs, 0)) {
2148 rs->is_possible_guard = 1;
2151 rs->is_bad_exit = listbadexits && node->is_bad_exit;
2152 node->is_hs_dir = dirserv_thinks_router_is_hs_dir(ri, node, now);
2153 rs->is_hs_dir = vote_on_hsdirs && node->is_hs_dir;
2155 rs->is_named = rs->is_unnamed = 0;
2157 rs->published_on = ri->cache_info.published_on;
2158 memcpy(rs->identity_digest, node->identity, DIGEST_LEN);
2159 memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest,
2160 DIGEST_LEN);
2161 rs->addr = ri->addr;
2162 strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname));
2163 rs->or_port = ri->or_port;
2164 rs->dir_port = ri->dir_port;
2165 if (options->AuthDirHasIPv6Connectivity == 1 &&
2166 !tor_addr_is_null(&ri->ipv6_addr) &&
2167 node->last_reachable6 >= now - REACHABLE_TIMEOUT) {
2168 /* We're configured as having IPv6 connectivity. There's an IPv6
2169 OR port and it's reachable so copy it to the routerstatus. */
2170 tor_addr_copy(&rs->ipv6_addr, &ri->ipv6_addr);
2171 rs->ipv6_orport = ri->ipv6_orport;
2175 /** Routerstatus <b>rs</b> is part of a group of routers that are on
2176 * too narrow an IP-space. Clear out its flags: we don't want people
2177 * using it.
2179 static void
2180 clear_status_flags_on_sybil(routerstatus_t *rs)
2182 rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
2183 rs->is_flagged_running = rs->is_named = rs->is_valid =
2184 rs->is_hs_dir = rs->is_possible_guard = rs->is_bad_exit =
2185 rs->is_bad_directory = 0;
2186 /* FFFF we might want some mechanism to check later on if we
2187 * missed zeroing any flags: it's easy to add a new flag but
2188 * forget to add it to this clause. */
2192 * Helper function to parse out a line in the measured bandwidth file
2193 * into a measured_bw_line_t output structure. Returns -1 on failure
2194 * or 0 on success.
2196 STATIC int
2197 measured_bw_line_parse(measured_bw_line_t *out, const char *orig_line)
2199 char *line = tor_strdup(orig_line);
2200 char *cp = line;
2201 int got_bw = 0;
2202 int got_node_id = 0;
2203 char *strtok_state; /* lame sauce d'jour */
2204 cp = tor_strtok_r(cp, " \t", &strtok_state);
2206 if (!cp) {
2207 log_warn(LD_DIRSERV, "Invalid line in bandwidth file: %s",
2208 escaped(orig_line));
2209 tor_free(line);
2210 return -1;
2213 if (orig_line[strlen(orig_line)-1] != '\n') {
2214 log_warn(LD_DIRSERV, "Incomplete line in bandwidth file: %s",
2215 escaped(orig_line));
2216 tor_free(line);
2217 return -1;
2220 do {
2221 if (strcmpstart(cp, "bw=") == 0) {
2222 int parse_ok = 0;
2223 char *endptr;
2224 if (got_bw) {
2225 log_warn(LD_DIRSERV, "Double bw= in bandwidth file line: %s",
2226 escaped(orig_line));
2227 tor_free(line);
2228 return -1;
2230 cp+=strlen("bw=");
2232 out->bw_kb = tor_parse_long(cp, 0, 0, LONG_MAX, &parse_ok, &endptr);
2233 if (!parse_ok || (*endptr && !TOR_ISSPACE(*endptr))) {
2234 log_warn(LD_DIRSERV, "Invalid bandwidth in bandwidth file line: %s",
2235 escaped(orig_line));
2236 tor_free(line);
2237 return -1;
2239 got_bw=1;
2240 } else if (strcmpstart(cp, "node_id=$") == 0) {
2241 if (got_node_id) {
2242 log_warn(LD_DIRSERV, "Double node_id= in bandwidth file line: %s",
2243 escaped(orig_line));
2244 tor_free(line);
2245 return -1;
2247 cp+=strlen("node_id=$");
2249 if (strlen(cp) != HEX_DIGEST_LEN ||
2250 base16_decode(out->node_id, DIGEST_LEN, cp, HEX_DIGEST_LEN)) {
2251 log_warn(LD_DIRSERV, "Invalid node_id in bandwidth file line: %s",
2252 escaped(orig_line));
2253 tor_free(line);
2254 return -1;
2256 strlcpy(out->node_hex, cp, sizeof(out->node_hex));
2257 got_node_id=1;
2259 } while ((cp = tor_strtok_r(NULL, " \t", &strtok_state)));
2261 if (got_bw && got_node_id) {
2262 tor_free(line);
2263 return 0;
2264 } else {
2265 log_warn(LD_DIRSERV, "Incomplete line in bandwidth file: %s",
2266 escaped(orig_line));
2267 tor_free(line);
2268 return -1;
2273 * Helper function to apply a parsed measurement line to a list
2274 * of bandwidth statuses. Returns true if a line is found,
2275 * false otherwise.
2277 STATIC int
2278 measured_bw_line_apply(measured_bw_line_t *parsed_line,
2279 smartlist_t *routerstatuses)
2281 vote_routerstatus_t *rs = NULL;
2282 if (!routerstatuses)
2283 return 0;
2285 rs = smartlist_bsearch(routerstatuses, parsed_line->node_id,
2286 compare_digest_to_vote_routerstatus_entry);
2288 if (rs) {
2289 rs->has_measured_bw = 1;
2290 rs->measured_bw_kb = (uint32_t)parsed_line->bw_kb;
2291 } else {
2292 log_info(LD_DIRSERV, "Node ID %s not found in routerstatus list",
2293 parsed_line->node_hex);
2296 return rs != NULL;
2300 * Read the measured bandwidth file and apply it to the list of
2301 * vote_routerstatus_t. Returns -1 on error, 0 otherwise.
2304 dirserv_read_measured_bandwidths(const char *from_file,
2305 smartlist_t *routerstatuses)
2307 char line[256];
2308 FILE *fp = tor_fopen_cloexec(from_file, "r");
2309 int applied_lines = 0;
2310 time_t file_time, now;
2311 int ok;
2313 if (fp == NULL) {
2314 log_warn(LD_CONFIG, "Can't open bandwidth file at configured location: %s",
2315 from_file);
2316 return -1;
2319 if (!fgets(line, sizeof(line), fp)
2320 || !strlen(line) || line[strlen(line)-1] != '\n') {
2321 log_warn(LD_DIRSERV, "Long or truncated time in bandwidth file: %s",
2322 escaped(line));
2323 fclose(fp);
2324 return -1;
2327 line[strlen(line)-1] = '\0';
2328 file_time = (time_t)tor_parse_ulong(line, 10, 0, ULONG_MAX, &ok, NULL);
2329 if (!ok) {
2330 log_warn(LD_DIRSERV, "Non-integer time in bandwidth file: %s",
2331 escaped(line));
2332 fclose(fp);
2333 return -1;
2336 now = time(NULL);
2337 if ((now - file_time) > MAX_MEASUREMENT_AGE) {
2338 log_warn(LD_DIRSERV, "Bandwidth measurement file stale. Age: %u",
2339 (unsigned)(time(NULL) - file_time));
2340 fclose(fp);
2341 return -1;
2344 if (routerstatuses)
2345 smartlist_sort(routerstatuses, compare_vote_routerstatus_entries);
2347 while (!feof(fp)) {
2348 measured_bw_line_t parsed_line;
2349 if (fgets(line, sizeof(line), fp) && strlen(line)) {
2350 if (measured_bw_line_parse(&parsed_line, line) != -1) {
2351 /* Also cache the line for dirserv_get_bandwidth_for_router() */
2352 dirserv_cache_measured_bw(&parsed_line, file_time);
2353 if (measured_bw_line_apply(&parsed_line, routerstatuses) > 0)
2354 applied_lines++;
2359 /* Now would be a nice time to clean the cache, too */
2360 dirserv_expire_measured_bw_cache(now);
2362 fclose(fp);
2363 log_info(LD_DIRSERV,
2364 "Bandwidth measurement file successfully read. "
2365 "Applied %d measurements.", applied_lines);
2366 return 0;
2369 /** Return a new networkstatus_t* containing our current opinion. (For v3
2370 * authorities) */
2371 networkstatus_t *
2372 dirserv_generate_networkstatus_vote_obj(crypto_pk_t *private_key,
2373 authority_cert_t *cert)
2375 const or_options_t *options = get_options();
2376 networkstatus_t *v3_out = NULL;
2377 uint32_t addr;
2378 char *hostname = NULL, *client_versions = NULL, *server_versions = NULL;
2379 const char *contact;
2380 smartlist_t *routers, *routerstatuses;
2381 char identity_digest[DIGEST_LEN];
2382 char signing_key_digest[DIGEST_LEN];
2383 int listbadexits = options->AuthDirListBadExits;
2384 int vote_on_hsdirs = options->VoteOnHidServDirectoriesV2;
2385 routerlist_t *rl = router_get_routerlist();
2386 time_t now = time(NULL);
2387 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2388 networkstatus_voter_info_t *voter = NULL;
2389 vote_timing_t timing;
2390 digestmap_t *omit_as_sybil = NULL;
2391 const int vote_on_reachability = running_long_enough_to_decide_unreachable();
2392 smartlist_t *microdescriptors = NULL;
2394 tor_assert(private_key);
2395 tor_assert(cert);
2397 if (crypto_pk_get_digest(private_key, signing_key_digest)<0) {
2398 log_err(LD_BUG, "Error computing signing key digest");
2399 return NULL;
2401 if (crypto_pk_get_digest(cert->identity_key, identity_digest)<0) {
2402 log_err(LD_BUG, "Error computing identity key digest");
2403 return NULL;
2405 if (resolve_my_address(LOG_WARN, options, &addr, NULL, &hostname)<0) {
2406 log_warn(LD_NET, "Couldn't resolve my hostname");
2407 return NULL;
2409 if (!hostname || !strchr(hostname, '.')) {
2410 tor_free(hostname);
2411 hostname = tor_dup_ip(addr);
2414 if (options->VersioningAuthoritativeDir) {
2415 client_versions = format_versions_list(options->RecommendedClientVersions);
2416 server_versions = format_versions_list(options->RecommendedServerVersions);
2419 contact = get_options()->ContactInfo;
2420 if (!contact)
2421 contact = "(none)";
2424 * Do this so dirserv_compute_performance_thresholds() and
2425 * set_routerstatus_from_routerinfo() see up-to-date bandwidth info.
2427 if (options->V3BandwidthsFile) {
2428 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
2429 } else {
2431 * No bandwidths file; clear the measured bandwidth cache in case we had
2432 * one last time around.
2434 if (dirserv_get_measured_bw_cache_size() > 0) {
2435 dirserv_clear_measured_bw_cache();
2439 /* precompute this part, since we need it to decide what "stable"
2440 * means. */
2441 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2442 dirserv_set_router_is_running(ri, now);
2445 routers = smartlist_new();
2446 smartlist_add_all(routers, rl->routers);
2447 routers_sort_by_identity(routers);
2448 omit_as_sybil = get_possible_sybil_list(routers);
2450 DIGESTMAP_FOREACH(omit_as_sybil, sybil_id, void *, ignore) {
2451 (void) ignore;
2452 rep_hist_make_router_pessimal(sybil_id, now);
2453 } DIGESTMAP_FOREACH_END;
2455 /* Count how many have measured bandwidths so we know how to assign flags;
2456 * this must come before dirserv_compute_performance_thresholds() */
2457 dirserv_count_measured_bws(rl);
2459 dirserv_compute_performance_thresholds(rl, omit_as_sybil);
2461 routerstatuses = smartlist_new();
2462 microdescriptors = smartlist_new();
2464 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
2465 if (ri->cache_info.published_on >= cutoff) {
2466 routerstatus_t *rs;
2467 vote_routerstatus_t *vrs;
2468 node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
2469 if (!node)
2470 continue;
2472 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
2473 rs = &vrs->status;
2474 set_routerstatus_from_routerinfo(rs, node, ri, now,
2475 listbadexits,
2476 vote_on_hsdirs);
2478 if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
2479 clear_status_flags_on_sybil(rs);
2481 if (!vote_on_reachability)
2482 rs->is_flagged_running = 0;
2484 vrs->version = version_from_platform(ri->platform);
2485 vrs->microdesc = dirvote_format_all_microdesc_vote_lines(ri, now,
2486 microdescriptors);
2488 smartlist_add(routerstatuses, vrs);
2490 } SMARTLIST_FOREACH_END(ri);
2493 smartlist_t *added =
2494 microdescs_add_list_to_cache(get_microdesc_cache(),
2495 microdescriptors, SAVED_NOWHERE, 0);
2496 smartlist_free(added);
2497 smartlist_free(microdescriptors);
2500 smartlist_free(routers);
2501 digestmap_free(omit_as_sybil, NULL);
2503 /* This pass through applies the measured bw lines to the routerstatuses */
2504 if (options->V3BandwidthsFile) {
2505 dirserv_read_measured_bandwidths(options->V3BandwidthsFile,
2506 routerstatuses);
2507 } else {
2509 * No bandwidths file; clear the measured bandwidth cache in case we had
2510 * one last time around.
2512 if (dirserv_get_measured_bw_cache_size() > 0) {
2513 dirserv_clear_measured_bw_cache();
2517 v3_out = tor_malloc_zero(sizeof(networkstatus_t));
2519 v3_out->type = NS_TYPE_VOTE;
2520 dirvote_get_preferred_voting_intervals(&timing);
2521 v3_out->published = now;
2523 char tbuf[ISO_TIME_LEN+1];
2524 networkstatus_t *current_consensus =
2525 networkstatus_get_live_consensus(now);
2526 long last_consensus_interval; /* only used to pick a valid_after */
2527 if (current_consensus)
2528 last_consensus_interval = current_consensus->fresh_until -
2529 current_consensus->valid_after;
2530 else
2531 last_consensus_interval = options->TestingV3AuthInitialVotingInterval;
2532 v3_out->valid_after =
2533 dirvote_get_start_of_next_interval(now, (int)last_consensus_interval,
2534 options->TestingV3AuthVotingStartOffset);
2535 format_iso_time(tbuf, v3_out->valid_after);
2536 log_notice(LD_DIR,"Choosing valid-after time in vote as %s: "
2537 "consensus_set=%d, last_interval=%d",
2538 tbuf, current_consensus?1:0, (int)last_consensus_interval);
2540 v3_out->fresh_until = v3_out->valid_after + timing.vote_interval;
2541 v3_out->valid_until = v3_out->valid_after +
2542 (timing.vote_interval * timing.n_intervals_valid);
2543 v3_out->vote_seconds = timing.vote_delay;
2544 v3_out->dist_seconds = timing.dist_delay;
2545 tor_assert(v3_out->vote_seconds > 0);
2546 tor_assert(v3_out->dist_seconds > 0);
2547 tor_assert(timing.n_intervals_valid > 0);
2549 v3_out->client_versions = client_versions;
2550 v3_out->server_versions = server_versions;
2551 v3_out->known_flags = smartlist_new();
2552 smartlist_split_string(v3_out->known_flags,
2553 "Authority Exit Fast Guard Stable V2Dir Valid",
2554 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2555 if (vote_on_reachability)
2556 smartlist_add(v3_out->known_flags, tor_strdup("Running"));
2557 if (listbadexits)
2558 smartlist_add(v3_out->known_flags, tor_strdup("BadExit"));
2559 if (vote_on_hsdirs)
2560 smartlist_add(v3_out->known_flags, tor_strdup("HSDir"));
2561 smartlist_sort_strings(v3_out->known_flags);
2563 if (options->ConsensusParams) {
2564 v3_out->net_params = smartlist_new();
2565 smartlist_split_string(v3_out->net_params,
2566 options->ConsensusParams, NULL, 0, 0);
2567 smartlist_sort_strings(v3_out->net_params);
2570 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
2571 voter->nickname = tor_strdup(options->Nickname);
2572 memcpy(voter->identity_digest, identity_digest, DIGEST_LEN);
2573 voter->sigs = smartlist_new();
2574 voter->address = hostname;
2575 voter->addr = addr;
2576 voter->dir_port = router_get_advertised_dir_port(options, 0);
2577 voter->or_port = router_get_advertised_or_port(options);
2578 voter->contact = tor_strdup(contact);
2579 if (options->V3AuthUseLegacyKey) {
2580 authority_cert_t *c = get_my_v3_legacy_cert();
2581 if (c) {
2582 if (crypto_pk_get_digest(c->identity_key, voter->legacy_id_digest)) {
2583 log_warn(LD_BUG, "Unable to compute digest of legacy v3 identity key");
2584 memset(voter->legacy_id_digest, 0, DIGEST_LEN);
2589 v3_out->voters = smartlist_new();
2590 smartlist_add(v3_out->voters, voter);
2591 v3_out->cert = authority_cert_dup(cert);
2592 v3_out->routerstatus_list = routerstatuses;
2593 /* Note: networkstatus_digest is unset; it won't get set until we actually
2594 * format the vote. */
2596 return v3_out;
2599 /** As dirserv_get_routerdescs(), but instead of getting signed_descriptor_t
2600 * pointers, adds copies of digests to fps_out, and doesn't use the
2601 * /tor/server/ prefix. For a /d/ request, adds descriptor digests; for other
2602 * requests, adds identity digests.
2605 dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
2606 const char **msg, int for_unencrypted_conn,
2607 int is_extrainfo)
2609 int by_id = 1;
2610 *msg = NULL;
2612 if (!strcmp(key, "all")) {
2613 routerlist_t *rl = router_get_routerlist();
2614 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2615 smartlist_add(fps_out,
2616 tor_memdup(r->cache_info.identity_digest, DIGEST_LEN)));
2617 /* Treat "all" requests as if they were unencrypted */
2618 for_unencrypted_conn = 1;
2619 } else if (!strcmp(key, "authority")) {
2620 const routerinfo_t *ri = router_get_my_routerinfo();
2621 if (ri)
2622 smartlist_add(fps_out,
2623 tor_memdup(ri->cache_info.identity_digest, DIGEST_LEN));
2624 } else if (!strcmpstart(key, "d/")) {
2625 by_id = 0;
2626 key += strlen("d/");
2627 dir_split_resource_into_fingerprints(key, fps_out, NULL,
2628 DSR_HEX|DSR_SORT_UNIQ);
2629 } else if (!strcmpstart(key, "fp/")) {
2630 key += strlen("fp/");
2631 dir_split_resource_into_fingerprints(key, fps_out, NULL,
2632 DSR_HEX|DSR_SORT_UNIQ);
2633 } else {
2634 *msg = "Key not recognized";
2635 return -1;
2638 if (for_unencrypted_conn) {
2639 /* Remove anything that insists it not be sent unencrypted. */
2640 SMARTLIST_FOREACH_BEGIN(fps_out, char *, cp) {
2641 const signed_descriptor_t *sd;
2642 if (by_id)
2643 sd = get_signed_descriptor_by_fp(cp,is_extrainfo,0);
2644 else if (is_extrainfo)
2645 sd = extrainfo_get_by_descriptor_digest(cp);
2646 else
2647 sd = router_get_by_descriptor_digest(cp);
2648 if (sd && !sd->send_unencrypted) {
2649 tor_free(cp);
2650 SMARTLIST_DEL_CURRENT(fps_out, cp);
2652 } SMARTLIST_FOREACH_END(cp);
2655 if (!smartlist_len(fps_out)) {
2656 *msg = "Servers unavailable";
2657 return -1;
2659 return 0;
2662 /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
2663 * <b>key</b>. The key should be either
2664 * - "/tor/server/authority" for our own routerinfo;
2665 * - "/tor/server/all" for all the routerinfos we have, concatenated;
2666 * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
2667 * hex identity digests; or
2668 * - "/tor/server/d/D" where D is a plus-separated sequence
2669 * of server descriptor digests, in hex.
2671 * Return 0 if we found some matching descriptors, or -1 if we do not
2672 * have any descriptors, no matching descriptors, or if we did not
2673 * recognize the key (URL).
2674 * If -1 is returned *<b>msg</b> will be set to an appropriate error
2675 * message.
2677 * XXXX rename this function. It's only called from the controller.
2678 * XXXX in fact, refactor this function, merging as much as possible.
2681 dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
2682 const char **msg)
2684 *msg = NULL;
2686 if (!strcmp(key, "/tor/server/all")) {
2687 routerlist_t *rl = router_get_routerlist();
2688 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2689 smartlist_add(descs_out, &(r->cache_info)));
2690 } else if (!strcmp(key, "/tor/server/authority")) {
2691 const routerinfo_t *ri = router_get_my_routerinfo();
2692 if (ri)
2693 smartlist_add(descs_out, (void*) &(ri->cache_info));
2694 } else if (!strcmpstart(key, "/tor/server/d/")) {
2695 smartlist_t *digests = smartlist_new();
2696 key += strlen("/tor/server/d/");
2697 dir_split_resource_into_fingerprints(key, digests, NULL,
2698 DSR_HEX|DSR_SORT_UNIQ);
2699 SMARTLIST_FOREACH(digests, const char *, d,
2701 signed_descriptor_t *sd = router_get_by_descriptor_digest(d);
2702 if (sd)
2703 smartlist_add(descs_out,sd);
2705 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
2706 smartlist_free(digests);
2707 } else if (!strcmpstart(key, "/tor/server/fp/")) {
2708 smartlist_t *digests = smartlist_new();
2709 time_t cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
2710 key += strlen("/tor/server/fp/");
2711 dir_split_resource_into_fingerprints(key, digests, NULL,
2712 DSR_HEX|DSR_SORT_UNIQ);
2713 SMARTLIST_FOREACH_BEGIN(digests, const char *, d) {
2714 if (router_digest_is_me(d)) {
2715 /* make sure desc_routerinfo exists */
2716 const routerinfo_t *ri = router_get_my_routerinfo();
2717 if (ri)
2718 smartlist_add(descs_out, (void*) &(ri->cache_info));
2719 } else {
2720 const routerinfo_t *ri = router_get_by_id_digest(d);
2721 /* Don't actually serve a descriptor that everyone will think is
2722 * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
2723 * Tors from downloading descriptors that they will throw away.
2725 if (ri && ri->cache_info.published_on > cutoff)
2726 smartlist_add(descs_out, (void*) &(ri->cache_info));
2728 } SMARTLIST_FOREACH_END(d);
2729 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
2730 smartlist_free(digests);
2731 } else {
2732 *msg = "Key not recognized";
2733 return -1;
2736 if (!smartlist_len(descs_out)) {
2737 *msg = "Servers unavailable";
2738 return -1;
2740 return 0;
2743 /** Called when a TLS handshake has completed successfully with a
2744 * router listening at <b>address</b>:<b>or_port</b>, and has yielded
2745 * a certificate with digest <b>digest_rcvd</b>.
2747 * Inform the reachability checker that we could get to this guy.
2749 void
2750 dirserv_orconn_tls_done(const tor_addr_t *addr,
2751 uint16_t or_port,
2752 const char *digest_rcvd)
2754 node_t *node = NULL;
2755 tor_addr_port_t orport;
2756 routerinfo_t *ri = NULL;
2757 time_t now = time(NULL);
2758 tor_assert(addr);
2759 tor_assert(digest_rcvd);
2761 node = node_get_mutable_by_id(digest_rcvd);
2762 if (node == NULL || node->ri == NULL)
2763 return;
2764 ri = node->ri;
2766 tor_addr_copy(&orport.addr, addr);
2767 orport.port = or_port;
2768 if (router_has_orport(ri, &orport)) {
2769 /* Found the right router. */
2770 if (!authdir_mode_bridge(get_options()) ||
2771 ri->purpose == ROUTER_PURPOSE_BRIDGE) {
2772 char addrstr[TOR_ADDR_BUF_LEN];
2773 /* This is a bridge or we're not a bridge authorititative --
2774 mark it as reachable. */
2775 log_info(LD_DIRSERV, "Found router %s to be reachable at %s:%d. Yay.",
2776 router_describe(ri),
2777 tor_addr_to_str(addrstr, addr, sizeof(addrstr), 1),
2778 ri->or_port);
2779 if (tor_addr_family(addr) == AF_INET) {
2780 rep_hist_note_router_reachable(digest_rcvd, addr, or_port, now);
2781 node->last_reachable = now;
2782 } else if (tor_addr_family(addr) == AF_INET6) {
2783 /* No rephist for IPv6. */
2784 node->last_reachable6 = now;
2790 /** Called when we, as an authority, receive a new router descriptor either as
2791 * an upload or a download. Used to decide whether to relaunch reachability
2792 * testing for the server. */
2794 dirserv_should_launch_reachability_test(const routerinfo_t *ri,
2795 const routerinfo_t *ri_old)
2797 if (!authdir_mode_handles_descs(get_options(), ri->purpose))
2798 return 0;
2799 if (!ri_old) {
2800 /* New router: Launch an immediate reachability test, so we will have an
2801 * opinion soon in case we're generating a consensus soon */
2802 return 1;
2804 if (ri_old->is_hibernating && !ri->is_hibernating) {
2805 /* It just came out of hibernation; launch a reachability test */
2806 return 1;
2808 if (! routers_have_same_or_addrs(ri, ri_old)) {
2809 /* Address or port changed; launch a reachability test */
2810 return 1;
2812 return 0;
2815 /** Helper function for dirserv_test_reachability(). Start a TLS
2816 * connection to <b>router</b>, and annotate it with when we started
2817 * the test. */
2818 void
2819 dirserv_single_reachability_test(time_t now, routerinfo_t *router)
2821 channel_t *chan = NULL;
2822 node_t *node = NULL;
2823 tor_addr_t router_addr;
2824 (void) now;
2826 tor_assert(router);
2827 node = node_get_mutable_by_id(router->cache_info.identity_digest);
2828 tor_assert(node);
2830 /* IPv4. */
2831 log_debug(LD_OR,"Testing reachability of %s at %s:%u.",
2832 router->nickname, fmt_addr32(router->addr), router->or_port);
2833 tor_addr_from_ipv4h(&router_addr, router->addr);
2834 chan = channel_tls_connect(&router_addr, router->or_port,
2835 router->cache_info.identity_digest);
2836 if (chan) command_setup_channel(chan);
2838 /* Possible IPv6. */
2839 if (get_options()->AuthDirHasIPv6Connectivity == 1 &&
2840 !tor_addr_is_null(&router->ipv6_addr)) {
2841 char addrstr[TOR_ADDR_BUF_LEN];
2842 log_debug(LD_OR, "Testing reachability of %s at %s:%u.",
2843 router->nickname,
2844 tor_addr_to_str(addrstr, &router->ipv6_addr, sizeof(addrstr), 1),
2845 router->ipv6_orport);
2846 chan = channel_tls_connect(&router->ipv6_addr, router->ipv6_orport,
2847 router->cache_info.identity_digest);
2848 if (chan) command_setup_channel(chan);
2852 /** Auth dir server only: load balance such that we only
2853 * try a few connections per call.
2855 * The load balancing is such that if we get called once every ten
2856 * seconds, we will cycle through all the tests in
2857 * REACHABILITY_TEST_CYCLE_PERIOD seconds (a bit over 20 minutes).
2859 void
2860 dirserv_test_reachability(time_t now)
2862 /* XXX decide what to do here; see or-talk thread "purging old router
2863 * information, revocation." -NM
2864 * We can't afford to mess with this in 0.1.2.x. The reason is that
2865 * if we stop doing reachability tests on some of routerlist, then
2866 * we'll for-sure think they're down, which may have unexpected
2867 * effects in other parts of the code. It doesn't hurt much to do
2868 * the testing, and directory authorities are easy to upgrade. Let's
2869 * wait til 0.2.0. -RD */
2870 // time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2871 routerlist_t *rl = router_get_routerlist();
2872 static char ctr = 0;
2873 int bridge_auth = authdir_mode_bridge(get_options());
2875 SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, router) {
2876 const char *id_digest = router->cache_info.identity_digest;
2877 if (router_is_me(router))
2878 continue;
2879 if (bridge_auth && router->purpose != ROUTER_PURPOSE_BRIDGE)
2880 continue; /* bridge authorities only test reachability on bridges */
2881 // if (router->cache_info.published_on > cutoff)
2882 // continue;
2883 if ((((uint8_t)id_digest[0]) % REACHABILITY_MODULO_PER_TEST) == ctr) {
2884 dirserv_single_reachability_test(now, router);
2886 } SMARTLIST_FOREACH_END(router);
2887 ctr = (ctr + 1) % REACHABILITY_MODULO_PER_TEST; /* increment ctr */
2890 /** Given a fingerprint <b>fp</b> which is either set if we're looking for a
2891 * v2 status, or zeroes if we're looking for a v3 status, or a NUL-padded
2892 * flavor name if we want a flavored v3 status, return a pointer to the
2893 * appropriate cached dir object, or NULL if there isn't one available. */
2894 static cached_dir_t *
2895 lookup_cached_dir_by_fp(const char *fp)
2897 cached_dir_t *d = NULL;
2898 if (tor_digest_is_zero(fp) && cached_consensuses) {
2899 d = strmap_get(cached_consensuses, "ns");
2900 } else if (memchr(fp, '\0', DIGEST_LEN) && cached_consensuses &&
2901 (d = strmap_get(cached_consensuses, fp))) {
2902 /* this here interface is a nasty hack XXXX024 */;
2904 return d;
2907 /** Remove from <b>fps</b> every networkstatus key where both
2908 * a) we have a networkstatus document and
2909 * b) it is not newer than <b>cutoff</b>.
2911 * Return 1 if any items were present at all; else return 0.
2914 dirserv_remove_old_statuses(smartlist_t *fps, time_t cutoff)
2916 int found_any = 0;
2917 SMARTLIST_FOREACH_BEGIN(fps, char *, digest) {
2918 cached_dir_t *d = lookup_cached_dir_by_fp(digest);
2919 if (!d)
2920 continue;
2921 found_any = 1;
2922 if (d->published <= cutoff) {
2923 tor_free(digest);
2924 SMARTLIST_DEL_CURRENT(fps, digest);
2926 } SMARTLIST_FOREACH_END(digest);
2928 return found_any;
2931 /** Return the cache-info for identity fingerprint <b>fp</b>, or
2932 * its extra-info document if <b>extrainfo</b> is true. Return
2933 * NULL if not found or if the descriptor is older than
2934 * <b>publish_cutoff</b>. */
2935 static const signed_descriptor_t *
2936 get_signed_descriptor_by_fp(const char *fp, int extrainfo,
2937 time_t publish_cutoff)
2939 if (router_digest_is_me(fp)) {
2940 if (extrainfo)
2941 return &(router_get_my_extrainfo()->cache_info);
2942 else
2943 return &(router_get_my_routerinfo()->cache_info);
2944 } else {
2945 const routerinfo_t *ri = router_get_by_id_digest(fp);
2946 if (ri &&
2947 ri->cache_info.published_on > publish_cutoff) {
2948 if (extrainfo)
2949 return extrainfo_get_by_descriptor_digest(
2950 ri->cache_info.extra_info_digest);
2951 else
2952 return &ri->cache_info;
2955 return NULL;
2958 /** Return true iff we have any of the documents (extrainfo or routerdesc)
2959 * specified by the fingerprints in <b>fps</b> and <b>spool_src</b>. Used to
2960 * decide whether to send a 404. */
2962 dirserv_have_any_serverdesc(smartlist_t *fps, int spool_src)
2964 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
2965 SMARTLIST_FOREACH_BEGIN(fps, const char *, fp) {
2966 switch (spool_src)
2968 case DIR_SPOOL_EXTRA_BY_DIGEST:
2969 if (extrainfo_get_by_descriptor_digest(fp)) return 1;
2970 break;
2971 case DIR_SPOOL_SERVER_BY_DIGEST:
2972 if (router_get_by_descriptor_digest(fp)) return 1;
2973 break;
2974 case DIR_SPOOL_EXTRA_BY_FP:
2975 case DIR_SPOOL_SERVER_BY_FP:
2976 if (get_signed_descriptor_by_fp(fp,
2977 spool_src == DIR_SPOOL_EXTRA_BY_FP, publish_cutoff))
2978 return 1;
2979 break;
2981 } SMARTLIST_FOREACH_END(fp);
2982 return 0;
2985 /** Return true iff any of the 256-bit elements in <b>fps</b> is the digest of
2986 * a microdescriptor we have. */
2988 dirserv_have_any_microdesc(const smartlist_t *fps)
2990 microdesc_cache_t *cache = get_microdesc_cache();
2991 SMARTLIST_FOREACH(fps, const char *, fp,
2992 if (microdesc_cache_lookup_by_digest256(cache, fp))
2993 return 1);
2994 return 0;
2997 /** Return an approximate estimate of the number of bytes that will
2998 * be needed to transmit the server descriptors (if is_serverdescs --
2999 * they can be either d/ or fp/ queries) or networkstatus objects (if
3000 * !is_serverdescs) listed in <b>fps</b>. If <b>compressed</b> is set,
3001 * we guess how large the data will be after compression.
3003 * The return value is an estimate; it might be larger or smaller.
3005 size_t
3006 dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
3007 int compressed)
3009 size_t result;
3010 tor_assert(fps);
3011 if (is_serverdescs) {
3012 int n = smartlist_len(fps);
3013 const routerinfo_t *me = router_get_my_routerinfo();
3014 result = (me?me->cache_info.signed_descriptor_len:2048) * n;
3015 if (compressed)
3016 result /= 2; /* observed compressibility is between 35 and 55%. */
3017 } else {
3018 result = 0;
3019 SMARTLIST_FOREACH(fps, const char *, digest, {
3020 cached_dir_t *dir = lookup_cached_dir_by_fp(digest);
3021 if (dir)
3022 result += compressed ? dir->dir_z_len : dir->dir_len;
3025 return result;
3028 /** Given a list of microdescriptor hashes, guess how many bytes will be
3029 * needed to transmit them, and return the guess. */
3030 size_t
3031 dirserv_estimate_microdesc_size(const smartlist_t *fps, int compressed)
3033 size_t result = smartlist_len(fps) * microdesc_average_size(NULL);
3034 if (compressed)
3035 result /= 2;
3036 return result;
3039 /** When we're spooling data onto our outbuf, add more whenever we dip
3040 * below this threshold. */
3041 #define DIRSERV_BUFFER_MIN 16384
3043 /** Spooling helper: called when we have no more data to spool to <b>conn</b>.
3044 * Flushes any remaining data to be (un)compressed, and changes the spool
3045 * source to NONE. Returns 0 on success, negative on failure. */
3046 static int
3047 connection_dirserv_finish_spooling(dir_connection_t *conn)
3049 if (conn->zlib_state) {
3050 connection_write_to_buf_zlib("", 0, conn, 1);
3051 tor_zlib_free(conn->zlib_state);
3052 conn->zlib_state = NULL;
3054 conn->dir_spool_src = DIR_SPOOL_NONE;
3055 return 0;
3058 /** Spooling helper: called when we're sending a bunch of server descriptors,
3059 * and the outbuf has become too empty. Pulls some entries from
3060 * fingerprint_stack, and writes the corresponding servers onto outbuf. If we
3061 * run out of entries, flushes the zlib state and sets the spool source to
3062 * NONE. Returns 0 on success, negative on failure.
3064 static int
3065 connection_dirserv_add_servers_to_outbuf(dir_connection_t *conn)
3067 int by_fp = (conn->dir_spool_src == DIR_SPOOL_SERVER_BY_FP ||
3068 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP);
3069 int extra = (conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP ||
3070 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_DIGEST);
3071 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
3073 const or_options_t *options = get_options();
3075 while (smartlist_len(conn->fingerprint_stack) &&
3076 connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
3077 const char *body;
3078 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3079 const signed_descriptor_t *sd = NULL;
3080 if (by_fp) {
3081 sd = get_signed_descriptor_by_fp(fp, extra, publish_cutoff);
3082 } else {
3083 sd = extra ? extrainfo_get_by_descriptor_digest(fp)
3084 : router_get_by_descriptor_digest(fp);
3086 tor_free(fp);
3087 if (!sd)
3088 continue;
3089 if (!connection_dir_is_encrypted(conn) && !sd->send_unencrypted) {
3090 /* we did this check once before (so we could have an accurate size
3091 * estimate and maybe send a 404 if somebody asked for only bridges on a
3092 * connection), but we need to do it again in case a previously
3093 * unknown bridge descriptor has shown up between then and now. */
3094 continue;
3097 /** If we are the bridge authority and the descriptor is a bridge
3098 * descriptor, remember that we served this descriptor for desc stats. */
3099 if (options->BridgeAuthoritativeDir && by_fp) {
3100 const routerinfo_t *router =
3101 router_get_by_id_digest(sd->identity_digest);
3102 /* router can be NULL here when the bridge auth is asked for its own
3103 * descriptor. */
3104 if (router && router->purpose == ROUTER_PURPOSE_BRIDGE)
3105 rep_hist_note_desc_served(sd->identity_digest);
3107 body = signed_descriptor_get_body(sd);
3108 if (conn->zlib_state) {
3109 int last = ! smartlist_len(conn->fingerprint_stack);
3110 connection_write_to_buf_zlib(body, sd->signed_descriptor_len, conn,
3111 last);
3112 if (last) {
3113 tor_zlib_free(conn->zlib_state);
3114 conn->zlib_state = NULL;
3116 } else {
3117 connection_write_to_buf(body,
3118 sd->signed_descriptor_len,
3119 TO_CONN(conn));
3123 if (!smartlist_len(conn->fingerprint_stack)) {
3124 /* We just wrote the last one; finish up. */
3125 if (conn->zlib_state) {
3126 connection_write_to_buf_zlib("", 0, conn, 1);
3127 tor_zlib_free(conn->zlib_state);
3128 conn->zlib_state = NULL;
3130 conn->dir_spool_src = DIR_SPOOL_NONE;
3131 smartlist_free(conn->fingerprint_stack);
3132 conn->fingerprint_stack = NULL;
3134 return 0;
3137 /** Spooling helper: called when we're sending a bunch of microdescriptors,
3138 * and the outbuf has become too empty. Pulls some entries from
3139 * fingerprint_stack, and writes the corresponding microdescs onto outbuf. If
3140 * we run out of entries, flushes the zlib state and sets the spool source to
3141 * NONE. Returns 0 on success, negative on failure.
3143 static int
3144 connection_dirserv_add_microdescs_to_outbuf(dir_connection_t *conn)
3146 microdesc_cache_t *cache = get_microdesc_cache();
3147 while (smartlist_len(conn->fingerprint_stack) &&
3148 connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
3149 char *fp256 = smartlist_pop_last(conn->fingerprint_stack);
3150 microdesc_t *md = microdesc_cache_lookup_by_digest256(cache, fp256);
3151 tor_free(fp256);
3152 if (!md || !md->body)
3153 continue;
3154 if (conn->zlib_state) {
3155 int last = !smartlist_len(conn->fingerprint_stack);
3156 connection_write_to_buf_zlib(md->body, md->bodylen, conn, last);
3157 if (last) {
3158 tor_zlib_free(conn->zlib_state);
3159 conn->zlib_state = NULL;
3161 } else {
3162 connection_write_to_buf(md->body, md->bodylen, TO_CONN(conn));
3165 if (!smartlist_len(conn->fingerprint_stack)) {
3166 if (conn->zlib_state) {
3167 connection_write_to_buf_zlib("", 0, conn, 1);
3168 tor_zlib_free(conn->zlib_state);
3169 conn->zlib_state = NULL;
3171 conn->dir_spool_src = DIR_SPOOL_NONE;
3172 smartlist_free(conn->fingerprint_stack);
3173 conn->fingerprint_stack = NULL;
3175 return 0;
3178 /** Spooling helper: Called when we're sending a directory or networkstatus,
3179 * and the outbuf has become too empty. Pulls some bytes from
3180 * <b>conn</b>-\>cached_dir-\>dir_z, uncompresses them if appropriate, and
3181 * puts them on the outbuf. If we run out of entries, flushes the zlib state
3182 * and sets the spool source to NONE. Returns 0 on success, negative on
3183 * failure. */
3184 static int
3185 connection_dirserv_add_dir_bytes_to_outbuf(dir_connection_t *conn)
3187 ssize_t bytes;
3188 int64_t remaining;
3190 bytes = DIRSERV_BUFFER_MIN - connection_get_outbuf_len(TO_CONN(conn));
3191 tor_assert(bytes > 0);
3192 tor_assert(conn->cached_dir);
3193 if (bytes < 8192)
3194 bytes = 8192;
3195 remaining = conn->cached_dir->dir_z_len - conn->cached_dir_offset;
3196 if (bytes > remaining)
3197 bytes = (ssize_t) remaining;
3199 if (conn->zlib_state) {
3200 connection_write_to_buf_zlib(
3201 conn->cached_dir->dir_z + conn->cached_dir_offset,
3202 bytes, conn, bytes == remaining);
3203 } else {
3204 connection_write_to_buf(conn->cached_dir->dir_z + conn->cached_dir_offset,
3205 bytes, TO_CONN(conn));
3207 conn->cached_dir_offset += bytes;
3208 if (conn->cached_dir_offset == (int)conn->cached_dir->dir_z_len) {
3209 /* We just wrote the last one; finish up. */
3210 connection_dirserv_finish_spooling(conn);
3211 cached_dir_decref(conn->cached_dir);
3212 conn->cached_dir = NULL;
3214 return 0;
3217 /** Spooling helper: Called when we're spooling networkstatus objects on
3218 * <b>conn</b>, and the outbuf has become too empty. If the current
3219 * networkstatus object (in <b>conn</b>-\>cached_dir) has more data, pull data
3220 * from there. Otherwise, pop the next fingerprint from fingerprint_stack,
3221 * and start spooling the next networkstatus. (A digest of all 0 bytes is
3222 * treated as a request for the current consensus.) If we run out of entries,
3223 * flushes the zlib state and sets the spool source to NONE. Returns 0 on
3224 * success, negative on failure. */
3225 static int
3226 connection_dirserv_add_networkstatus_bytes_to_outbuf(dir_connection_t *conn)
3229 while (connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
3230 if (conn->cached_dir) {
3231 int uncompressing = (conn->zlib_state != NULL);
3232 int r = connection_dirserv_add_dir_bytes_to_outbuf(conn);
3233 if (conn->dir_spool_src == DIR_SPOOL_NONE) {
3234 /* add_dir_bytes thinks we're done with the cached_dir. But we
3235 * may have more cached_dirs! */
3236 conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
3237 /* This bit is tricky. If we were uncompressing the last
3238 * networkstatus, we may need to make a new zlib object to
3239 * uncompress the next one. */
3240 if (uncompressing && ! conn->zlib_state &&
3241 conn->fingerprint_stack &&
3242 smartlist_len(conn->fingerprint_stack)) {
3243 conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
3246 if (r) return r;
3247 } else if (conn->fingerprint_stack &&
3248 smartlist_len(conn->fingerprint_stack)) {
3249 /* Add another networkstatus; start serving it. */
3250 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3251 cached_dir_t *d = lookup_cached_dir_by_fp(fp);
3252 tor_free(fp);
3253 if (d) {
3254 ++d->refcnt;
3255 conn->cached_dir = d;
3256 conn->cached_dir_offset = 0;
3258 } else {
3259 connection_dirserv_finish_spooling(conn);
3260 smartlist_free(conn->fingerprint_stack);
3261 conn->fingerprint_stack = NULL;
3262 return 0;
3265 return 0;
3268 /** Called whenever we have flushed some directory data in state
3269 * SERVER_WRITING. */
3271 connection_dirserv_flushed_some(dir_connection_t *conn)
3273 tor_assert(conn->base_.state == DIR_CONN_STATE_SERVER_WRITING);
3275 if (connection_get_outbuf_len(TO_CONN(conn)) >= DIRSERV_BUFFER_MIN)
3276 return 0;
3278 switch (conn->dir_spool_src) {
3279 case DIR_SPOOL_EXTRA_BY_DIGEST:
3280 case DIR_SPOOL_EXTRA_BY_FP:
3281 case DIR_SPOOL_SERVER_BY_DIGEST:
3282 case DIR_SPOOL_SERVER_BY_FP:
3283 return connection_dirserv_add_servers_to_outbuf(conn);
3284 case DIR_SPOOL_MICRODESC:
3285 return connection_dirserv_add_microdescs_to_outbuf(conn);
3286 case DIR_SPOOL_CACHED_DIR:
3287 return connection_dirserv_add_dir_bytes_to_outbuf(conn);
3288 case DIR_SPOOL_NETWORKSTATUS:
3289 return connection_dirserv_add_networkstatus_bytes_to_outbuf(conn);
3290 case DIR_SPOOL_NONE:
3291 default:
3292 return 0;
3296 /** Release all storage used by the directory server. */
3297 void
3298 dirserv_free_all(void)
3300 dirserv_free_fingerprint_list();
3302 strmap_free(cached_consensuses, free_cached_dir_);
3303 cached_consensuses = NULL;
3305 dirserv_clear_measured_bw_cache();