tor  0.4.1.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 < (3 + (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 
378 int
379 tor_addr_parse_PTR_name(tor_addr_t *result, const char *address,
380  int family, int accept_regular)
381 {
382  if (!strcasecmpend(address, ".in-addr.arpa")) {
383  /* We have an in-addr.arpa address. */
384  char buf[INET_NTOA_BUF_LEN];
385  size_t len;
386  struct in_addr inaddr;
387  if (family == AF_INET6)
388  return -1;
389 
390  len = strlen(address) - strlen(".in-addr.arpa");
391  if (len >= INET_NTOA_BUF_LEN)
392  return -1; /* Too long. */
393 
394  memcpy(buf, address, len);
395  buf[len] = '\0';
396  if (tor_inet_aton(buf, &inaddr) == 0)
397  return -1; /* malformed. */
398 
399  /* reverse the bytes */
400  inaddr.s_addr = (uint32_t)
401  (((inaddr.s_addr & 0x000000ff) << 24)
402  |((inaddr.s_addr & 0x0000ff00) << 8)
403  |((inaddr.s_addr & 0x00ff0000) >> 8)
404  |((inaddr.s_addr & 0xff000000) >> 24));
405 
406  if (result) {
407  tor_addr_from_in(result, &inaddr);
408  }
409  return 1;
410  }
411 
412  if (!strcasecmpend(address, ".ip6.arpa")) {
413  const char *cp;
414  int n0, n1;
415  struct in6_addr in6;
416 
417  if (family == AF_INET)
418  return -1;
419 
420  cp = address;
421  for (int i = 0; i < 16; ++i) {
422  n0 = hex_decode_digit(*cp++); /* The low-order nybble appears first. */
423  if (*cp++ != '.') return -1; /* Then a dot. */
424  n1 = hex_decode_digit(*cp++); /* The high-order nybble appears first. */
425  if (*cp++ != '.') return -1; /* Then another dot. */
426  if (n0<0 || n1 < 0) /* Both nybbles must be hex. */
427  return -1;
428 
429  /* We don't check the length of the string in here. But that's okay,
430  * since we already know that the string ends with ".ip6.arpa", and
431  * there is no way to frameshift .ip6.arpa so it fits into the pattern
432  * of hexdigit, period, hexdigit, period that we enforce above.
433  */
434 
435  /* Assign from low-byte to high-byte. */
436  in6.s6_addr[15-i] = n0 | (n1 << 4);
437  }
438  if (strcasecmp(cp, "ip6.arpa"))
439  return -1;
440 
441  if (result) {
442  tor_addr_from_in6(result, &in6);
443  }
444  return 1;
445  }
446 
447  if (accept_regular) {
448  tor_addr_t tmp;
449  int r = tor_addr_parse(&tmp, address);
450  if (r < 0)
451  return 0;
452  if (r != family && family != AF_UNSPEC)
453  return -1;
454 
455  if (result)
456  memcpy(result, &tmp, sizeof(tor_addr_t));
457 
458  return 1;
459  }
460 
461  return 0;
462 }
463 
468 int
469 tor_addr_to_PTR_name(char *out, size_t outlen,
470  const tor_addr_t *addr)
471 {
472  tor_assert(out);
473  tor_assert(addr);
474 
475  if (addr->family == AF_INET) {
476  uint32_t a = tor_addr_to_ipv4h(addr);
477 
478  return tor_snprintf(out, outlen, "%d.%d.%d.%d.in-addr.arpa",
479  (int)(uint8_t)((a )&0xff),
480  (int)(uint8_t)((a>>8 )&0xff),
481  (int)(uint8_t)((a>>16)&0xff),
482  (int)(uint8_t)((a>>24)&0xff));
483  } else if (addr->family == AF_INET6) {
484  int i;
485  char *cp = out;
486  const uint8_t *bytes = tor_addr_to_in6_addr8(addr);
487  if (outlen < REVERSE_LOOKUP_NAME_BUF_LEN)
488  return -1;
489  for (i = 15; i >= 0; --i) {
490  uint8_t byte = bytes[i];
491  *cp++ = "0123456789abcdef"[byte & 0x0f];
492  *cp++ = '.';
493  *cp++ = "0123456789abcdef"[byte >> 4];
494  *cp++ = '.';
495  }
496  memcpy(cp, "ip6.arpa", 9); /* 8 characters plus NUL */
497  return 32 * 2 + 8;
498  }
499  return -1;
500 }
501 
541 int
543  unsigned flags,
544  tor_addr_t *addr_out,
545  maskbits_t *maskbits_out,
546  uint16_t *port_min_out, uint16_t *port_max_out)
547 {
548  char *base = NULL, *address, *mask = NULL, *port = NULL, *rbracket = NULL;
549  char *endptr;
550  int any_flag=0, v4map=0;
551  sa_family_t family;
552  struct in6_addr in6_tmp;
553  struct in_addr in_tmp = { .s_addr = 0 };
554 
555  tor_assert(s);
556  tor_assert(addr_out);
557  /* We can either only want an IPv4 address or only want an IPv6 address,
558  * but we can't only want IPv4 & IPv6 at the same time. */
559  tor_assert(!((flags & TAPMP_STAR_IPV4_ONLY)
560  && (flags & TAPMP_STAR_IPV6_ONLY)));
561 
564 #define MAX_ADDRESS_LENGTH (TOR_ADDR_BUF_LEN+2+(1+INET_NTOA_BUF_LEN)+12+1)
565 
566  if (strlen(s) > MAX_ADDRESS_LENGTH) {
567  log_warn(LD_GENERAL, "Impossibly long IP %s; rejecting", escaped(s));
568  goto err;
569  }
570  base = tor_strdup(s);
571 
572  /* Break 'base' into separate strings. */
573  address = base;
574  if (*address == '[') { /* Probably IPv6 */
575  address++;
576  rbracket = strchr(address, ']');
577  if (!rbracket) {
578  log_warn(LD_GENERAL,
579  "No closing IPv6 bracket in address pattern; rejecting.");
580  goto err;
581  }
582  }
583  mask = strchr((rbracket?rbracket:address),'/');
584  port = strchr((mask?mask:(rbracket?rbracket:address)), ':');
585  if (port)
586  *port++ = '\0';
587  if (mask)
588  *mask++ = '\0';
589  if (rbracket)
590  *rbracket = '\0';
591  if (port && mask)
592  tor_assert(port > mask);
593  if (mask && rbracket)
594  tor_assert(mask > rbracket);
595 
596  /* Now "address" is the a.b.c.d|'*'|abcd::1 part...
597  * "mask" is the Mask|Maskbits part...
598  * and "port" is the *|port|min-max part.
599  */
600 
601  /* Process the address portion */
602  memset(addr_out, 0, sizeof(tor_addr_t));
603 
604  if (!strcmp(address, "*")) {
605  if (flags & TAPMP_EXTENDED_STAR) {
606  if (flags & TAPMP_STAR_IPV4_ONLY) {
607  family = AF_INET;
608  tor_addr_from_ipv4h(addr_out, 0);
609  } else if (flags & TAPMP_STAR_IPV6_ONLY) {
610  static char nil_bytes[16] = { [0]=0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };
611  family = AF_INET6;
612  tor_addr_from_ipv6_bytes(addr_out, nil_bytes);
613  } else {
614  family = AF_UNSPEC;
615  tor_addr_make_unspec(addr_out);
616  log_info(LD_GENERAL,
617  "'%s' expands into rules which apply to all IPv4 and IPv6 "
618  "addresses. (Use accept/reject *4:* for IPv4 or "
619  "accept[6]/reject[6] *6:* for IPv6.)", s);
620  }
621  } else {
622  family = AF_INET;
623  tor_addr_from_ipv4h(addr_out, 0);
624  }
625  any_flag = 1;
626  } else if (!strcmp(address, "*4") && (flags & TAPMP_EXTENDED_STAR)) {
627  family = AF_INET;
628  tor_addr_from_ipv4h(addr_out, 0);
629  any_flag = 1;
630  } else if (!strcmp(address, "*6") && (flags & TAPMP_EXTENDED_STAR)) {
631  static char nil_bytes[16] = { [0]=0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };
632  family = AF_INET6;
633  tor_addr_from_ipv6_bytes(addr_out, nil_bytes);
634  any_flag = 1;
635  } else if (tor_inet_pton(AF_INET6, address, &in6_tmp) > 0) {
636  family = AF_INET6;
637  tor_addr_from_in6(addr_out, &in6_tmp);
638  } else if (tor_inet_pton(AF_INET, address, &in_tmp) > 0) {
639  family = AF_INET;
640  tor_addr_from_in(addr_out, &in_tmp);
641  } else {
642  log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
643  escaped(address));
644  goto err;
645  }
646 
647  v4map = tor_addr_is_v4(addr_out);
648 
649  /* Parse mask */
650  if (maskbits_out) {
651  int bits = 0;
652  struct in_addr v4mask;
653 
654  if (mask) { /* the caller (tried to) specify a mask */
655  bits = (int) strtol(mask, &endptr, 10);
656  if (!*endptr) { /* strtol converted everything, so it was an integer */
657  if ((bits<0 || bits>128) ||
658  (family == AF_INET && bits > 32)) {
659  log_warn(LD_GENERAL,
660  "Bad number of mask bits (%d) on address range; rejecting.",
661  bits);
662  goto err;
663  }
664  } else { /* mask might still be an address-style mask */
665  if (tor_inet_pton(AF_INET, mask, &v4mask) > 0) {
666  bits = addr_mask_get_bits(ntohl(v4mask.s_addr));
667  if (bits < 0) {
668  log_warn(LD_GENERAL,
669  "IPv4-style mask %s is not a prefix address; rejecting.",
670  escaped(mask));
671  goto err;
672  }
673  } else { /* Not IPv4; we don't do address-style IPv6 masks. */
674  log_warn(LD_GENERAL,
675  "Malformed mask on address range %s; rejecting.",
676  escaped(s));
677  goto err;
678  }
679  }
680  if (family == AF_INET6 && v4map) {
681  if (bits > 32 && bits < 96) { /* Crazy */
682  log_warn(LD_GENERAL,
683  "Bad mask bits %d for V4-mapped V6 address; rejecting.",
684  bits);
685  goto err;
686  }
687  /* XXXX_IP6 is this really what we want? */
688  bits = 96 + bits%32; /* map v4-mapped masks onto 96-128 bits */
689  }
690  if (any_flag) {
691  log_warn(LD_GENERAL,
692  "Found bit prefix with wildcard address; rejecting");
693  goto err;
694  }
695  } else { /* pick an appropriate mask, as none was given */
696  if (any_flag)
697  bits = 0; /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */
698  else if (tor_addr_family(addr_out) == AF_INET)
699  bits = 32;
700  else if (tor_addr_family(addr_out) == AF_INET6)
701  bits = 128;
702  }
703  *maskbits_out = (maskbits_t) bits;
704  } else {
705  if (mask) {
706  log_warn(LD_GENERAL,
707  "Unexpected mask in address %s; rejecting", escaped(s));
708  goto err;
709  }
710  }
711 
712  /* Parse port(s) */
713  if (port_min_out) {
714  uint16_t port2;
715  if (!port_max_out) /* caller specified one port; fake the second one */
716  port_max_out = &port2;
717 
718  if (parse_port_range(port, port_min_out, port_max_out) < 0) {
719  goto err;
720  } else if ((*port_min_out != *port_max_out) && port_max_out == &port2) {
721  log_warn(LD_GENERAL,
722  "Wanted one port from address range, but there are two.");
723 
724  port_max_out = NULL; /* caller specified one port, so set this back */
725  goto err;
726  }
727  } else {
728  if (port) {
729  log_warn(LD_GENERAL,
730  "Unexpected ports in address %s; rejecting", escaped(s));
731  goto err;
732  }
733  }
734 
735  tor_free(base);
736  return tor_addr_family(addr_out);
737  err:
738  tor_free(base);
739  return -1;
740 }
741 
747 int
749 {
750  tor_assert(addr);
751 
752  if (tor_addr_family(addr) == AF_INET)
753  return 1;
754 
755  if (tor_addr_family(addr) == AF_INET6) {
756  /* First two don't need to be ordered */
757  uint32_t *a32 = tor_addr_to_in6_addr32(addr);
758  if (a32[0] == 0 && a32[1] == 0 && ntohl(a32[2]) == 0x0000ffffu)
759  return 1;
760  }
761 
762  return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */
763 }
764 
768 int
770 {
771  tor_assert(addr);
772 
773  switch (tor_addr_family(addr)) {
774  case AF_INET6: {
775  uint32_t *a32 = tor_addr_to_in6_addr32(addr);
776  return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 0);
777  }
778  case AF_INET:
779  return (tor_addr_to_ipv4n(addr) == 0);
780  case AF_UNIX:
781  return 1;
782  case AF_UNSPEC:
783  return 1;
784  default:
785  log_warn(LD_BUG, "Called with unknown address family %d",
786  (int)tor_addr_family(addr));
787  return 0;
788  }
789  //return 1;
790 }
791 
793 int
795 {
796  tor_assert(addr);
797  switch (tor_addr_family(addr)) {
798  case AF_INET6: {
799  /* ::1 */
800  uint32_t *a32 = tor_addr_to_in6_addr32(addr);
801  return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) &&
802  (ntohl(a32[3]) == 1);
803  }
804  case AF_INET:
805  /* 127.0.0.1 */
806  return (tor_addr_to_ipv4h(addr) & 0xff000000) == 0x7f000000;
807  case AF_UNSPEC:
808  return 0;
809  /* LCOV_EXCL_START */
810  default:
812  return 0;
813  /* LCOV_EXCL_STOP */
814  }
815 }
816 
817 /* Is addr valid?
818  * Checks that addr is non-NULL and not tor_addr_is_null().
819  * If for_listening is true, IPv4 addr 0.0.0.0 is allowed.
820  * It means "bind to all addresses on the local machine". */
821 int
822 tor_addr_is_valid(const tor_addr_t *addr, int for_listening)
823 {
824  /* NULL addresses are invalid regardless of for_listening */
825  if (addr == NULL) {
826  return 0;
827  }
828 
829  /* Only allow IPv4 0.0.0.0 for_listening. */
830  if (for_listening && addr->family == AF_INET
831  && tor_addr_to_ipv4h(addr) == 0) {
832  return 1;
833  }
834 
835  /* Otherwise, the address is valid if it's not tor_addr_is_null() */
836  return !tor_addr_is_null(addr);
837 }
838 
839 /* Is the network-order IPv4 address v4n_addr valid?
840  * Checks that addr is not zero.
841  * Except if for_listening is true, where IPv4 addr 0.0.0.0 is allowed. */
842 int
843 tor_addr_is_valid_ipv4n(uint32_t v4n_addr, int for_listening)
844 {
845  /* Any IPv4 address is valid with for_listening. */
846  if (for_listening) {
847  return 1;
848  }
849 
850  /* Otherwise, zero addresses are invalid. */
851  return v4n_addr != 0;
852 }
853 
854 /* Is port valid?
855  * Checks that port is not 0.
856  * Except if for_listening is true, where port 0 is allowed.
857  * It means "OS chooses a port". */
858 int
859 tor_port_is_valid(uint16_t port, int for_listening)
860 {
861  /* Any port value is valid with for_listening. */
862  if (for_listening) {
863  return 1;
864  }
865 
866  /* Otherwise, zero ports are invalid. */
867  return port != 0;
868 }
869 
872 void
873 tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
874 {
875  tor_assert(dest);
876  memset(dest, 0, sizeof(tor_addr_t));
877  dest->family = AF_INET;
878  dest->addr.in_addr.s_addr = v4addr;
879 }
880 
883 void
884 tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
885 {
886  tor_assert(dest);
887  tor_assert(ipv6_bytes);
888  memset(dest, 0, sizeof(tor_addr_t));
889  dest->family = AF_INET6;
890  memcpy(dest->addr.in6_addr.s6_addr, ipv6_bytes, 16);
891 }
892 
894 void
895 tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
896 {
897  tor_addr_from_ipv6_bytes(dest, (const char*)in6->s6_addr);
898 }
899 
902 void
904 {
905  if (src == dest)
906  return;
907  tor_assert(src);
908  tor_assert(dest);
909  memcpy(dest, src, sizeof(tor_addr_t));
910 }
911 
916 void
918 {
919  tor_assert(src != dest);
920  tor_assert(src);
921  tor_assert(dest);
922  memset(dest, 0, sizeof(tor_addr_t));
923  dest->family = src->family;
924  switch (tor_addr_family(src))
925  {
926  case AF_INET:
927  dest->addr.in_addr.s_addr = src->addr.in_addr.s_addr;
928  break;
929  case AF_INET6:
930  memcpy(dest->addr.in6_addr.s6_addr, src->addr.in6_addr.s6_addr, 16);
931  case AF_UNSPEC:
932  break;
933  // LCOV_EXCL_START
934  default:
936  // LCOV_EXCL_STOP
937  }
938 }
939 
952 int
953 tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2,
955 {
956  return tor_addr_compare_masked(addr1, addr2, 128, how);
957 }
958 
973 int
974 tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2,
976 {
979 #define TRISTATE(a,b) (((a)<(b))?-1: (((a)==(b))?0:1))
980  sa_family_t family1, family2, v_family1, v_family2;
981 
982  tor_assert(addr1 && addr2);
983 
984  v_family1 = family1 = tor_addr_family(addr1);
985  v_family2 = family2 = tor_addr_family(addr2);
986 
987  if (family1==family2) {
988  /* When the families are the same, there's only one way to do the
989  * comparison: exactly. */
990  int r;
991  switch (family1) {
992  case AF_UNSPEC:
993  return 0; /* All unspecified addresses are equal */
994  case AF_INET: {
995  uint32_t a1 = tor_addr_to_ipv4h(addr1);
996  uint32_t a2 = tor_addr_to_ipv4h(addr2);
997  if (mbits <= 0)
998  return 0;
999  if (mbits > 32)
1000  mbits = 32;
1001  a1 >>= (32-mbits);
1002  a2 >>= (32-mbits);
1003  r = TRISTATE(a1, a2);
1004  return r;
1005  }
1006  case AF_INET6: {
1007  if (mbits > 128)
1008  mbits = 128;
1009 
1010  const uint8_t *a1 = tor_addr_to_in6_addr8(addr1);
1011  const uint8_t *a2 = tor_addr_to_in6_addr8(addr2);
1012  const int bytes = mbits >> 3;
1013  const int leftover_bits = mbits & 7;
1014  if (bytes && (r = tor_memcmp(a1, a2, bytes))) {
1015  return r;
1016  } else if (leftover_bits) {
1017  uint8_t b1 = a1[bytes] >> (8-leftover_bits);
1018  uint8_t b2 = a2[bytes] >> (8-leftover_bits);
1019  return TRISTATE(b1, b2);
1020  } else {
1021  return 0;
1022  }
1023  }
1024  case AF_UNIX:
1025  /* HACKHACKHACKHACKHACK:
1026  * tor_addr_t doesn't contain a copy of sun_path, so it's not
1027  * possible to compare this at all.
1028  *
1029  * Since the only time we currently actually should be comparing
1030  * 2 AF_UNIX addresses is when dealing with ISO_CLIENTADDR (which
1031  * is disabled for AF_UNIX SocksPorts anyway), this just does
1032  * a pointer comparison.
1033  *
1034  * See: #20261.
1035  */
1036  if (addr1 < addr2)
1037  return -1;
1038  else if (addr1 == addr2)
1039  return 0;
1040  else
1041  return 1;
1042  /* LCOV_EXCL_START */
1043  default:
1045  return 0;
1046  /* LCOV_EXCL_STOP */
1047  }
1048  } else if (how == CMP_EXACT) {
1049  /* Unequal families and an exact comparison? Stop now! */
1050  return TRISTATE(family1, family2);
1051  }
1052 
1053  if (mbits == 0)
1054  return 0;
1055 
1056  if (family1 == AF_INET6 && tor_addr_is_v4(addr1))
1057  v_family1 = AF_INET;
1058  if (family2 == AF_INET6 && tor_addr_is_v4(addr2))
1059  v_family2 = AF_INET;
1060  if (v_family1 == v_family2) {
1061  /* One or both addresses are a mapped ipv4 address. */
1062  uint32_t a1, a2;
1063  if (family1 == AF_INET6) {
1064  a1 = tor_addr_to_mapped_ipv4h(addr1);
1065  if (mbits <= 96)
1066  return 0;
1067  mbits -= 96; /* We just decided that the first 96 bits of a1 "match". */
1068  } else {
1069  a1 = tor_addr_to_ipv4h(addr1);
1070  }
1071  if (family2 == AF_INET6) {
1072  a2 = tor_addr_to_mapped_ipv4h(addr2);
1073  } else {
1074  a2 = tor_addr_to_ipv4h(addr2);
1075  }
1076  if (mbits > 32) mbits = 32;
1077  a1 >>= (32-mbits);
1078  a2 >>= (32-mbits);
1079  return TRISTATE(a1, a2);
1080  } else {
1081  /* Unequal families, and semantic comparison, and no semantic family
1082  * matches. */
1083  return TRISTATE(family1, family2);
1084  }
1085 }
1086 
1088 static const uint32_t unspec_hash_input[] = { 0x4e4df09f, 0x92985342 };
1089 
1091 uint64_t
1093 {
1094  switch (tor_addr_family(addr)) {
1095  case AF_INET:
1096  return siphash24g(&addr->addr.in_addr.s_addr, 4);
1097  case AF_UNSPEC:
1098  return siphash24g(unspec_hash_input, sizeof(unspec_hash_input));
1099  case AF_INET6:
1100  return siphash24g(&addr->addr.in6_addr.s6_addr, 16);
1101  /* LCOV_EXCL_START */
1102  default:
1104  return 0;
1105  /* LCOV_EXCL_STOP */
1106  }
1107 }
1108 
1110 uint64_t
1111 tor_addr_keyed_hash(const struct sipkey *key, const tor_addr_t *addr)
1112 {
1113  /* This is duplicate code with tor_addr_hash, since this function needs to
1114  * be backportable all the way to 0.2.9. */
1115 
1116  switch (tor_addr_family(addr)) {
1117  case AF_INET:
1118  return siphash24(&addr->addr.in_addr.s_addr, 4, key);
1119  case AF_UNSPEC:
1120  return siphash24(unspec_hash_input, sizeof(unspec_hash_input), key);
1121  case AF_INET6:
1122  return siphash24(&addr->addr.in6_addr.s6_addr, 16, key);
1123  default:
1124  /* LCOV_EXCL_START */
1126  return 0;
1127  /* LCOV_EXCL_STOP */
1128  }
1129 }
1130 
1132 char *
1134 {
1135  char buf[TOR_ADDR_BUF_LEN];
1136  if (tor_addr_to_str(buf, addr, sizeof(buf), 0)) {
1137  return tor_strdup(buf);
1138  } else {
1139  return tor_strdup("<unknown address type>");
1140  }
1141 }
1142 
1152 const char *
1153 fmt_addr_impl(const tor_addr_t *addr, int decorate)
1154 {
1155  static char buf[TOR_ADDR_BUF_LEN];
1156  if (!addr) return "<null>";
1157  if (tor_addr_to_str(buf, addr, sizeof(buf), decorate))
1158  return buf;
1159  else
1160  return "???";
1161 }
1162 
1167 const char *
1168 fmt_addrport(const tor_addr_t *addr, uint16_t port)
1169 {
1170  /* Add space for a colon and up to 5 digits. */
1171  static char buf[TOR_ADDR_BUF_LEN + 6];
1172  tor_snprintf(buf, sizeof(buf), "%s:%u", fmt_and_decorate_addr(addr), port);
1173  return buf;
1174 }
1175 
1179 const char *
1180 fmt_addr32(uint32_t addr)
1181 {
1182  static char buf[INET_NTOA_BUF_LEN];
1183  struct in_addr in;
1184  in.s_addr = htonl(addr);
1185  tor_inet_ntoa(&in, buf, sizeof(buf));
1186  return buf;
1187 }
1188 
1195 int
1196 tor_addr_parse(tor_addr_t *addr, const char *src)
1197 {
1198  /* Holds substring of IPv6 address after removing square brackets */
1199  char *tmp = NULL;
1200  int result;
1201  struct in_addr in_tmp;
1202  struct in6_addr in6_tmp;
1203  int brackets_detected = 0;
1204 
1205  tor_assert(addr && src);
1206 
1207  size_t len = strlen(src);
1208 
1209  if (len && src[0] == '[' && src[len - 1] == ']') {
1210  brackets_detected = 1;
1211  src = tmp = tor_strndup(src+1, strlen(src)-2);
1212  }
1213 
1214  if (tor_inet_pton(AF_INET6, src, &in6_tmp) > 0) {
1215  result = AF_INET6;
1216  tor_addr_from_in6(addr, &in6_tmp);
1217  } else if (!brackets_detected &&
1218  tor_inet_pton(AF_INET, src, &in_tmp) > 0) {
1219  result = AF_INET;
1220  tor_addr_from_in(addr, &in_tmp);
1221  } else {
1222  result = -1;
1223  }
1224 
1225  tor_free(tmp);
1226  return result;
1227 }
1228 
1229 #ifdef HAVE_IFADDRS_TO_SMARTLIST
1230 /*
1231  * Convert a linked list consisting of <b>ifaddrs</b> structures
1232  * into smartlist of <b>tor_addr_t</b> structures.
1233  */
1234 STATIC smartlist_t *
1235 ifaddrs_to_smartlist(const struct ifaddrs *ifa, sa_family_t family)
1236 {
1237  smartlist_t *result = smartlist_new();
1238  const struct ifaddrs *i;
1239 
1240  for (i = ifa; i; i = i->ifa_next) {
1241  tor_addr_t tmp;
1242  if ((i->ifa_flags & (IFF_UP | IFF_RUNNING)) != (IFF_UP | IFF_RUNNING))
1243  continue;
1244  if (!i->ifa_addr)
1245  continue;
1246  if (i->ifa_addr->sa_family != AF_INET &&
1247  i->ifa_addr->sa_family != AF_INET6)
1248  continue;
1249  if (family != AF_UNSPEC && i->ifa_addr->sa_family != family)
1250  continue;
1251  if (tor_addr_from_sockaddr(&tmp, i->ifa_addr, NULL) < 0)
1252  continue;
1253  smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
1254  }
1255 
1256  return result;
1257 }
1258 
1263 STATIC smartlist_t *
1264 get_interface_addresses_ifaddrs(int severity, sa_family_t family)
1265 {
1266 
1267  /* Most free Unixy systems provide getifaddrs, which gives us a linked list
1268  * of struct ifaddrs. */
1269  struct ifaddrs *ifa = NULL;
1270  smartlist_t *result;
1271  if (getifaddrs(&ifa) < 0) {
1272  log_fn(severity, LD_NET, "Unable to call getifaddrs(): %s",
1273  strerror(errno));
1274  return NULL;
1275  }
1276 
1277  result = ifaddrs_to_smartlist(ifa, family);
1278 
1279  freeifaddrs(ifa);
1280 
1281  return result;
1282 }
1283 #endif /* defined(HAVE_IFADDRS_TO_SMARTLIST) */
1284 
1285 #ifdef HAVE_IP_ADAPTER_TO_SMARTLIST
1286 
1291 STATIC smartlist_t *
1292 ip_adapter_addresses_to_smartlist(const IP_ADAPTER_ADDRESSES *addresses)
1293 {
1294  smartlist_t *result = smartlist_new();
1295  const IP_ADAPTER_ADDRESSES *address;
1296 
1297  for (address = addresses; address; address = address->Next) {
1298  const IP_ADAPTER_UNICAST_ADDRESS *a;
1299  for (a = address->FirstUnicastAddress; a; a = a->Next) {
1300  /* Yes, it's a linked list inside a linked list */
1301  const struct sockaddr *sa = a->Address.lpSockaddr;
1302  tor_addr_t tmp;
1303  if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
1304  continue;
1305  if (tor_addr_from_sockaddr(&tmp, sa, NULL) < 0)
1306  continue;
1307  smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
1308  }
1309  }
1310 
1311  return result;
1312 }
1313 
1318 STATIC smartlist_t *
1319 get_interface_addresses_win32(int severity, sa_family_t family)
1320 {
1321  smartlist_t *result = NULL;
1322  ULONG size, res;
1323  IP_ADAPTER_ADDRESSES *addresses = NULL;
1324 
1325  (void) severity;
1326 
1327 #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
1328  GAA_FLAG_SKIP_MULTICAST | \
1329  GAA_FLAG_SKIP_DNS_SERVER)
1330 
1331  /* Guess how much space we need. */
1332  size = 15*1024;
1333  addresses = tor_malloc(size);
1334  /* Exists in windows XP and later. */
1335  res = GetAdaptersAddresses(family, FLAGS, NULL, addresses, &size);
1336  if (res == ERROR_BUFFER_OVERFLOW) {
1337  /* we didn't guess that we needed enough space; try again */
1338  tor_free(addresses);
1339  addresses = tor_malloc(size);
1340  res = GetAdaptersAddresses(AF_UNSPEC, FLAGS, NULL, addresses, &size);
1341  }
1342  if (res != NO_ERROR) {
1343  log_fn(severity, LD_NET, "GetAdaptersAddresses failed (result: %lu)", res);
1344  goto done;
1345  }
1346 
1347  result = ip_adapter_addresses_to_smartlist(addresses);
1348 
1349  done:
1350  tor_free(addresses);
1351  return result;
1352 }
1353 
1354 #endif /* defined(HAVE_IP_ADAPTER_TO_SMARTLIST) */
1355 
1356 #ifdef HAVE_IFCONF_TO_SMARTLIST
1357 
1358 /* Guess how much space we need. There shouldn't be any struct ifreqs
1359  * larger than this, even on OS X where the struct's size is dynamic. */
1360 #define IFREQ_SIZE 4096
1361 
1362 /* This is defined on Mac OS X */
1363 #ifndef _SIZEOF_ADDR_IFREQ
1364 #define _SIZEOF_ADDR_IFREQ sizeof
1365 #endif
1366 
1367 /* Free ifc->ifc_buf safely. */
1368 static void
1369 ifconf_free_ifc_buf(struct ifconf *ifc)
1370 {
1371  /* On macOS, tor_free() takes the address of ifc.ifc_buf, which leads to
1372  * undefined behaviour, because pointer-to-pointers are expected to be
1373  * aligned at 8-bytes, but the ifconf structure is packed. So we use
1374  * raw_free() instead. */
1375  raw_free(ifc->ifc_buf);
1376  ifc->ifc_buf = NULL;
1377 }
1378 
1382 STATIC smartlist_t *
1383 ifreq_to_smartlist(char *buf, size_t buflen)
1384 {
1385  smartlist_t *result = smartlist_new();
1386  char *end = buf + buflen;
1387 
1388  /* These acrobatics are due to alignment issues which trigger
1389  * undefined behaviour traps on OSX. */
1390  struct ifreq *r = tor_malloc(IFREQ_SIZE);
1391 
1392  while (buf < end) {
1393  /* Copy up to IFREQ_SIZE bytes into the struct ifreq, but don't overrun
1394  * buf. */
1395  memcpy(r, buf, end - buf < IFREQ_SIZE ? end - buf : IFREQ_SIZE);
1396 
1397  const struct sockaddr *sa = &r->ifr_addr;
1398  tor_addr_t tmp;
1399  int valid_sa_family = (sa->sa_family == AF_INET ||
1400  sa->sa_family == AF_INET6);
1401 
1402  int conversion_success = (tor_addr_from_sockaddr(&tmp, sa, NULL) == 0);
1403 
1404  if (valid_sa_family && conversion_success)
1405  smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
1406 
1407  buf += _SIZEOF_ADDR_IFREQ(*r);
1408  }
1409 
1410  tor_free(r);
1411  return result;
1412 }
1413 
1418 STATIC smartlist_t *
1419 get_interface_addresses_ioctl(int severity, sa_family_t family)
1420 {
1421  /* Some older unixy systems make us use ioctl(SIOCGIFCONF) */
1422  struct ifconf ifc;
1423  ifc.ifc_buf = NULL;
1424  int fd;
1425  smartlist_t *result = NULL;
1426 
1427  /* This interface, AFAICT, only supports AF_INET addresses,
1428  * except on AIX. For Solaris, we could use SIOCGLIFCONF. */
1429 
1430  /* Bail out if family is neither AF_INET nor AF_UNSPEC since
1431  * ioctl() technique supports non-IPv4 interface addresses on
1432  * a small number of niche systems only. If family is AF_UNSPEC,
1433  * fall back to getting AF_INET addresses only. */
1434  if (family == AF_UNSPEC)
1435  family = AF_INET;
1436  else if (family != AF_INET)
1437  return NULL;
1438 
1439  fd = socket(family, SOCK_DGRAM, 0);
1440  if (fd < 0) {
1441  tor_log(severity, LD_NET, "socket failed: %s", strerror(errno));
1442  goto done;
1443  }
1444 
1445  int mult = 1;
1446  do {
1447  mult *= 2;
1448  ifc.ifc_len = mult * IFREQ_SIZE;
1449  ifc.ifc_buf = tor_realloc(ifc.ifc_buf, ifc.ifc_len);
1450 
1451  tor_assert(ifc.ifc_buf);
1452 
1453  if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) {
1454  tor_log(severity, LD_NET, "ioctl failed: %s", strerror(errno));
1455  goto done;
1456  }
1457  /* Ensure we have least IFREQ_SIZE bytes unused at the end. Otherwise, we
1458  * don't know if we got everything during ioctl. */
1459  } while (mult * IFREQ_SIZE - ifc.ifc_len <= IFREQ_SIZE);
1460  result = ifreq_to_smartlist(ifc.ifc_buf, ifc.ifc_len);
1461 
1462  done:
1463  if (fd >= 0)
1464  close(fd);
1465  ifconf_free_ifc_buf(&ifc);
1466  return result;
1467 }
1468 #endif /* defined(HAVE_IFCONF_TO_SMARTLIST) */
1469 
1477 get_interface_addresses_raw,(int severity, sa_family_t family))
1478 {
1479  smartlist_t *result = NULL;
1480 #if defined(HAVE_IFADDRS_TO_SMARTLIST)
1481  if ((result = get_interface_addresses_ifaddrs(severity, family)))
1482  return result;
1483 #endif
1484 #if defined(HAVE_IP_ADAPTER_TO_SMARTLIST)
1485  if ((result = get_interface_addresses_win32(severity, family)))
1486  return result;
1487 #endif
1488 #if defined(HAVE_IFCONF_TO_SMARTLIST)
1489  if ((result = get_interface_addresses_ioctl(severity, family)))
1490  return result;
1491 #endif
1492  (void) severity;
1493  (void) result;
1494  return NULL;
1495 }
1496 
1498 int
1500 {
1501  sa_family_t family = tor_addr_family(a);
1502  if (family == AF_INET) {
1503  uint32_t ipv4h = tor_addr_to_ipv4h(a);
1504  if ((ipv4h >> 24) == 0xe0)
1505  return 1; /* Multicast */
1506  } else if (family == AF_INET6) {
1507  const uint8_t *a32 = tor_addr_to_in6_addr8(a);
1508  if (a32[0] == 0xff)
1509  return 1;
1510  }
1511  return 0;
1512 }
1513 
1520 get_interface_address6_via_udp_socket_hack,(int severity,
1521  sa_family_t family,
1522  tor_addr_t *addr))
1523 {
1524  struct sockaddr_storage target_addr;
1525  int sock=-1, r=-1;
1526  socklen_t addr_len;
1527 
1528  memset(addr, 0, sizeof(tor_addr_t));
1529  memset(&target_addr, 0, sizeof(target_addr));
1530 
1531  /* Don't worry: no packets are sent. We just need to use a real address
1532  * on the actual Internet. */
1533  if (family == AF_INET6) {
1534  struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&target_addr;
1535  /* Use the "discard" service port */
1536  sin6->sin6_port = htons(9);
1537  sock = tor_open_socket(PF_INET6,SOCK_DGRAM,IPPROTO_UDP);
1538  addr_len = (socklen_t)sizeof(struct sockaddr_in6);
1539  sin6->sin6_family = AF_INET6;
1540  S6_ADDR16(sin6->sin6_addr)[0] = htons(0x2002); /* 2002:: */
1541  } else if (family == AF_INET) {
1542  struct sockaddr_in *sin = (struct sockaddr_in*)&target_addr;
1543  /* Use the "discard" service port */
1544  sin->sin_port = htons(9);
1545  sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
1546  addr_len = (socklen_t)sizeof(struct sockaddr_in);
1547  sin->sin_family = AF_INET;
1548  sin->sin_addr.s_addr = htonl(0x12000001); /* 18.0.0.1 */
1549  } else {
1550  return -1;
1551  }
1552 
1553  if (sock < 0) {
1554  int e = tor_socket_errno(-1);
1555  log_fn(severity, LD_NET, "unable to create socket: %s",
1556  tor_socket_strerror(e));
1557  goto err;
1558  }
1559 
1560  if (tor_connect_socket(sock,(struct sockaddr *)&target_addr,
1561  addr_len) < 0) {
1562  int e = tor_socket_errno(sock);
1563  log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e));
1564  goto err;
1565  }
1566 
1567  if (tor_addr_from_getsockname(addr, sock) < 0) {
1568  int e = tor_socket_errno(sock);
1569  log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s",
1570  tor_socket_strerror(e));
1571  goto err;
1572  }
1573 
1574  if (tor_addr_is_loopback(addr) || tor_addr_is_multicast(addr)) {
1575  log_fn(severity, LD_NET, "Address that we determined via UDP socket"
1576  " magic is unsuitable for public comms.");
1577  } else {
1578  r=0;
1579  }
1580 
1581  err:
1582  if (sock >= 0)
1583  tor_close_socket(sock);
1584  if (r == -1)
1585  memset(addr, 0, sizeof(tor_addr_t));
1586  return r;
1587 }
1588 
1598 get_interface_address6,(int severity, sa_family_t family, tor_addr_t *addr))
1599 {
1600  smartlist_t *addrs;
1601  int rv = -1;
1602  tor_assert(addr);
1603 
1604  memset(addr, 0, sizeof(tor_addr_t));
1605 
1606  /* Get a list of public or internal IPs in arbitrary order */
1607  addrs = get_interface_address6_list(severity, family, 1);
1608 
1609  /* Find the first non-internal address, or the last internal address
1610  * Ideally, we want the default route, see #12377 for details */
1611  SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a) {
1612  tor_addr_copy(addr, a);
1613  rv = 0;
1614 
1615  /* If we found a non-internal address, declare success. Otherwise,
1616  * keep looking. */
1617  if (!tor_addr_is_internal(a, 0))
1618  break;
1619  } SMARTLIST_FOREACH_END(a);
1620 
1621  interface_address6_list_free(addrs);
1622  return rv;
1623 }
1624 
1627 void
1629 {
1630  if (addrs != NULL) {
1631  SMARTLIST_FOREACH(addrs, tor_addr_t *, a, tor_free(a));
1632  smartlist_free(addrs);
1633  }
1634 }
1635 
1646 get_interface_address6_list,(int severity,
1647  sa_family_t family,
1648  int include_internal))
1649 {
1650  smartlist_t *addrs;
1651  tor_addr_t addr;
1652 
1653  /* Try to do this the smart way if possible. */
1654  if ((addrs = get_interface_addresses_raw(severity, family))) {
1655  SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a)
1656  {
1657  if (tor_addr_is_loopback(a) ||
1658  tor_addr_is_multicast(a)) {
1660  tor_free(a);
1661  continue;
1662  }
1663 
1664  if (!include_internal && tor_addr_is_internal(a, 0)) {
1666  tor_free(a);
1667  continue;
1668  }
1669  } SMARTLIST_FOREACH_END(a);
1670  }
1671 
1672  if (addrs && smartlist_len(addrs) > 0) {
1673  return addrs;
1674  }
1675 
1676  /* if we removed all entries as unsuitable */
1677  if (addrs) {
1678  smartlist_free(addrs);
1679  }
1680 
1681  /* Okay, the smart way is out. */
1682  addrs = smartlist_new();
1683 
1684  if (family == AF_INET || family == AF_UNSPEC) {
1685  if (get_interface_address6_via_udp_socket_hack(severity,AF_INET,
1686  &addr) == 0) {
1687  if (include_internal || !tor_addr_is_internal(&addr, 0)) {
1688  smartlist_add(addrs, tor_memdup(&addr, sizeof(addr)));
1689  }
1690  }
1691  }
1692 
1693  if (family == AF_INET6 || family == AF_UNSPEC) {
1694  if (get_interface_address6_via_udp_socket_hack(severity,AF_INET6,
1695  &addr) == 0) {
1696  if (include_internal || !tor_addr_is_internal(&addr, 0)) {
1697  smartlist_add(addrs, tor_memdup(&addr, sizeof(addr)));
1698  }
1699  }
1700  }
1701 
1702  return addrs;
1703 }
1704 
1705 /* ======
1706  * IPv4 helpers
1707  * XXXX IPv6 deprecate some of these.
1708  */
1709 
1722 int
1723 tor_addr_port_parse(int severity, const char *addrport,
1724  tor_addr_t *address_out, uint16_t *port_out,
1725  int default_port)
1726 {
1727  int retval = -1;
1728  int r;
1729  char *addr_tmp = NULL;
1730 
1731  tor_assert(addrport);
1732  tor_assert(address_out);
1733  tor_assert(port_out);
1734 
1735  r = tor_addr_port_split(severity, addrport, &addr_tmp, port_out);
1736  if (r < 0)
1737  goto done;
1738 
1739  if (!*port_out) {
1740  if (default_port >= 0)
1741  *port_out = default_port;
1742  else
1743  goto done;
1744  }
1745 
1746  /* make sure that address_out is an IP address */
1747  if (tor_addr_parse(address_out, addr_tmp) < 0)
1748  goto done;
1749 
1750  retval = 0;
1751 
1752  done:
1753  tor_free(addr_tmp);
1754  return retval;
1755 }
1756 
1761 int
1762 tor_addr_port_split(int severity, const char *addrport,
1763  char **address_out, uint16_t *port_out)
1764 {
1765  tor_addr_t a_tmp;
1766  tor_assert(addrport);
1767  tor_assert(address_out);
1768  tor_assert(port_out);
1769  /* We need to check for IPv6 manually because the logic below doesn't
1770  * do a good job on IPv6 addresses that lack a port. */
1771  if (tor_addr_parse(&a_tmp, addrport) == AF_INET6) {
1772  *port_out = 0;
1773  *address_out = tor_strdup(addrport);
1774  return 0;
1775  }
1776 
1777  const char *colon;
1778  char *address_ = NULL;
1779  int port_;
1780  int ok = 1;
1781 
1782  colon = strrchr(addrport, ':');
1783  if (colon) {
1784  address_ = tor_strndup(addrport, colon-addrport);
1785  port_ = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
1786  if (!port_) {
1787  log_fn(severity, LD_GENERAL, "Port %s out of range", escaped(colon+1));
1788  ok = 0;
1789  }
1790  if (!port_out) {
1791  char *esc_addrport = esc_for_log(addrport);
1792  log_fn(severity, LD_GENERAL,
1793  "Port %s given on %s when not required",
1794  escaped(colon+1), esc_addrport);
1795  tor_free(esc_addrport);
1796  ok = 0;
1797  }
1798  } else {
1799  address_ = tor_strdup(addrport);
1800  port_ = 0;
1801  }
1802 
1803  if (ok) {
1804  *address_out = address_;
1805  } else {
1806  *address_out = NULL;
1807  tor_free(address_);
1808  }
1809 
1810  if (port_out)
1811  *port_out = ok ? ((uint16_t) port_) : 0;
1812 
1813  return ok ? 0 : -1;
1814 }
1815 
1818 int
1819 addr_mask_get_bits(uint32_t mask)
1820 {
1821  int i;
1822  if (mask == 0)
1823  return 0;
1824  if (mask == 0xFFFFFFFFu)
1825  return 32;
1826  for (i=1; i<=32; ++i) {
1827  if (mask == (uint32_t) ~((1u<<(32-i))-1)) {
1828  return i;
1829  }
1830  }
1831  return -1;
1832 }
1833 
1837 int
1838 parse_port_range(const char *port, uint16_t *port_min_out,
1839  uint16_t *port_max_out)
1840 {
1841  int port_min, port_max, ok;
1842  tor_assert(port_min_out);
1843  tor_assert(port_max_out);
1844 
1845  if (!port || *port == '\0' || strcmp(port, "*") == 0) {
1846  port_min = 1;
1847  port_max = 65535;
1848  } else {
1849  char *endptr = NULL;
1850  port_min = (int)tor_parse_long(port, 10, 0, 65535, &ok, &endptr);
1851  if (!ok) {
1852  log_warn(LD_GENERAL,
1853  "Malformed port %s on address range; rejecting.",
1854  escaped(port));
1855  return -1;
1856  } else if (endptr && *endptr == '-') {
1857  port = endptr+1;
1858  endptr = NULL;
1859  port_max = (int)tor_parse_long(port, 10, 1, 65535, &ok, &endptr);
1860  if (!ok) {
1861  log_warn(LD_GENERAL,
1862  "Malformed port %s on address range; rejecting.",
1863  escaped(port));
1864  return -1;
1865  }
1866  } else {
1867  port_max = port_min;
1868  }
1869  if (port_min > port_max) {
1870  log_warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
1871  return -1;
1872  }
1873  }
1874 
1875  if (port_min < 1)
1876  port_min = 1;
1877  if (port_max > 65535)
1878  port_max = 65535;
1879 
1880  *port_min_out = (uint16_t) port_min;
1881  *port_max_out = (uint16_t) port_max;
1882 
1883  return 0;
1884 }
1885 
1889 char *
1890 tor_dup_ip(uint32_t addr)
1891 {
1892  char buf[TOR_ADDR_BUF_LEN];
1893  struct in_addr in;
1894 
1895  in.s_addr = htonl(addr);
1896  tor_inet_ntop(AF_INET, &in, buf, sizeof(buf));
1897  return tor_strdup(buf);
1898 }
1899 
1910 get_interface_address,(int severity, uint32_t *addr))
1911 {
1912  tor_addr_t local_addr;
1913  int r;
1914 
1915  memset(addr, 0, sizeof(uint32_t));
1916 
1917  r = get_interface_address6(severity, AF_INET, &local_addr);
1918  if (r>=0)
1919  *addr = tor_addr_to_ipv4h(&local_addr);
1920  return r;
1921 }
1922 
1926 int
1928 {
1929  return !strcasecmp(name, "localhost") ||
1930  !strcasecmp(name, "local") ||
1931  !strcasecmpend(name, ".local");
1932 }
1933 
1937 tor_addr_port_new(const tor_addr_t *addr, uint16_t port)
1938 {
1939  tor_addr_port_t *ap = tor_malloc_zero(sizeof(tor_addr_port_t));
1940  if (addr)
1941  tor_addr_copy(&ap->addr, addr);
1942  ap->port = port;
1943  return ap;
1944 }
1945 
1947 int
1949  const tor_addr_port_t *b)
1950 {
1951  return tor_addr_eq(&a->addr, &b->addr) && a->port == b->port;
1952 }
1953 
1957 int
1958 string_is_valid_ipv4_address(const char *string)
1959 {
1960  struct in_addr addr;
1961 
1962  return (tor_inet_pton(AF_INET,string,&addr) == 1);
1963 }
1964 
1968 int
1969 string_is_valid_ipv6_address(const char *string)
1970 {
1971  struct in6_addr addr;
1972 
1973  return (tor_inet_pton(AF_INET6,string,&addr) == 1);
1974 }
1975 
1979 int
1980 string_is_valid_dest(const char *string)
1981 {
1982  char *tmp = NULL;
1983  int retval;
1984  size_t len;
1985 
1986  if (string == NULL)
1987  return 0;
1988 
1989  len = strlen(string);
1990 
1991  if (len == 0)
1992  return 0;
1993 
1994  if (string[0] == '[' && string[len - 1] == ']')
1995  string = tmp = tor_strndup(string + 1, len - 2);
1996 
1997  retval = string_is_valid_ipv4_address(string) ||
1998  string_is_valid_ipv6_address(string) ||
2000 
2001  tor_free(tmp);
2002 
2003  return retval;
2004 }
2005 
2012 int
2014 {
2015  int result = 1;
2016  int has_trailing_dot;
2017  char *last_label;
2018  smartlist_t *components;
2019 
2020  if (!string || strlen(string) == 0)
2021  return 0;
2022 
2023  if (string_is_valid_ipv4_address(string))
2024  return 0;
2025 
2026  components = smartlist_new();
2027 
2028  smartlist_split_string(components,string,".",0,0);
2029 
2030  if (BUG(smartlist_len(components) == 0)) {
2031  // LCOV_EXCL_START should be impossible given the earlier checks.
2032  smartlist_free(components);
2033  return 0;
2034  // LCOV_EXCL_STOP
2035  }
2036 
2037  /* Allow a single terminating '.' used rarely to indicate domains
2038  * are FQDNs rather than relative. */
2039  last_label = (char *)smartlist_get(components,
2040  smartlist_len(components) - 1);
2041  has_trailing_dot = (last_label[0] == '\0');
2042  if (has_trailing_dot) {
2043  smartlist_pop_last(components);
2044  tor_free(last_label);
2045  last_label = NULL;
2046  }
2047 
2048  SMARTLIST_FOREACH_BEGIN(components, char *, c) {
2049  if ((c[0] == '-') || (*c == '_')) {
2050  result = 0;
2051  break;
2052  }
2053 
2054  do {
2055  result = (TOR_ISALNUM(*c) || (*c == '-') || (*c == '_'));
2056  c++;
2057  } while (result && *c);
2058 
2059  if (result == 0) {
2060  break;
2061  }
2062  } SMARTLIST_FOREACH_END(c);
2063 
2064  SMARTLIST_FOREACH_BEGIN(components, char *, c) {
2065  tor_free(c);
2066  } SMARTLIST_FOREACH_END(c);
2067 
2068  smartlist_free(components);
2069 
2070  return result;
2071 }
void tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
Definition: address.c:873
int addr_mask_get_bits(uint32_t mask)
Definition: address.c:1819
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:1628
#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:469
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:1958
#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:379
#define LD_GENERAL
Definition: log.h:59
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:953
int tor_addr_port_eq(const tor_addr_port_t *a, const tor_addr_port_t *b)
Definition: address.c:1948
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:1927
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:632
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:2013
#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:1088
#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:1838
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:748
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:1168
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:1723
const char * fmt_addr_impl(const tor_addr_t *addr, int decorate)
Definition: address.c:1153
void tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
Definition: address.c:884
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:542
int tor_addr_parse(tor_addr_t *addr, const char *src)
Definition: address.c:1196
uint64_t tor_addr_hash(const tor_addr_t *addr)
Definition: address.c:1092
const char * fmt_addr32(uint32_t addr)
Definition: address.c:1180
int tor_addr_is_null(const tor_addr_t *addr)
Definition: address.c:769
Header for process.c.
int tor_addr_is_loopback(const tor_addr_t *addr)
Definition: address.c:794
uint64_t tor_addr_keyed_hash(const struct sipkey *key, const tor_addr_t *addr)
Definition: address.c:1111
int tor_addr_is_multicast(const tor_addr_t *a)
Definition: address.c:1499
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:1133
void tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
Definition: address.c:895
#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:1937
const char * escaped(const char *s)
Definition: escape.c:126
int string_is_valid_ipv6_address(const char *string)
Definition: address.c:1969
Locale-independent character-type inspection (header)
#define log_fn(severity, domain, args,...)
Definition: log.h:266
int string_is_valid_dest(const char *string)
Definition: address.c:1980
#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:1476
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:974
char * esc_for_log(const char *s)
Definition: escape.c:30
#define LD_NET
Definition: log.h:63
#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:903
void tor_addr_copy_tight(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:917
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:83
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:1762
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:1890