make new v3 authorities that aren't in the DirServers list believe
[tor.git] / src / or / router.c
blob5de54971b7c07ca718f17cd3a1766ebb790ef722
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 certificatge 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 return -1;
402 set_identity_key(prkey);
403 /* Create a TLS context; default the client nickname to "client". */
404 if (tor_tls_context_new(get_identity_key(),
405 options->Nickname ? options->Nickname : "client",
406 MAX_SSL_KEY_LIFETIME) < 0) {
407 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
408 return -1;
410 return 0;
412 /* Make sure DataDirectory exists, and is private. */
413 if (check_private_dir(options->DataDirectory, CPD_CREATE)) {
414 return -1;
416 /* Check the key directory. */
417 keydir = get_datadir_fname("keys");
418 if (check_private_dir(keydir, CPD_CREATE)) {
419 tor_free(keydir);
420 return -1;
422 tor_free(keydir);
424 /* 1a. Read v3 directory authority key/cert information. */
425 memset(v3_digest, 0, sizeof(v3_digest));
426 if (authdir_mode_v3(options)) {
427 if (init_v3_authority_keys()<0) {
428 log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
429 "were unable to load our v3 authority keys and certificate! "
430 "Use tor-gencert to generate them. Dying.");
431 return -1;
433 if (get_my_v3_authority_cert()) {
434 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
435 v3_digest);
436 v3_digest_set = 1;
440 /* 1. Read identity key. Make it if none is found. */
441 keydir = get_datadir_fname2("keys", "secret_id_key");
442 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
443 prkey = init_key_from_file(keydir, 1, LOG_ERR);
444 tor_free(keydir);
445 if (!prkey) return -1;
446 set_identity_key(prkey);
448 /* 2. Read onion key. Make it if none is found. */
449 keydir = get_datadir_fname2("keys", "secret_onion_key");
450 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
451 prkey = init_key_from_file(keydir, 1, LOG_ERR);
452 tor_free(keydir);
453 if (!prkey) return -1;
454 set_onion_key(prkey);
455 if (options->command == CMD_RUN_TOR) {
456 /* only mess with the state file if we're actually running Tor */
457 or_state_t *state = get_or_state();
458 if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
459 /* We allow for some parsing slop, but we don't want to risk accepting
460 * values in the distant future. If we did, we might never rotate the
461 * onion key. */
462 onionkey_set_at = state->LastRotatedOnionKey;
463 } else {
464 /* We have no LastRotatedOnionKey set; either we just created the key
465 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
466 * start the clock ticking now so that we will eventually rotate it even
467 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
468 state->LastRotatedOnionKey = onionkey_set_at = now;
469 or_state_mark_dirty(state, options->AvoidDiskWrites ?
470 time(NULL)+3600 : 0);
474 keydir = get_datadir_fname2("keys", "secret_onion_key.old");
475 if (!lastonionkey && file_status(keydir) == FN_FILE) {
476 prkey = init_key_from_file(keydir, 1, LOG_ERR);
477 if (prkey)
478 lastonionkey = prkey;
480 tor_free(keydir);
482 /* 3. Initialize link key and TLS context. */
483 if (tor_tls_context_new(get_identity_key(), options->Nickname,
484 MAX_SSL_KEY_LIFETIME) < 0) {
485 log_err(LD_GENERAL,"Error initializing TLS context");
486 return -1;
488 /* 4. Build our router descriptor. */
489 /* Must be called after keys are initialized. */
490 mydesc = router_get_my_descriptor();
491 if (authdir_mode(options)) {
492 const char *m;
493 routerinfo_t *ri;
494 /* We need to add our own fingerprint so it gets recognized. */
495 if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
496 log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
497 return -1;
499 if (mydesc) {
500 ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
501 if (!ri) {
502 log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
503 return -1;
505 if (dirserv_add_descriptor(ri, &m) < 0) {
506 log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
507 m?m:"<unknown error>");
508 return -1;
513 /* 5. Dump fingerprint to 'fingerprint' */
514 keydir = get_datadir_fname("fingerprint");
515 log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
516 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
517 log_err(LD_GENERAL,"Error computing fingerprint");
518 tor_free(keydir);
519 return -1;
521 tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
522 if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
523 "%s %s\n",options->Nickname, fingerprint) < 0) {
524 log_err(LD_GENERAL,"Error writing fingerprint line");
525 tor_free(keydir);
526 return -1;
528 /* Check whether we need to write the fingerprint file. */
529 cp = NULL;
530 if (file_status(keydir) == FN_FILE)
531 cp = read_file_to_str(keydir, 0, NULL);
532 if (!cp || strcmp(cp, fingerprint_line)) {
533 if (write_str_to_file(keydir, fingerprint_line, 0)) {
534 log_err(LD_FS, "Error writing fingerprint line to file");
535 tor_free(keydir);
536 return -1;
539 tor_free(cp);
540 tor_free(keydir);
542 log(LOG_NOTICE, LD_GENERAL,
543 "Your Tor server's identity key fingerprint is '%s %s'",
544 options->Nickname, fingerprint);
545 if (!authdir_mode(options))
546 return 0;
547 /* 6. [authdirserver only] load approved-routers file */
548 if (dirserv_load_fingerprint_file() < 0) {
549 log_err(LD_GENERAL,"Error loading fingerprints");
550 return -1;
552 /* 6b. [authdirserver only] add own key to approved directories. */
553 crypto_pk_get_digest(get_identity_key(), digest);
554 type = ((options->V1AuthoritativeDir ? V1_AUTHORITY : NO_AUTHORITY) |
555 (options->V2AuthoritativeDir ? V2_AUTHORITY : NO_AUTHORITY) |
556 (options->V3AuthoritativeDir ? V3_AUTHORITY : NO_AUTHORITY) |
557 (options->BridgeAuthoritativeDir ? BRIDGE_AUTHORITY : NO_AUTHORITY) |
558 (options->HSAuthoritativeDir ? HIDSERV_AUTHORITY : NO_AUTHORITY));
560 if (!router_get_trusteddirserver_by_digest(digest)) {
561 add_trusted_dir_server(options->Nickname, NULL,
562 (uint16_t)options->DirPort,
563 (uint16_t)options->ORPort,
564 digest,
565 v3_digest,
566 type);
568 if ((ds = router_get_trusteddirserver_by_digest(digest))) {
569 if (ds->type != type) {
570 log_warn(LD_DIR, "Configured authority type does not match authority "
571 "type in DirServer list. Adjusting. (%d v %d)",
572 type, ds->type);
573 ds->type = type;
575 if (v3_digest_set && (ds->type & V3_AUTHORITY) &&
576 memcmp(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
577 log_warn(LD_DIR, "V3 identity key does not match identity declared in "
578 "DirServer line. Adjusting.");
579 memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
583 return 0; /* success */
586 /* Keep track of whether we should upload our server descriptor,
587 * and what type of server we are.
590 /** Whether we can reach our ORPort from the outside. */
591 static int can_reach_or_port = 0;
592 /** Whether we can reach our DirPort from the outside. */
593 static int can_reach_dir_port = 0;
595 /** Forget what we have learned about our reachability status. */
596 void
597 router_reset_reachability(void)
599 can_reach_or_port = can_reach_dir_port = 0;
602 /** Return 1 if ORPort is known reachable; else return 0. */
604 check_whether_orport_reachable(void)
606 or_options_t *options = get_options();
607 return options->AssumeReachable ||
608 can_reach_or_port;
611 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
613 check_whether_dirport_reachable(void)
615 or_options_t *options = get_options();
616 return !options->DirPort ||
617 options->AssumeReachable ||
618 we_are_hibernating() ||
619 can_reach_dir_port;
622 /** Look at a variety of factors, and return 0 if we don't want to
623 * advertise the fact that we have a DirPort open. Else return the
624 * DirPort we want to advertise.
626 * Log a helpful message if we change our mind about whether to publish
627 * a DirPort.
629 static int
630 decide_to_advertise_dirport(or_options_t *options, uint16_t dir_port)
632 static int advertising=1; /* start out assuming we will advertise */
633 int new_choice=1;
634 const char *reason = NULL;
636 /* Section one: reasons to publish or not publish that aren't
637 * worth mentioning to the user, either because they're obvious
638 * or because they're normal behavior. */
640 if (!dir_port) /* short circuit the rest of the function */
641 return 0;
642 if (authdir_mode(options)) /* always publish */
643 return dir_port;
644 if (we_are_hibernating())
645 return 0;
646 if (!check_whether_dirport_reachable())
647 return 0;
649 /* Section two: reasons to publish or not publish that the user
650 * might find surprising. These are generally config options that
651 * make us choose not to publish. */
653 if (accounting_is_enabled(options)) {
654 /* if we might potentially hibernate */
655 new_choice = 0;
656 reason = "AccountingMax enabled";
657 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
658 } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
659 (options->RelayBandwidthRate > 0 &&
660 options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
661 /* if we're advertising a small amount */
662 new_choice = 0;
663 reason = "BandwidthRate under 50KB";
666 if (advertising != new_choice) {
667 if (new_choice == 1) {
668 log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
669 } else {
670 tor_assert(reason);
671 log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
673 advertising = new_choice;
676 return advertising ? dir_port : 0;
679 /** Some time has passed, or we just got new directory information.
680 * See if we currently believe our ORPort or DirPort to be
681 * unreachable. If so, launch a new test for it.
683 * For ORPort, we simply try making a circuit that ends at ourselves.
684 * Success is noticed in onionskin_answer().
686 * For DirPort, we make a connection via Tor to our DirPort and ask
687 * for our own server descriptor.
688 * Success is noticed in connection_dir_client_reached_eof().
690 void
691 consider_testing_reachability(int test_or, int test_dir)
693 routerinfo_t *me = router_get_my_routerinfo();
694 int orport_reachable = check_whether_orport_reachable();
695 if (!me)
696 return;
698 if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
699 log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
700 !orport_reachable ? "reachability" : "bandwidth",
701 me->address, me->or_port);
702 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me,
703 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
704 control_event_server_status(LOG_NOTICE,
705 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
706 me->address, me->or_port);
709 if (test_dir && !check_whether_dirport_reachable() &&
710 !connection_get_by_type_addr_port_purpose(
711 CONN_TYPE_DIR, me->addr, me->dir_port,
712 DIR_PURPOSE_FETCH_SERVERDESC)) {
713 /* ask myself, via tor, for my server descriptor. */
714 directory_initiate_command(me->address, me->addr,
715 me->or_port, me->dir_port,
716 0, me->cache_info.identity_digest,
717 DIR_PURPOSE_FETCH_SERVERDESC,
718 ROUTER_PURPOSE_GENERAL,
719 1, "authority.z", NULL, 0, 0);
721 control_event_server_status(LOG_NOTICE,
722 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
723 me->address, me->dir_port);
727 /** Annotate that we found our ORPort reachable. */
728 void
729 router_orport_found_reachable(void)
731 if (!can_reach_or_port) {
732 routerinfo_t *me = router_get_my_routerinfo();
733 log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
734 "the outside. Excellent.%s",
735 get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
736 " Publishing server descriptor." : "");
737 can_reach_or_port = 1;
738 mark_my_descriptor_dirty();
739 if (!me)
740 return;
741 control_event_server_status(LOG_NOTICE,
742 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
743 me->address, me->or_port);
747 /** Annotate that we found our DirPort reachable. */
748 void
749 router_dirport_found_reachable(void)
751 if (!can_reach_dir_port) {
752 routerinfo_t *me = router_get_my_routerinfo();
753 log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
754 "from the outside. Excellent.");
755 can_reach_dir_port = 1;
756 if (!me || decide_to_advertise_dirport(get_options(), me->dir_port))
757 mark_my_descriptor_dirty();
758 if (!me)
759 return;
760 control_event_server_status(LOG_NOTICE,
761 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
762 me->address, me->dir_port);
766 /** We have enough testing circuits open. Send a bunch of "drop"
767 * cells down each of them, to exercise our bandwidth. */
768 void
769 router_perform_bandwidth_test(int num_circs, time_t now)
771 int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
772 int max_cells = num_cells < CIRCWINDOW_START ?
773 num_cells : CIRCWINDOW_START;
774 int cells_per_circuit = max_cells / num_circs;
775 origin_circuit_t *circ = NULL;
777 log_notice(LD_OR,"Performing bandwidth self-test...done.");
778 while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
779 CIRCUIT_PURPOSE_TESTING))) {
780 /* dump cells_per_circuit drop cells onto this circ */
781 int i = cells_per_circuit;
782 if (circ->_base.state != CIRCUIT_STATE_OPEN)
783 continue;
784 circ->_base.timestamp_dirty = now;
785 while (i-- > 0) {
786 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
787 RELAY_COMMAND_DROP,
788 NULL, 0, circ->cpath->prev)<0) {
789 return; /* stop if error */
795 /** Return true iff we believe ourselves to be an authoritative
796 * directory server.
799 authdir_mode(or_options_t *options)
801 return options->AuthoritativeDir != 0;
803 /** Return true iff we believe ourselves to be a v1 authoritative
804 * directory server.
807 authdir_mode_v1(or_options_t *options)
809 return authdir_mode(options) && options->V1AuthoritativeDir != 0;
811 /** Return true iff we believe ourselves to be a v2 authoritative
812 * directory server.
815 authdir_mode_v2(or_options_t *options)
817 return authdir_mode(options) && options->V2AuthoritativeDir != 0;
819 /** Return true iff we believe ourselves to be a v3 authoritative
820 * directory server.
823 authdir_mode_v3(or_options_t *options)
825 return authdir_mode(options) && options->V3AuthoritativeDir != 0;
827 /** Return true iff we are a v1, v2, or v3 directory authority. */
829 authdir_mode_any_main(or_options_t *options)
831 return options->V1AuthoritativeDir ||
832 options->V2AuthoritativeDir ||
833 options->V3AuthoritativeDir;
835 /** Return true if we believe ourselves to be any kind of
836 * authoritative directory beyond just a hidserv authority. */
838 authdir_mode_any_nonhidserv(or_options_t *options)
840 return options->BridgeAuthoritativeDir ||
841 authdir_mode_any_main(options);
843 /** Return true iff we are an authoritative directory server that is
844 * authoritative about receiving and serving descriptors of type
845 * <b>purpose</b> its dirport. Use -1 for "any purpose". */
847 authdir_mode_handles_descs(or_options_t *options, int purpose)
849 if (purpose < 0)
850 return authdir_mode_any_nonhidserv(options);
851 else if (purpose == ROUTER_PURPOSE_GENERAL)
852 return authdir_mode_any_main(options);
853 else if (purpose == ROUTER_PURPOSE_BRIDGE)
854 return (options->BridgeAuthoritativeDir);
855 else
856 return 0;
858 /** Return true iff we are an authoritative directory server that
859 * publishes its own network statuses.
862 authdir_mode_publishes_statuses(or_options_t *options)
864 if (authdir_mode_bridge(options))
865 return 0;
866 return authdir_mode_any_nonhidserv(options);
868 /** Return true iff we are an authoritative directory server that
869 * tests reachability of the descriptors it learns about.
872 authdir_mode_tests_reachability(or_options_t *options)
874 return authdir_mode_handles_descs(options, -1);
876 /** Return true iff we believe ourselves to be a bridge authoritative
877 * directory server.
880 authdir_mode_bridge(or_options_t *options)
882 return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
884 /** Return true iff we once tried to stay connected to all ORs at once.
885 * FFFF this function, and the notion of staying connected to ORs, is
886 * nearly obsolete. One day there will be a proposal for getting rid of
887 * it.
890 clique_mode(or_options_t *options)
892 return authdir_mode_tests_reachability(options);
895 /** Return true iff we are trying to be a server.
898 server_mode(or_options_t *options)
900 if (options->ClientOnly) return 0;
901 return (options->ORPort != 0 || options->ORListenAddress);
904 /** Remember if we've advertised ourselves to the dirservers. */
905 static int server_is_advertised=0;
907 /** Return true iff we have published our descriptor lately.
910 advertised_server_mode(void)
912 return server_is_advertised;
916 * Called with a boolean: set whether we have recently published our
917 * descriptor.
919 static void
920 set_server_advertised(int s)
922 server_is_advertised = s;
925 /** Return true iff we are trying to be a socks proxy. */
927 proxy_mode(or_options_t *options)
929 return (options->SocksPort != 0 || options->SocksListenAddress ||
930 options->TransPort != 0 || options->TransListenAddress ||
931 options->NatdPort != 0 || options->NatdListenAddress ||
932 options->DNSPort != 0 || options->DNSListenAddress);
935 /** Decide if we're a publishable server. We are a publishable server if:
936 * - We don't have the ClientOnly option set
937 * and
938 * - We have the PublishServerDescriptor option set to non-empty
939 * and
940 * - We have ORPort set
941 * and
942 * - We believe we are reachable from the outside; or
943 * - We are an authoritative directory server.
945 static int
946 decide_if_publishable_server(void)
948 or_options_t *options = get_options();
950 if (options->ClientOnly)
951 return 0;
952 if (options->_PublishServerDescriptor == NO_AUTHORITY)
953 return 0;
954 if (!server_mode(options))
955 return 0;
956 if (authdir_mode(options))
957 return 1;
959 return check_whether_orport_reachable();
962 /** Initiate server descriptor upload as reasonable (if server is publishable,
963 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
965 * We need to rebuild the descriptor if it's dirty even if we're not
966 * uploading, because our reachability testing *uses* our descriptor to
967 * determine what IP address and ports to test.
969 void
970 consider_publishable_server(int force)
972 int rebuilt;
974 if (!server_mode(get_options()))
975 return;
977 rebuilt = router_rebuild_descriptor(0);
978 if (decide_if_publishable_server()) {
979 set_server_advertised(1);
980 if (rebuilt == 0)
981 router_upload_dir_desc_to_dirservers(force);
982 } else {
983 set_server_advertised(0);
988 * Clique maintenance -- to be phased out.
991 /** Return true iff we believe this OR tries to keep connections open
992 * to all other ORs. */
994 router_is_clique_mode(routerinfo_t *router)
996 if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
997 return 1;
998 return 0;
1002 * OR descriptor generation.
1005 /** My routerinfo. */
1006 static routerinfo_t *desc_routerinfo = NULL;
1007 /** My extrainfo */
1008 static extrainfo_t *desc_extrainfo = NULL;
1009 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1010 * now. */
1011 static time_t desc_clean_since = 0;
1012 /** Boolean: do we need to regenerate the above? */
1013 static int desc_needs_upload = 0;
1015 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1016 * descriptor successfully yet, try to upload our signed descriptor to
1017 * all the directory servers we know about.
1019 void
1020 router_upload_dir_desc_to_dirservers(int force)
1022 routerinfo_t *ri;
1023 extrainfo_t *ei;
1024 char *msg;
1025 size_t desc_len, extra_len = 0, total_len;
1026 authority_type_t auth = get_options()->_PublishServerDescriptor;
1028 ri = router_get_my_routerinfo();
1029 if (!ri) {
1030 log_info(LD_GENERAL, "No descriptor; skipping upload");
1031 return;
1033 ei = router_get_my_extrainfo();
1034 if (auth == NO_AUTHORITY)
1035 return;
1036 if (!force && !desc_needs_upload)
1037 return;
1038 desc_needs_upload = 0;
1040 desc_len = ri->cache_info.signed_descriptor_len;
1041 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1042 total_len = desc_len + extra_len + 1;
1043 msg = tor_malloc(total_len);
1044 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1045 if (ei) {
1046 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1048 msg[desc_len+extra_len] = 0;
1050 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
1051 (auth & BRIDGE_AUTHORITY) ?
1052 ROUTER_PURPOSE_BRIDGE :
1053 ROUTER_PURPOSE_GENERAL,
1054 auth, msg, desc_len, extra_len);
1055 tor_free(msg);
1058 /** OR only: Check whether my exit policy says to allow connection to
1059 * conn. Return 0 if we accept; non-0 if we reject.
1062 router_compare_to_my_exit_policy(edge_connection_t *conn)
1064 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1065 return -1;
1067 /* make sure it's resolved to something. this way we can't get a
1068 'maybe' below. */
1069 if (!conn->_base.addr)
1070 return -1;
1072 return compare_addr_to_addr_policy(conn->_base.addr, conn->_base.port,
1073 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
1076 /** Return true iff I'm a server and <b>digest</b> is equal to
1077 * my identity digest. */
1079 router_digest_is_me(const char *digest)
1081 return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
1084 /** A wrapper around router_digest_is_me(). */
1086 router_is_me(routerinfo_t *router)
1088 return router_digest_is_me(router->cache_info.identity_digest);
1091 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1093 router_fingerprint_is_me(const char *fp)
1095 char digest[DIGEST_LEN];
1096 if (strlen(fp) == HEX_DIGEST_LEN &&
1097 base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
1098 return router_digest_is_me(digest);
1100 return 0;
1103 /** Return a routerinfo for this OR, rebuilding a fresh one if
1104 * necessary. Return NULL on error, or if called on an OP. */
1105 routerinfo_t *
1106 router_get_my_routerinfo(void)
1108 if (!server_mode(get_options()))
1109 return NULL;
1110 if (router_rebuild_descriptor(0))
1111 return NULL;
1112 return desc_routerinfo;
1115 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1116 * one if necessary. Return NULL on error.
1118 const char *
1119 router_get_my_descriptor(void)
1121 const char *body;
1122 if (!router_get_my_routerinfo())
1123 return NULL;
1124 /* Make sure this is nul-terminated. */
1125 tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
1126 body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
1127 tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
1128 log_debug(LD_GENERAL,"my desc is '%s'", body);
1129 return body;
1132 /* Return the extrainfo document for this OR, or NULL if we have none.
1133 * Rebuilt it (and the server descriptor) if necessary. */
1134 extrainfo_t *
1135 router_get_my_extrainfo(void)
1137 if (!server_mode(get_options()))
1138 return NULL;
1139 if (router_rebuild_descriptor(0))
1140 return NULL;
1141 return desc_extrainfo;
1144 /** A list of nicknames that we've warned about including in our family
1145 * declaration verbatim rather than as digests. */
1146 static smartlist_t *warned_nonexistent_family = NULL;
1148 static int router_guess_address_from_dir_headers(uint32_t *guess);
1150 /** Return our current best guess at our address, either because
1151 * it's configured in torrc, or because we've learned it from
1152 * dirserver headers. */
1154 router_pick_published_address(or_options_t *options, uint32_t *addr)
1156 if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
1157 log_info(LD_CONFIG, "Could not determine our address locally. "
1158 "Checking if directory headers provide any hints.");
1159 if (router_guess_address_from_dir_headers(addr) < 0) {
1160 log_info(LD_CONFIG, "No hints from directory headers either. "
1161 "Will try again later.");
1162 return -1;
1165 return 0;
1168 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1169 * routerinfo, signed server descriptor, and extra-info document for this OR.
1170 * Return 0 on success, -1 on temporary error.
1173 router_rebuild_descriptor(int force)
1175 routerinfo_t *ri;
1176 extrainfo_t *ei;
1177 uint32_t addr;
1178 char platform[256];
1179 int hibernating = we_are_hibernating();
1180 or_options_t *options = get_options();
1182 if (desc_clean_since && !force)
1183 return 0;
1185 if (router_pick_published_address(options, &addr) < 0) {
1186 /* Stop trying to rebuild our descriptor every second. We'll
1187 * learn that it's time to try again when server_has_changed_ip()
1188 * marks it dirty. */
1189 desc_clean_since = time(NULL);
1190 return -1;
1193 ri = tor_malloc_zero(sizeof(routerinfo_t));
1194 ri->cache_info.routerlist_index = -1;
1195 ri->address = tor_dup_addr(addr);
1196 ri->nickname = tor_strdup(options->Nickname);
1197 ri->addr = addr;
1198 ri->or_port = options->ORPort;
1199 ri->dir_port = options->DirPort;
1200 ri->cache_info.published_on = time(NULL);
1201 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
1202 * main thread */
1203 ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
1204 if (crypto_pk_get_digest(ri->identity_pkey,
1205 ri->cache_info.identity_digest)<0) {
1206 routerinfo_free(ri);
1207 return -1;
1209 get_platform_str(platform, sizeof(platform));
1210 ri->platform = tor_strdup(platform);
1212 /* compute ri->bandwidthrate as the min of various options */
1213 ri->bandwidthrate = (int)options->BandwidthRate;
1214 if (ri->bandwidthrate > options->MaxAdvertisedBandwidth)
1215 ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
1216 if (options->RelayBandwidthRate > 0 &&
1217 ri->bandwidthrate > options->RelayBandwidthRate)
1218 ri->bandwidthrate = (int)options->RelayBandwidthRate;
1220 /* and compute ri->bandwidthburst similarly */
1221 ri->bandwidthburst = (int)options->BandwidthBurst;
1222 if (options->RelayBandwidthBurst > 0 &&
1223 ri->bandwidthburst > options->RelayBandwidthBurst)
1224 ri->bandwidthburst = (int)options->RelayBandwidthBurst;
1226 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
1228 policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
1229 options->ExitPolicyRejectPrivate,
1230 ri->address);
1232 if (desc_routerinfo) { /* inherit values */
1233 ri->is_valid = desc_routerinfo->is_valid;
1234 ri->is_running = desc_routerinfo->is_running;
1235 ri->is_named = desc_routerinfo->is_named;
1237 if (authdir_mode(options))
1238 ri->is_valid = ri->is_named = 1; /* believe in yourself */
1239 if (options->MyFamily) {
1240 smartlist_t *family;
1241 if (!warned_nonexistent_family)
1242 warned_nonexistent_family = smartlist_create();
1243 family = smartlist_create();
1244 ri->declared_family = smartlist_create();
1245 smartlist_split_string(family, options->MyFamily, ",",
1246 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1247 SMARTLIST_FOREACH(family, char *, name,
1249 routerinfo_t *member;
1250 if (!strcasecmp(name, options->Nickname))
1251 member = ri;
1252 else
1253 member = router_get_by_nickname(name, 1);
1254 if (!member) {
1255 int is_legal = is_legal_nickname_or_hexdigest(name);
1256 if (!smartlist_string_isin(warned_nonexistent_family, name) &&
1257 !is_legal_hexdigest(name)) {
1258 if (is_legal)
1259 log_warn(LD_CONFIG,
1260 "I have no descriptor for the router named \"%s\" in my "
1261 "declared family; I'll use the nickname as is, but "
1262 "this may confuse clients.", name);
1263 else
1264 log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
1265 "declared family, but that isn't a legal nickname. "
1266 "Skipping it.", escaped(name));
1267 smartlist_add(warned_nonexistent_family, tor_strdup(name));
1269 if (is_legal) {
1270 smartlist_add(ri->declared_family, name);
1271 name = NULL;
1273 } else if (router_is_me(member)) {
1274 /* Don't list ourself in our own family; that's redundant */
1275 } else {
1276 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1277 fp[0] = '$';
1278 base16_encode(fp+1,HEX_DIGEST_LEN+1,
1279 member->cache_info.identity_digest, DIGEST_LEN);
1280 smartlist_add(ri->declared_family, fp);
1281 if (smartlist_string_isin(warned_nonexistent_family, name))
1282 smartlist_string_remove(warned_nonexistent_family, name);
1284 tor_free(name);
1287 /* remove duplicates from the list */
1288 smartlist_sort_strings(ri->declared_family);
1289 smartlist_uniq_strings(ri->declared_family);
1291 smartlist_free(family);
1294 /* Now generate the extrainfo. */
1295 ei = tor_malloc_zero(sizeof(extrainfo_t));
1296 ei->cache_info.is_extrainfo = 1;
1297 strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
1298 ei->cache_info.published_on = ri->cache_info.published_on;
1299 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
1300 DIGEST_LEN);
1301 ei->cache_info.signed_descriptor_body = tor_malloc(8192);
1302 if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body, 8192,
1303 ei, get_identity_key()) < 0) {
1304 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
1305 return -1;
1307 ei->cache_info.signed_descriptor_len =
1308 strlen(ei->cache_info.signed_descriptor_body);
1309 router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
1310 ei->cache_info.signed_descriptor_digest);
1312 /* Now finish the router descriptor. */
1313 memcpy(ri->cache_info.extra_info_digest,
1314 ei->cache_info.signed_descriptor_digest,
1315 DIGEST_LEN);
1316 ri->cache_info.signed_descriptor_body = tor_malloc(8192);
1317 if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
1318 ri, get_identity_key())<0) {
1319 log_warn(LD_BUG, "Couldn't generate router descriptor.");
1320 return -1;
1322 ri->cache_info.signed_descriptor_len =
1323 strlen(ri->cache_info.signed_descriptor_body);
1325 router_get_router_hash(ri->cache_info.signed_descriptor_body,
1326 ri->cache_info.signed_descriptor_digest);
1328 tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
1330 if (desc_routerinfo)
1331 routerinfo_free(desc_routerinfo);
1332 desc_routerinfo = ri;
1333 if (desc_extrainfo)
1334 extrainfo_free(desc_extrainfo);
1335 desc_extrainfo = ei;
1337 desc_clean_since = time(NULL);
1338 desc_needs_upload = 1;
1339 control_event_my_descriptor_changed();
1340 return 0;
1343 /** Mark descriptor out of date if it's older than <b>when</b> */
1344 void
1345 mark_my_descriptor_dirty_if_older_than(time_t when)
1347 if (desc_clean_since < when)
1348 mark_my_descriptor_dirty();
1351 /** Call when the current descriptor is out of date. */
1352 void
1353 mark_my_descriptor_dirty(void)
1355 desc_clean_since = 0;
1358 /** How frequently will we republish our descriptor because of large (factor
1359 * of 2) shifts in estimated bandwidth? */
1360 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
1362 /** Check whether bandwidth has changed a lot since the last time we announced
1363 * bandwidth. If so, mark our descriptor dirty. */
1364 void
1365 check_descriptor_bandwidth_changed(time_t now)
1367 static time_t last_changed = 0;
1368 uint64_t prev, cur;
1369 if (!desc_routerinfo)
1370 return;
1372 prev = desc_routerinfo->bandwidthcapacity;
1373 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
1374 if ((prev != cur && (!prev || !cur)) ||
1375 cur > prev*2 ||
1376 cur < prev/2) {
1377 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
1378 log_info(LD_GENERAL,
1379 "Measured bandwidth has changed; rebuilding descriptor.");
1380 mark_my_descriptor_dirty();
1381 last_changed = now;
1386 /** Note at log level severity that our best guess of address has changed from
1387 * <b>prev</b> to <b>cur</b>. */
1388 static void
1389 log_addr_has_changed(int severity, uint32_t prev, uint32_t cur)
1391 char addrbuf_prev[INET_NTOA_BUF_LEN];
1392 char addrbuf_cur[INET_NTOA_BUF_LEN];
1393 struct in_addr in_prev;
1394 struct in_addr in_cur;
1396 in_prev.s_addr = htonl(prev);
1397 tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
1399 in_cur.s_addr = htonl(cur);
1400 tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
1402 if (prev)
1403 log_fn(severity, LD_GENERAL,
1404 "Our IP Address has changed from %s to %s; "
1405 "rebuilding descriptor.",
1406 addrbuf_prev, addrbuf_cur);
1407 else
1408 log_notice(LD_GENERAL,
1409 "Guessed our IP address as %s.",
1410 addrbuf_cur);
1413 /** Check whether our own address as defined by the Address configuration
1414 * has changed. This is for routers that get their address from a service
1415 * like dyndns. If our address has changed, mark our descriptor dirty. */
1416 void
1417 check_descriptor_ipaddress_changed(time_t now)
1419 uint32_t prev, cur;
1420 or_options_t *options = get_options();
1421 (void) now;
1423 if (!desc_routerinfo)
1424 return;
1426 prev = desc_routerinfo->addr;
1427 if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
1428 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
1429 return;
1432 if (prev != cur) {
1433 log_addr_has_changed(LOG_INFO, prev, cur);
1434 ip_address_changed(0);
1438 /** The most recently guessed value of our IP address, based on directory
1439 * headers. */
1440 static uint32_t last_guessed_ip = 0;
1442 /** A directory server told us our IP address is <b>suggestion</b>.
1443 * If this address is different from the one we think we are now, and
1444 * if our computer doesn't actually know its IP address, then switch. */
1445 void
1446 router_new_address_suggestion(const char *suggestion)
1448 uint32_t addr, cur = 0;
1449 struct in_addr in;
1450 or_options_t *options = get_options();
1452 /* first, learn what the IP address actually is */
1453 if (!tor_inet_aton(suggestion, &in)) {
1454 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
1455 escaped(suggestion));
1456 return;
1458 addr = ntohl(in.s_addr);
1460 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
1462 if (!server_mode(options)) {
1463 last_guessed_ip = addr; /* store it in case we need it later */
1464 return;
1467 if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
1468 /* We're all set -- we already know our address. Great. */
1469 last_guessed_ip = cur; /* store it in case we need it later */
1470 return;
1472 if (is_internal_IP(addr, 0)) {
1473 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1474 return;
1477 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1478 * us an answer different from what we had the last time we managed to
1479 * resolve it. */
1480 if (last_guessed_ip != addr) {
1481 control_event_server_status(LOG_NOTICE,
1482 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1483 suggestion);
1484 log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr);
1485 ip_address_changed(0);
1486 last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
1490 /** We failed to resolve our address locally, but we'd like to build
1491 * a descriptor and publish / test reachability. If we have a guess
1492 * about our address based on directory headers, answer it and return
1493 * 0; else return -1. */
1494 static int
1495 router_guess_address_from_dir_headers(uint32_t *guess)
1497 if (last_guessed_ip) {
1498 *guess = last_guessed_ip;
1499 return 0;
1501 return -1;
1504 extern const char tor_svn_revision[]; /* from main.c */
1506 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1507 * string describing the version of Tor and the operating system we're
1508 * currently running on.
1510 void
1511 get_platform_str(char *platform, size_t len)
1513 tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
1516 /* XXX need to audit this thing and count fenceposts. maybe
1517 * refactor so we don't have to keep asking if we're
1518 * near the end of maxlen?
1520 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1522 /** OR only: Given a routerinfo for this router, and an identity key to sign
1523 * with, encode the routerinfo as a signed server descriptor and write the
1524 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1525 * failure, and the number of bytes used on success.
1528 router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
1529 crypto_pk_env_t *ident_key)
1531 char *onion_pkey; /* Onion key, PEM-encoded. */
1532 char *identity_pkey; /* Identity key, PEM-encoded. */
1533 char digest[DIGEST_LEN];
1534 char published[ISO_TIME_LEN+1];
1535 char fingerprint[FINGERPRINT_LEN+1];
1536 char extra_info_digest[HEX_DIGEST_LEN+1];
1537 size_t onion_pkeylen, identity_pkeylen;
1538 size_t written;
1539 int result=0;
1540 addr_policy_t *tmpe;
1541 char *family_line;
1542 or_options_t *options = get_options();
1544 /* Make sure the identity key matches the one in the routerinfo. */
1545 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
1546 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
1547 "match router's public key!");
1548 return -1;
1551 /* record our fingerprint, so we can include it in the descriptor */
1552 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
1553 log_err(LD_BUG,"Error computing fingerprint");
1554 return -1;
1557 /* PEM-encode the onion key */
1558 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
1559 &onion_pkey,&onion_pkeylen)<0) {
1560 log_warn(LD_BUG,"write onion_pkey to string failed!");
1561 return -1;
1564 /* PEM-encode the identity key key */
1565 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
1566 &identity_pkey,&identity_pkeylen)<0) {
1567 log_warn(LD_BUG,"write identity_pkey to string failed!");
1568 tor_free(onion_pkey);
1569 return -1;
1572 /* Encode the publication time. */
1573 format_iso_time(published, router->cache_info.published_on);
1575 if (router->declared_family && smartlist_len(router->declared_family)) {
1576 size_t n;
1577 char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
1578 n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1579 family_line = tor_malloc(n);
1580 tor_snprintf(family_line, n, "family %s\n", family);
1581 tor_free(family);
1582 } else {
1583 family_line = tor_strdup("");
1586 base16_encode(extra_info_digest, sizeof(extra_info_digest),
1587 router->cache_info.extra_info_digest, DIGEST_LEN);
1589 /* Generate the easy portion of the router descriptor. */
1590 result = tor_snprintf(s, maxlen,
1591 "router %s %s %d 0 %d\n"
1592 "platform %s\n"
1593 "opt protocols Link 1 Circuit 1\n"
1594 "published %s\n"
1595 "opt fingerprint %s\n"
1596 "uptime %ld\n"
1597 "bandwidth %d %d %d\n"
1598 "opt extra-info-digest %s\n%s"
1599 "onion-key\n%s"
1600 "signing-key\n%s"
1601 "%s%s%s",
1602 router->nickname,
1603 router->address,
1604 router->or_port,
1605 decide_to_advertise_dirport(options, router->dir_port),
1606 router->platform,
1607 published,
1608 fingerprint,
1609 stats_n_seconds_working,
1610 (int) router->bandwidthrate,
1611 (int) router->bandwidthburst,
1612 (int) router->bandwidthcapacity,
1613 extra_info_digest,
1614 options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
1615 onion_pkey, identity_pkey,
1616 family_line,
1617 we_are_hibernating() ? "opt hibernating 1\n" : "",
1618 options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "");
1620 tor_free(family_line);
1621 tor_free(onion_pkey);
1622 tor_free(identity_pkey);
1624 if (result < 0) {
1625 log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
1626 return -1;
1628 /* From now on, we use 'written' to remember the current length of 's'. */
1629 written = result;
1631 if (options->ContactInfo && strlen(options->ContactInfo)) {
1632 const char *ci = options->ContactInfo;
1633 if (strchr(ci, '\n') || strchr(ci, '\r'))
1634 ci = escaped(ci);
1635 result = tor_snprintf(s+written,maxlen-written, "contact %s\n", ci);
1636 if (result<0) {
1637 log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
1638 return -1;
1640 written += result;
1643 /* Write the exit policy to the end of 's'. */
1644 if (dns_seems_to_be_broken()) {
1645 /* DNS is screwed up; don't claim to be an exit. */
1646 strlcat(s+written, "reject *:*\n", maxlen-written);
1647 written += strlen("reject *:*\n");
1648 tmpe = NULL;
1649 } else if (router->exit_policy) {
1650 int i;
1651 for (i = 0; i < smartlist_len(router->exit_policy); ++i) {
1652 tmpe = smartlist_get(router->exit_policy, i);
1653 result = policy_write_item(s+written, maxlen-written, tmpe);
1654 if (result < 0) {
1655 log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
1656 return -1;
1658 tor_assert(result == (int)strlen(s+written));
1659 written += result;
1660 if (written+2 > maxlen) {
1661 log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
1662 return -1;
1664 s[written++] = '\n';
1668 if (written+256 > maxlen) { /* Not enough room for signature. */
1669 log_warn(LD_BUG,"not enough room left in descriptor for signature!");
1670 return -1;
1673 /* Sign the directory */
1674 strlcpy(s+written, "router-signature\n", maxlen-written);
1675 written += strlen(s+written);
1676 s[written] = '\0';
1677 if (router_get_router_hash(s, digest) < 0) {
1678 return -1;
1681 note_crypto_pk_op(SIGN_RTR);
1682 if (router_append_dirobj_signature(s+written,maxlen-written,
1683 digest,ident_key)<0) {
1684 log_warn(LD_BUG, "Couldn't sign router descriptor");
1685 return -1;
1687 written += strlen(s+written);
1689 if (written+2 > maxlen) {
1690 log_warn(LD_BUG,"Not enough room to finish descriptor.");
1691 return -1;
1693 /* include a last '\n' */
1694 s[written] = '\n';
1695 s[written+1] = 0;
1697 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1699 char *s_dup;
1700 const char *cp;
1701 routerinfo_t *ri_tmp;
1702 cp = s_dup = tor_strdup(s);
1703 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
1704 if (!ri_tmp) {
1705 log_err(LD_BUG,
1706 "We just generated a router descriptor we can't parse.");
1707 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1708 return -1;
1710 tor_free(s_dup);
1711 routerinfo_free(ri_tmp);
1713 #endif
1715 return written+1;
1718 /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
1719 * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
1720 * negative on failure. */
1722 extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
1723 crypto_pk_env_t *ident_key)
1725 or_options_t *options = get_options();
1726 char identity[HEX_DIGEST_LEN+1];
1727 char published[ISO_TIME_LEN+1];
1728 char digest[DIGEST_LEN];
1729 char *bandwidth_usage;
1730 int result;
1731 size_t len;
1733 base16_encode(identity, sizeof(identity),
1734 extrainfo->cache_info.identity_digest, DIGEST_LEN);
1735 format_iso_time(published, extrainfo->cache_info.published_on);
1736 bandwidth_usage = rep_hist_get_bandwidth_lines(1);
1738 result = tor_snprintf(s, maxlen,
1739 "extra-info %s %s\n"
1740 "published %s\n%s",
1741 extrainfo->nickname, identity,
1742 published, bandwidth_usage);
1743 tor_free(bandwidth_usage);
1744 if (result<0)
1745 return -1;
1747 if (options->BridgeRelay && options->BridgeRecordUsageByCountry) {
1748 char *geoip_summary = geoip_get_client_history(time(NULL));
1749 if (geoip_summary) {
1750 char geoip_start[ISO_TIME_LEN+1];
1751 format_iso_time(geoip_start, geoip_get_history_start());
1752 result = tor_snprintf(s+strlen(s), maxlen-strlen(s),
1753 "geoip-start-time %s\n"
1754 "geoip-client-origins %s\n",
1755 geoip_start, geoip_summary);
1756 tor_free(geoip_summary);
1757 if (result<0)
1758 return -1;
1762 len = strlen(s);
1763 strlcat(s+len, "router-signature\n", maxlen-len);
1764 len += strlen(s+len);
1765 if (router_get_extrainfo_hash(s, digest)<0)
1766 return -1;
1767 if (router_append_dirobj_signature(s+len, maxlen-len, digest, ident_key)<0)
1768 return -1;
1770 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1772 char *cp, *s_dup;
1773 extrainfo_t *ei_tmp;
1774 cp = s_dup = tor_strdup(s);
1775 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
1776 if (!ei_tmp) {
1777 log_err(LD_BUG,
1778 "We just generated an extrainfo descriptor we can't parse.");
1779 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1780 return -1;
1782 tor_free(s_dup);
1783 extrainfo_free(ei_tmp);
1785 #endif
1787 return strlen(s)+1;
1790 /** Return true iff <b>s</b> is a legally valid server nickname. */
1792 is_legal_nickname(const char *s)
1794 size_t len;
1795 tor_assert(s);
1796 len = strlen(s);
1797 return len > 0 && len <= MAX_NICKNAME_LEN &&
1798 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
1801 /** Return true iff <b>s</b> is a legally valid server nickname or
1802 * hex-encoded identity-key digest. */
1804 is_legal_nickname_or_hexdigest(const char *s)
1806 if (*s!='$')
1807 return is_legal_nickname(s);
1808 else
1809 return is_legal_hexdigest(s);
1812 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
1813 * digest. */
1815 is_legal_hexdigest(const char *s)
1817 size_t len;
1818 tor_assert(s);
1819 if (s[0] == '$') s++;
1820 len = strlen(s);
1821 if (len > HEX_DIGEST_LEN) {
1822 if (s[HEX_DIGEST_LEN] == '=' ||
1823 s[HEX_DIGEST_LEN] == '~') {
1824 if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
1825 return 0;
1826 } else {
1827 return 0;
1830 return (len >= HEX_DIGEST_LEN &&
1831 strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
1834 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
1835 * verbose representation of the identity of <b>router</b>. The format is:
1836 * A dollar sign.
1837 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
1838 * A "=" if the router is named; a "~" if it is not.
1839 * The router's nickname.
1841 void
1842 router_get_verbose_nickname(char *buf, routerinfo_t *router)
1844 buf[0] = '$';
1845 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
1846 DIGEST_LEN);
1847 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
1848 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
1851 /** Forget that we have issued any router-related warnings, so that we'll
1852 * warn again if we see the same errors. */
1853 void
1854 router_reset_warnings(void)
1856 if (warned_nonexistent_family) {
1857 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1858 smartlist_clear(warned_nonexistent_family);
1862 /** Given a router purpose, convert it to a string. Don't call this on
1863 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
1864 * know its string representation. */
1865 const char *
1866 router_purpose_to_string(uint8_t p)
1868 switch (p)
1870 case ROUTER_PURPOSE_GENERAL: return "general";
1871 case ROUTER_PURPOSE_BRIDGE: return "bridge";
1872 case ROUTER_PURPOSE_CONTROLLER: return "controller";
1873 default:
1874 tor_assert(0);
1876 return NULL;
1879 /** Given a string, convert it to a router purpose. */
1880 uint8_t
1881 router_purpose_from_string(const char *s)
1883 if (!strcmp(s, "general"))
1884 return ROUTER_PURPOSE_GENERAL;
1885 else if (!strcmp(s, "bridge"))
1886 return ROUTER_PURPOSE_BRIDGE;
1887 else if (!strcmp(s, "controller"))
1888 return ROUTER_PURPOSE_CONTROLLER;
1889 else
1890 return ROUTER_PURPOSE_UNKNOWN;
1893 /** Release all static resources held in router.c */
1894 void
1895 router_free_all(void)
1897 if (onionkey)
1898 crypto_free_pk_env(onionkey);
1899 if (lastonionkey)
1900 crypto_free_pk_env(lastonionkey);
1901 if (identitykey)
1902 crypto_free_pk_env(identitykey);
1903 if (key_lock)
1904 tor_mutex_free(key_lock);
1905 if (desc_routerinfo)
1906 routerinfo_free(desc_routerinfo);
1907 if (desc_extrainfo)
1908 extrainfo_free(desc_extrainfo);
1909 if (authority_signing_key)
1910 crypto_free_pk_env(authority_signing_key);
1911 if (authority_key_certificate)
1912 authority_cert_free(authority_key_certificate);
1914 if (warned_nonexistent_family) {
1915 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1916 smartlist_free(warned_nonexistent_family);