Stop trying to generate test scripts via autoconf substitution.
[tor.git] / src / or / router.c
blob8fdad9a5fad64f9fef6fd6977ad4362c1fd445ca
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-2015, 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 "routerkeys.h"
30 #include "routerlist.h"
31 #include "routerparse.h"
32 #include "statefile.h"
33 #include "torcert.h"
34 #include "transports.h"
35 #include "routerset.h"
37 /**
38 * \file router.c
39 * \brief OR functionality, including key maintenance, generating
40 * and uploading server descriptors, retrying OR connections.
41 **/
43 extern long stats_n_seconds_working;
45 /************************************************************/
47 /*****
48 * Key management: ORs only.
49 *****/
51 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
53 static tor_mutex_t *key_lock=NULL;
54 static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
55 /** Current private onionskin decryption key: used to decode CREATE cells. */
56 static crypto_pk_t *onionkey=NULL;
57 /** Previous private onionskin decryption key: used to decode CREATE cells
58 * generated by clients that have an older version of our descriptor. */
59 static crypto_pk_t *lastonionkey=NULL;
60 /** Current private ntor secret key: used to perform the ntor handshake. */
61 static curve25519_keypair_t curve25519_onion_key;
62 /** Previous private ntor secret key: used to perform the ntor handshake
63 * with clients that have an older version of our descriptor. */
64 static curve25519_keypair_t last_curve25519_onion_key;
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 /** Return the current secret onion key for the ntor handshake. Must only
138 * be called from the main thread. */
139 static const curve25519_keypair_t *
140 get_current_curve25519_keypair(void)
142 return &curve25519_onion_key;
144 /** Return a map from KEYID (the key itself) to keypairs for use in the ntor
145 * handshake. Must only be called from the main thread. */
146 di_digest256_map_t *
147 construct_ntor_key_map(void)
149 di_digest256_map_t *m = NULL;
151 dimap_add_entry(&m,
152 curve25519_onion_key.pubkey.public_key,
153 tor_memdup(&curve25519_onion_key,
154 sizeof(curve25519_keypair_t)));
155 if (!tor_mem_is_zero((const char*)
156 last_curve25519_onion_key.pubkey.public_key,
157 CURVE25519_PUBKEY_LEN)) {
158 dimap_add_entry(&m,
159 last_curve25519_onion_key.pubkey.public_key,
160 tor_memdup(&last_curve25519_onion_key,
161 sizeof(curve25519_keypair_t)));
164 return m;
166 /** Helper used to deallocate a di_digest256_map_t returned by
167 * construct_ntor_key_map. */
168 static void
169 ntor_key_map_free_helper(void *arg)
171 curve25519_keypair_t *k = arg;
172 memwipe(k, 0, sizeof(*k));
173 tor_free(k);
175 /** Release all storage from a keymap returned by construct_ntor_key_map. */
176 void
177 ntor_key_map_free(di_digest256_map_t *map)
179 if (!map)
180 return;
181 dimap_free(map, ntor_key_map_free_helper);
184 /** Return the time when the onion key was last set. This is either the time
185 * when the process launched, or the time of the most recent key rotation since
186 * the process launched.
188 time_t
189 get_onion_key_set_at(void)
191 return onionkey_set_at;
194 /** Set the current server identity key to <b>k</b>.
196 void
197 set_server_identity_key(crypto_pk_t *k)
199 crypto_pk_free(server_identitykey);
200 server_identitykey = k;
201 crypto_pk_get_digest(server_identitykey, server_identitykey_digest);
204 /** Make sure that we have set up our identity keys to match or not match as
205 * appropriate, and die with an assertion if we have not. */
206 static void
207 assert_identity_keys_ok(void)
209 if (1)
210 return;
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 curve25519_keypair_t new_curve25519_keypair;
317 time_t now;
318 fname = get_datadir_fname2("keys", "secret_onion_key");
319 fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
320 /* There isn't much point replacing an old key with an empty file */
321 if (file_status(fname) == FN_FILE) {
322 if (replace_file(fname, fname_prev))
323 goto error;
325 if (!(prkey = crypto_pk_new())) {
326 log_err(LD_GENERAL,"Error constructing rotated onion key");
327 goto error;
329 if (crypto_pk_generate_key(prkey)) {
330 log_err(LD_BUG,"Error generating onion key");
331 goto error;
333 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
334 log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
335 goto error;
337 tor_free(fname);
338 tor_free(fname_prev);
339 fname = get_datadir_fname2("keys", "secret_onion_key_ntor");
340 fname_prev = get_datadir_fname2("keys", "secret_onion_key_ntor.old");
341 if (curve25519_keypair_generate(&new_curve25519_keypair, 1) < 0)
342 goto error;
343 /* There isn't much point replacing an old key with an empty file */
344 if (file_status(fname) == FN_FILE) {
345 if (replace_file(fname, fname_prev))
346 goto error;
348 if (curve25519_keypair_write_to_file(&new_curve25519_keypair, fname,
349 "onion") < 0) {
350 log_err(LD_FS,"Couldn't write curve25519 onion key to \"%s\".",fname);
351 goto error;
353 log_info(LD_GENERAL, "Rotating onion key");
354 tor_mutex_acquire(key_lock);
355 crypto_pk_free(lastonionkey);
356 lastonionkey = onionkey;
357 onionkey = prkey;
358 memcpy(&last_curve25519_onion_key, &curve25519_onion_key,
359 sizeof(curve25519_keypair_t));
360 memcpy(&curve25519_onion_key, &new_curve25519_keypair,
361 sizeof(curve25519_keypair_t));
362 now = time(NULL);
363 state->LastRotatedOnionKey = onionkey_set_at = now;
364 tor_mutex_release(key_lock);
365 mark_my_descriptor_dirty("rotated onion key");
366 or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
367 goto done;
368 error:
369 log_warn(LD_GENERAL, "Couldn't rotate onion key.");
370 if (prkey)
371 crypto_pk_free(prkey);
372 done:
373 memwipe(&new_curve25519_keypair, 0, sizeof(new_curve25519_keypair));
374 tor_free(fname);
375 tor_free(fname_prev);
378 /** Log greeting message that points to new relay lifecycle document the
379 * first time this function has been called.
381 static void
382 log_new_relay_greeting(void)
384 static int already_logged = 0;
386 if (already_logged)
387 return;
389 tor_log(LOG_NOTICE, LD_GENERAL, "You are running a new relay. "
390 "Thanks for helping the Tor network! If you wish to know "
391 "what will happen in the upcoming weeks regarding its usage, "
392 "have a look at https://blog.torproject.org/blog/lifecycle-of"
393 "-a-new-relay");
395 already_logged = 1;
398 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
399 * and <b>generate</b> is true, create a new RSA key and save it in
400 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
401 * errors at level <b>severity</b>. If <b>log_greeting</b> is non-zero and a
402 * new key was created, log_new_relay_greeting() is called.
404 crypto_pk_t *
405 init_key_from_file(const char *fname, int generate, int severity,
406 int log_greeting)
408 crypto_pk_t *prkey = NULL;
410 if (!(prkey = crypto_pk_new())) {
411 tor_log(severity, LD_GENERAL,"Error constructing key");
412 goto error;
415 switch (file_status(fname)) {
416 case FN_DIR:
417 case FN_ERROR:
418 tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
419 goto error;
420 /* treat empty key files as if the file doesn't exist, and,
421 * if generate is set, replace the empty file in
422 * crypto_pk_write_private_key_to_filename() */
423 case FN_NOENT:
424 case FN_EMPTY:
425 if (generate) {
426 if (!have_lockfile()) {
427 if (try_locking(get_options(), 0)<0) {
428 /* Make sure that --list-fingerprint only creates new keys
429 * if there is no possibility for a deadlock. */
430 tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
431 "Not writing any new keys.", fname);
432 /*XXXX The 'other process' might make a key in a second or two;
433 * maybe we should wait for it. */
434 goto error;
437 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
438 fname);
439 if (crypto_pk_generate_key(prkey)) {
440 tor_log(severity, LD_GENERAL,"Error generating onion key");
441 goto error;
443 if (crypto_pk_check_key(prkey) <= 0) {
444 tor_log(severity, LD_GENERAL,"Generated key seems invalid");
445 goto error;
447 log_info(LD_GENERAL, "Generated key seems valid");
448 if (log_greeting) {
449 log_new_relay_greeting();
451 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
452 tor_log(severity, LD_FS,
453 "Couldn't write generated key to \"%s\".", fname);
454 goto error;
456 } else {
457 log_info(LD_GENERAL, "No key found in \"%s\"", fname);
459 return prkey;
460 case FN_FILE:
461 if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
462 tor_log(severity, LD_GENERAL,"Error loading private key.");
463 goto error;
465 return prkey;
466 default:
467 tor_assert(0);
470 error:
471 if (prkey)
472 crypto_pk_free(prkey);
473 return NULL;
476 /** Load a curve25519 keypair from the file <b>fname</b>, writing it into
477 * <b>keys_out</b>. If the file isn't found, or is empty, and <b>generate</b>
478 * is true, create a new keypair and write it into the file. If there are
479 * errors, log them at level <b>severity</b>. Generate files using <b>tag</b>
480 * in their ASCII wrapper. */
481 static int
482 init_curve25519_keypair_from_file(curve25519_keypair_t *keys_out,
483 const char *fname,
484 int generate,
485 int severity,
486 const char *tag)
488 switch (file_status(fname)) {
489 case FN_DIR:
490 case FN_ERROR:
491 tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
492 goto error;
493 /* treat empty key files as if the file doesn't exist, and, if generate
494 * is set, replace the empty file in curve25519_keypair_write_to_file() */
495 case FN_NOENT:
496 case FN_EMPTY:
497 if (generate) {
498 if (!have_lockfile()) {
499 if (try_locking(get_options(), 0)<0) {
500 /* Make sure that --list-fingerprint only creates new keys
501 * if there is no possibility for a deadlock. */
502 tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
503 "Not writing any new keys.", fname);
504 /*XXXX The 'other process' might make a key in a second or two;
505 * maybe we should wait for it. */
506 goto error;
509 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
510 fname);
511 if (curve25519_keypair_generate(keys_out, 1) < 0)
512 goto error;
513 if (curve25519_keypair_write_to_file(keys_out, fname, tag)<0) {
514 tor_log(severity, LD_FS,
515 "Couldn't write generated key to \"%s\".", fname);
516 memwipe(keys_out, 0, sizeof(*keys_out));
517 goto error;
519 } else {
520 log_info(LD_GENERAL, "No key found in \"%s\"", fname);
522 return 0;
523 case FN_FILE:
525 char *tag_in=NULL;
526 if (curve25519_keypair_read_from_file(keys_out, &tag_in, fname) < 0) {
527 tor_log(severity, LD_GENERAL,"Error loading private key.");
528 tor_free(tag_in);
529 goto error;
531 if (!tag_in || strcmp(tag_in, tag)) {
532 tor_log(severity, LD_GENERAL,"Unexpected tag %s on private key.",
533 escaped(tag_in));
534 tor_free(tag_in);
535 goto error;
537 tor_free(tag_in);
538 return 0;
540 default:
541 tor_assert(0);
544 error:
545 return -1;
548 /** Try to load the vote-signing private key and certificate for being a v3
549 * directory authority, and make sure they match. If <b>legacy</b>, load a
550 * legacy key/cert set for emergency key migration; otherwise load the regular
551 * key/cert set. On success, store them into *<b>key_out</b> and
552 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
553 static int
554 load_authority_keyset(int legacy, crypto_pk_t **key_out,
555 authority_cert_t **cert_out)
557 int r = -1;
558 char *fname = NULL, *cert = NULL;
559 const char *eos = NULL;
560 crypto_pk_t *signing_key = NULL;
561 authority_cert_t *parsed = NULL;
563 fname = get_datadir_fname2("keys",
564 legacy ? "legacy_signing_key" : "authority_signing_key");
565 signing_key = init_key_from_file(fname, 0, LOG_INFO, 0);
566 if (!signing_key) {
567 log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
568 goto done;
570 tor_free(fname);
571 fname = get_datadir_fname2("keys",
572 legacy ? "legacy_certificate" : "authority_certificate");
573 cert = read_file_to_str(fname, 0, NULL);
574 if (!cert) {
575 log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
576 fname);
577 goto done;
579 parsed = authority_cert_parse_from_string(cert, &eos);
580 if (!parsed) {
581 log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
582 goto done;
584 if (!crypto_pk_eq_keys(signing_key, parsed->signing_key)) {
585 log_warn(LD_DIR, "Stored signing key does not match signing key in "
586 "certificate");
587 goto done;
590 crypto_pk_free(*key_out);
591 authority_cert_free(*cert_out);
593 *key_out = signing_key;
594 *cert_out = parsed;
595 r = 0;
596 signing_key = NULL;
597 parsed = NULL;
599 done:
600 tor_free(fname);
601 tor_free(cert);
602 crypto_pk_free(signing_key);
603 authority_cert_free(parsed);
604 return r;
607 /** Load the v3 (voting) authority signing key and certificate, if they are
608 * present. Return -1 if anything is missing, mismatched, or unloadable;
609 * return 0 on success. */
610 static int
611 init_v3_authority_keys(void)
613 if (load_authority_keyset(0, &authority_signing_key,
614 &authority_key_certificate)<0)
615 return -1;
617 if (get_options()->V3AuthUseLegacyKey &&
618 load_authority_keyset(1, &legacy_signing_key,
619 &legacy_key_certificate)<0)
620 return -1;
622 return 0;
625 /** If we're a v3 authority, check whether we have a certificate that's
626 * likely to expire soon. Warn if we do, but not too often. */
627 void
628 v3_authority_check_key_expiry(void)
630 time_t now, expires;
631 static time_t last_warned = 0;
632 int badness, time_left, warn_interval;
633 if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
634 return;
636 now = time(NULL);
637 expires = authority_key_certificate->expires;
638 time_left = (int)( expires - now );
639 if (time_left <= 0) {
640 badness = LOG_ERR;
641 warn_interval = 60*60;
642 } else if (time_left <= 24*60*60) {
643 badness = LOG_WARN;
644 warn_interval = 60*60;
645 } else if (time_left <= 24*60*60*7) {
646 badness = LOG_WARN;
647 warn_interval = 24*60*60;
648 } else if (time_left <= 24*60*60*30) {
649 badness = LOG_WARN;
650 warn_interval = 24*60*60*5;
651 } else {
652 return;
655 if (last_warned + warn_interval > now)
656 return;
658 if (time_left <= 0) {
659 tor_log(badness, LD_DIR, "Your v3 authority certificate has expired."
660 " Generate a new one NOW.");
661 } else if (time_left <= 24*60*60) {
662 tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
663 "hours; Generate a new one NOW.", time_left/(60*60));
664 } else {
665 tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
666 "days; Generate a new one soon.", time_left/(24*60*60));
668 last_warned = now;
671 /** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
672 * on success, and -1 on failure. */
674 router_initialize_tls_context(void)
676 unsigned int flags = 0;
677 const or_options_t *options = get_options();
678 int lifetime = options->SSLKeyLifetime;
679 if (public_server_mode(options))
680 flags |= TOR_TLS_CTX_IS_PUBLIC_SERVER;
681 if (options->TLSECGroup) {
682 if (!strcasecmp(options->TLSECGroup, "P256"))
683 flags |= TOR_TLS_CTX_USE_ECDHE_P256;
684 else if (!strcasecmp(options->TLSECGroup, "P224"))
685 flags |= TOR_TLS_CTX_USE_ECDHE_P224;
687 if (!lifetime) { /* we should guess a good ssl cert lifetime */
689 /* choose between 5 and 365 days, and round to the day */
690 unsigned int five_days = 5*24*3600;
691 unsigned int one_year = 365*24*3600;
692 lifetime = crypto_rand_int_range(five_days, one_year);
693 lifetime -= lifetime % (24*3600);
695 if (crypto_rand_int(2)) {
696 /* Half the time we expire at midnight, and half the time we expire
697 * one second before midnight. (Some CAs wobble their expiry times a
698 * bit in practice, perhaps to reduce collision attacks; see ticket
699 * 8443 for details about observed certs in the wild.) */
700 lifetime--;
704 /* It's ok to pass lifetime in as an unsigned int, since
705 * config_parse_interval() checked it. */
706 return tor_tls_context_init(flags,
707 get_tlsclient_identity_key(),
708 server_mode(options) ?
709 get_server_identity_key() : NULL,
710 (unsigned int)lifetime);
713 /** Compute fingerprint (or hashed fingerprint if hashed is 1) and write
714 * it to 'fingerprint' (or 'hashed-fingerprint'). Return 0 on success, or
715 * -1 if Tor should die,
717 STATIC int
718 router_write_fingerprint(int hashed)
720 char *keydir = NULL, *cp = NULL;
721 const char *fname = hashed ? "hashed-fingerprint" :
722 "fingerprint";
723 char fingerprint[FINGERPRINT_LEN+1];
724 const or_options_t *options = get_options();
725 char *fingerprint_line = NULL;
726 int result = -1;
728 keydir = get_datadir_fname(fname);
729 log_info(LD_GENERAL,"Dumping %sfingerprint to \"%s\"...",
730 hashed ? "hashed " : "", keydir);
731 if (!hashed) {
732 if (crypto_pk_get_fingerprint(get_server_identity_key(),
733 fingerprint, 0) < 0) {
734 log_err(LD_GENERAL,"Error computing fingerprint");
735 goto done;
737 } else {
738 if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
739 fingerprint) < 0) {
740 log_err(LD_GENERAL,"Error computing hashed fingerprint");
741 goto done;
745 tor_asprintf(&fingerprint_line, "%s %s\n", options->Nickname, fingerprint);
747 /* Check whether we need to write the (hashed-)fingerprint file. */
749 cp = read_file_to_str(keydir, RFTS_IGNORE_MISSING, NULL);
750 if (!cp || strcmp(cp, fingerprint_line)) {
751 if (write_str_to_file(keydir, fingerprint_line, 0)) {
752 log_err(LD_FS, "Error writing %sfingerprint line to file",
753 hashed ? "hashed " : "");
754 goto done;
758 log_notice(LD_GENERAL, "Your Tor %s identity key fingerprint is '%s %s'",
759 hashed ? "bridge's hashed" : "server's", options->Nickname,
760 fingerprint);
762 result = 0;
763 done:
764 tor_free(cp);
765 tor_free(keydir);
766 tor_free(fingerprint_line);
767 return result;
770 static int
771 init_keys_common(void)
773 if (!key_lock)
774 key_lock = tor_mutex_new();
776 /* There are a couple of paths that put us here before we've asked
777 * openssl to initialize itself. */
778 if (crypto_global_init(get_options()->HardwareAccel,
779 get_options()->AccelName,
780 get_options()->AccelDir)) {
781 log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
782 return -1;
785 return 0;
789 init_keys_client(void)
791 crypto_pk_t *prkey;
792 if (init_keys_common() < 0)
793 return -1;
795 if (!(prkey = crypto_pk_new()))
796 return -1;
797 if (crypto_pk_generate_key(prkey)) {
798 crypto_pk_free(prkey);
799 return -1;
801 set_client_identity_key(prkey);
802 /* Create a TLS context. */
803 if (router_initialize_tls_context() < 0) {
804 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
805 return -1;
807 return 0;
810 /** Initialize all OR private keys, and the TLS context, as necessary.
811 * On OPs, this only initializes the tls context. Return 0 on success,
812 * or -1 if Tor should die.
815 init_keys(void)
817 char *keydir;
818 const char *mydesc;
819 crypto_pk_t *prkey;
820 char digest[DIGEST_LEN];
821 char v3_digest[DIGEST_LEN];
822 const or_options_t *options = get_options();
823 dirinfo_type_t type;
824 time_t now = time(NULL);
825 dir_server_t *ds;
826 int v3_digest_set = 0;
827 authority_cert_t *cert = NULL;
829 /* OP's don't need persistent keys; just make up an identity and
830 * initialize the TLS context. */
831 if (!server_mode(options)) {
832 return init_keys_client();
834 if (init_keys_common() < 0)
835 return -1;
836 /* Make sure DataDirectory exists, and is private. */
837 if (check_private_dir(options->DataDirectory, CPD_CREATE, options->User)) {
838 return -1;
840 /* Check the key directory. */
841 keydir = get_datadir_fname("keys");
842 if (check_private_dir(keydir, CPD_CREATE, options->User)) {
843 tor_free(keydir);
844 return -1;
846 tor_free(keydir);
848 /* 1a. Read v3 directory authority key/cert information. */
849 memset(v3_digest, 0, sizeof(v3_digest));
850 if (authdir_mode_v3(options)) {
851 if (init_v3_authority_keys()<0) {
852 log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
853 "were unable to load our v3 authority keys and certificate! "
854 "Use tor-gencert to generate them. Dying.");
855 return -1;
857 cert = get_my_v3_authority_cert();
858 if (cert) {
859 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
860 v3_digest);
861 v3_digest_set = 1;
865 /* 1b. Read identity key. Make it if none is found. */
866 keydir = get_datadir_fname2("keys", "secret_id_key");
867 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
868 prkey = init_key_from_file(keydir, 1, LOG_ERR, 1);
869 tor_free(keydir);
870 if (!prkey) return -1;
871 set_server_identity_key(prkey);
873 /* 1c. If we are configured as a bridge, generate a client key;
874 * otherwise, set the server identity key as our client identity
875 * key. */
876 if (public_server_mode(options)) {
877 set_client_identity_key(crypto_pk_dup_key(prkey)); /* set above */
878 } else {
879 if (!(prkey = crypto_pk_new()))
880 return -1;
881 if (crypto_pk_generate_key(prkey)) {
882 crypto_pk_free(prkey);
883 return -1;
885 set_client_identity_key(prkey);
888 /* 1d. Load all ed25519 keys */
889 if (load_ed_keys(options,now) < 0)
890 return -1;
892 /* 2. Read onion key. Make it if none is found. */
893 keydir = get_datadir_fname2("keys", "secret_onion_key");
894 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
895 prkey = init_key_from_file(keydir, 1, LOG_ERR, 1);
896 tor_free(keydir);
897 if (!prkey) return -1;
898 set_onion_key(prkey);
899 if (options->command == CMD_RUN_TOR) {
900 /* only mess with the state file if we're actually running Tor */
901 or_state_t *state = get_or_state();
902 if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
903 /* We allow for some parsing slop, but we don't want to risk accepting
904 * values in the distant future. If we did, we might never rotate the
905 * onion key. */
906 onionkey_set_at = state->LastRotatedOnionKey;
907 } else {
908 /* We have no LastRotatedOnionKey set; either we just created the key
909 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
910 * start the clock ticking now so that we will eventually rotate it even
911 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
912 state->LastRotatedOnionKey = onionkey_set_at = now;
913 or_state_mark_dirty(state, options->AvoidDiskWrites ?
914 time(NULL)+3600 : 0);
918 keydir = get_datadir_fname2("keys", "secret_onion_key.old");
919 if (!lastonionkey && file_status(keydir) == FN_FILE) {
920 /* Load keys from non-empty files only.
921 * Missing old keys won't be replaced with freshly generated keys. */
922 prkey = init_key_from_file(keydir, 0, LOG_ERR, 0);
923 if (prkey)
924 lastonionkey = prkey;
926 tor_free(keydir);
929 /* 2b. Load curve25519 onion keys. */
930 int r;
931 keydir = get_datadir_fname2("keys", "secret_onion_key_ntor");
932 r = init_curve25519_keypair_from_file(&curve25519_onion_key,
933 keydir, 1, LOG_ERR, "onion");
934 tor_free(keydir);
935 if (r<0)
936 return -1;
938 keydir = get_datadir_fname2("keys", "secret_onion_key_ntor.old");
939 if (tor_mem_is_zero((const char *)
940 last_curve25519_onion_key.pubkey.public_key,
941 CURVE25519_PUBKEY_LEN) &&
942 file_status(keydir) == FN_FILE) {
943 /* Load keys from non-empty files only.
944 * Missing old keys won't be replaced with freshly generated keys. */
945 init_curve25519_keypair_from_file(&last_curve25519_onion_key,
946 keydir, 0, LOG_ERR, "onion");
948 tor_free(keydir);
951 /* 3. Initialize link key and TLS context. */
952 if (router_initialize_tls_context() < 0) {
953 log_err(LD_GENERAL,"Error initializing TLS context");
954 return -1;
957 /* 3b. Get an ed25519 link certificate. Note that we need to do this
958 * after we set up the TLS context */
959 if (generate_ed_link_cert(options, now) < 0) {
960 log_err(LD_GENERAL,"Couldn't make link cert");
961 return -1;
964 /* 4. Build our router descriptor. */
965 /* Must be called after keys are initialized. */
966 mydesc = router_get_my_descriptor();
967 if (authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)) {
968 const char *m = NULL;
969 routerinfo_t *ri;
970 /* We need to add our own fingerprint so it gets recognized. */
971 if (dirserv_add_own_fingerprint(get_server_identity_key())) {
972 log_err(LD_GENERAL,"Error adding own fingerprint to set of relays");
973 return -1;
975 if (mydesc) {
976 was_router_added_t added;
977 ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL, NULL);
978 if (!ri) {
979 log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
980 return -1;
982 added = dirserv_add_descriptor(ri, &m, "self");
983 if (!WRA_WAS_ADDED(added)) {
984 if (!WRA_WAS_OUTDATED(added)) {
985 log_err(LD_GENERAL, "Unable to add own descriptor to directory: %s",
986 m?m:"<unknown error>");
987 return -1;
988 } else {
989 /* If the descriptor was outdated, that's ok. This can happen
990 * when some config options are toggled that affect workers, but
991 * we don't really need new keys yet so the descriptor doesn't
992 * change and the old one is still fresh. */
993 log_info(LD_GENERAL, "Couldn't add own descriptor to directory "
994 "after key init: %s This is usually not a problem.",
995 m?m:"<unknown error>");
1001 /* 5. Dump fingerprint and possibly hashed fingerprint to files. */
1002 if (router_write_fingerprint(0)) {
1003 log_err(LD_FS, "Error writing fingerprint to file");
1004 return -1;
1006 if (!public_server_mode(options) && router_write_fingerprint(1)) {
1007 log_err(LD_FS, "Error writing hashed fingerprint to file");
1008 return -1;
1011 if (!authdir_mode(options))
1012 return 0;
1013 /* 6. [authdirserver only] load approved-routers file */
1014 if (dirserv_load_fingerprint_file() < 0) {
1015 log_err(LD_GENERAL,"Error loading fingerprints");
1016 return -1;
1018 /* 6b. [authdirserver only] add own key to approved directories. */
1019 crypto_pk_get_digest(get_server_identity_key(), digest);
1020 type = ((options->V3AuthoritativeDir ?
1021 (V3_DIRINFO|MICRODESC_DIRINFO|EXTRAINFO_DIRINFO) : NO_DIRINFO) |
1022 (options->BridgeAuthoritativeDir ? BRIDGE_DIRINFO : NO_DIRINFO));
1024 ds = router_get_trusteddirserver_by_digest(digest);
1025 if (!ds) {
1026 ds = trusted_dir_server_new(options->Nickname, NULL,
1027 router_get_advertised_dir_port(options, 0),
1028 router_get_advertised_or_port(options),
1029 digest,
1030 v3_digest,
1031 type, 0.0);
1032 if (!ds) {
1033 log_err(LD_GENERAL,"We want to be a directory authority, but we "
1034 "couldn't add ourselves to the authority list. Failing.");
1035 return -1;
1037 dir_server_add(ds);
1039 if (ds->type != type) {
1040 log_warn(LD_DIR, "Configured authority type does not match authority "
1041 "type in DirAuthority list. Adjusting. (%d v %d)",
1042 type, ds->type);
1043 ds->type = type;
1045 if (v3_digest_set && (ds->type & V3_DIRINFO) &&
1046 tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
1047 log_warn(LD_DIR, "V3 identity key does not match identity declared in "
1048 "DirAuthority line. Adjusting.");
1049 memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
1052 if (cert) { /* add my own cert to the list of known certs */
1053 log_info(LD_DIR, "adding my own v3 cert");
1054 if (trusted_dirs_load_certs_from_string(
1055 cert->cache_info.signed_descriptor_body,
1056 TRUSTED_DIRS_CERTS_SRC_SELF, 0)<0) {
1057 log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
1058 return -1;
1062 return 0; /* success */
1065 /* Keep track of whether we should upload our server descriptor,
1066 * and what type of server we are.
1069 /** Whether we can reach our ORPort from the outside. */
1070 static int can_reach_or_port = 0;
1071 /** Whether we can reach our DirPort from the outside. */
1072 static int can_reach_dir_port = 0;
1074 /** Forget what we have learned about our reachability status. */
1075 void
1076 router_reset_reachability(void)
1078 can_reach_or_port = can_reach_dir_port = 0;
1081 /** Return 1 if ORPort is known reachable; else return 0. */
1083 check_whether_orport_reachable(void)
1085 const or_options_t *options = get_options();
1086 return options->AssumeReachable ||
1087 can_reach_or_port;
1090 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
1092 check_whether_dirport_reachable(void)
1094 const or_options_t *options = get_options();
1095 return !options->DirPort_set ||
1096 options->AssumeReachable ||
1097 net_is_disabled() ||
1098 can_reach_dir_port;
1101 /** Look at a variety of factors, and return 0 if we don't want to
1102 * advertise the fact that we have a DirPort open. Else return the
1103 * DirPort we want to advertise.
1105 * Log a helpful message if we change our mind about whether to publish
1106 * a DirPort.
1108 static int
1109 decide_to_advertise_dirport(const or_options_t *options, uint16_t dir_port)
1111 static int advertising=1; /* start out assuming we will advertise */
1112 int new_choice=1;
1113 const char *reason = NULL;
1115 /* Section one: reasons to publish or not publish that aren't
1116 * worth mentioning to the user, either because they're obvious
1117 * or because they're normal behavior. */
1119 if (!dir_port) /* short circuit the rest of the function */
1120 return 0;
1121 if (authdir_mode(options)) /* always publish */
1122 return dir_port;
1123 if (net_is_disabled())
1124 return 0;
1125 if (!check_whether_dirport_reachable())
1126 return 0;
1127 if (!router_get_advertised_dir_port(options, dir_port))
1128 return 0;
1130 /* Section two: reasons to publish or not publish that the user
1131 * might find surprising. These are generally config options that
1132 * make us choose not to publish. */
1134 if (accounting_is_enabled(options)) {
1135 /* Don't spend bytes for directory traffic if we could end up hibernating,
1136 * but allow DirPort otherwise. Some people set AccountingMax because
1137 * they're confused or to get statistics. */
1138 int interval_length = accounting_get_interval_length();
1139 uint32_t effective_bw = get_effective_bwrate(options);
1140 uint64_t acc_bytes;
1141 if (!interval_length) {
1142 log_warn(LD_BUG, "An accounting interval is not allowed to be zero "
1143 "seconds long. Raising to 1.");
1144 interval_length = 1;
1146 log_info(LD_GENERAL, "Calculating whether to disable dirport: effective "
1147 "bwrate: %u, AccountingMax: "U64_FORMAT", "
1148 "accounting interval length %d", effective_bw,
1149 U64_PRINTF_ARG(options->AccountingMax),
1150 interval_length);
1152 acc_bytes = options->AccountingMax;
1153 if (get_options()->AccountingRule == ACCT_SUM)
1154 acc_bytes /= 2;
1155 if (effective_bw >=
1156 acc_bytes / interval_length) {
1157 new_choice = 0;
1158 reason = "AccountingMax enabled";
1160 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
1161 } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
1162 (options->RelayBandwidthRate > 0 &&
1163 options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
1164 /* if we're advertising a small amount */
1165 new_choice = 0;
1166 reason = "BandwidthRate under 50KB";
1169 if (advertising != new_choice) {
1170 if (new_choice == 1) {
1171 log_notice(LD_DIR, "Advertising DirPort as %d", dir_port);
1172 } else {
1173 tor_assert(reason);
1174 log_notice(LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
1176 advertising = new_choice;
1179 return advertising ? dir_port : 0;
1182 /** Allocate and return a new extend_info_t that can be used to build
1183 * a circuit to or through the router <b>r</b>. Use the primary
1184 * address of the router unless <b>for_direct_connect</b> is true, in
1185 * which case the preferred address is used instead. */
1186 static extend_info_t *
1187 extend_info_from_router(const routerinfo_t *r)
1189 tor_addr_port_t ap;
1190 tor_assert(r);
1192 router_get_prim_orport(r, &ap);
1193 return extend_info_new(r->nickname, r->cache_info.identity_digest,
1194 r->onion_pkey, r->onion_curve25519_pkey,
1195 &ap.addr, ap.port);
1198 /** Some time has passed, or we just got new directory information.
1199 * See if we currently believe our ORPort or DirPort to be
1200 * unreachable. If so, launch a new test for it.
1202 * For ORPort, we simply try making a circuit that ends at ourselves.
1203 * Success is noticed in onionskin_answer().
1205 * For DirPort, we make a connection via Tor to our DirPort and ask
1206 * for our own server descriptor.
1207 * Success is noticed in connection_dir_client_reached_eof().
1209 void
1210 consider_testing_reachability(int test_or, int test_dir)
1212 const routerinfo_t *me = router_get_my_routerinfo();
1213 int orport_reachable = check_whether_orport_reachable();
1214 tor_addr_t addr;
1215 const or_options_t *options = get_options();
1216 if (!me)
1217 return;
1219 if (routerset_contains_router(options->ExcludeNodes, me, -1) &&
1220 options->StrictNodes) {
1221 /* If we've excluded ourself, and StrictNodes is set, we can't test
1222 * ourself. */
1223 if (test_or || test_dir) {
1224 #define SELF_EXCLUDED_WARN_INTERVAL 3600
1225 static ratelim_t warning_limit=RATELIM_INIT(SELF_EXCLUDED_WARN_INTERVAL);
1226 log_fn_ratelim(&warning_limit, LOG_WARN, LD_CIRC,
1227 "Can't peform self-tests for this relay: we have "
1228 "listed ourself in ExcludeNodes, and StrictNodes is set. "
1229 "We cannot learn whether we are usable, and will not "
1230 "be able to advertise ourself.");
1232 return;
1235 if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
1236 extend_info_t *ei = extend_info_from_router(me);
1237 /* XXX IPv6 self testing */
1238 log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
1239 !orport_reachable ? "reachability" : "bandwidth",
1240 fmt_addr32(me->addr), me->or_port);
1241 circuit_launch_by_extend_info(CIRCUIT_PURPOSE_TESTING, ei,
1242 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
1243 extend_info_free(ei);
1246 tor_addr_from_ipv4h(&addr, me->addr);
1247 if (test_dir && !check_whether_dirport_reachable() &&
1248 !connection_get_by_type_addr_port_purpose(
1249 CONN_TYPE_DIR, &addr, me->dir_port,
1250 DIR_PURPOSE_FETCH_SERVERDESC)) {
1251 /* ask myself, via tor, for my server descriptor. */
1252 directory_initiate_command(&addr,
1253 me->or_port, me->dir_port,
1254 me->cache_info.identity_digest,
1255 DIR_PURPOSE_FETCH_SERVERDESC,
1256 ROUTER_PURPOSE_GENERAL,
1257 DIRIND_ANON_DIRPORT, "authority.z", NULL, 0, 0);
1261 /** Annotate that we found our ORPort reachable. */
1262 void
1263 router_orport_found_reachable(void)
1265 const routerinfo_t *me = router_get_my_routerinfo();
1266 if (!can_reach_or_port && me) {
1267 char *address = tor_dup_ip(me->addr);
1268 log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
1269 "the outside. Excellent.%s",
1270 get_options()->PublishServerDescriptor_ != NO_DIRINFO ?
1271 " Publishing server descriptor." : "");
1272 can_reach_or_port = 1;
1273 mark_my_descriptor_dirty("ORPort found reachable");
1274 /* This is a significant enough change to upload immediately,
1275 * at least in a test network */
1276 if (get_options()->TestingTorNetwork == 1) {
1277 reschedule_descriptor_update_check();
1279 control_event_server_status(LOG_NOTICE,
1280 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
1281 address, me->or_port);
1282 tor_free(address);
1286 /** Annotate that we found our DirPort reachable. */
1287 void
1288 router_dirport_found_reachable(void)
1290 const routerinfo_t *me = router_get_my_routerinfo();
1291 if (!can_reach_dir_port && me) {
1292 char *address = tor_dup_ip(me->addr);
1293 log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
1294 "from the outside. Excellent.");
1295 can_reach_dir_port = 1;
1296 if (decide_to_advertise_dirport(get_options(), me->dir_port)) {
1297 mark_my_descriptor_dirty("DirPort found reachable");
1298 /* This is a significant enough change to upload immediately,
1299 * at least in a test network */
1300 if (get_options()->TestingTorNetwork == 1) {
1301 reschedule_descriptor_update_check();
1304 control_event_server_status(LOG_NOTICE,
1305 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
1306 address, me->dir_port);
1307 tor_free(address);
1311 /** We have enough testing circuits open. Send a bunch of "drop"
1312 * cells down each of them, to exercise our bandwidth. */
1313 void
1314 router_perform_bandwidth_test(int num_circs, time_t now)
1316 int num_cells = (int)(get_options()->BandwidthRate * 10 /
1317 CELL_MAX_NETWORK_SIZE);
1318 int max_cells = num_cells < CIRCWINDOW_START ?
1319 num_cells : CIRCWINDOW_START;
1320 int cells_per_circuit = max_cells / num_circs;
1321 origin_circuit_t *circ = NULL;
1323 log_notice(LD_OR,"Performing bandwidth self-test...done.");
1324 while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
1325 CIRCUIT_PURPOSE_TESTING))) {
1326 /* dump cells_per_circuit drop cells onto this circ */
1327 int i = cells_per_circuit;
1328 if (circ->base_.state != CIRCUIT_STATE_OPEN)
1329 continue;
1330 circ->base_.timestamp_dirty = now;
1331 while (i-- > 0) {
1332 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
1333 RELAY_COMMAND_DROP,
1334 NULL, 0, circ->cpath->prev)<0) {
1335 return; /* stop if error */
1341 /** Return true iff our network is in some sense disabled: either we're
1342 * hibernating, entering hibernation, or the network is turned off with
1343 * DisableNetwork. */
1345 net_is_disabled(void)
1347 return get_options()->DisableNetwork || we_are_hibernating();
1350 /** Return true iff we believe ourselves to be an authoritative
1351 * directory server.
1354 authdir_mode(const or_options_t *options)
1356 return options->AuthoritativeDir != 0;
1358 /** Return true iff we believe ourselves to be a v3 authoritative
1359 * directory server.
1362 authdir_mode_v3(const or_options_t *options)
1364 return authdir_mode(options) && options->V3AuthoritativeDir != 0;
1366 /** Return true iff we are a v3 directory authority. */
1368 authdir_mode_any_main(const or_options_t *options)
1370 return options->V3AuthoritativeDir;
1372 /** Return true if we believe ourselves to be any kind of
1373 * authoritative directory beyond just a hidserv authority. */
1375 authdir_mode_any_nonhidserv(const or_options_t *options)
1377 return options->BridgeAuthoritativeDir ||
1378 authdir_mode_any_main(options);
1380 /** Return true iff we are an authoritative directory server that is
1381 * authoritative about receiving and serving descriptors of type
1382 * <b>purpose</b> on its dirport. Use -1 for "any purpose". */
1384 authdir_mode_handles_descs(const or_options_t *options, int purpose)
1386 if (purpose < 0)
1387 return authdir_mode_any_nonhidserv(options);
1388 else if (purpose == ROUTER_PURPOSE_GENERAL)
1389 return authdir_mode_any_main(options);
1390 else if (purpose == ROUTER_PURPOSE_BRIDGE)
1391 return (options->BridgeAuthoritativeDir);
1392 else
1393 return 0;
1395 /** Return true iff we are an authoritative directory server that
1396 * publishes its own network statuses.
1399 authdir_mode_publishes_statuses(const or_options_t *options)
1401 if (authdir_mode_bridge(options))
1402 return 0;
1403 return authdir_mode_any_nonhidserv(options);
1405 /** Return true iff we are an authoritative directory server that
1406 * tests reachability of the descriptors it learns about.
1409 authdir_mode_tests_reachability(const or_options_t *options)
1411 return authdir_mode_handles_descs(options, -1);
1413 /** Return true iff we believe ourselves to be a bridge authoritative
1414 * directory server.
1417 authdir_mode_bridge(const or_options_t *options)
1419 return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
1422 /** Return true iff we are trying to be a server.
1424 MOCK_IMPL(int,
1425 server_mode,(const or_options_t *options))
1427 if (options->ClientOnly) return 0;
1428 /* XXXX024 I believe we can kill off ORListenAddress here.*/
1429 return (options->ORPort_set || options->ORListenAddress);
1432 /** Return true iff we are trying to be a non-bridge server.
1434 MOCK_IMPL(int,
1435 public_server_mode,(const or_options_t *options))
1437 if (!server_mode(options)) return 0;
1438 return (!options->BridgeRelay);
1441 /** Return true iff the combination of options in <b>options</b> and parameters
1442 * in the consensus mean that we don't want to allow exits from circuits
1443 * we got from addresses not known to be servers. */
1445 should_refuse_unknown_exits(const or_options_t *options)
1447 if (options->RefuseUnknownExits != -1) {
1448 return options->RefuseUnknownExits;
1449 } else {
1450 return networkstatus_get_param(NULL, "refuseunknownexits", 1, 0, 1);
1454 /** Remember if we've advertised ourselves to the dirservers. */
1455 static int server_is_advertised=0;
1457 /** Return true iff we have published our descriptor lately.
1460 advertised_server_mode(void)
1462 return server_is_advertised;
1466 * Called with a boolean: set whether we have recently published our
1467 * descriptor.
1469 static void
1470 set_server_advertised(int s)
1472 server_is_advertised = s;
1475 /** Return true iff we are trying to proxy client connections. */
1477 proxy_mode(const or_options_t *options)
1479 (void)options;
1480 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t *, p) {
1481 if (p->type == CONN_TYPE_AP_LISTENER ||
1482 p->type == CONN_TYPE_AP_TRANS_LISTENER ||
1483 p->type == CONN_TYPE_AP_DNS_LISTENER ||
1484 p->type == CONN_TYPE_AP_NATD_LISTENER)
1485 return 1;
1486 } SMARTLIST_FOREACH_END(p);
1487 return 0;
1490 /** Decide if we're a publishable server. We are a publishable server if:
1491 * - We don't have the ClientOnly option set
1492 * and
1493 * - We have the PublishServerDescriptor option set to non-empty
1494 * and
1495 * - We have ORPort set
1496 * and
1497 * - We believe we are reachable from the outside; or
1498 * - We are an authoritative directory server.
1500 static int
1501 decide_if_publishable_server(void)
1503 const or_options_t *options = get_options();
1505 if (options->ClientOnly)
1506 return 0;
1507 if (options->PublishServerDescriptor_ == NO_DIRINFO)
1508 return 0;
1509 if (!server_mode(options))
1510 return 0;
1511 if (authdir_mode(options))
1512 return 1;
1513 if (!router_get_advertised_or_port(options))
1514 return 0;
1516 return check_whether_orport_reachable();
1519 /** Initiate server descriptor upload as reasonable (if server is publishable,
1520 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1522 * We need to rebuild the descriptor if it's dirty even if we're not
1523 * uploading, because our reachability testing *uses* our descriptor to
1524 * determine what IP address and ports to test.
1526 void
1527 consider_publishable_server(int force)
1529 int rebuilt;
1531 if (!server_mode(get_options()))
1532 return;
1534 rebuilt = router_rebuild_descriptor(0);
1535 if (decide_if_publishable_server()) {
1536 set_server_advertised(1);
1537 if (rebuilt == 0)
1538 router_upload_dir_desc_to_dirservers(force);
1539 } else {
1540 set_server_advertised(0);
1544 /** Return the port of the first active listener of type
1545 * <b>listener_type</b>. */
1546 /** XXX not a very good interface. it's not reliable when there are
1547 multiple listeners. */
1548 uint16_t
1549 router_get_active_listener_port_by_type_af(int listener_type,
1550 sa_family_t family)
1552 /* Iterate all connections, find one of the right kind and return
1553 the port. Not very sophisticated or fast, but effective. */
1554 smartlist_t *conns = get_connection_array();
1555 SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1556 if (conn->type == listener_type && !conn->marked_for_close &&
1557 conn->socket_family == family) {
1558 return conn->port;
1560 } SMARTLIST_FOREACH_END(conn);
1562 return 0;
1565 /** Return the port that we should advertise as our ORPort; this is either
1566 * the one configured in the ORPort option, or the one we actually bound to
1567 * if ORPort is "auto".
1569 uint16_t
1570 router_get_advertised_or_port(const or_options_t *options)
1572 return router_get_advertised_or_port_by_af(options, AF_INET);
1575 /** As router_get_advertised_or_port(), but allows an address family argument.
1577 uint16_t
1578 router_get_advertised_or_port_by_af(const or_options_t *options,
1579 sa_family_t family)
1581 int port = get_first_advertised_port_by_type_af(CONN_TYPE_OR_LISTENER,
1582 family);
1583 (void)options;
1585 /* If the port is in 'auto' mode, we have to use
1586 router_get_listener_port_by_type(). */
1587 if (port == CFG_AUTO_PORT)
1588 return router_get_active_listener_port_by_type_af(CONN_TYPE_OR_LISTENER,
1589 family);
1591 return port;
1594 /** Return the port that we should advertise as our DirPort;
1595 * this is one of three possibilities:
1596 * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
1597 * the one configured in the DirPort option,
1598 * or the one we actually bound to if DirPort is "auto". */
1599 uint16_t
1600 router_get_advertised_dir_port(const or_options_t *options, uint16_t dirport)
1602 int dirport_configured = get_primary_dir_port();
1603 (void)options;
1605 if (!dirport_configured)
1606 return dirport;
1608 if (dirport_configured == CFG_AUTO_PORT)
1609 return router_get_active_listener_port_by_type_af(CONN_TYPE_DIR_LISTENER,
1610 AF_INET);
1612 return dirport_configured;
1616 * OR descriptor generation.
1619 /** My routerinfo. */
1620 static routerinfo_t *desc_routerinfo = NULL;
1621 /** My extrainfo */
1622 static extrainfo_t *desc_extrainfo = NULL;
1623 /** Why did we most recently decide to regenerate our descriptor? Used to
1624 * tell the authorities why we're sending it to them. */
1625 static const char *desc_gen_reason = NULL;
1626 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1627 * now. */
1628 static time_t desc_clean_since = 0;
1629 /** Why did we mark the descriptor dirty? */
1630 static const char *desc_dirty_reason = NULL;
1631 /** Boolean: do we need to regenerate the above? */
1632 static int desc_needs_upload = 0;
1634 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1635 * descriptor successfully yet, try to upload our signed descriptor to
1636 * all the directory servers we know about.
1638 void
1639 router_upload_dir_desc_to_dirservers(int force)
1641 const routerinfo_t *ri;
1642 extrainfo_t *ei;
1643 char *msg;
1644 size_t desc_len, extra_len = 0, total_len;
1645 dirinfo_type_t auth = get_options()->PublishServerDescriptor_;
1647 ri = router_get_my_routerinfo();
1648 if (!ri) {
1649 log_info(LD_GENERAL, "No descriptor; skipping upload");
1650 return;
1652 ei = router_get_my_extrainfo();
1653 if (auth == NO_DIRINFO)
1654 return;
1655 if (!force && !desc_needs_upload)
1656 return;
1658 log_info(LD_OR, "Uploading relay descriptor to directory authorities%s",
1659 force ? " (forced)" : "");
1661 desc_needs_upload = 0;
1663 desc_len = ri->cache_info.signed_descriptor_len;
1664 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1665 total_len = desc_len + extra_len + 1;
1666 msg = tor_malloc(total_len);
1667 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1668 if (ei) {
1669 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1671 msg[desc_len+extra_len] = 0;
1673 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
1674 (auth & BRIDGE_DIRINFO) ?
1675 ROUTER_PURPOSE_BRIDGE :
1676 ROUTER_PURPOSE_GENERAL,
1677 auth, msg, desc_len, extra_len);
1678 tor_free(msg);
1681 /** OR only: Check whether my exit policy says to allow connection to
1682 * conn. Return 0 if we accept; non-0 if we reject.
1685 router_compare_to_my_exit_policy(const tor_addr_t *addr, uint16_t port)
1687 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1688 return -1;
1690 /* make sure it's resolved to something. this way we can't get a
1691 'maybe' below. */
1692 if (tor_addr_is_null(addr))
1693 return -1;
1695 /* look at desc_routerinfo->exit_policy for both the v4 and the v6
1696 * policies. The exit_policy field in desc_routerinfo is a bit unusual,
1697 * in that it contains IPv6 and IPv6 entries. We don't want to look
1698 * at desc_routerinfio->ipv6_exit_policy, since that's a port summary. */
1699 if ((tor_addr_family(addr) == AF_INET ||
1700 tor_addr_family(addr) == AF_INET6)) {
1701 return compare_tor_addr_to_addr_policy(addr, port,
1702 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
1703 #if 0
1704 } else if (tor_addr_family(addr) == AF_INET6) {
1705 return get_options()->IPv6Exit &&
1706 desc_routerinfo->ipv6_exit_policy &&
1707 compare_tor_addr_to_short_policy(addr, port,
1708 desc_routerinfo->ipv6_exit_policy) != ADDR_POLICY_ACCEPTED;
1709 #endif
1710 } else {
1711 return -1;
1715 /** Return true iff my exit policy is reject *:*. Return -1 if we don't
1716 * have a descriptor */
1718 router_my_exit_policy_is_reject_star(void)
1720 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1721 return -1;
1723 return desc_routerinfo->policy_is_reject_star;
1726 /** Return true iff I'm a server and <b>digest</b> is equal to
1727 * my server identity key digest. */
1729 router_digest_is_me(const char *digest)
1731 return (server_identitykey &&
1732 tor_memeq(server_identitykey_digest, digest, DIGEST_LEN));
1735 /** Return my identity digest. */
1736 const uint8_t *
1737 router_get_my_id_digest(void)
1739 return (const uint8_t *)server_identitykey_digest;
1742 /** Return true iff I'm a server and <b>digest</b> is equal to
1743 * my identity digest. */
1745 router_extrainfo_digest_is_me(const char *digest)
1747 extrainfo_t *ei = router_get_my_extrainfo();
1748 if (!ei)
1749 return 0;
1751 return tor_memeq(digest,
1752 ei->cache_info.signed_descriptor_digest,
1753 DIGEST_LEN);
1756 /** A wrapper around router_digest_is_me(). */
1758 router_is_me(const routerinfo_t *router)
1760 return router_digest_is_me(router->cache_info.identity_digest);
1763 /** Return a routerinfo for this OR, rebuilding a fresh one if
1764 * necessary. Return NULL on error, or if called on an OP. */
1765 MOCK_IMPL(const routerinfo_t *,
1766 router_get_my_routerinfo,(void))
1768 if (!server_mode(get_options()))
1769 return NULL;
1770 if (router_rebuild_descriptor(0))
1771 return NULL;
1772 return desc_routerinfo;
1775 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1776 * one if necessary. Return NULL on error.
1778 const char *
1779 router_get_my_descriptor(void)
1781 const char *body;
1782 if (!router_get_my_routerinfo())
1783 return NULL;
1784 /* Make sure this is nul-terminated. */
1785 tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
1786 body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
1787 tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
1788 log_debug(LD_GENERAL,"my desc is '%s'", body);
1789 return body;
1792 /** Return the extrainfo document for this OR, or NULL if we have none.
1793 * Rebuilt it (and the server descriptor) if necessary. */
1794 extrainfo_t *
1795 router_get_my_extrainfo(void)
1797 if (!server_mode(get_options()))
1798 return NULL;
1799 if (router_rebuild_descriptor(0))
1800 return NULL;
1801 return desc_extrainfo;
1804 /** Return a human-readable string describing what triggered us to generate
1805 * our current descriptor, or NULL if we don't know. */
1806 const char *
1807 router_get_descriptor_gen_reason(void)
1809 return desc_gen_reason;
1812 /** A list of nicknames that we've warned about including in our family
1813 * declaration verbatim rather than as digests. */
1814 static smartlist_t *warned_nonexistent_family = NULL;
1816 static int router_guess_address_from_dir_headers(uint32_t *guess);
1818 /** Make a current best guess at our address, either because
1819 * it's configured in torrc, or because we've learned it from
1820 * dirserver headers. Place the answer in *<b>addr</b> and return
1821 * 0 on success, else return -1 if we have no guess. */
1823 router_pick_published_address(const or_options_t *options, uint32_t *addr)
1825 *addr = get_last_resolved_addr();
1826 if (!*addr &&
1827 resolve_my_address(LOG_INFO, options, addr, NULL, NULL) < 0) {
1828 log_info(LD_CONFIG, "Could not determine our address locally. "
1829 "Checking if directory headers provide any hints.");
1830 if (router_guess_address_from_dir_headers(addr) < 0) {
1831 log_info(LD_CONFIG, "No hints from directory headers either. "
1832 "Will try again later.");
1833 return -1;
1836 log_info(LD_CONFIG,"Success: chose address '%s'.", fmt_addr32(*addr));
1837 return 0;
1840 /** Build a fresh routerinfo, signed server descriptor, and extra-info document
1841 * for this OR. Set r to the generated routerinfo, e to the generated
1842 * extra-info document. Return 0 on success, -1 on temporary error. Failure to
1843 * generate an extra-info document is not an error and is indicated by setting
1844 * e to NULL. Caller is responsible for freeing generated documents if 0 is
1845 * returned.
1848 router_build_fresh_descriptor(routerinfo_t **r, extrainfo_t **e)
1850 routerinfo_t *ri;
1851 extrainfo_t *ei;
1852 uint32_t addr;
1853 char platform[256];
1854 int hibernating = we_are_hibernating();
1855 const or_options_t *options = get_options();
1857 if (router_pick_published_address(options, &addr) < 0) {
1858 log_warn(LD_CONFIG, "Don't know my address while generating descriptor");
1859 return -1;
1862 ri = tor_malloc_zero(sizeof(routerinfo_t));
1863 ri->cache_info.routerlist_index = -1;
1864 ri->nickname = tor_strdup(options->Nickname);
1865 ri->addr = addr;
1866 ri->or_port = router_get_advertised_or_port(options);
1867 ri->dir_port = router_get_advertised_dir_port(options, 0);
1868 ri->cache_info.published_on = time(NULL);
1869 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
1870 * main thread */
1871 ri->onion_curve25519_pkey =
1872 tor_memdup(&get_current_curve25519_keypair()->pubkey,
1873 sizeof(curve25519_public_key_t));
1875 /* For now, at most one IPv6 or-address is being advertised. */
1877 const port_cfg_t *ipv6_orport = NULL;
1878 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t *, p) {
1879 if (p->type == CONN_TYPE_OR_LISTENER &&
1880 ! p->server_cfg.no_advertise &&
1881 ! p->server_cfg.bind_ipv4_only &&
1882 tor_addr_family(&p->addr) == AF_INET6) {
1883 if (! tor_addr_is_internal(&p->addr, 0)) {
1884 ipv6_orport = p;
1885 break;
1886 } else {
1887 char addrbuf[TOR_ADDR_BUF_LEN];
1888 log_warn(LD_CONFIG,
1889 "Unable to use configured IPv6 address \"%s\" in a "
1890 "descriptor. Skipping it. "
1891 "Try specifying a globally reachable address explicitly. ",
1892 tor_addr_to_str(addrbuf, &p->addr, sizeof(addrbuf), 1));
1895 } SMARTLIST_FOREACH_END(p);
1896 if (ipv6_orport) {
1897 tor_addr_copy(&ri->ipv6_addr, &ipv6_orport->addr);
1898 ri->ipv6_orport = ipv6_orport->port;
1902 ri->identity_pkey = crypto_pk_dup_key(get_server_identity_key());
1903 if (crypto_pk_get_digest(ri->identity_pkey,
1904 ri->cache_info.identity_digest)<0) {
1905 routerinfo_free(ri);
1906 return -1;
1908 ri->signing_key_cert = tor_cert_dup(get_master_signing_key_cert());
1910 get_platform_str(platform, sizeof(platform));
1911 ri->platform = tor_strdup(platform);
1913 /* compute ri->bandwidthrate as the min of various options */
1914 ri->bandwidthrate = get_effective_bwrate(options);
1916 /* and compute ri->bandwidthburst similarly */
1917 ri->bandwidthburst = get_effective_bwburst(options);
1919 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
1921 if (dns_seems_to_be_broken() || has_dns_init_failed()) {
1922 /* DNS is screwed up; don't claim to be an exit. */
1923 policies_exit_policy_append_reject_star(&ri->exit_policy);
1924 } else {
1925 policies_parse_exit_policy_from_options(options,ri->addr,&ri->ipv6_addr,1,
1926 &ri->exit_policy);
1928 ri->policy_is_reject_star =
1929 policy_is_reject_star(ri->exit_policy, AF_INET) &&
1930 policy_is_reject_star(ri->exit_policy, AF_INET6);
1932 if (options->IPv6Exit) {
1933 char *p_tmp = policy_summarize(ri->exit_policy, AF_INET6);
1934 if (p_tmp)
1935 ri->ipv6_exit_policy = parse_short_policy(p_tmp);
1936 tor_free(p_tmp);
1939 if (options->MyFamily && ! options->BridgeRelay) {
1940 smartlist_t *family;
1941 if (!warned_nonexistent_family)
1942 warned_nonexistent_family = smartlist_new();
1943 family = smartlist_new();
1944 ri->declared_family = smartlist_new();
1945 smartlist_split_string(family, options->MyFamily, ",",
1946 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
1947 SMARTLIST_FOREACH_BEGIN(family, char *, name) {
1948 const node_t *member;
1949 if (!strcasecmp(name, options->Nickname))
1950 goto skip; /* Don't list ourself, that's redundant */
1951 else
1952 member = node_get_by_nickname(name, 1);
1953 if (!member) {
1954 int is_legal = is_legal_nickname_or_hexdigest(name);
1955 if (!smartlist_contains_string(warned_nonexistent_family, name) &&
1956 !is_legal_hexdigest(name)) {
1957 if (is_legal)
1958 log_warn(LD_CONFIG,
1959 "I have no descriptor for the router named \"%s\" in my "
1960 "declared family; I'll use the nickname as is, but "
1961 "this may confuse clients.", name);
1962 else
1963 log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
1964 "declared family, but that isn't a legal nickname. "
1965 "Skipping it.", escaped(name));
1966 smartlist_add(warned_nonexistent_family, tor_strdup(name));
1968 if (is_legal) {
1969 smartlist_add(ri->declared_family, name);
1970 name = NULL;
1972 } else if (router_digest_is_me(member->identity)) {
1973 /* Don't list ourself in our own family; that's redundant */
1974 /* XXX shouldn't be possible */
1975 } else {
1976 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1977 fp[0] = '$';
1978 base16_encode(fp+1,HEX_DIGEST_LEN+1,
1979 member->identity, DIGEST_LEN);
1980 smartlist_add(ri->declared_family, fp);
1981 if (smartlist_contains_string(warned_nonexistent_family, name))
1982 smartlist_string_remove(warned_nonexistent_family, name);
1984 skip:
1985 tor_free(name);
1986 } SMARTLIST_FOREACH_END(name);
1988 /* remove duplicates from the list */
1989 smartlist_sort_strings(ri->declared_family);
1990 smartlist_uniq_strings(ri->declared_family);
1992 smartlist_free(family);
1995 /* Now generate the extrainfo. */
1996 ei = tor_malloc_zero(sizeof(extrainfo_t));
1997 ei->cache_info.is_extrainfo = 1;
1998 strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
1999 ei->cache_info.published_on = ri->cache_info.published_on;
2000 ei->signing_key_cert = tor_cert_dup(get_master_signing_key_cert());
2001 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
2002 DIGEST_LEN);
2003 if (extrainfo_dump_to_string(&ei->cache_info.signed_descriptor_body,
2004 ei, get_server_identity_key(),
2005 get_master_signing_keypair()) < 0) {
2006 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
2007 extrainfo_free(ei);
2008 ei = NULL;
2009 } else {
2010 ei->cache_info.signed_descriptor_len =
2011 strlen(ei->cache_info.signed_descriptor_body);
2012 router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
2013 ei->cache_info.signed_descriptor_len,
2014 ei->cache_info.signed_descriptor_digest);
2015 crypto_digest256((char*) ei->digest256,
2016 ei->cache_info.signed_descriptor_body,
2017 ei->cache_info.signed_descriptor_len,
2018 DIGEST_SHA256);
2021 /* Now finish the router descriptor. */
2022 if (ei) {
2023 memcpy(ri->cache_info.extra_info_digest,
2024 ei->cache_info.signed_descriptor_digest,
2025 DIGEST_LEN);
2026 memcpy(ri->extra_info_digest256,
2027 ei->digest256,
2028 DIGEST256_LEN);
2029 } else {
2030 /* ri was allocated with tor_malloc_zero, so there is no need to
2031 * zero ri->cache_info.extra_info_digest here. */
2033 if (! (ri->cache_info.signed_descriptor_body =
2034 router_dump_router_to_string(ri, get_server_identity_key(),
2035 get_onion_key(),
2036 get_current_curve25519_keypair(),
2037 get_master_signing_keypair())) ) {
2038 log_warn(LD_BUG, "Couldn't generate router descriptor.");
2039 routerinfo_free(ri);
2040 extrainfo_free(ei);
2041 return -1;
2043 ri->cache_info.signed_descriptor_len =
2044 strlen(ri->cache_info.signed_descriptor_body);
2046 ri->purpose =
2047 options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
2048 if (options->BridgeRelay) {
2049 /* Bridges shouldn't be able to send their descriptors unencrypted,
2050 anyway, since they don't have a DirPort, and always connect to the
2051 bridge authority anonymously. But just in case they somehow think of
2052 sending them on an unencrypted connection, don't allow them to try. */
2053 ri->cache_info.send_unencrypted = 0;
2054 if (ei)
2055 ei->cache_info.send_unencrypted = 0;
2056 } else {
2057 ri->cache_info.send_unencrypted = 1;
2058 if (ei)
2059 ei->cache_info.send_unencrypted = 1;
2062 router_get_router_hash(ri->cache_info.signed_descriptor_body,
2063 strlen(ri->cache_info.signed_descriptor_body),
2064 ri->cache_info.signed_descriptor_digest);
2066 if (ei) {
2067 tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
2070 *r = ri;
2071 *e = ei;
2072 return 0;
2075 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
2076 * routerinfo, signed server descriptor, and extra-info document for this OR.
2077 * Return 0 on success, -1 on temporary error.
2080 router_rebuild_descriptor(int force)
2082 routerinfo_t *ri;
2083 extrainfo_t *ei;
2084 uint32_t addr;
2085 const or_options_t *options = get_options();
2087 if (desc_clean_since && !force)
2088 return 0;
2090 if (router_pick_published_address(options, &addr) < 0 ||
2091 router_get_advertised_or_port(options) == 0) {
2092 /* Stop trying to rebuild our descriptor every second. We'll
2093 * learn that it's time to try again when ip_address_changed()
2094 * marks it dirty. */
2095 desc_clean_since = time(NULL);
2096 return -1;
2099 log_info(LD_OR, "Rebuilding relay descriptor%s", force ? " (forced)" : "");
2101 if (router_build_fresh_descriptor(&ri, &ei) < 0) {
2102 return -1;
2105 routerinfo_free(desc_routerinfo);
2106 desc_routerinfo = ri;
2107 extrainfo_free(desc_extrainfo);
2108 desc_extrainfo = ei;
2110 desc_clean_since = time(NULL);
2111 desc_needs_upload = 1;
2112 desc_gen_reason = desc_dirty_reason;
2113 desc_dirty_reason = NULL;
2114 control_event_my_descriptor_changed();
2115 return 0;
2118 /** If our router descriptor ever goes this long without being regenerated
2119 * because something changed, we force an immediate regenerate-and-upload. */
2120 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
2122 /** If our router descriptor seems to be missing or unacceptable according
2123 * to the authorities, regenerate and reupload it _this_ often. */
2124 #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
2126 /** Mark descriptor out of date if it's been "too long" since we last tried
2127 * to upload one. */
2128 void
2129 mark_my_descriptor_dirty_if_too_old(time_t now)
2131 networkstatus_t *ns;
2132 const routerstatus_t *rs;
2133 const char *retry_fast_reason = NULL; /* Set if we should retry frequently */
2134 const time_t slow_cutoff = now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL;
2135 const time_t fast_cutoff = now - FAST_RETRY_DESCRIPTOR_INTERVAL;
2137 /* If it's already dirty, don't mark it. */
2138 if (! desc_clean_since)
2139 return;
2141 /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
2142 * time to rebuild it. */
2143 if (desc_clean_since < slow_cutoff) {
2144 mark_my_descriptor_dirty("time for new descriptor");
2145 return;
2147 /* Now we see whether we want to be retrying frequently or no. The
2148 * rule here is that we'll retry frequently if we aren't listed in the
2149 * live consensus we have, or if the publication time of the
2150 * descriptor listed for us in the consensus is very old. */
2151 ns = networkstatus_get_live_consensus(now);
2152 if (ns) {
2153 rs = networkstatus_vote_find_entry(ns, server_identitykey_digest);
2154 if (rs == NULL)
2155 retry_fast_reason = "not listed in consensus";
2156 else if (rs->published_on < slow_cutoff)
2157 retry_fast_reason = "version listed in consensus is quite old";
2160 if (retry_fast_reason && desc_clean_since < fast_cutoff)
2161 mark_my_descriptor_dirty(retry_fast_reason);
2164 /** Call when the current descriptor is out of date. */
2165 void
2166 mark_my_descriptor_dirty(const char *reason)
2168 const or_options_t *options = get_options();
2169 if (server_mode(options) && options->PublishServerDescriptor_)
2170 log_info(LD_OR, "Decided to publish new relay descriptor: %s", reason);
2171 desc_clean_since = 0;
2172 if (!desc_dirty_reason)
2173 desc_dirty_reason = reason;
2176 /** How frequently will we republish our descriptor because of large (factor
2177 * of 2) shifts in estimated bandwidth? Note: We don't use this constant
2178 * if our previous bandwidth estimate was exactly 0. */
2179 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
2181 /** Check whether bandwidth has changed a lot since the last time we announced
2182 * bandwidth. If so, mark our descriptor dirty. */
2183 void
2184 check_descriptor_bandwidth_changed(time_t now)
2186 static time_t last_changed = 0;
2187 uint64_t prev, cur;
2188 if (!desc_routerinfo)
2189 return;
2191 prev = desc_routerinfo->bandwidthcapacity;
2192 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
2193 if ((prev != cur && (!prev || !cur)) ||
2194 cur > prev*2 ||
2195 cur < prev/2) {
2196 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now || !prev) {
2197 log_info(LD_GENERAL,
2198 "Measured bandwidth has changed; rebuilding descriptor.");
2199 mark_my_descriptor_dirty("bandwidth has changed");
2200 last_changed = now;
2205 /** Note at log level severity that our best guess of address has changed from
2206 * <b>prev</b> to <b>cur</b>. */
2207 static void
2208 log_addr_has_changed(int severity,
2209 const tor_addr_t *prev,
2210 const tor_addr_t *cur,
2211 const char *source)
2213 char addrbuf_prev[TOR_ADDR_BUF_LEN];
2214 char addrbuf_cur[TOR_ADDR_BUF_LEN];
2216 if (tor_addr_to_str(addrbuf_prev, prev, sizeof(addrbuf_prev), 1) == NULL)
2217 strlcpy(addrbuf_prev, "???", TOR_ADDR_BUF_LEN);
2218 if (tor_addr_to_str(addrbuf_cur, cur, sizeof(addrbuf_cur), 1) == NULL)
2219 strlcpy(addrbuf_cur, "???", TOR_ADDR_BUF_LEN);
2221 if (!tor_addr_is_null(prev))
2222 log_fn(severity, LD_GENERAL,
2223 "Our IP Address has changed from %s to %s; "
2224 "rebuilding descriptor (source: %s).",
2225 addrbuf_prev, addrbuf_cur, source);
2226 else
2227 log_notice(LD_GENERAL,
2228 "Guessed our IP address as %s (source: %s).",
2229 addrbuf_cur, source);
2232 /** Check whether our own address as defined by the Address configuration
2233 * has changed. This is for routers that get their address from a service
2234 * like dyndns. If our address has changed, mark our descriptor dirty. */
2235 void
2236 check_descriptor_ipaddress_changed(time_t now)
2238 uint32_t prev, cur;
2239 const or_options_t *options = get_options();
2240 const char *method = NULL;
2241 char *hostname = NULL;
2243 (void) now;
2245 if (!desc_routerinfo)
2246 return;
2248 /* XXXX ipv6 */
2249 prev = desc_routerinfo->addr;
2250 if (resolve_my_address(LOG_INFO, options, &cur, &method, &hostname) < 0) {
2251 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
2252 return;
2255 if (prev != cur) {
2256 char *source;
2257 tor_addr_t tmp_prev, tmp_cur;
2259 tor_addr_from_ipv4h(&tmp_prev, prev);
2260 tor_addr_from_ipv4h(&tmp_cur, cur);
2262 tor_asprintf(&source, "METHOD=%s%s%s", method,
2263 hostname ? " HOSTNAME=" : "",
2264 hostname ? hostname : "");
2266 log_addr_has_changed(LOG_NOTICE, &tmp_prev, &tmp_cur, source);
2267 tor_free(source);
2269 ip_address_changed(0);
2272 tor_free(hostname);
2275 /** The most recently guessed value of our IP address, based on directory
2276 * headers. */
2277 static tor_addr_t last_guessed_ip = TOR_ADDR_NULL;
2279 /** A directory server <b>d_conn</b> told us our IP address is
2280 * <b>suggestion</b>.
2281 * If this address is different from the one we think we are now, and
2282 * if our computer doesn't actually know its IP address, then switch. */
2283 void
2284 router_new_address_suggestion(const char *suggestion,
2285 const dir_connection_t *d_conn)
2287 tor_addr_t addr;
2288 uint32_t cur = 0; /* Current IPv4 address. */
2289 const or_options_t *options = get_options();
2291 /* first, learn what the IP address actually is */
2292 if (tor_addr_parse(&addr, suggestion) == -1) {
2293 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
2294 escaped(suggestion));
2295 return;
2298 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
2300 if (!server_mode(options)) {
2301 tor_addr_copy(&last_guessed_ip, &addr);
2302 return;
2305 /* XXXX ipv6 */
2306 cur = get_last_resolved_addr();
2307 if (cur ||
2308 resolve_my_address(LOG_INFO, options, &cur, NULL, NULL) >= 0) {
2309 /* We're all set -- we already know our address. Great. */
2310 tor_addr_from_ipv4h(&last_guessed_ip, cur); /* store it in case we
2311 need it later */
2312 return;
2314 if (tor_addr_is_internal(&addr, 0)) {
2315 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
2316 return;
2318 if (tor_addr_eq(&d_conn->base_.addr, &addr)) {
2319 /* Don't believe anybody who says our IP is their IP. */
2320 log_debug(LD_DIR, "A directory server told us our IP address is %s, "
2321 "but he's just reporting his own IP address. Ignoring.",
2322 suggestion);
2323 return;
2326 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
2327 * us an answer different from what we had the last time we managed to
2328 * resolve it. */
2329 if (!tor_addr_eq(&last_guessed_ip, &addr)) {
2330 control_event_server_status(LOG_NOTICE,
2331 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
2332 suggestion);
2333 log_addr_has_changed(LOG_NOTICE, &last_guessed_ip, &addr,
2334 d_conn->base_.address);
2335 ip_address_changed(0);
2336 tor_addr_copy(&last_guessed_ip, &addr); /* router_rebuild_descriptor()
2337 will fetch it */
2341 /** We failed to resolve our address locally, but we'd like to build
2342 * a descriptor and publish / test reachability. If we have a guess
2343 * about our address based on directory headers, answer it and return
2344 * 0; else return -1. */
2345 static int
2346 router_guess_address_from_dir_headers(uint32_t *guess)
2348 if (!tor_addr_is_null(&last_guessed_ip)) {
2349 *guess = tor_addr_to_ipv4h(&last_guessed_ip);
2350 return 0;
2352 return -1;
2355 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
2356 * string describing the version of Tor and the operating system we're
2357 * currently running on.
2359 STATIC void
2360 get_platform_str(char *platform, size_t len)
2362 tor_snprintf(platform, len, "Tor %s on %s",
2363 get_short_version(), get_uname());
2366 /* XXX need to audit this thing and count fenceposts. maybe
2367 * refactor so we don't have to keep asking if we're
2368 * near the end of maxlen?
2370 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2372 /** OR only: Given a routerinfo for this router, and an identity key to sign
2373 * with, encode the routerinfo as a signed server descriptor and return a new
2374 * string encoding the result, or NULL on failure.
2376 char *
2377 router_dump_router_to_string(routerinfo_t *router,
2378 const crypto_pk_t *ident_key,
2379 const crypto_pk_t *tap_key,
2380 const curve25519_keypair_t *ntor_keypair,
2381 const ed25519_keypair_t *signing_keypair)
2383 char *address = NULL;
2384 char *onion_pkey = NULL; /* Onion key, PEM-encoded. */
2385 char *identity_pkey = NULL; /* Identity key, PEM-encoded. */
2386 char digest[DIGEST256_LEN];
2387 char published[ISO_TIME_LEN+1];
2388 char fingerprint[FINGERPRINT_LEN+1];
2389 char *extra_info_line = NULL;
2390 size_t onion_pkeylen, identity_pkeylen;
2391 char *family_line = NULL;
2392 char *extra_or_address = NULL;
2393 const or_options_t *options = get_options();
2394 smartlist_t *chunks = NULL;
2395 char *output = NULL;
2396 const int emit_ed_sigs = signing_keypair && router->signing_key_cert;
2397 char *ed_cert_line = NULL;
2398 char *rsa_tap_cc_line = NULL;
2399 char *ntor_cc_line = NULL;
2401 /* Make sure the identity key matches the one in the routerinfo. */
2402 if (!crypto_pk_eq_keys(ident_key, router->identity_pkey)) {
2403 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
2404 "match router's public key!");
2405 goto err;
2407 if (emit_ed_sigs) {
2408 if (!router->signing_key_cert->signing_key_included ||
2409 !ed25519_pubkey_eq(&router->signing_key_cert->signed_key,
2410 &signing_keypair->pubkey)) {
2411 log_warn(LD_BUG, "Tried to sign a router descriptor with a mismatched "
2412 "ed25519 key chain %d",
2413 router->signing_key_cert->signing_key_included);
2414 goto err;
2418 /* record our fingerprint, so we can include it in the descriptor */
2419 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
2420 log_err(LD_BUG,"Error computing fingerprint");
2421 goto err;
2424 if (emit_ed_sigs) {
2425 /* Encode ed25519 signing cert */
2426 char ed_cert_base64[256];
2427 char ed_fp_base64[ED25519_BASE64_LEN+1];
2428 if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
2429 (const char*)router->signing_key_cert->encoded,
2430 router->signing_key_cert->encoded_len,
2431 BASE64_ENCODE_MULTILINE) < 0) {
2432 log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
2433 goto err;
2435 if (ed25519_public_to_base64(ed_fp_base64,
2436 &router->signing_key_cert->signing_key)<0) {
2437 log_err(LD_BUG,"Couldn't base64-encode identity key\n");
2438 goto err;
2440 tor_asprintf(&ed_cert_line, "identity-ed25519\n"
2441 "-----BEGIN ED25519 CERT-----\n"
2442 "%s"
2443 "-----END ED25519 CERT-----\n"
2444 "master-key-ed25519 %s\n",
2445 ed_cert_base64, ed_fp_base64);
2448 /* PEM-encode the onion key */
2449 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
2450 &onion_pkey,&onion_pkeylen)<0) {
2451 log_warn(LD_BUG,"write onion_pkey to string failed!");
2452 goto err;
2455 /* PEM-encode the identity key */
2456 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
2457 &identity_pkey,&identity_pkeylen)<0) {
2458 log_warn(LD_BUG,"write identity_pkey to string failed!");
2459 goto err;
2462 /* Cross-certify with RSA key */
2463 if (tap_key && router->signing_key_cert &&
2464 router->signing_key_cert->signing_key_included) {
2465 char buf[256];
2466 int tap_cc_len = 0;
2467 uint8_t *tap_cc =
2468 make_tap_onion_key_crosscert(tap_key,
2469 &router->signing_key_cert->signing_key,
2470 router->identity_pkey,
2471 &tap_cc_len);
2472 if (!tap_cc) {
2473 log_warn(LD_BUG,"make_tap_onion_key_crosscert failed!");
2474 goto err;
2477 if (base64_encode(buf, sizeof(buf), (const char*)tap_cc, tap_cc_len,
2478 BASE64_ENCODE_MULTILINE) < 0) {
2479 log_warn(LD_BUG,"base64_encode(rsa_crosscert) failed!");
2480 tor_free(tap_cc);
2481 goto err;
2483 tor_free(tap_cc);
2485 tor_asprintf(&rsa_tap_cc_line,
2486 "onion-key-crosscert\n"
2487 "-----BEGIN CROSSCERT-----\n"
2488 "%s"
2489 "-----END CROSSCERT-----\n", buf);
2492 /* Cross-certify with onion keys */
2493 if (ntor_keypair && router->signing_key_cert &&
2494 router->signing_key_cert->signing_key_included) {
2495 int sign = 0;
2496 char buf[256];
2497 /* XXXX Base the expiration date on the actual onion key expiration time?*/
2498 tor_cert_t *cert =
2499 make_ntor_onion_key_crosscert(ntor_keypair,
2500 &router->signing_key_cert->signing_key,
2501 router->cache_info.published_on,
2502 MIN_ONION_KEY_LIFETIME, &sign);
2503 if (!cert) {
2504 log_warn(LD_BUG,"make_ntor_onion_key_crosscert failed!");
2505 goto err;
2507 tor_assert(sign == 0 || sign == 1);
2509 if (base64_encode(buf, sizeof(buf),
2510 (const char*)cert->encoded, cert->encoded_len,
2511 BASE64_ENCODE_MULTILINE)<0) {
2512 log_warn(LD_BUG,"base64_encode(ntor_crosscert) failed!");
2513 tor_cert_free(cert);
2514 goto err;
2516 tor_cert_free(cert);
2518 tor_asprintf(&ntor_cc_line,
2519 "ntor-onion-key-crosscert %d\n"
2520 "-----BEGIN ED25519 CERT-----\n"
2521 "%s"
2522 "-----END ED25519 CERT-----\n", sign, buf);
2525 /* Encode the publication time. */
2526 format_iso_time(published, router->cache_info.published_on);
2528 if (router->declared_family && smartlist_len(router->declared_family)) {
2529 char *family = smartlist_join_strings(router->declared_family,
2530 " ", 0, NULL);
2531 tor_asprintf(&family_line, "family %s\n", family);
2532 tor_free(family);
2533 } else {
2534 family_line = tor_strdup("");
2537 if (!tor_digest_is_zero(router->cache_info.extra_info_digest)) {
2538 char extra_info_digest[HEX_DIGEST_LEN+1];
2539 base16_encode(extra_info_digest, sizeof(extra_info_digest),
2540 router->cache_info.extra_info_digest, DIGEST_LEN);
2541 if (!tor_digest256_is_zero(router->extra_info_digest256)) {
2542 char d256_64[BASE64_DIGEST256_LEN+1];
2543 digest256_to_base64(d256_64, router->extra_info_digest256);
2544 tor_asprintf(&extra_info_line, "extra-info-digest %s %s\n",
2545 extra_info_digest, d256_64);
2546 } else {
2547 tor_asprintf(&extra_info_line, "extra-info-digest %s\n",
2548 extra_info_digest);
2552 if (router->ipv6_orport &&
2553 tor_addr_family(&router->ipv6_addr) == AF_INET6) {
2554 char addr[TOR_ADDR_BUF_LEN];
2555 const char *a;
2556 a = tor_addr_to_str(addr, &router->ipv6_addr, sizeof(addr), 1);
2557 if (a) {
2558 tor_asprintf(&extra_or_address,
2559 "or-address %s:%d\n", a, router->ipv6_orport);
2560 log_debug(LD_OR, "My or-address line is <%s>", extra_or_address);
2564 address = tor_dup_ip(router->addr);
2565 chunks = smartlist_new();
2567 /* Generate the easy portion of the router descriptor. */
2568 smartlist_add_asprintf(chunks,
2569 "router %s %s %d 0 %d\n"
2570 "%s"
2571 "%s"
2572 "platform %s\n"
2573 "protocols Link 1 2 Circuit 1\n"
2574 "published %s\n"
2575 "fingerprint %s\n"
2576 "uptime %ld\n"
2577 "bandwidth %d %d %d\n"
2578 "%s%s"
2579 "onion-key\n%s"
2580 "signing-key\n%s"
2581 "%s%s"
2582 "%s%s%s%s",
2583 router->nickname,
2584 address,
2585 router->or_port,
2586 decide_to_advertise_dirport(options, router->dir_port),
2587 ed_cert_line ? ed_cert_line : "",
2588 extra_or_address ? extra_or_address : "",
2589 router->platform,
2590 published,
2591 fingerprint,
2592 stats_n_seconds_working,
2593 (int) router->bandwidthrate,
2594 (int) router->bandwidthburst,
2595 (int) router->bandwidthcapacity,
2596 extra_info_line ? extra_info_line : "",
2597 (options->DownloadExtraInfo || options->V3AuthoritativeDir) ?
2598 "caches-extra-info\n" : "",
2599 onion_pkey, identity_pkey,
2600 rsa_tap_cc_line ? rsa_tap_cc_line : "",
2601 ntor_cc_line ? ntor_cc_line : "",
2602 family_line,
2603 we_are_hibernating() ? "hibernating 1\n" : "",
2604 "hidden-service-dir\n",
2605 options->AllowSingleHopExits ? "allow-single-hop-exits\n" : "");
2607 if (options->ContactInfo && strlen(options->ContactInfo)) {
2608 const char *ci = options->ContactInfo;
2609 if (strchr(ci, '\n') || strchr(ci, '\r'))
2610 ci = escaped(ci);
2611 smartlist_add_asprintf(chunks, "contact %s\n", ci);
2614 if (router->onion_curve25519_pkey) {
2615 char kbuf[128];
2616 base64_encode(kbuf, sizeof(kbuf),
2617 (const char *)router->onion_curve25519_pkey->public_key,
2618 CURVE25519_PUBKEY_LEN, BASE64_ENCODE_MULTILINE);
2619 smartlist_add_asprintf(chunks, "ntor-onion-key %s", kbuf);
2622 /* Write the exit policy to the end of 's'. */
2623 if (!router->exit_policy || !smartlist_len(router->exit_policy)) {
2624 smartlist_add(chunks, tor_strdup("reject *:*\n"));
2625 } else if (router->exit_policy) {
2626 char *exit_policy = router_dump_exit_policy_to_string(router,1,0);
2628 if (!exit_policy)
2629 goto err;
2631 smartlist_add_asprintf(chunks, "%s\n", exit_policy);
2632 tor_free(exit_policy);
2635 if (router->ipv6_exit_policy) {
2636 char *p6 = write_short_policy(router->ipv6_exit_policy);
2637 if (p6 && strcmp(p6, "reject 1-65535")) {
2638 smartlist_add_asprintf(chunks,
2639 "ipv6-policy %s\n", p6);
2641 tor_free(p6);
2644 /* Sign the descriptor with Ed25519 */
2645 if (emit_ed_sigs) {
2646 smartlist_add(chunks, tor_strdup("router-sig-ed25519 "));
2647 crypto_digest_smartlist_prefix(digest, DIGEST256_LEN,
2648 ED_DESC_SIGNATURE_PREFIX,
2649 chunks, "", DIGEST_SHA256);
2650 ed25519_signature_t sig;
2651 char buf[ED25519_SIG_BASE64_LEN+1];
2652 if (ed25519_sign(&sig, (const uint8_t*)digest, DIGEST256_LEN,
2653 signing_keypair) < 0)
2654 goto err;
2655 if (ed25519_signature_to_base64(buf, &sig) < 0)
2656 goto err;
2658 smartlist_add_asprintf(chunks, "%s\n", buf);
2661 /* Sign the descriptor with RSA */
2662 smartlist_add(chunks, tor_strdup("router-signature\n"));
2664 crypto_digest_smartlist(digest, DIGEST_LEN, chunks, "", DIGEST_SHA1);
2666 note_crypto_pk_op(SIGN_RTR);
2668 char *sig;
2669 if (!(sig = router_get_dirobj_signature(digest, DIGEST_LEN, ident_key))) {
2670 log_warn(LD_BUG, "Couldn't sign router descriptor");
2671 goto err;
2673 smartlist_add(chunks, sig);
2676 /* include a last '\n' */
2677 smartlist_add(chunks, tor_strdup("\n"));
2679 output = smartlist_join_strings(chunks, "", 0, NULL);
2681 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2683 char *s_dup;
2684 const char *cp;
2685 routerinfo_t *ri_tmp;
2686 cp = s_dup = tor_strdup(output);
2687 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL, NULL);
2688 if (!ri_tmp) {
2689 log_err(LD_BUG,
2690 "We just generated a router descriptor we can't parse.");
2691 log_err(LD_BUG, "Descriptor was: <<%s>>", output);
2692 goto err;
2694 tor_free(s_dup);
2695 routerinfo_free(ri_tmp);
2697 #endif
2699 goto done;
2701 err:
2702 tor_free(output); /* sets output to NULL */
2703 done:
2704 if (chunks) {
2705 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
2706 smartlist_free(chunks);
2708 tor_free(address);
2709 tor_free(family_line);
2710 tor_free(onion_pkey);
2711 tor_free(identity_pkey);
2712 tor_free(extra_or_address);
2713 tor_free(ed_cert_line);
2714 tor_free(rsa_tap_cc_line);
2715 tor_free(ntor_cc_line);
2716 tor_free(extra_info_line);
2718 return output;
2722 * OR only: Given <b>router</b>, produce a string with its exit policy.
2723 * If <b>include_ipv4</b> is true, include IPv4 entries.
2724 * If <b>include_ipv6</b> is true, include IPv6 entries.
2726 char *
2727 router_dump_exit_policy_to_string(const routerinfo_t *router,
2728 int include_ipv4,
2729 int include_ipv6)
2731 smartlist_t *exit_policy_strings;
2732 char *policy_string = NULL;
2734 if ((!router->exit_policy) || (router->policy_is_reject_star)) {
2735 return tor_strdup("reject *:*");
2738 exit_policy_strings = smartlist_new();
2740 SMARTLIST_FOREACH_BEGIN(router->exit_policy, addr_policy_t *, tmpe) {
2741 char *pbuf;
2742 int bytes_written_to_pbuf;
2743 if ((tor_addr_family(&tmpe->addr) == AF_INET6) && (!include_ipv6)) {
2744 continue; /* Don't include IPv6 parts of address policy */
2746 if ((tor_addr_family(&tmpe->addr) == AF_INET) && (!include_ipv4)) {
2747 continue; /* Don't include IPv4 parts of address policy */
2750 pbuf = tor_malloc(POLICY_BUF_LEN);
2751 bytes_written_to_pbuf = policy_write_item(pbuf,POLICY_BUF_LEN, tmpe, 1);
2753 if (bytes_written_to_pbuf < 0) {
2754 log_warn(LD_BUG, "router_dump_exit_policy_to_string ran out of room!");
2755 tor_free(pbuf);
2756 goto done;
2759 smartlist_add(exit_policy_strings,pbuf);
2760 } SMARTLIST_FOREACH_END(tmpe);
2762 policy_string = smartlist_join_strings(exit_policy_strings, "\n", 0, NULL);
2764 done:
2765 SMARTLIST_FOREACH(exit_policy_strings, char *, str, tor_free(str));
2766 smartlist_free(exit_policy_strings);
2768 return policy_string;
2771 /** Copy the primary (IPv4) OR port (IP address and TCP port) for
2772 * <b>router</b> into *<b>ap_out</b>. */
2773 void
2774 router_get_prim_orport(const routerinfo_t *router, tor_addr_port_t *ap_out)
2776 tor_assert(ap_out != NULL);
2777 tor_addr_from_ipv4h(&ap_out->addr, router->addr);
2778 ap_out->port = router->or_port;
2781 /** Return 1 if any of <b>router</b>'s addresses are <b>addr</b>.
2782 * Otherwise return 0. */
2784 router_has_addr(const routerinfo_t *router, const tor_addr_t *addr)
2786 return
2787 tor_addr_eq_ipv4h(addr, router->addr) ||
2788 tor_addr_eq(&router->ipv6_addr, addr);
2792 router_has_orport(const routerinfo_t *router, const tor_addr_port_t *orport)
2794 return
2795 (tor_addr_eq_ipv4h(&orport->addr, router->addr) &&
2796 orport->port == router->or_port) ||
2797 (tor_addr_eq(&orport->addr, &router->ipv6_addr) &&
2798 orport->port == router->ipv6_orport);
2801 /** Load the contents of <b>filename</b>, find the last line starting with
2802 * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
2803 * the past or more than 1 hour in the future with respect to <b>now</b>,
2804 * and write the file contents starting with that line to *<b>out</b>.
2805 * Return 1 for success, 0 if the file does not exist or is empty, or -1
2806 * if the file does not contain a line matching these criteria or other
2807 * failure. */
2808 static int
2809 load_stats_file(const char *filename, const char *end_line, time_t now,
2810 char **out)
2812 int r = -1;
2813 char *fname = get_datadir_fname(filename);
2814 char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
2815 time_t written;
2816 switch (file_status(fname)) {
2817 case FN_FILE:
2818 /* X022 Find an alternative to reading the whole file to memory. */
2819 if ((contents = read_file_to_str(fname, 0, NULL))) {
2820 tmp = strstr(contents, end_line);
2821 /* Find last block starting with end_line */
2822 while (tmp) {
2823 start = tmp;
2824 tmp = strstr(tmp + 1, end_line);
2826 if (!start)
2827 goto notfound;
2828 if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
2829 goto notfound;
2830 strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
2831 if (parse_iso_time(timestr, &written) < 0)
2832 goto notfound;
2833 if (written < now - (25*60*60) || written > now + (1*60*60))
2834 goto notfound;
2835 *out = tor_strdup(start);
2836 r = 1;
2838 notfound:
2839 tor_free(contents);
2840 break;
2841 /* treat empty stats files as if the file doesn't exist */
2842 case FN_NOENT:
2843 case FN_EMPTY:
2844 r = 0;
2845 break;
2846 case FN_ERROR:
2847 case FN_DIR:
2848 default:
2849 break;
2851 tor_free(fname);
2852 return r;
2855 /** Write the contents of <b>extrainfo</b> and aggregated statistics to
2856 * *<b>s_out</b>, signing them with <b>ident_key</b>. Return 0 on
2857 * success, negative on failure. */
2859 extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo,
2860 crypto_pk_t *ident_key,
2861 const ed25519_keypair_t *signing_keypair)
2863 const or_options_t *options = get_options();
2864 char identity[HEX_DIGEST_LEN+1];
2865 char published[ISO_TIME_LEN+1];
2866 char digest[DIGEST_LEN];
2867 char *bandwidth_usage;
2868 int result;
2869 static int write_stats_to_extrainfo = 1;
2870 char sig[DIROBJ_MAX_SIG_LEN+1];
2871 char *s = NULL, *pre, *contents, *cp, *s_dup = NULL;
2872 time_t now = time(NULL);
2873 smartlist_t *chunks = smartlist_new();
2874 extrainfo_t *ei_tmp = NULL;
2875 const int emit_ed_sigs = signing_keypair && extrainfo->signing_key_cert;
2876 char *ed_cert_line = NULL;
2878 base16_encode(identity, sizeof(identity),
2879 extrainfo->cache_info.identity_digest, DIGEST_LEN);
2880 format_iso_time(published, extrainfo->cache_info.published_on);
2881 bandwidth_usage = rep_hist_get_bandwidth_lines();
2882 if (emit_ed_sigs) {
2883 if (!extrainfo->signing_key_cert->signing_key_included ||
2884 !ed25519_pubkey_eq(&extrainfo->signing_key_cert->signed_key,
2885 &signing_keypair->pubkey)) {
2886 log_warn(LD_BUG, "Tried to sign a extrainfo descriptor with a "
2887 "mismatched ed25519 key chain %d",
2888 extrainfo->signing_key_cert->signing_key_included);
2889 goto err;
2891 char ed_cert_base64[256];
2892 if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
2893 (const char*)extrainfo->signing_key_cert->encoded,
2894 extrainfo->signing_key_cert->encoded_len,
2895 BASE64_ENCODE_MULTILINE) < 0) {
2896 log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
2897 goto err;
2899 tor_asprintf(&ed_cert_line, "identity-ed25519\n"
2900 "-----BEGIN ED25519 CERT-----\n"
2901 "%s"
2902 "-----END ED25519 CERT-----\n", ed_cert_base64);
2903 } else {
2904 ed_cert_line = tor_strdup("");
2907 tor_asprintf(&pre, "extra-info %s %s\n%spublished %s\n%s",
2908 extrainfo->nickname, identity,
2909 ed_cert_line,
2910 published, bandwidth_usage);
2911 smartlist_add(chunks, pre);
2913 if (geoip_is_loaded(AF_INET))
2914 smartlist_add_asprintf(chunks, "geoip-db-digest %s\n",
2915 geoip_db_digest(AF_INET));
2916 if (geoip_is_loaded(AF_INET6))
2917 smartlist_add_asprintf(chunks, "geoip6-db-digest %s\n",
2918 geoip_db_digest(AF_INET6));
2920 if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
2921 log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
2922 if (options->DirReqStatistics &&
2923 load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
2924 "dirreq-stats-end", now, &contents) > 0) {
2925 smartlist_add(chunks, contents);
2927 if (options->HiddenServiceStatistics &&
2928 load_stats_file("stats"PATH_SEPARATOR"hidserv-stats",
2929 "hidserv-stats-end", now, &contents) > 0) {
2930 smartlist_add(chunks, contents);
2932 if (options->EntryStatistics &&
2933 load_stats_file("stats"PATH_SEPARATOR"entry-stats",
2934 "entry-stats-end", now, &contents) > 0) {
2935 smartlist_add(chunks, contents);
2937 if (options->CellStatistics &&
2938 load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
2939 "cell-stats-end", now, &contents) > 0) {
2940 smartlist_add(chunks, contents);
2942 if (options->ExitPortStatistics &&
2943 load_stats_file("stats"PATH_SEPARATOR"exit-stats",
2944 "exit-stats-end", now, &contents) > 0) {
2945 smartlist_add(chunks, contents);
2947 if (options->ConnDirectionStatistics &&
2948 load_stats_file("stats"PATH_SEPARATOR"conn-stats",
2949 "conn-bi-direct", now, &contents) > 0) {
2950 smartlist_add(chunks, contents);
2954 /* Add information about the pluggable transports we support. */
2955 if (options->ServerTransportPlugin) {
2956 char *pluggable_transports = pt_get_extra_info_descriptor_string();
2957 if (pluggable_transports)
2958 smartlist_add(chunks, pluggable_transports);
2961 if (should_record_bridge_info(options) && write_stats_to_extrainfo) {
2962 const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
2963 if (bridge_stats) {
2964 smartlist_add(chunks, tor_strdup(bridge_stats));
2968 if (emit_ed_sigs) {
2969 char digest[DIGEST256_LEN];
2970 smartlist_add(chunks, tor_strdup("router-sig-ed25519 "));
2971 crypto_digest_smartlist_prefix(digest, DIGEST256_LEN,
2972 ED_DESC_SIGNATURE_PREFIX,
2973 chunks, "", DIGEST_SHA256);
2974 ed25519_signature_t sig;
2975 char buf[ED25519_SIG_BASE64_LEN+1];
2976 if (ed25519_sign(&sig, (const uint8_t*)digest, DIGEST256_LEN,
2977 signing_keypair) < 0)
2978 goto err;
2979 if (ed25519_signature_to_base64(buf, &sig) < 0)
2980 goto err;
2982 smartlist_add_asprintf(chunks, "%s\n", buf);
2985 smartlist_add(chunks, tor_strdup("router-signature\n"));
2986 s = smartlist_join_strings(chunks, "", 0, NULL);
2988 while (strlen(s) > MAX_EXTRAINFO_UPLOAD_SIZE - DIROBJ_MAX_SIG_LEN) {
2989 /* So long as there are at least two chunks (one for the initial
2990 * extra-info line and one for the router-signature), we can keep removing
2991 * things. */
2992 if (smartlist_len(chunks) > 2) {
2993 /* We remove the next-to-last element (remember, len-1 is the last
2994 element), since we need to keep the router-signature element. */
2995 int idx = smartlist_len(chunks) - 2;
2996 char *e = smartlist_get(chunks, idx);
2997 smartlist_del_keeporder(chunks, idx);
2998 log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
2999 "with statistics that exceeds the 50 KB "
3000 "upload limit. Removing last added "
3001 "statistics.");
3002 tor_free(e);
3003 tor_free(s);
3004 s = smartlist_join_strings(chunks, "", 0, NULL);
3005 } else {
3006 log_warn(LD_BUG, "We just generated an extra-info descriptors that "
3007 "exceeds the 50 KB upload limit.");
3008 goto err;
3012 memset(sig, 0, sizeof(sig));
3013 if (router_get_extrainfo_hash(s, strlen(s), digest) < 0 ||
3014 router_append_dirobj_signature(sig, sizeof(sig), digest, DIGEST_LEN,
3015 ident_key) < 0) {
3016 log_warn(LD_BUG, "Could not append signature to extra-info "
3017 "descriptor.");
3018 goto err;
3020 smartlist_add(chunks, tor_strdup(sig));
3021 tor_free(s);
3022 s = smartlist_join_strings(chunks, "", 0, NULL);
3024 cp = s_dup = tor_strdup(s);
3025 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL, NULL);
3026 if (!ei_tmp) {
3027 if (write_stats_to_extrainfo) {
3028 log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
3029 "with statistics that we can't parse. Not "
3030 "adding statistics to this or any future "
3031 "extra-info descriptors.");
3032 write_stats_to_extrainfo = 0;
3033 result = extrainfo_dump_to_string(s_out, extrainfo, ident_key,
3034 signing_keypair);
3035 goto done;
3036 } else {
3037 log_warn(LD_BUG, "We just generated an extrainfo descriptor we "
3038 "can't parse.");
3039 goto err;
3043 *s_out = s;
3044 s = NULL; /* prevent free */
3045 result = 0;
3046 goto done;
3048 err:
3049 result = -1;
3051 done:
3052 tor_free(s);
3053 SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
3054 smartlist_free(chunks);
3055 tor_free(s_dup);
3056 tor_free(ed_cert_line);
3057 extrainfo_free(ei_tmp);
3058 tor_free(bandwidth_usage);
3060 return result;
3063 /** Return true iff <b>s</b> is a valid server nickname. (That is, a string
3064 * containing between 1 and MAX_NICKNAME_LEN characters from
3065 * LEGAL_NICKNAME_CHARACTERS.) */
3067 is_legal_nickname(const char *s)
3069 size_t len;
3070 tor_assert(s);
3071 len = strlen(s);
3072 return len > 0 && len <= MAX_NICKNAME_LEN &&
3073 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
3076 /** Return true iff <b>s</b> is a valid server nickname or
3077 * hex-encoded identity-key digest. */
3079 is_legal_nickname_or_hexdigest(const char *s)
3081 if (*s!='$')
3082 return is_legal_nickname(s);
3083 else
3084 return is_legal_hexdigest(s);
3087 /** Return true iff <b>s</b> is a valid hex-encoded identity-key
3088 * digest. (That is, an optional $, followed by 40 hex characters,
3089 * followed by either nothing, or = or ~ followed by a nickname, or
3090 * a character other than =, ~, or a hex character.)
3093 is_legal_hexdigest(const char *s)
3095 size_t len;
3096 tor_assert(s);
3097 if (s[0] == '$') s++;
3098 len = strlen(s);
3099 if (len > HEX_DIGEST_LEN) {
3100 if (s[HEX_DIGEST_LEN] == '=' ||
3101 s[HEX_DIGEST_LEN] == '~') {
3102 if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
3103 return 0;
3104 } else {
3105 return 0;
3108 return (len >= HEX_DIGEST_LEN &&
3109 strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
3112 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
3113 * hold a human-readable description of a node with identity digest
3114 * <b>id_digest</b>, named-status <b>is_named</b>, nickname <b>nickname</b>,
3115 * and address <b>addr</b> or <b>addr32h</b>.
3117 * The <b>nickname</b> and <b>addr</b> fields are optional and may be set to
3118 * NULL. The <b>addr32h</b> field is optional and may be set to 0.
3120 * Return a pointer to the front of <b>buf</b>.
3122 const char *
3123 format_node_description(char *buf,
3124 const char *id_digest,
3125 int is_named,
3126 const char *nickname,
3127 const tor_addr_t *addr,
3128 uint32_t addr32h)
3130 char *cp;
3132 if (!buf)
3133 return "<NULL BUFFER>";
3135 buf[0] = '$';
3136 base16_encode(buf+1, HEX_DIGEST_LEN+1, id_digest, DIGEST_LEN);
3137 cp = buf+1+HEX_DIGEST_LEN;
3138 if (nickname) {
3139 buf[1+HEX_DIGEST_LEN] = is_named ? '=' : '~';
3140 strlcpy(buf+1+HEX_DIGEST_LEN+1, nickname, MAX_NICKNAME_LEN+1);
3141 cp += strlen(cp);
3143 if (addr32h || addr) {
3144 memcpy(cp, " at ", 4);
3145 cp += 4;
3146 if (addr) {
3147 tor_addr_to_str(cp, addr, TOR_ADDR_BUF_LEN, 0);
3148 } else {
3149 struct in_addr in;
3150 in.s_addr = htonl(addr32h);
3151 tor_inet_ntoa(&in, cp, INET_NTOA_BUF_LEN);
3154 return buf;
3157 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
3158 * hold a human-readable description of <b>ri</b>.
3161 * Return a pointer to the front of <b>buf</b>.
3163 const char *
3164 router_get_description(char *buf, const routerinfo_t *ri)
3166 if (!ri)
3167 return "<null>";
3168 return format_node_description(buf,
3169 ri->cache_info.identity_digest,
3170 router_is_named(ri),
3171 ri->nickname,
3172 NULL,
3173 ri->addr);
3176 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
3177 * hold a human-readable description of <b>node</b>.
3179 * Return a pointer to the front of <b>buf</b>.
3181 const char *
3182 node_get_description(char *buf, const node_t *node)
3184 const char *nickname = NULL;
3185 uint32_t addr32h = 0;
3186 int is_named = 0;
3188 if (!node)
3189 return "<null>";
3191 if (node->rs) {
3192 nickname = node->rs->nickname;
3193 is_named = node->rs->is_named;
3194 addr32h = node->rs->addr;
3195 } else if (node->ri) {
3196 nickname = node->ri->nickname;
3197 addr32h = node->ri->addr;
3200 return format_node_description(buf,
3201 node->identity,
3202 is_named,
3203 nickname,
3204 NULL,
3205 addr32h);
3208 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
3209 * hold a human-readable description of <b>rs</b>.
3211 * Return a pointer to the front of <b>buf</b>.
3213 const char *
3214 routerstatus_get_description(char *buf, const routerstatus_t *rs)
3216 if (!rs)
3217 return "<null>";
3218 return format_node_description(buf,
3219 rs->identity_digest,
3220 rs->is_named,
3221 rs->nickname,
3222 NULL,
3223 rs->addr);
3226 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
3227 * hold a human-readable description of <b>ei</b>.
3229 * Return a pointer to the front of <b>buf</b>.
3231 const char *
3232 extend_info_get_description(char *buf, const extend_info_t *ei)
3234 if (!ei)
3235 return "<null>";
3236 return format_node_description(buf,
3237 ei->identity_digest,
3239 ei->nickname,
3240 &ei->addr,
3244 /** Return a human-readable description of the routerinfo_t <b>ri</b>.
3246 * This function is not thread-safe. Each call to this function invalidates
3247 * previous values returned by this function.
3249 const char *
3250 router_describe(const routerinfo_t *ri)
3252 static char buf[NODE_DESC_BUF_LEN];
3253 return router_get_description(buf, ri);
3256 /** Return a human-readable description of the node_t <b>node</b>.
3258 * This function is not thread-safe. Each call to this function invalidates
3259 * previous values returned by this function.
3261 const char *
3262 node_describe(const node_t *node)
3264 static char buf[NODE_DESC_BUF_LEN];
3265 return node_get_description(buf, node);
3268 /** Return a human-readable description of the routerstatus_t <b>rs</b>.
3270 * This function is not thread-safe. Each call to this function invalidates
3271 * previous values returned by this function.
3273 const char *
3274 routerstatus_describe(const routerstatus_t *rs)
3276 static char buf[NODE_DESC_BUF_LEN];
3277 return routerstatus_get_description(buf, rs);
3280 /** Return a human-readable description of the extend_info_t <b>ri</b>.
3282 * This function is not thread-safe. Each call to this function invalidates
3283 * previous values returned by this function.
3285 const char *
3286 extend_info_describe(const extend_info_t *ei)
3288 static char buf[NODE_DESC_BUF_LEN];
3289 return extend_info_get_description(buf, ei);
3292 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
3293 * verbose representation of the identity of <b>router</b>. The format is:
3294 * A dollar sign.
3295 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
3296 * A "=" if the router is named; a "~" if it is not.
3297 * The router's nickname.
3299 void
3300 router_get_verbose_nickname(char *buf, const routerinfo_t *router)
3302 const char *good_digest = networkstatus_get_router_digest_by_nickname(
3303 router->nickname);
3304 int is_named = good_digest && tor_memeq(good_digest,
3305 router->cache_info.identity_digest,
3306 DIGEST_LEN);
3307 buf[0] = '$';
3308 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
3309 DIGEST_LEN);
3310 buf[1+HEX_DIGEST_LEN] = is_named ? '=' : '~';
3311 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
3314 /** Forget that we have issued any router-related warnings, so that we'll
3315 * warn again if we see the same errors. */
3316 void
3317 router_reset_warnings(void)
3319 if (warned_nonexistent_family) {
3320 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
3321 smartlist_clear(warned_nonexistent_family);
3325 /** Given a router purpose, convert it to a string. Don't call this on
3326 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
3327 * know its string representation. */
3328 const char *
3329 router_purpose_to_string(uint8_t p)
3331 switch (p)
3333 case ROUTER_PURPOSE_GENERAL: return "general";
3334 case ROUTER_PURPOSE_BRIDGE: return "bridge";
3335 case ROUTER_PURPOSE_CONTROLLER: return "controller";
3336 default:
3337 tor_assert(0);
3339 return NULL;
3342 /** Given a string, convert it to a router purpose. */
3343 uint8_t
3344 router_purpose_from_string(const char *s)
3346 if (!strcmp(s, "general"))
3347 return ROUTER_PURPOSE_GENERAL;
3348 else if (!strcmp(s, "bridge"))
3349 return ROUTER_PURPOSE_BRIDGE;
3350 else if (!strcmp(s, "controller"))
3351 return ROUTER_PURPOSE_CONTROLLER;
3352 else
3353 return ROUTER_PURPOSE_UNKNOWN;
3356 /** Release all static resources held in router.c */
3357 void
3358 router_free_all(void)
3360 crypto_pk_free(onionkey);
3361 crypto_pk_free(lastonionkey);
3362 crypto_pk_free(server_identitykey);
3363 crypto_pk_free(client_identitykey);
3364 tor_mutex_free(key_lock);
3365 routerinfo_free(desc_routerinfo);
3366 extrainfo_free(desc_extrainfo);
3367 crypto_pk_free(authority_signing_key);
3368 authority_cert_free(authority_key_certificate);
3369 crypto_pk_free(legacy_signing_key);
3370 authority_cert_free(legacy_key_certificate);
3372 memwipe(&curve25519_onion_key, 0, sizeof(curve25519_onion_key));
3373 memwipe(&last_curve25519_onion_key, 0, sizeof(last_curve25519_onion_key));
3375 if (warned_nonexistent_family) {
3376 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
3377 smartlist_free(warned_nonexistent_family);
3381 /** Return a smartlist of tor_addr_port_t's with all the OR ports of
3382 <b>ri</b>. Note that freeing of the items in the list as well as
3383 the smartlist itself is the callers responsibility.
3385 XXX duplicating code from node_get_all_orports(). */
3386 smartlist_t *
3387 router_get_all_orports(const routerinfo_t *ri)
3389 smartlist_t *sl = smartlist_new();
3390 tor_assert(ri);
3392 if (ri->addr != 0) {
3393 tor_addr_port_t *ap = tor_malloc(sizeof(tor_addr_port_t));
3394 tor_addr_from_ipv4h(&ap->addr, ri->addr);
3395 ap->port = ri->or_port;
3396 smartlist_add(sl, ap);
3398 if (!tor_addr_is_null(&ri->ipv6_addr)) {
3399 tor_addr_port_t *ap = tor_malloc(sizeof(tor_addr_port_t));
3400 tor_addr_copy(&ap->addr, &ri->ipv6_addr);
3401 ap->port = ri->or_port;
3402 smartlist_add(sl, ap);
3405 return sl;