Maintain separate server and client identity keys when appropriate.
[tor.git] / src / or / router.c
blobc53bb8b4e9c80499b500435003d843d62899fefa
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-2011, 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 server "identity key": used to sign directory info and TLS
35 * certificates. Never changes. */
36 static crypto_pk_env_t *server_identitykey=NULL;
37 /** Digest of server_identitykey. */
38 static char server_identitykey_digest[DIGEST_LEN];
39 /** Private client "identity key": used to sign bridges' and clients'
40 * outbound TLS certificates. Regenerated on startup and on IP address
41 * change. */
42 static crypto_pk_env_t *client_identitykey=NULL;
43 /** Signing key used for v3 directory material; only set for authorities. */
44 static crypto_pk_env_t *authority_signing_key = NULL;
45 /** Key certificate to authenticate v3 directory material; only set for
46 * authorities. */
47 static authority_cert_t *authority_key_certificate = NULL;
49 /** For emergency V3 authority key migration: An extra signing key that we use
50 * with our old (obsolete) identity key for a while. */
51 static crypto_pk_env_t *legacy_signing_key = NULL;
52 /** For emergency V3 authority key migration: An extra certificate to
53 * authenticate legacy_signing_key with our obsolete identity key.*/
54 static authority_cert_t *legacy_key_certificate = NULL;
56 /* (Note that v3 authorities also have a separate "authority identity key",
57 * but this key is never actually loaded by the Tor process. Instead, it's
58 * used by tor-gencert to sign new signing keys and make new key
59 * certificates. */
61 /** Replace the current onion key with <b>k</b>. Does not affect
62 * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
64 static void
65 set_onion_key(crypto_pk_env_t *k)
67 tor_mutex_acquire(key_lock);
68 if (onionkey)
69 crypto_free_pk_env(onionkey);
70 onionkey = k;
71 onionkey_set_at = time(NULL);
72 tor_mutex_release(key_lock);
73 mark_my_descriptor_dirty();
76 /** Return the current onion key. Requires that the onion key has been
77 * loaded or generated. */
78 crypto_pk_env_t *
79 get_onion_key(void)
81 tor_assert(onionkey);
82 return onionkey;
85 /** Store a full copy of the current onion key into *<b>key</b>, and a full
86 * copy of the most recent onion key into *<b>last</b>.
88 void
89 dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
91 tor_assert(key);
92 tor_assert(last);
93 tor_mutex_acquire(key_lock);
94 tor_assert(onionkey);
95 *key = crypto_pk_copy_full(onionkey);
96 if (lastonionkey)
97 *last = crypto_pk_copy_full(lastonionkey);
98 else
99 *last = NULL;
100 tor_mutex_release(key_lock);
103 /** Return the time when the onion key was last set. This is either the time
104 * when the process launched, or the time of the most recent key rotation since
105 * the process launched.
107 time_t
108 get_onion_key_set_at(void)
110 return onionkey_set_at;
113 /** Set the current server identity key to <b>k</b>.
115 void
116 set_server_identity_key(crypto_pk_env_t *k)
118 if (server_identitykey)
119 crypto_free_pk_env(server_identitykey);
120 server_identitykey = k;
121 crypto_pk_get_digest(server_identitykey, server_identitykey_digest);
124 /** Returns the current server identity key; requires that the key has
125 * been set.
127 crypto_pk_env_t *
128 get_server_identity_key(void)
130 tor_assert(server_identitykey);
131 return server_identitykey;
134 /** Return true iff the server identity key has been set. */
136 server_identity_key_is_set(void)
138 return server_identitykey != NULL;
141 /** Set the current client identity key to <b>k</b>.
143 void
144 set_client_identity_key(crypto_pk_env_t *k)
146 if (client_identitykey)
147 crypto_free_pk_env(client_identitykey);
148 client_identitykey = k;
151 /** Returns the current client identity key; requires that the key has
152 * been set.
154 crypto_pk_env_t *
155 get_client_identity_key(void)
157 tor_assert(client_identitykey);
158 return client_identitykey;
161 /** Return true iff the client identity key has been set. */
163 client_identity_key_is_set(void)
165 return client_identitykey != NULL;
168 /** Return the key certificate for this v3 (voting) authority, or NULL
169 * if we have no such certificate. */
170 authority_cert_t *
171 get_my_v3_authority_cert(void)
173 return authority_key_certificate;
176 /** Return the v3 signing key for this v3 (voting) authority, or NULL
177 * if we have no such key. */
178 crypto_pk_env_t *
179 get_my_v3_authority_signing_key(void)
181 return authority_signing_key;
184 /** If we're an authority, and we're using a legacy authority identity key for
185 * emergency migration purposes, return the certificate associated with that
186 * key. */
187 authority_cert_t *
188 get_my_v3_legacy_cert(void)
190 return legacy_key_certificate;
193 /** If we're an authority, and we're using a legacy authority identity key for
194 * emergency migration purposes, return that key. */
195 crypto_pk_env_t *
196 get_my_v3_legacy_signing_key(void)
198 return legacy_signing_key;
201 /** Replace the previous onion key with the current onion key, and generate
202 * a new previous onion key. Immediately after calling this function,
203 * the OR should:
204 * - schedule all previous cpuworkers to shut down _after_ processing
205 * pending work. (This will cause fresh cpuworkers to be generated.)
206 * - generate and upload a fresh routerinfo.
208 void
209 rotate_onion_key(void)
211 char *fname, *fname_prev;
212 crypto_pk_env_t *prkey;
213 or_state_t *state = get_or_state();
214 time_t now;
215 fname = get_datadir_fname2("keys", "secret_onion_key");
216 fname_prev = get_datadir_fname2("keys", "secret_onion_key.old");
217 if (!(prkey = crypto_new_pk_env())) {
218 log_err(LD_GENERAL,"Error constructing rotated onion key");
219 goto error;
221 if (crypto_pk_generate_key(prkey)) {
222 log_err(LD_BUG,"Error generating onion key");
223 goto error;
225 if (file_status(fname) == FN_FILE) {
226 if (replace_file(fname, fname_prev))
227 goto error;
229 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
230 log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
231 goto error;
233 log_info(LD_GENERAL, "Rotating onion key");
234 tor_mutex_acquire(key_lock);
235 if (lastonionkey)
236 crypto_free_pk_env(lastonionkey);
237 lastonionkey = onionkey;
238 onionkey = prkey;
239 now = time(NULL);
240 state->LastRotatedOnionKey = onionkey_set_at = now;
241 tor_mutex_release(key_lock);
242 mark_my_descriptor_dirty();
243 or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
244 goto done;
245 error:
246 log_warn(LD_GENERAL, "Couldn't rotate onion key.");
247 if (prkey)
248 crypto_free_pk_env(prkey);
249 done:
250 tor_free(fname);
251 tor_free(fname_prev);
254 /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist
255 * and <b>generate</b> is true, create a new RSA key and save it in
256 * <b>fname</b>. Return the read/created key, or NULL on error. Log all
257 * errors at level <b>severity</b>.
259 crypto_pk_env_t *
260 init_key_from_file(const char *fname, int generate, int severity)
262 crypto_pk_env_t *prkey = NULL;
264 if (!(prkey = crypto_new_pk_env())) {
265 log(severity, LD_GENERAL,"Error constructing key");
266 goto error;
269 switch (file_status(fname)) {
270 case FN_DIR:
271 case FN_ERROR:
272 log(severity, LD_FS,"Can't read key from \"%s\"", fname);
273 goto error;
274 case FN_NOENT:
275 if (generate) {
276 if (!have_lockfile()) {
277 if (try_locking(get_options(), 0)<0) {
278 /* Make sure that --list-fingerprint only creates new keys
279 * if there is no possibility for a deadlock. */
280 log(severity, LD_FS, "Another Tor process has locked \"%s\". Not "
281 "writing any new keys.", fname);
282 /*XXXX The 'other process' might make a key in a second or two;
283 * maybe we should wait for it. */
284 goto error;
287 log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
288 fname);
289 if (crypto_pk_generate_key(prkey)) {
290 log(severity, LD_GENERAL,"Error generating onion key");
291 goto error;
293 if (crypto_pk_check_key(prkey) <= 0) {
294 log(severity, LD_GENERAL,"Generated key seems invalid");
295 goto error;
297 log_info(LD_GENERAL, "Generated key seems valid");
298 if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
299 log(severity, LD_FS,
300 "Couldn't write generated key to \"%s\".", fname);
301 goto error;
303 } else {
304 log_info(LD_GENERAL, "No key found in \"%s\"", fname);
306 return prkey;
307 case FN_FILE:
308 if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
309 log(severity, LD_GENERAL,"Error loading private key.");
310 goto error;
312 return prkey;
313 default:
314 tor_assert(0);
317 error:
318 if (prkey)
319 crypto_free_pk_env(prkey);
320 return NULL;
323 /** Try to load the vote-signing private key and certificate for being a v3
324 * directory authority, and make sure they match. If <b>legacy</b>, load a
325 * legacy key/cert set for emergency key migration; otherwise load the regular
326 * key/cert set. On success, store them into *<b>key_out</b> and
327 * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
328 static int
329 load_authority_keyset(int legacy, crypto_pk_env_t **key_out,
330 authority_cert_t **cert_out)
332 int r = -1;
333 char *fname = NULL, *cert = NULL;
334 const char *eos = NULL;
335 crypto_pk_env_t *signing_key = NULL;
336 authority_cert_t *parsed = NULL;
338 fname = get_datadir_fname2("keys",
339 legacy ? "legacy_signing_key" : "authority_signing_key");
340 signing_key = init_key_from_file(fname, 0, LOG_INFO);
341 if (!signing_key) {
342 log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
343 goto done;
345 tor_free(fname);
346 fname = get_datadir_fname2("keys",
347 legacy ? "legacy_certificate" : "authority_certificate");
348 cert = read_file_to_str(fname, 0, NULL);
349 if (!cert) {
350 log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
351 fname);
352 goto done;
354 parsed = authority_cert_parse_from_string(cert, &eos);
355 if (!parsed) {
356 log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
357 goto done;
359 if (crypto_pk_cmp_keys(signing_key, parsed->signing_key) != 0) {
360 log_warn(LD_DIR, "Stored signing key does not match signing key in "
361 "certificate");
362 goto done;
365 if (*key_out)
366 crypto_free_pk_env(*key_out);
367 if (*cert_out)
368 authority_cert_free(*cert_out);
369 *key_out = signing_key;
370 *cert_out = parsed;
371 r = 0;
372 signing_key = NULL;
373 parsed = NULL;
375 done:
376 tor_free(fname);
377 tor_free(cert);
378 if (signing_key)
379 crypto_free_pk_env(signing_key);
380 if (parsed)
381 authority_cert_free(parsed);
382 return r;
385 /** Load the v3 (voting) authority signing key and certificate, if they are
386 * present. Return -1 if anything is missing, mismatched, or unloadable;
387 * return 0 on success. */
388 static int
389 init_v3_authority_keys(void)
391 if (load_authority_keyset(0, &authority_signing_key,
392 &authority_key_certificate)<0)
393 return -1;
395 if (get_options()->V3AuthUseLegacyKey &&
396 load_authority_keyset(1, &legacy_signing_key,
397 &legacy_key_certificate)<0)
398 return -1;
400 return 0;
403 /** If we're a v3 authority, check whether we have a certificate that's
404 * likely to expire soon. Warn if we do, but not too often. */
405 void
406 v3_authority_check_key_expiry(void)
408 time_t now, expires;
409 static time_t last_warned = 0;
410 int badness, time_left, warn_interval;
411 if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
412 return;
414 now = time(NULL);
415 expires = authority_key_certificate->expires;
416 time_left = (int)( expires - now );
417 if (time_left <= 0) {
418 badness = LOG_ERR;
419 warn_interval = 60*60;
420 } else if (time_left <= 24*60*60) {
421 badness = LOG_WARN;
422 warn_interval = 60*60;
423 } else if (time_left <= 24*60*60*7) {
424 badness = LOG_WARN;
425 warn_interval = 24*60*60;
426 } else if (time_left <= 24*60*60*30) {
427 badness = LOG_WARN;
428 warn_interval = 24*60*60*5;
429 } else {
430 return;
433 if (last_warned + warn_interval > now)
434 return;
436 if (time_left <= 0) {
437 log(badness, LD_DIR, "Your v3 authority certificate has expired."
438 " Generate a new one NOW.");
439 } else if (time_left <= 24*60*60) {
440 log(badness, LD_DIR, "Your v3 authority certificate expires in %d hours;"
441 " Generate a new one NOW.", time_left/(60*60));
442 } else {
443 log(badness, LD_DIR, "Your v3 authority certificate expires in %d days;"
444 " Generate a new one soon.", time_left/(24*60*60));
446 last_warned = now;
449 /** Initialize all OR private keys, and the TLS context, as necessary.
450 * On OPs, this only initializes the tls context. Return 0 on success,
451 * or -1 if Tor should die.
454 init_keys(void)
456 char *keydir;
457 char fingerprint[FINGERPRINT_LEN+1];
458 /*nickname<space>fp\n\0 */
459 char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
460 const char *mydesc;
461 crypto_pk_env_t *prkey;
462 char digest[20];
463 char v3_digest[20];
464 char *cp;
465 or_options_t *options = get_options();
466 authority_type_t type;
467 time_t now = time(NULL);
468 trusted_dir_server_t *ds;
469 int v3_digest_set = 0;
470 authority_cert_t *cert = NULL;
472 if (!key_lock)
473 key_lock = tor_mutex_new();
475 /* There are a couple of paths that put us here before */
476 if (crypto_global_init(get_options()->HardwareAccel)) {
477 log_err(LD_BUG, "Unable to initialize OpenSSL. Exiting.");
478 return -1;
481 /* OP's don't need persistent keys; just make up an identity and
482 * initialize the TLS context. */
483 if (!server_mode(options)) {
484 if (!(prkey = crypto_new_pk_env()))
485 return -1;
486 if (crypto_pk_generate_key(prkey)) {
487 crypto_free_pk_env(prkey);
488 return -1;
490 set_client_identity_key(prkey);
491 /* Create a TLS context. */
492 if (tor_tls_context_init(0,
493 get_client_identity_key(),
494 NULL,
495 MAX_SSL_KEY_LIFETIME_ADVERTISED) < 0) {
496 log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
497 return -1;
499 return 0;
501 /* Make sure DataDirectory exists, and is private. */
502 if (check_private_dir(options->DataDirectory, CPD_CREATE)) {
503 return -1;
505 /* Check the key directory. */
506 keydir = get_datadir_fname("keys");
507 if (check_private_dir(keydir, CPD_CREATE)) {
508 tor_free(keydir);
509 return -1;
511 tor_free(keydir);
513 /* 1a. Read v3 directory authority key/cert information. */
514 memset(v3_digest, 0, sizeof(v3_digest));
515 if (authdir_mode_v3(options)) {
516 if (init_v3_authority_keys()<0) {
517 log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
518 "were unable to load our v3 authority keys and certificate! "
519 "Use tor-gencert to generate them. Dying.");
520 return -1;
522 cert = get_my_v3_authority_cert();
523 if (cert) {
524 crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
525 v3_digest);
526 v3_digest_set = 1;
530 /* 1b. Read identity key. Make it if none is found. */
531 keydir = get_datadir_fname2("keys", "secret_id_key");
532 log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
533 prkey = init_key_from_file(keydir, 1, LOG_ERR);
534 tor_free(keydir);
535 if (!prkey) return -1;
536 set_server_identity_key(prkey);
538 /* 1c. If we are configured as a bridge, generate a client key;
539 * otherwise, set the server identity key as our client identity
540 * key. */
541 if (public_server_mode(options)) {
542 set_client_identity_key(prkey); /* set above */
543 } else {
544 if (!(prkey = crypto_new_pk_env()))
545 return -1;
546 if (crypto_pk_generate_key(prkey)) {
547 crypto_free_pk_env(prkey);
548 return -1;
550 set_client_identity_key(prkey);
553 /* 2. Read onion key. Make it if none is found. */
554 keydir = get_datadir_fname2("keys", "secret_onion_key");
555 log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
556 prkey = init_key_from_file(keydir, 1, LOG_ERR);
557 tor_free(keydir);
558 if (!prkey) return -1;
559 set_onion_key(prkey);
560 if (options->command == CMD_RUN_TOR) {
561 /* only mess with the state file if we're actually running Tor */
562 or_state_t *state = get_or_state();
563 if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
564 /* We allow for some parsing slop, but we don't want to risk accepting
565 * values in the distant future. If we did, we might never rotate the
566 * onion key. */
567 onionkey_set_at = state->LastRotatedOnionKey;
568 } else {
569 /* We have no LastRotatedOnionKey set; either we just created the key
570 * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
571 * start the clock ticking now so that we will eventually rotate it even
572 * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
573 state->LastRotatedOnionKey = onionkey_set_at = now;
574 or_state_mark_dirty(state, options->AvoidDiskWrites ?
575 time(NULL)+3600 : 0);
579 keydir = get_datadir_fname2("keys", "secret_onion_key.old");
580 if (!lastonionkey && file_status(keydir) == FN_FILE) {
581 prkey = init_key_from_file(keydir, 1, LOG_ERR);
582 if (prkey)
583 lastonionkey = prkey;
585 tor_free(keydir);
587 /* 3. Initialize link key and TLS context. */
588 if (tor_tls_context_init(public_server_mode(options),
589 get_client_identity_key(),
590 get_server_identity_key(),
591 MAX_SSL_KEY_LIFETIME_ADVERTISED) < 0) {
592 log_err(LD_GENERAL,"Error initializing TLS context");
593 return -1;
595 /* 4. Build our router descriptor. */
596 /* Must be called after keys are initialized. */
597 mydesc = router_get_my_descriptor();
598 if (authdir_mode(options)) {
599 const char *m = NULL;
600 routerinfo_t *ri;
601 /* We need to add our own fingerprint so it gets recognized. */
602 if (dirserv_add_own_fingerprint(options->Nickname,
603 get_server_identity_key())) {
604 log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
605 return -1;
607 if (mydesc) {
608 ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
609 if (!ri) {
610 log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
611 return -1;
613 if (!WRA_WAS_ADDED(dirserv_add_descriptor(ri, &m, "self"))) {
614 log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
615 m?m:"<unknown error>");
616 return -1;
621 /* 5. Dump fingerprint to 'fingerprint' */
622 keydir = get_datadir_fname("fingerprint");
623 log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
624 if (crypto_pk_get_fingerprint(get_server_identity_key(),
625 fingerprint, 0) < 0) {
626 log_err(LD_GENERAL,"Error computing fingerprint");
627 tor_free(keydir);
628 return -1;
630 tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
631 if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
632 "%s %s\n",options->Nickname, fingerprint) < 0) {
633 log_err(LD_GENERAL,"Error writing fingerprint line");
634 tor_free(keydir);
635 return -1;
637 /* Check whether we need to write the fingerprint file. */
638 cp = NULL;
639 if (file_status(keydir) == FN_FILE)
640 cp = read_file_to_str(keydir, 0, NULL);
641 if (!cp || strcmp(cp, fingerprint_line)) {
642 if (write_str_to_file(keydir, fingerprint_line, 0)) {
643 log_err(LD_FS, "Error writing fingerprint line to file");
644 tor_free(keydir);
645 tor_free(cp);
646 return -1;
649 tor_free(cp);
650 tor_free(keydir);
652 log(LOG_NOTICE, LD_GENERAL,
653 "Your Tor server's identity key fingerprint is '%s %s'",
654 options->Nickname, fingerprint);
655 if (!authdir_mode(options))
656 return 0;
657 /* 6. [authdirserver only] load approved-routers file */
658 if (dirserv_load_fingerprint_file() < 0) {
659 log_err(LD_GENERAL,"Error loading fingerprints");
660 return -1;
662 /* 6b. [authdirserver only] add own key to approved directories. */
663 crypto_pk_get_digest(get_server_identity_key(), digest);
664 type = ((options->V1AuthoritativeDir ? V1_AUTHORITY : NO_AUTHORITY) |
665 (options->V2AuthoritativeDir ? V2_AUTHORITY : NO_AUTHORITY) |
666 (options->V3AuthoritativeDir ? V3_AUTHORITY : NO_AUTHORITY) |
667 (options->BridgeAuthoritativeDir ? BRIDGE_AUTHORITY : NO_AUTHORITY) |
668 (options->HSAuthoritativeDir ? HIDSERV_AUTHORITY : NO_AUTHORITY));
670 ds = router_get_trusteddirserver_by_digest(digest);
671 if (!ds) {
672 ds = add_trusted_dir_server(options->Nickname, NULL,
673 (uint16_t)options->DirPort,
674 (uint16_t)options->ORPort,
675 digest,
676 v3_digest,
677 type);
678 if (!ds) {
679 log_err(LD_GENERAL,"We want to be a directory authority, but we "
680 "couldn't add ourselves to the authority list. Failing.");
681 return -1;
684 if (ds->type != type) {
685 log_warn(LD_DIR, "Configured authority type does not match authority "
686 "type in DirServer list. Adjusting. (%d v %d)",
687 type, ds->type);
688 ds->type = type;
690 if (v3_digest_set && (ds->type & V3_AUTHORITY) &&
691 tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
692 log_warn(LD_DIR, "V3 identity key does not match identity declared in "
693 "DirServer line. Adjusting.");
694 memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
697 if (cert) { /* add my own cert to the list of known certs */
698 log_info(LD_DIR, "adding my own v3 cert");
699 if (trusted_dirs_load_certs_from_string(
700 cert->cache_info.signed_descriptor_body, 0, 0)<0) {
701 log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
702 return -1;
706 return 0; /* success */
709 /* Keep track of whether we should upload our server descriptor,
710 * and what type of server we are.
713 /** Whether we can reach our ORPort from the outside. */
714 static int can_reach_or_port = 0;
715 /** Whether we can reach our DirPort from the outside. */
716 static int can_reach_dir_port = 0;
718 /** Forget what we have learned about our reachability status. */
719 void
720 router_reset_reachability(void)
722 can_reach_or_port = can_reach_dir_port = 0;
725 /** Return 1 if ORPort is known reachable; else return 0. */
727 check_whether_orport_reachable(void)
729 or_options_t *options = get_options();
730 return options->AssumeReachable ||
731 can_reach_or_port;
734 /** Return 1 if we don't have a dirport configured, or if it's reachable. */
736 check_whether_dirport_reachable(void)
738 or_options_t *options = get_options();
739 return !options->DirPort ||
740 options->AssumeReachable ||
741 we_are_hibernating() ||
742 can_reach_dir_port;
745 /** Look at a variety of factors, and return 0 if we don't want to
746 * advertise the fact that we have a DirPort open. Else return the
747 * DirPort we want to advertise.
749 * Log a helpful message if we change our mind about whether to publish
750 * a DirPort.
752 static int
753 decide_to_advertise_dirport(or_options_t *options, uint16_t dir_port)
755 static int advertising=1; /* start out assuming we will advertise */
756 int new_choice=1;
757 const char *reason = NULL;
759 /* Section one: reasons to publish or not publish that aren't
760 * worth mentioning to the user, either because they're obvious
761 * or because they're normal behavior. */
763 if (!dir_port) /* short circuit the rest of the function */
764 return 0;
765 if (authdir_mode(options)) /* always publish */
766 return dir_port;
767 if (we_are_hibernating())
768 return 0;
769 if (!check_whether_dirport_reachable())
770 return 0;
772 /* Section two: reasons to publish or not publish that the user
773 * might find surprising. These are generally config options that
774 * make us choose not to publish. */
776 if (accounting_is_enabled(options)) {
777 /* if we might potentially hibernate */
778 new_choice = 0;
779 reason = "AccountingMax enabled";
780 #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
781 } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
782 (options->RelayBandwidthRate > 0 &&
783 options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
784 /* if we're advertising a small amount */
785 new_choice = 0;
786 reason = "BandwidthRate under 50KB";
789 if (advertising != new_choice) {
790 if (new_choice == 1) {
791 log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
792 } else {
793 tor_assert(reason);
794 log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
796 advertising = new_choice;
799 return advertising ? dir_port : 0;
802 /** Some time has passed, or we just got new directory information.
803 * See if we currently believe our ORPort or DirPort to be
804 * unreachable. If so, launch a new test for it.
806 * For ORPort, we simply try making a circuit that ends at ourselves.
807 * Success is noticed in onionskin_answer().
809 * For DirPort, we make a connection via Tor to our DirPort and ask
810 * for our own server descriptor.
811 * Success is noticed in connection_dir_client_reached_eof().
813 void
814 consider_testing_reachability(int test_or, int test_dir)
816 routerinfo_t *me = router_get_my_routerinfo();
817 int orport_reachable = check_whether_orport_reachable();
818 tor_addr_t addr;
819 if (!me)
820 return;
822 if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
823 log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
824 !orport_reachable ? "reachability" : "bandwidth",
825 me->address, me->or_port);
826 circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me,
827 CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
830 tor_addr_from_ipv4h(&addr, me->addr);
831 if (test_dir && !check_whether_dirport_reachable() &&
832 !connection_get_by_type_addr_port_purpose(
833 CONN_TYPE_DIR, &addr, me->dir_port,
834 DIR_PURPOSE_FETCH_SERVERDESC)) {
835 /* ask myself, via tor, for my server descriptor. */
836 directory_initiate_command(me->address, &addr,
837 me->or_port, me->dir_port,
838 0, /* does not matter */
839 0, me->cache_info.identity_digest,
840 DIR_PURPOSE_FETCH_SERVERDESC,
841 ROUTER_PURPOSE_GENERAL,
842 1, "authority.z", NULL, 0, 0);
846 /** Annotate that we found our ORPort reachable. */
847 void
848 router_orport_found_reachable(void)
850 routerinfo_t *me = router_get_my_routerinfo();
851 if (!can_reach_or_port && me) {
852 log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
853 "the outside. Excellent.%s",
854 get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
855 " Publishing server descriptor." : "");
856 can_reach_or_port = 1;
857 mark_my_descriptor_dirty();
858 control_event_server_status(LOG_NOTICE,
859 "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
860 me->address, me->or_port);
864 /** Annotate that we found our DirPort reachable. */
865 void
866 router_dirport_found_reachable(void)
868 routerinfo_t *me = router_get_my_routerinfo();
869 if (!can_reach_dir_port && me) {
870 log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
871 "from the outside. Excellent.");
872 can_reach_dir_port = 1;
873 if (decide_to_advertise_dirport(get_options(), me->dir_port))
874 mark_my_descriptor_dirty();
875 control_event_server_status(LOG_NOTICE,
876 "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
877 me->address, me->dir_port);
881 /** We have enough testing circuits open. Send a bunch of "drop"
882 * cells down each of them, to exercise our bandwidth. */
883 void
884 router_perform_bandwidth_test(int num_circs, time_t now)
886 int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
887 int max_cells = num_cells < CIRCWINDOW_START ?
888 num_cells : CIRCWINDOW_START;
889 int cells_per_circuit = max_cells / num_circs;
890 origin_circuit_t *circ = NULL;
892 log_notice(LD_OR,"Performing bandwidth self-test...done.");
893 while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
894 CIRCUIT_PURPOSE_TESTING))) {
895 /* dump cells_per_circuit drop cells onto this circ */
896 int i = cells_per_circuit;
897 if (circ->_base.state != CIRCUIT_STATE_OPEN)
898 continue;
899 circ->_base.timestamp_dirty = now;
900 while (i-- > 0) {
901 if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
902 RELAY_COMMAND_DROP,
903 NULL, 0, circ->cpath->prev)<0) {
904 return; /* stop if error */
910 /** Return true iff we believe ourselves to be an authoritative
911 * directory server.
914 authdir_mode(or_options_t *options)
916 return options->AuthoritativeDir != 0;
918 /** Return true iff we believe ourselves to be a v1 authoritative
919 * directory server.
922 authdir_mode_v1(or_options_t *options)
924 return authdir_mode(options) && options->V1AuthoritativeDir != 0;
926 /** Return true iff we believe ourselves to be a v2 authoritative
927 * directory server.
930 authdir_mode_v2(or_options_t *options)
932 return authdir_mode(options) && options->V2AuthoritativeDir != 0;
934 /** Return true iff we believe ourselves to be a v3 authoritative
935 * directory server.
938 authdir_mode_v3(or_options_t *options)
940 return authdir_mode(options) && options->V3AuthoritativeDir != 0;
942 /** Return true iff we are a v1, v2, or v3 directory authority. */
944 authdir_mode_any_main(or_options_t *options)
946 return options->V1AuthoritativeDir ||
947 options->V2AuthoritativeDir ||
948 options->V3AuthoritativeDir;
950 /** Return true if we believe ourselves to be any kind of
951 * authoritative directory beyond just a hidserv authority. */
953 authdir_mode_any_nonhidserv(or_options_t *options)
955 return options->BridgeAuthoritativeDir ||
956 authdir_mode_any_main(options);
958 /** Return true iff we are an authoritative directory server that is
959 * authoritative about receiving and serving descriptors of type
960 * <b>purpose</b> its dirport. Use -1 for "any purpose". */
962 authdir_mode_handles_descs(or_options_t *options, int purpose)
964 if (purpose < 0)
965 return authdir_mode_any_nonhidserv(options);
966 else if (purpose == ROUTER_PURPOSE_GENERAL)
967 return authdir_mode_any_main(options);
968 else if (purpose == ROUTER_PURPOSE_BRIDGE)
969 return (options->BridgeAuthoritativeDir);
970 else
971 return 0;
973 /** Return true iff we are an authoritative directory server that
974 * publishes its own network statuses.
977 authdir_mode_publishes_statuses(or_options_t *options)
979 if (authdir_mode_bridge(options))
980 return 0;
981 return authdir_mode_any_nonhidserv(options);
983 /** Return true iff we are an authoritative directory server that
984 * tests reachability of the descriptors it learns about.
987 authdir_mode_tests_reachability(or_options_t *options)
989 return authdir_mode_handles_descs(options, -1);
991 /** Return true iff we believe ourselves to be a bridge authoritative
992 * directory server.
995 authdir_mode_bridge(or_options_t *options)
997 return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
1000 /** Return true iff we are trying to be a server.
1003 server_mode(or_options_t *options)
1005 if (options->ClientOnly) return 0;
1006 return (options->ORPort != 0 || options->ORListenAddress);
1009 /** Return true iff we are trying to be a non-bridge server.
1012 public_server_mode(or_options_t *options)
1014 if (!server_mode(options)) return 0;
1015 return (!options->BridgeRelay);
1018 /** Remember if we've advertised ourselves to the dirservers. */
1019 static int server_is_advertised=0;
1021 /** Return true iff we have published our descriptor lately.
1024 advertised_server_mode(void)
1026 return server_is_advertised;
1030 * Called with a boolean: set whether we have recently published our
1031 * descriptor.
1033 static void
1034 set_server_advertised(int s)
1036 server_is_advertised = s;
1039 /** Return true iff we are trying to be a socks proxy. */
1041 proxy_mode(or_options_t *options)
1043 return (options->SocksPort != 0 || options->SocksListenAddress ||
1044 options->TransPort != 0 || options->TransListenAddress ||
1045 options->NatdPort != 0 || options->NatdListenAddress ||
1046 options->DNSPort != 0 || options->DNSListenAddress);
1049 /** Decide if we're a publishable server. We are a publishable server if:
1050 * - We don't have the ClientOnly option set
1051 * and
1052 * - We have the PublishServerDescriptor option set to non-empty
1053 * and
1054 * - We have ORPort set
1055 * and
1056 * - We believe we are reachable from the outside; or
1057 * - We are an authoritative directory server.
1059 static int
1060 decide_if_publishable_server(void)
1062 or_options_t *options = get_options();
1064 if (options->ClientOnly)
1065 return 0;
1066 if (options->_PublishServerDescriptor == NO_AUTHORITY)
1067 return 0;
1068 if (!server_mode(options))
1069 return 0;
1070 if (authdir_mode(options))
1071 return 1;
1073 return check_whether_orport_reachable();
1076 /** Initiate server descriptor upload as reasonable (if server is publishable,
1077 * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1079 * We need to rebuild the descriptor if it's dirty even if we're not
1080 * uploading, because our reachability testing *uses* our descriptor to
1081 * determine what IP address and ports to test.
1083 void
1084 consider_publishable_server(int force)
1086 int rebuilt;
1088 if (!server_mode(get_options()))
1089 return;
1091 rebuilt = router_rebuild_descriptor(0);
1092 if (decide_if_publishable_server()) {
1093 set_server_advertised(1);
1094 if (rebuilt == 0)
1095 router_upload_dir_desc_to_dirservers(force);
1096 } else {
1097 set_server_advertised(0);
1102 * OR descriptor generation.
1105 /** My routerinfo. */
1106 static routerinfo_t *desc_routerinfo = NULL;
1107 /** My extrainfo */
1108 static extrainfo_t *desc_extrainfo = NULL;
1109 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1110 * now. */
1111 static time_t desc_clean_since = 0;
1112 /** Boolean: do we need to regenerate the above? */
1113 static int desc_needs_upload = 0;
1115 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1116 * descriptor successfully yet, try to upload our signed descriptor to
1117 * all the directory servers we know about.
1119 void
1120 router_upload_dir_desc_to_dirservers(int force)
1122 routerinfo_t *ri;
1123 extrainfo_t *ei;
1124 char *msg;
1125 size_t desc_len, extra_len = 0, total_len;
1126 authority_type_t auth = get_options()->_PublishServerDescriptor;
1128 ri = router_get_my_routerinfo();
1129 if (!ri) {
1130 log_info(LD_GENERAL, "No descriptor; skipping upload");
1131 return;
1133 ei = router_get_my_extrainfo();
1134 if (auth == NO_AUTHORITY)
1135 return;
1136 if (!force && !desc_needs_upload)
1137 return;
1138 desc_needs_upload = 0;
1140 desc_len = ri->cache_info.signed_descriptor_len;
1141 extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1142 total_len = desc_len + extra_len + 1;
1143 msg = tor_malloc(total_len);
1144 memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1145 if (ei) {
1146 memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1148 msg[desc_len+extra_len] = 0;
1150 directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
1151 (auth & BRIDGE_AUTHORITY) ?
1152 ROUTER_PURPOSE_BRIDGE :
1153 ROUTER_PURPOSE_GENERAL,
1154 auth, msg, desc_len, extra_len);
1155 tor_free(msg);
1158 /** OR only: Check whether my exit policy says to allow connection to
1159 * conn. Return 0 if we accept; non-0 if we reject.
1162 router_compare_to_my_exit_policy(edge_connection_t *conn)
1164 if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
1165 return -1;
1167 /* make sure it's resolved to something. this way we can't get a
1168 'maybe' below. */
1169 if (tor_addr_is_null(&conn->_base.addr))
1170 return -1;
1172 /* XXXX IPv6 */
1173 if (tor_addr_family(&conn->_base.addr) != AF_INET)
1174 return -1;
1176 return compare_tor_addr_to_addr_policy(&conn->_base.addr, conn->_base.port,
1177 desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
1180 /** Return true iff I'm a server and <b>digest</b> is equal to
1181 * my server identity key digest. */
1183 router_digest_is_me(const char *digest)
1185 return (server_identitykey &&
1186 tor_memeq(server_identitykey_digest, digest, DIGEST_LEN));
1189 /** Return true iff I'm a server and <b>digest</b> is equal to
1190 * my identity digest. */
1192 router_extrainfo_digest_is_me(const char *digest)
1194 extrainfo_t *ei = router_get_my_extrainfo();
1195 if (!ei)
1196 return 0;
1198 return tor_memeq(digest,
1199 ei->cache_info.signed_descriptor_digest,
1200 DIGEST_LEN);
1203 /** A wrapper around router_digest_is_me(). */
1205 router_is_me(routerinfo_t *router)
1207 return router_digest_is_me(router->cache_info.identity_digest);
1210 /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
1212 router_fingerprint_is_me(const char *fp)
1214 char digest[DIGEST_LEN];
1215 if (strlen(fp) == HEX_DIGEST_LEN &&
1216 base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
1217 return router_digest_is_me(digest);
1219 return 0;
1222 /** Return a routerinfo for this OR, rebuilding a fresh one if
1223 * necessary. Return NULL on error, or if called on an OP. */
1224 routerinfo_t *
1225 router_get_my_routerinfo(void)
1227 if (!server_mode(get_options()))
1228 return NULL;
1229 if (router_rebuild_descriptor(0))
1230 return NULL;
1231 return desc_routerinfo;
1234 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1235 * one if necessary. Return NULL on error.
1237 const char *
1238 router_get_my_descriptor(void)
1240 const char *body;
1241 if (!router_get_my_routerinfo())
1242 return NULL;
1243 /* Make sure this is nul-terminated. */
1244 tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
1245 body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
1246 tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
1247 log_debug(LD_GENERAL,"my desc is '%s'", body);
1248 return body;
1251 /** Return the extrainfo document for this OR, or NULL if we have none.
1252 * Rebuilt it (and the server descriptor) if necessary. */
1253 extrainfo_t *
1254 router_get_my_extrainfo(void)
1256 if (!server_mode(get_options()))
1257 return NULL;
1258 if (router_rebuild_descriptor(0))
1259 return NULL;
1260 return desc_extrainfo;
1263 /** A list of nicknames that we've warned about including in our family
1264 * declaration verbatim rather than as digests. */
1265 static smartlist_t *warned_nonexistent_family = NULL;
1267 static int router_guess_address_from_dir_headers(uint32_t *guess);
1269 /** Make a current best guess at our address, either because
1270 * it's configured in torrc, or because we've learned it from
1271 * dirserver headers. Place the answer in *<b>addr</b> and return
1272 * 0 on success, else return -1 if we have no guess. */
1274 router_pick_published_address(or_options_t *options, uint32_t *addr)
1276 if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
1277 log_info(LD_CONFIG, "Could not determine our address locally. "
1278 "Checking if directory headers provide any hints.");
1279 if (router_guess_address_from_dir_headers(addr) < 0) {
1280 log_info(LD_CONFIG, "No hints from directory headers either. "
1281 "Will try again later.");
1282 return -1;
1285 return 0;
1288 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
1289 * routerinfo, signed server descriptor, and extra-info document for this OR.
1290 * Return 0 on success, -1 on temporary error.
1293 router_rebuild_descriptor(int force)
1295 routerinfo_t *ri;
1296 extrainfo_t *ei;
1297 uint32_t addr;
1298 char platform[256];
1299 int hibernating = we_are_hibernating();
1300 or_options_t *options = get_options();
1302 if (desc_clean_since && !force)
1303 return 0;
1305 if (router_pick_published_address(options, &addr) < 0) {
1306 /* Stop trying to rebuild our descriptor every second. We'll
1307 * learn that it's time to try again when server_has_changed_ip()
1308 * marks it dirty. */
1309 desc_clean_since = time(NULL);
1310 return -1;
1313 ri = tor_malloc_zero(sizeof(routerinfo_t));
1314 ri->cache_info.routerlist_index = -1;
1315 ri->address = tor_dup_ip(addr);
1316 ri->nickname = tor_strdup(options->Nickname);
1317 ri->addr = addr;
1318 ri->or_port = options->ORPort;
1319 ri->dir_port = options->DirPort;
1320 ri->cache_info.published_on = time(NULL);
1321 ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
1322 * main thread */
1323 ri->identity_pkey = crypto_pk_dup_key(get_server_identity_key());
1324 if (crypto_pk_get_digest(ri->identity_pkey,
1325 ri->cache_info.identity_digest)<0) {
1326 routerinfo_free(ri);
1327 return -1;
1329 get_platform_str(platform, sizeof(platform));
1330 ri->platform = tor_strdup(platform);
1332 /* compute ri->bandwidthrate as the min of various options */
1333 ri->bandwidthrate = get_effective_bwrate(options);
1335 /* and compute ri->bandwidthburst similarly */
1336 ri->bandwidthburst = get_effective_bwburst(options);
1338 ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
1340 policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
1341 options->ExitPolicyRejectPrivate,
1342 ri->address);
1344 if (desc_routerinfo) { /* inherit values */
1345 ri->is_valid = desc_routerinfo->is_valid;
1346 ri->is_running = desc_routerinfo->is_running;
1347 ri->is_named = desc_routerinfo->is_named;
1349 if (authdir_mode(options))
1350 ri->is_valid = ri->is_named = 1; /* believe in yourself */
1351 if (options->MyFamily) {
1352 smartlist_t *family;
1353 if (!warned_nonexistent_family)
1354 warned_nonexistent_family = smartlist_create();
1355 family = smartlist_create();
1356 ri->declared_family = smartlist_create();
1357 smartlist_split_string(family, options->MyFamily, ",",
1358 SPLIT_SKIP_SPACE|SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1359 SMARTLIST_FOREACH(family, char *, name,
1361 routerinfo_t *member;
1362 if (!strcasecmp(name, options->Nickname))
1363 member = ri;
1364 else
1365 member = router_get_by_nickname(name, 1);
1366 if (!member) {
1367 int is_legal = is_legal_nickname_or_hexdigest(name);
1368 if (!smartlist_string_isin(warned_nonexistent_family, name) &&
1369 !is_legal_hexdigest(name)) {
1370 if (is_legal)
1371 log_warn(LD_CONFIG,
1372 "I have no descriptor for the router named \"%s\" in my "
1373 "declared family; I'll use the nickname as is, but "
1374 "this may confuse clients.", name);
1375 else
1376 log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
1377 "declared family, but that isn't a legal nickname. "
1378 "Skipping it.", escaped(name));
1379 smartlist_add(warned_nonexistent_family, tor_strdup(name));
1381 if (is_legal) {
1382 smartlist_add(ri->declared_family, name);
1383 name = NULL;
1385 } else if (router_is_me(member)) {
1386 /* Don't list ourself in our own family; that's redundant */
1387 } else {
1388 char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1389 fp[0] = '$';
1390 base16_encode(fp+1,HEX_DIGEST_LEN+1,
1391 member->cache_info.identity_digest, DIGEST_LEN);
1392 smartlist_add(ri->declared_family, fp);
1393 if (smartlist_string_isin(warned_nonexistent_family, name))
1394 smartlist_string_remove(warned_nonexistent_family, name);
1396 tor_free(name);
1399 /* remove duplicates from the list */
1400 smartlist_sort_strings(ri->declared_family);
1401 smartlist_uniq_strings(ri->declared_family);
1403 smartlist_free(family);
1406 /* Now generate the extrainfo. */
1407 ei = tor_malloc_zero(sizeof(extrainfo_t));
1408 ei->cache_info.is_extrainfo = 1;
1409 strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
1410 ei->cache_info.published_on = ri->cache_info.published_on;
1411 memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
1412 DIGEST_LEN);
1413 ei->cache_info.signed_descriptor_body = tor_malloc(8192);
1414 if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body, 8192,
1415 ei, get_server_identity_key()) < 0) {
1416 log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
1417 routerinfo_free(ri);
1418 extrainfo_free(ei);
1419 return -1;
1421 ei->cache_info.signed_descriptor_len =
1422 strlen(ei->cache_info.signed_descriptor_body);
1423 router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
1424 ei->cache_info.signed_descriptor_digest);
1426 /* Now finish the router descriptor. */
1427 memcpy(ri->cache_info.extra_info_digest,
1428 ei->cache_info.signed_descriptor_digest,
1429 DIGEST_LEN);
1430 ri->cache_info.signed_descriptor_body = tor_malloc(8192);
1431 if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
1432 ri, get_server_identity_key()) < 0) {
1433 log_warn(LD_BUG, "Couldn't generate router descriptor.");
1434 routerinfo_free(ri);
1435 extrainfo_free(ei);
1436 return -1;
1438 ri->cache_info.signed_descriptor_len =
1439 strlen(ri->cache_info.signed_descriptor_body);
1441 ri->purpose =
1442 options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
1443 ri->cache_info.send_unencrypted = 1;
1444 /* Let bridges serve their own descriptors unencrypted, so they can
1445 * pass reachability testing. (If they want to be harder to notice,
1446 * they can always leave the DirPort off). */
1447 if (!options->BridgeRelay)
1448 ei->cache_info.send_unencrypted = 1;
1450 router_get_router_hash(ri->cache_info.signed_descriptor_body,
1451 strlen(ri->cache_info.signed_descriptor_body),
1452 ri->cache_info.signed_descriptor_digest);
1454 routerinfo_set_country(ri);
1456 tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
1458 if (desc_routerinfo)
1459 routerinfo_free(desc_routerinfo);
1460 desc_routerinfo = ri;
1461 if (desc_extrainfo)
1462 extrainfo_free(desc_extrainfo);
1463 desc_extrainfo = ei;
1465 desc_clean_since = time(NULL);
1466 desc_needs_upload = 1;
1467 control_event_my_descriptor_changed();
1468 return 0;
1471 /** Mark descriptor out of date if it's older than <b>when</b> */
1472 void
1473 mark_my_descriptor_dirty_if_older_than(time_t when)
1475 if (desc_clean_since < when)
1476 mark_my_descriptor_dirty();
1479 /** Call when the current descriptor is out of date. */
1480 void
1481 mark_my_descriptor_dirty(void)
1483 desc_clean_since = 0;
1486 /** How frequently will we republish our descriptor because of large (factor
1487 * of 2) shifts in estimated bandwidth? */
1488 #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
1490 /** Check whether bandwidth has changed a lot since the last time we announced
1491 * bandwidth. If so, mark our descriptor dirty. */
1492 void
1493 check_descriptor_bandwidth_changed(time_t now)
1495 static time_t last_changed = 0;
1496 uint64_t prev, cur;
1497 if (!desc_routerinfo)
1498 return;
1500 prev = desc_routerinfo->bandwidthcapacity;
1501 cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
1502 if ((prev != cur && (!prev || !cur)) ||
1503 cur > prev*2 ||
1504 cur < prev/2) {
1505 if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
1506 log_info(LD_GENERAL,
1507 "Measured bandwidth has changed; rebuilding descriptor.");
1508 mark_my_descriptor_dirty();
1509 last_changed = now;
1514 /** Note at log level severity that our best guess of address has changed from
1515 * <b>prev</b> to <b>cur</b>. */
1516 static void
1517 log_addr_has_changed(int severity, uint32_t prev, uint32_t cur,
1518 const char *source)
1520 char addrbuf_prev[INET_NTOA_BUF_LEN];
1521 char addrbuf_cur[INET_NTOA_BUF_LEN];
1522 struct in_addr in_prev;
1523 struct in_addr in_cur;
1525 in_prev.s_addr = htonl(prev);
1526 tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
1528 in_cur.s_addr = htonl(cur);
1529 tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
1531 if (prev)
1532 log_fn(severity, LD_GENERAL,
1533 "Our IP Address has changed from %s to %s; "
1534 "rebuilding descriptor (source: %s).",
1535 addrbuf_prev, addrbuf_cur, source);
1536 else
1537 log_notice(LD_GENERAL,
1538 "Guessed our IP address as %s (source: %s).",
1539 addrbuf_cur, source);
1542 /** Check whether our own address as defined by the Address configuration
1543 * has changed. This is for routers that get their address from a service
1544 * like dyndns. If our address has changed, mark our descriptor dirty. */
1545 void
1546 check_descriptor_ipaddress_changed(time_t now)
1548 uint32_t prev, cur;
1549 or_options_t *options = get_options();
1550 (void) now;
1552 if (!desc_routerinfo)
1553 return;
1555 prev = desc_routerinfo->addr;
1556 if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
1557 log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
1558 return;
1561 if (prev != cur) {
1562 log_addr_has_changed(LOG_NOTICE, prev, cur, "resolve");
1563 ip_address_changed(0);
1567 /** The most recently guessed value of our IP address, based on directory
1568 * headers. */
1569 static uint32_t last_guessed_ip = 0;
1571 /** A directory server <b>d_conn</b> told us our IP address is
1572 * <b>suggestion</b>.
1573 * If this address is different from the one we think we are now, and
1574 * if our computer doesn't actually know its IP address, then switch. */
1575 void
1576 router_new_address_suggestion(const char *suggestion,
1577 const dir_connection_t *d_conn)
1579 uint32_t addr, cur = 0;
1580 struct in_addr in;
1581 or_options_t *options = get_options();
1583 /* first, learn what the IP address actually is */
1584 if (!tor_inet_aton(suggestion, &in)) {
1585 log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
1586 escaped(suggestion));
1587 return;
1589 addr = ntohl(in.s_addr);
1591 log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
1593 if (!server_mode(options)) {
1594 last_guessed_ip = addr; /* store it in case we need it later */
1595 return;
1598 if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
1599 /* We're all set -- we already know our address. Great. */
1600 last_guessed_ip = cur; /* store it in case we need it later */
1601 return;
1603 if (is_internal_IP(addr, 0)) {
1604 /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
1605 return;
1607 if (tor_addr_eq_ipv4h(&d_conn->_base.addr, addr)) {
1608 /* Don't believe anybody who says our IP is their IP. */
1609 log_debug(LD_DIR, "A directory server told us our IP address is %s, "
1610 "but he's just reporting his own IP address. Ignoring.",
1611 suggestion);
1612 return;
1615 /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
1616 * us an answer different from what we had the last time we managed to
1617 * resolve it. */
1618 if (last_guessed_ip != addr) {
1619 control_event_server_status(LOG_NOTICE,
1620 "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
1621 suggestion);
1622 log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr,
1623 d_conn->_base.address);
1624 ip_address_changed(0);
1625 last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
1629 /** We failed to resolve our address locally, but we'd like to build
1630 * a descriptor and publish / test reachability. If we have a guess
1631 * about our address based on directory headers, answer it and return
1632 * 0; else return -1. */
1633 static int
1634 router_guess_address_from_dir_headers(uint32_t *guess)
1636 if (last_guessed_ip) {
1637 *guess = last_guessed_ip;
1638 return 0;
1640 return -1;
1643 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
1644 * string describing the version of Tor and the operating system we're
1645 * currently running on.
1647 void
1648 get_platform_str(char *platform, size_t len)
1650 tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
1653 /* XXX need to audit this thing and count fenceposts. maybe
1654 * refactor so we don't have to keep asking if we're
1655 * near the end of maxlen?
1657 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1659 /** OR only: Given a routerinfo for this router, and an identity key to sign
1660 * with, encode the routerinfo as a signed server descriptor and write the
1661 * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
1662 * failure, and the number of bytes used on success.
1665 router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
1666 crypto_pk_env_t *ident_key)
1668 char *onion_pkey; /* Onion key, PEM-encoded. */
1669 char *identity_pkey; /* Identity key, PEM-encoded. */
1670 char digest[DIGEST_LEN];
1671 char published[ISO_TIME_LEN+1];
1672 char fingerprint[FINGERPRINT_LEN+1];
1673 char extra_info_digest[HEX_DIGEST_LEN+1];
1674 size_t onion_pkeylen, identity_pkeylen;
1675 size_t written;
1676 int result=0;
1677 addr_policy_t *tmpe;
1678 char *family_line;
1679 or_options_t *options = get_options();
1681 /* Make sure the identity key matches the one in the routerinfo. */
1682 if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
1683 log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
1684 "match router's public key!");
1685 return -1;
1688 /* record our fingerprint, so we can include it in the descriptor */
1689 if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
1690 log_err(LD_BUG,"Error computing fingerprint");
1691 return -1;
1694 /* PEM-encode the onion key */
1695 if (crypto_pk_write_public_key_to_string(router->onion_pkey,
1696 &onion_pkey,&onion_pkeylen)<0) {
1697 log_warn(LD_BUG,"write onion_pkey to string failed!");
1698 return -1;
1701 /* PEM-encode the identity key key */
1702 if (crypto_pk_write_public_key_to_string(router->identity_pkey,
1703 &identity_pkey,&identity_pkeylen)<0) {
1704 log_warn(LD_BUG,"write identity_pkey to string failed!");
1705 tor_free(onion_pkey);
1706 return -1;
1709 /* Encode the publication time. */
1710 format_iso_time(published, router->cache_info.published_on);
1712 if (router->declared_family && smartlist_len(router->declared_family)) {
1713 size_t n;
1714 char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
1715 n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
1716 family_line = tor_malloc(n);
1717 tor_snprintf(family_line, n, "family %s\n", family);
1718 tor_free(family);
1719 } else {
1720 family_line = tor_strdup("");
1723 base16_encode(extra_info_digest, sizeof(extra_info_digest),
1724 router->cache_info.extra_info_digest, DIGEST_LEN);
1726 /* Generate the easy portion of the router descriptor. */
1727 result = tor_snprintf(s, maxlen,
1728 "router %s %s %d 0 %d\n"
1729 "platform %s\n"
1730 "opt protocols Link 1 2 Circuit 1\n"
1731 "published %s\n"
1732 "opt fingerprint %s\n"
1733 "uptime %ld\n"
1734 "bandwidth %d %d %d\n"
1735 "opt extra-info-digest %s\n%s"
1736 "onion-key\n%s"
1737 "signing-key\n%s"
1738 "%s%s%s%s",
1739 router->nickname,
1740 router->address,
1741 router->or_port,
1742 decide_to_advertise_dirport(options, router->dir_port),
1743 router->platform,
1744 published,
1745 fingerprint,
1746 stats_n_seconds_working,
1747 (int) router->bandwidthrate,
1748 (int) router->bandwidthburst,
1749 (int) router->bandwidthcapacity,
1750 extra_info_digest,
1751 options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
1752 onion_pkey, identity_pkey,
1753 family_line,
1754 we_are_hibernating() ? "opt hibernating 1\n" : "",
1755 options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "",
1756 options->AllowSingleHopExits ? "opt allow-single-hop-exits\n" : "");
1758 tor_free(family_line);
1759 tor_free(onion_pkey);
1760 tor_free(identity_pkey);
1762 if (result < 0) {
1763 log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
1764 return -1;
1766 /* From now on, we use 'written' to remember the current length of 's'. */
1767 written = result;
1769 if (options->ContactInfo && strlen(options->ContactInfo)) {
1770 const char *ci = options->ContactInfo;
1771 if (strchr(ci, '\n') || strchr(ci, '\r'))
1772 ci = escaped(ci);
1773 result = tor_snprintf(s+written,maxlen-written, "contact %s\n", ci);
1774 if (result<0) {
1775 log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
1776 return -1;
1778 written += result;
1781 /* Write the exit policy to the end of 's'. */
1782 if (dns_seems_to_be_broken() || has_dns_init_failed() ||
1783 !router->exit_policy || !smartlist_len(router->exit_policy)) {
1784 /* DNS is screwed up; don't claim to be an exit. */
1785 strlcat(s+written, "reject *:*\n", maxlen-written);
1786 written += strlen("reject *:*\n");
1787 tmpe = NULL;
1788 } else if (router->exit_policy) {
1789 int i;
1790 for (i = 0; i < smartlist_len(router->exit_policy); ++i) {
1791 tmpe = smartlist_get(router->exit_policy, i);
1792 result = policy_write_item(s+written, maxlen-written, tmpe, 1);
1793 if (result < 0) {
1794 log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
1795 return -1;
1797 tor_assert(result == (int)strlen(s+written));
1798 written += result;
1799 if (written+2 > maxlen) {
1800 log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
1801 return -1;
1803 s[written++] = '\n';
1807 if (written+256 > maxlen) { /* Not enough room for signature. */
1808 log_warn(LD_BUG,"not enough room left in descriptor for signature!");
1809 return -1;
1812 /* Sign the descriptor */
1813 strlcpy(s+written, "router-signature\n", maxlen-written);
1814 written += strlen(s+written);
1815 s[written] = '\0';
1816 if (router_get_router_hash(s, strlen(s), digest) < 0) {
1817 return -1;
1820 note_crypto_pk_op(SIGN_RTR);
1821 if (router_append_dirobj_signature(s+written,maxlen-written,
1822 digest,ident_key)<0) {
1823 log_warn(LD_BUG, "Couldn't sign router descriptor");
1824 return -1;
1826 written += strlen(s+written);
1828 if (written+2 > maxlen) {
1829 log_warn(LD_BUG,"Not enough room to finish descriptor.");
1830 return -1;
1832 /* include a last '\n' */
1833 s[written] = '\n';
1834 s[written+1] = 0;
1836 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1838 char *s_dup;
1839 const char *cp;
1840 routerinfo_t *ri_tmp;
1841 cp = s_dup = tor_strdup(s);
1842 ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
1843 if (!ri_tmp) {
1844 log_err(LD_BUG,
1845 "We just generated a router descriptor we can't parse.");
1846 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1847 return -1;
1849 tor_free(s_dup);
1850 routerinfo_free(ri_tmp);
1852 #endif
1854 return (int)written+1;
1857 /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
1858 * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
1859 * negative on failure. */
1861 extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
1862 crypto_pk_env_t *ident_key)
1864 or_options_t *options = get_options();
1865 char identity[HEX_DIGEST_LEN+1];
1866 char published[ISO_TIME_LEN+1];
1867 char digest[DIGEST_LEN];
1868 char *bandwidth_usage;
1869 int result;
1870 size_t len;
1872 base16_encode(identity, sizeof(identity),
1873 extrainfo->cache_info.identity_digest, DIGEST_LEN);
1874 format_iso_time(published, extrainfo->cache_info.published_on);
1875 bandwidth_usage = rep_hist_get_bandwidth_lines(1);
1877 result = tor_snprintf(s, maxlen,
1878 "extra-info %s %s\n"
1879 "published %s\n%s",
1880 extrainfo->nickname, identity,
1881 published, bandwidth_usage);
1882 tor_free(bandwidth_usage);
1883 if (result<0)
1884 return -1;
1886 if (should_record_bridge_info(options)) {
1887 char *geoip_summary = extrainfo_get_client_geoip_summary(time(NULL));
1888 if (geoip_summary) {
1889 char geoip_start[ISO_TIME_LEN+1];
1890 format_iso_time(geoip_start, geoip_get_history_start());
1891 result = tor_snprintf(s+strlen(s), maxlen-strlen(s),
1892 "geoip-start-time %s\n"
1893 "geoip-client-origins %s\n",
1894 geoip_start, geoip_summary);
1895 control_event_clients_seen(geoip_start, geoip_summary);
1896 tor_free(geoip_summary);
1897 if (result<0)
1898 return -1;
1902 len = strlen(s);
1903 strlcat(s+len, "router-signature\n", maxlen-len);
1904 len += strlen(s+len);
1905 if (router_get_extrainfo_hash(s, digest)<0)
1906 return -1;
1907 if (router_append_dirobj_signature(s+len, maxlen-len, digest, ident_key)<0)
1908 return -1;
1910 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
1912 char *cp, *s_dup;
1913 extrainfo_t *ei_tmp;
1914 cp = s_dup = tor_strdup(s);
1915 ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
1916 if (!ei_tmp) {
1917 log_err(LD_BUG,
1918 "We just generated an extrainfo descriptor we can't parse.");
1919 log_err(LD_BUG, "Descriptor was: <<%s>>", s);
1920 tor_free(s_dup);
1921 return -1;
1923 tor_free(s_dup);
1924 extrainfo_free(ei_tmp);
1926 #endif
1928 return (int)strlen(s)+1;
1931 /** Wrapper function for geoip_get_client_history(). It first discards
1932 * any items in the client history that are too old -- it dumps anything
1933 * more than 48 hours old, but it only considers whether to dump at most
1934 * once per 48 hours, so we aren't too precise to an observer (see also
1935 * r14780).
1937 char *
1938 extrainfo_get_client_geoip_summary(time_t now)
1940 static time_t last_purged_at = 0;
1941 int geoip_purge_interval = 48*60*60;
1942 #ifdef ENABLE_GEOIP_STATS
1943 if (get_options()->DirRecordUsageByCountry)
1944 geoip_purge_interval = get_options()->DirRecordUsageRetainIPs;
1945 #endif
1946 if (now > last_purged_at+geoip_purge_interval) {
1947 geoip_remove_old_clients(now-geoip_purge_interval);
1948 last_purged_at = now;
1950 return geoip_get_client_history(now, GEOIP_CLIENT_CONNECT);
1953 /** Return true iff <b>s</b> is a legally valid server nickname. */
1955 is_legal_nickname(const char *s)
1957 size_t len;
1958 tor_assert(s);
1959 len = strlen(s);
1960 return len > 0 && len <= MAX_NICKNAME_LEN &&
1961 strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
1964 /** Return true iff <b>s</b> is a legally valid server nickname or
1965 * hex-encoded identity-key digest. */
1967 is_legal_nickname_or_hexdigest(const char *s)
1969 if (*s!='$')
1970 return is_legal_nickname(s);
1971 else
1972 return is_legal_hexdigest(s);
1975 /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
1976 * digest. */
1978 is_legal_hexdigest(const char *s)
1980 size_t len;
1981 tor_assert(s);
1982 if (s[0] == '$') s++;
1983 len = strlen(s);
1984 if (len > HEX_DIGEST_LEN) {
1985 if (s[HEX_DIGEST_LEN] == '=' ||
1986 s[HEX_DIGEST_LEN] == '~') {
1987 if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
1988 return 0;
1989 } else {
1990 return 0;
1993 return (len >= HEX_DIGEST_LEN &&
1994 strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
1997 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
1998 * verbose representation of the identity of <b>router</b>. The format is:
1999 * A dollar sign.
2000 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
2001 * A "=" if the router is named; a "~" if it is not.
2002 * The router's nickname.
2004 void
2005 router_get_verbose_nickname(char *buf, const routerinfo_t *router)
2007 buf[0] = '$';
2008 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
2009 DIGEST_LEN);
2010 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
2011 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
2014 /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
2015 * verbose representation of the identity of <b>router</b>. The format is:
2016 * A dollar sign.
2017 * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
2018 * A "=" if the router is named; a "~" if it is not.
2019 * The router's nickname.
2021 void
2022 routerstatus_get_verbose_nickname(char *buf, const routerstatus_t *router)
2024 buf[0] = '$';
2025 base16_encode(buf+1, HEX_DIGEST_LEN+1, router->identity_digest,
2026 DIGEST_LEN);
2027 buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
2028 strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
2031 /** Forget that we have issued any router-related warnings, so that we'll
2032 * warn again if we see the same errors. */
2033 void
2034 router_reset_warnings(void)
2036 if (warned_nonexistent_family) {
2037 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
2038 smartlist_clear(warned_nonexistent_family);
2042 /** Given a router purpose, convert it to a string. Don't call this on
2043 * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
2044 * know its string representation. */
2045 const char *
2046 router_purpose_to_string(uint8_t p)
2048 switch (p)
2050 case ROUTER_PURPOSE_GENERAL: return "general";
2051 case ROUTER_PURPOSE_BRIDGE: return "bridge";
2052 case ROUTER_PURPOSE_CONTROLLER: return "controller";
2053 default:
2054 tor_assert(0);
2056 return NULL;
2059 /** Given a string, convert it to a router purpose. */
2060 uint8_t
2061 router_purpose_from_string(const char *s)
2063 if (!strcmp(s, "general"))
2064 return ROUTER_PURPOSE_GENERAL;
2065 else if (!strcmp(s, "bridge"))
2066 return ROUTER_PURPOSE_BRIDGE;
2067 else if (!strcmp(s, "controller"))
2068 return ROUTER_PURPOSE_CONTROLLER;
2069 else
2070 return ROUTER_PURPOSE_UNKNOWN;
2073 /** Release all static resources held in router.c */
2074 void
2075 router_free_all(void)
2077 if (onionkey)
2078 crypto_free_pk_env(onionkey);
2079 if (lastonionkey)
2080 crypto_free_pk_env(lastonionkey);
2081 if (server_identitykey)
2082 crypto_free_pk_env(server_identitykey);
2083 if (client_identitykey)
2084 crypto_free_pk_env(client_identitykey);
2085 if (key_lock)
2086 tor_mutex_free(key_lock);
2087 if (desc_routerinfo)
2088 routerinfo_free(desc_routerinfo);
2089 if (desc_extrainfo)
2090 extrainfo_free(desc_extrainfo);
2091 if (authority_signing_key)
2092 crypto_free_pk_env(authority_signing_key);
2093 if (authority_key_certificate)
2094 authority_cert_free(authority_key_certificate);
2095 if (legacy_signing_key)
2096 crypto_free_pk_env(legacy_signing_key);
2097 if (legacy_key_certificate)
2098 authority_cert_free(legacy_key_certificate);
2100 if (warned_nonexistent_family) {
2101 SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
2102 smartlist_free(warned_nonexistent_family);