Tor  0.4.6.0-alpha-dev
router.c
Go to the documentation of this file.
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-2020, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 
7 #define ROUTER_PRIVATE
8 
9 #include "core/or/or.h"
10 #include "app/config/config.h"
12 #include "app/config/statefile.h"
13 #include "app/main/main.h"
15 #include "core/mainloop/mainloop.h"
17 #include "core/or/policies.h"
18 #include "core/or/protover.h"
29 #include "feature/keymgt/loadkey.h"
38 #include "feature/relay/dns.h"
42 #include "feature/relay/router.h"
45 #include "feature/relay/selftest.h"
46 #include "lib/geoip/geoip.h"
48 #include "feature/stats/bwhist.h"
49 #include "feature/stats/rephist.h"
55 #include "lib/encoding/confline.h"
56 #include "lib/osinfo/uname.h"
57 #include "lib/tls/tortls.h"
58 #include "lib/version/torversion.h"
59 
61 
62 #include "app/config/or_state_st.h"
63 #include "core/or/port_cfg_st.h"
72 
73 /**
74  * \file router.c
75  * \brief Miscellaneous relay functionality, including RSA key maintenance,
76  * generating and uploading server descriptors, picking an address to
77  * advertise, and so on.
78  *
79  * This module handles the job of deciding whether we are a Tor relay, and if
80  * so what kind. (Mostly through functions like server_mode() that inspect an
81  * or_options_t, but in some cases based on our own capabilities, such as when
82  * we are deciding whether to be a directory cache in
83  * router_has_bandwidth_to_be_dirserver().)
84  *
85  * Also in this module are the functions to generate our own routerinfo_t and
86  * extrainfo_t, and to encode those to signed strings for upload to the
87  * directory authorities.
88  *
89  * This module also handles key maintenance for RSA and Curve25519-ntor keys,
90  * and for our TLS context. (These functions should eventually move to
91  * routerkeys.c along with the code that handles Ed25519 keys now.)
92  **/
93 
94 /************************************************************/
95 
96 /*****
97  * Key management: ORs only.
98  *****/
99 
100 /** Private keys for this OR. There is also an SSL key managed by tortls.c.
101  */
102 static tor_mutex_t *key_lock=NULL;
103 static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
104 /** Current private onionskin decryption key: used to decode CREATE cells. */
105 static crypto_pk_t *onionkey=NULL;
106 /** Previous private onionskin decryption key: used to decode CREATE cells
107  * generated by clients that have an older version of our descriptor. */
109 /** Current private ntor secret key: used to perform the ntor handshake. */
111 /** Previous private ntor secret key: used to perform the ntor handshake
112  * with clients that have an older version of our descriptor. */
114 /** Private server "identity key": used to sign directory info and TLS
115  * certificates. Never changes. */
117 /** Digest of server_identitykey. */
119 /** Private client "identity key": used to sign bridges' and clients'
120  * outbound TLS certificates. Regenerated on startup and on IP address
121  * change. */
123 /** Signing key used for v3 directory material; only set for authorities. */
125 /** Key certificate to authenticate v3 directory material; only set for
126  * authorities. */
128 
129 /** For emergency V3 authority key migration: An extra signing key that we use
130  * with our old (obsolete) identity key for a while. */
132 /** For emergency V3 authority key migration: An extra certificate to
133  * authenticate legacy_signing_key with our obsolete identity key.*/
135 
136 /* (Note that v3 authorities also have a separate "authority identity key",
137  * but this key is never actually loaded by the Tor process. Instead, it's
138  * used by tor-gencert to sign new signing keys and make new key
139  * certificates. */
140 
141 /** Return a readonly string with human readable description
142  * of <b>err</b>.
143  */
144 const char *
146 {
147  switch (err) {
148  case TOR_ROUTERINFO_ERROR_NO_EXT_ADDR:
149  return "No known exit address yet";
150  case TOR_ROUTERINFO_ERROR_CANNOT_PARSE:
151  return "Cannot parse descriptor";
152  case TOR_ROUTERINFO_ERROR_NOT_A_SERVER:
153  return "Not running in server mode";
154  case TOR_ROUTERINFO_ERROR_DIGEST_FAILED:
155  return "Key digest failed";
156  case TOR_ROUTERINFO_ERROR_CANNOT_GENERATE:
157  return "Cannot generate descriptor";
158  case TOR_ROUTERINFO_ERROR_DESC_REBUILDING:
159  return "Descriptor still rebuilding - not ready yet";
160  case TOR_ROUTERINFO_ERROR_INTERNAL_BUG:
161  return "Internal bug, see logs for details";
162  }
163 
164  log_warn(LD_BUG, "unknown routerinfo error %d - shouldn't happen", err);
165  tor_assert_unreached();
166 
167  return "Unknown error";
168 }
169 
170 /** Return true if we expect given error to be transient.
171  * Return false otherwise.
172  */
173 int
175 {
176  /**
177  * For simplicity, we consider all errors other than
178  * "not a server" transient - see discussion on
179  * https://bugs.torproject.org/tpo/core/tor/27034.
180  */
181  return err != TOR_ROUTERINFO_ERROR_NOT_A_SERVER;
182 }
183 
184 /** Replace the current onion key with <b>k</b>. Does not affect
185  * lastonionkey; to update lastonionkey correctly, call rotate_onion_key().
186  */
187 static void
189 {
190  if (onionkey && crypto_pk_eq_keys(onionkey, k)) {
191  /* k is already our onion key; free it and return */
192  crypto_pk_free(k);
193  return;
194  }
196  crypto_pk_free(onionkey);
197  onionkey = k;
199  mark_my_descriptor_dirty("set onion key");
200 }
201 
202 /** Return the current onion key. Requires that the onion key has been
203  * loaded or generated. */
206 {
208  return onionkey;
209 }
210 
211 /** Store a full copy of the current onion key into *<b>key</b>, and a full
212  * copy of the most recent onion key into *<b>last</b>. Store NULL into
213  * a pointer if the corresponding key does not exist.
214  */
215 void
217 {
218  tor_assert(key);
219  tor_assert(last);
221  if (onionkey)
223  else
224  *key = NULL;
225  if (lastonionkey)
227  else
228  *last = NULL;
230 }
231 
232 /** Expire our old set of onion keys. This is done by setting
233  * last_curve25519_onion_key and lastonionkey to all zero's and NULL
234  * respectively.
235  *
236  * This function does not perform any grace period checks for the old onion
237  * keys.
238  */
239 void
241 {
242  char *fname = NULL;
243 
245 
246  /* Free lastonionkey and set it to NULL. */
247  if (lastonionkey) {
248  crypto_pk_free(lastonionkey);
249  lastonionkey = NULL;
250  }
251 
252  /* We zero out the keypair. See the fast_mem_is_zero() check made in
253  * construct_ntor_key_map() below. */
255 
257 
258  fname = get_keydir_fname("secret_onion_key.old");
259  if (file_status(fname) == FN_FILE) {
260  if (tor_unlink(fname) != 0) {
261  log_warn(LD_FS, "Couldn't unlink old onion key file %s: %s",
262  fname, strerror(errno));
263  }
264  }
265  tor_free(fname);
266 
267  fname = get_keydir_fname("secret_onion_key_ntor.old");
268  if (file_status(fname) == FN_FILE) {
269  if (tor_unlink(fname) != 0) {
270  log_warn(LD_FS, "Couldn't unlink old ntor onion key file %s: %s",
271  fname, strerror(errno));
272  }
273  }
274  tor_free(fname);
275 }
276 
277 /** Return the current secret onion key for the ntor handshake. Must only
278  * be called from the main thread. */
279 MOCK_IMPL(STATIC const struct curve25519_keypair_t *,
281 {
282  return &curve25519_onion_key;
283 }
284 
285 /** Return a map from KEYID (the key itself) to keypairs for use in the ntor
286  * handshake. Must only be called from the main thread. */
289 {
290  di_digest256_map_t *m = NULL;
291 
292  const uint8_t *cur_pk = curve25519_onion_key.pubkey.public_key;
293  const uint8_t *last_pk = last_curve25519_onion_key.pubkey.public_key;
294 
295  if (!fast_mem_is_zero((const char *)cur_pk, CURVE25519_PUBKEY_LEN)) {
296  dimap_add_entry(&m, cur_pk,
297  tor_memdup(&curve25519_onion_key,
298  sizeof(curve25519_keypair_t)));
299  }
300  if (!fast_mem_is_zero((const char*)last_pk, CURVE25519_PUBKEY_LEN) &&
301  tor_memneq(cur_pk, last_pk, CURVE25519_PUBKEY_LEN)) {
302  dimap_add_entry(&m, last_pk,
303  tor_memdup(&last_curve25519_onion_key,
304  sizeof(curve25519_keypair_t)));
305  }
306 
307  return m;
308 }
309 /** Helper used to deallocate a di_digest256_map_t returned by
310  * construct_ntor_key_map. */
311 static void
313 {
314  curve25519_keypair_t *k = arg;
315  memwipe(k, 0, sizeof(*k));
316  tor_free(k);
317 }
318 /** Release all storage from a keymap returned by construct_ntor_key_map. */
319 void
321 {
322  if (!map)
323  return;
325 }
326 
327 /** Return the time when the onion key was last set. This is either the time
328  * when the process launched, or the time of the most recent key rotation since
329  * the process launched.
330  */
331 time_t
333 {
334  return onionkey_set_at;
335 }
336 
337 /** Set the current server identity key to <b>k</b>.
338  */
339 void
341 {
342  crypto_pk_free(server_identitykey);
343  server_identitykey = k;
346  log_err(LD_BUG, "Couldn't compute our own identity key digest.");
347  tor_assert(0);
348  }
349 }
350 
351 #ifdef TOR_UNIT_TESTS
352 /** Testing only -- set the server's RSA identity digest to
353  * be <b>digest</b> */
354 void
355 set_server_identity_key_digest_testing(const uint8_t *digest)
356 {
357  memcpy(server_identitykey_digest, digest, DIGEST_LEN);
358 }
359 #endif /* defined(TOR_UNIT_TESTS) */
360 
361 /** Make sure that we have set up our identity keys to match or not match as
362  * appropriate, and die with an assertion if we have not. */
363 static void
365 {
366  if (1)
367  return;
370  /* assert that we have set the client and server keys to be equal */
373  } else {
374  /* assert that we have set the client and server keys to be unequal */
375  if (server_identitykey)
377  }
378 }
379 
380 #ifdef HAVE_MODULE_RELAY
381 
382 /** Returns the current server identity key; requires that the key has
383  * been set, and that we are running as a Tor server.
384  */
386 get_server_identity_key,(void))
387 {
392  return server_identitykey;
393 }
394 
395 #endif /* defined(HAVE_MODULE_RELAY) */
396 
397 /** Return true iff we are a server and the server identity key
398  * has been set. */
399 int
401 {
402  return (server_mode(get_options()) ||
404  server_identitykey != NULL;
405 }
406 
407 /** Set the current client identity key to <b>k</b>.
408  */
409 void
411 {
412  crypto_pk_free(client_identitykey);
413  client_identitykey = k;
414 }
415 
416 /** Returns the current client identity key for use on outgoing TLS
417  * connections; requires that the key has been set.
418  */
419 crypto_pk_t *
421 {
424  return client_identitykey;
425 }
426 
427 /** Return true iff the client identity key has been set. */
428 int
430 {
431  return client_identitykey != NULL;
432 }
433 
434 /** Return the key certificate for this v3 (voting) authority, or NULL
435  * if we have no such certificate. */
438 {
440 }
441 
442 /** Return the v3 signing key for this v3 (voting) authority, or NULL
443  * if we have no such key. */
444 crypto_pk_t *
446 {
447  return authority_signing_key;
448 }
449 
450 /** If we're an authority, and we're using a legacy authority identity key for
451  * emergency migration purposes, return the certificate associated with that
452  * key. */
455 {
456  return legacy_key_certificate;
457 }
458 
459 /** If we're an authority, and we're using a legacy authority identity key for
460  * emergency migration purposes, return that key. */
461 crypto_pk_t *
463 {
464  return legacy_signing_key;
465 }
466 
467 /** Replace the previous onion key with the current onion key, and generate
468  * a new previous onion key. Immediately after calling this function,
469  * the OR should:
470  * - schedule all previous cpuworkers to shut down _after_ processing
471  * pending work. (This will cause fresh cpuworkers to be generated.)
472  * - generate and upload a fresh routerinfo.
473  */
474 void
476 {
477  char *fname, *fname_prev;
478  crypto_pk_t *prkey = NULL;
479  or_state_t *state = get_or_state();
480  curve25519_keypair_t new_curve25519_keypair;
481  time_t now;
482  fname = get_keydir_fname("secret_onion_key");
483  fname_prev = get_keydir_fname("secret_onion_key.old");
484  /* There isn't much point replacing an old key with an empty file */
485  if (file_status(fname) == FN_FILE) {
486  if (replace_file(fname, fname_prev))
487  goto error;
488  }
489  if (!(prkey = crypto_pk_new())) {
490  log_err(LD_GENERAL,"Error constructing rotated onion key");
491  goto error;
492  }
493  if (crypto_pk_generate_key(prkey)) {
494  log_err(LD_BUG,"Error generating onion key");
495  goto error;
496  }
497  if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
498  log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
499  goto error;
500  }
501  tor_free(fname);
502  tor_free(fname_prev);
503  fname = get_keydir_fname("secret_onion_key_ntor");
504  fname_prev = get_keydir_fname("secret_onion_key_ntor.old");
505  if (curve25519_keypair_generate(&new_curve25519_keypair, 1) < 0)
506  goto error;
507  /* There isn't much point replacing an old key with an empty file */
508  if (file_status(fname) == FN_FILE) {
509  if (replace_file(fname, fname_prev))
510  goto error;
511  }
512  if (curve25519_keypair_write_to_file(&new_curve25519_keypair, fname,
513  "onion") < 0) {
514  log_err(LD_FS,"Couldn't write curve25519 onion key to \"%s\".",fname);
515  goto error;
516  }
517  log_info(LD_GENERAL, "Rotating onion key");
519  crypto_pk_free(lastonionkey);
521  onionkey = prkey;
523  sizeof(curve25519_keypair_t));
524  memcpy(&curve25519_onion_key, &new_curve25519_keypair,
525  sizeof(curve25519_keypair_t));
526  now = time(NULL);
527  state->LastRotatedOnionKey = onionkey_set_at = now;
529  mark_my_descriptor_dirty("rotated onion key");
530  or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
531  goto done;
532  error:
533  log_warn(LD_GENERAL, "Couldn't rotate onion key.");
534  if (prkey)
535  crypto_pk_free(prkey);
536  done:
537  memwipe(&new_curve25519_keypair, 0, sizeof(new_curve25519_keypair));
538  tor_free(fname);
539  tor_free(fname_prev);
540 }
541 
542 /** Log greeting message that points to new relay lifecycle document the
543  * first time this function has been called.
544  */
545 static void
547 {
548  static int already_logged = 0;
549 
550  if (already_logged)
551  return;
552 
553  tor_log(LOG_NOTICE, LD_GENERAL, "You are running a new relay. "
554  "Thanks for helping the Tor network! If you wish to know "
555  "what will happen in the upcoming weeks regarding its usage, "
556  "have a look at https://blog.torproject.org/blog/lifecycle-of"
557  "-a-new-relay");
558 
559  already_logged = 1;
560 }
561 
562 /** Load a curve25519 keypair from the file <b>fname</b>, writing it into
563  * <b>keys_out</b>. If the file isn't found, or is empty, and <b>generate</b>
564  * is true, create a new keypair and write it into the file. If there are
565  * errors, log them at level <b>severity</b>. Generate files using <b>tag</b>
566  * in their ASCII wrapper. */
567 static int
569  const char *fname,
570  int generate,
571  int severity,
572  const char *tag)
573 {
574  switch (file_status(fname)) {
575  case FN_DIR:
576  case FN_ERROR:
577  tor_log(severity, LD_FS,"Can't read key from \"%s\"", fname);
578  goto error;
579  /* treat empty key files as if the file doesn't exist, and, if generate
580  * is set, replace the empty file in curve25519_keypair_write_to_file() */
581  case FN_NOENT:
582  case FN_EMPTY:
583  if (generate) {
584  if (!have_lockfile()) {
585  if (try_locking(get_options(), 0)<0) {
586  /* Make sure that --list-fingerprint only creates new keys
587  * if there is no possibility for a deadlock. */
588  tor_log(severity, LD_FS, "Another Tor process has locked \"%s\". "
589  "Not writing any new keys.", fname);
590  /*XXXX The 'other process' might make a key in a second or two;
591  * maybe we should wait for it. */
592  goto error;
593  }
594  }
595  log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
596  fname);
597  if (curve25519_keypair_generate(keys_out, 1) < 0)
598  goto error;
599  if (curve25519_keypair_write_to_file(keys_out, fname, tag)<0) {
600  tor_log(severity, LD_FS,
601  "Couldn't write generated key to \"%s\".", fname);
602  memwipe(keys_out, 0, sizeof(*keys_out));
603  goto error;
604  }
605  } else {
606  log_info(LD_GENERAL, "No key found in \"%s\"", fname);
607  }
608  return 0;
609  case FN_FILE:
610  {
611  char *tag_in=NULL;
612  if (curve25519_keypair_read_from_file(keys_out, &tag_in, fname) < 0) {
613  tor_log(severity, LD_GENERAL,"Error loading private key.");
614  tor_free(tag_in);
615  goto error;
616  }
617  if (!tag_in || strcmp(tag_in, tag)) {
618  tor_log(severity, LD_GENERAL,"Unexpected tag %s on private key.",
619  escaped(tag_in));
620  tor_free(tag_in);
621  goto error;
622  }
623  tor_free(tag_in);
624  return 0;
625  }
626  default:
627  tor_assert(0);
628  }
629 
630  error:
631  return -1;
632 }
633 
634 /** Try to load the vote-signing private key and certificate for being a v3
635  * directory authority, and make sure they match. If <b>legacy</b>, load a
636  * legacy key/cert set for emergency key migration; otherwise load the regular
637  * key/cert set. On success, store them into *<b>key_out</b> and
638  * *<b>cert_out</b> respectively, and return 0. On failure, return -1. */
639 static int
640 load_authority_keyset(int legacy, crypto_pk_t **key_out,
641  authority_cert_t **cert_out)
642 {
643  int r = -1;
644  char *fname = NULL, *cert = NULL;
645  const char *eos = NULL;
646  crypto_pk_t *signing_key = NULL;
647  authority_cert_t *parsed = NULL;
648 
649  fname = get_keydir_fname(
650  legacy ? "legacy_signing_key" : "authority_signing_key");
651  signing_key = init_key_from_file(fname, 0, LOG_ERR, NULL);
652  if (!signing_key) {
653  log_warn(LD_DIR, "No version 3 directory key found in %s", fname);
654  goto done;
655  }
656  tor_free(fname);
657  fname = get_keydir_fname(
658  legacy ? "legacy_certificate" : "authority_certificate");
659  cert = read_file_to_str(fname, 0, NULL);
660  if (!cert) {
661  log_warn(LD_DIR, "Signing key found, but no certificate found in %s",
662  fname);
663  goto done;
664  }
665  parsed = authority_cert_parse_from_string(cert, strlen(cert), &eos);
666  if (!parsed) {
667  log_warn(LD_DIR, "Unable to parse certificate in %s", fname);
668  goto done;
669  }
670  if (!crypto_pk_eq_keys(signing_key, parsed->signing_key)) {
671  log_warn(LD_DIR, "Stored signing key does not match signing key in "
672  "certificate");
673  goto done;
674  }
675 
676  crypto_pk_free(*key_out);
677  authority_cert_free(*cert_out);
678 
679  *key_out = signing_key;
680  *cert_out = parsed;
681  r = 0;
682  signing_key = NULL;
683  parsed = NULL;
684 
685  done:
686  tor_free(fname);
687  tor_free(cert);
688  crypto_pk_free(signing_key);
689  authority_cert_free(parsed);
690  return r;
691 }
692 
693 /** Load the v3 (voting) authority signing key and certificate, if they are
694  * present. Return -1 if anything is missing, mismatched, or unloadable;
695  * return 0 on success. */
696 static int
698 {
701  return -1;
702 
703  if (get_options()->V3AuthUseLegacyKey &&
706  return -1;
707 
708  return 0;
709 }
710 
711 /** If we're a v3 authority, check whether we have a certificate that's
712  * likely to expire soon. Warn if we do, but not too often. */
713 void
715 {
716  time_t now, expires;
717  static time_t last_warned = 0;
718  int badness, time_left, warn_interval;
719  if (!authdir_mode_v3(get_options()) || !authority_key_certificate)
720  return;
721 
722  now = time(NULL);
724  time_left = (int)( expires - now );
725  if (time_left <= 0) {
726  badness = LOG_ERR;
727  warn_interval = 60*60;
728  } else if (time_left <= 24*60*60) {
729  badness = LOG_WARN;
730  warn_interval = 60*60;
731  } else if (time_left <= 24*60*60*7) {
732  badness = LOG_WARN;
733  warn_interval = 24*60*60;
734  } else if (time_left <= 24*60*60*30) {
735  badness = LOG_WARN;
736  warn_interval = 24*60*60*5;
737  } else {
738  return;
739  }
740 
741  if (last_warned + warn_interval > now)
742  return;
743 
744  if (time_left <= 0) {
745  tor_log(badness, LD_DIR, "Your v3 authority certificate has expired."
746  " Generate a new one NOW.");
747  } else if (time_left <= 24*60*60) {
748  tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
749  "hours; Generate a new one NOW.", time_left/(60*60));
750  } else {
751  tor_log(badness, LD_DIR, "Your v3 authority certificate expires in %d "
752  "days; Generate a new one soon.", time_left/(24*60*60));
753  }
754  last_warned = now;
755 }
756 
757 /** Get the lifetime of an onion key in days. This value is defined by the
758  * network consensus parameter "onion-key-rotation-days". Always returns a
759  * value between <b>MIN_ONION_KEY_LIFETIME_DAYS</b> and
760  * <b>MAX_ONION_KEY_LIFETIME_DAYS</b>.
761  */
762 static int
764 {
765  return networkstatus_get_param(NULL,
766  "onion-key-rotation-days",
770 }
771 
772 /** Get the current lifetime of an onion key in seconds. This value is defined
773  * by the network consensus parameter "onion-key-rotation-days", but the value
774  * is converted to seconds.
775  */
776 int
778 {
779  return get_onion_key_rotation_days_()*24*60*60;
780 }
781 
782 /** Get the grace period of an onion key in seconds. This value is defined by
783  * the network consensus parameter "onion-key-grace-period-days", but the value
784  * is converted to seconds.
785  */
786 int
788 {
789  int grace_period;
790  grace_period = networkstatus_get_param(NULL,
791  "onion-key-grace-period-days",
795  return grace_period*24*60*60;
796 }
797 
798 /** Set up Tor's TLS contexts, based on our configuration and keys. Return 0
799  * on success, and -1 on failure. */
800 int
802 {
803  unsigned int flags = 0;
804  const or_options_t *options = get_options();
805  int lifetime = options->SSLKeyLifetime;
806  if (public_server_mode(options))
807  flags |= TOR_TLS_CTX_IS_PUBLIC_SERVER;
808  if (!lifetime) { /* we should guess a good ssl cert lifetime */
809 
810  /* choose between 5 and 365 days, and round to the day */
811  unsigned int five_days = 5*24*3600;
812  unsigned int one_year = 365*24*3600;
813  lifetime = crypto_rand_int_range(five_days, one_year);
814  lifetime -= lifetime % (24*3600);
815 
816  if (crypto_rand_int(2)) {
817  /* Half the time we expire at midnight, and half the time we expire
818  * one second before midnight. (Some CAs wobble their expiry times a
819  * bit in practice, perhaps to reduce collision attacks; see ticket
820  * 8443 for details about observed certs in the wild.) */
821  lifetime--;
822  }
823  }
824 
825  /* It's ok to pass lifetime in as an unsigned int, since
826  * config_parse_interval() checked it. */
827  return tor_tls_context_init(flags,
829  server_mode(options) ?
830  get_server_identity_key() : NULL,
831  (unsigned int)lifetime);
832 }
833 
834 /** Compute fingerprint (or hashed fingerprint if hashed is 1) and write
835  * it to 'fingerprint' (or 'hashed-fingerprint'). Return 0 on success, or
836  * -1 if Tor should die,
837  */
838 STATIC int
839 router_write_fingerprint(int hashed, int ed25519_identity)
840 {
841  char *keydir = NULL;
842  const char *fname = hashed ? "hashed-fingerprint" :
843  (ed25519_identity ? "fingerprint-ed25519" :
844  "fingerprint");
845  char fingerprint[FINGERPRINT_LEN+1];
846  const or_options_t *options = get_options();
847  char *fingerprint_line = NULL;
848  int result = -1;
849 
850  keydir = get_datadir_fname(fname);
851  log_info(LD_GENERAL,"Dumping %s%s to \"%s\"...", hashed ? "hashed " : "",
852  ed25519_identity ? "ed25519 identity" : "fingerprint", keydir);
853 
854  if (ed25519_identity) { /* ed25519 identity */
855  digest256_to_base64(fingerprint, (const char *)
856  get_master_identity_key()->pubkey);
857  } else { /* RSA identity */
858  if (!hashed) {
859  if (crypto_pk_get_fingerprint(get_server_identity_key(),
860  fingerprint, 0) < 0) {
861  log_err(LD_GENERAL,"Error computing fingerprint");
862  goto done;
863  }
864  } else {
865  if (crypto_pk_get_hashed_fingerprint(get_server_identity_key(),
866  fingerprint) < 0) {
867  log_err(LD_GENERAL,"Error computing hashed fingerprint");
868  goto done;
869  }
870  }
871  }
872 
873  tor_asprintf(&fingerprint_line, "%s %s\n", options->Nickname, fingerprint);
874 
875  /* Check whether we need to write the (hashed-)fingerprint file. */
876  if (write_str_to_file_if_not_equal(keydir, fingerprint_line)) {
877  log_err(LD_FS, "Error writing %s%s line to file",
878  hashed ? "hashed " : "",
879  ed25519_identity ? "ed25519 identity" : "fingerprint");
880  goto done;
881  }
882 
883  log_notice(LD_GENERAL, "Your Tor %s identity key %s fingerprint is '%s %s'",
884  hashed ? "bridge's hashed" : "server's",
885  ed25519_identity ? "ed25519" : "",
886  options->Nickname, fingerprint);
887 
888  result = 0;
889  done:
890  tor_free(keydir);
891  tor_free(fingerprint_line);
892  return result;
893 }
894 
895 static int
896 init_keys_common(void)
897 {
898  if (!key_lock)
900 
901  return 0;
902 }
903 
904 int
905 init_keys_client(void)
906 {
907  crypto_pk_t *prkey;
908  if (init_keys_common() < 0)
909  return -1;
910 
911  if (!(prkey = crypto_pk_new()))
912  return -1;
913  if (crypto_pk_generate_key(prkey)) {
914  crypto_pk_free(prkey);
915  return -1;
916  }
918  /* Create a TLS context. */
919  if (router_initialize_tls_context() < 0) {
920  log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
921  return -1;
922  }
923  return 0;
924 }
925 
926 /** Initialize all OR private keys, and the TLS context, as necessary.
927  * On OPs, this only initializes the tls context. Return 0 on success,
928  * or -1 if Tor should die.
929  */
930 int
932 {
933  char *keydir;
934  const char *mydesc;
935  crypto_pk_t *prkey;
936  char digest[DIGEST_LEN];
937  char v3_digest[DIGEST_LEN];
938  const or_options_t *options = get_options();
939  dirinfo_type_t type;
940  time_t now = time(NULL);
941  dir_server_t *ds;
942  int v3_digest_set = 0;
943  authority_cert_t *cert = NULL;
944 
945  /* OP's don't need persistent keys; just make up an identity and
946  * initialize the TLS context. */
947  if (!server_mode(options) && !(options->command == CMD_KEY_EXPIRATION)) {
948  return init_keys_client();
949  }
950  if (init_keys_common() < 0)
951  return -1;
952 
953  if (create_keys_directory(options) < 0)
954  return -1;
955 
956  /* 1a. Read v3 directory authority key/cert information. */
957  memset(v3_digest, 0, sizeof(v3_digest));
958  if (authdir_mode_v3(options)) {
959  if (init_v3_authority_keys()<0) {
960  log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
961  "were unable to load our v3 authority keys and certificate! "
962  "Use tor-gencert to generate them. Dying.");
963  return -1;
964  }
965  cert = get_my_v3_authority_cert();
966  if (cert) {
968  v3_digest) < 0) {
969  log_err(LD_BUG, "Couldn't compute my v3 authority identity key "
970  "digest.");
971  return -1;
972  }
973  v3_digest_set = 1;
974  }
975  }
976 
977  /* 1b. Read identity key. Make it if none is found. */
978  keydir = get_keydir_fname("secret_id_key");
979  log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
980  bool created = false;
981  prkey = init_key_from_file(keydir, 1, LOG_ERR, &created);
982  tor_free(keydir);
983  if (!prkey) return -1;
984  if (created)
987 
988  /* 1c. If we are configured as a bridge, generate a client key;
989  * otherwise, set the server identity key as our client identity
990  * key. */
991  if (public_server_mode(options)) {
992  set_client_identity_key(crypto_pk_dup_key(prkey)); /* set above */
993  } else {
994  if (!(prkey = crypto_pk_new()))
995  return -1;
996  if (crypto_pk_generate_key(prkey)) {
997  crypto_pk_free(prkey);
998  return -1;
999  }
1000  set_client_identity_key(prkey);
1001  }
1002 
1003  /* 1d. Load all ed25519 keys */
1004  const int new_signing_key = load_ed_keys(options,now);
1005  if (new_signing_key < 0)
1006  return -1;
1007 
1008  /* 2. Read onion key. Make it if none is found. */
1009  keydir = get_keydir_fname("secret_onion_key");
1010  log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
1011  prkey = init_key_from_file(keydir, 1, LOG_ERR, &created);
1012  if (created)
1014  tor_free(keydir);
1015  if (!prkey) return -1;
1016  set_onion_key(prkey);
1017  if (options->command == CMD_RUN_TOR) {
1018  /* only mess with the state file if we're actually running Tor */
1019  or_state_t *state = get_or_state();
1020  if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
1021  /* We allow for some parsing slop, but we don't want to risk accepting
1022  * values in the distant future. If we did, we might never rotate the
1023  * onion key. */
1025  } else {
1026  /* We have no LastRotatedOnionKey set; either we just created the key
1027  * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
1028  * start the clock ticking now so that we will eventually rotate it even
1029  * if we don't stay up for the full lifetime of an onion key. */
1030  state->LastRotatedOnionKey = onionkey_set_at = now;
1031  or_state_mark_dirty(state, options->AvoidDiskWrites ?
1032  time(NULL)+3600 : 0);
1033  }
1034  }
1035 
1036  keydir = get_keydir_fname("secret_onion_key.old");
1037  if (!lastonionkey && file_status(keydir) == FN_FILE) {
1038  /* Load keys from non-empty files only.
1039  * Missing old keys won't be replaced with freshly generated keys. */
1040  prkey = init_key_from_file(keydir, 0, LOG_ERR, 0);
1041  if (prkey)
1042  lastonionkey = prkey;
1043  }
1044  tor_free(keydir);
1045 
1046  {
1047  /* 2b. Load curve25519 onion keys. */
1048  int r;
1049  keydir = get_keydir_fname("secret_onion_key_ntor");
1051  keydir, 1, LOG_ERR, "onion");
1052  tor_free(keydir);
1053  if (r<0)
1054  return -1;
1055 
1056  keydir = get_keydir_fname("secret_onion_key_ntor.old");
1057  if (fast_mem_is_zero((const char *)
1058  last_curve25519_onion_key.pubkey.public_key,
1060  file_status(keydir) == FN_FILE) {
1061  /* Load keys from non-empty files only.
1062  * Missing old keys won't be replaced with freshly generated keys. */
1064  keydir, 0, LOG_ERR, "onion");
1065  }
1066  tor_free(keydir);
1067  }
1068 
1069  /* 3. Initialize link key and TLS context. */
1070  if (router_initialize_tls_context() < 0) {
1071  log_err(LD_GENERAL,"Error initializing TLS context");
1072  return -1;
1073  }
1074 
1075  /* 3b. Get an ed25519 link certificate. Note that we need to do this
1076  * after we set up the TLS context */
1077  if (generate_ed_link_cert(options, now, new_signing_key > 0) < 0) {
1078  log_err(LD_GENERAL,"Couldn't make link cert");
1079  return -1;
1080  }
1081 
1082  /* 4. Build our router descriptor. */
1083  /* Must be called after keys are initialized. */
1084  mydesc = router_get_my_descriptor();
1085  if (authdir_mode_v3(options)) {
1086  const char *m = NULL;
1087  routerinfo_t *ri;
1088  /* We need to add our own fingerprint and ed25519 key so it gets
1089  * recognized. */
1090  if (dirserv_add_own_fingerprint(get_server_identity_key(),
1091  get_master_identity_key())) {
1092  log_err(LD_GENERAL,"Error adding own fingerprint to set of relays");
1093  return -1;
1094  }
1095  if (mydesc) {
1096  was_router_added_t added;
1097  ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL, NULL);
1098  if (!ri) {
1099  log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
1100  return -1;
1101  }
1102  added = dirserv_add_descriptor(ri, &m, "self");
1103  if (!WRA_WAS_ADDED(added)) {
1104  if (!WRA_WAS_OUTDATED(added)) {
1105  log_err(LD_GENERAL, "Unable to add own descriptor to directory: %s",
1106  m?m:"<unknown error>");
1107  return -1;
1108  } else {
1109  /* If the descriptor was outdated, that's ok. This can happen
1110  * when some config options are toggled that affect workers, but
1111  * we don't really need new keys yet so the descriptor doesn't
1112  * change and the old one is still fresh. */
1113  log_info(LD_GENERAL, "Couldn't add own descriptor to directory "
1114  "after key init: %s This is usually not a problem.",
1115  m?m:"<unknown error>");
1116  }
1117  }
1118  }
1119  }
1120 
1121  /* 5. Dump fingerprint, ed25519 identity and possibly hashed fingerprint
1122  * to files. */
1123  if (router_write_fingerprint(0, 0)) {
1124  log_err(LD_FS, "Error writing fingerprint to file");
1125  return -1;
1126  }
1127  if (!public_server_mode(options) && router_write_fingerprint(1, 0)) {
1128  log_err(LD_FS, "Error writing hashed fingerprint to file");
1129  return -1;
1130  }
1131  if (router_write_fingerprint(0, 1)) {
1132  log_err(LD_FS, "Error writing ed25519 identity to file");
1133  return -1;
1134  }
1135 
1136  if (!authdir_mode(options))
1137  return 0;
1138  /* 6. [authdirserver only] load approved-routers file */
1139  if (dirserv_load_fingerprint_file() < 0) {
1140  log_err(LD_GENERAL,"Error loading fingerprints");
1141  return -1;
1142  }
1143  /* 6b. [authdirserver only] add own key to approved directories. */
1144  crypto_pk_get_digest(get_server_identity_key(), digest);
1145  type = ((options->V3AuthoritativeDir ?
1147  (options->BridgeAuthoritativeDir ? BRIDGE_DIRINFO : NO_DIRINFO));
1148 
1150  if (!ds) {
1151  tor_addr_port_t ipv6_orport;
1152  routerconf_find_ipv6_or_ap(options, &ipv6_orport);
1153  ds = trusted_dir_server_new(options->Nickname, NULL,
1154  routerconf_find_dir_port(options, 0),
1155  routerconf_find_or_port(options,AF_INET),
1156  &ipv6_orport,
1157  digest,
1158  v3_digest,
1159  type, 0.0);
1160  if (!ds) {
1161  log_err(LD_GENERAL,"We want to be a directory authority, but we "
1162  "couldn't add ourselves to the authority list. Failing.");
1163  return -1;
1164  }
1165  dir_server_add(ds);
1166  }
1167  if (ds->type != type) {
1168  log_warn(LD_DIR, "Configured authority type does not match authority "
1169  "type in DirAuthority list. Adjusting. (%d v %d)",
1170  type, ds->type);
1171  ds->type = type;
1172  }
1173  if (v3_digest_set && (ds->type & V3_DIRINFO) &&
1174  tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
1175  log_warn(LD_DIR, "V3 identity key does not match identity declared in "
1176  "DirAuthority line. Adjusting.");
1177  memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
1178  }
1179 
1180  if (cert) { /* add my own cert to the list of known certs */
1181  log_info(LD_DIR, "adding my own v3 cert");
1184  TRUSTED_DIRS_CERTS_SRC_SELF, 0,
1185  NULL)<0) {
1186  log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
1187  return -1;
1188  }
1189  }
1190 
1191  return 0; /* success */
1192 }
1193 
1194 /** The lower threshold of remaining bandwidth required to advertise (or
1195  * automatically provide) directory services */
1196 /* XXX Should this be increased? */
1197 #define MIN_BW_TO_ADVERTISE_DIRSERVER 51200
1198 
1199 /** Return true iff we have enough configured bandwidth to advertise or
1200  * automatically provide directory services from cache directory
1201  * information. */
1202 int
1204 {
1206  return 0;
1207  }
1208  if (options->RelayBandwidthRate > 0 &&
1210  return 0;
1211  }
1212  return 1;
1213 }
1214 
1215 /** Helper: Return 1 if we have sufficient resources for serving directory
1216  * requests, return 0 otherwise.
1217  * dir_port is either 0 or the configured DirPort number.
1218  * If AccountingMax is set less than our advertised bandwidth, then don't
1219  * serve requests. Likewise, if our advertised bandwidth is less than
1220  * MIN_BW_TO_ADVERTISE_DIRSERVER, don't bother trying to serve requests.
1221  */
1222 static int
1223 router_should_be_dirserver(const or_options_t *options, int dir_port)
1224 {
1225  static int advertising=1; /* start out assuming we will advertise */
1226  int new_choice=1;
1227  const char *reason = NULL;
1228 
1229  if (accounting_is_enabled(options) &&
1230  get_options()->AccountingRule != ACCT_IN) {
1231  /* Don't spend bytes for directory traffic if we could end up hibernating,
1232  * but allow DirPort otherwise. Some relay operators set AccountingMax
1233  * because they're confused or to get statistics. Directory traffic has a
1234  * much larger effect on output than input so there is no reason to turn it
1235  * off if using AccountingRule in. */
1236  int interval_length = accounting_get_interval_length();
1237  uint32_t effective_bw = relay_get_effective_bwrate(options);
1238  uint64_t acc_bytes;
1239  if (!interval_length) {
1240  log_warn(LD_BUG, "An accounting interval is not allowed to be zero "
1241  "seconds long. Raising to 1.");
1242  interval_length = 1;
1243  }
1244  log_info(LD_GENERAL, "Calculating whether to advertise %s: effective "
1245  "bwrate: %u, AccountingMax: %"PRIu64", "
1246  "accounting interval length %d",
1247  dir_port ? "dirport" : "begindir",
1248  effective_bw, (options->AccountingMax),
1249  interval_length);
1250 
1251  acc_bytes = options->AccountingMax;
1252  if (get_options()->AccountingRule == ACCT_SUM)
1253  acc_bytes /= 2;
1254  if (effective_bw >=
1255  acc_bytes / interval_length) {
1256  new_choice = 0;
1257  reason = "AccountingMax enabled";
1258  }
1259  } else if (! router_has_bandwidth_to_be_dirserver(options)) {
1260  /* if we're advertising a small amount */
1261  new_choice = 0;
1262  reason = "BandwidthRate under 50KB";
1263  }
1264 
1265  if (advertising != new_choice) {
1266  if (new_choice == 1) {
1267  if (dir_port > 0)
1268  log_notice(LD_DIR, "Advertising DirPort as %d", dir_port);
1269  else
1270  log_notice(LD_DIR, "Advertising directory service support");
1271  } else {
1272  tor_assert(reason);
1273  log_notice(LD_DIR, "Not advertising Dir%s (Reason: %s)",
1274  dir_port ? "Port" : "ectory Service support", reason);
1275  }
1276  advertising = new_choice;
1277  }
1278 
1279  return advertising;
1280 }
1281 
1282 /** Look at a variety of factors, and return 0 if we don't want to
1283  * advertise the fact that we have a DirPort open or begindir support, else
1284  * return 1.
1285  *
1286  * Where dir_port or supports_tunnelled_dir_requests are not relevant, they
1287  * must be 0.
1288  *
1289  * Log a helpful message if we change our mind about whether to publish.
1290  */
1291 static int
1293  uint16_t dir_port,
1294  int supports_tunnelled_dir_requests)
1295 {
1296  /* Part one: reasons to publish or not publish that aren't
1297  * worth mentioning to the user, either because they're obvious
1298  * or because they're normal behavior. */
1299 
1300  /* short circuit the rest of the function */
1301  if (!dir_port && !supports_tunnelled_dir_requests)
1302  return 0;
1303  if (authdir_mode(options)) /* always publish */
1304  return 1;
1305  if (net_is_disabled())
1306  return 0;
1307  if (dir_port && !routerconf_find_dir_port(options, dir_port))
1308  return 0;
1309  if (supports_tunnelled_dir_requests &&
1310  !routerconf_find_or_port(options, AF_INET))
1311  return 0;
1312 
1313  /* Part two: consider config options that could make us choose to
1314  * publish or not publish that the user might find surprising. */
1315  return router_should_be_dirserver(options, dir_port);
1316 }
1317 
1318 /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
1319  * advertise the fact that we have a DirPort open, else return the
1320  * DirPort we want to advertise.
1321  */
1322 int
1323 router_should_advertise_dirport(const or_options_t *options, uint16_t dir_port)
1324 {
1325  /* supports_tunnelled_dir_requests is not relevant, pass 0 */
1326  return decide_to_advertise_dir_impl(options, dir_port, 0) ? dir_port : 0;
1327 }
1328 
1329 /** Front-end to decide_to_advertise_dir_impl(): return 0 if we don't want to
1330  * advertise the fact that we support begindir requests, else return 1.
1331  */
1332 static int
1334  int supports_tunnelled_dir_requests)
1335 {
1336  /* dir_port is not relevant, pass 0 */
1337  return decide_to_advertise_dir_impl(options, 0,
1338  supports_tunnelled_dir_requests);
1339 }
1340 
1341 /** Return true iff the combination of options in <b>options</b> and parameters
1342  * in the consensus mean that we don't want to allow exits from circuits
1343  * we got from addresses not known to be servers. */
1344 int
1346 {
1347  if (options->RefuseUnknownExits != -1) {
1348  return options->RefuseUnknownExits;
1349  } else {
1350  return networkstatus_get_param(NULL, "refuseunknownexits", 1, 0, 1);
1351  }
1352 }
1353 
1354 /**
1355  * If true, then we will publish our descriptor even if our own IPv4 ORPort
1356  * seems to be unreachable.
1357  **/
1359 /**
1360  * If true, then we will publish our descriptor even if our own IPv6 ORPort
1361  * seems to be unreachable.
1362  **/
1364 
1365 /** Decide if we're a publishable server. We are a publishable server if:
1366  * - We don't have the ClientOnly option set
1367  * and
1368  * - We have the PublishServerDescriptor option set to non-empty
1369  * and
1370  * - We have ORPort set
1371  * and
1372  * - We believe our ORPort and DirPort (if present) are reachable from
1373  * the outside; or
1374  * - We believe our ORPort is reachable from the outside, and we can't
1375  * check our DirPort because the consensus has no exits; or
1376  * - We are an authoritative directory server.
1377  */
1378 static int
1380 {
1381  const or_options_t *options = get_options();
1382 
1383  if (options->ClientOnly)
1384  return 0;
1385  if (options->PublishServerDescriptor_ == NO_DIRINFO)
1386  return 0;
1387  if (!server_mode(options))
1388  return 0;
1389  if (authdir_mode(options))
1390  return 1;
1391  if (!routerconf_find_or_port(options, AF_INET))
1392  return 0;
1393  if (!router_orport_seems_reachable(options, AF_INET)) {
1394  // We have an ipv4 orport, and it doesn't seem reachable.
1396  return 0;
1397  }
1398  }
1399  if (!router_orport_seems_reachable(options, AF_INET6)) {
1400  // We have an ipv6 orport, and it doesn't seem reachable.
1402  return 0;
1403  }
1404  }
1405  if (router_have_consensus_path() == CONSENSUS_PATH_INTERNAL) {
1406  /* All set: there are no exits in the consensus (maybe this is a tiny
1407  * test network), so we can't check our DirPort reachability. */
1408  return 1;
1409  } else {
1410  return router_dirport_seems_reachable(options);
1411  }
1412 }
1413 
1414 /** Initiate server descriptor upload as reasonable (if server is publishable,
1415  * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
1416  *
1417  * We need to rebuild the descriptor if it's dirty even if we're not
1418  * uploading, because our reachability testing *uses* our descriptor to
1419  * determine what IP address and ports to test.
1420  */
1421 void
1423 {
1424  int rebuilt;
1425 
1426  if (!server_mode(get_options()))
1427  return;
1428 
1429  rebuilt = router_rebuild_descriptor(0);
1432  if (rebuilt == 0)
1434  } else {
1436  }
1437 }
1438 
1439 /** Return the port of the first active listener of type
1440  * <b>listener_type</b>. Returns 0 if no port is found. */
1441 /** XXX not a very good interface. it's not reliable when there are
1442  multiple listeners. */
1443 uint16_t
1445  sa_family_t family)
1446 {
1447  /* Iterate all connections, find one of the right kind and return
1448  the port. Not very sophisticated or fast, but effective. */
1449  smartlist_t *conns = get_connection_array();
1450  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1451  if (conn->type == listener_type && !conn->marked_for_close &&
1452  conn->socket_family == family) {
1453  return conn->port;
1454  }
1455  } SMARTLIST_FOREACH_END(conn);
1456 
1457  return 0;
1458 }
1459 
1460 /** Return the port that we should advertise as our ORPort in a given address
1461  * family; this is either the one configured in the ORPort option, or the one
1462  * we actually bound to if ORPort is "auto". Returns 0 if no port is found. */
1463 uint16_t
1465  sa_family_t family)
1466 {
1468  family);
1469  (void)options;
1470 
1471  /* If the port is in 'auto' mode, we have to use
1472  router_get_listener_port_by_type(). */
1473  if (port == CFG_AUTO_PORT)
1475  family);
1476 
1477  return port;
1478 }
1479 
1480 /** As routerconf_find_or_port(), but returns the IPv6 address and
1481  * port in ipv6_ap_out, which must not be NULL. Returns a null address and
1482  * zero port, if no ORPort is found. */
1483 void
1485  tor_addr_port_t *ipv6_ap_out)
1486 {
1487  /* Bug in calling function, we can't return a sensible result, and it
1488  * shouldn't use the NULL pointer once we return. */
1489  tor_assert(ipv6_ap_out);
1490 
1491  /* If there is no valid IPv6 ORPort, return a null address and port. */
1492  tor_addr_make_null(&ipv6_ap_out->addr, AF_INET6);
1493  ipv6_ap_out->port = 0;
1494 
1497  AF_INET6);
1498  const uint16_t port = routerconf_find_or_port(options,
1499  AF_INET6);
1500 
1501  if (!addr || port == 0) {
1502  log_debug(LD_CONFIG, "There is no advertised IPv6 ORPort.");
1503  return;
1504  }
1505 
1506  /* If the relay is configured using the default authorities, disallow
1507  * internal IPs. Otherwise, allow them. For IPv4 ORPorts and DirPorts,
1508  * this check is done in resolve_my_address(). See #33681. */
1509  const int default_auth = using_default_dir_authorities(options);
1510  if (tor_addr_is_internal(addr, 0) && default_auth) {
1511  log_warn(LD_CONFIG,
1512  "Unable to use configured IPv6 ORPort \"%s\" in a "
1513  "descriptor. Skipping it. "
1514  "Try specifying a globally reachable address explicitly.",
1515  fmt_addrport(addr, port));
1516  return;
1517  }
1518 
1519  tor_addr_copy(&ipv6_ap_out->addr, addr);
1520  ipv6_ap_out->port = port;
1521 }
1522 
1523 /** Returns true if this router has an advertised IPv6 ORPort. */
1524 bool
1526 {
1527  /* What we want here is to learn if we have configured an IPv6 ORPort.
1528  * Remember, ORPort can listen on [::] and thus consider internal by
1529  * router_get_advertised_ipv6_or_ap() since we do _not_ want to advertise
1530  * such address. */
1531  const tor_addr_t *addr =
1533  const uint16_t port =
1534  routerconf_find_or_port(options, AF_INET6);
1535 
1536  return tor_addr_port_is_valid(addr, port, 1);
1537 }
1538 
1539 /** Returns true if this router can extend over IPv6.
1540  *
1541  * This check should only be performed by relay extend code.
1542  *
1543  * Clients should check if relays can initiate and accept IPv6 extends using
1544  * node_supports_initiating_ipv6_extends() and
1545  * node_supports_accepting_ipv6_extends().
1546  *
1547  * As with other extends, relays should assume the client has already
1548  * performed the relevant checks for the next hop. (Otherwise, relays that
1549  * have just added IPv6 ORPorts won't be able to self-test those ORPorts.)
1550  *
1551  * Accepting relays don't need to perform any IPv6-specific checks before
1552  * accepting a connection, because having an IPv6 ORPort implies support for
1553  * the relevant protocol version.
1554  */
1555 MOCK_IMPL(bool,
1557 {
1558  /* We might add some extra checks here, such as ExtendAllowIPv6Addresses
1559  * from ticket 33818. */
1560  return routerconf_has_ipv6_orport(options);
1561 }
1562 
1563 /** Return the port that we should advertise as our DirPort;
1564  * this is one of three possibilities:
1565  * The one that is passed as <b>dirport</b> if the DirPort option is 0, or
1566  * the one configured in the DirPort option,
1567  * or the one we actually bound to if DirPort is "auto". */
1568 uint16_t
1569 routerconf_find_dir_port(const or_options_t *options, uint16_t dirport)
1570 {
1571  int dirport_configured = portconf_get_primary_dir_port();
1572  (void)options;
1573 
1574  if (!dirport_configured)
1575  return dirport;
1576 
1577  if (dirport_configured == CFG_AUTO_PORT)
1579  AF_INET);
1580 
1581  return dirport_configured;
1582 }
1583 
1584 /*
1585  * OR descriptor generation.
1586  */
1587 
1588 /** My routerinfo. */
1590 /** My extrainfo */
1592 /** Why did we most recently decide to regenerate our descriptor? Used to
1593  * tell the authorities why we're sending it to them. */
1594 static const char *desc_gen_reason = "uninitialized reason";
1595 /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
1596  * now. */
1598 /** Why did we mark the descriptor dirty? */
1599 STATIC const char *desc_dirty_reason = "Tor just started";
1600 /** Boolean: do we need to regenerate the above? */
1601 static int desc_needs_upload = 0;
1602 
1603 /** OR only: If <b>force</b> is true, or we haven't uploaded this
1604  * descriptor successfully yet, try to upload our signed descriptor to
1605  * all the directory servers we know about.
1606  */
1607 void
1609 {
1610  const routerinfo_t *ri;
1611  extrainfo_t *ei;
1612  char *msg;
1613  size_t desc_len, extra_len = 0, total_len;
1615 
1616  ri = router_get_my_routerinfo();
1617  if (!ri) {
1618  log_info(LD_GENERAL, "No descriptor; skipping upload");
1619  return;
1620  }
1621  ei = router_get_my_extrainfo();
1622  if (auth == NO_DIRINFO)
1623  return;
1624  if (!force && !desc_needs_upload)
1625  return;
1626 
1627  log_info(LD_OR, "Uploading relay descriptor to directory authorities%s",
1628  force ? " (forced)" : "");
1629 
1630  desc_needs_upload = 0;
1631 
1632  desc_len = ri->cache_info.signed_descriptor_len;
1633  extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
1634  total_len = desc_len + extra_len + 1;
1635  msg = tor_malloc(total_len);
1636  memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
1637  if (ei) {
1638  memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
1639  }
1640  msg[desc_len+extra_len] = 0;
1641 
1643  (auth & BRIDGE_DIRINFO) ?
1646  auth, msg, desc_len, extra_len);
1647  tor_free(msg);
1648 }
1649 
1650 /** OR only: Check whether my exit policy says to allow connection to
1651  * conn. Return 0 if we accept; non-0 if we reject.
1652  */
1653 int
1655 {
1656  const routerinfo_t *me = router_get_my_routerinfo();
1657  if (!me) /* make sure routerinfo exists */
1658  return -1;
1659 
1660  /* make sure it's resolved to something. this way we can't get a
1661  'maybe' below. */
1662  if (tor_addr_is_null(addr))
1663  return -1;
1664 
1665  /* look at router_get_my_routerinfo()->exit_policy for both the v4 and the
1666  * v6 policies. The exit_policy field in router_get_my_routerinfo() is a
1667  * bit unusual, in that it contains IPv6 and IPv6 entries. We don't want to
1668  * look at router_get_my_routerinfo()->ipv6_exit_policy, since that's a port
1669  * summary. */
1670  if ((tor_addr_family(addr) == AF_INET ||
1671  tor_addr_family(addr) == AF_INET6)) {
1672  return compare_tor_addr_to_addr_policy(addr, port,
1674 #if 0
1675  } else if (tor_addr_family(addr) == AF_INET6) {
1676  return get_options()->IPv6Exit &&
1680 #endif /* 0 */
1681  } else {
1682  return -1;
1683  }
1684 }
1685 
1686 /** Return true iff my exit policy is reject *:*. Return -1 if we don't
1687  * have a descriptor */
1688 MOCK_IMPL(int,
1690 {
1691  const routerinfo_t *me = router_get_my_routerinfo();
1692  if (!me) /* make sure routerinfo exists */
1693  return -1;
1694 
1695  return me->policy_is_reject_star;
1696 }
1697 
1698 /** Return true iff I'm a server and <b>digest</b> is equal to
1699  * my server identity key digest. */
1700 int
1701 router_digest_is_me(const char *digest)
1702 {
1703  return (server_identitykey &&
1705 }
1706 
1707 /** Return my identity digest. */
1708 const uint8_t *
1710 {
1711  return (const uint8_t *)server_identitykey_digest;
1712 }
1713 
1714 /** Return true iff I'm a server and <b>digest</b> is equal to
1715  * my identity digest. */
1716 int
1718 {
1720  if (!ei)
1721  return 0;
1722 
1723  return tor_memeq(digest,
1724  ei->cache_info.signed_descriptor_digest,
1725  DIGEST_LEN);
1726 }
1727 
1728 /** A wrapper around router_digest_is_me(). */
1729 int
1731 {
1732  return router_digest_is_me(router->cache_info.identity_digest);
1733 }
1734 
1735 /**
1736  * Return true if we are a server, and if @a addr is an address we are
1737  * currently publishing (or trying to publish) in our descriptor.
1738  * Return false otherwise.
1739  **/
1740 bool
1742 {
1743  IF_BUG_ONCE(!addr)
1744  return false;
1745 
1746  const routerinfo_t *me = router_get_my_routerinfo();
1747  if (!me)
1748  return false;
1749 
1750  switch (tor_addr_family(addr)) {
1751  case AF_INET:
1752  return tor_addr_eq(addr, &me->ipv4_addr);
1753  case AF_INET6:
1754  return tor_addr_eq(addr, &me->ipv6_addr);
1755  default:
1756  return false;
1757  }
1758 }
1759 
1760 /** Return a routerinfo for this OR, rebuilding a fresh one if
1761  * necessary. Return NULL on error, or if called on an OP. */
1762 MOCK_IMPL(const routerinfo_t *,
1764 {
1765  return router_get_my_routerinfo_with_err(NULL);
1766 }
1767 
1768 /** Return routerinfo of this OR. Rebuild it from
1769  * scratch if needed. Set <b>*err</b> to 0 on success or to
1770  * appropriate TOR_ROUTERINFO_ERROR_* value on failure.
1771  */
1772 MOCK_IMPL(const routerinfo_t *,
1774 {
1775  if (!server_mode(get_options())) {
1776  if (err)
1777  *err = TOR_ROUTERINFO_ERROR_NOT_A_SERVER;
1778 
1779  return NULL;
1780  }
1781 
1782  if (!desc_routerinfo) {
1783  if (err)
1784  *err = TOR_ROUTERINFO_ERROR_DESC_REBUILDING;
1785 
1786  return NULL;
1787  }
1788 
1789  if (err)
1790  *err = 0;
1791 
1792  return desc_routerinfo;
1793 }
1794 
1795 /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
1796  * one if necessary. Return NULL on error.
1797  */
1798 const char *
1800 {
1801  const char *body;
1802  const routerinfo_t *me = router_get_my_routerinfo();
1803  if (! me)
1804  return NULL;
1805  tor_assert(me->cache_info.saved_location == SAVED_NOWHERE);
1806  body = signed_descriptor_get_body(&me->cache_info);
1807  /* Make sure this is nul-terminated. */
1808  tor_assert(!body[me->cache_info.signed_descriptor_len]);
1809  log_debug(LD_GENERAL,"my desc is '%s'", body);
1810  return body;
1811 }
1812 
1813 /** Return the extrainfo document for this OR, or NULL if we have none.
1814  * Rebuilt it (and the server descriptor) if necessary. */
1815 extrainfo_t *
1817 {
1818  if (!server_mode(get_options()))
1819  return NULL;
1821  return NULL;
1822  return desc_extrainfo;
1823 }
1824 
1825 /** Return a human-readable string describing what triggered us to generate
1826  * our current descriptor, or NULL if we don't know. */
1827 const char *
1829 {
1830  return desc_gen_reason;
1831 }
1832 
1833 /* Like router_check_descriptor_address_consistency, but specifically for the
1834  * ORPort or DirPort.
1835  * listener_type is either CONN_TYPE_OR_LISTENER or CONN_TYPE_DIR_LISTENER. */
1836 static void
1837 router_check_descriptor_address_port_consistency(const tor_addr_t *addr,
1838  int listener_type)
1839 {
1840  int family, port_cfg;
1841 
1842  tor_assert(addr);
1843  tor_assert(listener_type == CONN_TYPE_OR_LISTENER ||
1844  listener_type == CONN_TYPE_DIR_LISTENER);
1845 
1846  family = tor_addr_family(addr);
1847  /* The first advertised Port may be the magic constant CFG_AUTO_PORT. */
1848  port_cfg = portconf_get_first_advertised_port(listener_type, family);
1849  if (port_cfg != 0 &&
1850  !port_exists_by_type_addr_port(listener_type, addr, port_cfg, 1)) {
1851  const tor_addr_t *port_addr =
1852  portconf_get_first_advertised_addr(listener_type, family);
1853  /* If we're building a descriptor with no advertised address,
1854  * something is terribly wrong. */
1855  tor_assert(port_addr);
1856 
1857  char port_addr_str[TOR_ADDR_BUF_LEN];
1858  char desc_addr_str[TOR_ADDR_BUF_LEN];
1859 
1860  tor_addr_to_str(port_addr_str, port_addr, TOR_ADDR_BUF_LEN, 0);
1861  tor_addr_to_str(desc_addr_str, addr, TOR_ADDR_BUF_LEN, 0);
1862 
1863  const char *listener_str = (listener_type == CONN_TYPE_OR_LISTENER ?
1864  "OR" : "Dir");
1865  const char *af_str = fmt_af_family(family);
1866  log_warn(LD_CONFIG, "The %s %sPort address %s does not match the "
1867  "descriptor address %s. If you have a static public IPv4 "
1868  "address, use 'Address <%s>' and 'OutboundBindAddress "
1869  "<%s>'. If you are behind a NAT, use two %sPort lines: "
1870  "'%sPort <PublicPort> NoListen' and '%sPort <InternalPort> "
1871  "NoAdvertise'.",
1872  af_str, listener_str, port_addr_str, desc_addr_str, af_str,
1873  af_str, listener_str, listener_str, listener_str);
1874  }
1875 }
1876 
1877 /** Tor relays only have one IPv4 or/and one IPv6 address in the descriptor,
1878  * which is derived from the Address torrc option, or guessed using various
1879  * methods in relay_find_addr_to_publish().
1880  *
1881  * Warn the operator if there is no ORPort associated with the given address
1882  * in addr.
1883  *
1884  * Warn the operator if there is no DirPort on the descriptor address.
1885  *
1886  * This catches a few common config errors:
1887  * - operators who expect ORPorts and DirPorts to be advertised on the
1888  * ports' listen addresses, rather than the torrc Address (or guessed
1889  * addresses in the absence of an Address config). This includes
1890  * operators who attempt to put their ORPort and DirPort on different
1891  * addresses;
1892  * - discrepancies between guessed addresses and configured listen
1893  * addresses (when the Address option isn't set).
1894  *
1895  * If a listener is listening on all IPv4 addresses, it is assumed that it
1896  * is listening on the configured Address, and no messages are logged.
1897  *
1898  * If an operators has specified NoAdvertise ORPorts in a NAT setting,
1899  * no messages are logged, unless they have specified other advertised
1900  * addresses.
1901  *
1902  * The message tells operators to configure an ORPort and DirPort that match
1903  * the Address (using NoListen if needed). */
1904 static void
1906 {
1907  router_check_descriptor_address_port_consistency(addr,
1909  router_check_descriptor_address_port_consistency(addr,
1911 }
1912 
1913 /** A list of nicknames that we've warned about including in our family,
1914  * for one reason or another. */
1916 
1917 /**
1918  * Return a new smartlist containing the family members configured in
1919  * <b>options</b>. Warn about invalid or missing entries. Return NULL
1920  * if this relay should not declare a family.
1921  **/
1924 {
1925  if (!options->MyFamily)
1926  return NULL;
1927 
1928  if (options->BridgeRelay)
1929  return NULL;
1930 
1931  if (!warned_family)
1933 
1934  smartlist_t *declared_family = smartlist_new();
1935  config_line_t *family;
1936 
1937  /* First we try to get the whole family in the form of hexdigests. */
1938  for (family = options->MyFamily; family; family = family->next) {
1939  char *name = family->value;
1940  const node_t *member;
1941  if (options->Nickname && !strcasecmp(name, options->Nickname))
1942  continue; /* Don't list ourself by nickname, that's redundant */
1943  else
1944  member = node_get_by_nickname(name, 0);
1945 
1946  if (!member) {
1947  /* This node doesn't seem to exist, so warn about it if it is not
1948  * a hexdigest. */
1949  int is_legal = is_legal_nickname_or_hexdigest(name);
1952  if (is_legal)
1953  log_warn(LD_CONFIG,
1954  "There is a router named %s in my declared family, but "
1955  "I have no descriptor for it. I'll use the nickname "
1956  "as is, but this may confuse clients. Please list it "
1957  "by identity digest instead.", escaped(name));
1958  else
1959  log_warn(LD_CONFIG, "There is a router named %s in my declared "
1960  "family, but that isn't a legal digest or nickname. "
1961  "Skipping it.", escaped(name));
1963  }
1964  if (is_legal) {
1965  smartlist_add_strdup(declared_family, name);
1966  }
1967  } else {
1968  /* List the node by digest. */
1969  char *fp = tor_malloc(HEX_DIGEST_LEN+2);
1970  fp[0] = '$';
1972  member->identity, DIGEST_LEN);
1973  smartlist_add(declared_family, fp);
1974 
1975  if (! is_legal_hexdigest(name) &&
1977  /* Warn if this node was not specified by hexdigest. */
1978  log_warn(LD_CONFIG, "There is a router named %s in my declared "
1979  "family, but it wasn't listed by digest. Please consider "
1980  "saying %s instead, if that's what you meant.",
1981  escaped(name), fp);
1983  }
1984  }
1985  }
1986 
1987  /* Now declared_family should have the closest we can come to the
1988  * identities that the user wanted.
1989  *
1990  * Unlike older versions of Tor, we _do_ include our own identity: this
1991  * helps microdescriptor compression, and helps in-memory compression
1992  * on clients. */
1993  nodefamily_t *nf = nodefamily_from_members(declared_family,
1995  NF_WARN_MALFORMED,
1996  NULL);
1997  SMARTLIST_FOREACH(declared_family, char *, s, tor_free(s));
1998  smartlist_free(declared_family);
1999  if (!nf) {
2000  return NULL;
2001  }
2002 
2003  char *s = nodefamily_format(nf);
2004  nodefamily_free(nf);
2005 
2006  smartlist_t *result = smartlist_new();
2007  smartlist_split_string(result, s, NULL,
2008  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2009  tor_free(s);
2010 
2011  if (smartlist_len(result) == 1) {
2012  /* This is a one-element list containing only ourself; instead return
2013  * nothing */
2014  const char *singleton = smartlist_get(result, 0);
2015  bool is_me = false;
2016  if (singleton[0] == '$') {
2017  char d[DIGEST_LEN];
2018  int n = base16_decode(d, sizeof(d), singleton+1, strlen(singleton+1));
2019  if (n == DIGEST_LEN &&
2021  is_me = true;
2022  }
2023  }
2024  if (!is_me) {
2025  // LCOV_EXCL_START
2026  log_warn(LD_BUG, "Found a singleton family list with an element "
2027  "that wasn't us! Element was %s", escaped(singleton));
2028  // LCOV_EXCL_STOP
2029  } else {
2030  SMARTLIST_FOREACH(result, char *, cp, tor_free(cp));
2031  smartlist_free(result);
2032  return NULL;
2033  }
2034  }
2035 
2036  return result;
2037 }
2038 
2039 /** Allocate a fresh, unsigned routerinfo for this OR, without any of the
2040  * fields that depend on the corresponding extrainfo.
2041  *
2042  * On success, set ri_out to the new routerinfo, and return 0.
2043  * Caller is responsible for freeing the generated routerinfo.
2044  *
2045  * Returns a negative value and sets ri_out to NULL on temporary error.
2046  */
2047 MOCK_IMPL(STATIC int,
2049 {
2050  routerinfo_t *ri = NULL;
2051  tor_addr_t ipv4_addr, ipv6_addr;
2052  char platform[256];
2053  int hibernating = we_are_hibernating();
2054  const or_options_t *options = get_options();
2055  int result = TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2056  uint16_t ipv6_orport = 0;
2057 
2058  if (BUG(!ri_out)) {
2059  result = TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2060  goto err;
2061  }
2062 
2063  /* Find our resolved address both IPv4 and IPv6. In case the address is not
2064  * found, the object is set to an UNSPEC address. */
2065  bool have_v4 = relay_find_addr_to_publish(options, AF_INET,
2066  RELAY_FIND_ADDR_NO_FLAG,
2067  &ipv4_addr);
2068  bool have_v6 = relay_find_addr_to_publish(options, AF_INET6,
2069  RELAY_FIND_ADDR_NO_FLAG,
2070  &ipv6_addr);
2071 
2072  /* Tor requires a relay to have an IPv4 so bail if we can't find it. */
2073  if (!have_v4) {
2074  log_info(LD_CONFIG, "Don't know my address while generating descriptor. "
2075  "Launching circuit to authority to learn it.");
2076  relay_addr_learn_from_dirauth();
2077  result = TOR_ROUTERINFO_ERROR_NO_EXT_ADDR;
2078  goto err;
2079  }
2080  /* Log a message if the address in the descriptor doesn't match the ORPort
2081  * and DirPort addresses configured by the operator. */
2084 
2085  ri = tor_malloc_zero(sizeof(routerinfo_t));
2086  ri->cache_info.routerlist_index = -1;
2087  ri->nickname = tor_strdup(options->Nickname);
2088 
2089  /* IPv4. */
2090  tor_addr_copy(&ri->ipv4_addr, &ipv4_addr);
2091  ri->ipv4_orport = routerconf_find_or_port(options, AF_INET);
2092  ri->ipv4_dirport = routerconf_find_dir_port(options, 0);
2093 
2094  /* IPv6. Do not publish an IPv6 if we don't have an ORPort that can be used
2095  * with the address. This is possible for instance if the ORPort is
2096  * IPv4Only. */
2097  ipv6_orport = routerconf_find_or_port(options, AF_INET6);
2098  if (have_v6 && ipv6_orport != 0) {
2099  tor_addr_copy(&ri->ipv6_addr, &ipv6_addr);
2100  ri->ipv6_orport = ipv6_orport;
2101  }
2102 
2105  ri->cache_info.published_on = time(NULL);
2106  /* get_onion_key() must invoke from main thread */
2107  router_set_rsa_onion_pkey(get_onion_key(), &ri->onion_pkey,
2108  &ri->onion_pkey_len);
2109 
2110  ri->onion_curve25519_pkey =
2111  tor_memdup(&get_current_curve25519_keypair()->pubkey,
2112  sizeof(curve25519_public_key_t));
2113 
2114  ri->identity_pkey = crypto_pk_dup_key(get_server_identity_key());
2115  if (BUG(crypto_pk_get_digest(ri->identity_pkey,
2116  ri->cache_info.identity_digest) < 0)) {
2117  result = TOR_ROUTERINFO_ERROR_DIGEST_FAILED;
2118  goto err;
2119  }
2120  ri->cache_info.signing_key_cert =
2121  tor_cert_dup(get_master_signing_key_cert());
2122 
2123  get_platform_str(platform, sizeof(platform));
2124  ri->platform = tor_strdup(platform);
2125 
2126  ri->protocol_list = tor_strdup(protover_get_supported_protocols());
2127 
2128  /* compute ri->bandwidthrate as the min of various options */
2130 
2131  /* and compute ri->bandwidthburst similarly */
2133 
2134  /* Report bandwidth, unless we're hibernating or shutting down */
2135  ri->bandwidthcapacity = hibernating ? 0 : bwhist_bandwidth_assess();
2136 
2138  /* DNS is screwed up; don't claim to be an exit. */
2140  } else {
2142  &ri->ipv6_addr,
2143  &ri->exit_policy);
2144  }
2145  ri->policy_is_reject_star =
2146  policy_is_reject_star(ri->exit_policy, AF_INET, 1) &&
2147  policy_is_reject_star(ri->exit_policy, AF_INET6, 1);
2148 
2149  if (options->IPv6Exit) {
2150  char *p_tmp = policy_summarize(ri->exit_policy, AF_INET6);
2151  if (p_tmp)
2152  ri->ipv6_exit_policy = parse_short_policy(p_tmp);
2153  tor_free(p_tmp);
2154  }
2155 
2156  ri->declared_family = get_my_declared_family(options);
2157 
2158  if (options->BridgeRelay) {
2160  /* Bridges shouldn't be able to send their descriptors unencrypted,
2161  anyway, since they don't have a DirPort, and always connect to the
2162  bridge authority anonymously. But just in case they somehow think of
2163  sending them on an unencrypted connection, don't allow them to try. */
2164  ri->cache_info.send_unencrypted = 0;
2165  } else {
2167  ri->cache_info.send_unencrypted = 1;
2168  }
2169 
2170  goto done;
2171 
2172  err:
2173  routerinfo_free(ri);
2174  *ri_out = NULL;
2175  return result;
2176 
2177  done:
2178  *ri_out = ri;
2179  return 0;
2180 }
2181 
2182 /** Allocate and return a fresh, unsigned extrainfo for this OR, based on the
2183  * routerinfo ri.
2184  *
2185  * Uses options->Nickname to set the nickname, and options->BridgeRelay to set
2186  * ei->cache_info.send_unencrypted.
2187  *
2188  * If ri is NULL, logs a BUG() warning and returns NULL.
2189  * Caller is responsible for freeing the generated extrainfo.
2190  */
2191 static extrainfo_t *
2193 {
2194  extrainfo_t *ei = NULL;
2195  const or_options_t *options = get_options();
2196 
2197  if (BUG(!ri))
2198  return NULL;
2199 
2200  /* Now generate the extrainfo. */
2201  ei = tor_malloc_zero(sizeof(extrainfo_t));
2202  ei->cache_info.is_extrainfo = 1;
2203  strlcpy(ei->nickname, options->Nickname, sizeof(ei->nickname));
2204  ei->cache_info.published_on = ri->cache_info.published_on;
2205  ei->cache_info.signing_key_cert =
2206  tor_cert_dup(get_master_signing_key_cert());
2207 
2208  memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
2209  DIGEST_LEN);
2210 
2211  if (options->BridgeRelay) {
2212  /* See note in router_build_fresh_routerinfo(). */
2213  ei->cache_info.send_unencrypted = 0;
2214  } else {
2215  ei->cache_info.send_unencrypted = 1;
2216  }
2217 
2218  return ei;
2219 }
2220 
2221 /** Dump the extrainfo descriptor body for ei, sign it, and add the body and
2222  * signature to ei->cache_info. Note that the extrainfo body is determined by
2223  * ei, and some additional config and statistics state: see
2224  * extrainfo_dump_to_string() for details.
2225  *
2226  * Return 0 on success, -1 on temporary error.
2227  * If ei is NULL, logs a BUG() warning and returns -1.
2228  * On error, ei->cache_info is not modified.
2229  */
2230 static int
2232 {
2233  if (BUG(!ei))
2234  return -1;
2235 
2237  ei, get_server_identity_key(),
2238  get_master_signing_keypair()) < 0) {
2239  log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
2240  return -1;
2241  }
2242 
2243  ei->cache_info.signed_descriptor_len =
2244  strlen(ei->cache_info.signed_descriptor_body);
2245 
2247  ei->cache_info.signed_descriptor_len,
2248  ei->cache_info.signed_descriptor_digest);
2249  crypto_digest256((char*) ei->digest256,
2250  ei->cache_info.signed_descriptor_body,
2251  ei->cache_info.signed_descriptor_len,
2252  DIGEST_SHA256);
2253 
2254  return 0;
2255 }
2256 
2257 /** Allocate and return a fresh, signed extrainfo for this OR, based on the
2258  * routerinfo ri.
2259  *
2260  * If ri is NULL, logs a BUG() warning and returns NULL.
2261  * Caller is responsible for freeing the generated extrainfo.
2262  */
2265 {
2266  int result = -1;
2267  extrainfo_t *ei = NULL;
2268 
2269  if (BUG(!ri))
2270  return NULL;
2271 
2273  /* router_build_fresh_unsigned_extrainfo() should not fail. */
2274  if (BUG(!ei))
2275  goto err;
2276 
2278  if (result < 0)
2279  goto err;
2280 
2281  goto done;
2282 
2283  err:
2284  extrainfo_free(ei);
2285  return NULL;
2286 
2287  done:
2288  return ei;
2289 }
2290 
2291 /** Set the fields in ri that depend on ei.
2292  *
2293  * If ei is NULL, logs a BUG() warning and zeroes the relevant fields.
2294  */
2295 STATIC void
2297  const extrainfo_t *ei)
2298 {
2299  if (BUG(!ei)) {
2300  /* Just to be safe, zero ri->cache_info.extra_info_digest here. */
2301  memset(ri->cache_info.extra_info_digest, 0, DIGEST_LEN);
2302  memset(ri->cache_info.extra_info_digest256, 0, DIGEST256_LEN);
2303  return;
2304  }
2305 
2306  /* Now finish the router descriptor. */
2307  memcpy(ri->cache_info.extra_info_digest,
2308  ei->cache_info.signed_descriptor_digest,
2309  DIGEST_LEN);
2310  memcpy(ri->cache_info.extra_info_digest256,
2311  ei->digest256,
2312  DIGEST256_LEN);
2313 }
2314 
2315 /** Dump the descriptor body for ri, sign it, and add the body and signature to
2316  * ri->cache_info. Note that the descriptor body is determined by ri, and some
2317  * additional config and state: see router_dump_router_to_string() for details.
2318  *
2319  * Return 0 on success, and a negative value on temporary error.
2320  * If ri is NULL, logs a BUG() warning and returns a negative value.
2321  * On error, ri->cache_info is not modified.
2322  */
2323 STATIC int
2325 {
2326  if (BUG(!ri))
2327  return TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2328 
2329  if (! (ri->cache_info.signed_descriptor_body =
2330  router_dump_router_to_string(ri, get_server_identity_key(),
2331  get_onion_key(),
2333  get_master_signing_keypair())) ) {
2334  log_warn(LD_BUG, "Couldn't generate router descriptor.");
2335  return TOR_ROUTERINFO_ERROR_CANNOT_GENERATE;
2336  }
2337 
2338  ri->cache_info.signed_descriptor_len =
2339  strlen(ri->cache_info.signed_descriptor_body);
2340 
2342  strlen(ri->cache_info.signed_descriptor_body),
2343  ri->cache_info.signed_descriptor_digest);
2344 
2345  return 0;
2346 }
2347 
2348 /** Build a fresh routerinfo, signed server descriptor, and signed extrainfo
2349  * document for this OR.
2350  *
2351  * Set r to the generated routerinfo, e to the generated extrainfo document.
2352  * Failure to generate an extra-info document is not an error and is indicated
2353  * by setting e to NULL.
2354  * Return 0 on success, and a negative value on temporary error.
2355  * Caller is responsible for freeing generated documents on success.
2356  */
2357 int
2359 {
2360  int result = TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2361  routerinfo_t *ri = NULL;
2362  extrainfo_t *ei = NULL;
2363 
2364  if (BUG(!r))
2365  goto err;
2366 
2367  if (BUG(!e))
2368  goto err;
2369 
2371  if (result < 0) {
2372  goto err;
2373  }
2374  /* If ri is NULL, then result should be negative. So this check should be
2375  * unreachable. */
2376  if (BUG(!ri)) {
2377  result = TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2378  goto err;
2379  }
2380 
2382 
2383  /* Failing to create an ei is not an error. */
2384  if (ei) {
2386  }
2387 
2389  if (result < 0)
2390  goto err;
2391 
2392  if (ei) {
2394  &ri->cache_info, NULL))) {
2395  result = TOR_ROUTERINFO_ERROR_INTERNAL_BUG;
2396  goto err;
2397  }
2398  }
2399 
2400  goto done;
2401 
2402  err:
2403  routerinfo_free(ri);
2404  extrainfo_free(ei);
2405  *r = NULL;
2406  *e = NULL;
2407  return result;
2408 
2409  done:
2410  *r = ri;
2411  *e = ei;
2412  return 0;
2413 }
2414 
2415 /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
2416  * routerinfo, signed server descriptor, and extra-info document for this OR.
2417  * Return 0 on success, -1 on temporary error.
2418  */
2419 int
2421 {
2422  int err = 0;
2423  routerinfo_t *ri;
2424  extrainfo_t *ei;
2425 
2426  if (desc_clean_since && !force)
2427  return 0;
2428 
2429  log_info(LD_OR, "Rebuilding relay descriptor%s", force ? " (forced)" : "");
2430 
2431  err = router_build_fresh_descriptor(&ri, &ei);
2432  if (err < 0) {
2433  return err;
2434  }
2435 
2436  routerinfo_free(desc_routerinfo);
2437  desc_routerinfo = ri;
2438  extrainfo_free(desc_extrainfo);
2439  desc_extrainfo = ei;
2440 
2441  desc_clean_since = time(NULL);
2442  desc_needs_upload = 1;
2444  if (BUG(desc_gen_reason == NULL)) {
2445  desc_gen_reason = "descriptor was marked dirty earlier, for no reason.";
2446  }
2447  desc_dirty_reason = NULL;
2449  return 0;
2450 }
2451 
2452 /** Called when we have a new set of consensus parameters. */
2453 void
2455 {
2456  const int32_t DEFAULT_ASSUME_REACHABLE = 0;
2457  const int32_t DEFAULT_ASSUME_REACHABLE_IPV6 = 0;
2458  int ar, ar6;
2459  ar = networkstatus_get_param(ns,
2460  "assume-reachable",
2461  DEFAULT_ASSUME_REACHABLE, 0, 1);
2462  ar6 = networkstatus_get_param(ns,
2463  "assume-reachable-ipv6",
2464  DEFAULT_ASSUME_REACHABLE_IPV6, 0, 1);
2465 
2468 }
2469 
2470 /** Indicate if the IPv6 address should be omitted from the descriptor when
2471  * publishing it. This can happen if the IPv4 is reachable but the
2472  * auto-discovered IPv6 is not. We still publish the descriptor.
2473  *
2474  * Only relays should look at this and only for their descriptor.
2475  *
2476  * XXX: The real harder fix is to never put in the routerinfo_t a non
2477  * reachable address and instead use the last resolved address cache to do
2478  * reachability test or anything that has to do with what address tor thinks
2479  * it has. */
2480 static bool omit_ipv6_on_publish = false;
2481 
2482 /** Mark our descriptor out of data iff the IPv6 omit status flag is flipped
2483  * it changes from its previous value.
2484  *
2485  * This is used when our IPv6 port is found reachable or not. */
2486 void
2487 mark_my_descriptor_if_omit_ipv6_changes(const char *reason, bool omit_ipv6)
2488 {
2489  bool previous = omit_ipv6_on_publish;
2490  omit_ipv6_on_publish = omit_ipv6;
2491 
2492  /* Only mark it dirty if the IPv6 omit flag was flipped. */
2493  if (previous != omit_ipv6) {
2494  mark_my_descriptor_dirty(reason);
2495  }
2496 }
2497 
2498 /** If our router descriptor ever goes this long without being regenerated
2499  * because something changed, we force an immediate regenerate-and-upload. */
2500 #define FORCE_REGENERATE_DESCRIPTOR_INTERVAL (18*60*60)
2501 
2502 /** If our router descriptor seems to be missing or unacceptable according
2503  * to the authorities, regenerate and reupload it _this_ often. */
2504 #define FAST_RETRY_DESCRIPTOR_INTERVAL (90*60)
2505 
2506 /** Mark descriptor out of date if it's been "too long" since we last tried
2507  * to upload one. */
2508 void
2510 {
2511  networkstatus_t *ns;
2512  const routerstatus_t *rs;
2513  const char *retry_fast_reason = NULL; /* Set if we should retry frequently */
2514  const time_t slow_cutoff = now - FORCE_REGENERATE_DESCRIPTOR_INTERVAL;
2515  const time_t fast_cutoff = now - FAST_RETRY_DESCRIPTOR_INTERVAL;
2516 
2517  /* If it's already dirty, don't mark it. */
2518  if (! desc_clean_since)
2519  return;
2520 
2521  /* If it's older than FORCE_REGENERATE_DESCRIPTOR_INTERVAL, it's always
2522  * time to rebuild it. */
2523  if (desc_clean_since < slow_cutoff) {
2524  mark_my_descriptor_dirty("time for new descriptor");
2525  return;
2526  }
2527  /* Now we see whether we want to be retrying frequently or no. The
2528  * rule here is that we'll retry frequently if we aren't listed in the
2529  * live consensus we have, or if the publication time of the
2530  * descriptor listed for us in the consensus is very old, or if the
2531  * consensus lists us as "stale" and we haven't regenerated since the
2532  * consensus was published. */
2534  if (ns) {
2536  if (rs == NULL)
2537  retry_fast_reason = "not listed in consensus";
2538  else if (rs->published_on < slow_cutoff)
2539  retry_fast_reason = "version listed in consensus is quite old";
2540  else if (rs->is_staledesc && ns->valid_after > desc_clean_since)
2541  retry_fast_reason = "listed as stale in consensus";
2542  }
2543 
2544  if (retry_fast_reason && desc_clean_since < fast_cutoff)
2545  mark_my_descriptor_dirty(retry_fast_reason);
2546 }
2547 
2548 /** Call when the current descriptor is out of date. */
2549 void
2550 mark_my_descriptor_dirty(const char *reason)
2551 {
2552  const or_options_t *options = get_options();
2553  if (BUG(reason == NULL)) {
2554  reason = "marked descriptor dirty for unspecified reason";
2555  }
2556  if (server_mode(options) && options->PublishServerDescriptor_) {
2557  log_info(LD_OR, "Decided to publish new relay descriptor: %s", reason);
2558  }
2559  desc_clean_since = 0;
2560  if (!desc_dirty_reason)
2561  desc_dirty_reason = reason;
2563 }
2564 
2565 /** How frequently will we republish our descriptor because of large (factor
2566  * of 2) shifts in estimated bandwidth? Note: We don't use this constant
2567  * if our previous bandwidth estimate was exactly 0. */
2568 #define MAX_BANDWIDTH_CHANGE_FREQ (3*60*60)
2569 
2570 /** Maximum uptime to republish our descriptor because of large shifts in
2571  * estimated bandwidth. */
2572 #define MAX_UPTIME_BANDWIDTH_CHANGE (24*60*60)
2573 
2574 /** By which factor bandwidth shifts have to change to be considered large. */
2575 #define BANDWIDTH_CHANGE_FACTOR 2
2576 
2577 /** Check whether bandwidth has changed a lot since the last time we announced
2578  * bandwidth while the uptime is smaller than MAX_UPTIME_BANDWIDTH_CHANGE.
2579  * If so, mark our descriptor dirty. */
2580 void
2582 {
2583  static time_t last_changed = 0;
2584  uint64_t prev, cur;
2585  const int hibernating = we_are_hibernating();
2586 
2587  /* If the relay uptime is bigger than MAX_UPTIME_BANDWIDTH_CHANGE,
2588  * the next regularly scheduled descriptor update (18h) will be enough */
2589  if (get_uptime() > MAX_UPTIME_BANDWIDTH_CHANGE && !hibernating)
2590  return;
2591 
2592  const routerinfo_t *my_ri = router_get_my_routerinfo();
2593 
2594  if (!my_ri)
2595  return;
2596 
2597  prev = my_ri->bandwidthcapacity;
2598 
2599  /* Consider ourselves to have zero bandwidth if we're hibernating or
2600  * shutting down. */
2601  cur = hibernating ? 0 : bwhist_bandwidth_assess();
2602 
2603  if ((prev != cur && (!prev || !cur)) ||
2604  cur > (prev * BANDWIDTH_CHANGE_FACTOR) ||
2605  cur < (prev / BANDWIDTH_CHANGE_FACTOR) ) {
2606  if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now || !prev) {
2607  log_info(LD_GENERAL,
2608  "Measured bandwidth has changed; rebuilding descriptor.");
2609  mark_my_descriptor_dirty("bandwidth has changed");
2610  last_changed = now;
2611  }
2612  }
2613 }
2614 
2615 // This function can be "noreturn" if relay mode is disabled and
2616 // ALL_BUGS_ARE_FATAL is set.
2617 DISABLE_GCC_WARNING("-Wmissing-noreturn")
2618 
2619 /** Note at log level severity that our best guess of address has changed from
2620  * <b>prev</b> to <b>cur</b>. */
2621 void
2623  const tor_addr_t *prev,
2624  const tor_addr_t *cur,
2625  const char *source)
2626 {
2627  char addrbuf_prev[TOR_ADDR_BUF_LEN];
2628  char addrbuf_cur[TOR_ADDR_BUF_LEN];
2629 
2630  if (BUG(!server_mode(get_options())))
2631  return;
2632 
2633  if (tor_addr_to_str(addrbuf_prev, prev, sizeof(addrbuf_prev), 1) == NULL)
2634  strlcpy(addrbuf_prev, "???", TOR_ADDR_BUF_LEN);
2635  if (tor_addr_to_str(addrbuf_cur, cur, sizeof(addrbuf_cur), 1) == NULL)
2636  strlcpy(addrbuf_cur, "???", TOR_ADDR_BUF_LEN);
2637 
2638  if (!tor_addr_is_null(prev))
2639  log_fn(severity, LD_GENERAL,
2640  "Our IP Address has changed from %s to %s; "
2641  "rebuilding descriptor (source: %s).",
2642  addrbuf_prev, addrbuf_cur, source);
2643  else
2644  log_notice(LD_GENERAL,
2645  "Guessed our IP address as %s (source: %s).",
2646  addrbuf_cur, source);
2647 }
2648 ENABLE_GCC_WARNING("-Wmissing-noreturn")
2649 
2650 /** Check whether our own address has changed versus the one we have in our
2651  * current descriptor.
2652  *
2653  * If our address has changed, call ip_address_changed() which takes
2654  * appropriate actions. */
2655 void
2657 {
2658  const routerinfo_t *my_ri = router_get_my_routerinfo();
2659  resolved_addr_method_t method = RESOLVED_ADDR_NONE;
2660  char *hostname = NULL;
2661  int families[2] = { AF_INET, AF_INET6 };
2662  bool has_changed = false;
2663 
2664  (void) now;
2665 
2666  /* We can't learn our descriptor address without one. */
2667  if (my_ri == NULL) {
2668  return;
2669  }
2670 
2671  for (size_t i = 0; i < ARRAY_LENGTH(families); i++) {
2672  tor_addr_t current;
2673  const tor_addr_t *previous;
2674  int family = families[i];
2675 
2676  /* Get the descriptor address from the family we are looking up. */
2677  previous = &my_ri->ipv4_addr;
2678  if (family == AF_INET6) {
2679  previous = &my_ri->ipv6_addr;
2680  }
2681 
2682  /* Ignore returned value because we want to notice not only an address
2683  * change but also if an address is lost (current == UNSPEC). */
2684  bool found = find_my_address(get_options(), family, LOG_INFO, &current,
2685  &method, &hostname);
2686  if (!found) {
2687  /* Address was possibly not found because it is simply not configured or
2688  * discoverable. Fallback to our cache, which includes any suggestion
2689  * sent by a trusted directory server. */
2690  found = relay_find_addr_to_publish(get_options(), family,
2691  RELAY_FIND_ADDR_CACHE_ONLY,
2692  &current);
2693  }
2694 
2695  /* The "current" address might be UNSPEC meaning it was not discovered nor
2696  * found in our current cache. If we had an address before and we have
2697  * none now, we consider this an IP change since it appears the relay lost
2698  * its address. */
2699 
2700  if (!tor_addr_eq(previous, &current)) {
2701  char *source;
2702  tor_asprintf(&source, "METHOD=%s%s%s",
2704  hostname ? " HOSTNAME=" : "",
2705  hostname ? hostname : "");
2706  log_addr_has_changed(LOG_NOTICE, previous, &current, source);
2707  tor_free(source);
2708  has_changed = true;
2709  }
2710  tor_free(hostname);
2711  }
2712 
2713  if (has_changed) {
2714  ip_address_changed(0);
2715  }
2716 }
2717 
2718 /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
2719  * string describing the version of Tor and the operating system we're
2720  * currently running on.
2721  */
2722 STATIC void
2723 get_platform_str(char *platform, size_t len)
2724 {
2725  tor_snprintf(platform, len, "Tor %s on %s",
2727 }
2728 
2729 /* XXX need to audit this thing and count fenceposts. maybe
2730  * refactor so we don't have to keep asking if we're
2731  * near the end of maxlen?
2732  */
2733 #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
2734 
2735 /** OR only: Given a routerinfo for this router, and an identity key to sign
2736  * with, encode the routerinfo as a signed server descriptor and return a new
2737  * string encoding the result, or NULL on failure.
2738  *
2739  * In addition to the fields in router, this function calls
2740  * onion_key_lifetime(), get_options(), and we_are_hibernating(), and uses the
2741  * results to populate some fields in the descriptor.
2742  */
2743 char *
2745  const crypto_pk_t *ident_key,
2746  const crypto_pk_t *tap_key,
2747  const curve25519_keypair_t *ntor_keypair,
2748  const ed25519_keypair_t *signing_keypair)
2749 {
2750  char *address = NULL;
2751  char *onion_pkey = NULL; /* Onion key, PEM-encoded. */
2752  crypto_pk_t *rsa_pubkey = NULL;
2753  char *identity_pkey = NULL; /* Identity key, PEM-encoded. */
2754  char digest[DIGEST256_LEN];
2755  char published[ISO_TIME_LEN+1];
2756  char fingerprint[FINGERPRINT_LEN+1];
2757  char *extra_info_line = NULL;
2758  size_t onion_pkeylen, identity_pkeylen;
2759  char *family_line = NULL;
2760  char *extra_or_address = NULL;
2761  const or_options_t *options = get_options();
2762  smartlist_t *chunks = NULL;
2763  char *output = NULL;
2764  const int emit_ed_sigs = signing_keypair &&
2765  router->cache_info.signing_key_cert;
2766  char *ed_cert_line = NULL;
2767  char *rsa_tap_cc_line = NULL;
2768  char *ntor_cc_line = NULL;
2769  char *proto_line = NULL;
2770 
2771  /* Make sure the identity key matches the one in the routerinfo. */
2772  if (!crypto_pk_eq_keys(ident_key, router->identity_pkey)) {
2773  log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
2774  "match router's public key!");
2775  goto err;
2776  }
2777  if (emit_ed_sigs) {
2778  if (!router->cache_info.signing_key_cert->signing_key_included ||
2779  !ed25519_pubkey_eq(&router->cache_info.signing_key_cert->signed_key,
2780  &signing_keypair->pubkey)) {
2781  log_warn(LD_BUG, "Tried to sign a router descriptor with a mismatched "
2782  "ed25519 key chain %d",
2783  router->cache_info.signing_key_cert->signing_key_included);
2784  goto err;
2785  }
2786  }
2787 
2788  /* record our fingerprint, so we can include it in the descriptor */
2789  if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
2790  log_err(LD_BUG,"Error computing fingerprint");
2791  goto err;
2792  }
2793 
2794  if (emit_ed_sigs) {
2795  /* Encode ed25519 signing cert */
2796  char ed_cert_base64[256];
2797  char ed_fp_base64[ED25519_BASE64_LEN+1];
2798  if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
2799  (const char*)router->cache_info.signing_key_cert->encoded,
2800  router->cache_info.signing_key_cert->encoded_len,
2801  BASE64_ENCODE_MULTILINE) < 0) {
2802  log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
2803  goto err;
2804  }
2805  ed25519_public_to_base64(ed_fp_base64,
2806  &router->cache_info.signing_key_cert->signing_key);
2807  tor_asprintf(&ed_cert_line, "identity-ed25519\n"
2808  "-----BEGIN ED25519 CERT-----\n"
2809  "%s"
2810  "-----END ED25519 CERT-----\n"
2811  "master-key-ed25519 %s\n",
2812  ed_cert_base64, ed_fp_base64);
2813  }
2814 
2815  /* PEM-encode the onion key */
2816  rsa_pubkey = router_get_rsa_onion_pkey(router->onion_pkey,
2817  router->onion_pkey_len);
2818  if (crypto_pk_write_public_key_to_string(rsa_pubkey,
2819  &onion_pkey,&onion_pkeylen)<0) {
2820  log_warn(LD_BUG,"write onion_pkey to string failed!");
2821  goto err;
2822  }
2823 
2824  /* PEM-encode the identity key */
2826  &identity_pkey,&identity_pkeylen)<0) {
2827  log_warn(LD_BUG,"write identity_pkey to string failed!");
2828  goto err;
2829  }
2830 
2831  /* Cross-certify with RSA key */
2832  if (tap_key && router->cache_info.signing_key_cert &&
2833  router->cache_info.signing_key_cert->signing_key_included) {
2834  char buf[256];
2835  int tap_cc_len = 0;
2836  uint8_t *tap_cc =
2838  &router->cache_info.signing_key_cert->signing_key,
2839  router->identity_pkey,
2840  &tap_cc_len);
2841  if (!tap_cc) {
2842  log_warn(LD_BUG,"make_tap_onion_key_crosscert failed!");
2843  goto err;
2844  }
2845 
2846  if (base64_encode(buf, sizeof(buf), (const char*)tap_cc, tap_cc_len,
2847  BASE64_ENCODE_MULTILINE) < 0) {
2848  log_warn(LD_BUG,"base64_encode(rsa_crosscert) failed!");
2849  tor_free(tap_cc);
2850  goto err;
2851  }
2852  tor_free(tap_cc);
2853 
2854  tor_asprintf(&rsa_tap_cc_line,
2855  "onion-key-crosscert\n"
2856  "-----BEGIN CROSSCERT-----\n"
2857  "%s"
2858  "-----END CROSSCERT-----\n", buf);
2859  }
2860 
2861  /* Cross-certify with onion keys */
2862  if (ntor_keypair && router->cache_info.signing_key_cert &&
2863  router->cache_info.signing_key_cert->signing_key_included) {
2864  int sign = 0;
2865  char buf[256];
2866  /* XXXX Base the expiration date on the actual onion key expiration time?*/
2867  tor_cert_t *cert =
2868  make_ntor_onion_key_crosscert(ntor_keypair,
2869  &router->cache_info.signing_key_cert->signing_key,
2870  router->cache_info.published_on,
2871  get_onion_key_lifetime(), &sign);
2872  if (!cert) {
2873  log_warn(LD_BUG,"make_ntor_onion_key_crosscert failed!");
2874  goto err;
2875  }
2876  tor_assert(sign == 0 || sign == 1);
2877 
2878  if (base64_encode(buf, sizeof(buf),
2879  (const char*)cert->encoded, cert->encoded_len,
2880  BASE64_ENCODE_MULTILINE)<0) {
2881  log_warn(LD_BUG,"base64_encode(ntor_crosscert) failed!");
2882  tor_cert_free(cert);
2883  goto err;
2884  }
2885  tor_cert_free(cert);
2886 
2887  tor_asprintf(&ntor_cc_line,
2888  "ntor-onion-key-crosscert %d\n"
2889  "-----BEGIN ED25519 CERT-----\n"
2890  "%s"
2891  "-----END ED25519 CERT-----\n", sign, buf);
2892  }
2893 
2894  /* Encode the publication time. */
2895  format_iso_time(published, router->cache_info.published_on);
2896 
2897  if (router->declared_family && smartlist_len(router->declared_family)) {
2898  char *family = smartlist_join_strings(router->declared_family,
2899  " ", 0, NULL);
2900  tor_asprintf(&family_line, "family %s\n", family);
2901  tor_free(family);
2902  } else {
2903  family_line = tor_strdup("");
2904  }
2905 
2906  if (!tor_digest_is_zero(router->cache_info.extra_info_digest)) {
2907  char extra_info_digest[HEX_DIGEST_LEN+1];
2908  base16_encode(extra_info_digest, sizeof(extra_info_digest),
2909  router->cache_info.extra_info_digest, DIGEST_LEN);
2910  if (!tor_digest256_is_zero(router->cache_info.extra_info_digest256)) {
2911  char d256_64[BASE64_DIGEST256_LEN+1];
2912  digest256_to_base64(d256_64, router->cache_info.extra_info_digest256);
2913  tor_asprintf(&extra_info_line, "extra-info-digest %s %s\n",
2914  extra_info_digest, d256_64);
2915  } else {
2916  tor_asprintf(&extra_info_line, "extra-info-digest %s\n",
2917  extra_info_digest);
2918  }
2919  }
2920 
2921  if (!omit_ipv6_on_publish && router->ipv6_orport &&
2922  tor_addr_family(&router->ipv6_addr) == AF_INET6) {
2923  char addr[TOR_ADDR_BUF_LEN];
2924  const char *a;
2925  a = tor_addr_to_str(addr, &router->ipv6_addr, sizeof(addr), 1);
2926  if (a) {
2927  tor_asprintf(&extra_or_address,
2928  "or-address %s:%d\n", a, router->ipv6_orport);
2929  log_debug(LD_OR, "My or-address line is <%s>", extra_or_address);
2930  }
2931  }
2932 
2933  if (router->protocol_list) {
2934  tor_asprintf(&proto_line, "proto %s\n", router->protocol_list);
2935  } else {
2936  proto_line = tor_strdup("");
2937  }
2938 
2939  address = tor_addr_to_str_dup(&router->ipv4_addr);
2940  if (!address)
2941  goto err;
2942 
2943  chunks = smartlist_new();
2944 
2945  /* Generate the easy portion of the router descriptor. */
2946  smartlist_add_asprintf(chunks,
2947  "router %s %s %d 0 %d\n"
2948  "%s"
2949  "%s"
2950  "platform %s\n"
2951  "%s"
2952  "published %s\n"
2953  "fingerprint %s\n"
2954  "uptime %ld\n"
2955  "bandwidth %d %d %d\n"
2956  "%s%s"
2957  "onion-key\n%s"
2958  "signing-key\n%s"
2959  "%s%s"
2960  "%s%s%s",
2961  router->nickname,
2962  address,
2963  router->ipv4_orport,
2964  router_should_advertise_dirport(options, router->ipv4_dirport),
2965  ed_cert_line ? ed_cert_line : "",
2966  extra_or_address ? extra_or_address : "",
2967  router->platform,
2968  proto_line,
2969  published,
2970  fingerprint,
2971  get_uptime(),
2972  (int) router->bandwidthrate,
2973  (int) router->bandwidthburst,
2974  (int) router->bandwidthcapacity,
2975  extra_info_line ? extra_info_line : "",
2976  (options->DownloadExtraInfo || options->V3AuthoritativeDir) ?
2977  "caches-extra-info\n" : "",
2978  onion_pkey, identity_pkey,
2979  rsa_tap_cc_line ? rsa_tap_cc_line : "",
2980  ntor_cc_line ? ntor_cc_line : "",
2981  family_line,
2982  we_are_hibernating() ? "hibernating 1\n" : "",
2983  "hidden-service-dir\n");
2984 
2985  if (options->ContactInfo && strlen(options->ContactInfo)) {
2986  const char *ci = options->ContactInfo;
2987  if (strchr(ci, '\n') || strchr(ci, '\r'))
2988  ci = escaped(ci);
2989  smartlist_add_asprintf(chunks, "contact %s\n", ci);
2990  }
2991 
2992  if (options->BridgeRelay) {
2993  char *bd = NULL;
2994 
2995  if (options->BridgeDistribution && strlen(options->BridgeDistribution)) {
2996  bd = tor_strdup(options->BridgeDistribution);
2997  } else {
2998  bd = tor_strdup("any");
2999  }
3000 
3001  // Make sure our value is lowercased in the descriptor instead of just
3002  // forwarding what the user wrote in their torrc directly.
3003  tor_strlower(bd);
3004 
3005  smartlist_add_asprintf(chunks, "bridge-distribution-request %s\n", bd);
3006  tor_free(bd);
3007  }
3008 
3009  if (router->onion_curve25519_pkey) {
3010  char kbuf[CURVE25519_BASE64_PADDED_LEN + 1];
3011  curve25519_public_to_base64(kbuf, router->onion_curve25519_pkey, false);
3012  smartlist_add_asprintf(chunks, "ntor-onion-key %s\n", kbuf);
3013  } else {
3014  /* Authorities will start rejecting relays without ntor keys in 0.2.9 */
3015  log_err(LD_BUG, "A relay must have an ntor onion key");
3016  goto err;
3017  }
3018 
3019  /* Write the exit policy to the end of 's'. */
3020  if (!router->exit_policy || !smartlist_len(router->exit_policy)) {
3021  smartlist_add_strdup(chunks, "reject *:*\n");
3022  } else if (router->exit_policy) {
3023  char *exit_policy = router_dump_exit_policy_to_string(router,1,0);
3024 
3025  if (!exit_policy)
3026  goto err;
3027 
3028  smartlist_add_asprintf(chunks, "%s\n", exit_policy);
3029  tor_free(exit_policy);
3030  }
3031 
3032  if (router->ipv6_exit_policy) {
3033  char *p6 = write_short_policy(router->ipv6_exit_policy);
3034  if (p6 && strcmp(p6, "reject 1-65535")) {
3035  smartlist_add_asprintf(chunks,
3036  "ipv6-policy %s\n", p6);
3037  }
3038  tor_free(p6);
3039  }
3040 
3043  smartlist_add_strdup(chunks, "tunnelled-dir-server\n");
3044  }
3045 
3046  /* Sign the descriptor with Ed25519 */
3047  if (emit_ed_sigs) {
3048  smartlist_add_strdup(chunks, "router-sig-ed25519 ");
3049  crypto_digest_smartlist_prefix(digest, DIGEST256_LEN,
3050  ED_DESC_SIGNATURE_PREFIX,
3051  chunks, "", DIGEST_SHA256);
3052  ed25519_signature_t sig;
3053  char buf[ED25519_SIG_BASE64_LEN+1];
3054  if (ed25519_sign(&sig, (const uint8_t*)digest, DIGEST256_LEN,
3055  signing_keypair) < 0)
3056  goto err;
3057  ed25519_signature_to_base64(buf, &sig);
3058 
3059  smartlist_add_asprintf(chunks, "%s\n", buf);
3060  }
3061 
3062  /* Sign the descriptor with RSA */
3063  smartlist_add_strdup(chunks, "router-signature\n");
3064 
3065  crypto_digest_smartlist(digest, DIGEST_LEN, chunks, "", DIGEST_SHA1);
3066 
3067  {
3068  char *sig;
3069  if (!(sig = router_get_dirobj_signature(digest, DIGEST_LEN, ident_key))) {
3070  log_warn(LD_BUG, "Couldn't sign router descriptor");
3071  goto err;
3072  }
3073  smartlist_add(chunks, sig);
3074  }
3075 
3076  /* include a last '\n' */
3077  smartlist_add_strdup(chunks, "\n");
3078 
3079  output = smartlist_join_strings(chunks, "", 0, NULL);
3080 
3081 #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
3082  {
3083  char *s_dup;
3084  const char *cp;
3085  routerinfo_t *ri_tmp;
3086  cp = s_dup = tor_strdup(output);
3087  ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL, NULL);
3088  if (!ri_tmp) {
3089  log_err(LD_BUG,
3090  "We just generated a router descriptor we can't parse.");
3091  log_err(LD_BUG, "Descriptor was: <<%s>>", output);
3092  goto err;
3093  }
3094  tor_free(s_dup);
3095  routerinfo_free(ri_tmp);
3096  }
3097 #endif /* defined(DEBUG_ROUTER_DUMP_ROUTER_TO_STRING) */
3098 
3099  goto done;
3100 
3101  err:
3102  tor_free(output); /* sets output to NULL */
3103  done:
3104  if (chunks) {
3105  SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
3106  smartlist_free(chunks);
3107  }
3108  crypto_pk_free(rsa_pubkey);
3109  tor_free(address);
3110  tor_free(family_line);
3111  tor_free(onion_pkey);
3112  tor_free(identity_pkey);
3113  tor_free(extra_or_address);
3114  tor_free(ed_cert_line);
3115  tor_free(rsa_tap_cc_line);
3116  tor_free(ntor_cc_line);
3117  tor_free(extra_info_line);
3118  tor_free(proto_line);
3119 
3120  return output;
3121 }
3122 
3123 /**
3124  * OR only: Given <b>router</b>, produce a string with its exit policy.
3125  * If <b>include_ipv4</b> is true, include IPv4 entries.
3126  * If <b>include_ipv6</b> is true, include IPv6 entries.
3127  */
3128 char *
3130  int include_ipv4,
3131  int include_ipv6)
3132 {
3133  if ((!router->exit_policy) || (router->policy_is_reject_star)) {
3134  return tor_strdup("reject *:*");
3135  }
3136 
3137  return policy_dump_to_string(router->exit_policy,
3138  include_ipv4,
3139  include_ipv6);
3140 }
3141 
3142 /** Load the contents of <b>filename</b>, find the last line starting with
3143  * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
3144  * the past or more than 1 hour in the future with respect to <b>now</b>,
3145  * and write the file contents starting with that line to *<b>out</b>.
3146  * Return 1 for success, 0 if the file does not exist or is empty, or -1
3147  * if the file does not contain a line matching these criteria or other
3148  * failure. */
3149 static int
3150 load_stats_file(const char *filename, const char *end_line, time_t now,
3151  char **out)
3152 {
3153  int r = -1;
3154  char *fname = get_datadir_fname(filename);
3155  char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
3156  time_t written;
3157  switch (file_status(fname)) {
3158  case FN_FILE:
3159  /* X022 Find an alternative to reading the whole file to memory. */
3160  if ((contents = read_file_to_str(fname, 0, NULL))) {
3161  tmp = strstr(contents, end_line);
3162  /* Find last block starting with end_line */
3163  while (tmp) {
3164  start = tmp;
3165  tmp = strstr(tmp + 1, end_line);
3166  }
3167  if (!start)
3168  goto notfound;
3169  if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
3170  goto notfound;
3171  strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
3172  if (parse_iso_time(timestr, &written) < 0)
3173  goto notfound;
3174  if (written < now - (25*60*60) || written > now + (1*60*60))
3175  goto notfound;
3176  *out = tor_strdup(start);
3177  r = 1;
3178  }
3179  notfound:
3180  tor_free(contents);
3181  break;
3182  /* treat empty stats files as if the file doesn't exist */
3183  case FN_NOENT:
3184  case FN_EMPTY:
3185  r = 0;
3186  break;
3187  case FN_ERROR:
3188  case FN_DIR:
3189  default:
3190  break;
3191  }
3192  tor_free(fname);
3193  return r;
3194 }
3195 
3196 /** Add header strings to chunks, based on the extrainfo object extrainfo,
3197  * and ed25519 keypair signing_keypair, if emit_ed_sigs is true.
3198  * Helper for extrainfo_dump_to_string().
3199  * Returns 0 on success, negative on failure. */
3200 static int
3202  smartlist_t *chunks,
3203  const extrainfo_t *extrainfo,
3204  const ed25519_keypair_t *signing_keypair,
3205  int emit_ed_sigs)
3206 {
3207  char identity[HEX_DIGEST_LEN+1];
3208  char published[ISO_TIME_LEN+1];
3209  char *ed_cert_line = NULL;
3210  char *pre = NULL;
3211  int rv = -1;
3212 
3213  base16_encode(identity, sizeof(identity),
3214  extrainfo->cache_info.identity_digest, DIGEST_LEN);
3215  format_iso_time(published, extrainfo->cache_info.published_on);
3216  if (emit_ed_sigs) {
3217  if (!extrainfo->cache_info.signing_key_cert->signing_key_included ||
3218  !ed25519_pubkey_eq(&extrainfo->cache_info.signing_key_cert->signed_key,
3219  &signing_keypair->pubkey)) {
3220  log_warn(LD_BUG, "Tried to sign a extrainfo descriptor with a "
3221  "mismatched ed25519 key chain %d",
3222  extrainfo->cache_info.signing_key_cert->signing_key_included);
3223  goto err;
3224  }
3225  char ed_cert_base64[256];
3226  if (base64_encode(ed_cert_base64, sizeof(ed_cert_base64),
3227  (const char*)extrainfo->cache_info.signing_key_cert->encoded,
3228  extrainfo->cache_info.signing_key_cert->encoded_len,
3229  BASE64_ENCODE_MULTILINE) < 0) {
3230  log_err(LD_BUG,"Couldn't base64-encode signing key certificate!");
3231  goto err;
3232  }
3233  tor_asprintf(&ed_cert_line, "identity-ed25519\n"
3234  "-----BEGIN ED25519 CERT-----\n"
3235  "%s"
3236  "-----END ED25519 CERT-----\n", ed_cert_base64);
3237  } else {
3238  ed_cert_line = tor_strdup("");
3239  }
3240 
3241  /* This is the first chunk in the file. If the file is too big, other chunks
3242  * are removed. So we must only add one chunk here. */
3243  tor_asprintf(&pre, "extra-info %s %s\n%spublished %s\n",
3244  extrainfo->nickname, identity,
3245  ed_cert_line,
3246  published);
3247  smartlist_add(chunks, pre);
3248 
3249  rv = 0;
3250  goto done;
3251 
3252  err:
3253  rv = -1;
3254 
3255  done:
3256  tor_free(ed_cert_line);
3257  return rv;
3258 }
3259 
3260 /** Add pluggable transport and statistics strings to chunks, skipping
3261  * statistics if write_stats_to_extrainfo is false.
3262  * Helper for extrainfo_dump_to_string().
3263  * Can not fail. */
3264 static void
3266  int write_stats_to_extrainfo)
3267 {
3268  const or_options_t *options = get_options();
3269  char *contents = NULL;
3270  time_t now = time(NULL);
3271 
3272  /* If the file is too big, these chunks are removed, starting with the last
3273  * chunk. So each chunk must be a complete line, and the file must be valid
3274  * after each chunk. */
3275 
3276  /* Add information about the pluggable transports we support, even if we
3277  * are not publishing statistics. This information is needed by BridgeDB
3278  * to distribute bridges. */
3279  if (options->ServerTransportPlugin) {
3280  char *pluggable_transports = pt_get_extra_info_descriptor_string();
3281  if (pluggable_transports)
3282  smartlist_add(chunks, pluggable_transports);
3283  }
3284 
3285  if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
3286  log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
3287  /* Bandwidth usage stats don't have their own option */
3288  {
3289  contents = bwhist_get_bandwidth_lines();
3290  smartlist_add(chunks, contents);
3291  }
3292  /* geoip hashes aren't useful unless we are publishing other stats */
3293  if (geoip_is_loaded(AF_INET))
3294  smartlist_add_asprintf(chunks, "geoip-db-digest %s\n",
3295  geoip_db_digest(AF_INET));
3296  if (geoip_is_loaded(AF_INET6))
3297  smartlist_add_asprintf(chunks, "geoip6-db-digest %s\n",
3298  geoip_db_digest(AF_INET6));
3299  if (options->DirReqStatistics &&
3300  load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
3301  "dirreq-stats-end", now, &contents) > 0) {
3302  smartlist_add(chunks, contents);
3303  }
3304  if (options->HiddenServiceStatistics &&
3305  load_stats_file("stats"PATH_SEPARATOR"hidserv-stats",
3306  "hidserv-stats-end", now, &contents) > 0) {
3307  smartlist_add(chunks, contents);
3308  }
3309  if (options->HiddenServiceStatistics &&
3310  load_stats_file("stats"PATH_SEPARATOR"hidserv-v3-stats",
3311  "hidserv-v3-stats-end", now, &contents) > 0) {
3312  smartlist_add(chunks, contents);
3313  }
3314  if (options->EntryStatistics &&
3315  load_stats_file("stats"PATH_SEPARATOR"entry-stats",
3316  "entry-stats-end", now, &contents) > 0) {
3317  smartlist_add(chunks, contents);
3318  }
3319  if (options->CellStatistics &&
3320  load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
3321  "cell-stats-end", now, &contents) > 0) {
3322  smartlist_add(chunks, contents);
3323  }
3324  if (options->ExitPortStatistics &&
3325  load_stats_file("stats"PATH_SEPARATOR"exit-stats",
3326  "exit-stats-end", now, &contents) > 0) {
3327  smartlist_add(chunks, contents);
3328  }
3329  if (options->ConnDirectionStatistics &&
3330  load_stats_file("stats"PATH_SEPARATOR"conn-stats",
3331  "conn-bi-direct", now, &contents) > 0) {
3332  smartlist_add(chunks, contents);
3333  }
3334  if (options->PaddingStatistics) {
3335  contents = rep_hist_get_padding_count_lines();
3336  if (contents)
3337  smartlist_add(chunks, contents);
3338  }
3339  /* bridge statistics */
3340  if (should_record_bridge_info(options)) {
3341  const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
3342  if (bridge_stats) {
3343  smartlist_add_strdup(chunks, bridge_stats);
3344  }
3345  }
3346  }
3347 }
3348 
3349 /** Add an ed25519 signature of chunks to chunks, using the ed25519 keypair
3350  * signing_keypair.
3351  * Helper for extrainfo_dump_to_string().
3352  * Returns 0 on success, negative on failure. */
3353 static int
3355  smartlist_t *chunks,
3356  const ed25519_keypair_t *signing_keypair)
3357 {
3358  char sha256_digest[DIGEST256_LEN];
3359  ed25519_signature_t ed_sig;
3360  char buf[ED25519_SIG_BASE64_LEN+1];
3361  int rv = -1;
3362 
3363  /* These are two of the three final chunks in the file. If the file is too
3364  * big, other chunks are removed. So we must only add two chunks here. */
3365  smartlist_add_strdup(chunks, "router-sig-ed25519 ");
3366  crypto_digest_smartlist_prefix(sha256_digest, DIGEST256_LEN,
3367  ED_DESC_SIGNATURE_PREFIX,
3368  chunks, "", DIGEST_SHA256);
3369  if (ed25519_sign(&ed_sig, (const uint8_t*)sha256_digest, DIGEST256_LEN,
3370  signing_keypair) < 0)
3371  goto err;
3372  ed25519_signature_to_base64(buf, &ed_sig);
3373 
3374  smartlist_add_asprintf(chunks, "%s\n", buf);
3375 
3376  rv = 0;
3377  goto done;
3378 
3379  err:
3380  rv = -1;
3381 
3382  done:
3383  return rv;
3384 }
3385 
3386 /** Add an RSA signature of extrainfo_string to chunks, using the RSA key
3387  * ident_key.
3388  * Helper for extrainfo_dump_to_string().
3389  * Returns 0 on success, negative on failure. */
3390 static int
3392  crypto_pk_t *ident_key,
3393  const char *extrainfo_string)
3394 {
3395  char sig[DIROBJ_MAX_SIG_LEN+1];
3396  char digest[DIGEST_LEN];
3397  int rv = -1;
3398 
3399  memset(sig, 0, sizeof(sig));
3400  if (router_get_extrainfo_hash(extrainfo_string, strlen(extrainfo_string),
3401  digest) < 0 ||
3402  router_append_dirobj_signature(sig, sizeof(sig), digest, DIGEST_LEN,
3403  ident_key) < 0) {
3404  log_warn(LD_BUG, "Could not append signature to extra-info "
3405  "descriptor.");
3406  goto err;
3407  }
3408  smartlist_add_strdup(chunks, sig);
3409 
3410  rv = 0;
3411  goto done;
3412 
3413  err:
3414  rv = -1;
3415 
3416  done:
3417  return rv;
3418 }
3419 
3420 /** Write the contents of <b>extrainfo</b>, to * *<b>s_out</b>, signing them
3421  * with <b>ident_key</b>.
3422  *
3423  * If ExtraInfoStatistics is 1, also write aggregated statistics and related
3424  * configuration data before signing. Most statistics also have an option that
3425  * enables or disables that particular statistic.
3426  *
3427  * Always write pluggable transport lines.
3428  *
3429  * Return 0 on success, negative on failure. */
3430 int
3431 extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo,
3432  crypto_pk_t *ident_key,
3433  const ed25519_keypair_t *signing_keypair)
3434 {
3435  int result;
3436  static int write_stats_to_extrainfo = 1;
3437  char *s = NULL, *cp, *s_dup = NULL;
3438  smartlist_t *chunks = smartlist_new();
3439  extrainfo_t *ei_tmp = NULL;
3440  const int emit_ed_sigs = signing_keypair &&
3441  extrainfo->cache_info.signing_key_cert;
3442  int rv = 0;
3443 
3444  rv = extrainfo_dump_to_string_header_helper(chunks, extrainfo,
3445  signing_keypair,
3446  emit_ed_sigs);
3447  if (rv < 0)
3448  goto err;
3449 
3450  extrainfo_dump_to_string_stats_helper(chunks, write_stats_to_extrainfo);
3451 
3452  if (emit_ed_sigs) {
3453  rv = extrainfo_dump_to_string_ed_sig_helper(chunks, signing_keypair);
3454  if (rv < 0)
3455  goto err;
3456  }
3457 
3458  /* This is one of the three final chunks in the file. If the file is too big,
3459  * other chunks are removed. So we must only add one chunk here. */
3460  smartlist_add_strdup(chunks, "router-signature\n");
3461  s = smartlist_join_strings(chunks, "", 0, NULL);
3462 
3463  while (strlen(s) > MAX_EXTRAINFO_UPLOAD_SIZE - DIROBJ_MAX_SIG_LEN) {
3464  /* So long as there are at least two chunks (one for the initial
3465  * extra-info line and one for the router-signature), we can keep removing
3466  * things. If emit_ed_sigs is true, we also keep 2 additional chunks at the
3467  * end for the ed25519 signature. */
3468  const int required_chunks = emit_ed_sigs ? 4 : 2;
3469  if (smartlist_len(chunks) > required_chunks) {
3470  /* We remove the next-to-last or 4th-last element (remember, len-1 is the
3471  * last element), since we need to keep the router-signature elements. */
3472  int idx = smartlist_len(chunks) - required_chunks;
3473  char *e = smartlist_get(chunks, idx);
3474  smartlist_del_keeporder(chunks, idx);
3475  log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
3476  "with statistics that exceeds the 50 KB "
3477  "upload limit. Removing last added "
3478  "statistics.");
3479  tor_free(e);
3480  tor_free(s);
3481  s = smartlist_join_strings(chunks, "", 0, NULL);
3482  } else {
3483  log_warn(LD_BUG, "We just generated an extra-info descriptors that "
3484  "exceeds the 50 KB upload limit.");
3485  goto err;
3486  }
3487  }
3488 
3489  rv = extrainfo_dump_to_string_rsa_sig_helper(chunks, ident_key, s);
3490  if (rv < 0)
3491  goto err;
3492 
3493  tor_free(s);
3494  s = smartlist_join_strings(chunks, "", 0, NULL);
3495 
3496  cp = s_dup = tor_strdup(s);
3497  ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL, NULL);
3498  if (!ei_tmp) {
3499  if (write_stats_to_extrainfo) {
3500  log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
3501  "with statistics that we can't parse. Not "
3502  "adding statistics to this or any future "
3503  "extra-info descriptors.");
3504  write_stats_to_extrainfo = 0;
3505  result = extrainfo_dump_to_string(s_out, extrainfo, ident_key,
3506  signing_keypair);
3507  goto done;
3508  } else {
3509  log_warn(LD_BUG, "We just generated an extrainfo descriptor we "
3510  "can't parse.");
3511  goto err;
3512  }
3513  }
3514 
3515  *s_out = s;
3516  s = NULL; /* prevent free */
3517  result = 0;
3518  goto done;
3519 
3520  err:
3521  result = -1;
3522 
3523  done:
3524  tor_free(s);
3525  SMARTLIST_FOREACH(chunks, char *, chunk, tor_free(chunk));
3526  smartlist_free(chunks);
3527  tor_free(s_dup);
3528  extrainfo_free(ei_tmp);
3529 
3530  return result;
3531 }
3532 
3533 /** Forget that we have issued any router-related warnings, so that we'll
3534  * warn again if we see the same errors. */
3535 void
3537 {
3538  if (warned_family) {
3539  SMARTLIST_FOREACH(warned_family, char *, cp, tor_free(cp));
3541  }
3542 }
3543 
3544 /** Release all static resources held in router.c */
3545 void
3547 {
3548  crypto_pk_free(onionkey);
3549  crypto_pk_free(lastonionkey);
3550  crypto_pk_free(server_identitykey);
3551  crypto_pk_free(client_identitykey);
3552 
3553  /* Destroying a locked mutex is undefined behaviour. This mutex may be
3554  * locked, because multiple threads can access it. But we need to destroy
3555  * it, otherwise re-initialisation will trigger undefined behaviour.
3556  * See #31735 for details. */
3558  routerinfo_free(desc_routerinfo);
3559  extrainfo_free(desc_extrainfo);
3560  crypto_pk_free(authority_signing_key);
3561  authority_cert_free(authority_key_certificate);
3562  crypto_pk_free(legacy_signing_key);
3563  authority_cert_free(legacy_key_certificate);
3564 
3567 
3568  if (warned_family) {
3569  SMARTLIST_FOREACH(warned_family, char *, cp, tor_free(cp));
3570  smartlist_free(warned_family);
3571  }
3572 }
3573 
3574 /* From the given RSA key object, convert it to ASN-1 encoded format and set
3575  * the newly allocated object in onion_pkey_out. The length of the key is set
3576  * in onion_pkey_len_out. */
3577 void
3578 router_set_rsa_onion_pkey(const crypto_pk_t *pk, char **onion_pkey_out,
3579  size_t *onion_pkey_len_out)
3580 {
3581  int len;
3582  char buf[1024];
3583 
3584  tor_assert(pk);
3585  tor_assert(onion_pkey_out);
3586  tor_assert(onion_pkey_len_out);
3587 
3588  len = crypto_pk_asn1_encode(pk, buf, sizeof(buf));
3589  if (BUG(len < 0)) {
3590  goto done;
3591  }
3592 
3593  *onion_pkey_out = tor_memdup(buf, len);
3594  *onion_pkey_len_out = len;
3595 
3596  done:
3597  return;
3598 }
3599 
3600 /* From an ASN-1 encoded onion pkey, return a newly allocated RSA key object.
3601  * It is the caller's responsibility to free the returned object.
3602  *
3603  * Return NULL if the pkey is NULL, malformed or if the length is 0. */
3604 crypto_pk_t *
3605 router_get_rsa_onion_pkey(const char *pkey, size_t pkey_len)
3606 {
3607  if (!pkey || pkey_len == 0) {
3608  return NULL;
3609  }
3610  return crypto_pk_asn1_decode(pkey, pkey_len);
3611 }
log_fn
#define log_fn(severity, domain, args,...)
Definition: log.h:283
MAX_UPTIME_BANDWIDTH_CHANGE
#define MAX_UPTIME_BANDWIDTH_CHANGE
Definition: router.c:2572
routerinfo_t::purpose
uint8_t purpose
Definition: routerinfo_st.h:115
crypto_rand_int_range
int crypto_rand_int_range(unsigned int min, unsigned int max)
Definition: crypto_rand_numeric.c:71
selftest.h
Header file for selftest.c.
routermode.h
Header file for routermode.c.
control_event_my_descriptor_changed
int control_event_my_descriptor_changed(void)
Definition: control_events.c:1679
net_is_disabled
int net_is_disabled(void)
Definition: netstatus.c:25
extrainfo_dump_to_string
int extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo, crypto_pk_t *ident_key, const ed25519_keypair_t *signing_keypair)
Definition: router.c:3431
tor_free
#define tor_free(p)
Definition: malloc.h:52
router_update_routerinfo_from_extrainfo
STATIC void router_update_routerinfo_from_extrainfo(routerinfo_t *ri, const extrainfo_t *ei)
Definition: router.c:2296
routerinfo_t
Definition: routerinfo_st.h:20
tor_cert_t::encoded_len
size_t encoded_len
Definition: torcert.h:42
dir_server_st.h
Trusted/fallback directory server structure.
CURVE25519_PUBKEY_LEN
#define CURVE25519_PUBKEY_LEN
Definition: x25519_sizes.h:20
get_short_version
const char * get_short_version(void)
Definition: version.c:56
or_state_t
Definition: or_state_st.h:21
extrainfo_t::nickname
char nickname[MAX_NICKNAME_LEN+1]
Definition: extrainfo_st.h:23
smartlist_split_string
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)
Definition: smartlist_split.c:37
tor_addr_family
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition: address.h:187
assert_identity_keys_ok
static void assert_identity_keys_ok(void)
Definition: router.c:364
or_state_mark_dirty
void or_state_mark_dirty(or_state_t *state, time_t when)
Definition: statefile.c:784
router_get_my_descriptor
const char * router_get_my_descriptor(void)
Definition: router.c:1799
routerinfo_err_to_string
const char * routerinfo_err_to_string(int err)
Definition: router.c:145
router_has_bandwidth_to_be_dirserver
int router_has_bandwidth_to_be_dirserver(const or_options_t *options)
Definition: router.c:1203
tor_addr_make_null
void tor_addr_make_null(tor_addr_t *a, sa_family_t family)
Definition: address.c:235
or_options_t::BandwidthRate
uint64_t BandwidthRate
Definition: or_options_st.h:416
or_options_t::IPv6Exit
int IPv6Exit
Definition: or_options_st.h:935
name
const char * name
Definition: config.c:2463
routerstatus_t::is_staledesc
unsigned int is_staledesc
Definition: routerstatus_st.h:59
tor_cert_t
Definition: torcert.h:30
memwipe
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:55
routerinfo_t::bandwidthcapacity
uint32_t bandwidthcapacity
Definition: routerinfo_st.h:58
tor_addr_t
Definition: address.h:69
ED25519_BASE64_LEN
#define ED25519_BASE64_LEN
Definition: x25519_sizes.h:43
get_onion_key_grace_period
int get_onion_key_grace_period(void)
Definition: router.c:787
compare_tor_addr_to_addr_policy
addr_policy_result_t compare_tor_addr_to_addr_policy(const tor_addr_t *addr, uint16_t port, const smartlist_t *policy)
Definition: policies.c:1516
publish_even_when_ipv4_orport_unreachable
static bool publish_even_when_ipv4_orport_unreachable
Definition: router.c:1358
protover.h
Headers and type declarations for protover.c.
smartlist_add_strdup
void smartlist_add_strdup(struct smartlist_t *sl, const char *string)
Definition: smartlist_core.c:137
init_v3_authority_keys
static int init_v3_authority_keys(void)
Definition: router.c:697
CMD_RUN_TOR
@ CMD_RUN_TOR
Definition: tor_cmdline_mode.h:20
extrainfo_t
Definition: extrainfo_st.h:18
LOG_NOTICE
#define LOG_NOTICE
Definition: log.h:50
or_options_t::BridgeRelay
int BridgeRelay
Definition: or_options_st.h:271
router_get_descriptor_gen_reason
const char * router_get_descriptor_gen_reason(void)
Definition: router.c:1828
MOCK_IMPL
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
tor_addr_to_str
const char * tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
Definition: address.c:328
BASE64_DIGEST256_LEN
#define BASE64_DIGEST256_LEN
Definition: crypto_digest.h:29
authcert_parse.h
Header file for authcert_parse.c.
router_get_active_listener_port_by_type_af
uint16_t router_get_active_listener_port_by_type_af(int listener_type, sa_family_t family)
Definition: router.c:1444
policy_dump_to_string
char * policy_dump_to_string(const smartlist_t *policy_list, int include_ipv4, int include_ipv6)
Definition: policies.c:2925
or_options_t::DirReqStatistics
int DirReqStatistics
Definition: or_options_st.h:652
or_options_t::ConnDirectionStatistics
int ConnDirectionStatistics
Definition: or_options_st.h:658
accounting_get_interval_length
int accounting_get_interval_length(void)
Definition: hibernate.c:315
port_cfg_st.h
Listener port configuration structure.
netstatus.h
Header for netstatus.c.
ed25519_sign
int ed25519_sign(ed25519_signature_t *signature_out, const uint8_t *msg, size_t len, const ed25519_keypair_t *keypair)
Definition: crypto_ed25519.c:271
tor_assert
#define tor_assert(expr)
Definition: util_bug.h:102
mark_my_descriptor_if_omit_ipv6_changes
void mark_my_descriptor_if_omit_ipv6_changes(const char *reason, bool omit_ipv6)
Definition: router.c:2487
routerkeys.h
Header for routerkeys.c.
MIN_BW_TO_ADVERTISE_DIRSERVER
#define MIN_BW_TO_ADVERTISE_DIRSERVER
Definition: router.c:1197
relay_find_addr.h
Header file for relay_find_addr.c.
crypto_pk_new
crypto_pk_t * crypto_pk_new(void)
Definition: crypto_rsa_nss.c:165
DEFAULT_ONION_KEY_GRACE_PERIOD_DAYS
#define DEFAULT_ONION_KEY_GRACE_PERIOD_DAYS
Definition: or.h:147
LD_BUG
#define LD_BUG
Definition: log.h:86
ed25519_pubkey_eq
int ed25519_pubkey_eq(const ed25519_public_key_t *key1, const ed25519_public_key_t *key2)
Definition: crypto_ed25519.c:642
router.h
Header file for router.c.
authcert.h
Header file for authcert.c.
routerinfo_t::ipv6_exit_policy
struct short_policy_t * ipv6_exit_policy
Definition: routerinfo_st.h:63
or_options_t::PublishServerDescriptor_
dirinfo_type_t PublishServerDescriptor_
Definition: or_options_st.h:306
format_iso_time
void format_iso_time(char *buf, time_t t)
Definition: time_fmt.c:295
fast_mem_is_zero
int fast_mem_is_zero(const char *mem, size_t len)
Definition: util_string.c:74
router_digest_is_me
int router_digest_is_me(const char *digest)
Definition: router.c:1701
bwhist.h
Header for feature/stats/bwhist.c.
publish_even_when_ipv6_orport_unreachable
static bool publish_even_when_ipv6_orport_unreachable
Definition: router.c:1363
CURVE25519_BASE64_PADDED_LEN
#define CURVE25519_BASE64_PADDED_LEN
Definition: x25519_sizes.h:37
LD_GENERAL
#define LD_GENERAL
Definition: log.h:62
desc_dirty_reason
STATIC const char * desc_dirty_reason
Definition: router.c:1599
set_client_identity_key
void set_client_identity_key(crypto_pk_t *k)
Definition: router.c:410
dup_onion_keys
void dup_onion_keys(crypto_pk_t **key, crypto_pk_t **last)
Definition: router.c:216
base16_encode
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:478
router_compare_to_my_exit_policy
int router_compare_to_my_exit_policy(const tor_addr_t *addr, uint16_t port)
Definition: router.c:1654
routerinfo_t::identity_pkey
crypto_pk_t * identity_pkey
Definition: routerinfo_st.h:41
geoip_is_loaded
int geoip_is_loaded(sa_family_t family)
Definition: geoip.c:458
router_get_my_routerinfo
const routerinfo_t * router_get_my_routerinfo(void)
Definition: router.c:1763
reschedule_descriptor_update_check
void reschedule_descriptor_update_check(void)
Definition: relay_periodic.c:358
loadkey.h
Header file for loadkey.c.
crypto_pk_dup_key
crypto_pk_t * crypto_pk_dup_key(crypto_pk_t *orig)
Definition: crypto_rsa_nss.c:351
extrainfo_t::digest256
uint8_t digest256[DIGEST256_LEN]
Definition: extrainfo_st.h:21
dir_server_t::v3_identity_digest
char v3_identity_digest[DIGEST_LEN]
Definition: dir_server_st.h:34
make_tap_onion_key_crosscert
uint8_t * make_tap_onion_key_crosscert(const crypto_pk_t *onion_key, const ed25519_public_key_t *master_id_key, const crypto_pk_t *rsa_id_key, int *len_out)
Definition: routerkeys.c:712
get_my_v3_authority_cert
authority_cert_t * get_my_v3_authority_cert(void)
Definition: router.c:437
crypto_pk_asn1_encode
int crypto_pk_asn1_encode(const crypto_pk_t *pk, char *dest, size_t dest_len)
Definition: crypto_rsa_nss.c:595
smartlist_del_keeporder
void smartlist_del_keeporder(smartlist_t *sl, int idx)
Definition: smartlist_core.c:228
node_get_by_nickname
const node_t * node_get_by_nickname(const char *nickname, unsigned flags)
Definition: nodelist.c:1004
process_descs.h
Header file for process_descs.c.
router_get_extrainfo_hash
int router_get_extrainfo_hash(const char *s, size_t s_len, char *digest)
Definition: routerparse.c:190
MAX_BANDWIDTH_CHANGE_FREQ
#define MAX_BANDWIDTH_CHANGE_FREQ
Definition: router.c:2568
onionkey_set_at
static time_t onionkey_set_at
Definition: router.c:103
networkstatus_get_live_consensus
networkstatus_t * networkstatus_get_live_consensus(time_t now)
Definition: networkstatus.c:1416
get_onion_key_lifetime
int get_onion_key_lifetime(void)
Definition: router.c:777
smartlist_add
void smartlist_add(smartlist_t *sl, void *element)
Definition: smartlist_core.c:117
replace_file
int replace_file(const char *from, const char *to)
Definition: files.c:117
crypto_pk_eq_keys
int crypto_pk_eq_keys(const crypto_pk_t *a, const crypto_pk_t *b)
Definition: crypto_rsa.c:71
tor_cert_dup
tor_cert_t * tor_cert_dup(const tor_cert_t *cert)
Definition: torcert.c:294
uname.h
Header for uname.c.
routerconf_has_ipv6_orport
bool routerconf_has_ipv6_orport(const or_options_t *options)
Definition: router.c:1525
routerstatus_t
Definition: routerstatus_st.h:19
lastonionkey
static crypto_pk_t * lastonionkey
Definition: router.c:108
or_options_t::command
tor_cmdline_mode_t command
Definition: or_options_st.h:68
router_rebuild_descriptor
int router_rebuild_descriptor(int force)
Definition: router.c:2420
portconf_get_first_advertised_addr
const tor_addr_t * portconf_get_first_advertised_addr(int listener_type, int address_family)
Definition: config.c:6705
CFG_AUTO_PORT
#define CFG_AUTO_PORT
Definition: or.h:1008
we_are_hibernating
int we_are_hibernating(void)
Definition: hibernate.c:937
authority_cert_t::expires
time_t expires
Definition: authority_cert_st.h:29
crypto_init.h
Headers for crypto_init.c.
relay_find_addr_to_publish
bool relay_find_addr_to_publish(const or_options_t *options, int family, int flags, tor_addr_t *addr_out)
Definition: relay_find_addr.c:107
router_dump_and_sign_routerinfo_descriptor_body
STATIC int router_dump_and_sign_routerinfo_descriptor_body(routerinfo_t *ri)
Definition: router.c:2324
TOR_ADDR_BUF_LEN
#define TOR_ADDR_BUF_LEN
Definition: address.h:224
find_my_address
bool find_my_address(const or_options_t *options, int family, int warn_severity, tor_addr_t *addr_out, resolved_addr_method_t *method_out, char **hostname_out)
Attempt to find our IP address that can be used as our external reachable address.
Definition: resolve_addr.c:695
ntor_key_map_free_helper
static void ntor_key_map_free_helper(void *arg)
Definition: router.c:312
or_options_t::SSLKeyLifetime
int SSLKeyLifetime
Definition: or_options_st.h:942
smartlist_new
smartlist_t * smartlist_new(void)
Definition: smartlist_core.c:26
crypto_pk_asn1_decode
crypto_pk_t * crypto_pk_asn1_decode(const char *str, size_t len)
Definition: crypto_rsa_nss.c:619
nodefamily_format
char * nodefamily_format(const nodefamily_t *family)
Definition: nodefamily.c:374
base64_encode
int base64_encode(char *dest, size_t destlen, const char *src, size_t srclen, int flags)
Definition: binascii.c:215
tor_cert_t::encoded
uint8_t * encoded
Definition: torcert.h:40
dimap_add_entry
void dimap_add_entry(di_digest256_map_t **map, const uint8_t *key, void *val)
Definition: di_ops.c:176
routerinfo_t::onion_pkey_len
size_t onion_pkey_len
Definition: routerinfo_st.h:39
trusted_dir_server_new
dir_server_t * trusted_dir_server_new(const char *nickname, const char *address, uint16_t ipv4_dirport, uint16_t ipv4_orport, const tor_addr_port_t *ipv6_addrport, const char *digest, const char *v3_auth_digest, dirinfo_type_t type, double weight)
Definition: dirlist.c:366
tor_snprintf
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
routerinfo_t::ipv6_addr
tor_addr_t ipv6_addr
Definition: routerinfo_st.h:30
load_authority_keyset
static int load_authority_keyset(int legacy, crypto_pk_t **key_out, authority_cert_t **cert_out)
Definition: router.c:640
statefile.h
Header for statefile.c.
parse_iso_time
int parse_iso_time(const char *cp, time_t *t)
Definition: time_fmt.c:392
ed25519_public_to_base64
void ed25519_public_to_base64(char *output, const ed25519_public_key_t *pkey)
Definition: crypto_format.c:227
SMARTLIST_FOREACH
#define SMARTLIST_FOREACH(sl, type, var, cmd)
Definition: smartlist_foreach.h:112
get_or_state
or_state_t * get_or_state(void)
Definition: statefile.c:220
init_keys
int init_keys(void)
Definition: router.c:931
crypto_rand_int
int crypto_rand_int(unsigned int max)
Definition: crypto_rand_numeric.c:52
router_extrainfo_digest_is_me
int router_extrainfo_digest_is_me(const char *digest)
Definition: router.c:1717
routerinfo_t::platform
char * platform
Definition: routerinfo_st.h:48
or_options_t::ExtraInfoStatistics
int ExtraInfoStatistics
Definition: or_options_st.h:678
router_get_trusteddirserver_by_digest
dir_server_t * router_get_trusteddirserver_by_digest(const char *digest)
Definition: dirlist.c:144
MAX_ONION_KEY_LIFETIME_DAYS
#define MAX_ONION_KEY_LIFETIME_DAYS
Definition: or.h:136
resolved_addr_method_t
resolved_addr_method_t
Definition: resolve_addr.h:19
or_options_t::MyFamily
struct config_line_t * MyFamily
Definition: or_options_st.h:490
networkstatus.h
Header file for networkstatus.c.
CONN_TYPE_OR_LISTENER
#define CONN_TYPE_OR_LISTENER
Definition: connection.h:41
networkstatus_vote_find_entry
const routerstatus_t * networkstatus_vote_find_entry(networkstatus_t *ns, const char *digest)
Definition: networkstatus.c:725
geoip_stats.h
Header file for geoip_stats.c.
extrainfo_dump_to_string_rsa_sig_helper
static int extrainfo_dump_to_string_rsa_sig_helper(smartlist_t *chunks, crypto_pk_t *ident_key, const char *extrainfo_string)
Definition: router.c:3391
digest256_to_base64
void digest256_to_base64(char *d64, const char *digest)
Definition: crypto_format.c:304
signed_descriptor_t::identity_digest
char identity_digest[DIGEST_LEN]
Definition: signed_descriptor_st.h:31
load_stats_file
static int load_stats_file(const char *filename, const char *end_line, time_t now, char **out)
Definition: router.c:3150
tor_memeq
int tor_memeq(const void *a, const void *b, size_t sz)
Definition: di_ops.c:107
router_build_fresh_descriptor
int router_build_fresh_descriptor(routerinfo_t **r, extrainfo_t **e)
Definition: router.c:2358
get_my_declared_family
STATIC smartlist_t * get_my_declared_family(const or_options_t *options)
Definition: router.c:1923
dirlist.h
Header file for dirlist.c.
crypto_util.h
Common functions for cryptographic routines.
base16_decode
int base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:506
hibernate.h
Header file for hibernate.c.
routerinfo_t::bandwidthburst
uint32_t bandwidthburst
Definition: routerinfo_st.h:56
compare_tor_addr_to_short_policy
addr_policy_result_t compare_tor_addr_to_short_policy(const tor_addr_t *addr, uint16_t port, const short_policy_t *policy)
Definition: policies.c:2822
router_upload_dir_desc_to_dirservers
void router_upload_dir_desc_to_dirservers(int force)
Definition: router.c:1608
should_record_bridge_info
int should_record_bridge_info(const or_options_t *options)
Definition: geoip_stats.c:112
routerinfo_t::protocol_list
char * protocol_list
Definition: routerinfo_st.h:50
protover_get_supported_protocols
const char * protover_get_supported_protocols(void)
C_RUST_COUPLED: src/rust/protover/protover.rs SUPPORTED_PROTOCOLS
Definition: protover.c:391
mainloop.h
Header file for mainloop.c.
routerconf_find_dir_port
uint16_t routerconf_find_dir_port(const or_options_t *options, uint16_t dirport)
Definition: router.c:1569
curve25519_keypair_read_from_file
int curve25519_keypair_read_from_file(curve25519_keypair_t *keypair_out, char **tag_out, const char *fname)
Definition: crypto_curve25519.c:233
DIGEST_LEN
#define DIGEST_LEN
Definition: digest_sizes.h:20
get_uname
const char * get_uname(void)
Definition: uname.c:67
make_ntor_onion_key_crosscert
tor_cert_t * make_ntor_onion_key_crosscert(const curve25519_keypair_t *onion_key, const ed25519_public_key_t *master_id_key, time_t now, time_t lifetime, int *sign_out)
Definition: routerkeys.c:689
router_my_exit_policy_is_reject_star
int router_my_exit_policy_is_reject_star(void)
Definition: router.c:1689
ROUTER_PURPOSE_BRIDGE
#define ROUTER_PURPOSE_BRIDGE
Definition: routerinfo_st.h:106
signed_descriptor_t::extra_info_digest256
char extra_info_digest256[DIGEST256_LEN]
Definition: signed_descriptor_st.h:37
or_options_t::BridgeAuthoritativeDir
int BridgeAuthoritativeDir
Definition: or_options_st.h:242
directory_permits_begindir_requests
int directory_permits_begindir_requests(const or_options_t *options)
Definition: dirserv.c:110
crypto_pk_write_private_key_to_filename
int crypto_pk_write_private_key_to_filename(crypto_pk_t *env, const char *fname)
Definition: crypto_rsa.c:610
accounting_is_enabled
int accounting_is_enabled(const or_options_t *options)
Definition: hibernate.c:305
router_parse_entry_from_string
routerinfo_t * router_parse_entry_from_string(const char *s, const char *end, int cache_copy, int allow_annotations, const char *prepend_annotations, int *can_dl_again_out)
Definition: routerparse.c:394
generate_ed_link_cert
int generate_ed_link_cert(const or_options_t *options, time_t now, int force)
Definition: routerkeys.c:365
log_addr_has_changed
void log_addr_has_changed(int severity, const tor_addr_t *prev, const tor_addr_t *cur, const char *source)
Definition: router.c:2622
signed_descriptor_get_body
const char * signed_descriptor_get_body(const signed_descriptor_t *desc)
Definition: routerlist.c:880
crypto_format.h
Header for crypto_format.c.
check_descriptor_bandwidth_changed
void check_descriptor_bandwidth_changed(time_t now)
Definition: router.c:2581
router_build_fresh_signed_extrainfo
STATIC extrainfo_t * router_build_fresh_signed_extrainfo(const routerinfo_t *ri)
Definition: router.c:2264
get_onion_key_rotation_days_
static int get_onion_key_rotation_days_(void)
Definition: router.c:763
set_onion_key
static void set_onion_key(crypto_pk_t *k)
Definition: router.c:188
signed_descriptor_t::saved_location
saved_location_t saved_location
Definition: signed_descriptor_st.h:44
geoip.h
Header file for geoip.c.
tor_mutex_t
Definition: compat_mutex.h:40
server_identitykey
static crypto_pk_t * server_identitykey
Definition: router.c:116
routerinfo_t::ipv4_addr
tor_addr_t ipv4_addr
Definition: routerinfo_st.h:25
tortls.h
Headers for tortls.c.
LD_FS
#define LD_FS
Definition: log.h:70
relay_get_effective_bwburst
uint32_t relay_get_effective_bwburst(const or_options_t *options)
Definition: relay_config.c:106
tor_addr_port_t
Definition: address.h:81
BANDWIDTH_CHANGE_FACTOR
#define BANDWIDTH_CHANGE_FACTOR
Definition: router.c:2575
tor_memneq
#define tor_memneq(a, b, sz)
Definition: di_ops.h:21
get_my_v3_legacy_cert
authority_cert_t * get_my_v3_legacy_cert(void)
Definition: router.c:454
relay_config.h
Header for feature/relay/relay_config.c.
log_new_relay_greeting
static void log_new_relay_greeting(void)
Definition: router.c:546
MICRODESC_DIRINFO
@ MICRODESC_DIRINFO
Definition: or.h:914
MIN_ONION_KEY_GRACE_PERIOD_DAYS
#define MIN_ONION_KEY_GRACE_PERIOD_DAYS
Definition: or.h:144
legacy_key_certificate
static authority_cert_t * legacy_key_certificate
Definition: router.c:134
set_server_identity_key
void set_server_identity_key(crypto_pk_t *k)
Definition: router.c:340
node_t
Definition: node_st.h:34
LD_OR
#define LD_OR
Definition: log.h:92
get_my_v3_authority_signing_key
crypto_pk_t * get_my_v3_authority_signing_key(void)
Definition: router.c:445
trusted_dirs_load_certs_from_string
int trusted_dirs_load_certs_from_string(const char *contents, int source, int flush, const char *source_dir)
Definition: authcert.c:373
get_onion_key_set_at
time_t get_onion_key_set_at(void)
Definition: router.c:332
torcert.h
Header for torcert.c.
construct_ntor_key_map
di_digest256_map_t * construct_ntor_key_map(void)
Definition: router.c:288
MIN_ONION_KEY_LIFETIME_DAYS
#define MIN_ONION_KEY_LIFETIME_DAYS
Definition: or.h:133
directory.h
Header file for directory.c.
warned_family
static smartlist_t * warned_family
Definition: router.c:1915
crypto_pk_get_digest
int crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
Definition: crypto_rsa.c:356
routerstatus_t::published_on
time_t published_on
Definition: routerstatus_st.h:24
omit_ipv6_on_publish
static bool omit_ipv6_on_publish
Definition: router.c:2480
tor_digest_is_zero
int tor_digest_is_zero(const char *digest)
Definition: util_string.c:96
routerinfo_t::policy_is_reject_star
unsigned int policy_is_reject_star
Definition: routerinfo_st.h:77
authority_signing_key
static crypto_pk_t * authority_signing_key
Definition: router.c:124
init_curve25519_keypair_from_file
static int init_curve25519_keypair_from_file(curve25519_keypair_t *keys_out, const char *fname, int generate, int severity, const char *tag)
Definition: router.c:568
authority_cert_st.h
Authority certificate structure.
ntor_key_map_free_
void ntor_key_map_free_(di_digest256_map_t *map)
Definition: router.c:320
legacy_signing_key
static crypto_pk_t * legacy_signing_key
Definition: router.c:131
router_build_fresh_unsigned_extrainfo
static extrainfo_t * router_build_fresh_unsigned_extrainfo(const routerinfo_t *ri)
Definition: router.c:2192
router_get_router_hash
int router_get_router_hash(const char *s, size_t s_len, char *digest)
Definition: routerparse.c:180
signed_descriptor_t::signed_descriptor_digest
char signed_descriptor_digest[DIGEST_LEN]
Definition: signed_descriptor_st.h:29
or_options_t::EntryStatistics
int EntryStatistics
Definition: or_options_st.h:667
or_options_t::ServerTransportPlugin
struct config_line_t * ServerTransportPlugin
Definition: or_options_st.h:262
escaped
const char * escaped(const char *s)
Definition: escape.c:126
tor_unlink
int tor_unlink(const char *pathname)
Definition: files.c:154
dns_seems_to_be_broken
int dns_seems_to_be_broken(void)
Definition: dns.c:2043
extrainfo_dump_to_string_stats_helper
static void extrainfo_dump_to_string_stats_helper(smartlist_t *chunks, int write_stats_to_extrainfo)
Definition: router.c:3265
router_new_consensus_params
void router_new_consensus_params(const networkstatus_t *ns)
Definition: router.c:2454
nodefamily_t
Definition: nodefamily_st.h:18
routerinfo_t::exit_policy
smartlist_t * exit_policy
Definition: routerinfo_st.h:59
should_refuse_unknown_exits
int should_refuse_unknown_exits(const or_options_t *options)
Definition: router.c:1345
authmode.h
Header file for directory authority mode.
get_connection_array
smartlist_t * get_connection_array(void)
Definition: mainloop.c:453
curve25519_keypair_generate
int curve25519_keypair_generate(curve25519_keypair_t *keypair_out, int extra_strong)
Definition: crypto_curve25519.c:190
get_onion_key
crypto_pk_t * get_onion_key(void)
Definition: router.c:205
curve25519_onion_key
static curve25519_keypair_t curve25519_onion_key
Definition: router.c:110
ed25519_signature_to_base64
void ed25519_signature_to_base64(char *output, const ed25519_signature_t *sig)
Definition: crypto_format.c:239
routerconf_find_ipv6_or_ap
void routerconf_find_ipv6_or_ap(const or_options_t *options, tor_addr_port_t *ipv6_ap_out)
Definition: router.c:1484
nodelist.h
Header file for nodelist.c.
or_options_t::HiddenServiceStatistics
int HiddenServiceStatistics
Definition: or_options_st.h:675
router_dump_router_to_string
char * router_dump_router_to_string(routerinfo_t *router, const crypto_pk_t *ident_key, const crypto_pk_t *tap_key, const curve25519_keypair_t *ntor_keypair, const ed25519_keypair_t *signing_keypair)
Definition: router.c:2744
WRA_WAS_OUTDATED
static int WRA_WAS_OUTDATED(was_router_added_t s)
Definition: routerlist.h:116
routerlist.h
Header file for routerlist.c.
routerinfo_t::supports_tunnelled_dir_requests
unsigned int supports_tunnelled_dir_requests
Definition: routerinfo_st.h:86
di_digest256_map_t
Definition: di_ops.c:147
or_options_t::DownloadExtraInfo
int DownloadExtraInfo
Definition: or_options_st.h:645
routerinfo_t::declared_family
smartlist_t * declared_family
Definition: routerinfo_st.h:65
policy_summarize
char * policy_summarize(smartlist_t *policy, sa_family_t family)
Definition: policies.c:2573
smartlist_contains_string
int smartlist_contains_string(const smartlist_t *sl, const char *element)
Definition: smartlist.c:93
routerinfo_st.h
Router descriptor structure.
or_options_t::V3AuthoritativeDir
int V3AuthoritativeDir
Definition: or_options_st.h:240
ADDR_POLICY_ACCEPTED
@ ADDR_POLICY_ACCEPTED
Definition: policies.h:40
try_locking
int try_locking(const or_options_t *options, int err_if_locked)
Definition: main.c:671
LD_CONFIG
#define LD_CONFIG
Definition: log.h:68
DIGEST256_LEN
#define DIGEST256_LEN
Definition: digest_sizes.h:23
dir_server_t
Definition: dir_server_st.h:21
tor_addr_to_str_dup
char * tor_addr_to_str_dup(const tor_addr_t *addr)
Definition: address.c:1164
router_dump_and_sign_extrainfo_descriptor_body
static int router_dump_and_sign_extrainfo_descriptor_body(extrainfo_t *ei)
Definition: router.c:2231
policies_exit_policy_append_reject_star
void policies_exit_policy_append_reject_star(smartlist_t **dest)
Definition: policies.c:2166
crypto_pk_get_hashed_fingerprint
int crypto_pk_get_hashed_fingerprint(crypto_pk_t *pk, char *fp_out)
Definition: crypto_rsa.c:254
set_server_advertised
void set_server_advertised(int s)
Definition: routermode.c:65
file_status
file_status_t file_status(const char *filename)
Definition: files.c:212
DIR_PURPOSE_UPLOAD_DIR
#define DIR_PURPOSE_UPLOAD_DIR
Definition: directory.h:44
authority_cert_t
Definition: authority_cert_st.h:19
command
tor_cmdline_mode_t command
Definition: config.c:2467
EXTRAINFO_DIRINFO
@ EXTRAINFO_DIRINFO
Definition: or.h:912
nodefamily.h
Header file for nodefamily.c.
WRA_WAS_ADDED
static int WRA_WAS_ADDED(was_router_added_t s)
Definition: routerlist.h:106
write_str_to_file_if_not_equal
int write_str_to_file_if_not_equal(const char *fname, const char *str)
Definition: files.c:743
connection_t
Definition: connection_st.h:45
or_options_t::RefuseUnknownExits
int RefuseUnknownExits
Definition: or_options_st.h:366
transports.h
Headers for transports.c.
dirserv_load_fingerprint_file
int dirserv_load_fingerprint_file(void)
Definition: process_descs.c:187
ARRAY_LENGTH
#define ARRAY_LENGTH(x)
Definition: compat_compiler.h:222
router_build_fresh_unsigned_routerinfo
STATIC int router_build_fresh_unsigned_routerinfo(routerinfo_t **ri_out)
Definition: router.c:2048
LOG_INFO
#define LOG_INFO
Definition: log.h:45
crypto_rand.h
Common functions for using (pseudo-)random number generators.
tor_mutex_new
tor_mutex_t * tor_mutex_new(void)
Definition: compat_mutex.c:17
DEFAULT_ONION_KEY_LIFETIME_DAYS
#define DEFAULT_ONION_KEY_LIFETIME_DAYS
Definition: or.h:139
control_events.h
Header file for control_events.c.
get_options
const or_options_t * get_options(void)
Definition: config.c:932
or_state_st.h
The or_state_t structure, which represents Tor's state file.
key_lock
static tor_mutex_t * key_lock
Definition: router.c:102
dirserv_add_descriptor
was_router_added_t dirserv_add_descriptor(routerinfo_t *ri, const char **msg, const char *source)
Definition: process_descs.c:741
has_dns_init_failed
int has_dns_init_failed(void)
Definition: dns.c:266
routerinfo_incompatible_with_extrainfo
int routerinfo_incompatible_with_extrainfo(const crypto_pk_t *identity_pkey, extrainfo_t *ei, signed_descriptor_t *sd, const char **msg)
Definition: routerlist.c:3018
get_current_curve25519_keypair
STATIC const struct curve25519_keypair_t * get_current_curve25519_keypair(void)
Definition: router.c:280
fmt_addrport
const char * fmt_addrport(const tor_addr_t *addr, uint16_t port)
Definition: address.c:1199
routerinfo_t::onion_pkey
char * onion_pkey
Definition: routerinfo_st.h:37
write_short_policy
char * write_short_policy(const short_policy_t *policy)
Definition: policies.c:2786
relay_periodic.h
Header for feature/relay/relay_periodic.c.
router_get_my_routerinfo_with_err
const routerinfo_t * router_get_my_routerinfo_with_err(int *err)
Definition: router.c:1773
smartlist_clear
void smartlist_clear(smartlist_t *sl)
Definition: smartlist_core.c:50
nodefamily_from_members
nodefamily_t * nodefamily_from_members(const smartlist_t *members, const uint8_t *rsa_id_self, unsigned flags, smartlist_t *unrecognized_out)
Definition: nodefamily.c:159
parse_short_policy
short_policy_t * parse_short_policy(const char *summary)
Definition: policies.c:2685
resolve_addr.h
Header file for resolve_addr.c.
routerstatus_st.h
Routerstatus (consensus entry) structure.
get_platform_str
STATIC void get_platform_str(char *platform, size_t len)
Definition: router.c:2723
signing.h
Header file for signing.c.
curve25519_public_key_t
Definition: crypto_curve25519.h:24
authority_cert_t::cache_info
signed_descriptor_t cache_info
Definition: authority_cert_st.h:21
FAST_RETRY_DESCRIPTOR_INTERVAL
#define FAST_RETRY_DESCRIPTOR_INTERVAL
Definition: router.c:2504
get_tlsclient_identity_key
crypto_pk_t * get_tlsclient_identity_key(void)
Definition: router.c:420
tor_digest256_is_zero
int tor_digest256_is_zero(const char *digest)
Definition: util_string.c:103
signed_descriptor_t::signing_key_cert
struct tor_cert_st * signing_key_cert
Definition: signed_descriptor_st.h:39
router_dump_exit_policy_to_string
char * router_dump_exit_policy_to_string(const routerinfo_t *router, int include_ipv4, int include_ipv6)
Definition: router.c:3129
is_legal_nickname_or_hexdigest
int is_legal_nickname_or_hexdigest(const char *s)
Definition: nickname.c:31
IF_BUG_ONCE
#define IF_BUG_ONCE(cond)
Definition: util_bug.h:246
authority_cert_parse_from_string
authority_cert_t * authority_cert_parse_from_string(const char *s, size_t maxlen, const char **end_of_string)
Definition: authcert_parse.c:35
MAX_EXTRAINFO_UPLOAD_SIZE
#define MAX_EXTRAINFO_UPLOAD_SIZE
Definition: or.h:130
tor_mutex_free
#define tor_mutex_free(m)
Definition: compat_mutex.h:66
connection.h
Header file for connection.c.
client_identity_key_is_set
int client_identity_key_is_set(void)
Definition: router.c:429
client_identitykey
static crypto_pk_t * client_identitykey
Definition: router.c:122
ed25519_signature_t
Definition: crypto_ed25519.h:18
geoip_get_bridge_stats_extrainfo
const char * geoip_get_bridge_stats_extrainfo(time_t)
Definition: geoip_stats.c:1300
confline.h
Header for confline.c.
or_options_t::ExitPortStatistics
int ExitPortStatistics
Definition: or_options_st.h:655
onionkey
static crypto_pk_t * onionkey
Definition: router.c:105
policies_parse_exit_policy_from_options
int policies_parse_exit_policy_from_options(const or_options_t *or_options, const tor_addr_t *ipv4_local_address, const tor_addr_t *ipv6_local_address, smartlist_t **result)
Definition: policies.c:2103
extrainfo_st.h
A relay's extra-info structure.
V3_DIRINFO
@ V3_DIRINFO
Definition: or.h:908
or_options_t::RelayBandwidthRate
uint64_t RelayBandwidthRate
Definition: or_options_st.h:422
or_options_t::ClientOnly
int ClientOnly
Definition: or_options_st.h:281
router_should_be_dirserver
static int router_should_be_dirserver(const or_options_t *options, int dir_port)
Definition: router.c:1223
tor_strlower
void tor_strlower(char *s)
Definition: util_string.c:127
networkstatus_t::valid_after
time_t valid_after
Definition: networkstatus_st.h:33
nickname.h
Header file for nickname.c.
decide_if_publishable_server
static int decide_if_publishable_server(void)
Definition: router.c:1379
dirserv.h
Header file for dirserv.c.
ip_address_changed
void ip_address_changed(int on_client_conn)
Definition: mainloop.c:2287
server_mode
int server_mode(const or_options_t *options)
Definition: routermode.c:34
tor_addr_is_null
int tor_addr_is_null(const tor_addr_t *addr)
Definition: address.c:780
crypto_pk_get_fingerprint
int crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
Definition: crypto_rsa.c:229
dirinfo_type_t
dirinfo_type_t
Definition: or.h:905
dirclient.h
Header file for dirclient.c.
main.h
Header file for main.c.
or_state_t::LastRotatedOnionKey
time_t LastRotatedOnionKey
Definition: or_state_st.h:92
dir_server_t::type
dirinfo_type_t type
Definition: dir_server_st.h:46
dirserv_add_own_fingerprint
int dirserv_add_own_fingerprint(crypto_pk_t *pk, const ed25519_public_key_t *edkey)
Definition: process_descs.c:161
extrainfo_dump_to_string_header_helper
static int extrainfo_dump_to_string_header_helper(smartlist_t *chunks, const extrainfo_t *extrainfo, const ed25519_keypair_t *signing_keypair, int emit_ed_sigs)
Definition: router.c:3201
tor_asprintf
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
or_options_t::PaddingStatistics
int PaddingStatistics
Definition: or_options_st.h:664
SMARTLIST_FOREACH_BEGIN
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
Definition: smartlist_foreach.h:78
crypto_pk_t
Definition: crypto_rsa_nss.c:37
ED25519_SIG_BASE64_LEN
#define ED25519_SIG_BASE64_LEN
Definition: x25519_sizes.h:45
or_options_t::ContactInfo
char * ContactInfo
Definition: or_options_st.h:436
v3_authority_check_key_expiry
void v3_authority_check_key_expiry(void)
Definition: router.c:714
router_dirport_seems_reachable
int router_dirport_seems_reachable(const or_options_t *options)
Definition: selftest.c:148
authority_key_certificate
static authority_cert_t * authority_key_certificate
Definition: router.c:127
dir_connection_st.h
Client/server directory connection structure.
public_server_mode
int public_server_mode(const or_options_t *options)
Definition: routermode.c:43
HEX_DIGEST_LEN
#define HEX_DIGEST_LEN
Definition: crypto_digest.h:35
FORCE_REGENERATE_DESCRIPTOR_INTERVAL
#define FORCE_REGENERATE_DESCRIPTOR_INTERVAL
Definition: router.c:2500
LOG_WARN
#define LOG_WARN
Definition: log.h:53
node_st.h
Node information structure.
router_get_my_extrainfo
extrainfo_t * router_get_my_extrainfo(void)
Definition: router.c:1816
router_initialize_tls_context
int router_initialize_tls_context(void)
Definition: router.c:801
router_have_consensus_path
consensus_path_type_t router_have_consensus_path(void)
Definition: nodelist.c:2379
router_reset_warnings
void router_reset_warnings(void)
Definition: router.c:3536
LOG_ERR
#define LOG_ERR
Definition: log.h:56
or_options_t::Nickname
char * Nickname
Definition: or_options_st.h:97
was_router_added_t
was_router_added_t
Definition: routerlist.h:17
have_lockfile
int have_lockfile(void)
Definition: main.c:707
or_options_t::AccountingMax
uint64_t AccountingMax
Definition: or_options_st.h:516
fmt_af_family
const char * fmt_af_family(sa_family_t family)
Definition: address.c:1246
desc_routerinfo
static routerinfo_t * desc_routerinfo
Definition: router.c:1589
crypto_pk_write_public_key_to_string
int crypto_pk_write_public_key_to_string(crypto_pk_t *env, char **dest, size_t *len)
Definition: crypto_rsa.c:466
policies.h
Header file for policies.c.
router_free_all
void router_free_all(void)
Definition: router.c:3546
router_addr_is_my_published_addr
bool router_addr_is_my_published_addr(const tor_addr_t *addr)
Definition: router.c:1741
config_line_t
Definition: confline.h:29
directory_post_to_dirservers
void directory_post_to_dirservers(uint8_t dir_purpose, uint8_t router_purpose, dirinfo_type_t type, const char *payload, size_t payload_len, size_t extrainfo_len)
Definition: dirclient.c:237
config.h
Header file for config.c.
desc_clean_since
STATIC time_t desc_clean_since
Definition: router.c:1597
router_write_fingerprint
STATIC int router_write_fingerprint(int hashed, int ed25519_identity)
Definition: router.c:839
router_is_me
int router_is_me(const routerinfo_t *router)
Definition: router.c:1730
desc_gen_reason
static const char * desc_gen_reason
Definition: router.c:1594
crypto_digest256
int crypto_digest256(char *digest, const char *m, size_t len, digest_algorithm_t algorithm)
Definition: crypto_digest_nss.c:121
get_my_v3_legacy_signing_key
crypto_pk_t * get_my_v3_legacy_signing_key(void)
Definition: router.c:462
router_get_dirobj_signature
char * router_get_dirobj_signature(const char *digest, size_t digest_len, const crypto_pk_t *private_key)
Definition: signing.c:22
BRIDGE_DIRINFO
@ BRIDGE_DIRINFO
Definition: or.h:910
server_identitykey_digest
static char server_identitykey_digest[DIGEST_LEN]
Definition: router.c:118
init_key_from_file
crypto_pk_t * init_key_from_file(const char *fname, int generate, int severity, bool *created_out)
Definition: loadkey.c:40
smartlist_add_asprintf
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition: smartlist.c:36
tor_mutex_acquire
void tor_mutex_acquire(tor_mutex_t *m)
Definition: compat_mutex_pthreads.c:71
crypto_pk_copy_full
crypto_pk_t * crypto_pk_copy_full(crypto_pk_t *orig)
Definition: crypto_rsa_nss.c:386
tor_log
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:590
extrainfo_parse_entry_from_string
extrainfo_t * extrainfo_parse_entry_from_string(const char *s, const char *end, int cache_copy, struct digest_ri_map_t *routermap, int *can_dl_again_out)
Definition: routerparse.c:967
signed_descriptor_t::published_on
time_t published_on
Definition: signed_descriptor_st.h:33
policy_is_reject_star
int policy_is_reject_star(const smartlist_t *policy, sa_family_t family, int default_reject)
Definition: policies.c:2244
sa_family_t
uint16_t sa_family_t
Definition: inaddr_st.h:77
relay_get_effective_bwrate
uint32_t relay_get_effective_bwrate(const or_options_t *options)
Definition: relay_config.c:92
ROUTER_PURPOSE_GENERAL
#define ROUTER_PURPOSE_GENERAL
Definition: routerinfo_st.h:98
mark_my_descriptor_dirty_if_too_old
void mark_my_descriptor_dirty_if_too_old(time_t now)
Definition: router.c:2509
rep_hist_get_padding_count_lines
char * rep_hist_get_padding_count_lines(void)
Definition: rephist.c:2206
or_options_t
Definition: or_options_st.h:64
authority_cert_t::signing_key
crypto_pk_t * signing_key
Definition: authority_cert_st.h:25
get_uptime
long get_uptime(void)
Definition: mainloop.c:2526
portconf_get_first_advertised_port
int portconf_get_first_advertised_port(int listener_type, int address_family)
Definition: config.c:6693
or_options_t::CellStatistics
int CellStatistics
Definition: or_options_st.h:661
signed_descriptor_t::routerlist_index
int routerlist_index
Definition: signed_descriptor_st.h:50
last_curve25519_onion_key
static curve25519_keypair_t last_curve25519_onion_key
Definition: router.c:113
STATIC
#define STATIC
Definition: testsupport.h:32
dimap_free
#define dimap_free(map, free_fn)
Definition: di_ops.h:63
decide_to_advertise_dir_impl
static int decide_to_advertise_dir_impl(const or_options_t *options, uint16_t dir_port, int supports_tunnelled_dir_requests)
Definition: router.c:1292
rotate_onion_key
void rotate_onion_key(void)
Definition: router.c:475
dns.h
Header file for dns.c.
signed_descriptor_t::signed_descriptor_body
char * signed_descriptor_body
Definition: signed_descriptor_st.h:22
signed_descriptor_t::signed_descriptor_len
size_t signed_descriptor_len
Definition: signed_descriptor_st.h:26
router_append_dirobj_signature
int router_append_dirobj_signature(char *buf, size_t buf_len, const char *digest, size_t digest_len, crypto_pk_t *private_key)
Definition: signing.c:79
routerparse.h
Header file for routerparse.c.
routerinfo_t::nickname
char * nickname
Definition: routerinfo_st.h:22
LD_DIR
#define LD_DIR
Definition: log.h:88
consider_publishable_server
void consider_publishable_server(int force)
Definition: router.c:1422
load_ed_keys
int load_ed_keys(const or_options_t *options, time_t now)
Definition: routerkeys.c:55
networkstatus_get_param
int32_t networkstatus_get_param(const networkstatus_t *ns, const char *param_name, int32_t default_val, int32_t min_val, int32_t max_val)
Definition: networkstatus.c:2500
networkstatus_st.h
Networkstatus consensus/vote structure.
tor_tls_context_init
int tor_tls_context_init(unsigned flags, crypto_pk_t *client_identity, crypto_pk_t *server_identity, unsigned int key_lifetime)
Definition: tortls.c:182
bwhist_bandwidth_assess
int bwhist_bandwidth_assess(void)
Definition: bwhist.c:233
FINGERPRINT_LEN
#define FINGERPRINT_LEN
Definition: crypto_rsa.h:34
networkstatus_t
Definition: networkstatus_st.h:26
check_descriptor_ipaddress_changed
void check_descriptor_ipaddress_changed(time_t now)
Definition: router.c:2656
crypto_ed25519.h
Header for crypto_ed25519.c.
SAVED_NOWHERE
@ SAVED_NOWHERE
Definition: or.h:750
curve25519_keypair_write_to_file
int curve25519_keypair_write_to_file(const curve25519_keypair_t *keypair, const char *fname, const char *tag)
Definition: crypto_curve25519.c:207
desc_extrainfo
static extrainfo_t * desc_extrainfo
Definition: router.c:1591
curve25519_public_to_base64
void curve25519_public_to_base64(char *output, const curve25519_public_key_t *pkey, bool pad)
Definition: crypto_format.c:144
router_should_advertise_dirport
int router_should_advertise_dirport(const or_options_t *options, uint16_t dir_port)
Definition: router.c:1323
routerinfo_t::bandwidthrate
uint32_t bandwidthrate
Definition: routerinfo_st.h:54
smartlist_t
Definition: smartlist_core.h:26
extrainfo_dump_to_string_ed_sig_helper
static int extrainfo_dump_to_string_ed_sig_helper(smartlist_t *chunks, const ed25519_keypair_t *signing_keypair)
Definition: router.c:3354
or_options_t::AvoidDiskWrites
int AvoidDiskWrites
Definition: or_options_st.h:279
smartlist_join_strings
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
torversion.h
Header for version.c.
fast_memeq
#define fast_memeq(a, b, c)
Definition: di_ops.h:35
geoip_db_digest
const char * geoip_db_digest(sa_family_t family)
Definition: geoip.c:473
tor_addr_eq
#define tor_addr_eq(a, b)
Definition: address.h:280
create_keys_directory
int create_keys_directory(const or_options_t *options)
Definition: config.c:1388
router_get_my_id_digest
const uint8_t * router_get_my_id_digest(void)
Definition: router.c:1709
desc_needs_upload
static int desc_needs_upload
Definition: router.c:1601
CONN_TYPE_DIR_LISTENER
#define CONN_TYPE_DIR_LISTENER
Definition: connection.h:53
rephist.h
Header file for rephist.c.
mark_my_descriptor_dirty
void mark_my_descriptor_dirty(const char *reason)
Definition: router.c:2550
authdir_mode
int authdir_mode(const or_options_t *options)
Definition: authmode.c:25
dir_server_add
void dir_server_add(dir_server_t *ent)
Definition: dirlist.c:423
expire_old_onion_keys
void expire_old_onion_keys(void)
Definition: router.c:240
tor_addr_copy
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:933
routerinfo_t::onion_curve25519_pkey
struct curve25519_public_key_t * onion_curve25519_pkey
Definition: routerinfo_st.h:43
curve25519_keypair_t
Definition: crypto_curve25519.h:38
router_can_extend_over_ipv6
bool router_can_extend_over_ipv6(const or_options_t *options)
Definition: router.c:1556
pt_get_extra_info_descriptor_string
char * pt_get_extra_info_descriptor_string(void)
Definition: transports.c:1658
server_identity_key_is_set
int server_identity_key_is_set(void)
Definition: router.c:400
is_legal_hexdigest
int is_legal_hexdigest(const char *s)
Definition: nickname.c:45
router_should_advertise_begindir
static int router_should_advertise_begindir(const or_options_t *options, int supports_tunnelled_dir_requests)
Definition: router.c:1333
node_t::identity
char identity[DIGEST_LEN]
Definition: node_st.h:46
resolved_addr_method_to_str
const char * resolved_addr_method_to_str(const resolved_addr_method_t method)
Definition: resolve_addr.c:81
router_orport_seems_reachable
int router_orport_seems_reachable(const or_options_t *options, int family)
Definition: selftest.c:106
port_exists_by_type_addr_port
int port_exists_by_type_addr_port(int listener_type, const tor_addr_t *addr, int port, int check_wildcard)
Definition: config.c:6720
or.h
Master header file for Tor-specific functionality.
router_check_descriptor_address_consistency
static void router_check_descriptor_address_consistency(const tor_addr_t *addr)
Definition: router.c:1905
tor_mutex_release
void tor_mutex_release(tor_mutex_t *m)
Definition: compat_mutex_pthreads.c:84
ed25519_keypair_t
Definition: crypto_ed25519.h:39
bwhist_get_bandwidth_lines
char * bwhist_get_bandwidth_lines(void)
Definition: bwhist.c:323
CMD_KEY_EXPIRATION
@ CMD_KEY_EXPIRATION
Definition: tor_cmdline_mode.h:26
routerconf_find_or_port
uint16_t routerconf_find_or_port(const or_options_t *options, sa_family_t family)
Definition: router.c:1464
or_options_t::BridgeDistribution
char * BridgeDistribution
Definition: or_options_st.h:247
routerinfo_err_is_transient
int routerinfo_err_is_transient(int err)
Definition: router.c:174
signed_descriptor_t::extra_info_digest
char extra_info_digest[DIGEST_LEN]
Definition: signed_descriptor_st.h:35