Tor  0.4.7.0-alpha-dev
networkstatus.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-2021, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 
7 /**
8  * \file networkstatus.c
9  * \brief Functions and structures for handling networkstatus documents as a
10  * client or as a directory cache.
11  *
12  * A consensus networkstatus object is created by the directory
13  * authorities. It authenticates a set of network parameters--most
14  * importantly, the list of all the relays in the network. This list
15  * of relays is represented as an array of routerstatus_t objects.
16  *
17  * There are currently two flavors of consensus. With the older "NS"
18  * flavor, each relay is associated with a digest of its router
19  * descriptor. Tor instances that use this consensus keep the list of
20  * router descriptors as routerinfo_t objects stored and managed in
21  * routerlist.c. With the newer "microdesc" flavor, each relay is
22  * associated with a digest of the microdescriptor that the authorities
23  * made for it. These are stored and managed in microdesc.c. Information
24  * about the router is divided between the the networkstatus and the
25  * microdescriptor according to the general rule that microdescriptors
26  * should hold information that changes much less frequently than the
27  * information in the networkstatus.
28  *
29  * Modern clients use microdescriptor networkstatuses. Directory caches
30  * need to keep both kinds of networkstatus document, so they can serve them.
31  *
32  * This module manages fetching, holding, storing, updating, and
33  * validating networkstatus objects. The download-and-validate process
34  * is slightly complicated by the fact that the keys you need to
35  * validate a consensus are stored in the authority certificates, which
36  * you might not have yet when you download the consensus.
37  */
38 
39 #define NETWORKSTATUS_PRIVATE
40 #include "core/or/or.h"
41 #include "app/config/config.h"
43 #include "core/mainloop/mainloop.h"
45 #include "core/or/channel.h"
46 #include "core/or/channelpadding.h"
47 #include "core/or/circuitpadding.h"
48 #include "core/or/circuitmux.h"
50 #include "core/or/circuitstats.h"
52 #include "core/or/connection_or.h"
53 #include "core/or/dos.h"
54 #include "core/or/protover.h"
55 #include "core/or/relay.h"
56 #include "core/or/scheduler.h"
57 #include "core/or/versions.h"
58 #include "feature/client/bridges.h"
72 #include "feature/hs/hs_dos.h"
86 
92 
106 
107 #ifdef HAVE_UNISTD_H
108 #include <unistd.h>
109 #endif
110 
111 /** Most recently received and validated v3 "ns"-flavored consensus network
112  * status. */
114 
115 /** Most recently received and validated v3 "microdesc"-flavored consensus
116  * network status. */
118 
119 /** A v3 consensus networkstatus that we've received, but which we don't
120  * have enough certificates to be happy about. */
122  /** The consensus itself. */
124  /** When did we set the current value of consensus_waiting_for_certs? If
125  * this is too recent, we shouldn't try to fetch a new consensus for a
126  * little while, to give ourselves time to get certificates for this one. */
127  time_t set_at;
128  /** Set to 1 if we've been holding on to it for so long we should maybe
129  * treat it as being bad. */
132 
133 /** An array, for each flavor of consensus we might want, of consensuses that
134  * we have downloaded, but which we cannot verify due to having insufficient
135  * authority certificates. */
138 
139 /** A time before which we shouldn't try to replace the current consensus:
140  * this will be at some point after the next consensus becomes valid, but
141  * before the current consensus becomes invalid. */
143 /** Download status for the current consensus networkstatus. */
145  {
146  { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
147  DL_SCHED_INCREMENT_FAILURE, 0, 0 },
148  { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
149  DL_SCHED_INCREMENT_FAILURE, 0, 0 },
150  };
151 
152 #define N_CONSENSUS_BOOTSTRAP_SCHEDULES 2
153 #define CONSENSUS_BOOTSTRAP_SOURCE_AUTHORITY 0
154 #define CONSENSUS_BOOTSTRAP_SOURCE_ANY_DIRSERVER 1
155 
156 /* Using DL_SCHED_INCREMENT_ATTEMPT on these schedules means that
157  * download_status_increment_failure won't increment these entries.
158  * However, any bootstrap connection failures that occur after we have
159  * a valid consensus will count against the failure counts on the non-bootstrap
160  * schedules. There should only be one of these, as all the others will have
161  * been cancelled. (This doesn't seem to be a significant issue.) */
162 static download_status_t
163  consensus_bootstrap_dl_status[N_CONSENSUS_BOOTSTRAP_SCHEDULES] =
164  {
165  { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_AUTHORITY,
166  DL_SCHED_INCREMENT_ATTEMPT, 0, 0 },
167  /* During bootstrap, DL_WANT_ANY_DIRSERVER means "use fallbacks". */
168  { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
169  DL_SCHED_INCREMENT_ATTEMPT, 0, 0 },
170  };
171 
172 /** True iff we have logged a warning about this OR's version being older than
173  * listed by the authorities. */
175 /** True iff we have logged a warning about this OR's version being newer than
176  * listed by the authorities. */
178 
180  time_t now,
181  const or_options_t *options);
183  int client_mode,
184  char **warning_out);
185 static int reload_consensus_from_file(const char *fname,
186  const char *flavor,
187  unsigned flags,
188  const char *source_dir);
189 
190 /** Forget that we've warned about anything networkstatus-related, so we will
191  * give fresh warnings if the same behavior happens again. */
192 void
194 {
196  node->name_lookup_warned = 0);
197 
200 }
201 
202 /** Reset the descriptor download failure count on all networkstatus docs, so
203  * that we can retry any long-failed documents immediately.
204  */
205 void
207 {
208  int i;
209 
210  log_debug(LD_GENERAL,
211  "In networkstatus_reset_download_failures()");
212 
213  for (i=0; i < N_CONSENSUS_FLAVORS; ++i)
215 
216  for (i=0; i < N_CONSENSUS_BOOTSTRAP_SCHEDULES; ++i)
217  download_status_reset(&consensus_bootstrap_dl_status[i]);
218 }
219 
220 /** Return the filename used to cache the consensus of a given flavor */
221 MOCK_IMPL(char *,
223  const char *flavorname,
224  int unverified_consensus))
225 {
226  char buf[128];
227  const char *prefix;
228  if (unverified_consensus) {
229  prefix = "unverified";
230  } else {
231  prefix = "cached";
232  }
233  if (flav == FLAV_NS) {
234  tor_snprintf(buf, sizeof(buf), "%s-consensus", prefix);
235  } else {
236  tor_snprintf(buf, sizeof(buf), "%s-%s-consensus", prefix, flavorname);
237  }
238 
239  return get_cachedir_fname(buf);
240 }
241 
242 /**
243  * Read and return the cached consensus of type <b>flavorname</b>. If
244  * <b>unverified</b> is false, get the one we haven't verified. Return NULL if
245  * the file isn't there. */
246 static tor_mmap_t *
248  const char *flavorname,
249  int unverified_consensus)
250 {
251  char *filename = networkstatus_get_cache_fname(flav,
252  flavorname,
253  unverified_consensus);
254  tor_mmap_t *result = tor_mmap_file(filename);
255  tor_free(filename);
256  return result;
257 }
258 
259 /** Map the file containing the current cached consensus of flavor
260  * <b>flavorname</b> */
261 tor_mmap_t *
262 networkstatus_map_cached_consensus(const char *flavorname)
263 {
264  int flav = networkstatus_parse_flavor_name(flavorname);
265  if (flav < 0)
266  return NULL;
267  return networkstatus_map_cached_consensus_impl(flav, flavorname, 0);
268 }
269 
270 /** Read every cached v3 consensus networkstatus from the disk. */
271 int
273 {
274  const unsigned int flags = NSSET_FROM_CACHE | NSSET_DONT_DOWNLOAD_CERTS;
275  int flav;
276 
277  /* FFFF Suppress warnings if cached consensus is bad? */
278  for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
279  const char *flavor = networkstatus_get_flavor_name(flav);
280  char *fname = networkstatus_get_cache_fname(flav, flavor, 0);
281  reload_consensus_from_file(fname, flavor, flags, NULL);
282  tor_free(fname);
283 
284  fname = networkstatus_get_cache_fname(flav, flavor, 1);
285  reload_consensus_from_file(fname, flavor,
286  flags | NSSET_WAS_WAITING_FOR_CERTS,
287  NULL);
288  tor_free(fname);
289  }
290 
291  update_certificate_downloads(time(NULL));
292 
295 
296  return 0;
297 }
298 
299 /** Free all storage held by the vote_routerstatus object <b>rs</b>. */
300 void
302 {
303  vote_microdesc_hash_t *h, *next;
304  if (!rs)
305  return;
306  tor_free(rs->version);
307  tor_free(rs->protocols);
309  for (h = rs->microdesc; h; h = next) {
311  next = h->next;
312  tor_free(h);
313  }
314  tor_free(rs);
315 }
316 
317 /** Free all storage held by the routerstatus object <b>rs</b>. */
318 void
320 {
321  if (!rs)
322  return;
323  tor_free(rs->exitsummary);
324  tor_free(rs);
325 }
326 
327 /** Free all storage held in <b>sig</b> */
328 void
330 {
331  tor_free(sig->signature);
332  tor_free(sig);
333 }
334 
335 /** Return a newly allocated copy of <b>sig</b> */
338 {
339  document_signature_t *r = tor_memdup(sig, sizeof(document_signature_t));
340  if (r->signature)
341  r->signature = tor_memdup(sig->signature, sig->signature_len);
342  return r;
343 }
344 
345 /** Free all storage held in <b>ns</b>. */
346 void
348 {
349  if (!ns)
350  return;
351 
353  tor_free(ns->server_versions);
354  tor_free(ns->recommended_client_protocols);
356  tor_free(ns->required_client_protocols);
357  tor_free(ns->required_relay_protocols);
358 
359  if (ns->known_flags) {
360  SMARTLIST_FOREACH(ns->known_flags, char *, c, tor_free(c));
361  smartlist_free(ns->known_flags);
362  }
363  if (ns->weight_params) {
364  SMARTLIST_FOREACH(ns->weight_params, char *, c, tor_free(c));
365  smartlist_free(ns->weight_params);
366  }
367  if (ns->net_params) {
368  SMARTLIST_FOREACH(ns->net_params, char *, c, tor_free(c));
369  smartlist_free(ns->net_params);
370  }
371  if (ns->supported_methods) {
372  SMARTLIST_FOREACH(ns->supported_methods, char *, c, tor_free(c));
373  smartlist_free(ns->supported_methods);
374  }
375  if (ns->package_lines) {
376  SMARTLIST_FOREACH(ns->package_lines, char *, c, tor_free(c));
377  smartlist_free(ns->package_lines);
378  }
379  if (ns->voters) {
381  tor_free(voter->nickname);
382  tor_free(voter->address);
383  tor_free(voter->contact);
384  if (voter->sigs) {
385  SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
386  document_signature_free(sig));
387  smartlist_free(voter->sigs);
388  }
389  tor_free(voter);
390  } SMARTLIST_FOREACH_END(voter);
391  smartlist_free(ns->voters);
392  }
393  authority_cert_free(ns->cert);
394 
395  if (ns->routerstatus_list) {
396  if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
398  vote_routerstatus_free(rs));
399  } else {
401  routerstatus_free(rs));
402  }
403 
404  smartlist_free(ns->routerstatus_list);
405  }
406 
407  if (ns->bw_file_headers) {
408  SMARTLIST_FOREACH(ns->bw_file_headers, char *, c, tor_free(c));
409  smartlist_free(ns->bw_file_headers);
410  }
411 
412  digestmap_free(ns->desc_digest_map, NULL);
413 
414  if (ns->sr_info.commits) {
415  dirvote_clear_commits(ns);
416  }
417  tor_free(ns->sr_info.previous_srv);
418  tor_free(ns->sr_info.current_srv);
419 
420  memwipe(ns, 11, sizeof(*ns));
421  tor_free(ns);
422 }
423 
424 /** Return the voter info from <b>vote</b> for the voter whose identity digest
425  * is <b>identity</b>, or NULL if no such voter is associated with
426  * <b>vote</b>. */
429  const char *identity)
430 {
431  if (!vote || !vote->voters)
432  return NULL;
434  if (fast_memeq(voter->identity_digest, identity, DIGEST_LEN))
435  return voter);
436  return NULL;
437 }
438 
439 /** Return the signature made by <b>voter</b> using the algorithm
440  * <b>alg</b>, or NULL if none is found. */
443  digest_algorithm_t alg)
444 {
445  if (!voter->sigs)
446  return NULL;
448  if (sig->alg == alg)
449  return sig);
450  return NULL;
451 }
452 
453 /** Check whether the signature <b>sig</b> is correctly signed with the
454  * signing key in <b>cert</b>. Return -1 if <b>cert</b> doesn't match the
455  * signing key; otherwise set the good_signature or bad_signature flag on
456  * <b>voter</b>, and return 0. */
457 int
460  const authority_cert_t *cert)
461 {
462  char key_digest[DIGEST_LEN];
463  const int dlen = sig->alg == DIGEST_SHA1 ? DIGEST_LEN : DIGEST256_LEN;
464  char *signed_digest;
465  size_t signed_digest_len;
466 
467  if (crypto_pk_get_digest(cert->signing_key, key_digest)<0)
468  return -1;
469  if (tor_memneq(sig->signing_key_digest, key_digest, DIGEST_LEN) ||
471  DIGEST_LEN))
472  return -1;
473 
474  if (authority_cert_is_denylisted(cert)) {
475  /* We implement denylisting for authority signing keys by treating
476  * all their signatures as always bad. That way we don't get into
477  * crazy loops of dropping and re-fetching signatures. */
478  log_warn(LD_DIR, "Ignoring a consensus signature made with deprecated"
479  " signing key %s",
481  sig->bad_signature = 1;
482  return 0;
483  }
484 
485  signed_digest_len = crypto_pk_keysize(cert->signing_key);
486  signed_digest = tor_malloc(signed_digest_len);
488  signed_digest,
489  signed_digest_len,
490  sig->signature,
491  sig->signature_len) < dlen ||
492  tor_memneq(signed_digest, consensus->digests.d[sig->alg], dlen)) {
493  log_warn(LD_DIR, "Got a bad signature on a networkstatus vote");
494  sig->bad_signature = 1;
495  } else {
496  sig->good_signature = 1;
497  }
498  tor_free(signed_digest);
499  return 0;
500 }
501 
502 /** Given a v3 networkstatus consensus in <b>consensus</b>, check every
503  * as-yet-unchecked signature on <b>consensus</b>. Return 1 if there is a
504  * signature from every recognized authority on it, 0 if there are
505  * enough good signatures from recognized authorities on it, -1 if we might
506  * get enough good signatures by fetching missing certificates, and -2
507  * otherwise. Log messages at INFO or WARN: if <b>warn</b> is over 1, warn
508  * about every problem; if warn is at least 1, warn only if we can't get
509  * enough signatures; if warn is negative, log nothing at all. */
510 int
512  int warn)
513 {
514  int n_good = 0;
515  int n_missing_key = 0, n_dl_failed_key = 0;
516  int n_bad = 0;
517  int n_unknown = 0;
518  int n_no_signature = 0;
519  int n_v3_authorities = get_n_authorities(V3_DIRINFO);
520  int n_required = n_v3_authorities/2 + 1;
521  smartlist_t *list_good = smartlist_new();
522  smartlist_t *list_no_signature = smartlist_new();
523  smartlist_t *need_certs_from = smartlist_new();
524  smartlist_t *unrecognized = smartlist_new();
525  smartlist_t *missing_authorities = smartlist_new();
526  int severity;
527  time_t now = time(NULL);
528 
529  tor_assert(consensus->type == NS_TYPE_CONSENSUS);
530 
532  voter) {
533  int good_here = 0;
534  int bad_here = 0;
535  int unknown_here = 0;
536  int missing_key_here = 0, dl_failed_key_here = 0;
537  SMARTLIST_FOREACH_BEGIN(voter->sigs, document_signature_t *, sig) {
538  if (!sig->good_signature && !sig->bad_signature &&
539  sig->signature) {
540  /* we can try to check the signature. */
542  sig->identity_digest) != NULL;
543  authority_cert_t *cert =
544  authority_cert_get_by_digests(sig->identity_digest,
545  sig->signing_key_digest);
546  tor_assert(tor_memeq(sig->identity_digest, voter->identity_digest,
547  DIGEST_LEN));
548 
549  if (!is_v3_auth) {
550  smartlist_add(unrecognized, voter);
551  ++unknown_here;
552  continue;
553  } else if (!cert || cert->expires < now) {
554  smartlist_add(need_certs_from, voter);
555  ++missing_key_here;
556  if (authority_cert_dl_looks_uncertain(sig->identity_digest))
557  ++dl_failed_key_here;
558  continue;
559  }
560  if (networkstatus_check_document_signature(consensus, sig, cert) < 0) {
561  smartlist_add(need_certs_from, voter);
562  ++missing_key_here;
563  if (authority_cert_dl_looks_uncertain(sig->identity_digest))
564  ++dl_failed_key_here;
565  continue;
566  }
567  }
568  if (sig->good_signature)
569  ++good_here;
570  else if (sig->bad_signature)
571  ++bad_here;
572  } SMARTLIST_FOREACH_END(sig);
573 
574  if (good_here) {
575  ++n_good;
576  smartlist_add(list_good, voter->nickname);
577  } else if (bad_here) {
578  ++n_bad;
579  } else if (missing_key_here) {
580  ++n_missing_key;
581  if (dl_failed_key_here)
582  ++n_dl_failed_key;
583  } else if (unknown_here) {
584  ++n_unknown;
585  } else {
586  ++n_no_signature;
587  smartlist_add(list_no_signature, voter->nickname);
588  }
589  } SMARTLIST_FOREACH_END(voter);
590 
591  /* Now see whether we're missing any voters entirely. */
592  SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
593  dir_server_t *, ds,
594  {
595  if ((ds->type & V3_DIRINFO) &&
596  !networkstatus_get_voter_by_id(consensus, ds->v3_identity_digest))
597  smartlist_add(missing_authorities, ds);
598  });
599 
600  if (warn > 1 || (warn >= 0 &&
601  (n_good + n_missing_key - n_dl_failed_key < n_required))) {
602  severity = LOG_WARN;
603  } else {
604  severity = LOG_INFO;
605  }
606 
607  if (warn >= 0) {
608  SMARTLIST_FOREACH(unrecognized, networkstatus_voter_info_t *, voter,
609  {
610  tor_log(severity, LD_DIR, "Consensus includes unrecognized authority "
611  "'%s' at %s:%" PRIu16 " (contact %s; identity %s)",
612  voter->nickname, voter->address, voter->ipv4_dirport,
613  voter->contact?voter->contact:"n/a",
614  hex_str(voter->identity_digest, DIGEST_LEN));
615  });
616  SMARTLIST_FOREACH(need_certs_from, networkstatus_voter_info_t *, voter,
617  {
618  tor_log(severity, LD_DIR, "Looks like we need to download a new "
619  "certificate from authority '%s' at %s:%" PRIu16
620  " (contact %s; identity %s)",
621  voter->nickname, voter->address, voter->ipv4_dirport,
622  voter->contact?voter->contact:"n/a",
623  hex_str(voter->identity_digest, DIGEST_LEN));
624  });
625  SMARTLIST_FOREACH(missing_authorities, dir_server_t *, ds,
626  {
627  tor_log(severity, LD_DIR, "Consensus does not include configured "
628  "authority '%s' at %s:%" PRIu16 " (identity %s)",
629  ds->nickname, ds->address, ds->ipv4_dirport,
630  hex_str(ds->v3_identity_digest, DIGEST_LEN));
631  });
632  {
633  char *joined;
634  smartlist_t *sl = smartlist_new();
635  char *tmp = smartlist_join_strings(list_good, " ", 0, NULL);
637  "A consensus needs %d good signatures from recognized "
638  "authorities for us to accept it. "
639  "This %s one has %d (%s).",
640  n_required,
642  n_good, tmp);
643  tor_free(tmp);
644  if (n_no_signature) {
645  tmp = smartlist_join_strings(list_no_signature, " ", 0, NULL);
647  "%d (%s) of the authorities we know didn't sign it.",
648  n_no_signature, tmp);
649  tor_free(tmp);
650  }
651  if (n_unknown) {
653  "It has %d signatures from authorities we don't "
654  "recognize.", n_unknown);
655  }
656  if (n_bad) {
657  smartlist_add_asprintf(sl, "%d of the signatures on it didn't verify "
658  "correctly.", n_bad);
659  }
660  if (n_missing_key) {
662  "We were unable to check %d of the signatures, "
663  "because we were missing the keys.", n_missing_key);
664  }
665  joined = smartlist_join_strings(sl, " ", 0, NULL);
666  tor_log(severity, LD_DIR, "%s", joined);
667  tor_free(joined);
668  SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
669  smartlist_free(sl);
670  }
671  }
672 
673  smartlist_free(list_good);
674  smartlist_free(list_no_signature);
675  smartlist_free(unrecognized);
676  smartlist_free(need_certs_from);
677  smartlist_free(missing_authorities);
678 
679  if (n_good == n_v3_authorities)
680  return 1;
681  else if (n_good >= n_required)
682  return 0;
683  else if (n_good + n_missing_key >= n_required)
684  return -1;
685  else
686  return -2;
687 }
688 
689 /** How far in the future do we allow a network-status to get before removing
690  * it? (seconds) */
691 #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
692 
693 /** Helper for bsearching a list of routerstatus_t pointers: compare a
694  * digest in the key to the identity digest of a routerstatus_t. */
695 int
696 compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
697 {
698  const char *key = _key;
699  const routerstatus_t *rs = *_member;
700  return tor_memcmp(key, rs->identity_digest, DIGEST_LEN);
701 }
702 
703 /** Helper for bsearching a list of routerstatus_t pointers: compare a
704  * digest in the key to the identity digest of a routerstatus_t. */
705 int
707  const void **_member)
708 {
709  const char *key = _key;
710  const vote_routerstatus_t *vrs = *_member;
711  return tor_memcmp(key, vrs->status.identity_digest, DIGEST_LEN);
712 }
713 
714 /** As networkstatus_find_entry, but do not return a const pointer */
717 {
718  return smartlist_bsearch(ns->routerstatus_list, digest,
720 }
721 
722 /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
723  * NULL if none was found. */
724 MOCK_IMPL(const routerstatus_t *,
726 {
727  return networkstatus_vote_find_mutable_entry(ns, digest);
728 }
729 
730 /*XXXX MOVE make this static once functions are moved into this file. */
731 /** Search the routerstatuses in <b>ns</b> for one whose identity digest is
732  * <b>digest</b>. Return value and set *<b>found_out</b> as for
733  * smartlist_bsearch_idx(). */
734 int
736  const char *digest, int *found_out)
737 {
738  return smartlist_bsearch_idx(ns->routerstatus_list, digest,
740  found_out);
741 }
742 
743 /** As router_get_consensus_status_by_descriptor_digest, but does not return
744  * a const pointer. */
747  networkstatus_t *consensus,
748  const char *digest))
749 {
750  if (!consensus)
752  if (!consensus)
753  return NULL;
754  if (!consensus->desc_digest_map) {
755  digestmap_t *m = consensus->desc_digest_map = digestmap_new();
757  routerstatus_t *, rs,
758  {
759  digestmap_set(m, rs->descriptor_digest, rs);
760  });
761  }
762  return digestmap_get(consensus->desc_digest_map, digest);
763 }
764 
765 /** Return the consensus view of the status of the router whose current
766  * <i>descriptor</i> digest in <b>consensus</b> is <b>digest</b>, or NULL if
767  * no such router is known. */
768 const routerstatus_t *
770  const char *digest)
771 {
773  consensus, digest);
774 }
775 
776 /** Return a smartlist of all router descriptor digests in a consensus */
777 static smartlist_t *
779 {
780  smartlist_t *result = smartlist_new();
781  digestmap_iter_t *i;
782  const char *digest;
783  void *rs;
784  char *digest_tmp;
785 
786  for (i = digestmap_iter_init(consensus->desc_digest_map);
787  !(digestmap_iter_done(i));
788  i = digestmap_iter_next(consensus->desc_digest_map, i)) {
789  digestmap_iter_get(i, &digest, &rs);
790  digest_tmp = tor_malloc(DIGEST_LEN);
791  memcpy(digest_tmp, digest, DIGEST_LEN);
792  smartlist_add(result, digest_tmp);
793  }
794 
795  return result;
796 }
797 
798 /** Return a smartlist of all router descriptor digests in the current
799  * consensus */
802 {
803  smartlist_t *result = NULL;
804 
805  if (current_ns_consensus) {
806  result =
808  }
809 
810  return result;
811 }
812 
813 /** Given the digest of a router descriptor, return its current download
814  * status, or NULL if the digest is unrecognized. */
817 {
818  routerstatus_t *rs;
820  return NULL;
823  return &rs->dl_status;
824 
825  return NULL;
826 }
827 
828 /** As router_get_consensus_status_by_id, but do not return a const pointer */
831 {
833  if (!ns)
834  return NULL;
835  smartlist_t *rslist = ns->routerstatus_list;
836  return smartlist_bsearch(rslist, digest,
838 }
839 
840 /** Return the consensus view of the status of the router whose identity
841  * digest is <b>digest</b>, or NULL if we don't know about any such router. */
842 const routerstatus_t *
844 {
846 }
847 
848 /** How frequently do directory authorities re-download fresh networkstatus
849  * documents? */
850 #define AUTHORITY_NS_CACHE_INTERVAL (10*60)
851 
852 /** How frequently do non-authority directory caches re-download fresh
853  * networkstatus documents? */
854 #define NONAUTHORITY_NS_CACHE_INTERVAL (60*60)
855 
856 /** Return true iff, given the options listed in <b>options</b>, <b>flavor</b>
857  * is the flavor of a consensus networkstatus that we would like to fetch.
858  *
859  * For certificate fetches, use we_want_to_fetch_unknown_auth_certs, and
860  * for serving fetched documents, use directory_caches_dir_info. */
861 int
862 we_want_to_fetch_flavor(const or_options_t *options, int flavor)
863 {
864  if (flavor < 0 || flavor > N_CONSENSUS_FLAVORS) {
865  /* This flavor is crazy; we don't want it */
866  /*XXXX handle unrecognized flavors later */
867  return 0;
868  }
869  if (authdir_mode_v3(options) || directory_caches_dir_info(options)) {
870  /* We want to serve all flavors to others, regardless if we would use
871  * it ourselves. */
872  return 1;
873  }
874  if (options->FetchUselessDescriptors) {
875  /* In order to get all descriptors, we need to fetch all consensuses. */
876  return 1;
877  }
878  /* Otherwise, we want the flavor only if we want to use it to build
879  * circuits. */
880  return flavor == usable_consensus_flavor();
881 }
882 
883 /** Return true iff, given the options listed in <b>options</b>, we would like
884  * to fetch and store unknown authority certificates.
885  *
886  * For consensus and descriptor fetches, use we_want_to_fetch_flavor, and
887  * for serving fetched certificates, use directory_caches_unknown_auth_certs.
888  */
889 int
891 {
892  if (authdir_mode_v3(options) ||
894  /* We want to serve all certs to others, regardless if we would use
895  * them ourselves. */
896  return 1;
897  }
898  if (options->FetchUselessDescriptors) {
899  /* Unknown certificates are definitely useless. */
900  return 1;
901  }
902  /* Otherwise, don't fetch unknown certificates. */
903  return 0;
904 }
905 
906 /** How long will we hang onto a possibly live consensus for which we're
907  * fetching certs before we check whether there is a better one? */
908 #define DELAY_WHILE_FETCHING_CERTS (20*60)
909 
910 /** What is the minimum time we need to have waited fetching certs, before we
911  * increment the consensus download schedule on failure? */
912 #define MIN_DELAY_FOR_FETCH_CERT_STATUS_FAILURE (1*60)
913 
914 /* Check if a downloaded consensus flavor should still wait for certificates
915  * to download now. If we decide not to wait, check if enough time has passed
916  * to consider the certificate download failure a separate failure. If so,
917  * fail dls.
918  * If waiting for certificates to download, return 1. If not, return 0. */
919 static int
920 check_consensus_waiting_for_certs(int flavor, time_t now,
921  download_status_t *dls)
922 {
924 
925  /* We should always have a known flavor, because we_want_to_fetch_flavor()
926  * filters out unknown flavors. */
927  tor_assert(flavor >= 0 && flavor < N_CONSENSUS_FLAVORS);
928 
929  waiting = &consensus_waiting_for_certs[flavor];
930  if (waiting->consensus) {
931  /* XXXX make sure this doesn't delay sane downloads. */
932  if (waiting->set_at + DELAY_WHILE_FETCHING_CERTS > now &&
933  waiting->consensus->valid_until > now) {
934  return 1;
935  } else {
936  if (!waiting->dl_failed) {
937  if (waiting->set_at + MIN_DELAY_FOR_FETCH_CERT_STATUS_FAILURE > now) {
938  download_status_failed(dls, 0);
939  }
940  waiting->dl_failed=1;
941  }
942  }
943  }
944 
945  return 0;
946 }
947 
948 /** If we want to download a fresh consensus, launch a new download as
949  * appropriate. */
950 static void
952 {
953  int i;
954  const or_options_t *options = get_options();
955  const int we_are_bootstrapping = networkstatus_consensus_is_bootstrapping(
956  now);
957  const int use_multi_conn =
959 
960  if (should_delay_dir_fetches(options, NULL))
961  return;
962 
963  for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
964  /* XXXX need some way to download unknown flavors if we are caching. */
965  const char *resource;
966  networkstatus_t *c;
967  int max_in_progress_conns = 1;
968 
969  if (! we_want_to_fetch_flavor(options, i))
970  continue;
971 
973  if (! (c && c->valid_after <= now && now <= c->valid_until)) {
974  /* No live consensus? Get one now!*/
976  }
977 
978  if (time_to_download_next_consensus[i] > now)
979  continue; /* Wait until the current consensus is older. */
980 
981  resource = networkstatus_get_flavor_name(i);
982 
983  /* Check if we already have enough connections in progress */
984  if (we_are_bootstrapping && use_multi_conn) {
985  max_in_progress_conns =
987  }
990  resource)
991  >= max_in_progress_conns) {
992  continue;
993  }
994 
995  /* Check if we want to launch another download for a usable consensus.
996  * Only used during bootstrap. */
997  if (we_are_bootstrapping && use_multi_conn
998  && i == usable_consensus_flavor()) {
999 
1000  /* Check if we're already downloading a usable consensus */
1001  if (networkstatus_consensus_is_already_downloading(resource))
1002  continue;
1003 
1004  /* Make multiple connections for a bootstrap consensus download. */
1006  } else {
1007  /* Check if we failed downloading a consensus too recently */
1008 
1009  /* Let's make sure we remembered to update consensus_dl_status */
1010  tor_assert(consensus_dl_status[i].schedule == DL_SCHED_CONSENSUS);
1011 
1013  continue;
1014  }
1015 
1016  /** Check if we're waiting for certificates to download. If we are,
1017  * launch download for missing directory authority certificates. */
1018  if (check_consensus_waiting_for_certs(i, now, &consensus_dl_status[i])) {
1020  continue;
1021  }
1022 
1023  /* Try the requested attempt */
1024  log_info(LD_DIR, "Launching %s standard networkstatus consensus "
1025  "download.", networkstatus_get_flavor_name(i));
1027  ROUTER_PURPOSE_GENERAL, resource,
1029  consensus_dl_status[i].want_authority);
1030  }
1031  }
1032 }
1033 
1034 /** When we're bootstrapping, launch one or more consensus download
1035  * connections, if schedule indicates connection(s) should be made after now.
1036  * If is_authority, connect to an authority, otherwise, use a fallback
1037  * directory mirror.
1038  */
1039 static void
1041  time_t now,
1042  download_status_t *dls,
1043  download_want_authority_t want_authority)
1044 {
1045  const char *resource = networkstatus_get_flavor_name(
1047 
1048  /* Let's make sure we remembered to update schedule */
1049  tor_assert(dls->schedule == DL_SCHED_CONSENSUS);
1050 
1051  /* Allow for multiple connections in the same second, if the schedule value
1052  * is 0. */
1053  while (download_status_is_ready(dls, now)) {
1054  log_info(LD_DIR, "Launching %s bootstrap %s networkstatus consensus "
1055  "download.", resource, (want_authority == DL_WANT_AUTHORITY
1056  ? "authority"
1057  : "mirror"));
1058 
1060  ROUTER_PURPOSE_GENERAL, resource,
1061  PDS_RETRY_IF_NO_SERVERS, want_authority);
1062  /* schedule the next attempt */
1063  download_status_increment_attempt(dls, resource, now);
1064  }
1065 }
1066 
1067 /** If we're bootstrapping, check the connection schedules and see if we want
1068  * to make additional, potentially concurrent, consensus download
1069  * connections.
1070  * Only call when bootstrapping, and when we want to make additional
1071  * connections. Only nodes that satisfy
1072  * networkstatus_consensus_can_use_multiple_directories make additional
1073  * connections.
1074  */
1075 static void
1077  const or_options_t *options)
1078 {
1079  const int usable_flavor = usable_consensus_flavor();
1080 
1081  /* make sure we can use multiple connections */
1083  return;
1084  }
1085 
1086  /* Launch concurrent consensus download attempt(s) based on the mirror and
1087  * authority schedules. Try the mirror first - this makes it slightly more
1088  * likely that we'll connect to the fallback first, and then end the
1089  * authority connection attempt. */
1090 
1091  /* If a consensus download fails because it's waiting for certificates,
1092  * we'll fail both the authority and fallback schedules. This is better than
1093  * failing only one of the schedules, and having the other continue
1094  * unchecked.
1095  */
1096 
1097  /* If we don't have or can't use extra fallbacks, don't try them. */
1099  download_status_t *dls_f =
1100  &consensus_bootstrap_dl_status[CONSENSUS_BOOTSTRAP_SOURCE_ANY_DIRSERVER];
1101 
1102  if (!check_consensus_waiting_for_certs(usable_flavor, now, dls_f)) {
1103  /* During bootstrap, DL_WANT_ANY_DIRSERVER means "use fallbacks". */
1105  DL_WANT_ANY_DIRSERVER);
1106  }
1107  }
1108 
1109  /* Now try an authority. */
1110  download_status_t *dls_a =
1111  &consensus_bootstrap_dl_status[CONSENSUS_BOOTSTRAP_SOURCE_AUTHORITY];
1112 
1113  if (!check_consensus_waiting_for_certs(usable_flavor, now, dls_a)) {
1115  DL_WANT_AUTHORITY);
1116  }
1117 }
1118 
1119 /** Called when an attempt to download a consensus fails: note that the
1120  * failure occurred, and possibly retry. */
1121 void
1122 networkstatus_consensus_download_failed(int status_code, const char *flavname)
1123 {
1124  int flav = networkstatus_parse_flavor_name(flavname);
1125  if (flav >= 0) {
1127  /* XXXX handle unrecognized flavors */
1128  download_status_failed(&consensus_dl_status[flav], status_code);
1129  /* Retry immediately, if appropriate. */
1131  }
1132 }
1133 
1134 /** How long do we (as a cache) wait after a consensus becomes non-fresh
1135  * before trying to fetch another? */
1136 #define CONSENSUS_MIN_SECONDS_BEFORE_CACHING 120
1137 
1138 /** Update the time at which we'll consider replacing the current
1139  * consensus of flavor <b>flav</b> */
1140 static void
1142 {
1143  const or_options_t *options = get_options();
1145  const char *flavor = networkstatus_get_flavor_name(flav);
1146  if (! we_want_to_fetch_flavor(get_options(), flav))
1147  return;
1148 
1149  if (c && c->valid_after <= now && now <= c->valid_until) {
1150  long dl_interval;
1151  long interval = c->fresh_until - c->valid_after;
1152  long min_sec_before_caching = CONSENSUS_MIN_SECONDS_BEFORE_CACHING;
1153  time_t start;
1154 
1155  if (min_sec_before_caching > interval/16) {
1156  /* Usually we allow 2-minutes slop factor in case clocks get
1157  desynchronized a little. If we're on a private network with
1158  a crazy-fast voting interval, though, 2 minutes may be too
1159  much. */
1160  min_sec_before_caching = interval/16;
1161  /* make sure we always delay by at least a second before caching */
1162  if (min_sec_before_caching == 0) {
1163  min_sec_before_caching = 1;
1164  }
1165  }
1166 
1167  if (dirclient_fetches_dir_info_early(options)) {
1168  /* We want to cache the next one at some point after this one
1169  * is no longer fresh... */
1170  start = (time_t)(c->fresh_until + min_sec_before_caching);
1171  /* Some clients may need the consensus sooner than others. */
1172  if (options->FetchDirInfoExtraEarly || authdir_mode_v3(options)) {
1173  dl_interval = 60;
1174  if (min_sec_before_caching + dl_interval > interval)
1175  dl_interval = interval/2;
1176  } else {
1177  /* But only in the first half-interval after that. */
1178  dl_interval = interval/2;
1179  }
1180  } else {
1181  /* We're an ordinary client, a bridge, or a hidden service.
1182  * Give all the caches enough time to download the consensus. */
1183  start = (time_t)(c->fresh_until + (interval*3)/4);
1184  /* But download the next one well before this one is expired. */
1185  dl_interval = ((c->valid_until - start) * 7 )/ 8;
1186 
1187  /* If we're a bridge user, make use of the numbers we just computed
1188  * to choose the rest of the interval *after* them. */
1189  if (dirclient_fetches_dir_info_later(options)) {
1190  /* Give all the *clients* enough time to download the consensus. */
1191  start = (time_t)(start + dl_interval + min_sec_before_caching);
1192  /* But try to get it before ours actually expires. */
1193  dl_interval = (c->valid_until - start) - min_sec_before_caching;
1194  }
1195  }
1196  /* catch low dl_interval in crazy-fast networks */
1197  if (dl_interval < 1)
1198  dl_interval = 1;
1199  /* catch late start in crazy-fast networks */
1200  if (start+dl_interval >= c->valid_until)
1201  start = c->valid_until - dl_interval - 1;
1202  log_debug(LD_DIR,
1203  "fresh_until: %ld start: %ld "
1204  "dl_interval: %ld valid_until: %ld ",
1205  (long)c->fresh_until, (long)start, dl_interval,
1206  (long)c->valid_until);
1207  /* We must not try to replace c while it's still fresh: */
1208  tor_assert(c->fresh_until < start);
1209  /* We must download the next one before c is invalid: */
1210  tor_assert(start+dl_interval < c->valid_until);
1212  start + crypto_rand_int((int)dl_interval);
1213  {
1214  char tbuf1[ISO_TIME_LEN+1];
1215  char tbuf2[ISO_TIME_LEN+1];
1216  char tbuf3[ISO_TIME_LEN+1];
1220  log_info(LD_DIR, "Live %s consensus %s the most recent until %s and "
1221  "will expire at %s; fetching the next one at %s.",
1222  flavor, (c->fresh_until > now) ? "will be" : "was",
1223  tbuf1, tbuf2, tbuf3);
1224  }
1225  } else {
1226  time_to_download_next_consensus[flav] = now;
1227  log_info(LD_DIR, "No live %s consensus; we should fetch one immediately.",
1228  flavor);
1229  }
1230 }
1231 
1232 /** Update the time at which we'll consider replacing the current
1233  * consensus of flavor 'flavor' */
1234 void
1236 {
1237  int i;
1238  for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
1241  }
1242 }
1243 
1244 /** Return 1 if there's a reason we shouldn't try any directory
1245  * fetches yet (e.g. we demand bridges and none are yet known).
1246  * Else return 0.
1247 
1248  * If we return 1 and <b>msg_out</b> is provided, set <b>msg_out</b>
1249  * to an explanation of why directory fetches are delayed. (If we
1250  * return 0, we set msg_out to NULL.)
1251  */
1252 int
1253 should_delay_dir_fetches(const or_options_t *options, const char **msg_out)
1254 {
1255  if (msg_out) {
1256  *msg_out = NULL;
1257  }
1258 
1259  if (options->DisableNetwork) {
1260  if (msg_out) {
1261  *msg_out = "DisableNetwork is set.";
1262  }
1263  log_info(LD_DIR, "Delaying dir fetches (DisableNetwork is set)");
1264  return 1;
1265  }
1266 
1267  if (we_are_hibernating()) {
1268  if (msg_out) {
1269  *msg_out = "We are hibernating or shutting down.";
1270  }
1271  log_info(LD_DIR, "Delaying dir fetches (Hibernating or shutting down)");
1272  return 1;
1273  }
1274 
1275  if (options->UseBridges) {
1276  /* If we know that none of our bridges can possibly work, avoid fetching
1277  * directory documents. But if some of them might work, try again. */
1278  if (num_bridges_usable(1) == 0) {
1279  if (msg_out) {
1280  *msg_out = "No running bridges";
1281  }
1282  log_info(LD_DIR, "Delaying dir fetches (no running bridges known)");
1283  return 1;
1284  }
1285 
1287  if (msg_out) {
1288  *msg_out = "Pluggable transport proxies still configuring";
1289  }
1290  log_info(LD_DIR, "Delaying dir fetches (pt proxies still configuring)");
1291  return 1;
1292  }
1293  }
1294 
1295  return 0;
1296 }
1297 
1298 /** Launch requests for networkstatus documents as appropriate. This is called
1299  * when we retry all the connections on a SIGHUP and periodically by a Periodic
1300  * event which checks whether we want to download any networkstatus documents.
1301  */
1302 void
1304 {
1305  const or_options_t *options = get_options();
1306  if (should_delay_dir_fetches(options, NULL))
1307  return;
1308  /** Launch a consensus download request, we will wait for the consensus to
1309  * download and when it completes we will launch a certificate download
1310  * request. */
1312 }
1313 
1314 /** Launch requests as appropriate for missing directory authority
1315  * certificates. */
1316 void
1318 {
1319  int i;
1320  for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
1321  if (consensus_waiting_for_certs[i].consensus)
1323  now, NULL);
1324  }
1325 
1330 }
1331 
1332 /** Return 1 if we have a consensus but we don't have enough certificates
1333  * to start using it yet. */
1334 int
1336 {
1338  ? 1 : 0;
1339 }
1340 
1341 /** Look up the currently active (depending on bootstrap status) download
1342  * status for this consensus flavor and return a pointer to it.
1343  */
1346 {
1347  download_status_t *dl = NULL;
1348  const int we_are_bootstrapping =
1350 
1351  if ((int)flavor <= N_CONSENSUS_FLAVORS) {
1352  dl = &((we_are_bootstrapping ?
1353  consensus_bootstrap_dl_status : consensus_dl_status)[flavor]);
1354  }
1355 
1356  return dl;
1357 }
1358 
1359 /** Look up the bootstrap download status for this consensus flavor
1360  * and return a pointer to it. */
1363 {
1364  download_status_t *dl = NULL;
1365 
1366  if ((int)flavor <= N_CONSENSUS_FLAVORS) {
1367  dl = &(consensus_bootstrap_dl_status[flavor]);
1368  }
1369 
1370  return dl;
1371 }
1372 
1373 /** Look up the running (non-bootstrap) download status for this consensus
1374  * flavor and return a pointer to it. */
1377 {
1378  download_status_t *dl = NULL;
1379 
1380  if ((int)flavor <= N_CONSENSUS_FLAVORS) {
1381  dl = &(consensus_dl_status[flavor]);
1382  }
1383 
1384  return dl;
1385 }
1386 
1387 /** Return the most recent consensus that we have downloaded, or NULL if we
1388  * don't have one. May return future or expired consensuses. */
1391 {
1393  return current_md_consensus;
1394  else
1395  return current_ns_consensus;
1396 }
1397 
1398 /** Return the latest consensus we have whose flavor matches <b>f</b>, or NULL
1399  * if we don't have one. May return future or expired consensuses. */
1402 {
1403  if (f == FLAV_NS)
1404  return current_ns_consensus;
1405  else if (f == FLAV_MICRODESC)
1406  return current_md_consensus;
1407  else {
1408  tor_assert(0);
1409  return NULL;
1410  }
1411 }
1412 
1413 /** Return the most recent consensus that we have downloaded, or NULL if it is
1414  * no longer live. */
1417 {
1419  if (ns && networkstatus_is_live(ns, now))
1420  return ns;
1421  else
1422  return NULL;
1423 }
1424 
1425 /** Given a consensus in <b>ns</b>, return true iff currently live and
1426  * unexpired. */
1427 int
1429 {
1430  return (ns->valid_after <= now && now <= ns->valid_until);
1431 }
1432 
1433 /** Determine if <b>consensus</b> is valid, or expired recently enough, or not
1434  * too far in the future, so that we can still use it.
1435  *
1436  * Return 1 if the consensus is reasonably live, or 0 if it is too old or
1437  * too new.
1438  */
1439 int
1441  time_t now)
1442 {
1443  if (BUG(!consensus))
1444  return 0;
1445 
1447  now) &&
1449  now);
1450 }
1451 
1452 #define REASONABLY_LIVE_TIME (24*60*60)
1453 
1454 /** As networkstatus_consensus_reasonably_live, but takes a valid_after
1455  * time, and checks to see if it is in the past, or not too far in the future.
1456  */
1457 int
1459  time_t now)
1460 {
1461  return (now >= valid_after - REASONABLY_LIVE_TIME);
1462 }
1463 
1464 /** As networkstatus_consensus_reasonably_live, but takes a valid_until
1465  * time, and checks to see if it is in the future, or not too far in the past.
1466  */
1467 int
1469  time_t now)
1470 {
1471  return (now <= valid_until + REASONABLY_LIVE_TIME);
1472 }
1473 
1474 /** As networkstatus_get_live_consensus(), but is way more tolerant of expired
1475  * and future consensuses. */
1478 {
1479  networkstatus_t *consensus =
1481  if (consensus &&
1483  return consensus;
1484  else
1485  return NULL;
1486 }
1487 
1488 /** Check if we need to download a consensus during tor's bootstrap phase.
1489  * If we have no consensus, or our consensus is unusably old, return 1.
1490  * As soon as we have received a consensus, return 0, even if we don't have
1491  * enough certificates to validate it.
1492  * If a fallback directory gives us a consensus we can never get certs for,
1493  * check_consensus_waiting_for_certs() will wait 20 minutes before failing
1494  * the cert downloads. After that, a new consensus will be fetched from a
1495  * randomly chosen fallback. */
1496 MOCK_IMPL(int,
1498 {
1499  /* If we have a validated, reasonably live consensus, we're not
1500  * bootstrapping a consensus at all. */
1502  now,
1504  return 0;
1505  }
1506 
1507  /* If we have a consensus, but we're waiting for certificates,
1508  * we're not waiting for a consensus download while bootstrapping. */
1510  return 0;
1511  }
1512 
1513  /* If we have no consensus, or our consensus is very old, we are
1514  * bootstrapping, and we need to download a consensus. */
1515  return 1;
1516 }
1517 
1518 /** Check if we can use multiple directories for a consensus download.
1519  * Only clients (including bridge relays, which act like clients) benefit
1520  * from multiple simultaneous consensus downloads. */
1521 int
1523  const or_options_t *options)
1524 {
1525  /* If we are a client, bridge, bridge client, or hidden service */
1526  return !public_server_mode(options);
1527 }
1528 
1529 /** Check if we can use fallback directory mirrors for a consensus download.
1530  * If we have fallbacks and don't want to fetch from the authorities,
1531  * we can use them. */
1532 MOCK_IMPL(int,
1534 {
1535  /* The list length comparisons are a quick way to check if we have any
1536  * non-authority fallback directories. If we ever have any authorities that
1537  * aren't fallback directories, we will need to change this code. */
1538  tor_assert(smartlist_len(router_get_fallback_dir_servers())
1539  >= smartlist_len(router_get_trusted_dir_servers()));
1540  /* If we don't fetch from the authorities, and we have additional mirrors,
1541  * we can use them. */
1542  return (!dirclient_fetches_from_authorities(options)
1543  && (smartlist_len(router_get_fallback_dir_servers())
1544  > smartlist_len(router_get_trusted_dir_servers())));
1545 }
1546 
1547 /* Is there a consensus fetch for flavor <b>resource</b> that's far
1548  * enough along to be attached to a circuit? */
1549 int
1550 networkstatus_consensus_is_already_downloading(const char *resource)
1551 {
1552  int answer = 0;
1553 
1554  /* First, get a list of all the dir conns that are fetching a consensus,
1555  * fetching *this* consensus, and are in state "reading" (meaning they
1556  * have already flushed their request onto the socks connection). */
1557  smartlist_t *fetching_conns =
1560 
1561  /* Then, walk through each conn, to see if its linked socks connection
1562  * is in an attached state. We have to check this separately, since with
1563  * the optimistic data feature, fetches can send their request to the
1564  * socks connection and go into state 'reading', even before they're
1565  * attached to any circuit. */
1566  SMARTLIST_FOREACH_BEGIN(fetching_conns, dir_connection_t *, dirconn) {
1567  /* Do any of these other dir conns have a linked socks conn that is
1568  * attached to a circuit already? */
1569  connection_t *base = TO_CONN(dirconn);
1570  if (base->linked_conn &&
1571  base->linked_conn->type == CONN_TYPE_AP &&
1573  answer = 1;
1574  break; /* stop looping, because we know the answer will be yes */
1575  }
1576  } SMARTLIST_FOREACH_END(dirconn);
1577  smartlist_free(fetching_conns);
1578 
1579  return answer;
1580 }
1581 
1582 /** Given two router status entries for the same router identity, return 1
1583  * if the contents have changed between them. Otherwise, return 0.
1584  * It only checks for fields that are output by control port.
1585  * This should be kept in sync with the struct routerstatus_t
1586  * and the printing function routerstatus_format_entry in
1587  * NS_CONTROL_PORT mode.
1588  **/
1589 STATIC int
1591  const routerstatus_t *b)
1592 {
1594 
1595  return strcmp(a->nickname, b->nickname) ||
1597  !tor_addr_eq(&a->ipv4_addr, &b->ipv4_addr) ||
1598  a->ipv4_orport != b->ipv4_orport ||
1599  a->ipv4_dirport != b->ipv4_dirport ||
1600  a->is_authority != b->is_authority ||
1601  a->is_exit != b->is_exit ||
1602  a->is_stable != b->is_stable ||
1603  a->is_fast != b->is_fast ||
1605  a->is_named != b->is_named ||
1606  a->is_unnamed != b->is_unnamed ||
1607  a->is_valid != b->is_valid ||
1609  a->is_bad_exit != b->is_bad_exit ||
1610  a->is_hs_dir != b->is_hs_dir ||
1611  a->is_staledesc != b->is_staledesc ||
1612  a->has_bandwidth != b->has_bandwidth ||
1613  a->published_on != b->published_on ||
1614  a->ipv6_orport != b->ipv6_orport ||
1615  a->is_v2_dir != b->is_v2_dir ||
1616  a->bandwidth_kb != b->bandwidth_kb ||
1617  tor_addr_compare(&a->ipv6_addr, &b->ipv6_addr, CMP_EXACT);
1618 }
1619 
1620 /** Notify controllers of any router status entries that changed between
1621  * <b>old_c</b> and <b>new_c</b>. */
1622 static void
1624  const networkstatus_t *new_c)
1625 {
1626  smartlist_t *changed;
1627  if (old_c == new_c)
1628  return;
1629 
1630  /* tell the controller exactly which relays are still listed, as well
1631  * as what they're listed as */
1633 
1634  if (!control_event_is_interesting(EVENT_NS))
1635  return;
1636 
1637  if (!old_c) {
1639  return;
1640  }
1641  changed = smartlist_new();
1642 
1643  SMARTLIST_FOREACH_JOIN(
1644  old_c->routerstatus_list, const routerstatus_t *, rs_old,
1645  new_c->routerstatus_list, const routerstatus_t *, rs_new,
1646  tor_memcmp(rs_old->identity_digest,
1647  rs_new->identity_digest, DIGEST_LEN),
1648  smartlist_add(changed, (void*) rs_new)) {
1649  if (routerstatus_has_visibly_changed(rs_old, rs_new))
1650  smartlist_add(changed, (void*)rs_new);
1651  } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
1652 
1654  smartlist_free(changed);
1655 }
1656 
1657 /* Called before the consensus changes from old_c to new_c. */
1658 static void
1659 notify_before_networkstatus_changes(const networkstatus_t *old_c,
1660  const networkstatus_t *new_c)
1661 {
1663  dos_consensus_has_changed(new_c);
1664  relay_consensus_has_changed(new_c);
1666 }
1667 
1668 /* Called after a new consensus has been put in the global state. It is safe
1669  * to use the consensus getters in this function. */
1670 static void
1671 notify_after_networkstatus_changes(void)
1672 {
1674  const or_options_t *options = get_options();
1675  const time_t now = approx_time();
1676 
1678 
1679  /* The "current" consensus has just been set and it is a usable flavor so
1680  * the first thing we need to do is recalculate the voting schedule static
1681  * object so we can use the timings in there needed by some subsystems
1682  * such as hidden service and shared random. */
1683  dirauth_sched_recalculate_timing(options, now);
1684  reschedule_dirvote(options);
1685 
1687 
1689 
1690  /* Change the cell EWMA settings */
1691  cmux_ewma_set_options(options, c);
1692 
1693  /* XXXX this call might be unnecessary here: can changing the
1694  * current consensus really alter our view of any OR's rate limits? */
1696 
1702 }
1703 
1704 /** Copy all the ancillary information (like router download status and so on)
1705  * from <b>old_c</b> to <b>new_c</b>. */
1706 static void
1708  const networkstatus_t *old_c)
1709 {
1710  if (old_c == new_c)
1711  return;
1712  if (!old_c || !smartlist_len(old_c->routerstatus_list))
1713  return;
1714 
1715  SMARTLIST_FOREACH_JOIN(old_c->routerstatus_list, routerstatus_t *, rs_old,
1716  new_c->routerstatus_list, routerstatus_t *, rs_new,
1717  tor_memcmp(rs_old->identity_digest,
1718  rs_new->identity_digest, DIGEST_LEN),
1719  STMT_NIL) {
1720  /* Okay, so we're looking at the same identity. */
1721  rs_new->last_dir_503_at = rs_old->last_dir_503_at;
1722 
1723  if (tor_memeq(rs_old->descriptor_digest, rs_new->descriptor_digest,
1724  DIGEST256_LEN)) {
1725  /* And the same descriptor too! */
1726  memcpy(&rs_new->dl_status, &rs_old->dl_status,sizeof(download_status_t));
1727  }
1728  } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
1729 }
1730 
1731 #ifdef TOR_UNIT_TESTS
1732 /**Accept a <b>flavor</b> consensus <b>c</b> without any additional
1733  * validation. This is exclusively for unit tests.
1734  * We copy any ancillary information from a pre-existing consensus
1735  * and then free the current one and replace it with the newly
1736  * provided instance. Returns -1 on unrecognized flavor, 0 otherwise.
1737  */
1738 int
1739 networkstatus_set_current_consensus_from_ns(networkstatus_t *c,
1740  const char *flavor)
1741 {
1742  int flav = networkstatus_parse_flavor_name(flavor);
1743  switch (flav) {
1744  case FLAV_NS:
1745  if (current_ns_consensus) {
1747  networkstatus_vote_free(current_ns_consensus);
1748  }
1750  break;
1751  case FLAV_MICRODESC:
1752  if (current_md_consensus) {
1754  networkstatus_vote_free(current_md_consensus);
1755  }
1757  break;
1758  }
1759  return current_md_consensus ? 0 : -1;
1760 }
1761 #endif /* defined(TOR_UNIT_TESTS) */
1762 
1763 /**
1764  * Helper: Read the current consensus of type <b>flavor</b> from
1765  * <b>fname</b>. Flags and return values are as for
1766  * networkstatus_set_current_consensus().
1767  **/
1768 static int
1769 reload_consensus_from_file(const char *fname,
1770  const char *flavor,
1771  unsigned flags,
1772  const char *source_dir)
1773 {
1774  tor_mmap_t *map = tor_mmap_file(fname);
1775  if (!map)
1776  return 0;
1777 
1778  int rv = networkstatus_set_current_consensus(map->data, map->size,
1779  flavor, flags, source_dir);
1780 #ifdef _WIN32
1781  if (rv < 0 && tor_memstr(map->data, map->size, "\r\n")) {
1782  log_notice(LD_GENERAL, "Looks like the above failures are probably "
1783  "because of a CRLF in consensus file %s; falling back to "
1784  "read_file_to_string. Nothing to worry about: this file "
1785  "was probably saved by an earlier version of Tor.",
1786  escaped(fname));
1787  char *content = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
1788  rv = networkstatus_set_current_consensus(content, strlen(content),
1789  flavor, flags, source_dir);
1790  tor_free(content);
1791  }
1792 #endif /* defined(_WIN32) */
1793  if (rv < -1) {
1794  log_warn(LD_GENERAL, "Couldn't set consensus from cache file %s",
1795  escaped(fname));
1796  }
1797  tor_munmap_file(map);
1798  return rv;
1799 }
1800 
1801 /**
1802  * Helper for handle_missing_protocol_warning: handles either the
1803  * client case (if <b>is_client</b> is set) or the server case otherwise.
1804  */
1805 static void
1807  int is_client)
1808 {
1809  char *protocol_warning = NULL;
1810 
1811  int should_exit = networkstatus_check_required_protocols(c,
1812  is_client,
1813  &protocol_warning);
1814  if (protocol_warning) {
1815  tor_log(should_exit ? LOG_ERR : LOG_WARN,
1816  LD_GENERAL,
1817  "%s", protocol_warning);
1818  }
1819  if (should_exit) {
1820  tor_assert_nonfatal(protocol_warning);
1821  }
1822  tor_free(protocol_warning);
1823  if (should_exit)
1824  exit(1); // XXXX bad exit: should return from main.
1825 }
1826 
1827 /** Called when we have received a networkstatus <b>c</b>. If there are
1828  * any _required_ protocols we are missing, log an error and exit
1829  * immediately. If there are any _recommended_ protocols we are missing,
1830  * warn. */
1831 static void
1833  const or_options_t *options)
1834 {
1835  const int is_server = server_mode(options);
1836  const int is_client = options_any_client_port_set(options) || !is_server;
1837 
1838  if (is_server)
1840  if (is_client)
1842 }
1843 
1844 /**
1845  * Check whether we received a consensus that appears to be coming
1846  * from the future. Because we implicitly trust the directory
1847  * authorities' idea of the current time, we produce a warning if we
1848  * get an early consensus.
1849  *
1850  * If we got a consensus that is time stamped far in the past, that
1851  * could simply have come from a stale cache. Possible ways to get a
1852  * consensus from the future can include:
1853  *
1854  * - enough directory authorities have wrong clocks
1855  * - directory authorities collude to produce misleading time stamps
1856  * - our own clock is wrong (this is by far the most likely)
1857  *
1858  * We neglect highly improbable scenarios that involve actual time
1859  * travel.
1860  */
1861 STATIC void
1862 warn_early_consensus(const networkstatus_t *c, const char *flavor,
1863  time_t now)
1864 {
1865  char tbuf[ISO_TIME_LEN+1];
1866  char dbuf[64];
1867  long delta = now - c->valid_after;
1868  char *flavormsg = NULL;
1869 
1870 /** If a consensus appears more than this many seconds before it could
1871  * possibly be a sufficiently-signed consensus, declare that our clock
1872  * is skewed. */
1873 #define EARLY_CONSENSUS_NOTICE_SKEW 60
1874 
1875  /* We assume that if a majority of dirauths have accurate clocks,
1876  * the earliest that a dirauth with a skewed clock could possibly
1877  * publish a sufficiently-signed consensus is (valid_after -
1878  * dist_seconds). Before that time, the skewed dirauth would be
1879  * unable to obtain enough authority signatures for the consensus to
1880  * be valid. */
1881  if (now >= c->valid_after - c->dist_seconds - EARLY_CONSENSUS_NOTICE_SKEW)
1882  return;
1883 
1884  format_iso_time(tbuf, c->valid_after);
1885  format_time_interval(dbuf, sizeof(dbuf), delta);
1886  log_warn(LD_GENERAL, "Our clock is %s behind the time published in the "
1887  "consensus network status document (%s UTC). Tor needs an "
1888  "accurate clock to work correctly. Please check your time and "
1889  "date settings!", dbuf, tbuf);
1890  tor_asprintf(&flavormsg, "%s flavor consensus", flavor);
1891  clock_skew_warning(NULL, delta, 1, LD_GENERAL, flavormsg, "CONSENSUS");
1892  tor_free(flavormsg);
1893 }
1894 
1895 /** Try to replace the current cached v3 networkstatus with the one in
1896  * <b>consensus</b>. If we don't have enough certificates to validate it,
1897  * store it in consensus_waiting_for_certs and launch a certificate fetch.
1898  *
1899  * If flags & NSSET_FROM_CACHE, this networkstatus has come from the disk
1900  * cache. If flags & NSSET_WAS_WAITING_FOR_CERTS, this networkstatus was
1901  * already received, but we were waiting for certificates on it. If flags &
1902  * NSSET_DONT_DOWNLOAD_CERTS, do not launch certificate downloads as needed.
1903  * If flags & NSSET_ACCEPT_OBSOLETE, then we should be willing to take this
1904  * consensus, even if it comes from many days in the past.
1905  *
1906  * If source_dir is non-NULL, it's the identity digest for a directory that
1907  * we've just successfully retrieved a consensus or certificates from, so try
1908  * it first to fetch any missing certificates.
1909  *
1910  * Return 0 on success, <0 on failure. On failure, caller should increment
1911  * the failure count as appropriate.
1912  *
1913  * We return -1 for mild failures that don't need to be reported to the
1914  * user, and -2 for more serious problems.
1915  */
1916 int
1918  size_t consensus_len,
1919  const char *flavor,
1920  unsigned flags,
1921  const char *source_dir)
1922 {
1923  networkstatus_t *c=NULL;
1924  int r, result = -1;
1925  time_t now = approx_time();
1926  const or_options_t *options = get_options();
1927  char *unverified_fname = NULL, *consensus_fname = NULL;
1928  int flav = networkstatus_parse_flavor_name(flavor);
1929  const unsigned from_cache = flags & NSSET_FROM_CACHE;
1930  const unsigned was_waiting_for_certs = flags & NSSET_WAS_WAITING_FOR_CERTS;
1931  const unsigned dl_certs = !(flags & NSSET_DONT_DOWNLOAD_CERTS);
1932  const unsigned accept_obsolete = flags & NSSET_ACCEPT_OBSOLETE;
1933  const unsigned require_flavor = flags & NSSET_REQUIRE_FLAVOR;
1934  const common_digests_t *current_digests = NULL;
1935  consensus_waiting_for_certs_t *waiting = NULL;
1936  time_t current_valid_after = 0;
1937  int free_consensus = 1; /* Free 'c' at the end of the function */
1938  int checked_protocols_already = 0;
1939 
1940  if (flav < 0) {
1941  /* XXXX we don't handle unrecognized flavors yet. */
1942  log_warn(LD_BUG, "Unrecognized consensus flavor %s", flavor);
1943  return -2;
1944  }
1945 
1946  /* Make sure it's parseable. */
1948  consensus_len,
1949  NULL, NS_TYPE_CONSENSUS);
1950  if (!c) {
1951  log_warn(LD_DIR, "Unable to parse networkstatus consensus");
1952  result = -2;
1953  goto done;
1954  }
1955 
1956  if (from_cache && !was_waiting_for_certs) {
1957  /* We previously stored this; check _now_ to make sure that version-kills
1958  * really work. This happens even before we check signatures: we did so
1959  * before when we stored this to disk. This does mean an attacker who can
1960  * write to the datadir can make us not start: such an attacker could
1961  * already harm us by replacing our guards, which would be worse. */
1962  checked_protocols_already = 1;
1963  handle_missing_protocol_warning(c, options);
1964  }
1965 
1966  if ((int)c->flavor != flav) {
1967  /* This wasn't the flavor we thought we were getting. */
1968  if (require_flavor) {
1969  log_warn(LD_DIR, "Got consensus with unexpected flavor %s (wanted %s)",
1971  goto done;
1972  }
1973  flav = c->flavor;
1974  flavor = networkstatus_get_flavor_name(flav);
1975  }
1976 
1977  if (flav != usable_consensus_flavor() &&
1978  !we_want_to_fetch_flavor(options, flav)) {
1979  /* This consensus is totally boring to us: we won't use it, we didn't want
1980  * it, and we won't serve it. Drop it. */
1981  goto done;
1982  }
1983 
1984  if (from_cache && !accept_obsolete &&
1986  log_info(LD_DIR, "Loaded an expired consensus. Discarding.");
1987  goto done;
1988  }
1989 
1990  if (!strcmp(flavor, "ns")) {
1991  consensus_fname = get_cachedir_fname("cached-consensus");
1992  unverified_fname = get_cachedir_fname("unverified-consensus");
1993  if (current_ns_consensus) {
1994  current_digests = &current_ns_consensus->digests;
1995  current_valid_after = current_ns_consensus->valid_after;
1996  }
1997  } else if (!strcmp(flavor, "microdesc")) {
1998  consensus_fname = get_cachedir_fname("cached-microdesc-consensus");
1999  unverified_fname = get_cachedir_fname("unverified-microdesc-consensus");
2000  if (current_md_consensus) {
2001  current_digests = &current_md_consensus->digests;
2002  current_valid_after = current_md_consensus->valid_after;
2003  }
2004  } else {
2006  result = -2;
2007  goto done;
2008  }
2009 
2010  if (current_digests &&
2011  tor_memeq(&c->digests, current_digests, sizeof(c->digests))) {
2012  /* We already have this one. That's a failure. */
2013  log_info(LD_DIR, "Got a %s consensus we already have", flavor);
2014  goto done;
2015  }
2016 
2017  if (current_valid_after && c->valid_after <= current_valid_after) {
2018  /* We have a newer one. There's no point in accepting this one,
2019  * even if it's great. */
2020  log_info(LD_DIR, "Got a %s consensus at least as old as the one we have",
2021  flavor);
2022  goto done;
2023  }
2024 
2025  /* Make sure it's signed enough. */
2026  if ((r=networkstatus_check_consensus_signature(c, 1))<0) {
2027  if (r == -1) {
2028  /* Okay, so it _might_ be signed enough if we get more certificates. */
2029  if (!was_waiting_for_certs) {
2030  log_info(LD_DIR,
2031  "Not enough certificates to check networkstatus consensus");
2032  }
2033  if (!current_valid_after ||
2034  c->valid_after > current_valid_after) {
2035  waiting = &consensus_waiting_for_certs[flav];
2036  networkstatus_vote_free(waiting->consensus);
2037  waiting->consensus = c;
2038  free_consensus = 0;
2039  waiting->set_at = now;
2040  waiting->dl_failed = 0;
2041  if (!from_cache) {
2042  write_bytes_to_file(unverified_fname, consensus, consensus_len, 1);
2043  }
2044  if (dl_certs)
2045  authority_certs_fetch_missing(c, now, source_dir);
2046  /* This case is not a success or a failure until we get the certs
2047  * or fail to get the certs. */
2048  result = 0;
2049  } else {
2050  /* Even if we had enough signatures, we'd never use this as the
2051  * latest consensus. */
2052  if (was_waiting_for_certs && from_cache)
2053  if (unlink(unverified_fname) != 0) {
2054  log_debug(LD_FS,
2055  "Failed to unlink %s: %s",
2056  unverified_fname, strerror(errno));
2057  }
2058  }
2059  goto done;
2060  } else {
2061  /* This can never be signed enough: Kill it. */
2062  if (!was_waiting_for_certs) {
2063  log_warn(LD_DIR, "Not enough good signatures on networkstatus "
2064  "consensus");
2065  result = -2;
2066  }
2067  if (was_waiting_for_certs && (r < -1) && from_cache) {
2068  if (unlink(unverified_fname) != 0) {
2069  log_debug(LD_FS,
2070  "Failed to unlink %s: %s",
2071  unverified_fname, strerror(errno));
2072  }
2073  }
2074  goto done;
2075  }
2076  }
2077 
2078  /* Signatures from the consensus are verified */
2079  if (from_cache && was_waiting_for_certs) {
2080  /* We check if the consensus is loaded from disk cache and that it
2081  * it is an unverified consensus. If it is unverified, rename it to
2082  * cached-*-consensus since it has been verified. */
2083  log_info(LD_DIR, "Unverified consensus signatures verified.");
2084  tor_rename(unverified_fname, consensus_fname);
2085  }
2086 
2087  if (!from_cache && flav == usable_consensus_flavor())
2088  control_event_client_status(LOG_NOTICE, "CONSENSUS_ARRIVED");
2089 
2090  if (!checked_protocols_already) {
2091  handle_missing_protocol_warning(c, options);
2092  }
2093 
2094  /* Are we missing any certificates at all? */
2095  if (r != 1 && dl_certs)
2096  authority_certs_fetch_missing(c, now, source_dir);
2097 
2098  const int is_usable_flavor = flav == usable_consensus_flavor();
2099 
2100  /* Before we switch to the new consensus, notify that we are about to change
2101  * it using the old consensus and the new one. */
2102  if (is_usable_flavor) {
2103  notify_before_networkstatus_changes(networkstatus_get_latest_consensus(),
2104  c);
2105  }
2106  if (flav == FLAV_NS) {
2107  if (current_ns_consensus) {
2109  networkstatus_vote_free(current_ns_consensus);
2110  /* Defensive programming : we should set current_ns_consensus very soon
2111  * but we're about to call some stuff in the meantime, and leaving this
2112  * dangling pointer around has proven to be trouble. */
2113  current_ns_consensus = NULL;
2114  }
2116  free_consensus = 0; /* avoid free */
2117  } else if (flav == FLAV_MICRODESC) {
2118  if (current_md_consensus) {
2120  networkstatus_vote_free(current_md_consensus);
2121  /* more defensive programming */
2122  current_md_consensus = NULL;
2123  }
2125  free_consensus = 0; /* avoid free */
2126  }
2127 
2128  waiting = &consensus_waiting_for_certs[flav];
2129  if (waiting->consensus &&
2130  waiting->consensus->valid_after <= c->valid_after) {
2131  networkstatus_vote_free(waiting->consensus);
2132  waiting->consensus = NULL;
2133  waiting->set_at = 0;
2134  waiting->dl_failed = 0;
2135  if (unlink(unverified_fname) != 0) {
2136  log_debug(LD_FS,
2137  "Failed to unlink %s: %s",
2138  unverified_fname, strerror(errno));
2139  }
2140  }
2141 
2142  if (is_usable_flavor) {
2143  /* Notify that we just changed the consensus so the current global value
2144  * can be looked at. */
2145  notify_after_networkstatus_changes();
2146  }
2147 
2148  /* Reset the failure count only if this consensus is actually valid. */
2149  if (c->valid_after <= now && now <= c->valid_until) {
2151  } else {
2152  if (!from_cache)
2154  }
2155 
2156  if (we_want_to_fetch_flavor(options, flav)) {
2157  if (dir_server_mode(get_options())) {
2159  consensus_len,
2160  flavor,
2161  &c->digests,
2163  c->valid_after);
2164 
2165  consdiffmgr_add_consensus(consensus, consensus_len, c);
2166  }
2167  }
2168 
2169  if (!from_cache) {
2170  write_bytes_to_file(consensus_fname, consensus, consensus_len, 1);
2171  }
2172 
2173  warn_early_consensus(c, flavor, now);
2174 
2175  /* We got a new consensus. Reset our md fetch fail cache */
2177 
2179 
2180  result = 0;
2181  done:
2182  if (free_consensus)
2183  networkstatus_vote_free(c);
2184  tor_free(consensus_fname);
2185  tor_free(unverified_fname);
2186  return result;
2187 }
2188 
2189 /** Called when we have gotten more certificates: see whether we can
2190  * now verify a pending consensus.
2191  *
2192  * If source_dir is non-NULL, it's the identity digest for a directory that
2193  * we've just successfully retrieved certificates from, so try it first to
2194  * fetch any missing certificates.
2195  */
2196 void
2197 networkstatus_note_certs_arrived(const char *source_dir)
2198 {
2199  int i;
2200  for (i=0; i<N_CONSENSUS_FLAVORS; ++i) {
2201  const char *flavor_name = networkstatus_get_flavor_name(i);
2203  if (!waiting->consensus)
2204  continue;
2205  if (networkstatus_check_consensus_signature(waiting->consensus, 0)>=0) {
2206  char *fname = networkstatus_get_cache_fname(i, flavor_name, 1);
2207  reload_consensus_from_file(fname, flavor_name,
2208  NSSET_WAS_WAITING_FOR_CERTS, source_dir);
2209  tor_free(fname);
2210  }
2211  }
2212 }
2213 
2214 /** If the network-status list has changed since the last time we called this
2215  * function, update the status of every routerinfo from the network-status
2216  * list. If <b>dir_version</b> is 2, it's a v2 networkstatus that changed.
2217  * If <b>dir_version</b> is 3, it's a v3 consensus that changed.
2218  */
2219 void
2220 routers_update_all_from_networkstatus(time_t now, int dir_version)
2221 {
2224  FLAV_NS);
2225 
2226  if (!consensus || dir_version < 3) /* nothing more we should do */
2227  return;
2228 
2229  /* calls router_dir_info_changed() when it's done -- more routers
2230  * might be up or down now, which might affect whether there's enough
2231  * directory info. */
2233 
2235  ri->cache_info.routerlist_index = ri_sl_idx);
2236  if (rl->old_routers)
2238 
2240  int is_server = server_mode(get_options());
2241  version_status_t status;
2242  const char *recommended = is_server ?
2243  consensus->server_versions : consensus->client_versions;
2244  status = tor_version_is_obsolete(VERSION, recommended);
2245 
2246  if (status == VS_RECOMMENDED) {
2247  log_info(LD_GENERAL, "The directory authorities say my version is ok.");
2248  } else if (status == VS_EMPTY) {
2249  log_info(LD_GENERAL,
2250  "The directory authorities don't recommend any versions.");
2251  } else if (status == VS_NEW || status == VS_NEW_IN_SERIES) {
2253  log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
2254  "recommended version%s, according to the directory "
2255  "authorities. Recommended versions are: %s",
2256  VERSION,
2257  status == VS_NEW_IN_SERIES ? " in its series" : "",
2258  recommended);
2260  control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
2261  "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
2262  VERSION, "NEW", recommended);
2263  }
2264  } else {
2265  log_warn(LD_GENERAL, "Please upgrade! "
2266  "This version of Tor (%s) is %s, according to the directory "
2267  "authorities. Recommended versions are: %s",
2268  VERSION,
2269  status == VS_OLD ? "obsolete" : "not recommended",
2270  recommended);
2272  control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
2273  "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
2274  VERSION, status == VS_OLD ? "OBSOLETE" : "UNRECOMMENDED",
2275  recommended);
2276  }
2277  }
2278 }
2279 
2280 /** Given a list <b>routers</b> of routerinfo_t *, update each status field
2281  * according to our current consensus networkstatus. May re-order
2282  * <b>routers</b>. */
2283 void
2285  int reset_failures)
2286 {
2287  const or_options_t *options = get_options();
2288  int authdir = authdir_mode_v3(options);
2290  if (!ns || !smartlist_len(ns->routerstatus_list))
2291  return;
2292 
2293  routers_sort_by_identity(routers);
2294 
2295  SMARTLIST_FOREACH_JOIN(ns->routerstatus_list, routerstatus_t *, rs,
2296  routers, routerinfo_t *, router,
2297  tor_memcmp(rs->identity_digest,
2298  router->cache_info.identity_digest, DIGEST_LEN),
2299  {
2300  }) {
2301  /* Is it the same descriptor, or only the same identity? */
2302  if (tor_memeq(router->cache_info.signed_descriptor_digest,
2303  rs->descriptor_digest, DIGEST_LEN)) {
2304  if (ns->valid_until > router->cache_info.last_listed_as_valid_until)
2305  router->cache_info.last_listed_as_valid_until = ns->valid_until;
2306  }
2307 
2308  if (authdir) {
2309  /* If we _are_ an authority, we should check whether this router
2310  * is one that will cause us to need a reachability test. */
2311  routerinfo_t *old_router =
2312  router_get_mutable_by_digest(router->cache_info.identity_digest);
2313  if (old_router != router) {
2314  router->needs_retest_if_added =
2315  dirserv_should_launch_reachability_test(router, old_router);
2316  }
2317  }
2318  if (reset_failures) {
2319  download_status_reset(&rs->dl_status);
2320  }
2321  } SMARTLIST_FOREACH_JOIN_END(rs, router);
2322 
2324 }
2325 
2326 /** Given a list of signed_descriptor_t, update their fields (mainly, when
2327  * they were last listed) from the most recent consensus. */
2328 void
2330 {
2332  if (!ns)
2333  return;
2334 
2335  if (!ns->desc_digest_map) {
2336  char dummy[DIGEST_LEN];
2337  /* instantiates the digest map. */
2338  memset(dummy, 0, sizeof(dummy));
2340  }
2342  {
2343  const routerstatus_t *rs = digestmap_get(ns->desc_digest_map,
2344  d->signed_descriptor_digest);
2345  if (rs) {
2346  if (ns->valid_until > d->last_listed_as_valid_until)
2347  d->last_listed_as_valid_until = ns->valid_until;
2348  }
2349  });
2350 }
2351 
2352 /** Generate networkstatus lines for a single routerstatus_t object, and
2353  * return the result in a newly allocated string. Used only by controller
2354  * interface (for now.) */
2355 char *
2357 {
2358  return routerstatus_format_entry(rs, NULL, NULL, NS_CONTROL_PORT,
2359  NULL);
2360 }
2361 
2362 /**
2363  * Extract status information from <b>ri</b> and from other authority
2364  * functions and store it in <b>rs</b>. <b>rs</b> is zeroed out before it is
2365  * set.
2366  *
2367  * We assume that node->is_running has already been set, e.g. by
2368  * dirserv_set_router_is_running(ri, now);
2369  */
2370 void
2372  const node_t *node,
2373  const routerinfo_t *ri)
2374 {
2375  memset(rs, 0, sizeof(routerstatus_t));
2376 
2377  rs->is_authority =
2378  router_digest_is_trusted_dir(ri->cache_info.identity_digest);
2379 
2380  /* Set by compute_performance_thresholds or from consensus */
2381  rs->is_exit = node->is_exit;
2382  rs->is_stable = node->is_stable;
2383  rs->is_fast = node->is_fast;
2384  rs->is_flagged_running = node->is_running;
2385  rs->is_valid = node->is_valid;
2387  rs->is_bad_exit = node->is_bad_exit;
2388  rs->is_hs_dir = node->is_hs_dir;
2389  rs->is_named = rs->is_unnamed = 0;
2390 
2391  rs->published_on = ri->cache_info.published_on;
2392  memcpy(rs->identity_digest, node->identity, DIGEST_LEN);
2393  memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest,
2394  DIGEST_LEN);
2395  tor_addr_copy(&rs->ipv4_addr, &ri->ipv4_addr);
2396  strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname));
2397  rs->ipv4_orport = ri->ipv4_orport;
2398  rs->ipv4_dirport = ri->ipv4_dirport;
2399  rs->is_v2_dir = ri->supports_tunnelled_dir_requests;
2400 
2401  tor_addr_copy(&rs->ipv6_addr, &ri->ipv6_addr);
2402  rs->ipv6_orport = ri->ipv6_orport;
2403 }
2404 
2405 /** Alloc and return a string describing routerstatuses for the most
2406  * recent info of each router we know about that is of purpose
2407  * <b>purpose_string</b>. Return NULL if unrecognized purpose.
2408  *
2409  * Right now this function is oriented toward listing bridges (you
2410  * shouldn't use this for general-purpose routers, since those
2411  * should be listed from the consensus, not from the routers list). */
2412 char *
2413 networkstatus_getinfo_by_purpose(const char *purpose_string, time_t now)
2414 {
2415  const time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
2416  char *answer;
2418  smartlist_t *statuses;
2419  const uint8_t purpose = router_purpose_from_string(purpose_string);
2420  routerstatus_t rs;
2421 
2422  if (purpose == ROUTER_PURPOSE_UNKNOWN) {
2423  log_info(LD_DIR, "Unrecognized purpose '%s' when listing router statuses.",
2424  purpose_string);
2425  return NULL;
2426  }
2427 
2428  statuses = smartlist_new();
2430  node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
2431  if (!node)
2432  continue;
2433  if (ri->cache_info.published_on < cutoff)
2434  continue;
2435  if (ri->purpose != purpose)
2436  continue;
2437  set_routerstatus_from_routerinfo(&rs, node, ri);
2439  } SMARTLIST_FOREACH_END(ri);
2440 
2441  answer = smartlist_join_strings(statuses, "", 0, NULL);
2442  SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
2443  smartlist_free(statuses);
2444  return answer;
2445 }
2446 
2447 /**
2448  * Search through a smartlist of "key=int32" strings for a value beginning
2449  * with "param_name=". If one is found, clip it to be between min_val and
2450  * max_val inclusive and return it. If one is not found, return
2451  * default_val.
2452  ***/
2453 static int32_t
2454 get_net_param_from_list(smartlist_t *net_params, const char *param_name,
2455  int32_t default_val, int32_t min_val, int32_t max_val)
2456 {
2457  int32_t res = default_val;
2458  size_t name_len = strlen(param_name);
2459 
2460  tor_assert(max_val > min_val);
2461  tor_assert(min_val <= default_val);
2462  tor_assert(max_val >= default_val);
2463 
2464  SMARTLIST_FOREACH_BEGIN(net_params, const char *, p) {
2465  if (!strcmpstart(p, param_name) && p[name_len] == '=') {
2466  int ok=0;
2467  long v = tor_parse_long(p+name_len+1, 10, INT32_MIN,
2468  INT32_MAX, &ok, NULL);
2469  if (ok) {
2470  res = (int32_t) v;
2471  break;
2472  }
2473  }
2474  } SMARTLIST_FOREACH_END(p);
2475 
2476  if (res < min_val) {
2477  log_warn(LD_DIR, "Consensus parameter %s is too small. Got %d, raising to "
2478  "%d.", param_name, res, min_val);
2479  res = min_val;
2480  } else if (res > max_val) {
2481  log_warn(LD_DIR, "Consensus parameter %s is too large. Got %d, capping to "
2482  "%d.", param_name, res, max_val);
2483  res = max_val;
2484  }
2485 
2486  tor_assert(res >= min_val);
2487  tor_assert(res <= max_val);
2488  return res;
2489 }
2490 
2491 /** Return the value of a integer parameter from the networkstatus <b>ns</b>
2492  * whose name is <b>param_name</b>. If <b>ns</b> is NULL, try loading the
2493  * latest consensus ourselves. Return <b>default_val</b> if no latest
2494  * consensus, or if it has no parameter called <b>param_name</b>.
2495  * Make sure the value parsed from the consensus is at least
2496  * <b>min_val</b> and at most <b>max_val</b> and raise/cap the parsed value
2497  * if necessary. */
2498 MOCK_IMPL(int32_t,
2499 networkstatus_get_param, (const networkstatus_t *ns, const char *param_name,
2500  int32_t default_val, int32_t min_val, int32_t max_val))
2501 {
2502  if (!ns) /* if they pass in null, go find it ourselves */
2504 
2505  if (!ns || !ns->net_params)
2506  return default_val;
2507 
2508  return get_net_param_from_list(ns->net_params, param_name,
2509  default_val, min_val, max_val);
2510 }
2511 
2512 /**
2513  * As networkstatus_get_param(), but check torrc_value before checking the
2514  * consensus. If torrc_value is in-range, then return it instead of the
2515  * value from the consensus.
2516  */
2517 int32_t
2519  int32_t torrc_value,
2520  const char *param_name,
2521  int32_t default_val,
2522  int32_t min_val, int32_t max_val)
2523 {
2524  if (torrc_value >= min_val && torrc_value <= max_val)
2525  return torrc_value;
2526  else
2527  return networkstatus_get_param(
2528  ns, param_name, default_val, min_val, max_val);
2529 }
2530 
2531 /**
2532  * Retrieve the consensus parameter that governs the
2533  * fixed-point precision of our network balancing 'bandwidth-weights'
2534  * (which are themselves integer consensus values). We divide them
2535  * by this value and ensure they never exceed this value.
2536  */
2537 int
2539 {
2540  return networkstatus_get_param(ns, "bwweightscale",
2542  BW_MIN_WEIGHT_SCALE,
2543  BW_MAX_WEIGHT_SCALE);
2544 }
2545 
2546 /** Return the value of a integer bw weight parameter from the networkstatus
2547  * <b>ns</b> whose name is <b>weight_name</b>. If <b>ns</b> is NULL, try
2548  * loading the latest consensus ourselves. Return <b>default_val</b> if no
2549  * latest consensus, or if it has no parameter called <b>weight_name</b>. */
2550 int32_t
2551 networkstatus_get_bw_weight(networkstatus_t *ns, const char *weight_name,
2552  int32_t default_val)
2553 {
2554  int32_t param;
2555  int max;
2556  if (!ns) /* if they pass in null, go find it ourselves */
2558 
2559  if (!ns || !ns->weight_params)
2560  return default_val;
2561 
2563  param = get_net_param_from_list(ns->weight_params, weight_name,
2564  default_val, -1,
2565  BW_MAX_WEIGHT_SCALE);
2566  if (param > max) {
2567  log_warn(LD_DIR, "Value of consensus weight %s was too large, capping "
2568  "to %d", weight_name, max);
2569  param = max;
2570  }
2571  return param;
2572 }
2573 
2574 /** Return the name of the consensus flavor <b>flav</b> as used to identify
2575  * the flavor in directory documents. */
2576 const char *
2578 {
2579  switch (flav) {
2580  case FLAV_NS:
2581  return "ns";
2582  case FLAV_MICRODESC:
2583  return "microdesc";
2584  default:
2586  return "??";
2587  }
2588 }
2589 
2590 /** Return the consensus_flavor_t value for the flavor called <b>flavname</b>,
2591  * or -1 if the flavor is not recognized. */
2592 int
2593 networkstatus_parse_flavor_name(const char *flavname)
2594 {
2595  if (!strcmp(flavname, "ns"))
2596  return FLAV_NS;
2597  else if (!strcmp(flavname, "microdesc"))
2598  return FLAV_MICRODESC;
2599  else
2600  return -1;
2601 }
2602 
2603 /** Return 0 if this routerstatus is obsolete, too new, isn't
2604  * running, or otherwise not a descriptor that we would make any
2605  * use of even if we had it. Else return 1. */
2606 int
2608 {
2609  if (!rs->is_flagged_running) {
2610  /* If we had this router descriptor, we wouldn't even bother using it.
2611  * (Fetching and storing depends on by we_want_to_fetch_flavor().) */
2612  return 0;
2613  }
2614  if (rs->published_on + OLD_ROUTER_DESC_MAX_AGE < now) {
2615  /* We'd drop it immediately for being too old. */
2616  return 0;
2617  }
2618  if (!routerstatus_version_supports_extend2_cells(rs, 1)) {
2619  /* We'd ignore it because it doesn't support EXTEND2 cells.
2620  * If we don't know the version, download the descriptor so we can
2621  * check if it supports EXTEND2 cells and ntor. */
2622  return 0;
2623  }
2624  return 1;
2625 }
2626 
2627 /** If <b>question</b> is a string beginning with "ns/" in a format the
2628  * control interface expects for a GETINFO question, set *<b>answer</b> to a
2629  * newly-allocated string containing networkstatus lines for the appropriate
2630  * ORs. Return 0 on success, -1 on unrecognized question format. */
2631 int
2633  const char *question, char **answer,
2634  const char **errmsg)
2635 {
2636  const routerstatus_t *status;
2637  (void) conn;
2638 
2640  *answer = tor_strdup("");
2641  return 0;
2642  }
2643 
2644  if (!strcmp(question, "ns/all")) {
2645  smartlist_t *statuses = smartlist_new();
2647  const routerstatus_t *, rs,
2648  {
2650  });
2651  *answer = smartlist_join_strings(statuses, "", 0, NULL);
2652  SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
2653  smartlist_free(statuses);
2654  return 0;
2655  } else if (!strcmpstart(question, "ns/id/")) {
2656  char d[DIGEST_LEN];
2657  const char *q = question + 6;
2658  if (*q == '$')
2659  ++q;
2660 
2661  if (base16_decode(d, DIGEST_LEN, q, strlen(q)) != DIGEST_LEN) {
2662  *errmsg = "Data not decodeable as hex";
2663  return -1;
2664  }
2666  } else if (!strcmpstart(question, "ns/name/")) {
2667  const node_t *n = node_get_by_nickname(question+8, 0);
2668  status = n ? n->rs : NULL;
2669  } else if (!strcmpstart(question, "ns/purpose/")) {
2670  *answer = networkstatus_getinfo_by_purpose(question+11, time(NULL));
2671  return *answer ? 0 : -1;
2672  } else if (!strcmp(question, "consensus/packages")) {
2674  if (ns && ns->package_lines)
2675  *answer = smartlist_join_strings(ns->package_lines, "\n", 0, NULL);
2676  else
2677  *errmsg = "No consensus available";
2678  return *answer ? 0 : -1;
2679  } else if (!strcmp(question, "consensus/valid-after") ||
2680  !strcmp(question, "consensus/fresh-until") ||
2681  !strcmp(question, "consensus/valid-until")) {
2683  if (ns) {
2684  time_t t;
2685  if (!strcmp(question, "consensus/valid-after"))
2686  t = ns->valid_after;
2687  else if (!strcmp(question, "consensus/fresh-until"))
2688  t = ns->fresh_until;
2689  else
2690  t = ns->valid_until;
2691 
2692  char tbuf[ISO_TIME_LEN+1];
2693  format_iso_time(tbuf, t);
2694  *answer = tor_strdup(tbuf);
2695  } else {
2696  *errmsg = "No consensus available";
2697  }
2698  return *answer ? 0 : -1;
2699  } else {
2700  return 0;
2701  }
2702 
2703  if (status)
2704  *answer = networkstatus_getinfo_helper_single(status);
2705  return 0;
2706 }
2707 
2708 /** Check whether the networkstatus <b>ns</b> lists any protocol
2709  * versions as "required" or "recommended" that we do not support. If
2710  * so, set *<b>warning_out</b> to a newly allocated string describing
2711  * the problem.
2712  *
2713  * Return 1 if we should exit, 0 if we should not. */
2714 int
2716  int client_mode,
2717  char **warning_out)
2718 {
2719  const char *func = client_mode ? "client" : "relay";
2720  const char *required, *recommended;
2721  char *missing = NULL;
2722 
2723  const bool consensus_postdates_this_release =
2725 
2726  if (! consensus_postdates_this_release) {
2727  // We can't meaningfully warn about this case: This consensus is from
2728  // before we were released, so whatever is says about required or
2729  // recommended versions may no longer be true.
2730  return 0;
2731  }
2732 
2733  tor_assert(warning_out);
2734 
2735  if (client_mode) {
2736  required = ns->required_client_protocols;
2737  recommended = ns->recommended_client_protocols;
2738  } else {
2739  required = ns->required_relay_protocols;
2740  recommended = ns->recommended_relay_protocols;
2741  }
2742 
2743  if (!protover_all_supported(required, &missing)) {
2744  tor_asprintf(warning_out, "At least one protocol listed as required in "
2745  "the consensus is not supported by this version of Tor. "
2746  "You should upgrade. This version of Tor will not work as a "
2747  "%s on the Tor network. The missing protocols are: %s",
2748  func, missing);
2749  tor_free(missing);
2750  return 1;
2751  }
2752 
2753  if (! protover_all_supported(recommended, &missing)) {
2754  tor_asprintf(warning_out, "At least one protocol listed as recommended in "
2755  "the consensus is not supported by this version of Tor. "
2756  "You should upgrade. This version of Tor will eventually "
2757  "stop working as a %s on the Tor network. The missing "
2758  "protocols are: %s",
2759  func, missing);
2760  tor_free(missing);
2761  }
2762 
2763  tor_assert_nonfatal(missing == NULL);
2764 
2765  return 0;
2766 }
2767 
2768 /** Free all storage held locally in this module. */
2769 void
2771 {
2772  int i;
2773  networkstatus_vote_free(current_ns_consensus);
2774  networkstatus_vote_free(current_md_consensus);
2776 
2777  for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
2779  if (waiting->consensus) {
2780  networkstatus_vote_free(waiting->consensus);
2781  waiting->consensus = NULL;
2782  }
2783  }
2784 }
2785 
2786 /** Return the start of the next interval of size <b>interval</b> (in
2787  * seconds) after <b>now</b>, plus <b>offset</b>. Midnight always
2788  * starts a fresh interval, and if the last interval of a day would be
2789  * truncated to less than half its size, it is rolled into the
2790  * previous interval. */
2791 time_t
2793  int offset)
2794 {
2795  struct tm tm;
2796  time_t midnight_today=0;
2797  time_t midnight_tomorrow;
2798  time_t next;
2799 
2800  tor_gmtime_r(&now, &tm);
2801  tm.tm_hour = 0;
2802  tm.tm_min = 0;
2803  tm.tm_sec = 0;
2804 
2805  if (tor_timegm(&tm, &midnight_today) < 0) {
2806  // LCOV_EXCL_START
2807  log_warn(LD_BUG, "Ran into an invalid time when trying to find midnight.");
2808  // LCOV_EXCL_STOP
2809  }
2810  midnight_tomorrow = midnight_today + (24*60*60);
2811 
2812  next = midnight_today + ((now-midnight_today)/interval + 1)*interval;
2813 
2814  /* Intervals never cross midnight. */
2815  if (next > midnight_tomorrow)
2816  next = midnight_tomorrow;
2817 
2818  /* If the interval would only last half as long as it's supposed to, then
2819  * skip over to the next day. */
2820  if (next + interval/2 > midnight_tomorrow)
2821  next = midnight_tomorrow;
2822 
2823  next += offset;
2824  if (next - interval > now)
2825  next -= interval;
2826 
2827  return next;
2828 }
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:933
int tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2, tor_addr_comparison_t how)
Definition: address.c:984
#define tor_addr_eq(a, b)
Definition: address.h:280
time_t approx_time(void)
Definition: approx_time.c:32
authority_cert_t * authority_cert_get_by_digests(const char *id_digest, const char *sk_digest)
Definition: authcert.c:648
void authority_certs_fetch_missing(networkstatus_t *status, time_t now, const char *dir_hint)
Definition: authcert.c:853
int authority_cert_is_denylisted(const authority_cert_t *cert)
Definition: authcert.c:744
int authority_cert_dl_looks_uncertain(const char *id_digest)
Definition: authcert.c:763
Header file for authcert.c.
Header file for directory authority mode.
Authority certificate structure.
const char * hex_str(const char *from, size_t fromlen)
Definition: binascii.c:34
int base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:506
Header file for circuitbuild.c.
Header file for channel.c.
void channelpadding_new_consensus_params(const networkstatus_t *ns)
Header file for circuitmux.c.
void cmux_ewma_set_options(const or_options_t *options, const networkstatus_t *consensus)
Header file for circuitmux_ewma.c.
void circpad_new_consensus_params(const networkstatus_t *ns)
Header file for circuitpadding.c.
void circuit_build_times_new_consensus_params(circuit_build_times_t *cbt, const networkstatus_t *ns)
Definition: circuitstats.c:426
circuit_build_times_t * get_circuit_build_times_mutable(void)
Definition: circuitstats.c:85
Header file for circuitstats.c.
#define STMT_NIL
const or_options_t * get_options(void)
Definition: config.c:919
int options_any_client_port_set(const or_options_t *options)
Definition: config.c:7502
Header file for config.c.
smartlist_t * connection_dir_list_by_purpose_resource_and_state(int purpose, const char *resource, int state)
Definition: connection.c:4889
void clock_skew_warning(const connection_t *conn, long apparent_skew, int trusted, log_domain_mask_t domain, const char *received, const char *source)
Definition: connection.c:5861
Header file for connection.c.
static int connection_dir_count_by_purpose_and_resource(int purpose, const char *resource)
Definition: connection.h:311
#define CONN_TYPE_AP
Definition: connection.h:51
Header file for connection_edge.c.
#define AP_CONN_STATE_IS_UNATTACHED(s)
void connection_or_update_token_buckets(smartlist_t *conns, const or_options_t *options)
Header file for connection_or.c.
int consdiffmgr_add_consensus(const char *consensus, size_t consensus_len, const networkstatus_t *as_parsed)
Definition: consdiffmgr.c:549
Header for consdiffmgr.c.
int control_event_general_status(int severity, const char *format,...)
int control_event_networkstatus_changed(smartlist_t *statuses)
int control_event_is_interesting(int event)
int control_event_client_status(int severity, const char *format,...)
int control_event_newconsensus(const networkstatus_t *consensus)
Header file for control_events.c.
digest_algorithm_t
Definition: crypto_digest.h:44
Common functions for using (pseudo-)random number generators.
int crypto_rand_int(unsigned int max)
int crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
Definition: crypto_rsa.c:356
size_t crypto_pk_keysize(const crypto_pk_t *env)
int crypto_pk_public_checksig(const crypto_pk_t *env, char *to, size_t tolen, const char *from, size_t fromlen)
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:55
Common functions for cryptographic routines.
int tor_memeq(const void *a, const void *b, size_t sz)
Definition: di_ops.c:107
int tor_memcmp(const void *a, const void *b, size_t len)
Definition: di_ops.c:31
#define fast_memeq(a, b, c)
Definition: di_ops.h:35
#define tor_memneq(a, b, sz)
Definition: di_ops.h:21
#define fast_memneq(a, b, c)
Definition: di_ops.h:42
#define DIGEST_LEN
Definition: digest_sizes.h:20
#define DIGEST256_LEN
Definition: digest_sizes.h:23
Client/server directory connection structure.
Trusted/fallback directory server structure.
void reschedule_dirvote(const or_options_t *options)
Header for dirauth_periodic.c.
void directory_get_from_dirserver(uint8_t dir_purpose, uint8_t router_purpose, const char *resource, int pds_flags, download_want_authority_t want_authority)
Definition: dirclient.c:448
Header file for dirclient.c.
int dirclient_fetches_dir_info_later(const or_options_t *options)
int dirclient_fetches_dir_info_early(const or_options_t *options)
int dirclient_fetches_from_authorities(const or_options_t *options)
Header for feature/dirclient/dirclient_modes.c.
Header file for directory.c.
#define DIR_CONN_STATE_CLIENT_READING
Definition: directory.h:24
#define DIR_PURPOSE_FETCH_CONSENSUS
Definition: directory.h:54
int get_n_authorities(dirinfo_type_t type)
Definition: dirlist.c:103
dir_server_t * trusteddirserver_get_by_v3_auth_digest(const char *digest)
Definition: dirlist.c:215
Header file for dirlist.c.
int directory_caches_dir_info(const or_options_t *options)
Definition: dirserv.c:94
int directory_caches_unknown_auth_certs(const or_options_t *options)
Definition: dirserv.c:79
void dirserv_set_cached_consensus_networkstatus(const char *networkstatus, size_t networkstatus_len, const char *flavor_name, const common_digests_t *digests, const uint8_t *sha3_as_signed, time_t published)
Definition: dirserv.c:174
Header file for dirserv.c.
Header file for dirvote.c.
int download_status_is_ready(download_status_t *dls, time_t now)
Definition: dlstatus.c:381
time_t download_status_increment_attempt(download_status_t *dls, const char *item, time_t now)
Definition: dlstatus.c:309
void download_status_reset(download_status_t *dls)
Definition: dlstatus.c:364
Header file for dlstatus.c.
#define download_status_failed(dls, sc)
Definition: dlstatus.h:22
Authority signature structure.
int num_bridges_usable(int use_maybe_reachable)
Definition: entrynodes.c:3412
Header file for circuitbuild.c.
const char * escaped(const char *s)
Definition: escape.c:126
#define RFTS_IGNORE_MISSING
Definition: files.h:101
int write_bytes_to_file(const char *fname, const char *str, size_t len, int bin)
Definition: files.c:545
int tor_rename(const char *path_old, const char *path_new)
Definition: files.c:103
Format routerstatus entries for controller, vote, or consensus.
@ NS_CONTROL_PORT
char * routerstatus_format_entry(const routerstatus_t *rs, const char *version, const char *protocols, routerstatus_format_type_t format, const vote_routerstatus_t *vrs)
int we_are_hibernating(void)
Definition: hibernate.c:937
Header file for hibernate.c.
void hs_dos_consensus_has_changed(const networkstatus_t *ns)
Definition: hs_dos.c:152
Header file containing denial of service defenses for the HS subsystem for all versions.
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:590
#define LOG_ERR
Definition: log.h:56
#define LD_FS
Definition: log.h:70
#define LD_BUG
Definition: log.h:86
#define LD_GENERAL
Definition: log.h:62
#define LD_DIR
Definition: log.h:88
#define LOG_NOTICE
Definition: log.h:50
#define LOG_WARN
Definition: log.h:53
#define LOG_INFO
Definition: log.h:45
smartlist_t * get_connection_array(void)
Definition: mainloop.c:451
Header file for mainloop.c.
#define tor_free(p)
Definition: malloc.h:52
void microdesc_reset_outdated_dirservers_list(void)
Definition: microdesc.c:186
int usable_consensus_flavor(void)
Definition: microdesc.c:1086
void update_microdescs_from_networkstatus(time_t now)
Definition: microdesc.c:1033
int we_use_microdescriptors_for_circuits(const or_options_t *options)
Definition: microdesc.c:1055
Header file for microdesc.c.
Header for netstatus.c.
routerstatus_t * networkstatus_vote_find_mutable_entry(networkstatus_t *ns, const char *digest)
char * networkstatus_getinfo_helper_single(const routerstatus_t *rs)
int networkstatus_valid_after_is_reasonably_live(time_t valid_after, time_t now)
void update_networkstatus_downloads(time_t now)
int networkstatus_consensus_can_use_multiple_directories(const or_options_t *options)
int getinfo_helper_networkstatus(control_connection_t *conn, const char *question, char **answer, const char **errmsg)
int networkstatus_check_document_signature(const networkstatus_t *consensus, document_signature_t *sig, const authority_cert_t *cert)
networkstatus_t * networkstatus_get_latest_consensus_by_flavor(consensus_flavor_t f)
void routers_update_all_from_networkstatus(time_t now, int dir_version)
int networkstatus_parse_flavor_name(const char *flavname)
download_status_t * networkstatus_get_dl_status_by_flavor_bootstrap(consensus_flavor_t flavor)
STATIC networkstatus_t * current_md_consensus
int networkstatus_set_current_consensus(const char *consensus, size_t consensus_len, const char *flavor, unsigned flags, const char *source_dir)
STATIC int routerstatus_has_visibly_changed(const routerstatus_t *a, const routerstatus_t *b)
int compare_digest_to_vote_routerstatus_entry(const void *_key, const void **_member)
static int reload_consensus_from_file(const char *fname, const char *flavor, unsigned flags, const char *source_dir)
static void notify_control_networkstatus_changed(const networkstatus_t *old_c, const networkstatus_t *new_c)
void signed_descs_update_status_from_consensus_networkstatus(smartlist_t *descs)
smartlist_t * router_get_descriptor_digests(void)
int networkstatus_consensus_reasonably_live(const networkstatus_t *consensus, time_t now)
const char * networkstatus_get_flavor_name(consensus_flavor_t flav)
int we_want_to_fetch_flavor(const or_options_t *options, int flavor)
static smartlist_t * router_get_descriptor_digests_in_consensus(networkstatus_t *consensus)
int32_t networkstatus_get_overridable_param(const networkstatus_t *ns, int32_t torrc_value, const char *param_name, int32_t default_val, int32_t min_val, int32_t max_val)
time_t voting_sched_get_start_of_interval_after(time_t now, int interval, int offset)
int client_would_use_router(const routerstatus_t *rs, time_t now)
networkstatus_t * networkstatus_get_reasonably_live_consensus(time_t now, int flavor)
networkstatus_voter_info_t * networkstatus_get_voter_by_id(networkstatus_t *vote, const char *identity)
static void handle_missing_protocol_warning(const networkstatus_t *c, const or_options_t *options)
download_status_t * networkstatus_get_dl_status_by_flavor(consensus_flavor_t flavor)
static void update_consensus_bootstrap_attempt_downloads(time_t now, download_status_t *dls, download_want_authority_t want_authority)
int networkstatus_vote_find_entry_idx(networkstatus_t *ns, const char *digest, int *found_out)
static void networkstatus_copy_old_consensus_info(networkstatus_t *new_c, const networkstatus_t *old_c)
static download_status_t consensus_dl_status[N_CONSENSUS_FLAVORS]
void document_signature_free_(document_signature_t *sig)
char * networkstatus_getinfo_by_purpose(const char *purpose_string, time_t now)
STATIC networkstatus_t * current_ns_consensus
void networkstatus_free_all(void)
static void update_consensus_networkstatus_downloads(time_t now)
networkstatus_t * networkstatus_get_latest_consensus(void)
static int32_t get_net_param_from_list(smartlist_t *net_params, const char *param_name, int32_t default_val, int32_t min_val, int32_t max_val)
download_status_t * router_get_dl_status_by_descriptor_digest(const char *d)
void networkstatus_note_certs_arrived(const char *source_dir)
int32_t networkstatus_get_bw_weight(networkstatus_t *ns, const char *weight_name, int32_t default_val)
int networkstatus_consensus_is_bootstrapping(time_t now)
int networkstatus_check_consensus_signature(networkstatus_t *consensus, int warn)
static int have_warned_about_old_version
const routerstatus_t * router_get_consensus_status_by_id(const char *digest)
download_status_t * networkstatus_get_dl_status_by_flavor_running(consensus_flavor_t flavor)
int networkstatus_valid_until_is_reasonably_live(time_t valid_until, time_t now)
int networkstatus_is_live(const networkstatus_t *ns, time_t now)
int compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
void vote_routerstatus_free_(vote_routerstatus_t *rs)
static void update_consensus_bootstrap_multiple_downloads(time_t now, const or_options_t *options)
document_signature_t * document_signature_dup(const document_signature_t *sig)
int should_delay_dir_fetches(const or_options_t *options, const char **msg_out)
static int networkstatus_check_required_protocols(const networkstatus_t *ns, int client_mode, char **warning_out)
int router_reload_consensus_networkstatus(void)
void update_certificate_downloads(time_t now)
int networkstatus_consensus_can_use_extra_fallbacks(const or_options_t *options)
const routerstatus_t * networkstatus_vote_find_entry(networkstatus_t *ns, const char *digest)
tor_mmap_t * networkstatus_map_cached_consensus(const char *flavorname)
static void handle_missing_protocol_warning_impl(const networkstatus_t *c, int is_client)
document_signature_t * networkstatus_get_voter_sig_by_alg(const networkstatus_voter_info_t *voter, digest_algorithm_t alg)
static time_t time_to_download_next_consensus[N_CONSENSUS_FLAVORS]
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)
void set_routerstatus_from_routerinfo(routerstatus_t *rs, const node_t *node, const routerinfo_t *ri)
routerstatus_t * router_get_mutable_consensus_status_by_id(const char *digest)
STATIC void warn_early_consensus(const networkstatus_t *c, const char *flavor, time_t now)
routerstatus_t * router_get_mutable_consensus_status_by_descriptor_digest(networkstatus_t *consensus, const char *digest)
#define MIN_DELAY_FOR_FETCH_CERT_STATUS_FAILURE
void networkstatus_vote_free_(networkstatus_t *ns)
static tor_mmap_t * networkstatus_map_cached_consensus_impl(int flav, const char *flavorname, int unverified_consensus)
#define DELAY_WHILE_FETCHING_CERTS
static int have_warned_about_new_version
static void update_consensus_networkstatus_fetch_time_impl(time_t now, int flav)
void update_consensus_networkstatus_fetch_time(time_t now)
void networkstatus_reset_download_failures(void)
void networkstatus_reset_warnings(void)
char * networkstatus_get_cache_fname(int flav, const char *flavorname, int unverified_consensus)
const routerstatus_t * router_get_consensus_status_by_descriptor_digest(networkstatus_t *consensus, const char *digest)
int we_want_to_fetch_unknown_auth_certs(const or_options_t *options)
#define CONSENSUS_MIN_SECONDS_BEFORE_CACHING
networkstatus_t * networkstatus_get_live_consensus(time_t now)
static consensus_waiting_for_certs_t consensus_waiting_for_certs[N_CONSENSUS_FLAVORS]
int consensus_is_waiting_for_certs(void)
void routerstatus_free_(routerstatus_t *rs)
void networkstatus_consensus_download_failed(int status_code, const char *flavname)
void routers_update_status_from_consensus_networkstatus(smartlist_t *routers, int reset_failures)
int networkstatus_get_weight_scale_param(networkstatus_t *ns)
Header file for networkstatus.c.
Networkstatus consensus/vote structure.
Single consensus voter structure.
Header file for node_select.c.
#define PDS_RETRY_IF_NO_SERVERS
Definition: node_select.h:54
Node information structure.
node_t * node_get_mutable_by_id(const char *identity_digest)
Definition: nodelist.c:197
void router_dir_info_changed(void)
Definition: nodelist.c:2470
const smartlist_t * nodelist_get_list(void)
Definition: nodelist.c:1047
const node_t * node_get_by_nickname(const char *nickname, unsigned flags)
Definition: nodelist.c:1085
void nodelist_set_consensus(const networkstatus_t *ns)
Definition: nodelist.c:689
Header file for nodelist.c.
Detached consensus signatures structure.
Header file for ns_parse.c.
networkstatus_t * networkstatus_parse_vote_from_string(const char *s, size_t len, const char **eos_out, enum networkstatus_type_t ns_type)
Definition: ns_parse.c:1089
Master header file for Tor-specific functionality.
#define BW_WEIGHT_SCALE
Definition: or.h:904
#define OLD_ROUTER_DESC_MAX_AGE
Definition: or.h:163
download_want_authority_t
Definition: or.h:659
#define TO_CONN(c)
Definition: or.h:616
consensus_flavor_t
Definition: or.h:761
#define ROUTER_MAX_AGE_TO_PUBLISH
Definition: or.h:161
@ V3_DIRINFO
Definition: or.h:788
#define N_CONSENSUS_FLAVORS
Definition: or.h:767
long tor_parse_long(const char *s, int base, long min, long max, int *ok, char **next)
Definition: parse_int.c:59
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
int protover_all_supported(const char *s, char **missing_out)
Definition: protover.c:609
Headers and type declarations for protover.c.
int dirserv_should_launch_reachability_test(const routerinfo_t *ri, const routerinfo_t *ri_old)
Definition: reachability.c:103
Header file for reachability.c.
Header file for relay.c.
void router_new_consensus_params(const networkstatus_t *ns)
Definition: router.c:2485
uint8_t router_purpose_from_string(const char *s)
Definition: routerinfo.c:113
Header file for routerinfo.c.
Router descriptor structure.
#define ROUTER_PURPOSE_UNKNOWN
#define ROUTER_PURPOSE_GENERAL
Definition: routerinfo_st.h:98
routerinfo_t * router_get_mutable_by_digest(const char *digest)
Definition: routerlist.c:762
routerlist_t * router_get_routerlist(void)
Definition: routerlist.c:895
void routers_sort_by_identity(smartlist_t *routers)
Definition: routerlist.c:3275
Header file for routerlist.c.
Router descriptor list structure.
int public_server_mode(const or_options_t *options)
Definition: routermode.c:43
int dir_server_mode(const or_options_t *options)
Definition: routermode.c:23
int server_mode(const or_options_t *options)
Definition: routermode.c:34
Header file for routermode.c.
Routerstatus (consensus entry) structure.
void scheduler_notify_networkstatus_changed(void)
Definition: scheduler.c:467
Header file for scheduler*.c.
This file contains ABI/API of the shared random protocol defined in proposal #250....
void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern,...)
Definition: smartlist.c:36
void * smartlist_bsearch(const smartlist_t *sl, const void *key, int(*compare)(const void *key, const void **member))
Definition: smartlist.c:411
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
int smartlist_bsearch_idx(const smartlist_t *sl, const void *key, int(*compare)(const void *key, const void **member), int *found_out)
Definition: smartlist.c:428
smartlist_t * smartlist_new(void)
void smartlist_add(smartlist_t *sl, void *element)
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
#define SMARTLIST_FOREACH(sl, type, var, cmd)
crypto_pk_t * signing_key
char signing_key_digest[DIGEST_LEN]
signed_descriptor_t cache_info
char d[N_COMMON_DIGEST_ALGORITHMS][DIGEST256_LEN]
Definition: crypto_digest.h:89
uint8_t state
Definition: connection_st.h:49
struct connection_t * linked_conn
unsigned int type
Definition: connection_st.h:50
char identity_digest[DIGEST_LEN]
digest_algorithm_t alg
char signing_key_digest[DIGEST_LEN]
download_schedule_bitfield_t schedule
smartlist_t * known_flags
common_digests_t digests
char * recommended_relay_protocols
digestmap_t * desc_digest_map
smartlist_t * voters
smartlist_t * net_params
smartlist_t * weight_params
smartlist_t * package_lines
smartlist_t * supported_methods
smartlist_t * routerstatus_list
networkstatus_sr_info_t sr_info
uint8_t digest_sha3_as_signed[DIGEST256_LEN]
struct authority_cert_t * cert
consensus_flavor_t flavor
networkstatus_type_t type
smartlist_t * bw_file_headers
Definition: node_st.h:34
unsigned int is_bad_exit
Definition: node_st.h:71
unsigned int is_running
Definition: node_st.h:63
unsigned int is_hs_dir
Definition: node_st.h:73
unsigned int is_valid
Definition: node_st.h:65
char identity[DIGEST_LEN]
Definition: node_st.h:46
unsigned int is_possible_guard
Definition: node_st.h:69
unsigned int is_stable
Definition: node_st.h:68
unsigned int is_exit
Definition: node_st.h:70
unsigned int name_lookup_warned
Definition: node_st.h:78
int ClientBootstrapConsensusMaxInProgressTries
int FetchDirInfoExtraEarly
int FetchUselessDescriptors
tor_addr_t ipv6_addr
Definition: routerinfo_st.h:30
tor_addr_t ipv4_addr
Definition: routerinfo_st.h:25
unsigned int supports_tunnelled_dir_requests
Definition: routerinfo_st.h:86
char * nickname
Definition: routerinfo_st.h:22
smartlist_t * routers
Definition: routerlist_st.h:32
smartlist_t * old_routers
Definition: routerlist_st.h:35
unsigned int is_bad_exit
uint16_t ipv6_orport
tor_addr_t ipv6_addr
unsigned int is_staledesc
char descriptor_digest[DIGEST256_LEN]
char identity_digest[DIGEST_LEN]
unsigned int is_hs_dir
unsigned int is_valid
char nickname[MAX_NICKNAME_LEN+1]
unsigned int has_bandwidth
uint16_t ipv4_dirport
unsigned int is_named
unsigned int is_possible_guard
unsigned int is_stable
unsigned int is_flagged_running
unsigned int is_exit
unsigned int is_authority
unsigned int is_fast
uint32_t bandwidth_kb
uint16_t ipv4_orport
unsigned int is_unnamed
char signed_descriptor_digest[DIGEST_LEN]
char identity_digest[DIGEST_LEN]
size_t size
Definition: mmap.h:27
const char * data
Definition: mmap.h:26
struct vote_microdesc_hash_t * next
vote_microdesc_hash_t * microdesc
#define STATIC
Definition: testsupport.h:32
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
void format_iso_time(char *buf, time_t t)
Definition: time_fmt.c:295
void format_local_iso_time(char *buf, time_t t)
Definition: time_fmt.c:285
int tor_timegm(const struct tm *tm, time_t *time_out)
Definition: time_fmt.c:96
struct tm * tor_gmtime_r(const time_t *timep, struct tm *result)
Definition: time_fmt.c:65
int format_time_interval(char *out, size_t out_len, long interval)
Definition: time_fmt.c:481
Header for torcert.c.
int pt_proxies_configuration_pending(void)
Definition: transports.c:396
Headers for transports.c.
#define tor_assert_nonfatal_unreached()
Definition: util_bug.h:176
#define tor_assert(expr)
Definition: util_bug.h:102
#define tor_fragile_assert()
Definition: util_bug.h:270
int strcmpstart(const char *s1, const char *s2)
Definition: util_string.c:215
time_t tor_get_approx_release_date(void)
Definition: versions.c:25
version_status_t tor_version_is_obsolete(const char *myversion, const char *versionlist)
Definition: versions.c:53
Header file for versions.c.
version_status_t
Definition: versions.h:17
@ VS_OLD
Definition: versions.h:19
@ VS_EMPTY
Definition: versions.h:25
@ VS_NEW_IN_SERIES
Definition: versions.h:21
@ VS_RECOMMENDED
Definition: versions.h:18
@ VS_NEW
Definition: versions.h:20
Microdescriptor-hash voting structure.
Routerstatus (vote entry) structure.
Header file for voteflags.c.
void dirauth_sched_recalculate_timing(const or_options_t *options, time_t now)
Header file for voting_schedule.c.