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-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 const char router_c_id
[] =
10 #define ROUTER_PRIVATE
16 * \brief OR functionality, including key maintenance, generating
17 * and uploading server descriptors, retrying OR connections.
20 extern long stats_n_seconds_working
;
22 /************************************************************/
25 * Key management: ORs only.
28 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
30 static tor_mutex_t
*key_lock
=NULL
;
31 static time_t onionkey_set_at
=0; /**< When was onionkey last changed? */
32 /** Current private onionskin decryption key: used to decode CREATE cells. */
33 static crypto_pk_env_t
*onionkey
=NULL
;
34 /** Previous private onionskin decription key: used to decode CREATE cells
35 * generated by clients that have an older version of our descriptor. */
36 static crypto_pk_env_t
*lastonionkey
=NULL
;
37 /** Private "identity key": used to sign directory info and TLS
38 * certificates. Never changes. */
39 static crypto_pk_env_t
*identitykey
=NULL
;
40 /** Digest of identitykey. */
41 static char identitykey_digest
[DIGEST_LEN
];
42 /** Signing key used for v3 directory material; only set for authorities. */
43 static crypto_pk_env_t
*authority_signing_key
= NULL
;
44 /** Key certificate to authenticate v3 directory material; only set for
46 static authority_cert_t
*authority_key_certificate
= NULL
;
48 static crypto_pk_env_t
*legacy_signing_key
= NULL
;
49 static authority_cert_t
*legacy_key_certificate
= NULL
;
51 /* (Note that v3 authorities also have a separate "authority identity key",
52 * but this key is never actually loaded by the Tor process. Instead, it's
53 * used by tor-gencert to sign new signing keys and make new key
56 /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
57 * to update onionkey correctly, call rotate_onion_key().
60 set_onion_key(crypto_pk_env_t
*k
)
62 tor_mutex_acquire(key_lock
);
64 onionkey_set_at
= time(NULL
);
65 tor_mutex_release(key_lock
);
66 mark_my_descriptor_dirty();
69 /** Return the current onion key. Requires that the onion key has been
70 * loaded or generated. */
78 /** Store a copy of the current onion key into *<b>key</b>, and a copy
79 * of the most recent onion key into *<b>last</b>.
82 dup_onion_keys(crypto_pk_env_t
**key
, crypto_pk_env_t
**last
)
86 tor_mutex_acquire(key_lock
);
88 *key
= crypto_pk_dup_key(onionkey
);
90 *last
= crypto_pk_dup_key(lastonionkey
);
93 tor_mutex_release(key_lock
);
96 /** Return the time when the onion key was last set. This is either the time
97 * when the process launched, or the time of the most recent key rotation since
98 * the process launched.
101 get_onion_key_set_at(void)
103 return onionkey_set_at
;
106 /** Set the current identity key to k.
109 set_identity_key(crypto_pk_env_t
*k
)
112 crypto_free_pk_env(identitykey
);
114 crypto_pk_get_digest(identitykey
, identitykey_digest
);
117 /** Returns the current identity key; requires that the identity key has been
121 get_identity_key(void)
123 tor_assert(identitykey
);
127 /** Return true iff the identity key has been set. */
129 identity_key_is_set(void)
131 return identitykey
!= NULL
;
134 /** Return the key certificate for this v3 (voting) authority, or NULL
135 * if we have no such certificate. */
137 get_my_v3_authority_cert(void)
139 return authority_key_certificate
;
142 /** Return the v3 signing key for this v3 (voting) authority, or NULL
143 * if we have no such key. */
145 get_my_v3_authority_signing_key(void)
147 return authority_signing_key
;
151 get_my_v3_legacy_cert(void)
153 return legacy_key_certificate
;
157 get_my_v3_legacy_signing_key(void)
159 return legacy_signing_key
;
162 /** Replace the previous onion key with the current onion key, and generate
163 * a new previous onion key. Immediately after calling this function,
165 * - schedule all previous cpuworkers to shut down _after_ processing
166 * pending work. (This will cause fresh cpuworkers to be generated.)
167 * - generate and upload a fresh routerinfo.
170 rotate_onion_key(void)
172 char *fname
, *fname_prev
;
173 crypto_pk_env_t
*prkey
;
174 or_state_t
*state
= get_or_state();
176 fname
= get_datadir_fname2("keys", "secret_onion_key");
177 fname_prev
= get_datadir_fname2("keys", "secret_onion_key.old");
178 if (!(prkey
= crypto_new_pk_env())) {
179 log_err(LD_GENERAL
,"Error constructing rotated onion key");
182 if (crypto_pk_generate_key(prkey
)) {
183 log_err(LD_BUG
,"Error generating onion key");
186 if (file_status(fname
) == FN_FILE
) {
187 if (replace_file(fname
, fname_prev
))
190 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
191 log_err(LD_FS
,"Couldn't write generated onion key to \"%s\".", fname
);
194 log_info(LD_GENERAL
, "Rotating onion key");
195 tor_mutex_acquire(key_lock
);
197 crypto_free_pk_env(lastonionkey
);
198 lastonionkey
= onionkey
;
201 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
202 tor_mutex_release(key_lock
);
203 mark_my_descriptor_dirty();
204 or_state_mark_dirty(state
, get_options()->AvoidDiskWrites
? now
+3600 : 0);
207 log_warn(LD_GENERAL
, "Couldn't rotate onion key.");
209 crypto_free_pk_env(prkey
);
212 tor_free(fname_prev
);
215 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
216 * and <b>generate</b> is true, create a new RSA key and save it in
217 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
218 * errors at level <b>severity</b>.
221 init_key_from_file(const char *fname
, int generate
, int severity
)
223 crypto_pk_env_t
*prkey
= NULL
;
225 if (!(prkey
= crypto_new_pk_env())) {
226 log(severity
, LD_GENERAL
,"Error constructing key");
230 switch (file_status(fname
)) {
233 log(severity
, LD_FS
,"Can't read key from \"%s\"", fname
);
237 if (!have_lockfile()) {
238 if (try_locking(get_options(), 0)<0) {
239 /* Make sure that --list-fingerprint only creates new keys
240 * if there is no possibility for a deadlock. */
241 log(severity
, LD_FS
, "Another Tor process has locked \"%s\". Not "
242 "writing any new keys.", fname
);
243 /*XXXX The 'other process' might make a key in a second or two;
244 * maybe we should wait for it. */
248 log_info(LD_GENERAL
, "No key found in \"%s\"; generating fresh key.",
250 if (crypto_pk_generate_key(prkey
)) {
251 log(severity
, LD_GENERAL
,"Error generating onion key");
254 if (crypto_pk_check_key(prkey
) <= 0) {
255 log(severity
, LD_GENERAL
,"Generated key seems invalid");
258 log_info(LD_GENERAL
, "Generated key seems valid");
259 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
261 "Couldn't write generated key to \"%s\".", fname
);
265 log_info(LD_GENERAL
, "No key found in \"%s\"", fname
);
269 if (crypto_pk_read_private_key_from_filename(prkey
, fname
)) {
270 log(severity
, LD_GENERAL
,"Error loading private key.");
280 crypto_free_pk_env(prkey
);
285 load_authority_keyset(int legacy
, crypto_pk_env_t
**key_out
,
286 authority_cert_t
**cert_out
)
289 char *fname
= NULL
, *cert
= NULL
;
290 const char *eos
= NULL
;
291 crypto_pk_env_t
*signing_key
= NULL
;
292 authority_cert_t
*parsed
= NULL
;
294 fname
= get_datadir_fname2("keys",
295 legacy
? "legacy_signing_key" : "authority_signing_key");
296 signing_key
= init_key_from_file(fname
, 0, LOG_INFO
);
298 log_warn(LD_DIR
, "No version 3 directory key found in %s", fname
);
302 fname
= get_datadir_fname2("keys",
303 legacy
? "legacy_certificate" : "authority_certificate");
304 cert
= read_file_to_str(fname
, 0, NULL
);
306 log_warn(LD_DIR
, "Signing key found, but no certificate found in %s",
310 parsed
= authority_cert_parse_from_string(cert
, &eos
);
312 log_warn(LD_DIR
, "Unable to parse certificate in %s", fname
);
315 if (crypto_pk_cmp_keys(signing_key
, parsed
->signing_key
) != 0) {
316 log_warn(LD_DIR
, "Stored signing key does not match signing key in "
320 parsed
->cache_info
.signed_descriptor_body
= cert
;
321 parsed
->cache_info
.signed_descriptor_len
= eos
-cert
;
325 crypto_free_pk_env(*key_out
);
327 authority_cert_free(*cert_out
);
328 *key_out
= signing_key
;
338 crypto_free_pk_env(signing_key
);
340 authority_cert_free(parsed
);
344 /** Load the v3 (voting) authority signing key and certificate, if they are
345 * present. Return -1 if anything is missing, mismatched, or unloadable;
346 * return 0 on success. */
348 init_v3_authority_keys(void)
350 if (load_authority_keyset(0, &authority_signing_key
,
351 &authority_key_certificate
)<0)
354 if (get_options()->V3AuthUseLegacyKey
&&
355 load_authority_keyset(1, &legacy_signing_key
,
356 &legacy_key_certificate
)<0)
362 /** If we're a v3 authority, check whether we have a certificate that's
363 * likely to expire soon. Warn if we do, but not too often. */
365 v3_authority_check_key_expiry(void)
368 static time_t last_warned
= 0;
369 int badness
, time_left
, warn_interval
;
370 if (!authdir_mode_v3(get_options()) || !authority_key_certificate
)
374 expires
= authority_key_certificate
->expires
;
375 time_left
= (int)( expires
- now
);
376 if (time_left
<= 0) {
378 warn_interval
= 60*60;
379 } else if (time_left
<= 24*60*60) {
381 warn_interval
= 60*60;
382 } else if (time_left
<= 24*60*60*7) {
384 warn_interval
= 24*60*60;
385 } else if (time_left
<= 24*60*60*30) {
387 warn_interval
= 24*60*60*5;
392 if (last_warned
+ warn_interval
> now
)
395 if (time_left
<= 0) {
396 log(badness
, LD_DIR
, "Your v3 authority certificate has expired."
397 " Generate a new one NOW.");
398 } else if (time_left
<= 24*60*60) {
399 log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d hours;"
400 " Generate a new one NOW.", time_left
/(60*60));
402 log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d days;"
403 " Generate a new one soon.", time_left
/(24*60*60));
408 /** Initialize all OR private keys, and the TLS context, as necessary.
409 * On OPs, this only initializes the tls context. Return 0 on success,
410 * or -1 if Tor should die.
416 char fingerprint
[FINGERPRINT_LEN
+1];
417 /*nickname<space>fp\n\0 */
418 char fingerprint_line
[MAX_NICKNAME_LEN
+FINGERPRINT_LEN
+3];
420 crypto_pk_env_t
*prkey
;
424 or_options_t
*options
= get_options();
425 authority_type_t type
;
426 time_t now
= time(NULL
);
427 trusted_dir_server_t
*ds
;
428 int v3_digest_set
= 0;
429 authority_cert_t
*cert
= NULL
;
432 key_lock
= tor_mutex_new();
434 /* OP's don't need persistent keys; just make up an identity and
435 * initialize the TLS context. */
436 if (!server_mode(options
)) {
437 if (!(prkey
= crypto_new_pk_env()))
439 if (crypto_pk_generate_key(prkey
)) {
440 crypto_free_pk_env(prkey
);
443 set_identity_key(prkey
);
444 /* Create a TLS context; default the client nickname to "client". */
445 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME
) < 0) {
446 log_err(LD_GENERAL
,"Error creating TLS context for Tor client.");
451 /* Make sure DataDirectory exists, and is private. */
452 if (check_private_dir(options
->DataDirectory
, CPD_CREATE
)) {
455 /* Check the key directory. */
456 keydir
= get_datadir_fname("keys");
457 if (check_private_dir(keydir
, CPD_CREATE
)) {
463 /* 1a. Read v3 directory authority key/cert information. */
464 memset(v3_digest
, 0, sizeof(v3_digest
));
465 if (authdir_mode_v3(options
)) {
466 if (init_v3_authority_keys()<0) {
467 log_err(LD_GENERAL
, "We're configured as a V3 authority, but we "
468 "were unable to load our v3 authority keys and certificate! "
469 "Use tor-gencert to generate them. Dying.");
472 cert
= get_my_v3_authority_cert();
474 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key
,
480 /* 1. Read identity key. Make it if none is found. */
481 keydir
= get_datadir_fname2("keys", "secret_id_key");
482 log_info(LD_GENERAL
,"Reading/making identity key \"%s\"...",keydir
);
483 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
485 if (!prkey
) return -1;
486 set_identity_key(prkey
);
488 /* 2. Read onion key. Make it if none is found. */
489 keydir
= get_datadir_fname2("keys", "secret_onion_key");
490 log_info(LD_GENERAL
,"Reading/making onion key \"%s\"...",keydir
);
491 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
493 if (!prkey
) return -1;
494 set_onion_key(prkey
);
495 if (options
->command
== CMD_RUN_TOR
) {
496 /* only mess with the state file if we're actually running Tor */
497 or_state_t
*state
= get_or_state();
498 if (state
->LastRotatedOnionKey
> 100 && state
->LastRotatedOnionKey
< now
) {
499 /* We allow for some parsing slop, but we don't want to risk accepting
500 * values in the distant future. If we did, we might never rotate the
502 onionkey_set_at
= state
->LastRotatedOnionKey
;
504 /* We have no LastRotatedOnionKey set; either we just created the key
505 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
506 * start the clock ticking now so that we will eventually rotate it even
507 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
508 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
509 or_state_mark_dirty(state
, options
->AvoidDiskWrites
?
510 time(NULL
)+3600 : 0);
514 keydir
= get_datadir_fname2("keys", "secret_onion_key.old");
515 if (!lastonionkey
&& file_status(keydir
) == FN_FILE
) {
516 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
518 lastonionkey
= prkey
;
522 /* 3. Initialize link key and TLS context. */
523 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME
) < 0) {
524 log_err(LD_GENERAL
,"Error initializing TLS context");
527 /* 4. Build our router descriptor. */
528 /* Must be called after keys are initialized. */
529 mydesc
= router_get_my_descriptor();
530 if (authdir_mode(options
)) {
533 /* We need to add our own fingerprint so it gets recognized. */
534 if (dirserv_add_own_fingerprint(options
->Nickname
, get_identity_key())) {
535 log_err(LD_GENERAL
,"Error adding own fingerprint to approved set");
539 ri
= router_parse_entry_from_string(mydesc
, NULL
, 1, 0, NULL
);
541 log_err(LD_GENERAL
,"Generated a routerinfo we couldn't parse.");
544 if (dirserv_add_descriptor(ri
, &m
) < 0) {
545 log_err(LD_GENERAL
,"Unable to add own descriptor to directory: %s",
546 m
?m
:"<unknown error>");
552 /* 5. Dump fingerprint to 'fingerprint' */
553 keydir
= get_datadir_fname("fingerprint");
554 log_info(LD_GENERAL
,"Dumping fingerprint to \"%s\"...",keydir
);
555 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint
, 1)<0) {
556 log_err(LD_GENERAL
,"Error computing fingerprint");
560 tor_assert(strlen(options
->Nickname
) <= MAX_NICKNAME_LEN
);
561 if (tor_snprintf(fingerprint_line
, sizeof(fingerprint_line
),
562 "%s %s\n",options
->Nickname
, fingerprint
) < 0) {
563 log_err(LD_GENERAL
,"Error writing fingerprint line");
567 /* Check whether we need to write the fingerprint file. */
569 if (file_status(keydir
) == FN_FILE
)
570 cp
= read_file_to_str(keydir
, 0, NULL
);
571 if (!cp
|| strcmp(cp
, fingerprint_line
)) {
572 if (write_str_to_file(keydir
, fingerprint_line
, 0)) {
573 log_err(LD_FS
, "Error writing fingerprint line to file");
581 log(LOG_NOTICE
, LD_GENERAL
,
582 "Your Tor server's identity key fingerprint is '%s %s'",
583 options
->Nickname
, fingerprint
);
584 if (!authdir_mode(options
))
586 /* 6. [authdirserver only] load approved-routers file */
587 if (dirserv_load_fingerprint_file() < 0) {
588 log_err(LD_GENERAL
,"Error loading fingerprints");
591 /* 6b. [authdirserver only] add own key to approved directories. */
592 crypto_pk_get_digest(get_identity_key(), digest
);
593 type
= ((options
->V1AuthoritativeDir
? V1_AUTHORITY
: NO_AUTHORITY
) |
594 (options
->V2AuthoritativeDir
? V2_AUTHORITY
: NO_AUTHORITY
) |
595 (options
->V3AuthoritativeDir
? V3_AUTHORITY
: NO_AUTHORITY
) |
596 (options
->BridgeAuthoritativeDir
? BRIDGE_AUTHORITY
: NO_AUTHORITY
) |
597 (options
->HSAuthoritativeDir
? HIDSERV_AUTHORITY
: NO_AUTHORITY
));
599 ds
= router_get_trusteddirserver_by_digest(digest
);
601 ds
= add_trusted_dir_server(options
->Nickname
, NULL
,
602 (uint16_t)options
->DirPort
,
603 (uint16_t)options
->ORPort
,
608 log_err(LD_GENERAL
,"We want to be a directory authority, but we "
609 "couldn't add ourselves to the authority list. Failing.");
613 if (ds
->type
!= type
) {
614 log_warn(LD_DIR
, "Configured authority type does not match authority "
615 "type in DirServer list. Adjusting. (%d v %d)",
619 if (v3_digest_set
&& (ds
->type
& V3_AUTHORITY
) &&
620 memcmp(v3_digest
, ds
->v3_identity_digest
, DIGEST_LEN
)) {
621 log_warn(LD_DIR
, "V3 identity key does not match identity declared in "
622 "DirServer line. Adjusting.");
623 memcpy(ds
->v3_identity_digest
, v3_digest
, DIGEST_LEN
);
626 if (cert
) { /* add my own cert to the list of known certs */
627 log_info(LD_DIR
, "adding my own v3 cert");
628 if (trusted_dirs_load_certs_from_string(
629 cert
->cache_info
.signed_descriptor_body
, 0, 0)<0) {
630 log_warn(LD_DIR
, "Unable to parse my own v3 cert! Failing.");
635 return 0; /* success */
638 /* Keep track of whether we should upload our server descriptor,
639 * and what type of server we are.
642 /** Whether we can reach our ORPort from the outside. */
643 static int can_reach_or_port
= 0;
644 /** Whether we can reach our DirPort from the outside. */
645 static int can_reach_dir_port
= 0;
647 /** Forget what we have learned about our reachability status. */
649 router_reset_reachability(void)
651 can_reach_or_port
= can_reach_dir_port
= 0;
654 /** Return 1 if ORPort is known reachable; else return 0. */
656 check_whether_orport_reachable(void)
658 or_options_t
*options
= get_options();
659 return options
->AssumeReachable
||
663 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
665 check_whether_dirport_reachable(void)
667 or_options_t
*options
= get_options();
668 return !options
->DirPort
||
669 options
->AssumeReachable
||
670 we_are_hibernating() ||
674 /** Look at a variety of factors, and return 0 if we don't want to
675 * advertise the fact that we have a DirPort open. Else return the
676 * DirPort we want to advertise.
678 * Log a helpful message if we change our mind about whether to publish
682 decide_to_advertise_dirport(or_options_t
*options
, uint16_t dir_port
)
684 static int advertising
=1; /* start out assuming we will advertise */
686 const char *reason
= NULL
;
688 /* Section one: reasons to publish or not publish that aren't
689 * worth mentioning to the user, either because they're obvious
690 * or because they're normal behavior. */
692 if (!dir_port
) /* short circuit the rest of the function */
694 if (authdir_mode(options
)) /* always publish */
696 if (we_are_hibernating())
698 if (!check_whether_dirport_reachable())
701 /* Section two: reasons to publish or not publish that the user
702 * might find surprising. These are generally config options that
703 * make us choose not to publish. */
705 if (accounting_is_enabled(options
)) {
706 /* if we might potentially hibernate */
708 reason
= "AccountingMax enabled";
709 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
710 } else if (options
->BandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
||
711 (options
->RelayBandwidthRate
> 0 &&
712 options
->RelayBandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
)) {
713 /* if we're advertising a small amount */
715 reason
= "BandwidthRate under 50KB";
718 if (advertising
!= new_choice
) {
719 if (new_choice
== 1) {
720 log(LOG_NOTICE
, LD_DIR
, "Advertising DirPort as %d", dir_port
);
723 log(LOG_NOTICE
, LD_DIR
, "Not advertising DirPort (Reason: %s)", reason
);
725 advertising
= new_choice
;
728 return advertising
? dir_port
: 0;
731 /** Some time has passed, or we just got new directory information.
732 * See if we currently believe our ORPort or DirPort to be
733 * unreachable. If so, launch a new test for it.
735 * For ORPort, we simply try making a circuit that ends at ourselves.
736 * Success is noticed in onionskin_answer().
738 * For DirPort, we make a connection via Tor to our DirPort and ask
739 * for our own server descriptor.
740 * Success is noticed in connection_dir_client_reached_eof().
743 consider_testing_reachability(int test_or
, int test_dir
)
745 routerinfo_t
*me
= router_get_my_routerinfo();
746 int orport_reachable
= check_whether_orport_reachable();
751 if (test_or
&& (!orport_reachable
|| !circuit_enough_testing_circs())) {
752 log_info(LD_CIRC
, "Testing %s of my ORPort: %s:%d.",
753 !orport_reachable
? "reachability" : "bandwidth",
754 me
->address
, me
->or_port
);
755 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING
, me
,
756 CIRCLAUNCH_NEED_CAPACITY
|CIRCLAUNCH_IS_INTERNAL
);
757 control_event_server_status(LOG_NOTICE
,
758 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
759 me
->address
, me
->or_port
);
762 tor_addr_from_ipv4h(&addr
, me
->addr
);
763 if (test_dir
&& !check_whether_dirport_reachable() &&
764 !connection_get_by_type_addr_port_purpose(
765 CONN_TYPE_DIR
, &addr
, me
->dir_port
,
766 DIR_PURPOSE_FETCH_SERVERDESC
)) {
767 /* ask myself, via tor, for my server descriptor. */
768 directory_initiate_command(me
->address
, &addr
,
769 me
->or_port
, me
->dir_port
,
770 0, /* does not matter */
771 0, me
->cache_info
.identity_digest
,
772 DIR_PURPOSE_FETCH_SERVERDESC
,
773 ROUTER_PURPOSE_GENERAL
,
774 1, "authority.z", NULL
, 0, 0);
776 control_event_server_status(LOG_NOTICE
,
777 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
778 me
->address
, me
->dir_port
);
782 /** Annotate that we found our ORPort reachable. */
784 router_orport_found_reachable(void)
786 if (!can_reach_or_port
) {
787 routerinfo_t
*me
= router_get_my_routerinfo();
788 log_notice(LD_OR
,"Self-testing indicates your ORPort is reachable from "
789 "the outside. Excellent.%s",
790 get_options()->_PublishServerDescriptor
!= NO_AUTHORITY
?
791 " Publishing server descriptor." : "");
792 can_reach_or_port
= 1;
793 mark_my_descriptor_dirty();
796 control_event_server_status(LOG_NOTICE
,
797 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
798 me
->address
, me
->or_port
);
802 /** Annotate that we found our DirPort reachable. */
804 router_dirport_found_reachable(void)
806 if (!can_reach_dir_port
) {
807 routerinfo_t
*me
= router_get_my_routerinfo();
808 log_notice(LD_DIRSERV
,"Self-testing indicates your DirPort is reachable "
809 "from the outside. Excellent.");
810 can_reach_dir_port
= 1;
811 if (!me
|| decide_to_advertise_dirport(get_options(), me
->dir_port
))
812 mark_my_descriptor_dirty();
815 control_event_server_status(LOG_NOTICE
,
816 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
817 me
->address
, me
->dir_port
);
821 /** We have enough testing circuits open. Send a bunch of "drop"
822 * cells down each of them, to exercise our bandwidth. */
824 router_perform_bandwidth_test(int num_circs
, time_t now
)
826 int num_cells
= (int)(get_options()->BandwidthRate
* 10 / CELL_NETWORK_SIZE
);
827 int max_cells
= num_cells
< CIRCWINDOW_START
?
828 num_cells
: CIRCWINDOW_START
;
829 int cells_per_circuit
= max_cells
/ num_circs
;
830 origin_circuit_t
*circ
= NULL
;
832 log_notice(LD_OR
,"Performing bandwidth self-test...done.");
833 while ((circ
= circuit_get_next_by_pk_and_purpose(circ
, NULL
,
834 CIRCUIT_PURPOSE_TESTING
))) {
835 /* dump cells_per_circuit drop cells onto this circ */
836 int i
= cells_per_circuit
;
837 if (circ
->_base
.state
!= CIRCUIT_STATE_OPEN
)
839 circ
->_base
.timestamp_dirty
= now
;
841 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
843 NULL
, 0, circ
->cpath
->prev
)<0) {
844 return; /* stop if error */
850 /** Return true iff we believe ourselves to be an authoritative
854 authdir_mode(or_options_t
*options
)
856 return options
->AuthoritativeDir
!= 0;
858 /** Return true iff we believe ourselves to be a v1 authoritative
862 authdir_mode_v1(or_options_t
*options
)
864 return authdir_mode(options
) && options
->V1AuthoritativeDir
!= 0;
866 /** Return true iff we believe ourselves to be a v2 authoritative
870 authdir_mode_v2(or_options_t
*options
)
872 return authdir_mode(options
) && options
->V2AuthoritativeDir
!= 0;
874 /** Return true iff we believe ourselves to be a v3 authoritative
878 authdir_mode_v3(or_options_t
*options
)
880 return authdir_mode(options
) && options
->V3AuthoritativeDir
!= 0;
882 /** Return true iff we are a v1, v2, or v3 directory authority. */
884 authdir_mode_any_main(or_options_t
*options
)
886 return options
->V1AuthoritativeDir
||
887 options
->V2AuthoritativeDir
||
888 options
->V3AuthoritativeDir
;
890 /** Return true if we believe ourselves to be any kind of
891 * authoritative directory beyond just a hidserv authority. */
893 authdir_mode_any_nonhidserv(or_options_t
*options
)
895 return options
->BridgeAuthoritativeDir
||
896 authdir_mode_any_main(options
);
898 /** Return true iff we are an authoritative directory server that is
899 * authoritative about receiving and serving descriptors of type
900 * <b>purpose</b> its dirport. Use -1 for "any purpose". */
902 authdir_mode_handles_descs(or_options_t
*options
, int purpose
)
905 return authdir_mode_any_nonhidserv(options
);
906 else if (purpose
== ROUTER_PURPOSE_GENERAL
)
907 return authdir_mode_any_main(options
);
908 else if (purpose
== ROUTER_PURPOSE_BRIDGE
)
909 return (options
->BridgeAuthoritativeDir
);
913 /** Return true iff we are an authoritative directory server that
914 * publishes its own network statuses.
917 authdir_mode_publishes_statuses(or_options_t
*options
)
919 if (authdir_mode_bridge(options
))
921 return authdir_mode_any_nonhidserv(options
);
923 /** Return true iff we are an authoritative directory server that
924 * tests reachability of the descriptors it learns about.
927 authdir_mode_tests_reachability(or_options_t
*options
)
929 return authdir_mode_handles_descs(options
, -1);
931 /** Return true iff we believe ourselves to be a bridge authoritative
935 authdir_mode_bridge(or_options_t
*options
)
937 return authdir_mode(options
) && options
->BridgeAuthoritativeDir
!= 0;
939 /** Return true iff we once tried to stay connected to all ORs at once.
940 * FFFF this function, and the notion of staying connected to ORs, is
941 * nearly obsolete. One day there will be a proposal for getting rid of
945 clique_mode(or_options_t
*options
)
947 return authdir_mode_tests_reachability(options
);
950 /** Return true iff we are trying to be a server.
953 server_mode(or_options_t
*options
)
955 if (options
->ClientOnly
) return 0;
956 return (options
->ORPort
!= 0 || options
->ORListenAddress
);
959 /** Remember if we've advertised ourselves to the dirservers. */
960 static int server_is_advertised
=0;
962 /** Return true iff we have published our descriptor lately.
965 advertised_server_mode(void)
967 return server_is_advertised
;
971 * Called with a boolean: set whether we have recently published our
975 set_server_advertised(int s
)
977 server_is_advertised
= s
;
980 /** Return true iff we are trying to be a socks proxy. */
982 proxy_mode(or_options_t
*options
)
984 return (options
->SocksPort
!= 0 || options
->SocksListenAddress
||
985 options
->TransPort
!= 0 || options
->TransListenAddress
||
986 options
->NatdPort
!= 0 || options
->NatdListenAddress
||
987 options
->DNSPort
!= 0 || options
->DNSListenAddress
);
990 /** Decide if we're a publishable server. We are a publishable server if:
991 * - We don't have the ClientOnly option set
993 * - We have the PublishServerDescriptor option set to non-empty
995 * - We have ORPort set
997 * - We believe we are reachable from the outside; or
998 * - We are an authoritative directory server.
1001 decide_if_publishable_server(void)
1003 or_options_t
*options
= get_options();
1005 if (options
->ClientOnly
)
1007 if (options
->_PublishServerDescriptor
== NO_AUTHORITY
)
1009 if (!server_mode(options
))
1011 if (authdir_mode(options
))
1014 return check_whether_orport_reachable();
1017 /** Initiate server descriptor upload as reasonable (if server is publishable,
1018 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1020 * We need to rebuild the descriptor if it's dirty even if we're not
1021 * uploading, because our reachability testing *uses* our descriptor to
1022 * determine what IP address and ports to test.
1025 consider_publishable_server(int force
)
1029 if (!server_mode(get_options()))
1032 rebuilt
= router_rebuild_descriptor(0);
1033 if (decide_if_publishable_server()) {
1034 set_server_advertised(1);
1036 router_upload_dir_desc_to_dirservers(force
);
1038 set_server_advertised(0);
1043 * Clique maintenance -- to be phased out.
1046 /** Return true iff we believe this OR tries to keep connections open
1047 * to all other ORs. */
1049 router_is_clique_mode(routerinfo_t
*router
)
1051 if (router_digest_is_trusted_dir(router
->cache_info
.identity_digest
))
1057 * OR descriptor generation.
1060 /** My routerinfo. */
1061 static routerinfo_t
*desc_routerinfo
= NULL
;
1063 static extrainfo_t
*desc_extrainfo
= NULL
;
1064 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1066 static time_t desc_clean_since
= 0;
1067 /** Boolean: do we need to regenerate the above? */
1068 static int desc_needs_upload
= 0;
1070 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1071 * descriptor successfully yet, try to upload our signed descriptor to
1072 * all the directory servers we know about.
1075 router_upload_dir_desc_to_dirservers(int force
)
1080 size_t desc_len
, extra_len
= 0, total_len
;
1081 authority_type_t auth
= get_options()->_PublishServerDescriptor
;
1083 ri
= router_get_my_routerinfo();
1085 log_info(LD_GENERAL
, "No descriptor; skipping upload");
1088 ei
= router_get_my_extrainfo();
1089 if (auth
== NO_AUTHORITY
)
1091 if (!force
&& !desc_needs_upload
)
1093 desc_needs_upload
= 0;
1095 desc_len
= ri
->cache_info
.signed_descriptor_len
;
1096 extra_len
= ei
? ei
->cache_info
.signed_descriptor_len
: 0;
1097 total_len
= desc_len
+ extra_len
+ 1;
1098 msg
= tor_malloc(total_len
);
1099 memcpy(msg
, ri
->cache_info
.signed_descriptor_body
, desc_len
);
1101 memcpy(msg
+desc_len
, ei
->cache_info
.signed_descriptor_body
, extra_len
);
1103 msg
[desc_len
+extra_len
] = 0;
1105 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR
,
1106 (auth
& BRIDGE_AUTHORITY
) ?
1107 ROUTER_PURPOSE_BRIDGE
:
1108 ROUTER_PURPOSE_GENERAL
,
1109 auth
, msg
, desc_len
, extra_len
);
1113 /** OR only: Check whether my exit policy says to allow connection to
1114 * conn. Return 0 if we accept; non-0 if we reject.
1117 router_compare_to_my_exit_policy(edge_connection_t
*conn
)
1119 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1122 /* make sure it's resolved to something. this way we can't get a
1124 if (tor_addr_is_null(&conn
->_base
.addr
))
1127 return compare_tor_addr_to_addr_policy(&conn
->_base
.addr
, conn
->_base
.port
,
1128 desc_routerinfo
->exit_policy
) != ADDR_POLICY_ACCEPTED
;
1131 /** Return true iff I'm a server and <b>digest</b> is equal to
1132 * my identity digest. */
1134 router_digest_is_me(const char *digest
)
1136 return identitykey
&& !memcmp(identitykey_digest
, digest
, DIGEST_LEN
);
1139 /** Return true iff I'm a server and <b>digest</b> is equal to
1140 * my identity digest. */
1142 router_extrainfo_digest_is_me(const char *digest
)
1144 extrainfo_t
*ei
= router_get_my_extrainfo();
1148 return !memcmp(digest
,
1149 ei
->cache_info
.signed_descriptor_digest
,
1153 /** A wrapper around router_digest_is_me(). */
1155 router_is_me(routerinfo_t
*router
)
1157 return router_digest_is_me(router
->cache_info
.identity_digest
);
1160 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1162 router_fingerprint_is_me(const char *fp
)
1164 char digest
[DIGEST_LEN
];
1165 if (strlen(fp
) == HEX_DIGEST_LEN
&&
1166 base16_decode(digest
, sizeof(digest
), fp
, HEX_DIGEST_LEN
) == 0)
1167 return router_digest_is_me(digest
);
1172 /** Return a routerinfo for this OR, rebuilding a fresh one if
1173 * necessary. Return NULL on error, or if called on an OP. */
1175 router_get_my_routerinfo(void)
1177 if (!server_mode(get_options()))
1179 if (router_rebuild_descriptor(0))
1181 return desc_routerinfo
;
1184 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1185 * one if necessary. Return NULL on error.
1188 router_get_my_descriptor(void)
1191 if (!router_get_my_routerinfo())
1193 /* Make sure this is nul-terminated. */
1194 tor_assert(desc_routerinfo
->cache_info
.saved_location
== SAVED_NOWHERE
);
1195 body
= signed_descriptor_get_body(&desc_routerinfo
->cache_info
);
1196 tor_assert(!body
[desc_routerinfo
->cache_info
.signed_descriptor_len
]);
1197 log_debug(LD_GENERAL
,"my desc is '%s'", body
);
1201 /* Return the extrainfo document for this OR, or NULL if we have none.
1202 * Rebuilt it (and the server descriptor) if necessary. */
1204 router_get_my_extrainfo(void)
1206 if (!server_mode(get_options()))
1208 if (router_rebuild_descriptor(0))
1210 return desc_extrainfo
;
1213 /** A list of nicknames that we've warned about including in our family
1214 * declaration verbatim rather than as digests. */
1215 static smartlist_t
*warned_nonexistent_family
= NULL
;
1217 static int router_guess_address_from_dir_headers(uint32_t *guess
);
1219 /** Make a current best guess at our address, either because
1220 * it's configured in torrc, or because we've learned it from
1221 * dirserver headers. Place the answer in *<b>addr</b> and return
1222 * 0 on success, else return -1 if we have no guess. */
1224 router_pick_published_address(or_options_t
*options
, uint32_t *addr
)
1226 if (resolve_my_address(LOG_INFO
, options
, addr
, NULL
) < 0) {
1227 log_info(LD_CONFIG
, "Could not determine our address locally. "
1228 "Checking if directory headers provide any hints.");
1229 if (router_guess_address_from_dir_headers(addr
) < 0) {
1230 log_info(LD_CONFIG
, "No hints from directory headers either. "
1231 "Will try again later.");
1238 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1239 * routerinfo, signed server descriptor, and extra-info document for this OR.
1240 * Return 0 on success, -1 on temporary error.
1243 router_rebuild_descriptor(int force
)
1249 int hibernating
= we_are_hibernating();
1250 or_options_t
*options
= get_options();
1252 if (desc_clean_since
&& !force
)
1255 if (router_pick_published_address(options
, &addr
) < 0) {
1256 /* Stop trying to rebuild our descriptor every second. We'll
1257 * learn that it's time to try again when server_has_changed_ip()
1258 * marks it dirty. */
1259 desc_clean_since
= time(NULL
);
1263 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
1264 ri
->cache_info
.routerlist_index
= -1;
1265 ri
->address
= tor_dup_ip(addr
);
1266 ri
->nickname
= tor_strdup(options
->Nickname
);
1268 ri
->or_port
= options
->ORPort
;
1269 ri
->dir_port
= options
->DirPort
;
1270 ri
->cache_info
.published_on
= time(NULL
);
1271 ri
->onion_pkey
= crypto_pk_dup_key(get_onion_key()); /* must invoke from
1273 ri
->identity_pkey
= crypto_pk_dup_key(get_identity_key());
1274 if (crypto_pk_get_digest(ri
->identity_pkey
,
1275 ri
->cache_info
.identity_digest
)<0) {
1276 routerinfo_free(ri
);
1279 get_platform_str(platform
, sizeof(platform
));
1280 ri
->platform
= tor_strdup(platform
);
1282 /* compute ri->bandwidthrate as the min of various options */
1283 ri
->bandwidthrate
= (int)options
->BandwidthRate
;
1284 if (ri
->bandwidthrate
> options
->MaxAdvertisedBandwidth
)
1285 ri
->bandwidthrate
= (int)options
->MaxAdvertisedBandwidth
;
1286 if (options
->RelayBandwidthRate
> 0 &&
1287 ri
->bandwidthrate
> options
->RelayBandwidthRate
)
1288 ri
->bandwidthrate
= (int)options
->RelayBandwidthRate
;
1290 /* and compute ri->bandwidthburst similarly */
1291 ri
->bandwidthburst
= (int)options
->BandwidthBurst
;
1292 if (options
->RelayBandwidthBurst
> 0 &&
1293 ri
->bandwidthburst
> options
->RelayBandwidthBurst
)
1294 ri
->bandwidthburst
= (int)options
->RelayBandwidthBurst
;
1296 ri
->bandwidthcapacity
= hibernating
? 0 : rep_hist_bandwidth_assess();
1298 policies_parse_exit_policy(options
->ExitPolicy
, &ri
->exit_policy
,
1299 options
->ExitPolicyRejectPrivate
,
1302 if (desc_routerinfo
) { /* inherit values */
1303 ri
->is_valid
= desc_routerinfo
->is_valid
;
1304 ri
->is_running
= desc_routerinfo
->is_running
;
1305 ri
->is_named
= desc_routerinfo
->is_named
;
1307 if (authdir_mode(options
))
1308 ri
->is_valid
= ri
->is_named
= 1; /* believe in yourself */
1309 if (options
->MyFamily
) {
1310 smartlist_t
*family
;
1311 if (!warned_nonexistent_family
)
1312 warned_nonexistent_family
= smartlist_create();
1313 family
= smartlist_create();
1314 ri
->declared_family
= smartlist_create();
1315 smartlist_split_string(family
, options
->MyFamily
, ",",
1316 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1317 SMARTLIST_FOREACH(family
, char *, name
,
1319 routerinfo_t
*member
;
1320 if (!strcasecmp(name
, options
->Nickname
))
1323 member
= router_get_by_nickname(name
, 1);
1325 int is_legal
= is_legal_nickname_or_hexdigest(name
);
1326 if (!smartlist_string_isin(warned_nonexistent_family
, name
) &&
1327 !is_legal_hexdigest(name
)) {
1330 "I have no descriptor for the router named \"%s\" in my "
1331 "declared family; I'll use the nickname as is, but "
1332 "this may confuse clients.", name
);
1334 log_warn(LD_CONFIG
, "There is a router named \"%s\" in my "
1335 "declared family, but that isn't a legal nickname. "
1336 "Skipping it.", escaped(name
));
1337 smartlist_add(warned_nonexistent_family
, tor_strdup(name
));
1340 smartlist_add(ri
->declared_family
, name
);
1343 } else if (router_is_me(member
)) {
1344 /* Don't list ourself in our own family; that's redundant */
1346 char *fp
= tor_malloc(HEX_DIGEST_LEN
+2);
1348 base16_encode(fp
+1,HEX_DIGEST_LEN
+1,
1349 member
->cache_info
.identity_digest
, DIGEST_LEN
);
1350 smartlist_add(ri
->declared_family
, fp
);
1351 if (smartlist_string_isin(warned_nonexistent_family
, name
))
1352 smartlist_string_remove(warned_nonexistent_family
, name
);
1357 /* remove duplicates from the list */
1358 smartlist_sort_strings(ri
->declared_family
);
1359 smartlist_uniq_strings(ri
->declared_family
);
1361 smartlist_free(family
);
1364 /* Now generate the extrainfo. */
1365 ei
= tor_malloc_zero(sizeof(extrainfo_t
));
1366 ei
->cache_info
.is_extrainfo
= 1;
1367 strlcpy(ei
->nickname
, get_options()->Nickname
, sizeof(ei
->nickname
));
1368 ei
->cache_info
.published_on
= ri
->cache_info
.published_on
;
1369 memcpy(ei
->cache_info
.identity_digest
, ri
->cache_info
.identity_digest
,
1371 ei
->cache_info
.signed_descriptor_body
= tor_malloc(8192);
1372 if (extrainfo_dump_to_string(ei
->cache_info
.signed_descriptor_body
, 8192,
1373 ei
, get_identity_key()) < 0) {
1374 log_warn(LD_BUG
, "Couldn't generate extra-info descriptor.");
1378 ei
->cache_info
.signed_descriptor_len
=
1379 strlen(ei
->cache_info
.signed_descriptor_body
);
1380 router_get_extrainfo_hash(ei
->cache_info
.signed_descriptor_body
,
1381 ei
->cache_info
.signed_descriptor_digest
);
1383 /* Now finish the router descriptor. */
1384 memcpy(ri
->cache_info
.extra_info_digest
,
1385 ei
->cache_info
.signed_descriptor_digest
,
1387 ri
->cache_info
.signed_descriptor_body
= tor_malloc(8192);
1388 if (router_dump_router_to_string(ri
->cache_info
.signed_descriptor_body
, 8192,
1389 ri
, get_identity_key())<0) {
1390 log_warn(LD_BUG
, "Couldn't generate router descriptor.");
1393 ri
->cache_info
.signed_descriptor_len
=
1394 strlen(ri
->cache_info
.signed_descriptor_body
);
1397 options
->BridgeRelay
? ROUTER_PURPOSE_BRIDGE
: ROUTER_PURPOSE_GENERAL
;
1398 if (!options
->BridgeRelay
) {
1399 ri
->cache_info
.send_unencrypted
= 1;
1400 ei
->cache_info
.send_unencrypted
= 1;
1403 router_get_router_hash(ri
->cache_info
.signed_descriptor_body
,
1404 ri
->cache_info
.signed_descriptor_digest
);
1406 tor_assert(! routerinfo_incompatible_with_extrainfo(ri
, ei
, NULL
, NULL
));
1408 if (desc_routerinfo
)
1409 routerinfo_free(desc_routerinfo
);
1410 desc_routerinfo
= ri
;
1412 extrainfo_free(desc_extrainfo
);
1413 desc_extrainfo
= ei
;
1415 desc_clean_since
= time(NULL
);
1416 desc_needs_upload
= 1;
1417 control_event_my_descriptor_changed();
1421 /** Mark descriptor out of date if it's older than <b>when</b> */
1423 mark_my_descriptor_dirty_if_older_than(time_t when
)
1425 if (desc_clean_since
< when
)
1426 mark_my_descriptor_dirty();
1429 /** Call when the current descriptor is out of date. */
1431 mark_my_descriptor_dirty(void)
1433 desc_clean_since
= 0;
1436 /** How frequently will we republish our descriptor because of large (factor
1437 * of 2) shifts in estimated bandwidth? */
1438 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
1440 /** Check whether bandwidth has changed a lot since the last time we announced
1441 * bandwidth. If so, mark our descriptor dirty. */
1443 check_descriptor_bandwidth_changed(time_t now
)
1445 static time_t last_changed
= 0;
1447 if (!desc_routerinfo
)
1450 prev
= desc_routerinfo
->bandwidthcapacity
;
1451 cur
= we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
1452 if ((prev
!= cur
&& (!prev
|| !cur
)) ||
1455 if (last_changed
+MAX_BANDWIDTH_CHANGE_FREQ
< now
) {
1456 log_info(LD_GENERAL
,
1457 "Measured bandwidth has changed; rebuilding descriptor.");
1458 mark_my_descriptor_dirty();
1464 /** Note at log level severity that our best guess of address has changed from
1465 * <b>prev</b> to <b>cur</b>. */
1467 log_addr_has_changed(int severity
, uint32_t prev
, uint32_t cur
)
1469 char addrbuf_prev
[INET_NTOA_BUF_LEN
];
1470 char addrbuf_cur
[INET_NTOA_BUF_LEN
];
1471 struct in_addr in_prev
;
1472 struct in_addr in_cur
;
1474 in_prev
.s_addr
= htonl(prev
);
1475 tor_inet_ntoa(&in_prev
, addrbuf_prev
, sizeof(addrbuf_prev
));
1477 in_cur
.s_addr
= htonl(cur
);
1478 tor_inet_ntoa(&in_cur
, addrbuf_cur
, sizeof(addrbuf_cur
));
1481 log_fn(severity
, LD_GENERAL
,
1482 "Our IP Address has changed from %s to %s; "
1483 "rebuilding descriptor.",
1484 addrbuf_prev
, addrbuf_cur
);
1486 log_notice(LD_GENERAL
,
1487 "Guessed our IP address as %s.",
1491 /** Check whether our own address as defined by the Address configuration
1492 * has changed. This is for routers that get their address from a service
1493 * like dyndns. If our address has changed, mark our descriptor dirty. */
1495 check_descriptor_ipaddress_changed(time_t now
)
1498 or_options_t
*options
= get_options();
1501 if (!desc_routerinfo
)
1504 prev
= desc_routerinfo
->addr
;
1505 if (resolve_my_address(LOG_INFO
, options
, &cur
, NULL
) < 0) {
1506 log_info(LD_CONFIG
,"options->Address didn't resolve into an IP.");
1511 log_addr_has_changed(LOG_INFO
, prev
, cur
);
1512 ip_address_changed(0);
1516 /** The most recently guessed value of our IP address, based on directory
1518 static uint32_t last_guessed_ip
= 0;
1520 /** A directory server <b>d_conn</b> told us our IP address is
1521 * <b>suggestion</b>.
1522 * If this address is different from the one we think we are now, and
1523 * if our computer doesn't actually know its IP address, then switch. */
1525 router_new_address_suggestion(const char *suggestion
,
1526 const dir_connection_t
*d_conn
)
1528 uint32_t addr
, cur
= 0;
1530 or_options_t
*options
= get_options();
1532 /* first, learn what the IP address actually is */
1533 if (!tor_inet_aton(suggestion
, &in
)) {
1534 log_debug(LD_DIR
, "Malformed X-Your-Address-Is header %s. Ignoring.",
1535 escaped(suggestion
));
1538 addr
= ntohl(in
.s_addr
);
1540 log_debug(LD_DIR
, "Got X-Your-Address-Is: %s.", suggestion
);
1542 if (!server_mode(options
)) {
1543 last_guessed_ip
= addr
; /* store it in case we need it later */
1547 if (resolve_my_address(LOG_INFO
, options
, &cur
, NULL
) >= 0) {
1548 /* We're all set -- we already know our address. Great. */
1549 last_guessed_ip
= cur
; /* store it in case we need it later */
1552 if (is_internal_IP(addr
, 0)) {
1553 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1556 if (tor_addr_eq_ipv4h(&d_conn
->_base
.addr
, addr
)) {
1557 /* Don't believe anybody who says our IP is their IP. */
1558 log_debug(LD_DIR
, "A directory server told us our IP address is %s, "
1559 "but he's just reporting his own IP address. Ignoring.",
1564 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1565 * us an answer different from what we had the last time we managed to
1567 if (last_guessed_ip
!= addr
) {
1568 control_event_server_status(LOG_NOTICE
,
1569 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1571 log_addr_has_changed(LOG_NOTICE
, last_guessed_ip
, addr
);
1572 ip_address_changed(0);
1573 last_guessed_ip
= addr
; /* router_rebuild_descriptor() will fetch it */
1577 /** We failed to resolve our address locally, but we'd like to build
1578 * a descriptor and publish / test reachability. If we have a guess
1579 * about our address based on directory headers, answer it and return
1580 * 0; else return -1. */
1582 router_guess_address_from_dir_headers(uint32_t *guess
)
1584 if (last_guessed_ip
) {
1585 *guess
= last_guessed_ip
;
1591 extern const char tor_svn_revision
[]; /* from main.c */
1593 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1594 * string describing the version of Tor and the operating system we're
1595 * currently running on.
1598 get_platform_str(char *platform
, size_t len
)
1600 tor_snprintf(platform
, len
, "Tor %s on %s", get_version(), get_uname());
1603 /* XXX need to audit this thing and count fenceposts. maybe
1604 * refactor so we don't have to keep asking if we're
1605 * near the end of maxlen?
1607 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1609 /** OR only: Given a routerinfo for this router, and an identity key to sign
1610 * with, encode the routerinfo as a signed server descriptor and write the
1611 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1612 * failure, and the number of bytes used on success.
1615 router_dump_router_to_string(char *s
, size_t maxlen
, routerinfo_t
*router
,
1616 crypto_pk_env_t
*ident_key
)
1618 char *onion_pkey
; /* Onion key, PEM-encoded. */
1619 char *identity_pkey
; /* Identity key, PEM-encoded. */
1620 char digest
[DIGEST_LEN
];
1621 char published
[ISO_TIME_LEN
+1];
1622 char fingerprint
[FINGERPRINT_LEN
+1];
1623 char extra_info_digest
[HEX_DIGEST_LEN
+1];
1624 size_t onion_pkeylen
, identity_pkeylen
;
1627 addr_policy_t
*tmpe
;
1629 or_options_t
*options
= get_options();
1631 /* Make sure the identity key matches the one in the routerinfo. */
1632 if (crypto_pk_cmp_keys(ident_key
, router
->identity_pkey
)) {
1633 log_warn(LD_BUG
,"Tried to sign a router with a private key that didn't "
1634 "match router's public key!");
1638 /* record our fingerprint, so we can include it in the descriptor */
1639 if (crypto_pk_get_fingerprint(router
->identity_pkey
, fingerprint
, 1)<0) {
1640 log_err(LD_BUG
,"Error computing fingerprint");
1644 /* PEM-encode the onion key */
1645 if (crypto_pk_write_public_key_to_string(router
->onion_pkey
,
1646 &onion_pkey
,&onion_pkeylen
)<0) {
1647 log_warn(LD_BUG
,"write onion_pkey to string failed!");
1651 /* PEM-encode the identity key key */
1652 if (crypto_pk_write_public_key_to_string(router
->identity_pkey
,
1653 &identity_pkey
,&identity_pkeylen
)<0) {
1654 log_warn(LD_BUG
,"write identity_pkey to string failed!");
1655 tor_free(onion_pkey
);
1659 /* Encode the publication time. */
1660 format_iso_time(published
, router
->cache_info
.published_on
);
1662 if (router
->declared_family
&& smartlist_len(router
->declared_family
)) {
1664 char *family
= smartlist_join_strings(router
->declared_family
, " ", 0, &n
);
1665 n
+= strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1666 family_line
= tor_malloc(n
);
1667 tor_snprintf(family_line
, n
, "family %s\n", family
);
1670 family_line
= tor_strdup("");
1673 base16_encode(extra_info_digest
, sizeof(extra_info_digest
),
1674 router
->cache_info
.extra_info_digest
, DIGEST_LEN
);
1676 /* Generate the easy portion of the router descriptor. */
1677 result
= tor_snprintf(s
, maxlen
,
1678 "router %s %s %d 0 %d\n"
1680 "opt protocols Link 1 2 Circuit 1\n"
1682 "opt fingerprint %s\n"
1684 "bandwidth %d %d %d\n"
1685 "opt extra-info-digest %s\n%s"
1692 decide_to_advertise_dirport(options
, router
->dir_port
),
1696 stats_n_seconds_working
,
1697 (int) router
->bandwidthrate
,
1698 (int) router
->bandwidthburst
,
1699 (int) router
->bandwidthcapacity
,
1701 options
->DownloadExtraInfo
? "opt caches-extra-info\n" : "",
1702 onion_pkey
, identity_pkey
,
1704 we_are_hibernating() ? "opt hibernating 1\n" : "",
1705 (options
->DirPort
&& options
->HidServDirectoryV2
) ?
1706 "opt hidden-service-dir\n" : "");
1708 tor_free(family_line
);
1709 tor_free(onion_pkey
);
1710 tor_free(identity_pkey
);
1713 log_warn(LD_BUG
,"descriptor snprintf #1 ran out of room!");
1716 /* From now on, we use 'written' to remember the current length of 's'. */
1719 if (options
->ContactInfo
&& strlen(options
->ContactInfo
)) {
1720 const char *ci
= options
->ContactInfo
;
1721 if (strchr(ci
, '\n') || strchr(ci
, '\r'))
1723 result
= tor_snprintf(s
+written
,maxlen
-written
, "contact %s\n", ci
);
1725 log_warn(LD_BUG
,"descriptor snprintf #2 ran out of room!");
1731 /* Write the exit policy to the end of 's'. */
1732 if (dns_seems_to_be_broken() ||
1733 !router
->exit_policy
|| !smartlist_len(router
->exit_policy
)) {
1734 /* DNS is screwed up; don't claim to be an exit. */
1735 strlcat(s
+written
, "reject *:*\n", maxlen
-written
);
1736 written
+= strlen("reject *:*\n");
1738 } else if (router
->exit_policy
) {
1740 for (i
= 0; i
< smartlist_len(router
->exit_policy
); ++i
) {
1741 tmpe
= smartlist_get(router
->exit_policy
, i
);
1742 result
= policy_write_item(s
+written
, maxlen
-written
, tmpe
, 1);
1744 log_warn(LD_BUG
,"descriptor policy_write_item ran out of room!");
1747 tor_assert(result
== (int)strlen(s
+written
));
1749 if (written
+2 > maxlen
) {
1750 log_warn(LD_BUG
,"descriptor policy_write_item ran out of room (2)!");
1753 s
[written
++] = '\n';
1757 if (written
+256 > maxlen
) { /* Not enough room for signature. */
1758 log_warn(LD_BUG
,"not enough room left in descriptor for signature!");
1762 /* Sign the directory */
1763 strlcpy(s
+written
, "router-signature\n", maxlen
-written
);
1764 written
+= strlen(s
+written
);
1766 if (router_get_router_hash(s
, digest
) < 0) {
1770 note_crypto_pk_op(SIGN_RTR
);
1771 if (router_append_dirobj_signature(s
+written
,maxlen
-written
,
1772 digest
,ident_key
)<0) {
1773 log_warn(LD_BUG
, "Couldn't sign router descriptor");
1776 written
+= strlen(s
+written
);
1778 if (written
+2 > maxlen
) {
1779 log_warn(LD_BUG
,"Not enough room to finish descriptor.");
1782 /* include a last '\n' */
1786 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1790 routerinfo_t
*ri_tmp
;
1791 cp
= s_dup
= tor_strdup(s
);
1792 ri_tmp
= router_parse_entry_from_string(cp
, NULL
, 1, 0, NULL
);
1795 "We just generated a router descriptor we can't parse.");
1796 log_err(LD_BUG
, "Descriptor was: <<%s>>", s
);
1800 routerinfo_free(ri_tmp
);
1804 return (int)written
+1;
1807 /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
1808 * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
1809 * negative on failure. */
1811 extrainfo_dump_to_string(char *s
, size_t maxlen
, extrainfo_t
*extrainfo
,
1812 crypto_pk_env_t
*ident_key
)
1814 or_options_t
*options
= get_options();
1815 char identity
[HEX_DIGEST_LEN
+1];
1816 char published
[ISO_TIME_LEN
+1];
1817 char digest
[DIGEST_LEN
];
1818 char *bandwidth_usage
;
1822 base16_encode(identity
, sizeof(identity
),
1823 extrainfo
->cache_info
.identity_digest
, DIGEST_LEN
);
1824 format_iso_time(published
, extrainfo
->cache_info
.published_on
);
1825 bandwidth_usage
= rep_hist_get_bandwidth_lines(1);
1827 result
= tor_snprintf(s
, maxlen
,
1828 "extra-info %s %s\n"
1830 extrainfo
->nickname
, identity
,
1831 published
, bandwidth_usage
);
1832 tor_free(bandwidth_usage
);
1836 if (should_record_bridge_info(options
)) {
1837 static time_t last_purged_at
= 0;
1838 char *geoip_summary
;
1839 time_t now
= time(NULL
);
1840 int geoip_purge_interval
= 48*60*60;
1841 #ifdef ENABLE_GEOIP_STATS
1842 if (get_options()->DirRecordUsageByCountry
)
1843 geoip_purge_interval
= get_options()->DirRecordUsageRetainIPs
;
1845 if (now
> last_purged_at
+geoip_purge_interval
) {
1846 geoip_remove_old_clients(now
-geoip_purge_interval
);
1847 last_purged_at
= now
;
1849 geoip_summary
= geoip_get_client_history(time(NULL
), GEOIP_CLIENT_CONNECT
);
1850 if (geoip_summary
) {
1851 char geoip_start
[ISO_TIME_LEN
+1];
1852 format_iso_time(geoip_start
, geoip_get_history_start());
1853 result
= tor_snprintf(s
+strlen(s
), maxlen
-strlen(s
),
1854 "geoip-start-time %s\n"
1855 "geoip-client-origins %s\n",
1856 geoip_start
, geoip_summary
);
1857 tor_free(geoip_summary
);
1864 strlcat(s
+len
, "router-signature\n", maxlen
-len
);
1865 len
+= strlen(s
+len
);
1866 if (router_get_extrainfo_hash(s
, digest
)<0)
1868 if (router_append_dirobj_signature(s
+len
, maxlen
-len
, digest
, ident_key
)<0)
1871 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1874 extrainfo_t
*ei_tmp
;
1875 cp
= s_dup
= tor_strdup(s
);
1876 ei_tmp
= extrainfo_parse_entry_from_string(cp
, NULL
, 1, NULL
);
1879 "We just generated an extrainfo descriptor we can't parse.");
1880 log_err(LD_BUG
, "Descriptor was: <<%s>>", s
);
1884 extrainfo_free(ei_tmp
);
1888 return (int)strlen(s
)+1;
1891 /** Return true iff <b>s</b> is a legally valid server nickname. */
1893 is_legal_nickname(const char *s
)
1898 return len
> 0 && len
<= MAX_NICKNAME_LEN
&&
1899 strspn(s
,LEGAL_NICKNAME_CHARACTERS
) == len
;
1902 /** Return true iff <b>s</b> is a legally valid server nickname or
1903 * hex-encoded identity-key digest. */
1905 is_legal_nickname_or_hexdigest(const char *s
)
1908 return is_legal_nickname(s
);
1910 return is_legal_hexdigest(s
);
1913 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
1916 is_legal_hexdigest(const char *s
)
1920 if (s
[0] == '$') s
++;
1922 if (len
> HEX_DIGEST_LEN
) {
1923 if (s
[HEX_DIGEST_LEN
] == '=' ||
1924 s
[HEX_DIGEST_LEN
] == '~') {
1925 if (!is_legal_nickname(s
+HEX_DIGEST_LEN
+1))
1931 return (len
>= HEX_DIGEST_LEN
&&
1932 strspn(s
,HEX_CHARACTERS
)==HEX_DIGEST_LEN
);
1935 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
1936 * verbose representation of the identity of <b>router</b>. The format is:
1938 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
1939 * A "=" if the router is named; a "~" if it is not.
1940 * The router's nickname.
1943 router_get_verbose_nickname(char *buf
, routerinfo_t
*router
)
1946 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, router
->cache_info
.identity_digest
,
1948 buf
[1+HEX_DIGEST_LEN
] = router
->is_named
? '=' : '~';
1949 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, router
->nickname
, MAX_NICKNAME_LEN
+1);
1952 /** Forget that we have issued any router-related warnings, so that we'll
1953 * warn again if we see the same errors. */
1955 router_reset_warnings(void)
1957 if (warned_nonexistent_family
) {
1958 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
1959 smartlist_clear(warned_nonexistent_family
);
1963 /** Given a router purpose, convert it to a string. Don't call this on
1964 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
1965 * know its string representation. */
1967 router_purpose_to_string(uint8_t p
)
1971 case ROUTER_PURPOSE_GENERAL
: return "general";
1972 case ROUTER_PURPOSE_BRIDGE
: return "bridge";
1973 case ROUTER_PURPOSE_CONTROLLER
: return "controller";
1980 /** Given a string, convert it to a router purpose. */
1982 router_purpose_from_string(const char *s
)
1984 if (!strcmp(s
, "general"))
1985 return ROUTER_PURPOSE_GENERAL
;
1986 else if (!strcmp(s
, "bridge"))
1987 return ROUTER_PURPOSE_BRIDGE
;
1988 else if (!strcmp(s
, "controller"))
1989 return ROUTER_PURPOSE_CONTROLLER
;
1991 return ROUTER_PURPOSE_UNKNOWN
;
1994 /** Release all static resources held in router.c */
1996 router_free_all(void)
1999 crypto_free_pk_env(onionkey
);
2001 crypto_free_pk_env(lastonionkey
);
2003 crypto_free_pk_env(identitykey
);
2005 tor_mutex_free(key_lock
);
2006 if (desc_routerinfo
)
2007 routerinfo_free(desc_routerinfo
);
2009 extrainfo_free(desc_extrainfo
);
2010 if (authority_signing_key
)
2011 crypto_free_pk_env(authority_signing_key
);
2012 if (authority_key_certificate
)
2013 authority_cert_free(authority_key_certificate
);
2014 if (legacy_signing_key
)
2015 crypto_free_pk_env(legacy_signing_key
);
2016 if (legacy_key_certificate
)
2017 authority_cert_free(legacy_key_certificate
);
2019 if (warned_nonexistent_family
) {
2020 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
2021 smartlist_free(warned_nonexistent_family
);