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