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