Possible fix for broken country settings in ExcludeExitNodes.
[tor/rransom.git] / src / or / dirserv.c
blob2647fe275c0954d1d923902b3834ad684738248c
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2008, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 #define DIRSERV_PRIVATE
7 #include "or.h"
9 /**
10 * \file dirserv.c
11 * \brief Directory server core implementation. Manages directory
12 * contents and generates directories.
15 /** How far in the future do we allow a router to get? (seconds) */
16 #define ROUTER_ALLOW_SKEW (60*60*12)
17 /** How many seconds do we wait before regenerating the directory? */
18 #define DIR_REGEN_SLACK_TIME 30
19 /** If we're a cache, keep this many networkstatuses around from non-trusted
20 * directory authorities. */
21 #define MAX_UNTRUSTED_NETWORKSTATUSES 16
23 /** If a v1 directory is older than this, discard it. */
24 #define MAX_V1_DIRECTORY_AGE (30*24*60*60)
25 /** If a v1 running-routers is older than this, discard it. */
26 #define MAX_V1_RR_AGE (7*24*60*60)
28 extern time_t time_of_process_start; /* from main.c */
30 /** Do we need to regenerate the v1 directory when someone asks for it? */
31 static time_t the_directory_is_dirty = 1;
32 /** Do we need to regenerate the v1 runningrouters document when somebody
33 * asks for it? */
34 static time_t runningrouters_is_dirty = 1;
35 /** Do we need to regenerate our v2 networkstatus document when somebody asks
36 * for it? */
37 static time_t the_v2_networkstatus_is_dirty = 1;
39 /** Most recently generated encoded signed v1 directory. (v1 auth dirservers
40 * only.) */
41 static cached_dir_t *the_directory = NULL;
43 /** For authoritative directories: the current (v1) network status. */
44 static cached_dir_t the_runningrouters = { NULL, NULL, 0, 0, 0, -1 };
46 static void directory_remove_invalid(void);
47 static cached_dir_t *dirserv_regenerate_directory(void);
48 static char *format_versions_list(config_line_t *ln);
49 struct authdir_config_t;
50 static int add_fingerprint_to_dir(const char *nickname, const char *fp,
51 struct authdir_config_t *list);
52 static uint32_t dirserv_router_get_status(const routerinfo_t *router,
53 const char **msg);
54 static uint32_t
55 dirserv_get_status_impl(const char *fp, const char *nickname,
56 const char *address,
57 uint32_t addr, uint16_t or_port,
58 const char *platform, const char *contact,
59 const char **msg, int should_log);
60 static void clear_cached_dir(cached_dir_t *d);
61 static signed_descriptor_t *get_signed_descriptor_by_fp(const char *fp,
62 int extrainfo,
63 time_t publish_cutoff);
64 static int dirserv_add_extrainfo(extrainfo_t *ei, const char **msg);
66 /************** Fingerprint handling code ************/
68 #define FP_NAMED 1 /**< Listed in fingerprint file. */
69 #define FP_INVALID 2 /**< Believed invalid. */
70 #define FP_REJECT 4 /**< We will not publish this router. */
71 #define FP_BADDIR 8 /**< We'll tell clients to avoid using this as a dir. */
72 #define FP_BADEXIT 16 /**< We'll tell clients not to use this as an exit. */
73 #define FP_UNNAMED 32 /**< Another router has this name in fingerprint file. */
75 /** Encapsulate a nickname and an FP_* status; target of status_by_digest
76 * map. */
77 typedef struct router_status_t {
78 char nickname[MAX_NICKNAME_LEN+1];
79 uint32_t status;
80 } router_status_t;
82 /** List of nickname-\>identity fingerprint mappings for all the routers
83 * that we name. Used to prevent router impersonation. */
84 typedef struct authdir_config_t {
85 strmap_t *fp_by_name; /**< Map from lc nickname to fingerprint. */
86 digestmap_t *status_by_digest; /**< Map from digest to router_status_t. */
87 } authdir_config_t;
89 /** Should be static; exposed for testing. */
90 static authdir_config_t *fingerprint_list = NULL;
92 /** Allocate and return a new, empty, authdir_config_t. */
93 static authdir_config_t *
94 authdir_config_new(void)
96 authdir_config_t *list = tor_malloc_zero(sizeof(authdir_config_t));
97 list->fp_by_name = strmap_new();
98 list->status_by_digest = digestmap_new();
99 return list;
102 /** Add the fingerprint <b>fp</b> for the nickname <b>nickname</b> to
103 * the smartlist of fingerprint_entry_t's <b>list</b>. Return 0 if it's
104 * new, or 1 if we replaced the old value.
106 /* static */ int
107 add_fingerprint_to_dir(const char *nickname, const char *fp,
108 authdir_config_t *list)
110 char *fingerprint;
111 char d[DIGEST_LEN];
112 router_status_t *status;
113 tor_assert(nickname);
114 tor_assert(fp);
115 tor_assert(list);
117 fingerprint = tor_strdup(fp);
118 tor_strstrip(fingerprint, " ");
119 if (base16_decode(d, DIGEST_LEN, fingerprint, strlen(fingerprint))) {
120 log_warn(LD_DIRSERV, "Couldn't decode fingerprint \"%s\"",
121 escaped(fp));
122 tor_free(fingerprint);
123 return 0;
126 if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME)) {
127 log_warn(LD_DIRSERV, "Tried to add a mapping for reserved nickname %s",
128 UNNAMED_ROUTER_NICKNAME);
129 tor_free(fingerprint);
130 return 0;
133 status = digestmap_get(list->status_by_digest, d);
134 if (!status) {
135 status = tor_malloc_zero(sizeof(router_status_t));
136 digestmap_set(list->status_by_digest, d, status);
139 if (nickname[0] != '!') {
140 char *old_fp = strmap_get_lc(list->fp_by_name, nickname);
141 if (old_fp && !strcasecmp(fingerprint, old_fp)) {
142 tor_free(fingerprint);
143 } else {
144 tor_free(old_fp);
145 strmap_set_lc(list->fp_by_name, nickname, fingerprint);
147 status->status |= FP_NAMED;
148 strlcpy(status->nickname, nickname, sizeof(status->nickname));
149 } else {
150 tor_free(fingerprint);
151 if (!strcasecmp(nickname, "!reject")) {
152 status->status |= FP_REJECT;
153 } else if (!strcasecmp(nickname, "!invalid")) {
154 status->status |= FP_INVALID;
155 } else if (!strcasecmp(nickname, "!baddir")) {
156 status->status |= FP_BADDIR;
157 } else if (!strcasecmp(nickname, "!badexit")) {
158 status->status |= FP_BADEXIT;
161 return 0;
164 /** Add the nickname and fingerprint for this OR to the
165 * global list of recognized identity key fingerprints. */
167 dirserv_add_own_fingerprint(const char *nickname, crypto_pk_env_t *pk)
169 char fp[FINGERPRINT_LEN+1];
170 if (crypto_pk_get_fingerprint(pk, fp, 0)<0) {
171 log_err(LD_BUG, "Error computing fingerprint");
172 return -1;
174 if (!fingerprint_list)
175 fingerprint_list = authdir_config_new();
176 add_fingerprint_to_dir(nickname, fp, fingerprint_list);
177 return 0;
180 /** Load the nickname-\>fingerprint mappings stored in the approved-routers
181 * file. The file format is line-based, with each non-blank holding one
182 * nickname, some space, and a fingerprint for that nickname. On success,
183 * replace the current fingerprint list with the new list and return 0. On
184 * failure, leave the current fingerprint list untouched, and
185 * return -1. */
187 dirserv_load_fingerprint_file(void)
189 char *fname;
190 char *cf;
191 char *nickname, *fingerprint;
192 authdir_config_t *fingerprint_list_new;
193 int result;
194 config_line_t *front=NULL, *list;
195 or_options_t *options = get_options();
197 fname = get_datadir_fname("approved-routers");
198 log_info(LD_GENERAL,
199 "Reloading approved fingerprints from \"%s\"...", fname);
201 cf = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
202 if (!cf) {
203 if (options->NamingAuthoritativeDir) {
204 log_warn(LD_FS, "Cannot open fingerprint file '%s'. Failing.", fname);
205 tor_free(fname);
206 return -1;
207 } else {
208 log_info(LD_FS, "Cannot open fingerprint file '%s'. That's ok.", fname);
209 tor_free(fname);
210 return 0;
213 tor_free(fname);
215 result = config_get_lines(cf, &front);
216 tor_free(cf);
217 if (result < 0) {
218 log_warn(LD_CONFIG, "Error reading from fingerprint file");
219 return -1;
222 fingerprint_list_new = authdir_config_new();
224 for (list=front; list; list=list->next) {
225 char digest_tmp[DIGEST_LEN];
226 nickname = list->key; fingerprint = list->value;
227 if (strlen(nickname) > MAX_NICKNAME_LEN) {
228 log_notice(LD_CONFIG,
229 "Nickname '%s' too long in fingerprint file. Skipping.",
230 nickname);
231 continue;
233 if (!is_legal_nickname(nickname) &&
234 strcasecmp(nickname, "!reject") &&
235 strcasecmp(nickname, "!invalid") &&
236 strcasecmp(nickname, "!badexit")) {
237 log_notice(LD_CONFIG,
238 "Invalid nickname '%s' in fingerprint file. Skipping.",
239 nickname);
240 continue;
242 tor_strstrip(fingerprint, " "); /* remove spaces */
243 if (strlen(fingerprint) != HEX_DIGEST_LEN ||
244 base16_decode(digest_tmp, sizeof(digest_tmp),
245 fingerprint, HEX_DIGEST_LEN) < 0) {
246 log_notice(LD_CONFIG,
247 "Invalid fingerprint (nickname '%s', "
248 "fingerprint %s). Skipping.",
249 nickname, fingerprint);
250 continue;
252 if (0==strcasecmp(nickname, DEFAULT_CLIENT_NICKNAME)) {
253 /* If you approved an OR called "client", then clients who use
254 * the default nickname could all be rejected. That's no good. */
255 log_notice(LD_CONFIG,
256 "Authorizing nickname '%s' would break "
257 "many clients; skipping.",
258 DEFAULT_CLIENT_NICKNAME);
259 continue;
261 if (0==strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME)) {
262 /* If you approved an OR called "unnamed", then clients will be
263 * confused. */
264 log_notice(LD_CONFIG,
265 "Authorizing nickname '%s' is not allowed; skipping.",
266 UNNAMED_ROUTER_NICKNAME);
267 continue;
269 if (add_fingerprint_to_dir(nickname, fingerprint, fingerprint_list_new)
270 != 0)
271 log_notice(LD_CONFIG, "Duplicate nickname '%s'.", nickname);
274 config_free_lines(front);
275 dirserv_free_fingerprint_list();
276 fingerprint_list = fingerprint_list_new;
277 /* Delete any routers whose fingerprints we no longer recognize */
278 directory_remove_invalid();
279 return 0;
282 /** Check whether <b>router</b> has a nickname/identity key combination that
283 * we recognize from the fingerprint list, or an IP we automatically act on
284 * according to our configuration. Return the appropriate router status.
286 * If the status is 'FP_REJECT' and <b>msg</b> is provided, set
287 * *<b>msg</b> to an explanation of why. */
288 static uint32_t
289 dirserv_router_get_status(const routerinfo_t *router, const char **msg)
291 char d[DIGEST_LEN];
293 if (crypto_pk_get_digest(router->identity_pkey, d)) {
294 log_warn(LD_BUG,"Error computing fingerprint");
295 if (msg)
296 *msg = "Bug: Error computing fingerprint";
297 return FP_REJECT;
300 return dirserv_get_status_impl(d, router->nickname,
301 router->address,
302 router->addr, router->or_port,
303 router->platform, router->contact_info,
304 msg, 1);
307 /** Return true if there is no point in downloading the router described by
308 * <b>rs</b> because this directory would reject it. */
310 dirserv_would_reject_router(routerstatus_t *rs)
312 uint32_t res;
314 res = dirserv_get_status_impl(rs->identity_digest, rs->nickname,
315 "", /* address is only used in logs */
316 rs->addr, rs->or_port,
317 NULL, NULL,
318 NULL, 0);
320 return (res & FP_REJECT) != 0;
323 /** Helper: Based only on the ID/Nickname combination,
324 * return FP_UNNAMED (unnamed), FP_NAMED (named), or 0 (neither).
326 static uint32_t
327 dirserv_get_name_status(const char *id_digest, const char *nickname)
329 char fp[HEX_DIGEST_LEN+1];
330 char *fp_by_name;
332 base16_encode(fp, sizeof(fp), id_digest, DIGEST_LEN);
334 if ((fp_by_name =
335 strmap_get_lc(fingerprint_list->fp_by_name, nickname))) {
336 if (!strcasecmp(fp, fp_by_name)) {
337 return FP_NAMED;
338 } else {
339 return FP_UNNAMED; /* Wrong fingerprint. */
342 return 0;
345 /** Helper: As dirserv_get_router_status, but takes the router fingerprint
346 * (hex, no spaces), nickname, address (used for logging only), IP address, OR
347 * port, platform (logging only) and contact info (logging only) as arguments.
349 * If should_log is false, do not log messages. (There's not much point in
350 * logging that we're rejecting servers we'll not download.)
352 static uint32_t
353 dirserv_get_status_impl(const char *id_digest, const char *nickname,
354 const char *address,
355 uint32_t addr, uint16_t or_port,
356 const char *platform, const char *contact,
357 const char **msg, int should_log)
359 int reject_unlisted = get_options()->AuthDirRejectUnlisted;
360 uint32_t result = 0;
361 router_status_t *status_by_digest;
363 if (!fingerprint_list)
364 fingerprint_list = authdir_config_new();
366 if (should_log)
367 log_debug(LD_DIRSERV, "%d fingerprints, %d digests known.",
368 strmap_size(fingerprint_list->fp_by_name),
369 digestmap_size(fingerprint_list->status_by_digest));
371 /* 0.1.1.17-rc was the first version that claimed to be stable, doesn't
372 * crash and drop circuits all the time, and is even vaguely compatible with
373 * the current network */
374 if (platform && !tor_version_as_new_as(platform,"0.1.1.17-rc")) {
375 if (msg)
376 *msg = "Tor version is far too old to work.";
377 return FP_REJECT;
380 result = dirserv_get_name_status(id_digest, nickname);
381 if (result & FP_NAMED) {
382 if (should_log)
383 log_debug(LD_DIRSERV,"Good fingerprint for '%s'",nickname);
385 if (result & FP_UNNAMED) {
386 if (should_log) {
387 char *esc_contact = esc_for_log(contact);
388 log_info(LD_DIRSERV,
389 "Mismatched fingerprint for '%s'. "
390 "ContactInfo '%s', platform '%s'.)",
391 nickname,
392 esc_contact,
393 platform ? escaped(platform) : "");
394 tor_free(esc_contact);
396 if (msg)
397 *msg = "Rejected: There is already a named server with this nickname "
398 "and a different fingerprint.";
401 status_by_digest = digestmap_get(fingerprint_list->status_by_digest,
402 id_digest);
403 if (status_by_digest)
404 result |= (status_by_digest->status & ~FP_NAMED);
406 if (result & FP_REJECT) {
407 if (msg)
408 *msg = "Fingerprint is marked rejected";
409 return FP_REJECT;
410 } else if (result & FP_INVALID) {
411 if (msg)
412 *msg = "Fingerprint is marked invalid";
415 if (authdir_policy_baddir_address(addr, or_port)) {
416 if (should_log)
417 log_info(LD_DIRSERV,
418 "Marking '%s' as bad directory because of address '%s'",
419 nickname, address);
420 result |= FP_BADDIR;
423 if (authdir_policy_badexit_address(addr, or_port)) {
424 if (should_log)
425 log_info(LD_DIRSERV, "Marking '%s' as bad exit because of address '%s'",
426 nickname, address);
427 result |= FP_BADEXIT;
430 if (!(result & FP_NAMED)) {
431 if (!authdir_policy_permits_address(addr, or_port)) {
432 if (should_log)
433 log_info(LD_DIRSERV, "Rejecting '%s' because of address '%s'",
434 nickname, address);
435 if (msg)
436 *msg = "Authdir is rejecting routers in this range.";
437 return FP_REJECT;
439 if (!authdir_policy_valid_address(addr, or_port)) {
440 if (should_log)
441 log_info(LD_DIRSERV, "Not marking '%s' valid because of address '%s'",
442 nickname, address);
443 result |= FP_INVALID;
445 if (reject_unlisted) {
446 if (msg)
447 *msg = "Authdir rejects unknown routers.";
448 return FP_REJECT;
452 return result;
455 /** If we are an authoritative dirserver, and the list of approved
456 * servers contains one whose identity key digest is <b>digest</b>,
457 * return that router's nickname. Otherwise return NULL. */
458 const char *
459 dirserv_get_nickname_by_digest(const char *digest)
461 router_status_t *status;
462 if (!fingerprint_list)
463 return NULL;
464 tor_assert(digest);
466 status = digestmap_get(fingerprint_list->status_by_digest, digest);
467 return status ? status->nickname : NULL;
470 /** Clear the current fingerprint list. */
471 void
472 dirserv_free_fingerprint_list(void)
474 if (!fingerprint_list)
475 return;
477 strmap_free(fingerprint_list->fp_by_name, _tor_free);
478 digestmap_free(fingerprint_list->status_by_digest, _tor_free);
479 tor_free(fingerprint_list);
483 * Descriptor list
486 /** Return -1 if <b>ri</b> has a private or otherwise bad address,
487 * unless we're configured to not care. Return 0 if all ok. */
488 static int
489 dirserv_router_has_valid_address(routerinfo_t *ri)
491 struct in_addr iaddr;
492 if (get_options()->DirAllowPrivateAddresses)
493 return 0; /* whatever it is, we're fine with it */
494 if (!tor_inet_aton(ri->address, &iaddr)) {
495 log_info(LD_DIRSERV,"Router '%s' published non-IP address '%s'. Refusing.",
496 ri->nickname, ri->address);
497 return -1;
499 if (is_internal_IP(ntohl(iaddr.s_addr), 0)) {
500 log_info(LD_DIRSERV,
501 "Router '%s' published internal IP address '%s'. Refusing.",
502 ri->nickname, ri->address);
503 return -1; /* it's a private IP, we should reject it */
505 return 0;
508 /** Check whether we, as a directory server, want to accept <b>ri</b>. If so,
509 * set its is_valid,named,running fields and return 0. Otherwise, return -1.
511 * If the router is rejected, set *<b>msg</b> to an explanation of why.
513 * If <b>complain</b> then explain at log-level 'notice' why we refused
514 * a descriptor; else explain at log-level 'info'.
517 authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
518 int complain)
520 /* Okay. Now check whether the fingerprint is recognized. */
521 uint32_t status = dirserv_router_get_status(ri, msg);
522 time_t now;
523 int severity = complain ? LOG_NOTICE : LOG_INFO;
524 tor_assert(msg);
525 if (status & FP_REJECT)
526 return -1; /* msg is already set. */
528 /* Is there too much clock skew? */
529 now = time(NULL);
530 if (ri->cache_info.published_on > now+ROUTER_ALLOW_SKEW) {
531 log_fn(severity, LD_DIRSERV, "Publication time for nickname '%s' is too "
532 "far (%d minutes) in the future; possible clock skew. Not adding "
533 "(%s)",
534 ri->nickname, (int)((ri->cache_info.published_on-now)/60),
535 esc_router_info(ri));
536 *msg = "Rejected: Your clock is set too far in the future, or your "
537 "timezone is not correct.";
538 return -1;
540 if (ri->cache_info.published_on < now-ROUTER_MAX_AGE_TO_PUBLISH) {
541 log_fn(severity, LD_DIRSERV,
542 "Publication time for router with nickname '%s' is too far "
543 "(%d minutes) in the past. Not adding (%s)",
544 ri->nickname, (int)((now-ri->cache_info.published_on)/60),
545 esc_router_info(ri));
546 *msg = "Rejected: Server is expired, or your clock is too far in the past,"
547 " or your timezone is not correct.";
548 return -1;
550 if (dirserv_router_has_valid_address(ri) < 0) {
551 log_fn(severity, LD_DIRSERV,
552 "Router with nickname '%s' has invalid address '%s'. "
553 "Not adding (%s).",
554 ri->nickname, ri->address,
555 esc_router_info(ri));
556 *msg = "Rejected: Address is not an IP, or IP is a private address.";
557 return -1;
559 /* Okay, looks like we're willing to accept this one. */
560 ri->is_named = (status & FP_NAMED) ? 1 : 0;
561 ri->is_valid = (status & FP_INVALID) ? 0 : 1;
562 ri->is_bad_directory = (status & FP_BADDIR) ? 1 : 0;
563 ri->is_bad_exit = (status & FP_BADEXIT) ? 1 : 0;
565 return 0;
568 /** True iff <b>a</b> is more severe than <b>b</b>. */
569 static int
570 WRA_MORE_SEVERE(was_router_added_t a, was_router_added_t b)
572 return a < b;
575 /** As for dirserv_add_descriptor(), but accepts multiple documents, and
576 * returns the most severe error that occurred for any one of them. */
577 was_router_added_t
578 dirserv_add_multiple_descriptors(const char *desc, uint8_t purpose,
579 const char *source,
580 const char **msg)
582 was_router_added_t r, r_tmp;
583 const char *msg_out;
584 smartlist_t *list;
585 const char *s;
586 int n_parsed = 0;
587 time_t now = time(NULL);
588 char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
589 char time_buf[ISO_TIME_LEN+1];
590 int general = purpose == ROUTER_PURPOSE_GENERAL;
591 tor_assert(msg);
593 r=ROUTER_ADDED_SUCCESSFULLY; /*Least severe return value. */
595 format_iso_time(time_buf, now);
596 if (tor_snprintf(annotation_buf, sizeof(annotation_buf),
597 "@uploaded-at %s\n"
598 "@source %s\n"
599 "%s%s%s", time_buf, escaped(source),
600 !general ? "@purpose " : "",
601 !general ? router_purpose_to_string(purpose) : "",
602 !general ? "\n" : "")<0) {
603 *msg = "Couldn't format annotations";
604 return -1;
607 s = desc;
608 list = smartlist_create();
609 if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 0, 0,
610 annotation_buf)) {
611 SMARTLIST_FOREACH(list, routerinfo_t *, ri, {
612 msg_out = NULL;
613 tor_assert(ri->purpose == purpose);
614 r_tmp = dirserv_add_descriptor(ri, &msg_out);
615 if (WRA_MORE_SEVERE(r_tmp, r)) {
616 r = r_tmp;
617 *msg = msg_out;
621 n_parsed += smartlist_len(list);
622 smartlist_clear(list);
624 s = desc;
625 if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 1, 0,
626 NULL)) {
627 SMARTLIST_FOREACH(list, extrainfo_t *, ei, {
628 msg_out = NULL;
630 r_tmp = dirserv_add_extrainfo(ei, &msg_out);
631 if (WRA_MORE_SEVERE(r_tmp, r)) {
632 r = r_tmp;
633 *msg = msg_out;
637 n_parsed += smartlist_len(list);
638 smartlist_free(list);
640 if (! *msg) {
641 if (!n_parsed) {
642 *msg = "No descriptors found in your POST.";
643 if (WRA_WAS_ADDED(r))
644 r = ROUTER_WAS_NOT_NEW;
645 } else {
646 *msg = "(no message)";
650 return r;
653 /** Examine the parsed server descriptor in <b>ri</b> and maybe insert it into
654 * the list of server descriptors. Set *<b>msg</b> to a message that should be
655 * passed back to the origin of this descriptor.
657 * Return the status of the operation
659 * This function is only called when fresh descriptors are posted, not when
660 * we re-load the cache.
662 was_router_added_t
663 dirserv_add_descriptor(routerinfo_t *ri, const char **msg)
665 was_router_added_t r;
666 routerinfo_t *ri_old;
667 char *desc = NULL;
668 size_t desclen = 0;
670 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
671 * network and it'll clog everything up. */
672 if (ri->cache_info.signed_descriptor_len > MAX_DESCRIPTOR_UPLOAD_SIZE) {
673 log_notice(LD_DIR, "Somebody attempted to publish a router descriptor "
674 "with size %d. Either this is an attack, or the "
675 "MAX_DESCRIPTOR_UPLOAD_SIZE (%d) constant is too low.",
676 (int)ri->cache_info.signed_descriptor_len,
677 MAX_DESCRIPTOR_UPLOAD_SIZE);
678 *msg = "Router descriptor was too large";
679 control_event_or_authdir_new_descriptor("REJECTED",
680 ri->cache_info.signed_descriptor_body,
681 ri->cache_info.signed_descriptor_len, *msg);
682 routerinfo_free(ri);
683 return ROUTER_AUTHDIR_REJECTS;
686 /* Check whether this descriptor is semantically identical to the last one
687 * from this server. (We do this here and not in router_add_to_routerlist
688 * because we want to be able to accept the newest router descriptor that
689 * another authority has, so we all converge on the same one.) */
690 ri_old = router_get_by_digest(ri->cache_info.identity_digest);
691 if (ri_old && ri_old->cache_info.published_on < ri->cache_info.published_on
692 && router_differences_are_cosmetic(ri_old, ri)
693 && !router_is_me(ri)) {
694 log_info(LD_DIRSERV,
695 "Not replacing descriptor from '%s'; differences are cosmetic.",
696 ri->nickname);
697 *msg = "Not replacing router descriptor; no information has changed since "
698 "the last one with this identity.";
699 control_event_or_authdir_new_descriptor("DROPPED",
700 ri->cache_info.signed_descriptor_body,
701 ri->cache_info.signed_descriptor_len, *msg);
702 routerinfo_free(ri);
703 return ROUTER_WAS_NOT_NEW;
705 if (control_event_is_interesting(EVENT_AUTHDIR_NEWDESCS)) {
706 /* Make a copy of desc, since router_add_to_routerlist might free
707 * ri and its associated signed_descriptor_t. */
708 desclen = ri->cache_info.signed_descriptor_len;
709 desc = tor_strndup(ri->cache_info.signed_descriptor_body, desclen);
712 r = router_add_to_routerlist(ri, msg, 0, 0);
713 if (!WRA_WAS_ADDED(r)) {
714 /* unless the routerinfo was fine, just out-of-date */
715 if (WRA_WAS_REJECTED(r) && desc)
716 control_event_or_authdir_new_descriptor("REJECTED", desc, desclen, *msg);
717 tor_free(desc);
718 } else {
719 smartlist_t *changed;
720 if (desc)
721 control_event_or_authdir_new_descriptor("ACCEPTED", desc, desclen, *msg);
723 changed = smartlist_create();
724 smartlist_add(changed, ri);
725 control_event_descriptors_changed(changed);
726 smartlist_free(changed);
727 if (!*msg) {
728 *msg = ri->is_valid ? "Descriptor for valid server accepted" :
729 "Descriptor for invalid server accepted";
731 tor_free(desc);
733 return r;
736 /** As dirserv_add_descriptor, but for an extrainfo_t <b>ei</b>. */
737 static was_router_added_t
738 dirserv_add_extrainfo(extrainfo_t *ei, const char **msg)
740 routerinfo_t *ri;
741 int r;
742 tor_assert(msg);
743 *msg = NULL;
745 ri = router_get_by_digest(ei->cache_info.identity_digest);
746 if (!ri) {
747 *msg = "No corresponding router descriptor for extra-info descriptor";
748 extrainfo_free(ei);
749 return ROUTER_BAD_EI;
752 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
753 * network and it'll clog everything up. */
754 if (ei->cache_info.signed_descriptor_len > MAX_EXTRAINFO_UPLOAD_SIZE) {
755 log_notice(LD_DIR, "Somebody attempted to publish an extrainfo "
756 "with size %d. Either this is an attack, or the "
757 "MAX_EXTRAINFO_UPLOAD_SIZE (%d) constant is too low.",
758 (int)ei->cache_info.signed_descriptor_len,
759 MAX_EXTRAINFO_UPLOAD_SIZE);
760 *msg = "Extrainfo document was too large";
761 extrainfo_free(ei);
762 return ROUTER_BAD_EI;
765 if ((r = routerinfo_incompatible_with_extrainfo(ri, ei, NULL, msg))) {
766 extrainfo_free(ei);
767 return r < 0 ? ROUTER_WAS_NOT_NEW : ROUTER_BAD_EI;
769 router_add_extrainfo_to_routerlist(ei, msg, 0, 0);
770 return ROUTER_ADDED_SUCCESSFULLY;
773 /** Remove all descriptors whose nicknames or fingerprints no longer
774 * are allowed by our fingerprint list. (Descriptors that used to be
775 * good can become bad when we reload the fingerprint list.)
777 static void
778 directory_remove_invalid(void)
780 int i;
781 int changed = 0;
782 routerlist_t *rl = router_get_routerlist();
784 routerlist_assert_ok(rl);
786 for (i = 0; i < smartlist_len(rl->routers); ++i) {
787 const char *msg;
788 routerinfo_t *ent = smartlist_get(rl->routers, i);
789 uint32_t r = dirserv_router_get_status(ent, &msg);
790 if (r & FP_REJECT) {
791 log_info(LD_DIRSERV, "Router '%s' is now rejected: %s",
792 ent->nickname, msg?msg:"");
793 routerlist_remove(rl, ent, 0);
794 i--;
795 changed = 1;
796 continue;
798 if (bool_neq((r & FP_NAMED), ent->is_named)) {
799 log_info(LD_DIRSERV,
800 "Router '%s' is now %snamed.", ent->nickname,
801 (r&FP_NAMED)?"":"un");
802 ent->is_named = (r&FP_NAMED)?1:0;
803 changed = 1;
805 if (bool_neq((r & FP_INVALID), !ent->is_valid)) {
806 log_info(LD_DIRSERV, "Router '%s' is now %svalid.", ent->nickname,
807 (r&FP_INVALID) ? "in" : "");
808 ent->is_valid = (r&FP_INVALID)?0:1;
809 changed = 1;
811 if (bool_neq((r & FP_BADDIR), ent->is_bad_directory)) {
812 log_info(LD_DIRSERV, "Router '%s' is now a %s directory", ent->nickname,
813 (r & FP_BADDIR) ? "bad" : "good");
814 ent->is_bad_directory = (r&FP_BADDIR) ? 1: 0;
815 changed = 1;
817 if (bool_neq((r & FP_BADEXIT), ent->is_bad_exit)) {
818 log_info(LD_DIRSERV, "Router '%s' is now a %s exit", ent->nickname,
819 (r & FP_BADEXIT) ? "bad" : "good");
820 ent->is_bad_exit = (r&FP_BADEXIT) ? 1: 0;
821 changed = 1;
824 if (changed)
825 directory_set_dirty();
827 routerlist_assert_ok(rl);
830 /** Write a list of unregistered descriptors into a newly allocated
831 * string and return it. Used by dirserv operators to keep track of
832 * fast nodes that haven't registered.
835 getinfo_helper_dirserv_unregistered(control_connection_t *control_conn,
836 const char *question, char **answer_out)
838 smartlist_t *answerlist;
839 char buf[1024];
840 char *answer;
841 int min_bw = atoi(question);
842 routerlist_t *rl = router_get_routerlist();
844 (void) control_conn;
846 if (strcmpstart(question, "unregistered-servers-"))
847 return 0;
848 question += strlen("unregistered-servers-");
850 answerlist = smartlist_create();
851 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ent, {
852 uint32_t r = dirserv_router_get_status(ent, NULL);
853 if (router_get_advertised_bandwidth(ent) >= (size_t)min_bw &&
854 !(r & FP_NAMED)) {
855 /* then log this one */
856 tor_snprintf(buf, sizeof(buf),
857 "%s: BW %d on '%s'.",
858 ent->nickname, router_get_advertised_bandwidth(ent),
859 ent->platform ? ent->platform : "");
860 smartlist_add(answerlist, tor_strdup(buf));
863 answer = smartlist_join_strings(answerlist, "\r\n", 0, NULL);
864 SMARTLIST_FOREACH(answerlist, char *, cp, tor_free(cp));
865 smartlist_free(answerlist);
866 *answer_out = answer;
867 return 0;
870 /** Mark the directory as <b>dirty</b> -- when we're next asked for a
871 * directory, we will rebuild it instead of reusing the most recently
872 * generated one.
874 void
875 directory_set_dirty(void)
877 time_t now = time(NULL);
878 int set_v1_dirty=0;
880 /* Regenerate stubs only every 8 hours.
881 * XXXX It would be nice to generate less often, but these are just
882 * stubs: it doesn't matter. */
883 #define STUB_REGENERATE_INTERVAL (8*60*60)
884 if (!the_directory || !the_runningrouters.dir)
885 set_v1_dirty = 1;
886 else if (the_directory->published < now - STUB_REGENERATE_INTERVAL ||
887 the_runningrouters.published < now - STUB_REGENERATE_INTERVAL)
888 set_v1_dirty = 1;
890 if (set_v1_dirty) {
891 if (!the_directory_is_dirty)
892 the_directory_is_dirty = now;
893 if (!runningrouters_is_dirty)
894 runningrouters_is_dirty = now;
896 if (!the_v2_networkstatus_is_dirty)
897 the_v2_networkstatus_is_dirty = now;
901 * Allocate and return a description of the status of the server <b>desc</b>,
902 * for use in a v1-style router-status line. The server is listed
903 * as running iff <b>is_live</b> is true.
905 static char *
906 list_single_server_status(routerinfo_t *desc, int is_live)
908 char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
909 char *cp;
911 tor_assert(desc);
913 cp = buf;
914 if (!is_live) {
915 *cp++ = '!';
917 if (desc->is_valid) {
918 strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
919 cp += strlen(cp);
920 *cp++ = '=';
922 *cp++ = '$';
923 base16_encode(cp, HEX_DIGEST_LEN+1, desc->cache_info.identity_digest,
924 DIGEST_LEN);
925 return tor_strdup(buf);
928 /** Each server needs to have passed a reachability test no more
929 * than this number of seconds ago, or he is listed as down in
930 * the directory. */
931 #define REACHABLE_TIMEOUT (45*60)
933 /** Treat a router as alive if
934 * - It's me, and I'm not hibernating.
935 * or - We've found it reachable recently. */
936 void
937 dirserv_set_router_is_running(routerinfo_t *router, time_t now)
939 int answer;
941 if (router_is_me(router) && !we_are_hibernating())
942 answer = 1;
943 else
944 answer = get_options()->AssumeReachable ||
945 now < router->last_reachable + REACHABLE_TIMEOUT;
947 if (router->is_running && !answer) {
948 /* it was running but now it's not. tell rephist. */
949 rep_hist_note_router_unreachable(router->cache_info.identity_digest, now);
952 router->is_running = answer;
955 /** Based on the routerinfo_ts in <b>routers</b>, allocate the
956 * contents of a v1-style router-status line, and store it in
957 * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
959 * If for_controller is true, include the routers with very old descriptors.
960 * If for_controller is &gt;1, use the verbose nickname format.
963 list_server_status_v1(smartlist_t *routers, char **router_status_out,
964 int for_controller)
966 /* List of entries in a router-status style: An optional !, then an optional
967 * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
968 smartlist_t *rs_entries;
969 time_t now = time(NULL);
970 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
971 or_options_t *options = get_options();
972 /* We include v2 dir auths here too, because they need to answer
973 * controllers. Eventually we'll deprecate this whole function;
974 * see also networkstatus_getinfo_by_purpose(). */
975 int authdir = authdir_mode_publishes_statuses(options);
976 tor_assert(router_status_out);
978 rs_entries = smartlist_create();
980 SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
982 if (authdir) {
983 /* Update router status in routerinfo_t. */
984 dirserv_set_router_is_running(ri, now);
986 if (for_controller == 1 || ri->cache_info.published_on >= cutoff)
987 smartlist_add(rs_entries, list_single_server_status(ri, ri->is_running));
988 else if (for_controller > 2) {
989 char name_buf[MAX_VERBOSE_NICKNAME_LEN+2];
990 char *cp = name_buf;
991 if (!ri->is_running)
992 *cp++ = '!';
993 router_get_verbose_nickname(cp, ri);
994 smartlist_add(rs_entries, tor_strdup(name_buf));
998 *router_status_out = smartlist_join_strings(rs_entries, " ", 0, NULL);
1000 SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
1001 smartlist_free(rs_entries);
1003 return 0;
1006 /** Given a (possibly empty) list of config_line_t, each line of which contains
1007 * a list of comma-separated version numbers surrounded by optional space,
1008 * allocate and return a new string containing the version numbers, in order,
1009 * separated by commas. Used to generate Recommended(Client|Server)?Versions
1011 static char *
1012 format_versions_list(config_line_t *ln)
1014 smartlist_t *versions;
1015 char *result;
1016 versions = smartlist_create();
1017 for ( ; ln; ln = ln->next) {
1018 smartlist_split_string(versions, ln->value, ",",
1019 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1021 sort_version_list(versions, 1);
1022 result = smartlist_join_strings(versions,",",0,NULL);
1023 SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
1024 smartlist_free(versions);
1025 return result;
1028 /** Return 1 if <b>ri</b>'s descriptor is "active" -- running, valid,
1029 * not hibernating, and not too old. Else return 0.
1031 static int
1032 router_is_active(routerinfo_t *ri, time_t now)
1034 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
1035 if (ri->cache_info.published_on < cutoff)
1036 return 0;
1037 if (!ri->is_running || !ri->is_valid || ri->is_hibernating)
1038 return 0;
1039 return 1;
1042 /** Generate a new v1 directory and write it into a newly allocated string.
1043 * Point *<b>dir_out</b> to the allocated string. Sign the
1044 * directory with <b>private_key</b>. Return 0 on success, -1 on
1045 * failure. If <b>complete</b> is set, give us all the descriptors;
1046 * otherwise leave out non-running and non-valid ones.
1049 dirserv_dump_directory_to_string(char **dir_out,
1050 crypto_pk_env_t *private_key)
1052 char *cp;
1053 char *identity_pkey; /* Identity key, DER64-encoded. */
1054 char *recommended_versions;
1055 char digest[DIGEST_LEN];
1056 char published[ISO_TIME_LEN+1];
1057 char *buf = NULL;
1058 size_t buf_len;
1059 size_t identity_pkey_len;
1060 time_t now = time(NULL);
1062 tor_assert(dir_out);
1063 *dir_out = NULL;
1065 if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
1066 &identity_pkey_len)<0) {
1067 log_warn(LD_BUG,"write identity_pkey to string failed!");
1068 return -1;
1071 recommended_versions =
1072 format_versions_list(get_options()->RecommendedVersions);
1074 format_iso_time(published, now);
1076 buf_len = 2048+strlen(recommended_versions);
1078 buf = tor_malloc(buf_len);
1079 /* We'll be comparing against buf_len throughout the rest of the
1080 function, though strictly speaking we shouldn't be able to exceed
1081 it. This is C, after all, so we may as well check for buffer
1082 overruns.*/
1084 tor_snprintf(buf, buf_len,
1085 "signed-directory\n"
1086 "published %s\n"
1087 "recommended-software %s\n"
1088 "router-status %s\n"
1089 "dir-signing-key\n%s\n",
1090 published, recommended_versions, "",
1091 identity_pkey);
1093 tor_free(recommended_versions);
1094 tor_free(identity_pkey);
1096 cp = buf + strlen(buf);
1097 *cp = '\0';
1099 /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
1100 signature. */
1101 if (strlcat(buf, "directory-signature ", buf_len) >= buf_len)
1102 goto truncated;
1103 if (strlcat(buf, get_options()->Nickname, buf_len) >= buf_len)
1104 goto truncated;
1105 if (strlcat(buf, "\n", buf_len) >= buf_len)
1106 goto truncated;
1108 if (router_get_dir_hash(buf,digest)) {
1109 log_warn(LD_BUG,"couldn't compute digest");
1110 tor_free(buf);
1111 return -1;
1113 note_crypto_pk_op(SIGN_DIR);
1114 if (router_append_dirobj_signature(buf,buf_len,digest,private_key)<0) {
1115 tor_free(buf);
1116 return -1;
1119 *dir_out = buf;
1120 return 0;
1121 truncated:
1122 log_warn(LD_BUG,"tried to exceed string length.");
1123 tor_free(buf);
1124 return -1;
1127 /********************************************************************/
1129 /* A set of functions to answer questions about how we'd like to behave
1130 * as a directory mirror/client. */
1132 /** Return 1 if we fetch our directory material directly from the
1133 * authorities, rather than from a mirror. */
1135 directory_fetches_from_authorities(or_options_t *options)
1137 routerinfo_t *me;
1138 uint32_t addr;
1139 if (options->FetchDirInfoEarly)
1140 return 1;
1141 if (options->BridgeRelay == 1)
1142 return 0;
1143 if (server_mode(options) && router_pick_published_address(options, &addr)<0)
1144 return 1; /* we don't know our IP address; ask an authority. */
1145 if (options->DirPort == 0)
1146 return 0;
1147 if (!server_mode(options) || !advertised_server_mode())
1148 return 0;
1149 me = router_get_my_routerinfo();
1150 if (!me || !me->dir_port)
1151 return 0; /* if dirport not advertised, return 0 too */
1152 return 1;
1155 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1156 * on the "mirror" schedule rather than the "client" schedule.
1159 directory_fetches_dir_info_early(or_options_t *options)
1161 return directory_fetches_from_authorities(options);
1164 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1165 * on a very passive schedule -- waiting long enough for ordinary clients
1166 * to probably have the info we want. These would include bridge users,
1167 * and maybe others in the future e.g. if a Tor client uses another Tor
1168 * client as a directory guard.
1171 directory_fetches_dir_info_later(or_options_t *options)
1173 return options->UseBridges != 0;
1176 /** Return 1 if we want to cache v2 dir info (each status file).
1179 directory_caches_v2_dir_info(or_options_t *options)
1181 return options->DirPort != 0;
1184 /** Return 1 if we want to keep descriptors, networkstatuses, etc around
1185 * and we're willing to serve them to others. Else return 0.
1188 directory_caches_dir_info(or_options_t *options)
1190 return options->BridgeRelay != 0 || options->DirPort != 0;
1193 /** Return 1 if we want to allow remote people to ask us directory
1194 * requests via the "begin_dir" interface, which doesn't require
1195 * having any separate port open. */
1197 directory_permits_begindir_requests(or_options_t *options)
1199 return options->BridgeRelay != 0 || options->DirPort != 0;
1202 /** Return 1 if we want to allow controllers to ask us directory
1203 * requests via the controller interface, which doesn't require
1204 * having any separate port open. */
1206 directory_permits_controller_requests(or_options_t *options)
1208 return options->DirPort != 0;
1211 /** Return 1 if we have no need to fetch new descriptors. This generally
1212 * happens when we're not a dir cache and we haven't built any circuits
1213 * lately.
1216 directory_too_idle_to_fetch_descriptors(or_options_t *options, time_t now)
1218 return !directory_caches_dir_info(options) &&
1219 !options->FetchUselessDescriptors &&
1220 rep_hist_circbuilding_dormant(now);
1223 /********************************************************************/
1225 /* Used only by non-v1-auth dirservers: The v1 directory and
1226 * runningrouters we'll serve when requested. */
1228 /** The v1 directory we'll serve (as a cache or as an authority) if
1229 * requested. */
1230 static cached_dir_t *cached_directory = NULL;
1231 /** The v1 runningrouters document we'll serve (as a cache or as an authority)
1232 * if requested. */
1233 static cached_dir_t cached_runningrouters = { NULL, NULL, 0, 0, 0, -1 };
1235 /** Used for other dirservers' v2 network statuses. Map from hexdigest to
1236 * cached_dir_t. */
1237 static digestmap_t *cached_v2_networkstatus = NULL;
1239 /** The v3 consensus network status that we're currently serving. */
1240 static cached_dir_t *cached_v3_networkstatus = NULL;
1242 /** Possibly replace the contents of <b>d</b> with the value of
1243 * <b>directory</b> published on <b>when</b>, unless <b>when</b> is older than
1244 * the last value, or too far in the future.
1246 * Does not copy <b>directory</b>; frees it if it isn't used.
1248 static void
1249 set_cached_dir(cached_dir_t *d, char *directory, time_t when)
1251 time_t now = time(NULL);
1252 if (when<=d->published) {
1253 log_info(LD_DIRSERV, "Ignoring old directory; not caching.");
1254 tor_free(directory);
1255 } else if (when>=now+ROUTER_MAX_AGE_TO_PUBLISH) {
1256 log_info(LD_DIRSERV, "Ignoring future directory; not caching.");
1257 tor_free(directory);
1258 } else {
1259 /* if (when>d->published && when<now+ROUTER_MAX_AGE) */
1260 log_debug(LD_DIRSERV, "Caching directory.");
1261 tor_free(d->dir);
1262 d->dir = directory;
1263 d->dir_len = strlen(directory);
1264 tor_free(d->dir_z);
1265 if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
1266 ZLIB_METHOD)) {
1267 log_warn(LD_BUG,"Error compressing cached directory");
1269 d->published = when;
1273 /** Decrement the reference count on <b>d</b>, and free it if it no longer has
1274 * any references. */
1275 void
1276 cached_dir_decref(cached_dir_t *d)
1278 if (!d || --d->refcnt > 0)
1279 return;
1280 clear_cached_dir(d);
1281 tor_free(d);
1284 /** Allocate and return a new cached_dir_t containing the string <b>s</b>,
1285 * published at <b>published</b>. */
1286 cached_dir_t *
1287 new_cached_dir(char *s, time_t published)
1289 cached_dir_t *d = tor_malloc_zero(sizeof(cached_dir_t));
1290 d->refcnt = 1;
1291 d->dir = s;
1292 d->dir_len = strlen(s);
1293 d->published = published;
1294 if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
1295 ZLIB_METHOD)) {
1296 log_warn(LD_BUG, "Error compressing directory");
1298 return d;
1301 /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
1302 static void
1303 clear_cached_dir(cached_dir_t *d)
1305 tor_free(d->dir);
1306 tor_free(d->dir_z);
1307 memset(d, 0, sizeof(cached_dir_t));
1310 /** Free all storage held by the cached_dir_t in <b>d</b>. */
1311 static void
1312 _free_cached_dir(void *_d)
1314 cached_dir_t *d = (cached_dir_t *)_d;
1315 cached_dir_decref(d);
1318 /** If we have no cached v1 directory, or it is older than <b>published</b>,
1319 * then replace it with <b>directory</b>, published at <b>published</b>.
1321 * If <b>published</b> is too old, do nothing.
1323 * If <b>is_running_routers</b>, this is really a v1 running_routers
1324 * document rather than a v1 directory.
1326 void
1327 dirserv_set_cached_directory(const char *directory, time_t published,
1328 int is_running_routers)
1330 time_t now = time(NULL);
1332 if (is_running_routers) {
1333 if (published >= now - MAX_V1_RR_AGE)
1334 set_cached_dir(&cached_runningrouters, tor_strdup(directory), published);
1335 } else {
1336 if (published >= now - MAX_V1_DIRECTORY_AGE) {
1337 cached_dir_decref(cached_directory);
1338 cached_directory = new_cached_dir(tor_strdup(directory), published);
1343 /** If <b>networkstatus</b> is non-NULL, we've just received a v2
1344 * network-status for an authoritative directory with identity digest
1345 * <b>identity</b> published at <b>published</b> -- store it so we can
1346 * serve it to others.
1348 * If <b>networkstatus</b> is NULL, remove the entry with the given
1349 * identity fingerprint from the v2 cache.
1351 void
1352 dirserv_set_cached_networkstatus_v2(const char *networkstatus,
1353 const char *identity,
1354 time_t published)
1356 cached_dir_t *d, *old_d;
1357 smartlist_t *trusted_dirs;
1358 if (!cached_v2_networkstatus)
1359 cached_v2_networkstatus = digestmap_new();
1361 old_d = digestmap_get(cached_v2_networkstatus, identity);
1362 if (!old_d && !networkstatus)
1363 return;
1365 if (networkstatus) {
1366 if (!old_d || published > old_d->published) {
1367 d = new_cached_dir(tor_strdup(networkstatus), published);
1368 digestmap_set(cached_v2_networkstatus, identity, d);
1369 if (old_d)
1370 cached_dir_decref(old_d);
1372 } else {
1373 if (old_d) {
1374 digestmap_remove(cached_v2_networkstatus, identity);
1375 cached_dir_decref(old_d);
1379 /* Now purge old entries. */
1380 trusted_dirs = router_get_trusted_dir_servers();
1381 if (digestmap_size(cached_v2_networkstatus) >
1382 smartlist_len(trusted_dirs) + MAX_UNTRUSTED_NETWORKSTATUSES) {
1383 /* We need to remove the oldest untrusted networkstatus. */
1384 const char *oldest = NULL;
1385 time_t oldest_published = TIME_MAX;
1386 digestmap_iter_t *iter;
1388 for (iter = digestmap_iter_init(cached_v2_networkstatus);
1389 !digestmap_iter_done(iter);
1390 iter = digestmap_iter_next(cached_v2_networkstatus, iter)) {
1391 const char *ident;
1392 void *val;
1393 digestmap_iter_get(iter, &ident, &val);
1394 d = val;
1395 if (d->published < oldest_published &&
1396 !router_digest_is_trusted_dir(ident)) {
1397 oldest = ident;
1398 oldest_published = d->published;
1401 tor_assert(oldest);
1402 d = digestmap_remove(cached_v2_networkstatus, oldest);
1403 if (d)
1404 cached_dir_decref(d);
1408 /** Replace the v3 consensus networkstatus that we're serving with
1409 * <b>networkstatus</b>, published at <b>published</b>. No validation is
1410 * performed. */
1411 void
1412 dirserv_set_cached_networkstatus_v3(const char *networkstatus,
1413 time_t published)
1415 if (cached_v3_networkstatus)
1416 cached_dir_decref(cached_v3_networkstatus);
1417 cached_v3_networkstatus = new_cached_dir(
1418 tor_strdup(networkstatus), published);
1421 /** Remove any v2 networkstatus from the directory cache that was published
1422 * before <b>cutoff</b>. */
1423 void
1424 dirserv_clear_old_networkstatuses(time_t cutoff)
1426 if (!cached_v2_networkstatus)
1427 return;
1429 DIGESTMAP_FOREACH_MODIFY(cached_v2_networkstatus, id, cached_dir_t *, dir) {
1430 if (dir->published < cutoff) {
1431 char *fname;
1432 fname = networkstatus_get_cache_filename(id);
1433 if (file_status(fname) == FN_FILE) {
1434 log_info(LD_DIR, "Removing too-old untrusted networkstatus in %s",
1435 fname);
1436 unlink(fname);
1438 tor_free(fname);
1439 cached_dir_decref(dir);
1440 MAP_DEL_CURRENT(id);
1442 } DIGESTMAP_FOREACH_END
1445 /** Remove any v1 info from the directory cache that was published
1446 * too long ago. */
1447 void
1448 dirserv_clear_old_v1_info(time_t now)
1450 if (cached_directory &&
1451 cached_directory->published < (now - MAX_V1_DIRECTORY_AGE)) {
1452 cached_dir_decref(cached_directory);
1453 cached_directory = NULL;
1455 if (cached_runningrouters.published < (now - MAX_V1_RR_AGE)) {
1456 clear_cached_dir(&cached_runningrouters);
1460 /** Helper: If we're an authority for the right directory version (v1 or v2)
1461 * (based on <b>auth_type</b>), try to regenerate
1462 * auth_src as appropriate and return it, falling back to cache_src on
1463 * failure. If we're a cache, simply return cache_src.
1465 static cached_dir_t *
1466 dirserv_pick_cached_dir_obj(cached_dir_t *cache_src,
1467 cached_dir_t *auth_src,
1468 time_t dirty, cached_dir_t *(*regenerate)(void),
1469 const char *name,
1470 authority_type_t auth_type)
1472 or_options_t *options = get_options();
1473 int authority = (auth_type == V1_AUTHORITY && authdir_mode_v1(options)) ||
1474 (auth_type == V2_AUTHORITY && authdir_mode_v2(options));
1476 if (!authority || authdir_mode_bridge(options)) {
1477 return cache_src;
1478 } else {
1479 /* We're authoritative. */
1480 if (regenerate != NULL) {
1481 if (dirty && dirty + DIR_REGEN_SLACK_TIME < time(NULL)) {
1482 if (!(auth_src = regenerate())) {
1483 log_err(LD_BUG, "Couldn't generate %s?", name);
1484 exit(1);
1486 } else {
1487 log_info(LD_DIRSERV, "The %s is still clean; reusing.", name);
1490 return auth_src ? auth_src : cache_src;
1494 /** Return the most recently generated encoded signed v1 directory,
1495 * generating a new one as necessary. If not a v1 authoritative directory
1496 * may return NULL if no directory is yet cached. */
1497 cached_dir_t *
1498 dirserv_get_directory(void)
1500 return dirserv_pick_cached_dir_obj(cached_directory, the_directory,
1501 the_directory_is_dirty,
1502 dirserv_regenerate_directory,
1503 "v1 server directory", V1_AUTHORITY);
1506 /** Only called by v1 auth dirservers.
1507 * Generate a fresh v1 directory; set the_directory and return a pointer
1508 * to the new value.
1510 static cached_dir_t *
1511 dirserv_regenerate_directory(void)
1513 char *new_directory=NULL;
1515 if (dirserv_dump_directory_to_string(&new_directory, get_identity_key())) {
1516 log_warn(LD_BUG, "Error creating directory.");
1517 tor_free(new_directory);
1518 return NULL;
1520 cached_dir_decref(the_directory);
1521 the_directory = new_cached_dir(new_directory, time(NULL));
1522 log_info(LD_DIRSERV,"New directory (size %d) has been built.",
1523 (int)the_directory->dir_len);
1524 log_debug(LD_DIRSERV,"New directory (size %d):\n%s",
1525 (int)the_directory->dir_len, the_directory->dir);
1527 the_directory_is_dirty = 0;
1529 /* Save the directory to disk so we re-load it quickly on startup.
1531 dirserv_set_cached_directory(the_directory->dir, time(NULL), 0);
1533 return the_directory;
1536 /** Only called by v1 auth dirservers.
1537 * Replace the current running-routers list with a newly generated one. */
1538 static cached_dir_t *
1539 generate_runningrouters(void)
1541 char *s=NULL;
1542 char digest[DIGEST_LEN];
1543 char published[ISO_TIME_LEN+1];
1544 size_t len;
1545 crypto_pk_env_t *private_key = get_identity_key();
1546 char *identity_pkey; /* Identity key, DER64-encoded. */
1547 size_t identity_pkey_len;
1549 if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
1550 &identity_pkey_len)<0) {
1551 log_warn(LD_BUG,"write identity_pkey to string failed!");
1552 goto err;
1554 format_iso_time(published, time(NULL));
1556 len = 2048;
1557 s = tor_malloc_zero(len);
1558 tor_snprintf(s, len,
1559 "network-status\n"
1560 "published %s\n"
1561 "router-status %s\n"
1562 "dir-signing-key\n%s"
1563 "directory-signature %s\n",
1564 published, "", identity_pkey,
1565 get_options()->Nickname);
1566 tor_free(identity_pkey);
1567 if (router_get_runningrouters_hash(s,digest)) {
1568 log_warn(LD_BUG,"couldn't compute digest");
1569 goto err;
1571 note_crypto_pk_op(SIGN_DIR);
1572 if (router_append_dirobj_signature(s, len, digest, private_key)<0)
1573 goto err;
1575 set_cached_dir(&the_runningrouters, s, time(NULL));
1576 runningrouters_is_dirty = 0;
1578 return &the_runningrouters;
1579 err:
1580 tor_free(s);
1581 return NULL;
1584 /** Set *<b>rr</b> to the most recently generated encoded signed
1585 * running-routers list, generating a new one as necessary. Return the
1586 * size of the directory on success, and 0 on failure. */
1587 cached_dir_t *
1588 dirserv_get_runningrouters(void)
1590 return dirserv_pick_cached_dir_obj(
1591 &cached_runningrouters, &the_runningrouters,
1592 runningrouters_is_dirty,
1593 generate_runningrouters,
1594 "v1 network status list", V1_AUTHORITY);
1597 /** Return the latest downloaded consensus networkstatus in encoded, signed,
1598 * optionally compressed format, suitable for sending to clients. */
1599 cached_dir_t *
1600 dirserv_get_consensus(void)
1602 return cached_v3_networkstatus;
1605 /** For authoritative directories: the current (v2) network status. */
1606 static cached_dir_t *the_v2_networkstatus = NULL;
1608 /** Return true iff our opinion of the routers has been stale for long
1609 * enough that we should generate a new v2 network status doc. */
1610 static int
1611 should_generate_v2_networkstatus(void)
1613 return authdir_mode_v2(get_options()) &&
1614 the_v2_networkstatus_is_dirty &&
1615 the_v2_networkstatus_is_dirty + DIR_REGEN_SLACK_TIME < time(NULL);
1618 /** If a router's uptime is at least this value, then it is always
1619 * considered stable, regardless of the rest of the network. This
1620 * way we resist attacks where an attacker doubles the size of the
1621 * network using allegedly high-uptime nodes, displacing all the
1622 * current guards. */
1623 #define UPTIME_TO_GUARANTEE_STABLE (3600*24*30)
1624 /** If a router's MTBF is at least this value, then it is always stable.
1625 * See above. (Corresponds to about 7 days for current decay rates.) */
1626 #define MTBF_TO_GUARANTEE_STABLE (60*60*24*5)
1627 /** Similarly, we protect sufficiently fast nodes from being pushed
1628 * out of the set of Fast nodes. */
1629 #define BANDWIDTH_TO_GUARANTEE_FAST (100*1024)
1630 /** Similarly, every node with sufficient bandwidth can be considered
1631 * for Guard status. */
1632 #define BANDWIDTH_TO_GUARANTEE_GUARD (250*1024)
1633 /** Similarly, every node with at least this much weighted time known can be
1634 * considered familiar enough to be a guard. Corresponds to about 20 days for
1635 * current decay rates.
1637 #define TIME_KNOWN_TO_GUARANTEE_FAMILIAR (8*24*60*60)
1638 /** Similarly, every node with sufficient WFU is around enough to be a guard.
1640 #define WFU_TO_GUARANTEE_GUARD (0.995)
1642 /* Thresholds for server performance: set by
1643 * dirserv_compute_performance_thresholds, and used by
1644 * generate_v2_networkstatus */
1646 /** Any router with an uptime of at least this value is stable. */
1647 static uint32_t stable_uptime = 0; /* start at a safe value */
1648 /** Any router with an mtbf of at least this value is stable. */
1649 static double stable_mtbf = 0.0;
1650 /** If true, we have measured enough mtbf info to look at stable_mtbf rather
1651 * than stable_uptime. */
1652 static int enough_mtbf_info = 0;
1653 /** Any router with a weighted fractional uptime of at least this much might
1654 * be good as a guard. */
1655 static double guard_wfu = 0.0;
1656 /** Don't call a router a guard unless we've known about it for at least this
1657 * many seconds. */
1658 static long guard_tk = 0;
1659 /** Any router with a bandwidth at least this high is "Fast" */
1660 static uint32_t fast_bandwidth = 0;
1661 /** If exits can be guards, then all guards must have a bandwidth this
1662 * high. */
1663 static uint32_t guard_bandwidth_including_exits = 0;
1664 /** If exits can't be guards, then all guards must have a bandwidth this
1665 * high. */
1666 static uint32_t guard_bandwidth_excluding_exits = 0;
1667 /** Total bandwidth of all the routers we're considering. */
1668 static uint64_t total_bandwidth = 0;
1669 /** Total bandwidth of all the exit routers we're considering. */
1670 static uint64_t total_exit_bandwidth = 0;
1672 /** Helper: estimate the uptime of a router given its stated uptime and the
1673 * amount of time since it last stated its stated uptime. */
1674 static INLINE long
1675 real_uptime(routerinfo_t *router, time_t now)
1677 if (now < router->cache_info.published_on)
1678 return router->uptime;
1679 else
1680 return router->uptime + (now - router->cache_info.published_on);
1683 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1684 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1685 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1686 * bandwidth.
1688 static int
1689 dirserv_thinks_router_is_unreliable(time_t now,
1690 routerinfo_t *router,
1691 int need_uptime, int need_capacity)
1693 if (need_uptime) {
1694 if (!enough_mtbf_info) {
1695 /* XXX022 Once most authorities are on v3, we should change the rule from
1696 * "use uptime if we don't have mtbf data" to "don't advertise Stable on
1697 * v3 if we don't have enough mtbf data." */
1698 long uptime = real_uptime(router, now);
1699 if ((unsigned)uptime < stable_uptime &&
1700 (unsigned)uptime < UPTIME_TO_GUARANTEE_STABLE)
1701 return 1;
1702 } else {
1703 double mtbf =
1704 rep_hist_get_stability(router->cache_info.identity_digest, now);
1705 if (mtbf < stable_mtbf &&
1706 mtbf < MTBF_TO_GUARANTEE_STABLE)
1707 return 1;
1710 if (need_capacity) {
1711 uint32_t bw = router_get_advertised_bandwidth(router);
1712 if (bw < fast_bandwidth)
1713 return 1;
1715 return 0;
1718 /** Return true iff <b>router</b> should be assigned the "HSDir" flag.
1719 * Right now this means it advertises support for it, it has a high
1720 * uptime, and it's currently considered Running.
1722 * This function needs to be called after router-\>is_running has
1723 * been set.
1725 static int
1726 dirserv_thinks_router_is_hs_dir(routerinfo_t *router, time_t now)
1728 long uptime = real_uptime(router, now);
1730 return (router->wants_to_be_hs_dir &&
1731 uptime > get_options()->MinUptimeHidServDirectoryV2 &&
1732 router->is_running);
1735 /** Look through the routerlist, the Mean Time Between Failure history, and
1736 * the Weighted Fractional Uptime history, and use them to set thresholds for
1737 * the Stable, Fast, and Guard flags. Update the fields stable_uptime,
1738 * stable_mtbf, enough_mtbf_info, guard_wfu, guard_tk, fast_bandwidth,
1739 * guard_bandwidh_including_exits, guard_bandwidth_excluding_exits,
1740 * total_bandwidth, and total_exit_bandwidth.
1742 * Also, set the is_exit flag of each router appropriately. */
1743 static void
1744 dirserv_compute_performance_thresholds(routerlist_t *rl)
1746 int n_active, n_active_nonexit, n_familiar;
1747 uint32_t *uptimes, *bandwidths, *bandwidths_excluding_exits;
1748 long *tks;
1749 double *mtbfs, *wfus;
1750 time_t now = time(NULL);
1752 /* initialize these all here, in case there are no routers */
1753 stable_uptime = 0;
1754 stable_mtbf = 0;
1755 fast_bandwidth = 0;
1756 guard_bandwidth_including_exits = 0;
1757 guard_bandwidth_excluding_exits = 0;
1758 guard_tk = 0;
1759 guard_wfu = 0;
1760 total_bandwidth = 0;
1761 total_exit_bandwidth = 0;
1763 /* Initialize arrays that will hold values for each router. We'll
1764 * sort them and use that to compute thresholds. */
1765 n_active = n_active_nonexit = 0;
1766 /* Uptime for every active router. */
1767 uptimes = tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
1768 /* Bandwidth for every active router. */
1769 bandwidths = tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
1770 /* Bandwidth for every active non-exit router. */
1771 bandwidths_excluding_exits =
1772 tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
1773 /* Weighted mean time between failure for each active router. */
1774 mtbfs = tor_malloc(sizeof(double)*smartlist_len(rl->routers));
1775 /* Time-known for each active router. */
1776 tks = tor_malloc(sizeof(long)*smartlist_len(rl->routers));
1777 /* Weighted fractional uptime for each active router. */
1778 wfus = tor_malloc(sizeof(double)*smartlist_len(rl->routers));
1780 /* Now, fill in the arrays. */
1781 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
1782 if (router_is_active(ri, now)) {
1783 const char *id = ri->cache_info.identity_digest;
1784 uint32_t bw;
1785 ri->is_exit = exit_policy_is_general_exit(ri->exit_policy);
1786 uptimes[n_active] = (uint32_t)real_uptime(ri, now);
1787 mtbfs[n_active] = rep_hist_get_stability(id, now);
1788 tks [n_active] = rep_hist_get_weighted_time_known(id, now);
1789 bandwidths[n_active] = bw = router_get_advertised_bandwidth(ri);
1790 total_bandwidth += bw;
1791 if (ri->is_exit && !ri->is_bad_exit) {
1792 total_exit_bandwidth += bw;
1793 } else {
1794 bandwidths_excluding_exits[n_active_nonexit] = bw;
1795 ++n_active_nonexit;
1797 ++n_active;
1801 /* Now, compute thresholds. */
1802 if (n_active) {
1803 /* The median uptime is stable. */
1804 stable_uptime = median_uint32(uptimes, n_active);
1805 /* The median mtbf is stable, if we have enough mtbf info */
1806 stable_mtbf = median_double(mtbfs, n_active);
1807 /* The 12.5th percentile bandwidth is fast. */
1808 fast_bandwidth = find_nth_uint32(bandwidths, n_active, n_active/8);
1809 /* (Now bandwidths is sorted.) */
1810 if (fast_bandwidth < ROUTER_REQUIRED_MIN_BANDWIDTH)
1811 fast_bandwidth = bandwidths[n_active/4];
1812 guard_bandwidth_including_exits = bandwidths[(n_active-1)/2];
1813 guard_tk = find_nth_long(tks, n_active, n_active/8);
1816 if (guard_tk > TIME_KNOWN_TO_GUARANTEE_FAMILIAR)
1817 guard_tk = TIME_KNOWN_TO_GUARANTEE_FAMILIAR;
1819 if (fast_bandwidth > BANDWIDTH_TO_GUARANTEE_FAST)
1820 fast_bandwidth = BANDWIDTH_TO_GUARANTEE_FAST;
1822 /* Now that we have a time-known that 7/8 routers are known longer than,
1823 * fill wfus with the wfu of every such "familiar" router. */
1824 n_familiar = 0;
1825 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
1826 if (router_is_active(ri, now)) {
1827 const char *id = ri->cache_info.identity_digest;
1828 long tk = rep_hist_get_weighted_time_known(id, now);
1829 if (tk < guard_tk)
1830 continue;
1831 wfus[n_familiar++] = rep_hist_get_weighted_fractional_uptime(id, now);
1834 if (n_familiar)
1835 guard_wfu = median_double(wfus, n_familiar);
1836 if (guard_wfu > WFU_TO_GUARANTEE_GUARD)
1837 guard_wfu = WFU_TO_GUARANTEE_GUARD;
1839 enough_mtbf_info = rep_hist_have_measured_enough_stability();
1841 if (n_active_nonexit) {
1842 guard_bandwidth_excluding_exits =
1843 median_uint32(bandwidths_excluding_exits, n_active_nonexit);
1846 log(LOG_INFO, LD_DIRSERV,
1847 "Cutoffs: For Stable, %lu sec uptime, %lu sec MTBF. "
1848 "For Fast: %lu bytes/sec. "
1849 "For Guard: WFU %.03lf%%, time-known %lu sec, "
1850 "and bandwidth %lu or %lu bytes/sec. We%s have enough stability data.",
1851 (unsigned long)stable_uptime,
1852 (unsigned long)stable_mtbf,
1853 (unsigned long)fast_bandwidth,
1854 guard_wfu*100,
1855 (unsigned long)guard_tk,
1856 (unsigned long)guard_bandwidth_including_exits,
1857 (unsigned long)guard_bandwidth_excluding_exits,
1858 enough_mtbf_info ? "" : " don't ");
1860 tor_free(uptimes);
1861 tor_free(mtbfs);
1862 tor_free(bandwidths);
1863 tor_free(bandwidths_excluding_exits);
1864 tor_free(tks);
1865 tor_free(wfus);
1868 /** Given a platform string as in a routerinfo_t (possibly null), return a
1869 * newly allocated version string for a networkstatus document, or NULL if the
1870 * platform doesn't give a Tor version. */
1871 static char *
1872 version_from_platform(const char *platform)
1874 if (platform && !strcmpstart(platform, "Tor ")) {
1875 const char *eos = find_whitespace(platform+4);
1876 if (eos && !strcmpstart(eos, " (r")) {
1877 /* XXXX Unify this logic with the other version extraction
1878 * logic in routerparse.c. */
1879 eos = find_whitespace(eos+1);
1881 if (eos) {
1882 return tor_strndup(platform, eos-platform);
1885 return NULL;
1888 /** Helper: write the router-status information in <b>rs</b> into <b>buf</b>,
1889 * which has at least <b>buf_len</b> free characters. Do NUL-termination.
1890 * Use the same format as in network-status documents. If <b>version</b> is
1891 * non-NULL, add a "v" line for the platform. Return 0 on success, -1 on
1892 * failure. If <b>first_line_only</b> is true, don't include any flags
1893 * or version line.
1896 routerstatus_format_entry(char *buf, size_t buf_len,
1897 routerstatus_t *rs, const char *version,
1898 int first_line_only, int v2_format)
1899 /* XXX: first_line_only and v2_format should probably be be both
1900 * replaced by a single purpose parameter.
1903 int r;
1904 struct in_addr in;
1905 char *cp;
1906 char *summary;
1908 char published[ISO_TIME_LEN+1];
1909 char ipaddr[INET_NTOA_BUF_LEN];
1910 char identity64[BASE64_DIGEST_LEN+1];
1911 char digest64[BASE64_DIGEST_LEN+1];
1913 format_iso_time(published, rs->published_on);
1914 digest_to_base64(identity64, rs->identity_digest);
1915 digest_to_base64(digest64, rs->descriptor_digest);
1916 in.s_addr = htonl(rs->addr);
1917 tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
1919 r = tor_snprintf(buf, buf_len,
1920 "r %s %s %s %s %s %d %d\n",
1921 rs->nickname,
1922 identity64,
1923 digest64,
1924 published,
1925 ipaddr,
1926 (int)rs->or_port,
1927 (int)rs->dir_port);
1928 if (r<0) {
1929 log_warn(LD_BUG, "Not enough space in buffer.");
1930 return -1;
1932 if (first_line_only)
1933 return 0;
1935 cp = buf + strlen(buf);
1936 /* NOTE: Whenever this list expands, be sure to increase MAX_FLAG_LINE_LEN*/
1937 r = tor_snprintf(cp, buf_len - (cp-buf),
1938 "s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
1939 /* These must stay in alphabetical order. */
1940 rs->is_authority?" Authority":"",
1941 rs->is_bad_directory?" BadDirectory":"",
1942 rs->is_bad_exit?" BadExit":"",
1943 rs->is_exit?" Exit":"",
1944 rs->is_fast?" Fast":"",
1945 rs->is_possible_guard?" Guard":"",
1946 rs->is_hs_dir?" HSDir":"",
1947 rs->is_named?" Named":"",
1948 rs->is_running?" Running":"",
1949 rs->is_stable?" Stable":"",
1950 rs->is_unnamed?" Unnamed":"",
1951 rs->is_v2_dir?" V2Dir":"",
1952 rs->is_valid?" Valid":"");
1953 if (r<0) {
1954 log_warn(LD_BUG, "Not enough space in buffer.");
1955 return -1;
1957 cp += strlen(cp);
1959 /* length of "opt v \n" */
1960 #define V_LINE_OVERHEAD 7
1961 if (version && strlen(version) < MAX_V_LINE_LEN - V_LINE_OVERHEAD) {
1962 if (tor_snprintf(cp, buf_len - (cp-buf), "opt v %s\n", version)<0) {
1963 log_warn(LD_BUG, "Unable to print router version.");
1964 return -1;
1966 cp += strlen(cp);
1969 if (!v2_format) {
1970 routerinfo_t* desc = router_get_by_digest(rs->identity_digest);
1972 /* Blow up more or less nicely if we didn't get anything or not the
1973 * thing we expected.
1975 if (!desc) {
1976 char id[HEX_DIGEST_LEN+1];
1977 char dd[HEX_DIGEST_LEN+1];
1979 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
1980 base16_encode(dd, sizeof(dd), rs->descriptor_digest, DIGEST_LEN);
1981 log_warn(LD_BUG, "Cannot get any descriptor for %s "
1982 "(wanted descriptor %s).",
1983 id, dd);
1984 return -1;
1986 if (memcmp(desc->cache_info.signed_descriptor_digest,
1987 rs->descriptor_digest,
1988 DIGEST_LEN)) {
1989 char rl_d[HEX_DIGEST_LEN+1];
1990 char rs_d[HEX_DIGEST_LEN+1];
1991 char id[HEX_DIGEST_LEN+1];
1993 base16_encode(rl_d, sizeof(rl_d),
1994 desc->cache_info.signed_descriptor_digest, DIGEST_LEN);
1995 base16_encode(rs_d, sizeof(rs_d), rs->descriptor_digest, DIGEST_LEN);
1996 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
1997 log_err(LD_BUG, "descriptor digest in routerlist does not match "
1998 "the one in routerstatus: %s vs %s "
1999 "(router %s)\n",
2000 rl_d, rs_d, id);
2002 tor_assert(!memcmp(desc->cache_info.signed_descriptor_digest,
2003 rs->descriptor_digest,
2004 DIGEST_LEN));
2007 r = tor_snprintf(cp, buf_len - (cp-buf),
2008 "w Bandwidth=%d\n",
2009 router_get_advertised_bandwidth_capped(desc) / 1024);
2010 if (r<0) {
2011 log_warn(LD_BUG, "Not enough space in buffer.");
2012 return -1;
2014 cp += strlen(cp);
2016 summary = policy_summarize(desc->exit_policy);
2017 r = tor_snprintf(cp, buf_len - (cp-buf), "p %s\n", summary);
2018 if (r<0) {
2019 log_warn(LD_BUG, "Not enough space in buffer.");
2020 tor_free(summary);
2021 return -1;
2023 cp += strlen(cp);
2024 tor_free(summary);
2027 return 0;
2030 /** Helper for sorting: compares two routerinfos first by address, and then by
2031 * descending order of "usefulness". (An authority is more useful than a
2032 * non-authority; a running router is more useful than a non-running router;
2033 * and a router with more bandwidth is more useful than one with less.)
2035 static int
2036 _compare_routerinfo_by_ip_and_bw(const void **a, const void **b)
2038 routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
2039 int first_is_auth, second_is_auth;
2040 uint32_t bw_first, bw_second;
2042 /* we return -1 if first should appear before second... that is,
2043 * if first is a better router. */
2044 if (first->addr < second->addr)
2045 return -1;
2046 else if (first->addr > second->addr)
2047 return 1;
2049 /* Potentially, this next bit could cause k n lg n memcmp calls. But in
2050 * reality, we will almost never get here, since addresses will usually be
2051 * different. */
2053 first_is_auth =
2054 router_digest_is_trusted_dir(first->cache_info.identity_digest);
2055 second_is_auth =
2056 router_digest_is_trusted_dir(second->cache_info.identity_digest);
2058 if (first_is_auth && !second_is_auth)
2059 return -1;
2060 else if (!first_is_auth && second_is_auth)
2061 return 1;
2063 else if (first->is_running && !second->is_running)
2064 return -1;
2065 else if (!first->is_running && second->is_running)
2066 return 1;
2068 bw_first = router_get_advertised_bandwidth(first);
2069 bw_second = router_get_advertised_bandwidth(second);
2071 if (bw_first > bw_second)
2072 return -1;
2073 else if (bw_first < bw_second)
2074 return 1;
2076 /* They're equal! Compare by identity digest, so there's a
2077 * deterministic order and we avoid flapping. */
2078 return memcmp(first->cache_info.identity_digest,
2079 second->cache_info.identity_digest,
2080 DIGEST_LEN);
2083 /** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
2084 * whose keys are the identity digests of those routers that we're going to
2085 * exclude for Sybil-like appearance. */
2086 static digestmap_t *
2087 get_possible_sybil_list(const smartlist_t *routers)
2089 or_options_t *options = get_options();
2090 digestmap_t *omit_as_sybil;
2091 smartlist_t *routers_by_ip = smartlist_create();
2092 uint32_t last_addr;
2093 int addr_count;
2094 /* Allow at most this number of Tor servers on a single IP address, ... */
2095 int max_with_same_addr = options->AuthDirMaxServersPerAddr;
2096 /* ... unless it's a directory authority, in which case allow more. */
2097 int max_with_same_addr_on_authority = options->AuthDirMaxServersPerAuthAddr;
2098 if (max_with_same_addr <= 0)
2099 max_with_same_addr = INT_MAX;
2100 if (max_with_same_addr_on_authority <= 0)
2101 max_with_same_addr_on_authority = INT_MAX;
2103 smartlist_add_all(routers_by_ip, routers);
2104 smartlist_sort(routers_by_ip, _compare_routerinfo_by_ip_and_bw);
2105 omit_as_sybil = digestmap_new();
2107 last_addr = 0;
2108 addr_count = 0;
2109 SMARTLIST_FOREACH(routers_by_ip, routerinfo_t *, ri,
2111 if (last_addr != ri->addr) {
2112 last_addr = ri->addr;
2113 addr_count = 1;
2114 } else if (++addr_count > max_with_same_addr) {
2115 if (!router_addr_is_trusted_dir(ri->addr) ||
2116 addr_count > max_with_same_addr_on_authority)
2117 digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
2121 smartlist_free(routers_by_ip);
2122 return omit_as_sybil;
2125 /** Extract status information from <b>ri</b> and from other authority
2126 * functions and store it in <b>rs</b>>. If <b>naming</b>, consider setting
2127 * the named flag in <b>rs</b>. If not <b>exits_can_be_guards</b>, never mark
2128 * an exit as a guard. If <b>listbadexits</b>, consider setting the badexit
2129 * flag.
2131 * We assume that ri-\>is_running has already been set, e.g. by
2132 * dirserv_set_router_is_running(ri, now);
2134 void
2135 set_routerstatus_from_routerinfo(routerstatus_t *rs,
2136 routerinfo_t *ri, time_t now,
2137 int naming, int exits_can_be_guards,
2138 int listbadexits, int listbaddirs)
2140 int unstable_version =
2141 !tor_version_as_new_as(ri->platform,"0.1.1.16-rc-cvs");
2142 memset(rs, 0, sizeof(routerstatus_t));
2144 rs->is_authority =
2145 router_digest_is_trusted_dir(ri->cache_info.identity_digest);
2147 /* Already set by compute_performance_thresholds. */
2148 rs->is_exit = ri->is_exit;
2149 rs->is_stable = ri->is_stable =
2150 router_is_active(ri, now) &&
2151 !dirserv_thinks_router_is_unreliable(now, ri, 1, 0) &&
2152 !unstable_version;
2153 rs->is_fast = ri->is_fast =
2154 router_is_active(ri, now) &&
2155 !dirserv_thinks_router_is_unreliable(now, ri, 0, 1);
2156 rs->is_running = ri->is_running; /* computed above */
2158 if (naming) {
2159 uint32_t name_status = dirserv_get_name_status(
2160 ri->cache_info.identity_digest, ri->nickname);
2161 rs->is_named = (naming && (name_status & FP_NAMED)) ? 1 : 0;
2162 rs->is_unnamed = (naming && (name_status & FP_UNNAMED)) ? 1 : 0;
2164 rs->is_valid = ri->is_valid;
2166 if (rs->is_fast &&
2167 (!rs->is_exit || exits_can_be_guards) &&
2168 (router_get_advertised_bandwidth(ri) >= BANDWIDTH_TO_GUARANTEE_GUARD ||
2169 router_get_advertised_bandwidth(ri) >=
2170 (exits_can_be_guards ? guard_bandwidth_including_exits :
2171 guard_bandwidth_excluding_exits))) {
2172 long tk = rep_hist_get_weighted_time_known(
2173 ri->cache_info.identity_digest, now);
2174 double wfu = rep_hist_get_weighted_fractional_uptime(
2175 ri->cache_info.identity_digest, now);
2176 rs->is_possible_guard = (wfu >= guard_wfu && tk >= guard_tk) ? 1 : 0;
2177 } else {
2178 rs->is_possible_guard = 0;
2180 rs->is_bad_directory = listbaddirs && ri->is_bad_directory;
2181 rs->is_bad_exit = listbadexits && ri->is_bad_exit;
2182 ri->is_hs_dir = dirserv_thinks_router_is_hs_dir(ri, now);
2183 rs->is_hs_dir = ri->is_hs_dir;
2184 rs->is_v2_dir = ri->dir_port != 0;
2186 if (!strcasecmp(ri->nickname, UNNAMED_ROUTER_NICKNAME))
2187 rs->is_named = rs->is_unnamed = 0;
2189 rs->published_on = ri->cache_info.published_on;
2190 memcpy(rs->identity_digest, ri->cache_info.identity_digest, DIGEST_LEN);
2191 memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest,
2192 DIGEST_LEN);
2193 rs->addr = ri->addr;
2194 strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname));
2195 rs->or_port = ri->or_port;
2196 rs->dir_port = ri->dir_port;
2199 /** Routerstatus <b>rs</b> is part of a group of routers that are on
2200 * too narrow an IP-space. Clear out its flags: we don't want people
2201 * using it.
2203 static void
2204 clear_status_flags_on_sybil(routerstatus_t *rs)
2206 rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
2207 rs->is_running = rs->is_named = rs->is_valid = rs->is_v2_dir =
2208 rs->is_hs_dir = rs->is_possible_guard = rs->is_bad_exit =
2209 rs->is_bad_directory = 0;
2210 /* FFFF we might want some mechanism to check later on if we
2211 * missed zeroing any flags: it's easy to add a new flag but
2212 * forget to add it to this clause. */
2215 /** Clear all the status flags in routerinfo <b>router</b>. We put this
2216 * function here because it's eerily similar to
2217 * clear_status_flags_on_sybil() above. One day we should merge them. */
2218 void
2219 router_clear_status_flags(routerinfo_t *router)
2221 router->is_valid = router->is_running = router->is_hs_dir =
2222 router->is_fast = router->is_stable =
2223 router->is_possible_guard = router->is_exit =
2224 router->is_bad_exit = router->is_bad_directory = 0;
2227 /** Return a new networkstatus_t* containing our current opinion. (For v3
2228 * authorities) */
2229 networkstatus_t *
2230 dirserv_generate_networkstatus_vote_obj(crypto_pk_env_t *private_key,
2231 authority_cert_t *cert)
2233 or_options_t *options = get_options();
2234 networkstatus_t *v3_out = NULL;
2235 uint32_t addr;
2236 char *hostname = NULL, *client_versions = NULL, *server_versions = NULL;
2237 const char *contact;
2238 smartlist_t *routers, *routerstatuses;
2239 char identity_digest[DIGEST_LEN];
2240 char signing_key_digest[DIGEST_LEN];
2241 int naming = options->NamingAuthoritativeDir;
2242 int listbadexits = options->AuthDirListBadExits;
2243 int listbaddirs = options->AuthDirListBadDirs;
2244 int exits_can_be_guards;
2245 routerlist_t *rl = router_get_routerlist();
2246 time_t now = time(NULL);
2247 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2248 networkstatus_voter_info_t *voter = NULL;
2249 vote_timing_t timing;
2250 digestmap_t *omit_as_sybil = NULL;
2251 int vote_on_reachability = 1;
2253 tor_assert(private_key);
2254 tor_assert(cert);
2256 if (now - time_of_process_start <
2257 options->TestingAuthDirTimeToLearnReachability)
2258 vote_on_reachability = 0;
2260 if (resolve_my_address(LOG_WARN, options, &addr, &hostname)<0) {
2261 log_warn(LD_NET, "Couldn't resolve my hostname");
2262 return NULL;
2264 if (!strchr(hostname, '.')) {
2265 tor_free(hostname);
2266 hostname = tor_dup_ip(addr);
2268 if (crypto_pk_get_digest(private_key, signing_key_digest)<0) {
2269 log_err(LD_BUG, "Error computing signing key digest");
2270 return NULL;
2272 if (crypto_pk_get_digest(cert->identity_key, identity_digest)<0) {
2273 log_err(LD_BUG, "Error computing identity key digest");
2274 return NULL;
2277 if (options->VersioningAuthoritativeDir) {
2278 client_versions = format_versions_list(options->RecommendedClientVersions);
2279 server_versions = format_versions_list(options->RecommendedServerVersions);
2282 contact = get_options()->ContactInfo;
2283 if (!contact)
2284 contact = "(none)";
2286 /* precompute this part, since we need it to decide what "stable"
2287 * means. */
2288 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2289 dirserv_set_router_is_running(ri, now);
2292 dirserv_compute_performance_thresholds(rl);
2294 /* XXXX We should take steps to keep this from oscillating if
2295 * total_exit_bandwidth is close to total_bandwidth/3. */
2296 exits_can_be_guards = total_exit_bandwidth >= (total_bandwidth / 3);
2298 routers = smartlist_create();
2299 smartlist_add_all(routers, rl->routers);
2300 routers_sort_by_identity(routers);
2301 omit_as_sybil = get_possible_sybil_list(routers);
2303 routerstatuses = smartlist_create();
2305 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
2306 if (ri->cache_info.published_on >= cutoff) {
2307 routerstatus_t *rs;
2308 vote_routerstatus_t *vrs;
2310 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
2311 rs = &vrs->status;
2312 set_routerstatus_from_routerinfo(rs, ri, now,
2313 naming, exits_can_be_guards,
2314 listbadexits, listbaddirs);
2316 if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
2317 clear_status_flags_on_sybil(rs);
2319 if (!vote_on_reachability)
2320 rs->is_running = 0;
2322 vrs->version = version_from_platform(ri->platform);
2323 smartlist_add(routerstatuses, vrs);
2326 smartlist_free(routers);
2327 digestmap_free(omit_as_sybil, NULL);
2329 v3_out = tor_malloc_zero(sizeof(networkstatus_t));
2331 v3_out->type = NS_TYPE_VOTE;
2332 dirvote_get_preferred_voting_intervals(&timing);
2333 v3_out->published = now;
2335 char tbuf[ISO_TIME_LEN+1];
2336 networkstatus_t *current_consensus =
2337 networkstatus_get_live_consensus(now);
2338 long last_consensus_interval; /* only used to pick a valid_after */
2339 if (current_consensus)
2340 last_consensus_interval = current_consensus->fresh_until -
2341 current_consensus->valid_after;
2342 else
2343 last_consensus_interval = options->TestingV3AuthInitialVotingInterval;
2344 v3_out->valid_after =
2345 dirvote_get_start_of_next_interval(now, (int)last_consensus_interval);
2346 format_iso_time(tbuf, v3_out->valid_after);
2347 log_notice(LD_DIR,"Choosing valid-after time in vote as %s: "
2348 "consensus_set=%d, last_interval=%d",
2349 tbuf, current_consensus?1:0, (int)last_consensus_interval);
2351 v3_out->fresh_until = v3_out->valid_after + timing.vote_interval;
2352 v3_out->valid_until = v3_out->valid_after +
2353 (timing.vote_interval * timing.n_intervals_valid);
2354 v3_out->vote_seconds = timing.vote_delay;
2355 v3_out->dist_seconds = timing.dist_delay;
2356 tor_assert(v3_out->vote_seconds > 0);
2357 tor_assert(v3_out->dist_seconds > 0);
2358 tor_assert(timing.n_intervals_valid > 0);
2360 v3_out->client_versions = client_versions;
2361 v3_out->server_versions = server_versions;
2362 v3_out->known_flags = smartlist_create();
2363 smartlist_split_string(v3_out->known_flags,
2364 "Authority Exit Fast Guard HSDir Stable V2Dir Valid",
2365 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2366 if (vote_on_reachability)
2367 smartlist_add(v3_out->known_flags, tor_strdup("Running"));
2368 if (listbaddirs)
2369 smartlist_add(v3_out->known_flags, tor_strdup("BadDirectory"));
2370 if (listbadexits)
2371 smartlist_add(v3_out->known_flags, tor_strdup("BadExit"));
2372 if (naming) {
2373 smartlist_add(v3_out->known_flags, tor_strdup("Named"));
2374 smartlist_add(v3_out->known_flags, tor_strdup("Unnamed"));
2376 smartlist_sort_strings(v3_out->known_flags);
2378 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
2379 voter->nickname = tor_strdup(options->Nickname);
2380 memcpy(voter->identity_digest, identity_digest, DIGEST_LEN);
2381 voter->address = hostname;
2382 voter->addr = addr;
2383 voter->dir_port = options->DirPort;
2384 voter->or_port = options->ORPort;
2385 voter->contact = tor_strdup(contact);
2386 memcpy(voter->signing_key_digest, signing_key_digest, DIGEST_LEN);
2387 if (options->V3AuthUseLegacyKey) {
2388 authority_cert_t *c = get_my_v3_legacy_cert();
2389 if (c) {
2390 crypto_pk_get_digest(c->identity_key, voter->legacy_id_digest);
2394 v3_out->voters = smartlist_create();
2395 smartlist_add(v3_out->voters, voter);
2396 v3_out->cert = authority_cert_dup(cert);
2397 v3_out->routerstatus_list = routerstatuses;
2398 /* Note: networkstatus_digest is unset; it won't get set until we actually
2399 * format the vote. */
2401 return v3_out;
2404 /** For v2 authoritative directories only: Replace the contents of
2405 * <b>the_v2_networkstatus</b> with a newly generated network status
2406 * object. */
2407 static cached_dir_t *
2408 generate_v2_networkstatus_opinion(void)
2410 cached_dir_t *r = NULL;
2411 size_t len, identity_pkey_len;
2412 char *status = NULL, *client_versions = NULL, *server_versions = NULL,
2413 *identity_pkey = NULL, *hostname = NULL;
2414 char *outp, *endp;
2415 or_options_t *options = get_options();
2416 char fingerprint[FINGERPRINT_LEN+1];
2417 char ipaddr[INET_NTOA_BUF_LEN];
2418 char published[ISO_TIME_LEN+1];
2419 char digest[DIGEST_LEN];
2420 struct in_addr in;
2421 uint32_t addr;
2422 crypto_pk_env_t *private_key;
2423 routerlist_t *rl = router_get_routerlist();
2424 time_t now = time(NULL);
2425 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2426 int naming = options->NamingAuthoritativeDir;
2427 int versioning = options->VersioningAuthoritativeDir;
2428 int listbaddirs = options->AuthDirListBadDirs;
2429 int listbadexits = options->AuthDirListBadExits;
2430 int exits_can_be_guards;
2431 const char *contact;
2432 char *version_lines = NULL;
2433 smartlist_t *routers = NULL;
2434 digestmap_t *omit_as_sybil = NULL;
2436 private_key = get_identity_key();
2438 if (resolve_my_address(LOG_WARN, options, &addr, &hostname)<0) {
2439 log_warn(LD_NET, "Couldn't resolve my hostname");
2440 goto done;
2442 in.s_addr = htonl(addr);
2443 tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
2445 format_iso_time(published, now);
2447 client_versions = format_versions_list(options->RecommendedClientVersions);
2448 server_versions = format_versions_list(options->RecommendedServerVersions);
2450 if (crypto_pk_write_public_key_to_string(private_key, &identity_pkey,
2451 &identity_pkey_len)<0) {
2452 log_warn(LD_BUG,"Writing public key to string failed.");
2453 goto done;
2456 if (crypto_pk_get_fingerprint(private_key, fingerprint, 0)<0) {
2457 log_err(LD_BUG, "Error computing fingerprint");
2458 goto done;
2461 contact = get_options()->ContactInfo;
2462 if (!contact)
2463 contact = "(none)";
2465 if (versioning) {
2466 size_t v_len = 64+strlen(client_versions)+strlen(server_versions);
2467 version_lines = tor_malloc(v_len);
2468 tor_snprintf(version_lines, v_len,
2469 "client-versions %s\nserver-versions %s\n",
2470 client_versions, server_versions);
2471 } else {
2472 version_lines = tor_strdup("");
2475 len = 4096+strlen(client_versions)+strlen(server_versions);
2476 len += identity_pkey_len*2;
2477 len += (RS_ENTRY_LEN)*smartlist_len(rl->routers);
2479 status = tor_malloc(len);
2480 tor_snprintf(status, len,
2481 "network-status-version 2\n"
2482 "dir-source %s %s %d\n"
2483 "fingerprint %s\n"
2484 "contact %s\n"
2485 "published %s\n"
2486 "dir-options%s%s%s%s\n"
2487 "%s" /* client version line, server version line. */
2488 "dir-signing-key\n%s",
2489 hostname, ipaddr, (int)options->DirPort,
2490 fingerprint,
2491 contact,
2492 published,
2493 naming ? " Names" : "",
2494 listbaddirs ? " BadDirectories" : "",
2495 listbadexits ? " BadExits" : "",
2496 versioning ? " Versions" : "",
2497 version_lines,
2498 identity_pkey);
2499 outp = status + strlen(status);
2500 endp = status + len;
2502 /* precompute this part, since we need it to decide what "stable"
2503 * means. */
2504 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2505 dirserv_set_router_is_running(ri, now);
2508 dirserv_compute_performance_thresholds(rl);
2510 /* XXXX We should take steps to keep this from oscillating if
2511 * total_exit_bandwidth is close to total_bandwidth/3. */
2512 exits_can_be_guards = total_exit_bandwidth >= (total_bandwidth / 3);
2514 routers = smartlist_create();
2515 smartlist_add_all(routers, rl->routers);
2516 routers_sort_by_identity(routers);
2518 omit_as_sybil = get_possible_sybil_list(routers);
2520 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
2521 if (ri->cache_info.published_on >= cutoff) {
2522 routerstatus_t rs;
2523 char *version = version_from_platform(ri->platform);
2525 set_routerstatus_from_routerinfo(&rs, ri, now,
2526 naming, exits_can_be_guards,
2527 listbadexits, listbaddirs);
2529 if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
2530 clear_status_flags_on_sybil(&rs);
2532 if (routerstatus_format_entry(outp, endp-outp, &rs, version, 0, 1)) {
2533 log_warn(LD_BUG, "Unable to print router status.");
2534 tor_free(version);
2535 goto done;
2537 tor_free(version);
2538 outp += strlen(outp);
2542 if (tor_snprintf(outp, endp-outp, "directory-signature %s\n",
2543 get_options()->Nickname)<0) {
2544 log_warn(LD_BUG, "Unable to write signature line.");
2545 goto done;
2547 if (router_get_networkstatus_v2_hash(status, digest)<0) {
2548 log_warn(LD_BUG, "Unable to hash network status");
2549 goto done;
2551 outp += strlen(outp);
2553 note_crypto_pk_op(SIGN_DIR);
2554 if (router_append_dirobj_signature(outp,endp-outp,digest,private_key)<0) {
2555 log_warn(LD_BUG, "Unable to sign router status.");
2556 goto done;
2560 networkstatus_v2_t *ns;
2561 if (!(ns = networkstatus_v2_parse_from_string(status))) {
2562 log_err(LD_BUG,"Generated a networkstatus we couldn't parse.");
2563 goto done;
2565 networkstatus_v2_free(ns);
2569 cached_dir_t **ns_ptr = &the_v2_networkstatus;
2570 if (*ns_ptr)
2571 cached_dir_decref(*ns_ptr);
2572 *ns_ptr = new_cached_dir(status, now);
2573 status = NULL; /* So it doesn't get double-freed. */
2574 the_v2_networkstatus_is_dirty = 0;
2575 router_set_networkstatus_v2((*ns_ptr)->dir, now, NS_GENERATED, NULL);
2576 r = *ns_ptr;
2579 done:
2580 tor_free(client_versions);
2581 tor_free(server_versions);
2582 tor_free(version_lines);
2583 tor_free(status);
2584 tor_free(hostname);
2585 tor_free(identity_pkey);
2586 if (routers)
2587 smartlist_free(routers);
2588 if (omit_as_sybil)
2589 digestmap_free(omit_as_sybil, NULL);
2590 return r;
2593 /** Given the portion of a networkstatus request URL after "tor/status/" in
2594 * <b>key</b>, append to <b>result</b> the digests of the identity keys of the
2595 * networkstatus objects that the client has requested. */
2596 void
2597 dirserv_get_networkstatus_v2_fingerprints(smartlist_t *result,
2598 const char *key)
2600 tor_assert(result);
2602 if (!cached_v2_networkstatus)
2603 cached_v2_networkstatus = digestmap_new();
2605 if (should_generate_v2_networkstatus())
2606 generate_v2_networkstatus_opinion();
2608 if (!strcmp(key,"authority")) {
2609 if (authdir_mode_v2(get_options())) {
2610 routerinfo_t *me = router_get_my_routerinfo();
2611 if (me)
2612 smartlist_add(result,
2613 tor_memdup(me->cache_info.identity_digest, DIGEST_LEN));
2615 } else if (!strcmp(key, "all")) {
2616 if (digestmap_size(cached_v2_networkstatus)) {
2617 digestmap_iter_t *iter;
2618 iter = digestmap_iter_init(cached_v2_networkstatus);
2619 while (!digestmap_iter_done(iter)) {
2620 const char *ident;
2621 void *val;
2622 digestmap_iter_get(iter, &ident, &val);
2623 smartlist_add(result, tor_memdup(ident, DIGEST_LEN));
2624 iter = digestmap_iter_next(cached_v2_networkstatus, iter);
2626 } else {
2627 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
2628 trusted_dir_server_t *, ds,
2629 if (ds->type & V2_AUTHORITY)
2630 smartlist_add(result, tor_memdup(ds->digest, DIGEST_LEN)));
2632 smartlist_sort_digests(result);
2633 if (smartlist_len(result) == 0)
2634 log_info(LD_DIRSERV,
2635 "Client requested 'all' network status objects; we have none.");
2636 } else if (!strcmpstart(key, "fp/")) {
2637 dir_split_resource_into_fingerprints(key+3, result, NULL, 1, 1);
2641 /** Look for a network status object as specified by <b>key</b>, which should
2642 * be either "authority" (to find a network status generated by us), a hex
2643 * identity digest (to find a network status generated by given directory), or
2644 * "all" (to return all the v2 network status objects we have).
2646 void
2647 dirserv_get_networkstatus_v2(smartlist_t *result,
2648 const char *key)
2650 cached_dir_t *cached;
2651 smartlist_t *fingerprints = smartlist_create();
2652 tor_assert(result);
2654 if (!cached_v2_networkstatus)
2655 cached_v2_networkstatus = digestmap_new();
2657 dirserv_get_networkstatus_v2_fingerprints(fingerprints, key);
2658 SMARTLIST_FOREACH(fingerprints, const char *, fp,
2660 if (router_digest_is_me(fp) && should_generate_v2_networkstatus())
2661 generate_v2_networkstatus_opinion();
2662 cached = digestmap_get(cached_v2_networkstatus, fp);
2663 if (cached) {
2664 smartlist_add(result, cached);
2665 } else {
2666 char hexbuf[HEX_DIGEST_LEN+1];
2667 base16_encode(hexbuf, sizeof(hexbuf), fp, DIGEST_LEN);
2668 log_info(LD_DIRSERV, "Don't know about any network status with "
2669 "fingerprint '%s'", hexbuf);
2672 SMARTLIST_FOREACH(fingerprints, char *, cp, tor_free(cp));
2673 smartlist_free(fingerprints);
2676 /** As dirserv_get_routerdescs(), but instead of getting signed_descriptor_t
2677 * pointers, adds copies of digests to fps_out, and doesn't use the
2678 * /tor/server/ prefix. For a /d/ request, adds descriptor digests; for other
2679 * requests, adds identity digests.
2682 dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
2683 const char **msg, int for_unencrypted_conn,
2684 int is_extrainfo)
2686 int by_id = 1;
2687 *msg = NULL;
2689 if (!strcmp(key, "all")) {
2690 routerlist_t *rl = router_get_routerlist();
2691 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2692 smartlist_add(fps_out,
2693 tor_memdup(r->cache_info.identity_digest, DIGEST_LEN)));
2694 } else if (!strcmp(key, "authority")) {
2695 routerinfo_t *ri = router_get_my_routerinfo();
2696 if (ri)
2697 smartlist_add(fps_out,
2698 tor_memdup(ri->cache_info.identity_digest, DIGEST_LEN));
2699 } else if (!strcmpstart(key, "d/")) {
2700 by_id = 0;
2701 key += strlen("d/");
2702 dir_split_resource_into_fingerprints(key, fps_out, NULL, 1, 1);
2703 } else if (!strcmpstart(key, "fp/")) {
2704 key += strlen("fp/");
2705 dir_split_resource_into_fingerprints(key, fps_out, NULL, 1, 1);
2706 } else {
2707 *msg = "Key not recognized";
2708 return -1;
2711 if (for_unencrypted_conn) {
2712 /* Remove anything that insists it not be sent unencrypted. */
2713 SMARTLIST_FOREACH(fps_out, char *, cp, {
2714 signed_descriptor_t *sd;
2715 if (by_id)
2716 sd = get_signed_descriptor_by_fp(cp,is_extrainfo,0);
2717 else if (is_extrainfo)
2718 sd = extrainfo_get_by_descriptor_digest(cp);
2719 else
2720 sd = router_get_by_descriptor_digest(cp);
2721 if (sd && !sd->send_unencrypted) {
2722 tor_free(cp);
2723 SMARTLIST_DEL_CURRENT(fps_out, cp);
2728 if (!smartlist_len(fps_out)) {
2729 *msg = "Servers unavailable";
2730 return -1;
2732 return 0;
2735 /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
2736 * <b>key</b>. The key should be either
2737 * - "/tor/server/authority" for our own routerinfo;
2738 * - "/tor/server/all" for all the routerinfos we have, concatenated;
2739 * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
2740 * hex identity digests; or
2741 * - "/tor/server/d/D" where D is a plus-separated sequence
2742 * of server descriptor digests, in hex.
2744 * Return 0 if we found some matching descriptors, or -1 if we do not
2745 * have any descriptors, no matching descriptors, or if we did not
2746 * recognize the key (URL).
2747 * If -1 is returned *<b>msg</b> will be set to an appropriate error
2748 * message.
2750 * XXXX rename this function. It's only called from the controller.
2751 * XXXX in fact, refactor this function, mergeing as much as possible.
2754 dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
2755 const char **msg)
2757 *msg = NULL;
2759 if (!strcmp(key, "/tor/server/all")) {
2760 routerlist_t *rl = router_get_routerlist();
2761 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2762 smartlist_add(descs_out, &(r->cache_info)));
2763 } else if (!strcmp(key, "/tor/server/authority")) {
2764 routerinfo_t *ri = router_get_my_routerinfo();
2765 if (ri)
2766 smartlist_add(descs_out, &(ri->cache_info));
2767 } else if (!strcmpstart(key, "/tor/server/d/")) {
2768 smartlist_t *digests = smartlist_create();
2769 key += strlen("/tor/server/d/");
2770 dir_split_resource_into_fingerprints(key, digests, NULL, 1, 1);
2771 SMARTLIST_FOREACH(digests, const char *, d,
2773 signed_descriptor_t *sd = router_get_by_descriptor_digest(d);
2774 if (sd)
2775 smartlist_add(descs_out,sd);
2777 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
2778 smartlist_free(digests);
2779 } else if (!strcmpstart(key, "/tor/server/fp/")) {
2780 smartlist_t *digests = smartlist_create();
2781 time_t cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
2782 key += strlen("/tor/server/fp/");
2783 dir_split_resource_into_fingerprints(key, digests, NULL, 1, 1);
2784 SMARTLIST_FOREACH(digests, const char *, d,
2786 if (router_digest_is_me(d)) {
2787 /* make sure desc_routerinfo exists */
2788 routerinfo_t *ri = router_get_my_routerinfo();
2789 if (ri)
2790 smartlist_add(descs_out, &(ri->cache_info));
2791 } else {
2792 routerinfo_t *ri = router_get_by_digest(d);
2793 /* Don't actually serve a descriptor that everyone will think is
2794 * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
2795 * Tors from downloading descriptors that they will throw away.
2797 if (ri && ri->cache_info.published_on > cutoff)
2798 smartlist_add(descs_out, &(ri->cache_info));
2801 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
2802 smartlist_free(digests);
2803 } else {
2804 *msg = "Key not recognized";
2805 return -1;
2808 if (!smartlist_len(descs_out)) {
2809 *msg = "Servers unavailable";
2810 return -1;
2812 return 0;
2815 /** Called when a TLS handshake has completed successfully with a
2816 * router listening at <b>address</b>:<b>or_port</b>, and has yielded
2817 * a certificate with digest <b>digest_rcvd</b>.
2819 * Also, if as_advertised is 1, then inform the reachability checker
2820 * that we could get to this guy.
2822 void
2823 dirserv_orconn_tls_done(const char *address,
2824 uint16_t or_port,
2825 const char *digest_rcvd,
2826 int as_advertised)
2828 routerlist_t *rl = router_get_routerlist();
2829 time_t now = time(NULL);
2830 int bridge_auth = authdir_mode_bridge(get_options());
2831 tor_assert(address);
2832 tor_assert(digest_rcvd);
2834 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2835 if (!strcasecmp(address, ri->address) && or_port == ri->or_port &&
2836 as_advertised &&
2837 !memcmp(ri->cache_info.identity_digest, digest_rcvd, DIGEST_LEN)) {
2838 /* correct digest. mark this router reachable! */
2839 if (!bridge_auth || ri->purpose == ROUTER_PURPOSE_BRIDGE) {
2840 log_info(LD_DIRSERV, "Found router %s to be reachable. Yay.",
2841 ri->nickname);
2842 rep_hist_note_router_reachable(digest_rcvd, now);
2843 ri->last_reachable = now;
2847 /* FFFF Maybe we should reinstate the code that dumps routers with the same
2848 * addr/port but with nonmatching keys, but instead of dumping, we should
2849 * skip testing. */
2852 /** Auth dir server only: if <b>try_all</b> is 1, launch connections to
2853 * all known routers; else we want to load balance such that we only
2854 * try a few connections per call.
2856 * The load balancing is such that if we get called once every ten
2857 * seconds, we will cycle through all the tests in 1280 seconds (a
2858 * bit over 20 minutes).
2860 void
2861 dirserv_test_reachability(time_t now, int try_all)
2863 /* XXX decide what to do here; see or-talk thread "purging old router
2864 * information, revocation." -NM
2865 * We can't afford to mess with this in 0.1.2.x. The reason is that
2866 * if we stop doing reachability tests on some of routerlist, then
2867 * we'll for-sure think they're down, which may have unexpected
2868 * effects in other parts of the code. It doesn't hurt much to do
2869 * the testing, and directory authorities are easy to upgrade. Let's
2870 * wait til 0.2.0. -RD */
2871 // time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2872 routerlist_t *rl = router_get_routerlist();
2873 static char ctr = 0;
2874 int bridge_auth = authdir_mode_bridge(get_options());
2876 SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, router) {
2877 const char *id_digest = router->cache_info.identity_digest;
2878 tor_addr_t router_addr;
2879 if (router_is_me(router))
2880 continue;
2881 if (bridge_auth && router->purpose != ROUTER_PURPOSE_BRIDGE)
2882 continue; /* bridge authorities only test reachability on bridges */
2883 // if (router->cache_info.published_on > cutoff)
2884 // continue;
2885 if (try_all || (((uint8_t)id_digest[0]) % 128) == ctr) {
2886 log_debug(LD_OR,"Testing reachability of %s at %s:%u.",
2887 router->nickname, router->address, router->or_port);
2888 /* Remember when we started trying to determine reachability */
2889 if (!router->testing_since)
2890 router->testing_since = now;
2891 tor_addr_from_ipv4h(&router_addr, router->addr);
2892 connection_or_connect(&router_addr, router->or_port, id_digest);
2894 } SMARTLIST_FOREACH_END(router);
2895 if (!try_all) /* increment ctr */
2896 ctr = (ctr + 1) % 128;
2899 /** Given a fingerprint <b>fp</b> which is either set if we're looking
2900 * for a v2 status, or zeroes if we're looking for a v3 status, return
2901 * a pointer to the appropriate cached dir object, or NULL if there isn't
2902 * one available. */
2903 static cached_dir_t *
2904 lookup_cached_dir_by_fp(const char *fp)
2906 cached_dir_t *d = NULL;
2907 if (tor_digest_is_zero(fp) && cached_v3_networkstatus)
2908 d = cached_v3_networkstatus;
2909 else if (router_digest_is_me(fp) && the_v2_networkstatus)
2910 d = the_v2_networkstatus;
2911 else if (cached_v2_networkstatus)
2912 d = digestmap_get(cached_v2_networkstatus, fp);
2913 return d;
2916 /** Remove from <b>fps</b> every networkstatus key where both
2917 * a) we have a networkstatus document and
2918 * b) it is not newer than <b>cutoff</b>.
2920 * Return 1 if any items were present at all; else return 0.
2923 dirserv_remove_old_statuses(smartlist_t *fps, time_t cutoff)
2925 int found_any = 0;
2926 SMARTLIST_FOREACH(fps, char *, digest,
2928 cached_dir_t *d = lookup_cached_dir_by_fp(digest);
2929 if (!d)
2930 continue;
2931 found_any = 1;
2932 if (d->published <= cutoff) {
2933 tor_free(digest);
2934 SMARTLIST_DEL_CURRENT(fps, digest);
2938 return found_any;
2941 /** Return the cache-info for identity fingerprint <b>fp</b>, or
2942 * its extra-info document if <b>extrainfo</b> is true. Return
2943 * NULL if not found or if the descriptor is older than
2944 * <b>publish_cutoff</b>. */
2945 static signed_descriptor_t *
2946 get_signed_descriptor_by_fp(const char *fp, int extrainfo,
2947 time_t publish_cutoff)
2949 if (router_digest_is_me(fp)) {
2950 if (extrainfo)
2951 return &(router_get_my_extrainfo()->cache_info);
2952 else
2953 return &(router_get_my_routerinfo()->cache_info);
2954 } else {
2955 routerinfo_t *ri = router_get_by_digest(fp);
2956 if (ri &&
2957 ri->cache_info.published_on > publish_cutoff) {
2958 if (extrainfo)
2959 return extrainfo_get_by_descriptor_digest(
2960 ri->cache_info.extra_info_digest);
2961 else
2962 return &ri->cache_info;
2965 return NULL;
2968 /** Return true iff we have any of the docments (extrainfo or routerdesc)
2969 * specified by the fingerprints in <b>fps</b> and <b>spool_src</b>. Used to
2970 * decide whether to send a 404. */
2972 dirserv_have_any_serverdesc(smartlist_t *fps, int spool_src)
2974 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
2975 SMARTLIST_FOREACH(fps, const char *, fp, {
2976 switch (spool_src)
2978 case DIR_SPOOL_EXTRA_BY_DIGEST:
2979 if (extrainfo_get_by_descriptor_digest(fp)) return 1;
2980 break;
2981 case DIR_SPOOL_SERVER_BY_DIGEST:
2982 if (router_get_by_descriptor_digest(fp)) return 1;
2983 break;
2984 case DIR_SPOOL_EXTRA_BY_FP:
2985 case DIR_SPOOL_SERVER_BY_FP:
2986 if (get_signed_descriptor_by_fp(fp,
2987 spool_src == DIR_SPOOL_EXTRA_BY_FP, publish_cutoff))
2988 return 1;
2989 break;
2992 return 0;
2995 /** Return an approximate estimate of the number of bytes that will
2996 * be needed to transmit the server descriptors (if is_serverdescs --
2997 * they can be either d/ or fp/ queries) or networkstatus objects (if
2998 * !is_serverdescs) listed in <b>fps</b>. If <b>compressed</b> is set,
2999 * we guess how large the data will be after compression.
3001 * The return value is an estimate; it might be larger or smaller.
3003 size_t
3004 dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
3005 int compressed)
3007 size_t result;
3008 tor_assert(fps);
3009 if (is_serverdescs) {
3010 int n = smartlist_len(fps);
3011 routerinfo_t *me = router_get_my_routerinfo();
3012 result = (me?me->cache_info.signed_descriptor_len:2048) * n;
3013 if (compressed)
3014 result /= 2; /* observed compressability is between 35 and 55%. */
3015 } else {
3016 result = 0;
3017 SMARTLIST_FOREACH(fps, const char *, digest, {
3018 cached_dir_t *dir = lookup_cached_dir_by_fp(digest);
3019 if (dir)
3020 result += compressed ? dir->dir_z_len : dir->dir_len;
3023 return result;
3026 /** When we're spooling data onto our outbuf, add more whenever we dip
3027 * below this threshold. */
3028 #define DIRSERV_BUFFER_MIN 16384
3030 /** Spooling helper: called when we have no more data to spool to <b>conn</b>.
3031 * Flushes any remaining data to be (un)compressed, and changes the spool
3032 * source to NONE. Returns 0 on success, negative on failure. */
3033 static int
3034 connection_dirserv_finish_spooling(dir_connection_t *conn)
3036 if (conn->zlib_state) {
3037 connection_write_to_buf_zlib("", 0, conn, 1);
3038 tor_zlib_free(conn->zlib_state);
3039 conn->zlib_state = NULL;
3041 conn->dir_spool_src = DIR_SPOOL_NONE;
3042 return 0;
3045 /** Spooling helper: called when we're sending a bunch of server descriptors,
3046 * and the outbuf has become too empty. Pulls some entries from
3047 * fingerprint_stack, and writes the corresponding servers onto outbuf. If we
3048 * run out of entries, flushes the zlib state and sets the spool source to
3049 * NONE. Returns 0 on success, negative on failure.
3051 static int
3052 connection_dirserv_add_servers_to_outbuf(dir_connection_t *conn)
3054 #ifdef TRACK_SERVED_TIME
3055 time_t now = time(NULL);
3056 #endif
3057 int by_fp = (conn->dir_spool_src == DIR_SPOOL_SERVER_BY_FP ||
3058 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP);
3059 int extra = (conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP ||
3060 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_DIGEST);
3061 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
3063 while (smartlist_len(conn->fingerprint_stack) &&
3064 buf_datalen(conn->_base.outbuf) < DIRSERV_BUFFER_MIN) {
3065 const char *body;
3066 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3067 signed_descriptor_t *sd = NULL;
3068 if (by_fp) {
3069 sd = get_signed_descriptor_by_fp(fp, extra, publish_cutoff);
3070 } else {
3071 sd = extra ? extrainfo_get_by_descriptor_digest(fp)
3072 : router_get_by_descriptor_digest(fp);
3074 tor_free(fp);
3075 if (!sd)
3076 continue;
3077 if (!connection_dir_is_encrypted(conn) && !sd->send_unencrypted) {
3078 /* we did this check once before (so we could have an accurate size
3079 * estimate and maybe send a 404 if somebody asked for only bridges on a
3080 * connection), but we need to do it again in case a previously
3081 * unknown bridge descriptor has shown up between then and now. */
3082 continue;
3084 #ifdef TRACK_SERVED_TIME
3085 sd->last_served_at = now;
3086 #endif
3087 body = signed_descriptor_get_body(sd);
3088 if (conn->zlib_state) {
3089 int last = ! smartlist_len(conn->fingerprint_stack);
3090 connection_write_to_buf_zlib(body, sd->signed_descriptor_len, conn,
3091 last);
3092 if (last) {
3093 tor_zlib_free(conn->zlib_state);
3094 conn->zlib_state = NULL;
3096 } else {
3097 connection_write_to_buf(body,
3098 sd->signed_descriptor_len,
3099 TO_CONN(conn));
3103 if (!smartlist_len(conn->fingerprint_stack)) {
3104 /* We just wrote the last one; finish up. */
3105 conn->dir_spool_src = DIR_SPOOL_NONE;
3106 smartlist_free(conn->fingerprint_stack);
3107 conn->fingerprint_stack = NULL;
3109 return 0;
3112 /** Spooling helper: Called when we're sending a directory or networkstatus,
3113 * and the outbuf has become too empty. Pulls some bytes from
3114 * <b>conn</b>-\>cached_dir-\>dir_z, uncompresses them if appropriate, and
3115 * puts them on the outbuf. If we run out of entries, flushes the zlib state
3116 * and sets the spool source to NONE. Returns 0 on success, negative on
3117 * failure. */
3118 static int
3119 connection_dirserv_add_dir_bytes_to_outbuf(dir_connection_t *conn)
3121 ssize_t bytes;
3122 int64_t remaining;
3124 bytes = DIRSERV_BUFFER_MIN - buf_datalen(conn->_base.outbuf);
3125 tor_assert(bytes > 0);
3126 tor_assert(conn->cached_dir);
3127 if (bytes < 8192)
3128 bytes = 8192;
3129 remaining = conn->cached_dir->dir_z_len - conn->cached_dir_offset;
3130 if (bytes > remaining)
3131 bytes = (ssize_t) remaining;
3133 if (conn->zlib_state) {
3134 connection_write_to_buf_zlib(
3135 conn->cached_dir->dir_z + conn->cached_dir_offset,
3136 bytes, conn, bytes == remaining);
3137 } else {
3138 connection_write_to_buf(conn->cached_dir->dir_z + conn->cached_dir_offset,
3139 bytes, TO_CONN(conn));
3141 conn->cached_dir_offset += bytes;
3142 if (conn->cached_dir_offset == (int)conn->cached_dir->dir_z_len) {
3143 /* We just wrote the last one; finish up. */
3144 connection_dirserv_finish_spooling(conn);
3145 cached_dir_decref(conn->cached_dir);
3146 conn->cached_dir = NULL;
3148 return 0;
3151 /** Spooling helper: Called when we're spooling networkstatus objects on
3152 * <b>conn</b>, and the outbuf has become too empty. If the current
3153 * networkstatus object (in <b>conn</b>-\>cached_dir) has more data, pull data
3154 * from there. Otherwise, pop the next fingerprint from fingerprint_stack,
3155 * and start spooling the next networkstatus. (A digest of all 0 bytes is
3156 * treated as a request for the current consensus.) If we run out of entries,
3157 * flushes the zlib state and sets the spool source to NONE. Returns 0 on
3158 * success, negative on failure. */
3159 static int
3160 connection_dirserv_add_networkstatus_bytes_to_outbuf(dir_connection_t *conn)
3163 while (buf_datalen(conn->_base.outbuf) < DIRSERV_BUFFER_MIN) {
3164 if (conn->cached_dir) {
3165 int uncompressing = (conn->zlib_state != NULL);
3166 int r = connection_dirserv_add_dir_bytes_to_outbuf(conn);
3167 if (conn->dir_spool_src == DIR_SPOOL_NONE) {
3168 /* add_dir_bytes thinks we're done with the cached_dir. But we
3169 * may have more cached_dirs! */
3170 conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
3171 /* This bit is tricky. If we were uncompressing the last
3172 * networkstatus, we may need to make a new zlib object to
3173 * uncompress the next one. */
3174 if (uncompressing && ! conn->zlib_state &&
3175 conn->fingerprint_stack &&
3176 smartlist_len(conn->fingerprint_stack)) {
3177 conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
3180 if (r) return r;
3181 } else if (conn->fingerprint_stack &&
3182 smartlist_len(conn->fingerprint_stack)) {
3183 /* Add another networkstatus; start serving it. */
3184 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3185 cached_dir_t *d = lookup_cached_dir_by_fp(fp);
3186 tor_free(fp);
3187 if (d) {
3188 ++d->refcnt;
3189 conn->cached_dir = d;
3190 conn->cached_dir_offset = 0;
3192 } else {
3193 connection_dirserv_finish_spooling(conn);
3194 if (conn->fingerprint_stack)
3195 smartlist_free(conn->fingerprint_stack);
3196 conn->fingerprint_stack = NULL;
3197 return 0;
3200 return 0;
3203 /** Called whenever we have flushed some directory data in state
3204 * SERVER_WRITING. */
3206 connection_dirserv_flushed_some(dir_connection_t *conn)
3208 tor_assert(conn->_base.state == DIR_CONN_STATE_SERVER_WRITING);
3210 if (buf_datalen(conn->_base.outbuf) >= DIRSERV_BUFFER_MIN)
3211 return 0;
3213 switch (conn->dir_spool_src) {
3214 case DIR_SPOOL_EXTRA_BY_DIGEST:
3215 case DIR_SPOOL_EXTRA_BY_FP:
3216 case DIR_SPOOL_SERVER_BY_DIGEST:
3217 case DIR_SPOOL_SERVER_BY_FP:
3218 return connection_dirserv_add_servers_to_outbuf(conn);
3219 case DIR_SPOOL_CACHED_DIR:
3220 return connection_dirserv_add_dir_bytes_to_outbuf(conn);
3221 case DIR_SPOOL_NETWORKSTATUS:
3222 return connection_dirserv_add_networkstatus_bytes_to_outbuf(conn);
3223 case DIR_SPOOL_NONE:
3224 default:
3225 return 0;
3229 /** Release all storage used by the directory server. */
3230 void
3231 dirserv_free_all(void)
3233 dirserv_free_fingerprint_list();
3235 cached_dir_decref(the_directory);
3236 clear_cached_dir(&the_runningrouters);
3237 cached_dir_decref(the_v2_networkstatus);
3238 cached_dir_decref(cached_directory);
3239 clear_cached_dir(&cached_runningrouters);
3240 if (cached_v2_networkstatus) {
3241 digestmap_free(cached_v2_networkstatus, _free_cached_dir);
3242 cached_v2_networkstatus = NULL;
3244 cached_dir_decref(cached_v3_networkstatus);