Update copyrights to 2021, using "make update-copyright"
[tor.git] / src / feature / relay / relay_config.c
blobbfc5ac26129ac3f0a01dd5a0fb17cee04786cec0
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 */
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 /** Return true iff port p1 is equal to p2.
193 * This does a field by field comparaison. */
194 static bool
195 port_cfg_eq(const port_cfg_t *p1, const port_cfg_t *p2)
197 bool ret = true;
199 tor_assert(p1);
200 tor_assert(p2);
202 /* Address, port and type. */
203 ret &= tor_addr_eq(&p1->addr, &p2->addr);
204 ret &= (p1->port == p2->port);
205 ret &= (p1->type == p2->type);
207 /* Mode. */
208 ret &= (p1->is_unix_addr == p2->is_unix_addr);
209 ret &= (p1->is_group_writable == p2->is_group_writable);
210 ret &= (p1->is_world_writable == p2->is_world_writable);
211 ret &= (p1->relax_dirmode_check == p2->relax_dirmode_check);
212 ret &= (p1->explicit_addr == p2->explicit_addr);
214 /* Entry config flags. */
215 ret &= tor_memeq(&p1->entry_cfg, &p2->entry_cfg,
216 sizeof(entry_port_cfg_t));
217 /* Server config flags. */
218 ret &= tor_memeq(&p1->server_cfg, &p2->server_cfg,
219 sizeof(server_port_cfg_t));
220 /* Unix address path if any. */
221 ret &= !strcmp(p1->unix_addr, p2->unix_addr);
223 return ret;
226 /** Attempt to find duplicate ORPort that would be superseded by another and
227 * remove them from the given ports list. This is possible if we have for
228 * instance:
230 * ORPort 9050
231 * ORPort [4242::1]:9050
233 * First one binds to both v4 and v6 address but second one is specific to an
234 * address superseding the global bind one.
236 * Another example is this one:
238 * ORPort 9001
239 * ORPort [4242::1]:9002
240 * ORPort [4242::2]:9003
242 * In this case, all IPv4 and IPv6 are kept since we do allow multiple ORPorts
243 * but the published port will be the first explicit one if any to be
244 * published or else the implicit.
246 * The following is O(n^2) but it is done at bootstrap or config reload and
247 * the list is not very long usually. */
248 STATIC void
249 remove_duplicate_orports(smartlist_t *ports)
251 /* First we'll decide what to remove, then we'll remove it. */
252 bool *removing = tor_calloc(smartlist_len(ports), sizeof(bool));
254 for (int i = 0; i < smartlist_len(ports); ++i) {
255 const port_cfg_t *current = smartlist_get(ports, i);
256 if (removing[i]) {
257 continue;
260 /* Skip non ORPorts. */
261 if (current->type != CONN_TYPE_OR_LISTENER) {
262 continue;
265 for (int j = 0; j < smartlist_len(ports); ++j) {
266 const port_cfg_t *next = smartlist_get(ports, j);
268 /* Avoid comparing the same object. */
269 if (current == next) {
270 continue;
272 if (removing[j]) {
273 continue;
275 /* Skip non ORPorts. */
276 if (next->type != CONN_TYPE_OR_LISTENER) {
277 continue;
279 /* Remove duplicates. */
280 if (port_cfg_eq(current, next)) {
281 removing[j] = true;
282 continue;
284 /* Don't compare addresses of different family. */
285 if (tor_addr_family(&current->addr) != tor_addr_family(&next->addr)) {
286 continue;
288 /* At this point, we have a port of the same type and same address
289 * family. Now, we want to avoid comparing addresses that are different
290 * but are both explicit. As an example, these are not duplicates:
292 * ORPort 127.0.0.:9001 NoAdvertise
293 * ORPort 1.2.3.4:9001 NoListen
295 * Any implicit address must be considered for removal since an explicit
296 * one will always supersedes it. */
297 if (!tor_addr_eq(&current->addr, &next->addr) &&
298 current->explicit_addr && next->explicit_addr) {
299 continue;
302 /* Port value is the same so we either have a duplicate or a port that
303 * supersedes another. */
304 if (current->port == next->port) {
305 /* Do not remove the explicit address. As stated before above, we keep
306 * explicit addresses which supersedes implicit ones. */
307 if (!current->explicit_addr && next->explicit_addr) {
308 continue;
310 removing[j] = true;
311 char *next_str = tor_strdup(describe_relay_port(next));
312 log_warn(LD_CONFIG, "Configuration port %s superseded by %s",
313 next_str, describe_relay_port(current));
314 tor_free(next_str);
319 /* Iterate over array in reverse order to keep indices valid. */
320 for (int i = smartlist_len(ports)-1; i >= 0; --i) {
321 tor_assert(i < smartlist_len(ports));
322 if (removing[i]) {
323 port_cfg_t *current = smartlist_get(ports, i);
324 smartlist_del_keeporder(ports, i);
325 port_cfg_free(current);
329 tor_free(removing);
332 /** Given a list of <b>port_cfg_t</b> in <b>ports</b>, check them for internal
333 * consistency and warn as appropriate. On Unix-based OSes, set
334 * *<b>n_low_ports_out</b> to the number of sub-1024 ports we will be
335 * binding, and warn if we may be unable to re-bind after hibernation. */
336 static int
337 check_and_prune_server_ports(smartlist_t *ports,
338 const or_options_t *options,
339 int *n_low_ports_out)
341 if (BUG(!ports))
342 return -1;
344 if (BUG(!options))
345 return -1;
347 if (BUG(!n_low_ports_out))
348 return -1;
350 int n_orport_advertised = 0;
351 int n_orport_advertised_ipv4 = 0;
352 int n_orport_listeners = 0;
353 int n_dirport_advertised = 0;
354 int n_dirport_listeners = 0;
355 int n_low_port = 0;
356 int r = 0;
358 /* Remove possible duplicate ORPorts before inspecting the list. */
359 remove_duplicate_orports(ports);
361 SMARTLIST_FOREACH_BEGIN(ports, const port_cfg_t *, port) {
362 if (port->type == CONN_TYPE_DIR_LISTENER) {
363 if (! port->server_cfg.no_advertise)
364 ++n_dirport_advertised;
365 if (! port->server_cfg.no_listen)
366 ++n_dirport_listeners;
367 } else if (port->type == CONN_TYPE_OR_LISTENER) {
368 if (! port->server_cfg.no_advertise) {
369 ++n_orport_advertised;
370 if (port_binds_ipv4(port))
371 ++n_orport_advertised_ipv4;
373 if (! port->server_cfg.no_listen)
374 ++n_orport_listeners;
375 } else {
376 continue;
378 #ifndef _WIN32
379 if (!port->server_cfg.no_listen && port->port < 1024)
380 ++n_low_port;
381 #endif
382 } SMARTLIST_FOREACH_END(port);
384 if (n_orport_advertised && !n_orport_listeners) {
385 log_warn(LD_CONFIG, "We are advertising an ORPort, but not actually "
386 "listening on one.");
387 r = -1;
389 if (n_orport_listeners && !n_orport_advertised) {
390 log_warn(LD_CONFIG, "We are listening on an ORPort, but not advertising "
391 "any ORPorts. This will keep us from building a %s "
392 "descriptor, and make us impossible to use.",
393 options->BridgeRelay ? "bridge" : "router");
394 r = -1;
396 if (n_dirport_advertised && !n_dirport_listeners) {
397 log_warn(LD_CONFIG, "We are advertising a DirPort, but not actually "
398 "listening on one.");
399 r = -1;
401 if (n_dirport_advertised > 1) {
402 log_warn(LD_CONFIG, "Can't advertise more than one DirPort.");
403 r = -1;
405 if (n_orport_advertised && !n_orport_advertised_ipv4 &&
406 !options->BridgeRelay) {
407 log_warn(LD_CONFIG, "Configured public relay to listen only on an IPv6 "
408 "address. Tor needs to listen on an IPv4 address too.");
409 r = -1;
412 if (n_low_port && options->AccountingMax &&
413 (!have_capability_support() || options->KeepBindCapabilities == 0)) {
414 const char *extra = "";
415 if (options->KeepBindCapabilities == 0 && have_capability_support())
416 extra = ", and you have disabled KeepBindCapabilities.";
417 log_warn(LD_CONFIG,
418 "You have set AccountingMax to use hibernation. You have also "
419 "chosen a low DirPort or OrPort%s."
420 "This combination can make Tor stop "
421 "working when it tries to re-attach the port after a period of "
422 "hibernation. Please choose a different port or turn off "
423 "hibernation unless you know this combination will work on your "
424 "platform.", extra);
427 if (n_low_ports_out)
428 *n_low_ports_out = n_low_port;
430 return r;
433 /** Parse all relay ports from <b>options</b>. On success, add parsed ports to
434 * <b>ports</b>, and return 0. On failure, set *<b>msg</b> to a newly
435 * allocated string describing the problem, and return -1.
438 port_parse_ports_relay(or_options_t *options,
439 char **msg,
440 smartlist_t *ports_out,
441 int *have_low_ports_out)
443 int retval = -1;
444 smartlist_t *ports = smartlist_new();
445 int n_low_ports = 0;
447 if (BUG(!options))
448 goto err;
450 if (BUG(!msg))
451 goto err;
453 if (BUG(!ports_out))
454 goto err;
456 if (BUG(!have_low_ports_out))
457 goto err;
459 if (options->ClientOnly) {
460 retval = 0;
461 goto err;
464 if (port_parse_config(ports,
465 options->ORPort_lines,
466 "OR", CONN_TYPE_OR_LISTENER,
467 "0.0.0.0", 0,
468 CL_PORT_SERVER_OPTIONS) < 0) {
469 *msg = tor_strdup("Invalid ORPort configuration");
470 goto err;
472 if (port_parse_config(ports,
473 options->ORPort_lines,
474 "OR", CONN_TYPE_OR_LISTENER,
475 "[::]", 0,
476 CL_PORT_SERVER_OPTIONS) < 0) {
477 *msg = tor_strdup("Invalid ORPort configuration");
478 goto err;
480 if (port_parse_config(ports,
481 options->ExtORPort_lines,
482 "ExtOR", CONN_TYPE_EXT_OR_LISTENER,
483 "127.0.0.1", 0,
484 CL_PORT_SERVER_OPTIONS|CL_PORT_WARN_NONLOCAL) < 0) {
485 *msg = tor_strdup("Invalid ExtORPort configuration");
486 goto err;
488 if (port_parse_config(ports,
489 options->DirPort_lines,
490 "Dir", CONN_TYPE_DIR_LISTENER,
491 "0.0.0.0", 0,
492 CL_PORT_SERVER_OPTIONS) < 0) {
493 *msg = tor_strdup("Invalid DirPort configuration");
494 goto err;
497 if (check_and_prune_server_ports(ports, options, &n_low_ports) < 0) {
498 *msg = tor_strdup("Misconfigured server ports");
499 goto err;
502 smartlist_add_all(ports_out, ports);
503 smartlist_free(ports);
504 ports = NULL;
505 retval = 0;
507 err:
508 if (*have_low_ports_out < 0)
509 *have_low_ports_out = (n_low_ports > 0);
510 if (ports) {
511 SMARTLIST_FOREACH(ports, port_cfg_t *, p, port_cfg_free(p));
512 smartlist_free(ports);
514 return retval;
517 /** Update the relay *Port_set values in <b>options</b> from <b>ports</b>. */
518 void
519 port_update_port_set_relay(or_options_t *options,
520 const smartlist_t *ports)
522 if (BUG(!options))
523 return;
525 if (BUG(!ports))
526 return;
528 if (options->ClientOnly)
529 return;
531 /* Update the relay *Port_set options. The !! here is to force a boolean
532 * out of an integer. */
533 options->ORPort_set =
534 !! port_count_real_listeners(ports, CONN_TYPE_OR_LISTENER, 0);
535 options->DirPort_set =
536 !! port_count_real_listeners(ports, CONN_TYPE_DIR_LISTENER, 0);
537 options->ExtORPort_set =
538 !! port_count_real_listeners(ports, CONN_TYPE_EXT_OR_LISTENER, 0);
542 * Legacy validation function, which checks that the current OS is usable in
543 * relay mode, if options is set to a relay mode.
545 * Warns about OSes with potential issues. Does not set *<b>msg</b>.
546 * Always returns 0.
549 options_validate_relay_os(const or_options_t *old_options,
550 or_options_t *options,
551 char **msg)
553 (void)old_options;
555 if (BUG(!options))
556 return -1;
558 if (BUG(!msg))
559 return -1;
561 if (!server_mode(options))
562 return 0;
564 const char *uname = get_uname();
566 if (!strcmpstart(uname, "Windows 95") ||
567 !strcmpstart(uname, "Windows 98") ||
568 !strcmpstart(uname, "Windows Me")) {
569 log_warn(LD_CONFIG, "Tor is running as a server, but you are "
570 "running %s; this probably won't work. See "
571 "https://www.torproject.org/docs/faq.html#BestOSForRelay "
572 "for details.", uname);
575 return 0;
579 * Legacy validation/normalization function for the relay info options.
580 * Uses old_options as the previous options.
582 * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
583 * on error.
586 options_validate_relay_info(const or_options_t *old_options,
587 or_options_t *options,
588 char **msg)
590 (void)old_options;
592 if (BUG(!options))
593 return -1;
595 if (BUG(!msg))
596 return -1;
598 if (options->Nickname == NULL) {
599 if (server_mode(options)) {
600 options->Nickname = tor_strdup(UNNAMED_ROUTER_NICKNAME);
602 } else {
603 if (!is_legal_nickname(options->Nickname)) {
604 tor_asprintf(msg,
605 "Nickname '%s', nicknames must be between 1 and 19 characters "
606 "inclusive, and must contain only the characters [a-zA-Z0-9].",
607 options->Nickname);
608 return -1;
612 if (server_mode(options) && !options->ContactInfo) {
613 log_warn(LD_CONFIG,
614 "Your ContactInfo config option is not set. Please strongly "
615 "consider setting it, so we can contact you if your relay is "
616 "misconfigured, end-of-life, or something else goes wrong. "
617 "It is also possible that your relay might get rejected from "
618 "the network due to a missing valid contact address.");
621 const char *ContactInfo = options->ContactInfo;
622 if (ContactInfo && !string_is_utf8(ContactInfo, strlen(ContactInfo)))
623 REJECT("ContactInfo config option must be UTF-8.");
625 return 0;
628 /** Parse an authority type from <b>options</b>-\>PublishServerDescriptor
629 * and write it to <b>options</b>-\>PublishServerDescriptor_. Treat "1"
630 * as "v3" unless BridgeRelay is 1, in which case treat it as "bridge".
631 * Treat "0" as "".
632 * Return 0 on success or -1 if not a recognized authority type (in which
633 * case the value of PublishServerDescriptor_ is undefined). */
634 static int
635 compute_publishserverdescriptor(or_options_t *options)
637 smartlist_t *list = options->PublishServerDescriptor;
638 dirinfo_type_t *auth = &options->PublishServerDescriptor_;
639 *auth = NO_DIRINFO;
640 if (!list) /* empty list, answer is none */
641 return 0;
642 SMARTLIST_FOREACH_BEGIN(list, const char *, string) {
643 if (!strcasecmp(string, "v1"))
644 log_warn(LD_CONFIG, "PublishServerDescriptor v1 has no effect, because "
645 "there are no v1 directory authorities anymore.");
646 else if (!strcmp(string, "1"))
647 if (options->BridgeRelay)
648 *auth |= BRIDGE_DIRINFO;
649 else
650 *auth |= V3_DIRINFO;
651 else if (!strcasecmp(string, "v2"))
652 log_warn(LD_CONFIG, "PublishServerDescriptor v2 has no effect, because "
653 "there are no v2 directory authorities anymore.");
654 else if (!strcasecmp(string, "v3"))
655 *auth |= V3_DIRINFO;
656 else if (!strcasecmp(string, "bridge"))
657 *auth |= BRIDGE_DIRINFO;
658 else if (!strcasecmp(string, "hidserv"))
659 log_warn(LD_CONFIG,
660 "PublishServerDescriptor hidserv is invalid. See "
661 "PublishHidServDescriptors.");
662 else if (!strcasecmp(string, "") || !strcmp(string, "0"))
663 /* no authority */;
664 else
665 return -1;
666 } SMARTLIST_FOREACH_END(string);
667 return 0;
671 * Validate the configured bridge distribution method from a BridgeDistribution
672 * config line.
674 * The input <b>bd</b>, is a string taken from the BridgeDistribution config
675 * line (if present). If the option wasn't set, return 0 immediately. The
676 * BridgeDistribution option is then validated. Currently valid, recognised
677 * options are:
679 * - "none"
680 * - "any"
681 * - "https"
682 * - "email"
683 * - "moat"
685 * If the option string is unrecognised, a warning will be logged and 0 is
686 * returned. If the option string contains an invalid character, -1 is
687 * returned.
689 STATIC int
690 check_bridge_distribution_setting(const char *bd)
692 if (bd == NULL)
693 return 0;
695 const char *RECOGNIZED[] = {
696 "none", "any", "https", "email", "moat"
698 unsigned i;
699 for (i = 0; i < ARRAY_LENGTH(RECOGNIZED); ++i) {
700 if (!strcasecmp(bd, RECOGNIZED[i]))
701 return 0;
704 const char *cp = bd;
705 // Method = (KeywordChar | "_") +
706 while (TOR_ISALNUM(*cp) || *cp == '-' || *cp == '_')
707 ++cp;
709 if (*cp == 0) {
710 log_warn(LD_CONFIG, "Unrecognized BridgeDistribution value %s. I'll "
711 "assume you know what you are doing...", escaped(bd));
712 return 0; // we reached the end of the string; all is well
713 } else {
714 return -1; // we found a bad character in the string.
719 * Legacy validation/normalization function for the bridge relay options.
720 * Uses old_options as the previous options.
722 * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
723 * on error.
726 options_validate_publish_server(const or_options_t *old_options,
727 or_options_t *options,
728 char **msg)
730 (void)old_options;
732 if (BUG(!options))
733 return -1;
735 if (BUG(!msg))
736 return -1;
738 if (compute_publishserverdescriptor(options) < 0) {
739 tor_asprintf(msg, "Unrecognized value in PublishServerDescriptor");
740 return -1;
743 if ((options->BridgeRelay
744 || options->PublishServerDescriptor_ & BRIDGE_DIRINFO)
745 && (options->PublishServerDescriptor_ & V3_DIRINFO)) {
746 REJECT("Bridges are not supposed to publish router descriptors to the "
747 "directory authorities. Please correct your "
748 "PublishServerDescriptor line.");
751 if (options->BridgeDistribution) {
752 if (!options->BridgeRelay) {
753 REJECT("You set BridgeDistribution, but you didn't set BridgeRelay!");
755 if (check_bridge_distribution_setting(options->BridgeDistribution) < 0) {
756 REJECT("Invalid BridgeDistribution value.");
760 if (options->PublishServerDescriptor)
761 SMARTLIST_FOREACH(options->PublishServerDescriptor, const char *, pubdes, {
762 if (!strcmp(pubdes, "1") || !strcmp(pubdes, "0"))
763 if (smartlist_len(options->PublishServerDescriptor) > 1) {
764 COMPLAIN("You have passed a list of multiple arguments to the "
765 "PublishServerDescriptor option that includes 0 or 1. "
766 "0 or 1 should only be used as the sole argument. "
767 "This configuration will be rejected in a future release.");
768 break;
772 return 0;
776 * Legacy validation/normalization function for the relay padding options.
777 * Uses old_options as the previous options.
779 * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
780 * on error.
783 options_validate_relay_padding(const or_options_t *old_options,
784 or_options_t *options,
785 char **msg)
787 (void)old_options;
789 if (BUG(!options))
790 return -1;
792 if (BUG(!msg))
793 return -1;
795 if (!server_mode(options))
796 return 0;
798 if (options->ConnectionPadding != -1) {
799 REJECT("Relays must use 'auto' for the ConnectionPadding setting.");
802 if (options->ReducedConnectionPadding != 0) {
803 REJECT("Relays cannot set ReducedConnectionPadding. ");
806 if (options->CircuitPadding == 0) {
807 REJECT("Relays cannot set CircuitPadding to 0. ");
810 if (options->ReducedCircuitPadding == 1) {
811 REJECT("Relays cannot set ReducedCircuitPadding. ");
814 return 0;
818 * Legacy validation/normalization function for the relay bandwidth options.
819 * Uses old_options as the previous options.
821 * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
822 * on error.
825 options_validate_relay_bandwidth(const or_options_t *old_options,
826 or_options_t *options,
827 char **msg)
829 (void)old_options;
831 if (BUG(!options))
832 return -1;
834 if (BUG(!msg))
835 return -1;
837 /* 31851: the tests expect us to validate bandwidths, even when we are not
838 * in relay mode. */
839 if (config_ensure_bandwidth_cap(&options->MaxAdvertisedBandwidth,
840 "MaxAdvertisedBandwidth", msg) < 0)
841 return -1;
842 if (config_ensure_bandwidth_cap(&options->RelayBandwidthRate,
843 "RelayBandwidthRate", msg) < 0)
844 return -1;
845 if (config_ensure_bandwidth_cap(&options->RelayBandwidthBurst,
846 "RelayBandwidthBurst", msg) < 0)
847 return -1;
848 if (config_ensure_bandwidth_cap(&options->PerConnBWRate,
849 "PerConnBWRate", msg) < 0)
850 return -1;
851 if (config_ensure_bandwidth_cap(&options->PerConnBWBurst,
852 "PerConnBWBurst", msg) < 0)
853 return -1;
855 if (options->RelayBandwidthRate && !options->RelayBandwidthBurst)
856 options->RelayBandwidthBurst = options->RelayBandwidthRate;
857 if (options->RelayBandwidthBurst && !options->RelayBandwidthRate)
858 options->RelayBandwidthRate = options->RelayBandwidthBurst;
860 if (server_mode(options)) {
861 const unsigned required_min_bw =
862 public_server_mode(options) ?
863 RELAY_REQUIRED_MIN_BANDWIDTH : BRIDGE_REQUIRED_MIN_BANDWIDTH;
864 const char * const optbridge =
865 public_server_mode(options) ? "" : "bridge ";
866 if (options->BandwidthRate < required_min_bw) {
867 tor_asprintf(msg,
868 "BandwidthRate is set to %d bytes/second. "
869 "For %sservers, it must be at least %u.",
870 (int)options->BandwidthRate, optbridge,
871 required_min_bw);
872 return -1;
873 } else if (options->MaxAdvertisedBandwidth <
874 required_min_bw/2) {
875 tor_asprintf(msg,
876 "MaxAdvertisedBandwidth is set to %d bytes/second. "
877 "For %sservers, it must be at least %u.",
878 (int)options->MaxAdvertisedBandwidth, optbridge,
879 required_min_bw/2);
880 return -1;
882 if (options->RelayBandwidthRate &&
883 options->RelayBandwidthRate < required_min_bw) {
884 tor_asprintf(msg,
885 "RelayBandwidthRate is set to %d bytes/second. "
886 "For %sservers, it must be at least %u.",
887 (int)options->RelayBandwidthRate, optbridge,
888 required_min_bw);
889 return -1;
893 /* 31851: the tests expect us to validate bandwidths, even when we are not
894 * in relay mode. */
895 if (options->RelayBandwidthRate > options->RelayBandwidthBurst)
896 REJECT("RelayBandwidthBurst must be at least equal "
897 "to RelayBandwidthRate.");
899 /* if they set relaybandwidth* really high but left bandwidth*
900 * at the default, raise the defaults. */
901 if (options->RelayBandwidthRate > options->BandwidthRate)
902 options->BandwidthRate = options->RelayBandwidthRate;
903 if (options->RelayBandwidthBurst > options->BandwidthBurst)
904 options->BandwidthBurst = options->RelayBandwidthBurst;
906 return 0;
910 * Legacy validation/normalization function for the relay bandwidth accounting
911 * options. Uses old_options as the previous options.
913 * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
914 * on error.
917 options_validate_relay_accounting(const or_options_t *old_options,
918 or_options_t *options,
919 char **msg)
921 (void)old_options;
923 if (BUG(!options))
924 return -1;
926 if (BUG(!msg))
927 return -1;
929 /* 31851: the tests expect us to validate accounting, even when we are not
930 * in relay mode. */
931 if (accounting_parse_options(options, 1)<0)
932 REJECT("Failed to parse accounting options. See logs for details.");
934 if (options->AccountingMax) {
935 if (options->RendConfigLines && server_mode(options)) {
936 log_warn(LD_CONFIG, "Using accounting with a hidden service and an "
937 "ORPort is risky: your hidden service(s) and your public "
938 "address will all turn off at the same time, which may alert "
939 "observers that they are being run by the same party.");
940 } else if (config_count_key(options->RendConfigLines,
941 "HiddenServiceDir") > 1) {
942 log_warn(LD_CONFIG, "Using accounting with multiple hidden services is "
943 "risky: they will all turn off at the same time, which may "
944 "alert observers that they are being run by the same party.");
948 options->AccountingRule = ACCT_MAX;
949 if (options->AccountingRule_option) {
950 if (!strcmp(options->AccountingRule_option, "sum"))
951 options->AccountingRule = ACCT_SUM;
952 else if (!strcmp(options->AccountingRule_option, "max"))
953 options->AccountingRule = ACCT_MAX;
954 else if (!strcmp(options->AccountingRule_option, "in"))
955 options->AccountingRule = ACCT_IN;
956 else if (!strcmp(options->AccountingRule_option, "out"))
957 options->AccountingRule = ACCT_OUT;
958 else
959 REJECT("AccountingRule must be 'sum', 'max', 'in', or 'out'");
962 return 0;
965 /** Verify whether lst is a list of strings containing valid-looking
966 * comma-separated nicknames, or NULL. Will normalise <b>lst</b> to prefix '$'
967 * to any nickname or fingerprint that needs it. Also splits comma-separated
968 * list elements into multiple elements. Return 0 on success.
969 * Warn and return -1 on failure.
971 static int
972 normalize_nickname_list(config_line_t **normalized_out,
973 const config_line_t *lst, const char *name,
974 char **msg)
976 if (!lst)
977 return 0;
979 config_line_t *new_nicknames = NULL;
980 config_line_t **new_nicknames_next = &new_nicknames;
982 const config_line_t *cl;
983 for (cl = lst; cl; cl = cl->next) {
984 const char *line = cl->value;
985 if (!line)
986 continue;
988 int valid_line = 1;
989 smartlist_t *sl = smartlist_new();
990 smartlist_split_string(sl, line, ",",
991 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK|SPLIT_STRIP_SPACE, 0);
992 SMARTLIST_FOREACH_BEGIN(sl, char *, s)
994 char *normalized = NULL;
995 if (!is_legal_nickname_or_hexdigest(s)) {
996 // check if first char is dollar
997 if (s[0] != '$') {
998 // Try again but with a dollar symbol prepended
999 char *prepended;
1000 tor_asprintf(&prepended, "$%s", s);
1002 if (is_legal_nickname_or_hexdigest(prepended)) {
1003 // The nickname is valid when it's prepended, set it as the
1004 // normalized version
1005 normalized = prepended;
1006 } else {
1007 // Still not valid, free and fallback to error message
1008 tor_free(prepended);
1012 if (!normalized) {
1013 tor_asprintf(msg, "Invalid nickname '%s' in %s line", s, name);
1014 valid_line = 0;
1015 break;
1017 } else {
1018 normalized = tor_strdup(s);
1021 config_line_t *next = tor_malloc_zero(sizeof(*next));
1022 next->key = tor_strdup(cl->key);
1023 next->value = normalized;
1024 next->next = NULL;
1026 *new_nicknames_next = next;
1027 new_nicknames_next = &next->next;
1028 } SMARTLIST_FOREACH_END(s);
1030 SMARTLIST_FOREACH(sl, char *, s, tor_free(s));
1031 smartlist_free(sl);
1033 if (!valid_line) {
1034 config_free_lines(new_nicknames);
1035 return -1;
1039 *normalized_out = new_nicknames;
1041 return 0;
1044 #define ONE_MEGABYTE (UINT64_C(1) << 20)
1046 /* If we have less than 300 MB suggest disabling dircache */
1047 #define DIRCACHE_MIN_MEM_MB 300
1048 #define DIRCACHE_MIN_MEM_BYTES (DIRCACHE_MIN_MEM_MB*ONE_MEGABYTE)
1049 #define STRINGIFY(val) #val
1051 /** Create a warning message for emitting if we are a dircache but may not have
1052 * enough system memory, or if we are not a dircache but probably should be.
1053 * Return -1 when a message is returned in *msg*, else return 0. */
1054 STATIC int
1055 have_enough_mem_for_dircache(const or_options_t *options, size_t total_mem,
1056 char **msg)
1058 *msg = NULL;
1059 /* XXX We should possibly be looking at MaxMemInQueues here
1060 * unconditionally. Or we should believe total_mem unconditionally. */
1061 if (total_mem == 0) {
1062 if (get_total_system_memory(&total_mem) < 0) {
1063 total_mem = options->MaxMemInQueues >= SIZE_MAX ?
1064 SIZE_MAX : (size_t)options->MaxMemInQueues;
1067 if (options->DirCache) {
1068 if (total_mem < DIRCACHE_MIN_MEM_BYTES) {
1069 if (options->BridgeRelay) {
1070 tor_asprintf(msg, "Running a Bridge with less than %d MB of memory "
1071 "is not recommended.", DIRCACHE_MIN_MEM_MB);
1072 } else {
1073 tor_asprintf(msg, "Being a directory cache (default) with less than "
1074 "%d MB of memory is not recommended and may consume "
1075 "most of the available resources. Consider disabling "
1076 "this functionality by setting the DirCache option "
1077 "to 0.", DIRCACHE_MIN_MEM_MB);
1080 } else {
1081 if (total_mem >= DIRCACHE_MIN_MEM_BYTES) {
1082 *msg = tor_strdup("DirCache is disabled and we are configured as a "
1083 "relay. We will not become a Guard.");
1086 return *msg == NULL ? 0 : -1;
1088 #undef STRINGIFY
1091 * Legacy validation/normalization function for the relay mode options.
1092 * Uses old_options as the previous options.
1094 * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
1095 * on error.
1098 options_validate_relay_mode(const or_options_t *old_options,
1099 or_options_t *options,
1100 char **msg)
1102 (void)old_options;
1104 if (BUG(!options))
1105 return -1;
1107 if (BUG(!msg))
1108 return -1;
1110 if (server_mode(options) && options->RendConfigLines)
1111 log_warn(LD_CONFIG,
1112 "Tor is currently configured as a relay and a hidden service. "
1113 "That's not very secure: you should probably run your hidden service "
1114 "in a separate Tor process, at least -- see "
1115 "https://bugs.torproject.org/tpo/core/tor/8742.");
1117 if (options->BridgeRelay && options->DirPort_set) {
1118 log_warn(LD_CONFIG, "Can't set a DirPort on a bridge relay; disabling "
1119 "DirPort");
1120 config_free_lines(options->DirPort_lines);
1121 options->DirPort_lines = NULL;
1122 options->DirPort_set = 0;
1125 if (options->DirPort_set && !options->DirCache) {
1126 REJECT("DirPort configured but DirCache disabled. DirPort requires "
1127 "DirCache.");
1130 if (options->BridgeRelay && !options->DirCache) {
1131 REJECT("We're a bridge but DirCache is disabled. BridgeRelay requires "
1132 "DirCache.");
1135 if (options->BridgeRelay == 1 && ! options->ORPort_set)
1136 REJECT("BridgeRelay is 1, ORPort is not set. This is an invalid "
1137 "combination.");
1139 if (server_mode(options)) {
1140 char *dircache_msg = NULL;
1141 if (have_enough_mem_for_dircache(options, 0, &dircache_msg)) {
1142 log_warn(LD_CONFIG, "%s", dircache_msg);
1143 tor_free(dircache_msg);
1147 if (options->MyFamily_lines && options->BridgeRelay) {
1148 log_warn(LD_CONFIG, "Listing a family for a bridge relay is not "
1149 "supported: it can reveal bridge fingerprints to censors. "
1150 "You should also make sure you aren't listing this bridge's "
1151 "fingerprint in any other MyFamily.");
1153 if (options->MyFamily_lines && !options->ContactInfo) {
1154 log_warn(LD_CONFIG, "MyFamily is set but ContactInfo is not configured. "
1155 "ContactInfo should always be set when MyFamily option is too.");
1157 if (normalize_nickname_list(&options->MyFamily,
1158 options->MyFamily_lines, "MyFamily", msg))
1159 return -1;
1161 if (options->ConstrainedSockets) {
1162 if (options->DirPort_set) {
1163 /* Providing cached directory entries while system TCP buffers are scarce
1164 * will exacerbate the socket errors. Suggest that this be disabled. */
1165 COMPLAIN("You have requested constrained socket buffers while also "
1166 "serving directory entries via DirPort. It is strongly "
1167 "suggested that you disable serving directory requests when "
1168 "system TCP buffer resources are scarce.");
1172 return 0;
1176 * Legacy validation/normalization function for the relay testing options
1177 * in options. Uses old_options as the previous options.
1179 * Returns 0 on success, returns -1 and sets *msg to a newly allocated string
1180 * on error.
1183 options_validate_relay_testing(const or_options_t *old_options,
1184 or_options_t *options,
1185 char **msg)
1187 (void)old_options;
1189 if (BUG(!options))
1190 return -1;
1192 if (BUG(!msg))
1193 return -1;
1195 if (options->SigningKeyLifetime < options->TestingSigningKeySlop*2)
1196 REJECT("SigningKeyLifetime is too short.");
1197 if (options->TestingLinkCertLifetime < options->TestingAuthKeySlop*2)
1198 REJECT("LinkCertLifetime is too short.");
1199 if (options->TestingAuthKeyLifetime < options->TestingLinkKeySlop*2)
1200 REJECT("TestingAuthKeyLifetime is too short.");
1202 return 0;
1205 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
1206 * will require us to rotate the CPU and DNS workers; else return 0. */
1207 static int
1208 options_transition_affects_workers(const or_options_t *old_options,
1209 const or_options_t *new_options)
1211 YES_IF_CHANGED_STRING(DataDirectory);
1212 YES_IF_CHANGED_INT(NumCPUs);
1213 YES_IF_CHANGED_LINELIST(ORPort_lines);
1214 YES_IF_CHANGED_BOOL(ServerDNSSearchDomains);
1215 YES_IF_CHANGED_BOOL(SafeLogging_);
1216 YES_IF_CHANGED_BOOL(ClientOnly);
1217 YES_IF_CHANGED_BOOL(LogMessageDomains);
1218 YES_IF_CHANGED_LINELIST(Logs);
1220 if (server_mode(old_options) != server_mode(new_options) ||
1221 public_server_mode(old_options) != public_server_mode(new_options) ||
1222 dir_server_mode(old_options) != dir_server_mode(new_options))
1223 return 1;
1225 /* Nothing that changed matters. */
1226 return 0;
1229 /** Return 1 if any change from <b>old_options</b> to <b>new_options</b>
1230 * will require us to generate a new descriptor; else return 0. */
1231 static int
1232 options_transition_affects_descriptor(const or_options_t *old_options,
1233 const or_options_t *new_options)
1235 /* XXX We can be smarter here. If your DirPort isn't being
1236 * published and you just turned it off, no need to republish. Etc. */
1238 YES_IF_CHANGED_STRING(DataDirectory);
1239 YES_IF_CHANGED_STRING(Nickname);
1240 YES_IF_CHANGED_LINELIST(Address);
1241 YES_IF_CHANGED_LINELIST(ExitPolicy);
1242 YES_IF_CHANGED_BOOL(ExitRelay);
1243 YES_IF_CHANGED_BOOL(ExitPolicyRejectPrivate);
1244 YES_IF_CHANGED_BOOL(ExitPolicyRejectLocalInterfaces);
1245 YES_IF_CHANGED_BOOL(IPv6Exit);
1246 YES_IF_CHANGED_LINELIST(ORPort_lines);
1247 YES_IF_CHANGED_LINELIST(DirPort_lines);
1248 YES_IF_CHANGED_LINELIST(DirPort_lines);
1249 YES_IF_CHANGED_BOOL(ClientOnly);
1250 YES_IF_CHANGED_BOOL(DisableNetwork);
1251 YES_IF_CHANGED_BOOL(PublishServerDescriptor_);
1252 YES_IF_CHANGED_STRING(ContactInfo);
1253 YES_IF_CHANGED_STRING(BridgeDistribution);
1254 YES_IF_CHANGED_LINELIST(MyFamily);
1255 YES_IF_CHANGED_STRING(AccountingStart);
1256 YES_IF_CHANGED_INT(AccountingMax);
1257 YES_IF_CHANGED_INT(AccountingRule);
1258 YES_IF_CHANGED_BOOL(DirCache);
1259 YES_IF_CHANGED_BOOL(AssumeReachable);
1261 if (relay_get_effective_bwrate(old_options) !=
1262 relay_get_effective_bwrate(new_options) ||
1263 relay_get_effective_bwburst(old_options) !=
1264 relay_get_effective_bwburst(new_options) ||
1265 public_server_mode(old_options) != public_server_mode(new_options))
1266 return 1;
1268 return 0;
1271 /** Fetch the active option list, and take relay actions based on it. All of
1272 * the things we do should survive being done repeatedly. If present,
1273 * <b>old_options</b> contains the previous value of the options.
1275 * Return 0 if all goes well, return -1 if it's time to die.
1277 * Note: We haven't moved all the "act on new configuration" logic
1278 * into the options_act* functions yet. Some is still in do_hup() and other
1279 * places.
1282 options_act_relay(const or_options_t *old_options)
1284 const or_options_t *options = get_options();
1286 const int transition_affects_workers =
1287 old_options && options_transition_affects_workers(old_options, options);
1289 /* We want to reinit keys as needed before we do much of anything else:
1290 keys are important, and other things can depend on them. */
1291 if (transition_affects_workers ||
1292 (authdir_mode_v3(options) && (!old_options ||
1293 !authdir_mode_v3(old_options)))) {
1294 if (init_keys() < 0) {
1295 log_warn(LD_BUG,"Error initializing keys; exiting");
1296 return -1;
1300 if (server_mode(options)) {
1301 static int cdm_initialized = 0;
1302 if (cdm_initialized == 0) {
1303 cdm_initialized = 1;
1304 consdiffmgr_configure(NULL);
1305 consdiffmgr_validate();
1309 /* Check for transitions that need action. */
1310 if (old_options) {
1311 if (transition_affects_workers) {
1312 log_info(LD_GENERAL,
1313 "Worker-related options changed. Rotating workers.");
1314 const int server_mode_turned_on =
1315 server_mode(options) && !server_mode(old_options);
1316 const int dir_server_mode_turned_on =
1317 dir_server_mode(options) && !dir_server_mode(old_options);
1319 if (server_mode_turned_on || dir_server_mode_turned_on) {
1320 cpu_init();
1323 if (server_mode_turned_on) {
1324 ip_address_changed(0);
1326 cpuworkers_rotate_keyinfo();
1330 return 0;
1333 /** Fetch the active option list, and take relay accounting actions based on
1334 * it. All of the things we do should survive being done repeatedly. If
1335 * present, <b>old_options</b> contains the previous value of the options.
1337 * Return 0 if all goes well, return -1 if it's time to die.
1339 * Note: We haven't moved all the "act on new configuration" logic
1340 * into the options_act* functions yet. Some is still in do_hup() and other
1341 * places.
1344 options_act_relay_accounting(const or_options_t *old_options)
1346 (void)old_options;
1348 const or_options_t *options = get_options();
1350 /* Set up accounting */
1351 if (accounting_parse_options(options, 0)<0) {
1352 // LCOV_EXCL_START
1353 log_warn(LD_BUG,"Error in previously validated accounting options");
1354 return -1;
1355 // LCOV_EXCL_STOP
1357 if (accounting_is_enabled(options))
1358 configure_accounting(time(NULL));
1360 return 0;
1363 /** Fetch the active option list, and take relay bandwidth actions based on
1364 * it. All of the things we do should survive being done repeatedly. If
1365 * present, <b>old_options</b> contains the previous value of the options.
1367 * Return 0 if all goes well, return -1 if it's time to die.
1369 * Note: We haven't moved all the "act on new configuration" logic
1370 * into the options_act* functions yet. Some is still in do_hup() and other
1371 * places.
1374 options_act_relay_bandwidth(const or_options_t *old_options)
1376 const or_options_t *options = get_options();
1378 /* Check for transitions that need action. */
1379 if (old_options) {
1380 if (options->PerConnBWRate != old_options->PerConnBWRate ||
1381 options->PerConnBWBurst != old_options->PerConnBWBurst)
1382 connection_or_update_token_buckets(get_connection_array(), options);
1384 if (options->RelayBandwidthRate != old_options->RelayBandwidthRate ||
1385 options->RelayBandwidthBurst != old_options->RelayBandwidthBurst)
1386 connection_bucket_adjust(options);
1389 return 0;
1392 /** Fetch the active option list, and take bridge statistics actions based on
1393 * it. All of the things we do should survive being done repeatedly. If
1394 * present, <b>old_options</b> contains the previous value of the options.
1396 * Return 0 if all goes well, return -1 if it's time to die.
1398 * Note: We haven't moved all the "act on new configuration" logic
1399 * into the options_act* functions yet. Some is still in do_hup() and other
1400 * places.
1403 options_act_bridge_stats(const or_options_t *old_options)
1405 const or_options_t *options = get_options();
1407 /* How long should we delay counting bridge stats after becoming a bridge?
1408 * We use this so we don't count clients who used our bridge thinking it is
1409 * a relay. If you change this, don't forget to change the log message
1410 * below. It's 4 hours (the time it takes to stop being used by clients)
1411 * plus some extra time for clock skew. */
1412 #define RELAY_BRIDGE_STATS_DELAY (6 * 60 * 60)
1414 /* Check for transitions that need action. */
1415 if (old_options) {
1416 if (! bool_eq(options->BridgeRelay, old_options->BridgeRelay)) {
1417 int was_relay = 0;
1418 if (options->BridgeRelay) {
1419 time_t int_start = time(NULL);
1420 if (config_lines_eq(old_options->ORPort_lines,options->ORPort_lines)) {
1421 int_start += RELAY_BRIDGE_STATS_DELAY;
1422 was_relay = 1;
1424 geoip_bridge_stats_init(int_start);
1425 log_info(LD_CONFIG, "We are acting as a bridge now. Starting new "
1426 "GeoIP stats interval%s.", was_relay ? " in 6 "
1427 "hours from now" : "");
1428 } else {
1429 geoip_bridge_stats_term();
1430 log_info(LD_GENERAL, "We are no longer acting as a bridge. "
1431 "Forgetting GeoIP stats.");
1436 return 0;
1439 /** Fetch the active option list, and take relay statistics actions based on
1440 * it. All of the things we do should survive being done repeatedly. If
1441 * present, <b>old_options</b> contains the previous value of the options.
1443 * Sets <b>*print_notice_out</b> if we enabled stats, and need to print
1444 * a stats log using options_act_relay_stats_msg().
1446 * If loading the GeoIP file failed, sets DirReqStatistics and
1447 * EntryStatistics to 0. This breaks the normalization/act ordering
1448 * introduced in 29211.
1450 * Return 0 if all goes well, return -1 if it's time to die.
1452 * Note: We haven't moved all the "act on new configuration" logic
1453 * into the options_act* functions yet. Some is still in do_hup() and other
1454 * places.
1457 options_act_relay_stats(const or_options_t *old_options,
1458 bool *print_notice_out)
1460 if (BUG(!print_notice_out))
1461 return -1;
1463 or_options_t *options = get_options_mutable();
1465 if (options->CellStatistics || options->DirReqStatistics ||
1466 options->EntryStatistics || options->ExitPortStatistics ||
1467 options->ConnDirectionStatistics ||
1468 options->HiddenServiceStatistics) {
1469 time_t now = time(NULL);
1470 int print_notice = 0;
1472 if ((!old_options || !old_options->CellStatistics) &&
1473 options->CellStatistics) {
1474 rep_hist_buffer_stats_init(now);
1475 print_notice = 1;
1477 if ((!old_options || !old_options->DirReqStatistics) &&
1478 options->DirReqStatistics) {
1479 if (geoip_is_loaded(AF_INET)) {
1480 geoip_dirreq_stats_init(now);
1481 print_notice = 1;
1482 } else {
1483 /* disable statistics collection since we have no geoip file */
1484 /* 29211: refactor to avoid the normalisation/act inversion */
1485 options->DirReqStatistics = 0;
1486 if (options->ORPort_set)
1487 log_notice(LD_CONFIG, "Configured to measure directory request "
1488 "statistics, but no GeoIP database found. "
1489 "Please specify a GeoIP database using the "
1490 "GeoIPFile option.");
1493 if ((!old_options || !old_options->EntryStatistics) &&
1494 options->EntryStatistics && !should_record_bridge_info(options)) {
1495 /* If we get here, we've started recording bridge info when we didn't
1496 * do so before. Note that "should_record_bridge_info()" will
1497 * always be false at this point, because of the earlier block
1498 * that cleared EntryStatistics when public_server_mode() was false.
1499 * We're leaving it in as defensive programming. */
1500 if (geoip_is_loaded(AF_INET) || geoip_is_loaded(AF_INET6)) {
1501 geoip_entry_stats_init(now);
1502 print_notice = 1;
1503 } else {
1504 options->EntryStatistics = 0;
1505 log_notice(LD_CONFIG, "Configured to measure entry node "
1506 "statistics, but no GeoIP database found. "
1507 "Please specify a GeoIP database using the "
1508 "GeoIPFile option.");
1511 if ((!old_options || !old_options->ExitPortStatistics) &&
1512 options->ExitPortStatistics) {
1513 rep_hist_exit_stats_init(now);
1514 print_notice = 1;
1516 if ((!old_options || !old_options->ConnDirectionStatistics) &&
1517 options->ConnDirectionStatistics) {
1518 conn_stats_init(now);
1520 if ((!old_options || !old_options->HiddenServiceStatistics) &&
1521 options->HiddenServiceStatistics) {
1522 log_info(LD_CONFIG, "Configured to measure hidden service statistics.");
1523 rep_hist_hs_stats_init(now);
1525 if (print_notice)
1526 *print_notice_out = 1;
1529 /* If we used to have statistics enabled but we just disabled them,
1530 stop gathering them. */
1531 if (old_options && old_options->CellStatistics &&
1532 !options->CellStatistics)
1533 rep_hist_buffer_stats_term();
1534 if (old_options && old_options->DirReqStatistics &&
1535 !options->DirReqStatistics)
1536 geoip_dirreq_stats_term();
1537 if (old_options && old_options->EntryStatistics &&
1538 !options->EntryStatistics)
1539 geoip_entry_stats_term();
1540 if (old_options && old_options->HiddenServiceStatistics &&
1541 !options->HiddenServiceStatistics)
1542 rep_hist_hs_stats_term();
1543 if (old_options && old_options->ExitPortStatistics &&
1544 !options->ExitPortStatistics)
1545 rep_hist_exit_stats_term();
1546 if (old_options && old_options->ConnDirectionStatistics &&
1547 !options->ConnDirectionStatistics)
1548 conn_stats_terminate();
1550 return 0;
1553 /** Print a notice about relay/dirauth stats being enabled. */
1554 void
1555 options_act_relay_stats_msg(void)
1557 log_notice(LD_CONFIG, "Configured to measure statistics. Look for "
1558 "the *-stats files that will first be written to the "
1559 "data directory in 24 hours from now.");
1562 /** Fetch the active option list, and take relay descriptor actions based on
1563 * it. All of the things we do should survive being done repeatedly. If
1564 * present, <b>old_options</b> contains the previous value of the options.
1566 * Return 0 if all goes well, return -1 if it's time to die.
1568 * Note: We haven't moved all the "act on new configuration" logic
1569 * into the options_act* functions yet. Some is still in do_hup() and other
1570 * places.
1573 options_act_relay_desc(const or_options_t *old_options)
1575 const or_options_t *options = get_options();
1577 /* Since our options changed, we might need to regenerate and upload our
1578 * server descriptor.
1580 if (!old_options ||
1581 options_transition_affects_descriptor(old_options, options))
1582 mark_my_descriptor_dirty("config change");
1584 return 0;
1587 /** Fetch the active option list, and take relay DoS actions based on
1588 * it. All of the things we do should survive being done repeatedly. If
1589 * present, <b>old_options</b> contains the previous value of the options.
1591 * Return 0 if all goes well, return -1 if it's time to die.
1593 * Note: We haven't moved all the "act on new configuration" logic
1594 * into the options_act* functions yet. Some is still in do_hup() and other
1595 * places.
1598 options_act_relay_dos(const or_options_t *old_options)
1600 const or_options_t *options = get_options();
1602 /* DoS mitigation subsystem only applies to public relay. */
1603 if (public_server_mode(options)) {
1604 /* If we are configured as a relay, initialize the subsystem. Even on HUP,
1605 * this is safe to call as it will load data from the current options
1606 * or/and the consensus. */
1607 dos_init();
1608 } else if (old_options && public_server_mode(old_options)) {
1609 /* Going from relay to non relay, clean it up. */
1610 dos_free_all();
1613 return 0;
1616 /** Fetch the active option list, and take dirport actions based on
1617 * it. All of the things we do should survive being done repeatedly. If
1618 * present, <b>old_options</b> contains the previous value of the options.
1620 * Return 0 if all goes well, return -1 if it's time to die.
1622 * Note: We haven't moved all the "act on new configuration" logic
1623 * into the options_act* functions yet. Some is still in do_hup() and other
1624 * places.
1627 options_act_relay_dir(const or_options_t *old_options)
1629 (void)old_options;
1631 const or_options_t *options = get_options();
1633 if (!public_server_mode(options))
1634 return 0;
1636 /* Load the webpage we're going to serve every time someone asks for '/' on
1637 our DirPort. */
1638 tor_free(global_dirfrontpagecontents);
1639 if (options->DirPortFrontPage) {
1640 global_dirfrontpagecontents =
1641 read_file_to_str(options->DirPortFrontPage, 0, NULL);
1642 if (!global_dirfrontpagecontents) {
1643 log_warn(LD_CONFIG,
1644 "DirPortFrontPage file '%s' not found. Continuing anyway.",
1645 options->DirPortFrontPage);
1649 return 0;