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-2016, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
10 #include "circuitbuild.h"
11 #include "circuitlist.h"
12 #include "circuituse.h"
14 #include "connection.h"
16 #include "crypto_curve25519.h"
17 #include "directory.h"
21 #include "hibernate.h"
23 #include "networkstatus.h"
30 #include "routerkeys.h"
31 #include "routerlist.h"
32 #include "routerparse.h"
33 #include "statefile.h"
35 #include "transports.h"
36 #include "routerset.h"
40 * \brief Miscellaneous relay functionality, including RSA key maintenance,
41 * generating and uploading server descriptors, picking an address to
42 * advertise, and so on.
44 * This module handles the job of deciding whether we are a Tor relay, and if
45 * so what kind. (Mostly through functions like server_mode() that inspect an
46 * or_options_t, but in some cases based on our own capabilities, such as when
47 * we are deciding whether to be a directory cache in
48 * router_has_bandwidth_to_be_dirserver().)
50 * Also in this module are the functions to generate our own routerinfo_t and
51 * extrainfo_t, and to encode those to signed strings for upload to the
52 * directory authorities.
54 * This module also handles key maintenance for RSA and Curve25519-ntor keys,
55 * and for our TLS context. (These functions should eventually move to
56 * routerkeys.c along with the code that handles Ed25519 keys now.)
59 /************************************************************/
62 * Key management: ORs only.
65 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
67 static tor_mutex_t
*key_lock
=NULL
;
68 static time_t onionkey_set_at
=0; /**< When was onionkey last changed? */
69 /** Current private onionskin decryption key: used to decode CREATE cells. */
70 static crypto_pk_t
*onionkey
=NULL
;
71 /** Previous private onionskin decryption key: used to decode CREATE cells
72 * generated by clients that have an older version of our descriptor. */
73 static crypto_pk_t
*lastonionkey
=NULL
;
74 /** Current private ntor secret key: used to perform the ntor handshake. */
75 static curve25519_keypair_t curve25519_onion_key
;
76 /** Previous private ntor secret key: used to perform the ntor handshake
77 * with clients that have an older version of our descriptor. */
78 static curve25519_keypair_t last_curve25519_onion_key
;
79 /** Private server "identity key": used to sign directory info and TLS
80 * certificates. Never changes. */
81 static crypto_pk_t
*server_identitykey
=NULL
;
82 /** Digest of server_identitykey. */
83 static char server_identitykey_digest
[DIGEST_LEN
];
84 /** Private client "identity key": used to sign bridges' and clients'
85 * outbound TLS certificates. Regenerated on startup and on IP address
87 static crypto_pk_t
*client_identitykey
=NULL
;
88 /** Signing key used for v3 directory material; only set for authorities. */
89 static crypto_pk_t
*authority_signing_key
= NULL
;
90 /** Key certificate to authenticate v3 directory material; only set for
92 static authority_cert_t
*authority_key_certificate
= NULL
;
94 /** For emergency V3 authority key migration: An extra signing key that we use
95 * with our old (obsolete) identity key for a while. */
96 static crypto_pk_t
*legacy_signing_key
= NULL
;
97 /** For emergency V3 authority key migration: An extra certificate to
98 * authenticate legacy_signing_key with our obsolete identity key.*/
99 static authority_cert_t
*legacy_key_certificate
= NULL
;
101 /* (Note that v3 authorities also have a separate "authority identity key",
102 * but this key is never actually loaded by the Tor process. Instead, it's
103 * used by tor-gencert to sign new signing keys and make new key
106 /** Replace the current onion key with <b>k</b>. Does not affect
107 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
110 set_onion_key(crypto_pk_t
*k
)
112 if (onionkey
&& crypto_pk_eq_keys(onionkey
, k
)) {
113 /* k is already our onion key; free it and return */
117 tor_mutex_acquire(key_lock
);
118 crypto_pk_free(onionkey
);
120 tor_mutex_release(key_lock
);
121 mark_my_descriptor_dirty("set onion key");
124 /** Return the current onion key. Requires that the onion key has been
125 * loaded or generated. */
129 tor_assert(onionkey
);
133 /** Store a full copy of the current onion key into *<b>key</b>, and a full
134 * copy of the most recent onion key into *<b>last</b>.
137 dup_onion_keys(crypto_pk_t
**key
, crypto_pk_t
**last
)
141 tor_mutex_acquire(key_lock
);
142 tor_assert(onionkey
);
143 *key
= crypto_pk_copy_full(onionkey
);
145 *last
= crypto_pk_copy_full(lastonionkey
);
148 tor_mutex_release(key_lock
);
151 /** Return the current secret onion key for the ntor handshake. Must only
152 * be called from the main thread. */
153 static const curve25519_keypair_t
*
154 get_current_curve25519_keypair(void)
156 return &curve25519_onion_key
;
158 /** Return a map from KEYID (the key itself) to keypairs for use in the ntor
159 * handshake. Must only be called from the main thread. */
161 construct_ntor_key_map(void)
163 di_digest256_map_t
*m
= NULL
;
166 curve25519_onion_key
.pubkey
.public_key
,
167 tor_memdup(&curve25519_onion_key
,
168 sizeof(curve25519_keypair_t
)));
169 if (!tor_mem_is_zero((const char*)
170 last_curve25519_onion_key
.pubkey
.public_key
,
171 CURVE25519_PUBKEY_LEN
)) {
173 last_curve25519_onion_key
.pubkey
.public_key
,
174 tor_memdup(&last_curve25519_onion_key
,
175 sizeof(curve25519_keypair_t
)));
180 /** Helper used to deallocate a di_digest256_map_t returned by
181 * construct_ntor_key_map. */
183 ntor_key_map_free_helper(void *arg
)
185 curve25519_keypair_t
*k
= arg
;
186 memwipe(k
, 0, sizeof(*k
));
189 /** Release all storage from a keymap returned by construct_ntor_key_map. */
191 ntor_key_map_free(di_digest256_map_t
*map
)
195 dimap_free(map
, ntor_key_map_free_helper
);
198 /** Return the time when the onion key was last set. This is either the time
199 * when the process launched, or the time of the most recent key rotation since
200 * the process launched.
203 get_onion_key_set_at(void)
205 return onionkey_set_at
;
208 /** Set the current server identity key to <b>k</b>.
211 set_server_identity_key(crypto_pk_t
*k
)
213 crypto_pk_free(server_identitykey
);
214 server_identitykey
= k
;
215 crypto_pk_get_digest(server_identitykey
, server_identitykey_digest
);
218 /** Make sure that we have set up our identity keys to match or not match as
219 * appropriate, and die with an assertion if we have not. */
221 assert_identity_keys_ok(void)
225 tor_assert(client_identitykey
);
226 if (public_server_mode(get_options())) {
227 /* assert that we have set the client and server keys to be equal */
228 tor_assert(server_identitykey
);
229 tor_assert(crypto_pk_eq_keys(client_identitykey
, server_identitykey
));
231 /* assert that we have set the client and server keys to be unequal */
232 if (server_identitykey
)
233 tor_assert(!crypto_pk_eq_keys(client_identitykey
, server_identitykey
));
237 /** Returns the current server identity key; requires that the key has
238 * been set, and that we are running as a Tor server.
241 get_server_identity_key(void)
243 tor_assert(server_identitykey
);
244 tor_assert(server_mode(get_options()));
245 assert_identity_keys_ok();
246 return server_identitykey
;
249 /** Return true iff we are a server and the server identity key
252 server_identity_key_is_set(void)
254 return server_mode(get_options()) && server_identitykey
!= NULL
;
257 /** Set the current client identity key to <b>k</b>.
260 set_client_identity_key(crypto_pk_t
*k
)
262 crypto_pk_free(client_identitykey
);
263 client_identitykey
= k
;
266 /** Returns the current client identity key for use on outgoing TLS
267 * connections; requires that the key has been set.
270 get_tlsclient_identity_key(void)
272 tor_assert(client_identitykey
);
273 assert_identity_keys_ok();
274 return client_identitykey
;
277 /** Return true iff the client identity key has been set. */
279 client_identity_key_is_set(void)
281 return client_identitykey
!= NULL
;
284 /** Return the key certificate for this v3 (voting) authority, or NULL
285 * if we have no such certificate. */
286 MOCK_IMPL(authority_cert_t
*,
287 get_my_v3_authority_cert
, (void))
289 return authority_key_certificate
;
292 /** Return the v3 signing key for this v3 (voting) authority, or NULL
293 * if we have no such key. */
295 get_my_v3_authority_signing_key(void)
297 return authority_signing_key
;
300 /** If we're an authority, and we're using a legacy authority identity key for
301 * emergency migration purposes, return the certificate associated with that
304 get_my_v3_legacy_cert(void)
306 return legacy_key_certificate
;
309 /** If we're an authority, and we're using a legacy authority identity key for
310 * emergency migration purposes, return that key. */
312 get_my_v3_legacy_signing_key(void)
314 return legacy_signing_key
;
317 /** Replace the previous onion key with the current onion key, and generate
318 * a new previous onion key. Immediately after calling this function,
320 * - schedule all previous cpuworkers to shut down _after_ processing
321 * pending work. (This will cause fresh cpuworkers to be generated.)
322 * - generate and upload a fresh routerinfo.
325 rotate_onion_key(void)
327 char *fname
, *fname_prev
;
328 crypto_pk_t
*prkey
= NULL
;
329 or_state_t
*state
= get_or_state();
330 curve25519_keypair_t new_curve25519_keypair
;
332 fname
= get_datadir_fname2("keys", "secret_onion_key");
333 fname_prev
= get_datadir_fname2("keys", "secret_onion_key.old");
334 /* There isn't much point replacing an old key with an empty file */
335 if (file_status(fname
) == FN_FILE
) {
336 if (replace_file(fname
, fname_prev
))
339 if (!(prkey
= crypto_pk_new())) {
340 log_err(LD_GENERAL
,"Error constructing rotated onion key");
343 if (crypto_pk_generate_key(prkey
)) {
344 log_err(LD_BUG
,"Error generating onion key");
347 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
348 log_err(LD_FS
,"Couldn't write generated onion key to \"%s\".", fname
);
352 tor_free(fname_prev
);
353 fname
= get_datadir_fname2("keys", "secret_onion_key_ntor");
354 fname_prev
= get_datadir_fname2("keys", "secret_onion_key_ntor.old");
355 if (curve25519_keypair_generate(&new_curve25519_keypair
, 1) < 0)
357 /* There isn't much point replacing an old key with an empty file */
358 if (file_status(fname
) == FN_FILE
) {
359 if (replace_file(fname
, fname_prev
))
362 if (curve25519_keypair_write_to_file(&new_curve25519_keypair
, fname
,
364 log_err(LD_FS
,"Couldn't write curve25519 onion key to \"%s\".",fname
);
367 log_info(LD_GENERAL
, "Rotating onion key");
368 tor_mutex_acquire(key_lock
);
369 crypto_pk_free(lastonionkey
);
370 lastonionkey
= onionkey
;
372 memcpy(&last_curve25519_onion_key
, &curve25519_onion_key
,
373 sizeof(curve25519_keypair_t
));
374 memcpy(&curve25519_onion_key
, &new_curve25519_keypair
,
375 sizeof(curve25519_keypair_t
));
377 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
378 tor_mutex_release(key_lock
);
379 mark_my_descriptor_dirty("rotated onion key");
380 or_state_mark_dirty(state
, get_options()->AvoidDiskWrites
? now
+3600 : 0);
383 log_warn(LD_GENERAL
, "Couldn't rotate onion key.");
385 crypto_pk_free(prkey
);
387 memwipe(&new_curve25519_keypair
, 0, sizeof(new_curve25519_keypair
));
389 tor_free(fname_prev
);
392 /** Log greeting message that points to new relay lifecycle document the
393 * first time this function has been called.
396 log_new_relay_greeting(void)
398 static int already_logged
= 0;
403 tor_log(LOG_NOTICE
, LD_GENERAL
, "You are running a new relay. "
404 "Thanks for helping the Tor network! If you wish to know "
405 "what will happen in the upcoming weeks regarding its usage, "
406 "have a look at https://blog.torproject.org/blog/lifecycle-of"
412 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
413 * and <b>generate</b> is true, create a new RSA key and save it in
414 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
415 * errors at level <b>severity</b>. If <b>log_greeting</b> is non-zero and a
416 * new key was created, log_new_relay_greeting() is called.
419 init_key_from_file(const char *fname
, int generate
, int severity
,
422 crypto_pk_t
*prkey
= NULL
;
424 if (!(prkey
= crypto_pk_new())) {
425 tor_log(severity
, LD_GENERAL
,"Error constructing key");
429 switch (file_status(fname
)) {
432 tor_log(severity
, LD_FS
,"Can't read key from \"%s\"", fname
);
434 /* treat empty key files as if the file doesn't exist, and,
435 * if generate is set, replace the empty file in
436 * crypto_pk_write_private_key_to_filename() */
440 if (!have_lockfile()) {
441 if (try_locking(get_options(), 0)<0) {
442 /* Make sure that --list-fingerprint only creates new keys
443 * if there is no possibility for a deadlock. */
444 tor_log(severity
, LD_FS
, "Another Tor process has locked \"%s\". "
445 "Not writing any new keys.", fname
);
446 /*XXXX The 'other process' might make a key in a second or two;
447 * maybe we should wait for it. */
451 log_info(LD_GENERAL
, "No key found in \"%s\"; generating fresh key.",
453 if (crypto_pk_generate_key(prkey
)) {
454 tor_log(severity
, LD_GENERAL
,"Error generating onion key");
457 if (crypto_pk_check_key(prkey
) <= 0) {
458 tor_log(severity
, LD_GENERAL
,"Generated key seems invalid");
461 log_info(LD_GENERAL
, "Generated key seems valid");
463 log_new_relay_greeting();
465 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
466 tor_log(severity
, LD_FS
,
467 "Couldn't write generated key to \"%s\".", fname
);
471 tor_log(severity
, LD_GENERAL
, "No key found in \"%s\"", fname
);
476 if (crypto_pk_read_private_key_from_filename(prkey
, fname
)) {
477 tor_log(severity
, LD_GENERAL
,"Error loading private key.");
487 crypto_pk_free(prkey
);
491 /** Load a curve25519 keypair from the file <b>fname</b>, writing it into
492 * <b>keys_out</b>. If the file isn't found, or is empty, and <b>generate</b>
493 * is true, create a new keypair and write it into the file. If there are
494 * errors, log them at level <b>severity</b>. Generate files using <b>tag</b>
495 * in their ASCII wrapper. */
497 init_curve25519_keypair_from_file(curve25519_keypair_t
*keys_out
,
503 switch (file_status(fname
)) {
506 tor_log(severity
, LD_FS
,"Can't read key from \"%s\"", fname
);
508 /* treat empty key files as if the file doesn't exist, and, if generate
509 * is set, replace the empty file in curve25519_keypair_write_to_file() */
513 if (!have_lockfile()) {
514 if (try_locking(get_options(), 0)<0) {
515 /* Make sure that --list-fingerprint only creates new keys
516 * if there is no possibility for a deadlock. */
517 tor_log(severity
, LD_FS
, "Another Tor process has locked \"%s\". "
518 "Not writing any new keys.", fname
);
519 /*XXXX The 'other process' might make a key in a second or two;
520 * maybe we should wait for it. */
524 log_info(LD_GENERAL
, "No key found in \"%s\"; generating fresh key.",
526 if (curve25519_keypair_generate(keys_out
, 1) < 0)
528 if (curve25519_keypair_write_to_file(keys_out
, fname
, tag
)<0) {
529 tor_log(severity
, LD_FS
,
530 "Couldn't write generated key to \"%s\".", fname
);
531 memwipe(keys_out
, 0, sizeof(*keys_out
));
535 log_info(LD_GENERAL
, "No key found in \"%s\"", fname
);
541 if (curve25519_keypair_read_from_file(keys_out
, &tag_in
, fname
) < 0) {
542 tor_log(severity
, LD_GENERAL
,"Error loading private key.");
546 if (!tag_in
|| strcmp(tag_in
, tag
)) {
547 tor_log(severity
, LD_GENERAL
,"Unexpected tag %s on private key.",
563 /** Try to load the vote-signing private key and certificate for being a v3
564 * directory authority, and make sure they match. If <b>legacy</b>, load a
565 * legacy key/cert set for emergency key migration; otherwise load the regular
566 * key/cert set. On success, store them into *<b>key_out</b> and
567 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
569 load_authority_keyset(int legacy
, crypto_pk_t
**key_out
,
570 authority_cert_t
**cert_out
)
573 char *fname
= NULL
, *cert
= NULL
;
574 const char *eos
= NULL
;
575 crypto_pk_t
*signing_key
= NULL
;
576 authority_cert_t
*parsed
= NULL
;
578 fname
= get_datadir_fname2("keys",
579 legacy
? "legacy_signing_key" : "authority_signing_key");
580 signing_key
= init_key_from_file(fname
, 0, LOG_ERR
, 0);
582 log_warn(LD_DIR
, "No version 3 directory key found in %s", fname
);
586 fname
= get_datadir_fname2("keys",
587 legacy
? "legacy_certificate" : "authority_certificate");
588 cert
= read_file_to_str(fname
, 0, NULL
);
590 log_warn(LD_DIR
, "Signing key found, but no certificate found in %s",
594 parsed
= authority_cert_parse_from_string(cert
, &eos
);
596 log_warn(LD_DIR
, "Unable to parse certificate in %s", fname
);
599 if (!crypto_pk_eq_keys(signing_key
, parsed
->signing_key
)) {
600 log_warn(LD_DIR
, "Stored signing key does not match signing key in "
605 crypto_pk_free(*key_out
);
606 authority_cert_free(*cert_out
);
608 *key_out
= signing_key
;
617 crypto_pk_free(signing_key
);
618 authority_cert_free(parsed
);
622 /** Load the v3 (voting) authority signing key and certificate, if they are
623 * present. Return -1 if anything is missing, mismatched, or unloadable;
624 * return 0 on success. */
626 init_v3_authority_keys(void)
628 if (load_authority_keyset(0, &authority_signing_key
,
629 &authority_key_certificate
)<0)
632 if (get_options()->V3AuthUseLegacyKey
&&
633 load_authority_keyset(1, &legacy_signing_key
,
634 &legacy_key_certificate
)<0)
640 /** If we're a v3 authority, check whether we have a certificate that's
641 * likely to expire soon. Warn if we do, but not too often. */
643 v3_authority_check_key_expiry(void)
646 static time_t last_warned
= 0;
647 int badness
, time_left
, warn_interval
;
648 if (!authdir_mode_v3(get_options()) || !authority_key_certificate
)
652 expires
= authority_key_certificate
->expires
;
653 time_left
= (int)( expires
- now
);
654 if (time_left
<= 0) {
656 warn_interval
= 60*60;
657 } else if (time_left
<= 24*60*60) {
659 warn_interval
= 60*60;
660 } else if (time_left
<= 24*60*60*7) {
662 warn_interval
= 24*60*60;
663 } else if (time_left
<= 24*60*60*30) {
665 warn_interval
= 24*60*60*5;
670 if (last_warned
+ warn_interval
> now
)
673 if (time_left
<= 0) {
674 tor_log(badness
, LD_DIR
, "Your v3 authority certificate has expired."
675 " Generate a new one NOW.");
676 } else if (time_left
<= 24*60*60) {
677 tor_log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d "
678 "hours; Generate a new one NOW.", time_left
/(60*60));
680 tor_log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d "
681 "days; Generate a new one soon.", time_left
/(24*60*60));
686 /** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
687 * on success, and -1 on failure. */
689 router_initialize_tls_context(void)
691 unsigned int flags
= 0;
692 const or_options_t
*options
= get_options();
693 int lifetime
= options
->SSLKeyLifetime
;
694 if (public_server_mode(options
))
695 flags
|= TOR_TLS_CTX_IS_PUBLIC_SERVER
;
696 if (options
->TLSECGroup
) {
697 if (!strcasecmp(options
->TLSECGroup
, "P256"))
698 flags
|= TOR_TLS_CTX_USE_ECDHE_P256
;
699 else if (!strcasecmp(options
->TLSECGroup
, "P224"))
700 flags
|= TOR_TLS_CTX_USE_ECDHE_P224
;
702 if (!lifetime
) { /* we should guess a good ssl cert lifetime */
704 /* choose between 5 and 365 days, and round to the day */
705 unsigned int five_days
= 5*24*3600;
706 unsigned int one_year
= 365*24*3600;
707 lifetime
= crypto_rand_int_range(five_days
, one_year
);
708 lifetime
-= lifetime
% (24*3600);
710 if (crypto_rand_int(2)) {
711 /* Half the time we expire at midnight, and half the time we expire
712 * one second before midnight. (Some CAs wobble their expiry times a
713 * bit in practice, perhaps to reduce collision attacks; see ticket
714 * 8443 for details about observed certs in the wild.) */
719 /* It's ok to pass lifetime in as an unsigned int, since
720 * config_parse_interval() checked it. */
721 return tor_tls_context_init(flags
,
722 get_tlsclient_identity_key(),
723 server_mode(options
) ?
724 get_server_identity_key() : NULL
,
725 (unsigned int)lifetime
);
728 /** Compute fingerprint (or hashed fingerprint if hashed is 1) and write
729 * it to 'fingerprint' (or 'hashed-fingerprint'). Return 0 on success, or
730 * -1 if Tor should die,
733 router_write_fingerprint(int hashed
)
735 char *keydir
= NULL
, *cp
= NULL
;
736 const char *fname
= hashed
? "hashed-fingerprint" :
738 char fingerprint
[FINGERPRINT_LEN
+1];
739 const or_options_t
*options
= get_options();
740 char *fingerprint_line
= NULL
;
743 keydir
= get_datadir_fname(fname
);
744 log_info(LD_GENERAL
,"Dumping %sfingerprint to \"%s\"...",
745 hashed
? "hashed " : "", keydir
);
747 if (crypto_pk_get_fingerprint(get_server_identity_key(),
748 fingerprint
, 0) < 0) {
749 log_err(LD_GENERAL
,"Error computing fingerprint");
753 if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
755 log_err(LD_GENERAL
,"Error computing hashed fingerprint");
760 tor_asprintf(&fingerprint_line
, "%s %s\n", options
->Nickname
, fingerprint
);
762 /* Check whether we need to write the (hashed-)fingerprint file. */
764 cp
= read_file_to_str(keydir
, RFTS_IGNORE_MISSING
, NULL
);
765 if (!cp
|| strcmp(cp
, fingerprint_line
)) {
766 if (write_str_to_file(keydir
, fingerprint_line
, 0)) {
767 log_err(LD_FS
, "Error writing %sfingerprint line to file",
768 hashed
? "hashed " : "");
773 log_notice(LD_GENERAL
, "Your Tor %s identity key fingerprint is '%s %s'",
774 hashed
? "bridge's hashed" : "server's", options
->Nickname
,
781 tor_free(fingerprint_line
);
786 init_keys_common(void)
789 key_lock
= tor_mutex_new();
791 /* There are a couple of paths that put us here before we've asked
792 * openssl to initialize itself. */
793 if (crypto_global_init(get_options()->HardwareAccel
,
794 get_options()->AccelName
,
795 get_options()->AccelDir
)) {
796 log_err(LD_BUG
, "Unable to initialize OpenSSL. Exiting.");
804 init_keys_client(void)
807 if (init_keys_common() < 0)
810 if (!(prkey
= crypto_pk_new()))
812 if (crypto_pk_generate_key(prkey
)) {
813 crypto_pk_free(prkey
);
816 set_client_identity_key(prkey
);
817 /* Create a TLS context. */
818 if (router_initialize_tls_context() < 0) {
819 log_err(LD_GENERAL
,"Error creating TLS context for Tor client.");
825 /** Initialize all OR private keys, and the TLS context, as necessary.
826 * On OPs, this only initializes the tls context. Return 0 on success,
827 * or -1 if Tor should die.
835 char digest
[DIGEST_LEN
];
836 char v3_digest
[DIGEST_LEN
];
837 const or_options_t
*options
= get_options();
839 time_t now
= time(NULL
);
841 int v3_digest_set
= 0;
842 authority_cert_t
*cert
= NULL
;
844 /* OP's don't need persistent keys; just make up an identity and
845 * initialize the TLS context. */
846 if (!server_mode(options
)) {
847 return init_keys_client();
849 if (init_keys_common() < 0)
851 /* Make sure DataDirectory exists, and is private. */
852 cpd_check_t cpd_opts
= CPD_CREATE
;
853 if (options
->DataDirectoryGroupReadable
)
854 cpd_opts
|= CPD_GROUP_READ
;
855 if (check_private_dir(options
->DataDirectory
, cpd_opts
, options
->User
)) {
856 log_err(LD_OR
, "Can't create/check datadirectory %s",
857 options
->DataDirectory
);
860 /* Check the key directory. */
861 keydir
= get_datadir_fname("keys");
862 if (check_private_dir(keydir
, CPD_CREATE
, options
->User
)) {
868 /* 1a. Read v3 directory authority key/cert information. */
869 memset(v3_digest
, 0, sizeof(v3_digest
));
870 if (authdir_mode_v3(options
)) {
871 if (init_v3_authority_keys()<0) {
872 log_err(LD_GENERAL
, "We're configured as a V3 authority, but we "
873 "were unable to load our v3 authority keys and certificate! "
874 "Use tor-gencert to generate them. Dying.");
877 cert
= get_my_v3_authority_cert();
879 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key
,
885 /* 1b. Read identity key. Make it if none is found. */
886 keydir
= get_datadir_fname2("keys", "secret_id_key");
887 log_info(LD_GENERAL
,"Reading/making identity key \"%s\"...",keydir
);
888 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
, 1);
890 if (!prkey
) return -1;
891 set_server_identity_key(prkey
);
893 /* 1c. If we are configured as a bridge, generate a client key;
894 * otherwise, set the server identity key as our client identity
896 if (public_server_mode(options
)) {
897 set_client_identity_key(crypto_pk_dup_key(prkey
)); /* set above */
899 if (!(prkey
= crypto_pk_new()))
901 if (crypto_pk_generate_key(prkey
)) {
902 crypto_pk_free(prkey
);
905 set_client_identity_key(prkey
);
908 /* 1d. Load all ed25519 keys */
909 const int new_signing_key
= load_ed_keys(options
,now
);
910 if (new_signing_key
< 0)
913 /* 2. Read onion key. Make it if none is found. */
914 keydir
= get_datadir_fname2("keys", "secret_onion_key");
915 log_info(LD_GENERAL
,"Reading/making onion key \"%s\"...",keydir
);
916 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
, 1);
918 if (!prkey
) return -1;
919 set_onion_key(prkey
);
920 if (options
->command
== CMD_RUN_TOR
) {
921 /* only mess with the state file if we're actually running Tor */
922 or_state_t
*state
= get_or_state();
923 if (state
->LastRotatedOnionKey
> 100 && state
->LastRotatedOnionKey
< now
) {
924 /* We allow for some parsing slop, but we don't want to risk accepting
925 * values in the distant future. If we did, we might never rotate the
927 onionkey_set_at
= state
->LastRotatedOnionKey
;
929 /* We have no LastRotatedOnionKey set; either we just created the key
930 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
931 * start the clock ticking now so that we will eventually rotate it even
932 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
933 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
934 or_state_mark_dirty(state
, options
->AvoidDiskWrites
?
935 time(NULL
)+3600 : 0);
939 keydir
= get_datadir_fname2("keys", "secret_onion_key.old");
940 if (!lastonionkey
&& file_status(keydir
) == FN_FILE
) {
941 /* Load keys from non-empty files only.
942 * Missing old keys won't be replaced with freshly generated keys. */
943 prkey
= init_key_from_file(keydir
, 0, LOG_ERR
, 0);
945 lastonionkey
= prkey
;
950 /* 2b. Load curve25519 onion keys. */
952 keydir
= get_datadir_fname2("keys", "secret_onion_key_ntor");
953 r
= init_curve25519_keypair_from_file(&curve25519_onion_key
,
954 keydir
, 1, LOG_ERR
, "onion");
959 keydir
= get_datadir_fname2("keys", "secret_onion_key_ntor.old");
960 if (tor_mem_is_zero((const char *)
961 last_curve25519_onion_key
.pubkey
.public_key
,
962 CURVE25519_PUBKEY_LEN
) &&
963 file_status(keydir
) == FN_FILE
) {
964 /* Load keys from non-empty files only.
965 * Missing old keys won't be replaced with freshly generated keys. */
966 init_curve25519_keypair_from_file(&last_curve25519_onion_key
,
967 keydir
, 0, LOG_ERR
, "onion");
972 /* 3. Initialize link key and TLS context. */
973 if (router_initialize_tls_context() < 0) {
974 log_err(LD_GENERAL
,"Error initializing TLS context");
978 /* 3b. Get an ed25519 link certificate. Note that we need to do this
979 * after we set up the TLS context */
980 if (generate_ed_link_cert(options
, now
, new_signing_key
> 0) < 0) {
981 log_err(LD_GENERAL
,"Couldn't make link cert");
985 /* 4. Build our router descriptor. */
986 /* Must be called after keys are initialized. */
987 mydesc
= router_get_my_descriptor();
988 if (authdir_mode_handles_descs(options
, ROUTER_PURPOSE_GENERAL
)) {
989 const char *m
= NULL
;
991 /* We need to add our own fingerprint so it gets recognized. */
992 if (dirserv_add_own_fingerprint(get_server_identity_key())) {
993 log_err(LD_GENERAL
,"Error adding own fingerprint to set of relays");
997 was_router_added_t added
;
998 ri
= router_parse_entry_from_string(mydesc
, NULL
, 1, 0, NULL
, NULL
);
1000 log_err(LD_GENERAL
,"Generated a routerinfo we couldn't parse.");
1003 added
= dirserv_add_descriptor(ri
, &m
, "self");
1004 if (!WRA_WAS_ADDED(added
)) {
1005 if (!WRA_WAS_OUTDATED(added
)) {
1006 log_err(LD_GENERAL
, "Unable to add own descriptor to directory: %s",
1007 m
?m
:"<unknown error>");
1010 /* If the descriptor was outdated, that's ok. This can happen
1011 * when some config options are toggled that affect workers, but
1012 * we don't really need new keys yet so the descriptor doesn't
1013 * change and the old one is still fresh. */
1014 log_info(LD_GENERAL
, "Couldn't add own descriptor to directory "
1015 "after key init: %s This is usually not a problem.",
1016 m
?m
:"<unknown error>");
1022 /* 5. Dump fingerprint and possibly hashed fingerprint to files. */
1023 if (router_write_fingerprint(0)) {
1024 log_err(LD_FS
, "Error writing fingerprint to file");
1027 if (!public_server_mode(options
) && router_write_fingerprint(1)) {
1028 log_err(LD_FS
, "Error writing hashed fingerprint to file");
1032 if (!authdir_mode(options
))
1034 /* 6. [authdirserver only] load approved-routers file */
1035 if (dirserv_load_fingerprint_file() < 0) {
1036 log_err(LD_GENERAL
,"Error loading fingerprints");
1039 /* 6b. [authdirserver only] add own key to approved directories. */
1040 crypto_pk_get_digest(get_server_identity_key(), digest
);
1041 type
= ((options
->V3AuthoritativeDir
?
1042 (V3_DIRINFO
|MICRODESC_DIRINFO
|EXTRAINFO_DIRINFO
) : NO_DIRINFO
) |
1043 (options
->BridgeAuthoritativeDir
? BRIDGE_DIRINFO
: NO_DIRINFO
));
1045 ds
= router_get_trusteddirserver_by_digest(digest
);
1047 ds
= trusted_dir_server_new(options
->Nickname
, NULL
,
1048 router_get_advertised_dir_port(options
, 0),
1049 router_get_advertised_or_port(options
),
1055 log_err(LD_GENERAL
,"We want to be a directory authority, but we "
1056 "couldn't add ourselves to the authority list. Failing.");
1061 if (ds
->type
!= type
) {
1062 log_warn(LD_DIR
, "Configured authority type does not match authority "
1063 "type in DirAuthority list. Adjusting. (%d v %d)",
1067 if (v3_digest_set
&& (ds
->type
& V3_DIRINFO
) &&
1068 tor_memneq(v3_digest
, ds
->v3_identity_digest
, DIGEST_LEN
)) {
1069 log_warn(LD_DIR
, "V3 identity key does not match identity declared in "
1070 "DirAuthority line. Adjusting.");
1071 memcpy(ds
->v3_identity_digest
, v3_digest
, DIGEST_LEN
);
1074 if (cert
) { /* add my own cert to the list of known certs */
1075 log_info(LD_DIR
, "adding my own v3 cert");
1076 if (trusted_dirs_load_certs_from_string(
1077 cert
->cache_info
.signed_descriptor_body
,
1078 TRUSTED_DIRS_CERTS_SRC_SELF
, 0,
1080 log_warn(LD_DIR
, "Unable to parse my own v3 cert! Failing.");
1085 return 0; /* success */
1088 /* Keep track of whether we should upload our server descriptor,
1089 * and what type of server we are.
1092 /** Whether we can reach our ORPort from the outside. */
1093 static int can_reach_or_port
= 0;
1094 /** Whether we can reach our DirPort from the outside. */
1095 static int can_reach_dir_port
= 0;
1097 /** Forget what we have learned about our reachability status. */
1099 router_reset_reachability(void)
1101 can_reach_or_port
= can_reach_dir_port
= 0;
1104 /** Return 1 if we won't do reachability checks, because:
1105 * - AssumeReachable is set, or
1106 * - the network is disabled.
1107 * Otherwise, return 0.
1110 router_reachability_checks_disabled(const or_options_t
*options
)
1112 return options
->AssumeReachable
||
1116 /** Return 0 if we need to do an ORPort reachability check, because:
1117 * - no reachability check has been done yet, or
1118 * - we've initiated reachability checks, but none have succeeded.
1119 * Return 1 if we don't need to do an ORPort reachability check, because:
1120 * - we've seen a successful reachability check, or
1121 * - AssumeReachable is set, or
1122 * - the network is disabled.
1125 check_whether_orport_reachable(const or_options_t
*options
)
1127 int reach_checks_disabled
= router_reachability_checks_disabled(options
);
1128 return reach_checks_disabled
||
1132 /** Return 0 if we need to do a DirPort reachability check, because:
1133 * - no reachability check has been done yet, or
1134 * - we've initiated reachability checks, but none have succeeded.
1135 * Return 1 if we don't need to do a DirPort reachability check, because:
1136 * - we've seen a successful reachability check, or
1137 * - there is no DirPort set, or
1138 * - AssumeReachable is set, or
1139 * - the network is disabled.
1142 check_whether_dirport_reachable(const or_options_t
*options
)
1144 int reach_checks_disabled
= router_reachability_checks_disabled(options
) ||
1145 !options
->DirPort_set
;
1146 return reach_checks_disabled
||
1150 /** The lower threshold of remaining bandwidth required to advertise (or
1151 * automatically provide) directory services */
1152 /* XXX Should this be increased? */
1153 #define MIN_BW_TO_ADVERTISE_DIRSERVER 51200
1155 /** Return true iff we have enough configured bandwidth to cache directory
1158 router_has_bandwidth_to_be_dirserver(const or_options_t
*options
)
1160 if (options
->BandwidthRate
< MIN_BW_TO_ADVERTISE_DIRSERVER
) {
1163 if (options
->RelayBandwidthRate
> 0 &&
1164 options
->RelayBandwidthRate
< MIN_BW_TO_ADVERTISE_DIRSERVER
) {
1170 /** Helper: Return 1 if we have sufficient resources for serving directory
1171 * requests, return 0 otherwise.
1172 * dir_port is either 0 or the configured DirPort number.
1173 * If AccountingMax is set less than our advertised bandwidth, then don't
1174 * serve requests. Likewise, if our advertised bandwidth is less than
1175 * MIN_BW_TO_ADVERTISE_DIRSERVER, don't bother trying to serve requests.
1178 router_should_be_directory_server(const or_options_t
*options
, int dir_port
)
1180 static int advertising
=1; /* start out assuming we will advertise */
1182 const char *reason
= NULL
;
1184 if (accounting_is_enabled(options
) &&
1185 get_options()->AccountingRule
!= ACCT_IN
) {
1186 /* Don't spend bytes for directory traffic if we could end up hibernating,
1187 * but allow DirPort otherwise. Some relay operators set AccountingMax
1188 * because they're confused or to get statistics. Directory traffic has a
1189 * much larger effect on output than input so there is no reason to turn it
1190 * off if using AccountingRule in. */
1191 int interval_length
= accounting_get_interval_length();
1192 uint32_t effective_bw
= get_effective_bwrate(options
);
1194 if (!interval_length
) {
1195 log_warn(LD_BUG
, "An accounting interval is not allowed to be zero "
1196 "seconds long. Raising to 1.");
1197 interval_length
= 1;
1199 log_info(LD_GENERAL
, "Calculating whether to advertise %s: effective "
1200 "bwrate: %u, AccountingMax: "U64_FORMAT
", "
1201 "accounting interval length %d",
1202 dir_port
? "dirport" : "begindir",
1203 effective_bw
, U64_PRINTF_ARG(options
->AccountingMax
),
1206 acc_bytes
= options
->AccountingMax
;
1207 if (get_options()->AccountingRule
== ACCT_SUM
)
1210 acc_bytes
/ interval_length
) {
1212 reason
= "AccountingMax enabled";
1214 } else if (! router_has_bandwidth_to_be_dirserver(options
)) {
1215 /* if we're advertising a small amount */
1217 reason
= "BandwidthRate under 50KB";
1220 if (advertising
!= new_choice
) {
1221 if (new_choice
== 1) {
1223 log_notice(LD_DIR
, "Advertising DirPort as %d", dir_port
);
1225 log_notice(LD_DIR
, "Advertising directory service support");
1228 log_notice(LD_DIR
, "Not advertising Dir%s (Reason: %s)",
1229 dir_port
? "Port" : "ectory Service support", reason
);
1231 advertising
= new_choice
;
1237 /** Return 1 if we are configured to accept either relay or directory requests
1238 * from clients and we aren't at risk of exceeding our bandwidth limits, thus
1239 * we should be a directory server. If not, return 0.
1242 dir_server_mode(const or_options_t
*options
)
1244 if (!options
->DirCache
)
1246 return options
->DirPort_set
||
1247 (server_mode(options
) && router_has_bandwidth_to_be_dirserver(options
));
1250 /** Look at a variety of factors, and return 0 if we don't want to
1251 * advertise the fact that we have a DirPort open or begindir support, else
1254 * Where dir_port or supports_tunnelled_dir_requests are not relevant, they
1257 * Log a helpful message if we change our mind about whether to publish.
1260 decide_to_advertise_dir_impl(const or_options_t
*options
,
1262 int supports_tunnelled_dir_requests
)
1264 /* Part one: reasons to publish or not publish that aren't
1265 * worth mentioning to the user, either because they're obvious
1266 * or because they're normal behavior. */
1268 /* short circuit the rest of the function */
1269 if (!dir_port
&& !supports_tunnelled_dir_requests
)
1271 if (authdir_mode(options
)) /* always publish */
1273 if (net_is_disabled())
1275 if (dir_port
&& !router_get_advertised_dir_port(options
, dir_port
))
1277 if (supports_tunnelled_dir_requests
&&
1278 !router_get_advertised_or_port(options
))
1281 /* Part two: consider config options that could make us choose to
1282 * publish or not publish that the user might find surprising. */
1283 return router_should_be_directory_server(options
, dir_port
);
1286 /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
1287 * advertise the fact that we have a DirPort open, else return the
1288 * DirPort we want to advertise.
1291 decide_to_advertise_dirport(const or_options_t
*options
, uint16_t dir_port
)
1293 /* supports_tunnelled_dir_requests is not relevant, pass 0 */
1294 return decide_to_advertise_dir_impl(options
, dir_port
, 0) ? dir_port
: 0;
1297 /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
1298 * advertise the fact that we support begindir requests, else return 1.
1301 decide_to_advertise_begindir(const or_options_t
*options
,
1302 int supports_tunnelled_dir_requests
)
1304 /* dir_port is not relevant, pass 0 */
1305 return decide_to_advertise_dir_impl(options
, 0,
1306 supports_tunnelled_dir_requests
);
1309 /** Allocate and return a new extend_info_t that can be used to build
1310 * a circuit to or through the router <b>r</b>. Uses the primary
1311 * address of the router, so should only be called on a server. */
1312 static extend_info_t
*
1313 extend_info_from_router(const routerinfo_t
*r
)
1318 /* Make sure we don't need to check address reachability */
1319 tor_assert_nonfatal(router_skip_or_reachability(get_options(), 0));
1321 const ed25519_public_key_t
*ed_id_key
;
1322 if (r
->cache_info
.signing_key_cert
)
1323 ed_id_key
= &r
->cache_info
.signing_key_cert
->signing_key
;
1327 router_get_prim_orport(r
, &ap
);
1328 return extend_info_new(r
->nickname
, r
->cache_info
.identity_digest
,
1330 r
->onion_pkey
, r
->onion_curve25519_pkey
,
1334 /** Some time has passed, or we just got new directory information.
1335 * See if we currently believe our ORPort or DirPort to be
1336 * unreachable. If so, launch a new test for it.
1338 * For ORPort, we simply try making a circuit that ends at ourselves.
1339 * Success is noticed in onionskin_answer().
1341 * For DirPort, we make a connection via Tor to our DirPort and ask
1342 * for our own server descriptor.
1343 * Success is noticed in connection_dir_client_reached_eof().
1346 consider_testing_reachability(int test_or
, int test_dir
)
1348 const routerinfo_t
*me
= router_get_my_routerinfo();
1349 const or_options_t
*options
= get_options();
1350 int orport_reachable
= check_whether_orport_reachable(options
);
1355 if (routerset_contains_router(options
->ExcludeNodes
, me
, -1) &&
1356 options
->StrictNodes
) {
1357 /* If we've excluded ourself, and StrictNodes is set, we can't test
1359 if (test_or
|| test_dir
) {
1360 #define SELF_EXCLUDED_WARN_INTERVAL 3600
1361 static ratelim_t warning_limit
=RATELIM_INIT(SELF_EXCLUDED_WARN_INTERVAL
);
1362 log_fn_ratelim(&warning_limit
, LOG_WARN
, LD_CIRC
,
1363 "Can't peform self-tests for this relay: we have "
1364 "listed ourself in ExcludeNodes, and StrictNodes is set. "
1365 "We cannot learn whether we are usable, and will not "
1366 "be able to advertise ourself.");
1371 if (test_or
&& (!orport_reachable
|| !circuit_enough_testing_circs())) {
1372 extend_info_t
*ei
= extend_info_from_router(me
);
1373 /* XXX IPv6 self testing */
1374 log_info(LD_CIRC
, "Testing %s of my ORPort: %s:%d.",
1375 !orport_reachable
? "reachability" : "bandwidth",
1376 fmt_addr32(me
->addr
), me
->or_port
);
1377 circuit_launch_by_extend_info(CIRCUIT_PURPOSE_TESTING
, ei
,
1378 CIRCLAUNCH_NEED_CAPACITY
|CIRCLAUNCH_IS_INTERNAL
);
1379 extend_info_free(ei
);
1382 /* XXX IPv6 self testing */
1383 tor_addr_from_ipv4h(&addr
, me
->addr
);
1384 if (test_dir
&& !check_whether_dirport_reachable(options
) &&
1385 !connection_get_by_type_addr_port_purpose(
1386 CONN_TYPE_DIR
, &addr
, me
->dir_port
,
1387 DIR_PURPOSE_FETCH_SERVERDESC
)) {
1388 /* ask myself, via tor, for my server descriptor. */
1389 directory_initiate_command(&addr
, me
->or_port
,
1390 &addr
, me
->dir_port
,
1391 me
->cache_info
.identity_digest
,
1392 DIR_PURPOSE_FETCH_SERVERDESC
,
1393 ROUTER_PURPOSE_GENERAL
,
1394 DIRIND_ANON_DIRPORT
, "authority.z",
1399 /** Annotate that we found our ORPort reachable. */
1401 router_orport_found_reachable(void)
1403 const routerinfo_t
*me
= router_get_my_routerinfo();
1404 const or_options_t
*options
= get_options();
1405 if (!can_reach_or_port
&& me
) {
1406 char *address
= tor_dup_ip(me
->addr
);
1407 log_notice(LD_OR
,"Self-testing indicates your ORPort is reachable from "
1408 "the outside. Excellent.%s",
1409 options
->PublishServerDescriptor_
!= NO_DIRINFO
1410 && check_whether_dirport_reachable(options
) ?
1411 " Publishing server descriptor." : "");
1412 can_reach_or_port
= 1;
1413 mark_my_descriptor_dirty("ORPort found reachable");
1414 /* This is a significant enough change to upload immediately,
1415 * at least in a test network */
1416 if (options
->TestingTorNetwork
== 1) {
1417 reschedule_descriptor_update_check();
1419 control_event_server_status(LOG_NOTICE
,
1420 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
1421 address
, me
->or_port
);
1426 /** Annotate that we found our DirPort reachable. */
1428 router_dirport_found_reachable(void)
1430 const routerinfo_t
*me
= router_get_my_routerinfo();
1431 const or_options_t
*options
= get_options();
1432 if (!can_reach_dir_port
&& me
) {
1433 char *address
= tor_dup_ip(me
->addr
);
1434 log_notice(LD_DIRSERV
,"Self-testing indicates your DirPort is reachable "
1435 "from the outside. Excellent.%s",
1436 options
->PublishServerDescriptor_
!= NO_DIRINFO
1437 && check_whether_orport_reachable(options
) ?
1438 " Publishing server descriptor." : "");
1439 can_reach_dir_port
= 1;
1440 if (decide_to_advertise_dirport(options
, me
->dir_port
)) {
1441 mark_my_descriptor_dirty("DirPort found reachable");
1442 /* This is a significant enough change to upload immediately,
1443 * at least in a test network */
1444 if (options
->TestingTorNetwork
== 1) {
1445 reschedule_descriptor_update_check();
1448 control_event_server_status(LOG_NOTICE
,
1449 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
1450 address
, me
->dir_port
);
1455 /** We have enough testing circuits open. Send a bunch of "drop"
1456 * cells down each of them, to exercise our bandwidth. */
1458 router_perform_bandwidth_test(int num_circs
, time_t now
)
1460 int num_cells
= (int)(get_options()->BandwidthRate
* 10 /
1461 CELL_MAX_NETWORK_SIZE
);
1462 int max_cells
= num_cells
< CIRCWINDOW_START
?
1463 num_cells
: CIRCWINDOW_START
;
1464 int cells_per_circuit
= max_cells
/ num_circs
;
1465 origin_circuit_t
*circ
= NULL
;
1467 log_notice(LD_OR
,"Performing bandwidth self-test...done.");
1468 while ((circ
= circuit_get_next_by_pk_and_purpose(circ
, NULL
,
1469 CIRCUIT_PURPOSE_TESTING
))) {
1470 /* dump cells_per_circuit drop cells onto this circ */
1471 int i
= cells_per_circuit
;
1472 if (circ
->base_
.state
!= CIRCUIT_STATE_OPEN
)
1474 circ
->base_
.timestamp_dirty
= now
;
1476 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
1478 NULL
, 0, circ
->cpath
->prev
)<0) {
1479 return; /* stop if error */
1485 /** Return true iff our network is in some sense disabled: either we're
1486 * hibernating, entering hibernation, or the network is turned off with
1487 * DisableNetwork. */
1489 net_is_disabled(void)
1491 return get_options()->DisableNetwork
|| we_are_hibernating();
1494 /** Return true iff we believe ourselves to be an authoritative
1498 authdir_mode(const or_options_t
*options
)
1500 return options
->AuthoritativeDir
!= 0;
1502 /** Return true iff we believe ourselves to be a v3 authoritative
1506 authdir_mode_v3(const or_options_t
*options
)
1508 return authdir_mode(options
) && options
->V3AuthoritativeDir
!= 0;
1510 /** Return true iff we are a v3 directory authority. */
1512 authdir_mode_any_main(const or_options_t
*options
)
1514 return options
->V3AuthoritativeDir
;
1516 /** Return true if we believe ourselves to be any kind of
1517 * authoritative directory beyond just a hidserv authority. */
1519 authdir_mode_any_nonhidserv(const or_options_t
*options
)
1521 return options
->BridgeAuthoritativeDir
||
1522 authdir_mode_any_main(options
);
1524 /** Return true iff we are an authoritative directory server that is
1525 * authoritative about receiving and serving descriptors of type
1526 * <b>purpose</b> on its dirport. Use -1 for "any purpose". */
1528 authdir_mode_handles_descs(const or_options_t
*options
, int purpose
)
1531 return authdir_mode_any_nonhidserv(options
);
1532 else if (purpose
== ROUTER_PURPOSE_GENERAL
)
1533 return authdir_mode_any_main(options
);
1534 else if (purpose
== ROUTER_PURPOSE_BRIDGE
)
1535 return (options
->BridgeAuthoritativeDir
);
1539 /** Return true iff we are an authoritative directory server that
1540 * publishes its own network statuses.
1543 authdir_mode_publishes_statuses(const or_options_t
*options
)
1545 if (authdir_mode_bridge(options
))
1547 return authdir_mode_any_nonhidserv(options
);
1549 /** Return true iff we are an authoritative directory server that
1550 * tests reachability of the descriptors it learns about.
1553 authdir_mode_tests_reachability(const or_options_t
*options
)
1555 return authdir_mode_handles_descs(options
, -1);
1557 /** Return true iff we believe ourselves to be a bridge authoritative
1561 authdir_mode_bridge(const or_options_t
*options
)
1563 return authdir_mode(options
) && options
->BridgeAuthoritativeDir
!= 0;
1566 /** Return true iff we are trying to be a server.
1569 server_mode
,(const or_options_t
*options
))
1571 if (options
->ClientOnly
) return 0;
1572 /* XXXX I believe we can kill off ORListenAddress here.*/
1573 return (options
->ORPort_set
|| options
->ORListenAddress
);
1576 /** Return true iff we are trying to be a non-bridge server.
1579 public_server_mode
,(const or_options_t
*options
))
1581 if (!server_mode(options
)) return 0;
1582 return (!options
->BridgeRelay
);
1585 /** Return true iff the combination of options in <b>options</b> and parameters
1586 * in the consensus mean that we don't want to allow exits from circuits
1587 * we got from addresses not known to be servers. */
1589 should_refuse_unknown_exits(const or_options_t
*options
)
1591 if (options
->RefuseUnknownExits
!= -1) {
1592 return options
->RefuseUnknownExits
;
1594 return networkstatus_get_param(NULL
, "refuseunknownexits", 1, 0, 1);
1598 /** Remember if we've advertised ourselves to the dirservers. */
1599 static int server_is_advertised
=0;
1601 /** Return true iff we have published our descriptor lately.
1604 advertised_server_mode
,(void))
1606 return server_is_advertised
;
1610 * Called with a boolean: set whether we have recently published our
1614 set_server_advertised(int s
)
1616 server_is_advertised
= s
;
1619 /** Return true iff we are trying to proxy client connections. */
1621 proxy_mode(const or_options_t
*options
)
1624 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t
*, p
) {
1625 if (p
->type
== CONN_TYPE_AP_LISTENER
||
1626 p
->type
== CONN_TYPE_AP_TRANS_LISTENER
||
1627 p
->type
== CONN_TYPE_AP_DNS_LISTENER
||
1628 p
->type
== CONN_TYPE_AP_NATD_LISTENER
)
1630 } SMARTLIST_FOREACH_END(p
);
1634 /** Decide if we're a publishable server. We are a publishable server if:
1635 * - We don't have the ClientOnly option set
1637 * - We have the PublishServerDescriptor option set to non-empty
1639 * - We have ORPort set
1641 * - We believe our ORPort and DirPort (if present) are reachable from
1643 * - We believe our ORPort is reachable from the outside, and we can't
1644 * check our DirPort because the consensus has no exits; or
1645 * - We are an authoritative directory server.
1648 decide_if_publishable_server(void)
1650 const or_options_t
*options
= get_options();
1652 if (options
->ClientOnly
)
1654 if (options
->PublishServerDescriptor_
== NO_DIRINFO
)
1656 if (!server_mode(options
))
1658 if (authdir_mode(options
))
1660 if (!router_get_advertised_or_port(options
))
1662 if (!check_whether_orport_reachable(options
))
1664 if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL
) {
1665 /* All set: there are no exits in the consensus (maybe this is a tiny
1666 * test network), so we can't check our DirPort reachability. */
1669 return check_whether_dirport_reachable(options
);
1673 /** Initiate server descriptor upload as reasonable (if server is publishable,
1674 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1676 * We need to rebuild the descriptor if it's dirty even if we're not
1677 * uploading, because our reachability testing *uses* our descriptor to
1678 * determine what IP address and ports to test.
1681 consider_publishable_server(int force
)
1685 if (!server_mode(get_options()))
1688 rebuilt
= router_rebuild_descriptor(0);
1689 if (decide_if_publishable_server()) {
1690 set_server_advertised(1);
1692 router_upload_dir_desc_to_dirservers(force
);
1694 set_server_advertised(0);
1698 /** Return the port of the first active listener of type
1699 * <b>listener_type</b>. */
1700 /** XXX not a very good interface. it's not reliable when there are
1701 multiple listeners. */
1703 router_get_active_listener_port_by_type_af(int listener_type
,
1706 /* Iterate all connections, find one of the right kind and return
1707 the port. Not very sophisticated or fast, but effective. */
1708 smartlist_t
*conns
= get_connection_array();
1709 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
1710 if (conn
->type
== listener_type
&& !conn
->marked_for_close
&&
1711 conn
->socket_family
== family
) {
1714 } SMARTLIST_FOREACH_END(conn
);
1719 /** Return the port that we should advertise as our ORPort; this is either
1720 * the one configured in the ORPort option, or the one we actually bound to
1721 * if ORPort is "auto".
1724 router_get_advertised_or_port(const or_options_t
*options
)
1726 return router_get_advertised_or_port_by_af(options
, AF_INET
);
1729 /** As router_get_advertised_or_port(), but allows an address family argument.
1732 router_get_advertised_or_port_by_af(const or_options_t
*options
,
1735 int port
= get_first_advertised_port_by_type_af(CONN_TYPE_OR_LISTENER
,
1739 /* If the port is in 'auto' mode, we have to use
1740 router_get_listener_port_by_type(). */
1741 if (port
== CFG_AUTO_PORT
)
1742 return router_get_active_listener_port_by_type_af(CONN_TYPE_OR_LISTENER
,
1748 /** Return the port that we should advertise as our DirPort;
1749 * this is one of three possibilities:
1750 * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
1751 * the one configured in the DirPort option,
1752 * or the one we actually bound to if DirPort is "auto". */
1754 router_get_advertised_dir_port(const or_options_t
*options
, uint16_t dirport
)
1756 int dirport_configured
= get_primary_dir_port();
1759 if (!dirport_configured
)
1762 if (dirport_configured
== CFG_AUTO_PORT
)
1763 return router_get_active_listener_port_by_type_af(CONN_TYPE_DIR_LISTENER
,
1766 return dirport_configured
;
1770 * OR descriptor generation.
1773 /** My routerinfo. */
1774 static routerinfo_t
*desc_routerinfo
= NULL
;
1776 static extrainfo_t
*desc_extrainfo
= NULL
;
1777 /** Why did we most recently decide to regenerate our descriptor? Used to
1778 * tell the authorities why we're sending it to them. */
1779 static const char *desc_gen_reason
= NULL
;
1780 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1782 static time_t desc_clean_since
= 0;
1783 /** Why did we mark the descriptor dirty? */
1784 static const char *desc_dirty_reason
= NULL
;
1785 /** Boolean: do we need to regenerate the above? */
1786 static int desc_needs_upload
= 0;
1788 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1789 * descriptor successfully yet, try to upload our signed descriptor to
1790 * all the directory servers we know about.
1793 router_upload_dir_desc_to_dirservers(int force
)
1795 const routerinfo_t
*ri
;
1798 size_t desc_len
, extra_len
= 0, total_len
;
1799 dirinfo_type_t auth
= get_options()->PublishServerDescriptor_
;
1801 ri
= router_get_my_routerinfo();
1803 log_info(LD_GENERAL
, "No descriptor; skipping upload");
1806 ei
= router_get_my_extrainfo();
1807 if (auth
== NO_DIRINFO
)
1809 if (!force
&& !desc_needs_upload
)
1812 log_info(LD_OR
, "Uploading relay descriptor to directory authorities%s",
1813 force
? " (forced)" : "");
1815 desc_needs_upload
= 0;
1817 desc_len
= ri
->cache_info
.signed_descriptor_len
;
1818 extra_len
= ei
? ei
->cache_info
.signed_descriptor_len
: 0;
1819 total_len
= desc_len
+ extra_len
+ 1;
1820 msg
= tor_malloc(total_len
);
1821 memcpy(msg
, ri
->cache_info
.signed_descriptor_body
, desc_len
);
1823 memcpy(msg
+desc_len
, ei
->cache_info
.signed_descriptor_body
, extra_len
);
1825 msg
[desc_len
+extra_len
] = 0;
1827 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR
,
1828 (auth
& BRIDGE_DIRINFO
) ?
1829 ROUTER_PURPOSE_BRIDGE
:
1830 ROUTER_PURPOSE_GENERAL
,
1831 auth
, msg
, desc_len
, extra_len
);
1835 /** OR only: Check whether my exit policy says to allow connection to
1836 * conn. Return 0 if we accept; non-0 if we reject.
1839 router_compare_to_my_exit_policy(const tor_addr_t
*addr
, uint16_t port
)
1841 const routerinfo_t
*me
= router_get_my_routerinfo();
1842 if (!me
) /* make sure routerinfo exists */
1845 /* make sure it's resolved to something. this way we can't get a
1847 if (tor_addr_is_null(addr
))
1850 /* look at router_get_my_routerinfo()->exit_policy for both the v4 and the
1851 * v6 policies. The exit_policy field in router_get_my_routerinfo() is a
1852 * bit unusual, in that it contains IPv6 and IPv6 entries. We don't want to
1853 * look at router_get_my_routerinfo()->ipv6_exit_policy, since that's a port
1855 if ((tor_addr_family(addr
) == AF_INET
||
1856 tor_addr_family(addr
) == AF_INET6
)) {
1857 return compare_tor_addr_to_addr_policy(addr
, port
,
1858 me
->exit_policy
) != ADDR_POLICY_ACCEPTED
;
1860 } else if (tor_addr_family(addr
) == AF_INET6
) {
1861 return get_options()->IPv6Exit
&&
1862 desc_routerinfo
->ipv6_exit_policy
&&
1863 compare_tor_addr_to_short_policy(addr
, port
,
1864 me
->ipv6_exit_policy
) != ADDR_POLICY_ACCEPTED
;
1871 /** Return true iff my exit policy is reject *:*. Return -1 if we don't
1872 * have a descriptor */
1874 router_my_exit_policy_is_reject_star
,(void))
1876 if (!router_get_my_routerinfo()) /* make sure routerinfo exists */
1879 return router_get_my_routerinfo()->policy_is_reject_star
;
1882 /** Return true iff I'm a server and <b>digest</b> is equal to
1883 * my server identity key digest. */
1885 router_digest_is_me(const char *digest
)
1887 return (server_identitykey
&&
1888 tor_memeq(server_identitykey_digest
, digest
, DIGEST_LEN
));
1891 /** Return my identity digest. */
1893 router_get_my_id_digest(void)
1895 return (const uint8_t *)server_identitykey_digest
;
1898 /** Return true iff I'm a server and <b>digest</b> is equal to
1899 * my identity digest. */
1901 router_extrainfo_digest_is_me(const char *digest
)
1903 extrainfo_t
*ei
= router_get_my_extrainfo();
1907 return tor_memeq(digest
,
1908 ei
->cache_info
.signed_descriptor_digest
,
1912 /** A wrapper around router_digest_is_me(). */
1914 router_is_me(const routerinfo_t
*router
)
1916 return router_digest_is_me(router
->cache_info
.identity_digest
);
1919 /** Return a routerinfo for this OR, rebuilding a fresh one if
1920 * necessary. Return NULL on error, or if called on an OP. */
1921 MOCK_IMPL(const routerinfo_t
*,
1922 router_get_my_routerinfo
,(void))
1924 if (!server_mode(get_options()))
1926 if (router_rebuild_descriptor(0))
1928 return desc_routerinfo
;
1931 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1932 * one if necessary. Return NULL on error.
1935 router_get_my_descriptor(void)
1938 const routerinfo_t
*me
= router_get_my_routerinfo();
1941 tor_assert(me
->cache_info
.saved_location
== SAVED_NOWHERE
);
1942 body
= signed_descriptor_get_body(&me
->cache_info
);
1943 /* Make sure this is nul-terminated. */
1944 tor_assert(!body
[me
->cache_info
.signed_descriptor_len
]);
1945 log_debug(LD_GENERAL
,"my desc is '%s'", body
);
1949 /** Return the extrainfo document for this OR, or NULL if we have none.
1950 * Rebuilt it (and the server descriptor) if necessary. */
1952 router_get_my_extrainfo(void)
1954 if (!server_mode(get_options()))
1956 if (router_rebuild_descriptor(0))
1958 return desc_extrainfo
;
1961 /** Return a human-readable string describing what triggered us to generate
1962 * our current descriptor, or NULL if we don't know. */
1964 router_get_descriptor_gen_reason(void)
1966 return desc_gen_reason
;
1969 /** A list of nicknames that we've warned about including in our family
1970 * declaration verbatim rather than as digests. */
1971 static smartlist_t
*warned_nonexistent_family
= NULL
;
1973 static int router_guess_address_from_dir_headers(uint32_t *guess
);
1975 /** Make a current best guess at our address, either because
1976 * it's configured in torrc, or because we've learned it from
1977 * dirserver headers. Place the answer in *<b>addr</b> and return
1978 * 0 on success, else return -1 if we have no guess.
1980 * If <b>cache_only</b> is true, just return any cached answers, and
1981 * don't try to get any new answers.
1984 router_pick_published_address
,(const or_options_t
*options
, uint32_t *addr
,
1987 /* First, check the cached output from resolve_my_address(). */
1988 *addr
= get_last_resolved_addr();
1992 /* Second, consider doing a resolve attempt right here. */
1994 if (resolve_my_address(LOG_INFO
, options
, addr
, NULL
, NULL
) >= 0) {
1995 log_info(LD_CONFIG
,"Success: chose address '%s'.", fmt_addr32(*addr
));
2000 /* Third, check the cached output from router_new_address_suggestion(). */
2001 if (router_guess_address_from_dir_headers(addr
) >= 0)
2004 /* We have no useful cached answers. Return failure. */
2008 /* Like router_check_descriptor_address_consistency, but specifically for the
2009 * ORPort or DirPort.
2010 * listener_type is either CONN_TYPE_OR_LISTENER or CONN_TYPE_DIR_LISTENER. */
2012 router_check_descriptor_address_port_consistency(uint32_t ipv4h_desc_addr
,
2015 tor_assert(listener_type
== CONN_TYPE_OR_LISTENER
||
2016 listener_type
== CONN_TYPE_DIR_LISTENER
);
2018 /* The first advertised Port may be the magic constant CFG_AUTO_PORT.
2020 int port_v4_cfg
= get_first_advertised_port_by_type_af(listener_type
,
2022 if (port_v4_cfg
!= 0 &&
2023 !port_exists_by_type_addr32h_port(listener_type
,
2024 ipv4h_desc_addr
, port_v4_cfg
, 1)) {
2025 const tor_addr_t
*port_addr
= get_first_advertised_addr_by_type_af(
2028 /* If we're building a descriptor with no advertised address,
2029 * something is terribly wrong. */
2030 tor_assert(port_addr
);
2032 tor_addr_t desc_addr
;
2033 char port_addr_str
[TOR_ADDR_BUF_LEN
];
2034 char desc_addr_str
[TOR_ADDR_BUF_LEN
];
2036 tor_addr_to_str(port_addr_str
, port_addr
, TOR_ADDR_BUF_LEN
, 0);
2038 tor_addr_from_ipv4h(&desc_addr
, ipv4h_desc_addr
);
2039 tor_addr_to_str(desc_addr_str
, &desc_addr
, TOR_ADDR_BUF_LEN
, 0);
2041 const char *listener_str
= (listener_type
== CONN_TYPE_OR_LISTENER
?
2043 log_warn(LD_CONFIG
, "The IPv4 %sPort address %s does not match the "
2044 "descriptor address %s. If you have a static public IPv4 "
2045 "address, use 'Address <IPv4>' and 'OutboundBindAddress "
2046 "<IPv4>'. If you are behind a NAT, use two %sPort lines: "
2047 "'%sPort <PublicPort> NoListen' and '%sPort <InternalPort> "
2049 listener_str
, port_addr_str
, desc_addr_str
, listener_str
,
2050 listener_str
, listener_str
);
2054 /* Tor relays only have one IPv4 address in the descriptor, which is derived
2055 * from the Address torrc option, or guessed using various methods in
2056 * router_pick_published_address().
2057 * Warn the operator if there is no ORPort on the descriptor address
2059 * Warn the operator if there is no DirPort on the descriptor address.
2060 * This catches a few common config errors:
2061 * - operators who expect ORPorts and DirPorts to be advertised on the
2062 * ports' listen addresses, rather than the torrc Address (or guessed
2063 * addresses in the absence of an Address config). This includes
2064 * operators who attempt to put their ORPort and DirPort on different
2066 * - discrepancies between guessed addresses and configured listen
2067 * addresses (when the Address option isn't set).
2068 * If a listener is listening on all IPv4 addresses, it is assumed that it
2069 * is listening on the configured Address, and no messages are logged.
2070 * If an operators has specified NoAdvertise ORPorts in a NAT setting,
2071 * no messages are logged, unless they have specified other advertised
2073 * The message tells operators to configure an ORPort and DirPort that match
2074 * the Address (using NoListen if needed).
2077 router_check_descriptor_address_consistency(uint32_t ipv4h_desc_addr
)
2079 router_check_descriptor_address_port_consistency(ipv4h_desc_addr
,
2080 CONN_TYPE_OR_LISTENER
);
2081 router_check_descriptor_address_port_consistency(ipv4h_desc_addr
,
2082 CONN_TYPE_DIR_LISTENER
);
2085 /** Build a fresh routerinfo, signed server descriptor, and extra-info document
2086 * for this OR. Set r to the generated routerinfo, e to the generated
2087 * extra-info document. Return 0 on success, -1 on temporary error. Failure to
2088 * generate an extra-info document is not an error and is indicated by setting
2089 * e to NULL. Caller is responsible for freeing generated documents if 0 is
2093 router_build_fresh_descriptor(routerinfo_t
**r
, extrainfo_t
**e
)
2099 int hibernating
= we_are_hibernating();
2100 const or_options_t
*options
= get_options();
2102 if (router_pick_published_address(options
, &addr
, 0) < 0) {
2103 log_warn(LD_CONFIG
, "Don't know my address while generating descriptor");
2107 /* Log a message if the address in the descriptor doesn't match the ORPort
2108 * and DirPort addresses configured by the operator. */
2109 router_check_descriptor_address_consistency(addr
);
2111 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
2112 ri
->cache_info
.routerlist_index
= -1;
2113 ri
->nickname
= tor_strdup(options
->Nickname
);
2115 ri
->or_port
= router_get_advertised_or_port(options
);
2116 ri
->dir_port
= router_get_advertised_dir_port(options
, 0);
2117 ri
->supports_tunnelled_dir_requests
=
2118 directory_permits_begindir_requests(options
);
2119 ri
->cache_info
.published_on
= time(NULL
);
2120 ri
->onion_pkey
= crypto_pk_dup_key(get_onion_key()); /* must invoke from
2122 ri
->onion_curve25519_pkey
=
2123 tor_memdup(&get_current_curve25519_keypair()->pubkey
,
2124 sizeof(curve25519_public_key_t
));
2126 /* For now, at most one IPv6 or-address is being advertised. */
2128 const port_cfg_t
*ipv6_orport
= NULL
;
2129 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t
*, p
) {
2130 if (p
->type
== CONN_TYPE_OR_LISTENER
&&
2131 ! p
->server_cfg
.no_advertise
&&
2132 ! p
->server_cfg
.bind_ipv4_only
&&
2133 tor_addr_family(&p
->addr
) == AF_INET6
) {
2134 /* Like IPv4, if the relay is configured using the default
2135 * authorities, disallow internal IPs. Otherwise, allow them. */
2136 const int default_auth
= using_default_dir_authorities(options
);
2137 if (! tor_addr_is_internal(&p
->addr
, 0) || ! default_auth
) {
2141 char addrbuf
[TOR_ADDR_BUF_LEN
];
2143 "Unable to use configured IPv6 address \"%s\" in a "
2144 "descriptor. Skipping it. "
2145 "Try specifying a globally reachable address explicitly.",
2146 tor_addr_to_str(addrbuf
, &p
->addr
, sizeof(addrbuf
), 1));
2149 } SMARTLIST_FOREACH_END(p
);
2151 tor_addr_copy(&ri
->ipv6_addr
, &ipv6_orport
->addr
);
2152 ri
->ipv6_orport
= ipv6_orport
->port
;
2156 ri
->identity_pkey
= crypto_pk_dup_key(get_server_identity_key());
2157 if (crypto_pk_get_digest(ri
->identity_pkey
,
2158 ri
->cache_info
.identity_digest
)<0) {
2159 routerinfo_free(ri
);
2162 ri
->cache_info
.signing_key_cert
=
2163 tor_cert_dup(get_master_signing_key_cert());
2165 get_platform_str(platform
, sizeof(platform
));
2166 ri
->platform
= tor_strdup(platform
);
2168 ri
->protocol_list
= tor_strdup(protover_get_supported_protocols());
2170 /* compute ri->bandwidthrate as the min of various options */
2171 ri
->bandwidthrate
= get_effective_bwrate(options
);
2173 /* and compute ri->bandwidthburst similarly */
2174 ri
->bandwidthburst
= get_effective_bwburst(options
);
2176 ri
->bandwidthcapacity
= hibernating
? 0 : rep_hist_bandwidth_assess();
2178 if (dns_seems_to_be_broken() || has_dns_init_failed()) {
2179 /* DNS is screwed up; don't claim to be an exit. */
2180 policies_exit_policy_append_reject_star(&ri
->exit_policy
);
2182 policies_parse_exit_policy_from_options(options
,ri
->addr
,&ri
->ipv6_addr
,
2185 ri
->policy_is_reject_star
=
2186 policy_is_reject_star(ri
->exit_policy
, AF_INET
, 1) &&
2187 policy_is_reject_star(ri
->exit_policy
, AF_INET6
, 1);
2189 if (options
->IPv6Exit
) {
2190 char *p_tmp
= policy_summarize(ri
->exit_policy
, AF_INET6
);
2192 ri
->ipv6_exit_policy
= parse_short_policy(p_tmp
);
2196 if (options
->MyFamily
&& ! options
->BridgeRelay
) {
2197 smartlist_t
*family
;
2198 if (!warned_nonexistent_family
)
2199 warned_nonexistent_family
= smartlist_new();
2200 family
= smartlist_new();
2201 ri
->declared_family
= smartlist_new();
2202 smartlist_split_string(family
, options
->MyFamily
, ",",
2203 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
|SPLIT_STRIP_SPACE
, 0);
2204 SMARTLIST_FOREACH_BEGIN(family
, char *, name
) {
2205 const node_t
*member
;
2206 if (!strcasecmp(name
, options
->Nickname
))
2207 goto skip
; /* Don't list ourself, that's redundant */
2209 member
= node_get_by_nickname(name
, 1);
2211 int is_legal
= is_legal_nickname_or_hexdigest(name
);
2212 if (!smartlist_contains_string(warned_nonexistent_family
, name
) &&
2213 !is_legal_hexdigest(name
)) {
2216 "I have no descriptor for the router named \"%s\" in my "
2217 "declared family; I'll use the nickname as is, but "
2218 "this may confuse clients.", name
);
2220 log_warn(LD_CONFIG
, "There is a router named \"%s\" in my "
2221 "declared family, but that isn't a legal nickname. "
2222 "Skipping it.", escaped(name
));
2223 smartlist_add_strdup(warned_nonexistent_family
, name
);
2226 smartlist_add(ri
->declared_family
, name
);
2229 } else if (router_digest_is_me(member
->identity
)) {
2230 /* Don't list ourself in our own family; that's redundant */
2231 /* XXX shouldn't be possible */
2233 char *fp
= tor_malloc(HEX_DIGEST_LEN
+2);
2235 base16_encode(fp
+1,HEX_DIGEST_LEN
+1,
2236 member
->identity
, DIGEST_LEN
);
2237 smartlist_add(ri
->declared_family
, fp
);
2238 if (smartlist_contains_string(warned_nonexistent_family
, name
))
2239 smartlist_string_remove(warned_nonexistent_family
, name
);
2243 } SMARTLIST_FOREACH_END(name
);
2245 /* remove duplicates from the list */
2246 smartlist_sort_strings(ri
->declared_family
);
2247 smartlist_uniq_strings(ri
->declared_family
);
2249 smartlist_free(family
);
2252 /* Now generate the extrainfo. */
2253 ei
= tor_malloc_zero(sizeof(extrainfo_t
));
2254 ei
->cache_info
.is_extrainfo
= 1;
2255 strlcpy(ei
->nickname
, get_options()->Nickname
, sizeof(ei
->nickname
));
2256 ei
->cache_info
.published_on
= ri
->cache_info
.published_on
;
2257 ei
->cache_info
.signing_key_cert
=
2258 tor_cert_dup(get_master_signing_key_cert());
2260 memcpy(ei
->cache_info
.identity_digest
, ri
->cache_info
.identity_digest
,
2262 if (extrainfo_dump_to_string(&ei
->cache_info
.signed_descriptor_body
,
2263 ei
, get_server_identity_key(),
2264 get_master_signing_keypair()) < 0) {
2265 log_warn(LD_BUG
, "Couldn't generate extra-info descriptor.");
2269 ei
->cache_info
.signed_descriptor_len
=
2270 strlen(ei
->cache_info
.signed_descriptor_body
);
2271 router_get_extrainfo_hash(ei
->cache_info
.signed_descriptor_body
,
2272 ei
->cache_info
.signed_descriptor_len
,
2273 ei
->cache_info
.signed_descriptor_digest
);
2274 crypto_digest256((char*) ei
->digest256
,
2275 ei
->cache_info
.signed_descriptor_body
,
2276 ei
->cache_info
.signed_descriptor_len
,
2280 /* Now finish the router descriptor. */
2282 memcpy(ri
->cache_info
.extra_info_digest
,
2283 ei
->cache_info
.signed_descriptor_digest
,
2285 memcpy(ri
->cache_info
.extra_info_digest256
,
2289 /* ri was allocated with tor_malloc_zero, so there is no need to
2290 * zero ri->cache_info.extra_info_digest here. */
2292 if (! (ri
->cache_info
.signed_descriptor_body
=
2293 router_dump_router_to_string(ri
, get_server_identity_key(),
2295 get_current_curve25519_keypair(),
2296 get_master_signing_keypair())) ) {
2297 log_warn(LD_BUG
, "Couldn't generate router descriptor.");
2298 routerinfo_free(ri
);
2302 ri
->cache_info
.signed_descriptor_len
=
2303 strlen(ri
->cache_info
.signed_descriptor_body
);
2306 options
->BridgeRelay
? ROUTER_PURPOSE_BRIDGE
: ROUTER_PURPOSE_GENERAL
;
2307 if (options
->BridgeRelay
) {
2308 /* Bridges shouldn't be able to send their descriptors unencrypted,
2309 anyway, since they don't have a DirPort, and always connect to the
2310 bridge authority anonymously. But just in case they somehow think of
2311 sending them on an unencrypted connection, don't allow them to try. */
2312 ri
->cache_info
.send_unencrypted
= 0;
2314 ei
->cache_info
.send_unencrypted
= 0;
2316 ri
->cache_info
.send_unencrypted
= 1;
2318 ei
->cache_info
.send_unencrypted
= 1;
2321 router_get_router_hash(ri
->cache_info
.signed_descriptor_body
,
2322 strlen(ri
->cache_info
.signed_descriptor_body
),
2323 ri
->cache_info
.signed_descriptor_digest
);
2327 routerinfo_incompatible_with_extrainfo(ri
->identity_pkey
, ei
,
2328 &ri
->cache_info
, NULL
));
2336 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
2337 * routerinfo, signed server descriptor, and extra-info document for this OR.
2338 * Return 0 on success, -1 on temporary error.
2341 router_rebuild_descriptor(int force
)
2346 const or_options_t
*options
= get_options();
2348 if (desc_clean_since
&& !force
)
2351 if (router_pick_published_address(options
, &addr
, 0) < 0 ||
2352 router_get_advertised_or_port(options
) == 0) {
2353 /* Stop trying to rebuild our descriptor every second. We'll
2354 * learn that it's time to try again when ip_address_changed()
2355 * marks it dirty. */
2356 desc_clean_since
= time(NULL
);
2360 log_info(LD_OR
, "Rebuilding relay descriptor%s", force
? " (forced)" : "");
2362 if (router_build_fresh_descriptor(&ri
, &ei
) < 0) {
2366 routerinfo_free(desc_routerinfo
);
2367 desc_routerinfo
= ri
;
2368 extrainfo_free(desc_extrainfo
);
2369 desc_extrainfo
= ei
;
2371 desc_clean_since
= time(NULL
);
2372 desc_needs_upload
= 1;
2373 desc_gen_reason
= desc_dirty_reason
;
2374 desc_dirty_reason
= NULL
;
2375 control_event_my_descriptor_changed();
2379 /** If our router descriptor ever goes this long without being regenerated
2380 * because something changed, we force an immediate regenerate-and-upload. */
2381 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
2383 /** If our router descriptor seems to be missing or unacceptable according
2384 * to the authorities, regenerate and reupload it _this_ often. */
2385 #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
2387 /** Mark descriptor out of date if it's been "too long" since we last tried
2390 mark_my_descriptor_dirty_if_too_old(time_t now
)
2392 networkstatus_t
*ns
;
2393 const routerstatus_t
*rs
;
2394 const char *retry_fast_reason
= NULL
; /* Set if we should retry frequently */
2395 const time_t slow_cutoff
= now
- FORCE_REGENERATE_DESCRIPTOR_INTERVAL
;
2396 const time_t fast_cutoff
= now
- FAST_RETRY_DESCRIPTOR_INTERVAL
;
2398 /* If it's already dirty, don't mark it. */
2399 if (! desc_clean_since
)
2402 /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
2403 * time to rebuild it. */
2404 if (desc_clean_since
< slow_cutoff
) {
2405 mark_my_descriptor_dirty("time for new descriptor");
2408 /* Now we see whether we want to be retrying frequently or no. The
2409 * rule here is that we'll retry frequently if we aren't listed in the
2410 * live consensus we have, or if the publication time of the
2411 * descriptor listed for us in the consensus is very old. */
2412 ns
= networkstatus_get_live_consensus(now
);
2414 rs
= networkstatus_vote_find_entry(ns
, server_identitykey_digest
);
2416 retry_fast_reason
= "not listed in consensus";
2417 else if (rs
->published_on
< slow_cutoff
)
2418 retry_fast_reason
= "version listed in consensus is quite old";
2421 if (retry_fast_reason
&& desc_clean_since
< fast_cutoff
)
2422 mark_my_descriptor_dirty(retry_fast_reason
);
2425 /** Call when the current descriptor is out of date. */
2427 mark_my_descriptor_dirty(const char *reason
)
2429 const or_options_t
*options
= get_options();
2430 if (server_mode(options
) && options
->PublishServerDescriptor_
)
2431 log_info(LD_OR
, "Decided to publish new relay descriptor: %s", reason
);
2432 desc_clean_since
= 0;
2433 if (!desc_dirty_reason
)
2434 desc_dirty_reason
= reason
;
2437 /** How frequently will we republish our descriptor because of large (factor
2438 * of 2) shifts in estimated bandwidth? Note: We don't use this constant
2439 * if our previous bandwidth estimate was exactly 0. */
2440 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
2442 /** Check whether bandwidth has changed a lot since the last time we announced
2443 * bandwidth. If so, mark our descriptor dirty. */
2445 check_descriptor_bandwidth_changed(time_t now
)
2447 static time_t last_changed
= 0;
2449 if (!router_get_my_routerinfo())
2452 prev
= router_get_my_routerinfo()->bandwidthcapacity
;
2453 cur
= we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
2454 if ((prev
!= cur
&& (!prev
|| !cur
)) ||
2457 if (last_changed
+MAX_BANDWIDTH_CHANGE_FREQ
< now
|| !prev
) {
2458 log_info(LD_GENERAL
,
2459 "Measured bandwidth has changed; rebuilding descriptor.");
2460 mark_my_descriptor_dirty("bandwidth has changed");
2466 /** Note at log level severity that our best guess of address has changed from
2467 * <b>prev</b> to <b>cur</b>. */
2469 log_addr_has_changed(int severity
,
2470 const tor_addr_t
*prev
,
2471 const tor_addr_t
*cur
,
2474 char addrbuf_prev
[TOR_ADDR_BUF_LEN
];
2475 char addrbuf_cur
[TOR_ADDR_BUF_LEN
];
2477 if (tor_addr_to_str(addrbuf_prev
, prev
, sizeof(addrbuf_prev
), 1) == NULL
)
2478 strlcpy(addrbuf_prev
, "???", TOR_ADDR_BUF_LEN
);
2479 if (tor_addr_to_str(addrbuf_cur
, cur
, sizeof(addrbuf_cur
), 1) == NULL
)
2480 strlcpy(addrbuf_cur
, "???", TOR_ADDR_BUF_LEN
);
2482 if (!tor_addr_is_null(prev
))
2483 log_fn(severity
, LD_GENERAL
,
2484 "Our IP Address has changed from %s to %s; "
2485 "rebuilding descriptor (source: %s).",
2486 addrbuf_prev
, addrbuf_cur
, source
);
2488 log_notice(LD_GENERAL
,
2489 "Guessed our IP address as %s (source: %s).",
2490 addrbuf_cur
, source
);
2493 /** Check whether our own address as defined by the Address configuration
2494 * has changed. This is for routers that get their address from a service
2495 * like dyndns. If our address has changed, mark our descriptor dirty. */
2497 check_descriptor_ipaddress_changed(time_t now
)
2500 const or_options_t
*options
= get_options();
2501 const char *method
= NULL
;
2502 char *hostname
= NULL
;
2506 if (router_get_my_routerinfo() == NULL
)
2510 prev
= router_get_my_routerinfo()->addr
;
2511 if (resolve_my_address(LOG_INFO
, options
, &cur
, &method
, &hostname
) < 0) {
2512 log_info(LD_CONFIG
,"options->Address didn't resolve into an IP.");
2518 tor_addr_t tmp_prev
, tmp_cur
;
2520 tor_addr_from_ipv4h(&tmp_prev
, prev
);
2521 tor_addr_from_ipv4h(&tmp_cur
, cur
);
2523 tor_asprintf(&source
, "METHOD=%s%s%s", method
,
2524 hostname
? " HOSTNAME=" : "",
2525 hostname
? hostname
: "");
2527 log_addr_has_changed(LOG_NOTICE
, &tmp_prev
, &tmp_cur
, source
);
2530 ip_address_changed(0);
2536 /** The most recently guessed value of our IP address, based on directory
2538 static tor_addr_t last_guessed_ip
= TOR_ADDR_NULL
;
2540 /** A directory server <b>d_conn</b> told us our IP address is
2541 * <b>suggestion</b>.
2542 * If this address is different from the one we think we are now, and
2543 * if our computer doesn't actually know its IP address, then switch. */
2545 router_new_address_suggestion(const char *suggestion
,
2546 const dir_connection_t
*d_conn
)
2549 uint32_t cur
= 0; /* Current IPv4 address. */
2550 const or_options_t
*options
= get_options();
2552 /* first, learn what the IP address actually is */
2553 if (tor_addr_parse(&addr
, suggestion
) == -1) {
2554 log_debug(LD_DIR
, "Malformed X-Your-Address-Is header %s. Ignoring.",
2555 escaped(suggestion
));
2559 log_debug(LD_DIR
, "Got X-Your-Address-Is: %s.", suggestion
);
2561 if (!server_mode(options
)) {
2562 tor_addr_copy(&last_guessed_ip
, &addr
);
2567 cur
= get_last_resolved_addr();
2569 resolve_my_address(LOG_INFO
, options
, &cur
, NULL
, NULL
) >= 0) {
2570 /* We're all set -- we already know our address. Great. */
2571 tor_addr_from_ipv4h(&last_guessed_ip
, cur
); /* store it in case we
2575 if (tor_addr_is_internal(&addr
, 0)) {
2576 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
2579 if (tor_addr_eq(&d_conn
->base_
.addr
, &addr
)) {
2580 /* Don't believe anybody who says our IP is their IP. */
2581 log_debug(LD_DIR
, "A directory server told us our IP address is %s, "
2582 "but they are just reporting their own IP address. Ignoring.",
2587 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
2588 * us an answer different from what we had the last time we managed to
2590 if (!tor_addr_eq(&last_guessed_ip
, &addr
)) {
2591 control_event_server_status(LOG_NOTICE
,
2592 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
2594 log_addr_has_changed(LOG_NOTICE
, &last_guessed_ip
, &addr
,
2595 d_conn
->base_
.address
);
2596 ip_address_changed(0);
2597 tor_addr_copy(&last_guessed_ip
, &addr
); /* router_rebuild_descriptor()
2602 /** We failed to resolve our address locally, but we'd like to build
2603 * a descriptor and publish / test reachability. If we have a guess
2604 * about our address based on directory headers, answer it and return
2605 * 0; else return -1. */
2607 router_guess_address_from_dir_headers(uint32_t *guess
)
2609 if (!tor_addr_is_null(&last_guessed_ip
)) {
2610 *guess
= tor_addr_to_ipv4h(&last_guessed_ip
);
2616 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
2617 * string describing the version of Tor and the operating system we're
2618 * currently running on.
2621 get_platform_str(char *platform
, size_t len
)
2623 tor_snprintf(platform
, len
, "Tor %s on %s",
2624 get_short_version(), get_uname());
2627 /* XXX need to audit this thing and count fenceposts. maybe
2628 * refactor so we don't have to keep asking if we're
2629 * near the end of maxlen?
2631 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2633 /** OR only: Given a routerinfo for this router, and an identity key to sign
2634 * with, encode the routerinfo as a signed server descriptor and return a new
2635 * string encoding the result, or NULL on failure.
2638 router_dump_router_to_string(routerinfo_t
*router
,
2639 const crypto_pk_t
*ident_key
,
2640 const crypto_pk_t
*tap_key
,
2641 const curve25519_keypair_t
*ntor_keypair
,
2642 const ed25519_keypair_t
*signing_keypair
)
2644 char *address
= NULL
;
2645 char *onion_pkey
= NULL
; /* Onion key, PEM-encoded. */
2646 char *identity_pkey
= NULL
; /* Identity key, PEM-encoded. */
2647 char digest
[DIGEST256_LEN
];
2648 char published
[ISO_TIME_LEN
+1];
2649 char fingerprint
[FINGERPRINT_LEN
+1];
2650 char *extra_info_line
= NULL
;
2651 size_t onion_pkeylen
, identity_pkeylen
;
2652 char *family_line
= NULL
;
2653 char *extra_or_address
= NULL
;
2654 const or_options_t
*options
= get_options();
2655 smartlist_t
*chunks
= NULL
;
2656 char *output
= NULL
;
2657 const int emit_ed_sigs
= signing_keypair
&&
2658 router
->cache_info
.signing_key_cert
;
2659 char *ed_cert_line
= NULL
;
2660 char *rsa_tap_cc_line
= NULL
;
2661 char *ntor_cc_line
= NULL
;
2662 char *proto_line
= NULL
;
2664 /* Make sure the identity key matches the one in the routerinfo. */
2665 if (!crypto_pk_eq_keys(ident_key
, router
->identity_pkey
)) {
2666 log_warn(LD_BUG
,"Tried to sign a router with a private key that didn't "
2667 "match router's public key!");
2671 if (!router
->cache_info
.signing_key_cert
->signing_key_included
||
2672 !ed25519_pubkey_eq(&router
->cache_info
.signing_key_cert
->signed_key
,
2673 &signing_keypair
->pubkey
)) {
2674 log_warn(LD_BUG
, "Tried to sign a router descriptor with a mismatched "
2675 "ed25519 key chain %d",
2676 router
->cache_info
.signing_key_cert
->signing_key_included
);
2681 /* record our fingerprint, so we can include it in the descriptor */
2682 if (crypto_pk_get_fingerprint(router
->identity_pkey
, fingerprint
, 1)<0) {
2683 log_err(LD_BUG
,"Error computing fingerprint");
2688 /* Encode ed25519 signing cert */
2689 char ed_cert_base64
[256];
2690 char ed_fp_base64
[ED25519_BASE64_LEN
+1];
2691 if (base64_encode(ed_cert_base64
, sizeof(ed_cert_base64
),
2692 (const char*)router
->cache_info
.signing_key_cert
->encoded
,
2693 router
->cache_info
.signing_key_cert
->encoded_len
,
2694 BASE64_ENCODE_MULTILINE
) < 0) {
2695 log_err(LD_BUG
,"Couldn't base64-encode signing key certificate!");
2698 if (ed25519_public_to_base64(ed_fp_base64
,
2699 &router
->cache_info
.signing_key_cert
->signing_key
)<0) {
2700 log_err(LD_BUG
,"Couldn't base64-encode identity key\n");
2703 tor_asprintf(&ed_cert_line
, "identity-ed25519\n"
2704 "-----BEGIN ED25519 CERT-----\n"
2706 "-----END ED25519 CERT-----\n"
2707 "master-key-ed25519 %s\n",
2708 ed_cert_base64
, ed_fp_base64
);
2711 /* PEM-encode the onion key */
2712 if (crypto_pk_write_public_key_to_string(router
->onion_pkey
,
2713 &onion_pkey
,&onion_pkeylen
)<0) {
2714 log_warn(LD_BUG
,"write onion_pkey to string failed!");
2718 /* PEM-encode the identity key */
2719 if (crypto_pk_write_public_key_to_string(router
->identity_pkey
,
2720 &identity_pkey
,&identity_pkeylen
)<0) {
2721 log_warn(LD_BUG
,"write identity_pkey to string failed!");
2725 /* Cross-certify with RSA key */
2726 if (tap_key
&& router
->cache_info
.signing_key_cert
&&
2727 router
->cache_info
.signing_key_cert
->signing_key_included
) {
2731 make_tap_onion_key_crosscert(tap_key
,
2732 &router
->cache_info
.signing_key_cert
->signing_key
,
2733 router
->identity_pkey
,
2736 log_warn(LD_BUG
,"make_tap_onion_key_crosscert failed!");
2740 if (base64_encode(buf
, sizeof(buf
), (const char*)tap_cc
, tap_cc_len
,
2741 BASE64_ENCODE_MULTILINE
) < 0) {
2742 log_warn(LD_BUG
,"base64_encode(rsa_crosscert) failed!");
2748 tor_asprintf(&rsa_tap_cc_line
,
2749 "onion-key-crosscert\n"
2750 "-----BEGIN CROSSCERT-----\n"
2752 "-----END CROSSCERT-----\n", buf
);
2755 /* Cross-certify with onion keys */
2756 if (ntor_keypair
&& router
->cache_info
.signing_key_cert
&&
2757 router
->cache_info
.signing_key_cert
->signing_key_included
) {
2760 /* XXXX Base the expiration date on the actual onion key expiration time?*/
2762 make_ntor_onion_key_crosscert(ntor_keypair
,
2763 &router
->cache_info
.signing_key_cert
->signing_key
,
2764 router
->cache_info
.published_on
,
2765 MIN_ONION_KEY_LIFETIME
, &sign
);
2767 log_warn(LD_BUG
,"make_ntor_onion_key_crosscert failed!");
2770 tor_assert(sign
== 0 || sign
== 1);
2772 if (base64_encode(buf
, sizeof(buf
),
2773 (const char*)cert
->encoded
, cert
->encoded_len
,
2774 BASE64_ENCODE_MULTILINE
)<0) {
2775 log_warn(LD_BUG
,"base64_encode(ntor_crosscert) failed!");
2776 tor_cert_free(cert
);
2779 tor_cert_free(cert
);
2781 tor_asprintf(&ntor_cc_line
,
2782 "ntor-onion-key-crosscert %d\n"
2783 "-----BEGIN ED25519 CERT-----\n"
2785 "-----END ED25519 CERT-----\n", sign
, buf
);
2788 /* Encode the publication time. */
2789 format_iso_time(published
, router
->cache_info
.published_on
);
2791 if (router
->declared_family
&& smartlist_len(router
->declared_family
)) {
2792 char *family
= smartlist_join_strings(router
->declared_family
,
2794 tor_asprintf(&family_line
, "family %s\n", family
);
2797 family_line
= tor_strdup("");
2800 if (!tor_digest_is_zero(router
->cache_info
.extra_info_digest
)) {
2801 char extra_info_digest
[HEX_DIGEST_LEN
+1];
2802 base16_encode(extra_info_digest
, sizeof(extra_info_digest
),
2803 router
->cache_info
.extra_info_digest
, DIGEST_LEN
);
2804 if (!tor_digest256_is_zero(router
->cache_info
.extra_info_digest256
)) {
2805 char d256_64
[BASE64_DIGEST256_LEN
+1];
2806 digest256_to_base64(d256_64
, router
->cache_info
.extra_info_digest256
);
2807 tor_asprintf(&extra_info_line
, "extra-info-digest %s %s\n",
2808 extra_info_digest
, d256_64
);
2810 tor_asprintf(&extra_info_line
, "extra-info-digest %s\n",
2815 if (router
->ipv6_orport
&&
2816 tor_addr_family(&router
->ipv6_addr
) == AF_INET6
) {
2817 char addr
[TOR_ADDR_BUF_LEN
];
2819 a
= tor_addr_to_str(addr
, &router
->ipv6_addr
, sizeof(addr
), 1);
2821 tor_asprintf(&extra_or_address
,
2822 "or-address %s:%d\n", a
, router
->ipv6_orport
);
2823 log_debug(LD_OR
, "My or-address line is <%s>", extra_or_address
);
2827 if (router
->protocol_list
) {
2828 tor_asprintf(&proto_line
, "proto %s\n", router
->protocol_list
);
2830 proto_line
= tor_strdup("");
2833 address
= tor_dup_ip(router
->addr
);
2834 chunks
= smartlist_new();
2836 /* Generate the easy portion of the router descriptor. */
2837 smartlist_add_asprintf(chunks
,
2838 "router %s %s %d 0 %d\n"
2846 "bandwidth %d %d %d\n"
2855 decide_to_advertise_dirport(options
, router
->dir_port
),
2856 ed_cert_line
? ed_cert_line
: "",
2857 extra_or_address
? extra_or_address
: "",
2862 stats_n_seconds_working
,
2863 (int) router
->bandwidthrate
,
2864 (int) router
->bandwidthburst
,
2865 (int) router
->bandwidthcapacity
,
2866 extra_info_line
? extra_info_line
: "",
2867 (options
->DownloadExtraInfo
|| options
->V3AuthoritativeDir
) ?
2868 "caches-extra-info\n" : "",
2869 onion_pkey
, identity_pkey
,
2870 rsa_tap_cc_line
? rsa_tap_cc_line
: "",
2871 ntor_cc_line
? ntor_cc_line
: "",
2873 we_are_hibernating() ? "hibernating 1\n" : "",
2874 "hidden-service-dir\n",
2875 options
->AllowSingleHopExits
? "allow-single-hop-exits\n" : "");
2877 if (options
->ContactInfo
&& strlen(options
->ContactInfo
)) {
2878 const char *ci
= options
->ContactInfo
;
2879 if (strchr(ci
, '\n') || strchr(ci
, '\r'))
2881 smartlist_add_asprintf(chunks
, "contact %s\n", ci
);
2884 if (options
->BridgeRelay
) {
2886 if (options
->PublishServerDescriptor_
& BRIDGE_DIRINFO
)
2890 smartlist_add_asprintf(chunks
, "bridge-distribution-request %s\n", bd
);
2893 if (router
->onion_curve25519_pkey
) {
2895 base64_encode(kbuf
, sizeof(kbuf
),
2896 (const char *)router
->onion_curve25519_pkey
->public_key
,
2897 CURVE25519_PUBKEY_LEN
, BASE64_ENCODE_MULTILINE
);
2898 smartlist_add_asprintf(chunks
, "ntor-onion-key %s", kbuf
);
2900 /* Authorities will start rejecting relays without ntor keys in 0.2.9 */
2901 log_err(LD_BUG
, "A relay must have an ntor onion key");
2905 /* Write the exit policy to the end of 's'. */
2906 if (!router
->exit_policy
|| !smartlist_len(router
->exit_policy
)) {
2907 smartlist_add_strdup(chunks
, "reject *:*\n");
2908 } else if (router
->exit_policy
) {
2909 char *exit_policy
= router_dump_exit_policy_to_string(router
,1,0);
2914 smartlist_add_asprintf(chunks
, "%s\n", exit_policy
);
2915 tor_free(exit_policy
);
2918 if (router
->ipv6_exit_policy
) {
2919 char *p6
= write_short_policy(router
->ipv6_exit_policy
);
2920 if (p6
&& strcmp(p6
, "reject 1-65535")) {
2921 smartlist_add_asprintf(chunks
,
2922 "ipv6-policy %s\n", p6
);
2927 if (decide_to_advertise_begindir(options
,
2928 router
->supports_tunnelled_dir_requests
)) {
2929 smartlist_add_strdup(chunks
, "tunnelled-dir-server\n");
2932 /* Sign the descriptor with Ed25519 */
2934 smartlist_add_strdup(chunks
, "router-sig-ed25519 ");
2935 crypto_digest_smartlist_prefix(digest
, DIGEST256_LEN
,
2936 ED_DESC_SIGNATURE_PREFIX
,
2937 chunks
, "", DIGEST_SHA256
);
2938 ed25519_signature_t sig
;
2939 char buf
[ED25519_SIG_BASE64_LEN
+1];
2940 if (ed25519_sign(&sig
, (const uint8_t*)digest
, DIGEST256_LEN
,
2941 signing_keypair
) < 0)
2943 if (ed25519_signature_to_base64(buf
, &sig
) < 0)
2946 smartlist_add_asprintf(chunks
, "%s\n", buf
);
2949 /* Sign the descriptor with RSA */
2950 smartlist_add_strdup(chunks
, "router-signature\n");
2952 crypto_digest_smartlist(digest
, DIGEST_LEN
, chunks
, "", DIGEST_SHA1
);
2954 note_crypto_pk_op(SIGN_RTR
);
2957 if (!(sig
= router_get_dirobj_signature(digest
, DIGEST_LEN
, ident_key
))) {
2958 log_warn(LD_BUG
, "Couldn't sign router descriptor");
2961 smartlist_add(chunks
, sig
);
2964 /* include a last '\n' */
2965 smartlist_add_strdup(chunks
, "\n");
2967 output
= smartlist_join_strings(chunks
, "", 0, NULL
);
2969 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2973 routerinfo_t
*ri_tmp
;
2974 cp
= s_dup
= tor_strdup(output
);
2975 ri_tmp
= router_parse_entry_from_string(cp
, NULL
, 1, 0, NULL
, NULL
);
2978 "We just generated a router descriptor we can't parse.");
2979 log_err(LD_BUG
, "Descriptor was: <<%s>>", output
);
2983 routerinfo_free(ri_tmp
);
2990 tor_free(output
); /* sets output to NULL */
2993 SMARTLIST_FOREACH(chunks
, char *, cp
, tor_free(cp
));
2994 smartlist_free(chunks
);
2997 tor_free(family_line
);
2998 tor_free(onion_pkey
);
2999 tor_free(identity_pkey
);
3000 tor_free(extra_or_address
);
3001 tor_free(ed_cert_line
);
3002 tor_free(rsa_tap_cc_line
);
3003 tor_free(ntor_cc_line
);
3004 tor_free(extra_info_line
);
3005 tor_free(proto_line
);
3011 * OR only: Given <b>router</b>, produce a string with its exit policy.
3012 * If <b>include_ipv4</b> is true, include IPv4 entries.
3013 * If <b>include_ipv6</b> is true, include IPv6 entries.
3016 router_dump_exit_policy_to_string(const routerinfo_t
*router
,
3020 if ((!router
->exit_policy
) || (router
->policy_is_reject_star
)) {
3021 return tor_strdup("reject *:*");
3024 return policy_dump_to_string(router
->exit_policy
,
3029 /** Copy the primary (IPv4) OR port (IP address and TCP port) for
3030 * <b>router</b> into *<b>ap_out</b>. */
3032 router_get_prim_orport(const routerinfo_t
*router
, tor_addr_port_t
*ap_out
)
3034 tor_assert(ap_out
!= NULL
);
3035 tor_addr_from_ipv4h(&ap_out
->addr
, router
->addr
);
3036 ap_out
->port
= router
->or_port
;
3039 /** Return 1 if any of <b>router</b>'s addresses are <b>addr</b>.
3040 * Otherwise return 0. */
3042 router_has_addr(const routerinfo_t
*router
, const tor_addr_t
*addr
)
3045 tor_addr_eq_ipv4h(addr
, router
->addr
) ||
3046 tor_addr_eq(&router
->ipv6_addr
, addr
);
3050 router_has_orport(const routerinfo_t
*router
, const tor_addr_port_t
*orport
)
3053 (tor_addr_eq_ipv4h(&orport
->addr
, router
->addr
) &&
3054 orport
->port
== router
->or_port
) ||
3055 (tor_addr_eq(&orport
->addr
, &router
->ipv6_addr
) &&
3056 orport
->port
== router
->ipv6_orport
);
3059 /** Load the contents of <b>filename</b>, find the last line starting with
3060 * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
3061 * the past or more than 1 hour in the future with respect to <b>now</b>,
3062 * and write the file contents starting with that line to *<b>out</b>.
3063 * Return 1 for success, 0 if the file does not exist or is empty, or -1
3064 * if the file does not contain a line matching these criteria or other
3067 load_stats_file(const char *filename
, const char *end_line
, time_t now
,
3071 char *fname
= get_datadir_fname(filename
);
3072 char *contents
, *start
= NULL
, *tmp
, timestr
[ISO_TIME_LEN
+1];
3074 switch (file_status(fname
)) {
3076 /* X022 Find an alternative to reading the whole file to memory. */
3077 if ((contents
= read_file_to_str(fname
, 0, NULL
))) {
3078 tmp
= strstr(contents
, end_line
);
3079 /* Find last block starting with end_line */
3082 tmp
= strstr(tmp
+ 1, end_line
);
3086 if (strlen(start
) < strlen(end_line
) + 1 + sizeof(timestr
))
3088 strlcpy(timestr
, start
+ 1 + strlen(end_line
), sizeof(timestr
));
3089 if (parse_iso_time(timestr
, &written
) < 0)
3091 if (written
< now
- (25*60*60) || written
> now
+ (1*60*60))
3093 *out
= tor_strdup(start
);
3099 /* treat empty stats files as if the file doesn't exist */
3113 /** Write the contents of <b>extrainfo</b> and aggregated statistics to
3114 * *<b>s_out</b>, signing them with <b>ident_key</b>. Return 0 on
3115 * success, negative on failure. */
3117 extrainfo_dump_to_string(char **s_out
, extrainfo_t
*extrainfo
,
3118 crypto_pk_t
*ident_key
,
3119 const ed25519_keypair_t
*signing_keypair
)
3121 const or_options_t
*options
= get_options();
3122 char identity
[HEX_DIGEST_LEN
+1];
3123 char published
[ISO_TIME_LEN
+1];
3124 char digest
[DIGEST_LEN
];
3125 char *bandwidth_usage
;
3127 static int write_stats_to_extrainfo
= 1;
3128 char sig
[DIROBJ_MAX_SIG_LEN
+1];
3129 char *s
= NULL
, *pre
, *contents
, *cp
, *s_dup
= NULL
;
3130 time_t now
= time(NULL
);
3131 smartlist_t
*chunks
= smartlist_new();
3132 extrainfo_t
*ei_tmp
= NULL
;
3133 const int emit_ed_sigs
= signing_keypair
&&
3134 extrainfo
->cache_info
.signing_key_cert
;
3135 char *ed_cert_line
= NULL
;
3137 base16_encode(identity
, sizeof(identity
),
3138 extrainfo
->cache_info
.identity_digest
, DIGEST_LEN
);
3139 format_iso_time(published
, extrainfo
->cache_info
.published_on
);
3140 bandwidth_usage
= rep_hist_get_bandwidth_lines();
3142 if (!extrainfo
->cache_info
.signing_key_cert
->signing_key_included
||
3143 !ed25519_pubkey_eq(&extrainfo
->cache_info
.signing_key_cert
->signed_key
,
3144 &signing_keypair
->pubkey
)) {
3145 log_warn(LD_BUG
, "Tried to sign a extrainfo descriptor with a "
3146 "mismatched ed25519 key chain %d",
3147 extrainfo
->cache_info
.signing_key_cert
->signing_key_included
);
3150 char ed_cert_base64
[256];
3151 if (base64_encode(ed_cert_base64
, sizeof(ed_cert_base64
),
3152 (const char*)extrainfo
->cache_info
.signing_key_cert
->encoded
,
3153 extrainfo
->cache_info
.signing_key_cert
->encoded_len
,
3154 BASE64_ENCODE_MULTILINE
) < 0) {
3155 log_err(LD_BUG
,"Couldn't base64-encode signing key certificate!");
3158 tor_asprintf(&ed_cert_line
, "identity-ed25519\n"
3159 "-----BEGIN ED25519 CERT-----\n"
3161 "-----END ED25519 CERT-----\n", ed_cert_base64
);
3163 ed_cert_line
= tor_strdup("");
3166 tor_asprintf(&pre
, "extra-info %s %s\n%spublished %s\n%s",
3167 extrainfo
->nickname
, identity
,
3169 published
, bandwidth_usage
);
3170 smartlist_add(chunks
, pre
);
3172 if (geoip_is_loaded(AF_INET
))
3173 smartlist_add_asprintf(chunks
, "geoip-db-digest %s\n",
3174 geoip_db_digest(AF_INET
));
3175 if (geoip_is_loaded(AF_INET6
))
3176 smartlist_add_asprintf(chunks
, "geoip6-db-digest %s\n",
3177 geoip_db_digest(AF_INET6
));
3179 if (options
->ExtraInfoStatistics
&& write_stats_to_extrainfo
) {
3180 log_info(LD_GENERAL
, "Adding stats to extra-info descriptor.");
3181 if (options
->DirReqStatistics
&&
3182 load_stats_file("stats"PATH_SEPARATOR
"dirreq-stats",
3183 "dirreq-stats-end", now
, &contents
) > 0) {
3184 smartlist_add(chunks
, contents
);
3186 if (options
->HiddenServiceStatistics
&&
3187 load_stats_file("stats"PATH_SEPARATOR
"hidserv-stats",
3188 "hidserv-stats-end", now
, &contents
) > 0) {
3189 smartlist_add(chunks
, contents
);
3191 if (options
->EntryStatistics
&&
3192 load_stats_file("stats"PATH_SEPARATOR
"entry-stats",
3193 "entry-stats-end", now
, &contents
) > 0) {
3194 smartlist_add(chunks
, contents
);
3196 if (options
->CellStatistics
&&
3197 load_stats_file("stats"PATH_SEPARATOR
"buffer-stats",
3198 "cell-stats-end", now
, &contents
) > 0) {
3199 smartlist_add(chunks
, contents
);
3201 if (options
->ExitPortStatistics
&&
3202 load_stats_file("stats"PATH_SEPARATOR
"exit-stats",
3203 "exit-stats-end", now
, &contents
) > 0) {
3204 smartlist_add(chunks
, contents
);
3206 if (options
->ConnDirectionStatistics
&&
3207 load_stats_file("stats"PATH_SEPARATOR
"conn-stats",
3208 "conn-bi-direct", now
, &contents
) > 0) {
3209 smartlist_add(chunks
, contents
);
3213 /* Add information about the pluggable transports we support. */
3214 if (options
->ServerTransportPlugin
) {
3215 char *pluggable_transports
= pt_get_extra_info_descriptor_string();
3216 if (pluggable_transports
)
3217 smartlist_add(chunks
, pluggable_transports
);
3220 if (should_record_bridge_info(options
) && write_stats_to_extrainfo
) {
3221 const char *bridge_stats
= geoip_get_bridge_stats_extrainfo(now
);
3223 smartlist_add_strdup(chunks
, bridge_stats
);
3228 char sha256_digest
[DIGEST256_LEN
];
3229 smartlist_add_strdup(chunks
, "router-sig-ed25519 ");
3230 crypto_digest_smartlist_prefix(sha256_digest
, DIGEST256_LEN
,
3231 ED_DESC_SIGNATURE_PREFIX
,
3232 chunks
, "", DIGEST_SHA256
);
3233 ed25519_signature_t ed_sig
;
3234 char buf
[ED25519_SIG_BASE64_LEN
+1];
3235 if (ed25519_sign(&ed_sig
, (const uint8_t*)sha256_digest
, DIGEST256_LEN
,
3236 signing_keypair
) < 0)
3238 if (ed25519_signature_to_base64(buf
, &ed_sig
) < 0)
3241 smartlist_add_asprintf(chunks
, "%s\n", buf
);
3244 smartlist_add_strdup(chunks
, "router-signature\n");
3245 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
3247 while (strlen(s
) > MAX_EXTRAINFO_UPLOAD_SIZE
- DIROBJ_MAX_SIG_LEN
) {
3248 /* So long as there are at least two chunks (one for the initial
3249 * extra-info line and one for the router-signature), we can keep removing
3251 if (smartlist_len(chunks
) > 2) {
3252 /* We remove the next-to-last element (remember, len-1 is the last
3253 element), since we need to keep the router-signature element. */
3254 int idx
= smartlist_len(chunks
) - 2;
3255 char *e
= smartlist_get(chunks
, idx
);
3256 smartlist_del_keeporder(chunks
, idx
);
3257 log_warn(LD_GENERAL
, "We just generated an extra-info descriptor "
3258 "with statistics that exceeds the 50 KB "
3259 "upload limit. Removing last added "
3263 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
3265 log_warn(LD_BUG
, "We just generated an extra-info descriptors that "
3266 "exceeds the 50 KB upload limit.");
3271 memset(sig
, 0, sizeof(sig
));
3272 if (router_get_extrainfo_hash(s
, strlen(s
), digest
) < 0 ||
3273 router_append_dirobj_signature(sig
, sizeof(sig
), digest
, DIGEST_LEN
,
3275 log_warn(LD_BUG
, "Could not append signature to extra-info "
3279 smartlist_add_strdup(chunks
, sig
);
3281 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
3283 cp
= s_dup
= tor_strdup(s
);
3284 ei_tmp
= extrainfo_parse_entry_from_string(cp
, NULL
, 1, NULL
, NULL
);
3286 if (write_stats_to_extrainfo
) {
3287 log_warn(LD_GENERAL
, "We just generated an extra-info descriptor "
3288 "with statistics that we can't parse. Not "
3289 "adding statistics to this or any future "
3290 "extra-info descriptors.");
3291 write_stats_to_extrainfo
= 0;
3292 result
= extrainfo_dump_to_string(s_out
, extrainfo
, ident_key
,
3296 log_warn(LD_BUG
, "We just generated an extrainfo descriptor we "
3303 s
= NULL
; /* prevent free */
3312 SMARTLIST_FOREACH(chunks
, char *, chunk
, tor_free(chunk
));
3313 smartlist_free(chunks
);
3315 tor_free(ed_cert_line
);
3316 extrainfo_free(ei_tmp
);
3317 tor_free(bandwidth_usage
);
3322 /** Return true iff <b>s</b> is a valid server nickname. (That is, a string
3323 * containing between 1 and MAX_NICKNAME_LEN characters from
3324 * LEGAL_NICKNAME_CHARACTERS.) */
3326 is_legal_nickname(const char *s
)
3331 return len
> 0 && len
<= MAX_NICKNAME_LEN
&&
3332 strspn(s
,LEGAL_NICKNAME_CHARACTERS
) == len
;
3335 /** Return true iff <b>s</b> is a valid server nickname or
3336 * hex-encoded identity-key digest. */
3338 is_legal_nickname_or_hexdigest(const char *s
)
3341 return is_legal_nickname(s
);
3343 return is_legal_hexdigest(s
);
3346 /** Return true iff <b>s</b> is a valid hex-encoded identity-key
3347 * digest. (That is, an optional $, followed by 40 hex characters,
3348 * followed by either nothing, or = or ~ followed by a nickname, or
3349 * a character other than =, ~, or a hex character.)
3352 is_legal_hexdigest(const char *s
)
3356 if (s
[0] == '$') s
++;
3358 if (len
> HEX_DIGEST_LEN
) {
3359 if (s
[HEX_DIGEST_LEN
] == '=' ||
3360 s
[HEX_DIGEST_LEN
] == '~') {
3361 if (!is_legal_nickname(s
+HEX_DIGEST_LEN
+1))
3367 return (len
>= HEX_DIGEST_LEN
&&
3368 strspn(s
,HEX_CHARACTERS
)==HEX_DIGEST_LEN
);
3371 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
3372 * hold a human-readable description of a node with identity digest
3373 * <b>id_digest</b>, named-status <b>is_named</b>, nickname <b>nickname</b>,
3374 * and address <b>addr</b> or <b>addr32h</b>.
3376 * The <b>nickname</b> and <b>addr</b> fields are optional and may be set to
3377 * NULL. The <b>addr32h</b> field is optional and may be set to 0.
3379 * Return a pointer to the front of <b>buf</b>.
3382 format_node_description(char *buf
,
3383 const char *id_digest
,
3385 const char *nickname
,
3386 const tor_addr_t
*addr
,
3392 return "<NULL BUFFER>";
3395 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, id_digest
, DIGEST_LEN
);
3396 cp
= buf
+1+HEX_DIGEST_LEN
;
3398 buf
[1+HEX_DIGEST_LEN
] = is_named
? '=' : '~';
3399 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, nickname
, MAX_NICKNAME_LEN
+1);
3402 if (addr32h
|| addr
) {
3403 memcpy(cp
, " at ", 4);
3406 tor_addr_to_str(cp
, addr
, TOR_ADDR_BUF_LEN
, 0);
3409 in
.s_addr
= htonl(addr32h
);
3410 tor_inet_ntoa(&in
, cp
, INET_NTOA_BUF_LEN
);
3416 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
3417 * hold a human-readable description of <b>ri</b>.
3420 * Return a pointer to the front of <b>buf</b>.
3423 router_get_description(char *buf
, const routerinfo_t
*ri
)
3427 return format_node_description(buf
,
3428 ri
->cache_info
.identity_digest
,
3429 router_is_named(ri
),
3435 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
3436 * hold a human-readable description of <b>node</b>.
3438 * Return a pointer to the front of <b>buf</b>.
3441 node_get_description(char *buf
, const node_t
*node
)
3443 const char *nickname
= NULL
;
3444 uint32_t addr32h
= 0;
3451 nickname
= node
->rs
->nickname
;
3452 is_named
= node
->rs
->is_named
;
3453 addr32h
= node
->rs
->addr
;
3454 } else if (node
->ri
) {
3455 nickname
= node
->ri
->nickname
;
3456 addr32h
= node
->ri
->addr
;
3459 return format_node_description(buf
,
3467 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
3468 * hold a human-readable description of <b>rs</b>.
3470 * Return a pointer to the front of <b>buf</b>.
3473 routerstatus_get_description(char *buf
, const routerstatus_t
*rs
)
3477 return format_node_description(buf
,
3478 rs
->identity_digest
,
3485 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
3486 * hold a human-readable description of <b>ei</b>.
3488 * Return a pointer to the front of <b>buf</b>.
3491 extend_info_get_description(char *buf
, const extend_info_t
*ei
)
3495 return format_node_description(buf
,
3496 ei
->identity_digest
,
3503 /** Return a human-readable description of the routerinfo_t <b>ri</b>.
3505 * This function is not thread-safe. Each call to this function invalidates
3506 * previous values returned by this function.
3509 router_describe(const routerinfo_t
*ri
)
3511 static char buf
[NODE_DESC_BUF_LEN
];
3512 return router_get_description(buf
, ri
);
3515 /** Return a human-readable description of the node_t <b>node</b>.
3517 * This function is not thread-safe. Each call to this function invalidates
3518 * previous values returned by this function.
3521 node_describe(const node_t
*node
)
3523 static char buf
[NODE_DESC_BUF_LEN
];
3524 return node_get_description(buf
, node
);
3527 /** Return a human-readable description of the routerstatus_t <b>rs</b>.
3529 * This function is not thread-safe. Each call to this function invalidates
3530 * previous values returned by this function.
3533 routerstatus_describe(const routerstatus_t
*rs
)
3535 static char buf
[NODE_DESC_BUF_LEN
];
3536 return routerstatus_get_description(buf
, rs
);
3539 /** Return a human-readable description of the extend_info_t <b>ri</b>.
3541 * This function is not thread-safe. Each call to this function invalidates
3542 * previous values returned by this function.
3545 extend_info_describe(const extend_info_t
*ei
)
3547 static char buf
[NODE_DESC_BUF_LEN
];
3548 return extend_info_get_description(buf
, ei
);
3551 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
3552 * verbose representation of the identity of <b>router</b>. The format is:
3554 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
3555 * A "=" if the router is named; a "~" if it is not.
3556 * The router's nickname.
3559 router_get_verbose_nickname(char *buf
, const routerinfo_t
*router
)
3561 const char *good_digest
= networkstatus_get_router_digest_by_nickname(
3563 int is_named
= good_digest
&& tor_memeq(good_digest
,
3564 router
->cache_info
.identity_digest
,
3567 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, router
->cache_info
.identity_digest
,
3569 buf
[1+HEX_DIGEST_LEN
] = is_named
? '=' : '~';
3570 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, router
->nickname
, MAX_NICKNAME_LEN
+1);
3573 /** Forget that we have issued any router-related warnings, so that we'll
3574 * warn again if we see the same errors. */
3576 router_reset_warnings(void)
3578 if (warned_nonexistent_family
) {
3579 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
3580 smartlist_clear(warned_nonexistent_family
);
3584 /** Given a router purpose, convert it to a string. Don't call this on
3585 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
3586 * know its string representation. */
3588 router_purpose_to_string(uint8_t p
)
3592 case ROUTER_PURPOSE_GENERAL
: return "general";
3593 case ROUTER_PURPOSE_BRIDGE
: return "bridge";
3594 case ROUTER_PURPOSE_CONTROLLER
: return "controller";
3601 /** Given a string, convert it to a router purpose. */
3603 router_purpose_from_string(const char *s
)
3605 if (!strcmp(s
, "general"))
3606 return ROUTER_PURPOSE_GENERAL
;
3607 else if (!strcmp(s
, "bridge"))
3608 return ROUTER_PURPOSE_BRIDGE
;
3609 else if (!strcmp(s
, "controller"))
3610 return ROUTER_PURPOSE_CONTROLLER
;
3612 return ROUTER_PURPOSE_UNKNOWN
;
3615 /** Release all static resources held in router.c */
3617 router_free_all(void)
3619 crypto_pk_free(onionkey
);
3620 crypto_pk_free(lastonionkey
);
3621 crypto_pk_free(server_identitykey
);
3622 crypto_pk_free(client_identitykey
);
3623 tor_mutex_free(key_lock
);
3624 routerinfo_free(desc_routerinfo
);
3625 extrainfo_free(desc_extrainfo
);
3626 crypto_pk_free(authority_signing_key
);
3627 authority_cert_free(authority_key_certificate
);
3628 crypto_pk_free(legacy_signing_key
);
3629 authority_cert_free(legacy_key_certificate
);
3631 memwipe(&curve25519_onion_key
, 0, sizeof(curve25519_onion_key
));
3632 memwipe(&last_curve25519_onion_key
, 0, sizeof(last_curve25519_onion_key
));
3634 if (warned_nonexistent_family
) {
3635 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
3636 smartlist_free(warned_nonexistent_family
);
3640 /** Return a smartlist of tor_addr_port_t's with all the OR ports of
3641 <b>ri</b>. Note that freeing of the items in the list as well as
3642 the smartlist itself is the callers responsibility. */
3644 router_get_all_orports(const routerinfo_t
*ri
)
3648 memset(&fake_node
, 0, sizeof(fake_node
));
3649 /* we don't modify ri, fake_node is passed as a const node_t *
3651 fake_node
.ri
= (routerinfo_t
*)ri
;
3652 return node_get_all_orports(&fake_node
);