tor  0.4.2.0-alpha-dev
address.c
Go to the documentation of this file.
1 /* Copyright (c) 2003-2004, Roger Dingledine
2  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3  * Copyright (c) 2007-2019, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
5 
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"
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"
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. Let us know about your platform, please!
101 #endif
102 CTASSERT(AF_UNSPEC == 0);
103 
112 socklen_t
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 
153 static void
155 {
156  memset(a, 0, sizeof(*a));
157  a->family = AF_UNIX;
158 }
159 
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) {
187  return 0;
188  } else {
190  return -1;
191  }
192  return 0;
193 }
194 
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 
224 void
226 {
227  memset(a, 0, sizeof(*a));
228  a->family = AF_UNSPEC;
229 }
230 
234 void
236 {
237  memset(a, 0, sizeof(*a));
238  a->family = family;
239 }
240 
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);
319  return 1;
320 }
321 
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 
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 
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 
542 int
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 
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 char nil_bytes[16] = { [0]=0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };
612  family = AF_INET6;
613  tor_addr_from_ipv6_bytes(addr_out, nil_bytes);
614  } else {
615  family = AF_UNSPEC;
616  tor_addr_make_unspec(addr_out);
617  log_info(LD_GENERAL,
618  "'%s' expands into rules which apply to all IPv4 and IPv6 "
619  "addresses. (Use accept/reject *4:* for IPv4 or "
620  "accept[6]/reject[6] *6:* for IPv6.)", s);
621  }
622  } else {
623  family = AF_INET;
624  tor_addr_from_ipv4h(addr_out, 0);
625  }
626  any_flag = 1;
627  } else if (!strcmp(address, "*4") && (flags & TAPMP_EXTENDED_STAR)) {
628  family = AF_INET;
629  tor_addr_from_ipv4h(addr_out, 0);
630  any_flag = 1;
631  } else if (!strcmp(address, "*6") && (flags & TAPMP_EXTENDED_STAR)) {
632  static char nil_bytes[16] = { [0]=0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };
633  family = AF_INET6;
634  tor_addr_from_ipv6_bytes(addr_out, nil_bytes);
635  any_flag = 1;
636  } else if (tor_inet_pton(AF_INET6, address, &in6_tmp) > 0) {
637  family = AF_INET6;
638  tor_addr_from_in6(addr_out, &in6_tmp);
639  } else if (tor_inet_pton(AF_INET, address, &in_tmp) > 0) {
640  family = AF_INET;
641  tor_addr_from_in(addr_out, &in_tmp);
642  } else {
643  log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
644  escaped(address));
645  goto err;
646  }
647 
648  v4map = tor_addr_is_v4(addr_out);
649 
650  /* Parse mask */
651  if (maskbits_out) {
652  int bits = 0;
653  struct in_addr v4mask;
654 
655  if (mask) { /* the caller (tried to) specify a mask */
656  bits = (int) strtol(mask, &endptr, 10);
657  if (!*endptr) { /* strtol converted everything, so it was an integer */
658  if ((bits<0 || bits>128) ||
659  (family == AF_INET && bits > 32)) {
660  log_warn(LD_GENERAL,
661  "Bad number of mask bits (%d) on address range; rejecting.",
662  bits);
663  goto err;
664  }
665  } else { /* mask might still be an address-style mask */
666  if (tor_inet_pton(AF_INET, mask, &v4mask) > 0) {
667  bits = addr_mask_get_bits(ntohl(v4mask.s_addr));
668  if (bits < 0) {
669  log_warn(LD_GENERAL,
670  "IPv4-style mask %s is not a prefix address; rejecting.",
671  escaped(mask));
672  goto err;
673  }
674  } else { /* Not IPv4; we don't do address-style IPv6 masks. */
675  log_warn(LD_GENERAL,
676  "Malformed mask on address range %s; rejecting.",
677  escaped(s));
678  goto err;
679  }
680  }
681  if (family == AF_INET6 && v4map) {
682  if (bits > 32 && bits < 96) { /* Crazy */
683  log_warn(LD_GENERAL,
684  "Bad mask bits %d for V4-mapped V6 address; rejecting.",
685  bits);
686  goto err;
687  }
688  /* XXXX_IP6 is this really what we want? */
689  bits = 96 + bits%32; /* map v4-mapped masks onto 96-128 bits */
690  }
691  if (any_flag) {
692  log_warn(LD_GENERAL,
693  "Found bit prefix with wildcard address; rejecting");
694  goto err;
695  }
696  } else { /* pick an appropriate mask, as none was given */
697  if (any_flag)
698  bits = 0; /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */
699  else if (tor_addr_family(addr_out) == AF_INET)
700  bits = 32;
701  else if (tor_addr_family(addr_out) == AF_INET6)
702  bits = 128;
703  }
704  *maskbits_out = (maskbits_t) bits;
705  } else {
706  if (mask) {
707  log_warn(LD_GENERAL,
708  "Unexpected mask in address %s; rejecting", escaped(s));
709  goto err;
710  }
711  }
712 
713  /* Parse port(s) */
714  if (port_min_out) {
715  uint16_t port2;
716  if (!port_max_out) /* caller specified one port; fake the second one */
717  port_max_out = &port2;
718 
719  if (parse_port_range(port, port_min_out, port_max_out) < 0) {
720  goto err;
721  } else if ((*port_min_out != *port_max_out) && port_max_out == &port2) {
722  log_warn(LD_GENERAL,
723  "Wanted one port from address range, but there are two.");
724 
725  port_max_out = NULL; /* caller specified one port, so set this back */
726  goto err;
727  }
728  } else {
729  if (port) {
730  log_warn(LD_GENERAL,
731  "Unexpected ports in address %s; rejecting", escaped(s));
732  goto err;
733  }
734  }
735 
736  tor_free(base);
737  return tor_addr_family(addr_out);
738  err:
739  tor_free(base);
740  return -1;
741 }
742 
748 int
750 {
751  tor_assert(addr);
752 
753  if (tor_addr_family(addr) == AF_INET)
754  return 1;
755 
756  if (tor_addr_family(addr) == AF_INET6) {
757  /* First two don't need to be ordered */
758  uint32_t *a32 = tor_addr_to_in6_addr32(addr);
759  if (a32[0] == 0 && a32[1] == 0 && ntohl(a32[2]) == 0x0000ffffu)
760  return 1;
761  }
762 
763  return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */
764 }
765 
769 int
771 {
772  tor_assert(addr);
773 
774  switch (tor_addr_family(addr)) {
775  case AF_INET6: {
776  uint32_t *a32 = tor_addr_to_in6_addr32(addr);
777  return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 0);
778  }
779  case AF_INET:
780  return (tor_addr_to_ipv4n(addr) == 0);
781  case AF_UNIX:
782  return 1;
783  case AF_UNSPEC:
784  return 1;
785  default:
786  log_warn(LD_BUG, "Called with unknown address family %d",
787  (int)tor_addr_family(addr));
788  return 0;
789  }
790  //return 1;
791 }
792 
794 int
796 {
797  tor_assert(addr);
798  switch (tor_addr_family(addr)) {
799  case AF_INET6: {
800  /* ::1 */
801  uint32_t *a32 = tor_addr_to_in6_addr32(addr);
802  return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) &&
803  (ntohl(a32[3]) == 1);
804  }
805  case AF_INET:
806  /* 127.0.0.1 */
807  return (tor_addr_to_ipv4h(addr) & 0xff000000) == 0x7f000000;
808  case AF_UNSPEC:
809  return 0;
810  /* LCOV_EXCL_START */
811  default:
813  return 0;
814  /* LCOV_EXCL_STOP */
815  }
816 }
817 
818 /* Is addr valid?
819  * Checks that addr is non-NULL and not tor_addr_is_null().
820  * If for_listening is true, IPv4 addr 0.0.0.0 is allowed.
821  * It means "bind to all addresses on the local machine". */
822 int
823 tor_addr_is_valid(const tor_addr_t *addr, int for_listening)
824 {
825  /* NULL addresses are invalid regardless of for_listening */
826  if (addr == NULL) {
827  return 0;
828  }
829 
830  /* Only allow IPv4 0.0.0.0 for_listening. */
831  if (for_listening && addr->family == AF_INET
832  && tor_addr_to_ipv4h(addr) == 0) {
833  return 1;
834  }
835 
836  /* Otherwise, the address is valid if it's not tor_addr_is_null() */
837  return !tor_addr_is_null(addr);
838 }
839 
840 /* Is the network-order IPv4 address v4n_addr valid?
841  * Checks that addr is not zero.
842  * Except if for_listening is true, where IPv4 addr 0.0.0.0 is allowed. */
843 int
844 tor_addr_is_valid_ipv4n(uint32_t v4n_addr, int for_listening)
845 {
846  /* Any IPv4 address is valid with for_listening. */
847  if (for_listening) {
848  return 1;
849  }
850 
851  /* Otherwise, zero addresses are invalid. */
852  return v4n_addr != 0;
853 }
854 
855 /* Is port valid?
856  * Checks that port is not 0.
857  * Except if for_listening is true, where port 0 is allowed.
858  * It means "OS chooses a port". */
859 int
860 tor_port_is_valid(uint16_t port, int for_listening)
861 {
862  /* Any port value is valid with for_listening. */
863  if (for_listening) {
864  return 1;
865  }
866 
867  /* Otherwise, zero ports are invalid. */
868  return port != 0;
869 }
870 
873 void
874 tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
875 {
876  tor_assert(dest);
877  memset(dest, 0, sizeof(tor_addr_t));
878  dest->family = AF_INET;
879  dest->addr.in_addr.s_addr = v4addr;
880 }
881 
884 void
885 tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
886 {
887  tor_assert(dest);
888  tor_assert(ipv6_bytes);
889  memset(dest, 0, sizeof(tor_addr_t));
890  dest->family = AF_INET6;
891  memcpy(dest->addr.in6_addr.s6_addr, ipv6_bytes, 16);
892 }
893 
895 void
896 tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
897 {
898  tor_addr_from_ipv6_bytes(dest, (const char*)in6->s6_addr);
899 }
900 
903 void
905 {
906  if (src == dest)
907  return;
908  tor_assert(src);
909  tor_assert(dest);
910  memcpy(dest, src, sizeof(tor_addr_t));
911 }
912 
917 void
919 {
920  tor_assert(src != dest);
921  tor_assert(src);
922  tor_assert(dest);
923  memset(dest, 0, sizeof(tor_addr_t));
924  dest->family = src->family;
925  switch (tor_addr_family(src))
926  {
927  case AF_INET:
928  dest->addr.in_addr.s_addr = src->addr.in_addr.s_addr;
929  break;
930  case AF_INET6:
931  memcpy(dest->addr.in6_addr.s6_addr, src->addr.in6_addr.s6_addr, 16);
932  case AF_UNSPEC:
933  break;
934  // LCOV_EXCL_START
935  default:
937  // LCOV_EXCL_STOP
938  }
939 }
940 
953 int
954 tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2,
956 {
957  return tor_addr_compare_masked(addr1, addr2, 128, how);
958 }
959 
974 int
975 tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2,
977 {
980 #define TRISTATE(a,b) (((a)<(b))?-1: (((a)==(b))?0:1))
981  sa_family_t family1, family2, v_family1, v_family2;
982 
983  tor_assert(addr1 && addr2);
984 
985  v_family1 = family1 = tor_addr_family(addr1);
986  v_family2 = family2 = tor_addr_family(addr2);
987 
988  if (family1==family2) {
989  /* When the families are the same, there's only one way to do the
990  * comparison: exactly. */
991  int r;
992  switch (family1) {
993  case AF_UNSPEC:
994  return 0; /* All unspecified addresses are equal */
995  case AF_INET: {
996  uint32_t a1 = tor_addr_to_ipv4h(addr1);
997  uint32_t a2 = tor_addr_to_ipv4h(addr2);
998  if (mbits <= 0)
999  return 0;
1000  if (mbits > 32)
1001  mbits = 32;
1002  a1 >>= (32-mbits);
1003  a2 >>= (32-mbits);
1004  r = TRISTATE(a1, a2);
1005  return r;
1006  }
1007  case AF_INET6: {
1008  if (mbits > 128)
1009  mbits = 128;
1010 
1011  const uint8_t *a1 = tor_addr_to_in6_addr8(addr1);
1012  const uint8_t *a2 = tor_addr_to_in6_addr8(addr2);
1013  const int bytes = mbits >> 3;
1014  const int leftover_bits = mbits & 7;
1015  if (bytes && (r = tor_memcmp(a1, a2, bytes))) {
1016  return r;
1017  } else if (leftover_bits) {
1018  uint8_t b1 = a1[bytes] >> (8-leftover_bits);
1019  uint8_t b2 = a2[bytes] >> (8-leftover_bits);
1020  return TRISTATE(b1, b2);
1021  } else {
1022  return 0;
1023  }
1024  }
1025  case AF_UNIX:
1026  /* HACKHACKHACKHACKHACK:
1027  * tor_addr_t doesn't contain a copy of sun_path, so it's not
1028  * possible to compare this at all.
1029  *
1030  * Since the only time we currently actually should be comparing
1031  * 2 AF_UNIX addresses is when dealing with ISO_CLIENTADDR (which
1032  * is disabled for AF_UNIX SocksPorts anyway), this just does
1033  * a pointer comparison.
1034  *
1035  * See: #20261.
1036  */
1037  if (addr1 < addr2)
1038  return -1;
1039  else if (addr1 == addr2)
1040  return 0;
1041  else
1042  return 1;
1043  /* LCOV_EXCL_START */
1044  default:
1046  return 0;
1047  /* LCOV_EXCL_STOP */
1048  }
1049  } else if (how == CMP_EXACT) {
1050  /* Unequal families and an exact comparison? Stop now! */
1051  return TRISTATE(family1, family2);
1052  }
1053 
1054  if (mbits == 0)
1055  return 0;
1056 
1057  if (family1 == AF_INET6 && tor_addr_is_v4(addr1))
1058  v_family1 = AF_INET;
1059  if (family2 == AF_INET6 && tor_addr_is_v4(addr2))
1060  v_family2 = AF_INET;
1061  if (v_family1 == v_family2) {
1062  /* One or both addresses are a mapped ipv4 address. */
1063  uint32_t a1, a2;
1064  if (family1 == AF_INET6) {
1065  a1 = tor_addr_to_mapped_ipv4h(addr1);
1066  if (mbits <= 96)
1067  return 0;
1068  mbits -= 96; /* We just decided that the first 96 bits of a1 "match". */
1069  } else {
1070  a1 = tor_addr_to_ipv4h(addr1);
1071  }
1072  if (family2 == AF_INET6) {
1073  a2 = tor_addr_to_mapped_ipv4h(addr2);
1074  } else {
1075  a2 = tor_addr_to_ipv4h(addr2);
1076  }
1077  if (mbits > 32) mbits = 32;
1078  a1 >>= (32-mbits);
1079  a2 >>= (32-mbits);
1080  return TRISTATE(a1, a2);
1081  } else {
1082  /* Unequal families, and semantic comparison, and no semantic family
1083  * matches. */
1084  return TRISTATE(family1, family2);
1085  }
1086 }
1087 
1089 static const uint32_t unspec_hash_input[] = { 0x4e4df09f, 0x92985342 };
1090 
1092 uint64_t
1094 {
1095  switch (tor_addr_family(addr)) {
1096  case AF_INET:
1097  return siphash24g(&addr->addr.in_addr.s_addr, 4);
1098  case AF_UNSPEC:
1099  return siphash24g(unspec_hash_input, sizeof(unspec_hash_input));
1100  case AF_INET6:
1101  return siphash24g(&addr->addr.in6_addr.s6_addr, 16);
1102  /* LCOV_EXCL_START */
1103  default:
1105  return 0;
1106  /* LCOV_EXCL_STOP */
1107  }
1108 }
1109 
1111 uint64_t
1112 tor_addr_keyed_hash(const struct sipkey *key, const tor_addr_t *addr)
1113 {
1114  /* This is duplicate code with tor_addr_hash, since this function needs to
1115  * be backportable all the way to 0.2.9. */
1116 
1117  switch (tor_addr_family(addr)) {
1118  case AF_INET:
1119  return siphash24(&addr->addr.in_addr.s_addr, 4, key);
1120  case AF_UNSPEC:
1121  return siphash24(unspec_hash_input, sizeof(unspec_hash_input), key);
1122  case AF_INET6:
1123  return siphash24(&addr->addr.in6_addr.s6_addr, 16, key);
1124  default:
1125  /* LCOV_EXCL_START */
1127  return 0;
1128  /* LCOV_EXCL_STOP */
1129  }
1130 }
1131 
1133 char *
1135 {
1136  char buf[TOR_ADDR_BUF_LEN];
1137  if (tor_addr_to_str(buf, addr, sizeof(buf), 0)) {
1138  return tor_strdup(buf);
1139  } else {
1140  return tor_strdup("<unknown address type>");
1141  }
1142 }
1143 
1153 const char *
1154 fmt_addr_impl(const tor_addr_t *addr, int decorate)
1155 {
1156  static char buf[TOR_ADDR_BUF_LEN];
1157  if (!addr) return "<null>";
1158  if (tor_addr_to_str(buf, addr, sizeof(buf), decorate))
1159  return buf;
1160  else
1161  return "???";
1162 }
1163 
1168 const char *
1169 fmt_addrport(const tor_addr_t *addr, uint16_t port)
1170 {
1171  /* Add space for a colon and up to 5 digits. */
1172  static char buf[TOR_ADDR_BUF_LEN + 6];
1173  tor_snprintf(buf, sizeof(buf), "%s:%u", fmt_and_decorate_addr(addr), port);
1174  return buf;
1175 }
1176 
1180 const char *
1181 fmt_addr32(uint32_t addr)
1182 {
1183  static char buf[INET_NTOA_BUF_LEN];
1184  struct in_addr in;
1185  in.s_addr = htonl(addr);
1186  tor_inet_ntoa(&in, buf, sizeof(buf));
1187  return buf;
1188 }
1189 
1200 static int
1201 tor_addr_parse_impl(tor_addr_t *addr, const char *src,
1202  bool allow_ipv6_without_brackets)
1203 {
1204  /* Holds substring of IPv6 address after removing square brackets */
1205  char *tmp = NULL;
1206  int result = -1;
1207  struct in_addr in_tmp;
1208  struct in6_addr in6_tmp;
1209  int brackets_detected = 0;
1210 
1211  tor_assert(addr && src);
1212 
1213  size_t len = strlen(src);
1214 
1215  if (len && src[0] == '[' && src[len - 1] == ']') {
1216  brackets_detected = 1;
1217  src = tmp = tor_strndup(src+1, strlen(src)-2);
1218  }
1219 
1220  /* Try to parse an IPv6 address if it has brackets, or if IPv6 addresses
1221  * without brackets are allowed */
1222  if (brackets_detected || allow_ipv6_without_brackets) {
1223  if (tor_inet_pton(AF_INET6, src, &in6_tmp) > 0) {
1224  result = AF_INET6;
1225  tor_addr_from_in6(addr, &in6_tmp);
1226  }
1227  }
1228 
1229  /* Try to parse an IPv4 address without brackets */
1230  if (!brackets_detected) {
1231  if (tor_inet_pton(AF_INET, src, &in_tmp) > 0) {
1232  result = AF_INET;
1233  tor_addr_from_in(addr, &in_tmp);
1234  }
1235  }
1236 
1237  /* Clear the address on error, to avoid returning uninitialised or partly
1238  * parsed data.
1239  */
1240  if (result == -1) {
1241  memset(addr, 0, sizeof(tor_addr_t));
1242  }
1243 
1244  tor_free(tmp);
1245  return result;
1246 }
1247 
1254 int
1255 tor_addr_parse(tor_addr_t *addr, const char *src)
1256 {
1257  return tor_addr_parse_impl(addr, src, 1);
1258 }
1259 
1260 #ifdef HAVE_IFADDRS_TO_SMARTLIST
1261 /*
1262  * Convert a linked list consisting of <b>ifaddrs</b> structures
1263  * into smartlist of <b>tor_addr_t</b> structures.
1264  */
1265 STATIC smartlist_t *
1266 ifaddrs_to_smartlist(const struct ifaddrs *ifa, sa_family_t family)
1267 {
1268  smartlist_t *result = smartlist_new();
1269  const struct ifaddrs *i;
1270 
1271  for (i = ifa; i; i = i->ifa_next) {
1272  tor_addr_t tmp;
1273  if ((i->ifa_flags & (IFF_UP | IFF_RUNNING)) != (IFF_UP | IFF_RUNNING))
1274  continue;
1275  if (!i->ifa_addr)
1276  continue;
1277  if (i->ifa_addr->sa_family != AF_INET &&
1278  i->ifa_addr->sa_family != AF_INET6)
1279  continue;
1280  if (family != AF_UNSPEC && i->ifa_addr->sa_family != family)
1281  continue;
1282  if (tor_addr_from_sockaddr(&tmp, i->ifa_addr, NULL) < 0)
1283  continue;
1284  smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
1285  }
1286 
1287  return result;
1288 }
1289 
1294 STATIC smartlist_t *
1295 get_interface_addresses_ifaddrs(int severity, sa_family_t family)
1296 {
1297 
1298  /* Most free Unixy systems provide getifaddrs, which gives us a linked list
1299  * of struct ifaddrs. */
1300  struct ifaddrs *ifa = NULL;
1301  smartlist_t *result;
1302  if (getifaddrs(&ifa) < 0) {
1303  log_fn(severity, LD_NET, "Unable to call getifaddrs(): %s",
1304  strerror(errno));
1305  return NULL;
1306  }
1307 
1308  result = ifaddrs_to_smartlist(ifa, family);
1309 
1310  freeifaddrs(ifa);
1311 
1312  return result;
1313 }
1314 #endif /* defined(HAVE_IFADDRS_TO_SMARTLIST) */
1315 
1316 #ifdef HAVE_IP_ADAPTER_TO_SMARTLIST
1317 
1322 STATIC smartlist_t *
1323 ip_adapter_addresses_to_smartlist(const IP_ADAPTER_ADDRESSES *addresses)
1324 {
1325  smartlist_t *result = smartlist_new();
1326  const IP_ADAPTER_ADDRESSES *address;
1327 
1328  for (address = addresses; address; address = address->Next) {
1329  const IP_ADAPTER_UNICAST_ADDRESS *a;
1330  for (a = address->FirstUnicastAddress; a; a = a->Next) {
1331  /* Yes, it's a linked list inside a linked list */
1332  const struct sockaddr *sa = a->Address.lpSockaddr;
1333  tor_addr_t tmp;
1334  if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
1335  continue;
1336  if (tor_addr_from_sockaddr(&tmp, sa, NULL) < 0)
1337  continue;
1338  smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
1339  }
1340  }
1341 
1342  return result;
1343 }
1344 
1349 STATIC smartlist_t *
1350 get_interface_addresses_win32(int severity, sa_family_t family)
1351 {
1352  smartlist_t *result = NULL;
1353  ULONG size, res;
1354  IP_ADAPTER_ADDRESSES *addresses = NULL;
1355 
1356  (void) severity;
1357 
1358 #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
1359  GAA_FLAG_SKIP_MULTICAST | \
1360  GAA_FLAG_SKIP_DNS_SERVER)
1361 
1362  /* Guess how much space we need. */
1363  size = 15*1024;
1364  addresses = tor_malloc(size);
1365  /* Exists in windows XP and later. */
1366  res = GetAdaptersAddresses(family, FLAGS, NULL, addresses, &size);
1367  if (res == ERROR_BUFFER_OVERFLOW) {
1368  /* we didn't guess that we needed enough space; try again */
1369  tor_free(addresses);
1370  addresses = tor_malloc(size);
1371  res = GetAdaptersAddresses(AF_UNSPEC, FLAGS, NULL, addresses, &size);
1372  }
1373  if (res != NO_ERROR) {
1374  log_fn(severity, LD_NET, "GetAdaptersAddresses failed (result: %lu)", res);
1375  goto done;
1376  }
1377 
1378  result = ip_adapter_addresses_to_smartlist(addresses);
1379 
1380  done:
1381  tor_free(addresses);
1382  return result;
1383 }
1384 
1385 #endif /* defined(HAVE_IP_ADAPTER_TO_SMARTLIST) */
1386 
1387 #ifdef HAVE_IFCONF_TO_SMARTLIST
1388 
1389 /* Guess how much space we need. There shouldn't be any struct ifreqs
1390  * larger than this, even on OS X where the struct's size is dynamic. */
1391 #define IFREQ_SIZE 4096
1392 
1393 /* This is defined on Mac OS X */
1394 #ifndef _SIZEOF_ADDR_IFREQ
1395 #define _SIZEOF_ADDR_IFREQ sizeof
1396 #endif
1397 
1398 /* Free ifc->ifc_buf safely. */
1399 static void
1400 ifconf_free_ifc_buf(struct ifconf *ifc)
1401 {
1402  /* On macOS, tor_free() takes the address of ifc.ifc_buf, which leads to
1403  * undefined behaviour, because pointer-to-pointers are expected to be
1404  * aligned at 8-bytes, but the ifconf structure is packed. So we use
1405  * raw_free() instead. */
1406  raw_free(ifc->ifc_buf);
1407  ifc->ifc_buf = NULL;
1408 }
1409 
1413 STATIC smartlist_t *
1414 ifreq_to_smartlist(char *buf, size_t buflen)
1415 {
1416  smartlist_t *result = smartlist_new();
1417  char *end = buf + buflen;
1418 
1419  /* These acrobatics are due to alignment issues which trigger
1420  * undefined behaviour traps on OSX. */
1421  struct ifreq *r = tor_malloc(IFREQ_SIZE);
1422 
1423  while (buf < end) {
1424  /* Copy up to IFREQ_SIZE bytes into the struct ifreq, but don't overrun
1425  * buf. */
1426  memcpy(r, buf, end - buf < IFREQ_SIZE ? end - buf : IFREQ_SIZE);
1427 
1428  const struct sockaddr *sa = &r->ifr_addr;
1429  tor_addr_t tmp;
1430  int valid_sa_family = (sa->sa_family == AF_INET ||
1431  sa->sa_family == AF_INET6);
1432 
1433  int conversion_success = (tor_addr_from_sockaddr(&tmp, sa, NULL) == 0);
1434 
1435  if (valid_sa_family && conversion_success)
1436  smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
1437 
1438  buf += _SIZEOF_ADDR_IFREQ(*r);
1439  }
1440 
1441  tor_free(r);
1442  return result;
1443 }
1444 
1449 STATIC smartlist_t *
1450 get_interface_addresses_ioctl(int severity, sa_family_t family)
1451 {
1452  /* Some older unixy systems make us use ioctl(SIOCGIFCONF) */
1453  struct ifconf ifc;
1454  ifc.ifc_buf = NULL;
1455  int fd;
1456  smartlist_t *result = NULL;
1457 
1458  /* This interface, AFAICT, only supports AF_INET addresses,
1459  * except on AIX. For Solaris, we could use SIOCGLIFCONF. */
1460 
1461  /* Bail out if family is neither AF_INET nor AF_UNSPEC since
1462  * ioctl() technique supports non-IPv4 interface addresses on
1463  * a small number of niche systems only. If family is AF_UNSPEC,
1464  * fall back to getting AF_INET addresses only. */
1465  if (family == AF_UNSPEC)
1466  family = AF_INET;
1467  else if (family != AF_INET)
1468  return NULL;
1469 
1470  fd = socket(family, SOCK_DGRAM, 0);
1471  if (fd < 0) {
1472  tor_log(severity, LD_NET, "socket failed: %s", strerror(errno));
1473  goto done;
1474  }
1475 
1476  int mult = 1;
1477  do {
1478  mult *= 2;
1479  ifc.ifc_len = mult * IFREQ_SIZE;
1480  ifc.ifc_buf = tor_realloc(ifc.ifc_buf, ifc.ifc_len);
1481 
1482  tor_assert(ifc.ifc_buf);
1483 
1484  if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) {
1485  tor_log(severity, LD_NET, "ioctl failed: %s", strerror(errno));
1486  goto done;
1487  }
1488  /* Ensure we have least IFREQ_SIZE bytes unused at the end. Otherwise, we
1489  * don't know if we got everything during ioctl. */
1490  } while (mult * IFREQ_SIZE - ifc.ifc_len <= IFREQ_SIZE);
1491  result = ifreq_to_smartlist(ifc.ifc_buf, ifc.ifc_len);
1492 
1493  done:
1494  if (fd >= 0)
1495  close(fd);
1496  ifconf_free_ifc_buf(&ifc);
1497  return result;
1498 }
1499 #endif /* defined(HAVE_IFCONF_TO_SMARTLIST) */
1500 
1508 get_interface_addresses_raw,(int severity, sa_family_t family))
1509 {
1510  smartlist_t *result = NULL;
1511 #if defined(HAVE_IFADDRS_TO_SMARTLIST)
1512  if ((result = get_interface_addresses_ifaddrs(severity, family)))
1513  return result;
1514 #endif
1515 #if defined(HAVE_IP_ADAPTER_TO_SMARTLIST)
1516  if ((result = get_interface_addresses_win32(severity, family)))
1517  return result;
1518 #endif
1519 #if defined(HAVE_IFCONF_TO_SMARTLIST)
1520  if ((result = get_interface_addresses_ioctl(severity, family)))
1521  return result;
1522 #endif
1523  (void) severity;
1524  (void) result;
1525  return NULL;
1526 }
1527 
1529 int
1531 {
1532  sa_family_t family = tor_addr_family(a);
1533  if (family == AF_INET) {
1534  uint32_t ipv4h = tor_addr_to_ipv4h(a);
1535  if ((ipv4h >> 24) == 0xe0)
1536  return 1; /* Multicast */
1537  } else if (family == AF_INET6) {
1538  const uint8_t *a32 = tor_addr_to_in6_addr8(a);
1539  if (a32[0] == 0xff)
1540  return 1;
1541  }
1542  return 0;
1543 }
1544 
1551 get_interface_address6_via_udp_socket_hack,(int severity,
1552  sa_family_t family,
1553  tor_addr_t *addr))
1554 {
1555  struct sockaddr_storage target_addr;
1556  int sock=-1, r=-1;
1557  socklen_t addr_len;
1558 
1559  memset(addr, 0, sizeof(tor_addr_t));
1560  memset(&target_addr, 0, sizeof(target_addr));
1561 
1562  /* Don't worry: no packets are sent. We just need to use a real address
1563  * on the actual Internet. */
1564  if (family == AF_INET6) {
1565  struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&target_addr;
1566  /* Use the "discard" service port */
1567  sin6->sin6_port = htons(9);
1568  sock = tor_open_socket(PF_INET6,SOCK_DGRAM,IPPROTO_UDP);
1569  addr_len = (socklen_t)sizeof(struct sockaddr_in6);
1570  sin6->sin6_family = AF_INET6;
1571  S6_ADDR16(sin6->sin6_addr)[0] = htons(0x2002); /* 2002:: */
1572  } else if (family == AF_INET) {
1573  struct sockaddr_in *sin = (struct sockaddr_in*)&target_addr;
1574  /* Use the "discard" service port */
1575  sin->sin_port = htons(9);
1576  sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
1577  addr_len = (socklen_t)sizeof(struct sockaddr_in);
1578  sin->sin_family = AF_INET;
1579  sin->sin_addr.s_addr = htonl(0x12000001); /* 18.0.0.1 */
1580  } else {
1581  return -1;
1582  }
1583 
1584  if (sock < 0) {
1585  int e = tor_socket_errno(-1);
1586  log_fn(severity, LD_NET, "unable to create socket: %s",
1587  tor_socket_strerror(e));
1588  goto err;
1589  }
1590 
1591  if (tor_connect_socket(sock,(struct sockaddr *)&target_addr,
1592  addr_len) < 0) {
1593  int e = tor_socket_errno(sock);
1594  log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e));
1595  goto err;
1596  }
1597 
1598  if (tor_addr_from_getsockname(addr, sock) < 0) {
1599  int e = tor_socket_errno(sock);
1600  log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s",
1601  tor_socket_strerror(e));
1602  goto err;
1603  }
1604 
1605  if (tor_addr_is_loopback(addr) || tor_addr_is_multicast(addr)) {
1606  log_fn(severity, LD_NET, "Address that we determined via UDP socket"
1607  " magic is unsuitable for public comms.");
1608  } else {
1609  r=0;
1610  }
1611 
1612  err:
1613  if (sock >= 0)
1614  tor_close_socket(sock);
1615  if (r == -1)
1616  memset(addr, 0, sizeof(tor_addr_t));
1617  return r;
1618 }
1619 
1629 get_interface_address6,(int severity, sa_family_t family, tor_addr_t *addr))
1630 {
1631  smartlist_t *addrs;
1632  int rv = -1;
1633  tor_assert(addr);
1634 
1635  memset(addr, 0, sizeof(tor_addr_t));
1636 
1637  /* Get a list of public or internal IPs in arbitrary order */
1638  addrs = get_interface_address6_list(severity, family, 1);
1639 
1640  /* Find the first non-internal address, or the last internal address
1641  * Ideally, we want the default route, see #12377 for details */
1642  SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a) {
1643  tor_addr_copy(addr, a);
1644  rv = 0;
1645 
1646  /* If we found a non-internal address, declare success. Otherwise,
1647  * keep looking. */
1648  if (!tor_addr_is_internal(a, 0))
1649  break;
1650  } SMARTLIST_FOREACH_END(a);
1651 
1652  interface_address6_list_free(addrs);
1653  return rv;
1654 }
1655 
1658 void
1660 {
1661  if (addrs != NULL) {
1662  SMARTLIST_FOREACH(addrs, tor_addr_t *, a, tor_free(a));
1663  smartlist_free(addrs);
1664  }
1665 }
1666 
1677 get_interface_address6_list,(int severity,
1678  sa_family_t family,
1679  int include_internal))
1680 {
1681  smartlist_t *addrs;
1682  tor_addr_t addr;
1683 
1684  /* Try to do this the smart way if possible. */
1685  if ((addrs = get_interface_addresses_raw(severity, family))) {
1686  SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a)
1687  {
1688  if (tor_addr_is_loopback(a) ||
1689  tor_addr_is_multicast(a)) {
1691  tor_free(a);
1692  continue;
1693  }
1694 
1695  if (!include_internal && tor_addr_is_internal(a, 0)) {
1697  tor_free(a);
1698  continue;
1699  }
1700  } SMARTLIST_FOREACH_END(a);
1701  }
1702 
1703  if (addrs && smartlist_len(addrs) > 0) {
1704  return addrs;
1705  }
1706 
1707  /* if we removed all entries as unsuitable */
1708  if (addrs) {
1709  smartlist_free(addrs);
1710  }
1711 
1712  /* Okay, the smart way is out. */
1713  addrs = smartlist_new();
1714 
1715  if (family == AF_INET || family == AF_UNSPEC) {
1716  if (get_interface_address6_via_udp_socket_hack(severity,AF_INET,
1717  &addr) == 0) {
1718  if (include_internal || !tor_addr_is_internal(&addr, 0)) {
1719  smartlist_add(addrs, tor_memdup(&addr, sizeof(addr)));
1720  }
1721  }
1722  }
1723 
1724  if (family == AF_INET6 || family == AF_UNSPEC) {
1725  if (get_interface_address6_via_udp_socket_hack(severity,AF_INET6,
1726  &addr) == 0) {
1727  if (include_internal || !tor_addr_is_internal(&addr, 0)) {
1728  smartlist_add(addrs, tor_memdup(&addr, sizeof(addr)));
1729  }
1730  }
1731  }
1732 
1733  return addrs;
1734 }
1735 
1736 /* ======
1737  * IPv4 helpers
1738  * XXXX IPv6 deprecate some of these.
1739  */
1740 
1758 int
1759 tor_addr_port_parse(int severity, const char *addrport,
1760  tor_addr_t *address_out, uint16_t *port_out,
1761  int default_port)
1762 {
1763  int retval = -1;
1764  int r;
1765  char *addr_tmp = NULL;
1766  bool has_port;
1767 
1768  tor_assert(addrport);
1769  tor_assert(address_out);
1770  tor_assert(port_out);
1771 
1772  r = tor_addr_port_split(severity, addrport, &addr_tmp, port_out);
1773  if (r < 0)
1774  goto done;
1775 
1776  has_port = !! *port_out;
1777  /* If there's no port, use the default port, or fail if there is no default
1778  */
1779  if (!has_port) {
1780  if (default_port >= 0)
1781  *port_out = default_port;
1782  else
1783  goto done;
1784  }
1785 
1786  /* Make sure that address_out is an IP address.
1787  * If there is no port in addrport, allow IPv6 addresses without brackets. */
1788  if (tor_addr_parse_impl(address_out, addr_tmp, !has_port) < 0)
1789  goto done;
1790 
1791  retval = 0;
1792 
1793  done:
1794  /* Clear the address and port on error, to avoid returning uninitialised or
1795  * partly parsed data.
1796  */
1797  if (retval == -1) {
1798  memset(address_out, 0, sizeof(tor_addr_t));
1799  *port_out = 0;
1800  }
1801  tor_free(addr_tmp);
1802  return retval;
1803 }
1804 
1817 int
1818 tor_addr_port_split(int severity, const char *addrport,
1819  char **address_out, uint16_t *port_out)
1820 {
1821  tor_addr_t a_tmp;
1822  tor_assert(addrport);
1823  tor_assert(address_out);
1824  tor_assert(port_out);
1825 
1826  /* We need to check for IPv6 manually because the logic below doesn't
1827  * do a good job on IPv6 addresses that lack a port.
1828  * If an IPv6 address without square brackets is ambiguous, it gets parsed
1829  * here as an address, rather than address:port. */
1830  if (tor_addr_parse(&a_tmp, addrport) == AF_INET6) {
1831  *port_out = 0;
1832  *address_out = tor_strdup(addrport);
1833  return 0;
1834  }
1835 
1836  const char *colon;
1837  char *address_ = NULL;
1838  int port_;
1839  int ok = 1;
1840 
1841  colon = strrchr(addrport, ':');
1842  if (colon) {
1843  address_ = tor_strndup(addrport, colon-addrport);
1844  port_ = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
1845  if (!port_) {
1846  log_fn(severity, LD_GENERAL, "Port %s out of range", escaped(colon+1));
1847  ok = 0;
1848  }
1849  if (!port_out) {
1850  char *esc_addrport = esc_for_log(addrport);
1851  log_fn(severity, LD_GENERAL,
1852  "Port %s given on %s when not required",
1853  escaped(colon+1), esc_addrport);
1854  tor_free(esc_addrport);
1855  ok = 0;
1856  }
1857  } else {
1858  address_ = tor_strdup(addrport);
1859  port_ = 0;
1860  }
1861 
1862  if (ok) {
1863  *address_out = address_;
1864  } else {
1865  *address_out = NULL;
1866  tor_free(address_);
1867  }
1868 
1869  *port_out = ok ? ((uint16_t) port_) : 0;
1870 
1871  return ok ? 0 : -1;
1872 }
1873 
1876 int
1877 addr_mask_get_bits(uint32_t mask)
1878 {
1879  int i;
1880  if (mask == 0)
1881  return 0;
1882  if (mask == 0xFFFFFFFFu)
1883  return 32;
1884  for (i=1; i<=32; ++i) {
1885  if (mask == (uint32_t) ~((1u<<(32-i))-1)) {
1886  return i;
1887  }
1888  }
1889  return -1;
1890 }
1891 
1895 int
1896 parse_port_range(const char *port, uint16_t *port_min_out,
1897  uint16_t *port_max_out)
1898 {
1899  int port_min, port_max, ok;
1900  tor_assert(port_min_out);
1901  tor_assert(port_max_out);
1902 
1903  if (!port || *port == '\0' || strcmp(port, "*") == 0) {
1904  port_min = 1;
1905  port_max = 65535;
1906  } else {
1907  char *endptr = NULL;
1908  port_min = (int)tor_parse_long(port, 10, 0, 65535, &ok, &endptr);
1909  if (!ok) {
1910  log_warn(LD_GENERAL,
1911  "Malformed port %s on address range; rejecting.",
1912  escaped(port));
1913  return -1;
1914  } else if (endptr && *endptr == '-') {
1915  port = endptr+1;
1916  endptr = NULL;
1917  port_max = (int)tor_parse_long(port, 10, 1, 65535, &ok, &endptr);
1918  if (!ok) {
1919  log_warn(LD_GENERAL,
1920  "Malformed port %s on address range; rejecting.",
1921  escaped(port));
1922  return -1;
1923  }
1924  } else {
1925  port_max = port_min;
1926  }
1927  if (port_min > port_max) {
1928  log_warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
1929  return -1;
1930  }
1931  }
1932 
1933  if (port_min < 1)
1934  port_min = 1;
1935  if (port_max > 65535)
1936  port_max = 65535;
1937 
1938  *port_min_out = (uint16_t) port_min;
1939  *port_max_out = (uint16_t) port_max;
1940 
1941  return 0;
1942 }
1943 
1947 char *
1948 tor_dup_ip(uint32_t addr)
1949 {
1950  char buf[TOR_ADDR_BUF_LEN];
1951  struct in_addr in;
1952 
1953  in.s_addr = htonl(addr);
1954  tor_inet_ntop(AF_INET, &in, buf, sizeof(buf));
1955  return tor_strdup(buf);
1956 }
1957 
1968 get_interface_address,(int severity, uint32_t *addr))
1969 {
1970  tor_addr_t local_addr;
1971  int r;
1972 
1973  memset(addr, 0, sizeof(uint32_t));
1974 
1975  r = get_interface_address6(severity, AF_INET, &local_addr);
1976  if (r>=0)
1977  *addr = tor_addr_to_ipv4h(&local_addr);
1978  return r;
1979 }
1980 
1984 int
1986 {
1987  return !strcasecmp(name, "localhost") ||
1988  !strcasecmp(name, "local") ||
1989  !strcasecmpend(name, ".local");
1990 }
1991 
1995 tor_addr_port_new(const tor_addr_t *addr, uint16_t port)
1996 {
1997  tor_addr_port_t *ap = tor_malloc_zero(sizeof(tor_addr_port_t));
1998  if (addr)
1999  tor_addr_copy(&ap->addr, addr);
2000  ap->port = port;
2001  return ap;
2002 }
2003 
2005 int
2007  const tor_addr_port_t *b)
2008 {
2009  return tor_addr_eq(&a->addr, &b->addr) && a->port == b->port;
2010 }
2011 
2015 int
2016 string_is_valid_ipv4_address(const char *string)
2017 {
2018  struct in_addr addr;
2019 
2020  return (tor_inet_pton(AF_INET,string,&addr) == 1);
2021 }
2022 
2026 int
2027 string_is_valid_ipv6_address(const char *string)
2028 {
2029  struct in6_addr addr;
2030 
2031  return (tor_inet_pton(AF_INET6,string,&addr) == 1);
2032 }
2033 
2037 int
2038 string_is_valid_dest(const char *string)
2039 {
2040  char *tmp = NULL;
2041  int retval;
2042  size_t len;
2043 
2044  if (string == NULL)
2045  return 0;
2046 
2047  len = strlen(string);
2048 
2049  if (len == 0)
2050  return 0;
2051 
2052  if (string[0] == '[' && string[len - 1] == ']')
2053  string = tmp = tor_strndup(string + 1, len - 2);
2054 
2055  retval = string_is_valid_ipv4_address(string) ||
2056  string_is_valid_ipv6_address(string) ||
2058 
2059  tor_free(tmp);
2060 
2061  return retval;
2062 }
2063 
2070 int
2072 {
2073  int result = 1;
2074  int has_trailing_dot;
2075  char *last_label;
2076  smartlist_t *components;
2077 
2078  if (!string || strlen(string) == 0)
2079  return 0;
2080 
2081  if (string_is_valid_ipv4_address(string))
2082  return 0;
2083 
2084  components = smartlist_new();
2085 
2086  smartlist_split_string(components,string,".",0,0);
2087 
2088  if (BUG(smartlist_len(components) == 0)) {
2089  // LCOV_EXCL_START should be impossible given the earlier checks.
2090  smartlist_free(components);
2091  return 0;
2092  // LCOV_EXCL_STOP
2093  }
2094 
2095  /* Allow a single terminating '.' used rarely to indicate domains
2096  * are FQDNs rather than relative. */
2097  last_label = (char *)smartlist_get(components,
2098  smartlist_len(components) - 1);
2099  has_trailing_dot = (last_label[0] == '\0');
2100  if (has_trailing_dot) {
2101  smartlist_pop_last(components);
2102  tor_free(last_label);
2103  last_label = NULL;
2104  }
2105 
2106  SMARTLIST_FOREACH_BEGIN(components, char *, c) {
2107  if ((c[0] == '-') || (*c == '_')) {
2108  result = 0;
2109  break;
2110  }
2111 
2112  do {
2113  result = (TOR_ISALNUM(*c) || (*c == '-') || (*c == '_'));
2114  c++;
2115  } while (result && *c);
2116 
2117  if (result == 0) {
2118  break;
2119  }
2120  } SMARTLIST_FOREACH_END(c);
2121 
2122  SMARTLIST_FOREACH_BEGIN(components, char *, c) {
2123  tor_free(c);
2124  } SMARTLIST_FOREACH_END(c);
2125 
2126  smartlist_free(components);
2127 
2128  return result;
2129 }
void tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
Definition: address.c:874
int addr_mask_get_bits(uint32_t mask)
Definition: address.c:1877
const char * tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
Definition: address.c:328
int tor_inet_pton(int af, const char *src, void *dst)
Definition: inaddr.c:166
void interface_address6_list_free_(smartlist_t *addrs)
Definition: address.c:1659
#define TOR_ADDR_BUF_LEN
Definition: address.h:205
#define SMARTLIST_DEL_CURRENT_KEEPORDER(sl, var)
int tor_addr_to_PTR_name(char *out, size_t outlen, const tor_addr_t *addr)
Definition: address.c:470
static int tor_addr_parse_impl(tor_addr_t *addr, const char *src, bool allow_ipv6_without_brackets)
Definition: address.c:1201
Header for printf.c.
static int hex_decode_digit(char c)
Definition: compat_ctype.h:43
Header for smartlist.c.
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
uint16_t sa_family_t
Definition: inaddr_st.h:77
Headers for di_ops.c.
void tor_addr_make_unspec(tor_addr_t *a)
Definition: address.c:225
int string_is_valid_ipv4_address(const char *string)
Definition: address.c:2016
#define CTASSERT(x)
Definition: ctassert.h:44
int tor_addr_parse_PTR_name(tor_addr_t *result, const char *address, int family, int accept_regular)
Definition: address.c:380
#define LD_GENERAL
Definition: log.h:60
int tor_addr_is_internal_(const tor_addr_t *addr, int for_listening, const char *filename, int lineno)
Definition: address.c:255
int tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2, tor_addr_comparison_t how)
Definition: address.c:954
int tor_addr_port_eq(const tor_addr_port_t *a, const tor_addr_port_t *b)
Definition: address.c:2006
static uint32_t tor_addr_to_ipv4n(const tor_addr_t *a)
Definition: address.h:145
int tor_addr_hostname_is_local(const char *name)
Definition: address.c:1985
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:633
void tor_addr_make_null(tor_addr_t *a, sa_family_t family)
Definition: address.c:235
void smartlist_add(smartlist_t *sl, void *element)
void * smartlist_pop_last(smartlist_t *sl)
#define fmt_and_decorate_addr(a)
Definition: address.h:214
socklen_t tor_addr_to_sockaddr(const tor_addr_t *a, uint16_t port, struct sockaddr *sa_out, socklen_t len)
Definition: address.c:113
static uint32_t tor_addr_to_ipv4h(const tor_addr_t *a)
Definition: address.h:152
int tor_inet_aton(const char *str, struct in_addr *addr)
Definition: inaddr.c:38
int string_is_valid_nonrfc_hostname(const char *string)
Definition: address.c:2071
#define tor_free(p)
Definition: malloc.h:52
Header for util_string.c.
Header for inaddr.c.
static const uint32_t unspec_hash_input[]
Definition: address.c:1089
#define tor_fragile_assert()
Definition: util_bug.h:241
#define INET_NTOA_BUF_LEN
Definition: inaddr.h:21
Headers for util_malloc.c.
int parse_port_range(const char *port, uint16_t *port_min_out, uint16_t *port_max_out)
Definition: address.c:1896
int tor_addr_from_getsockname(struct tor_addr_t *addr_out, tor_socket_t sock)
Definition: socket.c:545
#define tor_addr_from_in(dest, in)
Definition: address.h:291
const char * tor_inet_ntop(int af, const void *src, char *dst, size_t len)
Definition: inaddr.c:77
int tor_addr_is_v4(const tor_addr_t *addr)
Definition: address.c:749
uint8_t maskbits_t
Definition: address.h:62
tor_assert(buffer)
char * tor_sockaddr_to_str(const struct sockaddr *sa)
Definition: address.c:198
static uint32_t tor_addr_to_mapped_ipv4h(const tor_addr_t *a)
Definition: address.h:161
int strcasecmpend(const char *s1, const char *s2)
Definition: util_string.c:255
#define tor_addr_from_ipv4h(dest, v4addr)
Definition: address.h:287
tor_addr_comparison_t
Definition: address.h:233
int tor_memcmp(const void *a, const void *b, size_t len)
Definition: di_ops.c:31
#define REVERSE_LOOKUP_NAME_BUF_LEN
Definition: address.h:258
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
const char * fmt_addrport(const tor_addr_t *addr, uint16_t port)
Definition: address.c:1169
static void tor_addr_make_af_unix(tor_addr_t *a)
Definition: address.c:154
int tor_addr_port_parse(int severity, const char *addrport, tor_addr_t *address_out, uint16_t *port_out, int default_port)
Definition: address.c:1759
const char * fmt_addr_impl(const tor_addr_t *addr, int decorate)
Definition: address.c:1154
void tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
Definition: address.c:885
Headers for address.h.
int tor_addr_parse_mask_ports(const char *s, unsigned flags, tor_addr_t *addr_out, maskbits_t *maskbits_out, uint16_t *port_min_out, uint16_t *port_max_out)
Definition: address.c:543
int tor_addr_parse(tor_addr_t *addr, const char *src)
Definition: address.c:1255
uint64_t tor_addr_hash(const tor_addr_t *addr)
Definition: address.c:1093
const char * fmt_addr32(uint32_t addr)
Definition: address.c:1181
int tor_addr_is_null(const tor_addr_t *addr)
Definition: address.c:770
Header for process.c.
int tor_addr_is_loopback(const tor_addr_t *addr)
Definition: address.c:795
uint64_t tor_addr_keyed_hash(const struct sipkey *key, const tor_addr_t *addr)
Definition: address.c:1112
int tor_addr_is_multicast(const tor_addr_t *a)
Definition: address.c:1530
Compile-time assertions: CTASSERT(expression).
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
char * tor_addr_to_str_dup(const tor_addr_t *addr)
Definition: address.c:1134
void tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
Definition: address.c:896
#define SMARTLIST_FOREACH(sl, type, var, cmd)
tor_addr_port_t * tor_addr_port_new(const tor_addr_t *addr, uint16_t port)
Definition: address.c:1995
const char * escaped(const char *s)
Definition: escape.c:126
int string_is_valid_ipv6_address(const char *string)
Definition: address.c:2027
Locale-independent character-type inspection (header)
#define log_fn(severity, domain, args,...)
Definition: log.h:274
int string_is_valid_dest(const char *string)
Definition: address.c:2038
#define tor_addr_to_in6_addr32(x)
Definition: address.h:140
#define tor_addr_eq(a, b)
Definition: address.h:244
Header for compat_string.c.
int tor_inet_ntoa(const struct in_addr *in, char *buf, size_t buf_len)
Definition: inaddr.c:58
Header for escape.c.
static const struct in6_addr * tor_addr_to_in6_assert(const tor_addr_t *a)
Definition: address.h:119
long tor_parse_long(const char *s, int base, long min, long max, int *ok, char **next)
Definition: parse_int.c:56
MOCK_IMPL(smartlist_t *, get_interface_addresses_raw,(int severity, sa_family_t family))
Definition: address.c:1507
int tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2, maskbits_t mbits, tor_addr_comparison_t how)
Definition: address.c:975
char * esc_for_log(const char *s)
Definition: escape.c:30
#define LD_NET
Definition: log.h:64
#define tor_addr_to_in6_addr8(x)
Definition: address.h:129
Headers for log.c.
Header for socket.c.
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:904
void tor_addr_copy_tight(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:918
Header for parse_int.c.
int tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa, uint16_t *port_out)
Definition: address.c:165
#define LD_BUG
Definition: log.h:84
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition: address.h:179
int tor_addr_port_split(int severity, const char *addrport, char **address_out, uint16_t *port_out)
Definition: address.c:1818
int smartlist_split_string(smartlist_t *sl, const char *str, const char *sep, int flags, int max)
char * tor_dup_ip(uint32_t addr)
Definition: address.c:1948