tor

The Tor anonymity network
git clone https://git.dasho.dev/tor.git
Log | Files | Refs | README | LICENSE

relay_config.c (55669B)


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