1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2013, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
10 #include "circuitbuild.h"
11 #include "circuitlist.h"
12 #include "circuituse.h"
14 #include "connection.h"
16 #include "crypto_curve25519.h"
17 #include "directory.h"
21 #include "hibernate.h"
23 #include "networkstatus.h"
29 #include "routerlist.h"
30 #include "routerparse.h"
31 #include "statefile.h"
32 #include "transports.h"
33 #include "routerset.h"
37 * \brief OR functionality, including key maintenance, generating
38 * and uploading server descriptors, retrying OR connections.
41 extern long stats_n_seconds_working
;
43 /************************************************************/
46 * Key management: ORs only.
49 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
51 static tor_mutex_t
*key_lock
=NULL
;
52 static time_t onionkey_set_at
=0; /**< When was onionkey last changed? */
53 /** Current private onionskin decryption key: used to decode CREATE cells. */
54 static crypto_pk_t
*onionkey
=NULL
;
55 /** Previous private onionskin decryption key: used to decode CREATE cells
56 * generated by clients that have an older version of our descriptor. */
57 static crypto_pk_t
*lastonionkey
=NULL
;
58 #ifdef CURVE25519_ENABLED
59 /** Current private ntor secret key: used to perform the ntor handshake. */
60 static curve25519_keypair_t curve25519_onion_key
;
61 /** Previous private ntor secret key: used to perform the ntor handshake
62 * with clients that have an older version of our descriptor. */
63 static curve25519_keypair_t last_curve25519_onion_key
;
65 /** Private server "identity key": used to sign directory info and TLS
66 * certificates. Never changes. */
67 static crypto_pk_t
*server_identitykey
=NULL
;
68 /** Digest of server_identitykey. */
69 static char server_identitykey_digest
[DIGEST_LEN
];
70 /** Private client "identity key": used to sign bridges' and clients'
71 * outbound TLS certificates. Regenerated on startup and on IP address
73 static crypto_pk_t
*client_identitykey
=NULL
;
74 /** Signing key used for v3 directory material; only set for authorities. */
75 static crypto_pk_t
*authority_signing_key
= NULL
;
76 /** Key certificate to authenticate v3 directory material; only set for
78 static authority_cert_t
*authority_key_certificate
= NULL
;
80 /** For emergency V3 authority key migration: An extra signing key that we use
81 * with our old (obsolete) identity key for a while. */
82 static crypto_pk_t
*legacy_signing_key
= NULL
;
83 /** For emergency V3 authority key migration: An extra certificate to
84 * authenticate legacy_signing_key with our obsolete identity key.*/
85 static authority_cert_t
*legacy_key_certificate
= NULL
;
87 /* (Note that v3 authorities also have a separate "authority identity key",
88 * but this key is never actually loaded by the Tor process. Instead, it's
89 * used by tor-gencert to sign new signing keys and make new key
92 /** Replace the current onion key with <b>k</b>. Does not affect
93 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
96 set_onion_key(crypto_pk_t
*k
)
98 if (onionkey
&& crypto_pk_eq_keys(onionkey
, k
)) {
99 /* k is already our onion key; free it and return */
103 tor_mutex_acquire(key_lock
);
104 crypto_pk_free(onionkey
);
106 tor_mutex_release(key_lock
);
107 mark_my_descriptor_dirty("set onion key");
110 /** Return the current onion key. Requires that the onion key has been
111 * loaded or generated. */
115 tor_assert(onionkey
);
119 /** Store a full copy of the current onion key into *<b>key</b>, and a full
120 * copy of the most recent onion key into *<b>last</b>.
123 dup_onion_keys(crypto_pk_t
**key
, crypto_pk_t
**last
)
127 tor_mutex_acquire(key_lock
);
128 tor_assert(onionkey
);
129 *key
= crypto_pk_copy_full(onionkey
);
131 *last
= crypto_pk_copy_full(lastonionkey
);
134 tor_mutex_release(key_lock
);
137 #ifdef CURVE25519_ENABLED
138 /** Return the current secret onion key for the ntor handshake. Must only
139 * be called from the main thread. */
140 static const curve25519_keypair_t
*
141 get_current_curve25519_keypair(void)
143 return &curve25519_onion_key
;
145 /** Return a map from KEYID (the key itself) to keypairs for use in the ntor
146 * handshake. Must only be called from the main thread. */
148 construct_ntor_key_map(void)
150 di_digest256_map_t
*m
= NULL
;
153 curve25519_onion_key
.pubkey
.public_key
,
154 tor_memdup(&curve25519_onion_key
,
155 sizeof(curve25519_keypair_t
)));
156 if (!tor_mem_is_zero((const char*)
157 last_curve25519_onion_key
.pubkey
.public_key
,
158 CURVE25519_PUBKEY_LEN
)) {
160 last_curve25519_onion_key
.pubkey
.public_key
,
161 tor_memdup(&last_curve25519_onion_key
,
162 sizeof(curve25519_keypair_t
)));
167 /** Helper used to deallocate a di_digest256_map_t returned by
168 * construct_ntor_key_map. */
170 ntor_key_map_free_helper(void *arg
)
172 curve25519_keypair_t
*k
= arg
;
173 memwipe(k
, 0, sizeof(*k
));
176 /** Release all storage from a keymap returned by construct_ntor_key_map. */
178 ntor_key_map_free(di_digest256_map_t
*map
)
182 dimap_free(map
, ntor_key_map_free_helper
);
186 /** Return the time when the onion key was last set. This is either the time
187 * when the process launched, or the time of the most recent key rotation since
188 * the process launched.
191 get_onion_key_set_at(void)
193 return onionkey_set_at
;
196 /** Set the current server identity key to <b>k</b>.
199 set_server_identity_key(crypto_pk_t
*k
)
201 crypto_pk_free(server_identitykey
);
202 server_identitykey
= k
;
203 crypto_pk_get_digest(server_identitykey
, server_identitykey_digest
);
206 /** Make sure that we have set up our identity keys to match or not match as
207 * appropriate, and die with an assertion if we have not. */
209 assert_identity_keys_ok(void)
211 tor_assert(client_identitykey
);
212 if (public_server_mode(get_options())) {
213 /* assert that we have set the client and server keys to be equal */
214 tor_assert(server_identitykey
);
215 tor_assert(crypto_pk_eq_keys(client_identitykey
, server_identitykey
));
217 /* assert that we have set the client and server keys to be unequal */
218 if (server_identitykey
)
219 tor_assert(!crypto_pk_eq_keys(client_identitykey
, server_identitykey
));
223 /** Returns the current server identity key; requires that the key has
224 * been set, and that we are running as a Tor server.
227 get_server_identity_key(void)
229 tor_assert(server_identitykey
);
230 tor_assert(server_mode(get_options()));
231 assert_identity_keys_ok();
232 return server_identitykey
;
235 /** Return true iff 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. */
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 #ifdef CURVE25519_ENABLED
317 curve25519_keypair_t new_curve25519_keypair
;
320 fname
= get_datadir_fname2("keys", "secret_onion_key");
321 fname_prev
= get_datadir_fname2("keys", "secret_onion_key.old");
322 if (file_status(fname
) == FN_FILE
) {
323 if (replace_file(fname
, fname_prev
))
326 if (!(prkey
= crypto_pk_new())) {
327 log_err(LD_GENERAL
,"Error constructing rotated onion key");
330 if (crypto_pk_generate_key(prkey
)) {
331 log_err(LD_BUG
,"Error generating onion key");
334 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
335 log_err(LD_FS
,"Couldn't write generated onion key to \"%s\".", fname
);
338 #ifdef CURVE25519_ENABLED
340 tor_free(fname_prev
);
341 fname
= get_datadir_fname2("keys", "secret_onion_key_ntor");
342 fname_prev
= get_datadir_fname2("keys", "secret_onion_key_ntor.old");
343 if (curve25519_keypair_generate(&new_curve25519_keypair
, 1) < 0)
345 if (file_status(fname
) == FN_FILE
) {
346 if (replace_file(fname
, fname_prev
))
349 if (curve25519_keypair_write_to_file(&new_curve25519_keypair
, fname
,
351 log_err(LD_FS
,"Couldn't write curve25519 onion key to \"%s\".",fname
);
355 log_info(LD_GENERAL
, "Rotating onion key");
356 tor_mutex_acquire(key_lock
);
357 crypto_pk_free(lastonionkey
);
358 lastonionkey
= onionkey
;
360 #ifdef CURVE25519_ENABLED
361 memcpy(&last_curve25519_onion_key
, &curve25519_onion_key
,
362 sizeof(curve25519_keypair_t
));
363 memcpy(&curve25519_onion_key
, &new_curve25519_keypair
,
364 sizeof(curve25519_keypair_t
));
367 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
368 tor_mutex_release(key_lock
);
369 mark_my_descriptor_dirty("rotated onion key");
370 or_state_mark_dirty(state
, get_options()->AvoidDiskWrites
? now
+3600 : 0);
373 log_warn(LD_GENERAL
, "Couldn't rotate onion key.");
375 crypto_pk_free(prkey
);
377 #ifdef CURVE25519_ENABLED
378 memwipe(&new_curve25519_keypair
, 0, sizeof(new_curve25519_keypair
));
381 tor_free(fname_prev
);
384 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
385 * and <b>generate</b> is true, create a new RSA key and save it in
386 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
387 * errors at level <b>severity</b>.
390 init_key_from_file(const char *fname
, int generate
, int severity
)
392 crypto_pk_t
*prkey
= NULL
;
394 if (!(prkey
= crypto_pk_new())) {
395 tor_log(severity
, LD_GENERAL
,"Error constructing key");
399 switch (file_status(fname
)) {
402 tor_log(severity
, LD_FS
,"Can't read key from \"%s\"", fname
);
406 if (!have_lockfile()) {
407 if (try_locking(get_options(), 0)<0) {
408 /* Make sure that --list-fingerprint only creates new keys
409 * if there is no possibility for a deadlock. */
410 tor_log(severity
, LD_FS
, "Another Tor process has locked \"%s\". "
411 "Not writing any new keys.", fname
);
412 /*XXXX The 'other process' might make a key in a second or two;
413 * maybe we should wait for it. */
417 log_info(LD_GENERAL
, "No key found in \"%s\"; generating fresh key.",
419 if (crypto_pk_generate_key(prkey
)) {
420 tor_log(severity
, LD_GENERAL
,"Error generating onion key");
423 if (crypto_pk_check_key(prkey
) <= 0) {
424 tor_log(severity
, LD_GENERAL
,"Generated key seems invalid");
427 log_info(LD_GENERAL
, "Generated key seems valid");
428 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
429 tor_log(severity
, LD_FS
,
430 "Couldn't write generated key to \"%s\".", fname
);
434 log_info(LD_GENERAL
, "No key found in \"%s\"", fname
);
438 if (crypto_pk_read_private_key_from_filename(prkey
, fname
)) {
439 tor_log(severity
, LD_GENERAL
,"Error loading private key.");
449 crypto_pk_free(prkey
);
453 #ifdef CURVE25519_ENABLED
454 /** Load a curve25519 keypair from the file <b>fname</b>, writing it into
455 * <b>keys_out</b>. If the file isn't found and <b>generate</b> is true,
456 * create a new keypair and write it into the file. If there are errors, log
457 * them at level <b>severity</b>. Generate files using <b>tag</b> in their
460 init_curve25519_keypair_from_file(curve25519_keypair_t
*keys_out
,
466 switch (file_status(fname
)) {
469 tor_log(severity
, LD_FS
,"Can't read key from \"%s\"", fname
);
473 if (!have_lockfile()) {
474 if (try_locking(get_options(), 0)<0) {
475 /* Make sure that --list-fingerprint only creates new keys
476 * if there is no possibility for a deadlock. */
477 tor_log(severity
, LD_FS
, "Another Tor process has locked \"%s\". "
478 "Not writing any new keys.", fname
);
479 /*XXXX The 'other process' might make a key in a second or two;
480 * maybe we should wait for it. */
484 log_info(LD_GENERAL
, "No key found in \"%s\"; generating fresh key.",
486 if (curve25519_keypair_generate(keys_out
, 1) < 0)
488 if (curve25519_keypair_write_to_file(keys_out
, fname
, tag
)<0) {
489 tor_log(severity
, LD_FS
,
490 "Couldn't write generated key to \"%s\".", fname
);
491 memset(keys_out
, 0, sizeof(*keys_out
));
495 log_info(LD_GENERAL
, "No key found in \"%s\"", fname
);
501 if (curve25519_keypair_read_from_file(keys_out
, &tag_in
, fname
) < 0) {
502 tor_log(severity
, LD_GENERAL
,"Error loading private key.");
506 if (!tag_in
|| strcmp(tag_in
, tag
)) {
507 tor_log(severity
, LD_GENERAL
,"Unexpected tag %s on private key.",
524 /** Try to load the vote-signing private key and certificate for being a v3
525 * directory authority, and make sure they match. If <b>legacy</b>, load a
526 * legacy key/cert set for emergency key migration; otherwise load the regular
527 * key/cert set. On success, store them into *<b>key_out</b> and
528 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
530 load_authority_keyset(int legacy
, crypto_pk_t
**key_out
,
531 authority_cert_t
**cert_out
)
534 char *fname
= NULL
, *cert
= NULL
;
535 const char *eos
= NULL
;
536 crypto_pk_t
*signing_key
= NULL
;
537 authority_cert_t
*parsed
= NULL
;
539 fname
= get_datadir_fname2("keys",
540 legacy
? "legacy_signing_key" : "authority_signing_key");
541 signing_key
= init_key_from_file(fname
, 0, LOG_INFO
);
543 log_warn(LD_DIR
, "No version 3 directory key found in %s", fname
);
547 fname
= get_datadir_fname2("keys",
548 legacy
? "legacy_certificate" : "authority_certificate");
549 cert
= read_file_to_str(fname
, 0, NULL
);
551 log_warn(LD_DIR
, "Signing key found, but no certificate found in %s",
555 parsed
= authority_cert_parse_from_string(cert
, &eos
);
557 log_warn(LD_DIR
, "Unable to parse certificate in %s", fname
);
560 if (!crypto_pk_eq_keys(signing_key
, parsed
->signing_key
)) {
561 log_warn(LD_DIR
, "Stored signing key does not match signing key in "
566 crypto_pk_free(*key_out
);
567 authority_cert_free(*cert_out
);
569 *key_out
= signing_key
;
578 crypto_pk_free(signing_key
);
579 authority_cert_free(parsed
);
583 /** Load the v3 (voting) authority signing key and certificate, if they are
584 * present. Return -1 if anything is missing, mismatched, or unloadable;
585 * return 0 on success. */
587 init_v3_authority_keys(void)
589 if (load_authority_keyset(0, &authority_signing_key
,
590 &authority_key_certificate
)<0)
593 if (get_options()->V3AuthUseLegacyKey
&&
594 load_authority_keyset(1, &legacy_signing_key
,
595 &legacy_key_certificate
)<0)
601 /** If we're a v3 authority, check whether we have a certificate that's
602 * likely to expire soon. Warn if we do, but not too often. */
604 v3_authority_check_key_expiry(void)
607 static time_t last_warned
= 0;
608 int badness
, time_left
, warn_interval
;
609 if (!authdir_mode_v3(get_options()) || !authority_key_certificate
)
613 expires
= authority_key_certificate
->expires
;
614 time_left
= (int)( expires
- now
);
615 if (time_left
<= 0) {
617 warn_interval
= 60*60;
618 } else if (time_left
<= 24*60*60) {
620 warn_interval
= 60*60;
621 } else if (time_left
<= 24*60*60*7) {
623 warn_interval
= 24*60*60;
624 } else if (time_left
<= 24*60*60*30) {
626 warn_interval
= 24*60*60*5;
631 if (last_warned
+ warn_interval
> now
)
634 if (time_left
<= 0) {
635 tor_log(badness
, LD_DIR
, "Your v3 authority certificate has expired."
636 " Generate a new one NOW.");
637 } else if (time_left
<= 24*60*60) {
638 tor_log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d "
639 "hours; Generate a new one NOW.", time_left
/(60*60));
641 tor_log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d "
642 "days; Generate a new one soon.", time_left
/(24*60*60));
647 /** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
648 * on success, and -1 on failure. */
650 router_initialize_tls_context(void)
652 unsigned int flags
= 0;
653 const or_options_t
*options
= get_options();
654 int lifetime
= options
->SSLKeyLifetime
;
655 if (public_server_mode(options
))
656 flags
|= TOR_TLS_CTX_IS_PUBLIC_SERVER
;
657 if (options
->TLSECGroup
) {
658 if (!strcasecmp(options
->TLSECGroup
, "P256"))
659 flags
|= TOR_TLS_CTX_USE_ECDHE_P256
;
660 else if (!strcasecmp(options
->TLSECGroup
, "P224"))
661 flags
|= TOR_TLS_CTX_USE_ECDHE_P224
;
663 if (!lifetime
) { /* we should guess a good ssl cert lifetime */
665 /* choose between 5 and 365 days, and round to the day */
666 lifetime
= 5*24*3600 + crypto_rand_int(361*24*3600);
667 lifetime
-= lifetime
% (24*3600);
669 if (crypto_rand_int(2)) {
670 /* Half the time we expire at midnight, and half the time we expire
671 * one second before midnight. (Some CAs wobble their expiry times a
672 * bit in practice, perhaps to reduce collision attacks; see ticket
673 * 8443 for details about observed certs in the wild.) */
678 /* It's ok to pass lifetime in as an unsigned int, since
679 * config_parse_interval() checked it. */
680 return tor_tls_context_init(flags
,
681 get_tlsclient_identity_key(),
682 server_mode(options
) ?
683 get_server_identity_key() : NULL
,
684 (unsigned int)lifetime
);
687 /** Compute fingerprint (or hashed fingerprint if hashed is 1) and write
688 * it to 'fingerprint' (or 'hashed-fingerprint'). Return 0 on success, or
689 * -1 if Tor should die,
692 router_write_fingerprint(int hashed
)
694 char *keydir
= NULL
, *cp
= NULL
;
695 const char *fname
= hashed
? "hashed-fingerprint" :
697 char fingerprint
[FINGERPRINT_LEN
+1];
698 const or_options_t
*options
= get_options();
699 char *fingerprint_line
= NULL
;
702 keydir
= get_datadir_fname(fname
);
703 log_info(LD_GENERAL
,"Dumping %sfingerprint to \"%s\"...",
704 hashed
? "hashed " : "", keydir
);
706 if (crypto_pk_get_fingerprint(get_server_identity_key(),
707 fingerprint
, 0) < 0) {
708 log_err(LD_GENERAL
,"Error computing fingerprint");
712 if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
714 log_err(LD_GENERAL
,"Error computing hashed fingerprint");
719 tor_asprintf(&fingerprint_line
, "%s %s\n", options
->Nickname
, fingerprint
);
721 /* Check whether we need to write the (hashed-)fingerprint file. */
723 cp
= read_file_to_str(keydir
, RFTS_IGNORE_MISSING
, NULL
);
724 if (!cp
|| strcmp(cp
, fingerprint_line
)) {
725 if (write_str_to_file(keydir
, fingerprint_line
, 0)) {
726 log_err(LD_FS
, "Error writing %sfingerprint line to file",
727 hashed
? "hashed " : "");
732 log_notice(LD_GENERAL
, "Your Tor %s identity key fingerprint is '%s %s'",
733 hashed
? "bridge's hashed" : "server's", options
->Nickname
,
740 tor_free(fingerprint_line
);
744 /** Initialize all OR private keys, and the TLS context, as necessary.
745 * On OPs, this only initializes the tls context. Return 0 on success,
746 * or -1 if Tor should die.
754 char digest
[DIGEST_LEN
];
755 char v3_digest
[DIGEST_LEN
];
756 const or_options_t
*options
= get_options();
758 time_t now
= time(NULL
);
760 int v3_digest_set
= 0;
761 authority_cert_t
*cert
= NULL
;
764 key_lock
= tor_mutex_new();
766 /* There are a couple of paths that put us here before we've asked
767 * openssl to initialize itself. */
768 if (crypto_global_init(get_options()->HardwareAccel
,
769 get_options()->AccelName
,
770 get_options()->AccelDir
)) {
771 log_err(LD_BUG
, "Unable to initialize OpenSSL. Exiting.");
775 /* OP's don't need persistent keys; just make up an identity and
776 * initialize the TLS context. */
777 if (!server_mode(options
)) {
778 if (!(prkey
= crypto_pk_new()))
780 if (crypto_pk_generate_key(prkey
)) {
781 crypto_pk_free(prkey
);
784 set_client_identity_key(prkey
);
785 /* Create a TLS context. */
786 if (router_initialize_tls_context() < 0) {
787 log_err(LD_GENERAL
,"Error creating TLS context for Tor client.");
792 /* Make sure DataDirectory exists, and is private. */
793 if (check_private_dir(options
->DataDirectory
, CPD_CREATE
, options
->User
)) {
796 /* Check the key directory. */
797 keydir
= get_datadir_fname("keys");
798 if (check_private_dir(keydir
, CPD_CREATE
, options
->User
)) {
804 /* 1a. Read v3 directory authority key/cert information. */
805 memset(v3_digest
, 0, sizeof(v3_digest
));
806 if (authdir_mode_v3(options
)) {
807 if (init_v3_authority_keys()<0) {
808 log_err(LD_GENERAL
, "We're configured as a V3 authority, but we "
809 "were unable to load our v3 authority keys and certificate! "
810 "Use tor-gencert to generate them. Dying.");
813 cert
= get_my_v3_authority_cert();
815 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key
,
821 /* 1b. Read identity key. Make it if none is found. */
822 keydir
= get_datadir_fname2("keys", "secret_id_key");
823 log_info(LD_GENERAL
,"Reading/making identity key \"%s\"...",keydir
);
824 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
826 if (!prkey
) return -1;
827 set_server_identity_key(prkey
);
829 /* 1c. If we are configured as a bridge, generate a client key;
830 * otherwise, set the server identity key as our client identity
832 if (public_server_mode(options
)) {
833 set_client_identity_key(crypto_pk_dup_key(prkey
)); /* set above */
835 if (!(prkey
= crypto_pk_new()))
837 if (crypto_pk_generate_key(prkey
)) {
838 crypto_pk_free(prkey
);
841 set_client_identity_key(prkey
);
844 /* 2. Read onion key. Make it if none is found. */
845 keydir
= get_datadir_fname2("keys", "secret_onion_key");
846 log_info(LD_GENERAL
,"Reading/making onion key \"%s\"...",keydir
);
847 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
849 if (!prkey
) return -1;
850 set_onion_key(prkey
);
851 if (options
->command
== CMD_RUN_TOR
) {
852 /* only mess with the state file if we're actually running Tor */
853 or_state_t
*state
= get_or_state();
854 if (state
->LastRotatedOnionKey
> 100 && state
->LastRotatedOnionKey
< now
) {
855 /* We allow for some parsing slop, but we don't want to risk accepting
856 * values in the distant future. If we did, we might never rotate the
858 onionkey_set_at
= state
->LastRotatedOnionKey
;
860 /* We have no LastRotatedOnionKey set; either we just created the key
861 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
862 * start the clock ticking now so that we will eventually rotate it even
863 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
864 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
865 or_state_mark_dirty(state
, options
->AvoidDiskWrites
?
866 time(NULL
)+3600 : 0);
870 keydir
= get_datadir_fname2("keys", "secret_onion_key.old");
871 if (!lastonionkey
&& file_status(keydir
) == FN_FILE
) {
872 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
); /* XXXX Why 1? */
874 lastonionkey
= prkey
;
878 #ifdef CURVE25519_ENABLED
880 /* 2b. Load curve25519 onion keys. */
882 keydir
= get_datadir_fname2("keys", "secret_onion_key_ntor");
883 r
= init_curve25519_keypair_from_file(&curve25519_onion_key
,
884 keydir
, 1, LOG_ERR
, "onion");
889 keydir
= get_datadir_fname2("keys", "secret_onion_key_ntor.old");
890 if (tor_mem_is_zero((const char *)
891 last_curve25519_onion_key
.pubkey
.public_key
,
892 CURVE25519_PUBKEY_LEN
) &&
893 file_status(keydir
) == FN_FILE
) {
894 init_curve25519_keypair_from_file(&last_curve25519_onion_key
,
895 keydir
, 0, LOG_ERR
, "onion");
901 /* 3. Initialize link key and TLS context. */
902 if (router_initialize_tls_context() < 0) {
903 log_err(LD_GENERAL
,"Error initializing TLS context");
907 /* 4. Build our router descriptor. */
908 /* Must be called after keys are initialized. */
909 mydesc
= router_get_my_descriptor();
910 if (authdir_mode_handles_descs(options
, ROUTER_PURPOSE_GENERAL
)) {
911 const char *m
= NULL
;
913 /* We need to add our own fingerprint so it gets recognized. */
914 if (dirserv_add_own_fingerprint(options
->Nickname
,
915 get_server_identity_key())) {
916 log_err(LD_GENERAL
,"Error adding own fingerprint to approved set");
920 was_router_added_t added
;
921 ri
= router_parse_entry_from_string(mydesc
, NULL
, 1, 0, NULL
);
923 log_err(LD_GENERAL
,"Generated a routerinfo we couldn't parse.");
926 added
= dirserv_add_descriptor(ri
, &m
, "self");
927 if (!WRA_WAS_ADDED(added
)) {
928 if (!WRA_WAS_OUTDATED(added
)) {
929 log_err(LD_GENERAL
, "Unable to add own descriptor to directory: %s",
930 m
?m
:"<unknown error>");
933 /* If the descriptor was outdated, that's ok. This can happen
934 * when some config options are toggled that affect workers, but
935 * we don't really need new keys yet so the descriptor doesn't
936 * change and the old one is still fresh. */
937 log_info(LD_GENERAL
, "Couldn't add own descriptor to directory "
938 "after key init: %s This is usually not a problem.",
939 m
?m
:"<unknown error>");
945 /* 5. Dump fingerprint and possibly hashed fingerprint to files. */
946 if (router_write_fingerprint(0)) {
947 log_err(LD_FS
, "Error writing fingerprint to file");
950 if (!public_server_mode(options
) && router_write_fingerprint(1)) {
951 log_err(LD_FS
, "Error writing hashed fingerprint to file");
955 if (!authdir_mode(options
))
957 /* 6. [authdirserver only] load approved-routers file */
958 if (dirserv_load_fingerprint_file() < 0) {
959 log_err(LD_GENERAL
,"Error loading fingerprints");
962 /* 6b. [authdirserver only] add own key to approved directories. */
963 crypto_pk_get_digest(get_server_identity_key(), digest
);
964 type
= ((options
->V3AuthoritativeDir
?
965 (V3_DIRINFO
|MICRODESC_DIRINFO
|EXTRAINFO_DIRINFO
) : NO_DIRINFO
) |
966 (options
->BridgeAuthoritativeDir
? BRIDGE_DIRINFO
: NO_DIRINFO
));
968 ds
= router_get_trusteddirserver_by_digest(digest
);
970 ds
= trusted_dir_server_new(options
->Nickname
, NULL
,
971 router_get_advertised_dir_port(options
, 0),
972 router_get_advertised_or_port(options
),
977 log_err(LD_GENERAL
,"We want to be a directory authority, but we "
978 "couldn't add ourselves to the authority list. Failing.");
983 if (ds
->type
!= type
) {
984 log_warn(LD_DIR
, "Configured authority type does not match authority "
985 "type in DirAuthority list. Adjusting. (%d v %d)",
989 if (v3_digest_set
&& (ds
->type
& V3_DIRINFO
) &&
990 tor_memneq(v3_digest
, ds
->v3_identity_digest
, DIGEST_LEN
)) {
991 log_warn(LD_DIR
, "V3 identity key does not match identity declared in "
992 "DirAuthority line. Adjusting.");
993 memcpy(ds
->v3_identity_digest
, v3_digest
, DIGEST_LEN
);
996 if (cert
) { /* add my own cert to the list of known certs */
997 log_info(LD_DIR
, "adding my own v3 cert");
998 if (trusted_dirs_load_certs_from_string(
999 cert
->cache_info
.signed_descriptor_body
,
1000 TRUSTED_DIRS_CERTS_SRC_SELF
, 0)<0) {
1001 log_warn(LD_DIR
, "Unable to parse my own v3 cert! Failing.");
1006 return 0; /* success */
1009 /* Keep track of whether we should upload our server descriptor,
1010 * and what type of server we are.
1013 /** Whether we can reach our ORPort from the outside. */
1014 static int can_reach_or_port
= 0;
1015 /** Whether we can reach our DirPort from the outside. */
1016 static int can_reach_dir_port
= 0;
1018 /** Forget what we have learned about our reachability status. */
1020 router_reset_reachability(void)
1022 can_reach_or_port
= can_reach_dir_port
= 0;
1025 /** Return 1 if ORPort is known reachable; else return 0. */
1027 check_whether_orport_reachable(void)
1029 const or_options_t
*options
= get_options();
1030 return options
->AssumeReachable
||
1034 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
1036 check_whether_dirport_reachable(void)
1038 const or_options_t
*options
= get_options();
1039 return !options
->DirPort_set
||
1040 options
->AssumeReachable
||
1041 net_is_disabled() ||
1045 /** Look at a variety of factors, and return 0 if we don't want to
1046 * advertise the fact that we have a DirPort open. Else return the
1047 * DirPort we want to advertise.
1049 * Log a helpful message if we change our mind about whether to publish
1053 decide_to_advertise_dirport(const or_options_t
*options
, uint16_t dir_port
)
1055 static int advertising
=1; /* start out assuming we will advertise */
1057 const char *reason
= NULL
;
1059 /* Section one: reasons to publish or not publish that aren't
1060 * worth mentioning to the user, either because they're obvious
1061 * or because they're normal behavior. */
1063 if (!dir_port
) /* short circuit the rest of the function */
1065 if (authdir_mode(options
)) /* always publish */
1067 if (net_is_disabled())
1069 if (!check_whether_dirport_reachable())
1071 if (!router_get_advertised_dir_port(options
, dir_port
))
1074 /* Section two: reasons to publish or not publish that the user
1075 * might find surprising. These are generally config options that
1076 * make us choose not to publish. */
1078 if (accounting_is_enabled(options
)) {
1079 /* Don't spend bytes for directory traffic if we could end up hibernating,
1080 * but allow DirPort otherwise. Some people set AccountingMax because
1081 * they're confused or to get statistics. */
1082 int interval_length
= accounting_get_interval_length();
1083 uint32_t effective_bw
= get_effective_bwrate(options
);
1084 if (!interval_length
) {
1085 log_warn(LD_BUG
, "An accounting interval is not allowed to be zero "
1086 "seconds long. Raising to 1.");
1087 interval_length
= 1;
1089 log_info(LD_GENERAL
, "Calculating whether to disable dirport: effective "
1090 "bwrate: %u, AccountingMax: "U64_FORMAT
", "
1091 "accounting interval length %d", effective_bw
,
1092 U64_PRINTF_ARG(options
->AccountingMax
),
1095 options
->AccountingMax
/ interval_length
) {
1097 reason
= "AccountingMax enabled";
1099 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
1100 } else if (options
->BandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
||
1101 (options
->RelayBandwidthRate
> 0 &&
1102 options
->RelayBandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
)) {
1103 /* if we're advertising a small amount */
1105 reason
= "BandwidthRate under 50KB";
1108 if (advertising
!= new_choice
) {
1109 if (new_choice
== 1) {
1110 log_notice(LD_DIR
, "Advertising DirPort as %d", dir_port
);
1113 log_notice(LD_DIR
, "Not advertising DirPort (Reason: %s)", reason
);
1115 advertising
= new_choice
;
1118 return advertising
? dir_port
: 0;
1121 /** Allocate and return a new extend_info_t that can be used to build
1122 * a circuit to or through the router <b>r</b>. Use the primary
1123 * address of the router unless <b>for_direct_connect</b> is true, in
1124 * which case the preferred address is used instead. */
1125 static extend_info_t
*
1126 extend_info_from_router(const routerinfo_t
*r
)
1131 router_get_prim_orport(r
, &ap
);
1132 return extend_info_new(r
->nickname
, r
->cache_info
.identity_digest
,
1133 r
->onion_pkey
, r
->onion_curve25519_pkey
,
1137 /** Some time has passed, or we just got new directory information.
1138 * See if we currently believe our ORPort or DirPort to be
1139 * unreachable. If so, launch a new test for it.
1141 * For ORPort, we simply try making a circuit that ends at ourselves.
1142 * Success is noticed in onionskin_answer().
1144 * For DirPort, we make a connection via Tor to our DirPort and ask
1145 * for our own server descriptor.
1146 * Success is noticed in connection_dir_client_reached_eof().
1149 consider_testing_reachability(int test_or
, int test_dir
)
1151 const routerinfo_t
*me
= router_get_my_routerinfo();
1152 int orport_reachable
= check_whether_orport_reachable();
1154 const or_options_t
*options
= get_options();
1158 if (routerset_contains_router(options
->ExcludeNodes
, me
, -1) &&
1159 options
->StrictNodes
) {
1160 /* If we've excluded ourself, and StrictNodes is set, we can't test
1162 if (test_or
|| test_dir
) {
1163 #define SELF_EXCLUDED_WARN_INTERVAL 3600
1164 static ratelim_t warning_limit
=RATELIM_INIT(SELF_EXCLUDED_WARN_INTERVAL
);
1165 log_fn_ratelim(&warning_limit
, LOG_WARN
, LD_CIRC
,
1166 "Can't peform self-tests for this relay: we have "
1167 "listed ourself in ExcludeNodes, and StrictNodes is set. "
1168 "We cannot learn whether we are usable, and will not "
1169 "be able to advertise ourself.");
1174 if (test_or
&& (!orport_reachable
|| !circuit_enough_testing_circs())) {
1175 extend_info_t
*ei
= extend_info_from_router(me
);
1176 /* XXX IPv6 self testing */
1177 log_info(LD_CIRC
, "Testing %s of my ORPort: %s:%d.",
1178 !orport_reachable
? "reachability" : "bandwidth",
1179 fmt_addr32(me
->addr
), me
->or_port
);
1180 circuit_launch_by_extend_info(CIRCUIT_PURPOSE_TESTING
, ei
,
1181 CIRCLAUNCH_NEED_CAPACITY
|CIRCLAUNCH_IS_INTERNAL
);
1182 extend_info_free(ei
);
1185 tor_addr_from_ipv4h(&addr
, me
->addr
);
1186 if (test_dir
&& !check_whether_dirport_reachable() &&
1187 !connection_get_by_type_addr_port_purpose(
1188 CONN_TYPE_DIR
, &addr
, me
->dir_port
,
1189 DIR_PURPOSE_FETCH_SERVERDESC
)) {
1190 /* ask myself, via tor, for my server descriptor. */
1191 directory_initiate_command(&addr
,
1192 me
->or_port
, me
->dir_port
,
1193 me
->cache_info
.identity_digest
,
1194 DIR_PURPOSE_FETCH_SERVERDESC
,
1195 ROUTER_PURPOSE_GENERAL
,
1196 DIRIND_ANON_DIRPORT
, "authority.z", NULL
, 0, 0);
1200 /** Annotate that we found our ORPort reachable. */
1202 router_orport_found_reachable(void)
1204 const routerinfo_t
*me
= router_get_my_routerinfo();
1205 if (!can_reach_or_port
&& me
) {
1206 char *address
= tor_dup_ip(me
->addr
);
1207 log_notice(LD_OR
,"Self-testing indicates your ORPort is reachable from "
1208 "the outside. Excellent.%s",
1209 get_options()->PublishServerDescriptor_
!= NO_DIRINFO
?
1210 " Publishing server descriptor." : "");
1211 can_reach_or_port
= 1;
1212 mark_my_descriptor_dirty("ORPort found reachable");
1213 control_event_server_status(LOG_NOTICE
,
1214 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
1215 address
, me
->or_port
);
1220 /** Annotate that we found our DirPort reachable. */
1222 router_dirport_found_reachable(void)
1224 const routerinfo_t
*me
= router_get_my_routerinfo();
1225 if (!can_reach_dir_port
&& me
) {
1226 char *address
= tor_dup_ip(me
->addr
);
1227 log_notice(LD_DIRSERV
,"Self-testing indicates your DirPort is reachable "
1228 "from the outside. Excellent.");
1229 can_reach_dir_port
= 1;
1230 if (decide_to_advertise_dirport(get_options(), me
->dir_port
))
1231 mark_my_descriptor_dirty("DirPort found reachable");
1232 control_event_server_status(LOG_NOTICE
,
1233 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
1234 address
, me
->dir_port
);
1239 /** We have enough testing circuits open. Send a bunch of "drop"
1240 * cells down each of them, to exercise our bandwidth. */
1242 router_perform_bandwidth_test(int num_circs
, time_t now
)
1244 int num_cells
= (int)(get_options()->BandwidthRate
* 10 /
1245 CELL_MAX_NETWORK_SIZE
);
1246 int max_cells
= num_cells
< CIRCWINDOW_START
?
1247 num_cells
: CIRCWINDOW_START
;
1248 int cells_per_circuit
= max_cells
/ num_circs
;
1249 origin_circuit_t
*circ
= NULL
;
1251 log_notice(LD_OR
,"Performing bandwidth self-test...done.");
1252 while ((circ
= circuit_get_next_by_pk_and_purpose(circ
, NULL
,
1253 CIRCUIT_PURPOSE_TESTING
))) {
1254 /* dump cells_per_circuit drop cells onto this circ */
1255 int i
= cells_per_circuit
;
1256 if (circ
->base_
.state
!= CIRCUIT_STATE_OPEN
)
1258 circ
->base_
.timestamp_dirty
= now
;
1260 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
1262 NULL
, 0, circ
->cpath
->prev
)<0) {
1263 return; /* stop if error */
1269 /** Return true iff our network is in some sense disabled: either we're
1270 * hibernating, entering hibernation, or the network is turned off with
1271 * DisableNetwork. */
1273 net_is_disabled(void)
1275 return get_options()->DisableNetwork
|| we_are_hibernating();
1278 /** Return true iff we believe ourselves to be an authoritative
1282 authdir_mode(const or_options_t
*options
)
1284 return options
->AuthoritativeDir
!= 0;
1286 /** Return true iff we believe ourselves to be a v3 authoritative
1290 authdir_mode_v3(const or_options_t
*options
)
1292 return authdir_mode(options
) && options
->V3AuthoritativeDir
!= 0;
1294 /** Return true iff we are a v3 directory authority. */
1296 authdir_mode_any_main(const or_options_t
*options
)
1298 return options
->V3AuthoritativeDir
;
1300 /** Return true if we believe ourselves to be any kind of
1301 * authoritative directory beyond just a hidserv authority. */
1303 authdir_mode_any_nonhidserv(const or_options_t
*options
)
1305 return options
->BridgeAuthoritativeDir
||
1306 authdir_mode_any_main(options
);
1308 /** Return true iff we are an authoritative directory server that is
1309 * authoritative about receiving and serving descriptors of type
1310 * <b>purpose</b> on its dirport. Use -1 for "any purpose". */
1312 authdir_mode_handles_descs(const or_options_t
*options
, int purpose
)
1315 return authdir_mode_any_nonhidserv(options
);
1316 else if (purpose
== ROUTER_PURPOSE_GENERAL
)
1317 return authdir_mode_any_main(options
);
1318 else if (purpose
== ROUTER_PURPOSE_BRIDGE
)
1319 return (options
->BridgeAuthoritativeDir
);
1323 /** Return true iff we are an authoritative directory server that
1324 * publishes its own network statuses.
1327 authdir_mode_publishes_statuses(const or_options_t
*options
)
1329 if (authdir_mode_bridge(options
))
1331 return authdir_mode_any_nonhidserv(options
);
1333 /** Return true iff we are an authoritative directory server that
1334 * tests reachability of the descriptors it learns about.
1337 authdir_mode_tests_reachability(const or_options_t
*options
)
1339 return authdir_mode_handles_descs(options
, -1);
1341 /** Return true iff we believe ourselves to be a bridge authoritative
1345 authdir_mode_bridge(const or_options_t
*options
)
1347 return authdir_mode(options
) && options
->BridgeAuthoritativeDir
!= 0;
1350 /** Return true iff we are trying to be a server.
1353 server_mode
,(const or_options_t
*options
))
1355 if (options
->ClientOnly
) return 0;
1356 /* XXXX024 I believe we can kill off ORListenAddress here.*/
1357 return (options
->ORPort_set
|| options
->ORListenAddress
);
1360 /** Return true iff we are trying to be a non-bridge server.
1363 public_server_mode
,(const or_options_t
*options
))
1365 if (!server_mode(options
)) return 0;
1366 return (!options
->BridgeRelay
);
1369 /** Return true iff the combination of options in <b>options</b> and parameters
1370 * in the consensus mean that we don't want to allow exits from circuits
1371 * we got from addresses not known to be servers. */
1373 should_refuse_unknown_exits(const or_options_t
*options
)
1375 if (options
->RefuseUnknownExits
!= -1) {
1376 return options
->RefuseUnknownExits
;
1378 return networkstatus_get_param(NULL
, "refuseunknownexits", 1, 0, 1);
1382 /** Remember if we've advertised ourselves to the dirservers. */
1383 static int server_is_advertised
=0;
1385 /** Return true iff we have published our descriptor lately.
1388 advertised_server_mode(void)
1390 return server_is_advertised
;
1394 * Called with a boolean: set whether we have recently published our
1398 set_server_advertised(int s
)
1400 server_is_advertised
= s
;
1403 /** Return true iff we are trying to proxy client connections. */
1405 proxy_mode(const or_options_t
*options
)
1408 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t
*, p
) {
1409 if (p
->type
== CONN_TYPE_AP_LISTENER
||
1410 p
->type
== CONN_TYPE_AP_TRANS_LISTENER
||
1411 p
->type
== CONN_TYPE_AP_DNS_LISTENER
||
1412 p
->type
== CONN_TYPE_AP_NATD_LISTENER
)
1414 } SMARTLIST_FOREACH_END(p
);
1418 /** Decide if we're a publishable server. We are a publishable server if:
1419 * - We don't have the ClientOnly option set
1421 * - We have the PublishServerDescriptor option set to non-empty
1423 * - We have ORPort set
1425 * - We believe we are reachable from the outside; or
1426 * - We are an authoritative directory server.
1429 decide_if_publishable_server(void)
1431 const or_options_t
*options
= get_options();
1433 if (options
->ClientOnly
)
1435 if (options
->PublishServerDescriptor_
== NO_DIRINFO
)
1437 if (!server_mode(options
))
1439 if (authdir_mode(options
))
1441 if (!router_get_advertised_or_port(options
))
1444 return check_whether_orport_reachable();
1447 /** Initiate server descriptor upload as reasonable (if server is publishable,
1448 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1450 * We need to rebuild the descriptor if it's dirty even if we're not
1451 * uploading, because our reachability testing *uses* our descriptor to
1452 * determine what IP address and ports to test.
1455 consider_publishable_server(int force
)
1459 if (!server_mode(get_options()))
1462 rebuilt
= router_rebuild_descriptor(0);
1463 if (decide_if_publishable_server()) {
1464 set_server_advertised(1);
1466 router_upload_dir_desc_to_dirservers(force
);
1468 set_server_advertised(0);
1472 /** Return the port of the first active listener of type
1473 * <b>listener_type</b>. */
1474 /** XXX not a very good interface. it's not reliable when there are
1475 multiple listeners. */
1477 router_get_active_listener_port_by_type_af(int listener_type
,
1480 /* Iterate all connections, find one of the right kind and return
1481 the port. Not very sophisticated or fast, but effective. */
1482 smartlist_t
*conns
= get_connection_array();
1483 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
1484 if (conn
->type
== listener_type
&& !conn
->marked_for_close
&&
1485 conn
->socket_family
== family
) {
1488 } SMARTLIST_FOREACH_END(conn
);
1493 /** Return the port that we should advertise as our ORPort; this is either
1494 * the one configured in the ORPort option, or the one we actually bound to
1495 * if ORPort is "auto".
1498 router_get_advertised_or_port(const or_options_t
*options
)
1500 return router_get_advertised_or_port_by_af(options
, AF_INET
);
1503 /** As router_get_advertised_or_port(), but allows an address family argument.
1506 router_get_advertised_or_port_by_af(const or_options_t
*options
,
1509 int port
= get_first_advertised_port_by_type_af(CONN_TYPE_OR_LISTENER
,
1513 /* If the port is in 'auto' mode, we have to use
1514 router_get_listener_port_by_type(). */
1515 if (port
== CFG_AUTO_PORT
)
1516 return router_get_active_listener_port_by_type_af(CONN_TYPE_OR_LISTENER
,
1522 /** Return the port that we should advertise as our DirPort;
1523 * this is one of three possibilities:
1524 * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
1525 * the one configured in the DirPort option,
1526 * or the one we actually bound to if DirPort is "auto". */
1528 router_get_advertised_dir_port(const or_options_t
*options
, uint16_t dirport
)
1530 int dirport_configured
= get_primary_dir_port();
1533 if (!dirport_configured
)
1536 if (dirport_configured
== CFG_AUTO_PORT
)
1537 return router_get_active_listener_port_by_type_af(CONN_TYPE_DIR_LISTENER
,
1540 return dirport_configured
;
1544 * OR descriptor generation.
1547 /** My routerinfo. */
1548 static routerinfo_t
*desc_routerinfo
= NULL
;
1550 static extrainfo_t
*desc_extrainfo
= NULL
;
1551 /** Why did we most recently decide to regenerate our descriptor? Used to
1552 * tell the authorities why we're sending it to them. */
1553 static const char *desc_gen_reason
= NULL
;
1554 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1556 static time_t desc_clean_since
= 0;
1557 /** Why did we mark the descriptor dirty? */
1558 static const char *desc_dirty_reason
= NULL
;
1559 /** Boolean: do we need to regenerate the above? */
1560 static int desc_needs_upload
= 0;
1562 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1563 * descriptor successfully yet, try to upload our signed descriptor to
1564 * all the directory servers we know about.
1567 router_upload_dir_desc_to_dirservers(int force
)
1569 const routerinfo_t
*ri
;
1572 size_t desc_len
, extra_len
= 0, total_len
;
1573 dirinfo_type_t auth
= get_options()->PublishServerDescriptor_
;
1575 ri
= router_get_my_routerinfo();
1577 log_info(LD_GENERAL
, "No descriptor; skipping upload");
1580 ei
= router_get_my_extrainfo();
1581 if (auth
== NO_DIRINFO
)
1583 if (!force
&& !desc_needs_upload
)
1586 log_info(LD_OR
, "Uploading relay descriptor to directory authorities%s",
1587 force
? " (forced)" : "");
1589 desc_needs_upload
= 0;
1591 desc_len
= ri
->cache_info
.signed_descriptor_len
;
1592 extra_len
= ei
? ei
->cache_info
.signed_descriptor_len
: 0;
1593 total_len
= desc_len
+ extra_len
+ 1;
1594 msg
= tor_malloc(total_len
);
1595 memcpy(msg
, ri
->cache_info
.signed_descriptor_body
, desc_len
);
1597 memcpy(msg
+desc_len
, ei
->cache_info
.signed_descriptor_body
, extra_len
);
1599 msg
[desc_len
+extra_len
] = 0;
1601 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR
,
1602 (auth
& BRIDGE_DIRINFO
) ?
1603 ROUTER_PURPOSE_BRIDGE
:
1604 ROUTER_PURPOSE_GENERAL
,
1605 auth
, msg
, desc_len
, extra_len
);
1609 /** OR only: Check whether my exit policy says to allow connection to
1610 * conn. Return 0 if we accept; non-0 if we reject.
1613 router_compare_to_my_exit_policy(const tor_addr_t
*addr
, uint16_t port
)
1615 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1618 /* make sure it's resolved to something. this way we can't get a
1620 if (tor_addr_is_null(addr
))
1623 /* look at desc_routerinfo->exit_policy for both the v4 and the v6
1624 * policies. The exit_policy field in desc_routerinfo is a bit unusual,
1625 * in that it contains IPv6 and IPv6 entries. We don't want to look
1626 * at desc_routerinfio->ipv6_exit_policy, since that's a port summary. */
1627 if ((tor_addr_family(addr
) == AF_INET
||
1628 tor_addr_family(addr
) == AF_INET6
)) {
1629 return compare_tor_addr_to_addr_policy(addr
, port
,
1630 desc_routerinfo
->exit_policy
) != ADDR_POLICY_ACCEPTED
;
1632 } else if (tor_addr_family(addr
) == AF_INET6
) {
1633 return get_options()->IPv6Exit
&&
1634 desc_routerinfo
->ipv6_exit_policy
&&
1635 compare_tor_addr_to_short_policy(addr
, port
,
1636 desc_routerinfo
->ipv6_exit_policy
) != ADDR_POLICY_ACCEPTED
;
1643 /** Return true iff my exit policy is reject *:*. Return -1 if we don't
1644 * have a descriptor */
1646 router_my_exit_policy_is_reject_star(void)
1648 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1651 return desc_routerinfo
->policy_is_reject_star
;
1654 /** Return true iff I'm a server and <b>digest</b> is equal to
1655 * my server identity key digest. */
1657 router_digest_is_me(const char *digest
)
1659 return (server_identitykey
&&
1660 tor_memeq(server_identitykey_digest
, digest
, DIGEST_LEN
));
1663 /** Return my identity digest. */
1665 router_get_my_id_digest(void)
1667 return (const uint8_t *)server_identitykey_digest
;
1670 /** Return true iff I'm a server and <b>digest</b> is equal to
1671 * my identity digest. */
1673 router_extrainfo_digest_is_me(const char *digest
)
1675 extrainfo_t
*ei
= router_get_my_extrainfo();
1679 return tor_memeq(digest
,
1680 ei
->cache_info
.signed_descriptor_digest
,
1684 /** A wrapper around router_digest_is_me(). */
1686 router_is_me(const routerinfo_t
*router
)
1688 return router_digest_is_me(router
->cache_info
.identity_digest
);
1691 /** Return a routerinfo for this OR, rebuilding a fresh one if
1692 * necessary. Return NULL on error, or if called on an OP. */
1693 MOCK_IMPL(const routerinfo_t
*,
1694 router_get_my_routerinfo
,(void))
1696 if (!server_mode(get_options()))
1698 if (router_rebuild_descriptor(0))
1700 return desc_routerinfo
;
1703 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1704 * one if necessary. Return NULL on error.
1707 router_get_my_descriptor(void)
1710 if (!router_get_my_routerinfo())
1712 /* Make sure this is nul-terminated. */
1713 tor_assert(desc_routerinfo
->cache_info
.saved_location
== SAVED_NOWHERE
);
1714 body
= signed_descriptor_get_body(&desc_routerinfo
->cache_info
);
1715 tor_assert(!body
[desc_routerinfo
->cache_info
.signed_descriptor_len
]);
1716 log_debug(LD_GENERAL
,"my desc is '%s'", body
);
1720 /** Return the extrainfo document for this OR, or NULL if we have none.
1721 * Rebuilt it (and the server descriptor) if necessary. */
1723 router_get_my_extrainfo(void)
1725 if (!server_mode(get_options()))
1727 if (router_rebuild_descriptor(0))
1729 return desc_extrainfo
;
1732 /** Return a human-readable string describing what triggered us to generate
1733 * our current descriptor, or NULL if we don't know. */
1735 router_get_descriptor_gen_reason(void)
1737 return desc_gen_reason
;
1740 /** A list of nicknames that we've warned about including in our family
1741 * declaration verbatim rather than as digests. */
1742 static smartlist_t
*warned_nonexistent_family
= NULL
;
1744 static int router_guess_address_from_dir_headers(uint32_t *guess
);
1746 /** Make a current best guess at our address, either because
1747 * it's configured in torrc, or because we've learned it from
1748 * dirserver headers. Place the answer in *<b>addr</b> and return
1749 * 0 on success, else return -1 if we have no guess. */
1751 router_pick_published_address(const or_options_t
*options
, uint32_t *addr
)
1753 *addr
= get_last_resolved_addr();
1755 resolve_my_address(LOG_INFO
, options
, addr
, NULL
, NULL
) < 0) {
1756 log_info(LD_CONFIG
, "Could not determine our address locally. "
1757 "Checking if directory headers provide any hints.");
1758 if (router_guess_address_from_dir_headers(addr
) < 0) {
1759 log_info(LD_CONFIG
, "No hints from directory headers either. "
1760 "Will try again later.");
1764 log_info(LD_CONFIG
,"Success: chose address '%s'.", fmt_addr32(*addr
));
1768 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1769 * routerinfo, signed server descriptor, and extra-info document for this OR.
1770 * Return 0 on success, -1 on temporary error.
1773 router_rebuild_descriptor(int force
)
1779 int hibernating
= we_are_hibernating();
1780 const or_options_t
*options
= get_options();
1782 if (desc_clean_since
&& !force
)
1785 if (router_pick_published_address(options
, &addr
) < 0 ||
1786 router_get_advertised_or_port(options
) == 0) {
1787 /* Stop trying to rebuild our descriptor every second. We'll
1788 * learn that it's time to try again when ip_address_changed()
1789 * marks it dirty. */
1790 desc_clean_since
= time(NULL
);
1794 log_info(LD_OR
, "Rebuilding relay descriptor%s", force
? " (forced)" : "");
1796 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
1797 ri
->cache_info
.routerlist_index
= -1;
1798 ri
->nickname
= tor_strdup(options
->Nickname
);
1800 ri
->or_port
= router_get_advertised_or_port(options
);
1801 ri
->dir_port
= router_get_advertised_dir_port(options
, 0);
1802 ri
->cache_info
.published_on
= time(NULL
);
1803 ri
->onion_pkey
= crypto_pk_dup_key(get_onion_key()); /* must invoke from
1805 #ifdef CURVE25519_ENABLED
1806 ri
->onion_curve25519_pkey
=
1807 tor_memdup(&get_current_curve25519_keypair()->pubkey
,
1808 sizeof(curve25519_public_key_t
));
1811 /* For now, at most one IPv6 or-address is being advertised. */
1813 const port_cfg_t
*ipv6_orport
= NULL
;
1814 SMARTLIST_FOREACH_BEGIN(get_configured_ports(), const port_cfg_t
*, p
) {
1815 if (p
->type
== CONN_TYPE_OR_LISTENER
&&
1816 ! p
->no_advertise
&&
1817 ! p
->bind_ipv4_only
&&
1818 tor_addr_family(&p
->addr
) == AF_INET6
) {
1819 if (! tor_addr_is_internal(&p
->addr
, 0)) {
1823 char addrbuf
[TOR_ADDR_BUF_LEN
];
1825 "Unable to use configured IPv6 address \"%s\" in a "
1826 "descriptor. Skipping it. "
1827 "Try specifying a globally reachable address explicitly. ",
1828 tor_addr_to_str(addrbuf
, &p
->addr
, sizeof(addrbuf
), 1));
1831 } SMARTLIST_FOREACH_END(p
);
1833 tor_addr_copy(&ri
->ipv6_addr
, &ipv6_orport
->addr
);
1834 ri
->ipv6_orport
= ipv6_orport
->port
;
1838 ri
->identity_pkey
= crypto_pk_dup_key(get_server_identity_key());
1839 if (crypto_pk_get_digest(ri
->identity_pkey
,
1840 ri
->cache_info
.identity_digest
)<0) {
1841 routerinfo_free(ri
);
1844 get_platform_str(platform
, sizeof(platform
));
1845 ri
->platform
= tor_strdup(platform
);
1847 /* compute ri->bandwidthrate as the min of various options */
1848 ri
->bandwidthrate
= get_effective_bwrate(options
);
1850 /* and compute ri->bandwidthburst similarly */
1851 ri
->bandwidthburst
= get_effective_bwburst(options
);
1853 ri
->bandwidthcapacity
= hibernating
? 0 : rep_hist_bandwidth_assess();
1855 if (dns_seems_to_be_broken() || has_dns_init_failed()) {
1856 /* DNS is screwed up; don't claim to be an exit. */
1857 policies_exit_policy_append_reject_star(&ri
->exit_policy
);
1859 policies_parse_exit_policy(options
->ExitPolicy
, &ri
->exit_policy
,
1861 options
->ExitPolicyRejectPrivate
,
1862 ri
->addr
, !options
->BridgeRelay
);
1864 ri
->policy_is_reject_star
=
1865 policy_is_reject_star(ri
->exit_policy
, AF_INET
) &&
1866 policy_is_reject_star(ri
->exit_policy
, AF_INET6
);
1868 if (options
->IPv6Exit
) {
1869 char *p_tmp
= policy_summarize(ri
->exit_policy
, AF_INET6
);
1871 ri
->ipv6_exit_policy
= parse_short_policy(p_tmp
);
1875 if (options
->MyFamily
&& ! options
->BridgeRelay
) {
1876 smartlist_t
*family
;
1877 if (!warned_nonexistent_family
)
1878 warned_nonexistent_family
= smartlist_new();
1879 family
= smartlist_new();
1880 ri
->declared_family
= smartlist_new();
1881 smartlist_split_string(family
, options
->MyFamily
, ",",
1882 SPLIT_SKIP_SPACE
|SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1883 SMARTLIST_FOREACH_BEGIN(family
, char *, name
) {
1884 const node_t
*member
;
1885 if (!strcasecmp(name
, options
->Nickname
))
1886 goto skip
; /* Don't list ourself, that's redundant */
1888 member
= node_get_by_nickname(name
, 1);
1890 int is_legal
= is_legal_nickname_or_hexdigest(name
);
1891 if (!smartlist_contains_string(warned_nonexistent_family
, name
) &&
1892 !is_legal_hexdigest(name
)) {
1895 "I have no descriptor for the router named \"%s\" in my "
1896 "declared family; I'll use the nickname as is, but "
1897 "this may confuse clients.", name
);
1899 log_warn(LD_CONFIG
, "There is a router named \"%s\" in my "
1900 "declared family, but that isn't a legal nickname. "
1901 "Skipping it.", escaped(name
));
1902 smartlist_add(warned_nonexistent_family
, tor_strdup(name
));
1905 smartlist_add(ri
->declared_family
, name
);
1908 } else if (router_digest_is_me(member
->identity
)) {
1909 /* Don't list ourself in our own family; that's redundant */
1910 /* XXX shouldn't be possible */
1912 char *fp
= tor_malloc(HEX_DIGEST_LEN
+2);
1914 base16_encode(fp
+1,HEX_DIGEST_LEN
+1,
1915 member
->identity
, DIGEST_LEN
);
1916 smartlist_add(ri
->declared_family
, fp
);
1917 if (smartlist_contains_string(warned_nonexistent_family
, name
))
1918 smartlist_string_remove(warned_nonexistent_family
, name
);
1922 } SMARTLIST_FOREACH_END(name
);
1924 /* remove duplicates from the list */
1925 smartlist_sort_strings(ri
->declared_family
);
1926 smartlist_uniq_strings(ri
->declared_family
);
1928 smartlist_free(family
);
1931 /* Now generate the extrainfo. */
1932 ei
= tor_malloc_zero(sizeof(extrainfo_t
));
1933 ei
->cache_info
.is_extrainfo
= 1;
1934 strlcpy(ei
->nickname
, get_options()->Nickname
, sizeof(ei
->nickname
));
1935 ei
->cache_info
.published_on
= ri
->cache_info
.published_on
;
1936 memcpy(ei
->cache_info
.identity_digest
, ri
->cache_info
.identity_digest
,
1938 if (extrainfo_dump_to_string(&ei
->cache_info
.signed_descriptor_body
,
1939 ei
, get_server_identity_key()) < 0) {
1940 log_warn(LD_BUG
, "Couldn't generate extra-info descriptor.");
1944 ei
->cache_info
.signed_descriptor_len
=
1945 strlen(ei
->cache_info
.signed_descriptor_body
);
1946 router_get_extrainfo_hash(ei
->cache_info
.signed_descriptor_body
,
1947 ei
->cache_info
.signed_descriptor_len
,
1948 ei
->cache_info
.signed_descriptor_digest
);
1951 /* Now finish the router descriptor. */
1953 memcpy(ri
->cache_info
.extra_info_digest
,
1954 ei
->cache_info
.signed_descriptor_digest
,
1957 /* ri was allocated with tor_malloc_zero, so there is no need to
1958 * zero ri->cache_info.extra_info_digest here. */
1960 if (! (ri
->cache_info
.signed_descriptor_body
= router_dump_router_to_string(
1961 ri
, get_server_identity_key()))) {
1962 log_warn(LD_BUG
, "Couldn't generate router descriptor.");
1963 routerinfo_free(ri
);
1967 ri
->cache_info
.signed_descriptor_len
=
1968 strlen(ri
->cache_info
.signed_descriptor_body
);
1971 options
->BridgeRelay
? ROUTER_PURPOSE_BRIDGE
: ROUTER_PURPOSE_GENERAL
;
1972 if (options
->BridgeRelay
) {
1973 /* Bridges shouldn't be able to send their descriptors unencrypted,
1974 anyway, since they don't have a DirPort, and always connect to the
1975 bridge authority anonymously. But just in case they somehow think of
1976 sending them on an unencrypted connection, don't allow them to try. */
1977 ri
->cache_info
.send_unencrypted
= 0;
1979 ei
->cache_info
.send_unencrypted
= 0;
1981 ri
->cache_info
.send_unencrypted
= 1;
1983 ei
->cache_info
.send_unencrypted
= 1;
1986 router_get_router_hash(ri
->cache_info
.signed_descriptor_body
,
1987 strlen(ri
->cache_info
.signed_descriptor_body
),
1988 ri
->cache_info
.signed_descriptor_digest
);
1991 tor_assert(! routerinfo_incompatible_with_extrainfo(ri
, ei
, NULL
, NULL
));
1994 routerinfo_free(desc_routerinfo
);
1995 desc_routerinfo
= ri
;
1996 extrainfo_free(desc_extrainfo
);
1997 desc_extrainfo
= ei
;
1999 desc_clean_since
= time(NULL
);
2000 desc_needs_upload
= 1;
2001 desc_gen_reason
= desc_dirty_reason
;
2002 desc_dirty_reason
= NULL
;
2003 control_event_my_descriptor_changed();
2007 /** If our router descriptor ever goes this long without being regenerated
2008 * because something changed, we force an immediate regenerate-and-upload. */
2009 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
2011 /** If our router descriptor seems to be missing or unacceptable according
2012 * to the authorities, regenerate and reupload it _this_ often. */
2013 #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
2015 /** Mark descriptor out of date if it's been "too long" since we last tried
2018 mark_my_descriptor_dirty_if_too_old(time_t now
)
2020 networkstatus_t
*ns
;
2021 const routerstatus_t
*rs
;
2022 const char *retry_fast_reason
= NULL
; /* Set if we should retry frequently */
2023 const time_t slow_cutoff
= now
- FORCE_REGENERATE_DESCRIPTOR_INTERVAL
;
2024 const time_t fast_cutoff
= now
- FAST_RETRY_DESCRIPTOR_INTERVAL
;
2026 /* If it's already dirty, don't mark it. */
2027 if (! desc_clean_since
)
2030 /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
2031 * time to rebuild it. */
2032 if (desc_clean_since
< slow_cutoff
) {
2033 mark_my_descriptor_dirty("time for new descriptor");
2036 /* Now we see whether we want to be retrying frequently or no. The
2037 * rule here is that we'll retry frequently if we aren't listed in the
2038 * live consensus we have, or if the publication time of the
2039 * descriptor listed for us in the consensus is very old. */
2040 ns
= networkstatus_get_live_consensus(now
);
2042 rs
= networkstatus_vote_find_entry(ns
, server_identitykey_digest
);
2044 retry_fast_reason
= "not listed in consensus";
2045 else if (rs
->published_on
< slow_cutoff
)
2046 retry_fast_reason
= "version listed in consensus is quite old";
2049 if (retry_fast_reason
&& desc_clean_since
< fast_cutoff
)
2050 mark_my_descriptor_dirty(retry_fast_reason
);
2053 /** Call when the current descriptor is out of date. */
2055 mark_my_descriptor_dirty(const char *reason
)
2057 const or_options_t
*options
= get_options();
2058 if (server_mode(options
) && options
->PublishServerDescriptor_
)
2059 log_info(LD_OR
, "Decided to publish new relay descriptor: %s", reason
);
2060 desc_clean_since
= 0;
2061 if (!desc_dirty_reason
)
2062 desc_dirty_reason
= reason
;
2065 /** How frequently will we republish our descriptor because of large (factor
2066 * of 2) shifts in estimated bandwidth? */
2067 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
2069 /** Check whether bandwidth has changed a lot since the last time we announced
2070 * bandwidth. If so, mark our descriptor dirty. */
2072 check_descriptor_bandwidth_changed(time_t now
)
2074 static time_t last_changed
= 0;
2076 if (!desc_routerinfo
)
2079 prev
= desc_routerinfo
->bandwidthcapacity
;
2080 cur
= we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
2081 if ((prev
!= cur
&& (!prev
|| !cur
)) ||
2084 if (last_changed
+MAX_BANDWIDTH_CHANGE_FREQ
< now
) {
2085 log_info(LD_GENERAL
,
2086 "Measured bandwidth has changed; rebuilding descriptor.");
2087 mark_my_descriptor_dirty("bandwidth has changed");
2093 /** Note at log level severity that our best guess of address has changed from
2094 * <b>prev</b> to <b>cur</b>. */
2096 log_addr_has_changed(int severity
,
2097 const tor_addr_t
*prev
,
2098 const tor_addr_t
*cur
,
2101 char addrbuf_prev
[TOR_ADDR_BUF_LEN
];
2102 char addrbuf_cur
[TOR_ADDR_BUF_LEN
];
2104 if (tor_addr_to_str(addrbuf_prev
, prev
, sizeof(addrbuf_prev
), 1) == NULL
)
2105 strlcpy(addrbuf_prev
, "???", TOR_ADDR_BUF_LEN
);
2106 if (tor_addr_to_str(addrbuf_cur
, cur
, sizeof(addrbuf_cur
), 1) == NULL
)
2107 strlcpy(addrbuf_cur
, "???", TOR_ADDR_BUF_LEN
);
2109 if (!tor_addr_is_null(prev
))
2110 log_fn(severity
, LD_GENERAL
,
2111 "Our IP Address has changed from %s to %s; "
2112 "rebuilding descriptor (source: %s).",
2113 addrbuf_prev
, addrbuf_cur
, source
);
2115 log_notice(LD_GENERAL
,
2116 "Guessed our IP address as %s (source: %s).",
2117 addrbuf_cur
, source
);
2120 /** Check whether our own address as defined by the Address configuration
2121 * has changed. This is for routers that get their address from a service
2122 * like dyndns. If our address has changed, mark our descriptor dirty. */
2124 check_descriptor_ipaddress_changed(time_t now
)
2127 const or_options_t
*options
= get_options();
2128 const char *method
= NULL
;
2129 char *hostname
= NULL
;
2133 if (!desc_routerinfo
)
2137 prev
= desc_routerinfo
->addr
;
2138 if (resolve_my_address(LOG_INFO
, options
, &cur
, &method
, &hostname
) < 0) {
2139 log_info(LD_CONFIG
,"options->Address didn't resolve into an IP.");
2145 tor_addr_t tmp_prev
, tmp_cur
;
2147 tor_addr_from_ipv4h(&tmp_prev
, prev
);
2148 tor_addr_from_ipv4h(&tmp_cur
, cur
);
2150 tor_asprintf(&source
, "METHOD=%s%s%s", method
,
2151 hostname
? " HOSTNAME=" : "",
2152 hostname
? hostname
: "");
2154 log_addr_has_changed(LOG_NOTICE
, &tmp_prev
, &tmp_cur
, source
);
2157 ip_address_changed(0);
2163 /** The most recently guessed value of our IP address, based on directory
2165 static tor_addr_t last_guessed_ip
= TOR_ADDR_NULL
;
2167 /** A directory server <b>d_conn</b> told us our IP address is
2168 * <b>suggestion</b>.
2169 * If this address is different from the one we think we are now, and
2170 * if our computer doesn't actually know its IP address, then switch. */
2172 router_new_address_suggestion(const char *suggestion
,
2173 const dir_connection_t
*d_conn
)
2176 uint32_t cur
= 0; /* Current IPv4 address. */
2177 const or_options_t
*options
= get_options();
2179 /* first, learn what the IP address actually is */
2180 if (tor_addr_parse(&addr
, suggestion
) == -1) {
2181 log_debug(LD_DIR
, "Malformed X-Your-Address-Is header %s. Ignoring.",
2182 escaped(suggestion
));
2186 log_debug(LD_DIR
, "Got X-Your-Address-Is: %s.", suggestion
);
2188 if (!server_mode(options
)) {
2189 tor_addr_copy(&last_guessed_ip
, &addr
);
2194 cur
= get_last_resolved_addr();
2196 resolve_my_address(LOG_INFO
, options
, &cur
, NULL
, NULL
) >= 0) {
2197 /* We're all set -- we already know our address. Great. */
2198 tor_addr_from_ipv4h(&last_guessed_ip
, cur
); /* store it in case we
2202 if (tor_addr_is_internal(&addr
, 0)) {
2203 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
2206 if (tor_addr_eq(&d_conn
->base_
.addr
, &addr
)) {
2207 /* Don't believe anybody who says our IP is their IP. */
2208 log_debug(LD_DIR
, "A directory server told us our IP address is %s, "
2209 "but he's just reporting his own IP address. Ignoring.",
2214 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
2215 * us an answer different from what we had the last time we managed to
2217 if (!tor_addr_eq(&last_guessed_ip
, &addr
)) {
2218 control_event_server_status(LOG_NOTICE
,
2219 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
2221 log_addr_has_changed(LOG_NOTICE
, &last_guessed_ip
, &addr
,
2222 d_conn
->base_
.address
);
2223 ip_address_changed(0);
2224 tor_addr_copy(&last_guessed_ip
, &addr
); /* router_rebuild_descriptor()
2229 /** We failed to resolve our address locally, but we'd like to build
2230 * a descriptor and publish / test reachability. If we have a guess
2231 * about our address based on directory headers, answer it and return
2232 * 0; else return -1. */
2234 router_guess_address_from_dir_headers(uint32_t *guess
)
2236 if (!tor_addr_is_null(&last_guessed_ip
)) {
2237 *guess
= tor_addr_to_ipv4h(&last_guessed_ip
);
2243 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
2244 * string describing the version of Tor and the operating system we're
2245 * currently running on.
2248 get_platform_str(char *platform
, size_t len
)
2250 tor_snprintf(platform
, len
, "Tor %s on %s",
2251 get_short_version(), get_uname());
2254 /* XXX need to audit this thing and count fenceposts. maybe
2255 * refactor so we don't have to keep asking if we're
2256 * near the end of maxlen?
2258 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2260 /** OR only: Given a routerinfo for this router, and an identity key to sign
2261 * with, encode the routerinfo as a signed server descriptor and return a new
2262 * string encoding the result, or NULL on failure.
2265 router_dump_router_to_string(routerinfo_t
*router
,
2266 crypto_pk_t
*ident_key
)
2268 char *address
= NULL
;
2269 char *onion_pkey
= NULL
; /* Onion key, PEM-encoded. */
2270 char *identity_pkey
= NULL
; /* Identity key, PEM-encoded. */
2271 char digest
[DIGEST_LEN
];
2272 char published
[ISO_TIME_LEN
+1];
2273 char fingerprint
[FINGERPRINT_LEN
+1];
2274 int has_extra_info_digest
;
2275 char extra_info_digest
[HEX_DIGEST_LEN
+1];
2276 size_t onion_pkeylen
, identity_pkeylen
;
2277 char *family_line
= NULL
;
2278 char *extra_or_address
= NULL
;
2279 const or_options_t
*options
= get_options();
2280 smartlist_t
*chunks
= NULL
;
2281 char *output
= NULL
;
2283 /* Make sure the identity key matches the one in the routerinfo. */
2284 if (!crypto_pk_eq_keys(ident_key
, router
->identity_pkey
)) {
2285 log_warn(LD_BUG
,"Tried to sign a router with a private key that didn't "
2286 "match router's public key!");
2290 /* record our fingerprint, so we can include it in the descriptor */
2291 if (crypto_pk_get_fingerprint(router
->identity_pkey
, fingerprint
, 1)<0) {
2292 log_err(LD_BUG
,"Error computing fingerprint");
2296 /* PEM-encode the onion key */
2297 if (crypto_pk_write_public_key_to_string(router
->onion_pkey
,
2298 &onion_pkey
,&onion_pkeylen
)<0) {
2299 log_warn(LD_BUG
,"write onion_pkey to string failed!");
2303 /* PEM-encode the identity key */
2304 if (crypto_pk_write_public_key_to_string(router
->identity_pkey
,
2305 &identity_pkey
,&identity_pkeylen
)<0) {
2306 log_warn(LD_BUG
,"write identity_pkey to string failed!");
2310 /* Encode the publication time. */
2311 format_iso_time(published
, router
->cache_info
.published_on
);
2313 if (router
->declared_family
&& smartlist_len(router
->declared_family
)) {
2314 char *family
= smartlist_join_strings(router
->declared_family
,
2316 tor_asprintf(&family_line
, "family %s\n", family
);
2319 family_line
= tor_strdup("");
2322 has_extra_info_digest
=
2323 ! tor_digest_is_zero(router
->cache_info
.extra_info_digest
);
2325 if (has_extra_info_digest
) {
2326 base16_encode(extra_info_digest
, sizeof(extra_info_digest
),
2327 router
->cache_info
.extra_info_digest
, DIGEST_LEN
);
2330 if (router
->ipv6_orport
&&
2331 tor_addr_family(&router
->ipv6_addr
) == AF_INET6
) {
2332 char addr
[TOR_ADDR_BUF_LEN
];
2334 a
= tor_addr_to_str(addr
, &router
->ipv6_addr
, sizeof(addr
), 1);
2336 tor_asprintf(&extra_or_address
,
2337 "or-address %s:%d\n", a
, router
->ipv6_orport
);
2338 log_debug(LD_OR
, "My or-address line is <%s>", extra_or_address
);
2342 address
= tor_dup_ip(router
->addr
);
2343 chunks
= smartlist_new();
2345 /* Generate the easy portion of the router descriptor. */
2346 smartlist_add_asprintf(chunks
,
2347 "router %s %s %d 0 %d\n"
2350 "protocols Link 1 2 Circuit 1\n"
2354 "bandwidth %d %d %d\n"
2362 decide_to_advertise_dirport(options
, router
->dir_port
),
2363 extra_or_address
? extra_or_address
: "",
2367 stats_n_seconds_working
,
2368 (int) router
->bandwidthrate
,
2369 (int) router
->bandwidthburst
,
2370 (int) router
->bandwidthcapacity
,
2371 has_extra_info_digest
? "extra-info-digest " : "",
2372 has_extra_info_digest
? extra_info_digest
: "",
2373 has_extra_info_digest
? "\n" : "",
2374 options
->DownloadExtraInfo
? "caches-extra-info\n" : "",
2375 onion_pkey
, identity_pkey
,
2377 we_are_hibernating() ? "hibernating 1\n" : "",
2378 options
->HidServDirectoryV2
? "hidden-service-dir\n" : "",
2379 options
->AllowSingleHopExits
? "allow-single-hop-exits\n" : "");
2381 if (options
->ContactInfo
&& strlen(options
->ContactInfo
)) {
2382 const char *ci
= options
->ContactInfo
;
2383 if (strchr(ci
, '\n') || strchr(ci
, '\r'))
2385 smartlist_add_asprintf(chunks
, "contact %s\n", ci
);
2388 #ifdef CURVE25519_ENABLED
2389 if (router
->onion_curve25519_pkey
) {
2391 base64_encode(kbuf
, sizeof(kbuf
),
2392 (const char *)router
->onion_curve25519_pkey
->public_key
,
2393 CURVE25519_PUBKEY_LEN
);
2394 smartlist_add_asprintf(chunks
, "ntor-onion-key %s", kbuf
);
2398 /* Write the exit policy to the end of 's'. */
2399 if (!router
->exit_policy
|| !smartlist_len(router
->exit_policy
)) {
2400 smartlist_add(chunks
, tor_strdup("reject *:*\n"));
2401 } else if (router
->exit_policy
) {
2402 char *exit_policy
= router_dump_exit_policy_to_string(router
,1,0);
2407 smartlist_add_asprintf(chunks
, "%s\n", exit_policy
);
2408 tor_free(exit_policy
);
2411 if (router
->ipv6_exit_policy
) {
2412 char *p6
= write_short_policy(router
->ipv6_exit_policy
);
2413 if (p6
&& strcmp(p6
, "reject 1-65535")) {
2414 smartlist_add_asprintf(chunks
,
2415 "ipv6-policy %s\n", p6
);
2420 /* Sign the descriptor */
2421 smartlist_add(chunks
, tor_strdup("router-signature\n"));
2423 crypto_digest_smartlist(digest
, DIGEST_LEN
, chunks
, "", DIGEST_SHA1
);
2425 note_crypto_pk_op(SIGN_RTR
);
2428 if (!(sig
= router_get_dirobj_signature(digest
, DIGEST_LEN
, ident_key
))) {
2429 log_warn(LD_BUG
, "Couldn't sign router descriptor");
2432 smartlist_add(chunks
, sig
);
2435 /* include a last '\n' */
2436 smartlist_add(chunks
, tor_strdup("\n"));
2438 output
= smartlist_join_strings(chunks
, "", 0, NULL
);
2440 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2444 routerinfo_t
*ri_tmp
;
2445 cp
= s_dup
= tor_strdup(output
);
2446 ri_tmp
= router_parse_entry_from_string(cp
, NULL
, 1, 0, NULL
);
2449 "We just generated a router descriptor we can't parse.");
2450 log_err(LD_BUG
, "Descriptor was: <<%s>>", output
);
2454 routerinfo_free(ri_tmp
);
2461 tor_free(output
); /* sets output to NULL */
2464 SMARTLIST_FOREACH(chunks
, char *, cp
, tor_free(cp
));
2465 smartlist_free(chunks
);
2468 tor_free(family_line
);
2469 tor_free(onion_pkey
);
2470 tor_free(identity_pkey
);
2471 tor_free(extra_or_address
);
2477 * OR only: Given <b>router</b>, produce a string with its exit policy.
2478 * If <b>include_ipv4</b> is true, include IPv4 entries.
2479 * If <b>include_ipv6</b> is true, include IPv6 entries.
2482 router_dump_exit_policy_to_string(const routerinfo_t
*router
,
2486 smartlist_t
*exit_policy_strings
;
2487 char *policy_string
= NULL
;
2489 if ((!router
->exit_policy
) || (router
->policy_is_reject_star
)) {
2490 return tor_strdup("reject *:*");
2493 exit_policy_strings
= smartlist_new();
2495 SMARTLIST_FOREACH_BEGIN(router
->exit_policy
, addr_policy_t
*, tmpe
) {
2497 int bytes_written_to_pbuf
;
2498 if ((tor_addr_family(&tmpe
->addr
) == AF_INET6
) && (!include_ipv6
)) {
2499 continue; /* Don't include IPv6 parts of address policy */
2501 if ((tor_addr_family(&tmpe
->addr
) == AF_INET
) && (!include_ipv4
)) {
2502 continue; /* Don't include IPv4 parts of address policy */
2505 pbuf
= tor_malloc(POLICY_BUF_LEN
);
2506 bytes_written_to_pbuf
= policy_write_item(pbuf
,POLICY_BUF_LEN
, tmpe
, 1);
2508 if (bytes_written_to_pbuf
< 0) {
2509 log_warn(LD_BUG
, "router_dump_exit_policy_to_string ran out of room!");
2514 smartlist_add(exit_policy_strings
,pbuf
);
2515 } SMARTLIST_FOREACH_END(tmpe
);
2517 policy_string
= smartlist_join_strings(exit_policy_strings
, "\n", 0, NULL
);
2520 SMARTLIST_FOREACH(exit_policy_strings
, char *, str
, tor_free(str
));
2521 smartlist_free(exit_policy_strings
);
2523 return policy_string
;
2526 /** Copy the primary (IPv4) OR port (IP address and TCP port) for
2527 * <b>router</b> into *<b>ap_out</b>. */
2529 router_get_prim_orport(const routerinfo_t
*router
, tor_addr_port_t
*ap_out
)
2531 tor_assert(ap_out
!= NULL
);
2532 tor_addr_from_ipv4h(&ap_out
->addr
, router
->addr
);
2533 ap_out
->port
= router
->or_port
;
2536 /** Return 1 if any of <b>router</b>'s addresses are <b>addr</b>.
2537 * Otherwise return 0. */
2539 router_has_addr(const routerinfo_t
*router
, const tor_addr_t
*addr
)
2542 tor_addr_eq_ipv4h(addr
, router
->addr
) ||
2543 tor_addr_eq(&router
->ipv6_addr
, addr
);
2547 router_has_orport(const routerinfo_t
*router
, const tor_addr_port_t
*orport
)
2550 (tor_addr_eq_ipv4h(&orport
->addr
, router
->addr
) &&
2551 orport
->port
== router
->or_port
) ||
2552 (tor_addr_eq(&orport
->addr
, &router
->ipv6_addr
) &&
2553 orport
->port
== router
->ipv6_orport
);
2556 /** Load the contents of <b>filename</b>, find the last line starting with
2557 * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
2558 * the past or more than 1 hour in the future with respect to <b>now</b>,
2559 * and write the file contents starting with that line to *<b>out</b>.
2560 * Return 1 for success, 0 if the file does not exist, or -1 if the file
2561 * does not contain a line matching these criteria or other failure. */
2563 load_stats_file(const char *filename
, const char *end_line
, time_t now
,
2567 char *fname
= get_datadir_fname(filename
);
2568 char *contents
, *start
= NULL
, *tmp
, timestr
[ISO_TIME_LEN
+1];
2570 switch (file_status(fname
)) {
2572 /* X022 Find an alternative to reading the whole file to memory. */
2573 if ((contents
= read_file_to_str(fname
, 0, NULL
))) {
2574 tmp
= strstr(contents
, end_line
);
2575 /* Find last block starting with end_line */
2578 tmp
= strstr(tmp
+ 1, end_line
);
2582 if (strlen(start
) < strlen(end_line
) + 1 + sizeof(timestr
))
2584 strlcpy(timestr
, start
+ 1 + strlen(end_line
), sizeof(timestr
));
2585 if (parse_iso_time(timestr
, &written
) < 0)
2587 if (written
< now
- (25*60*60) || written
> now
+ (1*60*60))
2589 *out
= tor_strdup(start
);
2607 /** Write the contents of <b>extrainfo</b> and aggregated statistics to
2608 * *<b>s_out</b>, signing them with <b>ident_key</b>. Return 0 on
2609 * success, negative on failure. */
2611 extrainfo_dump_to_string(char **s_out
, extrainfo_t
*extrainfo
,
2612 crypto_pk_t
*ident_key
)
2614 const or_options_t
*options
= get_options();
2615 char identity
[HEX_DIGEST_LEN
+1];
2616 char published
[ISO_TIME_LEN
+1];
2617 char digest
[DIGEST_LEN
];
2618 char *bandwidth_usage
;
2620 static int write_stats_to_extrainfo
= 1;
2621 char sig
[DIROBJ_MAX_SIG_LEN
+1];
2622 char *s
, *pre
, *contents
, *cp
, *s_dup
= NULL
;
2623 time_t now
= time(NULL
);
2624 smartlist_t
*chunks
= smartlist_new();
2625 extrainfo_t
*ei_tmp
= NULL
;
2627 base16_encode(identity
, sizeof(identity
),
2628 extrainfo
->cache_info
.identity_digest
, DIGEST_LEN
);
2629 format_iso_time(published
, extrainfo
->cache_info
.published_on
);
2630 bandwidth_usage
= rep_hist_get_bandwidth_lines();
2632 tor_asprintf(&pre
, "extra-info %s %s\npublished %s\n%s",
2633 extrainfo
->nickname
, identity
,
2634 published
, bandwidth_usage
);
2635 tor_free(bandwidth_usage
);
2636 smartlist_add(chunks
, pre
);
2638 if (geoip_is_loaded(AF_INET
))
2639 smartlist_add_asprintf(chunks
, "geoip-db-digest %s\n",
2640 geoip_db_digest(AF_INET
));
2641 if (geoip_is_loaded(AF_INET6
))
2642 smartlist_add_asprintf(chunks
, "geoip6-db-digest %s\n",
2643 geoip_db_digest(AF_INET6
));
2645 if (options
->ExtraInfoStatistics
&& write_stats_to_extrainfo
) {
2646 log_info(LD_GENERAL
, "Adding stats to extra-info descriptor.");
2647 if (options
->DirReqStatistics
&&
2648 load_stats_file("stats"PATH_SEPARATOR
"dirreq-stats",
2649 "dirreq-stats-end", now
, &contents
) > 0) {
2650 smartlist_add(chunks
, contents
);
2652 if (options
->EntryStatistics
&&
2653 load_stats_file("stats"PATH_SEPARATOR
"entry-stats",
2654 "entry-stats-end", now
, &contents
) > 0) {
2655 smartlist_add(chunks
, contents
);
2657 if (options
->CellStatistics
&&
2658 load_stats_file("stats"PATH_SEPARATOR
"buffer-stats",
2659 "cell-stats-end", now
, &contents
) > 0) {
2660 smartlist_add(chunks
, contents
);
2662 if (options
->ExitPortStatistics
&&
2663 load_stats_file("stats"PATH_SEPARATOR
"exit-stats",
2664 "exit-stats-end", now
, &contents
) > 0) {
2665 smartlist_add(chunks
, contents
);
2667 if (options
->ConnDirectionStatistics
&&
2668 load_stats_file("stats"PATH_SEPARATOR
"conn-stats",
2669 "conn-bi-direct", now
, &contents
) > 0) {
2670 smartlist_add(chunks
, contents
);
2674 /* Add information about the pluggable transports we support. */
2675 if (options
->ServerTransportPlugin
) {
2676 char *pluggable_transports
= pt_get_extra_info_descriptor_string();
2677 if (pluggable_transports
)
2678 smartlist_add(chunks
, pluggable_transports
);
2681 if (should_record_bridge_info(options
) && write_stats_to_extrainfo
) {
2682 const char *bridge_stats
= geoip_get_bridge_stats_extrainfo(now
);
2684 smartlist_add(chunks
, tor_strdup(bridge_stats
));
2688 smartlist_add(chunks
, tor_strdup("router-signature\n"));
2689 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
2691 while (strlen(s
) > MAX_EXTRAINFO_UPLOAD_SIZE
- DIROBJ_MAX_SIG_LEN
) {
2692 /* So long as there are at least two chunks (one for the initial
2693 * extra-info line and one for the router-signature), we can keep removing
2695 if (smartlist_len(chunks
) > 2) {
2696 /* We remove the next-to-last element (remember, len-1 is the last
2697 element), since we need to keep the router-signature element. */
2698 int idx
= smartlist_len(chunks
) - 2;
2699 char *e
= smartlist_get(chunks
, idx
);
2700 smartlist_del_keeporder(chunks
, idx
);
2701 log_warn(LD_GENERAL
, "We just generated an extra-info descriptor "
2702 "with statistics that exceeds the 50 KB "
2703 "upload limit. Removing last added "
2707 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
2709 log_warn(LD_BUG
, "We just generated an extra-info descriptors that "
2710 "exceeds the 50 KB upload limit.");
2715 memset(sig
, 0, sizeof(sig
));
2716 if (router_get_extrainfo_hash(s
, strlen(s
), digest
) < 0 ||
2717 router_append_dirobj_signature(sig
, sizeof(sig
), digest
, DIGEST_LEN
,
2719 log_warn(LD_BUG
, "Could not append signature to extra-info "
2723 smartlist_add(chunks
, tor_strdup(sig
));
2725 s
= smartlist_join_strings(chunks
, "", 0, NULL
);
2727 cp
= s_dup
= tor_strdup(s
);
2728 ei_tmp
= extrainfo_parse_entry_from_string(cp
, NULL
, 1, NULL
);
2730 if (write_stats_to_extrainfo
) {
2731 log_warn(LD_GENERAL
, "We just generated an extra-info descriptor "
2732 "with statistics that we can't parse. Not "
2733 "adding statistics to this or any future "
2734 "extra-info descriptors.");
2735 write_stats_to_extrainfo
= 0;
2736 result
= extrainfo_dump_to_string(s_out
, extrainfo
, ident_key
);
2739 log_warn(LD_BUG
, "We just generated an extrainfo descriptor we "
2746 s
= NULL
; /* prevent free */
2755 SMARTLIST_FOREACH(chunks
, char *, cp
, tor_free(cp
));
2756 smartlist_free(chunks
);
2758 extrainfo_free(ei_tmp
);
2763 /** Return true iff <b>s</b> is a valid server nickname. (That is, a string
2764 * containing between 1 and MAX_NICKNAME_LEN characters from
2765 * LEGAL_NICKNAME_CHARACTERS.) */
2767 is_legal_nickname(const char *s
)
2772 return len
> 0 && len
<= MAX_NICKNAME_LEN
&&
2773 strspn(s
,LEGAL_NICKNAME_CHARACTERS
) == len
;
2776 /** Return true iff <b>s</b> is a valid server nickname or
2777 * hex-encoded identity-key digest. */
2779 is_legal_nickname_or_hexdigest(const char *s
)
2782 return is_legal_nickname(s
);
2784 return is_legal_hexdigest(s
);
2787 /** Return true iff <b>s</b> is a valid hex-encoded identity-key
2788 * digest. (That is, an optional $, followed by 40 hex characters,
2789 * followed by either nothing, or = or ~ followed by a nickname, or
2790 * a character other than =, ~, or a hex character.)
2793 is_legal_hexdigest(const char *s
)
2797 if (s
[0] == '$') s
++;
2799 if (len
> HEX_DIGEST_LEN
) {
2800 if (s
[HEX_DIGEST_LEN
] == '=' ||
2801 s
[HEX_DIGEST_LEN
] == '~') {
2802 if (!is_legal_nickname(s
+HEX_DIGEST_LEN
+1))
2808 return (len
>= HEX_DIGEST_LEN
&&
2809 strspn(s
,HEX_CHARACTERS
)==HEX_DIGEST_LEN
);
2812 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2813 * hold a human-readable description of a node with identity digest
2814 * <b>id_digest</b>, named-status <b>is_named</b>, nickname <b>nickname</b>,
2815 * and address <b>addr</b> or <b>addr32h</b>.
2817 * The <b>nickname</b> and <b>addr</b> fields are optional and may be set to
2818 * NULL. The <b>addr32h</b> field is optional and may be set to 0.
2820 * Return a pointer to the front of <b>buf</b>.
2823 format_node_description(char *buf
,
2824 const char *id_digest
,
2826 const char *nickname
,
2827 const tor_addr_t
*addr
,
2833 return "<NULL BUFFER>";
2836 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, id_digest
, DIGEST_LEN
);
2837 cp
= buf
+1+HEX_DIGEST_LEN
;
2839 buf
[1+HEX_DIGEST_LEN
] = is_named
? '=' : '~';
2840 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, nickname
, MAX_NICKNAME_LEN
+1);
2843 if (addr32h
|| addr
) {
2844 memcpy(cp
, " at ", 4);
2847 tor_addr_to_str(cp
, addr
, TOR_ADDR_BUF_LEN
, 0);
2850 in
.s_addr
= htonl(addr32h
);
2851 tor_inet_ntoa(&in
, cp
, INET_NTOA_BUF_LEN
);
2857 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2858 * hold a human-readable description of <b>ri</b>.
2861 * Return a pointer to the front of <b>buf</b>.
2864 router_get_description(char *buf
, const routerinfo_t
*ri
)
2868 return format_node_description(buf
,
2869 ri
->cache_info
.identity_digest
,
2870 router_is_named(ri
),
2876 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2877 * hold a human-readable description of <b>node</b>.
2879 * Return a pointer to the front of <b>buf</b>.
2882 node_get_description(char *buf
, const node_t
*node
)
2884 const char *nickname
= NULL
;
2885 uint32_t addr32h
= 0;
2892 nickname
= node
->rs
->nickname
;
2893 is_named
= node
->rs
->is_named
;
2894 addr32h
= node
->rs
->addr
;
2895 } else if (node
->ri
) {
2896 nickname
= node
->ri
->nickname
;
2897 addr32h
= node
->ri
->addr
;
2900 return format_node_description(buf
,
2908 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2909 * hold a human-readable description of <b>rs</b>.
2911 * Return a pointer to the front of <b>buf</b>.
2914 routerstatus_get_description(char *buf
, const routerstatus_t
*rs
)
2918 return format_node_description(buf
,
2919 rs
->identity_digest
,
2926 /** Use <b>buf</b> (which must be at least NODE_DESC_BUF_LEN bytes long) to
2927 * hold a human-readable description of <b>ei</b>.
2929 * Return a pointer to the front of <b>buf</b>.
2932 extend_info_get_description(char *buf
, const extend_info_t
*ei
)
2936 return format_node_description(buf
,
2937 ei
->identity_digest
,
2944 /** Return a human-readable description of the routerinfo_t <b>ri</b>.
2946 * This function is not thread-safe. Each call to this function invalidates
2947 * previous values returned by this function.
2950 router_describe(const routerinfo_t
*ri
)
2952 static char buf
[NODE_DESC_BUF_LEN
];
2953 return router_get_description(buf
, ri
);
2956 /** Return a human-readable description of the node_t <b>node</b>.
2958 * This function is not thread-safe. Each call to this function invalidates
2959 * previous values returned by this function.
2962 node_describe(const node_t
*node
)
2964 static char buf
[NODE_DESC_BUF_LEN
];
2965 return node_get_description(buf
, node
);
2968 /** Return a human-readable description of the routerstatus_t <b>rs</b>.
2970 * This function is not thread-safe. Each call to this function invalidates
2971 * previous values returned by this function.
2974 routerstatus_describe(const routerstatus_t
*rs
)
2976 static char buf
[NODE_DESC_BUF_LEN
];
2977 return routerstatus_get_description(buf
, rs
);
2980 /** Return a human-readable description of the extend_info_t <b>ri</b>.
2982 * This function is not thread-safe. Each call to this function invalidates
2983 * previous values returned by this function.
2986 extend_info_describe(const extend_info_t
*ei
)
2988 static char buf
[NODE_DESC_BUF_LEN
];
2989 return extend_info_get_description(buf
, ei
);
2992 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
2993 * verbose representation of the identity of <b>router</b>. The format is:
2995 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
2996 * A "=" if the router is named; a "~" if it is not.
2997 * The router's nickname.
3000 router_get_verbose_nickname(char *buf
, const routerinfo_t
*router
)
3002 const char *good_digest
= networkstatus_get_router_digest_by_nickname(
3004 int is_named
= good_digest
&& tor_memeq(good_digest
,
3005 router
->cache_info
.identity_digest
,
3008 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, router
->cache_info
.identity_digest
,
3010 buf
[1+HEX_DIGEST_LEN
] = is_named
? '=' : '~';
3011 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, router
->nickname
, MAX_NICKNAME_LEN
+1);
3014 /** Forget that we have issued any router-related warnings, so that we'll
3015 * warn again if we see the same errors. */
3017 router_reset_warnings(void)
3019 if (warned_nonexistent_family
) {
3020 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
3021 smartlist_clear(warned_nonexistent_family
);
3025 /** Given a router purpose, convert it to a string. Don't call this on
3026 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
3027 * know its string representation. */
3029 router_purpose_to_string(uint8_t p
)
3033 case ROUTER_PURPOSE_GENERAL
: return "general";
3034 case ROUTER_PURPOSE_BRIDGE
: return "bridge";
3035 case ROUTER_PURPOSE_CONTROLLER
: return "controller";
3042 /** Given a string, convert it to a router purpose. */
3044 router_purpose_from_string(const char *s
)
3046 if (!strcmp(s
, "general"))
3047 return ROUTER_PURPOSE_GENERAL
;
3048 else if (!strcmp(s
, "bridge"))
3049 return ROUTER_PURPOSE_BRIDGE
;
3050 else if (!strcmp(s
, "controller"))
3051 return ROUTER_PURPOSE_CONTROLLER
;
3053 return ROUTER_PURPOSE_UNKNOWN
;
3056 /** Release all static resources held in router.c */
3058 router_free_all(void)
3060 crypto_pk_free(onionkey
);
3061 crypto_pk_free(lastonionkey
);
3062 crypto_pk_free(server_identitykey
);
3063 crypto_pk_free(client_identitykey
);
3064 tor_mutex_free(key_lock
);
3065 routerinfo_free(desc_routerinfo
);
3066 extrainfo_free(desc_extrainfo
);
3067 crypto_pk_free(authority_signing_key
);
3068 authority_cert_free(authority_key_certificate
);
3069 crypto_pk_free(legacy_signing_key
);
3070 authority_cert_free(legacy_key_certificate
);
3072 #ifdef CURVE25519_ENABLED
3073 memwipe(&curve25519_onion_key
, 0, sizeof(curve25519_onion_key
));
3074 memwipe(&last_curve25519_onion_key
, 0, sizeof(last_curve25519_onion_key
));
3077 if (warned_nonexistent_family
) {
3078 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
3079 smartlist_free(warned_nonexistent_family
);
3083 /** Return a smartlist of tor_addr_port_t's with all the OR ports of
3084 <b>ri</b>. Note that freeing of the items in the list as well as
3085 the smartlist itself is the callers responsibility.
3087 XXX duplicating code from node_get_all_orports(). */
3089 router_get_all_orports(const routerinfo_t
*ri
)
3091 smartlist_t
*sl
= smartlist_new();
3094 if (ri
->addr
!= 0) {
3095 tor_addr_port_t
*ap
= tor_malloc(sizeof(tor_addr_port_t
));
3096 tor_addr_from_ipv4h(&ap
->addr
, ri
->addr
);
3097 ap
->port
= ri
->or_port
;
3098 smartlist_add(sl
, ap
);
3100 if (!tor_addr_is_null(&ri
->ipv6_addr
)) {
3101 tor_addr_port_t
*ap
= tor_malloc(sizeof(tor_addr_port_t
));
3102 tor_addr_copy(&ap
->addr
, &ri
->ipv6_addr
);
3103 ap
->port
= ri
->or_port
;
3104 smartlist_add(sl
, ap
);