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-2009, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
13 * \brief OR functionality, including key maintenance, generating
14 * and uploading server descriptors, retrying OR connections.
17 extern long stats_n_seconds_working
;
19 /************************************************************/
22 * Key management: ORs only.
25 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
27 static tor_mutex_t
*key_lock
=NULL
;
28 static time_t onionkey_set_at
=0; /**< When was onionkey last changed? */
29 /** Current private onionskin decryption key: used to decode CREATE cells. */
30 static crypto_pk_env_t
*onionkey
=NULL
;
31 /** Previous private onionskin decryption key: used to decode CREATE cells
32 * generated by clients that have an older version of our descriptor. */
33 static crypto_pk_env_t
*lastonionkey
=NULL
;
34 /** Private "identity key": used to sign directory info and TLS
35 * certificates. Never changes. */
36 static crypto_pk_env_t
*identitykey
=NULL
;
37 /** Digest of identitykey. */
38 static char identitykey_digest
[DIGEST_LEN
];
39 /** Signing key used for v3 directory material; only set for authorities. */
40 static crypto_pk_env_t
*authority_signing_key
= NULL
;
41 /** Key certificate to authenticate v3 directory material; only set for
43 static authority_cert_t
*authority_key_certificate
= NULL
;
45 /** For emergency V3 authority key migration: An extra signing key that we use
46 * with our old (obsolete) identity key for a while. */
47 static crypto_pk_env_t
*legacy_signing_key
= NULL
;
48 /** For emergency V3 authority key migration: An extra certificate to
49 * authenticate legacy_signing_key with our obsolete identity key.*/
50 static authority_cert_t
*legacy_key_certificate
= NULL
;
52 /* (Note that v3 authorities also have a separate "authority identity key",
53 * but this key is never actually loaded by the Tor process. Instead, it's
54 * used by tor-gencert to sign new signing keys and make new key
57 /** Replace the current onion key with <b>k</b>. Does not affect
58 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
61 set_onion_key(crypto_pk_env_t
*k
)
63 tor_mutex_acquire(key_lock
);
64 crypto_free_pk_env(onionkey
);
66 onionkey_set_at
= time(NULL
);
67 tor_mutex_release(key_lock
);
68 mark_my_descriptor_dirty();
71 /** Return the current onion key. Requires that the onion key has been
72 * loaded or generated. */
80 /** Store a full copy of the current onion key into *<b>key</b>, and a full
81 * copy of the most recent onion key into *<b>last</b>.
84 dup_onion_keys(crypto_pk_env_t
**key
, crypto_pk_env_t
**last
)
88 tor_mutex_acquire(key_lock
);
90 *key
= crypto_pk_copy_full(onionkey
);
92 *last
= crypto_pk_copy_full(lastonionkey
);
95 tor_mutex_release(key_lock
);
98 /** Return the time when the onion key was last set. This is either the time
99 * when the process launched, or the time of the most recent key rotation since
100 * the process launched.
103 get_onion_key_set_at(void)
105 return onionkey_set_at
;
108 /** Set the current identity key to k.
111 set_identity_key(crypto_pk_env_t
*k
)
113 crypto_free_pk_env(identitykey
);
115 crypto_pk_get_digest(identitykey
, identitykey_digest
);
118 /** Returns the current identity key; requires that the identity key has been
122 get_identity_key(void)
124 tor_assert(identitykey
);
128 /** Return true iff the identity key has been set. */
130 identity_key_is_set(void)
132 return identitykey
!= NULL
;
135 /** Return the key certificate for this v3 (voting) authority, or NULL
136 * if we have no such certificate. */
138 get_my_v3_authority_cert(void)
140 return authority_key_certificate
;
143 /** Return the v3 signing key for this v3 (voting) authority, or NULL
144 * if we have no such key. */
146 get_my_v3_authority_signing_key(void)
148 return authority_signing_key
;
151 /** If we're an authority, and we're using a legacy authority identity key for
152 * emergency migration purposes, return the certificate associated with that
155 get_my_v3_legacy_cert(void)
157 return legacy_key_certificate
;
160 /** If we're an authority, and we're using a legacy authority identity key for
161 * emergency migration purposes, return that key. */
163 get_my_v3_legacy_signing_key(void)
165 return legacy_signing_key
;
168 /** Replace the previous onion key with the current onion key, and generate
169 * a new previous onion key. Immediately after calling this function,
171 * - schedule all previous cpuworkers to shut down _after_ processing
172 * pending work. (This will cause fresh cpuworkers to be generated.)
173 * - generate and upload a fresh routerinfo.
176 rotate_onion_key(void)
178 char *fname
, *fname_prev
;
179 crypto_pk_env_t
*prkey
;
180 or_state_t
*state
= get_or_state();
182 fname
= get_datadir_fname2("keys", "secret_onion_key");
183 fname_prev
= get_datadir_fname2("keys", "secret_onion_key.old");
184 if (!(prkey
= crypto_new_pk_env())) {
185 log_err(LD_GENERAL
,"Error constructing rotated onion key");
188 if (crypto_pk_generate_key(prkey
)) {
189 log_err(LD_BUG
,"Error generating onion key");
192 if (file_status(fname
) == FN_FILE
) {
193 if (replace_file(fname
, fname_prev
))
196 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
197 log_err(LD_FS
,"Couldn't write generated onion key to \"%s\".", fname
);
200 log_info(LD_GENERAL
, "Rotating onion key");
201 tor_mutex_acquire(key_lock
);
202 crypto_free_pk_env(lastonionkey
);
203 lastonionkey
= onionkey
;
206 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
207 tor_mutex_release(key_lock
);
208 mark_my_descriptor_dirty();
209 or_state_mark_dirty(state
, get_options()->AvoidDiskWrites
? now
+3600 : 0);
212 log_warn(LD_GENERAL
, "Couldn't rotate onion key.");
214 crypto_free_pk_env(prkey
);
217 tor_free(fname_prev
);
220 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
221 * and <b>generate</b> is true, create a new RSA key and save it in
222 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
223 * errors at level <b>severity</b>.
226 init_key_from_file(const char *fname
, int generate
, int severity
)
228 crypto_pk_env_t
*prkey
= NULL
;
230 if (!(prkey
= crypto_new_pk_env())) {
231 log(severity
, LD_GENERAL
,"Error constructing key");
235 switch (file_status(fname
)) {
238 log(severity
, LD_FS
,"Can't read key from \"%s\"", fname
);
242 if (!have_lockfile()) {
243 if (try_locking(get_options(), 0)<0) {
244 /* Make sure that --list-fingerprint only creates new keys
245 * if there is no possibility for a deadlock. */
246 log(severity
, LD_FS
, "Another Tor process has locked \"%s\". Not "
247 "writing any new keys.", fname
);
248 /*XXXX The 'other process' might make a key in a second or two;
249 * maybe we should wait for it. */
253 log_info(LD_GENERAL
, "No key found in \"%s\"; generating fresh key.",
255 if (crypto_pk_generate_key(prkey
)) {
256 log(severity
, LD_GENERAL
,"Error generating onion key");
259 if (crypto_pk_check_key(prkey
) <= 0) {
260 log(severity
, LD_GENERAL
,"Generated key seems invalid");
263 log_info(LD_GENERAL
, "Generated key seems valid");
264 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
266 "Couldn't write generated key to \"%s\".", fname
);
270 log_info(LD_GENERAL
, "No key found in \"%s\"", fname
);
274 if (crypto_pk_read_private_key_from_filename(prkey
, fname
)) {
275 log(severity
, LD_GENERAL
,"Error loading private key.");
285 crypto_free_pk_env(prkey
);
289 /** Try to load the vote-signing private key and certificate for being a v3
290 * directory authority, and make sure they match. If <b>legacy</b>, load a
291 * legacy key/cert set for emergency key migration; otherwise load the regular
292 * key/cert set. On success, store them into *<b>key_out</b> and
293 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
295 load_authority_keyset(int legacy
, crypto_pk_env_t
**key_out
,
296 authority_cert_t
**cert_out
)
299 char *fname
= NULL
, *cert
= NULL
;
300 const char *eos
= NULL
;
301 crypto_pk_env_t
*signing_key
= NULL
;
302 authority_cert_t
*parsed
= NULL
;
304 fname
= get_datadir_fname2("keys",
305 legacy
? "legacy_signing_key" : "authority_signing_key");
306 signing_key
= init_key_from_file(fname
, 0, LOG_INFO
);
308 log_warn(LD_DIR
, "No version 3 directory key found in %s", fname
);
312 fname
= get_datadir_fname2("keys",
313 legacy
? "legacy_certificate" : "authority_certificate");
314 cert
= read_file_to_str(fname
, 0, NULL
);
316 log_warn(LD_DIR
, "Signing key found, but no certificate found in %s",
320 parsed
= authority_cert_parse_from_string(cert
, &eos
);
322 log_warn(LD_DIR
, "Unable to parse certificate in %s", fname
);
325 if (crypto_pk_cmp_keys(signing_key
, parsed
->signing_key
) != 0) {
326 log_warn(LD_DIR
, "Stored signing key does not match signing key in "
331 crypto_free_pk_env(*key_out
);
332 authority_cert_free(*cert_out
);
334 *key_out
= signing_key
;
343 crypto_free_pk_env(signing_key
);
344 authority_cert_free(parsed
);
348 /** Load the v3 (voting) authority signing key and certificate, if they are
349 * present. Return -1 if anything is missing, mismatched, or unloadable;
350 * return 0 on success. */
352 init_v3_authority_keys(void)
354 if (load_authority_keyset(0, &authority_signing_key
,
355 &authority_key_certificate
)<0)
358 if (get_options()->V3AuthUseLegacyKey
&&
359 load_authority_keyset(1, &legacy_signing_key
,
360 &legacy_key_certificate
)<0)
366 /** If we're a v3 authority, check whether we have a certificate that's
367 * likely to expire soon. Warn if we do, but not too often. */
369 v3_authority_check_key_expiry(void)
372 static time_t last_warned
= 0;
373 int badness
, time_left
, warn_interval
;
374 if (!authdir_mode_v3(get_options()) || !authority_key_certificate
)
378 expires
= authority_key_certificate
->expires
;
379 time_left
= (int)( expires
- now
);
380 if (time_left
<= 0) {
382 warn_interval
= 60*60;
383 } else if (time_left
<= 24*60*60) {
385 warn_interval
= 60*60;
386 } else if (time_left
<= 24*60*60*7) {
388 warn_interval
= 24*60*60;
389 } else if (time_left
<= 24*60*60*30) {
391 warn_interval
= 24*60*60*5;
396 if (last_warned
+ warn_interval
> now
)
399 if (time_left
<= 0) {
400 log(badness
, LD_DIR
, "Your v3 authority certificate has expired."
401 " Generate a new one NOW.");
402 } else if (time_left
<= 24*60*60) {
403 log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d hours;"
404 " Generate a new one NOW.", time_left
/(60*60));
406 log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d days;"
407 " Generate a new one soon.", time_left
/(24*60*60));
412 /** Initialize all OR private keys, and the TLS context, as necessary.
413 * On OPs, this only initializes the tls context. Return 0 on success,
414 * or -1 if Tor should die.
420 char fingerprint
[FINGERPRINT_LEN
+1];
421 /*nickname<space>fp\n\0 */
422 char fingerprint_line
[MAX_NICKNAME_LEN
+FINGERPRINT_LEN
+3];
424 crypto_pk_env_t
*prkey
;
428 or_options_t
*options
= get_options();
429 authority_type_t type
;
430 time_t now
= time(NULL
);
431 trusted_dir_server_t
*ds
;
432 int v3_digest_set
= 0;
433 authority_cert_t
*cert
= NULL
;
436 key_lock
= tor_mutex_new();
438 /* There are a couple of paths that put us here before */
439 if (crypto_global_init(get_options()->HardwareAccel
,
440 get_options()->AccelName
,
441 get_options()->AccelDir
)) {
442 log_err(LD_BUG
, "Unable to initialize OpenSSL. Exiting.");
446 /* OP's don't need persistent keys; just make up an identity and
447 * initialize the TLS context. */
448 if (!server_mode(options
)) {
449 if (!(prkey
= crypto_new_pk_env()))
451 if (crypto_pk_generate_key(prkey
)) {
452 crypto_free_pk_env(prkey
);
455 set_identity_key(prkey
);
456 /* Create a TLS context; default the client nickname to "client". */
457 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME
) < 0) {
458 log_err(LD_GENERAL
,"Error creating TLS context for Tor client.");
463 /* Make sure DataDirectory exists, and is private. */
464 if (check_private_dir(options
->DataDirectory
, CPD_CREATE
)) {
467 /* Check the key directory. */
468 keydir
= get_datadir_fname("keys");
469 if (check_private_dir(keydir
, CPD_CREATE
)) {
475 /* 1a. Read v3 directory authority key/cert information. */
476 memset(v3_digest
, 0, sizeof(v3_digest
));
477 if (authdir_mode_v3(options
)) {
478 if (init_v3_authority_keys()<0) {
479 log_err(LD_GENERAL
, "We're configured as a V3 authority, but we "
480 "were unable to load our v3 authority keys and certificate! "
481 "Use tor-gencert to generate them. Dying.");
484 cert
= get_my_v3_authority_cert();
486 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key
,
492 /* 1. Read identity key. Make it if none is found. */
493 keydir
= get_datadir_fname2("keys", "secret_id_key");
494 log_info(LD_GENERAL
,"Reading/making identity key \"%s\"...",keydir
);
495 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
497 if (!prkey
) return -1;
498 set_identity_key(prkey
);
500 /* 2. Read onion key. Make it if none is found. */
501 keydir
= get_datadir_fname2("keys", "secret_onion_key");
502 log_info(LD_GENERAL
,"Reading/making onion key \"%s\"...",keydir
);
503 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
505 if (!prkey
) return -1;
506 set_onion_key(prkey
);
507 if (options
->command
== CMD_RUN_TOR
) {
508 /* only mess with the state file if we're actually running Tor */
509 or_state_t
*state
= get_or_state();
510 if (state
->LastRotatedOnionKey
> 100 && state
->LastRotatedOnionKey
< now
) {
511 /* We allow for some parsing slop, but we don't want to risk accepting
512 * values in the distant future. If we did, we might never rotate the
514 onionkey_set_at
= state
->LastRotatedOnionKey
;
516 /* We have no LastRotatedOnionKey set; either we just created the key
517 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
518 * start the clock ticking now so that we will eventually rotate it even
519 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
520 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
521 or_state_mark_dirty(state
, options
->AvoidDiskWrites
?
522 time(NULL
)+3600 : 0);
526 keydir
= get_datadir_fname2("keys", "secret_onion_key.old");
527 if (!lastonionkey
&& file_status(keydir
) == FN_FILE
) {
528 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
530 lastonionkey
= prkey
;
534 /* 3. Initialize link key and TLS context. */
535 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME
) < 0) {
536 log_err(LD_GENERAL
,"Error initializing TLS context");
539 /* 4. Build our router descriptor. */
540 /* Must be called after keys are initialized. */
541 mydesc
= router_get_my_descriptor();
542 if (authdir_mode(options
)) {
543 const char *m
= NULL
;
545 /* We need to add our own fingerprint so it gets recognized. */
546 if (dirserv_add_own_fingerprint(options
->Nickname
, get_identity_key())) {
547 log_err(LD_GENERAL
,"Error adding own fingerprint to approved set");
551 ri
= router_parse_entry_from_string(mydesc
, NULL
, 1, 0, NULL
);
553 log_err(LD_GENERAL
,"Generated a routerinfo we couldn't parse.");
556 if (!WRA_WAS_ADDED(dirserv_add_descriptor(ri
, &m
, "self"))) {
557 log_err(LD_GENERAL
,"Unable to add own descriptor to directory: %s",
558 m
?m
:"<unknown error>");
564 /* 5. Dump fingerprint to 'fingerprint' */
565 keydir
= get_datadir_fname("fingerprint");
566 log_info(LD_GENERAL
,"Dumping fingerprint to \"%s\"...",keydir
);
567 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint
, 0)<0) {
568 log_err(LD_GENERAL
,"Error computing fingerprint");
572 tor_assert(strlen(options
->Nickname
) <= MAX_NICKNAME_LEN
);
573 if (tor_snprintf(fingerprint_line
, sizeof(fingerprint_line
),
574 "%s %s\n",options
->Nickname
, fingerprint
) < 0) {
575 log_err(LD_GENERAL
,"Error writing fingerprint line");
579 /* Check whether we need to write the fingerprint file. */
581 if (file_status(keydir
) == FN_FILE
)
582 cp
= read_file_to_str(keydir
, 0, NULL
);
583 if (!cp
|| strcmp(cp
, fingerprint_line
)) {
584 if (write_str_to_file(keydir
, fingerprint_line
, 0)) {
585 log_err(LD_FS
, "Error writing fingerprint line to file");
594 log(LOG_NOTICE
, LD_GENERAL
,
595 "Your Tor server's identity key fingerprint is '%s %s'",
596 options
->Nickname
, fingerprint
);
597 if (!authdir_mode(options
))
599 /* 6. [authdirserver only] load approved-routers file */
600 if (dirserv_load_fingerprint_file() < 0) {
601 log_err(LD_GENERAL
,"Error loading fingerprints");
604 /* 6b. [authdirserver only] add own key to approved directories. */
605 crypto_pk_get_digest(get_identity_key(), digest
);
606 type
= ((options
->V1AuthoritativeDir
? V1_AUTHORITY
: NO_AUTHORITY
) |
607 (options
->V2AuthoritativeDir
? V2_AUTHORITY
: NO_AUTHORITY
) |
608 (options
->V3AuthoritativeDir
? V3_AUTHORITY
: NO_AUTHORITY
) |
609 (options
->BridgeAuthoritativeDir
? BRIDGE_AUTHORITY
: NO_AUTHORITY
) |
610 (options
->HSAuthoritativeDir
? HIDSERV_AUTHORITY
: NO_AUTHORITY
));
612 ds
= router_get_trusteddirserver_by_digest(digest
);
614 ds
= add_trusted_dir_server(options
->Nickname
, NULL
,
615 (uint16_t)options
->DirPort
,
616 (uint16_t)options
->ORPort
,
621 log_err(LD_GENERAL
,"We want to be a directory authority, but we "
622 "couldn't add ourselves to the authority list. Failing.");
626 if (ds
->type
!= type
) {
627 log_warn(LD_DIR
, "Configured authority type does not match authority "
628 "type in DirServer list. Adjusting. (%d v %d)",
632 if (v3_digest_set
&& (ds
->type
& V3_AUTHORITY
) &&
633 memcmp(v3_digest
, ds
->v3_identity_digest
, DIGEST_LEN
)) {
634 log_warn(LD_DIR
, "V3 identity key does not match identity declared in "
635 "DirServer line. Adjusting.");
636 memcpy(ds
->v3_identity_digest
, v3_digest
, DIGEST_LEN
);
639 if (cert
) { /* add my own cert to the list of known certs */
640 log_info(LD_DIR
, "adding my own v3 cert");
641 if (trusted_dirs_load_certs_from_string(
642 cert
->cache_info
.signed_descriptor_body
, 0, 0)<0) {
643 log_warn(LD_DIR
, "Unable to parse my own v3 cert! Failing.");
648 return 0; /* success */
651 /* Keep track of whether we should upload our server descriptor,
652 * and what type of server we are.
655 /** Whether we can reach our ORPort from the outside. */
656 static int can_reach_or_port
= 0;
657 /** Whether we can reach our DirPort from the outside. */
658 static int can_reach_dir_port
= 0;
660 /** Forget what we have learned about our reachability status. */
662 router_reset_reachability(void)
664 can_reach_or_port
= can_reach_dir_port
= 0;
667 /** Return 1 if ORPort is known reachable; else return 0. */
669 check_whether_orport_reachable(void)
671 or_options_t
*options
= get_options();
672 return options
->AssumeReachable
||
676 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
678 check_whether_dirport_reachable(void)
680 or_options_t
*options
= get_options();
681 return !options
->DirPort
||
682 options
->AssumeReachable
||
683 we_are_hibernating() ||
687 /** Look at a variety of factors, and return 0 if we don't want to
688 * advertise the fact that we have a DirPort open. Else return the
689 * DirPort we want to advertise.
691 * Log a helpful message if we change our mind about whether to publish
695 decide_to_advertise_dirport(or_options_t
*options
, uint16_t dir_port
)
697 static int advertising
=1; /* start out assuming we will advertise */
699 const char *reason
= NULL
;
701 /* Section one: reasons to publish or not publish that aren't
702 * worth mentioning to the user, either because they're obvious
703 * or because they're normal behavior. */
705 if (!dir_port
) /* short circuit the rest of the function */
707 if (authdir_mode(options
)) /* always publish */
709 if (we_are_hibernating())
711 if (!check_whether_dirport_reachable())
714 /* Section two: reasons to publish or not publish that the user
715 * might find surprising. These are generally config options that
716 * make us choose not to publish. */
718 if (accounting_is_enabled(options
)) {
719 /* if we might potentially hibernate */
721 reason
= "AccountingMax enabled";
722 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
723 } else if (options
->BandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
||
724 (options
->RelayBandwidthRate
> 0 &&
725 options
->RelayBandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
)) {
726 /* if we're advertising a small amount */
728 reason
= "BandwidthRate under 50KB";
731 if (advertising
!= new_choice
) {
732 if (new_choice
== 1) {
733 log(LOG_NOTICE
, LD_DIR
, "Advertising DirPort as %d", dir_port
);
736 log(LOG_NOTICE
, LD_DIR
, "Not advertising DirPort (Reason: %s)", reason
);
738 advertising
= new_choice
;
741 return advertising
? dir_port
: 0;
744 /** Some time has passed, or we just got new directory information.
745 * See if we currently believe our ORPort or DirPort to be
746 * unreachable. If so, launch a new test for it.
748 * For ORPort, we simply try making a circuit that ends at ourselves.
749 * Success is noticed in onionskin_answer().
751 * For DirPort, we make a connection via Tor to our DirPort and ask
752 * for our own server descriptor.
753 * Success is noticed in connection_dir_client_reached_eof().
756 consider_testing_reachability(int test_or
, int test_dir
)
758 routerinfo_t
*me
= router_get_my_routerinfo();
759 int orport_reachable
= check_whether_orport_reachable();
764 if (test_or
&& (!orport_reachable
|| !circuit_enough_testing_circs())) {
765 log_info(LD_CIRC
, "Testing %s of my ORPort: %s:%d.",
766 !orport_reachable
? "reachability" : "bandwidth",
767 me
->address
, me
->or_port
);
768 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING
, me
,
769 CIRCLAUNCH_NEED_CAPACITY
|CIRCLAUNCH_IS_INTERNAL
);
772 tor_addr_from_ipv4h(&addr
, me
->addr
);
773 if (test_dir
&& !check_whether_dirport_reachable() &&
774 !connection_get_by_type_addr_port_purpose(
775 CONN_TYPE_DIR
, &addr
, me
->dir_port
,
776 DIR_PURPOSE_FETCH_SERVERDESC
)) {
777 /* ask myself, via tor, for my server descriptor. */
778 directory_initiate_command(me
->address
, &addr
,
779 me
->or_port
, me
->dir_port
,
780 0, /* does not matter */
781 0, me
->cache_info
.identity_digest
,
782 DIR_PURPOSE_FETCH_SERVERDESC
,
783 ROUTER_PURPOSE_GENERAL
,
784 1, "authority.z", NULL
, 0, 0);
788 /** Annotate that we found our ORPort reachable. */
790 router_orport_found_reachable(void)
792 if (!can_reach_or_port
) {
793 routerinfo_t
*me
= router_get_my_routerinfo();
794 log_notice(LD_OR
,"Self-testing indicates your ORPort is reachable from "
795 "the outside. Excellent.%s",
796 get_options()->_PublishServerDescriptor
!= NO_AUTHORITY
?
797 " Publishing server descriptor." : "");
798 can_reach_or_port
= 1;
799 mark_my_descriptor_dirty();
800 if (!me
) { /* should never happen */
801 log_warn(LD_BUG
, "ORPort found reachable, but I have no routerinfo "
802 "yet. Failing to inform controller of success.");
805 control_event_server_status(LOG_NOTICE
,
806 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
807 me
->address
, me
->or_port
);
811 /** Annotate that we found our DirPort reachable. */
813 router_dirport_found_reachable(void)
815 if (!can_reach_dir_port
) {
816 routerinfo_t
*me
= router_get_my_routerinfo();
817 log_notice(LD_DIRSERV
,"Self-testing indicates your DirPort is reachable "
818 "from the outside. Excellent.");
819 can_reach_dir_port
= 1;
820 if (!me
|| decide_to_advertise_dirport(get_options(), me
->dir_port
))
821 mark_my_descriptor_dirty();
822 if (!me
) { /* should never happen */
823 log_warn(LD_BUG
, "DirPort found reachable, but I have no routerinfo "
824 "yet. Failing to inform controller of success.");
827 control_event_server_status(LOG_NOTICE
,
828 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
829 me
->address
, me
->dir_port
);
833 /** We have enough testing circuits open. Send a bunch of "drop"
834 * cells down each of them, to exercise our bandwidth. */
836 router_perform_bandwidth_test(int num_circs
, time_t now
)
838 int num_cells
= (int)(get_options()->BandwidthRate
* 10 / CELL_NETWORK_SIZE
);
839 int max_cells
= num_cells
< CIRCWINDOW_START
?
840 num_cells
: CIRCWINDOW_START
;
841 int cells_per_circuit
= max_cells
/ num_circs
;
842 origin_circuit_t
*circ
= NULL
;
844 log_notice(LD_OR
,"Performing bandwidth self-test...done.");
845 while ((circ
= circuit_get_next_by_pk_and_purpose(circ
, NULL
,
846 CIRCUIT_PURPOSE_TESTING
))) {
847 /* dump cells_per_circuit drop cells onto this circ */
848 int i
= cells_per_circuit
;
849 if (circ
->_base
.state
!= CIRCUIT_STATE_OPEN
)
851 circ
->_base
.timestamp_dirty
= now
;
853 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
855 NULL
, 0, circ
->cpath
->prev
)<0) {
856 return; /* stop if error */
862 /** Return true iff we believe ourselves to be an authoritative
866 authdir_mode(or_options_t
*options
)
868 return options
->AuthoritativeDir
!= 0;
870 /** Return true iff we believe ourselves to be a v1 authoritative
874 authdir_mode_v1(or_options_t
*options
)
876 return authdir_mode(options
) && options
->V1AuthoritativeDir
!= 0;
878 /** Return true iff we believe ourselves to be a v2 authoritative
882 authdir_mode_v2(or_options_t
*options
)
884 return authdir_mode(options
) && options
->V2AuthoritativeDir
!= 0;
886 /** Return true iff we believe ourselves to be a v3 authoritative
890 authdir_mode_v3(or_options_t
*options
)
892 return authdir_mode(options
) && options
->V3AuthoritativeDir
!= 0;
894 /** Return true iff we are a v1, v2, or v3 directory authority. */
896 authdir_mode_any_main(or_options_t
*options
)
898 return options
->V1AuthoritativeDir
||
899 options
->V2AuthoritativeDir
||
900 options
->V3AuthoritativeDir
;
902 /** Return true if we believe ourselves to be any kind of
903 * authoritative directory beyond just a hidserv authority. */
905 authdir_mode_any_nonhidserv(or_options_t
*options
)
907 return options
->BridgeAuthoritativeDir
||
908 authdir_mode_any_main(options
);
910 /** Return true iff we are an authoritative directory server that is
911 * authoritative about receiving and serving descriptors of type
912 * <b>purpose</b> its dirport. Use -1 for "any purpose". */
914 authdir_mode_handles_descs(or_options_t
*options
, int purpose
)
917 return authdir_mode_any_nonhidserv(options
);
918 else if (purpose
== ROUTER_PURPOSE_GENERAL
)
919 return authdir_mode_any_main(options
);
920 else if (purpose
== ROUTER_PURPOSE_BRIDGE
)
921 return (options
->BridgeAuthoritativeDir
);
925 /** Return true iff we are an authoritative directory server that
926 * publishes its own network statuses.
929 authdir_mode_publishes_statuses(or_options_t
*options
)
931 if (authdir_mode_bridge(options
))
933 return authdir_mode_any_nonhidserv(options
);
935 /** Return true iff we are an authoritative directory server that
936 * tests reachability of the descriptors it learns about.
939 authdir_mode_tests_reachability(or_options_t
*options
)
941 return authdir_mode_handles_descs(options
, -1);
943 /** Return true iff we believe ourselves to be a bridge authoritative
947 authdir_mode_bridge(or_options_t
*options
)
949 return authdir_mode(options
) && options
->BridgeAuthoritativeDir
!= 0;
951 /** Return true iff we once tried to stay connected to all ORs at once.
952 * FFFF this function, and the notion of staying connected to ORs, is
953 * nearly obsolete. One day there will be a proposal for getting rid of
957 clique_mode(or_options_t
*options
)
959 return authdir_mode_tests_reachability(options
);
962 /** Return true iff we are trying to be a server.
965 server_mode(or_options_t
*options
)
967 if (options
->ClientOnly
) return 0;
968 return (options
->ORPort
!= 0 || options
->ORListenAddress
);
971 /** Remember if we've advertised ourselves to the dirservers. */
972 static int server_is_advertised
=0;
974 /** Return true iff we have published our descriptor lately.
977 advertised_server_mode(void)
979 return server_is_advertised
;
983 * Called with a boolean: set whether we have recently published our
987 set_server_advertised(int s
)
989 server_is_advertised
= s
;
992 /** Return true iff we are trying to be a socks proxy. */
994 proxy_mode(or_options_t
*options
)
996 return (options
->SocksPort
!= 0 || options
->SocksListenAddress
||
997 options
->TransPort
!= 0 || options
->TransListenAddress
||
998 options
->NatdPort
!= 0 || options
->NatdListenAddress
||
999 options
->DNSPort
!= 0 || options
->DNSListenAddress
);
1002 /** Decide if we're a publishable server. We are a publishable server if:
1003 * - We don't have the ClientOnly option set
1005 * - We have the PublishServerDescriptor option set to non-empty
1007 * - We have ORPort set
1009 * - We believe we are reachable from the outside; or
1010 * - We are an authoritative directory server.
1013 decide_if_publishable_server(void)
1015 or_options_t
*options
= get_options();
1017 if (options
->ClientOnly
)
1019 if (options
->_PublishServerDescriptor
== NO_AUTHORITY
)
1021 if (!server_mode(options
))
1023 if (authdir_mode(options
))
1026 return check_whether_orport_reachable();
1029 /** Initiate server descriptor upload as reasonable (if server is publishable,
1030 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1032 * We need to rebuild the descriptor if it's dirty even if we're not
1033 * uploading, because our reachability testing *uses* our descriptor to
1034 * determine what IP address and ports to test.
1037 consider_publishable_server(int force
)
1041 if (!server_mode(get_options()))
1044 rebuilt
= router_rebuild_descriptor(0);
1045 if (decide_if_publishable_server()) {
1046 set_server_advertised(1);
1048 router_upload_dir_desc_to_dirservers(force
);
1050 set_server_advertised(0);
1055 * Clique maintenance -- to be phased out.
1058 /** Return true iff we believe this OR tries to keep connections open
1059 * to all other ORs. */
1061 router_is_clique_mode(routerinfo_t
*router
)
1063 if (router_digest_is_trusted_dir(router
->cache_info
.identity_digest
))
1069 * OR descriptor generation.
1072 /** My routerinfo. */
1073 static routerinfo_t
*desc_routerinfo
= NULL
;
1075 static extrainfo_t
*desc_extrainfo
= NULL
;
1076 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1078 static time_t desc_clean_since
= 0;
1079 /** Boolean: do we need to regenerate the above? */
1080 static int desc_needs_upload
= 0;
1082 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1083 * descriptor successfully yet, try to upload our signed descriptor to
1084 * all the directory servers we know about.
1087 router_upload_dir_desc_to_dirservers(int force
)
1092 size_t desc_len
, extra_len
= 0, total_len
;
1093 authority_type_t auth
= get_options()->_PublishServerDescriptor
;
1095 ri
= router_get_my_routerinfo();
1097 log_info(LD_GENERAL
, "No descriptor; skipping upload");
1100 ei
= router_get_my_extrainfo();
1101 if (auth
== NO_AUTHORITY
)
1103 if (!force
&& !desc_needs_upload
)
1105 desc_needs_upload
= 0;
1107 desc_len
= ri
->cache_info
.signed_descriptor_len
;
1108 extra_len
= ei
? ei
->cache_info
.signed_descriptor_len
: 0;
1109 total_len
= desc_len
+ extra_len
+ 1;
1110 msg
= tor_malloc(total_len
);
1111 memcpy(msg
, ri
->cache_info
.signed_descriptor_body
, desc_len
);
1113 memcpy(msg
+desc_len
, ei
->cache_info
.signed_descriptor_body
, extra_len
);
1115 msg
[desc_len
+extra_len
] = 0;
1117 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR
,
1118 (auth
& BRIDGE_AUTHORITY
) ?
1119 ROUTER_PURPOSE_BRIDGE
:
1120 ROUTER_PURPOSE_GENERAL
,
1121 auth
, msg
, desc_len
, extra_len
);
1125 /** OR only: Check whether my exit policy says to allow connection to
1126 * conn. Return 0 if we accept; non-0 if we reject.
1129 router_compare_to_my_exit_policy(edge_connection_t
*conn
)
1131 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1134 /* make sure it's resolved to something. this way we can't get a
1136 if (tor_addr_is_null(&conn
->_base
.addr
))
1140 if (tor_addr_family(&conn
->_base
.addr
) != AF_INET
)
1143 return compare_tor_addr_to_addr_policy(&conn
->_base
.addr
, conn
->_base
.port
,
1144 desc_routerinfo
->exit_policy
) != ADDR_POLICY_ACCEPTED
;
1147 /** Return true iff I'm a server and <b>digest</b> is equal to
1148 * my identity digest. */
1150 router_digest_is_me(const char *digest
)
1152 return identitykey
&& !memcmp(identitykey_digest
, digest
, DIGEST_LEN
);
1155 /** Return true iff I'm a server and <b>digest</b> is equal to
1156 * my identity digest. */
1158 router_extrainfo_digest_is_me(const char *digest
)
1160 extrainfo_t
*ei
= router_get_my_extrainfo();
1164 return !memcmp(digest
,
1165 ei
->cache_info
.signed_descriptor_digest
,
1169 /** A wrapper around router_digest_is_me(). */
1171 router_is_me(routerinfo_t
*router
)
1173 return router_digest_is_me(router
->cache_info
.identity_digest
);
1176 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1178 router_fingerprint_is_me(const char *fp
)
1180 char digest
[DIGEST_LEN
];
1181 if (strlen(fp
) == HEX_DIGEST_LEN
&&
1182 base16_decode(digest
, sizeof(digest
), fp
, HEX_DIGEST_LEN
) == 0)
1183 return router_digest_is_me(digest
);
1188 /** Return a routerinfo for this OR, rebuilding a fresh one if
1189 * necessary. Return NULL on error, or if called on an OP. */
1191 router_get_my_routerinfo(void)
1193 if (!server_mode(get_options()))
1195 if (router_rebuild_descriptor(0))
1197 return desc_routerinfo
;
1200 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1201 * one if necessary. Return NULL on error.
1204 router_get_my_descriptor(void)
1207 if (!router_get_my_routerinfo())
1209 /* Make sure this is nul-terminated. */
1210 tor_assert(desc_routerinfo
->cache_info
.saved_location
== SAVED_NOWHERE
);
1211 body
= signed_descriptor_get_body(&desc_routerinfo
->cache_info
);
1212 tor_assert(!body
[desc_routerinfo
->cache_info
.signed_descriptor_len
]);
1213 log_debug(LD_GENERAL
,"my desc is '%s'", body
);
1217 /** Return the extrainfo document for this OR, or NULL if we have none.
1218 * Rebuilt it (and the server descriptor) if necessary. */
1220 router_get_my_extrainfo(void)
1222 if (!server_mode(get_options()))
1224 if (router_rebuild_descriptor(0))
1226 return desc_extrainfo
;
1229 /** A list of nicknames that we've warned about including in our family
1230 * declaration verbatim rather than as digests. */
1231 static smartlist_t
*warned_nonexistent_family
= NULL
;
1233 static int router_guess_address_from_dir_headers(uint32_t *guess
);
1235 /** Make a current best guess at our address, either because
1236 * it's configured in torrc, or because we've learned it from
1237 * dirserver headers. Place the answer in *<b>addr</b> and return
1238 * 0 on success, else return -1 if we have no guess. */
1240 router_pick_published_address(or_options_t
*options
, uint32_t *addr
)
1242 if (resolve_my_address(LOG_INFO
, options
, addr
, NULL
) < 0) {
1243 log_info(LD_CONFIG
, "Could not determine our address locally. "
1244 "Checking if directory headers provide any hints.");
1245 if (router_guess_address_from_dir_headers(addr
) < 0) {
1246 log_info(LD_CONFIG
, "No hints from directory headers either. "
1247 "Will try again later.");
1254 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1255 * routerinfo, signed server descriptor, and extra-info document for this OR.
1256 * Return 0 on success, -1 on temporary error.
1259 router_rebuild_descriptor(int force
)
1265 int hibernating
= we_are_hibernating();
1267 or_options_t
*options
= get_options();
1269 if (desc_clean_since
&& !force
)
1272 if (router_pick_published_address(options
, &addr
) < 0) {
1273 /* Stop trying to rebuild our descriptor every second. We'll
1274 * learn that it's time to try again when server_has_changed_ip()
1275 * marks it dirty. */
1276 desc_clean_since
= time(NULL
);
1280 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
1281 ri
->cache_info
.routerlist_index
= -1;
1282 ri
->address
= tor_dup_ip(addr
);
1283 ri
->nickname
= tor_strdup(options
->Nickname
);
1285 ri
->or_port
= options
->ORPort
;
1286 ri
->dir_port
= options
->DirPort
;
1287 ri
->cache_info
.published_on
= time(NULL
);
1288 ri
->onion_pkey
= crypto_pk_dup_key(get_onion_key()); /* must invoke from
1290 ri
->identity_pkey
= crypto_pk_dup_key(get_identity_key());
1291 if (crypto_pk_get_digest(ri
->identity_pkey
,
1292 ri
->cache_info
.identity_digest
)<0) {
1293 routerinfo_free(ri
);
1296 get_platform_str(platform
, sizeof(platform
));
1297 ri
->platform
= tor_strdup(platform
);
1299 /* compute ri->bandwidthrate as the min of various options */
1300 ri
->bandwidthrate
= get_effective_bwrate(options
);
1302 /* and compute ri->bandwidthburst similarly */
1303 ri
->bandwidthburst
= get_effective_bwburst(options
);
1305 ri
->bandwidthcapacity
= hibernating
? 0 : rep_hist_bandwidth_assess();
1307 policies_parse_exit_policy(options
->ExitPolicy
, &ri
->exit_policy
,
1308 options
->ExitPolicyRejectPrivate
,
1309 ri
->address
, !options
->BridgeRelay
);
1311 if (desc_routerinfo
) { /* inherit values */
1312 ri
->is_valid
= desc_routerinfo
->is_valid
;
1313 ri
->is_running
= desc_routerinfo
->is_running
;
1314 ri
->is_named
= desc_routerinfo
->is_named
;
1316 if (authdir_mode(options
))
1317 ri
->is_valid
= ri
->is_named
= 1; /* believe in yourself */
1318 if (options
->MyFamily
) {
1319 smartlist_t
*family
;
1320 if (!warned_nonexistent_family
)
1321 warned_nonexistent_family
= smartlist_create();
1322 family
= smartlist_create();
1323 ri
->declared_family
= smartlist_create();
1324 smartlist_split_string(family
, options
->MyFamily
, ",",
1325 SPLIT_SKIP_SPACE
|SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1326 SMARTLIST_FOREACH(family
, char *, name
,
1328 routerinfo_t
*member
;
1329 if (!strcasecmp(name
, options
->Nickname
))
1332 member
= router_get_by_nickname(name
, 1);
1334 int is_legal
= is_legal_nickname_or_hexdigest(name
);
1335 if (!smartlist_string_isin(warned_nonexistent_family
, name
) &&
1336 !is_legal_hexdigest(name
)) {
1339 "I have no descriptor for the router named \"%s\" in my "
1340 "declared family; I'll use the nickname as is, but "
1341 "this may confuse clients.", name
);
1343 log_warn(LD_CONFIG
, "There is a router named \"%s\" in my "
1344 "declared family, but that isn't a legal nickname. "
1345 "Skipping it.", escaped(name
));
1346 smartlist_add(warned_nonexistent_family
, tor_strdup(name
));
1349 smartlist_add(ri
->declared_family
, name
);
1352 } else if (router_is_me(member
)) {
1353 /* Don't list ourself in our own family; that's redundant */
1355 char *fp
= tor_malloc(HEX_DIGEST_LEN
+2);
1357 base16_encode(fp
+1,HEX_DIGEST_LEN
+1,
1358 member
->cache_info
.identity_digest
, DIGEST_LEN
);
1359 smartlist_add(ri
->declared_family
, fp
);
1360 if (smartlist_string_isin(warned_nonexistent_family
, name
))
1361 smartlist_string_remove(warned_nonexistent_family
, name
);
1366 /* remove duplicates from the list */
1367 smartlist_sort_strings(ri
->declared_family
);
1368 smartlist_uniq_strings(ri
->declared_family
);
1370 smartlist_free(family
);
1373 /* Now generate the extrainfo. */
1374 ei
= tor_malloc_zero(sizeof(extrainfo_t
));
1375 ei
->cache_info
.is_extrainfo
= 1;
1376 strlcpy(ei
->nickname
, get_options()->Nickname
, sizeof(ei
->nickname
));
1377 ei
->cache_info
.published_on
= ri
->cache_info
.published_on
;
1378 memcpy(ei
->cache_info
.identity_digest
, ri
->cache_info
.identity_digest
,
1380 ei_size
= options
->ExtraInfoStatistics
? MAX_EXTRAINFO_UPLOAD_SIZE
: 8192;
1381 ei
->cache_info
.signed_descriptor_body
= tor_malloc(ei_size
);
1382 if (extrainfo_dump_to_string(ei
->cache_info
.signed_descriptor_body
,
1383 ei_size
, ei
, get_identity_key()) < 0) {
1384 log_warn(LD_BUG
, "Couldn't generate extra-info descriptor.");
1388 ei
->cache_info
.signed_descriptor_len
=
1389 strlen(ei
->cache_info
.signed_descriptor_body
);
1390 router_get_extrainfo_hash(ei
->cache_info
.signed_descriptor_body
,
1391 ei
->cache_info
.signed_descriptor_digest
);
1393 /* Now finish the router descriptor. */
1394 memcpy(ri
->cache_info
.extra_info_digest
,
1395 ei
->cache_info
.signed_descriptor_digest
,
1397 ri
->cache_info
.signed_descriptor_body
= tor_malloc(8192);
1398 if (router_dump_router_to_string(ri
->cache_info
.signed_descriptor_body
, 8192,
1399 ri
, get_identity_key())<0) {
1400 log_warn(LD_BUG
, "Couldn't generate router descriptor.");
1403 ri
->cache_info
.signed_descriptor_len
=
1404 strlen(ri
->cache_info
.signed_descriptor_body
);
1407 options
->BridgeRelay
? ROUTER_PURPOSE_BRIDGE
: ROUTER_PURPOSE_GENERAL
;
1408 ri
->cache_info
.send_unencrypted
= 1;
1409 /* Let bridges serve their own descriptors unencrypted, so they can
1410 * pass reachability testing. (If they want to be harder to notice,
1411 * they can always leave the DirPort off). */
1412 if (!options
->BridgeRelay
)
1413 ei
->cache_info
.send_unencrypted
= 1;
1415 router_get_router_hash(ri
->cache_info
.signed_descriptor_body
,
1416 ri
->cache_info
.signed_descriptor_digest
);
1418 routerinfo_set_country(ri
);
1420 tor_assert(! routerinfo_incompatible_with_extrainfo(ri
, ei
, NULL
, NULL
));
1422 routerinfo_free(desc_routerinfo
);
1423 desc_routerinfo
= ri
;
1424 extrainfo_free(desc_extrainfo
);
1425 desc_extrainfo
= ei
;
1427 desc_clean_since
= time(NULL
);
1428 desc_needs_upload
= 1;
1429 control_event_my_descriptor_changed();
1433 /** Mark descriptor out of date if it's older than <b>when</b> */
1435 mark_my_descriptor_dirty_if_older_than(time_t when
)
1437 if (desc_clean_since
< when
)
1438 mark_my_descriptor_dirty();
1441 /** Call when the current descriptor is out of date. */
1443 mark_my_descriptor_dirty(void)
1445 desc_clean_since
= 0;
1448 /** How frequently will we republish our descriptor because of large (factor
1449 * of 2) shifts in estimated bandwidth? */
1450 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
1452 /** Check whether bandwidth has changed a lot since the last time we announced
1453 * bandwidth. If so, mark our descriptor dirty. */
1455 check_descriptor_bandwidth_changed(time_t now
)
1457 static time_t last_changed
= 0;
1459 if (!desc_routerinfo
)
1462 prev
= desc_routerinfo
->bandwidthcapacity
;
1463 cur
= we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
1464 if ((prev
!= cur
&& (!prev
|| !cur
)) ||
1467 if (last_changed
+MAX_BANDWIDTH_CHANGE_FREQ
< now
) {
1468 log_info(LD_GENERAL
,
1469 "Measured bandwidth has changed; rebuilding descriptor.");
1470 mark_my_descriptor_dirty();
1476 /** Note at log level severity that our best guess of address has changed from
1477 * <b>prev</b> to <b>cur</b>. */
1479 log_addr_has_changed(int severity
, uint32_t prev
, uint32_t cur
,
1482 char addrbuf_prev
[INET_NTOA_BUF_LEN
];
1483 char addrbuf_cur
[INET_NTOA_BUF_LEN
];
1484 struct in_addr in_prev
;
1485 struct in_addr in_cur
;
1487 in_prev
.s_addr
= htonl(prev
);
1488 tor_inet_ntoa(&in_prev
, addrbuf_prev
, sizeof(addrbuf_prev
));
1490 in_cur
.s_addr
= htonl(cur
);
1491 tor_inet_ntoa(&in_cur
, addrbuf_cur
, sizeof(addrbuf_cur
));
1494 log_fn(severity
, LD_GENERAL
,
1495 "Our IP Address has changed from %s to %s; "
1496 "rebuilding descriptor (source: %s).",
1497 addrbuf_prev
, addrbuf_cur
, source
);
1499 log_notice(LD_GENERAL
,
1500 "Guessed our IP address as %s (source: %s).",
1501 addrbuf_cur
, source
);
1504 /** Check whether our own address as defined by the Address configuration
1505 * has changed. This is for routers that get their address from a service
1506 * like dyndns. If our address has changed, mark our descriptor dirty. */
1508 check_descriptor_ipaddress_changed(time_t now
)
1511 or_options_t
*options
= get_options();
1514 if (!desc_routerinfo
)
1517 prev
= desc_routerinfo
->addr
;
1518 if (resolve_my_address(LOG_INFO
, options
, &cur
, NULL
) < 0) {
1519 log_info(LD_CONFIG
,"options->Address didn't resolve into an IP.");
1524 log_addr_has_changed(LOG_NOTICE
, prev
, cur
, "resolve");
1525 ip_address_changed(0);
1529 /** The most recently guessed value of our IP address, based on directory
1531 static uint32_t last_guessed_ip
= 0;
1533 /** A directory server <b>d_conn</b> told us our IP address is
1534 * <b>suggestion</b>.
1535 * If this address is different from the one we think we are now, and
1536 * if our computer doesn't actually know its IP address, then switch. */
1538 router_new_address_suggestion(const char *suggestion
,
1539 const dir_connection_t
*d_conn
)
1541 uint32_t addr
, cur
= 0;
1543 or_options_t
*options
= get_options();
1545 /* first, learn what the IP address actually is */
1546 if (!tor_inet_aton(suggestion
, &in
)) {
1547 log_debug(LD_DIR
, "Malformed X-Your-Address-Is header %s. Ignoring.",
1548 escaped(suggestion
));
1551 addr
= ntohl(in
.s_addr
);
1553 log_debug(LD_DIR
, "Got X-Your-Address-Is: %s.", suggestion
);
1555 if (!server_mode(options
)) {
1556 last_guessed_ip
= addr
; /* store it in case we need it later */
1560 if (resolve_my_address(LOG_INFO
, options
, &cur
, NULL
) >= 0) {
1561 /* We're all set -- we already know our address. Great. */
1562 last_guessed_ip
= cur
; /* store it in case we need it later */
1565 if (is_internal_IP(addr
, 0)) {
1566 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1569 if (tor_addr_eq_ipv4h(&d_conn
->_base
.addr
, addr
)) {
1570 /* Don't believe anybody who says our IP is their IP. */
1571 log_debug(LD_DIR
, "A directory server told us our IP address is %s, "
1572 "but he's just reporting his own IP address. Ignoring.",
1577 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1578 * us an answer different from what we had the last time we managed to
1580 if (last_guessed_ip
!= addr
) {
1581 control_event_server_status(LOG_NOTICE
,
1582 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1584 log_addr_has_changed(LOG_NOTICE
, last_guessed_ip
, addr
,
1585 d_conn
->_base
.address
);
1586 ip_address_changed(0);
1587 last_guessed_ip
= addr
; /* router_rebuild_descriptor() will fetch it */
1591 /** We failed to resolve our address locally, but we'd like to build
1592 * a descriptor and publish / test reachability. If we have a guess
1593 * about our address based on directory headers, answer it and return
1594 * 0; else return -1. */
1596 router_guess_address_from_dir_headers(uint32_t *guess
)
1598 if (last_guessed_ip
) {
1599 *guess
= last_guessed_ip
;
1605 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1606 * string describing the version of Tor and the operating system we're
1607 * currently running on.
1610 get_platform_str(char *platform
, size_t len
)
1612 tor_snprintf(platform
, len
, "Tor %s on %s", get_version(), get_uname());
1615 /* XXX need to audit this thing and count fenceposts. maybe
1616 * refactor so we don't have to keep asking if we're
1617 * near the end of maxlen?
1619 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1621 /** OR only: Given a routerinfo for this router, and an identity key to sign
1622 * with, encode the routerinfo as a signed server descriptor and write the
1623 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1624 * failure, and the number of bytes used on success.
1627 router_dump_router_to_string(char *s
, size_t maxlen
, routerinfo_t
*router
,
1628 crypto_pk_env_t
*ident_key
)
1630 char *onion_pkey
; /* Onion key, PEM-encoded. */
1631 char *identity_pkey
; /* Identity key, PEM-encoded. */
1632 char digest
[DIGEST_LEN
];
1633 char published
[ISO_TIME_LEN
+1];
1634 char fingerprint
[FINGERPRINT_LEN
+1];
1635 char extra_info_digest
[HEX_DIGEST_LEN
+1];
1636 size_t onion_pkeylen
, identity_pkeylen
;
1639 addr_policy_t
*tmpe
;
1641 or_options_t
*options
= get_options();
1643 /* Make sure the identity key matches the one in the routerinfo. */
1644 if (crypto_pk_cmp_keys(ident_key
, router
->identity_pkey
)) {
1645 log_warn(LD_BUG
,"Tried to sign a router with a private key that didn't "
1646 "match router's public key!");
1650 /* record our fingerprint, so we can include it in the descriptor */
1651 if (crypto_pk_get_fingerprint(router
->identity_pkey
, fingerprint
, 1)<0) {
1652 log_err(LD_BUG
,"Error computing fingerprint");
1656 /* PEM-encode the onion key */
1657 if (crypto_pk_write_public_key_to_string(router
->onion_pkey
,
1658 &onion_pkey
,&onion_pkeylen
)<0) {
1659 log_warn(LD_BUG
,"write onion_pkey to string failed!");
1663 /* PEM-encode the identity key key */
1664 if (crypto_pk_write_public_key_to_string(router
->identity_pkey
,
1665 &identity_pkey
,&identity_pkeylen
)<0) {
1666 log_warn(LD_BUG
,"write identity_pkey to string failed!");
1667 tor_free(onion_pkey
);
1671 /* Encode the publication time. */
1672 format_iso_time(published
, router
->cache_info
.published_on
);
1674 if (router
->declared_family
&& smartlist_len(router
->declared_family
)) {
1676 char *family
= smartlist_join_strings(router
->declared_family
, " ", 0, &n
);
1677 n
+= strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1678 family_line
= tor_malloc(n
);
1679 tor_snprintf(family_line
, n
, "family %s\n", family
);
1682 family_line
= tor_strdup("");
1685 base16_encode(extra_info_digest
, sizeof(extra_info_digest
),
1686 router
->cache_info
.extra_info_digest
, DIGEST_LEN
);
1688 /* Generate the easy portion of the router descriptor. */
1689 result
= tor_snprintf(s
, maxlen
,
1690 "router %s %s %d 0 %d\n"
1692 "opt protocols Link 1 2 Circuit 1\n"
1694 "opt fingerprint %s\n"
1696 "bandwidth %d %d %d\n"
1697 "opt extra-info-digest %s\n%s"
1704 decide_to_advertise_dirport(options
, router
->dir_port
),
1708 stats_n_seconds_working
,
1709 (int) router
->bandwidthrate
,
1710 (int) router
->bandwidthburst
,
1711 (int) router
->bandwidthcapacity
,
1713 options
->DownloadExtraInfo
? "opt caches-extra-info\n" : "",
1714 onion_pkey
, identity_pkey
,
1716 we_are_hibernating() ? "opt hibernating 1\n" : "",
1717 options
->HidServDirectoryV2
? "opt hidden-service-dir\n" : "",
1718 options
->AllowSingleHopExits
? "opt allow-single-hop-exits\n" : "");
1720 tor_free(family_line
);
1721 tor_free(onion_pkey
);
1722 tor_free(identity_pkey
);
1725 log_warn(LD_BUG
,"descriptor snprintf #1 ran out of room!");
1728 /* From now on, we use 'written' to remember the current length of 's'. */
1731 if (options
->ContactInfo
&& strlen(options
->ContactInfo
)) {
1732 const char *ci
= options
->ContactInfo
;
1733 if (strchr(ci
, '\n') || strchr(ci
, '\r'))
1735 result
= tor_snprintf(s
+written
,maxlen
-written
, "contact %s\n", ci
);
1737 log_warn(LD_BUG
,"descriptor snprintf #2 ran out of room!");
1743 /* Write the exit policy to the end of 's'. */
1744 if (dns_seems_to_be_broken() || has_dns_init_failed() ||
1745 !router
->exit_policy
|| !smartlist_len(router
->exit_policy
)) {
1746 /* DNS is screwed up; don't claim to be an exit. */
1747 strlcat(s
+written
, "reject *:*\n", maxlen
-written
);
1748 written
+= strlen("reject *:*\n");
1750 } else if (router
->exit_policy
) {
1752 for (i
= 0; i
< smartlist_len(router
->exit_policy
); ++i
) {
1753 tmpe
= smartlist_get(router
->exit_policy
, i
);
1754 result
= policy_write_item(s
+written
, maxlen
-written
, tmpe
, 1);
1756 log_warn(LD_BUG
,"descriptor policy_write_item ran out of room!");
1759 tor_assert(result
== (int)strlen(s
+written
));
1761 if (written
+2 > maxlen
) {
1762 log_warn(LD_BUG
,"descriptor policy_write_item ran out of room (2)!");
1765 s
[written
++] = '\n';
1769 if (written
+256 > maxlen
) { /* Not enough room for signature. */
1770 log_warn(LD_BUG
,"not enough room left in descriptor for signature!");
1774 /* Sign the descriptor */
1775 strlcpy(s
+written
, "router-signature\n", maxlen
-written
);
1776 written
+= strlen(s
+written
);
1778 if (router_get_router_hash(s
, digest
) < 0) {
1782 note_crypto_pk_op(SIGN_RTR
);
1783 if (router_append_dirobj_signature(s
+written
,maxlen
-written
,
1784 digest
,DIGEST_LEN
,ident_key
)<0) {
1785 log_warn(LD_BUG
, "Couldn't sign router descriptor");
1788 written
+= strlen(s
+written
);
1790 if (written
+2 > maxlen
) {
1791 log_warn(LD_BUG
,"Not enough room to finish descriptor.");
1794 /* include a last '\n' */
1798 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1802 routerinfo_t
*ri_tmp
;
1803 cp
= s_dup
= tor_strdup(s
);
1804 ri_tmp
= router_parse_entry_from_string(cp
, NULL
, 1, 0, NULL
);
1807 "We just generated a router descriptor we can't parse.");
1808 log_err(LD_BUG
, "Descriptor was: <<%s>>", s
);
1812 routerinfo_free(ri_tmp
);
1816 return (int)written
+1;
1819 /** Load the contents of <b>filename</b>, find the last line starting with
1820 * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
1821 * the past or more than 1 hour in the future with respect to <b>now</b>,
1822 * and write the file contents starting with that line to *<b>out</b>.
1823 * Return 1 for success, 0 if the file does not exist, or -1 if the file
1824 * does not contain a line matching these criteria or other failure. */
1826 load_stats_file(const char *filename
, const char *end_line
, time_t now
,
1830 char *fname
= get_datadir_fname(filename
);
1831 char *contents
, *start
= NULL
, *tmp
, timestr
[ISO_TIME_LEN
+1];
1833 switch (file_status(fname
)) {
1835 /* X022 Find an alternative to reading the whole file to memory. */
1836 if ((contents
= read_file_to_str(fname
, 0, NULL
))) {
1837 tmp
= strstr(contents
, end_line
);
1838 /* Find last block starting with end_line */
1841 tmp
= strstr(tmp
+ 1, end_line
);
1845 if (strlen(start
) < strlen(end_line
) + 1 + sizeof(timestr
))
1847 strlcpy(timestr
, start
+ 1 + strlen(end_line
), sizeof(timestr
));
1848 if (parse_iso_time(timestr
, &written
) < 0)
1850 if (written
< now
- (25*60*60) || written
> now
+ (1*60*60))
1852 *out
= tor_strdup(start
);
1870 /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
1871 * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
1872 * negative on failure. */
1874 extrainfo_dump_to_string(char *s
, size_t maxlen
, extrainfo_t
*extrainfo
,
1875 crypto_pk_env_t
*ident_key
)
1877 or_options_t
*options
= get_options();
1878 char identity
[HEX_DIGEST_LEN
+1];
1879 char published
[ISO_TIME_LEN
+1];
1880 char digest
[DIGEST_LEN
];
1881 char *bandwidth_usage
;
1884 static int write_stats_to_extrainfo
= 1;
1885 time_t now
= time(NULL
);
1887 base16_encode(identity
, sizeof(identity
),
1888 extrainfo
->cache_info
.identity_digest
, DIGEST_LEN
);
1889 format_iso_time(published
, extrainfo
->cache_info
.published_on
);
1890 bandwidth_usage
= rep_hist_get_bandwidth_lines(1);
1892 result
= tor_snprintf(s
, maxlen
,
1893 "extra-info %s %s\n"
1895 extrainfo
->nickname
, identity
,
1896 published
, bandwidth_usage
);
1898 if (options
->ExtraInfoStatistics
&& write_stats_to_extrainfo
) {
1899 char *contents
= NULL
;
1900 log_info(LD_GENERAL
, "Adding stats to extra-info descriptor.");
1901 if (options
->DirReqStatistics
&&
1902 load_stats_file("stats"PATH_SEPARATOR
"dirreq-stats",
1903 "dirreq-stats-end", now
, &contents
) > 0) {
1904 size_t pos
= strlen(s
);
1905 if (strlcpy(s
+ pos
, contents
, maxlen
- strlen(s
)) !=
1907 log_warn(LD_DIR
, "Could not write dirreq-stats to extra-info "
1913 if (options
->EntryStatistics
&&
1914 load_stats_file("stats"PATH_SEPARATOR
"entry-stats",
1915 "entry-stats-end", now
, &contents
) > 0) {
1916 size_t pos
= strlen(s
);
1917 if (strlcpy(s
+ pos
, contents
, maxlen
- strlen(s
)) !=
1919 log_warn(LD_DIR
, "Could not write entry-stats to extra-info "
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 "
1937 if (options
->ExitPortStatistics
&&
1938 load_stats_file("stats"PATH_SEPARATOR
"exit-stats",
1939 "exit-stats-end", now
, &contents
) > 0) {
1940 size_t pos
= strlen(s
);
1941 if (strlcpy(s
+ pos
, contents
, maxlen
- strlen(s
)) !=
1943 log_warn(LD_DIR
, "Could not write exit-stats to extra-info "
1951 tor_free(bandwidth_usage
);
1955 if (should_record_bridge_info(options
)) {
1956 char *bridge_stats
= geoip_get_bridge_stats_extrainfo(now
);
1958 size_t pos
= strlen(s
);
1959 if (strlcpy(s
+ pos
, bridge_stats
, maxlen
- strlen(s
)) !=
1960 strlen(bridge_stats
)) {
1961 log_warn(LD_DIR
, "Could not write bridge-stats to extra-info "
1965 tor_free(bridge_stats
);
1970 strlcat(s
+len
, "router-signature\n", maxlen
-len
);
1971 len
+= strlen(s
+len
);
1972 if (router_get_extrainfo_hash(s
, digest
)<0)
1974 if (router_append_dirobj_signature(s
+len
, maxlen
-len
, digest
, DIGEST_LEN
,
1980 extrainfo_t
*ei_tmp
;
1981 cp
= s_dup
= tor_strdup(s
);
1982 ei_tmp
= extrainfo_parse_entry_from_string(cp
, NULL
, 1, NULL
);
1985 "We just generated an extrainfo descriptor we can't parse.");
1986 log_err(LD_BUG
, "Descriptor was: <<%s>>", s
);
1990 extrainfo_free(ei_tmp
);
1993 if (options
->ExtraInfoStatistics
&& write_stats_to_extrainfo
) {
1995 extrainfo_t
*ei_tmp
;
1996 cp
= s_dup
= tor_strdup(s
);
1997 ei_tmp
= extrainfo_parse_entry_from_string(cp
, NULL
, 1, NULL
);
1999 log_warn(LD_GENERAL
,
2000 "We just generated an extra-info descriptor with "
2001 "statistics that we can't parse. Not adding statistics to "
2002 "this or any future extra-info descriptors. Descriptor "
2004 write_stats_to_extrainfo
= 0;
2005 extrainfo_dump_to_string(s
, maxlen
, extrainfo
, ident_key
);
2008 extrainfo_free(ei_tmp
);
2011 return (int)strlen(s
)+1;
2014 /** Return true iff <b>s</b> is a legally valid server nickname. */
2016 is_legal_nickname(const char *s
)
2021 return len
> 0 && len
<= MAX_NICKNAME_LEN
&&
2022 strspn(s
,LEGAL_NICKNAME_CHARACTERS
) == len
;
2025 /** Return true iff <b>s</b> is a legally valid server nickname or
2026 * hex-encoded identity-key digest. */
2028 is_legal_nickname_or_hexdigest(const char *s
)
2031 return is_legal_nickname(s
);
2033 return is_legal_hexdigest(s
);
2036 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
2039 is_legal_hexdigest(const char *s
)
2043 if (s
[0] == '$') s
++;
2045 if (len
> HEX_DIGEST_LEN
) {
2046 if (s
[HEX_DIGEST_LEN
] == '=' ||
2047 s
[HEX_DIGEST_LEN
] == '~') {
2048 if (!is_legal_nickname(s
+HEX_DIGEST_LEN
+1))
2054 return (len
>= HEX_DIGEST_LEN
&&
2055 strspn(s
,HEX_CHARACTERS
)==HEX_DIGEST_LEN
);
2058 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
2059 * verbose representation of the identity of <b>router</b>. The format is:
2061 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
2062 * A "=" if the router is named; a "~" if it is not.
2063 * The router's nickname.
2066 router_get_verbose_nickname(char *buf
, const routerinfo_t
*router
)
2069 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, router
->cache_info
.identity_digest
,
2071 buf
[1+HEX_DIGEST_LEN
] = router
->is_named
? '=' : '~';
2072 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, router
->nickname
, MAX_NICKNAME_LEN
+1);
2075 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
2076 * verbose representation of the identity of <b>router</b>. The format is:
2078 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
2079 * A "=" if the router is named; a "~" if it is not.
2080 * The router's nickname.
2083 routerstatus_get_verbose_nickname(char *buf
, const routerstatus_t
*router
)
2086 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, router
->identity_digest
,
2088 buf
[1+HEX_DIGEST_LEN
] = router
->is_named
? '=' : '~';
2089 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, router
->nickname
, MAX_NICKNAME_LEN
+1);
2092 /** Forget that we have issued any router-related warnings, so that we'll
2093 * warn again if we see the same errors. */
2095 router_reset_warnings(void)
2097 if (warned_nonexistent_family
) {
2098 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
2099 smartlist_clear(warned_nonexistent_family
);
2103 /** Given a router purpose, convert it to a string. Don't call this on
2104 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
2105 * know its string representation. */
2107 router_purpose_to_string(uint8_t p
)
2111 case ROUTER_PURPOSE_GENERAL
: return "general";
2112 case ROUTER_PURPOSE_BRIDGE
: return "bridge";
2113 case ROUTER_PURPOSE_CONTROLLER
: return "controller";
2120 /** Given a string, convert it to a router purpose. */
2122 router_purpose_from_string(const char *s
)
2124 if (!strcmp(s
, "general"))
2125 return ROUTER_PURPOSE_GENERAL
;
2126 else if (!strcmp(s
, "bridge"))
2127 return ROUTER_PURPOSE_BRIDGE
;
2128 else if (!strcmp(s
, "controller"))
2129 return ROUTER_PURPOSE_CONTROLLER
;
2131 return ROUTER_PURPOSE_UNKNOWN
;
2134 /** Release all static resources held in router.c */
2136 router_free_all(void)
2138 crypto_free_pk_env(onionkey
);
2139 crypto_free_pk_env(lastonionkey
);
2140 crypto_free_pk_env(identitykey
);
2141 tor_mutex_free(key_lock
);
2142 routerinfo_free(desc_routerinfo
);
2143 extrainfo_free(desc_extrainfo
);
2144 crypto_free_pk_env(authority_signing_key
);
2145 authority_cert_free(authority_key_certificate
);
2146 crypto_free_pk_env(legacy_signing_key
);
2147 authority_cert_free(legacy_key_certificate
);
2149 if (warned_nonexistent_family
) {
2150 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
2151 smartlist_free(warned_nonexistent_family
);