Tor  0.4.5.0-alpha-dev
routerlist.c
Go to the documentation of this file.
1 /* Copyright (c) 2001 Matej Pfajfar.
2  * Copyright (c) 2001-2004, Roger Dingledine.
3  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4  * Copyright (c) 2007-2020, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 
7 /**
8  * \file routerlist.c
9  * \brief Code to
10  * maintain and access the global list of routerinfos for known
11  * servers.
12  *
13  * A "routerinfo_t" object represents a single self-signed router
14  * descriptor, as generated by a Tor relay in order to tell the rest of
15  * the world about its keys, address, and capabilities. An
16  * "extrainfo_t" object represents an adjunct "extra-info" object,
17  * certified by a corresponding router descriptor, reporting more
18  * information about the relay that nearly all users will not need.
19  *
20  * Most users will not use router descriptors for most relays. Instead,
21  * they use the information in microdescriptors and in the consensus
22  * networkstatus.
23  *
24  * Right now, routerinfo_t objects are used in these ways:
25  * <ul>
26  * <li>By clients, in order to learn about bridge keys and capabilities.
27  * (Bridges aren't listed in the consensus networkstatus, so they
28  * can't have microdescriptors.)
29  * <li>By relays, since relays want more information about other relays
30  * than they can learn from microdescriptors. (TODO: Is this still true?)
31  * <li>By authorities, which receive them and use them to generate the
32  * consensus and the microdescriptors.
33  * <li>By all directory caches, which download them in case somebody
34  * else wants them.
35  * </ul>
36  *
37  * Routerinfos are mostly created by parsing them from a string, in
38  * routerparse.c. We store them to disk on receiving them, and
39  * periodically discard the ones we don't need. On restarting, we
40  * re-read them from disk. (This also applies to extrainfo documents, if
41  * we are configured to fetch them.)
42  *
43  * In order to keep our list of routerinfos up-to-date, we periodically
44  * check whether there are any listed in the latest consensus (or in the
45  * votes from other authorities, if we are an authority) that we don't
46  * have. (This also applies to extrainfo documents, if we are
47  * configured to fetch them.)
48  *
49  * Almost nothing in Tor should use a routerinfo_t to refer directly to
50  * a relay; instead, almost everything should use node_t (implemented in
51  * nodelist.c), which provides a common interface to routerinfo_t,
52  * routerstatus_t, and microdescriptor_t.
53  *
54  * <br>
55  *
56  * This module also has some of the functions used for choosing random
57  * nodes according to different rules and weights. Historically, they
58  * were all in this module. Now, they are spread across this module,
59  * nodelist.c, and networkstatus.c. (TODO: Fix that.)
60  **/
61 
62 #define ROUTERLIST_PRIVATE
63 #include "core/or/or.h"
64 
65 #include "app/config/config.h"
67 #include "core/mainloop/mainloop.h"
68 #include "core/or/policies.h"
69 #include "feature/client/bridges.h"
92 #include "feature/stats/rephist.h"
95 
106 
107 #include "lib/crypt_ops/digestset.h"
108 
109 #ifdef HAVE_SYS_STAT_H
110 #include <sys/stat.h>
111 #endif
112 
113 // #define DEBUG_ROUTERLIST
114 
115 /****************************************************************************/
116 
117 /* Typed wrappers for different digestmap types; used to avoid type
118  * confusion. */
119 
120 DECLARE_TYPED_DIGESTMAP_FNS(sdmap, digest_sd_map_t, signed_descriptor_t)
121 DECLARE_TYPED_DIGESTMAP_FNS(rimap, digest_ri_map_t, routerinfo_t)
122 DECLARE_TYPED_DIGESTMAP_FNS(eimap, digest_ei_map_t, extrainfo_t)
123 #define SDMAP_FOREACH(map, keyvar, valvar) \
124  DIGESTMAP_FOREACH(sdmap_to_digestmap(map), keyvar, signed_descriptor_t *, \
125  valvar)
126 #define RIMAP_FOREACH(map, keyvar, valvar) \
127  DIGESTMAP_FOREACH(rimap_to_digestmap(map), keyvar, routerinfo_t *, valvar)
128 #define EIMAP_FOREACH(map, keyvar, valvar) \
129  DIGESTMAP_FOREACH(eimap_to_digestmap(map), keyvar, extrainfo_t *, valvar)
130 #define eimap_free(map, fn) MAP_FREE_AND_NULL(eimap, (map), (fn))
131 #define rimap_free(map, fn) MAP_FREE_AND_NULL(rimap, (map), (fn))
132 #define sdmap_free(map, fn) MAP_FREE_AND_NULL(sdmap, (map), (fn))
133 
134 /* static function prototypes */
136 static const char *signed_descriptor_get_body_impl(
137  const signed_descriptor_t *desc,
138  int with_annotations);
139 static void launch_dummy_descriptor_download_as_needed(time_t now,
140  const or_options_t *options);
141 
142 /****************************************************************************/
143 
144 /** Global list of all of the routers that we know about. */
145 static routerlist_t *routerlist = NULL;
146 
147 /** List of strings for nicknames we've already warned about and that are
148  * still unknown / unavailable. */
150 
151 /** The last time we tried to download any routerdesc, or 0 for "never". We
152  * use this to rate-limit download attempts when the number of routerdescs to
153  * download is low. */
155 
156 /* Router descriptor storage.
157  *
158  * Routerdescs are stored in a big file, named "cached-descriptors". As new
159  * routerdescs arrive, we append them to a journal file named
160  * "cached-descriptors.new".
161  *
162  * From time to time, we replace "cached-descriptors" with a new file
163  * containing only the live, non-superseded descriptors, and clear
164  * cached-descriptors.new.
165  *
166  * On startup, we read both files.
167  */
168 
169 /** Helper: return 1 iff the router log is so big we want to rebuild the
170  * store. */
171 static int
173 {
174  if (store->store_len > (1<<16))
175  return (store->journal_len > store->store_len / 2 ||
176  store->bytes_dropped > store->store_len / 2);
177  else
178  return store->journal_len > (1<<15);
179 }
180 
181 /** Return the desc_store_t in <b>rl</b> that should be used to store
182  * <b>sd</b>. */
183 static inline desc_store_t *
185 {
186  if (sd->is_extrainfo)
187  return &rl->extrainfo_store;
188  else
189  return &rl->desc_store;
190 }
191 
192 /** Add the signed_descriptor_t in <b>desc</b> to the router
193  * journal; change its saved_location to SAVED_IN_JOURNAL and set its
194  * offset appropriately. */
195 static int
197  desc_store_t *store)
198 {
199  char *fname = get_cachedir_fname_suffix(store->fname_base, ".new");
200  const char *body = signed_descriptor_get_body_impl(desc,1);
201  size_t len = desc->signed_descriptor_len + desc->annotations_len;
202 
203  if (append_bytes_to_file(fname, body, len, 1)) {
204  log_warn(LD_FS, "Unable to store router descriptor");
205  tor_free(fname);
206  return -1;
207  }
209  tor_free(fname);
210 
211  desc->saved_offset = store->journal_len;
212  store->journal_len += len;
213 
214  return 0;
215 }
216 
217 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
218  * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
219  * the signed_descriptor_t* in *<b>b</b>. */
220 static int
221 compare_signed_descriptors_by_age_(const void **_a, const void **_b)
222 {
223  const signed_descriptor_t *r1 = *_a, *r2 = *_b;
224  return (int)(r1->published_on - r2->published_on);
225 }
226 
227 #define RRS_FORCE 1
228 #define RRS_DONT_REMOVE_OLD 2
229 
230 /** If the journal of <b>store</b> is too long, or if RRS_FORCE is set in
231  * <b>flags</b>, then atomically replace the saved router store with the
232  * routers currently in our routerlist, and clear the journal. Unless
233  * RRS_DONT_REMOVE_OLD is set in <b>flags</b>, delete expired routers before
234  * rebuilding the store. Return 0 on success, -1 on failure.
235  */
236 static int
238 {
239  smartlist_t *chunk_list = NULL;
240  char *fname = NULL, *fname_tmp = NULL;
241  int r = -1;
242  off_t offset = 0;
243  smartlist_t *signed_descriptors = NULL;
244  int nocache=0;
245  size_t total_expected_len = 0;
246  int had_any;
247  int force = flags & RRS_FORCE;
248 
249  if (!force && !router_should_rebuild_store(store)) {
250  r = 0;
251  goto done;
252  }
253  if (!routerlist) {
254  r = 0;
255  goto done;
256  }
257 
258  if (store->type == EXTRAINFO_STORE)
259  had_any = !eimap_isempty(routerlist->extra_info_map);
260  else
261  had_any = (smartlist_len(routerlist->routers)+
262  smartlist_len(routerlist->old_routers))>0;
263 
264  /* Don't save deadweight. */
265  if (!(flags & RRS_DONT_REMOVE_OLD))
267 
268  log_info(LD_DIR, "Rebuilding %s cache", store->description);
269 
270  fname = get_cachedir_fname(store->fname_base);
271  fname_tmp = get_cachedir_fname_suffix(store->fname_base, ".tmp");
272 
273  chunk_list = smartlist_new();
274 
275  /* We sort the routers by age to enhance locality on disk. */
276  signed_descriptors = smartlist_new();
277  if (store->type == EXTRAINFO_STORE) {
278  eimap_iter_t *iter;
279  for (iter = eimap_iter_init(routerlist->extra_info_map);
280  !eimap_iter_done(iter);
281  iter = eimap_iter_next(routerlist->extra_info_map, iter)) {
282  const char *key;
283  extrainfo_t *ei;
284  eimap_iter_get(iter, &key, &ei);
285  smartlist_add(signed_descriptors, &ei->cache_info);
286  }
287  } else {
289  smartlist_add(signed_descriptors, sd));
291  smartlist_add(signed_descriptors, &ri->cache_info));
292  }
293 
295 
296  /* Now, add the appropriate members to chunk_list */
297  SMARTLIST_FOREACH_BEGIN(signed_descriptors, signed_descriptor_t *, sd) {
298  sized_chunk_t *c;
299  const char *body = signed_descriptor_get_body_impl(sd, 1);
300  if (!body) {
301  log_warn(LD_BUG, "No descriptor available for router.");
302  goto done;
303  }
304  if (sd->do_not_cache) {
305  ++nocache;
306  continue;
307  }
308  c = tor_malloc(sizeof(sized_chunk_t));
309  c->bytes = body;
310  c->len = sd->signed_descriptor_len + sd->annotations_len;
311  total_expected_len += c->len;
312  smartlist_add(chunk_list, c);
313  } SMARTLIST_FOREACH_END(sd);
314 
315  if (write_chunks_to_file(fname_tmp, chunk_list, 1, 1)<0) {
316  log_warn(LD_FS, "Error writing router store to disk.");
317  goto done;
318  }
319 
320  /* Our mmap is now invalid. */
321  if (store->mmap) {
322  int res = tor_munmap_file(store->mmap);
323  store->mmap = NULL;
324  if (res != 0) {
325  log_warn(LD_FS, "Unable to munmap route store in %s", fname);
326  }
327  }
328 
329  if (replace_file(fname_tmp, fname)<0) {
330  log_warn(LD_FS, "Error replacing old router store: %s", strerror(errno));
331  goto done;
332  }
333 
334  errno = 0;
335  store->mmap = tor_mmap_file(fname);
336  if (! store->mmap) {
337  if (errno == ERANGE) {
338  /* empty store.*/
339  if (total_expected_len) {
340  log_warn(LD_FS, "We wrote some bytes to a new descriptor file at '%s',"
341  " but when we went to mmap it, it was empty!", fname);
342  } else if (had_any) {
343  log_info(LD_FS, "We just removed every descriptor in '%s'. This is "
344  "okay if we're just starting up after a long time. "
345  "Otherwise, it's a bug.", fname);
346  }
347  } else {
348  log_warn(LD_FS, "Unable to mmap new descriptor file at '%s'.",fname);
349  }
350  }
351 
352  log_info(LD_DIR, "Reconstructing pointers into cache");
353 
354  offset = 0;
355  SMARTLIST_FOREACH_BEGIN(signed_descriptors, signed_descriptor_t *, sd) {
356  if (sd->do_not_cache)
357  continue;
358  sd->saved_location = SAVED_IN_CACHE;
359  if (store->mmap) {
360  tor_free(sd->signed_descriptor_body); // sets it to null
361  sd->saved_offset = offset;
362  }
363  offset += sd->signed_descriptor_len + sd->annotations_len;
364  signed_descriptor_get_body(sd); /* reconstruct and assert */
365  } SMARTLIST_FOREACH_END(sd);
366 
367  tor_free(fname);
368  fname = get_cachedir_fname_suffix(store->fname_base, ".new");
369  write_str_to_file(fname, "", 1);
370 
371  r = 0;
372  store->store_len = (size_t) offset;
373  store->journal_len = 0;
374  store->bytes_dropped = 0;
375  done:
376  smartlist_free(signed_descriptors);
377  tor_free(fname);
378  tor_free(fname_tmp);
379  if (chunk_list) {
380  SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
381  smartlist_free(chunk_list);
382  }
383 
384  return r;
385 }
386 
387 /** Helper: Reload a cache file and its associated journal, setting metadata
388  * appropriately. If <b>extrainfo</b> is true, reload the extrainfo store;
389  * else reload the router descriptor store. */
390 static int
392 {
393  char *fname = NULL, *contents = NULL;
394  struct stat st;
395  int extrainfo = (store->type == EXTRAINFO_STORE);
396  store->journal_len = store->store_len = 0;
397 
398  fname = get_cachedir_fname(store->fname_base);
399 
400  if (store->mmap) {
401  /* get rid of it first */
402  int res = tor_munmap_file(store->mmap);
403  store->mmap = NULL;
404  if (res != 0) {
405  log_warn(LD_FS, "Failed to munmap %s", fname);
406  tor_free(fname);
407  return -1;
408  }
409  }
410 
411  store->mmap = tor_mmap_file(fname);
412  if (store->mmap) {
413  store->store_len = store->mmap->size;
414  if (extrainfo)
416  store->mmap->data+store->mmap->size,
417  SAVED_IN_CACHE, NULL, 0);
418  else
420  store->mmap->data+store->mmap->size,
421  SAVED_IN_CACHE, NULL, 0, NULL);
422  }
423 
424  tor_free(fname);
425  fname = get_cachedir_fname_suffix(store->fname_base, ".new");
426  /* don't load empty files - we wouldn't get any data, even if we tried */
427  if (file_status(fname) == FN_FILE)
428  contents = read_file_to_str(fname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
429  if (contents) {
430  if (extrainfo)
432  NULL, 0);
433  else
435  NULL, 0, NULL);
436  store->journal_len = (size_t) st.st_size;
437  tor_free(contents);
438  }
439 
440  tor_free(fname);
441 
442  if (store->journal_len) {
443  /* Always clear the journal on startup.*/
444  router_rebuild_store(RRS_FORCE, store);
445  } else if (!extrainfo) {
446  /* Don't cache expired routers. (This is in an else because
447  * router_rebuild_store() also calls remove_old_routers().) */
449  }
450 
451  return 0;
452 }
453 
454 /** Load all cached router descriptors and extra-info documents from the
455  * store. Return 0 on success and -1 on failure.
456  */
457 int
459 {
462  return -1;
464  return -1;
465  return 0;
466 }
467 
468 /* When selecting a router for a direct connection, can OR address/port
469  * preference and reachability checks be skipped?
470  *
471  * Servers never check ReachableAddresses or ClientPreferIPv6. Returns
472  * true for servers.
473  *
474  * Otherwise, if <b>try_ip_pref</b> is true, returns false. Used to make
475  * clients check ClientPreferIPv6, even if ReachableAddresses is not set.
476  * Finally, return true if ReachableAddresses is set.
477  */
478 int
479 router_or_conn_should_skip_reachable_address_check(
480  const or_options_t *options,
481  int try_ip_pref)
482 {
483  /* Servers always have and prefer IPv4.
484  * And if clients are checking against the firewall for reachability only,
485  * but there's no firewall, don't bother checking */
486  return server_mode(options) || (!try_ip_pref && !firewall_is_fascist_or());
487 }
488 
489 /* When selecting a router for a direct connection, can Dir address/port
490  * and reachability checks be skipped?
491  *
492  * This function is obsolete, because clients only use ORPorts.
493  */
494 int
495 router_dir_conn_should_skip_reachable_address_check(
496  const or_options_t *options,
497  int try_ip_pref)
498 {
499  /* Servers always have and prefer IPv4.
500  * And if clients are checking against the firewall for reachability only,
501  * but there's no firewall, don't bother checking */
502  return server_mode(options) || (!try_ip_pref && !firewall_is_fascist_dir());
503 }
504 
505 /** Return true iff r1 and r2 have the same address and OR port. */
506 int
508 {
509  return tor_addr_eq(&r1->ipv4_addr, &r2->ipv4_addr) &&
510  r1->ipv4_orport == r2->ipv4_orport &&
511  tor_addr_eq(&r1->ipv6_addr, &r2->ipv6_addr) &&
512  r1->ipv6_orport == r2->ipv6_orport;
513 }
514 
515 /* Returns true if <b>node</b> can be chosen based on <b>flags</b>.
516  *
517  * The following conditions are applied to all nodes:
518  * - is running;
519  * - is valid;
520  * - supports EXTEND2 cells;
521  * - has an ntor circuit crypto key; and
522  * - does not allow single-hop exits.
523  *
524  * If the node has a routerinfo, we're checking for a direct connection, and
525  * we're using bridges, the following condition is applied:
526  * - has a bridge-purpose routerinfo;
527  * and for all other nodes:
528  * - has a general-purpose routerinfo (or no routerinfo).
529  *
530  * Nodes that don't have a routerinfo must be general-purpose nodes, because
531  * routerstatuses and microdescriptors only come via consensuses.
532  *
533  * The <b>flags</b> chech that <b>node</b>:
534  * - <b>CRN_NEED_UPTIME</b>: has more than a minimum uptime;
535  * - <b>CRN_NEED_CAPACITY</b>: has more than a minimum capacity;
536  * - <b>CRN_NEED_GUARD</b>: is a Guard;
537  * - <b>CRN_NEED_DESC</b>: has a routerinfo or microdescriptor -- that is,
538  * enough info to be used to build a circuit;
539  * - <b>CRN_DIRECT_CONN</b>: is suitable for direct connections. Checks
540  * for the relevant descriptors. Checks the address
541  * against ReachableAddresses, ClientUseIPv4 0, and
542  * fascist_firewall_use_ipv6() == 0);
543  * - <b>CRN_PREF_ADDR</b>: if we are connecting directly to the node, it has
544  * an address that is preferred by the
545  * ClientPreferIPv6ORPort setting;
546  * - <b>CRN_RENDEZVOUS_V3</b>: can become a v3 onion service rendezvous point;
547  * - <b>CRN_INITIATE_IPV6_EXTEND</b>: can initiate IPv6 extends.
548  */
549 bool
550 router_can_choose_node(const node_t *node, int flags)
551 {
552  /* The full set of flags used for node selection. */
553  const bool need_uptime = (flags & CRN_NEED_UPTIME) != 0;
554  const bool need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
555  const bool need_guard = (flags & CRN_NEED_GUARD) != 0;
556  const bool need_desc = (flags & CRN_NEED_DESC) != 0;
557  const bool pref_addr = (flags & CRN_PREF_ADDR) != 0;
558  const bool direct_conn = (flags & CRN_DIRECT_CONN) != 0;
559  const bool rendezvous_v3 = (flags & CRN_RENDEZVOUS_V3) != 0;
560  const bool initiate_ipv6_extend = (flags & CRN_INITIATE_IPV6_EXTEND) != 0;
561 
562  const or_options_t *options = get_options();
563  const bool check_reach =
564  !router_or_conn_should_skip_reachable_address_check(options, pref_addr);
565  const bool direct_bridge = direct_conn && options->UseBridges;
566 
567  if (!node->is_running || !node->is_valid)
568  return false;
569  if (need_desc && !node_has_preferred_descriptor(node, direct_conn))
570  return false;
571  if (node->ri) {
572  if (direct_bridge && node->ri->purpose != ROUTER_PURPOSE_BRIDGE)
573  return false;
574  else if (node->ri->purpose != ROUTER_PURPOSE_GENERAL)
575  return false;
576  }
577  if (node_is_unreliable(node, need_uptime, need_capacity, need_guard))
578  return false;
579  /* Don't choose nodes if we are certain they can't do EXTEND2 cells */
580  if (node->rs && !routerstatus_version_supports_extend2_cells(node->rs, 1))
581  return false;
582  /* Don't choose nodes if we are certain they can't do ntor. */
583  if ((node->ri || node->md) && !node_has_curve25519_onion_key(node))
584  return false;
585  /* Exclude relays that allow single hop exit circuits. This is an
586  * obsolete option since 0.2.9.2-alpha and done by default in
587  * 0.3.1.0-alpha. */
589  return false;
590  /* Exclude relays that can not become a rendezvous for a hidden service
591  * version 3. */
592  if (rendezvous_v3 &&
594  return false;
595  /* Choose a node with an OR address that matches the firewall rules */
596  if (direct_conn && check_reach &&
598  FIREWALL_OR_CONNECTION,
599  pref_addr))
600  return false;
601  if (initiate_ipv6_extend && !node_supports_initiating_ipv6_extends(node))
602  return false;
603 
604  return true;
605 }
606 
607 /** Add every suitable node from our nodelist to <b>sl</b>, so that
608  * we can pick a node for a circuit based on <b>flags</b>.
609  *
610  * See router_can_choose_node() for details of <b>flags</b>.
611  */
612 void
614 {
616  if (!router_can_choose_node(node, flags))
617  continue;
618  smartlist_add(sl, (void *)node);
619  } SMARTLIST_FOREACH_END(node);
620 }
621 
622 /** Look through the routerlist until we find a router that has my key.
623  Return it. */
624 const routerinfo_t *
626 {
627  if (!routerlist)
628  return NULL;
629 
631  {
632  if (router_is_me(router))
633  return router;
634  });
635  return NULL;
636 }
637 
638 /** Return the smaller of the router's configured BandwidthRate
639  * and its advertised capacity. */
640 uint32_t
642 {
643  if (router->bandwidthcapacity < router->bandwidthrate)
644  return router->bandwidthcapacity;
645  return router->bandwidthrate;
646 }
647 
648 /** Do not weight any declared bandwidth more than this much when picking
649  * routers by bandwidth. */
650 #define DEFAULT_MAX_BELIEVABLE_BANDWIDTH 10000000 /* 10 MB/sec */
651 
652 /** Return the smaller of the router's configured BandwidthRate
653  * and its advertised capacity, capped by max-believe-bw. */
654 uint32_t
656 {
657  uint32_t result = router->bandwidthcapacity;
658  if (result > router->bandwidthrate)
659  result = router->bandwidthrate;
662  return result;
663 }
664 
665 /** Helper: given an extended nickname in <b>hexdigest</b> try to decode it.
666  * Return 0 on success, -1 on failure. Store the result into the
667  * DIGEST_LEN-byte buffer at <b>digest_out</b>, the single character at
668  * <b>nickname_qualifier_char_out</b>, and the MAXNICKNAME_LEN+1-byte buffer
669  * at <b>nickname_out</b>.
670  *
671  * The recognized format is:
672  * HexName = Dollar? HexDigest NamePart?
673  * Dollar = '?'
674  * HexDigest = HexChar*20
675  * HexChar = 'a'..'f' | 'A'..'F' | '0'..'9'
676  * NamePart = QualChar Name
677  * QualChar = '=' | '~'
678  * Name = NameChar*(1..MAX_NICKNAME_LEN)
679  * NameChar = Any ASCII alphanumeric character
680  */
681 int
682 hex_digest_nickname_decode(const char *hexdigest,
683  char *digest_out,
684  char *nickname_qualifier_char_out,
685  char *nickname_out)
686 {
687  size_t len;
688 
689  tor_assert(hexdigest);
690  if (hexdigest[0] == '$')
691  ++hexdigest;
692 
693  len = strlen(hexdigest);
694  if (len < HEX_DIGEST_LEN) {
695  return -1;
696  } else if (len > HEX_DIGEST_LEN && (hexdigest[HEX_DIGEST_LEN] == '=' ||
697  hexdigest[HEX_DIGEST_LEN] == '~') &&
698  len <= HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN) {
699  *nickname_qualifier_char_out = hexdigest[HEX_DIGEST_LEN];
700  strlcpy(nickname_out, hexdigest+HEX_DIGEST_LEN+1 , MAX_NICKNAME_LEN+1);
701  } else if (len == HEX_DIGEST_LEN) {
702  ;
703  } else {
704  return -1;
705  }
706 
707  if (base16_decode(digest_out, DIGEST_LEN,
708  hexdigest, HEX_DIGEST_LEN) != DIGEST_LEN)
709  return -1;
710  return 0;
711 }
712 
713 /** Helper: Return true iff the <b>identity_digest</b> and <b>nickname</b>
714  * combination of a router, encoded in hexadecimal, matches <b>hexdigest</b>
715  * (which is optionally prefixed with a single dollar sign). Return false if
716  * <b>hexdigest</b> is malformed, or it doesn't match. */
717 int
718 hex_digest_nickname_matches(const char *hexdigest, const char *identity_digest,
719  const char *nickname)
720 {
721  char digest[DIGEST_LEN];
722  char nn_char='\0';
723  char nn_buf[MAX_NICKNAME_LEN+1];
724 
725  if (hex_digest_nickname_decode(hexdigest, digest, &nn_char, nn_buf) == -1)
726  return 0;
727 
728  if (nn_char == '=') {
729  return 0;
730  }
731 
732  if (nn_char == '~') {
733  if (!nickname) // XXX This seems wrong. -NM
734  return 0;
735  if (strcasecmp(nn_buf, nickname))
736  return 0;
737  }
738 
739  return tor_memeq(digest, identity_digest, DIGEST_LEN);
740 }
741 
742 /** If hexdigest is correctly formed, base16_decode it into
743  * digest, which must have DIGEST_LEN space in it.
744  * Return 0 on success, -1 on failure.
745  */
746 int
747 hexdigest_to_digest(const char *hexdigest, char *digest)
748 {
749  if (hexdigest[0]=='$')
750  ++hexdigest;
751  if (strlen(hexdigest) < HEX_DIGEST_LEN ||
752  base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) != DIGEST_LEN)
753  return -1;
754  return 0;
755 }
756 
757 /** As router_get_by_id_digest,but return a pointer that you're allowed to
758  * modify */
759 routerinfo_t *
760 router_get_mutable_by_digest(const char *digest)
761 {
762  tor_assert(digest);
763 
764  if (!routerlist) return NULL;
765 
766  // routerlist_assert_ok(routerlist);
767 
768  return rimap_get(routerlist->identity_map, digest);
769 }
770 
771 /** Return the router in our routerlist whose 20-byte key digest
772  * is <b>digest</b>. Return NULL if no such router is known. */
773 const routerinfo_t *
774 router_get_by_id_digest(const char *digest)
775 {
776  return router_get_mutable_by_digest(digest);
777 }
778 
779 /** Return the router in our routerlist whose 20-byte descriptor
780  * is <b>digest</b>. Return NULL if no such router is known. */
783 {
784  tor_assert(digest);
785 
786  if (!routerlist) return NULL;
787 
788  return sdmap_get(routerlist->desc_digest_map, digest);
789 }
790 
791 /** Return the signed descriptor for the router in our routerlist whose
792  * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
793  * is known. */
795 router_get_by_extrainfo_digest,(const char *digest))
796 {
797  tor_assert(digest);
798 
799  if (!routerlist) return NULL;
800 
801  return sdmap_get(routerlist->desc_by_eid_map, digest);
802 }
803 
804 /** Return the signed descriptor for the extrainfo_t in our routerlist whose
805  * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
806  * document is known. */
809 {
810  extrainfo_t *ei;
811  tor_assert(digest);
812  if (!routerlist) return NULL;
813  ei = eimap_get(routerlist->extra_info_map, digest);
814  return ei ? &ei->cache_info : NULL;
815 }
816 
817 /** Return a pointer to the signed textual representation of a descriptor.
818  * The returned string is not guaranteed to be NUL-terminated: the string's
819  * length will be in desc->signed_descriptor_len.
820  *
821  * If <b>with_annotations</b> is set, the returned string will include
822  * the annotations
823  * (if any) preceding the descriptor. This will increase the length of the
824  * string by desc->annotations_len.
825  *
826  * The caller must not free the string returned.
827  */
828 static const char *
830  int with_annotations)
831 {
832  const char *r = NULL;
833  size_t len = desc->signed_descriptor_len;
834  off_t offset = desc->saved_offset;
835  if (with_annotations)
836  len += desc->annotations_len;
837  else
838  offset += desc->annotations_len;
839 
840  tor_assert(len > 32);
841  if (desc->saved_location == SAVED_IN_CACHE && routerlist) {
843  if (store && store->mmap) {
844  tor_assert(desc->saved_offset + len <= store->mmap->size);
845  r = store->mmap->data + offset;
846  } else if (store) {
847  log_err(LD_DIR, "We couldn't read a descriptor that is supposedly "
848  "mmaped in our cache. Is another process running in our data "
849  "directory? Exiting.");
850  exit(1); // XXXX bad exit: should recover.
851  }
852  }
853  if (!r) /* no mmap, or not in cache. */
854  r = desc->signed_descriptor_body +
855  (with_annotations ? 0 : desc->annotations_len);
856 
857  tor_assert(r);
858  if (!with_annotations) {
859  if (fast_memcmp("router ", r, 7) && fast_memcmp("extra-info ", r, 11)) {
860  char *cp = tor_strndup(r, 64);
861  log_err(LD_DIR, "descriptor at %p begins with unexpected string %s. "
862  "Is another process running in our data directory? Exiting.",
863  desc, escaped(cp));
864  exit(1); // XXXX bad exit: should recover.
865  }
866  }
867 
868  return r;
869 }
870 
871 /** Return a pointer to the signed textual representation of a descriptor.
872  * The returned string is not guaranteed to be NUL-terminated: the string's
873  * length will be in desc->signed_descriptor_len.
874  *
875  * The caller must not free the string returned.
876  */
877 const char *
879 {
880  return signed_descriptor_get_body_impl(desc, 0);
881 }
882 
883 /** As signed_descriptor_get_body(), but points to the beginning of the
884  * annotations section rather than the beginning of the descriptor. */
885 const char *
887 {
888  return signed_descriptor_get_body_impl(desc, 1);
889 }
890 
891 /** Return the current list of all known routers. */
892 routerlist_t *
894 {
895  if (PREDICT_UNLIKELY(!routerlist)) {
896  routerlist = tor_malloc_zero(sizeof(routerlist_t));
899  routerlist->identity_map = rimap_new();
900  routerlist->desc_digest_map = sdmap_new();
901  routerlist->desc_by_eid_map = sdmap_new();
902  routerlist->extra_info_map = eimap_new();
903 
904  routerlist->desc_store.fname_base = "cached-descriptors";
905  routerlist->extrainfo_store.fname_base = "cached-extrainfo";
906 
907  routerlist->desc_store.type = ROUTER_STORE;
908  routerlist->extrainfo_store.type = EXTRAINFO_STORE;
909 
910  routerlist->desc_store.description = "router descriptors";
911  routerlist->extrainfo_store.description = "extra-info documents";
912  }
913  return routerlist;
914 }
915 
916 /** Free all storage held by <b>router</b>. */
917 void
919 {
920  if (!router)
921  return;
922 
923  tor_free(router->cache_info.signed_descriptor_body);
924  tor_free(router->nickname);
925  tor_free(router->platform);
926  tor_free(router->protocol_list);
927  tor_free(router->contact_info);
928  if (router->onion_pkey)
929  tor_free(router->onion_pkey);
931  if (router->identity_pkey)
932  crypto_pk_free(router->identity_pkey);
933  tor_cert_free(router->cache_info.signing_key_cert);
934  if (router->declared_family) {
935  SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
936  smartlist_free(router->declared_family);
937  }
938  addr_policy_list_free(router->exit_policy);
939  short_policy_free(router->ipv6_exit_policy);
940 
941  memset(router, 77, sizeof(routerinfo_t));
942 
943  tor_free(router);
944 }
945 
946 /** Release all storage held by <b>extrainfo</b> */
947 void
949 {
950  if (!extrainfo)
951  return;
952  tor_cert_free(extrainfo->cache_info.signing_key_cert);
953  tor_free(extrainfo->cache_info.signed_descriptor_body);
954  tor_free(extrainfo->pending_sig);
955 
956  memset(extrainfo, 88, sizeof(extrainfo_t)); /* debug bad memory usage */
957  tor_free(extrainfo);
958 }
959 
960 #define signed_descriptor_free(val) \
961  FREE_AND_NULL(signed_descriptor_t, signed_descriptor_free_, (val))
962 
963 /** Release storage held by <b>sd</b>. */
964 static void
966 {
967  if (!sd)
968  return;
969 
971  tor_cert_free(sd->signing_key_cert);
972 
973  memset(sd, 99, sizeof(signed_descriptor_t)); /* Debug bad mem usage */
974  tor_free(sd);
975 }
976 
977 /** Reset the given signed descriptor <b>sd</b> by freeing the allocated
978  * memory inside the object and by zeroing its content. */
979 static void
981 {
982  tor_assert(sd);
984  tor_cert_free(sd->signing_key_cert);
985  memset(sd, 0, sizeof(*sd));
986 }
987 
988 /** Copy src into dest, and steal all references inside src so that when
989  * we free src, we don't mess up dest. */
990 static void
992  signed_descriptor_t *src)
993 {
994  tor_assert(dest != src);
995  /* Cleanup destination object before overwriting it.*/
997  memcpy(dest, src, sizeof(signed_descriptor_t));
998  src->signed_descriptor_body = NULL;
999  src->signing_key_cert = NULL;
1000  dest->routerlist_index = -1;
1001 }
1002 
1003 /** Extract a signed_descriptor_t from a general routerinfo, and free the
1004  * routerinfo.
1005  */
1006 static signed_descriptor_t *
1008 {
1009  signed_descriptor_t *sd;
1011  sd = tor_malloc_zero(sizeof(signed_descriptor_t));
1012  signed_descriptor_move(sd, &ri->cache_info);
1013  routerinfo_free(ri);
1014  return sd;
1015 }
1016 
1017 /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
1018 static void
1020 {
1021  extrainfo_free_(e);
1022 }
1023 
1024 /** Free all storage held by a routerlist <b>rl</b>. */
1025 void
1027 {
1028  if (!rl)
1029  return;
1030  rimap_free(rl->identity_map, NULL);
1031  sdmap_free(rl->desc_digest_map, NULL);
1032  sdmap_free(rl->desc_by_eid_map, NULL);
1033  eimap_free(rl->extra_info_map, extrainfo_free_void);
1035  routerinfo_free(r));
1037  signed_descriptor_free(sd));
1038  smartlist_free(rl->routers);
1039  smartlist_free(rl->old_routers);
1040  if (rl->desc_store.mmap) {
1041  int res = tor_munmap_file(rl->desc_store.mmap);
1042  if (res != 0) {
1043  log_warn(LD_FS, "Failed to munmap routerlist->desc_store.mmap");
1044  }
1045  }
1046  if (rl->extrainfo_store.mmap) {
1047  int res = tor_munmap_file(rl->extrainfo_store.mmap);
1048  if (res != 0) {
1049  log_warn(LD_FS, "Failed to munmap routerlist->extrainfo_store.mmap");
1050  }
1051  }
1052  tor_free(rl);
1053 }
1054 
1055 /** Log information about how much memory is being used for routerlist,
1056  * at log level <b>severity</b>. */
1057 void
1059 {
1060  uint64_t livedescs = 0;
1061  uint64_t olddescs = 0;
1062  if (!routerlist)
1063  return;
1065  livedescs += r->cache_info.signed_descriptor_len);
1067  olddescs += sd->signed_descriptor_len);
1068 
1069  tor_log(severity, LD_DIR,
1070  "In %d live descriptors: %"PRIu64" bytes. "
1071  "In %d old descriptors: %"PRIu64" bytes.",
1072  smartlist_len(routerlist->routers), (livedescs),
1073  smartlist_len(routerlist->old_routers), (olddescs));
1074 }
1075 
1076 /** Debugging helper: If <b>idx</b> is nonnegative, assert that <b>ri</b> is
1077  * in <b>sl</b> at position <b>idx</b>. Otherwise, search <b>sl</b> for
1078  * <b>ri</b>. Return the index of <b>ri</b> in <b>sl</b>, or -1 if <b>ri</b>
1079  * is not in <b>sl</b>. */
1080 static inline int
1081 routerlist_find_elt_(smartlist_t *sl, void *ri, int idx)
1082 {
1083  if (idx < 0) {
1084  idx = -1;
1086  if (r == ri) {
1087  idx = r_sl_idx;
1088  break;
1089  });
1090  } else {
1091  tor_assert(idx < smartlist_len(sl));
1092  tor_assert(smartlist_get(sl, idx) == ri);
1093  };
1094  return idx;
1095 }
1096 
1097 /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
1098  * as needed. There must be no previous member of <b>rl</b> with the same
1099  * identity digest as <b>ri</b>: If there is, call routerlist_replace
1100  * instead.
1101  */
1102 static void
1104 {
1105  routerinfo_t *ri_old;
1106  signed_descriptor_t *sd_old;
1107  {
1108  const routerinfo_t *ri_generated = router_get_my_routerinfo();
1109  tor_assert(ri_generated != ri);
1110  }
1111  tor_assert(ri->cache_info.routerlist_index == -1);
1112 
1113  ri_old = rimap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
1114  tor_assert(!ri_old);
1115 
1116  sd_old = sdmap_set(rl->desc_digest_map,
1117  ri->cache_info.signed_descriptor_digest,
1118  &(ri->cache_info));
1119  if (sd_old) {
1120  int idx = sd_old->routerlist_index;
1121  sd_old->routerlist_index = -1;
1122  smartlist_del(rl->old_routers, idx);
1123  if (idx < smartlist_len(rl->old_routers)) {
1124  signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
1125  d->routerlist_index = idx;
1126  }
1128  sdmap_remove(rl->desc_by_eid_map, sd_old->extra_info_digest);
1129  signed_descriptor_free(sd_old);
1130  }
1131 
1132  if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
1133  sdmap_set(rl->desc_by_eid_map, ri->cache_info.extra_info_digest,
1134  &ri->cache_info);
1135  smartlist_add(rl->routers, ri);
1136  ri->cache_info.routerlist_index = smartlist_len(rl->routers) - 1;
1137  nodelist_set_routerinfo(ri, NULL);
1139 #ifdef DEBUG_ROUTERLIST
1141 #endif
1142 }
1143 
1144 /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
1145  * corresponding router in rl->routers or rl->old_routers. Return the status
1146  * of inserting <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
1148 extrainfo_insert,(routerlist_t *rl, extrainfo_t *ei, int warn_if_incompatible))
1149 {
1151  const char *compatibility_error_msg;
1152  routerinfo_t *ri = rimap_get(rl->identity_map,
1153  ei->cache_info.identity_digest);
1154  signed_descriptor_t *sd =
1155  sdmap_get(rl->desc_by_eid_map, ei->cache_info.signed_descriptor_digest);
1156  extrainfo_t *ei_tmp;
1157  const int severity = warn_if_incompatible ? LOG_WARN : LOG_INFO;
1158 
1159  {
1160  extrainfo_t *ei_generated = router_get_my_extrainfo();
1161  tor_assert(ei_generated != ei);
1162  }
1163 
1164  if (!ri) {
1165  /* This router is unknown; we can't even verify the signature. Give up.*/
1166  r = ROUTER_NOT_IN_CONSENSUS;
1167  goto done;
1168  }
1169  if (! sd) {
1170  /* The extrainfo router doesn't have a known routerdesc to attach it to.
1171  * This just won't work. */;
1172  static ratelim_t no_sd_ratelim = RATELIM_INIT(1800);
1173  r = ROUTER_BAD_EI;
1174  /* This is a DEBUG because it can happen naturally, if we tried
1175  * to add an extrainfo for which we no longer have the
1176  * corresponding routerinfo.
1177  */
1178  log_fn_ratelim(&no_sd_ratelim, LOG_DEBUG, LD_DIR,
1179  "No entry found in extrainfo map.");
1180  goto done;
1181  }
1182  if (tor_memneq(ei->cache_info.signed_descriptor_digest,
1183  sd->extra_info_digest, DIGEST_LEN)) {
1184  static ratelim_t digest_mismatch_ratelim = RATELIM_INIT(1800);
1185  /* The sd we got from the map doesn't match the digest we used to look
1186  * it up. This makes no sense. */
1187  r = ROUTER_BAD_EI;
1188  log_fn_ratelim(&digest_mismatch_ratelim, severity, LD_BUG,
1189  "Mismatch in digest in extrainfo map.");
1190  goto done;
1191  }
1193  &compatibility_error_msg)) {
1194  char d1[HEX_DIGEST_LEN+1], d2[HEX_DIGEST_LEN+1];
1195  r = (ri->cache_info.extrainfo_is_bogus) ?
1196  ROUTER_BAD_EI : ROUTER_NOT_IN_CONSENSUS;
1197 
1198  base16_encode(d1, sizeof(d1), ri->cache_info.identity_digest, DIGEST_LEN);
1199  base16_encode(d2, sizeof(d2), ei->cache_info.identity_digest, DIGEST_LEN);
1200 
1201  log_fn(severity,LD_DIR,
1202  "router info incompatible with extra info (ri id: %s, ei id %s, "
1203  "reason: %s)", d1, d2, compatibility_error_msg);
1204 
1205  goto done;
1206  }
1207 
1208  /* Okay, if we make it here, we definitely have a router corresponding to
1209  * this extrainfo. */
1210 
1211  ei_tmp = eimap_set(rl->extra_info_map,
1212  ei->cache_info.signed_descriptor_digest,
1213  ei);
1214  r = ROUTER_ADDED_SUCCESSFULLY;
1215  if (ei_tmp) {
1217  ei_tmp->cache_info.signed_descriptor_len;
1218  extrainfo_free(ei_tmp);
1219  }
1220 
1221  done:
1222  if (r != ROUTER_ADDED_SUCCESSFULLY)
1223  extrainfo_free(ei);
1224 
1225 #ifdef DEBUG_ROUTERLIST
1227 #endif
1228  return r;
1229 }
1230 
1231 #define should_cache_old_descriptors() \
1232  directory_caches_dir_info(get_options())
1233 
1234 /** If we're a directory cache and routerlist <b>rl</b> doesn't have
1235  * a copy of router <b>ri</b> yet, add it to the list of old (not
1236  * recommended but still served) descriptors. Else free it. */
1237 static void
1239 {
1240  {
1241  const routerinfo_t *ri_generated = router_get_my_routerinfo();
1242  tor_assert(ri_generated != ri);
1243  }
1244  tor_assert(ri->cache_info.routerlist_index == -1);
1245 
1246  if (should_cache_old_descriptors() &&
1248  !sdmap_get(rl->desc_digest_map,
1249  ri->cache_info.signed_descriptor_digest)) {
1251  sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1252  smartlist_add(rl->old_routers, sd);
1253  sd->routerlist_index = smartlist_len(rl->old_routers)-1;
1255  sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
1256  } else {
1257  routerinfo_free(ri);
1258  }
1259 #ifdef DEBUG_ROUTERLIST
1261 #endif
1262 }
1263 
1264 /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
1265  * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
1266  * idx) == ri, we don't need to do a linear search over the list to decide
1267  * which to remove. We fill the gap in rl-&gt;routers with a later element in
1268  * the list, if any exists. <b>ri</b> is freed.
1269  *
1270  * If <b>make_old</b> is true, instead of deleting the router, we try adding
1271  * it to rl-&gt;old_routers. */
1272 void
1273 routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old, time_t now)
1274 {
1275  routerinfo_t *ri_tmp;
1276  extrainfo_t *ei_tmp;
1277  int idx = ri->cache_info.routerlist_index;
1278  tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
1279  tor_assert(smartlist_get(rl->routers, idx) == ri);
1280 
1282 
1283  /* make sure the rephist module knows that it's not running */
1285 
1286  ri->cache_info.routerlist_index = -1;
1287  smartlist_del(rl->routers, idx);
1288  if (idx < smartlist_len(rl->routers)) {
1289  routerinfo_t *r = smartlist_get(rl->routers, idx);
1290  r->cache_info.routerlist_index = idx;
1291  }
1292 
1293  ri_tmp = rimap_remove(rl->identity_map, ri->cache_info.identity_digest);
1295  tor_assert(ri_tmp == ri);
1296 
1297  if (make_old && should_cache_old_descriptors() &&
1299  signed_descriptor_t *sd;
1301  smartlist_add(rl->old_routers, sd);
1302  sd->routerlist_index = smartlist_len(rl->old_routers)-1;
1303  sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1305  sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
1306  } else {
1307  signed_descriptor_t *sd_tmp;
1308  sd_tmp = sdmap_remove(rl->desc_digest_map,
1309  ri->cache_info.signed_descriptor_digest);
1310  tor_assert(sd_tmp == &(ri->cache_info));
1311  rl->desc_store.bytes_dropped += ri->cache_info.signed_descriptor_len;
1312  ei_tmp = eimap_remove(rl->extra_info_map,
1313  ri->cache_info.extra_info_digest);
1314  if (ei_tmp) {
1316  ei_tmp->cache_info.signed_descriptor_len;
1317  extrainfo_free(ei_tmp);
1318  }
1319  if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
1320  sdmap_remove(rl->desc_by_eid_map, ri->cache_info.extra_info_digest);
1321  routerinfo_free(ri);
1322  }
1323 #ifdef DEBUG_ROUTERLIST
1325 #endif
1326 }
1327 
1328 /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>->old_routers, and
1329  * adjust <b>rl</b> as appropriate. <b>idx</b> is -1, or the index of
1330  * <b>sd</b>. */
1331 static void
1333 {
1334  signed_descriptor_t *sd_tmp;
1335  extrainfo_t *ei_tmp;
1336  desc_store_t *store;
1337  if (idx == -1) {
1338  idx = sd->routerlist_index;
1339  }
1340  tor_assert(0 <= idx && idx < smartlist_len(rl->old_routers));
1341  /* XXXX edmanm's bridge relay triggered the following assert while
1342  * running 0.2.0.12-alpha. If anybody triggers this again, see if we
1343  * can get a backtrace. */
1344  tor_assert(smartlist_get(rl->old_routers, idx) == sd);
1345  tor_assert(idx == sd->routerlist_index);
1346 
1347  sd->routerlist_index = -1;
1348  smartlist_del(rl->old_routers, idx);
1349  if (idx < smartlist_len(rl->old_routers)) {
1350  signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
1351  d->routerlist_index = idx;
1352  }
1353  sd_tmp = sdmap_remove(rl->desc_digest_map,
1355  tor_assert(sd_tmp == sd);
1356  store = desc_get_store(rl, sd);
1357  if (store)
1358  store->bytes_dropped += sd->signed_descriptor_len;
1359 
1360  ei_tmp = eimap_remove(rl->extra_info_map,
1361  sd->extra_info_digest);
1362  if (ei_tmp) {
1364  ei_tmp->cache_info.signed_descriptor_len;
1365  extrainfo_free(ei_tmp);
1366  }
1368  sdmap_remove(rl->desc_by_eid_map, sd->extra_info_digest);
1369 
1370  signed_descriptor_free(sd);
1371 #ifdef DEBUG_ROUTERLIST
1373 #endif
1374 }
1375 
1376 /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
1377  * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
1378  * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
1379  * search over the list to decide which to remove. We put ri_new in the same
1380  * index as ri_old, if possible. ri is freed as appropriate.
1381  *
1382  * If should_cache_descriptors() is true, instead of deleting the router,
1383  * we add it to rl-&gt;old_routers. */
1384 static void
1386  routerinfo_t *ri_new)
1387 {
1388  int idx;
1389  int same_descriptors;
1390 
1391  routerinfo_t *ri_tmp;
1392  extrainfo_t *ei_tmp;
1393  {
1394  const routerinfo_t *ri_generated = router_get_my_routerinfo();
1395  tor_assert(ri_generated != ri_new);
1396  }
1397  tor_assert(ri_old != ri_new);
1398  tor_assert(ri_new->cache_info.routerlist_index == -1);
1399 
1400  idx = ri_old->cache_info.routerlist_index;
1401  tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
1402  tor_assert(smartlist_get(rl->routers, idx) == ri_old);
1403 
1404  {
1405  routerinfo_t *ri_old_tmp=NULL;
1406  nodelist_set_routerinfo(ri_new, &ri_old_tmp);
1407  tor_assert(ri_old == ri_old_tmp);
1408  }
1409 
1411  if (idx >= 0) {
1412  smartlist_set(rl->routers, idx, ri_new);
1413  ri_old->cache_info.routerlist_index = -1;
1414  ri_new->cache_info.routerlist_index = idx;
1415  /* Check that ri_old is not in rl->routers anymore: */
1416  tor_assert( routerlist_find_elt_(rl->routers, ri_old, -1) == -1 );
1417  } else {
1418  log_warn(LD_BUG, "Appending entry from routerlist_replace.");
1419  routerlist_insert(rl, ri_new);
1420  return;
1421  }
1422  if (tor_memneq(ri_old->cache_info.identity_digest,
1423  ri_new->cache_info.identity_digest, DIGEST_LEN)) {
1424  /* digests don't match; digestmap_set won't replace */
1425  rimap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
1426  }
1427  ri_tmp = rimap_set(rl->identity_map,
1428  ri_new->cache_info.identity_digest, ri_new);
1429  tor_assert(!ri_tmp || ri_tmp == ri_old);
1430  sdmap_set(rl->desc_digest_map,
1431  ri_new->cache_info.signed_descriptor_digest,
1432  &(ri_new->cache_info));
1433 
1434  if (!tor_digest_is_zero(ri_new->cache_info.extra_info_digest)) {
1435  sdmap_set(rl->desc_by_eid_map, ri_new->cache_info.extra_info_digest,
1436  &ri_new->cache_info);
1437  }
1438 
1439  same_descriptors = tor_memeq(ri_old->cache_info.signed_descriptor_digest,
1440  ri_new->cache_info.signed_descriptor_digest,
1441  DIGEST_LEN);
1442 
1443  if (should_cache_old_descriptors() &&
1444  ri_old->purpose == ROUTER_PURPOSE_GENERAL &&
1445  !same_descriptors) {
1446  /* ri_old is going to become a signed_descriptor_t and go into
1447  * old_routers */
1449  smartlist_add(rl->old_routers, sd);
1450  sd->routerlist_index = smartlist_len(rl->old_routers)-1;
1451  sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
1453  sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
1454  } else {
1455  /* We're dropping ri_old. */
1456  if (!same_descriptors) {
1457  /* digests don't match; The sdmap_set above didn't replace */
1458  sdmap_remove(rl->desc_digest_map,
1459  ri_old->cache_info.signed_descriptor_digest);
1460 
1461  if (tor_memneq(ri_old->cache_info.extra_info_digest,
1462  ri_new->cache_info.extra_info_digest, DIGEST_LEN)) {
1463  ei_tmp = eimap_remove(rl->extra_info_map,
1464  ri_old->cache_info.extra_info_digest);
1465  if (ei_tmp) {
1467  ei_tmp->cache_info.signed_descriptor_len;
1468  extrainfo_free(ei_tmp);
1469  }
1470  }
1471 
1472  if (!tor_digest_is_zero(ri_old->cache_info.extra_info_digest)) {
1473  sdmap_remove(rl->desc_by_eid_map,
1474  ri_old->cache_info.extra_info_digest);
1475  }
1476  }
1477  rl->desc_store.bytes_dropped += ri_old->cache_info.signed_descriptor_len;
1478  routerinfo_free(ri_old);
1479  }
1480 #ifdef DEBUG_ROUTERLIST
1482 #endif
1483 }
1484 
1485 /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
1486  * it as a fresh routerinfo_t. */
1487 static routerinfo_t *
1489 {
1490  routerinfo_t *ri;
1491  const char *body;
1492 
1494 
1497  0, 1, NULL, NULL);
1498  if (!ri)
1499  return NULL;
1500  signed_descriptor_move(&ri->cache_info, sd);
1501 
1502  routerlist_remove_old(rl, sd, -1);
1503 
1504  return ri;
1505 }
1506 
1507 /** Free all memory held by the routerlist module.
1508  * Note: Calling routerlist_free_all() should always be paired with
1509  * a call to nodelist_free_all(). These should only be called during
1510  * cleanup.
1511  */
1512 void
1514 {
1515  routerlist_t *rl = routerlist;
1516  routerlist = NULL; // Prevent internals of routerlist_free() from using
1517  // routerlist.
1518  routerlist_free(rl);
1519  dirlist_free_all();
1520  if (warned_nicknames) {
1521  SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1522  smartlist_free(warned_nicknames);
1523  warned_nicknames = NULL;
1524  }
1525  authcert_free_all();
1526 }
1527 
1528 /** Forget that we have issued any router-related warnings, so that we'll
1529  * warn again if we see the same errors. */
1530 void
1532 {
1533  if (!warned_nicknames)
1535  SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
1536  smartlist_clear(warned_nicknames); /* now the list is empty. */
1537 
1539 }
1540 
1541 /** Return 1 if the signed descriptor of this router is older than
1542  * <b>seconds</b> seconds. Otherwise return 0. */
1543 MOCK_IMPL(int,
1544 router_descriptor_is_older_than,(const routerinfo_t *router, int seconds))
1545 {
1546  return router->cache_info.published_on < approx_time() - seconds;
1547 }
1548 
1549 /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
1550  * older entries (if any) with the same key.
1551  *
1552  * Note: Callers should not hold their pointers to <b>router</b> if this
1553  * function fails; <b>router</b> will either be inserted into the routerlist or
1554  * freed. Similarly, even if this call succeeds, they should not hold their
1555  * pointers to <b>router</b> after subsequent calls with other routerinfo's --
1556  * they might cause the original routerinfo to get freed.
1557  *
1558  * Returns the status for the operation. Might set *<b>msg</b> if it wants
1559  * the poster of the router to know something.
1560  *
1561  * If <b>from_cache</b>, this descriptor came from our disk cache. If
1562  * <b>from_fetch</b>, we received it in response to a request we made.
1563  * (If both are false, that means it was uploaded to us as an auth dir
1564  * server or via the controller.)
1565  *
1566  * This function should be called *after*
1567  * routers_update_status_from_consensus_networkstatus; subsequently, you
1568  * should call router_rebuild_store and routerlist_descriptors_added.
1569  */
1571 router_add_to_routerlist(routerinfo_t *router, const char **msg,
1572  int from_cache, int from_fetch)
1573 {
1574  const char *id_digest;
1575  const or_options_t *options = get_options();
1576  int authdir = authdir_mode_handles_descs(options, router->purpose);
1577  int authdir_believes_valid = 0;
1578  routerinfo_t *old_router;
1579  networkstatus_t *consensus =
1581  int in_consensus = 0;
1582 
1583  tor_assert(msg);
1584 
1585  if (!routerlist)
1587 
1588  id_digest = router->cache_info.identity_digest;
1589 
1590  old_router = router_get_mutable_by_digest(id_digest);
1591 
1592  /* Make sure that it isn't expired. */
1593  if (router->cert_expiration_time < approx_time()) {
1594  routerinfo_free(router);
1595  *msg = "Some certs on this router are expired.";
1596  return ROUTER_CERTS_EXPIRED;
1597  }
1598 
1599  /* Make sure that we haven't already got this exact descriptor. */
1600  if (sdmap_get(routerlist->desc_digest_map,
1601  router->cache_info.signed_descriptor_digest)) {
1602  /* If we have this descriptor already and the new descriptor is a bridge
1603  * descriptor, replace it. If we had a bridge descriptor before and the
1604  * new one is not a bridge descriptor, don't replace it. */
1605 
1606  /* Only members of routerlist->identity_map can be bridges; we don't
1607  * put bridges in old_routers. */
1608  const int was_bridge = old_router &&
1609  old_router->purpose == ROUTER_PURPOSE_BRIDGE;
1610 
1611  if (routerinfo_is_a_configured_bridge(router) &&
1612  router->purpose == ROUTER_PURPOSE_BRIDGE &&
1613  !was_bridge) {
1614  log_info(LD_DIR, "Replacing non-bridge descriptor with bridge "
1615  "descriptor for router %s",
1616  router_describe(router));
1617  } else {
1618  log_info(LD_DIR,
1619  "Dropping descriptor that we already have for router %s",
1620  router_describe(router));
1621  *msg = "Router descriptor was not new.";
1622  routerinfo_free(router);
1623  return ROUTER_IS_ALREADY_KNOWN;
1624  }
1625  }
1626 
1627  if (authdir) {
1628  if (authdir_wants_to_reject_router(router, msg,
1629  !from_cache && !from_fetch,
1630  &authdir_believes_valid)) {
1631  tor_assert(*msg);
1632  routerinfo_free(router);
1633  return ROUTER_AUTHDIR_REJECTS;
1634  }
1635  } else if (from_fetch) {
1636  /* Only check the descriptor digest against the network statuses when
1637  * we are receiving in response to a fetch. */
1638 
1639  if (!signed_desc_digest_is_recognized(&router->cache_info) &&
1641  /* We asked for it, so some networkstatus must have listed it when we
1642  * did. Save it if we're a cache in case somebody else asks for it. */
1643  log_info(LD_DIR,
1644  "Received a no-longer-recognized descriptor for router %s",
1645  router_describe(router));
1646  *msg = "Router descriptor is not referenced by any network-status.";
1647 
1648  /* Only journal this desc if we want to keep old descriptors */
1649  if (!from_cache && should_cache_old_descriptors())
1650  signed_desc_append_to_journal(&router->cache_info,
1653  return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS;
1654  }
1655  }
1656 
1657  /* We no longer need a router with this descriptor digest. */
1658  if (consensus) {
1660  consensus, id_digest);
1661  if (rs && tor_memeq(rs->descriptor_digest,
1662  router->cache_info.signed_descriptor_digest,
1663  DIGEST_LEN)) {
1664  in_consensus = 1;
1665  }
1666  }
1667 
1668  if (router->purpose == ROUTER_PURPOSE_GENERAL &&
1669  consensus && !in_consensus && !authdir) {
1670  /* If it's a general router not listed in the consensus, then don't
1671  * consider replacing the latest router with it. */
1672  if (!from_cache && should_cache_old_descriptors())
1673  signed_desc_append_to_journal(&router->cache_info,
1676  *msg = "Skipping router descriptor: not in consensus.";
1677  return ROUTER_NOT_IN_CONSENSUS;
1678  }
1679 
1680  /* If we're reading a bridge descriptor from our cache, and we don't
1681  * recognize it as one of our currently configured bridges, drop the
1682  * descriptor. Otherwise we could end up using it as one of our entry
1683  * guards even if it isn't in our Bridge config lines. */
1684  if (router->purpose == ROUTER_PURPOSE_BRIDGE && from_cache &&
1685  !authdir_mode_bridge(options) &&
1687  log_info(LD_DIR, "Dropping bridge descriptor for %s because we have "
1688  "no bridge configured at that address.",
1689  safe_str_client(router_describe(router)));
1690  *msg = "Router descriptor was not a configured bridge.";
1691  routerinfo_free(router);
1692  return ROUTER_WAS_NOT_WANTED;
1693  }
1694 
1695  /* If we have a router with the same identity key, choose the newer one. */
1696  if (old_router) {
1697  if (!in_consensus && (router->cache_info.published_on <=
1698  old_router->cache_info.published_on)) {
1699  /* Same key, but old. This one is not listed in the consensus. */
1700  log_debug(LD_DIR, "Not-new descriptor for router %s",
1701  router_describe(router));
1702  /* Only journal this desc if we'll be serving it. */
1703  if (!from_cache && should_cache_old_descriptors())
1704  signed_desc_append_to_journal(&router->cache_info,
1707  *msg = "Router descriptor was not new.";
1708  return ROUTER_IS_ALREADY_KNOWN;
1709  } else {
1710  /* Same key, and either new, or listed in the consensus. */
1711  log_debug(LD_DIR, "Replacing entry for router %s",
1712  router_describe(router));
1713  routerlist_replace(routerlist, old_router, router);
1714  if (!from_cache) {
1715  signed_desc_append_to_journal(&router->cache_info,
1717  }
1718  *msg = authdir_believes_valid ? "Valid server updated" :
1719  ("Invalid server updated. (This dirserver is marking your "
1720  "server as unapproved.)");
1721  return ROUTER_ADDED_SUCCESSFULLY;
1722  }
1723  }
1724 
1725  if (!in_consensus && from_cache &&
1727  *msg = "Router descriptor was really old.";
1728  routerinfo_free(router);
1729  return ROUTER_WAS_TOO_OLD;
1730  }
1731 
1732  /* We haven't seen a router with this identity before. Add it to the end of
1733  * the list. */
1734  routerlist_insert(routerlist, router);
1735  if (!from_cache) {
1736  signed_desc_append_to_journal(&router->cache_info,
1738  }
1739  return ROUTER_ADDED_SUCCESSFULLY;
1740 }
1741 
1742 /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
1743  * as for router_add_to_routerlist(). Return ROUTER_ADDED_SUCCESSFULLY iff
1744  * we actually inserted it, ROUTER_BAD_EI otherwise.
1745  */
1748  int from_cache, int from_fetch)
1749 {
1750  was_router_added_t inserted;
1751  (void)from_fetch;
1752  if (msg) *msg = NULL;
1753  /*XXXX Do something with msg */
1754 
1755  inserted = extrainfo_insert(router_get_routerlist(), ei, !from_cache);
1756 
1757  if (WRA_WAS_ADDED(inserted) && !from_cache)
1758  signed_desc_append_to_journal(&ei->cache_info,
1760 
1761  return inserted;
1762 }
1763 
1764 /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
1765  * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
1766  * to, or later than that of *<b>b</b>. */
1767 static int
1768 compare_old_routers_by_identity_(const void **_a, const void **_b)
1769 {
1770  int i;
1771  const signed_descriptor_t *r1 = *_a, *r2 = *_b;
1772  if ((i = fast_memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
1773  return i;
1774  return (int)(r1->published_on - r2->published_on);
1775 }
1776 
1777 /** Internal type used to represent how long an old descriptor was valid,
1778  * where it appeared in the list of old descriptors, and whether it's extra
1779  * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
1781  int duration;
1782  int idx;
1783  int old;
1784 };
1785 
1786 /** Sorting helper: compare two duration_idx_t by their duration. */
1787 static int
1788 compare_duration_idx_(const void *_d1, const void *_d2)
1789 {
1790  const struct duration_idx_t *d1 = _d1;
1791  const struct duration_idx_t *d2 = _d2;
1792  return d1->duration - d2->duration;
1793 }
1794 
1795 /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
1796  * must contain routerinfo_t with the same identity and with publication time
1797  * in ascending order. Remove members from this range until there are no more
1798  * than max_descriptors_per_router() remaining. Start by removing the oldest
1799  * members from before <b>cutoff</b>, then remove members which were current
1800  * for the lowest amount of time. The order of members of old_routers at
1801  * indices <b>lo</b> or higher may be changed.
1802  */
1803 static void
1805  time_t cutoff, int lo, int hi,
1806  digestset_t *retain)
1807 {
1808  int i, n = hi-lo+1;
1809  unsigned n_extra, n_rmv = 0;
1810  struct duration_idx_t *lifespans;
1811  uint8_t *rmv, *must_keep;
1813 #if 1
1814  const char *ident;
1815  tor_assert(hi < smartlist_len(lst));
1816  tor_assert(lo <= hi);
1817  ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
1818  for (i = lo+1; i <= hi; ++i) {
1819  signed_descriptor_t *r = smartlist_get(lst, i);
1821  }
1822 #endif /* 1 */
1823  /* Check whether we need to do anything at all. */
1824  {
1825  int mdpr = directory_caches_dir_info(get_options()) ? 2 : 1;
1826  if (n <= mdpr)
1827  return;
1828  n_extra = n - mdpr;
1829  }
1830 
1831  lifespans = tor_calloc(n, sizeof(struct duration_idx_t));
1832  rmv = tor_calloc(n, sizeof(uint8_t));
1833  must_keep = tor_calloc(n, sizeof(uint8_t));
1834  /* Set lifespans to contain the lifespan and index of each server. */
1835  /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
1836  for (i = lo; i <= hi; ++i) {
1837  signed_descriptor_t *r = smartlist_get(lst, i);
1838  signed_descriptor_t *r_next;
1839  lifespans[i-lo].idx = i;
1840  if (r->last_listed_as_valid_until >= now ||
1841  (retain && digestset_probably_contains(retain,
1842  r->signed_descriptor_digest))) {
1843  must_keep[i-lo] = 1;
1844  }
1845  if (i < hi) {
1846  r_next = smartlist_get(lst, i+1);
1847  tor_assert(r->published_on <= r_next->published_on);
1848  lifespans[i-lo].duration = (int)(r_next->published_on - r->published_on);
1849  } else {
1850  r_next = NULL;
1851  lifespans[i-lo].duration = INT_MAX;
1852  }
1853  if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
1854  ++n_rmv;
1855  lifespans[i-lo].old = 1;
1856  rmv[i-lo] = 1;
1857  }
1858  }
1859 
1860  if (n_rmv < n_extra) {
1861  /**
1862  * We aren't removing enough servers for being old. Sort lifespans by
1863  * the duration of liveness, and remove the ones we're not already going to
1864  * remove based on how long they were alive.
1865  **/
1866  qsort(lifespans, n, sizeof(struct duration_idx_t), compare_duration_idx_);
1867  for (i = 0; i < n && n_rmv < n_extra; ++i) {
1868  if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
1869  rmv[lifespans[i].idx-lo] = 1;
1870  ++n_rmv;
1871  }
1872  }
1873  }
1874 
1875  i = hi;
1876  do {
1877  if (rmv[i-lo])
1878  routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
1879  } while (--i >= lo);
1880  tor_free(must_keep);
1881  tor_free(rmv);
1882  tor_free(lifespans);
1883 }
1884 
1885 /** Deactivate any routers from the routerlist that are more than
1886  * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
1887  * remove old routers from the list of cached routers if we have too many.
1888  */
1889 void
1891 {
1892  int i, hi=-1;
1893  const char *cur_id = NULL;
1894  time_t now = time(NULL);
1895  time_t cutoff;
1896  routerinfo_t *router;
1897  signed_descriptor_t *sd;
1898  digestset_t *retain;
1900 
1902 
1903  if (!routerlist || !consensus)
1904  return;
1905 
1906  // routerlist_assert_ok(routerlist);
1907 
1908  /* We need to guess how many router descriptors we will wind up wanting to
1909  retain, so that we can be sure to allocate a large enough Bloom filter
1910  to hold the digest set. Overestimating is fine; underestimating is bad.
1911  */
1912  {
1913  /* We'll probably retain everything in the consensus. */
1914  int n_max_retain = smartlist_len(consensus->routerstatus_list);
1915  retain = digestset_new(n_max_retain);
1916  }
1917 
1918  cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
1919  /* Retain anything listed in the consensus. */
1920  if (consensus) {
1922  if (rs->published_on >= cutoff)
1923  digestset_add(retain, rs->descriptor_digest));
1924  }
1925 
1926  /* If we have a consensus, we should consider pruning current routers that
1927  * are too old and that nobody recommends. (If we don't have a consensus,
1928  * then we should get one before we decide to kill routers.) */
1929 
1930  if (consensus) {
1931  cutoff = now - ROUTER_MAX_AGE;
1932  /* Remove too-old unrecommended members of routerlist->routers. */
1933  for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
1934  router = smartlist_get(routerlist->routers, i);
1935  if (router->cache_info.published_on <= cutoff &&
1936  router->cache_info.last_listed_as_valid_until < now &&
1938  router->cache_info.signed_descriptor_digest)) {
1939  /* Too old: remove it. (If we're a cache, just move it into
1940  * old_routers.) */
1941  log_info(LD_DIR,
1942  "Forgetting obsolete (too old) routerinfo for router %s",
1943  router_describe(router));
1944  routerlist_remove(routerlist, router, 1, now);
1945  i--;
1946  }
1947  }
1948  }
1949 
1950  //routerlist_assert_ok(routerlist);
1951 
1952  /* Remove far-too-old members of routerlist->old_routers. */
1953  cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
1954  for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
1955  sd = smartlist_get(routerlist->old_routers, i);
1956  if (sd->published_on <= cutoff &&
1957  sd->last_listed_as_valid_until < now &&
1959  /* Too old. Remove it. */
1961  }
1962  }
1963 
1964  //routerlist_assert_ok(routerlist);
1965 
1966  log_info(LD_DIR, "We have %d live routers and %d old router descriptors.",
1967  smartlist_len(routerlist->routers),
1968  smartlist_len(routerlist->old_routers));
1969 
1970  /* Now we might have to look at routerlist->old_routers for extraneous
1971  * members. (We'd keep all the members if we could, but we need to save
1972  * space.) First, check whether we have too many router descriptors, total.
1973  * We're okay with having too many for some given router, so long as the
1974  * total number doesn't approach max_descriptors_per_router()*len(router).
1975  */
1976  if (smartlist_len(routerlist->old_routers) <
1977  smartlist_len(routerlist->routers))
1978  goto done;
1979 
1980  /* Sort by identity, then fix indices. */
1982  /* Fix indices. */
1983  for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
1984  signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
1985  r->routerlist_index = i;
1986  }
1987 
1988  /* Iterate through the list from back to front, so when we remove descriptors
1989  * we don't mess up groups we haven't gotten to. */
1990  for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
1991  signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
1992  if (!cur_id) {
1993  cur_id = r->identity_digest;
1994  hi = i;
1995  }
1996  if (tor_memneq(cur_id, r->identity_digest, DIGEST_LEN)) {
1998  cutoff, i+1, hi, retain);
1999  cur_id = r->identity_digest;
2000  hi = i;
2001  }
2002  }
2003  if (hi>=0)
2004  routerlist_remove_old_cached_routers_with_id(now, cutoff, 0, hi, retain);
2005  //routerlist_assert_ok(routerlist);
2006 
2007  done:
2008  digestset_free(retain);
2009  router_rebuild_store(RRS_DONT_REMOVE_OLD, &routerlist->desc_store);
2010  router_rebuild_store(RRS_DONT_REMOVE_OLD,&routerlist->extrainfo_store);
2011 }
2012 
2013 /** We just added a new set of descriptors. Take whatever extra steps
2014  * we need. */
2015 void
2017 {
2018  // XXXX use pubsub mechanism here.
2019 
2020  tor_assert(sl);
2023  if (ri->purpose == ROUTER_PURPOSE_BRIDGE)
2024  learned_bridge_descriptor(ri, from_cache);
2025  if (ri->needs_retest_if_added) {
2026  ri->needs_retest_if_added = 0;
2028  }
2029  } SMARTLIST_FOREACH_END(ri);
2030 }
2031 
2032 /**
2033  * Code to parse a single router descriptor and insert it into the
2034  * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
2035  * descriptor was well-formed but could not be added; and 1 if the
2036  * descriptor was added.
2037  *
2038  * If we don't add it and <b>msg</b> is not NULL, then assign to
2039  * *<b>msg</b> a static string describing the reason for refusing the
2040  * descriptor.
2041  *
2042  * This is used only by the controller.
2043  */
2044 int
2045 router_load_single_router(const char *s, uint8_t purpose, int cache,
2046  const char **msg)
2047 {
2048  routerinfo_t *ri;
2050  smartlist_t *lst;
2051  char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
2052  tor_assert(msg);
2053  *msg = NULL;
2054 
2055  tor_snprintf(annotation_buf, sizeof(annotation_buf),
2056  "@source controller\n"
2057  "@purpose %s\n", router_purpose_to_string(purpose));
2058 
2059  if (!(ri = router_parse_entry_from_string(s, NULL, 1, 0,
2060  annotation_buf, NULL))) {
2061  log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
2062  *msg = "Couldn't parse router descriptor.";
2063  return -1;
2064  }
2065  tor_assert(ri->purpose == purpose);
2066  if (router_is_me(ri)) {
2067  log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
2068  *msg = "Router's identity key matches mine.";
2069  routerinfo_free(ri);
2070  return 0;
2071  }
2072 
2073  if (!cache) /* obey the preference of the controller */
2074  ri->cache_info.do_not_cache = 1;
2075 
2076  lst = smartlist_new();
2077  smartlist_add(lst, ri);
2079 
2080  r = router_add_to_routerlist(ri, msg, 0, 0);
2081  if (!WRA_WAS_ADDED(r)) {
2082  /* we've already assigned to *msg now, and ri is already freed */
2083  tor_assert(*msg);
2084  if (r == ROUTER_AUTHDIR_REJECTS)
2085  log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
2086  smartlist_free(lst);
2087  return 0;
2088  } else {
2090  smartlist_free(lst);
2091  log_debug(LD_DIR, "Added router to list");
2092  return 1;
2093  }
2094 }
2095 
2096 /** Given a string <b>s</b> containing some routerdescs, parse it and put the
2097  * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
2098  * are in response to a query to the network: cache them by adding them to
2099  * the journal.
2100  *
2101  * Return the number of routers actually added.
2102  *
2103  * If <b>requested_fingerprints</b> is provided, it must contain a list of
2104  * uppercased fingerprints. Do not update any router whose
2105  * fingerprint is not on the list; after updating a router, remove its
2106  * fingerprint from the list.
2107  *
2108  * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
2109  * are descriptor digests. Otherwise they are identity digests.
2110  */
2111 int
2112 router_load_routers_from_string(const char *s, const char *eos,
2113  saved_location_t saved_location,
2114  smartlist_t *requested_fingerprints,
2115  int descriptor_digests,
2116  const char *prepend_annotations)
2117 {
2118  smartlist_t *routers = smartlist_new(), *changed = smartlist_new();
2119  char fp[HEX_DIGEST_LEN+1];
2120  const char *msg;
2121  int from_cache = (saved_location != SAVED_NOWHERE);
2122  int allow_annotations = (saved_location != SAVED_NOWHERE);
2123  int any_changed = 0;
2124  smartlist_t *invalid_digests = smartlist_new();
2125 
2126  router_parse_list_from_string(&s, eos, routers, saved_location, 0,
2127  allow_annotations, prepend_annotations,
2128  invalid_digests);
2129 
2131 
2132  log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
2133 
2134  SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
2136  char d[DIGEST_LEN];
2137  if (requested_fingerprints) {
2138  base16_encode(fp, sizeof(fp), descriptor_digests ?
2139  ri->cache_info.signed_descriptor_digest :
2140  ri->cache_info.identity_digest,
2141  DIGEST_LEN);
2142  if (smartlist_contains_string(requested_fingerprints, fp)) {
2143  smartlist_string_remove(requested_fingerprints, fp);
2144  } else {
2145  char *requested =
2146  smartlist_join_strings(requested_fingerprints," ",0,NULL);
2147  log_warn(LD_DIR,
2148  "We received a router descriptor with a fingerprint (%s) "
2149  "that we never requested. (We asked for: %s.) Dropping.",
2150  fp, requested);
2151  tor_free(requested);
2152  routerinfo_free(ri);
2153  continue;
2154  }
2155  }
2156 
2157  memcpy(d, ri->cache_info.signed_descriptor_digest, DIGEST_LEN);
2158  r = router_add_to_routerlist(ri, &msg, from_cache, !from_cache);
2159  if (WRA_WAS_ADDED(r)) {
2160  any_changed++;
2161  smartlist_add(changed, ri);
2162  routerlist_descriptors_added(changed, from_cache);
2163  smartlist_clear(changed);
2164  } else if (WRA_NEVER_DOWNLOADABLE(r)) {
2165  download_status_t *dl_status;
2167  if (dl_status) {
2168  log_info(LD_GENERAL, "Marking router %s as never downloadable",
2169  hex_str(d, DIGEST_LEN));
2171  }
2172  }
2173  } SMARTLIST_FOREACH_END(ri);
2174 
2175  SMARTLIST_FOREACH_BEGIN(invalid_digests, const uint8_t *, bad_digest) {
2176  /* This digest is never going to be parseable. */
2177  base16_encode(fp, sizeof(fp), (char*)bad_digest, DIGEST_LEN);
2178  if (requested_fingerprints && descriptor_digests) {
2179  if (! smartlist_contains_string(requested_fingerprints, fp)) {
2180  /* But we didn't ask for it, so we should assume shennanegans. */
2181  continue;
2182  }
2183  smartlist_string_remove(requested_fingerprints, fp);
2184  }
2185  download_status_t *dls;
2186  dls = router_get_dl_status_by_descriptor_digest((char*)bad_digest);
2187  if (dls) {
2188  log_info(LD_GENERAL, "Marking router with descriptor %s as unparseable, "
2189  "and therefore undownloadable", fp);
2191  }
2192  } SMARTLIST_FOREACH_END(bad_digest);
2193  SMARTLIST_FOREACH(invalid_digests, uint8_t *, d, tor_free(d));
2194  smartlist_free(invalid_digests);
2195 
2197 
2198  if (any_changed)
2200 
2201  smartlist_free(routers);
2202  smartlist_free(changed);
2203 
2204  return any_changed;
2205 }
2206 
2207 /** Parse one or more extrainfos from <b>s</b> (ending immediately before
2208  * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
2209  * router_load_routers_from_string(). */
2210 void
2211 router_load_extrainfo_from_string(const char *s, const char *eos,
2212  saved_location_t saved_location,
2213  smartlist_t *requested_fingerprints,
2214  int descriptor_digests)
2215 {
2216  smartlist_t *extrainfo_list = smartlist_new();
2217  const char *msg;
2218  int from_cache = (saved_location != SAVED_NOWHERE);
2219  smartlist_t *invalid_digests = smartlist_new();
2220 
2221  router_parse_list_from_string(&s, eos, extrainfo_list, saved_location, 1, 0,
2222  NULL, invalid_digests);
2223 
2224  log_info(LD_DIR, "%d elements to add", smartlist_len(extrainfo_list));
2225 
2226  SMARTLIST_FOREACH_BEGIN(extrainfo_list, extrainfo_t *, ei) {
2227  uint8_t d[DIGEST_LEN];
2228  memcpy(d, ei->cache_info.signed_descriptor_digest, DIGEST_LEN);
2229  was_router_added_t added =
2230  router_add_extrainfo_to_routerlist(ei, &msg, from_cache, !from_cache);
2231  if (WRA_WAS_ADDED(added) && requested_fingerprints) {
2232  char fp[HEX_DIGEST_LEN+1];
2233  base16_encode(fp, sizeof(fp), descriptor_digests ?
2234  ei->cache_info.signed_descriptor_digest :
2235  ei->cache_info.identity_digest,
2236  DIGEST_LEN);
2237  smartlist_string_remove(requested_fingerprints, fp);
2238  /* We silently let relays stuff us with extrainfos we didn't ask for,
2239  * so long as we would have wanted them anyway. Since we always fetch
2240  * all the extrainfos we want, and we never actually act on them
2241  * inside Tor, this should be harmless. */
2242  } else if (WRA_NEVER_DOWNLOADABLE(added)) {
2244  if (sd) {
2245  log_info(LD_GENERAL, "Marking extrainfo with descriptor %s as "
2246  "unparseable, and therefore undownloadable",
2247  hex_str((char*)d,DIGEST_LEN));
2249  }
2250  }
2251  } SMARTLIST_FOREACH_END(ei);
2252 
2253  SMARTLIST_FOREACH_BEGIN(invalid_digests, const uint8_t *, bad_digest) {
2254  /* This digest is never going to be parseable. */
2255  char fp[HEX_DIGEST_LEN+1];
2256  base16_encode(fp, sizeof(fp), (char*)bad_digest, DIGEST_LEN);
2257  if (requested_fingerprints) {
2258  if (! smartlist_contains_string(requested_fingerprints, fp)) {
2259  /* But we didn't ask for it, so we should assume shennanegans. */
2260  continue;
2261  }
2262  smartlist_string_remove(requested_fingerprints, fp);
2263  }
2264  signed_descriptor_t *sd =
2265  router_get_by_extrainfo_digest((char*)bad_digest);
2266  if (sd) {
2267  log_info(LD_GENERAL, "Marking extrainfo with descriptor %s as "
2268  "unparseable, and therefore undownloadable", fp);
2270  }
2271  } SMARTLIST_FOREACH_END(bad_digest);
2272  SMARTLIST_FOREACH(invalid_digests, uint8_t *, d, tor_free(d));
2273  smartlist_free(invalid_digests);
2274 
2276  router_rebuild_store(0, &router_get_routerlist()->extrainfo_store);
2277 
2278  smartlist_free(extrainfo_list);
2279 }
2280 
2281 /** Return true iff the latest ns-flavored consensus includes a descriptor
2282  * whose digest is that of <b>desc</b>. */
2283 static int
2285 {
2286  const routerstatus_t *rs;
2288  FLAV_NS);
2289 
2290  if (consensus) {
2291  rs = networkstatus_vote_find_entry(consensus, desc->identity_digest);
2292  if (rs && tor_memeq(rs->descriptor_digest,
2294  return 1;
2295  }
2296  return 0;
2297 }
2298 
2299 /** Update downloads for router descriptors and/or microdescriptors as
2300  * appropriate. */
2301 void
2303 {
2305  return;
2309 }
2310 
2311 /** Clear all our timeouts for fetching v3 directory stuff, and then
2312  * give it all a try again. */
2313 void
2315 {
2316  (void)now;
2317 
2318  log_debug(LD_GENERAL,
2319  "In routerlist_retry_directory_downloads()");
2320 
2324 }
2325 
2326 /** Return true iff <b>router</b> does not permit exit streams.
2327  */
2328 int
2330 {
2331  return router->policy_is_reject_star;
2332 }
2333 
2334 /** For every current directory connection whose purpose is <b>purpose</b>,
2335  * and where the resource being downloaded begins with <b>prefix</b>, split
2336  * rest of the resource into base16 fingerprints (or base64 fingerprints if
2337  * purpose==DIR_PURPOSE_FETCH_MICRODESC), decode them, and set the
2338  * corresponding elements of <b>result</b> to a nonzero value.
2339  */
2340 void
2341 list_pending_downloads(digestmap_t *result, digest256map_t *result256,
2342  int purpose, const char *prefix)
2343 {
2344  const size_t p_len = strlen(prefix);
2345  smartlist_t *tmp = smartlist_new();
2346  smartlist_t *conns = get_connection_array();
2347  int flags = DSR_HEX;
2348  if (purpose == DIR_PURPOSE_FETCH_MICRODESC)
2349  flags = DSR_DIGEST256|DSR_BASE64;
2350 
2351  tor_assert(result || result256);
2352 
2353  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
2354  if (conn->type == CONN_TYPE_DIR &&
2355  conn->purpose == purpose &&
2356  !conn->marked_for_close) {
2357  const char *resource = TO_DIR_CONN(conn)->requested_resource;
2358  if (!strcmpstart(resource, prefix))
2359  dir_split_resource_into_fingerprints(resource + p_len,
2360  tmp, NULL, flags);
2361  }
2362  } SMARTLIST_FOREACH_END(conn);
2363 
2364  if (result) {
2365  SMARTLIST_FOREACH(tmp, char *, d,
2366  {
2367  digestmap_set(result, d, (void*)1);
2368  tor_free(d);
2369  });
2370  } else if (result256) {
2371  SMARTLIST_FOREACH(tmp, uint8_t *, d,
2372  {
2373  digest256map_set(result256, d, (void*)1);
2374  tor_free(d);
2375  });
2376  }
2377  smartlist_free(tmp);
2378 }
2379 
2380 /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
2381  * true) we are currently downloading by descriptor digest, set result[d] to
2382  * (void*)1. */
2383 static void
2384 list_pending_descriptor_downloads(digestmap_t *result, int extrainfo)
2385 {
2386  int purpose =
2388  list_pending_downloads(result, NULL, purpose, "d/");
2389 }
2390 
2391 /** For every microdescriptor we are currently downloading by descriptor
2392  * digest, set result[d] to (void*)1.
2393  */
2394 void
2395 list_pending_microdesc_downloads(digest256map_t *result)
2396 {
2398 }
2399 
2400 /** Launch downloads for all the descriptors whose digests or digests256
2401  * are listed as digests[i] for lo <= i < hi. (Lo and hi may be out of
2402  * range.) If <b>source</b> is given, download from <b>source</b>;
2403  * otherwise, download from an appropriate random directory server.
2404  */
2405 MOCK_IMPL(STATIC void,
2407  int purpose, smartlist_t *digests,
2408  int lo, int hi, int pds_flags))
2409 {
2410  char *resource, *cp;
2411  int digest_len, enc_digest_len;
2412  const char *sep;
2413  int b64_256;
2414  smartlist_t *tmp;
2415 
2416  if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
2417  /* Microdescriptors are downloaded by "-"-separated base64-encoded
2418  * 256-bit digests. */
2419  digest_len = DIGEST256_LEN;
2420  enc_digest_len = BASE64_DIGEST256_LEN + 1;
2421  sep = "-";
2422  b64_256 = 1;
2423  } else {
2424  digest_len = DIGEST_LEN;
2425  enc_digest_len = HEX_DIGEST_LEN + 1;
2426  sep = "+";
2427  b64_256 = 0;
2428  }
2429 
2430  if (lo < 0)
2431  lo = 0;
2432  if (hi > smartlist_len(digests))
2433  hi = smartlist_len(digests);
2434 
2435  if (hi-lo <= 0)
2436  return;
2437 
2438  tmp = smartlist_new();
2439 
2440  for (; lo < hi; ++lo) {
2441  cp = tor_malloc(enc_digest_len);
2442  if (b64_256) {
2443  digest256_to_base64(cp, smartlist_get(digests, lo));
2444  } else {
2445  base16_encode(cp, enc_digest_len, smartlist_get(digests, lo),
2446  digest_len);
2447  }
2448  smartlist_add(tmp, cp);
2449  }
2450 
2451  cp = smartlist_join_strings(tmp, sep, 0, NULL);
2452  tor_asprintf(&resource, "d/%s.z", cp);
2453 
2454  SMARTLIST_FOREACH(tmp, char *, cp1, tor_free(cp1));
2455  smartlist_free(tmp);
2456  tor_free(cp);
2457 
2458  if (source) {
2459  /* We know which authority or directory mirror we want. */
2462  directory_request_set_resource(req, resource);
2464  directory_request_free(req);
2465  } else {
2467  pds_flags, DL_WANT_ANY_DIRSERVER);
2468  }
2469  tor_free(resource);
2470 }
2471 
2472 /** Return the max number of hashes to put in a URL for a given request.
2473  */
2474 static int
2475 max_dl_per_request(const or_options_t *options, int purpose)
2476 {
2477  /* Since squid does not like URLs >= 4096 bytes we limit it to 96.
2478  * 4096 - strlen(http://[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535
2479  * /tor/server/d/.z) == 4026
2480  * 4026/41 (40 for the hash and 1 for the + that separates them) => 98
2481  * So use 96 because it's a nice number.
2482  *
2483  * For microdescriptors, the calculation is
2484  * 4096 - strlen(http://[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]:65535
2485  * /tor/micro/d/.z) == 4027
2486  * 4027/44 (43 for the hash and 1 for the - that separates them) => 91
2487  * So use 90 because it's a nice number.
2488  */
2489  int max = 96;
2490  if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
2491  max = 90;
2492  }
2493  /* If we're going to tunnel our connections, we can ask for a lot more
2494  * in a request. */
2495  if (dirclient_must_use_begindir(options)) {
2496  max = 500;
2497  }
2498  return max;
2499 }
2500 
2501 /** Don't split our requests so finely that we are requesting fewer than
2502  * this number per server. (Grouping more than this at once leads to
2503  * diminishing returns.) */
2504 #define MIN_DL_PER_REQUEST 32
2505 /** To prevent a single screwy cache from confusing us by selective reply,
2506  * try to split our requests into at least this many requests. */
2507 #define MIN_REQUESTS 3
2508 /** If we want fewer than this many descriptors, wait until we
2509  * want more, or until TestingClientMaxIntervalWithoutRequest has passed. */
2510 #define MAX_DL_TO_DELAY 16
2512 /** Given a <b>purpose</b> (FETCH_MICRODESC or FETCH_SERVERDESC) and a list of
2513  * router descriptor digests or microdescriptor digest256s in
2514  * <b>downloadable</b>, decide whether to delay fetching until we have more.
2515  * If we don't want to delay, launch one or more requests to the appropriate
2516  * directory authorities.
2517  */
2518 void
2520  smartlist_t *downloadable,
2521  const routerstatus_t *source, time_t now)
2522 {
2523  const or_options_t *options = get_options();
2524  const char *descname;
2525  const int fetch_microdesc = (purpose == DIR_PURPOSE_FETCH_MICRODESC);
2526  int n_downloadable = smartlist_len(downloadable);
2527 
2528  int i, n_per_request, max_dl_per_req;
2529  const char *req_plural = "", *rtr_plural = "";
2530  int pds_flags = PDS_RETRY_IF_NO_SERVERS;
2531 
2532  tor_assert(fetch_microdesc || purpose == DIR_PURPOSE_FETCH_SERVERDESC);
2533  descname = fetch_microdesc ? "microdesc" : "routerdesc";
2534 
2535  if (!n_downloadable)
2536  return;
2537 
2538  if (!dirclient_fetches_dir_info_early(options)) {
2539  if (n_downloadable >= MAX_DL_TO_DELAY) {
2540  log_debug(LD_DIR,
2541  "There are enough downloadable %ss to launch requests.",
2542  descname);
2543  } else if (! router_have_minimum_dir_info()) {
2544  log_debug(LD_DIR,
2545  "We are only missing %d %ss, but we'll fetch anyway, since "
2546  "we don't yet have enough directory info.",
2547  n_downloadable, descname);
2548  } else {
2549 
2550  /* should delay */
2553  return;
2554 
2556  log_info(LD_DIR,
2557  "There are not many downloadable %ss, but we've "
2558  "been waiting long enough (%d seconds). Downloading.",
2559  descname,
2561  } else {
2562  log_info(LD_DIR,
2563  "There are not many downloadable %ss, but we haven't "
2564  "tried downloading descriptors recently. Downloading.",
2565  descname);
2566  }
2567  }
2568  }
2569 
2570  if (!authdir_mode(options)) {
2571  /* If we wind up going to the authorities, we want to only open one
2572  * connection to each authority at a time, so that we don't overload
2573  * them. We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
2574  * regardless of whether we're a cache or not.
2575  *
2576  * Setting this flag can make initiate_descriptor_downloads() ignore
2577  * requests. We need to make sure that we do in fact call
2578  * update_router_descriptor_downloads() later on, once the connections
2579  * have succeeded or failed.
2580  */
2581  pds_flags |= fetch_microdesc ?
2584  }
2585 
2586  n_per_request = CEIL_DIV(n_downloadable, MIN_REQUESTS);
2587  max_dl_per_req = max_dl_per_request(options, purpose);
2588 
2589  if (n_per_request > max_dl_per_req)
2590  n_per_request = max_dl_per_req;
2591 
2592  if (n_per_request < MIN_DL_PER_REQUEST) {
2593  n_per_request = MIN(MIN_DL_PER_REQUEST, n_downloadable);
2594  }
2595 
2596  if (n_downloadable > n_per_request)
2597  req_plural = rtr_plural = "s";
2598  else if (n_downloadable > 1)
2599  rtr_plural = "s";
2600 
2601  log_info(LD_DIR,
2602  "Launching %d request%s for %d %s%s, %d at a time",
2603  CEIL_DIV(n_downloadable, n_per_request), req_plural,
2604  n_downloadable, descname, rtr_plural, n_per_request);
2605  smartlist_sort_digests(downloadable);
2606  for (i=0; i < n_downloadable; i += n_per_request) {
2607  initiate_descriptor_downloads(source, purpose,
2608  downloadable, i, i+n_per_request,
2609  pds_flags);
2610  }
2612 }
2613 
2614 /** For any descriptor that we want that's currently listed in
2615  * <b>consensus</b>, download it as appropriate. */
2616 void
2618  networkstatus_t *consensus)
2619 {
2620  const or_options_t *options = get_options();
2621  digestmap_t *map = NULL;
2622  smartlist_t *no_longer_old = smartlist_new();
2623  smartlist_t *downloadable = smartlist_new();
2624  routerstatus_t *source = NULL;
2625  int authdir = authdir_mode(options);
2626  int n_delayed=0, n_have=0, n_would_reject=0, n_wouldnt_use=0,
2627  n_inprogress=0, n_in_oldrouters=0;
2628 
2629  if (dirclient_too_idle_to_fetch_descriptors(options, now))
2630  goto done;
2631  if (!consensus)
2632  goto done;
2633 
2634  if (is_vote) {
2635  /* where's it from, so we know whom to ask for descriptors */
2636  dir_server_t *ds;
2637  networkstatus_voter_info_t *voter = smartlist_get(consensus->voters, 0);
2638  tor_assert(voter);
2640  if (ds)
2641  source = &(ds->fake_status);
2642  else
2643  log_warn(LD_DIR, "couldn't lookup source from vote?");
2644  }
2645 
2646  map = digestmap_new();
2648  SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, void *, rsp) {
2649  routerstatus_t *rs;
2650  vote_routerstatus_t *vrs;
2651  if (is_vote) {
2652  rs = &(((vote_routerstatus_t *)rsp)->status);
2653  vrs = rsp;
2654  } else {
2655  rs = rsp;
2656  vrs = NULL;
2657  }
2658  signed_descriptor_t *sd;
2660  const routerinfo_t *ri;
2661  ++n_have;
2662  if (!(ri = router_get_by_id_digest(rs->identity_digest)) ||
2663  tor_memneq(ri->cache_info.signed_descriptor_digest,
2665  /* We have a descriptor with this digest, but either there is no
2666  * entry in routerlist with the same ID (!ri), or there is one,
2667  * but the identity digest differs (memneq).
2668  */
2669  smartlist_add(no_longer_old, sd);
2670  ++n_in_oldrouters; /* We have it in old_routers. */
2671  }
2672  continue; /* We have it already. */
2673  }
2674  if (digestmap_get(map, rs->descriptor_digest)) {
2675  ++n_inprogress;
2676  continue; /* We have an in-progress download. */
2677  }
2678  if (!download_status_is_ready(&rs->dl_status, now)) {
2679  ++n_delayed; /* Not ready for retry. */
2680  continue;
2681  }
2682  if (authdir && is_vote && dirserv_would_reject_router(rs, vrs)) {
2683  ++n_would_reject;
2684  continue; /* We would throw it out immediately. */
2685  }
2686  if (!we_want_to_fetch_flavor(options, consensus->flavor) &&
2687  !client_would_use_router(rs, now)) {
2688  ++n_wouldnt_use;
2689  continue; /* We would never use it ourself. */
2690  }
2691  if (is_vote && source) {
2692  char time_bufnew[ISO_TIME_LEN+1];
2693  char time_bufold[ISO_TIME_LEN+1];
2694  const routerinfo_t *oldrouter;
2695  oldrouter = router_get_by_id_digest(rs->identity_digest);
2696  format_iso_time(time_bufnew, rs->published_on);
2697  if (oldrouter)
2698  format_iso_time(time_bufold, oldrouter->cache_info.published_on);
2699  log_info(LD_DIR, "Learned about %s (%s vs %s) from %s's vote (%s)",
2701  time_bufnew,
2702  oldrouter ? time_bufold : "none",
2703  source->nickname, oldrouter ? "known" : "unknown");
2704  }
2705  smartlist_add(downloadable, rs->descriptor_digest);
2706  } SMARTLIST_FOREACH_END(rsp);
2707 
2708  if (!authdir_mode_v3(options)
2709  && smartlist_len(no_longer_old)) {
2711  log_info(LD_DIR, "%d router descriptors listed in consensus are "
2712  "currently in old_routers; making them current.",
2713  smartlist_len(no_longer_old));
2714  SMARTLIST_FOREACH_BEGIN(no_longer_old, signed_descriptor_t *, sd) {
2715  const char *msg;
2717  time_t tmp_cert_expiration_time;
2718  routerinfo_t *ri = routerlist_reparse_old(rl, sd);
2719  if (!ri) {
2720  log_warn(LD_BUG, "Failed to re-parse a router.");
2721  continue;
2722  }
2723  /* need to remember for below, since add_to_routerlist may free. */
2724  tmp_cert_expiration_time = ri->cert_expiration_time;
2725 
2726  r = router_add_to_routerlist(ri, &msg, 1, 0);
2727  if (WRA_WAS_OUTDATED(r)) {
2728  log_warn(LD_DIR, "Couldn't add re-parsed router: %s. This isn't "
2729  "usually a big deal, but you should make sure that your "
2730  "clock and timezone are set correctly.",
2731  msg?msg:"???");
2732  if (r == ROUTER_CERTS_EXPIRED) {
2733  char time_cons[ISO_TIME_LEN+1];
2734  char time_cert_expires[ISO_TIME_LEN+1];
2735  format_iso_time(time_cons, consensus->valid_after);
2736  format_iso_time(time_cert_expires, tmp_cert_expiration_time);
2737  log_warn(LD_DIR, " (I'm looking at a consensus from %s; This "
2738  "router's certificates began expiring at %s.)",
2739  time_cons, time_cert_expires);
2740  }
2741  }
2742  } SMARTLIST_FOREACH_END(sd);
2744  }
2745 
2746  log_info(LD_DIR,
2747  "%d router descriptors downloadable. %d delayed; %d present "
2748  "(%d of those were in old_routers); %d would_reject; "
2749  "%d wouldnt_use; %d in progress.",
2750  smartlist_len(downloadable), n_delayed, n_have, n_in_oldrouters,
2751  n_would_reject, n_wouldnt_use, n_inprogress);
2752 
2754  downloadable, source, now);
2755 
2756  digestmap_free(map, NULL);
2757  done:
2758  smartlist_free(downloadable);
2759  smartlist_free(no_longer_old);
2760 }
2761 
2762 /** How often should we launch a server/authority request to be sure of getting
2763  * a guess for our IP? */
2764 /*XXXX+ this info should come from netinfo cells or something, or we should
2765  * do this only when we aren't seeing incoming data. see bug 652. */
2766 #define DUMMY_DOWNLOAD_INTERVAL (20*60)
2768 /** As needed, launch a dummy router descriptor fetch to see if our
2769  * address has changed. */
2770 static void
2772  const or_options_t *options)
2773 {
2774  static time_t last_dummy_download = 0;
2775  /* XXXX+ we could be smarter here; see notes on bug 652. */
2776  /* If we're a server that doesn't have a configured address, we rely on
2777  * directory fetches to learn when our address changes. So if we haven't
2778  * tried to get any routerdescs in a long time, try a dummy fetch now. */
2779  if (!options->Address &&
2780  server_mode(options) &&
2782  last_dummy_download + DUMMY_DOWNLOAD_INTERVAL < now) {
2783  last_dummy_download = now;
2784  /* XX/teor - do we want an authority here, because they are less likely
2785  * to give us the wrong address? (See #17782)
2786  * I'm leaving the previous behaviour intact, because I don't like
2787  * the idea of some relays contacting an authority every 20 minutes. */
2789  ROUTER_PURPOSE_GENERAL, "authority.z",
2791  DL_WANT_ANY_DIRSERVER);
2792  }
2793 }
2794 
2795 /** Launch downloads for router status as needed. */
2796 void
2798 {
2799  const or_options_t *options = get_options();
2800  if (should_delay_dir_fetches(options, NULL))
2801  return;
2802  if (!we_fetch_router_descriptors(options))
2803  return;
2804 
2807 }
2808 
2809 /** Launch extrainfo downloads as needed. */
2810 void
2812 {
2813  const or_options_t *options = get_options();
2814  routerlist_t *rl;
2815  smartlist_t *wanted;
2816  digestmap_t *pending;
2817  int old_routers, i, max_dl_per_req;
2818  int n_no_ei = 0, n_pending = 0, n_have = 0, n_delay = 0, n_bogus[2] = {0,0};
2819  if (! options->DownloadExtraInfo)
2820  return;
2821  if (should_delay_dir_fetches(options, NULL))
2822  return;
2824  return;
2825 
2826  pending = digestmap_new();
2828  rl = router_get_routerlist();
2829  wanted = smartlist_new();
2830  for (old_routers = 0; old_routers < 2; ++old_routers) {
2831  smartlist_t *lst = old_routers ? rl->old_routers : rl->routers;
2832  for (i = 0; i < smartlist_len(lst); ++i) {
2833  signed_descriptor_t *sd;
2834  char *d;
2835  if (old_routers)
2836  sd = smartlist_get(lst, i);
2837  else
2838  sd = &((routerinfo_t*)smartlist_get(lst, i))->cache_info;
2839  if (sd->is_extrainfo)
2840  continue; /* This should never happen. */
2841  if (old_routers && !router_get_by_id_digest(sd->identity_digest))
2842  continue; /* Couldn't check the signature if we got it. */
2843  if (sd->extrainfo_is_bogus)
2844  continue;
2845  d = sd->extra_info_digest;
2846  if (tor_digest_is_zero(d)) {
2847  ++n_no_ei;
2848  continue;
2849  }
2850  if (eimap_get(rl->extra_info_map, d)) {
2851  ++n_have;
2852  continue;
2853  }
2854  if (!download_status_is_ready(&sd->ei_dl_status, now)) {
2855  ++n_delay;
2856  continue;
2857  }
2858  if (digestmap_get(pending, d)) {
2859  ++n_pending;
2860  continue;
2861  }
2862 
2864  if (sd2 != sd) {
2865  if (sd2 != NULL) {
2866  char d1[HEX_DIGEST_LEN+1], d2[HEX_DIGEST_LEN+1];
2867  char d3[HEX_DIGEST_LEN+1], d4[HEX_DIGEST_LEN+1];
2868  base16_encode(d1, sizeof(d1), sd->identity_digest, DIGEST_LEN);
2869  base16_encode(d2, sizeof(d2), sd2->identity_digest, DIGEST_LEN);
2870  base16_encode(d3, sizeof(d3), d, DIGEST_LEN);
2871  base16_encode(d4, sizeof(d3), sd2->extra_info_digest, DIGEST_LEN);
2872 
2873  log_info(LD_DIR, "Found an entry in %s with mismatched "
2874  "router_get_by_extrainfo_digest() value. This has ID %s "
2875  "but the entry in the map has ID %s. This has EI digest "
2876  "%s and the entry in the map has EI digest %s.",
2877  old_routers?"old_routers":"routers",
2878  d1, d2, d3, d4);
2879  } else {
2880  char d1[HEX_DIGEST_LEN+1], d2[HEX_DIGEST_LEN+1];
2881  base16_encode(d1, sizeof(d1), sd->identity_digest, DIGEST_LEN);
2882  base16_encode(d2, sizeof(d2), d, DIGEST_LEN);
2883 
2884  log_info(LD_DIR, "Found an entry in %s with NULL "
2885  "router_get_by_extrainfo_digest() value. This has ID %s "
2886  "and EI digest %s.",
2887  old_routers?"old_routers":"routers",
2888  d1, d2);
2889  }
2890  ++n_bogus[old_routers];
2891  continue;
2892  }
2893  smartlist_add(wanted, d);
2894  }
2895  }
2896  digestmap_free(pending, NULL);
2897 
2898  log_info(LD_DIR, "Extrainfo download status: %d router with no ei, %d "
2899  "with present ei, %d delaying, %d pending, %d downloadable, %d "
2900  "bogus in routers, %d bogus in old_routers",
2901  n_no_ei, n_have, n_delay, n_pending, smartlist_len(wanted),
2902  n_bogus[0], n_bogus[1]);
2903 
2904  smartlist_shuffle(wanted);
2905 
2906  max_dl_per_req = max_dl_per_request(options, DIR_PURPOSE_FETCH_EXTRAINFO);
2907  for (i = 0; i < smartlist_len(wanted); i += max_dl_per_req) {
2909  wanted, i, i+max_dl_per_req,
2911  }
2912 
2913  smartlist_free(wanted);
2914 }
2915 
2916 /** Reset the consensus and extra-info download failure count on all routers.
2917  * When we get a new consensus,
2918  * routers_update_status_from_consensus_networkstatus() will reset the
2919  * download statuses on the descriptors in that consensus.
2920  */
2921 void
2923 {
2924  log_debug(LD_GENERAL,
2925  "In router_reset_descriptor_download_failures()");
2926 
2929  if (!routerlist)
2930  return;
2931  /* We want to download *all* extra-info descriptors, not just those in
2932  * the consensus we currently have (or are about to have) */
2934  {
2935  download_status_reset(&ri->cache_info.ei_dl_status);
2936  });
2938  {
2939  download_status_reset(&sd->ei_dl_status);
2940  });
2941 }
2942 
2943 /** Any changes in a router descriptor's publication time larger than this are
2944  * automatically non-cosmetic. */
2945 #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (2*60*60)
2947 /** We allow uptime to vary from how much it ought to be by this much. */
2948 #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
2950 /** Return true iff the only differences between r1 and r2 are such that
2951  * would not cause a recent (post 0.1.1.6) dirserver to republish.
2952  */
2953 int
2955 {
2956  time_t r1pub, r2pub;
2957  time_t time_difference;
2958  tor_assert(r1 && r2);
2959 
2960  /* r1 should be the one that was published first. */
2961  if (r1->cache_info.published_on > r2->cache_info.published_on) {
2962  const routerinfo_t *ri_tmp = r2;
2963  r2 = r1;
2964  r1 = ri_tmp;
2965  }
2966 
2967  /* If any key fields differ, they're different. */
2968  if (!tor_addr_eq(&r1->ipv4_addr, &r2->ipv4_addr) ||
2969  strcasecmp(r1->nickname, r2->nickname) ||
2970  r1->ipv4_orport != r2->ipv4_orport ||
2971  !tor_addr_eq(&r1->ipv6_addr, &r2->ipv6_addr) ||
2972  r1->ipv6_orport != r2->ipv6_orport ||
2973  r1->ipv4_dirport != r2->ipv4_dirport ||
2974  r1->purpose != r2->purpose ||
2975  r1->onion_pkey_len != r2->onion_pkey_len ||
2976  !tor_memeq(r1->onion_pkey, r2->onion_pkey, r1->onion_pkey_len) ||
2978  strcasecmp(r1->platform, r2->platform) ||
2979  (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
2980  (!r1->contact_info && r2->contact_info) ||
2981  (r1->contact_info && r2->contact_info &&
2982  strcasecmp(r1->contact_info, r2->contact_info)) ||
2983  r1->is_hibernating != r2->is_hibernating ||
2987  return 0;
2988  if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
2989  return 0;
2990  if (r1->declared_family && r2->declared_family) {
2991  int i, n;
2992  if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
2993  return 0;
2994  n = smartlist_len(r1->declared_family);
2995  for (i=0; i < n; ++i) {
2996  if (strcasecmp(smartlist_get(r1->declared_family, i),
2997  smartlist_get(r2->declared_family, i)))
2998  return 0;
2999  }
3000  }
3001 
3002  /* Did bandwidth change a lot? */
3003  if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
3004  (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
3005  return 0;
3006 
3007  /* Did the bandwidthrate or bandwidthburst change? */
3008  if ((r1->bandwidthrate != r2->bandwidthrate) ||
3009  (r1->bandwidthburst != r2->bandwidthburst))
3010  return 0;
3011 
3012  /* Has enough time passed between the publication times? */
3014  < r2->cache_info.published_on)
3015  return 0;
3016 
3017  /* Did uptime fail to increase by approximately the amount we would think,
3018  * give or take some slop? */
3019  r1pub = r1->cache_info.published_on;
3020  r2pub = r2->cache_info.published_on;
3021  time_difference = r2->uptime - (r1->uptime + (r2pub - r1pub));
3022  if (time_difference < 0)
3023  time_difference = - time_difference;
3024  if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
3025  time_difference > r1->uptime * .05 &&
3026  time_difference > r2->uptime * .05)
3027  return 0;
3028 
3029  /* Otherwise, the difference is cosmetic. */
3030  return 1;
3031 }
3032 
3033 /** Check whether <b>sd</b> describes a router descriptor compatible with the
3034  * extrainfo document <b>ei</b>.
3035  *
3036  * <b>identity_pkey</b> (which must also be provided) is RSA1024 identity key
3037  * for the router. We use it to check the signature of the extrainfo document,
3038  * if it has not already been checked.
3039  *
3040  * If no router is compatible with <b>ei</b>, <b>ei</b> should be
3041  * dropped. Return 0 for "compatible", return 1 for "reject, and inform
3042  * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
3043  * <b>msg</b> is present, set *<b>msg</b> to a description of the
3044  * incompatibility (if any).
3045  *
3046  * Set the extrainfo_is_bogus field in <b>sd</b> if the digests matched
3047  * but the extrainfo was nonetheless incompatible.
3048  **/
3049 int
3051  extrainfo_t *ei,
3052  signed_descriptor_t *sd,
3053  const char **msg)
3054 {
3055  int digest_matches, digest256_matches, r=1;
3056  tor_assert(identity_pkey);
3057  tor_assert(sd);
3058  tor_assert(ei);
3059 
3060  if (ei->bad_sig) {
3061  if (msg) *msg = "Extrainfo signature was bad, or signed with wrong key.";
3062  return 1;
3063  }
3064 
3065  digest_matches = tor_memeq(ei->cache_info.signed_descriptor_digest,
3067  /* Set digest256_matches to 1 if the digest is correct, or if no
3068  * digest256 was in the ri. */
3069  digest256_matches = tor_memeq(ei->digest256,
3071  digest256_matches |=
3073 
3074  /* The identity must match exactly to have been generated at the same time
3075  * by the same router. */
3076  if (tor_memneq(sd->identity_digest,
3077  ei->cache_info.identity_digest,
3078  DIGEST_LEN)) {
3079  if (msg) *msg = "Extrainfo nickname or identity did not match routerinfo";
3080  goto err; /* different servers */
3081  }
3082 
3084  ei->cache_info.signing_key_cert)) {
3085  if (msg) *msg = "Extrainfo signing key cert didn't match routerinfo";
3086  goto err; /* different servers */
3087  }
3088 
3089  if (ei->pending_sig) {
3090  char signed_digest[128];
3091  if (crypto_pk_public_checksig(identity_pkey,
3092  signed_digest, sizeof(signed_digest),
3093  ei->pending_sig, ei->pending_sig_len) != DIGEST_LEN ||
3094  tor_memneq(signed_digest, ei->cache_info.signed_descriptor_digest,
3095  DIGEST_LEN)) {
3096  ei->bad_sig = 1;
3097  tor_free(ei->pending_sig);
3098  if (msg) *msg = "Extrainfo signature bad, or signed with wrong key";
3099  goto err; /* Bad signature, or no match. */
3100  }
3101 
3102  ei->cache_info.send_unencrypted = sd->send_unencrypted;
3103  tor_free(ei->pending_sig);
3104  }
3105 
3106  if (ei->cache_info.published_on < sd->published_on) {
3107  if (msg) *msg = "Extrainfo published time did not match routerdesc";
3108  goto err;
3109  } else if (ei->cache_info.published_on > sd->published_on) {
3110  if (msg) *msg = "Extrainfo published time did not match routerdesc";
3111  r = -1;
3112  goto err;
3113  }
3114 
3115  if (!digest256_matches && !digest_matches) {
3116  if (msg) *msg = "Neither digest256 or digest matched "
3117  "digest from routerdesc";
3118  goto err;
3119  }
3120 
3121  if (!digest256_matches) {
3122  if (msg) *msg = "Extrainfo digest did not match digest256 from routerdesc";
3123  goto err; /* Digest doesn't match declared value. */
3124  }
3125 
3126  if (!digest_matches) {
3127  if (msg) *msg = "Extrainfo digest did not match value from routerdesc";
3128  goto err; /* Digest doesn't match declared value. */
3129  }
3130 
3131  return 0;
3132  err:
3133  if (digest_matches) {
3134  /* This signature was okay, and the digest was right: This is indeed the
3135  * corresponding extrainfo. But insanely, it doesn't match the routerinfo
3136  * that lists it. Don't try to fetch this one again. */
3137  sd->extrainfo_is_bogus = 1;
3138  }
3139 
3140  return r;
3141 }
3142 
3143 /* Does ri have a valid ntor onion key?
3144  * Valid ntor onion keys exist and have at least one non-zero byte. */
3145 int
3146 routerinfo_has_curve25519_onion_key(const routerinfo_t *ri)
3147 {
3148  if (!ri) {
3149  return 0;
3150  }
3151 
3152  if (!ri->onion_curve25519_pkey) {
3153  return 0;
3154  }
3155 
3156  if (fast_mem_is_zero((const char*)ri->onion_curve25519_pkey->public_key,
3158  return 0;
3159  }
3160 
3161  return 1;
3162 }
3163 
3164 /* Is rs running a tor version known to support EXTEND2 cells?
3165  * If allow_unknown_versions is true, return true if we can't tell
3166  * (from a versions line or a protocols line) whether it supports extend2
3167  * cells.
3168  * Otherwise, return false if the version is unknown. */
3169 int
3170 routerstatus_version_supports_extend2_cells(const routerstatus_t *rs,
3171  int allow_unknown_versions)
3172 {
3173  if (!rs) {
3174  return allow_unknown_versions;
3175  }
3176 
3177  if (!rs->pv.protocols_known) {
3178  return allow_unknown_versions;
3179  }
3180 
3181  return rs->pv.supports_extend2_cells;
3182 }
3183 
3184 /** Assert that the internal representation of <b>rl</b> is
3185  * self-consistent. */
3186 void
3188 {
3189  routerinfo_t *r2;
3190  signed_descriptor_t *sd2;
3191  if (!rl)
3192  return;
3194  r2 = rimap_get(rl->identity_map, r->cache_info.identity_digest);
3195  tor_assert(r == r2);
3196  sd2 = sdmap_get(rl->desc_digest_map,
3197  r->cache_info.signed_descriptor_digest);
3198  tor_assert(&(r->cache_info) == sd2);
3199  tor_assert(r->cache_info.routerlist_index == r_sl_idx);
3200  /* XXXX
3201  *
3202  * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
3203  * commenting this out is just a band-aid.
3204  *
3205  * The problem is that, although well-behaved router descriptors
3206  * should never have the same value for their extra_info_digest, it's
3207  * possible for ill-behaved routers to claim whatever they like there.
3208  *
3209  * The real answer is to trash desc_by_eid_map and instead have
3210  * something that indicates for a given extra-info digest we want,
3211  * what its download status is. We'll do that as a part of routerlist
3212  * refactoring once consensus directories are in. For now,
3213  * this rep violation is probably harmless: an adversary can make us
3214  * reset our retry count for an extrainfo, but that's not the end
3215  * of the world. Changing the representation in 0.2.0.x would just
3216  * destabilize the codebase.
3217  if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
3218  signed_descriptor_t *sd3 =
3219  sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
3220  tor_assert(sd3 == &(r->cache_info));
3221  }
3222  */
3223  } SMARTLIST_FOREACH_END(r);
3225  r2 = rimap_get(rl->identity_map, sd->identity_digest);
3226  tor_assert(!r2 || sd != &(r2->cache_info));
3227  sd2 = sdmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
3228  tor_assert(sd == sd2);
3229  tor_assert(sd->routerlist_index == sd_sl_idx);
3230  /* XXXX see above.
3231  if (!tor_digest_is_zero(sd->extra_info_digest)) {
3232  signed_descriptor_t *sd3 =
3233  sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
3234  tor_assert(sd3 == sd);
3235  }
3236  */
3237  } SMARTLIST_FOREACH_END(sd);
3238 
3239  RIMAP_FOREACH(rl->identity_map, d, r) {
3240  tor_assert(tor_memeq(r->cache_info.identity_digest, d, DIGEST_LEN));
3242  SDMAP_FOREACH(rl->desc_digest_map, d, sd) {
3243  tor_assert(tor_memeq(sd->signed_descriptor_digest, d, DIGEST_LEN));
3245  SDMAP_FOREACH(rl->desc_by_eid_map, d, sd) {
3247  tor_assert(sd);
3248  tor_assert(tor_memeq(sd->extra_info_digest, d, DIGEST_LEN));
3250  EIMAP_FOREACH(rl->extra_info_map, d, ei) {
3251  signed_descriptor_t *sd;
3252  tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
3253  d, DIGEST_LEN));
3254  sd = sdmap_get(rl->desc_by_eid_map,
3255  ei->cache_info.signed_descriptor_digest);
3256  // tor_assert(sd); // XXXX see above
3257  if (sd) {
3258  tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
3260  }
3262 }
3263 
3264 /** Allocate and return a new string representing the contact info
3265  * and platform string for <b>router</b>,
3266  * surrounded by quotes and using standard C escapes.
3267  *
3268  * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
3269  * thread. Also, each call invalidates the last-returned value, so don't
3270  * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
3271  *
3272  * If <b>router</b> is NULL, it just frees its internal memory and returns.
3273  */
3274 const char *
3276 {
3277  static char *info=NULL;
3278  char *esc_contact, *esc_platform;
3279  tor_free(info);
3280 
3281  if (!router)
3282  return NULL; /* we're exiting; just free the memory we use */
3283 
3284  esc_contact = esc_for_log(router->contact_info);
3285  esc_platform = esc_for_log(router->platform);
3286 
3287  tor_asprintf(&info, "Contact %s, Platform %s", esc_contact, esc_platform);
3288  tor_free(esc_contact);
3289  tor_free(esc_platform);
3290 
3291  return info;
3292 }
3293 
3294 /** Helper for sorting: compare two routerinfos by their identity
3295  * digest. */
3296 static int
3297 compare_routerinfo_by_id_digest_(const void **a, const void **b)
3298 {
3299  routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
3300  return fast_memcmp(first->cache_info.identity_digest,
3301  second->cache_info.identity_digest,
3302  DIGEST_LEN);
3303 }
3304 
3305 /** Sort a list of routerinfo_t in ascending order of identity digest. */
3306 void
3308 {
3310 }
3311 
3312 /** Called when we change a node set, or when we reload the geoip IPv4 list:
3313  * recompute all country info in all configuration node sets and in the
3314  * routerlist. */
3315 void
3317 {
3318  const or_options_t *options = get_options();
3319 
3320  if (options->EntryNodes)
3322  if (options->ExitNodes)
3324  if (options->MiddleNodes)
3326  if (options->ExcludeNodes)
3328  if (options->ExcludeExitNodes)
3330  if (options->ExcludeExitNodesUnion_)
3332 
3334 }
log_fn
#define log_fn(severity, domain, args,...)
Definition: log.h:287
router_load_routers_from_string
int router_load_routers_from_string(const char *s, const char *eos, saved_location_t saved_location, smartlist_t *requested_fingerprints, int descriptor_digests, const char *prepend_annotations)
Definition: routerlist.c:2112
routerinfo_t::purpose
uint8_t purpose
Definition: routerinfo_st.h:115
hex_digest_nickname_decode
int hex_digest_nickname_decode(const char *hexdigest, char *digest_out, char *nickname_qualifier_char_out, char *nickname_out)
Definition: routerlist.c:682
signed_descriptor_t::last_listed_as_valid_until
time_t last_listed_as_valid_until
Definition: signed_descriptor_st.h:53
routermode.h
Header file for routermode.c.
routerlist_reparse_old
static routerinfo_t * routerlist_reparse_old(routerlist_t *rl, signed_descriptor_t *sd)
Definition: routerlist.c:1488
nodelist_refresh_countries
void nodelist_refresh_countries(void)
Definition: nodelist.c:2002
tor_free
#define tor_free(p)
Definition: malloc.h:52
routerinfo_t
Definition: routerinfo_st.h:20
ROUTER_ALLOW_UPTIME_DRIFT
#define ROUTER_ALLOW_UPTIME_DRIFT
Definition: routerlist.c:2948
authdir_mode_bridge
int authdir_mode_bridge(const or_options_t *options)
Definition: authmode.c:76
routerlist_insert
static void routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
Definition: routerlist.c:1103
dir_server_st.h
Trusted/fallback directory server structure.
CURVE25519_PUBKEY_LEN
#define CURVE25519_PUBKEY_LEN
Definition: x25519_sizes.h:20
dir_connection_t::requested_resource
char * requested_resource
Definition: dir_connection_st.h:30
desc_store_t::bytes_dropped
size_t bytes_dropped
Definition: desc_store_st.h:41
LOG_DEBUG
#define LOG_DEBUG
Definition: log.h:42
routerlist_reset_warnings
void routerlist_reset_warnings(void)
Definition: routerlist.c:1531
router_add_extrainfo_to_routerlist
was_router_added_t router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg, int from_cache, int from_fetch)
Definition: routerlist.c:1747
hex_str
const char * hex_str(const char *from, size_t fromlen)
Definition: binascii.c:34
routerinfo.h
Header file for routerinfo.c.
extrainfo_t::pending_sig_len
size_t pending_sig_len
Definition: extrainfo_st.h:31
router_reload_router_list
int router_reload_router_list(void)
Definition: routerlist.c:458
download_status_mark_impossible
void download_status_mark_impossible(download_status_t *dl)
Definition: dlstatus.c:393
routerlist_t::identity_map
struct digest_ri_map_t * identity_map
Definition: routerlist_st.h:20
routerstatus_describe
const char * routerstatus_describe(const routerstatus_t *rs)
Definition: describe.c:182
we_want_to_fetch_flavor
int we_want_to_fetch_flavor(const or_options_t *options, int flavor)
Definition: networkstatus.c:862
routerinfo_t::bandwidthcapacity
uint32_t bandwidthcapacity
Definition: routerinfo_st.h:58
extrainfo_t
Definition: extrainfo_st.h:18
router_differences_are_cosmetic
int router_differences_are_cosmetic(const routerinfo_t *r1, const routerinfo_t *r2)
Definition: routerlist.c:2954
directory_initiate_request
void directory_initiate_request(directory_request_t *request)
Definition: dirclient.c:1235
approx_time
time_t approx_time(void)
Definition: approx_time.c:32
firewall_is_fascist_or
int firewall_is_fascist_or(void)
Definition: policies.c:354
MOCK_IMPL
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
BASE64_DIGEST256_LEN
#define BASE64_DIGEST256_LEN
Definition: crypto_digest.h:29
routers_sort_by_identity
void routers_sort_by_identity(smartlist_t *routers)
Definition: routerlist.c:3307
routers_have_same_or_addrs
int routers_have_same_or_addrs(const routerinfo_t *r1, const routerinfo_t *r2)
Definition: routerlist.c:507
reschedule_directory_downloads
void reschedule_directory_downloads(void)
Definition: mainloop.c:1606
networkstatus_voter_info_t::identity_digest
char identity_digest[DIGEST_LEN]
Definition: networkstatus_voter_info_st.h:18
tor_assert
#define tor_assert(expr)
Definition: util_bug.h:102
desc_store_t
Definition: desc_store_st.h:23
CONN_TYPE_DIR
#define CONN_TYPE_DIR
Definition: connection.h:55
microdesc.h
Header file for microdesc.c.
LD_BUG
#define LD_BUG
Definition: log.h:86
DEFAULT_MAX_BELIEVABLE_BANDWIDTH
#define DEFAULT_MAX_BELIEVABLE_BANDWIDTH
Definition: routerlist.c:650
authcert.h
Header file for authcert.c.
router_should_rebuild_store
static int router_should_rebuild_store(desc_store_t *store)
Definition: routerlist.c:172
DIR_PURPOSE_FETCH_MICRODESC
#define DIR_PURPOSE_FETCH_MICRODESC
Definition: directory.h:71
routerinfo_t::ipv6_exit_policy
struct short_policy_t * ipv6_exit_policy
Definition: routerinfo_st.h:63
warned_nicknames
static smartlist_t * warned_nicknames
Definition: routerlist.c:149
format_iso_time
void format_iso_time(char *buf, time_t t)
Definition: time_fmt.c:295
fast_mem_is_zero
int fast_mem_is_zero(const char *mem, size_t len)
Definition: util_string.c:74
append_bytes_to_file
int append_bytes_to_file(const char *fname, const char *str, size_t len, int bin)
Definition: files.c:538
LD_GENERAL
#define LD_GENERAL
Definition: log.h:62
ROUTER_MAX_AGE
#define ROUTER_MAX_AGE
Definition: or.h:158
router_load_single_router
int router_load_single_router(const char *s, uint8_t purpose, int cache, const char **msg)
Definition: routerlist.c:2045
base16_encode
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:478
DIGESTMAP_FOREACH_END
#define DIGESTMAP_FOREACH_END
Definition: map.h:168
routerinfo_t::identity_pkey
crypto_pk_t * identity_pkey
Definition: routerinfo_st.h:41
router_get_my_routerinfo
const routerinfo_t * router_get_my_routerinfo(void)
Definition: router.c:1740
networkstatus_t::voters
smartlist_t * voters
Definition: networkstatus_st.h:83
sized_chunk_t
Definition: files.h:82
extrainfo_t::digest256
uint8_t digest256[DIGEST256_LEN]
Definition: extrainfo_st.h:21
update_router_descriptor_downloads
void update_router_descriptor_downloads(time_t now)
Definition: routerlist.c:2797
describe.h
Header file for describe.c.
desc_store_t::description
const char * description
Definition: desc_store_st.h:29
extrainfo_get_by_descriptor_digest
signed_descriptor_t * extrainfo_get_by_descriptor_digest(const char *digest)
Definition: routerlist.c:808
signed_descriptor_t::annotations_len
size_t annotations_len
Definition: signed_descriptor_st.h:24
desc_store_t::store_len
size_t store_len
Definition: desc_store_st.h:38
reachability.h
Header file for reachability.c.
node_supports_initiating_ipv6_extends
bool node_supports_initiating_ipv6_extends(const node_t *node)
Definition: nodelist.c:1222
process_descs.h
Header file for process_descs.c.
routerlist_t::desc_by_eid_map
struct digest_sd_map_t * desc_by_eid_map
Definition: routerlist_st.h:30
router_exit_policy_rejects_all
int router_exit_policy_rejects_all(const routerinfo_t *router)
Definition: routerlist.c:2329
routerlist_t::extrainfo_store
desc_store_t extrainfo_store
Definition: routerlist_st.h:41
smartlist_add
void smartlist_add(smartlist_t *sl, void *element)
Definition: smartlist_core.c:117
routerset_refresh_countries
void routerset_refresh_countries(routerset_t *target)
Definition: routerset.c:81
replace_file
int replace_file(const char *from, const char *to)
Definition: files.c:117
digestset_probably_contains
int digestset_probably_contains(const digestset_t *set, const char *digest)
Definition: digestset.c:54
crypto_pk_eq_keys
int crypto_pk_eq_keys(const crypto_pk_t *a, const crypto_pk_t *b)
Definition: crypto_rsa.c:71
routerstatus_t
Definition: routerstatus_st.h:19
dump_routerlist_mem_usage
void dump_routerlist_mem_usage(int severity)
Definition: routerlist.c:1058
signed_descriptor_from_routerinfo
static signed_descriptor_t * signed_descriptor_from_routerinfo(routerinfo_t *ri)
Definition: routerlist.c:1007
routerlist_t::old_routers
smartlist_t * old_routers
Definition: routerlist_st.h:35
routerlist_t::routers
smartlist_t * routers
Definition: routerlist_st.h:32
tor_mmap_t::data
const char * data
Definition: mmap.h:26
routerstatus_t::nickname
char nickname[MAX_NICKNAME_LEN+1]
Definition: routerstatus_st.h:25
WRA_NEVER_DOWNLOADABLE
static int WRA_NEVER_DOWNLOADABLE(was_router_added_t s)
Definition: routerlist.h:132
DUMMY_DOWNLOAD_INTERVAL
#define DUMMY_DOWNLOAD_INTERVAL
Definition: routerlist.c:2766
routerlist_t::desc_digest_map
struct digest_sd_map_t * desc_digest_map
Definition: routerlist_st.h:23
smartlist_new
smartlist_t * smartlist_new(void)
Definition: smartlist_core.c:26
nodelist_remove_routerinfo
void nodelist_remove_routerinfo(routerinfo_t *ri)
Definition: nodelist.c:745
routerinfo_t::onion_pkey_len
size_t onion_pkey_len
Definition: routerinfo_st.h:39
router_purpose_to_string
const char * router_purpose_to_string(uint8_t p)
Definition: routerinfo.c:82
tor_snprintf
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
nodelist_set_routerinfo
node_t * nodelist_set_routerinfo(routerinfo_t *ri, routerinfo_t **ri_old_out)
Definition: nodelist.c:505
routerinfo_t::ipv6_addr
tor_addr_t ipv6_addr
Definition: routerinfo_st.h:30
launch_descriptor_downloads
void launch_descriptor_downloads(int purpose, smartlist_t *downloadable, const routerstatus_t *source, time_t now)
Definition: routerlist.c:2519
trusted_dirs_remove_old_certs
void trusted_dirs_remove_old_certs(void)
Definition: authcert.c:548
extrainfo_free_void
static void extrainfo_free_void(void *e)
Definition: routerlist.c:1019
routerlist_insert_old
static void routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
Definition: routerlist.c:1238
authdir_mode_handles_descs
int authdir_mode_handles_descs(const or_options_t *options, int purpose)
Definition: authmode.c:43
SMARTLIST_FOREACH
#define SMARTLIST_FOREACH(sl, type, var, cmd)
Definition: smartlist_foreach.h:112
tor_mmap_t::size
size_t size
Definition: mmap.h:27
dir_split_resource_into_fingerprints
int dir_split_resource_into_fingerprints(const char *resource, smartlist_t *fp_out, int *compressed_out, int flags)
Definition: directory.c:644
routerinfo_t::platform
char * platform
Definition: routerinfo_st.h:48
list_pending_downloads
void list_pending_downloads(digestmap_t *result, digest256map_t *result256, int purpose, const char *prefix)
Definition: routerlist.c:2341
signed_descriptor_get_body_impl
static const char * signed_descriptor_get_body_impl(const signed_descriptor_t *desc, int with_annotations)
Definition: routerlist.c:829
routerinfo_is_a_configured_bridge
int routerinfo_is_a_configured_bridge(const routerinfo_t *ri)
Definition: bridges.c:300
digestset.h
Types to handle sets of digests, based on bloom filters.
networkstatus.h
Header file for networkstatus.c.
OLD_ROUTER_DESC_MAX_AGE
#define OLD_ROUTER_DESC_MAX_AGE
Definition: or.h:163
networkstatus_vote_find_entry
const routerstatus_t * networkstatus_vote_find_entry(networkstatus_t *ns, const char *digest)
Definition: networkstatus.c:725
router_get_by_id_digest
const routerinfo_t * router_get_by_id_digest(const char *digest)
Definition: routerlist.c:774
digest256_to_base64
void digest256_to_base64(char *d64, const char *digest)
Definition: crypto_format.c:304
signed_descriptor_t::identity_digest
char identity_digest[DIGEST_LEN]
Definition: signed_descriptor_st.h:31
routerlist_remove_old_routers
void routerlist_remove_old_routers(void)
Definition: routerlist.c:1890
tor_memeq
int tor_memeq(const void *a, const void *b, size_t sz)
Definition: di_ops.c:107
dirlist.h
Header file for dirlist.c.
directory_get_from_dirserver
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:456
update_all_descriptor_downloads
void update_all_descriptor_downloads(time_t now)
Definition: routerlist.c:2302
base16_decode
int base16_decode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:506
routerinfo_t::bandwidthburst
uint32_t bandwidthburst
Definition: routerinfo_st.h:56
or_options_t::TestingClientMaxIntervalWithoutRequest
int TestingClientMaxIntervalWithoutRequest
Definition: or_options_st.h:777
compare_signed_descriptors_by_age_
static int compare_signed_descriptors_by_age_(const void **_a, const void **_b)
Definition: routerlist.c:221
learned_bridge_descriptor
void learned_bridge_descriptor(routerinfo_t *ri, int from_cache)
Definition: bridges.c:917
duration_idx_t
Definition: routerlist.c:1780
routerinfo_t::protocol_list
char * protocol_list
Definition: routerinfo_st.h:50
mainloop.h
Header file for mainloop.c.
write_str_to_file
int write_str_to_file(const char *fname, const char *str, int bin)
Definition: files.c:258
DIGEST_LEN
#define DIGEST_LEN
Definition: digest_sizes.h:20
or_options_t::ExcludeExitNodesUnion_
struct routerset_t * ExcludeExitNodesUnion_
Definition: or_options_st.h:112
ROUTER_PURPOSE_BRIDGE
#define ROUTER_PURPOSE_BRIDGE
Definition: routerinfo_st.h:106
signed_descriptor_t::extra_info_digest256
char extra_info_digest256[DIGEST256_LEN]
Definition: signed_descriptor_st.h:37
router_parse_entry_from_string
routerinfo_t * router_parse_entry_from_string(const char *s, const char *end, int cache_copy, int allow_annotations, const char *prepend_annotations, int *can_dl_again_out)
Definition: routerparse.c:394
MIN_DL_PER_REQUEST
#define MIN_DL_PER_REQUEST
Definition: routerlist.c:2504
last_descriptor_download_attempted
static time_t last_descriptor_download_attempted
Definition: routerlist.c:154
signed_descriptor_get_body
const char * signed_descriptor_get_body(const signed_descriptor_t *desc)
Definition: routerlist.c:878
crypto_format.h
Header for crypto_format.c.
DIR_PURPOSE_FETCH_SERVERDESC
#define DIR_PURPOSE_FETCH_SERVERDESC
Definition: directory.h:39
digestset_new
digestset_t * digestset_new(int max_guess)
Definition: digestset.c:30
signed_descriptor_t::saved_location
saved_location_t saved_location
Definition: signed_descriptor_st.h:44
bridges.h
Header file for circuitbuild.c.
dirserv_would_reject_router
int dirserv_would_reject_router(const routerstatus_t *rs, const vote_routerstatus_t *vrs)
Definition: process_descs.c:374
routerlist_t
Definition: routerlist_st.h:18
networkstatus_get_latest_consensus_by_flavor
networkstatus_t * networkstatus_get_latest_consensus_by_flavor(consensus_flavor_t f)
Definition: networkstatus.c:1401
routerinfo_t::ipv4_addr
tor_addr_t ipv4_addr
Definition: routerinfo_st.h:25
LD_FS
#define LD_FS
Definition: log.h:70
tor_memneq
#define tor_memneq(a, b, sz)
Definition: di_ops.h:21
RFTS_BIN
#define RFTS_BIN
Definition: files.h:95
authdir_wants_to_reject_router
int authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg, int complain, int *valid_out)
Definition: process_descs.c:574
routerlist_retry_directory_downloads
void routerlist_retry_directory_downloads(time_t now)
Definition: routerlist.c:2314
networkstatus_get_latest_consensus
networkstatus_t * networkstatus_get_latest_consensus(void)
Definition: networkstatus.c:1390
node_t
Definition: node_st.h:34
directory_request_set_routerstatus
void directory_request_set_routerstatus(directory_request_t *req, const routerstatus_t *status)
Definition: dirclient.c:1162
RFTS_IGNORE_MISSING
#define RFTS_IGNORE_MISSING
Definition: files.h:97
vote_routerstatus_st.h
Routerstatus (vote entry) structure.
router_reload_router_list_impl
static int router_reload_router_list_impl(desc_store_t *store)
Definition: routerlist.c:391
protover_summary_flags_t::supports_extend2_cells
unsigned int supports_extend2_cells
Definition: or.h:817
networkstatus_t::flavor
consensus_flavor_t flavor
Definition: networkstatus_st.h:28
routerlist_find_my_routerinfo
const routerinfo_t * routerlist_find_my_routerinfo(void)
Definition: routerlist.c:625
torcert.h
Header for torcert.c.
max_dl_per_request
static int max_dl_per_request(const or_options_t *options, int purpose)
Definition: routerlist.c:2475
vote_routerstatus_t
Definition: vote_routerstatus_st.h:18
signed_descriptor_reset
static void signed_descriptor_reset(signed_descriptor_t *sd)
Definition: routerlist.c:980
router_get_dl_status_by_descriptor_digest
download_status_t * router_get_dl_status_by_descriptor_digest(const char *d)
Definition: networkstatus.c:816
directory.h
Header file for directory.c.
routerstatus_t::published_on
time_t published_on
Definition: routerstatus_st.h:24
tor_digest_is_zero
int tor_digest_is_zero(const char *digest)
Definition: util_string.c:96
routerinfo_t::policy_is_reject_star
unsigned int policy_is_reject_star
Definition: routerinfo_st.h:77
or_options_t::ExcludeNodes
struct routerset_t * ExcludeNodes
Definition: or_options_st.h:102
networkstatus_reset_warnings
void networkstatus_reset_warnings(void)
Definition: networkstatus.c:193
extrainfo_t::pending_sig
char * pending_sig
Definition: extrainfo_st.h:29
smartlist_string_remove
void smartlist_string_remove(smartlist_t *sl, const char *element)
Definition: smartlist.c:74
networkstatus_get_reasonably_live_consensus
networkstatus_t * networkstatus_get_reasonably_live_consensus(time_t now, int flavor)
Definition: networkstatus.c:1477
routerlist_replace
static void routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old, routerinfo_t *ri_new)
Definition: routerlist.c:1385
signed_descriptor_t::signed_descriptor_digest
char signed_descriptor_digest[DIGEST_LEN]
Definition: signed_descriptor_st.h:29
router_rebuild_store
static int router_rebuild_store(int flags, desc_store_t *store)
Definition: routerlist.c:237
desc_get_store
static desc_store_t * desc_get_store(routerlist_t *rl, const signed_descriptor_t *sd)
Definition: routerlist.c:184
dirclient_fetches_dir_info_early
int dirclient_fetches_dir_info_early(const or_options_t *options)
Definition: dirclient_modes.c:72
escaped
const char * escaped(const char *s)
Definition: escape.c:126
strcmpstart
int strcmpstart(const char *s1, const char *s2)
Definition: util_string.c:206
we_fetch_router_descriptors
int we_fetch_router_descriptors(const or_options_t *options)
Definition: microdesc.c:1074
SAVED_IN_JOURNAL
@ SAVED_IN_JOURNAL
Definition: or.h:761
smartlist_del
void smartlist_del(smartlist_t *sl, int idx)
Definition: smartlist_core.c:214
desc_store_t::fname_base
const char * fname_base
Definition: desc_store_st.h:27
networkstatus_voter_info_st.h
Single consensus voter structure.
signed_descriptor_free_
static void signed_descriptor_free_(signed_descriptor_t *sd)
Definition: routerlist.c:965
routerinfo_t::exit_policy
smartlist_t * exit_policy
Definition: routerinfo_st.h:59
download_status_t
Definition: download_status_st.h:41
routerlist_st.h
Router descriptor list structure.
authmode.h
Header file for directory authority mode.
get_connection_array
smartlist_t * get_connection_array(void)
Definition: mainloop.c:453
router_reset_descriptor_download_failures
void router_reset_descriptor_download_failures(void)
Definition: routerlist.c:2922
or_options_t::ExcludeExitNodes
struct routerset_t * ExcludeExitNodes
Definition: or_options_st.h:106
nodelist.h
Header file for nodelist.c.
DIR_PURPOSE_FETCH_EXTRAINFO
#define DIR_PURPOSE_FETCH_EXTRAINFO
Definition: directory.h:42
WRA_WAS_OUTDATED
static int WRA_WAS_OUTDATED(was_router_added_t s)
Definition: routerlist.h:116
routerlist.h
Header file for routerlist.c.
routerlist_t::desc_store
desc_store_t desc_store
Definition: routerlist_st.h:39
dir_server_t::fake_status
routerstatus_t fake_status
Definition: dir_server_st.h:51
networkstatus_voter_info_t
Definition: networkstatus_voter_info_st.h:16
routerset.h
Header file for routerset.c.
routerinfo_t::supports_tunnelled_dir_requests
unsigned int supports_tunnelled_dir_requests
Definition: routerinfo_st.h:86
PDS_NO_EXISTING_SERVERDESC_FETCH
#define PDS_NO_EXISTING_SERVERDESC_FETCH
Definition: node_select.h:67
initiate_descriptor_downloads
STATIC void initiate_descriptor_downloads(const routerstatus_t *source, int purpose, smartlist_t *digests, int lo, int hi, int pds_flags)
Definition: routerlist.c:2408
or_options_t::DownloadExtraInfo
int DownloadExtraInfo
Definition: or_options_st.h:622
routerinfo_t::declared_family
smartlist_t * declared_family
Definition: routerinfo_st.h:65
smartlist_contains_string
int smartlist_contains_string(const smartlist_t *sl, const char *element)
Definition: smartlist.c:93
node_has_curve25519_onion_key
int node_has_curve25519_onion_key(const node_t *node)
Definition: nodelist.c:1928
routerinfo_st.h
Router descriptor structure.
MIN_REQUESTS
#define MIN_REQUESTS
Definition: routerlist.c:2507
DIGEST256_LEN
#define DIGEST256_LEN
Definition: digest_sizes.h:23
dir_server_t
Definition: dir_server_st.h:21
routerlist_t::extra_info_map
struct digest_ei_map_t * extra_info_map
Definition: routerlist_st.h:26
node_select.h
Header file for node_select.c.
routerinfo_t::contact_info
char * contact_info
Definition: routerinfo_st.h:67
crypto_pk_public_checksig
int crypto_pk_public_checksig(const crypto_pk_t *env, char *to, size_t tolen, const char *from, size_t fromlen)
Definition: crypto_rsa_nss.c:513
networkstatus_t::routerstatus_list
smartlist_t * routerstatus_list
Definition: networkstatus_st.h:96
saved_location_t
saved_location_t
Definition: or.h:747
document_signature_st.h
Authority signature structure.
routers_update_status_from_consensus_networkstatus
void routers_update_status_from_consensus_networkstatus(smartlist_t *routers, int reset_failures)
Definition: networkstatus.c:2284
file_status
file_status_t file_status(const char *filename)
Definition: files.c:212
hex_digest_nickname_matches
int hex_digest_nickname_matches(const char *hexdigest, const char *identity_digest, const char *nickname)
Definition: routerlist.c:718
PDS_NO_EXISTING_MICRODESC_FETCH
#define PDS_NO_EXISTING_MICRODESC_FETCH
Definition: node_select.h:73
routerlist_descriptors_added
void routerlist_descriptors_added(smartlist_t *sl, int from_cache)
Definition: routerlist.c:2016
WRA_WAS_ADDED
static int WRA_WAS_ADDED(was_router_added_t s)
Definition: routerlist.h:106
protover_summary_flags_t::protocols_known
unsigned int protocols_known
Definition: or.h:813
connection_t
Definition: connection_st.h:45
node_allows_single_hop_exits
int node_allows_single_hop_exits(const node_t *node)
Definition: nodelist.c:1487
desc_store_t::type
store_type_t type
Definition: desc_store_st.h:33
router_get_by_extrainfo_digest
signed_descriptor_t * router_get_by_extrainfo_digest(const char *digest)
Definition: routerlist.c:795
routerstatus_t::pv
protover_summary_flags_t pv
Definition: routerstatus_st.h:68
LOG_INFO
#define LOG_INFO
Definition: log.h:45
signed_descriptor_t::ei_dl_status
download_status_t ei_dl_status
Definition: signed_descriptor_st.h:42
router_get_by_descriptor_digest
signed_descriptor_t * router_get_by_descriptor_digest(const char *digest)
Definition: routerlist.c:782
crypto_rand.h
Common functions for using (pseudo-)random number generators.
routerlist
static routerlist_t * routerlist
Definition: routerlist.c:145
control_events.h
Header file for control_events.c.
get_options
const or_options_t * get_options(void)
Definition: config.c:928
routerstatus_t::descriptor_digest
char descriptor_digest[DIGEST256_LEN]
Definition: routerstatus_st.h:31
desc_store_t::journal_len
size_t journal_len
Definition: desc_store_st.h:36
rep_hist_note_router_unreachable
void rep_hist_note_router_unreachable(const char *id, time_t when)
Definition: rephist.c:301
router_get_advertised_bandwidth
uint32_t router_get_advertised_bandwidth(const routerinfo_t *router)
Definition: routerlist.c:641
routerinfo_incompatible_with_extrainfo
int routerinfo_incompatible_with_extrainfo(const crypto_pk_t *identity_pkey, extrainfo_t *ei, signed_descriptor_t *sd, const char **msg)
Definition: routerlist.c:3050
SAVED_IN_CACHE
@ SAVED_IN_CACHE
Definition: or.h:754
or_options_t::ExitNodes
struct routerset_t * ExitNodes
Definition: or_options_st.h:90
signed_desc_append_to_journal
static int signed_desc_append_to_journal(signed_descriptor_t *desc, desc_store_t *store)
Definition: routerlist.c:196
routerlist_remove_old_cached_routers_with_id
static void routerlist_remove_old_cached_routers_with_id(time_t now, time_t cutoff, int lo, int hi, digestset_t *retain)
Definition: routerlist.c:1804
routerinfo_t::onion_pkey
char * onion_pkey
Definition: routerinfo_st.h:37
node_is_unreliable
int node_is_unreliable(const node_t *node, int need_uptime, int need_capacity, int need_guard)
Definition: nodelist.c:2254
MAX_NICKNAME_LEN
#define MAX_NICKNAME_LEN
Definition: or.h:112
or_options_t::MiddleNodes
struct routerset_t * MiddleNodes
Definition: or_options_st.h:93
smartlist_clear
void smartlist_clear(smartlist_t *sl)
Definition: smartlist_core.c:50
list_pending_descriptor_downloads
static void list_pending_descriptor_downloads(digestmap_t *result, int extrainfo)
Definition: routerlist.c:2384
directory_request_set_resource
void directory_request_set_resource(directory_request_t *req, const char *resource)
Definition: dirclient.c:1045
extrainfo_free_
void extrainfo_free_(extrainfo_t *extrainfo)
Definition: routerlist.c:948
signed_desc_digest_is_recognized
static int signed_desc_digest_is_recognized(signed_descriptor_t *desc)
Definition: routerlist.c:2284
firewall_is_fascist_dir
int firewall_is_fascist_dir(void)
Definition: policies.c:365
dirserv_single_reachability_test
void dirserv_single_reachability_test(time_t now, routerinfo_t *router)
Definition: reachability.c:130
compare_old_routers_by_identity_
static int compare_old_routers_by_identity_(const void **_a, const void **_b)
Definition: routerlist.c:1768
router_load_extrainfo_from_string
void router_load_extrainfo_from_string(const char *s, const char *eos, saved_location_t saved_location, smartlist_t *requested_fingerprints, int descriptor_digests)
Definition: routerlist.c:2211
routerlist_find_elt_
static int routerlist_find_elt_(smartlist_t *sl, void *ri, int idx)
Definition: routerlist.c:1081
signed_descriptor_t::signing_key_cert
struct tor_cert_st * signing_key_cert
Definition: signed_descriptor_st.h:39
nodelist_get_list
const smartlist_t * nodelist_get_list(void)
Definition: nodelist.c:966
tor_cert_opt_eq
int tor_cert_opt_eq(const tor_cert_t *cert1, const tor_cert_t *cert2)
Definition: torcert.c:315
trusteddirserver_get_by_v3_auth_digest
dir_server_t * trusteddirserver_get_by_v3_auth_digest(const char *digest)
Definition: dirlist.c:199
router_descriptor_is_older_than
int router_descriptor_is_older_than(const routerinfo_t *router, int seconds)
Definition: routerlist.c:1544
launch_dummy_descriptor_download_as_needed
static void launch_dummy_descriptor_download_as_needed(time_t now, const or_options_t *options)
Definition: routerlist.c:2771
extrainfo_insert
STATIC was_router_added_t extrainfo_insert(routerlist_t *rl, extrainfo_t *ei, int warn_if_incompatible)
Definition: routerlist.c:1148
connection.h
Header file for connection.c.
directory_caches_dir_info
int directory_caches_dir_info(const or_options_t *options)
Definition: dirserv.c:94
router_parse_list_from_string
int router_parse_list_from_string(const char **s, const char *eos, smartlist_t *dest, saved_location_t saved_location, int want_extrainfo, int allow_annotations, const char *prepend_annotations, smartlist_t *invalid_digests_out)
Definition: routerparse.c:249
directory_request_new
directory_request_t * directory_request_new(uint8_t dir_purpose)
Definition: dirclient.c:948
signed_descriptor_get_annotations
const char * signed_descriptor_get_annotations(const signed_descriptor_t *desc)
Definition: routerlist.c:886
smartlist_shuffle
void smartlist_shuffle(smartlist_t *sl)
Definition: crypto_rand.c:602
extrainfo_st.h
A relay's extra-info structure.
networkstatus_t::valid_after
time_t valid_after
Definition: networkstatus_st.h:33
dirserv.h
Header file for dirserv.c.
server_mode
int server_mode(const or_options_t *options)
Definition: routermode.c:34
router_reset_status_download_failures
void router_reset_status_download_failures(void)
Definition: dirlist.c:135
download_status_is_ready
int download_status_is_ready(download_status_t *dls, time_t now)
Definition: dlstatus.c:381
update_extrainfo_downloads
void update_extrainfo_downloads(time_t now)
Definition: routerlist.c:2811
signed_descriptor_t::saved_offset
off_t saved_offset
Definition: signed_descriptor_st.h:47
dirclient.h
Header file for dirclient.c.
digestset_add
void digestset_add(digestset_t *set, const char *digest)
Definition: digestset.c:44
node_supports_v3_rendezvous_point
bool node_supports_v3_rendezvous_point(const node_t *node)
Definition: nodelist.c:1190
ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
#define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
Definition: routerlist.c:2945
tor_asprintf
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
networkstatus_reset_download_failures
void networkstatus_reset_download_failures(void)
Definition: networkstatus.c:206
smartlist_sort_digests
void smartlist_sort_digests(smartlist_t *sl)
Definition: smartlist.c:824
SMARTLIST_FOREACH_BEGIN
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
Definition: smartlist_foreach.h:78
dlstatus.h
Header file for dlstatus.c.
log_fn_ratelim
#define log_fn_ratelim(ratelim, severity, domain, args,...)
Definition: log.h:292
crypto_pk_t
Definition: crypto_rsa_nss.c:37
update_microdesc_downloads
void update_microdesc_downloads(time_t now)
Definition: microdesc.c:992
router_get_routerlist
routerlist_t * router_get_routerlist(void)
Definition: routerlist.c:893
fast_memcmp
#define fast_memcmp(a, b, c)
Definition: di_ops.h:28
dir_connection_st.h
Client/server directory connection structure.
list_pending_microdesc_downloads
void list_pending_microdesc_downloads(digest256map_t *result)
Definition: routerlist.c:2395
networkstatus_vote_find_mutable_entry
routerstatus_t * networkstatus_vote_find_mutable_entry(networkstatus_t *ns, const char *digest)
Definition: networkstatus.c:716
HEX_DIGEST_LEN
#define HEX_DIGEST_LEN
Definition: crypto_digest.h:35
or_options_t::UseBridges
int UseBridges
Definition: or_options_st.h:233
LOG_WARN
#define LOG_WARN
Definition: log.h:53
node_st.h
Node information structure.
router_get_my_extrainfo
extrainfo_t * router_get_my_extrainfo(void)
Definition: router.c:1793
extrainfo_t::bad_sig
unsigned int bad_sig
Definition: extrainfo_st.h:26
or_options_t::EntryNodes
struct routerset_t * EntryNodes
Definition: or_options_st.h:96
was_router_added_t
was_router_added_t
Definition: routerlist.h:17
compare_routerinfo_by_id_digest_
static int compare_routerinfo_by_id_digest_(const void **a, const void **b)
Definition: routerlist.c:3297
router_describe
const char * router_describe(const routerinfo_t *ri)
Definition: describe.c:122
policies.h
Header file for policies.c.
TO_DIR_CONN
dir_connection_t * TO_DIR_CONN(connection_t *c)
Definition: directory.c:89
update_consensus_router_descriptor_downloads
void update_consensus_router_descriptor_downloads(time_t now, int is_vote, networkstatus_t *consensus)
Definition: routerlist.c:2617
routerinfo_t::uptime
long uptime
Definition: routerinfo_st.h:64
ROUTER_ANNOTATION_BUF_LEN
#define ROUTER_ANNOTATION_BUF_LEN
Definition: or.h:804
dirclient_too_idle_to_fetch_descriptors
int dirclient_too_idle_to_fetch_descriptors(const or_options_t *options, time_t now)
Definition: dirclient_modes.c:94
config.h
Header file for config.c.
hexdigest_to_digest
int hexdigest_to_digest(const char *hexdigest, char *digest)
Definition: routerlist.c:747
router_is_me
int router_is_me(const routerinfo_t *router)
Definition: router.c:1732
PDS_RETRY_IF_NO_SERVERS
#define PDS_RETRY_IF_NO_SERVERS
Definition: node_select.h:54
router_get_advertised_bandwidth_capped
uint32_t router_get_advertised_bandwidth_capped(const routerinfo_t *router)
Definition: routerlist.c:655
routerlist_free_all
void routerlist_free_all(void)
Definition: routerlist.c:1513
routerlist_assert_ok
void routerlist_assert_ok(const routerlist_t *rl)
Definition: routerlist.c:3187
routerinfo_free_
void routerinfo_free_(routerinfo_t *router)
Definition: routerlist.c:918
client_would_use_router
int client_would_use_router(const routerstatus_t *rs, time_t now)
Definition: networkstatus.c:2602
or_options_t::Address
struct config_line_t * Address
Definition: or_options_st.h:82
esc_for_log
char * esc_for_log(const char *s)
Definition: escape.c:30
node_t::is_valid
unsigned int is_valid
Definition: node_st.h:65
tor_log
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:628
routerinfo_t::is_hibernating
unsigned int is_hibernating
Definition: routerinfo_st.h:68
router_add_running_nodes_to_smartlist
void router_add_running_nodes_to_smartlist(smartlist_t *sl, int flags)
Definition: routerlist.c:613
signed_descriptor_t::published_on
time_t published_on
Definition: signed_descriptor_st.h:33
router_get_mutable_by_digest
routerinfo_t * router_get_mutable_by_digest(const char *digest)
Definition: routerlist.c:760
should_delay_dir_fetches
int should_delay_dir_fetches(const or_options_t *options, const char **msg_out)
Definition: networkstatus.c:1253
ROUTER_PURPOSE_GENERAL
#define ROUTER_PURPOSE_GENERAL
Definition: routerinfo_st.h:98
signed_descriptor_t
Definition: signed_descriptor_st.h:18
or_options_t
Definition: or_options_st.h:45
addr_policies_eq
int addr_policies_eq(const smartlist_t *a, const smartlist_t *b)
Definition: policies.c:1274
refresh_all_country_info
void refresh_all_country_info(void)
Definition: routerlist.c:3316
signed_descriptor_t::routerlist_index
int routerlist_index
Definition: signed_descriptor_st.h:50
STATIC
#define STATIC
Definition: testsupport.h:32
compare_duration_idx_
static int compare_duration_idx_(const void *_d1, const void *_d2)
Definition: routerlist.c:1788
control_event_descriptors_changed
int control_event_descriptors_changed(smartlist_t *routers)
Definition: control_events.c:1431
signed_descriptor_t::signed_descriptor_body
char * signed_descriptor_body
Definition: signed_descriptor_st.h:22
signed_descriptor_t::signed_descriptor_len
size_t signed_descriptor_len
Definition: signed_descriptor_st.h:26
router_have_minimum_dir_info
int router_have_minimum_dir_info(void)
Definition: nodelist.c:2346
routerparse.h
Header file for routerparse.c.
routerinfo_t::nickname
char * nickname
Definition: routerinfo_st.h:22
LD_DIR
#define LD_DIR
Definition: log.h:88
networkstatus_st.h
Networkstatus consensus/vote structure.
smartlist_sort
void smartlist_sort(smartlist_t *sl, int(*compare)(const void **a, const void **b))
Definition: smartlist.c:334
directory_request_t
struct directory_request_t directory_request_t
Definition: dirclient.h:52
dirclient_modes.h
Header for feature/dirclient/dirclient_modes.c.
routerstatus_t::identity_digest
char identity_digest[DIGEST_LEN]
Definition: routerstatus_st.h:27
networkstatus_t
Definition: networkstatus_st.h:26
fascist_firewall_allows_node
int fascist_firewall_allows_node(const node_t *node, firewall_connection_t fw_connection, int pref_only)
Definition: policies.c:688
SAVED_NOWHERE
@ SAVED_NOWHERE
Definition: or.h:750
router_dir_info_changed
void router_dir_info_changed(void)
Definition: nodelist.c:2389
MAX_DL_TO_DELAY
#define MAX_DL_TO_DELAY
Definition: routerlist.c:2510
esc_router_info
const char * esc_router_info(const routerinfo_t *router)
Definition: routerlist.c:3275
node_has_preferred_descriptor
int node_has_preferred_descriptor(const node_t *node, int for_direct_connect)
Definition: nodelist.c:1419
routerinfo_t::bandwidthrate
uint32_t bandwidthrate
Definition: routerinfo_st.h:54
node_t::is_running
unsigned int is_running
Definition: node_st.h:63
smartlist_t
Definition: smartlist_core.h:26
smartlist_join_strings
char * smartlist_join_strings(smartlist_t *sl, const char *join, int terminate, size_t *len_out)
Definition: smartlist.c:279
tor_addr_eq
#define tor_addr_eq(a, b)
Definition: address.h:280
routerlist_remove
void routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old, time_t now)
Definition: routerlist.c:1273
routerlist_free_
void routerlist_free_(routerlist_t *rl)
Definition: routerlist.c:1026
rephist.h
Header file for rephist.c.
signed_descriptor_move
static void signed_descriptor_move(signed_descriptor_t *dest, signed_descriptor_t *src)
Definition: routerlist.c:991
router_add_to_routerlist
was_router_added_t router_add_to_routerlist(routerinfo_t *router, const char **msg, int from_cache, int from_fetch)
Definition: routerlist.c:1571
desc_store_t::mmap
tor_mmap_t * mmap
Definition: desc_store_st.h:31
authdir_mode
int authdir_mode(const or_options_t *options)
Definition: authmode.c:25
routerinfo_t::onion_curve25519_pkey
struct curve25519_public_key_t * onion_curve25519_pkey
Definition: routerinfo_st.h:43
routerlist_remove_old
static void routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
Definition: routerlist.c:1332
ratelim_t
Definition: ratelim.h:42
or.h
Master header file for Tor-specific functionality.
routerinfo_t::cert_expiration_time
time_t cert_expiration_time
Definition: routerinfo_st.h:46
signed_descriptor_t::extra_info_digest
char extra_info_digest[DIGEST_LEN]
Definition: signed_descriptor_st.h:35