tor

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

address.c (66513B)


      1 /* Copyright (c) 2003-2004, Roger Dingledine
      2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
      3 * Copyright (c) 2007-2021, The Tor Project, Inc. */
      4 /* See LICENSE for licensing information */
      5 
      6 /**
      7 * \file address.c
      8 * \brief Functions to use and manipulate the tor_addr_t structure.
      9 *
     10 * This module doesn't have any support for the libc resolver: that is all in
     11 * resolve.c.
     12 **/
     13 
     14 #define ADDRESS_PRIVATE
     15 
     16 #include "orconfig.h"
     17 
     18 #ifdef _WIN32
     19 /* For access to structs needed by GetAdaptersAddresses */
     20 #ifndef WIN32_LEAN_AND_MEAN
     21 #error "orconfig.h didn't define WIN32_LEAN_AND_MEAN"
     22 #endif
     23 #ifndef WINVER
     24 #error "orconfig.h didn't define WINVER"
     25 #endif
     26 #ifndef _WIN32_WINNT
     27 #error "orconfig.h didn't define _WIN32_WINNT"
     28 #endif
     29 #if WINVER < 0x0501
     30 #error "winver too low"
     31 #endif
     32 #if _WIN32_WINNT < 0x0501
     33 #error "winver too low"
     34 #endif
     35 #include <winsock2.h>
     36 #include <process.h>
     37 #include <windows.h>
     38 #include <iphlpapi.h>
     39 #endif /* defined(_WIN32) */
     40 
     41 #include "lib/net/address.h"
     42 #include "lib/net/socket.h"
     43 #include "lib/cc/ctassert.h"
     44 #include "lib/container/smartlist.h"
     45 #include "lib/ctime/di_ops.h"
     46 #include "lib/log/log.h"
     47 #include "lib/log/escape.h"
     48 #include "lib/malloc/malloc.h"
     49 #include "lib/net/inaddr.h"
     50 #include "lib/string/compat_ctype.h"
     51 #include "lib/string/compat_string.h"
     52 #include "lib/string/parse_int.h"
     53 #include "lib/string/printf.h"
     54 #include "lib/string/util_string.h"
     55 
     56 #include "ext/siphash.h"
     57 
     58 #ifdef HAVE_SYS_TIME_H
     59 #include <sys/time.h>
     60 #endif
     61 #ifdef HAVE_UNISTD_H
     62 #include <unistd.h>
     63 #endif
     64 #ifdef HAVE_ERRNO_H
     65 #include <errno.h>
     66 #endif
     67 #ifdef HAVE_ARPA_INET_H
     68 #include <arpa/inet.h>
     69 #endif
     70 #ifdef HAVE_SYS_SOCKET_H
     71 #include <sys/socket.h>
     72 #endif
     73 #ifdef HAVE_NETDB_H
     74 #include <netdb.h>
     75 #endif
     76 #ifdef HAVE_SYS_PARAM_H
     77 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
     78 #endif
     79 #ifdef HAVE_SYS_UN_H
     80 #include <sys/un.h>
     81 #endif
     82 #ifdef HAVE_IFADDRS_H
     83 #include <ifaddrs.h>
     84 #endif
     85 #ifdef HAVE_SYS_IOCTL_H
     86 #include <sys/ioctl.h>
     87 #endif
     88 #ifdef HAVE_NET_IF_H
     89 #include <net/if.h>
     90 #endif
     91 #include <stdarg.h>
     92 #include <stdio.h>
     93 #include <stdlib.h>
     94 #include <string.h>
     95 
     96 /* tor_addr_is_null() and maybe other functions rely on AF_UNSPEC being 0 to
     97 * work correctly. Bail out here if we've found a platform where AF_UNSPEC
     98 * isn't 0. */
     99 #if AF_UNSPEC != 0
    100 #error "We rely on AF_UNSPEC being 0. Yours isn't. Please tell us more!"
    101 #endif
    102 CTASSERT(AF_UNSPEC == 0);
    103 
    104 /** Convert the tor_addr_t in <b>a</b>, with port in <b>port</b>, into a
    105 * sockaddr object in *<b>sa_out</b> of object size <b>len</b>.  If not enough
    106 * room is available in sa_out, or on error, return 0.  On success, return
    107 * the length of the sockaddr.
    108 *
    109 * Interface note: ordinarily, we return -1 for error.  We can't do that here,
    110 * since socklen_t is unsigned on some platforms.
    111 **/
    112 socklen_t
    113 tor_addr_to_sockaddr(const tor_addr_t *a,
    114                     uint16_t port,
    115                     struct sockaddr *sa_out,
    116                     socklen_t len)
    117 {
    118  memset(sa_out, 0, len);
    119 
    120  sa_family_t family = tor_addr_family(a);
    121  if (family == AF_INET) {
    122    struct sockaddr_in *sin;
    123    if (len < (int)sizeof(struct sockaddr_in))
    124      return 0;
    125    sin = (struct sockaddr_in *)sa_out;
    126 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
    127    sin->sin_len = sizeof(struct sockaddr_in);
    128 #endif
    129    sin->sin_family = AF_INET;
    130    sin->sin_port = htons(port);
    131    sin->sin_addr.s_addr = tor_addr_to_ipv4n(a);
    132    return sizeof(struct sockaddr_in);
    133  } else if (family == AF_INET6) {
    134    struct sockaddr_in6 *sin6;
    135    if (len < (int)sizeof(struct sockaddr_in6))
    136      return 0;
    137    sin6 = (struct sockaddr_in6 *)sa_out;
    138 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
    139    sin6->sin6_len = sizeof(struct sockaddr_in6);
    140 #endif
    141    sin6->sin6_family = AF_INET6;
    142    sin6->sin6_port = htons(port);
    143    memcpy(&sin6->sin6_addr, tor_addr_to_in6_assert(a),
    144           sizeof(struct in6_addr));
    145    return sizeof(struct sockaddr_in6);
    146  } else {
    147    return 0;
    148  }
    149 }
    150 
    151 /** Set address <b>a</b> to zero.  This address belongs to
    152 * the AF_UNIX family. */
    153 static void
    154 tor_addr_make_af_unix(tor_addr_t *a)
    155 {
    156  memset(a, 0, sizeof(*a));
    157  a->family = AF_UNIX;
    158 }
    159 
    160 /** Set the tor_addr_t in <b>a</b> to contain the socket address contained in
    161 * <b>sa</b>.  IF <b>port_out</b> is non-NULL and <b>sa</b> contains a port,
    162 * set *<b>port_out</b> to that port. Return 0 on success and -1 on
    163 * failure. */
    164 int
    165 tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa,
    166                       uint16_t *port_out)
    167 {
    168  tor_assert(a);
    169  tor_assert(sa);
    170 
    171  /* This memset is redundant; leaving it in to avoid any future accidents,
    172     however. */
    173  memset(a, 0, sizeof(*a));
    174 
    175  if (sa->sa_family == AF_INET) {
    176    struct sockaddr_in *sin = (struct sockaddr_in *) sa;
    177    tor_addr_from_ipv4n(a, sin->sin_addr.s_addr);
    178    if (port_out)
    179      *port_out = ntohs(sin->sin_port);
    180  } else if (sa->sa_family == AF_INET6) {
    181    struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
    182    tor_addr_from_in6(a, &sin6->sin6_addr);
    183    if (port_out)
    184      *port_out = ntohs(sin6->sin6_port);
    185  } else if (sa->sa_family == AF_UNIX) {
    186    tor_addr_make_af_unix(a);
    187    return 0;
    188  } else {
    189    tor_addr_make_unspec(a);
    190    return -1;
    191  }
    192  return 0;
    193 }
    194 
    195 /** Return a newly allocated string holding the address described in
    196 * <b>sa</b>.  AF_UNIX, AF_UNSPEC, AF_INET, and AF_INET6 are supported. */
    197 char *
    198 tor_sockaddr_to_str(const struct sockaddr *sa)
    199 {
    200  char address[TOR_ADDR_BUF_LEN];
    201  char *result;
    202  tor_addr_t addr;
    203  uint16_t port;
    204 #ifdef HAVE_SYS_UN_H
    205  if (sa->sa_family == AF_UNIX) {
    206    struct sockaddr_un *s_un = (struct sockaddr_un *)sa;
    207    tor_asprintf(&result, "unix:%s", s_un->sun_path);
    208    return result;
    209  }
    210 #endif /* defined(HAVE_SYS_UN_H) */
    211  if (sa->sa_family == AF_UNSPEC)
    212    return tor_strdup("unspec");
    213 
    214  if (tor_addr_from_sockaddr(&addr, sa, &port) < 0)
    215    return NULL;
    216  if (! tor_addr_to_str(address, &addr, sizeof(address), 1))
    217    return NULL;
    218  tor_asprintf(&result, "%s:%d", address, (int)port);
    219  return result;
    220 }
    221 
    222 /** Set address <b>a</b> to the unspecified address.  This address belongs to
    223 * no family. */
    224 void
    225 tor_addr_make_unspec(tor_addr_t *a)
    226 {
    227  memset(a, 0, sizeof(*a));
    228  a->family = AF_UNSPEC;
    229 }
    230 
    231 /** Set address <b>a</b> to the null address in address family <b>family</b>.
    232 * The null address for AF_INET is 0.0.0.0.  The null address for AF_INET6 is
    233 * [::].  AF_UNSPEC is all null. */
    234 void
    235 tor_addr_make_null(tor_addr_t *a, sa_family_t family)
    236 {
    237  memset(a, 0, sizeof(*a));
    238  a->family = family;
    239 }
    240 
    241 /** Return true iff <b>ip</b> is an IP reserved to localhost or local networks.
    242 *
    243 * If <b>ip</b> is in RFC1918 or RFC4193 or RFC4291, we will return true.
    244 * (fec0::/10, deprecated by RFC3879, is also treated as internal for now
    245 * and will return true.)
    246 *
    247 * If <b>ip</b> is 0.0.0.0 or 100.64.0.0/10 (RFC6598), we will act as:
    248 *  - Internal if <b>for_listening</b> is 0, as these addresses are not
    249 *    routable on the internet and we won't be publicly accessible to clients.
    250 *  - External if <b>for_listening</b> is 1, as clients could connect to us
    251 *    from the internet (in the case of 0.0.0.0) or a service provider's
    252 *    internal network (in the case of RFC6598).
    253 */
    254 int
    255 tor_addr_is_internal_(const tor_addr_t *addr, int for_listening,
    256                      const char *filename, int lineno)
    257 {
    258  uint32_t iph4 = 0;
    259  uint32_t iph6[4];
    260 
    261  tor_assert(addr);
    262  sa_family_t v_family = tor_addr_family(addr);
    263 
    264  if (v_family == AF_INET) {
    265    iph4 = tor_addr_to_ipv4h(addr);
    266  } else if (v_family == AF_INET6) {
    267    if (tor_addr_is_v4(addr)) { /* v4-mapped */
    268      uint32_t *addr32 = NULL;
    269      v_family = AF_INET;
    270      // Work around an incorrect NULL pointer dereference warning in
    271      // "clang --analyze" due to limited analysis depth
    272      addr32 = tor_addr_to_in6_addr32(addr);
    273      // To improve performance, wrap this assertion in:
    274      // #if !defined(__clang_analyzer__) || PARANOIA
    275      tor_assert(addr32);
    276      iph4 = ntohl(addr32[3]);
    277    }
    278  }
    279 
    280  if (v_family == AF_INET6) {
    281    const uint32_t *a32 = tor_addr_to_in6_addr32(addr);
    282    iph6[0] = ntohl(a32[0]);
    283    iph6[1] = ntohl(a32[1]);
    284    iph6[2] = ntohl(a32[2]);
    285    iph6[3] = ntohl(a32[3]);
    286    if (for_listening && !iph6[0] && !iph6[1] && !iph6[2] && !iph6[3]) /* :: */
    287      return 0;
    288 
    289    if (((iph6[0] & 0xfe000000) == 0xfc000000) || /* fc00/7  - RFC4193 */
    290        ((iph6[0] & 0xffc00000) == 0xfe800000) || /* fe80/10 - RFC4291 */
    291        ((iph6[0] & 0xffc00000) == 0xfec00000))   /* fec0/10 D- RFC3879 */
    292      return 1;
    293 
    294    if (!iph6[0] && !iph6[1] && !iph6[2] &&
    295        ((iph6[3] & 0xfffffffe) == 0x00000000))  /* ::/127 */
    296      return 1;
    297 
    298    return 0;
    299  } else if (v_family == AF_INET) {
    300    /* special case for binding to 0.0.0.0 or 100.64/10 (RFC6598) */
    301    if (for_listening && (!iph4 || ((iph4 & 0xffc00000) == 0x64400000)))
    302      return 0;
    303    if (((iph4 & 0xff000000) == 0x0a000000) || /*       10/8 */
    304        ((iph4 & 0xff000000) == 0x00000000) || /*        0/8 */
    305        ((iph4 & 0xff000000) == 0x7f000000) || /*      127/8 */
    306        ((iph4 & 0xffc00000) == 0x64400000) || /*  100.64/10 */
    307        ((iph4 & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
    308        ((iph4 & 0xfff00000) == 0xac100000) || /*  172.16/12 */
    309        ((iph4 & 0xffff0000) == 0xc0a80000))   /* 192.168/16 */
    310      return 1;
    311    return 0;
    312  }
    313 
    314  /* unknown address family... assume it's not safe for external use */
    315  /* rather than tor_assert(0) */
    316  log_warn(LD_BUG, "tor_addr_is_internal() called from %s:%d with a "
    317           "non-IP address of type %d", filename, lineno, (int)v_family);
    318  tor_fragile_assert();
    319  return 1;
    320 }
    321 
    322 /** Convert a tor_addr_t <b>addr</b> into a string, and store it in
    323 *  <b>dest</b> of size <b>len</b>.  Returns a pointer to dest on success,
    324 *  or NULL on failure.  If <b>decorate</b>, surround IPv6 addresses with
    325 *  brackets.
    326 */
    327 const char *
    328 tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
    329 {
    330  const char *ptr;
    331  tor_assert(addr && dest);
    332 
    333  switch (tor_addr_family(addr)) {
    334    case AF_INET:
    335      /* Shortest addr x.x.x.x + \0 */
    336      if (len < 8)
    337        return NULL;
    338      ptr = tor_inet_ntop(AF_INET, &addr->addr.in_addr, dest, len);
    339      break;
    340    case AF_INET6:
    341      /* Shortest addr [ :: ] + \0 */
    342      if (len < (3u + (decorate ? 2 : 0)))
    343        return NULL;
    344 
    345      if (decorate)
    346        ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest+1, len-2);
    347      else
    348        ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest, len);
    349 
    350      if (ptr && decorate) {
    351        *dest = '[';
    352        memcpy(dest+strlen(dest), "]", 2);
    353        tor_assert(ptr == dest+1);
    354        ptr = dest;
    355      }
    356      break;
    357    case AF_UNIX:
    358      tor_snprintf(dest, len, "AF_UNIX");
    359      ptr = dest;
    360      break;
    361    default:
    362      return NULL;
    363  }
    364  return ptr;
    365 }
    366 
    367 /** Parse an .in-addr.arpa or .ip6.arpa address from <b>address</b>.  Return 0
    368 * if this is not an .in-addr.arpa address or an .ip6.arpa address.  Return -1
    369 * if this is an ill-formed .in-addr.arpa address or an .ip6.arpa address.
    370 * Also return -1 if <b>family</b> is not AF_UNSPEC, and the parsed address
    371 * family does not match <b>family</b>.  On success, return 1, and store the
    372 * result, if any, into <b>result</b>, if provided.
    373 *
    374 * If <b>accept_regular</b> is set and the address is in neither recognized
    375 * reverse lookup hostname format, try parsing the address as a regular
    376 * IPv4 or IPv6 address too. This mode will accept IPv6 addresses with or
    377 * without square brackets.
    378 */
    379 int
    380 tor_addr_parse_PTR_name(tor_addr_t *result, const char *address,
    381                                   int family, int accept_regular)
    382 {
    383  if (!strcasecmpend(address, ".in-addr.arpa")) {
    384    /* We have an in-addr.arpa address. */
    385    char buf[INET_NTOA_BUF_LEN];
    386    size_t len;
    387    struct in_addr inaddr;
    388    if (family == AF_INET6)
    389      return -1;
    390 
    391    len = strlen(address) - strlen(".in-addr.arpa");
    392    if (len >= INET_NTOA_BUF_LEN)
    393      return -1; /* Too long. */
    394 
    395    memcpy(buf, address, len);
    396    buf[len] = '\0';
    397    if (tor_inet_aton(buf, &inaddr) == 0)
    398      return -1; /* malformed. */
    399 
    400    /* reverse the bytes */
    401    inaddr.s_addr = (uint32_t)
    402      (((inaddr.s_addr & 0x000000ff) << 24)
    403       |((inaddr.s_addr & 0x0000ff00) << 8)
    404       |((inaddr.s_addr & 0x00ff0000) >> 8)
    405       |((inaddr.s_addr & 0xff000000) >> 24));
    406 
    407    if (result) {
    408      tor_addr_from_in(result, &inaddr);
    409    }
    410    return 1;
    411  }
    412 
    413  if (!strcasecmpend(address, ".ip6.arpa")) {
    414    const char *cp;
    415    int n0, n1;
    416    struct in6_addr in6;
    417 
    418    if (family == AF_INET)
    419      return -1;
    420 
    421    cp = address;
    422    for (int i = 0; i < 16; ++i) {
    423      n0 = hex_decode_digit(*cp++); /* The low-order nybble appears first. */
    424      if (*cp++ != '.') return -1;  /* Then a dot. */
    425      n1 = hex_decode_digit(*cp++); /* The high-order nybble appears first. */
    426      if (*cp++ != '.') return -1;  /* Then another dot. */
    427      if (n0<0 || n1 < 0) /* Both nybbles must be hex. */
    428        return -1;
    429 
    430      /* We don't check the length of the string in here.  But that's okay,
    431       * since we already know that the string ends with ".ip6.arpa", and
    432       * there is no way to frameshift .ip6.arpa so it fits into the pattern
    433       * of hexdigit, period, hexdigit, period that we enforce above.
    434       */
    435 
    436      /* Assign from low-byte to high-byte. */
    437      in6.s6_addr[15-i] = n0 | (n1 << 4);
    438    }
    439    if (strcasecmp(cp, "ip6.arpa"))
    440      return -1;
    441 
    442    if (result) {
    443      tor_addr_from_in6(result, &in6);
    444    }
    445    return 1;
    446  }
    447 
    448  if (accept_regular) {
    449    tor_addr_t tmp;
    450    int r = tor_addr_parse(&tmp, address);
    451    if (r < 0)
    452      return 0;
    453    if (r != family && family != AF_UNSPEC)
    454      return -1;
    455 
    456    if (result)
    457      memcpy(result, &tmp, sizeof(tor_addr_t));
    458 
    459    return 1;
    460  }
    461 
    462  return 0;
    463 }
    464 
    465 /** Convert <b>addr</b> to an in-addr.arpa name or a .ip6.arpa name,
    466 * and store the result in the <b>outlen</b>-byte buffer at
    467 * <b>out</b>.  Returns a non-negative integer on success.
    468 * Returns -1 on failure. */
    469 int
    470 tor_addr_to_PTR_name(char *out, size_t outlen,
    471                     const tor_addr_t *addr)
    472 {
    473  tor_assert(out);
    474  tor_assert(addr);
    475 
    476  if (addr->family == AF_INET) {
    477    uint32_t a = tor_addr_to_ipv4h(addr);
    478 
    479    return tor_snprintf(out, outlen, "%d.%d.%d.%d.in-addr.arpa",
    480                        (int)(uint8_t)((a    )&0xff),
    481                        (int)(uint8_t)((a>>8 )&0xff),
    482                        (int)(uint8_t)((a>>16)&0xff),
    483                        (int)(uint8_t)((a>>24)&0xff));
    484  } else if (addr->family == AF_INET6) {
    485    int i;
    486    char *cp = out;
    487    const uint8_t *bytes = tor_addr_to_in6_addr8(addr);
    488    if (outlen < REVERSE_LOOKUP_NAME_BUF_LEN)
    489      return -1;
    490    for (i = 15; i >= 0; --i) {
    491      uint8_t byte = bytes[i];
    492      *cp++ = "0123456789abcdef"[byte & 0x0f];
    493      *cp++ = '.';
    494      *cp++ = "0123456789abcdef"[byte >> 4];
    495      *cp++ = '.';
    496    }
    497    memcpy(cp, "ip6.arpa", 9); /* 8 characters plus NUL */
    498    return 32 * 2 + 8;
    499  }
    500  return -1;
    501 }
    502 
    503 /** Parse a string <b>s</b> containing an IPv4/IPv6 address, and possibly
    504 *  a mask and port or port range.  Store the parsed address in
    505 *  <b>addr_out</b>, a mask (if any) in <b>mask_out</b>, and port(s) (if any)
    506 *  in <b>port_min_out</b> and <b>port_max_out</b>.
    507 *
    508 * The syntax is:
    509 *   Address OptMask OptPortRange
    510 *   Address ::= IPv4Address / "[" IPv6Address "]" / "*"
    511 *   OptMask ::= "/" Integer /
    512 *   OptPortRange ::= ":*" / ":" Integer / ":" Integer "-" Integer /
    513 *
    514 *  - If mask, minport, or maxport are NULL, we do not want these
    515 *    options to be set; treat them as an error if present.
    516 *  - If the string has no mask, the mask is set to /32 (IPv4) or /128 (IPv6).
    517 *  - If the string has one port, it is placed in both min and max port
    518 *    variables.
    519 *  - If the string has no port(s), port_(min|max)_out are set to 1 and 65535.
    520 *
    521 *  Return an address family on success, or -1 if an invalid address string is
    522 *  provided.
    523 *
    524 *  If 'flags & TAPMP_EXTENDED_STAR' is false, then the wildcard address '*'
    525 *  yield an IPv4 wildcard.
    526 *
    527 *  If 'flags & TAPMP_EXTENDED_STAR' is true, then the wildcard address '*'
    528 *  yields an AF_UNSPEC wildcard address, which expands to corresponding
    529 *  wildcard IPv4 and IPv6 rules, and the following change is made
    530 *  in the grammar above:
    531 *   Address ::= IPv4Address / "[" IPv6Address "]" / "*" / "*4" / "*6"
    532 *  with the new "*4" and "*6" productions creating a wildcard to match
    533 *  IPv4 or IPv6 addresses.
    534 *
    535 *  If 'flags & TAPMP_EXTENDED_STAR' and 'flags & TAPMP_STAR_IPV4_ONLY' are
    536 *  both true, then the wildcard address '*' yields an IPv4 wildcard.
    537 *
    538 *  If 'flags & TAPMP_EXTENDED_STAR' and 'flags & TAPMP_STAR_IPV6_ONLY' are
    539 *  both true, then the wildcard address '*' yields an IPv6 wildcard.
    540 *
    541 * TAPMP_STAR_IPV4_ONLY and TAPMP_STAR_IPV6_ONLY are mutually exclusive. */
    542 int
    543 tor_addr_parse_mask_ports(const char *s,
    544                          unsigned flags,
    545                          tor_addr_t *addr_out,
    546                          maskbits_t *maskbits_out,
    547                          uint16_t *port_min_out, uint16_t *port_max_out)
    548 {
    549  char *base = NULL, *address, *mask = NULL, *port = NULL, *rbracket = NULL;
    550  char *endptr;
    551  int any_flag=0, v4map=0;
    552  sa_family_t family;
    553  struct in6_addr in6_tmp;
    554  struct in_addr in_tmp = { .s_addr = 0 };
    555 
    556  tor_assert(s);
    557  tor_assert(addr_out);
    558  /* We can either only want an IPv4 address or only want an IPv6 address,
    559   * but we can't only want IPv4 & IPv6 at the same time. */
    560  tor_assert(!((flags & TAPMP_STAR_IPV4_ONLY)
    561               && (flags & TAPMP_STAR_IPV6_ONLY)));
    562 
    563  /** Longest possible length for an address, mask, and port-range combination.
    564   * Includes IP, [], /mask, :, ports */
    565 #define MAX_ADDRESS_LENGTH (TOR_ADDR_BUF_LEN+2+(1+INET_NTOA_BUF_LEN)+12+1)
    566 
    567  if (strlen(s) > MAX_ADDRESS_LENGTH) {
    568    log_warn(LD_GENERAL, "Impossibly long IP %s; rejecting", escaped(s));
    569    goto err;
    570  }
    571  base = tor_strdup(s);
    572 
    573  /* Break 'base' into separate strings. */
    574  address = base;
    575  if (*address == '[') {  /* Probably IPv6 */
    576    address++;
    577    rbracket = strchr(address, ']');
    578    if (!rbracket) {
    579      log_warn(LD_GENERAL,
    580               "No closing IPv6 bracket in address pattern; rejecting.");
    581      goto err;
    582    }
    583  }
    584  mask = strchr((rbracket?rbracket:address),'/');
    585  port = strchr((mask?mask:(rbracket?rbracket:address)), ':');
    586  if (port)
    587    *port++ = '\0';
    588  if (mask)
    589    *mask++ = '\0';
    590  if (rbracket)
    591    *rbracket = '\0';
    592  if (port && mask)
    593    tor_assert(port > mask);
    594  if (mask && rbracket)
    595    tor_assert(mask > rbracket);
    596 
    597  /* Now "address" is the a.b.c.d|'*'|abcd::1 part...
    598   *     "mask" is the Mask|Maskbits part...
    599   * and "port" is the *|port|min-max part.
    600   */
    601 
    602  /* Process the address portion */
    603  memset(addr_out, 0, sizeof(tor_addr_t));
    604 
    605  if (!strcmp(address, "*")) {
    606    if (flags & TAPMP_EXTENDED_STAR) {
    607      if (flags & TAPMP_STAR_IPV4_ONLY) {
    608        family = AF_INET;
    609        tor_addr_from_ipv4h(addr_out, 0);
    610      } else if (flags & TAPMP_STAR_IPV6_ONLY) {
    611        static uint8_t nil_bytes[16] =
    612          { [0]=0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };
    613        family = AF_INET6;
    614        tor_addr_from_ipv6_bytes(addr_out, nil_bytes);
    615      } else {
    616        family = AF_UNSPEC;
    617        tor_addr_make_unspec(addr_out);
    618        log_info(LD_GENERAL,
    619                 "'%s' expands into rules which apply to all IPv4 and IPv6 "
    620                 "addresses. (Use accept/reject *4:* for IPv4 or "
    621                 "accept[6]/reject[6] *6:* for IPv6.)", s);
    622      }
    623    } else {
    624      family = AF_INET;
    625      tor_addr_from_ipv4h(addr_out, 0);
    626    }
    627    any_flag = 1;
    628  } else if (!strcmp(address, "*4") && (flags & TAPMP_EXTENDED_STAR)) {
    629    family = AF_INET;
    630    tor_addr_from_ipv4h(addr_out, 0);
    631    any_flag = 1;
    632  } else if (!strcmp(address, "*6") && (flags & TAPMP_EXTENDED_STAR)) {
    633    static uint8_t nil_bytes[16] = { [0]=0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };
    634    family = AF_INET6;
    635    tor_addr_from_ipv6_bytes(addr_out, nil_bytes);
    636    any_flag = 1;
    637  } else if (tor_inet_pton(AF_INET6, address, &in6_tmp) > 0) {
    638    family = AF_INET6;
    639    tor_addr_from_in6(addr_out, &in6_tmp);
    640  } else if (tor_inet_pton(AF_INET, address, &in_tmp) > 0) {
    641    family = AF_INET;
    642    tor_addr_from_in(addr_out, &in_tmp);
    643  } else {
    644    log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
    645             escaped(address));
    646    goto err;
    647  }
    648 
    649  v4map = tor_addr_is_v4(addr_out);
    650 
    651  /* Parse mask */
    652  if (maskbits_out) {
    653    int bits = 0;
    654    struct in_addr v4mask;
    655 
    656    if (mask) {  /* the caller (tried to) specify a mask */
    657      bits = (int) strtol(mask, &endptr, 10);
    658      if (!*endptr) {  /* strtol converted everything, so it was an integer */
    659        if ((bits<0 || bits>128) ||
    660            (family == AF_INET && bits > 32)) {
    661          log_warn(LD_GENERAL,
    662                   "Bad number of mask bits (%d) on address range; rejecting.",
    663                   bits);
    664          goto err;
    665        }
    666      } else {  /* mask might still be an address-style mask */
    667        if (tor_inet_pton(AF_INET, mask, &v4mask) > 0) {
    668          bits = addr_mask_get_bits(ntohl(v4mask.s_addr));
    669          if (bits < 0) {
    670            log_warn(LD_GENERAL,
    671                     "IPv4-style mask %s is not a prefix address; rejecting.",
    672                     escaped(mask));
    673            goto err;
    674          }
    675        } else { /* Not IPv4; we don't do address-style IPv6 masks. */
    676          log_warn(LD_GENERAL,
    677                   "Malformed mask on address range %s; rejecting.",
    678                   escaped(s));
    679          goto err;
    680        }
    681      }
    682      if (family == AF_INET6 && v4map) {
    683        if (bits > 32 && bits < 96) { /* Crazy */
    684          log_warn(LD_GENERAL,
    685                   "Bad mask bits %d for V4-mapped V6 address; rejecting.",
    686                   bits);
    687          goto err;
    688        }
    689        /* XXXX_IP6 is this really what we want? */
    690        bits = 96 + bits%32; /* map v4-mapped masks onto 96-128 bits */
    691      }
    692      if (any_flag) {
    693        log_warn(LD_GENERAL,
    694                 "Found bit prefix with wildcard address; rejecting");
    695        goto err;
    696      }
    697    } else { /* pick an appropriate mask, as none was given */
    698      if (any_flag)
    699        bits = 0;  /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */
    700      else if (tor_addr_family(addr_out) == AF_INET)
    701        bits = 32;
    702      else if (tor_addr_family(addr_out) == AF_INET6)
    703        bits = 128;
    704    }
    705    *maskbits_out = (maskbits_t) bits;
    706  } else {
    707    if (mask) {
    708      log_warn(LD_GENERAL,
    709               "Unexpected mask in address %s; rejecting", escaped(s));
    710      goto err;
    711    }
    712  }
    713 
    714  /* Parse port(s) */
    715  if (port_min_out) {
    716    uint16_t port2;
    717    if (!port_max_out) /* caller specified one port; fake the second one */
    718      port_max_out = &port2;
    719 
    720    if (parse_port_range(port, port_min_out, port_max_out) < 0) {
    721      goto err;
    722    } else if ((*port_min_out != *port_max_out) && port_max_out == &port2) {
    723      log_warn(LD_GENERAL,
    724               "Wanted one port from address range, but there are two.");
    725 
    726      port_max_out = NULL;  /* caller specified one port, so set this back */
    727      goto err;
    728    }
    729  } else {
    730    if (port) {
    731      log_warn(LD_GENERAL,
    732               "Unexpected ports in address %s; rejecting", escaped(s));
    733      goto err;
    734    }
    735  }
    736 
    737  tor_free(base);
    738  return tor_addr_family(addr_out);
    739 err:
    740  tor_free(base);
    741  return -1;
    742 }
    743 
    744 /** Determine whether an address is IPv4, either native or IPv4-mapped IPv6.
    745 * Note that this is about representation only, as any decent stack will
    746 * reject IPv4-mapped addresses received on the wire (and won't use them
    747 * on the wire either).
    748 */
    749 int
    750 tor_addr_is_v4(const tor_addr_t *addr)
    751 {
    752  tor_assert(addr);
    753 
    754  if (tor_addr_family(addr) == AF_INET)
    755    return 1;
    756 
    757  if (tor_addr_family(addr) == AF_INET6) {
    758    /* First two don't need to be ordered */
    759    uint32_t *a32 = tor_addr_to_in6_addr32(addr);
    760    if (a32[0] == 0 && a32[1] == 0 && ntohl(a32[2]) == 0x0000ffffu)
    761      return 1;
    762  }
    763 
    764  return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */
    765 }
    766 
    767 /** Determine whether an address <b>addr</b> is an IPv6 (AF_INET6). Return
    768 * true if so else false. */
    769 int
    770 tor_addr_is_v6(const tor_addr_t *addr)
    771 {
    772  tor_assert(addr);
    773  return (tor_addr_family(addr) == AF_INET6);
    774 }
    775 
    776 /** Determine whether an address <b>addr</b> is null, either all zeroes or
    777 *  belonging to family AF_UNSPEC.
    778 */
    779 int
    780 tor_addr_is_null(const tor_addr_t *addr)
    781 {
    782  tor_assert(addr);
    783 
    784  switch (tor_addr_family(addr)) {
    785    case AF_INET6: {
    786      uint32_t *a32 = tor_addr_to_in6_addr32(addr);
    787      return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 0);
    788    }
    789    case AF_INET:
    790      return (tor_addr_to_ipv4n(addr) == 0);
    791    case AF_UNIX:
    792      return 1;
    793    case AF_UNSPEC:
    794      return 1;
    795    default:
    796      log_warn(LD_BUG, "Called with unknown address family %d",
    797               (int)tor_addr_family(addr));
    798      return 0;
    799  }
    800  //return 1;
    801 }
    802 
    803 /** Return true iff <b>addr</b> is a loopback address */
    804 int
    805 tor_addr_is_loopback(const tor_addr_t *addr)
    806 {
    807  tor_assert(addr);
    808  switch (tor_addr_family(addr)) {
    809    case AF_INET6: {
    810      /* ::1 */
    811      uint32_t *a32 = tor_addr_to_in6_addr32(addr);
    812      return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) &&
    813        (ntohl(a32[3]) == 1);
    814    }
    815    case AF_INET:
    816      /* 127.0.0.1 */
    817      return (tor_addr_to_ipv4h(addr) & 0xff000000) == 0x7f000000;
    818    case AF_UNSPEC:
    819      return 0;
    820      /* LCOV_EXCL_START */
    821    default:
    822      tor_fragile_assert();
    823      return 0;
    824      /* LCOV_EXCL_STOP */
    825  }
    826 }
    827 
    828 /* Is addr valid?
    829 * Checks that addr is non-NULL and not tor_addr_is_null().
    830 * If for_listening is true, all IPv4 and IPv6 addresses are valid, including
    831 * 0.0.0.0 (for IPv4) and :: (for IPv6). When listening, these addresses mean
    832 * "bind to all addresses on the local machine".
    833 * Otherwise, 0.0.0.0 and ::  are invalid, because they are null addresses.
    834 * All unspecified and unix addresses are invalid, regardless of for_listening.
    835 */
    836 int
    837 tor_addr_is_valid(const tor_addr_t *addr, int for_listening)
    838 {
    839  /* NULL addresses are invalid regardless of for_listening */
    840  if (addr == NULL) {
    841    return 0;
    842  }
    843 
    844  /* Allow all IPv4 and IPv6 addresses, when for_listening is true */
    845  if (for_listening) {
    846    if (addr->family == AF_INET || addr->family == AF_INET6) {
    847      return 1;
    848    }
    849  }
    850 
    851  /* Otherwise, the address is valid if it's not tor_addr_is_null() */
    852  return !tor_addr_is_null(addr);
    853 }
    854 
    855 /* Is the network-order IPv4 address v4n_addr valid?
    856 * Checks that addr is not zero.
    857 * Except if for_listening is true, where IPv4 addr 0.0.0.0 is allowed. */
    858 int
    859 tor_addr_is_valid_ipv4n(uint32_t v4n_addr, int for_listening)
    860 {
    861  /* Any IPv4 address is valid with for_listening. */
    862  if (for_listening) {
    863    return 1;
    864  }
    865 
    866  /* Otherwise, zero addresses are invalid. */
    867  return v4n_addr != 0;
    868 }
    869 
    870 /* Is port valid?
    871 * Checks that port is not 0.
    872 * Except if for_listening is true, where port 0 is allowed.
    873 * It means "OS chooses a port". */
    874 int
    875 tor_port_is_valid(uint16_t port, int for_listening)
    876 {
    877  /* Any port value is valid with for_listening. */
    878  if (for_listening) {
    879    return 1;
    880  }
    881 
    882  /* Otherwise, zero ports are invalid. */
    883  return port != 0;
    884 }
    885 
    886 /** Set <b>dest</b> to equal the IPv4 address in <b>v4addr</b> (given in
    887 * network order). */
    888 void
    889 tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
    890 {
    891  tor_assert(dest);
    892  memset(dest, 0, sizeof(tor_addr_t));
    893  dest->family = AF_INET;
    894  dest->addr.in_addr.s_addr = v4addr;
    895 }
    896 
    897 /** Set <b>dest</b> to equal the IPv6 address in the 16 bytes at
    898 * <b>ipv6_bytes</b>. */
    899 void
    900 tor_addr_from_ipv6_bytes(tor_addr_t *dest, const uint8_t *ipv6_bytes)
    901 {
    902  tor_assert(dest);
    903  tor_assert(ipv6_bytes);
    904  memset(dest, 0, sizeof(tor_addr_t));
    905  dest->family = AF_INET6;
    906  memcpy(dest->addr.in6_addr.s6_addr, ipv6_bytes, 16);
    907 }
    908 
    909 /** Set <b>dest</b> equal to the IPv6 address in the in6_addr <b>in6</b>. */
    910 void
    911 tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
    912 {
    913  tor_addr_from_ipv6_bytes(dest, in6->s6_addr);
    914 }
    915 
    916 /** Set the 16 bytes at <b>dest</b> to equal the IPv6 address <b>src</b>.
    917 * <b>src</b> must be an IPv6 address, if it is not, log a warning, and clear
    918 * <b>dest</b>. */
    919 void
    920 tor_addr_copy_ipv6_bytes(uint8_t *dest, const tor_addr_t *src)
    921 {
    922  tor_assert(dest);
    923  tor_assert(src);
    924  memset(dest, 0, 16);
    925  IF_BUG_ONCE(src->family != AF_INET6)
    926    return;
    927  memcpy(dest, src->addr.in6_addr.s6_addr, 16);
    928 }
    929 
    930 /** Copy a tor_addr_t from <b>src</b> to <b>dest</b>.
    931 */
    932 void
    933 tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
    934 {
    935  if (src == dest)
    936    return;
    937  tor_assert(src);
    938  tor_assert(dest);
    939  memcpy(dest, src, sizeof(tor_addr_t));
    940 }
    941 
    942 /** Copy a tor_addr_t from <b>src</b> to <b>dest</b>, taking extra care to
    943 * copy only the well-defined portions. Used for computing hashes of
    944 * addresses.
    945 */
    946 void
    947 tor_addr_copy_tight(tor_addr_t *dest, const tor_addr_t *src)
    948 {
    949  tor_assert(src != dest);
    950  tor_assert(src);
    951  tor_assert(dest);
    952  memset(dest, 0, sizeof(tor_addr_t));
    953  dest->family = src->family;
    954  switch (tor_addr_family(src))
    955    {
    956    case AF_INET:
    957      dest->addr.in_addr.s_addr = src->addr.in_addr.s_addr;
    958      break;
    959    case AF_INET6:
    960      memcpy(dest->addr.in6_addr.s6_addr, src->addr.in6_addr.s6_addr, 16);
    961      break;
    962    case AF_UNSPEC:
    963      break;
    964      // LCOV_EXCL_START
    965    default:
    966      tor_fragile_assert();
    967      // LCOV_EXCL_STOP
    968    }
    969 }
    970 
    971 /** Given two addresses <b>addr1</b> and <b>addr2</b>, return 0 if the two
    972 * addresses are equivalent under the mask mbits, less than 0 if addr1
    973 * precedes addr2, and greater than 0 otherwise.
    974 *
    975 * Different address families (IPv4 vs IPv6) are always considered unequal if
    976 * <b>how</b> is CMP_EXACT; otherwise, IPv6-mapped IPv4 addresses are
    977 * considered equivalent to their IPv4 equivalents.
    978 *
    979 * As a special case, all pointer-wise distinct AF_UNIX addresses are always
    980 * considered unequal since tor_addr_t currently does not contain the
    981 * information required to make the comparison.
    982 */
    983 int
    984 tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2,
    985                 tor_addr_comparison_t how)
    986 {
    987  return tor_addr_compare_masked(addr1, addr2, 128, how);
    988 }
    989 
    990 /** As tor_addr_compare(), but only looks at the first <b>mask</b> bits of
    991 * the address.
    992 *
    993 * Reduce over-specific masks (>128 for ipv6, >32 for ipv4) to 128 or 32.
    994 *
    995 * The mask is interpreted relative to <b>addr1</b>, so that if a is
    996 * \::ffff:1.2.3.4, and b is 3.4.5.6,
    997 * tor_addr_compare_masked(a,b,100,CMP_SEMANTIC) is the same as
    998 * -tor_addr_compare_masked(b,a,4,CMP_SEMANTIC).
    999 *
   1000 * We guarantee that the ordering from tor_addr_compare_masked is a total
   1001 * order on addresses, but not that it is any particular order, or that it
   1002 * will be the same from one version to the next.
   1003 */
   1004 int
   1005 tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2,
   1006                        maskbits_t mbits, tor_addr_comparison_t how)
   1007 {
   1008  /** Helper: Evaluates to -1 if a is less than b, 0 if a equals b, or 1 if a
   1009   * is greater than b.  May evaluate a and b more than once.  */
   1010 #define TRISTATE(a,b) (((a)<(b))?-1: (((a)==(b))?0:1))
   1011  sa_family_t family1, family2, v_family1, v_family2;
   1012 
   1013  tor_assert(addr1 && addr2);
   1014 
   1015  v_family1 = family1 = tor_addr_family(addr1);
   1016  v_family2 = family2 = tor_addr_family(addr2);
   1017 
   1018  if (family1==family2) {
   1019    /* When the families are the same, there's only one way to do the
   1020     * comparison: exactly. */
   1021    int r;
   1022    switch (family1) {
   1023      case AF_UNSPEC:
   1024        return 0; /* All unspecified addresses are equal */
   1025      case AF_INET: {
   1026        uint32_t a1 = tor_addr_to_ipv4h(addr1);
   1027        uint32_t a2 = tor_addr_to_ipv4h(addr2);
   1028        if (mbits <= 0)
   1029          return 0;
   1030        if (mbits > 32)
   1031          mbits = 32;
   1032        a1 >>= (32-mbits);
   1033        a2 >>= (32-mbits);
   1034        r = TRISTATE(a1, a2);
   1035        return r;
   1036      }
   1037      case AF_INET6: {
   1038        if (mbits > 128)
   1039          mbits = 128;
   1040 
   1041        const uint8_t *a1 = tor_addr_to_in6_addr8(addr1);
   1042        const uint8_t *a2 = tor_addr_to_in6_addr8(addr2);
   1043        const int bytes = mbits >> 3;
   1044        const int leftover_bits = mbits & 7;
   1045        if (bytes && (r = tor_memcmp(a1, a2, bytes))) {
   1046          return r;
   1047        } else if (leftover_bits) {
   1048          uint8_t b1 = a1[bytes] >> (8-leftover_bits);
   1049          uint8_t b2 = a2[bytes] >> (8-leftover_bits);
   1050          return TRISTATE(b1, b2);
   1051        } else {
   1052          return 0;
   1053        }
   1054      }
   1055      case AF_UNIX:
   1056        /* HACKHACKHACKHACKHACK:
   1057         * tor_addr_t doesn't contain a copy of sun_path, so it's not
   1058         * possible to compare this at all.
   1059         *
   1060         * Since the only time we currently actually should be comparing
   1061         * 2 AF_UNIX addresses is when dealing with ISO_CLIENTADDR (which
   1062         * is disabled for AF_UNIX SocksPorts anyway), this just does
   1063         * a pointer comparison.
   1064         *
   1065         * See: #20261.
   1066         */
   1067        if (addr1 < addr2)
   1068          return -1;
   1069        else if (addr1 == addr2)
   1070          return 0;
   1071        else
   1072          return 1;
   1073        /* LCOV_EXCL_START */
   1074      default:
   1075        tor_fragile_assert();
   1076        return 0;
   1077        /* LCOV_EXCL_STOP */
   1078    }
   1079  } else if (how == CMP_EXACT) {
   1080    /* Unequal families and an exact comparison?  Stop now! */
   1081    return TRISTATE(family1, family2);
   1082  }
   1083 
   1084  if (mbits == 0)
   1085    return 0;
   1086 
   1087  if (family1 == AF_INET6 && tor_addr_is_v4(addr1))
   1088    v_family1 = AF_INET;
   1089  if (family2 == AF_INET6 && tor_addr_is_v4(addr2))
   1090    v_family2 = AF_INET;
   1091  if (v_family1 == v_family2) {
   1092    /* One or both addresses are a mapped ipv4 address. */
   1093    uint32_t a1, a2;
   1094    if (family1 == AF_INET6) {
   1095      a1 = tor_addr_to_mapped_ipv4h(addr1);
   1096      if (mbits <= 96)
   1097        return 0;
   1098      mbits -= 96; /* We just decided that the first 96 bits of a1 "match". */
   1099    } else {
   1100      a1 = tor_addr_to_ipv4h(addr1);
   1101    }
   1102    if (family2 == AF_INET6) {
   1103      a2 = tor_addr_to_mapped_ipv4h(addr2);
   1104    } else {
   1105      a2 = tor_addr_to_ipv4h(addr2);
   1106    }
   1107    if (mbits > 32) mbits = 32;
   1108    a1 >>= (32-mbits);
   1109    a2 >>= (32-mbits);
   1110    return TRISTATE(a1, a2);
   1111  } else {
   1112    /* Unequal families, and semantic comparison, and no semantic family
   1113     * matches. */
   1114    return TRISTATE(family1, family2);
   1115  }
   1116 }
   1117 
   1118 /** Input for siphash, to produce some output for an unspec value. */
   1119 static const uint32_t unspec_hash_input[] = { 0x4e4df09f, 0x92985342 };
   1120 
   1121 /** Return a hash code based on the address addr. DOCDOC extra */
   1122 uint64_t
   1123 tor_addr_hash(const tor_addr_t *addr)
   1124 {
   1125  switch (tor_addr_family(addr)) {
   1126  case AF_INET:
   1127    return siphash24g(&addr->addr.in_addr.s_addr, 4);
   1128  case AF_UNSPEC:
   1129    return siphash24g(unspec_hash_input, sizeof(unspec_hash_input));
   1130  case AF_INET6:
   1131    return siphash24g(&addr->addr.in6_addr.s6_addr, 16);
   1132    /* LCOV_EXCL_START */
   1133  default:
   1134    tor_fragile_assert();
   1135    return 0;
   1136    /* LCOV_EXCL_STOP */
   1137  }
   1138 }
   1139 
   1140 /** As tor_addr_hash, but use a particular siphash key. */
   1141 uint64_t
   1142 tor_addr_keyed_hash(const struct sipkey *key, const tor_addr_t *addr)
   1143 {
   1144  /* This is duplicate code with tor_addr_hash, since this function needs to
   1145   * be backportable all the way to 0.2.9. */
   1146 
   1147  switch (tor_addr_family(addr)) {
   1148  case AF_INET:
   1149    return siphash24(&addr->addr.in_addr.s_addr, 4, key);
   1150  case AF_UNSPEC:
   1151    return siphash24(unspec_hash_input, sizeof(unspec_hash_input), key);
   1152  case AF_INET6:
   1153    return siphash24(&addr->addr.in6_addr.s6_addr, 16, key);
   1154  default:
   1155    /* LCOV_EXCL_START */
   1156    tor_fragile_assert();
   1157    return 0;
   1158    /* LCOV_EXCL_STOP */
   1159  }
   1160 }
   1161 
   1162 /** Return a newly allocated string with a representation of <b>addr</b>. */
   1163 char *
   1164 tor_addr_to_str_dup(const tor_addr_t *addr)
   1165 {
   1166  char buf[TOR_ADDR_BUF_LEN];
   1167  if (tor_addr_to_str(buf, addr, sizeof(buf), 0)) {
   1168    return tor_strdup(buf);
   1169  } else {
   1170    return tor_strdup("<unknown address type>");
   1171  }
   1172 }
   1173 
   1174 /** Return a string representing the address <b>addr</b>.  This string
   1175 * is statically allocated, and must not be freed.  Each call to
   1176 * <b>fmt_addr_impl</b> invalidates the last result of the function.
   1177 * This function is not thread-safe. If <b>decorate</b> is set, add
   1178 * brackets to IPv6 addresses.
   1179 *
   1180 * It's better to use the wrapper macros of this function:
   1181 * <b>fmt_addr()</b> and <b>fmt_and_decorate_addr()</b>.
   1182 */
   1183 const char *
   1184 fmt_addr_impl(const tor_addr_t *addr, int decorate)
   1185 {
   1186  static char buf[TOR_ADDR_BUF_LEN];
   1187  if (!addr) return "<null>";
   1188  if (tor_addr_to_str(buf, addr, sizeof(buf), decorate))
   1189    return buf;
   1190  else
   1191    return "???";
   1192 }
   1193 
   1194 /** Return a string representing the pair <b>addr</b> and <b>port</b>.
   1195 * This calls fmt_and_decorate_addr internally, so IPv6 addresses will
   1196 * have brackets, and the caveats of fmt_addr_impl apply.
   1197 */
   1198 const char *
   1199 fmt_addrport(const tor_addr_t *addr, uint16_t port)
   1200 {
   1201  static char buf[TOR_ADDRPORT_BUF_LEN];
   1202  tor_snprintf(buf, sizeof(buf), "%s:%u", fmt_and_decorate_addr(addr), port);
   1203  return buf;
   1204 }
   1205 
   1206 /** Like fmt_addr(), but takes <b>addr</b> as a host-order IPv4
   1207 * addresses. Also not thread-safe, also clobbers its return buffer on
   1208 * repeated calls. Clean internal buffer and return empty string on failure. */
   1209 const char *
   1210 fmt_addr32(uint32_t addr)
   1211 {
   1212  static char buf[INET_NTOA_BUF_LEN];
   1213  struct in_addr in;
   1214  int success;
   1215 
   1216  in.s_addr = htonl(addr);
   1217 
   1218  success = tor_inet_ntoa(&in, buf, sizeof(buf));
   1219  tor_assertf_nonfatal(success >= 0,
   1220      "Failed to convert IP 0x%08X (HBO) to string", addr);
   1221 
   1222  IF_BUG_ONCE(success < 0) {
   1223    memset(buf, 0, INET_NTOA_BUF_LEN);
   1224  }
   1225 
   1226  return buf;
   1227 }
   1228 
   1229 /** Like fmt_addrport(), but takes <b>addr</b> as a host-order IPv4
   1230 * addresses. Also not thread-safe, also clobbers its return buffer on
   1231 * repeated calls. */
   1232 const char *
   1233 fmt_addr32_port(uint32_t addr, uint16_t port)
   1234 {
   1235  static char buf[INET_NTOA_BUF_LEN + 6];
   1236  snprintf(buf, sizeof(buf), "%s:%u", fmt_addr32(addr), port);
   1237  return buf;
   1238 }
   1239 
   1240 /** Return a string representing <b>family</b>.
   1241 *
   1242 * This string is a string constant, and must not be freed.
   1243 * This function is thread-safe.
   1244 */
   1245 const char *
   1246 fmt_af_family(sa_family_t family)
   1247 {
   1248  static int default_bug_once = 0;
   1249 
   1250  switch (family) {
   1251    case AF_INET6:
   1252      return "IPv6";
   1253    case AF_INET:
   1254      return "IPv4";
   1255    case AF_UNIX:
   1256      return "UNIX socket";
   1257    case AF_UNSPEC:
   1258      return "unspecified";
   1259    default:
   1260      if (!default_bug_once) {
   1261        log_warn(LD_BUG, "Called with unknown address family %d",
   1262                 (int)family);
   1263        default_bug_once = 1;
   1264      }
   1265      return "unknown";
   1266  }
   1267  //return "(unreachable code)";
   1268 }
   1269 
   1270 /** Return a string representing the family of <b>addr</b>.
   1271 *
   1272 * This string is a string constant, and must not be freed.
   1273 * This function is thread-safe.
   1274 */
   1275 const char *
   1276 fmt_addr_family(const tor_addr_t *addr)
   1277 {
   1278  IF_BUG_ONCE(!addr)
   1279    return "NULL pointer";
   1280 
   1281  return fmt_af_family(tor_addr_family(addr));
   1282 }
   1283 
   1284 /** Convert the string in <b>src</b> to a tor_addr_t <b>addr</b>.  The string
   1285 * may be an IPv4 address, or an IPv6 address surrounded by square brackets.
   1286 *
   1287 * If <b>allow_ipv6_without_brackets</b> is true, also allow IPv6 addresses
   1288 * without brackets.
   1289 *
   1290 * Always rejects IPv4 addresses with brackets.
   1291 *
   1292 * Returns an address family on success, or -1 if an invalid address string is
   1293 * provided. */
   1294 static int
   1295 tor_addr_parse_impl(tor_addr_t *addr, const char *src,
   1296                    bool allow_ipv6_without_brackets)
   1297 {
   1298  /* Holds substring of IPv6 address after removing square brackets */
   1299  char *tmp = NULL;
   1300  int result = -1;
   1301  struct in_addr in_tmp;
   1302  struct in6_addr in6_tmp;
   1303  int brackets_detected = 0;
   1304 
   1305  tor_assert(addr && src);
   1306 
   1307  size_t len = strlen(src);
   1308 
   1309  if (len && src[0] == '[' && src[len - 1] == ']') {
   1310    brackets_detected = 1;
   1311    src = tmp = tor_strndup(src+1, strlen(src)-2);
   1312  }
   1313 
   1314  /* Try to parse an IPv6 address if it has brackets, or if IPv6 addresses
   1315   * without brackets are allowed */
   1316  if (brackets_detected || allow_ipv6_without_brackets) {
   1317    if (tor_inet_pton(AF_INET6, src, &in6_tmp) > 0) {
   1318      result = AF_INET6;
   1319      tor_addr_from_in6(addr, &in6_tmp);
   1320    }
   1321  }
   1322 
   1323  /* Try to parse an IPv4 address without brackets */
   1324  if (!brackets_detected) {
   1325    if (tor_inet_pton(AF_INET, src, &in_tmp) > 0) {
   1326      result = AF_INET;
   1327      tor_addr_from_in(addr, &in_tmp);
   1328    }
   1329  }
   1330 
   1331  /* Clear the address on error, to avoid returning uninitialised or partly
   1332   * parsed data.
   1333   */
   1334  if (result == -1) {
   1335    memset(addr, 0, sizeof(tor_addr_t));
   1336  }
   1337 
   1338  tor_free(tmp);
   1339  return result;
   1340 }
   1341 
   1342 /** Convert the string in <b>src</b> to a tor_addr_t <b>addr</b>.  The string
   1343 * may be an IPv4 address, an IPv6 address, or an IPv6 address surrounded by
   1344 * square brackets.
   1345 *
   1346 * Returns an address family on success, or -1 if an invalid address string is
   1347 * provided. */
   1348 int
   1349 tor_addr_parse(tor_addr_t *addr, const char *src)
   1350 {
   1351  return tor_addr_parse_impl(addr, src, 1);
   1352 }
   1353 
   1354 #ifdef HAVE_IFADDRS_TO_SMARTLIST
   1355 /*
   1356 * Convert a linked list consisting of <b>ifaddrs</b> structures
   1357 * into smartlist of <b>tor_addr_t</b> structures.
   1358 */
   1359 STATIC smartlist_t *
   1360 ifaddrs_to_smartlist(const struct ifaddrs *ifa, sa_family_t family)
   1361 {
   1362  smartlist_t *result = smartlist_new();
   1363  const struct ifaddrs *i;
   1364 
   1365  for (i = ifa; i; i = i->ifa_next) {
   1366    tor_addr_t tmp;
   1367    if ((i->ifa_flags & (IFF_UP | IFF_RUNNING)) != (IFF_UP | IFF_RUNNING))
   1368      continue;
   1369    if (!i->ifa_addr)
   1370      continue;
   1371    if (i->ifa_addr->sa_family != AF_INET &&
   1372        i->ifa_addr->sa_family != AF_INET6)
   1373      continue;
   1374    if (family != AF_UNSPEC && i->ifa_addr->sa_family != family)
   1375      continue;
   1376    if (tor_addr_from_sockaddr(&tmp, i->ifa_addr, NULL) < 0)
   1377      continue;
   1378    smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
   1379  }
   1380 
   1381  return result;
   1382 }
   1383 
   1384 /** Use getiffaddrs() function to get list of current machine
   1385 * network interface addresses. Represent the result by smartlist of
   1386 * <b>tor_addr_t</b> structures.
   1387 */
   1388 STATIC smartlist_t *
   1389 get_interface_addresses_ifaddrs(int severity, sa_family_t family)
   1390 {
   1391 
   1392  /* Most free Unixy systems provide getifaddrs, which gives us a linked list
   1393   * of struct ifaddrs. */
   1394  struct ifaddrs *ifa = NULL;
   1395  smartlist_t *result;
   1396  if (getifaddrs(&ifa) < 0) {
   1397    log_fn(severity, LD_NET, "Unable to call getifaddrs(): %s",
   1398           strerror(errno));
   1399    return NULL;
   1400  }
   1401 
   1402  result = ifaddrs_to_smartlist(ifa, family);
   1403 
   1404  freeifaddrs(ifa);
   1405 
   1406  return result;
   1407 }
   1408 #endif /* defined(HAVE_IFADDRS_TO_SMARTLIST) */
   1409 
   1410 #ifdef HAVE_IP_ADAPTER_TO_SMARTLIST
   1411 
   1412 /** Convert a Windows-specific <b>addresses</b> linked list into smartlist
   1413 * of <b>tor_addr_t</b> structures.
   1414 */
   1415 
   1416 STATIC smartlist_t *
   1417 ip_adapter_addresses_to_smartlist(const IP_ADAPTER_ADDRESSES *addresses)
   1418 {
   1419  smartlist_t *result = smartlist_new();
   1420  const IP_ADAPTER_ADDRESSES *address;
   1421 
   1422  for (address = addresses; address; address = address->Next) {
   1423    const IP_ADAPTER_UNICAST_ADDRESS *a;
   1424    for (a = address->FirstUnicastAddress; a; a = a->Next) {
   1425      /* Yes, it's a linked list inside a linked list */
   1426      const struct sockaddr *sa = a->Address.lpSockaddr;
   1427      tor_addr_t tmp;
   1428      if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
   1429        continue;
   1430      if (tor_addr_from_sockaddr(&tmp, sa, NULL) < 0)
   1431        continue;
   1432      smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
   1433    }
   1434  }
   1435 
   1436  return result;
   1437 }
   1438 
   1439 /** Windows only: use GetAdaptersAddresses() to retrieve the network interface
   1440 * addresses of the current machine.
   1441 * Returns a smartlist of <b>tor_addr_t</b>  structures.
   1442 */
   1443 STATIC smartlist_t *
   1444 get_interface_addresses_win32(int severity, sa_family_t family)
   1445 {
   1446  smartlist_t *result = NULL;
   1447  ULONG size, res;
   1448  IP_ADAPTER_ADDRESSES *addresses = NULL;
   1449 
   1450  (void) severity;
   1451 
   1452 #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
   1453               GAA_FLAG_SKIP_MULTICAST | \
   1454               GAA_FLAG_SKIP_DNS_SERVER)
   1455 
   1456  /* Guess how much space we need. */
   1457  size = 15*1024;
   1458  addresses = tor_malloc(size);
   1459  /* Exists in windows XP and later. */
   1460  res = GetAdaptersAddresses(family, FLAGS, NULL, addresses, &size);
   1461  if (res == ERROR_BUFFER_OVERFLOW) {
   1462    /* we didn't guess that we needed enough space; try again */
   1463    tor_free(addresses);
   1464    addresses = tor_malloc(size);
   1465    res = GetAdaptersAddresses(AF_UNSPEC, FLAGS, NULL, addresses, &size);
   1466  }
   1467  if (res != NO_ERROR) {
   1468    log_fn(severity, LD_NET, "GetAdaptersAddresses failed (result: %lu)", res);
   1469    goto done;
   1470  }
   1471 
   1472  result = ip_adapter_addresses_to_smartlist(addresses);
   1473 
   1474 done:
   1475  tor_free(addresses);
   1476  return result;
   1477 }
   1478 
   1479 #endif /* defined(HAVE_IP_ADAPTER_TO_SMARTLIST) */
   1480 
   1481 #ifdef HAVE_IFCONF_TO_SMARTLIST
   1482 
   1483 /* Guess how much space we need. There shouldn't be any struct ifreqs
   1484 * larger than this, even on OS X where the struct's size is dynamic. */
   1485 #define IFREQ_SIZE 4096
   1486 
   1487 /* This is defined on Mac OS X */
   1488 #ifndef _SIZEOF_ADDR_IFREQ
   1489 #define _SIZEOF_ADDR_IFREQ(x) sizeof(x)
   1490 #endif
   1491 
   1492 /* Free ifc->ifc_buf safely. */
   1493 static void
   1494 ifconf_free_ifc_buf(struct ifconf *ifc)
   1495 {
   1496  /* On macOS, tor_free() takes the address of ifc.ifc_buf, which leads to
   1497   * undefined behaviour, because pointer-to-pointers are expected to be
   1498   * aligned at 8-bytes, but the ifconf structure is packed.  So we use
   1499   * raw_free() instead. */
   1500  raw_free(ifc->ifc_buf);
   1501  ifc->ifc_buf = NULL;
   1502 }
   1503 
   1504 /** Convert <b>*buf</b>, an ifreq structure array of size <b>buflen</b>,
   1505 * into smartlist of <b>tor_addr_t</b> structures.
   1506 */
   1507 STATIC smartlist_t *
   1508 ifreq_to_smartlist(const uint8_t *buf, size_t buflen)
   1509 {
   1510  smartlist_t *result = smartlist_new();
   1511  const uint8_t *end = buf + buflen;
   1512 
   1513  /* These acrobatics are due to alignment issues which trigger
   1514   * undefined behaviour traps on OSX. */
   1515  struct ifreq *r = tor_malloc(IFREQ_SIZE);
   1516 
   1517  while (buf < end) {
   1518    /* Copy up to IFREQ_SIZE bytes into the struct ifreq, but don't overrun
   1519     * buf. */
   1520    memcpy(r, buf, end - buf < IFREQ_SIZE ? end - buf : IFREQ_SIZE);
   1521 
   1522    const struct sockaddr *sa = &r->ifr_addr;
   1523    tor_addr_t tmp;
   1524    int valid_sa_family = (sa->sa_family == AF_INET ||
   1525                           sa->sa_family == AF_INET6);
   1526 
   1527    int conversion_success = (tor_addr_from_sockaddr(&tmp, sa, NULL) == 0);
   1528 
   1529    if (valid_sa_family && conversion_success)
   1530      smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
   1531 
   1532    buf += _SIZEOF_ADDR_IFREQ(*r);
   1533  }
   1534 
   1535  tor_free(r);
   1536  return result;
   1537 }
   1538 
   1539 /** Use ioctl(.,SIOCGIFCONF,.) to get a list of current machine
   1540 * network interface addresses. Represent the result by smartlist of
   1541 * <b>tor_addr_t</b> structures.
   1542 */
   1543 STATIC smartlist_t *
   1544 get_interface_addresses_ioctl(int severity, sa_family_t family)
   1545 {
   1546  /* Some older unixy systems make us use ioctl(SIOCGIFCONF) */
   1547  struct ifconf ifc;
   1548  ifc.ifc_buf = NULL;
   1549  int fd;
   1550  smartlist_t *result = NULL;
   1551 
   1552  /* This interface, AFAICT, only supports AF_INET addresses,
   1553   * except on AIX. For Solaris, we could use SIOCGLIFCONF. */
   1554 
   1555  /* Bail out if family is neither AF_INET nor AF_UNSPEC since
   1556   * ioctl() technique supports non-IPv4 interface addresses on
   1557   * a small number of niche systems only. If family is AF_UNSPEC,
   1558   * fall back to getting AF_INET addresses only. */
   1559  if (family == AF_UNSPEC)
   1560    family = AF_INET;
   1561  else if (family != AF_INET)
   1562    return NULL;
   1563 
   1564  fd = socket(family, SOCK_DGRAM, 0);
   1565  if (fd < 0) {
   1566    tor_log(severity, LD_NET, "socket failed: %s", strerror(errno));
   1567    goto done;
   1568  }
   1569 
   1570  int mult = 1;
   1571  do {
   1572    mult *= 2;
   1573    ifc.ifc_len = mult * IFREQ_SIZE;
   1574    ifc.ifc_buf = tor_realloc(ifc.ifc_buf, ifc.ifc_len);
   1575 
   1576    tor_assert(ifc.ifc_buf);
   1577 
   1578    if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) {
   1579      tor_log(severity, LD_NET, "ioctl failed: %s", strerror(errno));
   1580      goto done;
   1581    }
   1582    /* Ensure we have least IFREQ_SIZE bytes unused at the end. Otherwise, we
   1583     * don't know if we got everything during ioctl. */
   1584  } while (mult * IFREQ_SIZE - ifc.ifc_len <= IFREQ_SIZE);
   1585  result = ifreq_to_smartlist((const uint8_t *)ifc.ifc_buf, ifc.ifc_len);
   1586 
   1587 done:
   1588  if (fd >= 0)
   1589    close(fd);
   1590  ifconf_free_ifc_buf(&ifc);
   1591  return result;
   1592 }
   1593 #endif /* defined(HAVE_IFCONF_TO_SMARTLIST) */
   1594 
   1595 /** Try to ask our network interfaces what addresses they are bound to.
   1596 * Return a new smartlist of tor_addr_t on success, and NULL on failure.
   1597 * (An empty smartlist indicates that we successfully learned that we have no
   1598 * addresses.)  Log failure messages at <b>severity</b>. Only return the
   1599 * interface addresses of requested <b>family</b> and ignore the addresses
   1600 * of other address families. */
   1601 MOCK_IMPL(smartlist_t *,
   1602 get_interface_addresses_raw,(int severity, sa_family_t family))
   1603 {
   1604  smartlist_t *result = NULL;
   1605 #if defined(HAVE_IFADDRS_TO_SMARTLIST)
   1606  if ((result = get_interface_addresses_ifaddrs(severity, family)))
   1607    return result;
   1608 #endif
   1609 #if defined(HAVE_IP_ADAPTER_TO_SMARTLIST)
   1610  if ((result = get_interface_addresses_win32(severity, family)))
   1611    return result;
   1612 #endif
   1613 #if defined(HAVE_IFCONF_TO_SMARTLIST)
   1614  if ((result = get_interface_addresses_ioctl(severity, family)))
   1615    return result;
   1616 #endif
   1617  (void) severity;
   1618  (void) result;
   1619  return NULL;
   1620 }
   1621 
   1622 /** Return true iff <b>a</b> is a multicast address.  */
   1623 int
   1624 tor_addr_is_multicast(const tor_addr_t *a)
   1625 {
   1626  sa_family_t family = tor_addr_family(a);
   1627  if (family == AF_INET) {
   1628    uint32_t ipv4h = tor_addr_to_ipv4h(a);
   1629    if ((ipv4h >> 24) == 0xe0)
   1630      return 1; /* Multicast */
   1631  } else if (family == AF_INET6) {
   1632    const uint8_t *a32 = tor_addr_to_in6_addr8(a);
   1633    if (a32[0] == 0xff)
   1634      return 1;
   1635  }
   1636  return 0;
   1637 }
   1638 
   1639 /** Attempt to retrieve IP address of current host by utilizing some
   1640 * UDP socket trickery. Only look for address of given <b>family</b>
   1641 * (only AF_INET and AF_INET6 are supported). Set result to *<b>addr</b>.
   1642 * Return 0 on success, -1 on failure.
   1643 */
   1644 MOCK_IMPL(int,
   1645 get_interface_address6_via_udp_socket_hack,(int severity,
   1646                                            sa_family_t family,
   1647                                            tor_addr_t *addr))
   1648 {
   1649  struct sockaddr_storage target_addr;
   1650  int sock=-1, r=-1;
   1651  socklen_t addr_len;
   1652 
   1653  memset(addr, 0, sizeof(tor_addr_t));
   1654  memset(&target_addr, 0, sizeof(target_addr));
   1655 
   1656  /* Don't worry: no packets are sent. We just need to use a real address
   1657   * on the actual Internet. */
   1658  if (family == AF_INET6) {
   1659    struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&target_addr;
   1660    /* Use the "discard" service port */
   1661    sin6->sin6_port = htons(9);
   1662    sock = tor_open_socket(PF_INET6,SOCK_DGRAM,IPPROTO_UDP);
   1663    addr_len = (socklen_t)sizeof(struct sockaddr_in6);
   1664    sin6->sin6_family = AF_INET6;
   1665    S6_ADDR16(sin6->sin6_addr)[0] = htons(0x2002); /* 2002:: */
   1666  } else if (family == AF_INET) {
   1667    struct sockaddr_in *sin = (struct sockaddr_in*)&target_addr;
   1668    /* Use the "discard" service port */
   1669    sin->sin_port = htons(9);
   1670    sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
   1671    addr_len = (socklen_t)sizeof(struct sockaddr_in);
   1672    sin->sin_family = AF_INET;
   1673    sin->sin_addr.s_addr = htonl(0x12000001); /* 18.0.0.1 */
   1674  } else {
   1675    return -1;
   1676  }
   1677 
   1678  if (sock < 0) {
   1679    int e = tor_socket_errno(-1);
   1680    log_fn(severity, LD_NET, "unable to create socket: %s",
   1681           tor_socket_strerror(e));
   1682    goto err;
   1683  }
   1684 
   1685  if (tor_connect_socket(sock,(struct sockaddr *)&target_addr,
   1686                         addr_len) < 0) {
   1687    int e = tor_socket_errno(sock);
   1688    log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e));
   1689    goto err;
   1690  }
   1691 
   1692  if (tor_addr_from_getsockname(addr, sock) < 0) {
   1693    int e = tor_socket_errno(sock);
   1694    log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s",
   1695           tor_socket_strerror(e));
   1696    goto err;
   1697  }
   1698 
   1699  if (tor_addr_is_loopback(addr) || tor_addr_is_multicast(addr)) {
   1700    log_fn(severity, LD_NET, "Address that we determined via UDP socket"
   1701           " magic is unsuitable for public comms.");
   1702  } else {
   1703    r=0;
   1704  }
   1705 
   1706 err:
   1707  if (sock >= 0)
   1708    tor_close_socket(sock);
   1709  if (r == -1)
   1710    memset(addr, 0, sizeof(tor_addr_t));
   1711  return r;
   1712 }
   1713 
   1714 /** Set *<b>addr</b> to an arbitrary IP address (if any) of an interface that
   1715 * connects to the Internet.  Prefer public IP addresses to internal IP
   1716 * addresses.  This address should only be used in checking whether our
   1717 * address has changed, as it may be an internal IP address.  Return 0 on
   1718 * success, -1 on failure.
   1719 * Prefer get_interface_address6_list for a list of all addresses on all
   1720 * interfaces which connect to the Internet.
   1721 */
   1722 MOCK_IMPL(int,
   1723 get_interface_address6,(int severity, sa_family_t family, tor_addr_t *addr))
   1724 {
   1725  smartlist_t *addrs;
   1726  int rv = -1;
   1727  tor_assert(addr);
   1728 
   1729  memset(addr, 0, sizeof(tor_addr_t));
   1730 
   1731  /* Get a list of public or internal IPs in arbitrary order */
   1732  addrs = get_interface_address6_list(severity, family, 1);
   1733 
   1734  /* Find the first non-internal address, or the last internal address.
   1735   * Ideally, we want the default route; see #12377 for details. */
   1736  SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a) {
   1737    tor_addr_copy(addr, a);
   1738    const bool is_internal = tor_addr_is_internal(a, 0);
   1739    rv = 0;
   1740 
   1741    log_debug(LD_NET, "Found %s interface address '%s'",
   1742              (is_internal ? "internal" : "external"), fmt_addr(addr));
   1743 
   1744    /* If we found a non-internal address, declare success.  Otherwise,
   1745     * keep looking. */
   1746    if (!is_internal)
   1747      break;
   1748  } SMARTLIST_FOREACH_END(a);
   1749 
   1750  interface_address6_list_free(addrs);
   1751  return rv;
   1752 }
   1753 
   1754 /** Free a smartlist of IP addresses returned by get_interface_address6_list.
   1755 */
   1756 void
   1757 interface_address6_list_free_(smartlist_t *addrs)
   1758 {
   1759  if (addrs != NULL) {
   1760    SMARTLIST_FOREACH(addrs, tor_addr_t *, a, tor_free(a));
   1761    smartlist_free(addrs);
   1762  }
   1763 }
   1764 
   1765 /** Return a smartlist of the IP addresses of type family from all interfaces
   1766 * on the server. Excludes loopback and multicast addresses. Only includes
   1767 * internal addresses if include_internal is true. (Note that a relay behind
   1768 * NAT may use an internal address to connect to the Internet.)
   1769 * An empty smartlist means that there are no addresses of the selected type
   1770 * matching these criteria.
   1771 * Returns NULL on failure.
   1772 * Use interface_address6_list_free to free the returned list.
   1773 */
   1774 MOCK_IMPL(smartlist_t *,
   1775 get_interface_address6_list,(int severity,
   1776                             sa_family_t family,
   1777                             int include_internal))
   1778 {
   1779  smartlist_t *addrs;
   1780  tor_addr_t addr;
   1781 
   1782  /* Try to do this the smart way if possible. */
   1783  if ((addrs = get_interface_addresses_raw(severity, family))) {
   1784    SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a)
   1785    {
   1786      if (tor_addr_is_loopback(a) ||
   1787          tor_addr_is_multicast(a)) {
   1788        SMARTLIST_DEL_CURRENT_KEEPORDER(addrs, a);
   1789        tor_free(a);
   1790        continue;
   1791      }
   1792 
   1793      if (!include_internal && tor_addr_is_internal(a, 0)) {
   1794        SMARTLIST_DEL_CURRENT_KEEPORDER(addrs, a);
   1795        tor_free(a);
   1796        continue;
   1797      }
   1798    } SMARTLIST_FOREACH_END(a);
   1799  }
   1800 
   1801  if (addrs && smartlist_len(addrs) > 0) {
   1802    return addrs;
   1803  }
   1804 
   1805  /* if we removed all entries as unsuitable */
   1806  if (addrs) {
   1807    smartlist_free(addrs);
   1808  }
   1809 
   1810  /* Okay, the smart way is out. */
   1811  addrs = smartlist_new();
   1812 
   1813  if (family == AF_INET || family == AF_UNSPEC) {
   1814    if (get_interface_address6_via_udp_socket_hack(severity,AF_INET,
   1815                                                   &addr) == 0) {
   1816      if (include_internal || !tor_addr_is_internal(&addr, 0)) {
   1817        smartlist_add(addrs, tor_memdup(&addr, sizeof(addr)));
   1818      }
   1819    }
   1820  }
   1821 
   1822  if (family == AF_INET6 || family == AF_UNSPEC) {
   1823    if (get_interface_address6_via_udp_socket_hack(severity,AF_INET6,
   1824                                                   &addr) == 0) {
   1825      if (include_internal || !tor_addr_is_internal(&addr, 0)) {
   1826        smartlist_add(addrs, tor_memdup(&addr, sizeof(addr)));
   1827      }
   1828    }
   1829  }
   1830 
   1831  return addrs;
   1832 }
   1833 
   1834 /* ======
   1835 * IPv4 helpers
   1836 * XXXX IPv6 deprecate some of these.
   1837 */
   1838 
   1839 /** Given an address of the form "ip:port", try to divide it into its
   1840 * ip and port portions, setting *<b>address_out</b> to a newly
   1841 * allocated string holding the address portion and *<b>port_out</b>
   1842 * to the port.
   1843 *
   1844 * Don't do DNS lookups and don't allow domain names in the "ip" field.
   1845 *
   1846 * If <b>default_port</b> is less than 0, don't accept <b>addrport</b> of the
   1847 * form "ip" or "ip:0".  Otherwise, accept those forms, and set
   1848 * *<b>port_out</b> to <b>default_port</b>.
   1849 *
   1850 * This function accepts:
   1851 *  - IPv6 address and port, when the IPv6 address is in square brackets,
   1852 *  - IPv6 address with square brackets,
   1853 *  - IPv6 address without square brackets.
   1854 *
   1855 * Return 0 on success, -1 on failure. */
   1856 int
   1857 tor_addr_port_parse(int severity, const char *addrport,
   1858                    tor_addr_t *address_out, uint16_t *port_out,
   1859                    int default_port)
   1860 {
   1861  int retval = -1;
   1862  int r;
   1863  char *addr_tmp = NULL;
   1864  bool has_port;
   1865 
   1866  tor_assert(addrport);
   1867  tor_assert(address_out);
   1868  tor_assert(port_out);
   1869 
   1870  r = tor_addr_port_split(severity, addrport, &addr_tmp, port_out);
   1871  if (r < 0)
   1872    goto done;
   1873 
   1874  has_port = !! *port_out;
   1875  /* If there's no port, use the default port, or fail if there is no default
   1876   */
   1877  if (!has_port) {
   1878    if (default_port >= 0)
   1879      *port_out = default_port;
   1880    else
   1881      goto done;
   1882  }
   1883 
   1884  /* Make sure that address_out is an IP address.
   1885   * If there is no port in addrport, allow IPv6 addresses without brackets. */
   1886  if (tor_addr_parse_impl(address_out, addr_tmp, !has_port) < 0)
   1887    goto done;
   1888 
   1889  retval = 0;
   1890 
   1891 done:
   1892  /* Clear the address and port on error, to avoid returning uninitialised or
   1893   * partly parsed data.
   1894   */
   1895  if (retval == -1) {
   1896    memset(address_out, 0, sizeof(tor_addr_t));
   1897    *port_out = 0;
   1898  }
   1899  tor_free(addr_tmp);
   1900  return retval;
   1901 }
   1902 
   1903 /** Given an address of the form "host[:port]", try to divide it into its host
   1904 * and port portions.
   1905 *
   1906 * Like tor_addr_port_parse(), this function accepts:
   1907 *  - IPv6 address and port, when the IPv6 address is in square brackets,
   1908 *  - IPv6 address with square brackets,
   1909 *  - IPv6 address without square brackets.
   1910 *
   1911 * Sets *<b>address_out</b> to a newly allocated string holding the address
   1912 * portion, and *<b>port_out</b> to the port (or 0 if no port is given).
   1913 *
   1914 * Return 0 on success, -1 on failure. */
   1915 int
   1916 tor_addr_port_split(int severity, const char *addrport,
   1917                    char **address_out, uint16_t *port_out)
   1918 {
   1919  tor_addr_t a_tmp;
   1920  tor_assert(addrport);
   1921  tor_assert(address_out);
   1922  tor_assert(port_out);
   1923 
   1924  /* We need to check for IPv6 manually because the logic below doesn't
   1925   * do a good job on IPv6 addresses that lack a port.
   1926   * If an IPv6 address without square brackets is ambiguous, it gets parsed
   1927   * here as an address, rather than address:port. */
   1928  if (tor_addr_parse(&a_tmp, addrport) == AF_INET6) {
   1929    *port_out = 0;
   1930    *address_out = tor_strdup(addrport);
   1931    return 0;
   1932  }
   1933 
   1934  const char *colon;
   1935  char *address_ = NULL;
   1936  int port_;
   1937  int ok = 1;
   1938 
   1939  colon = strrchr(addrport, ':');
   1940  if (colon) {
   1941    address_ = tor_strndup(addrport, colon-addrport);
   1942    port_ = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
   1943    if (!port_) {
   1944      log_fn(severity, LD_GENERAL, "Port %s out of range", escaped(colon+1));
   1945      ok = 0;
   1946    }
   1947    if (!port_out) {
   1948      char *esc_addrport = esc_for_log(addrport);
   1949      log_fn(severity, LD_GENERAL,
   1950             "Port %s given on %s when not required",
   1951             escaped(colon+1), esc_addrport);
   1952      tor_free(esc_addrport);
   1953      ok = 0;
   1954    }
   1955  } else {
   1956    address_ = tor_strdup(addrport);
   1957    port_ = 0;
   1958  }
   1959 
   1960  if (ok) {
   1961    *address_out = address_;
   1962  } else {
   1963    *address_out = NULL;
   1964    tor_free(address_);
   1965  }
   1966 
   1967  *port_out = ok ? ((uint16_t) port_) : 0;
   1968 
   1969  return ok ? 0 : -1;
   1970 }
   1971 
   1972 /** If <b>mask</b> is an address mask for a bit-prefix, return the number of
   1973 * bits.  Otherwise, return -1. */
   1974 int
   1975 addr_mask_get_bits(uint32_t mask)
   1976 {
   1977  int i;
   1978  if (mask == 0)
   1979    return 0;
   1980  if (mask == 0xFFFFFFFFu)
   1981    return 32;
   1982  for (i=1; i<=32; ++i) {
   1983    if (mask == (uint32_t) ~((1u<<(32-i))-1)) {
   1984      return i;
   1985    }
   1986  }
   1987  return -1;
   1988 }
   1989 
   1990 /** Parse a string <b>s</b> in the format of (*|port(-maxport)?)?, setting the
   1991 * various *out pointers as appropriate.  Return 0 on success, -1 on failure.
   1992 */
   1993 int
   1994 parse_port_range(const char *port, uint16_t *port_min_out,
   1995                 uint16_t *port_max_out)
   1996 {
   1997  int port_min, port_max, ok;
   1998  tor_assert(port_min_out);
   1999  tor_assert(port_max_out);
   2000 
   2001  if (!port || *port == '\0' || strcmp(port, "*") == 0) {
   2002    port_min = 1;
   2003    port_max = 65535;
   2004  } else {
   2005    char *endptr = NULL;
   2006    port_min = (int)tor_parse_long(port, 10, 0, 65535, &ok, &endptr);
   2007    if (!ok) {
   2008      goto malformed_port;
   2009    } else if (endptr && *endptr != '\0') {
   2010      if (*endptr != '-')
   2011        goto malformed_port;
   2012      port = endptr+1;
   2013      endptr = NULL;
   2014      port_max = (int)tor_parse_long(port, 10, 1, 65535, &ok, &endptr);
   2015      if (!ok)
   2016        goto malformed_port;
   2017    } else {
   2018      port_max = port_min;
   2019    }
   2020    if (port_min > port_max) {
   2021      log_warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
   2022      return -1;
   2023    }
   2024  }
   2025 
   2026  if (port_min < 1)
   2027    port_min = 1;
   2028  if (port_max > 65535)
   2029    port_max = 65535;
   2030 
   2031  *port_min_out = (uint16_t) port_min;
   2032  *port_max_out = (uint16_t) port_max;
   2033 
   2034  return 0;
   2035 malformed_port:
   2036  log_warn(LD_GENERAL,
   2037           "Malformed port %s on address range; rejecting.",
   2038           escaped(port));
   2039  return -1;
   2040 }
   2041 
   2042 /** Given a host-order <b>addr</b>, call tor_inet_ntop() on it
   2043 *  and return a strdup of the resulting address. Return NULL if
   2044 *  tor_inet_ntop() fails.
   2045 */
   2046 char *
   2047 tor_dup_ip(uint32_t addr)
   2048 {
   2049  const char *ip_str;
   2050  char buf[TOR_ADDR_BUF_LEN];
   2051  struct in_addr in;
   2052 
   2053  in.s_addr = htonl(addr);
   2054  ip_str = tor_inet_ntop(AF_INET, &in, buf, sizeof(buf));
   2055 
   2056  tor_assertf_nonfatal(ip_str, "Failed to duplicate IP %08X", addr);
   2057  if (ip_str)
   2058    return tor_strdup(buf);
   2059 
   2060  return NULL;
   2061 }
   2062 
   2063 /**
   2064 * Set *<b>addr</b> to a host-order IPv4 address (if any) of an
   2065 * interface that connects to the Internet.  Prefer public IP addresses to
   2066 * internal IP addresses.  This address should only be used in checking
   2067 * whether our address has changed, as it may be an internal IPv4 address.
   2068 * Return 0 on success, -1 on failure.
   2069 * Prefer get_interface_address_list6 for a list of all IPv4 and IPv6
   2070 * addresses on all interfaces which connect to the Internet.
   2071 */
   2072 MOCK_IMPL(int,
   2073 get_interface_address,(int severity, uint32_t *addr))
   2074 {
   2075  tor_addr_t local_addr;
   2076  int r;
   2077 
   2078  memset(addr, 0, sizeof(uint32_t));
   2079 
   2080  r = get_interface_address6(severity, AF_INET, &local_addr);
   2081  if (r>=0)
   2082    *addr = tor_addr_to_ipv4h(&local_addr);
   2083  return r;
   2084 }
   2085 
   2086 /** Return true if we can tell that <b>name</b> is a canonical name for the
   2087 * loopback address.  Return true also for *.local hostnames, which are
   2088 * multicast DNS names for hosts on the local network. */
   2089 int
   2090 tor_addr_hostname_is_local(const char *name)
   2091 {
   2092  return !strcasecmp(name, "localhost") ||
   2093    !strcasecmp(name, "local") ||
   2094    !strcasecmpend(name, ".local");
   2095 }
   2096 
   2097 /** Return a newly allocated tor_addr_port_t with <b>addr</b> and
   2098    <b>port</b> filled in. */
   2099 tor_addr_port_t *
   2100 tor_addr_port_new(const tor_addr_t *addr, uint16_t port)
   2101 {
   2102  tor_addr_port_t *ap = tor_malloc_zero(sizeof(tor_addr_port_t));
   2103  if (addr)
   2104    tor_addr_copy(&ap->addr, addr);
   2105  ap->port = port;
   2106  return ap;
   2107 }
   2108 
   2109 /** Return true iff <b>a</b> and <b>b</b> are the same address and port */
   2110 int
   2111 tor_addr_port_eq(const tor_addr_port_t *a,
   2112                 const tor_addr_port_t *b)
   2113 {
   2114  return tor_addr_eq(&a->addr, &b->addr) && a->port == b->port;
   2115 }
   2116 
   2117 /**
   2118 * Copy a tor_addr_port_t from @a source to @a dest.
   2119 **/
   2120 void
   2121 tor_addr_port_copy(tor_addr_port_t *dest,
   2122                   const tor_addr_port_t *source)
   2123 {
   2124  tor_assert(dest);
   2125  tor_assert(source);
   2126  memcpy(dest, source, sizeof(tor_addr_port_t));
   2127 }
   2128 
   2129 /** Return true if <b>string</b> represents a valid IPv4 address in
   2130 * 'a.b.c.d' form.
   2131 */
   2132 int
   2133 string_is_valid_ipv4_address(const char *string)
   2134 {
   2135  struct in_addr addr;
   2136 
   2137  return (tor_inet_pton(AF_INET,string,&addr) == 1);
   2138 }
   2139 
   2140 /** Return true if <b>string</b> represents a valid IPv6 address in
   2141 * a form that inet_pton() can parse.
   2142 */
   2143 int
   2144 string_is_valid_ipv6_address(const char *string)
   2145 {
   2146  struct in6_addr addr;
   2147 
   2148  return (tor_inet_pton(AF_INET6,string,&addr) == 1);
   2149 }
   2150 
   2151 /** Return true iff <b>string</b> is a valid destination address,
   2152 * i.e. either a DNS hostname or IPv4/IPv6 address string.
   2153 */
   2154 int
   2155 string_is_valid_dest(const char *string)
   2156 {
   2157  char *tmp = NULL;
   2158  int retval;
   2159  size_t len;
   2160 
   2161  if (string == NULL)
   2162    return 0;
   2163 
   2164  len = strlen(string);
   2165 
   2166  if (len == 0)
   2167    return 0;
   2168 
   2169  if (string[0] == '[' && string[len - 1] == ']')
   2170    string = tmp = tor_strndup(string + 1, len - 2);
   2171 
   2172  retval = string_is_valid_ipv4_address(string) ||
   2173    string_is_valid_ipv6_address(string) ||
   2174    string_is_valid_nonrfc_hostname(string);
   2175 
   2176  tor_free(tmp);
   2177 
   2178  return retval;
   2179 }
   2180 
   2181 /** Return true iff <b>string</b> matches a pattern of DNS names
   2182 * that we allow Tor clients to connect to.
   2183 *
   2184 * Note: This allows certain technically invalid characters ('_') to cope
   2185 * with misconfigured zones that have been encountered in the wild.
   2186 */
   2187 int
   2188 string_is_valid_nonrfc_hostname(const char *string)
   2189 {
   2190  int result = 1;
   2191  int has_trailing_dot;
   2192  char *last_label;
   2193  smartlist_t *components;
   2194 
   2195  if (!string || strlen(string) == 0)
   2196    return 0;
   2197 
   2198  if (string_is_valid_ipv4_address(string))
   2199    return 0;
   2200 
   2201  components = smartlist_new();
   2202 
   2203  smartlist_split_string(components,string,".",0,0);
   2204 
   2205  if (BUG(smartlist_len(components) == 0)) {
   2206    // LCOV_EXCL_START should be impossible given the earlier checks.
   2207    smartlist_free(components);
   2208    return 0;
   2209    // LCOV_EXCL_STOP
   2210  }
   2211 
   2212  /* Allow a single terminating '.' used rarely to indicate domains
   2213   * are FQDNs rather than relative. */
   2214  last_label = (char *)smartlist_get(components,
   2215                                     smartlist_len(components) - 1);
   2216  has_trailing_dot = (last_label[0] == '\0');
   2217  if (has_trailing_dot) {
   2218    smartlist_pop_last(components);
   2219    tor_free(last_label);
   2220    last_label = NULL;
   2221  }
   2222 
   2223  SMARTLIST_FOREACH_BEGIN(components, char *, c) {
   2224    if ((c[0] == '-') || (*c == '_')) {
   2225      result = 0;
   2226      break;
   2227    }
   2228 
   2229    do {
   2230      result = (TOR_ISALNUM(*c) || (*c == '-') || (*c == '_'));
   2231      c++;
   2232    } while (result && *c);
   2233 
   2234    if (result == 0) {
   2235      break;
   2236    }
   2237  } SMARTLIST_FOREACH_END(c);
   2238 
   2239  SMARTLIST_FOREACH_BEGIN(components, char *, c) {
   2240    tor_free(c);
   2241  } SMARTLIST_FOREACH_END(c);
   2242 
   2243  smartlist_free(components);
   2244 
   2245  return result;
   2246 }