1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2008, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 const char address_c_id
[] =
11 * \brief Functions to use and manipulate the tor_addr_t structure.
25 #ifdef HAVE_SYS_TIME_H
34 #ifdef HAVE_NETINET_IN_H
35 #include <netinet/in.h>
37 #ifdef HAVE_ARPA_INET_H
38 #include <arpa/inet.h>
40 #ifdef HAVE_SYS_SOCKET_H
41 #include <sys/socket.h>
46 #ifdef HAVE_SYS_PARAM_H
47 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
55 /** Convert the tor_addr_t in <b>a</b>, with port in <b>port</b>, into a
56 * socklen object in *<b>sa_out</b> of object size <b>len</b>. If not enough
57 * room is free, or on error, return -1. Else return the length of the
60 tor_addr_to_sockaddr(const tor_addr_t
*a
,
62 struct sockaddr
*sa_out
,
65 if (a
->family
== AF_INET
) {
66 struct sockaddr_in
*sin
;
67 if (len
< (int)sizeof(struct sockaddr_in
))
69 sin
= (struct sockaddr_in
*)sa_out
;
70 sin
->sin_family
= AF_INET
;
71 sin
->sin_port
= htons(port
);
72 sin
->sin_addr
.s_addr
= tor_addr_to_ipv4n(a
);
73 return sizeof(struct sockaddr_in
);
74 } else if (a
->family
== AF_INET6
) {
75 struct sockaddr_in6
*sin6
;
76 if (len
< (int)sizeof(struct sockaddr_in6
))
78 sin6
= (struct sockaddr_in6
*)sa_out
;
79 memset(sin6
, 0, sizeof(struct sockaddr_in6
));
80 sin6
->sin6_family
= AF_INET6
;
81 sin6
->sin6_port
= htons(port
);
82 memcpy(&sin6
->sin6_addr
, &a
->addr
.in6_addr
, sizeof(struct in6_addr
));
83 return sizeof(struct sockaddr_in6
);
89 /** Set the tor_addr_t in <b>a</b> to contain the socket address contained in
92 tor_addr_from_sockaddr(tor_addr_t
*a
, const struct sockaddr
*sa
,
97 memset(a
, 0, sizeof(tor_addr_t
));
98 if (sa
->sa_family
== AF_INET
) {
99 struct sockaddr_in
*sin
= (struct sockaddr_in
*) sa
;
101 a
->addr
.in_addr
.s_addr
= sin
->sin_addr
.s_addr
;
103 *port_out
= ntohs(sin
->sin_port
);
104 } else if (sa
->sa_family
== AF_INET6
) {
105 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*) sa
;
106 a
->family
= AF_INET6
;
107 memcpy(&a
->addr
.in6_addr
, &sin6
->sin6_addr
, sizeof(struct in6_addr
));
109 *port_out
= ntohs(sin6
->sin6_port
);
111 a
->family
= AF_UNSPEC
;
117 /** Set address <b>a</b> to the unspecified address. This address belongs to
120 tor_addr_make_unspec(tor_addr_t
*a
)
122 memset(a
, 0, sizeof(*a
));
123 a
->family
= AF_UNSPEC
;
126 /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
127 * *<b>addr</b> to the proper IP address and family. The <b>family</b>
128 * argument (which must be AF_INET, AF_INET6, or AF_UNSPEC) declares a
129 * <i>preferred</i> family, though another one may be returned if only one
130 * family is implemented for this address.
132 * Return 0 on success, -1 on failure; 1 on transient failure.
135 tor_addr_lookup(const char *name
, uint16_t family
, tor_addr_t
*addr
)
137 /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
140 struct in_addr iaddr
;
141 struct in6_addr iaddr6
;
144 tor_assert(family
== AF_INET
|| family
== AF_INET6
|| family
== AF_UNSPEC
);
145 memset(addr
, 0, sizeof(addr
)); /* Clear the extraneous fields. */
147 /* Empty address is an error. */
149 } else if (tor_inet_pton(AF_INET
, name
, &iaddr
)) {
150 /* It's an IPv4 IP. */
151 if (family
== AF_INET6
)
153 addr
->family
= AF_INET
;
154 memcpy(&addr
->addr
.in_addr
, &iaddr
, sizeof(struct in_addr
));
156 } else if (tor_inet_pton(AF_INET6
, name
, &iaddr6
)) {
157 if (family
== AF_INET
)
159 addr
->family
= AF_INET6
;
160 memcpy(&addr
->addr
.in6_addr
, &iaddr6
, sizeof(struct in6_addr
));
163 #ifdef HAVE_GETADDRINFO
165 struct addrinfo
*res
=NULL
, *res_p
;
166 struct addrinfo
*best
=NULL
;
167 struct addrinfo hints
;
169 memset(&hints
, 0, sizeof(hints
));
170 hints
.ai_family
= family
;
171 hints
.ai_socktype
= SOCK_STREAM
;
172 err
= getaddrinfo(name
, NULL
, &hints
, &res
);
175 for (res_p
= res
; res_p
; res_p
= res_p
->ai_next
) {
176 if (family
== AF_UNSPEC
) {
177 if (res_p
->ai_family
== AF_INET
) {
180 } else if (res_p
->ai_family
== AF_INET6
&& !best
) {
183 } else if (family
== res_p
->ai_family
) {
190 if (best
->ai_family
== AF_INET
) {
191 addr
->family
= AF_INET
;
192 memcpy(&addr
->addr
.in_addr
,
193 &((struct sockaddr_in
*)best
->ai_addr
)->sin_addr
,
194 sizeof(struct in_addr
));
196 } else if (best
->ai_family
== AF_INET6
) {
197 addr
->family
= AF_INET6
;
198 memcpy(&addr
->addr
.in6_addr
,
199 &((struct sockaddr_in6
*)best
->ai_addr
)->sin6_addr
,
200 sizeof(struct in6_addr
));
206 return (err
== EAI_AGAIN
) ? 1 : -1;
210 #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
212 struct hostent hostent
;
214 r
= gethostbyname_r(name
, &hostent
, buf
, sizeof(buf
), &ent
, &err
);
215 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
217 struct hostent hostent
;
218 ent
= gethostbyname_r(name
, &hostent
, buf
, sizeof(buf
), &err
);
219 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
220 struct hostent_data data
;
222 memset(&data
, 0, sizeof(data
));
223 err
= gethostbyname_r(name
, &hent
, &data
);
224 ent
= err
? NULL
: &hent
;
226 ent
= gethostbyname(name
);
228 err
= WSAGetLastError();
232 #endif /* endif HAVE_GETHOSTBYNAME_R_6_ARG. */
234 addr
->family
= ent
->h_addrtype
;
235 if (ent
->h_addrtype
== AF_INET
) {
236 memcpy(&addr
->addr
.in_addr
, ent
->h_addr
, sizeof(struct in_addr
));
237 } else if (ent
->h_addrtype
== AF_INET6
) {
238 memcpy(&addr
->addr
.in6_addr
, ent
->h_addr
, sizeof(struct in6_addr
));
240 tor_assert(0); /* gethostbyname() returned a bizarre addrtype */
245 return (err
== WSATRY_AGAIN
) ? 1 : -1;
247 return (err
== TRY_AGAIN
) ? 1 : -1;
253 /** Return true iff <b>ip</b> is an IP reserved to localhost or local networks
254 * in RFC1918 or RFC4193 or RFC4291. (fec0::/10, deprecated by RFC3879, is
255 * also treated as internal for now.)
258 tor_addr_is_internal(const tor_addr_t
*addr
, int for_listening
)
262 sa_family_t v_family
;
263 v_family
= tor_addr_family(addr
);
265 if (v_family
== AF_INET
) {
266 iph4
= tor_addr_to_ipv4h(addr
);
267 } else if (v_family
== AF_INET6
) {
268 if (tor_addr_is_v4(addr
)) { /* v4-mapped */
270 iph4
= ntohl(tor_addr_to_in6_addr32(addr
)[3]);
274 if (v_family
== AF_INET6
) {
275 const uint32_t *a32
= tor_addr_to_in6_addr32(addr
);
276 iph6
[0] = ntohl(a32
[0]);
277 iph6
[1] = ntohl(a32
[1]);
278 iph6
[2] = ntohl(a32
[2]);
279 iph6
[3] = ntohl(a32
[3]);
280 if (for_listening
&& !iph6
[0] && !iph6
[1] && !iph6
[2] && !iph6
[3]) /* :: */
283 if (((iph6
[0] & 0xfe000000) == 0xfc000000) || /* fc00/7 - RFC4193 */
284 ((iph6
[0] & 0xffc00000) == 0xfe800000) || /* fe80/10 - RFC4291 */
285 ((iph6
[0] & 0xffc00000) == 0xfec00000)) /* fec0/10 D- RFC3879 */
288 if (!iph6
[0] && !iph6
[1] && !iph6
[2] &&
289 ((iph6
[3] & 0xfffffffe) == 0x00000000)) /* ::/127 */
293 } else if (v_family
== AF_INET
) {
294 if (for_listening
&& !iph4
) /* special case for binding to 0.0.0.0 */
296 if (((iph4
& 0xff000000) == 0x0a000000) || /* 10/8 */
297 ((iph4
& 0xff000000) == 0x00000000) || /* 0/8 */
298 ((iph4
& 0xff000000) == 0x7f000000) || /* 127/8 */
299 ((iph4
& 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
300 ((iph4
& 0xfff00000) == 0xac100000) || /* 172.16/12 */
301 ((iph4
& 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
306 /* unknown address family... assume it's not safe for external use */
307 /* rather than tor_assert(0) */
308 log_warn(LD_BUG
, "tor_addr_is_internal() called with a non-IP address.");
312 /** Convert a tor_addr_t <b>addr</b> into a string, and store it in
313 * <b>dest</b> of size <b>len</b>. Returns a pointer to dest on success,
314 * or NULL on failure. If <b>decorate</b>, surround IPv6 addresses with
318 tor_addr_to_str(char *dest
, const tor_addr_t
*addr
, int len
, int decorate
)
321 tor_assert(addr
&& dest
);
323 switch (tor_addr_family(addr
)) {
327 ptr
= tor_inet_ntop(AF_INET
, &addr
->addr
.in_addr
, dest
, len
);
331 ptr
= tor_inet_ntop(AF_INET6
, &addr
->addr
.in6_addr
, dest
+1, len
-2);
333 ptr
= tor_inet_ntop(AF_INET6
, &addr
->addr
.in6_addr
, dest
, len
);
334 if (ptr
&& decorate
) {
336 memcpy(dest
+strlen(dest
), "]", 2);
337 tor_assert(ptr
== dest
+1);
347 /** Parse an .in-addr.arpa or .ip6.arpa address from <b>address</b>. Return 0
348 * if this is not an .in-addr.arpa address or an .ip6.arpa address. Return -1
349 * if this is an ill-formed .in-addr.arpa address or an .ip6.arpa address.
350 * Also return -1 if <b>family</b> is not AF_UNSPEC, and the parsed address
351 * family does not match <b>family</b>. On success, return 1, and store the
352 * result, if any, into <b>result</b>, if provided.
354 * If <b>accept_regular</b> is set and the address is in neither recognized
355 * reverse lookup hostname format, try parsing the address as a regular
356 * IPv4 or IPv6 address too.
359 tor_addr_parse_reverse_lookup_name(tor_addr_t
*result
, const char *address
,
360 int family
, int accept_regular
)
362 if (!strcasecmpend(address
, ".in-addr.arpa")) {
363 /* We have an in-addr.arpa address. */
364 char buf
[INET_NTOA_BUF_LEN
];
366 struct in_addr inaddr
;
367 if (family
== AF_INET6
)
370 len
= strlen(address
) - strlen(".in-addr.arpa");
371 if (len
>= INET_NTOA_BUF_LEN
)
372 return -1; /* Too long. */
374 memcpy(buf
, address
, len
);
376 if (tor_inet_aton(buf
, &inaddr
) == 0)
377 return -1; /* malformed. */
379 /* reverse the bytes */
380 inaddr
.s_addr
= (((inaddr
.s_addr
& 0x000000fful
) << 24)
381 |((inaddr
.s_addr
& 0x0000ff00ul
) << 8)
382 |((inaddr
.s_addr
& 0x00ff0000ul
) >> 8)
383 |((inaddr
.s_addr
& 0xff000000ul
) >> 24));
386 memset(result
, 0, sizeof(tor_addr_t
));
387 result
->family
= AF_INET
;
388 result
->addr
.in_addr
.s_addr
= inaddr
.s_addr
;
393 if (!strcasecmpend(address
, ".ip6.arpa")) {
399 if (family
== AF_INET
)
403 for (i
= 0; i
< 16; ++i
) {
404 n0
= hex_decode_digit(*cp
++); /* The low-order nybble appears first. */
405 if (*cp
++ != '.') return -1; /* Then a dot. */
406 n1
= hex_decode_digit(*cp
++); /* The high-order nybble appears first. */
407 if (*cp
++ != '.') return -1; /* Then another dot. */
408 if (n0
<0 || n1
< 0) /* Both nybbles must be hex. */
411 /* We don't check the length of the string in here. But that's okay,
412 * since we already know that the string ends with ".ip6.arpa", and
413 * there is no way to frameshift .ip6.arpa so it fits into the pattern
414 * of hexdigit, period, hexdigit, period that we enforce above.
417 /* Assign from low-byte to high-byte. */
418 in6
.s6_addr
[15-i
] = n0
| (n1
<< 4);
420 if (strcasecmp(cp
, "ip6.arpa"))
424 result
->family
= AF_INET6
;
425 memcpy(&result
->addr
.in6_addr
, &in6
, sizeof(in6
));
430 if (accept_regular
) {
432 int r
= tor_addr_from_str(&tmp
, address
);
435 if (r
!= family
&& family
!= AF_UNSPEC
)
439 memcpy(result
, &tmp
, sizeof(tor_addr_t
));
447 /** Convert <b>addr</b> to an in-addr.arpa name or a .ip6.arpa name, and store
448 * the result in the <b>outlen</b>-byte buffer at <b>out</b>. Return 0 on
449 * success, -1 on failure. */
451 tor_addr_to_reverse_lookup_name(char *out
, size_t outlen
,
452 const tor_addr_t
*addr
)
454 if (addr
->family
== AF_INET
) {
455 uint32_t a
= tor_addr_to_ipv4h(addr
);
457 return tor_snprintf(out
, outlen
, "%d.%d.%d.%d.in-addr.arpa",
458 (int)(uint8_t)((a
)&0xff),
459 (int)(uint8_t)((a
>>8 )&0xff),
460 (int)(uint8_t)((a
>>16)&0xff),
461 (int)(uint8_t)((a
>>24)&0xff));
462 } else if (addr
->family
== AF_INET6
) {
465 if (outlen
< REVERSE_LOOKUP_NAME_BUF_LEN
)
467 for (i
= 15; i
>= 0; --i
) {
468 uint8_t byte
= addr
->addr
.in6_addr
.s6_addr
[i
];
469 *cp
++ = "0123456789abcdef"[byte
& 0x0f];
471 *cp
++ = "0123456789abcdef"[byte
>> 4];
474 memcpy(cp
, "ip6.arpa", 9); /* 8 characters plus nul */
480 /** Parse a string <b>s</b> containing an IPv4/IPv6 address, and possibly
481 * a mask and port or port range. Store the parsed address in
482 * <b>addr_out</b>, a mask (if any) in <b>mask_out</b>, and port(s) (if any)
483 * in <b>port_min_out</b> and <b>port_max_out</b>.
486 * Address OptMask OptPortRange
487 * Address ::= IPv4Address / "[" IPv6Address "]" / "*"
488 * OptMask ::= "/" Integer /
489 * OptPortRange ::= ":*" / ":" Integer / ":" Integer "-" Integer /
491 * - If mask, minport, or maxport are NULL, we do not want these
492 * options to be set; treat them as an error if present.
493 * - If the string has no mask, the mask is set to /32 (IPv4) or /128 (IPv6).
494 * - If the string has one port, it is placed in both min and max port
496 * - If the string has no port(s), port_(min|max)_out are set to 1 and 65535.
498 * Return an address family on success, or -1 if an invalid address string is
502 tor_addr_parse_mask_ports(const char *s
, tor_addr_t
*addr_out
,
503 maskbits_t
*maskbits_out
,
504 uint16_t *port_min_out
, uint16_t *port_max_out
)
506 char *base
= NULL
, *address
, *mask
= NULL
, *port
= NULL
, *rbracket
= NULL
;
508 int any_flag
=0, v4map
=0;
511 tor_assert(addr_out
);
513 /* IP, [], /mask, ports */
514 #define MAX_ADDRESS_LENGTH (TOR_ADDR_BUF_LEN+2+(1+INET_NTOA_BUF_LEN)+12+1)
516 if (strlen(s
) > MAX_ADDRESS_LENGTH
) {
517 log_warn(LD_GENERAL
, "Impossibly long IP %s; rejecting", escaped(s
));
520 base
= tor_strdup(s
);
522 /* Break 'base' into separate strings. */
524 if (*address
== '[') { /* Probably IPv6 */
526 rbracket
= strchr(address
, ']');
529 "No closing IPv6 bracket in address pattern; rejecting.");
533 mask
= strchr((rbracket
?rbracket
:address
),'/');
534 port
= strchr((mask
?mask
:(rbracket
?rbracket
:address
)), ':');
542 tor_assert(port
> mask
);
543 if (mask
&& rbracket
)
544 tor_assert(mask
> rbracket
);
546 /* Now "address" is the a.b.c.d|'*'|abcd::1 part...
547 * "mask" is the Mask|Maskbits part...
548 * and "port" is the *|port|min-max part.
551 /* Process the address portion */
552 memset(addr_out
, 0, sizeof(tor_addr_t
));
554 if (!strcmp(address
, "*")) {
555 addr_out
->family
= AF_INET
; /* AF_UNSPEC ???? XXXX_IP6 */
557 } else if (tor_inet_pton(AF_INET6
, address
, &addr_out
->addr
.in6_addr
) > 0) {
558 addr_out
->family
= AF_INET6
;
559 } else if (tor_inet_pton(AF_INET
, address
, &addr_out
->addr
.in_addr
) > 0) {
560 addr_out
->family
= AF_INET
;
562 log_warn(LD_GENERAL
, "Malformed IP %s in address pattern; rejecting.",
567 v4map
= tor_addr_is_v4(addr_out
);
571 if (v_family == AF_INET) {
573 IN_ADDR6(addr_out).s6_addr32[3] = IN6_ADDRESS(addr_out).s_addr;
574 memset(&IN6_ADDRESS(addr_out), 0, 10);
575 IN_ADDR6(addr_out).s6_addr16[5] = 0xffff;
578 if (v_family == AF_INET6 && v4map) {
580 IN4_ADDRESS((addr_out).s_addr = IN6_ADDRESS(addr_out).s6_addr32[3];
588 struct in_addr v4mask
;
590 if (mask
) { /* the caller (tried to) specify a mask */
591 bits
= (int) strtol(mask
, &endptr
, 10);
592 if (!*endptr
) { /* strtol converted everything, so it was an integer */
593 if ((bits
<0 || bits
>128) ||
594 ((tor_addr_family(addr_out
) == AF_INET
) && bits
> 32)) {
596 "Bad number of mask bits (%d) on address range; rejecting.",
600 } else { /* mask might still be an address-style mask */
601 if (tor_inet_pton(AF_INET
, mask
, &v4mask
) > 0) {
602 bits
= addr_mask_get_bits(ntohl(v4mask
.s_addr
));
605 "IPv4-style mask %s is not a prefix address; rejecting.",
609 } else { /* Not IPv4; we don't do address-style IPv6 masks. */
611 "Malformed mask on address range %s; rejecting.",
616 if (tor_addr_family(addr_out
) == AF_INET6
&& v4map
) {
617 if (bits
> 32 && bits
< 96) { /* Crazy */
619 "Bad mask bits %i for V4-mapped V6 address; rejecting.",
623 /* XXXX_IP6 is this really what we want? */
624 bits
= 96 + bits
%32; /* map v4-mapped masks onto 96-128 bits */
626 } else { /* pick an appropriate mask, as none was given */
628 bits
= 0; /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */
629 else if (tor_addr_family(addr_out
) == AF_INET
)
631 else if (tor_addr_family(addr_out
) == AF_INET6
)
634 *maskbits_out
= (maskbits_t
) bits
;
638 "Unexpected mask in addrss %s; rejecting", escaped(s
));
646 if (!port_max_out
) /* caller specified one port; fake the second one */
647 port_max_out
= &port2
;
649 if (parse_port_range(port
, port_min_out
, port_max_out
) < 0) {
651 } else if ((*port_min_out
!= *port_max_out
) && port_max_out
== &port2
) {
653 "Wanted one port from address range, but there are two.");
655 port_max_out
= NULL
; /* caller specified one port, so set this back */
661 "Unexpected ports in addrss %s; rejecting", escaped(s
));
667 return tor_addr_family(addr_out
);
673 /** Determine whether an address is IPv4, either native or ipv4-mapped ipv6.
674 * Note that this is about representation only, as any decent stack will
675 * reject ipv4-mapped addresses received on the wire (and won't use them
676 * on the wire either).
679 tor_addr_is_v4(const tor_addr_t
*addr
)
683 if (tor_addr_family(addr
) == AF_INET
)
686 if (tor_addr_family(addr
) == AF_INET6
) {
687 /* First two don't need to be ordered */
688 uint32_t *a32
= tor_addr_to_in6_addr32(addr
);
689 if (a32
[0] == 0 && a32
[1] == 0 && ntohl(a32
[2]) == 0x0000ffffu
)
693 return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */
696 /** Determine whether an address <b>addr</b> is null, either all zeroes or
697 * belonging to family AF_UNSPEC.
700 tor_addr_is_null(const tor_addr_t
*addr
)
704 switch (tor_addr_family(addr
)) {
706 uint32_t *a32
= tor_addr_to_in6_addr32(addr
);
707 return (a32
[0] == 0) && (a32
[1] == 0) && (a32
[2] == 0) && (a32
[3] == 0);
710 return (tor_addr_to_ipv4n(addr
) == 0);
714 log_warn(LD_BUG
, "Called with unknown address family %d",
715 (int)tor_addr_family(addr
));
721 /** Return true iff <b>addr</b> is a loopback address */
723 tor_addr_is_loopback(const tor_addr_t
*addr
)
726 switch (tor_addr_family(addr
)) {
729 uint32_t *a32
= tor_addr_to_in6_addr32(addr
);
730 return (a32
[0] == 0) && (a32
[1] == 0) && (a32
[2] == 0) && (a32
[3] == 1);
734 return (tor_addr_to_ipv4h(addr
) & 0xff000000) == 0x7f000000;
738 tor_fragile_assert();
743 /** Set <b>dest</b> to equal the IPv4 address in <b>v4addr</b> (given in
746 tor_addr_from_ipv4n(tor_addr_t
*dest
, uint32_t v4addr
)
749 memset(dest
, 0, sizeof(dest
));
750 dest
->family
= AF_INET
;
751 dest
->addr
.in_addr
.s_addr
= v4addr
;
754 /** Set <b>dest</b> to equal the IPv6 address in the 16 bytes at
755 * <b>ipv6_bytes</b>. */
757 tor_addr_from_ipv6_bytes(tor_addr_t
*dest
, const char *ipv6_bytes
)
760 tor_assert(ipv6_bytes
);
761 memset(dest
, 0, sizeof(dest
));
762 dest
->family
= AF_INET6
;
763 memcpy(dest
->addr
.in6_addr
.s6_addr
, ipv6_bytes
, 16);
766 /** Set <b>dest</b> equal to the IPv6 address in the in6_addr <b>in6</b>. */
768 tor_addr_from_in6(tor_addr_t
*dest
, const struct in6_addr
*in6
)
770 tor_addr_from_ipv6_bytes(dest
, (const char*)in6
->s6_addr
);
773 /** Copy a tor_addr_t from <b>src</b> to <b>dest</b>.
776 tor_addr_copy(tor_addr_t
*dest
, const tor_addr_t
*src
)
780 memcpy(dest
, src
, sizeof(tor_addr_t
));
783 /** Given two addresses <b>addr1</b> and <b>addr2</b>, return 0 if the two
784 * addresses are equivalent under the mask mbits, less than 0 if addr1
785 * preceeds addr2, and greater than 0 otherwise.
787 * Different address families (IPv4 vs IPv6) are always considered unequal.
788 * NOT QUITE XXXX DOCDOC.
791 tor_addr_compare(const tor_addr_t
*addr1
, const tor_addr_t
*addr2
,
792 tor_addr_comparison_t how
)
794 return tor_addr_compare_masked(addr1
, addr2
, 128, how
);
797 /** As tor_addr_compare(), but only looks at the first <b>mask</b> bits of
800 * Reduce over-specific masks (>128 for ipv6, >32 for ipv4) to 128 or 32.
803 tor_addr_compare_masked(const tor_addr_t
*addr1
, const tor_addr_t
*addr2
,
804 maskbits_t mbits
, tor_addr_comparison_t how
)
806 uint32_t ip4a
=0, ip4b
=0;
807 sa_family_t v_family
[2];
809 uint32_t masked_a
, masked_b
;
811 tor_assert(addr1
&& addr2
);
813 if (how
== CMP_EXACT
) {
814 int r
= ((int)addr2
->family
) - ((int)addr1
->family
);
816 switch (addr1
->family
) {
818 return 0; /* All unspecified addresses are equal */
820 uint32_t a1
= ntohl(addr1
->addr
.in_addr
.s_addr
);
821 uint32_t a2
= ntohl(addr2
->addr
.in_addr
.s_addr
);
826 return (a1
< a2
) ? -1 : (a1
== a2
) ? 0 : 1;
829 const uint8_t *a1
= addr1
->addr
.in6_addr
.s6_addr
;
830 const uint8_t *a2
= addr2
->addr
.in6_addr
.s6_addr
;
831 const int bytes
= mbits
>> 3;
832 const int leftover_bits
= mbits
& 7;
833 if (bytes
&& (r
= memcmp(a1
, a2
, bytes
))) {
835 } else if (leftover_bits
) {
836 uint8_t b1
= a1
[bytes
] >> (8-leftover_bits
);
837 uint8_t b2
= a2
[bytes
] >> (8-leftover_bits
);
838 return (b1
< b2
) ? -1 : (b1
== b2
) ? 0 : 1;
844 tor_fragile_assert();
849 /* XXXX021 this code doesn't handle mask bits right it's using v4-mapped v6
850 * addresses. If I ask whether ::ffff:1.2.3.4 and ::ffff:1.2.7.8 are the
851 * same in the first 16 bits, it will say "yes." That's not so intuitive.
853 * XXXX021 Also, it's way too complicated.
856 v_family
[0] = tor_addr_family(addr1
);
857 v_family
[1] = tor_addr_family(addr2
);
859 /* All UNSPEC addresses are equal; they are unequal to all other addresses.*/
860 if (v_family
[0] == AF_UNSPEC
) {
861 if (v_family
[1] == AF_UNSPEC
)
866 if (v_family
[1] == AF_UNSPEC
)
870 if (v_family
[0] == AF_INET
) { /* If this is native IPv4, note the address */
871 /* Later we risk overwriting a v4-mapped address */
872 ip4a
= tor_addr_to_ipv4h(addr1
);
873 } else if ((v_family
[0] == AF_INET6
) && tor_addr_is_v4(addr1
)) {
874 v_family
[0] = AF_INET
;
875 ip4a
= tor_addr_to_mapped_ipv4h(addr1
);
878 if (v_family
[1] == AF_INET
) { /* If this is native IPv4, note the address */
879 /* Later we risk overwriting a v4-mapped address */
880 ip4b
= tor_addr_to_ipv4h(addr2
);
881 } else if ((v_family
[1] == AF_INET6
) && tor_addr_is_v4(addr2
)) {
882 v_family
[1] = AF_INET
;
883 ip4b
= tor_addr_to_mapped_ipv4h(addr2
);
886 if (v_family
[0] > v_family
[1]) /* Comparison of virtual families */
888 else if (v_family
[0] < v_family
[1])
891 if (mbits
== 0) /* Under a complete wildcard mask, consider them equal */
894 if (v_family
[0] == AF_INET
) { /* Real or mapped IPv4 */
898 } else if (mbits
== 0) {
901 masked_a
= ip4a
>> (32-mbits
);
902 masked_b
= ip4b
>> (32-mbits
);
904 if (masked_a
< masked_b
)
906 else if (masked_a
> masked_b
)
909 } else if (v_family
[0] == AF_INET6
) { /* Real IPv6 */
910 const uint32_t *a1
= tor_addr_to_in6_addr32(addr1
);
911 const uint32_t *a2
= tor_addr_to_in6_addr32(addr2
);
912 for (idx
= 0; idx
< 4; ++idx
) {
913 uint32_t masked_a
= ntohl(a1
[idx
]);
914 uint32_t masked_b
= ntohl(a2
[idx
]);
916 return 0; /* Mask covers both addresses from here on */
917 } else if (mbits
< 32) {
918 masked_a
>>= (32-mbits
);
919 masked_b
>>= (32-mbits
);
922 if (masked_a
> masked_b
)
924 else if (masked_a
< masked_b
)
934 tor_assert(0); /* Unknown address family */
935 return -1; /* unknown address family, return unequal? */
939 /** Return a hash code based on the address addr */
941 tor_addr_hash(const tor_addr_t
*addr
)
943 switch (tor_addr_family(addr
)) {
945 return tor_addr_to_ipv4h(addr
);
949 const uint32_t *u
= tor_addr_to_in6_addr32(addr
);
950 return u
[0] + u
[1] + u
[2] + u
[3];
953 tor_fragile_assert();
958 /** Return a newly allocated string with a representation of <b>addr</b>. */
960 tor_dup_addr(const tor_addr_t
*addr
)
962 char buf
[TOR_ADDR_BUF_LEN
];
963 tor_addr_to_str(buf
, addr
, sizeof(buf
), 0);
964 return tor_strdup(buf
);
967 /** Copy the address in <b>src</b> to <b>dest</b> */
969 tor_addr_assign(tor_addr_t
*dest
, const tor_addr_t
*src
)
971 memcpy(dest
, src
, sizeof(tor_addr_t
));
974 /** Return a string representing the address <b>addr</b>. This string is
975 * statically allocated, and must not be freed. Each call to
976 * <b>fmt_addr</b> invalidates the last result of the function. This
977 * function is not thread-safe. */
979 fmt_addr(const tor_addr_t
*addr
)
981 static char buf
[TOR_ADDR_BUF_LEN
];
982 if (!addr
) return "<null>";
983 tor_addr_to_str(buf
, addr
, sizeof(buf
), 0);
987 /** Convert the string in <b>src</b> to a tor_addr_t <b>addr</b>. The string
988 * may be an IPv4 address, an IPv6 address, or an IPv6 address surrounded by
991 * Return an address family on success, or -1 if an invalid address string is
994 tor_addr_from_str(tor_addr_t
*addr
, const char *src
)
996 char *tmp
= NULL
; /* Holds substring if we got a dotted quad. */
998 tor_assert(addr
&& src
);
999 if (src
[0] == '[' && src
[1])
1000 src
= tmp
= tor_strndup(src
+1, strlen(src
)-2);
1002 if (tor_inet_pton(AF_INET6
, src
, &addr
->addr
.in6_addr
) > 0) {
1003 result
= addr
->family
= AF_INET6
;
1004 } else if (tor_inet_pton(AF_INET
, src
, &addr
->addr
.in_addr
) > 0) {
1005 result
= addr
->family
= AF_INET
;
1014 /** Parse an address or address-port combination from <b>s</b>, and put the
1015 result in <b>addr_out</b> and (optionally) <b>port_out</b>. Return 0 on
1016 success, negative on failure.*/
1018 tor_addr_port_parse(const char *s
, tor_addr_t
*addr_out
, uint16_t *port_out
)
1026 tor_assert(addr_out
);
1028 s
= eat_whitespace(s
);
1031 port
= strstr(s
, "]");
1034 tmp
= tor_strndup(s
+1, port
-s
);
1041 port
= strchr(s
, ':');
1043 tmp
= tor_strndup(s
, port
-s
);
1045 tmp
= tor_strdup(s
);
1050 if (tor_addr_lookup(tmp
, AF_UNSPEC
, &addr
) < 0)
1055 portval
= (int) tor_parse_long(port
, 10, 1, 65535, NULL
, NULL
);
1063 *port_out
= portval
;
1064 tor_addr_copy(addr_out
, &addr
);
1072 /** Set *<b>addr</b> to the IP address (if any) of whatever interface
1073 * connects to the internet. This address should only be used in checking
1074 * whether our address has changed. Return 0 on success, -1 on failure.
1077 get_interface_address6(int severity
, sa_family_t family
, tor_addr_t
*addr
)
1080 struct sockaddr_storage my_addr
, target_addr
;
1081 socklen_t my_addr_len
;
1085 memset(addr
, 0, sizeof(tor_addr_t
));
1086 memset(&target_addr
, 0, sizeof(target_addr
));
1087 my_addr_len
= (socklen_t
)sizeof(my_addr
);
1088 /* Use the "discard" service port */
1089 ((struct sockaddr_in
*)&target_addr
)->sin_port
= 9;
1090 /* Don't worry: no packets are sent. We just need to use a real address
1091 * on the actual internet. */
1092 if (family
== AF_INET6
) {
1093 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)&target_addr
;
1094 sock
= tor_open_socket(PF_INET6
,SOCK_DGRAM
,IPPROTO_UDP
);
1095 my_addr_len
= (socklen_t
)sizeof(struct sockaddr_in6
);
1096 sin6
->sin6_family
= AF_INET6
;
1097 S6_ADDR16(sin6
->sin6_addr
)[0] = htons(0x2002); /* 2002:: */
1098 } else if (family
== AF_INET
) {
1099 struct sockaddr_in
*sin
= (struct sockaddr_in
*)&target_addr
;
1100 sock
= tor_open_socket(PF_INET
,SOCK_DGRAM
,IPPROTO_UDP
);
1101 my_addr_len
= (socklen_t
)sizeof(struct sockaddr_in
);
1102 sin
->sin_family
= AF_INET
;
1103 sin
->sin_addr
.s_addr
= htonl(0x12000001); /* 18.0.0.1 */
1108 int e
= tor_socket_errno(-1);
1109 log_fn(severity
, LD_NET
, "unable to create socket: %s",
1110 tor_socket_strerror(e
));
1114 if (connect(sock
,(struct sockaddr
*)&target_addr
,
1115 (socklen_t
)sizeof(target_addr
))<0) {
1116 int e
= tor_socket_errno(sock
);
1117 log_fn(severity
, LD_NET
, "connect() failed: %s", tor_socket_strerror(e
));
1121 if (getsockname(sock
,(struct sockaddr
*)&my_addr
, &my_addr_len
)) {
1122 int e
= tor_socket_errno(sock
);
1123 log_fn(severity
, LD_NET
, "getsockname() to determine interface failed: %s",
1124 tor_socket_strerror(e
));
1128 memcpy(addr
, &my_addr
, sizeof(tor_addr_t
));
1132 tor_close_socket(sock
);
1138 * XXXX022 IPv6 deprecate some of these.
1141 /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
1142 * or reserved for local networks by RFC 1918.
1145 is_internal_IP(uint32_t ip
, int for_listening
)
1148 myaddr
.family
= AF_INET
;
1149 myaddr
.addr
.in_addr
.s_addr
= htonl(ip
);
1151 return tor_addr_is_internal(&myaddr
, for_listening
);
1154 /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
1155 * <b>address</b> is provided, set *<b>address</b> to a copy of the
1156 * host portion of the string. If <b>addr</b> is provided, try to
1157 * resolve the host portion of the string and store it into
1158 * *<b>addr</b> (in host byte order). If <b>port_out</b> is provided,
1159 * store the port number into *<b>port_out</b>, or 0 if no port is given.
1160 * If <b>port_out</b> is NULL, then there must be no port number in
1162 * Return 0 on success, -1 on failure.
1165 parse_addr_port(int severity
, const char *addrport
, char **address
,
1166 uint32_t *addr
, uint16_t *port_out
)
1169 char *_address
= NULL
;
1173 tor_assert(addrport
);
1175 colon
= strchr(addrport
, ':');
1177 _address
= tor_strndup(addrport
, colon
-addrport
);
1178 _port
= (int) tor_parse_long(colon
+1,10,1,65535,NULL
,NULL
);
1180 log_fn(severity
, LD_GENERAL
, "Port %s out of range", escaped(colon
+1));
1184 char *esc_addrport
= esc_for_log(addrport
);
1185 log_fn(severity
, LD_GENERAL
,
1186 "Port %s given on %s when not required",
1187 escaped(colon
+1), esc_addrport
);
1188 tor_free(esc_addrport
);
1192 _address
= tor_strdup(addrport
);
1197 /* There's an addr pointer, so we need to resolve the hostname. */
1198 if (tor_lookup_hostname(_address
,addr
)) {
1199 log_fn(severity
, LD_NET
, "Couldn't look up %s", escaped(_address
));
1205 if (address
&& ok
) {
1206 *address
= _address
;
1213 *port_out
= ok
? ((uint16_t) _port
) : 0;
1218 /** If <b>mask</b> is an address mask for a bit-prefix, return the number of
1219 * bits. Otherwise, return -1. */
1221 addr_mask_get_bits(uint32_t mask
)
1226 if (mask
== 0xFFFFFFFFu
)
1228 for (i
=0; i
<=32; ++i
) {
1229 if (mask
== (uint32_t) ~((1u<<(32-i
))-1)) {
1236 /** Compare two addresses <b>a1</b> and <b>a2</b> for equality under a
1237 * netmask of <b>mbits</b> bits. Return -1, 0, or 1.
1239 * XXXX_IP6 Temporary function to allow masks as bitcounts everywhere. This
1240 * will be replaced with an IPv6-aware version as soon as 32-bit addresses are
1241 * no longer passed around.
1244 addr_mask_cmp_bits(uint32_t a1
, uint32_t a2
, maskbits_t bits
)
1262 /** Parse a string <b>s</b> in the format of (*|port(-maxport)?)?, setting the
1263 * various *out pointers as appropriate. Return 0 on success, -1 on failure.
1266 parse_port_range(const char *port
, uint16_t *port_min_out
,
1267 uint16_t *port_max_out
)
1269 int port_min
, port_max
, ok
;
1270 tor_assert(port_min_out
);
1271 tor_assert(port_max_out
);
1273 if (!port
|| *port
== '\0' || strcmp(port
, "*") == 0) {
1277 char *endptr
= NULL
;
1278 port_min
= (int)tor_parse_long(port
, 10, 0, 65535, &ok
, &endptr
);
1280 log_warn(LD_GENERAL
,
1281 "Malformed port %s on address range; rejecting.",
1284 } else if (endptr
&& *endptr
== '-') {
1287 port_max
= (int)tor_parse_long(port
, 10, 1, 65536, &ok
, &endptr
);
1289 log_warn(LD_GENERAL
,
1290 "Malformed port %s on address range; rejecting.",
1295 port_max
= port_min
;
1297 if (port_min
> port_max
) {
1298 log_warn(LD_GENERAL
, "Insane port range on address policy; rejecting.");
1305 if (port_max
> 65535)
1308 *port_min_out
= (uint16_t) port_min
;
1309 *port_max_out
= (uint16_t) port_max
;
1314 /** Parse a string <b>s</b> in the format of
1315 * (IP(/mask|/mask-bits)?|*)(:(*|port(-maxport))?)?, setting the various
1316 * *out pointers as appropriate. Return 0 on success, -1 on failure.
1319 parse_addr_and_port_range(const char *s
, uint32_t *addr_out
,
1320 maskbits_t
*maskbits_out
, uint16_t *port_min_out
,
1321 uint16_t *port_max_out
)
1324 char *mask
, *port
, *endptr
;
1329 tor_assert(addr_out
);
1330 tor_assert(maskbits_out
);
1331 tor_assert(port_min_out
);
1332 tor_assert(port_max_out
);
1334 address
= tor_strdup(s
);
1335 /* Break 'address' into separate strings.
1337 mask
= strchr(address
,'/');
1338 port
= strchr(mask
?mask
:address
,':');
1343 /* Now "address" is the IP|'*' part...
1344 * "mask" is the Mask|Maskbits part...
1345 * and "port" is the *|port|min-max part.
1348 if (strcmp(address
,"*")==0) {
1350 } else if (tor_inet_aton(address
, &in
) != 0) {
1351 *addr_out
= ntohl(in
.s_addr
);
1353 log_warn(LD_GENERAL
, "Malformed IP %s in address pattern; rejecting.",
1359 if (strcmp(address
,"*")==0)
1365 bits
= (int) strtol(mask
, &endptr
, 10);
1367 /* strtol handled the whole mask. */
1368 if (bits
< 0 || bits
> 32) {
1369 log_warn(LD_GENERAL
,
1370 "Bad number of mask bits on address range; rejecting.");
1373 *maskbits_out
= bits
;
1374 } else if (tor_inet_aton(mask
, &in
) != 0) {
1375 bits
= addr_mask_get_bits(ntohl(in
.s_addr
));
1377 log_warn(LD_GENERAL
,
1378 "Mask %s on address range isn't a prefix; dropping",
1382 *maskbits_out
= bits
;
1384 log_warn(LD_GENERAL
,
1385 "Malformed mask %s on address range; rejecting.",
1391 if (parse_port_range(port
, port_min_out
, port_max_out
)<0)
1401 /** Given an IPv4 in_addr struct *<b>in</b> (in network order, as usual),
1402 * write it as a string into the <b>buf_len</b>-byte buffer in
1406 tor_inet_ntoa(const struct in_addr
*in
, char *buf
, size_t buf_len
)
1408 uint32_t a
= ntohl(in
->s_addr
);
1409 return tor_snprintf(buf
, buf_len
, "%d.%d.%d.%d",
1410 (int)(uint8_t)((a
>>24)&0xff),
1411 (int)(uint8_t)((a
>>16)&0xff),
1412 (int)(uint8_t)((a
>>8 )&0xff),
1413 (int)(uint8_t)((a
)&0xff));
1416 /** Given a host-order <b>addr</b>, call tor_inet_ntop() on it
1417 * and return a strdup of the resulting address.
1420 tor_dup_ip(uint32_t addr
)
1422 char buf
[TOR_ADDR_BUF_LEN
];
1425 in
.s_addr
= htonl(addr
);
1426 tor_inet_ntop(AF_INET
, &in
, buf
, sizeof(buf
));
1427 return tor_strdup(buf
);
1431 * Set *<b>addr</b> to the host-order IPv4 address (if any) of whatever
1432 * interface connects to the internet. This address should only be used in
1433 * checking whether our address has changed. Return 0 on success, -1 on
1437 get_interface_address(int severity
, uint32_t *addr
)
1439 tor_addr_t local_addr
;
1442 r
= get_interface_address6(severity
, AF_INET
, &local_addr
);
1444 *addr
= tor_addr_to_ipv4h(&local_addr
);