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