log when we guess our ip address, not just when we fail
[tor/rransom.git] / src / or / router.c
blob56d88262d6c3d036667d1f05ec498e829c065bd2
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-2010, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 #define ROUTER_PRIVATE
9 #include "or.h"
10 #include "circuitlist.h"
11 #include "circuituse.h"
12 #include "config.h"
13 #include "connection.h"
14 #include "control.h"
15 #include "directory.h"
16 #include "dirserv.h"
17 #include "dns.h"
18 #include "geoip.h"
19 #include "hibernate.h"
20 #include "main.h"
21 #include "networkstatus.h"
22 #include "policies.h"
23 #include "relay.h"
24 #include "rephist.h"
25 #include "router.h"
26 #include "routerlist.h"
27 #include "routerparse.h"
29 /**
30 * \file router.c
31 * \brief OR functionality, including key maintenance, generating
32 * and uploading server descriptors, retrying OR connections.
33 **/
35 extern long stats_n_seconds_working;
37 /************************************************************/
39 /*****
40 * Key management: ORs only.
41 *****/
43 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
45 static tor_mutex_t *key_lock=NULL;
46 static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
47 /** Current private onionskin decryption key: used to decode CREATE cells. */
48 static crypto_pk_env_t *onionkey=NULL;
49 /** Previous private onionskin decryption key: used to decode CREATE cells
50 * generated by clients that have an older version of our descriptor. */
51 static crypto_pk_env_t *lastonionkey=NULL;
52 /** Private "identity key": used to sign directory info and TLS
53 * certificates. Never changes. */
54 static crypto_pk_env_t *identitykey=NULL;
55 /** Digest of identitykey. */
56 static char identitykey_digest[DIGEST_LEN];
57 /** Signing key used for v3 directory material; only set for authorities. */
58 static crypto_pk_env_t *authority_signing_key = NULL;
59 /** Key certificate to authenticate v3 directory material; only set for
60 * authorities. */
61 static authority_cert_t *authority_key_certificate = NULL;
63 /** For emergency V3 authority key migration: An extra signing key that we use
64 * with our old (obsolete) identity key for a while. */
65 static crypto_pk_env_t *legacy_signing_key = NULL;
66 /** For emergency V3 authority key migration: An extra certificate to
67 * authenticate legacy_signing_key with our obsolete identity key.*/
68 static authority_cert_t *legacy_key_certificate = NULL;
70 /* (Note that v3 authorities also have a separate "authority identity key",
71 * but this key is never actually loaded by the Tor process. Instead, it's
72 * used by tor-gencert to sign new signing keys and make new key
73 * certificates. */
75 /** Replace the current onion key with <b>k</b>. Does not affect
76 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
78 static void
79 set_onion_key(crypto_pk_env_t *k)
81 tor_mutex_acquire(key_lock);
82 crypto_free_pk_env(onionkey);
83 onionkey = k;
84 onionkey_set_at = time(NULL);
85 tor_mutex_release(key_lock);
86 mark_my_descriptor_dirty();
89 /** Return the current onion key. Requires that the onion key has been
90 * loaded or generated. */
91 crypto_pk_env_t *
92 get_onion_key(void)
94 tor_assert(onionkey);
95 return onionkey;
98 /** Store a full copy of the current onion key into *<b>key</b>, and a full
99 * copy of the most recent onion key into *<b>last</b>.
101 void
102 dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
104 tor_assert(key);
105 tor_assert(last);
106 tor_mutex_acquire(key_lock);
107 tor_assert(onionkey);
108 *key = crypto_pk_copy_full(onionkey);
109 if (lastonionkey)
110 *last = crypto_pk_copy_full(lastonionkey);
111 else
112 *last = NULL;
113 tor_mutex_release(key_lock);
116 /** Return the time when the onion key was last set. This is either the time
117 * when the process launched, or the time of the most recent key rotation since
118 * the process launched.
120 time_t
121 get_onion_key_set_at(void)
123 return onionkey_set_at;
126 /** Set the current identity key to k.
128 void
129 set_identity_key(crypto_pk_env_t *k)
131 crypto_free_pk_env(identitykey);
132 identitykey = k;
133 crypto_pk_get_digest(identitykey, identitykey_digest);
136 /** Returns the current identity key; requires that the identity key has been
137 * set.
139 crypto_pk_env_t *
140 get_identity_key(void)
142 tor_assert(identitykey);
143 return identitykey;
146 /** Return true iff the identity key has been set. */
148 identity_key_is_set(void)
150 return identitykey != NULL;
153 /** Return the key certificate for this v3 (voting) authority, or NULL
154 * if we have no such certificate. */
155 authority_cert_t *
156 get_my_v3_authority_cert(void)
158 return authority_key_certificate;
161 /** Return the v3 signing key for this v3 (voting) authority, or NULL
162 * if we have no such key. */
163 crypto_pk_env_t *
164 get_my_v3_authority_signing_key(void)
166 return authority_signing_key;
169 /** If we're an authority, and we're using a legacy authority identity key for
170 * emergency migration purposes, return the certificate associated with that
171 * key. */
172 authority_cert_t *
173 get_my_v3_legacy_cert(void)
175 return legacy_key_certificate;
178 /** If we're an authority, and we're using a legacy authority identity key for
179 * emergency migration purposes, return that key. */
180 crypto_pk_env_t *
181 get_my_v3_legacy_signing_key(void)
183 return legacy_signing_key;
186 /** Replace the previous onion key with the current onion key, and generate
187 * a new previous onion key. Immediately after calling this function,
188 * the OR should:
189 * - schedule all previous cpuworkers to shut down _after_ processing
190 * pending work. (This will cause fresh cpuworkers to be generated.)
191 * - generate and upload a fresh routerinfo.
193 void
194 rotate_onion_key(void)
196 char *fname, *fname_prev;
197 crypto_pk_env_t *prkey;
198 or_state_t *state = get_or_state();
199 time_t now;
200 fname = get_datadir_fname2("keys", "secret_onion_key");
201 fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
202 if (!(prkey = crypto_new_pk_env())) {
203 log_err(LD_GENERAL,"Error constructing rotated onion key");
204 goto error;
206 if (crypto_pk_generate_key(prkey)) {
207 log_err(LD_BUG,"Error generating onion key");
208 goto error;
210 if (file_status(fname) == FN_FILE) {
211 if (replace_file(fname, fname_prev))
212 goto error;
214 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
215 log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
216 goto error;
218 log_info(LD_GENERAL, "Rotating onion key");
219 tor_mutex_acquire(key_lock);
220 crypto_free_pk_env(lastonionkey);
221 lastonionkey = onionkey;
222 onionkey = prkey;
223 now = time(NULL);
224 state->LastRotatedOnionKey = onionkey_set_at = now;
225 tor_mutex_release(key_lock);
226 mark_my_descriptor_dirty();
227 or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
228 goto done;
229 error:
230 log_warn(LD_GENERAL, "Couldn't rotate onion key.");
231 if (prkey)
232 crypto_free_pk_env(prkey);
233 done:
234 tor_free(fname);
235 tor_free(fname_prev);
238 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
239 * and <b>generate</b> is true, create a new RSA key and save it in
240 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
241 * errors at level <b>severity</b>.
243 crypto_pk_env_t *
244 init_key_from_file(const char *fname, int generate, int severity)
246 crypto_pk_env_t *prkey = NULL;
248 if (!(prkey = crypto_new_pk_env())) {
249 log(severity, LD_GENERAL,"Error constructing key");
250 goto error;
253 switch (file_status(fname)) {
254 case FN_DIR:
255 case FN_ERROR:
256 log(severity, LD_FS,"Can't read key from \"%s\"", fname);
257 goto error;
258 case FN_NOENT:
259 if (generate) {
260 if (!have_lockfile()) {
261 if (try_locking(get_options(), 0)<0) {
262 /* Make sure that --list-fingerprint only creates new keys
263 * if there is no possibility for a deadlock. */
264 log(severity, LD_FS, "Another Tor process has locked \"%s\". Not "
265 "writing any new keys.", fname);
266 /*XXXX The 'other process' might make a key in a second or two;
267 * maybe we should wait for it. */
268 goto error;
271 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
272 fname);
273 if (crypto_pk_generate_key(prkey)) {
274 log(severity, LD_GENERAL,"Error generating onion key");
275 goto error;
277 if (crypto_pk_check_key(prkey) <= 0) {
278 log(severity, LD_GENERAL,"Generated key seems invalid");
279 goto error;
281 log_info(LD_GENERAL, "Generated key seems valid");
282 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
283 log(severity, LD_FS,
284 "Couldn't write generated key to \"%s\".", fname);
285 goto error;
287 } else {
288 log_info(LD_GENERAL, "No key found in \"%s\"", fname);
290 return prkey;
291 case FN_FILE:
292 if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
293 log(severity, LD_GENERAL,"Error loading private key.");
294 goto error;
296 return prkey;
297 default:
298 tor_assert(0);
301 error:
302 if (prkey)
303 crypto_free_pk_env(prkey);
304 return NULL;
307 /** Try to load the vote-signing private key and certificate for being a v3
308 * directory authority, and make sure they match. If <b>legacy</b>, load a
309 * legacy key/cert set for emergency key migration; otherwise load the regular
310 * key/cert set. On success, store them into *<b>key_out</b> and
311 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
312 static int
313 load_authority_keyset(int legacy, crypto_pk_env_t **key_out,
314 authority_cert_t **cert_out)
316 int r = -1;
317 char *fname = NULL, *cert = NULL;
318 const char *eos = NULL;
319 crypto_pk_env_t *signing_key = NULL;
320 authority_cert_t *parsed = NULL;
322 fname = get_datadir_fname2("keys",
323 legacy ? "legacy_signing_key" : "authority_signing_key");
324 signing_key = init_key_from_file(fname, 0, LOG_INFO);
325 if (!signing_key) {
326 log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
327 goto done;
329 tor_free(fname);
330 fname = get_datadir_fname2("keys",
331 legacy ? "legacy_certificate" : "authority_certificate");
332 cert = read_file_to_str(fname, 0, NULL);
333 if (!cert) {
334 log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
335 fname);
336 goto done;
338 parsed = authority_cert_parse_from_string(cert, &eos);
339 if (!parsed) {
340 log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
341 goto done;
343 if (crypto_pk_cmp_keys(signing_key, parsed->signing_key) != 0) {
344 log_warn(LD_DIR, "Stored signing key does not match signing key in "
345 "certificate");
346 goto done;
349 crypto_free_pk_env(*key_out);
350 authority_cert_free(*cert_out);
352 *key_out = signing_key;
353 *cert_out = parsed;
354 r = 0;
355 signing_key = NULL;
356 parsed = NULL;
358 done:
359 tor_free(fname);
360 tor_free(cert);
361 crypto_free_pk_env(signing_key);
362 authority_cert_free(parsed);
363 return r;
366 /** Load the v3 (voting) authority signing key and certificate, if they are
367 * present. Return -1 if anything is missing, mismatched, or unloadable;
368 * return 0 on success. */
369 static int
370 init_v3_authority_keys(void)
372 if (load_authority_keyset(0, &authority_signing_key,
373 &authority_key_certificate)<0)
374 return -1;
376 if (get_options()->V3AuthUseLegacyKey &&
377 load_authority_keyset(1, &legacy_signing_key,
378 &legacy_key_certificate)<0)
379 return -1;
381 return 0;
384 /** If we're a v3 authority, check whether we have a certificate that's
385 * likely to expire soon. Warn if we do, but not too often. */
386 void
387 v3_authority_check_key_expiry(void)
389 time_t now, expires;
390 static time_t last_warned = 0;
391 int badness, time_left, warn_interval;
392 if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
393 return;
395 now = time(NULL);
396 expires = authority_key_certificate->expires;
397 time_left = (int)( expires - now );
398 if (time_left <= 0) {
399 badness = LOG_ERR;
400 warn_interval = 60*60;
401 } else if (time_left <= 24*60*60) {
402 badness = LOG_WARN;
403 warn_interval = 60*60;
404 } else if (time_left <= 24*60*60*7) {
405 badness = LOG_WARN;
406 warn_interval = 24*60*60;
407 } else if (time_left <= 24*60*60*30) {
408 badness = LOG_WARN;
409 warn_interval = 24*60*60*5;
410 } else {
411 return;
414 if (last_warned + warn_interval > now)
415 return;
417 if (time_left <= 0) {
418 log(badness, LD_DIR, "Your v3 authority certificate has expired."
419 " Generate a new one NOW.");
420 } else if (time_left <= 24*60*60) {
421 log(badness, LD_DIR, "Your v3 authority certificate expires in %d hours;"
422 " Generate a new one NOW.", time_left/(60*60));
423 } else {
424 log(badness, LD_DIR, "Your v3 authority certificate expires in %d days;"
425 " Generate a new one soon.", time_left/(24*60*60));
427 last_warned = now;
430 /** Initialize all OR private keys, and the TLS context, as necessary.
431 * On OPs, this only initializes the tls context. Return 0 on success,
432 * or -1 if Tor should die.
435 init_keys(void)
437 char *keydir;
438 char fingerprint[FINGERPRINT_LEN+1];
439 /*nickname<space>fp\n\0 */
440 char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
441 const char *mydesc;
442 crypto_pk_env_t *prkey;
443 char digest[20];
444 char v3_digest[20];
445 char *cp;
446 or_options_t *options = get_options();
447 authority_type_t type;
448 time_t now = time(NULL);
449 trusted_dir_server_t *ds;
450 int v3_digest_set = 0;
451 authority_cert_t *cert = NULL;
453 if (!key_lock)
454 key_lock = tor_mutex_new();
456 /* There are a couple of paths that put us here before */
457 if (crypto_global_init(get_options()->HardwareAccel,
458 get_options()->AccelName,
459 get_options()->AccelDir)) {
460 log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
461 return -1;
464 /* OP's don't need persistent keys; just make up an identity and
465 * initialize the TLS context. */
466 if (!server_mode(options)) {
467 if (!(prkey = crypto_new_pk_env()))
468 return -1;
469 if (crypto_pk_generate_key(prkey)) {
470 crypto_free_pk_env(prkey);
471 return -1;
473 set_identity_key(prkey);
474 /* Create a TLS context; default the client nickname to "client". */
475 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
476 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
477 return -1;
479 return 0;
481 /* Make sure DataDirectory exists, and is private. */
482 if (check_private_dir(options->DataDirectory, CPD_CREATE)) {
483 return -1;
485 /* Check the key directory. */
486 keydir = get_datadir_fname("keys");
487 if (check_private_dir(keydir, CPD_CREATE)) {
488 tor_free(keydir);
489 return -1;
491 tor_free(keydir);
493 /* 1a. Read v3 directory authority key/cert information. */
494 memset(v3_digest, 0, sizeof(v3_digest));
495 if (authdir_mode_v3(options)) {
496 if (init_v3_authority_keys()<0) {
497 log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
498 "were unable to load our v3 authority keys and certificate! "
499 "Use tor-gencert to generate them. Dying.");
500 return -1;
502 cert = get_my_v3_authority_cert();
503 if (cert) {
504 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
505 v3_digest);
506 v3_digest_set = 1;
510 /* 1. Read identity key. Make it if none is found. */
511 keydir = get_datadir_fname2("keys", "secret_id_key");
512 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
513 prkey = init_key_from_file(keydir, 1, LOG_ERR);
514 tor_free(keydir);
515 if (!prkey) return -1;
516 set_identity_key(prkey);
518 /* 2. Read onion key. Make it if none is found. */
519 keydir = get_datadir_fname2("keys", "secret_onion_key");
520 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
521 prkey = init_key_from_file(keydir, 1, LOG_ERR);
522 tor_free(keydir);
523 if (!prkey) return -1;
524 set_onion_key(prkey);
525 if (options->command == CMD_RUN_TOR) {
526 /* only mess with the state file if we're actually running Tor */
527 or_state_t *state = get_or_state();
528 if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
529 /* We allow for some parsing slop, but we don't want to risk accepting
530 * values in the distant future. If we did, we might never rotate the
531 * onion key. */
532 onionkey_set_at = state->LastRotatedOnionKey;
533 } else {
534 /* We have no LastRotatedOnionKey set; either we just created the key
535 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
536 * start the clock ticking now so that we will eventually rotate it even
537 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
538 state->LastRotatedOnionKey = onionkey_set_at = now;
539 or_state_mark_dirty(state, options->AvoidDiskWrites ?
540 time(NULL)+3600 : 0);
544 keydir = get_datadir_fname2("keys", "secret_onion_key.old");
545 if (!lastonionkey && file_status(keydir) == FN_FILE) {
546 prkey = init_key_from_file(keydir, 1, LOG_ERR);
547 if (prkey)
548 lastonionkey = prkey;
550 tor_free(keydir);
552 /* 3. Initialize link key and TLS context. */
553 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
554 log_err(LD_GENERAL,"Error initializing TLS context");
555 return -1;
557 /* 4. Build our router descriptor. */
558 /* Must be called after keys are initialized. */
559 mydesc = router_get_my_descriptor();
560 if (authdir_mode(options)) {
561 const char *m = NULL;
562 routerinfo_t *ri;
563 /* We need to add our own fingerprint so it gets recognized. */
564 if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
565 log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
566 return -1;
568 if (mydesc) {
569 ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
570 if (!ri) {
571 log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
572 return -1;
574 if (!WRA_WAS_ADDED(dirserv_add_descriptor(ri, &m, "self"))) {
575 log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
576 m?m:"<unknown error>");
577 return -1;
582 /* 5. Dump fingerprint to 'fingerprint' */
583 keydir = get_datadir_fname("fingerprint");
584 log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
585 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 0)<0) {
586 log_err(LD_GENERAL,"Error computing fingerprint");
587 tor_free(keydir);
588 return -1;
590 tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
591 if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
592 "%s %s\n",options->Nickname, fingerprint) < 0) {
593 log_err(LD_GENERAL,"Error writing fingerprint line");
594 tor_free(keydir);
595 return -1;
597 /* Check whether we need to write the fingerprint file. */
598 cp = NULL;
599 if (file_status(keydir) == FN_FILE)
600 cp = read_file_to_str(keydir, 0, NULL);
601 if (!cp || strcmp(cp, fingerprint_line)) {
602 if (write_str_to_file(keydir, fingerprint_line, 0)) {
603 log_err(LD_FS, "Error writing fingerprint line to file");
604 tor_free(keydir);
605 tor_free(cp);
606 return -1;
609 tor_free(cp);
610 tor_free(keydir);
612 log(LOG_NOTICE, LD_GENERAL,
613 "Your Tor server's identity key fingerprint is '%s %s'",
614 options->Nickname, fingerprint);
615 if (!authdir_mode(options))
616 return 0;
617 /* 6. [authdirserver only] load approved-routers file */
618 if (dirserv_load_fingerprint_file() < 0) {
619 log_err(LD_GENERAL,"Error loading fingerprints");
620 return -1;
622 /* 6b. [authdirserver only] add own key to approved directories. */
623 crypto_pk_get_digest(get_identity_key(), digest);
624 type = ((options->V1AuthoritativeDir ? V1_AUTHORITY : NO_AUTHORITY) |
625 (options->V2AuthoritativeDir ? V2_AUTHORITY : NO_AUTHORITY) |
626 (options->V3AuthoritativeDir ? V3_AUTHORITY : NO_AUTHORITY) |
627 (options->BridgeAuthoritativeDir ? BRIDGE_AUTHORITY : NO_AUTHORITY) |
628 (options->HSAuthoritativeDir ? HIDSERV_AUTHORITY : NO_AUTHORITY));
630 ds = router_get_trusteddirserver_by_digest(digest);
631 if (!ds) {
632 ds = add_trusted_dir_server(options->Nickname, NULL,
633 (uint16_t)options->DirPort,
634 (uint16_t)options->ORPort,
635 digest,
636 v3_digest,
637 type);
638 if (!ds) {
639 log_err(LD_GENERAL,"We want to be a directory authority, but we "
640 "couldn't add ourselves to the authority list. Failing.");
641 return -1;
644 if (ds->type != type) {
645 log_warn(LD_DIR, "Configured authority type does not match authority "
646 "type in DirServer list. Adjusting. (%d v %d)",
647 type, ds->type);
648 ds->type = type;
650 if (v3_digest_set && (ds->type & V3_AUTHORITY) &&
651 memcmp(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
652 log_warn(LD_DIR, "V3 identity key does not match identity declared in "
653 "DirServer line. Adjusting.");
654 memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
657 if (cert) { /* add my own cert to the list of known certs */
658 log_info(LD_DIR, "adding my own v3 cert");
659 if (trusted_dirs_load_certs_from_string(
660 cert->cache_info.signed_descriptor_body, 0, 0)<0) {
661 log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
662 return -1;
666 return 0; /* success */
669 /* Keep track of whether we should upload our server descriptor,
670 * and what type of server we are.
673 /** Whether we can reach our ORPort from the outside. */
674 static int can_reach_or_port = 0;
675 /** Whether we can reach our DirPort from the outside. */
676 static int can_reach_dir_port = 0;
678 /** Forget what we have learned about our reachability status. */
679 void
680 router_reset_reachability(void)
682 can_reach_or_port = can_reach_dir_port = 0;
685 /** Return 1 if ORPort is known reachable; else return 0. */
687 check_whether_orport_reachable(void)
689 or_options_t *options = get_options();
690 return options->AssumeReachable ||
691 can_reach_or_port;
694 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
696 check_whether_dirport_reachable(void)
698 or_options_t *options = get_options();
699 return !options->DirPort ||
700 options->AssumeReachable ||
701 we_are_hibernating() ||
702 can_reach_dir_port;
705 /** Look at a variety of factors, and return 0 if we don't want to
706 * advertise the fact that we have a DirPort open. Else return the
707 * DirPort we want to advertise.
709 * Log a helpful message if we change our mind about whether to publish
710 * a DirPort.
712 static int
713 decide_to_advertise_dirport(or_options_t *options, uint16_t dir_port)
715 static int advertising=1; /* start out assuming we will advertise */
716 int new_choice=1;
717 const char *reason = NULL;
719 /* Section one: reasons to publish or not publish that aren't
720 * worth mentioning to the user, either because they're obvious
721 * or because they're normal behavior. */
723 if (!dir_port) /* short circuit the rest of the function */
724 return 0;
725 if (authdir_mode(options)) /* always publish */
726 return dir_port;
727 if (we_are_hibernating())
728 return 0;
729 if (!check_whether_dirport_reachable())
730 return 0;
732 /* Section two: reasons to publish or not publish that the user
733 * might find surprising. These are generally config options that
734 * make us choose not to publish. */
736 if (accounting_is_enabled(options)) {
737 /* if we might potentially hibernate */
738 new_choice = 0;
739 reason = "AccountingMax enabled";
740 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
741 } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
742 (options->RelayBandwidthRate > 0 &&
743 options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
744 /* if we're advertising a small amount */
745 new_choice = 0;
746 reason = "BandwidthRate under 50KB";
749 if (advertising != new_choice) {
750 if (new_choice == 1) {
751 log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
752 } else {
753 tor_assert(reason);
754 log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
756 advertising = new_choice;
759 return advertising ? dir_port : 0;
762 /** Some time has passed, or we just got new directory information.
763 * See if we currently believe our ORPort or DirPort to be
764 * unreachable. If so, launch a new test for it.
766 * For ORPort, we simply try making a circuit that ends at ourselves.
767 * Success is noticed in onionskin_answer().
769 * For DirPort, we make a connection via Tor to our DirPort and ask
770 * for our own server descriptor.
771 * Success is noticed in connection_dir_client_reached_eof().
773 void
774 consider_testing_reachability(int test_or, int test_dir)
776 routerinfo_t *me = router_get_my_routerinfo();
777 int orport_reachable = check_whether_orport_reachable();
778 tor_addr_t addr;
779 if (!me)
780 return;
782 if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
783 log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
784 !orport_reachable ? "reachability" : "bandwidth",
785 me->address, me->or_port);
786 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me,
787 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
790 tor_addr_from_ipv4h(&addr, me->addr);
791 if (test_dir && !check_whether_dirport_reachable() &&
792 !connection_get_by_type_addr_port_purpose(
793 CONN_TYPE_DIR, &addr, me->dir_port,
794 DIR_PURPOSE_FETCH_SERVERDESC)) {
795 /* ask myself, via tor, for my server descriptor. */
796 directory_initiate_command(me->address, &addr,
797 me->or_port, me->dir_port,
798 0, /* does not matter */
799 0, me->cache_info.identity_digest,
800 DIR_PURPOSE_FETCH_SERVERDESC,
801 ROUTER_PURPOSE_GENERAL,
802 1, "authority.z", NULL, 0, 0);
806 /** Annotate that we found our ORPort reachable. */
807 void
808 router_orport_found_reachable(void)
810 if (!can_reach_or_port) {
811 routerinfo_t *me = router_get_my_routerinfo();
812 log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
813 "the outside. Excellent.%s",
814 get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
815 " Publishing server descriptor." : "");
816 can_reach_or_port = 1;
817 mark_my_descriptor_dirty();
818 if (!me) { /* should never happen */
819 log_warn(LD_BUG, "ORPort found reachable, but I have no routerinfo "
820 "yet. Failing to inform controller of success.");
821 return;
823 control_event_server_status(LOG_NOTICE,
824 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
825 me->address, me->or_port);
829 /** Annotate that we found our DirPort reachable. */
830 void
831 router_dirport_found_reachable(void)
833 if (!can_reach_dir_port) {
834 routerinfo_t *me = router_get_my_routerinfo();
835 log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
836 "from the outside. Excellent.");
837 can_reach_dir_port = 1;
838 if (!me || decide_to_advertise_dirport(get_options(), me->dir_port))
839 mark_my_descriptor_dirty();
840 if (!me) { /* should never happen */
841 log_warn(LD_BUG, "DirPort found reachable, but I have no routerinfo "
842 "yet. Failing to inform controller of success.");
843 return;
845 control_event_server_status(LOG_NOTICE,
846 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
847 me->address, me->dir_port);
851 /** We have enough testing circuits open. Send a bunch of "drop"
852 * cells down each of them, to exercise our bandwidth. */
853 void
854 router_perform_bandwidth_test(int num_circs, time_t now)
856 int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
857 int max_cells = num_cells < CIRCWINDOW_START ?
858 num_cells : CIRCWINDOW_START;
859 int cells_per_circuit = max_cells / num_circs;
860 origin_circuit_t *circ = NULL;
862 log_notice(LD_OR,"Performing bandwidth self-test...done.");
863 while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
864 CIRCUIT_PURPOSE_TESTING))) {
865 /* dump cells_per_circuit drop cells onto this circ */
866 int i = cells_per_circuit;
867 if (circ->_base.state != CIRCUIT_STATE_OPEN)
868 continue;
869 circ->_base.timestamp_dirty = now;
870 while (i-- > 0) {
871 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
872 RELAY_COMMAND_DROP,
873 NULL, 0, circ->cpath->prev)<0) {
874 return; /* stop if error */
880 /** Return true iff we believe ourselves to be an authoritative
881 * directory server.
884 authdir_mode(or_options_t *options)
886 return options->AuthoritativeDir != 0;
888 /** Return true iff we believe ourselves to be a v1 authoritative
889 * directory server.
892 authdir_mode_v1(or_options_t *options)
894 return authdir_mode(options) && options->V1AuthoritativeDir != 0;
896 /** Return true iff we believe ourselves to be a v2 authoritative
897 * directory server.
900 authdir_mode_v2(or_options_t *options)
902 return authdir_mode(options) && options->V2AuthoritativeDir != 0;
904 /** Return true iff we believe ourselves to be a v3 authoritative
905 * directory server.
908 authdir_mode_v3(or_options_t *options)
910 return authdir_mode(options) && options->V3AuthoritativeDir != 0;
912 /** Return true iff we are a v1, v2, or v3 directory authority. */
914 authdir_mode_any_main(or_options_t *options)
916 return options->V1AuthoritativeDir ||
917 options->V2AuthoritativeDir ||
918 options->V3AuthoritativeDir;
920 /** Return true if we believe ourselves to be any kind of
921 * authoritative directory beyond just a hidserv authority. */
923 authdir_mode_any_nonhidserv(or_options_t *options)
925 return options->BridgeAuthoritativeDir ||
926 authdir_mode_any_main(options);
928 /** Return true iff we are an authoritative directory server that is
929 * authoritative about receiving and serving descriptors of type
930 * <b>purpose</b> its dirport. Use -1 for "any purpose". */
932 authdir_mode_handles_descs(or_options_t *options, int purpose)
934 if (purpose < 0)
935 return authdir_mode_any_nonhidserv(options);
936 else if (purpose == ROUTER_PURPOSE_GENERAL)
937 return authdir_mode_any_main(options);
938 else if (purpose == ROUTER_PURPOSE_BRIDGE)
939 return (options->BridgeAuthoritativeDir);
940 else
941 return 0;
943 /** Return true iff we are an authoritative directory server that
944 * publishes its own network statuses.
947 authdir_mode_publishes_statuses(or_options_t *options)
949 if (authdir_mode_bridge(options))
950 return 0;
951 return authdir_mode_any_nonhidserv(options);
953 /** Return true iff we are an authoritative directory server that
954 * tests reachability of the descriptors it learns about.
957 authdir_mode_tests_reachability(or_options_t *options)
959 return authdir_mode_handles_descs(options, -1);
961 /** Return true iff we believe ourselves to be a bridge authoritative
962 * directory server.
965 authdir_mode_bridge(or_options_t *options)
967 return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
970 /** Return true iff we are trying to be a server.
973 server_mode(or_options_t *options)
975 if (options->ClientOnly) return 0;
976 return (options->ORPort != 0 || options->ORListenAddress);
979 /** Return true iff the combination of options in <b>options</b> and parameters
980 * in the consensus mean that we don't want to allow exits from circuits
981 * we got from addresses not known to be servers. */
983 should_refuse_unknown_exits(or_options_t *options)
985 if (options->RefuseUnknownExits_ != -1) {
986 return options->RefuseUnknownExits_;
987 } else {
988 return networkstatus_get_param(NULL, "refuseunknownexits", 1);
992 /** Remember if we've advertised ourselves to the dirservers. */
993 static int server_is_advertised=0;
995 /** Return true iff we have published our descriptor lately.
998 advertised_server_mode(void)
1000 return server_is_advertised;
1004 * Called with a boolean: set whether we have recently published our
1005 * descriptor.
1007 static void
1008 set_server_advertised(int s)
1010 server_is_advertised = s;
1013 /** Return true iff we are trying to be a socks proxy. */
1015 proxy_mode(or_options_t *options)
1017 return (options->SocksPort != 0 || options->SocksListenAddress ||
1018 options->TransPort != 0 || options->TransListenAddress ||
1019 options->NatdPort != 0 || options->NatdListenAddress ||
1020 options->DNSPort != 0 || options->DNSListenAddress);
1023 /** Decide if we're a publishable server. We are a publishable server if:
1024 * - We don't have the ClientOnly option set
1025 * and
1026 * - We have the PublishServerDescriptor option set to non-empty
1027 * and
1028 * - We have ORPort set
1029 * and
1030 * - We believe we are reachable from the outside; or
1031 * - We are an authoritative directory server.
1033 static int
1034 decide_if_publishable_server(void)
1036 or_options_t *options = get_options();
1038 if (options->ClientOnly)
1039 return 0;
1040 if (options->_PublishServerDescriptor == NO_AUTHORITY)
1041 return 0;
1042 if (!server_mode(options))
1043 return 0;
1044 if (authdir_mode(options))
1045 return 1;
1047 return check_whether_orport_reachable();
1050 /** Initiate server descriptor upload as reasonable (if server is publishable,
1051 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1053 * We need to rebuild the descriptor if it's dirty even if we're not
1054 * uploading, because our reachability testing *uses* our descriptor to
1055 * determine what IP address and ports to test.
1057 void
1058 consider_publishable_server(int force)
1060 int rebuilt;
1062 if (!server_mode(get_options()))
1063 return;
1065 rebuilt = router_rebuild_descriptor(0);
1066 if (decide_if_publishable_server()) {
1067 set_server_advertised(1);
1068 if (rebuilt == 0)
1069 router_upload_dir_desc_to_dirservers(force);
1070 } else {
1071 set_server_advertised(0);
1076 * OR descriptor generation.
1079 /** My routerinfo. */
1080 static routerinfo_t *desc_routerinfo = NULL;
1081 /** My extrainfo */
1082 static extrainfo_t *desc_extrainfo = NULL;
1083 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1084 * now. */
1085 static time_t desc_clean_since = 0;
1086 /** Boolean: do we need to regenerate the above? */
1087 static int desc_needs_upload = 0;
1089 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1090 * descriptor successfully yet, try to upload our signed descriptor to
1091 * all the directory servers we know about.
1093 void
1094 router_upload_dir_desc_to_dirservers(int force)
1096 routerinfo_t *ri;
1097 extrainfo_t *ei;
1098 char *msg;
1099 size_t desc_len, extra_len = 0, total_len;
1100 authority_type_t auth = get_options()->_PublishServerDescriptor;
1102 ri = router_get_my_routerinfo();
1103 if (!ri) {
1104 log_info(LD_GENERAL, "No descriptor; skipping upload");
1105 return;
1107 ei = router_get_my_extrainfo();
1108 if (auth == NO_AUTHORITY)
1109 return;
1110 if (!force && !desc_needs_upload)
1111 return;
1112 desc_needs_upload = 0;
1114 desc_len = ri->cache_info.signed_descriptor_len;
1115 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1116 total_len = desc_len + extra_len + 1;
1117 msg = tor_malloc(total_len);
1118 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1119 if (ei) {
1120 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1122 msg[desc_len+extra_len] = 0;
1124 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
1125 (auth & BRIDGE_AUTHORITY) ?
1126 ROUTER_PURPOSE_BRIDGE :
1127 ROUTER_PURPOSE_GENERAL,
1128 auth, msg, desc_len, extra_len);
1129 tor_free(msg);
1132 /** OR only: Check whether my exit policy says to allow connection to
1133 * conn. Return 0 if we accept; non-0 if we reject.
1136 router_compare_to_my_exit_policy(edge_connection_t *conn)
1138 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1139 return -1;
1141 /* make sure it's resolved to something. this way we can't get a
1142 'maybe' below. */
1143 if (tor_addr_is_null(&conn->_base.addr))
1144 return -1;
1146 /* XXXX IPv6 */
1147 if (tor_addr_family(&conn->_base.addr) != AF_INET)
1148 return -1;
1150 return compare_tor_addr_to_addr_policy(&conn->_base.addr, conn->_base.port,
1151 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
1154 /** Return true iff my exit policy is reject *:*. Return -1 if we don't
1155 * have a descriptor */
1157 router_my_exit_policy_is_reject_star(void)
1159 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1160 return -1;
1162 return desc_routerinfo->policy_is_reject_star;
1165 /** Return true iff I'm a server and <b>digest</b> is equal to
1166 * my identity digest. */
1168 router_digest_is_me(const char *digest)
1170 return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
1173 /** Return true iff I'm a server and <b>digest</b> is equal to
1174 * my identity digest. */
1176 router_extrainfo_digest_is_me(const char *digest)
1178 extrainfo_t *ei = router_get_my_extrainfo();
1179 if (!ei)
1180 return 0;
1182 return !memcmp(digest,
1183 ei->cache_info.signed_descriptor_digest,
1184 DIGEST_LEN);
1187 /** A wrapper around router_digest_is_me(). */
1189 router_is_me(routerinfo_t *router)
1191 return router_digest_is_me(router->cache_info.identity_digest);
1194 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1196 router_fingerprint_is_me(const char *fp)
1198 char digest[DIGEST_LEN];
1199 if (strlen(fp) == HEX_DIGEST_LEN &&
1200 base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
1201 return router_digest_is_me(digest);
1203 return 0;
1206 /** Return a routerinfo for this OR, rebuilding a fresh one if
1207 * necessary. Return NULL on error, or if called on an OP. */
1208 routerinfo_t *
1209 router_get_my_routerinfo(void)
1211 if (!server_mode(get_options()))
1212 return NULL;
1213 if (router_rebuild_descriptor(0))
1214 return NULL;
1215 return desc_routerinfo;
1218 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1219 * one if necessary. Return NULL on error.
1221 const char *
1222 router_get_my_descriptor(void)
1224 const char *body;
1225 if (!router_get_my_routerinfo())
1226 return NULL;
1227 /* Make sure this is nul-terminated. */
1228 tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
1229 body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
1230 tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
1231 log_debug(LD_GENERAL,"my desc is '%s'", body);
1232 return body;
1235 /** Return the extrainfo document for this OR, or NULL if we have none.
1236 * Rebuilt it (and the server descriptor) if necessary. */
1237 extrainfo_t *
1238 router_get_my_extrainfo(void)
1240 if (!server_mode(get_options()))
1241 return NULL;
1242 if (router_rebuild_descriptor(0))
1243 return NULL;
1244 return desc_extrainfo;
1247 /** A list of nicknames that we've warned about including in our family
1248 * declaration verbatim rather than as digests. */
1249 static smartlist_t *warned_nonexistent_family = NULL;
1251 static int router_guess_address_from_dir_headers(uint32_t *guess);
1253 /** Make a current best guess at our address, either because
1254 * it's configured in torrc, or because we've learned it from
1255 * dirserver headers. Place the answer in *<b>addr</b> and return
1256 * 0 on success, else return -1 if we have no guess. */
1258 router_pick_published_address(or_options_t *options, uint32_t *addr)
1260 char buf[INET_NTOA_BUF_LEN];
1261 struct in_addr a;
1262 if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
1263 log_info(LD_CONFIG, "Could not determine our address locally. "
1264 "Checking if directory headers provide any hints.");
1265 if (router_guess_address_from_dir_headers(addr) < 0) {
1266 log_info(LD_CONFIG, "No hints from directory headers either. "
1267 "Will try again later.");
1268 return -1;
1271 a.s_addr = htonl(*addr);
1272 tor_inet_ntoa(&a, buf, sizeof(buf));
1273 log_info(LD_CONFIG,"Success: chose address '%s'.", buf);
1274 return 0;
1277 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1278 * routerinfo, signed server descriptor, and extra-info document for this OR.
1279 * Return 0 on success, -1 on temporary error.
1282 router_rebuild_descriptor(int force)
1284 routerinfo_t *ri;
1285 extrainfo_t *ei;
1286 uint32_t addr;
1287 char platform[256];
1288 int hibernating = we_are_hibernating();
1289 size_t ei_size;
1290 or_options_t *options = get_options();
1292 if (desc_clean_since && !force)
1293 return 0;
1295 if (router_pick_published_address(options, &addr) < 0) {
1296 /* Stop trying to rebuild our descriptor every second. We'll
1297 * learn that it's time to try again when server_has_changed_ip()
1298 * marks it dirty. */
1299 desc_clean_since = time(NULL);
1300 return -1;
1303 ri = tor_malloc_zero(sizeof(routerinfo_t));
1304 ri->cache_info.routerlist_index = -1;
1305 ri->address = tor_dup_ip(addr);
1306 ri->nickname = tor_strdup(options->Nickname);
1307 ri->addr = addr;
1308 ri->or_port = options->ORPort;
1309 ri->dir_port = options->DirPort;
1310 ri->cache_info.published_on = time(NULL);
1311 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
1312 * main thread */
1313 ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
1314 if (crypto_pk_get_digest(ri->identity_pkey,
1315 ri->cache_info.identity_digest)<0) {
1316 routerinfo_free(ri);
1317 return -1;
1319 get_platform_str(platform, sizeof(platform));
1320 ri->platform = tor_strdup(platform);
1322 /* compute ri->bandwidthrate as the min of various options */
1323 ri->bandwidthrate = get_effective_bwrate(options);
1325 /* and compute ri->bandwidthburst similarly */
1326 ri->bandwidthburst = get_effective_bwburst(options);
1328 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
1330 policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
1331 options->ExitPolicyRejectPrivate,
1332 ri->address, !options->BridgeRelay);
1333 ri->policy_is_reject_star =
1334 policy_is_reject_star(ri->exit_policy);
1336 if (desc_routerinfo) { /* inherit values */
1337 ri->is_valid = desc_routerinfo->is_valid;
1338 ri->is_running = desc_routerinfo->is_running;
1339 ri->is_named = desc_routerinfo->is_named;
1341 if (authdir_mode(options))
1342 ri->is_valid = ri->is_named = 1; /* believe in yourself */
1343 if (options->MyFamily) {
1344 smartlist_t *family;
1345 if (!warned_nonexistent_family)
1346 warned_nonexistent_family = smartlist_create();
1347 family = smartlist_create();
1348 ri->declared_family = smartlist_create();
1349 smartlist_split_string(family, options->MyFamily, ",",
1350 SPLIT_SKIP_SPACE|SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1351 SMARTLIST_FOREACH(family, char *, name,
1353 routerinfo_t *member;
1354 if (!strcasecmp(name, options->Nickname))
1355 member = ri;
1356 else
1357 member = router_get_by_nickname(name, 1);
1358 if (!member) {
1359 int is_legal = is_legal_nickname_or_hexdigest(name);
1360 if (!smartlist_string_isin(warned_nonexistent_family, name) &&
1361 !is_legal_hexdigest(name)) {
1362 if (is_legal)
1363 log_warn(LD_CONFIG,
1364 "I have no descriptor for the router named \"%s\" in my "
1365 "declared family; I'll use the nickname as is, but "
1366 "this may confuse clients.", name);
1367 else
1368 log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
1369 "declared family, but that isn't a legal nickname. "
1370 "Skipping it.", escaped(name));
1371 smartlist_add(warned_nonexistent_family, tor_strdup(name));
1373 if (is_legal) {
1374 smartlist_add(ri->declared_family, name);
1375 name = NULL;
1377 } else if (router_is_me(member)) {
1378 /* Don't list ourself in our own family; that's redundant */
1379 } else {
1380 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1381 fp[0] = '$';
1382 base16_encode(fp+1,HEX_DIGEST_LEN+1,
1383 member->cache_info.identity_digest, DIGEST_LEN);
1384 smartlist_add(ri->declared_family, fp);
1385 if (smartlist_string_isin(warned_nonexistent_family, name))
1386 smartlist_string_remove(warned_nonexistent_family, name);
1388 tor_free(name);
1391 /* remove duplicates from the list */
1392 smartlist_sort_strings(ri->declared_family);
1393 smartlist_uniq_strings(ri->declared_family);
1395 smartlist_free(family);
1398 /* Now generate the extrainfo. */
1399 ei = tor_malloc_zero(sizeof(extrainfo_t));
1400 ei->cache_info.is_extrainfo = 1;
1401 strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
1402 ei->cache_info.published_on = ri->cache_info.published_on;
1403 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
1404 DIGEST_LEN);
1405 ei_size = options->ExtraInfoStatistics ? MAX_EXTRAINFO_UPLOAD_SIZE : 8192;
1406 ei->cache_info.signed_descriptor_body = tor_malloc(ei_size);
1407 if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body,
1408 ei_size, ei, get_identity_key()) < 0) {
1409 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
1410 routerinfo_free(ri);
1411 extrainfo_free(ei);
1412 return -1;
1414 ei->cache_info.signed_descriptor_len =
1415 strlen(ei->cache_info.signed_descriptor_body);
1416 router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
1417 ei->cache_info.signed_descriptor_digest);
1419 /* Now finish the router descriptor. */
1420 memcpy(ri->cache_info.extra_info_digest,
1421 ei->cache_info.signed_descriptor_digest,
1422 DIGEST_LEN);
1423 ri->cache_info.signed_descriptor_body = tor_malloc(8192);
1424 if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
1425 ri, get_identity_key())<0) {
1426 log_warn(LD_BUG, "Couldn't generate router descriptor.");
1427 routerinfo_free(ri);
1428 extrainfo_free(ei);
1429 return -1;
1431 ri->cache_info.signed_descriptor_len =
1432 strlen(ri->cache_info.signed_descriptor_body);
1434 ri->purpose =
1435 options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
1436 ri->cache_info.send_unencrypted = 1;
1437 /* Let bridges serve their own descriptors unencrypted, so they can
1438 * pass reachability testing. (If they want to be harder to notice,
1439 * they can always leave the DirPort off). */
1440 if (!options->BridgeRelay)
1441 ei->cache_info.send_unencrypted = 1;
1443 router_get_router_hash(ri->cache_info.signed_descriptor_body,
1444 strlen(ri->cache_info.signed_descriptor_body),
1445 ri->cache_info.signed_descriptor_digest);
1447 routerinfo_set_country(ri);
1449 tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
1451 routerinfo_free(desc_routerinfo);
1452 desc_routerinfo = ri;
1453 extrainfo_free(desc_extrainfo);
1454 desc_extrainfo = ei;
1456 desc_clean_since = time(NULL);
1457 desc_needs_upload = 1;
1458 control_event_my_descriptor_changed();
1459 return 0;
1462 /** Mark descriptor out of date if it's older than <b>when</b> */
1463 void
1464 mark_my_descriptor_dirty_if_older_than(time_t when)
1466 if (desc_clean_since < when)
1467 mark_my_descriptor_dirty();
1470 /** Call when the current descriptor is out of date. */
1471 void
1472 mark_my_descriptor_dirty(void)
1474 desc_clean_since = 0;
1477 /** How frequently will we republish our descriptor because of large (factor
1478 * of 2) shifts in estimated bandwidth? */
1479 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
1481 /** Check whether bandwidth has changed a lot since the last time we announced
1482 * bandwidth. If so, mark our descriptor dirty. */
1483 void
1484 check_descriptor_bandwidth_changed(time_t now)
1486 static time_t last_changed = 0;
1487 uint64_t prev, cur;
1488 if (!desc_routerinfo)
1489 return;
1491 prev = desc_routerinfo->bandwidthcapacity;
1492 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
1493 if ((prev != cur && (!prev || !cur)) ||
1494 cur > prev*2 ||
1495 cur < prev/2) {
1496 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
1497 log_info(LD_GENERAL,
1498 "Measured bandwidth has changed; rebuilding descriptor.");
1499 mark_my_descriptor_dirty();
1500 last_changed = now;
1505 /** Note at log level severity that our best guess of address has changed from
1506 * <b>prev</b> to <b>cur</b>. */
1507 static void
1508 log_addr_has_changed(int severity, uint32_t prev, uint32_t cur,
1509 const char *source)
1511 char addrbuf_prev[INET_NTOA_BUF_LEN];
1512 char addrbuf_cur[INET_NTOA_BUF_LEN];
1513 struct in_addr in_prev;
1514 struct in_addr in_cur;
1516 in_prev.s_addr = htonl(prev);
1517 tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
1519 in_cur.s_addr = htonl(cur);
1520 tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
1522 if (prev)
1523 log_fn(severity, LD_GENERAL,
1524 "Our IP Address has changed from %s to %s; "
1525 "rebuilding descriptor (source: %s).",
1526 addrbuf_prev, addrbuf_cur, source);
1527 else
1528 log_notice(LD_GENERAL,
1529 "Guessed our IP address as %s (source: %s).",
1530 addrbuf_cur, source);
1533 /** Check whether our own address as defined by the Address configuration
1534 * has changed. This is for routers that get their address from a service
1535 * like dyndns. If our address has changed, mark our descriptor dirty. */
1536 void
1537 check_descriptor_ipaddress_changed(time_t now)
1539 uint32_t prev, cur;
1540 or_options_t *options = get_options();
1541 (void) now;
1543 if (!desc_routerinfo)
1544 return;
1546 prev = desc_routerinfo->addr;
1547 if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
1548 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
1549 return;
1552 if (prev != cur) {
1553 log_addr_has_changed(LOG_NOTICE, prev, cur, "resolve");
1554 ip_address_changed(0);
1558 /** The most recently guessed value of our IP address, based on directory
1559 * headers. */
1560 static uint32_t last_guessed_ip = 0;
1562 /** A directory server <b>d_conn</b> told us our IP address is
1563 * <b>suggestion</b>.
1564 * If this address is different from the one we think we are now, and
1565 * if our computer doesn't actually know its IP address, then switch. */
1566 void
1567 router_new_address_suggestion(const char *suggestion,
1568 const dir_connection_t *d_conn)
1570 uint32_t addr, cur = 0;
1571 struct in_addr in;
1572 or_options_t *options = get_options();
1574 /* first, learn what the IP address actually is */
1575 if (!tor_inet_aton(suggestion, &in)) {
1576 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
1577 escaped(suggestion));
1578 return;
1580 addr = ntohl(in.s_addr);
1582 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
1584 if (!server_mode(options)) {
1585 last_guessed_ip = addr; /* store it in case we need it later */
1586 return;
1589 if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
1590 /* We're all set -- we already know our address. Great. */
1591 last_guessed_ip = cur; /* store it in case we need it later */
1592 return;
1594 if (is_internal_IP(addr, 0)) {
1595 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1596 return;
1598 if (tor_addr_eq_ipv4h(&d_conn->_base.addr, addr)) {
1599 /* Don't believe anybody who says our IP is their IP. */
1600 log_debug(LD_DIR, "A directory server told us our IP address is %s, "
1601 "but he's just reporting his own IP address. Ignoring.",
1602 suggestion);
1603 return;
1606 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1607 * us an answer different from what we had the last time we managed to
1608 * resolve it. */
1609 if (last_guessed_ip != addr) {
1610 control_event_server_status(LOG_NOTICE,
1611 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1612 suggestion);
1613 log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr,
1614 d_conn->_base.address);
1615 ip_address_changed(0);
1616 last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
1620 /** We failed to resolve our address locally, but we'd like to build
1621 * a descriptor and publish / test reachability. If we have a guess
1622 * about our address based on directory headers, answer it and return
1623 * 0; else return -1. */
1624 static int
1625 router_guess_address_from_dir_headers(uint32_t *guess)
1627 if (last_guessed_ip) {
1628 *guess = last_guessed_ip;
1629 return 0;
1631 return -1;
1634 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1635 * string describing the version of Tor and the operating system we're
1636 * currently running on.
1638 void
1639 get_platform_str(char *platform, size_t len)
1641 tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
1644 /* XXX need to audit this thing and count fenceposts. maybe
1645 * refactor so we don't have to keep asking if we're
1646 * near the end of maxlen?
1648 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1650 /** OR only: Given a routerinfo for this router, and an identity key to sign
1651 * with, encode the routerinfo as a signed server descriptor and write the
1652 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1653 * failure, and the number of bytes used on success.
1656 router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
1657 crypto_pk_env_t *ident_key)
1659 char *onion_pkey; /* Onion key, PEM-encoded. */
1660 char *identity_pkey; /* Identity key, PEM-encoded. */
1661 char digest[DIGEST_LEN];
1662 char published[ISO_TIME_LEN+1];
1663 char fingerprint[FINGERPRINT_LEN+1];
1664 char extra_info_digest[HEX_DIGEST_LEN+1];
1665 size_t onion_pkeylen, identity_pkeylen;
1666 size_t written;
1667 int result=0;
1668 addr_policy_t *tmpe;
1669 char *family_line;
1670 or_options_t *options = get_options();
1672 /* Make sure the identity key matches the one in the routerinfo. */
1673 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
1674 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
1675 "match router's public key!");
1676 return -1;
1679 /* record our fingerprint, so we can include it in the descriptor */
1680 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
1681 log_err(LD_BUG,"Error computing fingerprint");
1682 return -1;
1685 /* PEM-encode the onion key */
1686 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
1687 &onion_pkey,&onion_pkeylen)<0) {
1688 log_warn(LD_BUG,"write onion_pkey to string failed!");
1689 return -1;
1692 /* PEM-encode the identity key */
1693 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
1694 &identity_pkey,&identity_pkeylen)<0) {
1695 log_warn(LD_BUG,"write identity_pkey to string failed!");
1696 tor_free(onion_pkey);
1697 return -1;
1700 /* Encode the publication time. */
1701 format_iso_time(published, router->cache_info.published_on);
1703 if (router->declared_family && smartlist_len(router->declared_family)) {
1704 size_t n;
1705 char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
1706 n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1707 family_line = tor_malloc(n);
1708 tor_snprintf(family_line, n, "family %s\n", family);
1709 tor_free(family);
1710 } else {
1711 family_line = tor_strdup("");
1714 base16_encode(extra_info_digest, sizeof(extra_info_digest),
1715 router->cache_info.extra_info_digest, DIGEST_LEN);
1717 /* Generate the easy portion of the router descriptor. */
1718 result = tor_snprintf(s, maxlen,
1719 "router %s %s %d 0 %d\n"
1720 "platform %s\n"
1721 "opt protocols Link 1 2 Circuit 1\n"
1722 "published %s\n"
1723 "opt fingerprint %s\n"
1724 "uptime %ld\n"
1725 "bandwidth %d %d %d\n"
1726 "opt extra-info-digest %s\n%s"
1727 "onion-key\n%s"
1728 "signing-key\n%s"
1729 "%s%s%s%s",
1730 router->nickname,
1731 router->address,
1732 router->or_port,
1733 decide_to_advertise_dirport(options, router->dir_port),
1734 router->platform,
1735 published,
1736 fingerprint,
1737 stats_n_seconds_working,
1738 (int) router->bandwidthrate,
1739 (int) router->bandwidthburst,
1740 (int) router->bandwidthcapacity,
1741 extra_info_digest,
1742 options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
1743 onion_pkey, identity_pkey,
1744 family_line,
1745 we_are_hibernating() ? "opt hibernating 1\n" : "",
1746 options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "",
1747 options->AllowSingleHopExits ? "opt allow-single-hop-exits\n" : "");
1749 tor_free(family_line);
1750 tor_free(onion_pkey);
1751 tor_free(identity_pkey);
1753 if (result < 0) {
1754 log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
1755 return -1;
1757 /* From now on, we use 'written' to remember the current length of 's'. */
1758 written = result;
1760 if (options->ContactInfo && strlen(options->ContactInfo)) {
1761 const char *ci = options->ContactInfo;
1762 if (strchr(ci, '\n') || strchr(ci, '\r'))
1763 ci = escaped(ci);
1764 result = tor_snprintf(s+written,maxlen-written, "contact %s\n", ci);
1765 if (result<0) {
1766 log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
1767 return -1;
1769 written += result;
1772 /* Write the exit policy to the end of 's'. */
1773 if (dns_seems_to_be_broken() || has_dns_init_failed() ||
1774 !router->exit_policy || !smartlist_len(router->exit_policy)) {
1775 /* DNS is screwed up; don't claim to be an exit. */
1776 strlcat(s+written, "reject *:*\n", maxlen-written);
1777 written += strlen("reject *:*\n");
1778 tmpe = NULL;
1779 } else if (router->exit_policy) {
1780 int i;
1781 for (i = 0; i < smartlist_len(router->exit_policy); ++i) {
1782 tmpe = smartlist_get(router->exit_policy, i);
1783 result = policy_write_item(s+written, maxlen-written, tmpe, 1);
1784 if (result < 0) {
1785 log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
1786 return -1;
1788 tor_assert(result == (int)strlen(s+written));
1789 written += result;
1790 if (written+2 > maxlen) {
1791 log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
1792 return -1;
1794 s[written++] = '\n';
1798 if (written+256 > maxlen) { /* Not enough room for signature. */
1799 log_warn(LD_BUG,"not enough room left in descriptor for signature!");
1800 return -1;
1803 /* Sign the descriptor */
1804 strlcpy(s+written, "router-signature\n", maxlen-written);
1805 written += strlen(s+written);
1806 s[written] = '\0';
1807 if (router_get_router_hash(s, strlen(s), digest) < 0) {
1808 return -1;
1811 note_crypto_pk_op(SIGN_RTR);
1812 if (router_append_dirobj_signature(s+written,maxlen-written,
1813 digest,DIGEST_LEN,ident_key)<0) {
1814 log_warn(LD_BUG, "Couldn't sign router descriptor");
1815 return -1;
1817 written += strlen(s+written);
1819 if (written+2 > maxlen) {
1820 log_warn(LD_BUG,"Not enough room to finish descriptor.");
1821 return -1;
1823 /* include a last '\n' */
1824 s[written] = '\n';
1825 s[written+1] = 0;
1827 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1829 char *s_dup;
1830 const char *cp;
1831 routerinfo_t *ri_tmp;
1832 cp = s_dup = tor_strdup(s);
1833 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
1834 if (!ri_tmp) {
1835 log_err(LD_BUG,
1836 "We just generated a router descriptor we can't parse.");
1837 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1838 return -1;
1840 tor_free(s_dup);
1841 routerinfo_free(ri_tmp);
1843 #endif
1845 return (int)written+1;
1848 /** Load the contents of <b>filename</b>, find the last line starting with
1849 * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
1850 * the past or more than 1 hour in the future with respect to <b>now</b>,
1851 * and write the file contents starting with that line to *<b>out</b>.
1852 * Return 1 for success, 0 if the file does not exist, or -1 if the file
1853 * does not contain a line matching these criteria or other failure. */
1854 static int
1855 load_stats_file(const char *filename, const char *end_line, time_t now,
1856 char **out)
1858 int r = -1;
1859 char *fname = get_datadir_fname(filename);
1860 char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
1861 time_t written;
1862 switch (file_status(fname)) {
1863 case FN_FILE:
1864 /* X022 Find an alternative to reading the whole file to memory. */
1865 if ((contents = read_file_to_str(fname, 0, NULL))) {
1866 tmp = strstr(contents, end_line);
1867 /* Find last block starting with end_line */
1868 while (tmp) {
1869 start = tmp;
1870 tmp = strstr(tmp + 1, end_line);
1872 if (!start)
1873 goto notfound;
1874 if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
1875 goto notfound;
1876 strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
1877 if (parse_iso_time(timestr, &written) < 0)
1878 goto notfound;
1879 if (written < now - (25*60*60) || written > now + (1*60*60))
1880 goto notfound;
1881 *out = tor_strdup(start);
1882 r = 1;
1884 notfound:
1885 tor_free(contents);
1886 break;
1887 case FN_NOENT:
1888 r = 0;
1889 break;
1890 case FN_ERROR:
1891 case FN_DIR:
1892 default:
1893 break;
1895 tor_free(fname);
1896 return r;
1899 /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
1900 * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
1901 * negative on failure. */
1903 extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
1904 crypto_pk_env_t *ident_key)
1906 or_options_t *options = get_options();
1907 char identity[HEX_DIGEST_LEN+1];
1908 char published[ISO_TIME_LEN+1];
1909 char digest[DIGEST_LEN];
1910 char *bandwidth_usage;
1911 int result;
1912 size_t len;
1913 static int write_stats_to_extrainfo = 1;
1914 time_t now = time(NULL);
1916 base16_encode(identity, sizeof(identity),
1917 extrainfo->cache_info.identity_digest, DIGEST_LEN);
1918 format_iso_time(published, extrainfo->cache_info.published_on);
1919 bandwidth_usage = rep_hist_get_bandwidth_lines(1);
1921 result = tor_snprintf(s, maxlen,
1922 "extra-info %s %s\n"
1923 "published %s\n%s",
1924 extrainfo->nickname, identity,
1925 published, bandwidth_usage);
1927 tor_free(bandwidth_usage);
1928 if (result<0)
1929 return -1;
1931 if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
1932 char *contents = NULL;
1933 log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
1934 if (options->DirReqStatistics &&
1935 load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
1936 "dirreq-stats-end", now, &contents) > 0) {
1937 size_t pos = strlen(s);
1938 if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
1939 strlen(contents)) {
1940 log_warn(LD_DIR, "Could not write dirreq-stats to extra-info "
1941 "descriptor.");
1942 s[pos] = '\0';
1943 write_stats_to_extrainfo = 0;
1945 tor_free(contents);
1947 if (options->EntryStatistics &&
1948 load_stats_file("stats"PATH_SEPARATOR"entry-stats",
1949 "entry-stats-end", now, &contents) > 0) {
1950 size_t pos = strlen(s);
1951 if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
1952 strlen(contents)) {
1953 log_warn(LD_DIR, "Could not write entry-stats to extra-info "
1954 "descriptor.");
1955 s[pos] = '\0';
1956 write_stats_to_extrainfo = 0;
1958 tor_free(contents);
1960 if (options->CellStatistics &&
1961 load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
1962 "cell-stats-end", now, &contents) > 0) {
1963 size_t pos = strlen(s);
1964 if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
1965 strlen(contents)) {
1966 log_warn(LD_DIR, "Could not write buffer-stats to extra-info "
1967 "descriptor.");
1968 s[pos] = '\0';
1969 write_stats_to_extrainfo = 0;
1971 tor_free(contents);
1973 if (options->ExitPortStatistics &&
1974 load_stats_file("stats"PATH_SEPARATOR"exit-stats",
1975 "exit-stats-end", now, &contents) > 0) {
1976 size_t pos = strlen(s);
1977 if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
1978 strlen(contents)) {
1979 log_warn(LD_DIR, "Could not write exit-stats to extra-info "
1980 "descriptor.");
1981 s[pos] = '\0';
1982 write_stats_to_extrainfo = 0;
1984 tor_free(contents);
1988 if (should_record_bridge_info(options) && write_stats_to_extrainfo) {
1989 const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
1990 if (bridge_stats) {
1991 size_t pos = strlen(s);
1992 if (strlcpy(s + pos, bridge_stats, maxlen - strlen(s)) !=
1993 strlen(bridge_stats)) {
1994 log_warn(LD_DIR, "Could not write bridge-stats to extra-info "
1995 "descriptor.");
1996 s[pos] = '\0';
1997 write_stats_to_extrainfo = 0;
2002 len = strlen(s);
2003 strlcat(s+len, "router-signature\n", maxlen-len);
2004 len += strlen(s+len);
2005 if (router_get_extrainfo_hash(s, digest)<0)
2006 return -1;
2007 if (router_append_dirobj_signature(s+len, maxlen-len, digest, DIGEST_LEN,
2008 ident_key)<0)
2009 return -1;
2012 char *cp, *s_dup;
2013 extrainfo_t *ei_tmp;
2014 cp = s_dup = tor_strdup(s);
2015 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
2016 if (!ei_tmp) {
2017 log_err(LD_BUG,
2018 "We just generated an extrainfo descriptor we can't parse.");
2019 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
2020 tor_free(s_dup);
2021 return -1;
2023 tor_free(s_dup);
2024 extrainfo_free(ei_tmp);
2027 if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
2028 char *cp, *s_dup;
2029 extrainfo_t *ei_tmp;
2030 cp = s_dup = tor_strdup(s);
2031 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
2032 if (!ei_tmp) {
2033 log_warn(LD_GENERAL,
2034 "We just generated an extra-info descriptor with "
2035 "statistics that we can't parse. Not adding statistics to "
2036 "this or any future extra-info descriptors. Descriptor "
2037 "was:\n%s", s);
2038 write_stats_to_extrainfo = 0;
2039 extrainfo_dump_to_string(s, maxlen, extrainfo, ident_key);
2041 tor_free(s_dup);
2042 extrainfo_free(ei_tmp);
2045 return (int)strlen(s)+1;
2048 /** Return true iff <b>s</b> is a legally valid server nickname. */
2050 is_legal_nickname(const char *s)
2052 size_t len;
2053 tor_assert(s);
2054 len = strlen(s);
2055 return len > 0 && len <= MAX_NICKNAME_LEN &&
2056 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
2059 /** Return true iff <b>s</b> is a legally valid server nickname or
2060 * hex-encoded identity-key digest. */
2062 is_legal_nickname_or_hexdigest(const char *s)
2064 if (*s!='$')
2065 return is_legal_nickname(s);
2066 else
2067 return is_legal_hexdigest(s);
2070 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
2071 * digest. */
2073 is_legal_hexdigest(const char *s)
2075 size_t len;
2076 tor_assert(s);
2077 if (s[0] == '$') s++;
2078 len = strlen(s);
2079 if (len > HEX_DIGEST_LEN) {
2080 if (s[HEX_DIGEST_LEN] == '=' ||
2081 s[HEX_DIGEST_LEN] == '~') {
2082 if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
2083 return 0;
2084 } else {
2085 return 0;
2088 return (len >= HEX_DIGEST_LEN &&
2089 strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
2092 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
2093 * verbose representation of the identity of <b>router</b>. The format is:
2094 * A dollar sign.
2095 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
2096 * A "=" if the router is named; a "~" if it is not.
2097 * The router's nickname.
2099 void
2100 router_get_verbose_nickname(char *buf, const routerinfo_t *router)
2102 buf[0] = '$';
2103 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
2104 DIGEST_LEN);
2105 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
2106 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
2109 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
2110 * verbose representation of the identity of <b>router</b>. The format is:
2111 * A dollar sign.
2112 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
2113 * A "=" if the router is named; a "~" if it is not.
2114 * The router's nickname.
2116 void
2117 routerstatus_get_verbose_nickname(char *buf, const routerstatus_t *router)
2119 buf[0] = '$';
2120 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->identity_digest,
2121 DIGEST_LEN);
2122 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
2123 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
2126 /** Forget that we have issued any router-related warnings, so that we'll
2127 * warn again if we see the same errors. */
2128 void
2129 router_reset_warnings(void)
2131 if (warned_nonexistent_family) {
2132 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
2133 smartlist_clear(warned_nonexistent_family);
2137 /** Given a router purpose, convert it to a string. Don't call this on
2138 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
2139 * know its string representation. */
2140 const char *
2141 router_purpose_to_string(uint8_t p)
2143 switch (p)
2145 case ROUTER_PURPOSE_GENERAL: return "general";
2146 case ROUTER_PURPOSE_BRIDGE: return "bridge";
2147 case ROUTER_PURPOSE_CONTROLLER: return "controller";
2148 default:
2149 tor_assert(0);
2151 return NULL;
2154 /** Given a string, convert it to a router purpose. */
2155 uint8_t
2156 router_purpose_from_string(const char *s)
2158 if (!strcmp(s, "general"))
2159 return ROUTER_PURPOSE_GENERAL;
2160 else if (!strcmp(s, "bridge"))
2161 return ROUTER_PURPOSE_BRIDGE;
2162 else if (!strcmp(s, "controller"))
2163 return ROUTER_PURPOSE_CONTROLLER;
2164 else
2165 return ROUTER_PURPOSE_UNKNOWN;
2168 /** Release all static resources held in router.c */
2169 void
2170 router_free_all(void)
2172 crypto_free_pk_env(onionkey);
2173 crypto_free_pk_env(lastonionkey);
2174 crypto_free_pk_env(identitykey);
2175 tor_mutex_free(key_lock);
2176 routerinfo_free(desc_routerinfo);
2177 extrainfo_free(desc_extrainfo);
2178 crypto_free_pk_env(authority_signing_key);
2179 authority_cert_free(authority_key_certificate);
2180 crypto_free_pk_env(legacy_signing_key);
2181 authority_cert_free(legacy_key_certificate);
2183 if (warned_nonexistent_family) {
2184 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
2185 smartlist_free(warned_nonexistent_family);