Use dir_compressed(_len) instead of dir_z(_len).
[tor.git] / src / or / dirserv.c
blobbbff13fb9a25d172a3ca021d471f8cb4a468f373
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2017, 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 "conscache.h"
17 #include "control.h"
18 #include "directory.h"
19 #include "dirserv.h"
20 #include "dirvote.h"
21 #include "hibernate.h"
22 #include "keypin.h"
23 #include "main.h"
24 #include "microdesc.h"
25 #include "networkstatus.h"
26 #include "nodelist.h"
27 #include "policies.h"
28 #include "protover.h"
29 #include "rephist.h"
30 #include "router.h"
31 #include "routerlist.h"
32 #include "routerparse.h"
33 #include "routerset.h"
34 #include "torcert.h"
36 /**
37 * \file dirserv.c
38 * \brief Directory server core implementation. Manages directory
39 * contents and generates directories.
41 * This module implements most of directory cache functionality, and some of
42 * the directory authority functionality. The directory.c module delegates
43 * here in order to handle incoming requests from clients, via
44 * connection_dirserv_flushed_some() and its kin. In order to save RAM, this
45 * module is reponsible for spooling directory objects (in whole or in part)
46 * onto buf_t instances, and then closing the dir_connection_t once the
47 * objects are totally flushed.
49 * The directory.c module also delegates here for handling descriptor uploads
50 * via dirserv_add_multiple_descriptors().
52 * Additionally, this module handles some aspects of voting, including:
53 * deciding how to vote on individual flags (based on decisions reached in
54 * rephist.c), of formatting routerstatus lines, and deciding what relays to
55 * include in an authority's vote. (TODO: Those functions could profitably be
56 * split off. They only live in this file because historically they were
57 * shared among the v1, v2, and v3 directory code.)
60 /** How far in the future do we allow a router to get? (seconds) */
61 #define ROUTER_ALLOW_SKEW (60*60*12)
62 /** How many seconds do we wait before regenerating the directory? */
63 #define DIR_REGEN_SLACK_TIME 30
64 /** If we're a cache, keep this many networkstatuses around from non-trusted
65 * directory authorities. */
66 #define MAX_UNTRUSTED_NETWORKSTATUSES 16
68 /** Total number of routers with measured bandwidth; this is set by
69 * dirserv_count_measured_bws() before the loop in
70 * dirserv_generate_networkstatus_vote_obj() and checked by
71 * dirserv_get_credible_bandwidth() and
72 * dirserv_compute_performance_thresholds() */
73 static int routers_with_measured_bw = 0;
75 static void directory_remove_invalid(void);
76 static char *format_versions_list(config_line_t *ln);
77 struct authdir_config_t;
78 static uint32_t
79 dirserv_get_status_impl(const char *fp, const char *nickname,
80 uint32_t addr, uint16_t or_port,
81 const char *platform, const char **msg,
82 int severity);
83 static void clear_cached_dir(cached_dir_t *d);
84 static const signed_descriptor_t *get_signed_descriptor_by_fp(
85 const uint8_t *fp,
86 int extrainfo);
87 static was_router_added_t dirserv_add_extrainfo(extrainfo_t *ei,
88 const char **msg);
89 static uint32_t dirserv_get_bandwidth_for_router_kb(const routerinfo_t *ri);
90 static uint32_t dirserv_get_credible_bandwidth_kb(const routerinfo_t *ri);
92 static int spooled_resource_lookup_body(const spooled_resource_t *spooled,
93 int conn_is_encrypted,
94 const uint8_t **body_out,
95 size_t *size_out,
96 time_t *published_out);
97 static cached_dir_t *spooled_resource_lookup_cached_dir(
98 const spooled_resource_t *spooled,
99 time_t *published_out);
100 static cached_dir_t *lookup_cached_dir_by_fp(const uint8_t *fp);
102 /************** Fingerprint handling code ************/
104 /* 1 Historically used to indicate Named */
105 #define FP_INVALID 2 /**< Believed invalid. */
106 #define FP_REJECT 4 /**< We will not publish this router. */
107 /* 8 Historically used to avoid using this as a dir. */
108 #define FP_BADEXIT 16 /**< We'll tell clients not to use this as an exit. */
109 /* 32 Historically used to indicade Unnamed */
111 /** Target of status_by_digest map. */
112 typedef uint32_t router_status_t;
114 static void add_fingerprint_to_dir(const char *fp,
115 struct authdir_config_t *list,
116 router_status_t add_status);
118 /** List of nickname-\>identity fingerprint mappings for all the routers
119 * that we name. Used to prevent router impersonation. */
120 typedef struct authdir_config_t {
121 strmap_t *fp_by_name; /**< Map from lc nickname to fingerprint. */
122 digestmap_t *status_by_digest; /**< Map from digest to router_status_t. */
123 } authdir_config_t;
125 /** Should be static; exposed for testing. */
126 static authdir_config_t *fingerprint_list = NULL;
128 /** Allocate and return a new, empty, authdir_config_t. */
129 static authdir_config_t *
130 authdir_config_new(void)
132 authdir_config_t *list = tor_malloc_zero(sizeof(authdir_config_t));
133 list->fp_by_name = strmap_new();
134 list->status_by_digest = digestmap_new();
135 return list;
138 /** Add the fingerprint <b>fp</b> to the smartlist of fingerprint_entry_t's
139 * <b>list</b>, or-ing the currently set status flags with
140 * <b>add_status</b>.
142 /* static */ void
143 add_fingerprint_to_dir(const char *fp, authdir_config_t *list,
144 router_status_t add_status)
146 char *fingerprint;
147 char d[DIGEST_LEN];
148 router_status_t *status;
149 tor_assert(fp);
150 tor_assert(list);
152 fingerprint = tor_strdup(fp);
153 tor_strstrip(fingerprint, " ");
154 if (base16_decode(d, DIGEST_LEN,
155 fingerprint, strlen(fingerprint)) != DIGEST_LEN) {
156 log_warn(LD_DIRSERV, "Couldn't decode fingerprint \"%s\"",
157 escaped(fp));
158 tor_free(fingerprint);
159 return;
162 status = digestmap_get(list->status_by_digest, d);
163 if (!status) {
164 status = tor_malloc_zero(sizeof(router_status_t));
165 digestmap_set(list->status_by_digest, d, status);
168 tor_free(fingerprint);
169 *status |= add_status;
170 return;
173 /** Add the fingerprint for this OR to the global list of recognized
174 * identity key fingerprints. */
176 dirserv_add_own_fingerprint(crypto_pk_t *pk)
178 char fp[FINGERPRINT_LEN+1];
179 if (crypto_pk_get_fingerprint(pk, fp, 0)<0) {
180 log_err(LD_BUG, "Error computing fingerprint");
181 return -1;
183 if (!fingerprint_list)
184 fingerprint_list = authdir_config_new();
185 add_fingerprint_to_dir(fp, fingerprint_list, 0);
186 return 0;
189 /** Load the nickname-\>fingerprint mappings stored in the approved-routers
190 * file. The file format is line-based, with each non-blank holding one
191 * nickname, some space, and a fingerprint for that nickname. On success,
192 * replace the current fingerprint list with the new list and return 0. On
193 * failure, leave the current fingerprint list untouched, and return -1. */
195 dirserv_load_fingerprint_file(void)
197 char *fname;
198 char *cf;
199 char *nickname, *fingerprint;
200 authdir_config_t *fingerprint_list_new;
201 int result;
202 config_line_t *front=NULL, *list;
204 fname = get_datadir_fname("approved-routers");
205 log_info(LD_GENERAL,
206 "Reloading approved fingerprints from \"%s\"...", fname);
208 cf = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
209 if (!cf) {
210 log_warn(LD_FS, "Cannot open fingerprint file '%s'. That's ok.", fname);
211 tor_free(fname);
212 return 0;
214 tor_free(fname);
216 result = config_get_lines(cf, &front, 0);
217 tor_free(cf);
218 if (result < 0) {
219 log_warn(LD_CONFIG, "Error reading from fingerprint file");
220 return -1;
223 fingerprint_list_new = authdir_config_new();
225 for (list=front; list; list=list->next) {
226 char digest_tmp[DIGEST_LEN];
227 router_status_t add_status = 0;
228 nickname = list->key; fingerprint = list->value;
229 tor_strstrip(fingerprint, " "); /* remove spaces */
230 if (strlen(fingerprint) != HEX_DIGEST_LEN ||
231 base16_decode(digest_tmp, sizeof(digest_tmp),
232 fingerprint, HEX_DIGEST_LEN) != sizeof(digest_tmp)) {
233 log_notice(LD_CONFIG,
234 "Invalid fingerprint (nickname '%s', "
235 "fingerprint %s). Skipping.",
236 nickname, fingerprint);
237 continue;
239 if (!strcasecmp(nickname, "!reject")) {
240 add_status = FP_REJECT;
241 } else if (!strcasecmp(nickname, "!badexit")) {
242 add_status = FP_BADEXIT;
243 } else if (!strcasecmp(nickname, "!invalid")) {
244 add_status = FP_INVALID;
246 add_fingerprint_to_dir(fingerprint, fingerprint_list_new, add_status);
249 config_free_lines(front);
250 dirserv_free_fingerprint_list();
251 fingerprint_list = fingerprint_list_new;
252 /* Delete any routers whose fingerprints we no longer recognize */
253 directory_remove_invalid();
254 return 0;
257 /* If this is set, then we don't allow routers that have advertised an Ed25519
258 * identity to stop doing so. This is going to be essential for good identity
259 * security: otherwise anybody who can attack RSA-1024 but not Ed25519 could
260 * just sign fake descriptors missing the Ed25519 key. But we won't actually
261 * be able to prevent that kind of thing until we're confident that there
262 * isn't actually a legit reason to downgrade to 0.2.5. So for now, we have
263 * to leave this #undef.
265 #undef DISABLE_DISABLING_ED25519
267 /** Check whether <b>router</b> has a nickname/identity key combination that
268 * we recognize from the fingerprint list, or an IP we automatically act on
269 * according to our configuration. Return the appropriate router status.
271 * If the status is 'FP_REJECT' and <b>msg</b> is provided, set
272 * *<b>msg</b> to an explanation of why. */
273 uint32_t
274 dirserv_router_get_status(const routerinfo_t *router, const char **msg,
275 int severity)
277 char d[DIGEST_LEN];
278 const int key_pinning = get_options()->AuthDirPinKeys;
280 if (crypto_pk_get_digest(router->identity_pkey, d)) {
281 log_warn(LD_BUG,"Error computing fingerprint");
282 if (msg)
283 *msg = "Bug: Error computing fingerprint";
284 return FP_REJECT;
287 /* dirserv_get_status_impl already rejects versions older than 0.2.4.18-rc,
288 * and onion_curve25519_pkey was introduced in 0.2.4.8-alpha.
289 * But just in case a relay doesn't provide or lies about its version, or
290 * doesn't include an ntor key in its descriptor, check that it exists,
291 * and is non-zero (clients check that it's non-zero before using it). */
292 if (!routerinfo_has_curve25519_onion_key(router)) {
293 log_fn(severity, LD_DIR,
294 "Descriptor from router %s is missing an ntor curve25519 onion "
295 "key.", router_describe(router));
296 if (msg)
297 *msg = "Missing ntor curve25519 onion key. Please upgrade!";
298 return FP_REJECT;
301 if (router->cache_info.signing_key_cert) {
302 /* This has an ed25519 identity key. */
303 if (KEYPIN_MISMATCH ==
304 keypin_check((const uint8_t*)router->cache_info.identity_digest,
305 router->cache_info.signing_key_cert->signing_key.pubkey)) {
306 log_fn(severity, LD_DIR,
307 "Descriptor from router %s has an Ed25519 key, "
308 "but the <rsa,ed25519> keys don't match what they were before.",
309 router_describe(router));
310 if (key_pinning) {
311 if (msg) {
312 *msg = "Ed25519 identity key or RSA identity key has changed.";
314 return FP_REJECT;
317 } else {
318 /* No ed25519 key */
319 if (KEYPIN_MISMATCH == keypin_check_lone_rsa(
320 (const uint8_t*)router->cache_info.identity_digest)) {
321 log_fn(severity, LD_DIR,
322 "Descriptor from router %s has no Ed25519 key, "
323 "when we previously knew an Ed25519 for it. Ignoring for now, "
324 "since Ed25519 keys are fairly new.",
325 router_describe(router));
326 #ifdef DISABLE_DISABLING_ED25519
327 if (key_pinning) {
328 if (msg) {
329 *msg = "Ed25519 identity key has disappeared.";
331 return FP_REJECT;
333 #endif
337 return dirserv_get_status_impl(d, router->nickname,
338 router->addr, router->or_port,
339 router->platform, msg, severity);
342 /** Return true if there is no point in downloading the router described by
343 * <b>rs</b> because this directory would reject it. */
345 dirserv_would_reject_router(const routerstatus_t *rs)
347 uint32_t res;
349 res = dirserv_get_status_impl(rs->identity_digest, rs->nickname,
350 rs->addr, rs->or_port,
351 NULL, NULL, LOG_DEBUG);
353 return (res & FP_REJECT) != 0;
356 /** Helper: As dirserv_router_get_status, but takes the router fingerprint
357 * (hex, no spaces), nickname, address (used for logging only), IP address, OR
358 * port and platform (logging only) as arguments.
360 * Log messages at 'severity'. (There's not much point in
361 * logging that we're rejecting servers we'll not download.)
363 static uint32_t
364 dirserv_get_status_impl(const char *id_digest, const char *nickname,
365 uint32_t addr, uint16_t or_port,
366 const char *platform, const char **msg, int severity)
368 uint32_t result = 0;
369 router_status_t *status_by_digest;
371 if (!fingerprint_list)
372 fingerprint_list = authdir_config_new();
374 log_debug(LD_DIRSERV, "%d fingerprints, %d digests known.",
375 strmap_size(fingerprint_list->fp_by_name),
376 digestmap_size(fingerprint_list->status_by_digest));
378 if (platform) {
379 tor_version_t ver_tmp;
380 if (tor_version_parse_platform(platform, &ver_tmp, 1) < 0) {
381 if (msg) {
382 *msg = "Malformed platform string.";
384 return FP_REJECT;
388 /* Versions before Tor 0.2.4.18-rc are too old to support, and are
389 * missing some important security fixes too. Disable them. */
390 if (platform && !tor_version_as_new_as(platform,"0.2.4.18-rc")) {
391 if (msg)
392 *msg = "Tor version is insecure or unsupported. Please upgrade!";
393 return FP_REJECT;
396 status_by_digest = digestmap_get(fingerprint_list->status_by_digest,
397 id_digest);
398 if (status_by_digest)
399 result |= *status_by_digest;
401 if (result & FP_REJECT) {
402 if (msg)
403 *msg = "Fingerprint is marked rejected -- please contact us?";
404 return FP_REJECT;
405 } else if (result & FP_INVALID) {
406 if (msg)
407 *msg = "Fingerprint is marked invalid";
410 if (authdir_policy_badexit_address(addr, or_port)) {
411 log_fn(severity, LD_DIRSERV,
412 "Marking '%s' as bad exit because of address '%s'",
413 nickname, fmt_addr32(addr));
414 result |= FP_BADEXIT;
417 if (!authdir_policy_permits_address(addr, or_port)) {
418 log_fn(severity, LD_DIRSERV, "Rejecting '%s' because of address '%s'",
419 nickname, fmt_addr32(addr));
420 if (msg)
421 *msg = "Suspicious relay address range -- please contact us?";
422 return FP_REJECT;
424 if (!authdir_policy_valid_address(addr, or_port)) {
425 log_fn(severity, LD_DIRSERV,
426 "Not marking '%s' valid because of address '%s'",
427 nickname, fmt_addr32(addr));
428 result |= FP_INVALID;
431 return result;
434 /** Clear the current fingerprint list. */
435 void
436 dirserv_free_fingerprint_list(void)
438 if (!fingerprint_list)
439 return;
441 strmap_free(fingerprint_list->fp_by_name, tor_free_);
442 digestmap_free(fingerprint_list->status_by_digest, tor_free_);
443 tor_free(fingerprint_list);
447 * Descriptor list
450 /** Return -1 if <b>ri</b> has a private or otherwise bad address,
451 * unless we're configured to not care. Return 0 if all ok. */
452 static int
453 dirserv_router_has_valid_address(routerinfo_t *ri)
455 tor_addr_t addr;
456 if (get_options()->DirAllowPrivateAddresses)
457 return 0; /* whatever it is, we're fine with it */
458 tor_addr_from_ipv4h(&addr, ri->addr);
460 if (tor_addr_is_internal(&addr, 0)) {
461 log_info(LD_DIRSERV,
462 "Router %s published internal IP address. Refusing.",
463 router_describe(ri));
464 return -1; /* it's a private IP, we should reject it */
466 return 0;
469 /** Check whether we, as a directory server, want to accept <b>ri</b>. If so,
470 * set its is_valid,running fields and return 0. Otherwise, return -1.
472 * If the router is rejected, set *<b>msg</b> to an explanation of why.
474 * If <b>complain</b> then explain at log-level 'notice' why we refused
475 * a descriptor; else explain at log-level 'info'.
478 authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
479 int complain, int *valid_out)
481 /* Okay. Now check whether the fingerprint is recognized. */
482 time_t now;
483 int severity = (complain && ri->contact_info) ? LOG_NOTICE : LOG_INFO;
484 uint32_t status = dirserv_router_get_status(ri, msg, severity);
485 tor_assert(msg);
486 if (status & FP_REJECT)
487 return -1; /* msg is already set. */
489 /* Is there too much clock skew? */
490 now = time(NULL);
491 if (ri->cache_info.published_on > now+ROUTER_ALLOW_SKEW) {
492 log_fn(severity, LD_DIRSERV, "Publication time for %s is too "
493 "far (%d minutes) in the future; possible clock skew. Not adding "
494 "(%s)",
495 router_describe(ri),
496 (int)((ri->cache_info.published_on-now)/60),
497 esc_router_info(ri));
498 *msg = "Rejected: Your clock is set too far in the future, or your "
499 "timezone is not correct.";
500 return -1;
502 if (ri->cache_info.published_on < now-ROUTER_MAX_AGE_TO_PUBLISH) {
503 log_fn(severity, LD_DIRSERV,
504 "Publication time for %s is too far "
505 "(%d minutes) in the past. Not adding (%s)",
506 router_describe(ri),
507 (int)((now-ri->cache_info.published_on)/60),
508 esc_router_info(ri));
509 *msg = "Rejected: Server is expired, or your clock is too far in the past,"
510 " or your timezone is not correct.";
511 return -1;
513 if (dirserv_router_has_valid_address(ri) < 0) {
514 log_fn(severity, LD_DIRSERV,
515 "Router %s has invalid address. Not adding (%s).",
516 router_describe(ri),
517 esc_router_info(ri));
518 *msg = "Rejected: Address is a private address.";
519 return -1;
522 *valid_out = ! (status & FP_INVALID);
524 return 0;
527 /** Update the relevant flags of <b>node</b> based on our opinion as a
528 * directory authority in <b>authstatus</b>, as returned by
529 * dirserv_router_get_status or equivalent. */
530 void
531 dirserv_set_node_flags_from_authoritative_status(node_t *node,
532 uint32_t authstatus)
534 node->is_valid = (authstatus & FP_INVALID) ? 0 : 1;
535 node->is_bad_exit = (authstatus & FP_BADEXIT) ? 1 : 0;
538 /** True iff <b>a</b> is more severe than <b>b</b>. */
539 static int
540 WRA_MORE_SEVERE(was_router_added_t a, was_router_added_t b)
542 return a < b;
545 /** As for dirserv_add_descriptor(), but accepts multiple documents, and
546 * returns the most severe error that occurred for any one of them. */
547 was_router_added_t
548 dirserv_add_multiple_descriptors(const char *desc, uint8_t purpose,
549 const char *source,
550 const char **msg)
552 was_router_added_t r, r_tmp;
553 const char *msg_out;
554 smartlist_t *list;
555 const char *s;
556 int n_parsed = 0;
557 time_t now = time(NULL);
558 char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
559 char time_buf[ISO_TIME_LEN+1];
560 int general = purpose == ROUTER_PURPOSE_GENERAL;
561 tor_assert(msg);
563 r=ROUTER_ADDED_SUCCESSFULLY; /*Least severe return value. */
565 format_iso_time(time_buf, now);
566 if (tor_snprintf(annotation_buf, sizeof(annotation_buf),
567 "@uploaded-at %s\n"
568 "@source %s\n"
569 "%s%s%s", time_buf, escaped(source),
570 !general ? "@purpose " : "",
571 !general ? router_purpose_to_string(purpose) : "",
572 !general ? "\n" : "")<0) {
573 *msg = "Couldn't format annotations";
574 /* XXX Not cool: we return -1 below, but (was_router_added_t)-1 is
575 * ROUTER_BAD_EI, which isn't what's gone wrong here. :( */
576 return -1;
579 s = desc;
580 list = smartlist_new();
581 if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 0, 0,
582 annotation_buf, NULL)) {
583 SMARTLIST_FOREACH(list, routerinfo_t *, ri, {
584 msg_out = NULL;
585 tor_assert(ri->purpose == purpose);
586 r_tmp = dirserv_add_descriptor(ri, &msg_out, source);
587 if (WRA_MORE_SEVERE(r_tmp, r)) {
588 r = r_tmp;
589 *msg = msg_out;
593 n_parsed += smartlist_len(list);
594 smartlist_clear(list);
596 s = desc;
597 if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 1, 0,
598 NULL, NULL)) {
599 SMARTLIST_FOREACH(list, extrainfo_t *, ei, {
600 msg_out = NULL;
602 r_tmp = dirserv_add_extrainfo(ei, &msg_out);
603 if (WRA_MORE_SEVERE(r_tmp, r)) {
604 r = r_tmp;
605 *msg = msg_out;
609 n_parsed += smartlist_len(list);
610 smartlist_free(list);
612 if (! *msg) {
613 if (!n_parsed) {
614 *msg = "No descriptors found in your POST.";
615 if (WRA_WAS_ADDED(r))
616 r = ROUTER_IS_ALREADY_KNOWN;
617 } else {
618 *msg = "(no message)";
622 return r;
625 /** Examine the parsed server descriptor in <b>ri</b> and maybe insert it into
626 * the list of server descriptors. Set *<b>msg</b> to a message that should be
627 * passed back to the origin of this descriptor, or NULL if there is no such
628 * message. Use <b>source</b> to produce better log messages.
630 * Return the status of the operation
632 * This function is only called when fresh descriptors are posted, not when
633 * we re-load the cache.
635 was_router_added_t
636 dirserv_add_descriptor(routerinfo_t *ri, const char **msg, const char *source)
638 was_router_added_t r;
639 routerinfo_t *ri_old;
640 char *desc, *nickname;
641 const size_t desclen = ri->cache_info.signed_descriptor_len +
642 ri->cache_info.annotations_len;
643 const int key_pinning = get_options()->AuthDirPinKeys;
644 *msg = NULL;
646 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
647 * network and it'll clog everything up. */
648 if (ri->cache_info.signed_descriptor_len > MAX_DESCRIPTOR_UPLOAD_SIZE) {
649 log_notice(LD_DIR, "Somebody attempted to publish a router descriptor '%s'"
650 " (source: %s) with size %d. Either this is an attack, or the "
651 "MAX_DESCRIPTOR_UPLOAD_SIZE (%d) constant is too low.",
652 ri->nickname, source, (int)ri->cache_info.signed_descriptor_len,
653 MAX_DESCRIPTOR_UPLOAD_SIZE);
654 *msg = "Router descriptor was too large.";
655 control_event_or_authdir_new_descriptor("REJECTED",
656 ri->cache_info.signed_descriptor_body,
657 desclen, *msg);
658 routerinfo_free(ri);
659 return ROUTER_AUTHDIR_REJECTS;
662 /* Check whether this descriptor is semantically identical to the last one
663 * from this server. (We do this here and not in router_add_to_routerlist
664 * because we want to be able to accept the newest router descriptor that
665 * another authority has, so we all converge on the same one.) */
666 ri_old = router_get_mutable_by_digest(ri->cache_info.identity_digest);
667 if (ri_old && ri_old->cache_info.published_on < ri->cache_info.published_on
668 && router_differences_are_cosmetic(ri_old, ri)
669 && !router_is_me(ri)) {
670 log_info(LD_DIRSERV,
671 "Not replacing descriptor from %s (source: %s); "
672 "differences are cosmetic.",
673 router_describe(ri), source);
674 *msg = "Not replacing router descriptor; no information has changed since "
675 "the last one with this identity.";
676 control_event_or_authdir_new_descriptor("DROPPED",
677 ri->cache_info.signed_descriptor_body,
678 desclen, *msg);
679 routerinfo_free(ri);
680 return ROUTER_IS_ALREADY_KNOWN;
683 /* Do keypinning again ... this time, to add the pin if appropriate */
684 int keypin_status;
685 if (ri->cache_info.signing_key_cert) {
686 keypin_status = keypin_check_and_add(
687 (const uint8_t*)ri->cache_info.identity_digest,
688 ri->cache_info.signing_key_cert->signing_key.pubkey,
689 ! key_pinning);
690 } else {
691 keypin_status = keypin_check_lone_rsa(
692 (const uint8_t*)ri->cache_info.identity_digest);
693 #ifndef DISABLE_DISABLING_ED25519
694 if (keypin_status == KEYPIN_MISMATCH)
695 keypin_status = KEYPIN_NOT_FOUND;
696 #endif
698 if (keypin_status == KEYPIN_MISMATCH && key_pinning) {
699 log_info(LD_DIRSERV, "Dropping descriptor from %s (source: %s) because "
700 "its key did not match an older RSA/Ed25519 keypair",
701 router_describe(ri), source);
702 *msg = "Looks like your keypair does not match its older value.";
703 return ROUTER_AUTHDIR_REJECTS;
706 /* Make a copy of desc, since router_add_to_routerlist might free
707 * ri and its associated signed_descriptor_t. */
708 desc = tor_strndup(ri->cache_info.signed_descriptor_body, desclen);
709 nickname = tor_strdup(ri->nickname);
711 /* Tell if we're about to need to launch a test if we add this. */
712 ri->needs_retest_if_added =
713 dirserv_should_launch_reachability_test(ri, ri_old);
715 r = router_add_to_routerlist(ri, msg, 0, 0);
716 if (!WRA_WAS_ADDED(r)) {
717 /* unless the routerinfo was fine, just out-of-date */
718 if (WRA_WAS_REJECTED(r))
719 control_event_or_authdir_new_descriptor("REJECTED", desc, desclen, *msg);
720 log_info(LD_DIRSERV,
721 "Did not add descriptor from '%s' (source: %s): %s.",
722 nickname, source, *msg ? *msg : "(no message)");
723 } else {
724 smartlist_t *changed;
725 control_event_or_authdir_new_descriptor("ACCEPTED", desc, desclen, *msg);
727 changed = smartlist_new();
728 smartlist_add(changed, ri);
729 routerlist_descriptors_added(changed, 0);
730 smartlist_free(changed);
731 if (!*msg) {
732 *msg = "Descriptor accepted";
734 log_info(LD_DIRSERV,
735 "Added descriptor from '%s' (source: %s): %s.",
736 nickname, source, *msg);
738 tor_free(desc);
739 tor_free(nickname);
740 return r;
743 /** As dirserv_add_descriptor, but for an extrainfo_t <b>ei</b>. */
744 static was_router_added_t
745 dirserv_add_extrainfo(extrainfo_t *ei, const char **msg)
747 routerinfo_t *ri;
748 int r;
749 tor_assert(msg);
750 *msg = NULL;
752 /* Needs to be mutable so routerinfo_incompatible_with_extrainfo
753 * can mess with some of the flags in ri->cache_info. */
754 ri = router_get_mutable_by_digest(ei->cache_info.identity_digest);
755 if (!ri) {
756 *msg = "No corresponding router descriptor for extra-info descriptor";
757 extrainfo_free(ei);
758 return ROUTER_BAD_EI;
761 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
762 * network and it'll clog everything up. */
763 if (ei->cache_info.signed_descriptor_len > MAX_EXTRAINFO_UPLOAD_SIZE) {
764 log_notice(LD_DIR, "Somebody attempted to publish an extrainfo "
765 "with size %d. Either this is an attack, or the "
766 "MAX_EXTRAINFO_UPLOAD_SIZE (%d) constant is too low.",
767 (int)ei->cache_info.signed_descriptor_len,
768 MAX_EXTRAINFO_UPLOAD_SIZE);
769 *msg = "Extrainfo document was too large";
770 extrainfo_free(ei);
771 return ROUTER_BAD_EI;
774 if ((r = routerinfo_incompatible_with_extrainfo(ri->identity_pkey, ei,
775 &ri->cache_info, msg))) {
776 extrainfo_free(ei);
777 return r < 0 ? ROUTER_IS_ALREADY_KNOWN : ROUTER_BAD_EI;
779 router_add_extrainfo_to_routerlist(ei, msg, 0, 0);
780 return ROUTER_ADDED_SUCCESSFULLY;
783 /** Remove all descriptors whose nicknames or fingerprints no longer
784 * are allowed by our fingerprint list. (Descriptors that used to be
785 * good can become bad when we reload the fingerprint list.)
787 static void
788 directory_remove_invalid(void)
790 routerlist_t *rl = router_get_routerlist();
791 smartlist_t *nodes = smartlist_new();
792 smartlist_add_all(nodes, nodelist_get_list());
794 SMARTLIST_FOREACH_BEGIN(nodes, node_t *, node) {
795 const char *msg = NULL;
796 routerinfo_t *ent = node->ri;
797 char description[NODE_DESC_BUF_LEN];
798 uint32_t r;
799 if (!ent)
800 continue;
801 r = dirserv_router_get_status(ent, &msg, LOG_INFO);
802 router_get_description(description, ent);
803 if (r & FP_REJECT) {
804 log_info(LD_DIRSERV, "Router %s is now rejected: %s",
805 description, msg?msg:"");
806 routerlist_remove(rl, ent, 0, time(NULL));
807 continue;
809 if (bool_neq((r & FP_INVALID), !node->is_valid)) {
810 log_info(LD_DIRSERV, "Router '%s' is now %svalid.", description,
811 (r&FP_INVALID) ? "in" : "");
812 node->is_valid = (r&FP_INVALID)?0:1;
814 if (bool_neq((r & FP_BADEXIT), node->is_bad_exit)) {
815 log_info(LD_DIRSERV, "Router '%s' is now a %s exit", description,
816 (r & FP_BADEXIT) ? "bad" : "good");
817 node->is_bad_exit = (r&FP_BADEXIT) ? 1: 0;
819 } SMARTLIST_FOREACH_END(node);
821 routerlist_assert_ok(rl);
822 smartlist_free(nodes);
826 * Allocate and return a description of the status of the server <b>desc</b>,
827 * for use in a v1-style router-status line. The server is listed
828 * as running iff <b>is_live</b> is true.
830 * This is deprecated: it's only used for controllers that want outputs in
831 * the old format.
833 static char *
834 list_single_server_status(const routerinfo_t *desc, int is_live)
836 char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
837 char *cp;
838 const node_t *node;
840 tor_assert(desc);
842 cp = buf;
843 if (!is_live) {
844 *cp++ = '!';
846 node = node_get_by_id(desc->cache_info.identity_digest);
847 if (node && node->is_valid) {
848 strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
849 cp += strlen(cp);
850 *cp++ = '=';
852 *cp++ = '$';
853 base16_encode(cp, HEX_DIGEST_LEN+1, desc->cache_info.identity_digest,
854 DIGEST_LEN);
855 return tor_strdup(buf);
858 /* DOCDOC running_long_enough_to_decide_unreachable */
859 static inline int
860 running_long_enough_to_decide_unreachable(void)
862 return time_of_process_start
863 + get_options()->TestingAuthDirTimeToLearnReachability < approx_time();
866 /** Each server needs to have passed a reachability test no more
867 * than this number of seconds ago, or it is listed as down in
868 * the directory. */
869 #define REACHABLE_TIMEOUT (45*60)
871 /** If we tested a router and found it reachable _at least this long_ after it
872 * declared itself hibernating, it is probably done hibernating and we just
873 * missed a descriptor from it. */
874 #define HIBERNATION_PUBLICATION_SKEW (60*60)
876 /** Treat a router as alive if
877 * - It's me, and I'm not hibernating.
878 * or - We've found it reachable recently. */
879 void
880 dirserv_set_router_is_running(routerinfo_t *router, time_t now)
882 /*XXXX This function is a mess. Separate out the part that calculates
883 whether it's reachable and the part that tells rephist that the router was
884 unreachable.
886 int answer;
887 const or_options_t *options = get_options();
888 node_t *node = node_get_mutable_by_id(router->cache_info.identity_digest);
889 tor_assert(node);
891 if (router_is_me(router)) {
892 /* We always know if we are down ourselves. */
893 answer = ! we_are_hibernating();
894 } else if (router->is_hibernating &&
895 (router->cache_info.published_on +
896 HIBERNATION_PUBLICATION_SKEW) > node->last_reachable) {
897 /* A hibernating router is down unless we (somehow) had contact with it
898 * since it declared itself to be hibernating. */
899 answer = 0;
900 } else if (options->AssumeReachable) {
901 /* If AssumeReachable, everybody is up unless they say they are down! */
902 answer = 1;
903 } else {
904 /* Otherwise, a router counts as up if we found all announced OR
905 ports reachable in the last REACHABLE_TIMEOUT seconds.
907 XXX prop186 For now there's always one IPv4 and at most one
908 IPv6 OR port.
910 If we're not on IPv6, don't consider reachability of potential
911 IPv6 OR port since that'd kill all dual stack relays until a
912 majority of the dir auths have IPv6 connectivity. */
913 answer = (now < node->last_reachable + REACHABLE_TIMEOUT &&
914 (options->AuthDirHasIPv6Connectivity != 1 ||
915 tor_addr_is_null(&router->ipv6_addr) ||
916 now < node->last_reachable6 + REACHABLE_TIMEOUT));
919 if (!answer && running_long_enough_to_decide_unreachable()) {
920 /* Not considered reachable. tell rephist about that.
922 Because we launch a reachability test for each router every
923 REACHABILITY_TEST_CYCLE_PERIOD seconds, then the router has probably
924 been down since at least that time after we last successfully reached
927 XXX ipv6
929 time_t when = now;
930 if (node->last_reachable &&
931 node->last_reachable + REACHABILITY_TEST_CYCLE_PERIOD < now)
932 when = node->last_reachable + REACHABILITY_TEST_CYCLE_PERIOD;
933 rep_hist_note_router_unreachable(router->cache_info.identity_digest, when);
936 node->is_running = answer;
939 /** Based on the routerinfo_ts in <b>routers</b>, allocate the
940 * contents of a v1-style router-status line, and store it in
941 * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
943 * If for_controller is true, include the routers with very old descriptors.
945 * This is deprecated: it's only used for controllers that want outputs in
946 * the old format.
949 list_server_status_v1(smartlist_t *routers, char **router_status_out,
950 int for_controller)
952 /* List of entries in a router-status style: An optional !, then an optional
953 * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
954 smartlist_t *rs_entries;
955 time_t now = time(NULL);
956 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
957 const or_options_t *options = get_options();
958 /* We include v2 dir auths here too, because they need to answer
959 * controllers. Eventually we'll deprecate this whole function;
960 * see also networkstatus_getinfo_by_purpose(). */
961 int authdir = authdir_mode_publishes_statuses(options);
962 tor_assert(router_status_out);
964 rs_entries = smartlist_new();
966 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
967 const node_t *node = node_get_by_id(ri->cache_info.identity_digest);
968 tor_assert(node);
969 if (authdir) {
970 /* Update router status in routerinfo_t. */
971 dirserv_set_router_is_running(ri, now);
973 if (for_controller) {
974 char name_buf[MAX_VERBOSE_NICKNAME_LEN+2];
975 char *cp = name_buf;
976 if (!node->is_running)
977 *cp++ = '!';
978 router_get_verbose_nickname(cp, ri);
979 smartlist_add_strdup(rs_entries, name_buf);
980 } else if (ri->cache_info.published_on >= cutoff) {
981 smartlist_add(rs_entries, list_single_server_status(ri,
982 node->is_running));
984 } SMARTLIST_FOREACH_END(ri);
986 *router_status_out = smartlist_join_strings(rs_entries, " ", 0, NULL);
988 SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
989 smartlist_free(rs_entries);
991 return 0;
994 /** Given a (possibly empty) list of config_line_t, each line of which contains
995 * a list of comma-separated version numbers surrounded by optional space,
996 * allocate and return a new string containing the version numbers, in order,
997 * separated by commas. Used to generate Recommended(Client|Server)?Versions
999 static char *
1000 format_versions_list(config_line_t *ln)
1002 smartlist_t *versions;
1003 char *result;
1004 versions = smartlist_new();
1005 for ( ; ln; ln = ln->next) {
1006 smartlist_split_string(versions, ln->value, ",",
1007 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1009 sort_version_list(versions, 1);
1010 result = smartlist_join_strings(versions,",",0,NULL);
1011 SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
1012 smartlist_free(versions);
1013 return result;
1016 /** Return 1 if <b>ri</b>'s descriptor is "active" -- running, valid,
1017 * not hibernating, having observed bw greater 0, and not too old. Else
1018 * return 0.
1020 static int
1021 router_is_active(const routerinfo_t *ri, const node_t *node, time_t now)
1023 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
1024 if (ri->cache_info.published_on < cutoff) {
1025 return 0;
1027 if (!node->is_running || !node->is_valid || ri->is_hibernating) {
1028 return 0;
1030 /* Only require bandwith capacity in non-test networks, or
1031 * if TestingTorNetwork, and TestingMinExitFlagThreshold is non-zero */
1032 if (!ri->bandwidthcapacity) {
1033 if (get_options()->TestingTorNetwork) {
1034 if (get_options()->TestingMinExitFlagThreshold > 0) {
1035 /* If we're in a TestingTorNetwork, and TestingMinExitFlagThreshold is,
1036 * then require bandwidthcapacity */
1037 return 0;
1039 } else {
1040 /* If we're not in a TestingTorNetwork, then require bandwidthcapacity */
1041 return 0;
1044 return 1;
1047 /********************************************************************/
1049 /* A set of functions to answer questions about how we'd like to behave
1050 * as a directory mirror/client. */
1052 /** Return 1 if we fetch our directory material directly from the
1053 * authorities, rather than from a mirror. */
1055 directory_fetches_from_authorities(const or_options_t *options)
1057 const routerinfo_t *me;
1058 uint32_t addr;
1059 int refuseunknown;
1060 if (options->FetchDirInfoEarly)
1061 return 1;
1062 if (options->BridgeRelay == 1)
1063 return 0;
1064 if (server_mode(options) &&
1065 router_pick_published_address(options, &addr, 1) < 0)
1066 return 1; /* we don't know our IP address; ask an authority. */
1067 refuseunknown = ! router_my_exit_policy_is_reject_star() &&
1068 should_refuse_unknown_exits(options);
1069 if (!dir_server_mode(options) && !refuseunknown)
1070 return 0;
1071 if (!server_mode(options) || !advertised_server_mode())
1072 return 0;
1073 me = router_get_my_routerinfo();
1074 if (!me || (!me->supports_tunnelled_dir_requests && !refuseunknown))
1075 return 0; /* if we don't service directory requests, return 0 too */
1076 return 1;
1079 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1080 * on the "mirror" schedule rather than the "client" schedule.
1083 directory_fetches_dir_info_early(const or_options_t *options)
1085 return directory_fetches_from_authorities(options);
1088 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1089 * on a very passive schedule -- waiting long enough for ordinary clients
1090 * to probably have the info we want. These would include bridge users,
1091 * and maybe others in the future e.g. if a Tor client uses another Tor
1092 * client as a directory guard.
1095 directory_fetches_dir_info_later(const or_options_t *options)
1097 return options->UseBridges != 0;
1100 /** Return true iff we want to serve certificates for authorities
1101 * that we don't acknowledge as authorities ourself.
1102 * Use we_want_to_fetch_unknown_auth_certs to check if we want to fetch
1103 * and keep these certificates.
1106 directory_caches_unknown_auth_certs(const or_options_t *options)
1108 return dir_server_mode(options) || options->BridgeRelay;
1111 /** Return 1 if we want to fetch and serve descriptors, networkstatuses, etc
1112 * Else return 0.
1113 * Check options->DirPort_set and directory_permits_begindir_requests()
1114 * to see if we are willing to serve these directory documents to others via
1115 * the DirPort and begindir-over-ORPort, respectively.
1117 * To check if we should fetch documents, use we_want_to_fetch_flavor and
1118 * we_want_to_fetch_unknown_auth_certs instead of this function.
1121 directory_caches_dir_info(const or_options_t *options)
1123 if (options->BridgeRelay || dir_server_mode(options))
1124 return 1;
1125 if (!server_mode(options) || !advertised_server_mode())
1126 return 0;
1127 /* We need an up-to-date view of network info if we're going to try to
1128 * block exit attempts from unknown relays. */
1129 return ! router_my_exit_policy_is_reject_star() &&
1130 should_refuse_unknown_exits(options);
1133 /** Return 1 if we want to allow remote clients to ask us directory
1134 * requests via the "begin_dir" interface, which doesn't require
1135 * having any separate port open. */
1137 directory_permits_begindir_requests(const or_options_t *options)
1139 return options->BridgeRelay != 0 || dir_server_mode(options);
1142 /** Return 1 if we have no need to fetch new descriptors. This generally
1143 * happens when we're not a dir cache and we haven't built any circuits
1144 * lately.
1147 directory_too_idle_to_fetch_descriptors(const or_options_t *options,
1148 time_t now)
1150 return !directory_caches_dir_info(options) &&
1151 !options->FetchUselessDescriptors &&
1152 rep_hist_circbuilding_dormant(now);
1155 /********************************************************************/
1157 /** Map from flavor name to the cached_dir_t for the v3 consensuses that we're
1158 * currently serving. */
1159 static strmap_t *cached_consensuses = NULL;
1161 /** Decrement the reference count on <b>d</b>, and free it if it no longer has
1162 * any references. */
1163 void
1164 cached_dir_decref(cached_dir_t *d)
1166 if (!d || --d->refcnt > 0)
1167 return;
1168 clear_cached_dir(d);
1169 tor_free(d);
1172 /** Allocate and return a new cached_dir_t containing the string <b>s</b>,
1173 * published at <b>published</b>. */
1174 cached_dir_t *
1175 new_cached_dir(char *s, time_t published)
1177 cached_dir_t *d = tor_malloc_zero(sizeof(cached_dir_t));
1178 d->refcnt = 1;
1179 d->dir = s;
1180 d->dir_len = strlen(s);
1181 d->published = published;
1182 if (tor_compress(&(d->dir_compressed), &(d->dir_compressed_len),
1183 d->dir, d->dir_len, ZLIB_METHOD)) {
1184 log_warn(LD_BUG, "Error compressing directory");
1186 return d;
1189 /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
1190 static void
1191 clear_cached_dir(cached_dir_t *d)
1193 tor_free(d->dir);
1194 tor_free(d->dir_compressed);
1195 memset(d, 0, sizeof(cached_dir_t));
1198 /** Free all storage held by the cached_dir_t in <b>d</b>. */
1199 static void
1200 free_cached_dir_(void *_d)
1202 cached_dir_t *d;
1203 if (!_d)
1204 return;
1206 d = (cached_dir_t *)_d;
1207 cached_dir_decref(d);
1210 /** Replace the v3 consensus networkstatus of type <b>flavor_name</b> that
1211 * we're serving with <b>networkstatus</b>, published at <b>published</b>. No
1212 * validation is performed. */
1213 void
1214 dirserv_set_cached_consensus_networkstatus(const char *networkstatus,
1215 const char *flavor_name,
1216 const common_digests_t *digests,
1217 const uint8_t *sha3_as_signed,
1218 time_t published)
1220 cached_dir_t *new_networkstatus;
1221 cached_dir_t *old_networkstatus;
1222 if (!cached_consensuses)
1223 cached_consensuses = strmap_new();
1225 new_networkstatus = new_cached_dir(tor_strdup(networkstatus), published);
1226 memcpy(&new_networkstatus->digests, digests, sizeof(common_digests_t));
1227 memcpy(&new_networkstatus->digest_sha3_as_signed, sha3_as_signed,
1228 DIGEST256_LEN);
1229 old_networkstatus = strmap_set(cached_consensuses, flavor_name,
1230 new_networkstatus);
1231 if (old_networkstatus)
1232 cached_dir_decref(old_networkstatus);
1235 /** Return the latest downloaded consensus networkstatus in encoded, signed,
1236 * optionally compressed format, suitable for sending to clients. */
1237 cached_dir_t *
1238 dirserv_get_consensus(const char *flavor_name)
1240 if (!cached_consensuses)
1241 return NULL;
1242 return strmap_get(cached_consensuses, flavor_name);
1245 /** If a router's uptime is at least this value, then it is always
1246 * considered stable, regardless of the rest of the network. This
1247 * way we resist attacks where an attacker doubles the size of the
1248 * network using allegedly high-uptime nodes, displacing all the
1249 * current guards. */
1250 #define UPTIME_TO_GUARANTEE_STABLE (3600*24*30)
1251 /** If a router's MTBF is at least this value, then it is always stable.
1252 * See above. (Corresponds to about 7 days for current decay rates.) */
1253 #define MTBF_TO_GUARANTEE_STABLE (60*60*24*5)
1254 /** Similarly, every node with at least this much weighted time known can be
1255 * considered familiar enough to be a guard. Corresponds to about 20 days for
1256 * current decay rates.
1258 #define TIME_KNOWN_TO_GUARANTEE_FAMILIAR (8*24*60*60)
1259 /** Similarly, every node with sufficient WFU is around enough to be a guard.
1261 #define WFU_TO_GUARANTEE_GUARD (0.98)
1263 /* Thresholds for server performance: set by
1264 * dirserv_compute_performance_thresholds, and used by
1265 * generate_v2_networkstatus */
1267 /** Any router with an uptime of at least this value is stable. */
1268 static uint32_t stable_uptime = 0; /* start at a safe value */
1269 /** Any router with an mtbf of at least this value is stable. */
1270 static double stable_mtbf = 0.0;
1271 /** If true, we have measured enough mtbf info to look at stable_mtbf rather
1272 * than stable_uptime. */
1273 static int enough_mtbf_info = 0;
1274 /** Any router with a weighted fractional uptime of at least this much might
1275 * be good as a guard. */
1276 static double guard_wfu = 0.0;
1277 /** Don't call a router a guard unless we've known about it for at least this
1278 * many seconds. */
1279 static long guard_tk = 0;
1280 /** Any router with a bandwidth at least this high is "Fast" */
1281 static uint32_t fast_bandwidth_kb = 0;
1282 /** If exits can be guards, then all guards must have a bandwidth this
1283 * high. */
1284 static uint32_t guard_bandwidth_including_exits_kb = 0;
1285 /** If exits can't be guards, then all guards must have a bandwidth this
1286 * high. */
1287 static uint32_t guard_bandwidth_excluding_exits_kb = 0;
1289 /** Helper: estimate the uptime of a router given its stated uptime and the
1290 * amount of time since it last stated its stated uptime. */
1291 static inline long
1292 real_uptime(const routerinfo_t *router, time_t now)
1294 if (now < router->cache_info.published_on)
1295 return router->uptime;
1296 else
1297 return router->uptime + (now - router->cache_info.published_on);
1300 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1301 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1302 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1303 * bandwidth.
1305 static int
1306 dirserv_thinks_router_is_unreliable(time_t now,
1307 routerinfo_t *router,
1308 int need_uptime, int need_capacity)
1310 if (need_uptime) {
1311 if (!enough_mtbf_info) {
1312 /* XXXX We should change the rule from
1313 * "use uptime if we don't have mtbf data" to "don't advertise Stable on
1314 * v3 if we don't have enough mtbf data." Or maybe not, since if we ever
1315 * hit a point where we need to reset a lot of authorities at once,
1316 * none of them would be in a position to declare Stable.
1318 long uptime = real_uptime(router, now);
1319 if ((unsigned)uptime < stable_uptime &&
1320 (unsigned)uptime < UPTIME_TO_GUARANTEE_STABLE)
1321 return 1;
1322 } else {
1323 double mtbf =
1324 rep_hist_get_stability(router->cache_info.identity_digest, now);
1325 if (mtbf < stable_mtbf &&
1326 mtbf < MTBF_TO_GUARANTEE_STABLE)
1327 return 1;
1330 if (need_capacity) {
1331 uint32_t bw_kb = dirserv_get_credible_bandwidth_kb(router);
1332 if (bw_kb < fast_bandwidth_kb)
1333 return 1;
1335 return 0;
1338 /** Return true iff <b>router</b> should be assigned the "HSDir" flag.
1340 * Right now this means it advertises support for it, it has a high uptime,
1341 * it's a directory cache, it has the Stable and Fast flags, and it's currently
1342 * considered Running.
1344 * This function needs to be called after router-\>is_running has
1345 * been set.
1347 static int
1348 dirserv_thinks_router_is_hs_dir(const routerinfo_t *router,
1349 const node_t *node, time_t now)
1352 long uptime;
1354 /* If we haven't been running for at least
1355 * get_options()->MinUptimeHidServDirectoryV2 seconds, we can't
1356 * have accurate data telling us a relay has been up for at least
1357 * that long. We also want to allow a bit of slack: Reachability
1358 * tests aren't instant. If we haven't been running long enough,
1359 * trust the relay. */
1361 if (stats_n_seconds_working >
1362 get_options()->MinUptimeHidServDirectoryV2 * 1.1)
1363 uptime = MIN(rep_hist_get_uptime(router->cache_info.identity_digest, now),
1364 real_uptime(router, now));
1365 else
1366 uptime = real_uptime(router, now);
1368 return (router->wants_to_be_hs_dir &&
1369 router->supports_tunnelled_dir_requests &&
1370 node->is_stable && node->is_fast &&
1371 uptime >= get_options()->MinUptimeHidServDirectoryV2 &&
1372 router_is_active(router, node, now));
1375 /** Don't consider routers with less bandwidth than this when computing
1376 * thresholds. */
1377 #define ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER_KB 4
1379 /** Helper for dirserv_compute_performance_thresholds(): Decide whether to
1380 * include a router in our calculations, and return true iff we should; the
1381 * require_mbw parameter is passed in by
1382 * dirserv_compute_performance_thresholds() and controls whether we ever
1383 * count routers with only advertised bandwidths */
1384 static int
1385 router_counts_toward_thresholds(const node_t *node, time_t now,
1386 const digestmap_t *omit_as_sybil,
1387 int require_mbw)
1389 /* Have measured bw? */
1390 int have_mbw =
1391 dirserv_has_measured_bw(node->identity);
1392 uint64_t min_bw_kb = ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER_KB;
1393 const or_options_t *options = get_options();
1395 if (options->TestingTorNetwork) {
1396 min_bw_kb = (int64_t)options->TestingMinExitFlagThreshold / 1000;
1399 return node->ri && router_is_active(node->ri, node, now) &&
1400 !digestmap_get(omit_as_sybil, node->identity) &&
1401 (dirserv_get_credible_bandwidth_kb(node->ri) >= min_bw_kb) &&
1402 (have_mbw || !require_mbw);
1405 /** Look through the routerlist, the Mean Time Between Failure history, and
1406 * the Weighted Fractional Uptime history, and use them to set thresholds for
1407 * the Stable, Fast, and Guard flags. Update the fields stable_uptime,
1408 * stable_mtbf, enough_mtbf_info, guard_wfu, guard_tk, fast_bandwidth,
1409 * guard_bandwidth_including_exits, and guard_bandwidth_excluding_exits.
1411 * Also, set the is_exit flag of each router appropriately. */
1412 static void
1413 dirserv_compute_performance_thresholds(digestmap_t *omit_as_sybil)
1415 int n_active, n_active_nonexit, n_familiar;
1416 uint32_t *uptimes, *bandwidths_kb, *bandwidths_excluding_exits_kb;
1417 long *tks;
1418 double *mtbfs, *wfus;
1419 smartlist_t *nodelist;
1420 time_t now = time(NULL);
1421 const or_options_t *options = get_options();
1423 /* Require mbw? */
1424 int require_mbw =
1425 (routers_with_measured_bw >
1426 options->MinMeasuredBWsForAuthToIgnoreAdvertised) ? 1 : 0;
1428 /* initialize these all here, in case there are no routers */
1429 stable_uptime = 0;
1430 stable_mtbf = 0;
1431 fast_bandwidth_kb = 0;
1432 guard_bandwidth_including_exits_kb = 0;
1433 guard_bandwidth_excluding_exits_kb = 0;
1434 guard_tk = 0;
1435 guard_wfu = 0;
1437 nodelist_assert_ok();
1438 nodelist = nodelist_get_list();
1440 /* Initialize arrays that will hold values for each router. We'll
1441 * sort them and use that to compute thresholds. */
1442 n_active = n_active_nonexit = 0;
1443 /* Uptime for every active router. */
1444 uptimes = tor_calloc(smartlist_len(nodelist), sizeof(uint32_t));
1445 /* Bandwidth for every active router. */
1446 bandwidths_kb = tor_calloc(smartlist_len(nodelist), sizeof(uint32_t));
1447 /* Bandwidth for every active non-exit router. */
1448 bandwidths_excluding_exits_kb =
1449 tor_calloc(smartlist_len(nodelist), sizeof(uint32_t));
1450 /* Weighted mean time between failure for each active router. */
1451 mtbfs = tor_calloc(smartlist_len(nodelist), sizeof(double));
1452 /* Time-known for each active router. */
1453 tks = tor_calloc(smartlist_len(nodelist), sizeof(long));
1454 /* Weighted fractional uptime for each active router. */
1455 wfus = tor_calloc(smartlist_len(nodelist), sizeof(double));
1457 /* Now, fill in the arrays. */
1458 SMARTLIST_FOREACH_BEGIN(nodelist, node_t *, node) {
1459 if (options->BridgeAuthoritativeDir &&
1460 node->ri &&
1461 node->ri->purpose != ROUTER_PURPOSE_BRIDGE)
1462 continue;
1463 if (router_counts_toward_thresholds(node, now, omit_as_sybil,
1464 require_mbw)) {
1465 routerinfo_t *ri = node->ri;
1466 const char *id = node->identity;
1467 uint32_t bw_kb;
1468 /* resolve spurious clang shallow analysis null pointer errors */
1469 tor_assert(ri);
1470 node->is_exit = (!router_exit_policy_rejects_all(ri) &&
1471 exit_policy_is_general_exit(ri->exit_policy));
1472 uptimes[n_active] = (uint32_t)real_uptime(ri, now);
1473 mtbfs[n_active] = rep_hist_get_stability(id, now);
1474 tks [n_active] = rep_hist_get_weighted_time_known(id, now);
1475 bandwidths_kb[n_active] = bw_kb = dirserv_get_credible_bandwidth_kb(ri);
1476 if (!node->is_exit || node->is_bad_exit) {
1477 bandwidths_excluding_exits_kb[n_active_nonexit] = bw_kb;
1478 ++n_active_nonexit;
1480 ++n_active;
1482 } SMARTLIST_FOREACH_END(node);
1484 /* Now, compute thresholds. */
1485 if (n_active) {
1486 /* The median uptime is stable. */
1487 stable_uptime = median_uint32(uptimes, n_active);
1488 /* The median mtbf is stable, if we have enough mtbf info */
1489 stable_mtbf = median_double(mtbfs, n_active);
1490 /* The 12.5th percentile bandwidth is fast. */
1491 fast_bandwidth_kb = find_nth_uint32(bandwidths_kb, n_active, n_active/8);
1492 /* (Now bandwidths is sorted.) */
1493 if (fast_bandwidth_kb < RELAY_REQUIRED_MIN_BANDWIDTH/(2 * 1000))
1494 fast_bandwidth_kb = bandwidths_kb[n_active/4];
1495 guard_bandwidth_including_exits_kb =
1496 third_quartile_uint32(bandwidths_kb, n_active);
1497 guard_tk = find_nth_long(tks, n_active, n_active/8);
1500 if (guard_tk > TIME_KNOWN_TO_GUARANTEE_FAMILIAR)
1501 guard_tk = TIME_KNOWN_TO_GUARANTEE_FAMILIAR;
1504 /* We can vote on a parameter for the minimum and maximum. */
1505 #define ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG 4
1506 int32_t min_fast_kb, max_fast_kb, min_fast, max_fast;
1507 min_fast = networkstatus_get_param(NULL, "FastFlagMinThreshold",
1508 ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG,
1509 ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG,
1510 INT32_MAX);
1511 if (options->TestingTorNetwork) {
1512 min_fast = (int32_t)options->TestingMinFastFlagThreshold;
1514 max_fast = networkstatus_get_param(NULL, "FastFlagMaxThreshold",
1515 INT32_MAX, min_fast, INT32_MAX);
1516 min_fast_kb = min_fast / 1000;
1517 max_fast_kb = max_fast / 1000;
1519 if (fast_bandwidth_kb < (uint32_t)min_fast_kb)
1520 fast_bandwidth_kb = min_fast_kb;
1521 if (fast_bandwidth_kb > (uint32_t)max_fast_kb)
1522 fast_bandwidth_kb = max_fast_kb;
1524 /* Protect sufficiently fast nodes from being pushed out of the set
1525 * of Fast nodes. */
1526 if (options->AuthDirFastGuarantee &&
1527 fast_bandwidth_kb > options->AuthDirFastGuarantee/1000)
1528 fast_bandwidth_kb = (uint32_t)options->AuthDirFastGuarantee/1000;
1530 /* Now that we have a time-known that 7/8 routers are known longer than,
1531 * fill wfus with the wfu of every such "familiar" router. */
1532 n_familiar = 0;
1534 SMARTLIST_FOREACH_BEGIN(nodelist, node_t *, node) {
1535 if (router_counts_toward_thresholds(node, now,
1536 omit_as_sybil, require_mbw)) {
1537 routerinfo_t *ri = node->ri;
1538 const char *id = ri->cache_info.identity_digest;
1539 long tk = rep_hist_get_weighted_time_known(id, now);
1540 if (tk < guard_tk)
1541 continue;
1542 wfus[n_familiar++] = rep_hist_get_weighted_fractional_uptime(id, now);
1544 } SMARTLIST_FOREACH_END(node);
1545 if (n_familiar)
1546 guard_wfu = median_double(wfus, n_familiar);
1547 if (guard_wfu > WFU_TO_GUARANTEE_GUARD)
1548 guard_wfu = WFU_TO_GUARANTEE_GUARD;
1550 enough_mtbf_info = rep_hist_have_measured_enough_stability();
1552 if (n_active_nonexit) {
1553 guard_bandwidth_excluding_exits_kb =
1554 find_nth_uint32(bandwidths_excluding_exits_kb,
1555 n_active_nonexit, n_active_nonexit*3/4);
1558 log_info(LD_DIRSERV,
1559 "Cutoffs: For Stable, %lu sec uptime, %lu sec MTBF. "
1560 "For Fast: %lu kilobytes/sec. "
1561 "For Guard: WFU %.03f%%, time-known %lu sec, "
1562 "and bandwidth %lu or %lu kilobytes/sec. "
1563 "We%s have enough stability data.",
1564 (unsigned long)stable_uptime,
1565 (unsigned long)stable_mtbf,
1566 (unsigned long)fast_bandwidth_kb,
1567 guard_wfu*100,
1568 (unsigned long)guard_tk,
1569 (unsigned long)guard_bandwidth_including_exits_kb,
1570 (unsigned long)guard_bandwidth_excluding_exits_kb,
1571 enough_mtbf_info ? "" : " don't");
1573 tor_free(uptimes);
1574 tor_free(mtbfs);
1575 tor_free(bandwidths_kb);
1576 tor_free(bandwidths_excluding_exits_kb);
1577 tor_free(tks);
1578 tor_free(wfus);
1581 /* Use dirserv_compute_performance_thresholds() to compute the thresholds
1582 * for the status flags, specifically for bridges.
1584 * This is only called by a Bridge Authority from
1585 * networkstatus_getinfo_by_purpose().
1587 void
1588 dirserv_compute_bridge_flag_thresholds(void)
1590 digestmap_t *omit_as_sybil = digestmap_new();
1591 dirserv_compute_performance_thresholds(omit_as_sybil);
1592 digestmap_free(omit_as_sybil, NULL);
1595 /** Measured bandwidth cache entry */
1596 typedef struct mbw_cache_entry_s {
1597 long mbw_kb;
1598 time_t as_of;
1599 } mbw_cache_entry_t;
1601 /** Measured bandwidth cache - keys are identity_digests, values are
1602 * mbw_cache_entry_t *. */
1603 static digestmap_t *mbw_cache = NULL;
1605 /** Store a measured bandwidth cache entry when reading the measured
1606 * bandwidths file. */
1607 STATIC void
1608 dirserv_cache_measured_bw(const measured_bw_line_t *parsed_line,
1609 time_t as_of)
1611 mbw_cache_entry_t *e = NULL;
1613 tor_assert(parsed_line);
1615 /* Allocate a cache if we need */
1616 if (!mbw_cache) mbw_cache = digestmap_new();
1618 /* Check if we have an existing entry */
1619 e = digestmap_get(mbw_cache, parsed_line->node_id);
1620 /* If we do, we can re-use it */
1621 if (e) {
1622 /* Check that we really are newer, and update */
1623 if (as_of > e->as_of) {
1624 e->mbw_kb = parsed_line->bw_kb;
1625 e->as_of = as_of;
1627 } else {
1628 /* We'll have to insert a new entry */
1629 e = tor_malloc(sizeof(*e));
1630 e->mbw_kb = parsed_line->bw_kb;
1631 e->as_of = as_of;
1632 digestmap_set(mbw_cache, parsed_line->node_id, e);
1636 /** Clear and free the measured bandwidth cache */
1637 STATIC void
1638 dirserv_clear_measured_bw_cache(void)
1640 if (mbw_cache) {
1641 /* Free the map and all entries */
1642 digestmap_free(mbw_cache, tor_free_);
1643 mbw_cache = NULL;
1647 /** Scan the measured bandwidth cache and remove expired entries */
1648 STATIC void
1649 dirserv_expire_measured_bw_cache(time_t now)
1652 if (mbw_cache) {
1653 /* Iterate through the cache and check each entry */
1654 DIGESTMAP_FOREACH_MODIFY(mbw_cache, k, mbw_cache_entry_t *, e) {
1655 if (now > e->as_of + MAX_MEASUREMENT_AGE) {
1656 tor_free(e);
1657 MAP_DEL_CURRENT(k);
1659 } DIGESTMAP_FOREACH_END;
1661 /* Check if we cleared the whole thing and free if so */
1662 if (digestmap_size(mbw_cache) == 0) {
1663 digestmap_free(mbw_cache, tor_free_);
1664 mbw_cache = 0;
1669 /** Get the current size of the measured bandwidth cache */
1670 STATIC int
1671 dirserv_get_measured_bw_cache_size(void)
1673 if (mbw_cache) return digestmap_size(mbw_cache);
1674 else return 0;
1677 /** Query the cache by identity digest, return value indicates whether
1678 * we found it. The bw_out and as_of_out pointers receive the cached
1679 * bandwidth value and the time it was cached if not NULL. */
1680 STATIC int
1681 dirserv_query_measured_bw_cache_kb(const char *node_id, long *bw_kb_out,
1682 time_t *as_of_out)
1684 mbw_cache_entry_t *v = NULL;
1685 int rv = 0;
1687 if (mbw_cache && node_id) {
1688 v = digestmap_get(mbw_cache, node_id);
1689 if (v) {
1690 /* Found something */
1691 rv = 1;
1692 if (bw_kb_out) *bw_kb_out = v->mbw_kb;
1693 if (as_of_out) *as_of_out = v->as_of;
1697 return rv;
1700 /** Predicate wrapper for dirserv_query_measured_bw_cache() */
1701 STATIC int
1702 dirserv_has_measured_bw(const char *node_id)
1704 return dirserv_query_measured_bw_cache_kb(node_id, NULL, NULL);
1707 /** Get the best estimate of a router's bandwidth for dirauth purposes,
1708 * preferring measured to advertised values if available. */
1710 static uint32_t
1711 dirserv_get_bandwidth_for_router_kb(const routerinfo_t *ri)
1713 uint32_t bw_kb = 0;
1715 * Yeah, measured bandwidths in measured_bw_line_t are (implicitly
1716 * signed) longs and the ones router_get_advertised_bandwidth() returns
1717 * are uint32_t.
1719 long mbw_kb = 0;
1721 if (ri) {
1723 * * First try to see if we have a measured bandwidth; don't bother with
1724 * as_of_out here, on the theory that a stale measured bandwidth is still
1725 * better to trust than an advertised one.
1727 if (dirserv_query_measured_bw_cache_kb(ri->cache_info.identity_digest,
1728 &mbw_kb, NULL)) {
1729 /* Got one! */
1730 bw_kb = (uint32_t)mbw_kb;
1731 } else {
1732 /* If not, fall back to advertised */
1733 bw_kb = router_get_advertised_bandwidth(ri) / 1000;
1737 return bw_kb;
1740 /** Look through the routerlist, and using the measured bandwidth cache count
1741 * how many measured bandwidths we know. This is used to decide whether we
1742 * ever trust advertised bandwidths for purposes of assigning flags. */
1743 static void
1744 dirserv_count_measured_bws(const smartlist_t *routers)
1746 /* Initialize this first */
1747 routers_with_measured_bw = 0;
1749 /* Iterate over the routerlist and count measured bandwidths */
1750 SMARTLIST_FOREACH_BEGIN(routers, const routerinfo_t *, ri) {
1751 /* Check if we know a measured bandwidth for this one */
1752 if (dirserv_has_measured_bw(ri->cache_info.identity_digest)) {
1753 ++routers_with_measured_bw;
1755 } SMARTLIST_FOREACH_END(ri);
1758 /** Return the bandwidth we believe for assigning flags; prefer measured
1759 * over advertised, and if we have above a threshold quantity of measured
1760 * bandwidths, we don't want to ever give flags to unmeasured routers, so
1761 * return 0. */
1762 static uint32_t
1763 dirserv_get_credible_bandwidth_kb(const routerinfo_t *ri)
1765 int threshold;
1766 uint32_t bw_kb = 0;
1767 long mbw_kb;
1769 tor_assert(ri);
1770 /* Check if we have a measured bandwidth, and check the threshold if not */
1771 if (!(dirserv_query_measured_bw_cache_kb(ri->cache_info.identity_digest,
1772 &mbw_kb, NULL))) {
1773 threshold = get_options()->MinMeasuredBWsForAuthToIgnoreAdvertised;
1774 if (routers_with_measured_bw > threshold) {
1775 /* Return zero for unmeasured bandwidth if we are above threshold */
1776 bw_kb = 0;
1777 } else {
1778 /* Return an advertised bandwidth otherwise */
1779 bw_kb = router_get_advertised_bandwidth_capped(ri) / 1000;
1781 } else {
1782 /* We have the measured bandwidth in mbw */
1783 bw_kb = (uint32_t)mbw_kb;
1786 return bw_kb;
1789 /** Give a statement of our current performance thresholds for inclusion
1790 * in a vote document. */
1791 char *
1792 dirserv_get_flag_thresholds_line(void)
1794 char *result=NULL;
1795 const int measured_threshold =
1796 get_options()->MinMeasuredBWsForAuthToIgnoreAdvertised;
1797 const int enough_measured_bw = routers_with_measured_bw > measured_threshold;
1799 tor_asprintf(&result,
1800 "stable-uptime=%lu stable-mtbf=%lu "
1801 "fast-speed=%lu "
1802 "guard-wfu=%.03f%% guard-tk=%lu "
1803 "guard-bw-inc-exits=%lu guard-bw-exc-exits=%lu "
1804 "enough-mtbf=%d ignoring-advertised-bws=%d",
1805 (unsigned long)stable_uptime,
1806 (unsigned long)stable_mtbf,
1807 (unsigned long)fast_bandwidth_kb*1000,
1808 guard_wfu*100,
1809 (unsigned long)guard_tk,
1810 (unsigned long)guard_bandwidth_including_exits_kb*1000,
1811 (unsigned long)guard_bandwidth_excluding_exits_kb*1000,
1812 enough_mtbf_info ? 1 : 0,
1813 enough_measured_bw ? 1 : 0);
1815 return result;
1818 /** Given a platform string as in a routerinfo_t (possibly null), return a
1819 * newly allocated version string for a networkstatus document, or NULL if the
1820 * platform doesn't give a Tor version. */
1821 static char *
1822 version_from_platform(const char *platform)
1824 if (platform && !strcmpstart(platform, "Tor ")) {
1825 const char *eos = find_whitespace(platform+4);
1826 if (eos && !strcmpstart(eos, " (r")) {
1827 /* XXXX Unify this logic with the other version extraction
1828 * logic in routerparse.c. */
1829 eos = find_whitespace(eos+1);
1831 if (eos) {
1832 return tor_strndup(platform, eos-platform);
1835 return NULL;
1838 /** Helper: write the router-status information in <b>rs</b> into a newly
1839 * allocated character buffer. Use the same format as in network-status
1840 * documents. If <b>version</b> is non-NULL, add a "v" line for the platform.
1841 * Return 0 on success, -1 on failure.
1843 * The format argument has one of the following values:
1844 * NS_V2 - Output an entry suitable for a V2 NS opinion document
1845 * NS_V3_CONSENSUS - Output the first portion of a V3 NS consensus entry
1846 * NS_V3_CONSENSUS_MICRODESC - Output the first portion of a V3 microdesc
1847 * consensus entry.
1848 * NS_V3_VOTE - Output a complete V3 NS vote. If <b>vrs</b> is present,
1849 * it contains additional information for the vote.
1850 * NS_CONTROL_PORT - Output a NS document for the control port
1852 char *
1853 routerstatus_format_entry(const routerstatus_t *rs, const char *version,
1854 const char *protocols,
1855 routerstatus_format_type_t format,
1856 const vote_routerstatus_t *vrs)
1858 char *summary;
1859 char *result = NULL;
1861 char published[ISO_TIME_LEN+1];
1862 char identity64[BASE64_DIGEST_LEN+1];
1863 char digest64[BASE64_DIGEST_LEN+1];
1864 smartlist_t *chunks = smartlist_new();
1866 format_iso_time(published, rs->published_on);
1867 digest_to_base64(identity64, rs->identity_digest);
1868 digest_to_base64(digest64, rs->descriptor_digest);
1870 smartlist_add_asprintf(chunks,
1871 "r %s %s %s%s%s %s %d %d\n",
1872 rs->nickname,
1873 identity64,
1874 (format==NS_V3_CONSENSUS_MICRODESC)?"":digest64,
1875 (format==NS_V3_CONSENSUS_MICRODESC)?"":" ",
1876 published,
1877 fmt_addr32(rs->addr),
1878 (int)rs->or_port,
1879 (int)rs->dir_port);
1881 /* TODO: Maybe we want to pass in what we need to build the rest of
1882 * this here, instead of in the caller. Then we could use the
1883 * networkstatus_type_t values, with an additional control port value
1884 * added -MP */
1886 /* V3 microdesc consensuses don't have "a" lines. */
1887 if (format == NS_V3_CONSENSUS_MICRODESC)
1888 goto done;
1890 /* Possible "a" line. At most one for now. */
1891 if (!tor_addr_is_null(&rs->ipv6_addr)) {
1892 smartlist_add_asprintf(chunks, "a %s\n",
1893 fmt_addrport(&rs->ipv6_addr, rs->ipv6_orport));
1896 if (format == NS_V3_CONSENSUS)
1897 goto done;
1899 smartlist_add_asprintf(chunks,
1900 "s%s%s%s%s%s%s%s%s%s%s\n",
1901 /* These must stay in alphabetical order. */
1902 rs->is_authority?" Authority":"",
1903 rs->is_bad_exit?" BadExit":"",
1904 rs->is_exit?" Exit":"",
1905 rs->is_fast?" Fast":"",
1906 rs->is_possible_guard?" Guard":"",
1907 rs->is_hs_dir?" HSDir":"",
1908 rs->is_flagged_running?" Running":"",
1909 rs->is_stable?" Stable":"",
1910 rs->is_v2_dir?" V2Dir":"",
1911 rs->is_valid?" Valid":"");
1913 /* length of "opt v \n" */
1914 #define V_LINE_OVERHEAD 7
1915 if (version && strlen(version) < MAX_V_LINE_LEN - V_LINE_OVERHEAD) {
1916 smartlist_add_asprintf(chunks, "v %s\n", version);
1918 if (protocols) {
1919 smartlist_add_asprintf(chunks, "pr %s\n", protocols);
1922 if (format != NS_V2) {
1923 const routerinfo_t* desc = router_get_by_id_digest(rs->identity_digest);
1924 uint32_t bw_kb;
1926 if (format != NS_CONTROL_PORT) {
1927 /* Blow up more or less nicely if we didn't get anything or not the
1928 * thing we expected.
1930 if (!desc) {
1931 char id[HEX_DIGEST_LEN+1];
1932 char dd[HEX_DIGEST_LEN+1];
1934 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
1935 base16_encode(dd, sizeof(dd), rs->descriptor_digest, DIGEST_LEN);
1936 log_warn(LD_BUG, "Cannot get any descriptor for %s "
1937 "(wanted descriptor %s).",
1938 id, dd);
1939 goto err;
1942 /* This assert could fire for the control port, because
1943 * it can request NS documents before all descriptors
1944 * have been fetched. Therefore, we only do this test when
1945 * format != NS_CONTROL_PORT. */
1946 if (tor_memneq(desc->cache_info.signed_descriptor_digest,
1947 rs->descriptor_digest,
1948 DIGEST_LEN)) {
1949 char rl_d[HEX_DIGEST_LEN+1];
1950 char rs_d[HEX_DIGEST_LEN+1];
1951 char id[HEX_DIGEST_LEN+1];
1953 base16_encode(rl_d, sizeof(rl_d),
1954 desc->cache_info.signed_descriptor_digest, DIGEST_LEN);
1955 base16_encode(rs_d, sizeof(rs_d), rs->descriptor_digest, DIGEST_LEN);
1956 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
1957 log_err(LD_BUG, "descriptor digest in routerlist does not match "
1958 "the one in routerstatus: %s vs %s "
1959 "(router %s)\n",
1960 rl_d, rs_d, id);
1962 tor_assert(tor_memeq(desc->cache_info.signed_descriptor_digest,
1963 rs->descriptor_digest,
1964 DIGEST_LEN));
1968 if (format == NS_CONTROL_PORT && rs->has_bandwidth) {
1969 bw_kb = rs->bandwidth_kb;
1970 } else {
1971 tor_assert(desc);
1972 bw_kb = router_get_advertised_bandwidth_capped(desc) / 1000;
1974 smartlist_add_asprintf(chunks,
1975 "w Bandwidth=%d", bw_kb);
1977 if (format == NS_V3_VOTE && vrs && vrs->has_measured_bw) {
1978 smartlist_add_asprintf(chunks,
1979 " Measured=%d", vrs->measured_bw_kb);
1981 /* Write down guardfraction information if we have it. */
1982 if (format == NS_V3_VOTE && vrs && vrs->status.has_guardfraction) {
1983 smartlist_add_asprintf(chunks,
1984 " GuardFraction=%d",
1985 vrs->status.guardfraction_percentage);
1988 smartlist_add_strdup(chunks, "\n");
1990 if (desc) {
1991 summary = policy_summarize(desc->exit_policy, AF_INET);
1992 smartlist_add_asprintf(chunks, "p %s\n", summary);
1993 tor_free(summary);
1996 if (format == NS_V3_VOTE && vrs) {
1997 if (tor_mem_is_zero((char*)vrs->ed25519_id, ED25519_PUBKEY_LEN)) {
1998 smartlist_add_strdup(chunks, "id ed25519 none\n");
1999 } else {
2000 char ed_b64[BASE64_DIGEST256_LEN+1];
2001 digest256_to_base64(ed_b64, (const char*)vrs->ed25519_id);
2002 smartlist_add_asprintf(chunks, "id ed25519 %s\n", ed_b64);
2007 done:
2008 result = smartlist_join_strings(chunks, "", 0, NULL);
2010 err:
2011 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
2012 smartlist_free(chunks);
2014 return result;
2017 /** Helper for sorting: compares two routerinfos first by address, and then by
2018 * descending order of "usefulness". (An authority is more useful than a
2019 * non-authority; a running router is more useful than a non-running router;
2020 * and a router with more bandwidth is more useful than one with less.)
2022 static int
2023 compare_routerinfo_by_ip_and_bw_(const void **a, const void **b)
2025 routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
2026 int first_is_auth, second_is_auth;
2027 uint32_t bw_kb_first, bw_kb_second;
2028 const node_t *node_first, *node_second;
2029 int first_is_running, second_is_running;
2031 /* we return -1 if first should appear before second... that is,
2032 * if first is a better router. */
2033 if (first->addr < second->addr)
2034 return -1;
2035 else if (first->addr > second->addr)
2036 return 1;
2038 /* Potentially, this next bit could cause k n lg n memeq calls. But in
2039 * reality, we will almost never get here, since addresses will usually be
2040 * different. */
2042 first_is_auth =
2043 router_digest_is_trusted_dir(first->cache_info.identity_digest);
2044 second_is_auth =
2045 router_digest_is_trusted_dir(second->cache_info.identity_digest);
2047 if (first_is_auth && !second_is_auth)
2048 return -1;
2049 else if (!first_is_auth && second_is_auth)
2050 return 1;
2052 node_first = node_get_by_id(first->cache_info.identity_digest);
2053 node_second = node_get_by_id(second->cache_info.identity_digest);
2054 first_is_running = node_first && node_first->is_running;
2055 second_is_running = node_second && node_second->is_running;
2057 if (first_is_running && !second_is_running)
2058 return -1;
2059 else if (!first_is_running && second_is_running)
2060 return 1;
2062 bw_kb_first = dirserv_get_bandwidth_for_router_kb(first);
2063 bw_kb_second = dirserv_get_bandwidth_for_router_kb(second);
2065 if (bw_kb_first > bw_kb_second)
2066 return -1;
2067 else if (bw_kb_first < bw_kb_second)
2068 return 1;
2070 /* They're equal! Compare by identity digest, so there's a
2071 * deterministic order and we avoid flapping. */
2072 return fast_memcmp(first->cache_info.identity_digest,
2073 second->cache_info.identity_digest,
2074 DIGEST_LEN);
2077 /** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
2078 * whose keys are the identity digests of those routers that we're going to
2079 * exclude for Sybil-like appearance. */
2080 static digestmap_t *
2081 get_possible_sybil_list(const smartlist_t *routers)
2083 const or_options_t *options = get_options();
2084 digestmap_t *omit_as_sybil;
2085 smartlist_t *routers_by_ip = smartlist_new();
2086 uint32_t last_addr;
2087 int addr_count;
2088 /* Allow at most this number of Tor servers on a single IP address, ... */
2089 int max_with_same_addr = options->AuthDirMaxServersPerAddr;
2090 if (max_with_same_addr <= 0)
2091 max_with_same_addr = INT_MAX;
2093 smartlist_add_all(routers_by_ip, routers);
2094 smartlist_sort(routers_by_ip, compare_routerinfo_by_ip_and_bw_);
2095 omit_as_sybil = digestmap_new();
2097 last_addr = 0;
2098 addr_count = 0;
2099 SMARTLIST_FOREACH_BEGIN(routers_by_ip, routerinfo_t *, ri) {
2100 if (last_addr != ri->addr) {
2101 last_addr = ri->addr;
2102 addr_count = 1;
2103 } else if (++addr_count > max_with_same_addr) {
2104 digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
2106 } SMARTLIST_FOREACH_END(ri);
2108 smartlist_free(routers_by_ip);
2109 return omit_as_sybil;
2112 /** If there are entries in <b>routers</b> with exactly the same ed25519 keys,
2113 * remove the older one. If they are exactly the same age, remove the one
2114 * with the greater descriptor digest. May alter the order of the list. */
2115 static void
2116 routers_make_ed_keys_unique(smartlist_t *routers)
2118 routerinfo_t *ri2;
2119 digest256map_t *by_ed_key = digest256map_new();
2121 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
2122 ri->omit_from_vote = 0;
2123 if (ri->cache_info.signing_key_cert == NULL)
2124 continue; /* No ed key */
2125 const uint8_t *pk = ri->cache_info.signing_key_cert->signing_key.pubkey;
2126 if ((ri2 = digest256map_get(by_ed_key, pk))) {
2127 /* Duplicate; must omit one. Set the omit_from_vote flag in whichever
2128 * one has the earlier published_on. */
2129 const time_t ri_pub = ri->cache_info.published_on;
2130 const time_t ri2_pub = ri2->cache_info.published_on;
2131 if (ri2_pub < ri_pub ||
2132 (ri2_pub == ri_pub &&
2133 fast_memcmp(ri->cache_info.signed_descriptor_digest,
2134 ri2->cache_info.signed_descriptor_digest,DIGEST_LEN)<0)) {
2135 digest256map_set(by_ed_key, pk, ri);
2136 ri2->omit_from_vote = 1;
2137 } else {
2138 ri->omit_from_vote = 1;
2140 } else {
2141 /* Add to map */
2142 digest256map_set(by_ed_key, pk, ri);
2144 } SMARTLIST_FOREACH_END(ri);
2146 digest256map_free(by_ed_key, NULL);
2148 /* Now remove every router where the omit_from_vote flag got set. */
2149 SMARTLIST_FOREACH_BEGIN(routers, const routerinfo_t *, ri) {
2150 if (ri->omit_from_vote) {
2151 SMARTLIST_DEL_CURRENT(routers, ri);
2153 } SMARTLIST_FOREACH_END(ri);
2156 /** Extract status information from <b>ri</b> and from other authority
2157 * functions and store it in <b>rs</b>>.
2159 * We assume that ri-\>is_running has already been set, e.g. by
2160 * dirserv_set_router_is_running(ri, now);
2162 void
2163 set_routerstatus_from_routerinfo(routerstatus_t *rs,
2164 node_t *node,
2165 routerinfo_t *ri,
2166 time_t now,
2167 int listbadexits)
2169 const or_options_t *options = get_options();
2170 uint32_t routerbw_kb = dirserv_get_credible_bandwidth_kb(ri);
2172 memset(rs, 0, sizeof(routerstatus_t));
2174 rs->is_authority =
2175 router_digest_is_trusted_dir(ri->cache_info.identity_digest);
2177 /* Already set by compute_performance_thresholds. */
2178 rs->is_exit = node->is_exit;
2179 rs->is_stable = node->is_stable =
2180 !dirserv_thinks_router_is_unreliable(now, ri, 1, 0);
2181 rs->is_fast = node->is_fast =
2182 !dirserv_thinks_router_is_unreliable(now, ri, 0, 1);
2183 rs->is_flagged_running = node->is_running; /* computed above */
2185 rs->is_valid = node->is_valid;
2187 if (node->is_fast && node->is_stable &&
2188 ((options->AuthDirGuardBWGuarantee &&
2189 routerbw_kb >= options->AuthDirGuardBWGuarantee/1000) ||
2190 routerbw_kb >= MIN(guard_bandwidth_including_exits_kb,
2191 guard_bandwidth_excluding_exits_kb))) {
2192 long tk = rep_hist_get_weighted_time_known(
2193 node->identity, now);
2194 double wfu = rep_hist_get_weighted_fractional_uptime(
2195 node->identity, now);
2196 rs->is_possible_guard = (wfu >= guard_wfu && tk >= guard_tk) ? 1 : 0;
2197 } else {
2198 rs->is_possible_guard = 0;
2201 rs->is_bad_exit = listbadexits && node->is_bad_exit;
2202 rs->is_hs_dir = node->is_hs_dir =
2203 dirserv_thinks_router_is_hs_dir(ri, node, now);
2205 rs->is_named = rs->is_unnamed = 0;
2207 rs->published_on = ri->cache_info.published_on;
2208 memcpy(rs->identity_digest, node->identity, DIGEST_LEN);
2209 memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest,
2210 DIGEST_LEN);
2211 rs->addr = ri->addr;
2212 strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname));
2213 rs->or_port = ri->or_port;
2214 rs->dir_port = ri->dir_port;
2215 rs->is_v2_dir = ri->supports_tunnelled_dir_requests;
2216 if (options->AuthDirHasIPv6Connectivity == 1 &&
2217 !tor_addr_is_null(&ri->ipv6_addr) &&
2218 node->last_reachable6 >= now - REACHABLE_TIMEOUT) {
2219 /* We're configured as having IPv6 connectivity. There's an IPv6
2220 OR port and it's reachable so copy it to the routerstatus. */
2221 tor_addr_copy(&rs->ipv6_addr, &ri->ipv6_addr);
2222 rs->ipv6_orport = ri->ipv6_orport;
2225 if (options->TestingTorNetwork) {
2226 dirserv_set_routerstatus_testing(rs);
2230 /** Use TestingDirAuthVoteExit, TestingDirAuthVoteGuard, and
2231 * TestingDirAuthVoteHSDir to give out the Exit, Guard, and HSDir flags,
2232 * respectively. But don't set the corresponding node flags.
2233 * Should only be called if TestingTorNetwork is set. */
2234 STATIC void
2235 dirserv_set_routerstatus_testing(routerstatus_t *rs)
2237 const or_options_t *options = get_options();
2239 tor_assert(options->TestingTorNetwork);
2241 if (routerset_contains_routerstatus(options->TestingDirAuthVoteExit,
2242 rs, 0)) {
2243 rs->is_exit = 1;
2244 } else if (options->TestingDirAuthVoteExitIsStrict) {
2245 rs->is_exit = 0;
2248 if (routerset_contains_routerstatus(options->TestingDirAuthVoteGuard,
2249 rs, 0)) {
2250 rs->is_possible_guard = 1;
2251 } else if (options->TestingDirAuthVoteGuardIsStrict) {
2252 rs->is_possible_guard = 0;
2255 if (routerset_contains_routerstatus(options->TestingDirAuthVoteHSDir,
2256 rs, 0)) {
2257 rs->is_hs_dir = 1;
2258 } else if (options->TestingDirAuthVoteHSDirIsStrict) {
2259 rs->is_hs_dir = 0;
2263 /** Routerstatus <b>rs</b> is part of a group of routers that are on
2264 * too narrow an IP-space. Clear out its flags since we don't want it be used
2265 * because of its Sybil-like appearance.
2267 * Leave its BadExit flag alone though, since if we think it's a bad exit,
2268 * we want to vote that way in case all the other authorities are voting
2269 * Running and Exit.
2271 static void
2272 clear_status_flags_on_sybil(routerstatus_t *rs)
2274 rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
2275 rs->is_flagged_running = rs->is_named = rs->is_valid =
2276 rs->is_hs_dir = rs->is_v2_dir = rs->is_possible_guard = 0;
2277 /* FFFF we might want some mechanism to check later on if we
2278 * missed zeroing any flags: it's easy to add a new flag but
2279 * forget to add it to this clause. */
2282 /** The guardfraction of the guard with identity fingerprint <b>guard_id</b>
2283 * is <b>guardfraction_percentage</b>. See if we have a vote routerstatus for
2284 * this guard in <b>vote_routerstatuses</b>, and if we do, register the
2285 * information to it.
2287 * Return 1 if we applied the information and 0 if we couldn't find a
2288 * matching guard.
2290 * Requires that <b>vote_routerstatuses</b> be sorted.
2292 static int
2293 guardfraction_line_apply(const char *guard_id,
2294 uint32_t guardfraction_percentage,
2295 smartlist_t *vote_routerstatuses)
2297 vote_routerstatus_t *vrs = NULL;
2299 tor_assert(vote_routerstatuses);
2301 vrs = smartlist_bsearch(vote_routerstatuses, guard_id,
2302 compare_digest_to_vote_routerstatus_entry);
2304 if (!vrs) {
2305 return 0;
2308 vrs->status.has_guardfraction = 1;
2309 vrs->status.guardfraction_percentage = guardfraction_percentage;
2311 return 1;
2314 /* Given a guard line from a guardfraction file, parse it and register
2315 * its information to <b>vote_routerstatuses</b>.
2317 * Return:
2318 * * 1 if the line was proper and its information got registered.
2319 * * 0 if the line was proper but no currently active guard was found
2320 * to register the guardfraction information to.
2321 * * -1 if the line could not be parsed and set <b>err_msg</b> to a
2322 newly allocated string containing the error message.
2324 static int
2325 guardfraction_file_parse_guard_line(const char *guard_line,
2326 smartlist_t *vote_routerstatuses,
2327 char **err_msg)
2329 char guard_id[DIGEST_LEN];
2330 uint32_t guardfraction;
2331 char *inputs_tmp = NULL;
2332 int num_ok = 1;
2334 smartlist_t *sl = smartlist_new();
2335 int retval = -1;
2337 tor_assert(err_msg);
2339 /* guard_line should contain something like this:
2340 <hex digest> <guardfraction> <appearances> */
2341 smartlist_split_string(sl, guard_line, " ",
2342 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
2343 if (smartlist_len(sl) < 3) {
2344 tor_asprintf(err_msg, "bad line '%s'", guard_line);
2345 goto done;
2348 inputs_tmp = smartlist_get(sl, 0);
2349 if (strlen(inputs_tmp) != HEX_DIGEST_LEN ||
2350 base16_decode(guard_id, DIGEST_LEN,
2351 inputs_tmp, HEX_DIGEST_LEN) != DIGEST_LEN) {
2352 tor_asprintf(err_msg, "bad digest '%s'", inputs_tmp);
2353 goto done;
2356 inputs_tmp = smartlist_get(sl, 1);
2357 /* Guardfraction is an integer in [0, 100]. */
2358 guardfraction =
2359 (uint32_t) tor_parse_long(inputs_tmp, 10, 0, 100, &num_ok, NULL);
2360 if (!num_ok) {
2361 tor_asprintf(err_msg, "wrong percentage '%s'", inputs_tmp);
2362 goto done;
2365 /* If routerstatuses were provided, apply this info to actual routers. */
2366 if (vote_routerstatuses) {
2367 retval = guardfraction_line_apply(guard_id, guardfraction,
2368 vote_routerstatuses);
2369 } else {
2370 retval = 0; /* If we got this far, line was correctly formatted. */
2373 done:
2375 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
2376 smartlist_free(sl);
2378 return retval;
2381 /** Given an inputs line from a guardfraction file, parse it and
2382 * register its information to <b>total_consensuses</b> and
2383 * <b>total_days</b>.
2385 * Return 0 if it parsed well. Return -1 if there was an error, and
2386 * set <b>err_msg</b> to a newly allocated string containing the
2387 * error message.
2389 static int
2390 guardfraction_file_parse_inputs_line(const char *inputs_line,
2391 int *total_consensuses,
2392 int *total_days,
2393 char **err_msg)
2395 int retval = -1;
2396 char *inputs_tmp = NULL;
2397 int num_ok = 1;
2398 smartlist_t *sl = smartlist_new();
2400 tor_assert(err_msg);
2402 /* Second line is inputs information:
2403 * n-inputs <total_consensuses> <total_days>. */
2404 smartlist_split_string(sl, inputs_line, " ",
2405 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
2406 if (smartlist_len(sl) < 2) {
2407 tor_asprintf(err_msg, "incomplete line '%s'", inputs_line);
2408 goto done;
2411 inputs_tmp = smartlist_get(sl, 0);
2412 *total_consensuses =
2413 (int) tor_parse_long(inputs_tmp, 10, 0, INT_MAX, &num_ok, NULL);
2414 if (!num_ok) {
2415 tor_asprintf(err_msg, "unparseable consensus '%s'", inputs_tmp);
2416 goto done;
2419 inputs_tmp = smartlist_get(sl, 1);
2420 *total_days =
2421 (int) tor_parse_long(inputs_tmp, 10, 0, INT_MAX, &num_ok, NULL);
2422 if (!num_ok) {
2423 tor_asprintf(err_msg, "unparseable days '%s'", inputs_tmp);
2424 goto done;
2427 retval = 0;
2429 done:
2430 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
2431 smartlist_free(sl);
2433 return retval;
2436 /* Maximum age of a guardfraction file that we are willing to accept. */
2437 #define MAX_GUARDFRACTION_FILE_AGE (7*24*60*60) /* approx a week */
2439 /** Static strings of guardfraction files. */
2440 #define GUARDFRACTION_DATE_STR "written-at"
2441 #define GUARDFRACTION_INPUTS "n-inputs"
2442 #define GUARDFRACTION_GUARD "guard-seen"
2443 #define GUARDFRACTION_VERSION "guardfraction-file-version"
2445 /** Given a guardfraction file in a string, parse it and register the
2446 * guardfraction information to the provided vote routerstatuses.
2448 * This is the rough format of the guardfraction file:
2450 * guardfraction-file-version 1
2451 * written-at <date and time>
2452 * n-inputs <number of consesuses parsed> <number of days considered>
2454 * guard-seen <fpr 1> <guardfraction percentage> <consensus appearances>
2455 * guard-seen <fpr 2> <guardfraction percentage> <consensus appearances>
2456 * guard-seen <fpr 3> <guardfraction percentage> <consensus appearances>
2457 * guard-seen <fpr 4> <guardfraction percentage> <consensus appearances>
2458 * guard-seen <fpr 5> <guardfraction percentage> <consensus appearances>
2459 * ...
2461 * Return -1 if the parsing failed and 0 if it went smoothly. Parsing
2462 * should tolerate errors in all lines but the written-at header.
2464 STATIC int
2465 dirserv_read_guardfraction_file_from_str(const char *guardfraction_file_str,
2466 smartlist_t *vote_routerstatuses)
2468 config_line_t *front=NULL, *line;
2469 int ret_tmp;
2470 int retval = -1;
2471 int current_line_n = 0; /* line counter for better log messages */
2473 /* Guardfraction info to be parsed */
2474 int total_consensuses = 0;
2475 int total_days = 0;
2477 /* Stats */
2478 int guards_read_n = 0;
2479 int guards_applied_n = 0;
2481 /* Parse file and split it in lines */
2482 ret_tmp = config_get_lines(guardfraction_file_str, &front, 0);
2483 if (ret_tmp < 0) {
2484 log_warn(LD_CONFIG, "Error reading from guardfraction file");
2485 goto done;
2488 /* Sort routerstatuses (needed later when applying guardfraction info) */
2489 if (vote_routerstatuses)
2490 smartlist_sort(vote_routerstatuses, compare_vote_routerstatus_entries);
2492 for (line = front; line; line=line->next) {
2493 current_line_n++;
2495 if (!strcmp(line->key, GUARDFRACTION_VERSION)) {
2496 int num_ok = 1;
2497 unsigned int version;
2499 version =
2500 (unsigned int) tor_parse_long(line->value,
2501 10, 0, INT_MAX, &num_ok, NULL);
2503 if (!num_ok || version != 1) {
2504 log_warn(LD_GENERAL, "Got unknown guardfraction version %d.", version);
2505 goto done;
2507 } else if (!strcmp(line->key, GUARDFRACTION_DATE_STR)) {
2508 time_t file_written_at;
2509 time_t now = time(NULL);
2511 /* First line is 'written-at <date>' */
2512 if (parse_iso_time(line->value, &file_written_at) < 0) {
2513 log_warn(LD_CONFIG, "Guardfraction:%d: Bad date '%s'. Ignoring",
2514 current_line_n, line->value);
2515 goto done; /* don't tolerate failure here. */
2517 if (file_written_at < now - MAX_GUARDFRACTION_FILE_AGE) {
2518 log_warn(LD_CONFIG, "Guardfraction:%d: was written very long ago '%s'",
2519 current_line_n, line->value);
2520 goto done; /* don't tolerate failure here. */
2522 } else if (!strcmp(line->key, GUARDFRACTION_INPUTS)) {
2523 char *err_msg = NULL;
2525 if (guardfraction_file_parse_inputs_line(line->value,
2526 &total_consensuses,
2527 &total_days,
2528 &err_msg) < 0) {
2529 log_warn(LD_CONFIG, "Guardfraction:%d: %s",
2530 current_line_n, err_msg);
2531 tor_free(err_msg);
2532 continue;
2535 } else if (!strcmp(line->key, GUARDFRACTION_GUARD)) {
2536 char *err_msg = NULL;
2538 ret_tmp = guardfraction_file_parse_guard_line(line->value,
2539 vote_routerstatuses,
2540 &err_msg);
2541 if (ret_tmp < 0) { /* failed while parsing the guard line */
2542 log_warn(LD_CONFIG, "Guardfraction:%d: %s",
2543 current_line_n, err_msg);
2544 tor_free(err_msg);
2545 continue;
2548 /* Successfully parsed guard line. Check if it was applied properly. */
2549 guards_read_n++;
2550 if (ret_tmp > 0) {
2551 guards_applied_n++;
2553 } else {
2554 log_warn(LD_CONFIG, "Unknown guardfraction line %d (%s %s)",
2555 current_line_n, line->key, line->value);
2559 retval = 0;
2561 log_info(LD_CONFIG,
2562 "Successfully parsed guardfraction file with %d consensuses over "
2563 "%d days. Parsed %d nodes and applied %d of them%s.",
2564 total_consensuses, total_days, guards_read_n, guards_applied_n,
2565 vote_routerstatuses ? "" : " (no routerstatus provided)" );
2567 done:
2568 config_free_lines(front);
2570 if (retval < 0) {
2571 return retval;
2572 } else {
2573 return guards_read_n;
2577 /** Read a guardfraction file at <b>fname</b> and load all its
2578 * information to <b>vote_routerstatuses</b>. */
2580 dirserv_read_guardfraction_file(const char *fname,
2581 smartlist_t *vote_routerstatuses)
2583 char *guardfraction_file_str;
2585 /* Read file to a string */
2586 guardfraction_file_str = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
2587 if (!guardfraction_file_str) {
2588 log_warn(LD_FS, "Cannot open guardfraction file '%s'. Failing.", fname);
2589 return -1;
2592 return dirserv_read_guardfraction_file_from_str(guardfraction_file_str,
2593 vote_routerstatuses);
2597 * Helper function to parse out a line in the measured bandwidth file
2598 * into a measured_bw_line_t output structure. Returns -1 on failure
2599 * or 0 on success.
2601 STATIC int
2602 measured_bw_line_parse(measured_bw_line_t *out, const char *orig_line)
2604 char *line = tor_strdup(orig_line);
2605 char *cp = line;
2606 int got_bw = 0;
2607 int got_node_id = 0;
2608 char *strtok_state; /* lame sauce d'jour */
2609 cp = tor_strtok_r(cp, " \t", &strtok_state);
2611 if (!cp) {
2612 log_warn(LD_DIRSERV, "Invalid line in bandwidth file: %s",
2613 escaped(orig_line));
2614 tor_free(line);
2615 return -1;
2618 if (orig_line[strlen(orig_line)-1] != '\n') {
2619 log_warn(LD_DIRSERV, "Incomplete line in bandwidth file: %s",
2620 escaped(orig_line));
2621 tor_free(line);
2622 return -1;
2625 do {
2626 if (strcmpstart(cp, "bw=") == 0) {
2627 int parse_ok = 0;
2628 char *endptr;
2629 if (got_bw) {
2630 log_warn(LD_DIRSERV, "Double bw= in bandwidth file line: %s",
2631 escaped(orig_line));
2632 tor_free(line);
2633 return -1;
2635 cp+=strlen("bw=");
2637 out->bw_kb = tor_parse_long(cp, 0, 0, LONG_MAX, &parse_ok, &endptr);
2638 if (!parse_ok || (*endptr && !TOR_ISSPACE(*endptr))) {
2639 log_warn(LD_DIRSERV, "Invalid bandwidth in bandwidth file line: %s",
2640 escaped(orig_line));
2641 tor_free(line);
2642 return -1;
2644 got_bw=1;
2645 } else if (strcmpstart(cp, "node_id=$") == 0) {
2646 if (got_node_id) {
2647 log_warn(LD_DIRSERV, "Double node_id= in bandwidth file line: %s",
2648 escaped(orig_line));
2649 tor_free(line);
2650 return -1;
2652 cp+=strlen("node_id=$");
2654 if (strlen(cp) != HEX_DIGEST_LEN ||
2655 base16_decode(out->node_id, DIGEST_LEN,
2656 cp, HEX_DIGEST_LEN) != DIGEST_LEN) {
2657 log_warn(LD_DIRSERV, "Invalid node_id in bandwidth file line: %s",
2658 escaped(orig_line));
2659 tor_free(line);
2660 return -1;
2662 strlcpy(out->node_hex, cp, sizeof(out->node_hex));
2663 got_node_id=1;
2665 } while ((cp = tor_strtok_r(NULL, " \t", &strtok_state)));
2667 if (got_bw && got_node_id) {
2668 tor_free(line);
2669 return 0;
2670 } else {
2671 log_warn(LD_DIRSERV, "Incomplete line in bandwidth file: %s",
2672 escaped(orig_line));
2673 tor_free(line);
2674 return -1;
2679 * Helper function to apply a parsed measurement line to a list
2680 * of bandwidth statuses. Returns true if a line is found,
2681 * false otherwise.
2683 STATIC int
2684 measured_bw_line_apply(measured_bw_line_t *parsed_line,
2685 smartlist_t *routerstatuses)
2687 vote_routerstatus_t *rs = NULL;
2688 if (!routerstatuses)
2689 return 0;
2691 rs = smartlist_bsearch(routerstatuses, parsed_line->node_id,
2692 compare_digest_to_vote_routerstatus_entry);
2694 if (rs) {
2695 rs->has_measured_bw = 1;
2696 rs->measured_bw_kb = (uint32_t)parsed_line->bw_kb;
2697 } else {
2698 log_info(LD_DIRSERV, "Node ID %s not found in routerstatus list",
2699 parsed_line->node_hex);
2702 return rs != NULL;
2706 * Read the measured bandwidth file and apply it to the list of
2707 * vote_routerstatus_t. Returns -1 on error, 0 otherwise.
2710 dirserv_read_measured_bandwidths(const char *from_file,
2711 smartlist_t *routerstatuses)
2713 char line[512];
2714 FILE *fp = tor_fopen_cloexec(from_file, "r");
2715 int applied_lines = 0;
2716 time_t file_time, now;
2717 int ok;
2719 if (fp == NULL) {
2720 log_warn(LD_CONFIG, "Can't open bandwidth file at configured location: %s",
2721 from_file);
2722 return -1;
2725 if (!fgets(line, sizeof(line), fp)
2726 || !strlen(line) || line[strlen(line)-1] != '\n') {
2727 log_warn(LD_DIRSERV, "Long or truncated time in bandwidth file: %s",
2728 escaped(line));
2729 fclose(fp);
2730 return -1;
2733 line[strlen(line)-1] = '\0';
2734 file_time = (time_t)tor_parse_ulong(line, 10, 0, ULONG_MAX, &ok, NULL);
2735 if (!ok) {
2736 log_warn(LD_DIRSERV, "Non-integer time in bandwidth file: %s",
2737 escaped(line));
2738 fclose(fp);
2739 return -1;
2742 now = time(NULL);
2743 if ((now - file_time) > MAX_MEASUREMENT_AGE) {
2744 log_warn(LD_DIRSERV, "Bandwidth measurement file stale. Age: %u",
2745 (unsigned)(time(NULL) - file_time));
2746 fclose(fp);
2747 return -1;
2750 if (routerstatuses)
2751 smartlist_sort(routerstatuses, compare_vote_routerstatus_entries);
2753 while (!feof(fp)) {
2754 measured_bw_line_t parsed_line;
2755 if (fgets(line, sizeof(line), fp) && strlen(line)) {
2756 if (measured_bw_line_parse(&parsed_line, line) != -1) {
2757 /* Also cache the line for dirserv_get_bandwidth_for_router() */
2758 dirserv_cache_measured_bw(&parsed_line, file_time);
2759 if (measured_bw_line_apply(&parsed_line, routerstatuses) > 0)
2760 applied_lines++;
2765 /* Now would be a nice time to clean the cache, too */
2766 dirserv_expire_measured_bw_cache(now);
2768 fclose(fp);
2769 log_info(LD_DIRSERV,
2770 "Bandwidth measurement file successfully read. "
2771 "Applied %d measurements.", applied_lines);
2772 return 0;
2775 /** Return a new networkstatus_t* containing our current opinion. (For v3
2776 * authorities) */
2777 networkstatus_t *
2778 dirserv_generate_networkstatus_vote_obj(crypto_pk_t *private_key,
2779 authority_cert_t *cert)
2781 const or_options_t *options = get_options();
2782 networkstatus_t *v3_out = NULL;
2783 uint32_t addr;
2784 char *hostname = NULL, *client_versions = NULL, *server_versions = NULL;
2785 const char *contact;
2786 smartlist_t *routers, *routerstatuses;
2787 char identity_digest[DIGEST_LEN];
2788 char signing_key_digest[DIGEST_LEN];
2789 int listbadexits = options->AuthDirListBadExits;
2790 routerlist_t *rl = router_get_routerlist();
2791 time_t now = time(NULL);
2792 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2793 networkstatus_voter_info_t *voter = NULL;
2794 vote_timing_t timing;
2795 digestmap_t *omit_as_sybil = NULL;
2796 const int vote_on_reachability = running_long_enough_to_decide_unreachable();
2797 smartlist_t *microdescriptors = NULL;
2799 tor_assert(private_key);
2800 tor_assert(cert);
2802 if (crypto_pk_get_digest(private_key, signing_key_digest)<0) {
2803 log_err(LD_BUG, "Error computing signing key digest");
2804 return NULL;
2806 if (crypto_pk_get_digest(cert->identity_key, identity_digest)<0) {
2807 log_err(LD_BUG, "Error computing identity key digest");
2808 return NULL;
2810 if (resolve_my_address(LOG_WARN, options, &addr, NULL, &hostname)<0) {
2811 log_warn(LD_NET, "Couldn't resolve my hostname");
2812 return NULL;
2814 if (!hostname || !strchr(hostname, '.')) {
2815 tor_free(hostname);
2816 hostname = tor_dup_ip(addr);
2819 if (options->VersioningAuthoritativeDir) {
2820 client_versions = format_versions_list(options->RecommendedClientVersions);
2821 server_versions = format_versions_list(options->RecommendedServerVersions);
2824 contact = get_options()->ContactInfo;
2825 if (!contact)
2826 contact = "(none)";
2829 * Do this so dirserv_compute_performance_thresholds() and
2830 * set_routerstatus_from_routerinfo() see up-to-date bandwidth info.
2832 if (options->V3BandwidthsFile) {
2833 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
2834 } else {
2836 * No bandwidths file; clear the measured bandwidth cache in case we had
2837 * one last time around.
2839 if (dirserv_get_measured_bw_cache_size() > 0) {
2840 dirserv_clear_measured_bw_cache();
2844 /* precompute this part, since we need it to decide what "stable"
2845 * means. */
2846 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2847 dirserv_set_router_is_running(ri, now);
2850 routers = smartlist_new();
2851 smartlist_add_all(routers, rl->routers);
2852 routers_make_ed_keys_unique(routers);
2853 /* After this point, don't use rl->routers; use 'routers' instead. */
2854 routers_sort_by_identity(routers);
2855 omit_as_sybil = get_possible_sybil_list(routers);
2857 DIGESTMAP_FOREACH(omit_as_sybil, sybil_id, void *, ignore) {
2858 (void) ignore;
2859 rep_hist_make_router_pessimal(sybil_id, now);
2860 } DIGESTMAP_FOREACH_END;
2862 /* Count how many have measured bandwidths so we know how to assign flags;
2863 * this must come before dirserv_compute_performance_thresholds() */
2864 dirserv_count_measured_bws(routers);
2866 dirserv_compute_performance_thresholds(omit_as_sybil);
2868 routerstatuses = smartlist_new();
2869 microdescriptors = smartlist_new();
2871 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
2872 if (ri->cache_info.published_on >= cutoff) {
2873 routerstatus_t *rs;
2874 vote_routerstatus_t *vrs;
2875 node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
2876 if (!node)
2877 continue;
2879 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
2880 rs = &vrs->status;
2881 set_routerstatus_from_routerinfo(rs, node, ri, now,
2882 listbadexits);
2884 if (ri->cache_info.signing_key_cert) {
2885 memcpy(vrs->ed25519_id,
2886 ri->cache_info.signing_key_cert->signing_key.pubkey,
2887 ED25519_PUBKEY_LEN);
2890 if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
2891 clear_status_flags_on_sybil(rs);
2893 if (!vote_on_reachability)
2894 rs->is_flagged_running = 0;
2896 vrs->version = version_from_platform(ri->platform);
2897 if (ri->protocol_list) {
2898 vrs->protocols = tor_strdup(ri->protocol_list);
2899 } else {
2900 vrs->protocols = tor_strdup(
2901 protover_compute_for_old_tor(vrs->version));
2903 vrs->microdesc = dirvote_format_all_microdesc_vote_lines(ri, now,
2904 microdescriptors);
2906 smartlist_add(routerstatuses, vrs);
2908 } SMARTLIST_FOREACH_END(ri);
2911 smartlist_t *added =
2912 microdescs_add_list_to_cache(get_microdesc_cache(),
2913 microdescriptors, SAVED_NOWHERE, 0);
2914 smartlist_free(added);
2915 smartlist_free(microdescriptors);
2918 smartlist_free(routers);
2919 digestmap_free(omit_as_sybil, NULL);
2921 /* Apply guardfraction information to routerstatuses. */
2922 if (options->GuardfractionFile) {
2923 dirserv_read_guardfraction_file(options->GuardfractionFile,
2924 routerstatuses);
2927 /* This pass through applies the measured bw lines to the routerstatuses */
2928 if (options->V3BandwidthsFile) {
2929 dirserv_read_measured_bandwidths(options->V3BandwidthsFile,
2930 routerstatuses);
2931 } else {
2933 * No bandwidths file; clear the measured bandwidth cache in case we had
2934 * one last time around.
2936 if (dirserv_get_measured_bw_cache_size() > 0) {
2937 dirserv_clear_measured_bw_cache();
2941 v3_out = tor_malloc_zero(sizeof(networkstatus_t));
2943 v3_out->type = NS_TYPE_VOTE;
2944 dirvote_get_preferred_voting_intervals(&timing);
2945 v3_out->published = now;
2947 char tbuf[ISO_TIME_LEN+1];
2948 networkstatus_t *current_consensus =
2949 networkstatus_get_live_consensus(now);
2950 long last_consensus_interval; /* only used to pick a valid_after */
2951 if (current_consensus)
2952 last_consensus_interval = current_consensus->fresh_until -
2953 current_consensus->valid_after;
2954 else
2955 last_consensus_interval = options->TestingV3AuthInitialVotingInterval;
2956 v3_out->valid_after =
2957 dirvote_get_start_of_next_interval(now, (int)last_consensus_interval,
2958 options->TestingV3AuthVotingStartOffset);
2959 format_iso_time(tbuf, v3_out->valid_after);
2960 log_notice(LD_DIR,"Choosing valid-after time in vote as %s: "
2961 "consensus_set=%d, last_interval=%d",
2962 tbuf, current_consensus?1:0, (int)last_consensus_interval);
2964 v3_out->fresh_until = v3_out->valid_after + timing.vote_interval;
2965 v3_out->valid_until = v3_out->valid_after +
2966 (timing.vote_interval * timing.n_intervals_valid);
2967 v3_out->vote_seconds = timing.vote_delay;
2968 v3_out->dist_seconds = timing.dist_delay;
2969 tor_assert(v3_out->vote_seconds > 0);
2970 tor_assert(v3_out->dist_seconds > 0);
2971 tor_assert(timing.n_intervals_valid > 0);
2973 v3_out->client_versions = client_versions;
2974 v3_out->server_versions = server_versions;
2976 /* These are hardwired, to avoid disaster. */
2977 v3_out->recommended_relay_protocols =
2978 tor_strdup("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 "
2979 "Link=4 LinkAuth=1 Microdesc=1-2 Relay=2");
2980 v3_out->recommended_client_protocols =
2981 tor_strdup("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 "
2982 "Link=4 LinkAuth=1 Microdesc=1-2 Relay=2");
2983 v3_out->required_client_protocols =
2984 tor_strdup("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 "
2985 "Link=4 LinkAuth=1 Microdesc=1-2 Relay=2");
2986 v3_out->required_relay_protocols =
2987 tor_strdup("Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 "
2988 "Link=3-4 LinkAuth=1 Microdesc=1 Relay=1-2");
2990 /* We are not allowed to vote to require anything we don't have. */
2991 tor_assert(protover_all_supported(v3_out->required_relay_protocols, NULL));
2992 tor_assert(protover_all_supported(v3_out->required_client_protocols, NULL));
2994 /* We should not recommend anything we don't have. */
2995 tor_assert_nonfatal(protover_all_supported(
2996 v3_out->recommended_relay_protocols, NULL));
2997 tor_assert_nonfatal(protover_all_supported(
2998 v3_out->recommended_client_protocols, NULL));
3000 v3_out->package_lines = smartlist_new();
3002 config_line_t *cl;
3003 for (cl = get_options()->RecommendedPackages; cl; cl = cl->next) {
3004 if (validate_recommended_package_line(cl->value))
3005 smartlist_add_strdup(v3_out->package_lines, cl->value);
3009 v3_out->known_flags = smartlist_new();
3010 smartlist_split_string(v3_out->known_flags,
3011 "Authority Exit Fast Guard Stable V2Dir Valid HSDir",
3012 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3013 if (vote_on_reachability)
3014 smartlist_add_strdup(v3_out->known_flags, "Running");
3015 if (listbadexits)
3016 smartlist_add_strdup(v3_out->known_flags, "BadExit");
3017 smartlist_sort_strings(v3_out->known_flags);
3019 if (options->ConsensusParams) {
3020 v3_out->net_params = smartlist_new();
3021 smartlist_split_string(v3_out->net_params,
3022 options->ConsensusParams, NULL, 0, 0);
3023 smartlist_sort_strings(v3_out->net_params);
3026 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
3027 voter->nickname = tor_strdup(options->Nickname);
3028 memcpy(voter->identity_digest, identity_digest, DIGEST_LEN);
3029 voter->sigs = smartlist_new();
3030 voter->address = hostname;
3031 voter->addr = addr;
3032 voter->dir_port = router_get_advertised_dir_port(options, 0);
3033 voter->or_port = router_get_advertised_or_port(options);
3034 voter->contact = tor_strdup(contact);
3035 if (options->V3AuthUseLegacyKey) {
3036 authority_cert_t *c = get_my_v3_legacy_cert();
3037 if (c) {
3038 if (crypto_pk_get_digest(c->identity_key, voter->legacy_id_digest)) {
3039 log_warn(LD_BUG, "Unable to compute digest of legacy v3 identity key");
3040 memset(voter->legacy_id_digest, 0, DIGEST_LEN);
3045 v3_out->voters = smartlist_new();
3046 smartlist_add(v3_out->voters, voter);
3047 v3_out->cert = authority_cert_dup(cert);
3048 v3_out->routerstatus_list = routerstatuses;
3049 /* Note: networkstatus_digest is unset; it won't get set until we actually
3050 * format the vote. */
3052 return v3_out;
3055 /** As dirserv_get_routerdescs(), but instead of getting signed_descriptor_t
3056 * pointers, adds copies of digests to fps_out, and doesn't use the
3057 * /tor/server/ prefix. For a /d/ request, adds descriptor digests; for other
3058 * requests, adds identity digests.
3061 dirserv_get_routerdesc_spool(smartlist_t *spool_out,
3062 const char *key,
3063 dir_spool_source_t source,
3064 int conn_is_encrypted,
3065 const char **msg_out)
3067 *msg_out = NULL;
3069 if (!strcmp(key, "all")) {
3070 const routerlist_t *rl = router_get_routerlist();
3071 SMARTLIST_FOREACH_BEGIN(rl->routers, const routerinfo_t *, r) {
3072 spooled_resource_t *spooled;
3073 spooled = spooled_resource_new(source,
3074 (const uint8_t *)r->cache_info.identity_digest,
3075 DIGEST_LEN);
3076 /* Treat "all" requests as if they were unencrypted */
3077 conn_is_encrypted = 0;
3078 smartlist_add(spool_out, spooled);
3079 } SMARTLIST_FOREACH_END(r);
3080 } else if (!strcmp(key, "authority")) {
3081 const routerinfo_t *ri = router_get_my_routerinfo();
3082 if (ri)
3083 smartlist_add(spool_out,
3084 spooled_resource_new(source,
3085 (const uint8_t *)ri->cache_info.identity_digest,
3086 DIGEST_LEN));
3087 } else if (!strcmpstart(key, "d/")) {
3088 key += strlen("d/");
3089 dir_split_resource_into_spoolable(key, source, spool_out, NULL,
3090 DSR_HEX|DSR_SORT_UNIQ);
3091 } else if (!strcmpstart(key, "fp/")) {
3092 key += strlen("fp/");
3093 dir_split_resource_into_spoolable(key, source, spool_out, NULL,
3094 DSR_HEX|DSR_SORT_UNIQ);
3095 } else {
3096 *msg_out = "Not found";
3097 return -1;
3100 if (! conn_is_encrypted) {
3101 /* Remove anything that insists it not be sent unencrypted. */
3102 SMARTLIST_FOREACH_BEGIN(spool_out, spooled_resource_t *, spooled) {
3103 const uint8_t *body = NULL;
3104 size_t bodylen = 0;
3105 int r = spooled_resource_lookup_body(spooled, conn_is_encrypted,
3106 &body, &bodylen, NULL);
3107 if (r < 0 || body == NULL || bodylen == 0) {
3108 SMARTLIST_DEL_CURRENT(spool_out, spooled);
3109 spooled_resource_free(spooled);
3111 } SMARTLIST_FOREACH_END(spooled);
3114 if (!smartlist_len(spool_out)) {
3115 *msg_out = "Servers unavailable";
3116 return -1;
3118 return 0;
3121 /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
3122 * <b>key</b>. The key should be either
3123 * - "/tor/server/authority" for our own routerinfo;
3124 * - "/tor/server/all" for all the routerinfos we have, concatenated;
3125 * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
3126 * hex identity digests; or
3127 * - "/tor/server/d/D" where D is a plus-separated sequence
3128 * of server descriptor digests, in hex.
3130 * Return 0 if we found some matching descriptors, or -1 if we do not
3131 * have any descriptors, no matching descriptors, or if we did not
3132 * recognize the key (URL).
3133 * If -1 is returned *<b>msg</b> will be set to an appropriate error
3134 * message.
3136 * XXXX rename this function. It's only called from the controller.
3137 * XXXX in fact, refactor this function, merging as much as possible.
3140 dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
3141 const char **msg)
3143 *msg = NULL;
3145 if (!strcmp(key, "/tor/server/all")) {
3146 routerlist_t *rl = router_get_routerlist();
3147 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
3148 smartlist_add(descs_out, &(r->cache_info)));
3149 } else if (!strcmp(key, "/tor/server/authority")) {
3150 const routerinfo_t *ri = router_get_my_routerinfo();
3151 if (ri)
3152 smartlist_add(descs_out, (void*) &(ri->cache_info));
3153 } else if (!strcmpstart(key, "/tor/server/d/")) {
3154 smartlist_t *digests = smartlist_new();
3155 key += strlen("/tor/server/d/");
3156 dir_split_resource_into_fingerprints(key, digests, NULL,
3157 DSR_HEX|DSR_SORT_UNIQ);
3158 SMARTLIST_FOREACH(digests, const char *, d,
3160 signed_descriptor_t *sd = router_get_by_descriptor_digest(d);
3161 if (sd)
3162 smartlist_add(descs_out,sd);
3164 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
3165 smartlist_free(digests);
3166 } else if (!strcmpstart(key, "/tor/server/fp/")) {
3167 smartlist_t *digests = smartlist_new();
3168 time_t cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
3169 key += strlen("/tor/server/fp/");
3170 dir_split_resource_into_fingerprints(key, digests, NULL,
3171 DSR_HEX|DSR_SORT_UNIQ);
3172 SMARTLIST_FOREACH_BEGIN(digests, const char *, d) {
3173 if (router_digest_is_me(d)) {
3174 /* calling router_get_my_routerinfo() to make sure it exists */
3175 const routerinfo_t *ri = router_get_my_routerinfo();
3176 if (ri)
3177 smartlist_add(descs_out, (void*) &(ri->cache_info));
3178 } else {
3179 const routerinfo_t *ri = router_get_by_id_digest(d);
3180 /* Don't actually serve a descriptor that everyone will think is
3181 * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
3182 * Tors from downloading descriptors that they will throw away.
3184 if (ri && ri->cache_info.published_on > cutoff)
3185 smartlist_add(descs_out, (void*) &(ri->cache_info));
3187 } SMARTLIST_FOREACH_END(d);
3188 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
3189 smartlist_free(digests);
3190 } else {
3191 *msg = "Key not recognized";
3192 return -1;
3195 if (!smartlist_len(descs_out)) {
3196 *msg = "Servers unavailable";
3197 return -1;
3199 return 0;
3202 /** Called when a TLS handshake has completed successfully with a
3203 * router listening at <b>address</b>:<b>or_port</b>, and has yielded
3204 * a certificate with digest <b>digest_rcvd</b>.
3206 * Inform the reachability checker that we could get to this relay.
3208 void
3209 dirserv_orconn_tls_done(const tor_addr_t *addr,
3210 uint16_t or_port,
3211 const char *digest_rcvd,
3212 const ed25519_public_key_t *ed_id_rcvd)
3214 node_t *node = NULL;
3215 tor_addr_port_t orport;
3216 routerinfo_t *ri = NULL;
3217 time_t now = time(NULL);
3218 tor_assert(addr);
3219 tor_assert(digest_rcvd);
3221 node = node_get_mutable_by_id(digest_rcvd);
3222 if (node == NULL || node->ri == NULL)
3223 return;
3225 ri = node->ri;
3227 if (get_options()->AuthDirTestEd25519LinkKeys &&
3228 node_supports_ed25519_link_authentication(node) &&
3229 ri->cache_info.signing_key_cert) {
3230 /* We allow the node to have an ed25519 key if we haven't been told one in
3231 * the routerinfo, but if we *HAVE* been told one in the routerinfo, it
3232 * needs to match. */
3233 const ed25519_public_key_t *expected_id =
3234 &ri->cache_info.signing_key_cert->signing_key;
3235 tor_assert(!ed25519_public_key_is_zero(expected_id));
3236 if (! ed_id_rcvd || ! ed25519_pubkey_eq(ed_id_rcvd, expected_id)) {
3237 log_info(LD_DIRSERV, "Router at %s:%d with RSA ID %s "
3238 "did not present expected Ed25519 ID.",
3239 fmt_addr(addr), or_port, hex_str(digest_rcvd, DIGEST_LEN));
3240 return; /* Don't mark it as reachable. */
3244 tor_addr_copy(&orport.addr, addr);
3245 orport.port = or_port;
3246 if (router_has_orport(ri, &orport)) {
3247 /* Found the right router. */
3248 if (!authdir_mode_bridge(get_options()) ||
3249 ri->purpose == ROUTER_PURPOSE_BRIDGE) {
3250 char addrstr[TOR_ADDR_BUF_LEN];
3251 /* This is a bridge or we're not a bridge authority --
3252 mark it as reachable. */
3253 log_info(LD_DIRSERV, "Found router %s to be reachable at %s:%d. Yay.",
3254 router_describe(ri),
3255 tor_addr_to_str(addrstr, addr, sizeof(addrstr), 1),
3256 ri->or_port);
3257 if (tor_addr_family(addr) == AF_INET) {
3258 rep_hist_note_router_reachable(digest_rcvd, addr, or_port, now);
3259 node->last_reachable = now;
3260 } else if (tor_addr_family(addr) == AF_INET6) {
3261 /* No rephist for IPv6. */
3262 node->last_reachable6 = now;
3268 /** Called when we, as an authority, receive a new router descriptor either as
3269 * an upload or a download. Used to decide whether to relaunch reachability
3270 * testing for the server. */
3272 dirserv_should_launch_reachability_test(const routerinfo_t *ri,
3273 const routerinfo_t *ri_old)
3275 if (!authdir_mode_handles_descs(get_options(), ri->purpose))
3276 return 0;
3277 if (!ri_old) {
3278 /* New router: Launch an immediate reachability test, so we will have an
3279 * opinion soon in case we're generating a consensus soon */
3280 return 1;
3282 if (ri_old->is_hibernating && !ri->is_hibernating) {
3283 /* It just came out of hibernation; launch a reachability test */
3284 return 1;
3286 if (! routers_have_same_or_addrs(ri, ri_old)) {
3287 /* Address or port changed; launch a reachability test */
3288 return 1;
3290 return 0;
3293 /** Helper function for dirserv_test_reachability(). Start a TLS
3294 * connection to <b>router</b>, and annotate it with when we started
3295 * the test. */
3296 void
3297 dirserv_single_reachability_test(time_t now, routerinfo_t *router)
3299 const or_options_t *options = get_options();
3300 channel_t *chan = NULL;
3301 const node_t *node = NULL;
3302 tor_addr_t router_addr;
3303 const ed25519_public_key_t *ed_id_key;
3304 (void) now;
3306 tor_assert(router);
3307 node = node_get_by_id(router->cache_info.identity_digest);
3308 tor_assert(node);
3310 if (options->AuthDirTestEd25519LinkKeys &&
3311 node_supports_ed25519_link_authentication(node)) {
3312 ed_id_key = &router->cache_info.signing_key_cert->signing_key;
3313 } else {
3314 ed_id_key = NULL;
3317 /* IPv4. */
3318 log_debug(LD_OR,"Testing reachability of %s at %s:%u.",
3319 router->nickname, fmt_addr32(router->addr), router->or_port);
3320 tor_addr_from_ipv4h(&router_addr, router->addr);
3321 chan = channel_tls_connect(&router_addr, router->or_port,
3322 router->cache_info.identity_digest,
3323 ed_id_key);
3324 if (chan) command_setup_channel(chan);
3326 /* Possible IPv6. */
3327 if (get_options()->AuthDirHasIPv6Connectivity == 1 &&
3328 !tor_addr_is_null(&router->ipv6_addr)) {
3329 char addrstr[TOR_ADDR_BUF_LEN];
3330 log_debug(LD_OR, "Testing reachability of %s at %s:%u.",
3331 router->nickname,
3332 tor_addr_to_str(addrstr, &router->ipv6_addr, sizeof(addrstr), 1),
3333 router->ipv6_orport);
3334 chan = channel_tls_connect(&router->ipv6_addr, router->ipv6_orport,
3335 router->cache_info.identity_digest,
3336 ed_id_key);
3337 if (chan) command_setup_channel(chan);
3341 /** Auth dir server only: load balance such that we only
3342 * try a few connections per call.
3344 * The load balancing is such that if we get called once every ten
3345 * seconds, we will cycle through all the tests in
3346 * REACHABILITY_TEST_CYCLE_PERIOD seconds (a bit over 20 minutes).
3348 void
3349 dirserv_test_reachability(time_t now)
3351 /* XXX decide what to do here; see or-talk thread "purging old router
3352 * information, revocation." -NM
3353 * We can't afford to mess with this in 0.1.2.x. The reason is that
3354 * if we stop doing reachability tests on some of routerlist, then
3355 * we'll for-sure think they're down, which may have unexpected
3356 * effects in other parts of the code. It doesn't hurt much to do
3357 * the testing, and directory authorities are easy to upgrade. Let's
3358 * wait til 0.2.0. -RD */
3359 // time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
3360 routerlist_t *rl = router_get_routerlist();
3361 static char ctr = 0;
3362 int bridge_auth = authdir_mode_bridge(get_options());
3364 SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, router) {
3365 const char *id_digest = router->cache_info.identity_digest;
3366 if (router_is_me(router))
3367 continue;
3368 if (bridge_auth && router->purpose != ROUTER_PURPOSE_BRIDGE)
3369 continue; /* bridge authorities only test reachability on bridges */
3370 // if (router->cache_info.published_on > cutoff)
3371 // continue;
3372 if ((((uint8_t)id_digest[0]) % REACHABILITY_MODULO_PER_TEST) == ctr) {
3373 dirserv_single_reachability_test(now, router);
3375 } SMARTLIST_FOREACH_END(router);
3376 ctr = (ctr + 1) % REACHABILITY_MODULO_PER_TEST; /* increment ctr */
3379 /* ==========
3380 * Spooling code.
3381 * ========== */
3383 spooled_resource_t *
3384 spooled_resource_new(dir_spool_source_t source,
3385 const uint8_t *digest, size_t digestlen)
3387 spooled_resource_t *spooled = tor_malloc_zero(sizeof(spooled_resource_t));
3388 spooled->spool_source = source;
3389 switch (source) {
3390 case DIR_SPOOL_NETWORKSTATUS:
3391 spooled->spool_eagerly = 0;
3392 break;
3393 case DIR_SPOOL_SERVER_BY_DIGEST:
3394 case DIR_SPOOL_SERVER_BY_FP:
3395 case DIR_SPOOL_EXTRA_BY_DIGEST:
3396 case DIR_SPOOL_EXTRA_BY_FP:
3397 case DIR_SPOOL_MICRODESC:
3398 default:
3399 spooled->spool_eagerly = 1;
3400 break;
3401 case DIR_SPOOL_CONSENSUS_CACHE_ENTRY:
3402 tor_assert_unreached();
3403 break;
3405 tor_assert(digestlen <= sizeof(spooled->digest));
3406 if (digest)
3407 memcpy(spooled->digest, digest, digestlen);
3408 return spooled;
3412 * Create a new spooled_resource_t to spool the contents of <b>entry</b> to
3413 * the user. Return the spooled object on success, or NULL on failure (which
3414 * is probably caused by a failure to map the body of the item from disk).
3416 * Adds a reference to entry's reference counter.
3418 spooled_resource_t *
3419 spooled_resource_new_from_cache_entry(consensus_cache_entry_t *entry)
3421 spooled_resource_t *spooled = tor_malloc_zero(sizeof(spooled_resource_t));
3422 spooled->spool_source = DIR_SPOOL_CONSENSUS_CACHE_ENTRY;
3423 spooled->spool_eagerly = 0;
3424 consensus_cache_entry_incref(entry);
3425 spooled->consensus_cache_entry = entry;
3427 int r = consensus_cache_entry_get_body(entry,
3428 &spooled->cce_body,
3429 &spooled->cce_len);
3430 if (r == 0) {
3431 return spooled;
3432 } else {
3433 spooled_resource_free(spooled);
3434 return NULL;
3438 /** Release all storage held by <b>spooled</b>. */
3439 void
3440 spooled_resource_free(spooled_resource_t *spooled)
3442 if (spooled == NULL)
3443 return;
3445 if (spooled->cached_dir_ref) {
3446 cached_dir_decref(spooled->cached_dir_ref);
3449 if (spooled->consensus_cache_entry) {
3450 consensus_cache_entry_decref(spooled->consensus_cache_entry);
3453 tor_free(spooled);
3456 /** When spooling data from a cached_dir_t object, we always add
3457 * at least this much. */
3458 #define DIRSERV_CACHED_DIR_CHUNK_SIZE 8192
3460 /** Return an compression ratio for compressing objects from <b>source</b>.
3462 static double
3463 estimate_compression_ratio(dir_spool_source_t source)
3465 /* We should put in better estimates here, depending on the number of
3466 objects and their type */
3467 (void) source;
3468 return 0.5;
3471 /** Return an estimated number of bytes needed for transmitting the
3472 * resource in <b>spooled</b> on <b>conn</b>
3474 * As a convenient side-effect, set *<b>published_out</b> to the resource's
3475 * publication time.
3477 static size_t
3478 spooled_resource_estimate_size(const spooled_resource_t *spooled,
3479 dir_connection_t *conn,
3480 int compressed,
3481 time_t *published_out)
3483 if (spooled->spool_eagerly) {
3484 const uint8_t *body = NULL;
3485 size_t bodylen = 0;
3486 int r = spooled_resource_lookup_body(spooled,
3487 connection_dir_is_encrypted(conn),
3488 &body, &bodylen,
3489 published_out);
3490 if (r == -1 || body == NULL || bodylen == 0)
3491 return 0;
3492 if (compressed) {
3493 double ratio = estimate_compression_ratio(spooled->spool_source);
3494 bodylen = (size_t)(bodylen * ratio);
3496 return bodylen;
3497 } else {
3498 cached_dir_t *cached;
3499 if (spooled->consensus_cache_entry) {
3500 return spooled->cce_len;
3502 if (spooled->cached_dir_ref) {
3503 cached = spooled->cached_dir_ref;
3504 } else {
3505 cached = spooled_resource_lookup_cached_dir(spooled,
3506 published_out);
3508 if (cached == NULL) {
3509 return 0;
3511 size_t result = compressed ? cached->dir_compressed_len : cached->dir_len;
3512 return result;
3516 /** Return code for spooled_resource_flush_some */
3517 typedef enum {
3518 SRFS_ERR = -1,
3519 SRFS_MORE = 0,
3520 SRFS_DONE
3521 } spooled_resource_flush_status_t;
3523 /** Flush some or all of the bytes from <b>spooled</b> onto <b>conn</b>.
3524 * Return SRFS_ERR on error, SRFS_MORE if there are more bytes to flush from
3525 * this spooled resource, or SRFS_DONE if we are done flushing this spooled
3526 * resource.
3528 static spooled_resource_flush_status_t
3529 spooled_resource_flush_some(spooled_resource_t *spooled,
3530 dir_connection_t *conn)
3532 if (spooled->spool_eagerly) {
3533 /* Spool_eagerly resources are sent all-at-once. */
3534 const uint8_t *body = NULL;
3535 size_t bodylen = 0;
3536 int r = spooled_resource_lookup_body(spooled,
3537 connection_dir_is_encrypted(conn),
3538 &body, &bodylen, NULL);
3539 if (r == -1 || body == NULL || bodylen == 0) {
3540 /* Absent objects count as "done". */
3541 return SRFS_DONE;
3543 if (conn->compress_state) {
3544 connection_write_to_buf_compress((const char*)body, bodylen, conn, 0);
3545 } else {
3546 connection_write_to_buf((const char*)body, bodylen, TO_CONN(conn));
3548 return SRFS_DONE;
3549 } else {
3550 cached_dir_t *cached = spooled->cached_dir_ref;
3551 consensus_cache_entry_t *cce = spooled->consensus_cache_entry;
3552 if (cached == NULL && cce == NULL) {
3553 /* The cached_dir_t hasn't been materialized yet. So let's look it up. */
3554 cached = spooled->cached_dir_ref =
3555 spooled_resource_lookup_cached_dir(spooled, NULL);
3556 if (!cached) {
3557 /* Absent objects count as done. */
3558 return SRFS_DONE;
3560 ++cached->refcnt;
3561 tor_assert_nonfatal(spooled->cached_dir_offset == 0);
3564 if (BUG(!cached && !cce))
3565 return SRFS_DONE;
3567 int64_t total_len;
3568 const char *ptr;
3569 if (cached) {
3570 total_len = cached->dir_compressed_len;
3571 ptr = cached->dir_compressed;
3572 } else {
3573 total_len = spooled->cce_len;
3574 ptr = (const char *)spooled->cce_body;
3576 /* How many bytes left to flush? */
3577 int64_t remaining;
3578 remaining = total_len - spooled->cached_dir_offset;
3579 if (BUG(remaining < 0))
3580 return SRFS_ERR;
3581 ssize_t bytes = (ssize_t) MIN(DIRSERV_CACHED_DIR_CHUNK_SIZE, remaining);
3582 if (conn->compress_state) {
3583 connection_write_to_buf_compress(
3584 ptr + spooled->cached_dir_offset,
3585 bytes, conn, 0);
3586 } else {
3587 connection_write_to_buf(ptr + spooled->cached_dir_offset,
3588 bytes, TO_CONN(conn));
3590 spooled->cached_dir_offset += bytes;
3591 if (spooled->cached_dir_offset >= (off_t)total_len) {
3592 return SRFS_DONE;
3593 } else {
3594 return SRFS_MORE;
3599 /** Helper: find the cached_dir_t for a spooled_resource_t, for
3600 * sending it to <b>conn</b>. Set *<b>published_out</b>, if provided,
3601 * to the published time of the cached_dir_t.
3603 * DOES NOT increase the reference count on the result. Callers must do that
3604 * themselves if they mean to hang on to it.
3606 static cached_dir_t *
3607 spooled_resource_lookup_cached_dir(const spooled_resource_t *spooled,
3608 time_t *published_out)
3610 tor_assert(spooled->spool_eagerly == 0);
3611 cached_dir_t *d = lookup_cached_dir_by_fp(spooled->digest);
3612 if (d != NULL) {
3613 if (published_out)
3614 *published_out = d->published;
3616 return d;
3619 /** Helper: Look up the body for an eagerly-served spooled_resource. If
3620 * <b>conn_is_encrypted</b> is false, don't look up any resource that
3621 * shouldn't be sent over an unencrypted connection. On success, set
3622 * <b>body_out</b>, <b>size_out</b>, and <b>published_out</b> to refer
3623 * to the resource's body, size, and publication date, and return 0.
3624 * On failure return -1. */
3625 static int
3626 spooled_resource_lookup_body(const spooled_resource_t *spooled,
3627 int conn_is_encrypted,
3628 const uint8_t **body_out,
3629 size_t *size_out,
3630 time_t *published_out)
3632 tor_assert(spooled->spool_eagerly == 1);
3634 const signed_descriptor_t *sd = NULL;
3636 switch (spooled->spool_source) {
3637 case DIR_SPOOL_EXTRA_BY_FP: {
3638 sd = get_signed_descriptor_by_fp(spooled->digest, 1);
3639 break;
3641 case DIR_SPOOL_SERVER_BY_FP: {
3642 sd = get_signed_descriptor_by_fp(spooled->digest, 0);
3643 break;
3645 case DIR_SPOOL_SERVER_BY_DIGEST: {
3646 sd = router_get_by_descriptor_digest((const char *)spooled->digest);
3647 break;
3649 case DIR_SPOOL_EXTRA_BY_DIGEST: {
3650 sd = extrainfo_get_by_descriptor_digest((const char *)spooled->digest);
3651 break;
3653 case DIR_SPOOL_MICRODESC: {
3654 microdesc_t *md = microdesc_cache_lookup_by_digest256(
3655 get_microdesc_cache(),
3656 (const char *)spooled->digest);
3657 if (! md || ! md->body) {
3658 return -1;
3660 *body_out = (const uint8_t *)md->body;
3661 *size_out = md->bodylen;
3662 if (published_out)
3663 *published_out = TIME_MAX;
3664 return 0;
3666 case DIR_SPOOL_NETWORKSTATUS:
3667 case DIR_SPOOL_CONSENSUS_CACHE_ENTRY:
3668 default:
3669 /* LCOV_EXCL_START */
3670 tor_assert_nonfatal_unreached();
3671 return -1;
3672 /* LCOV_EXCL_STOP */
3675 /* If we get here, then we tried to set "sd" to a signed_descriptor_t. */
3677 if (sd == NULL) {
3678 return -1;
3680 if (sd->send_unencrypted == 0 && ! conn_is_encrypted) {
3681 /* we did this check once before (so we could have an accurate size
3682 * estimate and maybe send a 404 if somebody asked for only bridges on
3683 * a connection), but we need to do it again in case a previously
3684 * unknown bridge descriptor has shown up between then and now. */
3685 return -1;
3687 *body_out = (const uint8_t *) signed_descriptor_get_body(sd);
3688 *size_out = sd->signed_descriptor_len;
3689 if (published_out)
3690 *published_out = sd->published_on;
3691 return 0;
3694 /** Given a fingerprint <b>fp</b> which is either set if we're looking for a
3695 * v2 status, or zeroes if we're looking for a v3 status, or a NUL-padded
3696 * flavor name if we want a flavored v3 status, return a pointer to the
3697 * appropriate cached dir object, or NULL if there isn't one available. */
3698 static cached_dir_t *
3699 lookup_cached_dir_by_fp(const uint8_t *fp)
3701 cached_dir_t *d = NULL;
3702 if (tor_digest_is_zero((const char *)fp) && cached_consensuses) {
3703 d = strmap_get(cached_consensuses, "ns");
3704 } else if (memchr(fp, '\0', DIGEST_LEN) && cached_consensuses) {
3705 /* this here interface is a nasty hack: we're shoving a flavor into
3706 * a digest field. */
3707 d = strmap_get(cached_consensuses, (const char *)fp);
3709 return d;
3712 /** Try to guess the number of bytes that will be needed to send the
3713 * spooled objects for <b>conn</b>'s outgoing spool. In the process,
3714 * remove every element of the spool that refers to an absent object, or
3715 * which was published earlier than <b>cutoff</b>. Set *<b>size_out</b>
3716 * to the number of bytes, and *<b>n_expired_out</b> to the number of
3717 * objects removed for being too old. */
3718 void
3719 dirserv_spool_remove_missing_and_guess_size(dir_connection_t *conn,
3720 time_t cutoff,
3721 int compression,
3722 size_t *size_out,
3723 int *n_expired_out)
3725 if (BUG(!conn))
3726 return;
3728 smartlist_t *spool = conn->spool;
3729 if (!spool) {
3730 if (size_out)
3731 *size_out = 0;
3732 if (n_expired_out)
3733 *n_expired_out = 0;
3734 return;
3736 int n_expired = 0;
3737 uint64_t total = 0;
3738 SMARTLIST_FOREACH_BEGIN(spool, spooled_resource_t *, spooled) {
3739 time_t published = TIME_MAX;
3740 size_t sz = spooled_resource_estimate_size(spooled, conn,
3741 compression, &published);
3742 if (published < cutoff) {
3743 ++n_expired;
3744 SMARTLIST_DEL_CURRENT(spool, spooled);
3745 spooled_resource_free(spooled);
3746 } else if (sz == 0) {
3747 SMARTLIST_DEL_CURRENT(spool, spooled);
3748 spooled_resource_free(spooled);
3749 } else {
3750 total += sz;
3752 } SMARTLIST_FOREACH_END(spooled);
3754 if (size_out) {
3755 *size_out = (total > SIZE_MAX) ? SIZE_MAX : (size_t)total;
3757 if (n_expired_out)
3758 *n_expired_out = n_expired;
3761 /** Helper: used to sort a connection's spool. */
3762 static int
3763 dirserv_spool_sort_comparison_(const void **a_, const void **b_)
3765 const spooled_resource_t *a = *a_;
3766 const spooled_resource_t *b = *b_;
3767 return fast_memcmp(a->digest, b->digest, sizeof(a->digest));
3770 /** Sort all the entries in <b>conn</b> by digest. */
3771 void
3772 dirserv_spool_sort(dir_connection_t *conn)
3774 if (conn->spool == NULL)
3775 return;
3776 smartlist_sort(conn->spool, dirserv_spool_sort_comparison_);
3779 /** Return the cache-info for identity fingerprint <b>fp</b>, or
3780 * its extra-info document if <b>extrainfo</b> is true. Return
3781 * NULL if not found or if the descriptor is older than
3782 * <b>publish_cutoff</b>. */
3783 static const signed_descriptor_t *
3784 get_signed_descriptor_by_fp(const uint8_t *fp, int extrainfo)
3786 if (router_digest_is_me((const char *)fp)) {
3787 if (extrainfo)
3788 return &(router_get_my_extrainfo()->cache_info);
3789 else
3790 return &(router_get_my_routerinfo()->cache_info);
3791 } else {
3792 const routerinfo_t *ri = router_get_by_id_digest((const char *)fp);
3793 if (ri) {
3794 if (extrainfo)
3795 return extrainfo_get_by_descriptor_digest(
3796 ri->cache_info.extra_info_digest);
3797 else
3798 return &ri->cache_info;
3801 return NULL;
3804 /** When we're spooling data onto our outbuf, add more whenever we dip
3805 * below this threshold. */
3806 #define DIRSERV_BUFFER_MIN 16384
3809 * Called whenever we have flushed some directory data in state
3810 * SERVER_WRITING, or whenever we want to fill the buffer with initial
3811 * directory data (so that subsequent writes will occur, and trigger this
3812 * function again.)
3814 * Return 0 on success, and -1 on failure.
3817 connection_dirserv_flushed_some(dir_connection_t *conn)
3819 tor_assert(conn->base_.state == DIR_CONN_STATE_SERVER_WRITING);
3820 if (conn->spool == NULL)
3821 return 0;
3823 while (connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN &&
3824 smartlist_len(conn->spool)) {
3825 spooled_resource_t *spooled =
3826 smartlist_get(conn->spool, smartlist_len(conn->spool)-1);
3827 spooled_resource_flush_status_t status;
3828 status = spooled_resource_flush_some(spooled, conn);
3829 if (status == SRFS_ERR) {
3830 return -1;
3831 } else if (status == SRFS_MORE) {
3832 return 0;
3834 tor_assert(status == SRFS_DONE);
3836 /* If we're here, we're done flushing this resource. */
3837 tor_assert(smartlist_pop_last(conn->spool) == spooled);
3838 spooled_resource_free(spooled);
3841 if (smartlist_len(conn->spool) > 0) {
3842 /* We're still spooling something. */
3843 return 0;
3846 /* If we get here, we're done. */
3847 smartlist_free(conn->spool);
3848 conn->spool = NULL;
3849 if (conn->compress_state) {
3850 /* Flush the compression state: there could be more bytes pending in there,
3851 * and we don't want to omit bytes. */
3852 connection_write_to_buf_compress("", 0, conn, 1);
3853 tor_compress_free(conn->compress_state);
3854 conn->compress_state = NULL;
3856 return 0;
3859 /** Remove every element from <b>conn</b>'s outgoing spool, and delete
3860 * the spool. */
3861 void
3862 dir_conn_clear_spool(dir_connection_t *conn)
3864 if (!conn || ! conn->spool)
3865 return;
3866 SMARTLIST_FOREACH(conn->spool, spooled_resource_t *, s,
3867 spooled_resource_free(s));
3868 smartlist_free(conn->spool);
3869 conn->spool = NULL;
3872 /** Return true iff <b>line</b> is a valid RecommendedPackages line.
3875 The grammar is:
3877 "package" SP PACKAGENAME SP VERSION SP URL SP DIGESTS NL
3879 PACKAGENAME = NONSPACE
3880 VERSION = NONSPACE
3881 URL = NONSPACE
3882 DIGESTS = DIGEST | DIGESTS SP DIGEST
3883 DIGEST = DIGESTTYPE "=" DIGESTVAL
3885 NONSPACE = one or more non-space printing characters
3887 DIGESTVAL = DIGESTTYPE = one or more non-=, non-" " characters.
3889 SP = " "
3890 NL = a newline
3894 validate_recommended_package_line(const char *line)
3896 const char *cp = line;
3898 #define WORD() \
3899 do { \
3900 if (*cp == ' ') \
3901 return 0; \
3902 cp = strchr(cp, ' '); \
3903 if (!cp) \
3904 return 0; \
3905 } while (0)
3907 WORD(); /* skip packagename */
3908 ++cp;
3909 WORD(); /* skip version */
3910 ++cp;
3911 WORD(); /* Skip URL */
3912 ++cp;
3914 /* Skip digesttype=digestval + */
3915 int n_entries = 0;
3916 while (1) {
3917 const char *start_of_word = cp;
3918 const char *end_of_word = strchr(cp, ' ');
3919 if (! end_of_word)
3920 end_of_word = cp + strlen(cp);
3922 if (start_of_word == end_of_word)
3923 return 0;
3925 const char *eq = memchr(start_of_word, '=', end_of_word - start_of_word);
3927 if (!eq)
3928 return 0;
3929 if (eq == start_of_word)
3930 return 0;
3931 if (eq == end_of_word - 1)
3932 return 0;
3933 if (memchr(eq+1, '=', end_of_word - (eq+1)))
3934 return 0;
3936 ++n_entries;
3937 if (0 == *end_of_word)
3938 break;
3940 cp = end_of_word + 1;
3943 /* If we reach this point, we have at least 1 entry. */
3944 tor_assert(n_entries > 0);
3945 return 1;
3948 /** Release all storage used by the directory server. */
3949 void
3950 dirserv_free_all(void)
3952 dirserv_free_fingerprint_list();
3954 strmap_free(cached_consensuses, free_cached_dir_);
3955 cached_consensuses = NULL;
3957 dirserv_clear_measured_bw_cache();