Possible fix for broken country settings in ExcludeExitNodes.
[tor/rransom.git] / src / or / router.c
blobf3e09e6db252412a02ec2149a213e5c74b0ef070
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 #define ROUTER_PRIVATE
9 #include "or.h"
11 /**
12 * \file router.c
13 * \brief OR functionality, including key maintenance, generating
14 * and uploading server descriptors, retrying OR connections.
15 **/
17 extern long stats_n_seconds_working;
19 /************************************************************/
21 /*****
22 * Key management: ORs only.
23 *****/
25 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
27 static tor_mutex_t *key_lock=NULL;
28 static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
29 /** Current private onionskin decryption key: used to decode CREATE cells. */
30 static crypto_pk_env_t *onionkey=NULL;
31 /** Previous private onionskin decription key: used to decode CREATE cells
32 * generated by clients that have an older version of our descriptor. */
33 static crypto_pk_env_t *lastonionkey=NULL;
34 /** Private "identity key": used to sign directory info and TLS
35 * certificates. Never changes. */
36 static crypto_pk_env_t *identitykey=NULL;
37 /** Digest of identitykey. */
38 static char identitykey_digest[DIGEST_LEN];
39 /** Signing key used for v3 directory material; only set for authorities. */
40 static crypto_pk_env_t *authority_signing_key = NULL;
41 /** Key certificate to authenticate v3 directory material; only set for
42 * authorities. */
43 static authority_cert_t *authority_key_certificate = NULL;
45 /** For emergency V3 authority key migration: An extra signing key that we use
46 * with our old (obsolete) identity key for a while. */
47 static crypto_pk_env_t *legacy_signing_key = NULL;
48 /** For emergency V3 authority key migration: An extra certificate to
49 * authenticate legacy_signing_key with our obsolete identity key.*/
50 static authority_cert_t *legacy_key_certificate = NULL;
52 /* (Note that v3 authorities also have a separate "authority identity key",
53 * but this key is never actually loaded by the Tor process. Instead, it's
54 * used by tor-gencert to sign new signing keys and make new key
55 * certificates. */
57 /** Replace the current onion key with <b>k</b>. Does not affect
58 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
60 static void
61 set_onion_key(crypto_pk_env_t *k)
63 tor_mutex_acquire(key_lock);
64 if (onionkey)
65 crypto_free_pk_env(onionkey);
66 onionkey = k;
67 onionkey_set_at = time(NULL);
68 tor_mutex_release(key_lock);
69 mark_my_descriptor_dirty();
72 /** Return the current onion key. Requires that the onion key has been
73 * loaded or generated. */
74 crypto_pk_env_t *
75 get_onion_key(void)
77 tor_assert(onionkey);
78 return onionkey;
81 /** Store a full copy of the current onion key into *<b>key</b>, and a full
82 * copy of the most recent onion key into *<b>last</b>.
84 void
85 dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
87 tor_assert(key);
88 tor_assert(last);
89 tor_mutex_acquire(key_lock);
90 tor_assert(onionkey);
91 *key = crypto_pk_copy_full(onionkey);
92 if (lastonionkey)
93 *last = crypto_pk_copy_full(lastonionkey);
94 else
95 *last = NULL;
96 tor_mutex_release(key_lock);
99 /** Return the time when the onion key was last set. This is either the time
100 * when the process launched, or the time of the most recent key rotation since
101 * the process launched.
103 time_t
104 get_onion_key_set_at(void)
106 return onionkey_set_at;
109 /** Set the current identity key to k.
111 void
112 set_identity_key(crypto_pk_env_t *k)
114 if (identitykey)
115 crypto_free_pk_env(identitykey);
116 identitykey = k;
117 crypto_pk_get_digest(identitykey, identitykey_digest);
120 /** Returns the current identity key; requires that the identity key has been
121 * set.
123 crypto_pk_env_t *
124 get_identity_key(void)
126 tor_assert(identitykey);
127 return identitykey;
130 /** Return true iff the identity key has been set. */
132 identity_key_is_set(void)
134 return identitykey != NULL;
137 /** Return the key certificate for this v3 (voting) authority, or NULL
138 * if we have no such certificate. */
139 authority_cert_t *
140 get_my_v3_authority_cert(void)
142 return authority_key_certificate;
145 /** Return the v3 signing key for this v3 (voting) authority, or NULL
146 * if we have no such key. */
147 crypto_pk_env_t *
148 get_my_v3_authority_signing_key(void)
150 return authority_signing_key;
153 /** If we're an authority, and we're using a legacy authority identity key for
154 * emergency migration purposes, return the certificate associated with that
155 * key. */
156 authority_cert_t *
157 get_my_v3_legacy_cert(void)
159 return legacy_key_certificate;
162 /** If we're an authority, and we're using a legacy authority identity key for
163 * emergency migration purposes, return that key. */
164 crypto_pk_env_t *
165 get_my_v3_legacy_signing_key(void)
167 return legacy_signing_key;
170 /** Replace the previous onion key with the current onion key, and generate
171 * a new previous onion key. Immediately after calling this function,
172 * the OR should:
173 * - schedule all previous cpuworkers to shut down _after_ processing
174 * pending work. (This will cause fresh cpuworkers to be generated.)
175 * - generate and upload a fresh routerinfo.
177 void
178 rotate_onion_key(void)
180 char *fname, *fname_prev;
181 crypto_pk_env_t *prkey;
182 or_state_t *state = get_or_state();
183 time_t now;
184 fname = get_datadir_fname2("keys", "secret_onion_key");
185 fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
186 if (!(prkey = crypto_new_pk_env())) {
187 log_err(LD_GENERAL,"Error constructing rotated onion key");
188 goto error;
190 if (crypto_pk_generate_key(prkey)) {
191 log_err(LD_BUG,"Error generating onion key");
192 goto error;
194 if (file_status(fname) == FN_FILE) {
195 if (replace_file(fname, fname_prev))
196 goto error;
198 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
199 log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
200 goto error;
202 log_info(LD_GENERAL, "Rotating onion key");
203 tor_mutex_acquire(key_lock);
204 if (lastonionkey)
205 crypto_free_pk_env(lastonionkey);
206 lastonionkey = onionkey;
207 onionkey = prkey;
208 now = time(NULL);
209 state->LastRotatedOnionKey = onionkey_set_at = now;
210 tor_mutex_release(key_lock);
211 mark_my_descriptor_dirty();
212 or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
213 goto done;
214 error:
215 log_warn(LD_GENERAL, "Couldn't rotate onion key.");
216 if (prkey)
217 crypto_free_pk_env(prkey);
218 done:
219 tor_free(fname);
220 tor_free(fname_prev);
223 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
224 * and <b>generate</b> is true, create a new RSA key and save it in
225 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
226 * errors at level <b>severity</b>.
228 crypto_pk_env_t *
229 init_key_from_file(const char *fname, int generate, int severity)
231 crypto_pk_env_t *prkey = NULL;
233 if (!(prkey = crypto_new_pk_env())) {
234 log(severity, LD_GENERAL,"Error constructing key");
235 goto error;
238 switch (file_status(fname)) {
239 case FN_DIR:
240 case FN_ERROR:
241 log(severity, LD_FS,"Can't read key from \"%s\"", fname);
242 goto error;
243 case FN_NOENT:
244 if (generate) {
245 if (!have_lockfile()) {
246 if (try_locking(get_options(), 0)<0) {
247 /* Make sure that --list-fingerprint only creates new keys
248 * if there is no possibility for a deadlock. */
249 log(severity, LD_FS, "Another Tor process has locked \"%s\". Not "
250 "writing any new keys.", fname);
251 /*XXXX The 'other process' might make a key in a second or two;
252 * maybe we should wait for it. */
253 goto error;
256 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
257 fname);
258 if (crypto_pk_generate_key(prkey)) {
259 log(severity, LD_GENERAL,"Error generating onion key");
260 goto error;
262 if (crypto_pk_check_key(prkey) <= 0) {
263 log(severity, LD_GENERAL,"Generated key seems invalid");
264 goto error;
266 log_info(LD_GENERAL, "Generated key seems valid");
267 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
268 log(severity, LD_FS,
269 "Couldn't write generated key to \"%s\".", fname);
270 goto error;
272 } else {
273 log_info(LD_GENERAL, "No key found in \"%s\"", fname);
275 return prkey;
276 case FN_FILE:
277 if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
278 log(severity, LD_GENERAL,"Error loading private key.");
279 goto error;
281 return prkey;
282 default:
283 tor_assert(0);
286 error:
287 if (prkey)
288 crypto_free_pk_env(prkey);
289 return NULL;
292 /** Try to load the vote-signing private key and certificate for being a v3
293 * directory authority, and make sure they match. If <b>legacy</b>, load a
294 * legacy key/cert set for emergency key migration; otherwise load the regular
295 * key/cert set. On success, store them into *<b>key_out</b> and
296 * *<b>cert_out</b> respectively, and return 0. On failrue, return -1. */
297 static int
298 load_authority_keyset(int legacy, crypto_pk_env_t **key_out,
299 authority_cert_t **cert_out)
301 int r = -1;
302 char *fname = NULL, *cert = NULL;
303 const char *eos = NULL;
304 crypto_pk_env_t *signing_key = NULL;
305 authority_cert_t *parsed = NULL;
307 fname = get_datadir_fname2("keys",
308 legacy ? "legacy_signing_key" : "authority_signing_key");
309 signing_key = init_key_from_file(fname, 0, LOG_INFO);
310 if (!signing_key) {
311 log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
312 goto done;
314 tor_free(fname);
315 fname = get_datadir_fname2("keys",
316 legacy ? "legacy_certificate" : "authority_certificate");
317 cert = read_file_to_str(fname, 0, NULL);
318 if (!cert) {
319 log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
320 fname);
321 goto done;
323 parsed = authority_cert_parse_from_string(cert, &eos);
324 if (!parsed) {
325 log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
326 goto done;
328 if (crypto_pk_cmp_keys(signing_key, parsed->signing_key) != 0) {
329 log_warn(LD_DIR, "Stored signing key does not match signing key in "
330 "certificate");
331 goto done;
333 parsed->cache_info.signed_descriptor_body = cert;
334 parsed->cache_info.signed_descriptor_len = eos-cert;
335 cert = NULL;
337 if (*key_out)
338 crypto_free_pk_env(*key_out);
339 if (*cert_out)
340 authority_cert_free(*cert_out);
341 *key_out = signing_key;
342 *cert_out = parsed;
343 r = 0;
344 signing_key = NULL;
345 parsed = NULL;
347 done:
348 tor_free(fname);
349 tor_free(cert);
350 if (signing_key)
351 crypto_free_pk_env(signing_key);
352 if (parsed)
353 authority_cert_free(parsed);
354 return r;
357 /** Load the v3 (voting) authority signing key and certificate, if they are
358 * present. Return -1 if anything is missing, mismatched, or unloadable;
359 * return 0 on success. */
360 static int
361 init_v3_authority_keys(void)
363 if (load_authority_keyset(0, &authority_signing_key,
364 &authority_key_certificate)<0)
365 return -1;
367 if (get_options()->V3AuthUseLegacyKey &&
368 load_authority_keyset(1, &legacy_signing_key,
369 &legacy_key_certificate)<0)
370 return -1;
372 return 0;
375 /** If we're a v3 authority, check whether we have a certificate that's
376 * likely to expire soon. Warn if we do, but not too often. */
377 void
378 v3_authority_check_key_expiry(void)
380 time_t now, expires;
381 static time_t last_warned = 0;
382 int badness, time_left, warn_interval;
383 if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
384 return;
386 now = time(NULL);
387 expires = authority_key_certificate->expires;
388 time_left = (int)( expires - now );
389 if (time_left <= 0) {
390 badness = LOG_ERR;
391 warn_interval = 60*60;
392 } else if (time_left <= 24*60*60) {
393 badness = LOG_WARN;
394 warn_interval = 60*60;
395 } else if (time_left <= 24*60*60*7) {
396 badness = LOG_WARN;
397 warn_interval = 24*60*60;
398 } else if (time_left <= 24*60*60*30) {
399 badness = LOG_WARN;
400 warn_interval = 24*60*60*5;
401 } else {
402 return;
405 if (last_warned + warn_interval > now)
406 return;
408 if (time_left <= 0) {
409 log(badness, LD_DIR, "Your v3 authority certificate has expired."
410 " Generate a new one NOW.");
411 } else if (time_left <= 24*60*60) {
412 log(badness, LD_DIR, "Your v3 authority certificate expires in %d hours;"
413 " Generate a new one NOW.", time_left/(60*60));
414 } else {
415 log(badness, LD_DIR, "Your v3 authority certificate expires in %d days;"
416 " Generate a new one soon.", time_left/(24*60*60));
418 last_warned = now;
421 /** Initialize all OR private keys, and the TLS context, as necessary.
422 * On OPs, this only initializes the tls context. Return 0 on success,
423 * or -1 if Tor should die.
426 init_keys(void)
428 char *keydir;
429 char fingerprint[FINGERPRINT_LEN+1];
430 /*nickname<space>fp\n\0 */
431 char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
432 const char *mydesc;
433 crypto_pk_env_t *prkey;
434 char digest[20];
435 char v3_digest[20];
436 char *cp;
437 or_options_t *options = get_options();
438 authority_type_t type;
439 time_t now = time(NULL);
440 trusted_dir_server_t *ds;
441 int v3_digest_set = 0;
442 authority_cert_t *cert = NULL;
444 if (!key_lock)
445 key_lock = tor_mutex_new();
447 /* There are a couple of paths that put us here before */
448 if (crypto_global_init(get_options()->HardwareAccel)) {
449 log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
450 return -1;
453 /* OP's don't need persistent keys; just make up an identity and
454 * initialize the TLS context. */
455 if (!server_mode(options)) {
456 if (!(prkey = crypto_new_pk_env()))
457 return -1;
458 if (crypto_pk_generate_key(prkey)) {
459 crypto_free_pk_env(prkey);
460 return -1;
462 set_identity_key(prkey);
463 /* Create a TLS context; default the client nickname to "client". */
464 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
465 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
466 return -1;
468 return 0;
470 /* Make sure DataDirectory exists, and is private. */
471 if (check_private_dir(options->DataDirectory, CPD_CREATE)) {
472 return -1;
474 /* Check the key directory. */
475 keydir = get_datadir_fname("keys");
476 if (check_private_dir(keydir, CPD_CREATE)) {
477 tor_free(keydir);
478 return -1;
480 tor_free(keydir);
482 /* 1a. Read v3 directory authority key/cert information. */
483 memset(v3_digest, 0, sizeof(v3_digest));
484 if (authdir_mode_v3(options)) {
485 if (init_v3_authority_keys()<0) {
486 log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
487 "were unable to load our v3 authority keys and certificate! "
488 "Use tor-gencert to generate them. Dying.");
489 return -1;
491 cert = get_my_v3_authority_cert();
492 if (cert) {
493 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
494 v3_digest);
495 v3_digest_set = 1;
499 /* 1. Read identity key. Make it if none is found. */
500 keydir = get_datadir_fname2("keys", "secret_id_key");
501 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
502 prkey = init_key_from_file(keydir, 1, LOG_ERR);
503 tor_free(keydir);
504 if (!prkey) return -1;
505 set_identity_key(prkey);
507 /* 2. Read onion key. Make it if none is found. */
508 keydir = get_datadir_fname2("keys", "secret_onion_key");
509 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
510 prkey = init_key_from_file(keydir, 1, LOG_ERR);
511 tor_free(keydir);
512 if (!prkey) return -1;
513 set_onion_key(prkey);
514 if (options->command == CMD_RUN_TOR) {
515 /* only mess with the state file if we're actually running Tor */
516 or_state_t *state = get_or_state();
517 if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
518 /* We allow for some parsing slop, but we don't want to risk accepting
519 * values in the distant future. If we did, we might never rotate the
520 * onion key. */
521 onionkey_set_at = state->LastRotatedOnionKey;
522 } else {
523 /* We have no LastRotatedOnionKey set; either we just created the key
524 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
525 * start the clock ticking now so that we will eventually rotate it even
526 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
527 state->LastRotatedOnionKey = onionkey_set_at = now;
528 or_state_mark_dirty(state, options->AvoidDiskWrites ?
529 time(NULL)+3600 : 0);
533 keydir = get_datadir_fname2("keys", "secret_onion_key.old");
534 if (!lastonionkey && file_status(keydir) == FN_FILE) {
535 prkey = init_key_from_file(keydir, 1, LOG_ERR);
536 if (prkey)
537 lastonionkey = prkey;
539 tor_free(keydir);
541 /* 3. Initialize link key and TLS context. */
542 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
543 log_err(LD_GENERAL,"Error initializing TLS context");
544 return -1;
546 /* 4. Build our router descriptor. */
547 /* Must be called after keys are initialized. */
548 mydesc = router_get_my_descriptor();
549 if (authdir_mode(options)) {
550 const char *m;
551 routerinfo_t *ri;
552 /* We need to add our own fingerprint so it gets recognized. */
553 if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
554 log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
555 return -1;
557 if (mydesc) {
558 ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
559 if (!ri) {
560 log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
561 return -1;
563 if (!WRA_WAS_ADDED(dirserv_add_descriptor(ri, &m))) {
564 log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
565 m?m:"<unknown error>");
566 return -1;
571 /* 5. Dump fingerprint to 'fingerprint' */
572 keydir = get_datadir_fname("fingerprint");
573 log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
574 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
575 log_err(LD_GENERAL,"Error computing fingerprint");
576 tor_free(keydir);
577 return -1;
579 tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
580 if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
581 "%s %s\n",options->Nickname, fingerprint) < 0) {
582 log_err(LD_GENERAL,"Error writing fingerprint line");
583 tor_free(keydir);
584 return -1;
586 /* Check whether we need to write the fingerprint file. */
587 cp = NULL;
588 if (file_status(keydir) == FN_FILE)
589 cp = read_file_to_str(keydir, 0, NULL);
590 if (!cp || strcmp(cp, fingerprint_line)) {
591 if (write_str_to_file(keydir, fingerprint_line, 0)) {
592 log_err(LD_FS, "Error writing fingerprint line to file");
593 tor_free(keydir);
594 return -1;
597 tor_free(cp);
598 tor_free(keydir);
600 log(LOG_NOTICE, LD_GENERAL,
601 "Your Tor server's identity key fingerprint is '%s %s'",
602 options->Nickname, fingerprint);
603 if (!authdir_mode(options))
604 return 0;
605 /* 6. [authdirserver only] load approved-routers file */
606 if (dirserv_load_fingerprint_file() < 0) {
607 log_err(LD_GENERAL,"Error loading fingerprints");
608 return -1;
610 /* 6b. [authdirserver only] add own key to approved directories. */
611 crypto_pk_get_digest(get_identity_key(), digest);
612 type = ((options->V1AuthoritativeDir ? V1_AUTHORITY : NO_AUTHORITY) |
613 (options->V2AuthoritativeDir ? V2_AUTHORITY : NO_AUTHORITY) |
614 (options->V3AuthoritativeDir ? V3_AUTHORITY : NO_AUTHORITY) |
615 (options->BridgeAuthoritativeDir ? BRIDGE_AUTHORITY : NO_AUTHORITY) |
616 (options->HSAuthoritativeDir ? HIDSERV_AUTHORITY : NO_AUTHORITY));
618 ds = router_get_trusteddirserver_by_digest(digest);
619 if (!ds) {
620 ds = add_trusted_dir_server(options->Nickname, NULL,
621 (uint16_t)options->DirPort,
622 (uint16_t)options->ORPort,
623 digest,
624 v3_digest,
625 type);
626 if (!ds) {
627 log_err(LD_GENERAL,"We want to be a directory authority, but we "
628 "couldn't add ourselves to the authority list. Failing.");
629 return -1;
632 if (ds->type != type) {
633 log_warn(LD_DIR, "Configured authority type does not match authority "
634 "type in DirServer list. Adjusting. (%d v %d)",
635 type, ds->type);
636 ds->type = type;
638 if (v3_digest_set && (ds->type & V3_AUTHORITY) &&
639 memcmp(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
640 log_warn(LD_DIR, "V3 identity key does not match identity declared in "
641 "DirServer line. Adjusting.");
642 memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
645 if (cert) { /* add my own cert to the list of known certs */
646 log_info(LD_DIR, "adding my own v3 cert");
647 if (trusted_dirs_load_certs_from_string(
648 cert->cache_info.signed_descriptor_body, 0, 0)<0) {
649 log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
650 return -1;
654 return 0; /* success */
657 /* Keep track of whether we should upload our server descriptor,
658 * and what type of server we are.
661 /** Whether we can reach our ORPort from the outside. */
662 static int can_reach_or_port = 0;
663 /** Whether we can reach our DirPort from the outside. */
664 static int can_reach_dir_port = 0;
666 /** Forget what we have learned about our reachability status. */
667 void
668 router_reset_reachability(void)
670 can_reach_or_port = can_reach_dir_port = 0;
673 /** Return 1 if ORPort is known reachable; else return 0. */
675 check_whether_orport_reachable(void)
677 or_options_t *options = get_options();
678 return options->AssumeReachable ||
679 can_reach_or_port;
682 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
684 check_whether_dirport_reachable(void)
686 or_options_t *options = get_options();
687 return !options->DirPort ||
688 options->AssumeReachable ||
689 we_are_hibernating() ||
690 can_reach_dir_port;
693 /** Look at a variety of factors, and return 0 if we don't want to
694 * advertise the fact that we have a DirPort open. Else return the
695 * DirPort we want to advertise.
697 * Log a helpful message if we change our mind about whether to publish
698 * a DirPort.
700 static int
701 decide_to_advertise_dirport(or_options_t *options, uint16_t dir_port)
703 static int advertising=1; /* start out assuming we will advertise */
704 int new_choice=1;
705 const char *reason = NULL;
707 /* Section one: reasons to publish or not publish that aren't
708 * worth mentioning to the user, either because they're obvious
709 * or because they're normal behavior. */
711 if (!dir_port) /* short circuit the rest of the function */
712 return 0;
713 if (authdir_mode(options)) /* always publish */
714 return dir_port;
715 if (we_are_hibernating())
716 return 0;
717 if (!check_whether_dirport_reachable())
718 return 0;
720 /* Section two: reasons to publish or not publish that the user
721 * might find surprising. These are generally config options that
722 * make us choose not to publish. */
724 if (accounting_is_enabled(options)) {
725 /* if we might potentially hibernate */
726 new_choice = 0;
727 reason = "AccountingMax enabled";
728 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
729 } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
730 (options->RelayBandwidthRate > 0 &&
731 options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
732 /* if we're advertising a small amount */
733 new_choice = 0;
734 reason = "BandwidthRate under 50KB";
737 if (advertising != new_choice) {
738 if (new_choice == 1) {
739 log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
740 } else {
741 tor_assert(reason);
742 log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
744 advertising = new_choice;
747 return advertising ? dir_port : 0;
750 /** Some time has passed, or we just got new directory information.
751 * See if we currently believe our ORPort or DirPort to be
752 * unreachable. If so, launch a new test for it.
754 * For ORPort, we simply try making a circuit that ends at ourselves.
755 * Success is noticed in onionskin_answer().
757 * For DirPort, we make a connection via Tor to our DirPort and ask
758 * for our own server descriptor.
759 * Success is noticed in connection_dir_client_reached_eof().
761 void
762 consider_testing_reachability(int test_or, int test_dir)
764 routerinfo_t *me = router_get_my_routerinfo();
765 int orport_reachable = check_whether_orport_reachable();
766 tor_addr_t addr;
767 if (!me)
768 return;
770 if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
771 log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
772 !orport_reachable ? "reachability" : "bandwidth",
773 me->address, me->or_port);
774 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me,
775 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
776 control_event_server_status(LOG_NOTICE,
777 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
778 me->address, me->or_port);
781 tor_addr_from_ipv4h(&addr, me->addr);
782 if (test_dir && !check_whether_dirport_reachable() &&
783 !connection_get_by_type_addr_port_purpose(
784 CONN_TYPE_DIR, &addr, me->dir_port,
785 DIR_PURPOSE_FETCH_SERVERDESC)) {
786 /* ask myself, via tor, for my server descriptor. */
787 directory_initiate_command(me->address, &addr,
788 me->or_port, me->dir_port,
789 0, /* does not matter */
790 0, me->cache_info.identity_digest,
791 DIR_PURPOSE_FETCH_SERVERDESC,
792 ROUTER_PURPOSE_GENERAL,
793 1, "authority.z", NULL, 0, 0);
795 control_event_server_status(LOG_NOTICE,
796 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
797 me->address, me->dir_port);
801 /** Annotate that we found our ORPort reachable. */
802 void
803 router_orport_found_reachable(void)
805 if (!can_reach_or_port) {
806 routerinfo_t *me = router_get_my_routerinfo();
807 log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
808 "the outside. Excellent.%s",
809 get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
810 " Publishing server descriptor." : "");
811 can_reach_or_port = 1;
812 mark_my_descriptor_dirty();
813 if (!me)
814 return;
815 control_event_server_status(LOG_NOTICE,
816 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
817 me->address, me->or_port);
821 /** Annotate that we found our DirPort reachable. */
822 void
823 router_dirport_found_reachable(void)
825 if (!can_reach_dir_port) {
826 routerinfo_t *me = router_get_my_routerinfo();
827 log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
828 "from the outside. Excellent.");
829 can_reach_dir_port = 1;
830 if (!me || decide_to_advertise_dirport(get_options(), me->dir_port))
831 mark_my_descriptor_dirty();
832 if (!me)
833 return;
834 control_event_server_status(LOG_NOTICE,
835 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
836 me->address, me->dir_port);
840 /** We have enough testing circuits open. Send a bunch of "drop"
841 * cells down each of them, to exercise our bandwidth. */
842 void
843 router_perform_bandwidth_test(int num_circs, time_t now)
845 int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
846 int max_cells = num_cells < CIRCWINDOW_START ?
847 num_cells : CIRCWINDOW_START;
848 int cells_per_circuit = max_cells / num_circs;
849 origin_circuit_t *circ = NULL;
851 log_notice(LD_OR,"Performing bandwidth self-test...done.");
852 while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
853 CIRCUIT_PURPOSE_TESTING))) {
854 /* dump cells_per_circuit drop cells onto this circ */
855 int i = cells_per_circuit;
856 if (circ->_base.state != CIRCUIT_STATE_OPEN)
857 continue;
858 circ->_base.timestamp_dirty = now;
859 while (i-- > 0) {
860 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
861 RELAY_COMMAND_DROP,
862 NULL, 0, circ->cpath->prev)<0) {
863 return; /* stop if error */
869 /** Return true iff we believe ourselves to be an authoritative
870 * directory server.
873 authdir_mode(or_options_t *options)
875 return options->AuthoritativeDir != 0;
877 /** Return true iff we believe ourselves to be a v1 authoritative
878 * directory server.
881 authdir_mode_v1(or_options_t *options)
883 return authdir_mode(options) && options->V1AuthoritativeDir != 0;
885 /** Return true iff we believe ourselves to be a v2 authoritative
886 * directory server.
889 authdir_mode_v2(or_options_t *options)
891 return authdir_mode(options) && options->V2AuthoritativeDir != 0;
893 /** Return true iff we believe ourselves to be a v3 authoritative
894 * directory server.
897 authdir_mode_v3(or_options_t *options)
899 return authdir_mode(options) && options->V3AuthoritativeDir != 0;
901 /** Return true iff we are a v1, v2, or v3 directory authority. */
903 authdir_mode_any_main(or_options_t *options)
905 return options->V1AuthoritativeDir ||
906 options->V2AuthoritativeDir ||
907 options->V3AuthoritativeDir;
909 /** Return true if we believe ourselves to be any kind of
910 * authoritative directory beyond just a hidserv authority. */
912 authdir_mode_any_nonhidserv(or_options_t *options)
914 return options->BridgeAuthoritativeDir ||
915 authdir_mode_any_main(options);
917 /** Return true iff we are an authoritative directory server that is
918 * authoritative about receiving and serving descriptors of type
919 * <b>purpose</b> its dirport. Use -1 for "any purpose". */
921 authdir_mode_handles_descs(or_options_t *options, int purpose)
923 if (purpose < 0)
924 return authdir_mode_any_nonhidserv(options);
925 else if (purpose == ROUTER_PURPOSE_GENERAL)
926 return authdir_mode_any_main(options);
927 else if (purpose == ROUTER_PURPOSE_BRIDGE)
928 return (options->BridgeAuthoritativeDir);
929 else
930 return 0;
932 /** Return true iff we are an authoritative directory server that
933 * publishes its own network statuses.
936 authdir_mode_publishes_statuses(or_options_t *options)
938 if (authdir_mode_bridge(options))
939 return 0;
940 return authdir_mode_any_nonhidserv(options);
942 /** Return true iff we are an authoritative directory server that
943 * tests reachability of the descriptors it learns about.
946 authdir_mode_tests_reachability(or_options_t *options)
948 return authdir_mode_handles_descs(options, -1);
950 /** Return true iff we believe ourselves to be a bridge authoritative
951 * directory server.
954 authdir_mode_bridge(or_options_t *options)
956 return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
958 /** Return true iff we once tried to stay connected to all ORs at once.
959 * FFFF this function, and the notion of staying connected to ORs, is
960 * nearly obsolete. One day there will be a proposal for getting rid of
961 * it.
964 clique_mode(or_options_t *options)
966 return authdir_mode_tests_reachability(options);
969 /** Return true iff we are trying to be a server.
972 server_mode(or_options_t *options)
974 if (options->ClientOnly) return 0;
975 return (options->ORPort != 0 || options->ORListenAddress);
978 /** Remember if we've advertised ourselves to the dirservers. */
979 static int server_is_advertised=0;
981 /** Return true iff we have published our descriptor lately.
984 advertised_server_mode(void)
986 return server_is_advertised;
990 * Called with a boolean: set whether we have recently published our
991 * descriptor.
993 static void
994 set_server_advertised(int s)
996 server_is_advertised = s;
999 /** Return true iff we are trying to be a socks proxy. */
1001 proxy_mode(or_options_t *options)
1003 return (options->SocksPort != 0 || options->SocksListenAddress ||
1004 options->TransPort != 0 || options->TransListenAddress ||
1005 options->NatdPort != 0 || options->NatdListenAddress ||
1006 options->DNSPort != 0 || options->DNSListenAddress);
1009 /** Decide if we're a publishable server. We are a publishable server if:
1010 * - We don't have the ClientOnly option set
1011 * and
1012 * - We have the PublishServerDescriptor option set to non-empty
1013 * and
1014 * - We have ORPort set
1015 * and
1016 * - We believe we are reachable from the outside; or
1017 * - We are an authoritative directory server.
1019 static int
1020 decide_if_publishable_server(void)
1022 or_options_t *options = get_options();
1024 if (options->ClientOnly)
1025 return 0;
1026 if (options->_PublishServerDescriptor == NO_AUTHORITY)
1027 return 0;
1028 if (!server_mode(options))
1029 return 0;
1030 if (authdir_mode(options))
1031 return 1;
1033 return check_whether_orport_reachable();
1036 /** Initiate server descriptor upload as reasonable (if server is publishable,
1037 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1039 * We need to rebuild the descriptor if it's dirty even if we're not
1040 * uploading, because our reachability testing *uses* our descriptor to
1041 * determine what IP address and ports to test.
1043 void
1044 consider_publishable_server(int force)
1046 int rebuilt;
1048 if (!server_mode(get_options()))
1049 return;
1051 rebuilt = router_rebuild_descriptor(0);
1052 if (decide_if_publishable_server()) {
1053 set_server_advertised(1);
1054 if (rebuilt == 0)
1055 router_upload_dir_desc_to_dirservers(force);
1056 } else {
1057 set_server_advertised(0);
1062 * Clique maintenance -- to be phased out.
1065 /** Return true iff we believe this OR tries to keep connections open
1066 * to all other ORs. */
1068 router_is_clique_mode(routerinfo_t *router)
1070 if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
1071 return 1;
1072 return 0;
1076 * OR descriptor generation.
1079 /** My routerinfo. */
1080 static routerinfo_t *desc_routerinfo = NULL;
1081 /** My extrainfo */
1082 static extrainfo_t *desc_extrainfo = NULL;
1083 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1084 * now. */
1085 static time_t desc_clean_since = 0;
1086 /** Boolean: do we need to regenerate the above? */
1087 static int desc_needs_upload = 0;
1089 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1090 * descriptor successfully yet, try to upload our signed descriptor to
1091 * all the directory servers we know about.
1093 void
1094 router_upload_dir_desc_to_dirservers(int force)
1096 routerinfo_t *ri;
1097 extrainfo_t *ei;
1098 char *msg;
1099 size_t desc_len, extra_len = 0, total_len;
1100 authority_type_t auth = get_options()->_PublishServerDescriptor;
1102 ri = router_get_my_routerinfo();
1103 if (!ri) {
1104 log_info(LD_GENERAL, "No descriptor; skipping upload");
1105 return;
1107 ei = router_get_my_extrainfo();
1108 if (auth == NO_AUTHORITY)
1109 return;
1110 if (!force && !desc_needs_upload)
1111 return;
1112 desc_needs_upload = 0;
1114 desc_len = ri->cache_info.signed_descriptor_len;
1115 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1116 total_len = desc_len + extra_len + 1;
1117 msg = tor_malloc(total_len);
1118 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1119 if (ei) {
1120 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1122 msg[desc_len+extra_len] = 0;
1124 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
1125 (auth & BRIDGE_AUTHORITY) ?
1126 ROUTER_PURPOSE_BRIDGE :
1127 ROUTER_PURPOSE_GENERAL,
1128 auth, msg, desc_len, extra_len);
1129 tor_free(msg);
1132 /** OR only: Check whether my exit policy says to allow connection to
1133 * conn. Return 0 if we accept; non-0 if we reject.
1136 router_compare_to_my_exit_policy(edge_connection_t *conn)
1138 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1139 return -1;
1141 /* make sure it's resolved to something. this way we can't get a
1142 'maybe' below. */
1143 if (tor_addr_is_null(&conn->_base.addr))
1144 return -1;
1146 /* XXXX IPv6 */
1147 if (tor_addr_family(&conn->_base.addr) != AF_INET)
1148 return -1;
1150 return compare_tor_addr_to_addr_policy(&conn->_base.addr, conn->_base.port,
1151 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
1154 /** Return true iff I'm a server and <b>digest</b> is equal to
1155 * my identity digest. */
1157 router_digest_is_me(const char *digest)
1159 return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
1162 /** Return true iff I'm a server and <b>digest</b> is equal to
1163 * my identity digest. */
1165 router_extrainfo_digest_is_me(const char *digest)
1167 extrainfo_t *ei = router_get_my_extrainfo();
1168 if (!ei)
1169 return 0;
1171 return !memcmp(digest,
1172 ei->cache_info.signed_descriptor_digest,
1173 DIGEST_LEN);
1176 /** A wrapper around router_digest_is_me(). */
1178 router_is_me(routerinfo_t *router)
1180 return router_digest_is_me(router->cache_info.identity_digest);
1183 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1185 router_fingerprint_is_me(const char *fp)
1187 char digest[DIGEST_LEN];
1188 if (strlen(fp) == HEX_DIGEST_LEN &&
1189 base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
1190 return router_digest_is_me(digest);
1192 return 0;
1195 /** Return a routerinfo for this OR, rebuilding a fresh one if
1196 * necessary. Return NULL on error, or if called on an OP. */
1197 routerinfo_t *
1198 router_get_my_routerinfo(void)
1200 if (!server_mode(get_options()))
1201 return NULL;
1202 if (router_rebuild_descriptor(0))
1203 return NULL;
1204 return desc_routerinfo;
1207 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1208 * one if necessary. Return NULL on error.
1210 const char *
1211 router_get_my_descriptor(void)
1213 const char *body;
1214 if (!router_get_my_routerinfo())
1215 return NULL;
1216 /* Make sure this is nul-terminated. */
1217 tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
1218 body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
1219 tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
1220 log_debug(LD_GENERAL,"my desc is '%s'", body);
1221 return body;
1224 /** Return the extrainfo document for this OR, or NULL if we have none.
1225 * Rebuilt it (and the server descriptor) if necessary. */
1226 extrainfo_t *
1227 router_get_my_extrainfo(void)
1229 if (!server_mode(get_options()))
1230 return NULL;
1231 if (router_rebuild_descriptor(0))
1232 return NULL;
1233 return desc_extrainfo;
1236 /** A list of nicknames that we've warned about including in our family
1237 * declaration verbatim rather than as digests. */
1238 static smartlist_t *warned_nonexistent_family = NULL;
1240 static int router_guess_address_from_dir_headers(uint32_t *guess);
1242 /** Make a current best guess at our address, either because
1243 * it's configured in torrc, or because we've learned it from
1244 * dirserver headers. Place the answer in *<b>addr</b> and return
1245 * 0 on success, else return -1 if we have no guess. */
1247 router_pick_published_address(or_options_t *options, uint32_t *addr)
1249 if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
1250 log_info(LD_CONFIG, "Could not determine our address locally. "
1251 "Checking if directory headers provide any hints.");
1252 if (router_guess_address_from_dir_headers(addr) < 0) {
1253 log_info(LD_CONFIG, "No hints from directory headers either. "
1254 "Will try again later.");
1255 return -1;
1258 return 0;
1261 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1262 * routerinfo, signed server descriptor, and extra-info document for this OR.
1263 * Return 0 on success, -1 on temporary error.
1266 router_rebuild_descriptor(int force)
1268 routerinfo_t *ri;
1269 extrainfo_t *ei;
1270 uint32_t addr;
1271 char platform[256];
1272 int hibernating = we_are_hibernating();
1273 or_options_t *options = get_options();
1275 if (desc_clean_since && !force)
1276 return 0;
1278 if (router_pick_published_address(options, &addr) < 0) {
1279 /* Stop trying to rebuild our descriptor every second. We'll
1280 * learn that it's time to try again when server_has_changed_ip()
1281 * marks it dirty. */
1282 desc_clean_since = time(NULL);
1283 return -1;
1286 ri = tor_malloc_zero(sizeof(routerinfo_t));
1287 ri->cache_info.routerlist_index = -1;
1288 ri->address = tor_dup_ip(addr);
1289 ri->nickname = tor_strdup(options->Nickname);
1290 ri->addr = addr;
1291 ri->or_port = options->ORPort;
1292 ri->dir_port = options->DirPort;
1293 ri->cache_info.published_on = time(NULL);
1294 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
1295 * main thread */
1296 ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
1297 if (crypto_pk_get_digest(ri->identity_pkey,
1298 ri->cache_info.identity_digest)<0) {
1299 routerinfo_free(ri);
1300 return -1;
1302 get_platform_str(platform, sizeof(platform));
1303 ri->platform = tor_strdup(platform);
1305 /* compute ri->bandwidthrate as the min of various options */
1306 ri->bandwidthrate = (int)options->BandwidthRate;
1307 if (ri->bandwidthrate > options->MaxAdvertisedBandwidth)
1308 ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
1309 if (options->RelayBandwidthRate > 0 &&
1310 ri->bandwidthrate > options->RelayBandwidthRate)
1311 ri->bandwidthrate = (int)options->RelayBandwidthRate;
1313 /* and compute ri->bandwidthburst similarly */
1314 ri->bandwidthburst = (int)options->BandwidthBurst;
1315 if (options->RelayBandwidthBurst > 0 &&
1316 ri->bandwidthburst > options->RelayBandwidthBurst)
1317 ri->bandwidthburst = (int)options->RelayBandwidthBurst;
1319 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
1321 policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
1322 options->ExitPolicyRejectPrivate,
1323 ri->address);
1325 if (desc_routerinfo) { /* inherit values */
1326 ri->is_valid = desc_routerinfo->is_valid;
1327 ri->is_running = desc_routerinfo->is_running;
1328 ri->is_named = desc_routerinfo->is_named;
1330 if (authdir_mode(options))
1331 ri->is_valid = ri->is_named = 1; /* believe in yourself */
1332 if (options->MyFamily) {
1333 smartlist_t *family;
1334 if (!warned_nonexistent_family)
1335 warned_nonexistent_family = smartlist_create();
1336 family = smartlist_create();
1337 ri->declared_family = smartlist_create();
1338 smartlist_split_string(family, options->MyFamily, ",",
1339 SPLIT_SKIP_SPACE|SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1340 SMARTLIST_FOREACH(family, char *, name,
1342 routerinfo_t *member;
1343 if (!strcasecmp(name, options->Nickname))
1344 member = ri;
1345 else
1346 member = router_get_by_nickname(name, 1);
1347 if (!member) {
1348 int is_legal = is_legal_nickname_or_hexdigest(name);
1349 if (!smartlist_string_isin(warned_nonexistent_family, name) &&
1350 !is_legal_hexdigest(name)) {
1351 if (is_legal)
1352 log_warn(LD_CONFIG,
1353 "I have no descriptor for the router named \"%s\" in my "
1354 "declared family; I'll use the nickname as is, but "
1355 "this may confuse clients.", name);
1356 else
1357 log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
1358 "declared family, but that isn't a legal nickname. "
1359 "Skipping it.", escaped(name));
1360 smartlist_add(warned_nonexistent_family, tor_strdup(name));
1362 if (is_legal) {
1363 smartlist_add(ri->declared_family, name);
1364 name = NULL;
1366 } else if (router_is_me(member)) {
1367 /* Don't list ourself in our own family; that's redundant */
1368 } else {
1369 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1370 fp[0] = '$';
1371 base16_encode(fp+1,HEX_DIGEST_LEN+1,
1372 member->cache_info.identity_digest, DIGEST_LEN);
1373 smartlist_add(ri->declared_family, fp);
1374 if (smartlist_string_isin(warned_nonexistent_family, name))
1375 smartlist_string_remove(warned_nonexistent_family, name);
1377 tor_free(name);
1380 /* remove duplicates from the list */
1381 smartlist_sort_strings(ri->declared_family);
1382 smartlist_uniq_strings(ri->declared_family);
1384 smartlist_free(family);
1387 /* Now generate the extrainfo. */
1388 ei = tor_malloc_zero(sizeof(extrainfo_t));
1389 ei->cache_info.is_extrainfo = 1;
1390 strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
1391 ei->cache_info.published_on = ri->cache_info.published_on;
1392 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
1393 DIGEST_LEN);
1394 ei->cache_info.signed_descriptor_body = tor_malloc(8192);
1395 if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body, 8192,
1396 ei, get_identity_key()) < 0) {
1397 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
1398 extrainfo_free(ei);
1399 return -1;
1401 ei->cache_info.signed_descriptor_len =
1402 strlen(ei->cache_info.signed_descriptor_body);
1403 router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
1404 ei->cache_info.signed_descriptor_digest);
1406 /* Now finish the router descriptor. */
1407 memcpy(ri->cache_info.extra_info_digest,
1408 ei->cache_info.signed_descriptor_digest,
1409 DIGEST_LEN);
1410 ri->cache_info.signed_descriptor_body = tor_malloc(8192);
1411 if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
1412 ri, get_identity_key())<0) {
1413 log_warn(LD_BUG, "Couldn't generate router descriptor.");
1414 return -1;
1416 ri->cache_info.signed_descriptor_len =
1417 strlen(ri->cache_info.signed_descriptor_body);
1419 ri->purpose =
1420 options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
1421 ri->cache_info.send_unencrypted = 1;
1422 /* Let bridges serve their own descriptors unencrypted, so they can
1423 * pass reachability testing. (If they want to be harder to notice,
1424 * they can always leave the DirPort off). */
1425 if (!options->BridgeRelay)
1426 ei->cache_info.send_unencrypted = 1;
1428 router_get_router_hash(ri->cache_info.signed_descriptor_body,
1429 ri->cache_info.signed_descriptor_digest);
1431 routerinfo_set_country(ri);
1433 tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
1435 if (desc_routerinfo)
1436 routerinfo_free(desc_routerinfo);
1437 desc_routerinfo = ri;
1438 if (desc_extrainfo)
1439 extrainfo_free(desc_extrainfo);
1440 desc_extrainfo = ei;
1442 desc_clean_since = time(NULL);
1443 desc_needs_upload = 1;
1444 control_event_my_descriptor_changed();
1445 return 0;
1448 /** Mark descriptor out of date if it's older than <b>when</b> */
1449 void
1450 mark_my_descriptor_dirty_if_older_than(time_t when)
1452 if (desc_clean_since < when)
1453 mark_my_descriptor_dirty();
1456 /** Call when the current descriptor is out of date. */
1457 void
1458 mark_my_descriptor_dirty(void)
1460 desc_clean_since = 0;
1463 /** How frequently will we republish our descriptor because of large (factor
1464 * of 2) shifts in estimated bandwidth? */
1465 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
1467 /** Check whether bandwidth has changed a lot since the last time we announced
1468 * bandwidth. If so, mark our descriptor dirty. */
1469 void
1470 check_descriptor_bandwidth_changed(time_t now)
1472 static time_t last_changed = 0;
1473 uint64_t prev, cur;
1474 if (!desc_routerinfo)
1475 return;
1477 prev = desc_routerinfo->bandwidthcapacity;
1478 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
1479 if ((prev != cur && (!prev || !cur)) ||
1480 cur > prev*2 ||
1481 cur < prev/2) {
1482 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
1483 log_info(LD_GENERAL,
1484 "Measured bandwidth has changed; rebuilding descriptor.");
1485 mark_my_descriptor_dirty();
1486 last_changed = now;
1491 /** Note at log level severity that our best guess of address has changed from
1492 * <b>prev</b> to <b>cur</b>. */
1493 static void
1494 log_addr_has_changed(int severity, uint32_t prev, uint32_t cur,
1495 const char *source)
1497 char addrbuf_prev[INET_NTOA_BUF_LEN];
1498 char addrbuf_cur[INET_NTOA_BUF_LEN];
1499 struct in_addr in_prev;
1500 struct in_addr in_cur;
1502 in_prev.s_addr = htonl(prev);
1503 tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
1505 in_cur.s_addr = htonl(cur);
1506 tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
1508 if (prev)
1509 log_fn(severity, LD_GENERAL,
1510 "Our IP Address has changed from %s to %s; "
1511 "rebuilding descriptor (source: %s).",
1512 addrbuf_prev, addrbuf_cur, source);
1513 else
1514 log_notice(LD_GENERAL,
1515 "Guessed our IP address as %s.",
1516 addrbuf_cur);
1519 /** Check whether our own address as defined by the Address configuration
1520 * has changed. This is for routers that get their address from a service
1521 * like dyndns. If our address has changed, mark our descriptor dirty. */
1522 void
1523 check_descriptor_ipaddress_changed(time_t now)
1525 uint32_t prev, cur;
1526 or_options_t *options = get_options();
1527 (void) now;
1529 if (!desc_routerinfo)
1530 return;
1532 prev = desc_routerinfo->addr;
1533 if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
1534 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
1535 return;
1538 if (prev != cur) {
1539 log_addr_has_changed(LOG_INFO, prev, cur, "resolve");
1540 ip_address_changed(0);
1544 /** The most recently guessed value of our IP address, based on directory
1545 * headers. */
1546 static uint32_t last_guessed_ip = 0;
1548 /** A directory server <b>d_conn</b> told us our IP address is
1549 * <b>suggestion</b>.
1550 * If this address is different from the one we think we are now, and
1551 * if our computer doesn't actually know its IP address, then switch. */
1552 void
1553 router_new_address_suggestion(const char *suggestion,
1554 const dir_connection_t *d_conn)
1556 uint32_t addr, cur = 0;
1557 struct in_addr in;
1558 or_options_t *options = get_options();
1560 /* first, learn what the IP address actually is */
1561 if (!tor_inet_aton(suggestion, &in)) {
1562 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
1563 escaped(suggestion));
1564 return;
1566 addr = ntohl(in.s_addr);
1568 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
1570 if (!server_mode(options)) {
1571 last_guessed_ip = addr; /* store it in case we need it later */
1572 return;
1575 if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
1576 /* We're all set -- we already know our address. Great. */
1577 last_guessed_ip = cur; /* store it in case we need it later */
1578 return;
1580 if (is_internal_IP(addr, 0)) {
1581 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1582 return;
1584 if (tor_addr_eq_ipv4h(&d_conn->_base.addr, addr)) {
1585 /* Don't believe anybody who says our IP is their IP. */
1586 log_debug(LD_DIR, "A directory server told us our IP address is %s, "
1587 "but he's just reporting his own IP address. Ignoring.",
1588 suggestion);
1589 return;
1592 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1593 * us an answer different from what we had the last time we managed to
1594 * resolve it. */
1595 if (last_guessed_ip != addr) {
1596 control_event_server_status(LOG_NOTICE,
1597 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1598 suggestion);
1599 log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr,
1600 d_conn->_base.address);
1601 ip_address_changed(0);
1602 last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
1606 /** We failed to resolve our address locally, but we'd like to build
1607 * a descriptor and publish / test reachability. If we have a guess
1608 * about our address based on directory headers, answer it and return
1609 * 0; else return -1. */
1610 static int
1611 router_guess_address_from_dir_headers(uint32_t *guess)
1613 if (last_guessed_ip) {
1614 *guess = last_guessed_ip;
1615 return 0;
1617 return -1;
1620 extern const char tor_svn_revision[]; /* from tor_main.c */
1622 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1623 * string describing the version of Tor and the operating system we're
1624 * currently running on.
1626 void
1627 get_platform_str(char *platform, size_t len)
1629 tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
1632 /* XXX need to audit this thing and count fenceposts. maybe
1633 * refactor so we don't have to keep asking if we're
1634 * near the end of maxlen?
1636 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1638 /** OR only: Given a routerinfo for this router, and an identity key to sign
1639 * with, encode the routerinfo as a signed server descriptor and write the
1640 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1641 * failure, and the number of bytes used on success.
1644 router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
1645 crypto_pk_env_t *ident_key)
1647 char *onion_pkey; /* Onion key, PEM-encoded. */
1648 char *identity_pkey; /* Identity key, PEM-encoded. */
1649 char digest[DIGEST_LEN];
1650 char published[ISO_TIME_LEN+1];
1651 char fingerprint[FINGERPRINT_LEN+1];
1652 char extra_info_digest[HEX_DIGEST_LEN+1];
1653 size_t onion_pkeylen, identity_pkeylen;
1654 size_t written;
1655 int result=0;
1656 addr_policy_t *tmpe;
1657 char *family_line;
1658 or_options_t *options = get_options();
1660 /* Make sure the identity key matches the one in the routerinfo. */
1661 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
1662 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
1663 "match router's public key!");
1664 return -1;
1667 /* record our fingerprint, so we can include it in the descriptor */
1668 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
1669 log_err(LD_BUG,"Error computing fingerprint");
1670 return -1;
1673 /* PEM-encode the onion key */
1674 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
1675 &onion_pkey,&onion_pkeylen)<0) {
1676 log_warn(LD_BUG,"write onion_pkey to string failed!");
1677 return -1;
1680 /* PEM-encode the identity key key */
1681 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
1682 &identity_pkey,&identity_pkeylen)<0) {
1683 log_warn(LD_BUG,"write identity_pkey to string failed!");
1684 tor_free(onion_pkey);
1685 return -1;
1688 /* Encode the publication time. */
1689 format_iso_time(published, router->cache_info.published_on);
1691 if (router->declared_family && smartlist_len(router->declared_family)) {
1692 size_t n;
1693 char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
1694 n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1695 family_line = tor_malloc(n);
1696 tor_snprintf(family_line, n, "family %s\n", family);
1697 tor_free(family);
1698 } else {
1699 family_line = tor_strdup("");
1702 base16_encode(extra_info_digest, sizeof(extra_info_digest),
1703 router->cache_info.extra_info_digest, DIGEST_LEN);
1705 /* Generate the easy portion of the router descriptor. */
1706 result = tor_snprintf(s, maxlen,
1707 "router %s %s %d 0 %d\n"
1708 "platform %s\n"
1709 "opt protocols Link 1 2 Circuit 1\n"
1710 "published %s\n"
1711 "opt fingerprint %s\n"
1712 "uptime %ld\n"
1713 "bandwidth %d %d %d\n"
1714 "opt extra-info-digest %s\n%s"
1715 "onion-key\n%s"
1716 "signing-key\n%s"
1717 "%s%s%s%s",
1718 router->nickname,
1719 router->address,
1720 router->or_port,
1721 decide_to_advertise_dirport(options, router->dir_port),
1722 router->platform,
1723 published,
1724 fingerprint,
1725 stats_n_seconds_working,
1726 (int) router->bandwidthrate,
1727 (int) router->bandwidthburst,
1728 (int) router->bandwidthcapacity,
1729 extra_info_digest,
1730 options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
1731 onion_pkey, identity_pkey,
1732 family_line,
1733 we_are_hibernating() ? "opt hibernating 1\n" : "",
1734 options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "",
1735 options->AllowSingleHopExits ? "opt allow-single-hop-exits\n" : "");
1737 tor_free(family_line);
1738 tor_free(onion_pkey);
1739 tor_free(identity_pkey);
1741 if (result < 0) {
1742 log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
1743 return -1;
1745 /* From now on, we use 'written' to remember the current length of 's'. */
1746 written = result;
1748 if (options->ContactInfo && strlen(options->ContactInfo)) {
1749 const char *ci = options->ContactInfo;
1750 if (strchr(ci, '\n') || strchr(ci, '\r'))
1751 ci = escaped(ci);
1752 result = tor_snprintf(s+written,maxlen-written, "contact %s\n", ci);
1753 if (result<0) {
1754 log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
1755 return -1;
1757 written += result;
1760 /* Write the exit policy to the end of 's'. */
1761 if (dns_seems_to_be_broken() || has_dns_init_failed() ||
1762 !router->exit_policy || !smartlist_len(router->exit_policy)) {
1763 /* DNS is screwed up; don't claim to be an exit. */
1764 strlcat(s+written, "reject *:*\n", maxlen-written);
1765 written += strlen("reject *:*\n");
1766 tmpe = NULL;
1767 } else if (router->exit_policy) {
1768 int i;
1769 for (i = 0; i < smartlist_len(router->exit_policy); ++i) {
1770 tmpe = smartlist_get(router->exit_policy, i);
1771 result = policy_write_item(s+written, maxlen-written, tmpe, 1);
1772 if (result < 0) {
1773 log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
1774 return -1;
1776 tor_assert(result == (int)strlen(s+written));
1777 written += result;
1778 if (written+2 > maxlen) {
1779 log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
1780 return -1;
1782 s[written++] = '\n';
1786 if (written+256 > maxlen) { /* Not enough room for signature. */
1787 log_warn(LD_BUG,"not enough room left in descriptor for signature!");
1788 return -1;
1791 /* Sign the directory */
1792 strlcpy(s+written, "router-signature\n", maxlen-written);
1793 written += strlen(s+written);
1794 s[written] = '\0';
1795 if (router_get_router_hash(s, digest) < 0) {
1796 return -1;
1799 note_crypto_pk_op(SIGN_RTR);
1800 if (router_append_dirobj_signature(s+written,maxlen-written,
1801 digest,ident_key)<0) {
1802 log_warn(LD_BUG, "Couldn't sign router descriptor");
1803 return -1;
1805 written += strlen(s+written);
1807 if (written+2 > maxlen) {
1808 log_warn(LD_BUG,"Not enough room to finish descriptor.");
1809 return -1;
1811 /* include a last '\n' */
1812 s[written] = '\n';
1813 s[written+1] = 0;
1815 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1817 char *s_dup;
1818 const char *cp;
1819 routerinfo_t *ri_tmp;
1820 cp = s_dup = tor_strdup(s);
1821 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
1822 if (!ri_tmp) {
1823 log_err(LD_BUG,
1824 "We just generated a router descriptor we can't parse.");
1825 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1826 return -1;
1828 tor_free(s_dup);
1829 routerinfo_free(ri_tmp);
1831 #endif
1833 return (int)written+1;
1836 /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
1837 * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
1838 * negative on failure. */
1840 extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
1841 crypto_pk_env_t *ident_key)
1843 or_options_t *options = get_options();
1844 char identity[HEX_DIGEST_LEN+1];
1845 char published[ISO_TIME_LEN+1];
1846 char digest[DIGEST_LEN];
1847 char *bandwidth_usage;
1848 int result;
1849 size_t len;
1851 base16_encode(identity, sizeof(identity),
1852 extrainfo->cache_info.identity_digest, DIGEST_LEN);
1853 format_iso_time(published, extrainfo->cache_info.published_on);
1854 bandwidth_usage = rep_hist_get_bandwidth_lines(1);
1856 result = tor_snprintf(s, maxlen,
1857 "extra-info %s %s\n"
1858 "published %s\n%s",
1859 extrainfo->nickname, identity,
1860 published, bandwidth_usage);
1861 tor_free(bandwidth_usage);
1862 if (result<0)
1863 return -1;
1865 if (should_record_bridge_info(options)) {
1866 char *geoip_summary = extrainfo_get_client_geoip_summary(time(NULL));
1867 if (geoip_summary) {
1868 char geoip_start[ISO_TIME_LEN+1];
1869 format_iso_time(geoip_start, geoip_get_history_start());
1870 result = tor_snprintf(s+strlen(s), maxlen-strlen(s),
1871 "geoip-start-time %s\n"
1872 "geoip-client-origins %s\n",
1873 geoip_start, geoip_summary);
1874 control_event_clients_seen(geoip_start, geoip_summary);
1875 tor_free(geoip_summary);
1876 if (result<0)
1877 return -1;
1881 len = strlen(s);
1882 strlcat(s+len, "router-signature\n", maxlen-len);
1883 len += strlen(s+len);
1884 if (router_get_extrainfo_hash(s, digest)<0)
1885 return -1;
1886 if (router_append_dirobj_signature(s+len, maxlen-len, digest, ident_key)<0)
1887 return -1;
1889 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1891 char *cp, *s_dup;
1892 extrainfo_t *ei_tmp;
1893 cp = s_dup = tor_strdup(s);
1894 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
1895 if (!ei_tmp) {
1896 log_err(LD_BUG,
1897 "We just generated an extrainfo descriptor we can't parse.");
1898 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1899 return -1;
1901 tor_free(s_dup);
1902 extrainfo_free(ei_tmp);
1904 #endif
1906 return (int)strlen(s)+1;
1909 /** Wrapper function for geoip_get_client_history(). It first discards
1910 * any items in the client history that are too old -- it dumps anything
1911 * more than 48 hours old, but it only considers whether to dump at most
1912 * once per 48 hours, so we aren't too precise to an observer (see also
1913 * r14780).
1915 char *
1916 extrainfo_get_client_geoip_summary(time_t now)
1918 static time_t last_purged_at = 0;
1919 int geoip_purge_interval = 48*60*60;
1920 #ifdef ENABLE_GEOIP_STATS
1921 if (get_options()->DirRecordUsageByCountry)
1922 geoip_purge_interval = get_options()->DirRecordUsageRetainIPs;
1923 #endif
1924 if (now > last_purged_at+geoip_purge_interval) {
1925 geoip_remove_old_clients(now-geoip_purge_interval);
1926 last_purged_at = now;
1928 return geoip_get_client_history(now, GEOIP_CLIENT_CONNECT);
1931 /** Return true iff <b>s</b> is a legally valid server nickname. */
1933 is_legal_nickname(const char *s)
1935 size_t len;
1936 tor_assert(s);
1937 len = strlen(s);
1938 return len > 0 && len <= MAX_NICKNAME_LEN &&
1939 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
1942 /** Return true iff <b>s</b> is a legally valid server nickname or
1943 * hex-encoded identity-key digest. */
1945 is_legal_nickname_or_hexdigest(const char *s)
1947 if (*s!='$')
1948 return is_legal_nickname(s);
1949 else
1950 return is_legal_hexdigest(s);
1953 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
1954 * digest. */
1956 is_legal_hexdigest(const char *s)
1958 size_t len;
1959 tor_assert(s);
1960 if (s[0] == '$') s++;
1961 len = strlen(s);
1962 if (len > HEX_DIGEST_LEN) {
1963 if (s[HEX_DIGEST_LEN] == '=' ||
1964 s[HEX_DIGEST_LEN] == '~') {
1965 if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
1966 return 0;
1967 } else {
1968 return 0;
1971 return (len >= HEX_DIGEST_LEN &&
1972 strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
1975 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
1976 * verbose representation of the identity of <b>router</b>. The format is:
1977 * A dollar sign.
1978 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
1979 * A "=" if the router is named; a "~" if it is not.
1980 * The router's nickname.
1982 void
1983 router_get_verbose_nickname(char *buf, routerinfo_t *router)
1985 buf[0] = '$';
1986 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
1987 DIGEST_LEN);
1988 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
1989 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
1992 /** Forget that we have issued any router-related warnings, so that we'll
1993 * warn again if we see the same errors. */
1994 void
1995 router_reset_warnings(void)
1997 if (warned_nonexistent_family) {
1998 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1999 smartlist_clear(warned_nonexistent_family);
2003 /** Given a router purpose, convert it to a string. Don't call this on
2004 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
2005 * know its string representation. */
2006 const char *
2007 router_purpose_to_string(uint8_t p)
2009 switch (p)
2011 case ROUTER_PURPOSE_GENERAL: return "general";
2012 case ROUTER_PURPOSE_BRIDGE: return "bridge";
2013 case ROUTER_PURPOSE_CONTROLLER: return "controller";
2014 default:
2015 tor_assert(0);
2017 return NULL;
2020 /** Given a string, convert it to a router purpose. */
2021 uint8_t
2022 router_purpose_from_string(const char *s)
2024 if (!strcmp(s, "general"))
2025 return ROUTER_PURPOSE_GENERAL;
2026 else if (!strcmp(s, "bridge"))
2027 return ROUTER_PURPOSE_BRIDGE;
2028 else if (!strcmp(s, "controller"))
2029 return ROUTER_PURPOSE_CONTROLLER;
2030 else
2031 return ROUTER_PURPOSE_UNKNOWN;
2034 /** Release all static resources held in router.c */
2035 void
2036 router_free_all(void)
2038 if (onionkey)
2039 crypto_free_pk_env(onionkey);
2040 if (lastonionkey)
2041 crypto_free_pk_env(lastonionkey);
2042 if (identitykey)
2043 crypto_free_pk_env(identitykey);
2044 if (key_lock)
2045 tor_mutex_free(key_lock);
2046 if (desc_routerinfo)
2047 routerinfo_free(desc_routerinfo);
2048 if (desc_extrainfo)
2049 extrainfo_free(desc_extrainfo);
2050 if (authority_signing_key)
2051 crypto_free_pk_env(authority_signing_key);
2052 if (authority_key_certificate)
2053 authority_cert_free(authority_key_certificate);
2054 if (legacy_signing_key)
2055 crypto_free_pk_env(legacy_signing_key);
2056 if (legacy_key_certificate)
2057 authority_cert_free(legacy_key_certificate);
2059 if (warned_nonexistent_family) {
2060 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
2061 smartlist_free(warned_nonexistent_family);