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, 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 /* (Note that v3 authorities also have a separate "authority identity key",
49 * but this key is never actually loaded by the Tor process. Instead, it's
50 * used by tor-gencert to sign new signing keys and make new key
53 /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
54 * to update onionkey correctly, call rotate_onion_key().
57 set_onion_key(crypto_pk_env_t
*k
)
59 tor_mutex_acquire(key_lock
);
61 onionkey_set_at
= time(NULL
);
62 tor_mutex_release(key_lock
);
63 mark_my_descriptor_dirty();
66 /** Return the current onion key. Requires that the onion key has been
67 * loaded or generated. */
75 /** Store a copy of the current onion key into *<b>key</b>, and a copy
76 * of the most recent onion key into *<b>last</b>.
79 dup_onion_keys(crypto_pk_env_t
**key
, crypto_pk_env_t
**last
)
83 tor_mutex_acquire(key_lock
);
85 *key
= crypto_pk_dup_key(onionkey
);
87 *last
= crypto_pk_dup_key(lastonionkey
);
90 tor_mutex_release(key_lock
);
93 /** Return the time when the onion key was last set. This is either the time
94 * when the process launched, or the time of the most recent key rotation since
95 * the process launched.
98 get_onion_key_set_at(void)
100 return onionkey_set_at
;
103 /** Set the current identity key to k.
106 set_identity_key(crypto_pk_env_t
*k
)
109 crypto_free_pk_env(identitykey
);
111 crypto_pk_get_digest(identitykey
, identitykey_digest
);
114 /** Returns the current identity key; requires that the identity key has been
118 get_identity_key(void)
120 tor_assert(identitykey
);
124 /** Return true iff the identity key has been set. */
126 identity_key_is_set(void)
128 return identitykey
!= NULL
;
131 /** Return the key certificate for this v3 (voting) authority, or NULL
132 * if we have no such certificate. */
134 get_my_v3_authority_cert(void)
136 return authority_key_certificate
;
139 /** Return the v3 signing key for this v3 (voting) authority, or NULL
140 * if we have no such key. */
142 get_my_v3_authority_signing_key(void)
144 return authority_signing_key
;
147 /** Replace the previous onion key with the current onion key, and generate
148 * a new previous onion key. Immediately after calling this function,
150 * - schedule all previous cpuworkers to shut down _after_ processing
151 * pending work. (This will cause fresh cpuworkers to be generated.)
152 * - generate and upload a fresh routerinfo.
155 rotate_onion_key(void)
157 char *fname
, *fname_prev
;
158 crypto_pk_env_t
*prkey
;
159 or_state_t
*state
= get_or_state();
161 fname
= get_datadir_fname2("keys", "secret_onion_key");
162 fname_prev
= get_datadir_fname2("keys", "secret_onion_key.old");
163 if (!(prkey
= crypto_new_pk_env())) {
164 log_err(LD_GENERAL
,"Error constructing rotated onion key");
167 if (crypto_pk_generate_key(prkey
)) {
168 log_err(LD_BUG
,"Error generating onion key");
171 if (file_status(fname
) == FN_FILE
) {
172 if (replace_file(fname
, fname_prev
))
175 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
176 log_err(LD_FS
,"Couldn't write generated onion key to \"%s\".", fname
);
179 log_info(LD_GENERAL
, "Rotating onion key");
180 tor_mutex_acquire(key_lock
);
182 crypto_free_pk_env(lastonionkey
);
183 lastonionkey
= onionkey
;
186 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
187 tor_mutex_release(key_lock
);
188 mark_my_descriptor_dirty();
189 or_state_mark_dirty(state
, get_options()->AvoidDiskWrites
? now
+3600 : 0);
192 log_warn(LD_GENERAL
, "Couldn't rotate onion key.");
194 crypto_free_pk_env(prkey
);
197 tor_free(fname_prev
);
200 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
201 * and <b>generate</b> is true, create a new RSA key and save it in
202 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
203 * errors at level <b>severity</b>.
206 init_key_from_file(const char *fname
, int generate
, int severity
)
208 crypto_pk_env_t
*prkey
= NULL
;
211 if (!(prkey
= crypto_new_pk_env())) {
212 log(severity
, LD_GENERAL
,"Error constructing key");
216 switch (file_status(fname
)) {
219 log(severity
, LD_FS
,"Can't read key from \"%s\"", fname
);
223 log_info(LD_GENERAL
, "No key found in \"%s\"; generating fresh key.",
225 if (crypto_pk_generate_key(prkey
)) {
226 log(severity
, LD_GENERAL
,"Error generating onion key");
229 if (crypto_pk_check_key(prkey
) <= 0) {
230 log(severity
, LD_GENERAL
,"Generated key seems invalid");
233 log_info(LD_GENERAL
, "Generated key seems valid");
234 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
236 "Couldn't write generated key to \"%s\".", fname
);
240 log_info(LD_GENERAL
, "No key found in \"%s\"", fname
);
244 if (crypto_pk_read_private_key_from_filename(prkey
, fname
)) {
245 log(severity
, LD_GENERAL
,"Error loading private key.");
255 crypto_free_pk_env(prkey
);
261 /** Load the v3 (voting) authority signing key and certificate, if they are
262 * present. Return -1 if anything is missing, mismatched, or unloadable;
263 * return 0 on success. */
264 /* XXXX020 maybe move to dirserv.c or dirvote.c */
266 init_v3_authority_keys(void)
268 char *fname
= NULL
, *cert
= NULL
;
269 const char *eos
= NULL
;
270 crypto_pk_env_t
*signing_key
= NULL
;
271 authority_cert_t
*parsed
= NULL
;
274 fname
= get_datadir_fname2("keys", "authority_signing_key");
275 signing_key
= init_key_from_file(fname
, 0, LOG_INFO
);
277 log_warn(LD_DIR
, "No version 3 directory key found in %s", fname
);
281 fname
= get_datadir_fname2("keys", "authority_certificate");
282 cert
= read_file_to_str(fname
, 0, NULL
);
284 log_warn(LD_DIR
, "Signing key found, but no certificate found in %s",
288 parsed
= authority_cert_parse_from_string(cert
, &eos
);
290 log_warn(LD_DIR
, "Unable to parse certificate in %s", fname
);
293 if (crypto_pk_cmp_keys(signing_key
, parsed
->signing_key
) != 0) {
294 log_warn(LD_DIR
, "Stored signing key does not match signing key in "
298 parsed
->cache_info
.signed_descriptor_body
= cert
;
299 parsed
->cache_info
.signed_descriptor_len
= eos
-cert
;
302 /* Free old values... */
303 if (authority_key_certificate
)
304 authority_cert_free(authority_key_certificate
);
305 if (authority_signing_key
)
306 crypto_free_pk_env(authority_signing_key
);
307 /* ...and replace them. */
308 authority_key_certificate
= parsed
;
309 authority_signing_key
= signing_key
;
318 crypto_free_pk_env(signing_key
);
320 authority_cert_free(parsed
);
324 /** If we're a v3 authority, check whether we have a certificatge that's
325 * likely to expire soon. Warn if we do, but not too often. */
327 v3_authority_check_key_expiry(void)
330 static time_t last_warned
= 0;
331 int badness
, time_left
, warn_interval
;
332 if (!authdir_mode_v3(get_options()) || !authority_key_certificate
)
336 expires
= authority_key_certificate
->expires
;
337 time_left
= expires
- now
;
338 if (time_left
<= 0) {
340 warn_interval
= 60*60;
341 } else if (time_left
<= 24*60*60) {
343 warn_interval
= 60*60;
344 } else if (time_left
<= 24*60*60*7) {
346 warn_interval
= 24*60*60;
347 } else if (time_left
<= 24*60*60*30) {
349 warn_interval
= 24*60*60*5;
354 if (last_warned
+ warn_interval
> now
)
357 if (time_left
<= 0) {
358 log(badness
, LD_DIR
, "Your v3 authority certificate has expired."
359 " Generate a new one NOW.");
360 } else if (time_left
<= 24*60*60) {
361 log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d hours;"
362 " Generate a new one NOW.", time_left
/(60*60));
364 log(badness
, LD_DIR
, "Your v3 authority certificate expires in %d days;"
365 " Generate a new one soon.", time_left
/(24*60*60));
370 /** Initialize all OR private keys, and the TLS context, as necessary.
371 * On OPs, this only initializes the tls context. Return 0 on success,
372 * or -1 if Tor should die.
378 char fingerprint
[FINGERPRINT_LEN
+1];
379 /*nickname<space>fp\n\0 */
380 char fingerprint_line
[MAX_NICKNAME_LEN
+FINGERPRINT_LEN
+3];
382 crypto_pk_env_t
*prkey
;
386 or_options_t
*options
= get_options();
387 authority_type_t type
;
388 time_t now
= time(NULL
);
389 trusted_dir_server_t
*ds
;
390 int v3_digest_set
= 0;
393 key_lock
= tor_mutex_new();
395 /* OP's don't need persistent keys; just make up an identity and
396 * initialize the TLS context. */
397 if (!server_mode(options
)) {
398 if (!(prkey
= crypto_new_pk_env()))
400 if (crypto_pk_generate_key(prkey
))
402 set_identity_key(prkey
);
403 /* Create a TLS context; default the client nickname to "client". */
404 if (tor_tls_context_new(get_identity_key(),
405 options
->Nickname
? options
->Nickname
: "client",
406 MAX_SSL_KEY_LIFETIME
) < 0) {
407 log_err(LD_GENERAL
,"Error creating TLS context for Tor client.");
412 /* Make sure DataDirectory exists, and is private. */
413 if (check_private_dir(options
->DataDirectory
, CPD_CREATE
)) {
416 /* Check the key directory. */
417 keydir
= get_datadir_fname("keys");
418 if (check_private_dir(keydir
, CPD_CREATE
)) {
424 /* 1a. Read v3 directory authority key/cert information. */
425 memset(v3_digest
, 0, sizeof(v3_digest
));
426 if (authdir_mode_v3(options
)) {
427 if (init_v3_authority_keys()<0) {
428 log_err(LD_GENERAL
, "We're configured as a V3 authority, but we "
429 "were unable to load our v3 authority keys and certificate! "
430 "Use tor-gencert to generate them. Dying.");
433 if (get_my_v3_authority_cert()) {
434 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key
,
440 /* 1. Read identity key. Make it if none is found. */
441 keydir
= get_datadir_fname2("keys", "secret_id_key");
442 log_info(LD_GENERAL
,"Reading/making identity key \"%s\"...",keydir
);
443 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
445 if (!prkey
) return -1;
446 set_identity_key(prkey
);
448 /* 2. Read onion key. Make it if none is found. */
449 keydir
= get_datadir_fname2("keys", "secret_onion_key");
450 log_info(LD_GENERAL
,"Reading/making onion key \"%s\"...",keydir
);
451 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
453 if (!prkey
) return -1;
454 set_onion_key(prkey
);
455 if (options
->command
== CMD_RUN_TOR
) {
456 /* only mess with the state file if we're actually running Tor */
457 or_state_t
*state
= get_or_state();
458 if (state
->LastRotatedOnionKey
> 100 && state
->LastRotatedOnionKey
< now
) {
459 /* We allow for some parsing slop, but we don't want to risk accepting
460 * values in the distant future. If we did, we might never rotate the
462 onionkey_set_at
= state
->LastRotatedOnionKey
;
464 /* We have no LastRotatedOnionKey set; either we just created the key
465 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
466 * start the clock ticking now so that we will eventually rotate it even
467 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
468 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
469 or_state_mark_dirty(state
, options
->AvoidDiskWrites
?
470 time(NULL
)+3600 : 0);
474 keydir
= get_datadir_fname2("keys", "secret_onion_key.old");
475 if (!lastonionkey
&& file_status(keydir
) == FN_FILE
) {
476 prkey
= init_key_from_file(keydir
, 1, LOG_ERR
);
478 lastonionkey
= prkey
;
482 /* 3. Initialize link key and TLS context. */
483 if (tor_tls_context_new(get_identity_key(), options
->Nickname
,
484 MAX_SSL_KEY_LIFETIME
) < 0) {
485 log_err(LD_GENERAL
,"Error initializing TLS context");
488 /* 4. Build our router descriptor. */
489 /* Must be called after keys are initialized. */
490 mydesc
= router_get_my_descriptor();
491 if (authdir_mode(options
)) {
494 /* We need to add our own fingerprint so it gets recognized. */
495 if (dirserv_add_own_fingerprint(options
->Nickname
, get_identity_key())) {
496 log_err(LD_GENERAL
,"Error adding own fingerprint to approved set");
500 ri
= router_parse_entry_from_string(mydesc
, NULL
, 1, 0, NULL
);
502 log_err(LD_GENERAL
,"Generated a routerinfo we couldn't parse.");
505 if (dirserv_add_descriptor(ri
, &m
) < 0) {
506 log_err(LD_GENERAL
,"Unable to add own descriptor to directory: %s",
507 m
?m
:"<unknown error>");
513 /* 5. Dump fingerprint to 'fingerprint' */
514 keydir
= get_datadir_fname("fingerprint");
515 log_info(LD_GENERAL
,"Dumping fingerprint to \"%s\"...",keydir
);
516 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint
, 1)<0) {
517 log_err(LD_GENERAL
,"Error computing fingerprint");
521 tor_assert(strlen(options
->Nickname
) <= MAX_NICKNAME_LEN
);
522 if (tor_snprintf(fingerprint_line
, sizeof(fingerprint_line
),
523 "%s %s\n",options
->Nickname
, fingerprint
) < 0) {
524 log_err(LD_GENERAL
,"Error writing fingerprint line");
528 /* Check whether we need to write the fingerprint file. */
530 if (file_status(keydir
) == FN_FILE
)
531 cp
= read_file_to_str(keydir
, 0, NULL
);
532 if (!cp
|| strcmp(cp
, fingerprint_line
)) {
533 if (write_str_to_file(keydir
, fingerprint_line
, 0)) {
534 log_err(LD_FS
, "Error writing fingerprint line to file");
542 log(LOG_NOTICE
, LD_GENERAL
,
543 "Your Tor server's identity key fingerprint is '%s %s'",
544 options
->Nickname
, fingerprint
);
545 if (!authdir_mode(options
))
547 /* 6. [authdirserver only] load approved-routers file */
548 if (dirserv_load_fingerprint_file() < 0) {
549 log_err(LD_GENERAL
,"Error loading fingerprints");
552 /* 6b. [authdirserver only] add own key to approved directories. */
553 crypto_pk_get_digest(get_identity_key(), digest
);
554 type
= ((options
->V1AuthoritativeDir
? V1_AUTHORITY
: NO_AUTHORITY
) |
555 (options
->V2AuthoritativeDir
? V2_AUTHORITY
: NO_AUTHORITY
) |
556 (options
->V3AuthoritativeDir
? V3_AUTHORITY
: NO_AUTHORITY
) |
557 (options
->BridgeAuthoritativeDir
? BRIDGE_AUTHORITY
: NO_AUTHORITY
) |
558 (options
->HSAuthoritativeDir
? HIDSERV_AUTHORITY
: NO_AUTHORITY
));
560 if (!router_get_trusteddirserver_by_digest(digest
)) {
561 add_trusted_dir_server(options
->Nickname
, NULL
,
562 (uint16_t)options
->DirPort
,
563 (uint16_t)options
->ORPort
,
568 if ((ds
= router_get_trusteddirserver_by_digest(digest
))) {
569 if (ds
->type
!= type
) {
570 log_warn(LD_DIR
, "Configured authority type does not match authority "
571 "type in DirServer list. Adjusting. (%d v %d)",
575 if (v3_digest_set
&& (ds
->type
& V3_AUTHORITY
) &&
576 memcmp(v3_digest
, ds
->v3_identity_digest
, DIGEST_LEN
)) {
577 log_warn(LD_DIR
, "V3 identity key does not match identity declared in "
578 "DirServer line. Adjusting.");
579 memcpy(ds
->v3_identity_digest
, v3_digest
, DIGEST_LEN
);
583 return 0; /* success */
586 /* Keep track of whether we should upload our server descriptor,
587 * and what type of server we are.
590 /** Whether we can reach our ORPort from the outside. */
591 static int can_reach_or_port
= 0;
592 /** Whether we can reach our DirPort from the outside. */
593 static int can_reach_dir_port
= 0;
595 /** Forget what we have learned about our reachability status. */
597 router_reset_reachability(void)
599 can_reach_or_port
= can_reach_dir_port
= 0;
602 /** Return 1 if ORPort is known reachable; else return 0. */
604 check_whether_orport_reachable(void)
606 or_options_t
*options
= get_options();
607 return options
->AssumeReachable
||
611 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
613 check_whether_dirport_reachable(void)
615 or_options_t
*options
= get_options();
616 return !options
->DirPort
||
617 options
->AssumeReachable
||
618 we_are_hibernating() ||
622 /** Look at a variety of factors, and return 0 if we don't want to
623 * advertise the fact that we have a DirPort open. Else return the
624 * DirPort we want to advertise.
626 * Log a helpful message if we change our mind about whether to publish
630 decide_to_advertise_dirport(or_options_t
*options
, uint16_t dir_port
)
632 static int advertising
=1; /* start out assuming we will advertise */
634 const char *reason
= NULL
;
636 /* Section one: reasons to publish or not publish that aren't
637 * worth mentioning to the user, either because they're obvious
638 * or because they're normal behavior. */
640 if (!dir_port
) /* short circuit the rest of the function */
642 if (authdir_mode(options
)) /* always publish */
644 if (we_are_hibernating())
646 if (!check_whether_dirport_reachable())
649 /* Section two: reasons to publish or not publish that the user
650 * might find surprising. These are generally config options that
651 * make us choose not to publish. */
653 if (accounting_is_enabled(options
)) {
654 /* if we might potentially hibernate */
656 reason
= "AccountingMax enabled";
657 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
658 } else if (options
->BandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
||
659 (options
->RelayBandwidthRate
> 0 &&
660 options
->RelayBandwidthRate
< MIN_BW_TO_ADVERTISE_DIRPORT
)) {
661 /* if we're advertising a small amount */
663 reason
= "BandwidthRate under 50KB";
666 if (advertising
!= new_choice
) {
667 if (new_choice
== 1) {
668 log(LOG_NOTICE
, LD_DIR
, "Advertising DirPort as %d", dir_port
);
671 log(LOG_NOTICE
, LD_DIR
, "Not advertising DirPort (Reason: %s)", reason
);
673 advertising
= new_choice
;
676 return advertising
? dir_port
: 0;
679 /** Some time has passed, or we just got new directory information.
680 * See if we currently believe our ORPort or DirPort to be
681 * unreachable. If so, launch a new test for it.
683 * For ORPort, we simply try making a circuit that ends at ourselves.
684 * Success is noticed in onionskin_answer().
686 * For DirPort, we make a connection via Tor to our DirPort and ask
687 * for our own server descriptor.
688 * Success is noticed in connection_dir_client_reached_eof().
691 consider_testing_reachability(int test_or
, int test_dir
)
693 routerinfo_t
*me
= router_get_my_routerinfo();
694 int orport_reachable
= check_whether_orport_reachable();
698 if (test_or
&& (!orport_reachable
|| !circuit_enough_testing_circs())) {
699 log_info(LD_CIRC
, "Testing %s of my ORPort: %s:%d.",
700 !orport_reachable
? "reachability" : "bandwidth",
701 me
->address
, me
->or_port
);
702 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING
, me
,
703 CIRCLAUNCH_NEED_CAPACITY
|CIRCLAUNCH_IS_INTERNAL
);
704 control_event_server_status(LOG_NOTICE
,
705 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
706 me
->address
, me
->or_port
);
709 if (test_dir
&& !check_whether_dirport_reachable() &&
710 !connection_get_by_type_addr_port_purpose(
711 CONN_TYPE_DIR
, me
->addr
, me
->dir_port
,
712 DIR_PURPOSE_FETCH_SERVERDESC
)) {
713 /* ask myself, via tor, for my server descriptor. */
714 directory_initiate_command(me
->address
, me
->addr
,
715 me
->or_port
, me
->dir_port
,
716 0, me
->cache_info
.identity_digest
,
717 DIR_PURPOSE_FETCH_SERVERDESC
,
718 ROUTER_PURPOSE_GENERAL
,
719 1, "authority.z", NULL
, 0, 0);
721 control_event_server_status(LOG_NOTICE
,
722 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
723 me
->address
, me
->dir_port
);
727 /** Annotate that we found our ORPort reachable. */
729 router_orport_found_reachable(void)
731 if (!can_reach_or_port
) {
732 routerinfo_t
*me
= router_get_my_routerinfo();
733 log_notice(LD_OR
,"Self-testing indicates your ORPort is reachable from "
734 "the outside. Excellent.%s",
735 get_options()->_PublishServerDescriptor
!= NO_AUTHORITY
?
736 " Publishing server descriptor." : "");
737 can_reach_or_port
= 1;
738 mark_my_descriptor_dirty();
741 control_event_server_status(LOG_NOTICE
,
742 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
743 me
->address
, me
->or_port
);
747 /** Annotate that we found our DirPort reachable. */
749 router_dirport_found_reachable(void)
751 if (!can_reach_dir_port
) {
752 routerinfo_t
*me
= router_get_my_routerinfo();
753 log_notice(LD_DIRSERV
,"Self-testing indicates your DirPort is reachable "
754 "from the outside. Excellent.");
755 can_reach_dir_port
= 1;
756 if (!me
|| decide_to_advertise_dirport(get_options(), me
->dir_port
))
757 mark_my_descriptor_dirty();
760 control_event_server_status(LOG_NOTICE
,
761 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
762 me
->address
, me
->dir_port
);
766 /** We have enough testing circuits open. Send a bunch of "drop"
767 * cells down each of them, to exercise our bandwidth. */
769 router_perform_bandwidth_test(int num_circs
, time_t now
)
771 int num_cells
= (int)(get_options()->BandwidthRate
* 10 / CELL_NETWORK_SIZE
);
772 int max_cells
= num_cells
< CIRCWINDOW_START
?
773 num_cells
: CIRCWINDOW_START
;
774 int cells_per_circuit
= max_cells
/ num_circs
;
775 origin_circuit_t
*circ
= NULL
;
777 log_notice(LD_OR
,"Performing bandwidth self-test...done.");
778 while ((circ
= circuit_get_next_by_pk_and_purpose(circ
, NULL
,
779 CIRCUIT_PURPOSE_TESTING
))) {
780 /* dump cells_per_circuit drop cells onto this circ */
781 int i
= cells_per_circuit
;
782 if (circ
->_base
.state
!= CIRCUIT_STATE_OPEN
)
784 circ
->_base
.timestamp_dirty
= now
;
786 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ
),
788 NULL
, 0, circ
->cpath
->prev
)<0) {
789 return; /* stop if error */
795 /** Return true iff we believe ourselves to be an authoritative
799 authdir_mode(or_options_t
*options
)
801 return options
->AuthoritativeDir
!= 0;
803 /** Return true iff we believe ourselves to be a v1 authoritative
807 authdir_mode_v1(or_options_t
*options
)
809 return authdir_mode(options
) && options
->V1AuthoritativeDir
!= 0;
811 /** Return true iff we believe ourselves to be a v2 authoritative
815 authdir_mode_v2(or_options_t
*options
)
817 return authdir_mode(options
) && options
->V2AuthoritativeDir
!= 0;
819 /** Return true iff we believe ourselves to be a v3 authoritative
823 authdir_mode_v3(or_options_t
*options
)
825 return authdir_mode(options
) && options
->V3AuthoritativeDir
!= 0;
827 /** Return true iff we are a v1, v2, or v3 directory authority. */
829 authdir_mode_any_main(or_options_t
*options
)
831 return options
->V1AuthoritativeDir
||
832 options
->V2AuthoritativeDir
||
833 options
->V3AuthoritativeDir
;
835 /** Return true if we believe ourselves to be any kind of
836 * authoritative directory beyond just a hidserv authority. */
838 authdir_mode_any_nonhidserv(or_options_t
*options
)
840 return options
->BridgeAuthoritativeDir
||
841 authdir_mode_any_main(options
);
843 /** Return true iff we are an authoritative directory server that is
844 * authoritative about receiving and serving descriptors of type
845 * <b>purpose</b> its dirport. Use -1 for "any purpose". */
847 authdir_mode_handles_descs(or_options_t
*options
, int purpose
)
850 return authdir_mode_any_nonhidserv(options
);
851 else if (purpose
== ROUTER_PURPOSE_GENERAL
)
852 return authdir_mode_any_main(options
);
853 else if (purpose
== ROUTER_PURPOSE_BRIDGE
)
854 return (options
->BridgeAuthoritativeDir
);
858 /** Return true iff we are an authoritative directory server that
859 * publishes its own network statuses.
862 authdir_mode_publishes_statuses(or_options_t
*options
)
864 if (authdir_mode_bridge(options
))
866 return authdir_mode_any_nonhidserv(options
);
868 /** Return true iff we are an authoritative directory server that
869 * tests reachability of the descriptors it learns about.
872 authdir_mode_tests_reachability(or_options_t
*options
)
874 return authdir_mode_handles_descs(options
, -1);
876 /** Return true iff we believe ourselves to be a bridge authoritative
880 authdir_mode_bridge(or_options_t
*options
)
882 return authdir_mode(options
) && options
->BridgeAuthoritativeDir
!= 0;
884 /** Return true iff we once tried to stay connected to all ORs at once.
885 * FFFF this function, and the notion of staying connected to ORs, is
886 * nearly obsolete. One day there will be a proposal for getting rid of
890 clique_mode(or_options_t
*options
)
892 return authdir_mode_tests_reachability(options
);
895 /** Return true iff we are trying to be a server.
898 server_mode(or_options_t
*options
)
900 if (options
->ClientOnly
) return 0;
901 return (options
->ORPort
!= 0 || options
->ORListenAddress
);
904 /** Remember if we've advertised ourselves to the dirservers. */
905 static int server_is_advertised
=0;
907 /** Return true iff we have published our descriptor lately.
910 advertised_server_mode(void)
912 return server_is_advertised
;
916 * Called with a boolean: set whether we have recently published our
920 set_server_advertised(int s
)
922 server_is_advertised
= s
;
925 /** Return true iff we are trying to be a socks proxy. */
927 proxy_mode(or_options_t
*options
)
929 return (options
->SocksPort
!= 0 || options
->SocksListenAddress
||
930 options
->TransPort
!= 0 || options
->TransListenAddress
||
931 options
->NatdPort
!= 0 || options
->NatdListenAddress
||
932 options
->DNSPort
!= 0 || options
->DNSListenAddress
);
935 /** Decide if we're a publishable server. We are a publishable server if:
936 * - We don't have the ClientOnly option set
938 * - We have the PublishServerDescriptor option set to non-empty
940 * - We have ORPort set
942 * - We believe we are reachable from the outside; or
943 * - We are an authoritative directory server.
946 decide_if_publishable_server(void)
948 or_options_t
*options
= get_options();
950 if (options
->ClientOnly
)
952 if (options
->_PublishServerDescriptor
== NO_AUTHORITY
)
954 if (!server_mode(options
))
956 if (authdir_mode(options
))
959 return check_whether_orport_reachable();
962 /** Initiate server descriptor upload as reasonable (if server is publishable,
963 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
965 * We need to rebuild the descriptor if it's dirty even if we're not
966 * uploading, because our reachability testing *uses* our descriptor to
967 * determine what IP address and ports to test.
970 consider_publishable_server(int force
)
974 if (!server_mode(get_options()))
977 rebuilt
= router_rebuild_descriptor(0);
978 if (decide_if_publishable_server()) {
979 set_server_advertised(1);
981 router_upload_dir_desc_to_dirservers(force
);
983 set_server_advertised(0);
988 * Clique maintenance -- to be phased out.
991 /** Return true iff we believe this OR tries to keep connections open
992 * to all other ORs. */
994 router_is_clique_mode(routerinfo_t
*router
)
996 if (router_digest_is_trusted_dir(router
->cache_info
.identity_digest
))
1002 * OR descriptor generation.
1005 /** My routerinfo. */
1006 static routerinfo_t
*desc_routerinfo
= NULL
;
1008 static extrainfo_t
*desc_extrainfo
= NULL
;
1009 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1011 static time_t desc_clean_since
= 0;
1012 /** Boolean: do we need to regenerate the above? */
1013 static int desc_needs_upload
= 0;
1015 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1016 * descriptor successfully yet, try to upload our signed descriptor to
1017 * all the directory servers we know about.
1020 router_upload_dir_desc_to_dirservers(int force
)
1025 size_t desc_len
, extra_len
= 0, total_len
;
1026 authority_type_t auth
= get_options()->_PublishServerDescriptor
;
1028 ri
= router_get_my_routerinfo();
1030 log_info(LD_GENERAL
, "No descriptor; skipping upload");
1033 ei
= router_get_my_extrainfo();
1034 if (auth
== NO_AUTHORITY
)
1036 if (!force
&& !desc_needs_upload
)
1038 desc_needs_upload
= 0;
1040 desc_len
= ri
->cache_info
.signed_descriptor_len
;
1041 extra_len
= ei
? ei
->cache_info
.signed_descriptor_len
: 0;
1042 total_len
= desc_len
+ extra_len
+ 1;
1043 msg
= tor_malloc(total_len
);
1044 memcpy(msg
, ri
->cache_info
.signed_descriptor_body
, desc_len
);
1046 memcpy(msg
+desc_len
, ei
->cache_info
.signed_descriptor_body
, extra_len
);
1048 msg
[desc_len
+extra_len
] = 0;
1050 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR
,
1051 (auth
& BRIDGE_AUTHORITY
) ?
1052 ROUTER_PURPOSE_BRIDGE
:
1053 ROUTER_PURPOSE_GENERAL
,
1054 auth
, msg
, desc_len
, extra_len
);
1058 /** OR only: Check whether my exit policy says to allow connection to
1059 * conn. Return 0 if we accept; non-0 if we reject.
1062 router_compare_to_my_exit_policy(edge_connection_t
*conn
)
1064 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1067 /* make sure it's resolved to something. this way we can't get a
1069 if (!conn
->_base
.addr
)
1072 return compare_addr_to_addr_policy(conn
->_base
.addr
, conn
->_base
.port
,
1073 desc_routerinfo
->exit_policy
) != ADDR_POLICY_ACCEPTED
;
1076 /** Return true iff I'm a server and <b>digest</b> is equal to
1077 * my identity digest. */
1079 router_digest_is_me(const char *digest
)
1081 return identitykey
&& !memcmp(identitykey_digest
, digest
, DIGEST_LEN
);
1084 /** A wrapper around router_digest_is_me(). */
1086 router_is_me(routerinfo_t
*router
)
1088 return router_digest_is_me(router
->cache_info
.identity_digest
);
1091 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1093 router_fingerprint_is_me(const char *fp
)
1095 char digest
[DIGEST_LEN
];
1096 if (strlen(fp
) == HEX_DIGEST_LEN
&&
1097 base16_decode(digest
, sizeof(digest
), fp
, HEX_DIGEST_LEN
) == 0)
1098 return router_digest_is_me(digest
);
1103 /** Return a routerinfo for this OR, rebuilding a fresh one if
1104 * necessary. Return NULL on error, or if called on an OP. */
1106 router_get_my_routerinfo(void)
1108 if (!server_mode(get_options()))
1110 if (router_rebuild_descriptor(0))
1112 return desc_routerinfo
;
1115 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1116 * one if necessary. Return NULL on error.
1119 router_get_my_descriptor(void)
1122 if (!router_get_my_routerinfo())
1124 /* Make sure this is nul-terminated. */
1125 tor_assert(desc_routerinfo
->cache_info
.saved_location
== SAVED_NOWHERE
);
1126 body
= signed_descriptor_get_body(&desc_routerinfo
->cache_info
);
1127 tor_assert(!body
[desc_routerinfo
->cache_info
.signed_descriptor_len
]);
1128 log_debug(LD_GENERAL
,"my desc is '%s'", body
);
1132 /* Return the extrainfo document for this OR, or NULL if we have none.
1133 * Rebuilt it (and the server descriptor) if necessary. */
1135 router_get_my_extrainfo(void)
1137 if (!server_mode(get_options()))
1139 if (router_rebuild_descriptor(0))
1141 return desc_extrainfo
;
1144 /** A list of nicknames that we've warned about including in our family
1145 * declaration verbatim rather than as digests. */
1146 static smartlist_t
*warned_nonexistent_family
= NULL
;
1148 static int router_guess_address_from_dir_headers(uint32_t *guess
);
1150 /** Return our current best guess at our address, either because
1151 * it's configured in torrc, or because we've learned it from
1152 * dirserver headers. */
1154 router_pick_published_address(or_options_t
*options
, uint32_t *addr
)
1156 if (resolve_my_address(LOG_INFO
, options
, addr
, NULL
) < 0) {
1157 log_info(LD_CONFIG
, "Could not determine our address locally. "
1158 "Checking if directory headers provide any hints.");
1159 if (router_guess_address_from_dir_headers(addr
) < 0) {
1160 log_info(LD_CONFIG
, "No hints from directory headers either. "
1161 "Will try again later.");
1168 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1169 * routerinfo, signed server descriptor, and extra-info document for this OR.
1170 * Return 0 on success, -1 on temporary error.
1173 router_rebuild_descriptor(int force
)
1179 int hibernating
= we_are_hibernating();
1180 or_options_t
*options
= get_options();
1182 if (desc_clean_since
&& !force
)
1185 if (router_pick_published_address(options
, &addr
) < 0) {
1186 /* Stop trying to rebuild our descriptor every second. We'll
1187 * learn that it's time to try again when server_has_changed_ip()
1188 * marks it dirty. */
1189 desc_clean_since
= time(NULL
);
1193 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
1194 ri
->cache_info
.routerlist_index
= -1;
1195 ri
->address
= tor_dup_addr(addr
);
1196 ri
->nickname
= tor_strdup(options
->Nickname
);
1198 ri
->or_port
= options
->ORPort
;
1199 ri
->dir_port
= options
->DirPort
;
1200 ri
->cache_info
.published_on
= time(NULL
);
1201 ri
->onion_pkey
= crypto_pk_dup_key(get_onion_key()); /* must invoke from
1203 ri
->identity_pkey
= crypto_pk_dup_key(get_identity_key());
1204 if (crypto_pk_get_digest(ri
->identity_pkey
,
1205 ri
->cache_info
.identity_digest
)<0) {
1206 routerinfo_free(ri
);
1209 get_platform_str(platform
, sizeof(platform
));
1210 ri
->platform
= tor_strdup(platform
);
1212 /* compute ri->bandwidthrate as the min of various options */
1213 ri
->bandwidthrate
= (int)options
->BandwidthRate
;
1214 if (ri
->bandwidthrate
> options
->MaxAdvertisedBandwidth
)
1215 ri
->bandwidthrate
= (int)options
->MaxAdvertisedBandwidth
;
1216 if (options
->RelayBandwidthRate
> 0 &&
1217 ri
->bandwidthrate
> options
->RelayBandwidthRate
)
1218 ri
->bandwidthrate
= (int)options
->RelayBandwidthRate
;
1220 /* and compute ri->bandwidthburst similarly */
1221 ri
->bandwidthburst
= (int)options
->BandwidthBurst
;
1222 if (options
->RelayBandwidthBurst
> 0 &&
1223 ri
->bandwidthburst
> options
->RelayBandwidthBurst
)
1224 ri
->bandwidthburst
= (int)options
->RelayBandwidthBurst
;
1226 ri
->bandwidthcapacity
= hibernating
? 0 : rep_hist_bandwidth_assess();
1228 policies_parse_exit_policy(options
->ExitPolicy
, &ri
->exit_policy
,
1229 options
->ExitPolicyRejectPrivate
,
1232 if (desc_routerinfo
) { /* inherit values */
1233 ri
->is_valid
= desc_routerinfo
->is_valid
;
1234 ri
->is_running
= desc_routerinfo
->is_running
;
1235 ri
->is_named
= desc_routerinfo
->is_named
;
1237 if (authdir_mode(options
))
1238 ri
->is_valid
= ri
->is_named
= 1; /* believe in yourself */
1239 if (options
->MyFamily
) {
1240 smartlist_t
*family
;
1241 if (!warned_nonexistent_family
)
1242 warned_nonexistent_family
= smartlist_create();
1243 family
= smartlist_create();
1244 ri
->declared_family
= smartlist_create();
1245 smartlist_split_string(family
, options
->MyFamily
, ",",
1246 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1247 SMARTLIST_FOREACH(family
, char *, name
,
1249 routerinfo_t
*member
;
1250 if (!strcasecmp(name
, options
->Nickname
))
1253 member
= router_get_by_nickname(name
, 1);
1255 int is_legal
= is_legal_nickname_or_hexdigest(name
);
1256 if (!smartlist_string_isin(warned_nonexistent_family
, name
) &&
1257 !is_legal_hexdigest(name
)) {
1260 "I have no descriptor for the router named \"%s\" in my "
1261 "declared family; I'll use the nickname as is, but "
1262 "this may confuse clients.", name
);
1264 log_warn(LD_CONFIG
, "There is a router named \"%s\" in my "
1265 "declared family, but that isn't a legal nickname. "
1266 "Skipping it.", escaped(name
));
1267 smartlist_add(warned_nonexistent_family
, tor_strdup(name
));
1270 smartlist_add(ri
->declared_family
, name
);
1273 } else if (router_is_me(member
)) {
1274 /* Don't list ourself in our own family; that's redundant */
1276 char *fp
= tor_malloc(HEX_DIGEST_LEN
+2);
1278 base16_encode(fp
+1,HEX_DIGEST_LEN
+1,
1279 member
->cache_info
.identity_digest
, DIGEST_LEN
);
1280 smartlist_add(ri
->declared_family
, fp
);
1281 if (smartlist_string_isin(warned_nonexistent_family
, name
))
1282 smartlist_string_remove(warned_nonexistent_family
, name
);
1287 /* remove duplicates from the list */
1288 smartlist_sort_strings(ri
->declared_family
);
1289 smartlist_uniq_strings(ri
->declared_family
);
1291 smartlist_free(family
);
1294 /* Now generate the extrainfo. */
1295 ei
= tor_malloc_zero(sizeof(extrainfo_t
));
1296 ei
->cache_info
.is_extrainfo
= 1;
1297 strlcpy(ei
->nickname
, get_options()->Nickname
, sizeof(ei
->nickname
));
1298 ei
->cache_info
.published_on
= ri
->cache_info
.published_on
;
1299 memcpy(ei
->cache_info
.identity_digest
, ri
->cache_info
.identity_digest
,
1301 ei
->cache_info
.signed_descriptor_body
= tor_malloc(8192);
1302 if (extrainfo_dump_to_string(ei
->cache_info
.signed_descriptor_body
, 8192,
1303 ei
, get_identity_key()) < 0) {
1304 log_warn(LD_BUG
, "Couldn't generate extra-info descriptor.");
1307 ei
->cache_info
.signed_descriptor_len
=
1308 strlen(ei
->cache_info
.signed_descriptor_body
);
1309 router_get_extrainfo_hash(ei
->cache_info
.signed_descriptor_body
,
1310 ei
->cache_info
.signed_descriptor_digest
);
1312 /* Now finish the router descriptor. */
1313 memcpy(ri
->cache_info
.extra_info_digest
,
1314 ei
->cache_info
.signed_descriptor_digest
,
1316 ri
->cache_info
.signed_descriptor_body
= tor_malloc(8192);
1317 if (router_dump_router_to_string(ri
->cache_info
.signed_descriptor_body
, 8192,
1318 ri
, get_identity_key())<0) {
1319 log_warn(LD_BUG
, "Couldn't generate router descriptor.");
1322 ri
->cache_info
.signed_descriptor_len
=
1323 strlen(ri
->cache_info
.signed_descriptor_body
);
1325 router_get_router_hash(ri
->cache_info
.signed_descriptor_body
,
1326 ri
->cache_info
.signed_descriptor_digest
);
1328 tor_assert(! routerinfo_incompatible_with_extrainfo(ri
, ei
, NULL
, NULL
));
1330 if (desc_routerinfo
)
1331 routerinfo_free(desc_routerinfo
);
1332 desc_routerinfo
= ri
;
1334 extrainfo_free(desc_extrainfo
);
1335 desc_extrainfo
= ei
;
1337 desc_clean_since
= time(NULL
);
1338 desc_needs_upload
= 1;
1339 control_event_my_descriptor_changed();
1343 /** Mark descriptor out of date if it's older than <b>when</b> */
1345 mark_my_descriptor_dirty_if_older_than(time_t when
)
1347 if (desc_clean_since
< when
)
1348 mark_my_descriptor_dirty();
1351 /** Call when the current descriptor is out of date. */
1353 mark_my_descriptor_dirty(void)
1355 desc_clean_since
= 0;
1358 /** How frequently will we republish our descriptor because of large (factor
1359 * of 2) shifts in estimated bandwidth? */
1360 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
1362 /** Check whether bandwidth has changed a lot since the last time we announced
1363 * bandwidth. If so, mark our descriptor dirty. */
1365 check_descriptor_bandwidth_changed(time_t now
)
1367 static time_t last_changed
= 0;
1369 if (!desc_routerinfo
)
1372 prev
= desc_routerinfo
->bandwidthcapacity
;
1373 cur
= we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
1374 if ((prev
!= cur
&& (!prev
|| !cur
)) ||
1377 if (last_changed
+MAX_BANDWIDTH_CHANGE_FREQ
< now
) {
1378 log_info(LD_GENERAL
,
1379 "Measured bandwidth has changed; rebuilding descriptor.");
1380 mark_my_descriptor_dirty();
1386 /** Note at log level severity that our best guess of address has changed from
1387 * <b>prev</b> to <b>cur</b>. */
1389 log_addr_has_changed(int severity
, uint32_t prev
, uint32_t cur
)
1391 char addrbuf_prev
[INET_NTOA_BUF_LEN
];
1392 char addrbuf_cur
[INET_NTOA_BUF_LEN
];
1393 struct in_addr in_prev
;
1394 struct in_addr in_cur
;
1396 in_prev
.s_addr
= htonl(prev
);
1397 tor_inet_ntoa(&in_prev
, addrbuf_prev
, sizeof(addrbuf_prev
));
1399 in_cur
.s_addr
= htonl(cur
);
1400 tor_inet_ntoa(&in_cur
, addrbuf_cur
, sizeof(addrbuf_cur
));
1403 log_fn(severity
, LD_GENERAL
,
1404 "Our IP Address has changed from %s to %s; "
1405 "rebuilding descriptor.",
1406 addrbuf_prev
, addrbuf_cur
);
1408 log_notice(LD_GENERAL
,
1409 "Guessed our IP address as %s.",
1413 /** Check whether our own address as defined by the Address configuration
1414 * has changed. This is for routers that get their address from a service
1415 * like dyndns. If our address has changed, mark our descriptor dirty. */
1417 check_descriptor_ipaddress_changed(time_t now
)
1420 or_options_t
*options
= get_options();
1423 if (!desc_routerinfo
)
1426 prev
= desc_routerinfo
->addr
;
1427 if (resolve_my_address(LOG_INFO
, options
, &cur
, NULL
) < 0) {
1428 log_info(LD_CONFIG
,"options->Address didn't resolve into an IP.");
1433 log_addr_has_changed(LOG_INFO
, prev
, cur
);
1434 ip_address_changed(0);
1438 /** The most recently guessed value of our IP address, based on directory
1440 static uint32_t last_guessed_ip
= 0;
1442 /** A directory server told us our IP address is <b>suggestion</b>.
1443 * If this address is different from the one we think we are now, and
1444 * if our computer doesn't actually know its IP address, then switch. */
1446 router_new_address_suggestion(const char *suggestion
)
1448 uint32_t addr
, cur
= 0;
1450 or_options_t
*options
= get_options();
1452 /* first, learn what the IP address actually is */
1453 if (!tor_inet_aton(suggestion
, &in
)) {
1454 log_debug(LD_DIR
, "Malformed X-Your-Address-Is header %s. Ignoring.",
1455 escaped(suggestion
));
1458 addr
= ntohl(in
.s_addr
);
1460 log_debug(LD_DIR
, "Got X-Your-Address-Is: %s.", suggestion
);
1462 if (!server_mode(options
)) {
1463 last_guessed_ip
= addr
; /* store it in case we need it later */
1467 if (resolve_my_address(LOG_INFO
, options
, &cur
, NULL
) >= 0) {
1468 /* We're all set -- we already know our address. Great. */
1469 last_guessed_ip
= cur
; /* store it in case we need it later */
1472 if (is_internal_IP(addr
, 0)) {
1473 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1477 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1478 * us an answer different from what we had the last time we managed to
1480 if (last_guessed_ip
!= addr
) {
1481 control_event_server_status(LOG_NOTICE
,
1482 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1484 log_addr_has_changed(LOG_NOTICE
, last_guessed_ip
, addr
);
1485 ip_address_changed(0);
1486 last_guessed_ip
= addr
; /* router_rebuild_descriptor() will fetch it */
1490 /** We failed to resolve our address locally, but we'd like to build
1491 * a descriptor and publish / test reachability. If we have a guess
1492 * about our address based on directory headers, answer it and return
1493 * 0; else return -1. */
1495 router_guess_address_from_dir_headers(uint32_t *guess
)
1497 if (last_guessed_ip
) {
1498 *guess
= last_guessed_ip
;
1504 extern const char tor_svn_revision
[]; /* from main.c */
1506 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1507 * string describing the version of Tor and the operating system we're
1508 * currently running on.
1511 get_platform_str(char *platform
, size_t len
)
1513 tor_snprintf(platform
, len
, "Tor %s on %s", get_version(), get_uname());
1516 /* XXX need to audit this thing and count fenceposts. maybe
1517 * refactor so we don't have to keep asking if we're
1518 * near the end of maxlen?
1520 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1522 /** OR only: Given a routerinfo for this router, and an identity key to sign
1523 * with, encode the routerinfo as a signed server descriptor and write the
1524 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1525 * failure, and the number of bytes used on success.
1528 router_dump_router_to_string(char *s
, size_t maxlen
, routerinfo_t
*router
,
1529 crypto_pk_env_t
*ident_key
)
1531 char *onion_pkey
; /* Onion key, PEM-encoded. */
1532 char *identity_pkey
; /* Identity key, PEM-encoded. */
1533 char digest
[DIGEST_LEN
];
1534 char published
[ISO_TIME_LEN
+1];
1535 char fingerprint
[FINGERPRINT_LEN
+1];
1536 char extra_info_digest
[HEX_DIGEST_LEN
+1];
1537 size_t onion_pkeylen
, identity_pkeylen
;
1540 addr_policy_t
*tmpe
;
1542 or_options_t
*options
= get_options();
1544 /* Make sure the identity key matches the one in the routerinfo. */
1545 if (crypto_pk_cmp_keys(ident_key
, router
->identity_pkey
)) {
1546 log_warn(LD_BUG
,"Tried to sign a router with a private key that didn't "
1547 "match router's public key!");
1551 /* record our fingerprint, so we can include it in the descriptor */
1552 if (crypto_pk_get_fingerprint(router
->identity_pkey
, fingerprint
, 1)<0) {
1553 log_err(LD_BUG
,"Error computing fingerprint");
1557 /* PEM-encode the onion key */
1558 if (crypto_pk_write_public_key_to_string(router
->onion_pkey
,
1559 &onion_pkey
,&onion_pkeylen
)<0) {
1560 log_warn(LD_BUG
,"write onion_pkey to string failed!");
1564 /* PEM-encode the identity key key */
1565 if (crypto_pk_write_public_key_to_string(router
->identity_pkey
,
1566 &identity_pkey
,&identity_pkeylen
)<0) {
1567 log_warn(LD_BUG
,"write identity_pkey to string failed!");
1568 tor_free(onion_pkey
);
1572 /* Encode the publication time. */
1573 format_iso_time(published
, router
->cache_info
.published_on
);
1575 if (router
->declared_family
&& smartlist_len(router
->declared_family
)) {
1577 char *family
= smartlist_join_strings(router
->declared_family
, " ", 0, &n
);
1578 n
+= strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1579 family_line
= tor_malloc(n
);
1580 tor_snprintf(family_line
, n
, "family %s\n", family
);
1583 family_line
= tor_strdup("");
1586 base16_encode(extra_info_digest
, sizeof(extra_info_digest
),
1587 router
->cache_info
.extra_info_digest
, DIGEST_LEN
);
1589 /* Generate the easy portion of the router descriptor. */
1590 result
= tor_snprintf(s
, maxlen
,
1591 "router %s %s %d 0 %d\n"
1593 "opt protocols Link 1 Circuit 1\n"
1595 "opt fingerprint %s\n"
1597 "bandwidth %d %d %d\n"
1598 "opt extra-info-digest %s\n%s"
1605 decide_to_advertise_dirport(options
, router
->dir_port
),
1609 stats_n_seconds_working
,
1610 (int) router
->bandwidthrate
,
1611 (int) router
->bandwidthburst
,
1612 (int) router
->bandwidthcapacity
,
1614 options
->DownloadExtraInfo
? "opt caches-extra-info\n" : "",
1615 onion_pkey
, identity_pkey
,
1617 we_are_hibernating() ? "opt hibernating 1\n" : "",
1618 options
->HidServDirectoryV2
? "opt hidden-service-dir\n" : "");
1620 tor_free(family_line
);
1621 tor_free(onion_pkey
);
1622 tor_free(identity_pkey
);
1625 log_warn(LD_BUG
,"descriptor snprintf #1 ran out of room!");
1628 /* From now on, we use 'written' to remember the current length of 's'. */
1631 if (options
->ContactInfo
&& strlen(options
->ContactInfo
)) {
1632 const char *ci
= options
->ContactInfo
;
1633 if (strchr(ci
, '\n') || strchr(ci
, '\r'))
1635 result
= tor_snprintf(s
+written
,maxlen
-written
, "contact %s\n", ci
);
1637 log_warn(LD_BUG
,"descriptor snprintf #2 ran out of room!");
1643 /* Write the exit policy to the end of 's'. */
1644 if (dns_seems_to_be_broken()) {
1645 /* DNS is screwed up; don't claim to be an exit. */
1646 strlcat(s
+written
, "reject *:*\n", maxlen
-written
);
1647 written
+= strlen("reject *:*\n");
1649 } else if (router
->exit_policy
) {
1651 for (i
= 0; i
< smartlist_len(router
->exit_policy
); ++i
) {
1652 tmpe
= smartlist_get(router
->exit_policy
, i
);
1653 result
= policy_write_item(s
+written
, maxlen
-written
, tmpe
);
1655 log_warn(LD_BUG
,"descriptor policy_write_item ran out of room!");
1658 tor_assert(result
== (int)strlen(s
+written
));
1660 if (written
+2 > maxlen
) {
1661 log_warn(LD_BUG
,"descriptor policy_write_item ran out of room (2)!");
1664 s
[written
++] = '\n';
1668 if (written
+256 > maxlen
) { /* Not enough room for signature. */
1669 log_warn(LD_BUG
,"not enough room left in descriptor for signature!");
1673 /* Sign the directory */
1674 strlcpy(s
+written
, "router-signature\n", maxlen
-written
);
1675 written
+= strlen(s
+written
);
1677 if (router_get_router_hash(s
, digest
) < 0) {
1681 note_crypto_pk_op(SIGN_RTR
);
1682 if (router_append_dirobj_signature(s
+written
,maxlen
-written
,
1683 digest
,ident_key
)<0) {
1684 log_warn(LD_BUG
, "Couldn't sign router descriptor");
1687 written
+= strlen(s
+written
);
1689 if (written
+2 > maxlen
) {
1690 log_warn(LD_BUG
,"Not enough room to finish descriptor.");
1693 /* include a last '\n' */
1697 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1701 routerinfo_t
*ri_tmp
;
1702 cp
= s_dup
= tor_strdup(s
);
1703 ri_tmp
= router_parse_entry_from_string(cp
, NULL
, 1, 0, NULL
);
1706 "We just generated a router descriptor we can't parse.");
1707 log_err(LD_BUG
, "Descriptor was: <<%s>>", s
);
1711 routerinfo_free(ri_tmp
);
1718 /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
1719 * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
1720 * negative on failure. */
1722 extrainfo_dump_to_string(char *s
, size_t maxlen
, extrainfo_t
*extrainfo
,
1723 crypto_pk_env_t
*ident_key
)
1725 or_options_t
*options
= get_options();
1726 char identity
[HEX_DIGEST_LEN
+1];
1727 char published
[ISO_TIME_LEN
+1];
1728 char digest
[DIGEST_LEN
];
1729 char *bandwidth_usage
;
1733 base16_encode(identity
, sizeof(identity
),
1734 extrainfo
->cache_info
.identity_digest
, DIGEST_LEN
);
1735 format_iso_time(published
, extrainfo
->cache_info
.published_on
);
1736 bandwidth_usage
= rep_hist_get_bandwidth_lines(1);
1738 result
= tor_snprintf(s
, maxlen
,
1739 "extra-info %s %s\n"
1741 extrainfo
->nickname
, identity
,
1742 published
, bandwidth_usage
);
1743 tor_free(bandwidth_usage
);
1747 if (options
->BridgeRelay
&& options
->BridgeRecordUsageByCountry
) {
1748 char *geoip_summary
= geoip_get_client_history(time(NULL
));
1749 if (geoip_summary
) {
1750 char geoip_start
[ISO_TIME_LEN
+1];
1751 format_iso_time(geoip_start
, geoip_get_history_start());
1752 result
= tor_snprintf(s
+strlen(s
), maxlen
-strlen(s
),
1753 "geoip-start-time %s\n"
1754 "geoip-client-origins %s\n",
1755 geoip_start
, geoip_summary
);
1756 tor_free(geoip_summary
);
1763 strlcat(s
+len
, "router-signature\n", maxlen
-len
);
1764 len
+= strlen(s
+len
);
1765 if (router_get_extrainfo_hash(s
, digest
)<0)
1767 if (router_append_dirobj_signature(s
+len
, maxlen
-len
, digest
, ident_key
)<0)
1770 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1773 extrainfo_t
*ei_tmp
;
1774 cp
= s_dup
= tor_strdup(s
);
1775 ei_tmp
= extrainfo_parse_entry_from_string(cp
, NULL
, 1, NULL
);
1778 "We just generated an extrainfo descriptor we can't parse.");
1779 log_err(LD_BUG
, "Descriptor was: <<%s>>", s
);
1783 extrainfo_free(ei_tmp
);
1790 /** Return true iff <b>s</b> is a legally valid server nickname. */
1792 is_legal_nickname(const char *s
)
1797 return len
> 0 && len
<= MAX_NICKNAME_LEN
&&
1798 strspn(s
,LEGAL_NICKNAME_CHARACTERS
) == len
;
1801 /** Return true iff <b>s</b> is a legally valid server nickname or
1802 * hex-encoded identity-key digest. */
1804 is_legal_nickname_or_hexdigest(const char *s
)
1807 return is_legal_nickname(s
);
1809 return is_legal_hexdigest(s
);
1812 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
1815 is_legal_hexdigest(const char *s
)
1819 if (s
[0] == '$') s
++;
1821 if (len
> HEX_DIGEST_LEN
) {
1822 if (s
[HEX_DIGEST_LEN
] == '=' ||
1823 s
[HEX_DIGEST_LEN
] == '~') {
1824 if (!is_legal_nickname(s
+HEX_DIGEST_LEN
+1))
1830 return (len
>= HEX_DIGEST_LEN
&&
1831 strspn(s
,HEX_CHARACTERS
)==HEX_DIGEST_LEN
);
1834 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
1835 * verbose representation of the identity of <b>router</b>. The format is:
1837 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
1838 * A "=" if the router is named; a "~" if it is not.
1839 * The router's nickname.
1842 router_get_verbose_nickname(char *buf
, routerinfo_t
*router
)
1845 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, router
->cache_info
.identity_digest
,
1847 buf
[1+HEX_DIGEST_LEN
] = router
->is_named
? '=' : '~';
1848 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, router
->nickname
, MAX_NICKNAME_LEN
+1);
1851 /** Forget that we have issued any router-related warnings, so that we'll
1852 * warn again if we see the same errors. */
1854 router_reset_warnings(void)
1856 if (warned_nonexistent_family
) {
1857 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
1858 smartlist_clear(warned_nonexistent_family
);
1862 /** Given a router purpose, convert it to a string. Don't call this on
1863 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
1864 * know its string representation. */
1866 router_purpose_to_string(uint8_t p
)
1870 case ROUTER_PURPOSE_GENERAL
: return "general";
1871 case ROUTER_PURPOSE_BRIDGE
: return "bridge";
1872 case ROUTER_PURPOSE_CONTROLLER
: return "controller";
1879 /** Given a string, convert it to a router purpose. */
1881 router_purpose_from_string(const char *s
)
1883 if (!strcmp(s
, "general"))
1884 return ROUTER_PURPOSE_GENERAL
;
1885 else if (!strcmp(s
, "bridge"))
1886 return ROUTER_PURPOSE_BRIDGE
;
1887 else if (!strcmp(s
, "controller"))
1888 return ROUTER_PURPOSE_CONTROLLER
;
1890 return ROUTER_PURPOSE_UNKNOWN
;
1893 /** Release all static resources held in router.c */
1895 router_free_all(void)
1898 crypto_free_pk_env(onionkey
);
1900 crypto_free_pk_env(lastonionkey
);
1902 crypto_free_pk_env(identitykey
);
1904 tor_mutex_free(key_lock
);
1905 if (desc_routerinfo
)
1906 routerinfo_free(desc_routerinfo
);
1908 extrainfo_free(desc_extrainfo
);
1909 if (authority_signing_key
)
1910 crypto_free_pk_env(authority_signing_key
);
1911 if (authority_key_certificate
)
1912 authority_cert_free(authority_key_certificate
);
1914 if (warned_nonexistent_family
) {
1915 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
1916 smartlist_free(warned_nonexistent_family
);