<weasel> tortls.c: In function `tor_tls_client_is_using_v2_ciphers':
[tor.git] / src / or / router.c
blob2a2493998d031e3d447bf328d7b60a2f42586891
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2008, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 /* $Id$ */
7 const char router_c_id[] =
8 "$Id$";
10 #define ROUTER_PRIVATE
12 #include "or.h"
14 /**
15 * \file router.c
16 * \brief OR functionality, including key maintenance, generating
17 * and uploading server descriptors, retrying OR connections.
18 **/
20 extern long stats_n_seconds_working;
22 /************************************************************/
24 /*****
25 * Key management: ORs only.
26 *****/
28 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
30 static tor_mutex_t *key_lock=NULL;
31 static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
32 /** Current private onionskin decryption key: used to decode CREATE cells. */
33 static crypto_pk_env_t *onionkey=NULL;
34 /** Previous private onionskin decription key: used to decode CREATE cells
35 * generated by clients that have an older version of our descriptor. */
36 static crypto_pk_env_t *lastonionkey=NULL;
37 /** Private "identity key": used to sign directory info and TLS
38 * certificates. Never changes. */
39 static crypto_pk_env_t *identitykey=NULL;
40 /** Digest of identitykey. */
41 static char identitykey_digest[DIGEST_LEN];
42 /** Signing key used for v3 directory material; only set for authorities. */
43 static crypto_pk_env_t *authority_signing_key = NULL;
44 /** Key certificate to authenticate v3 directory material; only set for
45 * authorities. */
46 static authority_cert_t *authority_key_certificate = NULL;
48 /* (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 static int
265 init_v3_authority_keys(void)
267 char *fname = NULL, *cert = NULL;
268 const char *eos = NULL;
269 crypto_pk_env_t *signing_key = NULL;
270 authority_cert_t *parsed = NULL;
271 int r = -1;
273 fname = get_datadir_fname2("keys", "authority_signing_key");
274 signing_key = init_key_from_file(fname, 0, LOG_INFO);
275 if (!signing_key) {
276 log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
277 goto done;
279 tor_free(fname);
280 fname = get_datadir_fname2("keys", "authority_certificate");
281 cert = read_file_to_str(fname, 0, NULL);
282 if (!cert) {
283 log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
284 fname);
285 goto done;
287 parsed = authority_cert_parse_from_string(cert, &eos);
288 if (!parsed) {
289 log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
290 goto done;
292 if (crypto_pk_cmp_keys(signing_key, parsed->signing_key) != 0) {
293 log_warn(LD_DIR, "Stored signing key does not match signing key in "
294 "certificate");
295 goto done;
297 parsed->cache_info.signed_descriptor_body = cert;
298 parsed->cache_info.signed_descriptor_len = eos-cert;
299 cert = NULL;
301 /* Free old values... */
302 if (authority_key_certificate)
303 authority_cert_free(authority_key_certificate);
304 if (authority_signing_key)
305 crypto_free_pk_env(authority_signing_key);
306 /* ...and replace them. */
307 authority_key_certificate = parsed;
308 authority_signing_key = signing_key;
309 parsed = NULL;
310 signing_key = NULL;
312 r = 0;
313 done:
314 tor_free(fname);
315 tor_free(cert);
316 if (signing_key)
317 crypto_free_pk_env(signing_key);
318 if (parsed)
319 authority_cert_free(parsed);
320 return r;
323 /** If we're a v3 authority, check whether we have a certificate that's
324 * likely to expire soon. Warn if we do, but not too often. */
325 void
326 v3_authority_check_key_expiry(void)
328 time_t now, expires;
329 static time_t last_warned = 0;
330 int badness, time_left, warn_interval;
331 if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
332 return;
334 now = time(NULL);
335 expires = authority_key_certificate->expires;
336 time_left = (int)( expires - now );
337 if (time_left <= 0) {
338 badness = LOG_ERR;
339 warn_interval = 60*60;
340 } else if (time_left <= 24*60*60) {
341 badness = LOG_WARN;
342 warn_interval = 60*60;
343 } else if (time_left <= 24*60*60*7) {
344 badness = LOG_WARN;
345 warn_interval = 24*60*60;
346 } else if (time_left <= 24*60*60*30) {
347 badness = LOG_WARN;
348 warn_interval = 24*60*60*5;
349 } else {
350 return;
353 if (last_warned + warn_interval > now)
354 return;
356 if (time_left <= 0) {
357 log(badness, LD_DIR, "Your v3 authority certificate has expired."
358 " Generate a new one NOW.");
359 } else if (time_left <= 24*60*60) {
360 log(badness, LD_DIR, "Your v3 authority certificate expires in %d hours;"
361 " Generate a new one NOW.", time_left/(60*60));
362 } else {
363 log(badness, LD_DIR, "Your v3 authority certificate expires in %d days;"
364 " Generate a new one soon.", time_left/(24*60*60));
366 last_warned = now;
369 /** Initialize all OR private keys, and the TLS context, as necessary.
370 * On OPs, this only initializes the tls context. Return 0 on success,
371 * or -1 if Tor should die.
374 init_keys(void)
376 char *keydir;
377 char fingerprint[FINGERPRINT_LEN+1];
378 /*nickname<space>fp\n\0 */
379 char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
380 const char *mydesc;
381 crypto_pk_env_t *prkey;
382 char digest[20];
383 char v3_digest[20];
384 char *cp;
385 or_options_t *options = get_options();
386 authority_type_t type;
387 time_t now = time(NULL);
388 trusted_dir_server_t *ds;
389 int v3_digest_set = 0;
390 authority_cert_t *cert = NULL;
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(), 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 cert = get_my_v3_authority_cert();
434 if (cert) {
435 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
436 v3_digest);
437 v3_digest_set = 1;
441 /* 1. Read identity key. Make it if none is found. */
442 keydir = get_datadir_fname2("keys", "secret_id_key");
443 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
444 prkey = init_key_from_file(keydir, 1, LOG_ERR);
445 tor_free(keydir);
446 if (!prkey) return -1;
447 set_identity_key(prkey);
449 /* 2. Read onion key. Make it if none is found. */
450 keydir = get_datadir_fname2("keys", "secret_onion_key");
451 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
452 prkey = init_key_from_file(keydir, 1, LOG_ERR);
453 tor_free(keydir);
454 if (!prkey) return -1;
455 set_onion_key(prkey);
456 if (options->command == CMD_RUN_TOR) {
457 /* only mess with the state file if we're actually running Tor */
458 or_state_t *state = get_or_state();
459 if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
460 /* We allow for some parsing slop, but we don't want to risk accepting
461 * values in the distant future. If we did, we might never rotate the
462 * onion key. */
463 onionkey_set_at = state->LastRotatedOnionKey;
464 } else {
465 /* We have no LastRotatedOnionKey set; either we just created the key
466 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
467 * start the clock ticking now so that we will eventually rotate it even
468 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
469 state->LastRotatedOnionKey = onionkey_set_at = now;
470 or_state_mark_dirty(state, options->AvoidDiskWrites ?
471 time(NULL)+3600 : 0);
475 keydir = get_datadir_fname2("keys", "secret_onion_key.old");
476 if (!lastonionkey && file_status(keydir) == FN_FILE) {
477 prkey = init_key_from_file(keydir, 1, LOG_ERR);
478 if (prkey)
479 lastonionkey = prkey;
481 tor_free(keydir);
483 /* 3. Initialize link key and TLS context. */
484 if (tor_tls_context_new(get_identity_key(), 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 ds = router_get_trusteddirserver_by_digest(digest);
561 if (!ds) {
562 ds = add_trusted_dir_server(options->Nickname, NULL,
563 (uint16_t)options->DirPort,
564 (uint16_t)options->ORPort,
565 digest,
566 v3_digest,
567 type);
568 if (!ds) {
569 log_err(LD_GENERAL,"We want to be a directory authority, but we "
570 "couldn't add ourselves to the authority list. Failing.");
571 return -1;
574 if (ds->type != type) {
575 log_warn(LD_DIR, "Configured authority type does not match authority "
576 "type in DirServer list. Adjusting. (%d v %d)",
577 type, ds->type);
578 ds->type = type;
580 if (v3_digest_set && (ds->type & V3_AUTHORITY) &&
581 memcmp(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
582 log_warn(LD_DIR, "V3 identity key does not match identity declared in "
583 "DirServer line. Adjusting.");
584 memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
587 if (cert) { /* add my own cert to the list of known certs */
588 log_info(LD_DIR, "adding my own v3 cert");
589 if (trusted_dirs_load_certs_from_string(
590 cert->cache_info.signed_descriptor_body, 0, 0)<0) {
591 log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
592 return -1;
596 return 0; /* success */
599 /* Keep track of whether we should upload our server descriptor,
600 * and what type of server we are.
603 /** Whether we can reach our ORPort from the outside. */
604 static int can_reach_or_port = 0;
605 /** Whether we can reach our DirPort from the outside. */
606 static int can_reach_dir_port = 0;
608 /** Forget what we have learned about our reachability status. */
609 void
610 router_reset_reachability(void)
612 can_reach_or_port = can_reach_dir_port = 0;
615 /** Return 1 if ORPort is known reachable; else return 0. */
617 check_whether_orport_reachable(void)
619 or_options_t *options = get_options();
620 return options->AssumeReachable ||
621 can_reach_or_port;
624 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
626 check_whether_dirport_reachable(void)
628 or_options_t *options = get_options();
629 return !options->DirPort ||
630 options->AssumeReachable ||
631 we_are_hibernating() ||
632 can_reach_dir_port;
635 /** Look at a variety of factors, and return 0 if we don't want to
636 * advertise the fact that we have a DirPort open. Else return the
637 * DirPort we want to advertise.
639 * Log a helpful message if we change our mind about whether to publish
640 * a DirPort.
642 static int
643 decide_to_advertise_dirport(or_options_t *options, uint16_t dir_port)
645 static int advertising=1; /* start out assuming we will advertise */
646 int new_choice=1;
647 const char *reason = NULL;
649 /* Section one: reasons to publish or not publish that aren't
650 * worth mentioning to the user, either because they're obvious
651 * or because they're normal behavior. */
653 if (!dir_port) /* short circuit the rest of the function */
654 return 0;
655 if (authdir_mode(options)) /* always publish */
656 return dir_port;
657 if (we_are_hibernating())
658 return 0;
659 if (!check_whether_dirport_reachable())
660 return 0;
662 /* Section two: reasons to publish or not publish that the user
663 * might find surprising. These are generally config options that
664 * make us choose not to publish. */
666 if (accounting_is_enabled(options)) {
667 /* if we might potentially hibernate */
668 new_choice = 0;
669 reason = "AccountingMax enabled";
670 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
671 } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
672 (options->RelayBandwidthRate > 0 &&
673 options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
674 /* if we're advertising a small amount */
675 new_choice = 0;
676 reason = "BandwidthRate under 50KB";
679 if (advertising != new_choice) {
680 if (new_choice == 1) {
681 log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
682 } else {
683 tor_assert(reason);
684 log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
686 advertising = new_choice;
689 return advertising ? dir_port : 0;
692 /** Some time has passed, or we just got new directory information.
693 * See if we currently believe our ORPort or DirPort to be
694 * unreachable. If so, launch a new test for it.
696 * For ORPort, we simply try making a circuit that ends at ourselves.
697 * Success is noticed in onionskin_answer().
699 * For DirPort, we make a connection via Tor to our DirPort and ask
700 * for our own server descriptor.
701 * Success is noticed in connection_dir_client_reached_eof().
703 void
704 consider_testing_reachability(int test_or, int test_dir)
706 routerinfo_t *me = router_get_my_routerinfo();
707 int orport_reachable = check_whether_orport_reachable();
708 if (!me)
709 return;
711 if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
712 log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
713 !orport_reachable ? "reachability" : "bandwidth",
714 me->address, me->or_port);
715 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me,
716 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
717 control_event_server_status(LOG_NOTICE,
718 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
719 me->address, me->or_port);
722 if (test_dir && !check_whether_dirport_reachable() &&
723 !connection_get_by_type_addr_port_purpose(
724 CONN_TYPE_DIR, me->addr, me->dir_port,
725 DIR_PURPOSE_FETCH_SERVERDESC)) {
726 /* ask myself, via tor, for my server descriptor. */
727 directory_initiate_command(me->address, me->addr,
728 me->or_port, me->dir_port,
729 0, me->cache_info.identity_digest,
730 DIR_PURPOSE_FETCH_SERVERDESC,
731 ROUTER_PURPOSE_GENERAL,
732 1, "authority.z", NULL, 0, 0);
734 control_event_server_status(LOG_NOTICE,
735 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
736 me->address, me->dir_port);
740 /** Annotate that we found our ORPort reachable. */
741 void
742 router_orport_found_reachable(void)
744 if (!can_reach_or_port) {
745 routerinfo_t *me = router_get_my_routerinfo();
746 log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
747 "the outside. Excellent.%s",
748 get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
749 " Publishing server descriptor." : "");
750 can_reach_or_port = 1;
751 mark_my_descriptor_dirty();
752 if (!me)
753 return;
754 control_event_server_status(LOG_NOTICE,
755 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
756 me->address, me->or_port);
760 /** Annotate that we found our DirPort reachable. */
761 void
762 router_dirport_found_reachable(void)
764 if (!can_reach_dir_port) {
765 routerinfo_t *me = router_get_my_routerinfo();
766 log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
767 "from the outside. Excellent.");
768 can_reach_dir_port = 1;
769 if (!me || decide_to_advertise_dirport(get_options(), me->dir_port))
770 mark_my_descriptor_dirty();
771 if (!me)
772 return;
773 control_event_server_status(LOG_NOTICE,
774 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
775 me->address, me->dir_port);
779 /** We have enough testing circuits open. Send a bunch of "drop"
780 * cells down each of them, to exercise our bandwidth. */
781 void
782 router_perform_bandwidth_test(int num_circs, time_t now)
784 int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
785 int max_cells = num_cells < CIRCWINDOW_START ?
786 num_cells : CIRCWINDOW_START;
787 int cells_per_circuit = max_cells / num_circs;
788 origin_circuit_t *circ = NULL;
790 log_notice(LD_OR,"Performing bandwidth self-test...done.");
791 while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
792 CIRCUIT_PURPOSE_TESTING))) {
793 /* dump cells_per_circuit drop cells onto this circ */
794 int i = cells_per_circuit;
795 if (circ->_base.state != CIRCUIT_STATE_OPEN)
796 continue;
797 circ->_base.timestamp_dirty = now;
798 while (i-- > 0) {
799 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
800 RELAY_COMMAND_DROP,
801 NULL, 0, circ->cpath->prev)<0) {
802 return; /* stop if error */
808 /** Return true iff we believe ourselves to be an authoritative
809 * directory server.
812 authdir_mode(or_options_t *options)
814 return options->AuthoritativeDir != 0;
816 /** Return true iff we believe ourselves to be a v1 authoritative
817 * directory server.
820 authdir_mode_v1(or_options_t *options)
822 return authdir_mode(options) && options->V1AuthoritativeDir != 0;
824 /** Return true iff we believe ourselves to be a v2 authoritative
825 * directory server.
828 authdir_mode_v2(or_options_t *options)
830 return authdir_mode(options) && options->V2AuthoritativeDir != 0;
832 /** Return true iff we believe ourselves to be a v3 authoritative
833 * directory server.
836 authdir_mode_v3(or_options_t *options)
838 return authdir_mode(options) && options->V3AuthoritativeDir != 0;
840 /** Return true iff we are a v1, v2, or v3 directory authority. */
842 authdir_mode_any_main(or_options_t *options)
844 return options->V1AuthoritativeDir ||
845 options->V2AuthoritativeDir ||
846 options->V3AuthoritativeDir;
848 /** Return true if we believe ourselves to be any kind of
849 * authoritative directory beyond just a hidserv authority. */
851 authdir_mode_any_nonhidserv(or_options_t *options)
853 return options->BridgeAuthoritativeDir ||
854 authdir_mode_any_main(options);
856 /** Return true iff we are an authoritative directory server that is
857 * authoritative about receiving and serving descriptors of type
858 * <b>purpose</b> its dirport. Use -1 for "any purpose". */
860 authdir_mode_handles_descs(or_options_t *options, int purpose)
862 if (purpose < 0)
863 return authdir_mode_any_nonhidserv(options);
864 else if (purpose == ROUTER_PURPOSE_GENERAL)
865 return authdir_mode_any_main(options);
866 else if (purpose == ROUTER_PURPOSE_BRIDGE)
867 return (options->BridgeAuthoritativeDir);
868 else
869 return 0;
871 /** Return true iff we are an authoritative directory server that
872 * publishes its own network statuses.
875 authdir_mode_publishes_statuses(or_options_t *options)
877 if (authdir_mode_bridge(options))
878 return 0;
879 return authdir_mode_any_nonhidserv(options);
881 /** Return true iff we are an authoritative directory server that
882 * tests reachability of the descriptors it learns about.
885 authdir_mode_tests_reachability(or_options_t *options)
887 return authdir_mode_handles_descs(options, -1);
889 /** Return true iff we believe ourselves to be a bridge authoritative
890 * directory server.
893 authdir_mode_bridge(or_options_t *options)
895 return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
897 /** Return true iff we once tried to stay connected to all ORs at once.
898 * FFFF this function, and the notion of staying connected to ORs, is
899 * nearly obsolete. One day there will be a proposal for getting rid of
900 * it.
903 clique_mode(or_options_t *options)
905 return authdir_mode_tests_reachability(options);
908 /** Return true iff we are trying to be a server.
911 server_mode(or_options_t *options)
913 if (options->ClientOnly) return 0;
914 return (options->ORPort != 0 || options->ORListenAddress);
917 /** Remember if we've advertised ourselves to the dirservers. */
918 static int server_is_advertised=0;
920 /** Return true iff we have published our descriptor lately.
923 advertised_server_mode(void)
925 return server_is_advertised;
929 * Called with a boolean: set whether we have recently published our
930 * descriptor.
932 static void
933 set_server_advertised(int s)
935 server_is_advertised = s;
938 /** Return true iff we are trying to be a socks proxy. */
940 proxy_mode(or_options_t *options)
942 return (options->SocksPort != 0 || options->SocksListenAddress ||
943 options->TransPort != 0 || options->TransListenAddress ||
944 options->NatdPort != 0 || options->NatdListenAddress ||
945 options->DNSPort != 0 || options->DNSListenAddress);
948 /** Decide if we're a publishable server. We are a publishable server if:
949 * - We don't have the ClientOnly option set
950 * and
951 * - We have the PublishServerDescriptor option set to non-empty
952 * and
953 * - We have ORPort set
954 * and
955 * - We believe we are reachable from the outside; or
956 * - We are an authoritative directory server.
958 static int
959 decide_if_publishable_server(void)
961 or_options_t *options = get_options();
963 if (options->ClientOnly)
964 return 0;
965 if (options->_PublishServerDescriptor == NO_AUTHORITY)
966 return 0;
967 if (!server_mode(options))
968 return 0;
969 if (authdir_mode(options))
970 return 1;
972 return check_whether_orport_reachable();
975 /** Initiate server descriptor upload as reasonable (if server is publishable,
976 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
978 * We need to rebuild the descriptor if it's dirty even if we're not
979 * uploading, because our reachability testing *uses* our descriptor to
980 * determine what IP address and ports to test.
982 void
983 consider_publishable_server(int force)
985 int rebuilt;
987 if (!server_mode(get_options()))
988 return;
990 rebuilt = router_rebuild_descriptor(0);
991 if (decide_if_publishable_server()) {
992 set_server_advertised(1);
993 if (rebuilt == 0)
994 router_upload_dir_desc_to_dirservers(force);
995 } else {
996 set_server_advertised(0);
1001 * Clique maintenance -- to be phased out.
1004 /** Return true iff we believe this OR tries to keep connections open
1005 * to all other ORs. */
1007 router_is_clique_mode(routerinfo_t *router)
1009 if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
1010 return 1;
1011 return 0;
1015 * OR descriptor generation.
1018 /** My routerinfo. */
1019 static routerinfo_t *desc_routerinfo = NULL;
1020 /** My extrainfo */
1021 static extrainfo_t *desc_extrainfo = NULL;
1022 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1023 * now. */
1024 static time_t desc_clean_since = 0;
1025 /** Boolean: do we need to regenerate the above? */
1026 static int desc_needs_upload = 0;
1028 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1029 * descriptor successfully yet, try to upload our signed descriptor to
1030 * all the directory servers we know about.
1032 void
1033 router_upload_dir_desc_to_dirservers(int force)
1035 routerinfo_t *ri;
1036 extrainfo_t *ei;
1037 char *msg;
1038 size_t desc_len, extra_len = 0, total_len;
1039 authority_type_t auth = get_options()->_PublishServerDescriptor;
1041 ri = router_get_my_routerinfo();
1042 if (!ri) {
1043 log_info(LD_GENERAL, "No descriptor; skipping upload");
1044 return;
1046 ei = router_get_my_extrainfo();
1047 if (auth == NO_AUTHORITY)
1048 return;
1049 if (!force && !desc_needs_upload)
1050 return;
1051 desc_needs_upload = 0;
1053 desc_len = ri->cache_info.signed_descriptor_len;
1054 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1055 total_len = desc_len + extra_len + 1;
1056 msg = tor_malloc(total_len);
1057 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1058 if (ei) {
1059 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1061 msg[desc_len+extra_len] = 0;
1063 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
1064 (auth & BRIDGE_AUTHORITY) ?
1065 ROUTER_PURPOSE_BRIDGE :
1066 ROUTER_PURPOSE_GENERAL,
1067 auth, msg, desc_len, extra_len);
1068 tor_free(msg);
1071 /** OR only: Check whether my exit policy says to allow connection to
1072 * conn. Return 0 if we accept; non-0 if we reject.
1075 router_compare_to_my_exit_policy(edge_connection_t *conn)
1077 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1078 return -1;
1080 /* make sure it's resolved to something. this way we can't get a
1081 'maybe' below. */
1082 if (!conn->_base.addr)
1083 return -1;
1085 return compare_addr_to_addr_policy(conn->_base.addr, conn->_base.port,
1086 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
1089 /** Return true iff I'm a server and <b>digest</b> is equal to
1090 * my identity digest. */
1092 router_digest_is_me(const char *digest)
1094 return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
1097 /** A wrapper around router_digest_is_me(). */
1099 router_is_me(routerinfo_t *router)
1101 return router_digest_is_me(router->cache_info.identity_digest);
1104 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1106 router_fingerprint_is_me(const char *fp)
1108 char digest[DIGEST_LEN];
1109 if (strlen(fp) == HEX_DIGEST_LEN &&
1110 base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
1111 return router_digest_is_me(digest);
1113 return 0;
1116 /** Return a routerinfo for this OR, rebuilding a fresh one if
1117 * necessary. Return NULL on error, or if called on an OP. */
1118 routerinfo_t *
1119 router_get_my_routerinfo(void)
1121 if (!server_mode(get_options()))
1122 return NULL;
1123 if (router_rebuild_descriptor(0))
1124 return NULL;
1125 return desc_routerinfo;
1128 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1129 * one if necessary. Return NULL on error.
1131 const char *
1132 router_get_my_descriptor(void)
1134 const char *body;
1135 if (!router_get_my_routerinfo())
1136 return NULL;
1137 /* Make sure this is nul-terminated. */
1138 tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
1139 body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
1140 tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
1141 log_debug(LD_GENERAL,"my desc is '%s'", body);
1142 return body;
1145 /* Return the extrainfo document for this OR, or NULL if we have none.
1146 * Rebuilt it (and the server descriptor) if necessary. */
1147 extrainfo_t *
1148 router_get_my_extrainfo(void)
1150 if (!server_mode(get_options()))
1151 return NULL;
1152 if (router_rebuild_descriptor(0))
1153 return NULL;
1154 return desc_extrainfo;
1157 /** A list of nicknames that we've warned about including in our family
1158 * declaration verbatim rather than as digests. */
1159 static smartlist_t *warned_nonexistent_family = NULL;
1161 static int router_guess_address_from_dir_headers(uint32_t *guess);
1163 /** Make a current best guess at our address, either because
1164 * it's configured in torrc, or because we've learned it from
1165 * dirserver headers. Place the answer in *<b>addr</b> and return
1166 * 0 on success, else return -1 if we have no guess. */
1168 router_pick_published_address(or_options_t *options, uint32_t *addr)
1170 if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
1171 log_info(LD_CONFIG, "Could not determine our address locally. "
1172 "Checking if directory headers provide any hints.");
1173 if (router_guess_address_from_dir_headers(addr) < 0) {
1174 log_info(LD_CONFIG, "No hints from directory headers either. "
1175 "Will try again later.");
1176 return -1;
1179 return 0;
1182 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1183 * routerinfo, signed server descriptor, and extra-info document for this OR.
1184 * Return 0 on success, -1 on temporary error.
1187 router_rebuild_descriptor(int force)
1189 routerinfo_t *ri;
1190 extrainfo_t *ei;
1191 uint32_t addr;
1192 char platform[256];
1193 int hibernating = we_are_hibernating();
1194 or_options_t *options = get_options();
1196 if (desc_clean_since && !force)
1197 return 0;
1199 if (router_pick_published_address(options, &addr) < 0) {
1200 /* Stop trying to rebuild our descriptor every second. We'll
1201 * learn that it's time to try again when server_has_changed_ip()
1202 * marks it dirty. */
1203 desc_clean_since = time(NULL);
1204 return -1;
1207 ri = tor_malloc_zero(sizeof(routerinfo_t));
1208 ri->cache_info.routerlist_index = -1;
1209 ri->address = tor_dup_addr(addr);
1210 ri->nickname = tor_strdup(options->Nickname);
1211 ri->addr = addr;
1212 ri->or_port = options->ORPort;
1213 ri->dir_port = options->DirPort;
1214 ri->cache_info.published_on = time(NULL);
1215 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
1216 * main thread */
1217 ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
1218 if (crypto_pk_get_digest(ri->identity_pkey,
1219 ri->cache_info.identity_digest)<0) {
1220 routerinfo_free(ri);
1221 return -1;
1223 get_platform_str(platform, sizeof(platform));
1224 ri->platform = tor_strdup(platform);
1226 /* compute ri->bandwidthrate as the min of various options */
1227 ri->bandwidthrate = (int)options->BandwidthRate;
1228 if (ri->bandwidthrate > options->MaxAdvertisedBandwidth)
1229 ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
1230 if (options->RelayBandwidthRate > 0 &&
1231 ri->bandwidthrate > options->RelayBandwidthRate)
1232 ri->bandwidthrate = (int)options->RelayBandwidthRate;
1234 /* and compute ri->bandwidthburst similarly */
1235 ri->bandwidthburst = (int)options->BandwidthBurst;
1236 if (options->RelayBandwidthBurst > 0 &&
1237 ri->bandwidthburst > options->RelayBandwidthBurst)
1238 ri->bandwidthburst = (int)options->RelayBandwidthBurst;
1240 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
1242 policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
1243 options->ExitPolicyRejectPrivate,
1244 ri->address);
1246 if (desc_routerinfo) { /* inherit values */
1247 ri->is_valid = desc_routerinfo->is_valid;
1248 ri->is_running = desc_routerinfo->is_running;
1249 ri->is_named = desc_routerinfo->is_named;
1251 if (authdir_mode(options))
1252 ri->is_valid = ri->is_named = 1; /* believe in yourself */
1253 if (options->MyFamily) {
1254 smartlist_t *family;
1255 if (!warned_nonexistent_family)
1256 warned_nonexistent_family = smartlist_create();
1257 family = smartlist_create();
1258 ri->declared_family = smartlist_create();
1259 smartlist_split_string(family, options->MyFamily, ",",
1260 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1261 SMARTLIST_FOREACH(family, char *, name,
1263 routerinfo_t *member;
1264 if (!strcasecmp(name, options->Nickname))
1265 member = ri;
1266 else
1267 member = router_get_by_nickname(name, 1);
1268 if (!member) {
1269 int is_legal = is_legal_nickname_or_hexdigest(name);
1270 if (!smartlist_string_isin(warned_nonexistent_family, name) &&
1271 !is_legal_hexdigest(name)) {
1272 if (is_legal)
1273 log_warn(LD_CONFIG,
1274 "I have no descriptor for the router named \"%s\" in my "
1275 "declared family; I'll use the nickname as is, but "
1276 "this may confuse clients.", name);
1277 else
1278 log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
1279 "declared family, but that isn't a legal nickname. "
1280 "Skipping it.", escaped(name));
1281 smartlist_add(warned_nonexistent_family, tor_strdup(name));
1283 if (is_legal) {
1284 smartlist_add(ri->declared_family, name);
1285 name = NULL;
1287 } else if (router_is_me(member)) {
1288 /* Don't list ourself in our own family; that's redundant */
1289 } else {
1290 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1291 fp[0] = '$';
1292 base16_encode(fp+1,HEX_DIGEST_LEN+1,
1293 member->cache_info.identity_digest, DIGEST_LEN);
1294 smartlist_add(ri->declared_family, fp);
1295 if (smartlist_string_isin(warned_nonexistent_family, name))
1296 smartlist_string_remove(warned_nonexistent_family, name);
1298 tor_free(name);
1301 /* remove duplicates from the list */
1302 smartlist_sort_strings(ri->declared_family);
1303 smartlist_uniq_strings(ri->declared_family);
1305 smartlist_free(family);
1308 /* Now generate the extrainfo. */
1309 ei = tor_malloc_zero(sizeof(extrainfo_t));
1310 ei->cache_info.is_extrainfo = 1;
1311 strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
1312 ei->cache_info.published_on = ri->cache_info.published_on;
1313 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
1314 DIGEST_LEN);
1315 ei->cache_info.signed_descriptor_body = tor_malloc(8192);
1316 if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body, 8192,
1317 ei, get_identity_key()) < 0) {
1318 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
1319 extrainfo_free(ei);
1320 return -1;
1322 ei->cache_info.signed_descriptor_len =
1323 strlen(ei->cache_info.signed_descriptor_body);
1324 router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
1325 ei->cache_info.signed_descriptor_digest);
1327 /* Now finish the router descriptor. */
1328 memcpy(ri->cache_info.extra_info_digest,
1329 ei->cache_info.signed_descriptor_digest,
1330 DIGEST_LEN);
1331 ri->cache_info.signed_descriptor_body = tor_malloc(8192);
1332 if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
1333 ri, get_identity_key())<0) {
1334 log_warn(LD_BUG, "Couldn't generate router descriptor.");
1335 return -1;
1337 ri->cache_info.signed_descriptor_len =
1338 strlen(ri->cache_info.signed_descriptor_body);
1340 ri->purpose =
1341 options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
1342 if (!options->BridgeRelay) {
1343 ri->cache_info.send_unencrypted = 1;
1344 ei->cache_info.send_unencrypted = 1;
1347 router_get_router_hash(ri->cache_info.signed_descriptor_body,
1348 ri->cache_info.signed_descriptor_digest);
1350 tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
1352 if (desc_routerinfo)
1353 routerinfo_free(desc_routerinfo);
1354 desc_routerinfo = ri;
1355 if (desc_extrainfo)
1356 extrainfo_free(desc_extrainfo);
1357 desc_extrainfo = ei;
1359 desc_clean_since = time(NULL);
1360 desc_needs_upload = 1;
1361 control_event_my_descriptor_changed();
1362 return 0;
1365 /** Mark descriptor out of date if it's older than <b>when</b> */
1366 void
1367 mark_my_descriptor_dirty_if_older_than(time_t when)
1369 if (desc_clean_since < when)
1370 mark_my_descriptor_dirty();
1373 /** Call when the current descriptor is out of date. */
1374 void
1375 mark_my_descriptor_dirty(void)
1377 desc_clean_since = 0;
1380 /** How frequently will we republish our descriptor because of large (factor
1381 * of 2) shifts in estimated bandwidth? */
1382 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
1384 /** Check whether bandwidth has changed a lot since the last time we announced
1385 * bandwidth. If so, mark our descriptor dirty. */
1386 void
1387 check_descriptor_bandwidth_changed(time_t now)
1389 static time_t last_changed = 0;
1390 uint64_t prev, cur;
1391 if (!desc_routerinfo)
1392 return;
1394 prev = desc_routerinfo->bandwidthcapacity;
1395 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
1396 if ((prev != cur && (!prev || !cur)) ||
1397 cur > prev*2 ||
1398 cur < prev/2) {
1399 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
1400 log_info(LD_GENERAL,
1401 "Measured bandwidth has changed; rebuilding descriptor.");
1402 mark_my_descriptor_dirty();
1403 last_changed = now;
1408 /** Note at log level severity that our best guess of address has changed from
1409 * <b>prev</b> to <b>cur</b>. */
1410 static void
1411 log_addr_has_changed(int severity, uint32_t prev, uint32_t cur)
1413 char addrbuf_prev[INET_NTOA_BUF_LEN];
1414 char addrbuf_cur[INET_NTOA_BUF_LEN];
1415 struct in_addr in_prev;
1416 struct in_addr in_cur;
1418 in_prev.s_addr = htonl(prev);
1419 tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
1421 in_cur.s_addr = htonl(cur);
1422 tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
1424 if (prev)
1425 log_fn(severity, LD_GENERAL,
1426 "Our IP Address has changed from %s to %s; "
1427 "rebuilding descriptor.",
1428 addrbuf_prev, addrbuf_cur);
1429 else
1430 log_notice(LD_GENERAL,
1431 "Guessed our IP address as %s.",
1432 addrbuf_cur);
1435 /** Check whether our own address as defined by the Address configuration
1436 * has changed. This is for routers that get their address from a service
1437 * like dyndns. If our address has changed, mark our descriptor dirty. */
1438 void
1439 check_descriptor_ipaddress_changed(time_t now)
1441 uint32_t prev, cur;
1442 or_options_t *options = get_options();
1443 (void) now;
1445 if (!desc_routerinfo)
1446 return;
1448 prev = desc_routerinfo->addr;
1449 if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
1450 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
1451 return;
1454 if (prev != cur) {
1455 log_addr_has_changed(LOG_INFO, prev, cur);
1456 ip_address_changed(0);
1460 /** The most recently guessed value of our IP address, based on directory
1461 * headers. */
1462 static uint32_t last_guessed_ip = 0;
1464 /** A directory server <b>d_conn</b> told us our IP address is
1465 * <b>suggestion</b>.
1466 * If this address is different from the one we think we are now, and
1467 * if our computer doesn't actually know its IP address, then switch. */
1468 void
1469 router_new_address_suggestion(const char *suggestion,
1470 const dir_connection_t *d_conn)
1472 uint32_t addr, cur = 0;
1473 struct in_addr in;
1474 or_options_t *options = get_options();
1476 /* first, learn what the IP address actually is */
1477 if (!tor_inet_aton(suggestion, &in)) {
1478 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
1479 escaped(suggestion));
1480 return;
1482 addr = ntohl(in.s_addr);
1484 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
1486 if (!server_mode(options)) {
1487 last_guessed_ip = addr; /* store it in case we need it later */
1488 return;
1491 if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
1492 /* We're all set -- we already know our address. Great. */
1493 last_guessed_ip = cur; /* store it in case we need it later */
1494 return;
1496 if (is_internal_IP(addr, 0)) {
1497 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1498 return;
1500 if (addr == d_conn->_base.addr) {
1501 /* Don't believe anybody who says our IP is their IP. */
1502 log_debug(LD_DIR, "A directory server told us our IP address is %s, "
1503 "but he's just reporting his own IP address. Ignoring.",
1504 suggestion);
1505 return;
1508 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1509 * us an answer different from what we had the last time we managed to
1510 * resolve it. */
1511 if (last_guessed_ip != addr) {
1512 control_event_server_status(LOG_NOTICE,
1513 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1514 suggestion);
1515 log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr);
1516 ip_address_changed(0);
1517 last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
1521 /** We failed to resolve our address locally, but we'd like to build
1522 * a descriptor and publish / test reachability. If we have a guess
1523 * about our address based on directory headers, answer it and return
1524 * 0; else return -1. */
1525 static int
1526 router_guess_address_from_dir_headers(uint32_t *guess)
1528 if (last_guessed_ip) {
1529 *guess = last_guessed_ip;
1530 return 0;
1532 return -1;
1535 extern const char tor_svn_revision[]; /* from main.c */
1537 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1538 * string describing the version of Tor and the operating system we're
1539 * currently running on.
1541 void
1542 get_platform_str(char *platform, size_t len)
1544 tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
1547 /* XXX need to audit this thing and count fenceposts. maybe
1548 * refactor so we don't have to keep asking if we're
1549 * near the end of maxlen?
1551 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1553 /** OR only: Given a routerinfo for this router, and an identity key to sign
1554 * with, encode the routerinfo as a signed server descriptor and write the
1555 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1556 * failure, and the number of bytes used on success.
1559 router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
1560 crypto_pk_env_t *ident_key)
1562 char *onion_pkey; /* Onion key, PEM-encoded. */
1563 char *identity_pkey; /* Identity key, PEM-encoded. */
1564 char digest[DIGEST_LEN];
1565 char published[ISO_TIME_LEN+1];
1566 char fingerprint[FINGERPRINT_LEN+1];
1567 char extra_info_digest[HEX_DIGEST_LEN+1];
1568 size_t onion_pkeylen, identity_pkeylen;
1569 size_t written;
1570 int result=0;
1571 addr_policy_t *tmpe;
1572 char *family_line;
1573 or_options_t *options = get_options();
1575 /* Make sure the identity key matches the one in the routerinfo. */
1576 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
1577 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
1578 "match router's public key!");
1579 return -1;
1582 /* record our fingerprint, so we can include it in the descriptor */
1583 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
1584 log_err(LD_BUG,"Error computing fingerprint");
1585 return -1;
1588 /* PEM-encode the onion key */
1589 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
1590 &onion_pkey,&onion_pkeylen)<0) {
1591 log_warn(LD_BUG,"write onion_pkey to string failed!");
1592 return -1;
1595 /* PEM-encode the identity key key */
1596 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
1597 &identity_pkey,&identity_pkeylen)<0) {
1598 log_warn(LD_BUG,"write identity_pkey to string failed!");
1599 tor_free(onion_pkey);
1600 return -1;
1603 /* Encode the publication time. */
1604 format_iso_time(published, router->cache_info.published_on);
1606 if (router->declared_family && smartlist_len(router->declared_family)) {
1607 size_t n;
1608 char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
1609 n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1610 family_line = tor_malloc(n);
1611 tor_snprintf(family_line, n, "family %s\n", family);
1612 tor_free(family);
1613 } else {
1614 family_line = tor_strdup("");
1617 base16_encode(extra_info_digest, sizeof(extra_info_digest),
1618 router->cache_info.extra_info_digest, DIGEST_LEN);
1620 /* Generate the easy portion of the router descriptor. */
1621 result = tor_snprintf(s, maxlen,
1622 "router %s %s %d 0 %d\n"
1623 "platform %s\n"
1624 "opt protocols Link 1 Circuit 1\n"
1625 "published %s\n"
1626 "opt fingerprint %s\n"
1627 "uptime %ld\n"
1628 "bandwidth %d %d %d\n"
1629 "opt extra-info-digest %s\n%s"
1630 "onion-key\n%s"
1631 "signing-key\n%s"
1632 "%s%s%s",
1633 router->nickname,
1634 router->address,
1635 router->or_port,
1636 decide_to_advertise_dirport(options, router->dir_port),
1637 router->platform,
1638 published,
1639 fingerprint,
1640 stats_n_seconds_working,
1641 (int) router->bandwidthrate,
1642 (int) router->bandwidthburst,
1643 (int) router->bandwidthcapacity,
1644 extra_info_digest,
1645 options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
1646 onion_pkey, identity_pkey,
1647 family_line,
1648 we_are_hibernating() ? "opt hibernating 1\n" : "",
1649 options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "");
1651 tor_free(family_line);
1652 tor_free(onion_pkey);
1653 tor_free(identity_pkey);
1655 if (result < 0) {
1656 log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
1657 return -1;
1659 /* From now on, we use 'written' to remember the current length of 's'. */
1660 written = result;
1662 if (options->ContactInfo && strlen(options->ContactInfo)) {
1663 const char *ci = options->ContactInfo;
1664 if (strchr(ci, '\n') || strchr(ci, '\r'))
1665 ci = escaped(ci);
1666 result = tor_snprintf(s+written,maxlen-written, "contact %s\n", ci);
1667 if (result<0) {
1668 log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
1669 return -1;
1671 written += result;
1674 /* Write the exit policy to the end of 's'. */
1675 if (dns_seems_to_be_broken()) {
1676 /* DNS is screwed up; don't claim to be an exit. */
1677 strlcat(s+written, "reject *:*\n", maxlen-written);
1678 written += strlen("reject *:*\n");
1679 tmpe = NULL;
1680 } else if (router->exit_policy) {
1681 int i;
1682 for (i = 0; i < smartlist_len(router->exit_policy); ++i) {
1683 tmpe = smartlist_get(router->exit_policy, i);
1684 result = policy_write_item(s+written, maxlen-written, tmpe);
1685 if (result < 0) {
1686 log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
1687 return -1;
1689 tor_assert(result == (int)strlen(s+written));
1690 written += result;
1691 if (written+2 > maxlen) {
1692 log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
1693 return -1;
1695 s[written++] = '\n';
1699 if (written+256 > maxlen) { /* Not enough room for signature. */
1700 log_warn(LD_BUG,"not enough room left in descriptor for signature!");
1701 return -1;
1704 /* Sign the directory */
1705 strlcpy(s+written, "router-signature\n", maxlen-written);
1706 written += strlen(s+written);
1707 s[written] = '\0';
1708 if (router_get_router_hash(s, digest) < 0) {
1709 return -1;
1712 note_crypto_pk_op(SIGN_RTR);
1713 if (router_append_dirobj_signature(s+written,maxlen-written,
1714 digest,ident_key)<0) {
1715 log_warn(LD_BUG, "Couldn't sign router descriptor");
1716 return -1;
1718 written += strlen(s+written);
1720 if (written+2 > maxlen) {
1721 log_warn(LD_BUG,"Not enough room to finish descriptor.");
1722 return -1;
1724 /* include a last '\n' */
1725 s[written] = '\n';
1726 s[written+1] = 0;
1728 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1730 char *s_dup;
1731 const char *cp;
1732 routerinfo_t *ri_tmp;
1733 cp = s_dup = tor_strdup(s);
1734 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
1735 if (!ri_tmp) {
1736 log_err(LD_BUG,
1737 "We just generated a router descriptor we can't parse.");
1738 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1739 return -1;
1741 tor_free(s_dup);
1742 routerinfo_free(ri_tmp);
1744 #endif
1746 return (int)written+1;
1749 /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
1750 * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
1751 * negative on failure. */
1753 extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
1754 crypto_pk_env_t *ident_key)
1756 or_options_t *options = get_options();
1757 char identity[HEX_DIGEST_LEN+1];
1758 char published[ISO_TIME_LEN+1];
1759 char digest[DIGEST_LEN];
1760 char *bandwidth_usage;
1761 int result;
1762 size_t len;
1764 base16_encode(identity, sizeof(identity),
1765 extrainfo->cache_info.identity_digest, DIGEST_LEN);
1766 format_iso_time(published, extrainfo->cache_info.published_on);
1767 bandwidth_usage = rep_hist_get_bandwidth_lines(1);
1769 result = tor_snprintf(s, maxlen,
1770 "extra-info %s %s\n"
1771 "published %s\n%s",
1772 extrainfo->nickname, identity,
1773 published, bandwidth_usage);
1774 tor_free(bandwidth_usage);
1775 if (result<0)
1776 return -1;
1778 if (options->BridgeRelay && options->BridgeRecordUsageByCountry) {
1779 char *geoip_summary = geoip_get_client_history(time(NULL));
1780 if (geoip_summary) {
1781 char geoip_start[ISO_TIME_LEN+1];
1782 format_iso_time(geoip_start, geoip_get_history_start());
1783 result = tor_snprintf(s+strlen(s), maxlen-strlen(s),
1784 "geoip-start-time %s\n"
1785 "geoip-client-origins %s\n",
1786 geoip_start, geoip_summary);
1787 tor_free(geoip_summary);
1788 if (result<0)
1789 return -1;
1793 len = strlen(s);
1794 strlcat(s+len, "router-signature\n", maxlen-len);
1795 len += strlen(s+len);
1796 if (router_get_extrainfo_hash(s, digest)<0)
1797 return -1;
1798 if (router_append_dirobj_signature(s+len, maxlen-len, digest, ident_key)<0)
1799 return -1;
1801 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1803 char *cp, *s_dup;
1804 extrainfo_t *ei_tmp;
1805 cp = s_dup = tor_strdup(s);
1806 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
1807 if (!ei_tmp) {
1808 log_err(LD_BUG,
1809 "We just generated an extrainfo descriptor we can't parse.");
1810 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1811 return -1;
1813 tor_free(s_dup);
1814 extrainfo_free(ei_tmp);
1816 #endif
1818 return (int)strlen(s)+1;
1821 /** Return true iff <b>s</b> is a legally valid server nickname. */
1823 is_legal_nickname(const char *s)
1825 size_t len;
1826 tor_assert(s);
1827 len = strlen(s);
1828 return len > 0 && len <= MAX_NICKNAME_LEN &&
1829 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
1832 /** Return true iff <b>s</b> is a legally valid server nickname or
1833 * hex-encoded identity-key digest. */
1835 is_legal_nickname_or_hexdigest(const char *s)
1837 if (*s!='$')
1838 return is_legal_nickname(s);
1839 else
1840 return is_legal_hexdigest(s);
1843 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
1844 * digest. */
1846 is_legal_hexdigest(const char *s)
1848 size_t len;
1849 tor_assert(s);
1850 if (s[0] == '$') s++;
1851 len = strlen(s);
1852 if (len > HEX_DIGEST_LEN) {
1853 if (s[HEX_DIGEST_LEN] == '=' ||
1854 s[HEX_DIGEST_LEN] == '~') {
1855 if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
1856 return 0;
1857 } else {
1858 return 0;
1861 return (len >= HEX_DIGEST_LEN &&
1862 strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
1865 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
1866 * verbose representation of the identity of <b>router</b>. The format is:
1867 * A dollar sign.
1868 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
1869 * A "=" if the router is named; a "~" if it is not.
1870 * The router's nickname.
1872 void
1873 router_get_verbose_nickname(char *buf, routerinfo_t *router)
1875 buf[0] = '$';
1876 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
1877 DIGEST_LEN);
1878 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
1879 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
1882 /** Forget that we have issued any router-related warnings, so that we'll
1883 * warn again if we see the same errors. */
1884 void
1885 router_reset_warnings(void)
1887 if (warned_nonexistent_family) {
1888 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1889 smartlist_clear(warned_nonexistent_family);
1893 /** Given a router purpose, convert it to a string. Don't call this on
1894 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
1895 * know its string representation. */
1896 const char *
1897 router_purpose_to_string(uint8_t p)
1899 switch (p)
1901 case ROUTER_PURPOSE_GENERAL: return "general";
1902 case ROUTER_PURPOSE_BRIDGE: return "bridge";
1903 case ROUTER_PURPOSE_CONTROLLER: return "controller";
1904 default:
1905 tor_assert(0);
1907 return NULL;
1910 /** Given a string, convert it to a router purpose. */
1911 uint8_t
1912 router_purpose_from_string(const char *s)
1914 if (!strcmp(s, "general"))
1915 return ROUTER_PURPOSE_GENERAL;
1916 else if (!strcmp(s, "bridge"))
1917 return ROUTER_PURPOSE_BRIDGE;
1918 else if (!strcmp(s, "controller"))
1919 return ROUTER_PURPOSE_CONTROLLER;
1920 else
1921 return ROUTER_PURPOSE_UNKNOWN;
1924 /** Release all static resources held in router.c */
1925 void
1926 router_free_all(void)
1928 if (onionkey)
1929 crypto_free_pk_env(onionkey);
1930 if (lastonionkey)
1931 crypto_free_pk_env(lastonionkey);
1932 if (identitykey)
1933 crypto_free_pk_env(identitykey);
1934 if (key_lock)
1935 tor_mutex_free(key_lock);
1936 if (desc_routerinfo)
1937 routerinfo_free(desc_routerinfo);
1938 if (desc_extrainfo)
1939 extrainfo_free(desc_extrainfo);
1940 if (authority_signing_key)
1941 crypto_free_pk_env(authority_signing_key);
1942 if (authority_key_certificate)
1943 authority_cert_free(authority_key_certificate);
1945 if (warned_nonexistent_family) {
1946 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1947 smartlist_free(warned_nonexistent_family);