naked constants are bad
[tor/rransom.git] / src / or / router.c
blobd105aeffad88b6388b8a597d354c9f852f23c906
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"
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 crypto_free_pk_env(onionkey);
65 onionkey = k;
66 onionkey_set_at = time(NULL);
67 tor_mutex_release(key_lock);
68 mark_my_descriptor_dirty();
71 /** Return the current onion key. Requires that the onion key has been
72 * loaded or generated. */
73 crypto_pk_env_t *
74 get_onion_key(void)
76 tor_assert(onionkey);
77 return onionkey;
80 /** Store a full copy of the current onion key into *<b>key</b>, and a full
81 * copy of the most recent onion key into *<b>last</b>.
83 void
84 dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
86 tor_assert(key);
87 tor_assert(last);
88 tor_mutex_acquire(key_lock);
89 tor_assert(onionkey);
90 *key = crypto_pk_copy_full(onionkey);
91 if (lastonionkey)
92 *last = crypto_pk_copy_full(lastonionkey);
93 else
94 *last = NULL;
95 tor_mutex_release(key_lock);
98 /** Return the time when the onion key was last set. This is either the time
99 * when the process launched, or the time of the most recent key rotation since
100 * the process launched.
102 time_t
103 get_onion_key_set_at(void)
105 return onionkey_set_at;
108 /** Set the current identity key to k.
110 void
111 set_identity_key(crypto_pk_env_t *k)
113 crypto_free_pk_env(identitykey);
114 identitykey = k;
115 crypto_pk_get_digest(identitykey, identitykey_digest);
118 /** Returns the current identity key; requires that the identity key has been
119 * set.
121 crypto_pk_env_t *
122 get_identity_key(void)
124 tor_assert(identitykey);
125 return identitykey;
128 /** Return true iff the identity key has been set. */
130 identity_key_is_set(void)
132 return identitykey != NULL;
135 /** Return the key certificate for this v3 (voting) authority, or NULL
136 * if we have no such certificate. */
137 authority_cert_t *
138 get_my_v3_authority_cert(void)
140 return authority_key_certificate;
143 /** Return the v3 signing key for this v3 (voting) authority, or NULL
144 * if we have no such key. */
145 crypto_pk_env_t *
146 get_my_v3_authority_signing_key(void)
148 return authority_signing_key;
151 /** If we're an authority, and we're using a legacy authority identity key for
152 * emergency migration purposes, return the certificate associated with that
153 * key. */
154 authority_cert_t *
155 get_my_v3_legacy_cert(void)
157 return legacy_key_certificate;
160 /** If we're an authority, and we're using a legacy authority identity key for
161 * emergency migration purposes, return that key. */
162 crypto_pk_env_t *
163 get_my_v3_legacy_signing_key(void)
165 return legacy_signing_key;
168 /** Replace the previous onion key with the current onion key, and generate
169 * a new previous onion key. Immediately after calling this function,
170 * the OR should:
171 * - schedule all previous cpuworkers to shut down _after_ processing
172 * pending work. (This will cause fresh cpuworkers to be generated.)
173 * - generate and upload a fresh routerinfo.
175 void
176 rotate_onion_key(void)
178 char *fname, *fname_prev;
179 crypto_pk_env_t *prkey;
180 or_state_t *state = get_or_state();
181 time_t now;
182 fname = get_datadir_fname2("keys", "secret_onion_key");
183 fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
184 if (!(prkey = crypto_new_pk_env())) {
185 log_err(LD_GENERAL,"Error constructing rotated onion key");
186 goto error;
188 if (crypto_pk_generate_key(prkey)) {
189 log_err(LD_BUG,"Error generating onion key");
190 goto error;
192 if (file_status(fname) == FN_FILE) {
193 if (replace_file(fname, fname_prev))
194 goto error;
196 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
197 log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
198 goto error;
200 log_info(LD_GENERAL, "Rotating onion key");
201 tor_mutex_acquire(key_lock);
202 crypto_free_pk_env(lastonionkey);
203 lastonionkey = onionkey;
204 onionkey = prkey;
205 now = time(NULL);
206 state->LastRotatedOnionKey = onionkey_set_at = now;
207 tor_mutex_release(key_lock);
208 mark_my_descriptor_dirty();
209 or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
210 goto done;
211 error:
212 log_warn(LD_GENERAL, "Couldn't rotate onion key.");
213 if (prkey)
214 crypto_free_pk_env(prkey);
215 done:
216 tor_free(fname);
217 tor_free(fname_prev);
220 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
221 * and <b>generate</b> is true, create a new RSA key and save it in
222 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
223 * errors at level <b>severity</b>.
225 crypto_pk_env_t *
226 init_key_from_file(const char *fname, int generate, int severity)
228 crypto_pk_env_t *prkey = NULL;
230 if (!(prkey = crypto_new_pk_env())) {
231 log(severity, LD_GENERAL,"Error constructing key");
232 goto error;
235 switch (file_status(fname)) {
236 case FN_DIR:
237 case FN_ERROR:
238 log(severity, LD_FS,"Can't read key from \"%s\"", fname);
239 goto error;
240 case FN_NOENT:
241 if (generate) {
242 if (!have_lockfile()) {
243 if (try_locking(get_options(), 0)<0) {
244 /* Make sure that --list-fingerprint only creates new keys
245 * if there is no possibility for a deadlock. */
246 log(severity, LD_FS, "Another Tor process has locked \"%s\". Not "
247 "writing any new keys.", fname);
248 /*XXXX The 'other process' might make a key in a second or two;
249 * maybe we should wait for it. */
250 goto error;
253 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
254 fname);
255 if (crypto_pk_generate_key(prkey)) {
256 log(severity, LD_GENERAL,"Error generating onion key");
257 goto error;
259 if (crypto_pk_check_key(prkey) <= 0) {
260 log(severity, LD_GENERAL,"Generated key seems invalid");
261 goto error;
263 log_info(LD_GENERAL, "Generated key seems valid");
264 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
265 log(severity, LD_FS,
266 "Couldn't write generated key to \"%s\".", fname);
267 goto error;
269 } else {
270 log_info(LD_GENERAL, "No key found in \"%s\"", fname);
272 return prkey;
273 case FN_FILE:
274 if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
275 log(severity, LD_GENERAL,"Error loading private key.");
276 goto error;
278 return prkey;
279 default:
280 tor_assert(0);
283 error:
284 if (prkey)
285 crypto_free_pk_env(prkey);
286 return NULL;
289 /** Try to load the vote-signing private key and certificate for being a v3
290 * directory authority, and make sure they match. If <b>legacy</b>, load a
291 * legacy key/cert set for emergency key migration; otherwise load the regular
292 * key/cert set. On success, store them into *<b>key_out</b> and
293 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
294 static int
295 load_authority_keyset(int legacy, crypto_pk_env_t **key_out,
296 authority_cert_t **cert_out)
298 int r = -1;
299 char *fname = NULL, *cert = NULL;
300 const char *eos = NULL;
301 crypto_pk_env_t *signing_key = NULL;
302 authority_cert_t *parsed = NULL;
304 fname = get_datadir_fname2("keys",
305 legacy ? "legacy_signing_key" : "authority_signing_key");
306 signing_key = init_key_from_file(fname, 0, LOG_INFO);
307 if (!signing_key) {
308 log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
309 goto done;
311 tor_free(fname);
312 fname = get_datadir_fname2("keys",
313 legacy ? "legacy_certificate" : "authority_certificate");
314 cert = read_file_to_str(fname, 0, NULL);
315 if (!cert) {
316 log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
317 fname);
318 goto done;
320 parsed = authority_cert_parse_from_string(cert, &eos);
321 if (!parsed) {
322 log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
323 goto done;
325 if (crypto_pk_cmp_keys(signing_key, parsed->signing_key) != 0) {
326 log_warn(LD_DIR, "Stored signing key does not match signing key in "
327 "certificate");
328 goto done;
331 crypto_free_pk_env(*key_out);
332 authority_cert_free(*cert_out);
334 *key_out = signing_key;
335 *cert_out = parsed;
336 r = 0;
337 signing_key = NULL;
338 parsed = NULL;
340 done:
341 tor_free(fname);
342 tor_free(cert);
343 crypto_free_pk_env(signing_key);
344 authority_cert_free(parsed);
345 return r;
348 /** Load the v3 (voting) authority signing key and certificate, if they are
349 * present. Return -1 if anything is missing, mismatched, or unloadable;
350 * return 0 on success. */
351 static int
352 init_v3_authority_keys(void)
354 if (load_authority_keyset(0, &authority_signing_key,
355 &authority_key_certificate)<0)
356 return -1;
358 if (get_options()->V3AuthUseLegacyKey &&
359 load_authority_keyset(1, &legacy_signing_key,
360 &legacy_key_certificate)<0)
361 return -1;
363 return 0;
366 /** If we're a v3 authority, check whether we have a certificate that's
367 * likely to expire soon. Warn if we do, but not too often. */
368 void
369 v3_authority_check_key_expiry(void)
371 time_t now, expires;
372 static time_t last_warned = 0;
373 int badness, time_left, warn_interval;
374 if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
375 return;
377 now = time(NULL);
378 expires = authority_key_certificate->expires;
379 time_left = (int)( expires - now );
380 if (time_left <= 0) {
381 badness = LOG_ERR;
382 warn_interval = 60*60;
383 } else if (time_left <= 24*60*60) {
384 badness = LOG_WARN;
385 warn_interval = 60*60;
386 } else if (time_left <= 24*60*60*7) {
387 badness = LOG_WARN;
388 warn_interval = 24*60*60;
389 } else if (time_left <= 24*60*60*30) {
390 badness = LOG_WARN;
391 warn_interval = 24*60*60*5;
392 } else {
393 return;
396 if (last_warned + warn_interval > now)
397 return;
399 if (time_left <= 0) {
400 log(badness, LD_DIR, "Your v3 authority certificate has expired."
401 " Generate a new one NOW.");
402 } else if (time_left <= 24*60*60) {
403 log(badness, LD_DIR, "Your v3 authority certificate expires in %d hours;"
404 " Generate a new one NOW.", time_left/(60*60));
405 } else {
406 log(badness, LD_DIR, "Your v3 authority certificate expires in %d days;"
407 " Generate a new one soon.", time_left/(24*60*60));
409 last_warned = now;
412 /** Initialize all OR private keys, and the TLS context, as necessary.
413 * On OPs, this only initializes the tls context. Return 0 on success,
414 * or -1 if Tor should die.
417 init_keys(void)
419 char *keydir;
420 char fingerprint[FINGERPRINT_LEN+1];
421 /*nickname<space>fp\n\0 */
422 char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
423 const char *mydesc;
424 crypto_pk_env_t *prkey;
425 char digest[20];
426 char v3_digest[20];
427 char *cp;
428 or_options_t *options = get_options();
429 authority_type_t type;
430 time_t now = time(NULL);
431 trusted_dir_server_t *ds;
432 int v3_digest_set = 0;
433 authority_cert_t *cert = NULL;
435 if (!key_lock)
436 key_lock = tor_mutex_new();
438 /* There are a couple of paths that put us here before */
439 if (crypto_global_init(get_options()->HardwareAccel,
440 get_options()->AccelName,
441 get_options()->AccelDir)) {
442 log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
443 return -1;
446 /* OP's don't need persistent keys; just make up an identity and
447 * initialize the TLS context. */
448 if (!server_mode(options)) {
449 if (!(prkey = crypto_new_pk_env()))
450 return -1;
451 if (crypto_pk_generate_key(prkey)) {
452 crypto_free_pk_env(prkey);
453 return -1;
455 set_identity_key(prkey);
456 /* Create a TLS context; default the client nickname to "client". */
457 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
458 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
459 return -1;
461 return 0;
463 /* Make sure DataDirectory exists, and is private. */
464 if (check_private_dir(options->DataDirectory, CPD_CREATE)) {
465 return -1;
467 /* Check the key directory. */
468 keydir = get_datadir_fname("keys");
469 if (check_private_dir(keydir, CPD_CREATE)) {
470 tor_free(keydir);
471 return -1;
473 tor_free(keydir);
475 /* 1a. Read v3 directory authority key/cert information. */
476 memset(v3_digest, 0, sizeof(v3_digest));
477 if (authdir_mode_v3(options)) {
478 if (init_v3_authority_keys()<0) {
479 log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
480 "were unable to load our v3 authority keys and certificate! "
481 "Use tor-gencert to generate them. Dying.");
482 return -1;
484 cert = get_my_v3_authority_cert();
485 if (cert) {
486 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
487 v3_digest);
488 v3_digest_set = 1;
492 /* 1. Read identity key. Make it if none is found. */
493 keydir = get_datadir_fname2("keys", "secret_id_key");
494 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
495 prkey = init_key_from_file(keydir, 1, LOG_ERR);
496 tor_free(keydir);
497 if (!prkey) return -1;
498 set_identity_key(prkey);
500 /* 2. Read onion key. Make it if none is found. */
501 keydir = get_datadir_fname2("keys", "secret_onion_key");
502 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
503 prkey = init_key_from_file(keydir, 1, LOG_ERR);
504 tor_free(keydir);
505 if (!prkey) return -1;
506 set_onion_key(prkey);
507 if (options->command == CMD_RUN_TOR) {
508 /* only mess with the state file if we're actually running Tor */
509 or_state_t *state = get_or_state();
510 if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
511 /* We allow for some parsing slop, but we don't want to risk accepting
512 * values in the distant future. If we did, we might never rotate the
513 * onion key. */
514 onionkey_set_at = state->LastRotatedOnionKey;
515 } else {
516 /* We have no LastRotatedOnionKey set; either we just created the key
517 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
518 * start the clock ticking now so that we will eventually rotate it even
519 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
520 state->LastRotatedOnionKey = onionkey_set_at = now;
521 or_state_mark_dirty(state, options->AvoidDiskWrites ?
522 time(NULL)+3600 : 0);
526 keydir = get_datadir_fname2("keys", "secret_onion_key.old");
527 if (!lastonionkey && file_status(keydir) == FN_FILE) {
528 prkey = init_key_from_file(keydir, 1, LOG_ERR);
529 if (prkey)
530 lastonionkey = prkey;
532 tor_free(keydir);
534 /* 3. Initialize link key and TLS context. */
535 if (tor_tls_context_new(get_identity_key(), MAX_SSL_KEY_LIFETIME) < 0) {
536 log_err(LD_GENERAL,"Error initializing TLS context");
537 return -1;
539 /* 4. Build our router descriptor. */
540 /* Must be called after keys are initialized. */
541 mydesc = router_get_my_descriptor();
542 if (authdir_mode(options)) {
543 const char *m = NULL;
544 routerinfo_t *ri;
545 /* We need to add our own fingerprint so it gets recognized. */
546 if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
547 log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
548 return -1;
550 if (mydesc) {
551 ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
552 if (!ri) {
553 log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
554 return -1;
556 if (!WRA_WAS_ADDED(dirserv_add_descriptor(ri, &m, "self"))) {
557 log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
558 m?m:"<unknown error>");
559 return -1;
564 /* 5. Dump fingerprint to 'fingerprint' */
565 keydir = get_datadir_fname("fingerprint");
566 log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
567 if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 0)<0) {
568 log_err(LD_GENERAL,"Error computing fingerprint");
569 tor_free(keydir);
570 return -1;
572 tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
573 if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
574 "%s %s\n",options->Nickname, fingerprint) < 0) {
575 log_err(LD_GENERAL,"Error writing fingerprint line");
576 tor_free(keydir);
577 return -1;
579 /* Check whether we need to write the fingerprint file. */
580 cp = NULL;
581 if (file_status(keydir) == FN_FILE)
582 cp = read_file_to_str(keydir, 0, NULL);
583 if (!cp || strcmp(cp, fingerprint_line)) {
584 if (write_str_to_file(keydir, fingerprint_line, 0)) {
585 log_err(LD_FS, "Error writing fingerprint line to file");
586 tor_free(keydir);
587 tor_free(cp);
588 return -1;
591 tor_free(cp);
592 tor_free(keydir);
594 log(LOG_NOTICE, LD_GENERAL,
595 "Your Tor server's identity key fingerprint is '%s %s'",
596 options->Nickname, fingerprint);
597 if (!authdir_mode(options))
598 return 0;
599 /* 6. [authdirserver only] load approved-routers file */
600 if (dirserv_load_fingerprint_file() < 0) {
601 log_err(LD_GENERAL,"Error loading fingerprints");
602 return -1;
604 /* 6b. [authdirserver only] add own key to approved directories. */
605 crypto_pk_get_digest(get_identity_key(), digest);
606 type = ((options->V1AuthoritativeDir ? V1_AUTHORITY : NO_AUTHORITY) |
607 (options->V2AuthoritativeDir ? V2_AUTHORITY : NO_AUTHORITY) |
608 (options->V3AuthoritativeDir ? V3_AUTHORITY : NO_AUTHORITY) |
609 (options->BridgeAuthoritativeDir ? BRIDGE_AUTHORITY : NO_AUTHORITY) |
610 (options->HSAuthoritativeDir ? HIDSERV_AUTHORITY : NO_AUTHORITY));
612 ds = router_get_trusteddirserver_by_digest(digest);
613 if (!ds) {
614 ds = add_trusted_dir_server(options->Nickname, NULL,
615 (uint16_t)options->DirPort,
616 (uint16_t)options->ORPort,
617 digest,
618 v3_digest,
619 type);
620 if (!ds) {
621 log_err(LD_GENERAL,"We want to be a directory authority, but we "
622 "couldn't add ourselves to the authority list. Failing.");
623 return -1;
626 if (ds->type != type) {
627 log_warn(LD_DIR, "Configured authority type does not match authority "
628 "type in DirServer list. Adjusting. (%d v %d)",
629 type, ds->type);
630 ds->type = type;
632 if (v3_digest_set && (ds->type & V3_AUTHORITY) &&
633 memcmp(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
634 log_warn(LD_DIR, "V3 identity key does not match identity declared in "
635 "DirServer line. Adjusting.");
636 memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
639 if (cert) { /* add my own cert to the list of known certs */
640 log_info(LD_DIR, "adding my own v3 cert");
641 if (trusted_dirs_load_certs_from_string(
642 cert->cache_info.signed_descriptor_body, 0, 0)<0) {
643 log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
644 return -1;
648 return 0; /* success */
651 /* Keep track of whether we should upload our server descriptor,
652 * and what type of server we are.
655 /** Whether we can reach our ORPort from the outside. */
656 static int can_reach_or_port = 0;
657 /** Whether we can reach our DirPort from the outside. */
658 static int can_reach_dir_port = 0;
660 /** Forget what we have learned about our reachability status. */
661 void
662 router_reset_reachability(void)
664 can_reach_or_port = can_reach_dir_port = 0;
667 /** Return 1 if ORPort is known reachable; else return 0. */
669 check_whether_orport_reachable(void)
671 or_options_t *options = get_options();
672 return options->AssumeReachable ||
673 can_reach_or_port;
676 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
678 check_whether_dirport_reachable(void)
680 or_options_t *options = get_options();
681 return !options->DirPort ||
682 options->AssumeReachable ||
683 we_are_hibernating() ||
684 can_reach_dir_port;
687 /** Look at a variety of factors, and return 0 if we don't want to
688 * advertise the fact that we have a DirPort open. Else return the
689 * DirPort we want to advertise.
691 * Log a helpful message if we change our mind about whether to publish
692 * a DirPort.
694 static int
695 decide_to_advertise_dirport(or_options_t *options, uint16_t dir_port)
697 static int advertising=1; /* start out assuming we will advertise */
698 int new_choice=1;
699 const char *reason = NULL;
701 /* Section one: reasons to publish or not publish that aren't
702 * worth mentioning to the user, either because they're obvious
703 * or because they're normal behavior. */
705 if (!dir_port) /* short circuit the rest of the function */
706 return 0;
707 if (authdir_mode(options)) /* always publish */
708 return dir_port;
709 if (we_are_hibernating())
710 return 0;
711 if (!check_whether_dirport_reachable())
712 return 0;
714 /* Section two: reasons to publish or not publish that the user
715 * might find surprising. These are generally config options that
716 * make us choose not to publish. */
718 if (accounting_is_enabled(options)) {
719 /* if we might potentially hibernate */
720 new_choice = 0;
721 reason = "AccountingMax enabled";
722 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
723 } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
724 (options->RelayBandwidthRate > 0 &&
725 options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
726 /* if we're advertising a small amount */
727 new_choice = 0;
728 reason = "BandwidthRate under 50KB";
731 if (advertising != new_choice) {
732 if (new_choice == 1) {
733 log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
734 } else {
735 tor_assert(reason);
736 log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
738 advertising = new_choice;
741 return advertising ? dir_port : 0;
744 /** Some time has passed, or we just got new directory information.
745 * See if we currently believe our ORPort or DirPort to be
746 * unreachable. If so, launch a new test for it.
748 * For ORPort, we simply try making a circuit that ends at ourselves.
749 * Success is noticed in onionskin_answer().
751 * For DirPort, we make a connection via Tor to our DirPort and ask
752 * for our own server descriptor.
753 * Success is noticed in connection_dir_client_reached_eof().
755 void
756 consider_testing_reachability(int test_or, int test_dir)
758 routerinfo_t *me = router_get_my_routerinfo();
759 int orport_reachable = check_whether_orport_reachable();
760 tor_addr_t addr;
761 if (!me)
762 return;
764 if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
765 log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
766 !orport_reachable ? "reachability" : "bandwidth",
767 me->address, me->or_port);
768 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me,
769 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
772 tor_addr_from_ipv4h(&addr, me->addr);
773 if (test_dir && !check_whether_dirport_reachable() &&
774 !connection_get_by_type_addr_port_purpose(
775 CONN_TYPE_DIR, &addr, me->dir_port,
776 DIR_PURPOSE_FETCH_SERVERDESC)) {
777 /* ask myself, via tor, for my server descriptor. */
778 directory_initiate_command(me->address, &addr,
779 me->or_port, me->dir_port,
780 0, /* does not matter */
781 0, me->cache_info.identity_digest,
782 DIR_PURPOSE_FETCH_SERVERDESC,
783 ROUTER_PURPOSE_GENERAL,
784 1, "authority.z", NULL, 0, 0);
788 /** Annotate that we found our ORPort reachable. */
789 void
790 router_orport_found_reachable(void)
792 if (!can_reach_or_port) {
793 routerinfo_t *me = router_get_my_routerinfo();
794 log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
795 "the outside. Excellent.%s",
796 get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
797 " Publishing server descriptor." : "");
798 can_reach_or_port = 1;
799 mark_my_descriptor_dirty();
800 if (!me) { /* should never happen */
801 log_warn(LD_BUG, "ORPort found reachable, but I have no routerinfo "
802 "yet. Failing to inform controller of success.");
803 return;
805 control_event_server_status(LOG_NOTICE,
806 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
807 me->address, me->or_port);
811 /** Annotate that we found our DirPort reachable. */
812 void
813 router_dirport_found_reachable(void)
815 if (!can_reach_dir_port) {
816 routerinfo_t *me = router_get_my_routerinfo();
817 log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
818 "from the outside. Excellent.");
819 can_reach_dir_port = 1;
820 if (!me || decide_to_advertise_dirport(get_options(), me->dir_port))
821 mark_my_descriptor_dirty();
822 if (!me) { /* should never happen */
823 log_warn(LD_BUG, "DirPort found reachable, but I have no routerinfo "
824 "yet. Failing to inform controller of success.");
825 return;
827 control_event_server_status(LOG_NOTICE,
828 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
829 me->address, me->dir_port);
833 /** We have enough testing circuits open. Send a bunch of "drop"
834 * cells down each of them, to exercise our bandwidth. */
835 void
836 router_perform_bandwidth_test(int num_circs, time_t now)
838 int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
839 int max_cells = num_cells < CIRCWINDOW_START ?
840 num_cells : CIRCWINDOW_START;
841 int cells_per_circuit = max_cells / num_circs;
842 origin_circuit_t *circ = NULL;
844 log_notice(LD_OR,"Performing bandwidth self-test...done.");
845 while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
846 CIRCUIT_PURPOSE_TESTING))) {
847 /* dump cells_per_circuit drop cells onto this circ */
848 int i = cells_per_circuit;
849 if (circ->_base.state != CIRCUIT_STATE_OPEN)
850 continue;
851 circ->_base.timestamp_dirty = now;
852 while (i-- > 0) {
853 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
854 RELAY_COMMAND_DROP,
855 NULL, 0, circ->cpath->prev)<0) {
856 return; /* stop if error */
862 /** Return true iff we believe ourselves to be an authoritative
863 * directory server.
866 authdir_mode(or_options_t *options)
868 return options->AuthoritativeDir != 0;
870 /** Return true iff we believe ourselves to be a v1 authoritative
871 * directory server.
874 authdir_mode_v1(or_options_t *options)
876 return authdir_mode(options) && options->V1AuthoritativeDir != 0;
878 /** Return true iff we believe ourselves to be a v2 authoritative
879 * directory server.
882 authdir_mode_v2(or_options_t *options)
884 return authdir_mode(options) && options->V2AuthoritativeDir != 0;
886 /** Return true iff we believe ourselves to be a v3 authoritative
887 * directory server.
890 authdir_mode_v3(or_options_t *options)
892 return authdir_mode(options) && options->V3AuthoritativeDir != 0;
894 /** Return true iff we are a v1, v2, or v3 directory authority. */
896 authdir_mode_any_main(or_options_t *options)
898 return options->V1AuthoritativeDir ||
899 options->V2AuthoritativeDir ||
900 options->V3AuthoritativeDir;
902 /** Return true if we believe ourselves to be any kind of
903 * authoritative directory beyond just a hidserv authority. */
905 authdir_mode_any_nonhidserv(or_options_t *options)
907 return options->BridgeAuthoritativeDir ||
908 authdir_mode_any_main(options);
910 /** Return true iff we are an authoritative directory server that is
911 * authoritative about receiving and serving descriptors of type
912 * <b>purpose</b> its dirport. Use -1 for "any purpose". */
914 authdir_mode_handles_descs(or_options_t *options, int purpose)
916 if (purpose < 0)
917 return authdir_mode_any_nonhidserv(options);
918 else if (purpose == ROUTER_PURPOSE_GENERAL)
919 return authdir_mode_any_main(options);
920 else if (purpose == ROUTER_PURPOSE_BRIDGE)
921 return (options->BridgeAuthoritativeDir);
922 else
923 return 0;
925 /** Return true iff we are an authoritative directory server that
926 * publishes its own network statuses.
929 authdir_mode_publishes_statuses(or_options_t *options)
931 if (authdir_mode_bridge(options))
932 return 0;
933 return authdir_mode_any_nonhidserv(options);
935 /** Return true iff we are an authoritative directory server that
936 * tests reachability of the descriptors it learns about.
939 authdir_mode_tests_reachability(or_options_t *options)
941 return authdir_mode_handles_descs(options, -1);
943 /** Return true iff we believe ourselves to be a bridge authoritative
944 * directory server.
947 authdir_mode_bridge(or_options_t *options)
949 return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
952 /** Return true iff we are trying to be a server.
955 server_mode(or_options_t *options)
957 if (options->ClientOnly) return 0;
958 return (options->ORPort != 0 || options->ORListenAddress);
961 /** Remember if we've advertised ourselves to the dirservers. */
962 static int server_is_advertised=0;
964 /** Return true iff we have published our descriptor lately.
967 advertised_server_mode(void)
969 return server_is_advertised;
973 * Called with a boolean: set whether we have recently published our
974 * descriptor.
976 static void
977 set_server_advertised(int s)
979 server_is_advertised = s;
982 /** Return true iff we are trying to be a socks proxy. */
984 proxy_mode(or_options_t *options)
986 return (options->SocksPort != 0 || options->SocksListenAddress ||
987 options->TransPort != 0 || options->TransListenAddress ||
988 options->NatdPort != 0 || options->NatdListenAddress ||
989 options->DNSPort != 0 || options->DNSListenAddress);
992 /** Decide if we're a publishable server. We are a publishable server if:
993 * - We don't have the ClientOnly option set
994 * and
995 * - We have the PublishServerDescriptor option set to non-empty
996 * and
997 * - We have ORPort set
998 * and
999 * - We believe we are reachable from the outside; or
1000 * - We are an authoritative directory server.
1002 static int
1003 decide_if_publishable_server(void)
1005 or_options_t *options = get_options();
1007 if (options->ClientOnly)
1008 return 0;
1009 if (options->_PublishServerDescriptor == NO_AUTHORITY)
1010 return 0;
1011 if (!server_mode(options))
1012 return 0;
1013 if (authdir_mode(options))
1014 return 1;
1016 return check_whether_orport_reachable();
1019 /** Initiate server descriptor upload as reasonable (if server is publishable,
1020 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1022 * We need to rebuild the descriptor if it's dirty even if we're not
1023 * uploading, because our reachability testing *uses* our descriptor to
1024 * determine what IP address and ports to test.
1026 void
1027 consider_publishable_server(int force)
1029 int rebuilt;
1031 if (!server_mode(get_options()))
1032 return;
1034 rebuilt = router_rebuild_descriptor(0);
1035 if (decide_if_publishable_server()) {
1036 set_server_advertised(1);
1037 if (rebuilt == 0)
1038 router_upload_dir_desc_to_dirservers(force);
1039 } else {
1040 set_server_advertised(0);
1045 * OR descriptor generation.
1048 /** My routerinfo. */
1049 static routerinfo_t *desc_routerinfo = NULL;
1050 /** My extrainfo */
1051 static extrainfo_t *desc_extrainfo = NULL;
1052 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1053 * now. */
1054 static time_t desc_clean_since = 0;
1055 /** Boolean: do we need to regenerate the above? */
1056 static int desc_needs_upload = 0;
1058 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1059 * descriptor successfully yet, try to upload our signed descriptor to
1060 * all the directory servers we know about.
1062 void
1063 router_upload_dir_desc_to_dirservers(int force)
1065 routerinfo_t *ri;
1066 extrainfo_t *ei;
1067 char *msg;
1068 size_t desc_len, extra_len = 0, total_len;
1069 authority_type_t auth = get_options()->_PublishServerDescriptor;
1071 ri = router_get_my_routerinfo();
1072 if (!ri) {
1073 log_info(LD_GENERAL, "No descriptor; skipping upload");
1074 return;
1076 ei = router_get_my_extrainfo();
1077 if (auth == NO_AUTHORITY)
1078 return;
1079 if (!force && !desc_needs_upload)
1080 return;
1081 desc_needs_upload = 0;
1083 desc_len = ri->cache_info.signed_descriptor_len;
1084 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1085 total_len = desc_len + extra_len + 1;
1086 msg = tor_malloc(total_len);
1087 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1088 if (ei) {
1089 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1091 msg[desc_len+extra_len] = 0;
1093 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
1094 (auth & BRIDGE_AUTHORITY) ?
1095 ROUTER_PURPOSE_BRIDGE :
1096 ROUTER_PURPOSE_GENERAL,
1097 auth, msg, desc_len, extra_len);
1098 tor_free(msg);
1101 /** OR only: Check whether my exit policy says to allow connection to
1102 * conn. Return 0 if we accept; non-0 if we reject.
1105 router_compare_to_my_exit_policy(edge_connection_t *conn)
1107 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1108 return -1;
1110 /* make sure it's resolved to something. this way we can't get a
1111 'maybe' below. */
1112 if (tor_addr_is_null(&conn->_base.addr))
1113 return -1;
1115 /* XXXX IPv6 */
1116 if (tor_addr_family(&conn->_base.addr) != AF_INET)
1117 return -1;
1119 return compare_tor_addr_to_addr_policy(&conn->_base.addr, conn->_base.port,
1120 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
1123 /** Return true iff I'm a server and <b>digest</b> is equal to
1124 * my identity digest. */
1126 router_digest_is_me(const char *digest)
1128 return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
1131 /** Return true iff I'm a server and <b>digest</b> is equal to
1132 * my identity digest. */
1134 router_extrainfo_digest_is_me(const char *digest)
1136 extrainfo_t *ei = router_get_my_extrainfo();
1137 if (!ei)
1138 return 0;
1140 return !memcmp(digest,
1141 ei->cache_info.signed_descriptor_digest,
1142 DIGEST_LEN);
1145 /** A wrapper around router_digest_is_me(). */
1147 router_is_me(routerinfo_t *router)
1149 return router_digest_is_me(router->cache_info.identity_digest);
1152 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1154 router_fingerprint_is_me(const char *fp)
1156 char digest[DIGEST_LEN];
1157 if (strlen(fp) == HEX_DIGEST_LEN &&
1158 base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
1159 return router_digest_is_me(digest);
1161 return 0;
1164 /** Return a routerinfo for this OR, rebuilding a fresh one if
1165 * necessary. Return NULL on error, or if called on an OP. */
1166 routerinfo_t *
1167 router_get_my_routerinfo(void)
1169 if (!server_mode(get_options()))
1170 return NULL;
1171 if (router_rebuild_descriptor(0))
1172 return NULL;
1173 return desc_routerinfo;
1176 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1177 * one if necessary. Return NULL on error.
1179 const char *
1180 router_get_my_descriptor(void)
1182 const char *body;
1183 if (!router_get_my_routerinfo())
1184 return NULL;
1185 /* Make sure this is nul-terminated. */
1186 tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
1187 body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
1188 tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
1189 log_debug(LD_GENERAL,"my desc is '%s'", body);
1190 return body;
1193 /** Return the extrainfo document for this OR, or NULL if we have none.
1194 * Rebuilt it (and the server descriptor) if necessary. */
1195 extrainfo_t *
1196 router_get_my_extrainfo(void)
1198 if (!server_mode(get_options()))
1199 return NULL;
1200 if (router_rebuild_descriptor(0))
1201 return NULL;
1202 return desc_extrainfo;
1205 /** A list of nicknames that we've warned about including in our family
1206 * declaration verbatim rather than as digests. */
1207 static smartlist_t *warned_nonexistent_family = NULL;
1209 static int router_guess_address_from_dir_headers(uint32_t *guess);
1211 /** Make a current best guess at our address, either because
1212 * it's configured in torrc, or because we've learned it from
1213 * dirserver headers. Place the answer in *<b>addr</b> and return
1214 * 0 on success, else return -1 if we have no guess. */
1216 router_pick_published_address(or_options_t *options, uint32_t *addr)
1218 if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
1219 log_info(LD_CONFIG, "Could not determine our address locally. "
1220 "Checking if directory headers provide any hints.");
1221 if (router_guess_address_from_dir_headers(addr) < 0) {
1222 log_info(LD_CONFIG, "No hints from directory headers either. "
1223 "Will try again later.");
1224 return -1;
1227 return 0;
1230 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1231 * routerinfo, signed server descriptor, and extra-info document for this OR.
1232 * Return 0 on success, -1 on temporary error.
1235 router_rebuild_descriptor(int force)
1237 routerinfo_t *ri;
1238 extrainfo_t *ei;
1239 uint32_t addr;
1240 char platform[256];
1241 int hibernating = we_are_hibernating();
1242 size_t ei_size;
1243 or_options_t *options = get_options();
1245 if (desc_clean_since && !force)
1246 return 0;
1248 if (router_pick_published_address(options, &addr) < 0) {
1249 /* Stop trying to rebuild our descriptor every second. We'll
1250 * learn that it's time to try again when server_has_changed_ip()
1251 * marks it dirty. */
1252 desc_clean_since = time(NULL);
1253 return -1;
1256 ri = tor_malloc_zero(sizeof(routerinfo_t));
1257 ri->cache_info.routerlist_index = -1;
1258 ri->address = tor_dup_ip(addr);
1259 ri->nickname = tor_strdup(options->Nickname);
1260 ri->addr = addr;
1261 ri->or_port = options->ORPort;
1262 ri->dir_port = options->DirPort;
1263 ri->cache_info.published_on = time(NULL);
1264 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
1265 * main thread */
1266 ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
1267 if (crypto_pk_get_digest(ri->identity_pkey,
1268 ri->cache_info.identity_digest)<0) {
1269 routerinfo_free(ri);
1270 return -1;
1272 get_platform_str(platform, sizeof(platform));
1273 ri->platform = tor_strdup(platform);
1275 /* compute ri->bandwidthrate as the min of various options */
1276 ri->bandwidthrate = get_effective_bwrate(options);
1278 /* and compute ri->bandwidthburst similarly */
1279 ri->bandwidthburst = get_effective_bwburst(options);
1281 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
1283 policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
1284 options->ExitPolicyRejectPrivate,
1285 ri->address, !options->BridgeRelay);
1287 if (desc_routerinfo) { /* inherit values */
1288 ri->is_valid = desc_routerinfo->is_valid;
1289 ri->is_running = desc_routerinfo->is_running;
1290 ri->is_named = desc_routerinfo->is_named;
1292 if (authdir_mode(options))
1293 ri->is_valid = ri->is_named = 1; /* believe in yourself */
1294 if (options->MyFamily) {
1295 smartlist_t *family;
1296 if (!warned_nonexistent_family)
1297 warned_nonexistent_family = smartlist_create();
1298 family = smartlist_create();
1299 ri->declared_family = smartlist_create();
1300 smartlist_split_string(family, options->MyFamily, ",",
1301 SPLIT_SKIP_SPACE|SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1302 SMARTLIST_FOREACH(family, char *, name,
1304 routerinfo_t *member;
1305 if (!strcasecmp(name, options->Nickname))
1306 member = ri;
1307 else
1308 member = router_get_by_nickname(name, 1);
1309 if (!member) {
1310 int is_legal = is_legal_nickname_or_hexdigest(name);
1311 if (!smartlist_string_isin(warned_nonexistent_family, name) &&
1312 !is_legal_hexdigest(name)) {
1313 if (is_legal)
1314 log_warn(LD_CONFIG,
1315 "I have no descriptor for the router named \"%s\" in my "
1316 "declared family; I'll use the nickname as is, but "
1317 "this may confuse clients.", name);
1318 else
1319 log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
1320 "declared family, but that isn't a legal nickname. "
1321 "Skipping it.", escaped(name));
1322 smartlist_add(warned_nonexistent_family, tor_strdup(name));
1324 if (is_legal) {
1325 smartlist_add(ri->declared_family, name);
1326 name = NULL;
1328 } else if (router_is_me(member)) {
1329 /* Don't list ourself in our own family; that's redundant */
1330 } else {
1331 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1332 fp[0] = '$';
1333 base16_encode(fp+1,HEX_DIGEST_LEN+1,
1334 member->cache_info.identity_digest, DIGEST_LEN);
1335 smartlist_add(ri->declared_family, fp);
1336 if (smartlist_string_isin(warned_nonexistent_family, name))
1337 smartlist_string_remove(warned_nonexistent_family, name);
1339 tor_free(name);
1342 /* remove duplicates from the list */
1343 smartlist_sort_strings(ri->declared_family);
1344 smartlist_uniq_strings(ri->declared_family);
1346 smartlist_free(family);
1349 /* Now generate the extrainfo. */
1350 ei = tor_malloc_zero(sizeof(extrainfo_t));
1351 ei->cache_info.is_extrainfo = 1;
1352 strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
1353 ei->cache_info.published_on = ri->cache_info.published_on;
1354 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
1355 DIGEST_LEN);
1356 ei_size = options->ExtraInfoStatistics ? MAX_EXTRAINFO_UPLOAD_SIZE : 8192;
1357 ei->cache_info.signed_descriptor_body = tor_malloc(ei_size);
1358 if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body,
1359 ei_size, ei, get_identity_key()) < 0) {
1360 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
1361 routerinfo_free(ri);
1362 extrainfo_free(ei);
1363 return -1;
1365 ei->cache_info.signed_descriptor_len =
1366 strlen(ei->cache_info.signed_descriptor_body);
1367 router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
1368 ei->cache_info.signed_descriptor_digest);
1370 /* Now finish the router descriptor. */
1371 memcpy(ri->cache_info.extra_info_digest,
1372 ei->cache_info.signed_descriptor_digest,
1373 DIGEST_LEN);
1374 ri->cache_info.signed_descriptor_body = tor_malloc(8192);
1375 if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
1376 ri, get_identity_key())<0) {
1377 log_warn(LD_BUG, "Couldn't generate router descriptor.");
1378 routerinfo_free(ri);
1379 extrainfo_free(ei);
1380 return -1;
1382 ri->cache_info.signed_descriptor_len =
1383 strlen(ri->cache_info.signed_descriptor_body);
1385 ri->purpose =
1386 options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
1387 ri->cache_info.send_unencrypted = 1;
1388 /* Let bridges serve their own descriptors unencrypted, so they can
1389 * pass reachability testing. (If they want to be harder to notice,
1390 * they can always leave the DirPort off). */
1391 if (!options->BridgeRelay)
1392 ei->cache_info.send_unencrypted = 1;
1394 router_get_router_hash(ri->cache_info.signed_descriptor_body,
1395 strlen(ri->cache_info.signed_descriptor_body),
1396 ri->cache_info.signed_descriptor_digest);
1398 routerinfo_set_country(ri);
1400 tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
1402 routerinfo_free(desc_routerinfo);
1403 desc_routerinfo = ri;
1404 extrainfo_free(desc_extrainfo);
1405 desc_extrainfo = ei;
1407 desc_clean_since = time(NULL);
1408 desc_needs_upload = 1;
1409 control_event_my_descriptor_changed();
1410 return 0;
1413 /** Mark descriptor out of date if it's older than <b>when</b> */
1414 void
1415 mark_my_descriptor_dirty_if_older_than(time_t when)
1417 if (desc_clean_since < when)
1418 mark_my_descriptor_dirty();
1421 /** Call when the current descriptor is out of date. */
1422 void
1423 mark_my_descriptor_dirty(void)
1425 desc_clean_since = 0;
1428 /** How frequently will we republish our descriptor because of large (factor
1429 * of 2) shifts in estimated bandwidth? */
1430 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
1432 /** Check whether bandwidth has changed a lot since the last time we announced
1433 * bandwidth. If so, mark our descriptor dirty. */
1434 void
1435 check_descriptor_bandwidth_changed(time_t now)
1437 static time_t last_changed = 0;
1438 uint64_t prev, cur;
1439 if (!desc_routerinfo)
1440 return;
1442 prev = desc_routerinfo->bandwidthcapacity;
1443 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
1444 if ((prev != cur && (!prev || !cur)) ||
1445 cur > prev*2 ||
1446 cur < prev/2) {
1447 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
1448 log_info(LD_GENERAL,
1449 "Measured bandwidth has changed; rebuilding descriptor.");
1450 mark_my_descriptor_dirty();
1451 last_changed = now;
1456 /** Note at log level severity that our best guess of address has changed from
1457 * <b>prev</b> to <b>cur</b>. */
1458 static void
1459 log_addr_has_changed(int severity, uint32_t prev, uint32_t cur,
1460 const char *source)
1462 char addrbuf_prev[INET_NTOA_BUF_LEN];
1463 char addrbuf_cur[INET_NTOA_BUF_LEN];
1464 struct in_addr in_prev;
1465 struct in_addr in_cur;
1467 in_prev.s_addr = htonl(prev);
1468 tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
1470 in_cur.s_addr = htonl(cur);
1471 tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
1473 if (prev)
1474 log_fn(severity, LD_GENERAL,
1475 "Our IP Address has changed from %s to %s; "
1476 "rebuilding descriptor (source: %s).",
1477 addrbuf_prev, addrbuf_cur, source);
1478 else
1479 log_notice(LD_GENERAL,
1480 "Guessed our IP address as %s (source: %s).",
1481 addrbuf_cur, source);
1484 /** Check whether our own address as defined by the Address configuration
1485 * has changed. This is for routers that get their address from a service
1486 * like dyndns. If our address has changed, mark our descriptor dirty. */
1487 void
1488 check_descriptor_ipaddress_changed(time_t now)
1490 uint32_t prev, cur;
1491 or_options_t *options = get_options();
1492 (void) now;
1494 if (!desc_routerinfo)
1495 return;
1497 prev = desc_routerinfo->addr;
1498 if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
1499 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
1500 return;
1503 if (prev != cur) {
1504 log_addr_has_changed(LOG_NOTICE, prev, cur, "resolve");
1505 ip_address_changed(0);
1509 /** The most recently guessed value of our IP address, based on directory
1510 * headers. */
1511 static uint32_t last_guessed_ip = 0;
1513 /** A directory server <b>d_conn</b> told us our IP address is
1514 * <b>suggestion</b>.
1515 * If this address is different from the one we think we are now, and
1516 * if our computer doesn't actually know its IP address, then switch. */
1517 void
1518 router_new_address_suggestion(const char *suggestion,
1519 const dir_connection_t *d_conn)
1521 uint32_t addr, cur = 0;
1522 struct in_addr in;
1523 or_options_t *options = get_options();
1525 /* first, learn what the IP address actually is */
1526 if (!tor_inet_aton(suggestion, &in)) {
1527 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
1528 escaped(suggestion));
1529 return;
1531 addr = ntohl(in.s_addr);
1533 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
1535 if (!server_mode(options)) {
1536 last_guessed_ip = addr; /* store it in case we need it later */
1537 return;
1540 if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
1541 /* We're all set -- we already know our address. Great. */
1542 last_guessed_ip = cur; /* store it in case we need it later */
1543 return;
1545 if (is_internal_IP(addr, 0)) {
1546 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1547 return;
1549 if (tor_addr_eq_ipv4h(&d_conn->_base.addr, addr)) {
1550 /* Don't believe anybody who says our IP is their IP. */
1551 log_debug(LD_DIR, "A directory server told us our IP address is %s, "
1552 "but he's just reporting his own IP address. Ignoring.",
1553 suggestion);
1554 return;
1557 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1558 * us an answer different from what we had the last time we managed to
1559 * resolve it. */
1560 if (last_guessed_ip != addr) {
1561 control_event_server_status(LOG_NOTICE,
1562 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1563 suggestion);
1564 log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr,
1565 d_conn->_base.address);
1566 ip_address_changed(0);
1567 last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
1571 /** We failed to resolve our address locally, but we'd like to build
1572 * a descriptor and publish / test reachability. If we have a guess
1573 * about our address based on directory headers, answer it and return
1574 * 0; else return -1. */
1575 static int
1576 router_guess_address_from_dir_headers(uint32_t *guess)
1578 if (last_guessed_ip) {
1579 *guess = last_guessed_ip;
1580 return 0;
1582 return -1;
1585 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1586 * string describing the version of Tor and the operating system we're
1587 * currently running on.
1589 void
1590 get_platform_str(char *platform, size_t len)
1592 tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
1595 /* XXX need to audit this thing and count fenceposts. maybe
1596 * refactor so we don't have to keep asking if we're
1597 * near the end of maxlen?
1599 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1601 /** OR only: Given a routerinfo for this router, and an identity key to sign
1602 * with, encode the routerinfo as a signed server descriptor and write the
1603 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1604 * failure, and the number of bytes used on success.
1607 router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
1608 crypto_pk_env_t *ident_key)
1610 char *onion_pkey; /* Onion key, PEM-encoded. */
1611 char *identity_pkey; /* Identity key, PEM-encoded. */
1612 char digest[DIGEST_LEN];
1613 char published[ISO_TIME_LEN+1];
1614 char fingerprint[FINGERPRINT_LEN+1];
1615 char extra_info_digest[HEX_DIGEST_LEN+1];
1616 size_t onion_pkeylen, identity_pkeylen;
1617 size_t written;
1618 int result=0;
1619 addr_policy_t *tmpe;
1620 char *family_line;
1621 or_options_t *options = get_options();
1623 /* Make sure the identity key matches the one in the routerinfo. */
1624 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
1625 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
1626 "match router's public key!");
1627 return -1;
1630 /* record our fingerprint, so we can include it in the descriptor */
1631 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
1632 log_err(LD_BUG,"Error computing fingerprint");
1633 return -1;
1636 /* PEM-encode the onion key */
1637 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
1638 &onion_pkey,&onion_pkeylen)<0) {
1639 log_warn(LD_BUG,"write onion_pkey to string failed!");
1640 return -1;
1643 /* PEM-encode the identity key */
1644 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
1645 &identity_pkey,&identity_pkeylen)<0) {
1646 log_warn(LD_BUG,"write identity_pkey to string failed!");
1647 tor_free(onion_pkey);
1648 return -1;
1651 /* Encode the publication time. */
1652 format_iso_time(published, router->cache_info.published_on);
1654 if (router->declared_family && smartlist_len(router->declared_family)) {
1655 size_t n;
1656 char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
1657 n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1658 family_line = tor_malloc(n);
1659 tor_snprintf(family_line, n, "family %s\n", family);
1660 tor_free(family);
1661 } else {
1662 family_line = tor_strdup("");
1665 base16_encode(extra_info_digest, sizeof(extra_info_digest),
1666 router->cache_info.extra_info_digest, DIGEST_LEN);
1668 /* Generate the easy portion of the router descriptor. */
1669 result = tor_snprintf(s, maxlen,
1670 "router %s %s %d 0 %d\n"
1671 "platform %s\n"
1672 "opt protocols Link 1 2 Circuit 1\n"
1673 "published %s\n"
1674 "opt fingerprint %s\n"
1675 "uptime %ld\n"
1676 "bandwidth %d %d %d\n"
1677 "opt extra-info-digest %s\n%s"
1678 "onion-key\n%s"
1679 "signing-key\n%s"
1680 "%s%s%s%s",
1681 router->nickname,
1682 router->address,
1683 router->or_port,
1684 decide_to_advertise_dirport(options, router->dir_port),
1685 router->platform,
1686 published,
1687 fingerprint,
1688 stats_n_seconds_working,
1689 (int) router->bandwidthrate,
1690 (int) router->bandwidthburst,
1691 (int) router->bandwidthcapacity,
1692 extra_info_digest,
1693 options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
1694 onion_pkey, identity_pkey,
1695 family_line,
1696 we_are_hibernating() ? "opt hibernating 1\n" : "",
1697 options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "",
1698 options->AllowSingleHopExits ? "opt allow-single-hop-exits\n" : "");
1700 tor_free(family_line);
1701 tor_free(onion_pkey);
1702 tor_free(identity_pkey);
1704 if (result < 0) {
1705 log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
1706 return -1;
1708 /* From now on, we use 'written' to remember the current length of 's'. */
1709 written = result;
1711 if (options->ContactInfo && strlen(options->ContactInfo)) {
1712 const char *ci = options->ContactInfo;
1713 if (strchr(ci, '\n') || strchr(ci, '\r'))
1714 ci = escaped(ci);
1715 result = tor_snprintf(s+written,maxlen-written, "contact %s\n", ci);
1716 if (result<0) {
1717 log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
1718 return -1;
1720 written += result;
1723 /* Write the exit policy to the end of 's'. */
1724 if (dns_seems_to_be_broken() || has_dns_init_failed() ||
1725 !router->exit_policy || !smartlist_len(router->exit_policy)) {
1726 /* DNS is screwed up; don't claim to be an exit. */
1727 strlcat(s+written, "reject *:*\n", maxlen-written);
1728 written += strlen("reject *:*\n");
1729 tmpe = NULL;
1730 } else if (router->exit_policy) {
1731 int i;
1732 for (i = 0; i < smartlist_len(router->exit_policy); ++i) {
1733 tmpe = smartlist_get(router->exit_policy, i);
1734 result = policy_write_item(s+written, maxlen-written, tmpe, 1);
1735 if (result < 0) {
1736 log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
1737 return -1;
1739 tor_assert(result == (int)strlen(s+written));
1740 written += result;
1741 if (written+2 > maxlen) {
1742 log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
1743 return -1;
1745 s[written++] = '\n';
1749 if (written+256 > maxlen) { /* Not enough room for signature. */
1750 log_warn(LD_BUG,"not enough room left in descriptor for signature!");
1751 return -1;
1754 /* Sign the descriptor */
1755 strlcpy(s+written, "router-signature\n", maxlen-written);
1756 written += strlen(s+written);
1757 s[written] = '\0';
1758 if (router_get_router_hash(s, strlen(s), digest) < 0) {
1759 return -1;
1762 note_crypto_pk_op(SIGN_RTR);
1763 if (router_append_dirobj_signature(s+written,maxlen-written,
1764 digest,DIGEST_LEN,ident_key)<0) {
1765 log_warn(LD_BUG, "Couldn't sign router descriptor");
1766 return -1;
1768 written += strlen(s+written);
1770 if (written+2 > maxlen) {
1771 log_warn(LD_BUG,"Not enough room to finish descriptor.");
1772 return -1;
1774 /* include a last '\n' */
1775 s[written] = '\n';
1776 s[written+1] = 0;
1778 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1780 char *s_dup;
1781 const char *cp;
1782 routerinfo_t *ri_tmp;
1783 cp = s_dup = tor_strdup(s);
1784 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
1785 if (!ri_tmp) {
1786 log_err(LD_BUG,
1787 "We just generated a router descriptor we can't parse.");
1788 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1789 return -1;
1791 tor_free(s_dup);
1792 routerinfo_free(ri_tmp);
1794 #endif
1796 return (int)written+1;
1799 /** Load the contents of <b>filename</b>, find the last line starting with
1800 * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
1801 * the past or more than 1 hour in the future with respect to <b>now</b>,
1802 * and write the file contents starting with that line to *<b>out</b>.
1803 * Return 1 for success, 0 if the file does not exist, or -1 if the file
1804 * does not contain a line matching these criteria or other failure. */
1805 static int
1806 load_stats_file(const char *filename, const char *end_line, time_t now,
1807 char **out)
1809 int r = -1;
1810 char *fname = get_datadir_fname(filename);
1811 char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
1812 time_t written;
1813 switch (file_status(fname)) {
1814 case FN_FILE:
1815 /* X022 Find an alternative to reading the whole file to memory. */
1816 if ((contents = read_file_to_str(fname, 0, NULL))) {
1817 tmp = strstr(contents, end_line);
1818 /* Find last block starting with end_line */
1819 while (tmp) {
1820 start = tmp;
1821 tmp = strstr(tmp + 1, end_line);
1823 if (!start)
1824 goto notfound;
1825 if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
1826 goto notfound;
1827 strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
1828 if (parse_iso_time(timestr, &written) < 0)
1829 goto notfound;
1830 if (written < now - (25*60*60) || written > now + (1*60*60))
1831 goto notfound;
1832 *out = tor_strdup(start);
1833 r = 1;
1835 notfound:
1836 tor_free(contents);
1837 break;
1838 case FN_NOENT:
1839 r = 0;
1840 break;
1841 case FN_ERROR:
1842 case FN_DIR:
1843 default:
1844 break;
1846 tor_free(fname);
1847 return r;
1850 /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
1851 * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
1852 * negative on failure. */
1854 extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
1855 crypto_pk_env_t *ident_key)
1857 or_options_t *options = get_options();
1858 char identity[HEX_DIGEST_LEN+1];
1859 char published[ISO_TIME_LEN+1];
1860 char digest[DIGEST_LEN];
1861 char *bandwidth_usage;
1862 int result;
1863 size_t len;
1864 static int write_stats_to_extrainfo = 1;
1865 time_t now = time(NULL);
1867 base16_encode(identity, sizeof(identity),
1868 extrainfo->cache_info.identity_digest, DIGEST_LEN);
1869 format_iso_time(published, extrainfo->cache_info.published_on);
1870 bandwidth_usage = rep_hist_get_bandwidth_lines(1);
1872 result = tor_snprintf(s, maxlen,
1873 "extra-info %s %s\n"
1874 "published %s\n%s",
1875 extrainfo->nickname, identity,
1876 published, bandwidth_usage);
1878 tor_free(bandwidth_usage);
1879 if (result<0)
1880 return -1;
1882 if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
1883 char *contents = NULL;
1884 log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
1885 if (options->DirReqStatistics &&
1886 load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
1887 "dirreq-stats-end", now, &contents) > 0) {
1888 size_t pos = strlen(s);
1889 if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
1890 strlen(contents)) {
1891 log_warn(LD_DIR, "Could not write dirreq-stats to extra-info "
1892 "descriptor.");
1893 s[pos] = '\0';
1894 write_stats_to_extrainfo = 0;
1896 tor_free(contents);
1898 if (options->EntryStatistics &&
1899 load_stats_file("stats"PATH_SEPARATOR"entry-stats",
1900 "entry-stats-end", now, &contents) > 0) {
1901 size_t pos = strlen(s);
1902 if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
1903 strlen(contents)) {
1904 log_warn(LD_DIR, "Could not write entry-stats to extra-info "
1905 "descriptor.");
1906 s[pos] = '\0';
1907 write_stats_to_extrainfo = 0;
1909 tor_free(contents);
1911 if (options->CellStatistics &&
1912 load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
1913 "cell-stats-end", now, &contents) > 0) {
1914 size_t pos = strlen(s);
1915 if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
1916 strlen(contents)) {
1917 log_warn(LD_DIR, "Could not write buffer-stats to extra-info "
1918 "descriptor.");
1919 s[pos] = '\0';
1920 write_stats_to_extrainfo = 0;
1922 tor_free(contents);
1924 if (options->ExitPortStatistics &&
1925 load_stats_file("stats"PATH_SEPARATOR"exit-stats",
1926 "exit-stats-end", now, &contents) > 0) {
1927 size_t pos = strlen(s);
1928 if (strlcpy(s + pos, contents, maxlen - strlen(s)) !=
1929 strlen(contents)) {
1930 log_warn(LD_DIR, "Could not write exit-stats to extra-info "
1931 "descriptor.");
1932 s[pos] = '\0';
1933 write_stats_to_extrainfo = 0;
1935 tor_free(contents);
1939 if (should_record_bridge_info(options) && write_stats_to_extrainfo) {
1940 const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
1941 if (bridge_stats) {
1942 size_t pos = strlen(s);
1943 if (strlcpy(s + pos, bridge_stats, maxlen - strlen(s)) !=
1944 strlen(bridge_stats)) {
1945 log_warn(LD_DIR, "Could not write bridge-stats to extra-info "
1946 "descriptor.");
1947 s[pos] = '\0';
1948 write_stats_to_extrainfo = 0;
1953 len = strlen(s);
1954 strlcat(s+len, "router-signature\n", maxlen-len);
1955 len += strlen(s+len);
1956 if (router_get_extrainfo_hash(s, digest)<0)
1957 return -1;
1958 if (router_append_dirobj_signature(s+len, maxlen-len, digest, DIGEST_LEN,
1959 ident_key)<0)
1960 return -1;
1963 char *cp, *s_dup;
1964 extrainfo_t *ei_tmp;
1965 cp = s_dup = tor_strdup(s);
1966 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
1967 if (!ei_tmp) {
1968 log_err(LD_BUG,
1969 "We just generated an extrainfo descriptor we can't parse.");
1970 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1971 tor_free(s_dup);
1972 return -1;
1974 tor_free(s_dup);
1975 extrainfo_free(ei_tmp);
1978 if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
1979 char *cp, *s_dup;
1980 extrainfo_t *ei_tmp;
1981 cp = s_dup = tor_strdup(s);
1982 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
1983 if (!ei_tmp) {
1984 log_warn(LD_GENERAL,
1985 "We just generated an extra-info descriptor with "
1986 "statistics that we can't parse. Not adding statistics to "
1987 "this or any future extra-info descriptors. Descriptor "
1988 "was:\n%s", s);
1989 write_stats_to_extrainfo = 0;
1990 extrainfo_dump_to_string(s, maxlen, extrainfo, ident_key);
1992 tor_free(s_dup);
1993 extrainfo_free(ei_tmp);
1996 return (int)strlen(s)+1;
1999 /** Return true iff <b>s</b> is a legally valid server nickname. */
2001 is_legal_nickname(const char *s)
2003 size_t len;
2004 tor_assert(s);
2005 len = strlen(s);
2006 return len > 0 && len <= MAX_NICKNAME_LEN &&
2007 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
2010 /** Return true iff <b>s</b> is a legally valid server nickname or
2011 * hex-encoded identity-key digest. */
2013 is_legal_nickname_or_hexdigest(const char *s)
2015 if (*s!='$')
2016 return is_legal_nickname(s);
2017 else
2018 return is_legal_hexdigest(s);
2021 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
2022 * digest. */
2024 is_legal_hexdigest(const char *s)
2026 size_t len;
2027 tor_assert(s);
2028 if (s[0] == '$') s++;
2029 len = strlen(s);
2030 if (len > HEX_DIGEST_LEN) {
2031 if (s[HEX_DIGEST_LEN] == '=' ||
2032 s[HEX_DIGEST_LEN] == '~') {
2033 if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
2034 return 0;
2035 } else {
2036 return 0;
2039 return (len >= HEX_DIGEST_LEN &&
2040 strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
2043 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
2044 * verbose representation of the identity of <b>router</b>. The format is:
2045 * A dollar sign.
2046 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
2047 * A "=" if the router is named; a "~" if it is not.
2048 * The router's nickname.
2050 void
2051 router_get_verbose_nickname(char *buf, const routerinfo_t *router)
2053 buf[0] = '$';
2054 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
2055 DIGEST_LEN);
2056 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
2057 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
2060 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
2061 * verbose representation of the identity of <b>router</b>. The format is:
2062 * A dollar sign.
2063 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
2064 * A "=" if the router is named; a "~" if it is not.
2065 * The router's nickname.
2067 void
2068 routerstatus_get_verbose_nickname(char *buf, const routerstatus_t *router)
2070 buf[0] = '$';
2071 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->identity_digest,
2072 DIGEST_LEN);
2073 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
2074 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
2077 /** Forget that we have issued any router-related warnings, so that we'll
2078 * warn again if we see the same errors. */
2079 void
2080 router_reset_warnings(void)
2082 if (warned_nonexistent_family) {
2083 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
2084 smartlist_clear(warned_nonexistent_family);
2088 /** Given a router purpose, convert it to a string. Don't call this on
2089 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
2090 * know its string representation. */
2091 const char *
2092 router_purpose_to_string(uint8_t p)
2094 switch (p)
2096 case ROUTER_PURPOSE_GENERAL: return "general";
2097 case ROUTER_PURPOSE_BRIDGE: return "bridge";
2098 case ROUTER_PURPOSE_CONTROLLER: return "controller";
2099 default:
2100 tor_assert(0);
2102 return NULL;
2105 /** Given a string, convert it to a router purpose. */
2106 uint8_t
2107 router_purpose_from_string(const char *s)
2109 if (!strcmp(s, "general"))
2110 return ROUTER_PURPOSE_GENERAL;
2111 else if (!strcmp(s, "bridge"))
2112 return ROUTER_PURPOSE_BRIDGE;
2113 else if (!strcmp(s, "controller"))
2114 return ROUTER_PURPOSE_CONTROLLER;
2115 else
2116 return ROUTER_PURPOSE_UNKNOWN;
2119 /** Release all static resources held in router.c */
2120 void
2121 router_free_all(void)
2123 crypto_free_pk_env(onionkey);
2124 crypto_free_pk_env(lastonionkey);
2125 crypto_free_pk_env(identitykey);
2126 tor_mutex_free(key_lock);
2127 routerinfo_free(desc_routerinfo);
2128 extrainfo_free(desc_extrainfo);
2129 crypto_free_pk_env(authority_signing_key);
2130 authority_cert_free(authority_key_certificate);
2131 crypto_free_pk_env(legacy_signing_key);
2132 authority_cert_free(legacy_key_certificate);
2134 if (warned_nonexistent_family) {
2135 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
2136 smartlist_free(warned_nonexistent_family);