1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
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"
29 #include "routerlist.h"
30 #include "routerparse.h"
31 #include "statefile.h"
32 #include "transports.h"
33 #include "routerset.h"
37 * \brief OR functionality, including key maintenance, generating
38 * and uploading server descriptors, retrying OR connections.
41 extern long stats_n_seconds_working
;
43 /************************************************************/
46 * Key management: ORs only.
49 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
51 static tor_mutex_t
*key_lock
=NULL
;
52 static time_t onionkey_set_at
=0; /**< When was onionkey last changed? */
53 /** Current private onionskin decryption key: used to decode CREATE cells. */
54 static crypto_pk_t
*onionkey
=NULL
;
55 /** Previous private onionskin decryption key: used to decode CREATE cells
56 * generated by clients that have an older version of our descriptor. */
57 static crypto_pk_t
*lastonionkey
=NULL
;
58 #ifdef CURVE25519_ENABLED
59 /** Current private ntor secret key: used to perform the ntor handshake. */
60 static curve25519_keypair_t curve25519_onion_key
;
61 /** Previous private ntor secret key: used to perform the ntor handshake
62 * with clients that have an older version of our descriptor. */
63 static curve25519_keypair_t last_curve25519_onion_key
;
65 /** Private server "identity key": used to sign directory info and TLS
66 * certificates. Never changes. */
67 static crypto_pk_t
*server_identitykey
=NULL
;
68 /** Digest of server_identitykey. */
69 static char server_identitykey_digest
[DIGEST_LEN
];
70 /** Private client "identity key": used to sign bridges' and clients'
71 * outbound TLS certificates. Regenerated on startup and on IP address
73 static crypto_pk_t
*client_identitykey
=NULL
;
74 /** Signing key used for v3 directory material; only set for authorities. */
75 static crypto_pk_t
*authority_signing_key
= NULL
;
76 /** Key certificate to authenticate v3 directory material; only set for
78 static authority_cert_t
*authority_key_certificate
= NULL
;
80 /** For emergency V3 authority key migration: An extra signing key that we use
81 * with our old (obsolete) identity key for a while. */
82 static crypto_pk_t
*legacy_signing_key
= NULL
;
83 /** For emergency V3 authority key migration: An extra certificate to
84 * authenticate legacy_signing_key with our obsolete identity key.*/
85 static authority_cert_t
*legacy_key_certificate
= NULL
;
87 /* (Note that v3 authorities also have a separate "authority identity key",
88 * but this key is never actually loaded by the Tor process. Instead, it's
89 * used by tor-gencert to sign new signing keys and make new key
92 /** Replace the current onion key with <b>k</b>. Does not affect
93 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
96 set_onion_key(crypto_pk_t
*k
)
98 if (onionkey
&& crypto_pk_eq_keys(onionkey
, k
)) {
99 /* k is already our onion key; free it and return */
103 tor_mutex_acquire(key_lock
);
104 crypto_pk_free(onionkey
);
106 tor_mutex_release(key_lock
);
107 mark_my_descriptor_dirty("set onion key");
110 /** Return the current onion key. Requires that the onion key has been
111 * loaded or generated. */
115 tor_assert(onionkey
);
119 /** Store a full copy of the current onion key into *<b>key</b>, and a full
120 * copy of the most recent onion key into *<b>last</b>.
123 dup_onion_keys(crypto_pk_t
**key
, crypto_pk_t
**last
)
127 tor_mutex_acquire(key_lock
);
128 tor_assert(onionkey
);
129 *key
= crypto_pk_copy_full(onionkey
);
131 *last
= crypto_pk_copy_full(lastonionkey
);
134 tor_mutex_release(key_lock
);
137 #ifdef CURVE25519_ENABLED
138 /** Return the current secret onion key for the ntor handshake. Must only
139 * be called from the main thread. */
140 static const curve25519_keypair_t
*
141 get_current_curve25519_keypair(void)
143 return &curve25519_onion_key
;
145 /** Return a map from KEYID (the key itself) to keypairs for use in the ntor
146 * handshake. Must only be called from the main thread. */
148 construct_ntor_key_map(void)
150 di_digest256_map_t
*m
= NULL
;
153 curve25519_onion_key
.pubkey
.public_key
,
154 tor_memdup(&curve25519_onion_key
,
155 sizeof(curve25519_keypair_t
)));
156 if (!tor_mem_is_zero((const char*)
157 last_curve25519_onion_key
.pubkey
.public_key
,
158 CURVE25519_PUBKEY_LEN
)) {
160 last_curve25519_onion_key
.pubkey
.public_key
,
161 tor_memdup(&last_curve25519_onion_key
,
162 sizeof(curve25519_keypair_t
)));
167 /** Helper used to deallocate a di_digest256_map_t returned by
168 * construct_ntor_key_map. */
170 ntor_key_map_free_helper(void *arg
)
172 curve25519_keypair_t
*k
= arg
;
173 memwipe(k
, 0, sizeof(*k
));
176 /** Release all storage from a keymap returned by construct_ntor_key_map. */
178 ntor_key_map_free(di_digest256_map_t
*map
)
182 dimap_free(map
, ntor_key_map_free_helper
);
186 /** Return the time when the onion key was last set. This is either the time
187 * when the process launched, or the time of the most recent key rotation since
188 * the process launched.
191 get_onion_key_set_at(void)
193 return onionkey_set_at
;
196 /** Set the current server identity key to <b>k</b>.
199 set_server_identity_key(crypto_pk_t
*k
)
201 crypto_pk_free(server_identitykey
);
202 server_identitykey
= k
;
203 crypto_pk_get_digest(server_identitykey
, server_identitykey_digest
);
206 /** Make sure that we have set up our identity keys to match or not match as
207 * appropriate, and die with an assertion if we have not. */
209 assert_identity_keys_ok(void)
211 tor_assert(client_identitykey
);
212 if (public_server_mode(get_options())) {
213 /* assert that we have set the client and server keys to be equal */
214 tor_assert(server_identitykey
);
215 tor_assert(crypto_pk_eq_keys(client_identitykey
, server_identitykey
));
217 /* assert that we have set the client and server keys to be unequal */
218 if (server_identitykey
)
219 tor_assert(!crypto_pk_eq_keys(client_identitykey
, server_identitykey
));
223 /** Returns the current server identity key; requires that the key has
224 * been set, and that we are running as a Tor server.
227 get_server_identity_key(void)
229 tor_assert(server_identitykey
);
230 tor_assert(server_mode(get_options()));
231 assert_identity_keys_ok();
232 return server_identitykey
;
235 /** Return true iff the server identity key has been set. */
237 server_identity_key_is_set(void)
239 return server_mode(get_options()) && server_identitykey
!= NULL
;
242 /** Set the current client identity key to <b>k</b>.
245 set_client_identity_key(crypto_pk_t
*k
)
247 crypto_pk_free(client_identitykey
);
248 client_identitykey
= k
;
251 /** Returns the current client identity key for use on outgoing TLS
252 * connections; requires that the key has been set.
255 get_tlsclient_identity_key(void)
257 tor_assert(client_identitykey
);
258 assert_identity_keys_ok();
259 return client_identitykey
;
262 /** Return true iff the client identity key has been set. */
264 client_identity_key_is_set(void)
266 return client_identitykey
!= NULL
;
269 /** Return the key certificate for this v3 (voting) authority, or NULL
270 * if we have no such certificate. */
272 get_my_v3_authority_cert(void)
274 return authority_key_certificate
;
277 /** Return the v3 signing key for this v3 (voting) authority, or NULL
278 * if we have no such key. */
280 get_my_v3_authority_signing_key(void)
282 return authority_signing_key
;
285 /** If we're an authority, and we're using a legacy authority identity key for
286 * emergency migration purposes, return the certificate associated with that
289 get_my_v3_legacy_cert(void)
291 return legacy_key_certificate
;
294 /** If we're an authority, and we're using a legacy authority identity key for
295 * emergency migration purposes, return that key. */
297 get_my_v3_legacy_signing_key(void)
299 return legacy_signing_key
;
302 /** Replace the previous onion key with the current onion key, and generate
303 * a new previous onion key. Immediately after calling this function,
305 * - schedule all previous cpuworkers to shut down _after_ processing
306 * pending work. (This will cause fresh cpuworkers to be generated.)
307 * - generate and upload a fresh routerinfo.
310 rotate_onion_key(void)
312 char *fname
, *fname_prev
;
313 crypto_pk_t
*prkey
= NULL
;
314 or_state_t
*state
= get_or_state();
315 #ifdef CURVE25519_ENABLED
316 curve25519_keypair_t new_curve25519_keypair
;
319 fname
= get_datadir_fname2("keys", "secret_onion_key");
320 fname_prev
= get_datadir_fname2("keys", "secret_onion_key.old");
321 if (file_status(fname
) == FN_FILE
) {
322 if (replace_file(fname
, fname_prev
))
325 if (!(prkey
= crypto_pk_new())) {
326 log_err(LD_GENERAL
,"Error constructing rotated onion key");
329 if (crypto_pk_generate_key(prkey
)) {
330 log_err(LD_BUG
,"Error generating onion key");
333 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
334 log_err(LD_FS
,"Couldn't write generated onion key to \"%s\".", fname
);
337 #ifdef CURVE25519_ENABLED
339 tor_free(fname_prev
);
340 fname
= get_datadir_fname2("keys", "secret_onion_key_ntor");
341 fname_prev
= get_datadir_fname2("keys", "secret_onion_key_ntor.old");
342 if (curve25519_keypair_generate(&new_curve25519_keypair
, 1) < 0)
344 if (file_status(fname
) == FN_FILE
) {
345 if (replace_file(fname
, fname_prev
))
348 if (curve25519_keypair_write_to_file(&new_curve25519_keypair
, fname
,
350 log_err(LD_FS
,"Couldn't write curve25519 onion key to \"%s\".",fname
);
354 log_info(LD_GENERAL
, "Rotating onion key");
355 tor_mutex_acquire(key_lock
);
356 crypto_pk_free(lastonionkey
);
357 lastonionkey
= onionkey
;
359 #ifdef CURVE25519_ENABLED
360 memcpy(&last_curve25519_onion_key
, &curve25519_onion_key
,
361 sizeof(curve25519_keypair_t
));
362 memcpy(&curve25519_onion_key
, &new_curve25519_keypair
,
363 sizeof(curve25519_keypair_t
));
366 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
367 tor_mutex_release(key_lock
);
368 mark_my_descriptor_dirty("rotated onion key");
369 or_state_mark_dirty(state
, get_options()->AvoidDiskWrites
? now
+3600 : 0);
372 log_warn(LD_GENERAL
, "Couldn't rotate onion key.");
374 crypto_pk_free(prkey
);
376 #ifdef CURVE25519_ENABLED
377 memwipe(&new_curve25519_keypair
, 0, sizeof(new_curve25519_keypair
));
380 tor_free(fname_prev
);
383 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
384 * and <b>generate</b> is true, create a new RSA key and save it in
385 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
386 * errors at level <b>severity</b>.
389 init_key_from_file(const char *fname
, int generate
, int severity
)
391 crypto_pk_t
*prkey
= NULL
;
393 if (!(prkey
= crypto_pk_new())) {
394 tor_log(severity
, LD_GENERAL
,"Error constructing key");
398 switch (file_status(fname
)) {
401 tor_log(severity
, LD_FS
,"Can't read key from \"%s\"", fname
);
405 if (!have_lockfile()) {
406 if (try_locking(get_options(), 0)<0) {
407 /* Make sure that --list-fingerprint only creates new keys
408 * if there is no possibility for a deadlock. */
409 tor_log(severity
, LD_FS
, "Another Tor process has locked \"%s\". "
410 "Not writing any new keys.", fname
);
411 /*XXXX The 'other process' might make a key in a second or two;
412 * maybe we should wait for it. */
416 log_info(LD_GENERAL
, "No key found in \"%s\"; generating fresh key.",
418 if (crypto_pk_generate_key(prkey
)) {
419 tor_log(severity
, LD_GENERAL
,"Error generating onion key");
422 if (crypto_pk_check_key(prkey
) <= 0) {
423 tor_log(severity
, LD_GENERAL
,"Generated key seems invalid");
426 log_info(LD_GENERAL
, "Generated key seems valid");
427 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
428 tor_log(severity
, LD_FS
,
429 "Couldn't write generated key to \"%s\".", fname
);
433 log_info(LD_GENERAL
, "No key found in \"%s\"", fname
);
437 if (crypto_pk_read_private_key_from_filename(prkey
, fname
)) {
438 tor_log(severity
, LD_GENERAL
,"Error loading private key.");
448 crypto_pk_free(prkey
);
452 #ifdef CURVE25519_ENABLED
453 /** Load a curve25519 keypair from the file <b>fname</b>, writing it into
454 * <b>keys_out</b>. If the file isn't found and <b>generate</b> is true,
455 * create a new keypair and write it into the file. If there are errors, log
456 * them at level <b>severity</b>. Generate files using <b>tag</b> in their
459 init_curve25519_keypair_from_file(curve25519_keypair_t
*keys_out
,
465 switch (file_status(fname
)) {
468 tor_log(severity
, LD_FS
,"Can't read key from \"%s\"", fname
);
472 if (!have_lockfile()) {
473 if (try_locking(get_options(), 0)<0) {
474 /* Make sure that --list-fingerprint only creates new keys
475 * if there is no possibility for a deadlock. */
476 tor_log(severity
, LD_FS
, "Another Tor process has locked \"%s\". "
477 "Not writing any new keys.", fname
);
478 /*XXXX The 'other process' might make a key in a second or two;
479 * maybe we should wait for it. */
483 log_info(LD_GENERAL
, "No key found in \"%s\"; generating fresh key.",
485 if (curve25519_keypair_generate(keys_out
, 1) < 0)
487 if (curve25519_keypair_write_to_file(keys_out
, fname
, tag
)<0) {
488 tor_log(severity
, LD_FS
,
489 "Couldn't write generated key to \"%s\".", fname
);
490 memset(keys_out
, 0, sizeof(*keys_out
));
494 log_info(LD_GENERAL
, "No key found in \"%s\"", fname
);
500 if (curve25519_keypair_read_from_file(keys_out
, &tag_in
, fname
) < 0) {
501 tor_log(severity
, LD_GENERAL
,"Error loading private key.");
505 if (!tag_in
|| strcmp(tag_in
, tag
)) {
506 tor_log(severity
, LD_GENERAL
,"Unexpected tag %s on private key.",
523 /** Try to load the vote-signing private key and certificate for being a v3
524 * directory authority, and make sure they match. If <b>legacy</b>, load a
525 * legacy key/cert set for emergency key migration; otherwise load the regular
526 * key/cert set. On success, store them into *<b>key_out</b> and
527 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
529 load_authority_keyset(int legacy
, crypto_pk_t
**key_out
,
530 authority_cert_t
**cert_out
)
533 char *fname
= NULL
, *cert
= NULL
;
534 const char *eos
= NULL
;
535 crypto_pk_t
*signing_key
= NULL
;
536 authority_cert_t
*parsed
= NULL
;
538 fname
= get_datadir_fname2("keys",
539 legacy
? "legacy_signing_key" : "authority_signing_key");
540 signing_key
= init_key_from_file(fname
, 0, LOG_INFO
);
542 log_warn(LD_DIR
, "No version 3 directory key found in %s", fname
);
546 fname
= get_datadir_fname2("keys",
547 legacy
? "legacy_certificate" : "authority_certificate");
548 cert
= read_file_to_str(fname
, 0, NULL
);
550 log_warn(LD_DIR
, "Signing key found, but no certificate found in %s",
554 parsed
= authority_cert_parse_from_string(cert
, &eos
);
556 log_warn(LD_DIR
, "Unable to parse certificate in %s", fname
);
559 if (!crypto_pk_eq_keys(signing_key
, parsed
->signing_key
)) {
560 log_warn(LD_DIR
, "Stored signing key does not match signing key in "
565 crypto_pk_free(*key_out
);
566 authority_cert_free(*cert_out
);
568 *key_out
= signing_key
;
577 crypto_pk_free(signing_key
);
578 authority_cert_free(parsed
);
582 /** Load the v3 (voting) authority signing key and certificate, if they are
583 * present. Return -1 if anything is missing, mismatched, or unloadable;
584 * return 0 on success. */
586 init_v3_authority_keys(void)
588 if (load_authority_keyset(0, &authority_signing_key
,
589 &authority_key_certificate
)<0)
592 if (get_options()->V3AuthUseLegacyKey
&&
593 load_authority_keyset(1, &legacy_signing_key
,
594 &legacy_key_certificate
)<0)
600 /** If we're a v3 authority, check whether we have a certificate that's
601 * likely to expire soon. Warn if we do, but not too often. */
603 v3_authority_check_key_expiry(void)
606 static time_t last_warned
= 0;
607 int badness
, time_left
, warn_interval
;
608 if (!authdir_mode_v3(get_options()) || !authority_key_certificate
)
612 expires
= authority_key_certificate
->expires
;
613 time_left
= (int)( expires
- now
);
614 if (time_left
<= 0) {
616 warn_interval
= 60*60;
617 } else if (time_left
<= 24*60*60) {
619 warn_interval
= 60*60;
620 } else if (time_left
<= 24*60*60*7) {
622 warn_interval
= 24*60*60;
623 } else if (time_left
<= 24*60*60*30) {
625 warn_interval
= 24*60*60*5;
630 if (last_warned
+ warn_interval
> now
)
633 if (time_left
<= 0) {
634 tor_log(badness
, LD_DIR
, "Your v3 authority certificate has expired."
635 " Generate a new one NOW.");
636 } else if (time_left
<= 24*60*60) {
637 tor_log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d "
638 "hours; Generate a new one NOW.", time_left
/(60*60));
640 tor_log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d "
641 "days; Generate a new one soon.", time_left
/(24*60*60));
646 /** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
647 * on success, and -1 on failure. */
649 router_initialize_tls_context(void)
651 unsigned int flags
= 0;
652 const or_options_t
*options
= get_options();
653 int lifetime
= options
->SSLKeyLifetime
;
654 if (public_server_mode(options
))
655 flags
|= TOR_TLS_CTX_IS_PUBLIC_SERVER
;
656 if (options
->TLSECGroup
) {
657 if (!strcasecmp(options
->TLSECGroup
, "P256"))
658 flags
|= TOR_TLS_CTX_USE_ECDHE_P256
;
659 else if (!strcasecmp(options
->TLSECGroup
, "P224"))
660 flags
|= TOR_TLS_CTX_USE_ECDHE_P224
;
662 if (!lifetime
) { /* we should guess a good ssl cert lifetime */
664 /* choose between 5 and 365 days, and round to the day */
665 lifetime
= 5*24*3600 + crypto_rand_int(361*24*3600);
666 lifetime
-= lifetime
% (24*3600);
668 if (crypto_rand_int(2)) {
669 /* Half the time we expire at midnight, and half the time we expire
670 * one second before midnight. (Some CAs wobble their expiry times a
671 * bit in practice, perhaps to reduce collision attacks; see ticket
672 * 8443 for details about observed certs in the wild.) */
677 /* It's ok to pass lifetime in as an unsigned int, since
678 * config_parse_interval() checked it. */
679 return tor_tls_context_init(flags
,
680 get_tlsclient_identity_key(),
681 server_mode(options
) ?
682 get_server_identity_key() : NULL
,
683 (unsigned int)lifetime
);
686 /** Initialize all OR private keys, and the TLS context, as necessary.
687 * On OPs, this only initializes the tls context. Return 0 on success,
688 * or -1 if Tor should die.
694 char fingerprint
[FINGERPRINT_LEN
+1];
695 /*nickname<space>fp\n\0 */
696 char fingerprint_line
[MAX_NICKNAME_LEN
+FINGERPRINT_LEN
+3];
699 char digest
[DIGEST_LEN
];
700 char v3_digest
[DIGEST_LEN
];
702 const or_options_t
*options
= get_options();
704 time_t now
= time(NULL
);
706 int v3_digest_set
= 0;
707 authority_cert_t
*cert
= NULL
;
710 key_lock
= tor_mutex_new();
712 /* There are a couple of paths that put us here before we've asked
713 * openssl to initialize itself. */
714 if (crypto_global_init(get_options()->HardwareAccel
,
715 get_options()->AccelName
,
716 get_options()->AccelDir
)) {
717 log_err(LD_BUG
, "Unable to initialize OpenSSL. Exiting.");
721 /* OP's don't need persistent keys; just make up an identity and
722 * initialize the TLS context. */
723 if (!server_mode(options
)) {
724 if (!(prkey
= crypto_pk_new()))
726 if (crypto_pk_generate_key(prkey
)) {
727 crypto_pk_free(prkey
);
730 set_client_identity_key(prkey
);
731 /* Create a TLS context. */
732 if (router_initialize_tls_context() < 0) {
733 log_err(LD_GENERAL
,"Error creating TLS context for Tor client.");
738 /* Make sure DataDirectory exists, and is private. */
739 if (check_private_dir(options
->DataDirectory
, CPD_CREATE
, options
->User
)) {
742 /* Check the key directory. */
743 keydir
= get_datadir_fname("keys");
744 if (check_private_dir(keydir
, CPD_CREATE
, options
->User
)) {
750 /* 1a. Read v3 directory authority key/cert information. */
751 memset(v3_digest
, 0, sizeof(v3_digest
));
752 if (authdir_mode_v3(options
)) {
753 if (init_v3_authority_keys()<0) {
754 log_err(LD_GENERAL
, "We're configured as a V3 authority, but we "
755 "were unable to load our v3 authority keys and certificate! "
756 "Use tor-gencert to generate them. Dying.");
759 cert
= get_my_v3_authority_cert();
761 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key
,
767 /* 1b. Read identity key. Make it if none is found. */
768 keydir
= get_datadir_fname2("keys", "secret_id_key");
769 log_info(LD_GENERAL
,"Reading/making identity key \"%s\"...",keydir
);
770 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
772 if (!prkey
) return -1;
773 set_server_identity_key(prkey
);
775 /* 1c. If we are configured as a bridge, generate a client key;
776 * otherwise, set the server identity key as our client identity
778 if (public_server_mode(options
)) {
779 set_client_identity_key(crypto_pk_dup_key(prkey
)); /* set above */
781 if (!(prkey
= crypto_pk_new()))
783 if (crypto_pk_generate_key(prkey
)) {
784 crypto_pk_free(prkey
);
787 set_client_identity_key(prkey
);
790 /* 2. Read onion key. Make it if none is found. */
791 keydir
= get_datadir_fname2("keys", "secret_onion_key");
792 log_info(LD_GENERAL
,"Reading/making onion key \"%s\"...",keydir
);
793 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
795 if (!prkey
) return -1;
796 set_onion_key(prkey
);
797 if (options
->command
== CMD_RUN_TOR
) {
798 /* only mess with the state file if we're actually running Tor */
799 or_state_t
*state
= get_or_state();
800 if (state
->LastRotatedOnionKey
> 100 && state
->LastRotatedOnionKey
< now
) {
801 /* We allow for some parsing slop, but we don't want to risk accepting
802 * values in the distant future. If we did, we might never rotate the
804 onionkey_set_at
= state
->LastRotatedOnionKey
;
806 /* We have no LastRotatedOnionKey set; either we just created the key
807 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
808 * start the clock ticking now so that we will eventually rotate it even
809 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
810 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
811 or_state_mark_dirty(state
, options
->AvoidDiskWrites
?
812 time(NULL
)+3600 : 0);
816 keydir
= get_datadir_fname2("keys", "secret_onion_key.old");
817 if (!lastonionkey
&& file_status(keydir
) == FN_FILE
) {
818 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
); /* XXXX Why 1? */
820 lastonionkey
= prkey
;
824 #ifdef CURVE25519_ENABLED
826 /* 2b. Load curve25519 onion keys. */
828 keydir
= get_datadir_fname2("keys", "secret_onion_key_ntor");
829 r
= init_curve25519_keypair_from_file(&curve25519_onion_key
,
830 keydir
, 1, LOG_ERR
, "onion");
835 keydir
= get_datadir_fname2("keys", "secret_onion_key_ntor.old");
836 if (tor_mem_is_zero((const char *)
837 last_curve25519_onion_key
.pubkey
.public_key
,
838 CURVE25519_PUBKEY_LEN
) &&
839 file_status(keydir
) == FN_FILE
) {
840 init_curve25519_keypair_from_file(&last_curve25519_onion_key
,
841 keydir
, 0, LOG_ERR
, "onion");
847 /* 3. Initialize link key and TLS context. */
848 if (router_initialize_tls_context() < 0) {
849 log_err(LD_GENERAL
,"Error initializing TLS context");
853 /* 4. Build our router descriptor. */
854 /* Must be called after keys are initialized. */
855 mydesc
= router_get_my_descriptor();
856 if (authdir_mode_handles_descs(options
, ROUTER_PURPOSE_GENERAL
)) {
857 const char *m
= NULL
;
859 /* We need to add our own fingerprint so it gets recognized. */
860 if (dirserv_add_own_fingerprint(options
->Nickname
,
861 get_server_identity_key())) {
862 log_err(LD_GENERAL
,"Error adding own fingerprint to approved set");
866 was_router_added_t added
;
867 ri
= router_parse_entry_from_string(mydesc
, NULL
, 1, 0, NULL
);
869 log_err(LD_GENERAL
,"Generated a routerinfo we couldn't parse.");
872 added
= dirserv_add_descriptor(ri
, &m
, "self");
873 if (!WRA_WAS_ADDED(added
)) {
874 if (!WRA_WAS_OUTDATED(added
)) {
875 log_err(LD_GENERAL
, "Unable to add own descriptor to directory: %s",
876 m
?m
:"<unknown error>");
879 /* If the descriptor was outdated, that's ok. This can happen
880 * when some config options are toggled that affect workers, but
881 * we don't really need new keys yet so the descriptor doesn't
882 * change and the old one is still fresh. */
883 log_info(LD_GENERAL
, "Couldn't add own descriptor to directory "
884 "after key init: %s This is usually not a problem.",
885 m
?m
:"<unknown error>");
891 /* 5. Dump fingerprint to 'fingerprint' */
892 keydir
= get_datadir_fname("fingerprint");
893 log_info(LD_GENERAL
,"Dumping fingerprint to \"%s\"...",keydir
);
894 if (crypto_pk_get_fingerprint(get_server_identity_key(),
895 fingerprint
, 0) < 0) {
896 log_err(LD_GENERAL
,"Error computing fingerprint");
900 tor_assert(strlen(options
->Nickname
) <= MAX_NICKNAME_LEN
);
901 if (tor_snprintf(fingerprint_line
, sizeof(fingerprint_line
),
902 "%s %s\n",options
->Nickname
, fingerprint
) < 0) {
903 log_err(LD_GENERAL
,"Error writing fingerprint line");
907 /* Check whether we need to write the fingerprint file. */
909 if (file_status(keydir
) == FN_FILE
)
910 cp
= read_file_to_str(keydir
, 0, NULL
);
911 if (!cp
|| strcmp(cp
, fingerprint_line
)) {
912 if (write_str_to_file(keydir
, fingerprint_line
, 0)) {
913 log_err(LD_FS
, "Error writing fingerprint line to file");
922 log_notice(LD_GENERAL
,
923 "Your Tor server's identity key fingerprint is '%s %s'",
924 options
->Nickname
, fingerprint
);
925 if (!authdir_mode(options
))
927 /* 6. [authdirserver only] load approved-routers file */
928 if (dirserv_load_fingerprint_file() < 0) {
929 log_err(LD_GENERAL
,"Error loading fingerprints");
932 /* 6b. [authdirserver only] add own key to approved directories. */
933 crypto_pk_get_digest(get_server_identity_key(), digest
);
934 type
= ((options
->V1AuthoritativeDir
? V1_DIRINFO
: NO_DIRINFO
) |
935 (options
->V2AuthoritativeDir
? V2_DIRINFO
: NO_DIRINFO
) |
936 (options
->V3AuthoritativeDir
?
937 (V3_DIRINFO
|MICRODESC_DIRINFO
|EXTRAINFO_DIRINFO
) : NO_DIRINFO
) |
938 (options
->BridgeAuthoritativeDir
? BRIDGE_DIRINFO
: NO_DIRINFO
) |
939 (options
->HSAuthoritativeDir
? HIDSERV_DIRINFO
: NO_DIRINFO
));
941 ds
= router_get_trusteddirserver_by_digest(digest
);
943 ds
= trusted_dir_server_new(options
->Nickname
, NULL
,
944 router_get_advertised_dir_port(options
, 0),
945 router_get_advertised_or_port(options
),
950 log_err(LD_GENERAL
,"We want to be a directory authority, but we "
951 "couldn't add ourselves to the authority list. Failing.");
956 if (ds
->type
!= type
) {
957 log_warn(LD_DIR
, "Configured authority type does not match authority "
958 "type in DirAuthority list. Adjusting. (%d v %d)",
962 if (v3_digest_set
&& (ds
->type
& V3_DIRINFO
) &&
963 tor_memneq(v3_digest
, ds
->v3_identity_digest
, DIGEST_LEN
)) {
964 log_warn(LD_DIR
, "V3 identity key does not match identity declared in "
965 "DirAuthority line. Adjusting.");
966 memcpy(ds
->v3_identity_digest
, v3_digest
, DIGEST_LEN
);
969 if (cert
) { /* add my own cert to the list of known certs */
970 log_info(LD_DIR
, "adding my own v3 cert");
971 if (trusted_dirs_load_certs_from_string(
972 cert
->cache_info
.signed_descriptor_body
,
973 TRUSTED_DIRS_CERTS_SRC_SELF
, 0)<0) {
974 log_warn(LD_DIR
, "Unable to parse my own v3 cert! Failing.");
979 return 0; /* success */
982 /* Keep track of whether we should upload our server descriptor,
983 * and what type of server we are.
986 /** Whether we can reach our ORPort from the outside. */
987 static int can_reach_or_port
= 0;
988 /** Whether we can reach our DirPort from the outside. */
989 static int can_reach_dir_port
= 0;
991 /** Forget what we have learned about our reachability status. */
993 router_reset_reachability(void)
995 can_reach_or_port
= can_reach_dir_port
= 0;
998 /** Return 1 if ORPort is known reachable; else return 0. */
1000 check_whether_orport_reachable(void)
1002 const or_options_t
*options
= get_options();
1003 return options
->AssumeReachable
||
1007 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
1009 check_whether_dirport_reachable(void)
1011 const or_options_t
*options
= get_options();
1012 return !options
->DirPort_set
||
1013 options
->AssumeReachable
||
1014 net_is_disabled() ||
1018 /** Look at a variety of factors, and return 0 if we don't want to
1019 * advertise the fact that we have a DirPort open. Else return the
1020 * DirPort we want to advertise.
1022 * Log a helpful message if we change our mind about whether to publish
1026 decide_to_advertise_dirport(const or_options_t
*options
, uint16_t dir_port
)
1028 static int advertising
=1; /* start out assuming we will advertise */
1030 const char *reason
= NULL
;
1032 /* Section one: reasons to publish or not publish that aren't
1033 * worth mentioning to the user, either because they're obvious
1034 * or because they're normal behavior. */
1036 if (!dir_port
) /* short circuit the rest of the function */
1038 if (authdir_mode(options
)) /* always publish */
1040 if (net_is_disabled())
1042 if (!check_whether_dirport_reachable())
1044 if (!router_get_advertised_dir_port(options
, dir_port
))
1047 /* Section two: reasons to publish or not publish that the user
1048 * might find surprising. These are generally config options that
1049 * make us choose not to publish. */
1051 if (accounting_is_enabled(options
)) {
1052 /* Don't spend bytes for directory traffic if we could end up hibernating,
1053 * but allow DirPort otherwise. Some people set AccountingMax because
1054 * they're confused or to get statistics. */
1055 int interval_length
= accounting_get_interval_length();
1056 uint32_t effective_bw
= get_effective_bwrate(options
);
1057 if (!interval_length
) {
1058 log_warn(LD_BUG
, "An accounting interval is not allowed to be zero "
1059 "seconds long. Raising to 1.");
1060 interval_length
= 1;
1062 log_info(LD_GENERAL
, "Calculating whether to disable dirport: effective "
1063 "bwrate: %u, AccountingMax: "U64_FORMAT
", "
1064 "accounting interval length %d", effective_bw
,
1065 U64_PRINTF_ARG(options
->AccountingMax
),
1068 options
->AccountingMax
/ interval_length
) {
1070 reason
= "AccountingMax enabled";
1072 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
1073 } else if (options
->BandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
||
1074 (options
->RelayBandwidthRate
> 0 &&
1075 options
->RelayBandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
)) {
1076 /* if we're advertising a small amount */
1078 reason
= "BandwidthRate under 50KB";
1081 if (advertising
!= new_choice
) {
1082 if (new_choice
== 1) {
1083 log_notice(LD_DIR
, "Advertising DirPort as %d", dir_port
);
1086 log_notice(LD_DIR
, "Not advertising DirPort (Reason: %s)", reason
);
1088 advertising
= new_choice
;
1091 return advertising
? dir_port
: 0;
1094 /** Allocate and return a new extend_info_t that can be used to build
1095 * a circuit to or through the router <b>r</b>. Use the primary
1096 * address of the router unless <b>for_direct_connect</b> is true, in
1097 * which case the preferred address is used instead. */
1098 static extend_info_t
*
1099 extend_info_from_router(const routerinfo_t
*r
)
1104 router_get_prim_orport(r
, &ap
);
1105 return extend_info_new(r
->nickname
, r
->cache_info
.identity_digest
,
1106 r
->onion_pkey
, r
->onion_curve25519_pkey
,
1110 /** Some time has passed, or we just got new directory information.
1111 * See if we currently believe our ORPort or DirPort to be
1112 * unreachable. If so, launch a new test for it.
1114 * For ORPort, we simply try making a circuit that ends at ourselves.
1115 * Success is noticed in onionskin_answer().
1117 * For DirPort, we make a connection via Tor to our DirPort and ask
1118 * for our own server descriptor.
1119 * Success is noticed in connection_dir_client_reached_eof().
1122 consider_testing_reachability(int test_or
, int test_dir
)
1124 const routerinfo_t
*me
= router_get_my_routerinfo();
1125 int orport_reachable
= check_whether_orport_reachable();
1127 const or_options_t
*options
= get_options();
1131 if (routerset_contains_router(options
->ExcludeNodes
, me
, -1) &&
1132 options
->StrictNodes
) {
1133 /* If we've excluded ourself, and StrictNodes is set, we can't test
1135 if (test_or
|| test_dir
) {
1136 #define SELF_EXCLUDED_WARN_INTERVAL 3600
1137 static ratelim_t warning_limit
=RATELIM_INIT(SELF_EXCLUDED_WARN_INTERVAL
);
1138 log_fn_ratelim(&warning_limit
, LOG_WARN
, LD_CIRC
,
1139 "Can't peform self-tests for this relay: we have "
1140 "listed ourself in ExcludeNodes, and StrictNodes is set. "
1141 "We cannot learn whether we are usable, and will not "
1142 "be able to advertise ourself.");
1147 if (test_or
&& (!orport_reachable
|| !circuit_enough_testing_circs())) {
1148 extend_info_t
*ei
= extend_info_from_router(me
);
1149 /* XXX IPv6 self testing */
1150 log_info(LD_CIRC
, "Testing %s of my ORPort: %s:%d.",
1151 !orport_reachable
? "reachability" : "bandwidth",
1152 me
->address
, me
->or_port
);
1153 circuit_launch_by_extend_info(CIRCUIT_PURPOSE_TESTING
, ei
,
1154 CIRCLAUNCH_NEED_CAPACITY
|CIRCLAUNCH_IS_INTERNAL
);
1155 extend_info_free(ei
);
1158 tor_addr_from_ipv4h(&addr
, me
->addr
);
1159 if (test_dir
&& !check_whether_dirport_reachable() &&
1160 !connection_get_by_type_addr_port_purpose(
1161 CONN_TYPE_DIR
, &addr
, me
->dir_port
,
1162 DIR_PURPOSE_FETCH_SERVERDESC
)) {
1163 /* ask myself, via tor, for my server descriptor. */
1164 directory_initiate_command(me
->address
, &addr
,
1165 me
->or_port
, me
->dir_port
,
1166 me
->cache_info
.identity_digest
,
1167 DIR_PURPOSE_FETCH_SERVERDESC
,
1168 ROUTER_PURPOSE_GENERAL
,
1169 DIRIND_ANON_DIRPORT
, "authority.z", NULL
, 0, 0);
1173 /** Annotate that we found our ORPort reachable. */
1175 router_orport_found_reachable(void)
1177 const routerinfo_t
*me
= router_get_my_routerinfo();
1178 if (!can_reach_or_port
&& me
) {
1179 log_notice(LD_OR
,"Self-testing indicates your ORPort is reachable from "
1180 "the outside. Excellent.%s",
1181 get_options()->PublishServerDescriptor_
!= NO_DIRINFO
?
1182 " Publishing server descriptor." : "");
1183 can_reach_or_port
= 1;
1184 mark_my_descriptor_dirty("ORPort found reachable");
1185 control_event_server_status(LOG_NOTICE
,
1186 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
1187 me
->address
, me
->or_port
);
1191 /** Annotate that we found our DirPort reachable. */
1193 router_dirport_found_reachable(void)
1195 const routerinfo_t
*me
= router_get_my_routerinfo();
1196 if (!can_reach_dir_port
&& me
) {
1197 log_notice(LD_DIRSERV
,"Self-testing indicates your DirPort is reachable "
1198 "from the outside. Excellent.");
1199 can_reach_dir_port
= 1;
1200 if (decide_to_advertise_dirport(get_options(), me
->dir_port
))
1201 mark_my_descriptor_dirty("DirPort found reachable");
1202 control_event_server_status(LOG_NOTICE
,
1203 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
1204 me
->address
, me
->dir_port
);
1208 /** We have enough testing circuits open. Send a bunch of "drop"
1209 * cells down each of them, to exercise our bandwidth. */
1211 router_perform_bandwidth_test(int num_circs
, time_t now
)
1213 int num_cells
= (int)(get_options()->BandwidthRate
* 10 /
1214 CELL_MAX_NETWORK_SIZE
);
1215 int max_cells
= num_cells
< CIRCWINDOW_START
?
1216 num_cells
: CIRCWINDOW_START
;
1217 int cells_per_circuit
= max_cells
/ num_circs
;
1218 origin_circuit_t
*circ
= NULL
;
1220 log_notice(LD_OR
,"Performing bandwidth self-test...done.");
1221 while ((circ
= circuit_get_next_by_pk_and_purpose(circ
, NULL
,
1222 CIRCUIT_PURPOSE_TESTING
))) {
1223 /* dump cells_per_circuit drop cells onto this circ */
1224 int i
= cells_per_circuit
;
1225 if (circ
->base_
.state
!= CIRCUIT_STATE_OPEN
)
1227 circ
->base_
.timestamp_dirty
= now
;
1229 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
1231 NULL
, 0, circ
->cpath
->prev
)<0) {
1232 return; /* stop if error */
1238 /** Return true iff our network is in some sense disabled: either we're
1239 * hibernating, entering hibernation, or */
1241 net_is_disabled(void)
1243 return get_options()->DisableNetwork
|| we_are_hibernating();
1246 /** Return true iff we believe ourselves to be an authoritative
1250 authdir_mode(const or_options_t
*options
)
1252 return options
->AuthoritativeDir
!= 0;
1254 /** Return true iff we believe ourselves to be a v1 authoritative
1258 authdir_mode_v1(const or_options_t
*options
)
1260 return authdir_mode(options
) && options
->V1AuthoritativeDir
!= 0;
1262 /** Return true iff we believe ourselves to be a v2 authoritative
1266 authdir_mode_v2(const or_options_t
*options
)
1268 return authdir_mode(options
) && options
->V2AuthoritativeDir
!= 0;
1270 /** Return true iff we believe ourselves to be a v3 authoritative
1274 authdir_mode_v3(const or_options_t
*options
)
1276 return authdir_mode(options
) && options
->V3AuthoritativeDir
!= 0;
1278 /** Return true iff we are a v1, v2, or v3 directory authority. */
1280 authdir_mode_any_main(const or_options_t
*options
)
1282 return options
->V1AuthoritativeDir
||
1283 options
->V2AuthoritativeDir
||
1284 options
->V3AuthoritativeDir
;
1286 /** Return true if we believe ourselves to be any kind of
1287 * authoritative directory beyond just a hidserv authority. */
1289 authdir_mode_any_nonhidserv(const or_options_t
*options
)
1291 return options
->BridgeAuthoritativeDir
||
1292 authdir_mode_any_main(options
);
1294 /** Return true iff we are an authoritative directory server that is
1295 * authoritative about receiving and serving descriptors of type
1296 * <b>purpose</b> on its dirport. Use -1 for "any purpose". */
1298 authdir_mode_handles_descs(const or_options_t
*options
, int purpose
)
1301 return authdir_mode_any_nonhidserv(options
);
1302 else if (purpose
== ROUTER_PURPOSE_GENERAL
)
1303 return authdir_mode_any_main(options
);
1304 else if (purpose
== ROUTER_PURPOSE_BRIDGE
)
1305 return (options
->BridgeAuthoritativeDir
);
1309 /** Return true iff we are an authoritative directory server that
1310 * publishes its own network statuses.
1313 authdir_mode_publishes_statuses(const or_options_t
*options
)
1315 if (authdir_mode_bridge(options
))
1317 return authdir_mode_any_nonhidserv(options
);
1319 /** Return true iff we are an authoritative directory server that
1320 * tests reachability of the descriptors it learns about.
1323 authdir_mode_tests_reachability(const or_options_t
*options
)
1325 return authdir_mode_handles_descs(options
, -1);
1327 /** Return true iff we believe ourselves to be a bridge authoritative
1331 authdir_mode_bridge(const or_options_t
*options
)
1333 return authdir_mode(options
) && options
->BridgeAuthoritativeDir
!= 0;
1336 /** Return true iff we are trying to be a server.
1339 server_mode(const or_options_t
*options
)
1341 if (options
->ClientOnly
) return 0;
1342 /* XXXX024 I believe we can kill off ORListenAddress here.*/
1343 return (options
->ORPort_set
|| options
->ORListenAddress
);
1346 /** Return true iff we are trying to be a non-bridge server.
1349 public_server_mode(const or_options_t
*options
)
1351 if (!server_mode(options
)) return 0;
1352 return (!options
->BridgeRelay
);
1355 /** Return true iff the combination of options in <b>options</b> and parameters
1356 * in the consensus mean that we don't want to allow exits from circuits
1357 * we got from addresses not known to be servers. */
1359 should_refuse_unknown_exits(const or_options_t
*options
)
1361 if (options
->RefuseUnknownExits
!= -1) {
1362 return options
->RefuseUnknownExits
;
1364 return networkstatus_get_param(NULL
, "refuseunknownexits", 1, 0, 1);
1368 /** Remember if we've advertised ourselves to the dirservers. */
1369 static int server_is_advertised
=0;
1371 /** Return true iff we have published our descriptor lately.
1374 advertised_server_mode(void)
1376 return server_is_advertised
;
1380 * Called with a boolean: set whether we have recently published our
1384 set_server_advertised(int s
)
1386 server_is_advertised
= s
;
1389 /** Return true iff we are trying to proxy client connections. */
1391 proxy_mode(const or_options_t
*options
)
1394 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t
*, p
) {
1395 if (p
->type
== CONN_TYPE_AP_LISTENER
||
1396 p
->type
== CONN_TYPE_AP_TRANS_LISTENER
||
1397 p
->type
== CONN_TYPE_AP_DNS_LISTENER
||
1398 p
->type
== CONN_TYPE_AP_NATD_LISTENER
)
1400 } SMARTLIST_FOREACH_END(p
);
1404 /** Decide if we're a publishable server. We are a publishable server if:
1405 * - We don't have the ClientOnly option set
1407 * - We have the PublishServerDescriptor option set to non-empty
1409 * - We have ORPort set
1411 * - We believe we are reachable from the outside; or
1412 * - We are an authoritative directory server.
1415 decide_if_publishable_server(void)
1417 const or_options_t
*options
= get_options();
1419 if (options
->ClientOnly
)
1421 if (options
->PublishServerDescriptor_
== NO_DIRINFO
)
1423 if (!server_mode(options
))
1425 if (authdir_mode(options
))
1427 if (!router_get_advertised_or_port(options
))
1430 return check_whether_orport_reachable();
1433 /** Initiate server descriptor upload as reasonable (if server is publishable,
1434 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1436 * We need to rebuild the descriptor if it's dirty even if we're not
1437 * uploading, because our reachability testing *uses* our descriptor to
1438 * determine what IP address and ports to test.
1441 consider_publishable_server(int force
)
1445 if (!server_mode(get_options()))
1448 rebuilt
= router_rebuild_descriptor(0);
1449 if (decide_if_publishable_server()) {
1450 set_server_advertised(1);
1452 router_upload_dir_desc_to_dirservers(force
);
1454 set_server_advertised(0);
1458 /** Return the port of the first active listener of type
1459 * <b>listener_type</b>. */
1460 /** XXX not a very good interface. it's not reliable when there are
1461 multiple listeners. */
1463 router_get_active_listener_port_by_type_af(int listener_type
,
1466 /* Iterate all connections, find one of the right kind and return
1467 the port. Not very sophisticated or fast, but effective. */
1468 smartlist_t
*conns
= get_connection_array();
1469 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
1470 if (conn
->type
== listener_type
&& !conn
->marked_for_close
&&
1471 conn
->socket_family
== family
) {
1474 } SMARTLIST_FOREACH_END(conn
);
1479 /** Return the port that we should advertise as our ORPort; this is either
1480 * the one configured in the ORPort option, or the one we actually bound to
1481 * if ORPort is "auto".
1484 router_get_advertised_or_port(const or_options_t
*options
)
1486 return router_get_advertised_or_port_by_af(options
, AF_INET
);
1489 /** As router_get_advertised_or_port(), but allows an address family argument.
1492 router_get_advertised_or_port_by_af(const or_options_t
*options
,
1495 int port
= get_first_advertised_port_by_type_af(CONN_TYPE_OR_LISTENER
,
1499 /* If the port is in 'auto' mode, we have to use
1500 router_get_listener_port_by_type(). */
1501 if (port
== CFG_AUTO_PORT
)
1502 return router_get_active_listener_port_by_type_af(CONN_TYPE_OR_LISTENER
,
1508 /** Return the port that we should advertise as our DirPort;
1509 * this is one of three possibilities:
1510 * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
1511 * the one configured in the DirPort option,
1512 * or the one we actually bound to if DirPort is "auto". */
1514 router_get_advertised_dir_port(const or_options_t
*options
, uint16_t dirport
)
1516 int dirport_configured
= get_primary_dir_port();
1519 if (!dirport_configured
)
1522 if (dirport_configured
== CFG_AUTO_PORT
)
1523 return router_get_active_listener_port_by_type_af(CONN_TYPE_DIR_LISTENER
,
1526 return dirport_configured
;
1530 * OR descriptor generation.
1533 /** My routerinfo. */
1534 static routerinfo_t
*desc_routerinfo
= NULL
;
1536 static extrainfo_t
*desc_extrainfo
= NULL
;
1537 /** Why did we most recently decide to regenerate our descriptor? Used to
1538 * tell the authorities why we're sending it to them. */
1539 static const char *desc_gen_reason
= NULL
;
1540 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1542 static time_t desc_clean_since
= 0;
1543 /** Why did we mark the descriptor dirty? */
1544 static const char *desc_dirty_reason
= NULL
;
1545 /** Boolean: do we need to regenerate the above? */
1546 static int desc_needs_upload
= 0;
1548 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1549 * descriptor successfully yet, try to upload our signed descriptor to
1550 * all the directory servers we know about.
1553 router_upload_dir_desc_to_dirservers(int force
)
1555 const routerinfo_t
*ri
;
1558 size_t desc_len
, extra_len
= 0, total_len
;
1559 dirinfo_type_t auth
= get_options()->PublishServerDescriptor_
;
1561 ri
= router_get_my_routerinfo();
1563 log_info(LD_GENERAL
, "No descriptor; skipping upload");
1566 ei
= router_get_my_extrainfo();
1567 if (auth
== NO_DIRINFO
)
1569 if (!force
&& !desc_needs_upload
)
1572 log_info(LD_OR
, "Uploading relay descriptor to directory authorities%s",
1573 force
? " (forced)" : "");
1575 desc_needs_upload
= 0;
1577 desc_len
= ri
->cache_info
.signed_descriptor_len
;
1578 extra_len
= ei
? ei
->cache_info
.signed_descriptor_len
: 0;
1579 total_len
= desc_len
+ extra_len
+ 1;
1580 msg
= tor_malloc(total_len
);
1581 memcpy(msg
, ri
->cache_info
.signed_descriptor_body
, desc_len
);
1583 memcpy(msg
+desc_len
, ei
->cache_info
.signed_descriptor_body
, extra_len
);
1585 msg
[desc_len
+extra_len
] = 0;
1587 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR
,
1588 (auth
& BRIDGE_DIRINFO
) ?
1589 ROUTER_PURPOSE_BRIDGE
:
1590 ROUTER_PURPOSE_GENERAL
,
1591 auth
, msg
, desc_len
, extra_len
);
1595 /** OR only: Check whether my exit policy says to allow connection to
1596 * conn. Return 0 if we accept; non-0 if we reject.
1599 router_compare_to_my_exit_policy(const tor_addr_t
*addr
, uint16_t port
)
1601 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1604 /* make sure it's resolved to something. this way we can't get a
1606 if (tor_addr_is_null(addr
))
1609 /* look at desc_routerinfo->exit_policy for both the v4 and the v6
1610 * policies. The exit_policy field in desc_routerinfo is a bit unusual,
1611 * in that it contains IPv6 and IPv6 entries. We don't want to look
1612 * at desc_routerinfio->ipv6_exit_policy, since that's a port summary. */
1613 if ((tor_addr_family(addr
) == AF_INET
||
1614 tor_addr_family(addr
) == AF_INET6
)) {
1615 return compare_tor_addr_to_addr_policy(addr
, port
,
1616 desc_routerinfo
->exit_policy
) != ADDR_POLICY_ACCEPTED
;
1618 } else if (tor_addr_family(addr
) == AF_INET6
) {
1619 return get_options()->IPv6Exit
&&
1620 desc_routerinfo
->ipv6_exit_policy
&&
1621 compare_tor_addr_to_short_policy(addr
, port
,
1622 desc_routerinfo
->ipv6_exit_policy
) != ADDR_POLICY_ACCEPTED
;
1629 /** Return true iff my exit policy is reject *:*. Return -1 if we don't
1630 * have a descriptor */
1632 router_my_exit_policy_is_reject_star(void)
1634 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1637 return desc_routerinfo
->policy_is_reject_star
;
1640 /** Return true iff I'm a server and <b>digest</b> is equal to
1641 * my server identity key digest. */
1643 router_digest_is_me(const char *digest
)
1645 return (server_identitykey
&&
1646 tor_memeq(server_identitykey_digest
, digest
, DIGEST_LEN
));
1649 /** Return my identity digest. */
1651 router_get_my_id_digest(void)
1653 return (const uint8_t *)server_identitykey_digest
;
1656 /** Return true iff I'm a server and <b>digest</b> is equal to
1657 * my identity digest. */
1659 router_extrainfo_digest_is_me(const char *digest
)
1661 extrainfo_t
*ei
= router_get_my_extrainfo();
1665 return tor_memeq(digest
,
1666 ei
->cache_info
.signed_descriptor_digest
,
1670 /** A wrapper around router_digest_is_me(). */
1672 router_is_me(const routerinfo_t
*router
)
1674 return router_digest_is_me(router
->cache_info
.identity_digest
);
1677 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1679 router_fingerprint_is_me(const char *fp
)
1681 char digest
[DIGEST_LEN
];
1682 if (strlen(fp
) == HEX_DIGEST_LEN
&&
1683 base16_decode(digest
, sizeof(digest
), fp
, HEX_DIGEST_LEN
) == 0)
1684 return router_digest_is_me(digest
);
1689 /** Return a routerinfo for this OR, rebuilding a fresh one if
1690 * necessary. Return NULL on error, or if called on an OP. */
1691 const routerinfo_t
*
1692 router_get_my_routerinfo(void)
1694 if (!server_mode(get_options()))
1696 if (router_rebuild_descriptor(0))
1698 return desc_routerinfo
;
1701 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1702 * one if necessary. Return NULL on error.
1705 router_get_my_descriptor(void)
1708 if (!router_get_my_routerinfo())
1710 /* Make sure this is nul-terminated. */
1711 tor_assert(desc_routerinfo
->cache_info
.saved_location
== SAVED_NOWHERE
);
1712 body
= signed_descriptor_get_body(&desc_routerinfo
->cache_info
);
1713 tor_assert(!body
[desc_routerinfo
->cache_info
.signed_descriptor_len
]);
1714 log_debug(LD_GENERAL
,"my desc is '%s'", body
);
1718 /** Return the extrainfo document for this OR, or NULL if we have none.
1719 * Rebuilt it (and the server descriptor) if necessary. */
1721 router_get_my_extrainfo(void)
1723 if (!server_mode(get_options()))
1725 if (router_rebuild_descriptor(0))
1727 return desc_extrainfo
;
1730 /** Return a human-readable string describing what triggered us to generate
1731 * our current descriptor, or NULL if we don't know. */
1733 router_get_descriptor_gen_reason(void)
1735 return desc_gen_reason
;
1738 /** A list of nicknames that we've warned about including in our family
1739 * declaration verbatim rather than as digests. */
1740 static smartlist_t
*warned_nonexistent_family
= NULL
;
1742 static int router_guess_address_from_dir_headers(uint32_t *guess
);
1744 /** Make a current best guess at our address, either because
1745 * it's configured in torrc, or because we've learned it from
1746 * dirserver headers. Place the answer in *<b>addr</b> and return
1747 * 0 on success, else return -1 if we have no guess. */
1749 router_pick_published_address(const or_options_t
*options
, uint32_t *addr
)
1751 *addr
= get_last_resolved_addr();
1753 resolve_my_address(LOG_INFO
, options
, addr
, NULL
, NULL
) < 0) {
1754 log_info(LD_CONFIG
, "Could not determine our address locally. "
1755 "Checking if directory headers provide any hints.");
1756 if (router_guess_address_from_dir_headers(addr
) < 0) {
1757 log_info(LD_CONFIG
, "No hints from directory headers either. "
1758 "Will try again later.");
1762 log_info(LD_CONFIG
,"Success: chose address '%s'.", fmt_addr32(*addr
));
1766 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1767 * routerinfo, signed server descriptor, and extra-info document for this OR.
1768 * Return 0 on success, -1 on temporary error.
1771 router_rebuild_descriptor(int force
)
1777 int hibernating
= we_are_hibernating();
1778 const or_options_t
*options
= get_options();
1780 if (desc_clean_since
&& !force
)
1783 if (router_pick_published_address(options
, &addr
) < 0 ||
1784 router_get_advertised_or_port(options
) == 0) {
1785 /* Stop trying to rebuild our descriptor every second. We'll
1786 * learn that it's time to try again when ip_address_changed()
1787 * marks it dirty. */
1788 desc_clean_since
= time(NULL
);
1792 log_info(LD_OR
, "Rebuilding relay descriptor%s", force
? " (forced)" : "");
1794 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
1795 ri
->cache_info
.routerlist_index
= -1;
1796 ri
->address
= tor_dup_ip(addr
);
1797 ri
->nickname
= tor_strdup(options
->Nickname
);
1799 ri
->or_port
= router_get_advertised_or_port(options
);
1800 ri
->dir_port
= router_get_advertised_dir_port(options
, 0);
1801 ri
->cache_info
.published_on
= time(NULL
);
1802 ri
->onion_pkey
= crypto_pk_dup_key(get_onion_key()); /* must invoke from
1804 #ifdef CURVE25519_ENABLED
1805 ri
->onion_curve25519_pkey
=
1806 tor_memdup(&get_current_curve25519_keypair()->pubkey
,
1807 sizeof(curve25519_public_key_t
));
1810 /* For now, at most one IPv6 or-address is being advertised. */
1812 const port_cfg_t
*ipv6_orport
= NULL
;
1813 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t
*, p
) {
1814 if (p
->type
== CONN_TYPE_OR_LISTENER
&&
1815 ! p
->no_advertise
&&
1816 ! p
->bind_ipv4_only
&&
1817 tor_addr_family(&p
->addr
) == AF_INET6
) {
1818 if (! tor_addr_is_internal(&p
->addr
, 0)) {
1822 char addrbuf
[TOR_ADDR_BUF_LEN
];
1824 "Unable to use configured IPv6 address \"%s\" in a "
1825 "descriptor. Skipping it. "
1826 "Try specifying a globally reachable address explicitly. ",
1827 tor_addr_to_str(addrbuf
, &p
->addr
, sizeof(addrbuf
), 1));
1830 } SMARTLIST_FOREACH_END(p
);
1832 tor_addr_copy(&ri
->ipv6_addr
, &ipv6_orport
->addr
);
1833 ri
->ipv6_orport
= ipv6_orport
->port
;
1837 ri
->identity_pkey
= crypto_pk_dup_key(get_server_identity_key());
1838 if (crypto_pk_get_digest(ri
->identity_pkey
,
1839 ri
->cache_info
.identity_digest
)<0) {
1840 routerinfo_free(ri
);
1843 get_platform_str(platform
, sizeof(platform
));
1844 ri
->platform
= tor_strdup(platform
);
1846 /* compute ri->bandwidthrate as the min of various options */
1847 ri
->bandwidthrate
= get_effective_bwrate(options
);
1849 /* and compute ri->bandwidthburst similarly */
1850 ri
->bandwidthburst
= get_effective_bwburst(options
);
1852 ri
->bandwidthcapacity
= hibernating
? 0 : rep_hist_bandwidth_assess();
1854 if (dns_seems_to_be_broken() || has_dns_init_failed()) {
1855 /* DNS is screwed up; don't claim to be an exit. */
1856 policies_exit_policy_append_reject_star(&ri
->exit_policy
);
1858 policies_parse_exit_policy(options
->ExitPolicy
, &ri
->exit_policy
,
1860 options
->ExitPolicyRejectPrivate
,
1861 ri
->address
, !options
->BridgeRelay
);
1863 ri
->policy_is_reject_star
=
1864 policy_is_reject_star(ri
->exit_policy
, AF_INET
) &&
1865 policy_is_reject_star(ri
->exit_policy
, AF_INET6
);
1867 if (options
->IPv6Exit
) {
1868 char *p_tmp
= policy_summarize(ri
->exit_policy
, AF_INET6
);
1870 ri
->ipv6_exit_policy
= parse_short_policy(p_tmp
);
1875 /* XXXX NM NM I belive this is safe to remove */
1876 if (authdir_mode(options
))
1877 ri
->is_valid
= ri
->is_named
= 1; /* believe in yourself */
1880 if (options
->MyFamily
&& ! options
->BridgeRelay
) {
1881 smartlist_t
*family
;
1882 if (!warned_nonexistent_family
)
1883 warned_nonexistent_family
= smartlist_new();
1884 family
= smartlist_new();
1885 ri
->declared_family
= smartlist_new();
1886 smartlist_split_string(family
, options
->MyFamily
, ",",
1887 SPLIT_SKIP_SPACE
|SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1888 SMARTLIST_FOREACH_BEGIN(family
, char *, name
) {
1889 const node_t
*member
;
1890 if (!strcasecmp(name
, options
->Nickname
))
1891 goto skip
; /* Don't list ourself, that's redundant */
1893 member
= node_get_by_nickname(name
, 1);
1895 int is_legal
= is_legal_nickname_or_hexdigest(name
);
1896 if (!smartlist_contains_string(warned_nonexistent_family
, name
) &&
1897 !is_legal_hexdigest(name
)) {
1900 "I have no descriptor for the router named \"%s\" in my "
1901 "declared family; I'll use the nickname as is, but "
1902 "this may confuse clients.", name
);
1904 log_warn(LD_CONFIG
, "There is a router named \"%s\" in my "
1905 "declared family, but that isn't a legal nickname. "
1906 "Skipping it.", escaped(name
));
1907 smartlist_add(warned_nonexistent_family
, tor_strdup(name
));
1910 smartlist_add(ri
->declared_family
, name
);
1913 } else if (router_digest_is_me(member
->identity
)) {
1914 /* Don't list ourself in our own family; that's redundant */
1915 /* XXX shouldn't be possible */
1917 char *fp
= tor_malloc(HEX_DIGEST_LEN
+2);
1919 base16_encode(fp
+1,HEX_DIGEST_LEN
+1,
1920 member
->identity
, DIGEST_LEN
);
1921 smartlist_add(ri
->declared_family
, fp
);
1922 if (smartlist_contains_string(warned_nonexistent_family
, name
))
1923 smartlist_string_remove(warned_nonexistent_family
, name
);
1927 } SMARTLIST_FOREACH_END(name
);
1929 /* remove duplicates from the list */
1930 smartlist_sort_strings(ri
->declared_family
);
1931 smartlist_uniq_strings(ri
->declared_family
);
1933 smartlist_free(family
);
1936 /* Now generate the extrainfo. */
1937 ei
= tor_malloc_zero(sizeof(extrainfo_t
));
1938 ei
->cache_info
.is_extrainfo
= 1;
1939 strlcpy(ei
->nickname
, get_options()->Nickname
, sizeof(ei
->nickname
));
1940 ei
->cache_info
.published_on
= ri
->cache_info
.published_on
;
1941 memcpy(ei
->cache_info
.identity_digest
, ri
->cache_info
.identity_digest
,
1943 if (extrainfo_dump_to_string(&ei
->cache_info
.signed_descriptor_body
,
1944 ei
, get_server_identity_key()) < 0) {
1945 log_warn(LD_BUG
, "Couldn't generate extra-info descriptor.");
1949 ei
->cache_info
.signed_descriptor_len
=
1950 strlen(ei
->cache_info
.signed_descriptor_body
);
1951 router_get_extrainfo_hash(ei
->cache_info
.signed_descriptor_body
,
1952 ei
->cache_info
.signed_descriptor_len
,
1953 ei
->cache_info
.signed_descriptor_digest
);
1956 /* Now finish the router descriptor. */
1958 memcpy(ri
->cache_info
.extra_info_digest
,
1959 ei
->cache_info
.signed_descriptor_digest
,
1962 /* ri was allocated with tor_malloc_zero, so there is no need to
1963 * zero ri->cache_info.extra_info_digest here. */
1965 if (! (ri
->cache_info
.signed_descriptor_body
= router_dump_router_to_string(
1966 ri
, get_server_identity_key()))) {
1967 log_warn(LD_BUG
, "Couldn't generate router descriptor.");
1968 routerinfo_free(ri
);
1972 ri
->cache_info
.signed_descriptor_len
=
1973 strlen(ri
->cache_info
.signed_descriptor_body
);
1976 options
->BridgeRelay
? ROUTER_PURPOSE_BRIDGE
: ROUTER_PURPOSE_GENERAL
;
1977 if (options
->BridgeRelay
) {
1978 /* Bridges shouldn't be able to send their descriptors unencrypted,
1979 anyway, since they don't have a DirPort, and always connect to the
1980 bridge authority anonymously. But just in case they somehow think of
1981 sending them on an unencrypted connection, don't allow them to try. */
1982 ri
->cache_info
.send_unencrypted
= 0;
1984 ei
->cache_info
.send_unencrypted
= 0;
1986 ri
->cache_info
.send_unencrypted
= 1;
1988 ei
->cache_info
.send_unencrypted
= 1;
1991 router_get_router_hash(ri
->cache_info
.signed_descriptor_body
,
1992 strlen(ri
->cache_info
.signed_descriptor_body
),
1993 ri
->cache_info
.signed_descriptor_digest
);
1996 tor_assert(! routerinfo_incompatible_with_extrainfo(ri
, ei
, NULL
, NULL
));
1999 routerinfo_free(desc_routerinfo
);
2000 desc_routerinfo
= ri
;
2001 extrainfo_free(desc_extrainfo
);
2002 desc_extrainfo
= ei
;
2004 desc_clean_since
= time(NULL
);
2005 desc_needs_upload
= 1;
2006 desc_gen_reason
= desc_dirty_reason
;
2007 desc_dirty_reason
= NULL
;
2008 control_event_my_descriptor_changed();
2012 /** If our router descriptor ever goes this long without being regenerated
2013 * because something changed, we force an immediate regenerate-and-upload. */
2014 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
2016 /** If our router descriptor seems to be missing or unacceptable according
2017 * to the authorities, regenerate and reupload it _this_ often. */
2018 #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
2020 /** Mark descriptor out of date if it's been "too long" since we last tried
2023 mark_my_descriptor_dirty_if_too_old(time_t now
)
2025 networkstatus_t
*ns
;
2026 const routerstatus_t
*rs
;
2027 const char *retry_fast_reason
= NULL
; /* Set if we should retry frequently */
2028 const time_t slow_cutoff
= now
- FORCE_REGENERATE_DESCRIPTOR_INTERVAL
;
2029 const time_t fast_cutoff
= now
- FAST_RETRY_DESCRIPTOR_INTERVAL
;
2031 /* If it's already dirty, don't mark it. */
2032 if (! desc_clean_since
)
2035 /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
2036 * time to rebuild it. */
2037 if (desc_clean_since
< slow_cutoff
) {
2038 mark_my_descriptor_dirty("time for new descriptor");
2041 /* Now we see whether we want to be retrying frequently or no. The
2042 * rule here is that we'll retry frequently if we aren't listed in the
2043 * live consensus we have, or if the publication time of the
2044 * descriptor listed for us in the consensus is very old. */
2045 ns
= networkstatus_get_live_consensus(now
);
2047 rs
= networkstatus_vote_find_entry(ns
, server_identitykey_digest
);
2049 retry_fast_reason
= "not listed in consensus";
2050 else if (rs
->published_on
< slow_cutoff
)
2051 retry_fast_reason
= "version listed in consensus is quite old";
2054 if (retry_fast_reason
&& desc_clean_since
< fast_cutoff
)
2055 mark_my_descriptor_dirty(retry_fast_reason
);
2058 /** Call when the current descriptor is out of date. */
2060 mark_my_descriptor_dirty(const char *reason
)
2062 const or_options_t
*options
= get_options();
2063 if (server_mode(options
) && options
->PublishServerDescriptor_
)
2064 log_info(LD_OR
, "Decided to publish new relay descriptor: %s", reason
);
2065 desc_clean_since
= 0;
2066 if (!desc_dirty_reason
)
2067 desc_dirty_reason
= reason
;
2070 /** How frequently will we republish our descriptor because of large (factor
2071 * of 2) shifts in estimated bandwidth? */
2072 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
2074 /** Check whether bandwidth has changed a lot since the last time we announced
2075 * bandwidth. If so, mark our descriptor dirty. */
2077 check_descriptor_bandwidth_changed(time_t now
)
2079 static time_t last_changed
= 0;
2081 if (!desc_routerinfo
)
2084 prev
= desc_routerinfo
->bandwidthcapacity
;
2085 cur
= we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
2086 if ((prev
!= cur
&& (!prev
|| !cur
)) ||
2089 if (last_changed
+MAX_BANDWIDTH_CHANGE_FREQ
< now
) {
2090 log_info(LD_GENERAL
,
2091 "Measured bandwidth has changed; rebuilding descriptor.");
2092 mark_my_descriptor_dirty("bandwidth has changed");
2098 /** Note at log level severity that our best guess of address has changed from
2099 * <b>prev</b> to <b>cur</b>. */
2101 log_addr_has_changed(int severity
,
2102 const tor_addr_t
*prev
,
2103 const tor_addr_t
*cur
,
2106 char addrbuf_prev
[TOR_ADDR_BUF_LEN
];
2107 char addrbuf_cur
[TOR_ADDR_BUF_LEN
];
2109 if (tor_addr_to_str(addrbuf_prev
, prev
, sizeof(addrbuf_prev
), 1) == NULL
)
2110 strlcpy(addrbuf_prev
, "???", TOR_ADDR_BUF_LEN
);
2111 if (tor_addr_to_str(addrbuf_cur
, cur
, sizeof(addrbuf_cur
), 1) == NULL
)
2112 strlcpy(addrbuf_cur
, "???", TOR_ADDR_BUF_LEN
);
2114 if (!tor_addr_is_null(prev
))
2115 log_fn(severity
, LD_GENERAL
,
2116 "Our IP Address has changed from %s to %s; "
2117 "rebuilding descriptor (source: %s).",
2118 addrbuf_prev
, addrbuf_cur
, source
);
2120 log_notice(LD_GENERAL
,
2121 "Guessed our IP address as %s (source: %s).",
2122 addrbuf_cur
, source
);
2125 /** Check whether our own address as defined by the Address configuration
2126 * has changed. This is for routers that get their address from a service
2127 * like dyndns. If our address has changed, mark our descriptor dirty. */
2129 check_descriptor_ipaddress_changed(time_t now
)
2132 const or_options_t
*options
= get_options();
2133 const char *method
= NULL
;
2134 char *hostname
= NULL
;
2138 if (!desc_routerinfo
)
2142 prev
= desc_routerinfo
->addr
;
2143 if (resolve_my_address(LOG_INFO
, options
, &cur
, &method
, &hostname
) < 0) {
2144 log_info(LD_CONFIG
,"options->Address didn't resolve into an IP.");
2150 tor_addr_t tmp_prev
, tmp_cur
;
2152 tor_addr_from_ipv4h(&tmp_prev
, prev
);
2153 tor_addr_from_ipv4h(&tmp_cur
, cur
);
2155 tor_asprintf(&source
, "METHOD=%s%s%s", method
,
2156 hostname
? " HOSTNAME=" : "",
2157 hostname
? hostname
: "");
2159 log_addr_has_changed(LOG_NOTICE
, &tmp_prev
, &tmp_cur
, source
);
2162 ip_address_changed(0);
2168 /** The most recently guessed value of our IP address, based on directory
2170 static tor_addr_t last_guessed_ip
= TOR_ADDR_NULL
;
2172 /** A directory server <b>d_conn</b> told us our IP address is
2173 * <b>suggestion</b>.
2174 * If this address is different from the one we think we are now, and
2175 * if our computer doesn't actually know its IP address, then switch. */
2177 router_new_address_suggestion(const char *suggestion
,
2178 const dir_connection_t
*d_conn
)
2181 uint32_t cur
= 0; /* Current IPv4 address. */
2182 const or_options_t
*options
= get_options();
2184 /* first, learn what the IP address actually is */
2185 if (tor_addr_parse(&addr
, suggestion
) == -1) {
2186 log_debug(LD_DIR
, "Malformed X-Your-Address-Is header %s. Ignoring.",
2187 escaped(suggestion
));
2191 log_debug(LD_DIR
, "Got X-Your-Address-Is: %s.", suggestion
);
2193 if (!server_mode(options
)) {
2194 tor_addr_copy(&last_guessed_ip
, &addr
);
2199 cur
= get_last_resolved_addr();
2201 resolve_my_address(LOG_INFO
, options
, &cur
, NULL
, NULL
) >= 0) {
2202 /* We're all set -- we already know our address. Great. */
2203 tor_addr_from_ipv4h(&last_guessed_ip
, cur
); /* store it in case we
2207 if (tor_addr_is_internal(&addr
, 0)) {
2208 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
2211 if (tor_addr_eq(&d_conn
->base_
.addr
, &addr
)) {
2212 /* Don't believe anybody who says our IP is their IP. */
2213 log_debug(LD_DIR
, "A directory server told us our IP address is %s, "
2214 "but he's just reporting his own IP address. Ignoring.",
2219 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
2220 * us an answer different from what we had the last time we managed to
2222 if (!tor_addr_eq(&last_guessed_ip
, &addr
)) {
2223 control_event_server_status(LOG_NOTICE
,
2224 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
2226 log_addr_has_changed(LOG_NOTICE
, &last_guessed_ip
, &addr
,
2227 d_conn
->base_
.address
);
2228 ip_address_changed(0);
2229 tor_addr_copy(&last_guessed_ip
, &addr
); /* router_rebuild_descriptor()
2234 /** We failed to resolve our address locally, but we'd like to build
2235 * a descriptor and publish / test reachability. If we have a guess
2236 * about our address based on directory headers, answer it and return
2237 * 0; else return -1. */
2239 router_guess_address_from_dir_headers(uint32_t *guess
)
2241 if (!tor_addr_is_null(&last_guessed_ip
)) {
2242 *guess
= tor_addr_to_ipv4h(&last_guessed_ip
);
2248 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
2249 * string describing the version of Tor and the operating system we're
2250 * currently running on.
2253 get_platform_str(char *platform
, size_t len
)
2255 tor_snprintf(platform
, len
, "Tor %s on %s",
2256 get_short_version(), get_uname());
2259 /* XXX need to audit this thing and count fenceposts. maybe
2260 * refactor so we don't have to keep asking if we're
2261 * near the end of maxlen?
2263 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2265 /** OR only: Given a routerinfo for this router, and an identity key to sign
2266 * with, encode the routerinfo as a signed server descriptor and return a new
2267 * string encoding the result, or NULL on failure.
2270 router_dump_router_to_string(routerinfo_t
*router
,
2271 crypto_pk_t
*ident_key
)
2273 /* XXXX025 Make this look entirely at its arguments, and not at globals.
2275 char *onion_pkey
= NULL
; /* Onion key, PEM-encoded. */
2276 char *identity_pkey
= NULL
; /* Identity key, PEM-encoded. */
2277 char digest
[DIGEST_LEN
];
2278 char published
[ISO_TIME_LEN
+1];
2279 char fingerprint
[FINGERPRINT_LEN
+1];
2280 int has_extra_info_digest
;
2281 char extra_info_digest
[HEX_DIGEST_LEN
+1];
2282 size_t onion_pkeylen
, identity_pkeylen
;
2283 char *family_line
= NULL
;
2284 char *extra_or_address
= NULL
;
2285 const or_options_t
*options
= get_options();
2286 smartlist_t
*chunks
= NULL
;
2287 char *output
= NULL
;
2289 /* Make sure the identity key matches the one in the routerinfo. */
2290 if (!crypto_pk_eq_keys(ident_key
, router
->identity_pkey
)) {
2291 log_warn(LD_BUG
,"Tried to sign a router with a private key that didn't "
2292 "match router's public key!");
2296 /* record our fingerprint, so we can include it in the descriptor */
2297 if (crypto_pk_get_fingerprint(router
->identity_pkey
, fingerprint
, 1)<0) {
2298 log_err(LD_BUG
,"Error computing fingerprint");
2302 /* PEM-encode the onion key */
2303 if (crypto_pk_write_public_key_to_string(router
->onion_pkey
,
2304 &onion_pkey
,&onion_pkeylen
)<0) {
2305 log_warn(LD_BUG
,"write onion_pkey to string failed!");
2309 /* PEM-encode the identity key */
2310 if (crypto_pk_write_public_key_to_string(router
->identity_pkey
,
2311 &identity_pkey
,&identity_pkeylen
)<0) {
2312 log_warn(LD_BUG
,"write identity_pkey to string failed!");
2316 /* Encode the publication time. */
2317 format_iso_time(published
, router
->cache_info
.published_on
);
2319 if (router
->declared_family
&& smartlist_len(router
->declared_family
)) {
2320 char *family
= smartlist_join_strings(router
->declared_family
,
2322 tor_asprintf(&family_line
, "family %s\n", family
);
2325 family_line
= tor_strdup("");
2328 has_extra_info_digest
=
2329 ! tor_digest_is_zero(router
->cache_info
.extra_info_digest
);
2331 if (has_extra_info_digest
) {
2332 base16_encode(extra_info_digest
, sizeof(extra_info_digest
),
2333 router
->cache_info
.extra_info_digest
, DIGEST_LEN
);
2336 if (router
->ipv6_orport
&&
2337 tor_addr_family(&router
->ipv6_addr
) == AF_INET6
) {
2338 char addr
[TOR_ADDR_BUF_LEN
];
2340 a
= tor_addr_to_str(addr
, &router
->ipv6_addr
, sizeof(addr
), 1);
2342 tor_asprintf(&extra_or_address
,
2343 "or-address %s:%d\n", a
, router
->ipv6_orport
);
2344 log_debug(LD_OR
, "My or-address line is <%s>", extra_or_address
);
2348 chunks
= smartlist_new();
2349 /* Generate the easy portion of the router descriptor. */
2350 smartlist_add_asprintf(chunks
,
2351 "router %s %s %d 0 %d\n"
2354 "protocols Link 1 2 Circuit 1\n"
2358 "bandwidth %d %d %d\n"
2366 decide_to_advertise_dirport(options
, router
->dir_port
),
2367 extra_or_address
? extra_or_address
: "",
2371 stats_n_seconds_working
,
2372 (int) router
->bandwidthrate
,
2373 (int) router
->bandwidthburst
,
2374 (int) router
->bandwidthcapacity
,
2375 has_extra_info_digest
? "extra-info-digest " : "",
2376 has_extra_info_digest
? extra_info_digest
: "",
2377 has_extra_info_digest
? "\n" : "",
2378 options
->DownloadExtraInfo
? "caches-extra-info\n" : "",
2379 onion_pkey
, identity_pkey
,
2381 we_are_hibernating() ? "hibernating 1\n" : "",
2382 options
->HidServDirectoryV2
? "hidden-service-dir\n" : "",
2383 options
->AllowSingleHopExits
? "allow-single-hop-exits\n" : "");
2385 if (options
->ContactInfo
&& strlen(options
->ContactInfo
)) {
2386 const char *ci
= options
->ContactInfo
;
2387 if (strchr(ci
, '\n') || strchr(ci
, '\r'))
2389 smartlist_add_asprintf(chunks
, "contact %s\n", ci
);
2392 #ifdef CURVE25519_ENABLED
2393 if (router
->onion_curve25519_pkey
) {
2395 base64_encode(kbuf
, sizeof(kbuf
),
2396 (const char *)router
->onion_curve25519_pkey
->public_key
,
2397 CURVE25519_PUBKEY_LEN
);
2398 smartlist_add_asprintf(chunks
, "ntor-onion-key %s", kbuf
);
2402 /* Write the exit policy to the end of 's'. */
2403 if (!router
->exit_policy
|| !smartlist_len(router
->exit_policy
)) {
2404 smartlist_add(chunks
, tor_strdup("reject *:*\n"));
2405 } else if (router
->exit_policy
) {
2407 for (i
= 0; i
< smartlist_len(router
->exit_policy
); ++i
) {
2408 char pbuf
[POLICY_BUF_LEN
];
2409 addr_policy_t
*tmpe
= smartlist_get(router
->exit_policy
, i
);
2411 if (tor_addr_family(&tmpe
->addr
) == AF_INET6
)
2412 continue; /* Don't include IPv6 parts of address policy */
2413 result
= policy_write_item(pbuf
, POLICY_BUF_LEN
, tmpe
, 1);
2415 log_warn(LD_BUG
,"descriptor policy_write_item ran out of room!");
2418 smartlist_add_asprintf(chunks
, "%s\n", pbuf
);
2422 if (router
->ipv6_exit_policy
) {
2423 char *p6
= write_short_policy(router
->ipv6_exit_policy
);
2424 if (p6
&& strcmp(p6
, "reject 1-65535")) {
2425 smartlist_add_asprintf(chunks
,
2426 "ipv6-policy %s\n", p6
);
2431 /* Sign the descriptor */
2432 smartlist_add(chunks
, tor_strdup("router-signature\n"));
2434 crypto_digest_smartlist(digest
, DIGEST_LEN
, chunks
, "", DIGEST_SHA1
);
2436 note_crypto_pk_op(SIGN_RTR
);
2439 if (!(sig
= router_get_dirobj_signature(digest
, DIGEST_LEN
, ident_key
))) {
2440 log_warn(LD_BUG
, "Couldn't sign router descriptor");
2443 smartlist_add(chunks
, sig
);
2446 /* include a last '\n' */
2447 smartlist_add(chunks
, tor_strdup("\n"));
2449 output
= smartlist_join_strings(chunks
, "", 0, NULL
);
2451 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2455 routerinfo_t
*ri_tmp
;
2456 cp
= s_dup
= tor_strdup(output
);
2457 ri_tmp
= router_parse_entry_from_string(cp
, NULL
, 1, 0, NULL
);
2460 "We just generated a router descriptor we can't parse.");
2461 log_err(LD_BUG
, "Descriptor was: <<%s>>", output
);
2465 routerinfo_free(ri_tmp
);
2472 tor_free(output
); /* sets output to NULL */
2475 SMARTLIST_FOREACH(chunks
, char *, cp
, tor_free(cp
));
2476 smartlist_free(chunks
);
2478 tor_free(family_line
);
2479 tor_free(onion_pkey
);
2480 tor_free(identity_pkey
);
2481 tor_free(extra_or_address
);
2486 /** Copy the primary (IPv4) OR port (IP address and TCP port) for
2487 * <b>router</b> into *<b>ap_out</b>. */
2489 router_get_prim_orport(const routerinfo_t
*router
, tor_addr_port_t
*ap_out
)
2491 tor_assert(ap_out
!= NULL
);
2492 tor_addr_from_ipv4h(&ap_out
->addr
, router
->addr
);
2493 ap_out
->port
= router
->or_port
;
2496 /** Return 1 if any of <b>router</b>'s addresses are <b>addr</b>.
2497 * Otherwise return 0. */
2499 router_has_addr(const routerinfo_t
*router
, const tor_addr_t
*addr
)
2502 tor_addr_eq_ipv4h(addr
, router
->addr
) ||
2503 tor_addr_eq(&router
->ipv6_addr
, addr
);
2507 router_has_orport(const routerinfo_t
*router
, const tor_addr_port_t
*orport
)
2510 (tor_addr_eq_ipv4h(&orport
->addr
, router
->addr
) &&
2511 orport
->port
== router
->or_port
) ||
2512 (tor_addr_eq(&orport
->addr
, &router
->ipv6_addr
) &&
2513 orport
->port
== router
->ipv6_orport
);
2516 /** Load the contents of <b>filename</b>, find the last line starting with
2517 * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
2518 * the past or more than 1 hour in the future with respect to <b>now</b>,
2519 * and write the file contents starting with that line to *<b>out</b>.
2520 * Return 1 for success, 0 if the file does not exist, or -1 if the file
2521 * does not contain a line matching these criteria or other failure. */
2523 load_stats_file(const char *filename
, const char *end_line
, time_t now
,
2527 char *fname
= get_datadir_fname(filename
);
2528 char *contents
, *start
= NULL
, *tmp
, timestr
[ISO_TIME_LEN
+1];
2530 switch (file_status(fname
)) {
2532 /* X022 Find an alternative to reading the whole file to memory. */
2533 if ((contents
= read_file_to_str(fname
, 0, NULL
))) {
2534 tmp
= strstr(contents
, end_line
);
2535 /* Find last block starting with end_line */
2538 tmp
= strstr(tmp
+ 1, end_line
);
2542 if (strlen(start
) < strlen(end_line
) + 1 + sizeof(timestr
))
2544 strlcpy(timestr
, start
+ 1 + strlen(end_line
), sizeof(timestr
));
2545 if (parse_iso_time(timestr
, &written
) < 0)
2547 if (written
< now
- (25*60*60) || written
> now
+ (1*60*60))
2549 *out
= tor_strdup(start
);
2567 /** Write the contents of <b>extrainfo</b> and aggregated statistics to
2568 * *<b>s_out</b>, signing them with <b>ident_key</b>. Return 0 on
2569 * success, negative on failure. */
2571 extrainfo_dump_to_string(char **s_out
, extrainfo_t
*extrainfo
,
2572 crypto_pk_t
*ident_key
)
2574 const or_options_t
*options
= get_options();
2575 char identity
[HEX_DIGEST_LEN
+1];
2576 char published
[ISO_TIME_LEN
+1];
2577 char digest
[DIGEST_LEN
];
2578 char *bandwidth_usage
;
2580 static int write_stats_to_extrainfo
= 1;
2581 char sig
[DIROBJ_MAX_SIG_LEN
+1];
2582 char *s
, *pre
, *contents
, *cp
, *s_dup
= NULL
;
2583 time_t now
= time(NULL
);
2584 smartlist_t
*chunks
= smartlist_new();
2585 extrainfo_t
*ei_tmp
= NULL
;
2587 base16_encode(identity
, sizeof(identity
),
2588 extrainfo
->cache_info
.identity_digest
, DIGEST_LEN
);
2589 format_iso_time(published
, extrainfo
->cache_info
.published_on
);
2590 bandwidth_usage
= rep_hist_get_bandwidth_lines();
2592 tor_asprintf(&pre
, "extra-info %s %s\npublished %s\n%s",
2593 extrainfo
->nickname
, identity
,
2594 published
, bandwidth_usage
);
2595 tor_free(bandwidth_usage
);
2596 smartlist_add(chunks
, pre
);
2598 if (geoip_is_loaded(AF_INET
))
2599 smartlist_add_asprintf(chunks
, "geoip-db-digest %s\n",
2600 geoip_db_digest(AF_INET
));
2601 if (geoip_is_loaded(AF_INET6
))
2602 smartlist_add_asprintf(chunks
, "geoip6-db-digest %s\n",
2603 geoip_db_digest(AF_INET6
));
2605 if (options
->ExtraInfoStatistics
&& write_stats_to_extrainfo
) {
2606 log_info(LD_GENERAL
, "Adding stats to extra-info descriptor.");
2607 if (options
->DirReqStatistics
&&
2608 load_stats_file("stats"PATH_SEPARATOR
"dirreq-stats",
2609 "dirreq-stats-end", now
, &contents
) > 0) {
2610 smartlist_add(chunks
, contents
);
2612 if (options
->EntryStatistics
&&
2613 load_stats_file("stats"PATH_SEPARATOR
"entry-stats",
2614 "entry-stats-end", now
, &contents
) > 0) {
2615 smartlist_add(chunks
, contents
);
2617 if (options
->CellStatistics
&&
2618 load_stats_file("stats"PATH_SEPARATOR
"buffer-stats",
2619 "cell-stats-end", now
, &contents
) > 0) {
2620 smartlist_add(chunks
, contents
);
2622 if (options
->ExitPortStatistics
&&
2623 load_stats_file("stats"PATH_SEPARATOR
"exit-stats",
2624 "exit-stats-end", now
, &contents
) > 0) {
2625 smartlist_add(chunks
, contents
);
2627 if (options
->ConnDirectionStatistics
&&
2628 load_stats_file("stats"PATH_SEPARATOR
"conn-stats",
2629 "conn-bi-direct", now
, &contents
) > 0) {
2630 smartlist_add(chunks
, contents
);
2634 /* Add information about the pluggable transports we support. */
2635 if (options
->ServerTransportPlugin
) {
2636 char *pluggable_transports
= pt_get_extra_info_descriptor_string();
2637 if (pluggable_transports
)
2638 smartlist_add(chunks
, pluggable_transports
);
2641 if (should_record_bridge_info(options
) && write_stats_to_extrainfo
) {
2642 const char *bridge_stats
= geoip_get_bridge_stats_extrainfo(now
);
2644 smartlist_add(chunks
, tor_strdup(bridge_stats
));
2648 smartlist_add(chunks
, tor_strdup("router-signature\n"));
2649 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
2651 while (strlen(s
) > MAX_EXTRAINFO_UPLOAD_SIZE
- DIROBJ_MAX_SIG_LEN
) {
2652 /* So long as there are at least two chunks (one for the initial
2653 * extra-info line and one for the router-signature), we can keep removing
2655 if (smartlist_len(chunks
) > 2) {
2656 /* We remove the next-to-last element (remember, len-1 is the last
2657 element), since we need to keep the router-signature element. */
2658 int idx
= smartlist_len(chunks
) - 2;
2659 char *e
= smartlist_get(chunks
, idx
);
2660 smartlist_del_keeporder(chunks
, idx
);
2661 log_warn(LD_GENERAL
, "We just generated an extra-info descriptor "
2662 "with statistics that exceeds the 50 KB "
2663 "upload limit. Removing last added "
2667 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
2669 log_warn(LD_BUG
, "We just generated an extra-info descriptors that "
2670 "exceeds the 50 KB upload limit.");
2675 memset(sig
, 0, sizeof(sig
));
2676 if (router_get_extrainfo_hash(s
, strlen(s
), digest
) < 0 ||
2677 router_append_dirobj_signature(sig
, sizeof(sig
), digest
, DIGEST_LEN
,
2679 log_warn(LD_BUG
, "Could not append signature to extra-info "
2683 smartlist_add(chunks
, tor_strdup(sig
));
2685 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
2687 cp
= s_dup
= tor_strdup(s
);
2688 ei_tmp
= extrainfo_parse_entry_from_string(cp
, NULL
, 1, NULL
);
2690 if (write_stats_to_extrainfo
) {
2691 log_warn(LD_GENERAL
, "We just generated an extra-info descriptor "
2692 "with statistics that we can't parse. Not "
2693 "adding statistics to this or any future "
2694 "extra-info descriptors.");
2695 write_stats_to_extrainfo
= 0;
2696 result
= extrainfo_dump_to_string(s_out
, extrainfo
, ident_key
);
2699 log_warn(LD_BUG
, "We just generated an extrainfo descriptor we "
2706 s
= NULL
; /* prevent free */
2715 SMARTLIST_FOREACH(chunks
, char *, cp
, tor_free(cp
));
2716 smartlist_free(chunks
);
2718 extrainfo_free(ei_tmp
);
2723 /** Return true iff <b>s</b> is a valid server nickname. (That is, a string
2724 * containing between 1 and MAX_NICKNAME_LEN characters from
2725 * LEGAL_NICKNAME_CHARACTERS.) */
2727 is_legal_nickname(const char *s
)
2732 return len
> 0 && len
<= MAX_NICKNAME_LEN
&&
2733 strspn(s
,LEGAL_NICKNAME_CHARACTERS
) == len
;
2736 /** Return true iff <b>s</b> is a valid server nickname or
2737 * hex-encoded identity-key digest. */
2739 is_legal_nickname_or_hexdigest(const char *s
)
2742 return is_legal_nickname(s
);
2744 return is_legal_hexdigest(s
);
2747 /** Return true iff <b>s</b> is a valid hex-encoded identity-key
2748 * digest. (That is, an optional $, followed by 40 hex characters,
2749 * followed by either nothing, or = or ~ followed by a nickname, or
2750 * a character other than =, ~, or a hex character.)
2753 is_legal_hexdigest(const char *s
)
2757 if (s
[0] == '$') s
++;
2759 if (len
> HEX_DIGEST_LEN
) {
2760 if (s
[HEX_DIGEST_LEN
] == '=' ||
2761 s
[HEX_DIGEST_LEN
] == '~') {
2762 if (!is_legal_nickname(s
+HEX_DIGEST_LEN
+1))
2768 return (len
>= HEX_DIGEST_LEN
&&
2769 strspn(s
,HEX_CHARACTERS
)==HEX_DIGEST_LEN
);
2772 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2773 * hold a human-readable description of a node with identity digest
2774 * <b>id_digest</b>, named-status <b>is_named</b>, nickname <b>nickname</b>,
2775 * and address <b>addr</b> or <b>addr32h</b>.
2777 * The <b>nickname</b> and <b>addr</b> fields are optional and may be set to
2778 * NULL. The <b>addr32h</b> field is optional and may be set to 0.
2780 * Return a pointer to the front of <b>buf</b>.
2783 format_node_description(char *buf
,
2784 const char *id_digest
,
2786 const char *nickname
,
2787 const tor_addr_t
*addr
,
2793 return "<NULL BUFFER>";
2796 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, id_digest
, DIGEST_LEN
);
2797 cp
= buf
+1+HEX_DIGEST_LEN
;
2799 buf
[1+HEX_DIGEST_LEN
] = is_named
? '=' : '~';
2800 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, nickname
, MAX_NICKNAME_LEN
+1);
2803 if (addr32h
|| addr
) {
2804 memcpy(cp
, " at ", 4);
2807 tor_addr_to_str(cp
, addr
, TOR_ADDR_BUF_LEN
, 0);
2810 in
.s_addr
= htonl(addr32h
);
2811 tor_inet_ntoa(&in
, cp
, INET_NTOA_BUF_LEN
);
2817 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2818 * hold a human-readable description of <b>ri</b>.
2821 * Return a pointer to the front of <b>buf</b>.
2824 router_get_description(char *buf
, const routerinfo_t
*ri
)
2828 return format_node_description(buf
,
2829 ri
->cache_info
.identity_digest
,
2830 router_is_named(ri
),
2836 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2837 * hold a human-readable description of <b>node</b>.
2839 * Return a pointer to the front of <b>buf</b>.
2842 node_get_description(char *buf
, const node_t
*node
)
2844 const char *nickname
= NULL
;
2845 uint32_t addr32h
= 0;
2852 nickname
= node
->rs
->nickname
;
2853 is_named
= node
->rs
->is_named
;
2854 addr32h
= node
->rs
->addr
;
2855 } else if (node
->ri
) {
2856 nickname
= node
->ri
->nickname
;
2857 addr32h
= node
->ri
->addr
;
2860 return format_node_description(buf
,
2868 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2869 * hold a human-readable description of <b>rs</b>.
2871 * Return a pointer to the front of <b>buf</b>.
2874 routerstatus_get_description(char *buf
, const routerstatus_t
*rs
)
2878 return format_node_description(buf
,
2879 rs
->identity_digest
,
2886 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2887 * hold a human-readable description of <b>ei</b>.
2889 * Return a pointer to the front of <b>buf</b>.
2892 extend_info_get_description(char *buf
, const extend_info_t
*ei
)
2896 return format_node_description(buf
,
2897 ei
->identity_digest
,
2904 /** Return a human-readable description of the routerinfo_t <b>ri</b>.
2906 * This function is not thread-safe. Each call to this function invalidates
2907 * previous values returned by this function.
2910 router_describe(const routerinfo_t
*ri
)
2912 static char buf
[NODE_DESC_BUF_LEN
];
2913 return router_get_description(buf
, ri
);
2916 /** Return a human-readable description of the node_t <b>node</b>.
2918 * This function is not thread-safe. Each call to this function invalidates
2919 * previous values returned by this function.
2922 node_describe(const node_t
*node
)
2924 static char buf
[NODE_DESC_BUF_LEN
];
2925 return node_get_description(buf
, node
);
2928 /** Return a human-readable description of the routerstatus_t <b>rs</b>.
2930 * This function is not thread-safe. Each call to this function invalidates
2931 * previous values returned by this function.
2934 routerstatus_describe(const routerstatus_t
*rs
)
2936 static char buf
[NODE_DESC_BUF_LEN
];
2937 return routerstatus_get_description(buf
, rs
);
2940 /** Return a human-readable description of the extend_info_t <b>ri</b>.
2942 * This function is not thread-safe. Each call to this function invalidates
2943 * previous values returned by this function.
2946 extend_info_describe(const extend_info_t
*ei
)
2948 static char buf
[NODE_DESC_BUF_LEN
];
2949 return extend_info_get_description(buf
, ei
);
2952 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
2953 * verbose representation of the identity of <b>router</b>. The format is:
2955 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
2956 * A "=" if the router is named; a "~" if it is not.
2957 * The router's nickname.
2960 router_get_verbose_nickname(char *buf
, const routerinfo_t
*router
)
2962 const char *good_digest
= networkstatus_get_router_digest_by_nickname(
2964 int is_named
= good_digest
&& tor_memeq(good_digest
,
2965 router
->cache_info
.identity_digest
,
2968 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, router
->cache_info
.identity_digest
,
2970 buf
[1+HEX_DIGEST_LEN
] = is_named
? '=' : '~';
2971 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, router
->nickname
, MAX_NICKNAME_LEN
+1);
2974 /** Forget that we have issued any router-related warnings, so that we'll
2975 * warn again if we see the same errors. */
2977 router_reset_warnings(void)
2979 if (warned_nonexistent_family
) {
2980 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
2981 smartlist_clear(warned_nonexistent_family
);
2985 /** Given a router purpose, convert it to a string. Don't call this on
2986 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
2987 * know its string representation. */
2989 router_purpose_to_string(uint8_t p
)
2993 case ROUTER_PURPOSE_GENERAL
: return "general";
2994 case ROUTER_PURPOSE_BRIDGE
: return "bridge";
2995 case ROUTER_PURPOSE_CONTROLLER
: return "controller";
3002 /** Given a string, convert it to a router purpose. */
3004 router_purpose_from_string(const char *s
)
3006 if (!strcmp(s
, "general"))
3007 return ROUTER_PURPOSE_GENERAL
;
3008 else if (!strcmp(s
, "bridge"))
3009 return ROUTER_PURPOSE_BRIDGE
;
3010 else if (!strcmp(s
, "controller"))
3011 return ROUTER_PURPOSE_CONTROLLER
;
3013 return ROUTER_PURPOSE_UNKNOWN
;
3016 /** Release all static resources held in router.c */
3018 router_free_all(void)
3020 crypto_pk_free(onionkey
);
3021 crypto_pk_free(lastonionkey
);
3022 crypto_pk_free(server_identitykey
);
3023 crypto_pk_free(client_identitykey
);
3024 tor_mutex_free(key_lock
);
3025 routerinfo_free(desc_routerinfo
);
3026 extrainfo_free(desc_extrainfo
);
3027 crypto_pk_free(authority_signing_key
);
3028 authority_cert_free(authority_key_certificate
);
3029 crypto_pk_free(legacy_signing_key
);
3030 authority_cert_free(legacy_key_certificate
);
3032 #ifdef CURVE25519_ENABLED
3033 memwipe(&curve25519_onion_key
, 0, sizeof(curve25519_onion_key
));
3034 memwipe(&last_curve25519_onion_key
, 0, sizeof(last_curve25519_onion_key
));
3037 if (warned_nonexistent_family
) {
3038 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
3039 smartlist_free(warned_nonexistent_family
);
3043 /** Return a smartlist of tor_addr_port_t's with all the OR ports of
3044 <b>ri</b>. Note that freeing of the items in the list as well as
3045 the smartlist itself is the callers responsibility.
3047 XXX duplicating code from node_get_all_orports(). */
3049 router_get_all_orports(const routerinfo_t
*ri
)
3051 smartlist_t
*sl
= smartlist_new();
3054 if (ri
->addr
!= 0) {
3055 tor_addr_port_t
*ap
= tor_malloc(sizeof(tor_addr_port_t
));
3056 tor_addr_from_ipv4h(&ap
->addr
, ri
->addr
);
3057 ap
->port
= ri
->or_port
;
3058 smartlist_add(sl
, ap
);
3060 if (!tor_addr_is_null(&ri
->ipv6_addr
)) {
3061 tor_addr_port_t
*ap
= tor_malloc(sizeof(tor_addr_port_t
));
3062 tor_addr_copy(&ap
->addr
, &ri
->ipv6_addr
);
3063 ap
->port
= ri
->or_port
;
3064 smartlist_add(sl
, ap
);