1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2010, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
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
);
65 crypto_free_pk_env(onionkey
);
67 onionkey_set_at
= time(NULL
);
68 tor_mutex_release(key_lock
);
69 mark_my_descriptor_dirty();
72 /** Return the current onion key. Requires that the onion key has been
73 * loaded or generated. */
81 /** Store a full copy of the current onion key into *<b>key</b>, and a full
82 * copy of the most recent onion key into *<b>last</b>.
85 dup_onion_keys(crypto_pk_env_t
**key
, crypto_pk_env_t
**last
)
89 tor_mutex_acquire(key_lock
);
91 *key
= crypto_pk_copy_full(onionkey
);
93 *last
= crypto_pk_copy_full(lastonionkey
);
96 tor_mutex_release(key_lock
);
99 /** Return the time when the onion key was last set. This is either the time
100 * when the process launched, or the time of the most recent key rotation since
101 * the process launched.
104 get_onion_key_set_at(void)
106 return onionkey_set_at
;
109 /** Set the current identity key to k.
112 set_identity_key(crypto_pk_env_t
*k
)
115 crypto_free_pk_env(identitykey
);
117 crypto_pk_get_digest(identitykey
, identitykey_digest
);
120 /** Returns the current identity key; requires that the identity key has been
124 get_identity_key(void)
126 tor_assert(identitykey
);
130 /** Return true iff the identity key has been set. */
132 identity_key_is_set(void)
134 return identitykey
!= NULL
;
137 /** Return the key certificate for this v3 (voting) authority, or NULL
138 * if we have no such certificate. */
140 get_my_v3_authority_cert(void)
142 return authority_key_certificate
;
145 /** Return the v3 signing key for this v3 (voting) authority, or NULL
146 * if we have no such key. */
148 get_my_v3_authority_signing_key(void)
150 return authority_signing_key
;
153 /** If we're an authority, and we're using a legacy authority identity key for
154 * emergency migration purposes, return the certificate associated with that
157 get_my_v3_legacy_cert(void)
159 return legacy_key_certificate
;
162 /** If we're an authority, and we're using a legacy authority identity key for
163 * emergency migration purposes, return that key. */
165 get_my_v3_legacy_signing_key(void)
167 return legacy_signing_key
;
170 /** Replace the previous onion key with the current onion key, and generate
171 * a new previous onion key. Immediately after calling this function,
173 * - schedule all previous cpuworkers to shut down _after_ processing
174 * pending work. (This will cause fresh cpuworkers to be generated.)
175 * - generate and upload a fresh routerinfo.
178 rotate_onion_key(void)
180 char *fname
, *fname_prev
;
181 crypto_pk_env_t
*prkey
;
182 or_state_t
*state
= get_or_state();
184 fname
= get_datadir_fname2("keys", "secret_onion_key");
185 fname_prev
= get_datadir_fname2("keys", "secret_onion_key.old");
186 if (!(prkey
= crypto_new_pk_env())) {
187 log_err(LD_GENERAL
,"Error constructing rotated onion key");
190 if (crypto_pk_generate_key(prkey
)) {
191 log_err(LD_BUG
,"Error generating onion key");
194 if (file_status(fname
) == FN_FILE
) {
195 if (replace_file(fname
, fname_prev
))
198 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
199 log_err(LD_FS
,"Couldn't write generated onion key to \"%s\".", fname
);
202 log_info(LD_GENERAL
, "Rotating onion key");
203 tor_mutex_acquire(key_lock
);
205 crypto_free_pk_env(lastonionkey
);
206 lastonionkey
= onionkey
;
209 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
210 tor_mutex_release(key_lock
);
211 mark_my_descriptor_dirty();
212 or_state_mark_dirty(state
, get_options()->AvoidDiskWrites
? now
+3600 : 0);
215 log_warn(LD_GENERAL
, "Couldn't rotate onion key.");
217 crypto_free_pk_env(prkey
);
220 tor_free(fname_prev
);
223 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
224 * and <b>generate</b> is true, create a new RSA key and save it in
225 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
226 * errors at level <b>severity</b>.
229 init_key_from_file(const char *fname
, int generate
, int severity
)
231 crypto_pk_env_t
*prkey
= NULL
;
233 if (!(prkey
= crypto_new_pk_env())) {
234 log(severity
, LD_GENERAL
,"Error constructing key");
238 switch (file_status(fname
)) {
241 log(severity
, LD_FS
,"Can't read key from \"%s\"", fname
);
245 if (!have_lockfile()) {
246 if (try_locking(get_options(), 0)<0) {
247 /* Make sure that --list-fingerprint only creates new keys
248 * if there is no possibility for a deadlock. */
249 log(severity
, LD_FS
, "Another Tor process has locked \"%s\". Not "
250 "writing any new keys.", fname
);
251 /*XXXX The 'other process' might make a key in a second or two;
252 * maybe we should wait for it. */
256 log_info(LD_GENERAL
, "No key found in \"%s\"; generating fresh key.",
258 if (crypto_pk_generate_key(prkey
)) {
259 log(severity
, LD_GENERAL
,"Error generating onion key");
262 if (crypto_pk_check_key(prkey
) <= 0) {
263 log(severity
, LD_GENERAL
,"Generated key seems invalid");
266 log_info(LD_GENERAL
, "Generated key seems valid");
267 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
269 "Couldn't write generated key to \"%s\".", fname
);
273 log_info(LD_GENERAL
, "No key found in \"%s\"", fname
);
277 if (crypto_pk_read_private_key_from_filename(prkey
, fname
)) {
278 log(severity
, LD_GENERAL
,"Error loading private key.");
288 crypto_free_pk_env(prkey
);
292 /** Try to load the vote-signing private key and certificate for being a v3
293 * directory authority, and make sure they match. If <b>legacy</b>, load a
294 * legacy key/cert set for emergency key migration; otherwise load the regular
295 * key/cert set. On success, store them into *<b>key_out</b> and
296 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
298 load_authority_keyset(int legacy
, crypto_pk_env_t
**key_out
,
299 authority_cert_t
**cert_out
)
302 char *fname
= NULL
, *cert
= NULL
;
303 const char *eos
= NULL
;
304 crypto_pk_env_t
*signing_key
= NULL
;
305 authority_cert_t
*parsed
= NULL
;
307 fname
= get_datadir_fname2("keys",
308 legacy
? "legacy_signing_key" : "authority_signing_key");
309 signing_key
= init_key_from_file(fname
, 0, LOG_INFO
);
311 log_warn(LD_DIR
, "No version 3 directory key found in %s", fname
);
315 fname
= get_datadir_fname2("keys",
316 legacy
? "legacy_certificate" : "authority_certificate");
317 cert
= read_file_to_str(fname
, 0, NULL
);
319 log_warn(LD_DIR
, "Signing key found, but no certificate found in %s",
323 parsed
= authority_cert_parse_from_string(cert
, &eos
);
325 log_warn(LD_DIR
, "Unable to parse certificate in %s", fname
);
328 if (crypto_pk_cmp_keys(signing_key
, parsed
->signing_key
) != 0) {
329 log_warn(LD_DIR
, "Stored signing key does not match signing key in "
335 crypto_free_pk_env(*key_out
);
337 authority_cert_free(*cert_out
);
338 *key_out
= signing_key
;
348 crypto_free_pk_env(signing_key
);
350 authority_cert_free(parsed
);
354 /** Load the v3 (voting) authority signing key and certificate, if they are
355 * present. Return -1 if anything is missing, mismatched, or unloadable;
356 * return 0 on success. */
358 init_v3_authority_keys(void)
360 if (load_authority_keyset(0, &authority_signing_key
,
361 &authority_key_certificate
)<0)
364 if (get_options()->V3AuthUseLegacyKey
&&
365 load_authority_keyset(1, &legacy_signing_key
,
366 &legacy_key_certificate
)<0)
372 /** If we're a v3 authority, check whether we have a certificate that's
373 * likely to expire soon. Warn if we do, but not too often. */
375 v3_authority_check_key_expiry(void)
378 static time_t last_warned
= 0;
379 int badness
, time_left
, warn_interval
;
380 if (!authdir_mode_v3(get_options()) || !authority_key_certificate
)
384 expires
= authority_key_certificate
->expires
;
385 time_left
= (int)( expires
- now
);
386 if (time_left
<= 0) {
388 warn_interval
= 60*60;
389 } else if (time_left
<= 24*60*60) {
391 warn_interval
= 60*60;
392 } else if (time_left
<= 24*60*60*7) {
394 warn_interval
= 24*60*60;
395 } else if (time_left
<= 24*60*60*30) {
397 warn_interval
= 24*60*60*5;
402 if (last_warned
+ warn_interval
> now
)
405 if (time_left
<= 0) {
406 log(badness
, LD_DIR
, "Your v3 authority certificate has expired."
407 " Generate a new one NOW.");
408 } else if (time_left
<= 24*60*60) {
409 log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d hours;"
410 " Generate a new one NOW.", time_left
/(60*60));
412 log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d days;"
413 " Generate a new one soon.", time_left
/(24*60*60));
418 /** Initialize all OR private keys, and the TLS context, as necessary.
419 * On OPs, this only initializes the tls context. Return 0 on success,
420 * or -1 if Tor should die.
426 char fingerprint
[FINGERPRINT_LEN
+1];
427 /*nickname<space>fp\n\0 */
428 char fingerprint_line
[MAX_NICKNAME_LEN
+FINGERPRINT_LEN
+3];
430 crypto_pk_env_t
*prkey
;
434 or_options_t
*options
= get_options();
435 authority_type_t type
;
436 time_t now
= time(NULL
);
437 trusted_dir_server_t
*ds
;
438 int v3_digest_set
= 0;
439 authority_cert_t
*cert
= NULL
;
442 key_lock
= tor_mutex_new();
444 /* There are a couple of paths that put us here before */
445 if (crypto_global_init(get_options()->HardwareAccel
)) {
446 log_err(LD_BUG
, "Unable to initialize OpenSSL. Exiting.");
450 /* OP's don't need persistent keys; just make up an identity and
451 * initialize the TLS context. */
452 if (!server_mode(options
)) {
453 if (!(prkey
= crypto_new_pk_env()))
455 if (crypto_pk_generate_key(prkey
)) {
456 crypto_free_pk_env(prkey
);
459 set_identity_key(prkey
);
460 /* Create a TLS context; default the client nickname to "client". */
461 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME
) < 0) {
462 log_err(LD_GENERAL
,"Error creating TLS context for Tor client.");
467 /* Make sure DataDirectory exists, and is private. */
468 if (check_private_dir(options
->DataDirectory
, CPD_CREATE
)) {
471 /* Check the key directory. */
472 keydir
= get_datadir_fname("keys");
473 if (check_private_dir(keydir
, CPD_CREATE
)) {
479 /* 1a. Read v3 directory authority key/cert information. */
480 memset(v3_digest
, 0, sizeof(v3_digest
));
481 if (authdir_mode_v3(options
)) {
482 if (init_v3_authority_keys()<0) {
483 log_err(LD_GENERAL
, "We're configured as a V3 authority, but we "
484 "were unable to load our v3 authority keys and certificate! "
485 "Use tor-gencert to generate them. Dying.");
488 cert
= get_my_v3_authority_cert();
490 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key
,
496 /* 1. Read identity key. Make it if none is found. */
497 keydir
= get_datadir_fname2("keys", "secret_id_key");
498 log_info(LD_GENERAL
,"Reading/making identity key \"%s\"...",keydir
);
499 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
501 if (!prkey
) return -1;
502 set_identity_key(prkey
);
504 /* 2. Read onion key. Make it if none is found. */
505 keydir
= get_datadir_fname2("keys", "secret_onion_key");
506 log_info(LD_GENERAL
,"Reading/making onion key \"%s\"...",keydir
);
507 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
509 if (!prkey
) return -1;
510 set_onion_key(prkey
);
511 if (options
->command
== CMD_RUN_TOR
) {
512 /* only mess with the state file if we're actually running Tor */
513 or_state_t
*state
= get_or_state();
514 if (state
->LastRotatedOnionKey
> 100 && state
->LastRotatedOnionKey
< now
) {
515 /* We allow for some parsing slop, but we don't want to risk accepting
516 * values in the distant future. If we did, we might never rotate the
518 onionkey_set_at
= state
->LastRotatedOnionKey
;
520 /* We have no LastRotatedOnionKey set; either we just created the key
521 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
522 * start the clock ticking now so that we will eventually rotate it even
523 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
524 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
525 or_state_mark_dirty(state
, options
->AvoidDiskWrites
?
526 time(NULL
)+3600 : 0);
530 keydir
= get_datadir_fname2("keys", "secret_onion_key.old");
531 if (!lastonionkey
&& file_status(keydir
) == FN_FILE
) {
532 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
534 lastonionkey
= prkey
;
538 /* 3. Initialize link key and TLS context. */
539 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME
) < 0) {
540 log_err(LD_GENERAL
,"Error initializing TLS context");
543 /* 4. Build our router descriptor. */
544 /* Must be called after keys are initialized. */
545 mydesc
= router_get_my_descriptor();
546 if (authdir_mode(options
)) {
547 const char *m
= NULL
;
549 /* We need to add our own fingerprint so it gets recognized. */
550 if (dirserv_add_own_fingerprint(options
->Nickname
, get_identity_key())) {
551 log_err(LD_GENERAL
,"Error adding own fingerprint to approved set");
555 ri
= router_parse_entry_from_string(mydesc
, NULL
, 1, 0, NULL
);
557 log_err(LD_GENERAL
,"Generated a routerinfo we couldn't parse.");
560 if (!WRA_WAS_ADDED(dirserv_add_descriptor(ri
, &m
, "self"))) {
561 log_err(LD_GENERAL
,"Unable to add own descriptor to directory: %s",
562 m
?m
:"<unknown error>");
568 /* 5. Dump fingerprint to 'fingerprint' */
569 keydir
= get_datadir_fname("fingerprint");
570 log_info(LD_GENERAL
,"Dumping fingerprint to \"%s\"...",keydir
);
571 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint
, 0)<0) {
572 log_err(LD_GENERAL
,"Error computing fingerprint");
576 tor_assert(strlen(options
->Nickname
) <= MAX_NICKNAME_LEN
);
577 if (tor_snprintf(fingerprint_line
, sizeof(fingerprint_line
),
578 "%s %s\n",options
->Nickname
, fingerprint
) < 0) {
579 log_err(LD_GENERAL
,"Error writing fingerprint line");
583 /* Check whether we need to write the fingerprint file. */
585 if (file_status(keydir
) == FN_FILE
)
586 cp
= read_file_to_str(keydir
, 0, NULL
);
587 if (!cp
|| strcmp(cp
, fingerprint_line
)) {
588 if (write_str_to_file(keydir
, fingerprint_line
, 0)) {
589 log_err(LD_FS
, "Error writing fingerprint line to file");
598 log(LOG_NOTICE
, LD_GENERAL
,
599 "Your Tor server's identity key fingerprint is '%s %s'",
600 options
->Nickname
, fingerprint
);
601 if (!authdir_mode(options
))
603 /* 6. [authdirserver only] load approved-routers file */
604 if (dirserv_load_fingerprint_file() < 0) {
605 log_err(LD_GENERAL
,"Error loading fingerprints");
608 /* 6b. [authdirserver only] add own key to approved directories. */
609 crypto_pk_get_digest(get_identity_key(), digest
);
610 type
= ((options
->V1AuthoritativeDir
? V1_AUTHORITY
: NO_AUTHORITY
) |
611 (options
->V2AuthoritativeDir
? V2_AUTHORITY
: NO_AUTHORITY
) |
612 (options
->V3AuthoritativeDir
? V3_AUTHORITY
: NO_AUTHORITY
) |
613 (options
->BridgeAuthoritativeDir
? BRIDGE_AUTHORITY
: NO_AUTHORITY
) |
614 (options
->HSAuthoritativeDir
? HIDSERV_AUTHORITY
: NO_AUTHORITY
));
616 ds
= router_get_trusteddirserver_by_digest(digest
);
618 ds
= add_trusted_dir_server(options
->Nickname
, NULL
,
619 (uint16_t)options
->DirPort
,
620 (uint16_t)options
->ORPort
,
625 log_err(LD_GENERAL
,"We want to be a directory authority, but we "
626 "couldn't add ourselves to the authority list. Failing.");
630 if (ds
->type
!= type
) {
631 log_warn(LD_DIR
, "Configured authority type does not match authority "
632 "type in DirServer list. Adjusting. (%d v %d)",
636 if (v3_digest_set
&& (ds
->type
& V3_AUTHORITY
) &&
637 memcmp(v3_digest
, ds
->v3_identity_digest
, DIGEST_LEN
)) {
638 log_warn(LD_DIR
, "V3 identity key does not match identity declared in "
639 "DirServer line. Adjusting.");
640 memcpy(ds
->v3_identity_digest
, v3_digest
, DIGEST_LEN
);
643 if (cert
) { /* add my own cert to the list of known certs */
644 log_info(LD_DIR
, "adding my own v3 cert");
645 if (trusted_dirs_load_certs_from_string(
646 cert
->cache_info
.signed_descriptor_body
, 0, 0)<0) {
647 log_warn(LD_DIR
, "Unable to parse my own v3 cert! Failing.");
652 return 0; /* success */
655 /* Keep track of whether we should upload our server descriptor,
656 * and what type of server we are.
659 /** Whether we can reach our ORPort from the outside. */
660 static int can_reach_or_port
= 0;
661 /** Whether we can reach our DirPort from the outside. */
662 static int can_reach_dir_port
= 0;
664 /** Forget what we have learned about our reachability status. */
666 router_reset_reachability(void)
668 can_reach_or_port
= can_reach_dir_port
= 0;
671 /** Return 1 if ORPort is known reachable; else return 0. */
673 check_whether_orport_reachable(void)
675 or_options_t
*options
= get_options();
676 return options
->AssumeReachable
||
680 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
682 check_whether_dirport_reachable(void)
684 or_options_t
*options
= get_options();
685 return !options
->DirPort
||
686 options
->AssumeReachable
||
687 we_are_hibernating() ||
691 /** Look at a variety of factors, and return 0 if we don't want to
692 * advertise the fact that we have a DirPort open. Else return the
693 * DirPort we want to advertise.
695 * Log a helpful message if we change our mind about whether to publish
699 decide_to_advertise_dirport(or_options_t
*options
, uint16_t dir_port
)
701 static int advertising
=1; /* start out assuming we will advertise */
703 const char *reason
= NULL
;
705 /* Section one: reasons to publish or not publish that aren't
706 * worth mentioning to the user, either because they're obvious
707 * or because they're normal behavior. */
709 if (!dir_port
) /* short circuit the rest of the function */
711 if (authdir_mode(options
)) /* always publish */
713 if (we_are_hibernating())
715 if (!check_whether_dirport_reachable())
718 /* Section two: reasons to publish or not publish that the user
719 * might find surprising. These are generally config options that
720 * make us choose not to publish. */
722 if (accounting_is_enabled(options
)) {
723 /* if we might potentially hibernate */
725 reason
= "AccountingMax enabled";
726 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
727 } else if (options
->BandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
||
728 (options
->RelayBandwidthRate
> 0 &&
729 options
->RelayBandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
)) {
730 /* if we're advertising a small amount */
732 reason
= "BandwidthRate under 50KB";
735 if (advertising
!= new_choice
) {
736 if (new_choice
== 1) {
737 log(LOG_NOTICE
, LD_DIR
, "Advertising DirPort as %d", dir_port
);
740 log(LOG_NOTICE
, LD_DIR
, "Not advertising DirPort (Reason: %s)", reason
);
742 advertising
= new_choice
;
745 return advertising
? dir_port
: 0;
748 /** Some time has passed, or we just got new directory information.
749 * See if we currently believe our ORPort or DirPort to be
750 * unreachable. If so, launch a new test for it.
752 * For ORPort, we simply try making a circuit that ends at ourselves.
753 * Success is noticed in onionskin_answer().
755 * For DirPort, we make a connection via Tor to our DirPort and ask
756 * for our own server descriptor.
757 * Success is noticed in connection_dir_client_reached_eof().
760 consider_testing_reachability(int test_or
, int test_dir
)
762 routerinfo_t
*me
= router_get_my_routerinfo();
763 int orport_reachable
= check_whether_orport_reachable();
768 if (test_or
&& (!orport_reachable
|| !circuit_enough_testing_circs())) {
769 log_info(LD_CIRC
, "Testing %s of my ORPort: %s:%d.",
770 !orport_reachable
? "reachability" : "bandwidth",
771 me
->address
, me
->or_port
);
772 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING
, me
,
773 CIRCLAUNCH_NEED_CAPACITY
|CIRCLAUNCH_IS_INTERNAL
);
776 tor_addr_from_ipv4h(&addr
, me
->addr
);
777 if (test_dir
&& !check_whether_dirport_reachable() &&
778 !connection_get_by_type_addr_port_purpose(
779 CONN_TYPE_DIR
, &addr
, me
->dir_port
,
780 DIR_PURPOSE_FETCH_SERVERDESC
)) {
781 /* ask myself, via tor, for my server descriptor. */
782 directory_initiate_command(me
->address
, &addr
,
783 me
->or_port
, me
->dir_port
,
784 0, /* does not matter */
785 0, me
->cache_info
.identity_digest
,
786 DIR_PURPOSE_FETCH_SERVERDESC
,
787 ROUTER_PURPOSE_GENERAL
,
788 1, "authority.z", NULL
, 0, 0);
792 /** Annotate that we found our ORPort reachable. */
794 router_orport_found_reachable(void)
796 if (!can_reach_or_port
) {
797 routerinfo_t
*me
= router_get_my_routerinfo();
798 log_notice(LD_OR
,"Self-testing indicates your ORPort is reachable from "
799 "the outside. Excellent.%s",
800 get_options()->_PublishServerDescriptor
!= NO_AUTHORITY
?
801 " Publishing server descriptor." : "");
802 can_reach_or_port
= 1;
803 mark_my_descriptor_dirty();
804 if (!me
) { /* should never happen */
805 log_warn(LD_BUG
, "ORPort found reachable, but I have no routerinfo "
806 "yet. Failing to inform controller of success.");
809 control_event_server_status(LOG_NOTICE
,
810 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
811 me
->address
, me
->or_port
);
815 /** Annotate that we found our DirPort reachable. */
817 router_dirport_found_reachable(void)
819 if (!can_reach_dir_port
) {
820 routerinfo_t
*me
= router_get_my_routerinfo();
821 log_notice(LD_DIRSERV
,"Self-testing indicates your DirPort is reachable "
822 "from the outside. Excellent.");
823 can_reach_dir_port
= 1;
824 if (!me
|| decide_to_advertise_dirport(get_options(), me
->dir_port
))
825 mark_my_descriptor_dirty();
826 if (!me
) { /* should never happen */
827 log_warn(LD_BUG
, "DirPort found reachable, but I have no routerinfo "
828 "yet. Failing to inform controller of success.");
831 control_event_server_status(LOG_NOTICE
,
832 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
833 me
->address
, me
->dir_port
);
837 /** We have enough testing circuits open. Send a bunch of "drop"
838 * cells down each of them, to exercise our bandwidth. */
840 router_perform_bandwidth_test(int num_circs
, time_t now
)
842 int num_cells
= (int)(get_options()->BandwidthRate
* 10 / CELL_NETWORK_SIZE
);
843 int max_cells
= num_cells
< CIRCWINDOW_START
?
844 num_cells
: CIRCWINDOW_START
;
845 int cells_per_circuit
= max_cells
/ num_circs
;
846 origin_circuit_t
*circ
= NULL
;
848 log_notice(LD_OR
,"Performing bandwidth self-test...done.");
849 while ((circ
= circuit_get_next_by_pk_and_purpose(circ
, NULL
,
850 CIRCUIT_PURPOSE_TESTING
))) {
851 /* dump cells_per_circuit drop cells onto this circ */
852 int i
= cells_per_circuit
;
853 if (circ
->_base
.state
!= CIRCUIT_STATE_OPEN
)
855 circ
->_base
.timestamp_dirty
= now
;
857 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
859 NULL
, 0, circ
->cpath
->prev
)<0) {
860 return; /* stop if error */
866 /** Return true iff we believe ourselves to be an authoritative
870 authdir_mode(or_options_t
*options
)
872 return options
->AuthoritativeDir
!= 0;
874 /** Return true iff we believe ourselves to be a v1 authoritative
878 authdir_mode_v1(or_options_t
*options
)
880 return authdir_mode(options
) && options
->V1AuthoritativeDir
!= 0;
882 /** Return true iff we believe ourselves to be a v2 authoritative
886 authdir_mode_v2(or_options_t
*options
)
888 return authdir_mode(options
) && options
->V2AuthoritativeDir
!= 0;
890 /** Return true iff we believe ourselves to be a v3 authoritative
894 authdir_mode_v3(or_options_t
*options
)
896 return authdir_mode(options
) && options
->V3AuthoritativeDir
!= 0;
898 /** Return true iff we are a v1, v2, or v3 directory authority. */
900 authdir_mode_any_main(or_options_t
*options
)
902 return options
->V1AuthoritativeDir
||
903 options
->V2AuthoritativeDir
||
904 options
->V3AuthoritativeDir
;
906 /** Return true if we believe ourselves to be any kind of
907 * authoritative directory beyond just a hidserv authority. */
909 authdir_mode_any_nonhidserv(or_options_t
*options
)
911 return options
->BridgeAuthoritativeDir
||
912 authdir_mode_any_main(options
);
914 /** Return true iff we are an authoritative directory server that is
915 * authoritative about receiving and serving descriptors of type
916 * <b>purpose</b> its dirport. Use -1 for "any purpose". */
918 authdir_mode_handles_descs(or_options_t
*options
, int purpose
)
921 return authdir_mode_any_nonhidserv(options
);
922 else if (purpose
== ROUTER_PURPOSE_GENERAL
)
923 return authdir_mode_any_main(options
);
924 else if (purpose
== ROUTER_PURPOSE_BRIDGE
)
925 return (options
->BridgeAuthoritativeDir
);
929 /** Return true iff we are an authoritative directory server that
930 * publishes its own network statuses.
933 authdir_mode_publishes_statuses(or_options_t
*options
)
935 if (authdir_mode_bridge(options
))
937 return authdir_mode_any_nonhidserv(options
);
939 /** Return true iff we are an authoritative directory server that
940 * tests reachability of the descriptors it learns about.
943 authdir_mode_tests_reachability(or_options_t
*options
)
945 return authdir_mode_handles_descs(options
, -1);
947 /** Return true iff we believe ourselves to be a bridge authoritative
951 authdir_mode_bridge(or_options_t
*options
)
953 return authdir_mode(options
) && options
->BridgeAuthoritativeDir
!= 0;
956 /** Return true iff we are trying to be a server.
959 server_mode(or_options_t
*options
)
961 if (options
->ClientOnly
) return 0;
962 return (options
->ORPort
!= 0 || options
->ORListenAddress
);
965 /** Remember if we've advertised ourselves to the dirservers. */
966 static int server_is_advertised
=0;
968 /** Return true iff we have published our descriptor lately.
971 advertised_server_mode(void)
973 return server_is_advertised
;
977 * Called with a boolean: set whether we have recently published our
981 set_server_advertised(int s
)
983 server_is_advertised
= s
;
986 /** Return true iff we are trying to be a socks proxy. */
988 proxy_mode(or_options_t
*options
)
990 return (options
->SocksPort
!= 0 || options
->SocksListenAddress
||
991 options
->TransPort
!= 0 || options
->TransListenAddress
||
992 options
->NatdPort
!= 0 || options
->NatdListenAddress
||
993 options
->DNSPort
!= 0 || options
->DNSListenAddress
);
996 /** Decide if we're a publishable server. We are a publishable server if:
997 * - We don't have the ClientOnly option set
999 * - We have the PublishServerDescriptor option set to non-empty
1001 * - We have ORPort set
1003 * - We believe we are reachable from the outside; or
1004 * - We are an authoritative directory server.
1007 decide_if_publishable_server(void)
1009 or_options_t
*options
= get_options();
1011 if (options
->ClientOnly
)
1013 if (options
->_PublishServerDescriptor
== NO_AUTHORITY
)
1015 if (!server_mode(options
))
1017 if (authdir_mode(options
))
1020 return check_whether_orport_reachable();
1023 /** Initiate server descriptor upload as reasonable (if server is publishable,
1024 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1026 * We need to rebuild the descriptor if it's dirty even if we're not
1027 * uploading, because our reachability testing *uses* our descriptor to
1028 * determine what IP address and ports to test.
1031 consider_publishable_server(int force
)
1035 if (!server_mode(get_options()))
1038 rebuilt
= router_rebuild_descriptor(0);
1039 if (decide_if_publishable_server()) {
1040 set_server_advertised(1);
1042 router_upload_dir_desc_to_dirservers(force
);
1044 set_server_advertised(0);
1049 * OR descriptor generation.
1052 /** My routerinfo. */
1053 static routerinfo_t
*desc_routerinfo
= NULL
;
1055 static extrainfo_t
*desc_extrainfo
= NULL
;
1056 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1058 static time_t desc_clean_since
= 0;
1059 /** Boolean: do we need to regenerate the above? */
1060 static int desc_needs_upload
= 0;
1062 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1063 * descriptor successfully yet, try to upload our signed descriptor to
1064 * all the directory servers we know about.
1067 router_upload_dir_desc_to_dirservers(int force
)
1072 size_t desc_len
, extra_len
= 0, total_len
;
1073 authority_type_t auth
= get_options()->_PublishServerDescriptor
;
1075 ri
= router_get_my_routerinfo();
1077 log_info(LD_GENERAL
, "No descriptor; skipping upload");
1080 ei
= router_get_my_extrainfo();
1081 if (auth
== NO_AUTHORITY
)
1083 if (!force
&& !desc_needs_upload
)
1085 desc_needs_upload
= 0;
1087 desc_len
= ri
->cache_info
.signed_descriptor_len
;
1088 extra_len
= ei
? ei
->cache_info
.signed_descriptor_len
: 0;
1089 total_len
= desc_len
+ extra_len
+ 1;
1090 msg
= tor_malloc(total_len
);
1091 memcpy(msg
, ri
->cache_info
.signed_descriptor_body
, desc_len
);
1093 memcpy(msg
+desc_len
, ei
->cache_info
.signed_descriptor_body
, extra_len
);
1095 msg
[desc_len
+extra_len
] = 0;
1097 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR
,
1098 (auth
& BRIDGE_AUTHORITY
) ?
1099 ROUTER_PURPOSE_BRIDGE
:
1100 ROUTER_PURPOSE_GENERAL
,
1101 auth
, msg
, desc_len
, extra_len
);
1105 /** OR only: Check whether my exit policy says to allow connection to
1106 * conn. Return 0 if we accept; non-0 if we reject.
1109 router_compare_to_my_exit_policy(edge_connection_t
*conn
)
1111 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1114 /* make sure it's resolved to something. this way we can't get a
1116 if (tor_addr_is_null(&conn
->_base
.addr
))
1120 if (tor_addr_family(&conn
->_base
.addr
) != AF_INET
)
1123 return compare_tor_addr_to_addr_policy(&conn
->_base
.addr
, conn
->_base
.port
,
1124 desc_routerinfo
->exit_policy
) != ADDR_POLICY_ACCEPTED
;
1127 /** Return true iff I'm a server and <b>digest</b> is equal to
1128 * my identity digest. */
1130 router_digest_is_me(const char *digest
)
1132 return identitykey
&& !memcmp(identitykey_digest
, digest
, DIGEST_LEN
);
1135 /** Return true iff I'm a server and <b>digest</b> is equal to
1136 * my identity digest. */
1138 router_extrainfo_digest_is_me(const char *digest
)
1140 extrainfo_t
*ei
= router_get_my_extrainfo();
1144 return !memcmp(digest
,
1145 ei
->cache_info
.signed_descriptor_digest
,
1149 /** A wrapper around router_digest_is_me(). */
1151 router_is_me(routerinfo_t
*router
)
1153 return router_digest_is_me(router
->cache_info
.identity_digest
);
1156 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1158 router_fingerprint_is_me(const char *fp
)
1160 char digest
[DIGEST_LEN
];
1161 if (strlen(fp
) == HEX_DIGEST_LEN
&&
1162 base16_decode(digest
, sizeof(digest
), fp
, HEX_DIGEST_LEN
) == 0)
1163 return router_digest_is_me(digest
);
1168 /** Return a routerinfo for this OR, rebuilding a fresh one if
1169 * necessary. Return NULL on error, or if called on an OP. */
1171 router_get_my_routerinfo(void)
1173 if (!server_mode(get_options()))
1175 if (router_rebuild_descriptor(0))
1177 return desc_routerinfo
;
1180 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1181 * one if necessary. Return NULL on error.
1184 router_get_my_descriptor(void)
1187 if (!router_get_my_routerinfo())
1189 /* Make sure this is nul-terminated. */
1190 tor_assert(desc_routerinfo
->cache_info
.saved_location
== SAVED_NOWHERE
);
1191 body
= signed_descriptor_get_body(&desc_routerinfo
->cache_info
);
1192 tor_assert(!body
[desc_routerinfo
->cache_info
.signed_descriptor_len
]);
1193 log_debug(LD_GENERAL
,"my desc is '%s'", body
);
1197 /** Return the extrainfo document for this OR, or NULL if we have none.
1198 * Rebuilt it (and the server descriptor) if necessary. */
1200 router_get_my_extrainfo(void)
1202 if (!server_mode(get_options()))
1204 if (router_rebuild_descriptor(0))
1206 return desc_extrainfo
;
1209 /** A list of nicknames that we've warned about including in our family
1210 * declaration verbatim rather than as digests. */
1211 static smartlist_t
*warned_nonexistent_family
= NULL
;
1213 static int router_guess_address_from_dir_headers(uint32_t *guess
);
1215 /** Make a current best guess at our address, either because
1216 * it's configured in torrc, or because we've learned it from
1217 * dirserver headers. Place the answer in *<b>addr</b> and return
1218 * 0 on success, else return -1 if we have no guess. */
1220 router_pick_published_address(or_options_t
*options
, uint32_t *addr
)
1222 if (resolve_my_address(LOG_INFO
, options
, addr
, NULL
) < 0) {
1223 log_info(LD_CONFIG
, "Could not determine our address locally. "
1224 "Checking if directory headers provide any hints.");
1225 if (router_guess_address_from_dir_headers(addr
) < 0) {
1226 log_info(LD_CONFIG
, "No hints from directory headers either. "
1227 "Will try again later.");
1234 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1235 * routerinfo, signed server descriptor, and extra-info document for this OR.
1236 * Return 0 on success, -1 on temporary error.
1239 router_rebuild_descriptor(int force
)
1245 int hibernating
= we_are_hibernating();
1246 or_options_t
*options
= get_options();
1248 if (desc_clean_since
&& !force
)
1251 if (router_pick_published_address(options
, &addr
) < 0) {
1252 /* Stop trying to rebuild our descriptor every second. We'll
1253 * learn that it's time to try again when server_has_changed_ip()
1254 * marks it dirty. */
1255 desc_clean_since
= time(NULL
);
1259 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
1260 ri
->cache_info
.routerlist_index
= -1;
1261 ri
->address
= tor_dup_ip(addr
);
1262 ri
->nickname
= tor_strdup(options
->Nickname
);
1264 ri
->or_port
= options
->ORPort
;
1265 ri
->dir_port
= options
->DirPort
;
1266 ri
->cache_info
.published_on
= time(NULL
);
1267 ri
->onion_pkey
= crypto_pk_dup_key(get_onion_key()); /* must invoke from
1269 ri
->identity_pkey
= crypto_pk_dup_key(get_identity_key());
1270 if (crypto_pk_get_digest(ri
->identity_pkey
,
1271 ri
->cache_info
.identity_digest
)<0) {
1272 routerinfo_free(ri
);
1275 get_platform_str(platform
, sizeof(platform
));
1276 ri
->platform
= tor_strdup(platform
);
1278 /* compute ri->bandwidthrate as the min of various options */
1279 ri
->bandwidthrate
= get_effective_bwrate(options
);
1281 /* and compute ri->bandwidthburst similarly */
1282 ri
->bandwidthburst
= get_effective_bwburst(options
);
1284 ri
->bandwidthcapacity
= hibernating
? 0 : rep_hist_bandwidth_assess();
1286 policies_parse_exit_policy(options
->ExitPolicy
, &ri
->exit_policy
,
1287 options
->ExitPolicyRejectPrivate
,
1290 if (desc_routerinfo
) { /* inherit values */
1291 ri
->is_valid
= desc_routerinfo
->is_valid
;
1292 ri
->is_running
= desc_routerinfo
->is_running
;
1293 ri
->is_named
= desc_routerinfo
->is_named
;
1295 if (authdir_mode(options
))
1296 ri
->is_valid
= ri
->is_named
= 1; /* believe in yourself */
1297 if (options
->MyFamily
) {
1298 smartlist_t
*family
;
1299 if (!warned_nonexistent_family
)
1300 warned_nonexistent_family
= smartlist_create();
1301 family
= smartlist_create();
1302 ri
->declared_family
= smartlist_create();
1303 smartlist_split_string(family
, options
->MyFamily
, ",",
1304 SPLIT_SKIP_SPACE
|SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1305 SMARTLIST_FOREACH(family
, char *, name
,
1307 routerinfo_t
*member
;
1308 if (!strcasecmp(name
, options
->Nickname
))
1311 member
= router_get_by_nickname(name
, 1);
1313 int is_legal
= is_legal_nickname_or_hexdigest(name
);
1314 if (!smartlist_string_isin(warned_nonexistent_family
, name
) &&
1315 !is_legal_hexdigest(name
)) {
1318 "I have no descriptor for the router named \"%s\" in my "
1319 "declared family; I'll use the nickname as is, but "
1320 "this may confuse clients.", name
);
1322 log_warn(LD_CONFIG
, "There is a router named \"%s\" in my "
1323 "declared family, but that isn't a legal nickname. "
1324 "Skipping it.", escaped(name
));
1325 smartlist_add(warned_nonexistent_family
, tor_strdup(name
));
1328 smartlist_add(ri
->declared_family
, name
);
1331 } else if (router_is_me(member
)) {
1332 /* Don't list ourself in our own family; that's redundant */
1334 char *fp
= tor_malloc(HEX_DIGEST_LEN
+2);
1336 base16_encode(fp
+1,HEX_DIGEST_LEN
+1,
1337 member
->cache_info
.identity_digest
, DIGEST_LEN
);
1338 smartlist_add(ri
->declared_family
, fp
);
1339 if (smartlist_string_isin(warned_nonexistent_family
, name
))
1340 smartlist_string_remove(warned_nonexistent_family
, name
);
1345 /* remove duplicates from the list */
1346 smartlist_sort_strings(ri
->declared_family
);
1347 smartlist_uniq_strings(ri
->declared_family
);
1349 smartlist_free(family
);
1352 /* Now generate the extrainfo. */
1353 ei
= tor_malloc_zero(sizeof(extrainfo_t
));
1354 ei
->cache_info
.is_extrainfo
= 1;
1355 strlcpy(ei
->nickname
, get_options()->Nickname
, sizeof(ei
->nickname
));
1356 ei
->cache_info
.published_on
= ri
->cache_info
.published_on
;
1357 memcpy(ei
->cache_info
.identity_digest
, ri
->cache_info
.identity_digest
,
1359 ei
->cache_info
.signed_descriptor_body
= tor_malloc(8192);
1360 if (extrainfo_dump_to_string(ei
->cache_info
.signed_descriptor_body
, 8192,
1361 ei
, get_identity_key()) < 0) {
1362 log_warn(LD_BUG
, "Couldn't generate extra-info descriptor.");
1363 routerinfo_free(ri
);
1367 ei
->cache_info
.signed_descriptor_len
=
1368 strlen(ei
->cache_info
.signed_descriptor_body
);
1369 router_get_extrainfo_hash(ei
->cache_info
.signed_descriptor_body
,
1370 ei
->cache_info
.signed_descriptor_digest
);
1372 /* Now finish the router descriptor. */
1373 memcpy(ri
->cache_info
.extra_info_digest
,
1374 ei
->cache_info
.signed_descriptor_digest
,
1376 ri
->cache_info
.signed_descriptor_body
= tor_malloc(8192);
1377 if (router_dump_router_to_string(ri
->cache_info
.signed_descriptor_body
, 8192,
1378 ri
, get_identity_key())<0) {
1379 log_warn(LD_BUG
, "Couldn't generate router descriptor.");
1380 routerinfo_free(ri
);
1384 ri
->cache_info
.signed_descriptor_len
=
1385 strlen(ri
->cache_info
.signed_descriptor_body
);
1388 options
->BridgeRelay
? ROUTER_PURPOSE_BRIDGE
: ROUTER_PURPOSE_GENERAL
;
1389 ri
->cache_info
.send_unencrypted
= 1;
1390 /* Let bridges serve their own descriptors unencrypted, so they can
1391 * pass reachability testing. (If they want to be harder to notice,
1392 * they can always leave the DirPort off). */
1393 if (!options
->BridgeRelay
)
1394 ei
->cache_info
.send_unencrypted
= 1;
1396 router_get_router_hash(ri
->cache_info
.signed_descriptor_body
,
1397 strlen(ri
->cache_info
.signed_descriptor_body
),
1398 ri
->cache_info
.signed_descriptor_digest
);
1400 routerinfo_set_country(ri
);
1402 tor_assert(! routerinfo_incompatible_with_extrainfo(ri
, ei
, NULL
, NULL
));
1404 if (desc_routerinfo
)
1405 routerinfo_free(desc_routerinfo
);
1406 desc_routerinfo
= ri
;
1408 extrainfo_free(desc_extrainfo
);
1409 desc_extrainfo
= ei
;
1411 desc_clean_since
= time(NULL
);
1412 desc_needs_upload
= 1;
1413 control_event_my_descriptor_changed();
1417 /** Mark descriptor out of date if it's older than <b>when</b> */
1419 mark_my_descriptor_dirty_if_older_than(time_t when
)
1421 if (desc_clean_since
< when
)
1422 mark_my_descriptor_dirty();
1425 /** Call when the current descriptor is out of date. */
1427 mark_my_descriptor_dirty(void)
1429 desc_clean_since
= 0;
1432 /** How frequently will we republish our descriptor because of large (factor
1433 * of 2) shifts in estimated bandwidth? */
1434 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
1436 /** Check whether bandwidth has changed a lot since the last time we announced
1437 * bandwidth. If so, mark our descriptor dirty. */
1439 check_descriptor_bandwidth_changed(time_t now
)
1441 static time_t last_changed
= 0;
1443 if (!desc_routerinfo
)
1446 prev
= desc_routerinfo
->bandwidthcapacity
;
1447 cur
= we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
1448 if ((prev
!= cur
&& (!prev
|| !cur
)) ||
1451 if (last_changed
+MAX_BANDWIDTH_CHANGE_FREQ
< now
) {
1452 log_info(LD_GENERAL
,
1453 "Measured bandwidth has changed; rebuilding descriptor.");
1454 mark_my_descriptor_dirty();
1460 /** Note at log level severity that our best guess of address has changed from
1461 * <b>prev</b> to <b>cur</b>. */
1463 log_addr_has_changed(int severity
, uint32_t prev
, uint32_t cur
,
1466 char addrbuf_prev
[INET_NTOA_BUF_LEN
];
1467 char addrbuf_cur
[INET_NTOA_BUF_LEN
];
1468 struct in_addr in_prev
;
1469 struct in_addr in_cur
;
1471 in_prev
.s_addr
= htonl(prev
);
1472 tor_inet_ntoa(&in_prev
, addrbuf_prev
, sizeof(addrbuf_prev
));
1474 in_cur
.s_addr
= htonl(cur
);
1475 tor_inet_ntoa(&in_cur
, addrbuf_cur
, sizeof(addrbuf_cur
));
1478 log_fn(severity
, LD_GENERAL
,
1479 "Our IP Address has changed from %s to %s; "
1480 "rebuilding descriptor (source: %s).",
1481 addrbuf_prev
, addrbuf_cur
, source
);
1483 log_notice(LD_GENERAL
,
1484 "Guessed our IP address as %s (source: %s).",
1485 addrbuf_cur
, source
);
1488 /** Check whether our own address as defined by the Address configuration
1489 * has changed. This is for routers that get their address from a service
1490 * like dyndns. If our address has changed, mark our descriptor dirty. */
1492 check_descriptor_ipaddress_changed(time_t now
)
1495 or_options_t
*options
= get_options();
1498 if (!desc_routerinfo
)
1501 prev
= desc_routerinfo
->addr
;
1502 if (resolve_my_address(LOG_INFO
, options
, &cur
, NULL
) < 0) {
1503 log_info(LD_CONFIG
,"options->Address didn't resolve into an IP.");
1508 log_addr_has_changed(LOG_NOTICE
, prev
, cur
, "resolve");
1509 ip_address_changed(0);
1513 /** The most recently guessed value of our IP address, based on directory
1515 static uint32_t last_guessed_ip
= 0;
1517 /** A directory server <b>d_conn</b> told us our IP address is
1518 * <b>suggestion</b>.
1519 * If this address is different from the one we think we are now, and
1520 * if our computer doesn't actually know its IP address, then switch. */
1522 router_new_address_suggestion(const char *suggestion
,
1523 const dir_connection_t
*d_conn
)
1525 uint32_t addr
, cur
= 0;
1527 or_options_t
*options
= get_options();
1529 /* first, learn what the IP address actually is */
1530 if (!tor_inet_aton(suggestion
, &in
)) {
1531 log_debug(LD_DIR
, "Malformed X-Your-Address-Is header %s. Ignoring.",
1532 escaped(suggestion
));
1535 addr
= ntohl(in
.s_addr
);
1537 log_debug(LD_DIR
, "Got X-Your-Address-Is: %s.", suggestion
);
1539 if (!server_mode(options
)) {
1540 last_guessed_ip
= addr
; /* store it in case we need it later */
1544 if (resolve_my_address(LOG_INFO
, options
, &cur
, NULL
) >= 0) {
1545 /* We're all set -- we already know our address. Great. */
1546 last_guessed_ip
= cur
; /* store it in case we need it later */
1549 if (is_internal_IP(addr
, 0)) {
1550 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1553 if (tor_addr_eq_ipv4h(&d_conn
->_base
.addr
, addr
)) {
1554 /* Don't believe anybody who says our IP is their IP. */
1555 log_debug(LD_DIR
, "A directory server told us our IP address is %s, "
1556 "but he's just reporting his own IP address. Ignoring.",
1561 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1562 * us an answer different from what we had the last time we managed to
1564 if (last_guessed_ip
!= addr
) {
1565 control_event_server_status(LOG_NOTICE
,
1566 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1568 log_addr_has_changed(LOG_NOTICE
, last_guessed_ip
, addr
,
1569 d_conn
->_base
.address
);
1570 ip_address_changed(0);
1571 last_guessed_ip
= addr
; /* router_rebuild_descriptor() will fetch it */
1575 /** We failed to resolve our address locally, but we'd like to build
1576 * a descriptor and publish / test reachability. If we have a guess
1577 * about our address based on directory headers, answer it and return
1578 * 0; else return -1. */
1580 router_guess_address_from_dir_headers(uint32_t *guess
)
1582 if (last_guessed_ip
) {
1583 *guess
= last_guessed_ip
;
1589 extern const char tor_svn_revision
[]; /* from tor_main.c */
1591 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1592 * string describing the version of Tor and the operating system we're
1593 * currently running on.
1596 get_platform_str(char *platform
, size_t len
)
1598 tor_snprintf(platform
, len
, "Tor %s on %s", get_version(), get_uname());
1601 /* XXX need to audit this thing and count fenceposts. maybe
1602 * refactor so we don't have to keep asking if we're
1603 * near the end of maxlen?
1605 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1607 /** OR only: Given a routerinfo for this router, and an identity key to sign
1608 * with, encode the routerinfo as a signed server descriptor and write the
1609 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1610 * failure, and the number of bytes used on success.
1613 router_dump_router_to_string(char *s
, size_t maxlen
, routerinfo_t
*router
,
1614 crypto_pk_env_t
*ident_key
)
1616 char *onion_pkey
; /* Onion key, PEM-encoded. */
1617 char *identity_pkey
; /* Identity key, PEM-encoded. */
1618 char digest
[DIGEST_LEN
];
1619 char published
[ISO_TIME_LEN
+1];
1620 char fingerprint
[FINGERPRINT_LEN
+1];
1621 char extra_info_digest
[HEX_DIGEST_LEN
+1];
1622 size_t onion_pkeylen
, identity_pkeylen
;
1625 addr_policy_t
*tmpe
;
1627 or_options_t
*options
= get_options();
1629 /* Make sure the identity key matches the one in the routerinfo. */
1630 if (crypto_pk_cmp_keys(ident_key
, router
->identity_pkey
)) {
1631 log_warn(LD_BUG
,"Tried to sign a router with a private key that didn't "
1632 "match router's public key!");
1636 /* record our fingerprint, so we can include it in the descriptor */
1637 if (crypto_pk_get_fingerprint(router
->identity_pkey
, fingerprint
, 1)<0) {
1638 log_err(LD_BUG
,"Error computing fingerprint");
1642 /* PEM-encode the onion key */
1643 if (crypto_pk_write_public_key_to_string(router
->onion_pkey
,
1644 &onion_pkey
,&onion_pkeylen
)<0) {
1645 log_warn(LD_BUG
,"write onion_pkey to string failed!");
1649 /* PEM-encode the identity key key */
1650 if (crypto_pk_write_public_key_to_string(router
->identity_pkey
,
1651 &identity_pkey
,&identity_pkeylen
)<0) {
1652 log_warn(LD_BUG
,"write identity_pkey to string failed!");
1653 tor_free(onion_pkey
);
1657 /* Encode the publication time. */
1658 format_iso_time(published
, router
->cache_info
.published_on
);
1660 if (router
->declared_family
&& smartlist_len(router
->declared_family
)) {
1662 char *family
= smartlist_join_strings(router
->declared_family
, " ", 0, &n
);
1663 n
+= strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1664 family_line
= tor_malloc(n
);
1665 tor_snprintf(family_line
, n
, "family %s\n", family
);
1668 family_line
= tor_strdup("");
1671 base16_encode(extra_info_digest
, sizeof(extra_info_digest
),
1672 router
->cache_info
.extra_info_digest
, DIGEST_LEN
);
1674 /* Generate the easy portion of the router descriptor. */
1675 result
= tor_snprintf(s
, maxlen
,
1676 "router %s %s %d 0 %d\n"
1678 "opt protocols Link 1 2 Circuit 1\n"
1680 "opt fingerprint %s\n"
1682 "bandwidth %d %d %d\n"
1683 "opt extra-info-digest %s\n%s"
1690 decide_to_advertise_dirport(options
, router
->dir_port
),
1694 stats_n_seconds_working
,
1695 (int) router
->bandwidthrate
,
1696 (int) router
->bandwidthburst
,
1697 (int) router
->bandwidthcapacity
,
1699 options
->DownloadExtraInfo
? "opt caches-extra-info\n" : "",
1700 onion_pkey
, identity_pkey
,
1702 we_are_hibernating() ? "opt hibernating 1\n" : "",
1703 options
->HidServDirectoryV2
? "opt hidden-service-dir\n" : "",
1704 options
->AllowSingleHopExits
? "opt allow-single-hop-exits\n" : "");
1706 tor_free(family_line
);
1707 tor_free(onion_pkey
);
1708 tor_free(identity_pkey
);
1711 log_warn(LD_BUG
,"descriptor snprintf #1 ran out of room!");
1714 /* From now on, we use 'written' to remember the current length of 's'. */
1717 if (options
->ContactInfo
&& strlen(options
->ContactInfo
)) {
1718 const char *ci
= options
->ContactInfo
;
1719 if (strchr(ci
, '\n') || strchr(ci
, '\r'))
1721 result
= tor_snprintf(s
+written
,maxlen
-written
, "contact %s\n", ci
);
1723 log_warn(LD_BUG
,"descriptor snprintf #2 ran out of room!");
1729 /* Write the exit policy to the end of 's'. */
1730 if (dns_seems_to_be_broken() || has_dns_init_failed() ||
1731 !router
->exit_policy
|| !smartlist_len(router
->exit_policy
)) {
1732 /* DNS is screwed up; don't claim to be an exit. */
1733 strlcat(s
+written
, "reject *:*\n", maxlen
-written
);
1734 written
+= strlen("reject *:*\n");
1736 } else if (router
->exit_policy
) {
1738 for (i
= 0; i
< smartlist_len(router
->exit_policy
); ++i
) {
1739 tmpe
= smartlist_get(router
->exit_policy
, i
);
1740 result
= policy_write_item(s
+written
, maxlen
-written
, tmpe
, 1);
1742 log_warn(LD_BUG
,"descriptor policy_write_item ran out of room!");
1745 tor_assert(result
== (int)strlen(s
+written
));
1747 if (written
+2 > maxlen
) {
1748 log_warn(LD_BUG
,"descriptor policy_write_item ran out of room (2)!");
1751 s
[written
++] = '\n';
1755 if (written
+256 > maxlen
) { /* Not enough room for signature. */
1756 log_warn(LD_BUG
,"not enough room left in descriptor for signature!");
1760 /* Sign the descriptor */
1761 strlcpy(s
+written
, "router-signature\n", maxlen
-written
);
1762 written
+= strlen(s
+written
);
1764 if (router_get_router_hash(s
, strlen(s
), digest
) < 0) {
1768 note_crypto_pk_op(SIGN_RTR
);
1769 if (router_append_dirobj_signature(s
+written
,maxlen
-written
,
1770 digest
,ident_key
)<0) {
1771 log_warn(LD_BUG
, "Couldn't sign router descriptor");
1774 written
+= strlen(s
+written
);
1776 if (written
+2 > maxlen
) {
1777 log_warn(LD_BUG
,"Not enough room to finish descriptor.");
1780 /* include a last '\n' */
1784 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1788 routerinfo_t
*ri_tmp
;
1789 cp
= s_dup
= tor_strdup(s
);
1790 ri_tmp
= router_parse_entry_from_string(cp
, NULL
, 1, 0, NULL
);
1793 "We just generated a router descriptor we can't parse.");
1794 log_err(LD_BUG
, "Descriptor was: <<%s>>", s
);
1798 routerinfo_free(ri_tmp
);
1802 return (int)written
+1;
1805 /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
1806 * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
1807 * negative on failure. */
1809 extrainfo_dump_to_string(char *s
, size_t maxlen
, extrainfo_t
*extrainfo
,
1810 crypto_pk_env_t
*ident_key
)
1812 or_options_t
*options
= get_options();
1813 char identity
[HEX_DIGEST_LEN
+1];
1814 char published
[ISO_TIME_LEN
+1];
1815 char digest
[DIGEST_LEN
];
1816 char *bandwidth_usage
;
1820 base16_encode(identity
, sizeof(identity
),
1821 extrainfo
->cache_info
.identity_digest
, DIGEST_LEN
);
1822 format_iso_time(published
, extrainfo
->cache_info
.published_on
);
1823 bandwidth_usage
= rep_hist_get_bandwidth_lines(1);
1825 result
= tor_snprintf(s
, maxlen
,
1826 "extra-info %s %s\n"
1828 extrainfo
->nickname
, identity
,
1829 published
, bandwidth_usage
);
1830 tor_free(bandwidth_usage
);
1834 if (should_record_bridge_info(options
)) {
1835 char *geoip_summary
= extrainfo_get_client_geoip_summary(time(NULL
));
1836 if (geoip_summary
) {
1837 char geoip_start
[ISO_TIME_LEN
+1];
1838 format_iso_time(geoip_start
, geoip_get_history_start());
1839 result
= tor_snprintf(s
+strlen(s
), maxlen
-strlen(s
),
1840 "geoip-start-time %s\n"
1841 "geoip-client-origins %s\n",
1842 geoip_start
, geoip_summary
);
1843 control_event_clients_seen(geoip_start
, geoip_summary
);
1844 tor_free(geoip_summary
);
1851 strlcat(s
+len
, "router-signature\n", maxlen
-len
);
1852 len
+= strlen(s
+len
);
1853 if (router_get_extrainfo_hash(s
, digest
)<0)
1855 if (router_append_dirobj_signature(s
+len
, maxlen
-len
, digest
, ident_key
)<0)
1858 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1861 extrainfo_t
*ei_tmp
;
1862 cp
= s_dup
= tor_strdup(s
);
1863 ei_tmp
= extrainfo_parse_entry_from_string(cp
, NULL
, 1, NULL
);
1866 "We just generated an extrainfo descriptor we can't parse.");
1867 log_err(LD_BUG
, "Descriptor was: <<%s>>", s
);
1872 extrainfo_free(ei_tmp
);
1876 return (int)strlen(s
)+1;
1879 /** Wrapper function for geoip_get_client_history(). It first discards
1880 * any items in the client history that are too old -- it dumps anything
1881 * more than 48 hours old, but it only considers whether to dump at most
1882 * once per 48 hours, so we aren't too precise to an observer (see also
1886 extrainfo_get_client_geoip_summary(time_t now
)
1888 static time_t last_purged_at
= 0;
1889 int geoip_purge_interval
= 48*60*60;
1890 #ifdef ENABLE_GEOIP_STATS
1891 if (get_options()->DirRecordUsageByCountry
)
1892 geoip_purge_interval
= get_options()->DirRecordUsageRetainIPs
;
1894 if (now
> last_purged_at
+geoip_purge_interval
) {
1895 geoip_remove_old_clients(now
-geoip_purge_interval
);
1896 last_purged_at
= now
;
1898 return geoip_get_client_history(now
, GEOIP_CLIENT_CONNECT
);
1901 /** Return true iff <b>s</b> is a legally valid server nickname. */
1903 is_legal_nickname(const char *s
)
1908 return len
> 0 && len
<= MAX_NICKNAME_LEN
&&
1909 strspn(s
,LEGAL_NICKNAME_CHARACTERS
) == len
;
1912 /** Return true iff <b>s</b> is a legally valid server nickname or
1913 * hex-encoded identity-key digest. */
1915 is_legal_nickname_or_hexdigest(const char *s
)
1918 return is_legal_nickname(s
);
1920 return is_legal_hexdigest(s
);
1923 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
1926 is_legal_hexdigest(const char *s
)
1930 if (s
[0] == '$') s
++;
1932 if (len
> HEX_DIGEST_LEN
) {
1933 if (s
[HEX_DIGEST_LEN
] == '=' ||
1934 s
[HEX_DIGEST_LEN
] == '~') {
1935 if (!is_legal_nickname(s
+HEX_DIGEST_LEN
+1))
1941 return (len
>= HEX_DIGEST_LEN
&&
1942 strspn(s
,HEX_CHARACTERS
)==HEX_DIGEST_LEN
);
1945 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
1946 * verbose representation of the identity of <b>router</b>. The format is:
1948 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
1949 * A "=" if the router is named; a "~" if it is not.
1950 * The router's nickname.
1953 router_get_verbose_nickname(char *buf
, const routerinfo_t
*router
)
1956 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, router
->cache_info
.identity_digest
,
1958 buf
[1+HEX_DIGEST_LEN
] = router
->is_named
? '=' : '~';
1959 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, router
->nickname
, MAX_NICKNAME_LEN
+1);
1962 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
1963 * verbose representation of the identity of <b>router</b>. The format is:
1965 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
1966 * A "=" if the router is named; a "~" if it is not.
1967 * The router's nickname.
1970 routerstatus_get_verbose_nickname(char *buf
, const routerstatus_t
*router
)
1973 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, router
->identity_digest
,
1975 buf
[1+HEX_DIGEST_LEN
] = router
->is_named
? '=' : '~';
1976 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, router
->nickname
, MAX_NICKNAME_LEN
+1);
1979 /** Forget that we have issued any router-related warnings, so that we'll
1980 * warn again if we see the same errors. */
1982 router_reset_warnings(void)
1984 if (warned_nonexistent_family
) {
1985 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
1986 smartlist_clear(warned_nonexistent_family
);
1990 /** Given a router purpose, convert it to a string. Don't call this on
1991 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
1992 * know its string representation. */
1994 router_purpose_to_string(uint8_t p
)
1998 case ROUTER_PURPOSE_GENERAL
: return "general";
1999 case ROUTER_PURPOSE_BRIDGE
: return "bridge";
2000 case ROUTER_PURPOSE_CONTROLLER
: return "controller";
2007 /** Given a string, convert it to a router purpose. */
2009 router_purpose_from_string(const char *s
)
2011 if (!strcmp(s
, "general"))
2012 return ROUTER_PURPOSE_GENERAL
;
2013 else if (!strcmp(s
, "bridge"))
2014 return ROUTER_PURPOSE_BRIDGE
;
2015 else if (!strcmp(s
, "controller"))
2016 return ROUTER_PURPOSE_CONTROLLER
;
2018 return ROUTER_PURPOSE_UNKNOWN
;
2021 /** Release all static resources held in router.c */
2023 router_free_all(void)
2026 crypto_free_pk_env(onionkey
);
2028 crypto_free_pk_env(lastonionkey
);
2030 crypto_free_pk_env(identitykey
);
2032 tor_mutex_free(key_lock
);
2033 if (desc_routerinfo
)
2034 routerinfo_free(desc_routerinfo
);
2036 extrainfo_free(desc_extrainfo
);
2037 if (authority_signing_key
)
2038 crypto_free_pk_env(authority_signing_key
);
2039 if (authority_key_certificate
)
2040 authority_cert_free(authority_key_certificate
);
2041 if (legacy_signing_key
)
2042 crypto_free_pk_env(legacy_signing_key
);
2043 if (legacy_key_certificate
)
2044 authority_cert_free(legacy_key_certificate
);
2046 if (warned_nonexistent_family
) {
2047 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
2048 smartlist_free(warned_nonexistent_family
);