Issues with router_get_by_nickname() (3)
[tor/rransom.git] / src / or / dirserv.c
blob851fc5cbdd062f18576b6458beeaff9bb7e04be1
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2010, 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, get_identity_key())) {
1524 log_warn(LD_BUG, "Error creating directory.");
1525 tor_free(new_directory);
1526 return NULL;
1528 cached_dir_decref(the_directory);
1529 the_directory = new_cached_dir(new_directory, time(NULL));
1530 log_info(LD_DIRSERV,"New directory (size %d) has been built.",
1531 (int)the_directory->dir_len);
1532 log_debug(LD_DIRSERV,"New directory (size %d):\n%s",
1533 (int)the_directory->dir_len, the_directory->dir);
1535 the_directory_is_dirty = 0;
1537 /* Save the directory to disk so we re-load it quickly on startup.
1539 dirserv_set_cached_directory(the_directory->dir, time(NULL), 0);
1541 return the_directory;
1544 /** Only called by v1 auth dirservers.
1545 * Replace the current running-routers list with a newly generated one. */
1546 static cached_dir_t *
1547 generate_runningrouters(void)
1549 char *s=NULL;
1550 char digest[DIGEST_LEN];
1551 char published[ISO_TIME_LEN+1];
1552 size_t len;
1553 crypto_pk_env_t *private_key = get_identity_key();
1554 char *identity_pkey; /* Identity key, DER64-encoded. */
1555 size_t identity_pkey_len;
1557 if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
1558 &identity_pkey_len)<0) {
1559 log_warn(LD_BUG,"write identity_pkey to string failed!");
1560 goto err;
1562 format_iso_time(published, time(NULL));
1564 len = 2048;
1565 s = tor_malloc_zero(len);
1566 tor_snprintf(s, len,
1567 "network-status\n"
1568 "published %s\n"
1569 "router-status %s\n"
1570 "dir-signing-key\n%s"
1571 "directory-signature %s\n",
1572 published, "", identity_pkey,
1573 get_options()->Nickname);
1574 tor_free(identity_pkey);
1575 if (router_get_runningrouters_hash(s,digest)) {
1576 log_warn(LD_BUG,"couldn't compute digest");
1577 goto err;
1579 note_crypto_pk_op(SIGN_DIR);
1580 if (router_append_dirobj_signature(s, len, digest, private_key)<0)
1581 goto err;
1583 set_cached_dir(&the_runningrouters, s, time(NULL));
1584 runningrouters_is_dirty = 0;
1586 return &the_runningrouters;
1587 err:
1588 tor_free(s);
1589 return NULL;
1592 /** Set *<b>rr</b> to the most recently generated encoded signed
1593 * running-routers list, generating a new one as necessary. Return the
1594 * size of the directory on success, and 0 on failure. */
1595 cached_dir_t *
1596 dirserv_get_runningrouters(void)
1598 return dirserv_pick_cached_dir_obj(
1599 &cached_runningrouters, &the_runningrouters,
1600 runningrouters_is_dirty,
1601 generate_runningrouters,
1602 "v1 network status list", V1_AUTHORITY);
1605 /** Return the latest downloaded consensus networkstatus in encoded, signed,
1606 * optionally compressed format, suitable for sending to clients. */
1607 cached_dir_t *
1608 dirserv_get_consensus(void)
1610 return cached_v3_networkstatus;
1613 /** For authoritative directories: the current (v2) network status. */
1614 static cached_dir_t *the_v2_networkstatus = NULL;
1616 /** Return true iff our opinion of the routers has been stale for long
1617 * enough that we should generate a new v2 network status doc. */
1618 static int
1619 should_generate_v2_networkstatus(void)
1621 return authdir_mode_v2(get_options()) &&
1622 the_v2_networkstatus_is_dirty &&
1623 the_v2_networkstatus_is_dirty + DIR_REGEN_SLACK_TIME < time(NULL);
1626 /** If a router's uptime is at least this value, then it is always
1627 * considered stable, regardless of the rest of the network. This
1628 * way we resist attacks where an attacker doubles the size of the
1629 * network using allegedly high-uptime nodes, displacing all the
1630 * current guards. */
1631 #define UPTIME_TO_GUARANTEE_STABLE (3600*24*30)
1632 /** If a router's MTBF is at least this value, then it is always stable.
1633 * See above. (Corresponds to about 7 days for current decay rates.) */
1634 #define MTBF_TO_GUARANTEE_STABLE (60*60*24*5)
1635 /** Similarly, we protect sufficiently fast nodes from being pushed
1636 * out of the set of Fast nodes. */
1637 #define BANDWIDTH_TO_GUARANTEE_FAST ROUTER_REQUIRED_MIN_BANDWIDTH
1638 /** Similarly, every node with sufficient bandwidth can be considered
1639 * for Guard status. */
1640 #define BANDWIDTH_TO_GUARANTEE_GUARD (250*1024)
1641 /** Similarly, every node with at least this much weighted time known can be
1642 * considered familiar enough to be a guard. Corresponds to about 20 days for
1643 * current decay rates.
1645 #define TIME_KNOWN_TO_GUARANTEE_FAMILIAR (8*24*60*60)
1646 /** Similarly, every node with sufficient WFU is around enough to be a guard.
1648 #define WFU_TO_GUARANTEE_GUARD (0.995)
1650 /* Thresholds for server performance: set by
1651 * dirserv_compute_performance_thresholds, and used by
1652 * generate_v2_networkstatus */
1654 /** Any router with an uptime of at least this value is stable. */
1655 static uint32_t stable_uptime = 0; /* start at a safe value */
1656 /** Any router with an mtbf of at least this value is stable. */
1657 static double stable_mtbf = 0.0;
1658 /** If true, we have measured enough mtbf info to look at stable_mtbf rather
1659 * than stable_uptime. */
1660 static int enough_mtbf_info = 0;
1661 /** Any router with a weighted fractional uptime of at least this much might
1662 * be good as a guard. */
1663 static double guard_wfu = 0.0;
1664 /** Don't call a router a guard unless we've known about it for at least this
1665 * many seconds. */
1666 static long guard_tk = 0;
1667 /** Any router with a bandwidth at least this high is "Fast" */
1668 static uint32_t fast_bandwidth = 0;
1669 /** If exits can be guards, then all guards must have a bandwidth this
1670 * high. */
1671 static uint32_t guard_bandwidth_including_exits = 0;
1672 /** If exits can't be guards, then all guards must have a bandwidth this
1673 * high. */
1674 static uint32_t guard_bandwidth_excluding_exits = 0;
1675 /** Total bandwidth of all the routers we're considering. */
1676 static uint64_t total_bandwidth = 0;
1677 /** Total bandwidth of all the exit routers we're considering. */
1678 static uint64_t total_exit_bandwidth = 0;
1680 /** Helper: estimate the uptime of a router given its stated uptime and the
1681 * amount of time since it last stated its stated uptime. */
1682 static INLINE long
1683 real_uptime(routerinfo_t *router, time_t now)
1685 if (now < router->cache_info.published_on)
1686 return router->uptime;
1687 else
1688 return router->uptime + (now - router->cache_info.published_on);
1691 /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
1692 * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
1693 * If <b>need_capacity</b> is non-zero, we require a minimum advertised
1694 * bandwidth.
1696 static int
1697 dirserv_thinks_router_is_unreliable(time_t now,
1698 routerinfo_t *router,
1699 int need_uptime, int need_capacity)
1701 if (need_uptime) {
1702 if (!enough_mtbf_info) {
1703 /* XXX022 Once most authorities are on v3, we should change the rule from
1704 * "use uptime if we don't have mtbf data" to "don't advertise Stable on
1705 * v3 if we don't have enough mtbf data." */
1706 long uptime = real_uptime(router, now);
1707 if ((unsigned)uptime < stable_uptime &&
1708 (unsigned)uptime < UPTIME_TO_GUARANTEE_STABLE)
1709 return 1;
1710 } else {
1711 double mtbf =
1712 rep_hist_get_stability(router->cache_info.identity_digest, now);
1713 if (mtbf < stable_mtbf &&
1714 mtbf < MTBF_TO_GUARANTEE_STABLE)
1715 return 1;
1718 if (need_capacity) {
1719 uint32_t bw = router_get_advertised_bandwidth(router);
1720 if (bw < fast_bandwidth)
1721 return 1;
1723 return 0;
1726 /** Return true iff <b>router</b> should be assigned the "HSDir" flag.
1727 * Right now this means it advertises support for it, it has a high
1728 * uptime, and it's currently considered Running.
1730 * This function needs to be called after router-\>is_running has
1731 * been set.
1733 static int
1734 dirserv_thinks_router_is_hs_dir(routerinfo_t *router, time_t now)
1736 long uptime = real_uptime(router, now);
1738 return (router->wants_to_be_hs_dir &&
1739 uptime > get_options()->MinUptimeHidServDirectoryV2 &&
1740 router->is_running);
1743 /** Look through the routerlist, the Mean Time Between Failure history, and
1744 * the Weighted Fractional Uptime history, and use them to set thresholds for
1745 * the Stable, Fast, and Guard flags. Update the fields stable_uptime,
1746 * stable_mtbf, enough_mtbf_info, guard_wfu, guard_tk, fast_bandwidth,
1747 * guard_bandwidh_including_exits, guard_bandwidth_excluding_exits,
1748 * total_bandwidth, and total_exit_bandwidth.
1750 * Also, set the is_exit flag of each router appropriately. */
1751 static void
1752 dirserv_compute_performance_thresholds(routerlist_t *rl)
1754 int n_active, n_active_nonexit, n_familiar;
1755 uint32_t *uptimes, *bandwidths, *bandwidths_excluding_exits;
1756 long *tks;
1757 double *mtbfs, *wfus;
1758 time_t now = time(NULL);
1760 /* initialize these all here, in case there are no routers */
1761 stable_uptime = 0;
1762 stable_mtbf = 0;
1763 fast_bandwidth = 0;
1764 guard_bandwidth_including_exits = 0;
1765 guard_bandwidth_excluding_exits = 0;
1766 guard_tk = 0;
1767 guard_wfu = 0;
1768 total_bandwidth = 0;
1769 total_exit_bandwidth = 0;
1771 /* Initialize arrays that will hold values for each router. We'll
1772 * sort them and use that to compute thresholds. */
1773 n_active = n_active_nonexit = 0;
1774 /* Uptime for every active router. */
1775 uptimes = tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
1776 /* Bandwidth for every active router. */
1777 bandwidths = tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
1778 /* Bandwidth for every active non-exit router. */
1779 bandwidths_excluding_exits =
1780 tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
1781 /* Weighted mean time between failure for each active router. */
1782 mtbfs = tor_malloc(sizeof(double)*smartlist_len(rl->routers));
1783 /* Time-known for each active router. */
1784 tks = tor_malloc(sizeof(long)*smartlist_len(rl->routers));
1785 /* Weighted fractional uptime for each active router. */
1786 wfus = tor_malloc(sizeof(double)*smartlist_len(rl->routers));
1788 /* Now, fill in the arrays. */
1789 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
1790 if (router_is_active(ri, now)) {
1791 const char *id = ri->cache_info.identity_digest;
1792 uint32_t bw;
1793 ri->is_exit = exit_policy_is_general_exit(ri->exit_policy);
1794 uptimes[n_active] = (uint32_t)real_uptime(ri, now);
1795 mtbfs[n_active] = rep_hist_get_stability(id, now);
1796 tks [n_active] = rep_hist_get_weighted_time_known(id, now);
1797 bandwidths[n_active] = bw = router_get_advertised_bandwidth(ri);
1798 total_bandwidth += bw;
1799 if (ri->is_exit && !ri->is_bad_exit) {
1800 total_exit_bandwidth += bw;
1801 } else {
1802 bandwidths_excluding_exits[n_active_nonexit] = bw;
1803 ++n_active_nonexit;
1805 ++n_active;
1809 /* Now, compute thresholds. */
1810 if (n_active) {
1811 /* The median uptime is stable. */
1812 stable_uptime = median_uint32(uptimes, n_active);
1813 /* The median mtbf is stable, if we have enough mtbf info */
1814 stable_mtbf = median_double(mtbfs, n_active);
1815 /* The 12.5th percentile bandwidth is fast. */
1816 fast_bandwidth = find_nth_uint32(bandwidths, n_active, n_active/8);
1817 /* (Now bandwidths is sorted.) */
1818 if (fast_bandwidth < ROUTER_REQUIRED_MIN_BANDWIDTH/2)
1819 fast_bandwidth = bandwidths[n_active/4];
1820 guard_bandwidth_including_exits = bandwidths[(n_active-1)/2];
1821 guard_tk = find_nth_long(tks, n_active, n_active/8);
1824 if (guard_tk > TIME_KNOWN_TO_GUARANTEE_FAMILIAR)
1825 guard_tk = TIME_KNOWN_TO_GUARANTEE_FAMILIAR;
1827 if (fast_bandwidth > BANDWIDTH_TO_GUARANTEE_FAST)
1828 fast_bandwidth = BANDWIDTH_TO_GUARANTEE_FAST;
1830 /* Now that we have a time-known that 7/8 routers are known longer than,
1831 * fill wfus with the wfu of every such "familiar" router. */
1832 n_familiar = 0;
1833 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
1834 if (router_is_active(ri, now)) {
1835 const char *id = ri->cache_info.identity_digest;
1836 long tk = rep_hist_get_weighted_time_known(id, now);
1837 if (tk < guard_tk)
1838 continue;
1839 wfus[n_familiar++] = rep_hist_get_weighted_fractional_uptime(id, now);
1842 if (n_familiar)
1843 guard_wfu = median_double(wfus, n_familiar);
1844 if (guard_wfu > WFU_TO_GUARANTEE_GUARD)
1845 guard_wfu = WFU_TO_GUARANTEE_GUARD;
1847 enough_mtbf_info = rep_hist_have_measured_enough_stability();
1849 if (n_active_nonexit) {
1850 guard_bandwidth_excluding_exits =
1851 median_uint32(bandwidths_excluding_exits, n_active_nonexit);
1854 log(LOG_INFO, LD_DIRSERV,
1855 "Cutoffs: For Stable, %lu sec uptime, %lu sec MTBF. "
1856 "For Fast: %lu bytes/sec. "
1857 "For Guard: WFU %.03lf%%, time-known %lu sec, "
1858 "and bandwidth %lu or %lu bytes/sec. We%s have enough stability data.",
1859 (unsigned long)stable_uptime,
1860 (unsigned long)stable_mtbf,
1861 (unsigned long)fast_bandwidth,
1862 guard_wfu*100,
1863 (unsigned long)guard_tk,
1864 (unsigned long)guard_bandwidth_including_exits,
1865 (unsigned long)guard_bandwidth_excluding_exits,
1866 enough_mtbf_info ? "" : " don't ");
1868 tor_free(uptimes);
1869 tor_free(mtbfs);
1870 tor_free(bandwidths);
1871 tor_free(bandwidths_excluding_exits);
1872 tor_free(tks);
1873 tor_free(wfus);
1876 /** Given a platform string as in a routerinfo_t (possibly null), return a
1877 * newly allocated version string for a networkstatus document, or NULL if the
1878 * platform doesn't give a Tor version. */
1879 static char *
1880 version_from_platform(const char *platform)
1882 if (platform && !strcmpstart(platform, "Tor ")) {
1883 const char *eos = find_whitespace(platform+4);
1884 if (eos && !strcmpstart(eos, " (r")) {
1885 /* XXXX Unify this logic with the other version extraction
1886 * logic in routerparse.c. */
1887 eos = find_whitespace(eos+1);
1889 if (eos) {
1890 return tor_strndup(platform, eos-platform);
1893 return NULL;
1896 /** Helper: write the router-status information in <b>rs</b> into <b>buf</b>,
1897 * which has at least <b>buf_len</b> free characters. Do NUL-termination.
1898 * Use the same format as in network-status documents. If <b>version</b> is
1899 * non-NULL, add a "v" line for the platform. Return 0 on success, -1 on
1900 * failure. If <b>first_line_only</b> is true, don't include any flags
1901 * or version line.
1904 routerstatus_format_entry(char *buf, size_t buf_len,
1905 routerstatus_t *rs, const char *version,
1906 int first_line_only, int v2_format)
1907 /* XXX: first_line_only and v2_format should probably be be both
1908 * replaced by a single purpose parameter.
1911 int r;
1912 struct in_addr in;
1913 char *cp;
1914 char *summary;
1916 char published[ISO_TIME_LEN+1];
1917 char ipaddr[INET_NTOA_BUF_LEN];
1918 char identity64[BASE64_DIGEST_LEN+1];
1919 char digest64[BASE64_DIGEST_LEN+1];
1921 format_iso_time(published, rs->published_on);
1922 digest_to_base64(identity64, rs->identity_digest);
1923 digest_to_base64(digest64, rs->descriptor_digest);
1924 in.s_addr = htonl(rs->addr);
1925 tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
1927 r = tor_snprintf(buf, buf_len,
1928 "r %s %s %s %s %s %d %d\n",
1929 rs->nickname,
1930 identity64,
1931 digest64,
1932 published,
1933 ipaddr,
1934 (int)rs->or_port,
1935 (int)rs->dir_port);
1936 if (r<0) {
1937 log_warn(LD_BUG, "Not enough space in buffer.");
1938 return -1;
1940 if (first_line_only)
1941 return 0;
1943 cp = buf + strlen(buf);
1944 /* NOTE: Whenever this list expands, be sure to increase MAX_FLAG_LINE_LEN*/
1945 r = tor_snprintf(cp, buf_len - (cp-buf),
1946 "s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
1947 /* These must stay in alphabetical order. */
1948 rs->is_authority?" Authority":"",
1949 rs->is_bad_directory?" BadDirectory":"",
1950 rs->is_bad_exit?" BadExit":"",
1951 rs->is_exit?" Exit":"",
1952 rs->is_fast?" Fast":"",
1953 rs->is_possible_guard?" Guard":"",
1954 rs->is_hs_dir?" HSDir":"",
1955 rs->is_named?" Named":"",
1956 rs->is_running?" Running":"",
1957 rs->is_stable?" Stable":"",
1958 rs->is_unnamed?" Unnamed":"",
1959 rs->is_v2_dir?" V2Dir":"",
1960 rs->is_valid?" Valid":"");
1961 if (r<0) {
1962 log_warn(LD_BUG, "Not enough space in buffer.");
1963 return -1;
1965 cp += strlen(cp);
1967 /* length of "opt v \n" */
1968 #define V_LINE_OVERHEAD 7
1969 if (version && strlen(version) < MAX_V_LINE_LEN - V_LINE_OVERHEAD) {
1970 if (tor_snprintf(cp, buf_len - (cp-buf), "opt v %s\n", version)<0) {
1971 log_warn(LD_BUG, "Unable to print router version.");
1972 return -1;
1974 cp += strlen(cp);
1977 if (!v2_format) {
1978 routerinfo_t* desc = router_get_by_digest(rs->identity_digest);
1980 /* Blow up more or less nicely if we didn't get anything or not the
1981 * thing we expected.
1983 if (!desc) {
1984 char id[HEX_DIGEST_LEN+1];
1985 char dd[HEX_DIGEST_LEN+1];
1987 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
1988 base16_encode(dd, sizeof(dd), rs->descriptor_digest, DIGEST_LEN);
1989 log_warn(LD_BUG, "Cannot get any descriptor for %s "
1990 "(wanted descriptor %s).",
1991 id, dd);
1992 return -1;
1994 if (memcmp(desc->cache_info.signed_descriptor_digest,
1995 rs->descriptor_digest,
1996 DIGEST_LEN)) {
1997 char rl_d[HEX_DIGEST_LEN+1];
1998 char rs_d[HEX_DIGEST_LEN+1];
1999 char id[HEX_DIGEST_LEN+1];
2001 base16_encode(rl_d, sizeof(rl_d),
2002 desc->cache_info.signed_descriptor_digest, DIGEST_LEN);
2003 base16_encode(rs_d, sizeof(rs_d), rs->descriptor_digest, DIGEST_LEN);
2004 base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
2005 log_err(LD_BUG, "descriptor digest in routerlist does not match "
2006 "the one in routerstatus: %s vs %s "
2007 "(router %s)\n",
2008 rl_d, rs_d, id);
2010 tor_assert(!memcmp(desc->cache_info.signed_descriptor_digest,
2011 rs->descriptor_digest,
2012 DIGEST_LEN));
2015 r = tor_snprintf(cp, buf_len - (cp-buf),
2016 "w Bandwidth=%d\n",
2017 router_get_advertised_bandwidth_capped(desc) / 1024);
2018 if (r<0) {
2019 log_warn(LD_BUG, "Not enough space in buffer.");
2020 return -1;
2022 cp += strlen(cp);
2024 summary = policy_summarize(desc->exit_policy);
2025 r = tor_snprintf(cp, buf_len - (cp-buf), "p %s\n", summary);
2026 if (r<0) {
2027 log_warn(LD_BUG, "Not enough space in buffer.");
2028 tor_free(summary);
2029 return -1;
2031 cp += strlen(cp);
2032 tor_free(summary);
2035 return 0;
2038 /** Helper for sorting: compares two routerinfos first by address, and then by
2039 * descending order of "usefulness". (An authority is more useful than a
2040 * non-authority; a running router is more useful than a non-running router;
2041 * and a router with more bandwidth is more useful than one with less.)
2043 static int
2044 _compare_routerinfo_by_ip_and_bw(const void **a, const void **b)
2046 routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
2047 int first_is_auth, second_is_auth;
2048 uint32_t bw_first, bw_second;
2050 /* we return -1 if first should appear before second... that is,
2051 * if first is a better router. */
2052 if (first->addr < second->addr)
2053 return -1;
2054 else if (first->addr > second->addr)
2055 return 1;
2057 /* Potentially, this next bit could cause k n lg n memcmp calls. But in
2058 * reality, we will almost never get here, since addresses will usually be
2059 * different. */
2061 first_is_auth =
2062 router_digest_is_trusted_dir(first->cache_info.identity_digest);
2063 second_is_auth =
2064 router_digest_is_trusted_dir(second->cache_info.identity_digest);
2066 if (first_is_auth && !second_is_auth)
2067 return -1;
2068 else if (!first_is_auth && second_is_auth)
2069 return 1;
2071 else if (first->is_running && !second->is_running)
2072 return -1;
2073 else if (!first->is_running && second->is_running)
2074 return 1;
2076 bw_first = router_get_advertised_bandwidth(first);
2077 bw_second = router_get_advertised_bandwidth(second);
2079 if (bw_first > bw_second)
2080 return -1;
2081 else if (bw_first < bw_second)
2082 return 1;
2084 /* They're equal! Compare by identity digest, so there's a
2085 * deterministic order and we avoid flapping. */
2086 return memcmp(first->cache_info.identity_digest,
2087 second->cache_info.identity_digest,
2088 DIGEST_LEN);
2091 /** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
2092 * whose keys are the identity digests of those routers that we're going to
2093 * exclude for Sybil-like appearance. */
2094 static digestmap_t *
2095 get_possible_sybil_list(const smartlist_t *routers)
2097 or_options_t *options = get_options();
2098 digestmap_t *omit_as_sybil;
2099 smartlist_t *routers_by_ip = smartlist_create();
2100 uint32_t last_addr;
2101 int addr_count;
2102 /* Allow at most this number of Tor servers on a single IP address, ... */
2103 int max_with_same_addr = options->AuthDirMaxServersPerAddr;
2104 /* ... unless it's a directory authority, in which case allow more. */
2105 int max_with_same_addr_on_authority = options->AuthDirMaxServersPerAuthAddr;
2106 if (max_with_same_addr <= 0)
2107 max_with_same_addr = INT_MAX;
2108 if (max_with_same_addr_on_authority <= 0)
2109 max_with_same_addr_on_authority = INT_MAX;
2111 smartlist_add_all(routers_by_ip, routers);
2112 smartlist_sort(routers_by_ip, _compare_routerinfo_by_ip_and_bw);
2113 omit_as_sybil = digestmap_new();
2115 last_addr = 0;
2116 addr_count = 0;
2117 SMARTLIST_FOREACH(routers_by_ip, routerinfo_t *, ri,
2119 if (last_addr != ri->addr) {
2120 last_addr = ri->addr;
2121 addr_count = 1;
2122 } else if (++addr_count > max_with_same_addr) {
2123 if (!router_addr_is_trusted_dir(ri->addr) ||
2124 addr_count > max_with_same_addr_on_authority)
2125 digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
2129 smartlist_free(routers_by_ip);
2130 return omit_as_sybil;
2133 /** Extract status information from <b>ri</b> and from other authority
2134 * functions and store it in <b>rs</b>>. If <b>naming</b>, consider setting
2135 * the named flag in <b>rs</b>. If not <b>exits_can_be_guards</b>, never mark
2136 * an exit as a guard. If <b>listbadexits</b>, consider setting the badexit
2137 * flag.
2139 * We assume that ri-\>is_running has already been set, e.g. by
2140 * dirserv_set_router_is_running(ri, now);
2142 void
2143 set_routerstatus_from_routerinfo(routerstatus_t *rs,
2144 routerinfo_t *ri, time_t now,
2145 int naming, int exits_can_be_guards,
2146 int listbadexits, int listbaddirs)
2148 int unstable_version =
2149 !tor_version_as_new_as(ri->platform,"0.1.1.16-rc-cvs");
2150 memset(rs, 0, sizeof(routerstatus_t));
2152 rs->is_authority =
2153 router_digest_is_trusted_dir(ri->cache_info.identity_digest);
2155 /* Already set by compute_performance_thresholds. */
2156 rs->is_exit = ri->is_exit;
2157 rs->is_stable = ri->is_stable =
2158 router_is_active(ri, now) &&
2159 !dirserv_thinks_router_is_unreliable(now, ri, 1, 0) &&
2160 !unstable_version;
2161 rs->is_fast = ri->is_fast =
2162 router_is_active(ri, now) &&
2163 !dirserv_thinks_router_is_unreliable(now, ri, 0, 1);
2164 rs->is_running = ri->is_running; /* computed above */
2166 if (naming) {
2167 uint32_t name_status = dirserv_get_name_status(
2168 ri->cache_info.identity_digest, ri->nickname);
2169 rs->is_named = (naming && (name_status & FP_NAMED)) ? 1 : 0;
2170 rs->is_unnamed = (naming && (name_status & FP_UNNAMED)) ? 1 : 0;
2172 rs->is_valid = ri->is_valid;
2174 if (rs->is_fast &&
2175 (!rs->is_exit || exits_can_be_guards) &&
2176 (router_get_advertised_bandwidth(ri) >= BANDWIDTH_TO_GUARANTEE_GUARD ||
2177 router_get_advertised_bandwidth(ri) >=
2178 (exits_can_be_guards ? guard_bandwidth_including_exits :
2179 guard_bandwidth_excluding_exits))) {
2180 long tk = rep_hist_get_weighted_time_known(
2181 ri->cache_info.identity_digest, now);
2182 double wfu = rep_hist_get_weighted_fractional_uptime(
2183 ri->cache_info.identity_digest, now);
2184 rs->is_possible_guard = (wfu >= guard_wfu && tk >= guard_tk) ? 1 : 0;
2185 } else {
2186 rs->is_possible_guard = 0;
2188 rs->is_bad_directory = listbaddirs && ri->is_bad_directory;
2189 rs->is_bad_exit = listbadexits && ri->is_bad_exit;
2190 ri->is_hs_dir = dirserv_thinks_router_is_hs_dir(ri, now);
2191 rs->is_hs_dir = ri->is_hs_dir;
2192 rs->is_v2_dir = ri->dir_port != 0;
2194 if (!strcasecmp(ri->nickname, UNNAMED_ROUTER_NICKNAME))
2195 rs->is_named = rs->is_unnamed = 0;
2197 rs->published_on = ri->cache_info.published_on;
2198 memcpy(rs->identity_digest, ri->cache_info.identity_digest, DIGEST_LEN);
2199 memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest,
2200 DIGEST_LEN);
2201 rs->addr = ri->addr;
2202 strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname));
2203 rs->or_port = ri->or_port;
2204 rs->dir_port = ri->dir_port;
2207 /** Routerstatus <b>rs</b> is part of a group of routers that are on
2208 * too narrow an IP-space. Clear out its flags: we don't want people
2209 * using it.
2211 static void
2212 clear_status_flags_on_sybil(routerstatus_t *rs)
2214 rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
2215 rs->is_running = rs->is_named = rs->is_valid = rs->is_v2_dir =
2216 rs->is_hs_dir = rs->is_possible_guard = rs->is_bad_exit =
2217 rs->is_bad_directory = 0;
2218 /* FFFF we might want some mechanism to check later on if we
2219 * missed zeroing any flags: it's easy to add a new flag but
2220 * forget to add it to this clause. */
2223 /** Clear all the status flags in routerinfo <b>router</b>. We put this
2224 * function here because it's eerily similar to
2225 * clear_status_flags_on_sybil() above. One day we should merge them. */
2226 void
2227 router_clear_status_flags(routerinfo_t *router)
2229 router->is_valid = router->is_running = router->is_hs_dir =
2230 router->is_fast = router->is_stable =
2231 router->is_possible_guard = router->is_exit =
2232 router->is_bad_exit = router->is_bad_directory = 0;
2235 /** Return a new networkstatus_t* containing our current opinion. (For v3
2236 * authorities) */
2237 networkstatus_t *
2238 dirserv_generate_networkstatus_vote_obj(crypto_pk_env_t *private_key,
2239 authority_cert_t *cert)
2241 or_options_t *options = get_options();
2242 networkstatus_t *v3_out = NULL;
2243 uint32_t addr;
2244 char *hostname = NULL, *client_versions = NULL, *server_versions = NULL;
2245 const char *contact;
2246 smartlist_t *routers, *routerstatuses;
2247 char identity_digest[DIGEST_LEN];
2248 char signing_key_digest[DIGEST_LEN];
2249 int naming = options->NamingAuthoritativeDir;
2250 int listbadexits = options->AuthDirListBadExits;
2251 int listbaddirs = options->AuthDirListBadDirs;
2252 int exits_can_be_guards;
2253 routerlist_t *rl = router_get_routerlist();
2254 time_t now = time(NULL);
2255 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2256 networkstatus_voter_info_t *voter = NULL;
2257 vote_timing_t timing;
2258 digestmap_t *omit_as_sybil = NULL;
2259 int vote_on_reachability = 1;
2261 tor_assert(private_key);
2262 tor_assert(cert);
2264 if (now - time_of_process_start <
2265 options->TestingAuthDirTimeToLearnReachability)
2266 vote_on_reachability = 0;
2268 if (resolve_my_address(LOG_WARN, options, &addr, &hostname)<0) {
2269 log_warn(LD_NET, "Couldn't resolve my hostname");
2270 return NULL;
2272 if (!strchr(hostname, '.')) {
2273 tor_free(hostname);
2274 hostname = tor_dup_ip(addr);
2276 if (crypto_pk_get_digest(private_key, signing_key_digest)<0) {
2277 log_err(LD_BUG, "Error computing signing key digest");
2278 return NULL;
2280 if (crypto_pk_get_digest(cert->identity_key, identity_digest)<0) {
2281 log_err(LD_BUG, "Error computing identity key digest");
2282 return NULL;
2285 if (options->VersioningAuthoritativeDir) {
2286 client_versions = format_versions_list(options->RecommendedClientVersions);
2287 server_versions = format_versions_list(options->RecommendedServerVersions);
2290 contact = get_options()->ContactInfo;
2291 if (!contact)
2292 contact = "(none)";
2294 /* precompute this part, since we need it to decide what "stable"
2295 * means. */
2296 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2297 dirserv_set_router_is_running(ri, now);
2300 dirserv_compute_performance_thresholds(rl);
2302 /* XXXX We should take steps to keep this from oscillating if
2303 * total_exit_bandwidth is close to total_bandwidth/3. */
2304 exits_can_be_guards = total_exit_bandwidth >= (total_bandwidth / 3);
2306 routers = smartlist_create();
2307 smartlist_add_all(routers, rl->routers);
2308 routers_sort_by_identity(routers);
2309 omit_as_sybil = get_possible_sybil_list(routers);
2311 routerstatuses = smartlist_create();
2313 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
2314 if (ri->cache_info.published_on >= cutoff) {
2315 routerstatus_t *rs;
2316 vote_routerstatus_t *vrs;
2318 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
2319 rs = &vrs->status;
2320 set_routerstatus_from_routerinfo(rs, ri, now,
2321 naming, exits_can_be_guards,
2322 listbadexits, listbaddirs);
2324 if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
2325 clear_status_flags_on_sybil(rs);
2327 if (!vote_on_reachability)
2328 rs->is_running = 0;
2330 vrs->version = version_from_platform(ri->platform);
2331 smartlist_add(routerstatuses, vrs);
2334 smartlist_free(routers);
2335 digestmap_free(omit_as_sybil, NULL);
2337 v3_out = tor_malloc_zero(sizeof(networkstatus_t));
2339 v3_out->type = NS_TYPE_VOTE;
2340 dirvote_get_preferred_voting_intervals(&timing);
2341 v3_out->published = now;
2343 char tbuf[ISO_TIME_LEN+1];
2344 networkstatus_t *current_consensus =
2345 networkstatus_get_live_consensus(now);
2346 long last_consensus_interval; /* only used to pick a valid_after */
2347 if (current_consensus)
2348 last_consensus_interval = current_consensus->fresh_until -
2349 current_consensus->valid_after;
2350 else
2351 last_consensus_interval = options->TestingV3AuthInitialVotingInterval;
2352 v3_out->valid_after =
2353 dirvote_get_start_of_next_interval(now, (int)last_consensus_interval);
2354 format_iso_time(tbuf, v3_out->valid_after);
2355 log_notice(LD_DIR,"Choosing valid-after time in vote as %s: "
2356 "consensus_set=%d, last_interval=%d",
2357 tbuf, current_consensus?1:0, (int)last_consensus_interval);
2359 v3_out->fresh_until = v3_out->valid_after + timing.vote_interval;
2360 v3_out->valid_until = v3_out->valid_after +
2361 (timing.vote_interval * timing.n_intervals_valid);
2362 v3_out->vote_seconds = timing.vote_delay;
2363 v3_out->dist_seconds = timing.dist_delay;
2364 tor_assert(v3_out->vote_seconds > 0);
2365 tor_assert(v3_out->dist_seconds > 0);
2366 tor_assert(timing.n_intervals_valid > 0);
2368 v3_out->client_versions = client_versions;
2369 v3_out->server_versions = server_versions;
2370 v3_out->known_flags = smartlist_create();
2371 smartlist_split_string(v3_out->known_flags,
2372 "Authority Exit Fast Guard HSDir Stable V2Dir Valid",
2373 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2374 if (vote_on_reachability)
2375 smartlist_add(v3_out->known_flags, tor_strdup("Running"));
2376 if (listbaddirs)
2377 smartlist_add(v3_out->known_flags, tor_strdup("BadDirectory"));
2378 if (listbadexits)
2379 smartlist_add(v3_out->known_flags, tor_strdup("BadExit"));
2380 if (naming) {
2381 smartlist_add(v3_out->known_flags, tor_strdup("Named"));
2382 smartlist_add(v3_out->known_flags, tor_strdup("Unnamed"));
2384 smartlist_sort_strings(v3_out->known_flags);
2386 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
2387 voter->nickname = tor_strdup(options->Nickname);
2388 memcpy(voter->identity_digest, identity_digest, DIGEST_LEN);
2389 voter->address = hostname;
2390 voter->addr = addr;
2391 voter->dir_port = options->DirPort;
2392 voter->or_port = options->ORPort;
2393 voter->contact = tor_strdup(contact);
2394 memcpy(voter->signing_key_digest, signing_key_digest, DIGEST_LEN);
2395 if (options->V3AuthUseLegacyKey) {
2396 authority_cert_t *c = get_my_v3_legacy_cert();
2397 if (c) {
2398 crypto_pk_get_digest(c->identity_key, voter->legacy_id_digest);
2402 v3_out->voters = smartlist_create();
2403 smartlist_add(v3_out->voters, voter);
2404 v3_out->cert = authority_cert_dup(cert);
2405 v3_out->routerstatus_list = routerstatuses;
2406 /* Note: networkstatus_digest is unset; it won't get set until we actually
2407 * format the vote. */
2409 return v3_out;
2412 /** For v2 authoritative directories only: Replace the contents of
2413 * <b>the_v2_networkstatus</b> with a newly generated network status
2414 * object. */
2415 static cached_dir_t *
2416 generate_v2_networkstatus_opinion(void)
2418 cached_dir_t *r = NULL;
2419 size_t len, identity_pkey_len;
2420 char *status = NULL, *client_versions = NULL, *server_versions = NULL,
2421 *identity_pkey = NULL, *hostname = NULL;
2422 char *outp, *endp;
2423 or_options_t *options = get_options();
2424 char fingerprint[FINGERPRINT_LEN+1];
2425 char ipaddr[INET_NTOA_BUF_LEN];
2426 char published[ISO_TIME_LEN+1];
2427 char digest[DIGEST_LEN];
2428 struct in_addr in;
2429 uint32_t addr;
2430 crypto_pk_env_t *private_key;
2431 routerlist_t *rl = router_get_routerlist();
2432 time_t now = time(NULL);
2433 time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2434 int naming = options->NamingAuthoritativeDir;
2435 int versioning = options->VersioningAuthoritativeDir;
2436 int listbaddirs = options->AuthDirListBadDirs;
2437 int listbadexits = options->AuthDirListBadExits;
2438 int exits_can_be_guards;
2439 const char *contact;
2440 char *version_lines = NULL;
2441 smartlist_t *routers = NULL;
2442 digestmap_t *omit_as_sybil = NULL;
2444 private_key = get_identity_key();
2446 if (resolve_my_address(LOG_WARN, options, &addr, &hostname)<0) {
2447 log_warn(LD_NET, "Couldn't resolve my hostname");
2448 goto done;
2450 in.s_addr = htonl(addr);
2451 tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
2453 format_iso_time(published, now);
2455 client_versions = format_versions_list(options->RecommendedClientVersions);
2456 server_versions = format_versions_list(options->RecommendedServerVersions);
2458 if (crypto_pk_write_public_key_to_string(private_key, &identity_pkey,
2459 &identity_pkey_len)<0) {
2460 log_warn(LD_BUG,"Writing public key to string failed.");
2461 goto done;
2464 if (crypto_pk_get_fingerprint(private_key, fingerprint, 0)<0) {
2465 log_err(LD_BUG, "Error computing fingerprint");
2466 goto done;
2469 contact = get_options()->ContactInfo;
2470 if (!contact)
2471 contact = "(none)";
2473 if (versioning) {
2474 size_t v_len = 64+strlen(client_versions)+strlen(server_versions);
2475 version_lines = tor_malloc(v_len);
2476 tor_snprintf(version_lines, v_len,
2477 "client-versions %s\nserver-versions %s\n",
2478 client_versions, server_versions);
2479 } else {
2480 version_lines = tor_strdup("");
2483 len = 4096+strlen(client_versions)+strlen(server_versions);
2484 len += identity_pkey_len*2;
2485 len += (RS_ENTRY_LEN)*smartlist_len(rl->routers);
2487 status = tor_malloc(len);
2488 tor_snprintf(status, len,
2489 "network-status-version 2\n"
2490 "dir-source %s %s %d\n"
2491 "fingerprint %s\n"
2492 "contact %s\n"
2493 "published %s\n"
2494 "dir-options%s%s%s%s\n"
2495 "%s" /* client version line, server version line. */
2496 "dir-signing-key\n%s",
2497 hostname, ipaddr, (int)options->DirPort,
2498 fingerprint,
2499 contact,
2500 published,
2501 naming ? " Names" : "",
2502 listbaddirs ? " BadDirectories" : "",
2503 listbadexits ? " BadExits" : "",
2504 versioning ? " Versions" : "",
2505 version_lines,
2506 identity_pkey);
2507 outp = status + strlen(status);
2508 endp = status + len;
2510 /* precompute this part, since we need it to decide what "stable"
2511 * means. */
2512 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2513 dirserv_set_router_is_running(ri, now);
2516 dirserv_compute_performance_thresholds(rl);
2518 /* XXXX We should take steps to keep this from oscillating if
2519 * total_exit_bandwidth is close to total_bandwidth/3. */
2520 exits_can_be_guards = total_exit_bandwidth >= (total_bandwidth / 3);
2522 routers = smartlist_create();
2523 smartlist_add_all(routers, rl->routers);
2524 routers_sort_by_identity(routers);
2526 omit_as_sybil = get_possible_sybil_list(routers);
2528 SMARTLIST_FOREACH(routers, routerinfo_t *, ri, {
2529 if (ri->cache_info.published_on >= cutoff) {
2530 routerstatus_t rs;
2531 char *version = version_from_platform(ri->platform);
2533 set_routerstatus_from_routerinfo(&rs, ri, now,
2534 naming, exits_can_be_guards,
2535 listbadexits, listbaddirs);
2537 if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
2538 clear_status_flags_on_sybil(&rs);
2540 if (routerstatus_format_entry(outp, endp-outp, &rs, version, 0, 1)) {
2541 log_warn(LD_BUG, "Unable to print router status.");
2542 tor_free(version);
2543 goto done;
2545 tor_free(version);
2546 outp += strlen(outp);
2550 if (tor_snprintf(outp, endp-outp, "directory-signature %s\n",
2551 get_options()->Nickname)<0) {
2552 log_warn(LD_BUG, "Unable to write signature line.");
2553 goto done;
2555 if (router_get_networkstatus_v2_hash(status, digest)<0) {
2556 log_warn(LD_BUG, "Unable to hash network status");
2557 goto done;
2559 outp += strlen(outp);
2561 note_crypto_pk_op(SIGN_DIR);
2562 if (router_append_dirobj_signature(outp,endp-outp,digest,private_key)<0) {
2563 log_warn(LD_BUG, "Unable to sign router status.");
2564 goto done;
2568 networkstatus_v2_t *ns;
2569 if (!(ns = networkstatus_v2_parse_from_string(status))) {
2570 log_err(LD_BUG,"Generated a networkstatus we couldn't parse.");
2571 goto done;
2573 networkstatus_v2_free(ns);
2577 cached_dir_t **ns_ptr = &the_v2_networkstatus;
2578 if (*ns_ptr)
2579 cached_dir_decref(*ns_ptr);
2580 *ns_ptr = new_cached_dir(status, now);
2581 status = NULL; /* So it doesn't get double-freed. */
2582 the_v2_networkstatus_is_dirty = 0;
2583 router_set_networkstatus_v2((*ns_ptr)->dir, now, NS_GENERATED, NULL);
2584 r = *ns_ptr;
2587 done:
2588 tor_free(client_versions);
2589 tor_free(server_versions);
2590 tor_free(version_lines);
2591 tor_free(status);
2592 tor_free(hostname);
2593 tor_free(identity_pkey);
2594 if (routers)
2595 smartlist_free(routers);
2596 if (omit_as_sybil)
2597 digestmap_free(omit_as_sybil, NULL);
2598 return r;
2601 /** Given the portion of a networkstatus request URL after "tor/status/" in
2602 * <b>key</b>, append to <b>result</b> the digests of the identity keys of the
2603 * networkstatus objects that the client has requested. */
2604 void
2605 dirserv_get_networkstatus_v2_fingerprints(smartlist_t *result,
2606 const char *key)
2608 tor_assert(result);
2610 if (!cached_v2_networkstatus)
2611 cached_v2_networkstatus = digestmap_new();
2613 if (should_generate_v2_networkstatus())
2614 generate_v2_networkstatus_opinion();
2616 if (!strcmp(key,"authority")) {
2617 if (authdir_mode_v2(get_options())) {
2618 routerinfo_t *me = router_get_my_routerinfo();
2619 if (me)
2620 smartlist_add(result,
2621 tor_memdup(me->cache_info.identity_digest, DIGEST_LEN));
2623 } else if (!strcmp(key, "all")) {
2624 if (digestmap_size(cached_v2_networkstatus)) {
2625 digestmap_iter_t *iter;
2626 iter = digestmap_iter_init(cached_v2_networkstatus);
2627 while (!digestmap_iter_done(iter)) {
2628 const char *ident;
2629 void *val;
2630 digestmap_iter_get(iter, &ident, &val);
2631 smartlist_add(result, tor_memdup(ident, DIGEST_LEN));
2632 iter = digestmap_iter_next(cached_v2_networkstatus, iter);
2634 } else {
2635 SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
2636 trusted_dir_server_t *, ds,
2637 if (ds->type & V2_AUTHORITY)
2638 smartlist_add(result, tor_memdup(ds->digest, DIGEST_LEN)));
2640 smartlist_sort_digests(result);
2641 if (smartlist_len(result) == 0)
2642 log_info(LD_DIRSERV,
2643 "Client requested 'all' network status objects; we have none.");
2644 } else if (!strcmpstart(key, "fp/")) {
2645 dir_split_resource_into_fingerprints(key+3, result, NULL, 1, 1);
2649 /** Look for a network status object as specified by <b>key</b>, which should
2650 * be either "authority" (to find a network status generated by us), a hex
2651 * identity digest (to find a network status generated by given directory), or
2652 * "all" (to return all the v2 network status objects we have).
2654 void
2655 dirserv_get_networkstatus_v2(smartlist_t *result,
2656 const char *key)
2658 cached_dir_t *cached;
2659 smartlist_t *fingerprints = smartlist_create();
2660 tor_assert(result);
2662 if (!cached_v2_networkstatus)
2663 cached_v2_networkstatus = digestmap_new();
2665 dirserv_get_networkstatus_v2_fingerprints(fingerprints, key);
2666 SMARTLIST_FOREACH(fingerprints, const char *, fp,
2668 if (router_digest_is_me(fp) && should_generate_v2_networkstatus())
2669 generate_v2_networkstatus_opinion();
2670 cached = digestmap_get(cached_v2_networkstatus, fp);
2671 if (cached) {
2672 smartlist_add(result, cached);
2673 } else {
2674 char hexbuf[HEX_DIGEST_LEN+1];
2675 base16_encode(hexbuf, sizeof(hexbuf), fp, DIGEST_LEN);
2676 log_info(LD_DIRSERV, "Don't know about any network status with "
2677 "fingerprint '%s'", hexbuf);
2680 SMARTLIST_FOREACH(fingerprints, char *, cp, tor_free(cp));
2681 smartlist_free(fingerprints);
2684 /** As dirserv_get_routerdescs(), but instead of getting signed_descriptor_t
2685 * pointers, adds copies of digests to fps_out, and doesn't use the
2686 * /tor/server/ prefix. For a /d/ request, adds descriptor digests; for other
2687 * requests, adds identity digests.
2690 dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
2691 const char **msg, int for_unencrypted_conn,
2692 int is_extrainfo)
2694 int by_id = 1;
2695 *msg = NULL;
2697 if (!strcmp(key, "all")) {
2698 routerlist_t *rl = router_get_routerlist();
2699 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2700 smartlist_add(fps_out,
2701 tor_memdup(r->cache_info.identity_digest, DIGEST_LEN)));
2702 } else if (!strcmp(key, "authority")) {
2703 routerinfo_t *ri = router_get_my_routerinfo();
2704 if (ri)
2705 smartlist_add(fps_out,
2706 tor_memdup(ri->cache_info.identity_digest, DIGEST_LEN));
2707 } else if (!strcmpstart(key, "d/")) {
2708 by_id = 0;
2709 key += strlen("d/");
2710 dir_split_resource_into_fingerprints(key, fps_out, NULL, 1, 1);
2711 } else if (!strcmpstart(key, "fp/")) {
2712 key += strlen("fp/");
2713 dir_split_resource_into_fingerprints(key, fps_out, NULL, 1, 1);
2714 } else {
2715 *msg = "Key not recognized";
2716 return -1;
2719 if (for_unencrypted_conn) {
2720 /* Remove anything that insists it not be sent unencrypted. */
2721 SMARTLIST_FOREACH(fps_out, char *, cp, {
2722 signed_descriptor_t *sd;
2723 if (by_id)
2724 sd = get_signed_descriptor_by_fp(cp,is_extrainfo,0);
2725 else if (is_extrainfo)
2726 sd = extrainfo_get_by_descriptor_digest(cp);
2727 else
2728 sd = router_get_by_descriptor_digest(cp);
2729 if (sd && !sd->send_unencrypted) {
2730 tor_free(cp);
2731 SMARTLIST_DEL_CURRENT(fps_out, cp);
2736 if (!smartlist_len(fps_out)) {
2737 *msg = "Servers unavailable";
2738 return -1;
2740 return 0;
2743 /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
2744 * <b>key</b>. The key should be either
2745 * - "/tor/server/authority" for our own routerinfo;
2746 * - "/tor/server/all" for all the routerinfos we have, concatenated;
2747 * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
2748 * hex identity digests; or
2749 * - "/tor/server/d/D" where D is a plus-separated sequence
2750 * of server descriptor digests, in hex.
2752 * Return 0 if we found some matching descriptors, or -1 if we do not
2753 * have any descriptors, no matching descriptors, or if we did not
2754 * recognize the key (URL).
2755 * If -1 is returned *<b>msg</b> will be set to an appropriate error
2756 * message.
2758 * XXXX rename this function. It's only called from the controller.
2759 * XXXX in fact, refactor this function, merging as much as possible.
2762 dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
2763 const char **msg)
2765 *msg = NULL;
2767 if (!strcmp(key, "/tor/server/all")) {
2768 routerlist_t *rl = router_get_routerlist();
2769 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
2770 smartlist_add(descs_out, &(r->cache_info)));
2771 } else if (!strcmp(key, "/tor/server/authority")) {
2772 routerinfo_t *ri = router_get_my_routerinfo();
2773 if (ri)
2774 smartlist_add(descs_out, &(ri->cache_info));
2775 } else if (!strcmpstart(key, "/tor/server/d/")) {
2776 smartlist_t *digests = smartlist_create();
2777 key += strlen("/tor/server/d/");
2778 dir_split_resource_into_fingerprints(key, digests, NULL, 1, 1);
2779 SMARTLIST_FOREACH(digests, const char *, d,
2781 signed_descriptor_t *sd = router_get_by_descriptor_digest(d);
2782 if (sd)
2783 smartlist_add(descs_out,sd);
2785 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
2786 smartlist_free(digests);
2787 } else if (!strcmpstart(key, "/tor/server/fp/")) {
2788 smartlist_t *digests = smartlist_create();
2789 time_t cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
2790 key += strlen("/tor/server/fp/");
2791 dir_split_resource_into_fingerprints(key, digests, NULL, 1, 1);
2792 SMARTLIST_FOREACH(digests, const char *, d,
2794 if (router_digest_is_me(d)) {
2795 /* make sure desc_routerinfo exists */
2796 routerinfo_t *ri = router_get_my_routerinfo();
2797 if (ri)
2798 smartlist_add(descs_out, &(ri->cache_info));
2799 } else {
2800 routerinfo_t *ri = router_get_by_digest(d);
2801 /* Don't actually serve a descriptor that everyone will think is
2802 * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
2803 * Tors from downloading descriptors that they will throw away.
2805 if (ri && ri->cache_info.published_on > cutoff)
2806 smartlist_add(descs_out, &(ri->cache_info));
2809 SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
2810 smartlist_free(digests);
2811 } else {
2812 *msg = "Key not recognized";
2813 return -1;
2816 if (!smartlist_len(descs_out)) {
2817 *msg = "Servers unavailable";
2818 return -1;
2820 return 0;
2823 /** Called when a TLS handshake has completed successfully with a
2824 * router listening at <b>address</b>:<b>or_port</b>, and has yielded
2825 * a certificate with digest <b>digest_rcvd</b>.
2827 * Also, if as_advertised is 1, then inform the reachability checker
2828 * that we could get to this guy.
2830 void
2831 dirserv_orconn_tls_done(const char *address,
2832 uint16_t or_port,
2833 const char *digest_rcvd,
2834 int as_advertised)
2836 routerlist_t *rl = router_get_routerlist();
2837 time_t now = time(NULL);
2838 int bridge_auth = authdir_mode_bridge(get_options());
2839 tor_assert(address);
2840 tor_assert(digest_rcvd);
2842 SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
2843 if (!strcasecmp(address, ri->address) && or_port == ri->or_port &&
2844 as_advertised &&
2845 !memcmp(ri->cache_info.identity_digest, digest_rcvd, DIGEST_LEN)) {
2846 /* correct digest. mark this router reachable! */
2847 if (!bridge_auth || ri->purpose == ROUTER_PURPOSE_BRIDGE) {
2848 log_info(LD_DIRSERV, "Found router %s to be reachable. Yay.",
2849 ri->nickname);
2850 rep_hist_note_router_reachable(digest_rcvd, now);
2851 ri->last_reachable = now;
2855 /* FFFF Maybe we should reinstate the code that dumps routers with the same
2856 * addr/port but with nonmatching keys, but instead of dumping, we should
2857 * skip testing. */
2860 /** Auth dir server only: if <b>try_all</b> is 1, launch connections to
2861 * all known routers; else we want to load balance such that we only
2862 * try a few connections per call.
2864 * The load balancing is such that if we get called once every ten
2865 * seconds, we will cycle through all the tests in 1280 seconds (a
2866 * bit over 20 minutes).
2868 void
2869 dirserv_test_reachability(time_t now, int try_all)
2871 /* XXX decide what to do here; see or-talk thread "purging old router
2872 * information, revocation." -NM
2873 * We can't afford to mess with this in 0.1.2.x. The reason is that
2874 * if we stop doing reachability tests on some of routerlist, then
2875 * we'll for-sure think they're down, which may have unexpected
2876 * effects in other parts of the code. It doesn't hurt much to do
2877 * the testing, and directory authorities are easy to upgrade. Let's
2878 * wait til 0.2.0. -RD */
2879 // time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2880 routerlist_t *rl = router_get_routerlist();
2881 static char ctr = 0;
2882 int bridge_auth = authdir_mode_bridge(get_options());
2884 SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, router) {
2885 const char *id_digest = router->cache_info.identity_digest;
2886 tor_addr_t router_addr;
2887 if (router_is_me(router))
2888 continue;
2889 if (bridge_auth && router->purpose != ROUTER_PURPOSE_BRIDGE)
2890 continue; /* bridge authorities only test reachability on bridges */
2891 // if (router->cache_info.published_on > cutoff)
2892 // continue;
2893 if (try_all || (((uint8_t)id_digest[0]) % 128) == ctr) {
2894 log_debug(LD_OR,"Testing reachability of %s at %s:%u.",
2895 router->nickname, router->address, router->or_port);
2896 /* Remember when we started trying to determine reachability */
2897 if (!router->testing_since)
2898 router->testing_since = now;
2899 tor_addr_from_ipv4h(&router_addr, router->addr);
2900 connection_or_connect(&router_addr, router->or_port, id_digest);
2902 } SMARTLIST_FOREACH_END(router);
2903 if (!try_all) /* increment ctr */
2904 ctr = (ctr + 1) % 128;
2907 /** Given a fingerprint <b>fp</b> which is either set if we're looking
2908 * for a v2 status, or zeroes if we're looking for a v3 status, return
2909 * a pointer to the appropriate cached dir object, or NULL if there isn't
2910 * one available. */
2911 static cached_dir_t *
2912 lookup_cached_dir_by_fp(const char *fp)
2914 cached_dir_t *d = NULL;
2915 if (tor_digest_is_zero(fp) && cached_v3_networkstatus)
2916 d = cached_v3_networkstatus;
2917 else if (router_digest_is_me(fp) && the_v2_networkstatus)
2918 d = the_v2_networkstatus;
2919 else if (cached_v2_networkstatus)
2920 d = digestmap_get(cached_v2_networkstatus, fp);
2921 return d;
2924 /** Remove from <b>fps</b> every networkstatus key where both
2925 * a) we have a networkstatus document and
2926 * b) it is not newer than <b>cutoff</b>.
2928 * Return 1 if any items were present at all; else return 0.
2931 dirserv_remove_old_statuses(smartlist_t *fps, time_t cutoff)
2933 int found_any = 0;
2934 SMARTLIST_FOREACH(fps, char *, digest,
2936 cached_dir_t *d = lookup_cached_dir_by_fp(digest);
2937 if (!d)
2938 continue;
2939 found_any = 1;
2940 if (d->published <= cutoff) {
2941 tor_free(digest);
2942 SMARTLIST_DEL_CURRENT(fps, digest);
2946 return found_any;
2949 /** Return the cache-info for identity fingerprint <b>fp</b>, or
2950 * its extra-info document if <b>extrainfo</b> is true. Return
2951 * NULL if not found or if the descriptor is older than
2952 * <b>publish_cutoff</b>. */
2953 static signed_descriptor_t *
2954 get_signed_descriptor_by_fp(const char *fp, int extrainfo,
2955 time_t publish_cutoff)
2957 if (router_digest_is_me(fp)) {
2958 if (extrainfo)
2959 return &(router_get_my_extrainfo()->cache_info);
2960 else
2961 return &(router_get_my_routerinfo()->cache_info);
2962 } else {
2963 routerinfo_t *ri = router_get_by_digest(fp);
2964 if (ri &&
2965 ri->cache_info.published_on > publish_cutoff) {
2966 if (extrainfo)
2967 return extrainfo_get_by_descriptor_digest(
2968 ri->cache_info.extra_info_digest);
2969 else
2970 return &ri->cache_info;
2973 return NULL;
2976 /** Return true iff we have any of the documents (extrainfo or routerdesc)
2977 * specified by the fingerprints in <b>fps</b> and <b>spool_src</b>. Used to
2978 * decide whether to send a 404. */
2980 dirserv_have_any_serverdesc(smartlist_t *fps, int spool_src)
2982 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
2983 SMARTLIST_FOREACH(fps, const char *, fp, {
2984 switch (spool_src)
2986 case DIR_SPOOL_EXTRA_BY_DIGEST:
2987 if (extrainfo_get_by_descriptor_digest(fp)) return 1;
2988 break;
2989 case DIR_SPOOL_SERVER_BY_DIGEST:
2990 if (router_get_by_descriptor_digest(fp)) return 1;
2991 break;
2992 case DIR_SPOOL_EXTRA_BY_FP:
2993 case DIR_SPOOL_SERVER_BY_FP:
2994 if (get_signed_descriptor_by_fp(fp,
2995 spool_src == DIR_SPOOL_EXTRA_BY_FP, publish_cutoff))
2996 return 1;
2997 break;
3000 return 0;
3003 /** Return an approximate estimate of the number of bytes that will
3004 * be needed to transmit the server descriptors (if is_serverdescs --
3005 * they can be either d/ or fp/ queries) or networkstatus objects (if
3006 * !is_serverdescs) listed in <b>fps</b>. If <b>compressed</b> is set,
3007 * we guess how large the data will be after compression.
3009 * The return value is an estimate; it might be larger or smaller.
3011 size_t
3012 dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
3013 int compressed)
3015 size_t result;
3016 tor_assert(fps);
3017 if (is_serverdescs) {
3018 int n = smartlist_len(fps);
3019 routerinfo_t *me = router_get_my_routerinfo();
3020 result = (me?me->cache_info.signed_descriptor_len:2048) * n;
3021 if (compressed)
3022 result /= 2; /* observed compressibility is between 35 and 55%. */
3023 } else {
3024 result = 0;
3025 SMARTLIST_FOREACH(fps, const char *, digest, {
3026 cached_dir_t *dir = lookup_cached_dir_by_fp(digest);
3027 if (dir)
3028 result += compressed ? dir->dir_z_len : dir->dir_len;
3031 return result;
3034 /** When we're spooling data onto our outbuf, add more whenever we dip
3035 * below this threshold. */
3036 #define DIRSERV_BUFFER_MIN 16384
3038 /** Spooling helper: called when we have no more data to spool to <b>conn</b>.
3039 * Flushes any remaining data to be (un)compressed, and changes the spool
3040 * source to NONE. Returns 0 on success, negative on failure. */
3041 static int
3042 connection_dirserv_finish_spooling(dir_connection_t *conn)
3044 if (conn->zlib_state) {
3045 connection_write_to_buf_zlib("", 0, conn, 1);
3046 tor_zlib_free(conn->zlib_state);
3047 conn->zlib_state = NULL;
3049 conn->dir_spool_src = DIR_SPOOL_NONE;
3050 return 0;
3053 /** Spooling helper: called when we're sending a bunch of server descriptors,
3054 * and the outbuf has become too empty. Pulls some entries from
3055 * fingerprint_stack, and writes the corresponding servers onto outbuf. If we
3056 * run out of entries, flushes the zlib state and sets the spool source to
3057 * NONE. Returns 0 on success, negative on failure.
3059 static int
3060 connection_dirserv_add_servers_to_outbuf(dir_connection_t *conn)
3062 #ifdef TRACK_SERVED_TIME
3063 time_t now = time(NULL);
3064 #endif
3065 int by_fp = (conn->dir_spool_src == DIR_SPOOL_SERVER_BY_FP ||
3066 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP);
3067 int extra = (conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP ||
3068 conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_DIGEST);
3069 time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
3071 while (smartlist_len(conn->fingerprint_stack) &&
3072 buf_datalen(conn->_base.outbuf) < DIRSERV_BUFFER_MIN) {
3073 const char *body;
3074 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3075 signed_descriptor_t *sd = NULL;
3076 if (by_fp) {
3077 sd = get_signed_descriptor_by_fp(fp, extra, publish_cutoff);
3078 } else {
3079 sd = extra ? extrainfo_get_by_descriptor_digest(fp)
3080 : router_get_by_descriptor_digest(fp);
3082 tor_free(fp);
3083 if (!sd)
3084 continue;
3085 if (!connection_dir_is_encrypted(conn) && !sd->send_unencrypted) {
3086 /* we did this check once before (so we could have an accurate size
3087 * estimate and maybe send a 404 if somebody asked for only bridges on a
3088 * connection), but we need to do it again in case a previously
3089 * unknown bridge descriptor has shown up between then and now. */
3090 continue;
3092 #ifdef TRACK_SERVED_TIME
3093 sd->last_served_at = now;
3094 #endif
3095 body = signed_descriptor_get_body(sd);
3096 if (conn->zlib_state) {
3097 int last = ! smartlist_len(conn->fingerprint_stack);
3098 connection_write_to_buf_zlib(body, sd->signed_descriptor_len, conn,
3099 last);
3100 if (last) {
3101 tor_zlib_free(conn->zlib_state);
3102 conn->zlib_state = NULL;
3104 } else {
3105 connection_write_to_buf(body,
3106 sd->signed_descriptor_len,
3107 TO_CONN(conn));
3111 if (!smartlist_len(conn->fingerprint_stack)) {
3112 /* We just wrote the last one; finish up. */
3113 conn->dir_spool_src = DIR_SPOOL_NONE;
3114 smartlist_free(conn->fingerprint_stack);
3115 conn->fingerprint_stack = NULL;
3117 return 0;
3120 /** Spooling helper: Called when we're sending a directory or networkstatus,
3121 * and the outbuf has become too empty. Pulls some bytes from
3122 * <b>conn</b>-\>cached_dir-\>dir_z, uncompresses them if appropriate, and
3123 * puts them on the outbuf. If we run out of entries, flushes the zlib state
3124 * and sets the spool source to NONE. Returns 0 on success, negative on
3125 * failure. */
3126 static int
3127 connection_dirserv_add_dir_bytes_to_outbuf(dir_connection_t *conn)
3129 ssize_t bytes;
3130 int64_t remaining;
3132 bytes = DIRSERV_BUFFER_MIN - buf_datalen(conn->_base.outbuf);
3133 tor_assert(bytes > 0);
3134 tor_assert(conn->cached_dir);
3135 if (bytes < 8192)
3136 bytes = 8192;
3137 remaining = conn->cached_dir->dir_z_len - conn->cached_dir_offset;
3138 if (bytes > remaining)
3139 bytes = (ssize_t) remaining;
3141 if (conn->zlib_state) {
3142 connection_write_to_buf_zlib(
3143 conn->cached_dir->dir_z + conn->cached_dir_offset,
3144 bytes, conn, bytes == remaining);
3145 } else {
3146 connection_write_to_buf(conn->cached_dir->dir_z + conn->cached_dir_offset,
3147 bytes, TO_CONN(conn));
3149 conn->cached_dir_offset += bytes;
3150 if (conn->cached_dir_offset == (int)conn->cached_dir->dir_z_len) {
3151 /* We just wrote the last one; finish up. */
3152 connection_dirserv_finish_spooling(conn);
3153 cached_dir_decref(conn->cached_dir);
3154 conn->cached_dir = NULL;
3156 return 0;
3159 /** Spooling helper: Called when we're spooling networkstatus objects on
3160 * <b>conn</b>, and the outbuf has become too empty. If the current
3161 * networkstatus object (in <b>conn</b>-\>cached_dir) has more data, pull data
3162 * from there. Otherwise, pop the next fingerprint from fingerprint_stack,
3163 * and start spooling the next networkstatus. (A digest of all 0 bytes is
3164 * treated as a request for the current consensus.) If we run out of entries,
3165 * flushes the zlib state and sets the spool source to NONE. Returns 0 on
3166 * success, negative on failure. */
3167 static int
3168 connection_dirserv_add_networkstatus_bytes_to_outbuf(dir_connection_t *conn)
3171 while (buf_datalen(conn->_base.outbuf) < DIRSERV_BUFFER_MIN) {
3172 if (conn->cached_dir) {
3173 int uncompressing = (conn->zlib_state != NULL);
3174 int r = connection_dirserv_add_dir_bytes_to_outbuf(conn);
3175 if (conn->dir_spool_src == DIR_SPOOL_NONE) {
3176 /* add_dir_bytes thinks we're done with the cached_dir. But we
3177 * may have more cached_dirs! */
3178 conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
3179 /* This bit is tricky. If we were uncompressing the last
3180 * networkstatus, we may need to make a new zlib object to
3181 * uncompress the next one. */
3182 if (uncompressing && ! conn->zlib_state &&
3183 conn->fingerprint_stack &&
3184 smartlist_len(conn->fingerprint_stack)) {
3185 conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
3188 if (r) return r;
3189 } else if (conn->fingerprint_stack &&
3190 smartlist_len(conn->fingerprint_stack)) {
3191 /* Add another networkstatus; start serving it. */
3192 char *fp = smartlist_pop_last(conn->fingerprint_stack);
3193 cached_dir_t *d = lookup_cached_dir_by_fp(fp);
3194 tor_free(fp);
3195 if (d) {
3196 ++d->refcnt;
3197 conn->cached_dir = d;
3198 conn->cached_dir_offset = 0;
3200 } else {
3201 connection_dirserv_finish_spooling(conn);
3202 if (conn->fingerprint_stack)
3203 smartlist_free(conn->fingerprint_stack);
3204 conn->fingerprint_stack = NULL;
3205 return 0;
3208 return 0;
3211 /** Called whenever we have flushed some directory data in state
3212 * SERVER_WRITING. */
3214 connection_dirserv_flushed_some(dir_connection_t *conn)
3216 tor_assert(conn->_base.state == DIR_CONN_STATE_SERVER_WRITING);
3218 if (buf_datalen(conn->_base.outbuf) >= DIRSERV_BUFFER_MIN)
3219 return 0;
3221 switch (conn->dir_spool_src) {
3222 case DIR_SPOOL_EXTRA_BY_DIGEST:
3223 case DIR_SPOOL_EXTRA_BY_FP:
3224 case DIR_SPOOL_SERVER_BY_DIGEST:
3225 case DIR_SPOOL_SERVER_BY_FP:
3226 return connection_dirserv_add_servers_to_outbuf(conn);
3227 case DIR_SPOOL_CACHED_DIR:
3228 return connection_dirserv_add_dir_bytes_to_outbuf(conn);
3229 case DIR_SPOOL_NETWORKSTATUS:
3230 return connection_dirserv_add_networkstatus_bytes_to_outbuf(conn);
3231 case DIR_SPOOL_NONE:
3232 default:
3233 return 0;
3237 /** Release all storage used by the directory server. */
3238 void
3239 dirserv_free_all(void)
3241 dirserv_free_fingerprint_list();
3243 cached_dir_decref(the_directory);
3244 clear_cached_dir(&the_runningrouters);
3245 cached_dir_decref(the_v2_networkstatus);
3246 cached_dir_decref(cached_directory);
3247 clear_cached_dir(&cached_runningrouters);
3248 if (cached_v2_networkstatus) {
3249 digestmap_free(cached_v2_networkstatus, _free_cached_dir);
3250 cached_v2_networkstatus = NULL;
3252 cached_dir_decref(cached_v3_networkstatus);