In routerlist_assert_ok(), check r2 before taking &(r2->cache_info)
[tor.git] / src / or / dirserv.c
blob49fafafab2b7ef0aebe03dca03f9aef4a5869911
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2013, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 #define DIRSERV_PRIVATE
7 #include "or.h"
8 #include "buffers.h"
9 #include "config.h"
10 #include "confparse.h"
11 #include "channel.h"
12 #include "channeltls.h"
13 #include "command.h"
14 #include "connection.h"
15 #include "connection_or.h"
16 #include "control.h"
17 #include "directory.h"
18 #include "dirserv.h"
19 #include "dirvote.h"
20 #include "hibernate.h"
21 #include "microdesc.h"
22 #include "networkstatus.h"
23 #include "nodelist.h"
24 #include "policies.h"
25 #include "rephist.h"
26 #include "router.h"
27 #include "routerlist.h"
28 #include "routerparse.h"
29 #include "routerset.h"
31 /**
32 * \file dirserv.c
33 * \brief Directory server core implementation. Manages directory
34 * contents and generates directories.
37 /** How far in the future do we allow a router to get? (seconds) */
38 #define ROUTER_ALLOW_SKEW (60*60*12)
39 /** How many seconds do we wait before regenerating the directory? */
40 #define DIR_REGEN_SLACK_TIME 30
41 /** If we're a cache, keep this many networkstatuses around from non-trusted
42 * directory authorities. */
43 #define MAX_UNTRUSTED_NETWORKSTATUSES 16
45 extern time_t time_of_process_start; /* from main.c */
47 extern long stats_n_seconds_working; /* from main.c */
49 /** Total number of routers with measured bandwidth; this is set by
50 * dirserv_count_measured_bws() before the loop in
51 * dirserv_generate_networkstatus_vote_obj() and checked by
52 * dirserv_get_credible_bandwidth() and
53 * dirserv_compute_performance_thresholds() */
54 static int routers_with_measured_bw = 0;
56 static void directory_remove_invalid(void);
57 static char *format_versions_list(config_line_t *ln);
58 struct authdir_config_t;
59 static int add_fingerprint_to_dir(const char *nickname, const char *fp,
60 struct authdir_config_t *list);
61 static uint32_t
62 dirserv_get_status_impl(const char *fp, const char *nickname,
63 uint32_t addr, uint16_t or_port,
64 const char *platform, const char *contact,
65 const char **msg, int should_log);
66 static void clear_cached_dir(cached_dir_t *d);
67 static const signed_descriptor_t *get_signed_descriptor_by_fp(
68 const char *fp,
69 int extrainfo,
70 time_t publish_cutoff);
71 static was_router_added_t dirserv_add_extrainfo(extrainfo_t *ei,
72 const char **msg);
73 static uint32_t dirserv_get_bandwidth_for_router_kb(const routerinfo_t *ri);
74 static uint32_t dirserv_get_credible_bandwidth_kb(const routerinfo_t *ri);
76 /************** Fingerprint handling code ************/
78 #define FP_NAMED 1 /**< Listed in fingerprint file. */
79 #define FP_INVALID 2 /**< Believed invalid. */
80 #define FP_REJECT 4 /**< We will not publish this router. */
81 #define FP_BADDIR 8 /**< We'll tell clients to avoid using this as a dir. */
82 #define FP_BADEXIT 16 /**< We'll tell clients not to use this as an exit. */
83 #define FP_UNNAMED 32 /**< Another router has this name in fingerprint file. */
85 /** Encapsulate a nickname and an FP_* status; target of status_by_digest
86 * map. */
87 typedef struct router_status_t {
88 char nickname[MAX_NICKNAME_LEN+1];
89 uint32_t status;
90 } router_status_t;
92 /** List of nickname-\>identity fingerprint mappings for all the routers
93 * that we name. Used to prevent router impersonation. */
94 typedef struct authdir_config_t {
95 strmap_t *fp_by_name; /**< Map from lc nickname to fingerprint. */
96 digestmap_t *status_by_digest; /**< Map from digest to router_status_t. */
97 } authdir_config_t;
99 /** Should be static; exposed for testing. */
100 static authdir_config_t *fingerprint_list = NULL;
102 /** Allocate and return a new, empty, authdir_config_t. */
103 static authdir_config_t *
104 authdir_config_new(void)
106 authdir_config_t *list = tor_malloc_zero(sizeof(authdir_config_t));
107 list->fp_by_name = strmap_new();
108 list->status_by_digest = digestmap_new();
109 return list;
112 /** Add the fingerprint <b>fp</b> for <b>nickname</b> to
113 * the smartlist of fingerprint_entry_t's <b>list</b>. Return 0 if it's
114 * new, or 1 if we replaced the old value.
116 /* static */ int
117 add_fingerprint_to_dir(const char *nickname, const char *fp,
118 authdir_config_t *list)
120 char *fingerprint;
121 char d[DIGEST_LEN];
122 router_status_t *status;
123 tor_assert(nickname);
124 tor_assert(fp);
125 tor_assert(list);
127 fingerprint = tor_strdup(fp);
128 tor_strstrip(fingerprint, " ");
129 if (base16_decode(d, DIGEST_LEN, fingerprint, strlen(fingerprint))) {
130 log_warn(LD_DIRSERV, "Couldn't decode fingerprint \"%s\"",
131 escaped(fp));
132 tor_free(fingerprint);
133 return 0;
136 if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME)) {
137 log_warn(LD_DIRSERV, "Tried to add a mapping for reserved nickname %s",
138 UNNAMED_ROUTER_NICKNAME);
139 tor_free(fingerprint);
140 return 0;
143 status = digestmap_get(list->status_by_digest, d);
144 if (!status) {
145 status = tor_malloc_zero(sizeof(router_status_t));
146 digestmap_set(list->status_by_digest, d, status);
149 if (nickname[0] != '!') {
150 char *old_fp = strmap_get_lc(list->fp_by_name, nickname);
151 if (old_fp && !strcasecmp(fingerprint, old_fp)) {
152 tor_free(fingerprint);
153 } else {
154 tor_free(old_fp);
155 strmap_set_lc(list->fp_by_name, nickname, fingerprint);
157 status->status |= FP_NAMED;
158 strlcpy(status->nickname, nickname, sizeof(status->nickname));
159 } else {
160 tor_free(fingerprint);
161 if (!strcasecmp(nickname, "!reject")) {
162 status->status |= FP_REJECT;
163 } else if (!strcasecmp(nickname, "!invalid")) {
164 status->status |= FP_INVALID;
165 } else if (!strcasecmp(nickname, "!baddir")) {
166 status->status |= FP_BADDIR;
167 } else if (!strcasecmp(nickname, "!badexit")) {
168 status->status |= FP_BADEXIT;
171 return 0;
174 /** Add the nickname and fingerprint for this OR to the
175 * global list of recognized identity key fingerprints. */
177 dirserv_add_own_fingerprint(const char *nickname, crypto_pk_t *pk)
179 char fp[FINGERPRINT_LEN+1];
180 if (crypto_pk_get_fingerprint(pk, fp, 0)<0) {
181 log_err(LD_BUG, "Error computing fingerprint");
182 return -1;
184 if (!fingerprint_list)
185 fingerprint_list = authdir_config_new();
186 add_fingerprint_to_dir(nickname, fp, fingerprint_list);
187 return 0;
190 /** Load the nickname-\>fingerprint mappings stored in the approved-routers
191 * file. The file format is line-based, with each non-blank holding one
192 * nickname, some space, and a fingerprint for that nickname. On success,
193 * replace the current fingerprint list with the new list and return 0. On
194 * failure, leave the current fingerprint list untouched, and return -1. */
196 dirserv_load_fingerprint_file(void)
198 char *fname;
199 char *cf;
200 char *nickname, *fingerprint;
201 authdir_config_t *fingerprint_list_new;
202 int result;
203 config_line_t *front=NULL, *list;
204 const or_options_t *options = get_options();
206 fname = get_datadir_fname("approved-routers");
207 log_info(LD_GENERAL,
208 "Reloading approved fingerprints from \"%s\"...", fname);
210 cf = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
211 if (!cf) {
212 if (options->NamingAuthoritativeDir) {
213 log_warn(LD_FS, "Cannot open fingerprint file '%s'. Failing.", fname);
214 tor_free(fname);
215 return -1;
216 } else {
217 log_info(LD_FS, "Cannot open fingerprint file '%s'. That's ok.", fname);
218 tor_free(fname);
219 return 0;
222 tor_free(fname);
224 result = config_get_lines(cf, &front, 0);
225 tor_free(cf);
226 if (result < 0) {
227 log_warn(LD_CONFIG, "Error reading from fingerprint file");
228 return -1;
231 fingerprint_list_new = authdir_config_new();
233 for (list=front; list; list=list->next) {
234 char digest_tmp[DIGEST_LEN];
235 nickname = list->key; fingerprint = list->value;
236 if (strlen(nickname) > MAX_NICKNAME_LEN) {
237 log_notice(LD_CONFIG,
238 "Nickname '%s' too long in fingerprint file. Skipping.",
239 nickname);
240 continue;
242 if (!is_legal_nickname(nickname) &&
243 strcasecmp(nickname, "!reject") &&
244 strcasecmp(nickname, "!invalid") &&
245 strcasecmp(nickname, "!badexit")) {
246 log_notice(LD_CONFIG,
247 "Invalid nickname '%s' in fingerprint file. Skipping.",
248 nickname);
249 continue;
251 tor_strstrip(fingerprint, " "); /* remove spaces */
252 if (strlen(fingerprint) != HEX_DIGEST_LEN ||
253 base16_decode(digest_tmp, sizeof(digest_tmp),
254 fingerprint, HEX_DIGEST_LEN) < 0) {
255 log_notice(LD_CONFIG,
256 "Invalid fingerprint (nickname '%s', "
257 "fingerprint %s). Skipping.",
258 nickname, fingerprint);
259 continue;
261 if (0==strcasecmp(nickname, DEFAULT_CLIENT_NICKNAME)) {
262 /* If you approved an OR called "client", then clients who use
263 * the default nickname could all be rejected. That's no good. */
264 log_notice(LD_CONFIG,
265 "Authorizing nickname '%s' would break "
266 "many clients; skipping.",
267 DEFAULT_CLIENT_NICKNAME);
268 continue;
270 if (0==strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME)) {
271 /* If you approved an OR called "unnamed", then clients will be
272 * confused. */
273 log_notice(LD_CONFIG,
274 "Authorizing nickname '%s' is not allowed; skipping.",
275 UNNAMED_ROUTER_NICKNAME);
276 continue;
278 if (add_fingerprint_to_dir(nickname, fingerprint, fingerprint_list_new)
279 != 0)
280 log_notice(LD_CONFIG, "Duplicate nickname '%s'.", nickname);
283 config_free_lines(front);
284 dirserv_free_fingerprint_list();
285 fingerprint_list = fingerprint_list_new;
286 /* Delete any routers whose fingerprints we no longer recognize */
287 directory_remove_invalid();
288 return 0;
291 /** Check whether <b>router</b> has a nickname/identity key combination that
292 * we recognize from the fingerprint list, or an IP we automatically act on
293 * according to our configuration. Return the appropriate router status.
295 * If the status is 'FP_REJECT' and <b>msg</b> is provided, set
296 * *<b>msg</b> to an explanation of why. */
297 uint32_t
298 dirserv_router_get_status(const routerinfo_t *router, const char **msg)
300 char d[DIGEST_LEN];
302 if (crypto_pk_get_digest(router->identity_pkey, d)) {
303 log_warn(LD_BUG,"Error computing fingerprint");
304 if (msg)
305 *msg = "Bug: Error computing fingerprint";
306 return FP_REJECT;
309 return dirserv_get_status_impl(d, router->nickname,
310 router->addr, router->or_port,
311 router->platform, router->contact_info,
312 msg, 1);
315 /** Return true if there is no point in downloading the router described by
316 * <b>rs</b> because this directory would reject it. */
318 dirserv_would_reject_router(const routerstatus_t *rs)
320 uint32_t res;
322 res = dirserv_get_status_impl(rs->identity_digest, rs->nickname,
323 rs->addr, rs->or_port,
324 NULL, NULL,
325 NULL, 0);
327 return (res & FP_REJECT) != 0;
330 /** Helper: Based only on the ID/Nickname combination,
331 * return FP_UNNAMED (unnamed), FP_NAMED (named), or 0 (neither).
333 static uint32_t
334 dirserv_get_name_status(const char *id_digest, const char *nickname)
336 char fp[HEX_DIGEST_LEN+1];
337 char *fp_by_name;
339 base16_encode(fp, sizeof(fp), id_digest, DIGEST_LEN);
341 if ((fp_by_name =
342 strmap_get_lc(fingerprint_list->fp_by_name, nickname))) {
343 if (!strcasecmp(fp, fp_by_name)) {
344 return FP_NAMED;
345 } else {
346 return FP_UNNAMED; /* Wrong fingerprint. */
349 return 0;
352 /** Helper: As dirserv_router_get_status, but takes the router fingerprint
353 * (hex, no spaces), nickname, address (used for logging only), IP address, OR
354 * port, platform (logging only) and contact info (logging only) as arguments.
356 * If should_log is false, do not log messages. (There's not much point in
357 * logging that we're rejecting servers we'll not download.)
359 static uint32_t
360 dirserv_get_status_impl(const char *id_digest, const char *nickname,
361 uint32_t addr, uint16_t or_port,
362 const char *platform, const char *contact,
363 const char **msg, int should_log)
365 int reject_unlisted = get_options()->AuthDirRejectUnlisted;
366 uint32_t result;
367 router_status_t *status_by_digest;
369 if (!fingerprint_list)
370 fingerprint_list = authdir_config_new();
372 if (should_log)
373 log_debug(LD_DIRSERV, "%d fingerprints, %d digests known.",
374 strmap_size(fingerprint_list->fp_by_name),
375 digestmap_size(fingerprint_list->status_by_digest));
377 /* Versions before Tor 0.2.3.16-alpha are too old to support, and are
378 * missing some important security fixes too. Disable them. */
379 if (platform && !tor_version_as_new_as(platform,"0.2.3.16-alpha")) {
380 if (msg)
381 *msg = "Tor version is insecure or unsupported. Please upgrade!";
382 return FP_REJECT;
384 #if 0
385 else if (platform && tor_version_as_new_as(platform,"0.2.3.0-alpha")) {
386 /* Versions from 0.2.3-alpha...0.2.3.9-alpha have known security
387 * issues that make them unusable for the current network */
388 if (!tor_version_as_new_as(platform, "0.2.3.10-alpha")) {
389 if (msg)
390 *msg = "Tor version is insecure or unsupported. Please upgrade!";
391 return FP_REJECT;
394 #endif
396 result = dirserv_get_name_status(id_digest, nickname);
397 if (result & FP_NAMED) {
398 if (should_log)
399 log_debug(LD_DIRSERV,"Good fingerprint for '%s'",nickname);
401 if (result & FP_UNNAMED) {
402 if (should_log) {
403 char *esc_contact = esc_for_log(contact);
404 log_info(LD_DIRSERV,
405 "Mismatched fingerprint for '%s'. "
406 "ContactInfo '%s', platform '%s'.)",
407 nickname,
408 esc_contact,
409 platform ? escaped(platform) : "");
410 tor_free(esc_contact);
412 if (msg)
413 *msg = "Rejected: There is already a named server with this nickname "
414 "and a different fingerprint.";
417 status_by_digest = digestmap_get(fingerprint_list->status_by_digest,
418 id_digest);
419 if (status_by_digest)
420 result |= (status_by_digest->status & ~FP_NAMED);
422 if (result & FP_REJECT) {
423 if (msg)
424 *msg = "Fingerprint is marked rejected";
425 return FP_REJECT;
426 } else if (result & FP_INVALID) {
427 if (msg)
428 *msg = "Fingerprint is marked invalid";
431 if (authdir_policy_baddir_address(addr, or_port)) {
432 if (should_log)
433 log_info(LD_DIRSERV,
434 "Marking '%s' as bad directory because of address '%s'",
435 nickname, fmt_addr32(addr));
436 result |= FP_BADDIR;
439 if (authdir_policy_badexit_address(addr, or_port)) {
440 if (should_log)
441 log_info(LD_DIRSERV, "Marking '%s' as bad exit because of address '%s'",
442 nickname, fmt_addr32(addr));
443 result |= FP_BADEXIT;
446 if (!(result & FP_NAMED)) {
447 if (!authdir_policy_permits_address(addr, or_port)) {
448 if (should_log)
449 log_info(LD_DIRSERV, "Rejecting '%s' because of address '%s'",
450 nickname, fmt_addr32(addr));
451 if (msg)
452 *msg = "Authdir is rejecting routers in this range.";
453 return FP_REJECT;
455 if (!authdir_policy_valid_address(addr, or_port)) {
456 if (should_log)
457 log_info(LD_DIRSERV, "Not marking '%s' valid because of address '%s'",
458 nickname, fmt_addr32(addr));
459 result |= FP_INVALID;
461 if (reject_unlisted) {
462 if (msg)
463 *msg = "Authdir rejects unknown routers.";
464 return FP_REJECT;
468 return result;
471 /** If we are an authoritative dirserver, and the list of approved
472 * servers contains one whose identity key digest is <b>digest</b>,
473 * return that router's nickname. Otherwise return NULL. */
474 const char *
475 dirserv_get_nickname_by_digest(const char *digest)
477 router_status_t *status;
478 if (!fingerprint_list)
479 return NULL;
480 tor_assert(digest);
482 status = digestmap_get(fingerprint_list->status_by_digest, digest);
483 return status ? status->nickname : NULL;
486 /** Clear the current fingerprint list. */
487 void
488 dirserv_free_fingerprint_list(void)
490 if (!fingerprint_list)
491 return;
493 strmap_free(fingerprint_list->fp_by_name, tor_free_);
494 digestmap_free(fingerprint_list->status_by_digest, tor_free_);
495 tor_free(fingerprint_list);
499 * Descriptor list
502 /** Return -1 if <b>ri</b> has a private or otherwise bad address,
503 * unless we're configured to not care. Return 0 if all ok. */
504 static int
505 dirserv_router_has_valid_address(routerinfo_t *ri)
507 tor_addr_t addr;
508 if (get_options()->DirAllowPrivateAddresses)
509 return 0; /* whatever it is, we're fine with it */
510 tor_addr_from_ipv4h(&addr, ri->addr);
512 if (tor_addr_is_internal(&addr, 0)) {
513 log_info(LD_DIRSERV,
514 "Router %s published internal IP address. Refusing.",
515 router_describe(ri));
516 return -1; /* it's a private IP, we should reject it */
518 return 0;
521 /** Check whether we, as a directory server, want to accept <b>ri</b>. If so,
522 * set its is_valid,named,running fields and return 0. Otherwise, return -1.
524 * If the router is rejected, set *<b>msg</b> to an explanation of why.
526 * If <b>complain</b> then explain at log-level 'notice' why we refused
527 * a descriptor; else explain at log-level 'info'.
530 authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
531 int complain, int *valid_out)
533 /* Okay. Now check whether the fingerprint is recognized. */
534 uint32_t status = dirserv_router_get_status(ri, msg);
535 time_t now;
536 int severity = (complain && ri->contact_info) ? LOG_NOTICE : LOG_INFO;
537 tor_assert(msg);
538 if (status & FP_REJECT)
539 return -1; /* msg is already set. */
541 /* Is there too much clock skew? */
542 now = time(NULL);
543 if (ri->cache_info.published_on > now+ROUTER_ALLOW_SKEW) {
544 log_fn(severity, LD_DIRSERV, "Publication time for %s is too "
545 "far (%d minutes) in the future; possible clock skew. Not adding "
546 "(%s)",
547 router_describe(ri),
548 (int)((ri->cache_info.published_on-now)/60),
549 esc_router_info(ri));
550 *msg = "Rejected: Your clock is set too far in the future, or your "
551 "timezone is not correct.";
552 return -1;
554 if (ri->cache_info.published_on < now-ROUTER_MAX_AGE_TO_PUBLISH) {
555 log_fn(severity, LD_DIRSERV,
556 "Publication time for %s is too far "
557 "(%d minutes) in the past. Not adding (%s)",
558 router_describe(ri),
559 (int)((now-ri->cache_info.published_on)/60),
560 esc_router_info(ri));
561 *msg = "Rejected: Server is expired, or your clock is too far in the past,"
562 " or your timezone is not correct.";
563 return -1;
565 if (dirserv_router_has_valid_address(ri) < 0) {
566 log_fn(severity, LD_DIRSERV,
567 "Router %s has invalid address. Not adding (%s).",
568 router_describe(ri),
569 esc_router_info(ri));
570 *msg = "Rejected: Address is a private address.";
571 return -1;
574 *valid_out = ! (status & FP_INVALID);
576 return 0;
579 /** Update the relevant flags of <b>node</b> based on our opinion as a
580 * directory authority in <b>authstatus</b>, as returned by
581 * dirserv_router_get_status or equivalent. */
582 void
583 dirserv_set_node_flags_from_authoritative_status(node_t *node,
584 uint32_t authstatus)
586 node->is_valid = (authstatus & FP_INVALID) ? 0 : 1;
587 node->is_bad_directory = (authstatus & FP_BADDIR) ? 1 : 0;
588 node->is_bad_exit = (authstatus & FP_BADEXIT) ? 1 : 0;
591 /** True iff <b>a</b> is more severe than <b>b</b>. */
592 static int
593 WRA_MORE_SEVERE(was_router_added_t a, was_router_added_t b)
595 return a < b;
598 /** As for dirserv_add_descriptor(), but accepts multiple documents, and
599 * returns the most severe error that occurred for any one of them. */
600 was_router_added_t
601 dirserv_add_multiple_descriptors(const char *desc, uint8_t purpose,
602 const char *source,
603 const char **msg)
605 was_router_added_t r, r_tmp;
606 const char *msg_out;
607 smartlist_t *list;
608 const char *s;
609 int n_parsed = 0;
610 time_t now = time(NULL);
611 char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
612 char time_buf[ISO_TIME_LEN+1];
613 int general = purpose == ROUTER_PURPOSE_GENERAL;
614 tor_assert(msg);
616 r=ROUTER_ADDED_SUCCESSFULLY; /*Least severe return value. */
618 format_iso_time(time_buf, now);
619 if (tor_snprintf(annotation_buf, sizeof(annotation_buf),
620 "@uploaded-at %s\n"
621 "@source %s\n"
622 "%s%s%s", time_buf, escaped(source),
623 !general ? "@purpose " : "",
624 !general ? router_purpose_to_string(purpose) : "",
625 !general ? "\n" : "")<0) {
626 *msg = "Couldn't format annotations";
627 return -1;
630 s = desc;
631 list = smartlist_new();
632 if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 0, 0,
633 annotation_buf)) {
634 SMARTLIST_FOREACH(list, routerinfo_t *, ri, {
635 msg_out = NULL;
636 tor_assert(ri->purpose == purpose);
637 r_tmp = dirserv_add_descriptor(ri, &msg_out, source);
638 if (WRA_MORE_SEVERE(r_tmp, r)) {
639 r = r_tmp;
640 *msg = msg_out;
644 n_parsed += smartlist_len(list);
645 smartlist_clear(list);
647 s = desc;
648 if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 1, 0,
649 NULL)) {
650 SMARTLIST_FOREACH(list, extrainfo_t *, ei, {
651 msg_out = NULL;
653 r_tmp = dirserv_add_extrainfo(ei, &msg_out);
654 if (WRA_MORE_SEVERE(r_tmp, r)) {
655 r = r_tmp;
656 *msg = msg_out;
660 n_parsed += smartlist_len(list);
661 smartlist_free(list);
663 if (! *msg) {
664 if (!n_parsed) {
665 *msg = "No descriptors found in your POST.";
666 if (WRA_WAS_ADDED(r))
667 r = ROUTER_WAS_NOT_NEW;
668 } else {
669 *msg = "(no message)";
673 return r;
676 /** Examine the parsed server descriptor in <b>ri</b> and maybe insert it into
677 * the list of server descriptors. Set *<b>msg</b> to a message that should be
678 * passed back to the origin of this descriptor, or NULL if there is no such
679 * message. Use <b>source</b> to produce better log messages.
681 * Return the status of the operation
683 * This function is only called when fresh descriptors are posted, not when
684 * we re-load the cache.
686 was_router_added_t
687 dirserv_add_descriptor(routerinfo_t *ri, const char **msg, const char *source)
689 was_router_added_t r;
690 routerinfo_t *ri_old;
691 char *desc, *nickname;
692 size_t desclen = 0;
693 *msg = NULL;
695 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
696 * network and it'll clog everything up. */
697 if (ri->cache_info.signed_descriptor_len > MAX_DESCRIPTOR_UPLOAD_SIZE) {
698 log_notice(LD_DIR, "Somebody attempted to publish a router descriptor '%s'"
699 " (source: %s) with size %d. Either this is an attack, or the "
700 "MAX_DESCRIPTOR_UPLOAD_SIZE (%d) constant is too low.",
701 ri->nickname, source, (int)ri->cache_info.signed_descriptor_len,
702 MAX_DESCRIPTOR_UPLOAD_SIZE);
703 *msg = "Router descriptor was too large.";
704 control_event_or_authdir_new_descriptor("REJECTED",
705 ri->cache_info.signed_descriptor_body,
706 ri->cache_info.signed_descriptor_len, *msg);
707 routerinfo_free(ri);
708 return ROUTER_AUTHDIR_REJECTS;
711 /* Check whether this descriptor is semantically identical to the last one
712 * from this server. (We do this here and not in router_add_to_routerlist
713 * because we want to be able to accept the newest router descriptor that
714 * another authority has, so we all converge on the same one.) */
715 ri_old = router_get_mutable_by_digest(ri->cache_info.identity_digest);
716 if (ri_old && ri_old->cache_info.published_on < ri->cache_info.published_on
717 && router_differences_are_cosmetic(ri_old, ri)
718 && !router_is_me(ri)) {
719 log_info(LD_DIRSERV,
720 "Not replacing descriptor from %s (source: %s); "
721 "differences are cosmetic.",
722 router_describe(ri), source);
723 *msg = "Not replacing router descriptor; no information has changed since "
724 "the last one with this identity.";
725 control_event_or_authdir_new_descriptor("DROPPED",
726 ri->cache_info.signed_descriptor_body,
727 ri->cache_info.signed_descriptor_len, *msg);
728 routerinfo_free(ri);
729 return ROUTER_WAS_NOT_NEW;
732 /* Make a copy of desc, since router_add_to_routerlist might free
733 * ri and its associated signed_descriptor_t. */
734 desclen = ri->cache_info.signed_descriptor_len;
735 desc = tor_strndup(ri->cache_info.signed_descriptor_body, desclen);
736 nickname = tor_strdup(ri->nickname);
738 /* Tell if we're about to need to launch a test if we add this. */
739 ri->needs_retest_if_added =
740 dirserv_should_launch_reachability_test(ri, ri_old);
742 r = router_add_to_routerlist(ri, msg, 0, 0);
743 if (!WRA_WAS_ADDED(r)) {
744 /* unless the routerinfo was fine, just out-of-date */
745 if (WRA_WAS_REJECTED(r))
746 control_event_or_authdir_new_descriptor("REJECTED", desc, desclen, *msg);
747 log_info(LD_DIRSERV,
748 "Did not add descriptor from '%s' (source: %s): %s.",
749 nickname, source, *msg ? *msg : "(no message)");
750 } else {
751 smartlist_t *changed;
752 control_event_or_authdir_new_descriptor("ACCEPTED", desc, desclen, *msg);
754 changed = smartlist_new();
755 smartlist_add(changed, ri);
756 routerlist_descriptors_added(changed, 0);
757 smartlist_free(changed);
758 if (!*msg) {
759 *msg = "Descriptor accepted";
761 log_info(LD_DIRSERV,
762 "Added descriptor from '%s' (source: %s): %s.",
763 nickname, source, *msg);
765 tor_free(desc);
766 tor_free(nickname);
767 return r;
770 /** As dirserv_add_descriptor, but for an extrainfo_t <b>ei</b>. */
771 static was_router_added_t
772 dirserv_add_extrainfo(extrainfo_t *ei, const char **msg)
774 const routerinfo_t *ri;
775 int r;
776 tor_assert(msg);
777 *msg = NULL;
779 ri = router_get_by_id_digest(ei->cache_info.identity_digest);
780 if (!ri) {
781 *msg = "No corresponding router descriptor for extra-info descriptor";
782 extrainfo_free(ei);
783 return ROUTER_BAD_EI;
786 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
787 * network and it'll clog everything up. */
788 if (ei->cache_info.signed_descriptor_len > MAX_EXTRAINFO_UPLOAD_SIZE) {
789 log_notice(LD_DIR, "Somebody attempted to publish an extrainfo "
790 "with size %d. Either this is an attack, or the "
791 "MAX_EXTRAINFO_UPLOAD_SIZE (%d) constant is too low.",
792 (int)ei->cache_info.signed_descriptor_len,
793 MAX_EXTRAINFO_UPLOAD_SIZE);
794 *msg = "Extrainfo document was too large";
795 extrainfo_free(ei);
796 return ROUTER_BAD_EI;
799 if ((r = routerinfo_incompatible_with_extrainfo(ri, ei, NULL, msg))) {
800 extrainfo_free(ei);
801 return r < 0 ? ROUTER_WAS_NOT_NEW : ROUTER_BAD_EI;
803 router_add_extrainfo_to_routerlist(ei, msg, 0, 0);
804 return ROUTER_ADDED_SUCCESSFULLY;
807 /** Remove all descriptors whose nicknames or fingerprints no longer
808 * are allowed by our fingerprint list. (Descriptors that used to be
809 * good can become bad when we reload the fingerprint list.)
811 static void
812 directory_remove_invalid(void)
814 routerlist_t *rl = router_get_routerlist();
815 smartlist_t *nodes = smartlist_new();
816 smartlist_add_all(nodes, nodelist_get_list());
818 SMARTLIST_FOREACH_BEGIN(nodes, node_t *, node) {
819 const char *msg;
820 routerinfo_t *ent = node->ri;
821 char description[NODE_DESC_BUF_LEN];
822 uint32_t r;
823 if (!ent)
824 continue;
825 r = dirserv_router_get_status(ent, &msg);
826 router_get_description(description, ent);
827 if (r & FP_REJECT) {
828 log_info(LD_DIRSERV, "Router %s is now rejected: %s",
829 description, msg?msg:"");
830 routerlist_remove(rl, ent, 0, time(NULL));
831 continue;
833 #if 0
834 if (bool_neq((r & FP_NAMED), ent->auth_says_is_named)) {
835 log_info(LD_DIRSERV,
836 "Router %s is now %snamed.", description,
837 (r&FP_NAMED)?"":"un");
838 ent->is_named = (r&FP_NAMED)?1:0;
840 if (bool_neq((r & FP_UNNAMED), ent->auth_says_is_unnamed)) {
841 log_info(LD_DIRSERV,
842 "Router '%s' is now %snamed. (FP_UNNAMED)", description,
843 (r&FP_NAMED)?"":"un");
844 ent->is_named = (r&FP_NUNAMED)?0:1;
846 #endif
847 if (bool_neq((r & FP_INVALID), !node->is_valid)) {
848 log_info(LD_DIRSERV, "Router '%s' is now %svalid.", description,
849 (r&FP_INVALID) ? "in" : "");
850 node->is_valid = (r&FP_INVALID)?0:1;
852 if (bool_neq((r & FP_BADDIR), node->is_bad_directory)) {
853 log_info(LD_DIRSERV, "Router '%s' is now a %s directory", description,
854 (r & FP_BADDIR) ? "bad" : "good");
855 node->is_bad_directory = (r&FP_BADDIR) ? 1: 0;
857 if (bool_neq((r & FP_BADEXIT), node->is_bad_exit)) {
858 log_info(LD_DIRSERV, "Router '%s' is now a %s exit", description,
859 (r & FP_BADEXIT) ? "bad" : "good");
860 node->is_bad_exit = (r&FP_BADEXIT) ? 1: 0;
862 } SMARTLIST_FOREACH_END(node);
864 routerlist_assert_ok(rl);
865 smartlist_free(nodes);
869 * Allocate and return a description of the status of the server <b>desc</b>,
870 * for use in a v1-style router-status line. The server is listed
871 * as running iff <b>is_live</b> is true.
873 static char *
874 list_single_server_status(const routerinfo_t *desc, int is_live)
876 char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
877 char *cp;
878 const node_t *node;
880 tor_assert(desc);
882 cp = buf;
883 if (!is_live) {
884 *cp++ = '!';
886 node = node_get_by_id(desc->cache_info.identity_digest);
887 if (node && node->is_valid) {
888 strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
889 cp += strlen(cp);
890 *cp++ = '=';
892 *cp++ = '$';
893 base16_encode(cp, HEX_DIGEST_LEN+1, desc->cache_info.identity_digest,
894 DIGEST_LEN);
895 return tor_strdup(buf);
898 /* DOCDOC running_long_enough_to_decide_unreachable */
899 static INLINE int
900 running_long_enough_to_decide_unreachable(void)
902 return time_of_process_start
903 + get_options()->TestingAuthDirTimeToLearnReachability < approx_time();
906 /** Each server needs to have passed a reachability test no more
907 * than this number of seconds ago, or he is listed as down in
908 * the directory. */
909 #define REACHABLE_TIMEOUT (45*60)
911 /** If we tested a router and found it reachable _at least this long_ after it
912 * declared itself hibernating, it is probably done hibernating and we just
913 * missed a descriptor from it. */
914 #define HIBERNATION_PUBLICATION_SKEW (60*60)
916 /** Treat a router as alive if
917 * - It's me, and I'm not hibernating.
918 * or - We've found it reachable recently. */
919 void
920 dirserv_set_router_is_running(routerinfo_t *router, time_t now)
922 /*XXXX024 This function is a mess. Separate out the part that calculates
923 whether it's reachable and the part that tells rephist that the router was
924 unreachable.
926 int answer;
927 const or_options_t *options = get_options();
928 node_t *node = node_get_mutable_by_id(router->cache_info.identity_digest);
929 tor_assert(node);
931 if (router_is_me(router)) {
932 /* We always know if we are down ourselves. */
933 answer = ! we_are_hibernating();
934 } else if (router->is_hibernating &&
935 (router->cache_info.published_on +
936 HIBERNATION_PUBLICATION_SKEW) > node->last_reachable) {
937 /* A hibernating router is down unless we (somehow) had contact with it
938 * since it declared itself to be hibernating. */
939 answer = 0;
940 } else if (options->AssumeReachable) {
941 /* If AssumeReachable, everybody is up unless they say they are down! */
942 answer = 1;
943 } else {
944 /* Otherwise, a router counts as up if we found all announced OR
945 ports reachable in the last REACHABLE_TIMEOUT seconds.
947 XXX prop186 For now there's always one IPv4 and at most one
948 IPv6 OR port.
950 If we're not on IPv6, don't consider reachability of potential
951 IPv6 OR port since that'd kill all dual stack relays until a
952 majority of the dir auths have IPv6 connectivity. */
953 answer = (now < node->last_reachable + REACHABLE_TIMEOUT &&
954 (options->AuthDirHasIPv6Connectivity != 1 ||
955 tor_addr_is_null(&router->ipv6_addr) ||
956 now < node->last_reachable6 + REACHABLE_TIMEOUT));
959 if (!answer && running_long_enough_to_decide_unreachable()) {
960 /* Not considered reachable. tell rephist about that.
962 Because we launch a reachability test for each router every
963 REACHABILITY_TEST_CYCLE_PERIOD seconds, then the router has probably
964 been down since at least that time after we last successfully reached
967 XXX ipv6
969 time_t when = now;
970 if (node->last_reachable &&
971 node->last_reachable + REACHABILITY_TEST_CYCLE_PERIOD < now)
972 when = node->last_reachable + REACHABILITY_TEST_CYCLE_PERIOD;
973 rep_hist_note_router_unreachable(router->cache_info.identity_digest, when);
976 node->is_running = answer;
979 /** Based on the routerinfo_ts in <b>routers</b>, allocate the
980 * contents of a v1-style router-status line, and store it in
981 * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
983 * If for_controller is true, include the routers with very old descriptors.
986 list_server_status_v1(smartlist_t *routers, char **router_status_out,
987 int for_controller)
989 /* List of entries in a router-status style: An optional !, then an optional
990 * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
991 smartlist_t *rs_entries;
992 time_t now = time(NULL);
993 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
994 const or_options_t *options = get_options();
995 /* We include v2 dir auths here too, because they need to answer
996 * controllers. Eventually we'll deprecate this whole function;
997 * see also networkstatus_getinfo_by_purpose(). */
998 int authdir = authdir_mode_publishes_statuses(options);
999 tor_assert(router_status_out);
1001 rs_entries = smartlist_new();
1003 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
1004 const node_t *node = node_get_by_id(ri->cache_info.identity_digest);
1005 tor_assert(node);
1006 if (authdir) {
1007 /* Update router status in routerinfo_t. */
1008 dirserv_set_router_is_running(ri, now);
1010 if (for_controller) {
1011 char name_buf[MAX_VERBOSE_NICKNAME_LEN+2];
1012 char *cp = name_buf;
1013 if (!node->is_running)
1014 *cp++ = '!';
1015 router_get_verbose_nickname(cp, ri);
1016 smartlist_add(rs_entries, tor_strdup(name_buf));
1017 } else if (ri->cache_info.published_on >= cutoff) {
1018 smartlist_add(rs_entries, list_single_server_status(ri,
1019 node->is_running));
1021 } SMARTLIST_FOREACH_END(ri);
1023 *router_status_out = smartlist_join_strings(rs_entries, " ", 0, NULL);
1025 SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
1026 smartlist_free(rs_entries);
1028 return 0;
1031 /** Given a (possibly empty) list of config_line_t, each line of which contains
1032 * a list of comma-separated version numbers surrounded by optional space,
1033 * allocate and return a new string containing the version numbers, in order,
1034 * separated by commas. Used to generate Recommended(Client|Server)?Versions
1036 static char *
1037 format_versions_list(config_line_t *ln)
1039 smartlist_t *versions;
1040 char *result;
1041 versions = smartlist_new();
1042 for ( ; ln; ln = ln->next) {
1043 smartlist_split_string(versions, ln->value, ",",
1044 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1046 sort_version_list(versions, 1);
1047 result = smartlist_join_strings(versions,",",0,NULL);
1048 SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
1049 smartlist_free(versions);
1050 return result;
1053 /** Return 1 if <b>ri</b>'s descriptor is "active" -- running, valid,
1054 * not hibernating, and not too old. Else return 0.
1056 static int
1057 router_is_active(const routerinfo_t *ri, const node_t *node, time_t now)
1059 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
1060 if (ri->cache_info.published_on < cutoff)
1061 return 0;
1062 if (!node->is_running || !node->is_valid || ri->is_hibernating)
1063 return 0;
1064 return 1;
1067 /** Generate a new v1 directory and write it into a newly allocated string.
1068 * Point *<b>dir_out</b> to the allocated string. Sign the
1069 * directory with <b>private_key</b>. Return 0 on success, -1 on
1070 * failure. If <b>complete</b> is set, give us all the descriptors;
1071 * otherwise leave out non-running and non-valid ones.
1074 dirserv_dump_directory_to_string(char **dir_out,
1075 crypto_pk_t *private_key)
1077 /* XXXX 024 Get rid of this function if we can confirm that nobody's
1078 * fetching these any longer */
1079 char *cp;
1080 char *identity_pkey; /* Identity key, DER64-encoded. */
1081 char *recommended_versions;
1082 char digest[DIGEST_LEN];
1083 char published[ISO_TIME_LEN+1];
1084 char *buf = NULL;
1085 size_t buf_len;
1086 size_t identity_pkey_len;
1087 time_t now = time(NULL);
1089 tor_assert(dir_out);
1090 *dir_out = NULL;
1092 if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
1093 &identity_pkey_len)<0) {
1094 log_warn(LD_BUG,"write identity_pkey to string failed!");
1095 return -1;
1098 recommended_versions =
1099 format_versions_list(get_options()->RecommendedVersions);
1101 format_iso_time(published, now);
1103 buf_len = 2048+strlen(recommended_versions);
1105 buf = tor_malloc(buf_len);
1106 /* We'll be comparing against buf_len throughout the rest of the
1107 function, though strictly speaking we shouldn't be able to exceed
1108 it. This is C, after all, so we may as well check for buffer
1109 overruns.*/
1111 tor_snprintf(buf, buf_len,
1112 "signed-directory\n"
1113 "published %s\n"
1114 "recommended-software %s\n"
1115 "router-status %s\n"
1116 "dir-signing-key\n%s\n",
1117 published, recommended_versions, "",
1118 identity_pkey);
1120 tor_free(recommended_versions);
1121 tor_free(identity_pkey);
1123 cp = buf + strlen(buf);
1124 *cp = '\0';
1126 /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
1127 signature. */
1128 if (strlcat(buf, "directory-signature ", buf_len) >= buf_len)
1129 goto truncated;
1130 if (strlcat(buf, get_options()->Nickname, buf_len) >= buf_len)
1131 goto truncated;
1132 if (strlcat(buf, "\n", buf_len) >= buf_len)
1133 goto truncated;
1135 if (router_get_dir_hash(buf,digest)) {
1136 log_warn(LD_BUG,"couldn't compute digest");
1137 tor_free(buf);
1138 return -1;
1140 note_crypto_pk_op(SIGN_DIR);
1141 if (router_append_dirobj_signature(buf,buf_len,digest,DIGEST_LEN,
1142 private_key)<0) {
1143 tor_free(buf);
1144 return -1;
1147 *dir_out = buf;
1148 return 0;
1149 truncated:
1150 log_warn(LD_BUG,"tried to exceed string length.");
1151 tor_free(buf);
1152 return -1;
1155 /********************************************************************/
1157 /* A set of functions to answer questions about how we'd like to behave
1158 * as a directory mirror/client. */
1160 /** Return 1 if we fetch our directory material directly from the
1161 * authorities, rather than from a mirror. */
1163 directory_fetches_from_authorities(const or_options_t *options)
1165 const routerinfo_t *me;
1166 uint32_t addr;
1167 int refuseunknown;
1168 if (options->FetchDirInfoEarly)
1169 return 1;
1170 if (options->BridgeRelay == 1)
1171 return 0;
1172 if (server_mode(options) && router_pick_published_address(options, &addr)<0)
1173 return 1; /* we don't know our IP address; ask an authority. */
1174 refuseunknown = ! router_my_exit_policy_is_reject_star() &&
1175 should_refuse_unknown_exits(options);
1176 if (!options->DirPort_set && !refuseunknown)
1177 return 0;
1178 if (!server_mode(options) || !advertised_server_mode())
1179 return 0;
1180 me = router_get_my_routerinfo();
1181 if (!me || (!me->dir_port && !refuseunknown))
1182 return 0; /* if dirport not advertised, return 0 too */
1183 return 1;
1186 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1187 * on the "mirror" schedule rather than the "client" schedule.
1190 directory_fetches_dir_info_early(const or_options_t *options)
1192 return directory_fetches_from_authorities(options);
1195 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1196 * on a very passive schedule -- waiting long enough for ordinary clients
1197 * to probably have the info we want. These would include bridge users,
1198 * and maybe others in the future e.g. if a Tor client uses another Tor
1199 * client as a directory guard.
1202 directory_fetches_dir_info_later(const or_options_t *options)
1204 return options->UseBridges != 0;
1207 /** Return true iff we want to fetch and keep certificates for authorities
1208 * that we don't acknowledge as aurthorities ourself.
1211 directory_caches_unknown_auth_certs(const or_options_t *options)
1213 return options->DirPort_set || options->BridgeRelay;
1216 /** Return 1 if we want to keep descriptors, networkstatuses, etc around
1217 * and we're willing to serve them to others. Else return 0.
1220 directory_caches_dir_info(const or_options_t *options)
1222 if (options->BridgeRelay || options->DirPort_set)
1223 return 1;
1224 if (!server_mode(options) || !advertised_server_mode())
1225 return 0;
1226 /* We need an up-to-date view of network info if we're going to try to
1227 * block exit attempts from unknown relays. */
1228 return ! router_my_exit_policy_is_reject_star() &&
1229 should_refuse_unknown_exits(options);
1232 /** Return 1 if we want to allow remote people to ask us directory
1233 * requests via the "begin_dir" interface, which doesn't require
1234 * having any separate port open. */
1236 directory_permits_begindir_requests(const or_options_t *options)
1238 return options->BridgeRelay != 0 || options->DirPort_set;
1241 /** Return 1 if we have no need to fetch new descriptors. This generally
1242 * happens when we're not a dir cache and we haven't built any circuits
1243 * lately.
1246 directory_too_idle_to_fetch_descriptors(const or_options_t *options,
1247 time_t now)
1249 return !directory_caches_dir_info(options) &&
1250 !options->FetchUselessDescriptors &&
1251 rep_hist_circbuilding_dormant(now);
1254 /********************************************************************/
1256 /** Map from flavor name to the cached_dir_t for the v3 consensuses that we're
1257 * currently serving. */
1258 static strmap_t *cached_consensuses = NULL;
1260 /** Decrement the reference count on <b>d</b>, and free it if it no longer has
1261 * any references. */
1262 void
1263 cached_dir_decref(cached_dir_t *d)
1265 if (!d || --d->refcnt > 0)
1266 return;
1267 clear_cached_dir(d);
1268 tor_free(d);
1271 /** Allocate and return a new cached_dir_t containing the string <b>s</b>,
1272 * published at <b>published</b>. */
1273 cached_dir_t *
1274 new_cached_dir(char *s, time_t published)
1276 cached_dir_t *d = tor_malloc_zero(sizeof(cached_dir_t));
1277 d->refcnt = 1;
1278 d->dir = s;
1279 d->dir_len = strlen(s);
1280 d->published = published;
1281 if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
1282 ZLIB_METHOD)) {
1283 log_warn(LD_BUG, "Error compressing directory");
1285 return d;
1288 /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
1289 static void
1290 clear_cached_dir(cached_dir_t *d)
1292 tor_free(d->dir);
1293 tor_free(d->dir_z);
1294 memset(d, 0, sizeof(cached_dir_t));
1297 /** Free all storage held by the cached_dir_t in <b>d</b>. */
1298 static void
1299 free_cached_dir_(void *_d)
1301 cached_dir_t *d;
1302 if (!_d)
1303 return;
1305 d = (cached_dir_t *)_d;
1306 cached_dir_decref(d);
1309 /** Replace the v3 consensus networkstatus of type <b>flavor_name</b> that
1310 * we're serving with <b>networkstatus</b>, published at <b>published</b>. No
1311 * validation is performed. */
1312 void
1313 dirserv_set_cached_consensus_networkstatus(const char *networkstatus,
1314 const char *flavor_name,
1315 const digests_t *digests,
1316 time_t published)
1318 cached_dir_t *new_networkstatus;
1319 cached_dir_t *old_networkstatus;
1320 if (!cached_consensuses)
1321 cached_consensuses = strmap_new();
1323 new_networkstatus = new_cached_dir(tor_strdup(networkstatus), published);
1324 memcpy(&new_networkstatus->digests, digests, sizeof(digests_t));
1325 old_networkstatus = strmap_set(cached_consensuses, flavor_name,
1326 new_networkstatus);
1327 if (old_networkstatus)
1328 cached_dir_decref(old_networkstatus);
1331 /** Return the latest downloaded consensus networkstatus in encoded, signed,
1332 * optionally compressed format, suitable for sending to clients. */
1333 cached_dir_t *
1334 dirserv_get_consensus(const char *flavor_name)
1336 if (!cached_consensuses)
1337 return NULL;
1338 return strmap_get(cached_consensuses, flavor_name);
1341 /** If a router's uptime is at least this value, then it is always
1342 * considered stable, regardless of the rest of the network. This
1343 * way we resist attacks where an attacker doubles the size of the
1344 * network using allegedly high-uptime nodes, displacing all the
1345 * current guards. */
1346 #define UPTIME_TO_GUARANTEE_STABLE (3600*24*30)
1347 /** If a router's MTBF is at least this value, then it is always stable.
1348 * See above. (Corresponds to about 7 days for current decay rates.) */
1349 #define MTBF_TO_GUARANTEE_STABLE (60*60*24*5)
1350 /** Similarly, every node with at least this much weighted time known can be
1351 * considered familiar enough to be a guard. Corresponds to about 20 days for
1352 * current decay rates.
1354 #define TIME_KNOWN_TO_GUARANTEE_FAMILIAR (8*24*60*60)
1355 /** Similarly, every node with sufficient WFU is around enough to be a guard.
1357 #define WFU_TO_GUARANTEE_GUARD (0.98)
1359 /* Thresholds for server performance: set by
1360 * dirserv_compute_performance_thresholds, and used by
1361 * generate_v2_networkstatus */
1363 /** Any router with an uptime of at least this value is stable. */
1364 static uint32_t stable_uptime = 0; /* start at a safe value */
1365 /** Any router with an mtbf of at least this value is stable. */
1366 static double stable_mtbf = 0.0;
1367 /** If true, we have measured enough mtbf info to look at stable_mtbf rather
1368 * than stable_uptime. */
1369 static int enough_mtbf_info = 0;
1370 /** Any router with a weighted fractional uptime of at least this much might
1371 * be good as a guard. */
1372 static double guard_wfu = 0.0;
1373 /** Don't call a router a guard unless we've known about it for at least this
1374 * many seconds. */
1375 static long guard_tk = 0;
1376 /** Any router with a bandwidth at least this high is "Fast" */
1377 static uint32_t fast_bandwidth_kb = 0;
1378 /** If exits can be guards, then all guards must have a bandwidth this
1379 * high. */
1380 static uint32_t guard_bandwidth_including_exits_kb = 0;
1381 /** If exits can't be guards, then all guards must have a bandwidth this
1382 * high. */
1383 static uint32_t guard_bandwidth_excluding_exits_kb = 0;
1385 /** Helper: estimate the uptime of a router given its stated uptime and the
1386 * amount of time since it last stated its stated uptime. */
1387 static INLINE long
1388 real_uptime(const routerinfo_t *router, time_t now)
1390 if (now < router->cache_info.published_on)
1391 return router->uptime;
1392 else
1393 return router->uptime + (now - router->cache_info.published_on);
1396 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1397 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1398 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1399 * bandwidth.
1401 static int
1402 dirserv_thinks_router_is_unreliable(time_t now,
1403 routerinfo_t *router,
1404 int need_uptime, int need_capacity)
1406 if (need_uptime) {
1407 if (!enough_mtbf_info) {
1408 /* XXX024 Once most authorities are on v3, we should change the rule from
1409 * "use uptime if we don't have mtbf data" to "don't advertise Stable on
1410 * v3 if we don't have enough mtbf data." Or maybe not, since if we ever
1411 * hit a point where we need to reset a lot of authorities at once,
1412 * none of them would be in a position to declare Stable.
1414 long uptime = real_uptime(router, now);
1415 if ((unsigned)uptime < stable_uptime &&
1416 (unsigned)uptime < UPTIME_TO_GUARANTEE_STABLE)
1417 return 1;
1418 } else {
1419 double mtbf =
1420 rep_hist_get_stability(router->cache_info.identity_digest, now);
1421 if (mtbf < stable_mtbf &&
1422 mtbf < MTBF_TO_GUARANTEE_STABLE)
1423 return 1;
1426 if (need_capacity) {
1427 uint32_t bw_kb = dirserv_get_credible_bandwidth_kb(router);
1428 if (bw_kb < fast_bandwidth_kb)
1429 return 1;
1431 return 0;
1434 /** Return true iff <b>router</b> should be assigned the "HSDir" flag.
1435 * Right now this means it advertises support for it, it has a high
1436 * uptime, it has a DirPort open, and it's currently considered Running.
1438 * This function needs to be called after router-\>is_running has
1439 * been set.
1441 static int
1442 dirserv_thinks_router_is_hs_dir(const routerinfo_t *router,
1443 const node_t *node, time_t now)
1446 long uptime;
1448 /* If we haven't been running for at least
1449 * get_options()->MinUptimeHidServDirectoryV2 seconds, we can't
1450 * have accurate data telling us a relay has been up for at least
1451 * that long. We also want to allow a bit of slack: Reachability
1452 * tests aren't instant. If we haven't been running long enough,
1453 * trust the relay. */
1455 if (stats_n_seconds_working >
1456 get_options()->MinUptimeHidServDirectoryV2 * 1.1)
1457 uptime = MIN(rep_hist_get_uptime(router->cache_info.identity_digest, now),
1458 real_uptime(router, now));
1459 else
1460 uptime = real_uptime(router, now);
1462 /* XXX We shouldn't need to check dir_port, but we do because of
1463 * bug 1693. In the future, once relays set wants_to_be_hs_dir
1464 * correctly, we can revert to only checking dir_port if router's
1465 * version is too old. */
1466 /* XXX Unfortunately, we need to keep checking dir_port until all
1467 * *clients* suffering from bug 2722 are obsolete. The first version
1468 * to fix the bug was 0.2.2.25-alpha. */
1469 return (router->wants_to_be_hs_dir && router->dir_port &&
1470 uptime >= get_options()->MinUptimeHidServDirectoryV2 &&
1471 node->is_running);
1474 /** Don't consider routers with less bandwidth than this when computing
1475 * thresholds. */
1476 #define ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER_KB 4
1478 /** Helper for dirserv_compute_performance_thresholds(): Decide whether to
1479 * include a router in our calculations, and return true iff we should; the
1480 * require_mbw parameter is passed in by
1481 * dirserv_compute_performance_thresholds() and controls whether we ever
1482 * count routers with only advertised bandwidths */
1483 static int
1484 router_counts_toward_thresholds(const node_t *node, time_t now,
1485 const digestmap_t *omit_as_sybil,
1486 int require_mbw)
1488 /* Have measured bw? */
1489 int have_mbw =
1490 dirserv_has_measured_bw(node->identity);
1491 uint64_t min_bw_kb = ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER_KB;
1492 const or_options_t *options = get_options();
1494 if (options->TestingTorNetwork) {
1495 min_bw_kb = (int64_t)options->TestingMinExitFlagThreshold / 1000;
1498 return node->ri && router_is_active(node->ri, node, now) &&
1499 !digestmap_get(omit_as_sybil, node->identity) &&
1500 (dirserv_get_credible_bandwidth_kb(node->ri) >= min_bw_kb) &&
1501 (have_mbw || !require_mbw);
1504 /** Look through the routerlist, the Mean Time Between Failure history, and
1505 * the Weighted Fractional Uptime history, and use them to set thresholds for
1506 * the Stable, Fast, and Guard flags. Update the fields stable_uptime,
1507 * stable_mtbf, enough_mtbf_info, guard_wfu, guard_tk, fast_bandwidth,
1508 * guard_bandwidth_including_exits, and guard_bandwidth_excluding_exits.
1510 * Also, set the is_exit flag of each router appropriately. */
1511 static void
1512 dirserv_compute_performance_thresholds(routerlist_t *rl,
1513 digestmap_t *omit_as_sybil)
1515 int n_active, n_active_nonexit, n_familiar;
1516 uint32_t *uptimes, *bandwidths_kb, *bandwidths_excluding_exits_kb;
1517 long *tks;
1518 double *mtbfs, *wfus;
1519 time_t now = time(NULL);
1520 const or_options_t *options = get_options();
1522 /* Require mbw? */
1523 int require_mbw =
1524 (routers_with_measured_bw >
1525 options->MinMeasuredBWsForAuthToIgnoreAdvertised) ? 1 : 0;
1527 /* initialize these all here, in case there are no routers */
1528 stable_uptime = 0;
1529 stable_mtbf = 0;
1530 fast_bandwidth_kb = 0;
1531 guard_bandwidth_including_exits_kb = 0;
1532 guard_bandwidth_excluding_exits_kb = 0;
1533 guard_tk = 0;
1534 guard_wfu = 0;
1536 /* Initialize arrays that will hold values for each router. We'll
1537 * sort them and use that to compute thresholds. */
1538 n_active = n_active_nonexit = 0;
1539 /* Uptime for every active router. */
1540 uptimes = tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
1541 /* Bandwidth for every active router. */
1542 bandwidths_kb = tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
1543 /* Bandwidth for every active non-exit router. */
1544 bandwidths_excluding_exits_kb =
1545 tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
1546 /* Weighted mean time between failure for each active router. */
1547 mtbfs = tor_malloc(sizeof(double)*smartlist_len(rl->routers));
1548 /* Time-known for each active router. */
1549 tks = tor_malloc(sizeof(long)*smartlist_len(rl->routers));
1550 /* Weighted fractional uptime for each active router. */
1551 wfus = tor_malloc(sizeof(double)*smartlist_len(rl->routers));
1553 nodelist_assert_ok();
1555 /* Now, fill in the arrays. */
1556 SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), node_t *, node) {
1557 if (options->BridgeAuthoritativeDir &&
1558 node->ri &&
1559 node->ri->purpose != ROUTER_PURPOSE_BRIDGE)
1560 continue;
1561 if (router_counts_toward_thresholds(node, now, omit_as_sybil,
1562 require_mbw)) {
1563 routerinfo_t *ri = node->ri;
1564 const char *id = node->identity;
1565 uint32_t bw_kb;
1566 node->is_exit = (!router_exit_policy_rejects_all(ri) &&
1567 exit_policy_is_general_exit(ri->exit_policy));
1568 uptimes[n_active] = (uint32_t)real_uptime(ri, now);
1569 mtbfs[n_active] = rep_hist_get_stability(id, now);
1570 tks [n_active] = rep_hist_get_weighted_time_known(id, now);
1571 bandwidths_kb[n_active] = bw_kb = dirserv_get_credible_bandwidth_kb(ri);
1572 if (!node->is_exit || node->is_bad_exit) {
1573 bandwidths_excluding_exits_kb[n_active_nonexit] = bw_kb;
1574 ++n_active_nonexit;
1576 ++n_active;
1578 } SMARTLIST_FOREACH_END(node);
1580 /* Now, compute thresholds. */
1581 if (n_active) {
1582 /* The median uptime is stable. */
1583 stable_uptime = median_uint32(uptimes, n_active);
1584 /* The median mtbf is stable, if we have enough mtbf info */
1585 stable_mtbf = median_double(mtbfs, n_active);
1586 /* The 12.5th percentile bandwidth is fast. */
1587 fast_bandwidth_kb = find_nth_uint32(bandwidths_kb, n_active, n_active/8);
1588 /* (Now bandwidths is sorted.) */
1589 if (fast_bandwidth_kb < ROUTER_REQUIRED_MIN_BANDWIDTH/(2 * 1000))
1590 fast_bandwidth_kb = bandwidths_kb[n_active/4];
1591 guard_bandwidth_including_exits_kb = bandwidths_kb[n_active*3/4];
1592 guard_tk = find_nth_long(tks, n_active, n_active/8);
1595 if (guard_tk > TIME_KNOWN_TO_GUARANTEE_FAMILIAR)
1596 guard_tk = TIME_KNOWN_TO_GUARANTEE_FAMILIAR;
1599 /* We can vote on a parameter for the minimum and maximum. */
1600 #define ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG 4
1601 int32_t min_fast_kb, max_fast_kb, min_fast, max_fast;
1602 min_fast = networkstatus_get_param(NULL, "FastFlagMinThreshold",
1603 ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG,
1604 ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG,
1605 INT32_MAX);
1606 if (options->TestingTorNetwork) {
1607 min_fast = (int32_t)options->TestingMinFastFlagThreshold;
1609 max_fast = networkstatus_get_param(NULL, "FastFlagMaxThreshold",
1610 INT32_MAX, min_fast, INT32_MAX);
1611 min_fast_kb = min_fast / 1000;
1612 max_fast_kb = max_fast / 1000;
1614 if (fast_bandwidth_kb < (uint32_t)min_fast_kb)
1615 fast_bandwidth_kb = min_fast_kb;
1616 if (fast_bandwidth_kb > (uint32_t)max_fast_kb)
1617 fast_bandwidth_kb = max_fast_kb;
1619 /* Protect sufficiently fast nodes from being pushed out of the set
1620 * of Fast nodes. */
1621 if (options->AuthDirFastGuarantee &&
1622 fast_bandwidth_kb > options->AuthDirFastGuarantee/1000)
1623 fast_bandwidth_kb = (uint32_t)options->AuthDirFastGuarantee/1000;
1625 /* Now that we have a time-known that 7/8 routers are known longer than,
1626 * fill wfus with the wfu of every such "familiar" router. */
1627 n_familiar = 0;
1629 SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), node_t *, node) {
1630 if (router_counts_toward_thresholds(node, now,
1631 omit_as_sybil, require_mbw)) {
1632 routerinfo_t *ri = node->ri;
1633 const char *id = ri->cache_info.identity_digest;
1634 long tk = rep_hist_get_weighted_time_known(id, now);
1635 if (tk < guard_tk)
1636 continue;
1637 wfus[n_familiar++] = rep_hist_get_weighted_fractional_uptime(id, now);
1639 } SMARTLIST_FOREACH_END(node);
1640 if (n_familiar)
1641 guard_wfu = median_double(wfus, n_familiar);
1642 if (guard_wfu > WFU_TO_GUARANTEE_GUARD)
1643 guard_wfu = WFU_TO_GUARANTEE_GUARD;
1645 enough_mtbf_info = rep_hist_have_measured_enough_stability();
1647 if (n_active_nonexit) {
1648 guard_bandwidth_excluding_exits_kb =
1649 find_nth_uint32(bandwidths_excluding_exits_kb,
1650 n_active_nonexit, n_active_nonexit*3/4);
1653 log_info(LD_DIRSERV,
1654 "Cutoffs: For Stable, %lu sec uptime, %lu sec MTBF. "
1655 "For Fast: %lu kilobytes/sec. "
1656 "For Guard: WFU %.03f%%, time-known %lu sec, "
1657 "and bandwidth %lu or %lu kilobytes/sec. "
1658 "We%s have enough stability data.",
1659 (unsigned long)stable_uptime,
1660 (unsigned long)stable_mtbf,
1661 (unsigned long)fast_bandwidth_kb,
1662 guard_wfu*100,
1663 (unsigned long)guard_tk,
1664 (unsigned long)guard_bandwidth_including_exits_kb,
1665 (unsigned long)guard_bandwidth_excluding_exits_kb,
1666 enough_mtbf_info ? "" : " don't ");
1668 tor_free(uptimes);
1669 tor_free(mtbfs);
1670 tor_free(bandwidths_kb);
1671 tor_free(bandwidths_excluding_exits_kb);
1672 tor_free(tks);
1673 tor_free(wfus);
1676 /* Use dirserv_compute_performance_thresholds() to compute the thresholds
1677 * for the status flags, specifically for bridges.
1679 * This is only called by a Bridge Authority from
1680 * networkstatus_getinfo_by_purpose().
1682 void
1683 dirserv_compute_bridge_flag_thresholds(routerlist_t *rl)
1686 digestmap_t *omit_as_sybil = digestmap_new();
1687 dirserv_compute_performance_thresholds(rl, omit_as_sybil);
1688 digestmap_free(omit_as_sybil, NULL);
1691 /** Measured bandwidth cache entry */
1692 typedef struct mbw_cache_entry_s {
1693 long mbw_kb;
1694 time_t as_of;
1695 } mbw_cache_entry_t;
1697 /** Measured bandwidth cache - keys are identity_digests, values are
1698 * mbw_cache_entry_t *. */
1699 static digestmap_t *mbw_cache = NULL;
1701 /** Store a measured bandwidth cache entry when reading the measured
1702 * bandwidths file. */
1703 STATIC void
1704 dirserv_cache_measured_bw(const measured_bw_line_t *parsed_line,
1705 time_t as_of)
1707 mbw_cache_entry_t *e = NULL;
1709 tor_assert(parsed_line);
1711 /* Allocate a cache if we need */
1712 if (!mbw_cache) mbw_cache = digestmap_new();
1714 /* Check if we have an existing entry */
1715 e = digestmap_get(mbw_cache, parsed_line->node_id);
1716 /* If we do, we can re-use it */
1717 if (e) {
1718 /* Check that we really are newer, and update */
1719 if (as_of > e->as_of) {
1720 e->mbw_kb = parsed_line->bw_kb;
1721 e->as_of = as_of;
1723 } else {
1724 /* We'll have to insert a new entry */
1725 e = tor_malloc(sizeof(*e));
1726 e->mbw_kb = parsed_line->bw_kb;
1727 e->as_of = as_of;
1728 digestmap_set(mbw_cache, parsed_line->node_id, e);
1732 /** Clear and free the measured bandwidth cache */
1733 STATIC void
1734 dirserv_clear_measured_bw_cache(void)
1736 if (mbw_cache) {
1737 /* Free the map and all entries */
1738 digestmap_free(mbw_cache, tor_free_);
1739 mbw_cache = NULL;
1743 /** Scan the measured bandwidth cache and remove expired entries */
1744 STATIC void
1745 dirserv_expire_measured_bw_cache(time_t now)
1748 if (mbw_cache) {
1749 /* Iterate through the cache and check each entry */
1750 DIGESTMAP_FOREACH_MODIFY(mbw_cache, k, mbw_cache_entry_t *, e) {
1751 if (now > e->as_of + MAX_MEASUREMENT_AGE) {
1752 tor_free(e);
1753 MAP_DEL_CURRENT(k);
1755 } DIGESTMAP_FOREACH_END;
1757 /* Check if we cleared the whole thing and free if so */
1758 if (digestmap_size(mbw_cache) == 0) {
1759 digestmap_free(mbw_cache, tor_free_);
1760 mbw_cache = 0;
1765 /** Get the current size of the measured bandwidth cache */
1766 STATIC int
1767 dirserv_get_measured_bw_cache_size(void)
1769 if (mbw_cache) return digestmap_size(mbw_cache);
1770 else return 0;
1773 /** Query the cache by identity digest, return value indicates whether
1774 * we found it. The bw_out and as_of_out pointers receive the cached
1775 * bandwidth value and the time it was cached if not NULL. */
1776 STATIC int
1777 dirserv_query_measured_bw_cache_kb(const char *node_id, long *bw_kb_out,
1778 time_t *as_of_out)
1780 mbw_cache_entry_t *v = NULL;
1781 int rv = 0;
1783 if (mbw_cache && node_id) {
1784 v = digestmap_get(mbw_cache, node_id);
1785 if (v) {
1786 /* Found something */
1787 rv = 1;
1788 if (bw_kb_out) *bw_kb_out = v->mbw_kb;
1789 if (as_of_out) *as_of_out = v->as_of;
1793 return rv;
1796 /** Predicate wrapper for dirserv_query_measured_bw_cache() */
1797 STATIC int
1798 dirserv_has_measured_bw(const char *node_id)
1800 return dirserv_query_measured_bw_cache_kb(node_id, NULL, NULL);
1803 /** Get the best estimate of a router's bandwidth for dirauth purposes,
1804 * preferring measured to advertised values if available. */
1806 static uint32_t
1807 dirserv_get_bandwidth_for_router_kb(const routerinfo_t *ri)
1809 uint32_t bw_kb = 0;
1811 * Yeah, measured bandwidths in measured_bw_line_t are (implicitly
1812 * signed) longs and the ones router_get_advertised_bandwidth() returns
1813 * are uint32_t.
1815 long mbw_kb = 0;
1817 if (ri) {
1819 * * First try to see if we have a measured bandwidth; don't bother with
1820 * as_of_out here, on the theory that a stale measured bandwidth is still
1821 * better to trust than an advertised one.
1823 if (dirserv_query_measured_bw_cache_kb(ri->cache_info.identity_digest,
1824 &mbw_kb, NULL)) {
1825 /* Got one! */
1826 bw_kb = (uint32_t)mbw_kb;
1827 } else {
1828 /* If not, fall back to advertised */
1829 bw_kb = router_get_advertised_bandwidth(ri) / 1000;
1833 return bw_kb;
1836 /** Look through the routerlist, and using the measured bandwidth cache count
1837 * how many measured bandwidths we know. This is used to decide whether we
1838 * ever trust advertised bandwidths for purposes of assigning flags. */
1839 static void
1840 dirserv_count_measured_bws(routerlist_t *rl)
1842 /* Initialize this first */
1843 routers_with_measured_bw = 0;
1845 tor_assert(rl);
1846 tor_assert(rl->routers);
1848 /* Iterate over the routerlist and count measured bandwidths */
1849 SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) {
1850 /* Check if we know a measured bandwidth for this one */
1851 if (dirserv_has_measured_bw(ri->cache_info.identity_digest)) {
1852 ++routers_with_measured_bw;
1854 } SMARTLIST_FOREACH_END(ri);
1857 /** Return the bandwidth we believe for assigning flags; prefer measured
1858 * over advertised, and if we have above a threshold quantity of measured
1859 * bandwidths, we don't want to ever give flags to unmeasured routers, so
1860 * return 0. */
1861 static uint32_t
1862 dirserv_get_credible_bandwidth_kb(const routerinfo_t *ri)
1864 int threshold;
1865 uint32_t bw_kb = 0;
1866 long mbw_kb;
1868 tor_assert(ri);
1869 /* Check if we have a measured bandwidth, and check the threshold if not */
1870 if (!(dirserv_query_measured_bw_cache_kb(ri->cache_info.identity_digest,
1871 &mbw_kb, NULL))) {
1872 threshold = get_options()->MinMeasuredBWsForAuthToIgnoreAdvertised;
1873 if (routers_with_measured_bw > threshold) {
1874 /* Return zero for unmeasured bandwidth if we are above threshold */
1875 bw_kb = 0;
1876 } else {
1877 /* Return an advertised bandwidth otherwise */
1878 bw_kb = router_get_advertised_bandwidth_capped(ri) / 1000;
1880 } else {
1881 /* We have the measured bandwidth in mbw */
1882 bw_kb = (uint32_t)mbw_kb;
1885 return bw_kb;
1888 /** Give a statement of our current performance thresholds for inclusion
1889 * in a vote document. */
1890 char *
1891 dirserv_get_flag_thresholds_line(void)
1893 char *result=NULL;
1894 const int measured_threshold =
1895 get_options()->MinMeasuredBWsForAuthToIgnoreAdvertised;
1896 const int enough_measured_bw = routers_with_measured_bw > measured_threshold;
1898 tor_asprintf(&result,
1899 "stable-uptime=%lu stable-mtbf=%lu "
1900 "fast-speed=%lu "
1901 "guard-wfu=%.03f%% guard-tk=%lu "
1902 "guard-bw-inc-exits=%lu guard-bw-exc-exits=%lu "
1903 "enough-mtbf=%d ignoring-advertised-bws=%d",
1904 (unsigned long)stable_uptime,
1905 (unsigned long)stable_mtbf,
1906 (unsigned long)fast_bandwidth_kb*1000,
1907 guard_wfu*100,
1908 (unsigned long)guard_tk,
1909 (unsigned long)guard_bandwidth_including_exits_kb*1000,
1910 (unsigned long)guard_bandwidth_excluding_exits_kb*1000,
1911 enough_mtbf_info ? 1 : 0,
1912 enough_measured_bw ? 1 : 0);
1914 return result;
1917 /** Given a platform string as in a routerinfo_t (possibly null), return a
1918 * newly allocated version string for a networkstatus document, or NULL if the
1919 * platform doesn't give a Tor version. */
1920 static char *
1921 version_from_platform(const char *platform)
1923 if (platform && !strcmpstart(platform, "Tor ")) {
1924 const char *eos = find_whitespace(platform+4);
1925 if (eos && !strcmpstart(eos, " (r")) {
1926 /* XXXX Unify this logic with the other version extraction
1927 * logic in routerparse.c. */
1928 eos = find_whitespace(eos+1);
1930 if (eos) {
1931 return tor_strndup(platform, eos-platform);
1934 return NULL;
1937 /** Helper: write the router-status information in <b>rs</b> into a newly
1938 * allocated character buffer. Use the same format as in network-status
1939 * documents. If <b>version</b> is non-NULL, add a "v" line for the platform.
1940 * Return 0 on success, -1 on failure.
1942 * The format argument has one of the following values:
1943 * NS_V2 - Output an entry suitable for a V2 NS opinion document
1944 * NS_V3_CONSENSUS - Output the first portion of a V3 NS consensus entry
1945 * NS_V3_CONSENSUS_MICRODESC - Output the first portion of a V3 microdesc
1946 * consensus entry.
1947 * NS_V3_VOTE - Output a complete V3 NS vote. If <b>vrs</b> is present,
1948 * it contains additional information for the vote.
1949 * NS_CONTROL_PORT - Output a NS document for the control port
1951 char *
1952 routerstatus_format_entry(const routerstatus_t *rs, const char *version,
1953 routerstatus_format_type_t format,
1954 const vote_routerstatus_t *vrs)
1956 char *summary;
1957 char *result = NULL;
1959 char published[ISO_TIME_LEN+1];
1960 char identity64[BASE64_DIGEST_LEN+1];
1961 char digest64[BASE64_DIGEST_LEN+1];
1962 smartlist_t *chunks = NULL;
1964 format_iso_time(published, rs->published_on);
1965 digest_to_base64(identity64, rs->identity_digest);
1966 digest_to_base64(digest64, rs->descriptor_digest);
1968 chunks = smartlist_new();
1969 smartlist_add_asprintf(chunks,
1970 "r %s %s %s%s%s %s %d %d\n",
1971 rs->nickname,
1972 identity64,
1973 (format==NS_V3_CONSENSUS_MICRODESC)?"":digest64,
1974 (format==NS_V3_CONSENSUS_MICRODESC)?"":" ",
1975 published,
1976 fmt_addr32(rs->addr),
1977 (int)rs->or_port,
1978 (int)rs->dir_port);
1980 /* TODO: Maybe we want to pass in what we need to build the rest of
1981 * this here, instead of in the caller. Then we could use the
1982 * networkstatus_type_t values, with an additional control port value
1983 * added -MP */
1985 /* V3 microdesc consensuses don't have "a" lines. */
1986 if (format == NS_V3_CONSENSUS_MICRODESC)
1987 goto done;
1989 /* Possible "a" line. At most one for now. */
1990 if (!tor_addr_is_null(&rs->ipv6_addr)) {
1991 smartlist_add_asprintf(chunks, "a %s\n",
1992 fmt_addrport(&rs->ipv6_addr, rs->ipv6_orport));
1995 if (format == NS_V3_CONSENSUS)
1996 goto done;
1998 smartlist_add_asprintf(chunks,
1999 "s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
2000 /* These must stay in alphabetical order. */
2001 rs->is_authority?" Authority":"",
2002 rs->is_bad_directory?" BadDirectory":"",
2003 rs->is_bad_exit?" BadExit":"",
2004 rs->is_exit?" Exit":"",
2005 rs->is_fast?" Fast":"",
2006 rs->is_possible_guard?" Guard":"",
2007 rs->is_hs_dir?" HSDir":"",
2008 rs->is_named?" Named":"",
2009 rs->is_flagged_running?" Running":"",
2010 rs->is_stable?" Stable":"",
2011 rs->is_unnamed?" Unnamed":"",
2012 (rs->dir_port!=0)?" V2Dir":"",
2013 rs->is_valid?" Valid":"");
2015 /* length of "opt v \n" */
2016 #define V_LINE_OVERHEAD 7
2017 if (version && strlen(version) < MAX_V_LINE_LEN - V_LINE_OVERHEAD) {
2018 smartlist_add_asprintf(chunks, "v %s\n", version);
2021 if (format != NS_V2) {
2022 const routerinfo_t* desc = router_get_by_id_digest(rs->identity_digest);
2023 uint32_t bw_kb;
2025 if (format != NS_CONTROL_PORT) {
2026 /* Blow up more or less nicely if we didn't get anything or not the
2027 * thing we expected.
2029 if (!desc) {
2030 char id[HEX_DIGEST_LEN+1];
2031 char dd[HEX_DIGEST_LEN+1];
2033 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
2034 base16_encode(dd, sizeof(dd), rs->descriptor_digest, DIGEST_LEN);
2035 log_warn(LD_BUG, "Cannot get any descriptor for %s "
2036 "(wanted descriptor %s).",
2037 id, dd);
2038 goto err;
2041 /* This assert could fire for the control port, because
2042 * it can request NS documents before all descriptors
2043 * have been fetched. Therefore, we only do this test when
2044 * format != NS_CONTROL_PORT. */
2045 if (tor_memneq(desc->cache_info.signed_descriptor_digest,
2046 rs->descriptor_digest,
2047 DIGEST_LEN)) {
2048 char rl_d[HEX_DIGEST_LEN+1];
2049 char rs_d[HEX_DIGEST_LEN+1];
2050 char id[HEX_DIGEST_LEN+1];
2052 base16_encode(rl_d, sizeof(rl_d),
2053 desc->cache_info.signed_descriptor_digest, DIGEST_LEN);
2054 base16_encode(rs_d, sizeof(rs_d), rs->descriptor_digest, DIGEST_LEN);
2055 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
2056 log_err(LD_BUG, "descriptor digest in routerlist does not match "
2057 "the one in routerstatus: %s vs %s "
2058 "(router %s)\n",
2059 rl_d, rs_d, id);
2061 tor_assert(tor_memeq(desc->cache_info.signed_descriptor_digest,
2062 rs->descriptor_digest,
2063 DIGEST_LEN));
2067 if (format == NS_CONTROL_PORT && rs->has_bandwidth) {
2068 bw_kb = rs->bandwidth_kb;
2069 } else {
2070 tor_assert(desc);
2071 bw_kb = router_get_advertised_bandwidth_capped(desc) / 1000;
2073 smartlist_add_asprintf(chunks,
2074 "w Bandwidth=%d", bw_kb);
2076 if (format == NS_V3_VOTE && vrs && vrs->has_measured_bw) {
2077 smartlist_add_asprintf(chunks,
2078 " Measured=%d", vrs->measured_bw_kb);
2080 smartlist_add(chunks, tor_strdup("\n"));
2082 if (desc) {
2083 summary = policy_summarize(desc->exit_policy, AF_INET);
2084 smartlist_add_asprintf(chunks, "p %s\n", summary);
2085 tor_free(summary);
2089 done:
2090 result = smartlist_join_strings(chunks, "", 0, NULL);
2092 err:
2093 if (chunks) {
2094 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
2095 smartlist_free(chunks);
2098 return result;
2101 /** Helper for sorting: compares two routerinfos first by address, and then by
2102 * descending order of "usefulness". (An authority is more useful than a
2103 * non-authority; a running router is more useful than a non-running router;
2104 * and a router with more bandwidth is more useful than one with less.)
2106 static int
2107 compare_routerinfo_by_ip_and_bw_(const void **a, const void **b)
2109 routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
2110 int first_is_auth, second_is_auth;
2111 uint32_t bw_kb_first, bw_kb_second;
2112 const node_t *node_first, *node_second;
2113 int first_is_running, second_is_running;
2115 /* we return -1 if first should appear before second... that is,
2116 * if first is a better router. */
2117 if (first->addr < second->addr)
2118 return -1;
2119 else if (first->addr > second->addr)
2120 return 1;
2122 /* Potentially, this next bit could cause k n lg n memeq calls. But in
2123 * reality, we will almost never get here, since addresses will usually be
2124 * different. */
2126 first_is_auth =
2127 router_digest_is_trusted_dir(first->cache_info.identity_digest);
2128 second_is_auth =
2129 router_digest_is_trusted_dir(second->cache_info.identity_digest);
2131 if (first_is_auth && !second_is_auth)
2132 return -1;
2133 else if (!first_is_auth && second_is_auth)
2134 return 1;
2136 node_first = node_get_by_id(first->cache_info.identity_digest);
2137 node_second = node_get_by_id(second->cache_info.identity_digest);
2138 first_is_running = node_first && node_first->is_running;
2139 second_is_running = node_second && node_second->is_running;
2141 if (first_is_running && !second_is_running)
2142 return -1;
2143 else if (!first_is_running && second_is_running)
2144 return 1;
2146 bw_kb_first = dirserv_get_bandwidth_for_router_kb(first);
2147 bw_kb_second = dirserv_get_bandwidth_for_router_kb(second);
2149 if (bw_kb_first > bw_kb_second)
2150 return -1;
2151 else if (bw_kb_first < bw_kb_second)
2152 return 1;
2154 /* They're equal! Compare by identity digest, so there's a
2155 * deterministic order and we avoid flapping. */
2156 return fast_memcmp(first->cache_info.identity_digest,
2157 second->cache_info.identity_digest,
2158 DIGEST_LEN);
2161 /** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
2162 * whose keys are the identity digests of those routers that we're going to
2163 * exclude for Sybil-like appearance. */
2164 static digestmap_t *
2165 get_possible_sybil_list(const smartlist_t *routers)
2167 const or_options_t *options = get_options();
2168 digestmap_t *omit_as_sybil;
2169 smartlist_t *routers_by_ip = smartlist_new();
2170 uint32_t last_addr;
2171 int addr_count;
2172 /* Allow at most this number of Tor servers on a single IP address, ... */
2173 int max_with_same_addr = options->AuthDirMaxServersPerAddr;
2174 /* ... unless it's a directory authority, in which case allow more. */
2175 int max_with_same_addr_on_authority = options->AuthDirMaxServersPerAuthAddr;
2176 if (max_with_same_addr <= 0)
2177 max_with_same_addr = INT_MAX;
2178 if (max_with_same_addr_on_authority <= 0)
2179 max_with_same_addr_on_authority = INT_MAX;
2181 smartlist_add_all(routers_by_ip, routers);
2182 smartlist_sort(routers_by_ip, compare_routerinfo_by_ip_and_bw_);
2183 omit_as_sybil = digestmap_new();
2185 last_addr = 0;
2186 addr_count = 0;
2187 SMARTLIST_FOREACH_BEGIN(routers_by_ip, routerinfo_t *, ri) {
2188 if (last_addr != ri->addr) {
2189 last_addr = ri->addr;
2190 addr_count = 1;
2191 } else if (++addr_count > max_with_same_addr) {
2192 if (!router_addr_is_trusted_dir(ri->addr) ||
2193 addr_count > max_with_same_addr_on_authority)
2194 digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
2196 } SMARTLIST_FOREACH_END(ri);
2198 smartlist_free(routers_by_ip);
2199 return omit_as_sybil;
2202 /** Return non-zero iff a relay running the Tor version specified in
2203 * <b>platform</b> is suitable for use as a potential entry guard. */
2204 static int
2205 is_router_version_good_for_possible_guard(const char *platform)
2207 static int parsed_versions_initialized = 0;
2208 static tor_version_t first_good_0_2_1_guard_version;
2209 static tor_version_t first_good_0_2_2_guard_version;
2210 static tor_version_t first_good_later_guard_version;
2212 tor_version_t router_version;
2214 /* XXX024 This block should be extracted into its own function. */
2215 /* XXXX Begin code copied from tor_version_as_new_as (in routerparse.c) */
2217 char *s, *s2, *start;
2218 char tmp[128];
2220 tor_assert(platform);
2222 /* nonstandard Tor; be safe and say yes */
2223 if (strcmpstart(platform,"Tor "))
2224 return 1;
2226 start = (char *)eat_whitespace(platform+3);
2227 if (!*start) return 0;
2228 s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
2229 s2 = (char*)eat_whitespace(s);
2230 if (!strcmpstart(s2, "(r") || !strcmpstart(s2, "(git-"))
2231 s = (char*)find_whitespace(s2);
2233 if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
2234 return 0;
2235 strlcpy(tmp, start, s-start+1);
2237 if (tor_version_parse(tmp, &router_version)<0) {
2238 log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
2239 return 1; /* be safe and say yes */
2242 /* XXXX End code copied from tor_version_as_new_as (in routerparse.c) */
2244 if (!parsed_versions_initialized) {
2245 /* CVE-2011-2769 was fixed on the relay side in Tor versions
2246 * 0.2.1.31, 0.2.2.34, and 0.2.3.6-alpha. */
2247 tor_assert(tor_version_parse("0.2.1.31",
2248 &first_good_0_2_1_guard_version)>=0);
2249 tor_assert(tor_version_parse("0.2.2.34",
2250 &first_good_0_2_2_guard_version)>=0);
2251 tor_assert(tor_version_parse("0.2.3.6-alpha",
2252 &first_good_later_guard_version)>=0);
2254 /* Don't parse these constant version strings once for every relay
2255 * for every vote. */
2256 parsed_versions_initialized = 1;
2259 return ((tor_version_same_series(&first_good_0_2_1_guard_version,
2260 &router_version) &&
2261 tor_version_compare(&first_good_0_2_1_guard_version,
2262 &router_version) <= 0) ||
2263 (tor_version_same_series(&first_good_0_2_2_guard_version,
2264 &router_version) &&
2265 tor_version_compare(&first_good_0_2_2_guard_version,
2266 &router_version) <= 0) ||
2267 (tor_version_compare(&first_good_later_guard_version,
2268 &router_version) <= 0));
2271 /** Extract status information from <b>ri</b> and from other authority
2272 * functions and store it in <b>rs</b>>. If <b>naming</b>, consider setting
2273 * the named flag in <b>rs</b>.
2275 * We assume that ri-\>is_running has already been set, e.g. by
2276 * dirserv_set_router_is_running(ri, now);
2278 void
2279 set_routerstatus_from_routerinfo(routerstatus_t *rs,
2280 node_t *node,
2281 routerinfo_t *ri,
2282 time_t now,
2283 int naming, int listbadexits,
2284 int listbaddirs, int vote_on_hsdirs)
2286 const or_options_t *options = get_options();
2287 uint32_t routerbw_kb = dirserv_get_credible_bandwidth_kb(ri);
2289 memset(rs, 0, sizeof(routerstatus_t));
2291 rs->is_authority =
2292 router_digest_is_trusted_dir(ri->cache_info.identity_digest);
2294 /* Already set by compute_performance_thresholds. */
2295 rs->is_exit = node->is_exit;
2296 rs->is_stable = node->is_stable =
2297 router_is_active(ri, node, now) &&
2298 !dirserv_thinks_router_is_unreliable(now, ri, 1, 0);
2299 rs->is_fast = node->is_fast =
2300 router_is_active(ri, node, now) &&
2301 !dirserv_thinks_router_is_unreliable(now, ri, 0, 1);
2302 rs->is_flagged_running = node->is_running; /* computed above */
2304 if (naming) {
2305 uint32_t name_status = dirserv_get_name_status(
2306 node->identity, ri->nickname);
2307 rs->is_named = (naming && (name_status & FP_NAMED)) ? 1 : 0;
2308 rs->is_unnamed = (naming && (name_status & FP_UNNAMED)) ? 1 : 0;
2310 rs->is_valid = node->is_valid;
2312 if (node->is_fast &&
2313 ((options->AuthDirGuardBWGuarantee &&
2314 routerbw_kb >= options->AuthDirGuardBWGuarantee/1000) ||
2315 routerbw_kb >= MIN(guard_bandwidth_including_exits_kb,
2316 guard_bandwidth_excluding_exits_kb)) &&
2317 is_router_version_good_for_possible_guard(ri->platform)) {
2318 long tk = rep_hist_get_weighted_time_known(
2319 node->identity, now);
2320 double wfu = rep_hist_get_weighted_fractional_uptime(
2321 node->identity, now);
2322 rs->is_possible_guard = (wfu >= guard_wfu && tk >= guard_tk) ? 1 : 0;
2323 } else {
2324 rs->is_possible_guard = 0;
2326 if (options->TestingTorNetwork &&
2327 routerset_contains_routerstatus(options->TestingDirAuthVoteGuard,
2328 rs, 0)) {
2329 rs->is_possible_guard = 1;
2332 rs->is_bad_directory = listbaddirs && node->is_bad_directory;
2333 rs->is_bad_exit = listbadexits && node->is_bad_exit;
2334 node->is_hs_dir = dirserv_thinks_router_is_hs_dir(ri, node, now);
2335 rs->is_hs_dir = vote_on_hsdirs && node->is_hs_dir;
2337 if (!strcasecmp(ri->nickname, UNNAMED_ROUTER_NICKNAME))
2338 rs->is_named = rs->is_unnamed = 0;
2340 rs->published_on = ri->cache_info.published_on;
2341 memcpy(rs->identity_digest, node->identity, DIGEST_LEN);
2342 memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest,
2343 DIGEST_LEN);
2344 rs->addr = ri->addr;
2345 strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname));
2346 rs->or_port = ri->or_port;
2347 rs->dir_port = ri->dir_port;
2348 if (options->AuthDirHasIPv6Connectivity == 1 &&
2349 !tor_addr_is_null(&ri->ipv6_addr) &&
2350 node->last_reachable6 >= now - REACHABLE_TIMEOUT) {
2351 /* We're configured as having IPv6 connectivity. There's an IPv6
2352 OR port and it's reachable so copy it to the routerstatus. */
2353 tor_addr_copy(&rs->ipv6_addr, &ri->ipv6_addr);
2354 rs->ipv6_orport = ri->ipv6_orport;
2358 /** Routerstatus <b>rs</b> is part of a group of routers that are on
2359 * too narrow an IP-space. Clear out its flags: we don't want people
2360 * using it.
2362 static void
2363 clear_status_flags_on_sybil(routerstatus_t *rs)
2365 rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
2366 rs->is_flagged_running = rs->is_named = rs->is_valid =
2367 rs->is_hs_dir = rs->is_possible_guard = rs->is_bad_exit =
2368 rs->is_bad_directory = 0;
2369 /* FFFF we might want some mechanism to check later on if we
2370 * missed zeroing any flags: it's easy to add a new flag but
2371 * forget to add it to this clause. */
2375 * Helper function to parse out a line in the measured bandwidth file
2376 * into a measured_bw_line_t output structure. Returns -1 on failure
2377 * or 0 on success.
2379 STATIC int
2380 measured_bw_line_parse(measured_bw_line_t *out, const char *orig_line)
2382 char *line = tor_strdup(orig_line);
2383 char *cp = line;
2384 int got_bw = 0;
2385 int got_node_id = 0;
2386 char *strtok_state; /* lame sauce d'jour */
2387 cp = tor_strtok_r(cp, " \t", &strtok_state);
2389 if (!cp) {
2390 log_warn(LD_DIRSERV, "Invalid line in bandwidth file: %s",
2391 escaped(orig_line));
2392 tor_free(line);
2393 return -1;
2396 if (orig_line[strlen(orig_line)-1] != '\n') {
2397 log_warn(LD_DIRSERV, "Incomplete line in bandwidth file: %s",
2398 escaped(orig_line));
2399 tor_free(line);
2400 return -1;
2403 do {
2404 if (strcmpstart(cp, "bw=") == 0) {
2405 int parse_ok = 0;
2406 char *endptr;
2407 if (got_bw) {
2408 log_warn(LD_DIRSERV, "Double bw= in bandwidth file line: %s",
2409 escaped(orig_line));
2410 tor_free(line);
2411 return -1;
2413 cp+=strlen("bw=");
2415 out->bw_kb = tor_parse_long(cp, 0, 0, LONG_MAX, &parse_ok, &endptr);
2416 if (!parse_ok || (*endptr && !TOR_ISSPACE(*endptr))) {
2417 log_warn(LD_DIRSERV, "Invalid bandwidth in bandwidth file line: %s",
2418 escaped(orig_line));
2419 tor_free(line);
2420 return -1;
2422 got_bw=1;
2423 } else if (strcmpstart(cp, "node_id=$") == 0) {
2424 if (got_node_id) {
2425 log_warn(LD_DIRSERV, "Double node_id= in bandwidth file line: %s",
2426 escaped(orig_line));
2427 tor_free(line);
2428 return -1;
2430 cp+=strlen("node_id=$");
2432 if (strlen(cp) != HEX_DIGEST_LEN ||
2433 base16_decode(out->node_id, DIGEST_LEN, cp, HEX_DIGEST_LEN)) {
2434 log_warn(LD_DIRSERV, "Invalid node_id in bandwidth file line: %s",
2435 escaped(orig_line));
2436 tor_free(line);
2437 return -1;
2439 strlcpy(out->node_hex, cp, sizeof(out->node_hex));
2440 got_node_id=1;
2442 } while ((cp = tor_strtok_r(NULL, " \t", &strtok_state)));
2444 if (got_bw && got_node_id) {
2445 tor_free(line);
2446 return 0;
2447 } else {
2448 log_warn(LD_DIRSERV, "Incomplete line in bandwidth file: %s",
2449 escaped(orig_line));
2450 tor_free(line);
2451 return -1;
2456 * Helper function to apply a parsed measurement line to a list
2457 * of bandwidth statuses. Returns true if a line is found,
2458 * false otherwise.
2460 STATIC int
2461 measured_bw_line_apply(measured_bw_line_t *parsed_line,
2462 smartlist_t *routerstatuses)
2464 vote_routerstatus_t *rs = NULL;
2465 if (!routerstatuses)
2466 return 0;
2468 rs = smartlist_bsearch(routerstatuses, parsed_line->node_id,
2469 compare_digest_to_vote_routerstatus_entry);
2471 if (rs) {
2472 rs->has_measured_bw = 1;
2473 rs->measured_bw_kb = (uint32_t)parsed_line->bw_kb;
2474 } else {
2475 log_info(LD_DIRSERV, "Node ID %s not found in routerstatus list",
2476 parsed_line->node_hex);
2479 return rs != NULL;
2483 * Read the measured bandwidth file and apply it to the list of
2484 * vote_routerstatus_t. Returns -1 on error, 0 otherwise.
2487 dirserv_read_measured_bandwidths(const char *from_file,
2488 smartlist_t *routerstatuses)
2490 char line[256];
2491 FILE *fp = tor_fopen_cloexec(from_file, "r");
2492 int applied_lines = 0;
2493 time_t file_time, now;
2494 int ok;
2496 if (fp == NULL) {
2497 log_warn(LD_CONFIG, "Can't open bandwidth file at configured location: %s",
2498 from_file);
2499 return -1;
2502 if (!fgets(line, sizeof(line), fp)
2503 || !strlen(line) || line[strlen(line)-1] != '\n') {
2504 log_warn(LD_DIRSERV, "Long or truncated time in bandwidth file: %s",
2505 escaped(line));
2506 fclose(fp);
2507 return -1;
2510 line[strlen(line)-1] = '\0';
2511 file_time = (time_t)tor_parse_ulong(line, 10, 0, ULONG_MAX, &ok, NULL);
2512 if (!ok) {
2513 log_warn(LD_DIRSERV, "Non-integer time in bandwidth file: %s",
2514 escaped(line));
2515 fclose(fp);
2516 return -1;
2519 now = time(NULL);
2520 if ((now - file_time) > MAX_MEASUREMENT_AGE) {
2521 log_warn(LD_DIRSERV, "Bandwidth measurement file stale. Age: %u",
2522 (unsigned)(time(NULL) - file_time));
2523 fclose(fp);
2524 return -1;
2527 if (routerstatuses)
2528 smartlist_sort(routerstatuses, compare_vote_routerstatus_entries);
2530 while (!feof(fp)) {
2531 measured_bw_line_t parsed_line;
2532 if (fgets(line, sizeof(line), fp) && strlen(line)) {
2533 if (measured_bw_line_parse(&parsed_line, line) != -1) {
2534 /* Also cache the line for dirserv_get_bandwidth_for_router() */
2535 dirserv_cache_measured_bw(&parsed_line, file_time);
2536 if (measured_bw_line_apply(&parsed_line, routerstatuses) > 0)
2537 applied_lines++;
2542 /* Now would be a nice time to clean the cache, too */
2543 dirserv_expire_measured_bw_cache(now);
2545 fclose(fp);
2546 log_info(LD_DIRSERV,
2547 "Bandwidth measurement file successfully read. "
2548 "Applied %d measurements.", applied_lines);
2549 return 0;
2552 /** Return a new networkstatus_t* containing our current opinion. (For v3
2553 * authorities) */
2554 networkstatus_t *
2555 dirserv_generate_networkstatus_vote_obj(crypto_pk_t *private_key,
2556 authority_cert_t *cert)
2558 const or_options_t *options = get_options();
2559 networkstatus_t *v3_out = NULL;
2560 uint32_t addr;
2561 char *hostname = NULL, *client_versions = NULL, *server_versions = NULL;
2562 const char *contact;
2563 smartlist_t *routers, *routerstatuses;
2564 char identity_digest[DIGEST_LEN];
2565 char signing_key_digest[DIGEST_LEN];
2566 int naming = options->NamingAuthoritativeDir;
2567 int listbadexits = options->AuthDirListBadExits;
2568 int listbaddirs = options->AuthDirListBadDirs;
2569 int vote_on_hsdirs = options->VoteOnHidServDirectoriesV2;
2570 routerlist_t *rl = router_get_routerlist();
2571 time_t now = time(NULL);
2572 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2573 networkstatus_voter_info_t *voter = NULL;
2574 vote_timing_t timing;
2575 digestmap_t *omit_as_sybil = NULL;
2576 const int vote_on_reachability = running_long_enough_to_decide_unreachable();
2577 smartlist_t *microdescriptors = NULL;
2579 tor_assert(private_key);
2580 tor_assert(cert);
2582 if (crypto_pk_get_digest(private_key, signing_key_digest)<0) {
2583 log_err(LD_BUG, "Error computing signing key digest");
2584 return NULL;
2586 if (crypto_pk_get_digest(cert->identity_key, identity_digest)<0) {
2587 log_err(LD_BUG, "Error computing identity key digest");
2588 return NULL;
2590 if (resolve_my_address(LOG_WARN, options, &addr, NULL, &hostname)<0) {
2591 log_warn(LD_NET, "Couldn't resolve my hostname");
2592 return NULL;
2594 if (!hostname || !strchr(hostname, '.')) {
2595 tor_free(hostname);
2596 hostname = tor_dup_ip(addr);
2599 if (options->VersioningAuthoritativeDir) {
2600 client_versions = format_versions_list(options->RecommendedClientVersions);
2601 server_versions = format_versions_list(options->RecommendedServerVersions);
2604 contact = get_options()->ContactInfo;
2605 if (!contact)
2606 contact = "(none)";
2609 * Do this so dirserv_compute_performance_thresholds() and
2610 * set_routerstatus_from_routerinfo() see up-to-date bandwidth info.
2612 if (options->V3BandwidthsFile) {
2613 dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
2614 } else {
2616 * No bandwidths file; clear the measured bandwidth cache in case we had
2617 * one last time around.
2619 if (dirserv_get_measured_bw_cache_size() > 0) {
2620 dirserv_clear_measured_bw_cache();
2624 /* precompute this part, since we need it to decide what "stable"
2625 * means. */
2626 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2627 dirserv_set_router_is_running(ri, now);
2630 routers = smartlist_new();
2631 smartlist_add_all(routers, rl->routers);
2632 routers_sort_by_identity(routers);
2633 omit_as_sybil = get_possible_sybil_list(routers);
2635 DIGESTMAP_FOREACH(omit_as_sybil, sybil_id, void *, ignore) {
2636 (void) ignore;
2637 rep_hist_make_router_pessimal(sybil_id, now);
2638 } DIGESTMAP_FOREACH_END;
2640 /* Count how many have measured bandwidths so we know how to assign flags;
2641 * this must come before dirserv_compute_performance_thresholds() */
2642 dirserv_count_measured_bws(rl);
2644 dirserv_compute_performance_thresholds(rl, omit_as_sybil);
2646 routerstatuses = smartlist_new();
2647 microdescriptors = smartlist_new();
2649 SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
2650 if (ri->cache_info.published_on >= cutoff) {
2651 routerstatus_t *rs;
2652 vote_routerstatus_t *vrs;
2653 node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
2654 if (!node)
2655 continue;
2657 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
2658 rs = &vrs->status;
2659 set_routerstatus_from_routerinfo(rs, node, ri, now,
2660 naming, listbadexits, listbaddirs,
2661 vote_on_hsdirs);
2663 if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
2664 clear_status_flags_on_sybil(rs);
2666 if (!vote_on_reachability)
2667 rs->is_flagged_running = 0;
2669 vrs->version = version_from_platform(ri->platform);
2670 vrs->microdesc = dirvote_format_all_microdesc_vote_lines(ri, now,
2671 microdescriptors);
2673 smartlist_add(routerstatuses, vrs);
2675 } SMARTLIST_FOREACH_END(ri);
2678 smartlist_t *added =
2679 microdescs_add_list_to_cache(get_microdesc_cache(),
2680 microdescriptors, SAVED_NOWHERE, 0);
2681 smartlist_free(added);
2682 smartlist_free(microdescriptors);
2685 smartlist_free(routers);
2686 digestmap_free(omit_as_sybil, NULL);
2688 /* This pass through applies the measured bw lines to the routerstatuses */
2689 if (options->V3BandwidthsFile) {
2690 dirserv_read_measured_bandwidths(options->V3BandwidthsFile,
2691 routerstatuses);
2692 } else {
2694 * No bandwidths file; clear the measured bandwidth cache in case we had
2695 * one last time around.
2697 if (dirserv_get_measured_bw_cache_size() > 0) {
2698 dirserv_clear_measured_bw_cache();
2702 v3_out = tor_malloc_zero(sizeof(networkstatus_t));
2704 v3_out->type = NS_TYPE_VOTE;
2705 dirvote_get_preferred_voting_intervals(&timing);
2706 v3_out->published = now;
2708 char tbuf[ISO_TIME_LEN+1];
2709 networkstatus_t *current_consensus =
2710 networkstatus_get_live_consensus(now);
2711 long last_consensus_interval; /* only used to pick a valid_after */
2712 if (current_consensus)
2713 last_consensus_interval = current_consensus->fresh_until -
2714 current_consensus->valid_after;
2715 else
2716 last_consensus_interval = options->TestingV3AuthInitialVotingInterval;
2717 v3_out->valid_after =
2718 dirvote_get_start_of_next_interval(now, (int)last_consensus_interval,
2719 options->TestingV3AuthVotingStartOffset);
2720 format_iso_time(tbuf, v3_out->valid_after);
2721 log_notice(LD_DIR,"Choosing valid-after time in vote as %s: "
2722 "consensus_set=%d, last_interval=%d",
2723 tbuf, current_consensus?1:0, (int)last_consensus_interval);
2725 v3_out->fresh_until = v3_out->valid_after + timing.vote_interval;
2726 v3_out->valid_until = v3_out->valid_after +
2727 (timing.vote_interval * timing.n_intervals_valid);
2728 v3_out->vote_seconds = timing.vote_delay;
2729 v3_out->dist_seconds = timing.dist_delay;
2730 tor_assert(v3_out->vote_seconds > 0);
2731 tor_assert(v3_out->dist_seconds > 0);
2732 tor_assert(timing.n_intervals_valid > 0);
2734 v3_out->client_versions = client_versions;
2735 v3_out->server_versions = server_versions;
2736 v3_out->known_flags = smartlist_new();
2737 smartlist_split_string(v3_out->known_flags,
2738 "Authority Exit Fast Guard Stable V2Dir Valid",
2739 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2740 if (vote_on_reachability)
2741 smartlist_add(v3_out->known_flags, tor_strdup("Running"));
2742 if (listbaddirs)
2743 smartlist_add(v3_out->known_flags, tor_strdup("BadDirectory"));
2744 if (listbadexits)
2745 smartlist_add(v3_out->known_flags, tor_strdup("BadExit"));
2746 if (naming) {
2747 smartlist_add(v3_out->known_flags, tor_strdup("Named"));
2748 smartlist_add(v3_out->known_flags, tor_strdup("Unnamed"));
2750 if (vote_on_hsdirs)
2751 smartlist_add(v3_out->known_flags, tor_strdup("HSDir"));
2752 smartlist_sort_strings(v3_out->known_flags);
2754 if (options->ConsensusParams) {
2755 v3_out->net_params = smartlist_new();
2756 smartlist_split_string(v3_out->net_params,
2757 options->ConsensusParams, NULL, 0, 0);
2758 smartlist_sort_strings(v3_out->net_params);
2761 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
2762 voter->nickname = tor_strdup(options->Nickname);
2763 memcpy(voter->identity_digest, identity_digest, DIGEST_LEN);
2764 voter->sigs = smartlist_new();
2765 voter->address = hostname;
2766 voter->addr = addr;
2767 voter->dir_port = router_get_advertised_dir_port(options, 0);
2768 voter->or_port = router_get_advertised_or_port(options);
2769 voter->contact = tor_strdup(contact);
2770 if (options->V3AuthUseLegacyKey) {
2771 authority_cert_t *c = get_my_v3_legacy_cert();
2772 if (c) {
2773 if (crypto_pk_get_digest(c->identity_key, voter->legacy_id_digest)) {
2774 log_warn(LD_BUG, "Unable to compute digest of legacy v3 identity key");
2775 memset(voter->legacy_id_digest, 0, DIGEST_LEN);
2780 v3_out->voters = smartlist_new();
2781 smartlist_add(v3_out->voters, voter);
2782 v3_out->cert = authority_cert_dup(cert);
2783 v3_out->routerstatus_list = routerstatuses;
2784 /* Note: networkstatus_digest is unset; it won't get set until we actually
2785 * format the vote. */
2787 return v3_out;
2790 /** As dirserv_get_routerdescs(), but instead of getting signed_descriptor_t
2791 * pointers, adds copies of digests to fps_out, and doesn't use the
2792 * /tor/server/ prefix. For a /d/ request, adds descriptor digests; for other
2793 * requests, adds identity digests.
2796 dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
2797 const char **msg, int for_unencrypted_conn,
2798 int is_extrainfo)
2800 int by_id = 1;
2801 *msg = NULL;
2803 if (!strcmp(key, "all")) {
2804 routerlist_t *rl = router_get_routerlist();
2805 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2806 smartlist_add(fps_out,
2807 tor_memdup(r->cache_info.identity_digest, DIGEST_LEN)));
2808 /* Treat "all" requests as if they were unencrypted */
2809 for_unencrypted_conn = 1;
2810 } else if (!strcmp(key, "authority")) {
2811 const routerinfo_t *ri = router_get_my_routerinfo();
2812 if (ri)
2813 smartlist_add(fps_out,
2814 tor_memdup(ri->cache_info.identity_digest, DIGEST_LEN));
2815 } else if (!strcmpstart(key, "d/")) {
2816 by_id = 0;
2817 key += strlen("d/");
2818 dir_split_resource_into_fingerprints(key, fps_out, NULL,
2819 DSR_HEX|DSR_SORT_UNIQ);
2820 } else if (!strcmpstart(key, "fp/")) {
2821 key += strlen("fp/");
2822 dir_split_resource_into_fingerprints(key, fps_out, NULL,
2823 DSR_HEX|DSR_SORT_UNIQ);
2824 } else {
2825 *msg = "Key not recognized";
2826 return -1;
2829 if (for_unencrypted_conn) {
2830 /* Remove anything that insists it not be sent unencrypted. */
2831 SMARTLIST_FOREACH_BEGIN(fps_out, char *, cp) {
2832 const signed_descriptor_t *sd;
2833 if (by_id)
2834 sd = get_signed_descriptor_by_fp(cp,is_extrainfo,0);
2835 else if (is_extrainfo)
2836 sd = extrainfo_get_by_descriptor_digest(cp);
2837 else
2838 sd = router_get_by_descriptor_digest(cp);
2839 if (sd && !sd->send_unencrypted) {
2840 tor_free(cp);
2841 SMARTLIST_DEL_CURRENT(fps_out, cp);
2843 } SMARTLIST_FOREACH_END(cp);
2846 if (!smartlist_len(fps_out)) {
2847 *msg = "Servers unavailable";
2848 return -1;
2850 return 0;
2853 /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
2854 * <b>key</b>. The key should be either
2855 * - "/tor/server/authority" for our own routerinfo;
2856 * - "/tor/server/all" for all the routerinfos we have, concatenated;
2857 * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
2858 * hex identity digests; or
2859 * - "/tor/server/d/D" where D is a plus-separated sequence
2860 * of server descriptor digests, in hex.
2862 * Return 0 if we found some matching descriptors, or -1 if we do not
2863 * have any descriptors, no matching descriptors, or if we did not
2864 * recognize the key (URL).
2865 * If -1 is returned *<b>msg</b> will be set to an appropriate error
2866 * message.
2868 * XXXX rename this function. It's only called from the controller.
2869 * XXXX in fact, refactor this function, merging as much as possible.
2872 dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
2873 const char **msg)
2875 *msg = NULL;
2877 if (!strcmp(key, "/tor/server/all")) {
2878 routerlist_t *rl = router_get_routerlist();
2879 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2880 smartlist_add(descs_out, &(r->cache_info)));
2881 } else if (!strcmp(key, "/tor/server/authority")) {
2882 const routerinfo_t *ri = router_get_my_routerinfo();
2883 if (ri)
2884 smartlist_add(descs_out, (void*) &(ri->cache_info));
2885 } else if (!strcmpstart(key, "/tor/server/d/")) {
2886 smartlist_t *digests = smartlist_new();
2887 key += strlen("/tor/server/d/");
2888 dir_split_resource_into_fingerprints(key, digests, NULL,
2889 DSR_HEX|DSR_SORT_UNIQ);
2890 SMARTLIST_FOREACH(digests, const char *, d,
2892 signed_descriptor_t *sd = router_get_by_descriptor_digest(d);
2893 if (sd)
2894 smartlist_add(descs_out,sd);
2896 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
2897 smartlist_free(digests);
2898 } else if (!strcmpstart(key, "/tor/server/fp/")) {
2899 smartlist_t *digests = smartlist_new();
2900 time_t cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
2901 key += strlen("/tor/server/fp/");
2902 dir_split_resource_into_fingerprints(key, digests, NULL,
2903 DSR_HEX|DSR_SORT_UNIQ);
2904 SMARTLIST_FOREACH_BEGIN(digests, const char *, d) {
2905 if (router_digest_is_me(d)) {
2906 /* make sure desc_routerinfo exists */
2907 const routerinfo_t *ri = router_get_my_routerinfo();
2908 if (ri)
2909 smartlist_add(descs_out, (void*) &(ri->cache_info));
2910 } else {
2911 const routerinfo_t *ri = router_get_by_id_digest(d);
2912 /* Don't actually serve a descriptor that everyone will think is
2913 * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
2914 * Tors from downloading descriptors that they will throw away.
2916 if (ri && ri->cache_info.published_on > cutoff)
2917 smartlist_add(descs_out, (void*) &(ri->cache_info));
2919 } SMARTLIST_FOREACH_END(d);
2920 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
2921 smartlist_free(digests);
2922 } else {
2923 *msg = "Key not recognized";
2924 return -1;
2927 if (!smartlist_len(descs_out)) {
2928 *msg = "Servers unavailable";
2929 return -1;
2931 return 0;
2934 /** Called when a TLS handshake has completed successfully with a
2935 * router listening at <b>address</b>:<b>or_port</b>, and has yielded
2936 * a certificate with digest <b>digest_rcvd</b>.
2938 * Inform the reachability checker that we could get to this guy.
2940 void
2941 dirserv_orconn_tls_done(const tor_addr_t *addr,
2942 uint16_t or_port,
2943 const char *digest_rcvd)
2945 node_t *node = NULL;
2946 tor_addr_port_t orport;
2947 routerinfo_t *ri = NULL;
2948 time_t now = time(NULL);
2949 tor_assert(addr);
2950 tor_assert(digest_rcvd);
2952 node = node_get_mutable_by_id(digest_rcvd);
2953 if (node == NULL || node->ri == NULL)
2954 return;
2955 ri = node->ri;
2957 tor_addr_copy(&orport.addr, addr);
2958 orport.port = or_port;
2959 if (router_has_orport(ri, &orport)) {
2960 /* Found the right router. */
2961 if (!authdir_mode_bridge(get_options()) ||
2962 ri->purpose == ROUTER_PURPOSE_BRIDGE) {
2963 char addrstr[TOR_ADDR_BUF_LEN];
2964 /* This is a bridge or we're not a bridge authorititative --
2965 mark it as reachable. */
2966 log_info(LD_DIRSERV, "Found router %s to be reachable at %s:%d. Yay.",
2967 router_describe(ri),
2968 tor_addr_to_str(addrstr, addr, sizeof(addrstr), 1),
2969 ri->or_port);
2970 if (tor_addr_family(addr) == AF_INET) {
2971 rep_hist_note_router_reachable(digest_rcvd, addr, or_port, now);
2972 node->last_reachable = now;
2973 } else if (tor_addr_family(addr) == AF_INET6) {
2974 /* No rephist for IPv6. */
2975 node->last_reachable6 = now;
2981 /** Called when we, as an authority, receive a new router descriptor either as
2982 * an upload or a download. Used to decide whether to relaunch reachability
2983 * testing for the server. */
2985 dirserv_should_launch_reachability_test(const routerinfo_t *ri,
2986 const routerinfo_t *ri_old)
2988 if (!authdir_mode_handles_descs(get_options(), ri->purpose))
2989 return 0;
2990 if (!ri_old) {
2991 /* New router: Launch an immediate reachability test, so we will have an
2992 * opinion soon in case we're generating a consensus soon */
2993 return 1;
2995 if (ri_old->is_hibernating && !ri->is_hibernating) {
2996 /* It just came out of hibernation; launch a reachability test */
2997 return 1;
2999 if (! routers_have_same_or_addrs(ri, ri_old)) {
3000 /* Address or port changed; launch a reachability test */
3001 return 1;
3003 return 0;
3006 /** Helper function for dirserv_test_reachability(). Start a TLS
3007 * connection to <b>router</b>, and annotate it with when we started
3008 * the test. */
3009 void
3010 dirserv_single_reachability_test(time_t now, routerinfo_t *router)
3012 channel_t *chan = NULL;
3013 node_t *node = NULL;
3014 tor_addr_t router_addr;
3015 (void) now;
3017 tor_assert(router);
3018 node = node_get_mutable_by_id(router->cache_info.identity_digest);
3019 tor_assert(node);
3021 /* IPv4. */
3022 log_debug(LD_OR,"Testing reachability of %s at %s:%u.",
3023 router->nickname, fmt_addr32(router->addr), router->or_port);
3024 tor_addr_from_ipv4h(&router_addr, router->addr);
3025 chan = channel_tls_connect(&router_addr, router->or_port,
3026 router->cache_info.identity_digest);
3027 if (chan) command_setup_channel(chan);
3029 /* Possible IPv6. */
3030 if (get_options()->AuthDirHasIPv6Connectivity == 1 &&
3031 !tor_addr_is_null(&router->ipv6_addr)) {
3032 char addrstr[TOR_ADDR_BUF_LEN];
3033 log_debug(LD_OR, "Testing reachability of %s at %s:%u.",
3034 router->nickname,
3035 tor_addr_to_str(addrstr, &router->ipv6_addr, sizeof(addrstr), 1),
3036 router->ipv6_orport);
3037 chan = channel_tls_connect(&router->ipv6_addr, router->ipv6_orport,
3038 router->cache_info.identity_digest);
3039 if (chan) command_setup_channel(chan);
3043 /** Auth dir server only: load balance such that we only
3044 * try a few connections per call.
3046 * The load balancing is such that if we get called once every ten
3047 * seconds, we will cycle through all the tests in
3048 * REACHABILITY_TEST_CYCLE_PERIOD seconds (a bit over 20 minutes).
3050 void
3051 dirserv_test_reachability(time_t now)
3053 /* XXX decide what to do here; see or-talk thread "purging old router
3054 * information, revocation." -NM
3055 * We can't afford to mess with this in 0.1.2.x. The reason is that
3056 * if we stop doing reachability tests on some of routerlist, then
3057 * we'll for-sure think they're down, which may have unexpected
3058 * effects in other parts of the code. It doesn't hurt much to do
3059 * the testing, and directory authorities are easy to upgrade. Let's
3060 * wait til 0.2.0. -RD */
3061 // time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
3062 routerlist_t *rl = router_get_routerlist();
3063 static char ctr = 0;
3064 int bridge_auth = authdir_mode_bridge(get_options());
3066 SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, router) {
3067 const char *id_digest = router->cache_info.identity_digest;
3068 if (router_is_me(router))
3069 continue;
3070 if (bridge_auth && router->purpose != ROUTER_PURPOSE_BRIDGE)
3071 continue; /* bridge authorities only test reachability on bridges */
3072 // if (router->cache_info.published_on > cutoff)
3073 // continue;
3074 if ((((uint8_t)id_digest[0]) % REACHABILITY_MODULO_PER_TEST) == ctr) {
3075 dirserv_single_reachability_test(now, router);
3077 } SMARTLIST_FOREACH_END(router);
3078 ctr = (ctr + 1) % REACHABILITY_MODULO_PER_TEST; /* increment ctr */
3081 /** Given a fingerprint <b>fp</b> which is either set if we're looking for a
3082 * v2 status, or zeroes if we're looking for a v3 status, or a NUL-padded
3083 * flavor name if we want a flavored v3 status, return a pointer to the
3084 * appropriate cached dir object, or NULL if there isn't one available. */
3085 static cached_dir_t *
3086 lookup_cached_dir_by_fp(const char *fp)
3088 cached_dir_t *d = NULL;
3089 if (tor_digest_is_zero(fp) && cached_consensuses) {
3090 d = strmap_get(cached_consensuses, "ns");
3091 } else if (memchr(fp, '\0', DIGEST_LEN) && cached_consensuses &&
3092 (d = strmap_get(cached_consensuses, fp))) {
3093 /* this here interface is a nasty hack XXXX024 */;
3095 return d;
3098 /** Remove from <b>fps</b> every networkstatus key where both
3099 * a) we have a networkstatus document and
3100 * b) it is not newer than <b>cutoff</b>.
3102 * Return 1 if any items were present at all; else return 0.
3105 dirserv_remove_old_statuses(smartlist_t *fps, time_t cutoff)
3107 int found_any = 0;
3108 SMARTLIST_FOREACH_BEGIN(fps, char *, digest) {
3109 cached_dir_t *d = lookup_cached_dir_by_fp(digest);
3110 if (!d)
3111 continue;
3112 found_any = 1;
3113 if (d->published <= cutoff) {
3114 tor_free(digest);
3115 SMARTLIST_DEL_CURRENT(fps, digest);
3117 } SMARTLIST_FOREACH_END(digest);
3119 return found_any;
3122 /** Return the cache-info for identity fingerprint <b>fp</b>, or
3123 * its extra-info document if <b>extrainfo</b> is true. Return
3124 * NULL if not found or if the descriptor is older than
3125 * <b>publish_cutoff</b>. */
3126 static const signed_descriptor_t *
3127 get_signed_descriptor_by_fp(const char *fp, int extrainfo,
3128 time_t publish_cutoff)
3130 if (router_digest_is_me(fp)) {
3131 if (extrainfo)
3132 return &(router_get_my_extrainfo()->cache_info);
3133 else
3134 return &(router_get_my_routerinfo()->cache_info);
3135 } else {
3136 const routerinfo_t *ri = router_get_by_id_digest(fp);
3137 if (ri &&
3138 ri->cache_info.published_on > publish_cutoff) {
3139 if (extrainfo)
3140 return extrainfo_get_by_descriptor_digest(
3141 ri->cache_info.extra_info_digest);
3142 else
3143 return &ri->cache_info;
3146 return NULL;
3149 /** Return true iff we have any of the documents (extrainfo or routerdesc)
3150 * specified by the fingerprints in <b>fps</b> and <b>spool_src</b>. Used to
3151 * decide whether to send a 404. */
3153 dirserv_have_any_serverdesc(smartlist_t *fps, int spool_src)
3155 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
3156 SMARTLIST_FOREACH_BEGIN(fps, const char *, fp) {
3157 switch (spool_src)
3159 case DIR_SPOOL_EXTRA_BY_DIGEST:
3160 if (extrainfo_get_by_descriptor_digest(fp)) return 1;
3161 break;
3162 case DIR_SPOOL_SERVER_BY_DIGEST:
3163 if (router_get_by_descriptor_digest(fp)) return 1;
3164 break;
3165 case DIR_SPOOL_EXTRA_BY_FP:
3166 case DIR_SPOOL_SERVER_BY_FP:
3167 if (get_signed_descriptor_by_fp(fp,
3168 spool_src == DIR_SPOOL_EXTRA_BY_FP, publish_cutoff))
3169 return 1;
3170 break;
3172 } SMARTLIST_FOREACH_END(fp);
3173 return 0;
3176 /** Return true iff any of the 256-bit elements in <b>fps</b> is the digest of
3177 * a microdescriptor we have. */
3179 dirserv_have_any_microdesc(const smartlist_t *fps)
3181 microdesc_cache_t *cache = get_microdesc_cache();
3182 SMARTLIST_FOREACH(fps, const char *, fp,
3183 if (microdesc_cache_lookup_by_digest256(cache, fp))
3184 return 1);
3185 return 0;
3188 /** Return an approximate estimate of the number of bytes that will
3189 * be needed to transmit the server descriptors (if is_serverdescs --
3190 * they can be either d/ or fp/ queries) or networkstatus objects (if
3191 * !is_serverdescs) listed in <b>fps</b>. If <b>compressed</b> is set,
3192 * we guess how large the data will be after compression.
3194 * The return value is an estimate; it might be larger or smaller.
3196 size_t
3197 dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
3198 int compressed)
3200 size_t result;
3201 tor_assert(fps);
3202 if (is_serverdescs) {
3203 int n = smartlist_len(fps);
3204 const routerinfo_t *me = router_get_my_routerinfo();
3205 result = (me?me->cache_info.signed_descriptor_len:2048) * n;
3206 if (compressed)
3207 result /= 2; /* observed compressibility is between 35 and 55%. */
3208 } else {
3209 result = 0;
3210 SMARTLIST_FOREACH(fps, const char *, digest, {
3211 cached_dir_t *dir = lookup_cached_dir_by_fp(digest);
3212 if (dir)
3213 result += compressed ? dir->dir_z_len : dir->dir_len;
3216 return result;
3219 /** Given a list of microdescriptor hashes, guess how many bytes will be
3220 * needed to transmit them, and return the guess. */
3221 size_t
3222 dirserv_estimate_microdesc_size(const smartlist_t *fps, int compressed)
3224 size_t result = smartlist_len(fps) * microdesc_average_size(NULL);
3225 if (compressed)
3226 result /= 2;
3227 return result;
3230 /** When we're spooling data onto our outbuf, add more whenever we dip
3231 * below this threshold. */
3232 #define DIRSERV_BUFFER_MIN 16384
3234 /** Spooling helper: called when we have no more data to spool to <b>conn</b>.
3235 * Flushes any remaining data to be (un)compressed, and changes the spool
3236 * source to NONE. Returns 0 on success, negative on failure. */
3237 static int
3238 connection_dirserv_finish_spooling(dir_connection_t *conn)
3240 if (conn->zlib_state) {
3241 connection_write_to_buf_zlib("", 0, conn, 1);
3242 tor_zlib_free(conn->zlib_state);
3243 conn->zlib_state = NULL;
3245 conn->dir_spool_src = DIR_SPOOL_NONE;
3246 return 0;
3249 /** Spooling helper: called when we're sending a bunch of server descriptors,
3250 * and the outbuf has become too empty. Pulls some entries from
3251 * fingerprint_stack, and writes the corresponding servers onto outbuf. If we
3252 * run out of entries, flushes the zlib state and sets the spool source to
3253 * NONE. Returns 0 on success, negative on failure.
3255 static int
3256 connection_dirserv_add_servers_to_outbuf(dir_connection_t *conn)
3258 int by_fp = (conn->dir_spool_src == DIR_SPOOL_SERVER_BY_FP ||
3259 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP);
3260 int extra = (conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP ||
3261 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_DIGEST);
3262 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
3264 const or_options_t *options = get_options();
3266 while (smartlist_len(conn->fingerprint_stack) &&
3267 connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
3268 const char *body;
3269 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3270 const signed_descriptor_t *sd = NULL;
3271 if (by_fp) {
3272 sd = get_signed_descriptor_by_fp(fp, extra, publish_cutoff);
3273 } else {
3274 sd = extra ? extrainfo_get_by_descriptor_digest(fp)
3275 : router_get_by_descriptor_digest(fp);
3277 tor_free(fp);
3278 if (!sd)
3279 continue;
3280 if (!connection_dir_is_encrypted(conn) && !sd->send_unencrypted) {
3281 /* we did this check once before (so we could have an accurate size
3282 * estimate and maybe send a 404 if somebody asked for only bridges on a
3283 * connection), but we need to do it again in case a previously
3284 * unknown bridge descriptor has shown up between then and now. */
3285 continue;
3288 /** If we are the bridge authority and the descriptor is a bridge
3289 * descriptor, remember that we served this descriptor for desc stats. */
3290 if (options->BridgeAuthoritativeDir && by_fp) {
3291 const routerinfo_t *router =
3292 router_get_by_id_digest(sd->identity_digest);
3293 /* router can be NULL here when the bridge auth is asked for its own
3294 * descriptor. */
3295 if (router && router->purpose == ROUTER_PURPOSE_BRIDGE)
3296 rep_hist_note_desc_served(sd->identity_digest);
3298 body = signed_descriptor_get_body(sd);
3299 if (conn->zlib_state) {
3300 int last = ! smartlist_len(conn->fingerprint_stack);
3301 connection_write_to_buf_zlib(body, sd->signed_descriptor_len, conn,
3302 last);
3303 if (last) {
3304 tor_zlib_free(conn->zlib_state);
3305 conn->zlib_state = NULL;
3307 } else {
3308 connection_write_to_buf(body,
3309 sd->signed_descriptor_len,
3310 TO_CONN(conn));
3314 if (!smartlist_len(conn->fingerprint_stack)) {
3315 /* We just wrote the last one; finish up. */
3316 if (conn->zlib_state) {
3317 connection_write_to_buf_zlib("", 0, conn, 1);
3318 tor_zlib_free(conn->zlib_state);
3319 conn->zlib_state = NULL;
3321 conn->dir_spool_src = DIR_SPOOL_NONE;
3322 smartlist_free(conn->fingerprint_stack);
3323 conn->fingerprint_stack = NULL;
3325 return 0;
3328 /** Spooling helper: called when we're sending a bunch of microdescriptors,
3329 * and the outbuf has become too empty. Pulls some entries from
3330 * fingerprint_stack, and writes the corresponding microdescs onto outbuf. If
3331 * we run out of entries, flushes the zlib state and sets the spool source to
3332 * NONE. Returns 0 on success, negative on failure.
3334 static int
3335 connection_dirserv_add_microdescs_to_outbuf(dir_connection_t *conn)
3337 microdesc_cache_t *cache = get_microdesc_cache();
3338 while (smartlist_len(conn->fingerprint_stack) &&
3339 connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
3340 char *fp256 = smartlist_pop_last(conn->fingerprint_stack);
3341 microdesc_t *md = microdesc_cache_lookup_by_digest256(cache, fp256);
3342 tor_free(fp256);
3343 if (!md || !md->body)
3344 continue;
3345 if (conn->zlib_state) {
3346 int last = !smartlist_len(conn->fingerprint_stack);
3347 connection_write_to_buf_zlib(md->body, md->bodylen, conn, last);
3348 if (last) {
3349 tor_zlib_free(conn->zlib_state);
3350 conn->zlib_state = NULL;
3352 } else {
3353 connection_write_to_buf(md->body, md->bodylen, TO_CONN(conn));
3356 if (!smartlist_len(conn->fingerprint_stack)) {
3357 if (conn->zlib_state) {
3358 connection_write_to_buf_zlib("", 0, conn, 1);
3359 tor_zlib_free(conn->zlib_state);
3360 conn->zlib_state = NULL;
3362 conn->dir_spool_src = DIR_SPOOL_NONE;
3363 smartlist_free(conn->fingerprint_stack);
3364 conn->fingerprint_stack = NULL;
3366 return 0;
3369 /** Spooling helper: Called when we're sending a directory or networkstatus,
3370 * and the outbuf has become too empty. Pulls some bytes from
3371 * <b>conn</b>-\>cached_dir-\>dir_z, uncompresses them if appropriate, and
3372 * puts them on the outbuf. If we run out of entries, flushes the zlib state
3373 * and sets the spool source to NONE. Returns 0 on success, negative on
3374 * failure. */
3375 static int
3376 connection_dirserv_add_dir_bytes_to_outbuf(dir_connection_t *conn)
3378 ssize_t bytes;
3379 int64_t remaining;
3381 bytes = DIRSERV_BUFFER_MIN - connection_get_outbuf_len(TO_CONN(conn));
3382 tor_assert(bytes > 0);
3383 tor_assert(conn->cached_dir);
3384 if (bytes < 8192)
3385 bytes = 8192;
3386 remaining = conn->cached_dir->dir_z_len - conn->cached_dir_offset;
3387 if (bytes > remaining)
3388 bytes = (ssize_t) remaining;
3390 if (conn->zlib_state) {
3391 connection_write_to_buf_zlib(
3392 conn->cached_dir->dir_z + conn->cached_dir_offset,
3393 bytes, conn, bytes == remaining);
3394 } else {
3395 connection_write_to_buf(conn->cached_dir->dir_z + conn->cached_dir_offset,
3396 bytes, TO_CONN(conn));
3398 conn->cached_dir_offset += bytes;
3399 if (conn->cached_dir_offset == (int)conn->cached_dir->dir_z_len) {
3400 /* We just wrote the last one; finish up. */
3401 connection_dirserv_finish_spooling(conn);
3402 cached_dir_decref(conn->cached_dir);
3403 conn->cached_dir = NULL;
3405 return 0;
3408 /** Spooling helper: Called when we're spooling networkstatus objects on
3409 * <b>conn</b>, and the outbuf has become too empty. If the current
3410 * networkstatus object (in <b>conn</b>-\>cached_dir) has more data, pull data
3411 * from there. Otherwise, pop the next fingerprint from fingerprint_stack,
3412 * and start spooling the next networkstatus. (A digest of all 0 bytes is
3413 * treated as a request for the current consensus.) If we run out of entries,
3414 * flushes the zlib state and sets the spool source to NONE. Returns 0 on
3415 * success, negative on failure. */
3416 static int
3417 connection_dirserv_add_networkstatus_bytes_to_outbuf(dir_connection_t *conn)
3420 while (connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
3421 if (conn->cached_dir) {
3422 int uncompressing = (conn->zlib_state != NULL);
3423 int r = connection_dirserv_add_dir_bytes_to_outbuf(conn);
3424 if (conn->dir_spool_src == DIR_SPOOL_NONE) {
3425 /* add_dir_bytes thinks we're done with the cached_dir. But we
3426 * may have more cached_dirs! */
3427 conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
3428 /* This bit is tricky. If we were uncompressing the last
3429 * networkstatus, we may need to make a new zlib object to
3430 * uncompress the next one. */
3431 if (uncompressing && ! conn->zlib_state &&
3432 conn->fingerprint_stack &&
3433 smartlist_len(conn->fingerprint_stack)) {
3434 conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
3437 if (r) return r;
3438 } else if (conn->fingerprint_stack &&
3439 smartlist_len(conn->fingerprint_stack)) {
3440 /* Add another networkstatus; start serving it. */
3441 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3442 cached_dir_t *d = lookup_cached_dir_by_fp(fp);
3443 tor_free(fp);
3444 if (d) {
3445 ++d->refcnt;
3446 conn->cached_dir = d;
3447 conn->cached_dir_offset = 0;
3449 } else {
3450 connection_dirserv_finish_spooling(conn);
3451 smartlist_free(conn->fingerprint_stack);
3452 conn->fingerprint_stack = NULL;
3453 return 0;
3456 return 0;
3459 /** Called whenever we have flushed some directory data in state
3460 * SERVER_WRITING. */
3462 connection_dirserv_flushed_some(dir_connection_t *conn)
3464 tor_assert(conn->base_.state == DIR_CONN_STATE_SERVER_WRITING);
3466 if (connection_get_outbuf_len(TO_CONN(conn)) >= DIRSERV_BUFFER_MIN)
3467 return 0;
3469 switch (conn->dir_spool_src) {
3470 case DIR_SPOOL_EXTRA_BY_DIGEST:
3471 case DIR_SPOOL_EXTRA_BY_FP:
3472 case DIR_SPOOL_SERVER_BY_DIGEST:
3473 case DIR_SPOOL_SERVER_BY_FP:
3474 return connection_dirserv_add_servers_to_outbuf(conn);
3475 case DIR_SPOOL_MICRODESC:
3476 return connection_dirserv_add_microdescs_to_outbuf(conn);
3477 case DIR_SPOOL_CACHED_DIR:
3478 return connection_dirserv_add_dir_bytes_to_outbuf(conn);
3479 case DIR_SPOOL_NETWORKSTATUS:
3480 return connection_dirserv_add_networkstatus_bytes_to_outbuf(conn);
3481 case DIR_SPOOL_NONE:
3482 default:
3483 return 0;
3487 /** Release all storage used by the directory server. */
3488 void
3489 dirserv_free_all(void)
3491 dirserv_free_fingerprint_list();
3493 strmap_free(cached_consensuses, free_cached_dir_);
3494 cached_consensuses = NULL;
3496 dirserv_clear_measured_bw_cache();