Remove some totally unused functions
[tor.git] / src / common / address.c
blob69e7f681036d15039f0223fbf2daeda02d2e8b14
1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2013, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /**
7 * \file address.c
8 * \brief Functions to use and manipulate the tor_addr_t structure.
9 **/
11 #include "orconfig.h"
12 #include "compat.h"
13 #include "util.h"
14 #include "address.h"
15 #include "torlog.h"
16 #include "container.h"
18 #ifdef _WIN32
19 #include <process.h>
20 #include <windows.h>
21 #include <winsock2.h>
22 /* For access to structs needed by GetAdaptersAddresses */
23 #undef _WIN32_WINNT
24 #define _WIN32_WINNT 0x0501
25 #include <iphlpapi.h>
26 #endif
28 #ifdef HAVE_SYS_TIME_H
29 #include <sys/time.h>
30 #endif
31 #ifdef HAVE_UNISTD_H
32 #include <unistd.h>
33 #endif
34 #ifdef HAVE_ERRNO_H
35 #include <errno.h>
36 #endif
37 #ifdef HAVE_NETINET_IN_H
38 #include <netinet/in.h>
39 #endif
40 #ifdef HAVE_ARPA_INET_H
41 #include <arpa/inet.h>
42 #endif
43 #ifdef HAVE_SYS_SOCKET_H
44 #include <sys/socket.h>
45 #endif
46 #ifdef HAVE_NETDB_H
47 #include <netdb.h>
48 #endif
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
51 #endif
52 #ifdef HAVE_SYS_UN_H
53 #include <sys/un.h>
54 #endif
55 #ifdef HAVE_IFADDRS_H
56 #include <ifaddrs.h>
57 #endif
58 #ifdef HAVE_SYS_IOCTL_H
59 #include <sys/ioctl.h>
60 #endif
61 #ifdef HAVE_NET_IF_H
62 #include <net/if.h>
63 #endif
64 #include <stdarg.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <assert.h>
70 /* tor_addr_is_null() and maybe other functions rely on AF_UNSPEC being 0 to
71 * work correctly. Bail out here if we've found a platform where AF_UNSPEC
72 * isn't 0. */
73 #if AF_UNSPEC != 0
74 #error We rely on AF_UNSPEC being 0. Let us know about your platform, please!
75 #endif
77 /** Convert the tor_addr_t in <b>a</b>, with port in <b>port</b>, into a
78 * sockaddr object in *<b>sa_out</b> of object size <b>len</b>. If not enough
79 * room is available in sa_out, or on error, return 0. On success, return
80 * the length of the sockaddr.
82 * Interface note: ordinarily, we return -1 for error. We can't do that here,
83 * since socklen_t is unsigned on some platforms.
84 **/
85 socklen_t
86 tor_addr_to_sockaddr(const tor_addr_t *a,
87 uint16_t port,
88 struct sockaddr *sa_out,
89 socklen_t len)
91 sa_family_t family = tor_addr_family(a);
92 if (family == AF_INET) {
93 struct sockaddr_in *sin;
94 if (len < (int)sizeof(struct sockaddr_in))
95 return 0;
96 sin = (struct sockaddr_in *)sa_out;
97 memset(sin, 0, sizeof(struct sockaddr_in));
98 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
99 sin->sin_len = sizeof(struct sockaddr_in);
100 #endif
101 sin->sin_family = AF_INET;
102 sin->sin_port = htons(port);
103 sin->sin_addr.s_addr = tor_addr_to_ipv4n(a);
104 return sizeof(struct sockaddr_in);
105 } else if (family == AF_INET6) {
106 struct sockaddr_in6 *sin6;
107 if (len < (int)sizeof(struct sockaddr_in6))
108 return 0;
109 sin6 = (struct sockaddr_in6 *)sa_out;
110 memset(sin6, 0, sizeof(struct sockaddr_in6));
111 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
112 sin6->sin6_len = sizeof(struct sockaddr_in6);
113 #endif
114 sin6->sin6_family = AF_INET6;
115 sin6->sin6_port = htons(port);
116 memcpy(&sin6->sin6_addr, tor_addr_to_in6(a), sizeof(struct in6_addr));
117 return sizeof(struct sockaddr_in6);
118 } else {
119 return 0;
123 /** Set the tor_addr_t in <b>a</b> to contain the socket address contained in
124 * <b>sa</b>. */
126 tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa,
127 uint16_t *port_out)
129 tor_assert(a);
130 tor_assert(sa);
131 if (sa->sa_family == AF_INET) {
132 struct sockaddr_in *sin = (struct sockaddr_in *) sa;
133 tor_addr_from_ipv4n(a, sin->sin_addr.s_addr);
134 if (port_out)
135 *port_out = ntohs(sin->sin_port);
136 } else if (sa->sa_family == AF_INET6) {
137 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
138 tor_addr_from_in6(a, &sin6->sin6_addr);
139 if (port_out)
140 *port_out = ntohs(sin6->sin6_port);
141 } else {
142 tor_addr_make_unspec(a);
143 return -1;
145 return 0;
148 /** Return a newly allocated string holding the address described in
149 * <b>sa</b>. AF_UNIX, AF_UNSPEC, AF_INET, and AF_INET6 are supported. */
150 char *
151 tor_sockaddr_to_str(const struct sockaddr *sa)
153 char address[TOR_ADDR_BUF_LEN];
154 char *result;
155 tor_addr_t addr;
156 uint16_t port;
157 #ifdef HAVE_SYS_UN_H
158 if (sa->sa_family == AF_UNIX) {
159 struct sockaddr_un *s_un = (struct sockaddr_un *)sa;
160 tor_asprintf(&result, "unix:%s", s_un->sun_path);
161 return result;
163 #endif
164 if (sa->sa_family == AF_UNSPEC)
165 return tor_strdup("unspec");
167 if (tor_addr_from_sockaddr(&addr, sa, &port) < 0)
168 return NULL;
169 if (! tor_addr_to_str(address, &addr, sizeof(address), 1))
170 return NULL;
171 tor_asprintf(&result, "%s:%d", address, (int)port);
172 return result;
175 /** Set address <b>a</b> to the unspecified address. This address belongs to
176 * no family. */
177 void
178 tor_addr_make_unspec(tor_addr_t *a)
180 memset(a, 0, sizeof(*a));
181 a->family = AF_UNSPEC;
184 /** Set address <a>a</b> to the null address in address family <b>family</b>.
185 * The null address for AF_INET is 0.0.0.0. The null address for AF_INET6 is
186 * [::]. AF_UNSPEC is all null. */
187 void
188 tor_addr_make_null(tor_addr_t *a, sa_family_t family)
190 memset(a, 0, sizeof(*a));
191 a->family = family;
194 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
195 * *<b>addr</b> to the proper IP address and family. The <b>family</b>
196 * argument (which must be AF_INET, AF_INET6, or AF_UNSPEC) declares a
197 * <i>preferred</i> family, though another one may be returned if only one
198 * family is implemented for this address.
200 * Return 0 on success, -1 on failure; 1 on transient failure.
203 tor_addr_lookup(const char *name, uint16_t family, tor_addr_t *addr)
205 /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
206 * something.
208 struct in_addr iaddr;
209 struct in6_addr iaddr6;
210 tor_assert(name);
211 tor_assert(addr);
212 tor_assert(family == AF_INET || family == AF_INET6 || family == AF_UNSPEC);
213 if (!*name) {
214 /* Empty address is an error. */
215 return -1;
216 } else if (tor_inet_pton(AF_INET, name, &iaddr)) {
217 /* It's an IPv4 IP. */
218 if (family == AF_INET6)
219 return -1;
220 tor_addr_from_in(addr, &iaddr);
221 return 0;
222 } else if (tor_inet_pton(AF_INET6, name, &iaddr6)) {
223 if (family == AF_INET)
224 return -1;
225 tor_addr_from_in6(addr, &iaddr6);
226 return 0;
227 } else {
228 #ifdef HAVE_GETADDRINFO
229 int err;
230 struct addrinfo *res=NULL, *res_p;
231 struct addrinfo *best=NULL;
232 struct addrinfo hints;
233 int result = -1;
234 memset(&hints, 0, sizeof(hints));
235 hints.ai_family = family;
236 hints.ai_socktype = SOCK_STREAM;
237 err = getaddrinfo(name, NULL, &hints, &res);
238 if (!err) {
239 best = NULL;
240 for (res_p = res; res_p; res_p = res_p->ai_next) {
241 if (family == AF_UNSPEC) {
242 if (res_p->ai_family == AF_INET) {
243 best = res_p;
244 break;
245 } else if (res_p->ai_family == AF_INET6 && !best) {
246 best = res_p;
248 } else if (family == res_p->ai_family) {
249 best = res_p;
250 break;
253 if (!best)
254 best = res;
255 if (best->ai_family == AF_INET) {
256 tor_addr_from_in(addr,
257 &((struct sockaddr_in*)best->ai_addr)->sin_addr);
258 result = 0;
259 } else if (best->ai_family == AF_INET6) {
260 tor_addr_from_in6(addr,
261 &((struct sockaddr_in6*)best->ai_addr)->sin6_addr);
262 result = 0;
264 freeaddrinfo(res);
265 return result;
267 return (err == EAI_AGAIN) ? 1 : -1;
268 #else
269 struct hostent *ent;
270 int err;
271 #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
272 char buf[2048];
273 struct hostent hostent;
274 int r;
275 r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err);
276 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
277 char buf[2048];
278 struct hostent hostent;
279 ent = gethostbyname_r(name, &hostent, buf, sizeof(buf), &err);
280 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
281 struct hostent_data data;
282 struct hostent hent;
283 memset(&data, 0, sizeof(data));
284 err = gethostbyname_r(name, &hent, &data);
285 ent = err ? NULL : &hent;
286 #else
287 ent = gethostbyname(name);
288 #ifdef _WIN32
289 err = WSAGetLastError();
290 #else
291 err = h_errno;
292 #endif
293 #endif /* endif HAVE_GETHOSTBYNAME_R_6_ARG. */
294 if (ent) {
295 if (ent->h_addrtype == AF_INET) {
296 tor_addr_from_in(addr, (struct in_addr*) ent->h_addr);
297 } else if (ent->h_addrtype == AF_INET6) {
298 tor_addr_from_in6(addr, (struct in6_addr*) ent->h_addr);
299 } else {
300 tor_assert(0); /* gethostbyname() returned a bizarre addrtype */
302 return 0;
304 #ifdef _WIN32
305 return (err == WSATRY_AGAIN) ? 1 : -1;
306 #else
307 return (err == TRY_AGAIN) ? 1 : -1;
308 #endif
309 #endif
313 /** Return true iff <b>ip</b> is an IP reserved to localhost or local networks
314 * in RFC1918 or RFC4193 or RFC4291. (fec0::/10, deprecated by RFC3879, is
315 * also treated as internal for now.)
318 tor_addr_is_internal_(const tor_addr_t *addr, int for_listening,
319 const char *filename, int lineno)
321 uint32_t iph4 = 0;
322 uint32_t iph6[4];
323 sa_family_t v_family;
324 v_family = tor_addr_family(addr);
326 if (v_family == AF_INET) {
327 iph4 = tor_addr_to_ipv4h(addr);
328 } else if (v_family == AF_INET6) {
329 if (tor_addr_is_v4(addr)) { /* v4-mapped */
330 v_family = AF_INET;
331 iph4 = ntohl(tor_addr_to_in6_addr32(addr)[3]);
335 if (v_family == AF_INET6) {
336 const uint32_t *a32 = tor_addr_to_in6_addr32(addr);
337 iph6[0] = ntohl(a32[0]);
338 iph6[1] = ntohl(a32[1]);
339 iph6[2] = ntohl(a32[2]);
340 iph6[3] = ntohl(a32[3]);
341 if (for_listening && !iph6[0] && !iph6[1] && !iph6[2] && !iph6[3]) /* :: */
342 return 0;
344 if (((iph6[0] & 0xfe000000) == 0xfc000000) || /* fc00/7 - RFC4193 */
345 ((iph6[0] & 0xffc00000) == 0xfe800000) || /* fe80/10 - RFC4291 */
346 ((iph6[0] & 0xffc00000) == 0xfec00000)) /* fec0/10 D- RFC3879 */
347 return 1;
349 if (!iph6[0] && !iph6[1] && !iph6[2] &&
350 ((iph6[3] & 0xfffffffe) == 0x00000000)) /* ::/127 */
351 return 1;
353 return 0;
354 } else if (v_family == AF_INET) {
355 if (for_listening && !iph4) /* special case for binding to 0.0.0.0 */
356 return 0;
357 if (((iph4 & 0xff000000) == 0x0a000000) || /* 10/8 */
358 ((iph4 & 0xff000000) == 0x00000000) || /* 0/8 */
359 ((iph4 & 0xff000000) == 0x7f000000) || /* 127/8 */
360 ((iph4 & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
361 ((iph4 & 0xfff00000) == 0xac100000) || /* 172.16/12 */
362 ((iph4 & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
363 return 1;
364 return 0;
367 /* unknown address family... assume it's not safe for external use */
368 /* rather than tor_assert(0) */
369 log_warn(LD_BUG, "tor_addr_is_internal() called from %s:%d with a "
370 "non-IP address of type %d", filename, lineno, (int)v_family);
371 tor_fragile_assert();
372 return 1;
375 /** Convert a tor_addr_t <b>addr</b> into a string, and store it in
376 * <b>dest</b> of size <b>len</b>. Returns a pointer to dest on success,
377 * or NULL on failure. If <b>decorate</b>, surround IPv6 addresses with
378 * brackets.
380 const char *
381 tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
383 const char *ptr;
384 tor_assert(addr && dest);
386 switch (tor_addr_family(addr)) {
387 case AF_INET:
388 /* Shortest addr x.x.x.x + \0 */
389 if (len < 8)
390 return NULL;
391 ptr = tor_inet_ntop(AF_INET, &addr->addr.in_addr, dest, len);
392 break;
393 case AF_INET6:
394 /* Shortest addr [ :: ] + \0 */
395 if (len < (3 + (decorate ? 2 : 0)))
396 return NULL;
398 if (decorate)
399 ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest+1, len-2);
400 else
401 ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest, len);
403 if (ptr && decorate) {
404 *dest = '[';
405 memcpy(dest+strlen(dest), "]", 2);
406 tor_assert(ptr == dest+1);
407 ptr = dest;
409 break;
410 default:
411 return NULL;
413 return ptr;
416 /** Parse an .in-addr.arpa or .ip6.arpa address from <b>address</b>. Return 0
417 * if this is not an .in-addr.arpa address or an .ip6.arpa address. Return -1
418 * if this is an ill-formed .in-addr.arpa address or an .ip6.arpa address.
419 * Also return -1 if <b>family</b> is not AF_UNSPEC, and the parsed address
420 * family does not match <b>family</b>. On success, return 1, and store the
421 * result, if any, into <b>result</b>, if provided.
423 * If <b>accept_regular</b> is set and the address is in neither recognized
424 * reverse lookup hostname format, try parsing the address as a regular
425 * IPv4 or IPv6 address too.
428 tor_addr_parse_PTR_name(tor_addr_t *result, const char *address,
429 int family, int accept_regular)
431 if (!strcasecmpend(address, ".in-addr.arpa")) {
432 /* We have an in-addr.arpa address. */
433 char buf[INET_NTOA_BUF_LEN];
434 size_t len;
435 struct in_addr inaddr;
436 if (family == AF_INET6)
437 return -1;
439 len = strlen(address) - strlen(".in-addr.arpa");
440 if (len >= INET_NTOA_BUF_LEN)
441 return -1; /* Too long. */
443 memcpy(buf, address, len);
444 buf[len] = '\0';
445 if (tor_inet_aton(buf, &inaddr) == 0)
446 return -1; /* malformed. */
448 /* reverse the bytes */
449 inaddr.s_addr = (uint32_t)
450 (((inaddr.s_addr & 0x000000ff) << 24)
451 |((inaddr.s_addr & 0x0000ff00) << 8)
452 |((inaddr.s_addr & 0x00ff0000) >> 8)
453 |((inaddr.s_addr & 0xff000000) >> 24));
455 if (result) {
456 tor_addr_from_in(result, &inaddr);
458 return 1;
461 if (!strcasecmpend(address, ".ip6.arpa")) {
462 const char *cp;
463 int i;
464 int n0, n1;
465 struct in6_addr in6;
467 if (family == AF_INET)
468 return -1;
470 cp = address;
471 for (i = 0; i < 16; ++i) {
472 n0 = hex_decode_digit(*cp++); /* The low-order nybble appears first. */
473 if (*cp++ != '.') return -1; /* Then a dot. */
474 n1 = hex_decode_digit(*cp++); /* The high-order nybble appears first. */
475 if (*cp++ != '.') return -1; /* Then another dot. */
476 if (n0<0 || n1 < 0) /* Both nybbles must be hex. */
477 return -1;
479 /* We don't check the length of the string in here. But that's okay,
480 * since we already know that the string ends with ".ip6.arpa", and
481 * there is no way to frameshift .ip6.arpa so it fits into the pattern
482 * of hexdigit, period, hexdigit, period that we enforce above.
485 /* Assign from low-byte to high-byte. */
486 in6.s6_addr[15-i] = n0 | (n1 << 4);
488 if (strcasecmp(cp, "ip6.arpa"))
489 return -1;
491 if (result) {
492 tor_addr_from_in6(result, &in6);
494 return 1;
497 if (accept_regular) {
498 tor_addr_t tmp;
499 int r = tor_addr_parse(&tmp, address);
500 if (r < 0)
501 return 0;
502 if (r != family && family != AF_UNSPEC)
503 return -1;
505 if (result)
506 memcpy(result, &tmp, sizeof(tor_addr_t));
508 return 1;
511 return 0;
514 /** Convert <b>addr</b> to an in-addr.arpa name or a .ip6.arpa name,
515 * and store the result in the <b>outlen</b>-byte buffer at
516 * <b>out</b>. Return the number of chars written to <b>out</b>, not
517 * including the trailing \0, on success. Returns -1 on failure. */
519 tor_addr_to_PTR_name(char *out, size_t outlen,
520 const tor_addr_t *addr)
522 tor_assert(out);
523 tor_assert(addr);
525 if (addr->family == AF_INET) {
526 uint32_t a = tor_addr_to_ipv4h(addr);
528 return tor_snprintf(out, outlen, "%d.%d.%d.%d.in-addr.arpa",
529 (int)(uint8_t)((a )&0xff),
530 (int)(uint8_t)((a>>8 )&0xff),
531 (int)(uint8_t)((a>>16)&0xff),
532 (int)(uint8_t)((a>>24)&0xff));
533 } else if (addr->family == AF_INET6) {
534 int i;
535 char *cp = out;
536 const uint8_t *bytes = tor_addr_to_in6_addr8(addr);
537 if (outlen < REVERSE_LOOKUP_NAME_BUF_LEN)
538 return -1;
539 for (i = 15; i >= 0; --i) {
540 uint8_t byte = bytes[i];
541 *cp++ = "0123456789abcdef"[byte & 0x0f];
542 *cp++ = '.';
543 *cp++ = "0123456789abcdef"[byte >> 4];
544 *cp++ = '.';
546 memcpy(cp, "ip6.arpa", 9); /* 8 characters plus NUL */
547 return 32 * 2 + 8;
549 return -1;
552 /** Parse a string <b>s</b> containing an IPv4/IPv6 address, and possibly
553 * a mask and port or port range. Store the parsed address in
554 * <b>addr_out</b>, a mask (if any) in <b>mask_out</b>, and port(s) (if any)
555 * in <b>port_min_out</b> and <b>port_max_out</b>.
557 * The syntax is:
558 * Address OptMask OptPortRange
559 * Address ::= IPv4Address / "[" IPv6Address "]" / "*"
560 * OptMask ::= "/" Integer /
561 * OptPortRange ::= ":*" / ":" Integer / ":" Integer "-" Integer /
563 * - If mask, minport, or maxport are NULL, we do not want these
564 * options to be set; treat them as an error if present.
565 * - If the string has no mask, the mask is set to /32 (IPv4) or /128 (IPv6).
566 * - If the string has one port, it is placed in both min and max port
567 * variables.
568 * - If the string has no port(s), port_(min|max)_out are set to 1 and 65535.
570 * Return an address family on success, or -1 if an invalid address string is
571 * provided.
573 * If 'flags & TAPMP_EXTENDED_STAR' is false, then the wildcard address '*'
574 * yield an IPv4 wildcard.
576 * If 'flags & TAPMP_EXTENDED_STAR' is true, then the wildcard address '*'
577 * yields an AF_UNSPEC wildcard address, and the following change is made
578 * in the grammar above:
579 * Address ::= IPv4Address / "[" IPv6Address "]" / "*" / "*4" / "*6"
580 * with the new "*4" and "*6" productions creating a wildcard to match
581 * IPv4 or IPv6 addresses.
585 tor_addr_parse_mask_ports(const char *s,
586 unsigned flags,
587 tor_addr_t *addr_out,
588 maskbits_t *maskbits_out,
589 uint16_t *port_min_out, uint16_t *port_max_out)
591 char *base = NULL, *address, *mask = NULL, *port = NULL, *rbracket = NULL;
592 char *endptr;
593 int any_flag=0, v4map=0;
594 sa_family_t family;
595 struct in6_addr in6_tmp;
596 struct in_addr in_tmp;
598 tor_assert(s);
599 tor_assert(addr_out);
601 /** Longest possible length for an address, mask, and port-range combination.
602 * Includes IP, [], /mask, :, ports */
603 #define MAX_ADDRESS_LENGTH (TOR_ADDR_BUF_LEN+2+(1+INET_NTOA_BUF_LEN)+12+1)
605 if (strlen(s) > MAX_ADDRESS_LENGTH) {
606 log_warn(LD_GENERAL, "Impossibly long IP %s; rejecting", escaped(s));
607 goto err;
609 base = tor_strdup(s);
611 /* Break 'base' into separate strings. */
612 address = base;
613 if (*address == '[') { /* Probably IPv6 */
614 address++;
615 rbracket = strchr(address, ']');
616 if (!rbracket) {
617 log_warn(LD_GENERAL,
618 "No closing IPv6 bracket in address pattern; rejecting.");
619 goto err;
622 mask = strchr((rbracket?rbracket:address),'/');
623 port = strchr((mask?mask:(rbracket?rbracket:address)), ':');
624 if (port)
625 *port++ = '\0';
626 if (mask)
627 *mask++ = '\0';
628 if (rbracket)
629 *rbracket = '\0';
630 if (port && mask)
631 tor_assert(port > mask);
632 if (mask && rbracket)
633 tor_assert(mask > rbracket);
635 /* Now "address" is the a.b.c.d|'*'|abcd::1 part...
636 * "mask" is the Mask|Maskbits part...
637 * and "port" is the *|port|min-max part.
640 /* Process the address portion */
641 memset(addr_out, 0, sizeof(tor_addr_t));
643 if (!strcmp(address, "*")) {
644 if (flags & TAPMP_EXTENDED_STAR) {
645 family = AF_UNSPEC;
646 tor_addr_make_unspec(addr_out);
647 } else {
648 family = AF_INET;
649 tor_addr_from_ipv4h(addr_out, 0);
651 any_flag = 1;
652 } else if (!strcmp(address, "*4") && (flags & TAPMP_EXTENDED_STAR)) {
653 family = AF_INET;
654 tor_addr_from_ipv4h(addr_out, 0);
655 any_flag = 1;
656 } else if (!strcmp(address, "*6") && (flags & TAPMP_EXTENDED_STAR)) {
657 static char nil_bytes[16] = { 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };
658 family = AF_INET6;
659 tor_addr_from_ipv6_bytes(addr_out, nil_bytes);
660 any_flag = 1;
661 } else if (tor_inet_pton(AF_INET6, address, &in6_tmp) > 0) {
662 family = AF_INET6;
663 tor_addr_from_in6(addr_out, &in6_tmp);
664 } else if (tor_inet_pton(AF_INET, address, &in_tmp) > 0) {
665 family = AF_INET;
666 tor_addr_from_in(addr_out, &in_tmp);
667 } else {
668 log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
669 escaped(address));
670 goto err;
673 v4map = tor_addr_is_v4(addr_out);
675 /* Parse mask */
676 if (maskbits_out) {
677 int bits = 0;
678 struct in_addr v4mask;
680 if (mask) { /* the caller (tried to) specify a mask */
681 bits = (int) strtol(mask, &endptr, 10);
682 if (!*endptr) { /* strtol converted everything, so it was an integer */
683 if ((bits<0 || bits>128) ||
684 (family == AF_INET && bits > 32)) {
685 log_warn(LD_GENERAL,
686 "Bad number of mask bits (%d) on address range; rejecting.",
687 bits);
688 goto err;
690 } else { /* mask might still be an address-style mask */
691 if (tor_inet_pton(AF_INET, mask, &v4mask) > 0) {
692 bits = addr_mask_get_bits(ntohl(v4mask.s_addr));
693 if (bits < 0) {
694 log_warn(LD_GENERAL,
695 "IPv4-style mask %s is not a prefix address; rejecting.",
696 escaped(mask));
697 goto err;
699 } else { /* Not IPv4; we don't do address-style IPv6 masks. */
700 log_warn(LD_GENERAL,
701 "Malformed mask on address range %s; rejecting.",
702 escaped(s));
703 goto err;
706 if (family == AF_INET6 && v4map) {
707 if (bits > 32 && bits < 96) { /* Crazy */
708 log_warn(LD_GENERAL,
709 "Bad mask bits %d for V4-mapped V6 address; rejecting.",
710 bits);
711 goto err;
713 /* XXXX_IP6 is this really what we want? */
714 bits = 96 + bits%32; /* map v4-mapped masks onto 96-128 bits */
716 } else { /* pick an appropriate mask, as none was given */
717 if (any_flag)
718 bits = 0; /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */
719 else if (tor_addr_family(addr_out) == AF_INET)
720 bits = 32;
721 else if (tor_addr_family(addr_out) == AF_INET6)
722 bits = 128;
724 *maskbits_out = (maskbits_t) bits;
725 } else {
726 if (mask) {
727 log_warn(LD_GENERAL,
728 "Unexpected mask in address %s; rejecting", escaped(s));
729 goto err;
733 /* Parse port(s) */
734 if (port_min_out) {
735 uint16_t port2;
736 if (!port_max_out) /* caller specified one port; fake the second one */
737 port_max_out = &port2;
739 if (parse_port_range(port, port_min_out, port_max_out) < 0) {
740 goto err;
741 } else if ((*port_min_out != *port_max_out) && port_max_out == &port2) {
742 log_warn(LD_GENERAL,
743 "Wanted one port from address range, but there are two.");
745 port_max_out = NULL; /* caller specified one port, so set this back */
746 goto err;
748 } else {
749 if (port) {
750 log_warn(LD_GENERAL,
751 "Unexpected ports in address %s; rejecting", escaped(s));
752 goto err;
756 tor_free(base);
757 return tor_addr_family(addr_out);
758 err:
759 tor_free(base);
760 return -1;
763 /** Determine whether an address is IPv4, either native or IPv4-mapped IPv6.
764 * Note that this is about representation only, as any decent stack will
765 * reject IPv4-mapped addresses received on the wire (and won't use them
766 * on the wire either).
769 tor_addr_is_v4(const tor_addr_t *addr)
771 tor_assert(addr);
773 if (tor_addr_family(addr) == AF_INET)
774 return 1;
776 if (tor_addr_family(addr) == AF_INET6) {
777 /* First two don't need to be ordered */
778 uint32_t *a32 = tor_addr_to_in6_addr32(addr);
779 if (a32[0] == 0 && a32[1] == 0 && ntohl(a32[2]) == 0x0000ffffu)
780 return 1;
783 return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */
786 /** Determine whether an address <b>addr</b> is null, either all zeroes or
787 * belonging to family AF_UNSPEC.
790 tor_addr_is_null(const tor_addr_t *addr)
792 tor_assert(addr);
794 switch (tor_addr_family(addr)) {
795 case AF_INET6: {
796 uint32_t *a32 = tor_addr_to_in6_addr32(addr);
797 return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 0);
799 case AF_INET:
800 return (tor_addr_to_ipv4n(addr) == 0);
801 case AF_UNSPEC:
802 return 1;
803 default:
804 log_warn(LD_BUG, "Called with unknown address family %d",
805 (int)tor_addr_family(addr));
806 return 0;
808 //return 1;
811 /** Return true iff <b>addr</b> is a loopback address */
813 tor_addr_is_loopback(const tor_addr_t *addr)
815 tor_assert(addr);
816 switch (tor_addr_family(addr)) {
817 case AF_INET6: {
818 /* ::1 */
819 uint32_t *a32 = tor_addr_to_in6_addr32(addr);
820 return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 1);
822 case AF_INET:
823 /* 127.0.0.1 */
824 return (tor_addr_to_ipv4h(addr) & 0xff000000) == 0x7f000000;
825 case AF_UNSPEC:
826 return 0;
827 default:
828 tor_fragile_assert();
829 return 0;
833 /** Set <b>dest</b> to equal the IPv4 address in <b>v4addr</b> (given in
834 * network order). */
835 void
836 tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
838 tor_assert(dest);
839 memset(dest, 0, sizeof(tor_addr_t));
840 dest->family = AF_INET;
841 dest->addr.in_addr.s_addr = v4addr;
844 /** Set <b>dest</b> to equal the IPv6 address in the 16 bytes at
845 * <b>ipv6_bytes</b>. */
846 void
847 tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
849 tor_assert(dest);
850 tor_assert(ipv6_bytes);
851 memset(dest, 0, sizeof(tor_addr_t));
852 dest->family = AF_INET6;
853 memcpy(dest->addr.in6_addr.s6_addr, ipv6_bytes, 16);
856 /** Set <b>dest</b> equal to the IPv6 address in the in6_addr <b>in6</b>. */
857 void
858 tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
860 tor_addr_from_ipv6_bytes(dest, (const char*)in6->s6_addr);
863 /** Copy a tor_addr_t from <b>src</b> to <b>dest</b>.
865 void
866 tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
868 if (src == dest)
869 return;
870 tor_assert(src);
871 tor_assert(dest);
872 memcpy(dest, src, sizeof(tor_addr_t));
875 /** Given two addresses <b>addr1</b> and <b>addr2</b>, return 0 if the two
876 * addresses are equivalent under the mask mbits, less than 0 if addr1
877 * precedes addr2, and greater than 0 otherwise.
879 * Different address families (IPv4 vs IPv6) are always considered unequal if
880 * <b>how</b> is CMP_EXACT; otherwise, IPv6-mapped IPv4 addresses are
881 * considered equivalent to their IPv4 equivalents.
884 tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2,
885 tor_addr_comparison_t how)
887 return tor_addr_compare_masked(addr1, addr2, 128, how);
890 /** As tor_addr_compare(), but only looks at the first <b>mask</b> bits of
891 * the address.
893 * Reduce over-specific masks (>128 for ipv6, >32 for ipv4) to 128 or 32.
895 * The mask is interpreted relative to <b>addr1</b>, so that if a is
896 * \::ffff:1.2.3.4, and b is 3.4.5.6,
897 * tor_addr_compare_masked(a,b,100,CMP_SEMANTIC) is the same as
898 * -tor_addr_compare_masked(b,a,4,CMP_SEMANTIC).
900 * We guarantee that the ordering from tor_addr_compare_masked is a total
901 * order on addresses, but not that it is any particular order, or that it
902 * will be the same from one version to the next.
905 tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2,
906 maskbits_t mbits, tor_addr_comparison_t how)
908 /** Helper: Evaluates to -1 if a is less than b, 0 if a equals b, or 1 if a
909 * is greater than b. May evaluate a and b more than once. */
910 #define TRISTATE(a,b) (((a)<(b))?-1: (((a)==(b))?0:1))
911 sa_family_t family1, family2, v_family1, v_family2;
913 tor_assert(addr1 && addr2);
915 v_family1 = family1 = tor_addr_family(addr1);
916 v_family2 = family2 = tor_addr_family(addr2);
918 if (family1==family2) {
919 /* When the families are the same, there's only one way to do the
920 * comparison: exactly. */
921 int r;
922 switch (family1) {
923 case AF_UNSPEC:
924 return 0; /* All unspecified addresses are equal */
925 case AF_INET: {
926 uint32_t a1 = tor_addr_to_ipv4h(addr1);
927 uint32_t a2 = tor_addr_to_ipv4h(addr2);
928 if (mbits <= 0)
929 return 0;
930 if (mbits > 32)
931 mbits = 32;
932 a1 >>= (32-mbits);
933 a2 >>= (32-mbits);
934 r = TRISTATE(a1, a2);
935 return r;
937 case AF_INET6: {
938 const uint8_t *a1 = tor_addr_to_in6_addr8(addr1);
939 const uint8_t *a2 = tor_addr_to_in6_addr8(addr2);
940 const int bytes = mbits >> 3;
941 const int leftover_bits = mbits & 7;
942 if (bytes && (r = tor_memcmp(a1, a2, bytes))) {
943 return r;
944 } else if (leftover_bits) {
945 uint8_t b1 = a1[bytes] >> (8-leftover_bits);
946 uint8_t b2 = a2[bytes] >> (8-leftover_bits);
947 return TRISTATE(b1, b2);
948 } else {
949 return 0;
952 default:
953 tor_fragile_assert();
954 return 0;
956 } else if (how == CMP_EXACT) {
957 /* Unequal families and an exact comparison? Stop now! */
958 return TRISTATE(family1, family2);
961 if (mbits == 0)
962 return 0;
964 if (family1 == AF_INET6 && tor_addr_is_v4(addr1))
965 v_family1 = AF_INET;
966 if (family2 == AF_INET6 && tor_addr_is_v4(addr2))
967 v_family2 = AF_INET;
968 if (v_family1 == v_family2) {
969 /* One or both addresses are a mapped ipv4 address. */
970 uint32_t a1, a2;
971 if (family1 == AF_INET6) {
972 a1 = tor_addr_to_mapped_ipv4h(addr1);
973 if (mbits <= 96)
974 return 0;
975 mbits -= 96; /* We just decided that the first 96 bits of a1 "match". */
976 } else {
977 a1 = tor_addr_to_ipv4h(addr1);
979 if (family2 == AF_INET6) {
980 a2 = tor_addr_to_mapped_ipv4h(addr2);
981 } else {
982 a2 = tor_addr_to_ipv4h(addr2);
984 if (mbits <= 0) return 0;
985 if (mbits > 32) mbits = 32;
986 a1 >>= (32-mbits);
987 a2 >>= (32-mbits);
988 return TRISTATE(a1, a2);
989 } else {
990 /* Unequal families, and semantic comparison, and no semantic family
991 * matches. */
992 return TRISTATE(family1, family2);
996 /** Return a hash code based on the address addr */
997 unsigned int
998 tor_addr_hash(const tor_addr_t *addr)
1000 switch (tor_addr_family(addr)) {
1001 case AF_INET:
1002 return tor_addr_to_ipv4h(addr);
1003 case AF_UNSPEC:
1004 return 0x4e4d5342;
1005 case AF_INET6: {
1006 const uint32_t *u = tor_addr_to_in6_addr32(addr);
1007 return u[0] + u[1] + u[2] + u[3];
1009 default:
1010 tor_fragile_assert();
1011 return 0;
1015 /** Return a newly allocated string with a representation of <b>addr</b>. */
1016 char *
1017 tor_dup_addr(const tor_addr_t *addr)
1019 char buf[TOR_ADDR_BUF_LEN];
1020 if (tor_addr_to_str(buf, addr, sizeof(buf), 0)) {
1021 return tor_strdup(buf);
1022 } else {
1023 return tor_strdup("<unknown address type>");
1027 /** Return a string representing the address <b>addr</b>. This string
1028 * is statically allocated, and must not be freed. Each call to
1029 * <b>fmt_addr_impl</b> invalidates the last result of the function.
1030 * This function is not thread-safe. If <b>decorate</b> is set, add
1031 * brackets to IPv6 addresses.
1033 * It's better to use the wrapper macros of this function:
1034 * <b>fmt_addr()</b> and <b>fmt_and_decorate_addr()</b>.
1036 const char *
1037 fmt_addr_impl(const tor_addr_t *addr, int decorate)
1039 static char buf[TOR_ADDR_BUF_LEN];
1040 if (!addr) return "<null>";
1041 if (tor_addr_to_str(buf, addr, sizeof(buf), decorate))
1042 return buf;
1043 else
1044 return "???";
1047 /** Return a string representing the pair <b>addr</b> and <b>port</b>.
1048 * This calls fmt_and_decorate_addr internally, so IPv6 addresses will
1049 * have brackets, and the caveats of fmt_addr_impl apply.
1051 const char *
1052 fmt_addrport(const tor_addr_t *addr, uint16_t port)
1054 /* Add space for a colon and up to 5 digits. */
1055 static char buf[TOR_ADDR_BUF_LEN + 6];
1056 tor_snprintf(buf, sizeof(buf), "%s:%u", fmt_and_decorate_addr(addr), port);
1057 return buf;
1060 /** Like fmt_addr(), but takes <b>addr</b> as a host-order IPv4
1061 * addresses. Also not thread-safe, also clobbers its return buffer on
1062 * repeated calls. */
1063 const char *
1064 fmt_addr32(uint32_t addr)
1066 static char buf[INET_NTOA_BUF_LEN];
1067 struct in_addr in;
1068 in.s_addr = htonl(addr);
1069 tor_inet_ntoa(&in, buf, sizeof(buf));
1070 return buf;
1073 /** Convert the string in <b>src</b> to a tor_addr_t <b>addr</b>. The string
1074 * may be an IPv4 address, an IPv6 address, or an IPv6 address surrounded by
1075 * square brackets.
1077 * Return an address family on success, or -1 if an invalid address string is
1078 * provided. */
1080 tor_addr_parse(tor_addr_t *addr, const char *src)
1082 char *tmp = NULL; /* Holds substring if we got a dotted quad. */
1083 int result;
1084 struct in_addr in_tmp;
1085 struct in6_addr in6_tmp;
1086 tor_assert(addr && src);
1087 if (src[0] == '[' && src[1])
1088 src = tmp = tor_strndup(src+1, strlen(src)-2);
1090 if (tor_inet_pton(AF_INET6, src, &in6_tmp) > 0) {
1091 result = AF_INET6;
1092 tor_addr_from_in6(addr, &in6_tmp);
1093 } else if (tor_inet_pton(AF_INET, src, &in_tmp) > 0) {
1094 result = AF_INET;
1095 tor_addr_from_in(addr, &in_tmp);
1096 } else {
1097 result = -1;
1100 tor_free(tmp);
1101 return result;
1104 /** Parse an address or address-port combination from <b>s</b>, resolve the
1105 * address as needed, and put the result in <b>addr_out</b> and (optionally)
1106 * <b>port_out</b>. Return 0 on success, negative on failure. */
1108 tor_addr_port_lookup(const char *s, tor_addr_t *addr_out, uint16_t *port_out)
1110 const char *port;
1111 tor_addr_t addr;
1112 uint16_t portval;
1113 char *tmp = NULL;
1115 tor_assert(s);
1116 tor_assert(addr_out);
1118 s = eat_whitespace(s);
1120 if (*s == '[') {
1121 port = strstr(s, "]");
1122 if (!port)
1123 goto err;
1124 tmp = tor_strndup(s+1, port-(s+1));
1125 port = port+1;
1126 if (*port == ':')
1127 port++;
1128 else
1129 port = NULL;
1130 } else {
1131 port = strchr(s, ':');
1132 if (port)
1133 tmp = tor_strndup(s, port-s);
1134 else
1135 tmp = tor_strdup(s);
1136 if (port)
1137 ++port;
1140 if (tor_addr_lookup(tmp, AF_UNSPEC, &addr) != 0)
1141 goto err;
1142 tor_free(tmp);
1144 if (port) {
1145 portval = (int) tor_parse_long(port, 10, 1, 65535, NULL, NULL);
1146 if (!portval)
1147 goto err;
1148 } else {
1149 portval = 0;
1152 if (port_out)
1153 *port_out = portval;
1154 tor_addr_copy(addr_out, &addr);
1156 return 0;
1157 err:
1158 tor_free(tmp);
1159 return -1;
1162 #ifdef _WIN32
1163 typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)(
1164 ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
1165 #endif
1167 /** Try to ask our network interfaces what addresses they are bound to.
1168 * Return a new smartlist of tor_addr_t on success, and NULL on failure.
1169 * (An empty smartlist indicates that we successfully learned that we have no
1170 * addresses.) Log failure messages at <b>severity</b>. */
1171 static smartlist_t *
1172 get_interface_addresses_raw(int severity)
1174 #if defined(HAVE_GETIFADDRS)
1175 /* Most free Unixy systems provide getifaddrs, which gives us a linked list
1176 * of struct ifaddrs. */
1177 struct ifaddrs *ifa = NULL;
1178 const struct ifaddrs *i;
1179 smartlist_t *result;
1180 if (getifaddrs(&ifa) < 0) {
1181 log_fn(severity, LD_NET, "Unable to call getifaddrs(): %s",
1182 strerror(errno));
1183 return NULL;
1186 result = smartlist_new();
1187 for (i = ifa; i; i = i->ifa_next) {
1188 tor_addr_t tmp;
1189 if (!i->ifa_addr)
1190 continue;
1191 if (i->ifa_addr->sa_family != AF_INET &&
1192 i->ifa_addr->sa_family != AF_INET6)
1193 continue;
1194 if (tor_addr_from_sockaddr(&tmp, i->ifa_addr, NULL) < 0)
1195 continue;
1196 smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
1199 freeifaddrs(ifa);
1200 return result;
1201 #elif defined(_WIN32)
1202 /* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
1203 "GetAdaptersInfo", but that's deprecated; let's just try
1204 GetAdaptersAddresses and fall back to connect+getsockname.
1206 HANDLE lib = load_windows_system_library(TEXT("iphlpapi.dll"));
1207 smartlist_t *result = NULL;
1208 GetAdaptersAddresses_fn_t fn;
1209 ULONG size, res;
1210 IP_ADAPTER_ADDRESSES *addresses = NULL, *address;
1212 (void) severity;
1214 #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
1215 GAA_FLAG_SKIP_MULTICAST | \
1216 GAA_FLAG_SKIP_DNS_SERVER)
1218 if (!lib) {
1219 log_fn(severity, LD_NET, "Unable to load iphlpapi.dll");
1220 goto done;
1223 if (!(fn = (GetAdaptersAddresses_fn_t)
1224 GetProcAddress(lib, "GetAdaptersAddresses"))) {
1225 log_fn(severity, LD_NET, "Unable to obtain pointer to "
1226 "GetAdaptersAddresses");
1227 goto done;
1230 /* Guess how much space we need. */
1231 size = 15*1024;
1232 addresses = tor_malloc(size);
1233 res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
1234 if (res == ERROR_BUFFER_OVERFLOW) {
1235 /* we didn't guess that we needed enough space; try again */
1236 tor_free(addresses);
1237 addresses = tor_malloc(size);
1238 res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
1240 if (res != NO_ERROR) {
1241 log_fn(severity, LD_NET, "GetAdaptersAddresses failed (result: %lu)", res);
1242 goto done;
1245 result = smartlist_new();
1246 for (address = addresses; address; address = address->Next) {
1247 IP_ADAPTER_UNICAST_ADDRESS *a;
1248 for (a = address->FirstUnicastAddress; a; a = a->Next) {
1249 /* Yes, it's a linked list inside a linked list */
1250 struct sockaddr *sa = a->Address.lpSockaddr;
1251 tor_addr_t tmp;
1252 if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
1253 continue;
1254 if (tor_addr_from_sockaddr(&tmp, sa, NULL) < 0)
1255 continue;
1256 smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
1260 done:
1261 if (lib)
1262 FreeLibrary(lib);
1263 tor_free(addresses);
1264 return result;
1265 #elif defined(SIOCGIFCONF) && defined(HAVE_IOCTL)
1266 /* Some older unixy systems make us use ioctl(SIOCGIFCONF) */
1267 struct ifconf ifc;
1268 int fd, i, sz, n;
1269 smartlist_t *result = NULL;
1270 /* This interface, AFAICT, only supports AF_INET addresses */
1271 fd = socket(AF_INET, SOCK_DGRAM, 0);
1272 if (fd < 0) {
1273 tor_log(severity, LD_NET, "socket failed: %s", strerror(errno));
1274 goto done;
1276 /* Guess how much space we need. */
1277 ifc.ifc_len = sz = 15*1024;
1278 ifc.ifc_ifcu.ifcu_req = tor_malloc(sz);
1279 if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) {
1280 tor_log(severity, LD_NET, "ioctl failed: %s", strerror(errno));
1281 close(fd);
1282 goto done;
1284 close(fd);
1285 result = smartlist_new();
1286 if (ifc.ifc_len < sz)
1287 sz = ifc.ifc_len;
1288 n = sz / sizeof(struct ifreq);
1289 for (i = 0; i < n ; ++i) {
1290 struct ifreq *r = &ifc.ifc_ifcu.ifcu_req[i];
1291 struct sockaddr *sa = &r->ifr_addr;
1292 tor_addr_t tmp;
1293 if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
1294 continue; /* should be impossible */
1295 if (tor_addr_from_sockaddr(&tmp, sa, NULL) < 0)
1296 continue;
1297 smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
1299 done:
1300 tor_free(ifc.ifc_ifcu.ifcu_req);
1301 return result;
1302 #else
1303 (void) severity;
1304 return NULL;
1305 #endif
1308 /** Return true iff <b>a</b> is a multicast address. */
1309 static int
1310 tor_addr_is_multicast(const tor_addr_t *a)
1312 sa_family_t family = tor_addr_family(a);
1313 if (family == AF_INET) {
1314 uint32_t ipv4h = tor_addr_to_ipv4h(a);
1315 if ((ipv4h >> 24) == 0xe0)
1316 return 1; /* Multicast */
1317 } else if (family == AF_INET6) {
1318 const uint8_t *a32 = tor_addr_to_in6_addr8(a);
1319 if (a32[0] == 0xff)
1320 return 1;
1322 return 0;
1325 /** Set *<b>addr</b> to the IP address (if any) of whatever interface
1326 * connects to the Internet. This address should only be used in checking
1327 * whether our address has changed. Return 0 on success, -1 on failure.
1330 get_interface_address6(int severity, sa_family_t family, tor_addr_t *addr)
1332 /* XXX really, this function should yield a smartlist of addresses. */
1333 smartlist_t *addrs;
1334 int sock=-1, r=-1;
1335 struct sockaddr_storage my_addr, target_addr;
1336 socklen_t addr_len;
1337 tor_assert(addr);
1339 /* Try to do this the smart way if possible. */
1340 if ((addrs = get_interface_addresses_raw(severity))) {
1341 int rv = -1;
1342 SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a) {
1343 if (family != AF_UNSPEC && family != tor_addr_family(a))
1344 continue;
1345 if (tor_addr_is_loopback(a) ||
1346 tor_addr_is_multicast(a))
1347 continue;
1349 tor_addr_copy(addr, a);
1350 rv = 0;
1352 /* If we found a non-internal address, declare success. Otherwise,
1353 * keep looking. */
1354 if (!tor_addr_is_internal(a, 0))
1355 break;
1356 } SMARTLIST_FOREACH_END(a);
1358 SMARTLIST_FOREACH(addrs, tor_addr_t *, a, tor_free(a));
1359 smartlist_free(addrs);
1360 return rv;
1363 /* Okay, the smart way is out. */
1364 memset(addr, 0, sizeof(tor_addr_t));
1365 memset(&target_addr, 0, sizeof(target_addr));
1366 /* Don't worry: no packets are sent. We just need to use a real address
1367 * on the actual Internet. */
1368 if (family == AF_INET6) {
1369 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&target_addr;
1370 /* Use the "discard" service port */
1371 sin6->sin6_port = htons(9);
1372 sock = tor_open_socket(PF_INET6,SOCK_DGRAM,IPPROTO_UDP);
1373 addr_len = (socklen_t)sizeof(struct sockaddr_in6);
1374 sin6->sin6_family = AF_INET6;
1375 S6_ADDR16(sin6->sin6_addr)[0] = htons(0x2002); /* 2002:: */
1376 } else if (family == AF_INET) {
1377 struct sockaddr_in *sin = (struct sockaddr_in*)&target_addr;
1378 /* Use the "discard" service port */
1379 sin->sin_port = htons(9);
1380 sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
1381 addr_len = (socklen_t)sizeof(struct sockaddr_in);
1382 sin->sin_family = AF_INET;
1383 sin->sin_addr.s_addr = htonl(0x12000001); /* 18.0.0.1 */
1384 } else {
1385 return -1;
1387 if (sock < 0) {
1388 int e = tor_socket_errno(-1);
1389 log_fn(severity, LD_NET, "unable to create socket: %s",
1390 tor_socket_strerror(e));
1391 goto err;
1394 if (connect(sock,(struct sockaddr *)&target_addr, addr_len) < 0) {
1395 int e = tor_socket_errno(sock);
1396 log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e));
1397 goto err;
1400 if (getsockname(sock,(struct sockaddr*)&my_addr, &addr_len)) {
1401 int e = tor_socket_errno(sock);
1402 log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s",
1403 tor_socket_strerror(e));
1404 goto err;
1407 tor_addr_from_sockaddr(addr, (struct sockaddr*)&my_addr, NULL);
1408 r=0;
1409 err:
1410 if (sock >= 0)
1411 tor_close_socket(sock);
1412 return r;
1415 /* ======
1416 * IPv4 helpers
1417 * XXXX024 IPv6 deprecate some of these.
1420 /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
1421 * or reserved for local networks by RFC 1918.
1424 is_internal_IP(uint32_t ip, int for_listening)
1426 tor_addr_t myaddr;
1427 myaddr.family = AF_INET;
1428 myaddr.addr.in_addr.s_addr = htonl(ip);
1430 return tor_addr_is_internal(&myaddr, for_listening);
1433 /** Given an address of the form "ip:port", try to divide it into its
1434 * ip and port portions, setting *<b>address_out</b> to a newly
1435 * allocated string holding the address portion and *<b>port_out</b>
1436 * to the port.
1438 * Don't do DNS lookups and don't allow domain names in the <ip> field.
1439 * Don't accept <b>addrport</b> of the form "<ip>" or "<ip>:0".
1441 * Return 0 on success, -1 on failure. */
1443 tor_addr_port_parse(int severity, const char *addrport,
1444 tor_addr_t *address_out, uint16_t *port_out)
1446 int retval = -1;
1447 int r;
1448 char *addr_tmp = NULL;
1450 tor_assert(addrport);
1451 tor_assert(address_out);
1452 tor_assert(port_out);
1454 r = tor_addr_port_split(severity, addrport, &addr_tmp, port_out);
1455 if (r < 0)
1456 goto done;
1458 if (!*port_out)
1459 goto done;
1461 /* make sure that address_out is an IP address */
1462 if (tor_addr_parse(address_out, addr_tmp) < 0)
1463 goto done;
1465 retval = 0;
1467 done:
1468 tor_free(addr_tmp);
1469 return retval;
1472 /** Given an address of the form "host[:port]", try to divide it into its host
1473 * ane port portions, setting *<b>address_out</b> to a newly allocated string
1474 * holding the address portion and *<b>port_out</b> to the port (or 0 if no
1475 * port is given). Return 0 on success, -1 on failure. */
1477 tor_addr_port_split(int severity, const char *addrport,
1478 char **address_out, uint16_t *port_out)
1480 tor_assert(addrport);
1481 tor_assert(address_out);
1482 tor_assert(port_out);
1483 return addr_port_lookup(severity, addrport, address_out, NULL, port_out);
1486 /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
1487 * <b>address</b> is provided, set *<b>address</b> to a copy of the
1488 * host portion of the string. If <b>addr</b> is provided, try to
1489 * resolve the host portion of the string and store it into
1490 * *<b>addr</b> (in host byte order). If <b>port_out</b> is provided,
1491 * store the port number into *<b>port_out</b>, or 0 if no port is given.
1492 * If <b>port_out</b> is NULL, then there must be no port number in
1493 * <b>addrport</b>.
1494 * Return 0 on success, -1 on failure.
1497 addr_port_lookup(int severity, const char *addrport, char **address,
1498 uint32_t *addr, uint16_t *port_out)
1500 const char *colon;
1501 char *address_ = NULL;
1502 int port_;
1503 int ok = 1;
1505 tor_assert(addrport);
1507 colon = strrchr(addrport, ':');
1508 if (colon) {
1509 address_ = tor_strndup(addrport, colon-addrport);
1510 port_ = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
1511 if (!port_) {
1512 log_fn(severity, LD_GENERAL, "Port %s out of range", escaped(colon+1));
1513 ok = 0;
1515 if (!port_out) {
1516 char *esc_addrport = esc_for_log(addrport);
1517 log_fn(severity, LD_GENERAL,
1518 "Port %s given on %s when not required",
1519 escaped(colon+1), esc_addrport);
1520 tor_free(esc_addrport);
1521 ok = 0;
1523 } else {
1524 address_ = tor_strdup(addrport);
1525 port_ = 0;
1528 if (addr) {
1529 /* There's an addr pointer, so we need to resolve the hostname. */
1530 if (tor_lookup_hostname(address_,addr)) {
1531 log_fn(severity, LD_NET, "Couldn't look up %s", escaped(address_));
1532 ok = 0;
1533 *addr = 0;
1537 if (address && ok) {
1538 *address = address_;
1539 } else {
1540 if (address)
1541 *address = NULL;
1542 tor_free(address_);
1544 if (port_out)
1545 *port_out = ok ? ((uint16_t) port_) : 0;
1547 return ok ? 0 : -1;
1550 /** If <b>mask</b> is an address mask for a bit-prefix, return the number of
1551 * bits. Otherwise, return -1. */
1553 addr_mask_get_bits(uint32_t mask)
1555 int i;
1556 if (mask == 0)
1557 return 0;
1558 if (mask == 0xFFFFFFFFu)
1559 return 32;
1560 for (i=0; i<=32; ++i) {
1561 if (mask == (uint32_t) ~((1u<<(32-i))-1)) {
1562 return i;
1565 return -1;
1568 /** Parse a string <b>s</b> in the format of (*|port(-maxport)?)?, setting the
1569 * various *out pointers as appropriate. Return 0 on success, -1 on failure.
1572 parse_port_range(const char *port, uint16_t *port_min_out,
1573 uint16_t *port_max_out)
1575 int port_min, port_max, ok;
1576 tor_assert(port_min_out);
1577 tor_assert(port_max_out);
1579 if (!port || *port == '\0' || strcmp(port, "*") == 0) {
1580 port_min = 1;
1581 port_max = 65535;
1582 } else {
1583 char *endptr = NULL;
1584 port_min = (int)tor_parse_long(port, 10, 0, 65535, &ok, &endptr);
1585 if (!ok) {
1586 log_warn(LD_GENERAL,
1587 "Malformed port %s on address range; rejecting.",
1588 escaped(port));
1589 return -1;
1590 } else if (endptr && *endptr == '-') {
1591 port = endptr+1;
1592 endptr = NULL;
1593 port_max = (int)tor_parse_long(port, 10, 1, 65535, &ok, &endptr);
1594 if (!ok) {
1595 log_warn(LD_GENERAL,
1596 "Malformed port %s on address range; rejecting.",
1597 escaped(port));
1598 return -1;
1600 } else {
1601 port_max = port_min;
1603 if (port_min > port_max) {
1604 log_warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
1605 return -1;
1609 if (port_min < 1)
1610 port_min = 1;
1611 if (port_max > 65535)
1612 port_max = 65535;
1614 *port_min_out = (uint16_t) port_min;
1615 *port_max_out = (uint16_t) port_max;
1617 return 0;
1620 /** Given an IPv4 in_addr struct *<b>in</b> (in network order, as usual),
1621 * write it as a string into the <b>buf_len</b>-byte buffer in
1622 * <b>buf</b>.
1625 tor_inet_ntoa(const struct in_addr *in, char *buf, size_t buf_len)
1627 uint32_t a = ntohl(in->s_addr);
1628 return tor_snprintf(buf, buf_len, "%d.%d.%d.%d",
1629 (int)(uint8_t)((a>>24)&0xff),
1630 (int)(uint8_t)((a>>16)&0xff),
1631 (int)(uint8_t)((a>>8 )&0xff),
1632 (int)(uint8_t)((a )&0xff));
1635 /** Given a host-order <b>addr</b>, call tor_inet_ntop() on it
1636 * and return a strdup of the resulting address.
1638 char *
1639 tor_dup_ip(uint32_t addr)
1641 char buf[TOR_ADDR_BUF_LEN];
1642 struct in_addr in;
1644 in.s_addr = htonl(addr);
1645 tor_inet_ntop(AF_INET, &in, buf, sizeof(buf));
1646 return tor_strdup(buf);
1650 * Set *<b>addr</b> to the host-order IPv4 address (if any) of whatever
1651 * interface connects to the Internet. This address should only be used in
1652 * checking whether our address has changed. Return 0 on success, -1 on
1653 * failure.
1656 get_interface_address(int severity, uint32_t *addr)
1658 tor_addr_t local_addr;
1659 int r;
1661 r = get_interface_address6(severity, AF_INET, &local_addr);
1662 if (r>=0)
1663 *addr = tor_addr_to_ipv4h(&local_addr);
1664 return r;
1667 /** Return true if we can tell that <b>name</b> is a canonical name for the
1668 * loopback address. */
1670 tor_addr_hostname_is_local(const char *name)
1672 return !strcasecmp(name, "localhost") ||
1673 !strcasecmp(name, "local") ||
1674 !strcasecmpend(name, ".local");
1677 /** Return a newly allocated tor_addr_port_t with <b>addr</b> and
1678 <b>port</b> filled in. */
1679 tor_addr_port_t *
1680 tor_addr_port_new(const tor_addr_t *addr, uint16_t port)
1682 tor_addr_port_t *ap = tor_malloc_zero(sizeof(tor_addr_port_t));
1683 if (addr)
1684 tor_addr_copy(&ap->addr, addr);
1685 ap->port = port;
1686 return ap;