1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2015, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
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 "routerkeys.h"
30 #include "routerlist.h"
31 #include "routerparse.h"
32 #include "statefile.h"
34 #include "transports.h"
35 #include "routerset.h"
39 * \brief OR functionality, including key maintenance, generating
40 * and uploading server descriptors, retrying OR connections.
43 extern long stats_n_seconds_working
;
45 /************************************************************/
48 * Key management: ORs only.
51 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
53 static tor_mutex_t
*key_lock
=NULL
;
54 static time_t onionkey_set_at
=0; /**< When was onionkey last changed? */
55 /** Current private onionskin decryption key: used to decode CREATE cells. */
56 static crypto_pk_t
*onionkey
=NULL
;
57 /** Previous private onionskin decryption key: used to decode CREATE cells
58 * generated by clients that have an older version of our descriptor. */
59 static crypto_pk_t
*lastonionkey
=NULL
;
60 /** Current private ntor secret key: used to perform the ntor handshake. */
61 static curve25519_keypair_t curve25519_onion_key
;
62 /** Previous private ntor secret key: used to perform the ntor handshake
63 * with clients that have an older version of our descriptor. */
64 static curve25519_keypair_t last_curve25519_onion_key
;
65 /** Private server "identity key": used to sign directory info and TLS
66 * certificates. Never changes. */
67 static crypto_pk_t
*server_identitykey
=NULL
;
68 /** Digest of server_identitykey. */
69 static char server_identitykey_digest
[DIGEST_LEN
];
70 /** Private client "identity key": used to sign bridges' and clients'
71 * outbound TLS certificates. Regenerated on startup and on IP address
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 /** Return the current secret onion key for the ntor handshake. Must only
138 * be called from the main thread. */
139 static const curve25519_keypair_t
*
140 get_current_curve25519_keypair(void)
142 return &curve25519_onion_key
;
144 /** Return a map from KEYID (the key itself) to keypairs for use in the ntor
145 * handshake. Must only be called from the main thread. */
147 construct_ntor_key_map(void)
149 di_digest256_map_t
*m
= NULL
;
152 curve25519_onion_key
.pubkey
.public_key
,
153 tor_memdup(&curve25519_onion_key
,
154 sizeof(curve25519_keypair_t
)));
155 if (!tor_mem_is_zero((const char*)
156 last_curve25519_onion_key
.pubkey
.public_key
,
157 CURVE25519_PUBKEY_LEN
)) {
159 last_curve25519_onion_key
.pubkey
.public_key
,
160 tor_memdup(&last_curve25519_onion_key
,
161 sizeof(curve25519_keypair_t
)));
166 /** Helper used to deallocate a di_digest256_map_t returned by
167 * construct_ntor_key_map. */
169 ntor_key_map_free_helper(void *arg
)
171 curve25519_keypair_t
*k
= arg
;
172 memwipe(k
, 0, sizeof(*k
));
175 /** Release all storage from a keymap returned by construct_ntor_key_map. */
177 ntor_key_map_free(di_digest256_map_t
*map
)
181 dimap_free(map
, ntor_key_map_free_helper
);
184 /** Return the time when the onion key was last set. This is either the time
185 * when the process launched, or the time of the most recent key rotation since
186 * the process launched.
189 get_onion_key_set_at(void)
191 return onionkey_set_at
;
194 /** Set the current server identity key to <b>k</b>.
197 set_server_identity_key(crypto_pk_t
*k
)
199 crypto_pk_free(server_identitykey
);
200 server_identitykey
= k
;
201 crypto_pk_get_digest(server_identitykey
, server_identitykey_digest
);
204 /** Make sure that we have set up our identity keys to match or not match as
205 * appropriate, and die with an assertion if we have not. */
207 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 we are a server and the server identity key
238 server_identity_key_is_set(void)
240 return server_mode(get_options()) && server_identitykey
!= NULL
;
243 /** Set the current client identity key to <b>k</b>.
246 set_client_identity_key(crypto_pk_t
*k
)
248 crypto_pk_free(client_identitykey
);
249 client_identitykey
= k
;
252 /** Returns the current client identity key for use on outgoing TLS
253 * connections; requires that the key has been set.
256 get_tlsclient_identity_key(void)
258 tor_assert(client_identitykey
);
259 assert_identity_keys_ok();
260 return client_identitykey
;
263 /** Return true iff the client identity key has been set. */
265 client_identity_key_is_set(void)
267 return client_identitykey
!= NULL
;
270 /** Return the key certificate for this v3 (voting) authority, or NULL
271 * if we have no such certificate. */
272 MOCK_IMPL(authority_cert_t
*,
273 get_my_v3_authority_cert
, (void))
275 return authority_key_certificate
;
278 /** Return the v3 signing key for this v3 (voting) authority, or NULL
279 * if we have no such key. */
281 get_my_v3_authority_signing_key(void)
283 return authority_signing_key
;
286 /** If we're an authority, and we're using a legacy authority identity key for
287 * emergency migration purposes, return the certificate associated with that
290 get_my_v3_legacy_cert(void)
292 return legacy_key_certificate
;
295 /** If we're an authority, and we're using a legacy authority identity key for
296 * emergency migration purposes, return that key. */
298 get_my_v3_legacy_signing_key(void)
300 return legacy_signing_key
;
303 /** Replace the previous onion key with the current onion key, and generate
304 * a new previous onion key. Immediately after calling this function,
306 * - schedule all previous cpuworkers to shut down _after_ processing
307 * pending work. (This will cause fresh cpuworkers to be generated.)
308 * - generate and upload a fresh routerinfo.
311 rotate_onion_key(void)
313 char *fname
, *fname_prev
;
314 crypto_pk_t
*prkey
= NULL
;
315 or_state_t
*state
= get_or_state();
316 curve25519_keypair_t new_curve25519_keypair
;
318 fname
= get_datadir_fname2("keys", "secret_onion_key");
319 fname_prev
= get_datadir_fname2("keys", "secret_onion_key.old");
320 /* There isn't much point replacing an old key with an empty file */
321 if (file_status(fname
) == FN_FILE
) {
322 if (replace_file(fname
, fname_prev
))
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
);
338 tor_free(fname_prev
);
339 fname
= get_datadir_fname2("keys", "secret_onion_key_ntor");
340 fname_prev
= get_datadir_fname2("keys", "secret_onion_key_ntor.old");
341 if (curve25519_keypair_generate(&new_curve25519_keypair
, 1) < 0)
343 /* There isn't much point replacing an old key with an empty file */
344 if (file_status(fname
) == FN_FILE
) {
345 if (replace_file(fname
, fname_prev
))
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
);
353 log_info(LD_GENERAL
, "Rotating onion key");
354 tor_mutex_acquire(key_lock
);
355 crypto_pk_free(lastonionkey
);
356 lastonionkey
= onionkey
;
358 memcpy(&last_curve25519_onion_key
, &curve25519_onion_key
,
359 sizeof(curve25519_keypair_t
));
360 memcpy(&curve25519_onion_key
, &new_curve25519_keypair
,
361 sizeof(curve25519_keypair_t
));
363 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
364 tor_mutex_release(key_lock
);
365 mark_my_descriptor_dirty("rotated onion key");
366 or_state_mark_dirty(state
, get_options()->AvoidDiskWrites
? now
+3600 : 0);
369 log_warn(LD_GENERAL
, "Couldn't rotate onion key.");
371 crypto_pk_free(prkey
);
373 memwipe(&new_curve25519_keypair
, 0, sizeof(new_curve25519_keypair
));
375 tor_free(fname_prev
);
378 /** Log greeting message that points to new relay lifecycle document the
379 * first time this function has been called.
382 log_new_relay_greeting(void)
384 static int already_logged
= 0;
389 tor_log(LOG_NOTICE
, LD_GENERAL
, "You are running a new relay. "
390 "Thanks for helping the Tor network! If you wish to know "
391 "what will happen in the upcoming weeks regarding its usage, "
392 "have a look at https://blog.torproject.org/blog/lifecycle-of"
398 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
399 * and <b>generate</b> is true, create a new RSA key and save it in
400 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
401 * errors at level <b>severity</b>. If <b>log_greeting</b> is non-zero and a
402 * new key was created, log_new_relay_greeting() is called.
405 init_key_from_file(const char *fname
, int generate
, int severity
,
408 crypto_pk_t
*prkey
= NULL
;
410 if (!(prkey
= crypto_pk_new())) {
411 tor_log(severity
, LD_GENERAL
,"Error constructing key");
415 switch (file_status(fname
)) {
418 tor_log(severity
, LD_FS
,"Can't read key from \"%s\"", fname
);
420 /* treat empty key files as if the file doesn't exist, and,
421 * if generate is set, replace the empty file in
422 * crypto_pk_write_private_key_to_filename() */
426 if (!have_lockfile()) {
427 if (try_locking(get_options(), 0)<0) {
428 /* Make sure that --list-fingerprint only creates new keys
429 * if there is no possibility for a deadlock. */
430 tor_log(severity
, LD_FS
, "Another Tor process has locked \"%s\". "
431 "Not writing any new keys.", fname
);
432 /*XXXX The 'other process' might make a key in a second or two;
433 * maybe we should wait for it. */
437 log_info(LD_GENERAL
, "No key found in \"%s\"; generating fresh key.",
439 if (crypto_pk_generate_key(prkey
)) {
440 tor_log(severity
, LD_GENERAL
,"Error generating onion key");
443 if (crypto_pk_check_key(prkey
) <= 0) {
444 tor_log(severity
, LD_GENERAL
,"Generated key seems invalid");
447 log_info(LD_GENERAL
, "Generated key seems valid");
449 log_new_relay_greeting();
451 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
452 tor_log(severity
, LD_FS
,
453 "Couldn't write generated key to \"%s\".", fname
);
457 log_info(LD_GENERAL
, "No key found in \"%s\"", fname
);
461 if (crypto_pk_read_private_key_from_filename(prkey
, fname
)) {
462 tor_log(severity
, LD_GENERAL
,"Error loading private key.");
472 crypto_pk_free(prkey
);
476 /** Load a curve25519 keypair from the file <b>fname</b>, writing it into
477 * <b>keys_out</b>. If the file isn't found, or is empty, and <b>generate</b>
478 * is true, create a new keypair and write it into the file. If there are
479 * errors, log them at level <b>severity</b>. Generate files using <b>tag</b>
480 * in their ASCII wrapper. */
482 init_curve25519_keypair_from_file(curve25519_keypair_t
*keys_out
,
488 switch (file_status(fname
)) {
491 tor_log(severity
, LD_FS
,"Can't read key from \"%s\"", fname
);
493 /* treat empty key files as if the file doesn't exist, and, if generate
494 * is set, replace the empty file in curve25519_keypair_write_to_file() */
498 if (!have_lockfile()) {
499 if (try_locking(get_options(), 0)<0) {
500 /* Make sure that --list-fingerprint only creates new keys
501 * if there is no possibility for a deadlock. */
502 tor_log(severity
, LD_FS
, "Another Tor process has locked \"%s\". "
503 "Not writing any new keys.", fname
);
504 /*XXXX The 'other process' might make a key in a second or two;
505 * maybe we should wait for it. */
509 log_info(LD_GENERAL
, "No key found in \"%s\"; generating fresh key.",
511 if (curve25519_keypair_generate(keys_out
, 1) < 0)
513 if (curve25519_keypair_write_to_file(keys_out
, fname
, tag
)<0) {
514 tor_log(severity
, LD_FS
,
515 "Couldn't write generated key to \"%s\".", fname
);
516 memwipe(keys_out
, 0, sizeof(*keys_out
));
520 log_info(LD_GENERAL
, "No key found in \"%s\"", fname
);
526 if (curve25519_keypair_read_from_file(keys_out
, &tag_in
, fname
) < 0) {
527 tor_log(severity
, LD_GENERAL
,"Error loading private key.");
531 if (!tag_in
|| strcmp(tag_in
, tag
)) {
532 tor_log(severity
, LD_GENERAL
,"Unexpected tag %s on private key.",
548 /** Try to load the vote-signing private key and certificate for being a v3
549 * directory authority, and make sure they match. If <b>legacy</b>, load a
550 * legacy key/cert set for emergency key migration; otherwise load the regular
551 * key/cert set. On success, store them into *<b>key_out</b> and
552 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
554 load_authority_keyset(int legacy
, crypto_pk_t
**key_out
,
555 authority_cert_t
**cert_out
)
558 char *fname
= NULL
, *cert
= NULL
;
559 const char *eos
= NULL
;
560 crypto_pk_t
*signing_key
= NULL
;
561 authority_cert_t
*parsed
= NULL
;
563 fname
= get_datadir_fname2("keys",
564 legacy
? "legacy_signing_key" : "authority_signing_key");
565 signing_key
= init_key_from_file(fname
, 0, LOG_INFO
, 0);
567 log_warn(LD_DIR
, "No version 3 directory key found in %s", fname
);
571 fname
= get_datadir_fname2("keys",
572 legacy
? "legacy_certificate" : "authority_certificate");
573 cert
= read_file_to_str(fname
, 0, NULL
);
575 log_warn(LD_DIR
, "Signing key found, but no certificate found in %s",
579 parsed
= authority_cert_parse_from_string(cert
, &eos
);
581 log_warn(LD_DIR
, "Unable to parse certificate in %s", fname
);
584 if (!crypto_pk_eq_keys(signing_key
, parsed
->signing_key
)) {
585 log_warn(LD_DIR
, "Stored signing key does not match signing key in "
590 crypto_pk_free(*key_out
);
591 authority_cert_free(*cert_out
);
593 *key_out
= signing_key
;
602 crypto_pk_free(signing_key
);
603 authority_cert_free(parsed
);
607 /** Load the v3 (voting) authority signing key and certificate, if they are
608 * present. Return -1 if anything is missing, mismatched, or unloadable;
609 * return 0 on success. */
611 init_v3_authority_keys(void)
613 if (load_authority_keyset(0, &authority_signing_key
,
614 &authority_key_certificate
)<0)
617 if (get_options()->V3AuthUseLegacyKey
&&
618 load_authority_keyset(1, &legacy_signing_key
,
619 &legacy_key_certificate
)<0)
625 /** If we're a v3 authority, check whether we have a certificate that's
626 * likely to expire soon. Warn if we do, but not too often. */
628 v3_authority_check_key_expiry(void)
631 static time_t last_warned
= 0;
632 int badness
, time_left
, warn_interval
;
633 if (!authdir_mode_v3(get_options()) || !authority_key_certificate
)
637 expires
= authority_key_certificate
->expires
;
638 time_left
= (int)( expires
- now
);
639 if (time_left
<= 0) {
641 warn_interval
= 60*60;
642 } else if (time_left
<= 24*60*60) {
644 warn_interval
= 60*60;
645 } else if (time_left
<= 24*60*60*7) {
647 warn_interval
= 24*60*60;
648 } else if (time_left
<= 24*60*60*30) {
650 warn_interval
= 24*60*60*5;
655 if (last_warned
+ warn_interval
> now
)
658 if (time_left
<= 0) {
659 tor_log(badness
, LD_DIR
, "Your v3 authority certificate has expired."
660 " Generate a new one NOW.");
661 } else if (time_left
<= 24*60*60) {
662 tor_log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d "
663 "hours; Generate a new one NOW.", time_left
/(60*60));
665 tor_log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d "
666 "days; Generate a new one soon.", time_left
/(24*60*60));
671 /** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
672 * on success, and -1 on failure. */
674 router_initialize_tls_context(void)
676 unsigned int flags
= 0;
677 const or_options_t
*options
= get_options();
678 int lifetime
= options
->SSLKeyLifetime
;
679 if (public_server_mode(options
))
680 flags
|= TOR_TLS_CTX_IS_PUBLIC_SERVER
;
681 if (options
->TLSECGroup
) {
682 if (!strcasecmp(options
->TLSECGroup
, "P256"))
683 flags
|= TOR_TLS_CTX_USE_ECDHE_P256
;
684 else if (!strcasecmp(options
->TLSECGroup
, "P224"))
685 flags
|= TOR_TLS_CTX_USE_ECDHE_P224
;
687 if (!lifetime
) { /* we should guess a good ssl cert lifetime */
689 /* choose between 5 and 365 days, and round to the day */
690 unsigned int five_days
= 5*24*3600;
691 unsigned int one_year
= 365*24*3600;
692 lifetime
= crypto_rand_int_range(five_days
, one_year
);
693 lifetime
-= lifetime
% (24*3600);
695 if (crypto_rand_int(2)) {
696 /* Half the time we expire at midnight, and half the time we expire
697 * one second before midnight. (Some CAs wobble their expiry times a
698 * bit in practice, perhaps to reduce collision attacks; see ticket
699 * 8443 for details about observed certs in the wild.) */
704 /* It's ok to pass lifetime in as an unsigned int, since
705 * config_parse_interval() checked it. */
706 return tor_tls_context_init(flags
,
707 get_tlsclient_identity_key(),
708 server_mode(options
) ?
709 get_server_identity_key() : NULL
,
710 (unsigned int)lifetime
);
713 /** Compute fingerprint (or hashed fingerprint if hashed is 1) and write
714 * it to 'fingerprint' (or 'hashed-fingerprint'). Return 0 on success, or
715 * -1 if Tor should die,
718 router_write_fingerprint(int hashed
)
720 char *keydir
= NULL
, *cp
= NULL
;
721 const char *fname
= hashed
? "hashed-fingerprint" :
723 char fingerprint
[FINGERPRINT_LEN
+1];
724 const or_options_t
*options
= get_options();
725 char *fingerprint_line
= NULL
;
728 keydir
= get_datadir_fname(fname
);
729 log_info(LD_GENERAL
,"Dumping %sfingerprint to \"%s\"...",
730 hashed
? "hashed " : "", keydir
);
732 if (crypto_pk_get_fingerprint(get_server_identity_key(),
733 fingerprint
, 0) < 0) {
734 log_err(LD_GENERAL
,"Error computing fingerprint");
738 if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
740 log_err(LD_GENERAL
,"Error computing hashed fingerprint");
745 tor_asprintf(&fingerprint_line
, "%s %s\n", options
->Nickname
, fingerprint
);
747 /* Check whether we need to write the (hashed-)fingerprint file. */
749 cp
= read_file_to_str(keydir
, RFTS_IGNORE_MISSING
, NULL
);
750 if (!cp
|| strcmp(cp
, fingerprint_line
)) {
751 if (write_str_to_file(keydir
, fingerprint_line
, 0)) {
752 log_err(LD_FS
, "Error writing %sfingerprint line to file",
753 hashed
? "hashed " : "");
758 log_notice(LD_GENERAL
, "Your Tor %s identity key fingerprint is '%s %s'",
759 hashed
? "bridge's hashed" : "server's", options
->Nickname
,
766 tor_free(fingerprint_line
);
771 init_keys_common(void)
774 key_lock
= tor_mutex_new();
776 /* There are a couple of paths that put us here before we've asked
777 * openssl to initialize itself. */
778 if (crypto_global_init(get_options()->HardwareAccel
,
779 get_options()->AccelName
,
780 get_options()->AccelDir
)) {
781 log_err(LD_BUG
, "Unable to initialize OpenSSL. Exiting.");
789 init_keys_client(void)
792 if (init_keys_common() < 0)
795 if (!(prkey
= crypto_pk_new()))
797 if (crypto_pk_generate_key(prkey
)) {
798 crypto_pk_free(prkey
);
801 set_client_identity_key(prkey
);
802 /* Create a TLS context. */
803 if (router_initialize_tls_context() < 0) {
804 log_err(LD_GENERAL
,"Error creating TLS context for Tor client.");
810 /** Initialize all OR private keys, and the TLS context, as necessary.
811 * On OPs, this only initializes the tls context. Return 0 on success,
812 * or -1 if Tor should die.
820 char digest
[DIGEST_LEN
];
821 char v3_digest
[DIGEST_LEN
];
822 const or_options_t
*options
= get_options();
824 time_t now
= time(NULL
);
826 int v3_digest_set
= 0;
827 authority_cert_t
*cert
= NULL
;
829 /* OP's don't need persistent keys; just make up an identity and
830 * initialize the TLS context. */
831 if (!server_mode(options
)) {
832 return init_keys_client();
834 if (init_keys_common() < 0)
836 /* Make sure DataDirectory exists, and is private. */
837 if (check_private_dir(options
->DataDirectory
, CPD_CREATE
, options
->User
)) {
840 /* Check the key directory. */
841 keydir
= get_datadir_fname("keys");
842 if (check_private_dir(keydir
, CPD_CREATE
, options
->User
)) {
848 /* 1a. Read v3 directory authority key/cert information. */
849 memset(v3_digest
, 0, sizeof(v3_digest
));
850 if (authdir_mode_v3(options
)) {
851 if (init_v3_authority_keys()<0) {
852 log_err(LD_GENERAL
, "We're configured as a V3 authority, but we "
853 "were unable to load our v3 authority keys and certificate! "
854 "Use tor-gencert to generate them. Dying.");
857 cert
= get_my_v3_authority_cert();
859 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key
,
865 /* 1b. Read identity key. Make it if none is found. */
866 keydir
= get_datadir_fname2("keys", "secret_id_key");
867 log_info(LD_GENERAL
,"Reading/making identity key \"%s\"...",keydir
);
868 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
, 1);
870 if (!prkey
) return -1;
871 set_server_identity_key(prkey
);
873 /* 1c. If we are configured as a bridge, generate a client key;
874 * otherwise, set the server identity key as our client identity
876 if (public_server_mode(options
)) {
877 set_client_identity_key(crypto_pk_dup_key(prkey
)); /* set above */
879 if (!(prkey
= crypto_pk_new()))
881 if (crypto_pk_generate_key(prkey
)) {
882 crypto_pk_free(prkey
);
885 set_client_identity_key(prkey
);
888 /* 1d. Load all ed25519 keys */
889 if (load_ed_keys(options
,now
) < 0)
892 /* 2. Read onion key. Make it if none is found. */
893 keydir
= get_datadir_fname2("keys", "secret_onion_key");
894 log_info(LD_GENERAL
,"Reading/making onion key \"%s\"...",keydir
);
895 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
, 1);
897 if (!prkey
) return -1;
898 set_onion_key(prkey
);
899 if (options
->command
== CMD_RUN_TOR
) {
900 /* only mess with the state file if we're actually running Tor */
901 or_state_t
*state
= get_or_state();
902 if (state
->LastRotatedOnionKey
> 100 && state
->LastRotatedOnionKey
< now
) {
903 /* We allow for some parsing slop, but we don't want to risk accepting
904 * values in the distant future. If we did, we might never rotate the
906 onionkey_set_at
= state
->LastRotatedOnionKey
;
908 /* We have no LastRotatedOnionKey set; either we just created the key
909 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
910 * start the clock ticking now so that we will eventually rotate it even
911 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
912 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
913 or_state_mark_dirty(state
, options
->AvoidDiskWrites
?
914 time(NULL
)+3600 : 0);
918 keydir
= get_datadir_fname2("keys", "secret_onion_key.old");
919 if (!lastonionkey
&& file_status(keydir
) == FN_FILE
) {
920 /* Load keys from non-empty files only.
921 * Missing old keys won't be replaced with freshly generated keys. */
922 prkey
= init_key_from_file(keydir
, 0, LOG_ERR
, 0);
924 lastonionkey
= prkey
;
929 /* 2b. Load curve25519 onion keys. */
931 keydir
= get_datadir_fname2("keys", "secret_onion_key_ntor");
932 r
= init_curve25519_keypair_from_file(&curve25519_onion_key
,
933 keydir
, 1, LOG_ERR
, "onion");
938 keydir
= get_datadir_fname2("keys", "secret_onion_key_ntor.old");
939 if (tor_mem_is_zero((const char *)
940 last_curve25519_onion_key
.pubkey
.public_key
,
941 CURVE25519_PUBKEY_LEN
) &&
942 file_status(keydir
) == FN_FILE
) {
943 /* Load keys from non-empty files only.
944 * Missing old keys won't be replaced with freshly generated keys. */
945 init_curve25519_keypair_from_file(&last_curve25519_onion_key
,
946 keydir
, 0, LOG_ERR
, "onion");
951 /* 3. Initialize link key and TLS context. */
952 if (router_initialize_tls_context() < 0) {
953 log_err(LD_GENERAL
,"Error initializing TLS context");
957 /* 3b. Get an ed25519 link certificate. Note that we need to do this
958 * after we set up the TLS context */
959 if (generate_ed_link_cert(options
, now
) < 0) {
960 log_err(LD_GENERAL
,"Couldn't make link cert");
964 /* 4. Build our router descriptor. */
965 /* Must be called after keys are initialized. */
966 mydesc
= router_get_my_descriptor();
967 if (authdir_mode_handles_descs(options
, ROUTER_PURPOSE_GENERAL
)) {
968 const char *m
= NULL
;
970 /* We need to add our own fingerprint so it gets recognized. */
971 if (dirserv_add_own_fingerprint(get_server_identity_key())) {
972 log_err(LD_GENERAL
,"Error adding own fingerprint to set of relays");
976 was_router_added_t added
;
977 ri
= router_parse_entry_from_string(mydesc
, NULL
, 1, 0, NULL
, NULL
);
979 log_err(LD_GENERAL
,"Generated a routerinfo we couldn't parse.");
982 added
= dirserv_add_descriptor(ri
, &m
, "self");
983 if (!WRA_WAS_ADDED(added
)) {
984 if (!WRA_WAS_OUTDATED(added
)) {
985 log_err(LD_GENERAL
, "Unable to add own descriptor to directory: %s",
986 m
?m
:"<unknown error>");
989 /* If the descriptor was outdated, that's ok. This can happen
990 * when some config options are toggled that affect workers, but
991 * we don't really need new keys yet so the descriptor doesn't
992 * change and the old one is still fresh. */
993 log_info(LD_GENERAL
, "Couldn't add own descriptor to directory "
994 "after key init: %s This is usually not a problem.",
995 m
?m
:"<unknown error>");
1001 /* 5. Dump fingerprint and possibly hashed fingerprint to files. */
1002 if (router_write_fingerprint(0)) {
1003 log_err(LD_FS
, "Error writing fingerprint to file");
1006 if (!public_server_mode(options
) && router_write_fingerprint(1)) {
1007 log_err(LD_FS
, "Error writing hashed fingerprint to file");
1011 if (!authdir_mode(options
))
1013 /* 6. [authdirserver only] load approved-routers file */
1014 if (dirserv_load_fingerprint_file() < 0) {
1015 log_err(LD_GENERAL
,"Error loading fingerprints");
1018 /* 6b. [authdirserver only] add own key to approved directories. */
1019 crypto_pk_get_digest(get_server_identity_key(), digest
);
1020 type
= ((options
->V3AuthoritativeDir
?
1021 (V3_DIRINFO
|MICRODESC_DIRINFO
|EXTRAINFO_DIRINFO
) : NO_DIRINFO
) |
1022 (options
->BridgeAuthoritativeDir
? BRIDGE_DIRINFO
: NO_DIRINFO
));
1024 ds
= router_get_trusteddirserver_by_digest(digest
);
1026 ds
= trusted_dir_server_new(options
->Nickname
, NULL
,
1027 router_get_advertised_dir_port(options
, 0),
1028 router_get_advertised_or_port(options
),
1034 log_err(LD_GENERAL
,"We want to be a directory authority, but we "
1035 "couldn't add ourselves to the authority list. Failing.");
1040 if (ds
->type
!= type
) {
1041 log_warn(LD_DIR
, "Configured authority type does not match authority "
1042 "type in DirAuthority list. Adjusting. (%d v %d)",
1046 if (v3_digest_set
&& (ds
->type
& V3_DIRINFO
) &&
1047 tor_memneq(v3_digest
, ds
->v3_identity_digest
, DIGEST_LEN
)) {
1048 log_warn(LD_DIR
, "V3 identity key does not match identity declared in "
1049 "DirAuthority line. Adjusting.");
1050 memcpy(ds
->v3_identity_digest
, v3_digest
, DIGEST_LEN
);
1053 if (cert
) { /* add my own cert to the list of known certs */
1054 log_info(LD_DIR
, "adding my own v3 cert");
1055 if (trusted_dirs_load_certs_from_string(
1056 cert
->cache_info
.signed_descriptor_body
,
1057 TRUSTED_DIRS_CERTS_SRC_SELF
, 0)<0) {
1058 log_warn(LD_DIR
, "Unable to parse my own v3 cert! Failing.");
1063 return 0; /* success */
1066 /* Keep track of whether we should upload our server descriptor,
1067 * and what type of server we are.
1070 /** Whether we can reach our ORPort from the outside. */
1071 static int can_reach_or_port
= 0;
1072 /** Whether we can reach our DirPort from the outside. */
1073 static int can_reach_dir_port
= 0;
1075 /** Forget what we have learned about our reachability status. */
1077 router_reset_reachability(void)
1079 can_reach_or_port
= can_reach_dir_port
= 0;
1082 /** Return 1 if ORPort is known reachable; else return 0. */
1084 check_whether_orport_reachable(void)
1086 const or_options_t
*options
= get_options();
1087 return options
->AssumeReachable
||
1091 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
1093 check_whether_dirport_reachable(void)
1095 const or_options_t
*options
= get_options();
1096 return !options
->DirPort_set
||
1097 options
->AssumeReachable
||
1098 net_is_disabled() ||
1102 /** Look at a variety of factors, and return 0 if we don't want to
1103 * advertise the fact that we have a DirPort open. Else return the
1104 * DirPort we want to advertise.
1106 * Log a helpful message if we change our mind about whether to publish
1110 decide_to_advertise_dirport(const or_options_t
*options
, uint16_t dir_port
)
1112 static int advertising
=1; /* start out assuming we will advertise */
1114 const char *reason
= NULL
;
1116 /* Section one: reasons to publish or not publish that aren't
1117 * worth mentioning to the user, either because they're obvious
1118 * or because they're normal behavior. */
1120 if (!dir_port
) /* short circuit the rest of the function */
1122 if (authdir_mode(options
)) /* always publish */
1124 if (net_is_disabled())
1126 if (!check_whether_dirport_reachable())
1128 if (!router_get_advertised_dir_port(options
, dir_port
))
1131 /* Section two: reasons to publish or not publish that the user
1132 * might find surprising. These are generally config options that
1133 * make us choose not to publish. */
1135 if (accounting_is_enabled(options
)) {
1136 /* Don't spend bytes for directory traffic if we could end up hibernating,
1137 * but allow DirPort otherwise. Some people set AccountingMax because
1138 * they're confused or to get statistics. */
1139 int interval_length
= accounting_get_interval_length();
1140 uint32_t effective_bw
= get_effective_bwrate(options
);
1142 if (!interval_length
) {
1143 log_warn(LD_BUG
, "An accounting interval is not allowed to be zero "
1144 "seconds long. Raising to 1.");
1145 interval_length
= 1;
1147 log_info(LD_GENERAL
, "Calculating whether to disable dirport: effective "
1148 "bwrate: %u, AccountingMax: "U64_FORMAT
", "
1149 "accounting interval length %d", effective_bw
,
1150 U64_PRINTF_ARG(options
->AccountingMax
),
1153 acc_bytes
= options
->AccountingMax
;
1154 if (get_options()->AccountingRule
== ACCT_SUM
)
1157 acc_bytes
/ interval_length
) {
1159 reason
= "AccountingMax enabled";
1161 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
1162 } else if (options
->BandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
||
1163 (options
->RelayBandwidthRate
> 0 &&
1164 options
->RelayBandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
)) {
1165 /* if we're advertising a small amount */
1167 reason
= "BandwidthRate under 50KB";
1170 if (advertising
!= new_choice
) {
1171 if (new_choice
== 1) {
1172 log_notice(LD_DIR
, "Advertising DirPort as %d", dir_port
);
1175 log_notice(LD_DIR
, "Not advertising DirPort (Reason: %s)", reason
);
1177 advertising
= new_choice
;
1180 return advertising
? dir_port
: 0;
1183 /** Allocate and return a new extend_info_t that can be used to build
1184 * a circuit to or through the router <b>r</b>. Use the primary
1185 * address of the router unless <b>for_direct_connect</b> is true, in
1186 * which case the preferred address is used instead. */
1187 static extend_info_t
*
1188 extend_info_from_router(const routerinfo_t
*r
)
1193 router_get_prim_orport(r
, &ap
);
1194 return extend_info_new(r
->nickname
, r
->cache_info
.identity_digest
,
1195 r
->onion_pkey
, r
->onion_curve25519_pkey
,
1199 /** Some time has passed, or we just got new directory information.
1200 * See if we currently believe our ORPort or DirPort to be
1201 * unreachable. If so, launch a new test for it.
1203 * For ORPort, we simply try making a circuit that ends at ourselves.
1204 * Success is noticed in onionskin_answer().
1206 * For DirPort, we make a connection via Tor to our DirPort and ask
1207 * for our own server descriptor.
1208 * Success is noticed in connection_dir_client_reached_eof().
1211 consider_testing_reachability(int test_or
, int test_dir
)
1213 const routerinfo_t
*me
= router_get_my_routerinfo();
1214 int orport_reachable
= check_whether_orport_reachable();
1216 const or_options_t
*options
= get_options();
1220 if (routerset_contains_router(options
->ExcludeNodes
, me
, -1) &&
1221 options
->StrictNodes
) {
1222 /* If we've excluded ourself, and StrictNodes is set, we can't test
1224 if (test_or
|| test_dir
) {
1225 #define SELF_EXCLUDED_WARN_INTERVAL 3600
1226 static ratelim_t warning_limit
=RATELIM_INIT(SELF_EXCLUDED_WARN_INTERVAL
);
1227 log_fn_ratelim(&warning_limit
, LOG_WARN
, LD_CIRC
,
1228 "Can't peform self-tests for this relay: we have "
1229 "listed ourself in ExcludeNodes, and StrictNodes is set. "
1230 "We cannot learn whether we are usable, and will not "
1231 "be able to advertise ourself.");
1236 if (test_or
&& (!orport_reachable
|| !circuit_enough_testing_circs())) {
1237 extend_info_t
*ei
= extend_info_from_router(me
);
1238 /* XXX IPv6 self testing */
1239 log_info(LD_CIRC
, "Testing %s of my ORPort: %s:%d.",
1240 !orport_reachable
? "reachability" : "bandwidth",
1241 fmt_addr32(me
->addr
), me
->or_port
);
1242 circuit_launch_by_extend_info(CIRCUIT_PURPOSE_TESTING
, ei
,
1243 CIRCLAUNCH_NEED_CAPACITY
|CIRCLAUNCH_IS_INTERNAL
);
1244 extend_info_free(ei
);
1247 tor_addr_from_ipv4h(&addr
, me
->addr
);
1248 if (test_dir
&& !check_whether_dirport_reachable() &&
1249 !connection_get_by_type_addr_port_purpose(
1250 CONN_TYPE_DIR
, &addr
, me
->dir_port
,
1251 DIR_PURPOSE_FETCH_SERVERDESC
)) {
1252 /* ask myself, via tor, for my server descriptor. */
1253 directory_initiate_command(&addr
,
1254 me
->or_port
, me
->dir_port
,
1255 me
->cache_info
.identity_digest
,
1256 DIR_PURPOSE_FETCH_SERVERDESC
,
1257 ROUTER_PURPOSE_GENERAL
,
1258 DIRIND_ANON_DIRPORT
, "authority.z", NULL
, 0, 0);
1262 /** Annotate that we found our ORPort reachable. */
1264 router_orport_found_reachable(void)
1266 const routerinfo_t
*me
= router_get_my_routerinfo();
1267 if (!can_reach_or_port
&& me
) {
1268 char *address
= tor_dup_ip(me
->addr
);
1269 log_notice(LD_OR
,"Self-testing indicates your ORPort is reachable from "
1270 "the outside. Excellent.%s",
1271 get_options()->PublishServerDescriptor_
!= NO_DIRINFO
?
1272 " Publishing server descriptor." : "");
1273 can_reach_or_port
= 1;
1274 mark_my_descriptor_dirty("ORPort found reachable");
1275 /* This is a significant enough change to upload immediately,
1276 * at least in a test network */
1277 if (get_options()->TestingTorNetwork
== 1) {
1278 reschedule_descriptor_update_check();
1280 control_event_server_status(LOG_NOTICE
,
1281 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
1282 address
, me
->or_port
);
1287 /** Annotate that we found our DirPort reachable. */
1289 router_dirport_found_reachable(void)
1291 const routerinfo_t
*me
= router_get_my_routerinfo();
1292 if (!can_reach_dir_port
&& me
) {
1293 char *address
= tor_dup_ip(me
->addr
);
1294 log_notice(LD_DIRSERV
,"Self-testing indicates your DirPort is reachable "
1295 "from the outside. Excellent.");
1296 can_reach_dir_port
= 1;
1297 if (decide_to_advertise_dirport(get_options(), me
->dir_port
)) {
1298 mark_my_descriptor_dirty("DirPort found reachable");
1299 /* This is a significant enough change to upload immediately,
1300 * at least in a test network */
1301 if (get_options()->TestingTorNetwork
== 1) {
1302 reschedule_descriptor_update_check();
1305 control_event_server_status(LOG_NOTICE
,
1306 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
1307 address
, me
->dir_port
);
1312 /** We have enough testing circuits open. Send a bunch of "drop"
1313 * cells down each of them, to exercise our bandwidth. */
1315 router_perform_bandwidth_test(int num_circs
, time_t now
)
1317 int num_cells
= (int)(get_options()->BandwidthRate
* 10 /
1318 CELL_MAX_NETWORK_SIZE
);
1319 int max_cells
= num_cells
< CIRCWINDOW_START
?
1320 num_cells
: CIRCWINDOW_START
;
1321 int cells_per_circuit
= max_cells
/ num_circs
;
1322 origin_circuit_t
*circ
= NULL
;
1324 log_notice(LD_OR
,"Performing bandwidth self-test...done.");
1325 while ((circ
= circuit_get_next_by_pk_and_purpose(circ
, NULL
,
1326 CIRCUIT_PURPOSE_TESTING
))) {
1327 /* dump cells_per_circuit drop cells onto this circ */
1328 int i
= cells_per_circuit
;
1329 if (circ
->base_
.state
!= CIRCUIT_STATE_OPEN
)
1331 circ
->base_
.timestamp_dirty
= now
;
1333 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
1335 NULL
, 0, circ
->cpath
->prev
)<0) {
1336 return; /* stop if error */
1342 /** Return true iff our network is in some sense disabled: either we're
1343 * hibernating, entering hibernation, or the network is turned off with
1344 * DisableNetwork. */
1346 net_is_disabled(void)
1348 return get_options()->DisableNetwork
|| we_are_hibernating();
1351 /** Return true iff we believe ourselves to be an authoritative
1355 authdir_mode(const or_options_t
*options
)
1357 return options
->AuthoritativeDir
!= 0;
1359 /** Return true iff we believe ourselves to be a v3 authoritative
1363 authdir_mode_v3(const or_options_t
*options
)
1365 return authdir_mode(options
) && options
->V3AuthoritativeDir
!= 0;
1367 /** Return true iff we are a v3 directory authority. */
1369 authdir_mode_any_main(const or_options_t
*options
)
1371 return options
->V3AuthoritativeDir
;
1373 /** Return true if we believe ourselves to be any kind of
1374 * authoritative directory beyond just a hidserv authority. */
1376 authdir_mode_any_nonhidserv(const or_options_t
*options
)
1378 return options
->BridgeAuthoritativeDir
||
1379 authdir_mode_any_main(options
);
1381 /** Return true iff we are an authoritative directory server that is
1382 * authoritative about receiving and serving descriptors of type
1383 * <b>purpose</b> on its dirport. Use -1 for "any purpose". */
1385 authdir_mode_handles_descs(const or_options_t
*options
, int purpose
)
1388 return authdir_mode_any_nonhidserv(options
);
1389 else if (purpose
== ROUTER_PURPOSE_GENERAL
)
1390 return authdir_mode_any_main(options
);
1391 else if (purpose
== ROUTER_PURPOSE_BRIDGE
)
1392 return (options
->BridgeAuthoritativeDir
);
1396 /** Return true iff we are an authoritative directory server that
1397 * publishes its own network statuses.
1400 authdir_mode_publishes_statuses(const or_options_t
*options
)
1402 if (authdir_mode_bridge(options
))
1404 return authdir_mode_any_nonhidserv(options
);
1406 /** Return true iff we are an authoritative directory server that
1407 * tests reachability of the descriptors it learns about.
1410 authdir_mode_tests_reachability(const or_options_t
*options
)
1412 return authdir_mode_handles_descs(options
, -1);
1414 /** Return true iff we believe ourselves to be a bridge authoritative
1418 authdir_mode_bridge(const or_options_t
*options
)
1420 return authdir_mode(options
) && options
->BridgeAuthoritativeDir
!= 0;
1423 /** Return true iff we are trying to be a server.
1426 server_mode
,(const or_options_t
*options
))
1428 if (options
->ClientOnly
) return 0;
1429 /* XXXX024 I believe we can kill off ORListenAddress here.*/
1430 return (options
->ORPort_set
|| options
->ORListenAddress
);
1433 /** Return true iff we are trying to be a non-bridge server.
1436 public_server_mode
,(const or_options_t
*options
))
1438 if (!server_mode(options
)) return 0;
1439 return (!options
->BridgeRelay
);
1442 /** Return true iff the combination of options in <b>options</b> and parameters
1443 * in the consensus mean that we don't want to allow exits from circuits
1444 * we got from addresses not known to be servers. */
1446 should_refuse_unknown_exits(const or_options_t
*options
)
1448 if (options
->RefuseUnknownExits
!= -1) {
1449 return options
->RefuseUnknownExits
;
1451 return networkstatus_get_param(NULL
, "refuseunknownexits", 1, 0, 1);
1455 /** Remember if we've advertised ourselves to the dirservers. */
1456 static int server_is_advertised
=0;
1458 /** Return true iff we have published our descriptor lately.
1461 advertised_server_mode(void)
1463 return server_is_advertised
;
1467 * Called with a boolean: set whether we have recently published our
1471 set_server_advertised(int s
)
1473 server_is_advertised
= s
;
1476 /** Return true iff we are trying to proxy client connections. */
1478 proxy_mode(const or_options_t
*options
)
1481 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t
*, p
) {
1482 if (p
->type
== CONN_TYPE_AP_LISTENER
||
1483 p
->type
== CONN_TYPE_AP_TRANS_LISTENER
||
1484 p
->type
== CONN_TYPE_AP_DNS_LISTENER
||
1485 p
->type
== CONN_TYPE_AP_NATD_LISTENER
)
1487 } SMARTLIST_FOREACH_END(p
);
1491 /** Decide if we're a publishable server. We are a publishable server if:
1492 * - We don't have the ClientOnly option set
1494 * - We have the PublishServerDescriptor option set to non-empty
1496 * - We have ORPort set
1498 * - We believe we are reachable from the outside; or
1499 * - We are an authoritative directory server.
1502 decide_if_publishable_server(void)
1504 const or_options_t
*options
= get_options();
1506 if (options
->ClientOnly
)
1508 if (options
->PublishServerDescriptor_
== NO_DIRINFO
)
1510 if (!server_mode(options
))
1512 if (authdir_mode(options
))
1514 if (!router_get_advertised_or_port(options
))
1517 return check_whether_orport_reachable();
1520 /** Initiate server descriptor upload as reasonable (if server is publishable,
1521 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1523 * We need to rebuild the descriptor if it's dirty even if we're not
1524 * uploading, because our reachability testing *uses* our descriptor to
1525 * determine what IP address and ports to test.
1528 consider_publishable_server(int force
)
1532 if (!server_mode(get_options()))
1535 rebuilt
= router_rebuild_descriptor(0);
1536 if (decide_if_publishable_server()) {
1537 set_server_advertised(1);
1539 router_upload_dir_desc_to_dirservers(force
);
1541 set_server_advertised(0);
1545 /** Return the port of the first active listener of type
1546 * <b>listener_type</b>. */
1547 /** XXX not a very good interface. it's not reliable when there are
1548 multiple listeners. */
1550 router_get_active_listener_port_by_type_af(int listener_type
,
1553 /* Iterate all connections, find one of the right kind and return
1554 the port. Not very sophisticated or fast, but effective. */
1555 smartlist_t
*conns
= get_connection_array();
1556 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
1557 if (conn
->type
== listener_type
&& !conn
->marked_for_close
&&
1558 conn
->socket_family
== family
) {
1561 } SMARTLIST_FOREACH_END(conn
);
1566 /** Return the port that we should advertise as our ORPort; this is either
1567 * the one configured in the ORPort option, or the one we actually bound to
1568 * if ORPort is "auto".
1571 router_get_advertised_or_port(const or_options_t
*options
)
1573 return router_get_advertised_or_port_by_af(options
, AF_INET
);
1576 /** As router_get_advertised_or_port(), but allows an address family argument.
1579 router_get_advertised_or_port_by_af(const or_options_t
*options
,
1582 int port
= get_first_advertised_port_by_type_af(CONN_TYPE_OR_LISTENER
,
1586 /* If the port is in 'auto' mode, we have to use
1587 router_get_listener_port_by_type(). */
1588 if (port
== CFG_AUTO_PORT
)
1589 return router_get_active_listener_port_by_type_af(CONN_TYPE_OR_LISTENER
,
1595 /** Return the port that we should advertise as our DirPort;
1596 * this is one of three possibilities:
1597 * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
1598 * the one configured in the DirPort option,
1599 * or the one we actually bound to if DirPort is "auto". */
1601 router_get_advertised_dir_port(const or_options_t
*options
, uint16_t dirport
)
1603 int dirport_configured
= get_primary_dir_port();
1606 if (!dirport_configured
)
1609 if (dirport_configured
== CFG_AUTO_PORT
)
1610 return router_get_active_listener_port_by_type_af(CONN_TYPE_DIR_LISTENER
,
1613 return dirport_configured
;
1617 * OR descriptor generation.
1620 /** My routerinfo. */
1621 static routerinfo_t
*desc_routerinfo
= NULL
;
1623 static extrainfo_t
*desc_extrainfo
= NULL
;
1624 /** Why did we most recently decide to regenerate our descriptor? Used to
1625 * tell the authorities why we're sending it to them. */
1626 static const char *desc_gen_reason
= NULL
;
1627 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1629 static time_t desc_clean_since
= 0;
1630 /** Why did we mark the descriptor dirty? */
1631 static const char *desc_dirty_reason
= NULL
;
1632 /** Boolean: do we need to regenerate the above? */
1633 static int desc_needs_upload
= 0;
1635 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1636 * descriptor successfully yet, try to upload our signed descriptor to
1637 * all the directory servers we know about.
1640 router_upload_dir_desc_to_dirservers(int force
)
1642 const routerinfo_t
*ri
;
1645 size_t desc_len
, extra_len
= 0, total_len
;
1646 dirinfo_type_t auth
= get_options()->PublishServerDescriptor_
;
1648 ri
= router_get_my_routerinfo();
1650 log_info(LD_GENERAL
, "No descriptor; skipping upload");
1653 ei
= router_get_my_extrainfo();
1654 if (auth
== NO_DIRINFO
)
1656 if (!force
&& !desc_needs_upload
)
1659 log_info(LD_OR
, "Uploading relay descriptor to directory authorities%s",
1660 force
? " (forced)" : "");
1662 desc_needs_upload
= 0;
1664 desc_len
= ri
->cache_info
.signed_descriptor_len
;
1665 extra_len
= ei
? ei
->cache_info
.signed_descriptor_len
: 0;
1666 total_len
= desc_len
+ extra_len
+ 1;
1667 msg
= tor_malloc(total_len
);
1668 memcpy(msg
, ri
->cache_info
.signed_descriptor_body
, desc_len
);
1670 memcpy(msg
+desc_len
, ei
->cache_info
.signed_descriptor_body
, extra_len
);
1672 msg
[desc_len
+extra_len
] = 0;
1674 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR
,
1675 (auth
& BRIDGE_DIRINFO
) ?
1676 ROUTER_PURPOSE_BRIDGE
:
1677 ROUTER_PURPOSE_GENERAL
,
1678 auth
, msg
, desc_len
, extra_len
);
1682 /** OR only: Check whether my exit policy says to allow connection to
1683 * conn. Return 0 if we accept; non-0 if we reject.
1686 router_compare_to_my_exit_policy(const tor_addr_t
*addr
, uint16_t port
)
1688 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1691 /* make sure it's resolved to something. this way we can't get a
1693 if (tor_addr_is_null(addr
))
1696 /* look at desc_routerinfo->exit_policy for both the v4 and the v6
1697 * policies. The exit_policy field in desc_routerinfo is a bit unusual,
1698 * in that it contains IPv6 and IPv6 entries. We don't want to look
1699 * at desc_routerinfio->ipv6_exit_policy, since that's a port summary. */
1700 if ((tor_addr_family(addr
) == AF_INET
||
1701 tor_addr_family(addr
) == AF_INET6
)) {
1702 return compare_tor_addr_to_addr_policy(addr
, port
,
1703 desc_routerinfo
->exit_policy
) != ADDR_POLICY_ACCEPTED
;
1705 } else if (tor_addr_family(addr
) == AF_INET6
) {
1706 return get_options()->IPv6Exit
&&
1707 desc_routerinfo
->ipv6_exit_policy
&&
1708 compare_tor_addr_to_short_policy(addr
, port
,
1709 desc_routerinfo
->ipv6_exit_policy
) != ADDR_POLICY_ACCEPTED
;
1716 /** Return true iff my exit policy is reject *:*. Return -1 if we don't
1717 * have a descriptor */
1719 router_my_exit_policy_is_reject_star
,(void))
1721 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1724 return desc_routerinfo
->policy_is_reject_star
;
1727 /** Return true iff I'm a server and <b>digest</b> is equal to
1728 * my server identity key digest. */
1730 router_digest_is_me(const char *digest
)
1732 return (server_identitykey
&&
1733 tor_memeq(server_identitykey_digest
, digest
, DIGEST_LEN
));
1736 /** Return my identity digest. */
1738 router_get_my_id_digest(void)
1740 return (const uint8_t *)server_identitykey_digest
;
1743 /** Return true iff I'm a server and <b>digest</b> is equal to
1744 * my identity digest. */
1746 router_extrainfo_digest_is_me(const char *digest
)
1748 extrainfo_t
*ei
= router_get_my_extrainfo();
1752 return tor_memeq(digest
,
1753 ei
->cache_info
.signed_descriptor_digest
,
1757 /** A wrapper around router_digest_is_me(). */
1759 router_is_me(const routerinfo_t
*router
)
1761 return router_digest_is_me(router
->cache_info
.identity_digest
);
1764 /** Return a routerinfo for this OR, rebuilding a fresh one if
1765 * necessary. Return NULL on error, or if called on an OP. */
1766 MOCK_IMPL(const routerinfo_t
*,
1767 router_get_my_routerinfo
,(void))
1769 if (!server_mode(get_options()))
1771 if (router_rebuild_descriptor(0))
1773 return desc_routerinfo
;
1776 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1777 * one if necessary. Return NULL on error.
1780 router_get_my_descriptor(void)
1783 if (!router_get_my_routerinfo())
1785 tor_assert(desc_routerinfo
->cache_info
.saved_location
== SAVED_NOWHERE
);
1786 body
= signed_descriptor_get_body(&desc_routerinfo
->cache_info
);
1787 /* Make sure this is nul-terminated. */
1788 tor_assert(!body
[desc_routerinfo
->cache_info
.signed_descriptor_len
]);
1789 log_debug(LD_GENERAL
,"my desc is '%s'", body
);
1793 /** Return the extrainfo document for this OR, or NULL if we have none.
1794 * Rebuilt it (and the server descriptor) if necessary. */
1796 router_get_my_extrainfo(void)
1798 if (!server_mode(get_options()))
1800 if (router_rebuild_descriptor(0))
1802 return desc_extrainfo
;
1805 /** Return a human-readable string describing what triggered us to generate
1806 * our current descriptor, or NULL if we don't know. */
1808 router_get_descriptor_gen_reason(void)
1810 return desc_gen_reason
;
1813 /** A list of nicknames that we've warned about including in our family
1814 * declaration verbatim rather than as digests. */
1815 static smartlist_t
*warned_nonexistent_family
= NULL
;
1817 static int router_guess_address_from_dir_headers(uint32_t *guess
);
1819 /** Make a current best guess at our address, either because
1820 * it's configured in torrc, or because we've learned it from
1821 * dirserver headers. Place the answer in *<b>addr</b> and return
1822 * 0 on success, else return -1 if we have no guess. */
1824 router_pick_published_address(const or_options_t
*options
, uint32_t *addr
)
1826 *addr
= get_last_resolved_addr();
1828 resolve_my_address(LOG_INFO
, options
, addr
, NULL
, NULL
) < 0) {
1829 log_info(LD_CONFIG
, "Could not determine our address locally. "
1830 "Checking if directory headers provide any hints.");
1831 if (router_guess_address_from_dir_headers(addr
) < 0) {
1832 log_info(LD_CONFIG
, "No hints from directory headers either. "
1833 "Will try again later.");
1837 log_info(LD_CONFIG
,"Success: chose address '%s'.", fmt_addr32(*addr
));
1841 /** Build a fresh routerinfo, signed server descriptor, and extra-info document
1842 * for this OR. Set r to the generated routerinfo, e to the generated
1843 * extra-info document. Return 0 on success, -1 on temporary error. Failure to
1844 * generate an extra-info document is not an error and is indicated by setting
1845 * e to NULL. Caller is responsible for freeing generated documents if 0 is
1849 router_build_fresh_descriptor(routerinfo_t
**r
, extrainfo_t
**e
)
1855 int hibernating
= we_are_hibernating();
1856 const or_options_t
*options
= get_options();
1858 if (router_pick_published_address(options
, &addr
) < 0) {
1859 log_warn(LD_CONFIG
, "Don't know my address while generating descriptor");
1863 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
1864 ri
->cache_info
.routerlist_index
= -1;
1865 ri
->nickname
= tor_strdup(options
->Nickname
);
1867 ri
->or_port
= router_get_advertised_or_port(options
);
1868 ri
->dir_port
= router_get_advertised_dir_port(options
, 0);
1869 ri
->cache_info
.published_on
= time(NULL
);
1870 ri
->onion_pkey
= crypto_pk_dup_key(get_onion_key()); /* must invoke from
1872 ri
->onion_curve25519_pkey
=
1873 tor_memdup(&get_current_curve25519_keypair()->pubkey
,
1874 sizeof(curve25519_public_key_t
));
1876 /* For now, at most one IPv6 or-address is being advertised. */
1878 const port_cfg_t
*ipv6_orport
= NULL
;
1879 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t
*, p
) {
1880 if (p
->type
== CONN_TYPE_OR_LISTENER
&&
1881 ! p
->server_cfg
.no_advertise
&&
1882 ! p
->server_cfg
.bind_ipv4_only
&&
1883 tor_addr_family(&p
->addr
) == AF_INET6
) {
1884 if (! tor_addr_is_internal(&p
->addr
, 0)) {
1888 char addrbuf
[TOR_ADDR_BUF_LEN
];
1890 "Unable to use configured IPv6 address \"%s\" in a "
1891 "descriptor. Skipping it. "
1892 "Try specifying a globally reachable address explicitly. ",
1893 tor_addr_to_str(addrbuf
, &p
->addr
, sizeof(addrbuf
), 1));
1896 } SMARTLIST_FOREACH_END(p
);
1898 tor_addr_copy(&ri
->ipv6_addr
, &ipv6_orport
->addr
);
1899 ri
->ipv6_orport
= ipv6_orport
->port
;
1903 ri
->identity_pkey
= crypto_pk_dup_key(get_server_identity_key());
1904 if (crypto_pk_get_digest(ri
->identity_pkey
,
1905 ri
->cache_info
.identity_digest
)<0) {
1906 routerinfo_free(ri
);
1909 ri
->signing_key_cert
= tor_cert_dup(get_master_signing_key_cert());
1911 get_platform_str(platform
, sizeof(platform
));
1912 ri
->platform
= tor_strdup(platform
);
1914 /* compute ri->bandwidthrate as the min of various options */
1915 ri
->bandwidthrate
= get_effective_bwrate(options
);
1917 /* and compute ri->bandwidthburst similarly */
1918 ri
->bandwidthburst
= get_effective_bwburst(options
);
1920 ri
->bandwidthcapacity
= hibernating
? 0 : rep_hist_bandwidth_assess();
1922 if (dns_seems_to_be_broken() || has_dns_init_failed()) {
1923 /* DNS is screwed up; don't claim to be an exit. */
1924 policies_exit_policy_append_reject_star(&ri
->exit_policy
);
1926 policies_parse_exit_policy_from_options(options
,ri
->addr
,&ri
->ipv6_addr
,
1929 ri
->policy_is_reject_star
=
1930 policy_is_reject_star(ri
->exit_policy
, AF_INET
) &&
1931 policy_is_reject_star(ri
->exit_policy
, AF_INET6
);
1933 if (options
->IPv6Exit
) {
1934 char *p_tmp
= policy_summarize(ri
->exit_policy
, AF_INET6
);
1936 ri
->ipv6_exit_policy
= parse_short_policy(p_tmp
);
1940 if (options
->MyFamily
&& ! options
->BridgeRelay
) {
1941 smartlist_t
*family
;
1942 if (!warned_nonexistent_family
)
1943 warned_nonexistent_family
= smartlist_new();
1944 family
= smartlist_new();
1945 ri
->declared_family
= smartlist_new();
1946 smartlist_split_string(family
, options
->MyFamily
, ",",
1947 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
|SPLIT_STRIP_SPACE
, 0);
1948 SMARTLIST_FOREACH_BEGIN(family
, char *, name
) {
1949 const node_t
*member
;
1950 if (!strcasecmp(name
, options
->Nickname
))
1951 goto skip
; /* Don't list ourself, that's redundant */
1953 member
= node_get_by_nickname(name
, 1);
1955 int is_legal
= is_legal_nickname_or_hexdigest(name
);
1956 if (!smartlist_contains_string(warned_nonexistent_family
, name
) &&
1957 !is_legal_hexdigest(name
)) {
1960 "I have no descriptor for the router named \"%s\" in my "
1961 "declared family; I'll use the nickname as is, but "
1962 "this may confuse clients.", name
);
1964 log_warn(LD_CONFIG
, "There is a router named \"%s\" in my "
1965 "declared family, but that isn't a legal nickname. "
1966 "Skipping it.", escaped(name
));
1967 smartlist_add(warned_nonexistent_family
, tor_strdup(name
));
1970 smartlist_add(ri
->declared_family
, name
);
1973 } else if (router_digest_is_me(member
->identity
)) {
1974 /* Don't list ourself in our own family; that's redundant */
1975 /* XXX shouldn't be possible */
1977 char *fp
= tor_malloc(HEX_DIGEST_LEN
+2);
1979 base16_encode(fp
+1,HEX_DIGEST_LEN
+1,
1980 member
->identity
, DIGEST_LEN
);
1981 smartlist_add(ri
->declared_family
, fp
);
1982 if (smartlist_contains_string(warned_nonexistent_family
, name
))
1983 smartlist_string_remove(warned_nonexistent_family
, name
);
1987 } SMARTLIST_FOREACH_END(name
);
1989 /* remove duplicates from the list */
1990 smartlist_sort_strings(ri
->declared_family
);
1991 smartlist_uniq_strings(ri
->declared_family
);
1993 smartlist_free(family
);
1996 /* Now generate the extrainfo. */
1997 ei
= tor_malloc_zero(sizeof(extrainfo_t
));
1998 ei
->cache_info
.is_extrainfo
= 1;
1999 strlcpy(ei
->nickname
, get_options()->Nickname
, sizeof(ei
->nickname
));
2000 ei
->cache_info
.published_on
= ri
->cache_info
.published_on
;
2001 ei
->signing_key_cert
= tor_cert_dup(get_master_signing_key_cert());
2002 memcpy(ei
->cache_info
.identity_digest
, ri
->cache_info
.identity_digest
,
2004 if (extrainfo_dump_to_string(&ei
->cache_info
.signed_descriptor_body
,
2005 ei
, get_server_identity_key(),
2006 get_master_signing_keypair()) < 0) {
2007 log_warn(LD_BUG
, "Couldn't generate extra-info descriptor.");
2011 ei
->cache_info
.signed_descriptor_len
=
2012 strlen(ei
->cache_info
.signed_descriptor_body
);
2013 router_get_extrainfo_hash(ei
->cache_info
.signed_descriptor_body
,
2014 ei
->cache_info
.signed_descriptor_len
,
2015 ei
->cache_info
.signed_descriptor_digest
);
2016 crypto_digest256((char*) ei
->digest256
,
2017 ei
->cache_info
.signed_descriptor_body
,
2018 ei
->cache_info
.signed_descriptor_len
,
2022 /* Now finish the router descriptor. */
2024 memcpy(ri
->cache_info
.extra_info_digest
,
2025 ei
->cache_info
.signed_descriptor_digest
,
2027 memcpy(ri
->extra_info_digest256
,
2031 /* ri was allocated with tor_malloc_zero, so there is no need to
2032 * zero ri->cache_info.extra_info_digest here. */
2034 if (! (ri
->cache_info
.signed_descriptor_body
=
2035 router_dump_router_to_string(ri
, get_server_identity_key(),
2037 get_current_curve25519_keypair(),
2038 get_master_signing_keypair())) ) {
2039 log_warn(LD_BUG
, "Couldn't generate router descriptor.");
2040 routerinfo_free(ri
);
2044 ri
->cache_info
.signed_descriptor_len
=
2045 strlen(ri
->cache_info
.signed_descriptor_body
);
2048 options
->BridgeRelay
? ROUTER_PURPOSE_BRIDGE
: ROUTER_PURPOSE_GENERAL
;
2049 if (options
->BridgeRelay
) {
2050 /* Bridges shouldn't be able to send their descriptors unencrypted,
2051 anyway, since they don't have a DirPort, and always connect to the
2052 bridge authority anonymously. But just in case they somehow think of
2053 sending them on an unencrypted connection, don't allow them to try. */
2054 ri
->cache_info
.send_unencrypted
= 0;
2056 ei
->cache_info
.send_unencrypted
= 0;
2058 ri
->cache_info
.send_unencrypted
= 1;
2060 ei
->cache_info
.send_unencrypted
= 1;
2063 router_get_router_hash(ri
->cache_info
.signed_descriptor_body
,
2064 strlen(ri
->cache_info
.signed_descriptor_body
),
2065 ri
->cache_info
.signed_descriptor_digest
);
2068 tor_assert(! routerinfo_incompatible_with_extrainfo(ri
, ei
, NULL
, NULL
));
2076 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
2077 * routerinfo, signed server descriptor, and extra-info document for this OR.
2078 * Return 0 on success, -1 on temporary error.
2081 router_rebuild_descriptor(int force
)
2086 const or_options_t
*options
= get_options();
2088 if (desc_clean_since
&& !force
)
2091 if (router_pick_published_address(options
, &addr
) < 0 ||
2092 router_get_advertised_or_port(options
) == 0) {
2093 /* Stop trying to rebuild our descriptor every second. We'll
2094 * learn that it's time to try again when ip_address_changed()
2095 * marks it dirty. */
2096 desc_clean_since
= time(NULL
);
2100 log_info(LD_OR
, "Rebuilding relay descriptor%s", force
? " (forced)" : "");
2102 if (router_build_fresh_descriptor(&ri
, &ei
) < 0) {
2106 routerinfo_free(desc_routerinfo
);
2107 desc_routerinfo
= ri
;
2108 extrainfo_free(desc_extrainfo
);
2109 desc_extrainfo
= ei
;
2111 desc_clean_since
= time(NULL
);
2112 desc_needs_upload
= 1;
2113 desc_gen_reason
= desc_dirty_reason
;
2114 desc_dirty_reason
= NULL
;
2115 control_event_my_descriptor_changed();
2119 /** If our router descriptor ever goes this long without being regenerated
2120 * because something changed, we force an immediate regenerate-and-upload. */
2121 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
2123 /** If our router descriptor seems to be missing or unacceptable according
2124 * to the authorities, regenerate and reupload it _this_ often. */
2125 #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
2127 /** Mark descriptor out of date if it's been "too long" since we last tried
2130 mark_my_descriptor_dirty_if_too_old(time_t now
)
2132 networkstatus_t
*ns
;
2133 const routerstatus_t
*rs
;
2134 const char *retry_fast_reason
= NULL
; /* Set if we should retry frequently */
2135 const time_t slow_cutoff
= now
- FORCE_REGENERATE_DESCRIPTOR_INTERVAL
;
2136 const time_t fast_cutoff
= now
- FAST_RETRY_DESCRIPTOR_INTERVAL
;
2138 /* If it's already dirty, don't mark it. */
2139 if (! desc_clean_since
)
2142 /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
2143 * time to rebuild it. */
2144 if (desc_clean_since
< slow_cutoff
) {
2145 mark_my_descriptor_dirty("time for new descriptor");
2148 /* Now we see whether we want to be retrying frequently or no. The
2149 * rule here is that we'll retry frequently if we aren't listed in the
2150 * live consensus we have, or if the publication time of the
2151 * descriptor listed for us in the consensus is very old. */
2152 ns
= networkstatus_get_live_consensus(now
);
2154 rs
= networkstatus_vote_find_entry(ns
, server_identitykey_digest
);
2156 retry_fast_reason
= "not listed in consensus";
2157 else if (rs
->published_on
< slow_cutoff
)
2158 retry_fast_reason
= "version listed in consensus is quite old";
2161 if (retry_fast_reason
&& desc_clean_since
< fast_cutoff
)
2162 mark_my_descriptor_dirty(retry_fast_reason
);
2165 /** Call when the current descriptor is out of date. */
2167 mark_my_descriptor_dirty(const char *reason
)
2169 const or_options_t
*options
= get_options();
2170 if (server_mode(options
) && options
->PublishServerDescriptor_
)
2171 log_info(LD_OR
, "Decided to publish new relay descriptor: %s", reason
);
2172 desc_clean_since
= 0;
2173 if (!desc_dirty_reason
)
2174 desc_dirty_reason
= reason
;
2177 /** How frequently will we republish our descriptor because of large (factor
2178 * of 2) shifts in estimated bandwidth? Note: We don't use this constant
2179 * if our previous bandwidth estimate was exactly 0. */
2180 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
2182 /** Check whether bandwidth has changed a lot since the last time we announced
2183 * bandwidth. If so, mark our descriptor dirty. */
2185 check_descriptor_bandwidth_changed(time_t now
)
2187 static time_t last_changed
= 0;
2189 if (!desc_routerinfo
)
2192 prev
= desc_routerinfo
->bandwidthcapacity
;
2193 cur
= we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
2194 if ((prev
!= cur
&& (!prev
|| !cur
)) ||
2197 if (last_changed
+MAX_BANDWIDTH_CHANGE_FREQ
< now
|| !prev
) {
2198 log_info(LD_GENERAL
,
2199 "Measured bandwidth has changed; rebuilding descriptor.");
2200 mark_my_descriptor_dirty("bandwidth has changed");
2206 /** Note at log level severity that our best guess of address has changed from
2207 * <b>prev</b> to <b>cur</b>. */
2209 log_addr_has_changed(int severity
,
2210 const tor_addr_t
*prev
,
2211 const tor_addr_t
*cur
,
2214 char addrbuf_prev
[TOR_ADDR_BUF_LEN
];
2215 char addrbuf_cur
[TOR_ADDR_BUF_LEN
];
2217 if (tor_addr_to_str(addrbuf_prev
, prev
, sizeof(addrbuf_prev
), 1) == NULL
)
2218 strlcpy(addrbuf_prev
, "???", TOR_ADDR_BUF_LEN
);
2219 if (tor_addr_to_str(addrbuf_cur
, cur
, sizeof(addrbuf_cur
), 1) == NULL
)
2220 strlcpy(addrbuf_cur
, "???", TOR_ADDR_BUF_LEN
);
2222 if (!tor_addr_is_null(prev
))
2223 log_fn(severity
, LD_GENERAL
,
2224 "Our IP Address has changed from %s to %s; "
2225 "rebuilding descriptor (source: %s).",
2226 addrbuf_prev
, addrbuf_cur
, source
);
2228 log_notice(LD_GENERAL
,
2229 "Guessed our IP address as %s (source: %s).",
2230 addrbuf_cur
, source
);
2233 /** Check whether our own address as defined by the Address configuration
2234 * has changed. This is for routers that get their address from a service
2235 * like dyndns. If our address has changed, mark our descriptor dirty. */
2237 check_descriptor_ipaddress_changed(time_t now
)
2240 const or_options_t
*options
= get_options();
2241 const char *method
= NULL
;
2242 char *hostname
= NULL
;
2246 if (!desc_routerinfo
)
2250 prev
= desc_routerinfo
->addr
;
2251 if (resolve_my_address(LOG_INFO
, options
, &cur
, &method
, &hostname
) < 0) {
2252 log_info(LD_CONFIG
,"options->Address didn't resolve into an IP.");
2258 tor_addr_t tmp_prev
, tmp_cur
;
2260 tor_addr_from_ipv4h(&tmp_prev
, prev
);
2261 tor_addr_from_ipv4h(&tmp_cur
, cur
);
2263 tor_asprintf(&source
, "METHOD=%s%s%s", method
,
2264 hostname
? " HOSTNAME=" : "",
2265 hostname
? hostname
: "");
2267 log_addr_has_changed(LOG_NOTICE
, &tmp_prev
, &tmp_cur
, source
);
2270 ip_address_changed(0);
2276 /** The most recently guessed value of our IP address, based on directory
2278 static tor_addr_t last_guessed_ip
= TOR_ADDR_NULL
;
2280 /** A directory server <b>d_conn</b> told us our IP address is
2281 * <b>suggestion</b>.
2282 * If this address is different from the one we think we are now, and
2283 * if our computer doesn't actually know its IP address, then switch. */
2285 router_new_address_suggestion(const char *suggestion
,
2286 const dir_connection_t
*d_conn
)
2289 uint32_t cur
= 0; /* Current IPv4 address. */
2290 const or_options_t
*options
= get_options();
2292 /* first, learn what the IP address actually is */
2293 if (tor_addr_parse(&addr
, suggestion
) == -1) {
2294 log_debug(LD_DIR
, "Malformed X-Your-Address-Is header %s. Ignoring.",
2295 escaped(suggestion
));
2299 log_debug(LD_DIR
, "Got X-Your-Address-Is: %s.", suggestion
);
2301 if (!server_mode(options
)) {
2302 tor_addr_copy(&last_guessed_ip
, &addr
);
2307 cur
= get_last_resolved_addr();
2309 resolve_my_address(LOG_INFO
, options
, &cur
, NULL
, NULL
) >= 0) {
2310 /* We're all set -- we already know our address. Great. */
2311 tor_addr_from_ipv4h(&last_guessed_ip
, cur
); /* store it in case we
2315 if (tor_addr_is_internal(&addr
, 0)) {
2316 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
2319 if (tor_addr_eq(&d_conn
->base_
.addr
, &addr
)) {
2320 /* Don't believe anybody who says our IP is their IP. */
2321 log_debug(LD_DIR
, "A directory server told us our IP address is %s, "
2322 "but he's just reporting his own IP address. Ignoring.",
2327 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
2328 * us an answer different from what we had the last time we managed to
2330 if (!tor_addr_eq(&last_guessed_ip
, &addr
)) {
2331 control_event_server_status(LOG_NOTICE
,
2332 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
2334 log_addr_has_changed(LOG_NOTICE
, &last_guessed_ip
, &addr
,
2335 d_conn
->base_
.address
);
2336 ip_address_changed(0);
2337 tor_addr_copy(&last_guessed_ip
, &addr
); /* router_rebuild_descriptor()
2342 /** We failed to resolve our address locally, but we'd like to build
2343 * a descriptor and publish / test reachability. If we have a guess
2344 * about our address based on directory headers, answer it and return
2345 * 0; else return -1. */
2347 router_guess_address_from_dir_headers(uint32_t *guess
)
2349 if (!tor_addr_is_null(&last_guessed_ip
)) {
2350 *guess
= tor_addr_to_ipv4h(&last_guessed_ip
);
2356 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
2357 * string describing the version of Tor and the operating system we're
2358 * currently running on.
2361 get_platform_str(char *platform
, size_t len
)
2363 tor_snprintf(platform
, len
, "Tor %s on %s",
2364 get_short_version(), get_uname());
2367 /* XXX need to audit this thing and count fenceposts. maybe
2368 * refactor so we don't have to keep asking if we're
2369 * near the end of maxlen?
2371 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2373 /** OR only: Given a routerinfo for this router, and an identity key to sign
2374 * with, encode the routerinfo as a signed server descriptor and return a new
2375 * string encoding the result, or NULL on failure.
2378 router_dump_router_to_string(routerinfo_t
*router
,
2379 const crypto_pk_t
*ident_key
,
2380 const crypto_pk_t
*tap_key
,
2381 const curve25519_keypair_t
*ntor_keypair
,
2382 const ed25519_keypair_t
*signing_keypair
)
2384 char *address
= NULL
;
2385 char *onion_pkey
= NULL
; /* Onion key, PEM-encoded. */
2386 char *identity_pkey
= NULL
; /* Identity key, PEM-encoded. */
2387 char digest
[DIGEST256_LEN
];
2388 char published
[ISO_TIME_LEN
+1];
2389 char fingerprint
[FINGERPRINT_LEN
+1];
2390 char *extra_info_line
= NULL
;
2391 size_t onion_pkeylen
, identity_pkeylen
;
2392 char *family_line
= NULL
;
2393 char *extra_or_address
= NULL
;
2394 const or_options_t
*options
= get_options();
2395 smartlist_t
*chunks
= NULL
;
2396 char *output
= NULL
;
2397 const int emit_ed_sigs
= signing_keypair
&& router
->signing_key_cert
;
2398 char *ed_cert_line
= NULL
;
2399 char *rsa_tap_cc_line
= NULL
;
2400 char *ntor_cc_line
= NULL
;
2402 /* Make sure the identity key matches the one in the routerinfo. */
2403 if (!crypto_pk_eq_keys(ident_key
, router
->identity_pkey
)) {
2404 log_warn(LD_BUG
,"Tried to sign a router with a private key that didn't "
2405 "match router's public key!");
2409 if (!router
->signing_key_cert
->signing_key_included
||
2410 !ed25519_pubkey_eq(&router
->signing_key_cert
->signed_key
,
2411 &signing_keypair
->pubkey
)) {
2412 log_warn(LD_BUG
, "Tried to sign a router descriptor with a mismatched "
2413 "ed25519 key chain %d",
2414 router
->signing_key_cert
->signing_key_included
);
2419 /* record our fingerprint, so we can include it in the descriptor */
2420 if (crypto_pk_get_fingerprint(router
->identity_pkey
, fingerprint
, 1)<0) {
2421 log_err(LD_BUG
,"Error computing fingerprint");
2426 /* Encode ed25519 signing cert */
2427 char ed_cert_base64
[256];
2428 char ed_fp_base64
[ED25519_BASE64_LEN
+1];
2429 if (base64_encode(ed_cert_base64
, sizeof(ed_cert_base64
),
2430 (const char*)router
->signing_key_cert
->encoded
,
2431 router
->signing_key_cert
->encoded_len
,
2432 BASE64_ENCODE_MULTILINE
) < 0) {
2433 log_err(LD_BUG
,"Couldn't base64-encode signing key certificate!");
2436 if (ed25519_public_to_base64(ed_fp_base64
,
2437 &router
->signing_key_cert
->signing_key
)<0) {
2438 log_err(LD_BUG
,"Couldn't base64-encode identity key\n");
2441 tor_asprintf(&ed_cert_line
, "identity-ed25519\n"
2442 "-----BEGIN ED25519 CERT-----\n"
2444 "-----END ED25519 CERT-----\n"
2445 "master-key-ed25519 %s\n",
2446 ed_cert_base64
, ed_fp_base64
);
2449 /* PEM-encode the onion key */
2450 if (crypto_pk_write_public_key_to_string(router
->onion_pkey
,
2451 &onion_pkey
,&onion_pkeylen
)<0) {
2452 log_warn(LD_BUG
,"write onion_pkey to string failed!");
2456 /* PEM-encode the identity key */
2457 if (crypto_pk_write_public_key_to_string(router
->identity_pkey
,
2458 &identity_pkey
,&identity_pkeylen
)<0) {
2459 log_warn(LD_BUG
,"write identity_pkey to string failed!");
2463 /* Cross-certify with RSA key */
2464 if (tap_key
&& router
->signing_key_cert
&&
2465 router
->signing_key_cert
->signing_key_included
) {
2469 make_tap_onion_key_crosscert(tap_key
,
2470 &router
->signing_key_cert
->signing_key
,
2471 router
->identity_pkey
,
2474 log_warn(LD_BUG
,"make_tap_onion_key_crosscert failed!");
2478 if (base64_encode(buf
, sizeof(buf
), (const char*)tap_cc
, tap_cc_len
,
2479 BASE64_ENCODE_MULTILINE
) < 0) {
2480 log_warn(LD_BUG
,"base64_encode(rsa_crosscert) failed!");
2486 tor_asprintf(&rsa_tap_cc_line
,
2487 "onion-key-crosscert\n"
2488 "-----BEGIN CROSSCERT-----\n"
2490 "-----END CROSSCERT-----\n", buf
);
2493 /* Cross-certify with onion keys */
2494 if (ntor_keypair
&& router
->signing_key_cert
&&
2495 router
->signing_key_cert
->signing_key_included
) {
2498 /* XXXX Base the expiration date on the actual onion key expiration time?*/
2500 make_ntor_onion_key_crosscert(ntor_keypair
,
2501 &router
->signing_key_cert
->signing_key
,
2502 router
->cache_info
.published_on
,
2503 MIN_ONION_KEY_LIFETIME
, &sign
);
2505 log_warn(LD_BUG
,"make_ntor_onion_key_crosscert failed!");
2508 tor_assert(sign
== 0 || sign
== 1);
2510 if (base64_encode(buf
, sizeof(buf
),
2511 (const char*)cert
->encoded
, cert
->encoded_len
,
2512 BASE64_ENCODE_MULTILINE
)<0) {
2513 log_warn(LD_BUG
,"base64_encode(ntor_crosscert) failed!");
2514 tor_cert_free(cert
);
2517 tor_cert_free(cert
);
2519 tor_asprintf(&ntor_cc_line
,
2520 "ntor-onion-key-crosscert %d\n"
2521 "-----BEGIN ED25519 CERT-----\n"
2523 "-----END ED25519 CERT-----\n", sign
, buf
);
2526 /* Encode the publication time. */
2527 format_iso_time(published
, router
->cache_info
.published_on
);
2529 if (router
->declared_family
&& smartlist_len(router
->declared_family
)) {
2530 char *family
= smartlist_join_strings(router
->declared_family
,
2532 tor_asprintf(&family_line
, "family %s\n", family
);
2535 family_line
= tor_strdup("");
2538 if (!tor_digest_is_zero(router
->cache_info
.extra_info_digest
)) {
2539 char extra_info_digest
[HEX_DIGEST_LEN
+1];
2540 base16_encode(extra_info_digest
, sizeof(extra_info_digest
),
2541 router
->cache_info
.extra_info_digest
, DIGEST_LEN
);
2542 if (!tor_digest256_is_zero(router
->extra_info_digest256
)) {
2543 char d256_64
[BASE64_DIGEST256_LEN
+1];
2544 digest256_to_base64(d256_64
, router
->extra_info_digest256
);
2545 tor_asprintf(&extra_info_line
, "extra-info-digest %s %s\n",
2546 extra_info_digest
, d256_64
);
2548 tor_asprintf(&extra_info_line
, "extra-info-digest %s\n",
2553 if (router
->ipv6_orport
&&
2554 tor_addr_family(&router
->ipv6_addr
) == AF_INET6
) {
2555 char addr
[TOR_ADDR_BUF_LEN
];
2557 a
= tor_addr_to_str(addr
, &router
->ipv6_addr
, sizeof(addr
), 1);
2559 tor_asprintf(&extra_or_address
,
2560 "or-address %s:%d\n", a
, router
->ipv6_orport
);
2561 log_debug(LD_OR
, "My or-address line is <%s>", extra_or_address
);
2565 address
= tor_dup_ip(router
->addr
);
2566 chunks
= smartlist_new();
2568 /* Generate the easy portion of the router descriptor. */
2569 smartlist_add_asprintf(chunks
,
2570 "router %s %s %d 0 %d\n"
2574 "protocols Link 1 2 Circuit 1\n"
2578 "bandwidth %d %d %d\n"
2587 decide_to_advertise_dirport(options
, router
->dir_port
),
2588 ed_cert_line
? ed_cert_line
: "",
2589 extra_or_address
? extra_or_address
: "",
2593 stats_n_seconds_working
,
2594 (int) router
->bandwidthrate
,
2595 (int) router
->bandwidthburst
,
2596 (int) router
->bandwidthcapacity
,
2597 extra_info_line
? extra_info_line
: "",
2598 (options
->DownloadExtraInfo
|| options
->V3AuthoritativeDir
) ?
2599 "caches-extra-info\n" : "",
2600 onion_pkey
, identity_pkey
,
2601 rsa_tap_cc_line
? rsa_tap_cc_line
: "",
2602 ntor_cc_line
? ntor_cc_line
: "",
2604 we_are_hibernating() ? "hibernating 1\n" : "",
2605 "hidden-service-dir\n",
2606 options
->AllowSingleHopExits
? "allow-single-hop-exits\n" : "");
2608 if (options
->ContactInfo
&& strlen(options
->ContactInfo
)) {
2609 const char *ci
= options
->ContactInfo
;
2610 if (strchr(ci
, '\n') || strchr(ci
, '\r'))
2612 smartlist_add_asprintf(chunks
, "contact %s\n", ci
);
2615 if (router
->onion_curve25519_pkey
) {
2617 base64_encode(kbuf
, sizeof(kbuf
),
2618 (const char *)router
->onion_curve25519_pkey
->public_key
,
2619 CURVE25519_PUBKEY_LEN
, BASE64_ENCODE_MULTILINE
);
2620 smartlist_add_asprintf(chunks
, "ntor-onion-key %s", kbuf
);
2623 /* Write the exit policy to the end of 's'. */
2624 if (!router
->exit_policy
|| !smartlist_len(router
->exit_policy
)) {
2625 smartlist_add(chunks
, tor_strdup("reject *:*\n"));
2626 } else if (router
->exit_policy
) {
2627 char *exit_policy
= router_dump_exit_policy_to_string(router
,1,0);
2632 smartlist_add_asprintf(chunks
, "%s\n", exit_policy
);
2633 tor_free(exit_policy
);
2636 if (router
->ipv6_exit_policy
) {
2637 char *p6
= write_short_policy(router
->ipv6_exit_policy
);
2638 if (p6
&& strcmp(p6
, "reject 1-65535")) {
2639 smartlist_add_asprintf(chunks
,
2640 "ipv6-policy %s\n", p6
);
2645 /* Sign the descriptor with Ed25519 */
2647 smartlist_add(chunks
, tor_strdup("router-sig-ed25519 "));
2648 crypto_digest_smartlist_prefix(digest
, DIGEST256_LEN
,
2649 ED_DESC_SIGNATURE_PREFIX
,
2650 chunks
, "", DIGEST_SHA256
);
2651 ed25519_signature_t sig
;
2652 char buf
[ED25519_SIG_BASE64_LEN
+1];
2653 if (ed25519_sign(&sig
, (const uint8_t*)digest
, DIGEST256_LEN
,
2654 signing_keypair
) < 0)
2656 if (ed25519_signature_to_base64(buf
, &sig
) < 0)
2659 smartlist_add_asprintf(chunks
, "%s\n", buf
);
2662 /* Sign the descriptor with RSA */
2663 smartlist_add(chunks
, tor_strdup("router-signature\n"));
2665 crypto_digest_smartlist(digest
, DIGEST_LEN
, chunks
, "", DIGEST_SHA1
);
2667 note_crypto_pk_op(SIGN_RTR
);
2670 if (!(sig
= router_get_dirobj_signature(digest
, DIGEST_LEN
, ident_key
))) {
2671 log_warn(LD_BUG
, "Couldn't sign router descriptor");
2674 smartlist_add(chunks
, sig
);
2677 /* include a last '\n' */
2678 smartlist_add(chunks
, tor_strdup("\n"));
2680 output
= smartlist_join_strings(chunks
, "", 0, NULL
);
2682 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2686 routerinfo_t
*ri_tmp
;
2687 cp
= s_dup
= tor_strdup(output
);
2688 ri_tmp
= router_parse_entry_from_string(cp
, NULL
, 1, 0, NULL
, NULL
);
2691 "We just generated a router descriptor we can't parse.");
2692 log_err(LD_BUG
, "Descriptor was: <<%s>>", output
);
2696 routerinfo_free(ri_tmp
);
2703 tor_free(output
); /* sets output to NULL */
2706 SMARTLIST_FOREACH(chunks
, char *, cp
, tor_free(cp
));
2707 smartlist_free(chunks
);
2710 tor_free(family_line
);
2711 tor_free(onion_pkey
);
2712 tor_free(identity_pkey
);
2713 tor_free(extra_or_address
);
2714 tor_free(ed_cert_line
);
2715 tor_free(rsa_tap_cc_line
);
2716 tor_free(ntor_cc_line
);
2717 tor_free(extra_info_line
);
2723 * OR only: Given <b>router</b>, produce a string with its exit policy.
2724 * If <b>include_ipv4</b> is true, include IPv4 entries.
2725 * If <b>include_ipv6</b> is true, include IPv6 entries.
2728 router_dump_exit_policy_to_string(const routerinfo_t
*router
,
2732 if ((!router
->exit_policy
) || (router
->policy_is_reject_star
)) {
2733 return tor_strdup("reject *:*");
2736 return policy_dump_to_string(router
->exit_policy
,
2741 /** Copy the primary (IPv4) OR port (IP address and TCP port) for
2742 * <b>router</b> into *<b>ap_out</b>. */
2744 router_get_prim_orport(const routerinfo_t
*router
, tor_addr_port_t
*ap_out
)
2746 tor_assert(ap_out
!= NULL
);
2747 tor_addr_from_ipv4h(&ap_out
->addr
, router
->addr
);
2748 ap_out
->port
= router
->or_port
;
2751 /** Return 1 if any of <b>router</b>'s addresses are <b>addr</b>.
2752 * Otherwise return 0. */
2754 router_has_addr(const routerinfo_t
*router
, const tor_addr_t
*addr
)
2757 tor_addr_eq_ipv4h(addr
, router
->addr
) ||
2758 tor_addr_eq(&router
->ipv6_addr
, addr
);
2762 router_has_orport(const routerinfo_t
*router
, const tor_addr_port_t
*orport
)
2765 (tor_addr_eq_ipv4h(&orport
->addr
, router
->addr
) &&
2766 orport
->port
== router
->or_port
) ||
2767 (tor_addr_eq(&orport
->addr
, &router
->ipv6_addr
) &&
2768 orport
->port
== router
->ipv6_orport
);
2771 /** Load the contents of <b>filename</b>, find the last line starting with
2772 * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
2773 * the past or more than 1 hour in the future with respect to <b>now</b>,
2774 * and write the file contents starting with that line to *<b>out</b>.
2775 * Return 1 for success, 0 if the file does not exist or is empty, or -1
2776 * if the file does not contain a line matching these criteria or other
2779 load_stats_file(const char *filename
, const char *end_line
, time_t now
,
2783 char *fname
= get_datadir_fname(filename
);
2784 char *contents
, *start
= NULL
, *tmp
, timestr
[ISO_TIME_LEN
+1];
2786 switch (file_status(fname
)) {
2788 /* X022 Find an alternative to reading the whole file to memory. */
2789 if ((contents
= read_file_to_str(fname
, 0, NULL
))) {
2790 tmp
= strstr(contents
, end_line
);
2791 /* Find last block starting with end_line */
2794 tmp
= strstr(tmp
+ 1, end_line
);
2798 if (strlen(start
) < strlen(end_line
) + 1 + sizeof(timestr
))
2800 strlcpy(timestr
, start
+ 1 + strlen(end_line
), sizeof(timestr
));
2801 if (parse_iso_time(timestr
, &written
) < 0)
2803 if (written
< now
- (25*60*60) || written
> now
+ (1*60*60))
2805 *out
= tor_strdup(start
);
2811 /* treat empty stats files as if the file doesn't exist */
2825 /** Write the contents of <b>extrainfo</b> and aggregated statistics to
2826 * *<b>s_out</b>, signing them with <b>ident_key</b>. Return 0 on
2827 * success, negative on failure. */
2829 extrainfo_dump_to_string(char **s_out
, extrainfo_t
*extrainfo
,
2830 crypto_pk_t
*ident_key
,
2831 const ed25519_keypair_t
*signing_keypair
)
2833 const or_options_t
*options
= get_options();
2834 char identity
[HEX_DIGEST_LEN
+1];
2835 char published
[ISO_TIME_LEN
+1];
2836 char digest
[DIGEST_LEN
];
2837 char *bandwidth_usage
;
2839 static int write_stats_to_extrainfo
= 1;
2840 char sig
[DIROBJ_MAX_SIG_LEN
+1];
2841 char *s
= NULL
, *pre
, *contents
, *cp
, *s_dup
= NULL
;
2842 time_t now
= time(NULL
);
2843 smartlist_t
*chunks
= smartlist_new();
2844 extrainfo_t
*ei_tmp
= NULL
;
2845 const int emit_ed_sigs
= signing_keypair
&& extrainfo
->signing_key_cert
;
2846 char *ed_cert_line
= NULL
;
2848 base16_encode(identity
, sizeof(identity
),
2849 extrainfo
->cache_info
.identity_digest
, DIGEST_LEN
);
2850 format_iso_time(published
, extrainfo
->cache_info
.published_on
);
2851 bandwidth_usage
= rep_hist_get_bandwidth_lines();
2853 if (!extrainfo
->signing_key_cert
->signing_key_included
||
2854 !ed25519_pubkey_eq(&extrainfo
->signing_key_cert
->signed_key
,
2855 &signing_keypair
->pubkey
)) {
2856 log_warn(LD_BUG
, "Tried to sign a extrainfo descriptor with a "
2857 "mismatched ed25519 key chain %d",
2858 extrainfo
->signing_key_cert
->signing_key_included
);
2861 char ed_cert_base64
[256];
2862 if (base64_encode(ed_cert_base64
, sizeof(ed_cert_base64
),
2863 (const char*)extrainfo
->signing_key_cert
->encoded
,
2864 extrainfo
->signing_key_cert
->encoded_len
,
2865 BASE64_ENCODE_MULTILINE
) < 0) {
2866 log_err(LD_BUG
,"Couldn't base64-encode signing key certificate!");
2869 tor_asprintf(&ed_cert_line
, "identity-ed25519\n"
2870 "-----BEGIN ED25519 CERT-----\n"
2872 "-----END ED25519 CERT-----\n", ed_cert_base64
);
2874 ed_cert_line
= tor_strdup("");
2877 tor_asprintf(&pre
, "extra-info %s %s\n%spublished %s\n%s",
2878 extrainfo
->nickname
, identity
,
2880 published
, bandwidth_usage
);
2881 smartlist_add(chunks
, pre
);
2883 if (geoip_is_loaded(AF_INET
))
2884 smartlist_add_asprintf(chunks
, "geoip-db-digest %s\n",
2885 geoip_db_digest(AF_INET
));
2886 if (geoip_is_loaded(AF_INET6
))
2887 smartlist_add_asprintf(chunks
, "geoip6-db-digest %s\n",
2888 geoip_db_digest(AF_INET6
));
2890 if (options
->ExtraInfoStatistics
&& write_stats_to_extrainfo
) {
2891 log_info(LD_GENERAL
, "Adding stats to extra-info descriptor.");
2892 if (options
->DirReqStatistics
&&
2893 load_stats_file("stats"PATH_SEPARATOR
"dirreq-stats",
2894 "dirreq-stats-end", now
, &contents
) > 0) {
2895 smartlist_add(chunks
, contents
);
2897 if (options
->HiddenServiceStatistics
&&
2898 load_stats_file("stats"PATH_SEPARATOR
"hidserv-stats",
2899 "hidserv-stats-end", now
, &contents
) > 0) {
2900 smartlist_add(chunks
, contents
);
2902 if (options
->EntryStatistics
&&
2903 load_stats_file("stats"PATH_SEPARATOR
"entry-stats",
2904 "entry-stats-end", now
, &contents
) > 0) {
2905 smartlist_add(chunks
, contents
);
2907 if (options
->CellStatistics
&&
2908 load_stats_file("stats"PATH_SEPARATOR
"buffer-stats",
2909 "cell-stats-end", now
, &contents
) > 0) {
2910 smartlist_add(chunks
, contents
);
2912 if (options
->ExitPortStatistics
&&
2913 load_stats_file("stats"PATH_SEPARATOR
"exit-stats",
2914 "exit-stats-end", now
, &contents
) > 0) {
2915 smartlist_add(chunks
, contents
);
2917 if (options
->ConnDirectionStatistics
&&
2918 load_stats_file("stats"PATH_SEPARATOR
"conn-stats",
2919 "conn-bi-direct", now
, &contents
) > 0) {
2920 smartlist_add(chunks
, contents
);
2924 /* Add information about the pluggable transports we support. */
2925 if (options
->ServerTransportPlugin
) {
2926 char *pluggable_transports
= pt_get_extra_info_descriptor_string();
2927 if (pluggable_transports
)
2928 smartlist_add(chunks
, pluggable_transports
);
2931 if (should_record_bridge_info(options
) && write_stats_to_extrainfo
) {
2932 const char *bridge_stats
= geoip_get_bridge_stats_extrainfo(now
);
2934 smartlist_add(chunks
, tor_strdup(bridge_stats
));
2939 char digest
[DIGEST256_LEN
];
2940 smartlist_add(chunks
, tor_strdup("router-sig-ed25519 "));
2941 crypto_digest_smartlist_prefix(digest
, DIGEST256_LEN
,
2942 ED_DESC_SIGNATURE_PREFIX
,
2943 chunks
, "", DIGEST_SHA256
);
2944 ed25519_signature_t sig
;
2945 char buf
[ED25519_SIG_BASE64_LEN
+1];
2946 if (ed25519_sign(&sig
, (const uint8_t*)digest
, DIGEST256_LEN
,
2947 signing_keypair
) < 0)
2949 if (ed25519_signature_to_base64(buf
, &sig
) < 0)
2952 smartlist_add_asprintf(chunks
, "%s\n", buf
);
2955 smartlist_add(chunks
, tor_strdup("router-signature\n"));
2956 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
2958 while (strlen(s
) > MAX_EXTRAINFO_UPLOAD_SIZE
- DIROBJ_MAX_SIG_LEN
) {
2959 /* So long as there are at least two chunks (one for the initial
2960 * extra-info line and one for the router-signature), we can keep removing
2962 if (smartlist_len(chunks
) > 2) {
2963 /* We remove the next-to-last element (remember, len-1 is the last
2964 element), since we need to keep the router-signature element. */
2965 int idx
= smartlist_len(chunks
) - 2;
2966 char *e
= smartlist_get(chunks
, idx
);
2967 smartlist_del_keeporder(chunks
, idx
);
2968 log_warn(LD_GENERAL
, "We just generated an extra-info descriptor "
2969 "with statistics that exceeds the 50 KB "
2970 "upload limit. Removing last added "
2974 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
2976 log_warn(LD_BUG
, "We just generated an extra-info descriptors that "
2977 "exceeds the 50 KB upload limit.");
2982 memset(sig
, 0, sizeof(sig
));
2983 if (router_get_extrainfo_hash(s
, strlen(s
), digest
) < 0 ||
2984 router_append_dirobj_signature(sig
, sizeof(sig
), digest
, DIGEST_LEN
,
2986 log_warn(LD_BUG
, "Could not append signature to extra-info "
2990 smartlist_add(chunks
, tor_strdup(sig
));
2992 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
2994 cp
= s_dup
= tor_strdup(s
);
2995 ei_tmp
= extrainfo_parse_entry_from_string(cp
, NULL
, 1, NULL
, NULL
);
2997 if (write_stats_to_extrainfo
) {
2998 log_warn(LD_GENERAL
, "We just generated an extra-info descriptor "
2999 "with statistics that we can't parse. Not "
3000 "adding statistics to this or any future "
3001 "extra-info descriptors.");
3002 write_stats_to_extrainfo
= 0;
3003 result
= extrainfo_dump_to_string(s_out
, extrainfo
, ident_key
,
3007 log_warn(LD_BUG
, "We just generated an extrainfo descriptor we "
3014 s
= NULL
; /* prevent free */
3023 SMARTLIST_FOREACH(chunks
, char *, cp
, tor_free(cp
));
3024 smartlist_free(chunks
);
3026 tor_free(ed_cert_line
);
3027 extrainfo_free(ei_tmp
);
3028 tor_free(bandwidth_usage
);
3033 /** Return true iff <b>s</b> is a valid server nickname. (That is, a string
3034 * containing between 1 and MAX_NICKNAME_LEN characters from
3035 * LEGAL_NICKNAME_CHARACTERS.) */
3037 is_legal_nickname(const char *s
)
3042 return len
> 0 && len
<= MAX_NICKNAME_LEN
&&
3043 strspn(s
,LEGAL_NICKNAME_CHARACTERS
) == len
;
3046 /** Return true iff <b>s</b> is a valid server nickname or
3047 * hex-encoded identity-key digest. */
3049 is_legal_nickname_or_hexdigest(const char *s
)
3052 return is_legal_nickname(s
);
3054 return is_legal_hexdigest(s
);
3057 /** Return true iff <b>s</b> is a valid hex-encoded identity-key
3058 * digest. (That is, an optional $, followed by 40 hex characters,
3059 * followed by either nothing, or = or ~ followed by a nickname, or
3060 * a character other than =, ~, or a hex character.)
3063 is_legal_hexdigest(const char *s
)
3067 if (s
[0] == '$') s
++;
3069 if (len
> HEX_DIGEST_LEN
) {
3070 if (s
[HEX_DIGEST_LEN
] == '=' ||
3071 s
[HEX_DIGEST_LEN
] == '~') {
3072 if (!is_legal_nickname(s
+HEX_DIGEST_LEN
+1))
3078 return (len
>= HEX_DIGEST_LEN
&&
3079 strspn(s
,HEX_CHARACTERS
)==HEX_DIGEST_LEN
);
3082 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
3083 * hold a human-readable description of a node with identity digest
3084 * <b>id_digest</b>, named-status <b>is_named</b>, nickname <b>nickname</b>,
3085 * and address <b>addr</b> or <b>addr32h</b>.
3087 * The <b>nickname</b> and <b>addr</b> fields are optional and may be set to
3088 * NULL. The <b>addr32h</b> field is optional and may be set to 0.
3090 * Return a pointer to the front of <b>buf</b>.
3093 format_node_description(char *buf
,
3094 const char *id_digest
,
3096 const char *nickname
,
3097 const tor_addr_t
*addr
,
3103 return "<NULL BUFFER>";
3106 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, id_digest
, DIGEST_LEN
);
3107 cp
= buf
+1+HEX_DIGEST_LEN
;
3109 buf
[1+HEX_DIGEST_LEN
] = is_named
? '=' : '~';
3110 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, nickname
, MAX_NICKNAME_LEN
+1);
3113 if (addr32h
|| addr
) {
3114 memcpy(cp
, " at ", 4);
3117 tor_addr_to_str(cp
, addr
, TOR_ADDR_BUF_LEN
, 0);
3120 in
.s_addr
= htonl(addr32h
);
3121 tor_inet_ntoa(&in
, cp
, INET_NTOA_BUF_LEN
);
3127 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
3128 * hold a human-readable description of <b>ri</b>.
3131 * Return a pointer to the front of <b>buf</b>.
3134 router_get_description(char *buf
, const routerinfo_t
*ri
)
3138 return format_node_description(buf
,
3139 ri
->cache_info
.identity_digest
,
3140 router_is_named(ri
),
3146 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
3147 * hold a human-readable description of <b>node</b>.
3149 * Return a pointer to the front of <b>buf</b>.
3152 node_get_description(char *buf
, const node_t
*node
)
3154 const char *nickname
= NULL
;
3155 uint32_t addr32h
= 0;
3162 nickname
= node
->rs
->nickname
;
3163 is_named
= node
->rs
->is_named
;
3164 addr32h
= node
->rs
->addr
;
3165 } else if (node
->ri
) {
3166 nickname
= node
->ri
->nickname
;
3167 addr32h
= node
->ri
->addr
;
3170 return format_node_description(buf
,
3178 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
3179 * hold a human-readable description of <b>rs</b>.
3181 * Return a pointer to the front of <b>buf</b>.
3184 routerstatus_get_description(char *buf
, const routerstatus_t
*rs
)
3188 return format_node_description(buf
,
3189 rs
->identity_digest
,
3196 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
3197 * hold a human-readable description of <b>ei</b>.
3199 * Return a pointer to the front of <b>buf</b>.
3202 extend_info_get_description(char *buf
, const extend_info_t
*ei
)
3206 return format_node_description(buf
,
3207 ei
->identity_digest
,
3214 /** Return a human-readable description of the routerinfo_t <b>ri</b>.
3216 * This function is not thread-safe. Each call to this function invalidates
3217 * previous values returned by this function.
3220 router_describe(const routerinfo_t
*ri
)
3222 static char buf
[NODE_DESC_BUF_LEN
];
3223 return router_get_description(buf
, ri
);
3226 /** Return a human-readable description of the node_t <b>node</b>.
3228 * This function is not thread-safe. Each call to this function invalidates
3229 * previous values returned by this function.
3232 node_describe(const node_t
*node
)
3234 static char buf
[NODE_DESC_BUF_LEN
];
3235 return node_get_description(buf
, node
);
3238 /** Return a human-readable description of the routerstatus_t <b>rs</b>.
3240 * This function is not thread-safe. Each call to this function invalidates
3241 * previous values returned by this function.
3244 routerstatus_describe(const routerstatus_t
*rs
)
3246 static char buf
[NODE_DESC_BUF_LEN
];
3247 return routerstatus_get_description(buf
, rs
);
3250 /** Return a human-readable description of the extend_info_t <b>ri</b>.
3252 * This function is not thread-safe. Each call to this function invalidates
3253 * previous values returned by this function.
3256 extend_info_describe(const extend_info_t
*ei
)
3258 static char buf
[NODE_DESC_BUF_LEN
];
3259 return extend_info_get_description(buf
, ei
);
3262 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
3263 * verbose representation of the identity of <b>router</b>. The format is:
3265 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
3266 * A "=" if the router is named; a "~" if it is not.
3267 * The router's nickname.
3270 router_get_verbose_nickname(char *buf
, const routerinfo_t
*router
)
3272 const char *good_digest
= networkstatus_get_router_digest_by_nickname(
3274 int is_named
= good_digest
&& tor_memeq(good_digest
,
3275 router
->cache_info
.identity_digest
,
3278 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, router
->cache_info
.identity_digest
,
3280 buf
[1+HEX_DIGEST_LEN
] = is_named
? '=' : '~';
3281 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, router
->nickname
, MAX_NICKNAME_LEN
+1);
3284 /** Forget that we have issued any router-related warnings, so that we'll
3285 * warn again if we see the same errors. */
3287 router_reset_warnings(void)
3289 if (warned_nonexistent_family
) {
3290 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
3291 smartlist_clear(warned_nonexistent_family
);
3295 /** Given a router purpose, convert it to a string. Don't call this on
3296 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
3297 * know its string representation. */
3299 router_purpose_to_string(uint8_t p
)
3303 case ROUTER_PURPOSE_GENERAL
: return "general";
3304 case ROUTER_PURPOSE_BRIDGE
: return "bridge";
3305 case ROUTER_PURPOSE_CONTROLLER
: return "controller";
3312 /** Given a string, convert it to a router purpose. */
3314 router_purpose_from_string(const char *s
)
3316 if (!strcmp(s
, "general"))
3317 return ROUTER_PURPOSE_GENERAL
;
3318 else if (!strcmp(s
, "bridge"))
3319 return ROUTER_PURPOSE_BRIDGE
;
3320 else if (!strcmp(s
, "controller"))
3321 return ROUTER_PURPOSE_CONTROLLER
;
3323 return ROUTER_PURPOSE_UNKNOWN
;
3326 /** Release all static resources held in router.c */
3328 router_free_all(void)
3330 crypto_pk_free(onionkey
);
3331 crypto_pk_free(lastonionkey
);
3332 crypto_pk_free(server_identitykey
);
3333 crypto_pk_free(client_identitykey
);
3334 tor_mutex_free(key_lock
);
3335 routerinfo_free(desc_routerinfo
);
3336 extrainfo_free(desc_extrainfo
);
3337 crypto_pk_free(authority_signing_key
);
3338 authority_cert_free(authority_key_certificate
);
3339 crypto_pk_free(legacy_signing_key
);
3340 authority_cert_free(legacy_key_certificate
);
3342 memwipe(&curve25519_onion_key
, 0, sizeof(curve25519_onion_key
));
3343 memwipe(&last_curve25519_onion_key
, 0, sizeof(last_curve25519_onion_key
));
3345 if (warned_nonexistent_family
) {
3346 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
3347 smartlist_free(warned_nonexistent_family
);
3351 /** Return a smartlist of tor_addr_port_t's with all the OR ports of
3352 <b>ri</b>. Note that freeing of the items in the list as well as
3353 the smartlist itself is the callers responsibility.
3355 XXX duplicating code from node_get_all_orports(). */
3357 router_get_all_orports(const routerinfo_t
*ri
)
3359 smartlist_t
*sl
= smartlist_new();
3362 if (ri
->addr
!= 0) {
3363 tor_addr_port_t
*ap
= tor_malloc(sizeof(tor_addr_port_t
));
3364 tor_addr_from_ipv4h(&ap
->addr
, ri
->addr
);
3365 ap
->port
= ri
->or_port
;
3366 smartlist_add(sl
, ap
);
3368 if (!tor_addr_is_null(&ri
->ipv6_addr
)) {
3369 tor_addr_port_t
*ap
= tor_malloc(sizeof(tor_addr_port_t
));
3370 tor_addr_copy(&ap
->addr
, &ri
->ipv6_addr
);
3371 ap
->port
= ri
->or_port
;
3372 smartlist_add(sl
, ap
);