Minimal implementation of bridge-distribution-request
[tor.git] / src / or / router.c
blob90b2431a222b5096bafed2186784c0706e5c333b
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-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 #define ROUTER_PRIVATE
9 #include "or.h"
10 #include "circuitbuild.h"
11 #include "circuitlist.h"
12 #include "circuituse.h"
13 #include "config.h"
14 #include "connection.h"
15 #include "control.h"
16 #include "crypto_curve25519.h"
17 #include "directory.h"
18 #include "dirserv.h"
19 #include "dns.h"
20 #include "geoip.h"
21 #include "hibernate.h"
22 #include "main.h"
23 #include "networkstatus.h"
24 #include "nodelist.h"
25 #include "policies.h"
26 #include "relay.h"
27 #include "rephist.h"
28 #include "router.h"
29 #include "routerlist.h"
30 #include "routerparse.h"
31 #include "statefile.h"
32 #include "transports.h"
33 #include "routerset.h"
35 /**
36 * \file router.c
37 * \brief OR functionality, including key maintenance, generating
38 * and uploading server descriptors, retrying OR connections.
39 **/
41 extern long stats_n_seconds_working;
43 /************************************************************/
45 /*****
46 * Key management: ORs only.
47 *****/
49 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
51 static tor_mutex_t *key_lock=NULL;
52 static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
53 /** Current private onionskin decryption key: used to decode CREATE cells. */
54 static crypto_pk_t *onionkey=NULL;
55 /** Previous private onionskin decryption key: used to decode CREATE cells
56 * generated by clients that have an older version of our descriptor. */
57 static crypto_pk_t *lastonionkey=NULL;
58 #ifdef CURVE25519_ENABLED
59 /** Current private ntor secret key: used to perform the ntor handshake. */
60 static curve25519_keypair_t curve25519_onion_key;
61 /** Previous private ntor secret key: used to perform the ntor handshake
62 * with clients that have an older version of our descriptor. */
63 static curve25519_keypair_t last_curve25519_onion_key;
64 #endif
65 /** Private server "identity key": used to sign directory info and TLS
66 * certificates. Never changes. */
67 static crypto_pk_t *server_identitykey=NULL;
68 /** Digest of server_identitykey. */
69 static char server_identitykey_digest[DIGEST_LEN];
70 /** Private client "identity key": used to sign bridges' and clients'
71 * outbound TLS certificates. Regenerated on startup and on IP address
72 * change. */
73 static crypto_pk_t *client_identitykey=NULL;
74 /** Signing key used for v3 directory material; only set for authorities. */
75 static crypto_pk_t *authority_signing_key = NULL;
76 /** Key certificate to authenticate v3 directory material; only set for
77 * authorities. */
78 static authority_cert_t *authority_key_certificate = NULL;
80 /** For emergency V3 authority key migration: An extra signing key that we use
81 * with our old (obsolete) identity key for a while. */
82 static crypto_pk_t *legacy_signing_key = NULL;
83 /** For emergency V3 authority key migration: An extra certificate to
84 * authenticate legacy_signing_key with our obsolete identity key.*/
85 static authority_cert_t *legacy_key_certificate = NULL;
87 /* (Note that v3 authorities also have a separate "authority identity key",
88 * but this key is never actually loaded by the Tor process. Instead, it's
89 * used by tor-gencert to sign new signing keys and make new key
90 * certificates. */
92 /** Replace the current onion key with <b>k</b>. Does not affect
93 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
95 static void
96 set_onion_key(crypto_pk_t *k)
98 if (onionkey && crypto_pk_eq_keys(onionkey, k)) {
99 /* k is already our onion key; free it and return */
100 crypto_pk_free(k);
101 return;
103 tor_mutex_acquire(key_lock);
104 crypto_pk_free(onionkey);
105 onionkey = k;
106 tor_mutex_release(key_lock);
107 mark_my_descriptor_dirty("set onion key");
110 /** Return the current onion key. Requires that the onion key has been
111 * loaded or generated. */
112 crypto_pk_t *
113 get_onion_key(void)
115 tor_assert(onionkey);
116 return onionkey;
119 /** Store a full copy of the current onion key into *<b>key</b>, and a full
120 * copy of the most recent onion key into *<b>last</b>.
122 void
123 dup_onion_keys(crypto_pk_t **key, crypto_pk_t **last)
125 tor_assert(key);
126 tor_assert(last);
127 tor_mutex_acquire(key_lock);
128 tor_assert(onionkey);
129 *key = crypto_pk_copy_full(onionkey);
130 if (lastonionkey)
131 *last = crypto_pk_copy_full(lastonionkey);
132 else
133 *last = NULL;
134 tor_mutex_release(key_lock);
137 #ifdef CURVE25519_ENABLED
138 /** Return the current secret onion key for the ntor handshake. Must only
139 * be called from the main thread. */
140 static const curve25519_keypair_t *
141 get_current_curve25519_keypair(void)
143 return &curve25519_onion_key;
145 /** Return a map from KEYID (the key itself) to keypairs for use in the ntor
146 * handshake. Must only be called from the main thread. */
147 di_digest256_map_t *
148 construct_ntor_key_map(void)
150 di_digest256_map_t *m = NULL;
152 dimap_add_entry(&m,
153 curve25519_onion_key.pubkey.public_key,
154 tor_memdup(&curve25519_onion_key,
155 sizeof(curve25519_keypair_t)));
156 if (!tor_mem_is_zero((const char*)
157 last_curve25519_onion_key.pubkey.public_key,
158 CURVE25519_PUBKEY_LEN)) {
159 dimap_add_entry(&m,
160 last_curve25519_onion_key.pubkey.public_key,
161 tor_memdup(&last_curve25519_onion_key,
162 sizeof(curve25519_keypair_t)));
165 return m;
167 /** Helper used to deallocate a di_digest256_map_t returned by
168 * construct_ntor_key_map. */
169 static void
170 ntor_key_map_free_helper(void *arg)
172 curve25519_keypair_t *k = arg;
173 memwipe(k, 0, sizeof(*k));
174 tor_free(k);
176 /** Release all storage from a keymap returned by construct_ntor_key_map. */
177 void
178 ntor_key_map_free(di_digest256_map_t *map)
180 if (!map)
181 return;
182 dimap_free(map, ntor_key_map_free_helper);
184 #endif
186 /** Return the time when the onion key was last set. This is either the time
187 * when the process launched, or the time of the most recent key rotation since
188 * the process launched.
190 time_t
191 get_onion_key_set_at(void)
193 return onionkey_set_at;
196 /** Set the current server identity key to <b>k</b>.
198 void
199 set_server_identity_key(crypto_pk_t *k)
201 crypto_pk_free(server_identitykey);
202 server_identitykey = k;
203 crypto_pk_get_digest(server_identitykey, server_identitykey_digest);
206 /** Make sure that we have set up our identity keys to match or not match as
207 * appropriate, and die with an assertion if we have not. */
208 static void
209 assert_identity_keys_ok(void)
211 tor_assert(client_identitykey);
212 if (public_server_mode(get_options())) {
213 /* assert that we have set the client and server keys to be equal */
214 tor_assert(server_identitykey);
215 tor_assert(crypto_pk_eq_keys(client_identitykey, server_identitykey));
216 } else {
217 /* assert that we have set the client and server keys to be unequal */
218 if (server_identitykey)
219 tor_assert(!crypto_pk_eq_keys(client_identitykey, server_identitykey));
223 /** Returns the current server identity key; requires that the key has
224 * been set, and that we are running as a Tor server.
226 crypto_pk_t *
227 get_server_identity_key(void)
229 tor_assert(server_identitykey);
230 tor_assert(server_mode(get_options()));
231 assert_identity_keys_ok();
232 return server_identitykey;
235 /** Return true iff we are a server and the server identity key
236 * has been set. */
238 server_identity_key_is_set(void)
240 return server_mode(get_options()) && server_identitykey != NULL;
243 /** Set the current client identity key to <b>k</b>.
245 void
246 set_client_identity_key(crypto_pk_t *k)
248 crypto_pk_free(client_identitykey);
249 client_identitykey = k;
252 /** Returns the current client identity key for use on outgoing TLS
253 * connections; requires that the key has been set.
255 crypto_pk_t *
256 get_tlsclient_identity_key(void)
258 tor_assert(client_identitykey);
259 assert_identity_keys_ok();
260 return client_identitykey;
263 /** Return true iff the client identity key has been set. */
265 client_identity_key_is_set(void)
267 return client_identitykey != NULL;
270 /** Return the key certificate for this v3 (voting) authority, or NULL
271 * if we have no such certificate. */
272 authority_cert_t *
273 get_my_v3_authority_cert(void)
275 return authority_key_certificate;
278 /** Return the v3 signing key for this v3 (voting) authority, or NULL
279 * if we have no such key. */
280 crypto_pk_t *
281 get_my_v3_authority_signing_key(void)
283 return authority_signing_key;
286 /** If we're an authority, and we're using a legacy authority identity key for
287 * emergency migration purposes, return the certificate associated with that
288 * key. */
289 authority_cert_t *
290 get_my_v3_legacy_cert(void)
292 return legacy_key_certificate;
295 /** If we're an authority, and we're using a legacy authority identity key for
296 * emergency migration purposes, return that key. */
297 crypto_pk_t *
298 get_my_v3_legacy_signing_key(void)
300 return legacy_signing_key;
303 /** Replace the previous onion key with the current onion key, and generate
304 * a new previous onion key. Immediately after calling this function,
305 * the OR should:
306 * - schedule all previous cpuworkers to shut down _after_ processing
307 * pending work. (This will cause fresh cpuworkers to be generated.)
308 * - generate and upload a fresh routerinfo.
310 void
311 rotate_onion_key(void)
313 char *fname, *fname_prev;
314 crypto_pk_t *prkey = NULL;
315 or_state_t *state = get_or_state();
316 #ifdef CURVE25519_ENABLED
317 curve25519_keypair_t new_curve25519_keypair;
318 #endif
319 time_t now;
320 fname = get_datadir_fname2("keys", "secret_onion_key");
321 fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
322 if (file_status(fname) == FN_FILE) {
323 if (replace_file(fname, fname_prev))
324 goto error;
326 if (!(prkey = crypto_pk_new())) {
327 log_err(LD_GENERAL,"Error constructing rotated onion key");
328 goto error;
330 if (crypto_pk_generate_key(prkey)) {
331 log_err(LD_BUG,"Error generating onion key");
332 goto error;
334 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
335 log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
336 goto error;
338 #ifdef CURVE25519_ENABLED
339 tor_free(fname);
340 tor_free(fname_prev);
341 fname = get_datadir_fname2("keys", "secret_onion_key_ntor");
342 fname_prev = get_datadir_fname2("keys", "secret_onion_key_ntor.old");
343 if (curve25519_keypair_generate(&new_curve25519_keypair, 1) < 0)
344 goto error;
345 if (file_status(fname) == FN_FILE) {
346 if (replace_file(fname, fname_prev))
347 goto error;
349 if (curve25519_keypair_write_to_file(&new_curve25519_keypair, fname,
350 "onion") < 0) {
351 log_err(LD_FS,"Couldn't write curve25519 onion key to \"%s\".",fname);
352 goto error;
354 #endif
355 log_info(LD_GENERAL, "Rotating onion key");
356 tor_mutex_acquire(key_lock);
357 crypto_pk_free(lastonionkey);
358 lastonionkey = onionkey;
359 onionkey = prkey;
360 #ifdef CURVE25519_ENABLED
361 memcpy(&last_curve25519_onion_key, &curve25519_onion_key,
362 sizeof(curve25519_keypair_t));
363 memcpy(&curve25519_onion_key, &new_curve25519_keypair,
364 sizeof(curve25519_keypair_t));
365 #endif
366 now = time(NULL);
367 state->LastRotatedOnionKey = onionkey_set_at = now;
368 tor_mutex_release(key_lock);
369 mark_my_descriptor_dirty("rotated onion key");
370 or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
371 goto done;
372 error:
373 log_warn(LD_GENERAL, "Couldn't rotate onion key.");
374 if (prkey)
375 crypto_pk_free(prkey);
376 done:
377 #ifdef CURVE25519_ENABLED
378 memwipe(&new_curve25519_keypair, 0, sizeof(new_curve25519_keypair));
379 #endif
380 tor_free(fname);
381 tor_free(fname_prev);
384 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
385 * and <b>generate</b> is true, create a new RSA key and save it in
386 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
387 * errors at level <b>severity</b>.
389 crypto_pk_t *
390 init_key_from_file(const char *fname, int generate, int severity)
392 crypto_pk_t *prkey = NULL;
394 if (!(prkey = crypto_pk_new())) {
395 tor_log(severity, LD_GENERAL,"Error constructing key");
396 goto error;
399 switch (file_status(fname)) {
400 case FN_DIR:
401 case FN_ERROR:
402 tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
403 goto error;
404 case FN_NOENT:
405 if (generate) {
406 if (!have_lockfile()) {
407 if (try_locking(get_options(), 0)<0) {
408 /* Make sure that --list-fingerprint only creates new keys
409 * if there is no possibility for a deadlock. */
410 tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
411 "Not writing any new keys.", fname);
412 /*XXXX The 'other process' might make a key in a second or two;
413 * maybe we should wait for it. */
414 goto error;
417 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
418 fname);
419 if (crypto_pk_generate_key(prkey)) {
420 tor_log(severity, LD_GENERAL,"Error generating onion key");
421 goto error;
423 if (crypto_pk_check_key(prkey) <= 0) {
424 tor_log(severity, LD_GENERAL,"Generated key seems invalid");
425 goto error;
427 log_info(LD_GENERAL, "Generated key seems valid");
428 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
429 tor_log(severity, LD_FS,
430 "Couldn't write generated key to \"%s\".", fname);
431 goto error;
433 } else {
434 log_info(LD_GENERAL, "No key found in \"%s\"", fname);
436 return prkey;
437 case FN_FILE:
438 if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
439 tor_log(severity, LD_GENERAL,"Error loading private key.");
440 goto error;
442 return prkey;
443 default:
444 tor_assert(0);
447 error:
448 if (prkey)
449 crypto_pk_free(prkey);
450 return NULL;
453 #ifdef CURVE25519_ENABLED
454 /** Load a curve25519 keypair from the file <b>fname</b>, writing it into
455 * <b>keys_out</b>. If the file isn't found and <b>generate</b> is true,
456 * create a new keypair and write it into the file. If there are errors, log
457 * them at level <b>severity</b>. Generate files using <b>tag</b> in their
458 * ASCII wrapper. */
459 static int
460 init_curve25519_keypair_from_file(curve25519_keypair_t *keys_out,
461 const char *fname,
462 int generate,
463 int severity,
464 const char *tag)
466 switch (file_status(fname)) {
467 case FN_DIR:
468 case FN_ERROR:
469 tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
470 goto error;
471 case FN_NOENT:
472 if (generate) {
473 if (!have_lockfile()) {
474 if (try_locking(get_options(), 0)<0) {
475 /* Make sure that --list-fingerprint only creates new keys
476 * if there is no possibility for a deadlock. */
477 tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
478 "Not writing any new keys.", fname);
479 /*XXXX The 'other process' might make a key in a second or two;
480 * maybe we should wait for it. */
481 goto error;
484 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
485 fname);
486 if (curve25519_keypair_generate(keys_out, 1) < 0)
487 goto error;
488 if (curve25519_keypair_write_to_file(keys_out, fname, tag)<0) {
489 tor_log(severity, LD_FS,
490 "Couldn't write generated key to \"%s\".", fname);
491 memset(keys_out, 0, sizeof(*keys_out));
492 goto error;
494 } else {
495 log_info(LD_GENERAL, "No key found in \"%s\"", fname);
497 return 0;
498 case FN_FILE:
500 char *tag_in=NULL;
501 if (curve25519_keypair_read_from_file(keys_out, &tag_in, fname) < 0) {
502 tor_log(severity, LD_GENERAL,"Error loading private key.");
503 tor_free(tag_in);
504 goto error;
506 if (!tag_in || strcmp(tag_in, tag)) {
507 tor_log(severity, LD_GENERAL,"Unexpected tag %s on private key.",
508 escaped(tag_in));
509 tor_free(tag_in);
510 goto error;
512 tor_free(tag_in);
513 return 0;
515 default:
516 tor_assert(0);
519 error:
520 return -1;
522 #endif
524 /** Try to load the vote-signing private key and certificate for being a v3
525 * directory authority, and make sure they match. If <b>legacy</b>, load a
526 * legacy key/cert set for emergency key migration; otherwise load the regular
527 * key/cert set. On success, store them into *<b>key_out</b> and
528 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
529 static int
530 load_authority_keyset(int legacy, crypto_pk_t **key_out,
531 authority_cert_t **cert_out)
533 int r = -1;
534 char *fname = NULL, *cert = NULL;
535 const char *eos = NULL;
536 crypto_pk_t *signing_key = NULL;
537 authority_cert_t *parsed = NULL;
539 fname = get_datadir_fname2("keys",
540 legacy ? "legacy_signing_key" : "authority_signing_key");
541 signing_key = init_key_from_file(fname, 0, LOG_INFO);
542 if (!signing_key) {
543 log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
544 goto done;
546 tor_free(fname);
547 fname = get_datadir_fname2("keys",
548 legacy ? "legacy_certificate" : "authority_certificate");
549 cert = read_file_to_str(fname, 0, NULL);
550 if (!cert) {
551 log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
552 fname);
553 goto done;
555 parsed = authority_cert_parse_from_string(cert, &eos);
556 if (!parsed) {
557 log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
558 goto done;
560 if (!crypto_pk_eq_keys(signing_key, parsed->signing_key)) {
561 log_warn(LD_DIR, "Stored signing key does not match signing key in "
562 "certificate");
563 goto done;
566 crypto_pk_free(*key_out);
567 authority_cert_free(*cert_out);
569 *key_out = signing_key;
570 *cert_out = parsed;
571 r = 0;
572 signing_key = NULL;
573 parsed = NULL;
575 done:
576 tor_free(fname);
577 tor_free(cert);
578 crypto_pk_free(signing_key);
579 authority_cert_free(parsed);
580 return r;
583 /** Load the v3 (voting) authority signing key and certificate, if they are
584 * present. Return -1 if anything is missing, mismatched, or unloadable;
585 * return 0 on success. */
586 static int
587 init_v3_authority_keys(void)
589 if (load_authority_keyset(0, &authority_signing_key,
590 &authority_key_certificate)<0)
591 return -1;
593 if (get_options()->V3AuthUseLegacyKey &&
594 load_authority_keyset(1, &legacy_signing_key,
595 &legacy_key_certificate)<0)
596 return -1;
598 return 0;
601 /** If we're a v3 authority, check whether we have a certificate that's
602 * likely to expire soon. Warn if we do, but not too often. */
603 void
604 v3_authority_check_key_expiry(void)
606 time_t now, expires;
607 static time_t last_warned = 0;
608 int badness, time_left, warn_interval;
609 if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
610 return;
612 now = time(NULL);
613 expires = authority_key_certificate->expires;
614 time_left = (int)( expires - now );
615 if (time_left <= 0) {
616 badness = LOG_ERR;
617 warn_interval = 60*60;
618 } else if (time_left <= 24*60*60) {
619 badness = LOG_WARN;
620 warn_interval = 60*60;
621 } else if (time_left <= 24*60*60*7) {
622 badness = LOG_WARN;
623 warn_interval = 24*60*60;
624 } else if (time_left <= 24*60*60*30) {
625 badness = LOG_WARN;
626 warn_interval = 24*60*60*5;
627 } else {
628 return;
631 if (last_warned + warn_interval > now)
632 return;
634 if (time_left <= 0) {
635 tor_log(badness, LD_DIR, "Your v3 authority certificate has expired."
636 " Generate a new one NOW.");
637 } else if (time_left <= 24*60*60) {
638 tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
639 "hours; Generate a new one NOW.", time_left/(60*60));
640 } else {
641 tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
642 "days; Generate a new one soon.", time_left/(24*60*60));
644 last_warned = now;
647 /** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
648 * on success, and -1 on failure. */
650 router_initialize_tls_context(void)
652 unsigned int flags = 0;
653 const or_options_t *options = get_options();
654 int lifetime = options->SSLKeyLifetime;
655 if (public_server_mode(options))
656 flags |= TOR_TLS_CTX_IS_PUBLIC_SERVER;
657 if (options->TLSECGroup) {
658 if (!strcasecmp(options->TLSECGroup, "P256"))
659 flags |= TOR_TLS_CTX_USE_ECDHE_P256;
660 else if (!strcasecmp(options->TLSECGroup, "P224"))
661 flags |= TOR_TLS_CTX_USE_ECDHE_P224;
663 if (!lifetime) { /* we should guess a good ssl cert lifetime */
665 /* choose between 5 and 365 days, and round to the day */
666 lifetime = 5*24*3600 + crypto_rand_int(361*24*3600);
667 lifetime -= lifetime % (24*3600);
669 if (crypto_rand_int(2)) {
670 /* Half the time we expire at midnight, and half the time we expire
671 * one second before midnight. (Some CAs wobble their expiry times a
672 * bit in practice, perhaps to reduce collision attacks; see ticket
673 * 8443 for details about observed certs in the wild.) */
674 lifetime--;
678 /* It's ok to pass lifetime in as an unsigned int, since
679 * config_parse_interval() checked it. */
680 return tor_tls_context_init(flags,
681 get_tlsclient_identity_key(),
682 server_mode(options) ?
683 get_server_identity_key() : NULL,
684 (unsigned int)lifetime);
687 /** Compute fingerprint (or hashed fingerprint if hashed is 1) and write
688 * it to 'fingerprint' (or 'hashed-fingerprint'). Return 0 on success, or
689 * -1 if Tor should die,
691 STATIC int
692 router_write_fingerprint(int hashed)
694 char *keydir = NULL, *cp = NULL;
695 const char *fname = hashed ? "hashed-fingerprint" :
696 "fingerprint";
697 char fingerprint[FINGERPRINT_LEN+1];
698 const or_options_t *options = get_options();
699 char *fingerprint_line = NULL;
700 int result = -1;
702 keydir = get_datadir_fname(fname);
703 log_info(LD_GENERAL,"Dumping %sfingerprint to \"%s\"...",
704 hashed ? "hashed " : "", keydir);
705 if (!hashed) {
706 if (crypto_pk_get_fingerprint(get_server_identity_key(),
707 fingerprint, 0) < 0) {
708 log_err(LD_GENERAL,"Error computing fingerprint");
709 goto done;
711 } else {
712 if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
713 fingerprint) < 0) {
714 log_err(LD_GENERAL,"Error computing hashed fingerprint");
715 goto done;
719 tor_asprintf(&fingerprint_line, "%s %s\n", options->Nickname, fingerprint);
721 /* Check whether we need to write the (hashed-)fingerprint file. */
723 cp = read_file_to_str(keydir, RFTS_IGNORE_MISSING, NULL);
724 if (!cp || strcmp(cp, fingerprint_line)) {
725 if (write_str_to_file(keydir, fingerprint_line, 0)) {
726 log_err(LD_FS, "Error writing %sfingerprint line to file",
727 hashed ? "hashed " : "");
728 goto done;
732 log_notice(LD_GENERAL, "Your Tor %s identity key fingerprint is '%s %s'",
733 hashed ? "bridge's hashed" : "server's", options->Nickname,
734 fingerprint);
736 result = 0;
737 done:
738 tor_free(cp);
739 tor_free(keydir);
740 tor_free(fingerprint_line);
741 return result;
744 /** Initialize all OR private keys, and the TLS context, as necessary.
745 * On OPs, this only initializes the tls context. Return 0 on success,
746 * or -1 if Tor should die.
749 init_keys(void)
751 char *keydir;
752 const char *mydesc;
753 crypto_pk_t *prkey;
754 char digest[DIGEST_LEN];
755 char v3_digest[DIGEST_LEN];
756 const or_options_t *options = get_options();
757 dirinfo_type_t type;
758 time_t now = time(NULL);
759 dir_server_t *ds;
760 int v3_digest_set = 0;
761 authority_cert_t *cert = NULL;
763 if (!key_lock)
764 key_lock = tor_mutex_new();
766 /* There are a couple of paths that put us here before we've asked
767 * openssl to initialize itself. */
768 if (crypto_global_init(get_options()->HardwareAccel,
769 get_options()->AccelName,
770 get_options()->AccelDir)) {
771 log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
772 return -1;
775 /* OP's don't need persistent keys; just make up an identity and
776 * initialize the TLS context. */
777 if (!server_mode(options)) {
778 if (!(prkey = crypto_pk_new()))
779 return -1;
780 if (crypto_pk_generate_key(prkey)) {
781 crypto_pk_free(prkey);
782 return -1;
784 set_client_identity_key(prkey);
785 /* Create a TLS context. */
786 if (router_initialize_tls_context() < 0) {
787 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
788 return -1;
790 return 0;
792 /* Make sure DataDirectory exists, and is private. */
793 if (check_private_dir(options->DataDirectory, CPD_CREATE, options->User)) {
794 return -1;
796 /* Check the key directory. */
797 keydir = get_datadir_fname("keys");
798 if (check_private_dir(keydir, CPD_CREATE, options->User)) {
799 tor_free(keydir);
800 return -1;
802 tor_free(keydir);
804 /* 1a. Read v3 directory authority key/cert information. */
805 memset(v3_digest, 0, sizeof(v3_digest));
806 if (authdir_mode_v3(options)) {
807 if (init_v3_authority_keys()<0) {
808 log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
809 "were unable to load our v3 authority keys and certificate! "
810 "Use tor-gencert to generate them. Dying.");
811 return -1;
813 cert = get_my_v3_authority_cert();
814 if (cert) {
815 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
816 v3_digest);
817 v3_digest_set = 1;
821 /* 1b. Read identity key. Make it if none is found. */
822 keydir = get_datadir_fname2("keys", "secret_id_key");
823 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
824 prkey = init_key_from_file(keydir, 1, LOG_ERR);
825 tor_free(keydir);
826 if (!prkey) return -1;
827 set_server_identity_key(prkey);
829 /* 1c. If we are configured as a bridge, generate a client key;
830 * otherwise, set the server identity key as our client identity
831 * key. */
832 if (public_server_mode(options)) {
833 set_client_identity_key(crypto_pk_dup_key(prkey)); /* set above */
834 } else {
835 if (!(prkey = crypto_pk_new()))
836 return -1;
837 if (crypto_pk_generate_key(prkey)) {
838 crypto_pk_free(prkey);
839 return -1;
841 set_client_identity_key(prkey);
844 /* 2. Read onion key. Make it if none is found. */
845 keydir = get_datadir_fname2("keys", "secret_onion_key");
846 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
847 prkey = init_key_from_file(keydir, 1, LOG_ERR);
848 tor_free(keydir);
849 if (!prkey) return -1;
850 set_onion_key(prkey);
851 if (options->command == CMD_RUN_TOR) {
852 /* only mess with the state file if we're actually running Tor */
853 or_state_t *state = get_or_state();
854 if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
855 /* We allow for some parsing slop, but we don't want to risk accepting
856 * values in the distant future. If we did, we might never rotate the
857 * onion key. */
858 onionkey_set_at = state->LastRotatedOnionKey;
859 } else {
860 /* We have no LastRotatedOnionKey set; either we just created the key
861 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
862 * start the clock ticking now so that we will eventually rotate it even
863 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
864 state->LastRotatedOnionKey = onionkey_set_at = now;
865 or_state_mark_dirty(state, options->AvoidDiskWrites ?
866 time(NULL)+3600 : 0);
870 keydir = get_datadir_fname2("keys", "secret_onion_key.old");
871 if (!lastonionkey && file_status(keydir) == FN_FILE) {
872 prkey = init_key_from_file(keydir, 1, LOG_ERR); /* XXXX Why 1? */
873 if (prkey)
874 lastonionkey = prkey;
876 tor_free(keydir);
878 #ifdef CURVE25519_ENABLED
880 /* 2b. Load curve25519 onion keys. */
881 int r;
882 keydir = get_datadir_fname2("keys", "secret_onion_key_ntor");
883 r = init_curve25519_keypair_from_file(&curve25519_onion_key,
884 keydir, 1, LOG_ERR, "onion");
885 tor_free(keydir);
886 if (r<0)
887 return -1;
889 keydir = get_datadir_fname2("keys", "secret_onion_key_ntor.old");
890 if (tor_mem_is_zero((const char *)
891 last_curve25519_onion_key.pubkey.public_key,
892 CURVE25519_PUBKEY_LEN) &&
893 file_status(keydir) == FN_FILE) {
894 init_curve25519_keypair_from_file(&last_curve25519_onion_key,
895 keydir, 0, LOG_ERR, "onion");
897 tor_free(keydir);
899 #endif
901 /* 3. Initialize link key and TLS context. */
902 if (router_initialize_tls_context() < 0) {
903 log_err(LD_GENERAL,"Error initializing TLS context");
904 return -1;
907 /* 4. Build our router descriptor. */
908 /* Must be called after keys are initialized. */
909 mydesc = router_get_my_descriptor();
910 if (authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)) {
911 const char *m = NULL;
912 routerinfo_t *ri;
913 /* We need to add our own fingerprint so it gets recognized. */
914 if (dirserv_add_own_fingerprint(options->Nickname,
915 get_server_identity_key())) {
916 log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
917 return -1;
919 if (mydesc) {
920 was_router_added_t added;
921 ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
922 if (!ri) {
923 log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
924 return -1;
926 added = dirserv_add_descriptor(ri, &m, "self");
927 if (!WRA_WAS_ADDED(added)) {
928 if (!WRA_WAS_OUTDATED(added)) {
929 log_err(LD_GENERAL, "Unable to add own descriptor to directory: %s",
930 m?m:"<unknown error>");
931 return -1;
932 } else {
933 /* If the descriptor was outdated, that's ok. This can happen
934 * when some config options are toggled that affect workers, but
935 * we don't really need new keys yet so the descriptor doesn't
936 * change and the old one is still fresh. */
937 log_info(LD_GENERAL, "Couldn't add own descriptor to directory "
938 "after key init: %s This is usually not a problem.",
939 m?m:"<unknown error>");
945 /* 5. Dump fingerprint and possibly hashed fingerprint to files. */
946 if (router_write_fingerprint(0)) {
947 log_err(LD_FS, "Error writing fingerprint to file");
948 return -1;
950 if (!public_server_mode(options) && router_write_fingerprint(1)) {
951 log_err(LD_FS, "Error writing hashed fingerprint to file");
952 return -1;
955 if (!authdir_mode(options))
956 return 0;
957 /* 6. [authdirserver only] load approved-routers file */
958 if (dirserv_load_fingerprint_file() < 0) {
959 log_err(LD_GENERAL,"Error loading fingerprints");
960 return -1;
962 /* 6b. [authdirserver only] add own key to approved directories. */
963 crypto_pk_get_digest(get_server_identity_key(), digest);
964 type = ((options->V3AuthoritativeDir ?
965 (V3_DIRINFO|MICRODESC_DIRINFO|EXTRAINFO_DIRINFO) : NO_DIRINFO) |
966 (options->BridgeAuthoritativeDir ? BRIDGE_DIRINFO : NO_DIRINFO));
968 ds = router_get_trusteddirserver_by_digest(digest);
969 if (!ds) {
970 ds = trusted_dir_server_new(options->Nickname, NULL,
971 router_get_advertised_dir_port(options, 0),
972 router_get_advertised_or_port(options),
973 digest,
974 v3_digest,
975 type, 0.0);
976 if (!ds) {
977 log_err(LD_GENERAL,"We want to be a directory authority, but we "
978 "couldn't add ourselves to the authority list. Failing.");
979 return -1;
981 dir_server_add(ds);
983 if (ds->type != type) {
984 log_warn(LD_DIR, "Configured authority type does not match authority "
985 "type in DirAuthority list. Adjusting. (%d v %d)",
986 type, ds->type);
987 ds->type = type;
989 if (v3_digest_set && (ds->type & V3_DIRINFO) &&
990 tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
991 log_warn(LD_DIR, "V3 identity key does not match identity declared in "
992 "DirAuthority line. Adjusting.");
993 memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
996 if (cert) { /* add my own cert to the list of known certs */
997 log_info(LD_DIR, "adding my own v3 cert");
998 if (trusted_dirs_load_certs_from_string(
999 cert->cache_info.signed_descriptor_body,
1000 TRUSTED_DIRS_CERTS_SRC_SELF, 0)<0) {
1001 log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
1002 return -1;
1006 return 0; /* success */
1009 /* Keep track of whether we should upload our server descriptor,
1010 * and what type of server we are.
1013 /** Whether we can reach our ORPort from the outside. */
1014 static int can_reach_or_port = 0;
1015 /** Whether we can reach our DirPort from the outside. */
1016 static int can_reach_dir_port = 0;
1018 /** Forget what we have learned about our reachability status. */
1019 void
1020 router_reset_reachability(void)
1022 can_reach_or_port = can_reach_dir_port = 0;
1025 /** Return 1 if ORPort is known reachable; else return 0. */
1027 check_whether_orport_reachable(void)
1029 const or_options_t *options = get_options();
1030 return options->AssumeReachable ||
1031 can_reach_or_port;
1034 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
1036 check_whether_dirport_reachable(void)
1038 const or_options_t *options = get_options();
1039 return !options->DirPort_set ||
1040 options->AssumeReachable ||
1041 net_is_disabled() ||
1042 can_reach_dir_port;
1045 /** Look at a variety of factors, and return 0 if we don't want to
1046 * advertise the fact that we have a DirPort open. Else return the
1047 * DirPort we want to advertise.
1049 * Log a helpful message if we change our mind about whether to publish
1050 * a DirPort.
1052 static int
1053 decide_to_advertise_dirport(const or_options_t *options, uint16_t dir_port)
1055 static int advertising=1; /* start out assuming we will advertise */
1056 int new_choice=1;
1057 const char *reason = NULL;
1059 /* Section one: reasons to publish or not publish that aren't
1060 * worth mentioning to the user, either because they're obvious
1061 * or because they're normal behavior. */
1063 if (!dir_port) /* short circuit the rest of the function */
1064 return 0;
1065 if (authdir_mode(options)) /* always publish */
1066 return dir_port;
1067 if (net_is_disabled())
1068 return 0;
1069 if (!check_whether_dirport_reachable())
1070 return 0;
1071 if (!router_get_advertised_dir_port(options, dir_port))
1072 return 0;
1074 /* Section two: reasons to publish or not publish that the user
1075 * might find surprising. These are generally config options that
1076 * make us choose not to publish. */
1078 if (accounting_is_enabled(options)) {
1079 /* Don't spend bytes for directory traffic if we could end up hibernating,
1080 * but allow DirPort otherwise. Some people set AccountingMax because
1081 * they're confused or to get statistics. */
1082 int interval_length = accounting_get_interval_length();
1083 uint32_t effective_bw = get_effective_bwrate(options);
1084 if (!interval_length) {
1085 log_warn(LD_BUG, "An accounting interval is not allowed to be zero "
1086 "seconds long. Raising to 1.");
1087 interval_length = 1;
1089 log_info(LD_GENERAL, "Calculating whether to disable dirport: effective "
1090 "bwrate: %u, AccountingMax: "U64_FORMAT", "
1091 "accounting interval length %d", effective_bw,
1092 U64_PRINTF_ARG(options->AccountingMax),
1093 interval_length);
1094 if (effective_bw >=
1095 options->AccountingMax / interval_length) {
1096 new_choice = 0;
1097 reason = "AccountingMax enabled";
1099 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
1100 } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
1101 (options->RelayBandwidthRate > 0 &&
1102 options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
1103 /* if we're advertising a small amount */
1104 new_choice = 0;
1105 reason = "BandwidthRate under 50KB";
1108 if (advertising != new_choice) {
1109 if (new_choice == 1) {
1110 log_notice(LD_DIR, "Advertising DirPort as %d", dir_port);
1111 } else {
1112 tor_assert(reason);
1113 log_notice(LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
1115 advertising = new_choice;
1118 return advertising ? dir_port : 0;
1121 /** Allocate and return a new extend_info_t that can be used to build
1122 * a circuit to or through the router <b>r</b>. Use the primary
1123 * address of the router unless <b>for_direct_connect</b> is true, in
1124 * which case the preferred address is used instead. */
1125 static extend_info_t *
1126 extend_info_from_router(const routerinfo_t *r)
1128 tor_addr_port_t ap;
1129 tor_assert(r);
1131 router_get_prim_orport(r, &ap);
1132 return extend_info_new(r->nickname, r->cache_info.identity_digest,
1133 r->onion_pkey, r->onion_curve25519_pkey,
1134 &ap.addr, ap.port);
1137 /** Some time has passed, or we just got new directory information.
1138 * See if we currently believe our ORPort or DirPort to be
1139 * unreachable. If so, launch a new test for it.
1141 * For ORPort, we simply try making a circuit that ends at ourselves.
1142 * Success is noticed in onionskin_answer().
1144 * For DirPort, we make a connection via Tor to our DirPort and ask
1145 * for our own server descriptor.
1146 * Success is noticed in connection_dir_client_reached_eof().
1148 void
1149 consider_testing_reachability(int test_or, int test_dir)
1151 const routerinfo_t *me = router_get_my_routerinfo();
1152 int orport_reachable = check_whether_orport_reachable();
1153 tor_addr_t addr;
1154 const or_options_t *options = get_options();
1155 if (!me)
1156 return;
1158 if (routerset_contains_router(options->ExcludeNodes, me, -1) &&
1159 options->StrictNodes) {
1160 /* If we've excluded ourself, and StrictNodes is set, we can't test
1161 * ourself. */
1162 if (test_or || test_dir) {
1163 #define SELF_EXCLUDED_WARN_INTERVAL 3600
1164 static ratelim_t warning_limit=RATELIM_INIT(SELF_EXCLUDED_WARN_INTERVAL);
1165 log_fn_ratelim(&warning_limit, LOG_WARN, LD_CIRC,
1166 "Can't peform self-tests for this relay: we have "
1167 "listed ourself in ExcludeNodes, and StrictNodes is set. "
1168 "We cannot learn whether we are usable, and will not "
1169 "be able to advertise ourself.");
1171 return;
1174 if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
1175 extend_info_t *ei = extend_info_from_router(me);
1176 /* XXX IPv6 self testing */
1177 log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
1178 !orport_reachable ? "reachability" : "bandwidth",
1179 fmt_addr32(me->addr), me->or_port);
1180 circuit_launch_by_extend_info(CIRCUIT_PURPOSE_TESTING, ei,
1181 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
1182 extend_info_free(ei);
1185 tor_addr_from_ipv4h(&addr, me->addr);
1186 if (test_dir && !check_whether_dirport_reachable() &&
1187 !connection_get_by_type_addr_port_purpose(
1188 CONN_TYPE_DIR, &addr, me->dir_port,
1189 DIR_PURPOSE_FETCH_SERVERDESC)) {
1190 /* ask myself, via tor, for my server descriptor. */
1191 directory_initiate_command(&addr,
1192 me->or_port, me->dir_port,
1193 me->cache_info.identity_digest,
1194 DIR_PURPOSE_FETCH_SERVERDESC,
1195 ROUTER_PURPOSE_GENERAL,
1196 DIRIND_ANON_DIRPORT, "authority.z", NULL, 0, 0);
1200 /** Annotate that we found our ORPort reachable. */
1201 void
1202 router_orport_found_reachable(void)
1204 const routerinfo_t *me = router_get_my_routerinfo();
1205 if (!can_reach_or_port && me) {
1206 char *address = tor_dup_ip(me->addr);
1207 log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
1208 "the outside. Excellent.%s",
1209 get_options()->PublishServerDescriptor_ != NO_DIRINFO ?
1210 " Publishing server descriptor." : "");
1211 can_reach_or_port = 1;
1212 mark_my_descriptor_dirty("ORPort found reachable");
1213 control_event_server_status(LOG_NOTICE,
1214 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
1215 address, me->or_port);
1216 tor_free(address);
1220 /** Annotate that we found our DirPort reachable. */
1221 void
1222 router_dirport_found_reachable(void)
1224 const routerinfo_t *me = router_get_my_routerinfo();
1225 if (!can_reach_dir_port && me) {
1226 char *address = tor_dup_ip(me->addr);
1227 log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
1228 "from the outside. Excellent.");
1229 can_reach_dir_port = 1;
1230 if (decide_to_advertise_dirport(get_options(), me->dir_port))
1231 mark_my_descriptor_dirty("DirPort found reachable");
1232 control_event_server_status(LOG_NOTICE,
1233 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
1234 address, me->dir_port);
1235 tor_free(address);
1239 /** We have enough testing circuits open. Send a bunch of "drop"
1240 * cells down each of them, to exercise our bandwidth. */
1241 void
1242 router_perform_bandwidth_test(int num_circs, time_t now)
1244 int num_cells = (int)(get_options()->BandwidthRate * 10 /
1245 CELL_MAX_NETWORK_SIZE);
1246 int max_cells = num_cells < CIRCWINDOW_START ?
1247 num_cells : CIRCWINDOW_START;
1248 int cells_per_circuit = max_cells / num_circs;
1249 origin_circuit_t *circ = NULL;
1251 log_notice(LD_OR,"Performing bandwidth self-test...done.");
1252 while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
1253 CIRCUIT_PURPOSE_TESTING))) {
1254 /* dump cells_per_circuit drop cells onto this circ */
1255 int i = cells_per_circuit;
1256 if (circ->base_.state != CIRCUIT_STATE_OPEN)
1257 continue;
1258 circ->base_.timestamp_dirty = now;
1259 while (i-- > 0) {
1260 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
1261 RELAY_COMMAND_DROP,
1262 NULL, 0, circ->cpath->prev)<0) {
1263 return; /* stop if error */
1269 /** Return true iff our network is in some sense disabled: either we're
1270 * hibernating, entering hibernation, or the network is turned off with
1271 * DisableNetwork. */
1273 net_is_disabled(void)
1275 return get_options()->DisableNetwork || we_are_hibernating();
1278 /** Return true iff we believe ourselves to be an authoritative
1279 * directory server.
1282 authdir_mode(const or_options_t *options)
1284 return options->AuthoritativeDir != 0;
1286 /** Return true iff we believe ourselves to be a v3 authoritative
1287 * directory server.
1290 authdir_mode_v3(const or_options_t *options)
1292 return authdir_mode(options) && options->V3AuthoritativeDir != 0;
1294 /** Return true iff we are a v3 directory authority. */
1296 authdir_mode_any_main(const or_options_t *options)
1298 return options->V3AuthoritativeDir;
1300 /** Return true if we believe ourselves to be any kind of
1301 * authoritative directory beyond just a hidserv authority. */
1303 authdir_mode_any_nonhidserv(const or_options_t *options)
1305 return options->BridgeAuthoritativeDir ||
1306 authdir_mode_any_main(options);
1308 /** Return true iff we are an authoritative directory server that is
1309 * authoritative about receiving and serving descriptors of type
1310 * <b>purpose</b> on its dirport. Use -1 for "any purpose". */
1312 authdir_mode_handles_descs(const or_options_t *options, int purpose)
1314 if (purpose < 0)
1315 return authdir_mode_any_nonhidserv(options);
1316 else if (purpose == ROUTER_PURPOSE_GENERAL)
1317 return authdir_mode_any_main(options);
1318 else if (purpose == ROUTER_PURPOSE_BRIDGE)
1319 return (options->BridgeAuthoritativeDir);
1320 else
1321 return 0;
1323 /** Return true iff we are an authoritative directory server that
1324 * publishes its own network statuses.
1327 authdir_mode_publishes_statuses(const or_options_t *options)
1329 if (authdir_mode_bridge(options))
1330 return 0;
1331 return authdir_mode_any_nonhidserv(options);
1333 /** Return true iff we are an authoritative directory server that
1334 * tests reachability of the descriptors it learns about.
1337 authdir_mode_tests_reachability(const or_options_t *options)
1339 return authdir_mode_handles_descs(options, -1);
1341 /** Return true iff we believe ourselves to be a bridge authoritative
1342 * directory server.
1345 authdir_mode_bridge(const or_options_t *options)
1347 return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
1350 /** Return true iff we are trying to be a server.
1352 MOCK_IMPL(int,
1353 server_mode,(const or_options_t *options))
1355 if (options->ClientOnly) return 0;
1356 /* XXXX024 I believe we can kill off ORListenAddress here.*/
1357 return (options->ORPort_set || options->ORListenAddress);
1360 /** Return true iff we are trying to be a non-bridge server.
1362 MOCK_IMPL(int,
1363 public_server_mode,(const or_options_t *options))
1365 if (!server_mode(options)) return 0;
1366 return (!options->BridgeRelay);
1369 /** Return true iff the combination of options in <b>options</b> and parameters
1370 * in the consensus mean that we don't want to allow exits from circuits
1371 * we got from addresses not known to be servers. */
1373 should_refuse_unknown_exits(const or_options_t *options)
1375 if (options->RefuseUnknownExits != -1) {
1376 return options->RefuseUnknownExits;
1377 } else {
1378 return networkstatus_get_param(NULL, "refuseunknownexits", 1, 0, 1);
1382 /** Remember if we've advertised ourselves to the dirservers. */
1383 static int server_is_advertised=0;
1385 /** Return true iff we have published our descriptor lately.
1388 advertised_server_mode(void)
1390 return server_is_advertised;
1394 * Called with a boolean: set whether we have recently published our
1395 * descriptor.
1397 static void
1398 set_server_advertised(int s)
1400 server_is_advertised = s;
1403 /** Return true iff we are trying to proxy client connections. */
1405 proxy_mode(const or_options_t *options)
1407 (void)options;
1408 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t *, p) {
1409 if (p->type == CONN_TYPE_AP_LISTENER ||
1410 p->type == CONN_TYPE_AP_TRANS_LISTENER ||
1411 p->type == CONN_TYPE_AP_DNS_LISTENER ||
1412 p->type == CONN_TYPE_AP_NATD_LISTENER)
1413 return 1;
1414 } SMARTLIST_FOREACH_END(p);
1415 return 0;
1418 /** Decide if we're a publishable server. We are a publishable server if:
1419 * - We don't have the ClientOnly option set
1420 * and
1421 * - We have the PublishServerDescriptor option set to non-empty
1422 * and
1423 * - We have ORPort set
1424 * and
1425 * - We believe we are reachable from the outside; or
1426 * - We are an authoritative directory server.
1428 static int
1429 decide_if_publishable_server(void)
1431 const or_options_t *options = get_options();
1433 if (options->ClientOnly)
1434 return 0;
1435 if (options->PublishServerDescriptor_ == NO_DIRINFO)
1436 return 0;
1437 if (!server_mode(options))
1438 return 0;
1439 if (authdir_mode(options))
1440 return 1;
1441 if (!router_get_advertised_or_port(options))
1442 return 0;
1444 return check_whether_orport_reachable();
1447 /** Initiate server descriptor upload as reasonable (if server is publishable,
1448 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1450 * We need to rebuild the descriptor if it's dirty even if we're not
1451 * uploading, because our reachability testing *uses* our descriptor to
1452 * determine what IP address and ports to test.
1454 void
1455 consider_publishable_server(int force)
1457 int rebuilt;
1459 if (!server_mode(get_options()))
1460 return;
1462 rebuilt = router_rebuild_descriptor(0);
1463 if (decide_if_publishable_server()) {
1464 set_server_advertised(1);
1465 if (rebuilt == 0)
1466 router_upload_dir_desc_to_dirservers(force);
1467 } else {
1468 set_server_advertised(0);
1472 /** Return the port of the first active listener of type
1473 * <b>listener_type</b>. */
1474 /** XXX not a very good interface. it's not reliable when there are
1475 multiple listeners. */
1476 uint16_t
1477 router_get_active_listener_port_by_type_af(int listener_type,
1478 sa_family_t family)
1480 /* Iterate all connections, find one of the right kind and return
1481 the port. Not very sophisticated or fast, but effective. */
1482 smartlist_t *conns = get_connection_array();
1483 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1484 if (conn->type == listener_type && !conn->marked_for_close &&
1485 conn->socket_family == family) {
1486 return conn->port;
1488 } SMARTLIST_FOREACH_END(conn);
1490 return 0;
1493 /** Return the port that we should advertise as our ORPort; this is either
1494 * the one configured in the ORPort option, or the one we actually bound to
1495 * if ORPort is "auto".
1497 uint16_t
1498 router_get_advertised_or_port(const or_options_t *options)
1500 return router_get_advertised_or_port_by_af(options, AF_INET);
1503 /** As router_get_advertised_or_port(), but allows an address family argument.
1505 uint16_t
1506 router_get_advertised_or_port_by_af(const or_options_t *options,
1507 sa_family_t family)
1509 int port = get_first_advertised_port_by_type_af(CONN_TYPE_OR_LISTENER,
1510 family);
1511 (void)options;
1513 /* If the port is in 'auto' mode, we have to use
1514 router_get_listener_port_by_type(). */
1515 if (port == CFG_AUTO_PORT)
1516 return router_get_active_listener_port_by_type_af(CONN_TYPE_OR_LISTENER,
1517 family);
1519 return port;
1522 /** Return the port that we should advertise as our DirPort;
1523 * this is one of three possibilities:
1524 * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
1525 * the one configured in the DirPort option,
1526 * or the one we actually bound to if DirPort is "auto". */
1527 uint16_t
1528 router_get_advertised_dir_port(const or_options_t *options, uint16_t dirport)
1530 int dirport_configured = get_primary_dir_port();
1531 (void)options;
1533 if (!dirport_configured)
1534 return dirport;
1536 if (dirport_configured == CFG_AUTO_PORT)
1537 return router_get_active_listener_port_by_type_af(CONN_TYPE_DIR_LISTENER,
1538 AF_INET);
1540 return dirport_configured;
1544 * OR descriptor generation.
1547 /** My routerinfo. */
1548 static routerinfo_t *desc_routerinfo = NULL;
1549 /** My extrainfo */
1550 static extrainfo_t *desc_extrainfo = NULL;
1551 /** Why did we most recently decide to regenerate our descriptor? Used to
1552 * tell the authorities why we're sending it to them. */
1553 static const char *desc_gen_reason = NULL;
1554 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1555 * now. */
1556 static time_t desc_clean_since = 0;
1557 /** Why did we mark the descriptor dirty? */
1558 static const char *desc_dirty_reason = NULL;
1559 /** Boolean: do we need to regenerate the above? */
1560 static int desc_needs_upload = 0;
1562 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1563 * descriptor successfully yet, try to upload our signed descriptor to
1564 * all the directory servers we know about.
1566 void
1567 router_upload_dir_desc_to_dirservers(int force)
1569 const routerinfo_t *ri;
1570 extrainfo_t *ei;
1571 char *msg;
1572 size_t desc_len, extra_len = 0, total_len;
1573 dirinfo_type_t auth = get_options()->PublishServerDescriptor_;
1575 ri = router_get_my_routerinfo();
1576 if (!ri) {
1577 log_info(LD_GENERAL, "No descriptor; skipping upload");
1578 return;
1580 ei = router_get_my_extrainfo();
1581 if (auth == NO_DIRINFO)
1582 return;
1583 if (!force && !desc_needs_upload)
1584 return;
1586 log_info(LD_OR, "Uploading relay descriptor to directory authorities%s",
1587 force ? " (forced)" : "");
1589 desc_needs_upload = 0;
1591 desc_len = ri->cache_info.signed_descriptor_len;
1592 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1593 total_len = desc_len + extra_len + 1;
1594 msg = tor_malloc(total_len);
1595 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1596 if (ei) {
1597 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1599 msg[desc_len+extra_len] = 0;
1601 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
1602 (auth & BRIDGE_DIRINFO) ?
1603 ROUTER_PURPOSE_BRIDGE :
1604 ROUTER_PURPOSE_GENERAL,
1605 auth, msg, desc_len, extra_len);
1606 tor_free(msg);
1609 /** OR only: Check whether my exit policy says to allow connection to
1610 * conn. Return 0 if we accept; non-0 if we reject.
1613 router_compare_to_my_exit_policy(const tor_addr_t *addr, uint16_t port)
1615 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1616 return -1;
1618 /* make sure it's resolved to something. this way we can't get a
1619 'maybe' below. */
1620 if (tor_addr_is_null(addr))
1621 return -1;
1623 /* look at desc_routerinfo->exit_policy for both the v4 and the v6
1624 * policies. The exit_policy field in desc_routerinfo is a bit unusual,
1625 * in that it contains IPv6 and IPv6 entries. We don't want to look
1626 * at desc_routerinfio->ipv6_exit_policy, since that's a port summary. */
1627 if ((tor_addr_family(addr) == AF_INET ||
1628 tor_addr_family(addr) == AF_INET6)) {
1629 return compare_tor_addr_to_addr_policy(addr, port,
1630 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
1631 #if 0
1632 } else if (tor_addr_family(addr) == AF_INET6) {
1633 return get_options()->IPv6Exit &&
1634 desc_routerinfo->ipv6_exit_policy &&
1635 compare_tor_addr_to_short_policy(addr, port,
1636 desc_routerinfo->ipv6_exit_policy) != ADDR_POLICY_ACCEPTED;
1637 #endif
1638 } else {
1639 return -1;
1643 /** Return true iff my exit policy is reject *:*. Return -1 if we don't
1644 * have a descriptor */
1646 router_my_exit_policy_is_reject_star(void)
1648 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1649 return -1;
1651 return desc_routerinfo->policy_is_reject_star;
1654 /** Return true iff I'm a server and <b>digest</b> is equal to
1655 * my server identity key digest. */
1657 router_digest_is_me(const char *digest)
1659 return (server_identitykey &&
1660 tor_memeq(server_identitykey_digest, digest, DIGEST_LEN));
1663 /** Return my identity digest. */
1664 const uint8_t *
1665 router_get_my_id_digest(void)
1667 return (const uint8_t *)server_identitykey_digest;
1670 /** Return true iff I'm a server and <b>digest</b> is equal to
1671 * my identity digest. */
1673 router_extrainfo_digest_is_me(const char *digest)
1675 extrainfo_t *ei = router_get_my_extrainfo();
1676 if (!ei)
1677 return 0;
1679 return tor_memeq(digest,
1680 ei->cache_info.signed_descriptor_digest,
1681 DIGEST_LEN);
1684 /** A wrapper around router_digest_is_me(). */
1686 router_is_me(const routerinfo_t *router)
1688 return router_digest_is_me(router->cache_info.identity_digest);
1691 /** Return a routerinfo for this OR, rebuilding a fresh one if
1692 * necessary. Return NULL on error, or if called on an OP. */
1693 MOCK_IMPL(const routerinfo_t *,
1694 router_get_my_routerinfo,(void))
1696 if (!server_mode(get_options()))
1697 return NULL;
1698 if (router_rebuild_descriptor(0))
1699 return NULL;
1700 return desc_routerinfo;
1703 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1704 * one if necessary. Return NULL on error.
1706 const char *
1707 router_get_my_descriptor(void)
1709 const char *body;
1710 if (!router_get_my_routerinfo())
1711 return NULL;
1712 /* Make sure this is nul-terminated. */
1713 tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
1714 body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
1715 tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
1716 log_debug(LD_GENERAL,"my desc is '%s'", body);
1717 return body;
1720 /** Return the extrainfo document for this OR, or NULL if we have none.
1721 * Rebuilt it (and the server descriptor) if necessary. */
1722 extrainfo_t *
1723 router_get_my_extrainfo(void)
1725 if (!server_mode(get_options()))
1726 return NULL;
1727 if (router_rebuild_descriptor(0))
1728 return NULL;
1729 return desc_extrainfo;
1732 /** Return a human-readable string describing what triggered us to generate
1733 * our current descriptor, or NULL if we don't know. */
1734 const char *
1735 router_get_descriptor_gen_reason(void)
1737 return desc_gen_reason;
1740 /** A list of nicknames that we've warned about including in our family
1741 * declaration verbatim rather than as digests. */
1742 static smartlist_t *warned_nonexistent_family = NULL;
1744 static int router_guess_address_from_dir_headers(uint32_t *guess);
1746 /** Make a current best guess at our address, either because
1747 * it's configured in torrc, or because we've learned it from
1748 * dirserver headers. Place the answer in *<b>addr</b> and return
1749 * 0 on success, else return -1 if we have no guess. */
1751 router_pick_published_address(const or_options_t *options, uint32_t *addr)
1753 *addr = get_last_resolved_addr();
1754 if (!*addr &&
1755 resolve_my_address(LOG_INFO, options, addr, NULL, NULL) < 0) {
1756 log_info(LD_CONFIG, "Could not determine our address locally. "
1757 "Checking if directory headers provide any hints.");
1758 if (router_guess_address_from_dir_headers(addr) < 0) {
1759 log_info(LD_CONFIG, "No hints from directory headers either. "
1760 "Will try again later.");
1761 return -1;
1764 log_info(LD_CONFIG,"Success: chose address '%s'.", fmt_addr32(*addr));
1765 return 0;
1768 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1769 * routerinfo, signed server descriptor, and extra-info document for this OR.
1770 * Return 0 on success, -1 on temporary error.
1773 router_rebuild_descriptor(int force)
1775 routerinfo_t *ri;
1776 extrainfo_t *ei;
1777 uint32_t addr;
1778 char platform[256];
1779 int hibernating = we_are_hibernating();
1780 const or_options_t *options = get_options();
1782 if (desc_clean_since && !force)
1783 return 0;
1785 if (router_pick_published_address(options, &addr) < 0 ||
1786 router_get_advertised_or_port(options) == 0) {
1787 /* Stop trying to rebuild our descriptor every second. We'll
1788 * learn that it's time to try again when ip_address_changed()
1789 * marks it dirty. */
1790 desc_clean_since = time(NULL);
1791 return -1;
1794 log_info(LD_OR, "Rebuilding relay descriptor%s", force ? " (forced)" : "");
1796 ri = tor_malloc_zero(sizeof(routerinfo_t));
1797 ri->cache_info.routerlist_index = -1;
1798 ri->nickname = tor_strdup(options->Nickname);
1799 ri->addr = addr;
1800 ri->or_port = router_get_advertised_or_port(options);
1801 ri->dir_port = router_get_advertised_dir_port(options, 0);
1802 ri->cache_info.published_on = time(NULL);
1803 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
1804 * main thread */
1805 #ifdef CURVE25519_ENABLED
1806 ri->onion_curve25519_pkey =
1807 tor_memdup(&get_current_curve25519_keypair()->pubkey,
1808 sizeof(curve25519_public_key_t));
1809 #endif
1811 /* For now, at most one IPv6 or-address is being advertised. */
1813 const port_cfg_t *ipv6_orport = NULL;
1814 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t *, p) {
1815 if (p->type == CONN_TYPE_OR_LISTENER &&
1816 ! p->no_advertise &&
1817 ! p->bind_ipv4_only &&
1818 tor_addr_family(&p->addr) == AF_INET6) {
1819 if (! tor_addr_is_internal(&p->addr, 0)) {
1820 ipv6_orport = p;
1821 break;
1822 } else {
1823 char addrbuf[TOR_ADDR_BUF_LEN];
1824 log_warn(LD_CONFIG,
1825 "Unable to use configured IPv6 address \"%s\" in a "
1826 "descriptor. Skipping it. "
1827 "Try specifying a globally reachable address explicitly. ",
1828 tor_addr_to_str(addrbuf, &p->addr, sizeof(addrbuf), 1));
1831 } SMARTLIST_FOREACH_END(p);
1832 if (ipv6_orport) {
1833 tor_addr_copy(&ri->ipv6_addr, &ipv6_orport->addr);
1834 ri->ipv6_orport = ipv6_orport->port;
1838 ri->identity_pkey = crypto_pk_dup_key(get_server_identity_key());
1839 if (crypto_pk_get_digest(ri->identity_pkey,
1840 ri->cache_info.identity_digest)<0) {
1841 routerinfo_free(ri);
1842 return -1;
1844 get_platform_str(platform, sizeof(platform));
1845 ri->platform = tor_strdup(platform);
1847 /* compute ri->bandwidthrate as the min of various options */
1848 ri->bandwidthrate = get_effective_bwrate(options);
1850 /* and compute ri->bandwidthburst similarly */
1851 ri->bandwidthburst = get_effective_bwburst(options);
1853 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
1855 if (dns_seems_to_be_broken() || has_dns_init_failed()) {
1856 /* DNS is screwed up; don't claim to be an exit. */
1857 policies_exit_policy_append_reject_star(&ri->exit_policy);
1858 } else {
1859 policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
1860 options->IPv6Exit,
1861 options->ExitPolicyRejectPrivate,
1862 ri->addr, !options->BridgeRelay);
1864 ri->policy_is_reject_star =
1865 policy_is_reject_star(ri->exit_policy, AF_INET) &&
1866 policy_is_reject_star(ri->exit_policy, AF_INET6);
1868 if (options->IPv6Exit) {
1869 char *p_tmp = policy_summarize(ri->exit_policy, AF_INET6);
1870 if (p_tmp)
1871 ri->ipv6_exit_policy = parse_short_policy(p_tmp);
1872 tor_free(p_tmp);
1875 if (options->MyFamily && ! options->BridgeRelay) {
1876 smartlist_t *family;
1877 if (!warned_nonexistent_family)
1878 warned_nonexistent_family = smartlist_new();
1879 family = smartlist_new();
1880 ri->declared_family = smartlist_new();
1881 smartlist_split_string(family, options->MyFamily, ",",
1882 SPLIT_SKIP_SPACE|SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1883 SMARTLIST_FOREACH_BEGIN(family, char *, name) {
1884 const node_t *member;
1885 if (!strcasecmp(name, options->Nickname))
1886 goto skip; /* Don't list ourself, that's redundant */
1887 else
1888 member = node_get_by_nickname(name, 1);
1889 if (!member) {
1890 int is_legal = is_legal_nickname_or_hexdigest(name);
1891 if (!smartlist_contains_string(warned_nonexistent_family, name) &&
1892 !is_legal_hexdigest(name)) {
1893 if (is_legal)
1894 log_warn(LD_CONFIG,
1895 "I have no descriptor for the router named \"%s\" in my "
1896 "declared family; I'll use the nickname as is, but "
1897 "this may confuse clients.", name);
1898 else
1899 log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
1900 "declared family, but that isn't a legal nickname. "
1901 "Skipping it.", escaped(name));
1902 smartlist_add(warned_nonexistent_family, tor_strdup(name));
1904 if (is_legal) {
1905 smartlist_add(ri->declared_family, name);
1906 name = NULL;
1908 } else if (router_digest_is_me(member->identity)) {
1909 /* Don't list ourself in our own family; that's redundant */
1910 /* XXX shouldn't be possible */
1911 } else {
1912 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1913 fp[0] = '$';
1914 base16_encode(fp+1,HEX_DIGEST_LEN+1,
1915 member->identity, DIGEST_LEN);
1916 smartlist_add(ri->declared_family, fp);
1917 if (smartlist_contains_string(warned_nonexistent_family, name))
1918 smartlist_string_remove(warned_nonexistent_family, name);
1920 skip:
1921 tor_free(name);
1922 } SMARTLIST_FOREACH_END(name);
1924 /* remove duplicates from the list */
1925 smartlist_sort_strings(ri->declared_family);
1926 smartlist_uniq_strings(ri->declared_family);
1928 smartlist_free(family);
1931 /* Now generate the extrainfo. */
1932 ei = tor_malloc_zero(sizeof(extrainfo_t));
1933 ei->cache_info.is_extrainfo = 1;
1934 strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
1935 ei->cache_info.published_on = ri->cache_info.published_on;
1936 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
1937 DIGEST_LEN);
1938 if (extrainfo_dump_to_string(&ei->cache_info.signed_descriptor_body,
1939 ei, get_server_identity_key()) < 0) {
1940 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
1941 extrainfo_free(ei);
1942 ei = NULL;
1943 } else {
1944 ei->cache_info.signed_descriptor_len =
1945 strlen(ei->cache_info.signed_descriptor_body);
1946 router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
1947 ei->cache_info.signed_descriptor_len,
1948 ei->cache_info.signed_descriptor_digest);
1951 /* Now finish the router descriptor. */
1952 if (ei) {
1953 memcpy(ri->cache_info.extra_info_digest,
1954 ei->cache_info.signed_descriptor_digest,
1955 DIGEST_LEN);
1956 } else {
1957 /* ri was allocated with tor_malloc_zero, so there is no need to
1958 * zero ri->cache_info.extra_info_digest here. */
1960 if (! (ri->cache_info.signed_descriptor_body = router_dump_router_to_string(
1961 ri, get_server_identity_key()))) {
1962 log_warn(LD_BUG, "Couldn't generate router descriptor.");
1963 routerinfo_free(ri);
1964 extrainfo_free(ei);
1965 return -1;
1967 ri->cache_info.signed_descriptor_len =
1968 strlen(ri->cache_info.signed_descriptor_body);
1970 ri->purpose =
1971 options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
1972 if (options->BridgeRelay) {
1973 /* Bridges shouldn't be able to send their descriptors unencrypted,
1974 anyway, since they don't have a DirPort, and always connect to the
1975 bridge authority anonymously. But just in case they somehow think of
1976 sending them on an unencrypted connection, don't allow them to try. */
1977 ri->cache_info.send_unencrypted = 0;
1978 if (ei)
1979 ei->cache_info.send_unencrypted = 0;
1980 } else {
1981 ri->cache_info.send_unencrypted = 1;
1982 if (ei)
1983 ei->cache_info.send_unencrypted = 1;
1986 router_get_router_hash(ri->cache_info.signed_descriptor_body,
1987 strlen(ri->cache_info.signed_descriptor_body),
1988 ri->cache_info.signed_descriptor_digest);
1990 if (ei) {
1991 tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
1994 routerinfo_free(desc_routerinfo);
1995 desc_routerinfo = ri;
1996 extrainfo_free(desc_extrainfo);
1997 desc_extrainfo = ei;
1999 desc_clean_since = time(NULL);
2000 desc_needs_upload = 1;
2001 desc_gen_reason = desc_dirty_reason;
2002 desc_dirty_reason = NULL;
2003 control_event_my_descriptor_changed();
2004 return 0;
2007 /** If our router descriptor ever goes this long without being regenerated
2008 * because something changed, we force an immediate regenerate-and-upload. */
2009 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
2011 /** If our router descriptor seems to be missing or unacceptable according
2012 * to the authorities, regenerate and reupload it _this_ often. */
2013 #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
2015 /** Mark descriptor out of date if it's been "too long" since we last tried
2016 * to upload one. */
2017 void
2018 mark_my_descriptor_dirty_if_too_old(time_t now)
2020 networkstatus_t *ns;
2021 const routerstatus_t *rs;
2022 const char *retry_fast_reason = NULL; /* Set if we should retry frequently */
2023 const time_t slow_cutoff = now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL;
2024 const time_t fast_cutoff = now - FAST_RETRY_DESCRIPTOR_INTERVAL;
2026 /* If it's already dirty, don't mark it. */
2027 if (! desc_clean_since)
2028 return;
2030 /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
2031 * time to rebuild it. */
2032 if (desc_clean_since < slow_cutoff) {
2033 mark_my_descriptor_dirty("time for new descriptor");
2034 return;
2036 /* Now we see whether we want to be retrying frequently or no. The
2037 * rule here is that we'll retry frequently if we aren't listed in the
2038 * live consensus we have, or if the publication time of the
2039 * descriptor listed for us in the consensus is very old. */
2040 ns = networkstatus_get_live_consensus(now);
2041 if (ns) {
2042 rs = networkstatus_vote_find_entry(ns, server_identitykey_digest);
2043 if (rs == NULL)
2044 retry_fast_reason = "not listed in consensus";
2045 else if (rs->published_on < slow_cutoff)
2046 retry_fast_reason = "version listed in consensus is quite old";
2049 if (retry_fast_reason && desc_clean_since < fast_cutoff)
2050 mark_my_descriptor_dirty(retry_fast_reason);
2053 /** Call when the current descriptor is out of date. */
2054 void
2055 mark_my_descriptor_dirty(const char *reason)
2057 const or_options_t *options = get_options();
2058 if (server_mode(options) && options->PublishServerDescriptor_)
2059 log_info(LD_OR, "Decided to publish new relay descriptor: %s", reason);
2060 desc_clean_since = 0;
2061 if (!desc_dirty_reason)
2062 desc_dirty_reason = reason;
2065 /** How frequently will we republish our descriptor because of large (factor
2066 * of 2) shifts in estimated bandwidth? */
2067 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
2069 /** Check whether bandwidth has changed a lot since the last time we announced
2070 * bandwidth. If so, mark our descriptor dirty. */
2071 void
2072 check_descriptor_bandwidth_changed(time_t now)
2074 static time_t last_changed = 0;
2075 uint64_t prev, cur;
2076 if (!desc_routerinfo)
2077 return;
2079 prev = desc_routerinfo->bandwidthcapacity;
2080 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
2081 if ((prev != cur && (!prev || !cur)) ||
2082 cur > prev*2 ||
2083 cur < prev/2) {
2084 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
2085 log_info(LD_GENERAL,
2086 "Measured bandwidth has changed; rebuilding descriptor.");
2087 mark_my_descriptor_dirty("bandwidth has changed");
2088 last_changed = now;
2093 /** Note at log level severity that our best guess of address has changed from
2094 * <b>prev</b> to <b>cur</b>. */
2095 static void
2096 log_addr_has_changed(int severity,
2097 const tor_addr_t *prev,
2098 const tor_addr_t *cur,
2099 const char *source)
2101 char addrbuf_prev[TOR_ADDR_BUF_LEN];
2102 char addrbuf_cur[TOR_ADDR_BUF_LEN];
2104 if (tor_addr_to_str(addrbuf_prev, prev, sizeof(addrbuf_prev), 1) == NULL)
2105 strlcpy(addrbuf_prev, "???", TOR_ADDR_BUF_LEN);
2106 if (tor_addr_to_str(addrbuf_cur, cur, sizeof(addrbuf_cur), 1) == NULL)
2107 strlcpy(addrbuf_cur, "???", TOR_ADDR_BUF_LEN);
2109 if (!tor_addr_is_null(prev))
2110 log_fn(severity, LD_GENERAL,
2111 "Our IP Address has changed from %s to %s; "
2112 "rebuilding descriptor (source: %s).",
2113 addrbuf_prev, addrbuf_cur, source);
2114 else
2115 log_notice(LD_GENERAL,
2116 "Guessed our IP address as %s (source: %s).",
2117 addrbuf_cur, source);
2120 /** Check whether our own address as defined by the Address configuration
2121 * has changed. This is for routers that get their address from a service
2122 * like dyndns. If our address has changed, mark our descriptor dirty. */
2123 void
2124 check_descriptor_ipaddress_changed(time_t now)
2126 uint32_t prev, cur;
2127 const or_options_t *options = get_options();
2128 const char *method = NULL;
2129 char *hostname = NULL;
2131 (void) now;
2133 if (!desc_routerinfo)
2134 return;
2136 /* XXXX ipv6 */
2137 prev = desc_routerinfo->addr;
2138 if (resolve_my_address(LOG_INFO, options, &cur, &method, &hostname) < 0) {
2139 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
2140 return;
2143 if (prev != cur) {
2144 char *source;
2145 tor_addr_t tmp_prev, tmp_cur;
2147 tor_addr_from_ipv4h(&tmp_prev, prev);
2148 tor_addr_from_ipv4h(&tmp_cur, cur);
2150 tor_asprintf(&source, "METHOD=%s%s%s", method,
2151 hostname ? " HOSTNAME=" : "",
2152 hostname ? hostname : "");
2154 log_addr_has_changed(LOG_NOTICE, &tmp_prev, &tmp_cur, source);
2155 tor_free(source);
2157 ip_address_changed(0);
2160 tor_free(hostname);
2163 /** The most recently guessed value of our IP address, based on directory
2164 * headers. */
2165 static tor_addr_t last_guessed_ip = TOR_ADDR_NULL;
2167 /** A directory server <b>d_conn</b> told us our IP address is
2168 * <b>suggestion</b>.
2169 * If this address is different from the one we think we are now, and
2170 * if our computer doesn't actually know its IP address, then switch. */
2171 void
2172 router_new_address_suggestion(const char *suggestion,
2173 const dir_connection_t *d_conn)
2175 tor_addr_t addr;
2176 uint32_t cur = 0; /* Current IPv4 address. */
2177 const or_options_t *options = get_options();
2179 /* first, learn what the IP address actually is */
2180 if (tor_addr_parse(&addr, suggestion) == -1) {
2181 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
2182 escaped(suggestion));
2183 return;
2186 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
2188 if (!server_mode(options)) {
2189 tor_addr_copy(&last_guessed_ip, &addr);
2190 return;
2193 /* XXXX ipv6 */
2194 cur = get_last_resolved_addr();
2195 if (cur ||
2196 resolve_my_address(LOG_INFO, options, &cur, NULL, NULL) >= 0) {
2197 /* We're all set -- we already know our address. Great. */
2198 tor_addr_from_ipv4h(&last_guessed_ip, cur); /* store it in case we
2199 need it later */
2200 return;
2202 if (tor_addr_is_internal(&addr, 0)) {
2203 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
2204 return;
2206 if (tor_addr_eq(&d_conn->base_.addr, &addr)) {
2207 /* Don't believe anybody who says our IP is their IP. */
2208 log_debug(LD_DIR, "A directory server told us our IP address is %s, "
2209 "but he's just reporting his own IP address. Ignoring.",
2210 suggestion);
2211 return;
2214 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
2215 * us an answer different from what we had the last time we managed to
2216 * resolve it. */
2217 if (!tor_addr_eq(&last_guessed_ip, &addr)) {
2218 control_event_server_status(LOG_NOTICE,
2219 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
2220 suggestion);
2221 log_addr_has_changed(LOG_NOTICE, &last_guessed_ip, &addr,
2222 d_conn->base_.address);
2223 ip_address_changed(0);
2224 tor_addr_copy(&last_guessed_ip, &addr); /* router_rebuild_descriptor()
2225 will fetch it */
2229 /** We failed to resolve our address locally, but we'd like to build
2230 * a descriptor and publish / test reachability. If we have a guess
2231 * about our address based on directory headers, answer it and return
2232 * 0; else return -1. */
2233 static int
2234 router_guess_address_from_dir_headers(uint32_t *guess)
2236 if (!tor_addr_is_null(&last_guessed_ip)) {
2237 *guess = tor_addr_to_ipv4h(&last_guessed_ip);
2238 return 0;
2240 return -1;
2243 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
2244 * string describing the version of Tor and the operating system we're
2245 * currently running on.
2247 STATIC void
2248 get_platform_str(char *platform, size_t len)
2250 tor_snprintf(platform, len, "Tor %s on %s",
2251 get_short_version(), get_uname());
2254 /* XXX need to audit this thing and count fenceposts. maybe
2255 * refactor so we don't have to keep asking if we're
2256 * near the end of maxlen?
2258 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2260 /** OR only: Given a routerinfo for this router, and an identity key to sign
2261 * with, encode the routerinfo as a signed server descriptor and return a new
2262 * string encoding the result, or NULL on failure.
2264 char *
2265 router_dump_router_to_string(routerinfo_t *router,
2266 crypto_pk_t *ident_key)
2268 char *address = NULL;
2269 char *onion_pkey = NULL; /* Onion key, PEM-encoded. */
2270 char *identity_pkey = NULL; /* Identity key, PEM-encoded. */
2271 char digest[DIGEST_LEN];
2272 char published[ISO_TIME_LEN+1];
2273 char fingerprint[FINGERPRINT_LEN+1];
2274 int has_extra_info_digest;
2275 char extra_info_digest[HEX_DIGEST_LEN+1];
2276 size_t onion_pkeylen, identity_pkeylen;
2277 char *family_line = NULL;
2278 char *extra_or_address = NULL;
2279 const or_options_t *options = get_options();
2280 smartlist_t *chunks = NULL;
2281 char *output = NULL;
2283 /* Make sure the identity key matches the one in the routerinfo. */
2284 if (!crypto_pk_eq_keys(ident_key, router->identity_pkey)) {
2285 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
2286 "match router's public key!");
2287 goto err;
2290 /* record our fingerprint, so we can include it in the descriptor */
2291 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
2292 log_err(LD_BUG,"Error computing fingerprint");
2293 goto err;
2296 /* PEM-encode the onion key */
2297 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
2298 &onion_pkey,&onion_pkeylen)<0) {
2299 log_warn(LD_BUG,"write onion_pkey to string failed!");
2300 goto err;
2303 /* PEM-encode the identity key */
2304 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
2305 &identity_pkey,&identity_pkeylen)<0) {
2306 log_warn(LD_BUG,"write identity_pkey to string failed!");
2307 goto err;
2310 /* Encode the publication time. */
2311 format_iso_time(published, router->cache_info.published_on);
2313 if (router->declared_family && smartlist_len(router->declared_family)) {
2314 char *family = smartlist_join_strings(router->declared_family,
2315 " ", 0, NULL);
2316 tor_asprintf(&family_line, "family %s\n", family);
2317 tor_free(family);
2318 } else {
2319 family_line = tor_strdup("");
2322 has_extra_info_digest =
2323 ! tor_digest_is_zero(router->cache_info.extra_info_digest);
2325 if (has_extra_info_digest) {
2326 base16_encode(extra_info_digest, sizeof(extra_info_digest),
2327 router->cache_info.extra_info_digest, DIGEST_LEN);
2330 if (router->ipv6_orport &&
2331 tor_addr_family(&router->ipv6_addr) == AF_INET6) {
2332 char addr[TOR_ADDR_BUF_LEN];
2333 const char *a;
2334 a = tor_addr_to_str(addr, &router->ipv6_addr, sizeof(addr), 1);
2335 if (a) {
2336 tor_asprintf(&extra_or_address,
2337 "or-address %s:%d\n", a, router->ipv6_orport);
2338 log_debug(LD_OR, "My or-address line is <%s>", extra_or_address);
2342 address = tor_dup_ip(router->addr);
2343 chunks = smartlist_new();
2345 /* Generate the easy portion of the router descriptor. */
2346 smartlist_add_asprintf(chunks,
2347 "router %s %s %d 0 %d\n"
2348 "%s"
2349 "platform %s\n"
2350 "protocols Link 1 2 Circuit 1\n"
2351 "published %s\n"
2352 "fingerprint %s\n"
2353 "uptime %ld\n"
2354 "bandwidth %d %d %d\n"
2355 "%s%s%s%s"
2356 "onion-key\n%s"
2357 "signing-key\n%s"
2358 "%s%s%s%s",
2359 router->nickname,
2360 address,
2361 router->or_port,
2362 decide_to_advertise_dirport(options, router->dir_port),
2363 extra_or_address ? extra_or_address : "",
2364 router->platform,
2365 published,
2366 fingerprint,
2367 stats_n_seconds_working,
2368 (int) router->bandwidthrate,
2369 (int) router->bandwidthburst,
2370 (int) router->bandwidthcapacity,
2371 has_extra_info_digest ? "extra-info-digest " : "",
2372 has_extra_info_digest ? extra_info_digest : "",
2373 has_extra_info_digest ? "\n" : "",
2374 options->DownloadExtraInfo ? "caches-extra-info\n" : "",
2375 onion_pkey, identity_pkey,
2376 family_line,
2377 we_are_hibernating() ? "hibernating 1\n" : "",
2378 options->HidServDirectoryV2 ? "hidden-service-dir\n" : "",
2379 options->AllowSingleHopExits ? "allow-single-hop-exits\n" : "");
2381 if (options->ContactInfo && strlen(options->ContactInfo)) {
2382 const char *ci = options->ContactInfo;
2383 if (strchr(ci, '\n') || strchr(ci, '\r'))
2384 ci = escaped(ci);
2385 smartlist_add_asprintf(chunks, "contact %s\n", ci);
2388 if (options->BridgeRelay) {
2389 const char *bd;
2390 if (options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
2391 bd = "any";
2392 else
2393 bd = "none";
2394 smartlist_add_asprintf(chunks, "bridge-distribution-request %s\n", bd);
2397 #ifdef CURVE25519_ENABLED
2398 if (router->onion_curve25519_pkey) {
2399 char kbuf[128];
2400 base64_encode(kbuf, sizeof(kbuf),
2401 (const char *)router->onion_curve25519_pkey->public_key,
2402 CURVE25519_PUBKEY_LEN);
2403 smartlist_add_asprintf(chunks, "ntor-onion-key %s", kbuf);
2405 #endif
2407 /* Write the exit policy to the end of 's'. */
2408 if (!router->exit_policy || !smartlist_len(router->exit_policy)) {
2409 smartlist_add(chunks, tor_strdup("reject *:*\n"));
2410 } else if (router->exit_policy) {
2411 char *exit_policy = router_dump_exit_policy_to_string(router,1,0);
2413 if (!exit_policy)
2414 goto err;
2416 smartlist_add_asprintf(chunks, "%s\n", exit_policy);
2417 tor_free(exit_policy);
2420 if (router->ipv6_exit_policy) {
2421 char *p6 = write_short_policy(router->ipv6_exit_policy);
2422 if (p6 && strcmp(p6, "reject 1-65535")) {
2423 smartlist_add_asprintf(chunks,
2424 "ipv6-policy %s\n", p6);
2426 tor_free(p6);
2429 /* Sign the descriptor */
2430 smartlist_add(chunks, tor_strdup("router-signature\n"));
2432 crypto_digest_smartlist(digest, DIGEST_LEN, chunks, "", DIGEST_SHA1);
2434 note_crypto_pk_op(SIGN_RTR);
2436 char *sig;
2437 if (!(sig = router_get_dirobj_signature(digest, DIGEST_LEN, ident_key))) {
2438 log_warn(LD_BUG, "Couldn't sign router descriptor");
2439 goto err;
2441 smartlist_add(chunks, sig);
2444 /* include a last '\n' */
2445 smartlist_add(chunks, tor_strdup("\n"));
2447 output = smartlist_join_strings(chunks, "", 0, NULL);
2449 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2451 char *s_dup;
2452 const char *cp;
2453 routerinfo_t *ri_tmp;
2454 cp = s_dup = tor_strdup(output);
2455 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
2456 if (!ri_tmp) {
2457 log_err(LD_BUG,
2458 "We just generated a router descriptor we can't parse.");
2459 log_err(LD_BUG, "Descriptor was: <<%s>>", output);
2460 goto err;
2462 tor_free(s_dup);
2463 routerinfo_free(ri_tmp);
2465 #endif
2467 goto done;
2469 err:
2470 tor_free(output); /* sets output to NULL */
2471 done:
2472 if (chunks) {
2473 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
2474 smartlist_free(chunks);
2476 tor_free(address);
2477 tor_free(family_line);
2478 tor_free(onion_pkey);
2479 tor_free(identity_pkey);
2480 tor_free(extra_or_address);
2482 return output;
2486 * OR only: Given <b>router</b>, produce a string with its exit policy.
2487 * If <b>include_ipv4</b> is true, include IPv4 entries.
2488 * If <b>include_ipv6</b> is true, include IPv6 entries.
2490 char *
2491 router_dump_exit_policy_to_string(const routerinfo_t *router,
2492 int include_ipv4,
2493 int include_ipv6)
2495 smartlist_t *exit_policy_strings;
2496 char *policy_string = NULL;
2498 if ((!router->exit_policy) || (router->policy_is_reject_star)) {
2499 return tor_strdup("reject *:*");
2502 exit_policy_strings = smartlist_new();
2504 SMARTLIST_FOREACH_BEGIN(router->exit_policy, addr_policy_t *, tmpe) {
2505 char *pbuf;
2506 int bytes_written_to_pbuf;
2507 if ((tor_addr_family(&tmpe->addr) == AF_INET6) && (!include_ipv6)) {
2508 continue; /* Don't include IPv6 parts of address policy */
2510 if ((tor_addr_family(&tmpe->addr) == AF_INET) && (!include_ipv4)) {
2511 continue; /* Don't include IPv4 parts of address policy */
2514 pbuf = tor_malloc(POLICY_BUF_LEN);
2515 bytes_written_to_pbuf = policy_write_item(pbuf,POLICY_BUF_LEN, tmpe, 1);
2517 if (bytes_written_to_pbuf < 0) {
2518 log_warn(LD_BUG, "router_dump_exit_policy_to_string ran out of room!");
2519 tor_free(pbuf);
2520 goto done;
2523 smartlist_add(exit_policy_strings,pbuf);
2524 } SMARTLIST_FOREACH_END(tmpe);
2526 policy_string = smartlist_join_strings(exit_policy_strings, "\n", 0, NULL);
2528 done:
2529 SMARTLIST_FOREACH(exit_policy_strings, char *, str, tor_free(str));
2530 smartlist_free(exit_policy_strings);
2532 return policy_string;
2535 /** Copy the primary (IPv4) OR port (IP address and TCP port) for
2536 * <b>router</b> into *<b>ap_out</b>. */
2537 void
2538 router_get_prim_orport(const routerinfo_t *router, tor_addr_port_t *ap_out)
2540 tor_assert(ap_out != NULL);
2541 tor_addr_from_ipv4h(&ap_out->addr, router->addr);
2542 ap_out->port = router->or_port;
2545 /** Return 1 if any of <b>router</b>'s addresses are <b>addr</b>.
2546 * Otherwise return 0. */
2548 router_has_addr(const routerinfo_t *router, const tor_addr_t *addr)
2550 return
2551 tor_addr_eq_ipv4h(addr, router->addr) ||
2552 tor_addr_eq(&router->ipv6_addr, addr);
2556 router_has_orport(const routerinfo_t *router, const tor_addr_port_t *orport)
2558 return
2559 (tor_addr_eq_ipv4h(&orport->addr, router->addr) &&
2560 orport->port == router->or_port) ||
2561 (tor_addr_eq(&orport->addr, &router->ipv6_addr) &&
2562 orport->port == router->ipv6_orport);
2565 /** Load the contents of <b>filename</b>, find the last line starting with
2566 * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
2567 * the past or more than 1 hour in the future with respect to <b>now</b>,
2568 * and write the file contents starting with that line to *<b>out</b>.
2569 * Return 1 for success, 0 if the file does not exist, or -1 if the file
2570 * does not contain a line matching these criteria or other failure. */
2571 static int
2572 load_stats_file(const char *filename, const char *end_line, time_t now,
2573 char **out)
2575 int r = -1;
2576 char *fname = get_datadir_fname(filename);
2577 char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
2578 time_t written;
2579 switch (file_status(fname)) {
2580 case FN_FILE:
2581 /* X022 Find an alternative to reading the whole file to memory. */
2582 if ((contents = read_file_to_str(fname, 0, NULL))) {
2583 tmp = strstr(contents, end_line);
2584 /* Find last block starting with end_line */
2585 while (tmp) {
2586 start = tmp;
2587 tmp = strstr(tmp + 1, end_line);
2589 if (!start)
2590 goto notfound;
2591 if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
2592 goto notfound;
2593 strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
2594 if (parse_iso_time(timestr, &written) < 0)
2595 goto notfound;
2596 if (written < now - (25*60*60) || written > now + (1*60*60))
2597 goto notfound;
2598 *out = tor_strdup(start);
2599 r = 1;
2601 notfound:
2602 tor_free(contents);
2603 break;
2604 case FN_NOENT:
2605 r = 0;
2606 break;
2607 case FN_ERROR:
2608 case FN_DIR:
2609 default:
2610 break;
2612 tor_free(fname);
2613 return r;
2616 /** Write the contents of <b>extrainfo</b> and aggregated statistics to
2617 * *<b>s_out</b>, signing them with <b>ident_key</b>. Return 0 on
2618 * success, negative on failure. */
2620 extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo,
2621 crypto_pk_t *ident_key)
2623 const or_options_t *options = get_options();
2624 char identity[HEX_DIGEST_LEN+1];
2625 char published[ISO_TIME_LEN+1];
2626 char digest[DIGEST_LEN];
2627 char *bandwidth_usage;
2628 int result;
2629 static int write_stats_to_extrainfo = 1;
2630 char sig[DIROBJ_MAX_SIG_LEN+1];
2631 char *s, *pre, *contents, *cp, *s_dup = NULL;
2632 time_t now = time(NULL);
2633 smartlist_t *chunks = smartlist_new();
2634 extrainfo_t *ei_tmp = NULL;
2636 base16_encode(identity, sizeof(identity),
2637 extrainfo->cache_info.identity_digest, DIGEST_LEN);
2638 format_iso_time(published, extrainfo->cache_info.published_on);
2639 bandwidth_usage = rep_hist_get_bandwidth_lines();
2641 tor_asprintf(&pre, "extra-info %s %s\npublished %s\n%s",
2642 extrainfo->nickname, identity,
2643 published, bandwidth_usage);
2644 tor_free(bandwidth_usage);
2645 smartlist_add(chunks, pre);
2647 if (geoip_is_loaded(AF_INET))
2648 smartlist_add_asprintf(chunks, "geoip-db-digest %s\n",
2649 geoip_db_digest(AF_INET));
2650 if (geoip_is_loaded(AF_INET6))
2651 smartlist_add_asprintf(chunks, "geoip6-db-digest %s\n",
2652 geoip_db_digest(AF_INET6));
2654 if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
2655 log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
2656 if (options->DirReqStatistics &&
2657 load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
2658 "dirreq-stats-end", now, &contents) > 0) {
2659 smartlist_add(chunks, contents);
2661 if (options->EntryStatistics &&
2662 load_stats_file("stats"PATH_SEPARATOR"entry-stats",
2663 "entry-stats-end", now, &contents) > 0) {
2664 smartlist_add(chunks, contents);
2666 if (options->CellStatistics &&
2667 load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
2668 "cell-stats-end", now, &contents) > 0) {
2669 smartlist_add(chunks, contents);
2671 if (options->ExitPortStatistics &&
2672 load_stats_file("stats"PATH_SEPARATOR"exit-stats",
2673 "exit-stats-end", now, &contents) > 0) {
2674 smartlist_add(chunks, contents);
2676 if (options->ConnDirectionStatistics &&
2677 load_stats_file("stats"PATH_SEPARATOR"conn-stats",
2678 "conn-bi-direct", now, &contents) > 0) {
2679 smartlist_add(chunks, contents);
2683 /* Add information about the pluggable transports we support. */
2684 if (options->ServerTransportPlugin) {
2685 char *pluggable_transports = pt_get_extra_info_descriptor_string();
2686 if (pluggable_transports)
2687 smartlist_add(chunks, pluggable_transports);
2690 if (should_record_bridge_info(options) && write_stats_to_extrainfo) {
2691 const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
2692 if (bridge_stats) {
2693 smartlist_add(chunks, tor_strdup(bridge_stats));
2697 smartlist_add(chunks, tor_strdup("router-signature\n"));
2698 s = smartlist_join_strings(chunks, "", 0, NULL);
2700 while (strlen(s) > MAX_EXTRAINFO_UPLOAD_SIZE - DIROBJ_MAX_SIG_LEN) {
2701 /* So long as there are at least two chunks (one for the initial
2702 * extra-info line and one for the router-signature), we can keep removing
2703 * things. */
2704 if (smartlist_len(chunks) > 2) {
2705 /* We remove the next-to-last element (remember, len-1 is the last
2706 element), since we need to keep the router-signature element. */
2707 int idx = smartlist_len(chunks) - 2;
2708 char *e = smartlist_get(chunks, idx);
2709 smartlist_del_keeporder(chunks, idx);
2710 log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
2711 "with statistics that exceeds the 50 KB "
2712 "upload limit. Removing last added "
2713 "statistics.");
2714 tor_free(e);
2715 tor_free(s);
2716 s = smartlist_join_strings(chunks, "", 0, NULL);
2717 } else {
2718 log_warn(LD_BUG, "We just generated an extra-info descriptors that "
2719 "exceeds the 50 KB upload limit.");
2720 goto err;
2724 memset(sig, 0, sizeof(sig));
2725 if (router_get_extrainfo_hash(s, strlen(s), digest) < 0 ||
2726 router_append_dirobj_signature(sig, sizeof(sig), digest, DIGEST_LEN,
2727 ident_key) < 0) {
2728 log_warn(LD_BUG, "Could not append signature to extra-info "
2729 "descriptor.");
2730 goto err;
2732 smartlist_add(chunks, tor_strdup(sig));
2733 tor_free(s);
2734 s = smartlist_join_strings(chunks, "", 0, NULL);
2736 cp = s_dup = tor_strdup(s);
2737 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
2738 if (!ei_tmp) {
2739 if (write_stats_to_extrainfo) {
2740 log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
2741 "with statistics that we can't parse. Not "
2742 "adding statistics to this or any future "
2743 "extra-info descriptors.");
2744 write_stats_to_extrainfo = 0;
2745 result = extrainfo_dump_to_string(s_out, extrainfo, ident_key);
2746 goto done;
2747 } else {
2748 log_warn(LD_BUG, "We just generated an extrainfo descriptor we "
2749 "can't parse.");
2750 goto err;
2754 *s_out = s;
2755 s = NULL; /* prevent free */
2756 result = 0;
2757 goto done;
2759 err:
2760 result = -1;
2762 done:
2763 tor_free(s);
2764 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
2765 smartlist_free(chunks);
2766 tor_free(s_dup);
2767 extrainfo_free(ei_tmp);
2769 return result;
2772 /** Return true iff <b>s</b> is a valid server nickname. (That is, a string
2773 * containing between 1 and MAX_NICKNAME_LEN characters from
2774 * LEGAL_NICKNAME_CHARACTERS.) */
2776 is_legal_nickname(const char *s)
2778 size_t len;
2779 tor_assert(s);
2780 len = strlen(s);
2781 return len > 0 && len <= MAX_NICKNAME_LEN &&
2782 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
2785 /** Return true iff <b>s</b> is a valid server nickname or
2786 * hex-encoded identity-key digest. */
2788 is_legal_nickname_or_hexdigest(const char *s)
2790 if (*s!='$')
2791 return is_legal_nickname(s);
2792 else
2793 return is_legal_hexdigest(s);
2796 /** Return true iff <b>s</b> is a valid hex-encoded identity-key
2797 * digest. (That is, an optional $, followed by 40 hex characters,
2798 * followed by either nothing, or = or ~ followed by a nickname, or
2799 * a character other than =, ~, or a hex character.)
2802 is_legal_hexdigest(const char *s)
2804 size_t len;
2805 tor_assert(s);
2806 if (s[0] == '$') s++;
2807 len = strlen(s);
2808 if (len > HEX_DIGEST_LEN) {
2809 if (s[HEX_DIGEST_LEN] == '=' ||
2810 s[HEX_DIGEST_LEN] == '~') {
2811 if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
2812 return 0;
2813 } else {
2814 return 0;
2817 return (len >= HEX_DIGEST_LEN &&
2818 strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
2821 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2822 * hold a human-readable description of a node with identity digest
2823 * <b>id_digest</b>, named-status <b>is_named</b>, nickname <b>nickname</b>,
2824 * and address <b>addr</b> or <b>addr32h</b>.
2826 * The <b>nickname</b> and <b>addr</b> fields are optional and may be set to
2827 * NULL. The <b>addr32h</b> field is optional and may be set to 0.
2829 * Return a pointer to the front of <b>buf</b>.
2831 const char *
2832 format_node_description(char *buf,
2833 const char *id_digest,
2834 int is_named,
2835 const char *nickname,
2836 const tor_addr_t *addr,
2837 uint32_t addr32h)
2839 char *cp;
2841 if (!buf)
2842 return "<NULL BUFFER>";
2844 buf[0] = '$';
2845 base16_encode(buf+1, HEX_DIGEST_LEN+1, id_digest, DIGEST_LEN);
2846 cp = buf+1+HEX_DIGEST_LEN;
2847 if (nickname) {
2848 buf[1+HEX_DIGEST_LEN] = is_named ? '=' : '~';
2849 strlcpy(buf+1+HEX_DIGEST_LEN+1, nickname, MAX_NICKNAME_LEN+1);
2850 cp += strlen(cp);
2852 if (addr32h || addr) {
2853 memcpy(cp, " at ", 4);
2854 cp += 4;
2855 if (addr) {
2856 tor_addr_to_str(cp, addr, TOR_ADDR_BUF_LEN, 0);
2857 } else {
2858 struct in_addr in;
2859 in.s_addr = htonl(addr32h);
2860 tor_inet_ntoa(&in, cp, INET_NTOA_BUF_LEN);
2863 return buf;
2866 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2867 * hold a human-readable description of <b>ri</b>.
2870 * Return a pointer to the front of <b>buf</b>.
2872 const char *
2873 router_get_description(char *buf, const routerinfo_t *ri)
2875 if (!ri)
2876 return "<null>";
2877 return format_node_description(buf,
2878 ri->cache_info.identity_digest,
2879 router_is_named(ri),
2880 ri->nickname,
2881 NULL,
2882 ri->addr);
2885 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2886 * hold a human-readable description of <b>node</b>.
2888 * Return a pointer to the front of <b>buf</b>.
2890 const char *
2891 node_get_description(char *buf, const node_t *node)
2893 const char *nickname = NULL;
2894 uint32_t addr32h = 0;
2895 int is_named = 0;
2897 if (!node)
2898 return "<null>";
2900 if (node->rs) {
2901 nickname = node->rs->nickname;
2902 is_named = node->rs->is_named;
2903 addr32h = node->rs->addr;
2904 } else if (node->ri) {
2905 nickname = node->ri->nickname;
2906 addr32h = node->ri->addr;
2909 return format_node_description(buf,
2910 node->identity,
2911 is_named,
2912 nickname,
2913 NULL,
2914 addr32h);
2917 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2918 * hold a human-readable description of <b>rs</b>.
2920 * Return a pointer to the front of <b>buf</b>.
2922 const char *
2923 routerstatus_get_description(char *buf, const routerstatus_t *rs)
2925 if (!rs)
2926 return "<null>";
2927 return format_node_description(buf,
2928 rs->identity_digest,
2929 rs->is_named,
2930 rs->nickname,
2931 NULL,
2932 rs->addr);
2935 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2936 * hold a human-readable description of <b>ei</b>.
2938 * Return a pointer to the front of <b>buf</b>.
2940 const char *
2941 extend_info_get_description(char *buf, const extend_info_t *ei)
2943 if (!ei)
2944 return "<null>";
2945 return format_node_description(buf,
2946 ei->identity_digest,
2948 ei->nickname,
2949 &ei->addr,
2953 /** Return a human-readable description of the routerinfo_t <b>ri</b>.
2955 * This function is not thread-safe. Each call to this function invalidates
2956 * previous values returned by this function.
2958 const char *
2959 router_describe(const routerinfo_t *ri)
2961 static char buf[NODE_DESC_BUF_LEN];
2962 return router_get_description(buf, ri);
2965 /** Return a human-readable description of the node_t <b>node</b>.
2967 * This function is not thread-safe. Each call to this function invalidates
2968 * previous values returned by this function.
2970 const char *
2971 node_describe(const node_t *node)
2973 static char buf[NODE_DESC_BUF_LEN];
2974 return node_get_description(buf, node);
2977 /** Return a human-readable description of the routerstatus_t <b>rs</b>.
2979 * This function is not thread-safe. Each call to this function invalidates
2980 * previous values returned by this function.
2982 const char *
2983 routerstatus_describe(const routerstatus_t *rs)
2985 static char buf[NODE_DESC_BUF_LEN];
2986 return routerstatus_get_description(buf, rs);
2989 /** Return a human-readable description of the extend_info_t <b>ri</b>.
2991 * This function is not thread-safe. Each call to this function invalidates
2992 * previous values returned by this function.
2994 const char *
2995 extend_info_describe(const extend_info_t *ei)
2997 static char buf[NODE_DESC_BUF_LEN];
2998 return extend_info_get_description(buf, ei);
3001 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
3002 * verbose representation of the identity of <b>router</b>. The format is:
3003 * A dollar sign.
3004 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
3005 * A "=" if the router is named; a "~" if it is not.
3006 * The router's nickname.
3008 void
3009 router_get_verbose_nickname(char *buf, const routerinfo_t *router)
3011 const char *good_digest = networkstatus_get_router_digest_by_nickname(
3012 router->nickname);
3013 int is_named = good_digest && tor_memeq(good_digest,
3014 router->cache_info.identity_digest,
3015 DIGEST_LEN);
3016 buf[0] = '$';
3017 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
3018 DIGEST_LEN);
3019 buf[1+HEX_DIGEST_LEN] = is_named ? '=' : '~';
3020 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
3023 /** Forget that we have issued any router-related warnings, so that we'll
3024 * warn again if we see the same errors. */
3025 void
3026 router_reset_warnings(void)
3028 if (warned_nonexistent_family) {
3029 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
3030 smartlist_clear(warned_nonexistent_family);
3034 /** Given a router purpose, convert it to a string. Don't call this on
3035 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
3036 * know its string representation. */
3037 const char *
3038 router_purpose_to_string(uint8_t p)
3040 switch (p)
3042 case ROUTER_PURPOSE_GENERAL: return "general";
3043 case ROUTER_PURPOSE_BRIDGE: return "bridge";
3044 case ROUTER_PURPOSE_CONTROLLER: return "controller";
3045 default:
3046 tor_assert(0);
3048 return NULL;
3051 /** Given a string, convert it to a router purpose. */
3052 uint8_t
3053 router_purpose_from_string(const char *s)
3055 if (!strcmp(s, "general"))
3056 return ROUTER_PURPOSE_GENERAL;
3057 else if (!strcmp(s, "bridge"))
3058 return ROUTER_PURPOSE_BRIDGE;
3059 else if (!strcmp(s, "controller"))
3060 return ROUTER_PURPOSE_CONTROLLER;
3061 else
3062 return ROUTER_PURPOSE_UNKNOWN;
3065 /** Release all static resources held in router.c */
3066 void
3067 router_free_all(void)
3069 crypto_pk_free(onionkey);
3070 crypto_pk_free(lastonionkey);
3071 crypto_pk_free(server_identitykey);
3072 crypto_pk_free(client_identitykey);
3073 tor_mutex_free(key_lock);
3074 routerinfo_free(desc_routerinfo);
3075 extrainfo_free(desc_extrainfo);
3076 crypto_pk_free(authority_signing_key);
3077 authority_cert_free(authority_key_certificate);
3078 crypto_pk_free(legacy_signing_key);
3079 authority_cert_free(legacy_key_certificate);
3081 #ifdef CURVE25519_ENABLED
3082 memwipe(&curve25519_onion_key, 0, sizeof(curve25519_onion_key));
3083 memwipe(&last_curve25519_onion_key, 0, sizeof(last_curve25519_onion_key));
3084 #endif
3086 if (warned_nonexistent_family) {
3087 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
3088 smartlist_free(warned_nonexistent_family);
3092 /** Return a smartlist of tor_addr_port_t's with all the OR ports of
3093 <b>ri</b>. Note that freeing of the items in the list as well as
3094 the smartlist itself is the callers responsibility.
3096 XXX duplicating code from node_get_all_orports(). */
3097 smartlist_t *
3098 router_get_all_orports(const routerinfo_t *ri)
3100 smartlist_t *sl = smartlist_new();
3101 tor_assert(ri);
3103 if (ri->addr != 0) {
3104 tor_addr_port_t *ap = tor_malloc(sizeof(tor_addr_port_t));
3105 tor_addr_from_ipv4h(&ap->addr, ri->addr);
3106 ap->port = ri->or_port;
3107 smartlist_add(sl, ap);
3109 if (!tor_addr_is_null(&ri->ipv6_addr)) {
3110 tor_addr_port_t *ap = tor_malloc(sizeof(tor_addr_port_t));
3111 tor_addr_copy(&ap->addr, &ri->ipv6_addr);
3112 ap->port = ri->or_port;
3113 smartlist_add(sl, ap);
3116 return sl;