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_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 if (public_server_mode(options
))
654 flags
|= TOR_TLS_CTX_IS_PUBLIC_SERVER
;
655 if (options
->TLSECGroup
) {
656 if (!strcasecmp(options
->TLSECGroup
, "P256"))
657 flags
|= TOR_TLS_CTX_USE_ECDHE_P256
;
658 else if (!strcasecmp(options
->TLSECGroup
, "P224"))
659 flags
|= TOR_TLS_CTX_USE_ECDHE_P224
;
662 return tor_tls_context_init(flags
,
663 get_tlsclient_identity_key(),
664 server_mode(get_options()) ?
665 get_server_identity_key() : NULL
,
666 MAX_SSL_KEY_LIFETIME_ADVERTISED
);
669 /** Initialize all OR private keys, and the TLS context, as necessary.
670 * On OPs, this only initializes the tls context. Return 0 on success,
671 * or -1 if Tor should die.
677 char fingerprint
[FINGERPRINT_LEN
+1];
678 /*nickname<space>fp\n\0 */
679 char fingerprint_line
[MAX_NICKNAME_LEN
+FINGERPRINT_LEN
+3];
682 char digest
[DIGEST_LEN
];
683 char v3_digest
[DIGEST_LEN
];
685 const or_options_t
*options
= get_options();
687 time_t now
= time(NULL
);
689 int v3_digest_set
= 0;
690 authority_cert_t
*cert
= NULL
;
693 key_lock
= tor_mutex_new();
695 /* There are a couple of paths that put us here before we've asked
696 * openssl to initialize itself. */
697 if (crypto_global_init(get_options()->HardwareAccel
,
698 get_options()->AccelName
,
699 get_options()->AccelDir
)) {
700 log_err(LD_BUG
, "Unable to initialize OpenSSL. Exiting.");
704 /* OP's don't need persistent keys; just make up an identity and
705 * initialize the TLS context. */
706 if (!server_mode(options
)) {
707 if (!(prkey
= crypto_pk_new()))
709 if (crypto_pk_generate_key(prkey
)) {
710 crypto_pk_free(prkey
);
713 set_client_identity_key(prkey
);
714 /* Create a TLS context. */
715 if (router_initialize_tls_context() < 0) {
716 log_err(LD_GENERAL
,"Error creating TLS context for Tor client.");
721 /* Make sure DataDirectory exists, and is private. */
722 if (check_private_dir(options
->DataDirectory
, CPD_CREATE
, options
->User
)) {
725 /* Check the key directory. */
726 keydir
= get_datadir_fname("keys");
727 if (check_private_dir(keydir
, CPD_CREATE
, options
->User
)) {
733 /* 1a. Read v3 directory authority key/cert information. */
734 memset(v3_digest
, 0, sizeof(v3_digest
));
735 if (authdir_mode_v3(options
)) {
736 if (init_v3_authority_keys()<0) {
737 log_err(LD_GENERAL
, "We're configured as a V3 authority, but we "
738 "were unable to load our v3 authority keys and certificate! "
739 "Use tor-gencert to generate them. Dying.");
742 cert
= get_my_v3_authority_cert();
744 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key
,
750 /* 1b. Read identity key. Make it if none is found. */
751 keydir
= get_datadir_fname2("keys", "secret_id_key");
752 log_info(LD_GENERAL
,"Reading/making identity key \"%s\"...",keydir
);
753 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
755 if (!prkey
) return -1;
756 set_server_identity_key(prkey
);
758 /* 1c. If we are configured as a bridge, generate a client key;
759 * otherwise, set the server identity key as our client identity
761 if (public_server_mode(options
)) {
762 set_client_identity_key(crypto_pk_dup_key(prkey
)); /* set above */
764 if (!(prkey
= crypto_pk_new()))
766 if (crypto_pk_generate_key(prkey
)) {
767 crypto_pk_free(prkey
);
770 set_client_identity_key(prkey
);
773 /* 2. Read onion key. Make it if none is found. */
774 keydir
= get_datadir_fname2("keys", "secret_onion_key");
775 log_info(LD_GENERAL
,"Reading/making onion key \"%s\"...",keydir
);
776 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
778 if (!prkey
) return -1;
779 set_onion_key(prkey
);
780 if (options
->command
== CMD_RUN_TOR
) {
781 /* only mess with the state file if we're actually running Tor */
782 or_state_t
*state
= get_or_state();
783 if (state
->LastRotatedOnionKey
> 100 && state
->LastRotatedOnionKey
< now
) {
784 /* We allow for some parsing slop, but we don't want to risk accepting
785 * values in the distant future. If we did, we might never rotate the
787 onionkey_set_at
= state
->LastRotatedOnionKey
;
789 /* We have no LastRotatedOnionKey set; either we just created the key
790 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
791 * start the clock ticking now so that we will eventually rotate it even
792 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
793 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
794 or_state_mark_dirty(state
, options
->AvoidDiskWrites
?
795 time(NULL
)+3600 : 0);
799 keydir
= get_datadir_fname2("keys", "secret_onion_key.old");
800 if (!lastonionkey
&& file_status(keydir
) == FN_FILE
) {
801 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
); /* XXXX Why 1? */
803 lastonionkey
= prkey
;
807 #ifdef CURVE25519_ENABLED
809 /* 2b. Load curve25519 onion keys. */
811 keydir
= get_datadir_fname2("keys", "secret_onion_key_ntor");
812 r
= init_curve25519_keypair_from_file(&curve25519_onion_key
,
813 keydir
, 1, LOG_ERR
, "onion");
818 keydir
= get_datadir_fname2("keys", "secret_onion_key_ntor.old");
819 if (tor_mem_is_zero((const char *)
820 last_curve25519_onion_key
.pubkey
.public_key
,
821 CURVE25519_PUBKEY_LEN
) &&
822 file_status(keydir
) == FN_FILE
) {
823 init_curve25519_keypair_from_file(&last_curve25519_onion_key
,
824 keydir
, 0, LOG_ERR
, "onion");
830 /* 3. Initialize link key and TLS context. */
831 if (router_initialize_tls_context() < 0) {
832 log_err(LD_GENERAL
,"Error initializing TLS context");
836 /* 4. Build our router descriptor. */
837 /* Must be called after keys are initialized. */
838 mydesc
= router_get_my_descriptor();
839 if (authdir_mode_handles_descs(options
, ROUTER_PURPOSE_GENERAL
)) {
840 const char *m
= NULL
;
842 /* We need to add our own fingerprint so it gets recognized. */
843 if (dirserv_add_own_fingerprint(options
->Nickname
,
844 get_server_identity_key())) {
845 log_err(LD_GENERAL
,"Error adding own fingerprint to approved set");
849 was_router_added_t added
;
850 ri
= router_parse_entry_from_string(mydesc
, NULL
, 1, 0, NULL
);
852 log_err(LD_GENERAL
,"Generated a routerinfo we couldn't parse.");
855 added
= dirserv_add_descriptor(ri
, &m
, "self");
856 if (!WRA_WAS_ADDED(added
)) {
857 if (!WRA_WAS_OUTDATED(added
)) {
858 log_err(LD_GENERAL
, "Unable to add own descriptor to directory: %s",
859 m
?m
:"<unknown error>");
862 /* If the descriptor was outdated, that's ok. This can happen
863 * when some config options are toggled that affect workers, but
864 * we don't really need new keys yet so the descriptor doesn't
865 * change and the old one is still fresh. */
866 log_info(LD_GENERAL
, "Couldn't add own descriptor to directory "
867 "after key init: %s This is usually not a problem.",
868 m
?m
:"<unknown error>");
874 /* 5. Dump fingerprint to 'fingerprint' */
875 keydir
= get_datadir_fname("fingerprint");
876 log_info(LD_GENERAL
,"Dumping fingerprint to \"%s\"...",keydir
);
877 if (crypto_pk_get_fingerprint(get_server_identity_key(),
878 fingerprint
, 0) < 0) {
879 log_err(LD_GENERAL
,"Error computing fingerprint");
883 tor_assert(strlen(options
->Nickname
) <= MAX_NICKNAME_LEN
);
884 if (tor_snprintf(fingerprint_line
, sizeof(fingerprint_line
),
885 "%s %s\n",options
->Nickname
, fingerprint
) < 0) {
886 log_err(LD_GENERAL
,"Error writing fingerprint line");
890 /* Check whether we need to write the fingerprint file. */
892 if (file_status(keydir
) == FN_FILE
)
893 cp
= read_file_to_str(keydir
, 0, NULL
);
894 if (!cp
|| strcmp(cp
, fingerprint_line
)) {
895 if (write_str_to_file(keydir
, fingerprint_line
, 0)) {
896 log_err(LD_FS
, "Error writing fingerprint line to file");
905 log_notice(LD_GENERAL
,
906 "Your Tor server's identity key fingerprint is '%s %s'",
907 options
->Nickname
, fingerprint
);
908 if (!authdir_mode(options
))
910 /* 6. [authdirserver only] load approved-routers file */
911 if (dirserv_load_fingerprint_file() < 0) {
912 log_err(LD_GENERAL
,"Error loading fingerprints");
915 /* 6b. [authdirserver only] add own key to approved directories. */
916 crypto_pk_get_digest(get_server_identity_key(), digest
);
917 type
= ((options
->V1AuthoritativeDir
? V1_DIRINFO
: NO_DIRINFO
) |
918 (options
->V2AuthoritativeDir
? V2_DIRINFO
: NO_DIRINFO
) |
919 (options
->V3AuthoritativeDir
?
920 (V3_DIRINFO
|MICRODESC_DIRINFO
|EXTRAINFO_DIRINFO
) : NO_DIRINFO
) |
921 (options
->BridgeAuthoritativeDir
? BRIDGE_DIRINFO
: NO_DIRINFO
) |
922 (options
->HSAuthoritativeDir
? HIDSERV_DIRINFO
: NO_DIRINFO
));
924 ds
= router_get_trusteddirserver_by_digest(digest
);
926 ds
= trusted_dir_server_new(options
->Nickname
, NULL
,
927 router_get_advertised_dir_port(options
, 0),
928 router_get_advertised_or_port(options
),
933 log_err(LD_GENERAL
,"We want to be a directory authority, but we "
934 "couldn't add ourselves to the authority list. Failing.");
939 if (ds
->type
!= type
) {
940 log_warn(LD_DIR
, "Configured authority type does not match authority "
941 "type in DirServer list. Adjusting. (%d v %d)",
945 if (v3_digest_set
&& (ds
->type
& V3_DIRINFO
) &&
946 tor_memneq(v3_digest
, ds
->v3_identity_digest
, DIGEST_LEN
)) {
947 log_warn(LD_DIR
, "V3 identity key does not match identity declared in "
948 "DirServer line. Adjusting.");
949 memcpy(ds
->v3_identity_digest
, v3_digest
, DIGEST_LEN
);
952 if (cert
) { /* add my own cert to the list of known certs */
953 log_info(LD_DIR
, "adding my own v3 cert");
954 if (trusted_dirs_load_certs_from_string(
955 cert
->cache_info
.signed_descriptor_body
, 0, 0)<0) {
956 log_warn(LD_DIR
, "Unable to parse my own v3 cert! Failing.");
961 return 0; /* success */
964 /* Keep track of whether we should upload our server descriptor,
965 * and what type of server we are.
968 /** Whether we can reach our ORPort from the outside. */
969 static int can_reach_or_port
= 0;
970 /** Whether we can reach our DirPort from the outside. */
971 static int can_reach_dir_port
= 0;
973 /** Forget what we have learned about our reachability status. */
975 router_reset_reachability(void)
977 can_reach_or_port
= can_reach_dir_port
= 0;
980 /** Return 1 if ORPort is known reachable; else return 0. */
982 check_whether_orport_reachable(void)
984 const or_options_t
*options
= get_options();
985 return options
->AssumeReachable
||
989 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
991 check_whether_dirport_reachable(void)
993 const or_options_t
*options
= get_options();
994 return !options
->DirPort_set
||
995 options
->AssumeReachable
||
1000 /** Look at a variety of factors, and return 0 if we don't want to
1001 * advertise the fact that we have a DirPort open. Else return the
1002 * DirPort we want to advertise.
1004 * Log a helpful message if we change our mind about whether to publish
1008 decide_to_advertise_dirport(const or_options_t
*options
, uint16_t dir_port
)
1010 static int advertising
=1; /* start out assuming we will advertise */
1012 const char *reason
= NULL
;
1014 /* Section one: reasons to publish or not publish that aren't
1015 * worth mentioning to the user, either because they're obvious
1016 * or because they're normal behavior. */
1018 if (!dir_port
) /* short circuit the rest of the function */
1020 if (authdir_mode(options
)) /* always publish */
1022 if (net_is_disabled())
1024 if (!check_whether_dirport_reachable())
1026 if (!router_get_advertised_dir_port(options
, dir_port
))
1029 /* Section two: reasons to publish or not publish that the user
1030 * might find surprising. These are generally config options that
1031 * make us choose not to publish. */
1033 if (accounting_is_enabled(options
)) {
1034 /* Don't spend bytes for directory traffic if we could end up hibernating,
1035 * but allow DirPort otherwise. Some people set AccountingMax because
1036 * they're confused or to get statistics. */
1037 int interval_length
= accounting_get_interval_length();
1038 uint32_t effective_bw
= get_effective_bwrate(options
);
1039 if (!interval_length
) {
1040 log_warn(LD_BUG
, "An accounting interval is not allowed to be zero "
1041 "seconds long. Raising to 1.");
1042 interval_length
= 1;
1044 log_info(LD_GENERAL
, "Calculating whether to disable dirport: effective "
1045 "bwrate: %u, AccountingMax: "U64_FORMAT
", "
1046 "accounting interval length %d", effective_bw
,
1047 U64_PRINTF_ARG(options
->AccountingMax
),
1050 options
->AccountingMax
/ interval_length
) {
1052 reason
= "AccountingMax enabled";
1054 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
1055 } else if (options
->BandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
||
1056 (options
->RelayBandwidthRate
> 0 &&
1057 options
->RelayBandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
)) {
1058 /* if we're advertising a small amount */
1060 reason
= "BandwidthRate under 50KB";
1063 if (advertising
!= new_choice
) {
1064 if (new_choice
== 1) {
1065 log_notice(LD_DIR
, "Advertising DirPort as %d", dir_port
);
1068 log_notice(LD_DIR
, "Not advertising DirPort (Reason: %s)", reason
);
1070 advertising
= new_choice
;
1073 return advertising
? dir_port
: 0;
1076 /** Allocate and return a new extend_info_t that can be used to build
1077 * a circuit to or through the router <b>r</b>. Use the primary
1078 * address of the router unless <b>for_direct_connect</b> is true, in
1079 * which case the preferred address is used instead. */
1080 static extend_info_t
*
1081 extend_info_from_router(const routerinfo_t
*r
)
1086 router_get_prim_orport(r
, &ap
);
1087 return extend_info_new(r
->nickname
, r
->cache_info
.identity_digest
,
1088 r
->onion_pkey
, r
->onion_curve25519_pkey
,
1092 /** Some time has passed, or we just got new directory information.
1093 * See if we currently believe our ORPort or DirPort to be
1094 * unreachable. If so, launch a new test for it.
1096 * For ORPort, we simply try making a circuit that ends at ourselves.
1097 * Success is noticed in onionskin_answer().
1099 * For DirPort, we make a connection via Tor to our DirPort and ask
1100 * for our own server descriptor.
1101 * Success is noticed in connection_dir_client_reached_eof().
1104 consider_testing_reachability(int test_or
, int test_dir
)
1106 const routerinfo_t
*me
= router_get_my_routerinfo();
1107 int orport_reachable
= check_whether_orport_reachable();
1109 const or_options_t
*options
= get_options();
1113 if (routerset_contains_router(options
->ExcludeNodes
, me
, -1) &&
1114 options
->StrictNodes
) {
1115 /* If we've excluded ourself, and StrictNodes is set, we can't test
1117 if (test_or
|| test_dir
) {
1118 #define SELF_EXCLUDED_WARN_INTERVAL 3600
1119 static ratelim_t warning_limit
=RATELIM_INIT(SELF_EXCLUDED_WARN_INTERVAL
);
1120 log_fn_ratelim(&warning_limit
, LOG_WARN
, LD_CIRC
,
1121 "Can't peform self-tests for this relay: we have "
1122 "listed ourself in ExcludeNodes, and StrictNodes is set. "
1123 "We cannot learn whether we are usable, and will not "
1124 "be able to advertise ourself.");
1129 if (test_or
&& (!orport_reachable
|| !circuit_enough_testing_circs())) {
1130 extend_info_t
*ei
= extend_info_from_router(me
);
1131 /* XXX IPv6 self testing */
1132 log_info(LD_CIRC
, "Testing %s of my ORPort: %s:%d.",
1133 !orport_reachable
? "reachability" : "bandwidth",
1134 me
->address
, me
->or_port
);
1135 circuit_launch_by_extend_info(CIRCUIT_PURPOSE_TESTING
, ei
,
1136 CIRCLAUNCH_NEED_CAPACITY
|CIRCLAUNCH_IS_INTERNAL
);
1137 extend_info_free(ei
);
1140 tor_addr_from_ipv4h(&addr
, me
->addr
);
1141 if (test_dir
&& !check_whether_dirport_reachable() &&
1142 !connection_get_by_type_addr_port_purpose(
1143 CONN_TYPE_DIR
, &addr
, me
->dir_port
,
1144 DIR_PURPOSE_FETCH_SERVERDESC
)) {
1145 /* ask myself, via tor, for my server descriptor. */
1146 directory_initiate_command(me
->address
, &addr
,
1147 me
->or_port
, me
->dir_port
,
1148 me
->cache_info
.identity_digest
,
1149 DIR_PURPOSE_FETCH_SERVERDESC
,
1150 ROUTER_PURPOSE_GENERAL
,
1151 DIRIND_ANON_DIRPORT
, "authority.z", NULL
, 0, 0);
1155 /** Annotate that we found our ORPort reachable. */
1157 router_orport_found_reachable(void)
1159 const routerinfo_t
*me
= router_get_my_routerinfo();
1160 if (!can_reach_or_port
&& me
) {
1161 log_notice(LD_OR
,"Self-testing indicates your ORPort is reachable from "
1162 "the outside. Excellent.%s",
1163 get_options()->PublishServerDescriptor_
!= NO_DIRINFO
?
1164 " Publishing server descriptor." : "");
1165 can_reach_or_port
= 1;
1166 mark_my_descriptor_dirty("ORPort found reachable");
1167 control_event_server_status(LOG_NOTICE
,
1168 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
1169 me
->address
, me
->or_port
);
1173 /** Annotate that we found our DirPort reachable. */
1175 router_dirport_found_reachable(void)
1177 const routerinfo_t
*me
= router_get_my_routerinfo();
1178 if (!can_reach_dir_port
&& me
) {
1179 log_notice(LD_DIRSERV
,"Self-testing indicates your DirPort is reachable "
1180 "from the outside. Excellent.");
1181 can_reach_dir_port
= 1;
1182 if (decide_to_advertise_dirport(get_options(), me
->dir_port
))
1183 mark_my_descriptor_dirty("DirPort found reachable");
1184 control_event_server_status(LOG_NOTICE
,
1185 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
1186 me
->address
, me
->dir_port
);
1190 /** We have enough testing circuits open. Send a bunch of "drop"
1191 * cells down each of them, to exercise our bandwidth. */
1193 router_perform_bandwidth_test(int num_circs
, time_t now
)
1195 int num_cells
= (int)(get_options()->BandwidthRate
* 10 /
1196 CELL_MAX_NETWORK_SIZE
);
1197 int max_cells
= num_cells
< CIRCWINDOW_START
?
1198 num_cells
: CIRCWINDOW_START
;
1199 int cells_per_circuit
= max_cells
/ num_circs
;
1200 origin_circuit_t
*circ
= NULL
;
1202 log_notice(LD_OR
,"Performing bandwidth self-test...done.");
1203 while ((circ
= circuit_get_next_by_pk_and_purpose(circ
, NULL
,
1204 CIRCUIT_PURPOSE_TESTING
))) {
1205 /* dump cells_per_circuit drop cells onto this circ */
1206 int i
= cells_per_circuit
;
1207 if (circ
->base_
.state
!= CIRCUIT_STATE_OPEN
)
1209 circ
->base_
.timestamp_dirty
= now
;
1211 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
1213 NULL
, 0, circ
->cpath
->prev
)<0) {
1214 return; /* stop if error */
1220 /** Return true iff our network is in some sense disabled: either we're
1221 * hibernating, entering hibernation, or */
1223 net_is_disabled(void)
1225 return get_options()->DisableNetwork
|| we_are_hibernating();
1228 /** Return true iff we believe ourselves to be an authoritative
1232 authdir_mode(const or_options_t
*options
)
1234 return options
->AuthoritativeDir
!= 0;
1236 /** Return true iff we believe ourselves to be a v1 authoritative
1240 authdir_mode_v1(const or_options_t
*options
)
1242 return authdir_mode(options
) && options
->V1AuthoritativeDir
!= 0;
1244 /** Return true iff we believe ourselves to be a v2 authoritative
1248 authdir_mode_v2(const or_options_t
*options
)
1250 return authdir_mode(options
) && options
->V2AuthoritativeDir
!= 0;
1252 /** Return true iff we believe ourselves to be a v3 authoritative
1256 authdir_mode_v3(const or_options_t
*options
)
1258 return authdir_mode(options
) && options
->V3AuthoritativeDir
!= 0;
1260 /** Return true iff we are a v1, v2, or v3 directory authority. */
1262 authdir_mode_any_main(const or_options_t
*options
)
1264 return options
->V1AuthoritativeDir
||
1265 options
->V2AuthoritativeDir
||
1266 options
->V3AuthoritativeDir
;
1268 /** Return true if we believe ourselves to be any kind of
1269 * authoritative directory beyond just a hidserv authority. */
1271 authdir_mode_any_nonhidserv(const or_options_t
*options
)
1273 return options
->BridgeAuthoritativeDir
||
1274 authdir_mode_any_main(options
);
1276 /** Return true iff we are an authoritative directory server that is
1277 * authoritative about receiving and serving descriptors of type
1278 * <b>purpose</b> on its dirport. Use -1 for "any purpose". */
1280 authdir_mode_handles_descs(const or_options_t
*options
, int purpose
)
1283 return authdir_mode_any_nonhidserv(options
);
1284 else if (purpose
== ROUTER_PURPOSE_GENERAL
)
1285 return authdir_mode_any_main(options
);
1286 else if (purpose
== ROUTER_PURPOSE_BRIDGE
)
1287 return (options
->BridgeAuthoritativeDir
);
1291 /** Return true iff we are an authoritative directory server that
1292 * publishes its own network statuses.
1295 authdir_mode_publishes_statuses(const or_options_t
*options
)
1297 if (authdir_mode_bridge(options
))
1299 return authdir_mode_any_nonhidserv(options
);
1301 /** Return true iff we are an authoritative directory server that
1302 * tests reachability of the descriptors it learns about.
1305 authdir_mode_tests_reachability(const or_options_t
*options
)
1307 return authdir_mode_handles_descs(options
, -1);
1309 /** Return true iff we believe ourselves to be a bridge authoritative
1313 authdir_mode_bridge(const or_options_t
*options
)
1315 return authdir_mode(options
) && options
->BridgeAuthoritativeDir
!= 0;
1318 /** Return true iff we are trying to be a server.
1321 server_mode(const or_options_t
*options
)
1323 if (options
->ClientOnly
) return 0;
1324 /* XXXX024 I believe we can kill off ORListenAddress here.*/
1325 return (options
->ORPort_set
|| options
->ORListenAddress
);
1328 /** Return true iff we are trying to be a non-bridge server.
1331 public_server_mode(const or_options_t
*options
)
1333 if (!server_mode(options
)) return 0;
1334 return (!options
->BridgeRelay
);
1337 /** Return true iff the combination of options in <b>options</b> and parameters
1338 * in the consensus mean that we don't want to allow exits from circuits
1339 * we got from addresses not known to be servers. */
1341 should_refuse_unknown_exits(const or_options_t
*options
)
1343 if (options
->RefuseUnknownExits
!= -1) {
1344 return options
->RefuseUnknownExits
;
1346 return networkstatus_get_param(NULL
, "refuseunknownexits", 1, 0, 1);
1350 /** Remember if we've advertised ourselves to the dirservers. */
1351 static int server_is_advertised
=0;
1353 /** Return true iff we have published our descriptor lately.
1356 advertised_server_mode(void)
1358 return server_is_advertised
;
1362 * Called with a boolean: set whether we have recently published our
1366 set_server_advertised(int s
)
1368 server_is_advertised
= s
;
1371 /** Return true iff we are trying to proxy client connections. */
1373 proxy_mode(const or_options_t
*options
)
1376 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t
*, p
) {
1377 if (p
->type
== CONN_TYPE_AP_LISTENER
||
1378 p
->type
== CONN_TYPE_AP_TRANS_LISTENER
||
1379 p
->type
== CONN_TYPE_AP_DNS_LISTENER
||
1380 p
->type
== CONN_TYPE_AP_NATD_LISTENER
)
1382 } SMARTLIST_FOREACH_END(p
);
1386 /** Decide if we're a publishable server. We are a publishable server if:
1387 * - We don't have the ClientOnly option set
1389 * - We have the PublishServerDescriptor option set to non-empty
1391 * - We have ORPort set
1393 * - We believe we are reachable from the outside; or
1394 * - We are an authoritative directory server.
1397 decide_if_publishable_server(void)
1399 const or_options_t
*options
= get_options();
1401 if (options
->ClientOnly
)
1403 if (options
->PublishServerDescriptor_
== NO_DIRINFO
)
1405 if (!server_mode(options
))
1407 if (authdir_mode(options
))
1409 if (!router_get_advertised_or_port(options
))
1412 return check_whether_orport_reachable();
1415 /** Initiate server descriptor upload as reasonable (if server is publishable,
1416 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1418 * We need to rebuild the descriptor if it's dirty even if we're not
1419 * uploading, because our reachability testing *uses* our descriptor to
1420 * determine what IP address and ports to test.
1423 consider_publishable_server(int force
)
1427 if (!server_mode(get_options()))
1430 rebuilt
= router_rebuild_descriptor(0);
1431 if (decide_if_publishable_server()) {
1432 set_server_advertised(1);
1434 router_upload_dir_desc_to_dirservers(force
);
1436 set_server_advertised(0);
1440 /** Return the port of the first active listener of type
1441 * <b>listener_type</b>. */
1442 /** XXX not a very good interface. it's not reliable when there are
1443 multiple listeners. */
1445 router_get_active_listener_port_by_type(int listener_type
)
1447 /* Iterate all connections, find one of the right kind and return
1448 the port. Not very sophisticated or fast, but effective. */
1449 const connection_t
*c
= connection_get_by_type(listener_type
);
1456 /** Return the port that we should advertise as our ORPort; this is either
1457 * the one configured in the ORPort option, or the one we actually bound to
1458 * if ORPort is "auto".
1461 router_get_advertised_or_port(const or_options_t
*options
)
1463 int port
= get_primary_or_port();
1466 /* If the port is in 'auto' mode, we have to use
1467 router_get_listener_port_by_type(). */
1468 if (port
== CFG_AUTO_PORT
)
1469 return router_get_active_listener_port_by_type(CONN_TYPE_OR_LISTENER
);
1474 /** Return the port that we should advertise as our DirPort;
1475 * this is one of three possibilities:
1476 * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
1477 * the one configured in the DirPort option,
1478 * or the one we actually bound to if DirPort is "auto". */
1480 router_get_advertised_dir_port(const or_options_t
*options
, uint16_t dirport
)
1482 int dirport_configured
= get_primary_dir_port();
1485 if (!dirport_configured
)
1488 if (dirport_configured
== CFG_AUTO_PORT
)
1489 return router_get_active_listener_port_by_type(CONN_TYPE_DIR_LISTENER
);
1491 return dirport_configured
;
1495 * OR descriptor generation.
1498 /** My routerinfo. */
1499 static routerinfo_t
*desc_routerinfo
= NULL
;
1501 static extrainfo_t
*desc_extrainfo
= NULL
;
1502 /** Why did we most recently decide to regenerate our descriptor? Used to
1503 * tell the authorities why we're sending it to them. */
1504 static const char *desc_gen_reason
= NULL
;
1505 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1507 static time_t desc_clean_since
= 0;
1508 /** Why did we mark the descriptor dirty? */
1509 static const char *desc_dirty_reason
= NULL
;
1510 /** Boolean: do we need to regenerate the above? */
1511 static int desc_needs_upload
= 0;
1513 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1514 * descriptor successfully yet, try to upload our signed descriptor to
1515 * all the directory servers we know about.
1518 router_upload_dir_desc_to_dirservers(int force
)
1520 const routerinfo_t
*ri
;
1523 size_t desc_len
, extra_len
= 0, total_len
;
1524 dirinfo_type_t auth
= get_options()->PublishServerDescriptor_
;
1526 ri
= router_get_my_routerinfo();
1528 log_info(LD_GENERAL
, "No descriptor; skipping upload");
1531 ei
= router_get_my_extrainfo();
1532 if (auth
== NO_DIRINFO
)
1534 if (!force
&& !desc_needs_upload
)
1537 log_info(LD_OR
, "Uploading relay descriptor to directory authorities%s",
1538 force
? " (forced)" : "");
1540 desc_needs_upload
= 0;
1542 desc_len
= ri
->cache_info
.signed_descriptor_len
;
1543 extra_len
= ei
? ei
->cache_info
.signed_descriptor_len
: 0;
1544 total_len
= desc_len
+ extra_len
+ 1;
1545 msg
= tor_malloc(total_len
);
1546 memcpy(msg
, ri
->cache_info
.signed_descriptor_body
, desc_len
);
1548 memcpy(msg
+desc_len
, ei
->cache_info
.signed_descriptor_body
, extra_len
);
1550 msg
[desc_len
+extra_len
] = 0;
1552 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR
,
1553 (auth
& BRIDGE_DIRINFO
) ?
1554 ROUTER_PURPOSE_BRIDGE
:
1555 ROUTER_PURPOSE_GENERAL
,
1556 auth
, msg
, desc_len
, extra_len
);
1560 /** OR only: Check whether my exit policy says to allow connection to
1561 * conn. Return 0 if we accept; non-0 if we reject.
1564 router_compare_to_my_exit_policy(const tor_addr_t
*addr
, uint16_t port
)
1566 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1569 /* make sure it's resolved to something. this way we can't get a
1571 if (tor_addr_is_null(addr
))
1574 /* look at desc_routerinfo->exit_policy for both the v4 and the v6
1575 * policies. The exit_policy field in desc_routerinfo is a bit unusual,
1576 * in that it contains IPv6 and IPv6 entries. We don't want to look
1577 * at desc_routerinfio->ipv6_exit_policy, since that's a port summary. */
1578 if ((tor_addr_family(addr
) == AF_INET
||
1579 tor_addr_family(addr
) == AF_INET6
)) {
1580 return compare_tor_addr_to_addr_policy(addr
, port
,
1581 desc_routerinfo
->exit_policy
) != ADDR_POLICY_ACCEPTED
;
1583 } else if (tor_addr_family(addr
) == AF_INET6
) {
1584 return get_options()->IPv6Exit
&&
1585 desc_routerinfo
->ipv6_exit_policy
&&
1586 compare_tor_addr_to_short_policy(addr
, port
,
1587 desc_routerinfo
->ipv6_exit_policy
) != ADDR_POLICY_ACCEPTED
;
1594 /** Return true iff my exit policy is reject *:*. Return -1 if we don't
1595 * have a descriptor */
1597 router_my_exit_policy_is_reject_star(void)
1599 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1602 return desc_routerinfo
->policy_is_reject_star
;
1605 /** Return true iff I'm a server and <b>digest</b> is equal to
1606 * my server identity key digest. */
1608 router_digest_is_me(const char *digest
)
1610 return (server_identitykey
&&
1611 tor_memeq(server_identitykey_digest
, digest
, DIGEST_LEN
));
1614 /** Return my identity digest. */
1616 router_get_my_id_digest(void)
1618 return (const uint8_t *)server_identitykey_digest
;
1621 /** Return true iff I'm a server and <b>digest</b> is equal to
1622 * my identity digest. */
1624 router_extrainfo_digest_is_me(const char *digest
)
1626 extrainfo_t
*ei
= router_get_my_extrainfo();
1630 return tor_memeq(digest
,
1631 ei
->cache_info
.signed_descriptor_digest
,
1635 /** A wrapper around router_digest_is_me(). */
1637 router_is_me(const routerinfo_t
*router
)
1639 return router_digest_is_me(router
->cache_info
.identity_digest
);
1642 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1644 router_fingerprint_is_me(const char *fp
)
1646 char digest
[DIGEST_LEN
];
1647 if (strlen(fp
) == HEX_DIGEST_LEN
&&
1648 base16_decode(digest
, sizeof(digest
), fp
, HEX_DIGEST_LEN
) == 0)
1649 return router_digest_is_me(digest
);
1654 /** Return a routerinfo for this OR, rebuilding a fresh one if
1655 * necessary. Return NULL on error, or if called on an OP. */
1656 const routerinfo_t
*
1657 router_get_my_routerinfo(void)
1659 if (!server_mode(get_options()))
1661 if (router_rebuild_descriptor(0))
1663 return desc_routerinfo
;
1666 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1667 * one if necessary. Return NULL on error.
1670 router_get_my_descriptor(void)
1673 if (!router_get_my_routerinfo())
1675 /* Make sure this is nul-terminated. */
1676 tor_assert(desc_routerinfo
->cache_info
.saved_location
== SAVED_NOWHERE
);
1677 body
= signed_descriptor_get_body(&desc_routerinfo
->cache_info
);
1678 tor_assert(!body
[desc_routerinfo
->cache_info
.signed_descriptor_len
]);
1679 log_debug(LD_GENERAL
,"my desc is '%s'", body
);
1683 /** Return the extrainfo document for this OR, or NULL if we have none.
1684 * Rebuilt it (and the server descriptor) if necessary. */
1686 router_get_my_extrainfo(void)
1688 if (!server_mode(get_options()))
1690 if (router_rebuild_descriptor(0))
1692 return desc_extrainfo
;
1695 /** Return a human-readable string describing what triggered us to generate
1696 * our current descriptor, or NULL if we don't know. */
1698 router_get_descriptor_gen_reason(void)
1700 return desc_gen_reason
;
1703 /** A list of nicknames that we've warned about including in our family
1704 * declaration verbatim rather than as digests. */
1705 static smartlist_t
*warned_nonexistent_family
= NULL
;
1707 static int router_guess_address_from_dir_headers(uint32_t *guess
);
1709 /** Make a current best guess at our address, either because
1710 * it's configured in torrc, or because we've learned it from
1711 * dirserver headers. Place the answer in *<b>addr</b> and return
1712 * 0 on success, else return -1 if we have no guess. */
1714 router_pick_published_address(const or_options_t
*options
, uint32_t *addr
)
1716 *addr
= get_last_resolved_addr();
1718 resolve_my_address(LOG_INFO
, options
, addr
, NULL
, NULL
) < 0) {
1719 log_info(LD_CONFIG
, "Could not determine our address locally. "
1720 "Checking if directory headers provide any hints.");
1721 if (router_guess_address_from_dir_headers(addr
) < 0) {
1722 log_info(LD_CONFIG
, "No hints from directory headers either. "
1723 "Will try again later.");
1727 log_info(LD_CONFIG
,"Success: chose address '%s'.", fmt_addr32(*addr
));
1731 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1732 * routerinfo, signed server descriptor, and extra-info document for this OR.
1733 * Return 0 on success, -1 on temporary error.
1736 router_rebuild_descriptor(int force
)
1742 int hibernating
= we_are_hibernating();
1743 const or_options_t
*options
= get_options();
1745 if (desc_clean_since
&& !force
)
1748 if (router_pick_published_address(options
, &addr
) < 0 ||
1749 router_get_advertised_or_port(options
) == 0) {
1750 /* Stop trying to rebuild our descriptor every second. We'll
1751 * learn that it's time to try again when ip_address_changed()
1752 * marks it dirty. */
1753 desc_clean_since
= time(NULL
);
1757 log_info(LD_OR
, "Rebuilding relay descriptor%s", force
? " (forced)" : "");
1759 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
1760 ri
->cache_info
.routerlist_index
= -1;
1761 ri
->address
= tor_dup_ip(addr
);
1762 ri
->nickname
= tor_strdup(options
->Nickname
);
1764 ri
->or_port
= router_get_advertised_or_port(options
);
1765 ri
->dir_port
= router_get_advertised_dir_port(options
, 0);
1766 ri
->cache_info
.published_on
= time(NULL
);
1767 ri
->onion_pkey
= crypto_pk_dup_key(get_onion_key()); /* must invoke from
1769 #ifdef CURVE25519_ENABLED
1770 ri
->onion_curve25519_pkey
=
1771 tor_memdup(&get_current_curve25519_keypair()->pubkey
,
1772 sizeof(curve25519_public_key_t
));
1775 /* For now, at most one IPv6 or-address is being advertised. */
1777 const port_cfg_t
*ipv6_orport
= NULL
;
1778 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t
*, p
) {
1779 if (p
->type
== CONN_TYPE_OR_LISTENER
&&
1780 ! p
->no_advertise
&&
1781 ! p
->bind_ipv4_only
&&
1782 tor_addr_family(&p
->addr
) == AF_INET6
) {
1783 if (! tor_addr_is_internal(&p
->addr
, 0)) {
1787 char addrbuf
[TOR_ADDR_BUF_LEN
];
1789 "Unable to use configured IPv6 address \"%s\" in a "
1790 "descriptor. Skipping it. "
1791 "Try specifying a globally reachable address explicitly. ",
1792 tor_addr_to_str(addrbuf
, &p
->addr
, sizeof(addrbuf
), 1));
1795 } SMARTLIST_FOREACH_END(p
);
1797 tor_addr_copy(&ri
->ipv6_addr
, &ipv6_orport
->addr
);
1798 ri
->ipv6_orport
= ipv6_orport
->port
;
1802 ri
->identity_pkey
= crypto_pk_dup_key(get_server_identity_key());
1803 if (crypto_pk_get_digest(ri
->identity_pkey
,
1804 ri
->cache_info
.identity_digest
)<0) {
1805 routerinfo_free(ri
);
1808 get_platform_str(platform
, sizeof(platform
));
1809 ri
->platform
= tor_strdup(platform
);
1811 /* compute ri->bandwidthrate as the min of various options */
1812 ri
->bandwidthrate
= get_effective_bwrate(options
);
1814 /* and compute ri->bandwidthburst similarly */
1815 ri
->bandwidthburst
= get_effective_bwburst(options
);
1817 ri
->bandwidthcapacity
= hibernating
? 0 : rep_hist_bandwidth_assess();
1819 if (dns_seems_to_be_broken() || has_dns_init_failed()) {
1820 /* DNS is screwed up; don't claim to be an exit. */
1821 policies_exit_policy_append_reject_star(&ri
->exit_policy
);
1823 policies_parse_exit_policy(options
->ExitPolicy
, &ri
->exit_policy
,
1825 options
->ExitPolicyRejectPrivate
,
1826 ri
->address
, !options
->BridgeRelay
);
1828 ri
->policy_is_reject_star
=
1829 policy_is_reject_star(ri
->exit_policy
, AF_INET
) &&
1830 policy_is_reject_star(ri
->exit_policy
, AF_INET6
);
1832 if (options
->IPv6Exit
) {
1833 char *p_tmp
= policy_summarize(ri
->exit_policy
, AF_INET6
);
1835 ri
->ipv6_exit_policy
= parse_short_policy(p_tmp
);
1840 /* XXXX NM NM I belive this is safe to remove */
1841 if (authdir_mode(options
))
1842 ri
->is_valid
= ri
->is_named
= 1; /* believe in yourself */
1845 if (options
->MyFamily
&& ! options
->BridgeRelay
) {
1846 smartlist_t
*family
;
1847 if (!warned_nonexistent_family
)
1848 warned_nonexistent_family
= smartlist_new();
1849 family
= smartlist_new();
1850 ri
->declared_family
= smartlist_new();
1851 smartlist_split_string(family
, options
->MyFamily
, ",",
1852 SPLIT_SKIP_SPACE
|SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1853 SMARTLIST_FOREACH_BEGIN(family
, char *, name
) {
1854 const node_t
*member
;
1855 if (!strcasecmp(name
, options
->Nickname
))
1856 goto skip
; /* Don't list ourself, that's redundant */
1858 member
= node_get_by_nickname(name
, 1);
1860 int is_legal
= is_legal_nickname_or_hexdigest(name
);
1861 if (!smartlist_contains_string(warned_nonexistent_family
, name
) &&
1862 !is_legal_hexdigest(name
)) {
1865 "I have no descriptor for the router named \"%s\" in my "
1866 "declared family; I'll use the nickname as is, but "
1867 "this may confuse clients.", name
);
1869 log_warn(LD_CONFIG
, "There is a router named \"%s\" in my "
1870 "declared family, but that isn't a legal nickname. "
1871 "Skipping it.", escaped(name
));
1872 smartlist_add(warned_nonexistent_family
, tor_strdup(name
));
1875 smartlist_add(ri
->declared_family
, name
);
1878 } else if (router_digest_is_me(member
->identity
)) {
1879 /* Don't list ourself in our own family; that's redundant */
1880 /* XXX shouldn't be possible */
1882 char *fp
= tor_malloc(HEX_DIGEST_LEN
+2);
1884 base16_encode(fp
+1,HEX_DIGEST_LEN
+1,
1885 member
->identity
, DIGEST_LEN
);
1886 smartlist_add(ri
->declared_family
, fp
);
1887 if (smartlist_contains_string(warned_nonexistent_family
, name
))
1888 smartlist_string_remove(warned_nonexistent_family
, name
);
1892 } SMARTLIST_FOREACH_END(name
);
1894 /* remove duplicates from the list */
1895 smartlist_sort_strings(ri
->declared_family
);
1896 smartlist_uniq_strings(ri
->declared_family
);
1898 smartlist_free(family
);
1901 /* Now generate the extrainfo. */
1902 ei
= tor_malloc_zero(sizeof(extrainfo_t
));
1903 ei
->cache_info
.is_extrainfo
= 1;
1904 strlcpy(ei
->nickname
, get_options()->Nickname
, sizeof(ei
->nickname
));
1905 ei
->cache_info
.published_on
= ri
->cache_info
.published_on
;
1906 memcpy(ei
->cache_info
.identity_digest
, ri
->cache_info
.identity_digest
,
1908 if (extrainfo_dump_to_string(&ei
->cache_info
.signed_descriptor_body
,
1909 ei
, get_server_identity_key()) < 0) {
1910 log_warn(LD_BUG
, "Couldn't generate extra-info descriptor.");
1914 ei
->cache_info
.signed_descriptor_len
=
1915 strlen(ei
->cache_info
.signed_descriptor_body
);
1916 router_get_extrainfo_hash(ei
->cache_info
.signed_descriptor_body
,
1917 ei
->cache_info
.signed_descriptor_len
,
1918 ei
->cache_info
.signed_descriptor_digest
);
1921 /* Now finish the router descriptor. */
1923 memcpy(ri
->cache_info
.extra_info_digest
,
1924 ei
->cache_info
.signed_descriptor_digest
,
1927 /* ri was allocated with tor_malloc_zero, so there is no need to
1928 * zero ri->cache_info.extra_info_digest here. */
1930 ri
->cache_info
.signed_descriptor_body
= tor_malloc(8192);
1931 if (router_dump_router_to_string(ri
->cache_info
.signed_descriptor_body
, 8192,
1932 ri
, get_server_identity_key()) < 0) {
1933 log_warn(LD_BUG
, "Couldn't generate router descriptor.");
1934 routerinfo_free(ri
);
1938 ri
->cache_info
.signed_descriptor_len
=
1939 strlen(ri
->cache_info
.signed_descriptor_body
);
1942 options
->BridgeRelay
? ROUTER_PURPOSE_BRIDGE
: ROUTER_PURPOSE_GENERAL
;
1943 if (options
->BridgeRelay
) {
1944 /* Bridges shouldn't be able to send their descriptors unencrypted,
1945 anyway, since they don't have a DirPort, and always connect to the
1946 bridge authority anonymously. But just in case they somehow think of
1947 sending them on an unencrypted connection, don't allow them to try. */
1948 ri
->cache_info
.send_unencrypted
= 0;
1950 ei
->cache_info
.send_unencrypted
= 0;
1952 ri
->cache_info
.send_unencrypted
= 1;
1954 ei
->cache_info
.send_unencrypted
= 1;
1957 router_get_router_hash(ri
->cache_info
.signed_descriptor_body
,
1958 strlen(ri
->cache_info
.signed_descriptor_body
),
1959 ri
->cache_info
.signed_descriptor_digest
);
1962 tor_assert(! routerinfo_incompatible_with_extrainfo(ri
, ei
, NULL
, NULL
));
1965 routerinfo_free(desc_routerinfo
);
1966 desc_routerinfo
= ri
;
1967 extrainfo_free(desc_extrainfo
);
1968 desc_extrainfo
= ei
;
1970 desc_clean_since
= time(NULL
);
1971 desc_needs_upload
= 1;
1972 desc_gen_reason
= desc_dirty_reason
;
1973 desc_dirty_reason
= NULL
;
1974 control_event_my_descriptor_changed();
1978 /** If our router descriptor ever goes this long without being regenerated
1979 * because something changed, we force an immediate regenerate-and-upload. */
1980 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
1982 /** If our router descriptor seems to be missing or unacceptable according
1983 * to the authorities, regenerate and reupload it _this_ often. */
1984 #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
1986 /** Mark descriptor out of date if it's been "too long" since we last tried
1989 mark_my_descriptor_dirty_if_too_old(time_t now
)
1991 networkstatus_t
*ns
;
1992 const routerstatus_t
*rs
;
1993 const char *retry_fast_reason
= NULL
; /* Set if we should retry frequently */
1994 const time_t slow_cutoff
= now
- FORCE_REGENERATE_DESCRIPTOR_INTERVAL
;
1995 const time_t fast_cutoff
= now
- FAST_RETRY_DESCRIPTOR_INTERVAL
;
1997 /* If it's already dirty, don't mark it. */
1998 if (! desc_clean_since
)
2001 /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
2002 * time to rebuild it. */
2003 if (desc_clean_since
< slow_cutoff
) {
2004 mark_my_descriptor_dirty("time for new descriptor");
2007 /* Now we see whether we want to be retrying frequently or no. The
2008 * rule here is that we'll retry frequently if we aren't listed in the
2009 * live consensus we have, or if the publication time of the
2010 * descriptor listed for us in the consensus is very old. */
2011 ns
= networkstatus_get_live_consensus(now
);
2013 rs
= networkstatus_vote_find_entry(ns
, server_identitykey_digest
);
2015 retry_fast_reason
= "not listed in consensus";
2016 else if (rs
->published_on
< slow_cutoff
)
2017 retry_fast_reason
= "version listed in consensus is quite old";
2020 if (retry_fast_reason
&& desc_clean_since
< fast_cutoff
)
2021 mark_my_descriptor_dirty(retry_fast_reason
);
2024 /** Call when the current descriptor is out of date. */
2026 mark_my_descriptor_dirty(const char *reason
)
2028 const or_options_t
*options
= get_options();
2029 if (server_mode(options
) && options
->PublishServerDescriptor_
)
2030 log_info(LD_OR
, "Decided to publish new relay descriptor: %s", reason
);
2031 desc_clean_since
= 0;
2032 if (!desc_dirty_reason
)
2033 desc_dirty_reason
= reason
;
2036 /** How frequently will we republish our descriptor because of large (factor
2037 * of 2) shifts in estimated bandwidth? */
2038 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
2040 /** Check whether bandwidth has changed a lot since the last time we announced
2041 * bandwidth. If so, mark our descriptor dirty. */
2043 check_descriptor_bandwidth_changed(time_t now
)
2045 static time_t last_changed
= 0;
2047 if (!desc_routerinfo
)
2050 prev
= desc_routerinfo
->bandwidthcapacity
;
2051 cur
= we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
2052 if ((prev
!= cur
&& (!prev
|| !cur
)) ||
2055 if (last_changed
+MAX_BANDWIDTH_CHANGE_FREQ
< now
) {
2056 log_info(LD_GENERAL
,
2057 "Measured bandwidth has changed; rebuilding descriptor.");
2058 mark_my_descriptor_dirty("bandwidth has changed");
2064 /** Note at log level severity that our best guess of address has changed from
2065 * <b>prev</b> to <b>cur</b>. */
2067 log_addr_has_changed(int severity
,
2068 const tor_addr_t
*prev
,
2069 const tor_addr_t
*cur
,
2072 char addrbuf_prev
[TOR_ADDR_BUF_LEN
];
2073 char addrbuf_cur
[TOR_ADDR_BUF_LEN
];
2075 if (tor_addr_to_str(addrbuf_prev
, prev
, sizeof(addrbuf_prev
), 1) == NULL
)
2076 strlcpy(addrbuf_prev
, "???", TOR_ADDR_BUF_LEN
);
2077 if (tor_addr_to_str(addrbuf_cur
, cur
, sizeof(addrbuf_cur
), 1) == NULL
)
2078 strlcpy(addrbuf_cur
, "???", TOR_ADDR_BUF_LEN
);
2080 if (!tor_addr_is_null(prev
))
2081 log_fn(severity
, LD_GENERAL
,
2082 "Our IP Address has changed from %s to %s; "
2083 "rebuilding descriptor (source: %s).",
2084 addrbuf_prev
, addrbuf_cur
, source
);
2086 log_notice(LD_GENERAL
,
2087 "Guessed our IP address as %s (source: %s).",
2088 addrbuf_cur
, source
);
2091 /** Check whether our own address as defined by the Address configuration
2092 * has changed. This is for routers that get their address from a service
2093 * like dyndns. If our address has changed, mark our descriptor dirty. */
2095 check_descriptor_ipaddress_changed(time_t now
)
2098 const or_options_t
*options
= get_options();
2099 const char *method
= NULL
;
2100 char *hostname
= NULL
;
2104 if (!desc_routerinfo
)
2108 prev
= desc_routerinfo
->addr
;
2109 if (resolve_my_address(LOG_INFO
, options
, &cur
, &method
, &hostname
) < 0) {
2110 log_info(LD_CONFIG
,"options->Address didn't resolve into an IP.");
2116 tor_addr_t tmp_prev
, tmp_cur
;
2118 tor_addr_from_ipv4h(&tmp_prev
, prev
);
2119 tor_addr_from_ipv4h(&tmp_cur
, cur
);
2121 tor_asprintf(&source
, "METHOD=%s%s%s", method
,
2122 hostname
? " HOSTNAME=" : "",
2123 hostname
? hostname
: "");
2125 log_addr_has_changed(LOG_NOTICE
, &tmp_prev
, &tmp_cur
, source
);
2128 ip_address_changed(0);
2134 /** The most recently guessed value of our IP address, based on directory
2136 static tor_addr_t last_guessed_ip
= TOR_ADDR_NULL
;
2138 /** A directory server <b>d_conn</b> told us our IP address is
2139 * <b>suggestion</b>.
2140 * If this address is different from the one we think we are now, and
2141 * if our computer doesn't actually know its IP address, then switch. */
2143 router_new_address_suggestion(const char *suggestion
,
2144 const dir_connection_t
*d_conn
)
2147 uint32_t cur
= 0; /* Current IPv4 address. */
2148 const or_options_t
*options
= get_options();
2150 /* first, learn what the IP address actually is */
2151 if (tor_addr_parse(&addr
, suggestion
) == -1) {
2152 log_debug(LD_DIR
, "Malformed X-Your-Address-Is header %s. Ignoring.",
2153 escaped(suggestion
));
2157 log_debug(LD_DIR
, "Got X-Your-Address-Is: %s.", suggestion
);
2159 if (!server_mode(options
)) {
2160 tor_addr_copy(&last_guessed_ip
, &addr
);
2165 cur
= get_last_resolved_addr();
2167 resolve_my_address(LOG_INFO
, options
, &cur
, NULL
, NULL
) >= 0) {
2168 /* We're all set -- we already know our address. Great. */
2169 tor_addr_from_ipv4h(&last_guessed_ip
, cur
); /* store it in case we
2173 if (tor_addr_is_internal(&addr
, 0)) {
2174 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
2177 if (tor_addr_eq(&d_conn
->base_
.addr
, &addr
)) {
2178 /* Don't believe anybody who says our IP is their IP. */
2179 log_debug(LD_DIR
, "A directory server told us our IP address is %s, "
2180 "but he's just reporting his own IP address. Ignoring.",
2185 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
2186 * us an answer different from what we had the last time we managed to
2188 if (!tor_addr_eq(&last_guessed_ip
, &addr
)) {
2189 control_event_server_status(LOG_NOTICE
,
2190 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
2192 log_addr_has_changed(LOG_NOTICE
, &last_guessed_ip
, &addr
,
2193 d_conn
->base_
.address
);
2194 ip_address_changed(0);
2195 tor_addr_copy(&last_guessed_ip
, &addr
); /* router_rebuild_descriptor()
2200 /** We failed to resolve our address locally, but we'd like to build
2201 * a descriptor and publish / test reachability. If we have a guess
2202 * about our address based on directory headers, answer it and return
2203 * 0; else return -1. */
2205 router_guess_address_from_dir_headers(uint32_t *guess
)
2207 if (!tor_addr_is_null(&last_guessed_ip
)) {
2208 *guess
= tor_addr_to_ipv4h(&last_guessed_ip
);
2214 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
2215 * string describing the version of Tor and the operating system we're
2216 * currently running on.
2219 get_platform_str(char *platform
, size_t len
)
2221 tor_snprintf(platform
, len
, "Tor %s on %s",
2222 get_short_version(), get_uname());
2225 /* XXX need to audit this thing and count fenceposts. maybe
2226 * refactor so we don't have to keep asking if we're
2227 * near the end of maxlen?
2229 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2231 /** OR only: Given a routerinfo for this router, and an identity key to sign
2232 * with, encode the routerinfo as a signed server descriptor and write the
2233 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
2234 * failure, and the number of bytes used on success.
2237 router_dump_router_to_string(char *s
, size_t maxlen
, routerinfo_t
*router
,
2238 crypto_pk_t
*ident_key
)
2240 char *onion_pkey
; /* Onion key, PEM-encoded. */
2241 char *identity_pkey
; /* Identity key, PEM-encoded. */
2242 char digest
[DIGEST_LEN
];
2243 char published
[ISO_TIME_LEN
+1];
2244 char fingerprint
[FINGERPRINT_LEN
+1];
2245 int has_extra_info_digest
;
2246 char extra_info_digest
[HEX_DIGEST_LEN
+1];
2247 size_t onion_pkeylen
, identity_pkeylen
;
2251 char *extra_or_address
= NULL
;
2252 const or_options_t
*options
= get_options();
2254 /* Make sure the identity key matches the one in the routerinfo. */
2255 if (!crypto_pk_eq_keys(ident_key
, router
->identity_pkey
)) {
2256 log_warn(LD_BUG
,"Tried to sign a router with a private key that didn't "
2257 "match router's public key!");
2261 /* record our fingerprint, so we can include it in the descriptor */
2262 if (crypto_pk_get_fingerprint(router
->identity_pkey
, fingerprint
, 1)<0) {
2263 log_err(LD_BUG
,"Error computing fingerprint");
2267 /* PEM-encode the onion key */
2268 if (crypto_pk_write_public_key_to_string(router
->onion_pkey
,
2269 &onion_pkey
,&onion_pkeylen
)<0) {
2270 log_warn(LD_BUG
,"write onion_pkey to string failed!");
2274 /* PEM-encode the identity key */
2275 if (crypto_pk_write_public_key_to_string(router
->identity_pkey
,
2276 &identity_pkey
,&identity_pkeylen
)<0) {
2277 log_warn(LD_BUG
,"write identity_pkey to string failed!");
2278 tor_free(onion_pkey
);
2282 /* Encode the publication time. */
2283 format_iso_time(published
, router
->cache_info
.published_on
);
2285 if (router
->declared_family
&& smartlist_len(router
->declared_family
)) {
2286 char *family
= smartlist_join_strings(router
->declared_family
,
2288 tor_asprintf(&family_line
, "family %s\n", family
);
2291 family_line
= tor_strdup("");
2294 has_extra_info_digest
=
2295 ! tor_digest_is_zero(router
->cache_info
.extra_info_digest
);
2297 if (has_extra_info_digest
) {
2298 base16_encode(extra_info_digest
, sizeof(extra_info_digest
),
2299 router
->cache_info
.extra_info_digest
, DIGEST_LEN
);
2302 if (router
->ipv6_orport
&&
2303 tor_addr_family(&router
->ipv6_addr
) == AF_INET6
) {
2304 char addr
[TOR_ADDR_BUF_LEN
];
2306 a
= tor_addr_to_str(addr
, &router
->ipv6_addr
, sizeof(addr
), 1);
2308 tor_asprintf(&extra_or_address
,
2309 "or-address %s:%d\n", a
, router
->ipv6_orport
);
2310 log_debug(LD_OR
, "My or-address line is <%s>", extra_or_address
);
2314 /* Generate the easy portion of the router descriptor. */
2315 result
= tor_snprintf(s
, maxlen
,
2316 "router %s %s %d 0 %d\n"
2319 "protocols Link 1 2 Circuit 1\n"
2323 "bandwidth %d %d %d\n"
2331 decide_to_advertise_dirport(options
, router
->dir_port
),
2332 extra_or_address
? extra_or_address
: "",
2336 stats_n_seconds_working
,
2337 (int) router
->bandwidthrate
,
2338 (int) router
->bandwidthburst
,
2339 (int) router
->bandwidthcapacity
,
2340 has_extra_info_digest
? "extra-info-digest " : "",
2341 has_extra_info_digest
? extra_info_digest
: "",
2342 has_extra_info_digest
? "\n" : "",
2343 options
->DownloadExtraInfo
? "caches-extra-info\n" : "",
2344 onion_pkey
, identity_pkey
,
2346 we_are_hibernating() ? "hibernating 1\n" : "",
2347 options
->HidServDirectoryV2
? "hidden-service-dir\n" : "",
2348 options
->AllowSingleHopExits
? "allow-single-hop-exits\n" : "");
2350 tor_free(family_line
);
2351 tor_free(onion_pkey
);
2352 tor_free(identity_pkey
);
2353 tor_free(extra_or_address
);
2356 log_warn(LD_BUG
,"descriptor snprintf #1 ran out of room!");
2359 /* From now on, we use 'written' to remember the current length of 's'. */
2362 if (options
->ContactInfo
&& strlen(options
->ContactInfo
)) {
2363 const char *ci
= options
->ContactInfo
;
2364 if (strchr(ci
, '\n') || strchr(ci
, '\r'))
2366 result
= tor_snprintf(s
+written
,maxlen
-written
, "contact %s\n", ci
);
2368 log_warn(LD_BUG
,"descriptor snprintf #2 ran out of room!");
2374 #ifdef CURVE25519_ENABLED
2375 if (router
->onion_curve25519_pkey
) {
2377 base64_encode(kbuf
, sizeof(kbuf
),
2378 (const char *)router
->onion_curve25519_pkey
->public_key
,
2379 CURVE25519_PUBKEY_LEN
);
2380 result
= tor_snprintf(s
+written
,maxlen
-written
, "ntor-onion-key %s",
2383 log_warn(LD_BUG
,"descriptor snprintf ran out of room!");
2390 /* Write the exit policy to the end of 's'. */
2391 if (!router
->exit_policy
|| !smartlist_len(router
->exit_policy
)) {
2392 strlcat(s
+written
, "reject *:*\n", maxlen
-written
);
2393 written
+= strlen("reject *:*\n");
2394 } else if (router
->exit_policy
) {
2396 for (i
= 0; i
< smartlist_len(router
->exit_policy
); ++i
) {
2397 addr_policy_t
*tmpe
= smartlist_get(router
->exit_policy
, i
);
2398 if (tor_addr_family(&tmpe
->addr
) == AF_INET6
)
2399 continue; /* Don't include IPv6 parts of address policy */
2400 result
= policy_write_item(s
+written
, maxlen
-written
, tmpe
, 1);
2402 log_warn(LD_BUG
,"descriptor policy_write_item ran out of room!");
2405 tor_assert(result
== (int)strlen(s
+written
));
2407 if (written
+2 > maxlen
) {
2408 log_warn(LD_BUG
,"descriptor policy_write_item ran out of room (2)!");
2411 s
[written
++] = '\n';
2415 if (router
->ipv6_exit_policy
) {
2416 char *p6
= write_short_policy(router
->ipv6_exit_policy
);
2417 if (p6
&& strcmp(p6
, "reject 1-65535")) {
2418 result
= tor_snprintf(s
+written
, maxlen
-written
,
2419 "ipv6-policy %s\n", p6
);
2421 log_warn(LD_BUG
,"Descriptor printf of policy ran out of room");
2430 if (written
+ DIROBJ_MAX_SIG_LEN
> maxlen
) {
2431 /* Not enough room for signature. */
2432 log_warn(LD_BUG
,"not enough room left in descriptor for signature!");
2436 /* Sign the descriptor */
2437 strlcpy(s
+written
, "router-signature\n", maxlen
-written
);
2438 written
+= strlen(s
+written
);
2440 if (router_get_router_hash(s
, strlen(s
), digest
) < 0) {
2444 note_crypto_pk_op(SIGN_RTR
);
2445 if (router_append_dirobj_signature(s
+written
,maxlen
-written
,
2446 digest
,DIGEST_LEN
,ident_key
)<0) {
2447 log_warn(LD_BUG
, "Couldn't sign router descriptor");
2450 written
+= strlen(s
+written
);
2452 if (written
+2 > maxlen
) {
2453 log_warn(LD_BUG
,"Not enough room to finish descriptor.");
2456 /* include a last '\n' */
2460 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2464 routerinfo_t
*ri_tmp
;
2465 cp
= s_dup
= tor_strdup(s
);
2466 ri_tmp
= router_parse_entry_from_string(cp
, NULL
, 1, 0, NULL
);
2469 "We just generated a router descriptor we can't parse.");
2470 log_err(LD_BUG
, "Descriptor was: <<%s>>", s
);
2474 routerinfo_free(ri_tmp
);
2478 return (int)written
+1;
2481 /** Copy the primary (IPv4) OR port (IP address and TCP port) for
2482 * <b>router</b> into *<b>ap_out</b>. */
2484 router_get_prim_orport(const routerinfo_t
*router
, tor_addr_port_t
*ap_out
)
2486 tor_assert(ap_out
!= NULL
);
2487 tor_addr_from_ipv4h(&ap_out
->addr
, router
->addr
);
2488 ap_out
->port
= router
->or_port
;
2491 /** Return 1 if any of <b>router</b>'s addresses are <b>addr</b>.
2492 * Otherwise return 0. */
2494 router_has_addr(const routerinfo_t
*router
, const tor_addr_t
*addr
)
2497 tor_addr_eq_ipv4h(addr
, router
->addr
) ||
2498 tor_addr_eq(&router
->ipv6_addr
, addr
);
2502 router_has_orport(const routerinfo_t
*router
, const tor_addr_port_t
*orport
)
2505 (tor_addr_eq_ipv4h(&orport
->addr
, router
->addr
) &&
2506 orport
->port
== router
->or_port
) ||
2507 (tor_addr_eq(&orport
->addr
, &router
->ipv6_addr
) &&
2508 orport
->port
== router
->ipv6_orport
);
2511 /** Load the contents of <b>filename</b>, find the last line starting with
2512 * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
2513 * the past or more than 1 hour in the future with respect to <b>now</b>,
2514 * and write the file contents starting with that line to *<b>out</b>.
2515 * Return 1 for success, 0 if the file does not exist, or -1 if the file
2516 * does not contain a line matching these criteria or other failure. */
2518 load_stats_file(const char *filename
, const char *end_line
, time_t now
,
2522 char *fname
= get_datadir_fname(filename
);
2523 char *contents
, *start
= NULL
, *tmp
, timestr
[ISO_TIME_LEN
+1];
2525 switch (file_status(fname
)) {
2527 /* X022 Find an alternative to reading the whole file to memory. */
2528 if ((contents
= read_file_to_str(fname
, 0, NULL
))) {
2529 tmp
= strstr(contents
, end_line
);
2530 /* Find last block starting with end_line */
2533 tmp
= strstr(tmp
+ 1, end_line
);
2537 if (strlen(start
) < strlen(end_line
) + 1 + sizeof(timestr
))
2539 strlcpy(timestr
, start
+ 1 + strlen(end_line
), sizeof(timestr
));
2540 if (parse_iso_time(timestr
, &written
) < 0)
2542 if (written
< now
- (25*60*60) || written
> now
+ (1*60*60))
2544 *out
= tor_strdup(start
);
2562 /** Write the contents of <b>extrainfo</b> and aggregated statistics to
2563 * *<b>s_out</b>, signing them with <b>ident_key</b>. Return 0 on
2564 * success, negative on failure. */
2566 extrainfo_dump_to_string(char **s_out
, extrainfo_t
*extrainfo
,
2567 crypto_pk_t
*ident_key
)
2569 const or_options_t
*options
= get_options();
2570 char identity
[HEX_DIGEST_LEN
+1];
2571 char published
[ISO_TIME_LEN
+1];
2572 char digest
[DIGEST_LEN
];
2573 char *bandwidth_usage
;
2575 static int write_stats_to_extrainfo
= 1;
2576 char sig
[DIROBJ_MAX_SIG_LEN
+1];
2577 char *s
, *pre
, *contents
, *cp
, *s_dup
= NULL
;
2578 time_t now
= time(NULL
);
2579 smartlist_t
*chunks
= smartlist_new();
2580 extrainfo_t
*ei_tmp
= NULL
;
2582 base16_encode(identity
, sizeof(identity
),
2583 extrainfo
->cache_info
.identity_digest
, DIGEST_LEN
);
2584 format_iso_time(published
, extrainfo
->cache_info
.published_on
);
2585 bandwidth_usage
= rep_hist_get_bandwidth_lines();
2587 tor_asprintf(&pre
, "extra-info %s %s\npublished %s\n%s",
2588 extrainfo
->nickname
, identity
,
2589 published
, bandwidth_usage
);
2590 tor_free(bandwidth_usage
);
2591 smartlist_add(chunks
, pre
);
2593 if (geoip_is_loaded(AF_INET
))
2594 smartlist_add_asprintf(chunks
, "geoip-db-digest %s\n",
2595 geoip_db_digest(AF_INET
));
2596 if (geoip_is_loaded(AF_INET6
))
2597 smartlist_add_asprintf(chunks
, "geoip6-db-digest %s\n",
2598 geoip_db_digest(AF_INET6
));
2600 if (options
->ExtraInfoStatistics
&& write_stats_to_extrainfo
) {
2601 log_info(LD_GENERAL
, "Adding stats to extra-info descriptor.");
2602 if (options
->DirReqStatistics
&&
2603 load_stats_file("stats"PATH_SEPARATOR
"dirreq-stats",
2604 "dirreq-stats-end", now
, &contents
) > 0) {
2605 smartlist_add(chunks
, contents
);
2607 if (options
->EntryStatistics
&&
2608 load_stats_file("stats"PATH_SEPARATOR
"entry-stats",
2609 "entry-stats-end", now
, &contents
) > 0) {
2610 smartlist_add(chunks
, contents
);
2612 if (options
->CellStatistics
&&
2613 load_stats_file("stats"PATH_SEPARATOR
"buffer-stats",
2614 "cell-stats-end", now
, &contents
) > 0) {
2615 smartlist_add(chunks
, contents
);
2617 if (options
->ExitPortStatistics
&&
2618 load_stats_file("stats"PATH_SEPARATOR
"exit-stats",
2619 "exit-stats-end", now
, &contents
) > 0) {
2620 smartlist_add(chunks
, contents
);
2622 if (options
->ConnDirectionStatistics
&&
2623 load_stats_file("stats"PATH_SEPARATOR
"conn-stats",
2624 "conn-bi-direct", now
, &contents
) > 0) {
2625 smartlist_add(chunks
, contents
);
2629 /* Add information about the pluggable transports we support. */
2630 if (options
->ServerTransportPlugin
) {
2631 char *pluggable_transports
= pt_get_extra_info_descriptor_string();
2632 if (pluggable_transports
)
2633 smartlist_add(chunks
, pluggable_transports
);
2636 if (should_record_bridge_info(options
) && write_stats_to_extrainfo
) {
2637 const char *bridge_stats
= geoip_get_bridge_stats_extrainfo(now
);
2639 smartlist_add(chunks
, tor_strdup(bridge_stats
));
2643 smartlist_add(chunks
, tor_strdup("router-signature\n"));
2644 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
2646 while (strlen(s
) > MAX_EXTRAINFO_UPLOAD_SIZE
- DIROBJ_MAX_SIG_LEN
) {
2647 /* So long as there are at least two chunks (one for the initial
2648 * extra-info line and one for the router-signature), we can keep removing
2650 if (smartlist_len(chunks
) > 2) {
2651 /* We remove the next-to-last element (remember, len-1 is the last
2652 element), since we need to keep the router-signature element. */
2653 int idx
= smartlist_len(chunks
) - 2;
2654 char *e
= smartlist_get(chunks
, idx
);
2655 smartlist_del_keeporder(chunks
, idx
);
2656 log_warn(LD_GENERAL
, "We just generated an extra-info descriptor "
2657 "with statistics that exceeds the 50 KB "
2658 "upload limit. Removing last added "
2662 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
2664 log_warn(LD_BUG
, "We just generated an extra-info descriptors that "
2665 "exceeds the 50 KB upload limit.");
2670 memset(sig
, 0, sizeof(sig
));
2671 if (router_get_extrainfo_hash(s
, strlen(s
), digest
) < 0 ||
2672 router_append_dirobj_signature(sig
, sizeof(sig
), digest
, DIGEST_LEN
,
2674 log_warn(LD_BUG
, "Could not append signature to extra-info "
2678 smartlist_add(chunks
, tor_strdup(sig
));
2680 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
2682 cp
= s_dup
= tor_strdup(s
);
2683 ei_tmp
= extrainfo_parse_entry_from_string(cp
, NULL
, 1, NULL
);
2685 if (write_stats_to_extrainfo
) {
2686 log_warn(LD_GENERAL
, "We just generated an extra-info descriptor "
2687 "with statistics that we can't parse. Not "
2688 "adding statistics to this or any future "
2689 "extra-info descriptors.");
2690 write_stats_to_extrainfo
= 0;
2691 result
= extrainfo_dump_to_string(s_out
, extrainfo
, ident_key
);
2694 log_warn(LD_BUG
, "We just generated an extrainfo descriptor we "
2701 s
= NULL
; /* prevent free */
2710 SMARTLIST_FOREACH(chunks
, char *, cp
, tor_free(cp
));
2711 smartlist_free(chunks
);
2713 extrainfo_free(ei_tmp
);
2718 /** Return true iff <b>s</b> is a valid server nickname. (That is, a string
2719 * containing between 1 and MAX_NICKNAME_LEN characters from
2720 * LEGAL_NICKNAME_CHARACTERS.) */
2722 is_legal_nickname(const char *s
)
2727 return len
> 0 && len
<= MAX_NICKNAME_LEN
&&
2728 strspn(s
,LEGAL_NICKNAME_CHARACTERS
) == len
;
2731 /** Return true iff <b>s</b> is a valid server nickname or
2732 * hex-encoded identity-key digest. */
2734 is_legal_nickname_or_hexdigest(const char *s
)
2737 return is_legal_nickname(s
);
2739 return is_legal_hexdigest(s
);
2742 /** Return true iff <b>s</b> is a valid hex-encoded identity-key
2743 * digest. (That is, an optional $, followed by 40 hex characters,
2744 * followed by either nothing, or = or ~ followed by a nickname, or
2745 * a character other than =, ~, or a hex character.)
2748 is_legal_hexdigest(const char *s
)
2752 if (s
[0] == '$') s
++;
2754 if (len
> HEX_DIGEST_LEN
) {
2755 if (s
[HEX_DIGEST_LEN
] == '=' ||
2756 s
[HEX_DIGEST_LEN
] == '~') {
2757 if (!is_legal_nickname(s
+HEX_DIGEST_LEN
+1))
2763 return (len
>= HEX_DIGEST_LEN
&&
2764 strspn(s
,HEX_CHARACTERS
)==HEX_DIGEST_LEN
);
2767 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2768 * hold a human-readable description of a node with identity digest
2769 * <b>id_digest</b>, named-status <b>is_named</b>, nickname <b>nickname</b>,
2770 * and address <b>addr</b> or <b>addr32h</b>.
2772 * The <b>nickname</b> and <b>addr</b> fields are optional and may be set to
2773 * NULL. The <b>addr32h</b> field is optional and may be set to 0.
2775 * Return a pointer to the front of <b>buf</b>.
2778 format_node_description(char *buf
,
2779 const char *id_digest
,
2781 const char *nickname
,
2782 const tor_addr_t
*addr
,
2788 return "<NULL BUFFER>";
2791 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, id_digest
, DIGEST_LEN
);
2792 cp
= buf
+1+HEX_DIGEST_LEN
;
2794 buf
[1+HEX_DIGEST_LEN
] = is_named
? '=' : '~';
2795 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, nickname
, MAX_NICKNAME_LEN
+1);
2798 if (addr32h
|| addr
) {
2799 memcpy(cp
, " at ", 4);
2802 tor_addr_to_str(cp
, addr
, TOR_ADDR_BUF_LEN
, 0);
2805 in
.s_addr
= htonl(addr32h
);
2806 tor_inet_ntoa(&in
, cp
, INET_NTOA_BUF_LEN
);
2812 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2813 * hold a human-readable description of <b>ri</b>.
2816 * Return a pointer to the front of <b>buf</b>.
2819 router_get_description(char *buf
, const routerinfo_t
*ri
)
2823 return format_node_description(buf
,
2824 ri
->cache_info
.identity_digest
,
2825 router_is_named(ri
),
2831 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2832 * hold a human-readable description of <b>node</b>.
2834 * Return a pointer to the front of <b>buf</b>.
2837 node_get_description(char *buf
, const node_t
*node
)
2839 const char *nickname
= NULL
;
2840 uint32_t addr32h
= 0;
2847 nickname
= node
->rs
->nickname
;
2848 is_named
= node
->rs
->is_named
;
2849 addr32h
= node
->rs
->addr
;
2850 } else if (node
->ri
) {
2851 nickname
= node
->ri
->nickname
;
2852 addr32h
= node
->ri
->addr
;
2855 return format_node_description(buf
,
2863 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2864 * hold a human-readable description of <b>rs</b>.
2866 * Return a pointer to the front of <b>buf</b>.
2869 routerstatus_get_description(char *buf
, const routerstatus_t
*rs
)
2873 return format_node_description(buf
,
2874 rs
->identity_digest
,
2881 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2882 * hold a human-readable description of <b>ei</b>.
2884 * Return a pointer to the front of <b>buf</b>.
2887 extend_info_get_description(char *buf
, const extend_info_t
*ei
)
2891 return format_node_description(buf
,
2892 ei
->identity_digest
,
2899 /** Return a human-readable description of the routerinfo_t <b>ri</b>.
2901 * This function is not thread-safe. Each call to this function invalidates
2902 * previous values returned by this function.
2905 router_describe(const routerinfo_t
*ri
)
2907 static char buf
[NODE_DESC_BUF_LEN
];
2908 return router_get_description(buf
, ri
);
2911 /** Return a human-readable description of the node_t <b>node</b>.
2913 * This function is not thread-safe. Each call to this function invalidates
2914 * previous values returned by this function.
2917 node_describe(const node_t
*node
)
2919 static char buf
[NODE_DESC_BUF_LEN
];
2920 return node_get_description(buf
, node
);
2923 /** Return a human-readable description of the routerstatus_t <b>rs</b>.
2925 * This function is not thread-safe. Each call to this function invalidates
2926 * previous values returned by this function.
2929 routerstatus_describe(const routerstatus_t
*rs
)
2931 static char buf
[NODE_DESC_BUF_LEN
];
2932 return routerstatus_get_description(buf
, rs
);
2935 /** Return a human-readable description of the extend_info_t <b>ri</b>.
2937 * This function is not thread-safe. Each call to this function invalidates
2938 * previous values returned by this function.
2941 extend_info_describe(const extend_info_t
*ei
)
2943 static char buf
[NODE_DESC_BUF_LEN
];
2944 return extend_info_get_description(buf
, ei
);
2947 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
2948 * verbose representation of the identity of <b>router</b>. The format is:
2950 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
2951 * A "=" if the router is named; a "~" if it is not.
2952 * The router's nickname.
2955 router_get_verbose_nickname(char *buf
, const routerinfo_t
*router
)
2957 const char *good_digest
= networkstatus_get_router_digest_by_nickname(
2959 int is_named
= good_digest
&& tor_memeq(good_digest
,
2960 router
->cache_info
.identity_digest
,
2963 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, router
->cache_info
.identity_digest
,
2965 buf
[1+HEX_DIGEST_LEN
] = is_named
? '=' : '~';
2966 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, router
->nickname
, MAX_NICKNAME_LEN
+1);
2969 /** Forget that we have issued any router-related warnings, so that we'll
2970 * warn again if we see the same errors. */
2972 router_reset_warnings(void)
2974 if (warned_nonexistent_family
) {
2975 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
2976 smartlist_clear(warned_nonexistent_family
);
2980 /** Given a router purpose, convert it to a string. Don't call this on
2981 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
2982 * know its string representation. */
2984 router_purpose_to_string(uint8_t p
)
2988 case ROUTER_PURPOSE_GENERAL
: return "general";
2989 case ROUTER_PURPOSE_BRIDGE
: return "bridge";
2990 case ROUTER_PURPOSE_CONTROLLER
: return "controller";
2997 /** Given a string, convert it to a router purpose. */
2999 router_purpose_from_string(const char *s
)
3001 if (!strcmp(s
, "general"))
3002 return ROUTER_PURPOSE_GENERAL
;
3003 else if (!strcmp(s
, "bridge"))
3004 return ROUTER_PURPOSE_BRIDGE
;
3005 else if (!strcmp(s
, "controller"))
3006 return ROUTER_PURPOSE_CONTROLLER
;
3008 return ROUTER_PURPOSE_UNKNOWN
;
3011 /** Release all static resources held in router.c */
3013 router_free_all(void)
3015 crypto_pk_free(onionkey
);
3016 crypto_pk_free(lastonionkey
);
3017 crypto_pk_free(server_identitykey
);
3018 crypto_pk_free(client_identitykey
);
3019 tor_mutex_free(key_lock
);
3020 routerinfo_free(desc_routerinfo
);
3021 extrainfo_free(desc_extrainfo
);
3022 crypto_pk_free(authority_signing_key
);
3023 authority_cert_free(authority_key_certificate
);
3024 crypto_pk_free(legacy_signing_key
);
3025 authority_cert_free(legacy_key_certificate
);
3027 #ifdef CURVE25519_ENABLED
3028 memwipe(&curve25519_onion_key
, 0, sizeof(curve25519_onion_key
));
3029 memwipe(&last_curve25519_onion_key
, 0, sizeof(last_curve25519_onion_key
));
3032 if (warned_nonexistent_family
) {
3033 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
3034 smartlist_free(warned_nonexistent_family
);
3038 /** Return a smartlist of tor_addr_port_t's with all the OR ports of
3039 <b>ri</b>. Note that freeing of the items in the list as well as
3040 the smartlist itself is the callers responsibility.
3042 XXX duplicating code from node_get_all_orports(). */
3044 router_get_all_orports(const routerinfo_t
*ri
)
3046 smartlist_t
*sl
= smartlist_new();
3049 if (ri
->addr
!= 0) {
3050 tor_addr_port_t
*ap
= tor_malloc(sizeof(tor_addr_port_t
));
3051 tor_addr_from_ipv4h(&ap
->addr
, ri
->addr
);
3052 ap
->port
= ri
->or_port
;
3053 smartlist_add(sl
, ap
);
3055 if (!tor_addr_is_null(&ri
->ipv6_addr
)) {
3056 tor_addr_port_t
*ap
= tor_malloc(sizeof(tor_addr_port_t
));
3057 tor_addr_copy(&ap
->addr
, &ri
->ipv6_addr
);
3058 ap
->port
= ri
->or_port
;
3059 smartlist_add(sl
, ap
);