Tor  0.4.5.0-alpha-dev
relay_config.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 relay_config.c
9  * @brief Code to interpret the user's configuration of Tor's relay module.
10  **/
11 
12 #include "orconfig.h"
13 #define RELAY_CONFIG_PRIVATE
15 
16 #include "lib/encoding/confline.h"
17 #include "lib/confmgt/confmgt.h"
18 
20 #include "lib/geoip/geoip.h"
21 #include "lib/meminfo/meminfo.h"
22 #include "lib/osinfo/uname.h"
23 #include "lib/process/setuid.h"
24 
25 /* Required for dirinfo_type_t in or_options_t */
26 #include "core/or/or.h"
27 #include "app/config/config.h"
28 
31 #include "core/mainloop/mainloop.h"
32 #include "core/or/connection_or.h"
33 #include "core/or/port_cfg_st.h"
34 
40 #include "feature/stats/rephist.h"
41 
43 
45 #include "feature/relay/dns.h"
47 #include "feature/relay/selftest.h"
48 
49 /** Contents of most recently read DirPortFrontPage file. */
50 static char *global_dirfrontpagecontents = NULL;
51 
52 /* Copied from config.c, we will refactor later in 29211. */
53 #define REJECT(arg) \
54  STMT_BEGIN *msg = tor_strdup(arg); return -1; STMT_END
55 #if defined(__GNUC__) && __GNUC__ <= 3
56 #define COMPLAIN(args...) \
57  STMT_BEGIN log_warn(LD_CONFIG, args); STMT_END
58 #else
59 #define COMPLAIN(args, ...) \
60  STMT_BEGIN log_warn(LD_CONFIG, args, ##__VA_ARGS__); STMT_END
61 #endif /* defined(__GNUC__) && __GNUC__ <= 3 */
62 
63 /* Used in the various options_transition_affects* functions. */
64 #define YES_IF_CHANGED_BOOL(opt) \
65  if (!CFG_EQ_BOOL(old_options, new_options, opt)) return 1;
66 #define YES_IF_CHANGED_INT(opt) \
67  if (!CFG_EQ_INT(old_options, new_options, opt)) return 1;
68 #define YES_IF_CHANGED_STRING(opt) \
69  if (!CFG_EQ_STRING(old_options, new_options, opt)) return 1;
70 #define YES_IF_CHANGED_LINELIST(opt) \
71  if (!CFG_EQ_LINELIST(old_options, new_options, opt)) return 1;
72 
73 /** Return the contents of our frontpage string, or NULL if not configured. */
74 MOCK_IMPL(const char*,
76 {
78 }
79 
80 /** Release all memory and resources held by global relay configuration
81  * structures.
82  */
83 void
85 {
87 }
88 
89 /** Return the bandwidthrate that we are going to report to the authorities
90  * based on the config options. */
91 uint32_t
93 {
94  uint64_t bw = options->BandwidthRate;
95  if (bw > options->MaxAdvertisedBandwidth)
96  bw = options->MaxAdvertisedBandwidth;
97  if (options->RelayBandwidthRate > 0 && bw > options->RelayBandwidthRate)
98  bw = options->RelayBandwidthRate;
99  /* config_ensure_bandwidth_cap() makes sure that this cast can't overflow. */
100  return (uint32_t)bw;
101 }
102 
103 /** Return the bandwidthburst that we are going to report to the authorities
104  * based on the config options. */
105 uint32_t
107 {
108  uint64_t bw = options->BandwidthBurst;
109  if (options->RelayBandwidthBurst > 0 && bw > options->RelayBandwidthBurst)
110  bw = options->RelayBandwidthBurst;
111  /* config_ensure_bandwidth_cap() makes sure that this cast can't overflow. */
112  return (uint32_t)bw;
113 }
114 
115 /** Warn for every Extended ORPort port in <b>ports</b> that is on a
116  * publicly routable address. */
117 void
118 port_warn_nonlocal_ext_orports(const smartlist_t *ports, const char *portname)
119 {
120  SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
121  if (port->type != CONN_TYPE_EXT_OR_LISTENER)
122  continue;
123  if (port->is_unix_addr)
124  continue;
125  /* XXX maybe warn even if address is RFC1918? */
126  if (!tor_addr_is_internal(&port->addr, 1)) {
127  log_warn(LD_CONFIG, "You specified a public address '%s' for %sPort. "
128  "This is not advised; this address is supposed to only be "
129  "exposed on localhost so that your pluggable transport "
130  "proxies can connect to it.",
131  fmt_addrport(&port->addr, port->port), portname);
132  }
133  } SMARTLIST_FOREACH_END(port);
134 }
135 
136 /**
137  * Return a static buffer describing the port number in @a port, which may
138  * CFG_AUTO_PORT.
139  **/
140 static const char *
142 {
143  static char buf[16];
144  if (port == CFG_AUTO_PORT) {
145  return "auto";
146  } else {
147  tor_snprintf(buf, sizeof(buf), "%d", port);
148  return buf;
149  }
150 }
151 
152 /** Return a static buffer containing the human readable logging string that
153  * describes the given port object. */
154 static const char *
156 {
157  IF_BUG_ONCE(!port) {
158  return "<null port>";
159  }
160 
161  static char buf[256];
162  const char *type, *addr;
163 
164  switch (port->type) {
166  type = "OR";
167  break;
169  type = "Dir";
170  break;
172  type = "ExtOR";
173  break;
174  default:
175  type = "";
176  break;
177  }
178 
179  if (port->explicit_addr) {
180  addr = fmt_and_decorate_addr(&port->addr);
181  } else {
182  addr = "";
183  }
184 
185  tor_snprintf(buf, sizeof(buf), "%sPort %s%s%s",
186  type, addr, (strlen(addr) > 0) ? ":" : "",
187  describe_portnum(port->port));
188  return buf;
189 }
190 
191 /** Attempt to find duplicate ORPort that would be superseded by another and
192  * remove them from the given ports list. This is possible if we have for
193  * instance:
194  *
195  * ORPort 9050
196  * ORPort [4242::1]:9050
197  *
198  * First one binds to both v4 and v6 address but second one is specific to an
199  * address superseding the global bind one.
200  *
201  * The following is O(n^2) but it is done at bootstrap or config reload and
202  * the list is not very long usually. */
203 STATIC void
205 {
206  /* First we'll decide what to remove, then we'll remove it. */
207  bool *removing = tor_calloc(smartlist_len(ports), sizeof(bool));
208 
209  for (int i = 0; i < smartlist_len(ports); ++i) {
210  const port_cfg_t *current = smartlist_get(ports, i);
211  if (removing[i]) {
212  continue;
213  }
214 
215  /* Skip non ORPorts. */
216  if (current->type != CONN_TYPE_OR_LISTENER) {
217  continue;
218  }
219 
220  for (int j = 0; j < smartlist_len(ports); ++j) {
221  const port_cfg_t *next = smartlist_get(ports, j);
222 
223  /* Avoid comparing the same object. */
224  if (current == next) {
225  continue;
226  }
227  if (removing[j]) {
228  continue;
229  }
230  /* Same address family and same port number, we have a match. */
231  if (!current->explicit_addr && next->explicit_addr &&
232  tor_addr_family(&current->addr) == tor_addr_family(&next->addr) &&
233  current->port == next->port) {
234  /* Remove current because next is explicitly set. */
235  removing[i] = true;
236  char *next_str = tor_strdup(describe_relay_port(next));
237  log_warn(LD_CONFIG, "Configuration port %s superseded by %s",
238  describe_relay_port(current), next_str);
239  tor_free(next_str);
240  }
241  }
242  }
243 
244  /* Iterate over array in reverse order to keep indices valid. */
245  for (int i = smartlist_len(ports)-1; i >= 0; --i) {
246  tor_assert(i < smartlist_len(ports));
247  if (removing[i]) {
248  port_cfg_t *current = smartlist_get(ports, i);
249  smartlist_del_keeporder(ports, i);
250  port_cfg_free(current);
251  }
252  }
253 
254  tor_free(removing);
255 }
256 
257 /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
258  * consistency and warn as appropriate. On Unix-based OSes, set
259  * *<b>n_low_ports_out</b> to the number of sub-1024 ports we will be
260  * binding, and warn if we may be unable to re-bind after hibernation. */
261 static int
263  const or_options_t *options,
264  int *n_low_ports_out)
265 {
266  if (BUG(!ports))
267  return -1;
268 
269  if (BUG(!options))
270  return -1;
271 
272  if (BUG(!n_low_ports_out))
273  return -1;
274 
275  int n_orport_advertised = 0;
276  int n_orport_advertised_ipv4 = 0;
277  int n_orport_listeners = 0;
278  int n_dirport_advertised = 0;
279  int n_dirport_listeners = 0;
280  int n_low_port = 0;
281  int r = 0;
282 
283  /* Remove possible duplicate ORPorts before inspecting the list. */
285 
286  SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
287  if (port->type == CONN_TYPE_DIR_LISTENER) {
288  if (! port->server_cfg.no_advertise)
289  ++n_dirport_advertised;
290  if (! port->server_cfg.no_listen)
291  ++n_dirport_listeners;
292  } else if (port->type == CONN_TYPE_OR_LISTENER) {
293  if (! port->server_cfg.no_advertise) {
294  ++n_orport_advertised;
295  if (port_binds_ipv4(port))
296  ++n_orport_advertised_ipv4;
297  }
298  if (! port->server_cfg.no_listen)
299  ++n_orport_listeners;
300  } else {
301  continue;
302  }
303 #ifndef _WIN32
304  if (!port->server_cfg.no_listen && port->port < 1024)
305  ++n_low_port;
306 #endif
307  } SMARTLIST_FOREACH_END(port);
308 
309  if (n_orport_advertised && !n_orport_listeners) {
310  log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
311  "listening on one.");
312  r = -1;
313  }
314  if (n_orport_listeners && !n_orport_advertised) {
315  log_warn(LD_CONFIG, "We are listening on an ORPort, but not advertising "
316  "any ORPorts. This will keep us from building a %s "
317  "descriptor, and make us impossible to use.",
318  options->BridgeRelay ? "bridge" : "router");
319  r = -1;
320  }
321  if (n_dirport_advertised && !n_dirport_listeners) {
322  log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
323  "listening on one.");
324  r = -1;
325  }
326  if (n_dirport_advertised > 1) {
327  log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
328  r = -1;
329  }
330  if (n_orport_advertised && !n_orport_advertised_ipv4 &&
331  !options->BridgeRelay) {
332  log_warn(LD_CONFIG, "Configured public relay to listen only on an IPv6 "
333  "address. Tor needs to listen on an IPv4 address too.");
334  r = -1;
335  }
336 
337  if (n_low_port && options->AccountingMax &&
338  (!have_capability_support() || options->KeepBindCapabilities == 0)) {
339  const char *extra = "";
340  if (options->KeepBindCapabilities == 0 && have_capability_support())
341  extra = ", and you have disabled KeepBindCapabilities.";
342  log_warn(LD_CONFIG,
343  "You have set AccountingMax to use hibernation. You have also "
344  "chosen a low DirPort or OrPort%s."
345  "This combination can make Tor stop "
346  "working when it tries to re-attach the port after a period of "
347  "hibernation. Please choose a different port or turn off "
348  "hibernation unless you know this combination will work on your "
349  "platform.", extra);
350  }
351 
352  if (n_low_ports_out)
353  *n_low_ports_out = n_low_port;
354 
355  return r;
356 }
357 
358 /** Parse all relay ports from <b>options</b>. On success, add parsed ports to
359  * <b>ports</b>, and return 0. On failure, set *<b>msg</b> to a newly
360  * allocated string describing the problem, and return -1.
361  **/
362 int
364  char **msg,
365  smartlist_t *ports_out,
366  int *have_low_ports_out)
367 {
368  int retval = -1;
369  smartlist_t *ports = smartlist_new();
370  int n_low_ports = 0;
371 
372  if (BUG(!options))
373  goto err;
374 
375  if (BUG(!msg))
376  goto err;
377 
378  if (BUG(!ports_out))
379  goto err;
380 
381  if (BUG(!have_low_ports_out))
382  goto err;
383 
384  if (options->ClientOnly) {
385  retval = 0;
386  goto err;
387  }
388 
389  if (port_parse_config(ports,
390  options->ORPort_lines,
391  "OR", CONN_TYPE_OR_LISTENER,
392  "0.0.0.0", 0,
393  CL_PORT_SERVER_OPTIONS) < 0) {
394  *msg = tor_strdup("Invalid ORPort configuration");
395  goto err;
396  }
397  if (port_parse_config(ports,
398  options->ORPort_lines,
399  "OR", CONN_TYPE_OR_LISTENER,
400  "[::]", 0,
401  CL_PORT_SERVER_OPTIONS) < 0) {
402  *msg = tor_strdup("Invalid ORPort configuration");
403  goto err;
404  }
405  if (port_parse_config(ports,
406  options->ExtORPort_lines,
407  "ExtOR", CONN_TYPE_EXT_OR_LISTENER,
408  "127.0.0.1", 0,
409  CL_PORT_SERVER_OPTIONS|CL_PORT_WARN_NONLOCAL) < 0) {
410  *msg = tor_strdup("Invalid ExtORPort configuration");
411  goto err;
412  }
413  if (port_parse_config(ports,
414  options->DirPort_lines,
415  "Dir", CONN_TYPE_DIR_LISTENER,
416  "0.0.0.0", 0,
417  CL_PORT_SERVER_OPTIONS) < 0) {
418  *msg = tor_strdup("Invalid DirPort configuration");
419  goto err;
420  }
421 
422  if (check_and_prune_server_ports(ports, options, &n_low_ports) < 0) {
423  *msg = tor_strdup("Misconfigured server ports");
424  goto err;
425  }
426 
427  smartlist_add_all(ports_out, ports);
428  smartlist_free(ports);
429  ports = NULL;
430  retval = 0;
431 
432  err:
433  if (*have_low_ports_out < 0)
434  *have_low_ports_out = (n_low_ports > 0);
435  if (ports) {
436  SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
437  smartlist_free(ports);
438  }
439  return retval;
440 }
441 
442 /** Update the relay *Port_set values in <b>options</b> from <b>ports</b>. */
443 void
445  const smartlist_t *ports)
446 {
447  if (BUG(!options))
448  return;
449 
450  if (BUG(!ports))
451  return;
452 
453  if (options->ClientOnly)
454  return;
455 
456  /* Update the relay *Port_set options. The !! here is to force a boolean
457  * out of an integer. */
458  options->ORPort_set =
460  options->DirPort_set =
462  options->ExtORPort_set =
464 }
465 
466 /**
467  * Legacy validation function, which checks that the current OS is usable in
468  * relay mode, if options is set to a relay mode.
469  *
470  * Warns about OSes with potential issues. Does not set *<b>msg</b>.
471  * Always returns 0.
472  */
473 int
475  or_options_t *options,
476  char **msg)
477 {
478  (void)old_options;
479 
480  if (BUG(!options))
481  return -1;
482 
483  if (BUG(!msg))
484  return -1;
485 
486  if (!server_mode(options))
487  return 0;
488 
489  const char *uname = get_uname();
490 
491  if (!strcmpstart(uname, "Windows 95") ||
492  !strcmpstart(uname, "Windows 98") ||
493  !strcmpstart(uname, "Windows Me")) {
494  log_warn(LD_CONFIG, "Tor is running as a server, but you are "
495  "running %s; this probably won't work. See "
496  "https://www.torproject.org/docs/faq.html#BestOSForRelay "
497  "for details.", uname);
498  }
499 
500  return 0;
501 }
502 
503 /**
504  * Legacy validation/normalization function for the relay info options.
505  * Uses old_options as the previous options.
506  *
507  * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
508  * on error.
509  */
510 int
512  or_options_t *options,
513  char **msg)
514 {
515  (void)old_options;
516 
517  if (BUG(!options))
518  return -1;
519 
520  if (BUG(!msg))
521  return -1;
522 
523  if (options->Nickname == NULL) {
524  if (server_mode(options)) {
525  options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
526  }
527  } else {
528  if (!is_legal_nickname(options->Nickname)) {
529  tor_asprintf(msg,
530  "Nickname '%s', nicknames must be between 1 and 19 characters "
531  "inclusive, and must contain only the characters [a-zA-Z0-9].",
532  options->Nickname);
533  return -1;
534  }
535  }
536 
537  if (server_mode(options) && !options->ContactInfo) {
538  log_warn(LD_CONFIG,
539  "Your ContactInfo config option is not set. Please strongly "
540  "consider setting it, so we can contact you if your relay is "
541  "misconfigured, end-of-life, or something else goes wrong. "
542  "It is also possible that your relay might get rejected from "
543  "the network due to a missing valid contact address.");
544  }
545 
546  const char *ContactInfo = options->ContactInfo;
547  if (ContactInfo && !string_is_utf8(ContactInfo, strlen(ContactInfo)))
548  REJECT("ContactInfo config option must be UTF-8.");
549 
550  return 0;
551 }
552 
553 /** Parse an authority type from <b>options</b>->PublishServerDescriptor
554  * and write it to <b>options</b>->PublishServerDescriptor_. Treat "1"
555  * as "v3" unless BridgeRelay is 1, in which case treat it as "bridge".
556  * Treat "0" as "".
557  * Return 0 on success or -1 if not a recognized authority type (in which
558  * case the value of PublishServerDescriptor_ is undefined). */
559 static int
561 {
562  smartlist_t *list = options->PublishServerDescriptor;
563  dirinfo_type_t *auth = &options->PublishServerDescriptor_;
564  *auth = NO_DIRINFO;
565  if (!list) /* empty list, answer is none */
566  return 0;
567  SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
568  if (!strcasecmp(string, "v1"))
569  log_warn(LD_CONFIG, "PublishServerDescriptor v1 has no effect, because "
570  "there are no v1 directory authorities anymore.");
571  else if (!strcmp(string, "1"))
572  if (options->BridgeRelay)
573  *auth |= BRIDGE_DIRINFO;
574  else
575  *auth |= V3_DIRINFO;
576  else if (!strcasecmp(string, "v2"))
577  log_warn(LD_CONFIG, "PublishServerDescriptor v2 has no effect, because "
578  "there are no v2 directory authorities anymore.");
579  else if (!strcasecmp(string, "v3"))
580  *auth |= V3_DIRINFO;
581  else if (!strcasecmp(string, "bridge"))
582  *auth |= BRIDGE_DIRINFO;
583  else if (!strcasecmp(string, "hidserv"))
584  log_warn(LD_CONFIG,
585  "PublishServerDescriptor hidserv is invalid. See "
586  "PublishHidServDescriptors.");
587  else if (!strcasecmp(string, "") || !strcmp(string, "0"))
588  /* no authority */;
589  else
590  return -1;
591  } SMARTLIST_FOREACH_END(string);
592  return 0;
593 }
594 
595 /**
596  * Validate the configured bridge distribution method from a BridgeDistribution
597  * config line.
598  *
599  * The input <b>bd</b>, is a string taken from the BridgeDistribution config
600  * line (if present). If the option wasn't set, return 0 immediately. The
601  * BridgeDistribution option is then validated. Currently valid, recognised
602  * options are:
603  *
604  * - "none"
605  * - "any"
606  * - "https"
607  * - "email"
608  * - "moat"
609  *
610  * If the option string is unrecognised, a warning will be logged and 0 is
611  * returned. If the option string contains an invalid character, -1 is
612  * returned.
613  **/
614 STATIC int
616 {
617  if (bd == NULL)
618  return 0;
619 
620  const char *RECOGNIZED[] = {
621  "none", "any", "https", "email", "moat"
622  };
623  unsigned i;
624  for (i = 0; i < ARRAY_LENGTH(RECOGNIZED); ++i) {
625  if (!strcasecmp(bd, RECOGNIZED[i]))
626  return 0;
627  }
628 
629  const char *cp = bd;
630  // Method = (KeywordChar | "_") +
631  while (TOR_ISALNUM(*cp) || *cp == '-' || *cp == '_')
632  ++cp;
633 
634  if (*cp == 0) {
635  log_warn(LD_CONFIG, "Unrecognized BridgeDistribution value %s. I'll "
636  "assume you know what you are doing...", escaped(bd));
637  return 0; // we reached the end of the string; all is well
638  } else {
639  return -1; // we found a bad character in the string.
640  }
641 }
642 
643 /**
644  * Legacy validation/normalization function for the bridge relay options.
645  * Uses old_options as the previous options.
646  *
647  * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
648  * on error.
649  */
650 int
652  or_options_t *options,
653  char **msg)
654 {
655  (void)old_options;
656 
657  if (BUG(!options))
658  return -1;
659 
660  if (BUG(!msg))
661  return -1;
662 
663  if (compute_publishserverdescriptor(options) < 0) {
664  tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
665  return -1;
666  }
667 
668  if ((options->BridgeRelay
670  && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
671  REJECT("Bridges are not supposed to publish router descriptors to the "
672  "directory authorities. Please correct your "
673  "PublishServerDescriptor line.");
674  }
675 
676  if (options->BridgeDistribution) {
677  if (!options->BridgeRelay) {
678  REJECT("You set BridgeDistribution, but you didn't set BridgeRelay!");
679  }
681  REJECT("Invalid BridgeDistribution value.");
682  }
683  }
684 
685  if (options->PublishServerDescriptor)
686  SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
687  if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
688  if (smartlist_len(options->PublishServerDescriptor) > 1) {
689  COMPLAIN("You have passed a list of multiple arguments to the "
690  "PublishServerDescriptor option that includes 0 or 1. "
691  "0 or 1 should only be used as the sole argument. "
692  "This configuration will be rejected in a future release.");
693  break;
694  }
695  });
696 
697  return 0;
698 }
699 
700 /**
701  * Legacy validation/normalization function for the relay padding options.
702  * Uses old_options as the previous options.
703  *
704  * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
705  * on error.
706  */
707 int
709  or_options_t *options,
710  char **msg)
711 {
712  (void)old_options;
713 
714  if (BUG(!options))
715  return -1;
716 
717  if (BUG(!msg))
718  return -1;
719 
720  if (!server_mode(options))
721  return 0;
722 
723  if (options->ConnectionPadding != -1) {
724  REJECT("Relays must use 'auto' for the ConnectionPadding setting.");
725  }
726 
727  if (options->ReducedConnectionPadding != 0) {
728  REJECT("Relays cannot set ReducedConnectionPadding. ");
729  }
730 
731  if (options->CircuitPadding == 0) {
732  REJECT("Relays cannot set CircuitPadding to 0. ");
733  }
734 
735  if (options->ReducedCircuitPadding == 1) {
736  REJECT("Relays cannot set ReducedCircuitPadding. ");
737  }
738 
739  return 0;
740 }
741 
742 /**
743  * Legacy validation/normalization function for the relay bandwidth options.
744  * Uses old_options as the previous options.
745  *
746  * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
747  * on error.
748  */
749 int
751  or_options_t *options,
752  char **msg)
753 {
754  (void)old_options;
755 
756  if (BUG(!options))
757  return -1;
758 
759  if (BUG(!msg))
760  return -1;
761 
762  /* 31851: the tests expect us to validate bandwidths, even when we are not
763  * in relay mode. */
765  "MaxAdvertisedBandwidth", msg) < 0)
766  return -1;
768  "RelayBandwidthRate", msg) < 0)
769  return -1;
771  "RelayBandwidthBurst", msg) < 0)
772  return -1;
774  "PerConnBWRate", msg) < 0)
775  return -1;
777  "PerConnBWBurst", msg) < 0)
778  return -1;
779 
780  if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
781  options->RelayBandwidthBurst = options->RelayBandwidthRate;
782  if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
783  options->RelayBandwidthRate = options->RelayBandwidthBurst;
784 
785  if (server_mode(options)) {
786  const unsigned required_min_bw =
787  public_server_mode(options) ?
788  RELAY_REQUIRED_MIN_BANDWIDTH : BRIDGE_REQUIRED_MIN_BANDWIDTH;
789  const char * const optbridge =
790  public_server_mode(options) ? "" : "bridge ";
791  if (options->BandwidthRate < required_min_bw) {
792  tor_asprintf(msg,
793  "BandwidthRate is set to %d bytes/second. "
794  "For %sservers, it must be at least %u.",
795  (int)options->BandwidthRate, optbridge,
796  required_min_bw);
797  return -1;
798  } else if (options->MaxAdvertisedBandwidth <
799  required_min_bw/2) {
800  tor_asprintf(msg,
801  "MaxAdvertisedBandwidth is set to %d bytes/second. "
802  "For %sservers, it must be at least %u.",
803  (int)options->MaxAdvertisedBandwidth, optbridge,
804  required_min_bw/2);
805  return -1;
806  }
807  if (options->RelayBandwidthRate &&
808  options->RelayBandwidthRate < required_min_bw) {
809  tor_asprintf(msg,
810  "RelayBandwidthRate is set to %d bytes/second. "
811  "For %sservers, it must be at least %u.",
812  (int)options->RelayBandwidthRate, optbridge,
813  required_min_bw);
814  return -1;
815  }
816  }
817 
818  /* 31851: the tests expect us to validate bandwidths, even when we are not
819  * in relay mode. */
820  if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
821  REJECT("RelayBandwidthBurst must be at least equal "
822  "to RelayBandwidthRate.");
823 
824  /* if they set relaybandwidth* really high but left bandwidth*
825  * at the default, raise the defaults. */
826  if (options->RelayBandwidthRate > options->BandwidthRate)
827  options->BandwidthRate = options->RelayBandwidthRate;
828  if (options->RelayBandwidthBurst > options->BandwidthBurst)
829  options->BandwidthBurst = options->RelayBandwidthBurst;
830 
831  return 0;
832 }
833 
834 /**
835  * Legacy validation/normalization function for the relay bandwidth accounting
836  * options. Uses old_options as the previous options.
837  *
838  * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
839  * on error.
840  */
841 int
843  or_options_t *options,
844  char **msg)
845 {
846  (void)old_options;
847 
848  if (BUG(!options))
849  return -1;
850 
851  if (BUG(!msg))
852  return -1;
853 
854  /* 31851: the tests expect us to validate accounting, even when we are not
855  * in relay mode. */
856  if (accounting_parse_options(options, 1)<0)
857  REJECT("Failed to parse accounting options. See logs for details.");
858 
859  if (options->AccountingMax) {
860  if (options->RendConfigLines && server_mode(options)) {
861  log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
862  "ORPort is risky: your hidden service(s) and your public "
863  "address will all turn off at the same time, which may alert "
864  "observers that they are being run by the same party.");
865  } else if (config_count_key(options->RendConfigLines,
866  "HiddenServiceDir") > 1) {
867  log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
868  "risky: they will all turn off at the same time, which may "
869  "alert observers that they are being run by the same party.");
870  }
871  }
872 
873  options->AccountingRule = ACCT_MAX;
874  if (options->AccountingRule_option) {
875  if (!strcmp(options->AccountingRule_option, "sum"))
876  options->AccountingRule = ACCT_SUM;
877  else if (!strcmp(options->AccountingRule_option, "max"))
878  options->AccountingRule = ACCT_MAX;
879  else if (!strcmp(options->AccountingRule_option, "in"))
880  options->AccountingRule = ACCT_IN;
881  else if (!strcmp(options->AccountingRule_option, "out"))
882  options->AccountingRule = ACCT_OUT;
883  else
884  REJECT("AccountingRule must be 'sum', 'max', 'in', or 'out'");
885  }
886 
887  return 0;
888 }
889 
890 /** Verify whether lst is a list of strings containing valid-looking
891  * comma-separated nicknames, or NULL. Will normalise <b>lst</b> to prefix '$'
892  * to any nickname or fingerprint that needs it. Also splits comma-separated
893  * list elements into multiple elements. Return 0 on success.
894  * Warn and return -1 on failure.
895  */
896 static int
898  const config_line_t *lst, const char *name,
899  char **msg)
900 {
901  if (!lst)
902  return 0;
903 
904  config_line_t *new_nicknames = NULL;
905  config_line_t **new_nicknames_next = &new_nicknames;
906 
907  const config_line_t *cl;
908  for (cl = lst; cl; cl = cl->next) {
909  const char *line = cl->value;
910  if (!line)
911  continue;
912 
913  int valid_line = 1;
914  smartlist_t *sl = smartlist_new();
915  smartlist_split_string(sl, line, ",",
916  SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
917  SMARTLIST_FOREACH_BEGIN(sl, char *, s)
918  {
919  char *normalized = NULL;
921  // check if first char is dollar
922  if (s[0] != '$') {
923  // Try again but with a dollar symbol prepended
924  char *prepended;
925  tor_asprintf(&prepended, "$%s", s);
926 
927  if (is_legal_nickname_or_hexdigest(prepended)) {
928  // The nickname is valid when it's prepended, set it as the
929  // normalized version
930  normalized = prepended;
931  } else {
932  // Still not valid, free and fallback to error message
933  tor_free(prepended);
934  }
935  }
936 
937  if (!normalized) {
938  tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
939  valid_line = 0;
940  break;
941  }
942  } else {
943  normalized = tor_strdup(s);
944  }
945 
946  config_line_t *next = tor_malloc_zero(sizeof(*next));
947  next->key = tor_strdup(cl->key);
948  next->value = normalized;
949  next->next = NULL;
950 
951  *new_nicknames_next = next;
952  new_nicknames_next = &next->next;
953  } SMARTLIST_FOREACH_END(s);
954 
955  SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
956  smartlist_free(sl);
957 
958  if (!valid_line) {
959  config_free_lines(new_nicknames);
960  return -1;
961  }
962  }
963 
964  *normalized_out = new_nicknames;
965 
966  return 0;
967 }
968 
969 #define ONE_MEGABYTE (UINT64_C(1) << 20)
970 
971 /* If we have less than 300 MB suggest disabling dircache */
972 #define DIRCACHE_MIN_MEM_MB 300
973 #define DIRCACHE_MIN_MEM_BYTES (DIRCACHE_MIN_MEM_MB*ONE_MEGABYTE)
974 #define STRINGIFY(val) #val
975 
976 /** Create a warning message for emitting if we are a dircache but may not have
977  * enough system memory, or if we are not a dircache but probably should be.
978  * Return -1 when a message is returned in *msg*, else return 0. */
979 STATIC int
980 have_enough_mem_for_dircache(const or_options_t *options, size_t total_mem,
981  char **msg)
982 {
983  *msg = NULL;
984  /* XXX We should possibly be looking at MaxMemInQueues here
985  * unconditionally. Or we should believe total_mem unconditionally. */
986  if (total_mem == 0) {
987  if (get_total_system_memory(&total_mem) < 0) {
988  total_mem = options->MaxMemInQueues >= SIZE_MAX ?
989  SIZE_MAX : (size_t)options->MaxMemInQueues;
990  }
991  }
992  if (options->DirCache) {
993  if (total_mem < DIRCACHE_MIN_MEM_BYTES) {
994  if (options->BridgeRelay) {
995  tor_asprintf(msg, "Running a Bridge with less than %d MB of memory "
996  "is not recommended.", DIRCACHE_MIN_MEM_MB);
997  } else {
998  tor_asprintf(msg, "Being a directory cache (default) with less than "
999  "%d MB of memory is not recommended and may consume "
1000  "most of the available resources. Consider disabling "
1001  "this functionality by setting the DirCache option "
1002  "to 0.", DIRCACHE_MIN_MEM_MB);
1003  }
1004  }
1005  } else {
1006  if (total_mem >= DIRCACHE_MIN_MEM_BYTES) {
1007  *msg = tor_strdup("DirCache is disabled and we are configured as a "
1008  "relay. We will not become a Guard.");
1009  }
1010  }
1011  return *msg == NULL ? 0 : -1;
1012 }
1013 #undef STRINGIFY
1014 
1015 /**
1016  * Legacy validation/normalization function for the relay mode options.
1017  * Uses old_options as the previous options.
1018  *
1019  * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
1020  * on error.
1021  */
1022 int
1024  or_options_t *options,
1025  char **msg)
1026 {
1027  (void)old_options;
1028 
1029  if (BUG(!options))
1030  return -1;
1031 
1032  if (BUG(!msg))
1033  return -1;
1034 
1035  if (server_mode(options) && options->RendConfigLines)
1036  log_warn(LD_CONFIG,
1037  "Tor is currently configured as a relay and a hidden service. "
1038  "That's not very secure: you should probably run your hidden service "
1039  "in a separate Tor process, at least -- see "
1040  "https://bugs.torproject.org/tpo/core/tor/8742.");
1041 
1042  if (options->BridgeRelay && options->DirPort_set) {
1043  log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
1044  "DirPort");
1045  config_free_lines(options->DirPort_lines);
1046  options->DirPort_lines = NULL;
1047  options->DirPort_set = 0;
1048  }
1049 
1050  if (options->DirPort_set && !options->DirCache) {
1051  REJECT("DirPort configured but DirCache disabled. DirPort requires "
1052  "DirCache.");
1053  }
1054 
1055  if (options->BridgeRelay && !options->DirCache) {
1056  REJECT("We're a bridge but DirCache is disabled. BridgeRelay requires "
1057  "DirCache.");
1058  }
1059 
1060  if (options->BridgeRelay == 1 && ! options->ORPort_set)
1061  REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
1062  "combination.");
1063 
1064  if (server_mode(options)) {
1065  char *dircache_msg = NULL;
1066  if (have_enough_mem_for_dircache(options, 0, &dircache_msg)) {
1067  log_warn(LD_CONFIG, "%s", dircache_msg);
1068  tor_free(dircache_msg);
1069  }
1070  }
1071 
1072  if (options->MyFamily_lines && options->BridgeRelay) {
1073  log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
1074  "supported: it can reveal bridge fingerprints to censors. "
1075  "You should also make sure you aren't listing this bridge's "
1076  "fingerprint in any other MyFamily.");
1077  }
1078  if (options->MyFamily_lines && !options->ContactInfo) {
1079  log_warn(LD_CONFIG, "MyFamily is set but ContactInfo is not configured. "
1080  "ContactInfo should always be set when MyFamily option is too.");
1081  }
1082  if (normalize_nickname_list(&options->MyFamily,
1083  options->MyFamily_lines, "MyFamily", msg))
1084  return -1;
1085 
1086  if (options->ConstrainedSockets) {
1087  if (options->DirPort_set) {
1088  /* Providing cached directory entries while system TCP buffers are scarce
1089  * will exacerbate the socket errors. Suggest that this be disabled. */
1090  COMPLAIN("You have requested constrained socket buffers while also "
1091  "serving directory entries via DirPort. It is strongly "
1092  "suggested that you disable serving directory requests when "
1093  "system TCP buffer resources are scarce.");
1094  }
1095  }
1096 
1097  return 0;
1098 }
1099 
1100 /**
1101  * Legacy validation/normalization function for the relay testing options
1102  * in options. Uses old_options as the previous options.
1103  *
1104  * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
1105  * on error.
1106  */
1107 int
1109  or_options_t *options,
1110  char **msg)
1111 {
1112  (void)old_options;
1113 
1114  if (BUG(!options))
1115  return -1;
1116 
1117  if (BUG(!msg))
1118  return -1;
1119 
1120  if (options->SigningKeyLifetime < options->TestingSigningKeySlop*2)
1121  REJECT("SigningKeyLifetime is too short.");
1122  if (options->TestingLinkCertLifetime < options->TestingAuthKeySlop*2)
1123  REJECT("LinkCertLifetime is too short.");
1124  if (options->TestingAuthKeyLifetime < options->TestingLinkKeySlop*2)
1125  REJECT("TestingAuthKeyLifetime is too short.");
1126 
1127  return 0;
1128 }
1129 
1130 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
1131  * will require us to rotate the CPU and DNS workers; else return 0. */
1132 static int
1134  const or_options_t *new_options)
1135 {
1136  YES_IF_CHANGED_STRING(DataDirectory);
1137  YES_IF_CHANGED_INT(NumCPUs);
1138  YES_IF_CHANGED_LINELIST(ORPort_lines);
1139  YES_IF_CHANGED_BOOL(ServerDNSSearchDomains);
1140  YES_IF_CHANGED_BOOL(SafeLogging_);
1141  YES_IF_CHANGED_BOOL(ClientOnly);
1142  YES_IF_CHANGED_BOOL(LogMessageDomains);
1143  YES_IF_CHANGED_LINELIST(Logs);
1144 
1145  if (server_mode(old_options) != server_mode(new_options) ||
1146  public_server_mode(old_options) != public_server_mode(new_options) ||
1147  dir_server_mode(old_options) != dir_server_mode(new_options))
1148  return 1;
1149 
1150  /* Nothing that changed matters. */
1151  return 0;
1152 }
1153 
1154 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
1155  * will require us to generate a new descriptor; else return 0. */
1156 static int
1158  const or_options_t *new_options)
1159 {
1160  /* XXX We can be smarter here. If your DirPort isn't being
1161  * published and you just turned it off, no need to republish. Etc. */
1162 
1163  YES_IF_CHANGED_STRING(DataDirectory);
1164  YES_IF_CHANGED_STRING(Nickname);
1165  YES_IF_CHANGED_LINELIST(Address);
1166  YES_IF_CHANGED_LINELIST(ExitPolicy);
1167  YES_IF_CHANGED_BOOL(ExitRelay);
1168  YES_IF_CHANGED_BOOL(ExitPolicyRejectPrivate);
1169  YES_IF_CHANGED_BOOL(ExitPolicyRejectLocalInterfaces);
1170  YES_IF_CHANGED_BOOL(IPv6Exit);
1171  YES_IF_CHANGED_LINELIST(ORPort_lines);
1172  YES_IF_CHANGED_LINELIST(DirPort_lines);
1173  YES_IF_CHANGED_LINELIST(DirPort_lines);
1174  YES_IF_CHANGED_BOOL(ClientOnly);
1175  YES_IF_CHANGED_BOOL(DisableNetwork);
1176  YES_IF_CHANGED_BOOL(PublishServerDescriptor_);
1177  YES_IF_CHANGED_STRING(ContactInfo);
1178  YES_IF_CHANGED_STRING(BridgeDistribution);
1179  YES_IF_CHANGED_LINELIST(MyFamily);
1180  YES_IF_CHANGED_STRING(AccountingStart);
1181  YES_IF_CHANGED_INT(AccountingMax);
1182  YES_IF_CHANGED_INT(AccountingRule);
1183  YES_IF_CHANGED_BOOL(DirCache);
1184  YES_IF_CHANGED_BOOL(AssumeReachable);
1185 
1186  if (relay_get_effective_bwrate(old_options) !=
1187  relay_get_effective_bwrate(new_options) ||
1188  relay_get_effective_bwburst(old_options) !=
1189  relay_get_effective_bwburst(new_options) ||
1190  public_server_mode(old_options) != public_server_mode(new_options))
1191  return 1;
1192 
1193  return 0;
1194 }
1195 
1196 /** Fetch the active option list, and take relay actions based on it. All of
1197  * the things we do should survive being done repeatedly. If present,
1198  * <b>old_options</b> contains the previous value of the options.
1199  *
1200  * Return 0 if all goes well, return -1 if it's time to die.
1201  *
1202  * Note: We haven't moved all the "act on new configuration" logic
1203  * into the options_act* functions yet. Some is still in do_hup() and other
1204  * places.
1205  */
1206 int
1207 options_act_relay(const or_options_t *old_options)
1208 {
1209  const or_options_t *options = get_options();
1210 
1211  const int transition_affects_workers =
1212  old_options && options_transition_affects_workers(old_options, options);
1213 
1214  /* We want to reinit keys as needed before we do much of anything else:
1215  keys are important, and other things can depend on them. */
1216  if (transition_affects_workers ||
1217  (authdir_mode_v3(options) && (!old_options ||
1218  !authdir_mode_v3(old_options)))) {
1219  if (init_keys() < 0) {
1220  log_warn(LD_BUG,"Error initializing keys; exiting");
1221  return -1;
1222  }
1223  }
1224 
1225  if (server_mode(options)) {
1226  static int cdm_initialized = 0;
1227  if (cdm_initialized == 0) {
1228  cdm_initialized = 1;
1229  consdiffmgr_configure(NULL);
1231  }
1232  }
1233 
1234  /* Check for transitions that need action. */
1235  if (old_options) {
1236  if (transition_affects_workers) {
1237  log_info(LD_GENERAL,
1238  "Worker-related options changed. Rotating workers.");
1239  const int server_mode_turned_on =
1240  server_mode(options) && !server_mode(old_options);
1241  const int dir_server_mode_turned_on =
1242  dir_server_mode(options) && !dir_server_mode(old_options);
1243 
1244  if (server_mode_turned_on || dir_server_mode_turned_on) {
1245  cpu_init();
1246  }
1247 
1248  if (server_mode_turned_on) {
1249  ip_address_changed(0);
1250  }
1252  }
1253  }
1254 
1255  return 0;
1256 }
1257 
1258 /** Fetch the active option list, and take relay accounting actions based on
1259  * it. All of the things we do should survive being done repeatedly. If
1260  * present, <b>old_options</b> contains the previous value of the options.
1261  *
1262  * Return 0 if all goes well, return -1 if it's time to die.
1263  *
1264  * Note: We haven't moved all the "act on new configuration" logic
1265  * into the options_act* functions yet. Some is still in do_hup() and other
1266  * places.
1267  */
1268 int
1270 {
1271  (void)old_options;
1272 
1273  const or_options_t *options = get_options();
1274 
1275  /* Set up accounting */
1276  if (accounting_parse_options(options, 0)<0) {
1277  // LCOV_EXCL_START
1278  log_warn(LD_BUG,"Error in previously validated accounting options");
1279  return -1;
1280  // LCOV_EXCL_STOP
1281  }
1282  if (accounting_is_enabled(options))
1283  configure_accounting(time(NULL));
1284 
1285  return 0;
1286 }
1287 
1288 /** Fetch the active option list, and take relay bandwidth actions based on
1289  * it. All of the things we do should survive being done repeatedly. If
1290  * present, <b>old_options</b> contains the previous value of the options.
1291  *
1292  * Return 0 if all goes well, return -1 if it's time to die.
1293  *
1294  * Note: We haven't moved all the "act on new configuration" logic
1295  * into the options_act* functions yet. Some is still in do_hup() and other
1296  * places.
1297  */
1298 int
1300 {
1301  const or_options_t *options = get_options();
1302 
1303  /* Check for transitions that need action. */
1304  if (old_options) {
1305  if (options->PerConnBWRate != old_options->PerConnBWRate ||
1306  options->PerConnBWBurst != old_options->PerConnBWBurst)
1308 
1309  if (options->RelayBandwidthRate != old_options->RelayBandwidthRate ||
1310  options->RelayBandwidthBurst != old_options->RelayBandwidthBurst)
1311  connection_bucket_adjust(options);
1312  }
1313 
1314  return 0;
1315 }
1316 
1317 /** Fetch the active option list, and take bridge statistics actions based on
1318  * it. All of the things we do should survive being done repeatedly. If
1319  * present, <b>old_options</b> contains the previous value of the options.
1320  *
1321  * Return 0 if all goes well, return -1 if it's time to die.
1322  *
1323  * Note: We haven't moved all the "act on new configuration" logic
1324  * into the options_act* functions yet. Some is still in do_hup() and other
1325  * places.
1326  */
1327 int
1329 {
1330  const or_options_t *options = get_options();
1331 
1332 /* How long should we delay counting bridge stats after becoming a bridge?
1333  * We use this so we don't count clients who used our bridge thinking it is
1334  * a relay. If you change this, don't forget to change the log message
1335  * below. It's 4 hours (the time it takes to stop being used by clients)
1336  * plus some extra time for clock skew. */
1337 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1338 
1339  /* Check for transitions that need action. */
1340  if (old_options) {
1341  if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1342  int was_relay = 0;
1343  if (options->BridgeRelay) {
1344  time_t int_start = time(NULL);
1345  if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
1346  int_start += RELAY_BRIDGE_STATS_DELAY;
1347  was_relay = 1;
1348  }
1349  geoip_bridge_stats_init(int_start);
1350  log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
1351  "GeoIP stats interval%s.", was_relay ? " in 6 "
1352  "hours from now" : "");
1353  } else {
1355  log_info(LD_GENERAL, "We are no longer acting as a bridge. "
1356  "Forgetting GeoIP stats.");
1357  }
1358  }
1359  }
1360 
1361  return 0;
1362 }
1363 
1364 /** Fetch the active option list, and take relay statistics actions based on
1365  * it. All of the things we do should survive being done repeatedly. If
1366  * present, <b>old_options</b> contains the previous value of the options.
1367  *
1368  * Sets <b>*print_notice_out</b> if we enabled stats, and need to print
1369  * a stats log using options_act_relay_stats_msg().
1370  *
1371  * If loading the GeoIP file failed, sets DirReqStatistics and
1372  * EntryStatistics to 0. This breaks the normalization/act ordering
1373  * introduced in 29211.
1374  *
1375  * Return 0 if all goes well, return -1 if it's time to die.
1376  *
1377  * Note: We haven't moved all the "act on new configuration" logic
1378  * into the options_act* functions yet. Some is still in do_hup() and other
1379  * places.
1380  */
1381 int
1383  bool *print_notice_out)
1384 {
1385  if (BUG(!print_notice_out))
1386  return -1;
1387 
1388  or_options_t *options = get_options_mutable();
1389 
1390  if (options->CellStatistics || options->DirReqStatistics ||
1391  options->EntryStatistics || options->ExitPortStatistics ||
1392  options->ConnDirectionStatistics ||
1393  options->HiddenServiceStatistics) {
1394  time_t now = time(NULL);
1395  int print_notice = 0;
1396 
1397  if ((!old_options || !old_options->CellStatistics) &&
1398  options->CellStatistics) {
1400  print_notice = 1;
1401  }
1402  if ((!old_options || !old_options->DirReqStatistics) &&
1403  options->DirReqStatistics) {
1404  if (geoip_is_loaded(AF_INET)) {
1406  print_notice = 1;
1407  } else {
1408  /* disable statistics collection since we have no geoip file */
1409  /* 29211: refactor to avoid the normalisation/act inversion */
1410  options->DirReqStatistics = 0;
1411  if (options->ORPort_set)
1412  log_notice(LD_CONFIG, "Configured to measure directory request "
1413  "statistics, but no GeoIP database found. "
1414  "Please specify a GeoIP database using the "
1415  "GeoIPFile option.");
1416  }
1417  }
1418  if ((!old_options || !old_options->EntryStatistics) &&
1419  options->EntryStatistics && !should_record_bridge_info(options)) {
1420  /* If we get here, we've started recording bridge info when we didn't
1421  * do so before. Note that "should_record_bridge_info()" will
1422  * always be false at this point, because of the earlier block
1423  * that cleared EntryStatistics when public_server_mode() was false.
1424  * We're leaving it in as defensive programming. */
1425  if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
1427  print_notice = 1;
1428  } else {
1429  options->EntryStatistics = 0;
1430  log_notice(LD_CONFIG, "Configured to measure entry node "
1431  "statistics, but no GeoIP database found. "
1432  "Please specify a GeoIP database using the "
1433  "GeoIPFile option.");
1434  }
1435  }
1436  if ((!old_options || !old_options->ExitPortStatistics) &&
1437  options->ExitPortStatistics) {
1439  print_notice = 1;
1440  }
1441  if ((!old_options || !old_options->ConnDirectionStatistics) &&
1442  options->ConnDirectionStatistics) {
1443  conn_stats_init(now);
1444  }
1445  if ((!old_options || !old_options->HiddenServiceStatistics) &&
1446  options->HiddenServiceStatistics) {
1447  log_info(LD_CONFIG, "Configured to measure hidden service statistics.");
1449  }
1450  if (print_notice)
1451  *print_notice_out = 1;
1452  }
1453 
1454  /* If we used to have statistics enabled but we just disabled them,
1455  stop gathering them. */
1456  if (old_options && old_options->CellStatistics &&
1457  !options->CellStatistics)
1459  if (old_options && old_options->DirReqStatistics &&
1460  !options->DirReqStatistics)
1462  if (old_options && old_options->EntryStatistics &&
1463  !options->EntryStatistics)
1465  if (old_options && old_options->HiddenServiceStatistics &&
1466  !options->HiddenServiceStatistics)
1468  if (old_options && old_options->ExitPortStatistics &&
1469  !options->ExitPortStatistics)
1471  if (old_options && old_options->ConnDirectionStatistics &&
1472  !options->ConnDirectionStatistics)
1474 
1475  return 0;
1476 }
1477 
1478 /** Print a notice about relay/dirauth stats being enabled. */
1479 void
1481 {
1482  log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
1483  "the *-stats files that will first be written to the "
1484  "data directory in 24 hours from now.");
1485 }
1486 
1487 /** Fetch the active option list, and take relay descriptor actions based on
1488  * it. All of the things we do should survive being done repeatedly. If
1489  * present, <b>old_options</b> contains the previous value of the options.
1490  *
1491  * Return 0 if all goes well, return -1 if it's time to die.
1492  *
1493  * Note: We haven't moved all the "act on new configuration" logic
1494  * into the options_act* functions yet. Some is still in do_hup() and other
1495  * places.
1496  */
1497 int
1499 {
1500  const or_options_t *options = get_options();
1501 
1502  /* Since our options changed, we might need to regenerate and upload our
1503  * server descriptor.
1504  */
1505  if (!old_options ||
1506  options_transition_affects_descriptor(old_options, options))
1507  mark_my_descriptor_dirty("config change");
1508 
1509  return 0;
1510 }
1511 
1512 /** Fetch the active option list, and take relay DoS actions based on
1513  * it. All of the things we do should survive being done repeatedly. If
1514  * present, <b>old_options</b> contains the previous value of the options.
1515  *
1516  * Return 0 if all goes well, return -1 if it's time to die.
1517  *
1518  * Note: We haven't moved all the "act on new configuration" logic
1519  * into the options_act* functions yet. Some is still in do_hup() and other
1520  * places.
1521  */
1522 int
1524 {
1525  const or_options_t *options = get_options();
1526 
1527  /* DoS mitigation subsystem only applies to public relay. */
1528  if (public_server_mode(options)) {
1529  /* If we are configured as a relay, initialize the subsystem. Even on HUP,
1530  * this is safe to call as it will load data from the current options
1531  * or/and the consensus. */
1532  dos_init();
1533  } else if (old_options && public_server_mode(old_options)) {
1534  /* Going from relay to non relay, clean it up. */
1535  dos_free_all();
1536  }
1537 
1538  return 0;
1539 }
1540 
1541 /** Fetch the active option list, and take dirport actions based on
1542  * it. All of the things we do should survive being done repeatedly. If
1543  * present, <b>old_options</b> contains the previous value of the options.
1544  *
1545  * Return 0 if all goes well, return -1 if it's time to die.
1546  *
1547  * Note: We haven't moved all the "act on new configuration" logic
1548  * into the options_act* functions yet. Some is still in do_hup() and other
1549  * places.
1550  */
1551 int
1553 {
1554  (void)old_options;
1555 
1556  const or_options_t *options = get_options();
1557 
1558  if (!public_server_mode(options))
1559  return 0;
1560 
1561  /* Load the webpage we're going to serve every time someone asks for '/' on
1562  our DirPort. */
1564  if (options->DirPortFrontPage) {
1566  read_file_to_str(options->DirPortFrontPage, 0, NULL);
1568  log_warn(LD_CONFIG,
1569  "DirPortFrontPage file '%s' not found. Continuing anyway.",
1570  options->DirPortFrontPage);
1571  }
1572  }
1573 
1574  return 0;
1575 }
check_and_prune_server_ports
static int check_and_prune_server_ports(smartlist_t *ports, const or_options_t *options, int *n_low_ports_out)
Definition: relay_config.c:262
selftest.h
Header file for selftest.c.
routermode.h
Header file for routermode.c.
or_options_t::ORPort_lines
struct config_line_t * ORPort_lines
Definition: or_options_st.h:144
tor_free
#define tor_free(p)
Definition: malloc.h:52
smartlist_split_string
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)
Definition: smartlist_split.c:37
tor_addr_family
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition: address.h:187
or_options_t::TestingAuthKeyLifetime
int TestingAuthKeyLifetime
Definition: or_options_st.h:940
options_validate_relay_bandwidth
int options_validate_relay_bandwidth(const or_options_t *old_options, or_options_t *options, char **msg)
Definition: relay_config.c:750
or_options_t::BandwidthRate
uint64_t BandwidthRate
Definition: or_options_st.h:393
name
const char * name
Definition: config.c:2443
config_count_key
int config_count_key(const config_line_t *a, const char *key)
Definition: confline.c:302
options_act_relay_bandwidth
int options_act_relay_bandwidth(const or_options_t *old_options)
Definition: relay_config.c:1299
compute_publishserverdescriptor
static int compute_publishserverdescriptor(or_options_t *options)
Definition: relay_config.c:560
connection_bucket_adjust
void connection_bucket_adjust(const or_options_t *options)
Definition: connection.c:3735
smartlist.h
Header for smartlist.c.
or_options_t::BridgeRelay
int BridgeRelay
Definition: or_options_st.h:248
MOCK_IMPL
#define MOCK_IMPL(rv, funcname, arglist)
Definition: testsupport.h:133
geoip_bridge_stats_term
void geoip_bridge_stats_term(void)
Definition: geoip_stats.c:1072
or_options_t::TestingAuthKeySlop
int TestingAuthKeySlop
Definition: or_options_st.h:947
or_options_t::DirReqStatistics
int DirReqStatistics
Definition: or_options_st.h:629
or_options_t::ConnDirectionStatistics
int ConnDirectionStatistics
Definition: or_options_st.h:635
port_cfg_st.h
Listener port configuration structure.
geoip_dirreq_stats_term
void geoip_dirreq_stats_term(void)
Definition: geoip_stats.c:957
tor_assert
#define tor_assert(expr)
Definition: util_bug.h:102
confmgt.h
Header for confmgt.c.
LD_BUG
#define LD_BUG
Definition: log.h:86
or_options_t::PublishServerDescriptor_
dirinfo_type_t PublishServerDescriptor_
Definition: or_options_st.h:283
LD_GENERAL
#define LD_GENERAL
Definition: log.h:62
port_cfg_t::addr
tor_addr_t addr
Definition: port_cfg_st.h:20
geoip_is_loaded
int geoip_is_loaded(sa_family_t family)
Definition: geoip.c:458
smartlist_add_all
void smartlist_add_all(smartlist_t *s1, const smartlist_t *s2)
Definition: smartlist_core.c:125
smartlist_del_keeporder
void smartlist_del_keeporder(smartlist_t *sl, int idx)
Definition: smartlist_core.c:228
rep_hist_exit_stats_term
void rep_hist_exit_stats_term(void)
Definition: rephist.c:1012
uname.h
Header for uname.c.
rep_hist_exit_stats_init
void rep_hist_exit_stats_init(time_t now)
Definition: rephist.c:991
accounting_parse_options
int accounting_parse_options(const or_options_t *options, int validate_only)
Definition: hibernate.c:190
CFG_AUTO_PORT
#define CFG_AUTO_PORT
Definition: or.h:1008
is_legal_nickname
int is_legal_nickname(const char *s)
Definition: nickname.c:19
or_options_t::PerConnBWRate
uint64_t PerConnBWRate
Definition: or_options_st.h:403
options_validate_publish_server
int options_validate_publish_server(const or_options_t *old_options, or_options_t *options, char **msg)
Definition: relay_config.c:651
smartlist_new
smartlist_t * smartlist_new(void)
Definition: smartlist_core.c:26
or_options_t::PublishServerDescriptor
struct smartlist_t * PublishServerDescriptor
Definition: or_options_st.h:281
tor_snprintf
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
consdiffmgr_validate
int consdiffmgr_validate(void)
Definition: consdiffmgr.c:858
options_validate_relay_padding
int options_validate_relay_padding(const or_options_t *old_options, or_options_t *options, char **msg)
Definition: relay_config.c:708
conn_stats_terminate
void conn_stats_terminate(void)
Definition: connstats.c:136
cpuworkers_rotate_keyinfo
void cpuworkers_rotate_keyinfo(void)
Definition: cpuworker.c:188
SMARTLIST_FOREACH
#define SMARTLIST_FOREACH(sl, type, var, cmd)
Definition: smartlist_foreach.h:112
init_keys
int init_keys(void)
Definition: router.c:928
rep_hist_buffer_stats_init
void rep_hist_buffer_stats_init(time_t now)
Definition: rephist.c:1248
CONN_TYPE_EXT_OR_LISTENER
#define CONN_TYPE_EXT_OR_LISTENER
Definition: connection.h:73
geoip_dirreq_stats_init
void geoip_dirreq_stats_init(time_t now)
Definition: geoip_stats.c:918
options_validate_relay_info
int options_validate_relay_info(const or_options_t *old_options, or_options_t *options, char **msg)
Definition: relay_config.c:511
check_bridge_distribution_setting
STATIC int check_bridge_distribution_setting(const char *bd)
Definition: relay_config.c:615
or_options_t::MyFamily
struct config_line_t * MyFamily
Definition: or_options_st.h:467
or_options_t::MyFamily_lines
struct config_line_t * MyFamily_lines
Definition: or_options_st.h:466
CONN_TYPE_OR_LISTENER
#define CONN_TYPE_OR_LISTENER
Definition: connection.h:41
or_options_t::SigningKeyLifetime
int SigningKeyLifetime
Definition: or_options_st.h:936
geoip_stats.h
Header file for geoip_stats.c.
hibernate.h
Header file for hibernate.c.
rep_hist_buffer_stats_term
void rep_hist_buffer_stats_term(void)
Definition: rephist.c:1340
should_record_bridge_info
int should_record_bridge_info(const or_options_t *options)
Definition: geoip_stats.c:112
options_validate_relay_os
int options_validate_relay_os(const or_options_t *old_options, or_options_t *options, char **msg)
Definition: relay_config.c:474
mainloop.h
Header file for mainloop.c.
get_uname
const char * get_uname(void)
Definition: uname.c:67
or_options_t::TestingSigningKeySlop
int TestingSigningKeySlop
Definition: or_options_st.h:943
relay_config_free_all
void relay_config_free_all(void)
Definition: relay_config.c:84
accounting_is_enabled
int accounting_is_enabled(const or_options_t *options)
Definition: hibernate.c:305
fmt_and_decorate_addr
#define fmt_and_decorate_addr(a)
Definition: address.h:243
geoip.h
Header file for geoip.c.
remove_duplicate_orports
STATIC void remove_duplicate_orports(smartlist_t *ports)
Definition: relay_config.c:204
or_options_t::AccountingRule_option
char * AccountingRule_option
Definition: or_options_st.h:501
or_options_t::RelayBandwidthBurst
uint64_t RelayBandwidthBurst
Definition: or_options_st.h:401
relay_get_effective_bwburst
uint32_t relay_get_effective_bwburst(const or_options_t *options)
Definition: relay_config.c:106
options_act_relay_stats_msg
void options_act_relay_stats_msg(void)
Definition: relay_config.c:1480
options_act_relay_dir
int options_act_relay_dir(const or_options_t *old_options)
Definition: relay_config.c:1552
consdiffmgr_configure
void consdiffmgr_configure(const consdiff_cfg_t *cfg)
Definition: consdiffmgr.c:834
relay_config.h
Header for feature/relay/relay_config.c.
conn_stats_init
void conn_stats_init(time_t now)
Definition: connstats.c:30
port_cfg_t::port
int port
Definition: port_cfg_st.h:21
options_act_bridge_stats
int options_act_bridge_stats(const or_options_t *old_options)
Definition: relay_config.c:1328
string_is_utf8
int string_is_utf8(const char *str, size_t len)
Definition: util_string.c:516
rep_hist_hs_stats_term
void rep_hist_hs_stats_term(void)
Definition: rephist.c:1785
rep_hist_hs_stats_init
void rep_hist_hs_stats_init(time_t now)
Definition: rephist.c:1756
have_capability_support
int have_capability_support(void)
Definition: setuid.c:149
or_options_t::EntryStatistics
int EntryStatistics
Definition: or_options_st.h:644
or_options_t::ReducedConnectionPadding
int ReducedConnectionPadding
Definition: or_options_st.h:260
escaped
const char * escaped(const char *s)
Definition: escape.c:126
strcmpstart
int strcmpstart(const char *s1, const char *s2)
Definition: util_string.c:215
options_act_relay_desc
int options_act_relay_desc(const or_options_t *old_options)
Definition: relay_config.c:1498
meminfo.h
Header for meminfo.c.
authmode.h
Header file for directory authority mode.
port_cfg_t
Definition: port_cfg_st.h:19
get_connection_array
smartlist_t * get_connection_array(void)
Definition: mainloop.c:453
or_options_t::HiddenServiceStatistics
int HiddenServiceStatistics
Definition: or_options_st.h:652
or_options_t::TestingLinkKeySlop
int TestingLinkKeySlop
Definition: or_options_st.h:945
get_options_mutable
or_options_t * get_options_mutable(void)
Definition: config.c:919
or_options_t::ConstrainedSockets
int ConstrainedSockets
Definition: or_options_st.h:336
options_act_relay_dos
int options_act_relay_dos(const or_options_t *old_options)
Definition: relay_config.c:1523
predict_ports.h
Header file for predict_ports.c.
LD_CONFIG
#define LD_CONFIG
Definition: log.h:68
dir_server_mode
int dir_server_mode(const or_options_t *options)
Definition: routermode.c:23
describe_portnum
static const char * describe_portnum(int port)
Definition: relay_config.c:141
options_act_relay
int options_act_relay(const or_options_t *old_options)
Definition: relay_config.c:1207
ARRAY_LENGTH
#define ARRAY_LENGTH(x)
Definition: compat_compiler.h:222
or_options_t::ExtORPort_lines
struct config_line_t * ExtORPort_lines
Definition: or_options_st.h:146
port_parse_ports_relay
int port_parse_ports_relay(or_options_t *options, char **msg, smartlist_t *ports_out, int *have_low_ports_out)
Definition: relay_config.c:363
options_validate_relay_mode
int options_validate_relay_mode(const or_options_t *old_options, or_options_t *options, char **msg)
Definition: relay_config.c:1023
get_options
const or_options_t * get_options(void)
Definition: config.c:928
bool_eq
#define bool_eq(a, b)
Definition: logic.h:16
or_options_t::PerConnBWBurst
uint64_t PerConnBWBurst
Definition: or_options_st.h:404
geoip_bridge_stats_init
void geoip_bridge_stats_init(time_t now)
Definition: geoip_stats.c:1064
or_options_t::ReducedCircuitPadding
int ReducedCircuitPadding
Definition: or_options_st.h:277
fmt_addrport
const char * fmt_addrport(const tor_addr_t *addr, uint16_t port)
Definition: address.c:1199
or_options_t::KeepBindCapabilities
int KeepBindCapabilities
Definition: or_options_st.h:966
config_ensure_bandwidth_cap
int config_ensure_bandwidth_cap(uint64_t *value, const char *desc, char **msg)
Definition: config.c:2953
or_options_t::TestingLinkCertLifetime
int TestingLinkCertLifetime
Definition: or_options_st.h:938
is_legal_nickname_or_hexdigest
int is_legal_nickname_or_hexdigest(const char *s)
Definition: nickname.c:31
IF_BUG_ONCE
#define IF_BUG_ONCE(cond)
Definition: util_bug.h:246
port_warn_nonlocal_ext_orports
void port_warn_nonlocal_ext_orports(const smartlist_t *ports, const char *portname)
Definition: relay_config.c:118
connstats.h
Header for feature/stats/connstats.c.
config_lines_eq
int config_lines_eq(const config_line_t *a, const config_line_t *b)
Definition: confline.c:287
connection.h
Header file for connection.c.
or_options_t::MaxMemInQueues
uint64_t MaxMemInQueues
Definition: or_options_st.h:179
confline.h
Header for confline.c.
or_options_t::ExitPortStatistics
int ExitPortStatistics
Definition: or_options_st.h:632
V3_DIRINFO
@ V3_DIRINFO
Definition: or.h:908
or_options_t::RelayBandwidthRate
uint64_t RelayBandwidthRate
Definition: or_options_st.h:399
or_options_t::ClientOnly
int ClientOnly
Definition: or_options_st.h:258
nickname.h
Header file for nickname.c.
ip_address_changed
void ip_address_changed(int on_client_conn)
Definition: mainloop.c:2283
UNNAMED_ROUTER_NICKNAME
#define UNNAMED_ROUTER_NICKNAME
Definition: or.h:561
server_mode
int server_mode(const or_options_t *options)
Definition: routermode.c:34
dirinfo_type_t
dirinfo_type_t
Definition: or.h:905
cpuworker.h
Header file for cpuworker.c.
connection_or_update_token_buckets
void connection_or_update_token_buckets(smartlist_t *conns, const or_options_t *options)
Definition: connection_or.c:838
or_options_t::MaxAdvertisedBandwidth
uint64_t MaxAdvertisedBandwidth
Definition: or_options_st.h:397
tor_asprintf
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
SMARTLIST_FOREACH_BEGIN
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
Definition: smartlist_foreach.h:78
or_options_t::ContactInfo
char * ContactInfo
Definition: or_options_st.h:413
geoip_entry_stats_init
void geoip_entry_stats_init(time_t now)
Definition: geoip_stats.c:1320
public_server_mode
int public_server_mode(const or_options_t *options)
Definition: routermode.c:43
port_count_real_listeners
int port_count_real_listeners(const smartlist_t *ports, int listenertype, int count_sockets)
Definition: config.c:6379
options_validate_relay_accounting
int options_validate_relay_accounting(const or_options_t *old_options, or_options_t *options, char **msg)
Definition: relay_config.c:842
or_options_t::Nickname
char * Nickname
Definition: or_options_st.h:79
or_options_t::AccountingMax
uint64_t AccountingMax
Definition: or_options_st.h:493
or_options_t::RendConfigLines
struct config_line_t * RendConfigLines
Definition: or_options_st.h:406
normalize_nickname_list
static int normalize_nickname_list(config_line_t **normalized_out, const config_line_t *lst, const char *name, char **msg)
Definition: relay_config.c:897
or_options_t::ConnectionPadding
int ConnectionPadding
Definition: or_options_st.h:266
options_validate_relay_testing
int options_validate_relay_testing(const or_options_t *old_options, or_options_t *options, char **msg)
Definition: relay_config.c:1108
port_parse_config
int port_parse_config(smartlist_t *out, const config_line_t *ports, const char *portname, int listener_type, const char *defaultaddr, int defaultport, const unsigned flags)
Definition: config.c:5905
config_line_t
Definition: confline.h:29
cpu_init
void cpu_init(void)
Definition: cpuworker.c:83
config.h
Header file for config.c.
geoip_entry_stats_term
void geoip_entry_stats_term(void)
Definition: geoip_stats.c:1336
BRIDGE_DIRINFO
@ BRIDGE_DIRINFO
Definition: or.h:910
relay_get_dirportfrontpage
const char * relay_get_dirportfrontpage(void)
Definition: relay_config.c:75
describe_relay_port
static const char * describe_relay_port(const port_cfg_t *port)
Definition: relay_config.c:155
relay_get_effective_bwrate
uint32_t relay_get_effective_bwrate(const or_options_t *options)
Definition: relay_config.c:92
or_options_t
Definition: or_options_st.h:45
or_options_t::DirPort_lines
struct config_line_t * DirPort_lines
Definition: or_options_st.h:172
port_update_port_set_relay
void port_update_port_set_relay(or_options_t *options, const smartlist_t *ports)
Definition: relay_config.c:444
or_options_t::DirCache
int DirCache
Definition: or_options_st.h:578
or_options_t::CellStatistics
int CellStatistics
Definition: or_options_st.h:638
STATIC
#define STATIC
Definition: testsupport.h:32
options_act_relay_accounting
int options_act_relay_accounting(const or_options_t *old_options)
Definition: relay_config.c:1269
dns.h
Header file for dns.c.
get_total_system_memory
int get_total_system_memory(size_t *mem_out)
Definition: meminfo.c:151
or_options_t::BandwidthBurst
uint64_t BandwidthBurst
Definition: or_options_st.h:395
have_enough_mem_for_dircache
STATIC int have_enough_mem_for_dircache(const or_options_t *options, size_t total_mem, char **msg)
Definition: relay_config.c:980
options_transition_affects_descriptor
static int options_transition_affects_descriptor(const or_options_t *old_options, const or_options_t *new_options)
Definition: relay_config.c:1157
configure_accounting
void configure_accounting(time_t now)
Definition: hibernate.c:430
or_options_t::CircuitPadding
int CircuitPadding
Definition: or_options_st.h:271
global_dirfrontpagecontents
static char * global_dirfrontpagecontents
Definition: relay_config.c:50
or_options_t::DirPortFrontPage
char * DirPortFrontPage
Definition: or_options_st.h:598
smartlist_t
Definition: smartlist_core.h:26
port_cfg_t::type
uint8_t type
Definition: port_cfg_st.h:23
CONN_TYPE_DIR_LISTENER
#define CONN_TYPE_DIR_LISTENER
Definition: connection.h:53
rephist.h
Header file for rephist.c.
mark_my_descriptor_dirty
void mark_my_descriptor_dirty(const char *reason)
Definition: router.c:2545
options_transition_affects_workers
static int options_transition_affects_workers(const or_options_t *old_options, const or_options_t *new_options)
Definition: relay_config.c:1133
connection_or.h
Header file for connection_or.c.
options_act_relay_stats
int options_act_relay_stats(const or_options_t *old_options, bool *print_notice_out)
Definition: relay_config.c:1382
setuid.h
Header for setuid.c.
or.h
Master header file for Tor-specific functionality.
consdiffmgr.h
Header for consdiffmgr.c.
or_options_t::BridgeDistribution
char * BridgeDistribution
Definition: or_options_st.h:224