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