1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
4 /* See LICENSE for licensing information */
6 const char router_c_id
[] =
13 * \brief OR functionality, including key maintenance, generating
14 * and uploading server descriptors, retrying OR connections.
17 extern long stats_n_seconds_working
;
19 /* Exposed for test.c. */ void get_platform_str(char *platform
, size_t len
);
21 /************************************************************/
24 * Key management: ORs only.
27 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
29 static tor_mutex_t
*key_lock
=NULL
;
30 static time_t onionkey_set_at
=0; /**< When was onionkey last changed? */
31 /** Current private onionskin decryption key: used to decode CREATE cells. */
32 static crypto_pk_env_t
*onionkey
=NULL
;
33 /** Previous private onionskin decription key: used to decode CREATE cells
34 * generated by clients that have an older version of our descriptor. */
35 static crypto_pk_env_t
*lastonionkey
=NULL
;
36 /** Private "identity key": used to sign directory info and TLS
37 * certificates. Never changes. */
38 static crypto_pk_env_t
*identitykey
=NULL
;
39 /** Digest of identitykey. */
40 static char identitykey_digest
[DIGEST_LEN
];
42 /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
43 * to update onionkey correctly, call rotate_onion_key().
46 set_onion_key(crypto_pk_env_t
*k
)
48 tor_mutex_acquire(key_lock
);
50 onionkey_set_at
= time(NULL
);
51 tor_mutex_release(key_lock
);
52 mark_my_descriptor_dirty();
55 /** Return the current onion key. Requires that the onion key has been
56 * loaded or generated. */
64 /** Store a copy of the current onion key into *<b>key</b>, and a copy
65 * of the most recent onion key into *<b>last</b>.
68 dup_onion_keys(crypto_pk_env_t
**key
, crypto_pk_env_t
**last
)
72 tor_mutex_acquire(key_lock
);
74 *key
= crypto_pk_dup_key(onionkey
);
76 *last
= crypto_pk_dup_key(lastonionkey
);
79 tor_mutex_release(key_lock
);
82 /** Return the time when the onion key was last set. This is either the time
83 * when the process launched, or the time of the most recent key rotation since
84 * the process launched.
87 get_onion_key_set_at(void)
89 return onionkey_set_at
;
92 /** Set the current identity key to k.
95 set_identity_key(crypto_pk_env_t
*k
)
98 crypto_free_pk_env(identitykey
);
100 crypto_pk_get_digest(identitykey
, identitykey_digest
);
103 /** Returns the current identity key; requires that the identity key has been
107 get_identity_key(void)
109 tor_assert(identitykey
);
113 /** Return true iff the identity key has been set. */
115 identity_key_is_set(void)
117 return identitykey
!= NULL
;
120 /** Replace the previous onion key with the current onion key, and generate
121 * a new previous onion key. Immediately after calling this function,
123 * - schedule all previous cpuworkers to shut down _after_ processing
124 * pending work. (This will cause fresh cpuworkers to be generated.)
125 * - generate and upload a fresh routerinfo.
128 rotate_onion_key(void)
131 char fname_prev
[512];
132 crypto_pk_env_t
*prkey
;
133 or_state_t
*state
= get_or_state();
135 tor_snprintf(fname
,sizeof(fname
),
136 "%s/keys/secret_onion_key",get_options()->DataDirectory
);
137 tor_snprintf(fname_prev
,sizeof(fname_prev
),
138 "%s/keys/secret_onion_key.old",get_options()->DataDirectory
);
139 if (!(prkey
= crypto_new_pk_env())) {
140 log_err(LD_GENERAL
,"Error constructing rotated onion key");
143 if (crypto_pk_generate_key(prkey
)) {
144 log_err(LD_BUG
,"Error generating onion key");
147 if (file_status(fname
) == FN_FILE
) {
148 if (replace_file(fname
, fname_prev
))
151 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
152 log_err(LD_FS
,"Couldn't write generated onion key to \"%s\".", fname
);
155 log_info(LD_GENERAL
, "Rotating onion key");
156 tor_mutex_acquire(key_lock
);
158 crypto_free_pk_env(lastonionkey
);
159 lastonionkey
= onionkey
;
162 state
->LastRotatedOnionKey
= onionkey_set_at
= now
;
163 tor_mutex_release(key_lock
);
164 mark_my_descriptor_dirty();
165 or_state_mark_dirty(state
, get_options()->AvoidDiskWrites
? now
+3600 : 0);
168 log_warn(LD_GENERAL
, "Couldn't rotate onion key.");
171 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
172 * create a new RSA key and save it in <b>fname</b>. Return the read/created
173 * key, or NULL on error.
176 init_key_from_file(const char *fname
)
178 crypto_pk_env_t
*prkey
= NULL
;
181 if (!(prkey
= crypto_new_pk_env())) {
182 log_err(LD_GENERAL
,"Error constructing key");
186 switch (file_status(fname
)) {
189 log_err(LD_FS
,"Can't read key from \"%s\"", fname
);
192 log_info(LD_GENERAL
, "No key found in \"%s\"; generating fresh key.",
194 if (crypto_pk_generate_key(prkey
)) {
195 log_err(LD_GENERAL
,"Error generating onion key");
198 if (crypto_pk_check_key(prkey
) <= 0) {
199 log_err(LD_GENERAL
,"Generated key seems invalid");
202 log_info(LD_GENERAL
, "Generated key seems valid");
203 if (crypto_pk_write_private_key_to_filename(prkey
, fname
)) {
204 log_err(LD_FS
,"Couldn't write generated key to \"%s\".", fname
);
209 if (crypto_pk_read_private_key_from_filename(prkey
, fname
)) {
210 log_err(LD_GENERAL
,"Error loading private key.");
220 crypto_free_pk_env(prkey
);
226 /** Initialize all OR private keys, and the TLS context, as necessary.
227 * On OPs, this only initializes the tls context. Return 0 on success,
228 * or -1 if Tor should die.
234 char fingerprint
[FINGERPRINT_LEN
+1];
235 /*nickname<space>fp\n\0 */
236 char fingerprint_line
[MAX_NICKNAME_LEN
+FINGERPRINT_LEN
+3];
237 const char *mydesc
, *datadir
;
238 crypto_pk_env_t
*prkey
;
241 or_options_t
*options
= get_options();
242 or_state_t
*state
= get_or_state();
245 key_lock
= tor_mutex_new();
247 /* OP's don't need persistent keys; just make up an identity and
248 * initialize the TLS context. */
249 if (!server_mode(options
)) {
250 if (!(prkey
= crypto_new_pk_env()))
252 if (crypto_pk_generate_key(prkey
))
254 set_identity_key(prkey
);
255 /* Create a TLS context; default the client nickname to "client". */
256 if (tor_tls_context_new(get_identity_key(),
257 options
->Nickname
? options
->Nickname
: "client",
258 MAX_SSL_KEY_LIFETIME
) < 0) {
259 log_err(LD_GENERAL
,"Error creating TLS context for Tor client.");
264 /* Make sure DataDirectory exists, and is private. */
265 datadir
= options
->DataDirectory
;
266 if (check_private_dir(datadir
, CPD_CREATE
)) {
269 /* Check the key directory. */
270 tor_snprintf(keydir
,sizeof(keydir
),"%s/keys", datadir
);
271 if (check_private_dir(keydir
, CPD_CREATE
)) {
275 /* 1. Read identity key. Make it if none is found. */
276 tor_snprintf(keydir
,sizeof(keydir
),"%s/keys/secret_id_key",datadir
);
277 log_info(LD_GENERAL
,"Reading/making identity key \"%s\"...",keydir
);
278 prkey
= init_key_from_file(keydir
);
279 if (!prkey
) return -1;
280 set_identity_key(prkey
);
281 /* 2. Read onion key. Make it if none is found. */
282 tor_snprintf(keydir
,sizeof(keydir
),"%s/keys/secret_onion_key",datadir
);
283 log_info(LD_GENERAL
,"Reading/making onion key \"%s\"...",keydir
);
284 prkey
= init_key_from_file(keydir
);
285 if (!prkey
) return -1;
286 set_onion_key(prkey
);
287 if (state
->LastRotatedOnionKey
> 100) { /* allow for some parsing slop. */
288 onionkey_set_at
= state
->LastRotatedOnionKey
;
290 /* We have no LastRotatedOnionKey set; either we just created the key
291 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
292 * start the clock ticking now so that we will eventually rotate it even
293 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
294 state
->LastRotatedOnionKey
= onionkey_set_at
= time(NULL
);
295 or_state_mark_dirty(state
, options
->AvoidDiskWrites
? time(NULL
)+3600 : 0);
298 tor_snprintf(keydir
,sizeof(keydir
),"%s/keys/secret_onion_key.old",datadir
);
299 if (file_status(keydir
) == FN_FILE
) {
300 prkey
= init_key_from_file(keydir
);
302 lastonionkey
= prkey
;
305 /* 3. Initialize link key and TLS context. */
306 if (tor_tls_context_new(get_identity_key(), options
->Nickname
,
307 MAX_SSL_KEY_LIFETIME
) < 0) {
308 log_err(LD_GENERAL
,"Error initializing TLS context");
311 /* 4. Build our router descriptor. */
312 /* Must be called after keys are initialized. */
313 mydesc
= router_get_my_descriptor();
314 if (authdir_mode(options
)) {
316 /* We need to add our own fingerprint so it gets recognized. */
317 if (dirserv_add_own_fingerprint(options
->Nickname
, get_identity_key())) {
318 log_err(LD_GENERAL
,"Error adding own fingerprint to approved set");
322 log_err(LD_GENERAL
,"Error initializing descriptor.");
325 if (dirserv_add_descriptor(mydesc
, &m
) < 0) {
326 log_err(LD_GENERAL
,"Unable to add own descriptor to directory: %s",
327 m
?m
:"<unknown error>");
332 /* 5. Dump fingerprint to 'fingerprint' */
333 tor_snprintf(keydir
,sizeof(keydir
),"%s/fingerprint", datadir
);
334 log_info(LD_GENERAL
,"Dumping fingerprint to \"%s\"...",keydir
);
335 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint
, 1)<0) {
336 log_err(LD_GENERAL
,"Error computing fingerprint");
339 tor_assert(strlen(options
->Nickname
) <= MAX_NICKNAME_LEN
);
340 if (tor_snprintf(fingerprint_line
, sizeof(fingerprint_line
),
341 "%s %s\n",options
->Nickname
, fingerprint
) < 0) {
342 log_err(LD_GENERAL
,"Error writing fingerprint line");
345 /* Check whether we need to write the fingerprint file. */
347 if (file_status(keydir
) == FN_FILE
)
348 cp
= read_file_to_str(keydir
, 0, NULL
);
349 if (!cp
|| strcmp(cp
, fingerprint_line
)) {
350 if (write_str_to_file(keydir
, fingerprint_line
, 0)) {
351 log_err(LD_FS
, "Error writing fingerprint line to file");
357 log(LOG_NOTICE
, LD_GENERAL
,
358 "Your Tor server's identity key fingerprint is '%s %s'",
359 options
->Nickname
, fingerprint
);
360 if (!authdir_mode(options
))
362 /* 6. [authdirserver only] load approved-routers file */
363 if (dirserv_load_fingerprint_file() < 0) {
364 log_err(LD_GENERAL
,"Error loading fingerprints");
367 /* 6b. [authdirserver only] add own key to approved directories. */
368 crypto_pk_get_digest(get_identity_key(), digest
);
369 if (!router_digest_is_trusted_dir(digest
)) {
370 add_trusted_dir_server(options
->Nickname
, NULL
,
371 (uint16_t)options
->DirPort
,
372 (uint16_t)options
->ORPort
,
374 options
->V1AuthoritativeDir
, /* v1 authority */
375 1, /* v2 authority */
376 options
->HSAuthoritativeDir
/*hidserv authority*/);
378 return 0; /* success */
381 /* Keep track of whether we should upload our server descriptor,
382 * and what type of server we are.
385 /** Whether we can reach our ORPort from the outside. */
386 static int can_reach_or_port
= 0;
387 /** Whether we can reach our DirPort from the outside. */
388 static int can_reach_dir_port
= 0;
390 /** Forget what we have learned about our reachability status. */
392 router_reset_reachability(void)
394 can_reach_or_port
= can_reach_dir_port
= 0;
397 /** Return 1 if ORPort is known reachable; else return 0. */
399 check_whether_orport_reachable(void)
401 or_options_t
*options
= get_options();
402 return options
->AssumeReachable
||
406 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
408 check_whether_dirport_reachable(void)
410 or_options_t
*options
= get_options();
411 return !options
->DirPort
||
412 options
->AssumeReachable
||
413 we_are_hibernating() ||
417 /** Look at a variety of factors, and return 0 if we don't want to
418 * advertise the fact that we have a DirPort open. Else return the
419 * DirPort we want to advertise.
421 * Log a helpful message if we change our mind about whether to publish
425 decide_to_advertise_dirport(or_options_t
*options
, routerinfo_t
*router
)
427 static int advertising
=1; /* start out assuming we will advertise */
429 const char *reason
= NULL
;
431 /* Section one: reasons to publish or not publish that aren't
432 * worth mentioning to the user, either because they're obvious
433 * or because they're normal behavior. */
435 if (!router
->dir_port
) /* short circuit the rest of the function */
437 if (authdir_mode(options
)) /* always publish */
438 return router
->dir_port
;
439 if (we_are_hibernating())
441 if (!check_whether_dirport_reachable())
444 /* Section two: reasons to publish or not publish that the user
445 * might find surprising. These are generally config options that
446 * make us choose not to publish. */
448 if (accounting_is_enabled(options
)) {
449 /* if we might potentially hibernate */
451 reason
= "AccountingMax enabled";
452 } else if (router
->bandwidthrate
< 51200) {
453 /* if we're advertising a small amount */
455 reason
= "BandwidthRate under 50KB";
458 if (advertising
!= new_choice
) {
459 if (new_choice
== 1) {
460 log(LOG_NOTICE
, LD_DIR
, "Advertising DirPort as %d", router
->dir_port
);
463 log(LOG_NOTICE
, LD_DIR
, "Not advertising DirPort (Reason: %s)", reason
);
465 advertising
= new_choice
;
468 return advertising
? router
->dir_port
: 0;
471 /** Some time has passed, or we just got new directory information.
472 * See if we currently believe our ORPort or DirPort to be
473 * unreachable. If so, launch a new test for it.
475 * For ORPort, we simply try making a circuit that ends at ourselves.
476 * Success is noticed in onionskin_answer().
478 * For DirPort, we make a connection via Tor to our DirPort and ask
479 * for our own server descriptor.
480 * Success is noticed in connection_dir_client_reached_eof().
483 consider_testing_reachability(int test_or
, int test_dir
)
485 routerinfo_t
*me
= router_get_my_routerinfo();
486 int orport_reachable
= check_whether_orport_reachable();
490 if (test_or
&& (!orport_reachable
|| !circuit_enough_testing_circs())) {
491 log_info(LD_CIRC
, "Testing %s of my ORPort: %s:%d.",
492 !orport_reachable
? "reachability" : "bandwidth",
493 me
->address
, me
->or_port
);
494 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING
, 0, me
, 0, 1, 1);
495 control_event_server_status(LOG_NOTICE
,
496 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
497 me
->address
, me
->or_port
);
500 if (test_dir
&& !check_whether_dirport_reachable() &&
501 !connection_get_by_type_addr_port_purpose(
502 CONN_TYPE_DIR
, me
->addr
, me
->dir_port
,
503 DIR_PURPOSE_FETCH_SERVERDESC
)) {
504 /* ask myself, via tor, for my server descriptor. */
505 directory_initiate_command(me
->address
, me
->addr
, me
->dir_port
,
506 0, me
->cache_info
.identity_digest
,
507 DIR_PURPOSE_FETCH_SERVERDESC
,
508 1, "authority", NULL
, 0);
510 control_event_server_status(LOG_NOTICE
,
511 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
512 me
->address
, me
->dir_port
);
516 /** Annotate that we found our ORPort reachable. */
518 router_orport_found_reachable(void)
520 if (!can_reach_or_port
) {
521 routerinfo_t
*me
= router_get_my_routerinfo();
522 log_notice(LD_OR
,"Self-testing indicates your ORPort is reachable from "
523 "the outside. Excellent.%s",
524 get_options()->PublishServerDescriptor
?
525 " Publishing server descriptor." : "");
526 can_reach_or_port
= 1;
527 mark_my_descriptor_dirty();
530 control_event_server_status(LOG_NOTICE
,
531 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
532 me
->address
, me
->dir_port
);
536 /** Annotate that we found our DirPort reachable. */
538 router_dirport_found_reachable(void)
540 if (!can_reach_dir_port
) {
541 routerinfo_t
*me
= router_get_my_routerinfo();
542 log_notice(LD_DIRSERV
,"Self-testing indicates your DirPort is reachable "
543 "from the outside. Excellent.");
544 can_reach_dir_port
= 1;
545 mark_my_descriptor_dirty();
548 control_event_server_status(LOG_NOTICE
,
549 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
550 me
->address
, me
->dir_port
);
554 /** We have enough testing circuits open. Send a bunch of "drop"
555 * cells down each of them, to exercise our bandwidth. */
557 router_perform_bandwidth_test(int num_circs
, time_t now
)
559 int num_cells
= (int)(get_options()->BandwidthRate
* 10 / CELL_NETWORK_SIZE
);
560 int max_cells
= num_cells
< CIRCWINDOW_START
?
561 num_cells
: CIRCWINDOW_START
;
562 int cells_per_circuit
= max_cells
/ num_circs
;
563 origin_circuit_t
*circ
= NULL
;
565 log_notice(LD_OR
,"Performing bandwidth self-test...done.");
566 while ((circ
= circuit_get_next_by_pk_and_purpose(circ
, NULL
,
567 CIRCUIT_PURPOSE_TESTING
))) {
568 /* dump cells_per_circuit drop cells onto this circ */
569 int i
= cells_per_circuit
;
570 if (circ
->_base
.state
!= CIRCUIT_STATE_OPEN
)
572 circ
->_base
.timestamp_dirty
= now
;
574 if (connection_edge_send_command(NULL
, TO_CIRCUIT(circ
),
576 NULL
, 0, circ
->cpath
->prev
)<0) {
577 return; /* stop if error */
583 /** Return true iff we believe ourselves to be an authoritative
587 authdir_mode(or_options_t
*options
)
589 return options
->AuthoritativeDir
!= 0;
591 /** Return true iff we try to stay connected to all ORs at once.
594 clique_mode(or_options_t
*options
)
596 return authdir_mode(options
);
599 /** Return true iff we are trying to be a server.
602 server_mode(or_options_t
*options
)
604 if (options
->ClientOnly
) return 0;
605 return (options
->ORPort
!= 0 || options
->ORListenAddress
);
608 /** Remember if we've advertised ourselves to the dirservers. */
609 static int server_is_advertised
=0;
611 /** Return true iff we have published our descriptor lately.
614 advertised_server_mode(void)
616 return server_is_advertised
;
620 * Called with a boolean: set whether we have recently published our
624 set_server_advertised(int s
)
626 server_is_advertised
= s
;
629 /** Return true iff we are trying to be a socks proxy. */
631 proxy_mode(or_options_t
*options
)
633 return (options
->SocksPort
!= 0 || options
->SocksListenAddress
);
636 /** Decide if we're a publishable server. We are a publishable server if:
637 * - We don't have the ClientOnly option set
639 * - We have the PublishServerDescriptor option set
641 * - We have ORPort set
643 * - We believe we are reachable from the outside; or
644 * - We have the AuthoritativeDirectory option set.
647 decide_if_publishable_server(void)
649 or_options_t
*options
= get_options();
651 if (options
->ClientOnly
)
653 if (!options
->PublishServerDescriptor
)
655 if (!server_mode(options
))
657 if (options
->AuthoritativeDir
)
660 return check_whether_orport_reachable();
663 /** Initiate server descriptor upload as reasonable (if server is publishable,
664 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
666 * We need to rebuild the descriptor if it's dirty even if we're not
667 * uploading, because our reachability testing *uses* our descriptor to
668 * determine what IP address and ports to test.
671 consider_publishable_server(int force
)
675 if (!server_mode(get_options()))
678 rebuilt
= router_rebuild_descriptor(0);
679 if (decide_if_publishable_server()) {
680 set_server_advertised(1);
682 router_upload_dir_desc_to_dirservers(force
);
684 set_server_advertised(0);
689 * Clique maintenance -- to be phased out.
692 /** Return true iff this OR should try to keep connections open to all
695 router_is_clique_mode(routerinfo_t
*router
)
697 if (router_digest_is_trusted_dir(router
->cache_info
.identity_digest
))
703 * OR descriptor generation.
706 /** My routerinfo. */
707 static routerinfo_t
*desc_routerinfo
= NULL
;
708 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
710 static time_t desc_clean_since
= 0;
711 /** Boolean: do we need to regenerate the above? */
712 static int desc_needs_upload
= 0;
714 /** OR only: If <b>force</b> is true, or we haven't uploaded this
715 * descriptor successfully yet, try to upload our signed descriptor to
716 * all the directory servers we know about.
719 router_upload_dir_desc_to_dirservers(int force
)
723 s
= router_get_my_descriptor();
725 log_info(LD_GENERAL
, "No descriptor; skipping upload");
728 if (!get_options()->PublishServerDescriptor
)
730 if (!force
&& !desc_needs_upload
)
732 desc_needs_upload
= 0;
733 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR
, s
, strlen(s
));
736 /** OR only: Check whether my exit policy says to allow connection to
737 * conn. Return 0 if we accept; non-0 if we reject.
740 router_compare_to_my_exit_policy(edge_connection_t
*conn
)
742 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
745 /* make sure it's resolved to something. this way we can't get a
747 if (!conn
->_base
.addr
)
750 return compare_addr_to_addr_policy(conn
->_base
.addr
, conn
->_base
.port
,
751 desc_routerinfo
->exit_policy
) != ADDR_POLICY_ACCEPTED
;
754 /** Return true iff I'm a server and <b>digest</b> is equal to
755 * my identity digest. */
757 router_digest_is_me(const char *digest
)
759 return identitykey
&& !memcmp(identitykey_digest
, digest
, DIGEST_LEN
);
762 /** A wrapper around router_digest_is_me(). */
764 router_is_me(routerinfo_t
*router
)
766 return router_digest_is_me(router
->cache_info
.identity_digest
);
769 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
771 router_fingerprint_is_me(const char *fp
)
773 char digest
[DIGEST_LEN
];
774 if (strlen(fp
) == HEX_DIGEST_LEN
&&
775 base16_decode(digest
, sizeof(digest
), fp
, HEX_DIGEST_LEN
) == 0)
776 return router_digest_is_me(digest
);
781 /** Return a routerinfo for this OR, rebuilding a fresh one if
782 * necessary. Return NULL on error, or if called on an OP. */
784 router_get_my_routerinfo(void)
786 if (!server_mode(get_options()))
788 if (router_rebuild_descriptor(0))
790 return desc_routerinfo
;
793 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
794 * one if necessary. Return NULL on error.
797 router_get_my_descriptor(void)
800 if (!router_get_my_routerinfo())
802 /* Make sure this is nul-terminated. */
803 tor_assert(desc_routerinfo
->cache_info
.saved_location
== SAVED_NOWHERE
);
804 body
= signed_descriptor_get_body(&desc_routerinfo
->cache_info
);
805 tor_assert(!body
[desc_routerinfo
->cache_info
.signed_descriptor_len
]);
806 log_debug(LD_GENERAL
,"my desc is '%s'", body
);
810 /** A list of nicknames that we've warned about including in our family
811 * declaration verbatim rather than as digests. */
812 static smartlist_t
*warned_nonexistent_family
= NULL
;
814 static int router_guess_address_from_dir_headers(uint32_t *guess
);
816 /** Return our current best guess at our address, either because
817 * it's configured in torrc, or because we've learned it from
818 * dirserver headers. */
820 router_pick_published_address(or_options_t
*options
, uint32_t *addr
)
822 if (resolve_my_address(LOG_INFO
, options
, addr
, NULL
) < 0) {
823 log_info(LD_CONFIG
, "Could not determine our address locally. "
824 "Checking if directory headers provide any hints.");
825 if (router_guess_address_from_dir_headers(addr
) < 0) {
826 log_info(LD_CONFIG
, "No hints from directory headers either. "
827 "Will try again later.");
834 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
835 * a fresh routerinfo and signed server descriptor for this OR.
836 * Return 0 on success, -1 on temporary error.
839 router_rebuild_descriptor(int force
)
844 int hibernating
= we_are_hibernating();
845 or_options_t
*options
= get_options();
847 if (desc_clean_since
&& !force
)
850 if (router_pick_published_address(options
, &addr
) < 0) {
851 /* Stop trying to rebuild our descriptor every second. We'll
852 * learn that it's time to try again when server_has_changed_ip()
854 desc_clean_since
= time(NULL
);
858 ri
= tor_malloc_zero(sizeof(routerinfo_t
));
859 ri
->routerlist_index
= -1;
860 ri
->address
= tor_dup_addr(addr
);
861 ri
->nickname
= tor_strdup(options
->Nickname
);
863 ri
->or_port
= options
->ORPort
;
864 ri
->dir_port
= options
->DirPort
;
865 ri
->cache_info
.published_on
= time(NULL
);
866 ri
->onion_pkey
= crypto_pk_dup_key(get_onion_key()); /* must invoke from
868 ri
->identity_pkey
= crypto_pk_dup_key(get_identity_key());
869 if (crypto_pk_get_digest(ri
->identity_pkey
,
870 ri
->cache_info
.identity_digest
)<0) {
874 get_platform_str(platform
, sizeof(platform
));
875 ri
->platform
= tor_strdup(platform
);
876 ri
->bandwidthrate
= (int)options
->BandwidthRate
;
877 ri
->bandwidthburst
= (int)options
->BandwidthBurst
;
878 ri
->bandwidthcapacity
= hibernating
? 0 : rep_hist_bandwidth_assess();
880 if (options
->BandwidthRate
> options
->MaxAdvertisedBandwidth
) {
881 if (options
->MaxAdvertisedBandwidth
> ROUTER_MAX_DECLARED_BANDWIDTH
) {
882 ri
->bandwidthrate
= ROUTER_MAX_DECLARED_BANDWIDTH
;
884 ri
->bandwidthrate
= (int)options
->MaxAdvertisedBandwidth
;
888 policies_parse_exit_policy(options
->ExitPolicy
, &ri
->exit_policy
,
889 options
->ExitPolicyRejectPrivate
);
891 if (desc_routerinfo
) { /* inherit values */
892 ri
->is_valid
= desc_routerinfo
->is_valid
;
893 ri
->is_running
= desc_routerinfo
->is_running
;
894 ri
->is_named
= desc_routerinfo
->is_named
;
896 if (authdir_mode(options
))
897 ri
->is_valid
= ri
->is_named
= 1; /* believe in yourself */
898 if (options
->MyFamily
) {
900 if (!warned_nonexistent_family
)
901 warned_nonexistent_family
= smartlist_create();
902 family
= smartlist_create();
903 ri
->declared_family
= smartlist_create();
904 smartlist_split_string(family
, options
->MyFamily
, ",",
905 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
906 SMARTLIST_FOREACH(family
, char *, name
,
908 routerinfo_t
*member
;
909 if (!strcasecmp(name
, options
->Nickname
))
912 member
= router_get_by_nickname(name
, 1);
914 if (!smartlist_string_isin(warned_nonexistent_family
, name
) &&
915 !is_legal_hexdigest(name
)) {
917 "I have no descriptor for the router named \"%s\" "
918 "in my declared family; I'll use the nickname as is, but "
919 "this may confuse clients.", name
);
920 smartlist_add(warned_nonexistent_family
, tor_strdup(name
));
922 smartlist_add(ri
->declared_family
, name
);
924 } else if (router_is_me(member
)) {
925 /* Don't list ourself in our own family; that's redundant */
927 char *fp
= tor_malloc(HEX_DIGEST_LEN
+2);
929 base16_encode(fp
+1,HEX_DIGEST_LEN
+1,
930 member
->cache_info
.identity_digest
, DIGEST_LEN
);
931 smartlist_add(ri
->declared_family
, fp
);
932 if (smartlist_string_isin(warned_nonexistent_family
, name
))
933 smartlist_string_remove(warned_nonexistent_family
, name
);
938 /* remove duplicates from the list */
939 smartlist_sort_strings(ri
->declared_family
);
940 smartlist_uniq_strings(ri
->declared_family
);
942 smartlist_free(family
);
944 ri
->cache_info
.signed_descriptor_body
= tor_malloc(8192);
945 if (router_dump_router_to_string(ri
->cache_info
.signed_descriptor_body
, 8192,
946 ri
, get_identity_key())<0) {
947 log_warn(LD_BUG
, "Bug: Couldn't generate router descriptor.");
950 ri
->cache_info
.signed_descriptor_len
=
951 strlen(ri
->cache_info
.signed_descriptor_body
);
953 router_get_router_hash(ri
->cache_info
.signed_descriptor_body
,
954 ri
->cache_info
.signed_descriptor_digest
);
957 routerinfo_free(desc_routerinfo
);
958 desc_routerinfo
= ri
;
960 desc_clean_since
= time(NULL
);
961 desc_needs_upload
= 1;
962 control_event_my_descriptor_changed();
966 /** Mark descriptor out of date if it's older than <b>when</b> */
968 mark_my_descriptor_dirty_if_older_than(time_t when
)
970 if (desc_clean_since
< when
)
971 mark_my_descriptor_dirty();
974 /** Call when the current descriptor is out of date. */
976 mark_my_descriptor_dirty(void)
978 desc_clean_since
= 0;
981 /** How frequently will we republish our descriptor because of large (factor
982 * of 2) shifts in estimated bandwidth? */
983 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
985 /** Check whether bandwidth has changed a lot since the last time we announced
986 * bandwidth. If so, mark our descriptor dirty. */
988 check_descriptor_bandwidth_changed(time_t now
)
990 static time_t last_changed
= 0;
992 if (!desc_routerinfo
)
995 prev
= desc_routerinfo
->bandwidthcapacity
;
996 cur
= we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
997 if ((prev
!= cur
&& (!prev
|| !cur
)) ||
1000 if (last_changed
+MAX_BANDWIDTH_CHANGE_FREQ
< now
) {
1001 log_info(LD_GENERAL
,
1002 "Measured bandwidth has changed; rebuilding descriptor.");
1003 mark_my_descriptor_dirty();
1009 /** Note at log level severity that our best guess of address has changed from
1010 * <b>prev</b> to <b>cur</b>. */
1012 log_addr_has_changed(int severity
, uint32_t prev
, uint32_t cur
)
1014 char addrbuf_prev
[INET_NTOA_BUF_LEN
];
1015 char addrbuf_cur
[INET_NTOA_BUF_LEN
];
1016 struct in_addr in_prev
;
1017 struct in_addr in_cur
;
1019 in_prev
.s_addr
= htonl(prev
);
1020 tor_inet_ntoa(&in_prev
, addrbuf_prev
, sizeof(addrbuf_prev
));
1022 in_cur
.s_addr
= htonl(cur
);
1023 tor_inet_ntoa(&in_cur
, addrbuf_cur
, sizeof(addrbuf_cur
));
1026 log_fn(severity
, LD_GENERAL
,
1027 "Our IP Address has changed from %s to %s; "
1028 "rebuilding descriptor.",
1029 addrbuf_prev
, addrbuf_cur
);
1031 log_notice(LD_GENERAL
,
1032 "Guessed our IP address as %s.",
1036 /** Check whether our own address as defined by the Address configuration
1037 * has changed. This is for routers that get their address from a service
1038 * like dyndns. If our address has changed, mark our descriptor dirty. */
1040 check_descriptor_ipaddress_changed(time_t now
)
1043 or_options_t
*options
= get_options();
1046 if (!desc_routerinfo
)
1049 prev
= desc_routerinfo
->addr
;
1050 if (resolve_my_address(LOG_INFO
, options
, &cur
, NULL
) < 0) {
1051 log_info(LD_CONFIG
,"options->Address didn't resolve into an IP.");
1056 log_addr_has_changed(LOG_INFO
, prev
, cur
);
1057 ip_address_changed(0);
1061 /** The most recently guessed value of our IP address, based on directory
1063 static uint32_t last_guessed_ip
= 0;
1065 /** A directory authority told us our IP address is <b>suggestion</b>.
1066 * If this address is different from the one we think we are now, and
1067 * if our computer doesn't actually know its IP address, then switch. */
1069 router_new_address_suggestion(const char *suggestion
)
1071 uint32_t addr
, cur
= 0;
1073 or_options_t
*options
= get_options();
1075 /* first, learn what the IP address actually is */
1076 if (!tor_inet_aton(suggestion
, &in
)) {
1077 log_debug(LD_DIR
, "Malformed X-Your-Address-Is header %s. Ignoring.",
1078 escaped(suggestion
));
1081 addr
= ntohl(in
.s_addr
);
1083 log_debug(LD_DIR
, "Got X-Your-Address-Is: %s.", suggestion
);
1085 if (!server_mode(options
)) {
1086 last_guessed_ip
= addr
; /* store it in case we need it later */
1090 if (resolve_my_address(LOG_INFO
, options
, &cur
, NULL
) >= 0) {
1091 /* We're all set -- we already know our address. Great. */
1092 last_guessed_ip
= cur
; /* store it in case we need it later */
1095 if (is_internal_IP(addr
, 0)) {
1096 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1100 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1101 * us an answer different from what we had the last time we managed to
1103 if (last_guessed_ip
!= addr
) {
1104 control_event_server_status(LOG_NOTICE
,
1105 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1107 log_addr_has_changed(LOG_NOTICE
, last_guessed_ip
, addr
);
1108 ip_address_changed(0);
1109 last_guessed_ip
= addr
; /* router_rebuild_descriptor() will fetch it */
1113 /** We failed to resolve our address locally, but we'd like to build
1114 * a descriptor and publish / test reachability. If we have a guess
1115 * about our address based on directory headers, answer it and return
1116 * 0; else return -1. */
1118 router_guess_address_from_dir_headers(uint32_t *guess
)
1120 if (last_guessed_ip
) {
1121 *guess
= last_guessed_ip
;
1127 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1128 * string describing the version of Tor and the operating system we're
1129 * currently running on.
1132 get_platform_str(char *platform
, size_t len
)
1134 tor_snprintf(platform
, len
, "Tor %s on %s",
1135 VERSION
, get_uname());
1139 /* XXX need to audit this thing and count fenceposts. maybe
1140 * refactor so we don't have to keep asking if we're
1141 * near the end of maxlen?
1143 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1145 /** OR only: Given a routerinfo for this router, and an identity key to sign
1146 * with, encode the routerinfo as a signed server descriptor and write the
1147 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1148 * failure, and the number of bytes used on success.
1151 router_dump_router_to_string(char *s
, size_t maxlen
, routerinfo_t
*router
,
1152 crypto_pk_env_t
*ident_key
)
1154 char *onion_pkey
; /* Onion key, PEM-encoded. */
1155 char *identity_pkey
; /* Identity key, PEM-encoded. */
1156 char digest
[DIGEST_LEN
];
1157 char published
[ISO_TIME_LEN
+1];
1158 char fingerprint
[FINGERPRINT_LEN
+1];
1159 size_t onion_pkeylen
, identity_pkeylen
;
1162 addr_policy_t
*tmpe
;
1163 char *bandwidth_usage
;
1165 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1168 routerinfo_t
*ri_tmp
;
1170 or_options_t
*options
= get_options();
1172 /* Make sure the identity key matches the one in the routerinfo. */
1173 if (crypto_pk_cmp_keys(ident_key
, router
->identity_pkey
)) {
1174 log_warn(LD_BUG
,"Tried to sign a router with a private key that didn't "
1175 "match router's public key!");
1179 /* record our fingerprint, so we can include it in the descriptor */
1180 if (crypto_pk_get_fingerprint(router
->identity_pkey
, fingerprint
, 1)<0) {
1181 log_err(LD_BUG
,"Error computing fingerprint");
1185 /* PEM-encode the onion key */
1186 if (crypto_pk_write_public_key_to_string(router
->onion_pkey
,
1187 &onion_pkey
,&onion_pkeylen
)<0) {
1188 log_warn(LD_BUG
,"write onion_pkey to string failed!");
1192 /* PEM-encode the identity key key */
1193 if (crypto_pk_write_public_key_to_string(router
->identity_pkey
,
1194 &identity_pkey
,&identity_pkeylen
)<0) {
1195 log_warn(LD_BUG
,"write identity_pkey to string failed!");
1196 tor_free(onion_pkey
);
1200 /* Encode the publication time. */
1201 format_iso_time(published
, router
->cache_info
.published_on
);
1203 /* How busy have we been? */
1204 bandwidth_usage
= rep_hist_get_bandwidth_lines();
1206 if (router
->declared_family
&& smartlist_len(router
->declared_family
)) {
1208 char *s
= smartlist_join_strings(router
->declared_family
, " ", 0, &n
);
1209 n
+= strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1210 family_line
= tor_malloc(n
);
1211 tor_snprintf(family_line
, n
, "family %s\n", s
);
1214 family_line
= tor_strdup("");
1217 /* Generate the easy portion of the router descriptor. */
1218 result
= tor_snprintf(s
, maxlen
,
1219 "router %s %s %d 0 %d\n"
1222 "opt fingerprint %s\n"
1224 "bandwidth %d %d %d\n"
1227 #ifndef USE_EVENTDNS
1234 decide_to_advertise_dirport(options
, router
),
1238 stats_n_seconds_working
,
1239 (int) router
->bandwidthrate
,
1240 (int) router
->bandwidthburst
,
1241 (int) router
->bandwidthcapacity
,
1242 onion_pkey
, identity_pkey
,
1243 family_line
, bandwidth_usage
,
1244 we_are_hibernating() ? "opt hibernating 1\n" : "");
1245 tor_free(family_line
);
1246 tor_free(onion_pkey
);
1247 tor_free(identity_pkey
);
1248 tor_free(bandwidth_usage
);
1251 log_warn(LD_BUG
,"descriptor snprintf #1 ran out of room!");
1254 /* From now on, we use 'written' to remember the current length of 's'. */
1257 if (options
->ContactInfo
&& strlen(options
->ContactInfo
)) {
1258 result
= tor_snprintf(s
+written
,maxlen
-written
, "contact %s\n",
1259 options
->ContactInfo
);
1261 log_warn(LD_BUG
,"descriptor snprintf #2 ran out of room!");
1267 /* Write the exit policy to the end of 's'. */
1268 tmpe
= router
->exit_policy
;
1269 if (dns_seems_to_be_broken()) {
1270 /* DNS is screwed up; don't claim to be an exit. */
1271 strlcat(s
+written
, "reject *:*\n", maxlen
-written
);
1272 written
+= strlen("reject *:*\n");
1275 for ( ; tmpe
; tmpe
=tmpe
->next
) {
1276 result
= policy_write_item(s
+written
, maxlen
-written
, tmpe
);
1278 log_warn(LD_BUG
,"descriptor policy_write_item ran out of room!");
1281 tor_assert(result
== (int)strlen(s
+written
));
1283 if (written
+2 > maxlen
) {
1284 log_warn(LD_BUG
,"descriptor policy_write_item ran out of room (2)!");
1287 s
[written
++] = '\n';
1290 if (written
+256 > maxlen
) { /* Not enough room for signature. */
1291 log_warn(LD_BUG
,"not enough room left in descriptor for signature!");
1295 /* Sign the directory */
1296 strlcpy(s
+written
, "router-signature\n", maxlen
-written
);
1297 written
+= strlen(s
+written
);
1299 if (router_get_router_hash(s
, digest
) < 0) {
1303 note_crypto_pk_op(SIGN_RTR
);
1304 if (router_append_dirobj_signature(s
+written
,maxlen
-written
,
1305 digest
,ident_key
)<0) {
1306 log_warn(LD_BUG
, "Couldn't sign router descriptor");
1309 written
+= strlen(s
+written
);
1311 if (written
+2 > maxlen
) {
1312 log_warn(LD_BUG
,"Not enough room to finish descriptor.");
1315 /* include a last '\n' */
1319 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1320 cp
= s_dup
= tor_strdup(s
);
1321 ri_tmp
= router_parse_entry_from_string(cp
, NULL
, 1);
1324 "We just generated a router descriptor we can't parse.");
1325 log_err(LD_BUG
, "Descriptor was: <<%s>>", s
);
1329 routerinfo_free(ri_tmp
);
1335 /** Return true iff <b>s</b> is a legally valid server nickname. */
1337 is_legal_nickname(const char *s
)
1342 return len
> 0 && len
<= MAX_NICKNAME_LEN
&&
1343 strspn(s
,LEGAL_NICKNAME_CHARACTERS
) == len
;
1346 /** Return true iff <b>s</b> is a legally valid server nickname or
1347 * hex-encoded identity-key digest. */
1349 is_legal_nickname_or_hexdigest(const char *s
)
1352 return is_legal_nickname(s
);
1354 return is_legal_hexdigest(s
);
1357 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
1360 is_legal_hexdigest(const char *s
)
1364 if (s
[0] == '$') s
++;
1366 if (len
> HEX_DIGEST_LEN
) {
1367 if (s
[HEX_DIGEST_LEN
] == '=' ||
1368 s
[HEX_DIGEST_LEN
] == '~') {
1369 if (!is_legal_nickname(s
+HEX_DIGEST_LEN
+1))
1375 return (len
>= HEX_DIGEST_LEN
&&
1376 strspn(s
,HEX_CHARACTERS
)==HEX_DIGEST_LEN
);
1379 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
1380 * verbose representation of the identity of <b>router</b>. The format is:
1382 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
1383 * A "=" if the router is named; a "~" if it is not.
1384 * The router's nickname.
1387 router_get_verbose_nickname(char *buf
, routerinfo_t
*router
)
1390 base16_encode(buf
+1, HEX_DIGEST_LEN
+1, router
->cache_info
.identity_digest
,
1392 buf
[1+HEX_DIGEST_LEN
] = router
->is_named
? '=' : '~';
1393 strlcpy(buf
+1+HEX_DIGEST_LEN
+1, router
->nickname
, MAX_NICKNAME_LEN
+1);
1396 /** Forget that we have issued any router-related warnings, so that we'll
1397 * warn again if we see the same errors. */
1399 router_reset_warnings(void)
1401 if (warned_nonexistent_family
) {
1402 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
1403 smartlist_clear(warned_nonexistent_family
);
1407 /** Release all static resources held in router.c */
1409 router_free_all(void)
1412 crypto_free_pk_env(onionkey
);
1414 crypto_free_pk_env(lastonionkey
);
1416 crypto_free_pk_env(identitykey
);
1418 tor_mutex_free(key_lock
);
1419 if (desc_routerinfo
)
1420 routerinfo_free(desc_routerinfo
);
1421 if (warned_nonexistent_family
) {
1422 SMARTLIST_FOREACH(warned_nonexistent_family
, char *, cp
, tor_free(cp
));
1423 smartlist_free(warned_nonexistent_family
);