Back to index

tor  0.2.3.19-rc
address.c
Go to the documentation of this file.
00001 /* Copyright (c) 2003-2004, Roger Dingledine
00002  * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
00003  * Copyright (c) 2007-2012, The Tor Project, Inc. */
00004 /* See LICENSE for licensing information */
00005 
00011 #include "orconfig.h"
00012 #include "compat.h"
00013 #include "util.h"
00014 #include "address.h"
00015 #include "torlog.h"
00016 #include "container.h"
00017 
00018 #ifdef _WIN32
00019 #include <process.h>
00020 #include <windows.h>
00021 #include <winsock2.h>
00022 /* For access to structs needed by GetAdaptersAddresses */
00023 #undef _WIN32_WINNT
00024 #define _WIN32_WINNT 0x0501
00025 #include <iphlpapi.h>
00026 #endif
00027 
00028 #ifdef HAVE_SYS_TIME_H
00029 #include <sys/time.h>
00030 #endif
00031 #ifdef HAVE_UNISTD_H
00032 #include <unistd.h>
00033 #endif
00034 #ifdef HAVE_ERRNO_H
00035 #include <errno.h>
00036 #endif
00037 #ifdef HAVE_NETINET_IN_H
00038 #include <netinet/in.h>
00039 #endif
00040 #ifdef HAVE_ARPA_INET_H
00041 #include <arpa/inet.h>
00042 #endif
00043 #ifdef HAVE_SYS_SOCKET_H
00044 #include <sys/socket.h>
00045 #endif
00046 #ifdef HAVE_NETDB_H
00047 #include <netdb.h>
00048 #endif
00049 #ifdef HAVE_SYS_PARAM_H
00050 #include <sys/param.h> /* FreeBSD needs this to know what version it is */
00051 #endif
00052 #ifdef HAVE_SYS_UN_H
00053 #include <sys/un.h>
00054 #endif
00055 #ifdef HAVE_IFADDRS_H
00056 #include <ifaddrs.h>
00057 #endif
00058 #ifdef HAVE_SYS_IOCTL_H
00059 #include <sys/ioctl.h>
00060 #endif
00061 #ifdef HAVE_NET_IF_H
00062 #include <net/if.h>
00063 #endif
00064 #include <stdarg.h>
00065 #include <stdio.h>
00066 #include <stdlib.h>
00067 #include <string.h>
00068 #include <assert.h>
00069 
00070 /* tor_addr_is_null() and maybe other functions rely on AF_UNSPEC being 0 to
00071  * work correctly. Bail out here if we've found a platform where AF_UNSPEC
00072  * isn't 0. */
00073 #if AF_UNSPEC != 0
00074 #error We rely on AF_UNSPEC being 0. Let us know about your platform, please!
00075 #endif
00076 
00085 socklen_t
00086 tor_addr_to_sockaddr(const tor_addr_t *a,
00087                      uint16_t port,
00088                      struct sockaddr *sa_out,
00089                      socklen_t len)
00090 {
00091   sa_family_t family = tor_addr_family(a);
00092   if (family == AF_INET) {
00093     struct sockaddr_in *sin;
00094     if (len < (int)sizeof(struct sockaddr_in))
00095       return 0;
00096     sin = (struct sockaddr_in *)sa_out;
00097     memset(sin, 0, sizeof(struct sockaddr_in));
00098 #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
00099     sin->sin_len = sizeof(struct sockaddr_in);
00100 #endif
00101     sin->sin_family = AF_INET;
00102     sin->sin_port = htons(port);
00103     sin->sin_addr.s_addr = tor_addr_to_ipv4n(a);
00104     return sizeof(struct sockaddr_in);
00105   } else if (family == AF_INET6) {
00106     struct sockaddr_in6 *sin6;
00107     if (len < (int)sizeof(struct sockaddr_in6))
00108       return 0;
00109     sin6 = (struct sockaddr_in6 *)sa_out;
00110     memset(sin6, 0, sizeof(struct sockaddr_in6));
00111 #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
00112     sin6->sin6_len = sizeof(struct sockaddr_in6);
00113 #endif
00114     sin6->sin6_family = AF_INET6;
00115     sin6->sin6_port = htons(port);
00116     memcpy(&sin6->sin6_addr, tor_addr_to_in6(a), sizeof(struct in6_addr));
00117     return sizeof(struct sockaddr_in6);
00118   } else {
00119     return 0;
00120   }
00121 }
00122 
00125 int
00126 tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa,
00127                        uint16_t *port_out)
00128 {
00129   tor_assert(a);
00130   tor_assert(sa);
00131   if (sa->sa_family == AF_INET) {
00132     struct sockaddr_in *sin = (struct sockaddr_in *) sa;
00133     tor_addr_from_ipv4n(a, sin->sin_addr.s_addr);
00134     if (port_out)
00135       *port_out = ntohs(sin->sin_port);
00136   } else if (sa->sa_family == AF_INET6) {
00137     struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
00138     tor_addr_from_in6(a, &sin6->sin6_addr);
00139     if (port_out)
00140       *port_out = ntohs(sin6->sin6_port);
00141   } else {
00142     tor_addr_make_unspec(a);
00143     return -1;
00144   }
00145   return 0;
00146 }
00147 
00150 char *
00151 tor_sockaddr_to_str(const struct sockaddr *sa)
00152 {
00153   char address[TOR_ADDR_BUF_LEN];
00154   char *result;
00155   tor_addr_t addr;
00156   uint16_t port;
00157 #ifdef HAVE_SYS_UN_H
00158   if (sa->sa_family == AF_UNIX) {
00159     struct sockaddr_un *s_un = (struct sockaddr_un *)sa;
00160     tor_asprintf(&result, "unix:%s", s_un->sun_path);
00161     return result;
00162   }
00163 #endif
00164   if (sa->sa_family == AF_UNSPEC)
00165     return tor_strdup("unspec");
00166 
00167   if (tor_addr_from_sockaddr(&addr, sa, &port) < 0)
00168     return NULL;
00169   if (! tor_addr_to_str(address, &addr, sizeof(address), 1))
00170     return NULL;
00171   tor_asprintf(&result, "%s:%d", address, (int)port);
00172   return result;
00173 }
00174 
00177 void
00178 tor_addr_make_unspec(tor_addr_t *a)
00179 {
00180   memset(a, 0, sizeof(*a));
00181   a->family = AF_UNSPEC;
00182 }
00183 
00192 int
00193 tor_addr_lookup(const char *name, uint16_t family, tor_addr_t *addr)
00194 {
00195   /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
00196    * something.
00197    */
00198   struct in_addr iaddr;
00199   struct in6_addr iaddr6;
00200   tor_assert(name);
00201   tor_assert(addr);
00202   tor_assert(family == AF_INET || family == AF_INET6 || family == AF_UNSPEC);
00203   if (!*name) {
00204     /* Empty address is an error. */
00205     return -1;
00206   } else if (tor_inet_pton(AF_INET, name, &iaddr)) {
00207     /* It's an IPv4 IP. */
00208     if (family == AF_INET6)
00209       return -1;
00210     tor_addr_from_in(addr, &iaddr);
00211     return 0;
00212   } else if (tor_inet_pton(AF_INET6, name, &iaddr6)) {
00213     if (family == AF_INET)
00214       return -1;
00215     tor_addr_from_in6(addr, &iaddr6);
00216     return 0;
00217   } else {
00218 #ifdef HAVE_GETADDRINFO
00219     int err;
00220     struct addrinfo *res=NULL, *res_p;
00221     struct addrinfo *best=NULL;
00222     struct addrinfo hints;
00223     int result = -1;
00224     memset(&hints, 0, sizeof(hints));
00225     hints.ai_family = family;
00226     hints.ai_socktype = SOCK_STREAM;
00227     err = getaddrinfo(name, NULL, &hints, &res);
00228     if (!err) {
00229       best = NULL;
00230       for (res_p = res; res_p; res_p = res_p->ai_next) {
00231         if (family == AF_UNSPEC) {
00232           if (res_p->ai_family == AF_INET) {
00233             best = res_p;
00234             break;
00235           } else if (res_p->ai_family == AF_INET6 && !best) {
00236             best = res_p;
00237           }
00238         } else if (family == res_p->ai_family) {
00239           best = res_p;
00240           break;
00241         }
00242       }
00243       if (!best)
00244         best = res;
00245       if (best->ai_family == AF_INET) {
00246         tor_addr_from_in(addr,
00247                          &((struct sockaddr_in*)best->ai_addr)->sin_addr);
00248         result = 0;
00249       } else if (best->ai_family == AF_INET6) {
00250         tor_addr_from_in6(addr,
00251                           &((struct sockaddr_in6*)best->ai_addr)->sin6_addr);
00252         result = 0;
00253       }
00254       freeaddrinfo(res);
00255       return result;
00256     }
00257     return (err == EAI_AGAIN) ? 1 : -1;
00258 #else
00259     struct hostent *ent;
00260     int err;
00261 #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
00262     char buf[2048];
00263     struct hostent hostent;
00264     int r;
00265     r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err);
00266 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
00267     char buf[2048];
00268     struct hostent hostent;
00269     ent = gethostbyname_r(name, &hostent, buf, sizeof(buf), &err);
00270 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
00271     struct hostent_data data;
00272     struct hostent hent;
00273     memset(&data, 0, sizeof(data));
00274     err = gethostbyname_r(name, &hent, &data);
00275     ent = err ? NULL : &hent;
00276 #else
00277     ent = gethostbyname(name);
00278 #ifdef _WIN32
00279     err = WSAGetLastError();
00280 #else
00281     err = h_errno;
00282 #endif
00283 #endif /* endif HAVE_GETHOSTBYNAME_R_6_ARG. */
00284     if (ent) {
00285       if (ent->h_addrtype == AF_INET) {
00286         tor_addr_from_in(addr, (struct in_addr*) ent->h_addr);
00287       } else if (ent->h_addrtype == AF_INET6) {
00288         tor_addr_from_in6(addr, (struct in6_addr*) ent->h_addr);
00289       } else {
00290         tor_assert(0); /* gethostbyname() returned a bizarre addrtype */
00291       }
00292       return 0;
00293     }
00294 #ifdef _WIN32
00295     return (err == WSATRY_AGAIN) ? 1 : -1;
00296 #else
00297     return (err == TRY_AGAIN) ? 1 : -1;
00298 #endif
00299 #endif
00300   }
00301 }
00302 
00307 int
00308 tor_addr_is_internal(const tor_addr_t *addr, int for_listening)
00309 {
00310   uint32_t iph4 = 0;
00311   uint32_t iph6[4];
00312   sa_family_t v_family;
00313   v_family = tor_addr_family(addr);
00314 
00315   if (v_family == AF_INET) {
00316     iph4 = tor_addr_to_ipv4h(addr);
00317   } else if (v_family == AF_INET6) {
00318     if (tor_addr_is_v4(addr)) { /* v4-mapped */
00319       v_family = AF_INET;
00320       iph4 = ntohl(tor_addr_to_in6_addr32(addr)[3]);
00321     }
00322   }
00323 
00324   if (v_family == AF_INET6) {
00325     const uint32_t *a32 = tor_addr_to_in6_addr32(addr);
00326     iph6[0] = ntohl(a32[0]);
00327     iph6[1] = ntohl(a32[1]);
00328     iph6[2] = ntohl(a32[2]);
00329     iph6[3] = ntohl(a32[3]);
00330     if (for_listening && !iph6[0] && !iph6[1] && !iph6[2] && !iph6[3]) /* :: */
00331       return 0;
00332 
00333     if (((iph6[0] & 0xfe000000) == 0xfc000000) || /* fc00/7  - RFC4193 */
00334         ((iph6[0] & 0xffc00000) == 0xfe800000) || /* fe80/10 - RFC4291 */
00335         ((iph6[0] & 0xffc00000) == 0xfec00000))   /* fec0/10 D- RFC3879 */
00336       return 1;
00337 
00338     if (!iph6[0] && !iph6[1] && !iph6[2] &&
00339         ((iph6[3] & 0xfffffffe) == 0x00000000))  /* ::/127 */
00340       return 1;
00341 
00342     return 0;
00343   } else if (v_family == AF_INET) {
00344     if (for_listening && !iph4) /* special case for binding to 0.0.0.0 */
00345       return 0;
00346     if (((iph4 & 0xff000000) == 0x0a000000) || /*       10/8 */
00347         ((iph4 & 0xff000000) == 0x00000000) || /*        0/8 */
00348         ((iph4 & 0xff000000) == 0x7f000000) || /*      127/8 */
00349         ((iph4 & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
00350         ((iph4 & 0xfff00000) == 0xac100000) || /*  172.16/12 */
00351         ((iph4 & 0xffff0000) == 0xc0a80000))   /* 192.168/16 */
00352       return 1;
00353     return 0;
00354   }
00355 
00356   /* unknown address family... assume it's not safe for external use */
00357   /* rather than tor_assert(0) */
00358   log_warn(LD_BUG, "tor_addr_is_internal() called with a non-IP address of "
00359            "type %d", (int)v_family);
00360   tor_fragile_assert();
00361   return 1;
00362 }
00363 
00369 const char *
00370 tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
00371 {
00372   const char *ptr;
00373   tor_assert(addr && dest);
00374 
00375   switch (tor_addr_family(addr)) {
00376     case AF_INET:
00377       /* Shortest addr x.x.x.x + \0 */
00378       if (len < 8)
00379         return NULL;
00380       ptr = tor_inet_ntop(AF_INET, &addr->addr.in_addr, dest, len);
00381       break;
00382     case AF_INET6:
00383       /* Shortest addr [ :: ] + \0 */
00384       if (len < (3 + (decorate ? 2 : 0)))
00385         return NULL;
00386 
00387       if (decorate)
00388         ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest+1, len-2);
00389       else
00390         ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest, len);
00391 
00392       if (ptr && decorate) {
00393         *dest = '[';
00394         memcpy(dest+strlen(dest), "]", 2);
00395         tor_assert(ptr == dest+1);
00396         ptr = dest;
00397       }
00398       break;
00399     default:
00400       return NULL;
00401   }
00402   return ptr;
00403 }
00404 
00416 int
00417 tor_addr_parse_PTR_name(tor_addr_t *result, const char *address,
00418                                    int family, int accept_regular)
00419 {
00420   if (!strcasecmpend(address, ".in-addr.arpa")) {
00421     /* We have an in-addr.arpa address. */
00422     char buf[INET_NTOA_BUF_LEN];
00423     size_t len;
00424     struct in_addr inaddr;
00425     if (family == AF_INET6)
00426       return -1;
00427 
00428     len = strlen(address) - strlen(".in-addr.arpa");
00429     if (len >= INET_NTOA_BUF_LEN)
00430       return -1; /* Too long. */
00431 
00432     memcpy(buf, address, len);
00433     buf[len] = '\0';
00434     if (tor_inet_aton(buf, &inaddr) == 0)
00435       return -1; /* malformed. */
00436 
00437     /* reverse the bytes */
00438     inaddr.s_addr = (uint32_t)
00439       (((inaddr.s_addr & 0x000000ff) << 24)
00440        |((inaddr.s_addr & 0x0000ff00) << 8)
00441        |((inaddr.s_addr & 0x00ff0000) >> 8)
00442        |((inaddr.s_addr & 0xff000000) >> 24));
00443 
00444     if (result) {
00445       tor_addr_from_in(result, &inaddr);
00446     }
00447     return 1;
00448   }
00449 
00450   if (!strcasecmpend(address, ".ip6.arpa")) {
00451     const char *cp;
00452     int i;
00453     int n0, n1;
00454     struct in6_addr in6;
00455 
00456     if (family == AF_INET)
00457       return -1;
00458 
00459     cp = address;
00460     for (i = 0; i < 16; ++i) {
00461       n0 = hex_decode_digit(*cp++); /* The low-order nybble appears first. */
00462       if (*cp++ != '.') return -1;  /* Then a dot. */
00463       n1 = hex_decode_digit(*cp++); /* The high-order nybble appears first. */
00464       if (*cp++ != '.') return -1;  /* Then another dot. */
00465       if (n0<0 || n1 < 0) /* Both nybbles must be hex. */
00466         return -1;
00467 
00468       /* We don't check the length of the string in here.  But that's okay,
00469        * since we already know that the string ends with ".ip6.arpa", and
00470        * there is no way to frameshift .ip6.arpa so it fits into the pattern
00471        * of hexdigit, period, hexdigit, period that we enforce above.
00472        */
00473 
00474       /* Assign from low-byte to high-byte. */
00475       in6.s6_addr[15-i] = n0 | (n1 << 4);
00476     }
00477     if (strcasecmp(cp, "ip6.arpa"))
00478       return -1;
00479 
00480     if (result) {
00481       tor_addr_from_in6(result, &in6);
00482     }
00483     return 1;
00484   }
00485 
00486   if (accept_regular) {
00487     tor_addr_t tmp;
00488     int r = tor_addr_parse(&tmp, address);
00489     if (r < 0)
00490       return 0;
00491     if (r != family && family != AF_UNSPEC)
00492       return -1;
00493 
00494     if (result)
00495       memcpy(result, &tmp, sizeof(tor_addr_t));
00496 
00497     return 1;
00498   }
00499 
00500   return 0;
00501 }
00502 
00507 int
00508 tor_addr_to_PTR_name(char *out, size_t outlen,
00509                      const tor_addr_t *addr)
00510 {
00511   tor_assert(out);
00512   tor_assert(addr);
00513 
00514   if (addr->family == AF_INET) {
00515     uint32_t a = tor_addr_to_ipv4h(addr);
00516 
00517     return tor_snprintf(out, outlen, "%d.%d.%d.%d.in-addr.arpa",
00518                         (int)(uint8_t)((a    )&0xff),
00519                         (int)(uint8_t)((a>>8 )&0xff),
00520                         (int)(uint8_t)((a>>16)&0xff),
00521                         (int)(uint8_t)((a>>24)&0xff));
00522   } else if (addr->family == AF_INET6) {
00523     int i;
00524     char *cp = out;
00525     const uint8_t *bytes = tor_addr_to_in6_addr8(addr);
00526     if (outlen < REVERSE_LOOKUP_NAME_BUF_LEN)
00527       return -1;
00528     for (i = 15; i >= 0; --i) {
00529       uint8_t byte = bytes[i];
00530       *cp++ = "0123456789abcdef"[byte & 0x0f];
00531       *cp++ = '.';
00532       *cp++ = "0123456789abcdef"[byte >> 4];
00533       *cp++ = '.';
00534     }
00535     memcpy(cp, "ip6.arpa", 9); /* 8 characters plus NUL */
00536     return 32 * 2 + 8;
00537   }
00538   return -1;
00539 }
00540 
00562 int
00563 tor_addr_parse_mask_ports(const char *s, tor_addr_t *addr_out,
00564                           maskbits_t *maskbits_out,
00565                           uint16_t *port_min_out, uint16_t *port_max_out)
00566 {
00567   char *base = NULL, *address, *mask = NULL, *port = NULL, *rbracket = NULL;
00568   char *endptr;
00569   int any_flag=0, v4map=0;
00570   sa_family_t family;
00571   struct in6_addr in6_tmp;
00572   struct in_addr in_tmp;
00573 
00574   tor_assert(s);
00575   tor_assert(addr_out);
00576 
00579 #define MAX_ADDRESS_LENGTH (TOR_ADDR_BUF_LEN+2+(1+INET_NTOA_BUF_LEN)+12+1)
00580 
00581   if (strlen(s) > MAX_ADDRESS_LENGTH) {
00582     log_warn(LD_GENERAL, "Impossibly long IP %s; rejecting", escaped(s));
00583     goto err;
00584   }
00585   base = tor_strdup(s);
00586 
00587   /* Break 'base' into separate strings. */
00588   address = base;
00589   if (*address == '[') {  /* Probably IPv6 */
00590     address++;
00591     rbracket = strchr(address, ']');
00592     if (!rbracket) {
00593       log_warn(LD_GENERAL,
00594                "No closing IPv6 bracket in address pattern; rejecting.");
00595       goto err;
00596     }
00597   }
00598   mask = strchr((rbracket?rbracket:address),'/');
00599   port = strchr((mask?mask:(rbracket?rbracket:address)), ':');
00600   if (port)
00601     *port++ = '\0';
00602   if (mask)
00603     *mask++ = '\0';
00604   if (rbracket)
00605     *rbracket = '\0';
00606   if (port && mask)
00607     tor_assert(port > mask);
00608   if (mask && rbracket)
00609     tor_assert(mask > rbracket);
00610 
00611   /* Now "address" is the a.b.c.d|'*'|abcd::1 part...
00612    *     "mask" is the Mask|Maskbits part...
00613    * and "port" is the *|port|min-max part.
00614    */
00615 
00616   /* Process the address portion */
00617   memset(addr_out, 0, sizeof(tor_addr_t));
00618 
00619   if (!strcmp(address, "*")) {
00620     family = AF_INET; /* AF_UNSPEC ???? XXXX_IP6 */
00621     tor_addr_from_ipv4h(addr_out, 0);
00622     any_flag = 1;
00623   } else if (tor_inet_pton(AF_INET6, address, &in6_tmp) > 0) {
00624     family = AF_INET6;
00625     tor_addr_from_in6(addr_out, &in6_tmp);
00626   } else if (tor_inet_pton(AF_INET, address, &in_tmp) > 0) {
00627     family = AF_INET;
00628     tor_addr_from_in(addr_out, &in_tmp);
00629   } else {
00630     log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
00631              escaped(address));
00632     goto err;
00633   }
00634 
00635   v4map = tor_addr_is_v4(addr_out);
00636 
00637   /* Parse mask */
00638   if (maskbits_out) {
00639     int bits = 0;
00640     struct in_addr v4mask;
00641 
00642     if (mask) {  /* the caller (tried to) specify a mask */
00643       bits = (int) strtol(mask, &endptr, 10);
00644       if (!*endptr) {  /* strtol converted everything, so it was an integer */
00645         if ((bits<0 || bits>128) ||
00646             (family == AF_INET && bits > 32)) {
00647           log_warn(LD_GENERAL,
00648                    "Bad number of mask bits (%d) on address range; rejecting.",
00649                    bits);
00650           goto err;
00651         }
00652       } else {  /* mask might still be an address-style mask */
00653         if (tor_inet_pton(AF_INET, mask, &v4mask) > 0) {
00654           bits = addr_mask_get_bits(ntohl(v4mask.s_addr));
00655           if (bits < 0) {
00656             log_warn(LD_GENERAL,
00657                      "IPv4-style mask %s is not a prefix address; rejecting.",
00658                      escaped(mask));
00659             goto err;
00660           }
00661         } else { /* Not IPv4; we don't do address-style IPv6 masks. */
00662           log_warn(LD_GENERAL,
00663                    "Malformed mask on address range %s; rejecting.",
00664                    escaped(s));
00665           goto err;
00666         }
00667       }
00668       if (family == AF_INET6 && v4map) {
00669         if (bits > 32 && bits < 96) { /* Crazy */
00670           log_warn(LD_GENERAL,
00671                    "Bad mask bits %d for V4-mapped V6 address; rejecting.",
00672                    bits);
00673           goto err;
00674         }
00675         /* XXXX_IP6 is this really what we want? */
00676         bits = 96 + bits%32; /* map v4-mapped masks onto 96-128 bits */
00677       }
00678     } else { /* pick an appropriate mask, as none was given */
00679       if (any_flag)
00680         bits = 0;  /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */
00681       else if (tor_addr_family(addr_out) == AF_INET)
00682         bits = 32;
00683       else if (tor_addr_family(addr_out) == AF_INET6)
00684         bits = 128;
00685     }
00686     *maskbits_out = (maskbits_t) bits;
00687   } else {
00688     if (mask) {
00689       log_warn(LD_GENERAL,
00690                "Unexpected mask in address %s; rejecting", escaped(s));
00691       goto err;
00692     }
00693   }
00694 
00695   /* Parse port(s) */
00696   if (port_min_out) {
00697     uint16_t port2;
00698     if (!port_max_out) /* caller specified one port; fake the second one */
00699       port_max_out = &port2;
00700 
00701     if (parse_port_range(port, port_min_out, port_max_out) < 0) {
00702       goto err;
00703     } else if ((*port_min_out != *port_max_out) && port_max_out == &port2) {
00704       log_warn(LD_GENERAL,
00705                "Wanted one port from address range, but there are two.");
00706 
00707       port_max_out = NULL;  /* caller specified one port, so set this back */
00708       goto err;
00709     }
00710   } else {
00711     if (port) {
00712       log_warn(LD_GENERAL,
00713                "Unexpected ports in address %s; rejecting", escaped(s));
00714       goto err;
00715     }
00716   }
00717 
00718   tor_free(base);
00719   return tor_addr_family(addr_out);
00720  err:
00721   tor_free(base);
00722   return -1;
00723 }
00724 
00730 int
00731 tor_addr_is_v4(const tor_addr_t *addr)
00732 {
00733   tor_assert(addr);
00734 
00735   if (tor_addr_family(addr) == AF_INET)
00736     return 1;
00737 
00738   if (tor_addr_family(addr) == AF_INET6) {
00739     /* First two don't need to be ordered */
00740     uint32_t *a32 = tor_addr_to_in6_addr32(addr);
00741     if (a32[0] == 0 && a32[1] == 0 && ntohl(a32[2]) == 0x0000ffffu)
00742       return 1;
00743   }
00744 
00745   return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */
00746 }
00747 
00751 int
00752 tor_addr_is_null(const tor_addr_t *addr)
00753 {
00754   tor_assert(addr);
00755 
00756   switch (tor_addr_family(addr)) {
00757     case AF_INET6: {
00758       uint32_t *a32 = tor_addr_to_in6_addr32(addr);
00759       return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 0);
00760     }
00761     case AF_INET:
00762       return (tor_addr_to_ipv4n(addr) == 0);
00763     case AF_UNSPEC:
00764       return 1;
00765     default:
00766       log_warn(LD_BUG, "Called with unknown address family %d",
00767                (int)tor_addr_family(addr));
00768       return 0;
00769   }
00770   //return 1;
00771 }
00772 
00774 int
00775 tor_addr_is_loopback(const tor_addr_t *addr)
00776 {
00777   tor_assert(addr);
00778   switch (tor_addr_family(addr)) {
00779     case AF_INET6: {
00780       /* ::1 */
00781       uint32_t *a32 = tor_addr_to_in6_addr32(addr);
00782       return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 1);
00783     }
00784     case AF_INET:
00785       /* 127.0.0.1 */
00786       return (tor_addr_to_ipv4h(addr) & 0xff000000) == 0x7f000000;
00787     case AF_UNSPEC:
00788       return 0;
00789     default:
00790       tor_fragile_assert();
00791       return 0;
00792   }
00793 }
00794 
00797 void
00798 tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
00799 {
00800   tor_assert(dest);
00801   memset(dest, 0, sizeof(tor_addr_t));
00802   dest->family = AF_INET;
00803   dest->addr.in_addr.s_addr = v4addr;
00804 }
00805 
00808 void
00809 tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
00810 {
00811   tor_assert(dest);
00812   tor_assert(ipv6_bytes);
00813   memset(dest, 0, sizeof(tor_addr_t));
00814   dest->family = AF_INET6;
00815   memcpy(dest->addr.in6_addr.s6_addr, ipv6_bytes, 16);
00816 }
00817 
00819 void
00820 tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
00821 {
00822   tor_addr_from_ipv6_bytes(dest, (const char*)in6->s6_addr);
00823 }
00824 
00827 void
00828 tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
00829 {
00830   if (src == dest)
00831     return;
00832   tor_assert(src);
00833   tor_assert(dest);
00834   memcpy(dest, src, sizeof(tor_addr_t));
00835 }
00836 
00845 int
00846 tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2,
00847                  tor_addr_comparison_t how)
00848 {
00849   return tor_addr_compare_masked(addr1, addr2, 128, how);
00850 }
00851 
00866 int
00867 tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2,
00868                         maskbits_t mbits, tor_addr_comparison_t how)
00869 {
00872 #define TRISTATE(a,b) (((a)<(b))?-1: (((a)==(b))?0:1))
00873   sa_family_t family1, family2, v_family1, v_family2;
00874 
00875   tor_assert(addr1 && addr2);
00876 
00877   v_family1 = family1 = tor_addr_family(addr1);
00878   v_family2 = family2 = tor_addr_family(addr2);
00879 
00880   if (family1==family2) {
00881     /* When the families are the same, there's only one way to do the
00882      * comparison: exactly. */
00883     int r;
00884     switch (family1) {
00885       case AF_UNSPEC:
00886         return 0; /* All unspecified addresses are equal */
00887       case AF_INET: {
00888         uint32_t a1 = tor_addr_to_ipv4h(addr1);
00889         uint32_t a2 = tor_addr_to_ipv4h(addr2);
00890         if (mbits <= 0)
00891           return 0;
00892         if (mbits > 32)
00893           mbits = 32;
00894         a1 >>= (32-mbits);
00895         a2 >>= (32-mbits);
00896         r = TRISTATE(a1, a2);
00897         return r;
00898       }
00899       case AF_INET6: {
00900         const uint8_t *a1 = tor_addr_to_in6_addr8(addr1);
00901         const uint8_t *a2 = tor_addr_to_in6_addr8(addr2);
00902         const int bytes = mbits >> 3;
00903         const int leftover_bits = mbits & 7;
00904         if (bytes && (r = tor_memcmp(a1, a2, bytes))) {
00905           return r;
00906         } else if (leftover_bits) {
00907           uint8_t b1 = a1[bytes] >> (8-leftover_bits);
00908           uint8_t b2 = a2[bytes] >> (8-leftover_bits);
00909           return TRISTATE(b1, b2);
00910         } else {
00911           return 0;
00912         }
00913       }
00914       default:
00915         tor_fragile_assert();
00916         return 0;
00917     }
00918   } else if (how == CMP_EXACT) {
00919     /* Unequal families and an exact comparison?  Stop now! */
00920     return TRISTATE(family1, family2);
00921   }
00922 
00923   if (mbits == 0)
00924     return 0;
00925 
00926   if (family1 == AF_INET6 && tor_addr_is_v4(addr1))
00927     v_family1 = AF_INET;
00928   if (family2 == AF_INET6 && tor_addr_is_v4(addr2))
00929     v_family2 = AF_INET;
00930   if (v_family1 == v_family2) {
00931     /* One or both addresses are a mapped ipv4 address. */
00932     uint32_t a1, a2;
00933     if (family1 == AF_INET6) {
00934       a1 = tor_addr_to_mapped_ipv4h(addr1);
00935       if (mbits <= 96)
00936         return 0;
00937       mbits -= 96; /* We just decided that the first 96 bits of a1 "match". */
00938     } else {
00939       a1 = tor_addr_to_ipv4h(addr1);
00940     }
00941     if (family2 == AF_INET6) {
00942       a2 = tor_addr_to_mapped_ipv4h(addr2);
00943     } else {
00944       a2 = tor_addr_to_ipv4h(addr2);
00945     }
00946     if (mbits <= 0) return 0;
00947     if (mbits > 32) mbits = 32;
00948     a1 >>= (32-mbits);
00949     a2 >>= (32-mbits);
00950     return TRISTATE(a1, a2);
00951   } else {
00952     /* Unequal families, and semantic comparison, and no semantic family
00953      * matches. */
00954     return TRISTATE(family1, family2);
00955   }
00956 }
00957 
00959 unsigned int
00960 tor_addr_hash(const tor_addr_t *addr)
00961 {
00962   switch (tor_addr_family(addr)) {
00963   case AF_INET:
00964     return tor_addr_to_ipv4h(addr);
00965   case AF_UNSPEC:
00966     return 0x4e4d5342;
00967   case AF_INET6: {
00968     const uint32_t *u = tor_addr_to_in6_addr32(addr);
00969     return u[0] + u[1] + u[2] + u[3];
00970     }
00971   default:
00972     tor_fragile_assert();
00973     return 0;
00974   }
00975 }
00976 
00978 char *
00979 tor_dup_addr(const tor_addr_t *addr)
00980 {
00981   char buf[TOR_ADDR_BUF_LEN];
00982   if (tor_addr_to_str(buf, addr, sizeof(buf), 0)) {
00983     return tor_strdup(buf);
00984   } else {
00985     return tor_strdup("<unknown address type>");
00986   }
00987 }
00988 
00998 const char *
00999 fmt_addr_impl(const tor_addr_t *addr, int decorate)
01000 {
01001   static char buf[TOR_ADDR_BUF_LEN];
01002   if (!addr) return "<null>";
01003   if (tor_addr_to_str(buf, addr, sizeof(buf), decorate))
01004     return buf;
01005   else
01006     return "???";
01007 }
01008 
01012 const char *
01013 fmt_addr32(uint32_t addr)
01014 {
01015   static char buf[INET_NTOA_BUF_LEN];
01016   struct in_addr in;
01017   in.s_addr = htonl(addr);
01018   tor_inet_ntoa(&in, buf, sizeof(buf));
01019   return buf;
01020 }
01021 
01028 int
01029 tor_addr_parse(tor_addr_t *addr, const char *src)
01030 {
01031   char *tmp = NULL; /* Holds substring if we got a dotted quad. */
01032   int result;
01033   struct in_addr in_tmp;
01034   struct in6_addr in6_tmp;
01035   tor_assert(addr && src);
01036   if (src[0] == '[' && src[1])
01037     src = tmp = tor_strndup(src+1, strlen(src)-2);
01038 
01039   if (tor_inet_pton(AF_INET6, src, &in6_tmp) > 0) {
01040     result = AF_INET6;
01041     tor_addr_from_in6(addr, &in6_tmp);
01042   } else if (tor_inet_pton(AF_INET, src, &in_tmp) > 0) {
01043     result = AF_INET;
01044     tor_addr_from_in(addr, &in_tmp);
01045   } else {
01046     result = -1;
01047   }
01048 
01049   tor_free(tmp);
01050   return result;
01051 }
01052 
01056 int
01057 tor_addr_port_lookup(const char *s, tor_addr_t *addr_out, uint16_t *port_out)
01058 {
01059   const char *port;
01060   tor_addr_t addr;
01061   uint16_t portval;
01062   char *tmp = NULL;
01063 
01064   tor_assert(s);
01065   tor_assert(addr_out);
01066 
01067   s = eat_whitespace(s);
01068 
01069   if (*s == '[') {
01070     port = strstr(s, "]");
01071     if (!port)
01072       goto err;
01073     tmp = tor_strndup(s+1, port-(s+1));
01074     port = port+1;
01075     if (*port == ':')
01076       port++;
01077     else
01078       port = NULL;
01079   } else {
01080     port = strchr(s, ':');
01081     if (port)
01082       tmp = tor_strndup(s, port-s);
01083     else
01084       tmp = tor_strdup(s);
01085     if (port)
01086       ++port;
01087   }
01088 
01089   if (tor_addr_lookup(tmp, AF_UNSPEC, &addr) != 0)
01090     goto err;
01091   tor_free(tmp);
01092 
01093   if (port) {
01094     portval = (int) tor_parse_long(port, 10, 1, 65535, NULL, NULL);
01095     if (!portval)
01096       goto err;
01097   } else {
01098     portval = 0;
01099   }
01100 
01101   if (port_out)
01102     *port_out = portval;
01103   tor_addr_copy(addr_out, &addr);
01104 
01105   return 0;
01106  err:
01107   tor_free(tmp);
01108   return -1;
01109 }
01110 
01111 #ifdef _WIN32
01112 typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)(
01113               ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
01114 #endif
01115 
01120 static smartlist_t *
01121 get_interface_addresses_raw(int severity)
01122 {
01123 #if defined(HAVE_GETIFADDRS)
01124   /* Most free Unixy systems provide getifaddrs, which gives us a linked list
01125    * of struct ifaddrs. */
01126   struct ifaddrs *ifa = NULL;
01127   const struct ifaddrs *i;
01128   smartlist_t *result;
01129   if (getifaddrs(&ifa) < 0) {
01130     log_fn(severity, LD_NET, "Unable to call getifaddrs(): %s",
01131            strerror(errno));
01132     return NULL;
01133   }
01134 
01135   result = smartlist_new();
01136   for (i = ifa; i; i = i->ifa_next) {
01137     tor_addr_t tmp;
01138     if (!i->ifa_addr)
01139       continue;
01140     if (i->ifa_addr->sa_family != AF_INET &&
01141         i->ifa_addr->sa_family != AF_INET6)
01142       continue;
01143     if (tor_addr_from_sockaddr(&tmp, i->ifa_addr, NULL) < 0)
01144       continue;
01145     smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
01146   }
01147 
01148   freeifaddrs(ifa);
01149   return result;
01150 #elif defined(_WIN32)
01151   /* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
01152      "GetAdaptersInfo", but that's deprecated; let's just try
01153      GetAdaptersAddresses and fall back to connect+getsockname.
01154   */
01155   HANDLE lib = load_windows_system_library(TEXT("iphlpapi.dll"));
01156   smartlist_t *result = NULL;
01157   GetAdaptersAddresses_fn_t fn;
01158   ULONG size, res;
01159   IP_ADAPTER_ADDRESSES *addresses = NULL, *address;
01160 
01161   (void) severity;
01162 
01163 #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
01164                GAA_FLAG_SKIP_MULTICAST | \
01165                GAA_FLAG_SKIP_DNS_SERVER)
01166 
01167   if (!lib) {
01168     log_fn(severity, LD_NET, "Unable to load iphlpapi.dll");
01169     goto done;
01170   }
01171 
01172   if (!(fn = (GetAdaptersAddresses_fn_t)
01173                   GetProcAddress(lib, "GetAdaptersAddresses"))) {
01174     log_fn(severity, LD_NET, "Unable to obtain pointer to "
01175            "GetAdaptersAddresses");
01176     goto done;
01177   }
01178 
01179   /* Guess how much space we need. */
01180   size = 15*1024;
01181   addresses = tor_malloc(size);
01182   res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
01183   if (res == ERROR_BUFFER_OVERFLOW) {
01184     /* we didn't guess that we needed enough space; try again */
01185     tor_free(addresses);
01186     addresses = tor_malloc(size);
01187     res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
01188   }
01189   if (res != NO_ERROR) {
01190     log_fn(severity, LD_NET, "GetAdaptersAddresses failed (result: %lu)", res);
01191     goto done;
01192   }
01193 
01194   result = smartlist_new();
01195   for (address = addresses; address; address = address->Next) {
01196     IP_ADAPTER_UNICAST_ADDRESS *a;
01197     for (a = address->FirstUnicastAddress; a; a = a->Next) {
01198       /* Yes, it's a linked list inside a linked list */
01199       struct sockaddr *sa = a->Address.lpSockaddr;
01200       tor_addr_t tmp;
01201       if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
01202         continue;
01203       if (tor_addr_from_sockaddr(&tmp, sa, NULL) < 0)
01204         continue;
01205       smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
01206     }
01207   }
01208 
01209  done:
01210   if (lib)
01211     FreeLibrary(lib);
01212   tor_free(addresses);
01213   return result;
01214 #elif defined(SIOCGIFCONF) && defined(HAVE_IOCTL)
01215   /* Some older unixy systems make us use ioctl(SIOCGIFCONF) */
01216   struct ifconf ifc;
01217   int fd, i, sz, n;
01218   smartlist_t *result = NULL;
01219   /* This interface, AFAICT, only supports AF_INET addresses */
01220   fd = socket(AF_INET, SOCK_DGRAM, 0);
01221   if (fd < 0) {
01222     log(severity, LD_NET, "socket failed: %s", strerror(errno));
01223     goto done;
01224   }
01225   /* Guess how much space we need. */
01226   ifc.ifc_len = sz = 15*1024;
01227   ifc.ifc_ifcu.ifcu_req = tor_malloc(sz);
01228   if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) {
01229     log(severity, LD_NET, "ioctl failed: %s", strerror(errno));
01230     close(fd);
01231     goto done;
01232   }
01233   close(fd);
01234   result = smartlist_new();
01235   if (ifc.ifc_len < sz)
01236     sz = ifc.ifc_len;
01237   n = sz / sizeof(struct ifreq);
01238   for (i = 0; i < n ; ++i) {
01239     struct ifreq *r = &ifc.ifc_ifcu.ifcu_req[i];
01240     struct sockaddr *sa = &r->ifr_addr;
01241     tor_addr_t tmp;
01242     if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
01243       continue; /* should be impossible */
01244     if (tor_addr_from_sockaddr(&tmp, sa, NULL) < 0)
01245       continue;
01246     smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
01247   }
01248  done:
01249   tor_free(ifc.ifc_ifcu.ifcu_req);
01250   return result;
01251 #else
01252   (void) severity;
01253   return NULL;
01254 #endif
01255 }
01256 
01258 static int
01259 tor_addr_is_multicast(const tor_addr_t *a)
01260 {
01261   sa_family_t family = tor_addr_family(a);
01262   if (family == AF_INET) {
01263     uint32_t ipv4h = tor_addr_to_ipv4h(a);
01264     if ((ipv4h >> 24) == 0xe0)
01265       return 1; /* Multicast */
01266   } else if (family == AF_INET6) {
01267     const uint8_t *a32 = tor_addr_to_in6_addr8(a);
01268     if (a32[0] == 0xff)
01269       return 1;
01270   }
01271   return 0;
01272 }
01273 
01278 int
01279 get_interface_address6(int severity, sa_family_t family, tor_addr_t *addr)
01280 {
01281   /* XXX really, this function should yield a smartlist of addresses. */
01282   smartlist_t *addrs;
01283   int sock=-1, r=-1;
01284   struct sockaddr_storage my_addr, target_addr;
01285   socklen_t addr_len;
01286   tor_assert(addr);
01287 
01288   /* Try to do this the smart way if possible. */
01289   if ((addrs = get_interface_addresses_raw(severity))) {
01290     int rv = -1;
01291     SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a) {
01292       if (family != AF_UNSPEC && family != tor_addr_family(a))
01293         continue;
01294       if (tor_addr_is_loopback(a) ||
01295           tor_addr_is_multicast(a))
01296         continue;
01297 
01298       tor_addr_copy(addr, a);
01299       rv = 0;
01300 
01301       /* If we found a non-internal address, declare success.  Otherwise,
01302        * keep looking. */
01303       if (!tor_addr_is_internal(a, 0))
01304         break;
01305     } SMARTLIST_FOREACH_END(a);
01306 
01307     SMARTLIST_FOREACH(addrs, tor_addr_t *, a, tor_free(a));
01308     smartlist_free(addrs);
01309     return rv;
01310   }
01311 
01312   /* Okay, the smart way is out. */
01313   memset(addr, 0, sizeof(tor_addr_t));
01314   memset(&target_addr, 0, sizeof(target_addr));
01315   /* Don't worry: no packets are sent. We just need to use a real address
01316    * on the actual Internet. */
01317   if (family == AF_INET6) {
01318     struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&target_addr;
01319     /* Use the "discard" service port */
01320     sin6->sin6_port = htons(9);
01321     sock = tor_open_socket(PF_INET6,SOCK_DGRAM,IPPROTO_UDP);
01322     addr_len = (socklen_t)sizeof(struct sockaddr_in6);
01323     sin6->sin6_family = AF_INET6;
01324     S6_ADDR16(sin6->sin6_addr)[0] = htons(0x2002); /* 2002:: */
01325   } else if (family == AF_INET) {
01326     struct sockaddr_in *sin = (struct sockaddr_in*)&target_addr;
01327     /* Use the "discard" service port */
01328     sin->sin_port = htons(9);
01329     sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
01330     addr_len = (socklen_t)sizeof(struct sockaddr_in);
01331     sin->sin_family = AF_INET;
01332     sin->sin_addr.s_addr = htonl(0x12000001); /* 18.0.0.1 */
01333   } else {
01334     return -1;
01335   }
01336   if (sock < 0) {
01337     int e = tor_socket_errno(-1);
01338     log_fn(severity, LD_NET, "unable to create socket: %s",
01339            tor_socket_strerror(e));
01340     goto err;
01341   }
01342 
01343   if (connect(sock,(struct sockaddr *)&target_addr, addr_len) < 0) {
01344     int e = tor_socket_errno(sock);
01345     log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e));
01346     goto err;
01347   }
01348 
01349   if (getsockname(sock,(struct sockaddr*)&my_addr, &addr_len)) {
01350     int e = tor_socket_errno(sock);
01351     log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s",
01352            tor_socket_strerror(e));
01353     goto err;
01354   }
01355 
01356   tor_addr_from_sockaddr(addr, (struct sockaddr*)&my_addr, NULL);
01357   r=0;
01358  err:
01359   if (sock >= 0)
01360     tor_close_socket(sock);
01361   return r;
01362 }
01363 
01364 /* ======
01365  * IPv4 helpers
01366  * XXXX024 IPv6 deprecate some of these.
01367  */
01368 
01372 int
01373 is_internal_IP(uint32_t ip, int for_listening)
01374 {
01375   tor_addr_t myaddr;
01376   myaddr.family = AF_INET;
01377   myaddr.addr.in_addr.s_addr = htonl(ip);
01378 
01379   return tor_addr_is_internal(&myaddr, for_listening);
01380 }
01381 
01386 int
01387 tor_addr_port_split(int severity, const char *addrport,
01388                     char **address_out, uint16_t *port_out)
01389 {
01390   tor_assert(addrport);
01391   tor_assert(address_out);
01392   tor_assert(port_out);
01393   return addr_port_lookup(severity, addrport, address_out, NULL, port_out);
01394 }
01395 
01406 int
01407 addr_port_lookup(int severity, const char *addrport, char **address,
01408                 uint32_t *addr, uint16_t *port_out)
01409 {
01410   const char *colon;
01411   char *_address = NULL;
01412   int _port;
01413   int ok = 1;
01414 
01415   tor_assert(addrport);
01416 
01417   colon = strrchr(addrport, ':');
01418   if (colon) {
01419     _address = tor_strndup(addrport, colon-addrport);
01420     _port = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
01421     if (!_port) {
01422       log_fn(severity, LD_GENERAL, "Port %s out of range", escaped(colon+1));
01423       ok = 0;
01424     }
01425     if (!port_out) {
01426       char *esc_addrport = esc_for_log(addrport);
01427       log_fn(severity, LD_GENERAL,
01428              "Port %s given on %s when not required",
01429              escaped(colon+1), esc_addrport);
01430       tor_free(esc_addrport);
01431       ok = 0;
01432     }
01433   } else {
01434     _address = tor_strdup(addrport);
01435     _port = 0;
01436   }
01437 
01438   if (addr) {
01439     /* There's an addr pointer, so we need to resolve the hostname. */
01440     if (tor_lookup_hostname(_address,addr)) {
01441       log_fn(severity, LD_NET, "Couldn't look up %s", escaped(_address));
01442       ok = 0;
01443       *addr = 0;
01444     }
01445   }
01446 
01447   if (address && ok) {
01448     *address = _address;
01449   } else {
01450     if (address)
01451       *address = NULL;
01452     tor_free(_address);
01453   }
01454   if (port_out)
01455     *port_out = ok ? ((uint16_t) _port) : 0;
01456 
01457   return ok ? 0 : -1;
01458 }
01459 
01462 int
01463 addr_mask_get_bits(uint32_t mask)
01464 {
01465   int i;
01466   if (mask == 0)
01467     return 0;
01468   if (mask == 0xFFFFFFFFu)
01469     return 32;
01470   for (i=0; i<=32; ++i) {
01471     if (mask == (uint32_t) ~((1u<<(32-i))-1)) {
01472       return i;
01473     }
01474   }
01475   return -1;
01476 }
01477 
01485 int
01486 addr_mask_cmp_bits(uint32_t a1, uint32_t a2, maskbits_t bits)
01487 {
01488   if (bits > 32)
01489     bits = 32;
01490   else if (bits == 0)
01491     return 0;
01492 
01493   a1 >>= (32-bits);
01494   a2 >>= (32-bits);
01495 
01496   if (a1 < a2)
01497     return -1;
01498   else if (a1 > a2)
01499     return 1;
01500   else
01501     return 0;
01502 }
01503 
01507 int
01508 parse_port_range(const char *port, uint16_t *port_min_out,
01509                  uint16_t *port_max_out)
01510 {
01511   int port_min, port_max, ok;
01512   tor_assert(port_min_out);
01513   tor_assert(port_max_out);
01514 
01515   if (!port || *port == '\0' || strcmp(port, "*") == 0) {
01516     port_min = 1;
01517     port_max = 65535;
01518   } else {
01519     char *endptr = NULL;
01520     port_min = (int)tor_parse_long(port, 10, 0, 65535, &ok, &endptr);
01521     if (!ok) {
01522       log_warn(LD_GENERAL,
01523                "Malformed port %s on address range; rejecting.",
01524                escaped(port));
01525       return -1;
01526     } else if (endptr && *endptr == '-') {
01527       port = endptr+1;
01528       endptr = NULL;
01529       port_max = (int)tor_parse_long(port, 10, 1, 65535, &ok, &endptr);
01530       if (!ok) {
01531         log_warn(LD_GENERAL,
01532                  "Malformed port %s on address range; rejecting.",
01533                  escaped(port));
01534         return -1;
01535       }
01536     } else {
01537       port_max = port_min;
01538     }
01539     if (port_min > port_max) {
01540       log_warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
01541       return -1;
01542     }
01543   }
01544 
01545   if (port_min < 1)
01546     port_min = 1;
01547   if (port_max > 65535)
01548     port_max = 65535;
01549 
01550   *port_min_out = (uint16_t) port_min;
01551   *port_max_out = (uint16_t) port_max;
01552 
01553   return 0;
01554 }
01555 
01560 int
01561 parse_addr_and_port_range(const char *s, uint32_t *addr_out,
01562                           maskbits_t *maskbits_out, uint16_t *port_min_out,
01563                           uint16_t *port_max_out)
01564 {
01565   char *address;
01566   char *mask, *port, *endptr;
01567   struct in_addr in;
01568   int bits;
01569 
01570   tor_assert(s);
01571   tor_assert(addr_out);
01572   tor_assert(maskbits_out);
01573   tor_assert(port_min_out);
01574   tor_assert(port_max_out);
01575 
01576   address = tor_strdup(s);
01577   /* Break 'address' into separate strings.
01578    */
01579   mask = strchr(address,'/');
01580   port = strchr(mask?mask:address,':');
01581   if (mask)
01582     *mask++ = '\0';
01583   if (port)
01584     *port++ = '\0';
01585   /* Now "address" is the IP|'*' part...
01586    *     "mask" is the Mask|Maskbits part...
01587    * and "port" is the *|port|min-max part.
01588    */
01589 
01590   if (strcmp(address,"*")==0) {
01591     *addr_out = 0;
01592   } else if (tor_inet_aton(address, &in) != 0) {
01593     *addr_out = ntohl(in.s_addr);
01594   } else {
01595     log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
01596              escaped(address));
01597     goto err;
01598   }
01599 
01600   if (!mask) {
01601     if (strcmp(address,"*")==0)
01602       *maskbits_out = 0;
01603     else
01604       *maskbits_out = 32;
01605   } else {
01606     endptr = NULL;
01607     bits = (int) strtol(mask, &endptr, 10);
01608     if (!*endptr) {
01609       /* strtol handled the whole mask. */
01610       if (bits < 0 || bits > 32) {
01611         log_warn(LD_GENERAL,
01612                  "Bad number of mask bits on address range; rejecting.");
01613         goto err;
01614       }
01615       *maskbits_out = bits;
01616     } else if (tor_inet_aton(mask, &in) != 0) {
01617       bits = addr_mask_get_bits(ntohl(in.s_addr));
01618       if (bits < 0) {
01619         log_warn(LD_GENERAL,
01620                  "Mask %s on address range isn't a prefix; dropping",
01621                  escaped(mask));
01622         goto err;
01623       }
01624       *maskbits_out = bits;
01625     } else {
01626       log_warn(LD_GENERAL,
01627                "Malformed mask %s on address range; rejecting.",
01628                escaped(mask));
01629       goto err;
01630     }
01631   }
01632 
01633   if (parse_port_range(port, port_min_out, port_max_out)<0)
01634     goto err;
01635 
01636   tor_free(address);
01637   return 0;
01638  err:
01639   tor_free(address);
01640   return -1;
01641 }
01642 
01647 int
01648 tor_inet_ntoa(const struct in_addr *in, char *buf, size_t buf_len)
01649 {
01650   uint32_t a = ntohl(in->s_addr);
01651   return tor_snprintf(buf, buf_len, "%d.%d.%d.%d",
01652                       (int)(uint8_t)((a>>24)&0xff),
01653                       (int)(uint8_t)((a>>16)&0xff),
01654                       (int)(uint8_t)((a>>8 )&0xff),
01655                       (int)(uint8_t)((a    )&0xff));
01656 }
01657 
01661 char *
01662 tor_dup_ip(uint32_t addr)
01663 {
01664   char buf[TOR_ADDR_BUF_LEN];
01665   struct in_addr in;
01666 
01667   in.s_addr = htonl(addr);
01668   tor_inet_ntop(AF_INET, &in, buf, sizeof(buf));
01669   return tor_strdup(buf);
01670 }
01671 
01678 int
01679 get_interface_address(int severity, uint32_t *addr)
01680 {
01681   tor_addr_t local_addr;
01682   int r;
01683 
01684   r = get_interface_address6(severity, AF_INET, &local_addr);
01685   if (r>=0)
01686     *addr = tor_addr_to_ipv4h(&local_addr);
01687   return r;
01688 }
01689 
01692 int
01693 tor_addr_hostname_is_local(const char *name)
01694 {
01695   return !strcasecmp(name, "localhost") ||
01696     !strcasecmp(name, "local") ||
01697     !strcasecmpend(name, ".local");
01698 }
01699