Document most undocumented variables.
[tor/rransom.git] / src / or / router.c
blobec36bdfe91c6dd8c5275e6e1a04fdcc43bca3b2f
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 /* $Id$ */
7 const char router_c_id[] =
8 "$Id$";
10 #define ROUTER_PRIVATE
12 #include "or.h"
14 /**
15 * \file router.c
16 * \brief OR functionality, including key maintenance, generating
17 * and uploading server descriptors, retrying OR connections.
18 **/
20 extern long stats_n_seconds_working;
22 /************************************************************/
24 /*****
25 * Key management: ORs only.
26 *****/
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
45 * authorities. */
46 static authority_cert_t *authority_key_certificate = NULL;
48 /** For emergency V3 authority key migration: An extra signing key that we use
49 * with our old (obsolete) identity key for a while. */
50 static crypto_pk_env_t *legacy_signing_key = NULL;
51 /** For emergency V3 authority key migration: An extra certificate to
52 * authenticate legacy_signing_key with our obsolete identity key.*/
53 static authority_cert_t *legacy_key_certificate = NULL;
55 /* (Note that v3 authorities also have a separate "authority identity key",
56 * but this key is never actually loaded by the Tor process. Instead, it's
57 * used by tor-gencert to sign new signing keys and make new key
58 * certificates. */
60 /** Replace the current onion key with <b>k</b>. Does not affect
61 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
63 static void
64 set_onion_key(crypto_pk_env_t *k)
66 tor_mutex_acquire(key_lock);
67 if (onionkey)
68 crypto_free_pk_env(onionkey);
69 onionkey = k;
70 onionkey_set_at = time(NULL);
71 tor_mutex_release(key_lock);
72 mark_my_descriptor_dirty();
75 /** Return the current onion key. Requires that the onion key has been
76 * loaded or generated. */
77 crypto_pk_env_t *
78 get_onion_key(void)
80 tor_assert(onionkey);
81 return onionkey;
84 /** Store a full copy of the current onion key into *<b>key</b>, and a full
85 * copy of the most recent onion key into *<b>last</b>.
87 void
88 dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
90 tor_assert(key);
91 tor_assert(last);
92 tor_mutex_acquire(key_lock);
93 tor_assert(onionkey);
94 *key = crypto_pk_copy_full(onionkey);
95 if (lastonionkey)
96 *last = crypto_pk_copy_full(lastonionkey);
97 else
98 *last = NULL;
99 tor_mutex_release(key_lock);
102 /** Return the time when the onion key was last set. This is either the time
103 * when the process launched, or the time of the most recent key rotation since
104 * the process launched.
106 time_t
107 get_onion_key_set_at(void)
109 return onionkey_set_at;
112 /** Set the current identity key to k.
114 void
115 set_identity_key(crypto_pk_env_t *k)
117 if (identitykey)
118 crypto_free_pk_env(identitykey);
119 identitykey = k;
120 crypto_pk_get_digest(identitykey, identitykey_digest);
123 /** Returns the current identity key; requires that the identity key has been
124 * set.
126 crypto_pk_env_t *
127 get_identity_key(void)
129 tor_assert(identitykey);
130 return identitykey;
133 /** Return true iff the identity key has been set. */
135 identity_key_is_set(void)
137 return identitykey != NULL;
140 /** Return the key certificate for this v3 (voting) authority, or NULL
141 * if we have no such certificate. */
142 authority_cert_t *
143 get_my_v3_authority_cert(void)
145 return authority_key_certificate;
148 /** Return the v3 signing key for this v3 (voting) authority, or NULL
149 * if we have no such key. */
150 crypto_pk_env_t *
151 get_my_v3_authority_signing_key(void)
153 return authority_signing_key;
156 /** If we're an authority, and we're using a legacy authority identity key for
157 * emergency migration purposes, return the certificate associated with that
158 * key. */
159 authority_cert_t *
160 get_my_v3_legacy_cert(void)
162 return legacy_key_certificate;
165 /** If we're an authority, and we're using a legacy authority identity key for
166 * emergency migration purposes, return that key. */
167 crypto_pk_env_t *
168 get_my_v3_legacy_signing_key(void)
170 return legacy_signing_key;
173 /** Replace the previous onion key with the current onion key, and generate
174 * a new previous onion key. Immediately after calling this function,
175 * the OR should:
176 * - schedule all previous cpuworkers to shut down _after_ processing
177 * pending work. (This will cause fresh cpuworkers to be generated.)
178 * - generate and upload a fresh routerinfo.
180 void
181 rotate_onion_key(void)
183 char *fname, *fname_prev;
184 crypto_pk_env_t *prkey;
185 or_state_t *state = get_or_state();
186 time_t now;
187 fname = get_datadir_fname2("keys", "secret_onion_key");
188 fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
189 if (!(prkey = crypto_new_pk_env())) {
190 log_err(LD_GENERAL,"Error constructing rotated onion key");
191 goto error;
193 if (crypto_pk_generate_key(prkey)) {
194 log_err(LD_BUG,"Error generating onion key");
195 goto error;
197 if (file_status(fname) == FN_FILE) {
198 if (replace_file(fname, fname_prev))
199 goto error;
201 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
202 log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
203 goto error;
205 log_info(LD_GENERAL, "Rotating onion key");
206 tor_mutex_acquire(key_lock);
207 if (lastonionkey)
208 crypto_free_pk_env(lastonionkey);
209 lastonionkey = onionkey;
210 onionkey = prkey;
211 now = time(NULL);
212 state->LastRotatedOnionKey = onionkey_set_at = now;
213 tor_mutex_release(key_lock);
214 mark_my_descriptor_dirty();
215 or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
216 goto done;
217 error:
218 log_warn(LD_GENERAL, "Couldn't rotate onion key.");
219 if (prkey)
220 crypto_free_pk_env(prkey);
221 done:
222 tor_free(fname);
223 tor_free(fname_prev);
226 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
227 * and <b>generate</b> is true, create a new RSA key and save it in
228 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
229 * errors at level <b>severity</b>.
231 crypto_pk_env_t *
232 init_key_from_file(const char *fname, int generate, int severity)
234 crypto_pk_env_t *prkey = NULL;
236 if (!(prkey = crypto_new_pk_env())) {
237 log(severity, LD_GENERAL,"Error constructing key");
238 goto error;
241 switch (file_status(fname)) {
242 case FN_DIR:
243 case FN_ERROR:
244 log(severity, LD_FS,"Can't read key from \"%s\"", fname);
245 goto error;
246 case FN_NOENT:
247 if (generate) {
248 if (!have_lockfile()) {
249 if (try_locking(get_options(), 0)<0) {
250 /* Make sure that --list-fingerprint only creates new keys
251 * if there is no possibility for a deadlock. */
252 log(severity, LD_FS, "Another Tor process has locked \"%s\". Not "
253 "writing any new keys.", fname);
254 /*XXXX The 'other process' might make a key in a second or two;
255 * maybe we should wait for it. */
256 goto error;
259 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
260 fname);
261 if (crypto_pk_generate_key(prkey)) {
262 log(severity, LD_GENERAL,"Error generating onion key");
263 goto error;
265 if (crypto_pk_check_key(prkey) <= 0) {
266 log(severity, LD_GENERAL,"Generated key seems invalid");
267 goto error;
269 log_info(LD_GENERAL, "Generated key seems valid");
270 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
271 log(severity, LD_FS,
272 "Couldn't write generated key to \"%s\".", fname);
273 goto error;
275 } else {
276 log_info(LD_GENERAL, "No key found in \"%s\"", fname);
278 return prkey;
279 case FN_FILE:
280 if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
281 log(severity, LD_GENERAL,"Error loading private key.");
282 goto error;
284 return prkey;
285 default:
286 tor_assert(0);
289 error:
290 if (prkey)
291 crypto_free_pk_env(prkey);
292 return NULL;
295 /** Try to load the vote-signing private key and certificate for being a v3
296 * directory authority, and make sure they match. If <b>legacy</b>, load a
297 * legacy key/cert set for emergency key migration; otherwise load the regular
298 * key/cert set. On success, store them into *<b>key_out</b> and
299 * *<b>cert_out</b> respectively, and return 0. On failrue, return -1. */
300 static int
301 load_authority_keyset(int legacy, crypto_pk_env_t **key_out,
302 authority_cert_t **cert_out)
304 int r = -1;
305 char *fname = NULL, *cert = NULL;
306 const char *eos = NULL;
307 crypto_pk_env_t *signing_key = NULL;
308 authority_cert_t *parsed = NULL;
310 fname = get_datadir_fname2("keys",
311 legacy ? "legacy_signing_key" : "authority_signing_key");
312 signing_key = init_key_from_file(fname, 0, LOG_INFO);
313 if (!signing_key) {
314 log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
315 goto done;
317 tor_free(fname);
318 fname = get_datadir_fname2("keys",
319 legacy ? "legacy_certificate" : "authority_certificate");
320 cert = read_file_to_str(fname, 0, NULL);
321 if (!cert) {
322 log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
323 fname);
324 goto done;
326 parsed = authority_cert_parse_from_string(cert, &eos);
327 if (!parsed) {
328 log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
329 goto done;
331 if (crypto_pk_cmp_keys(signing_key, parsed->signing_key) != 0) {
332 log_warn(LD_DIR, "Stored signing key does not match signing key in "
333 "certificate");
334 goto done;
336 parsed->cache_info.signed_descriptor_body = cert;
337 parsed->cache_info.signed_descriptor_len = eos-cert;
338 cert = NULL;
340 if (*key_out)
341 crypto_free_pk_env(*key_out);
342 if (*cert_out)
343 authority_cert_free(*cert_out);
344 *key_out = signing_key;
345 *cert_out = parsed;
346 r = 0;
347 signing_key = NULL;
348 parsed = NULL;
350 done:
351 tor_free(fname);
352 tor_free(cert);
353 if (signing_key)
354 crypto_free_pk_env(signing_key);
355 if (parsed)
356 authority_cert_free(parsed);
357 return r;
360 /** Load the v3 (voting) authority signing key and certificate, if they are
361 * present. Return -1 if anything is missing, mismatched, or unloadable;
362 * return 0 on success. */
363 static int
364 init_v3_authority_keys(void)
366 if (load_authority_keyset(0, &authority_signing_key,
367 &authority_key_certificate)<0)
368 return -1;
370 if (get_options()->V3AuthUseLegacyKey &&
371 load_authority_keyset(1, &legacy_signing_key,
372 &legacy_key_certificate)<0)
373 return -1;
375 return 0;
378 /** If we're a v3 authority, check whether we have a certificate that's
379 * likely to expire soon. Warn if we do, but not too often. */
380 void
381 v3_authority_check_key_expiry(void)
383 time_t now, expires;
384 static time_t last_warned = 0;
385 int badness, time_left, warn_interval;
386 if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
387 return;
389 now = time(NULL);
390 expires = authority_key_certificate->expires;
391 time_left = (int)( expires - now );
392 if (time_left <= 0) {
393 badness = LOG_ERR;
394 warn_interval = 60*60;
395 } else if (time_left <= 24*60*60) {
396 badness = LOG_WARN;
397 warn_interval = 60*60;
398 } else if (time_left <= 24*60*60*7) {
399 badness = LOG_WARN;
400 warn_interval = 24*60*60;
401 } else if (time_left <= 24*60*60*30) {
402 badness = LOG_WARN;
403 warn_interval = 24*60*60*5;
404 } else {
405 return;
408 if (last_warned + warn_interval > now)
409 return;
411 if (time_left <= 0) {
412 log(badness, LD_DIR, "Your v3 authority certificate has expired."
413 " Generate a new one NOW.");
414 } else if (time_left <= 24*60*60) {
415 log(badness, LD_DIR, "Your v3 authority certificate expires in %d hours;"
416 " Generate a new one NOW.", time_left/(60*60));
417 } else {
418 log(badness, LD_DIR, "Your v3 authority certificate expires in %d days;"
419 " Generate a new one soon.", time_left/(24*60*60));
421 last_warned = now;
424 /** Initialize all OR private keys, and the TLS context, as necessary.
425 * On OPs, this only initializes the tls context. Return 0 on success,
426 * or -1 if Tor should die.
429 init_keys(void)
431 char *keydir;
432 char fingerprint[FINGERPRINT_LEN+1];
433 /*nickname<space>fp\n\0 */
434 char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
435 const char *mydesc;
436 crypto_pk_env_t *prkey;
437 char digest[20];
438 char v3_digest[20];
439 char *cp;
440 or_options_t *options = get_options();
441 authority_type_t type;
442 time_t now = time(NULL);
443 trusted_dir_server_t *ds;
444 int v3_digest_set = 0;
445 authority_cert_t *cert = NULL;
447 if (!key_lock)
448 key_lock = tor_mutex_new();
450 /* OP's don't need persistent keys; just make up an identity and
451 * initialize the TLS context. */
452 if (!server_mode(options)) {
453 if (!(prkey = crypto_new_pk_env()))
454 return -1;
455 if (crypto_pk_generate_key(prkey)) {
456 crypto_free_pk_env(prkey);
457 return -1;
459 set_identity_key(prkey);
460 /* Create a TLS context; default the client nickname to "client". */
461 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
462 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
463 return -1;
465 return 0;
467 /* Make sure DataDirectory exists, and is private. */
468 if (check_private_dir(options->DataDirectory, CPD_CREATE)) {
469 return -1;
471 /* Check the key directory. */
472 keydir = get_datadir_fname("keys");
473 if (check_private_dir(keydir, CPD_CREATE)) {
474 tor_free(keydir);
475 return -1;
477 tor_free(keydir);
479 /* 1a. Read v3 directory authority key/cert information. */
480 memset(v3_digest, 0, sizeof(v3_digest));
481 if (authdir_mode_v3(options)) {
482 if (init_v3_authority_keys()<0) {
483 log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
484 "were unable to load our v3 authority keys and certificate! "
485 "Use tor-gencert to generate them. Dying.");
486 return -1;
488 cert = get_my_v3_authority_cert();
489 if (cert) {
490 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
491 v3_digest);
492 v3_digest_set = 1;
496 /* 1. Read identity key. Make it if none is found. */
497 keydir = get_datadir_fname2("keys", "secret_id_key");
498 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
499 prkey = init_key_from_file(keydir, 1, LOG_ERR);
500 tor_free(keydir);
501 if (!prkey) return -1;
502 set_identity_key(prkey);
504 /* 2. Read onion key. Make it if none is found. */
505 keydir = get_datadir_fname2("keys", "secret_onion_key");
506 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
507 prkey = init_key_from_file(keydir, 1, LOG_ERR);
508 tor_free(keydir);
509 if (!prkey) return -1;
510 set_onion_key(prkey);
511 if (options->command == CMD_RUN_TOR) {
512 /* only mess with the state file if we're actually running Tor */
513 or_state_t *state = get_or_state();
514 if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
515 /* We allow for some parsing slop, but we don't want to risk accepting
516 * values in the distant future. If we did, we might never rotate the
517 * onion key. */
518 onionkey_set_at = state->LastRotatedOnionKey;
519 } else {
520 /* We have no LastRotatedOnionKey set; either we just created the key
521 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
522 * start the clock ticking now so that we will eventually rotate it even
523 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
524 state->LastRotatedOnionKey = onionkey_set_at = now;
525 or_state_mark_dirty(state, options->AvoidDiskWrites ?
526 time(NULL)+3600 : 0);
530 keydir = get_datadir_fname2("keys", "secret_onion_key.old");
531 if (!lastonionkey && file_status(keydir) == FN_FILE) {
532 prkey = init_key_from_file(keydir, 1, LOG_ERR);
533 if (prkey)
534 lastonionkey = prkey;
536 tor_free(keydir);
538 /* 3. Initialize link key and TLS context. */
539 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
540 log_err(LD_GENERAL,"Error initializing TLS context");
541 return -1;
543 /* 4. Build our router descriptor. */
544 /* Must be called after keys are initialized. */
545 mydesc = router_get_my_descriptor();
546 if (authdir_mode(options)) {
547 const char *m;
548 routerinfo_t *ri;
549 /* We need to add our own fingerprint so it gets recognized. */
550 if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
551 log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
552 return -1;
554 if (mydesc) {
555 ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
556 if (!ri) {
557 log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
558 return -1;
560 if (!WRA_WAS_ADDED(dirserv_add_descriptor(ri, &m))) {
561 log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
562 m?m:"<unknown error>");
563 return -1;
568 /* 5. Dump fingerprint to 'fingerprint' */
569 keydir = get_datadir_fname("fingerprint");
570 log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
571 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
572 log_err(LD_GENERAL,"Error computing fingerprint");
573 tor_free(keydir);
574 return -1;
576 tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
577 if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
578 "%s %s\n",options->Nickname, fingerprint) < 0) {
579 log_err(LD_GENERAL,"Error writing fingerprint line");
580 tor_free(keydir);
581 return -1;
583 /* Check whether we need to write the fingerprint file. */
584 cp = NULL;
585 if (file_status(keydir) == FN_FILE)
586 cp = read_file_to_str(keydir, 0, NULL);
587 if (!cp || strcmp(cp, fingerprint_line)) {
588 if (write_str_to_file(keydir, fingerprint_line, 0)) {
589 log_err(LD_FS, "Error writing fingerprint line to file");
590 tor_free(keydir);
591 return -1;
594 tor_free(cp);
595 tor_free(keydir);
597 log(LOG_NOTICE, LD_GENERAL,
598 "Your Tor server's identity key fingerprint is '%s %s'",
599 options->Nickname, fingerprint);
600 if (!authdir_mode(options))
601 return 0;
602 /* 6. [authdirserver only] load approved-routers file */
603 if (dirserv_load_fingerprint_file() < 0) {
604 log_err(LD_GENERAL,"Error loading fingerprints");
605 return -1;
607 /* 6b. [authdirserver only] add own key to approved directories. */
608 crypto_pk_get_digest(get_identity_key(), digest);
609 type = ((options->V1AuthoritativeDir ? V1_AUTHORITY : NO_AUTHORITY) |
610 (options->V2AuthoritativeDir ? V2_AUTHORITY : NO_AUTHORITY) |
611 (options->V3AuthoritativeDir ? V3_AUTHORITY : NO_AUTHORITY) |
612 (options->BridgeAuthoritativeDir ? BRIDGE_AUTHORITY : NO_AUTHORITY) |
613 (options->HSAuthoritativeDir ? HIDSERV_AUTHORITY : NO_AUTHORITY));
615 ds = router_get_trusteddirserver_by_digest(digest);
616 if (!ds) {
617 ds = add_trusted_dir_server(options->Nickname, NULL,
618 (uint16_t)options->DirPort,
619 (uint16_t)options->ORPort,
620 digest,
621 v3_digest,
622 type);
623 if (!ds) {
624 log_err(LD_GENERAL,"We want to be a directory authority, but we "
625 "couldn't add ourselves to the authority list. Failing.");
626 return -1;
629 if (ds->type != type) {
630 log_warn(LD_DIR, "Configured authority type does not match authority "
631 "type in DirServer list. Adjusting. (%d v %d)",
632 type, ds->type);
633 ds->type = type;
635 if (v3_digest_set && (ds->type & V3_AUTHORITY) &&
636 memcmp(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
637 log_warn(LD_DIR, "V3 identity key does not match identity declared in "
638 "DirServer line. Adjusting.");
639 memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
642 if (cert) { /* add my own cert to the list of known certs */
643 log_info(LD_DIR, "adding my own v3 cert");
644 if (trusted_dirs_load_certs_from_string(
645 cert->cache_info.signed_descriptor_body, 0, 0)<0) {
646 log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
647 return -1;
651 return 0; /* success */
654 /* Keep track of whether we should upload our server descriptor,
655 * and what type of server we are.
658 /** Whether we can reach our ORPort from the outside. */
659 static int can_reach_or_port = 0;
660 /** Whether we can reach our DirPort from the outside. */
661 static int can_reach_dir_port = 0;
663 /** Forget what we have learned about our reachability status. */
664 void
665 router_reset_reachability(void)
667 can_reach_or_port = can_reach_dir_port = 0;
670 /** Return 1 if ORPort is known reachable; else return 0. */
672 check_whether_orport_reachable(void)
674 or_options_t *options = get_options();
675 return options->AssumeReachable ||
676 can_reach_or_port;
679 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
681 check_whether_dirport_reachable(void)
683 or_options_t *options = get_options();
684 return !options->DirPort ||
685 options->AssumeReachable ||
686 we_are_hibernating() ||
687 can_reach_dir_port;
690 /** Look at a variety of factors, and return 0 if we don't want to
691 * advertise the fact that we have a DirPort open. Else return the
692 * DirPort we want to advertise.
694 * Log a helpful message if we change our mind about whether to publish
695 * a DirPort.
697 static int
698 decide_to_advertise_dirport(or_options_t *options, uint16_t dir_port)
700 static int advertising=1; /* start out assuming we will advertise */
701 int new_choice=1;
702 const char *reason = NULL;
704 /* Section one: reasons to publish or not publish that aren't
705 * worth mentioning to the user, either because they're obvious
706 * or because they're normal behavior. */
708 if (!dir_port) /* short circuit the rest of the function */
709 return 0;
710 if (authdir_mode(options)) /* always publish */
711 return dir_port;
712 if (we_are_hibernating())
713 return 0;
714 if (!check_whether_dirport_reachable())
715 return 0;
717 /* Section two: reasons to publish or not publish that the user
718 * might find surprising. These are generally config options that
719 * make us choose not to publish. */
721 if (accounting_is_enabled(options)) {
722 /* if we might potentially hibernate */
723 new_choice = 0;
724 reason = "AccountingMax enabled";
725 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
726 } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
727 (options->RelayBandwidthRate > 0 &&
728 options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
729 /* if we're advertising a small amount */
730 new_choice = 0;
731 reason = "BandwidthRate under 50KB";
734 if (advertising != new_choice) {
735 if (new_choice == 1) {
736 log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
737 } else {
738 tor_assert(reason);
739 log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
741 advertising = new_choice;
744 return advertising ? dir_port : 0;
747 /** Some time has passed, or we just got new directory information.
748 * See if we currently believe our ORPort or DirPort to be
749 * unreachable. If so, launch a new test for it.
751 * For ORPort, we simply try making a circuit that ends at ourselves.
752 * Success is noticed in onionskin_answer().
754 * For DirPort, we make a connection via Tor to our DirPort and ask
755 * for our own server descriptor.
756 * Success is noticed in connection_dir_client_reached_eof().
758 void
759 consider_testing_reachability(int test_or, int test_dir)
761 routerinfo_t *me = router_get_my_routerinfo();
762 int orport_reachable = check_whether_orport_reachable();
763 tor_addr_t addr;
764 if (!me)
765 return;
767 if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
768 log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
769 !orport_reachable ? "reachability" : "bandwidth",
770 me->address, me->or_port);
771 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me,
772 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
773 control_event_server_status(LOG_NOTICE,
774 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
775 me->address, me->or_port);
778 tor_addr_from_ipv4h(&addr, me->addr);
779 if (test_dir && !check_whether_dirport_reachable() &&
780 !connection_get_by_type_addr_port_purpose(
781 CONN_TYPE_DIR, &addr, me->dir_port,
782 DIR_PURPOSE_FETCH_SERVERDESC)) {
783 /* ask myself, via tor, for my server descriptor. */
784 directory_initiate_command(me->address, &addr,
785 me->or_port, me->dir_port,
786 0, /* does not matter */
787 0, me->cache_info.identity_digest,
788 DIR_PURPOSE_FETCH_SERVERDESC,
789 ROUTER_PURPOSE_GENERAL,
790 1, "authority.z", NULL, 0, 0);
792 control_event_server_status(LOG_NOTICE,
793 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
794 me->address, me->dir_port);
798 /** Annotate that we found our ORPort reachable. */
799 void
800 router_orport_found_reachable(void)
802 if (!can_reach_or_port) {
803 routerinfo_t *me = router_get_my_routerinfo();
804 log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
805 "the outside. Excellent.%s",
806 get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
807 " Publishing server descriptor." : "");
808 can_reach_or_port = 1;
809 mark_my_descriptor_dirty();
810 if (!me)
811 return;
812 control_event_server_status(LOG_NOTICE,
813 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
814 me->address, me->or_port);
818 /** Annotate that we found our DirPort reachable. */
819 void
820 router_dirport_found_reachable(void)
822 if (!can_reach_dir_port) {
823 routerinfo_t *me = router_get_my_routerinfo();
824 log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
825 "from the outside. Excellent.");
826 can_reach_dir_port = 1;
827 if (!me || decide_to_advertise_dirport(get_options(), me->dir_port))
828 mark_my_descriptor_dirty();
829 if (!me)
830 return;
831 control_event_server_status(LOG_NOTICE,
832 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
833 me->address, me->dir_port);
837 /** We have enough testing circuits open. Send a bunch of "drop"
838 * cells down each of them, to exercise our bandwidth. */
839 void
840 router_perform_bandwidth_test(int num_circs, time_t now)
842 int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
843 int max_cells = num_cells < CIRCWINDOW_START ?
844 num_cells : CIRCWINDOW_START;
845 int cells_per_circuit = max_cells / num_circs;
846 origin_circuit_t *circ = NULL;
848 log_notice(LD_OR,"Performing bandwidth self-test...done.");
849 while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
850 CIRCUIT_PURPOSE_TESTING))) {
851 /* dump cells_per_circuit drop cells onto this circ */
852 int i = cells_per_circuit;
853 if (circ->_base.state != CIRCUIT_STATE_OPEN)
854 continue;
855 circ->_base.timestamp_dirty = now;
856 while (i-- > 0) {
857 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
858 RELAY_COMMAND_DROP,
859 NULL, 0, circ->cpath->prev)<0) {
860 return; /* stop if error */
866 /** Return true iff we believe ourselves to be an authoritative
867 * directory server.
870 authdir_mode(or_options_t *options)
872 return options->AuthoritativeDir != 0;
874 /** Return true iff we believe ourselves to be a v1 authoritative
875 * directory server.
878 authdir_mode_v1(or_options_t *options)
880 return authdir_mode(options) && options->V1AuthoritativeDir != 0;
882 /** Return true iff we believe ourselves to be a v2 authoritative
883 * directory server.
886 authdir_mode_v2(or_options_t *options)
888 return authdir_mode(options) && options->V2AuthoritativeDir != 0;
890 /** Return true iff we believe ourselves to be a v3 authoritative
891 * directory server.
894 authdir_mode_v3(or_options_t *options)
896 return authdir_mode(options) && options->V3AuthoritativeDir != 0;
898 /** Return true iff we are a v1, v2, or v3 directory authority. */
900 authdir_mode_any_main(or_options_t *options)
902 return options->V1AuthoritativeDir ||
903 options->V2AuthoritativeDir ||
904 options->V3AuthoritativeDir;
906 /** Return true if we believe ourselves to be any kind of
907 * authoritative directory beyond just a hidserv authority. */
909 authdir_mode_any_nonhidserv(or_options_t *options)
911 return options->BridgeAuthoritativeDir ||
912 authdir_mode_any_main(options);
914 /** Return true iff we are an authoritative directory server that is
915 * authoritative about receiving and serving descriptors of type
916 * <b>purpose</b> its dirport. Use -1 for "any purpose". */
918 authdir_mode_handles_descs(or_options_t *options, int purpose)
920 if (purpose < 0)
921 return authdir_mode_any_nonhidserv(options);
922 else if (purpose == ROUTER_PURPOSE_GENERAL)
923 return authdir_mode_any_main(options);
924 else if (purpose == ROUTER_PURPOSE_BRIDGE)
925 return (options->BridgeAuthoritativeDir);
926 else
927 return 0;
929 /** Return true iff we are an authoritative directory server that
930 * publishes its own network statuses.
933 authdir_mode_publishes_statuses(or_options_t *options)
935 if (authdir_mode_bridge(options))
936 return 0;
937 return authdir_mode_any_nonhidserv(options);
939 /** Return true iff we are an authoritative directory server that
940 * tests reachability of the descriptors it learns about.
943 authdir_mode_tests_reachability(or_options_t *options)
945 return authdir_mode_handles_descs(options, -1);
947 /** Return true iff we believe ourselves to be a bridge authoritative
948 * directory server.
951 authdir_mode_bridge(or_options_t *options)
953 return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
955 /** Return true iff we once tried to stay connected to all ORs at once.
956 * FFFF this function, and the notion of staying connected to ORs, is
957 * nearly obsolete. One day there will be a proposal for getting rid of
958 * it.
961 clique_mode(or_options_t *options)
963 return authdir_mode_tests_reachability(options);
966 /** Return true iff we are trying to be a server.
969 server_mode(or_options_t *options)
971 if (options->ClientOnly) return 0;
972 return (options->ORPort != 0 || options->ORListenAddress);
975 /** Remember if we've advertised ourselves to the dirservers. */
976 static int server_is_advertised=0;
978 /** Return true iff we have published our descriptor lately.
981 advertised_server_mode(void)
983 return server_is_advertised;
987 * Called with a boolean: set whether we have recently published our
988 * descriptor.
990 static void
991 set_server_advertised(int s)
993 server_is_advertised = s;
996 /** Return true iff we are trying to be a socks proxy. */
998 proxy_mode(or_options_t *options)
1000 return (options->SocksPort != 0 || options->SocksListenAddress ||
1001 options->TransPort != 0 || options->TransListenAddress ||
1002 options->NatdPort != 0 || options->NatdListenAddress ||
1003 options->DNSPort != 0 || options->DNSListenAddress);
1006 /** Decide if we're a publishable server. We are a publishable server if:
1007 * - We don't have the ClientOnly option set
1008 * and
1009 * - We have the PublishServerDescriptor option set to non-empty
1010 * and
1011 * - We have ORPort set
1012 * and
1013 * - We believe we are reachable from the outside; or
1014 * - We are an authoritative directory server.
1016 static int
1017 decide_if_publishable_server(void)
1019 or_options_t *options = get_options();
1021 if (options->ClientOnly)
1022 return 0;
1023 if (options->_PublishServerDescriptor == NO_AUTHORITY)
1024 return 0;
1025 if (!server_mode(options))
1026 return 0;
1027 if (authdir_mode(options))
1028 return 1;
1030 return check_whether_orport_reachable();
1033 /** Initiate server descriptor upload as reasonable (if server is publishable,
1034 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1036 * We need to rebuild the descriptor if it's dirty even if we're not
1037 * uploading, because our reachability testing *uses* our descriptor to
1038 * determine what IP address and ports to test.
1040 void
1041 consider_publishable_server(int force)
1043 int rebuilt;
1045 if (!server_mode(get_options()))
1046 return;
1048 rebuilt = router_rebuild_descriptor(0);
1049 if (decide_if_publishable_server()) {
1050 set_server_advertised(1);
1051 if (rebuilt == 0)
1052 router_upload_dir_desc_to_dirservers(force);
1053 } else {
1054 set_server_advertised(0);
1059 * Clique maintenance -- to be phased out.
1062 /** Return true iff we believe this OR tries to keep connections open
1063 * to all other ORs. */
1065 router_is_clique_mode(routerinfo_t *router)
1067 if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
1068 return 1;
1069 return 0;
1073 * OR descriptor generation.
1076 /** My routerinfo. */
1077 static routerinfo_t *desc_routerinfo = NULL;
1078 /** My extrainfo */
1079 static extrainfo_t *desc_extrainfo = NULL;
1080 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1081 * now. */
1082 static time_t desc_clean_since = 0;
1083 /** Boolean: do we need to regenerate the above? */
1084 static int desc_needs_upload = 0;
1086 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1087 * descriptor successfully yet, try to upload our signed descriptor to
1088 * all the directory servers we know about.
1090 void
1091 router_upload_dir_desc_to_dirservers(int force)
1093 routerinfo_t *ri;
1094 extrainfo_t *ei;
1095 char *msg;
1096 size_t desc_len, extra_len = 0, total_len;
1097 authority_type_t auth = get_options()->_PublishServerDescriptor;
1099 ri = router_get_my_routerinfo();
1100 if (!ri) {
1101 log_info(LD_GENERAL, "No descriptor; skipping upload");
1102 return;
1104 ei = router_get_my_extrainfo();
1105 if (auth == NO_AUTHORITY)
1106 return;
1107 if (!force && !desc_needs_upload)
1108 return;
1109 desc_needs_upload = 0;
1111 desc_len = ri->cache_info.signed_descriptor_len;
1112 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1113 total_len = desc_len + extra_len + 1;
1114 msg = tor_malloc(total_len);
1115 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1116 if (ei) {
1117 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1119 msg[desc_len+extra_len] = 0;
1121 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
1122 (auth & BRIDGE_AUTHORITY) ?
1123 ROUTER_PURPOSE_BRIDGE :
1124 ROUTER_PURPOSE_GENERAL,
1125 auth, msg, desc_len, extra_len);
1126 tor_free(msg);
1129 /** OR only: Check whether my exit policy says to allow connection to
1130 * conn. Return 0 if we accept; non-0 if we reject.
1133 router_compare_to_my_exit_policy(edge_connection_t *conn)
1135 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1136 return -1;
1138 /* make sure it's resolved to something. this way we can't get a
1139 'maybe' below. */
1140 if (tor_addr_is_null(&conn->_base.addr))
1141 return -1;
1143 return compare_tor_addr_to_addr_policy(&conn->_base.addr, conn->_base.port,
1144 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
1147 /** Return true iff I'm a server and <b>digest</b> is equal to
1148 * my identity digest. */
1150 router_digest_is_me(const char *digest)
1152 return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
1155 /** Return true iff I'm a server and <b>digest</b> is equal to
1156 * my identity digest. */
1158 router_extrainfo_digest_is_me(const char *digest)
1160 extrainfo_t *ei = router_get_my_extrainfo();
1161 if (!ei)
1162 return 0;
1164 return !memcmp(digest,
1165 ei->cache_info.signed_descriptor_digest,
1166 DIGEST_LEN);
1169 /** A wrapper around router_digest_is_me(). */
1171 router_is_me(routerinfo_t *router)
1173 return router_digest_is_me(router->cache_info.identity_digest);
1176 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1178 router_fingerprint_is_me(const char *fp)
1180 char digest[DIGEST_LEN];
1181 if (strlen(fp) == HEX_DIGEST_LEN &&
1182 base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
1183 return router_digest_is_me(digest);
1185 return 0;
1188 /** Return a routerinfo for this OR, rebuilding a fresh one if
1189 * necessary. Return NULL on error, or if called on an OP. */
1190 routerinfo_t *
1191 router_get_my_routerinfo(void)
1193 if (!server_mode(get_options()))
1194 return NULL;
1195 if (router_rebuild_descriptor(0))
1196 return NULL;
1197 return desc_routerinfo;
1200 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1201 * one if necessary. Return NULL on error.
1203 const char *
1204 router_get_my_descriptor(void)
1206 const char *body;
1207 if (!router_get_my_routerinfo())
1208 return NULL;
1209 /* Make sure this is nul-terminated. */
1210 tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
1211 body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
1212 tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
1213 log_debug(LD_GENERAL,"my desc is '%s'", body);
1214 return body;
1217 /** Return the extrainfo document for this OR, or NULL if we have none.
1218 * Rebuilt it (and the server descriptor) if necessary. */
1219 extrainfo_t *
1220 router_get_my_extrainfo(void)
1222 if (!server_mode(get_options()))
1223 return NULL;
1224 if (router_rebuild_descriptor(0))
1225 return NULL;
1226 return desc_extrainfo;
1229 /** A list of nicknames that we've warned about including in our family
1230 * declaration verbatim rather than as digests. */
1231 static smartlist_t *warned_nonexistent_family = NULL;
1233 static int router_guess_address_from_dir_headers(uint32_t *guess);
1235 /** Make a current best guess at our address, either because
1236 * it's configured in torrc, or because we've learned it from
1237 * dirserver headers. Place the answer in *<b>addr</b> and return
1238 * 0 on success, else return -1 if we have no guess. */
1240 router_pick_published_address(or_options_t *options, uint32_t *addr)
1242 if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
1243 log_info(LD_CONFIG, "Could not determine our address locally. "
1244 "Checking if directory headers provide any hints.");
1245 if (router_guess_address_from_dir_headers(addr) < 0) {
1246 log_info(LD_CONFIG, "No hints from directory headers either. "
1247 "Will try again later.");
1248 return -1;
1251 return 0;
1254 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1255 * routerinfo, signed server descriptor, and extra-info document for this OR.
1256 * Return 0 on success, -1 on temporary error.
1259 router_rebuild_descriptor(int force)
1261 routerinfo_t *ri;
1262 extrainfo_t *ei;
1263 uint32_t addr;
1264 char platform[256];
1265 int hibernating = we_are_hibernating();
1266 or_options_t *options = get_options();
1268 if (desc_clean_since && !force)
1269 return 0;
1271 if (router_pick_published_address(options, &addr) < 0) {
1272 /* Stop trying to rebuild our descriptor every second. We'll
1273 * learn that it's time to try again when server_has_changed_ip()
1274 * marks it dirty. */
1275 desc_clean_since = time(NULL);
1276 return -1;
1279 ri = tor_malloc_zero(sizeof(routerinfo_t));
1280 ri->cache_info.routerlist_index = -1;
1281 ri->address = tor_dup_ip(addr);
1282 ri->nickname = tor_strdup(options->Nickname);
1283 ri->addr = addr;
1284 ri->or_port = options->ORPort;
1285 ri->dir_port = options->DirPort;
1286 ri->cache_info.published_on = time(NULL);
1287 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
1288 * main thread */
1289 ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
1290 if (crypto_pk_get_digest(ri->identity_pkey,
1291 ri->cache_info.identity_digest)<0) {
1292 routerinfo_free(ri);
1293 return -1;
1295 get_platform_str(platform, sizeof(platform));
1296 ri->platform = tor_strdup(platform);
1298 /* compute ri->bandwidthrate as the min of various options */
1299 ri->bandwidthrate = (int)options->BandwidthRate;
1300 if (ri->bandwidthrate > options->MaxAdvertisedBandwidth)
1301 ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
1302 if (options->RelayBandwidthRate > 0 &&
1303 ri->bandwidthrate > options->RelayBandwidthRate)
1304 ri->bandwidthrate = (int)options->RelayBandwidthRate;
1306 /* and compute ri->bandwidthburst similarly */
1307 ri->bandwidthburst = (int)options->BandwidthBurst;
1308 if (options->RelayBandwidthBurst > 0 &&
1309 ri->bandwidthburst > options->RelayBandwidthBurst)
1310 ri->bandwidthburst = (int)options->RelayBandwidthBurst;
1312 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
1314 policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
1315 options->ExitPolicyRejectPrivate,
1316 ri->address);
1318 if (desc_routerinfo) { /* inherit values */
1319 ri->is_valid = desc_routerinfo->is_valid;
1320 ri->is_running = desc_routerinfo->is_running;
1321 ri->is_named = desc_routerinfo->is_named;
1323 if (authdir_mode(options))
1324 ri->is_valid = ri->is_named = 1; /* believe in yourself */
1325 if (options->MyFamily) {
1326 smartlist_t *family;
1327 if (!warned_nonexistent_family)
1328 warned_nonexistent_family = smartlist_create();
1329 family = smartlist_create();
1330 ri->declared_family = smartlist_create();
1331 smartlist_split_string(family, options->MyFamily, ",",
1332 SPLIT_SKIP_SPACE|SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1333 SMARTLIST_FOREACH(family, char *, name,
1335 routerinfo_t *member;
1336 if (!strcasecmp(name, options->Nickname))
1337 member = ri;
1338 else
1339 member = router_get_by_nickname(name, 1);
1340 if (!member) {
1341 int is_legal = is_legal_nickname_or_hexdigest(name);
1342 if (!smartlist_string_isin(warned_nonexistent_family, name) &&
1343 !is_legal_hexdigest(name)) {
1344 if (is_legal)
1345 log_warn(LD_CONFIG,
1346 "I have no descriptor for the router named \"%s\" in my "
1347 "declared family; I'll use the nickname as is, but "
1348 "this may confuse clients.", name);
1349 else
1350 log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
1351 "declared family, but that isn't a legal nickname. "
1352 "Skipping it.", escaped(name));
1353 smartlist_add(warned_nonexistent_family, tor_strdup(name));
1355 if (is_legal) {
1356 smartlist_add(ri->declared_family, name);
1357 name = NULL;
1359 } else if (router_is_me(member)) {
1360 /* Don't list ourself in our own family; that's redundant */
1361 } else {
1362 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1363 fp[0] = '$';
1364 base16_encode(fp+1,HEX_DIGEST_LEN+1,
1365 member->cache_info.identity_digest, DIGEST_LEN);
1366 smartlist_add(ri->declared_family, fp);
1367 if (smartlist_string_isin(warned_nonexistent_family, name))
1368 smartlist_string_remove(warned_nonexistent_family, name);
1370 tor_free(name);
1373 /* remove duplicates from the list */
1374 smartlist_sort_strings(ri->declared_family);
1375 smartlist_uniq_strings(ri->declared_family);
1377 smartlist_free(family);
1380 /* Now generate the extrainfo. */
1381 ei = tor_malloc_zero(sizeof(extrainfo_t));
1382 ei->cache_info.is_extrainfo = 1;
1383 strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
1384 ei->cache_info.published_on = ri->cache_info.published_on;
1385 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
1386 DIGEST_LEN);
1387 ei->cache_info.signed_descriptor_body = tor_malloc(8192);
1388 if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body, 8192,
1389 ei, get_identity_key()) < 0) {
1390 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
1391 extrainfo_free(ei);
1392 return -1;
1394 ei->cache_info.signed_descriptor_len =
1395 strlen(ei->cache_info.signed_descriptor_body);
1396 router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
1397 ei->cache_info.signed_descriptor_digest);
1399 /* Now finish the router descriptor. */
1400 memcpy(ri->cache_info.extra_info_digest,
1401 ei->cache_info.signed_descriptor_digest,
1402 DIGEST_LEN);
1403 ri->cache_info.signed_descriptor_body = tor_malloc(8192);
1404 if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
1405 ri, get_identity_key())<0) {
1406 log_warn(LD_BUG, "Couldn't generate router descriptor.");
1407 return -1;
1409 ri->cache_info.signed_descriptor_len =
1410 strlen(ri->cache_info.signed_descriptor_body);
1412 ri->purpose =
1413 options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
1414 if (!options->BridgeRelay) {
1415 ri->cache_info.send_unencrypted = 1;
1416 ei->cache_info.send_unencrypted = 1;
1419 router_get_router_hash(ri->cache_info.signed_descriptor_body,
1420 ri->cache_info.signed_descriptor_digest);
1422 routerinfo_set_country(ri);
1424 tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
1426 if (desc_routerinfo)
1427 routerinfo_free(desc_routerinfo);
1428 desc_routerinfo = ri;
1429 if (desc_extrainfo)
1430 extrainfo_free(desc_extrainfo);
1431 desc_extrainfo = ei;
1433 desc_clean_since = time(NULL);
1434 desc_needs_upload = 1;
1435 control_event_my_descriptor_changed();
1436 return 0;
1439 /** Mark descriptor out of date if it's older than <b>when</b> */
1440 void
1441 mark_my_descriptor_dirty_if_older_than(time_t when)
1443 if (desc_clean_since < when)
1444 mark_my_descriptor_dirty();
1447 /** Call when the current descriptor is out of date. */
1448 void
1449 mark_my_descriptor_dirty(void)
1451 desc_clean_since = 0;
1454 /** How frequently will we republish our descriptor because of large (factor
1455 * of 2) shifts in estimated bandwidth? */
1456 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
1458 /** Check whether bandwidth has changed a lot since the last time we announced
1459 * bandwidth. If so, mark our descriptor dirty. */
1460 void
1461 check_descriptor_bandwidth_changed(time_t now)
1463 static time_t last_changed = 0;
1464 uint64_t prev, cur;
1465 if (!desc_routerinfo)
1466 return;
1468 prev = desc_routerinfo->bandwidthcapacity;
1469 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
1470 if ((prev != cur && (!prev || !cur)) ||
1471 cur > prev*2 ||
1472 cur < prev/2) {
1473 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
1474 log_info(LD_GENERAL,
1475 "Measured bandwidth has changed; rebuilding descriptor.");
1476 mark_my_descriptor_dirty();
1477 last_changed = now;
1482 /** Note at log level severity that our best guess of address has changed from
1483 * <b>prev</b> to <b>cur</b>. */
1484 static void
1485 log_addr_has_changed(int severity, uint32_t prev, uint32_t cur,
1486 const char *source)
1488 char addrbuf_prev[INET_NTOA_BUF_LEN];
1489 char addrbuf_cur[INET_NTOA_BUF_LEN];
1490 struct in_addr in_prev;
1491 struct in_addr in_cur;
1493 in_prev.s_addr = htonl(prev);
1494 tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
1496 in_cur.s_addr = htonl(cur);
1497 tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
1499 if (prev)
1500 log_fn(severity, LD_GENERAL,
1501 "Our IP Address has changed from %s to %s; "
1502 "rebuilding descriptor (source: %s).",
1503 addrbuf_prev, addrbuf_cur, source);
1504 else
1505 log_notice(LD_GENERAL,
1506 "Guessed our IP address as %s.",
1507 addrbuf_cur);
1510 /** Check whether our own address as defined by the Address configuration
1511 * has changed. This is for routers that get their address from a service
1512 * like dyndns. If our address has changed, mark our descriptor dirty. */
1513 void
1514 check_descriptor_ipaddress_changed(time_t now)
1516 uint32_t prev, cur;
1517 or_options_t *options = get_options();
1518 (void) now;
1520 if (!desc_routerinfo)
1521 return;
1523 prev = desc_routerinfo->addr;
1524 if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
1525 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
1526 return;
1529 if (prev != cur) {
1530 log_addr_has_changed(LOG_INFO, prev, cur, "resolve");
1531 ip_address_changed(0);
1535 /** The most recently guessed value of our IP address, based on directory
1536 * headers. */
1537 static uint32_t last_guessed_ip = 0;
1539 /** A directory server <b>d_conn</b> told us our IP address is
1540 * <b>suggestion</b>.
1541 * If this address is different from the one we think we are now, and
1542 * if our computer doesn't actually know its IP address, then switch. */
1543 void
1544 router_new_address_suggestion(const char *suggestion,
1545 const dir_connection_t *d_conn)
1547 uint32_t addr, cur = 0;
1548 struct in_addr in;
1549 or_options_t *options = get_options();
1551 /* first, learn what the IP address actually is */
1552 if (!tor_inet_aton(suggestion, &in)) {
1553 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
1554 escaped(suggestion));
1555 return;
1557 addr = ntohl(in.s_addr);
1559 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
1561 if (!server_mode(options)) {
1562 last_guessed_ip = addr; /* store it in case we need it later */
1563 return;
1566 if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
1567 /* We're all set -- we already know our address. Great. */
1568 last_guessed_ip = cur; /* store it in case we need it later */
1569 return;
1571 if (is_internal_IP(addr, 0)) {
1572 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1573 return;
1575 if (tor_addr_eq_ipv4h(&d_conn->_base.addr, addr)) {
1576 /* Don't believe anybody who says our IP is their IP. */
1577 log_debug(LD_DIR, "A directory server told us our IP address is %s, "
1578 "but he's just reporting his own IP address. Ignoring.",
1579 suggestion);
1580 return;
1583 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1584 * us an answer different from what we had the last time we managed to
1585 * resolve it. */
1586 if (last_guessed_ip != addr) {
1587 control_event_server_status(LOG_NOTICE,
1588 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1589 suggestion);
1590 log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr,
1591 d_conn->_base.address);
1592 ip_address_changed(0);
1593 last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
1597 /** We failed to resolve our address locally, but we'd like to build
1598 * a descriptor and publish / test reachability. If we have a guess
1599 * about our address based on directory headers, answer it and return
1600 * 0; else return -1. */
1601 static int
1602 router_guess_address_from_dir_headers(uint32_t *guess)
1604 if (last_guessed_ip) {
1605 *guess = last_guessed_ip;
1606 return 0;
1608 return -1;
1611 extern const char tor_svn_revision[]; /* from tor_main.c */
1613 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1614 * string describing the version of Tor and the operating system we're
1615 * currently running on.
1617 void
1618 get_platform_str(char *platform, size_t len)
1620 tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
1623 /* XXX need to audit this thing and count fenceposts. maybe
1624 * refactor so we don't have to keep asking if we're
1625 * near the end of maxlen?
1627 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1629 /** OR only: Given a routerinfo for this router, and an identity key to sign
1630 * with, encode the routerinfo as a signed server descriptor and write the
1631 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1632 * failure, and the number of bytes used on success.
1635 router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
1636 crypto_pk_env_t *ident_key)
1638 char *onion_pkey; /* Onion key, PEM-encoded. */
1639 char *identity_pkey; /* Identity key, PEM-encoded. */
1640 char digest[DIGEST_LEN];
1641 char published[ISO_TIME_LEN+1];
1642 char fingerprint[FINGERPRINT_LEN+1];
1643 char extra_info_digest[HEX_DIGEST_LEN+1];
1644 size_t onion_pkeylen, identity_pkeylen;
1645 size_t written;
1646 int result=0;
1647 addr_policy_t *tmpe;
1648 char *family_line;
1649 or_options_t *options = get_options();
1651 /* Make sure the identity key matches the one in the routerinfo. */
1652 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
1653 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
1654 "match router's public key!");
1655 return -1;
1658 /* record our fingerprint, so we can include it in the descriptor */
1659 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
1660 log_err(LD_BUG,"Error computing fingerprint");
1661 return -1;
1664 /* PEM-encode the onion key */
1665 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
1666 &onion_pkey,&onion_pkeylen)<0) {
1667 log_warn(LD_BUG,"write onion_pkey to string failed!");
1668 return -1;
1671 /* PEM-encode the identity key key */
1672 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
1673 &identity_pkey,&identity_pkeylen)<0) {
1674 log_warn(LD_BUG,"write identity_pkey to string failed!");
1675 tor_free(onion_pkey);
1676 return -1;
1679 /* Encode the publication time. */
1680 format_iso_time(published, router->cache_info.published_on);
1682 if (router->declared_family && smartlist_len(router->declared_family)) {
1683 size_t n;
1684 char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
1685 n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1686 family_line = tor_malloc(n);
1687 tor_snprintf(family_line, n, "family %s\n", family);
1688 tor_free(family);
1689 } else {
1690 family_line = tor_strdup("");
1693 base16_encode(extra_info_digest, sizeof(extra_info_digest),
1694 router->cache_info.extra_info_digest, DIGEST_LEN);
1696 /* Generate the easy portion of the router descriptor. */
1697 result = tor_snprintf(s, maxlen,
1698 "router %s %s %d 0 %d\n"
1699 "platform %s\n"
1700 "opt protocols Link 1 2 Circuit 1\n"
1701 "published %s\n"
1702 "opt fingerprint %s\n"
1703 "uptime %ld\n"
1704 "bandwidth %d %d %d\n"
1705 "opt extra-info-digest %s\n%s"
1706 "onion-key\n%s"
1707 "signing-key\n%s"
1708 "%s%s%s%s",
1709 router->nickname,
1710 router->address,
1711 router->or_port,
1712 decide_to_advertise_dirport(options, router->dir_port),
1713 router->platform,
1714 published,
1715 fingerprint,
1716 stats_n_seconds_working,
1717 (int) router->bandwidthrate,
1718 (int) router->bandwidthburst,
1719 (int) router->bandwidthcapacity,
1720 extra_info_digest,
1721 options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
1722 onion_pkey, identity_pkey,
1723 family_line,
1724 we_are_hibernating() ? "opt hibernating 1\n" : "",
1725 options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "",
1726 options->AllowSingleHopExits ? "opt allow-single-hop-exits\n" : "");
1728 tor_free(family_line);
1729 tor_free(onion_pkey);
1730 tor_free(identity_pkey);
1732 if (result < 0) {
1733 log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
1734 return -1;
1736 /* From now on, we use 'written' to remember the current length of 's'. */
1737 written = result;
1739 if (options->ContactInfo && strlen(options->ContactInfo)) {
1740 const char *ci = options->ContactInfo;
1741 if (strchr(ci, '\n') || strchr(ci, '\r'))
1742 ci = escaped(ci);
1743 result = tor_snprintf(s+written,maxlen-written, "contact %s\n", ci);
1744 if (result<0) {
1745 log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
1746 return -1;
1748 written += result;
1751 /* Write the exit policy to the end of 's'. */
1752 if (dns_seems_to_be_broken() || has_dns_init_failed() ||
1753 !router->exit_policy || !smartlist_len(router->exit_policy)) {
1754 /* DNS is screwed up; don't claim to be an exit. */
1755 strlcat(s+written, "reject *:*\n", maxlen-written);
1756 written += strlen("reject *:*\n");
1757 tmpe = NULL;
1758 } else if (router->exit_policy) {
1759 int i;
1760 for (i = 0; i < smartlist_len(router->exit_policy); ++i) {
1761 tmpe = smartlist_get(router->exit_policy, i);
1762 result = policy_write_item(s+written, maxlen-written, tmpe, 1);
1763 if (result < 0) {
1764 log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
1765 return -1;
1767 tor_assert(result == (int)strlen(s+written));
1768 written += result;
1769 if (written+2 > maxlen) {
1770 log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
1771 return -1;
1773 s[written++] = '\n';
1777 if (written+256 > maxlen) { /* Not enough room for signature. */
1778 log_warn(LD_BUG,"not enough room left in descriptor for signature!");
1779 return -1;
1782 /* Sign the directory */
1783 strlcpy(s+written, "router-signature\n", maxlen-written);
1784 written += strlen(s+written);
1785 s[written] = '\0';
1786 if (router_get_router_hash(s, digest) < 0) {
1787 return -1;
1790 note_crypto_pk_op(SIGN_RTR);
1791 if (router_append_dirobj_signature(s+written,maxlen-written,
1792 digest,ident_key)<0) {
1793 log_warn(LD_BUG, "Couldn't sign router descriptor");
1794 return -1;
1796 written += strlen(s+written);
1798 if (written+2 > maxlen) {
1799 log_warn(LD_BUG,"Not enough room to finish descriptor.");
1800 return -1;
1802 /* include a last '\n' */
1803 s[written] = '\n';
1804 s[written+1] = 0;
1806 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1808 char *s_dup;
1809 const char *cp;
1810 routerinfo_t *ri_tmp;
1811 cp = s_dup = tor_strdup(s);
1812 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
1813 if (!ri_tmp) {
1814 log_err(LD_BUG,
1815 "We just generated a router descriptor we can't parse.");
1816 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1817 return -1;
1819 tor_free(s_dup);
1820 routerinfo_free(ri_tmp);
1822 #endif
1824 return (int)written+1;
1827 /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
1828 * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
1829 * negative on failure. */
1831 extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
1832 crypto_pk_env_t *ident_key)
1834 or_options_t *options = get_options();
1835 char identity[HEX_DIGEST_LEN+1];
1836 char published[ISO_TIME_LEN+1];
1837 char digest[DIGEST_LEN];
1838 char *bandwidth_usage;
1839 int result;
1840 size_t len;
1842 base16_encode(identity, sizeof(identity),
1843 extrainfo->cache_info.identity_digest, DIGEST_LEN);
1844 format_iso_time(published, extrainfo->cache_info.published_on);
1845 bandwidth_usage = rep_hist_get_bandwidth_lines(1);
1847 result = tor_snprintf(s, maxlen,
1848 "extra-info %s %s\n"
1849 "published %s\n%s",
1850 extrainfo->nickname, identity,
1851 published, bandwidth_usage);
1852 tor_free(bandwidth_usage);
1853 if (result<0)
1854 return -1;
1856 if (should_record_bridge_info(options)) {
1857 static time_t last_purged_at = 0;
1858 char *geoip_summary;
1859 time_t now = time(NULL);
1860 int geoip_purge_interval = 48*60*60;
1861 #ifdef ENABLE_GEOIP_STATS
1862 if (get_options()->DirRecordUsageByCountry)
1863 geoip_purge_interval = get_options()->DirRecordUsageRetainIPs;
1864 #endif
1865 if (now > last_purged_at+geoip_purge_interval) {
1866 geoip_remove_old_clients(now-geoip_purge_interval);
1867 last_purged_at = now;
1869 geoip_summary = geoip_get_client_history(time(NULL), GEOIP_CLIENT_CONNECT);
1870 if (geoip_summary) {
1871 char geoip_start[ISO_TIME_LEN+1];
1872 format_iso_time(geoip_start, geoip_get_history_start());
1873 result = tor_snprintf(s+strlen(s), maxlen-strlen(s),
1874 "geoip-start-time %s\n"
1875 "geoip-client-origins %s\n",
1876 geoip_start, geoip_summary);
1877 tor_free(geoip_summary);
1878 if (result<0)
1879 return -1;
1883 len = strlen(s);
1884 strlcat(s+len, "router-signature\n", maxlen-len);
1885 len += strlen(s+len);
1886 if (router_get_extrainfo_hash(s, digest)<0)
1887 return -1;
1888 if (router_append_dirobj_signature(s+len, maxlen-len, digest, ident_key)<0)
1889 return -1;
1891 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1893 char *cp, *s_dup;
1894 extrainfo_t *ei_tmp;
1895 cp = s_dup = tor_strdup(s);
1896 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
1897 if (!ei_tmp) {
1898 log_err(LD_BUG,
1899 "We just generated an extrainfo descriptor we can't parse.");
1900 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1901 return -1;
1903 tor_free(s_dup);
1904 extrainfo_free(ei_tmp);
1906 #endif
1908 return (int)strlen(s)+1;
1911 /** Return true iff <b>s</b> is a legally valid server nickname. */
1913 is_legal_nickname(const char *s)
1915 size_t len;
1916 tor_assert(s);
1917 len = strlen(s);
1918 return len > 0 && len <= MAX_NICKNAME_LEN &&
1919 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
1922 /** Return true iff <b>s</b> is a legally valid server nickname or
1923 * hex-encoded identity-key digest. */
1925 is_legal_nickname_or_hexdigest(const char *s)
1927 if (*s!='$')
1928 return is_legal_nickname(s);
1929 else
1930 return is_legal_hexdigest(s);
1933 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
1934 * digest. */
1936 is_legal_hexdigest(const char *s)
1938 size_t len;
1939 tor_assert(s);
1940 if (s[0] == '$') s++;
1941 len = strlen(s);
1942 if (len > HEX_DIGEST_LEN) {
1943 if (s[HEX_DIGEST_LEN] == '=' ||
1944 s[HEX_DIGEST_LEN] == '~') {
1945 if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
1946 return 0;
1947 } else {
1948 return 0;
1951 return (len >= HEX_DIGEST_LEN &&
1952 strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
1955 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
1956 * verbose representation of the identity of <b>router</b>. The format is:
1957 * A dollar sign.
1958 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
1959 * A "=" if the router is named; a "~" if it is not.
1960 * The router's nickname.
1962 void
1963 router_get_verbose_nickname(char *buf, routerinfo_t *router)
1965 buf[0] = '$';
1966 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
1967 DIGEST_LEN);
1968 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
1969 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
1972 /** Forget that we have issued any router-related warnings, so that we'll
1973 * warn again if we see the same errors. */
1974 void
1975 router_reset_warnings(void)
1977 if (warned_nonexistent_family) {
1978 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1979 smartlist_clear(warned_nonexistent_family);
1983 /** Given a router purpose, convert it to a string. Don't call this on
1984 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
1985 * know its string representation. */
1986 const char *
1987 router_purpose_to_string(uint8_t p)
1989 switch (p)
1991 case ROUTER_PURPOSE_GENERAL: return "general";
1992 case ROUTER_PURPOSE_BRIDGE: return "bridge";
1993 case ROUTER_PURPOSE_CONTROLLER: return "controller";
1994 default:
1995 tor_assert(0);
1997 return NULL;
2000 /** Given a string, convert it to a router purpose. */
2001 uint8_t
2002 router_purpose_from_string(const char *s)
2004 if (!strcmp(s, "general"))
2005 return ROUTER_PURPOSE_GENERAL;
2006 else if (!strcmp(s, "bridge"))
2007 return ROUTER_PURPOSE_BRIDGE;
2008 else if (!strcmp(s, "controller"))
2009 return ROUTER_PURPOSE_CONTROLLER;
2010 else
2011 return ROUTER_PURPOSE_UNKNOWN;
2014 /** Release all static resources held in router.c */
2015 void
2016 router_free_all(void)
2018 if (onionkey)
2019 crypto_free_pk_env(onionkey);
2020 if (lastonionkey)
2021 crypto_free_pk_env(lastonionkey);
2022 if (identitykey)
2023 crypto_free_pk_env(identitykey);
2024 if (key_lock)
2025 tor_mutex_free(key_lock);
2026 if (desc_routerinfo)
2027 routerinfo_free(desc_routerinfo);
2028 if (desc_extrainfo)
2029 extrainfo_free(desc_extrainfo);
2030 if (authority_signing_key)
2031 crypto_free_pk_env(authority_signing_key);
2032 if (authority_key_certificate)
2033 authority_cert_free(authority_key_certificate);
2034 if (legacy_signing_key)
2035 crypto_free_pk_env(legacy_signing_key);
2036 if (legacy_key_certificate)
2037 authority_cert_free(legacy_key_certificate);
2039 if (warned_nonexistent_family) {
2040 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
2041 smartlist_free(warned_nonexistent_family);