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-2010, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
10 #include "circuitlist.h"
11 #include "circuituse.h"
13 #include "connection.h"
15 #include "directory.h"
19 #include "hibernate.h"
23 #include "routerlist.h"
27 * \brief OR functionality, including key maintenance, generating
28 * and uploading server descriptors, retrying OR connections.
31 extern long stats_n_seconds_working
;
33 /************************************************************/
36 * Key management: ORs only.
39 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
41 static tor_mutex_t
*key_lock
=NULL
;
42 static time_t onionkey_set_at
=0; /**< When was onionkey last changed? */
43 /** Current private onionskin decryption key: used to decode CREATE cells. */
44 static crypto_pk_env_t
*onionkey
=NULL
;
45 /** Previous private onionskin decryption key: used to decode CREATE cells
46 * generated by clients that have an older version of our descriptor. */
47 static crypto_pk_env_t
*lastonionkey
=NULL
;
48 /** Private "identity key": used to sign directory info and TLS
49 * certificates. Never changes. */
50 static crypto_pk_env_t
*identitykey
=NULL
;
51 /** Digest of identitykey. */
52 static char identitykey_digest
[DIGEST_LEN
];
53 /** Signing key used for v3 directory material; only set for authorities. */
54 static crypto_pk_env_t
*authority_signing_key
= NULL
;
55 /** Key certificate to authenticate v3 directory material; only set for
57 static authority_cert_t
*authority_key_certificate
= NULL
;
59 /** For emergency V3 authority key migration: An extra signing key that we use
60 * with our old (obsolete) identity key for a while. */
61 static crypto_pk_env_t
*legacy_signing_key
= NULL
;
62 /** For emergency V3 authority key migration: An extra certificate to
63 * authenticate legacy_signing_key with our obsolete identity key.*/
64 static authority_cert_t
*legacy_key_certificate
= NULL
;
66 /* (Note that v3 authorities also have a separate "authority identity key",
67 * but this key is never actually loaded by the Tor process. Instead, it's
68 * used by tor-gencert to sign new signing keys and make new key
71 /** Replace the current onion key with <b>k</b>. Does not affect
72 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
75 set_onion_key(crypto_pk_env_t
*k
)
77 tor_mutex_acquire(key_lock
);
78 crypto_free_pk_env(onionkey
);
80 onionkey_set_at
= time(NULL
);
81 tor_mutex_release(key_lock
);
82 mark_my_descriptor_dirty();
85 /** Return the current onion key. Requires that the onion key has been
86 * loaded or generated. */
94 /** Store a full copy of the current onion key into *<b>key</b>, and a full
95 * copy of the most recent onion key into *<b>last</b>.
98 dup_onion_keys(crypto_pk_env_t
**key
, crypto_pk_env_t
**last
)
102 tor_mutex_acquire(key_lock
);
103 tor_assert(onionkey
);
104 *key
= crypto_pk_copy_full(onionkey
);
106 *last
= crypto_pk_copy_full(lastonionkey
);
109 tor_mutex_release(key_lock
);
112 /** Return the time when the onion key was last set. This is either the time
113 * when the process launched, or the time of the most recent key rotation since
114 * the process launched.
117 get_onion_key_set_at(void)
119 return onionkey_set_at
;
122 /** Set the current identity key to k.
125 set_identity_key(crypto_pk_env_t
*k
)
127 crypto_free_pk_env(identitykey
);
129 crypto_pk_get_digest(identitykey
, identitykey_digest
);
132 /** Returns the current identity key; requires that the identity key has been
136 get_identity_key(void)
138 tor_assert(identitykey
);
142 /** Return true iff the identity key has been set. */
144 identity_key_is_set(void)
146 return identitykey
!= NULL
;
149 /** Return the key certificate for this v3 (voting) authority, or NULL
150 * if we have no such certificate. */
152 get_my_v3_authority_cert(void)
154 return authority_key_certificate
;
157 /** Return the v3 signing key for this v3 (voting) authority, or NULL
158 * if we have no such key. */
160 get_my_v3_authority_signing_key(void)
162 return authority_signing_key
;
165 /** If we're an authority, and we're using a legacy authority identity key for
166 * emergency migration purposes, return the certificate associated with that
169 get_my_v3_legacy_cert(void)
171 return legacy_key_certificate
;
174 /** If we're an authority, and we're using a legacy authority identity key for
175 * emergency migration purposes, return that key. */
177 get_my_v3_legacy_signing_key(void)
179 return legacy_signing_key
;
182 /** Replace the previous onion key with the current onion key, and generate
183 * a new previous onion key. Immediately after calling this function,
185 * - schedule all previous cpuworkers to shut down _after_ processing
186 * pending work. (This will cause fresh cpuworkers to be generated.)
187 * - generate and upload a fresh routerinfo.
190 rotate_onion_key(void)
192 char *fname
, *fname_prev
;
193 crypto_pk_env_t
*prkey
;
194 or_state_t
*state
= get_or_state();
196 fname
= get_datadir_fname2("keys", "secret_onion_key");
197 fname_prev
= get_datadir_fname2("keys", "secret_onion_key.old");
198 if (!(prkey
= crypto_new_pk_env())) {
199 log_err(LD_GENERAL
,"Error constructing rotated onion key");
202 if (crypto_pk_generate_key(prkey
)) {
203 log_err(LD_BUG
,"Error generating onion key");
206 if (file_status(fname
) == FN_FILE
) {
207 if (replace_file(fname
, fname_prev
))
210 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
211 log_err(LD_FS
,"Couldn't write generated onion key to \"%s\".", fname
);
214 log_info(LD_GENERAL
, "Rotating onion key");
215 tor_mutex_acquire(key_lock
);
216 crypto_free_pk_env(lastonionkey
);
217 lastonionkey
= onionkey
;
220 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
221 tor_mutex_release(key_lock
);
222 mark_my_descriptor_dirty();
223 or_state_mark_dirty(state
, get_options()->AvoidDiskWrites
? now
+3600 : 0);
226 log_warn(LD_GENERAL
, "Couldn't rotate onion key.");
228 crypto_free_pk_env(prkey
);
231 tor_free(fname_prev
);
234 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
235 * and <b>generate</b> is true, create a new RSA key and save it in
236 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
237 * errors at level <b>severity</b>.
240 init_key_from_file(const char *fname
, int generate
, int severity
)
242 crypto_pk_env_t
*prkey
= NULL
;
244 if (!(prkey
= crypto_new_pk_env())) {
245 log(severity
, LD_GENERAL
,"Error constructing key");
249 switch (file_status(fname
)) {
252 log(severity
, LD_FS
,"Can't read key from \"%s\"", fname
);
256 if (!have_lockfile()) {
257 if (try_locking(get_options(), 0)<0) {
258 /* Make sure that --list-fingerprint only creates new keys
259 * if there is no possibility for a deadlock. */
260 log(severity
, LD_FS
, "Another Tor process has locked \"%s\". Not "
261 "writing any new keys.", fname
);
262 /*XXXX The 'other process' might make a key in a second or two;
263 * maybe we should wait for it. */
267 log_info(LD_GENERAL
, "No key found in \"%s\"; generating fresh key.",
269 if (crypto_pk_generate_key(prkey
)) {
270 log(severity
, LD_GENERAL
,"Error generating onion key");
273 if (crypto_pk_check_key(prkey
) <= 0) {
274 log(severity
, LD_GENERAL
,"Generated key seems invalid");
277 log_info(LD_GENERAL
, "Generated key seems valid");
278 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
280 "Couldn't write generated key to \"%s\".", fname
);
284 log_info(LD_GENERAL
, "No key found in \"%s\"", fname
);
288 if (crypto_pk_read_private_key_from_filename(prkey
, fname
)) {
289 log(severity
, LD_GENERAL
,"Error loading private key.");
299 crypto_free_pk_env(prkey
);
303 /** Try to load the vote-signing private key and certificate for being a v3
304 * directory authority, and make sure they match. If <b>legacy</b>, load a
305 * legacy key/cert set for emergency key migration; otherwise load the regular
306 * key/cert set. On success, store them into *<b>key_out</b> and
307 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
309 load_authority_keyset(int legacy
, crypto_pk_env_t
**key_out
,
310 authority_cert_t
**cert_out
)
313 char *fname
= NULL
, *cert
= NULL
;
314 const char *eos
= NULL
;
315 crypto_pk_env_t
*signing_key
= NULL
;
316 authority_cert_t
*parsed
= NULL
;
318 fname
= get_datadir_fname2("keys",
319 legacy
? "legacy_signing_key" : "authority_signing_key");
320 signing_key
= init_key_from_file(fname
, 0, LOG_INFO
);
322 log_warn(LD_DIR
, "No version 3 directory key found in %s", fname
);
326 fname
= get_datadir_fname2("keys",
327 legacy
? "legacy_certificate" : "authority_certificate");
328 cert
= read_file_to_str(fname
, 0, NULL
);
330 log_warn(LD_DIR
, "Signing key found, but no certificate found in %s",
334 parsed
= authority_cert_parse_from_string(cert
, &eos
);
336 log_warn(LD_DIR
, "Unable to parse certificate in %s", fname
);
339 if (crypto_pk_cmp_keys(signing_key
, parsed
->signing_key
) != 0) {
340 log_warn(LD_DIR
, "Stored signing key does not match signing key in "
345 crypto_free_pk_env(*key_out
);
346 authority_cert_free(*cert_out
);
348 *key_out
= signing_key
;
357 crypto_free_pk_env(signing_key
);
358 authority_cert_free(parsed
);
362 /** Load the v3 (voting) authority signing key and certificate, if they are
363 * present. Return -1 if anything is missing, mismatched, or unloadable;
364 * return 0 on success. */
366 init_v3_authority_keys(void)
368 if (load_authority_keyset(0, &authority_signing_key
,
369 &authority_key_certificate
)<0)
372 if (get_options()->V3AuthUseLegacyKey
&&
373 load_authority_keyset(1, &legacy_signing_key
,
374 &legacy_key_certificate
)<0)
380 /** If we're a v3 authority, check whether we have a certificate that's
381 * likely to expire soon. Warn if we do, but not too often. */
383 v3_authority_check_key_expiry(void)
386 static time_t last_warned
= 0;
387 int badness
, time_left
, warn_interval
;
388 if (!authdir_mode_v3(get_options()) || !authority_key_certificate
)
392 expires
= authority_key_certificate
->expires
;
393 time_left
= (int)( expires
- now
);
394 if (time_left
<= 0) {
396 warn_interval
= 60*60;
397 } else if (time_left
<= 24*60*60) {
399 warn_interval
= 60*60;
400 } else if (time_left
<= 24*60*60*7) {
402 warn_interval
= 24*60*60;
403 } else if (time_left
<= 24*60*60*30) {
405 warn_interval
= 24*60*60*5;
410 if (last_warned
+ warn_interval
> now
)
413 if (time_left
<= 0) {
414 log(badness
, LD_DIR
, "Your v3 authority certificate has expired."
415 " Generate a new one NOW.");
416 } else if (time_left
<= 24*60*60) {
417 log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d hours;"
418 " Generate a new one NOW.", time_left
/(60*60));
420 log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d days;"
421 " Generate a new one soon.", time_left
/(24*60*60));
426 /** Initialize all OR private keys, and the TLS context, as necessary.
427 * On OPs, this only initializes the tls context. Return 0 on success,
428 * or -1 if Tor should die.
434 char fingerprint
[FINGERPRINT_LEN
+1];
435 /*nickname<space>fp\n\0 */
436 char fingerprint_line
[MAX_NICKNAME_LEN
+FINGERPRINT_LEN
+3];
438 crypto_pk_env_t
*prkey
;
442 or_options_t
*options
= get_options();
443 authority_type_t type
;
444 time_t now
= time(NULL
);
445 trusted_dir_server_t
*ds
;
446 int v3_digest_set
= 0;
447 authority_cert_t
*cert
= NULL
;
450 key_lock
= tor_mutex_new();
452 /* There are a couple of paths that put us here before */
453 if (crypto_global_init(get_options()->HardwareAccel
,
454 get_options()->AccelName
,
455 get_options()->AccelDir
)) {
456 log_err(LD_BUG
, "Unable to initialize OpenSSL. Exiting.");
460 /* OP's don't need persistent keys; just make up an identity and
461 * initialize the TLS context. */
462 if (!server_mode(options
)) {
463 if (!(prkey
= crypto_new_pk_env()))
465 if (crypto_pk_generate_key(prkey
)) {
466 crypto_free_pk_env(prkey
);
469 set_identity_key(prkey
);
470 /* Create a TLS context; default the client nickname to "client". */
471 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME
) < 0) {
472 log_err(LD_GENERAL
,"Error creating TLS context for Tor client.");
477 /* Make sure DataDirectory exists, and is private. */
478 if (check_private_dir(options
->DataDirectory
, CPD_CREATE
)) {
481 /* Check the key directory. */
482 keydir
= get_datadir_fname("keys");
483 if (check_private_dir(keydir
, CPD_CREATE
)) {
489 /* 1a. Read v3 directory authority key/cert information. */
490 memset(v3_digest
, 0, sizeof(v3_digest
));
491 if (authdir_mode_v3(options
)) {
492 if (init_v3_authority_keys()<0) {
493 log_err(LD_GENERAL
, "We're configured as a V3 authority, but we "
494 "were unable to load our v3 authority keys and certificate! "
495 "Use tor-gencert to generate them. Dying.");
498 cert
= get_my_v3_authority_cert();
500 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key
,
506 /* 1. Read identity key. Make it if none is found. */
507 keydir
= get_datadir_fname2("keys", "secret_id_key");
508 log_info(LD_GENERAL
,"Reading/making identity key \"%s\"...",keydir
);
509 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
511 if (!prkey
) return -1;
512 set_identity_key(prkey
);
514 /* 2. Read onion key. Make it if none is found. */
515 keydir
= get_datadir_fname2("keys", "secret_onion_key");
516 log_info(LD_GENERAL
,"Reading/making onion key \"%s\"...",keydir
);
517 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
519 if (!prkey
) return -1;
520 set_onion_key(prkey
);
521 if (options
->command
== CMD_RUN_TOR
) {
522 /* only mess with the state file if we're actually running Tor */
523 or_state_t
*state
= get_or_state();
524 if (state
->LastRotatedOnionKey
> 100 && state
->LastRotatedOnionKey
< now
) {
525 /* We allow for some parsing slop, but we don't want to risk accepting
526 * values in the distant future. If we did, we might never rotate the
528 onionkey_set_at
= state
->LastRotatedOnionKey
;
530 /* We have no LastRotatedOnionKey set; either we just created the key
531 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
532 * start the clock ticking now so that we will eventually rotate it even
533 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
534 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
535 or_state_mark_dirty(state
, options
->AvoidDiskWrites
?
536 time(NULL
)+3600 : 0);
540 keydir
= get_datadir_fname2("keys", "secret_onion_key.old");
541 if (!lastonionkey
&& file_status(keydir
) == FN_FILE
) {
542 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
544 lastonionkey
= prkey
;
548 /* 3. Initialize link key and TLS context. */
549 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME
) < 0) {
550 log_err(LD_GENERAL
,"Error initializing TLS context");
553 /* 4. Build our router descriptor. */
554 /* Must be called after keys are initialized. */
555 mydesc
= router_get_my_descriptor();
556 if (authdir_mode(options
)) {
557 const char *m
= NULL
;
559 /* We need to add our own fingerprint so it gets recognized. */
560 if (dirserv_add_own_fingerprint(options
->Nickname
, get_identity_key())) {
561 log_err(LD_GENERAL
,"Error adding own fingerprint to approved set");
565 ri
= router_parse_entry_from_string(mydesc
, NULL
, 1, 0, NULL
);
567 log_err(LD_GENERAL
,"Generated a routerinfo we couldn't parse.");
570 if (!WRA_WAS_ADDED(dirserv_add_descriptor(ri
, &m
, "self"))) {
571 log_err(LD_GENERAL
,"Unable to add own descriptor to directory: %s",
572 m
?m
:"<unknown error>");
578 /* 5. Dump fingerprint to 'fingerprint' */
579 keydir
= get_datadir_fname("fingerprint");
580 log_info(LD_GENERAL
,"Dumping fingerprint to \"%s\"...",keydir
);
581 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint
, 0)<0) {
582 log_err(LD_GENERAL
,"Error computing fingerprint");
586 tor_assert(strlen(options
->Nickname
) <= MAX_NICKNAME_LEN
);
587 if (tor_snprintf(fingerprint_line
, sizeof(fingerprint_line
),
588 "%s %s\n",options
->Nickname
, fingerprint
) < 0) {
589 log_err(LD_GENERAL
,"Error writing fingerprint line");
593 /* Check whether we need to write the fingerprint file. */
595 if (file_status(keydir
) == FN_FILE
)
596 cp
= read_file_to_str(keydir
, 0, NULL
);
597 if (!cp
|| strcmp(cp
, fingerprint_line
)) {
598 if (write_str_to_file(keydir
, fingerprint_line
, 0)) {
599 log_err(LD_FS
, "Error writing fingerprint line to file");
608 log(LOG_NOTICE
, LD_GENERAL
,
609 "Your Tor server's identity key fingerprint is '%s %s'",
610 options
->Nickname
, fingerprint
);
611 if (!authdir_mode(options
))
613 /* 6. [authdirserver only] load approved-routers file */
614 if (dirserv_load_fingerprint_file() < 0) {
615 log_err(LD_GENERAL
,"Error loading fingerprints");
618 /* 6b. [authdirserver only] add own key to approved directories. */
619 crypto_pk_get_digest(get_identity_key(), digest
);
620 type
= ((options
->V1AuthoritativeDir
? V1_AUTHORITY
: NO_AUTHORITY
) |
621 (options
->V2AuthoritativeDir
? V2_AUTHORITY
: NO_AUTHORITY
) |
622 (options
->V3AuthoritativeDir
? V3_AUTHORITY
: NO_AUTHORITY
) |
623 (options
->BridgeAuthoritativeDir
? BRIDGE_AUTHORITY
: NO_AUTHORITY
) |
624 (options
->HSAuthoritativeDir
? HIDSERV_AUTHORITY
: NO_AUTHORITY
));
626 ds
= router_get_trusteddirserver_by_digest(digest
);
628 ds
= add_trusted_dir_server(options
->Nickname
, NULL
,
629 (uint16_t)options
->DirPort
,
630 (uint16_t)options
->ORPort
,
635 log_err(LD_GENERAL
,"We want to be a directory authority, but we "
636 "couldn't add ourselves to the authority list. Failing.");
640 if (ds
->type
!= type
) {
641 log_warn(LD_DIR
, "Configured authority type does not match authority "
642 "type in DirServer list. Adjusting. (%d v %d)",
646 if (v3_digest_set
&& (ds
->type
& V3_AUTHORITY
) &&
647 memcmp(v3_digest
, ds
->v3_identity_digest
, DIGEST_LEN
)) {
648 log_warn(LD_DIR
, "V3 identity key does not match identity declared in "
649 "DirServer line. Adjusting.");
650 memcpy(ds
->v3_identity_digest
, v3_digest
, DIGEST_LEN
);
653 if (cert
) { /* add my own cert to the list of known certs */
654 log_info(LD_DIR
, "adding my own v3 cert");
655 if (trusted_dirs_load_certs_from_string(
656 cert
->cache_info
.signed_descriptor_body
, 0, 0)<0) {
657 log_warn(LD_DIR
, "Unable to parse my own v3 cert! Failing.");
662 return 0; /* success */
665 /* Keep track of whether we should upload our server descriptor,
666 * and what type of server we are.
669 /** Whether we can reach our ORPort from the outside. */
670 static int can_reach_or_port
= 0;
671 /** Whether we can reach our DirPort from the outside. */
672 static int can_reach_dir_port
= 0;
674 /** Forget what we have learned about our reachability status. */
676 router_reset_reachability(void)
678 can_reach_or_port
= can_reach_dir_port
= 0;
681 /** Return 1 if ORPort is known reachable; else return 0. */
683 check_whether_orport_reachable(void)
685 or_options_t
*options
= get_options();
686 return options
->AssumeReachable
||
690 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
692 check_whether_dirport_reachable(void)
694 or_options_t
*options
= get_options();
695 return !options
->DirPort
||
696 options
->AssumeReachable
||
697 we_are_hibernating() ||
701 /** Look at a variety of factors, and return 0 if we don't want to
702 * advertise the fact that we have a DirPort open. Else return the
703 * DirPort we want to advertise.
705 * Log a helpful message if we change our mind about whether to publish
709 decide_to_advertise_dirport(or_options_t
*options
, uint16_t dir_port
)
711 static int advertising
=1; /* start out assuming we will advertise */
713 const char *reason
= NULL
;
715 /* Section one: reasons to publish or not publish that aren't
716 * worth mentioning to the user, either because they're obvious
717 * or because they're normal behavior. */
719 if (!dir_port
) /* short circuit the rest of the function */
721 if (authdir_mode(options
)) /* always publish */
723 if (we_are_hibernating())
725 if (!check_whether_dirport_reachable())
728 /* Section two: reasons to publish or not publish that the user
729 * might find surprising. These are generally config options that
730 * make us choose not to publish. */
732 if (accounting_is_enabled(options
)) {
733 /* if we might potentially hibernate */
735 reason
= "AccountingMax enabled";
736 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
737 } else if (options
->BandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
||
738 (options
->RelayBandwidthRate
> 0 &&
739 options
->RelayBandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
)) {
740 /* if we're advertising a small amount */
742 reason
= "BandwidthRate under 50KB";
745 if (advertising
!= new_choice
) {
746 if (new_choice
== 1) {
747 log(LOG_NOTICE
, LD_DIR
, "Advertising DirPort as %d", dir_port
);
750 log(LOG_NOTICE
, LD_DIR
, "Not advertising DirPort (Reason: %s)", reason
);
752 advertising
= new_choice
;
755 return advertising
? dir_port
: 0;
758 /** Some time has passed, or we just got new directory information.
759 * See if we currently believe our ORPort or DirPort to be
760 * unreachable. If so, launch a new test for it.
762 * For ORPort, we simply try making a circuit that ends at ourselves.
763 * Success is noticed in onionskin_answer().
765 * For DirPort, we make a connection via Tor to our DirPort and ask
766 * for our own server descriptor.
767 * Success is noticed in connection_dir_client_reached_eof().
770 consider_testing_reachability(int test_or
, int test_dir
)
772 routerinfo_t
*me
= router_get_my_routerinfo();
773 int orport_reachable
= check_whether_orport_reachable();
778 if (test_or
&& (!orport_reachable
|| !circuit_enough_testing_circs())) {
779 log_info(LD_CIRC
, "Testing %s of my ORPort: %s:%d.",
780 !orport_reachable
? "reachability" : "bandwidth",
781 me
->address
, me
->or_port
);
782 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING
, me
,
783 CIRCLAUNCH_NEED_CAPACITY
|CIRCLAUNCH_IS_INTERNAL
);
786 tor_addr_from_ipv4h(&addr
, me
->addr
);
787 if (test_dir
&& !check_whether_dirport_reachable() &&
788 !connection_get_by_type_addr_port_purpose(
789 CONN_TYPE_DIR
, &addr
, me
->dir_port
,
790 DIR_PURPOSE_FETCH_SERVERDESC
)) {
791 /* ask myself, via tor, for my server descriptor. */
792 directory_initiate_command(me
->address
, &addr
,
793 me
->or_port
, me
->dir_port
,
794 0, /* does not matter */
795 0, me
->cache_info
.identity_digest
,
796 DIR_PURPOSE_FETCH_SERVERDESC
,
797 ROUTER_PURPOSE_GENERAL
,
798 1, "authority.z", NULL
, 0, 0);
802 /** Annotate that we found our ORPort reachable. */
804 router_orport_found_reachable(void)
806 if (!can_reach_or_port
) {
807 routerinfo_t
*me
= router_get_my_routerinfo();
808 log_notice(LD_OR
,"Self-testing indicates your ORPort is reachable from "
809 "the outside. Excellent.%s",
810 get_options()->_PublishServerDescriptor
!= NO_AUTHORITY
?
811 " Publishing server descriptor." : "");
812 can_reach_or_port
= 1;
813 mark_my_descriptor_dirty();
814 if (!me
) { /* should never happen */
815 log_warn(LD_BUG
, "ORPort found reachable, but I have no routerinfo "
816 "yet. Failing to inform controller of success.");
819 control_event_server_status(LOG_NOTICE
,
820 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
821 me
->address
, me
->or_port
);
825 /** Annotate that we found our DirPort reachable. */
827 router_dirport_found_reachable(void)
829 if (!can_reach_dir_port
) {
830 routerinfo_t
*me
= router_get_my_routerinfo();
831 log_notice(LD_DIRSERV
,"Self-testing indicates your DirPort is reachable "
832 "from the outside. Excellent.");
833 can_reach_dir_port
= 1;
834 if (!me
|| decide_to_advertise_dirport(get_options(), me
->dir_port
))
835 mark_my_descriptor_dirty();
836 if (!me
) { /* should never happen */
837 log_warn(LD_BUG
, "DirPort found reachable, but I have no routerinfo "
838 "yet. Failing to inform controller of success.");
841 control_event_server_status(LOG_NOTICE
,
842 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
843 me
->address
, me
->dir_port
);
847 /** We have enough testing circuits open. Send a bunch of "drop"
848 * cells down each of them, to exercise our bandwidth. */
850 router_perform_bandwidth_test(int num_circs
, time_t now
)
852 int num_cells
= (int)(get_options()->BandwidthRate
* 10 / CELL_NETWORK_SIZE
);
853 int max_cells
= num_cells
< CIRCWINDOW_START
?
854 num_cells
: CIRCWINDOW_START
;
855 int cells_per_circuit
= max_cells
/ num_circs
;
856 origin_circuit_t
*circ
= NULL
;
858 log_notice(LD_OR
,"Performing bandwidth self-test...done.");
859 while ((circ
= circuit_get_next_by_pk_and_purpose(circ
, NULL
,
860 CIRCUIT_PURPOSE_TESTING
))) {
861 /* dump cells_per_circuit drop cells onto this circ */
862 int i
= cells_per_circuit
;
863 if (circ
->_base
.state
!= CIRCUIT_STATE_OPEN
)
865 circ
->_base
.timestamp_dirty
= now
;
867 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
869 NULL
, 0, circ
->cpath
->prev
)<0) {
870 return; /* stop if error */
876 /** Return true iff we believe ourselves to be an authoritative
880 authdir_mode(or_options_t
*options
)
882 return options
->AuthoritativeDir
!= 0;
884 /** Return true iff we believe ourselves to be a v1 authoritative
888 authdir_mode_v1(or_options_t
*options
)
890 return authdir_mode(options
) && options
->V1AuthoritativeDir
!= 0;
892 /** Return true iff we believe ourselves to be a v2 authoritative
896 authdir_mode_v2(or_options_t
*options
)
898 return authdir_mode(options
) && options
->V2AuthoritativeDir
!= 0;
900 /** Return true iff we believe ourselves to be a v3 authoritative
904 authdir_mode_v3(or_options_t
*options
)
906 return authdir_mode(options
) && options
->V3AuthoritativeDir
!= 0;
908 /** Return true iff we are a v1, v2, or v3 directory authority. */
910 authdir_mode_any_main(or_options_t
*options
)
912 return options
->V1AuthoritativeDir
||
913 options
->V2AuthoritativeDir
||
914 options
->V3AuthoritativeDir
;
916 /** Return true if we believe ourselves to be any kind of
917 * authoritative directory beyond just a hidserv authority. */
919 authdir_mode_any_nonhidserv(or_options_t
*options
)
921 return options
->BridgeAuthoritativeDir
||
922 authdir_mode_any_main(options
);
924 /** Return true iff we are an authoritative directory server that is
925 * authoritative about receiving and serving descriptors of type
926 * <b>purpose</b> its dirport. Use -1 for "any purpose". */
928 authdir_mode_handles_descs(or_options_t
*options
, int purpose
)
931 return authdir_mode_any_nonhidserv(options
);
932 else if (purpose
== ROUTER_PURPOSE_GENERAL
)
933 return authdir_mode_any_main(options
);
934 else if (purpose
== ROUTER_PURPOSE_BRIDGE
)
935 return (options
->BridgeAuthoritativeDir
);
939 /** Return true iff we are an authoritative directory server that
940 * publishes its own network statuses.
943 authdir_mode_publishes_statuses(or_options_t
*options
)
945 if (authdir_mode_bridge(options
))
947 return authdir_mode_any_nonhidserv(options
);
949 /** Return true iff we are an authoritative directory server that
950 * tests reachability of the descriptors it learns about.
953 authdir_mode_tests_reachability(or_options_t
*options
)
955 return authdir_mode_handles_descs(options
, -1);
957 /** Return true iff we believe ourselves to be a bridge authoritative
961 authdir_mode_bridge(or_options_t
*options
)
963 return authdir_mode(options
) && options
->BridgeAuthoritativeDir
!= 0;
966 /** Return true iff we are trying to be a server.
969 server_mode(or_options_t
*options
)
971 if (options
->ClientOnly
) return 0;
972 return (options
->ORPort
!= 0 || options
->ORListenAddress
);
975 /** Remember if we've advertised ourselves to the dirservers. */
976 static int server_is_advertised
=0;
978 /** Return true iff we have published our descriptor lately.
981 advertised_server_mode(void)
983 return server_is_advertised
;
987 * Called with a boolean: set whether we have recently published our
991 set_server_advertised(int s
)
993 server_is_advertised
= s
;
996 /** Return true iff we are trying to be a socks proxy. */
998 proxy_mode(or_options_t
*options
)
1000 return (options
->SocksPort
!= 0 || options
->SocksListenAddress
||
1001 options
->TransPort
!= 0 || options
->TransListenAddress
||
1002 options
->NatdPort
!= 0 || options
->NatdListenAddress
||
1003 options
->DNSPort
!= 0 || options
->DNSListenAddress
);
1006 /** Decide if we're a publishable server. We are a publishable server if:
1007 * - We don't have the ClientOnly option set
1009 * - We have the PublishServerDescriptor option set to non-empty
1011 * - We have ORPort set
1013 * - We believe we are reachable from the outside; or
1014 * - We are an authoritative directory server.
1017 decide_if_publishable_server(void)
1019 or_options_t
*options
= get_options();
1021 if (options
->ClientOnly
)
1023 if (options
->_PublishServerDescriptor
== NO_AUTHORITY
)
1025 if (!server_mode(options
))
1027 if (authdir_mode(options
))
1030 return check_whether_orport_reachable();
1033 /** Initiate server descriptor upload as reasonable (if server is publishable,
1034 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1036 * We need to rebuild the descriptor if it's dirty even if we're not
1037 * uploading, because our reachability testing *uses* our descriptor to
1038 * determine what IP address and ports to test.
1041 consider_publishable_server(int force
)
1045 if (!server_mode(get_options()))
1048 rebuilt
= router_rebuild_descriptor(0);
1049 if (decide_if_publishable_server()) {
1050 set_server_advertised(1);
1052 router_upload_dir_desc_to_dirservers(force
);
1054 set_server_advertised(0);
1059 * OR descriptor generation.
1062 /** My routerinfo. */
1063 static routerinfo_t
*desc_routerinfo
= NULL
;
1065 static extrainfo_t
*desc_extrainfo
= NULL
;
1066 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1068 static time_t desc_clean_since
= 0;
1069 /** Boolean: do we need to regenerate the above? */
1070 static int desc_needs_upload
= 0;
1072 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1073 * descriptor successfully yet, try to upload our signed descriptor to
1074 * all the directory servers we know about.
1077 router_upload_dir_desc_to_dirservers(int force
)
1082 size_t desc_len
, extra_len
= 0, total_len
;
1083 authority_type_t auth
= get_options()->_PublishServerDescriptor
;
1085 ri
= router_get_my_routerinfo();
1087 log_info(LD_GENERAL
, "No descriptor; skipping upload");
1090 ei
= router_get_my_extrainfo();
1091 if (auth
== NO_AUTHORITY
)
1093 if (!force
&& !desc_needs_upload
)
1095 desc_needs_upload
= 0;
1097 desc_len
= ri
->cache_info
.signed_descriptor_len
;
1098 extra_len
= ei
? ei
->cache_info
.signed_descriptor_len
: 0;
1099 total_len
= desc_len
+ extra_len
+ 1;
1100 msg
= tor_malloc(total_len
);
1101 memcpy(msg
, ri
->cache_info
.signed_descriptor_body
, desc_len
);
1103 memcpy(msg
+desc_len
, ei
->cache_info
.signed_descriptor_body
, extra_len
);
1105 msg
[desc_len
+extra_len
] = 0;
1107 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR
,
1108 (auth
& BRIDGE_AUTHORITY
) ?
1109 ROUTER_PURPOSE_BRIDGE
:
1110 ROUTER_PURPOSE_GENERAL
,
1111 auth
, msg
, desc_len
, extra_len
);
1115 /** OR only: Check whether my exit policy says to allow connection to
1116 * conn. Return 0 if we accept; non-0 if we reject.
1119 router_compare_to_my_exit_policy(edge_connection_t
*conn
)
1121 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1124 /* make sure it's resolved to something. this way we can't get a
1126 if (tor_addr_is_null(&conn
->_base
.addr
))
1130 if (tor_addr_family(&conn
->_base
.addr
) != AF_INET
)
1133 return compare_tor_addr_to_addr_policy(&conn
->_base
.addr
, conn
->_base
.port
,
1134 desc_routerinfo
->exit_policy
) != ADDR_POLICY_ACCEPTED
;
1137 /** Return true iff I'm a server and <b>digest</b> is equal to
1138 * my identity digest. */
1140 router_digest_is_me(const char *digest
)
1142 return identitykey
&& !memcmp(identitykey_digest
, digest
, DIGEST_LEN
);
1145 /** Return true iff I'm a server and <b>digest</b> is equal to
1146 * my identity digest. */
1148 router_extrainfo_digest_is_me(const char *digest
)
1150 extrainfo_t
*ei
= router_get_my_extrainfo();
1154 return !memcmp(digest
,
1155 ei
->cache_info
.signed_descriptor_digest
,
1159 /** A wrapper around router_digest_is_me(). */
1161 router_is_me(routerinfo_t
*router
)
1163 return router_digest_is_me(router
->cache_info
.identity_digest
);
1166 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1168 router_fingerprint_is_me(const char *fp
)
1170 char digest
[DIGEST_LEN
];
1171 if (strlen(fp
) == HEX_DIGEST_LEN
&&
1172 base16_decode(digest
, sizeof(digest
), fp
, HEX_DIGEST_LEN
) == 0)
1173 return router_digest_is_me(digest
);
1178 /** Return a routerinfo for this OR, rebuilding a fresh one if
1179 * necessary. Return NULL on error, or if called on an OP. */
1181 router_get_my_routerinfo(void)
1183 if (!server_mode(get_options()))
1185 if (router_rebuild_descriptor(0))
1187 return desc_routerinfo
;
1190 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1191 * one if necessary. Return NULL on error.
1194 router_get_my_descriptor(void)
1197 if (!router_get_my_routerinfo())
1199 /* Make sure this is nul-terminated. */
1200 tor_assert(desc_routerinfo
->cache_info
.saved_location
== SAVED_NOWHERE
);
1201 body
= signed_descriptor_get_body(&desc_routerinfo
->cache_info
);
1202 tor_assert(!body
[desc_routerinfo
->cache_info
.signed_descriptor_len
]);
1203 log_debug(LD_GENERAL
,"my desc is '%s'", body
);
1207 /** Return the extrainfo document for this OR, or NULL if we have none.
1208 * Rebuilt it (and the server descriptor) if necessary. */
1210 router_get_my_extrainfo(void)
1212 if (!server_mode(get_options()))
1214 if (router_rebuild_descriptor(0))
1216 return desc_extrainfo
;
1219 /** A list of nicknames that we've warned about including in our family
1220 * declaration verbatim rather than as digests. */
1221 static smartlist_t
*warned_nonexistent_family
= NULL
;
1223 static int router_guess_address_from_dir_headers(uint32_t *guess
);
1225 /** Make a current best guess at our address, either because
1226 * it's configured in torrc, or because we've learned it from
1227 * dirserver headers. Place the answer in *<b>addr</b> and return
1228 * 0 on success, else return -1 if we have no guess. */
1230 router_pick_published_address(or_options_t
*options
, uint32_t *addr
)
1232 if (resolve_my_address(LOG_INFO
, options
, addr
, NULL
) < 0) {
1233 log_info(LD_CONFIG
, "Could not determine our address locally. "
1234 "Checking if directory headers provide any hints.");
1235 if (router_guess_address_from_dir_headers(addr
) < 0) {
1236 log_info(LD_CONFIG
, "No hints from directory headers either. "
1237 "Will try again later.");
1244 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1245 * routerinfo, signed server descriptor, and extra-info document for this OR.
1246 * Return 0 on success, -1 on temporary error.
1249 router_rebuild_descriptor(int force
)
1255 int hibernating
= we_are_hibernating();
1257 or_options_t
*options
= get_options();
1259 if (desc_clean_since
&& !force
)
1262 if (router_pick_published_address(options
, &addr
) < 0) {
1263 /* Stop trying to rebuild our descriptor every second. We'll
1264 * learn that it's time to try again when server_has_changed_ip()
1265 * marks it dirty. */
1266 desc_clean_since
= time(NULL
);
1270 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
1271 ri
->cache_info
.routerlist_index
= -1;
1272 ri
->address
= tor_dup_ip(addr
);
1273 ri
->nickname
= tor_strdup(options
->Nickname
);
1275 ri
->or_port
= options
->ORPort
;
1276 ri
->dir_port
= options
->DirPort
;
1277 ri
->cache_info
.published_on
= time(NULL
);
1278 ri
->onion_pkey
= crypto_pk_dup_key(get_onion_key()); /* must invoke from
1280 ri
->identity_pkey
= crypto_pk_dup_key(get_identity_key());
1281 if (crypto_pk_get_digest(ri
->identity_pkey
,
1282 ri
->cache_info
.identity_digest
)<0) {
1283 routerinfo_free(ri
);
1286 get_platform_str(platform
, sizeof(platform
));
1287 ri
->platform
= tor_strdup(platform
);
1289 /* compute ri->bandwidthrate as the min of various options */
1290 ri
->bandwidthrate
= get_effective_bwrate(options
);
1292 /* and compute ri->bandwidthburst similarly */
1293 ri
->bandwidthburst
= get_effective_bwburst(options
);
1295 ri
->bandwidthcapacity
= hibernating
? 0 : rep_hist_bandwidth_assess();
1297 policies_parse_exit_policy(options
->ExitPolicy
, &ri
->exit_policy
,
1298 options
->ExitPolicyRejectPrivate
,
1299 ri
->address
, !options
->BridgeRelay
);
1301 if (desc_routerinfo
) { /* inherit values */
1302 ri
->is_valid
= desc_routerinfo
->is_valid
;
1303 ri
->is_running
= desc_routerinfo
->is_running
;
1304 ri
->is_named
= desc_routerinfo
->is_named
;
1306 if (authdir_mode(options
))
1307 ri
->is_valid
= ri
->is_named
= 1; /* believe in yourself */
1308 if (options
->MyFamily
) {
1309 smartlist_t
*family
;
1310 if (!warned_nonexistent_family
)
1311 warned_nonexistent_family
= smartlist_create();
1312 family
= smartlist_create();
1313 ri
->declared_family
= smartlist_create();
1314 smartlist_split_string(family
, options
->MyFamily
, ",",
1315 SPLIT_SKIP_SPACE
|SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1316 SMARTLIST_FOREACH(family
, char *, name
,
1318 routerinfo_t
*member
;
1319 if (!strcasecmp(name
, options
->Nickname
))
1322 member
= router_get_by_nickname(name
, 1);
1324 int is_legal
= is_legal_nickname_or_hexdigest(name
);
1325 if (!smartlist_string_isin(warned_nonexistent_family
, name
) &&
1326 !is_legal_hexdigest(name
)) {
1329 "I have no descriptor for the router named \"%s\" in my "
1330 "declared family; I'll use the nickname as is, but "
1331 "this may confuse clients.", name
);
1333 log_warn(LD_CONFIG
, "There is a router named \"%s\" in my "
1334 "declared family, but that isn't a legal nickname. "
1335 "Skipping it.", escaped(name
));
1336 smartlist_add(warned_nonexistent_family
, tor_strdup(name
));
1339 smartlist_add(ri
->declared_family
, name
);
1342 } else if (router_is_me(member
)) {
1343 /* Don't list ourself in our own family; that's redundant */
1345 char *fp
= tor_malloc(HEX_DIGEST_LEN
+2);
1347 base16_encode(fp
+1,HEX_DIGEST_LEN
+1,
1348 member
->cache_info
.identity_digest
, DIGEST_LEN
);
1349 smartlist_add(ri
->declared_family
, fp
);
1350 if (smartlist_string_isin(warned_nonexistent_family
, name
))
1351 smartlist_string_remove(warned_nonexistent_family
, name
);
1356 /* remove duplicates from the list */
1357 smartlist_sort_strings(ri
->declared_family
);
1358 smartlist_uniq_strings(ri
->declared_family
);
1360 smartlist_free(family
);
1363 /* Now generate the extrainfo. */
1364 ei
= tor_malloc_zero(sizeof(extrainfo_t
));
1365 ei
->cache_info
.is_extrainfo
= 1;
1366 strlcpy(ei
->nickname
, get_options()->Nickname
, sizeof(ei
->nickname
));
1367 ei
->cache_info
.published_on
= ri
->cache_info
.published_on
;
1368 memcpy(ei
->cache_info
.identity_digest
, ri
->cache_info
.identity_digest
,
1370 ei_size
= options
->ExtraInfoStatistics
? MAX_EXTRAINFO_UPLOAD_SIZE
: 8192;
1371 ei
->cache_info
.signed_descriptor_body
= tor_malloc(ei_size
);
1372 if (extrainfo_dump_to_string(ei
->cache_info
.signed_descriptor_body
,
1373 ei_size
, ei
, get_identity_key()) < 0) {
1374 log_warn(LD_BUG
, "Couldn't generate extra-info descriptor.");
1375 routerinfo_free(ri
);
1379 ei
->cache_info
.signed_descriptor_len
=
1380 strlen(ei
->cache_info
.signed_descriptor_body
);
1381 router_get_extrainfo_hash(ei
->cache_info
.signed_descriptor_body
,
1382 ei
->cache_info
.signed_descriptor_digest
);
1384 /* Now finish the router descriptor. */
1385 memcpy(ri
->cache_info
.extra_info_digest
,
1386 ei
->cache_info
.signed_descriptor_digest
,
1388 ri
->cache_info
.signed_descriptor_body
= tor_malloc(8192);
1389 if (router_dump_router_to_string(ri
->cache_info
.signed_descriptor_body
, 8192,
1390 ri
, get_identity_key())<0) {
1391 log_warn(LD_BUG
, "Couldn't generate router descriptor.");
1392 routerinfo_free(ri
);
1396 ri
->cache_info
.signed_descriptor_len
=
1397 strlen(ri
->cache_info
.signed_descriptor_body
);
1400 options
->BridgeRelay
? ROUTER_PURPOSE_BRIDGE
: ROUTER_PURPOSE_GENERAL
;
1401 ri
->cache_info
.send_unencrypted
= 1;
1402 /* Let bridges serve their own descriptors unencrypted, so they can
1403 * pass reachability testing. (If they want to be harder to notice,
1404 * they can always leave the DirPort off). */
1405 if (!options
->BridgeRelay
)
1406 ei
->cache_info
.send_unencrypted
= 1;
1408 router_get_router_hash(ri
->cache_info
.signed_descriptor_body
,
1409 strlen(ri
->cache_info
.signed_descriptor_body
),
1410 ri
->cache_info
.signed_descriptor_digest
);
1412 routerinfo_set_country(ri
);
1414 tor_assert(! routerinfo_incompatible_with_extrainfo(ri
, ei
, NULL
, NULL
));
1416 routerinfo_free(desc_routerinfo
);
1417 desc_routerinfo
= ri
;
1418 extrainfo_free(desc_extrainfo
);
1419 desc_extrainfo
= ei
;
1421 desc_clean_since
= time(NULL
);
1422 desc_needs_upload
= 1;
1423 control_event_my_descriptor_changed();
1427 /** Mark descriptor out of date if it's older than <b>when</b> */
1429 mark_my_descriptor_dirty_if_older_than(time_t when
)
1431 if (desc_clean_since
< when
)
1432 mark_my_descriptor_dirty();
1435 /** Call when the current descriptor is out of date. */
1437 mark_my_descriptor_dirty(void)
1439 desc_clean_since
= 0;
1442 /** How frequently will we republish our descriptor because of large (factor
1443 * of 2) shifts in estimated bandwidth? */
1444 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
1446 /** Check whether bandwidth has changed a lot since the last time we announced
1447 * bandwidth. If so, mark our descriptor dirty. */
1449 check_descriptor_bandwidth_changed(time_t now
)
1451 static time_t last_changed
= 0;
1453 if (!desc_routerinfo
)
1456 prev
= desc_routerinfo
->bandwidthcapacity
;
1457 cur
= we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
1458 if ((prev
!= cur
&& (!prev
|| !cur
)) ||
1461 if (last_changed
+MAX_BANDWIDTH_CHANGE_FREQ
< now
) {
1462 log_info(LD_GENERAL
,
1463 "Measured bandwidth has changed; rebuilding descriptor.");
1464 mark_my_descriptor_dirty();
1470 /** Note at log level severity that our best guess of address has changed from
1471 * <b>prev</b> to <b>cur</b>. */
1473 log_addr_has_changed(int severity
, uint32_t prev
, uint32_t cur
,
1476 char addrbuf_prev
[INET_NTOA_BUF_LEN
];
1477 char addrbuf_cur
[INET_NTOA_BUF_LEN
];
1478 struct in_addr in_prev
;
1479 struct in_addr in_cur
;
1481 in_prev
.s_addr
= htonl(prev
);
1482 tor_inet_ntoa(&in_prev
, addrbuf_prev
, sizeof(addrbuf_prev
));
1484 in_cur
.s_addr
= htonl(cur
);
1485 tor_inet_ntoa(&in_cur
, addrbuf_cur
, sizeof(addrbuf_cur
));
1488 log_fn(severity
, LD_GENERAL
,
1489 "Our IP Address has changed from %s to %s; "
1490 "rebuilding descriptor (source: %s).",
1491 addrbuf_prev
, addrbuf_cur
, source
);
1493 log_notice(LD_GENERAL
,
1494 "Guessed our IP address as %s (source: %s).",
1495 addrbuf_cur
, source
);
1498 /** Check whether our own address as defined by the Address configuration
1499 * has changed. This is for routers that get their address from a service
1500 * like dyndns. If our address has changed, mark our descriptor dirty. */
1502 check_descriptor_ipaddress_changed(time_t now
)
1505 or_options_t
*options
= get_options();
1508 if (!desc_routerinfo
)
1511 prev
= desc_routerinfo
->addr
;
1512 if (resolve_my_address(LOG_INFO
, options
, &cur
, NULL
) < 0) {
1513 log_info(LD_CONFIG
,"options->Address didn't resolve into an IP.");
1518 log_addr_has_changed(LOG_NOTICE
, prev
, cur
, "resolve");
1519 ip_address_changed(0);
1523 /** The most recently guessed value of our IP address, based on directory
1525 static uint32_t last_guessed_ip
= 0;
1527 /** A directory server <b>d_conn</b> told us our IP address is
1528 * <b>suggestion</b>.
1529 * If this address is different from the one we think we are now, and
1530 * if our computer doesn't actually know its IP address, then switch. */
1532 router_new_address_suggestion(const char *suggestion
,
1533 const dir_connection_t
*d_conn
)
1535 uint32_t addr
, cur
= 0;
1537 or_options_t
*options
= get_options();
1539 /* first, learn what the IP address actually is */
1540 if (!tor_inet_aton(suggestion
, &in
)) {
1541 log_debug(LD_DIR
, "Malformed X-Your-Address-Is header %s. Ignoring.",
1542 escaped(suggestion
));
1545 addr
= ntohl(in
.s_addr
);
1547 log_debug(LD_DIR
, "Got X-Your-Address-Is: %s.", suggestion
);
1549 if (!server_mode(options
)) {
1550 last_guessed_ip
= addr
; /* store it in case we need it later */
1554 if (resolve_my_address(LOG_INFO
, options
, &cur
, NULL
) >= 0) {
1555 /* We're all set -- we already know our address. Great. */
1556 last_guessed_ip
= cur
; /* store it in case we need it later */
1559 if (is_internal_IP(addr
, 0)) {
1560 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1563 if (tor_addr_eq_ipv4h(&d_conn
->_base
.addr
, addr
)) {
1564 /* Don't believe anybody who says our IP is their IP. */
1565 log_debug(LD_DIR
, "A directory server told us our IP address is %s, "
1566 "but he's just reporting his own IP address. Ignoring.",
1571 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1572 * us an answer different from what we had the last time we managed to
1574 if (last_guessed_ip
!= addr
) {
1575 control_event_server_status(LOG_NOTICE
,
1576 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1578 log_addr_has_changed(LOG_NOTICE
, last_guessed_ip
, addr
,
1579 d_conn
->_base
.address
);
1580 ip_address_changed(0);
1581 last_guessed_ip
= addr
; /* router_rebuild_descriptor() will fetch it */
1585 /** We failed to resolve our address locally, but we'd like to build
1586 * a descriptor and publish / test reachability. If we have a guess
1587 * about our address based on directory headers, answer it and return
1588 * 0; else return -1. */
1590 router_guess_address_from_dir_headers(uint32_t *guess
)
1592 if (last_guessed_ip
) {
1593 *guess
= last_guessed_ip
;
1599 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1600 * string describing the version of Tor and the operating system we're
1601 * currently running on.
1604 get_platform_str(char *platform
, size_t len
)
1606 tor_snprintf(platform
, len
, "Tor %s on %s", get_version(), get_uname());
1609 /* XXX need to audit this thing and count fenceposts. maybe
1610 * refactor so we don't have to keep asking if we're
1611 * near the end of maxlen?
1613 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1615 /** OR only: Given a routerinfo for this router, and an identity key to sign
1616 * with, encode the routerinfo as a signed server descriptor and write the
1617 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1618 * failure, and the number of bytes used on success.
1621 router_dump_router_to_string(char *s
, size_t maxlen
, routerinfo_t
*router
,
1622 crypto_pk_env_t
*ident_key
)
1624 char *onion_pkey
; /* Onion key, PEM-encoded. */
1625 char *identity_pkey
; /* Identity key, PEM-encoded. */
1626 char digest
[DIGEST_LEN
];
1627 char published
[ISO_TIME_LEN
+1];
1628 char fingerprint
[FINGERPRINT_LEN
+1];
1629 char extra_info_digest
[HEX_DIGEST_LEN
+1];
1630 size_t onion_pkeylen
, identity_pkeylen
;
1633 addr_policy_t
*tmpe
;
1635 or_options_t
*options
= get_options();
1637 /* Make sure the identity key matches the one in the routerinfo. */
1638 if (crypto_pk_cmp_keys(ident_key
, router
->identity_pkey
)) {
1639 log_warn(LD_BUG
,"Tried to sign a router with a private key that didn't "
1640 "match router's public key!");
1644 /* record our fingerprint, so we can include it in the descriptor */
1645 if (crypto_pk_get_fingerprint(router
->identity_pkey
, fingerprint
, 1)<0) {
1646 log_err(LD_BUG
,"Error computing fingerprint");
1650 /* PEM-encode the onion key */
1651 if (crypto_pk_write_public_key_to_string(router
->onion_pkey
,
1652 &onion_pkey
,&onion_pkeylen
)<0) {
1653 log_warn(LD_BUG
,"write onion_pkey to string failed!");
1657 /* PEM-encode the identity key */
1658 if (crypto_pk_write_public_key_to_string(router
->identity_pkey
,
1659 &identity_pkey
,&identity_pkeylen
)<0) {
1660 log_warn(LD_BUG
,"write identity_pkey to string failed!");
1661 tor_free(onion_pkey
);
1665 /* Encode the publication time. */
1666 format_iso_time(published
, router
->cache_info
.published_on
);
1668 if (router
->declared_family
&& smartlist_len(router
->declared_family
)) {
1670 char *family
= smartlist_join_strings(router
->declared_family
, " ", 0, &n
);
1671 n
+= strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1672 family_line
= tor_malloc(n
);
1673 tor_snprintf(family_line
, n
, "family %s\n", family
);
1676 family_line
= tor_strdup("");
1679 base16_encode(extra_info_digest
, sizeof(extra_info_digest
),
1680 router
->cache_info
.extra_info_digest
, DIGEST_LEN
);
1682 /* Generate the easy portion of the router descriptor. */
1683 result
= tor_snprintf(s
, maxlen
,
1684 "router %s %s %d 0 %d\n"
1686 "opt protocols Link 1 2 Circuit 1\n"
1688 "opt fingerprint %s\n"
1690 "bandwidth %d %d %d\n"
1691 "opt extra-info-digest %s\n%s"
1698 decide_to_advertise_dirport(options
, router
->dir_port
),
1702 stats_n_seconds_working
,
1703 (int) router
->bandwidthrate
,
1704 (int) router
->bandwidthburst
,
1705 (int) router
->bandwidthcapacity
,
1707 options
->DownloadExtraInfo
? "opt caches-extra-info\n" : "",
1708 onion_pkey
, identity_pkey
,
1710 we_are_hibernating() ? "opt hibernating 1\n" : "",
1711 options
->HidServDirectoryV2
? "opt hidden-service-dir\n" : "",
1712 options
->AllowSingleHopExits
? "opt allow-single-hop-exits\n" : "");
1714 tor_free(family_line
);
1715 tor_free(onion_pkey
);
1716 tor_free(identity_pkey
);
1719 log_warn(LD_BUG
,"descriptor snprintf #1 ran out of room!");
1722 /* From now on, we use 'written' to remember the current length of 's'. */
1725 if (options
->ContactInfo
&& strlen(options
->ContactInfo
)) {
1726 const char *ci
= options
->ContactInfo
;
1727 if (strchr(ci
, '\n') || strchr(ci
, '\r'))
1729 result
= tor_snprintf(s
+written
,maxlen
-written
, "contact %s\n", ci
);
1731 log_warn(LD_BUG
,"descriptor snprintf #2 ran out of room!");
1737 /* Write the exit policy to the end of 's'. */
1738 if (dns_seems_to_be_broken() || has_dns_init_failed() ||
1739 !router
->exit_policy
|| !smartlist_len(router
->exit_policy
)) {
1740 /* DNS is screwed up; don't claim to be an exit. */
1741 strlcat(s
+written
, "reject *:*\n", maxlen
-written
);
1742 written
+= strlen("reject *:*\n");
1744 } else if (router
->exit_policy
) {
1746 for (i
= 0; i
< smartlist_len(router
->exit_policy
); ++i
) {
1747 tmpe
= smartlist_get(router
->exit_policy
, i
);
1748 result
= policy_write_item(s
+written
, maxlen
-written
, tmpe
, 1);
1750 log_warn(LD_BUG
,"descriptor policy_write_item ran out of room!");
1753 tor_assert(result
== (int)strlen(s
+written
));
1755 if (written
+2 > maxlen
) {
1756 log_warn(LD_BUG
,"descriptor policy_write_item ran out of room (2)!");
1759 s
[written
++] = '\n';
1763 if (written
+256 > maxlen
) { /* Not enough room for signature. */
1764 log_warn(LD_BUG
,"not enough room left in descriptor for signature!");
1768 /* Sign the descriptor */
1769 strlcpy(s
+written
, "router-signature\n", maxlen
-written
);
1770 written
+= strlen(s
+written
);
1772 if (router_get_router_hash(s
, strlen(s
), digest
) < 0) {
1776 note_crypto_pk_op(SIGN_RTR
);
1777 if (router_append_dirobj_signature(s
+written
,maxlen
-written
,
1778 digest
,DIGEST_LEN
,ident_key
)<0) {
1779 log_warn(LD_BUG
, "Couldn't sign router descriptor");
1782 written
+= strlen(s
+written
);
1784 if (written
+2 > maxlen
) {
1785 log_warn(LD_BUG
,"Not enough room to finish descriptor.");
1788 /* include a last '\n' */
1792 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1796 routerinfo_t
*ri_tmp
;
1797 cp
= s_dup
= tor_strdup(s
);
1798 ri_tmp
= router_parse_entry_from_string(cp
, NULL
, 1, 0, NULL
);
1801 "We just generated a router descriptor we can't parse.");
1802 log_err(LD_BUG
, "Descriptor was: <<%s>>", s
);
1806 routerinfo_free(ri_tmp
);
1810 return (int)written
+1;
1813 /** Load the contents of <b>filename</b>, find the last line starting with
1814 * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
1815 * the past or more than 1 hour in the future with respect to <b>now</b>,
1816 * and write the file contents starting with that line to *<b>out</b>.
1817 * Return 1 for success, 0 if the file does not exist, or -1 if the file
1818 * does not contain a line matching these criteria or other failure. */
1820 load_stats_file(const char *filename
, const char *end_line
, time_t now
,
1824 char *fname
= get_datadir_fname(filename
);
1825 char *contents
, *start
= NULL
, *tmp
, timestr
[ISO_TIME_LEN
+1];
1827 switch (file_status(fname
)) {
1829 /* X022 Find an alternative to reading the whole file to memory. */
1830 if ((contents
= read_file_to_str(fname
, 0, NULL
))) {
1831 tmp
= strstr(contents
, end_line
);
1832 /* Find last block starting with end_line */
1835 tmp
= strstr(tmp
+ 1, end_line
);
1839 if (strlen(start
) < strlen(end_line
) + 1 + sizeof(timestr
))
1841 strlcpy(timestr
, start
+ 1 + strlen(end_line
), sizeof(timestr
));
1842 if (parse_iso_time(timestr
, &written
) < 0)
1844 if (written
< now
- (25*60*60) || written
> now
+ (1*60*60))
1846 *out
= tor_strdup(start
);
1864 /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
1865 * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
1866 * negative on failure. */
1868 extrainfo_dump_to_string(char *s
, size_t maxlen
, extrainfo_t
*extrainfo
,
1869 crypto_pk_env_t
*ident_key
)
1871 or_options_t
*options
= get_options();
1872 char identity
[HEX_DIGEST_LEN
+1];
1873 char published
[ISO_TIME_LEN
+1];
1874 char digest
[DIGEST_LEN
];
1875 char *bandwidth_usage
;
1878 static int write_stats_to_extrainfo
= 1;
1879 time_t now
= time(NULL
);
1881 base16_encode(identity
, sizeof(identity
),
1882 extrainfo
->cache_info
.identity_digest
, DIGEST_LEN
);
1883 format_iso_time(published
, extrainfo
->cache_info
.published_on
);
1884 bandwidth_usage
= rep_hist_get_bandwidth_lines(1);
1886 result
= tor_snprintf(s
, maxlen
,
1887 "extra-info %s %s\n"
1889 extrainfo
->nickname
, identity
,
1890 published
, bandwidth_usage
);
1892 tor_free(bandwidth_usage
);
1896 if (options
->ExtraInfoStatistics
&& write_stats_to_extrainfo
) {
1897 char *contents
= NULL
;
1898 log_info(LD_GENERAL
, "Adding stats to extra-info descriptor.");
1899 if (options
->DirReqStatistics
&&
1900 load_stats_file("stats"PATH_SEPARATOR
"dirreq-stats",
1901 "dirreq-stats-end", now
, &contents
) > 0) {
1902 size_t pos
= strlen(s
);
1903 if (strlcpy(s
+ pos
, contents
, maxlen
- strlen(s
)) !=
1905 log_warn(LD_DIR
, "Could not write dirreq-stats to extra-info "
1908 write_stats_to_extrainfo
= 0;
1912 if (options
->EntryStatistics
&&
1913 load_stats_file("stats"PATH_SEPARATOR
"entry-stats",
1914 "entry-stats-end", now
, &contents
) > 0) {
1915 size_t pos
= strlen(s
);
1916 if (strlcpy(s
+ pos
, contents
, maxlen
- strlen(s
)) !=
1918 log_warn(LD_DIR
, "Could not write entry-stats to extra-info "
1921 write_stats_to_extrainfo
= 0;
1925 if (options
->CellStatistics
&&
1926 load_stats_file("stats"PATH_SEPARATOR
"buffer-stats",
1927 "cell-stats-end", now
, &contents
) > 0) {
1928 size_t pos
= strlen(s
);
1929 if (strlcpy(s
+ pos
, contents
, maxlen
- strlen(s
)) !=
1931 log_warn(LD_DIR
, "Could not write buffer-stats to extra-info "
1934 write_stats_to_extrainfo
= 0;
1938 if (options
->ExitPortStatistics
&&
1939 load_stats_file("stats"PATH_SEPARATOR
"exit-stats",
1940 "exit-stats-end", now
, &contents
) > 0) {
1941 size_t pos
= strlen(s
);
1942 if (strlcpy(s
+ pos
, contents
, maxlen
- strlen(s
)) !=
1944 log_warn(LD_DIR
, "Could not write exit-stats to extra-info "
1947 write_stats_to_extrainfo
= 0;
1953 if (should_record_bridge_info(options
) && write_stats_to_extrainfo
) {
1954 const char *bridge_stats
= geoip_get_bridge_stats_extrainfo(now
);
1956 size_t pos
= strlen(s
);
1957 if (strlcpy(s
+ pos
, bridge_stats
, maxlen
- strlen(s
)) !=
1958 strlen(bridge_stats
)) {
1959 log_warn(LD_DIR
, "Could not write bridge-stats to extra-info "
1962 write_stats_to_extrainfo
= 0;
1968 strlcat(s
+len
, "router-signature\n", maxlen
-len
);
1969 len
+= strlen(s
+len
);
1970 if (router_get_extrainfo_hash(s
, digest
)<0)
1972 if (router_append_dirobj_signature(s
+len
, maxlen
-len
, digest
, DIGEST_LEN
,
1978 extrainfo_t
*ei_tmp
;
1979 cp
= s_dup
= tor_strdup(s
);
1980 ei_tmp
= extrainfo_parse_entry_from_string(cp
, NULL
, 1, NULL
);
1983 "We just generated an extrainfo descriptor we can't parse.");
1984 log_err(LD_BUG
, "Descriptor was: <<%s>>", s
);
1989 extrainfo_free(ei_tmp
);
1992 if (options
->ExtraInfoStatistics
&& write_stats_to_extrainfo
) {
1994 extrainfo_t
*ei_tmp
;
1995 cp
= s_dup
= tor_strdup(s
);
1996 ei_tmp
= extrainfo_parse_entry_from_string(cp
, NULL
, 1, NULL
);
1998 log_warn(LD_GENERAL
,
1999 "We just generated an extra-info descriptor with "
2000 "statistics that we can't parse. Not adding statistics to "
2001 "this or any future extra-info descriptors. Descriptor "
2003 write_stats_to_extrainfo
= 0;
2004 extrainfo_dump_to_string(s
, maxlen
, extrainfo
, ident_key
);
2007 extrainfo_free(ei_tmp
);
2010 return (int)strlen(s
)+1;
2013 /** Return true iff <b>s</b> is a legally valid server nickname. */
2015 is_legal_nickname(const char *s
)
2020 return len
> 0 && len
<= MAX_NICKNAME_LEN
&&
2021 strspn(s
,LEGAL_NICKNAME_CHARACTERS
) == len
;
2024 /** Return true iff <b>s</b> is a legally valid server nickname or
2025 * hex-encoded identity-key digest. */
2027 is_legal_nickname_or_hexdigest(const char *s
)
2030 return is_legal_nickname(s
);
2032 return is_legal_hexdigest(s
);
2035 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
2038 is_legal_hexdigest(const char *s
)
2042 if (s
[0] == '$') s
++;
2044 if (len
> HEX_DIGEST_LEN
) {
2045 if (s
[HEX_DIGEST_LEN
] == '=' ||
2046 s
[HEX_DIGEST_LEN
] == '~') {
2047 if (!is_legal_nickname(s
+HEX_DIGEST_LEN
+1))
2053 return (len
>= HEX_DIGEST_LEN
&&
2054 strspn(s
,HEX_CHARACTERS
)==HEX_DIGEST_LEN
);
2057 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
2058 * verbose representation of the identity of <b>router</b>. The format is:
2060 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
2061 * A "=" if the router is named; a "~" if it is not.
2062 * The router's nickname.
2065 router_get_verbose_nickname(char *buf
, const routerinfo_t
*router
)
2068 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, router
->cache_info
.identity_digest
,
2070 buf
[1+HEX_DIGEST_LEN
] = router
->is_named
? '=' : '~';
2071 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, router
->nickname
, MAX_NICKNAME_LEN
+1);
2074 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
2075 * verbose representation of the identity of <b>router</b>. The format is:
2077 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
2078 * A "=" if the router is named; a "~" if it is not.
2079 * The router's nickname.
2082 routerstatus_get_verbose_nickname(char *buf
, const routerstatus_t
*router
)
2085 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, router
->identity_digest
,
2087 buf
[1+HEX_DIGEST_LEN
] = router
->is_named
? '=' : '~';
2088 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, router
->nickname
, MAX_NICKNAME_LEN
+1);
2091 /** Forget that we have issued any router-related warnings, so that we'll
2092 * warn again if we see the same errors. */
2094 router_reset_warnings(void)
2096 if (warned_nonexistent_family
) {
2097 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
2098 smartlist_clear(warned_nonexistent_family
);
2102 /** Given a router purpose, convert it to a string. Don't call this on
2103 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
2104 * know its string representation. */
2106 router_purpose_to_string(uint8_t p
)
2110 case ROUTER_PURPOSE_GENERAL
: return "general";
2111 case ROUTER_PURPOSE_BRIDGE
: return "bridge";
2112 case ROUTER_PURPOSE_CONTROLLER
: return "controller";
2119 /** Given a string, convert it to a router purpose. */
2121 router_purpose_from_string(const char *s
)
2123 if (!strcmp(s
, "general"))
2124 return ROUTER_PURPOSE_GENERAL
;
2125 else if (!strcmp(s
, "bridge"))
2126 return ROUTER_PURPOSE_BRIDGE
;
2127 else if (!strcmp(s
, "controller"))
2128 return ROUTER_PURPOSE_CONTROLLER
;
2130 return ROUTER_PURPOSE_UNKNOWN
;
2133 /** Release all static resources held in router.c */
2135 router_free_all(void)
2137 crypto_free_pk_env(onionkey
);
2138 crypto_free_pk_env(lastonionkey
);
2139 crypto_free_pk_env(identitykey
);
2140 tor_mutex_free(key_lock
);
2141 routerinfo_free(desc_routerinfo
);
2142 extrainfo_free(desc_extrainfo
);
2143 crypto_free_pk_env(authority_signing_key
);
2144 authority_cert_free(authority_key_certificate
);
2145 crypto_free_pk_env(legacy_signing_key
);
2146 authority_cert_free(legacy_key_certificate
);
2148 if (warned_nonexistent_family
) {
2149 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
2150 smartlist_free(warned_nonexistent_family
);