fix some irix compile complaints; make "kbytes" work as a memory unit
[tor.git] / src / or / router.c
blob510b0b773cd701baa7fc0d9a2ef6b7866eba3cdc
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_digest_is_trusted_dir(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, 0, me, 0, 1, 1);
703 control_event_server_status(LOG_NOTICE,
704 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
705 me->address, me->or_port);
708 if (test_dir && !check_whether_dirport_reachable() &&
709 !connection_get_by_type_addr_port_purpose(
710 CONN_TYPE_DIR, me->addr, me->dir_port,
711 DIR_PURPOSE_FETCH_SERVERDESC)) {
712 /* ask myself, via tor, for my server descriptor. */
713 directory_initiate_command(me->address, me->addr,
714 me->or_port, me->dir_port,
715 0, me->cache_info.identity_digest,
716 DIR_PURPOSE_FETCH_SERVERDESC,
717 ROUTER_PURPOSE_GENERAL,
718 1, "authority.z", NULL, 0, 0);
720 control_event_server_status(LOG_NOTICE,
721 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
722 me->address, me->dir_port);
726 /** Annotate that we found our ORPort reachable. */
727 void
728 router_orport_found_reachable(void)
730 if (!can_reach_or_port) {
731 routerinfo_t *me = router_get_my_routerinfo();
732 log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
733 "the outside. Excellent.%s",
734 get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
735 " Publishing server descriptor." : "");
736 can_reach_or_port = 1;
737 mark_my_descriptor_dirty();
738 if (!me)
739 return;
740 control_event_server_status(LOG_NOTICE,
741 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
742 me->address, me->or_port);
746 /** Annotate that we found our DirPort reachable. */
747 void
748 router_dirport_found_reachable(void)
750 if (!can_reach_dir_port) {
751 routerinfo_t *me = router_get_my_routerinfo();
752 log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
753 "from the outside. Excellent.");
754 can_reach_dir_port = 1;
755 if (!me || decide_to_advertise_dirport(get_options(), me->dir_port))
756 mark_my_descriptor_dirty();
757 if (!me)
758 return;
759 control_event_server_status(LOG_NOTICE,
760 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
761 me->address, me->dir_port);
765 /** We have enough testing circuits open. Send a bunch of "drop"
766 * cells down each of them, to exercise our bandwidth. */
767 void
768 router_perform_bandwidth_test(int num_circs, time_t now)
770 int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
771 int max_cells = num_cells < CIRCWINDOW_START ?
772 num_cells : CIRCWINDOW_START;
773 int cells_per_circuit = max_cells / num_circs;
774 origin_circuit_t *circ = NULL;
776 log_notice(LD_OR,"Performing bandwidth self-test...done.");
777 while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
778 CIRCUIT_PURPOSE_TESTING))) {
779 /* dump cells_per_circuit drop cells onto this circ */
780 int i = cells_per_circuit;
781 if (circ->_base.state != CIRCUIT_STATE_OPEN)
782 continue;
783 circ->_base.timestamp_dirty = now;
784 while (i-- > 0) {
785 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
786 RELAY_COMMAND_DROP,
787 NULL, 0, circ->cpath->prev)<0) {
788 return; /* stop if error */
794 /** Return true iff we believe ourselves to be an authoritative
795 * directory server.
798 authdir_mode(or_options_t *options)
800 return options->AuthoritativeDir != 0;
802 /** Return true iff we believe ourselves to be a v1 authoritative
803 * directory server.
806 authdir_mode_v1(or_options_t *options)
808 return authdir_mode(options) && options->V1AuthoritativeDir != 0;
810 /** Return true iff we believe ourselves to be a v2 authoritative
811 * directory server.
814 authdir_mode_v2(or_options_t *options)
816 return authdir_mode(options) && options->V2AuthoritativeDir != 0;
818 /** Return true iff we believe ourselves to be a v3 authoritative
819 * directory server.
822 authdir_mode_v3(or_options_t *options)
824 return authdir_mode(options) && options->V3AuthoritativeDir != 0;
826 /** Return true iff we are a v1, v2, or v3 directory authority. */
828 authdir_mode_any_main(or_options_t *options)
830 return options->V1AuthoritativeDir ||
831 options->V2AuthoritativeDir ||
832 options->V3AuthoritativeDir;
834 /** Return true if we believe ourselves to be any kind of
835 * authoritative directory beyond just a hidserv authority. */
837 authdir_mode_any_nonhidserv(or_options_t *options)
839 return options->BridgeAuthoritativeDir ||
840 authdir_mode_any_main(options);
842 /** Return true iff we are an authoritative directory server that is
843 * authoritative about receiving and serving descriptors of type
844 * <b>purpose</b> its dirport. Use -1 for "any purpose". */
846 authdir_mode_handles_descs(or_options_t *options, int purpose)
848 if (purpose < 0)
849 return authdir_mode_any_nonhidserv(options);
850 else if (purpose == ROUTER_PURPOSE_GENERAL)
851 return authdir_mode_any_main(options);
852 else if (purpose == ROUTER_PURPOSE_BRIDGE)
853 return (options->BridgeAuthoritativeDir);
854 else
855 return 0;
857 /** Return true iff we are an authoritative directory server that
858 * publishes its own network statuses.
861 authdir_mode_publishes_statuses(or_options_t *options)
863 if (authdir_mode_bridge(options))
864 return 0;
865 return authdir_mode_any_nonhidserv(options);
867 /** Return true iff we are an authoritative directory server that
868 * tests reachability of the descriptors it learns about.
871 authdir_mode_tests_reachability(or_options_t *options)
873 return authdir_mode_handles_descs(options, -1);
875 /** Return true iff we believe ourselves to be a bridge authoritative
876 * directory server.
879 authdir_mode_bridge(or_options_t *options)
881 return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
883 /** Return true iff we once tried to stay connected to all ORs at once.
884 * FFFF this function, and the notion of staying connected to ORs, is
885 * nearly obsolete. One day there will be a proposal for getting rid of
886 * it.
889 clique_mode(or_options_t *options)
891 return authdir_mode_tests_reachability(options);
894 /** Return true iff we are trying to be a server.
897 server_mode(or_options_t *options)
899 if (options->ClientOnly) return 0;
900 return (options->ORPort != 0 || options->ORListenAddress);
903 /** Remember if we've advertised ourselves to the dirservers. */
904 static int server_is_advertised=0;
906 /** Return true iff we have published our descriptor lately.
909 advertised_server_mode(void)
911 return server_is_advertised;
915 * Called with a boolean: set whether we have recently published our
916 * descriptor.
918 static void
919 set_server_advertised(int s)
921 server_is_advertised = s;
924 /** Return true iff we are trying to be a socks proxy. */
926 proxy_mode(or_options_t *options)
928 return (options->SocksPort != 0 || options->SocksListenAddress ||
929 options->TransPort != 0 || options->TransListenAddress ||
930 options->NatdPort != 0 || options->NatdListenAddress ||
931 options->DNSPort != 0 || options->DNSListenAddress);
934 /** Decide if we're a publishable server. We are a publishable server if:
935 * - We don't have the ClientOnly option set
936 * and
937 * - We have the PublishServerDescriptor option set to non-empty
938 * and
939 * - We have ORPort set
940 * and
941 * - We believe we are reachable from the outside; or
942 * - We are an authoritative directory server.
944 static int
945 decide_if_publishable_server(void)
947 or_options_t *options = get_options();
949 if (options->ClientOnly)
950 return 0;
951 if (options->_PublishServerDescriptor == NO_AUTHORITY)
952 return 0;
953 if (!server_mode(options))
954 return 0;
955 if (authdir_mode(options))
956 return 1;
958 return check_whether_orport_reachable();
961 /** Initiate server descriptor upload as reasonable (if server is publishable,
962 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
964 * We need to rebuild the descriptor if it's dirty even if we're not
965 * uploading, because our reachability testing *uses* our descriptor to
966 * determine what IP address and ports to test.
968 void
969 consider_publishable_server(int force)
971 int rebuilt;
973 if (!server_mode(get_options()))
974 return;
976 rebuilt = router_rebuild_descriptor(0);
977 if (decide_if_publishable_server()) {
978 set_server_advertised(1);
979 if (rebuilt == 0)
980 router_upload_dir_desc_to_dirservers(force);
981 } else {
982 set_server_advertised(0);
987 * Clique maintenance -- to be phased out.
990 /** Return true iff we believe this OR tries to keep connections open
991 * to all other ORs. */
993 router_is_clique_mode(routerinfo_t *router)
995 if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
996 return 1;
997 return 0;
1001 * OR descriptor generation.
1004 /** My routerinfo. */
1005 static routerinfo_t *desc_routerinfo = NULL;
1006 /** My extrainfo */
1007 static extrainfo_t *desc_extrainfo = NULL;
1008 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1009 * now. */
1010 static time_t desc_clean_since = 0;
1011 /** Boolean: do we need to regenerate the above? */
1012 static int desc_needs_upload = 0;
1014 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1015 * descriptor successfully yet, try to upload our signed descriptor to
1016 * all the directory servers we know about.
1018 void
1019 router_upload_dir_desc_to_dirservers(int force)
1021 routerinfo_t *ri;
1022 extrainfo_t *ei;
1023 char *msg;
1024 size_t desc_len, extra_len = 0, total_len;
1025 authority_type_t auth = get_options()->_PublishServerDescriptor;
1027 ri = router_get_my_routerinfo();
1028 if (!ri) {
1029 log_info(LD_GENERAL, "No descriptor; skipping upload");
1030 return;
1032 ei = router_get_my_extrainfo();
1033 if (auth == NO_AUTHORITY)
1034 return;
1035 if (!force && !desc_needs_upload)
1036 return;
1037 desc_needs_upload = 0;
1039 desc_len = ri->cache_info.signed_descriptor_len;
1040 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1041 total_len = desc_len + extra_len + 1;
1042 msg = tor_malloc(total_len);
1043 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1044 if (ei) {
1045 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1047 msg[desc_len+extra_len] = 0;
1049 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
1050 (auth & BRIDGE_AUTHORITY) ?
1051 ROUTER_PURPOSE_BRIDGE :
1052 ROUTER_PURPOSE_GENERAL,
1053 auth, msg, desc_len, extra_len);
1054 tor_free(msg);
1057 /** OR only: Check whether my exit policy says to allow connection to
1058 * conn. Return 0 if we accept; non-0 if we reject.
1061 router_compare_to_my_exit_policy(edge_connection_t *conn)
1063 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1064 return -1;
1066 /* make sure it's resolved to something. this way we can't get a
1067 'maybe' below. */
1068 if (!conn->_base.addr)
1069 return -1;
1071 return compare_addr_to_addr_policy(conn->_base.addr, conn->_base.port,
1072 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
1075 /** Return true iff I'm a server and <b>digest</b> is equal to
1076 * my identity digest. */
1078 router_digest_is_me(const char *digest)
1080 return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
1083 /** A wrapper around router_digest_is_me(). */
1085 router_is_me(routerinfo_t *router)
1087 return router_digest_is_me(router->cache_info.identity_digest);
1090 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1092 router_fingerprint_is_me(const char *fp)
1094 char digest[DIGEST_LEN];
1095 if (strlen(fp) == HEX_DIGEST_LEN &&
1096 base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
1097 return router_digest_is_me(digest);
1099 return 0;
1102 /** Return a routerinfo for this OR, rebuilding a fresh one if
1103 * necessary. Return NULL on error, or if called on an OP. */
1104 routerinfo_t *
1105 router_get_my_routerinfo(void)
1107 if (!server_mode(get_options()))
1108 return NULL;
1109 if (router_rebuild_descriptor(0))
1110 return NULL;
1111 return desc_routerinfo;
1114 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1115 * one if necessary. Return NULL on error.
1117 const char *
1118 router_get_my_descriptor(void)
1120 const char *body;
1121 if (!router_get_my_routerinfo())
1122 return NULL;
1123 /* Make sure this is nul-terminated. */
1124 tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
1125 body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
1126 tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
1127 log_debug(LD_GENERAL,"my desc is '%s'", body);
1128 return body;
1131 /* Return the extrainfo document for this OR, or NULL if we have none.
1132 * Rebuilt it (and the server descriptor) if necessary. */
1133 extrainfo_t *
1134 router_get_my_extrainfo(void)
1136 if (!server_mode(get_options()))
1137 return NULL;
1138 if (router_rebuild_descriptor(0))
1139 return NULL;
1140 return desc_extrainfo;
1143 /** A list of nicknames that we've warned about including in our family
1144 * declaration verbatim rather than as digests. */
1145 static smartlist_t *warned_nonexistent_family = NULL;
1147 static int router_guess_address_from_dir_headers(uint32_t *guess);
1149 /** Return our current best guess at our address, either because
1150 * it's configured in torrc, or because we've learned it from
1151 * dirserver headers. */
1153 router_pick_published_address(or_options_t *options, uint32_t *addr)
1155 if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
1156 log_info(LD_CONFIG, "Could not determine our address locally. "
1157 "Checking if directory headers provide any hints.");
1158 if (router_guess_address_from_dir_headers(addr) < 0) {
1159 log_info(LD_CONFIG, "No hints from directory headers either. "
1160 "Will try again later.");
1161 return -1;
1164 return 0;
1167 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1168 * routerinfo, signed server descriptor, and extra-info document for this OR.
1169 * Return 0 on success, -1 on temporary error.
1172 router_rebuild_descriptor(int force)
1174 routerinfo_t *ri;
1175 extrainfo_t *ei;
1176 uint32_t addr;
1177 char platform[256];
1178 int hibernating = we_are_hibernating();
1179 or_options_t *options = get_options();
1181 if (desc_clean_since && !force)
1182 return 0;
1184 if (router_pick_published_address(options, &addr) < 0) {
1185 /* Stop trying to rebuild our descriptor every second. We'll
1186 * learn that it's time to try again when server_has_changed_ip()
1187 * marks it dirty. */
1188 desc_clean_since = time(NULL);
1189 return -1;
1192 ri = tor_malloc_zero(sizeof(routerinfo_t));
1193 ri->cache_info.routerlist_index = -1;
1194 ri->address = tor_dup_addr(addr);
1195 ri->nickname = tor_strdup(options->Nickname);
1196 ri->addr = addr;
1197 ri->or_port = options->ORPort;
1198 ri->dir_port = options->DirPort;
1199 ri->cache_info.published_on = time(NULL);
1200 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
1201 * main thread */
1202 ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
1203 if (crypto_pk_get_digest(ri->identity_pkey,
1204 ri->cache_info.identity_digest)<0) {
1205 routerinfo_free(ri);
1206 return -1;
1208 get_platform_str(platform, sizeof(platform));
1209 ri->platform = tor_strdup(platform);
1211 /* compute ri->bandwidthrate as the min of various options */
1212 ri->bandwidthrate = (int)options->BandwidthRate;
1213 if (ri->bandwidthrate > options->MaxAdvertisedBandwidth)
1214 ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
1215 if (options->RelayBandwidthRate > 0 &&
1216 ri->bandwidthrate > options->RelayBandwidthRate)
1217 ri->bandwidthrate = (int)options->RelayBandwidthRate;
1219 /* and compute ri->bandwidthburst similarly */
1220 ri->bandwidthburst = (int)options->BandwidthBurst;
1221 if (options->RelayBandwidthBurst > 0 &&
1222 ri->bandwidthburst > options->RelayBandwidthBurst)
1223 ri->bandwidthburst = (int)options->RelayBandwidthBurst;
1225 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
1227 policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
1228 options->ExitPolicyRejectPrivate,
1229 ri->address);
1231 if (desc_routerinfo) { /* inherit values */
1232 ri->is_valid = desc_routerinfo->is_valid;
1233 ri->is_running = desc_routerinfo->is_running;
1234 ri->is_named = desc_routerinfo->is_named;
1236 if (authdir_mode(options))
1237 ri->is_valid = ri->is_named = 1; /* believe in yourself */
1238 if (options->MyFamily) {
1239 smartlist_t *family;
1240 if (!warned_nonexistent_family)
1241 warned_nonexistent_family = smartlist_create();
1242 family = smartlist_create();
1243 ri->declared_family = smartlist_create();
1244 smartlist_split_string(family, options->MyFamily, ",",
1245 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1246 SMARTLIST_FOREACH(family, char *, name,
1248 routerinfo_t *member;
1249 if (!strcasecmp(name, options->Nickname))
1250 member = ri;
1251 else
1252 member = router_get_by_nickname(name, 1);
1253 if (!member) {
1254 if (!smartlist_string_isin(warned_nonexistent_family, name) &&
1255 !is_legal_hexdigest(name)) {
1256 log_warn(LD_CONFIG,
1257 "I have no descriptor for the router named \"%s\" "
1258 "in my declared family; I'll use the nickname as is, but "
1259 "this may confuse clients.", name);
1260 smartlist_add(warned_nonexistent_family, tor_strdup(name));
1262 smartlist_add(ri->declared_family, name);
1263 name = NULL;
1264 } else if (router_is_me(member)) {
1265 /* Don't list ourself in our own family; that's redundant */
1266 } else {
1267 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1268 fp[0] = '$';
1269 base16_encode(fp+1,HEX_DIGEST_LEN+1,
1270 member->cache_info.identity_digest, DIGEST_LEN);
1271 smartlist_add(ri->declared_family, fp);
1272 if (smartlist_string_isin(warned_nonexistent_family, name))
1273 smartlist_string_remove(warned_nonexistent_family, name);
1275 tor_free(name);
1278 /* remove duplicates from the list */
1279 smartlist_sort_strings(ri->declared_family);
1280 smartlist_uniq_strings(ri->declared_family);
1282 smartlist_free(family);
1285 /* Now generate the extrainfo. */
1286 ei = tor_malloc_zero(sizeof(extrainfo_t));
1287 ei->cache_info.is_extrainfo = 1;
1288 strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
1289 ei->cache_info.published_on = ri->cache_info.published_on;
1290 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
1291 DIGEST_LEN);
1292 ei->cache_info.signed_descriptor_body = tor_malloc(8192);
1293 if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body, 8192,
1294 ei, get_identity_key()) < 0) {
1295 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
1296 return -1;
1298 ei->cache_info.signed_descriptor_len =
1299 strlen(ei->cache_info.signed_descriptor_body);
1300 router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
1301 ei->cache_info.signed_descriptor_digest);
1303 /* Now finish the router descriptor. */
1304 memcpy(ri->cache_info.extra_info_digest,
1305 ei->cache_info.signed_descriptor_digest,
1306 DIGEST_LEN);
1307 ri->cache_info.signed_descriptor_body = tor_malloc(8192);
1308 if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
1309 ri, get_identity_key())<0) {
1310 log_warn(LD_BUG, "Couldn't generate router descriptor.");
1311 return -1;
1313 ri->cache_info.signed_descriptor_len =
1314 strlen(ri->cache_info.signed_descriptor_body);
1316 router_get_router_hash(ri->cache_info.signed_descriptor_body,
1317 ri->cache_info.signed_descriptor_digest);
1319 tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
1321 if (desc_routerinfo)
1322 routerinfo_free(desc_routerinfo);
1323 desc_routerinfo = ri;
1324 if (desc_extrainfo)
1325 extrainfo_free(desc_extrainfo);
1326 desc_extrainfo = ei;
1328 desc_clean_since = time(NULL);
1329 desc_needs_upload = 1;
1330 control_event_my_descriptor_changed();
1331 return 0;
1334 /** Mark descriptor out of date if it's older than <b>when</b> */
1335 void
1336 mark_my_descriptor_dirty_if_older_than(time_t when)
1338 if (desc_clean_since < when)
1339 mark_my_descriptor_dirty();
1342 /** Call when the current descriptor is out of date. */
1343 void
1344 mark_my_descriptor_dirty(void)
1346 desc_clean_since = 0;
1349 /** How frequently will we republish our descriptor because of large (factor
1350 * of 2) shifts in estimated bandwidth? */
1351 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
1353 /** Check whether bandwidth has changed a lot since the last time we announced
1354 * bandwidth. If so, mark our descriptor dirty. */
1355 void
1356 check_descriptor_bandwidth_changed(time_t now)
1358 static time_t last_changed = 0;
1359 uint64_t prev, cur;
1360 if (!desc_routerinfo)
1361 return;
1363 prev = desc_routerinfo->bandwidthcapacity;
1364 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
1365 if ((prev != cur && (!prev || !cur)) ||
1366 cur > prev*2 ||
1367 cur < prev/2) {
1368 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
1369 log_info(LD_GENERAL,
1370 "Measured bandwidth has changed; rebuilding descriptor.");
1371 mark_my_descriptor_dirty();
1372 last_changed = now;
1377 /** Note at log level severity that our best guess of address has changed from
1378 * <b>prev</b> to <b>cur</b>. */
1379 static void
1380 log_addr_has_changed(int severity, uint32_t prev, uint32_t cur)
1382 char addrbuf_prev[INET_NTOA_BUF_LEN];
1383 char addrbuf_cur[INET_NTOA_BUF_LEN];
1384 struct in_addr in_prev;
1385 struct in_addr in_cur;
1387 in_prev.s_addr = htonl(prev);
1388 tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
1390 in_cur.s_addr = htonl(cur);
1391 tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
1393 if (prev)
1394 log_fn(severity, LD_GENERAL,
1395 "Our IP Address has changed from %s to %s; "
1396 "rebuilding descriptor.",
1397 addrbuf_prev, addrbuf_cur);
1398 else
1399 log_notice(LD_GENERAL,
1400 "Guessed our IP address as %s.",
1401 addrbuf_cur);
1404 /** Check whether our own address as defined by the Address configuration
1405 * has changed. This is for routers that get their address from a service
1406 * like dyndns. If our address has changed, mark our descriptor dirty. */
1407 void
1408 check_descriptor_ipaddress_changed(time_t now)
1410 uint32_t prev, cur;
1411 or_options_t *options = get_options();
1412 (void) now;
1414 if (!desc_routerinfo)
1415 return;
1417 prev = desc_routerinfo->addr;
1418 if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
1419 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
1420 return;
1423 if (prev != cur) {
1424 log_addr_has_changed(LOG_INFO, prev, cur);
1425 ip_address_changed(0);
1429 /** The most recently guessed value of our IP address, based on directory
1430 * headers. */
1431 static uint32_t last_guessed_ip = 0;
1433 /** A directory server told us our IP address is <b>suggestion</b>.
1434 * If this address is different from the one we think we are now, and
1435 * if our computer doesn't actually know its IP address, then switch. */
1436 void
1437 router_new_address_suggestion(const char *suggestion)
1439 uint32_t addr, cur = 0;
1440 struct in_addr in;
1441 or_options_t *options = get_options();
1443 /* first, learn what the IP address actually is */
1444 if (!tor_inet_aton(suggestion, &in)) {
1445 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
1446 escaped(suggestion));
1447 return;
1449 addr = ntohl(in.s_addr);
1451 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
1453 if (!server_mode(options)) {
1454 last_guessed_ip = addr; /* store it in case we need it later */
1455 return;
1458 if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
1459 /* We're all set -- we already know our address. Great. */
1460 last_guessed_ip = cur; /* store it in case we need it later */
1461 return;
1463 if (is_internal_IP(addr, 0)) {
1464 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1465 return;
1468 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1469 * us an answer different from what we had the last time we managed to
1470 * resolve it. */
1471 if (last_guessed_ip != addr) {
1472 control_event_server_status(LOG_NOTICE,
1473 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1474 suggestion);
1475 log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr);
1476 ip_address_changed(0);
1477 last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
1481 /** We failed to resolve our address locally, but we'd like to build
1482 * a descriptor and publish / test reachability. If we have a guess
1483 * about our address based on directory headers, answer it and return
1484 * 0; else return -1. */
1485 static int
1486 router_guess_address_from_dir_headers(uint32_t *guess)
1488 if (last_guessed_ip) {
1489 *guess = last_guessed_ip;
1490 return 0;
1492 return -1;
1495 extern const char tor_svn_revision[]; /* from main.c */
1497 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1498 * string describing the version of Tor and the operating system we're
1499 * currently running on.
1501 void
1502 get_platform_str(char *platform, size_t len)
1504 tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
1507 /* XXX need to audit this thing and count fenceposts. maybe
1508 * refactor so we don't have to keep asking if we're
1509 * near the end of maxlen?
1511 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1513 /** OR only: Given a routerinfo for this router, and an identity key to sign
1514 * with, encode the routerinfo as a signed server descriptor and write the
1515 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1516 * failure, and the number of bytes used on success.
1519 router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
1520 crypto_pk_env_t *ident_key)
1522 char *onion_pkey; /* Onion key, PEM-encoded. */
1523 char *identity_pkey; /* Identity key, PEM-encoded. */
1524 char digest[DIGEST_LEN];
1525 char published[ISO_TIME_LEN+1];
1526 char fingerprint[FINGERPRINT_LEN+1];
1527 char extra_info_digest[HEX_DIGEST_LEN+1];
1528 size_t onion_pkeylen, identity_pkeylen;
1529 size_t written;
1530 int result=0;
1531 addr_policy_t *tmpe;
1532 char *family_line;
1533 or_options_t *options = get_options();
1535 /* Make sure the identity key matches the one in the routerinfo. */
1536 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
1537 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
1538 "match router's public key!");
1539 return -1;
1542 /* record our fingerprint, so we can include it in the descriptor */
1543 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
1544 log_err(LD_BUG,"Error computing fingerprint");
1545 return -1;
1548 /* PEM-encode the onion key */
1549 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
1550 &onion_pkey,&onion_pkeylen)<0) {
1551 log_warn(LD_BUG,"write onion_pkey to string failed!");
1552 return -1;
1555 /* PEM-encode the identity key key */
1556 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
1557 &identity_pkey,&identity_pkeylen)<0) {
1558 log_warn(LD_BUG,"write identity_pkey to string failed!");
1559 tor_free(onion_pkey);
1560 return -1;
1563 /* Encode the publication time. */
1564 format_iso_time(published, router->cache_info.published_on);
1566 if (router->declared_family && smartlist_len(router->declared_family)) {
1567 size_t n;
1568 char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
1569 n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1570 family_line = tor_malloc(n);
1571 tor_snprintf(family_line, n, "family %s\n", family);
1572 tor_free(family);
1573 } else {
1574 family_line = tor_strdup("");
1577 base16_encode(extra_info_digest, sizeof(extra_info_digest),
1578 router->cache_info.extra_info_digest, DIGEST_LEN);
1580 /* Generate the easy portion of the router descriptor. */
1581 result = tor_snprintf(s, maxlen,
1582 "router %s %s %d 0 %d\n"
1583 "platform %s\n"
1584 "opt protocols Link 1 Circuit 1\n"
1585 "published %s\n"
1586 "opt fingerprint %s\n"
1587 "uptime %ld\n"
1588 "bandwidth %d %d %d\n"
1589 "opt extra-info-digest %s\n%s"
1590 "onion-key\n%s"
1591 "signing-key\n%s"
1592 "%s%s%s",
1593 router->nickname,
1594 router->address,
1595 router->or_port,
1596 decide_to_advertise_dirport(options, router->dir_port),
1597 router->platform,
1598 published,
1599 fingerprint,
1600 stats_n_seconds_working,
1601 (int) router->bandwidthrate,
1602 (int) router->bandwidthburst,
1603 (int) router->bandwidthcapacity,
1604 extra_info_digest,
1605 options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
1606 onion_pkey, identity_pkey,
1607 family_line,
1608 we_are_hibernating() ? "opt hibernating 1\n" : "",
1609 options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "");
1611 tor_free(family_line);
1612 tor_free(onion_pkey);
1613 tor_free(identity_pkey);
1615 if (result < 0) {
1616 log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
1617 return -1;
1619 /* From now on, we use 'written' to remember the current length of 's'. */
1620 written = result;
1622 if (options->ContactInfo && strlen(options->ContactInfo)) {
1623 result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
1624 options->ContactInfo);
1625 if (result<0) {
1626 log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
1627 return -1;
1629 written += result;
1632 /* Write the exit policy to the end of 's'. */
1633 tmpe = router->exit_policy;
1634 if (dns_seems_to_be_broken()) {
1635 /* DNS is screwed up; don't claim to be an exit. */
1636 strlcat(s+written, "reject *:*\n", maxlen-written);
1637 written += strlen("reject *:*\n");
1638 tmpe = NULL;
1640 for ( ; tmpe; tmpe=tmpe->next) {
1641 result = policy_write_item(s+written, maxlen-written, tmpe);
1642 if (result < 0) {
1643 log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
1644 return -1;
1646 tor_assert(result == (int)strlen(s+written));
1647 written += result;
1648 if (written+2 > maxlen) {
1649 log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
1650 return -1;
1652 s[written++] = '\n';
1655 if (written+256 > maxlen) { /* Not enough room for signature. */
1656 log_warn(LD_BUG,"not enough room left in descriptor for signature!");
1657 return -1;
1660 /* Sign the directory */
1661 strlcpy(s+written, "router-signature\n", maxlen-written);
1662 written += strlen(s+written);
1663 s[written] = '\0';
1664 if (router_get_router_hash(s, digest) < 0) {
1665 return -1;
1668 note_crypto_pk_op(SIGN_RTR);
1669 if (router_append_dirobj_signature(s+written,maxlen-written,
1670 digest,ident_key)<0) {
1671 log_warn(LD_BUG, "Couldn't sign router descriptor");
1672 return -1;
1674 written += strlen(s+written);
1676 if (written+2 > maxlen) {
1677 log_warn(LD_BUG,"Not enough room to finish descriptor.");
1678 return -1;
1680 /* include a last '\n' */
1681 s[written] = '\n';
1682 s[written+1] = 0;
1684 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1686 char *s_dup;
1687 const char *cp;
1688 routerinfo_t *ri_tmp;
1689 cp = s_dup = tor_strdup(s);
1690 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
1691 if (!ri_tmp) {
1692 log_err(LD_BUG,
1693 "We just generated a router descriptor we can't parse.");
1694 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1695 return -1;
1697 tor_free(s_dup);
1698 routerinfo_free(ri_tmp);
1700 #endif
1702 return written+1;
1705 /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
1706 * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
1707 * negative on failure. */
1709 extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
1710 crypto_pk_env_t *ident_key)
1712 or_options_t *options = get_options();
1713 char identity[HEX_DIGEST_LEN+1];
1714 char published[ISO_TIME_LEN+1];
1715 char digest[DIGEST_LEN];
1716 char *bandwidth_usage;
1717 int result;
1718 size_t len;
1720 base16_encode(identity, sizeof(identity),
1721 extrainfo->cache_info.identity_digest, DIGEST_LEN);
1722 format_iso_time(published, extrainfo->cache_info.published_on);
1723 bandwidth_usage = rep_hist_get_bandwidth_lines(1);
1725 result = tor_snprintf(s, maxlen,
1726 "extra-info %s %s\n"
1727 "published %s\n%s",
1728 extrainfo->nickname, identity,
1729 published, bandwidth_usage);
1730 tor_free(bandwidth_usage);
1731 if (result<0)
1732 return -1;
1734 if (options->BridgeRelay && options->BridgeRecordUsageByCountry) {
1735 char *geoip_summary = geoip_get_client_history(time(NULL));
1736 if (geoip_summary) {
1737 char geoip_start[ISO_TIME_LEN+1];
1738 format_iso_time(geoip_start, geoip_get_history_start());
1739 result = tor_snprintf(s+strlen(s), maxlen-strlen(s),
1740 "geoip-start-time %s\n"
1741 "geoip-client-origins %s\n",
1742 geoip_start, geoip_summary);
1743 tor_free(geoip_summary);
1744 if (result<0)
1745 return -1;
1749 len = strlen(s);
1750 strlcat(s+len, "router-signature\n", maxlen-len);
1751 len += strlen(s+len);
1752 if (router_get_extrainfo_hash(s, digest)<0)
1753 return -1;
1754 if (router_append_dirobj_signature(s+len, maxlen-len, digest, ident_key)<0)
1755 return -1;
1757 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1759 char *cp, *s_dup;
1760 extrainfo_t *ei_tmp;
1761 cp = s_dup = tor_strdup(s);
1762 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
1763 if (!ei_tmp) {
1764 log_err(LD_BUG,
1765 "We just generated an extrainfo descriptor we can't parse.");
1766 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1767 return -1;
1769 tor_free(s_dup);
1770 extrainfo_free(ei_tmp);
1772 #endif
1774 return strlen(s)+1;
1777 /** Return true iff <b>s</b> is a legally valid server nickname. */
1779 is_legal_nickname(const char *s)
1781 size_t len;
1782 tor_assert(s);
1783 len = strlen(s);
1784 return len > 0 && len <= MAX_NICKNAME_LEN &&
1785 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
1788 /** Return true iff <b>s</b> is a legally valid server nickname or
1789 * hex-encoded identity-key digest. */
1791 is_legal_nickname_or_hexdigest(const char *s)
1793 if (*s!='$')
1794 return is_legal_nickname(s);
1795 else
1796 return is_legal_hexdigest(s);
1799 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
1800 * digest. */
1802 is_legal_hexdigest(const char *s)
1804 size_t len;
1805 tor_assert(s);
1806 if (s[0] == '$') s++;
1807 len = strlen(s);
1808 if (len > HEX_DIGEST_LEN) {
1809 if (s[HEX_DIGEST_LEN] == '=' ||
1810 s[HEX_DIGEST_LEN] == '~') {
1811 if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
1812 return 0;
1813 } else {
1814 return 0;
1817 return (len >= HEX_DIGEST_LEN &&
1818 strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
1821 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
1822 * verbose representation of the identity of <b>router</b>. The format is:
1823 * A dollar sign.
1824 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
1825 * A "=" if the router is named; a "~" if it is not.
1826 * The router's nickname.
1828 void
1829 router_get_verbose_nickname(char *buf, routerinfo_t *router)
1831 buf[0] = '$';
1832 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
1833 DIGEST_LEN);
1834 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
1835 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
1838 /** Forget that we have issued any router-related warnings, so that we'll
1839 * warn again if we see the same errors. */
1840 void
1841 router_reset_warnings(void)
1843 if (warned_nonexistent_family) {
1844 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1845 smartlist_clear(warned_nonexistent_family);
1849 /** Given a router purpose, convert it to a string. Don't call this on
1850 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
1851 * know its string representation. */
1852 const char *
1853 router_purpose_to_string(uint8_t p)
1855 switch (p)
1857 case ROUTER_PURPOSE_GENERAL: return "general";
1858 case ROUTER_PURPOSE_BRIDGE: return "bridge";
1859 case ROUTER_PURPOSE_CONTROLLER: return "controller";
1860 default:
1861 tor_assert(0);
1863 return NULL;
1866 /** Given a string, convert it to a router purpose. */
1867 uint8_t
1868 router_purpose_from_string(const char *s)
1870 if (!strcmp(s, "general"))
1871 return ROUTER_PURPOSE_GENERAL;
1872 else if (!strcmp(s, "bridge"))
1873 return ROUTER_PURPOSE_BRIDGE;
1874 else if (!strcmp(s, "controller"))
1875 return ROUTER_PURPOSE_CONTROLLER;
1876 else
1877 return ROUTER_PURPOSE_UNKNOWN;
1880 /** Release all static resources held in router.c */
1881 void
1882 router_free_all(void)
1884 if (onionkey)
1885 crypto_free_pk_env(onionkey);
1886 if (lastonionkey)
1887 crypto_free_pk_env(lastonionkey);
1888 if (identitykey)
1889 crypto_free_pk_env(identitykey);
1890 if (key_lock)
1891 tor_mutex_free(key_lock);
1892 if (desc_routerinfo)
1893 routerinfo_free(desc_routerinfo);
1894 if (desc_extrainfo)
1895 extrainfo_free(desc_extrainfo);
1896 if (authority_signing_key)
1897 crypto_free_pk_env(authority_signing_key);
1898 if (authority_key_certificate)
1899 authority_cert_free(authority_key_certificate);
1901 if (warned_nonexistent_family) {
1902 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
1903 smartlist_free(warned_nonexistent_family);