tor  0.4.0.1-alpha
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 
245 int
246 tor_addr_is_internal_(const tor_addr_t *addr, int for_listening,
247  const char *filename, int lineno)
248 {
249  uint32_t iph4 = 0;
250  uint32_t iph6[4];
251 
252  tor_assert(addr);
253  sa_family_t v_family = tor_addr_family(addr);
254 
255  if (v_family == AF_INET) {
256  iph4 = tor_addr_to_ipv4h(addr);
257  } else if (v_family == AF_INET6) {
258  if (tor_addr_is_v4(addr)) { /* v4-mapped */
259  uint32_t *addr32 = NULL;
260  v_family = AF_INET;
261  // Work around an incorrect NULL pointer dereference warning in
262  // "clang --analyze" due to limited analysis depth
263  addr32 = tor_addr_to_in6_addr32(addr);
264  // To improve performance, wrap this assertion in:
265  // #if !defined(__clang_analyzer__) || PARANOIA
266  tor_assert(addr32);
267  iph4 = ntohl(addr32[3]);
268  }
269  }
270 
271  if (v_family == AF_INET6) {
272  const uint32_t *a32 = tor_addr_to_in6_addr32(addr);
273  iph6[0] = ntohl(a32[0]);
274  iph6[1] = ntohl(a32[1]);
275  iph6[2] = ntohl(a32[2]);
276  iph6[3] = ntohl(a32[3]);
277  if (for_listening && !iph6[0] && !iph6[1] && !iph6[2] && !iph6[3]) /* :: */
278  return 0;
279 
280  if (((iph6[0] & 0xfe000000) == 0xfc000000) || /* fc00/7 - RFC4193 */
281  ((iph6[0] & 0xffc00000) == 0xfe800000) || /* fe80/10 - RFC4291 */
282  ((iph6[0] & 0xffc00000) == 0xfec00000)) /* fec0/10 D- RFC3879 */
283  return 1;
284 
285  if (!iph6[0] && !iph6[1] && !iph6[2] &&
286  ((iph6[3] & 0xfffffffe) == 0x00000000)) /* ::/127 */
287  return 1;
288 
289  return 0;
290  } else if (v_family == AF_INET) {
291  if (for_listening && !iph4) /* special case for binding to 0.0.0.0 */
292  return 0;
293  if (((iph4 & 0xff000000) == 0x0a000000) || /* 10/8 */
294  ((iph4 & 0xff000000) == 0x00000000) || /* 0/8 */
295  ((iph4 & 0xff000000) == 0x7f000000) || /* 127/8 */
296  ((iph4 & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
297  ((iph4 & 0xfff00000) == 0xac100000) || /* 172.16/12 */
298  ((iph4 & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
299  return 1;
300  return 0;
301  }
302 
303  /* unknown address family... assume it's not safe for external use */
304  /* rather than tor_assert(0) */
305  log_warn(LD_BUG, "tor_addr_is_internal() called from %s:%d with a "
306  "non-IP address of type %d", filename, lineno, (int)v_family);
308  return 1;
309 }
310 
316 const char *
317 tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
318 {
319  const char *ptr;
320  tor_assert(addr && dest);
321 
322  switch (tor_addr_family(addr)) {
323  case AF_INET:
324  /* Shortest addr x.x.x.x + \0 */
325  if (len < 8)
326  return NULL;
327  ptr = tor_inet_ntop(AF_INET, &addr->addr.in_addr, dest, len);
328  break;
329  case AF_INET6:
330  /* Shortest addr [ :: ] + \0 */
331  if (len < (3 + (decorate ? 2 : 0)))
332  return NULL;
333 
334  if (decorate)
335  ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest+1, len-2);
336  else
337  ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest, len);
338 
339  if (ptr && decorate) {
340  *dest = '[';
341  memcpy(dest+strlen(dest), "]", 2);
342  tor_assert(ptr == dest+1);
343  ptr = dest;
344  }
345  break;
346  case AF_UNIX:
347  tor_snprintf(dest, len, "AF_UNIX");
348  ptr = dest;
349  break;
350  default:
351  return NULL;
352  }
353  return ptr;
354 }
355 
367 int
368 tor_addr_parse_PTR_name(tor_addr_t *result, const char *address,
369  int family, int accept_regular)
370 {
371  if (!strcasecmpend(address, ".in-addr.arpa")) {
372  /* We have an in-addr.arpa address. */
373  char buf[INET_NTOA_BUF_LEN];
374  size_t len;
375  struct in_addr inaddr;
376  if (family == AF_INET6)
377  return -1;
378 
379  len = strlen(address) - strlen(".in-addr.arpa");
380  if (len >= INET_NTOA_BUF_LEN)
381  return -1; /* Too long. */
382 
383  memcpy(buf, address, len);
384  buf[len] = '\0';
385  if (tor_inet_aton(buf, &inaddr) == 0)
386  return -1; /* malformed. */
387 
388  /* reverse the bytes */
389  inaddr.s_addr = (uint32_t)
390  (((inaddr.s_addr & 0x000000ff) << 24)
391  |((inaddr.s_addr & 0x0000ff00) << 8)
392  |((inaddr.s_addr & 0x00ff0000) >> 8)
393  |((inaddr.s_addr & 0xff000000) >> 24));
394 
395  if (result) {
396  tor_addr_from_in(result, &inaddr);
397  }
398  return 1;
399  }
400 
401  if (!strcasecmpend(address, ".ip6.arpa")) {
402  const char *cp;
403  int n0, n1;
404  struct in6_addr in6;
405 
406  if (family == AF_INET)
407  return -1;
408 
409  cp = address;
410  for (int i = 0; i < 16; ++i) {
411  n0 = hex_decode_digit(*cp++); /* The low-order nybble appears first. */
412  if (*cp++ != '.') return -1; /* Then a dot. */
413  n1 = hex_decode_digit(*cp++); /* The high-order nybble appears first. */
414  if (*cp++ != '.') return -1; /* Then another dot. */
415  if (n0<0 || n1 < 0) /* Both nybbles must be hex. */
416  return -1;
417 
418  /* We don't check the length of the string in here. But that's okay,
419  * since we already know that the string ends with ".ip6.arpa", and
420  * there is no way to frameshift .ip6.arpa so it fits into the pattern
421  * of hexdigit, period, hexdigit, period that we enforce above.
422  */
423 
424  /* Assign from low-byte to high-byte. */
425  in6.s6_addr[15-i] = n0 | (n1 << 4);
426  }
427  if (strcasecmp(cp, "ip6.arpa"))
428  return -1;
429 
430  if (result) {
431  tor_addr_from_in6(result, &in6);
432  }
433  return 1;
434  }
435 
436  if (accept_regular) {
437  tor_addr_t tmp;
438  int r = tor_addr_parse(&tmp, address);
439  if (r < 0)
440  return 0;
441  if (r != family && family != AF_UNSPEC)
442  return -1;
443 
444  if (result)
445  memcpy(result, &tmp, sizeof(tor_addr_t));
446 
447  return 1;
448  }
449 
450  return 0;
451 }
452 
457 int
458 tor_addr_to_PTR_name(char *out, size_t outlen,
459  const tor_addr_t *addr)
460 {
461  tor_assert(out);
462  tor_assert(addr);
463 
464  if (addr->family == AF_INET) {
465  uint32_t a = tor_addr_to_ipv4h(addr);
466 
467  return tor_snprintf(out, outlen, "%d.%d.%d.%d.in-addr.arpa",
468  (int)(uint8_t)((a )&0xff),
469  (int)(uint8_t)((a>>8 )&0xff),
470  (int)(uint8_t)((a>>16)&0xff),
471  (int)(uint8_t)((a>>24)&0xff));
472  } else if (addr->family == AF_INET6) {
473  int i;
474  char *cp = out;
475  const uint8_t *bytes = tor_addr_to_in6_addr8(addr);
476  if (outlen < REVERSE_LOOKUP_NAME_BUF_LEN)
477  return -1;
478  for (i = 15; i >= 0; --i) {
479  uint8_t byte = bytes[i];
480  *cp++ = "0123456789abcdef"[byte & 0x0f];
481  *cp++ = '.';
482  *cp++ = "0123456789abcdef"[byte >> 4];
483  *cp++ = '.';
484  }
485  memcpy(cp, "ip6.arpa", 9); /* 8 characters plus NUL */
486  return 32 * 2 + 8;
487  }
488  return -1;
489 }
490 
530 int
532  unsigned flags,
533  tor_addr_t *addr_out,
534  maskbits_t *maskbits_out,
535  uint16_t *port_min_out, uint16_t *port_max_out)
536 {
537  char *base = NULL, *address, *mask = NULL, *port = NULL, *rbracket = NULL;
538  char *endptr;
539  int any_flag=0, v4map=0;
540  sa_family_t family;
541  struct in6_addr in6_tmp;
542  struct in_addr in_tmp = { .s_addr = 0 };
543 
544  tor_assert(s);
545  tor_assert(addr_out);
546  /* We can either only want an IPv4 address or only want an IPv6 address,
547  * but we can't only want IPv4 & IPv6 at the same time. */
548  tor_assert(!((flags & TAPMP_STAR_IPV4_ONLY)
549  && (flags & TAPMP_STAR_IPV6_ONLY)));
550 
553 #define MAX_ADDRESS_LENGTH (TOR_ADDR_BUF_LEN+2+(1+INET_NTOA_BUF_LEN)+12+1)
554 
555  if (strlen(s) > MAX_ADDRESS_LENGTH) {
556  log_warn(LD_GENERAL, "Impossibly long IP %s; rejecting", escaped(s));
557  goto err;
558  }
559  base = tor_strdup(s);
560 
561  /* Break 'base' into separate strings. */
562  address = base;
563  if (*address == '[') { /* Probably IPv6 */
564  address++;
565  rbracket = strchr(address, ']');
566  if (!rbracket) {
567  log_warn(LD_GENERAL,
568  "No closing IPv6 bracket in address pattern; rejecting.");
569  goto err;
570  }
571  }
572  mask = strchr((rbracket?rbracket:address),'/');
573  port = strchr((mask?mask:(rbracket?rbracket:address)), ':');
574  if (port)
575  *port++ = '\0';
576  if (mask)
577  *mask++ = '\0';
578  if (rbracket)
579  *rbracket = '\0';
580  if (port && mask)
581  tor_assert(port > mask);
582  if (mask && rbracket)
583  tor_assert(mask > rbracket);
584 
585  /* Now "address" is the a.b.c.d|'*'|abcd::1 part...
586  * "mask" is the Mask|Maskbits part...
587  * and "port" is the *|port|min-max part.
588  */
589 
590  /* Process the address portion */
591  memset(addr_out, 0, sizeof(tor_addr_t));
592 
593  if (!strcmp(address, "*")) {
594  if (flags & TAPMP_EXTENDED_STAR) {
595  if (flags & TAPMP_STAR_IPV4_ONLY) {
596  family = AF_INET;
597  tor_addr_from_ipv4h(addr_out, 0);
598  } else if (flags & TAPMP_STAR_IPV6_ONLY) {
599  static char nil_bytes[16] = { [0]=0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };
600  family = AF_INET6;
601  tor_addr_from_ipv6_bytes(addr_out, nil_bytes);
602  } else {
603  family = AF_UNSPEC;
604  tor_addr_make_unspec(addr_out);
605  log_info(LD_GENERAL,
606  "'%s' expands into rules which apply to all IPv4 and IPv6 "
607  "addresses. (Use accept/reject *4:* for IPv4 or "
608  "accept[6]/reject[6] *6:* for IPv6.)", s);
609  }
610  } else {
611  family = AF_INET;
612  tor_addr_from_ipv4h(addr_out, 0);
613  }
614  any_flag = 1;
615  } else if (!strcmp(address, "*4") && (flags & TAPMP_EXTENDED_STAR)) {
616  family = AF_INET;
617  tor_addr_from_ipv4h(addr_out, 0);
618  any_flag = 1;
619  } else if (!strcmp(address, "*6") && (flags & TAPMP_EXTENDED_STAR)) {
620  static char nil_bytes[16] = { [0]=0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };
621  family = AF_INET6;
622  tor_addr_from_ipv6_bytes(addr_out, nil_bytes);
623  any_flag = 1;
624  } else if (tor_inet_pton(AF_INET6, address, &in6_tmp) > 0) {
625  family = AF_INET6;
626  tor_addr_from_in6(addr_out, &in6_tmp);
627  } else if (tor_inet_pton(AF_INET, address, &in_tmp) > 0) {
628  family = AF_INET;
629  tor_addr_from_in(addr_out, &in_tmp);
630  } else {
631  log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
632  escaped(address));
633  goto err;
634  }
635 
636  v4map = tor_addr_is_v4(addr_out);
637 
638  /* Parse mask */
639  if (maskbits_out) {
640  int bits = 0;
641  struct in_addr v4mask;
642 
643  if (mask) { /* the caller (tried to) specify a mask */
644  bits = (int) strtol(mask, &endptr, 10);
645  if (!*endptr) { /* strtol converted everything, so it was an integer */
646  if ((bits<0 || bits>128) ||
647  (family == AF_INET && bits > 32)) {
648  log_warn(LD_GENERAL,
649  "Bad number of mask bits (%d) on address range; rejecting.",
650  bits);
651  goto err;
652  }
653  } else { /* mask might still be an address-style mask */
654  if (tor_inet_pton(AF_INET, mask, &v4mask) > 0) {
655  bits = addr_mask_get_bits(ntohl(v4mask.s_addr));
656  if (bits < 0) {
657  log_warn(LD_GENERAL,
658  "IPv4-style mask %s is not a prefix address; rejecting.",
659  escaped(mask));
660  goto err;
661  }
662  } else { /* Not IPv4; we don't do address-style IPv6 masks. */
663  log_warn(LD_GENERAL,
664  "Malformed mask on address range %s; rejecting.",
665  escaped(s));
666  goto err;
667  }
668  }
669  if (family == AF_INET6 && v4map) {
670  if (bits > 32 && bits < 96) { /* Crazy */
671  log_warn(LD_GENERAL,
672  "Bad mask bits %d for V4-mapped V6 address; rejecting.",
673  bits);
674  goto err;
675  }
676  /* XXXX_IP6 is this really what we want? */
677  bits = 96 + bits%32; /* map v4-mapped masks onto 96-128 bits */
678  }
679  if (any_flag) {
680  log_warn(LD_GENERAL,
681  "Found bit prefix with wildcard address; rejecting");
682  goto err;
683  }
684  } else { /* pick an appropriate mask, as none was given */
685  if (any_flag)
686  bits = 0; /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */
687  else if (tor_addr_family(addr_out) == AF_INET)
688  bits = 32;
689  else if (tor_addr_family(addr_out) == AF_INET6)
690  bits = 128;
691  }
692  *maskbits_out = (maskbits_t) bits;
693  } else {
694  if (mask) {
695  log_warn(LD_GENERAL,
696  "Unexpected mask in address %s; rejecting", escaped(s));
697  goto err;
698  }
699  }
700 
701  /* Parse port(s) */
702  if (port_min_out) {
703  uint16_t port2;
704  if (!port_max_out) /* caller specified one port; fake the second one */
705  port_max_out = &port2;
706 
707  if (parse_port_range(port, port_min_out, port_max_out) < 0) {
708  goto err;
709  } else if ((*port_min_out != *port_max_out) && port_max_out == &port2) {
710  log_warn(LD_GENERAL,
711  "Wanted one port from address range, but there are two.");
712 
713  port_max_out = NULL; /* caller specified one port, so set this back */
714  goto err;
715  }
716  } else {
717  if (port) {
718  log_warn(LD_GENERAL,
719  "Unexpected ports in address %s; rejecting", escaped(s));
720  goto err;
721  }
722  }
723 
724  tor_free(base);
725  return tor_addr_family(addr_out);
726  err:
727  tor_free(base);
728  return -1;
729 }
730 
736 int
738 {
739  tor_assert(addr);
740 
741  if (tor_addr_family(addr) == AF_INET)
742  return 1;
743 
744  if (tor_addr_family(addr) == AF_INET6) {
745  /* First two don't need to be ordered */
746  uint32_t *a32 = tor_addr_to_in6_addr32(addr);
747  if (a32[0] == 0 && a32[1] == 0 && ntohl(a32[2]) == 0x0000ffffu)
748  return 1;
749  }
750 
751  return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */
752 }
753 
757 int
759 {
760  tor_assert(addr);
761 
762  switch (tor_addr_family(addr)) {
763  case AF_INET6: {
764  uint32_t *a32 = tor_addr_to_in6_addr32(addr);
765  return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 0);
766  }
767  case AF_INET:
768  return (tor_addr_to_ipv4n(addr) == 0);
769  case AF_UNIX:
770  return 1;
771  case AF_UNSPEC:
772  return 1;
773  default:
774  log_warn(LD_BUG, "Called with unknown address family %d",
775  (int)tor_addr_family(addr));
776  return 0;
777  }
778  //return 1;
779 }
780 
782 int
784 {
785  tor_assert(addr);
786  switch (tor_addr_family(addr)) {
787  case AF_INET6: {
788  /* ::1 */
789  uint32_t *a32 = tor_addr_to_in6_addr32(addr);
790  return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) &&
791  (ntohl(a32[3]) == 1);
792  }
793  case AF_INET:
794  /* 127.0.0.1 */
795  return (tor_addr_to_ipv4h(addr) & 0xff000000) == 0x7f000000;
796  case AF_UNSPEC:
797  return 0;
798  /* LCOV_EXCL_START */
799  default:
801  return 0;
802  /* LCOV_EXCL_STOP */
803  }
804 }
805 
806 /* Is addr valid?
807  * Checks that addr is non-NULL and not tor_addr_is_null().
808  * If for_listening is true, IPv4 addr 0.0.0.0 is allowed.
809  * It means "bind to all addresses on the local machine". */
810 int
811 tor_addr_is_valid(const tor_addr_t *addr, int for_listening)
812 {
813  /* NULL addresses are invalid regardless of for_listening */
814  if (addr == NULL) {
815  return 0;
816  }
817 
818  /* Only allow IPv4 0.0.0.0 for_listening. */
819  if (for_listening && addr->family == AF_INET
820  && tor_addr_to_ipv4h(addr) == 0) {
821  return 1;
822  }
823 
824  /* Otherwise, the address is valid if it's not tor_addr_is_null() */
825  return !tor_addr_is_null(addr);
826 }
827 
828 /* Is the network-order IPv4 address v4n_addr valid?
829  * Checks that addr is not zero.
830  * Except if for_listening is true, where IPv4 addr 0.0.0.0 is allowed. */
831 int
832 tor_addr_is_valid_ipv4n(uint32_t v4n_addr, int for_listening)
833 {
834  /* Any IPv4 address is valid with for_listening. */
835  if (for_listening) {
836  return 1;
837  }
838 
839  /* Otherwise, zero addresses are invalid. */
840  return v4n_addr != 0;
841 }
842 
843 /* Is port valid?
844  * Checks that port is not 0.
845  * Except if for_listening is true, where port 0 is allowed.
846  * It means "OS chooses a port". */
847 int
848 tor_port_is_valid(uint16_t port, int for_listening)
849 {
850  /* Any port value is valid with for_listening. */
851  if (for_listening) {
852  return 1;
853  }
854 
855  /* Otherwise, zero ports are invalid. */
856  return port != 0;
857 }
858 
861 void
862 tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
863 {
864  tor_assert(dest);
865  memset(dest, 0, sizeof(tor_addr_t));
866  dest->family = AF_INET;
867  dest->addr.in_addr.s_addr = v4addr;
868 }
869 
872 void
873 tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
874 {
875  tor_assert(dest);
876  tor_assert(ipv6_bytes);
877  memset(dest, 0, sizeof(tor_addr_t));
878  dest->family = AF_INET6;
879  memcpy(dest->addr.in6_addr.s6_addr, ipv6_bytes, 16);
880 }
881 
883 void
884 tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
885 {
886  tor_addr_from_ipv6_bytes(dest, (const char*)in6->s6_addr);
887 }
888 
891 void
893 {
894  if (src == dest)
895  return;
896  tor_assert(src);
897  tor_assert(dest);
898  memcpy(dest, src, sizeof(tor_addr_t));
899 }
900 
905 void
907 {
908  tor_assert(src != dest);
909  tor_assert(src);
910  tor_assert(dest);
911  memset(dest, 0, sizeof(tor_addr_t));
912  dest->family = src->family;
913  switch (tor_addr_family(src))
914  {
915  case AF_INET:
916  dest->addr.in_addr.s_addr = src->addr.in_addr.s_addr;
917  break;
918  case AF_INET6:
919  memcpy(dest->addr.in6_addr.s6_addr, src->addr.in6_addr.s6_addr, 16);
920  case AF_UNSPEC:
921  break;
922  // LCOV_EXCL_START
923  default:
925  // LCOV_EXCL_STOP
926  }
927 }
928 
941 int
942 tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2,
944 {
945  return tor_addr_compare_masked(addr1, addr2, 128, how);
946 }
947 
962 int
963 tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2,
965 {
968 #define TRISTATE(a,b) (((a)<(b))?-1: (((a)==(b))?0:1))
969  sa_family_t family1, family2, v_family1, v_family2;
970 
971  tor_assert(addr1 && addr2);
972 
973  v_family1 = family1 = tor_addr_family(addr1);
974  v_family2 = family2 = tor_addr_family(addr2);
975 
976  if (family1==family2) {
977  /* When the families are the same, there's only one way to do the
978  * comparison: exactly. */
979  int r;
980  switch (family1) {
981  case AF_UNSPEC:
982  return 0; /* All unspecified addresses are equal */
983  case AF_INET: {
984  uint32_t a1 = tor_addr_to_ipv4h(addr1);
985  uint32_t a2 = tor_addr_to_ipv4h(addr2);
986  if (mbits <= 0)
987  return 0;
988  if (mbits > 32)
989  mbits = 32;
990  a1 >>= (32-mbits);
991  a2 >>= (32-mbits);
992  r = TRISTATE(a1, a2);
993  return r;
994  }
995  case AF_INET6: {
996  if (mbits > 128)
997  mbits = 128;
998 
999  const uint8_t *a1 = tor_addr_to_in6_addr8(addr1);
1000  const uint8_t *a2 = tor_addr_to_in6_addr8(addr2);
1001  const int bytes = mbits >> 3;
1002  const int leftover_bits = mbits & 7;
1003  if (bytes && (r = tor_memcmp(a1, a2, bytes))) {
1004  return r;
1005  } else if (leftover_bits) {
1006  uint8_t b1 = a1[bytes] >> (8-leftover_bits);
1007  uint8_t b2 = a2[bytes] >> (8-leftover_bits);
1008  return TRISTATE(b1, b2);
1009  } else {
1010  return 0;
1011  }
1012  }
1013  case AF_UNIX:
1014  /* HACKHACKHACKHACKHACK:
1015  * tor_addr_t doesn't contain a copy of sun_path, so it's not
1016  * possible to compare this at all.
1017  *
1018  * Since the only time we currently actually should be comparing
1019  * 2 AF_UNIX addresses is when dealing with ISO_CLIENTADDR (which
1020  * is disabled for AF_UNIX SocksPorts anyway), this just does
1021  * a pointer comparison.
1022  *
1023  * See: #20261.
1024  */
1025  if (addr1 < addr2)
1026  return -1;
1027  else if (addr1 == addr2)
1028  return 0;
1029  else
1030  return 1;
1031  /* LCOV_EXCL_START */
1032  default:
1034  return 0;
1035  /* LCOV_EXCL_STOP */
1036  }
1037  } else if (how == CMP_EXACT) {
1038  /* Unequal families and an exact comparison? Stop now! */
1039  return TRISTATE(family1, family2);
1040  }
1041 
1042  if (mbits == 0)
1043  return 0;
1044 
1045  if (family1 == AF_INET6 && tor_addr_is_v4(addr1))
1046  v_family1 = AF_INET;
1047  if (family2 == AF_INET6 && tor_addr_is_v4(addr2))
1048  v_family2 = AF_INET;
1049  if (v_family1 == v_family2) {
1050  /* One or both addresses are a mapped ipv4 address. */
1051  uint32_t a1, a2;
1052  if (family1 == AF_INET6) {
1053  a1 = tor_addr_to_mapped_ipv4h(addr1);
1054  if (mbits <= 96)
1055  return 0;
1056  mbits -= 96; /* We just decided that the first 96 bits of a1 "match". */
1057  } else {
1058  a1 = tor_addr_to_ipv4h(addr1);
1059  }
1060  if (family2 == AF_INET6) {
1061  a2 = tor_addr_to_mapped_ipv4h(addr2);
1062  } else {
1063  a2 = tor_addr_to_ipv4h(addr2);
1064  }
1065  if (mbits > 32) mbits = 32;
1066  a1 >>= (32-mbits);
1067  a2 >>= (32-mbits);
1068  return TRISTATE(a1, a2);
1069  } else {
1070  /* Unequal families, and semantic comparison, and no semantic family
1071  * matches. */
1072  return TRISTATE(family1, family2);
1073  }
1074 }
1075 
1077 static const uint32_t unspec_hash_input[] = { 0x4e4df09f, 0x92985342 };
1078 
1080 uint64_t
1082 {
1083  switch (tor_addr_family(addr)) {
1084  case AF_INET:
1085  return siphash24g(&addr->addr.in_addr.s_addr, 4);
1086  case AF_UNSPEC:
1087  return siphash24g(unspec_hash_input, sizeof(unspec_hash_input));
1088  case AF_INET6:
1089  return siphash24g(&addr->addr.in6_addr.s6_addr, 16);
1090  /* LCOV_EXCL_START */
1091  default:
1093  return 0;
1094  /* LCOV_EXCL_STOP */
1095  }
1096 }
1097 
1099 uint64_t
1100 tor_addr_keyed_hash(const struct sipkey *key, const tor_addr_t *addr)
1101 {
1102  /* This is duplicate code with tor_addr_hash, since this function needs to
1103  * be backportable all the way to 0.2.9. */
1104 
1105  switch (tor_addr_family(addr)) {
1106  case AF_INET:
1107  return siphash24(&addr->addr.in_addr.s_addr, 4, key);
1108  case AF_UNSPEC:
1109  return siphash24(unspec_hash_input, sizeof(unspec_hash_input), key);
1110  case AF_INET6:
1111  return siphash24(&addr->addr.in6_addr.s6_addr, 16, key);
1112  default:
1113  /* LCOV_EXCL_START */
1115  return 0;
1116  /* LCOV_EXCL_STOP */
1117  }
1118 }
1119 
1121 char *
1123 {
1124  char buf[TOR_ADDR_BUF_LEN];
1125  if (tor_addr_to_str(buf, addr, sizeof(buf), 0)) {
1126  return tor_strdup(buf);
1127  } else {
1128  return tor_strdup("<unknown address type>");
1129  }
1130 }
1131 
1141 const char *
1142 fmt_addr_impl(const tor_addr_t *addr, int decorate)
1143 {
1144  static char buf[TOR_ADDR_BUF_LEN];
1145  if (!addr) return "<null>";
1146  if (tor_addr_to_str(buf, addr, sizeof(buf), decorate))
1147  return buf;
1148  else
1149  return "???";
1150 }
1151 
1156 const char *
1157 fmt_addrport(const tor_addr_t *addr, uint16_t port)
1158 {
1159  /* Add space for a colon and up to 5 digits. */
1160  static char buf[TOR_ADDR_BUF_LEN + 6];
1161  tor_snprintf(buf, sizeof(buf), "%s:%u", fmt_and_decorate_addr(addr), port);
1162  return buf;
1163 }
1164 
1168 const char *
1169 fmt_addr32(uint32_t addr)
1170 {
1171  static char buf[INET_NTOA_BUF_LEN];
1172  struct in_addr in;
1173  in.s_addr = htonl(addr);
1174  tor_inet_ntoa(&in, buf, sizeof(buf));
1175  return buf;
1176 }
1177 
1184 int
1185 tor_addr_parse(tor_addr_t *addr, const char *src)
1186 {
1187  /* Holds substring of IPv6 address after removing square brackets */
1188  char *tmp = NULL;
1189  int result;
1190  struct in_addr in_tmp;
1191  struct in6_addr in6_tmp;
1192  int brackets_detected = 0;
1193 
1194  tor_assert(addr && src);
1195 
1196  size_t len = strlen(src);
1197 
1198  if (len && src[0] == '[' && src[len - 1] == ']') {
1199  brackets_detected = 1;
1200  src = tmp = tor_strndup(src+1, strlen(src)-2);
1201  }
1202 
1203  if (tor_inet_pton(AF_INET6, src, &in6_tmp) > 0) {
1204  result = AF_INET6;
1205  tor_addr_from_in6(addr, &in6_tmp);
1206  } else if (!brackets_detected &&
1207  tor_inet_pton(AF_INET, src, &in_tmp) > 0) {
1208  result = AF_INET;
1209  tor_addr_from_in(addr, &in_tmp);
1210  } else {
1211  result = -1;
1212  }
1213 
1214  tor_free(tmp);
1215  return result;
1216 }
1217 
1218 #ifdef HAVE_IFADDRS_TO_SMARTLIST
1219 /*
1220  * Convert a linked list consisting of <b>ifaddrs</b> structures
1221  * into smartlist of <b>tor_addr_t</b> structures.
1222  */
1223 STATIC smartlist_t *
1224 ifaddrs_to_smartlist(const struct ifaddrs *ifa, sa_family_t family)
1225 {
1226  smartlist_t *result = smartlist_new();
1227  const struct ifaddrs *i;
1228 
1229  for (i = ifa; i; i = i->ifa_next) {
1230  tor_addr_t tmp;
1231  if ((i->ifa_flags & (IFF_UP | IFF_RUNNING)) != (IFF_UP | IFF_RUNNING))
1232  continue;
1233  if (!i->ifa_addr)
1234  continue;
1235  if (i->ifa_addr->sa_family != AF_INET &&
1236  i->ifa_addr->sa_family != AF_INET6)
1237  continue;
1238  if (family != AF_UNSPEC && i->ifa_addr->sa_family != family)
1239  continue;
1240  if (tor_addr_from_sockaddr(&tmp, i->ifa_addr, NULL) < 0)
1241  continue;
1242  smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
1243  }
1244 
1245  return result;
1246 }
1247 
1252 STATIC smartlist_t *
1253 get_interface_addresses_ifaddrs(int severity, sa_family_t family)
1254 {
1255 
1256  /* Most free Unixy systems provide getifaddrs, which gives us a linked list
1257  * of struct ifaddrs. */
1258  struct ifaddrs *ifa = NULL;
1259  smartlist_t *result;
1260  if (getifaddrs(&ifa) < 0) {
1261  log_fn(severity, LD_NET, "Unable to call getifaddrs(): %s",
1262  strerror(errno));
1263  return NULL;
1264  }
1265 
1266  result = ifaddrs_to_smartlist(ifa, family);
1267 
1268  freeifaddrs(ifa);
1269 
1270  return result;
1271 }
1272 #endif /* defined(HAVE_IFADDRS_TO_SMARTLIST) */
1273 
1274 #ifdef HAVE_IP_ADAPTER_TO_SMARTLIST
1275 
1280 STATIC smartlist_t *
1281 ip_adapter_addresses_to_smartlist(const IP_ADAPTER_ADDRESSES *addresses)
1282 {
1283  smartlist_t *result = smartlist_new();
1284  const IP_ADAPTER_ADDRESSES *address;
1285 
1286  for (address = addresses; address; address = address->Next) {
1287  const IP_ADAPTER_UNICAST_ADDRESS *a;
1288  for (a = address->FirstUnicastAddress; a; a = a->Next) {
1289  /* Yes, it's a linked list inside a linked list */
1290  const struct sockaddr *sa = a->Address.lpSockaddr;
1291  tor_addr_t tmp;
1292  if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
1293  continue;
1294  if (tor_addr_from_sockaddr(&tmp, sa, NULL) < 0)
1295  continue;
1296  smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
1297  }
1298  }
1299 
1300  return result;
1301 }
1302 
1307 STATIC smartlist_t *
1308 get_interface_addresses_win32(int severity, sa_family_t family)
1309 {
1310  smartlist_t *result = NULL;
1311  ULONG size, res;
1312  IP_ADAPTER_ADDRESSES *addresses = NULL;
1313 
1314  (void) severity;
1315 
1316 #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
1317  GAA_FLAG_SKIP_MULTICAST | \
1318  GAA_FLAG_SKIP_DNS_SERVER)
1319 
1320  /* Guess how much space we need. */
1321  size = 15*1024;
1322  addresses = tor_malloc(size);
1323  /* Exists in windows XP and later. */
1324  res = GetAdaptersAddresses(family, FLAGS, NULL, addresses, &size);
1325  if (res == ERROR_BUFFER_OVERFLOW) {
1326  /* we didn't guess that we needed enough space; try again */
1327  tor_free(addresses);
1328  addresses = tor_malloc(size);
1329  res = GetAdaptersAddresses(AF_UNSPEC, FLAGS, NULL, addresses, &size);
1330  }
1331  if (res != NO_ERROR) {
1332  log_fn(severity, LD_NET, "GetAdaptersAddresses failed (result: %lu)", res);
1333  goto done;
1334  }
1335 
1336  result = ip_adapter_addresses_to_smartlist(addresses);
1337 
1338  done:
1339  tor_free(addresses);
1340  return result;
1341 }
1342 
1343 #endif /* defined(HAVE_IP_ADAPTER_TO_SMARTLIST) */
1344 
1345 #ifdef HAVE_IFCONF_TO_SMARTLIST
1346 
1347 /* Guess how much space we need. There shouldn't be any struct ifreqs
1348  * larger than this, even on OS X where the struct's size is dynamic. */
1349 #define IFREQ_SIZE 4096
1350 
1351 /* This is defined on Mac OS X */
1352 #ifndef _SIZEOF_ADDR_IFREQ
1353 #define _SIZEOF_ADDR_IFREQ sizeof
1354 #endif
1355 
1356 /* Free ifc->ifc_buf safely. */
1357 static void
1358 ifconf_free_ifc_buf(struct ifconf *ifc)
1359 {
1360  /* On macOS, tor_free() takes the address of ifc.ifc_buf, which leads to
1361  * undefined behaviour, because pointer-to-pointers are expected to be
1362  * aligned at 8-bytes, but the ifconf structure is packed. So we use
1363  * raw_free() instead. */
1364  raw_free(ifc->ifc_buf);
1365  ifc->ifc_buf = NULL;
1366 }
1367 
1371 STATIC smartlist_t *
1372 ifreq_to_smartlist(char *buf, size_t buflen)
1373 {
1374  smartlist_t *result = smartlist_new();
1375  char *end = buf + buflen;
1376 
1377  /* These acrobatics are due to alignment issues which trigger
1378  * undefined behaviour traps on OSX. */
1379  struct ifreq *r = tor_malloc(IFREQ_SIZE);
1380 
1381  while (buf < end) {
1382  /* Copy up to IFREQ_SIZE bytes into the struct ifreq, but don't overrun
1383  * buf. */
1384  memcpy(r, buf, end - buf < IFREQ_SIZE ? end - buf : IFREQ_SIZE);
1385 
1386  const struct sockaddr *sa = &r->ifr_addr;
1387  tor_addr_t tmp;
1388  int valid_sa_family = (sa->sa_family == AF_INET ||
1389  sa->sa_family == AF_INET6);
1390 
1391  int conversion_success = (tor_addr_from_sockaddr(&tmp, sa, NULL) == 0);
1392 
1393  if (valid_sa_family && conversion_success)
1394  smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
1395 
1396  buf += _SIZEOF_ADDR_IFREQ(*r);
1397  }
1398 
1399  tor_free(r);
1400  return result;
1401 }
1402 
1407 STATIC smartlist_t *
1408 get_interface_addresses_ioctl(int severity, sa_family_t family)
1409 {
1410  /* Some older unixy systems make us use ioctl(SIOCGIFCONF) */
1411  struct ifconf ifc;
1412  ifc.ifc_buf = NULL;
1413  int fd;
1414  smartlist_t *result = NULL;
1415 
1416  /* This interface, AFAICT, only supports AF_INET addresses,
1417  * except on AIX. For Solaris, we could use SIOCGLIFCONF. */
1418 
1419  /* Bail out if family is neither AF_INET nor AF_UNSPEC since
1420  * ioctl() technique supports non-IPv4 interface addresses on
1421  * a small number of niche systems only. If family is AF_UNSPEC,
1422  * fall back to getting AF_INET addresses only. */
1423  if (family == AF_UNSPEC)
1424  family = AF_INET;
1425  else if (family != AF_INET)
1426  return NULL;
1427 
1428  fd = socket(family, SOCK_DGRAM, 0);
1429  if (fd < 0) {
1430  tor_log(severity, LD_NET, "socket failed: %s", strerror(errno));
1431  goto done;
1432  }
1433 
1434  int mult = 1;
1435  do {
1436  mult *= 2;
1437  ifc.ifc_len = mult * IFREQ_SIZE;
1438  ifc.ifc_buf = tor_realloc(ifc.ifc_buf, ifc.ifc_len);
1439 
1440  tor_assert(ifc.ifc_buf);
1441 
1442  if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) {
1443  tor_log(severity, LD_NET, "ioctl failed: %s", strerror(errno));
1444  goto done;
1445  }
1446  /* Ensure we have least IFREQ_SIZE bytes unused at the end. Otherwise, we
1447  * don't know if we got everything during ioctl. */
1448  } while (mult * IFREQ_SIZE - ifc.ifc_len <= IFREQ_SIZE);
1449  result = ifreq_to_smartlist(ifc.ifc_buf, ifc.ifc_len);
1450 
1451  done:
1452  if (fd >= 0)
1453  close(fd);
1454  ifconf_free_ifc_buf(&ifc);
1455  return result;
1456 }
1457 #endif /* defined(HAVE_IFCONF_TO_SMARTLIST) */
1458 
1466 get_interface_addresses_raw,(int severity, sa_family_t family))
1467 {
1468  smartlist_t *result = NULL;
1469 #if defined(HAVE_IFADDRS_TO_SMARTLIST)
1470  if ((result = get_interface_addresses_ifaddrs(severity, family)))
1471  return result;
1472 #endif
1473 #if defined(HAVE_IP_ADAPTER_TO_SMARTLIST)
1474  if ((result = get_interface_addresses_win32(severity, family)))
1475  return result;
1476 #endif
1477 #if defined(HAVE_IFCONF_TO_SMARTLIST)
1478  if ((result = get_interface_addresses_ioctl(severity, family)))
1479  return result;
1480 #endif
1481  (void) severity;
1482  (void) result;
1483  return NULL;
1484 }
1485 
1487 int
1489 {
1490  sa_family_t family = tor_addr_family(a);
1491  if (family == AF_INET) {
1492  uint32_t ipv4h = tor_addr_to_ipv4h(a);
1493  if ((ipv4h >> 24) == 0xe0)
1494  return 1; /* Multicast */
1495  } else if (family == AF_INET6) {
1496  const uint8_t *a32 = tor_addr_to_in6_addr8(a);
1497  if (a32[0] == 0xff)
1498  return 1;
1499  }
1500  return 0;
1501 }
1502 
1509 get_interface_address6_via_udp_socket_hack,(int severity,
1510  sa_family_t family,
1511  tor_addr_t *addr))
1512 {
1513  struct sockaddr_storage target_addr;
1514  int sock=-1, r=-1;
1515  socklen_t addr_len;
1516 
1517  memset(addr, 0, sizeof(tor_addr_t));
1518  memset(&target_addr, 0, sizeof(target_addr));
1519 
1520  /* Don't worry: no packets are sent. We just need to use a real address
1521  * on the actual Internet. */
1522  if (family == AF_INET6) {
1523  struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&target_addr;
1524  /* Use the "discard" service port */
1525  sin6->sin6_port = htons(9);
1526  sock = tor_open_socket(PF_INET6,SOCK_DGRAM,IPPROTO_UDP);
1527  addr_len = (socklen_t)sizeof(struct sockaddr_in6);
1528  sin6->sin6_family = AF_INET6;
1529  S6_ADDR16(sin6->sin6_addr)[0] = htons(0x2002); /* 2002:: */
1530  } else if (family == AF_INET) {
1531  struct sockaddr_in *sin = (struct sockaddr_in*)&target_addr;
1532  /* Use the "discard" service port */
1533  sin->sin_port = htons(9);
1534  sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
1535  addr_len = (socklen_t)sizeof(struct sockaddr_in);
1536  sin->sin_family = AF_INET;
1537  sin->sin_addr.s_addr = htonl(0x12000001); /* 18.0.0.1 */
1538  } else {
1539  return -1;
1540  }
1541 
1542  if (sock < 0) {
1543  int e = tor_socket_errno(-1);
1544  log_fn(severity, LD_NET, "unable to create socket: %s",
1545  tor_socket_strerror(e));
1546  goto err;
1547  }
1548 
1549  if (tor_connect_socket(sock,(struct sockaddr *)&target_addr,
1550  addr_len) < 0) {
1551  int e = tor_socket_errno(sock);
1552  log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e));
1553  goto err;
1554  }
1555 
1556  if (tor_addr_from_getsockname(addr, sock) < 0) {
1557  int e = tor_socket_errno(sock);
1558  log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s",
1559  tor_socket_strerror(e));
1560  goto err;
1561  }
1562 
1563  if (tor_addr_is_loopback(addr) || tor_addr_is_multicast(addr)) {
1564  log_fn(severity, LD_NET, "Address that we determined via UDP socket"
1565  " magic is unsuitable for public comms.");
1566  } else {
1567  r=0;
1568  }
1569 
1570  err:
1571  if (sock >= 0)
1572  tor_close_socket(sock);
1573  if (r == -1)
1574  memset(addr, 0, sizeof(tor_addr_t));
1575  return r;
1576 }
1577 
1587 get_interface_address6,(int severity, sa_family_t family, tor_addr_t *addr))
1588 {
1589  smartlist_t *addrs;
1590  int rv = -1;
1591  tor_assert(addr);
1592 
1593  memset(addr, 0, sizeof(tor_addr_t));
1594 
1595  /* Get a list of public or internal IPs in arbitrary order */
1596  addrs = get_interface_address6_list(severity, family, 1);
1597 
1598  /* Find the first non-internal address, or the last internal address
1599  * Ideally, we want the default route, see #12377 for details */
1600  SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a) {
1601  tor_addr_copy(addr, a);
1602  rv = 0;
1603 
1604  /* If we found a non-internal address, declare success. Otherwise,
1605  * keep looking. */
1606  if (!tor_addr_is_internal(a, 0))
1607  break;
1608  } SMARTLIST_FOREACH_END(a);
1609 
1610  interface_address6_list_free(addrs);
1611  return rv;
1612 }
1613 
1616 void
1618 {
1619  if (addrs != NULL) {
1620  SMARTLIST_FOREACH(addrs, tor_addr_t *, a, tor_free(a));
1621  smartlist_free(addrs);
1622  }
1623 }
1624 
1635 get_interface_address6_list,(int severity,
1636  sa_family_t family,
1637  int include_internal))
1638 {
1639  smartlist_t *addrs;
1640  tor_addr_t addr;
1641 
1642  /* Try to do this the smart way if possible. */
1643  if ((addrs = get_interface_addresses_raw(severity, family))) {
1644  SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a)
1645  {
1646  if (tor_addr_is_loopback(a) ||
1647  tor_addr_is_multicast(a)) {
1649  tor_free(a);
1650  continue;
1651  }
1652 
1653  if (!include_internal && tor_addr_is_internal(a, 0)) {
1655  tor_free(a);
1656  continue;
1657  }
1658  } SMARTLIST_FOREACH_END(a);
1659  }
1660 
1661  if (addrs && smartlist_len(addrs) > 0) {
1662  return addrs;
1663  }
1664 
1665  /* if we removed all entries as unsuitable */
1666  if (addrs) {
1667  smartlist_free(addrs);
1668  }
1669 
1670  /* Okay, the smart way is out. */
1671  addrs = smartlist_new();
1672 
1673  if (family == AF_INET || family == AF_UNSPEC) {
1674  if (get_interface_address6_via_udp_socket_hack(severity,AF_INET,
1675  &addr) == 0) {
1676  if (include_internal || !tor_addr_is_internal(&addr, 0)) {
1677  smartlist_add(addrs, tor_memdup(&addr, sizeof(addr)));
1678  }
1679  }
1680  }
1681 
1682  if (family == AF_INET6 || family == AF_UNSPEC) {
1683  if (get_interface_address6_via_udp_socket_hack(severity,AF_INET6,
1684  &addr) == 0) {
1685  if (include_internal || !tor_addr_is_internal(&addr, 0)) {
1686  smartlist_add(addrs, tor_memdup(&addr, sizeof(addr)));
1687  }
1688  }
1689  }
1690 
1691  return addrs;
1692 }
1693 
1694 /* ======
1695  * IPv4 helpers
1696  * XXXX IPv6 deprecate some of these.
1697  */
1698 
1711 int
1712 tor_addr_port_parse(int severity, const char *addrport,
1713  tor_addr_t *address_out, uint16_t *port_out,
1714  int default_port)
1715 {
1716  int retval = -1;
1717  int r;
1718  char *addr_tmp = NULL;
1719 
1720  tor_assert(addrport);
1721  tor_assert(address_out);
1722  tor_assert(port_out);
1723 
1724  r = tor_addr_port_split(severity, addrport, &addr_tmp, port_out);
1725  if (r < 0)
1726  goto done;
1727 
1728  if (!*port_out) {
1729  if (default_port >= 0)
1730  *port_out = default_port;
1731  else
1732  goto done;
1733  }
1734 
1735  /* make sure that address_out is an IP address */
1736  if (tor_addr_parse(address_out, addr_tmp) < 0)
1737  goto done;
1738 
1739  retval = 0;
1740 
1741  done:
1742  tor_free(addr_tmp);
1743  return retval;
1744 }
1745 
1750 int
1751 tor_addr_port_split(int severity, const char *addrport,
1752  char **address_out, uint16_t *port_out)
1753 {
1754  tor_addr_t a_tmp;
1755  tor_assert(addrport);
1756  tor_assert(address_out);
1757  tor_assert(port_out);
1758  /* We need to check for IPv6 manually because the logic below doesn't
1759  * do a good job on IPv6 addresses that lack a port. */
1760  if (tor_addr_parse(&a_tmp, addrport) == AF_INET6) {
1761  *port_out = 0;
1762  *address_out = tor_strdup(addrport);
1763  return 0;
1764  }
1765 
1766  const char *colon;
1767  char *address_ = NULL;
1768  int port_;
1769  int ok = 1;
1770 
1771  colon = strrchr(addrport, ':');
1772  if (colon) {
1773  address_ = tor_strndup(addrport, colon-addrport);
1774  port_ = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
1775  if (!port_) {
1776  log_fn(severity, LD_GENERAL, "Port %s out of range", escaped(colon+1));
1777  ok = 0;
1778  }
1779  if (!port_out) {
1780  char *esc_addrport = esc_for_log(addrport);
1781  log_fn(severity, LD_GENERAL,
1782  "Port %s given on %s when not required",
1783  escaped(colon+1), esc_addrport);
1784  tor_free(esc_addrport);
1785  ok = 0;
1786  }
1787  } else {
1788  address_ = tor_strdup(addrport);
1789  port_ = 0;
1790  }
1791 
1792  if (ok) {
1793  *address_out = address_;
1794  } else {
1795  *address_out = NULL;
1796  tor_free(address_);
1797  }
1798 
1799  if (port_out)
1800  *port_out = ok ? ((uint16_t) port_) : 0;
1801 
1802  return ok ? 0 : -1;
1803 }
1804 
1807 int
1808 addr_mask_get_bits(uint32_t mask)
1809 {
1810  int i;
1811  if (mask == 0)
1812  return 0;
1813  if (mask == 0xFFFFFFFFu)
1814  return 32;
1815  for (i=1; i<=32; ++i) {
1816  if (mask == (uint32_t) ~((1u<<(32-i))-1)) {
1817  return i;
1818  }
1819  }
1820  return -1;
1821 }
1822 
1826 int
1827 parse_port_range(const char *port, uint16_t *port_min_out,
1828  uint16_t *port_max_out)
1829 {
1830  int port_min, port_max, ok;
1831  tor_assert(port_min_out);
1832  tor_assert(port_max_out);
1833 
1834  if (!port || *port == '\0' || strcmp(port, "*") == 0) {
1835  port_min = 1;
1836  port_max = 65535;
1837  } else {
1838  char *endptr = NULL;
1839  port_min = (int)tor_parse_long(port, 10, 0, 65535, &ok, &endptr);
1840  if (!ok) {
1841  log_warn(LD_GENERAL,
1842  "Malformed port %s on address range; rejecting.",
1843  escaped(port));
1844  return -1;
1845  } else if (endptr && *endptr == '-') {
1846  port = endptr+1;
1847  endptr = NULL;
1848  port_max = (int)tor_parse_long(port, 10, 1, 65535, &ok, &endptr);
1849  if (!ok) {
1850  log_warn(LD_GENERAL,
1851  "Malformed port %s on address range; rejecting.",
1852  escaped(port));
1853  return -1;
1854  }
1855  } else {
1856  port_max = port_min;
1857  }
1858  if (port_min > port_max) {
1859  log_warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
1860  return -1;
1861  }
1862  }
1863 
1864  if (port_min < 1)
1865  port_min = 1;
1866  if (port_max > 65535)
1867  port_max = 65535;
1868 
1869  *port_min_out = (uint16_t) port_min;
1870  *port_max_out = (uint16_t) port_max;
1871 
1872  return 0;
1873 }
1874 
1878 char *
1879 tor_dup_ip(uint32_t addr)
1880 {
1881  char buf[TOR_ADDR_BUF_LEN];
1882  struct in_addr in;
1883 
1884  in.s_addr = htonl(addr);
1885  tor_inet_ntop(AF_INET, &in, buf, sizeof(buf));
1886  return tor_strdup(buf);
1887 }
1888 
1899 get_interface_address,(int severity, uint32_t *addr))
1900 {
1901  tor_addr_t local_addr;
1902  int r;
1903 
1904  memset(addr, 0, sizeof(uint32_t));
1905 
1906  r = get_interface_address6(severity, AF_INET, &local_addr);
1907  if (r>=0)
1908  *addr = tor_addr_to_ipv4h(&local_addr);
1909  return r;
1910 }
1911 
1915 int
1917 {
1918  return !strcasecmp(name, "localhost") ||
1919  !strcasecmp(name, "local") ||
1920  !strcasecmpend(name, ".local");
1921 }
1922 
1926 tor_addr_port_new(const tor_addr_t *addr, uint16_t port)
1927 {
1928  tor_addr_port_t *ap = tor_malloc_zero(sizeof(tor_addr_port_t));
1929  if (addr)
1930  tor_addr_copy(&ap->addr, addr);
1931  ap->port = port;
1932  return ap;
1933 }
1934 
1936 int
1938  const tor_addr_port_t *b)
1939 {
1940  return tor_addr_eq(&a->addr, &b->addr) && a->port == b->port;
1941 }
1942 
1946 int
1947 string_is_valid_ipv4_address(const char *string)
1948 {
1949  struct in_addr addr;
1950 
1951  return (tor_inet_pton(AF_INET,string,&addr) == 1);
1952 }
1953 
1957 int
1958 string_is_valid_ipv6_address(const char *string)
1959 {
1960  struct in6_addr addr;
1961 
1962  return (tor_inet_pton(AF_INET6,string,&addr) == 1);
1963 }
1964 
1968 int
1969 string_is_valid_dest(const char *string)
1970 {
1971  char *tmp = NULL;
1972  int retval;
1973  size_t len;
1974 
1975  if (string == NULL)
1976  return 0;
1977 
1978  len = strlen(string);
1979 
1980  if (len == 0)
1981  return 0;
1982 
1983  if (string[0] == '[' && string[len - 1] == ']')
1984  string = tmp = tor_strndup(string + 1, len - 2);
1985 
1986  retval = string_is_valid_ipv4_address(string) ||
1987  string_is_valid_ipv6_address(string) ||
1989 
1990  tor_free(tmp);
1991 
1992  return retval;
1993 }
1994 
2001 int
2003 {
2004  int result = 1;
2005  int has_trailing_dot;
2006  char *last_label;
2007  smartlist_t *components;
2008 
2009  if (!string || strlen(string) == 0)
2010  return 0;
2011 
2012  if (string_is_valid_ipv4_address(string))
2013  return 0;
2014 
2015  components = smartlist_new();
2016 
2017  smartlist_split_string(components,string,".",0,0);
2018 
2019  if (BUG(smartlist_len(components) == 0))
2020  return 0; // LCOV_EXCL_LINE should be impossible given the earlier checks.
2021 
2022  /* Allow a single terminating '.' used rarely to indicate domains
2023  * are FQDNs rather than relative. */
2024  last_label = (char *)smartlist_get(components,
2025  smartlist_len(components) - 1);
2026  has_trailing_dot = (last_label[0] == '\0');
2027  if (has_trailing_dot) {
2028  smartlist_pop_last(components);
2029  tor_free(last_label);
2030  last_label = NULL;
2031  }
2032 
2033  SMARTLIST_FOREACH_BEGIN(components, char *, c) {
2034  if ((c[0] == '-') || (*c == '_')) {
2035  result = 0;
2036  break;
2037  }
2038 
2039  do {
2040  result = (TOR_ISALNUM(*c) || (*c == '-') || (*c == '_'));
2041  c++;
2042  } while (result && *c);
2043 
2044  if (result == 0) {
2045  break;
2046  }
2047  } SMARTLIST_FOREACH_END(c);
2048 
2049  SMARTLIST_FOREACH_BEGIN(components, char *, c) {
2050  tor_free(c);
2051  } SMARTLIST_FOREACH_END(c);
2052 
2053  smartlist_free(components);
2054 
2055  return result;
2056 }
void tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
Definition: address.c:862
int addr_mask_get_bits(uint32_t mask)
Definition: address.c:1808
const char * tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
Definition: address.c:317
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:1617
#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:458
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:1947
#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:368
#define LD_GENERAL
Definition: log.h:58
int tor_addr_is_internal_(const tor_addr_t *addr, int for_listening, const char *filename, int lineno)
Definition: address.c:246
int tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2, tor_addr_comparison_t how)
Definition: address.c:942
int tor_addr_port_eq(const tor_addr_port_t *a, const tor_addr_port_t *b)
Definition: address.c:1937
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:1916
void tor_log(int severity, log_domain_mask_t domain, const char *format,...)
Definition: log.c:631
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:2002
#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:1077
#define tor_fragile_assert()
Definition: util_bug.h:221
#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:1827
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:737
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:258
#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:1157
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:1712
const char * fmt_addr_impl(const tor_addr_t *addr, int decorate)
Definition: address.c:1142
void tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
Definition: address.c:873
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:531
int tor_addr_parse(tor_addr_t *addr, const char *src)
Definition: address.c:1185
uint64_t tor_addr_hash(const tor_addr_t *addr)
Definition: address.c:1081
const char * fmt_addr32(uint32_t addr)
Definition: address.c:1169
int tor_addr_is_null(const tor_addr_t *addr)
Definition: address.c:758
Header for process.c.
int tor_addr_is_loopback(const tor_addr_t *addr)
Definition: address.c:783
uint64_t tor_addr_keyed_hash(const struct sipkey *key, const tor_addr_t *addr)
Definition: address.c:1100
int tor_addr_is_multicast(const tor_addr_t *a)
Definition: address.c:1488
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:1122
void tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
Definition: address.c:884
#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:1926
const char * escaped(const char *s)
Definition: escape.c:126
int string_is_valid_ipv6_address(const char *string)
Definition: address.c:1958
Locale-independent character-type inspection (header)
#define log_fn(severity, domain, args,...)
Definition: log.h:255
int string_is_valid_dest(const char *string)
Definition: address.c:1969
#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:1465
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:963
char * esc_for_log(const char *s)
Definition: escape.c:30
#define LD_NET
Definition: log.h:62
#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:892
void tor_addr_copy_tight(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:906
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:82
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:1751
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:1879