config: Really ignore non ORPorts when removing duplicates
[tor.git] / src / feature / relay / relay_config.c
blobe8c29fa7ed9f958aff2ef255334b37236a309e0d
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 */
7 /**
8 * @file relay_config.c
9 * @brief Code to interpret the user's configuration of Tor's relay module.
10 **/
12 #include "orconfig.h"
13 #define RELAY_CONFIG_PRIVATE
14 #include "feature/relay/relay_config.h"
16 #include "lib/encoding/confline.h"
17 #include "lib/confmgt/confmgt.h"
19 #include "lib/container/smartlist.h"
20 #include "lib/geoip/geoip.h"
21 #include "lib/meminfo/meminfo.h"
22 #include "lib/osinfo/uname.h"
23 #include "lib/process/setuid.h"
25 /* Required for dirinfo_type_t in or_options_t */
26 #include "core/or/or.h"
27 #include "app/config/config.h"
29 #include "core/mainloop/connection.h"
30 #include "core/mainloop/cpuworker.h"
31 #include "core/mainloop/mainloop.h"
32 #include "core/or/connection_or.h"
33 #include "core/or/port_cfg_st.h"
35 #include "feature/hibernate/hibernate.h"
36 #include "feature/nodelist/nickname.h"
37 #include "feature/stats/geoip_stats.h"
38 #include "feature/stats/predict_ports.h"
39 #include "feature/stats/connstats.h"
40 #include "feature/stats/rephist.h"
42 #include "feature/dirauth/authmode.h"
44 #include "feature/dircache/consdiffmgr.h"
45 #include "feature/relay/dns.h"
46 #include "feature/relay/routermode.h"
47 #include "feature/relay/selftest.h"
49 /** Contents of most recently read DirPortFrontPage file. */
50 static char *global_dirfrontpagecontents = NULL;
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 */
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;
73 /** Return the contents of our frontpage string, or NULL if not configured. */
74 MOCK_IMPL(const char*,
75 relay_get_dirportfrontpage, (void))
77 return global_dirfrontpagecontents;
80 /** Release all memory and resources held by global relay configuration
81 * structures.
83 void
84 relay_config_free_all(void)
86 tor_free(global_dirfrontpagecontents);
89 /** Return the bandwidthrate that we are going to report to the authorities
90 * based on the config options. */
91 uint32_t
92 relay_get_effective_bwrate(const or_options_t *options)
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;
103 /** Return the bandwidthburst that we are going to report to the authorities
104 * based on the config options. */
105 uint32_t
106 relay_get_effective_bwburst(const or_options_t *options)
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;
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)
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);
133 } SMARTLIST_FOREACH_END(port);
137 * Return a static buffer describing the port number in @a port, which may
138 * CFG_AUTO_PORT.
140 static const char *
141 describe_portnum(int port)
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;
152 /** Return a static buffer containing the human readable logging string that
153 * describes the given port object. */
154 static const char *
155 describe_relay_port(const port_cfg_t *port)
157 IF_BUG_ONCE(!port) {
158 return "<null port>";
161 static char buf[256];
162 const char *type, *addr;
164 switch (port->type) {
165 case CONN_TYPE_OR_LISTENER:
166 type = "OR";
167 break;
168 case CONN_TYPE_DIR_LISTENER:
169 type = "Dir";
170 break;
171 case CONN_TYPE_EXT_OR_LISTENER:
172 type = "ExtOR";
173 break;
174 default:
175 type = "";
176 break;
179 if (port->explicit_addr) {
180 addr = fmt_and_decorate_addr(&port->addr);
181 } else {
182 addr = "";
185 tor_snprintf(buf, sizeof(buf), "%sPort %s%s%s",
186 type, addr, (strlen(addr) > 0) ? ":" : "",
187 describe_portnum(port->port));
188 return buf;
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:
195 * ORPort 9050
196 * ORPort [4242::1]:9050
198 * First one binds to both v4 and v6 address but second one is specific to an
199 * address superseding the global bind one.
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
204 remove_duplicate_orports(smartlist_t *ports)
206 /* First we'll decide what to remove, then we'll remove it. */
207 bool *removing = tor_calloc(smartlist_len(ports), sizeof(bool));
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;
215 /* Skip non ORPorts. */
216 if (current->type != CONN_TYPE_OR_LISTENER) {
217 continue;
220 for (int j = 0; j < smartlist_len(ports); ++j) {
221 const port_cfg_t *next = smartlist_get(ports, j);
223 /* Avoid comparing the same object. */
224 if (current == next) {
225 continue;
227 if (removing[j]) {
228 continue;
230 /* Skip non ORPorts. */
231 if (next->type != CONN_TYPE_OR_LISTENER) {
232 continue;
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);
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);
259 tor_free(removing);
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
267 check_and_prune_server_ports(smartlist_t *ports,
268 const or_options_t *options,
269 int *n_low_ports_out)
271 if (BUG(!ports))
272 return -1;
274 if (BUG(!options))
275 return -1;
277 if (BUG(!n_low_ports_out))
278 return -1;
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;
288 /* Remove possible duplicate ORPorts before inspecting the list. */
289 remove_duplicate_orports(ports);
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;
303 if (! port->server_cfg.no_listen)
304 ++n_orport_listeners;
305 } else {
306 continue;
308 #ifndef _WIN32
309 if (!port->server_cfg.no_listen && port->port < 1024)
310 ++n_low_port;
311 #endif
312 } SMARTLIST_FOREACH_END(port);
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;
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;
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;
331 if (n_dirport_advertised > 1) {
332 log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
333 r = -1;
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;
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);
357 if (n_low_ports_out)
358 *n_low_ports_out = n_low_port;
360 return r;
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.
368 port_parse_ports_relay(or_options_t *options,
369 char **msg,
370 smartlist_t *ports_out,
371 int *have_low_ports_out)
373 int retval = -1;
374 smartlist_t *ports = smartlist_new();
375 int n_low_ports = 0;
377 if (BUG(!options))
378 goto err;
380 if (BUG(!msg))
381 goto err;
383 if (BUG(!ports_out))
384 goto err;
386 if (BUG(!have_low_ports_out))
387 goto err;
389 if (options->ClientOnly) {
390 retval = 0;
391 goto err;
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;
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;
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;
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;
427 if (check_and_prune_server_ports(ports, options, &n_low_ports) < 0) {
428 *msg = tor_strdup("Misconfigured server ports");
429 goto err;
432 smartlist_add_all(ports_out, ports);
433 smartlist_free(ports);
434 ports = NULL;
435 retval = 0;
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);
444 return retval;
447 /** Update the relay *Port_set values in <b>options</b> from <b>ports</b>. */
448 void
449 port_update_port_set_relay(or_options_t *options,
450 const smartlist_t *ports)
452 if (BUG(!options))
453 return;
455 if (BUG(!ports))
456 return;
458 if (options->ClientOnly)
459 return;
461 /* Update the relay *Port_set options. The !! here is to force a boolean
462 * out of an integer. */
463 options->ORPort_set =
464 !! port_count_real_listeners(ports, CONN_TYPE_OR_LISTENER, 0);
465 options->DirPort_set =
466 !! port_count_real_listeners(ports, CONN_TYPE_DIR_LISTENER, 0);
467 options->ExtORPort_set =
468 !! port_count_real_listeners(ports, CONN_TYPE_EXT_OR_LISTENER, 0);
472 * Legacy validation function, which checks that the current OS is usable in
473 * relay mode, if options is set to a relay mode.
475 * Warns about OSes with potential issues. Does not set *<b>msg</b>.
476 * Always returns 0.
479 options_validate_relay_os(const or_options_t *old_options,
480 or_options_t *options,
481 char **msg)
483 (void)old_options;
485 if (BUG(!options))
486 return -1;
488 if (BUG(!msg))
489 return -1;
491 if (!server_mode(options))
492 return 0;
494 const char *uname = get_uname();
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);
505 return 0;
509 * Legacy validation/normalization function for the relay info options.
510 * Uses old_options as the previous options.
512 * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
513 * on error.
516 options_validate_relay_info(const or_options_t *old_options,
517 or_options_t *options,
518 char **msg)
520 (void)old_options;
522 if (BUG(!options))
523 return -1;
525 if (BUG(!msg))
526 return -1;
528 if (options->Nickname == NULL) {
529 if (server_mode(options)) {
530 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
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;
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.");
551 const char *ContactInfo = options->ContactInfo;
552 if (ContactInfo && !string_is_utf8(ContactInfo, strlen(ContactInfo)))
553 REJECT("ContactInfo config option must be UTF-8.");
555 return 0;
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
565 compute_publishserverdescriptor(or_options_t *options)
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;
601 * Validate the configured bridge distribution method from a BridgeDistribution
602 * config line.
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:
609 * - "none"
610 * - "any"
611 * - "https"
612 * - "email"
613 * - "moat"
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.
619 STATIC int
620 check_bridge_distribution_setting(const char *bd)
622 if (bd == NULL)
623 return 0;
625 const char *RECOGNIZED[] = {
626 "none", "any", "https", "email", "moat"
628 unsigned i;
629 for (i = 0; i < ARRAY_LENGTH(RECOGNIZED); ++i) {
630 if (!strcasecmp(bd, RECOGNIZED[i]))
631 return 0;
634 const char *cp = bd;
635 // Method = (KeywordChar | "_") +
636 while (TOR_ISALNUM(*cp) || *cp == '-' || *cp == '_')
637 ++cp;
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.
649 * Legacy validation/normalization function for the bridge relay options.
650 * Uses old_options as the previous options.
652 * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
653 * on error.
656 options_validate_publish_server(const or_options_t *old_options,
657 or_options_t *options,
658 char **msg)
660 (void)old_options;
662 if (BUG(!options))
663 return -1;
665 if (BUG(!msg))
666 return -1;
668 if (compute_publishserverdescriptor(options) < 0) {
669 tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
670 return -1;
673 if ((options->BridgeRelay
674 || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
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.");
681 if (options->BridgeDistribution) {
682 if (!options->BridgeRelay) {
683 REJECT("You set BridgeDistribution, but you didn't set BridgeRelay!");
685 if (check_bridge_distribution_setting(options->BridgeDistribution) < 0) {
686 REJECT("Invalid BridgeDistribution value.");
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;
702 return 0;
706 * Legacy validation/normalization function for the relay padding options.
707 * Uses old_options as the previous options.
709 * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
710 * on error.
713 options_validate_relay_padding(const or_options_t *old_options,
714 or_options_t *options,
715 char **msg)
717 (void)old_options;
719 if (BUG(!options))
720 return -1;
722 if (BUG(!msg))
723 return -1;
725 if (!server_mode(options))
726 return 0;
728 if (options->ConnectionPadding != -1) {
729 REJECT("Relays must use 'auto' for the ConnectionPadding setting.");
732 if (options->ReducedConnectionPadding != 0) {
733 REJECT("Relays cannot set ReducedConnectionPadding. ");
736 if (options->CircuitPadding == 0) {
737 REJECT("Relays cannot set CircuitPadding to 0. ");
740 if (options->ReducedCircuitPadding == 1) {
741 REJECT("Relays cannot set ReducedCircuitPadding. ");
744 return 0;
748 * Legacy validation/normalization function for the relay bandwidth options.
749 * Uses old_options as the previous options.
751 * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
752 * on error.
755 options_validate_relay_bandwidth(const or_options_t *old_options,
756 or_options_t *options,
757 char **msg)
759 (void)old_options;
761 if (BUG(!options))
762 return -1;
764 if (BUG(!msg))
765 return -1;
767 /* 31851: the tests expect us to validate bandwidths, even when we are not
768 * in relay mode. */
769 if (config_ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
770 "MaxAdvertisedBandwidth", msg) < 0)
771 return -1;
772 if (config_ensure_bandwidth_cap(&options->RelayBandwidthRate,
773 "RelayBandwidthRate", msg) < 0)
774 return -1;
775 if (config_ensure_bandwidth_cap(&options->RelayBandwidthBurst,
776 "RelayBandwidthBurst", msg) < 0)
777 return -1;
778 if (config_ensure_bandwidth_cap(&options->PerConnBWRate,
779 "PerConnBWRate", msg) < 0)
780 return -1;
781 if (config_ensure_bandwidth_cap(&options->PerConnBWBurst,
782 "PerConnBWBurst", msg) < 0)
783 return -1;
785 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
786 options->RelayBandwidthBurst = options->RelayBandwidthRate;
787 if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
788 options->RelayBandwidthRate = options->RelayBandwidthBurst;
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;
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;
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.");
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;
836 return 0;
840 * Legacy validation/normalization function for the relay bandwidth accounting
841 * options. Uses old_options as the previous options.
843 * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
844 * on error.
847 options_validate_relay_accounting(const or_options_t *old_options,
848 or_options_t *options,
849 char **msg)
851 (void)old_options;
853 if (BUG(!options))
854 return -1;
856 if (BUG(!msg))
857 return -1;
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.");
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.");
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'");
892 return 0;
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.
901 static int
902 normalize_nickname_list(config_line_t **normalized_out,
903 const config_line_t *lst, const char *name,
904 char **msg)
906 if (!lst)
907 return 0;
909 config_line_t *new_nicknames = NULL;
910 config_line_t **new_nicknames_next = &new_nicknames;
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;
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)
924 char *normalized = NULL;
925 if (!is_legal_nickname_or_hexdigest(s)) {
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);
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);
942 if (!normalized) {
943 tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
944 valid_line = 0;
945 break;
947 } else {
948 normalized = tor_strdup(s);
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;
956 *new_nicknames_next = next;
957 new_nicknames_next = &next->next;
958 } SMARTLIST_FOREACH_END(s);
960 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
961 smartlist_free(sl);
963 if (!valid_line) {
964 config_free_lines(new_nicknames);
965 return -1;
969 *normalized_out = new_nicknames;
971 return 0;
974 #define ONE_MEGABYTE (UINT64_C(1) << 20)
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
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)
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;
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);
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.");
1016 return *msg == NULL ? 0 : -1;
1018 #undef STRINGIFY
1021 * Legacy validation/normalization function for the relay mode options.
1022 * Uses old_options as the previous options.
1024 * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
1025 * on error.
1028 options_validate_relay_mode(const or_options_t *old_options,
1029 or_options_t *options,
1030 char **msg)
1032 (void)old_options;
1034 if (BUG(!options))
1035 return -1;
1037 if (BUG(!msg))
1038 return -1;
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.");
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;
1055 if (options->DirPort_set && !options->DirCache) {
1056 REJECT("DirPort configured but DirCache disabled. DirPort requires "
1057 "DirCache.");
1060 if (options->BridgeRelay && !options->DirCache) {
1061 REJECT("We're a bridge but DirCache is disabled. BridgeRelay requires "
1062 "DirCache.");
1065 if (options->BridgeRelay == 1 && ! options->ORPort_set)
1066 REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
1067 "combination.");
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);
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.");
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.");
1087 if (normalize_nickname_list(&options->MyFamily,
1088 options->MyFamily_lines, "MyFamily", msg))
1089 return -1;
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.");
1102 return 0;
1106 * Legacy validation/normalization function for the relay testing options
1107 * in options. Uses old_options as the previous options.
1109 * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
1110 * on error.
1113 options_validate_relay_testing(const or_options_t *old_options,
1114 or_options_t *options,
1115 char **msg)
1117 (void)old_options;
1119 if (BUG(!options))
1120 return -1;
1122 if (BUG(!msg))
1123 return -1;
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.");
1132 return 0;
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
1138 options_transition_affects_workers(const or_options_t *old_options,
1139 const or_options_t *new_options)
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);
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;
1155 /* Nothing that changed matters. */
1156 return 0;
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
1162 options_transition_affects_descriptor(const or_options_t *old_options,
1163 const or_options_t *new_options)
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. */
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);
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;
1198 return 0;
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.
1205 * Return 0 if all goes well, return -1 if it's time to die.
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.
1212 options_act_relay(const or_options_t *old_options)
1214 const or_options_t *options = get_options();
1216 const int transition_affects_workers =
1217 old_options && options_transition_affects_workers(old_options, options);
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;
1230 if (server_mode(options)) {
1231 static int cdm_initialized = 0;
1232 if (cdm_initialized == 0) {
1233 cdm_initialized = 1;
1234 consdiffmgr_configure(NULL);
1235 consdiffmgr_validate();
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);
1249 if (server_mode_turned_on || dir_server_mode_turned_on) {
1250 cpu_init();
1253 if (server_mode_turned_on) {
1254 ip_address_changed(0);
1256 cpuworkers_rotate_keyinfo();
1260 return 0;
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.
1267 * Return 0 if all goes well, return -1 if it's time to die.
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.
1274 options_act_relay_accounting(const or_options_t *old_options)
1276 (void)old_options;
1278 const or_options_t *options = get_options();
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
1287 if (accounting_is_enabled(options))
1288 configure_accounting(time(NULL));
1290 return 0;
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.
1297 * Return 0 if all goes well, return -1 if it's time to die.
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.
1304 options_act_relay_bandwidth(const or_options_t *old_options)
1306 const or_options_t *options = get_options();
1308 /* Check for transitions that need action. */
1309 if (old_options) {
1310 if (options->PerConnBWRate != old_options->PerConnBWRate ||
1311 options->PerConnBWBurst != old_options->PerConnBWBurst)
1312 connection_or_update_token_buckets(get_connection_array(), options);
1314 if (options->RelayBandwidthRate != old_options->RelayBandwidthRate ||
1315 options->RelayBandwidthBurst != old_options->RelayBandwidthBurst)
1316 connection_bucket_adjust(options);
1319 return 0;
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.
1326 * Return 0 if all goes well, return -1 if it's time to die.
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.
1333 options_act_bridge_stats(const or_options_t *old_options)
1335 const or_options_t *options = get_options();
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)
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;
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 {
1359 geoip_bridge_stats_term();
1360 log_info(LD_GENERAL, "We are no longer acting as a bridge. "
1361 "Forgetting GeoIP stats.");
1366 return 0;
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.
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().
1376 * If loading the GeoIP file failed, sets DirReqStatistics and
1377 * EntryStatistics to 0. This breaks the normalization/act ordering
1378 * introduced in 29211.
1380 * Return 0 if all goes well, return -1 if it's time to die.
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.
1387 options_act_relay_stats(const or_options_t *old_options,
1388 bool *print_notice_out)
1390 if (BUG(!print_notice_out))
1391 return -1;
1393 or_options_t *options = get_options_mutable();
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;
1402 if ((!old_options || !old_options->CellStatistics) &&
1403 options->CellStatistics) {
1404 rep_hist_buffer_stats_init(now);
1405 print_notice = 1;
1407 if ((!old_options || !old_options->DirReqStatistics) &&
1408 options->DirReqStatistics) {
1409 if (geoip_is_loaded(AF_INET)) {
1410 geoip_dirreq_stats_init(now);
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.");
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)) {
1431 geoip_entry_stats_init(now);
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.");
1441 if ((!old_options || !old_options->ExitPortStatistics) &&
1442 options->ExitPortStatistics) {
1443 rep_hist_exit_stats_init(now);
1444 print_notice = 1;
1446 if ((!old_options || !old_options->ConnDirectionStatistics) &&
1447 options->ConnDirectionStatistics) {
1448 conn_stats_init(now);
1450 if ((!old_options || !old_options->HiddenServiceStatistics) &&
1451 options->HiddenServiceStatistics) {
1452 log_info(LD_CONFIG, "Configured to measure hidden service statistics.");
1453 rep_hist_hs_stats_init(now);
1455 if (print_notice)
1456 *print_notice_out = 1;
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)
1463 rep_hist_buffer_stats_term();
1464 if (old_options && old_options->DirReqStatistics &&
1465 !options->DirReqStatistics)
1466 geoip_dirreq_stats_term();
1467 if (old_options && old_options->EntryStatistics &&
1468 !options->EntryStatistics)
1469 geoip_entry_stats_term();
1470 if (old_options && old_options->HiddenServiceStatistics &&
1471 !options->HiddenServiceStatistics)
1472 rep_hist_hs_stats_term();
1473 if (old_options && old_options->ExitPortStatistics &&
1474 !options->ExitPortStatistics)
1475 rep_hist_exit_stats_term();
1476 if (old_options && old_options->ConnDirectionStatistics &&
1477 !options->ConnDirectionStatistics)
1478 conn_stats_terminate();
1480 return 0;
1483 /** Print a notice about relay/dirauth stats being enabled. */
1484 void
1485 options_act_relay_stats_msg(void)
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.");
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.
1496 * Return 0 if all goes well, return -1 if it's time to die.
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.
1503 options_act_relay_desc(const or_options_t *old_options)
1505 const or_options_t *options = get_options();
1507 /* Since our options changed, we might need to regenerate and upload our
1508 * server descriptor.
1510 if (!old_options ||
1511 options_transition_affects_descriptor(old_options, options))
1512 mark_my_descriptor_dirty("config change");
1514 return 0;
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.
1521 * Return 0 if all goes well, return -1 if it's time to die.
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.
1528 options_act_relay_dos(const or_options_t *old_options)
1530 const or_options_t *options = get_options();
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();
1543 return 0;
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.
1550 * Return 0 if all goes well, return -1 if it's time to die.
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.
1557 options_act_relay_dir(const or_options_t *old_options)
1559 (void)old_options;
1561 const or_options_t *options = get_options();
1563 if (!public_server_mode(options))
1564 return 0;
1566 /* Load the webpage we're going to serve every time someone asks for '/' on
1567 our DirPort. */
1568 tor_free(global_dirfrontpagecontents);
1569 if (options->DirPortFrontPage) {
1570 global_dirfrontpagecontents =
1571 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1572 if (!global_dirfrontpagecontents) {
1573 log_warn(LD_CONFIG,
1574 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1575 options->DirPortFrontPage);
1579 return 0;