Don't trigger an assert if we start a directory authority with a
[tor.git] / src / or / router.c
blob349c11954732a585130b0cc3d26ff8236e35cf94
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
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 /* (Note that v3 authorities also have a separate "authority identity key",
49 * but this key is never actually loaded by the Tor process. Instead, it's
50 * used by tor-gencert to sign new signing keys and make new key
51 * certificates. */
53 /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
54 * to update onionkey correctly, call rotate_onion_key().
56 static void
57 set_onion_key(crypto_pk_env_t *k)
59 tor_mutex_acquire(key_lock);
60 onionkey = k;
61 onionkey_set_at = time(NULL);
62 tor_mutex_release(key_lock);
63 mark_my_descriptor_dirty();
66 /** Return the current onion key. Requires that the onion key has been
67 * loaded or generated. */
68 crypto_pk_env_t *
69 get_onion_key(void)
71 tor_assert(onionkey);
72 return onionkey;
75 /** Store a copy of the current onion key into *<b>key</b>, and a copy
76 * of the most recent onion key into *<b>last</b>.
78 void
79 dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
81 tor_assert(key);
82 tor_assert(last);
83 tor_mutex_acquire(key_lock);
84 tor_assert(onionkey);
85 *key = crypto_pk_dup_key(onionkey);
86 if (lastonionkey)
87 *last = crypto_pk_dup_key(lastonionkey);
88 else
89 *last = NULL;
90 tor_mutex_release(key_lock);
93 /** Return the time when the onion key was last set. This is either the time
94 * when the process launched, or the time of the most recent key rotation since
95 * the process launched.
97 time_t
98 get_onion_key_set_at(void)
100 return onionkey_set_at;
103 /** Set the current identity key to k.
105 void
106 set_identity_key(crypto_pk_env_t *k)
108 if (identitykey)
109 crypto_free_pk_env(identitykey);
110 identitykey = k;
111 crypto_pk_get_digest(identitykey, identitykey_digest);
114 /** Returns the current identity key; requires that the identity key has been
115 * set.
117 crypto_pk_env_t *
118 get_identity_key(void)
120 tor_assert(identitykey);
121 return identitykey;
124 /** Return true iff the identity key has been set. */
126 identity_key_is_set(void)
128 return identitykey != NULL;
131 /** Return the key certificate for this v3 (voting) authority, or NULL
132 * if we have no such certificate. */
133 authority_cert_t *
134 get_my_v3_authority_cert(void)
136 return authority_key_certificate;
139 /** Return the v3 signing key for this v3 (voting) authority, or NULL
140 * if we have no such key. */
141 crypto_pk_env_t *
142 get_my_v3_authority_signing_key(void)
144 return authority_signing_key;
147 /** Replace the previous onion key with the current onion key, and generate
148 * a new previous onion key. Immediately after calling this function,
149 * the OR should:
150 * - schedule all previous cpuworkers to shut down _after_ processing
151 * pending work. (This will cause fresh cpuworkers to be generated.)
152 * - generate and upload a fresh routerinfo.
154 void
155 rotate_onion_key(void)
157 char *fname, *fname_prev;
158 crypto_pk_env_t *prkey;
159 or_state_t *state = get_or_state();
160 time_t now;
161 fname = get_datadir_fname2("keys", "secret_onion_key");
162 fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
163 if (!(prkey = crypto_new_pk_env())) {
164 log_err(LD_GENERAL,"Error constructing rotated onion key");
165 goto error;
167 if (crypto_pk_generate_key(prkey)) {
168 log_err(LD_BUG,"Error generating onion key");
169 goto error;
171 if (file_status(fname) == FN_FILE) {
172 if (replace_file(fname, fname_prev))
173 goto error;
175 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
176 log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
177 goto error;
179 log_info(LD_GENERAL, "Rotating onion key");
180 tor_mutex_acquire(key_lock);
181 if (lastonionkey)
182 crypto_free_pk_env(lastonionkey);
183 lastonionkey = onionkey;
184 onionkey = prkey;
185 now = time(NULL);
186 state->LastRotatedOnionKey = onionkey_set_at = now;
187 tor_mutex_release(key_lock);
188 mark_my_descriptor_dirty();
189 or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
190 goto done;
191 error:
192 log_warn(LD_GENERAL, "Couldn't rotate onion key.");
193 if (prkey)
194 crypto_free_pk_env(prkey);
195 done:
196 tor_free(fname);
197 tor_free(fname_prev);
200 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
201 * and <b>generate</b> is true, create a new RSA key and save it in
202 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
203 * errors at level <b>severity</b>.
205 crypto_pk_env_t *
206 init_key_from_file(const char *fname, int generate, int severity)
208 crypto_pk_env_t *prkey = NULL;
209 FILE *file = NULL;
211 if (!(prkey = crypto_new_pk_env())) {
212 log(severity, LD_GENERAL,"Error constructing key");
213 goto error;
216 switch (file_status(fname)) {
217 case FN_DIR:
218 case FN_ERROR:
219 log(severity, LD_FS,"Can't read key from \"%s\"", fname);
220 goto error;
221 case FN_NOENT:
222 if (generate) {
223 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
224 fname);
225 if (crypto_pk_generate_key(prkey)) {
226 log(severity, LD_GENERAL,"Error generating onion key");
227 goto error;
229 if (crypto_pk_check_key(prkey) <= 0) {
230 log(severity, LD_GENERAL,"Generated key seems invalid");
231 goto error;
233 log_info(LD_GENERAL, "Generated key seems valid");
234 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
235 log(severity, LD_FS,
236 "Couldn't write generated key to \"%s\".", fname);
237 goto error;
239 } else {
240 log_info(LD_GENERAL, "No key found in \"%s\"", fname);
242 return prkey;
243 case FN_FILE:
244 if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
245 log(severity, LD_GENERAL,"Error loading private key.");
246 goto error;
248 return prkey;
249 default:
250 tor_assert(0);
253 error:
254 if (prkey)
255 crypto_free_pk_env(prkey);
256 if (file)
257 fclose(file);
258 return NULL;
261 /** Load the v3 (voting) authority signing key and certificate, if they are
262 * present. Return -1 if anything is missing, mismatched, or unloadable;
263 * return 0 on success. */
264 /* XXXX020 maybe move to dirserv.c or dirvote.c */
265 static int
266 init_v3_authority_keys(void)
268 char *fname = NULL, *cert = NULL;
269 const char *eos = NULL;
270 crypto_pk_env_t *signing_key = NULL;
271 authority_cert_t *parsed = NULL;
272 int r = -1;
274 fname = get_datadir_fname2("keys", "authority_signing_key");
275 signing_key = init_key_from_file(fname, 0, LOG_INFO);
276 if (!signing_key) {
277 log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
278 goto done;
280 tor_free(fname);
281 fname = get_datadir_fname2("keys", "authority_certificate");
282 cert = read_file_to_str(fname, 0, NULL);
283 if (!cert) {
284 log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
285 fname);
286 goto done;
288 parsed = authority_cert_parse_from_string(cert, &eos);
289 if (!parsed) {
290 log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
291 goto done;
293 if (crypto_pk_cmp_keys(signing_key, parsed->signing_key) != 0) {
294 log_warn(LD_DIR, "Stored signing key does not match signing key in "
295 "certificate");
296 goto done;
298 parsed->cache_info.signed_descriptor_body = cert;
299 parsed->cache_info.signed_descriptor_len = eos-cert;
300 cert = NULL;
302 /* Free old values... */
303 if (authority_key_certificate)
304 authority_cert_free(authority_key_certificate);
305 if (authority_signing_key)
306 crypto_free_pk_env(authority_signing_key);
307 /* ...and replace them. */
308 authority_key_certificate = parsed;
309 authority_signing_key = signing_key;
310 parsed = NULL;
311 signing_key = NULL;
313 r = 0;
314 done:
315 tor_free(fname);
316 tor_free(cert);
317 if (signing_key)
318 crypto_free_pk_env(signing_key);
319 if (parsed)
320 authority_cert_free(parsed);
321 return r;
324 /** If we're a v3 authority, check whether we have a certificate that's
325 * likely to expire soon. Warn if we do, but not too often. */
326 void
327 v3_authority_check_key_expiry(void)
329 time_t now, expires;
330 static time_t last_warned = 0;
331 int badness, time_left, warn_interval;
332 if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
333 return;
335 now = time(NULL);
336 expires = authority_key_certificate->expires;
337 time_left = expires - now;
338 if (time_left <= 0) {
339 badness = LOG_ERR;
340 warn_interval = 60*60;
341 } else if (time_left <= 24*60*60) {
342 badness = LOG_WARN;
343 warn_interval = 60*60;
344 } else if (time_left <= 24*60*60*7) {
345 badness = LOG_WARN;
346 warn_interval = 24*60*60;
347 } else if (time_left <= 24*60*60*30) {
348 badness = LOG_WARN;
349 warn_interval = 24*60*60*5;
350 } else {
351 return;
354 if (last_warned + warn_interval > now)
355 return;
357 if (time_left <= 0) {
358 log(badness, LD_DIR, "Your v3 authority certificate has expired."
359 " Generate a new one NOW.");
360 } else if (time_left <= 24*60*60) {
361 log(badness, LD_DIR, "Your v3 authority certificate expires in %d hours;"
362 " Generate a new one NOW.", time_left/(60*60));
363 } else {
364 log(badness, LD_DIR, "Your v3 authority certificate expires in %d days;"
365 " Generate a new one soon.", time_left/(24*60*60));
367 last_warned = now;
370 /** Initialize all OR private keys, and the TLS context, as necessary.
371 * On OPs, this only initializes the tls context. Return 0 on success,
372 * or -1 if Tor should die.
375 init_keys(void)
377 char *keydir;
378 char fingerprint[FINGERPRINT_LEN+1];
379 /*nickname<space>fp\n\0 */
380 char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
381 const char *mydesc;
382 crypto_pk_env_t *prkey;
383 char digest[20];
384 char v3_digest[20];
385 char *cp;
386 or_options_t *options = get_options();
387 authority_type_t type;
388 time_t now = time(NULL);
389 trusted_dir_server_t *ds;
390 int v3_digest_set = 0;
392 if (!key_lock)
393 key_lock = tor_mutex_new();
395 /* OP's don't need persistent keys; just make up an identity and
396 * initialize the TLS context. */
397 if (!server_mode(options)) {
398 if (!(prkey = crypto_new_pk_env()))
399 return -1;
400 if (crypto_pk_generate_key(prkey)) {
401 crypto_free_pk_env(prkey);
402 return -1;
404 set_identity_key(prkey);
405 /* Create a TLS context; default the client nickname to "client". */
406 if (tor_tls_context_new(get_identity_key(),
407 options->Nickname ? options->Nickname : "client",
408 MAX_SSL_KEY_LIFETIME) < 0) {
409 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
410 return -1;
412 return 0;
414 /* Make sure DataDirectory exists, and is private. */
415 if (check_private_dir(options->DataDirectory, CPD_CREATE)) {
416 return -1;
418 /* Check the key directory. */
419 keydir = get_datadir_fname("keys");
420 if (check_private_dir(keydir, CPD_CREATE)) {
421 tor_free(keydir);
422 return -1;
424 tor_free(keydir);
426 /* 1a. Read v3 directory authority key/cert information. */
427 memset(v3_digest, 0, sizeof(v3_digest));
428 if (authdir_mode_v3(options)) {
429 if (init_v3_authority_keys()<0) {
430 log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
431 "were unable to load our v3 authority keys and certificate! "
432 "Use tor-gencert to generate them. Dying.");
433 return -1;
435 if (get_my_v3_authority_cert()) {
436 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
437 v3_digest);
438 v3_digest_set = 1;
442 /* 1. Read identity key. Make it if none is found. */
443 keydir = get_datadir_fname2("keys", "secret_id_key");
444 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
445 prkey = init_key_from_file(keydir, 1, LOG_ERR);
446 tor_free(keydir);
447 if (!prkey) return -1;
448 set_identity_key(prkey);
450 /* 2. Read onion key. Make it if none is found. */
451 keydir = get_datadir_fname2("keys", "secret_onion_key");
452 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
453 prkey = init_key_from_file(keydir, 1, LOG_ERR);
454 tor_free(keydir);
455 if (!prkey) return -1;
456 set_onion_key(prkey);
457 if (options->command == CMD_RUN_TOR) {
458 /* only mess with the state file if we're actually running Tor */
459 or_state_t *state = get_or_state();
460 if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
461 /* We allow for some parsing slop, but we don't want to risk accepting
462 * values in the distant future. If we did, we might never rotate the
463 * onion key. */
464 onionkey_set_at = state->LastRotatedOnionKey;
465 } else {
466 /* We have no LastRotatedOnionKey set; either we just created the key
467 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
468 * start the clock ticking now so that we will eventually rotate it even
469 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
470 state->LastRotatedOnionKey = onionkey_set_at = now;
471 or_state_mark_dirty(state, options->AvoidDiskWrites ?
472 time(NULL)+3600 : 0);
476 keydir = get_datadir_fname2("keys", "secret_onion_key.old");
477 if (!lastonionkey && file_status(keydir) == FN_FILE) {
478 prkey = init_key_from_file(keydir, 1, LOG_ERR);
479 if (prkey)
480 lastonionkey = prkey;
482 tor_free(keydir);
484 /* 3. Initialize link key and TLS context. */
485 if (tor_tls_context_new(get_identity_key(), options->Nickname,
486 MAX_SSL_KEY_LIFETIME) < 0) {
487 log_err(LD_GENERAL,"Error initializing TLS context");
488 return -1;
490 /* 4. Build our router descriptor. */
491 /* Must be called after keys are initialized. */
492 mydesc = router_get_my_descriptor();
493 if (authdir_mode(options)) {
494 const char *m;
495 routerinfo_t *ri;
496 /* We need to add our own fingerprint so it gets recognized. */
497 if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
498 log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
499 return -1;
501 if (mydesc) {
502 ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
503 if (!ri) {
504 log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
505 return -1;
507 if (dirserv_add_descriptor(ri, &m) < 0) {
508 log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
509 m?m:"<unknown error>");
510 return -1;
515 /* 5. Dump fingerprint to 'fingerprint' */
516 keydir = get_datadir_fname("fingerprint");
517 log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
518 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
519 log_err(LD_GENERAL,"Error computing fingerprint");
520 tor_free(keydir);
521 return -1;
523 tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
524 if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
525 "%s %s\n",options->Nickname, fingerprint) < 0) {
526 log_err(LD_GENERAL,"Error writing fingerprint line");
527 tor_free(keydir);
528 return -1;
530 /* Check whether we need to write the fingerprint file. */
531 cp = NULL;
532 if (file_status(keydir) == FN_FILE)
533 cp = read_file_to_str(keydir, 0, NULL);
534 if (!cp || strcmp(cp, fingerprint_line)) {
535 if (write_str_to_file(keydir, fingerprint_line, 0)) {
536 log_err(LD_FS, "Error writing fingerprint line to file");
537 tor_free(keydir);
538 return -1;
541 tor_free(cp);
542 tor_free(keydir);
544 log(LOG_NOTICE, LD_GENERAL,
545 "Your Tor server's identity key fingerprint is '%s %s'",
546 options->Nickname, fingerprint);
547 if (!authdir_mode(options))
548 return 0;
549 /* 6. [authdirserver only] load approved-routers file */
550 if (dirserv_load_fingerprint_file() < 0) {
551 log_err(LD_GENERAL,"Error loading fingerprints");
552 return -1;
554 /* 6b. [authdirserver only] add own key to approved directories. */
555 crypto_pk_get_digest(get_identity_key(), digest);
556 type = ((options->V1AuthoritativeDir ? V1_AUTHORITY : NO_AUTHORITY) |
557 (options->V2AuthoritativeDir ? V2_AUTHORITY : NO_AUTHORITY) |
558 (options->V3AuthoritativeDir ? V3_AUTHORITY : NO_AUTHORITY) |
559 (options->BridgeAuthoritativeDir ? BRIDGE_AUTHORITY : NO_AUTHORITY) |
560 (options->HSAuthoritativeDir ? HIDSERV_AUTHORITY : NO_AUTHORITY));
562 ds = router_get_trusteddirserver_by_digest(digest);
563 if (!ds) {
564 ds = add_trusted_dir_server(options->Nickname, NULL,
565 (uint16_t)options->DirPort,
566 (uint16_t)options->ORPort,
567 digest,
568 v3_digest,
569 type);
570 if (!ds) {
571 log_err(LD_GENERAL,"We want to be a directory authority, but we "
572 "couldn't add ourselves to the authority list. Failing.");
573 return -1;
576 if (ds->type != type) {
577 log_warn(LD_DIR, "Configured authority type does not match authority "
578 "type in DirServer list. Adjusting. (%d v %d)",
579 type, ds->type);
580 ds->type = type;
582 if (v3_digest_set && (ds->type & V3_AUTHORITY) &&
583 memcmp(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
584 log_warn(LD_DIR, "V3 identity key does not match identity declared in "
585 "DirServer line. Adjusting.");
586 memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
589 return 0; /* success */
592 /* Keep track of whether we should upload our server descriptor,
593 * and what type of server we are.
596 /** Whether we can reach our ORPort from the outside. */
597 static int can_reach_or_port = 0;
598 /** Whether we can reach our DirPort from the outside. */
599 static int can_reach_dir_port = 0;
601 /** Forget what we have learned about our reachability status. */
602 void
603 router_reset_reachability(void)
605 can_reach_or_port = can_reach_dir_port = 0;
608 /** Return 1 if ORPort is known reachable; else return 0. */
610 check_whether_orport_reachable(void)
612 or_options_t *options = get_options();
613 return options->AssumeReachable ||
614 can_reach_or_port;
617 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
619 check_whether_dirport_reachable(void)
621 or_options_t *options = get_options();
622 return !options->DirPort ||
623 options->AssumeReachable ||
624 we_are_hibernating() ||
625 can_reach_dir_port;
628 /** Look at a variety of factors, and return 0 if we don't want to
629 * advertise the fact that we have a DirPort open. Else return the
630 * DirPort we want to advertise.
632 * Log a helpful message if we change our mind about whether to publish
633 * a DirPort.
635 static int
636 decide_to_advertise_dirport(or_options_t *options, uint16_t dir_port)
638 static int advertising=1; /* start out assuming we will advertise */
639 int new_choice=1;
640 const char *reason = NULL;
642 /* Section one: reasons to publish or not publish that aren't
643 * worth mentioning to the user, either because they're obvious
644 * or because they're normal behavior. */
646 if (!dir_port) /* short circuit the rest of the function */
647 return 0;
648 if (authdir_mode(options)) /* always publish */
649 return dir_port;
650 if (we_are_hibernating())
651 return 0;
652 if (!check_whether_dirport_reachable())
653 return 0;
655 /* Section two: reasons to publish or not publish that the user
656 * might find surprising. These are generally config options that
657 * make us choose not to publish. */
659 if (accounting_is_enabled(options)) {
660 /* if we might potentially hibernate */
661 new_choice = 0;
662 reason = "AccountingMax enabled";
663 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
664 } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
665 (options->RelayBandwidthRate > 0 &&
666 options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
667 /* if we're advertising a small amount */
668 new_choice = 0;
669 reason = "BandwidthRate under 50KB";
672 if (advertising != new_choice) {
673 if (new_choice == 1) {
674 log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
675 } else {
676 tor_assert(reason);
677 log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
679 advertising = new_choice;
682 return advertising ? dir_port : 0;
685 /** Some time has passed, or we just got new directory information.
686 * See if we currently believe our ORPort or DirPort to be
687 * unreachable. If so, launch a new test for it.
689 * For ORPort, we simply try making a circuit that ends at ourselves.
690 * Success is noticed in onionskin_answer().
692 * For DirPort, we make a connection via Tor to our DirPort and ask
693 * for our own server descriptor.
694 * Success is noticed in connection_dir_client_reached_eof().
696 void
697 consider_testing_reachability(int test_or, int test_dir)
699 routerinfo_t *me = router_get_my_routerinfo();
700 int orport_reachable = check_whether_orport_reachable();
701 if (!me)
702 return;
704 if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
705 log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
706 !orport_reachable ? "reachability" : "bandwidth",
707 me->address, me->or_port);
708 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me,
709 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
710 control_event_server_status(LOG_NOTICE,
711 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
712 me->address, me->or_port);
715 if (test_dir && !check_whether_dirport_reachable() &&
716 !connection_get_by_type_addr_port_purpose(
717 CONN_TYPE_DIR, me->addr, me->dir_port,
718 DIR_PURPOSE_FETCH_SERVERDESC)) {
719 /* ask myself, via tor, for my server descriptor. */
720 directory_initiate_command(me->address, me->addr,
721 me->or_port, me->dir_port,
722 0, me->cache_info.identity_digest,
723 DIR_PURPOSE_FETCH_SERVERDESC,
724 ROUTER_PURPOSE_GENERAL,
725 1, "authority.z", NULL, 0, 0);
727 control_event_server_status(LOG_NOTICE,
728 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
729 me->address, me->dir_port);
733 /** Annotate that we found our ORPort reachable. */
734 void
735 router_orport_found_reachable(void)
737 if (!can_reach_or_port) {
738 routerinfo_t *me = router_get_my_routerinfo();
739 log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
740 "the outside. Excellent.%s",
741 get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
742 " Publishing server descriptor." : "");
743 can_reach_or_port = 1;
744 mark_my_descriptor_dirty();
745 if (!me)
746 return;
747 control_event_server_status(LOG_NOTICE,
748 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
749 me->address, me->or_port);
753 /** Annotate that we found our DirPort reachable. */
754 void
755 router_dirport_found_reachable(void)
757 if (!can_reach_dir_port) {
758 routerinfo_t *me = router_get_my_routerinfo();
759 log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
760 "from the outside. Excellent.");
761 can_reach_dir_port = 1;
762 if (!me || decide_to_advertise_dirport(get_options(), me->dir_port))
763 mark_my_descriptor_dirty();
764 if (!me)
765 return;
766 control_event_server_status(LOG_NOTICE,
767 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
768 me->address, me->dir_port);
772 /** We have enough testing circuits open. Send a bunch of "drop"
773 * cells down each of them, to exercise our bandwidth. */
774 void
775 router_perform_bandwidth_test(int num_circs, time_t now)
777 int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
778 int max_cells = num_cells < CIRCWINDOW_START ?
779 num_cells : CIRCWINDOW_START;
780 int cells_per_circuit = max_cells / num_circs;
781 origin_circuit_t *circ = NULL;
783 log_notice(LD_OR,"Performing bandwidth self-test...done.");
784 while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
785 CIRCUIT_PURPOSE_TESTING))) {
786 /* dump cells_per_circuit drop cells onto this circ */
787 int i = cells_per_circuit;
788 if (circ->_base.state != CIRCUIT_STATE_OPEN)
789 continue;
790 circ->_base.timestamp_dirty = now;
791 while (i-- > 0) {
792 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
793 RELAY_COMMAND_DROP,
794 NULL, 0, circ->cpath->prev)<0) {
795 return; /* stop if error */
801 /** Return true iff we believe ourselves to be an authoritative
802 * directory server.
805 authdir_mode(or_options_t *options)
807 return options->AuthoritativeDir != 0;
809 /** Return true iff we believe ourselves to be a v1 authoritative
810 * directory server.
813 authdir_mode_v1(or_options_t *options)
815 return authdir_mode(options) && options->V1AuthoritativeDir != 0;
817 /** Return true iff we believe ourselves to be a v2 authoritative
818 * directory server.
821 authdir_mode_v2(or_options_t *options)
823 return authdir_mode(options) && options->V2AuthoritativeDir != 0;
825 /** Return true iff we believe ourselves to be a v3 authoritative
826 * directory server.
829 authdir_mode_v3(or_options_t *options)
831 return authdir_mode(options) && options->V3AuthoritativeDir != 0;
833 /** Return true iff we are a v1, v2, or v3 directory authority. */
835 authdir_mode_any_main(or_options_t *options)
837 return options->V1AuthoritativeDir ||
838 options->V2AuthoritativeDir ||
839 options->V3AuthoritativeDir;
841 /** Return true if we believe ourselves to be any kind of
842 * authoritative directory beyond just a hidserv authority. */
844 authdir_mode_any_nonhidserv(or_options_t *options)
846 return options->BridgeAuthoritativeDir ||
847 authdir_mode_any_main(options);
849 /** Return true iff we are an authoritative directory server that is
850 * authoritative about receiving and serving descriptors of type
851 * <b>purpose</b> its dirport. Use -1 for "any purpose". */
853 authdir_mode_handles_descs(or_options_t *options, int purpose)
855 if (purpose < 0)
856 return authdir_mode_any_nonhidserv(options);
857 else if (purpose == ROUTER_PURPOSE_GENERAL)
858 return authdir_mode_any_main(options);
859 else if (purpose == ROUTER_PURPOSE_BRIDGE)
860 return (options->BridgeAuthoritativeDir);
861 else
862 return 0;
864 /** Return true iff we are an authoritative directory server that
865 * publishes its own network statuses.
868 authdir_mode_publishes_statuses(or_options_t *options)
870 if (authdir_mode_bridge(options))
871 return 0;
872 return authdir_mode_any_nonhidserv(options);
874 /** Return true iff we are an authoritative directory server that
875 * tests reachability of the descriptors it learns about.
878 authdir_mode_tests_reachability(or_options_t *options)
880 return authdir_mode_handles_descs(options, -1);
882 /** Return true iff we believe ourselves to be a bridge authoritative
883 * directory server.
886 authdir_mode_bridge(or_options_t *options)
888 return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
890 /** Return true iff we once tried to stay connected to all ORs at once.
891 * FFFF this function, and the notion of staying connected to ORs, is
892 * nearly obsolete. One day there will be a proposal for getting rid of
893 * it.
896 clique_mode(or_options_t *options)
898 return authdir_mode_tests_reachability(options);
901 /** Return true iff we are trying to be a server.
904 server_mode(or_options_t *options)
906 if (options->ClientOnly) return 0;
907 return (options->ORPort != 0 || options->ORListenAddress);
910 /** Remember if we've advertised ourselves to the dirservers. */
911 static int server_is_advertised=0;
913 /** Return true iff we have published our descriptor lately.
916 advertised_server_mode(void)
918 return server_is_advertised;
922 * Called with a boolean: set whether we have recently published our
923 * descriptor.
925 static void
926 set_server_advertised(int s)
928 server_is_advertised = s;
931 /** Return true iff we are trying to be a socks proxy. */
933 proxy_mode(or_options_t *options)
935 return (options->SocksPort != 0 || options->SocksListenAddress ||
936 options->TransPort != 0 || options->TransListenAddress ||
937 options->NatdPort != 0 || options->NatdListenAddress ||
938 options->DNSPort != 0 || options->DNSListenAddress);
941 /** Decide if we're a publishable server. We are a publishable server if:
942 * - We don't have the ClientOnly option set
943 * and
944 * - We have the PublishServerDescriptor option set to non-empty
945 * and
946 * - We have ORPort set
947 * and
948 * - We believe we are reachable from the outside; or
949 * - We are an authoritative directory server.
951 static int
952 decide_if_publishable_server(void)
954 or_options_t *options = get_options();
956 if (options->ClientOnly)
957 return 0;
958 if (options->_PublishServerDescriptor == NO_AUTHORITY)
959 return 0;
960 if (!server_mode(options))
961 return 0;
962 if (authdir_mode(options))
963 return 1;
965 return check_whether_orport_reachable();
968 /** Initiate server descriptor upload as reasonable (if server is publishable,
969 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
971 * We need to rebuild the descriptor if it's dirty even if we're not
972 * uploading, because our reachability testing *uses* our descriptor to
973 * determine what IP address and ports to test.
975 void
976 consider_publishable_server(int force)
978 int rebuilt;
980 if (!server_mode(get_options()))
981 return;
983 rebuilt = router_rebuild_descriptor(0);
984 if (decide_if_publishable_server()) {
985 set_server_advertised(1);
986 if (rebuilt == 0)
987 router_upload_dir_desc_to_dirservers(force);
988 } else {
989 set_server_advertised(0);
994 * Clique maintenance -- to be phased out.
997 /** Return true iff we believe this OR tries to keep connections open
998 * to all other ORs. */
1000 router_is_clique_mode(routerinfo_t *router)
1002 if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
1003 return 1;
1004 return 0;
1008 * OR descriptor generation.
1011 /** My routerinfo. */
1012 static routerinfo_t *desc_routerinfo = NULL;
1013 /** My extrainfo */
1014 static extrainfo_t *desc_extrainfo = NULL;
1015 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1016 * now. */
1017 static time_t desc_clean_since = 0;
1018 /** Boolean: do we need to regenerate the above? */
1019 static int desc_needs_upload = 0;
1021 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1022 * descriptor successfully yet, try to upload our signed descriptor to
1023 * all the directory servers we know about.
1025 void
1026 router_upload_dir_desc_to_dirservers(int force)
1028 routerinfo_t *ri;
1029 extrainfo_t *ei;
1030 char *msg;
1031 size_t desc_len, extra_len = 0, total_len;
1032 authority_type_t auth = get_options()->_PublishServerDescriptor;
1034 ri = router_get_my_routerinfo();
1035 if (!ri) {
1036 log_info(LD_GENERAL, "No descriptor; skipping upload");
1037 return;
1039 ei = router_get_my_extrainfo();
1040 if (auth == NO_AUTHORITY)
1041 return;
1042 if (!force && !desc_needs_upload)
1043 return;
1044 desc_needs_upload = 0;
1046 desc_len = ri->cache_info.signed_descriptor_len;
1047 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1048 total_len = desc_len + extra_len + 1;
1049 msg = tor_malloc(total_len);
1050 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1051 if (ei) {
1052 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1054 msg[desc_len+extra_len] = 0;
1056 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
1057 (auth & BRIDGE_AUTHORITY) ?
1058 ROUTER_PURPOSE_BRIDGE :
1059 ROUTER_PURPOSE_GENERAL,
1060 auth, msg, desc_len, extra_len);
1061 tor_free(msg);
1064 /** OR only: Check whether my exit policy says to allow connection to
1065 * conn. Return 0 if we accept; non-0 if we reject.
1068 router_compare_to_my_exit_policy(edge_connection_t *conn)
1070 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1071 return -1;
1073 /* make sure it's resolved to something. this way we can't get a
1074 'maybe' below. */
1075 if (!conn->_base.addr)
1076 return -1;
1078 return compare_addr_to_addr_policy(conn->_base.addr, conn->_base.port,
1079 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
1082 /** Return true iff I'm a server and <b>digest</b> is equal to
1083 * my identity digest. */
1085 router_digest_is_me(const char *digest)
1087 return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
1090 /** A wrapper around router_digest_is_me(). */
1092 router_is_me(routerinfo_t *router)
1094 return router_digest_is_me(router->cache_info.identity_digest);
1097 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1099 router_fingerprint_is_me(const char *fp)
1101 char digest[DIGEST_LEN];
1102 if (strlen(fp) == HEX_DIGEST_LEN &&
1103 base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
1104 return router_digest_is_me(digest);
1106 return 0;
1109 /** Return a routerinfo for this OR, rebuilding a fresh one if
1110 * necessary. Return NULL on error, or if called on an OP. */
1111 routerinfo_t *
1112 router_get_my_routerinfo(void)
1114 if (!server_mode(get_options()))
1115 return NULL;
1116 if (router_rebuild_descriptor(0))
1117 return NULL;
1118 return desc_routerinfo;
1121 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1122 * one if necessary. Return NULL on error.
1124 const char *
1125 router_get_my_descriptor(void)
1127 const char *body;
1128 if (!router_get_my_routerinfo())
1129 return NULL;
1130 /* Make sure this is nul-terminated. */
1131 tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
1132 body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
1133 tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
1134 log_debug(LD_GENERAL,"my desc is '%s'", body);
1135 return body;
1138 /* Return the extrainfo document for this OR, or NULL if we have none.
1139 * Rebuilt it (and the server descriptor) if necessary. */
1140 extrainfo_t *
1141 router_get_my_extrainfo(void)
1143 if (!server_mode(get_options()))
1144 return NULL;
1145 if (router_rebuild_descriptor(0))
1146 return NULL;
1147 return desc_extrainfo;
1150 /** A list of nicknames that we've warned about including in our family
1151 * declaration verbatim rather than as digests. */
1152 static smartlist_t *warned_nonexistent_family = NULL;
1154 static int router_guess_address_from_dir_headers(uint32_t *guess);
1156 /** Return our current best guess at our address, either because
1157 * it's configured in torrc, or because we've learned it from
1158 * dirserver headers. */
1160 router_pick_published_address(or_options_t *options, uint32_t *addr)
1162 if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
1163 log_info(LD_CONFIG, "Could not determine our address locally. "
1164 "Checking if directory headers provide any hints.");
1165 if (router_guess_address_from_dir_headers(addr) < 0) {
1166 log_info(LD_CONFIG, "No hints from directory headers either. "
1167 "Will try again later.");
1168 return -1;
1171 return 0;
1174 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1175 * routerinfo, signed server descriptor, and extra-info document for this OR.
1176 * Return 0 on success, -1 on temporary error.
1179 router_rebuild_descriptor(int force)
1181 routerinfo_t *ri;
1182 extrainfo_t *ei;
1183 uint32_t addr;
1184 char platform[256];
1185 int hibernating = we_are_hibernating();
1186 or_options_t *options = get_options();
1188 if (desc_clean_since && !force)
1189 return 0;
1191 if (router_pick_published_address(options, &addr) < 0) {
1192 /* Stop trying to rebuild our descriptor every second. We'll
1193 * learn that it's time to try again when server_has_changed_ip()
1194 * marks it dirty. */
1195 desc_clean_since = time(NULL);
1196 return -1;
1199 ri = tor_malloc_zero(sizeof(routerinfo_t));
1200 ri->cache_info.routerlist_index = -1;
1201 ri->address = tor_dup_addr(addr);
1202 ri->nickname = tor_strdup(options->Nickname);
1203 ri->addr = addr;
1204 ri->or_port = options->ORPort;
1205 ri->dir_port = options->DirPort;
1206 ri->cache_info.published_on = time(NULL);
1207 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
1208 * main thread */
1209 ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
1210 if (crypto_pk_get_digest(ri->identity_pkey,
1211 ri->cache_info.identity_digest)<0) {
1212 routerinfo_free(ri);
1213 return -1;
1215 get_platform_str(platform, sizeof(platform));
1216 ri->platform = tor_strdup(platform);
1218 /* compute ri->bandwidthrate as the min of various options */
1219 ri->bandwidthrate = (int)options->BandwidthRate;
1220 if (ri->bandwidthrate > options->MaxAdvertisedBandwidth)
1221 ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
1222 if (options->RelayBandwidthRate > 0 &&
1223 ri->bandwidthrate > options->RelayBandwidthRate)
1224 ri->bandwidthrate = (int)options->RelayBandwidthRate;
1226 /* and compute ri->bandwidthburst similarly */
1227 ri->bandwidthburst = (int)options->BandwidthBurst;
1228 if (options->RelayBandwidthBurst > 0 &&
1229 ri->bandwidthburst > options->RelayBandwidthBurst)
1230 ri->bandwidthburst = (int)options->RelayBandwidthBurst;
1232 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
1234 policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
1235 options->ExitPolicyRejectPrivate,
1236 ri->address);
1238 if (desc_routerinfo) { /* inherit values */
1239 ri->is_valid = desc_routerinfo->is_valid;
1240 ri->is_running = desc_routerinfo->is_running;
1241 ri->is_named = desc_routerinfo->is_named;
1243 if (authdir_mode(options))
1244 ri->is_valid = ri->is_named = 1; /* believe in yourself */
1245 if (options->MyFamily) {
1246 smartlist_t *family;
1247 if (!warned_nonexistent_family)
1248 warned_nonexistent_family = smartlist_create();
1249 family = smartlist_create();
1250 ri->declared_family = smartlist_create();
1251 smartlist_split_string(family, options->MyFamily, ",",
1252 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1253 SMARTLIST_FOREACH(family, char *, name,
1255 routerinfo_t *member;
1256 if (!strcasecmp(name, options->Nickname))
1257 member = ri;
1258 else
1259 member = router_get_by_nickname(name, 1);
1260 if (!member) {
1261 int is_legal = is_legal_nickname_or_hexdigest(name);
1262 if (!smartlist_string_isin(warned_nonexistent_family, name) &&
1263 !is_legal_hexdigest(name)) {
1264 if (is_legal)
1265 log_warn(LD_CONFIG,
1266 "I have no descriptor for the router named \"%s\" in my "
1267 "declared family; I'll use the nickname as is, but "
1268 "this may confuse clients.", name);
1269 else
1270 log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
1271 "declared family, but that isn't a legal nickname. "
1272 "Skipping it.", escaped(name));
1273 smartlist_add(warned_nonexistent_family, tor_strdup(name));
1275 if (is_legal) {
1276 smartlist_add(ri->declared_family, name);
1277 name = NULL;
1279 } else if (router_is_me(member)) {
1280 /* Don't list ourself in our own family; that's redundant */
1281 } else {
1282 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1283 fp[0] = '$';
1284 base16_encode(fp+1,HEX_DIGEST_LEN+1,
1285 member->cache_info.identity_digest, DIGEST_LEN);
1286 smartlist_add(ri->declared_family, fp);
1287 if (smartlist_string_isin(warned_nonexistent_family, name))
1288 smartlist_string_remove(warned_nonexistent_family, name);
1290 tor_free(name);
1293 /* remove duplicates from the list */
1294 smartlist_sort_strings(ri->declared_family);
1295 smartlist_uniq_strings(ri->declared_family);
1297 smartlist_free(family);
1300 /* Now generate the extrainfo. */
1301 ei = tor_malloc_zero(sizeof(extrainfo_t));
1302 ei->cache_info.is_extrainfo = 1;
1303 strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
1304 ei->cache_info.published_on = ri->cache_info.published_on;
1305 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
1306 DIGEST_LEN);
1307 ei->cache_info.signed_descriptor_body = tor_malloc(8192);
1308 if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body, 8192,
1309 ei, get_identity_key()) < 0) {
1310 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
1311 extrainfo_free(ei);
1312 return -1;
1314 ei->cache_info.signed_descriptor_len =
1315 strlen(ei->cache_info.signed_descriptor_body);
1316 router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
1317 ei->cache_info.signed_descriptor_digest);
1319 /* Now finish the router descriptor. */
1320 memcpy(ri->cache_info.extra_info_digest,
1321 ei->cache_info.signed_descriptor_digest,
1322 DIGEST_LEN);
1323 ri->cache_info.signed_descriptor_body = tor_malloc(8192);
1324 if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
1325 ri, get_identity_key())<0) {
1326 log_warn(LD_BUG, "Couldn't generate router descriptor.");
1327 return -1;
1329 ri->cache_info.signed_descriptor_len =
1330 strlen(ri->cache_info.signed_descriptor_body);
1332 ri->purpose =
1333 options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
1334 if (!options->BridgeRelay) {
1335 ri->cache_info.send_unencrypted = 1;
1336 ei->cache_info.send_unencrypted = 1;
1339 router_get_router_hash(ri->cache_info.signed_descriptor_body,
1340 ri->cache_info.signed_descriptor_digest);
1342 tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
1344 if (desc_routerinfo)
1345 routerinfo_free(desc_routerinfo);
1346 desc_routerinfo = ri;
1347 if (desc_extrainfo)
1348 extrainfo_free(desc_extrainfo);
1349 desc_extrainfo = ei;
1351 desc_clean_since = time(NULL);
1352 desc_needs_upload = 1;
1353 control_event_my_descriptor_changed();
1354 return 0;
1357 /** Mark descriptor out of date if it's older than <b>when</b> */
1358 void
1359 mark_my_descriptor_dirty_if_older_than(time_t when)
1361 if (desc_clean_since < when)
1362 mark_my_descriptor_dirty();
1365 /** Call when the current descriptor is out of date. */
1366 void
1367 mark_my_descriptor_dirty(void)
1369 desc_clean_since = 0;
1372 /** How frequently will we republish our descriptor because of large (factor
1373 * of 2) shifts in estimated bandwidth? */
1374 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
1376 /** Check whether bandwidth has changed a lot since the last time we announced
1377 * bandwidth. If so, mark our descriptor dirty. */
1378 void
1379 check_descriptor_bandwidth_changed(time_t now)
1381 static time_t last_changed = 0;
1382 uint64_t prev, cur;
1383 if (!desc_routerinfo)
1384 return;
1386 prev = desc_routerinfo->bandwidthcapacity;
1387 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
1388 if ((prev != cur && (!prev || !cur)) ||
1389 cur > prev*2 ||
1390 cur < prev/2) {
1391 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
1392 log_info(LD_GENERAL,
1393 "Measured bandwidth has changed; rebuilding descriptor.");
1394 mark_my_descriptor_dirty();
1395 last_changed = now;
1400 /** Note at log level severity that our best guess of address has changed from
1401 * <b>prev</b> to <b>cur</b>. */
1402 static void
1403 log_addr_has_changed(int severity, uint32_t prev, uint32_t cur)
1405 char addrbuf_prev[INET_NTOA_BUF_LEN];
1406 char addrbuf_cur[INET_NTOA_BUF_LEN];
1407 struct in_addr in_prev;
1408 struct in_addr in_cur;
1410 in_prev.s_addr = htonl(prev);
1411 tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
1413 in_cur.s_addr = htonl(cur);
1414 tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
1416 if (prev)
1417 log_fn(severity, LD_GENERAL,
1418 "Our IP Address has changed from %s to %s; "
1419 "rebuilding descriptor.",
1420 addrbuf_prev, addrbuf_cur);
1421 else
1422 log_notice(LD_GENERAL,
1423 "Guessed our IP address as %s.",
1424 addrbuf_cur);
1427 /** Check whether our own address as defined by the Address configuration
1428 * has changed. This is for routers that get their address from a service
1429 * like dyndns. If our address has changed, mark our descriptor dirty. */
1430 void
1431 check_descriptor_ipaddress_changed(time_t now)
1433 uint32_t prev, cur;
1434 or_options_t *options = get_options();
1435 (void) now;
1437 if (!desc_routerinfo)
1438 return;
1440 prev = desc_routerinfo->addr;
1441 if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
1442 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
1443 return;
1446 if (prev != cur) {
1447 log_addr_has_changed(LOG_INFO, prev, cur);
1448 ip_address_changed(0);
1452 /** The most recently guessed value of our IP address, based on directory
1453 * headers. */
1454 static uint32_t last_guessed_ip = 0;
1456 /** A directory server told us our IP address is <b>suggestion</b>.
1457 * If this address is different from the one we think we are now, and
1458 * if our computer doesn't actually know its IP address, then switch. */
1459 void
1460 router_new_address_suggestion(const char *suggestion)
1462 uint32_t addr, cur = 0;
1463 struct in_addr in;
1464 or_options_t *options = get_options();
1466 /* first, learn what the IP address actually is */
1467 if (!tor_inet_aton(suggestion, &in)) {
1468 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
1469 escaped(suggestion));
1470 return;
1472 addr = ntohl(in.s_addr);
1474 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
1476 if (!server_mode(options)) {
1477 last_guessed_ip = addr; /* store it in case we need it later */
1478 return;
1481 if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
1482 /* We're all set -- we already know our address. Great. */
1483 last_guessed_ip = cur; /* store it in case we need it later */
1484 return;
1486 if (is_internal_IP(addr, 0)) {
1487 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1488 return;
1491 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1492 * us an answer different from what we had the last time we managed to
1493 * resolve it. */
1494 if (last_guessed_ip != addr) {
1495 control_event_server_status(LOG_NOTICE,
1496 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1497 suggestion);
1498 log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr);
1499 ip_address_changed(0);
1500 last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
1504 /** We failed to resolve our address locally, but we'd like to build
1505 * a descriptor and publish / test reachability. If we have a guess
1506 * about our address based on directory headers, answer it and return
1507 * 0; else return -1. */
1508 static int
1509 router_guess_address_from_dir_headers(uint32_t *guess)
1511 if (last_guessed_ip) {
1512 *guess = last_guessed_ip;
1513 return 0;
1515 return -1;
1518 extern const char tor_svn_revision[]; /* from main.c */
1520 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1521 * string describing the version of Tor and the operating system we're
1522 * currently running on.
1524 void
1525 get_platform_str(char *platform, size_t len)
1527 tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
1530 /* XXX need to audit this thing and count fenceposts. maybe
1531 * refactor so we don't have to keep asking if we're
1532 * near the end of maxlen?
1534 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1536 /** OR only: Given a routerinfo for this router, and an identity key to sign
1537 * with, encode the routerinfo as a signed server descriptor and write the
1538 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1539 * failure, and the number of bytes used on success.
1542 router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
1543 crypto_pk_env_t *ident_key)
1545 char *onion_pkey; /* Onion key, PEM-encoded. */
1546 char *identity_pkey; /* Identity key, PEM-encoded. */
1547 char digest[DIGEST_LEN];
1548 char published[ISO_TIME_LEN+1];
1549 char fingerprint[FINGERPRINT_LEN+1];
1550 char extra_info_digest[HEX_DIGEST_LEN+1];
1551 size_t onion_pkeylen, identity_pkeylen;
1552 size_t written;
1553 int result=0;
1554 addr_policy_t *tmpe;
1555 char *family_line;
1556 or_options_t *options = get_options();
1558 /* Make sure the identity key matches the one in the routerinfo. */
1559 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
1560 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
1561 "match router's public key!");
1562 return -1;
1565 /* record our fingerprint, so we can include it in the descriptor */
1566 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
1567 log_err(LD_BUG,"Error computing fingerprint");
1568 return -1;
1571 /* PEM-encode the onion key */
1572 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
1573 &onion_pkey,&onion_pkeylen)<0) {
1574 log_warn(LD_BUG,"write onion_pkey to string failed!");
1575 return -1;
1578 /* PEM-encode the identity key key */
1579 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
1580 &identity_pkey,&identity_pkeylen)<0) {
1581 log_warn(LD_BUG,"write identity_pkey to string failed!");
1582 tor_free(onion_pkey);
1583 return -1;
1586 /* Encode the publication time. */
1587 format_iso_time(published, router->cache_info.published_on);
1589 if (router->declared_family && smartlist_len(router->declared_family)) {
1590 size_t n;
1591 char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
1592 n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1593 family_line = tor_malloc(n);
1594 tor_snprintf(family_line, n, "family %s\n", family);
1595 tor_free(family);
1596 } else {
1597 family_line = tor_strdup("");
1600 base16_encode(extra_info_digest, sizeof(extra_info_digest),
1601 router->cache_info.extra_info_digest, DIGEST_LEN);
1603 /* Generate the easy portion of the router descriptor. */
1604 result = tor_snprintf(s, maxlen,
1605 "router %s %s %d 0 %d\n"
1606 "platform %s\n"
1607 "opt protocols Link 1 Circuit 1\n"
1608 "published %s\n"
1609 "opt fingerprint %s\n"
1610 "uptime %ld\n"
1611 "bandwidth %d %d %d\n"
1612 "opt extra-info-digest %s\n%s"
1613 "onion-key\n%s"
1614 "signing-key\n%s"
1615 "%s%s%s",
1616 router->nickname,
1617 router->address,
1618 router->or_port,
1619 decide_to_advertise_dirport(options, router->dir_port),
1620 router->platform,
1621 published,
1622 fingerprint,
1623 stats_n_seconds_working,
1624 (int) router->bandwidthrate,
1625 (int) router->bandwidthburst,
1626 (int) router->bandwidthcapacity,
1627 extra_info_digest,
1628 options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
1629 onion_pkey, identity_pkey,
1630 family_line,
1631 we_are_hibernating() ? "opt hibernating 1\n" : "",
1632 options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "");
1634 tor_free(family_line);
1635 tor_free(onion_pkey);
1636 tor_free(identity_pkey);
1638 if (result < 0) {
1639 log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
1640 return -1;
1642 /* From now on, we use 'written' to remember the current length of 's'. */
1643 written = result;
1645 if (options->ContactInfo && strlen(options->ContactInfo)) {
1646 const char *ci = options->ContactInfo;
1647 if (strchr(ci, '\n') || strchr(ci, '\r'))
1648 ci = escaped(ci);
1649 result = tor_snprintf(s+written,maxlen-written, "contact %s\n", ci);
1650 if (result<0) {
1651 log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
1652 return -1;
1654 written += result;
1657 /* Write the exit policy to the end of 's'. */
1658 if (dns_seems_to_be_broken()) {
1659 /* DNS is screwed up; don't claim to be an exit. */
1660 strlcat(s+written, "reject *:*\n", maxlen-written);
1661 written += strlen("reject *:*\n");
1662 tmpe = NULL;
1663 } else if (router->exit_policy) {
1664 int i;
1665 for (i = 0; i < smartlist_len(router->exit_policy); ++i) {
1666 tmpe = smartlist_get(router->exit_policy, i);
1667 result = policy_write_item(s+written, maxlen-written, tmpe);
1668 if (result < 0) {
1669 log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
1670 return -1;
1672 tor_assert(result == (int)strlen(s+written));
1673 written += result;
1674 if (written+2 > maxlen) {
1675 log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
1676 return -1;
1678 s[written++] = '\n';
1682 if (written+256 > maxlen) { /* Not enough room for signature. */
1683 log_warn(LD_BUG,"not enough room left in descriptor for signature!");
1684 return -1;
1687 /* Sign the directory */
1688 strlcpy(s+written, "router-signature\n", maxlen-written);
1689 written += strlen(s+written);
1690 s[written] = '\0';
1691 if (router_get_router_hash(s, digest) < 0) {
1692 return -1;
1695 note_crypto_pk_op(SIGN_RTR);
1696 if (router_append_dirobj_signature(s+written,maxlen-written,
1697 digest,ident_key)<0) {
1698 log_warn(LD_BUG, "Couldn't sign router descriptor");
1699 return -1;
1701 written += strlen(s+written);
1703 if (written+2 > maxlen) {
1704 log_warn(LD_BUG,"Not enough room to finish descriptor.");
1705 return -1;
1707 /* include a last '\n' */
1708 s[written] = '\n';
1709 s[written+1] = 0;
1711 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1713 char *s_dup;
1714 const char *cp;
1715 routerinfo_t *ri_tmp;
1716 cp = s_dup = tor_strdup(s);
1717 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
1718 if (!ri_tmp) {
1719 log_err(LD_BUG,
1720 "We just generated a router descriptor we can't parse.");
1721 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1722 return -1;
1724 tor_free(s_dup);
1725 routerinfo_free(ri_tmp);
1727 #endif
1729 return written+1;
1732 /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
1733 * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
1734 * negative on failure. */
1736 extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
1737 crypto_pk_env_t *ident_key)
1739 or_options_t *options = get_options();
1740 char identity[HEX_DIGEST_LEN+1];
1741 char published[ISO_TIME_LEN+1];
1742 char digest[DIGEST_LEN];
1743 char *bandwidth_usage;
1744 int result;
1745 size_t len;
1747 base16_encode(identity, sizeof(identity),
1748 extrainfo->cache_info.identity_digest, DIGEST_LEN);
1749 format_iso_time(published, extrainfo->cache_info.published_on);
1750 bandwidth_usage = rep_hist_get_bandwidth_lines(1);
1752 result = tor_snprintf(s, maxlen,
1753 "extra-info %s %s\n"
1754 "published %s\n%s",
1755 extrainfo->nickname, identity,
1756 published, bandwidth_usage);
1757 tor_free(bandwidth_usage);
1758 if (result<0)
1759 return -1;
1761 if (options->BridgeRelay && options->BridgeRecordUsageByCountry) {
1762 char *geoip_summary = geoip_get_client_history(time(NULL));
1763 if (geoip_summary) {
1764 char geoip_start[ISO_TIME_LEN+1];
1765 format_iso_time(geoip_start, geoip_get_history_start());
1766 result = tor_snprintf(s+strlen(s), maxlen-strlen(s),
1767 "geoip-start-time %s\n"
1768 "geoip-client-origins %s\n",
1769 geoip_start, geoip_summary);
1770 tor_free(geoip_summary);
1771 if (result<0)
1772 return -1;
1776 len = strlen(s);
1777 strlcat(s+len, "router-signature\n", maxlen-len);
1778 len += strlen(s+len);
1779 if (router_get_extrainfo_hash(s, digest)<0)
1780 return -1;
1781 if (router_append_dirobj_signature(s+len, maxlen-len, digest, ident_key)<0)
1782 return -1;
1784 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1786 char *cp, *s_dup;
1787 extrainfo_t *ei_tmp;
1788 cp = s_dup = tor_strdup(s);
1789 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
1790 if (!ei_tmp) {
1791 log_err(LD_BUG,
1792 "We just generated an extrainfo descriptor we can't parse.");
1793 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1794 return -1;
1796 tor_free(s_dup);
1797 extrainfo_free(ei_tmp);
1799 #endif
1801 return strlen(s)+1;
1804 /** Return true iff <b>s</b> is a legally valid server nickname. */
1806 is_legal_nickname(const char *s)
1808 size_t len;
1809 tor_assert(s);
1810 len = strlen(s);
1811 return len > 0 && len <= MAX_NICKNAME_LEN &&
1812 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
1815 /** Return true iff <b>s</b> is a legally valid server nickname or
1816 * hex-encoded identity-key digest. */
1818 is_legal_nickname_or_hexdigest(const char *s)
1820 if (*s!='$')
1821 return is_legal_nickname(s);
1822 else
1823 return is_legal_hexdigest(s);
1826 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
1827 * digest. */
1829 is_legal_hexdigest(const char *s)
1831 size_t len;
1832 tor_assert(s);
1833 if (s[0] == '$') s++;
1834 len = strlen(s);
1835 if (len > HEX_DIGEST_LEN) {
1836 if (s[HEX_DIGEST_LEN] == '=' ||
1837 s[HEX_DIGEST_LEN] == '~') {
1838 if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
1839 return 0;
1840 } else {
1841 return 0;
1844 return (len >= HEX_DIGEST_LEN &&
1845 strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
1848 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
1849 * verbose representation of the identity of <b>router</b>. The format is:
1850 * A dollar sign.
1851 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
1852 * A "=" if the router is named; a "~" if it is not.
1853 * The router's nickname.
1855 void
1856 router_get_verbose_nickname(char *buf, routerinfo_t *router)
1858 buf[0] = '$';
1859 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
1860 DIGEST_LEN);
1861 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
1862 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
1865 /** Forget that we have issued any router-related warnings, so that we'll
1866 * warn again if we see the same errors. */
1867 void
1868 router_reset_warnings(void)
1870 if (warned_nonexistent_family) {
1871 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1872 smartlist_clear(warned_nonexistent_family);
1876 /** Given a router purpose, convert it to a string. Don't call this on
1877 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
1878 * know its string representation. */
1879 const char *
1880 router_purpose_to_string(uint8_t p)
1882 switch (p)
1884 case ROUTER_PURPOSE_GENERAL: return "general";
1885 case ROUTER_PURPOSE_BRIDGE: return "bridge";
1886 case ROUTER_PURPOSE_CONTROLLER: return "controller";
1887 default:
1888 tor_assert(0);
1890 return NULL;
1893 /** Given a string, convert it to a router purpose. */
1894 uint8_t
1895 router_purpose_from_string(const char *s)
1897 if (!strcmp(s, "general"))
1898 return ROUTER_PURPOSE_GENERAL;
1899 else if (!strcmp(s, "bridge"))
1900 return ROUTER_PURPOSE_BRIDGE;
1901 else if (!strcmp(s, "controller"))
1902 return ROUTER_PURPOSE_CONTROLLER;
1903 else
1904 return ROUTER_PURPOSE_UNKNOWN;
1907 /** Release all static resources held in router.c */
1908 void
1909 router_free_all(void)
1911 if (onionkey)
1912 crypto_free_pk_env(onionkey);
1913 if (lastonionkey)
1914 crypto_free_pk_env(lastonionkey);
1915 if (identitykey)
1916 crypto_free_pk_env(identitykey);
1917 if (key_lock)
1918 tor_mutex_free(key_lock);
1919 if (desc_routerinfo)
1920 routerinfo_free(desc_routerinfo);
1921 if (desc_extrainfo)
1922 extrainfo_free(desc_extrainfo);
1923 if (authority_signing_key)
1924 crypto_free_pk_env(authority_signing_key);
1925 if (authority_key_certificate)
1926 authority_cert_free(authority_key_certificate);
1928 if (warned_nonexistent_family) {
1929 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1930 smartlist_free(warned_nonexistent_family);