Don't write extra-info document to debug logs.
[tor/rransom.git] / src / or / router.c
blobd744b9bc06007ed8be11b4201db904e45b445514
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-2009, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 #define ROUTER_PRIVATE
9 #include "or.h"
11 /**
12 * \file router.c
13 * \brief OR functionality, including key maintenance, generating
14 * and uploading server descriptors, retrying OR connections.
15 **/
17 extern long stats_n_seconds_working;
19 /************************************************************/
21 /*****
22 * Key management: ORs only.
23 *****/
25 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
27 static tor_mutex_t *key_lock=NULL;
28 static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
29 /** Current private onionskin decryption key: used to decode CREATE cells. */
30 static crypto_pk_env_t *onionkey=NULL;
31 /** Previous private onionskin decryption key: used to decode CREATE cells
32 * generated by clients that have an older version of our descriptor. */
33 static crypto_pk_env_t *lastonionkey=NULL;
34 /** Private "identity key": used to sign directory info and TLS
35 * certificates. Never changes. */
36 static crypto_pk_env_t *identitykey=NULL;
37 /** Digest of identitykey. */
38 static char identitykey_digest[DIGEST_LEN];
39 /** Signing key used for v3 directory material; only set for authorities. */
40 static crypto_pk_env_t *authority_signing_key = NULL;
41 /** Key certificate to authenticate v3 directory material; only set for
42 * authorities. */
43 static authority_cert_t *authority_key_certificate = NULL;
45 /** For emergency V3 authority key migration: An extra signing key that we use
46 * with our old (obsolete) identity key for a while. */
47 static crypto_pk_env_t *legacy_signing_key = NULL;
48 /** For emergency V3 authority key migration: An extra certificate to
49 * authenticate legacy_signing_key with our obsolete identity key.*/
50 static authority_cert_t *legacy_key_certificate = NULL;
52 /* (Note that v3 authorities also have a separate "authority identity key",
53 * but this key is never actually loaded by the Tor process. Instead, it's
54 * used by tor-gencert to sign new signing keys and make new key
55 * certificates. */
57 /** Replace the current onion key with <b>k</b>. Does not affect
58 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
60 static void
61 set_onion_key(crypto_pk_env_t *k)
63 tor_mutex_acquire(key_lock);
64 if (onionkey)
65 crypto_free_pk_env(onionkey);
66 onionkey = k;
67 onionkey_set_at = time(NULL);
68 tor_mutex_release(key_lock);
69 mark_my_descriptor_dirty();
72 /** Return the current onion key. Requires that the onion key has been
73 * loaded or generated. */
74 crypto_pk_env_t *
75 get_onion_key(void)
77 tor_assert(onionkey);
78 return onionkey;
81 /** Store a full copy of the current onion key into *<b>key</b>, and a full
82 * copy of the most recent onion key into *<b>last</b>.
84 void
85 dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
87 tor_assert(key);
88 tor_assert(last);
89 tor_mutex_acquire(key_lock);
90 tor_assert(onionkey);
91 *key = crypto_pk_copy_full(onionkey);
92 if (lastonionkey)
93 *last = crypto_pk_copy_full(lastonionkey);
94 else
95 *last = NULL;
96 tor_mutex_release(key_lock);
99 /** Return the time when the onion key was last set. This is either the time
100 * when the process launched, or the time of the most recent key rotation since
101 * the process launched.
103 time_t
104 get_onion_key_set_at(void)
106 return onionkey_set_at;
109 /** Set the current identity key to k.
111 void
112 set_identity_key(crypto_pk_env_t *k)
114 if (identitykey)
115 crypto_free_pk_env(identitykey);
116 identitykey = k;
117 crypto_pk_get_digest(identitykey, identitykey_digest);
120 /** Returns the current identity key; requires that the identity key has been
121 * set.
123 crypto_pk_env_t *
124 get_identity_key(void)
126 tor_assert(identitykey);
127 return identitykey;
130 /** Return true iff the identity key has been set. */
132 identity_key_is_set(void)
134 return identitykey != NULL;
137 /** Return the key certificate for this v3 (voting) authority, or NULL
138 * if we have no such certificate. */
139 authority_cert_t *
140 get_my_v3_authority_cert(void)
142 return authority_key_certificate;
145 /** Return the v3 signing key for this v3 (voting) authority, or NULL
146 * if we have no such key. */
147 crypto_pk_env_t *
148 get_my_v3_authority_signing_key(void)
150 return authority_signing_key;
153 /** If we're an authority, and we're using a legacy authority identity key for
154 * emergency migration purposes, return the certificate associated with that
155 * key. */
156 authority_cert_t *
157 get_my_v3_legacy_cert(void)
159 return legacy_key_certificate;
162 /** If we're an authority, and we're using a legacy authority identity key for
163 * emergency migration purposes, return that key. */
164 crypto_pk_env_t *
165 get_my_v3_legacy_signing_key(void)
167 return legacy_signing_key;
170 /** Replace the previous onion key with the current onion key, and generate
171 * a new previous onion key. Immediately after calling this function,
172 * the OR should:
173 * - schedule all previous cpuworkers to shut down _after_ processing
174 * pending work. (This will cause fresh cpuworkers to be generated.)
175 * - generate and upload a fresh routerinfo.
177 void
178 rotate_onion_key(void)
180 char *fname, *fname_prev;
181 crypto_pk_env_t *prkey;
182 or_state_t *state = get_or_state();
183 time_t now;
184 fname = get_datadir_fname2("keys", "secret_onion_key");
185 fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
186 if (!(prkey = crypto_new_pk_env())) {
187 log_err(LD_GENERAL,"Error constructing rotated onion key");
188 goto error;
190 if (crypto_pk_generate_key(prkey)) {
191 log_err(LD_BUG,"Error generating onion key");
192 goto error;
194 if (file_status(fname) == FN_FILE) {
195 if (replace_file(fname, fname_prev))
196 goto error;
198 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
199 log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
200 goto error;
202 log_info(LD_GENERAL, "Rotating onion key");
203 tor_mutex_acquire(key_lock);
204 if (lastonionkey)
205 crypto_free_pk_env(lastonionkey);
206 lastonionkey = onionkey;
207 onionkey = prkey;
208 now = time(NULL);
209 state->LastRotatedOnionKey = onionkey_set_at = now;
210 tor_mutex_release(key_lock);
211 mark_my_descriptor_dirty();
212 or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
213 goto done;
214 error:
215 log_warn(LD_GENERAL, "Couldn't rotate onion key.");
216 if (prkey)
217 crypto_free_pk_env(prkey);
218 done:
219 tor_free(fname);
220 tor_free(fname_prev);
223 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
224 * and <b>generate</b> is true, create a new RSA key and save it in
225 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
226 * errors at level <b>severity</b>.
228 crypto_pk_env_t *
229 init_key_from_file(const char *fname, int generate, int severity)
231 crypto_pk_env_t *prkey = NULL;
233 if (!(prkey = crypto_new_pk_env())) {
234 log(severity, LD_GENERAL,"Error constructing key");
235 goto error;
238 switch (file_status(fname)) {
239 case FN_DIR:
240 case FN_ERROR:
241 log(severity, LD_FS,"Can't read key from \"%s\"", fname);
242 goto error;
243 case FN_NOENT:
244 if (generate) {
245 if (!have_lockfile()) {
246 if (try_locking(get_options(), 0)<0) {
247 /* Make sure that --list-fingerprint only creates new keys
248 * if there is no possibility for a deadlock. */
249 log(severity, LD_FS, "Another Tor process has locked \"%s\". Not "
250 "writing any new keys.", fname);
251 /*XXXX The 'other process' might make a key in a second or two;
252 * maybe we should wait for it. */
253 goto error;
256 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
257 fname);
258 if (crypto_pk_generate_key(prkey)) {
259 log(severity, LD_GENERAL,"Error generating onion key");
260 goto error;
262 if (crypto_pk_check_key(prkey) <= 0) {
263 log(severity, LD_GENERAL,"Generated key seems invalid");
264 goto error;
266 log_info(LD_GENERAL, "Generated key seems valid");
267 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
268 log(severity, LD_FS,
269 "Couldn't write generated key to \"%s\".", fname);
270 goto error;
272 } else {
273 log_info(LD_GENERAL, "No key found in \"%s\"", fname);
275 return prkey;
276 case FN_FILE:
277 if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
278 log(severity, LD_GENERAL,"Error loading private key.");
279 goto error;
281 return prkey;
282 default:
283 tor_assert(0);
286 error:
287 if (prkey)
288 crypto_free_pk_env(prkey);
289 return NULL;
292 /** Try to load the vote-signing private key and certificate for being a v3
293 * directory authority, and make sure they match. If <b>legacy</b>, load a
294 * legacy key/cert set for emergency key migration; otherwise load the regular
295 * key/cert set. On success, store them into *<b>key_out</b> and
296 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
297 static int
298 load_authority_keyset(int legacy, crypto_pk_env_t **key_out,
299 authority_cert_t **cert_out)
301 int r = -1;
302 char *fname = NULL, *cert = NULL;
303 const char *eos = NULL;
304 crypto_pk_env_t *signing_key = NULL;
305 authority_cert_t *parsed = NULL;
307 fname = get_datadir_fname2("keys",
308 legacy ? "legacy_signing_key" : "authority_signing_key");
309 signing_key = init_key_from_file(fname, 0, LOG_INFO);
310 if (!signing_key) {
311 log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
312 goto done;
314 tor_free(fname);
315 fname = get_datadir_fname2("keys",
316 legacy ? "legacy_certificate" : "authority_certificate");
317 cert = read_file_to_str(fname, 0, NULL);
318 if (!cert) {
319 log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
320 fname);
321 goto done;
323 parsed = authority_cert_parse_from_string(cert, &eos);
324 if (!parsed) {
325 log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
326 goto done;
328 if (crypto_pk_cmp_keys(signing_key, parsed->signing_key) != 0) {
329 log_warn(LD_DIR, "Stored signing key does not match signing key in "
330 "certificate");
331 goto done;
334 if (*key_out)
335 crypto_free_pk_env(*key_out);
336 if (*cert_out)
337 authority_cert_free(*cert_out);
338 *key_out = signing_key;
339 *cert_out = parsed;
340 r = 0;
341 signing_key = NULL;
342 parsed = NULL;
344 done:
345 tor_free(fname);
346 tor_free(cert);
347 if (signing_key)
348 crypto_free_pk_env(signing_key);
349 if (parsed)
350 authority_cert_free(parsed);
351 return r;
354 /** Load the v3 (voting) authority signing key and certificate, if they are
355 * present. Return -1 if anything is missing, mismatched, or unloadable;
356 * return 0 on success. */
357 static int
358 init_v3_authority_keys(void)
360 if (load_authority_keyset(0, &authority_signing_key,
361 &authority_key_certificate)<0)
362 return -1;
364 if (get_options()->V3AuthUseLegacyKey &&
365 load_authority_keyset(1, &legacy_signing_key,
366 &legacy_key_certificate)<0)
367 return -1;
369 return 0;
372 /** If we're a v3 authority, check whether we have a certificate that's
373 * likely to expire soon. Warn if we do, but not too often. */
374 void
375 v3_authority_check_key_expiry(void)
377 time_t now, expires;
378 static time_t last_warned = 0;
379 int badness, time_left, warn_interval;
380 if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
381 return;
383 now = time(NULL);
384 expires = authority_key_certificate->expires;
385 time_left = (int)( expires - now );
386 if (time_left <= 0) {
387 badness = LOG_ERR;
388 warn_interval = 60*60;
389 } else if (time_left <= 24*60*60) {
390 badness = LOG_WARN;
391 warn_interval = 60*60;
392 } else if (time_left <= 24*60*60*7) {
393 badness = LOG_WARN;
394 warn_interval = 24*60*60;
395 } else if (time_left <= 24*60*60*30) {
396 badness = LOG_WARN;
397 warn_interval = 24*60*60*5;
398 } else {
399 return;
402 if (last_warned + warn_interval > now)
403 return;
405 if (time_left <= 0) {
406 log(badness, LD_DIR, "Your v3 authority certificate has expired."
407 " Generate a new one NOW.");
408 } else if (time_left <= 24*60*60) {
409 log(badness, LD_DIR, "Your v3 authority certificate expires in %d hours;"
410 " Generate a new one NOW.", time_left/(60*60));
411 } else {
412 log(badness, LD_DIR, "Your v3 authority certificate expires in %d days;"
413 " Generate a new one soon.", time_left/(24*60*60));
415 last_warned = now;
418 /** Initialize all OR private keys, and the TLS context, as necessary.
419 * On OPs, this only initializes the tls context. Return 0 on success,
420 * or -1 if Tor should die.
423 init_keys(void)
425 char *keydir;
426 char fingerprint[FINGERPRINT_LEN+1];
427 /*nickname<space>fp\n\0 */
428 char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
429 const char *mydesc;
430 crypto_pk_env_t *prkey;
431 char digest[20];
432 char v3_digest[20];
433 char *cp;
434 or_options_t *options = get_options();
435 authority_type_t type;
436 time_t now = time(NULL);
437 trusted_dir_server_t *ds;
438 int v3_digest_set = 0;
439 authority_cert_t *cert = NULL;
441 if (!key_lock)
442 key_lock = tor_mutex_new();
444 /* There are a couple of paths that put us here before */
445 if (crypto_global_init(get_options()->HardwareAccel,
446 get_options()->AccelName,
447 get_options()->AccelDir)) {
448 log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
449 return -1;
452 /* OP's don't need persistent keys; just make up an identity and
453 * initialize the TLS context. */
454 if (!server_mode(options)) {
455 if (!(prkey = crypto_new_pk_env()))
456 return -1;
457 if (crypto_pk_generate_key(prkey)) {
458 crypto_free_pk_env(prkey);
459 return -1;
461 set_identity_key(prkey);
462 /* Create a TLS context; default the client nickname to "client". */
463 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
464 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
465 return -1;
467 return 0;
469 /* Make sure DataDirectory exists, and is private. */
470 if (check_private_dir(options->DataDirectory, CPD_CREATE)) {
471 return -1;
473 /* Check the key directory. */
474 keydir = get_datadir_fname("keys");
475 if (check_private_dir(keydir, CPD_CREATE)) {
476 tor_free(keydir);
477 return -1;
479 tor_free(keydir);
481 /* 1a. Read v3 directory authority key/cert information. */
482 memset(v3_digest, 0, sizeof(v3_digest));
483 if (authdir_mode_v3(options)) {
484 if (init_v3_authority_keys()<0) {
485 log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
486 "were unable to load our v3 authority keys and certificate! "
487 "Use tor-gencert to generate them. Dying.");
488 return -1;
490 cert = get_my_v3_authority_cert();
491 if (cert) {
492 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
493 v3_digest);
494 v3_digest_set = 1;
498 /* 1. Read identity key. Make it if none is found. */
499 keydir = get_datadir_fname2("keys", "secret_id_key");
500 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
501 prkey = init_key_from_file(keydir, 1, LOG_ERR);
502 tor_free(keydir);
503 if (!prkey) return -1;
504 set_identity_key(prkey);
506 /* 2. Read onion key. Make it if none is found. */
507 keydir = get_datadir_fname2("keys", "secret_onion_key");
508 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
509 prkey = init_key_from_file(keydir, 1, LOG_ERR);
510 tor_free(keydir);
511 if (!prkey) return -1;
512 set_onion_key(prkey);
513 if (options->command == CMD_RUN_TOR) {
514 /* only mess with the state file if we're actually running Tor */
515 or_state_t *state = get_or_state();
516 if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
517 /* We allow for some parsing slop, but we don't want to risk accepting
518 * values in the distant future. If we did, we might never rotate the
519 * onion key. */
520 onionkey_set_at = state->LastRotatedOnionKey;
521 } else {
522 /* We have no LastRotatedOnionKey set; either we just created the key
523 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
524 * start the clock ticking now so that we will eventually rotate it even
525 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
526 state->LastRotatedOnionKey = onionkey_set_at = now;
527 or_state_mark_dirty(state, options->AvoidDiskWrites ?
528 time(NULL)+3600 : 0);
532 keydir = get_datadir_fname2("keys", "secret_onion_key.old");
533 if (!lastonionkey && file_status(keydir) == FN_FILE) {
534 prkey = init_key_from_file(keydir, 1, LOG_ERR);
535 if (prkey)
536 lastonionkey = prkey;
538 tor_free(keydir);
540 /* 3. Initialize link key and TLS context. */
541 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
542 log_err(LD_GENERAL,"Error initializing TLS context");
543 return -1;
545 /* 4. Build our router descriptor. */
546 /* Must be called after keys are initialized. */
547 mydesc = router_get_my_descriptor();
548 if (authdir_mode(options)) {
549 const char *m = NULL;
550 routerinfo_t *ri;
551 /* We need to add our own fingerprint so it gets recognized. */
552 if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
553 log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
554 return -1;
556 if (mydesc) {
557 ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
558 if (!ri) {
559 log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
560 return -1;
562 if (!WRA_WAS_ADDED(dirserv_add_descriptor(ri, &m, "self"))) {
563 log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
564 m?m:"<unknown error>");
565 return -1;
570 /* 5. Dump fingerprint to 'fingerprint' */
571 keydir = get_datadir_fname("fingerprint");
572 log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
573 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 0)<0) {
574 log_err(LD_GENERAL,"Error computing fingerprint");
575 tor_free(keydir);
576 return -1;
578 tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
579 if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
580 "%s %s\n",options->Nickname, fingerprint) < 0) {
581 log_err(LD_GENERAL,"Error writing fingerprint line");
582 tor_free(keydir);
583 return -1;
585 /* Check whether we need to write the fingerprint file. */
586 cp = NULL;
587 if (file_status(keydir) == FN_FILE)
588 cp = read_file_to_str(keydir, 0, NULL);
589 if (!cp || strcmp(cp, fingerprint_line)) {
590 if (write_str_to_file(keydir, fingerprint_line, 0)) {
591 log_err(LD_FS, "Error writing fingerprint line to file");
592 tor_free(keydir);
593 return -1;
596 tor_free(cp);
597 tor_free(keydir);
599 log(LOG_NOTICE, LD_GENERAL,
600 "Your Tor server's identity key fingerprint is '%s %s'",
601 options->Nickname, fingerprint);
602 if (!authdir_mode(options))
603 return 0;
604 /* 6. [authdirserver only] load approved-routers file */
605 if (dirserv_load_fingerprint_file() < 0) {
606 log_err(LD_GENERAL,"Error loading fingerprints");
607 return -1;
609 /* 6b. [authdirserver only] add own key to approved directories. */
610 crypto_pk_get_digest(get_identity_key(), digest);
611 type = ((options->V1AuthoritativeDir ? V1_AUTHORITY : NO_AUTHORITY) |
612 (options->V2AuthoritativeDir ? V2_AUTHORITY : NO_AUTHORITY) |
613 (options->V3AuthoritativeDir ? V3_AUTHORITY : NO_AUTHORITY) |
614 (options->BridgeAuthoritativeDir ? BRIDGE_AUTHORITY : NO_AUTHORITY) |
615 (options->HSAuthoritativeDir ? HIDSERV_AUTHORITY : NO_AUTHORITY));
617 ds = router_get_trusteddirserver_by_digest(digest);
618 if (!ds) {
619 ds = add_trusted_dir_server(options->Nickname, NULL,
620 (uint16_t)options->DirPort,
621 (uint16_t)options->ORPort,
622 digest,
623 v3_digest,
624 type);
625 if (!ds) {
626 log_err(LD_GENERAL,"We want to be a directory authority, but we "
627 "couldn't add ourselves to the authority list. Failing.");
628 return -1;
631 if (ds->type != type) {
632 log_warn(LD_DIR, "Configured authority type does not match authority "
633 "type in DirServer list. Adjusting. (%d v %d)",
634 type, ds->type);
635 ds->type = type;
637 if (v3_digest_set && (ds->type & V3_AUTHORITY) &&
638 memcmp(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
639 log_warn(LD_DIR, "V3 identity key does not match identity declared in "
640 "DirServer line. Adjusting.");
641 memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
644 if (cert) { /* add my own cert to the list of known certs */
645 log_info(LD_DIR, "adding my own v3 cert");
646 if (trusted_dirs_load_certs_from_string(
647 cert->cache_info.signed_descriptor_body, 0, 0)<0) {
648 log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
649 return -1;
653 return 0; /* success */
656 /* Keep track of whether we should upload our server descriptor,
657 * and what type of server we are.
660 /** Whether we can reach our ORPort from the outside. */
661 static int can_reach_or_port = 0;
662 /** Whether we can reach our DirPort from the outside. */
663 static int can_reach_dir_port = 0;
665 /** Forget what we have learned about our reachability status. */
666 void
667 router_reset_reachability(void)
669 can_reach_or_port = can_reach_dir_port = 0;
672 /** Return 1 if ORPort is known reachable; else return 0. */
674 check_whether_orport_reachable(void)
676 or_options_t *options = get_options();
677 return options->AssumeReachable ||
678 can_reach_or_port;
681 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
683 check_whether_dirport_reachable(void)
685 or_options_t *options = get_options();
686 return !options->DirPort ||
687 options->AssumeReachable ||
688 we_are_hibernating() ||
689 can_reach_dir_port;
692 /** Look at a variety of factors, and return 0 if we don't want to
693 * advertise the fact that we have a DirPort open. Else return the
694 * DirPort we want to advertise.
696 * Log a helpful message if we change our mind about whether to publish
697 * a DirPort.
699 static int
700 decide_to_advertise_dirport(or_options_t *options, uint16_t dir_port)
702 static int advertising=1; /* start out assuming we will advertise */
703 int new_choice=1;
704 const char *reason = NULL;
706 /* Section one: reasons to publish or not publish that aren't
707 * worth mentioning to the user, either because they're obvious
708 * or because they're normal behavior. */
710 if (!dir_port) /* short circuit the rest of the function */
711 return 0;
712 if (authdir_mode(options)) /* always publish */
713 return dir_port;
714 if (we_are_hibernating())
715 return 0;
716 if (!check_whether_dirport_reachable())
717 return 0;
719 /* Section two: reasons to publish or not publish that the user
720 * might find surprising. These are generally config options that
721 * make us choose not to publish. */
723 if (accounting_is_enabled(options)) {
724 /* if we might potentially hibernate */
725 new_choice = 0;
726 reason = "AccountingMax enabled";
727 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
728 } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
729 (options->RelayBandwidthRate > 0 &&
730 options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
731 /* if we're advertising a small amount */
732 new_choice = 0;
733 reason = "BandwidthRate under 50KB";
736 if (advertising != new_choice) {
737 if (new_choice == 1) {
738 log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
739 } else {
740 tor_assert(reason);
741 log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
743 advertising = new_choice;
746 return advertising ? dir_port : 0;
749 /** Some time has passed, or we just got new directory information.
750 * See if we currently believe our ORPort or DirPort to be
751 * unreachable. If so, launch a new test for it.
753 * For ORPort, we simply try making a circuit that ends at ourselves.
754 * Success is noticed in onionskin_answer().
756 * For DirPort, we make a connection via Tor to our DirPort and ask
757 * for our own server descriptor.
758 * Success is noticed in connection_dir_client_reached_eof().
760 void
761 consider_testing_reachability(int test_or, int test_dir)
763 routerinfo_t *me = router_get_my_routerinfo();
764 int orport_reachable = check_whether_orport_reachable();
765 tor_addr_t addr;
766 if (!me)
767 return;
769 if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
770 log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
771 !orport_reachable ? "reachability" : "bandwidth",
772 me->address, me->or_port);
773 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me,
774 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
775 control_event_server_status(LOG_NOTICE,
776 "CHECKING_REACHABILITY ORADDRESS=%s:%d",
777 me->address, me->or_port);
780 tor_addr_from_ipv4h(&addr, me->addr);
781 if (test_dir && !check_whether_dirport_reachable() &&
782 !connection_get_by_type_addr_port_purpose(
783 CONN_TYPE_DIR, &addr, me->dir_port,
784 DIR_PURPOSE_FETCH_SERVERDESC)) {
785 /* ask myself, via tor, for my server descriptor. */
786 directory_initiate_command(me->address, &addr,
787 me->or_port, me->dir_port,
788 0, /* does not matter */
789 0, me->cache_info.identity_digest,
790 DIR_PURPOSE_FETCH_SERVERDESC,
791 ROUTER_PURPOSE_GENERAL,
792 1, "authority.z", NULL, 0, 0);
794 control_event_server_status(LOG_NOTICE,
795 "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
796 me->address, me->dir_port);
800 /** Annotate that we found our ORPort reachable. */
801 void
802 router_orport_found_reachable(void)
804 if (!can_reach_or_port) {
805 routerinfo_t *me = router_get_my_routerinfo();
806 log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
807 "the outside. Excellent.%s",
808 get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
809 " Publishing server descriptor." : "");
810 can_reach_or_port = 1;
811 mark_my_descriptor_dirty();
812 if (!me)
813 return;
814 control_event_server_status(LOG_NOTICE,
815 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
816 me->address, me->or_port);
820 /** Annotate that we found our DirPort reachable. */
821 void
822 router_dirport_found_reachable(void)
824 if (!can_reach_dir_port) {
825 routerinfo_t *me = router_get_my_routerinfo();
826 log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
827 "from the outside. Excellent.");
828 can_reach_dir_port = 1;
829 if (!me || decide_to_advertise_dirport(get_options(), me->dir_port))
830 mark_my_descriptor_dirty();
831 if (!me)
832 return;
833 control_event_server_status(LOG_NOTICE,
834 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
835 me->address, me->dir_port);
839 /** We have enough testing circuits open. Send a bunch of "drop"
840 * cells down each of them, to exercise our bandwidth. */
841 void
842 router_perform_bandwidth_test(int num_circs, time_t now)
844 int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
845 int max_cells = num_cells < CIRCWINDOW_START ?
846 num_cells : CIRCWINDOW_START;
847 int cells_per_circuit = max_cells / num_circs;
848 origin_circuit_t *circ = NULL;
850 log_notice(LD_OR,"Performing bandwidth self-test...done.");
851 while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
852 CIRCUIT_PURPOSE_TESTING))) {
853 /* dump cells_per_circuit drop cells onto this circ */
854 int i = cells_per_circuit;
855 if (circ->_base.state != CIRCUIT_STATE_OPEN)
856 continue;
857 circ->_base.timestamp_dirty = now;
858 while (i-- > 0) {
859 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
860 RELAY_COMMAND_DROP,
861 NULL, 0, circ->cpath->prev)<0) {
862 return; /* stop if error */
868 /** Return true iff we believe ourselves to be an authoritative
869 * directory server.
872 authdir_mode(or_options_t *options)
874 return options->AuthoritativeDir != 0;
876 /** Return true iff we believe ourselves to be a v1 authoritative
877 * directory server.
880 authdir_mode_v1(or_options_t *options)
882 return authdir_mode(options) && options->V1AuthoritativeDir != 0;
884 /** Return true iff we believe ourselves to be a v2 authoritative
885 * directory server.
888 authdir_mode_v2(or_options_t *options)
890 return authdir_mode(options) && options->V2AuthoritativeDir != 0;
892 /** Return true iff we believe ourselves to be a v3 authoritative
893 * directory server.
896 authdir_mode_v3(or_options_t *options)
898 return authdir_mode(options) && options->V3AuthoritativeDir != 0;
900 /** Return true iff we are a v1, v2, or v3 directory authority. */
902 authdir_mode_any_main(or_options_t *options)
904 return options->V1AuthoritativeDir ||
905 options->V2AuthoritativeDir ||
906 options->V3AuthoritativeDir;
908 /** Return true if we believe ourselves to be any kind of
909 * authoritative directory beyond just a hidserv authority. */
911 authdir_mode_any_nonhidserv(or_options_t *options)
913 return options->BridgeAuthoritativeDir ||
914 authdir_mode_any_main(options);
916 /** Return true iff we are an authoritative directory server that is
917 * authoritative about receiving and serving descriptors of type
918 * <b>purpose</b> its dirport. Use -1 for "any purpose". */
920 authdir_mode_handles_descs(or_options_t *options, int purpose)
922 if (purpose < 0)
923 return authdir_mode_any_nonhidserv(options);
924 else if (purpose == ROUTER_PURPOSE_GENERAL)
925 return authdir_mode_any_main(options);
926 else if (purpose == ROUTER_PURPOSE_BRIDGE)
927 return (options->BridgeAuthoritativeDir);
928 else
929 return 0;
931 /** Return true iff we are an authoritative directory server that
932 * publishes its own network statuses.
935 authdir_mode_publishes_statuses(or_options_t *options)
937 if (authdir_mode_bridge(options))
938 return 0;
939 return authdir_mode_any_nonhidserv(options);
941 /** Return true iff we are an authoritative directory server that
942 * tests reachability of the descriptors it learns about.
945 authdir_mode_tests_reachability(or_options_t *options)
947 return authdir_mode_handles_descs(options, -1);
949 /** Return true iff we believe ourselves to be a bridge authoritative
950 * directory server.
953 authdir_mode_bridge(or_options_t *options)
955 return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
957 /** Return true iff we once tried to stay connected to all ORs at once.
958 * FFFF this function, and the notion of staying connected to ORs, is
959 * nearly obsolete. One day there will be a proposal for getting rid of
960 * it.
963 clique_mode(or_options_t *options)
965 return authdir_mode_tests_reachability(options);
968 /** Return true iff we are trying to be a server.
971 server_mode(or_options_t *options)
973 if (options->ClientOnly) return 0;
974 return (options->ORPort != 0 || options->ORListenAddress);
977 /** Remember if we've advertised ourselves to the dirservers. */
978 static int server_is_advertised=0;
980 /** Return true iff we have published our descriptor lately.
983 advertised_server_mode(void)
985 return server_is_advertised;
989 * Called with a boolean: set whether we have recently published our
990 * descriptor.
992 static void
993 set_server_advertised(int s)
995 server_is_advertised = s;
998 /** Return true iff we are trying to be a socks proxy. */
1000 proxy_mode(or_options_t *options)
1002 return (options->SocksPort != 0 || options->SocksListenAddress ||
1003 options->TransPort != 0 || options->TransListenAddress ||
1004 options->NatdPort != 0 || options->NatdListenAddress ||
1005 options->DNSPort != 0 || options->DNSListenAddress);
1008 /** Decide if we're a publishable server. We are a publishable server if:
1009 * - We don't have the ClientOnly option set
1010 * and
1011 * - We have the PublishServerDescriptor option set to non-empty
1012 * and
1013 * - We have ORPort set
1014 * and
1015 * - We believe we are reachable from the outside; or
1016 * - We are an authoritative directory server.
1018 static int
1019 decide_if_publishable_server(void)
1021 or_options_t *options = get_options();
1023 if (options->ClientOnly)
1024 return 0;
1025 if (options->_PublishServerDescriptor == NO_AUTHORITY)
1026 return 0;
1027 if (!server_mode(options))
1028 return 0;
1029 if (authdir_mode(options))
1030 return 1;
1032 return check_whether_orport_reachable();
1035 /** Initiate server descriptor upload as reasonable (if server is publishable,
1036 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1038 * We need to rebuild the descriptor if it's dirty even if we're not
1039 * uploading, because our reachability testing *uses* our descriptor to
1040 * determine what IP address and ports to test.
1042 void
1043 consider_publishable_server(int force)
1045 int rebuilt;
1047 if (!server_mode(get_options()))
1048 return;
1050 rebuilt = router_rebuild_descriptor(0);
1051 if (decide_if_publishable_server()) {
1052 set_server_advertised(1);
1053 if (rebuilt == 0)
1054 router_upload_dir_desc_to_dirservers(force);
1055 } else {
1056 set_server_advertised(0);
1061 * Clique maintenance -- to be phased out.
1064 /** Return true iff we believe this OR tries to keep connections open
1065 * to all other ORs. */
1067 router_is_clique_mode(routerinfo_t *router)
1069 if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
1070 return 1;
1071 return 0;
1075 * OR descriptor generation.
1078 /** My routerinfo. */
1079 static routerinfo_t *desc_routerinfo = NULL;
1080 /** My extrainfo */
1081 static extrainfo_t *desc_extrainfo = NULL;
1082 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1083 * now. */
1084 static time_t desc_clean_since = 0;
1085 /** Boolean: do we need to regenerate the above? */
1086 static int desc_needs_upload = 0;
1088 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1089 * descriptor successfully yet, try to upload our signed descriptor to
1090 * all the directory servers we know about.
1092 void
1093 router_upload_dir_desc_to_dirservers(int force)
1095 routerinfo_t *ri;
1096 extrainfo_t *ei;
1097 char *msg;
1098 size_t desc_len, extra_len = 0, total_len;
1099 authority_type_t auth = get_options()->_PublishServerDescriptor;
1101 ri = router_get_my_routerinfo();
1102 if (!ri) {
1103 log_info(LD_GENERAL, "No descriptor; skipping upload");
1104 return;
1106 ei = router_get_my_extrainfo();
1107 if (auth == NO_AUTHORITY)
1108 return;
1109 if (!force && !desc_needs_upload)
1110 return;
1111 desc_needs_upload = 0;
1113 desc_len = ri->cache_info.signed_descriptor_len;
1114 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1115 total_len = desc_len + extra_len + 1;
1116 msg = tor_malloc(total_len);
1117 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1118 if (ei) {
1119 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1121 msg[desc_len+extra_len] = 0;
1123 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
1124 (auth & BRIDGE_AUTHORITY) ?
1125 ROUTER_PURPOSE_BRIDGE :
1126 ROUTER_PURPOSE_GENERAL,
1127 auth, msg, desc_len, extra_len);
1128 tor_free(msg);
1131 /** OR only: Check whether my exit policy says to allow connection to
1132 * conn. Return 0 if we accept; non-0 if we reject.
1135 router_compare_to_my_exit_policy(edge_connection_t *conn)
1137 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1138 return -1;
1140 /* make sure it's resolved to something. this way we can't get a
1141 'maybe' below. */
1142 if (tor_addr_is_null(&conn->_base.addr))
1143 return -1;
1145 /* XXXX IPv6 */
1146 if (tor_addr_family(&conn->_base.addr) != AF_INET)
1147 return -1;
1149 return compare_tor_addr_to_addr_policy(&conn->_base.addr, conn->_base.port,
1150 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
1153 /** Return true iff I'm a server and <b>digest</b> is equal to
1154 * my identity digest. */
1156 router_digest_is_me(const char *digest)
1158 return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
1161 /** Return true iff I'm a server and <b>digest</b> is equal to
1162 * my identity digest. */
1164 router_extrainfo_digest_is_me(const char *digest)
1166 extrainfo_t *ei = router_get_my_extrainfo();
1167 if (!ei)
1168 return 0;
1170 return !memcmp(digest,
1171 ei->cache_info.signed_descriptor_digest,
1172 DIGEST_LEN);
1175 /** A wrapper around router_digest_is_me(). */
1177 router_is_me(routerinfo_t *router)
1179 return router_digest_is_me(router->cache_info.identity_digest);
1182 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1184 router_fingerprint_is_me(const char *fp)
1186 char digest[DIGEST_LEN];
1187 if (strlen(fp) == HEX_DIGEST_LEN &&
1188 base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
1189 return router_digest_is_me(digest);
1191 return 0;
1194 /** Return a routerinfo for this OR, rebuilding a fresh one if
1195 * necessary. Return NULL on error, or if called on an OP. */
1196 routerinfo_t *
1197 router_get_my_routerinfo(void)
1199 if (!server_mode(get_options()))
1200 return NULL;
1201 if (router_rebuild_descriptor(0))
1202 return NULL;
1203 return desc_routerinfo;
1206 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1207 * one if necessary. Return NULL on error.
1209 const char *
1210 router_get_my_descriptor(void)
1212 const char *body;
1213 if (!router_get_my_routerinfo())
1214 return NULL;
1215 /* Make sure this is nul-terminated. */
1216 tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
1217 body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
1218 tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
1219 log_debug(LD_GENERAL,"my desc is '%s'", body);
1220 return body;
1223 /** Return the extrainfo document for this OR, or NULL if we have none.
1224 * Rebuilt it (and the server descriptor) if necessary. */
1225 extrainfo_t *
1226 router_get_my_extrainfo(void)
1228 if (!server_mode(get_options()))
1229 return NULL;
1230 if (router_rebuild_descriptor(0))
1231 return NULL;
1232 return desc_extrainfo;
1235 /** A list of nicknames that we've warned about including in our family
1236 * declaration verbatim rather than as digests. */
1237 static smartlist_t *warned_nonexistent_family = NULL;
1239 static int router_guess_address_from_dir_headers(uint32_t *guess);
1241 /** Make a current best guess at our address, either because
1242 * it's configured in torrc, or because we've learned it from
1243 * dirserver headers. Place the answer in *<b>addr</b> and return
1244 * 0 on success, else return -1 if we have no guess. */
1246 router_pick_published_address(or_options_t *options, uint32_t *addr)
1248 if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
1249 log_info(LD_CONFIG, "Could not determine our address locally. "
1250 "Checking if directory headers provide any hints.");
1251 if (router_guess_address_from_dir_headers(addr) < 0) {
1252 log_info(LD_CONFIG, "No hints from directory headers either. "
1253 "Will try again later.");
1254 return -1;
1257 return 0;
1260 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1261 * routerinfo, signed server descriptor, and extra-info document for this OR.
1262 * Return 0 on success, -1 on temporary error.
1265 router_rebuild_descriptor(int force)
1267 routerinfo_t *ri;
1268 extrainfo_t *ei;
1269 uint32_t addr;
1270 char platform[256];
1271 int hibernating = we_are_hibernating();
1272 size_t ei_size;
1273 or_options_t *options = get_options();
1275 if (desc_clean_since && !force)
1276 return 0;
1278 if (router_pick_published_address(options, &addr) < 0) {
1279 /* Stop trying to rebuild our descriptor every second. We'll
1280 * learn that it's time to try again when server_has_changed_ip()
1281 * marks it dirty. */
1282 desc_clean_since = time(NULL);
1283 return -1;
1286 ri = tor_malloc_zero(sizeof(routerinfo_t));
1287 ri->cache_info.routerlist_index = -1;
1288 ri->address = tor_dup_ip(addr);
1289 ri->nickname = tor_strdup(options->Nickname);
1290 ri->addr = addr;
1291 ri->or_port = options->ORPort;
1292 ri->dir_port = options->DirPort;
1293 ri->cache_info.published_on = time(NULL);
1294 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
1295 * main thread */
1296 ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
1297 if (crypto_pk_get_digest(ri->identity_pkey,
1298 ri->cache_info.identity_digest)<0) {
1299 routerinfo_free(ri);
1300 return -1;
1302 get_platform_str(platform, sizeof(platform));
1303 ri->platform = tor_strdup(platform);
1305 /* compute ri->bandwidthrate as the min of various options */
1306 ri->bandwidthrate = get_effective_bwrate(options);
1308 /* and compute ri->bandwidthburst similarly */
1309 ri->bandwidthburst = get_effective_bwburst(options);
1311 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
1313 policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
1314 options->ExitPolicyRejectPrivate,
1315 ri->address);
1317 if (desc_routerinfo) { /* inherit values */
1318 ri->is_valid = desc_routerinfo->is_valid;
1319 ri->is_running = desc_routerinfo->is_running;
1320 ri->is_named = desc_routerinfo->is_named;
1322 if (authdir_mode(options))
1323 ri->is_valid = ri->is_named = 1; /* believe in yourself */
1324 if (options->MyFamily) {
1325 smartlist_t *family;
1326 if (!warned_nonexistent_family)
1327 warned_nonexistent_family = smartlist_create();
1328 family = smartlist_create();
1329 ri->declared_family = smartlist_create();
1330 smartlist_split_string(family, options->MyFamily, ",",
1331 SPLIT_SKIP_SPACE|SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1332 SMARTLIST_FOREACH(family, char *, name,
1334 routerinfo_t *member;
1335 if (!strcasecmp(name, options->Nickname))
1336 member = ri;
1337 else
1338 member = router_get_by_nickname(name, 1);
1339 if (!member) {
1340 int is_legal = is_legal_nickname_or_hexdigest(name);
1341 if (!smartlist_string_isin(warned_nonexistent_family, name) &&
1342 !is_legal_hexdigest(name)) {
1343 if (is_legal)
1344 log_warn(LD_CONFIG,
1345 "I have no descriptor for the router named \"%s\" in my "
1346 "declared family; I'll use the nickname as is, but "
1347 "this may confuse clients.", name);
1348 else
1349 log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
1350 "declared family, but that isn't a legal nickname. "
1351 "Skipping it.", escaped(name));
1352 smartlist_add(warned_nonexistent_family, tor_strdup(name));
1354 if (is_legal) {
1355 smartlist_add(ri->declared_family, name);
1356 name = NULL;
1358 } else if (router_is_me(member)) {
1359 /* Don't list ourself in our own family; that's redundant */
1360 } else {
1361 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1362 fp[0] = '$';
1363 base16_encode(fp+1,HEX_DIGEST_LEN+1,
1364 member->cache_info.identity_digest, DIGEST_LEN);
1365 smartlist_add(ri->declared_family, fp);
1366 if (smartlist_string_isin(warned_nonexistent_family, name))
1367 smartlist_string_remove(warned_nonexistent_family, name);
1369 tor_free(name);
1372 /* remove duplicates from the list */
1373 smartlist_sort_strings(ri->declared_family);
1374 smartlist_uniq_strings(ri->declared_family);
1376 smartlist_free(family);
1379 /* Now generate the extrainfo. */
1380 ei = tor_malloc_zero(sizeof(extrainfo_t));
1381 ei->cache_info.is_extrainfo = 1;
1382 strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
1383 ei->cache_info.published_on = ri->cache_info.published_on;
1384 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
1385 DIGEST_LEN);
1386 ei_size = options->ExtraInfoStatistics ? MAX_EXTRAINFO_UPLOAD_SIZE : 8192;
1387 ei->cache_info.signed_descriptor_body = tor_malloc(ei_size);
1388 if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body,
1389 ei_size, ei, get_identity_key()) < 0) {
1390 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
1391 extrainfo_free(ei);
1392 return -1;
1394 ei->cache_info.signed_descriptor_len =
1395 strlen(ei->cache_info.signed_descriptor_body);
1396 router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
1397 ei->cache_info.signed_descriptor_digest);
1399 /* Now finish the router descriptor. */
1400 memcpy(ri->cache_info.extra_info_digest,
1401 ei->cache_info.signed_descriptor_digest,
1402 DIGEST_LEN);
1403 ri->cache_info.signed_descriptor_body = tor_malloc(8192);
1404 if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
1405 ri, get_identity_key())<0) {
1406 log_warn(LD_BUG, "Couldn't generate router descriptor.");
1407 return -1;
1409 ri->cache_info.signed_descriptor_len =
1410 strlen(ri->cache_info.signed_descriptor_body);
1412 ri->purpose =
1413 options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
1414 ri->cache_info.send_unencrypted = 1;
1415 /* Let bridges serve their own descriptors unencrypted, so they can
1416 * pass reachability testing. (If they want to be harder to notice,
1417 * they can always leave the DirPort off). */
1418 if (!options->BridgeRelay)
1419 ei->cache_info.send_unencrypted = 1;
1421 router_get_router_hash(ri->cache_info.signed_descriptor_body,
1422 ri->cache_info.signed_descriptor_digest);
1424 routerinfo_set_country(ri);
1426 tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
1428 if (desc_routerinfo)
1429 routerinfo_free(desc_routerinfo);
1430 desc_routerinfo = ri;
1431 if (desc_extrainfo)
1432 extrainfo_free(desc_extrainfo);
1433 desc_extrainfo = ei;
1435 desc_clean_since = time(NULL);
1436 desc_needs_upload = 1;
1437 control_event_my_descriptor_changed();
1438 return 0;
1441 /** Mark descriptor out of date if it's older than <b>when</b> */
1442 void
1443 mark_my_descriptor_dirty_if_older_than(time_t when)
1445 if (desc_clean_since < when)
1446 mark_my_descriptor_dirty();
1449 /** Call when the current descriptor is out of date. */
1450 void
1451 mark_my_descriptor_dirty(void)
1453 desc_clean_since = 0;
1456 /** How frequently will we republish our descriptor because of large (factor
1457 * of 2) shifts in estimated bandwidth? */
1458 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
1460 /** Check whether bandwidth has changed a lot since the last time we announced
1461 * bandwidth. If so, mark our descriptor dirty. */
1462 void
1463 check_descriptor_bandwidth_changed(time_t now)
1465 static time_t last_changed = 0;
1466 uint64_t prev, cur;
1467 if (!desc_routerinfo)
1468 return;
1470 prev = desc_routerinfo->bandwidthcapacity;
1471 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
1472 if ((prev != cur && (!prev || !cur)) ||
1473 cur > prev*2 ||
1474 cur < prev/2) {
1475 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
1476 log_info(LD_GENERAL,
1477 "Measured bandwidth has changed; rebuilding descriptor.");
1478 mark_my_descriptor_dirty();
1479 last_changed = now;
1484 /** Note at log level severity that our best guess of address has changed from
1485 * <b>prev</b> to <b>cur</b>. */
1486 static void
1487 log_addr_has_changed(int severity, uint32_t prev, uint32_t cur,
1488 const char *source)
1490 char addrbuf_prev[INET_NTOA_BUF_LEN];
1491 char addrbuf_cur[INET_NTOA_BUF_LEN];
1492 struct in_addr in_prev;
1493 struct in_addr in_cur;
1495 in_prev.s_addr = htonl(prev);
1496 tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
1498 in_cur.s_addr = htonl(cur);
1499 tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
1501 if (prev)
1502 log_fn(severity, LD_GENERAL,
1503 "Our IP Address has changed from %s to %s; "
1504 "rebuilding descriptor (source: %s).",
1505 addrbuf_prev, addrbuf_cur, source);
1506 else
1507 log_notice(LD_GENERAL,
1508 "Guessed our IP address as %s (source: %s).",
1509 addrbuf_cur, source);
1512 /** Check whether our own address as defined by the Address configuration
1513 * has changed. This is for routers that get their address from a service
1514 * like dyndns. If our address has changed, mark our descriptor dirty. */
1515 void
1516 check_descriptor_ipaddress_changed(time_t now)
1518 uint32_t prev, cur;
1519 or_options_t *options = get_options();
1520 (void) now;
1522 if (!desc_routerinfo)
1523 return;
1525 prev = desc_routerinfo->addr;
1526 if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
1527 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
1528 return;
1531 if (prev != cur) {
1532 log_addr_has_changed(LOG_NOTICE, prev, cur, "resolve");
1533 ip_address_changed(0);
1537 /** The most recently guessed value of our IP address, based on directory
1538 * headers. */
1539 static uint32_t last_guessed_ip = 0;
1541 /** A directory server <b>d_conn</b> told us our IP address is
1542 * <b>suggestion</b>.
1543 * If this address is different from the one we think we are now, and
1544 * if our computer doesn't actually know its IP address, then switch. */
1545 void
1546 router_new_address_suggestion(const char *suggestion,
1547 const dir_connection_t *d_conn)
1549 uint32_t addr, cur = 0;
1550 struct in_addr in;
1551 or_options_t *options = get_options();
1553 /* first, learn what the IP address actually is */
1554 if (!tor_inet_aton(suggestion, &in)) {
1555 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
1556 escaped(suggestion));
1557 return;
1559 addr = ntohl(in.s_addr);
1561 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
1563 if (!server_mode(options)) {
1564 last_guessed_ip = addr; /* store it in case we need it later */
1565 return;
1568 if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
1569 /* We're all set -- we already know our address. Great. */
1570 last_guessed_ip = cur; /* store it in case we need it later */
1571 return;
1573 if (is_internal_IP(addr, 0)) {
1574 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1575 return;
1577 if (tor_addr_eq_ipv4h(&d_conn->_base.addr, addr)) {
1578 /* Don't believe anybody who says our IP is their IP. */
1579 log_debug(LD_DIR, "A directory server told us our IP address is %s, "
1580 "but he's just reporting his own IP address. Ignoring.",
1581 suggestion);
1582 return;
1585 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1586 * us an answer different from what we had the last time we managed to
1587 * resolve it. */
1588 if (last_guessed_ip != addr) {
1589 control_event_server_status(LOG_NOTICE,
1590 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1591 suggestion);
1592 log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr,
1593 d_conn->_base.address);
1594 ip_address_changed(0);
1595 last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
1599 /** We failed to resolve our address locally, but we'd like to build
1600 * a descriptor and publish / test reachability. If we have a guess
1601 * about our address based on directory headers, answer it and return
1602 * 0; else return -1. */
1603 static int
1604 router_guess_address_from_dir_headers(uint32_t *guess)
1606 if (last_guessed_ip) {
1607 *guess = last_guessed_ip;
1608 return 0;
1610 return -1;
1613 extern const char tor_svn_revision[]; /* from tor_main.c */
1615 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1616 * string describing the version of Tor and the operating system we're
1617 * currently running on.
1619 void
1620 get_platform_str(char *platform, size_t len)
1622 tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
1625 /* XXX need to audit this thing and count fenceposts. maybe
1626 * refactor so we don't have to keep asking if we're
1627 * near the end of maxlen?
1629 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1631 /** OR only: Given a routerinfo for this router, and an identity key to sign
1632 * with, encode the routerinfo as a signed server descriptor and write the
1633 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1634 * failure, and the number of bytes used on success.
1637 router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
1638 crypto_pk_env_t *ident_key)
1640 char *onion_pkey; /* Onion key, PEM-encoded. */
1641 char *identity_pkey; /* Identity key, PEM-encoded. */
1642 char digest[DIGEST_LEN];
1643 char published[ISO_TIME_LEN+1];
1644 char fingerprint[FINGERPRINT_LEN+1];
1645 char extra_info_digest[HEX_DIGEST_LEN+1];
1646 size_t onion_pkeylen, identity_pkeylen;
1647 size_t written;
1648 int result=0;
1649 addr_policy_t *tmpe;
1650 char *family_line;
1651 or_options_t *options = get_options();
1653 /* Make sure the identity key matches the one in the routerinfo. */
1654 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
1655 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
1656 "match router's public key!");
1657 return -1;
1660 /* record our fingerprint, so we can include it in the descriptor */
1661 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
1662 log_err(LD_BUG,"Error computing fingerprint");
1663 return -1;
1666 /* PEM-encode the onion key */
1667 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
1668 &onion_pkey,&onion_pkeylen)<0) {
1669 log_warn(LD_BUG,"write onion_pkey to string failed!");
1670 return -1;
1673 /* PEM-encode the identity key key */
1674 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
1675 &identity_pkey,&identity_pkeylen)<0) {
1676 log_warn(LD_BUG,"write identity_pkey to string failed!");
1677 tor_free(onion_pkey);
1678 return -1;
1681 /* Encode the publication time. */
1682 format_iso_time(published, router->cache_info.published_on);
1684 if (router->declared_family && smartlist_len(router->declared_family)) {
1685 size_t n;
1686 char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
1687 n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1688 family_line = tor_malloc(n);
1689 tor_snprintf(family_line, n, "family %s\n", family);
1690 tor_free(family);
1691 } else {
1692 family_line = tor_strdup("");
1695 base16_encode(extra_info_digest, sizeof(extra_info_digest),
1696 router->cache_info.extra_info_digest, DIGEST_LEN);
1698 /* Generate the easy portion of the router descriptor. */
1699 result = tor_snprintf(s, maxlen,
1700 "router %s %s %d 0 %d\n"
1701 "platform %s\n"
1702 "opt protocols Link 1 2 Circuit 1\n"
1703 "published %s\n"
1704 "opt fingerprint %s\n"
1705 "uptime %ld\n"
1706 "bandwidth %d %d %d\n"
1707 "opt extra-info-digest %s\n%s"
1708 "onion-key\n%s"
1709 "signing-key\n%s"
1710 "%s%s%s%s",
1711 router->nickname,
1712 router->address,
1713 router->or_port,
1714 decide_to_advertise_dirport(options, router->dir_port),
1715 router->platform,
1716 published,
1717 fingerprint,
1718 stats_n_seconds_working,
1719 (int) router->bandwidthrate,
1720 (int) router->bandwidthburst,
1721 (int) router->bandwidthcapacity,
1722 extra_info_digest,
1723 options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
1724 onion_pkey, identity_pkey,
1725 family_line,
1726 we_are_hibernating() ? "opt hibernating 1\n" : "",
1727 options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "",
1728 options->AllowSingleHopExits ? "opt allow-single-hop-exits\n" : "");
1730 tor_free(family_line);
1731 tor_free(onion_pkey);
1732 tor_free(identity_pkey);
1734 if (result < 0) {
1735 log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
1736 return -1;
1738 /* From now on, we use 'written' to remember the current length of 's'. */
1739 written = result;
1741 if (options->ContactInfo && strlen(options->ContactInfo)) {
1742 const char *ci = options->ContactInfo;
1743 if (strchr(ci, '\n') || strchr(ci, '\r'))
1744 ci = escaped(ci);
1745 result = tor_snprintf(s+written,maxlen-written, "contact %s\n", ci);
1746 if (result<0) {
1747 log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
1748 return -1;
1750 written += result;
1753 /* Write the exit policy to the end of 's'. */
1754 if (dns_seems_to_be_broken() || has_dns_init_failed() ||
1755 !router->exit_policy || !smartlist_len(router->exit_policy)) {
1756 /* DNS is screwed up; don't claim to be an exit. */
1757 strlcat(s+written, "reject *:*\n", maxlen-written);
1758 written += strlen("reject *:*\n");
1759 tmpe = NULL;
1760 } else if (router->exit_policy) {
1761 int i;
1762 for (i = 0; i < smartlist_len(router->exit_policy); ++i) {
1763 tmpe = smartlist_get(router->exit_policy, i);
1764 result = policy_write_item(s+written, maxlen-written, tmpe, 1);
1765 if (result < 0) {
1766 log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
1767 return -1;
1769 tor_assert(result == (int)strlen(s+written));
1770 written += result;
1771 if (written+2 > maxlen) {
1772 log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
1773 return -1;
1775 s[written++] = '\n';
1779 if (written+256 > maxlen) { /* Not enough room for signature. */
1780 log_warn(LD_BUG,"not enough room left in descriptor for signature!");
1781 return -1;
1784 /* Sign the descriptor */
1785 strlcpy(s+written, "router-signature\n", maxlen-written);
1786 written += strlen(s+written);
1787 s[written] = '\0';
1788 if (router_get_router_hash(s, digest) < 0) {
1789 return -1;
1792 note_crypto_pk_op(SIGN_RTR);
1793 if (router_append_dirobj_signature(s+written,maxlen-written,
1794 digest,ident_key)<0) {
1795 log_warn(LD_BUG, "Couldn't sign router descriptor");
1796 return -1;
1798 written += strlen(s+written);
1800 if (written+2 > maxlen) {
1801 log_warn(LD_BUG,"Not enough room to finish descriptor.");
1802 return -1;
1804 /* include a last '\n' */
1805 s[written] = '\n';
1806 s[written+1] = 0;
1808 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1810 char *s_dup;
1811 const char *cp;
1812 routerinfo_t *ri_tmp;
1813 cp = s_dup = tor_strdup(s);
1814 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
1815 if (!ri_tmp) {
1816 log_err(LD_BUG,
1817 "We just generated a router descriptor we can't parse.");
1818 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1819 return -1;
1821 tor_free(s_dup);
1822 routerinfo_free(ri_tmp);
1824 #endif
1826 return (int)written+1;
1829 /** Load the contents of <b>filename</b>, find the first line starting
1830 * with <b>end_line</b> that has a timestamp after <b>after</b>, and write
1831 * the file contents starting with that line to **<b>contents</b>. Return
1832 * 1 for success, 0 if the file does not exist or does not contain a line
1833 * matching these criteria, or -1 for failure. */
1834 static int
1835 load_stats_file(const char *filename, const char *end_line, time_t after,
1836 char **out)
1838 int r = -1;
1839 char *fname = get_datadir_fname(filename);
1840 char *contents, *start, timestr[ISO_TIME_LEN+1];
1841 time_t written;
1842 switch (file_status(fname)) {
1843 case FN_FILE:
1844 if ((contents = read_file_to_str(fname, 0, NULL))) {
1845 do {
1846 if ((start = strstr(contents, end_line)))
1847 goto err;
1848 if (strlen(start) < strlen(end_line) + sizeof(timestr))
1849 goto err;
1850 if (strlcpy(timestr, start + strlen(end_line), sizeof(timestr)))
1851 goto err;
1852 if (parse_iso_time(timestr, &written) < 0)
1853 goto err;
1854 } while (written < after);
1855 *out = tor_malloc(strlen(start));
1856 strlcpy(*out, start, strlen(start));
1857 r = 1;
1859 err:
1860 tor_free(contents);
1861 break;
1862 case FN_NOENT:
1863 r = 0;
1864 break;
1865 case FN_ERROR:
1866 case FN_DIR:
1867 default:
1868 break;
1870 tor_free(fname);
1871 return r;
1874 /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
1875 * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
1876 * negative on failure. */
1878 extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
1879 crypto_pk_env_t *ident_key)
1881 or_options_t *options = get_options();
1882 char identity[HEX_DIGEST_LEN+1];
1883 char published[ISO_TIME_LEN+1];
1884 char digest[DIGEST_LEN];
1885 char *bandwidth_usage;
1886 int result;
1887 size_t len;
1888 static int write_stats_to_extrainfo = 1;
1890 base16_encode(identity, sizeof(identity),
1891 extrainfo->cache_info.identity_digest, DIGEST_LEN);
1892 format_iso_time(published, extrainfo->cache_info.published_on);
1893 bandwidth_usage = rep_hist_get_bandwidth_lines(1);
1895 result = tor_snprintf(s, maxlen,
1896 "extra-info %s %s\n"
1897 "published %s\n%s",
1898 extrainfo->nickname, identity,
1899 published, bandwidth_usage);
1901 if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
1902 char *contents = NULL;
1903 time_t since = time(NULL) - (24*60*60);
1904 log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
1905 if (options->DirReqStatistics &&
1906 load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
1907 "dirreq-stats-end", since, &contents) > 0) {
1908 int pos = strlen(s);
1909 if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
1910 strlen(contents)) {
1911 log_warn(LD_DIR, "Could not write dirreq-stats to extra-info "
1912 "descriptor.");
1913 s[pos] = '\0';
1915 tor_free(contents);
1917 if (options->EntryStatistics &&
1918 load_stats_file("stats"PATH_SEPARATOR"entry-stats",
1919 "entry-stats-end", since, &contents) > 0) {
1920 int pos = strlen(s);
1921 if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
1922 strlen(contents)) {
1923 log_warn(LD_DIR, "Could not write entry-stats to extra-info "
1924 "descriptor.");
1925 s[pos] = '\0';
1927 tor_free(contents);
1929 if (options->CellStatistics &&
1930 load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
1931 "cell-stats-end", since, &contents) > 0) {
1932 int pos = strlen(s);
1933 if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
1934 strlen(contents)) {
1935 log_warn(LD_DIR, "Could not write buffer-stats to extra-info "
1936 "descriptor.");
1937 s[pos] = '\0';
1939 tor_free(contents);
1941 if (options->ExitPortStatistics &&
1942 load_stats_file("stats"PATH_SEPARATOR"exit-stats",
1943 "exit-stats-end", since, &contents) > 0) {
1944 int pos = strlen(s);
1945 if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
1946 strlen(contents)) {
1947 log_warn(LD_DIR, "Could not write exit-stats to extra-info "
1948 "descriptor.");
1949 s[pos] = '\0';
1951 tor_free(contents);
1955 tor_free(bandwidth_usage);
1956 if (result<0)
1957 return -1;
1959 if (should_record_bridge_info(options)) {
1960 char *geoip_summary = extrainfo_get_client_geoip_summary(time(NULL));
1961 if (geoip_summary) {
1962 char geoip_start[ISO_TIME_LEN+1];
1963 format_iso_time(geoip_start, geoip_get_history_start());
1964 result = tor_snprintf(s+strlen(s), maxlen-strlen(s),
1965 "geoip-start-time %s\n"
1966 "geoip-client-origins %s\n",
1967 geoip_start, geoip_summary);
1968 control_event_clients_seen(geoip_start, geoip_summary);
1969 tor_free(geoip_summary);
1970 if (result<0)
1971 return -1;
1975 len = strlen(s);
1976 strlcat(s+len, "router-signature\n", maxlen-len);
1977 len += strlen(s+len);
1978 if (router_get_extrainfo_hash(s, digest)<0)
1979 return -1;
1980 if (router_append_dirobj_signature(s+len, maxlen-len, digest, ident_key)<0)
1981 return -1;
1984 char *cp, *s_dup;
1985 extrainfo_t *ei_tmp;
1986 cp = s_dup = tor_strdup(s);
1987 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
1988 if (!ei_tmp) {
1989 log_err(LD_BUG,
1990 "We just generated an extrainfo descriptor we can't parse.");
1991 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1992 return -1;
1994 tor_free(s_dup);
1995 extrainfo_free(ei_tmp);
1998 if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
1999 char *cp, *s_dup;
2000 extrainfo_t *ei_tmp;
2001 cp = s_dup = tor_strdup(s);
2002 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
2003 if (!ei_tmp) {
2004 log_warn(LD_GENERAL,
2005 "We just generated an extra-info descriptor with "
2006 "statistics that we can't parse. Not adding statistics to "
2007 "this or any future extra-info descriptors. Descriptor "
2008 "was:\n%s", s);
2009 write_stats_to_extrainfo = 0;
2010 tor_free(s);
2011 s = NULL;
2012 extrainfo_dump_to_string(s, maxlen, extrainfo, ident_key);
2014 tor_free(s_dup);
2015 extrainfo_free(ei_tmp);
2018 log_info(LD_GENERAL, "Done with dumping our extra-info descriptor.");
2020 return (int)strlen(s)+1;
2023 /** Wrapper function for geoip_get_client_history(). It first discards
2024 * any items in the client history that are too old -- it dumps anything
2025 * more than 48 hours old, but it only considers whether to dump at most
2026 * once per 48 hours, so we aren't too precise to an observer (see also
2027 * r14780).
2029 char *
2030 extrainfo_get_client_geoip_summary(time_t now)
2032 static time_t last_purged_at = 0;
2033 int geoip_purge_interval =
2034 (get_options()->DirReqStatistics || get_options()->EntryStatistics) ?
2035 DIR_ENTRY_RECORD_USAGE_RETAIN_IPS : 48*60*60;
2036 if (now > last_purged_at+geoip_purge_interval) {
2037 /* (Note that this also discards items in the client history with
2038 * action GEOIP_CLIENT_NETWORKSTATUS{_V2}, which doesn't matter
2039 * because bridge and directory stats are independent. Keep in mind
2040 * for future extensions, though.) */
2041 geoip_remove_old_clients(now-geoip_purge_interval);
2042 last_purged_at = now;
2044 return geoip_get_client_history_bridge(now, GEOIP_CLIENT_CONNECT);
2047 /** Return true iff <b>s</b> is a legally valid server nickname. */
2049 is_legal_nickname(const char *s)
2051 size_t len;
2052 tor_assert(s);
2053 len = strlen(s);
2054 return len > 0 && len <= MAX_NICKNAME_LEN &&
2055 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
2058 /** Return true iff <b>s</b> is a legally valid server nickname or
2059 * hex-encoded identity-key digest. */
2061 is_legal_nickname_or_hexdigest(const char *s)
2063 if (*s!='$')
2064 return is_legal_nickname(s);
2065 else
2066 return is_legal_hexdigest(s);
2069 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
2070 * digest. */
2072 is_legal_hexdigest(const char *s)
2074 size_t len;
2075 tor_assert(s);
2076 if (s[0] == '$') s++;
2077 len = strlen(s);
2078 if (len > HEX_DIGEST_LEN) {
2079 if (s[HEX_DIGEST_LEN] == '=' ||
2080 s[HEX_DIGEST_LEN] == '~') {
2081 if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
2082 return 0;
2083 } else {
2084 return 0;
2087 return (len >= HEX_DIGEST_LEN &&
2088 strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
2091 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
2092 * verbose representation of the identity of <b>router</b>. The format is:
2093 * A dollar sign.
2094 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
2095 * A "=" if the router is named; a "~" if it is not.
2096 * The router's nickname.
2098 void
2099 router_get_verbose_nickname(char *buf, const routerinfo_t *router)
2101 buf[0] = '$';
2102 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
2103 DIGEST_LEN);
2104 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
2105 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
2108 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
2109 * verbose representation of the identity of <b>router</b>. The format is:
2110 * A dollar sign.
2111 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
2112 * A "=" if the router is named; a "~" if it is not.
2113 * The router's nickname.
2115 void
2116 routerstatus_get_verbose_nickname(char *buf, const routerstatus_t *router)
2118 buf[0] = '$';
2119 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->identity_digest,
2120 DIGEST_LEN);
2121 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
2122 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
2125 /** Forget that we have issued any router-related warnings, so that we'll
2126 * warn again if we see the same errors. */
2127 void
2128 router_reset_warnings(void)
2130 if (warned_nonexistent_family) {
2131 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
2132 smartlist_clear(warned_nonexistent_family);
2136 /** Given a router purpose, convert it to a string. Don't call this on
2137 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
2138 * know its string representation. */
2139 const char *
2140 router_purpose_to_string(uint8_t p)
2142 switch (p)
2144 case ROUTER_PURPOSE_GENERAL: return "general";
2145 case ROUTER_PURPOSE_BRIDGE: return "bridge";
2146 case ROUTER_PURPOSE_CONTROLLER: return "controller";
2147 default:
2148 tor_assert(0);
2150 return NULL;
2153 /** Given a string, convert it to a router purpose. */
2154 uint8_t
2155 router_purpose_from_string(const char *s)
2157 if (!strcmp(s, "general"))
2158 return ROUTER_PURPOSE_GENERAL;
2159 else if (!strcmp(s, "bridge"))
2160 return ROUTER_PURPOSE_BRIDGE;
2161 else if (!strcmp(s, "controller"))
2162 return ROUTER_PURPOSE_CONTROLLER;
2163 else
2164 return ROUTER_PURPOSE_UNKNOWN;
2167 /** Release all static resources held in router.c */
2168 void
2169 router_free_all(void)
2171 if (onionkey)
2172 crypto_free_pk_env(onionkey);
2173 if (lastonionkey)
2174 crypto_free_pk_env(lastonionkey);
2175 if (identitykey)
2176 crypto_free_pk_env(identitykey);
2177 if (key_lock)
2178 tor_mutex_free(key_lock);
2179 if (desc_routerinfo)
2180 routerinfo_free(desc_routerinfo);
2181 if (desc_extrainfo)
2182 extrainfo_free(desc_extrainfo);
2183 if (authority_signing_key)
2184 crypto_free_pk_env(authority_signing_key);
2185 if (authority_key_certificate)
2186 authority_cert_free(authority_key_certificate);
2187 if (legacy_signing_key)
2188 crypto_free_pk_env(legacy_signing_key);
2189 if (legacy_key_certificate)
2190 authority_cert_free(legacy_key_certificate);
2192 if (warned_nonexistent_family) {
2193 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
2194 smartlist_free(warned_nonexistent_family);