Rename "proto " to "pr " in consensuses
[tor.git] / src / or / dirserv.c
blobd7a707d8475c5e78f74d1cd5aa64a217ffeac491
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.
41 /** How far in the future do we allow a router to get? (seconds) */
42 #define ROUTER_ALLOW_SKEW (60*60*12)
43 /** How many seconds do we wait before regenerating the directory? */
44 #define DIR_REGEN_SLACK_TIME 30
45 /** If we're a cache, keep this many networkstatuses around from non-trusted
46 * directory authorities. */
47 #define MAX_UNTRUSTED_NETWORKSTATUSES 16
49 /** Total number of routers with measured bandwidth; this is set by
50 * dirserv_count_measured_bws() before the loop in
51 * dirserv_generate_networkstatus_vote_obj() and checked by
52 * dirserv_get_credible_bandwidth() and
53 * dirserv_compute_performance_thresholds() */
54 static int routers_with_measured_bw = 0;
56 static void directory_remove_invalid(void);
57 static char *format_versions_list(config_line_t *ln);
58 struct authdir_config_t;
59 static uint32_t
60 dirserv_get_status_impl(const char *fp, const char *nickname,
61 uint32_t addr, uint16_t or_port,
62 const char *platform, const char **msg,
63 int severity);
64 static void clear_cached_dir(cached_dir_t *d);
65 static const signed_descriptor_t *get_signed_descriptor_by_fp(
66 const char *fp,
67 int extrainfo,
68 time_t publish_cutoff);
69 static was_router_added_t dirserv_add_extrainfo(extrainfo_t *ei,
70 const char **msg);
71 static uint32_t dirserv_get_bandwidth_for_router_kb(const routerinfo_t *ri);
72 static uint32_t dirserv_get_credible_bandwidth_kb(const routerinfo_t *ri);
74 /************** Fingerprint handling code ************/
76 /* 1 Historically used to indicate Named */
77 #define FP_INVALID 2 /**< Believed invalid. */
78 #define FP_REJECT 4 /**< We will not publish this router. */
79 /* 8 Historically used to avoid using this as a dir. */
80 #define FP_BADEXIT 16 /**< We'll tell clients not to use this as an exit. */
81 /* 32 Historically used to indicade Unnamed */
83 /** Target of status_by_digest map. */
84 typedef uint32_t router_status_t;
86 static void add_fingerprint_to_dir(const char *fp,
87 struct authdir_config_t *list,
88 router_status_t add_status);
90 /** List of nickname-\>identity fingerprint mappings for all the routers
91 * that we name. Used to prevent router impersonation. */
92 typedef struct authdir_config_t {
93 strmap_t *fp_by_name; /**< Map from lc nickname to fingerprint. */
94 digestmap_t *status_by_digest; /**< Map from digest to router_status_t. */
95 } authdir_config_t;
97 /** Should be static; exposed for testing. */
98 static authdir_config_t *fingerprint_list = NULL;
100 /** Allocate and return a new, empty, authdir_config_t. */
101 static authdir_config_t *
102 authdir_config_new(void)
104 authdir_config_t *list = tor_malloc_zero(sizeof(authdir_config_t));
105 list->fp_by_name = strmap_new();
106 list->status_by_digest = digestmap_new();
107 return list;
110 /** Add the fingerprint <b>fp</b> to the smartlist of fingerprint_entry_t's
111 * <b>list</b>, or-ing the currently set status flags with
112 * <b>add_status</b>.
114 /* static */ void
115 add_fingerprint_to_dir(const char *fp, authdir_config_t *list,
116 router_status_t add_status)
118 char *fingerprint;
119 char d[DIGEST_LEN];
120 router_status_t *status;
121 tor_assert(fp);
122 tor_assert(list);
124 fingerprint = tor_strdup(fp);
125 tor_strstrip(fingerprint, " ");
126 if (base16_decode(d, DIGEST_LEN,
127 fingerprint, strlen(fingerprint)) != DIGEST_LEN) {
128 log_warn(LD_DIRSERV, "Couldn't decode fingerprint \"%s\"",
129 escaped(fp));
130 tor_free(fingerprint);
131 return;
134 status = digestmap_get(list->status_by_digest, d);
135 if (!status) {
136 status = tor_malloc_zero(sizeof(router_status_t));
137 digestmap_set(list->status_by_digest, d, status);
140 tor_free(fingerprint);
141 *status |= add_status;
142 return;
145 /** Add the fingerprint for this OR to the global list of recognized
146 * identity key fingerprints. */
148 dirserv_add_own_fingerprint(crypto_pk_t *pk)
150 char fp[FINGERPRINT_LEN+1];
151 if (crypto_pk_get_fingerprint(pk, fp, 0)<0) {
152 log_err(LD_BUG, "Error computing fingerprint");
153 return -1;
155 if (!fingerprint_list)
156 fingerprint_list = authdir_config_new();
157 add_fingerprint_to_dir(fp, fingerprint_list, 0);
158 return 0;
161 /** Load the nickname-\>fingerprint mappings stored in the approved-routers
162 * file. The file format is line-based, with each non-blank holding one
163 * nickname, some space, and a fingerprint for that nickname. On success,
164 * replace the current fingerprint list with the new list and return 0. On
165 * failure, leave the current fingerprint list untouched, and return -1. */
167 dirserv_load_fingerprint_file(void)
169 char *fname;
170 char *cf;
171 char *nickname, *fingerprint;
172 authdir_config_t *fingerprint_list_new;
173 int result;
174 config_line_t *front=NULL, *list;
176 fname = get_datadir_fname("approved-routers");
177 log_info(LD_GENERAL,
178 "Reloading approved fingerprints from \"%s\"...", fname);
180 cf = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
181 if (!cf) {
182 log_warn(LD_FS, "Cannot open fingerprint file '%s'. That's ok.", fname);
183 tor_free(fname);
184 return 0;
186 tor_free(fname);
188 result = config_get_lines(cf, &front, 0);
189 tor_free(cf);
190 if (result < 0) {
191 log_warn(LD_CONFIG, "Error reading from fingerprint file");
192 return -1;
195 fingerprint_list_new = authdir_config_new();
197 for (list=front; list; list=list->next) {
198 char digest_tmp[DIGEST_LEN];
199 router_status_t add_status = 0;
200 nickname = list->key; fingerprint = list->value;
201 tor_strstrip(fingerprint, " "); /* remove spaces */
202 if (strlen(fingerprint) != HEX_DIGEST_LEN ||
203 base16_decode(digest_tmp, sizeof(digest_tmp),
204 fingerprint, HEX_DIGEST_LEN) != sizeof(digest_tmp)) {
205 log_notice(LD_CONFIG,
206 "Invalid fingerprint (nickname '%s', "
207 "fingerprint %s). Skipping.",
208 nickname, fingerprint);
209 continue;
211 if (!strcasecmp(nickname, "!reject")) {
212 add_status = FP_REJECT;
213 } else if (!strcasecmp(nickname, "!badexit")) {
214 add_status = FP_BADEXIT;
215 } else if (!strcasecmp(nickname, "!invalid")) {
216 add_status = FP_INVALID;
218 add_fingerprint_to_dir(fingerprint, fingerprint_list_new, add_status);
221 config_free_lines(front);
222 dirserv_free_fingerprint_list();
223 fingerprint_list = fingerprint_list_new;
224 /* Delete any routers whose fingerprints we no longer recognize */
225 directory_remove_invalid();
226 return 0;
229 /* If this is set, then we don't allow routers that have advertised an Ed25519
230 * identity to stop doing so. This is going to be essential for good identity
231 * security: otherwise anybody who can attack RSA-1024 but not Ed25519 could
232 * just sign fake descriptors missing the Ed25519 key. But we won't actually
233 * be able to prevent that kind of thing until we're confident that there
234 * isn't actually a legit reason to downgrade to 0.2.5. So for now, we have
235 * to leave this #undef.
237 #undef DISABLE_DISABLING_ED25519
239 /** Check whether <b>router</b> has a nickname/identity key combination that
240 * we recognize from the fingerprint list, or an IP we automatically act on
241 * according to our configuration. Return the appropriate router status.
243 * If the status is 'FP_REJECT' and <b>msg</b> is provided, set
244 * *<b>msg</b> to an explanation of why. */
245 uint32_t
246 dirserv_router_get_status(const routerinfo_t *router, const char **msg,
247 int severity)
249 char d[DIGEST_LEN];
250 const int key_pinning = get_options()->AuthDirPinKeys;
252 if (crypto_pk_get_digest(router->identity_pkey, d)) {
253 log_warn(LD_BUG,"Error computing fingerprint");
254 if (msg)
255 *msg = "Bug: Error computing fingerprint";
256 return FP_REJECT;
259 /* dirserv_get_status_impl already rejects versions older than 0.2.4.18-rc,
260 * and onion_curve25519_pkey was introduced in 0.2.4.8-alpha.
261 * But just in case a relay doesn't provide or lies about its version, or
262 * doesn't include an ntor key in its descriptor, check that it exists,
263 * and is non-zero (clients check that it's non-zero before using it). */
264 if (!routerinfo_has_curve25519_onion_key(router)) {
265 log_fn(severity, LD_DIR,
266 "Descriptor from router %s is missing an ntor curve25519 onion "
267 "key.", router_describe(router));
268 if (msg)
269 *msg = "Missing ntor curve25519 onion key. Please upgrade!";
270 return FP_REJECT;
273 if (router->cache_info.signing_key_cert) {
274 /* This has an ed25519 identity key. */
275 if (KEYPIN_MISMATCH ==
276 keypin_check((const uint8_t*)router->cache_info.identity_digest,
277 router->cache_info.signing_key_cert->signing_key.pubkey)) {
278 log_fn(severity, LD_DIR,
279 "Descriptor from router %s has an Ed25519 key, "
280 "but the <rsa,ed25519> keys don't match what they were before.",
281 router_describe(router));
282 if (key_pinning) {
283 if (msg) {
284 *msg = "Ed25519 identity key or RSA identity key has changed.";
286 return FP_REJECT;
289 } else {
290 /* No ed25519 key */
291 if (KEYPIN_MISMATCH == keypin_check_lone_rsa(
292 (const uint8_t*)router->cache_info.identity_digest)) {
293 log_fn(severity, LD_DIR,
294 "Descriptor from router %s has no Ed25519 key, "
295 "when we previously knew an Ed25519 for it. Ignoring for now, "
296 "since Ed25519 keys are fairly new.",
297 router_describe(router));
298 #ifdef DISABLE_DISABLING_ED25519
299 if (key_pinning) {
300 if (msg) {
301 *msg = "Ed25519 identity key has disappeared.";
303 return FP_REJECT;
305 #endif
309 return dirserv_get_status_impl(d, router->nickname,
310 router->addr, router->or_port,
311 router->platform, msg, severity);
314 /** Return true if there is no point in downloading the router described by
315 * <b>rs</b> because this directory would reject it. */
317 dirserv_would_reject_router(const routerstatus_t *rs)
319 uint32_t res;
321 res = dirserv_get_status_impl(rs->identity_digest, rs->nickname,
322 rs->addr, rs->or_port,
323 NULL, NULL, LOG_DEBUG);
325 return (res & FP_REJECT) != 0;
328 /** Helper: As dirserv_router_get_status, but takes the router fingerprint
329 * (hex, no spaces), nickname, address (used for logging only), IP address, OR
330 * port and platform (logging only) as arguments.
332 * Log messages at 'severity'. (There's not much point in
333 * logging that we're rejecting servers we'll not download.)
335 static uint32_t
336 dirserv_get_status_impl(const char *id_digest, const char *nickname,
337 uint32_t addr, uint16_t or_port,
338 const char *platform, const char **msg, int severity)
340 uint32_t result = 0;
341 router_status_t *status_by_digest;
343 if (!fingerprint_list)
344 fingerprint_list = authdir_config_new();
346 log_debug(LD_DIRSERV, "%d fingerprints, %d digests known.",
347 strmap_size(fingerprint_list->fp_by_name),
348 digestmap_size(fingerprint_list->status_by_digest));
350 /* Versions before Tor 0.2.4.18-rc are too old to support, and are
351 * missing some important security fixes too. Disable them. */
352 if (platform && !tor_version_as_new_as(platform,"0.2.4.18-rc")) {
353 if (msg)
354 *msg = "Tor version is insecure or unsupported. Please upgrade!";
355 return FP_REJECT;
358 status_by_digest = digestmap_get(fingerprint_list->status_by_digest,
359 id_digest);
360 if (status_by_digest)
361 result |= *status_by_digest;
363 if (result & FP_REJECT) {
364 if (msg)
365 *msg = "Fingerprint is marked rejected -- please contact us?";
366 return FP_REJECT;
367 } else if (result & FP_INVALID) {
368 if (msg)
369 *msg = "Fingerprint is marked invalid";
372 if (authdir_policy_badexit_address(addr, or_port)) {
373 log_fn(severity, LD_DIRSERV,
374 "Marking '%s' as bad exit because of address '%s'",
375 nickname, fmt_addr32(addr));
376 result |= FP_BADEXIT;
379 if (!authdir_policy_permits_address(addr, or_port)) {
380 log_fn(severity, LD_DIRSERV, "Rejecting '%s' because of address '%s'",
381 nickname, fmt_addr32(addr));
382 if (msg)
383 *msg = "Suspicious relay address range -- please contact us?";
384 return FP_REJECT;
386 if (!authdir_policy_valid_address(addr, or_port)) {
387 log_fn(severity, LD_DIRSERV,
388 "Not marking '%s' valid because of address '%s'",
389 nickname, fmt_addr32(addr));
390 result |= FP_INVALID;
393 return result;
396 /** Clear the current fingerprint list. */
397 void
398 dirserv_free_fingerprint_list(void)
400 if (!fingerprint_list)
401 return;
403 strmap_free(fingerprint_list->fp_by_name, tor_free_);
404 digestmap_free(fingerprint_list->status_by_digest, tor_free_);
405 tor_free(fingerprint_list);
409 * Descriptor list
412 /** Return -1 if <b>ri</b> has a private or otherwise bad address,
413 * unless we're configured to not care. Return 0 if all ok. */
414 static int
415 dirserv_router_has_valid_address(routerinfo_t *ri)
417 tor_addr_t addr;
418 if (get_options()->DirAllowPrivateAddresses)
419 return 0; /* whatever it is, we're fine with it */
420 tor_addr_from_ipv4h(&addr, ri->addr);
422 if (tor_addr_is_internal(&addr, 0)) {
423 log_info(LD_DIRSERV,
424 "Router %s published internal IP address. Refusing.",
425 router_describe(ri));
426 return -1; /* it's a private IP, we should reject it */
428 return 0;
431 /** Check whether we, as a directory server, want to accept <b>ri</b>. If so,
432 * set its is_valid,running fields and return 0. Otherwise, return -1.
434 * If the router is rejected, set *<b>msg</b> to an explanation of why.
436 * If <b>complain</b> then explain at log-level 'notice' why we refused
437 * a descriptor; else explain at log-level 'info'.
440 authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
441 int complain, int *valid_out)
443 /* Okay. Now check whether the fingerprint is recognized. */
444 time_t now;
445 int severity = (complain && ri->contact_info) ? LOG_NOTICE : LOG_INFO;
446 uint32_t status = dirserv_router_get_status(ri, msg, severity);
447 tor_assert(msg);
448 if (status & FP_REJECT)
449 return -1; /* msg is already set. */
451 /* Is there too much clock skew? */
452 now = time(NULL);
453 if (ri->cache_info.published_on > now+ROUTER_ALLOW_SKEW) {
454 log_fn(severity, LD_DIRSERV, "Publication time for %s is too "
455 "far (%d minutes) in the future; possible clock skew. Not adding "
456 "(%s)",
457 router_describe(ri),
458 (int)((ri->cache_info.published_on-now)/60),
459 esc_router_info(ri));
460 *msg = "Rejected: Your clock is set too far in the future, or your "
461 "timezone is not correct.";
462 return -1;
464 if (ri->cache_info.published_on < now-ROUTER_MAX_AGE_TO_PUBLISH) {
465 log_fn(severity, LD_DIRSERV,
466 "Publication time for %s is too far "
467 "(%d minutes) in the past. Not adding (%s)",
468 router_describe(ri),
469 (int)((now-ri->cache_info.published_on)/60),
470 esc_router_info(ri));
471 *msg = "Rejected: Server is expired, or your clock is too far in the past,"
472 " or your timezone is not correct.";
473 return -1;
475 if (dirserv_router_has_valid_address(ri) < 0) {
476 log_fn(severity, LD_DIRSERV,
477 "Router %s has invalid address. Not adding (%s).",
478 router_describe(ri),
479 esc_router_info(ri));
480 *msg = "Rejected: Address is a private address.";
481 return -1;
484 *valid_out = ! (status & FP_INVALID);
486 return 0;
489 /** Update the relevant flags of <b>node</b> based on our opinion as a
490 * directory authority in <b>authstatus</b>, as returned by
491 * dirserv_router_get_status or equivalent. */
492 void
493 dirserv_set_node_flags_from_authoritative_status(node_t *node,
494 uint32_t authstatus)
496 node->is_valid = (authstatus & FP_INVALID) ? 0 : 1;
497 node->is_bad_exit = (authstatus & FP_BADEXIT) ? 1 : 0;
500 /** True iff <b>a</b> is more severe than <b>b</b>. */
501 static int
502 WRA_MORE_SEVERE(was_router_added_t a, was_router_added_t b)
504 return a < b;
507 /** As for dirserv_add_descriptor(), but accepts multiple documents, and
508 * returns the most severe error that occurred for any one of them. */
509 was_router_added_t
510 dirserv_add_multiple_descriptors(const char *desc, uint8_t purpose,
511 const char *source,
512 const char **msg)
514 was_router_added_t r, r_tmp;
515 const char *msg_out;
516 smartlist_t *list;
517 const char *s;
518 int n_parsed = 0;
519 time_t now = time(NULL);
520 char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
521 char time_buf[ISO_TIME_LEN+1];
522 int general = purpose == ROUTER_PURPOSE_GENERAL;
523 tor_assert(msg);
525 r=ROUTER_ADDED_SUCCESSFULLY; /*Least severe return value. */
527 format_iso_time(time_buf, now);
528 if (tor_snprintf(annotation_buf, sizeof(annotation_buf),
529 "@uploaded-at %s\n"
530 "@source %s\n"
531 "%s%s%s", time_buf, escaped(source),
532 !general ? "@purpose " : "",
533 !general ? router_purpose_to_string(purpose) : "",
534 !general ? "\n" : "")<0) {
535 *msg = "Couldn't format annotations";
536 return -1;
539 s = desc;
540 list = smartlist_new();
541 if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 0, 0,
542 annotation_buf, NULL)) {
543 SMARTLIST_FOREACH(list, routerinfo_t *, ri, {
544 msg_out = NULL;
545 tor_assert(ri->purpose == purpose);
546 r_tmp = dirserv_add_descriptor(ri, &msg_out, source);
547 if (WRA_MORE_SEVERE(r_tmp, r)) {
548 r = r_tmp;
549 *msg = msg_out;
553 n_parsed += smartlist_len(list);
554 smartlist_clear(list);
556 s = desc;
557 if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 1, 0,
558 NULL, NULL)) {
559 SMARTLIST_FOREACH(list, extrainfo_t *, ei, {
560 msg_out = NULL;
562 r_tmp = dirserv_add_extrainfo(ei, &msg_out);
563 if (WRA_MORE_SEVERE(r_tmp, r)) {
564 r = r_tmp;
565 *msg = msg_out;
569 n_parsed += smartlist_len(list);
570 smartlist_free(list);
572 if (! *msg) {
573 if (!n_parsed) {
574 *msg = "No descriptors found in your POST.";
575 if (WRA_WAS_ADDED(r))
576 r = ROUTER_IS_ALREADY_KNOWN;
577 } else {
578 *msg = "(no message)";
582 return r;
585 /** Examine the parsed server descriptor in <b>ri</b> and maybe insert it into
586 * the list of server descriptors. Set *<b>msg</b> to a message that should be
587 * passed back to the origin of this descriptor, or NULL if there is no such
588 * message. Use <b>source</b> to produce better log messages.
590 * Return the status of the operation
592 * This function is only called when fresh descriptors are posted, not when
593 * we re-load the cache.
595 was_router_added_t
596 dirserv_add_descriptor(routerinfo_t *ri, const char **msg, const char *source)
598 was_router_added_t r;
599 routerinfo_t *ri_old;
600 char *desc, *nickname;
601 const size_t desclen = ri->cache_info.signed_descriptor_len +
602 ri->cache_info.annotations_len;
603 const int key_pinning = get_options()->AuthDirPinKeys;
604 *msg = NULL;
606 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
607 * network and it'll clog everything up. */
608 if (ri->cache_info.signed_descriptor_len > MAX_DESCRIPTOR_UPLOAD_SIZE) {
609 log_notice(LD_DIR, "Somebody attempted to publish a router descriptor '%s'"
610 " (source: %s) with size %d. Either this is an attack, or the "
611 "MAX_DESCRIPTOR_UPLOAD_SIZE (%d) constant is too low.",
612 ri->nickname, source, (int)ri->cache_info.signed_descriptor_len,
613 MAX_DESCRIPTOR_UPLOAD_SIZE);
614 *msg = "Router descriptor was too large.";
615 control_event_or_authdir_new_descriptor("REJECTED",
616 ri->cache_info.signed_descriptor_body,
617 desclen, *msg);
618 routerinfo_free(ri);
619 return ROUTER_AUTHDIR_REJECTS;
622 /* Check whether this descriptor is semantically identical to the last one
623 * from this server. (We do this here and not in router_add_to_routerlist
624 * because we want to be able to accept the newest router descriptor that
625 * another authority has, so we all converge on the same one.) */
626 ri_old = router_get_mutable_by_digest(ri->cache_info.identity_digest);
627 if (ri_old && ri_old->cache_info.published_on < ri->cache_info.published_on
628 && router_differences_are_cosmetic(ri_old, ri)
629 && !router_is_me(ri)) {
630 log_info(LD_DIRSERV,
631 "Not replacing descriptor from %s (source: %s); "
632 "differences are cosmetic.",
633 router_describe(ri), source);
634 *msg = "Not replacing router descriptor; no information has changed since "
635 "the last one with this identity.";
636 control_event_or_authdir_new_descriptor("DROPPED",
637 ri->cache_info.signed_descriptor_body,
638 desclen, *msg);
639 routerinfo_free(ri);
640 return ROUTER_IS_ALREADY_KNOWN;
643 /* Do keypinning again ... this time, to add the pin if appropriate */
644 int keypin_status;
645 if (ri->cache_info.signing_key_cert) {
646 keypin_status = keypin_check_and_add(
647 (const uint8_t*)ri->cache_info.identity_digest,
648 ri->cache_info.signing_key_cert->signing_key.pubkey,
649 ! key_pinning);
650 } else {
651 keypin_status = keypin_check_lone_rsa(
652 (const uint8_t*)ri->cache_info.identity_digest);
653 #ifndef DISABLE_DISABLING_ED25519
654 if (keypin_status == KEYPIN_MISMATCH)
655 keypin_status = KEYPIN_NOT_FOUND;
656 #endif
658 if (keypin_status == KEYPIN_MISMATCH && key_pinning) {
659 log_info(LD_DIRSERV, "Dropping descriptor from %s (source: %s) because "
660 "its key did not match an older RSA/Ed25519 keypair",
661 router_describe(ri), source);
662 *msg = "Looks like your keypair does not match its older value.";
663 return ROUTER_AUTHDIR_REJECTS;
666 /* Make a copy of desc, since router_add_to_routerlist might free
667 * ri and its associated signed_descriptor_t. */
668 desc = tor_strndup(ri->cache_info.signed_descriptor_body, desclen);
669 nickname = tor_strdup(ri->nickname);
671 /* Tell if we're about to need to launch a test if we add this. */
672 ri->needs_retest_if_added =
673 dirserv_should_launch_reachability_test(ri, ri_old);
675 r = router_add_to_routerlist(ri, msg, 0, 0);
676 if (!WRA_WAS_ADDED(r)) {
677 /* unless the routerinfo was fine, just out-of-date */
678 if (WRA_WAS_REJECTED(r))
679 control_event_or_authdir_new_descriptor("REJECTED", desc, desclen, *msg);
680 log_info(LD_DIRSERV,
681 "Did not add descriptor from '%s' (source: %s): %s.",
682 nickname, source, *msg ? *msg : "(no message)");
683 } else {
684 smartlist_t *changed;
685 control_event_or_authdir_new_descriptor("ACCEPTED", desc, desclen, *msg);
687 changed = smartlist_new();
688 smartlist_add(changed, ri);
689 routerlist_descriptors_added(changed, 0);
690 smartlist_free(changed);
691 if (!*msg) {
692 *msg = "Descriptor accepted";
694 log_info(LD_DIRSERV,
695 "Added descriptor from '%s' (source: %s): %s.",
696 nickname, source, *msg);
698 tor_free(desc);
699 tor_free(nickname);
700 return r;
703 /** As dirserv_add_descriptor, but for an extrainfo_t <b>ei</b>. */
704 static was_router_added_t
705 dirserv_add_extrainfo(extrainfo_t *ei, const char **msg)
707 routerinfo_t *ri;
708 int r;
709 tor_assert(msg);
710 *msg = NULL;
712 /* Needs to be mutable so routerinfo_incompatible_with_extrainfo
713 * can mess with some of the flags in ri->cache_info. */
714 ri = router_get_mutable_by_digest(ei->cache_info.identity_digest);
715 if (!ri) {
716 *msg = "No corresponding router descriptor for extra-info descriptor";
717 extrainfo_free(ei);
718 return ROUTER_BAD_EI;
721 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
722 * network and it'll clog everything up. */
723 if (ei->cache_info.signed_descriptor_len > MAX_EXTRAINFO_UPLOAD_SIZE) {
724 log_notice(LD_DIR, "Somebody attempted to publish an extrainfo "
725 "with size %d. Either this is an attack, or the "
726 "MAX_EXTRAINFO_UPLOAD_SIZE (%d) constant is too low.",
727 (int)ei->cache_info.signed_descriptor_len,
728 MAX_EXTRAINFO_UPLOAD_SIZE);
729 *msg = "Extrainfo document was too large";
730 extrainfo_free(ei);
731 return ROUTER_BAD_EI;
734 if ((r = routerinfo_incompatible_with_extrainfo(ri->identity_pkey, ei,
735 &ri->cache_info, msg))) {
736 extrainfo_free(ei);
737 return r < 0 ? ROUTER_IS_ALREADY_KNOWN : ROUTER_BAD_EI;
739 router_add_extrainfo_to_routerlist(ei, msg, 0, 0);
740 return ROUTER_ADDED_SUCCESSFULLY;
743 /** Remove all descriptors whose nicknames or fingerprints no longer
744 * are allowed by our fingerprint list. (Descriptors that used to be
745 * good can become bad when we reload the fingerprint list.)
747 static void
748 directory_remove_invalid(void)
750 routerlist_t *rl = router_get_routerlist();
751 smartlist_t *nodes = smartlist_new();
752 smartlist_add_all(nodes, nodelist_get_list());
754 SMARTLIST_FOREACH_BEGIN(nodes, node_t *, node) {
755 const char *msg = NULL;
756 routerinfo_t *ent = node->ri;
757 char description[NODE_DESC_BUF_LEN];
758 uint32_t r;
759 if (!ent)
760 continue;
761 r = dirserv_router_get_status(ent, &msg, LOG_INFO);
762 router_get_description(description, ent);
763 if (r & FP_REJECT) {
764 log_info(LD_DIRSERV, "Router %s is now rejected: %s",
765 description, msg?msg:"");
766 routerlist_remove(rl, ent, 0, time(NULL));
767 continue;
769 if (bool_neq((r & FP_INVALID), !node->is_valid)) {
770 log_info(LD_DIRSERV, "Router '%s' is now %svalid.", description,
771 (r&FP_INVALID) ? "in" : "");
772 node->is_valid = (r&FP_INVALID)?0:1;
774 if (bool_neq((r & FP_BADEXIT), node->is_bad_exit)) {
775 log_info(LD_DIRSERV, "Router '%s' is now a %s exit", description,
776 (r & FP_BADEXIT) ? "bad" : "good");
777 node->is_bad_exit = (r&FP_BADEXIT) ? 1: 0;
779 } SMARTLIST_FOREACH_END(node);
781 routerlist_assert_ok(rl);
782 smartlist_free(nodes);
786 * Allocate and return a description of the status of the server <b>desc</b>,
787 * for use in a v1-style router-status line. The server is listed
788 * as running iff <b>is_live</b> is true.
790 static char *
791 list_single_server_status(const routerinfo_t *desc, int is_live)
793 char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
794 char *cp;
795 const node_t *node;
797 tor_assert(desc);
799 cp = buf;
800 if (!is_live) {
801 *cp++ = '!';
803 node = node_get_by_id(desc->cache_info.identity_digest);
804 if (node && node->is_valid) {
805 strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
806 cp += strlen(cp);
807 *cp++ = '=';
809 *cp++ = '$';
810 base16_encode(cp, HEX_DIGEST_LEN+1, desc->cache_info.identity_digest,
811 DIGEST_LEN);
812 return tor_strdup(buf);
815 /* DOCDOC running_long_enough_to_decide_unreachable */
816 static inline int
817 running_long_enough_to_decide_unreachable(void)
819 return time_of_process_start
820 + get_options()->TestingAuthDirTimeToLearnReachability < approx_time();
823 /** Each server needs to have passed a reachability test no more
824 * than this number of seconds ago, or it is listed as down in
825 * the directory. */
826 #define REACHABLE_TIMEOUT (45*60)
828 /** If we tested a router and found it reachable _at least this long_ after it
829 * declared itself hibernating, it is probably done hibernating and we just
830 * missed a descriptor from it. */
831 #define HIBERNATION_PUBLICATION_SKEW (60*60)
833 /** Treat a router as alive if
834 * - It's me, and I'm not hibernating.
835 * or - We've found it reachable recently. */
836 void
837 dirserv_set_router_is_running(routerinfo_t *router, time_t now)
839 /*XXXX This function is a mess. Separate out the part that calculates
840 whether it's reachable and the part that tells rephist that the router was
841 unreachable.
843 int answer;
844 const or_options_t *options = get_options();
845 node_t *node = node_get_mutable_by_id(router->cache_info.identity_digest);
846 tor_assert(node);
848 if (router_is_me(router)) {
849 /* We always know if we are down ourselves. */
850 answer = ! we_are_hibernating();
851 } else if (router->is_hibernating &&
852 (router->cache_info.published_on +
853 HIBERNATION_PUBLICATION_SKEW) > node->last_reachable) {
854 /* A hibernating router is down unless we (somehow) had contact with it
855 * since it declared itself to be hibernating. */
856 answer = 0;
857 } else if (options->AssumeReachable) {
858 /* If AssumeReachable, everybody is up unless they say they are down! */
859 answer = 1;
860 } else {
861 /* Otherwise, a router counts as up if we found all announced OR
862 ports reachable in the last REACHABLE_TIMEOUT seconds.
864 XXX prop186 For now there's always one IPv4 and at most one
865 IPv6 OR port.
867 If we're not on IPv6, don't consider reachability of potential
868 IPv6 OR port since that'd kill all dual stack relays until a
869 majority of the dir auths have IPv6 connectivity. */
870 answer = (now < node->last_reachable + REACHABLE_TIMEOUT &&
871 (options->AuthDirHasIPv6Connectivity != 1 ||
872 tor_addr_is_null(&router->ipv6_addr) ||
873 now < node->last_reachable6 + REACHABLE_TIMEOUT));
876 if (!answer && running_long_enough_to_decide_unreachable()) {
877 /* Not considered reachable. tell rephist about that.
879 Because we launch a reachability test for each router every
880 REACHABILITY_TEST_CYCLE_PERIOD seconds, then the router has probably
881 been down since at least that time after we last successfully reached
884 XXX ipv6
886 time_t when = now;
887 if (node->last_reachable &&
888 node->last_reachable + REACHABILITY_TEST_CYCLE_PERIOD < now)
889 when = node->last_reachable + REACHABILITY_TEST_CYCLE_PERIOD;
890 rep_hist_note_router_unreachable(router->cache_info.identity_digest, when);
893 node->is_running = answer;
896 /** Based on the routerinfo_ts in <b>routers</b>, allocate the
897 * contents of a v1-style router-status line, and store it in
898 * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
900 * If for_controller is true, include the routers with very old descriptors.
903 list_server_status_v1(smartlist_t *routers, char **router_status_out,
904 int for_controller)
906 /* List of entries in a router-status style: An optional !, then an optional
907 * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
908 smartlist_t *rs_entries;
909 time_t now = time(NULL);
910 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
911 const or_options_t *options = get_options();
912 /* We include v2 dir auths here too, because they need to answer
913 * controllers. Eventually we'll deprecate this whole function;
914 * see also networkstatus_getinfo_by_purpose(). */
915 int authdir = authdir_mode_publishes_statuses(options);
916 tor_assert(router_status_out);
918 rs_entries = smartlist_new();
920 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
921 const node_t *node = node_get_by_id(ri->cache_info.identity_digest);
922 tor_assert(node);
923 if (authdir) {
924 /* Update router status in routerinfo_t. */
925 dirserv_set_router_is_running(ri, now);
927 if (for_controller) {
928 char name_buf[MAX_VERBOSE_NICKNAME_LEN+2];
929 char *cp = name_buf;
930 if (!node->is_running)
931 *cp++ = '!';
932 router_get_verbose_nickname(cp, ri);
933 smartlist_add(rs_entries, tor_strdup(name_buf));
934 } else if (ri->cache_info.published_on >= cutoff) {
935 smartlist_add(rs_entries, list_single_server_status(ri,
936 node->is_running));
938 } SMARTLIST_FOREACH_END(ri);
940 *router_status_out = smartlist_join_strings(rs_entries, " ", 0, NULL);
942 SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
943 smartlist_free(rs_entries);
945 return 0;
948 /** Given a (possibly empty) list of config_line_t, each line of which contains
949 * a list of comma-separated version numbers surrounded by optional space,
950 * allocate and return a new string containing the version numbers, in order,
951 * separated by commas. Used to generate Recommended(Client|Server)?Versions
953 static char *
954 format_versions_list(config_line_t *ln)
956 smartlist_t *versions;
957 char *result;
958 versions = smartlist_new();
959 for ( ; ln; ln = ln->next) {
960 smartlist_split_string(versions, ln->value, ",",
961 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
963 sort_version_list(versions, 1);
964 result = smartlist_join_strings(versions,",",0,NULL);
965 SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
966 smartlist_free(versions);
967 return result;
970 /** Return 1 if <b>ri</b>'s descriptor is "active" -- running, valid,
971 * not hibernating, having observed bw greater 0, and not too old. Else
972 * return 0.
974 static int
975 router_is_active(const routerinfo_t *ri, const node_t *node, time_t now)
977 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
978 if (ri->cache_info.published_on < cutoff) {
979 return 0;
981 if (!node->is_running || !node->is_valid || ri->is_hibernating) {
982 return 0;
984 /* Only require bandwith capacity in non-test networks, or
985 * if TestingTorNetwork, and TestingMinExitFlagThreshold is non-zero */
986 if (!ri->bandwidthcapacity) {
987 if (get_options()->TestingTorNetwork) {
988 if (get_options()->TestingMinExitFlagThreshold > 0) {
989 /* If we're in a TestingTorNetwork, and TestingMinExitFlagThreshold is,
990 * then require bandwidthcapacity */
991 return 0;
993 } else {
994 /* If we're not in a TestingTorNetwork, then require bandwidthcapacity */
995 return 0;
998 return 1;
1001 /********************************************************************/
1003 /* A set of functions to answer questions about how we'd like to behave
1004 * as a directory mirror/client. */
1006 /** Return 1 if we fetch our directory material directly from the
1007 * authorities, rather than from a mirror. */
1009 directory_fetches_from_authorities(const or_options_t *options)
1011 const routerinfo_t *me;
1012 uint32_t addr;
1013 int refuseunknown;
1014 if (options->FetchDirInfoEarly)
1015 return 1;
1016 if (options->BridgeRelay == 1)
1017 return 0;
1018 if (server_mode(options) && router_pick_published_address(options, &addr)<0)
1019 return 1; /* we don't know our IP address; ask an authority. */
1020 refuseunknown = ! router_my_exit_policy_is_reject_star() &&
1021 should_refuse_unknown_exits(options);
1022 if (!dir_server_mode(options) && !refuseunknown)
1023 return 0;
1024 if (!server_mode(options) || !advertised_server_mode())
1025 return 0;
1026 me = router_get_my_routerinfo();
1027 if (!me || (!me->supports_tunnelled_dir_requests && !refuseunknown))
1028 return 0; /* if we don't service directory requests, return 0 too */
1029 return 1;
1032 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1033 * on the "mirror" schedule rather than the "client" schedule.
1036 directory_fetches_dir_info_early(const or_options_t *options)
1038 return directory_fetches_from_authorities(options);
1041 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1042 * on a very passive schedule -- waiting long enough for ordinary clients
1043 * to probably have the info we want. These would include bridge users,
1044 * and maybe others in the future e.g. if a Tor client uses another Tor
1045 * client as a directory guard.
1048 directory_fetches_dir_info_later(const or_options_t *options)
1050 return options->UseBridges != 0;
1053 /** Return true iff we want to fetch and keep certificates for authorities
1054 * that we don't acknowledge as authorities ourself.
1057 directory_caches_unknown_auth_certs(const or_options_t *options)
1059 return dir_server_mode(options) || options->BridgeRelay;
1062 /** Return 1 if we want to keep descriptors, networkstatuses, etc around.
1063 * Else return 0.
1064 * Check options->DirPort_set and directory_permits_begindir_requests()
1065 * to see if we are willing to serve these directory documents to others via
1066 * the DirPort and begindir-over-ORPort, respectively.
1069 directory_caches_dir_info(const or_options_t *options)
1071 if (options->BridgeRelay || dir_server_mode(options))
1072 return 1;
1073 if (!server_mode(options) || !advertised_server_mode())
1074 return 0;
1075 /* We need an up-to-date view of network info if we're going to try to
1076 * block exit attempts from unknown relays. */
1077 return ! router_my_exit_policy_is_reject_star() &&
1078 should_refuse_unknown_exits(options);
1081 /** Return 1 if we want to allow remote people to ask us directory
1082 * requests via the "begin_dir" interface, which doesn't require
1083 * having any separate port open. */
1085 directory_permits_begindir_requests(const or_options_t *options)
1087 return options->BridgeRelay != 0 || dir_server_mode(options);
1090 /** Return 1 if we have no need to fetch new descriptors. This generally
1091 * happens when we're not a dir cache and we haven't built any circuits
1092 * lately.
1095 directory_too_idle_to_fetch_descriptors(const or_options_t *options,
1096 time_t now)
1098 return !directory_caches_dir_info(options) &&
1099 !options->FetchUselessDescriptors &&
1100 rep_hist_circbuilding_dormant(now);
1103 /********************************************************************/
1105 /** Map from flavor name to the cached_dir_t for the v3 consensuses that we're
1106 * currently serving. */
1107 static strmap_t *cached_consensuses = NULL;
1109 /** Decrement the reference count on <b>d</b>, and free it if it no longer has
1110 * any references. */
1111 void
1112 cached_dir_decref(cached_dir_t *d)
1114 if (!d || --d->refcnt > 0)
1115 return;
1116 clear_cached_dir(d);
1117 tor_free(d);
1120 /** Allocate and return a new cached_dir_t containing the string <b>s</b>,
1121 * published at <b>published</b>. */
1122 cached_dir_t *
1123 new_cached_dir(char *s, time_t published)
1125 cached_dir_t *d = tor_malloc_zero(sizeof(cached_dir_t));
1126 d->refcnt = 1;
1127 d->dir = s;
1128 d->dir_len = strlen(s);
1129 d->published = published;
1130 if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
1131 ZLIB_METHOD)) {
1132 log_warn(LD_BUG, "Error compressing directory");
1134 return d;
1137 /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
1138 static void
1139 clear_cached_dir(cached_dir_t *d)
1141 tor_free(d->dir);
1142 tor_free(d->dir_z);
1143 memset(d, 0, sizeof(cached_dir_t));
1146 /** Free all storage held by the cached_dir_t in <b>d</b>. */
1147 static void
1148 free_cached_dir_(void *_d)
1150 cached_dir_t *d;
1151 if (!_d)
1152 return;
1154 d = (cached_dir_t *)_d;
1155 cached_dir_decref(d);
1158 /** Replace the v3 consensus networkstatus of type <b>flavor_name</b> that
1159 * we're serving with <b>networkstatus</b>, published at <b>published</b>. No
1160 * validation is performed. */
1161 void
1162 dirserv_set_cached_consensus_networkstatus(const char *networkstatus,
1163 const char *flavor_name,
1164 const common_digests_t *digests,
1165 time_t published)
1167 cached_dir_t *new_networkstatus;
1168 cached_dir_t *old_networkstatus;
1169 if (!cached_consensuses)
1170 cached_consensuses = strmap_new();
1172 new_networkstatus = new_cached_dir(tor_strdup(networkstatus), published);
1173 memcpy(&new_networkstatus->digests, digests, sizeof(common_digests_t));
1174 old_networkstatus = strmap_set(cached_consensuses, flavor_name,
1175 new_networkstatus);
1176 if (old_networkstatus)
1177 cached_dir_decref(old_networkstatus);
1180 /** Return the latest downloaded consensus networkstatus in encoded, signed,
1181 * optionally compressed format, suitable for sending to clients. */
1182 cached_dir_t *
1183 dirserv_get_consensus(const char *flavor_name)
1185 if (!cached_consensuses)
1186 return NULL;
1187 return strmap_get(cached_consensuses, flavor_name);
1190 /** If a router's uptime is at least this value, then it is always
1191 * considered stable, regardless of the rest of the network. This
1192 * way we resist attacks where an attacker doubles the size of the
1193 * network using allegedly high-uptime nodes, displacing all the
1194 * current guards. */
1195 #define UPTIME_TO_GUARANTEE_STABLE (3600*24*30)
1196 /** If a router's MTBF is at least this value, then it is always stable.
1197 * See above. (Corresponds to about 7 days for current decay rates.) */
1198 #define MTBF_TO_GUARANTEE_STABLE (60*60*24*5)
1199 /** Similarly, every node with at least this much weighted time known can be
1200 * considered familiar enough to be a guard. Corresponds to about 20 days for
1201 * current decay rates.
1203 #define TIME_KNOWN_TO_GUARANTEE_FAMILIAR (8*24*60*60)
1204 /** Similarly, every node with sufficient WFU is around enough to be a guard.
1206 #define WFU_TO_GUARANTEE_GUARD (0.98)
1208 /* Thresholds for server performance: set by
1209 * dirserv_compute_performance_thresholds, and used by
1210 * generate_v2_networkstatus */
1212 /** Any router with an uptime of at least this value is stable. */
1213 static uint32_t stable_uptime = 0; /* start at a safe value */
1214 /** Any router with an mtbf of at least this value is stable. */
1215 static double stable_mtbf = 0.0;
1216 /** If true, we have measured enough mtbf info to look at stable_mtbf rather
1217 * than stable_uptime. */
1218 static int enough_mtbf_info = 0;
1219 /** Any router with a weighted fractional uptime of at least this much might
1220 * be good as a guard. */
1221 static double guard_wfu = 0.0;
1222 /** Don't call a router a guard unless we've known about it for at least this
1223 * many seconds. */
1224 static long guard_tk = 0;
1225 /** Any router with a bandwidth at least this high is "Fast" */
1226 static uint32_t fast_bandwidth_kb = 0;
1227 /** If exits can be guards, then all guards must have a bandwidth this
1228 * high. */
1229 static uint32_t guard_bandwidth_including_exits_kb = 0;
1230 /** If exits can't be guards, then all guards must have a bandwidth this
1231 * high. */
1232 static uint32_t guard_bandwidth_excluding_exits_kb = 0;
1234 /** Helper: estimate the uptime of a router given its stated uptime and the
1235 * amount of time since it last stated its stated uptime. */
1236 static inline long
1237 real_uptime(const routerinfo_t *router, time_t now)
1239 if (now < router->cache_info.published_on)
1240 return router->uptime;
1241 else
1242 return router->uptime + (now - router->cache_info.published_on);
1245 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1246 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1247 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1248 * bandwidth.
1250 static int
1251 dirserv_thinks_router_is_unreliable(time_t now,
1252 routerinfo_t *router,
1253 int need_uptime, int need_capacity)
1255 if (need_uptime) {
1256 if (!enough_mtbf_info) {
1257 /* XXXX We should change the rule from
1258 * "use uptime if we don't have mtbf data" to "don't advertise Stable on
1259 * v3 if we don't have enough mtbf data." Or maybe not, since if we ever
1260 * hit a point where we need to reset a lot of authorities at once,
1261 * none of them would be in a position to declare Stable.
1263 long uptime = real_uptime(router, now);
1264 if ((unsigned)uptime < stable_uptime &&
1265 (unsigned)uptime < UPTIME_TO_GUARANTEE_STABLE)
1266 return 1;
1267 } else {
1268 double mtbf =
1269 rep_hist_get_stability(router->cache_info.identity_digest, now);
1270 if (mtbf < stable_mtbf &&
1271 mtbf < MTBF_TO_GUARANTEE_STABLE)
1272 return 1;
1275 if (need_capacity) {
1276 uint32_t bw_kb = dirserv_get_credible_bandwidth_kb(router);
1277 if (bw_kb < fast_bandwidth_kb)
1278 return 1;
1280 return 0;
1283 /** Return true iff <b>router</b> should be assigned the "HSDir" flag.
1285 * Right now this means it advertises support for it, it has a high uptime,
1286 * it's a directory cache, it has the Stable and Fast flags, and it's currently
1287 * considered Running.
1289 * This function needs to be called after router-\>is_running has
1290 * been set.
1292 static int
1293 dirserv_thinks_router_is_hs_dir(const routerinfo_t *router,
1294 const node_t *node, time_t now)
1297 long uptime;
1299 /* If we haven't been running for at least
1300 * get_options()->MinUptimeHidServDirectoryV2 seconds, we can't
1301 * have accurate data telling us a relay has been up for at least
1302 * that long. We also want to allow a bit of slack: Reachability
1303 * tests aren't instant. If we haven't been running long enough,
1304 * trust the relay. */
1306 if (stats_n_seconds_working >
1307 get_options()->MinUptimeHidServDirectoryV2 * 1.1)
1308 uptime = MIN(rep_hist_get_uptime(router->cache_info.identity_digest, now),
1309 real_uptime(router, now));
1310 else
1311 uptime = real_uptime(router, now);
1313 return (router->wants_to_be_hs_dir &&
1314 router->supports_tunnelled_dir_requests &&
1315 node->is_stable && node->is_fast &&
1316 uptime >= get_options()->MinUptimeHidServDirectoryV2 &&
1317 router_is_active(router, node, now));
1320 /** Don't consider routers with less bandwidth than this when computing
1321 * thresholds. */
1322 #define ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER_KB 4
1324 /** Helper for dirserv_compute_performance_thresholds(): Decide whether to
1325 * include a router in our calculations, and return true iff we should; the
1326 * require_mbw parameter is passed in by
1327 * dirserv_compute_performance_thresholds() and controls whether we ever
1328 * count routers with only advertised bandwidths */
1329 static int
1330 router_counts_toward_thresholds(const node_t *node, time_t now,
1331 const digestmap_t *omit_as_sybil,
1332 int require_mbw)
1334 /* Have measured bw? */
1335 int have_mbw =
1336 dirserv_has_measured_bw(node->identity);
1337 uint64_t min_bw_kb = ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER_KB;
1338 const or_options_t *options = get_options();
1340 if (options->TestingTorNetwork) {
1341 min_bw_kb = (int64_t)options->TestingMinExitFlagThreshold / 1000;
1344 return node->ri && router_is_active(node->ri, node, now) &&
1345 !digestmap_get(omit_as_sybil, node->identity) &&
1346 (dirserv_get_credible_bandwidth_kb(node->ri) >= min_bw_kb) &&
1347 (have_mbw || !require_mbw);
1350 /** Look through the routerlist, the Mean Time Between Failure history, and
1351 * the Weighted Fractional Uptime history, and use them to set thresholds for
1352 * the Stable, Fast, and Guard flags. Update the fields stable_uptime,
1353 * stable_mtbf, enough_mtbf_info, guard_wfu, guard_tk, fast_bandwidth,
1354 * guard_bandwidth_including_exits, and guard_bandwidth_excluding_exits.
1356 * Also, set the is_exit flag of each router appropriately. */
1357 static void
1358 dirserv_compute_performance_thresholds(digestmap_t *omit_as_sybil)
1360 int n_active, n_active_nonexit, n_familiar;
1361 uint32_t *uptimes, *bandwidths_kb, *bandwidths_excluding_exits_kb;
1362 long *tks;
1363 double *mtbfs, *wfus;
1364 smartlist_t *nodelist;
1365 time_t now = time(NULL);
1366 const or_options_t *options = get_options();
1368 /* Require mbw? */
1369 int require_mbw =
1370 (routers_with_measured_bw >
1371 options->MinMeasuredBWsForAuthToIgnoreAdvertised) ? 1 : 0;
1373 /* initialize these all here, in case there are no routers */
1374 stable_uptime = 0;
1375 stable_mtbf = 0;
1376 fast_bandwidth_kb = 0;
1377 guard_bandwidth_including_exits_kb = 0;
1378 guard_bandwidth_excluding_exits_kb = 0;
1379 guard_tk = 0;
1380 guard_wfu = 0;
1382 nodelist_assert_ok();
1383 nodelist = nodelist_get_list();
1385 /* Initialize arrays that will hold values for each router. We'll
1386 * sort them and use that to compute thresholds. */
1387 n_active = n_active_nonexit = 0;
1388 /* Uptime for every active router. */
1389 uptimes = tor_calloc(smartlist_len(nodelist), sizeof(uint32_t));
1390 /* Bandwidth for every active router. */
1391 bandwidths_kb = tor_calloc(smartlist_len(nodelist), sizeof(uint32_t));
1392 /* Bandwidth for every active non-exit router. */
1393 bandwidths_excluding_exits_kb =
1394 tor_calloc(smartlist_len(nodelist), sizeof(uint32_t));
1395 /* Weighted mean time between failure for each active router. */
1396 mtbfs = tor_calloc(smartlist_len(nodelist), sizeof(double));
1397 /* Time-known for each active router. */
1398 tks = tor_calloc(smartlist_len(nodelist), sizeof(long));
1399 /* Weighted fractional uptime for each active router. */
1400 wfus = tor_calloc(smartlist_len(nodelist), sizeof(double));
1402 /* Now, fill in the arrays. */
1403 SMARTLIST_FOREACH_BEGIN(nodelist, node_t *, node) {
1404 if (options->BridgeAuthoritativeDir &&
1405 node->ri &&
1406 node->ri->purpose != ROUTER_PURPOSE_BRIDGE)
1407 continue;
1408 if (router_counts_toward_thresholds(node, now, omit_as_sybil,
1409 require_mbw)) {
1410 routerinfo_t *ri = node->ri;
1411 const char *id = node->identity;
1412 uint32_t bw_kb;
1413 /* resolve spurious clang shallow analysis null pointer errors */
1414 tor_assert(ri);
1415 node->is_exit = (!router_exit_policy_rejects_all(ri) &&
1416 exit_policy_is_general_exit(ri->exit_policy));
1417 uptimes[n_active] = (uint32_t)real_uptime(ri, now);
1418 mtbfs[n_active] = rep_hist_get_stability(id, now);
1419 tks [n_active] = rep_hist_get_weighted_time_known(id, now);
1420 bandwidths_kb[n_active] = bw_kb = dirserv_get_credible_bandwidth_kb(ri);
1421 if (!node->is_exit || node->is_bad_exit) {
1422 bandwidths_excluding_exits_kb[n_active_nonexit] = bw_kb;
1423 ++n_active_nonexit;
1425 ++n_active;
1427 } SMARTLIST_FOREACH_END(node);
1429 /* Now, compute thresholds. */
1430 if (n_active) {
1431 /* The median uptime is stable. */
1432 stable_uptime = median_uint32(uptimes, n_active);
1433 /* The median mtbf is stable, if we have enough mtbf info */
1434 stable_mtbf = median_double(mtbfs, n_active);
1435 /* The 12.5th percentile bandwidth is fast. */
1436 fast_bandwidth_kb = find_nth_uint32(bandwidths_kb, n_active, n_active/8);
1437 /* (Now bandwidths is sorted.) */
1438 if (fast_bandwidth_kb < RELAY_REQUIRED_MIN_BANDWIDTH/(2 * 1000))
1439 fast_bandwidth_kb = bandwidths_kb[n_active/4];
1440 guard_bandwidth_including_exits_kb =
1441 third_quartile_uint32(bandwidths_kb, n_active);
1442 guard_tk = find_nth_long(tks, n_active, n_active/8);
1445 if (guard_tk > TIME_KNOWN_TO_GUARANTEE_FAMILIAR)
1446 guard_tk = TIME_KNOWN_TO_GUARANTEE_FAMILIAR;
1449 /* We can vote on a parameter for the minimum and maximum. */
1450 #define ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG 4
1451 int32_t min_fast_kb, max_fast_kb, min_fast, max_fast;
1452 min_fast = networkstatus_get_param(NULL, "FastFlagMinThreshold",
1453 ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG,
1454 ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG,
1455 INT32_MAX);
1456 if (options->TestingTorNetwork) {
1457 min_fast = (int32_t)options->TestingMinFastFlagThreshold;
1459 max_fast = networkstatus_get_param(NULL, "FastFlagMaxThreshold",
1460 INT32_MAX, min_fast, INT32_MAX);
1461 min_fast_kb = min_fast / 1000;
1462 max_fast_kb = max_fast / 1000;
1464 if (fast_bandwidth_kb < (uint32_t)min_fast_kb)
1465 fast_bandwidth_kb = min_fast_kb;
1466 if (fast_bandwidth_kb > (uint32_t)max_fast_kb)
1467 fast_bandwidth_kb = max_fast_kb;
1469 /* Protect sufficiently fast nodes from being pushed out of the set
1470 * of Fast nodes. */
1471 if (options->AuthDirFastGuarantee &&
1472 fast_bandwidth_kb > options->AuthDirFastGuarantee/1000)
1473 fast_bandwidth_kb = (uint32_t)options->AuthDirFastGuarantee/1000;
1475 /* Now that we have a time-known that 7/8 routers are known longer than,
1476 * fill wfus with the wfu of every such "familiar" router. */
1477 n_familiar = 0;
1479 SMARTLIST_FOREACH_BEGIN(nodelist, node_t *, node) {
1480 if (router_counts_toward_thresholds(node, now,
1481 omit_as_sybil, require_mbw)) {
1482 routerinfo_t *ri = node->ri;
1483 const char *id = ri->cache_info.identity_digest;
1484 long tk = rep_hist_get_weighted_time_known(id, now);
1485 if (tk < guard_tk)
1486 continue;
1487 wfus[n_familiar++] = rep_hist_get_weighted_fractional_uptime(id, now);
1489 } SMARTLIST_FOREACH_END(node);
1490 if (n_familiar)
1491 guard_wfu = median_double(wfus, n_familiar);
1492 if (guard_wfu > WFU_TO_GUARANTEE_GUARD)
1493 guard_wfu = WFU_TO_GUARANTEE_GUARD;
1495 enough_mtbf_info = rep_hist_have_measured_enough_stability();
1497 if (n_active_nonexit) {
1498 guard_bandwidth_excluding_exits_kb =
1499 find_nth_uint32(bandwidths_excluding_exits_kb,
1500 n_active_nonexit, n_active_nonexit*3/4);
1503 log_info(LD_DIRSERV,
1504 "Cutoffs: For Stable, %lu sec uptime, %lu sec MTBF. "
1505 "For Fast: %lu kilobytes/sec. "
1506 "For Guard: WFU %.03f%%, time-known %lu sec, "
1507 "and bandwidth %lu or %lu kilobytes/sec. "
1508 "We%s have enough stability data.",
1509 (unsigned long)stable_uptime,
1510 (unsigned long)stable_mtbf,
1511 (unsigned long)fast_bandwidth_kb,
1512 guard_wfu*100,
1513 (unsigned long)guard_tk,
1514 (unsigned long)guard_bandwidth_including_exits_kb,
1515 (unsigned long)guard_bandwidth_excluding_exits_kb,
1516 enough_mtbf_info ? "" : " don't");
1518 tor_free(uptimes);
1519 tor_free(mtbfs);
1520 tor_free(bandwidths_kb);
1521 tor_free(bandwidths_excluding_exits_kb);
1522 tor_free(tks);
1523 tor_free(wfus);
1526 /* Use dirserv_compute_performance_thresholds() to compute the thresholds
1527 * for the status flags, specifically for bridges.
1529 * This is only called by a Bridge Authority from
1530 * networkstatus_getinfo_by_purpose().
1532 void
1533 dirserv_compute_bridge_flag_thresholds(void)
1535 digestmap_t *omit_as_sybil = digestmap_new();
1536 dirserv_compute_performance_thresholds(omit_as_sybil);
1537 digestmap_free(omit_as_sybil, NULL);
1540 /** Measured bandwidth cache entry */
1541 typedef struct mbw_cache_entry_s {
1542 long mbw_kb;
1543 time_t as_of;
1544 } mbw_cache_entry_t;
1546 /** Measured bandwidth cache - keys are identity_digests, values are
1547 * mbw_cache_entry_t *. */
1548 static digestmap_t *mbw_cache = NULL;
1550 /** Store a measured bandwidth cache entry when reading the measured
1551 * bandwidths file. */
1552 STATIC void
1553 dirserv_cache_measured_bw(const measured_bw_line_t *parsed_line,
1554 time_t as_of)
1556 mbw_cache_entry_t *e = NULL;
1558 tor_assert(parsed_line);
1560 /* Allocate a cache if we need */
1561 if (!mbw_cache) mbw_cache = digestmap_new();
1563 /* Check if we have an existing entry */
1564 e = digestmap_get(mbw_cache, parsed_line->node_id);
1565 /* If we do, we can re-use it */
1566 if (e) {
1567 /* Check that we really are newer, and update */
1568 if (as_of > e->as_of) {
1569 e->mbw_kb = parsed_line->bw_kb;
1570 e->as_of = as_of;
1572 } else {
1573 /* We'll have to insert a new entry */
1574 e = tor_malloc(sizeof(*e));
1575 e->mbw_kb = parsed_line->bw_kb;
1576 e->as_of = as_of;
1577 digestmap_set(mbw_cache, parsed_line->node_id, e);
1581 /** Clear and free the measured bandwidth cache */
1582 STATIC void
1583 dirserv_clear_measured_bw_cache(void)
1585 if (mbw_cache) {
1586 /* Free the map and all entries */
1587 digestmap_free(mbw_cache, tor_free_);
1588 mbw_cache = NULL;
1592 /** Scan the measured bandwidth cache and remove expired entries */
1593 STATIC void
1594 dirserv_expire_measured_bw_cache(time_t now)
1597 if (mbw_cache) {
1598 /* Iterate through the cache and check each entry */
1599 DIGESTMAP_FOREACH_MODIFY(mbw_cache, k, mbw_cache_entry_t *, e) {
1600 if (now > e->as_of + MAX_MEASUREMENT_AGE) {
1601 tor_free(e);
1602 MAP_DEL_CURRENT(k);
1604 } DIGESTMAP_FOREACH_END;
1606 /* Check if we cleared the whole thing and free if so */
1607 if (digestmap_size(mbw_cache) == 0) {
1608 digestmap_free(mbw_cache, tor_free_);
1609 mbw_cache = 0;
1614 /** Get the current size of the measured bandwidth cache */
1615 STATIC int
1616 dirserv_get_measured_bw_cache_size(void)
1618 if (mbw_cache) return digestmap_size(mbw_cache);
1619 else return 0;
1622 /** Query the cache by identity digest, return value indicates whether
1623 * we found it. The bw_out and as_of_out pointers receive the cached
1624 * bandwidth value and the time it was cached if not NULL. */
1625 STATIC int
1626 dirserv_query_measured_bw_cache_kb(const char *node_id, long *bw_kb_out,
1627 time_t *as_of_out)
1629 mbw_cache_entry_t *v = NULL;
1630 int rv = 0;
1632 if (mbw_cache && node_id) {
1633 v = digestmap_get(mbw_cache, node_id);
1634 if (v) {
1635 /* Found something */
1636 rv = 1;
1637 if (bw_kb_out) *bw_kb_out = v->mbw_kb;
1638 if (as_of_out) *as_of_out = v->as_of;
1642 return rv;
1645 /** Predicate wrapper for dirserv_query_measured_bw_cache() */
1646 STATIC int
1647 dirserv_has_measured_bw(const char *node_id)
1649 return dirserv_query_measured_bw_cache_kb(node_id, NULL, NULL);
1652 /** Get the best estimate of a router's bandwidth for dirauth purposes,
1653 * preferring measured to advertised values if available. */
1655 static uint32_t
1656 dirserv_get_bandwidth_for_router_kb(const routerinfo_t *ri)
1658 uint32_t bw_kb = 0;
1660 * Yeah, measured bandwidths in measured_bw_line_t are (implicitly
1661 * signed) longs and the ones router_get_advertised_bandwidth() returns
1662 * are uint32_t.
1664 long mbw_kb = 0;
1666 if (ri) {
1668 * * First try to see if we have a measured bandwidth; don't bother with
1669 * as_of_out here, on the theory that a stale measured bandwidth is still
1670 * better to trust than an advertised one.
1672 if (dirserv_query_measured_bw_cache_kb(ri->cache_info.identity_digest,
1673 &mbw_kb, NULL)) {
1674 /* Got one! */
1675 bw_kb = (uint32_t)mbw_kb;
1676 } else {
1677 /* If not, fall back to advertised */
1678 bw_kb = router_get_advertised_bandwidth(ri) / 1000;
1682 return bw_kb;
1685 /** Look through the routerlist, and using the measured bandwidth cache count
1686 * how many measured bandwidths we know. This is used to decide whether we
1687 * ever trust advertised bandwidths for purposes of assigning flags. */
1688 static void
1689 dirserv_count_measured_bws(const smartlist_t *routers)
1691 /* Initialize this first */
1692 routers_with_measured_bw = 0;
1694 /* Iterate over the routerlist and count measured bandwidths */
1695 SMARTLIST_FOREACH_BEGIN(routers, const routerinfo_t *, ri) {
1696 /* Check if we know a measured bandwidth for this one */
1697 if (dirserv_has_measured_bw(ri->cache_info.identity_digest)) {
1698 ++routers_with_measured_bw;
1700 } SMARTLIST_FOREACH_END(ri);
1703 /** Return the bandwidth we believe for assigning flags; prefer measured
1704 * over advertised, and if we have above a threshold quantity of measured
1705 * bandwidths, we don't want to ever give flags to unmeasured routers, so
1706 * return 0. */
1707 static uint32_t
1708 dirserv_get_credible_bandwidth_kb(const routerinfo_t *ri)
1710 int threshold;
1711 uint32_t bw_kb = 0;
1712 long mbw_kb;
1714 tor_assert(ri);
1715 /* Check if we have a measured bandwidth, and check the threshold if not */
1716 if (!(dirserv_query_measured_bw_cache_kb(ri->cache_info.identity_digest,
1717 &mbw_kb, NULL))) {
1718 threshold = get_options()->MinMeasuredBWsForAuthToIgnoreAdvertised;
1719 if (routers_with_measured_bw > threshold) {
1720 /* Return zero for unmeasured bandwidth if we are above threshold */
1721 bw_kb = 0;
1722 } else {
1723 /* Return an advertised bandwidth otherwise */
1724 bw_kb = router_get_advertised_bandwidth_capped(ri) / 1000;
1726 } else {
1727 /* We have the measured bandwidth in mbw */
1728 bw_kb = (uint32_t)mbw_kb;
1731 return bw_kb;
1734 /** Give a statement of our current performance thresholds for inclusion
1735 * in a vote document. */
1736 char *
1737 dirserv_get_flag_thresholds_line(void)
1739 char *result=NULL;
1740 const int measured_threshold =
1741 get_options()->MinMeasuredBWsForAuthToIgnoreAdvertised;
1742 const int enough_measured_bw = routers_with_measured_bw > measured_threshold;
1744 tor_asprintf(&result,
1745 "stable-uptime=%lu stable-mtbf=%lu "
1746 "fast-speed=%lu "
1747 "guard-wfu=%.03f%% guard-tk=%lu "
1748 "guard-bw-inc-exits=%lu guard-bw-exc-exits=%lu "
1749 "enough-mtbf=%d ignoring-advertised-bws=%d",
1750 (unsigned long)stable_uptime,
1751 (unsigned long)stable_mtbf,
1752 (unsigned long)fast_bandwidth_kb*1000,
1753 guard_wfu*100,
1754 (unsigned long)guard_tk,
1755 (unsigned long)guard_bandwidth_including_exits_kb*1000,
1756 (unsigned long)guard_bandwidth_excluding_exits_kb*1000,
1757 enough_mtbf_info ? 1 : 0,
1758 enough_measured_bw ? 1 : 0);
1760 return result;
1763 /** Given a platform string as in a routerinfo_t (possibly null), return a
1764 * newly allocated version string for a networkstatus document, or NULL if the
1765 * platform doesn't give a Tor version. */
1766 static char *
1767 version_from_platform(const char *platform)
1769 if (platform && !strcmpstart(platform, "Tor ")) {
1770 const char *eos = find_whitespace(platform+4);
1771 if (eos && !strcmpstart(eos, " (r")) {
1772 /* XXXX Unify this logic with the other version extraction
1773 * logic in routerparse.c. */
1774 eos = find_whitespace(eos+1);
1776 if (eos) {
1777 return tor_strndup(platform, eos-platform);
1780 return NULL;
1783 /** Helper: write the router-status information in <b>rs</b> into a newly
1784 * allocated character buffer. Use the same format as in network-status
1785 * documents. If <b>version</b> is non-NULL, add a "v" line for the platform.
1786 * Return 0 on success, -1 on failure.
1788 * The format argument has one of the following values:
1789 * NS_V2 - Output an entry suitable for a V2 NS opinion document
1790 * NS_V3_CONSENSUS - Output the first portion of a V3 NS consensus entry
1791 * NS_V3_CONSENSUS_MICRODESC - Output the first portion of a V3 microdesc
1792 * consensus entry.
1793 * NS_V3_VOTE - Output a complete V3 NS vote. If <b>vrs</b> is present,
1794 * it contains additional information for the vote.
1795 * NS_CONTROL_PORT - Output a NS document for the control port
1797 char *
1798 routerstatus_format_entry(const routerstatus_t *rs, const char *version,
1799 const char *protocols,
1800 routerstatus_format_type_t format,
1801 const vote_routerstatus_t *vrs)
1803 char *summary;
1804 char *result = NULL;
1806 char published[ISO_TIME_LEN+1];
1807 char identity64[BASE64_DIGEST_LEN+1];
1808 char digest64[BASE64_DIGEST_LEN+1];
1809 smartlist_t *chunks = smartlist_new();
1811 format_iso_time(published, rs->published_on);
1812 digest_to_base64(identity64, rs->identity_digest);
1813 digest_to_base64(digest64, rs->descriptor_digest);
1815 smartlist_add_asprintf(chunks,
1816 "r %s %s %s%s%s %s %d %d\n",
1817 rs->nickname,
1818 identity64,
1819 (format==NS_V3_CONSENSUS_MICRODESC)?"":digest64,
1820 (format==NS_V3_CONSENSUS_MICRODESC)?"":" ",
1821 published,
1822 fmt_addr32(rs->addr),
1823 (int)rs->or_port,
1824 (int)rs->dir_port);
1826 /* TODO: Maybe we want to pass in what we need to build the rest of
1827 * this here, instead of in the caller. Then we could use the
1828 * networkstatus_type_t values, with an additional control port value
1829 * added -MP */
1831 /* V3 microdesc consensuses don't have "a" lines. */
1832 if (format == NS_V3_CONSENSUS_MICRODESC)
1833 goto done;
1835 /* Possible "a" line. At most one for now. */
1836 if (!tor_addr_is_null(&rs->ipv6_addr)) {
1837 smartlist_add_asprintf(chunks, "a %s\n",
1838 fmt_addrport(&rs->ipv6_addr, rs->ipv6_orport));
1841 if (format == NS_V3_CONSENSUS)
1842 goto done;
1844 smartlist_add_asprintf(chunks,
1845 "s%s%s%s%s%s%s%s%s%s%s\n",
1846 /* These must stay in alphabetical order. */
1847 rs->is_authority?" Authority":"",
1848 rs->is_bad_exit?" BadExit":"",
1849 rs->is_exit?" Exit":"",
1850 rs->is_fast?" Fast":"",
1851 rs->is_possible_guard?" Guard":"",
1852 rs->is_hs_dir?" HSDir":"",
1853 rs->is_flagged_running?" Running":"",
1854 rs->is_stable?" Stable":"",
1855 rs->is_v2_dir?" V2Dir":"",
1856 rs->is_valid?" Valid":"");
1858 /* length of "opt v \n" */
1859 #define V_LINE_OVERHEAD 7
1860 if (version && strlen(version) < MAX_V_LINE_LEN - V_LINE_OVERHEAD) {
1861 smartlist_add_asprintf(chunks, "v %s\n", version);
1863 if (protocols) {
1864 smartlist_add_asprintf(chunks, "pr %s\n", protocols);
1867 if (format != NS_V2) {
1868 const routerinfo_t* desc = router_get_by_id_digest(rs->identity_digest);
1869 uint32_t bw_kb;
1871 if (format != NS_CONTROL_PORT) {
1872 /* Blow up more or less nicely if we didn't get anything or not the
1873 * thing we expected.
1875 if (!desc) {
1876 char id[HEX_DIGEST_LEN+1];
1877 char dd[HEX_DIGEST_LEN+1];
1879 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
1880 base16_encode(dd, sizeof(dd), rs->descriptor_digest, DIGEST_LEN);
1881 log_warn(LD_BUG, "Cannot get any descriptor for %s "
1882 "(wanted descriptor %s).",
1883 id, dd);
1884 goto err;
1887 /* This assert could fire for the control port, because
1888 * it can request NS documents before all descriptors
1889 * have been fetched. Therefore, we only do this test when
1890 * format != NS_CONTROL_PORT. */
1891 if (tor_memneq(desc->cache_info.signed_descriptor_digest,
1892 rs->descriptor_digest,
1893 DIGEST_LEN)) {
1894 char rl_d[HEX_DIGEST_LEN+1];
1895 char rs_d[HEX_DIGEST_LEN+1];
1896 char id[HEX_DIGEST_LEN+1];
1898 base16_encode(rl_d, sizeof(rl_d),
1899 desc->cache_info.signed_descriptor_digest, DIGEST_LEN);
1900 base16_encode(rs_d, sizeof(rs_d), rs->descriptor_digest, DIGEST_LEN);
1901 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
1902 log_err(LD_BUG, "descriptor digest in routerlist does not match "
1903 "the one in routerstatus: %s vs %s "
1904 "(router %s)\n",
1905 rl_d, rs_d, id);
1907 tor_assert(tor_memeq(desc->cache_info.signed_descriptor_digest,
1908 rs->descriptor_digest,
1909 DIGEST_LEN));
1913 if (format == NS_CONTROL_PORT && rs->has_bandwidth) {
1914 bw_kb = rs->bandwidth_kb;
1915 } else {
1916 tor_assert(desc);
1917 bw_kb = router_get_advertised_bandwidth_capped(desc) / 1000;
1919 smartlist_add_asprintf(chunks,
1920 "w Bandwidth=%d", bw_kb);
1922 if (format == NS_V3_VOTE && vrs && vrs->has_measured_bw) {
1923 smartlist_add_asprintf(chunks,
1924 " Measured=%d", vrs->measured_bw_kb);
1926 /* Write down guardfraction information if we have it. */
1927 if (format == NS_V3_VOTE && vrs && vrs->status.has_guardfraction) {
1928 smartlist_add_asprintf(chunks,
1929 " GuardFraction=%d",
1930 vrs->status.guardfraction_percentage);
1933 smartlist_add(chunks, tor_strdup("\n"));
1935 if (desc) {
1936 summary = policy_summarize(desc->exit_policy, AF_INET);
1937 smartlist_add_asprintf(chunks, "p %s\n", summary);
1938 tor_free(summary);
1941 if (format == NS_V3_VOTE && vrs) {
1942 if (tor_mem_is_zero((char*)vrs->ed25519_id, ED25519_PUBKEY_LEN)) {
1943 smartlist_add(chunks, tor_strdup("id ed25519 none\n"));
1944 } else {
1945 char ed_b64[BASE64_DIGEST256_LEN+1];
1946 digest256_to_base64(ed_b64, (const char*)vrs->ed25519_id);
1947 smartlist_add_asprintf(chunks, "id ed25519 %s\n", ed_b64);
1952 done:
1953 result = smartlist_join_strings(chunks, "", 0, NULL);
1955 err:
1956 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
1957 smartlist_free(chunks);
1959 return result;
1962 /** Helper for sorting: compares two routerinfos first by address, and then by
1963 * descending order of "usefulness". (An authority is more useful than a
1964 * non-authority; a running router is more useful than a non-running router;
1965 * and a router with more bandwidth is more useful than one with less.)
1967 static int
1968 compare_routerinfo_by_ip_and_bw_(const void **a, const void **b)
1970 routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
1971 int first_is_auth, second_is_auth;
1972 uint32_t bw_kb_first, bw_kb_second;
1973 const node_t *node_first, *node_second;
1974 int first_is_running, second_is_running;
1976 /* we return -1 if first should appear before second... that is,
1977 * if first is a better router. */
1978 if (first->addr < second->addr)
1979 return -1;
1980 else if (first->addr > second->addr)
1981 return 1;
1983 /* Potentially, this next bit could cause k n lg n memeq calls. But in
1984 * reality, we will almost never get here, since addresses will usually be
1985 * different. */
1987 first_is_auth =
1988 router_digest_is_trusted_dir(first->cache_info.identity_digest);
1989 second_is_auth =
1990 router_digest_is_trusted_dir(second->cache_info.identity_digest);
1992 if (first_is_auth && !second_is_auth)
1993 return -1;
1994 else if (!first_is_auth && second_is_auth)
1995 return 1;
1997 node_first = node_get_by_id(first->cache_info.identity_digest);
1998 node_second = node_get_by_id(second->cache_info.identity_digest);
1999 first_is_running = node_first && node_first->is_running;
2000 second_is_running = node_second && node_second->is_running;
2002 if (first_is_running && !second_is_running)
2003 return -1;
2004 else if (!first_is_running && second_is_running)
2005 return 1;
2007 bw_kb_first = dirserv_get_bandwidth_for_router_kb(first);
2008 bw_kb_second = dirserv_get_bandwidth_for_router_kb(second);
2010 if (bw_kb_first > bw_kb_second)
2011 return -1;
2012 else if (bw_kb_first < bw_kb_second)
2013 return 1;
2015 /* They're equal! Compare by identity digest, so there's a
2016 * deterministic order and we avoid flapping. */
2017 return fast_memcmp(first->cache_info.identity_digest,
2018 second->cache_info.identity_digest,
2019 DIGEST_LEN);
2022 /** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
2023 * whose keys are the identity digests of those routers that we're going to
2024 * exclude for Sybil-like appearance. */
2025 static digestmap_t *
2026 get_possible_sybil_list(const smartlist_t *routers)
2028 const or_options_t *options = get_options();
2029 digestmap_t *omit_as_sybil;
2030 smartlist_t *routers_by_ip = smartlist_new();
2031 uint32_t last_addr;
2032 int addr_count;
2033 /* Allow at most this number of Tor servers on a single IP address, ... */
2034 int max_with_same_addr = options->AuthDirMaxServersPerAddr;
2035 /* ... unless it's a directory authority, in which case allow more. */
2036 int max_with_same_addr_on_authority = options->AuthDirMaxServersPerAuthAddr;
2037 if (max_with_same_addr <= 0)
2038 max_with_same_addr = INT_MAX;
2039 if (max_with_same_addr_on_authority <= 0)
2040 max_with_same_addr_on_authority = INT_MAX;
2042 smartlist_add_all(routers_by_ip, routers);
2043 smartlist_sort(routers_by_ip, compare_routerinfo_by_ip_and_bw_);
2044 omit_as_sybil = digestmap_new();
2046 last_addr = 0;
2047 addr_count = 0;
2048 SMARTLIST_FOREACH_BEGIN(routers_by_ip, routerinfo_t *, ri) {
2049 if (last_addr != ri->addr) {
2050 last_addr = ri->addr;
2051 addr_count = 1;
2052 } else if (++addr_count > max_with_same_addr) {
2053 if (!router_addr_is_trusted_dir(ri->addr) ||
2054 addr_count > max_with_same_addr_on_authority)
2055 digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
2057 } SMARTLIST_FOREACH_END(ri);
2059 smartlist_free(routers_by_ip);
2060 return omit_as_sybil;
2063 /** If there are entries in <b>routers</b> with exactly the same ed25519 keys,
2064 * remove the older one. If they are exactly the same age, remove the one
2065 * with the greater descriptor digest. May alter the order of the list. */
2066 static void
2067 routers_make_ed_keys_unique(smartlist_t *routers)
2069 routerinfo_t *ri2;
2070 digest256map_t *by_ed_key = digest256map_new();
2072 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
2073 ri->omit_from_vote = 0;
2074 if (ri->cache_info.signing_key_cert == NULL)
2075 continue; /* No ed key */
2076 const uint8_t *pk = ri->cache_info.signing_key_cert->signing_key.pubkey;
2077 if ((ri2 = digest256map_get(by_ed_key, pk))) {
2078 /* Duplicate; must omit one. Set the omit_from_vote flag in whichever
2079 * one has the earlier published_on. */
2080 const time_t ri_pub = ri->cache_info.published_on;
2081 const time_t ri2_pub = ri2->cache_info.published_on;
2082 if (ri2_pub < ri_pub ||
2083 (ri2_pub == ri_pub &&
2084 fast_memcmp(ri->cache_info.signed_descriptor_digest,
2085 ri2->cache_info.signed_descriptor_digest,DIGEST_LEN)<0)) {
2086 digest256map_set(by_ed_key, pk, ri);
2087 ri2->omit_from_vote = 1;
2088 } else {
2089 ri->omit_from_vote = 1;
2091 } else {
2092 /* Add to map */
2093 digest256map_set(by_ed_key, pk, ri);
2095 } SMARTLIST_FOREACH_END(ri);
2097 digest256map_free(by_ed_key, NULL);
2099 /* Now remove every router where the omit_from_vote flag got set. */
2100 SMARTLIST_FOREACH_BEGIN(routers, const routerinfo_t *, ri) {
2101 if (ri->omit_from_vote) {
2102 SMARTLIST_DEL_CURRENT(routers, ri);
2104 } SMARTLIST_FOREACH_END(ri);
2107 /** Extract status information from <b>ri</b> and from other authority
2108 * functions and store it in <b>rs</b>>.
2110 * We assume that ri-\>is_running has already been set, e.g. by
2111 * dirserv_set_router_is_running(ri, now);
2113 void
2114 set_routerstatus_from_routerinfo(routerstatus_t *rs,
2115 node_t *node,
2116 routerinfo_t *ri,
2117 time_t now,
2118 int listbadexits)
2120 const or_options_t *options = get_options();
2121 uint32_t routerbw_kb = dirserv_get_credible_bandwidth_kb(ri);
2123 memset(rs, 0, sizeof(routerstatus_t));
2125 rs->is_authority =
2126 router_digest_is_trusted_dir(ri->cache_info.identity_digest);
2128 /* Already set by compute_performance_thresholds. */
2129 rs->is_exit = node->is_exit;
2130 rs->is_stable = node->is_stable =
2131 !dirserv_thinks_router_is_unreliable(now, ri, 1, 0);
2132 rs->is_fast = node->is_fast =
2133 !dirserv_thinks_router_is_unreliable(now, ri, 0, 1);
2134 rs->is_flagged_running = node->is_running; /* computed above */
2136 rs->is_valid = node->is_valid;
2138 if (node->is_fast && node->is_stable &&
2139 ((options->AuthDirGuardBWGuarantee &&
2140 routerbw_kb >= options->AuthDirGuardBWGuarantee/1000) ||
2141 routerbw_kb >= MIN(guard_bandwidth_including_exits_kb,
2142 guard_bandwidth_excluding_exits_kb))) {
2143 long tk = rep_hist_get_weighted_time_known(
2144 node->identity, now);
2145 double wfu = rep_hist_get_weighted_fractional_uptime(
2146 node->identity, now);
2147 rs->is_possible_guard = (wfu >= guard_wfu && tk >= guard_tk) ? 1 : 0;
2148 } else {
2149 rs->is_possible_guard = 0;
2152 rs->is_bad_exit = listbadexits && node->is_bad_exit;
2153 rs->is_hs_dir = node->is_hs_dir =
2154 dirserv_thinks_router_is_hs_dir(ri, node, now);
2156 rs->is_named = rs->is_unnamed = 0;
2158 rs->published_on = ri->cache_info.published_on;
2159 memcpy(rs->identity_digest, node->identity, DIGEST_LEN);
2160 memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest,
2161 DIGEST_LEN);
2162 rs->addr = ri->addr;
2163 strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname));
2164 rs->or_port = ri->or_port;
2165 rs->dir_port = ri->dir_port;
2166 rs->is_v2_dir = ri->supports_tunnelled_dir_requests;
2167 if (options->AuthDirHasIPv6Connectivity == 1 &&
2168 !tor_addr_is_null(&ri->ipv6_addr) &&
2169 node->last_reachable6 >= now - REACHABLE_TIMEOUT) {
2170 /* We're configured as having IPv6 connectivity. There's an IPv6
2171 OR port and it's reachable so copy it to the routerstatus. */
2172 tor_addr_copy(&rs->ipv6_addr, &ri->ipv6_addr);
2173 rs->ipv6_orport = ri->ipv6_orport;
2176 if (options->TestingTorNetwork) {
2177 dirserv_set_routerstatus_testing(rs);
2181 /** Use TestingDirAuthVoteExit, TestingDirAuthVoteGuard, and
2182 * TestingDirAuthVoteHSDir to give out the Exit, Guard, and HSDir flags,
2183 * respectively. But don't set the corresponding node flags.
2184 * Should only be called if TestingTorNetwork is set. */
2185 STATIC void
2186 dirserv_set_routerstatus_testing(routerstatus_t *rs)
2188 const or_options_t *options = get_options();
2190 tor_assert(options->TestingTorNetwork);
2192 if (routerset_contains_routerstatus(options->TestingDirAuthVoteExit,
2193 rs, 0)) {
2194 rs->is_exit = 1;
2195 } else if (options->TestingDirAuthVoteExitIsStrict) {
2196 rs->is_exit = 0;
2199 if (routerset_contains_routerstatus(options->TestingDirAuthVoteGuard,
2200 rs, 0)) {
2201 rs->is_possible_guard = 1;
2202 } else if (options->TestingDirAuthVoteGuardIsStrict) {
2203 rs->is_possible_guard = 0;
2206 if (routerset_contains_routerstatus(options->TestingDirAuthVoteHSDir,
2207 rs, 0)) {
2208 rs->is_hs_dir = 1;
2209 } else if (options->TestingDirAuthVoteHSDirIsStrict) {
2210 rs->is_hs_dir = 0;
2214 /** Routerstatus <b>rs</b> is part of a group of routers that are on
2215 * too narrow an IP-space. Clear out its flags: we don't want people
2216 * using it.
2218 static void
2219 clear_status_flags_on_sybil(routerstatus_t *rs)
2221 rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
2222 rs->is_flagged_running = rs->is_named = rs->is_valid =
2223 rs->is_hs_dir = rs->is_possible_guard = rs->is_bad_exit = 0;
2224 /* FFFF we might want some mechanism to check later on if we
2225 * missed zeroing any flags: it's easy to add a new flag but
2226 * forget to add it to this clause. */
2229 /** The guardfraction of the guard with identity fingerprint <b>guard_id</b>
2230 * is <b>guardfraction_percentage</b>. See if we have a vote routerstatus for
2231 * this guard in <b>vote_routerstatuses</b>, and if we do, register the
2232 * information to it.
2234 * Return 1 if we applied the information and 0 if we couldn't find a
2235 * matching guard.
2237 * Requires that <b>vote_routerstatuses</b> be sorted.
2239 static int
2240 guardfraction_line_apply(const char *guard_id,
2241 uint32_t guardfraction_percentage,
2242 smartlist_t *vote_routerstatuses)
2244 vote_routerstatus_t *vrs = NULL;
2246 tor_assert(vote_routerstatuses);
2248 vrs = smartlist_bsearch(vote_routerstatuses, guard_id,
2249 compare_digest_to_vote_routerstatus_entry);
2251 if (!vrs) {
2252 return 0;
2255 vrs->status.has_guardfraction = 1;
2256 vrs->status.guardfraction_percentage = guardfraction_percentage;
2258 return 1;
2261 /* Given a guard line from a guardfraction file, parse it and register
2262 * its information to <b>vote_routerstatuses</b>.
2264 * Return:
2265 * * 1 if the line was proper and its information got registered.
2266 * * 0 if the line was proper but no currently active guard was found
2267 * to register the guardfraction information to.
2268 * * -1 if the line could not be parsed and set <b>err_msg</b> to a
2269 newly allocated string containing the error message.
2271 static int
2272 guardfraction_file_parse_guard_line(const char *guard_line,
2273 smartlist_t *vote_routerstatuses,
2274 char **err_msg)
2276 char guard_id[DIGEST_LEN];
2277 uint32_t guardfraction;
2278 char *inputs_tmp = NULL;
2279 int num_ok = 1;
2281 smartlist_t *sl = smartlist_new();
2282 int retval = -1;
2284 tor_assert(err_msg);
2286 /* guard_line should contain something like this:
2287 <hex digest> <guardfraction> <appearances> */
2288 smartlist_split_string(sl, guard_line, " ",
2289 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
2290 if (smartlist_len(sl) < 3) {
2291 tor_asprintf(err_msg, "bad line '%s'", guard_line);
2292 goto done;
2295 inputs_tmp = smartlist_get(sl, 0);
2296 if (strlen(inputs_tmp) != HEX_DIGEST_LEN ||
2297 base16_decode(guard_id, DIGEST_LEN,
2298 inputs_tmp, HEX_DIGEST_LEN) != DIGEST_LEN) {
2299 tor_asprintf(err_msg, "bad digest '%s'", inputs_tmp);
2300 goto done;
2303 inputs_tmp = smartlist_get(sl, 1);
2304 /* Guardfraction is an integer in [0, 100]. */
2305 guardfraction =
2306 (uint32_t) tor_parse_long(inputs_tmp, 10, 0, 100, &num_ok, NULL);
2307 if (!num_ok) {
2308 tor_asprintf(err_msg, "wrong percentage '%s'", inputs_tmp);
2309 goto done;
2312 /* If routerstatuses were provided, apply this info to actual routers. */
2313 if (vote_routerstatuses) {
2314 retval = guardfraction_line_apply(guard_id, guardfraction,
2315 vote_routerstatuses);
2316 } else {
2317 retval = 0; /* If we got this far, line was correctly formatted. */
2320 done:
2322 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
2323 smartlist_free(sl);
2325 return retval;
2328 /** Given an inputs line from a guardfraction file, parse it and
2329 * register its information to <b>total_consensuses</b> and
2330 * <b>total_days</b>.
2332 * Return 0 if it parsed well. Return -1 if there was an error, and
2333 * set <b>err_msg</b> to a newly allocated string containing the
2334 * error message.
2336 static int
2337 guardfraction_file_parse_inputs_line(const char *inputs_line,
2338 int *total_consensuses,
2339 int *total_days,
2340 char **err_msg)
2342 int retval = -1;
2343 char *inputs_tmp = NULL;
2344 int num_ok = 1;
2345 smartlist_t *sl = smartlist_new();
2347 tor_assert(err_msg);
2349 /* Second line is inputs information:
2350 * n-inputs <total_consensuses> <total_days>. */
2351 smartlist_split_string(sl, inputs_line, " ",
2352 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
2353 if (smartlist_len(sl) < 2) {
2354 tor_asprintf(err_msg, "incomplete line '%s'", inputs_line);
2355 goto done;
2358 inputs_tmp = smartlist_get(sl, 0);
2359 *total_consensuses =
2360 (int) tor_parse_long(inputs_tmp, 10, 0, INT_MAX, &num_ok, NULL);
2361 if (!num_ok) {
2362 tor_asprintf(err_msg, "unparseable consensus '%s'", inputs_tmp);
2363 goto done;
2366 inputs_tmp = smartlist_get(sl, 1);
2367 *total_days =
2368 (int) tor_parse_long(inputs_tmp, 10, 0, INT_MAX, &num_ok, NULL);
2369 if (!num_ok) {
2370 tor_asprintf(err_msg, "unparseable days '%s'", inputs_tmp);
2371 goto done;
2374 retval = 0;
2376 done:
2377 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
2378 smartlist_free(sl);
2380 return retval;
2383 /* Maximum age of a guardfraction file that we are willing to accept. */
2384 #define MAX_GUARDFRACTION_FILE_AGE (7*24*60*60) /* approx a week */
2386 /** Static strings of guardfraction files. */
2387 #define GUARDFRACTION_DATE_STR "written-at"
2388 #define GUARDFRACTION_INPUTS "n-inputs"
2389 #define GUARDFRACTION_GUARD "guard-seen"
2390 #define GUARDFRACTION_VERSION "guardfraction-file-version"
2392 /** Given a guardfraction file in a string, parse it and register the
2393 * guardfraction information to the provided vote routerstatuses.
2395 * This is the rough format of the guardfraction file:
2397 * guardfraction-file-version 1
2398 * written-at <date and time>
2399 * n-inputs <number of consesuses parsed> <number of days considered>
2401 * guard-seen <fpr 1> <guardfraction percentage> <consensus appearances>
2402 * guard-seen <fpr 2> <guardfraction percentage> <consensus appearances>
2403 * guard-seen <fpr 3> <guardfraction percentage> <consensus appearances>
2404 * guard-seen <fpr 4> <guardfraction percentage> <consensus appearances>
2405 * guard-seen <fpr 5> <guardfraction percentage> <consensus appearances>
2406 * ...
2408 * Return -1 if the parsing failed and 0 if it went smoothly. Parsing
2409 * should tolerate errors in all lines but the written-at header.
2411 STATIC int
2412 dirserv_read_guardfraction_file_from_str(const char *guardfraction_file_str,
2413 smartlist_t *vote_routerstatuses)
2415 config_line_t *front=NULL, *line;
2416 int ret_tmp;
2417 int retval = -1;
2418 int current_line_n = 0; /* line counter for better log messages */
2420 /* Guardfraction info to be parsed */
2421 int total_consensuses = 0;
2422 int total_days = 0;
2424 /* Stats */
2425 int guards_read_n = 0;
2426 int guards_applied_n = 0;
2428 /* Parse file and split it in lines */
2429 ret_tmp = config_get_lines(guardfraction_file_str, &front, 0);
2430 if (ret_tmp < 0) {
2431 log_warn(LD_CONFIG, "Error reading from guardfraction file");
2432 goto done;
2435 /* Sort routerstatuses (needed later when applying guardfraction info) */
2436 if (vote_routerstatuses)
2437 smartlist_sort(vote_routerstatuses, compare_vote_routerstatus_entries);
2439 for (line = front; line; line=line->next) {
2440 current_line_n++;
2442 if (!strcmp(line->key, GUARDFRACTION_VERSION)) {
2443 int num_ok = 1;
2444 unsigned int version;
2446 version =
2447 (unsigned int) tor_parse_long(line->value,
2448 10, 0, INT_MAX, &num_ok, NULL);
2450 if (!num_ok || version != 1) {
2451 log_warn(LD_GENERAL, "Got unknown guardfraction version %d.", version);
2452 goto done;
2454 } else if (!strcmp(line->key, GUARDFRACTION_DATE_STR)) {
2455 time_t file_written_at;
2456 time_t now = time(NULL);
2458 /* First line is 'written-at <date>' */
2459 if (parse_iso_time(line->value, &file_written_at) < 0) {
2460 log_warn(LD_CONFIG, "Guardfraction:%d: Bad date '%s'. Ignoring",
2461 current_line_n, line->value);
2462 goto done; /* don't tolerate failure here. */
2464 if (file_written_at < now - MAX_GUARDFRACTION_FILE_AGE) {
2465 log_warn(LD_CONFIG, "Guardfraction:%d: was written very long ago '%s'",
2466 current_line_n, line->value);
2467 goto done; /* don't tolerate failure here. */
2469 } else if (!strcmp(line->key, GUARDFRACTION_INPUTS)) {
2470 char *err_msg = NULL;
2472 if (guardfraction_file_parse_inputs_line(line->value,
2473 &total_consensuses,
2474 &total_days,
2475 &err_msg) < 0) {
2476 log_warn(LD_CONFIG, "Guardfraction:%d: %s",
2477 current_line_n, err_msg);
2478 tor_free(err_msg);
2479 continue;
2482 } else if (!strcmp(line->key, GUARDFRACTION_GUARD)) {
2483 char *err_msg = NULL;
2485 ret_tmp = guardfraction_file_parse_guard_line(line->value,
2486 vote_routerstatuses,
2487 &err_msg);
2488 if (ret_tmp < 0) { /* failed while parsing the guard line */
2489 log_warn(LD_CONFIG, "Guardfraction:%d: %s",
2490 current_line_n, err_msg);
2491 tor_free(err_msg);
2492 continue;
2495 /* Successfully parsed guard line. Check if it was applied properly. */
2496 guards_read_n++;
2497 if (ret_tmp > 0) {
2498 guards_applied_n++;
2500 } else {
2501 log_warn(LD_CONFIG, "Unknown guardfraction line %d (%s %s)",
2502 current_line_n, line->key, line->value);
2506 retval = 0;
2508 log_info(LD_CONFIG,
2509 "Successfully parsed guardfraction file with %d consensuses over "
2510 "%d days. Parsed %d nodes and applied %d of them%s.",
2511 total_consensuses, total_days, guards_read_n, guards_applied_n,
2512 vote_routerstatuses ? "" : " (no routerstatus provided)" );
2514 done:
2515 config_free_lines(front);
2517 if (retval < 0) {
2518 return retval;
2519 } else {
2520 return guards_read_n;
2524 /** Read a guardfraction file at <b>fname</b> and load all its
2525 * information to <b>vote_routerstatuses</b>. */
2527 dirserv_read_guardfraction_file(const char *fname,
2528 smartlist_t *vote_routerstatuses)
2530 char *guardfraction_file_str;
2532 /* Read file to a string */
2533 guardfraction_file_str = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
2534 if (!guardfraction_file_str) {
2535 log_warn(LD_FS, "Cannot open guardfraction file '%s'. Failing.", fname);
2536 return -1;
2539 return dirserv_read_guardfraction_file_from_str(guardfraction_file_str,
2540 vote_routerstatuses);
2544 * Helper function to parse out a line in the measured bandwidth file
2545 * into a measured_bw_line_t output structure. Returns -1 on failure
2546 * or 0 on success.
2548 STATIC int
2549 measured_bw_line_parse(measured_bw_line_t *out, const char *orig_line)
2551 char *line = tor_strdup(orig_line);
2552 char *cp = line;
2553 int got_bw = 0;
2554 int got_node_id = 0;
2555 char *strtok_state; /* lame sauce d'jour */
2556 cp = tor_strtok_r(cp, " \t", &strtok_state);
2558 if (!cp) {
2559 log_warn(LD_DIRSERV, "Invalid line in bandwidth file: %s",
2560 escaped(orig_line));
2561 tor_free(line);
2562 return -1;
2565 if (orig_line[strlen(orig_line)-1] != '\n') {
2566 log_warn(LD_DIRSERV, "Incomplete line in bandwidth file: %s",
2567 escaped(orig_line));
2568 tor_free(line);
2569 return -1;
2572 do {
2573 if (strcmpstart(cp, "bw=") == 0) {
2574 int parse_ok = 0;
2575 char *endptr;
2576 if (got_bw) {
2577 log_warn(LD_DIRSERV, "Double bw= in bandwidth file line: %s",
2578 escaped(orig_line));
2579 tor_free(line);
2580 return -1;
2582 cp+=strlen("bw=");
2584 out->bw_kb = tor_parse_long(cp, 0, 0, LONG_MAX, &parse_ok, &endptr);
2585 if (!parse_ok || (*endptr && !TOR_ISSPACE(*endptr))) {
2586 log_warn(LD_DIRSERV, "Invalid bandwidth in bandwidth file line: %s",
2587 escaped(orig_line));
2588 tor_free(line);
2589 return -1;
2591 got_bw=1;
2592 } else if (strcmpstart(cp, "node_id=$") == 0) {
2593 if (got_node_id) {
2594 log_warn(LD_DIRSERV, "Double node_id= in bandwidth file line: %s",
2595 escaped(orig_line));
2596 tor_free(line);
2597 return -1;
2599 cp+=strlen("node_id=$");
2601 if (strlen(cp) != HEX_DIGEST_LEN ||
2602 base16_decode(out->node_id, DIGEST_LEN,
2603 cp, HEX_DIGEST_LEN) != DIGEST_LEN) {
2604 log_warn(LD_DIRSERV, "Invalid node_id in bandwidth file line: %s",
2605 escaped(orig_line));
2606 tor_free(line);
2607 return -1;
2609 strlcpy(out->node_hex, cp, sizeof(out->node_hex));
2610 got_node_id=1;
2612 } while ((cp = tor_strtok_r(NULL, " \t", &strtok_state)));
2614 if (got_bw && got_node_id) {
2615 tor_free(line);
2616 return 0;
2617 } else {
2618 log_warn(LD_DIRSERV, "Incomplete line in bandwidth file: %s",
2619 escaped(orig_line));
2620 tor_free(line);
2621 return -1;
2626 * Helper function to apply a parsed measurement line to a list
2627 * of bandwidth statuses. Returns true if a line is found,
2628 * false otherwise.
2630 STATIC int
2631 measured_bw_line_apply(measured_bw_line_t *parsed_line,
2632 smartlist_t *routerstatuses)
2634 vote_routerstatus_t *rs = NULL;
2635 if (!routerstatuses)
2636 return 0;
2638 rs = smartlist_bsearch(routerstatuses, parsed_line->node_id,
2639 compare_digest_to_vote_routerstatus_entry);
2641 if (rs) {
2642 rs->has_measured_bw = 1;
2643 rs->measured_bw_kb = (uint32_t)parsed_line->bw_kb;
2644 } else {
2645 log_info(LD_DIRSERV, "Node ID %s not found in routerstatus list",
2646 parsed_line->node_hex);
2649 return rs != NULL;
2653 * Read the measured bandwidth file and apply it to the list of
2654 * vote_routerstatus_t. Returns -1 on error, 0 otherwise.
2657 dirserv_read_measured_bandwidths(const char *from_file,
2658 smartlist_t *routerstatuses)
2660 char line[512];
2661 FILE *fp = tor_fopen_cloexec(from_file, "r");
2662 int applied_lines = 0;
2663 time_t file_time, now;
2664 int ok;
2666 if (fp == NULL) {
2667 log_warn(LD_CONFIG, "Can't open bandwidth file at configured location: %s",
2668 from_file);
2669 return -1;
2672 if (!fgets(line, sizeof(line), fp)
2673 || !strlen(line) || line[strlen(line)-1] != '\n') {
2674 log_warn(LD_DIRSERV, "Long or truncated time in bandwidth file: %s",
2675 escaped(line));
2676 fclose(fp);
2677 return -1;
2680 line[strlen(line)-1] = '\0';
2681 file_time = (time_t)tor_parse_ulong(line, 10, 0, ULONG_MAX, &ok, NULL);
2682 if (!ok) {
2683 log_warn(LD_DIRSERV, "Non-integer time in bandwidth file: %s",
2684 escaped(line));
2685 fclose(fp);
2686 return -1;
2689 now = time(NULL);
2690 if ((now - file_time) > MAX_MEASUREMENT_AGE) {
2691 log_warn(LD_DIRSERV, "Bandwidth measurement file stale. Age: %u",
2692 (unsigned)(time(NULL) - file_time));
2693 fclose(fp);
2694 return -1;
2697 if (routerstatuses)
2698 smartlist_sort(routerstatuses, compare_vote_routerstatus_entries);
2700 while (!feof(fp)) {
2701 measured_bw_line_t parsed_line;
2702 if (fgets(line, sizeof(line), fp) && strlen(line)) {
2703 if (measured_bw_line_parse(&parsed_line, line) != -1) {
2704 /* Also cache the line for dirserv_get_bandwidth_for_router() */
2705 dirserv_cache_measured_bw(&parsed_line, file_time);
2706 if (measured_bw_line_apply(&parsed_line, routerstatuses) > 0)
2707 applied_lines++;
2712 /* Now would be a nice time to clean the cache, too */
2713 dirserv_expire_measured_bw_cache(now);
2715 fclose(fp);
2716 log_info(LD_DIRSERV,
2717 "Bandwidth measurement file successfully read. "
2718 "Applied %d measurements.", applied_lines);
2719 return 0;
2722 /** Return a new networkstatus_t* containing our current opinion. (For v3
2723 * authorities) */
2724 networkstatus_t *
2725 dirserv_generate_networkstatus_vote_obj(crypto_pk_t *private_key,
2726 authority_cert_t *cert)
2728 const or_options_t *options = get_options();
2729 networkstatus_t *v3_out = NULL;
2730 uint32_t addr;
2731 char *hostname = NULL, *client_versions = NULL, *server_versions = NULL;
2732 const char *contact;
2733 smartlist_t *routers, *routerstatuses;
2734 char identity_digest[DIGEST_LEN];
2735 char signing_key_digest[DIGEST_LEN];
2736 int listbadexits = options->AuthDirListBadExits;
2737 routerlist_t *rl = router_get_routerlist();
2738 time_t now = time(NULL);
2739 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2740 networkstatus_voter_info_t *voter = NULL;
2741 vote_timing_t timing;
2742 digestmap_t *omit_as_sybil = NULL;
2743 const int vote_on_reachability = running_long_enough_to_decide_unreachable();
2744 smartlist_t *microdescriptors = NULL;
2746 tor_assert(private_key);
2747 tor_assert(cert);
2749 if (crypto_pk_get_digest(private_key, signing_key_digest)<0) {
2750 log_err(LD_BUG, "Error computing signing key digest");
2751 return NULL;
2753 if (crypto_pk_get_digest(cert->identity_key, identity_digest)<0) {
2754 log_err(LD_BUG, "Error computing identity key digest");
2755 return NULL;
2757 if (resolve_my_address(LOG_WARN, options, &addr, NULL, &hostname)<0) {
2758 log_warn(LD_NET, "Couldn't resolve my hostname");
2759 return NULL;
2761 if (!hostname || !strchr(hostname, '.')) {
2762 tor_free(hostname);
2763 hostname = tor_dup_ip(addr);
2766 if (options->VersioningAuthoritativeDir) {
2767 client_versions = format_versions_list(options->RecommendedClientVersions);
2768 server_versions = format_versions_list(options->RecommendedServerVersions);
2771 contact = get_options()->ContactInfo;
2772 if (!contact)
2773 contact = "(none)";
2776 * Do this so dirserv_compute_performance_thresholds() and
2777 * set_routerstatus_from_routerinfo() see up-to-date bandwidth info.
2779 if (options->V3BandwidthsFile) {
2780 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
2781 } else {
2783 * No bandwidths file; clear the measured bandwidth cache in case we had
2784 * one last time around.
2786 if (dirserv_get_measured_bw_cache_size() > 0) {
2787 dirserv_clear_measured_bw_cache();
2791 /* precompute this part, since we need it to decide what "stable"
2792 * means. */
2793 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2794 dirserv_set_router_is_running(ri, now);
2797 routers = smartlist_new();
2798 smartlist_add_all(routers, rl->routers);
2799 routers_make_ed_keys_unique(routers);
2800 /* After this point, don't use rl->routers; use 'routers' instead. */
2801 routers_sort_by_identity(routers);
2802 omit_as_sybil = get_possible_sybil_list(routers);
2804 DIGESTMAP_FOREACH(omit_as_sybil, sybil_id, void *, ignore) {
2805 (void) ignore;
2806 rep_hist_make_router_pessimal(sybil_id, now);
2807 } DIGESTMAP_FOREACH_END;
2809 /* Count how many have measured bandwidths so we know how to assign flags;
2810 * this must come before dirserv_compute_performance_thresholds() */
2811 dirserv_count_measured_bws(routers);
2813 dirserv_compute_performance_thresholds(omit_as_sybil);
2815 routerstatuses = smartlist_new();
2816 microdescriptors = smartlist_new();
2818 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
2819 if (ri->cache_info.published_on >= cutoff) {
2820 routerstatus_t *rs;
2821 vote_routerstatus_t *vrs;
2822 node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
2823 if (!node)
2824 continue;
2826 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
2827 rs = &vrs->status;
2828 set_routerstatus_from_routerinfo(rs, node, ri, now,
2829 listbadexits);
2831 if (ri->cache_info.signing_key_cert) {
2832 memcpy(vrs->ed25519_id,
2833 ri->cache_info.signing_key_cert->signing_key.pubkey,
2834 ED25519_PUBKEY_LEN);
2837 if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
2838 clear_status_flags_on_sybil(rs);
2840 if (!vote_on_reachability)
2841 rs->is_flagged_running = 0;
2843 vrs->version = version_from_platform(ri->platform);
2844 if (ri->protocol_list) {
2845 vrs->protocols = tor_strdup(ri->protocol_list);
2846 } else {
2847 vrs->protocols = tor_strdup(
2848 protover_compute_for_old_tor(vrs->version));
2850 vrs->microdesc = dirvote_format_all_microdesc_vote_lines(ri, now,
2851 microdescriptors);
2853 smartlist_add(routerstatuses, vrs);
2855 } SMARTLIST_FOREACH_END(ri);
2858 smartlist_t *added =
2859 microdescs_add_list_to_cache(get_microdesc_cache(),
2860 microdescriptors, SAVED_NOWHERE, 0);
2861 smartlist_free(added);
2862 smartlist_free(microdescriptors);
2865 smartlist_free(routers);
2866 digestmap_free(omit_as_sybil, NULL);
2868 /* Apply guardfraction information to routerstatuses. */
2869 if (options->GuardfractionFile) {
2870 dirserv_read_guardfraction_file(options->GuardfractionFile,
2871 routerstatuses);
2874 /* This pass through applies the measured bw lines to the routerstatuses */
2875 if (options->V3BandwidthsFile) {
2876 dirserv_read_measured_bandwidths(options->V3BandwidthsFile,
2877 routerstatuses);
2878 } else {
2880 * No bandwidths file; clear the measured bandwidth cache in case we had
2881 * one last time around.
2883 if (dirserv_get_measured_bw_cache_size() > 0) {
2884 dirserv_clear_measured_bw_cache();
2888 v3_out = tor_malloc_zero(sizeof(networkstatus_t));
2890 v3_out->type = NS_TYPE_VOTE;
2891 dirvote_get_preferred_voting_intervals(&timing);
2892 v3_out->published = now;
2894 char tbuf[ISO_TIME_LEN+1];
2895 networkstatus_t *current_consensus =
2896 networkstatus_get_live_consensus(now);
2897 long last_consensus_interval; /* only used to pick a valid_after */
2898 if (current_consensus)
2899 last_consensus_interval = current_consensus->fresh_until -
2900 current_consensus->valid_after;
2901 else
2902 last_consensus_interval = options->TestingV3AuthInitialVotingInterval;
2903 v3_out->valid_after =
2904 dirvote_get_start_of_next_interval(now, (int)last_consensus_interval,
2905 options->TestingV3AuthVotingStartOffset);
2906 format_iso_time(tbuf, v3_out->valid_after);
2907 log_notice(LD_DIR,"Choosing valid-after time in vote as %s: "
2908 "consensus_set=%d, last_interval=%d",
2909 tbuf, current_consensus?1:0, (int)last_consensus_interval);
2911 v3_out->fresh_until = v3_out->valid_after + timing.vote_interval;
2912 v3_out->valid_until = v3_out->valid_after +
2913 (timing.vote_interval * timing.n_intervals_valid);
2914 v3_out->vote_seconds = timing.vote_delay;
2915 v3_out->dist_seconds = timing.dist_delay;
2916 tor_assert(v3_out->vote_seconds > 0);
2917 tor_assert(v3_out->dist_seconds > 0);
2918 tor_assert(timing.n_intervals_valid > 0);
2920 v3_out->client_versions = client_versions;
2921 v3_out->server_versions = server_versions;
2923 /* These are hardwired, to avoid disaster. */
2924 v3_out->recommended_relay_protocols =
2925 tor_strdup("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 "
2926 "Link=4 LinkAuth=1 Microdesc=1-2 Relay=2");
2927 v3_out->recommended_client_protocols =
2928 tor_strdup("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 "
2929 "Link=4 LinkAuth=1 Microdesc=1-2 Relay=2");
2930 v3_out->required_client_protocols =
2931 tor_strdup("Cons=1-2 Desc=1-2 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 "
2932 "Link=4 LinkAuth=1 Microdesc=1-2 Relay=2");
2933 v3_out->required_relay_protocols =
2934 tor_strdup("Cons=1 Desc=1 DirCache=1 HSDir=1 HSIntro=3 HSRend=1 "
2935 "Link=3-4 LinkAuth=1 Microdesc=1 Relay=1-2");
2937 v3_out->package_lines = smartlist_new();
2939 config_line_t *cl;
2940 for (cl = get_options()->RecommendedPackages; cl; cl = cl->next) {
2941 if (validate_recommended_package_line(cl->value))
2942 smartlist_add(v3_out->package_lines, tor_strdup(cl->value));
2946 v3_out->known_flags = smartlist_new();
2947 smartlist_split_string(v3_out->known_flags,
2948 "Authority Exit Fast Guard Stable V2Dir Valid HSDir",
2949 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2950 if (vote_on_reachability)
2951 smartlist_add(v3_out->known_flags, tor_strdup("Running"));
2952 if (listbadexits)
2953 smartlist_add(v3_out->known_flags, tor_strdup("BadExit"));
2954 smartlist_sort_strings(v3_out->known_flags);
2956 if (options->ConsensusParams) {
2957 v3_out->net_params = smartlist_new();
2958 smartlist_split_string(v3_out->net_params,
2959 options->ConsensusParams, NULL, 0, 0);
2960 smartlist_sort_strings(v3_out->net_params);
2963 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
2964 voter->nickname = tor_strdup(options->Nickname);
2965 memcpy(voter->identity_digest, identity_digest, DIGEST_LEN);
2966 voter->sigs = smartlist_new();
2967 voter->address = hostname;
2968 voter->addr = addr;
2969 voter->dir_port = router_get_advertised_dir_port(options, 0);
2970 voter->or_port = router_get_advertised_or_port(options);
2971 voter->contact = tor_strdup(contact);
2972 if (options->V3AuthUseLegacyKey) {
2973 authority_cert_t *c = get_my_v3_legacy_cert();
2974 if (c) {
2975 if (crypto_pk_get_digest(c->identity_key, voter->legacy_id_digest)) {
2976 log_warn(LD_BUG, "Unable to compute digest of legacy v3 identity key");
2977 memset(voter->legacy_id_digest, 0, DIGEST_LEN);
2982 v3_out->voters = smartlist_new();
2983 smartlist_add(v3_out->voters, voter);
2984 v3_out->cert = authority_cert_dup(cert);
2985 v3_out->routerstatus_list = routerstatuses;
2986 /* Note: networkstatus_digest is unset; it won't get set until we actually
2987 * format the vote. */
2989 return v3_out;
2992 /** As dirserv_get_routerdescs(), but instead of getting signed_descriptor_t
2993 * pointers, adds copies of digests to fps_out, and doesn't use the
2994 * /tor/server/ prefix. For a /d/ request, adds descriptor digests; for other
2995 * requests, adds identity digests.
2998 dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
2999 const char **msg, int for_unencrypted_conn,
3000 int is_extrainfo)
3002 int by_id = 1;
3003 *msg = NULL;
3005 if (!strcmp(key, "all")) {
3006 routerlist_t *rl = router_get_routerlist();
3007 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
3008 smartlist_add(fps_out,
3009 tor_memdup(r->cache_info.identity_digest, DIGEST_LEN)));
3010 /* Treat "all" requests as if they were unencrypted */
3011 for_unencrypted_conn = 1;
3012 } else if (!strcmp(key, "authority")) {
3013 const routerinfo_t *ri = router_get_my_routerinfo();
3014 if (ri)
3015 smartlist_add(fps_out,
3016 tor_memdup(ri->cache_info.identity_digest, DIGEST_LEN));
3017 } else if (!strcmpstart(key, "d/")) {
3018 by_id = 0;
3019 key += strlen("d/");
3020 dir_split_resource_into_fingerprints(key, fps_out, NULL,
3021 DSR_HEX|DSR_SORT_UNIQ);
3022 } else if (!strcmpstart(key, "fp/")) {
3023 key += strlen("fp/");
3024 dir_split_resource_into_fingerprints(key, fps_out, NULL,
3025 DSR_HEX|DSR_SORT_UNIQ);
3026 } else {
3027 *msg = "Key not recognized";
3028 return -1;
3031 if (for_unencrypted_conn) {
3032 /* Remove anything that insists it not be sent unencrypted. */
3033 SMARTLIST_FOREACH_BEGIN(fps_out, char *, cp) {
3034 const signed_descriptor_t *sd;
3035 if (by_id)
3036 sd = get_signed_descriptor_by_fp(cp,is_extrainfo,0);
3037 else if (is_extrainfo)
3038 sd = extrainfo_get_by_descriptor_digest(cp);
3039 else
3040 sd = router_get_by_descriptor_digest(cp);
3041 if (sd && !sd->send_unencrypted) {
3042 tor_free(cp);
3043 SMARTLIST_DEL_CURRENT(fps_out, cp);
3045 } SMARTLIST_FOREACH_END(cp);
3048 if (!smartlist_len(fps_out)) {
3049 *msg = "Servers unavailable";
3050 return -1;
3052 return 0;
3055 /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
3056 * <b>key</b>. The key should be either
3057 * - "/tor/server/authority" for our own routerinfo;
3058 * - "/tor/server/all" for all the routerinfos we have, concatenated;
3059 * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
3060 * hex identity digests; or
3061 * - "/tor/server/d/D" where D is a plus-separated sequence
3062 * of server descriptor digests, in hex.
3064 * Return 0 if we found some matching descriptors, or -1 if we do not
3065 * have any descriptors, no matching descriptors, or if we did not
3066 * recognize the key (URL).
3067 * If -1 is returned *<b>msg</b> will be set to an appropriate error
3068 * message.
3070 * XXXX rename this function. It's only called from the controller.
3071 * XXXX in fact, refactor this function, merging as much as possible.
3074 dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
3075 const char **msg)
3077 *msg = NULL;
3079 if (!strcmp(key, "/tor/server/all")) {
3080 routerlist_t *rl = router_get_routerlist();
3081 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
3082 smartlist_add(descs_out, &(r->cache_info)));
3083 } else if (!strcmp(key, "/tor/server/authority")) {
3084 const routerinfo_t *ri = router_get_my_routerinfo();
3085 if (ri)
3086 smartlist_add(descs_out, (void*) &(ri->cache_info));
3087 } else if (!strcmpstart(key, "/tor/server/d/")) {
3088 smartlist_t *digests = smartlist_new();
3089 key += strlen("/tor/server/d/");
3090 dir_split_resource_into_fingerprints(key, digests, NULL,
3091 DSR_HEX|DSR_SORT_UNIQ);
3092 SMARTLIST_FOREACH(digests, const char *, d,
3094 signed_descriptor_t *sd = router_get_by_descriptor_digest(d);
3095 if (sd)
3096 smartlist_add(descs_out,sd);
3098 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
3099 smartlist_free(digests);
3100 } else if (!strcmpstart(key, "/tor/server/fp/")) {
3101 smartlist_t *digests = smartlist_new();
3102 time_t cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
3103 key += strlen("/tor/server/fp/");
3104 dir_split_resource_into_fingerprints(key, digests, NULL,
3105 DSR_HEX|DSR_SORT_UNIQ);
3106 SMARTLIST_FOREACH_BEGIN(digests, const char *, d) {
3107 if (router_digest_is_me(d)) {
3108 /* calling router_get_my_routerinfo() to make sure it exists */
3109 const routerinfo_t *ri = router_get_my_routerinfo();
3110 if (ri)
3111 smartlist_add(descs_out, (void*) &(ri->cache_info));
3112 } else {
3113 const routerinfo_t *ri = router_get_by_id_digest(d);
3114 /* Don't actually serve a descriptor that everyone will think is
3115 * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
3116 * Tors from downloading descriptors that they will throw away.
3118 if (ri && ri->cache_info.published_on > cutoff)
3119 smartlist_add(descs_out, (void*) &(ri->cache_info));
3121 } SMARTLIST_FOREACH_END(d);
3122 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
3123 smartlist_free(digests);
3124 } else {
3125 *msg = "Key not recognized";
3126 return -1;
3129 if (!smartlist_len(descs_out)) {
3130 *msg = "Servers unavailable";
3131 return -1;
3133 return 0;
3136 /** Called when a TLS handshake has completed successfully with a
3137 * router listening at <b>address</b>:<b>or_port</b>, and has yielded
3138 * a certificate with digest <b>digest_rcvd</b>.
3140 * Inform the reachability checker that we could get to this relay.
3142 void
3143 dirserv_orconn_tls_done(const tor_addr_t *addr,
3144 uint16_t or_port,
3145 const char *digest_rcvd)
3147 node_t *node = NULL;
3148 tor_addr_port_t orport;
3149 routerinfo_t *ri = NULL;
3150 time_t now = time(NULL);
3151 tor_assert(addr);
3152 tor_assert(digest_rcvd);
3154 node = node_get_mutable_by_id(digest_rcvd);
3155 if (node == NULL || node->ri == NULL)
3156 return;
3157 ri = node->ri;
3159 tor_addr_copy(&orport.addr, addr);
3160 orport.port = or_port;
3161 if (router_has_orport(ri, &orport)) {
3162 /* Found the right router. */
3163 if (!authdir_mode_bridge(get_options()) ||
3164 ri->purpose == ROUTER_PURPOSE_BRIDGE) {
3165 char addrstr[TOR_ADDR_BUF_LEN];
3166 /* This is a bridge or we're not a bridge authorititative --
3167 mark it as reachable. */
3168 log_info(LD_DIRSERV, "Found router %s to be reachable at %s:%d. Yay.",
3169 router_describe(ri),
3170 tor_addr_to_str(addrstr, addr, sizeof(addrstr), 1),
3171 ri->or_port);
3172 if (tor_addr_family(addr) == AF_INET) {
3173 rep_hist_note_router_reachable(digest_rcvd, addr, or_port, now);
3174 node->last_reachable = now;
3175 } else if (tor_addr_family(addr) == AF_INET6) {
3176 /* No rephist for IPv6. */
3177 node->last_reachable6 = now;
3183 /** Called when we, as an authority, receive a new router descriptor either as
3184 * an upload or a download. Used to decide whether to relaunch reachability
3185 * testing for the server. */
3187 dirserv_should_launch_reachability_test(const routerinfo_t *ri,
3188 const routerinfo_t *ri_old)
3190 if (!authdir_mode_handles_descs(get_options(), ri->purpose))
3191 return 0;
3192 if (!ri_old) {
3193 /* New router: Launch an immediate reachability test, so we will have an
3194 * opinion soon in case we're generating a consensus soon */
3195 return 1;
3197 if (ri_old->is_hibernating && !ri->is_hibernating) {
3198 /* It just came out of hibernation; launch a reachability test */
3199 return 1;
3201 if (! routers_have_same_or_addrs(ri, ri_old)) {
3202 /* Address or port changed; launch a reachability test */
3203 return 1;
3205 return 0;
3208 /** Helper function for dirserv_test_reachability(). Start a TLS
3209 * connection to <b>router</b>, and annotate it with when we started
3210 * the test. */
3211 void
3212 dirserv_single_reachability_test(time_t now, routerinfo_t *router)
3214 channel_t *chan = NULL;
3215 node_t *node = NULL;
3216 tor_addr_t router_addr;
3217 (void) now;
3219 tor_assert(router);
3220 node = node_get_mutable_by_id(router->cache_info.identity_digest);
3221 tor_assert(node);
3223 /* IPv4. */
3224 log_debug(LD_OR,"Testing reachability of %s at %s:%u.",
3225 router->nickname, fmt_addr32(router->addr), router->or_port);
3226 tor_addr_from_ipv4h(&router_addr, router->addr);
3227 chan = channel_tls_connect(&router_addr, router->or_port,
3228 router->cache_info.identity_digest);
3229 if (chan) command_setup_channel(chan);
3231 /* Possible IPv6. */
3232 if (get_options()->AuthDirHasIPv6Connectivity == 1 &&
3233 !tor_addr_is_null(&router->ipv6_addr)) {
3234 char addrstr[TOR_ADDR_BUF_LEN];
3235 log_debug(LD_OR, "Testing reachability of %s at %s:%u.",
3236 router->nickname,
3237 tor_addr_to_str(addrstr, &router->ipv6_addr, sizeof(addrstr), 1),
3238 router->ipv6_orport);
3239 chan = channel_tls_connect(&router->ipv6_addr, router->ipv6_orport,
3240 router->cache_info.identity_digest);
3241 if (chan) command_setup_channel(chan);
3245 /** Auth dir server only: load balance such that we only
3246 * try a few connections per call.
3248 * The load balancing is such that if we get called once every ten
3249 * seconds, we will cycle through all the tests in
3250 * REACHABILITY_TEST_CYCLE_PERIOD seconds (a bit over 20 minutes).
3252 void
3253 dirserv_test_reachability(time_t now)
3255 /* XXX decide what to do here; see or-talk thread "purging old router
3256 * information, revocation." -NM
3257 * We can't afford to mess with this in 0.1.2.x. The reason is that
3258 * if we stop doing reachability tests on some of routerlist, then
3259 * we'll for-sure think they're down, which may have unexpected
3260 * effects in other parts of the code. It doesn't hurt much to do
3261 * the testing, and directory authorities are easy to upgrade. Let's
3262 * wait til 0.2.0. -RD */
3263 // time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
3264 routerlist_t *rl = router_get_routerlist();
3265 static char ctr = 0;
3266 int bridge_auth = authdir_mode_bridge(get_options());
3268 SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, router) {
3269 const char *id_digest = router->cache_info.identity_digest;
3270 if (router_is_me(router))
3271 continue;
3272 if (bridge_auth && router->purpose != ROUTER_PURPOSE_BRIDGE)
3273 continue; /* bridge authorities only test reachability on bridges */
3274 // if (router->cache_info.published_on > cutoff)
3275 // continue;
3276 if ((((uint8_t)id_digest[0]) % REACHABILITY_MODULO_PER_TEST) == ctr) {
3277 dirserv_single_reachability_test(now, router);
3279 } SMARTLIST_FOREACH_END(router);
3280 ctr = (ctr + 1) % REACHABILITY_MODULO_PER_TEST; /* increment ctr */
3283 /** Given a fingerprint <b>fp</b> which is either set if we're looking for a
3284 * v2 status, or zeroes if we're looking for a v3 status, or a NUL-padded
3285 * flavor name if we want a flavored v3 status, return a pointer to the
3286 * appropriate cached dir object, or NULL if there isn't one available. */
3287 static cached_dir_t *
3288 lookup_cached_dir_by_fp(const char *fp)
3290 cached_dir_t *d = NULL;
3291 if (tor_digest_is_zero(fp) && cached_consensuses) {
3292 d = strmap_get(cached_consensuses, "ns");
3293 } else if (memchr(fp, '\0', DIGEST_LEN) && cached_consensuses &&
3294 (d = strmap_get(cached_consensuses, fp))) {
3295 /* this here interface is a nasty hack XXXX */;
3297 return d;
3300 /** Remove from <b>fps</b> every networkstatus key where both
3301 * a) we have a networkstatus document and
3302 * b) it is not newer than <b>cutoff</b>.
3304 * Return 1 if any items were present at all; else return 0.
3307 dirserv_remove_old_statuses(smartlist_t *fps, time_t cutoff)
3309 int found_any = 0;
3310 SMARTLIST_FOREACH_BEGIN(fps, char *, digest) {
3311 cached_dir_t *d = lookup_cached_dir_by_fp(digest);
3312 if (!d)
3313 continue;
3314 found_any = 1;
3315 if (d->published <= cutoff) {
3316 tor_free(digest);
3317 SMARTLIST_DEL_CURRENT(fps, digest);
3319 } SMARTLIST_FOREACH_END(digest);
3321 return found_any;
3324 /** Return the cache-info for identity fingerprint <b>fp</b>, or
3325 * its extra-info document if <b>extrainfo</b> is true. Return
3326 * NULL if not found or if the descriptor is older than
3327 * <b>publish_cutoff</b>. */
3328 static const signed_descriptor_t *
3329 get_signed_descriptor_by_fp(const char *fp, int extrainfo,
3330 time_t publish_cutoff)
3332 if (router_digest_is_me(fp)) {
3333 if (extrainfo)
3334 return &(router_get_my_extrainfo()->cache_info);
3335 else
3336 return &(router_get_my_routerinfo()->cache_info);
3337 } else {
3338 const routerinfo_t *ri = router_get_by_id_digest(fp);
3339 if (ri &&
3340 ri->cache_info.published_on > publish_cutoff) {
3341 if (extrainfo)
3342 return extrainfo_get_by_descriptor_digest(
3343 ri->cache_info.extra_info_digest);
3344 else
3345 return &ri->cache_info;
3348 return NULL;
3351 /** Return true iff we have any of the documents (extrainfo or routerdesc)
3352 * specified by the fingerprints in <b>fps</b> and <b>spool_src</b>. Used to
3353 * decide whether to send a 404. */
3355 dirserv_have_any_serverdesc(smartlist_t *fps, int spool_src)
3357 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
3358 SMARTLIST_FOREACH_BEGIN(fps, const char *, fp) {
3359 switch (spool_src)
3361 case DIR_SPOOL_EXTRA_BY_DIGEST:
3362 if (extrainfo_get_by_descriptor_digest(fp)) return 1;
3363 break;
3364 case DIR_SPOOL_SERVER_BY_DIGEST:
3365 if (router_get_by_descriptor_digest(fp)) return 1;
3366 break;
3367 case DIR_SPOOL_EXTRA_BY_FP:
3368 case DIR_SPOOL_SERVER_BY_FP:
3369 if (get_signed_descriptor_by_fp(fp,
3370 spool_src == DIR_SPOOL_EXTRA_BY_FP, publish_cutoff))
3371 return 1;
3372 break;
3374 } SMARTLIST_FOREACH_END(fp);
3375 return 0;
3378 /** Return true iff any of the 256-bit elements in <b>fps</b> is the digest of
3379 * a microdescriptor we have. */
3381 dirserv_have_any_microdesc(const smartlist_t *fps)
3383 microdesc_cache_t *cache = get_microdesc_cache();
3384 SMARTLIST_FOREACH(fps, const char *, fp,
3385 if (microdesc_cache_lookup_by_digest256(cache, fp))
3386 return 1);
3387 return 0;
3390 /** Return an approximate estimate of the number of bytes that will
3391 * be needed to transmit the server descriptors (if is_serverdescs --
3392 * they can be either d/ or fp/ queries) or networkstatus objects (if
3393 * !is_serverdescs) listed in <b>fps</b>. If <b>compressed</b> is set,
3394 * we guess how large the data will be after compression.
3396 * The return value is an estimate; it might be larger or smaller.
3398 size_t
3399 dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
3400 int compressed)
3402 size_t result;
3403 tor_assert(fps);
3404 if (is_serverdescs) {
3405 int n = smartlist_len(fps);
3406 const routerinfo_t *me = router_get_my_routerinfo();
3407 result = (me?me->cache_info.signed_descriptor_len:2048) * n;
3408 if (compressed)
3409 result /= 2; /* observed compressibility is between 35 and 55%. */
3410 } else {
3411 result = 0;
3412 SMARTLIST_FOREACH(fps, const char *, digest, {
3413 cached_dir_t *dir = lookup_cached_dir_by_fp(digest);
3414 if (dir)
3415 result += compressed ? dir->dir_z_len : dir->dir_len;
3418 return result;
3421 /** Given a list of microdescriptor hashes, guess how many bytes will be
3422 * needed to transmit them, and return the guess. */
3423 size_t
3424 dirserv_estimate_microdesc_size(const smartlist_t *fps, int compressed)
3426 size_t result = smartlist_len(fps) * microdesc_average_size(NULL);
3427 if (compressed)
3428 result /= 2;
3429 return result;
3432 /** When we're spooling data onto our outbuf, add more whenever we dip
3433 * below this threshold. */
3434 #define DIRSERV_BUFFER_MIN 16384
3436 /** Spooling helper: called when we have no more data to spool to <b>conn</b>.
3437 * Flushes any remaining data to be (un)compressed, and changes the spool
3438 * source to NONE. Returns 0 on success, negative on failure. */
3439 static int
3440 connection_dirserv_finish_spooling(dir_connection_t *conn)
3442 if (conn->zlib_state) {
3443 connection_write_to_buf_zlib("", 0, conn, 1);
3444 tor_zlib_free(conn->zlib_state);
3445 conn->zlib_state = NULL;
3447 conn->dir_spool_src = DIR_SPOOL_NONE;
3448 return 0;
3451 /** Spooling helper: called when we're sending a bunch of server descriptors,
3452 * and the outbuf has become too empty. Pulls some entries from
3453 * fingerprint_stack, and writes the corresponding servers onto outbuf. If we
3454 * run out of entries, flushes the zlib state and sets the spool source to
3455 * NONE. Returns 0 on success, negative on failure.
3457 static int
3458 connection_dirserv_add_servers_to_outbuf(dir_connection_t *conn)
3460 int by_fp = (conn->dir_spool_src == DIR_SPOOL_SERVER_BY_FP ||
3461 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP);
3462 int extra = (conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP ||
3463 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_DIGEST);
3464 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
3466 const or_options_t *options = get_options();
3468 while (smartlist_len(conn->fingerprint_stack) &&
3469 connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
3470 const char *body;
3471 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3472 const signed_descriptor_t *sd = NULL;
3473 if (by_fp) {
3474 sd = get_signed_descriptor_by_fp(fp, extra, publish_cutoff);
3475 } else {
3476 sd = extra ? extrainfo_get_by_descriptor_digest(fp)
3477 : router_get_by_descriptor_digest(fp);
3479 tor_free(fp);
3480 if (!sd)
3481 continue;
3482 if (!connection_dir_is_encrypted(conn) && !sd->send_unencrypted) {
3483 /* we did this check once before (so we could have an accurate size
3484 * estimate and maybe send a 404 if somebody asked for only bridges on a
3485 * connection), but we need to do it again in case a previously
3486 * unknown bridge descriptor has shown up between then and now. */
3487 continue;
3490 /** If we are the bridge authority and the descriptor is a bridge
3491 * descriptor, remember that we served this descriptor for desc stats. */
3492 if (options->BridgeAuthoritativeDir && by_fp) {
3493 const routerinfo_t *router =
3494 router_get_by_id_digest(sd->identity_digest);
3495 /* router can be NULL here when the bridge auth is asked for its own
3496 * descriptor. */
3497 if (router && router->purpose == ROUTER_PURPOSE_BRIDGE)
3498 rep_hist_note_desc_served(sd->identity_digest);
3500 body = signed_descriptor_get_body(sd);
3501 if (conn->zlib_state) {
3502 int last = ! smartlist_len(conn->fingerprint_stack);
3503 connection_write_to_buf_zlib(body, sd->signed_descriptor_len, conn,
3504 last);
3505 if (last) {
3506 tor_zlib_free(conn->zlib_state);
3507 conn->zlib_state = NULL;
3509 } else {
3510 connection_write_to_buf(body,
3511 sd->signed_descriptor_len,
3512 TO_CONN(conn));
3516 if (!smartlist_len(conn->fingerprint_stack)) {
3517 /* We just wrote the last one; finish up. */
3518 if (conn->zlib_state) {
3519 connection_write_to_buf_zlib("", 0, conn, 1);
3520 tor_zlib_free(conn->zlib_state);
3521 conn->zlib_state = NULL;
3523 conn->dir_spool_src = DIR_SPOOL_NONE;
3524 smartlist_free(conn->fingerprint_stack);
3525 conn->fingerprint_stack = NULL;
3527 return 0;
3530 /** Spooling helper: called when we're sending a bunch of microdescriptors,
3531 * and the outbuf has become too empty. Pulls some entries from
3532 * fingerprint_stack, and writes the corresponding microdescs onto outbuf. If
3533 * we run out of entries, flushes the zlib state and sets the spool source to
3534 * NONE. Returns 0 on success, negative on failure.
3536 static int
3537 connection_dirserv_add_microdescs_to_outbuf(dir_connection_t *conn)
3539 microdesc_cache_t *cache = get_microdesc_cache();
3540 while (smartlist_len(conn->fingerprint_stack) &&
3541 connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
3542 char *fp256 = smartlist_pop_last(conn->fingerprint_stack);
3543 microdesc_t *md = microdesc_cache_lookup_by_digest256(cache, fp256);
3544 tor_free(fp256);
3545 if (!md || !md->body)
3546 continue;
3547 if (conn->zlib_state) {
3548 int last = !smartlist_len(conn->fingerprint_stack);
3549 connection_write_to_buf_zlib(md->body, md->bodylen, conn, last);
3550 if (last) {
3551 tor_zlib_free(conn->zlib_state);
3552 conn->zlib_state = NULL;
3554 } else {
3555 connection_write_to_buf(md->body, md->bodylen, TO_CONN(conn));
3558 if (!smartlist_len(conn->fingerprint_stack)) {
3559 if (conn->zlib_state) {
3560 connection_write_to_buf_zlib("", 0, conn, 1);
3561 tor_zlib_free(conn->zlib_state);
3562 conn->zlib_state = NULL;
3564 conn->dir_spool_src = DIR_SPOOL_NONE;
3565 smartlist_free(conn->fingerprint_stack);
3566 conn->fingerprint_stack = NULL;
3568 return 0;
3571 /** Spooling helper: Called when we're sending a directory or networkstatus,
3572 * and the outbuf has become too empty. Pulls some bytes from
3573 * <b>conn</b>-\>cached_dir-\>dir_z, uncompresses them if appropriate, and
3574 * puts them on the outbuf. If we run out of entries, flushes the zlib state
3575 * and sets the spool source to NONE. Returns 0 on success, negative on
3576 * failure. */
3577 static int
3578 connection_dirserv_add_dir_bytes_to_outbuf(dir_connection_t *conn)
3580 ssize_t bytes;
3581 int64_t remaining;
3583 bytes = DIRSERV_BUFFER_MIN - connection_get_outbuf_len(TO_CONN(conn));
3584 tor_assert(bytes > 0);
3585 tor_assert(conn->cached_dir);
3586 if (bytes < 8192)
3587 bytes = 8192;
3588 remaining = conn->cached_dir->dir_z_len - conn->cached_dir_offset;
3589 if (bytes > remaining)
3590 bytes = (ssize_t) remaining;
3592 if (conn->zlib_state) {
3593 connection_write_to_buf_zlib(
3594 conn->cached_dir->dir_z + conn->cached_dir_offset,
3595 bytes, conn, bytes == remaining);
3596 } else {
3597 connection_write_to_buf(conn->cached_dir->dir_z + conn->cached_dir_offset,
3598 bytes, TO_CONN(conn));
3600 conn->cached_dir_offset += bytes;
3601 if (conn->cached_dir_offset == (int)conn->cached_dir->dir_z_len) {
3602 /* We just wrote the last one; finish up. */
3603 connection_dirserv_finish_spooling(conn);
3604 cached_dir_decref(conn->cached_dir);
3605 conn->cached_dir = NULL;
3607 return 0;
3610 /** Spooling helper: Called when we're spooling networkstatus objects on
3611 * <b>conn</b>, and the outbuf has become too empty. If the current
3612 * networkstatus object (in <b>conn</b>-\>cached_dir) has more data, pull data
3613 * from there. Otherwise, pop the next fingerprint from fingerprint_stack,
3614 * and start spooling the next networkstatus. (A digest of all 0 bytes is
3615 * treated as a request for the current consensus.) If we run out of entries,
3616 * flushes the zlib state and sets the spool source to NONE. Returns 0 on
3617 * success, negative on failure. */
3618 static int
3619 connection_dirserv_add_networkstatus_bytes_to_outbuf(dir_connection_t *conn)
3622 while (connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
3623 if (conn->cached_dir) {
3624 int uncompressing = (conn->zlib_state != NULL);
3625 int r = connection_dirserv_add_dir_bytes_to_outbuf(conn);
3626 if (conn->dir_spool_src == DIR_SPOOL_NONE) {
3627 /* add_dir_bytes thinks we're done with the cached_dir. But we
3628 * may have more cached_dirs! */
3629 conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
3630 /* This bit is tricky. If we were uncompressing the last
3631 * networkstatus, we may need to make a new zlib object to
3632 * uncompress the next one. */
3633 if (uncompressing && ! conn->zlib_state &&
3634 conn->fingerprint_stack &&
3635 smartlist_len(conn->fingerprint_stack)) {
3636 conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD, HIGH_COMPRESSION);
3639 if (r) return r;
3640 } else if (conn->fingerprint_stack &&
3641 smartlist_len(conn->fingerprint_stack)) {
3642 /* Add another networkstatus; start serving it. */
3643 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3644 cached_dir_t *d = lookup_cached_dir_by_fp(fp);
3645 tor_free(fp);
3646 if (d) {
3647 ++d->refcnt;
3648 conn->cached_dir = d;
3649 conn->cached_dir_offset = 0;
3651 } else {
3652 connection_dirserv_finish_spooling(conn);
3653 smartlist_free(conn->fingerprint_stack);
3654 conn->fingerprint_stack = NULL;
3655 return 0;
3658 return 0;
3661 /** Called whenever we have flushed some directory data in state
3662 * SERVER_WRITING. */
3664 connection_dirserv_flushed_some(dir_connection_t *conn)
3666 tor_assert(conn->base_.state == DIR_CONN_STATE_SERVER_WRITING);
3668 if (connection_get_outbuf_len(TO_CONN(conn)) >= DIRSERV_BUFFER_MIN)
3669 return 0;
3671 switch (conn->dir_spool_src) {
3672 case DIR_SPOOL_EXTRA_BY_DIGEST:
3673 case DIR_SPOOL_EXTRA_BY_FP:
3674 case DIR_SPOOL_SERVER_BY_DIGEST:
3675 case DIR_SPOOL_SERVER_BY_FP:
3676 return connection_dirserv_add_servers_to_outbuf(conn);
3677 case DIR_SPOOL_MICRODESC:
3678 return connection_dirserv_add_microdescs_to_outbuf(conn);
3679 case DIR_SPOOL_CACHED_DIR:
3680 return connection_dirserv_add_dir_bytes_to_outbuf(conn);
3681 case DIR_SPOOL_NETWORKSTATUS:
3682 return connection_dirserv_add_networkstatus_bytes_to_outbuf(conn);
3683 case DIR_SPOOL_NONE:
3684 default:
3685 return 0;
3689 /** Return true iff <b>line</b> is a valid RecommendedPackages line.
3692 The grammar is:
3694 "package" SP PACKAGENAME SP VERSION SP URL SP DIGESTS NL
3696 PACKAGENAME = NONSPACE
3697 VERSION = NONSPACE
3698 URL = NONSPACE
3699 DIGESTS = DIGEST | DIGESTS SP DIGEST
3700 DIGEST = DIGESTTYPE "=" DIGESTVAL
3702 NONSPACE = one or more non-space printing characters
3704 DIGESTVAL = DIGESTTYPE = one or more non-=, non-" " characters.
3706 SP = " "
3707 NL = a newline
3711 validate_recommended_package_line(const char *line)
3713 const char *cp = line;
3715 #define WORD() \
3716 do { \
3717 if (*cp == ' ') \
3718 return 0; \
3719 cp = strchr(cp, ' '); \
3720 if (!cp) \
3721 return 0; \
3722 } while (0)
3724 WORD(); /* skip packagename */
3725 ++cp;
3726 WORD(); /* skip version */
3727 ++cp;
3728 WORD(); /* Skip URL */
3729 ++cp;
3731 /* Skip digesttype=digestval + */
3732 int n_entries = 0;
3733 while (1) {
3734 const char *start_of_word = cp;
3735 const char *end_of_word = strchr(cp, ' ');
3736 if (! end_of_word)
3737 end_of_word = cp + strlen(cp);
3739 if (start_of_word == end_of_word)
3740 return 0;
3742 const char *eq = memchr(start_of_word, '=', end_of_word - start_of_word);
3744 if (!eq)
3745 return 0;
3746 if (eq == start_of_word)
3747 return 0;
3748 if (eq == end_of_word - 1)
3749 return 0;
3750 if (memchr(eq+1, '=', end_of_word - (eq+1)))
3751 return 0;
3753 ++n_entries;
3754 if (0 == *end_of_word)
3755 break;
3757 cp = end_of_word + 1;
3760 /* If we reach this point, we have at least 1 entry. */
3761 tor_assert(n_entries > 0);
3762 return 1;
3765 /** Release all storage used by the directory server. */
3766 void
3767 dirserv_free_all(void)
3769 dirserv_free_fingerprint_list();
3771 strmap_free(cached_consensuses, free_cached_dir_);
3772 cached_consensuses = NULL;
3774 dirserv_clear_measured_bw_cache();