Maintain separate server and client identity keys when appropriate.
[tor.git] / src / or / dirserv.c
blob46775805cd3f182997395709b3070bfc5f9633a5
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2011, 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, source);
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, or NULL if there is no such
656 * message. Use <b>source</b> to produce better log messages.
658 * Return the status of the operation
660 * This function is only called when fresh descriptors are posted, not when
661 * we re-load the cache.
663 was_router_added_t
664 dirserv_add_descriptor(routerinfo_t *ri, const char **msg, const char *source)
666 was_router_added_t r;
667 routerinfo_t *ri_old;
668 char *desc, *nickname;
669 size_t desclen = 0;
670 *msg = NULL;
672 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
673 * network and it'll clog everything up. */
674 if (ri->cache_info.signed_descriptor_len > MAX_DESCRIPTOR_UPLOAD_SIZE) {
675 log_notice(LD_DIR, "Somebody attempted to publish a router descriptor '%s'"
676 " (source: %s) with size %d. Either this is an attack, or the "
677 "MAX_DESCRIPTOR_UPLOAD_SIZE (%d) constant is too low.",
678 ri->nickname, source, (int)ri->cache_info.signed_descriptor_len,
679 MAX_DESCRIPTOR_UPLOAD_SIZE);
680 *msg = "Router descriptor was too large";
681 control_event_or_authdir_new_descriptor("REJECTED",
682 ri->cache_info.signed_descriptor_body,
683 ri->cache_info.signed_descriptor_len, *msg);
684 routerinfo_free(ri);
685 return ROUTER_AUTHDIR_REJECTS;
688 /* Check whether this descriptor is semantically identical to the last one
689 * from this server. (We do this here and not in router_add_to_routerlist
690 * because we want to be able to accept the newest router descriptor that
691 * another authority has, so we all converge on the same one.) */
692 ri_old = router_get_by_digest(ri->cache_info.identity_digest);
693 if (ri_old && ri_old->cache_info.published_on < ri->cache_info.published_on
694 && router_differences_are_cosmetic(ri_old, ri)
695 && !router_is_me(ri)) {
696 log_info(LD_DIRSERV,
697 "Not replacing descriptor from '%s' (source: %s); "
698 "differences are cosmetic.",
699 ri->nickname, source);
700 *msg = "Not replacing router descriptor; no information has changed since "
701 "the last one with this identity.";
702 control_event_or_authdir_new_descriptor("DROPPED",
703 ri->cache_info.signed_descriptor_body,
704 ri->cache_info.signed_descriptor_len, *msg);
705 routerinfo_free(ri);
706 return ROUTER_WAS_NOT_NEW;
709 /* Make a copy of desc, since router_add_to_routerlist might free
710 * ri and its associated signed_descriptor_t. */
711 desclen = ri->cache_info.signed_descriptor_len;
712 desc = tor_strndup(ri->cache_info.signed_descriptor_body, desclen);
713 nickname = tor_strdup(ri->nickname);
715 r = router_add_to_routerlist(ri, msg, 0, 0);
716 if (!WRA_WAS_ADDED(r)) {
717 /* unless the routerinfo was fine, just out-of-date */
718 if (WRA_WAS_REJECTED(r))
719 control_event_or_authdir_new_descriptor("REJECTED", desc, desclen, *msg);
720 log_info(LD_DIRSERV,
721 "Did not add descriptor from '%s' (source: %s): %s.",
722 nickname, source, *msg ? *msg : "(no message)");
723 } else {
724 smartlist_t *changed;
725 control_event_or_authdir_new_descriptor("ACCEPTED", desc, desclen, *msg);
727 changed = smartlist_create();
728 smartlist_add(changed, ri);
729 control_event_descriptors_changed(changed);
730 smartlist_free(changed);
731 if (!*msg) {
732 *msg = ri->is_valid ? "Descriptor for valid server accepted" :
733 "Descriptor for invalid server accepted";
735 log_info(LD_DIRSERV,
736 "Added descriptor from '%s' (source: %s): %s.",
737 nickname, source, *msg);
739 tor_free(desc);
740 tor_free(nickname);
741 return r;
744 /** As dirserv_add_descriptor, but for an extrainfo_t <b>ei</b>. */
745 static was_router_added_t
746 dirserv_add_extrainfo(extrainfo_t *ei, const char **msg)
748 routerinfo_t *ri;
749 int r;
750 tor_assert(msg);
751 *msg = NULL;
753 ri = router_get_by_digest(ei->cache_info.identity_digest);
754 if (!ri) {
755 *msg = "No corresponding router descriptor for extra-info descriptor";
756 extrainfo_free(ei);
757 return ROUTER_BAD_EI;
760 /* If it's too big, refuse it now. Otherwise we'll cache it all over the
761 * network and it'll clog everything up. */
762 if (ei->cache_info.signed_descriptor_len > MAX_EXTRAINFO_UPLOAD_SIZE) {
763 log_notice(LD_DIR, "Somebody attempted to publish an extrainfo "
764 "with size %d. Either this is an attack, or the "
765 "MAX_EXTRAINFO_UPLOAD_SIZE (%d) constant is too low.",
766 (int)ei->cache_info.signed_descriptor_len,
767 MAX_EXTRAINFO_UPLOAD_SIZE);
768 *msg = "Extrainfo document was too large";
769 extrainfo_free(ei);
770 return ROUTER_BAD_EI;
773 if ((r = routerinfo_incompatible_with_extrainfo(ri, ei, NULL, msg))) {
774 extrainfo_free(ei);
775 return r < 0 ? ROUTER_WAS_NOT_NEW : ROUTER_BAD_EI;
777 router_add_extrainfo_to_routerlist(ei, msg, 0, 0);
778 return ROUTER_ADDED_SUCCESSFULLY;
781 /** Remove all descriptors whose nicknames or fingerprints no longer
782 * are allowed by our fingerprint list. (Descriptors that used to be
783 * good can become bad when we reload the fingerprint list.)
785 static void
786 directory_remove_invalid(void)
788 int i;
789 int changed = 0;
790 routerlist_t *rl = router_get_routerlist();
792 routerlist_assert_ok(rl);
794 for (i = 0; i < smartlist_len(rl->routers); ++i) {
795 const char *msg;
796 routerinfo_t *ent = smartlist_get(rl->routers, i);
797 uint32_t r = dirserv_router_get_status(ent, &msg);
798 if (r & FP_REJECT) {
799 log_info(LD_DIRSERV, "Router '%s' is now rejected: %s",
800 ent->nickname, msg?msg:"");
801 routerlist_remove(rl, ent, 0, time(NULL));
802 i--;
803 changed = 1;
804 continue;
806 if (bool_neq((r & FP_NAMED), ent->is_named)) {
807 log_info(LD_DIRSERV,
808 "Router '%s' is now %snamed.", ent->nickname,
809 (r&FP_NAMED)?"":"un");
810 ent->is_named = (r&FP_NAMED)?1:0;
811 changed = 1;
813 if (bool_neq((r & FP_INVALID), !ent->is_valid)) {
814 log_info(LD_DIRSERV, "Router '%s' is now %svalid.", ent->nickname,
815 (r&FP_INVALID) ? "in" : "");
816 ent->is_valid = (r&FP_INVALID)?0:1;
817 changed = 1;
819 if (bool_neq((r & FP_BADDIR), ent->is_bad_directory)) {
820 log_info(LD_DIRSERV, "Router '%s' is now a %s directory", ent->nickname,
821 (r & FP_BADDIR) ? "bad" : "good");
822 ent->is_bad_directory = (r&FP_BADDIR) ? 1: 0;
823 changed = 1;
825 if (bool_neq((r & FP_BADEXIT), ent->is_bad_exit)) {
826 log_info(LD_DIRSERV, "Router '%s' is now a %s exit", ent->nickname,
827 (r & FP_BADEXIT) ? "bad" : "good");
828 ent->is_bad_exit = (r&FP_BADEXIT) ? 1: 0;
829 changed = 1;
832 if (changed)
833 directory_set_dirty();
835 routerlist_assert_ok(rl);
838 /** Write a list of unregistered descriptors into a newly allocated
839 * string and return it. Used by dirserv operators to keep track of
840 * fast nodes that haven't registered.
843 getinfo_helper_dirserv_unregistered(control_connection_t *control_conn,
844 const char *question, char **answer_out)
846 smartlist_t *answerlist;
847 char buf[1024];
848 char *answer;
849 int min_bw = atoi(question);
850 routerlist_t *rl = router_get_routerlist();
852 (void) control_conn;
854 if (strcmpstart(question, "unregistered-servers-"))
855 return 0;
856 question += strlen("unregistered-servers-");
858 answerlist = smartlist_create();
859 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ent, {
860 uint32_t r = dirserv_router_get_status(ent, NULL);
861 if (router_get_advertised_bandwidth(ent) >= (size_t)min_bw &&
862 !(r & FP_NAMED)) {
863 /* then log this one */
864 tor_snprintf(buf, sizeof(buf),
865 "%s: BW %d on '%s'.",
866 ent->nickname, router_get_advertised_bandwidth(ent),
867 ent->platform ? ent->platform : "");
868 smartlist_add(answerlist, tor_strdup(buf));
871 answer = smartlist_join_strings(answerlist, "\r\n", 0, NULL);
872 SMARTLIST_FOREACH(answerlist, char *, cp, tor_free(cp));
873 smartlist_free(answerlist);
874 *answer_out = answer;
875 return 0;
878 /** Mark the directory as <b>dirty</b> -- when we're next asked for a
879 * directory, we will rebuild it instead of reusing the most recently
880 * generated one.
882 void
883 directory_set_dirty(void)
885 time_t now = time(NULL);
886 int set_v1_dirty=0;
888 /* Regenerate stubs only every 8 hours.
889 * XXXX It would be nice to generate less often, but these are just
890 * stubs: it doesn't matter. */
891 #define STUB_REGENERATE_INTERVAL (8*60*60)
892 if (!the_directory || !the_runningrouters.dir)
893 set_v1_dirty = 1;
894 else if (the_directory->published < now - STUB_REGENERATE_INTERVAL ||
895 the_runningrouters.published < now - STUB_REGENERATE_INTERVAL)
896 set_v1_dirty = 1;
898 if (set_v1_dirty) {
899 if (!the_directory_is_dirty)
900 the_directory_is_dirty = now;
901 if (!runningrouters_is_dirty)
902 runningrouters_is_dirty = now;
904 if (!the_v2_networkstatus_is_dirty)
905 the_v2_networkstatus_is_dirty = now;
909 * Allocate and return a description of the status of the server <b>desc</b>,
910 * for use in a v1-style router-status line. The server is listed
911 * as running iff <b>is_live</b> is true.
913 static char *
914 list_single_server_status(routerinfo_t *desc, int is_live)
916 char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
917 char *cp;
919 tor_assert(desc);
921 cp = buf;
922 if (!is_live) {
923 *cp++ = '!';
925 if (desc->is_valid) {
926 strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
927 cp += strlen(cp);
928 *cp++ = '=';
930 *cp++ = '$';
931 base16_encode(cp, HEX_DIGEST_LEN+1, desc->cache_info.identity_digest,
932 DIGEST_LEN);
933 return tor_strdup(buf);
936 /** Each server needs to have passed a reachability test no more
937 * than this number of seconds ago, or he is listed as down in
938 * the directory. */
939 #define REACHABLE_TIMEOUT (45*60)
941 /** Treat a router as alive if
942 * - It's me, and I'm not hibernating.
943 * or - We've found it reachable recently. */
944 void
945 dirserv_set_router_is_running(routerinfo_t *router, time_t now)
947 int answer;
949 if (router_is_me(router) && !we_are_hibernating())
950 answer = 1;
951 else
952 answer = get_options()->AssumeReachable ||
953 now < router->last_reachable + REACHABLE_TIMEOUT;
955 if (!answer) {
956 /* not considered reachable. tell rephist. */
957 rep_hist_note_router_unreachable(router->cache_info.identity_digest, now);
960 router->is_running = answer;
963 /** Based on the routerinfo_ts in <b>routers</b>, allocate the
964 * contents of a v1-style router-status line, and store it in
965 * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
967 * If for_controller is true, include the routers with very old descriptors.
968 * If for_controller is &gt;1, use the verbose nickname format.
971 list_server_status_v1(smartlist_t *routers, char **router_status_out,
972 int for_controller)
974 /* List of entries in a router-status style: An optional !, then an optional
975 * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
976 smartlist_t *rs_entries;
977 time_t now = time(NULL);
978 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
979 or_options_t *options = get_options();
980 /* We include v2 dir auths here too, because they need to answer
981 * controllers. Eventually we'll deprecate this whole function;
982 * see also networkstatus_getinfo_by_purpose(). */
983 int authdir = authdir_mode_publishes_statuses(options);
984 tor_assert(router_status_out);
986 rs_entries = smartlist_create();
988 SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
990 if (authdir) {
991 /* Update router status in routerinfo_t. */
992 dirserv_set_router_is_running(ri, now);
994 if (for_controller == 1 || ri->cache_info.published_on >= cutoff)
995 smartlist_add(rs_entries, list_single_server_status(ri, ri->is_running));
996 else if (for_controller > 2) {
997 char name_buf[MAX_VERBOSE_NICKNAME_LEN+2];
998 char *cp = name_buf;
999 if (!ri->is_running)
1000 *cp++ = '!';
1001 router_get_verbose_nickname(cp, ri);
1002 smartlist_add(rs_entries, tor_strdup(name_buf));
1006 *router_status_out = smartlist_join_strings(rs_entries, " ", 0, NULL);
1008 SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
1009 smartlist_free(rs_entries);
1011 return 0;
1014 /** Given a (possibly empty) list of config_line_t, each line of which contains
1015 * a list of comma-separated version numbers surrounded by optional space,
1016 * allocate and return a new string containing the version numbers, in order,
1017 * separated by commas. Used to generate Recommended(Client|Server)?Versions
1019 static char *
1020 format_versions_list(config_line_t *ln)
1022 smartlist_t *versions;
1023 char *result;
1024 versions = smartlist_create();
1025 for ( ; ln; ln = ln->next) {
1026 smartlist_split_string(versions, ln->value, ",",
1027 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1029 sort_version_list(versions, 1);
1030 result = smartlist_join_strings(versions,",",0,NULL);
1031 SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
1032 smartlist_free(versions);
1033 return result;
1036 /** Return 1 if <b>ri</b>'s descriptor is "active" -- running, valid,
1037 * not hibernating, and not too old. Else return 0.
1039 static int
1040 router_is_active(routerinfo_t *ri, time_t now)
1042 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
1043 if (ri->cache_info.published_on < cutoff)
1044 return 0;
1045 if (!ri->is_running || !ri->is_valid || ri->is_hibernating)
1046 return 0;
1047 return 1;
1050 /** Generate a new v1 directory and write it into a newly allocated string.
1051 * Point *<b>dir_out</b> to the allocated string. Sign the
1052 * directory with <b>private_key</b>. Return 0 on success, -1 on
1053 * failure. If <b>complete</b> is set, give us all the descriptors;
1054 * otherwise leave out non-running and non-valid ones.
1057 dirserv_dump_directory_to_string(char **dir_out,
1058 crypto_pk_env_t *private_key)
1060 char *cp;
1061 char *identity_pkey; /* Identity key, DER64-encoded. */
1062 char *recommended_versions;
1063 char digest[DIGEST_LEN];
1064 char published[ISO_TIME_LEN+1];
1065 char *buf = NULL;
1066 size_t buf_len;
1067 size_t identity_pkey_len;
1068 time_t now = time(NULL);
1070 tor_assert(dir_out);
1071 *dir_out = NULL;
1073 if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
1074 &identity_pkey_len)<0) {
1075 log_warn(LD_BUG,"write identity_pkey to string failed!");
1076 return -1;
1079 recommended_versions =
1080 format_versions_list(get_options()->RecommendedVersions);
1082 format_iso_time(published, now);
1084 buf_len = 2048+strlen(recommended_versions);
1086 buf = tor_malloc(buf_len);
1087 /* We'll be comparing against buf_len throughout the rest of the
1088 function, though strictly speaking we shouldn't be able to exceed
1089 it. This is C, after all, so we may as well check for buffer
1090 overruns.*/
1092 tor_snprintf(buf, buf_len,
1093 "signed-directory\n"
1094 "published %s\n"
1095 "recommended-software %s\n"
1096 "router-status %s\n"
1097 "dir-signing-key\n%s\n",
1098 published, recommended_versions, "",
1099 identity_pkey);
1101 tor_free(recommended_versions);
1102 tor_free(identity_pkey);
1104 cp = buf + strlen(buf);
1105 *cp = '\0';
1107 /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
1108 signature. */
1109 if (strlcat(buf, "directory-signature ", buf_len) >= buf_len)
1110 goto truncated;
1111 if (strlcat(buf, get_options()->Nickname, buf_len) >= buf_len)
1112 goto truncated;
1113 if (strlcat(buf, "\n", buf_len) >= buf_len)
1114 goto truncated;
1116 if (router_get_dir_hash(buf,digest)) {
1117 log_warn(LD_BUG,"couldn't compute digest");
1118 tor_free(buf);
1119 return -1;
1121 note_crypto_pk_op(SIGN_DIR);
1122 if (router_append_dirobj_signature(buf,buf_len,digest,private_key)<0) {
1123 tor_free(buf);
1124 return -1;
1127 *dir_out = buf;
1128 return 0;
1129 truncated:
1130 log_warn(LD_BUG,"tried to exceed string length.");
1131 tor_free(buf);
1132 return -1;
1135 /********************************************************************/
1137 /* A set of functions to answer questions about how we'd like to behave
1138 * as a directory mirror/client. */
1140 /** Return 1 if we fetch our directory material directly from the
1141 * authorities, rather than from a mirror. */
1143 directory_fetches_from_authorities(or_options_t *options)
1145 routerinfo_t *me;
1146 uint32_t addr;
1147 if (options->FetchDirInfoEarly)
1148 return 1;
1149 if (options->BridgeRelay == 1)
1150 return 0;
1151 if (server_mode(options) && router_pick_published_address(options, &addr)<0)
1152 return 1; /* we don't know our IP address; ask an authority. */
1153 if (options->DirPort == 0)
1154 return 0;
1155 if (!server_mode(options) || !advertised_server_mode())
1156 return 0;
1157 me = router_get_my_routerinfo();
1158 if (!me || !me->dir_port)
1159 return 0; /* if dirport not advertised, return 0 too */
1160 return 1;
1163 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1164 * on the "mirror" schedule rather than the "client" schedule.
1167 directory_fetches_dir_info_early(or_options_t *options)
1169 return directory_fetches_from_authorities(options);
1172 /** Return 1 if we should fetch new networkstatuses, descriptors, etc
1173 * on a very passive schedule -- waiting long enough for ordinary clients
1174 * to probably have the info we want. These would include bridge users,
1175 * and maybe others in the future e.g. if a Tor client uses another Tor
1176 * client as a directory guard.
1179 directory_fetches_dir_info_later(or_options_t *options)
1181 return options->UseBridges != 0;
1184 /** Return 1 if we want to cache v2 dir info (each status file).
1187 directory_caches_v2_dir_info(or_options_t *options)
1189 return options->DirPort != 0;
1192 /** Return 1 if we want to keep descriptors, networkstatuses, etc around
1193 * and we're willing to serve them to others. Else return 0.
1196 directory_caches_dir_info(or_options_t *options)
1198 return options->BridgeRelay != 0 || options->DirPort != 0;
1201 /** Return 1 if we want to allow remote people to ask us directory
1202 * requests via the "begin_dir" interface, which doesn't require
1203 * having any separate port open. */
1205 directory_permits_begindir_requests(or_options_t *options)
1207 return options->BridgeRelay != 0 || options->DirPort != 0;
1210 /** Return 1 if we want to allow controllers to ask us directory
1211 * requests via the controller interface, which doesn't require
1212 * having any separate port open. */
1214 directory_permits_controller_requests(or_options_t *options)
1216 return options->DirPort != 0;
1219 /** Return 1 if we have no need to fetch new descriptors. This generally
1220 * happens when we're not a dir cache and we haven't built any circuits
1221 * lately.
1224 directory_too_idle_to_fetch_descriptors(or_options_t *options, time_t now)
1226 return !directory_caches_dir_info(options) &&
1227 !options->FetchUselessDescriptors &&
1228 rep_hist_circbuilding_dormant(now);
1231 /********************************************************************/
1233 /* Used only by non-v1-auth dirservers: The v1 directory and
1234 * runningrouters we'll serve when requested. */
1236 /** The v1 directory we'll serve (as a cache or as an authority) if
1237 * requested. */
1238 static cached_dir_t *cached_directory = NULL;
1239 /** The v1 runningrouters document we'll serve (as a cache or as an authority)
1240 * if requested. */
1241 static cached_dir_t cached_runningrouters = { NULL, NULL, 0, 0, 0, -1 };
1243 /** Used for other dirservers' v2 network statuses. Map from hexdigest to
1244 * cached_dir_t. */
1245 static digestmap_t *cached_v2_networkstatus = NULL;
1247 /** The v3 consensus network status that we're currently serving. */
1248 static cached_dir_t *cached_v3_networkstatus = NULL;
1250 /** Possibly replace the contents of <b>d</b> with the value of
1251 * <b>directory</b> published on <b>when</b>, unless <b>when</b> is older than
1252 * the last value, or too far in the future.
1254 * Does not copy <b>directory</b>; frees it if it isn't used.
1256 static void
1257 set_cached_dir(cached_dir_t *d, char *directory, time_t when)
1259 time_t now = time(NULL);
1260 if (when<=d->published) {
1261 log_info(LD_DIRSERV, "Ignoring old directory; not caching.");
1262 tor_free(directory);
1263 } else if (when>=now+ROUTER_MAX_AGE_TO_PUBLISH) {
1264 log_info(LD_DIRSERV, "Ignoring future directory; not caching.");
1265 tor_free(directory);
1266 } else {
1267 /* if (when>d->published && when<now+ROUTER_MAX_AGE) */
1268 log_debug(LD_DIRSERV, "Caching directory.");
1269 tor_free(d->dir);
1270 d->dir = directory;
1271 d->dir_len = strlen(directory);
1272 tor_free(d->dir_z);
1273 if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
1274 ZLIB_METHOD)) {
1275 log_warn(LD_BUG,"Error compressing cached directory");
1277 d->published = when;
1281 /** Decrement the reference count on <b>d</b>, and free it if it no longer has
1282 * any references. */
1283 void
1284 cached_dir_decref(cached_dir_t *d)
1286 if (!d || --d->refcnt > 0)
1287 return;
1288 clear_cached_dir(d);
1289 tor_free(d);
1292 /** Allocate and return a new cached_dir_t containing the string <b>s</b>,
1293 * published at <b>published</b>. */
1294 cached_dir_t *
1295 new_cached_dir(char *s, time_t published)
1297 cached_dir_t *d = tor_malloc_zero(sizeof(cached_dir_t));
1298 d->refcnt = 1;
1299 d->dir = s;
1300 d->dir_len = strlen(s);
1301 d->published = published;
1302 if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
1303 ZLIB_METHOD)) {
1304 log_warn(LD_BUG, "Error compressing directory");
1306 return d;
1309 /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
1310 static void
1311 clear_cached_dir(cached_dir_t *d)
1313 tor_free(d->dir);
1314 tor_free(d->dir_z);
1315 memset(d, 0, sizeof(cached_dir_t));
1318 /** Free all storage held by the cached_dir_t in <b>d</b>. */
1319 static void
1320 _free_cached_dir(void *_d)
1322 cached_dir_t *d = (cached_dir_t *)_d;
1323 cached_dir_decref(d);
1326 /** If we have no cached v1 directory, or it is older than <b>published</b>,
1327 * then replace it with <b>directory</b>, published at <b>published</b>.
1329 * If <b>published</b> is too old, do nothing.
1331 * If <b>is_running_routers</b>, this is really a v1 running_routers
1332 * document rather than a v1 directory.
1334 void
1335 dirserv_set_cached_directory(const char *directory, time_t published,
1336 int is_running_routers)
1338 time_t now = time(NULL);
1340 if (is_running_routers) {
1341 if (published >= now - MAX_V1_RR_AGE)
1342 set_cached_dir(&cached_runningrouters, tor_strdup(directory), published);
1343 } else {
1344 if (published >= now - MAX_V1_DIRECTORY_AGE) {
1345 cached_dir_decref(cached_directory);
1346 cached_directory = new_cached_dir(tor_strdup(directory), published);
1351 /** If <b>networkstatus</b> is non-NULL, we've just received a v2
1352 * network-status for an authoritative directory with identity digest
1353 * <b>identity</b> published at <b>published</b> -- store it so we can
1354 * serve it to others.
1356 * If <b>networkstatus</b> is NULL, remove the entry with the given
1357 * identity fingerprint from the v2 cache.
1359 void
1360 dirserv_set_cached_networkstatus_v2(const char *networkstatus,
1361 const char *identity,
1362 time_t published)
1364 cached_dir_t *d, *old_d;
1365 smartlist_t *trusted_dirs;
1366 if (!cached_v2_networkstatus)
1367 cached_v2_networkstatus = digestmap_new();
1369 old_d = digestmap_get(cached_v2_networkstatus, identity);
1370 if (!old_d && !networkstatus)
1371 return;
1373 if (networkstatus) {
1374 if (!old_d || published > old_d->published) {
1375 d = new_cached_dir(tor_strdup(networkstatus), published);
1376 digestmap_set(cached_v2_networkstatus, identity, d);
1377 if (old_d)
1378 cached_dir_decref(old_d);
1380 } else {
1381 if (old_d) {
1382 digestmap_remove(cached_v2_networkstatus, identity);
1383 cached_dir_decref(old_d);
1387 /* Now purge old entries. */
1388 trusted_dirs = router_get_trusted_dir_servers();
1389 if (digestmap_size(cached_v2_networkstatus) >
1390 smartlist_len(trusted_dirs) + MAX_UNTRUSTED_NETWORKSTATUSES) {
1391 /* We need to remove the oldest untrusted networkstatus. */
1392 const char *oldest = NULL;
1393 time_t oldest_published = TIME_MAX;
1394 digestmap_iter_t *iter;
1396 for (iter = digestmap_iter_init(cached_v2_networkstatus);
1397 !digestmap_iter_done(iter);
1398 iter = digestmap_iter_next(cached_v2_networkstatus, iter)) {
1399 const char *ident;
1400 void *val;
1401 digestmap_iter_get(iter, &ident, &val);
1402 d = val;
1403 if (d->published < oldest_published &&
1404 !router_digest_is_trusted_dir(ident)) {
1405 oldest = ident;
1406 oldest_published = d->published;
1409 tor_assert(oldest);
1410 d = digestmap_remove(cached_v2_networkstatus, oldest);
1411 if (d)
1412 cached_dir_decref(d);
1416 /** Replace the v3 consensus networkstatus that we're serving with
1417 * <b>networkstatus</b>, published at <b>published</b>. No validation is
1418 * performed. */
1419 void
1420 dirserv_set_cached_networkstatus_v3(const char *networkstatus,
1421 time_t published)
1423 if (cached_v3_networkstatus)
1424 cached_dir_decref(cached_v3_networkstatus);
1425 cached_v3_networkstatus = new_cached_dir(
1426 tor_strdup(networkstatus), published);
1429 /** Remove any v2 networkstatus from the directory cache that was published
1430 * before <b>cutoff</b>. */
1431 void
1432 dirserv_clear_old_networkstatuses(time_t cutoff)
1434 if (!cached_v2_networkstatus)
1435 return;
1437 DIGESTMAP_FOREACH_MODIFY(cached_v2_networkstatus, id, cached_dir_t *, dir) {
1438 if (dir->published < cutoff) {
1439 char *fname;
1440 fname = networkstatus_get_cache_filename(id);
1441 if (file_status(fname) == FN_FILE) {
1442 log_info(LD_DIR, "Removing too-old untrusted networkstatus in %s",
1443 fname);
1444 unlink(fname);
1446 tor_free(fname);
1447 cached_dir_decref(dir);
1448 MAP_DEL_CURRENT(id);
1450 } DIGESTMAP_FOREACH_END
1453 /** Remove any v1 info from the directory cache that was published
1454 * too long ago. */
1455 void
1456 dirserv_clear_old_v1_info(time_t now)
1458 if (cached_directory &&
1459 cached_directory->published < (now - MAX_V1_DIRECTORY_AGE)) {
1460 cached_dir_decref(cached_directory);
1461 cached_directory = NULL;
1463 if (cached_runningrouters.published < (now - MAX_V1_RR_AGE)) {
1464 clear_cached_dir(&cached_runningrouters);
1468 /** Helper: If we're an authority for the right directory version (v1 or v2)
1469 * (based on <b>auth_type</b>), try to regenerate
1470 * auth_src as appropriate and return it, falling back to cache_src on
1471 * failure. If we're a cache, simply return cache_src.
1473 static cached_dir_t *
1474 dirserv_pick_cached_dir_obj(cached_dir_t *cache_src,
1475 cached_dir_t *auth_src,
1476 time_t dirty, cached_dir_t *(*regenerate)(void),
1477 const char *name,
1478 authority_type_t auth_type)
1480 or_options_t *options = get_options();
1481 int authority = (auth_type == V1_AUTHORITY && authdir_mode_v1(options)) ||
1482 (auth_type == V2_AUTHORITY && authdir_mode_v2(options));
1484 if (!authority || authdir_mode_bridge(options)) {
1485 return cache_src;
1486 } else {
1487 /* We're authoritative. */
1488 if (regenerate != NULL) {
1489 if (dirty && dirty + DIR_REGEN_SLACK_TIME < time(NULL)) {
1490 if (!(auth_src = regenerate())) {
1491 log_err(LD_BUG, "Couldn't generate %s?", name);
1492 exit(1);
1494 } else {
1495 log_info(LD_DIRSERV, "The %s is still clean; reusing.", name);
1498 return auth_src ? auth_src : cache_src;
1502 /** Return the most recently generated encoded signed v1 directory,
1503 * generating a new one as necessary. If not a v1 authoritative directory
1504 * may return NULL if no directory is yet cached. */
1505 cached_dir_t *
1506 dirserv_get_directory(void)
1508 return dirserv_pick_cached_dir_obj(cached_directory, the_directory,
1509 the_directory_is_dirty,
1510 dirserv_regenerate_directory,
1511 "v1 server directory", V1_AUTHORITY);
1514 /** Only called by v1 auth dirservers.
1515 * Generate a fresh v1 directory; set the_directory and return a pointer
1516 * to the new value.
1518 static cached_dir_t *
1519 dirserv_regenerate_directory(void)
1521 char *new_directory=NULL;
1523 if (dirserv_dump_directory_to_string(&new_directory,
1524 get_server_identity_key())) {
1525 log_warn(LD_BUG, "Error creating directory.");
1526 tor_free(new_directory);
1527 return NULL;
1529 cached_dir_decref(the_directory);
1530 the_directory = new_cached_dir(new_directory, time(NULL));
1531 log_info(LD_DIRSERV,"New directory (size %d) has been built.",
1532 (int)the_directory->dir_len);
1533 log_debug(LD_DIRSERV,"New directory (size %d):\n%s",
1534 (int)the_directory->dir_len, the_directory->dir);
1536 the_directory_is_dirty = 0;
1538 /* Save the directory to disk so we re-load it quickly on startup.
1540 dirserv_set_cached_directory(the_directory->dir, time(NULL), 0);
1542 return the_directory;
1545 /** Only called by v1 auth dirservers.
1546 * Replace the current running-routers list with a newly generated one. */
1547 static cached_dir_t *
1548 generate_runningrouters(void)
1550 char *s=NULL;
1551 char digest[DIGEST_LEN];
1552 char published[ISO_TIME_LEN+1];
1553 size_t len;
1554 crypto_pk_env_t *private_key = get_server_identity_key();
1555 char *identity_pkey; /* Identity key, DER64-encoded. */
1556 size_t identity_pkey_len;
1558 if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
1559 &identity_pkey_len)<0) {
1560 log_warn(LD_BUG,"write identity_pkey to string failed!");
1561 goto err;
1563 format_iso_time(published, time(NULL));
1565 len = 2048;
1566 s = tor_malloc_zero(len);
1567 tor_snprintf(s, len,
1568 "network-status\n"
1569 "published %s\n"
1570 "router-status %s\n"
1571 "dir-signing-key\n%s"
1572 "directory-signature %s\n",
1573 published, "", identity_pkey,
1574 get_options()->Nickname);
1575 tor_free(identity_pkey);
1576 if (router_get_runningrouters_hash(s,digest)) {
1577 log_warn(LD_BUG,"couldn't compute digest");
1578 goto err;
1580 note_crypto_pk_op(SIGN_DIR);
1581 if (router_append_dirobj_signature(s, len, digest, private_key)<0)
1582 goto err;
1584 set_cached_dir(&the_runningrouters, s, time(NULL));
1585 runningrouters_is_dirty = 0;
1587 return &the_runningrouters;
1588 err:
1589 tor_free(s);
1590 return NULL;
1593 /** Set *<b>rr</b> to the most recently generated encoded signed
1594 * running-routers list, generating a new one as necessary. Return the
1595 * size of the directory on success, and 0 on failure. */
1596 cached_dir_t *
1597 dirserv_get_runningrouters(void)
1599 return dirserv_pick_cached_dir_obj(
1600 &cached_runningrouters, &the_runningrouters,
1601 runningrouters_is_dirty,
1602 generate_runningrouters,
1603 "v1 network status list", V1_AUTHORITY);
1606 /** Return the latest downloaded consensus networkstatus in encoded, signed,
1607 * optionally compressed format, suitable for sending to clients. */
1608 cached_dir_t *
1609 dirserv_get_consensus(void)
1611 return cached_v3_networkstatus;
1614 /** For authoritative directories: the current (v2) network status. */
1615 static cached_dir_t *the_v2_networkstatus = NULL;
1617 /** Return true iff our opinion of the routers has been stale for long
1618 * enough that we should generate a new v2 network status doc. */
1619 static int
1620 should_generate_v2_networkstatus(void)
1622 return authdir_mode_v2(get_options()) &&
1623 the_v2_networkstatus_is_dirty &&
1624 the_v2_networkstatus_is_dirty + DIR_REGEN_SLACK_TIME < time(NULL);
1627 /** If a router's uptime is at least this value, then it is always
1628 * considered stable, regardless of the rest of the network. This
1629 * way we resist attacks where an attacker doubles the size of the
1630 * network using allegedly high-uptime nodes, displacing all the
1631 * current guards. */
1632 #define UPTIME_TO_GUARANTEE_STABLE (3600*24*30)
1633 /** If a router's MTBF is at least this value, then it is always stable.
1634 * See above. (Corresponds to about 7 days for current decay rates.) */
1635 #define MTBF_TO_GUARANTEE_STABLE (60*60*24*5)
1636 /** Similarly, we protect sufficiently fast nodes from being pushed
1637 * out of the set of Fast nodes. */
1638 #define BANDWIDTH_TO_GUARANTEE_FAST ROUTER_REQUIRED_MIN_BANDWIDTH
1639 /** Similarly, every node with sufficient bandwidth can be considered
1640 * for Guard status. */
1641 #define BANDWIDTH_TO_GUARANTEE_GUARD (250*1024)
1642 /** Similarly, every node with at least this much weighted time known can be
1643 * considered familiar enough to be a guard. Corresponds to about 20 days for
1644 * current decay rates.
1646 #define TIME_KNOWN_TO_GUARANTEE_FAMILIAR (8*24*60*60)
1647 /** Similarly, every node with sufficient WFU is around enough to be a guard.
1649 #define WFU_TO_GUARANTEE_GUARD (0.995)
1651 /* Thresholds for server performance: set by
1652 * dirserv_compute_performance_thresholds, and used by
1653 * generate_v2_networkstatus */
1655 /** Any router with an uptime of at least this value is stable. */
1656 static uint32_t stable_uptime = 0; /* start at a safe value */
1657 /** Any router with an mtbf of at least this value is stable. */
1658 static double stable_mtbf = 0.0;
1659 /** If true, we have measured enough mtbf info to look at stable_mtbf rather
1660 * than stable_uptime. */
1661 static int enough_mtbf_info = 0;
1662 /** Any router with a weighted fractional uptime of at least this much might
1663 * be good as a guard. */
1664 static double guard_wfu = 0.0;
1665 /** Don't call a router a guard unless we've known about it for at least this
1666 * many seconds. */
1667 static long guard_tk = 0;
1668 /** Any router with a bandwidth at least this high is "Fast" */
1669 static uint32_t fast_bandwidth = 0;
1670 /** If exits can be guards, then all guards must have a bandwidth this
1671 * high. */
1672 static uint32_t guard_bandwidth_including_exits = 0;
1673 /** If exits can't be guards, then all guards must have a bandwidth this
1674 * high. */
1675 static uint32_t guard_bandwidth_excluding_exits = 0;
1676 /** Total bandwidth of all the routers we're considering. */
1677 static uint64_t total_bandwidth = 0;
1678 /** Total bandwidth of all the exit routers we're considering. */
1679 static uint64_t total_exit_bandwidth = 0;
1681 /** Helper: estimate the uptime of a router given its stated uptime and the
1682 * amount of time since it last stated its stated uptime. */
1683 static INLINE long
1684 real_uptime(routerinfo_t *router, time_t now)
1686 if (now < router->cache_info.published_on)
1687 return router->uptime;
1688 else
1689 return router->uptime + (now - router->cache_info.published_on);
1692 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1693 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1694 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1695 * bandwidth.
1697 static int
1698 dirserv_thinks_router_is_unreliable(time_t now,
1699 routerinfo_t *router,
1700 int need_uptime, int need_capacity)
1702 if (need_uptime) {
1703 if (!enough_mtbf_info) {
1704 /* XXX022 Once most authorities are on v3, we should change the rule from
1705 * "use uptime if we don't have mtbf data" to "don't advertise Stable on
1706 * v3 if we don't have enough mtbf data." */
1707 long uptime = real_uptime(router, now);
1708 if ((unsigned)uptime < stable_uptime &&
1709 (unsigned)uptime < UPTIME_TO_GUARANTEE_STABLE)
1710 return 1;
1711 } else {
1712 double mtbf =
1713 rep_hist_get_stability(router->cache_info.identity_digest, now);
1714 if (mtbf < stable_mtbf &&
1715 mtbf < MTBF_TO_GUARANTEE_STABLE)
1716 return 1;
1719 if (need_capacity) {
1720 uint32_t bw = router_get_advertised_bandwidth(router);
1721 if (bw < fast_bandwidth)
1722 return 1;
1724 return 0;
1727 /** Return true iff <b>router</b> should be assigned the "HSDir" flag.
1728 * Right now this means it advertises support for it, it has a high
1729 * uptime, and it's currently considered Running.
1731 * This function needs to be called after router-\>is_running has
1732 * been set.
1734 static int
1735 dirserv_thinks_router_is_hs_dir(routerinfo_t *router, time_t now)
1737 long uptime = real_uptime(router, now);
1739 return (router->wants_to_be_hs_dir &&
1740 uptime > get_options()->MinUptimeHidServDirectoryV2 &&
1741 router->is_running);
1744 /** Look through the routerlist, the Mean Time Between Failure history, and
1745 * the Weighted Fractional Uptime history, and use them to set thresholds for
1746 * the Stable, Fast, and Guard flags. Update the fields stable_uptime,
1747 * stable_mtbf, enough_mtbf_info, guard_wfu, guard_tk, fast_bandwidth,
1748 * guard_bandwidh_including_exits, guard_bandwidth_excluding_exits,
1749 * total_bandwidth, and total_exit_bandwidth.
1751 * Also, set the is_exit flag of each router appropriately. */
1752 static void
1753 dirserv_compute_performance_thresholds(routerlist_t *rl)
1755 int n_active, n_active_nonexit, n_familiar;
1756 uint32_t *uptimes, *bandwidths, *bandwidths_excluding_exits;
1757 long *tks;
1758 double *mtbfs, *wfus;
1759 time_t now = time(NULL);
1761 /* initialize these all here, in case there are no routers */
1762 stable_uptime = 0;
1763 stable_mtbf = 0;
1764 fast_bandwidth = 0;
1765 guard_bandwidth_including_exits = 0;
1766 guard_bandwidth_excluding_exits = 0;
1767 guard_tk = 0;
1768 guard_wfu = 0;
1769 total_bandwidth = 0;
1770 total_exit_bandwidth = 0;
1772 /* Initialize arrays that will hold values for each router. We'll
1773 * sort them and use that to compute thresholds. */
1774 n_active = n_active_nonexit = 0;
1775 /* Uptime for every active router. */
1776 uptimes = tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
1777 /* Bandwidth for every active router. */
1778 bandwidths = tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
1779 /* Bandwidth for every active non-exit router. */
1780 bandwidths_excluding_exits =
1781 tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
1782 /* Weighted mean time between failure for each active router. */
1783 mtbfs = tor_malloc(sizeof(double)*smartlist_len(rl->routers));
1784 /* Time-known for each active router. */
1785 tks = tor_malloc(sizeof(long)*smartlist_len(rl->routers));
1786 /* Weighted fractional uptime for each active router. */
1787 wfus = tor_malloc(sizeof(double)*smartlist_len(rl->routers));
1789 /* Now, fill in the arrays. */
1790 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
1791 if (router_is_active(ri, now)) {
1792 const char *id = ri->cache_info.identity_digest;
1793 uint32_t bw;
1794 ri->is_exit = exit_policy_is_general_exit(ri->exit_policy);
1795 uptimes[n_active] = (uint32_t)real_uptime(ri, now);
1796 mtbfs[n_active] = rep_hist_get_stability(id, now);
1797 tks [n_active] = rep_hist_get_weighted_time_known(id, now);
1798 bandwidths[n_active] = bw = router_get_advertised_bandwidth(ri);
1799 total_bandwidth += bw;
1800 if (ri->is_exit && !ri->is_bad_exit) {
1801 total_exit_bandwidth += bw;
1802 } else {
1803 bandwidths_excluding_exits[n_active_nonexit] = bw;
1804 ++n_active_nonexit;
1806 ++n_active;
1810 /* Now, compute thresholds. */
1811 if (n_active) {
1812 /* The median uptime is stable. */
1813 stable_uptime = median_uint32(uptimes, n_active);
1814 /* The median mtbf is stable, if we have enough mtbf info */
1815 stable_mtbf = median_double(mtbfs, n_active);
1816 /* The 12.5th percentile bandwidth is fast. */
1817 fast_bandwidth = find_nth_uint32(bandwidths, n_active, n_active/8);
1818 /* (Now bandwidths is sorted.) */
1819 if (fast_bandwidth < ROUTER_REQUIRED_MIN_BANDWIDTH/2)
1820 fast_bandwidth = bandwidths[n_active/4];
1821 guard_bandwidth_including_exits = bandwidths[(n_active-1)/2];
1822 guard_tk = find_nth_long(tks, n_active, n_active/8);
1825 if (guard_tk > TIME_KNOWN_TO_GUARANTEE_FAMILIAR)
1826 guard_tk = TIME_KNOWN_TO_GUARANTEE_FAMILIAR;
1828 if (fast_bandwidth > BANDWIDTH_TO_GUARANTEE_FAST)
1829 fast_bandwidth = BANDWIDTH_TO_GUARANTEE_FAST;
1831 /* Now that we have a time-known that 7/8 routers are known longer than,
1832 * fill wfus with the wfu of every such "familiar" router. */
1833 n_familiar = 0;
1834 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
1835 if (router_is_active(ri, now)) {
1836 const char *id = ri->cache_info.identity_digest;
1837 long tk = rep_hist_get_weighted_time_known(id, now);
1838 if (tk < guard_tk)
1839 continue;
1840 wfus[n_familiar++] = rep_hist_get_weighted_fractional_uptime(id, now);
1843 if (n_familiar)
1844 guard_wfu = median_double(wfus, n_familiar);
1845 if (guard_wfu > WFU_TO_GUARANTEE_GUARD)
1846 guard_wfu = WFU_TO_GUARANTEE_GUARD;
1848 enough_mtbf_info = rep_hist_have_measured_enough_stability();
1850 if (n_active_nonexit) {
1851 guard_bandwidth_excluding_exits =
1852 median_uint32(bandwidths_excluding_exits, n_active_nonexit);
1855 log(LOG_INFO, LD_DIRSERV,
1856 "Cutoffs: For Stable, %lu sec uptime, %lu sec MTBF. "
1857 "For Fast: %lu bytes/sec. "
1858 "For Guard: WFU %.03lf%%, time-known %lu sec, "
1859 "and bandwidth %lu or %lu bytes/sec. We%s have enough stability data.",
1860 (unsigned long)stable_uptime,
1861 (unsigned long)stable_mtbf,
1862 (unsigned long)fast_bandwidth,
1863 guard_wfu*100,
1864 (unsigned long)guard_tk,
1865 (unsigned long)guard_bandwidth_including_exits,
1866 (unsigned long)guard_bandwidth_excluding_exits,
1867 enough_mtbf_info ? "" : " don't ");
1869 tor_free(uptimes);
1870 tor_free(mtbfs);
1871 tor_free(bandwidths);
1872 tor_free(bandwidths_excluding_exits);
1873 tor_free(tks);
1874 tor_free(wfus);
1877 /** Given a platform string as in a routerinfo_t (possibly null), return a
1878 * newly allocated version string for a networkstatus document, or NULL if the
1879 * platform doesn't give a Tor version. */
1880 static char *
1881 version_from_platform(const char *platform)
1883 if (platform && !strcmpstart(platform, "Tor ")) {
1884 const char *eos = find_whitespace(platform+4);
1885 if (eos && !strcmpstart(eos, " (r")) {
1886 /* XXXX Unify this logic with the other version extraction
1887 * logic in routerparse.c. */
1888 eos = find_whitespace(eos+1);
1890 if (eos) {
1891 return tor_strndup(platform, eos-platform);
1894 return NULL;
1897 /** Helper: write the router-status information in <b>rs</b> into <b>buf</b>,
1898 * which has at least <b>buf_len</b> free characters. Do NUL-termination.
1899 * Use the same format as in network-status documents. If <b>version</b> is
1900 * non-NULL, add a "v" line for the platform. Return 0 on success, -1 on
1901 * failure. If <b>first_line_only</b> is true, don't include any flags
1902 * or version line.
1905 routerstatus_format_entry(char *buf, size_t buf_len,
1906 routerstatus_t *rs, const char *version,
1907 int first_line_only, int v2_format)
1908 /* XXX: first_line_only and v2_format should probably be be both
1909 * replaced by a single purpose parameter.
1912 int r;
1913 struct in_addr in;
1914 char *cp;
1915 char *summary;
1917 char published[ISO_TIME_LEN+1];
1918 char ipaddr[INET_NTOA_BUF_LEN];
1919 char identity64[BASE64_DIGEST_LEN+1];
1920 char digest64[BASE64_DIGEST_LEN+1];
1922 format_iso_time(published, rs->published_on);
1923 digest_to_base64(identity64, rs->identity_digest);
1924 digest_to_base64(digest64, rs->descriptor_digest);
1925 in.s_addr = htonl(rs->addr);
1926 tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
1928 r = tor_snprintf(buf, buf_len,
1929 "r %s %s %s %s %s %d %d\n",
1930 rs->nickname,
1931 identity64,
1932 digest64,
1933 published,
1934 ipaddr,
1935 (int)rs->or_port,
1936 (int)rs->dir_port);
1937 if (r<0) {
1938 log_warn(LD_BUG, "Not enough space in buffer.");
1939 return -1;
1941 if (first_line_only)
1942 return 0;
1944 cp = buf + strlen(buf);
1945 /* NOTE: Whenever this list expands, be sure to increase MAX_FLAG_LINE_LEN*/
1946 r = tor_snprintf(cp, buf_len - (cp-buf),
1947 "s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
1948 /* These must stay in alphabetical order. */
1949 rs->is_authority?" Authority":"",
1950 rs->is_bad_directory?" BadDirectory":"",
1951 rs->is_bad_exit?" BadExit":"",
1952 rs->is_exit?" Exit":"",
1953 rs->is_fast?" Fast":"",
1954 rs->is_possible_guard?" Guard":"",
1955 rs->is_hs_dir?" HSDir":"",
1956 rs->is_named?" Named":"",
1957 rs->is_running?" Running":"",
1958 rs->is_stable?" Stable":"",
1959 rs->is_unnamed?" Unnamed":"",
1960 rs->is_v2_dir?" V2Dir":"",
1961 rs->is_valid?" Valid":"");
1962 if (r<0) {
1963 log_warn(LD_BUG, "Not enough space in buffer.");
1964 return -1;
1966 cp += strlen(cp);
1968 /* length of "opt v \n" */
1969 #define V_LINE_OVERHEAD 7
1970 if (version && strlen(version) < MAX_V_LINE_LEN - V_LINE_OVERHEAD) {
1971 if (tor_snprintf(cp, buf_len - (cp-buf), "opt v %s\n", version)<0) {
1972 log_warn(LD_BUG, "Unable to print router version.");
1973 return -1;
1975 cp += strlen(cp);
1978 if (!v2_format) {
1979 routerinfo_t* desc = router_get_by_digest(rs->identity_digest);
1981 /* Blow up more or less nicely if we didn't get anything or not the
1982 * thing we expected.
1984 if (!desc) {
1985 char id[HEX_DIGEST_LEN+1];
1986 char dd[HEX_DIGEST_LEN+1];
1988 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
1989 base16_encode(dd, sizeof(dd), rs->descriptor_digest, DIGEST_LEN);
1990 log_warn(LD_BUG, "Cannot get any descriptor for %s "
1991 "(wanted descriptor %s).",
1992 id, dd);
1993 return -1;
1995 if (fast_memcmp(desc->cache_info.signed_descriptor_digest,
1996 rs->descriptor_digest,
1997 DIGEST_LEN)) {
1998 char rl_d[HEX_DIGEST_LEN+1];
1999 char rs_d[HEX_DIGEST_LEN+1];
2000 char id[HEX_DIGEST_LEN+1];
2002 base16_encode(rl_d, sizeof(rl_d),
2003 desc->cache_info.signed_descriptor_digest, DIGEST_LEN);
2004 base16_encode(rs_d, sizeof(rs_d), rs->descriptor_digest, DIGEST_LEN);
2005 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
2006 log_err(LD_BUG, "descriptor digest in routerlist does not match "
2007 "the one in routerstatus: %s vs %s "
2008 "(router %s)\n",
2009 rl_d, rs_d, id);
2011 tor_assert(fast_memeq(desc->cache_info.signed_descriptor_digest,
2012 rs->descriptor_digest,
2013 DIGEST_LEN));
2016 r = tor_snprintf(cp, buf_len - (cp-buf),
2017 "w Bandwidth=%d\n",
2018 router_get_advertised_bandwidth_capped(desc) / 1024);
2019 if (r<0) {
2020 log_warn(LD_BUG, "Not enough space in buffer.");
2021 return -1;
2023 cp += strlen(cp);
2025 summary = policy_summarize(desc->exit_policy);
2026 r = tor_snprintf(cp, buf_len - (cp-buf), "p %s\n", summary);
2027 if (r<0) {
2028 log_warn(LD_BUG, "Not enough space in buffer.");
2029 tor_free(summary);
2030 return -1;
2032 cp += strlen(cp);
2033 tor_free(summary);
2036 return 0;
2039 /** Helper for sorting: compares two routerinfos first by address, and then by
2040 * descending order of "usefulness". (An authority is more useful than a
2041 * non-authority; a running router is more useful than a non-running router;
2042 * and a router with more bandwidth is more useful than one with less.)
2044 static int
2045 _compare_routerinfo_by_ip_and_bw(const void **a, const void **b)
2047 routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
2048 int first_is_auth, second_is_auth;
2049 uint32_t bw_first, bw_second;
2051 /* we return -1 if first should appear before second... that is,
2052 * if first is a better router. */
2053 if (first->addr < second->addr)
2054 return -1;
2055 else if (first->addr > second->addr)
2056 return 1;
2058 /* Potentially, this next bit could cause k n lg n memcmp calls. But in
2059 * reality, we will almost never get here, since addresses will usually be
2060 * different. */
2062 first_is_auth =
2063 router_digest_is_trusted_dir(first->cache_info.identity_digest);
2064 second_is_auth =
2065 router_digest_is_trusted_dir(second->cache_info.identity_digest);
2067 if (first_is_auth && !second_is_auth)
2068 return -1;
2069 else if (!first_is_auth && second_is_auth)
2070 return 1;
2072 else if (first->is_running && !second->is_running)
2073 return -1;
2074 else if (!first->is_running && second->is_running)
2075 return 1;
2077 bw_first = router_get_advertised_bandwidth(first);
2078 bw_second = router_get_advertised_bandwidth(second);
2080 if (bw_first > bw_second)
2081 return -1;
2082 else if (bw_first < bw_second)
2083 return 1;
2085 /* They're equal! Compare by identity digest, so there's a
2086 * deterministic order and we avoid flapping. */
2087 return fast_memcmp(first->cache_info.identity_digest,
2088 second->cache_info.identity_digest,
2089 DIGEST_LEN);
2092 /** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
2093 * whose keys are the identity digests of those routers that we're going to
2094 * exclude for Sybil-like appearance. */
2095 static digestmap_t *
2096 get_possible_sybil_list(const smartlist_t *routers)
2098 or_options_t *options = get_options();
2099 digestmap_t *omit_as_sybil;
2100 smartlist_t *routers_by_ip = smartlist_create();
2101 uint32_t last_addr;
2102 int addr_count;
2103 /* Allow at most this number of Tor servers on a single IP address, ... */
2104 int max_with_same_addr = options->AuthDirMaxServersPerAddr;
2105 /* ... unless it's a directory authority, in which case allow more. */
2106 int max_with_same_addr_on_authority = options->AuthDirMaxServersPerAuthAddr;
2107 if (max_with_same_addr <= 0)
2108 max_with_same_addr = INT_MAX;
2109 if (max_with_same_addr_on_authority <= 0)
2110 max_with_same_addr_on_authority = INT_MAX;
2112 smartlist_add_all(routers_by_ip, routers);
2113 smartlist_sort(routers_by_ip, _compare_routerinfo_by_ip_and_bw);
2114 omit_as_sybil = digestmap_new();
2116 last_addr = 0;
2117 addr_count = 0;
2118 SMARTLIST_FOREACH(routers_by_ip, routerinfo_t *, ri,
2120 if (last_addr != ri->addr) {
2121 last_addr = ri->addr;
2122 addr_count = 1;
2123 } else if (++addr_count > max_with_same_addr) {
2124 if (!router_addr_is_trusted_dir(ri->addr) ||
2125 addr_count > max_with_same_addr_on_authority)
2126 digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
2130 smartlist_free(routers_by_ip);
2131 return omit_as_sybil;
2134 /** Extract status information from <b>ri</b> and from other authority
2135 * functions and store it in <b>rs</b>>. If <b>naming</b>, consider setting
2136 * the named flag in <b>rs</b>. If not <b>exits_can_be_guards</b>, never mark
2137 * an exit as a guard. If <b>listbadexits</b>, consider setting the badexit
2138 * flag.
2140 * We assume that ri-\>is_running has already been set, e.g. by
2141 * dirserv_set_router_is_running(ri, now);
2143 void
2144 set_routerstatus_from_routerinfo(routerstatus_t *rs,
2145 routerinfo_t *ri, time_t now,
2146 int naming, int exits_can_be_guards,
2147 int listbadexits, int listbaddirs)
2149 int unstable_version =
2150 !tor_version_as_new_as(ri->platform,"0.1.1.16-rc-cvs");
2151 memset(rs, 0, sizeof(routerstatus_t));
2153 rs->is_authority =
2154 router_digest_is_trusted_dir(ri->cache_info.identity_digest);
2156 /* Already set by compute_performance_thresholds. */
2157 rs->is_exit = ri->is_exit;
2158 rs->is_stable = ri->is_stable =
2159 router_is_active(ri, now) &&
2160 !dirserv_thinks_router_is_unreliable(now, ri, 1, 0) &&
2161 !unstable_version;
2162 rs->is_fast = ri->is_fast =
2163 router_is_active(ri, now) &&
2164 !dirserv_thinks_router_is_unreliable(now, ri, 0, 1);
2165 rs->is_running = ri->is_running; /* computed above */
2167 if (naming) {
2168 uint32_t name_status = dirserv_get_name_status(
2169 ri->cache_info.identity_digest, ri->nickname);
2170 rs->is_named = (naming && (name_status & FP_NAMED)) ? 1 : 0;
2171 rs->is_unnamed = (naming && (name_status & FP_UNNAMED)) ? 1 : 0;
2173 rs->is_valid = ri->is_valid;
2175 if (rs->is_fast &&
2176 (!rs->is_exit || exits_can_be_guards) &&
2177 (router_get_advertised_bandwidth(ri) >= BANDWIDTH_TO_GUARANTEE_GUARD ||
2178 router_get_advertised_bandwidth(ri) >=
2179 (exits_can_be_guards ? guard_bandwidth_including_exits :
2180 guard_bandwidth_excluding_exits))) {
2181 long tk = rep_hist_get_weighted_time_known(
2182 ri->cache_info.identity_digest, now);
2183 double wfu = rep_hist_get_weighted_fractional_uptime(
2184 ri->cache_info.identity_digest, now);
2185 rs->is_possible_guard = (wfu >= guard_wfu && tk >= guard_tk) ? 1 : 0;
2186 } else {
2187 rs->is_possible_guard = 0;
2189 rs->is_bad_directory = listbaddirs && ri->is_bad_directory;
2190 rs->is_bad_exit = listbadexits && ri->is_bad_exit;
2191 ri->is_hs_dir = dirserv_thinks_router_is_hs_dir(ri, now);
2192 rs->is_hs_dir = ri->is_hs_dir;
2193 rs->is_v2_dir = ri->dir_port != 0;
2195 if (!strcasecmp(ri->nickname, UNNAMED_ROUTER_NICKNAME))
2196 rs->is_named = rs->is_unnamed = 0;
2198 rs->published_on = ri->cache_info.published_on;
2199 memcpy(rs->identity_digest, ri->cache_info.identity_digest, DIGEST_LEN);
2200 memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest,
2201 DIGEST_LEN);
2202 rs->addr = ri->addr;
2203 strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname));
2204 rs->or_port = ri->or_port;
2205 rs->dir_port = ri->dir_port;
2208 /** Routerstatus <b>rs</b> is part of a group of routers that are on
2209 * too narrow an IP-space. Clear out its flags: we don't want people
2210 * using it.
2212 static void
2213 clear_status_flags_on_sybil(routerstatus_t *rs)
2215 rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
2216 rs->is_running = rs->is_named = rs->is_valid = rs->is_v2_dir =
2217 rs->is_hs_dir = rs->is_possible_guard = rs->is_bad_exit =
2218 rs->is_bad_directory = 0;
2219 /* FFFF we might want some mechanism to check later on if we
2220 * missed zeroing any flags: it's easy to add a new flag but
2221 * forget to add it to this clause. */
2224 /** Clear all the status flags in routerinfo <b>router</b>. We put this
2225 * function here because it's eerily similar to
2226 * clear_status_flags_on_sybil() above. One day we should merge them. */
2227 void
2228 router_clear_status_flags(routerinfo_t *router)
2230 router->is_valid = router->is_running = router->is_hs_dir =
2231 router->is_fast = router->is_stable =
2232 router->is_possible_guard = router->is_exit =
2233 router->is_bad_exit = router->is_bad_directory = 0;
2236 /** Return a new networkstatus_t* containing our current opinion. (For v3
2237 * authorities) */
2238 networkstatus_t *
2239 dirserv_generate_networkstatus_vote_obj(crypto_pk_env_t *private_key,
2240 authority_cert_t *cert)
2242 or_options_t *options = get_options();
2243 networkstatus_t *v3_out = NULL;
2244 uint32_t addr;
2245 char *hostname = NULL, *client_versions = NULL, *server_versions = NULL;
2246 const char *contact;
2247 smartlist_t *routers, *routerstatuses;
2248 char identity_digest[DIGEST_LEN];
2249 char signing_key_digest[DIGEST_LEN];
2250 int naming = options->NamingAuthoritativeDir;
2251 int listbadexits = options->AuthDirListBadExits;
2252 int listbaddirs = options->AuthDirListBadDirs;
2253 int exits_can_be_guards;
2254 routerlist_t *rl = router_get_routerlist();
2255 time_t now = time(NULL);
2256 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2257 networkstatus_voter_info_t *voter = NULL;
2258 vote_timing_t timing;
2259 digestmap_t *omit_as_sybil = NULL;
2260 int vote_on_reachability = 1;
2262 tor_assert(private_key);
2263 tor_assert(cert);
2265 if (now - time_of_process_start <
2266 options->TestingAuthDirTimeToLearnReachability)
2267 vote_on_reachability = 0;
2269 if (resolve_my_address(LOG_WARN, options, &addr, &hostname)<0) {
2270 log_warn(LD_NET, "Couldn't resolve my hostname");
2271 return NULL;
2273 if (!strchr(hostname, '.')) {
2274 tor_free(hostname);
2275 hostname = tor_dup_ip(addr);
2277 if (crypto_pk_get_digest(private_key, signing_key_digest)<0) {
2278 log_err(LD_BUG, "Error computing signing key digest");
2279 return NULL;
2281 if (crypto_pk_get_digest(cert->identity_key, identity_digest)<0) {
2282 log_err(LD_BUG, "Error computing identity key digest");
2283 return NULL;
2286 if (options->VersioningAuthoritativeDir) {
2287 client_versions = format_versions_list(options->RecommendedClientVersions);
2288 server_versions = format_versions_list(options->RecommendedServerVersions);
2291 contact = get_options()->ContactInfo;
2292 if (!contact)
2293 contact = "(none)";
2295 /* precompute this part, since we need it to decide what "stable"
2296 * means. */
2297 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2298 dirserv_set_router_is_running(ri, now);
2301 dirserv_compute_performance_thresholds(rl);
2303 /* XXXX We should take steps to keep this from oscillating if
2304 * total_exit_bandwidth is close to total_bandwidth/3. */
2305 exits_can_be_guards = total_exit_bandwidth >= (total_bandwidth / 3);
2307 routers = smartlist_create();
2308 smartlist_add_all(routers, rl->routers);
2309 routers_sort_by_identity(routers);
2310 omit_as_sybil = get_possible_sybil_list(routers);
2312 routerstatuses = smartlist_create();
2314 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
2315 if (ri->cache_info.published_on >= cutoff) {
2316 routerstatus_t *rs;
2317 vote_routerstatus_t *vrs;
2319 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
2320 rs = &vrs->status;
2321 set_routerstatus_from_routerinfo(rs, ri, now,
2322 naming, exits_can_be_guards,
2323 listbadexits, listbaddirs);
2325 if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
2326 clear_status_flags_on_sybil(rs);
2328 if (!vote_on_reachability)
2329 rs->is_running = 0;
2331 vrs->version = version_from_platform(ri->platform);
2332 smartlist_add(routerstatuses, vrs);
2335 smartlist_free(routers);
2336 digestmap_free(omit_as_sybil, NULL);
2338 v3_out = tor_malloc_zero(sizeof(networkstatus_t));
2340 v3_out->type = NS_TYPE_VOTE;
2341 dirvote_get_preferred_voting_intervals(&timing);
2342 v3_out->published = now;
2344 char tbuf[ISO_TIME_LEN+1];
2345 networkstatus_t *current_consensus =
2346 networkstatus_get_live_consensus(now);
2347 long last_consensus_interval; /* only used to pick a valid_after */
2348 if (current_consensus)
2349 last_consensus_interval = current_consensus->fresh_until -
2350 current_consensus->valid_after;
2351 else
2352 last_consensus_interval = options->TestingV3AuthInitialVotingInterval;
2353 v3_out->valid_after =
2354 dirvote_get_start_of_next_interval(now, (int)last_consensus_interval);
2355 format_iso_time(tbuf, v3_out->valid_after);
2356 log_notice(LD_DIR,"Choosing valid-after time in vote as %s: "
2357 "consensus_set=%d, last_interval=%d",
2358 tbuf, current_consensus?1:0, (int)last_consensus_interval);
2360 v3_out->fresh_until = v3_out->valid_after + timing.vote_interval;
2361 v3_out->valid_until = v3_out->valid_after +
2362 (timing.vote_interval * timing.n_intervals_valid);
2363 v3_out->vote_seconds = timing.vote_delay;
2364 v3_out->dist_seconds = timing.dist_delay;
2365 tor_assert(v3_out->vote_seconds > 0);
2366 tor_assert(v3_out->dist_seconds > 0);
2367 tor_assert(timing.n_intervals_valid > 0);
2369 v3_out->client_versions = client_versions;
2370 v3_out->server_versions = server_versions;
2371 v3_out->known_flags = smartlist_create();
2372 smartlist_split_string(v3_out->known_flags,
2373 "Authority Exit Fast Guard HSDir Stable V2Dir Valid",
2374 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2375 if (vote_on_reachability)
2376 smartlist_add(v3_out->known_flags, tor_strdup("Running"));
2377 if (listbaddirs)
2378 smartlist_add(v3_out->known_flags, tor_strdup("BadDirectory"));
2379 if (listbadexits)
2380 smartlist_add(v3_out->known_flags, tor_strdup("BadExit"));
2381 if (naming) {
2382 smartlist_add(v3_out->known_flags, tor_strdup("Named"));
2383 smartlist_add(v3_out->known_flags, tor_strdup("Unnamed"));
2385 smartlist_sort_strings(v3_out->known_flags);
2387 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
2388 voter->nickname = tor_strdup(options->Nickname);
2389 memcpy(voter->identity_digest, identity_digest, DIGEST_LEN);
2390 voter->address = hostname;
2391 voter->addr = addr;
2392 voter->dir_port = options->DirPort;
2393 voter->or_port = options->ORPort;
2394 voter->contact = tor_strdup(contact);
2395 memcpy(voter->signing_key_digest, signing_key_digest, DIGEST_LEN);
2396 if (options->V3AuthUseLegacyKey) {
2397 authority_cert_t *c = get_my_v3_legacy_cert();
2398 if (c) {
2399 crypto_pk_get_digest(c->identity_key, voter->legacy_id_digest);
2403 v3_out->voters = smartlist_create();
2404 smartlist_add(v3_out->voters, voter);
2405 v3_out->cert = authority_cert_dup(cert);
2406 v3_out->routerstatus_list = routerstatuses;
2407 /* Note: networkstatus_digest is unset; it won't get set until we actually
2408 * format the vote. */
2410 return v3_out;
2413 /** For v2 authoritative directories only: Replace the contents of
2414 * <b>the_v2_networkstatus</b> with a newly generated network status
2415 * object. */
2416 static cached_dir_t *
2417 generate_v2_networkstatus_opinion(void)
2419 cached_dir_t *r = NULL;
2420 size_t len, identity_pkey_len;
2421 char *status = NULL, *client_versions = NULL, *server_versions = NULL,
2422 *identity_pkey = NULL, *hostname = NULL;
2423 char *outp, *endp;
2424 or_options_t *options = get_options();
2425 char fingerprint[FINGERPRINT_LEN+1];
2426 char ipaddr[INET_NTOA_BUF_LEN];
2427 char published[ISO_TIME_LEN+1];
2428 char digest[DIGEST_LEN];
2429 struct in_addr in;
2430 uint32_t addr;
2431 crypto_pk_env_t *private_key;
2432 routerlist_t *rl = router_get_routerlist();
2433 time_t now = time(NULL);
2434 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2435 int naming = options->NamingAuthoritativeDir;
2436 int versioning = options->VersioningAuthoritativeDir;
2437 int listbaddirs = options->AuthDirListBadDirs;
2438 int listbadexits = options->AuthDirListBadExits;
2439 int exits_can_be_guards;
2440 const char *contact;
2441 char *version_lines = NULL;
2442 smartlist_t *routers = NULL;
2443 digestmap_t *omit_as_sybil = NULL;
2445 private_key = get_server_identity_key();
2447 if (resolve_my_address(LOG_WARN, options, &addr, &hostname)<0) {
2448 log_warn(LD_NET, "Couldn't resolve my hostname");
2449 goto done;
2451 in.s_addr = htonl(addr);
2452 tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
2454 format_iso_time(published, now);
2456 client_versions = format_versions_list(options->RecommendedClientVersions);
2457 server_versions = format_versions_list(options->RecommendedServerVersions);
2459 if (crypto_pk_write_public_key_to_string(private_key, &identity_pkey,
2460 &identity_pkey_len)<0) {
2461 log_warn(LD_BUG,"Writing public key to string failed.");
2462 goto done;
2465 if (crypto_pk_get_fingerprint(private_key, fingerprint, 0)<0) {
2466 log_err(LD_BUG, "Error computing fingerprint");
2467 goto done;
2470 contact = get_options()->ContactInfo;
2471 if (!contact)
2472 contact = "(none)";
2474 if (versioning) {
2475 size_t v_len = 64+strlen(client_versions)+strlen(server_versions);
2476 version_lines = tor_malloc(v_len);
2477 tor_snprintf(version_lines, v_len,
2478 "client-versions %s\nserver-versions %s\n",
2479 client_versions, server_versions);
2480 } else {
2481 version_lines = tor_strdup("");
2484 len = 4096+strlen(client_versions)+strlen(server_versions);
2485 len += identity_pkey_len*2;
2486 len += (RS_ENTRY_LEN)*smartlist_len(rl->routers);
2488 status = tor_malloc(len);
2489 tor_snprintf(status, len,
2490 "network-status-version 2\n"
2491 "dir-source %s %s %d\n"
2492 "fingerprint %s\n"
2493 "contact %s\n"
2494 "published %s\n"
2495 "dir-options%s%s%s%s\n"
2496 "%s" /* client version line, server version line. */
2497 "dir-signing-key\n%s",
2498 hostname, ipaddr, (int)options->DirPort,
2499 fingerprint,
2500 contact,
2501 published,
2502 naming ? " Names" : "",
2503 listbaddirs ? " BadDirectories" : "",
2504 listbadexits ? " BadExits" : "",
2505 versioning ? " Versions" : "",
2506 version_lines,
2507 identity_pkey);
2508 outp = status + strlen(status);
2509 endp = status + len;
2511 /* precompute this part, since we need it to decide what "stable"
2512 * means. */
2513 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2514 dirserv_set_router_is_running(ri, now);
2517 dirserv_compute_performance_thresholds(rl);
2519 /* XXXX We should take steps to keep this from oscillating if
2520 * total_exit_bandwidth is close to total_bandwidth/3. */
2521 exits_can_be_guards = total_exit_bandwidth >= (total_bandwidth / 3);
2523 routers = smartlist_create();
2524 smartlist_add_all(routers, rl->routers);
2525 routers_sort_by_identity(routers);
2527 omit_as_sybil = get_possible_sybil_list(routers);
2529 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
2530 if (ri->cache_info.published_on >= cutoff) {
2531 routerstatus_t rs;
2532 char *version = version_from_platform(ri->platform);
2534 set_routerstatus_from_routerinfo(&rs, ri, now,
2535 naming, exits_can_be_guards,
2536 listbadexits, listbaddirs);
2538 if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
2539 clear_status_flags_on_sybil(&rs);
2541 if (routerstatus_format_entry(outp, endp-outp, &rs, version, 0, 1)) {
2542 log_warn(LD_BUG, "Unable to print router status.");
2543 tor_free(version);
2544 goto done;
2546 tor_free(version);
2547 outp += strlen(outp);
2551 if (tor_snprintf(outp, endp-outp, "directory-signature %s\n",
2552 get_options()->Nickname)<0) {
2553 log_warn(LD_BUG, "Unable to write signature line.");
2554 goto done;
2556 if (router_get_networkstatus_v2_hash(status, digest)<0) {
2557 log_warn(LD_BUG, "Unable to hash network status");
2558 goto done;
2560 outp += strlen(outp);
2562 note_crypto_pk_op(SIGN_DIR);
2563 if (router_append_dirobj_signature(outp,endp-outp,digest,private_key)<0) {
2564 log_warn(LD_BUG, "Unable to sign router status.");
2565 goto done;
2569 networkstatus_v2_t *ns;
2570 if (!(ns = networkstatus_v2_parse_from_string(status))) {
2571 log_err(LD_BUG,"Generated a networkstatus we couldn't parse.");
2572 goto done;
2574 networkstatus_v2_free(ns);
2578 cached_dir_t **ns_ptr = &the_v2_networkstatus;
2579 if (*ns_ptr)
2580 cached_dir_decref(*ns_ptr);
2581 *ns_ptr = new_cached_dir(status, now);
2582 status = NULL; /* So it doesn't get double-freed. */
2583 the_v2_networkstatus_is_dirty = 0;
2584 router_set_networkstatus_v2((*ns_ptr)->dir, now, NS_GENERATED, NULL);
2585 r = *ns_ptr;
2588 done:
2589 tor_free(client_versions);
2590 tor_free(server_versions);
2591 tor_free(version_lines);
2592 tor_free(status);
2593 tor_free(hostname);
2594 tor_free(identity_pkey);
2595 if (routers)
2596 smartlist_free(routers);
2597 if (omit_as_sybil)
2598 digestmap_free(omit_as_sybil, NULL);
2599 return r;
2602 /** Given the portion of a networkstatus request URL after "tor/status/" in
2603 * <b>key</b>, append to <b>result</b> the digests of the identity keys of the
2604 * networkstatus objects that the client has requested. */
2605 void
2606 dirserv_get_networkstatus_v2_fingerprints(smartlist_t *result,
2607 const char *key)
2609 tor_assert(result);
2611 if (!cached_v2_networkstatus)
2612 cached_v2_networkstatus = digestmap_new();
2614 if (should_generate_v2_networkstatus())
2615 generate_v2_networkstatus_opinion();
2617 if (!strcmp(key,"authority")) {
2618 if (authdir_mode_v2(get_options())) {
2619 routerinfo_t *me = router_get_my_routerinfo();
2620 if (me)
2621 smartlist_add(result,
2622 tor_memdup(me->cache_info.identity_digest, DIGEST_LEN));
2624 } else if (!strcmp(key, "all")) {
2625 if (digestmap_size(cached_v2_networkstatus)) {
2626 digestmap_iter_t *iter;
2627 iter = digestmap_iter_init(cached_v2_networkstatus);
2628 while (!digestmap_iter_done(iter)) {
2629 const char *ident;
2630 void *val;
2631 digestmap_iter_get(iter, &ident, &val);
2632 smartlist_add(result, tor_memdup(ident, DIGEST_LEN));
2633 iter = digestmap_iter_next(cached_v2_networkstatus, iter);
2635 } else {
2636 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
2637 trusted_dir_server_t *, ds,
2638 if (ds->type & V2_AUTHORITY)
2639 smartlist_add(result, tor_memdup(ds->digest, DIGEST_LEN)));
2641 smartlist_sort_digests(result);
2642 if (smartlist_len(result) == 0)
2643 log_info(LD_DIRSERV,
2644 "Client requested 'all' network status objects; we have none.");
2645 } else if (!strcmpstart(key, "fp/")) {
2646 dir_split_resource_into_fingerprints(key+3, result, NULL, 1, 1);
2650 /** Look for a network status object as specified by <b>key</b>, which should
2651 * be either "authority" (to find a network status generated by us), a hex
2652 * identity digest (to find a network status generated by given directory), or
2653 * "all" (to return all the v2 network status objects we have).
2655 void
2656 dirserv_get_networkstatus_v2(smartlist_t *result,
2657 const char *key)
2659 cached_dir_t *cached;
2660 smartlist_t *fingerprints = smartlist_create();
2661 tor_assert(result);
2663 if (!cached_v2_networkstatus)
2664 cached_v2_networkstatus = digestmap_new();
2666 dirserv_get_networkstatus_v2_fingerprints(fingerprints, key);
2667 SMARTLIST_FOREACH(fingerprints, const char *, fp,
2669 if (router_digest_is_me(fp) && should_generate_v2_networkstatus())
2670 generate_v2_networkstatus_opinion();
2671 cached = digestmap_get(cached_v2_networkstatus, fp);
2672 if (cached) {
2673 smartlist_add(result, cached);
2674 } else {
2675 char hexbuf[HEX_DIGEST_LEN+1];
2676 base16_encode(hexbuf, sizeof(hexbuf), fp, DIGEST_LEN);
2677 log_info(LD_DIRSERV, "Don't know about any network status with "
2678 "fingerprint '%s'", hexbuf);
2681 SMARTLIST_FOREACH(fingerprints, char *, cp, tor_free(cp));
2682 smartlist_free(fingerprints);
2685 /** As dirserv_get_routerdescs(), but instead of getting signed_descriptor_t
2686 * pointers, adds copies of digests to fps_out, and doesn't use the
2687 * /tor/server/ prefix. For a /d/ request, adds descriptor digests; for other
2688 * requests, adds identity digests.
2691 dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
2692 const char **msg, int for_unencrypted_conn,
2693 int is_extrainfo)
2695 int by_id = 1;
2696 *msg = NULL;
2698 if (!strcmp(key, "all")) {
2699 routerlist_t *rl = router_get_routerlist();
2700 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2701 smartlist_add(fps_out,
2702 tor_memdup(r->cache_info.identity_digest, DIGEST_LEN)));
2703 /* Treat "all" requests as if they were unencrypted */
2704 for_unencrypted_conn = 1;
2705 } else if (!strcmp(key, "authority")) {
2706 routerinfo_t *ri = router_get_my_routerinfo();
2707 if (ri)
2708 smartlist_add(fps_out,
2709 tor_memdup(ri->cache_info.identity_digest, DIGEST_LEN));
2710 } else if (!strcmpstart(key, "d/")) {
2711 by_id = 0;
2712 key += strlen("d/");
2713 dir_split_resource_into_fingerprints(key, fps_out, NULL, 1, 1);
2714 } else if (!strcmpstart(key, "fp/")) {
2715 key += strlen("fp/");
2716 dir_split_resource_into_fingerprints(key, fps_out, NULL, 1, 1);
2717 } else {
2718 *msg = "Key not recognized";
2719 return -1;
2722 if (for_unencrypted_conn) {
2723 /* Remove anything that insists it not be sent unencrypted. */
2724 SMARTLIST_FOREACH(fps_out, char *, cp, {
2725 signed_descriptor_t *sd;
2726 if (by_id)
2727 sd = get_signed_descriptor_by_fp(cp,is_extrainfo,0);
2728 else if (is_extrainfo)
2729 sd = extrainfo_get_by_descriptor_digest(cp);
2730 else
2731 sd = router_get_by_descriptor_digest(cp);
2732 if (sd && !sd->send_unencrypted) {
2733 tor_free(cp);
2734 SMARTLIST_DEL_CURRENT(fps_out, cp);
2739 if (!smartlist_len(fps_out)) {
2740 *msg = "Servers unavailable";
2741 return -1;
2743 return 0;
2746 /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
2747 * <b>key</b>. The key should be either
2748 * - "/tor/server/authority" for our own routerinfo;
2749 * - "/tor/server/all" for all the routerinfos we have, concatenated;
2750 * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
2751 * hex identity digests; or
2752 * - "/tor/server/d/D" where D is a plus-separated sequence
2753 * of server descriptor digests, in hex.
2755 * Return 0 if we found some matching descriptors, or -1 if we do not
2756 * have any descriptors, no matching descriptors, or if we did not
2757 * recognize the key (URL).
2758 * If -1 is returned *<b>msg</b> will be set to an appropriate error
2759 * message.
2761 * XXXX rename this function. It's only called from the controller.
2762 * XXXX in fact, refactor this function, merging as much as possible.
2765 dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
2766 const char **msg)
2768 *msg = NULL;
2770 if (!strcmp(key, "/tor/server/all")) {
2771 routerlist_t *rl = router_get_routerlist();
2772 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2773 smartlist_add(descs_out, &(r->cache_info)));
2774 } else if (!strcmp(key, "/tor/server/authority")) {
2775 routerinfo_t *ri = router_get_my_routerinfo();
2776 if (ri)
2777 smartlist_add(descs_out, &(ri->cache_info));
2778 } else if (!strcmpstart(key, "/tor/server/d/")) {
2779 smartlist_t *digests = smartlist_create();
2780 key += strlen("/tor/server/d/");
2781 dir_split_resource_into_fingerprints(key, digests, NULL, 1, 1);
2782 SMARTLIST_FOREACH(digests, const char *, d,
2784 signed_descriptor_t *sd = router_get_by_descriptor_digest(d);
2785 if (sd)
2786 smartlist_add(descs_out,sd);
2788 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
2789 smartlist_free(digests);
2790 } else if (!strcmpstart(key, "/tor/server/fp/")) {
2791 smartlist_t *digests = smartlist_create();
2792 time_t cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
2793 key += strlen("/tor/server/fp/");
2794 dir_split_resource_into_fingerprints(key, digests, NULL, 1, 1);
2795 SMARTLIST_FOREACH(digests, const char *, d,
2797 if (router_digest_is_me(d)) {
2798 /* make sure desc_routerinfo exists */
2799 routerinfo_t *ri = router_get_my_routerinfo();
2800 if (ri)
2801 smartlist_add(descs_out, &(ri->cache_info));
2802 } else {
2803 routerinfo_t *ri = router_get_by_digest(d);
2804 /* Don't actually serve a descriptor that everyone will think is
2805 * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
2806 * Tors from downloading descriptors that they will throw away.
2808 if (ri && ri->cache_info.published_on > cutoff)
2809 smartlist_add(descs_out, &(ri->cache_info));
2812 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
2813 smartlist_free(digests);
2814 } else {
2815 *msg = "Key not recognized";
2816 return -1;
2819 if (!smartlist_len(descs_out)) {
2820 *msg = "Servers unavailable";
2821 return -1;
2823 return 0;
2826 /** Called when a TLS handshake has completed successfully with a
2827 * router listening at <b>address</b>:<b>or_port</b>, and has yielded
2828 * a certificate with digest <b>digest_rcvd</b>.
2830 * Also, if as_advertised is 1, then inform the reachability checker
2831 * that we could get to this guy.
2833 void
2834 dirserv_orconn_tls_done(const char *address,
2835 uint16_t or_port,
2836 const char *digest_rcvd,
2837 int as_advertised)
2839 routerlist_t *rl = router_get_routerlist();
2840 time_t now = time(NULL);
2841 int bridge_auth = authdir_mode_bridge(get_options());
2842 tor_assert(address);
2843 tor_assert(digest_rcvd);
2845 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2846 if (!strcasecmp(address, ri->address) && or_port == ri->or_port &&
2847 as_advertised &&
2848 fast_memeq(ri->cache_info.identity_digest, digest_rcvd, DIGEST_LEN)) {
2849 /* correct digest. mark this router reachable! */
2850 if (!bridge_auth || ri->purpose == ROUTER_PURPOSE_BRIDGE) {
2851 log_info(LD_DIRSERV, "Found router %s to be reachable. Yay.",
2852 ri->nickname);
2853 rep_hist_note_router_reachable(digest_rcvd, now);
2854 ri->last_reachable = now;
2858 /* FFFF Maybe we should reinstate the code that dumps routers with the same
2859 * addr/port but with nonmatching keys, but instead of dumping, we should
2860 * skip testing. */
2863 /** Auth dir server only: if <b>try_all</b> is 1, launch connections to
2864 * all known routers; else we want to load balance such that we only
2865 * try a few connections per call.
2867 * The load balancing is such that if we get called once every ten
2868 * seconds, we will cycle through all the tests in 1280 seconds (a
2869 * bit over 20 minutes).
2871 void
2872 dirserv_test_reachability(time_t now, int try_all)
2874 /* XXX decide what to do here; see or-talk thread "purging old router
2875 * information, revocation." -NM
2876 * We can't afford to mess with this in 0.1.2.x. The reason is that
2877 * if we stop doing reachability tests on some of routerlist, then
2878 * we'll for-sure think they're down, which may have unexpected
2879 * effects in other parts of the code. It doesn't hurt much to do
2880 * the testing, and directory authorities are easy to upgrade. Let's
2881 * wait til 0.2.0. -RD */
2882 // time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2883 routerlist_t *rl = router_get_routerlist();
2884 static char ctr = 0;
2885 int bridge_auth = authdir_mode_bridge(get_options());
2887 SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, router) {
2888 const char *id_digest = router->cache_info.identity_digest;
2889 tor_addr_t router_addr;
2890 if (router_is_me(router))
2891 continue;
2892 if (bridge_auth && router->purpose != ROUTER_PURPOSE_BRIDGE)
2893 continue; /* bridge authorities only test reachability on bridges */
2894 // if (router->cache_info.published_on > cutoff)
2895 // continue;
2896 if (try_all || (((uint8_t)id_digest[0]) % 128) == ctr) {
2897 log_debug(LD_OR,"Testing reachability of %s at %s:%u.",
2898 router->nickname, router->address, router->or_port);
2899 /* Remember when we started trying to determine reachability */
2900 if (!router->testing_since)
2901 router->testing_since = now;
2902 tor_addr_from_ipv4h(&router_addr, router->addr);
2903 connection_or_connect(&router_addr, router->or_port, id_digest);
2905 } SMARTLIST_FOREACH_END(router);
2906 if (!try_all) /* increment ctr */
2907 ctr = (ctr + 1) % 128;
2910 /** Given a fingerprint <b>fp</b> which is either set if we're looking
2911 * for a v2 status, or zeroes if we're looking for a v3 status, return
2912 * a pointer to the appropriate cached dir object, or NULL if there isn't
2913 * one available. */
2914 static cached_dir_t *
2915 lookup_cached_dir_by_fp(const char *fp)
2917 cached_dir_t *d = NULL;
2918 if (tor_digest_is_zero(fp) && cached_v3_networkstatus)
2919 d = cached_v3_networkstatus;
2920 else if (router_digest_is_me(fp) && the_v2_networkstatus)
2921 d = the_v2_networkstatus;
2922 else if (cached_v2_networkstatus)
2923 d = digestmap_get(cached_v2_networkstatus, fp);
2924 return d;
2927 /** Remove from <b>fps</b> every networkstatus key where both
2928 * a) we have a networkstatus document and
2929 * b) it is not newer than <b>cutoff</b>.
2931 * Return 1 if any items were present at all; else return 0.
2934 dirserv_remove_old_statuses(smartlist_t *fps, time_t cutoff)
2936 int found_any = 0;
2937 SMARTLIST_FOREACH(fps, char *, digest,
2939 cached_dir_t *d = lookup_cached_dir_by_fp(digest);
2940 if (!d)
2941 continue;
2942 found_any = 1;
2943 if (d->published <= cutoff) {
2944 tor_free(digest);
2945 SMARTLIST_DEL_CURRENT(fps, digest);
2949 return found_any;
2952 /** Return the cache-info for identity fingerprint <b>fp</b>, or
2953 * its extra-info document if <b>extrainfo</b> is true. Return
2954 * NULL if not found or if the descriptor is older than
2955 * <b>publish_cutoff</b>. */
2956 static signed_descriptor_t *
2957 get_signed_descriptor_by_fp(const char *fp, int extrainfo,
2958 time_t publish_cutoff)
2960 if (router_digest_is_me(fp)) {
2961 if (extrainfo)
2962 return &(router_get_my_extrainfo()->cache_info);
2963 else
2964 return &(router_get_my_routerinfo()->cache_info);
2965 } else {
2966 routerinfo_t *ri = router_get_by_digest(fp);
2967 if (ri &&
2968 ri->cache_info.published_on > publish_cutoff) {
2969 if (extrainfo)
2970 return extrainfo_get_by_descriptor_digest(
2971 ri->cache_info.extra_info_digest);
2972 else
2973 return &ri->cache_info;
2976 return NULL;
2979 /** Return true iff we have any of the documents (extrainfo or routerdesc)
2980 * specified by the fingerprints in <b>fps</b> and <b>spool_src</b>. Used to
2981 * decide whether to send a 404. */
2983 dirserv_have_any_serverdesc(smartlist_t *fps, int spool_src)
2985 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
2986 SMARTLIST_FOREACH(fps, const char *, fp, {
2987 switch (spool_src)
2989 case DIR_SPOOL_EXTRA_BY_DIGEST:
2990 if (extrainfo_get_by_descriptor_digest(fp)) return 1;
2991 break;
2992 case DIR_SPOOL_SERVER_BY_DIGEST:
2993 if (router_get_by_descriptor_digest(fp)) return 1;
2994 break;
2995 case DIR_SPOOL_EXTRA_BY_FP:
2996 case DIR_SPOOL_SERVER_BY_FP:
2997 if (get_signed_descriptor_by_fp(fp,
2998 spool_src == DIR_SPOOL_EXTRA_BY_FP, publish_cutoff))
2999 return 1;
3000 break;
3003 return 0;
3006 /** Return an approximate estimate of the number of bytes that will
3007 * be needed to transmit the server descriptors (if is_serverdescs --
3008 * they can be either d/ or fp/ queries) or networkstatus objects (if
3009 * !is_serverdescs) listed in <b>fps</b>. If <b>compressed</b> is set,
3010 * we guess how large the data will be after compression.
3012 * The return value is an estimate; it might be larger or smaller.
3014 size_t
3015 dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
3016 int compressed)
3018 size_t result;
3019 tor_assert(fps);
3020 if (is_serverdescs) {
3021 int n = smartlist_len(fps);
3022 routerinfo_t *me = router_get_my_routerinfo();
3023 result = (me?me->cache_info.signed_descriptor_len:2048) * n;
3024 if (compressed)
3025 result /= 2; /* observed compressibility is between 35 and 55%. */
3026 } else {
3027 result = 0;
3028 SMARTLIST_FOREACH(fps, const char *, digest, {
3029 cached_dir_t *dir = lookup_cached_dir_by_fp(digest);
3030 if (dir)
3031 result += compressed ? dir->dir_z_len : dir->dir_len;
3034 return result;
3037 /** When we're spooling data onto our outbuf, add more whenever we dip
3038 * below this threshold. */
3039 #define DIRSERV_BUFFER_MIN 16384
3041 /** Spooling helper: called when we have no more data to spool to <b>conn</b>.
3042 * Flushes any remaining data to be (un)compressed, and changes the spool
3043 * source to NONE. Returns 0 on success, negative on failure. */
3044 static int
3045 connection_dirserv_finish_spooling(dir_connection_t *conn)
3047 if (conn->zlib_state) {
3048 connection_write_to_buf_zlib("", 0, conn, 1);
3049 tor_zlib_free(conn->zlib_state);
3050 conn->zlib_state = NULL;
3052 conn->dir_spool_src = DIR_SPOOL_NONE;
3053 return 0;
3056 /** Spooling helper: called when we're sending a bunch of server descriptors,
3057 * and the outbuf has become too empty. Pulls some entries from
3058 * fingerprint_stack, and writes the corresponding servers onto outbuf. If we
3059 * run out of entries, flushes the zlib state and sets the spool source to
3060 * NONE. Returns 0 on success, negative on failure.
3062 static int
3063 connection_dirserv_add_servers_to_outbuf(dir_connection_t *conn)
3065 #ifdef TRACK_SERVED_TIME
3066 time_t now = time(NULL);
3067 #endif
3068 int by_fp = (conn->dir_spool_src == DIR_SPOOL_SERVER_BY_FP ||
3069 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP);
3070 int extra = (conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP ||
3071 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_DIGEST);
3072 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
3074 while (smartlist_len(conn->fingerprint_stack) &&
3075 buf_datalen(conn->_base.outbuf) < DIRSERV_BUFFER_MIN) {
3076 const char *body;
3077 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3078 signed_descriptor_t *sd = NULL;
3079 if (by_fp) {
3080 sd = get_signed_descriptor_by_fp(fp, extra, publish_cutoff);
3081 } else {
3082 sd = extra ? extrainfo_get_by_descriptor_digest(fp)
3083 : router_get_by_descriptor_digest(fp);
3085 tor_free(fp);
3086 if (!sd)
3087 continue;
3088 if (!connection_dir_is_encrypted(conn) && !sd->send_unencrypted) {
3089 /* we did this check once before (so we could have an accurate size
3090 * estimate and maybe send a 404 if somebody asked for only bridges on a
3091 * connection), but we need to do it again in case a previously
3092 * unknown bridge descriptor has shown up between then and now. */
3093 continue;
3095 #ifdef TRACK_SERVED_TIME
3096 sd->last_served_at = now;
3097 #endif
3098 body = signed_descriptor_get_body(sd);
3099 if (conn->zlib_state) {
3100 int last = ! smartlist_len(conn->fingerprint_stack);
3101 connection_write_to_buf_zlib(body, sd->signed_descriptor_len, conn,
3102 last);
3103 if (last) {
3104 tor_zlib_free(conn->zlib_state);
3105 conn->zlib_state = NULL;
3107 } else {
3108 connection_write_to_buf(body,
3109 sd->signed_descriptor_len,
3110 TO_CONN(conn));
3114 if (!smartlist_len(conn->fingerprint_stack)) {
3115 /* We just wrote the last one; finish up. */
3116 conn->dir_spool_src = DIR_SPOOL_NONE;
3117 smartlist_free(conn->fingerprint_stack);
3118 conn->fingerprint_stack = NULL;
3120 return 0;
3123 /** Spooling helper: Called when we're sending a directory or networkstatus,
3124 * and the outbuf has become too empty. Pulls some bytes from
3125 * <b>conn</b>-\>cached_dir-\>dir_z, uncompresses them if appropriate, and
3126 * puts them on the outbuf. If we run out of entries, flushes the zlib state
3127 * and sets the spool source to NONE. Returns 0 on success, negative on
3128 * failure. */
3129 static int
3130 connection_dirserv_add_dir_bytes_to_outbuf(dir_connection_t *conn)
3132 ssize_t bytes;
3133 int64_t remaining;
3135 bytes = DIRSERV_BUFFER_MIN - buf_datalen(conn->_base.outbuf);
3136 tor_assert(bytes > 0);
3137 tor_assert(conn->cached_dir);
3138 if (bytes < 8192)
3139 bytes = 8192;
3140 remaining = conn->cached_dir->dir_z_len - conn->cached_dir_offset;
3141 if (bytes > remaining)
3142 bytes = (ssize_t) remaining;
3144 if (conn->zlib_state) {
3145 connection_write_to_buf_zlib(
3146 conn->cached_dir->dir_z + conn->cached_dir_offset,
3147 bytes, conn, bytes == remaining);
3148 } else {
3149 connection_write_to_buf(conn->cached_dir->dir_z + conn->cached_dir_offset,
3150 bytes, TO_CONN(conn));
3152 conn->cached_dir_offset += bytes;
3153 if (conn->cached_dir_offset == (int)conn->cached_dir->dir_z_len) {
3154 /* We just wrote the last one; finish up. */
3155 connection_dirserv_finish_spooling(conn);
3156 cached_dir_decref(conn->cached_dir);
3157 conn->cached_dir = NULL;
3159 return 0;
3162 /** Spooling helper: Called when we're spooling networkstatus objects on
3163 * <b>conn</b>, and the outbuf has become too empty. If the current
3164 * networkstatus object (in <b>conn</b>-\>cached_dir) has more data, pull data
3165 * from there. Otherwise, pop the next fingerprint from fingerprint_stack,
3166 * and start spooling the next networkstatus. (A digest of all 0 bytes is
3167 * treated as a request for the current consensus.) If we run out of entries,
3168 * flushes the zlib state and sets the spool source to NONE. Returns 0 on
3169 * success, negative on failure. */
3170 static int
3171 connection_dirserv_add_networkstatus_bytes_to_outbuf(dir_connection_t *conn)
3174 while (buf_datalen(conn->_base.outbuf) < DIRSERV_BUFFER_MIN) {
3175 if (conn->cached_dir) {
3176 int uncompressing = (conn->zlib_state != NULL);
3177 int r = connection_dirserv_add_dir_bytes_to_outbuf(conn);
3178 if (conn->dir_spool_src == DIR_SPOOL_NONE) {
3179 /* add_dir_bytes thinks we're done with the cached_dir. But we
3180 * may have more cached_dirs! */
3181 conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
3182 /* This bit is tricky. If we were uncompressing the last
3183 * networkstatus, we may need to make a new zlib object to
3184 * uncompress the next one. */
3185 if (uncompressing && ! conn->zlib_state &&
3186 conn->fingerprint_stack &&
3187 smartlist_len(conn->fingerprint_stack)) {
3188 conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
3191 if (r) return r;
3192 } else if (conn->fingerprint_stack &&
3193 smartlist_len(conn->fingerprint_stack)) {
3194 /* Add another networkstatus; start serving it. */
3195 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3196 cached_dir_t *d = lookup_cached_dir_by_fp(fp);
3197 tor_free(fp);
3198 if (d) {
3199 ++d->refcnt;
3200 conn->cached_dir = d;
3201 conn->cached_dir_offset = 0;
3203 } else {
3204 connection_dirserv_finish_spooling(conn);
3205 if (conn->fingerprint_stack)
3206 smartlist_free(conn->fingerprint_stack);
3207 conn->fingerprint_stack = NULL;
3208 return 0;
3211 return 0;
3214 /** Called whenever we have flushed some directory data in state
3215 * SERVER_WRITING. */
3217 connection_dirserv_flushed_some(dir_connection_t *conn)
3219 tor_assert(conn->_base.state == DIR_CONN_STATE_SERVER_WRITING);
3221 if (buf_datalen(conn->_base.outbuf) >= DIRSERV_BUFFER_MIN)
3222 return 0;
3224 switch (conn->dir_spool_src) {
3225 case DIR_SPOOL_EXTRA_BY_DIGEST:
3226 case DIR_SPOOL_EXTRA_BY_FP:
3227 case DIR_SPOOL_SERVER_BY_DIGEST:
3228 case DIR_SPOOL_SERVER_BY_FP:
3229 return connection_dirserv_add_servers_to_outbuf(conn);
3230 case DIR_SPOOL_CACHED_DIR:
3231 return connection_dirserv_add_dir_bytes_to_outbuf(conn);
3232 case DIR_SPOOL_NETWORKSTATUS:
3233 return connection_dirserv_add_networkstatus_bytes_to_outbuf(conn);
3234 case DIR_SPOOL_NONE:
3235 default:
3236 return 0;
3240 /** Release all storage used by the directory server. */
3241 void
3242 dirserv_free_all(void)
3244 dirserv_free_fingerprint_list();
3246 cached_dir_decref(the_directory);
3247 clear_cached_dir(&the_runningrouters);
3248 cached_dir_decref(the_v2_networkstatus);
3249 cached_dir_decref(cached_directory);
3250 clear_cached_dir(&cached_runningrouters);
3251 if (cached_v2_networkstatus) {
3252 digestmap_free(cached_v2_networkstatus, _free_cached_dir);
3253 cached_v2_networkstatus = NULL;
3255 cached_dir_decref(cached_v3_networkstatus);