don't attempt a resolve when the cached answer will do
[tor.git] / src / or / dirserv.c
blob34db06355b12b393e22ef9b7bb2936c99bafb169
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2016, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 #define DIRSERV_PRIVATE
7 #include "or.h"
8 #include "buffers.h"
9 #include "config.h"
10 #include "confparse.h"
11 #include "channel.h"
12 #include "channeltls.h"
13 #include "command.h"
14 #include "connection.h"
15 #include "connection_or.h"
16 #include "control.h"
17 #include "directory.h"
18 #include "dirserv.h"
19 #include "dirvote.h"
20 #include "hibernate.h"
21 #include "keypin.h"
22 #include "main.h"
23 #include "microdesc.h"
24 #include "networkstatus.h"
25 #include "nodelist.h"
26 #include "policies.h"
27 #include "protover.h"
28 #include "rephist.h"
29 #include "router.h"
30 #include "routerlist.h"
31 #include "routerparse.h"
32 #include "routerset.h"
33 #include "torcert.h"
35 /**
36 * \file dirserv.c
37 * \brief Directory server core implementation. Manages directory
38 * contents and generates directories.
40 * This module implements most of directory cache functionality, and some of
41 * the directory authority functionality. The directory.c module delegates
42 * here in order to handle incoming requests from clients, via
43 * connection_dirserv_flushed_some() and its kin. In order to save RAM, this
44 * module is reponsible for spooling directory objects (in whole or in part)
45 * onto buf_t instances, and then closing the dir_connection_t once the
46 * objects are totally flushed.
48 * The directory.c module also delegates here for handling descriptor uploads
49 * via dirserv_add_multiple_descriptors().
51 * Additionally, this module handles some aspects of voting, including:
52 * deciding how to vote on individual flags (based on decisions reached in
53 * rephist.c), of formatting routerstatus lines, and deciding what relays to
54 * include in an authority's vote. (TODO: Those functions could profitably be
55 * split off. They only live in this file because historically they were
56 * shared among the v1, v2, and v3 directory code.)
59 /** How far in the future do we allow a router to get? (seconds) */
60 #define ROUTER_ALLOW_SKEW (60*60*12)
61 /** How many seconds do we wait before regenerating the directory? */
62 #define DIR_REGEN_SLACK_TIME 30
63 /** If we're a cache, keep this many networkstatuses around from non-trusted
64 * directory authorities. */
65 #define MAX_UNTRUSTED_NETWORKSTATUSES 16
67 /** Total number of routers with measured bandwidth; this is set by
68 * dirserv_count_measured_bws() before the loop in
69 * dirserv_generate_networkstatus_vote_obj() and checked by
70 * dirserv_get_credible_bandwidth() and
71 * dirserv_compute_performance_thresholds() */
72 static int routers_with_measured_bw = 0;
74 static void directory_remove_invalid(void);
75 static char *format_versions_list(config_line_t *ln);
76 struct authdir_config_t;
77 static uint32_t
78 dirserv_get_status_impl(const char *fp, const char *nickname,
79 uint32_t addr, uint16_t or_port,
80 const char *platform, const char **msg,
81 int severity);
82 static void clear_cached_dir(cached_dir_t *d);
83 static const signed_descriptor_t *get_signed_descriptor_by_fp(
84 const char *fp,
85 int extrainfo,
86 time_t publish_cutoff);
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 /************** Fingerprint handling code ************/
94 /* 1 Historically used to indicate Named */
95 #define FP_INVALID 2 /**< Believed invalid. */
96 #define FP_REJECT 4 /**< We will not publish this router. */
97 /* 8 Historically used to avoid using this as a dir. */
98 #define FP_BADEXIT 16 /**< We'll tell clients not to use this as an exit. */
99 /* 32 Historically used to indicade Unnamed */
101 /** Target of status_by_digest map. */
102 typedef uint32_t router_status_t;
104 static void add_fingerprint_to_dir(const char *fp,
105 struct authdir_config_t *list,
106 router_status_t add_status);
108 /** List of nickname-\>identity fingerprint mappings for all the routers
109 * that we name. Used to prevent router impersonation. */
110 typedef struct authdir_config_t {
111 strmap_t *fp_by_name; /**< Map from lc nickname to fingerprint. */
112 digestmap_t *status_by_digest; /**< Map from digest to router_status_t. */
113 } authdir_config_t;
115 /** Should be static; exposed for testing. */
116 static authdir_config_t *fingerprint_list = NULL;
118 /** Allocate and return a new, empty, authdir_config_t. */
119 static authdir_config_t *
120 authdir_config_new(void)
122 authdir_config_t *list = tor_malloc_zero(sizeof(authdir_config_t));
123 list->fp_by_name = strmap_new();
124 list->status_by_digest = digestmap_new();
125 return list;
128 /** Add the fingerprint <b>fp</b> to the smartlist of fingerprint_entry_t's
129 * <b>list</b>, or-ing the currently set status flags with
130 * <b>add_status</b>.
132 /* static */ void
133 add_fingerprint_to_dir(const char *fp, authdir_config_t *list,
134 router_status_t add_status)
136 char *fingerprint;
137 char d[DIGEST_LEN];
138 router_status_t *status;
139 tor_assert(fp);
140 tor_assert(list);
142 fingerprint = tor_strdup(fp);
143 tor_strstrip(fingerprint, " ");
144 if (base16_decode(d, DIGEST_LEN,
145 fingerprint, strlen(fingerprint)) != DIGEST_LEN) {
146 log_warn(LD_DIRSERV, "Couldn't decode fingerprint \"%s\"",
147 escaped(fp));
148 tor_free(fingerprint);
149 return;
152 status = digestmap_get(list->status_by_digest, d);
153 if (!status) {
154 status = tor_malloc_zero(sizeof(router_status_t));
155 digestmap_set(list->status_by_digest, d, status);
158 tor_free(fingerprint);
159 *status |= add_status;
160 return;
163 /** Add the fingerprint for this OR to the global list of recognized
164 * identity key fingerprints. */
166 dirserv_add_own_fingerprint(crypto_pk_t *pk)
168 char fp[FINGERPRINT_LEN+1];
169 if (crypto_pk_get_fingerprint(pk, fp, 0)<0) {
170 log_err(LD_BUG, "Error computing fingerprint");
171 return -1;
173 if (!fingerprint_list)
174 fingerprint_list = authdir_config_new();
175 add_fingerprint_to_dir(fp, fingerprint_list, 0);
176 return 0;
179 /** Load the nickname-\>fingerprint mappings stored in the approved-routers
180 * file. The file format is line-based, with each non-blank holding one
181 * nickname, some space, and a fingerprint for that nickname. On success,
182 * replace the current fingerprint list with the new list and return 0. On
183 * failure, leave the current fingerprint list untouched, and return -1. */
185 dirserv_load_fingerprint_file(void)
187 char *fname;
188 char *cf;
189 char *nickname, *fingerprint;
190 authdir_config_t *fingerprint_list_new;
191 int result;
192 config_line_t *front=NULL, *list;
194 fname = get_datadir_fname("approved-routers");
195 log_info(LD_GENERAL,
196 "Reloading approved fingerprints from \"%s\"...", fname);
198 cf = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
199 if (!cf) {
200 log_warn(LD_FS, "Cannot open fingerprint file '%s'. That's ok.", fname);
201 tor_free(fname);
202 return 0;
204 tor_free(fname);
206 result = config_get_lines(cf, &front, 0);
207 tor_free(cf);
208 if (result < 0) {
209 log_warn(LD_CONFIG, "Error reading from fingerprint file");
210 return -1;
213 fingerprint_list_new = authdir_config_new();
215 for (list=front; list; list=list->next) {
216 char digest_tmp[DIGEST_LEN];
217 router_status_t add_status = 0;
218 nickname = list->key; fingerprint = list->value;
219 tor_strstrip(fingerprint, " "); /* remove spaces */
220 if (strlen(fingerprint) != HEX_DIGEST_LEN ||
221 base16_decode(digest_tmp, sizeof(digest_tmp),
222 fingerprint, HEX_DIGEST_LEN) != sizeof(digest_tmp)) {
223 log_notice(LD_CONFIG,
224 "Invalid fingerprint (nickname '%s', "
225 "fingerprint %s). Skipping.",
226 nickname, fingerprint);
227 continue;
229 if (!strcasecmp(nickname, "!reject")) {
230 add_status = FP_REJECT;
231 } else if (!strcasecmp(nickname, "!badexit")) {
232 add_status = FP_BADEXIT;
233 } else if (!strcasecmp(nickname, "!invalid")) {
234 add_status = FP_INVALID;
236 add_fingerprint_to_dir(fingerprint, fingerprint_list_new, add_status);
239 config_free_lines(front);
240 dirserv_free_fingerprint_list();
241 fingerprint_list = fingerprint_list_new;
242 /* Delete any routers whose fingerprints we no longer recognize */
243 directory_remove_invalid();
244 return 0;
247 /* If this is set, then we don't allow routers that have advertised an Ed25519
248 * identity to stop doing so. This is going to be essential for good identity
249 * security: otherwise anybody who can attack RSA-1024 but not Ed25519 could
250 * just sign fake descriptors missing the Ed25519 key. But we won't actually
251 * be able to prevent that kind of thing until we're confident that there
252 * isn't actually a legit reason to downgrade to 0.2.5. So for now, we have
253 * to leave this #undef.
255 #undef DISABLE_DISABLING_ED25519
257 /** Check whether <b>router</b> has a nickname/identity key combination that
258 * we recognize from the fingerprint list, or an IP we automatically act on
259 * according to our configuration. Return the appropriate router status.
261 * If the status is 'FP_REJECT' and <b>msg</b> is provided, set
262 * *<b>msg</b> to an explanation of why. */
263 uint32_t
264 dirserv_router_get_status(const routerinfo_t *router, const char **msg,
265 int severity)
267 char d[DIGEST_LEN];
268 const int key_pinning = get_options()->AuthDirPinKeys;
270 if (crypto_pk_get_digest(router->identity_pkey, d)) {
271 log_warn(LD_BUG,"Error computing fingerprint");
272 if (msg)
273 *msg = "Bug: Error computing fingerprint";
274 return FP_REJECT;
277 /* dirserv_get_status_impl already rejects versions older than 0.2.4.18-rc,
278 * and onion_curve25519_pkey was introduced in 0.2.4.8-alpha.
279 * But just in case a relay doesn't provide or lies about its version, or
280 * doesn't include an ntor key in its descriptor, check that it exists,
281 * and is non-zero (clients check that it's non-zero before using it). */
282 if (!routerinfo_has_curve25519_onion_key(router)) {
283 log_fn(severity, LD_DIR,
284 "Descriptor from router %s is missing an ntor curve25519 onion "
285 "key.", router_describe(router));
286 if (msg)
287 *msg = "Missing ntor curve25519 onion key. Please upgrade!";
288 return FP_REJECT;
291 if (router->cache_info.signing_key_cert) {
292 /* This has an ed25519 identity key. */
293 if (KEYPIN_MISMATCH ==
294 keypin_check((const uint8_t*)router->cache_info.identity_digest,
295 router->cache_info.signing_key_cert->signing_key.pubkey)) {
296 log_fn(severity, LD_DIR,
297 "Descriptor from router %s has an Ed25519 key, "
298 "but the <rsa,ed25519> keys don't match what they were before.",
299 router_describe(router));
300 if (key_pinning) {
301 if (msg) {
302 *msg = "Ed25519 identity key or RSA identity key has changed.";
304 return FP_REJECT;
307 } else {
308 /* No ed25519 key */
309 if (KEYPIN_MISMATCH == keypin_check_lone_rsa(
310 (const uint8_t*)router->cache_info.identity_digest)) {
311 log_fn(severity, LD_DIR,
312 "Descriptor from router %s has no Ed25519 key, "
313 "when we previously knew an Ed25519 for it. Ignoring for now, "
314 "since Ed25519 keys are fairly new.",
315 router_describe(router));
316 #ifdef DISABLE_DISABLING_ED25519
317 if (key_pinning) {
318 if (msg) {
319 *msg = "Ed25519 identity key has disappeared.";
321 return FP_REJECT;
323 #endif
327 return dirserv_get_status_impl(d, router->nickname,
328 router->addr, router->or_port,
329 router->platform, msg, severity);
332 /** Return true if there is no point in downloading the router described by
333 * <b>rs</b> because this directory would reject it. */
335 dirserv_would_reject_router(const routerstatus_t *rs)
337 uint32_t res;
339 res = dirserv_get_status_impl(rs->identity_digest, rs->nickname,
340 rs->addr, rs->or_port,
341 NULL, NULL, LOG_DEBUG);
343 return (res & FP_REJECT) != 0;
346 /** Helper: As dirserv_router_get_status, but takes the router fingerprint
347 * (hex, no spaces), nickname, address (used for logging only), IP address, OR
348 * port and platform (logging only) as arguments.
350 * Log messages at 'severity'. (There's not much point in
351 * logging that we're rejecting servers we'll not download.)
353 static uint32_t
354 dirserv_get_status_impl(const char *id_digest, const char *nickname,
355 uint32_t addr, uint16_t or_port,
356 const char *platform, const char **msg, int severity)
358 uint32_t result = 0;
359 router_status_t *status_by_digest;
361 if (!fingerprint_list)
362 fingerprint_list = authdir_config_new();
364 log_debug(LD_DIRSERV, "%d fingerprints, %d digests known.",
365 strmap_size(fingerprint_list->fp_by_name),
366 digestmap_size(fingerprint_list->status_by_digest));
368 /* Versions before Tor 0.2.4.18-rc are too old to support, and are
369 * missing some important security fixes too. Disable them. */
370 if (platform && !tor_version_as_new_as(platform,"0.2.4.18-rc")) {
371 if (msg)
372 *msg = "Tor version is insecure or unsupported. Please upgrade!";
373 return FP_REJECT;
376 status_by_digest = digestmap_get(fingerprint_list->status_by_digest,
377 id_digest);
378 if (status_by_digest)
379 result |= *status_by_digest;
381 if (result & FP_REJECT) {
382 if (msg)
383 *msg = "Fingerprint is marked rejected -- please contact us?";
384 return FP_REJECT;
385 } else if (result & FP_INVALID) {
386 if (msg)
387 *msg = "Fingerprint is marked invalid";
390 if (authdir_policy_badexit_address(addr, or_port)) {
391 log_fn(severity, LD_DIRSERV,
392 "Marking '%s' as bad exit because of address '%s'",
393 nickname, fmt_addr32(addr));
394 result |= FP_BADEXIT;
397 if (!authdir_policy_permits_address(addr, or_port)) {
398 log_fn(severity, LD_DIRSERV, "Rejecting '%s' because of address '%s'",
399 nickname, fmt_addr32(addr));
400 if (msg)
401 *msg = "Suspicious relay address range -- please contact us?";
402 return FP_REJECT;
404 if (!authdir_policy_valid_address(addr, or_port)) {
405 log_fn(severity, LD_DIRSERV,
406 "Not marking '%s' valid because of address '%s'",
407 nickname, fmt_addr32(addr));
408 result |= FP_INVALID;
411 return result;
414 /** Clear the current fingerprint list. */
415 void
416 dirserv_free_fingerprint_list(void)
418 if (!fingerprint_list)
419 return;
421 strmap_free(fingerprint_list->fp_by_name, tor_free_);
422 digestmap_free(fingerprint_list->status_by_digest, tor_free_);
423 tor_free(fingerprint_list);
427 * Descriptor list
430 /** Return -1 if <b>ri</b> has a private or otherwise bad address,
431 * unless we're configured to not care. Return 0 if all ok. */
432 static int
433 dirserv_router_has_valid_address(routerinfo_t *ri)
435 tor_addr_t addr;
436 if (get_options()->DirAllowPrivateAddresses)
437 return 0; /* whatever it is, we're fine with it */
438 tor_addr_from_ipv4h(&addr, ri->addr);
440 if (tor_addr_is_internal(&addr, 0)) {
441 log_info(LD_DIRSERV,
442 "Router %s published internal IP address. Refusing.",
443 router_describe(ri));
444 return -1; /* it's a private IP, we should reject it */
446 return 0;
449 /** Check whether we, as a directory server, want to accept <b>ri</b>. If so,
450 * set its is_valid,running fields and return 0. Otherwise, return -1.
452 * If the router is rejected, set *<b>msg</b> to an explanation of why.
454 * If <b>complain</b> then explain at log-level 'notice' why we refused
455 * a descriptor; else explain at log-level 'info'.
458 authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
459 int complain, int *valid_out)
461 /* Okay. Now check whether the fingerprint is recognized. */
462 time_t now;
463 int severity = (complain && ri->contact_info) ? LOG_NOTICE : LOG_INFO;
464 uint32_t status = dirserv_router_get_status(ri, msg, severity);
465 tor_assert(msg);
466 if (status & FP_REJECT)
467 return -1; /* msg is already set. */
469 /* Is there too much clock skew? */
470 now = time(NULL);
471 if (ri->cache_info.published_on > now+ROUTER_ALLOW_SKEW) {
472 log_fn(severity, LD_DIRSERV, "Publication time for %s is too "
473 "far (%d minutes) in the future; possible clock skew. Not adding "
474 "(%s)",
475 router_describe(ri),
476 (int)((ri->cache_info.published_on-now)/60),
477 esc_router_info(ri));
478 *msg = "Rejected: Your clock is set too far in the future, or your "
479 "timezone is not correct.";
480 return -1;
482 if (ri->cache_info.published_on < now-ROUTER_MAX_AGE_TO_PUBLISH) {
483 log_fn(severity, LD_DIRSERV,
484 "Publication time for %s is too far "
485 "(%d minutes) in the past. Not adding (%s)",
486 router_describe(ri),
487 (int)((now-ri->cache_info.published_on)/60),
488 esc_router_info(ri));
489 *msg = "Rejected: Server is expired, or your clock is too far in the past,"
490 " or your timezone is not correct.";
491 return -1;
493 if (dirserv_router_has_valid_address(ri) < 0) {
494 log_fn(severity, LD_DIRSERV,
495 "Router %s has invalid address. Not adding (%s).",
496 router_describe(ri),
497 esc_router_info(ri));
498 *msg = "Rejected: Address is a private address.";
499 return -1;
502 *valid_out = ! (status & FP_INVALID);
504 return 0;
507 /** Update the relevant flags of <b>node</b> based on our opinion as a
508 * directory authority in <b>authstatus</b>, as returned by
509 * dirserv_router_get_status or equivalent. */
510 void
511 dirserv_set_node_flags_from_authoritative_status(node_t *node,
512 uint32_t authstatus)
514 node->is_valid = (authstatus & FP_INVALID) ? 0 : 1;
515 node->is_bad_exit = (authstatus & FP_BADEXIT) ? 1 : 0;
518 /** True iff <b>a</b> is more severe than <b>b</b>. */
519 static int
520 WRA_MORE_SEVERE(was_router_added_t a, was_router_added_t b)
522 return a < b;
525 /** As for dirserv_add_descriptor(), but accepts multiple documents, and
526 * returns the most severe error that occurred for any one of them. */
527 was_router_added_t
528 dirserv_add_multiple_descriptors(const char *desc, uint8_t purpose,
529 const char *source,
530 const char **msg)
532 was_router_added_t r, r_tmp;
533 const char *msg_out;
534 smartlist_t *list;
535 const char *s;
536 int n_parsed = 0;
537 time_t now = time(NULL);
538 char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
539 char time_buf[ISO_TIME_LEN+1];
540 int general = purpose == ROUTER_PURPOSE_GENERAL;
541 tor_assert(msg);
543 r=ROUTER_ADDED_SUCCESSFULLY; /*Least severe return value. */
545 format_iso_time(time_buf, now);
546 if (tor_snprintf(annotation_buf, sizeof(annotation_buf),
547 "@uploaded-at %s\n"
548 "@source %s\n"
549 "%s%s%s", time_buf, escaped(source),
550 !general ? "@purpose " : "",
551 !general ? router_purpose_to_string(purpose) : "",
552 !general ? "\n" : "")<0) {
553 *msg = "Couldn't format annotations";
554 return -1;
557 s = desc;
558 list = smartlist_new();
559 if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 0, 0,
560 annotation_buf, NULL)) {
561 SMARTLIST_FOREACH(list, routerinfo_t *, ri, {
562 msg_out = NULL;
563 tor_assert(ri->purpose == purpose);
564 r_tmp = dirserv_add_descriptor(ri, &msg_out, source);
565 if (WRA_MORE_SEVERE(r_tmp, r)) {
566 r = r_tmp;
567 *msg = msg_out;
571 n_parsed += smartlist_len(list);
572 smartlist_clear(list);
574 s = desc;
575 if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 1, 0,
576 NULL, NULL)) {
577 SMARTLIST_FOREACH(list, extrainfo_t *, ei, {
578 msg_out = NULL;
580 r_tmp = dirserv_add_extrainfo(ei, &msg_out);
581 if (WRA_MORE_SEVERE(r_tmp, r)) {
582 r = r_tmp;
583 *msg = msg_out;
587 n_parsed += smartlist_len(list);
588 smartlist_free(list);
590 if (! *msg) {
591 if (!n_parsed) {
592 *msg = "No descriptors found in your POST.";
593 if (WRA_WAS_ADDED(r))
594 r = ROUTER_IS_ALREADY_KNOWN;
595 } else {
596 *msg = "(no message)";
600 return r;
603 /** Examine the parsed server descriptor in <b>ri</b> and maybe insert it into
604 * the list of server descriptors. Set *<b>msg</b> to a message that should be
605 * passed back to the origin of this descriptor, or NULL if there is no such
606 * message. Use <b>source</b> to produce better log messages.
608 * Return the status of the operation
610 * This function is only called when fresh descriptors are posted, not when
611 * we re-load the cache.
613 was_router_added_t
614 dirserv_add_descriptor(routerinfo_t *ri, const char **msg, const char *source)
616 was_router_added_t r;
617 routerinfo_t *ri_old;
618 char *desc, *nickname;
619 const size_t desclen = ri->cache_info.signed_descriptor_len +
620 ri->cache_info.annotations_len;
621 const int key_pinning = get_options()->AuthDirPinKeys;
622 *msg = NULL;
624 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
625 * network and it'll clog everything up. */
626 if (ri->cache_info.signed_descriptor_len > MAX_DESCRIPTOR_UPLOAD_SIZE) {
627 log_notice(LD_DIR, "Somebody attempted to publish a router descriptor '%s'"
628 " (source: %s) with size %d. Either this is an attack, or the "
629 "MAX_DESCRIPTOR_UPLOAD_SIZE (%d) constant is too low.",
630 ri->nickname, source, (int)ri->cache_info.signed_descriptor_len,
631 MAX_DESCRIPTOR_UPLOAD_SIZE);
632 *msg = "Router descriptor was too large.";
633 control_event_or_authdir_new_descriptor("REJECTED",
634 ri->cache_info.signed_descriptor_body,
635 desclen, *msg);
636 routerinfo_free(ri);
637 return ROUTER_AUTHDIR_REJECTS;
640 /* Check whether this descriptor is semantically identical to the last one
641 * from this server. (We do this here and not in router_add_to_routerlist
642 * because we want to be able to accept the newest router descriptor that
643 * another authority has, so we all converge on the same one.) */
644 ri_old = router_get_mutable_by_digest(ri->cache_info.identity_digest);
645 if (ri_old && ri_old->cache_info.published_on < ri->cache_info.published_on
646 && router_differences_are_cosmetic(ri_old, ri)
647 && !router_is_me(ri)) {
648 log_info(LD_DIRSERV,
649 "Not replacing descriptor from %s (source: %s); "
650 "differences are cosmetic.",
651 router_describe(ri), source);
652 *msg = "Not replacing router descriptor; no information has changed since "
653 "the last one with this identity.";
654 control_event_or_authdir_new_descriptor("DROPPED",
655 ri->cache_info.signed_descriptor_body,
656 desclen, *msg);
657 routerinfo_free(ri);
658 return ROUTER_IS_ALREADY_KNOWN;
661 /* Do keypinning again ... this time, to add the pin if appropriate */
662 int keypin_status;
663 if (ri->cache_info.signing_key_cert) {
664 keypin_status = keypin_check_and_add(
665 (const uint8_t*)ri->cache_info.identity_digest,
666 ri->cache_info.signing_key_cert->signing_key.pubkey,
667 ! key_pinning);
668 } else {
669 keypin_status = keypin_check_lone_rsa(
670 (const uint8_t*)ri->cache_info.identity_digest);
671 #ifndef DISABLE_DISABLING_ED25519
672 if (keypin_status == KEYPIN_MISMATCH)
673 keypin_status = KEYPIN_NOT_FOUND;
674 #endif
676 if (keypin_status == KEYPIN_MISMATCH && key_pinning) {
677 log_info(LD_DIRSERV, "Dropping descriptor from %s (source: %s) because "
678 "its key did not match an older RSA/Ed25519 keypair",
679 router_describe(ri), source);
680 *msg = "Looks like your keypair does not match its older value.";
681 return ROUTER_AUTHDIR_REJECTS;
684 /* Make a copy of desc, since router_add_to_routerlist might free
685 * ri and its associated signed_descriptor_t. */
686 desc = tor_strndup(ri->cache_info.signed_descriptor_body, desclen);
687 nickname = tor_strdup(ri->nickname);
689 /* Tell if we're about to need to launch a test if we add this. */
690 ri->needs_retest_if_added =
691 dirserv_should_launch_reachability_test(ri, ri_old);
693 r = router_add_to_routerlist(ri, msg, 0, 0);
694 if (!WRA_WAS_ADDED(r)) {
695 /* unless the routerinfo was fine, just out-of-date */
696 if (WRA_WAS_REJECTED(r))
697 control_event_or_authdir_new_descriptor("REJECTED", desc, desclen, *msg);
698 log_info(LD_DIRSERV,
699 "Did not add descriptor from '%s' (source: %s): %s.",
700 nickname, source, *msg ? *msg : "(no message)");
701 } else {
702 smartlist_t *changed;
703 control_event_or_authdir_new_descriptor("ACCEPTED", desc, desclen, *msg);
705 changed = smartlist_new();
706 smartlist_add(changed, ri);
707 routerlist_descriptors_added(changed, 0);
708 smartlist_free(changed);
709 if (!*msg) {
710 *msg = "Descriptor accepted";
712 log_info(LD_DIRSERV,
713 "Added descriptor from '%s' (source: %s): %s.",
714 nickname, source, *msg);
716 tor_free(desc);
717 tor_free(nickname);
718 return r;
721 /** As dirserv_add_descriptor, but for an extrainfo_t <b>ei</b>. */
722 static was_router_added_t
723 dirserv_add_extrainfo(extrainfo_t *ei, const char **msg)
725 routerinfo_t *ri;
726 int r;
727 tor_assert(msg);
728 *msg = NULL;
730 /* Needs to be mutable so routerinfo_incompatible_with_extrainfo
731 * can mess with some of the flags in ri->cache_info. */
732 ri = router_get_mutable_by_digest(ei->cache_info.identity_digest);
733 if (!ri) {
734 *msg = "No corresponding router descriptor for extra-info descriptor";
735 extrainfo_free(ei);
736 return ROUTER_BAD_EI;
739 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
740 * network and it'll clog everything up. */
741 if (ei->cache_info.signed_descriptor_len > MAX_EXTRAINFO_UPLOAD_SIZE) {
742 log_notice(LD_DIR, "Somebody attempted to publish an extrainfo "
743 "with size %d. Either this is an attack, or the "
744 "MAX_EXTRAINFO_UPLOAD_SIZE (%d) constant is too low.",
745 (int)ei->cache_info.signed_descriptor_len,
746 MAX_EXTRAINFO_UPLOAD_SIZE);
747 *msg = "Extrainfo document was too large";
748 extrainfo_free(ei);
749 return ROUTER_BAD_EI;
752 if ((r = routerinfo_incompatible_with_extrainfo(ri->identity_pkey, ei,
753 &ri->cache_info, msg))) {
754 extrainfo_free(ei);
755 return r < 0 ? ROUTER_IS_ALREADY_KNOWN : ROUTER_BAD_EI;
757 router_add_extrainfo_to_routerlist(ei, msg, 0, 0);
758 return ROUTER_ADDED_SUCCESSFULLY;
761 /** Remove all descriptors whose nicknames or fingerprints no longer
762 * are allowed by our fingerprint list. (Descriptors that used to be
763 * good can become bad when we reload the fingerprint list.)
765 static void
766 directory_remove_invalid(void)
768 routerlist_t *rl = router_get_routerlist();
769 smartlist_t *nodes = smartlist_new();
770 smartlist_add_all(nodes, nodelist_get_list());
772 SMARTLIST_FOREACH_BEGIN(nodes, node_t *, node) {
773 const char *msg = NULL;
774 routerinfo_t *ent = node->ri;
775 char description[NODE_DESC_BUF_LEN];
776 uint32_t r;
777 if (!ent)
778 continue;
779 r = dirserv_router_get_status(ent, &msg, LOG_INFO);
780 router_get_description(description, ent);
781 if (r & FP_REJECT) {
782 log_info(LD_DIRSERV, "Router %s is now rejected: %s",
783 description, msg?msg:"");
784 routerlist_remove(rl, ent, 0, time(NULL));
785 continue;
787 if (bool_neq((r & FP_INVALID), !node->is_valid)) {
788 log_info(LD_DIRSERV, "Router '%s' is now %svalid.", description,
789 (r&FP_INVALID) ? "in" : "");
790 node->is_valid = (r&FP_INVALID)?0:1;
792 if (bool_neq((r & FP_BADEXIT), node->is_bad_exit)) {
793 log_info(LD_DIRSERV, "Router '%s' is now a %s exit", description,
794 (r & FP_BADEXIT) ? "bad" : "good");
795 node->is_bad_exit = (r&FP_BADEXIT) ? 1: 0;
797 } SMARTLIST_FOREACH_END(node);
799 routerlist_assert_ok(rl);
800 smartlist_free(nodes);
804 * Allocate and return a description of the status of the server <b>desc</b>,
805 * for use in a v1-style router-status line. The server is listed
806 * as running iff <b>is_live</b> is true.
808 static char *
809 list_single_server_status(const routerinfo_t *desc, int is_live)
811 char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
812 char *cp;
813 const node_t *node;
815 tor_assert(desc);
817 cp = buf;
818 if (!is_live) {
819 *cp++ = '!';
821 node = node_get_by_id(desc->cache_info.identity_digest);
822 if (node && node->is_valid) {
823 strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
824 cp += strlen(cp);
825 *cp++ = '=';
827 *cp++ = '$';
828 base16_encode(cp, HEX_DIGEST_LEN+1, desc->cache_info.identity_digest,
829 DIGEST_LEN);
830 return tor_strdup(buf);
833 /* DOCDOC running_long_enough_to_decide_unreachable */
834 static inline int
835 running_long_enough_to_decide_unreachable(void)
837 return time_of_process_start
838 + get_options()->TestingAuthDirTimeToLearnReachability < approx_time();
841 /** Each server needs to have passed a reachability test no more
842 * than this number of seconds ago, or it is listed as down in
843 * the directory. */
844 #define REACHABLE_TIMEOUT (45*60)
846 /** If we tested a router and found it reachable _at least this long_ after it
847 * declared itself hibernating, it is probably done hibernating and we just
848 * missed a descriptor from it. */
849 #define HIBERNATION_PUBLICATION_SKEW (60*60)
851 /** Treat a router as alive if
852 * - It's me, and I'm not hibernating.
853 * or - We've found it reachable recently. */
854 void
855 dirserv_set_router_is_running(routerinfo_t *router, time_t now)
857 /*XXXX This function is a mess. Separate out the part that calculates
858 whether it's reachable and the part that tells rephist that the router was
859 unreachable.
861 int answer;
862 const or_options_t *options = get_options();
863 node_t *node = node_get_mutable_by_id(router->cache_info.identity_digest);
864 tor_assert(node);
866 if (router_is_me(router)) {
867 /* We always know if we are down ourselves. */
868 answer = ! we_are_hibernating();
869 } else if (router->is_hibernating &&
870 (router->cache_info.published_on +
871 HIBERNATION_PUBLICATION_SKEW) > node->last_reachable) {
872 /* A hibernating router is down unless we (somehow) had contact with it
873 * since it declared itself to be hibernating. */
874 answer = 0;
875 } else if (options->AssumeReachable) {
876 /* If AssumeReachable, everybody is up unless they say they are down! */
877 answer = 1;
878 } else {
879 /* Otherwise, a router counts as up if we found all announced OR
880 ports reachable in the last REACHABLE_TIMEOUT seconds.
882 XXX prop186 For now there's always one IPv4 and at most one
883 IPv6 OR port.
885 If we're not on IPv6, don't consider reachability of potential
886 IPv6 OR port since that'd kill all dual stack relays until a
887 majority of the dir auths have IPv6 connectivity. */
888 answer = (now < node->last_reachable + REACHABLE_TIMEOUT &&
889 (options->AuthDirHasIPv6Connectivity != 1 ||
890 tor_addr_is_null(&router->ipv6_addr) ||
891 now < node->last_reachable6 + REACHABLE_TIMEOUT));
894 if (!answer && running_long_enough_to_decide_unreachable()) {
895 /* Not considered reachable. tell rephist about that.
897 Because we launch a reachability test for each router every
898 REACHABILITY_TEST_CYCLE_PERIOD seconds, then the router has probably
899 been down since at least that time after we last successfully reached
902 XXX ipv6
904 time_t when = now;
905 if (node->last_reachable &&
906 node->last_reachable + REACHABILITY_TEST_CYCLE_PERIOD < now)
907 when = node->last_reachable + REACHABILITY_TEST_CYCLE_PERIOD;
908 rep_hist_note_router_unreachable(router->cache_info.identity_digest, when);
911 node->is_running = answer;
914 /** Based on the routerinfo_ts in <b>routers</b>, allocate the
915 * contents of a v1-style router-status line, and store it in
916 * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
918 * If for_controller is true, include the routers with very old descriptors.
921 list_server_status_v1(smartlist_t *routers, char **router_status_out,
922 int for_controller)
924 /* List of entries in a router-status style: An optional !, then an optional
925 * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
926 smartlist_t *rs_entries;
927 time_t now = time(NULL);
928 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
929 const or_options_t *options = get_options();
930 /* We include v2 dir auths here too, because they need to answer
931 * controllers. Eventually we'll deprecate this whole function;
932 * see also networkstatus_getinfo_by_purpose(). */
933 int authdir = authdir_mode_publishes_statuses(options);
934 tor_assert(router_status_out);
936 rs_entries = smartlist_new();
938 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
939 const node_t *node = node_get_by_id(ri->cache_info.identity_digest);
940 tor_assert(node);
941 if (authdir) {
942 /* Update router status in routerinfo_t. */
943 dirserv_set_router_is_running(ri, now);
945 if (for_controller) {
946 char name_buf[MAX_VERBOSE_NICKNAME_LEN+2];
947 char *cp = name_buf;
948 if (!node->is_running)
949 *cp++ = '!';
950 router_get_verbose_nickname(cp, ri);
951 smartlist_add(rs_entries, tor_strdup(name_buf));
952 } else if (ri->cache_info.published_on >= cutoff) {
953 smartlist_add(rs_entries, list_single_server_status(ri,
954 node->is_running));
956 } SMARTLIST_FOREACH_END(ri);
958 *router_status_out = smartlist_join_strings(rs_entries, " ", 0, NULL);
960 SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
961 smartlist_free(rs_entries);
963 return 0;
966 /** Given a (possibly empty) list of config_line_t, each line of which contains
967 * a list of comma-separated version numbers surrounded by optional space,
968 * allocate and return a new string containing the version numbers, in order,
969 * separated by commas. Used to generate Recommended(Client|Server)?Versions
971 static char *
972 format_versions_list(config_line_t *ln)
974 smartlist_t *versions;
975 char *result;
976 versions = smartlist_new();
977 for ( ; ln; ln = ln->next) {
978 smartlist_split_string(versions, ln->value, ",",
979 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
981 sort_version_list(versions, 1);
982 result = smartlist_join_strings(versions,",",0,NULL);
983 SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
984 smartlist_free(versions);
985 return result;
988 /** Return 1 if <b>ri</b>'s descriptor is "active" -- running, valid,
989 * not hibernating, having observed bw greater 0, and not too old. Else
990 * return 0.
992 static int
993 router_is_active(const routerinfo_t *ri, const node_t *node, time_t now)
995 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
996 if (ri->cache_info.published_on < cutoff) {
997 return 0;
999 if (!node->is_running || !node->is_valid || ri->is_hibernating) {
1000 return 0;
1002 /* Only require bandwith capacity in non-test networks, or
1003 * if TestingTorNetwork, and TestingMinExitFlagThreshold is non-zero */
1004 if (!ri->bandwidthcapacity) {
1005 if (get_options()->TestingTorNetwork) {
1006 if (get_options()->TestingMinExitFlagThreshold > 0) {
1007 /* If we're in a TestingTorNetwork, and TestingMinExitFlagThreshold is,
1008 * then require bandwidthcapacity */
1009 return 0;
1011 } else {
1012 /* If we're not in a TestingTorNetwork, then require bandwidthcapacity */
1013 return 0;
1016 return 1;
1019 /********************************************************************/
1021 /* A set of functions to answer questions about how we'd like to behave
1022 * as a directory mirror/client. */
1024 /** Return 1 if we fetch our directory material directly from the
1025 * authorities, rather than from a mirror. */
1027 directory_fetches_from_authorities(const or_options_t *options)
1029 const routerinfo_t *me;
1030 uint32_t addr;
1031 int refuseunknown;
1032 if (options->FetchDirInfoEarly)
1033 return 1;
1034 if (options->BridgeRelay == 1)
1035 return 0;
1036 if (server_mode(options) &&
1037 router_pick_published_address(options, &addr, 1) < 0)
1038 return 1; /* we don't know our IP address; ask an authority. */
1039 refuseunknown = ! router_my_exit_policy_is_reject_star() &&
1040 should_refuse_unknown_exits(options);
1041 if (!dir_server_mode(options) && !refuseunknown)
1042 return 0;
1043 if (!server_mode(options) || !advertised_server_mode())
1044 return 0;
1045 me = router_get_my_routerinfo();
1046 if (!me || (!me->supports_tunnelled_dir_requests && !refuseunknown))
1047 return 0; /* if we don't service directory requests, return 0 too */
1048 return 1;
1051 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1052 * on the "mirror" schedule rather than the "client" schedule.
1055 directory_fetches_dir_info_early(const or_options_t *options)
1057 return directory_fetches_from_authorities(options);
1060 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1061 * on a very passive schedule -- waiting long enough for ordinary clients
1062 * to probably have the info we want. These would include bridge users,
1063 * and maybe others in the future e.g. if a Tor client uses another Tor
1064 * client as a directory guard.
1067 directory_fetches_dir_info_later(const or_options_t *options)
1069 return options->UseBridges != 0;
1072 /** Return true iff we want to fetch and keep certificates for authorities
1073 * that we don't acknowledge as authorities ourself.
1076 directory_caches_unknown_auth_certs(const or_options_t *options)
1078 return dir_server_mode(options) || options->BridgeRelay;
1081 /** Return 1 if we want to keep descriptors, networkstatuses, etc around.
1082 * Else return 0.
1083 * Check options->DirPort_set and directory_permits_begindir_requests()
1084 * to see if we are willing to serve these directory documents to others via
1085 * the DirPort and begindir-over-ORPort, respectively.
1088 directory_caches_dir_info(const or_options_t *options)
1090 if (options->BridgeRelay || dir_server_mode(options))
1091 return 1;
1092 if (!server_mode(options) || !advertised_server_mode())
1093 return 0;
1094 /* We need an up-to-date view of network info if we're going to try to
1095 * block exit attempts from unknown relays. */
1096 return ! router_my_exit_policy_is_reject_star() &&
1097 should_refuse_unknown_exits(options);
1100 /** Return 1 if we want to allow remote people to ask us directory
1101 * requests via the "begin_dir" interface, which doesn't require
1102 * having any separate port open. */
1104 directory_permits_begindir_requests(const or_options_t *options)
1106 return options->BridgeRelay != 0 || dir_server_mode(options);
1109 /** Return 1 if we have no need to fetch new descriptors. This generally
1110 * happens when we're not a dir cache and we haven't built any circuits
1111 * lately.
1114 directory_too_idle_to_fetch_descriptors(const or_options_t *options,
1115 time_t now)
1117 return !directory_caches_dir_info(options) &&
1118 !options->FetchUselessDescriptors &&
1119 rep_hist_circbuilding_dormant(now);
1122 /********************************************************************/
1124 /** Map from flavor name to the cached_dir_t for the v3 consensuses that we're
1125 * currently serving. */
1126 static strmap_t *cached_consensuses = NULL;
1128 /** Decrement the reference count on <b>d</b>, and free it if it no longer has
1129 * any references. */
1130 void
1131 cached_dir_decref(cached_dir_t *d)
1133 if (!d || --d->refcnt > 0)
1134 return;
1135 clear_cached_dir(d);
1136 tor_free(d);
1139 /** Allocate and return a new cached_dir_t containing the string <b>s</b>,
1140 * published at <b>published</b>. */
1141 cached_dir_t *
1142 new_cached_dir(char *s, time_t published)
1144 cached_dir_t *d = tor_malloc_zero(sizeof(cached_dir_t));
1145 d->refcnt = 1;
1146 d->dir = s;
1147 d->dir_len = strlen(s);
1148 d->published = published;
1149 if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
1150 ZLIB_METHOD)) {
1151 log_warn(LD_BUG, "Error compressing directory");
1153 return d;
1156 /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
1157 static void
1158 clear_cached_dir(cached_dir_t *d)
1160 tor_free(d->dir);
1161 tor_free(d->dir_z);
1162 memset(d, 0, sizeof(cached_dir_t));
1165 /** Free all storage held by the cached_dir_t in <b>d</b>. */
1166 static void
1167 free_cached_dir_(void *_d)
1169 cached_dir_t *d;
1170 if (!_d)
1171 return;
1173 d = (cached_dir_t *)_d;
1174 cached_dir_decref(d);
1177 /** Replace the v3 consensus networkstatus of type <b>flavor_name</b> that
1178 * we're serving with <b>networkstatus</b>, published at <b>published</b>. No
1179 * validation is performed. */
1180 void
1181 dirserv_set_cached_consensus_networkstatus(const char *networkstatus,
1182 const char *flavor_name,
1183 const common_digests_t *digests,
1184 time_t published)
1186 cached_dir_t *new_networkstatus;
1187 cached_dir_t *old_networkstatus;
1188 if (!cached_consensuses)
1189 cached_consensuses = strmap_new();
1191 new_networkstatus = new_cached_dir(tor_strdup(networkstatus), published);
1192 memcpy(&new_networkstatus->digests, digests, sizeof(common_digests_t));
1193 old_networkstatus = strmap_set(cached_consensuses, flavor_name,
1194 new_networkstatus);
1195 if (old_networkstatus)
1196 cached_dir_decref(old_networkstatus);
1199 /** Return the latest downloaded consensus networkstatus in encoded, signed,
1200 * optionally compressed format, suitable for sending to clients. */
1201 cached_dir_t *
1202 dirserv_get_consensus(const char *flavor_name)
1204 if (!cached_consensuses)
1205 return NULL;
1206 return strmap_get(cached_consensuses, flavor_name);
1209 /** If a router's uptime is at least this value, then it is always
1210 * considered stable, regardless of the rest of the network. This
1211 * way we resist attacks where an attacker doubles the size of the
1212 * network using allegedly high-uptime nodes, displacing all the
1213 * current guards. */
1214 #define UPTIME_TO_GUARANTEE_STABLE (3600*24*30)
1215 /** If a router's MTBF is at least this value, then it is always stable.
1216 * See above. (Corresponds to about 7 days for current decay rates.) */
1217 #define MTBF_TO_GUARANTEE_STABLE (60*60*24*5)
1218 /** Similarly, every node with at least this much weighted time known can be
1219 * considered familiar enough to be a guard. Corresponds to about 20 days for
1220 * current decay rates.
1222 #define TIME_KNOWN_TO_GUARANTEE_FAMILIAR (8*24*60*60)
1223 /** Similarly, every node with sufficient WFU is around enough to be a guard.
1225 #define WFU_TO_GUARANTEE_GUARD (0.98)
1227 /* Thresholds for server performance: set by
1228 * dirserv_compute_performance_thresholds, and used by
1229 * generate_v2_networkstatus */
1231 /** Any router with an uptime of at least this value is stable. */
1232 static uint32_t stable_uptime = 0; /* start at a safe value */
1233 /** Any router with an mtbf of at least this value is stable. */
1234 static double stable_mtbf = 0.0;
1235 /** If true, we have measured enough mtbf info to look at stable_mtbf rather
1236 * than stable_uptime. */
1237 static int enough_mtbf_info = 0;
1238 /** Any router with a weighted fractional uptime of at least this much might
1239 * be good as a guard. */
1240 static double guard_wfu = 0.0;
1241 /** Don't call a router a guard unless we've known about it for at least this
1242 * many seconds. */
1243 static long guard_tk = 0;
1244 /** Any router with a bandwidth at least this high is "Fast" */
1245 static uint32_t fast_bandwidth_kb = 0;
1246 /** If exits can be guards, then all guards must have a bandwidth this
1247 * high. */
1248 static uint32_t guard_bandwidth_including_exits_kb = 0;
1249 /** If exits can't be guards, then all guards must have a bandwidth this
1250 * high. */
1251 static uint32_t guard_bandwidth_excluding_exits_kb = 0;
1253 /** Helper: estimate the uptime of a router given its stated uptime and the
1254 * amount of time since it last stated its stated uptime. */
1255 static inline long
1256 real_uptime(const routerinfo_t *router, time_t now)
1258 if (now < router->cache_info.published_on)
1259 return router->uptime;
1260 else
1261 return router->uptime + (now - router->cache_info.published_on);
1264 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1265 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1266 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1267 * bandwidth.
1269 static int
1270 dirserv_thinks_router_is_unreliable(time_t now,
1271 routerinfo_t *router,
1272 int need_uptime, int need_capacity)
1274 if (need_uptime) {
1275 if (!enough_mtbf_info) {
1276 /* XXXX We should change the rule from
1277 * "use uptime if we don't have mtbf data" to "don't advertise Stable on
1278 * v3 if we don't have enough mtbf data." Or maybe not, since if we ever
1279 * hit a point where we need to reset a lot of authorities at once,
1280 * none of them would be in a position to declare Stable.
1282 long uptime = real_uptime(router, now);
1283 if ((unsigned)uptime < stable_uptime &&
1284 (unsigned)uptime < UPTIME_TO_GUARANTEE_STABLE)
1285 return 1;
1286 } else {
1287 double mtbf =
1288 rep_hist_get_stability(router->cache_info.identity_digest, now);
1289 if (mtbf < stable_mtbf &&
1290 mtbf < MTBF_TO_GUARANTEE_STABLE)
1291 return 1;
1294 if (need_capacity) {
1295 uint32_t bw_kb = dirserv_get_credible_bandwidth_kb(router);
1296 if (bw_kb < fast_bandwidth_kb)
1297 return 1;
1299 return 0;
1302 /** Return true iff <b>router</b> should be assigned the "HSDir" flag.
1304 * Right now this means it advertises support for it, it has a high uptime,
1305 * it's a directory cache, it has the Stable and Fast flags, and it's currently
1306 * considered Running.
1308 * This function needs to be called after router-\>is_running has
1309 * been set.
1311 static int
1312 dirserv_thinks_router_is_hs_dir(const routerinfo_t *router,
1313 const node_t *node, time_t now)
1316 long uptime;
1318 /* If we haven't been running for at least
1319 * get_options()->MinUptimeHidServDirectoryV2 seconds, we can't
1320 * have accurate data telling us a relay has been up for at least
1321 * that long. We also want to allow a bit of slack: Reachability
1322 * tests aren't instant. If we haven't been running long enough,
1323 * trust the relay. */
1325 if (stats_n_seconds_working >
1326 get_options()->MinUptimeHidServDirectoryV2 * 1.1)
1327 uptime = MIN(rep_hist_get_uptime(router->cache_info.identity_digest, now),
1328 real_uptime(router, now));
1329 else
1330 uptime = real_uptime(router, now);
1332 return (router->wants_to_be_hs_dir &&
1333 router->supports_tunnelled_dir_requests &&
1334 node->is_stable && node->is_fast &&
1335 uptime >= get_options()->MinUptimeHidServDirectoryV2 &&
1336 router_is_active(router, node, now));
1339 /** Don't consider routers with less bandwidth than this when computing
1340 * thresholds. */
1341 #define ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER_KB 4
1343 /** Helper for dirserv_compute_performance_thresholds(): Decide whether to
1344 * include a router in our calculations, and return true iff we should; the
1345 * require_mbw parameter is passed in by
1346 * dirserv_compute_performance_thresholds() and controls whether we ever
1347 * count routers with only advertised bandwidths */
1348 static int
1349 router_counts_toward_thresholds(const node_t *node, time_t now,
1350 const digestmap_t *omit_as_sybil,
1351 int require_mbw)
1353 /* Have measured bw? */
1354 int have_mbw =
1355 dirserv_has_measured_bw(node->identity);
1356 uint64_t min_bw_kb = ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER_KB;
1357 const or_options_t *options = get_options();
1359 if (options->TestingTorNetwork) {
1360 min_bw_kb = (int64_t)options->TestingMinExitFlagThreshold / 1000;
1363 return node->ri && router_is_active(node->ri, node, now) &&
1364 !digestmap_get(omit_as_sybil, node->identity) &&
1365 (dirserv_get_credible_bandwidth_kb(node->ri) >= min_bw_kb) &&
1366 (have_mbw || !require_mbw);
1369 /** Look through the routerlist, the Mean Time Between Failure history, and
1370 * the Weighted Fractional Uptime history, and use them to set thresholds for
1371 * the Stable, Fast, and Guard flags. Update the fields stable_uptime,
1372 * stable_mtbf, enough_mtbf_info, guard_wfu, guard_tk, fast_bandwidth,
1373 * guard_bandwidth_including_exits, and guard_bandwidth_excluding_exits.
1375 * Also, set the is_exit flag of each router appropriately. */
1376 static void
1377 dirserv_compute_performance_thresholds(digestmap_t *omit_as_sybil)
1379 int n_active, n_active_nonexit, n_familiar;
1380 uint32_t *uptimes, *bandwidths_kb, *bandwidths_excluding_exits_kb;
1381 long *tks;
1382 double *mtbfs, *wfus;
1383 smartlist_t *nodelist;
1384 time_t now = time(NULL);
1385 const or_options_t *options = get_options();
1387 /* Require mbw? */
1388 int require_mbw =
1389 (routers_with_measured_bw >
1390 options->MinMeasuredBWsForAuthToIgnoreAdvertised) ? 1 : 0;
1392 /* initialize these all here, in case there are no routers */
1393 stable_uptime = 0;
1394 stable_mtbf = 0;
1395 fast_bandwidth_kb = 0;
1396 guard_bandwidth_including_exits_kb = 0;
1397 guard_bandwidth_excluding_exits_kb = 0;
1398 guard_tk = 0;
1399 guard_wfu = 0;
1401 nodelist_assert_ok();
1402 nodelist = nodelist_get_list();
1404 /* Initialize arrays that will hold values for each router. We'll
1405 * sort them and use that to compute thresholds. */
1406 n_active = n_active_nonexit = 0;
1407 /* Uptime for every active router. */
1408 uptimes = tor_calloc(smartlist_len(nodelist), sizeof(uint32_t));
1409 /* Bandwidth for every active router. */
1410 bandwidths_kb = tor_calloc(smartlist_len(nodelist), sizeof(uint32_t));
1411 /* Bandwidth for every active non-exit router. */
1412 bandwidths_excluding_exits_kb =
1413 tor_calloc(smartlist_len(nodelist), sizeof(uint32_t));
1414 /* Weighted mean time between failure for each active router. */
1415 mtbfs = tor_calloc(smartlist_len(nodelist), sizeof(double));
1416 /* Time-known for each active router. */
1417 tks = tor_calloc(smartlist_len(nodelist), sizeof(long));
1418 /* Weighted fractional uptime for each active router. */
1419 wfus = tor_calloc(smartlist_len(nodelist), sizeof(double));
1421 /* Now, fill in the arrays. */
1422 SMARTLIST_FOREACH_BEGIN(nodelist, node_t *, node) {
1423 if (options->BridgeAuthoritativeDir &&
1424 node->ri &&
1425 node->ri->purpose != ROUTER_PURPOSE_BRIDGE)
1426 continue;
1427 if (router_counts_toward_thresholds(node, now, omit_as_sybil,
1428 require_mbw)) {
1429 routerinfo_t *ri = node->ri;
1430 const char *id = node->identity;
1431 uint32_t bw_kb;
1432 /* resolve spurious clang shallow analysis null pointer errors */
1433 tor_assert(ri);
1434 node->is_exit = (!router_exit_policy_rejects_all(ri) &&
1435 exit_policy_is_general_exit(ri->exit_policy));
1436 uptimes[n_active] = (uint32_t)real_uptime(ri, now);
1437 mtbfs[n_active] = rep_hist_get_stability(id, now);
1438 tks [n_active] = rep_hist_get_weighted_time_known(id, now);
1439 bandwidths_kb[n_active] = bw_kb = dirserv_get_credible_bandwidth_kb(ri);
1440 if (!node->is_exit || node->is_bad_exit) {
1441 bandwidths_excluding_exits_kb[n_active_nonexit] = bw_kb;
1442 ++n_active_nonexit;
1444 ++n_active;
1446 } SMARTLIST_FOREACH_END(node);
1448 /* Now, compute thresholds. */
1449 if (n_active) {
1450 /* The median uptime is stable. */
1451 stable_uptime = median_uint32(uptimes, n_active);
1452 /* The median mtbf is stable, if we have enough mtbf info */
1453 stable_mtbf = median_double(mtbfs, n_active);
1454 /* The 12.5th percentile bandwidth is fast. */
1455 fast_bandwidth_kb = find_nth_uint32(bandwidths_kb, n_active, n_active/8);
1456 /* (Now bandwidths is sorted.) */
1457 if (fast_bandwidth_kb < RELAY_REQUIRED_MIN_BANDWIDTH/(2 * 1000))
1458 fast_bandwidth_kb = bandwidths_kb[n_active/4];
1459 guard_bandwidth_including_exits_kb =
1460 third_quartile_uint32(bandwidths_kb, n_active);
1461 guard_tk = find_nth_long(tks, n_active, n_active/8);
1464 if (guard_tk > TIME_KNOWN_TO_GUARANTEE_FAMILIAR)
1465 guard_tk = TIME_KNOWN_TO_GUARANTEE_FAMILIAR;
1468 /* We can vote on a parameter for the minimum and maximum. */
1469 #define ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG 4
1470 int32_t min_fast_kb, max_fast_kb, min_fast, max_fast;
1471 min_fast = networkstatus_get_param(NULL, "FastFlagMinThreshold",
1472 ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG,
1473 ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG,
1474 INT32_MAX);
1475 if (options->TestingTorNetwork) {
1476 min_fast = (int32_t)options->TestingMinFastFlagThreshold;
1478 max_fast = networkstatus_get_param(NULL, "FastFlagMaxThreshold",
1479 INT32_MAX, min_fast, INT32_MAX);
1480 min_fast_kb = min_fast / 1000;
1481 max_fast_kb = max_fast / 1000;
1483 if (fast_bandwidth_kb < (uint32_t)min_fast_kb)
1484 fast_bandwidth_kb = min_fast_kb;
1485 if (fast_bandwidth_kb > (uint32_t)max_fast_kb)
1486 fast_bandwidth_kb = max_fast_kb;
1488 /* Protect sufficiently fast nodes from being pushed out of the set
1489 * of Fast nodes. */
1490 if (options->AuthDirFastGuarantee &&
1491 fast_bandwidth_kb > options->AuthDirFastGuarantee/1000)
1492 fast_bandwidth_kb = (uint32_t)options->AuthDirFastGuarantee/1000;
1494 /* Now that we have a time-known that 7/8 routers are known longer than,
1495 * fill wfus with the wfu of every such "familiar" router. */
1496 n_familiar = 0;
1498 SMARTLIST_FOREACH_BEGIN(nodelist, node_t *, node) {
1499 if (router_counts_toward_thresholds(node, now,
1500 omit_as_sybil, require_mbw)) {
1501 routerinfo_t *ri = node->ri;
1502 const char *id = ri->cache_info.identity_digest;
1503 long tk = rep_hist_get_weighted_time_known(id, now);
1504 if (tk < guard_tk)
1505 continue;
1506 wfus[n_familiar++] = rep_hist_get_weighted_fractional_uptime(id, now);
1508 } SMARTLIST_FOREACH_END(node);
1509 if (n_familiar)
1510 guard_wfu = median_double(wfus, n_familiar);
1511 if (guard_wfu > WFU_TO_GUARANTEE_GUARD)
1512 guard_wfu = WFU_TO_GUARANTEE_GUARD;
1514 enough_mtbf_info = rep_hist_have_measured_enough_stability();
1516 if (n_active_nonexit) {
1517 guard_bandwidth_excluding_exits_kb =
1518 find_nth_uint32(bandwidths_excluding_exits_kb,
1519 n_active_nonexit, n_active_nonexit*3/4);
1522 log_info(LD_DIRSERV,
1523 "Cutoffs: For Stable, %lu sec uptime, %lu sec MTBF. "
1524 "For Fast: %lu kilobytes/sec. "
1525 "For Guard: WFU %.03f%%, time-known %lu sec, "
1526 "and bandwidth %lu or %lu kilobytes/sec. "
1527 "We%s have enough stability data.",
1528 (unsigned long)stable_uptime,
1529 (unsigned long)stable_mtbf,
1530 (unsigned long)fast_bandwidth_kb,
1531 guard_wfu*100,
1532 (unsigned long)guard_tk,
1533 (unsigned long)guard_bandwidth_including_exits_kb,
1534 (unsigned long)guard_bandwidth_excluding_exits_kb,
1535 enough_mtbf_info ? "" : " don't");
1537 tor_free(uptimes);
1538 tor_free(mtbfs);
1539 tor_free(bandwidths_kb);
1540 tor_free(bandwidths_excluding_exits_kb);
1541 tor_free(tks);
1542 tor_free(wfus);
1545 /* Use dirserv_compute_performance_thresholds() to compute the thresholds
1546 * for the status flags, specifically for bridges.
1548 * This is only called by a Bridge Authority from
1549 * networkstatus_getinfo_by_purpose().
1551 void
1552 dirserv_compute_bridge_flag_thresholds(void)
1554 digestmap_t *omit_as_sybil = digestmap_new();
1555 dirserv_compute_performance_thresholds(omit_as_sybil);
1556 digestmap_free(omit_as_sybil, NULL);
1559 /** Measured bandwidth cache entry */
1560 typedef struct mbw_cache_entry_s {
1561 long mbw_kb;
1562 time_t as_of;
1563 } mbw_cache_entry_t;
1565 /** Measured bandwidth cache - keys are identity_digests, values are
1566 * mbw_cache_entry_t *. */
1567 static digestmap_t *mbw_cache = NULL;
1569 /** Store a measured bandwidth cache entry when reading the measured
1570 * bandwidths file. */
1571 STATIC void
1572 dirserv_cache_measured_bw(const measured_bw_line_t *parsed_line,
1573 time_t as_of)
1575 mbw_cache_entry_t *e = NULL;
1577 tor_assert(parsed_line);
1579 /* Allocate a cache if we need */
1580 if (!mbw_cache) mbw_cache = digestmap_new();
1582 /* Check if we have an existing entry */
1583 e = digestmap_get(mbw_cache, parsed_line->node_id);
1584 /* If we do, we can re-use it */
1585 if (e) {
1586 /* Check that we really are newer, and update */
1587 if (as_of > e->as_of) {
1588 e->mbw_kb = parsed_line->bw_kb;
1589 e->as_of = as_of;
1591 } else {
1592 /* We'll have to insert a new entry */
1593 e = tor_malloc(sizeof(*e));
1594 e->mbw_kb = parsed_line->bw_kb;
1595 e->as_of = as_of;
1596 digestmap_set(mbw_cache, parsed_line->node_id, e);
1600 /** Clear and free the measured bandwidth cache */
1601 STATIC void
1602 dirserv_clear_measured_bw_cache(void)
1604 if (mbw_cache) {
1605 /* Free the map and all entries */
1606 digestmap_free(mbw_cache, tor_free_);
1607 mbw_cache = NULL;
1611 /** Scan the measured bandwidth cache and remove expired entries */
1612 STATIC void
1613 dirserv_expire_measured_bw_cache(time_t now)
1616 if (mbw_cache) {
1617 /* Iterate through the cache and check each entry */
1618 DIGESTMAP_FOREACH_MODIFY(mbw_cache, k, mbw_cache_entry_t *, e) {
1619 if (now > e->as_of + MAX_MEASUREMENT_AGE) {
1620 tor_free(e);
1621 MAP_DEL_CURRENT(k);
1623 } DIGESTMAP_FOREACH_END;
1625 /* Check if we cleared the whole thing and free if so */
1626 if (digestmap_size(mbw_cache) == 0) {
1627 digestmap_free(mbw_cache, tor_free_);
1628 mbw_cache = 0;
1633 /** Get the current size of the measured bandwidth cache */
1634 STATIC int
1635 dirserv_get_measured_bw_cache_size(void)
1637 if (mbw_cache) return digestmap_size(mbw_cache);
1638 else return 0;
1641 /** Query the cache by identity digest, return value indicates whether
1642 * we found it. The bw_out and as_of_out pointers receive the cached
1643 * bandwidth value and the time it was cached if not NULL. */
1644 STATIC int
1645 dirserv_query_measured_bw_cache_kb(const char *node_id, long *bw_kb_out,
1646 time_t *as_of_out)
1648 mbw_cache_entry_t *v = NULL;
1649 int rv = 0;
1651 if (mbw_cache && node_id) {
1652 v = digestmap_get(mbw_cache, node_id);
1653 if (v) {
1654 /* Found something */
1655 rv = 1;
1656 if (bw_kb_out) *bw_kb_out = v->mbw_kb;
1657 if (as_of_out) *as_of_out = v->as_of;
1661 return rv;
1664 /** Predicate wrapper for dirserv_query_measured_bw_cache() */
1665 STATIC int
1666 dirserv_has_measured_bw(const char *node_id)
1668 return dirserv_query_measured_bw_cache_kb(node_id, NULL, NULL);
1671 /** Get the best estimate of a router's bandwidth for dirauth purposes,
1672 * preferring measured to advertised values if available. */
1674 static uint32_t
1675 dirserv_get_bandwidth_for_router_kb(const routerinfo_t *ri)
1677 uint32_t bw_kb = 0;
1679 * Yeah, measured bandwidths in measured_bw_line_t are (implicitly
1680 * signed) longs and the ones router_get_advertised_bandwidth() returns
1681 * are uint32_t.
1683 long mbw_kb = 0;
1685 if (ri) {
1687 * * First try to see if we have a measured bandwidth; don't bother with
1688 * as_of_out here, on the theory that a stale measured bandwidth is still
1689 * better to trust than an advertised one.
1691 if (dirserv_query_measured_bw_cache_kb(ri->cache_info.identity_digest,
1692 &mbw_kb, NULL)) {
1693 /* Got one! */
1694 bw_kb = (uint32_t)mbw_kb;
1695 } else {
1696 /* If not, fall back to advertised */
1697 bw_kb = router_get_advertised_bandwidth(ri) / 1000;
1701 return bw_kb;
1704 /** Look through the routerlist, and using the measured bandwidth cache count
1705 * how many measured bandwidths we know. This is used to decide whether we
1706 * ever trust advertised bandwidths for purposes of assigning flags. */
1707 static void
1708 dirserv_count_measured_bws(const smartlist_t *routers)
1710 /* Initialize this first */
1711 routers_with_measured_bw = 0;
1713 /* Iterate over the routerlist and count measured bandwidths */
1714 SMARTLIST_FOREACH_BEGIN(routers, const routerinfo_t *, ri) {
1715 /* Check if we know a measured bandwidth for this one */
1716 if (dirserv_has_measured_bw(ri->cache_info.identity_digest)) {
1717 ++routers_with_measured_bw;
1719 } SMARTLIST_FOREACH_END(ri);
1722 /** Return the bandwidth we believe for assigning flags; prefer measured
1723 * over advertised, and if we have above a threshold quantity of measured
1724 * bandwidths, we don't want to ever give flags to unmeasured routers, so
1725 * return 0. */
1726 static uint32_t
1727 dirserv_get_credible_bandwidth_kb(const routerinfo_t *ri)
1729 int threshold;
1730 uint32_t bw_kb = 0;
1731 long mbw_kb;
1733 tor_assert(ri);
1734 /* Check if we have a measured bandwidth, and check the threshold if not */
1735 if (!(dirserv_query_measured_bw_cache_kb(ri->cache_info.identity_digest,
1736 &mbw_kb, NULL))) {
1737 threshold = get_options()->MinMeasuredBWsForAuthToIgnoreAdvertised;
1738 if (routers_with_measured_bw > threshold) {
1739 /* Return zero for unmeasured bandwidth if we are above threshold */
1740 bw_kb = 0;
1741 } else {
1742 /* Return an advertised bandwidth otherwise */
1743 bw_kb = router_get_advertised_bandwidth_capped(ri) / 1000;
1745 } else {
1746 /* We have the measured bandwidth in mbw */
1747 bw_kb = (uint32_t)mbw_kb;
1750 return bw_kb;
1753 /** Give a statement of our current performance thresholds for inclusion
1754 * in a vote document. */
1755 char *
1756 dirserv_get_flag_thresholds_line(void)
1758 char *result=NULL;
1759 const int measured_threshold =
1760 get_options()->MinMeasuredBWsForAuthToIgnoreAdvertised;
1761 const int enough_measured_bw = routers_with_measured_bw > measured_threshold;
1763 tor_asprintf(&result,
1764 "stable-uptime=%lu stable-mtbf=%lu "
1765 "fast-speed=%lu "
1766 "guard-wfu=%.03f%% guard-tk=%lu "
1767 "guard-bw-inc-exits=%lu guard-bw-exc-exits=%lu "
1768 "enough-mtbf=%d ignoring-advertised-bws=%d",
1769 (unsigned long)stable_uptime,
1770 (unsigned long)stable_mtbf,
1771 (unsigned long)fast_bandwidth_kb*1000,
1772 guard_wfu*100,
1773 (unsigned long)guard_tk,
1774 (unsigned long)guard_bandwidth_including_exits_kb*1000,
1775 (unsigned long)guard_bandwidth_excluding_exits_kb*1000,
1776 enough_mtbf_info ? 1 : 0,
1777 enough_measured_bw ? 1 : 0);
1779 return result;
1782 /** Given a platform string as in a routerinfo_t (possibly null), return a
1783 * newly allocated version string for a networkstatus document, or NULL if the
1784 * platform doesn't give a Tor version. */
1785 static char *
1786 version_from_platform(const char *platform)
1788 if (platform && !strcmpstart(platform, "Tor ")) {
1789 const char *eos = find_whitespace(platform+4);
1790 if (eos && !strcmpstart(eos, " (r")) {
1791 /* XXXX Unify this logic with the other version extraction
1792 * logic in routerparse.c. */
1793 eos = find_whitespace(eos+1);
1795 if (eos) {
1796 return tor_strndup(platform, eos-platform);
1799 return NULL;
1802 /** Helper: write the router-status information in <b>rs</b> into a newly
1803 * allocated character buffer. Use the same format as in network-status
1804 * documents. If <b>version</b> is non-NULL, add a "v" line for the platform.
1805 * Return 0 on success, -1 on failure.
1807 * The format argument has one of the following values:
1808 * NS_V2 - Output an entry suitable for a V2 NS opinion document
1809 * NS_V3_CONSENSUS - Output the first portion of a V3 NS consensus entry
1810 * NS_V3_CONSENSUS_MICRODESC - Output the first portion of a V3 microdesc
1811 * consensus entry.
1812 * NS_V3_VOTE - Output a complete V3 NS vote. If <b>vrs</b> is present,
1813 * it contains additional information for the vote.
1814 * NS_CONTROL_PORT - Output a NS document for the control port
1816 char *
1817 routerstatus_format_entry(const routerstatus_t *rs, const char *version,
1818 const char *protocols,
1819 routerstatus_format_type_t format,
1820 const vote_routerstatus_t *vrs)
1822 char *summary;
1823 char *result = NULL;
1825 char published[ISO_TIME_LEN+1];
1826 char identity64[BASE64_DIGEST_LEN+1];
1827 char digest64[BASE64_DIGEST_LEN+1];
1828 smartlist_t *chunks = smartlist_new();
1830 format_iso_time(published, rs->published_on);
1831 digest_to_base64(identity64, rs->identity_digest);
1832 digest_to_base64(digest64, rs->descriptor_digest);
1834 smartlist_add_asprintf(chunks,
1835 "r %s %s %s%s%s %s %d %d\n",
1836 rs->nickname,
1837 identity64,
1838 (format==NS_V3_CONSENSUS_MICRODESC)?"":digest64,
1839 (format==NS_V3_CONSENSUS_MICRODESC)?"":" ",
1840 published,
1841 fmt_addr32(rs->addr),
1842 (int)rs->or_port,
1843 (int)rs->dir_port);
1845 /* TODO: Maybe we want to pass in what we need to build the rest of
1846 * this here, instead of in the caller. Then we could use the
1847 * networkstatus_type_t values, with an additional control port value
1848 * added -MP */
1850 /* V3 microdesc consensuses don't have "a" lines. */
1851 if (format == NS_V3_CONSENSUS_MICRODESC)
1852 goto done;
1854 /* Possible "a" line. At most one for now. */
1855 if (!tor_addr_is_null(&rs->ipv6_addr)) {
1856 smartlist_add_asprintf(chunks, "a %s\n",
1857 fmt_addrport(&rs->ipv6_addr, rs->ipv6_orport));
1860 if (format == NS_V3_CONSENSUS)
1861 goto done;
1863 smartlist_add_asprintf(chunks,
1864 "s%s%s%s%s%s%s%s%s%s%s\n",
1865 /* These must stay in alphabetical order. */
1866 rs->is_authority?" Authority":"",
1867 rs->is_bad_exit?" BadExit":"",
1868 rs->is_exit?" Exit":"",
1869 rs->is_fast?" Fast":"",
1870 rs->is_possible_guard?" Guard":"",
1871 rs->is_hs_dir?" HSDir":"",
1872 rs->is_flagged_running?" Running":"",
1873 rs->is_stable?" Stable":"",
1874 rs->is_v2_dir?" V2Dir":"",
1875 rs->is_valid?" Valid":"");
1877 /* length of "opt v \n" */
1878 #define V_LINE_OVERHEAD 7
1879 if (version && strlen(version) < MAX_V_LINE_LEN - V_LINE_OVERHEAD) {
1880 smartlist_add_asprintf(chunks, "v %s\n", version);
1882 if (protocols) {
1883 smartlist_add_asprintf(chunks, "pr %s\n", protocols);
1886 if (format != NS_V2) {
1887 const routerinfo_t* desc = router_get_by_id_digest(rs->identity_digest);
1888 uint32_t bw_kb;
1890 if (format != NS_CONTROL_PORT) {
1891 /* Blow up more or less nicely if we didn't get anything or not the
1892 * thing we expected.
1894 if (!desc) {
1895 char id[HEX_DIGEST_LEN+1];
1896 char dd[HEX_DIGEST_LEN+1];
1898 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
1899 base16_encode(dd, sizeof(dd), rs->descriptor_digest, DIGEST_LEN);
1900 log_warn(LD_BUG, "Cannot get any descriptor for %s "
1901 "(wanted descriptor %s).",
1902 id, dd);
1903 goto err;
1906 /* This assert could fire for the control port, because
1907 * it can request NS documents before all descriptors
1908 * have been fetched. Therefore, we only do this test when
1909 * format != NS_CONTROL_PORT. */
1910 if (tor_memneq(desc->cache_info.signed_descriptor_digest,
1911 rs->descriptor_digest,
1912 DIGEST_LEN)) {
1913 char rl_d[HEX_DIGEST_LEN+1];
1914 char rs_d[HEX_DIGEST_LEN+1];
1915 char id[HEX_DIGEST_LEN+1];
1917 base16_encode(rl_d, sizeof(rl_d),
1918 desc->cache_info.signed_descriptor_digest, DIGEST_LEN);
1919 base16_encode(rs_d, sizeof(rs_d), rs->descriptor_digest, DIGEST_LEN);
1920 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
1921 log_err(LD_BUG, "descriptor digest in routerlist does not match "
1922 "the one in routerstatus: %s vs %s "
1923 "(router %s)\n",
1924 rl_d, rs_d, id);
1926 tor_assert(tor_memeq(desc->cache_info.signed_descriptor_digest,
1927 rs->descriptor_digest,
1928 DIGEST_LEN));
1932 if (format == NS_CONTROL_PORT && rs->has_bandwidth) {
1933 bw_kb = rs->bandwidth_kb;
1934 } else {
1935 tor_assert(desc);
1936 bw_kb = router_get_advertised_bandwidth_capped(desc) / 1000;
1938 smartlist_add_asprintf(chunks,
1939 "w Bandwidth=%d", bw_kb);
1941 if (format == NS_V3_VOTE && vrs && vrs->has_measured_bw) {
1942 smartlist_add_asprintf(chunks,
1943 " Measured=%d", vrs->measured_bw_kb);
1945 /* Write down guardfraction information if we have it. */
1946 if (format == NS_V3_VOTE && vrs && vrs->status.has_guardfraction) {
1947 smartlist_add_asprintf(chunks,
1948 " GuardFraction=%d",
1949 vrs->status.guardfraction_percentage);
1952 smartlist_add(chunks, tor_strdup("\n"));
1954 if (desc) {
1955 summary = policy_summarize(desc->exit_policy, AF_INET);
1956 smartlist_add_asprintf(chunks, "p %s\n", summary);
1957 tor_free(summary);
1960 if (format == NS_V3_VOTE && vrs) {
1961 if (tor_mem_is_zero((char*)vrs->ed25519_id, ED25519_PUBKEY_LEN)) {
1962 smartlist_add(chunks, tor_strdup("id ed25519 none\n"));
1963 } else {
1964 char ed_b64[BASE64_DIGEST256_LEN+1];
1965 digest256_to_base64(ed_b64, (const char*)vrs->ed25519_id);
1966 smartlist_add_asprintf(chunks, "id ed25519 %s\n", ed_b64);
1971 done:
1972 result = smartlist_join_strings(chunks, "", 0, NULL);
1974 err:
1975 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
1976 smartlist_free(chunks);
1978 return result;
1981 /** Helper for sorting: compares two routerinfos first by address, and then by
1982 * descending order of "usefulness". (An authority is more useful than a
1983 * non-authority; a running router is more useful than a non-running router;
1984 * and a router with more bandwidth is more useful than one with less.)
1986 static int
1987 compare_routerinfo_by_ip_and_bw_(const void **a, const void **b)
1989 routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
1990 int first_is_auth, second_is_auth;
1991 uint32_t bw_kb_first, bw_kb_second;
1992 const node_t *node_first, *node_second;
1993 int first_is_running, second_is_running;
1995 /* we return -1 if first should appear before second... that is,
1996 * if first is a better router. */
1997 if (first->addr < second->addr)
1998 return -1;
1999 else if (first->addr > second->addr)
2000 return 1;
2002 /* Potentially, this next bit could cause k n lg n memeq calls. But in
2003 * reality, we will almost never get here, since addresses will usually be
2004 * different. */
2006 first_is_auth =
2007 router_digest_is_trusted_dir(first->cache_info.identity_digest);
2008 second_is_auth =
2009 router_digest_is_trusted_dir(second->cache_info.identity_digest);
2011 if (first_is_auth && !second_is_auth)
2012 return -1;
2013 else if (!first_is_auth && second_is_auth)
2014 return 1;
2016 node_first = node_get_by_id(first->cache_info.identity_digest);
2017 node_second = node_get_by_id(second->cache_info.identity_digest);
2018 first_is_running = node_first && node_first->is_running;
2019 second_is_running = node_second && node_second->is_running;
2021 if (first_is_running && !second_is_running)
2022 return -1;
2023 else if (!first_is_running && second_is_running)
2024 return 1;
2026 bw_kb_first = dirserv_get_bandwidth_for_router_kb(first);
2027 bw_kb_second = dirserv_get_bandwidth_for_router_kb(second);
2029 if (bw_kb_first > bw_kb_second)
2030 return -1;
2031 else if (bw_kb_first < bw_kb_second)
2032 return 1;
2034 /* They're equal! Compare by identity digest, so there's a
2035 * deterministic order and we avoid flapping. */
2036 return fast_memcmp(first->cache_info.identity_digest,
2037 second->cache_info.identity_digest,
2038 DIGEST_LEN);
2041 /** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
2042 * whose keys are the identity digests of those routers that we're going to
2043 * exclude for Sybil-like appearance. */
2044 static digestmap_t *
2045 get_possible_sybil_list(const smartlist_t *routers)
2047 const or_options_t *options = get_options();
2048 digestmap_t *omit_as_sybil;
2049 smartlist_t *routers_by_ip = smartlist_new();
2050 uint32_t last_addr;
2051 int addr_count;
2052 /* Allow at most this number of Tor servers on a single IP address, ... */
2053 int max_with_same_addr = options->AuthDirMaxServersPerAddr;
2054 /* ... unless it's a directory authority, in which case allow more. */
2055 int max_with_same_addr_on_authority = options->AuthDirMaxServersPerAuthAddr;
2056 if (max_with_same_addr <= 0)
2057 max_with_same_addr = INT_MAX;
2058 if (max_with_same_addr_on_authority <= 0)
2059 max_with_same_addr_on_authority = INT_MAX;
2061 smartlist_add_all(routers_by_ip, routers);
2062 smartlist_sort(routers_by_ip, compare_routerinfo_by_ip_and_bw_);
2063 omit_as_sybil = digestmap_new();
2065 last_addr = 0;
2066 addr_count = 0;
2067 SMARTLIST_FOREACH_BEGIN(routers_by_ip, routerinfo_t *, ri) {
2068 if (last_addr != ri->addr) {
2069 last_addr = ri->addr;
2070 addr_count = 1;
2071 } else if (++addr_count > max_with_same_addr) {
2072 if (!router_addr_is_trusted_dir(ri->addr) ||
2073 addr_count > max_with_same_addr_on_authority)
2074 digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
2076 } SMARTLIST_FOREACH_END(ri);
2078 smartlist_free(routers_by_ip);
2079 return omit_as_sybil;
2082 /** If there are entries in <b>routers</b> with exactly the same ed25519 keys,
2083 * remove the older one. If they are exactly the same age, remove the one
2084 * with the greater descriptor digest. May alter the order of the list. */
2085 static void
2086 routers_make_ed_keys_unique(smartlist_t *routers)
2088 routerinfo_t *ri2;
2089 digest256map_t *by_ed_key = digest256map_new();
2091 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
2092 ri->omit_from_vote = 0;
2093 if (ri->cache_info.signing_key_cert == NULL)
2094 continue; /* No ed key */
2095 const uint8_t *pk = ri->cache_info.signing_key_cert->signing_key.pubkey;
2096 if ((ri2 = digest256map_get(by_ed_key, pk))) {
2097 /* Duplicate; must omit one. Set the omit_from_vote flag in whichever
2098 * one has the earlier published_on. */
2099 const time_t ri_pub = ri->cache_info.published_on;
2100 const time_t ri2_pub = ri2->cache_info.published_on;
2101 if (ri2_pub < ri_pub ||
2102 (ri2_pub == ri_pub &&
2103 fast_memcmp(ri->cache_info.signed_descriptor_digest,
2104 ri2->cache_info.signed_descriptor_digest,DIGEST_LEN)<0)) {
2105 digest256map_set(by_ed_key, pk, ri);
2106 ri2->omit_from_vote = 1;
2107 } else {
2108 ri->omit_from_vote = 1;
2110 } else {
2111 /* Add to map */
2112 digest256map_set(by_ed_key, pk, ri);
2114 } SMARTLIST_FOREACH_END(ri);
2116 digest256map_free(by_ed_key, NULL);
2118 /* Now remove every router where the omit_from_vote flag got set. */
2119 SMARTLIST_FOREACH_BEGIN(routers, const routerinfo_t *, ri) {
2120 if (ri->omit_from_vote) {
2121 SMARTLIST_DEL_CURRENT(routers, ri);
2123 } SMARTLIST_FOREACH_END(ri);
2126 /** Extract status information from <b>ri</b> and from other authority
2127 * functions and store it in <b>rs</b>>.
2129 * We assume that ri-\>is_running has already been set, e.g. by
2130 * dirserv_set_router_is_running(ri, now);
2132 void
2133 set_routerstatus_from_routerinfo(routerstatus_t *rs,
2134 node_t *node,
2135 routerinfo_t *ri,
2136 time_t now,
2137 int listbadexits)
2139 const or_options_t *options = get_options();
2140 uint32_t routerbw_kb = dirserv_get_credible_bandwidth_kb(ri);
2142 memset(rs, 0, sizeof(routerstatus_t));
2144 rs->is_authority =
2145 router_digest_is_trusted_dir(ri->cache_info.identity_digest);
2147 /* Already set by compute_performance_thresholds. */
2148 rs->is_exit = node->is_exit;
2149 rs->is_stable = node->is_stable =
2150 !dirserv_thinks_router_is_unreliable(now, ri, 1, 0);
2151 rs->is_fast = node->is_fast =
2152 !dirserv_thinks_router_is_unreliable(now, ri, 0, 1);
2153 rs->is_flagged_running = node->is_running; /* computed above */
2155 rs->is_valid = node->is_valid;
2157 if (node->is_fast && node->is_stable &&
2158 ((options->AuthDirGuardBWGuarantee &&
2159 routerbw_kb >= options->AuthDirGuardBWGuarantee/1000) ||
2160 routerbw_kb >= MIN(guard_bandwidth_including_exits_kb,
2161 guard_bandwidth_excluding_exits_kb))) {
2162 long tk = rep_hist_get_weighted_time_known(
2163 node->identity, now);
2164 double wfu = rep_hist_get_weighted_fractional_uptime(
2165 node->identity, now);
2166 rs->is_possible_guard = (wfu >= guard_wfu && tk >= guard_tk) ? 1 : 0;
2167 } else {
2168 rs->is_possible_guard = 0;
2171 rs->is_bad_exit = listbadexits && node->is_bad_exit;
2172 rs->is_hs_dir = node->is_hs_dir =
2173 dirserv_thinks_router_is_hs_dir(ri, node, now);
2175 rs->is_named = rs->is_unnamed = 0;
2177 rs->published_on = ri->cache_info.published_on;
2178 memcpy(rs->identity_digest, node->identity, DIGEST_LEN);
2179 memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest,
2180 DIGEST_LEN);
2181 rs->addr = ri->addr;
2182 strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname));
2183 rs->or_port = ri->or_port;
2184 rs->dir_port = ri->dir_port;
2185 rs->is_v2_dir = ri->supports_tunnelled_dir_requests;
2186 if (options->AuthDirHasIPv6Connectivity == 1 &&
2187 !tor_addr_is_null(&ri->ipv6_addr) &&
2188 node->last_reachable6 >= now - REACHABLE_TIMEOUT) {
2189 /* We're configured as having IPv6 connectivity. There's an IPv6
2190 OR port and it's reachable so copy it to the routerstatus. */
2191 tor_addr_copy(&rs->ipv6_addr, &ri->ipv6_addr);
2192 rs->ipv6_orport = ri->ipv6_orport;
2195 if (options->TestingTorNetwork) {
2196 dirserv_set_routerstatus_testing(rs);
2200 /** Use TestingDirAuthVoteExit, TestingDirAuthVoteGuard, and
2201 * TestingDirAuthVoteHSDir to give out the Exit, Guard, and HSDir flags,
2202 * respectively. But don't set the corresponding node flags.
2203 * Should only be called if TestingTorNetwork is set. */
2204 STATIC void
2205 dirserv_set_routerstatus_testing(routerstatus_t *rs)
2207 const or_options_t *options = get_options();
2209 tor_assert(options->TestingTorNetwork);
2211 if (routerset_contains_routerstatus(options->TestingDirAuthVoteExit,
2212 rs, 0)) {
2213 rs->is_exit = 1;
2214 } else if (options->TestingDirAuthVoteExitIsStrict) {
2215 rs->is_exit = 0;
2218 if (routerset_contains_routerstatus(options->TestingDirAuthVoteGuard,
2219 rs, 0)) {
2220 rs->is_possible_guard = 1;
2221 } else if (options->TestingDirAuthVoteGuardIsStrict) {
2222 rs->is_possible_guard = 0;
2225 if (routerset_contains_routerstatus(options->TestingDirAuthVoteHSDir,
2226 rs, 0)) {
2227 rs->is_hs_dir = 1;
2228 } else if (options->TestingDirAuthVoteHSDirIsStrict) {
2229 rs->is_hs_dir = 0;
2233 /** Routerstatus <b>rs</b> is part of a group of routers that are on
2234 * too narrow an IP-space. Clear out its flags: we don't want people
2235 * using it.
2237 static void
2238 clear_status_flags_on_sybil(routerstatus_t *rs)
2240 rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
2241 rs->is_flagged_running = rs->is_named = rs->is_valid =
2242 rs->is_hs_dir = rs->is_possible_guard = rs->is_bad_exit = 0;
2243 /* FFFF we might want some mechanism to check later on if we
2244 * missed zeroing any flags: it's easy to add a new flag but
2245 * forget to add it to this clause. */
2248 /** The guardfraction of the guard with identity fingerprint <b>guard_id</b>
2249 * is <b>guardfraction_percentage</b>. See if we have a vote routerstatus for
2250 * this guard in <b>vote_routerstatuses</b>, and if we do, register the
2251 * information to it.
2253 * Return 1 if we applied the information and 0 if we couldn't find a
2254 * matching guard.
2256 * Requires that <b>vote_routerstatuses</b> be sorted.
2258 static int
2259 guardfraction_line_apply(const char *guard_id,
2260 uint32_t guardfraction_percentage,
2261 smartlist_t *vote_routerstatuses)
2263 vote_routerstatus_t *vrs = NULL;
2265 tor_assert(vote_routerstatuses);
2267 vrs = smartlist_bsearch(vote_routerstatuses, guard_id,
2268 compare_digest_to_vote_routerstatus_entry);
2270 if (!vrs) {
2271 return 0;
2274 vrs->status.has_guardfraction = 1;
2275 vrs->status.guardfraction_percentage = guardfraction_percentage;
2277 return 1;
2280 /* Given a guard line from a guardfraction file, parse it and register
2281 * its information to <b>vote_routerstatuses</b>.
2283 * Return:
2284 * * 1 if the line was proper and its information got registered.
2285 * * 0 if the line was proper but no currently active guard was found
2286 * to register the guardfraction information to.
2287 * * -1 if the line could not be parsed and set <b>err_msg</b> to a
2288 newly allocated string containing the error message.
2290 static int
2291 guardfraction_file_parse_guard_line(const char *guard_line,
2292 smartlist_t *vote_routerstatuses,
2293 char **err_msg)
2295 char guard_id[DIGEST_LEN];
2296 uint32_t guardfraction;
2297 char *inputs_tmp = NULL;
2298 int num_ok = 1;
2300 smartlist_t *sl = smartlist_new();
2301 int retval = -1;
2303 tor_assert(err_msg);
2305 /* guard_line should contain something like this:
2306 <hex digest> <guardfraction> <appearances> */
2307 smartlist_split_string(sl, guard_line, " ",
2308 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
2309 if (smartlist_len(sl) < 3) {
2310 tor_asprintf(err_msg, "bad line '%s'", guard_line);
2311 goto done;
2314 inputs_tmp = smartlist_get(sl, 0);
2315 if (strlen(inputs_tmp) != HEX_DIGEST_LEN ||
2316 base16_decode(guard_id, DIGEST_LEN,
2317 inputs_tmp, HEX_DIGEST_LEN) != DIGEST_LEN) {
2318 tor_asprintf(err_msg, "bad digest '%s'", inputs_tmp);
2319 goto done;
2322 inputs_tmp = smartlist_get(sl, 1);
2323 /* Guardfraction is an integer in [0, 100]. */
2324 guardfraction =
2325 (uint32_t) tor_parse_long(inputs_tmp, 10, 0, 100, &num_ok, NULL);
2326 if (!num_ok) {
2327 tor_asprintf(err_msg, "wrong percentage '%s'", inputs_tmp);
2328 goto done;
2331 /* If routerstatuses were provided, apply this info to actual routers. */
2332 if (vote_routerstatuses) {
2333 retval = guardfraction_line_apply(guard_id, guardfraction,
2334 vote_routerstatuses);
2335 } else {
2336 retval = 0; /* If we got this far, line was correctly formatted. */
2339 done:
2341 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
2342 smartlist_free(sl);
2344 return retval;
2347 /** Given an inputs line from a guardfraction file, parse it and
2348 * register its information to <b>total_consensuses</b> and
2349 * <b>total_days</b>.
2351 * Return 0 if it parsed well. Return -1 if there was an error, and
2352 * set <b>err_msg</b> to a newly allocated string containing the
2353 * error message.
2355 static int
2356 guardfraction_file_parse_inputs_line(const char *inputs_line,
2357 int *total_consensuses,
2358 int *total_days,
2359 char **err_msg)
2361 int retval = -1;
2362 char *inputs_tmp = NULL;
2363 int num_ok = 1;
2364 smartlist_t *sl = smartlist_new();
2366 tor_assert(err_msg);
2368 /* Second line is inputs information:
2369 * n-inputs <total_consensuses> <total_days>. */
2370 smartlist_split_string(sl, inputs_line, " ",
2371 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
2372 if (smartlist_len(sl) < 2) {
2373 tor_asprintf(err_msg, "incomplete line '%s'", inputs_line);
2374 goto done;
2377 inputs_tmp = smartlist_get(sl, 0);
2378 *total_consensuses =
2379 (int) tor_parse_long(inputs_tmp, 10, 0, INT_MAX, &num_ok, NULL);
2380 if (!num_ok) {
2381 tor_asprintf(err_msg, "unparseable consensus '%s'", inputs_tmp);
2382 goto done;
2385 inputs_tmp = smartlist_get(sl, 1);
2386 *total_days =
2387 (int) tor_parse_long(inputs_tmp, 10, 0, INT_MAX, &num_ok, NULL);
2388 if (!num_ok) {
2389 tor_asprintf(err_msg, "unparseable days '%s'", inputs_tmp);
2390 goto done;
2393 retval = 0;
2395 done:
2396 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
2397 smartlist_free(sl);
2399 return retval;
2402 /* Maximum age of a guardfraction file that we are willing to accept. */
2403 #define MAX_GUARDFRACTION_FILE_AGE (7*24*60*60) /* approx a week */
2405 /** Static strings of guardfraction files. */
2406 #define GUARDFRACTION_DATE_STR "written-at"
2407 #define GUARDFRACTION_INPUTS "n-inputs"
2408 #define GUARDFRACTION_GUARD "guard-seen"
2409 #define GUARDFRACTION_VERSION "guardfraction-file-version"
2411 /** Given a guardfraction file in a string, parse it and register the
2412 * guardfraction information to the provided vote routerstatuses.
2414 * This is the rough format of the guardfraction file:
2416 * guardfraction-file-version 1
2417 * written-at <date and time>
2418 * n-inputs <number of consesuses parsed> <number of days considered>
2420 * guard-seen <fpr 1> <guardfraction percentage> <consensus appearances>
2421 * guard-seen <fpr 2> <guardfraction percentage> <consensus appearances>
2422 * guard-seen <fpr 3> <guardfraction percentage> <consensus appearances>
2423 * guard-seen <fpr 4> <guardfraction percentage> <consensus appearances>
2424 * guard-seen <fpr 5> <guardfraction percentage> <consensus appearances>
2425 * ...
2427 * Return -1 if the parsing failed and 0 if it went smoothly. Parsing
2428 * should tolerate errors in all lines but the written-at header.
2430 STATIC int
2431 dirserv_read_guardfraction_file_from_str(const char *guardfraction_file_str,
2432 smartlist_t *vote_routerstatuses)
2434 config_line_t *front=NULL, *line;
2435 int ret_tmp;
2436 int retval = -1;
2437 int current_line_n = 0; /* line counter for better log messages */
2439 /* Guardfraction info to be parsed */
2440 int total_consensuses = 0;
2441 int total_days = 0;
2443 /* Stats */
2444 int guards_read_n = 0;
2445 int guards_applied_n = 0;
2447 /* Parse file and split it in lines */
2448 ret_tmp = config_get_lines(guardfraction_file_str, &front, 0);
2449 if (ret_tmp < 0) {
2450 log_warn(LD_CONFIG, "Error reading from guardfraction file");
2451 goto done;
2454 /* Sort routerstatuses (needed later when applying guardfraction info) */
2455 if (vote_routerstatuses)
2456 smartlist_sort(vote_routerstatuses, compare_vote_routerstatus_entries);
2458 for (line = front; line; line=line->next) {
2459 current_line_n++;
2461 if (!strcmp(line->key, GUARDFRACTION_VERSION)) {
2462 int num_ok = 1;
2463 unsigned int version;
2465 version =
2466 (unsigned int) tor_parse_long(line->value,
2467 10, 0, INT_MAX, &num_ok, NULL);
2469 if (!num_ok || version != 1) {
2470 log_warn(LD_GENERAL, "Got unknown guardfraction version %d.", version);
2471 goto done;
2473 } else if (!strcmp(line->key, GUARDFRACTION_DATE_STR)) {
2474 time_t file_written_at;
2475 time_t now = time(NULL);
2477 /* First line is 'written-at <date>' */
2478 if (parse_iso_time(line->value, &file_written_at) < 0) {
2479 log_warn(LD_CONFIG, "Guardfraction:%d: Bad date '%s'. Ignoring",
2480 current_line_n, line->value);
2481 goto done; /* don't tolerate failure here. */
2483 if (file_written_at < now - MAX_GUARDFRACTION_FILE_AGE) {
2484 log_warn(LD_CONFIG, "Guardfraction:%d: was written very long ago '%s'",
2485 current_line_n, line->value);
2486 goto done; /* don't tolerate failure here. */
2488 } else if (!strcmp(line->key, GUARDFRACTION_INPUTS)) {
2489 char *err_msg = NULL;
2491 if (guardfraction_file_parse_inputs_line(line->value,
2492 &total_consensuses,
2493 &total_days,
2494 &err_msg) < 0) {
2495 log_warn(LD_CONFIG, "Guardfraction:%d: %s",
2496 current_line_n, err_msg);
2497 tor_free(err_msg);
2498 continue;
2501 } else if (!strcmp(line->key, GUARDFRACTION_GUARD)) {
2502 char *err_msg = NULL;
2504 ret_tmp = guardfraction_file_parse_guard_line(line->value,
2505 vote_routerstatuses,
2506 &err_msg);
2507 if (ret_tmp < 0) { /* failed while parsing the guard line */
2508 log_warn(LD_CONFIG, "Guardfraction:%d: %s",
2509 current_line_n, err_msg);
2510 tor_free(err_msg);
2511 continue;
2514 /* Successfully parsed guard line. Check if it was applied properly. */
2515 guards_read_n++;
2516 if (ret_tmp > 0) {
2517 guards_applied_n++;
2519 } else {
2520 log_warn(LD_CONFIG, "Unknown guardfraction line %d (%s %s)",
2521 current_line_n, line->key, line->value);
2525 retval = 0;
2527 log_info(LD_CONFIG,
2528 "Successfully parsed guardfraction file with %d consensuses over "
2529 "%d days. Parsed %d nodes and applied %d of them%s.",
2530 total_consensuses, total_days, guards_read_n, guards_applied_n,
2531 vote_routerstatuses ? "" : " (no routerstatus provided)" );
2533 done:
2534 config_free_lines(front);
2536 if (retval < 0) {
2537 return retval;
2538 } else {
2539 return guards_read_n;
2543 /** Read a guardfraction file at <b>fname</b> and load all its
2544 * information to <b>vote_routerstatuses</b>. */
2546 dirserv_read_guardfraction_file(const char *fname,
2547 smartlist_t *vote_routerstatuses)
2549 char *guardfraction_file_str;
2551 /* Read file to a string */
2552 guardfraction_file_str = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
2553 if (!guardfraction_file_str) {
2554 log_warn(LD_FS, "Cannot open guardfraction file '%s'. Failing.", fname);
2555 return -1;
2558 return dirserv_read_guardfraction_file_from_str(guardfraction_file_str,
2559 vote_routerstatuses);
2563 * Helper function to parse out a line in the measured bandwidth file
2564 * into a measured_bw_line_t output structure. Returns -1 on failure
2565 * or 0 on success.
2567 STATIC int
2568 measured_bw_line_parse(measured_bw_line_t *out, const char *orig_line)
2570 char *line = tor_strdup(orig_line);
2571 char *cp = line;
2572 int got_bw = 0;
2573 int got_node_id = 0;
2574 char *strtok_state; /* lame sauce d'jour */
2575 cp = tor_strtok_r(cp, " \t", &strtok_state);
2577 if (!cp) {
2578 log_warn(LD_DIRSERV, "Invalid line in bandwidth file: %s",
2579 escaped(orig_line));
2580 tor_free(line);
2581 return -1;
2584 if (orig_line[strlen(orig_line)-1] != '\n') {
2585 log_warn(LD_DIRSERV, "Incomplete line in bandwidth file: %s",
2586 escaped(orig_line));
2587 tor_free(line);
2588 return -1;
2591 do {
2592 if (strcmpstart(cp, "bw=") == 0) {
2593 int parse_ok = 0;
2594 char *endptr;
2595 if (got_bw) {
2596 log_warn(LD_DIRSERV, "Double bw= in bandwidth file line: %s",
2597 escaped(orig_line));
2598 tor_free(line);
2599 return -1;
2601 cp+=strlen("bw=");
2603 out->bw_kb = tor_parse_long(cp, 0, 0, LONG_MAX, &parse_ok, &endptr);
2604 if (!parse_ok || (*endptr && !TOR_ISSPACE(*endptr))) {
2605 log_warn(LD_DIRSERV, "Invalid bandwidth in bandwidth file line: %s",
2606 escaped(orig_line));
2607 tor_free(line);
2608 return -1;
2610 got_bw=1;
2611 } else if (strcmpstart(cp, "node_id=$") == 0) {
2612 if (got_node_id) {
2613 log_warn(LD_DIRSERV, "Double node_id= in bandwidth file line: %s",
2614 escaped(orig_line));
2615 tor_free(line);
2616 return -1;
2618 cp+=strlen("node_id=$");
2620 if (strlen(cp) != HEX_DIGEST_LEN ||
2621 base16_decode(out->node_id, DIGEST_LEN,
2622 cp, HEX_DIGEST_LEN) != DIGEST_LEN) {
2623 log_warn(LD_DIRSERV, "Invalid node_id in bandwidth file line: %s",
2624 escaped(orig_line));
2625 tor_free(line);
2626 return -1;
2628 strlcpy(out->node_hex, cp, sizeof(out->node_hex));
2629 got_node_id=1;
2631 } while ((cp = tor_strtok_r(NULL, " \t", &strtok_state)));
2633 if (got_bw && got_node_id) {
2634 tor_free(line);
2635 return 0;
2636 } else {
2637 log_warn(LD_DIRSERV, "Incomplete line in bandwidth file: %s",
2638 escaped(orig_line));
2639 tor_free(line);
2640 return -1;
2645 * Helper function to apply a parsed measurement line to a list
2646 * of bandwidth statuses. Returns true if a line is found,
2647 * false otherwise.
2649 STATIC int
2650 measured_bw_line_apply(measured_bw_line_t *parsed_line,
2651 smartlist_t *routerstatuses)
2653 vote_routerstatus_t *rs = NULL;
2654 if (!routerstatuses)
2655 return 0;
2657 rs = smartlist_bsearch(routerstatuses, parsed_line->node_id,
2658 compare_digest_to_vote_routerstatus_entry);
2660 if (rs) {
2661 rs->has_measured_bw = 1;
2662 rs->measured_bw_kb = (uint32_t)parsed_line->bw_kb;
2663 } else {
2664 log_info(LD_DIRSERV, "Node ID %s not found in routerstatus list",
2665 parsed_line->node_hex);
2668 return rs != NULL;
2672 * Read the measured bandwidth file and apply it to the list of
2673 * vote_routerstatus_t. Returns -1 on error, 0 otherwise.
2676 dirserv_read_measured_bandwidths(const char *from_file,
2677 smartlist_t *routerstatuses)
2679 char line[512];
2680 FILE *fp = tor_fopen_cloexec(from_file, "r");
2681 int applied_lines = 0;
2682 time_t file_time, now;
2683 int ok;
2685 if (fp == NULL) {
2686 log_warn(LD_CONFIG, "Can't open bandwidth file at configured location: %s",
2687 from_file);
2688 return -1;
2691 if (!fgets(line, sizeof(line), fp)
2692 || !strlen(line) || line[strlen(line)-1] != '\n') {
2693 log_warn(LD_DIRSERV, "Long or truncated time in bandwidth file: %s",
2694 escaped(line));
2695 fclose(fp);
2696 return -1;
2699 line[strlen(line)-1] = '\0';
2700 file_time = (time_t)tor_parse_ulong(line, 10, 0, ULONG_MAX, &ok, NULL);
2701 if (!ok) {
2702 log_warn(LD_DIRSERV, "Non-integer time in bandwidth file: %s",
2703 escaped(line));
2704 fclose(fp);
2705 return -1;
2708 now = time(NULL);
2709 if ((now - file_time) > MAX_MEASUREMENT_AGE) {
2710 log_warn(LD_DIRSERV, "Bandwidth measurement file stale. Age: %u",
2711 (unsigned)(time(NULL) - file_time));
2712 fclose(fp);
2713 return -1;
2716 if (routerstatuses)
2717 smartlist_sort(routerstatuses, compare_vote_routerstatus_entries);
2719 while (!feof(fp)) {
2720 measured_bw_line_t parsed_line;
2721 if (fgets(line, sizeof(line), fp) && strlen(line)) {
2722 if (measured_bw_line_parse(&parsed_line, line) != -1) {
2723 /* Also cache the line for dirserv_get_bandwidth_for_router() */
2724 dirserv_cache_measured_bw(&parsed_line, file_time);
2725 if (measured_bw_line_apply(&parsed_line, routerstatuses) > 0)
2726 applied_lines++;
2731 /* Now would be a nice time to clean the cache, too */
2732 dirserv_expire_measured_bw_cache(now);
2734 fclose(fp);
2735 log_info(LD_DIRSERV,
2736 "Bandwidth measurement file successfully read. "
2737 "Applied %d measurements.", applied_lines);
2738 return 0;
2741 /** Return a new networkstatus_t* containing our current opinion. (For v3
2742 * authorities) */
2743 networkstatus_t *
2744 dirserv_generate_networkstatus_vote_obj(crypto_pk_t *private_key,
2745 authority_cert_t *cert)
2747 const or_options_t *options = get_options();
2748 networkstatus_t *v3_out = NULL;
2749 uint32_t addr;
2750 char *hostname = NULL, *client_versions = NULL, *server_versions = NULL;
2751 const char *contact;
2752 smartlist_t *routers, *routerstatuses;
2753 char identity_digest[DIGEST_LEN];
2754 char signing_key_digest[DIGEST_LEN];
2755 int listbadexits = options->AuthDirListBadExits;
2756 routerlist_t *rl = router_get_routerlist();
2757 time_t now = time(NULL);
2758 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2759 networkstatus_voter_info_t *voter = NULL;
2760 vote_timing_t timing;
2761 digestmap_t *omit_as_sybil = NULL;
2762 const int vote_on_reachability = running_long_enough_to_decide_unreachable();
2763 smartlist_t *microdescriptors = NULL;
2765 tor_assert(private_key);
2766 tor_assert(cert);
2768 if (crypto_pk_get_digest(private_key, signing_key_digest)<0) {
2769 log_err(LD_BUG, "Error computing signing key digest");
2770 return NULL;
2772 if (crypto_pk_get_digest(cert->identity_key, identity_digest)<0) {
2773 log_err(LD_BUG, "Error computing identity key digest");
2774 return NULL;
2776 if (resolve_my_address(LOG_WARN, options, &addr, NULL, &hostname)<0) {
2777 log_warn(LD_NET, "Couldn't resolve my hostname");
2778 return NULL;
2780 if (!hostname || !strchr(hostname, '.')) {
2781 tor_free(hostname);
2782 hostname = tor_dup_ip(addr);
2785 if (options->VersioningAuthoritativeDir) {
2786 client_versions = format_versions_list(options->RecommendedClientVersions);
2787 server_versions = format_versions_list(options->RecommendedServerVersions);
2790 contact = get_options()->ContactInfo;
2791 if (!contact)
2792 contact = "(none)";
2795 * Do this so dirserv_compute_performance_thresholds() and
2796 * set_routerstatus_from_routerinfo() see up-to-date bandwidth info.
2798 if (options->V3BandwidthsFile) {
2799 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
2800 } else {
2802 * No bandwidths file; clear the measured bandwidth cache in case we had
2803 * one last time around.
2805 if (dirserv_get_measured_bw_cache_size() > 0) {
2806 dirserv_clear_measured_bw_cache();
2810 /* precompute this part, since we need it to decide what "stable"
2811 * means. */
2812 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2813 dirserv_set_router_is_running(ri, now);
2816 routers = smartlist_new();
2817 smartlist_add_all(routers, rl->routers);
2818 routers_make_ed_keys_unique(routers);
2819 /* After this point, don't use rl->routers; use 'routers' instead. */
2820 routers_sort_by_identity(routers);
2821 omit_as_sybil = get_possible_sybil_list(routers);
2823 DIGESTMAP_FOREACH(omit_as_sybil, sybil_id, void *, ignore) {
2824 (void) ignore;
2825 rep_hist_make_router_pessimal(sybil_id, now);
2826 } DIGESTMAP_FOREACH_END;
2828 /* Count how many have measured bandwidths so we know how to assign flags;
2829 * this must come before dirserv_compute_performance_thresholds() */
2830 dirserv_count_measured_bws(routers);
2832 dirserv_compute_performance_thresholds(omit_as_sybil);
2834 routerstatuses = smartlist_new();
2835 microdescriptors = smartlist_new();
2837 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
2838 if (ri->cache_info.published_on >= cutoff) {
2839 routerstatus_t *rs;
2840 vote_routerstatus_t *vrs;
2841 node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
2842 if (!node)
2843 continue;
2845 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
2846 rs = &vrs->status;
2847 set_routerstatus_from_routerinfo(rs, node, ri, now,
2848 listbadexits);
2850 if (ri->cache_info.signing_key_cert) {
2851 memcpy(vrs->ed25519_id,
2852 ri->cache_info.signing_key_cert->signing_key.pubkey,
2853 ED25519_PUBKEY_LEN);
2856 if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
2857 clear_status_flags_on_sybil(rs);
2859 if (!vote_on_reachability)
2860 rs->is_flagged_running = 0;
2862 vrs->version = version_from_platform(ri->platform);
2863 if (ri->protocol_list) {
2864 vrs->protocols = tor_strdup(ri->protocol_list);
2865 } else {
2866 vrs->protocols = tor_strdup(
2867 protover_compute_for_old_tor(vrs->version));
2869 vrs->microdesc = dirvote_format_all_microdesc_vote_lines(ri, now,
2870 microdescriptors);
2872 smartlist_add(routerstatuses, vrs);
2874 } SMARTLIST_FOREACH_END(ri);
2877 smartlist_t *added =
2878 microdescs_add_list_to_cache(get_microdesc_cache(),
2879 microdescriptors, SAVED_NOWHERE, 0);
2880 smartlist_free(added);
2881 smartlist_free(microdescriptors);
2884 smartlist_free(routers);
2885 digestmap_free(omit_as_sybil, NULL);
2887 /* Apply guardfraction information to routerstatuses. */
2888 if (options->GuardfractionFile) {
2889 dirserv_read_guardfraction_file(options->GuardfractionFile,
2890 routerstatuses);
2893 /* This pass through applies the measured bw lines to the routerstatuses */
2894 if (options->V3BandwidthsFile) {
2895 dirserv_read_measured_bandwidths(options->V3BandwidthsFile,
2896 routerstatuses);
2897 } else {
2899 * No bandwidths file; clear the measured bandwidth cache in case we had
2900 * one last time around.
2902 if (dirserv_get_measured_bw_cache_size() > 0) {
2903 dirserv_clear_measured_bw_cache();
2907 v3_out = tor_malloc_zero(sizeof(networkstatus_t));
2909 v3_out->type = NS_TYPE_VOTE;
2910 dirvote_get_preferred_voting_intervals(&timing);
2911 v3_out->published = now;
2913 char tbuf[ISO_TIME_LEN+1];
2914 networkstatus_t *current_consensus =
2915 networkstatus_get_live_consensus(now);
2916 long last_consensus_interval; /* only used to pick a valid_after */
2917 if (current_consensus)
2918 last_consensus_interval = current_consensus->fresh_until -
2919 current_consensus->valid_after;
2920 else
2921 last_consensus_interval = options->TestingV3AuthInitialVotingInterval;
2922 v3_out->valid_after =
2923 dirvote_get_start_of_next_interval(now, (int)last_consensus_interval,
2924 options->TestingV3AuthVotingStartOffset);
2925 format_iso_time(tbuf, v3_out->valid_after);
2926 log_notice(LD_DIR,"Choosing valid-after time in vote as %s: "
2927 "consensus_set=%d, last_interval=%d",
2928 tbuf, current_consensus?1:0, (int)last_consensus_interval);
2930 v3_out->fresh_until = v3_out->valid_after + timing.vote_interval;
2931 v3_out->valid_until = v3_out->valid_after +
2932 (timing.vote_interval * timing.n_intervals_valid);
2933 v3_out->vote_seconds = timing.vote_delay;
2934 v3_out->dist_seconds = timing.dist_delay;
2935 tor_assert(v3_out->vote_seconds > 0);
2936 tor_assert(v3_out->dist_seconds > 0);
2937 tor_assert(timing.n_intervals_valid > 0);
2939 v3_out->client_versions = client_versions;
2940 v3_out->server_versions = server_versions;
2942 /* These are hardwired, to avoid disaster. */
2943 v3_out->recommended_relay_protocols =
2944 tor_strdup("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 "
2945 "Link=4 LinkAuth=1 Microdesc=1-2 Relay=2");
2946 v3_out->recommended_client_protocols =
2947 tor_strdup("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 "
2948 "Link=4 LinkAuth=1 Microdesc=1-2 Relay=2");
2949 v3_out->required_client_protocols =
2950 tor_strdup("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 "
2951 "Link=4 LinkAuth=1 Microdesc=1-2 Relay=2");
2952 v3_out->required_relay_protocols =
2953 tor_strdup("Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 "
2954 "Link=3-4 LinkAuth=1 Microdesc=1 Relay=1-2");
2956 /* We are not allowed to vote to require anything we don't have. */
2957 tor_assert(protover_all_supported(v3_out->required_relay_protocols, NULL));
2958 tor_assert(protover_all_supported(v3_out->required_client_protocols, NULL));
2960 /* We should not recommend anything we don't have. */
2961 tor_assert_nonfatal(protover_all_supported(
2962 v3_out->recommended_relay_protocols, NULL));
2963 tor_assert_nonfatal(protover_all_supported(
2964 v3_out->recommended_client_protocols, NULL));
2966 v3_out->package_lines = smartlist_new();
2968 config_line_t *cl;
2969 for (cl = get_options()->RecommendedPackages; cl; cl = cl->next) {
2970 if (validate_recommended_package_line(cl->value))
2971 smartlist_add(v3_out->package_lines, tor_strdup(cl->value));
2975 v3_out->known_flags = smartlist_new();
2976 smartlist_split_string(v3_out->known_flags,
2977 "Authority Exit Fast Guard Stable V2Dir Valid HSDir",
2978 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2979 if (vote_on_reachability)
2980 smartlist_add(v3_out->known_flags, tor_strdup("Running"));
2981 if (listbadexits)
2982 smartlist_add(v3_out->known_flags, tor_strdup("BadExit"));
2983 smartlist_sort_strings(v3_out->known_flags);
2985 if (options->ConsensusParams) {
2986 v3_out->net_params = smartlist_new();
2987 smartlist_split_string(v3_out->net_params,
2988 options->ConsensusParams, NULL, 0, 0);
2989 smartlist_sort_strings(v3_out->net_params);
2992 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
2993 voter->nickname = tor_strdup(options->Nickname);
2994 memcpy(voter->identity_digest, identity_digest, DIGEST_LEN);
2995 voter->sigs = smartlist_new();
2996 voter->address = hostname;
2997 voter->addr = addr;
2998 voter->dir_port = router_get_advertised_dir_port(options, 0);
2999 voter->or_port = router_get_advertised_or_port(options);
3000 voter->contact = tor_strdup(contact);
3001 if (options->V3AuthUseLegacyKey) {
3002 authority_cert_t *c = get_my_v3_legacy_cert();
3003 if (c) {
3004 if (crypto_pk_get_digest(c->identity_key, voter->legacy_id_digest)) {
3005 log_warn(LD_BUG, "Unable to compute digest of legacy v3 identity key");
3006 memset(voter->legacy_id_digest, 0, DIGEST_LEN);
3011 v3_out->voters = smartlist_new();
3012 smartlist_add(v3_out->voters, voter);
3013 v3_out->cert = authority_cert_dup(cert);
3014 v3_out->routerstatus_list = routerstatuses;
3015 /* Note: networkstatus_digest is unset; it won't get set until we actually
3016 * format the vote. */
3018 return v3_out;
3021 /** As dirserv_get_routerdescs(), but instead of getting signed_descriptor_t
3022 * pointers, adds copies of digests to fps_out, and doesn't use the
3023 * /tor/server/ prefix. For a /d/ request, adds descriptor digests; for other
3024 * requests, adds identity digests.
3027 dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
3028 const char **msg, int for_unencrypted_conn,
3029 int is_extrainfo)
3031 int by_id = 1;
3032 *msg = NULL;
3034 if (!strcmp(key, "all")) {
3035 routerlist_t *rl = router_get_routerlist();
3036 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
3037 smartlist_add(fps_out,
3038 tor_memdup(r->cache_info.identity_digest, DIGEST_LEN)));
3039 /* Treat "all" requests as if they were unencrypted */
3040 for_unencrypted_conn = 1;
3041 } else if (!strcmp(key, "authority")) {
3042 const routerinfo_t *ri = router_get_my_routerinfo();
3043 if (ri)
3044 smartlist_add(fps_out,
3045 tor_memdup(ri->cache_info.identity_digest, DIGEST_LEN));
3046 } else if (!strcmpstart(key, "d/")) {
3047 by_id = 0;
3048 key += strlen("d/");
3049 dir_split_resource_into_fingerprints(key, fps_out, NULL,
3050 DSR_HEX|DSR_SORT_UNIQ);
3051 } else if (!strcmpstart(key, "fp/")) {
3052 key += strlen("fp/");
3053 dir_split_resource_into_fingerprints(key, fps_out, NULL,
3054 DSR_HEX|DSR_SORT_UNIQ);
3055 } else {
3056 *msg = "Key not recognized";
3057 return -1;
3060 if (for_unencrypted_conn) {
3061 /* Remove anything that insists it not be sent unencrypted. */
3062 SMARTLIST_FOREACH_BEGIN(fps_out, char *, cp) {
3063 const signed_descriptor_t *sd;
3064 if (by_id)
3065 sd = get_signed_descriptor_by_fp(cp,is_extrainfo,0);
3066 else if (is_extrainfo)
3067 sd = extrainfo_get_by_descriptor_digest(cp);
3068 else
3069 sd = router_get_by_descriptor_digest(cp);
3070 if (sd && !sd->send_unencrypted) {
3071 tor_free(cp);
3072 SMARTLIST_DEL_CURRENT(fps_out, cp);
3074 } SMARTLIST_FOREACH_END(cp);
3077 if (!smartlist_len(fps_out)) {
3078 *msg = "Servers unavailable";
3079 return -1;
3081 return 0;
3084 /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
3085 * <b>key</b>. The key should be either
3086 * - "/tor/server/authority" for our own routerinfo;
3087 * - "/tor/server/all" for all the routerinfos we have, concatenated;
3088 * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
3089 * hex identity digests; or
3090 * - "/tor/server/d/D" where D is a plus-separated sequence
3091 * of server descriptor digests, in hex.
3093 * Return 0 if we found some matching descriptors, or -1 if we do not
3094 * have any descriptors, no matching descriptors, or if we did not
3095 * recognize the key (URL).
3096 * If -1 is returned *<b>msg</b> will be set to an appropriate error
3097 * message.
3099 * XXXX rename this function. It's only called from the controller.
3100 * XXXX in fact, refactor this function, merging as much as possible.
3103 dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
3104 const char **msg)
3106 *msg = NULL;
3108 if (!strcmp(key, "/tor/server/all")) {
3109 routerlist_t *rl = router_get_routerlist();
3110 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
3111 smartlist_add(descs_out, &(r->cache_info)));
3112 } else if (!strcmp(key, "/tor/server/authority")) {
3113 const routerinfo_t *ri = router_get_my_routerinfo();
3114 if (ri)
3115 smartlist_add(descs_out, (void*) &(ri->cache_info));
3116 } else if (!strcmpstart(key, "/tor/server/d/")) {
3117 smartlist_t *digests = smartlist_new();
3118 key += strlen("/tor/server/d/");
3119 dir_split_resource_into_fingerprints(key, digests, NULL,
3120 DSR_HEX|DSR_SORT_UNIQ);
3121 SMARTLIST_FOREACH(digests, const char *, d,
3123 signed_descriptor_t *sd = router_get_by_descriptor_digest(d);
3124 if (sd)
3125 smartlist_add(descs_out,sd);
3127 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
3128 smartlist_free(digests);
3129 } else if (!strcmpstart(key, "/tor/server/fp/")) {
3130 smartlist_t *digests = smartlist_new();
3131 time_t cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
3132 key += strlen("/tor/server/fp/");
3133 dir_split_resource_into_fingerprints(key, digests, NULL,
3134 DSR_HEX|DSR_SORT_UNIQ);
3135 SMARTLIST_FOREACH_BEGIN(digests, const char *, d) {
3136 if (router_digest_is_me(d)) {
3137 /* calling router_get_my_routerinfo() to make sure it exists */
3138 const routerinfo_t *ri = router_get_my_routerinfo();
3139 if (ri)
3140 smartlist_add(descs_out, (void*) &(ri->cache_info));
3141 } else {
3142 const routerinfo_t *ri = router_get_by_id_digest(d);
3143 /* Don't actually serve a descriptor that everyone will think is
3144 * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
3145 * Tors from downloading descriptors that they will throw away.
3147 if (ri && ri->cache_info.published_on > cutoff)
3148 smartlist_add(descs_out, (void*) &(ri->cache_info));
3150 } SMARTLIST_FOREACH_END(d);
3151 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
3152 smartlist_free(digests);
3153 } else {
3154 *msg = "Key not recognized";
3155 return -1;
3158 if (!smartlist_len(descs_out)) {
3159 *msg = "Servers unavailable";
3160 return -1;
3162 return 0;
3165 /** Called when a TLS handshake has completed successfully with a
3166 * router listening at <b>address</b>:<b>or_port</b>, and has yielded
3167 * a certificate with digest <b>digest_rcvd</b>.
3169 * Inform the reachability checker that we could get to this relay.
3171 void
3172 dirserv_orconn_tls_done(const tor_addr_t *addr,
3173 uint16_t or_port,
3174 const char *digest_rcvd)
3176 node_t *node = NULL;
3177 tor_addr_port_t orport;
3178 routerinfo_t *ri = NULL;
3179 time_t now = time(NULL);
3180 tor_assert(addr);
3181 tor_assert(digest_rcvd);
3183 node = node_get_mutable_by_id(digest_rcvd);
3184 if (node == NULL || node->ri == NULL)
3185 return;
3186 ri = node->ri;
3188 tor_addr_copy(&orport.addr, addr);
3189 orport.port = or_port;
3190 if (router_has_orport(ri, &orport)) {
3191 /* Found the right router. */
3192 if (!authdir_mode_bridge(get_options()) ||
3193 ri->purpose == ROUTER_PURPOSE_BRIDGE) {
3194 char addrstr[TOR_ADDR_BUF_LEN];
3195 /* This is a bridge or we're not a bridge authorititative --
3196 mark it as reachable. */
3197 log_info(LD_DIRSERV, "Found router %s to be reachable at %s:%d. Yay.",
3198 router_describe(ri),
3199 tor_addr_to_str(addrstr, addr, sizeof(addrstr), 1),
3200 ri->or_port);
3201 if (tor_addr_family(addr) == AF_INET) {
3202 rep_hist_note_router_reachable(digest_rcvd, addr, or_port, now);
3203 node->last_reachable = now;
3204 } else if (tor_addr_family(addr) == AF_INET6) {
3205 /* No rephist for IPv6. */
3206 node->last_reachable6 = now;
3212 /** Called when we, as an authority, receive a new router descriptor either as
3213 * an upload or a download. Used to decide whether to relaunch reachability
3214 * testing for the server. */
3216 dirserv_should_launch_reachability_test(const routerinfo_t *ri,
3217 const routerinfo_t *ri_old)
3219 if (!authdir_mode_handles_descs(get_options(), ri->purpose))
3220 return 0;
3221 if (!ri_old) {
3222 /* New router: Launch an immediate reachability test, so we will have an
3223 * opinion soon in case we're generating a consensus soon */
3224 return 1;
3226 if (ri_old->is_hibernating && !ri->is_hibernating) {
3227 /* It just came out of hibernation; launch a reachability test */
3228 return 1;
3230 if (! routers_have_same_or_addrs(ri, ri_old)) {
3231 /* Address or port changed; launch a reachability test */
3232 return 1;
3234 return 0;
3237 /** Helper function for dirserv_test_reachability(). Start a TLS
3238 * connection to <b>router</b>, and annotate it with when we started
3239 * the test. */
3240 void
3241 dirserv_single_reachability_test(time_t now, routerinfo_t *router)
3243 channel_t *chan = NULL;
3244 node_t *node = NULL;
3245 tor_addr_t router_addr;
3246 (void) now;
3248 tor_assert(router);
3249 node = node_get_mutable_by_id(router->cache_info.identity_digest);
3250 tor_assert(node);
3252 /* IPv4. */
3253 log_debug(LD_OR,"Testing reachability of %s at %s:%u.",
3254 router->nickname, fmt_addr32(router->addr), router->or_port);
3255 tor_addr_from_ipv4h(&router_addr, router->addr);
3256 chan = channel_tls_connect(&router_addr, router->or_port,
3257 router->cache_info.identity_digest);
3258 if (chan) command_setup_channel(chan);
3260 /* Possible IPv6. */
3261 if (get_options()->AuthDirHasIPv6Connectivity == 1 &&
3262 !tor_addr_is_null(&router->ipv6_addr)) {
3263 char addrstr[TOR_ADDR_BUF_LEN];
3264 log_debug(LD_OR, "Testing reachability of %s at %s:%u.",
3265 router->nickname,
3266 tor_addr_to_str(addrstr, &router->ipv6_addr, sizeof(addrstr), 1),
3267 router->ipv6_orport);
3268 chan = channel_tls_connect(&router->ipv6_addr, router->ipv6_orport,
3269 router->cache_info.identity_digest);
3270 if (chan) command_setup_channel(chan);
3274 /** Auth dir server only: load balance such that we only
3275 * try a few connections per call.
3277 * The load balancing is such that if we get called once every ten
3278 * seconds, we will cycle through all the tests in
3279 * REACHABILITY_TEST_CYCLE_PERIOD seconds (a bit over 20 minutes).
3281 void
3282 dirserv_test_reachability(time_t now)
3284 /* XXX decide what to do here; see or-talk thread "purging old router
3285 * information, revocation." -NM
3286 * We can't afford to mess with this in 0.1.2.x. The reason is that
3287 * if we stop doing reachability tests on some of routerlist, then
3288 * we'll for-sure think they're down, which may have unexpected
3289 * effects in other parts of the code. It doesn't hurt much to do
3290 * the testing, and directory authorities are easy to upgrade. Let's
3291 * wait til 0.2.0. -RD */
3292 // time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
3293 routerlist_t *rl = router_get_routerlist();
3294 static char ctr = 0;
3295 int bridge_auth = authdir_mode_bridge(get_options());
3297 SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, router) {
3298 const char *id_digest = router->cache_info.identity_digest;
3299 if (router_is_me(router))
3300 continue;
3301 if (bridge_auth && router->purpose != ROUTER_PURPOSE_BRIDGE)
3302 continue; /* bridge authorities only test reachability on bridges */
3303 // if (router->cache_info.published_on > cutoff)
3304 // continue;
3305 if ((((uint8_t)id_digest[0]) % REACHABILITY_MODULO_PER_TEST) == ctr) {
3306 dirserv_single_reachability_test(now, router);
3308 } SMARTLIST_FOREACH_END(router);
3309 ctr = (ctr + 1) % REACHABILITY_MODULO_PER_TEST; /* increment ctr */
3312 /** Given a fingerprint <b>fp</b> which is either set if we're looking for a
3313 * v2 status, or zeroes if we're looking for a v3 status, or a NUL-padded
3314 * flavor name if we want a flavored v3 status, return a pointer to the
3315 * appropriate cached dir object, or NULL if there isn't one available. */
3316 static cached_dir_t *
3317 lookup_cached_dir_by_fp(const char *fp)
3319 cached_dir_t *d = NULL;
3320 if (tor_digest_is_zero(fp) && cached_consensuses) {
3321 d = strmap_get(cached_consensuses, "ns");
3322 } else if (memchr(fp, '\0', DIGEST_LEN) && cached_consensuses &&
3323 (d = strmap_get(cached_consensuses, fp))) {
3324 /* this here interface is a nasty hack XXXX */;
3326 return d;
3329 /** Remove from <b>fps</b> every networkstatus key where both
3330 * a) we have a networkstatus document and
3331 * b) it is not newer than <b>cutoff</b>.
3333 * Return 1 if any items were present at all; else return 0.
3336 dirserv_remove_old_statuses(smartlist_t *fps, time_t cutoff)
3338 int found_any = 0;
3339 SMARTLIST_FOREACH_BEGIN(fps, char *, digest) {
3340 cached_dir_t *d = lookup_cached_dir_by_fp(digest);
3341 if (!d)
3342 continue;
3343 found_any = 1;
3344 if (d->published <= cutoff) {
3345 tor_free(digest);
3346 SMARTLIST_DEL_CURRENT(fps, digest);
3348 } SMARTLIST_FOREACH_END(digest);
3350 return found_any;
3353 /** Return the cache-info for identity fingerprint <b>fp</b>, or
3354 * its extra-info document if <b>extrainfo</b> is true. Return
3355 * NULL if not found or if the descriptor is older than
3356 * <b>publish_cutoff</b>. */
3357 static const signed_descriptor_t *
3358 get_signed_descriptor_by_fp(const char *fp, int extrainfo,
3359 time_t publish_cutoff)
3361 if (router_digest_is_me(fp)) {
3362 if (extrainfo)
3363 return &(router_get_my_extrainfo()->cache_info);
3364 else
3365 return &(router_get_my_routerinfo()->cache_info);
3366 } else {
3367 const routerinfo_t *ri = router_get_by_id_digest(fp);
3368 if (ri &&
3369 ri->cache_info.published_on > publish_cutoff) {
3370 if (extrainfo)
3371 return extrainfo_get_by_descriptor_digest(
3372 ri->cache_info.extra_info_digest);
3373 else
3374 return &ri->cache_info;
3377 return NULL;
3380 /** Return true iff we have any of the documents (extrainfo or routerdesc)
3381 * specified by the fingerprints in <b>fps</b> and <b>spool_src</b>. Used to
3382 * decide whether to send a 404. */
3384 dirserv_have_any_serverdesc(smartlist_t *fps, int spool_src)
3386 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
3387 SMARTLIST_FOREACH_BEGIN(fps, const char *, fp) {
3388 switch (spool_src)
3390 case DIR_SPOOL_EXTRA_BY_DIGEST:
3391 if (extrainfo_get_by_descriptor_digest(fp)) return 1;
3392 break;
3393 case DIR_SPOOL_SERVER_BY_DIGEST:
3394 if (router_get_by_descriptor_digest(fp)) return 1;
3395 break;
3396 case DIR_SPOOL_EXTRA_BY_FP:
3397 case DIR_SPOOL_SERVER_BY_FP:
3398 if (get_signed_descriptor_by_fp(fp,
3399 spool_src == DIR_SPOOL_EXTRA_BY_FP, publish_cutoff))
3400 return 1;
3401 break;
3403 } SMARTLIST_FOREACH_END(fp);
3404 return 0;
3407 /** Return true iff any of the 256-bit elements in <b>fps</b> is the digest of
3408 * a microdescriptor we have. */
3410 dirserv_have_any_microdesc(const smartlist_t *fps)
3412 microdesc_cache_t *cache = get_microdesc_cache();
3413 SMARTLIST_FOREACH(fps, const char *, fp,
3414 if (microdesc_cache_lookup_by_digest256(cache, fp))
3415 return 1);
3416 return 0;
3419 /** Return an approximate estimate of the number of bytes that will
3420 * be needed to transmit the server descriptors (if is_serverdescs --
3421 * they can be either d/ or fp/ queries) or networkstatus objects (if
3422 * !is_serverdescs) listed in <b>fps</b>. If <b>compressed</b> is set,
3423 * we guess how large the data will be after compression.
3425 * The return value is an estimate; it might be larger or smaller.
3427 size_t
3428 dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
3429 int compressed)
3431 size_t result;
3432 tor_assert(fps);
3433 if (is_serverdescs) {
3434 int n = smartlist_len(fps);
3435 const routerinfo_t *me = router_get_my_routerinfo();
3436 result = (me?me->cache_info.signed_descriptor_len:2048) * n;
3437 if (compressed)
3438 result /= 2; /* observed compressibility is between 35 and 55%. */
3439 } else {
3440 result = 0;
3441 SMARTLIST_FOREACH(fps, const char *, digest, {
3442 cached_dir_t *dir = lookup_cached_dir_by_fp(digest);
3443 if (dir)
3444 result += compressed ? dir->dir_z_len : dir->dir_len;
3447 return result;
3450 /** Given a list of microdescriptor hashes, guess how many bytes will be
3451 * needed to transmit them, and return the guess. */
3452 size_t
3453 dirserv_estimate_microdesc_size(const smartlist_t *fps, int compressed)
3455 size_t result = smartlist_len(fps) * microdesc_average_size(NULL);
3456 if (compressed)
3457 result /= 2;
3458 return result;
3461 /** When we're spooling data onto our outbuf, add more whenever we dip
3462 * below this threshold. */
3463 #define DIRSERV_BUFFER_MIN 16384
3465 /** Spooling helper: called when we have no more data to spool to <b>conn</b>.
3466 * Flushes any remaining data to be (un)compressed, and changes the spool
3467 * source to NONE. Returns 0 on success, negative on failure. */
3468 static int
3469 connection_dirserv_finish_spooling(dir_connection_t *conn)
3471 if (conn->zlib_state) {
3472 connection_write_to_buf_zlib("", 0, conn, 1);
3473 tor_zlib_free(conn->zlib_state);
3474 conn->zlib_state = NULL;
3476 conn->dir_spool_src = DIR_SPOOL_NONE;
3477 return 0;
3480 /** Spooling helper: called when we're sending a bunch of server descriptors,
3481 * and the outbuf has become too empty. Pulls some entries from
3482 * fingerprint_stack, and writes the corresponding servers onto outbuf. If we
3483 * run out of entries, flushes the zlib state and sets the spool source to
3484 * NONE. Returns 0 on success, negative on failure.
3486 static int
3487 connection_dirserv_add_servers_to_outbuf(dir_connection_t *conn)
3489 int by_fp = (conn->dir_spool_src == DIR_SPOOL_SERVER_BY_FP ||
3490 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP);
3491 int extra = (conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP ||
3492 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_DIGEST);
3493 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
3495 const or_options_t *options = get_options();
3497 while (smartlist_len(conn->fingerprint_stack) &&
3498 connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
3499 const char *body;
3500 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3501 const signed_descriptor_t *sd = NULL;
3502 if (by_fp) {
3503 sd = get_signed_descriptor_by_fp(fp, extra, publish_cutoff);
3504 } else {
3505 sd = extra ? extrainfo_get_by_descriptor_digest(fp)
3506 : router_get_by_descriptor_digest(fp);
3508 tor_free(fp);
3509 if (!sd)
3510 continue;
3511 if (!connection_dir_is_encrypted(conn) && !sd->send_unencrypted) {
3512 /* we did this check once before (so we could have an accurate size
3513 * estimate and maybe send a 404 if somebody asked for only bridges on a
3514 * connection), but we need to do it again in case a previously
3515 * unknown bridge descriptor has shown up between then and now. */
3516 continue;
3519 /** If we are the bridge authority and the descriptor is a bridge
3520 * descriptor, remember that we served this descriptor for desc stats. */
3521 if (options->BridgeAuthoritativeDir && by_fp) {
3522 const routerinfo_t *router =
3523 router_get_by_id_digest(sd->identity_digest);
3524 /* router can be NULL here when the bridge auth is asked for its own
3525 * descriptor. */
3526 if (router && router->purpose == ROUTER_PURPOSE_BRIDGE)
3527 rep_hist_note_desc_served(sd->identity_digest);
3529 body = signed_descriptor_get_body(sd);
3530 if (conn->zlib_state) {
3531 int last = ! smartlist_len(conn->fingerprint_stack);
3532 connection_write_to_buf_zlib(body, sd->signed_descriptor_len, conn,
3533 last);
3534 if (last) {
3535 tor_zlib_free(conn->zlib_state);
3536 conn->zlib_state = NULL;
3538 } else {
3539 connection_write_to_buf(body,
3540 sd->signed_descriptor_len,
3541 TO_CONN(conn));
3545 if (!smartlist_len(conn->fingerprint_stack)) {
3546 /* We just wrote the last one; finish up. */
3547 if (conn->zlib_state) {
3548 connection_write_to_buf_zlib("", 0, conn, 1);
3549 tor_zlib_free(conn->zlib_state);
3550 conn->zlib_state = NULL;
3552 conn->dir_spool_src = DIR_SPOOL_NONE;
3553 smartlist_free(conn->fingerprint_stack);
3554 conn->fingerprint_stack = NULL;
3556 return 0;
3559 /** Spooling helper: called when we're sending a bunch of microdescriptors,
3560 * and the outbuf has become too empty. Pulls some entries from
3561 * fingerprint_stack, and writes the corresponding microdescs onto outbuf. If
3562 * we run out of entries, flushes the zlib state and sets the spool source to
3563 * NONE. Returns 0 on success, negative on failure.
3565 static int
3566 connection_dirserv_add_microdescs_to_outbuf(dir_connection_t *conn)
3568 microdesc_cache_t *cache = get_microdesc_cache();
3569 while (smartlist_len(conn->fingerprint_stack) &&
3570 connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
3571 char *fp256 = smartlist_pop_last(conn->fingerprint_stack);
3572 microdesc_t *md = microdesc_cache_lookup_by_digest256(cache, fp256);
3573 tor_free(fp256);
3574 if (!md || !md->body)
3575 continue;
3576 if (conn->zlib_state) {
3577 int last = !smartlist_len(conn->fingerprint_stack);
3578 connection_write_to_buf_zlib(md->body, md->bodylen, conn, last);
3579 if (last) {
3580 tor_zlib_free(conn->zlib_state);
3581 conn->zlib_state = NULL;
3583 } else {
3584 connection_write_to_buf(md->body, md->bodylen, TO_CONN(conn));
3587 if (!smartlist_len(conn->fingerprint_stack)) {
3588 if (conn->zlib_state) {
3589 connection_write_to_buf_zlib("", 0, conn, 1);
3590 tor_zlib_free(conn->zlib_state);
3591 conn->zlib_state = NULL;
3593 conn->dir_spool_src = DIR_SPOOL_NONE;
3594 smartlist_free(conn->fingerprint_stack);
3595 conn->fingerprint_stack = NULL;
3597 return 0;
3600 /** Spooling helper: Called when we're sending a directory or networkstatus,
3601 * and the outbuf has become too empty. Pulls some bytes from
3602 * <b>conn</b>-\>cached_dir-\>dir_z, uncompresses them if appropriate, and
3603 * puts them on the outbuf. If we run out of entries, flushes the zlib state
3604 * and sets the spool source to NONE. Returns 0 on success, negative on
3605 * failure. */
3606 static int
3607 connection_dirserv_add_dir_bytes_to_outbuf(dir_connection_t *conn)
3609 ssize_t bytes;
3610 int64_t remaining;
3612 bytes = DIRSERV_BUFFER_MIN - connection_get_outbuf_len(TO_CONN(conn));
3613 tor_assert(bytes > 0);
3614 tor_assert(conn->cached_dir);
3615 if (bytes < 8192)
3616 bytes = 8192;
3617 remaining = conn->cached_dir->dir_z_len - conn->cached_dir_offset;
3618 if (bytes > remaining)
3619 bytes = (ssize_t) remaining;
3621 if (conn->zlib_state) {
3622 connection_write_to_buf_zlib(
3623 conn->cached_dir->dir_z + conn->cached_dir_offset,
3624 bytes, conn, bytes == remaining);
3625 } else {
3626 connection_write_to_buf(conn->cached_dir->dir_z + conn->cached_dir_offset,
3627 bytes, TO_CONN(conn));
3629 conn->cached_dir_offset += bytes;
3630 if (conn->cached_dir_offset == (int)conn->cached_dir->dir_z_len) {
3631 /* We just wrote the last one; finish up. */
3632 connection_dirserv_finish_spooling(conn);
3633 cached_dir_decref(conn->cached_dir);
3634 conn->cached_dir = NULL;
3636 return 0;
3639 /** Spooling helper: Called when we're spooling networkstatus objects on
3640 * <b>conn</b>, and the outbuf has become too empty. If the current
3641 * networkstatus object (in <b>conn</b>-\>cached_dir) has more data, pull data
3642 * from there. Otherwise, pop the next fingerprint from fingerprint_stack,
3643 * and start spooling the next networkstatus. (A digest of all 0 bytes is
3644 * treated as a request for the current consensus.) If we run out of entries,
3645 * flushes the zlib state and sets the spool source to NONE. Returns 0 on
3646 * success, negative on failure. */
3647 static int
3648 connection_dirserv_add_networkstatus_bytes_to_outbuf(dir_connection_t *conn)
3651 while (connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
3652 if (conn->cached_dir) {
3653 int uncompressing = (conn->zlib_state != NULL);
3654 int r = connection_dirserv_add_dir_bytes_to_outbuf(conn);
3655 if (conn->dir_spool_src == DIR_SPOOL_NONE) {
3656 /* add_dir_bytes thinks we're done with the cached_dir. But we
3657 * may have more cached_dirs! */
3658 conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
3659 /* This bit is tricky. If we were uncompressing the last
3660 * networkstatus, we may need to make a new zlib object to
3661 * uncompress the next one. */
3662 if (uncompressing && ! conn->zlib_state &&
3663 conn->fingerprint_stack &&
3664 smartlist_len(conn->fingerprint_stack)) {
3665 conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD, HIGH_COMPRESSION);
3668 if (r) return r;
3669 } else if (conn->fingerprint_stack &&
3670 smartlist_len(conn->fingerprint_stack)) {
3671 /* Add another networkstatus; start serving it. */
3672 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3673 cached_dir_t *d = lookup_cached_dir_by_fp(fp);
3674 tor_free(fp);
3675 if (d) {
3676 ++d->refcnt;
3677 conn->cached_dir = d;
3678 conn->cached_dir_offset = 0;
3680 } else {
3681 connection_dirserv_finish_spooling(conn);
3682 smartlist_free(conn->fingerprint_stack);
3683 conn->fingerprint_stack = NULL;
3684 return 0;
3687 return 0;
3690 /** Called whenever we have flushed some directory data in state
3691 * SERVER_WRITING. */
3693 connection_dirserv_flushed_some(dir_connection_t *conn)
3695 tor_assert(conn->base_.state == DIR_CONN_STATE_SERVER_WRITING);
3697 if (connection_get_outbuf_len(TO_CONN(conn)) >= DIRSERV_BUFFER_MIN)
3698 return 0;
3700 switch (conn->dir_spool_src) {
3701 case DIR_SPOOL_EXTRA_BY_DIGEST:
3702 case DIR_SPOOL_EXTRA_BY_FP:
3703 case DIR_SPOOL_SERVER_BY_DIGEST:
3704 case DIR_SPOOL_SERVER_BY_FP:
3705 return connection_dirserv_add_servers_to_outbuf(conn);
3706 case DIR_SPOOL_MICRODESC:
3707 return connection_dirserv_add_microdescs_to_outbuf(conn);
3708 case DIR_SPOOL_CACHED_DIR:
3709 return connection_dirserv_add_dir_bytes_to_outbuf(conn);
3710 case DIR_SPOOL_NETWORKSTATUS:
3711 return connection_dirserv_add_networkstatus_bytes_to_outbuf(conn);
3712 case DIR_SPOOL_NONE:
3713 default:
3714 return 0;
3718 /** Return true iff <b>line</b> is a valid RecommendedPackages line.
3721 The grammar is:
3723 "package" SP PACKAGENAME SP VERSION SP URL SP DIGESTS NL
3725 PACKAGENAME = NONSPACE
3726 VERSION = NONSPACE
3727 URL = NONSPACE
3728 DIGESTS = DIGEST | DIGESTS SP DIGEST
3729 DIGEST = DIGESTTYPE "=" DIGESTVAL
3731 NONSPACE = one or more non-space printing characters
3733 DIGESTVAL = DIGESTTYPE = one or more non-=, non-" " characters.
3735 SP = " "
3736 NL = a newline
3740 validate_recommended_package_line(const char *line)
3742 const char *cp = line;
3744 #define WORD() \
3745 do { \
3746 if (*cp == ' ') \
3747 return 0; \
3748 cp = strchr(cp, ' '); \
3749 if (!cp) \
3750 return 0; \
3751 } while (0)
3753 WORD(); /* skip packagename */
3754 ++cp;
3755 WORD(); /* skip version */
3756 ++cp;
3757 WORD(); /* Skip URL */
3758 ++cp;
3760 /* Skip digesttype=digestval + */
3761 int n_entries = 0;
3762 while (1) {
3763 const char *start_of_word = cp;
3764 const char *end_of_word = strchr(cp, ' ');
3765 if (! end_of_word)
3766 end_of_word = cp + strlen(cp);
3768 if (start_of_word == end_of_word)
3769 return 0;
3771 const char *eq = memchr(start_of_word, '=', end_of_word - start_of_word);
3773 if (!eq)
3774 return 0;
3775 if (eq == start_of_word)
3776 return 0;
3777 if (eq == end_of_word - 1)
3778 return 0;
3779 if (memchr(eq+1, '=', end_of_word - (eq+1)))
3780 return 0;
3782 ++n_entries;
3783 if (0 == *end_of_word)
3784 break;
3786 cp = end_of_word + 1;
3789 /* If we reach this point, we have at least 1 entry. */
3790 tor_assert(n_entries > 0);
3791 return 1;
3794 /** Release all storage used by the directory server. */
3795 void
3796 dirserv_free_all(void)
3798 dirserv_free_fingerprint_list();
3800 strmap_free(cached_consensuses, free_cached_dir_);
3801 cached_consensuses = NULL;
3803 dirserv_clear_measured_bw_cache();