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