address.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2011, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file address.c
  7. * \brief Functions to use and manipulate the tor_addr_t structure.
  8. **/
  9. #include "orconfig.h"
  10. #include "compat.h"
  11. #include "util.h"
  12. #include "address.h"
  13. #include "torlog.h"
  14. #ifdef MS_WINDOWS
  15. #include <process.h>
  16. #include <windows.h>
  17. #endif
  18. #ifdef HAVE_SYS_TIME_H
  19. #include <sys/time.h>
  20. #endif
  21. #ifdef HAVE_UNISTD_H
  22. #include <unistd.h>
  23. #endif
  24. #ifdef HAVE_ERRNO_H
  25. #include <errno.h>
  26. #endif
  27. #ifdef HAVE_NETINET_IN_H
  28. #include <netinet/in.h>
  29. #endif
  30. #ifdef HAVE_ARPA_INET_H
  31. #include <arpa/inet.h>
  32. #endif
  33. #ifdef HAVE_SYS_SOCKET_H
  34. #include <sys/socket.h>
  35. #endif
  36. #ifdef HAVE_NETDB_H
  37. #include <netdb.h>
  38. #endif
  39. #ifdef HAVE_SYS_PARAM_H
  40. #include <sys/param.h> /* FreeBSD needs this to know what version it is */
  41. #endif
  42. #include <stdarg.h>
  43. #include <stdio.h>
  44. #include <stdlib.h>
  45. #include <string.h>
  46. #include <assert.h>
  47. /** Convert the tor_addr_t in <b>a</b>, with port in <b>port</b>, into a
  48. * socklen object in *<b>sa_out</b> of object size <b>len</b>. If not enough
  49. * room is free, or on error, return -1. Else return the length of the
  50. * sockaddr. */
  51. int
  52. tor_addr_to_sockaddr(const tor_addr_t *a,
  53. uint16_t port,
  54. struct sockaddr *sa_out,
  55. socklen_t len)
  56. {
  57. sa_family_t family = tor_addr_family(a);
  58. if (family == AF_INET) {
  59. struct sockaddr_in *sin;
  60. if (len < (int)sizeof(struct sockaddr_in))
  61. return -1;
  62. sin = (struct sockaddr_in *)sa_out;
  63. memset(sin, 0, sizeof(struct sockaddr_in));
  64. #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
  65. sin->sin_len = sizeof(struct sockaddr_in);
  66. #endif
  67. sin->sin_family = AF_INET;
  68. sin->sin_port = htons(port);
  69. sin->sin_addr.s_addr = tor_addr_to_ipv4n(a);
  70. return sizeof(struct sockaddr_in);
  71. } else if (family == AF_INET6) {
  72. struct sockaddr_in6 *sin6;
  73. if (len < (int)sizeof(struct sockaddr_in6))
  74. return -1;
  75. sin6 = (struct sockaddr_in6 *)sa_out;
  76. memset(sin6, 0, sizeof(struct sockaddr_in6));
  77. #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
  78. sin6->sin6_len = sizeof(struct sockaddr_in6);
  79. #endif
  80. sin6->sin6_family = AF_INET6;
  81. sin6->sin6_port = htons(port);
  82. memcpy(&sin6->sin6_addr, tor_addr_to_in6(a), sizeof(struct in6_addr));
  83. return sizeof(struct sockaddr_in6);
  84. } else {
  85. return -1;
  86. }
  87. }
  88. /** Set the tor_addr_t in <b>a</b> to contain the socket address contained in
  89. * <b>sa</b>. */
  90. int
  91. tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa,
  92. uint16_t *port_out)
  93. {
  94. tor_assert(a);
  95. tor_assert(sa);
  96. if (sa->sa_family == AF_INET) {
  97. struct sockaddr_in *sin = (struct sockaddr_in *) sa;
  98. tor_addr_from_ipv4n(a, sin->sin_addr.s_addr);
  99. if (port_out)
  100. *port_out = ntohs(sin->sin_port);
  101. } else if (sa->sa_family == AF_INET6) {
  102. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
  103. tor_addr_from_in6(a, &sin6->sin6_addr);
  104. if (port_out)
  105. *port_out = ntohs(sin6->sin6_port);
  106. } else {
  107. tor_addr_make_unspec(a);
  108. return -1;
  109. }
  110. return 0;
  111. }
  112. /** Set address <b>a</b> to the unspecified address. This address belongs to
  113. * no family. */
  114. void
  115. tor_addr_make_unspec(tor_addr_t *a)
  116. {
  117. memset(a, 0, sizeof(*a));
  118. a->family = AF_UNSPEC;
  119. }
  120. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  121. * *<b>addr</b> to the proper IP address and family. The <b>family</b>
  122. * argument (which must be AF_INET, AF_INET6, or AF_UNSPEC) declares a
  123. * <i>preferred</i> family, though another one may be returned if only one
  124. * family is implemented for this address.
  125. *
  126. * Return 0 on success, -1 on failure; 1 on transient failure.
  127. */
  128. int
  129. tor_addr_lookup(const char *name, uint16_t family, tor_addr_t *addr)
  130. {
  131. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  132. * something.
  133. */
  134. struct in_addr iaddr;
  135. struct in6_addr iaddr6;
  136. tor_assert(name);
  137. tor_assert(addr);
  138. tor_assert(family == AF_INET || family == AF_INET6 || family == AF_UNSPEC);
  139. if (!*name) {
  140. /* Empty address is an error. */
  141. return -1;
  142. } else if (tor_inet_pton(AF_INET, name, &iaddr)) {
  143. /* It's an IPv4 IP. */
  144. if (family == AF_INET6)
  145. return -1;
  146. tor_addr_from_in(addr, &iaddr);
  147. return 0;
  148. } else if (tor_inet_pton(AF_INET6, name, &iaddr6)) {
  149. if (family == AF_INET)
  150. return -1;
  151. tor_addr_from_in6(addr, &iaddr6);
  152. return 0;
  153. } else {
  154. #ifdef HAVE_GETADDRINFO
  155. int err;
  156. struct addrinfo *res=NULL, *res_p;
  157. struct addrinfo *best=NULL;
  158. struct addrinfo hints;
  159. int result = -1;
  160. memset(&hints, 0, sizeof(hints));
  161. hints.ai_family = family;
  162. hints.ai_socktype = SOCK_STREAM;
  163. err = getaddrinfo(name, NULL, &hints, &res);
  164. if (!err) {
  165. best = NULL;
  166. for (res_p = res; res_p; res_p = res_p->ai_next) {
  167. if (family == AF_UNSPEC) {
  168. if (res_p->ai_family == AF_INET) {
  169. best = res_p;
  170. break;
  171. } else if (res_p->ai_family == AF_INET6 && !best) {
  172. best = res_p;
  173. }
  174. } else if (family == res_p->ai_family) {
  175. best = res_p;
  176. break;
  177. }
  178. }
  179. if (!best)
  180. best = res;
  181. if (best->ai_family == AF_INET) {
  182. tor_addr_from_in(addr,
  183. &((struct sockaddr_in*)best->ai_addr)->sin_addr);
  184. result = 0;
  185. } else if (best->ai_family == AF_INET6) {
  186. tor_addr_from_in6(addr,
  187. &((struct sockaddr_in6*)best->ai_addr)->sin6_addr);
  188. result = 0;
  189. }
  190. freeaddrinfo(res);
  191. return result;
  192. }
  193. return (err == EAI_AGAIN) ? 1 : -1;
  194. #else
  195. struct hostent *ent;
  196. int err;
  197. #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
  198. char buf[2048];
  199. struct hostent hostent;
  200. int r;
  201. r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err);
  202. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  203. char buf[2048];
  204. struct hostent hostent;
  205. ent = gethostbyname_r(name, &hostent, buf, sizeof(buf), &err);
  206. #elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
  207. struct hostent_data data;
  208. struct hostent hent;
  209. memset(&data, 0, sizeof(data));
  210. err = gethostbyname_r(name, &hent, &data);
  211. ent = err ? NULL : &hent;
  212. #else
  213. ent = gethostbyname(name);
  214. #ifdef MS_WINDOWS
  215. err = WSAGetLastError();
  216. #else
  217. err = h_errno;
  218. #endif
  219. #endif /* endif HAVE_GETHOSTBYNAME_R_6_ARG. */
  220. if (ent) {
  221. if (ent->h_addrtype == AF_INET) {
  222. tor_addr_from_in(addr, (struct in_addr*) ent->h_addr);
  223. } else if (ent->h_addrtype == AF_INET6) {
  224. tor_addr_from_in6(addr, (struct in6_addr*) ent->h_addr);
  225. } else {
  226. tor_assert(0); /* gethostbyname() returned a bizarre addrtype */
  227. }
  228. return 0;
  229. }
  230. #ifdef MS_WINDOWS
  231. return (err == WSATRY_AGAIN) ? 1 : -1;
  232. #else
  233. return (err == TRY_AGAIN) ? 1 : -1;
  234. #endif
  235. #endif
  236. }
  237. }
  238. /** Return true iff <b>ip</b> is an IP reserved to localhost or local networks
  239. * in RFC1918 or RFC4193 or RFC4291. (fec0::/10, deprecated by RFC3879, is
  240. * also treated as internal for now.)
  241. */
  242. int
  243. tor_addr_is_internal(const tor_addr_t *addr, int for_listening)
  244. {
  245. uint32_t iph4 = 0;
  246. uint32_t iph6[4];
  247. sa_family_t v_family;
  248. v_family = tor_addr_family(addr);
  249. if (v_family == AF_INET) {
  250. iph4 = tor_addr_to_ipv4h(addr);
  251. } else if (v_family == AF_INET6) {
  252. if (tor_addr_is_v4(addr)) { /* v4-mapped */
  253. v_family = AF_INET;
  254. iph4 = ntohl(tor_addr_to_in6_addr32(addr)[3]);
  255. }
  256. }
  257. if (v_family == AF_INET6) {
  258. const uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  259. iph6[0] = ntohl(a32[0]);
  260. iph6[1] = ntohl(a32[1]);
  261. iph6[2] = ntohl(a32[2]);
  262. iph6[3] = ntohl(a32[3]);
  263. if (for_listening && !iph6[0] && !iph6[1] && !iph6[2] && !iph6[3]) /* :: */
  264. return 0;
  265. if (((iph6[0] & 0xfe000000) == 0xfc000000) || /* fc00/7 - RFC4193 */
  266. ((iph6[0] & 0xffc00000) == 0xfe800000) || /* fe80/10 - RFC4291 */
  267. ((iph6[0] & 0xffc00000) == 0xfec00000)) /* fec0/10 D- RFC3879 */
  268. return 1;
  269. if (!iph6[0] && !iph6[1] && !iph6[2] &&
  270. ((iph6[3] & 0xfffffffe) == 0x00000000)) /* ::/127 */
  271. return 1;
  272. return 0;
  273. } else if (v_family == AF_INET) {
  274. if (for_listening && !iph4) /* special case for binding to 0.0.0.0 */
  275. return 0;
  276. if (((iph4 & 0xff000000) == 0x0a000000) || /* 10/8 */
  277. ((iph4 & 0xff000000) == 0x00000000) || /* 0/8 */
  278. ((iph4 & 0xff000000) == 0x7f000000) || /* 127/8 */
  279. ((iph4 & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  280. ((iph4 & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  281. ((iph4 & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  282. return 1;
  283. return 0;
  284. }
  285. /* unknown address family... assume it's not safe for external use */
  286. /* rather than tor_assert(0) */
  287. log_warn(LD_BUG, "tor_addr_is_internal() called with a non-IP address.");
  288. return 1;
  289. }
  290. /** Convert a tor_addr_t <b>addr</b> into a string, and store it in
  291. * <b>dest</b> of size <b>len</b>. Returns a pointer to dest on success,
  292. * or NULL on failure. If <b>decorate</b>, surround IPv6 addresses with
  293. * brackets.
  294. */
  295. const char *
  296. tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
  297. {
  298. const char *ptr;
  299. tor_assert(addr && dest);
  300. switch (tor_addr_family(addr)) {
  301. case AF_INET:
  302. if (len<3)
  303. return NULL;
  304. ptr = tor_inet_ntop(AF_INET, &addr->addr.in_addr, dest, len);
  305. break;
  306. case AF_INET6:
  307. if (decorate)
  308. ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest+1, len-2);
  309. else
  310. ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest, len);
  311. if (ptr && decorate) {
  312. *dest = '[';
  313. memcpy(dest+strlen(dest), "]", 2);
  314. tor_assert(ptr == dest+1);
  315. ptr = dest;
  316. }
  317. break;
  318. default:
  319. return NULL;
  320. }
  321. return ptr;
  322. }
  323. /** Parse an .in-addr.arpa or .ip6.arpa address from <b>address</b>. Return 0
  324. * if this is not an .in-addr.arpa address or an .ip6.arpa address. Return -1
  325. * if this is an ill-formed .in-addr.arpa address or an .ip6.arpa address.
  326. * Also return -1 if <b>family</b> is not AF_UNSPEC, and the parsed address
  327. * family does not match <b>family</b>. On success, return 1, and store the
  328. * result, if any, into <b>result</b>, if provided.
  329. *
  330. * If <b>accept_regular</b> is set and the address is in neither recognized
  331. * reverse lookup hostname format, try parsing the address as a regular
  332. * IPv4 or IPv6 address too.
  333. */
  334. int
  335. tor_addr_parse_reverse_lookup_name(tor_addr_t *result, const char *address,
  336. int family, int accept_regular)
  337. {
  338. if (!strcasecmpend(address, ".in-addr.arpa")) {
  339. /* We have an in-addr.arpa address. */
  340. char buf[INET_NTOA_BUF_LEN];
  341. size_t len;
  342. struct in_addr inaddr;
  343. if (family == AF_INET6)
  344. return -1;
  345. len = strlen(address) - strlen(".in-addr.arpa");
  346. if (len >= INET_NTOA_BUF_LEN)
  347. return -1; /* Too long. */
  348. memcpy(buf, address, len);
  349. buf[len] = '\0';
  350. if (tor_inet_aton(buf, &inaddr) == 0)
  351. return -1; /* malformed. */
  352. /* reverse the bytes */
  353. inaddr.s_addr = (uint32_t)
  354. (((inaddr.s_addr & 0x000000ff) << 24)
  355. |((inaddr.s_addr & 0x0000ff00) << 8)
  356. |((inaddr.s_addr & 0x00ff0000) >> 8)
  357. |((inaddr.s_addr & 0xff000000) >> 24));
  358. if (result) {
  359. tor_addr_from_in(result, &inaddr);
  360. }
  361. return 1;
  362. }
  363. if (!strcasecmpend(address, ".ip6.arpa")) {
  364. const char *cp;
  365. int i;
  366. int n0, n1;
  367. struct in6_addr in6;
  368. if (family == AF_INET)
  369. return -1;
  370. cp = address;
  371. for (i = 0; i < 16; ++i) {
  372. n0 = hex_decode_digit(*cp++); /* The low-order nybble appears first. */
  373. if (*cp++ != '.') return -1; /* Then a dot. */
  374. n1 = hex_decode_digit(*cp++); /* The high-order nybble appears first. */
  375. if (*cp++ != '.') return -1; /* Then another dot. */
  376. if (n0<0 || n1 < 0) /* Both nybbles must be hex. */
  377. return -1;
  378. /* We don't check the length of the string in here. But that's okay,
  379. * since we already know that the string ends with ".ip6.arpa", and
  380. * there is no way to frameshift .ip6.arpa so it fits into the pattern
  381. * of hexdigit, period, hexdigit, period that we enforce above.
  382. */
  383. /* Assign from low-byte to high-byte. */
  384. in6.s6_addr[15-i] = n0 | (n1 << 4);
  385. }
  386. if (strcasecmp(cp, "ip6.arpa"))
  387. return -1;
  388. if (result) {
  389. tor_addr_from_in6(result, &in6);
  390. }
  391. return 1;
  392. }
  393. if (accept_regular) {
  394. tor_addr_t tmp;
  395. int r = tor_addr_from_str(&tmp, address);
  396. if (r < 0)
  397. return 0;
  398. if (r != family && family != AF_UNSPEC)
  399. return -1;
  400. if (result)
  401. memcpy(result, &tmp, sizeof(tor_addr_t));
  402. return 1;
  403. }
  404. return 0;
  405. }
  406. /** Convert <b>addr</b> to an in-addr.arpa name or a .ip6.arpa name, and store
  407. * the result in the <b>outlen</b>-byte buffer at <b>out</b>. Return 0 on
  408. * success, -1 on failure. */
  409. int
  410. tor_addr_to_reverse_lookup_name(char *out, size_t outlen,
  411. const tor_addr_t *addr)
  412. {
  413. if (addr->family == AF_INET) {
  414. uint32_t a = tor_addr_to_ipv4h(addr);
  415. return tor_snprintf(out, outlen, "%d.%d.%d.%d.in-addr.arpa",
  416. (int)(uint8_t)((a )&0xff),
  417. (int)(uint8_t)((a>>8 )&0xff),
  418. (int)(uint8_t)((a>>16)&0xff),
  419. (int)(uint8_t)((a>>24)&0xff));
  420. } else if (addr->family == AF_INET6) {
  421. int i;
  422. char *cp = out;
  423. const uint8_t *bytes = tor_addr_to_in6_addr8(addr);
  424. if (outlen < REVERSE_LOOKUP_NAME_BUF_LEN)
  425. return -1;
  426. for (i = 15; i >= 0; --i) {
  427. uint8_t byte = bytes[i];
  428. *cp++ = "0123456789abcdef"[byte & 0x0f];
  429. *cp++ = '.';
  430. *cp++ = "0123456789abcdef"[byte >> 4];
  431. *cp++ = '.';
  432. }
  433. memcpy(cp, "ip6.arpa", 9); /* 8 characters plus NUL */
  434. return 0;
  435. }
  436. return -1;
  437. }
  438. /** Parse a string <b>s</b> containing an IPv4/IPv6 address, and possibly
  439. * a mask and port or port range. Store the parsed address in
  440. * <b>addr_out</b>, a mask (if any) in <b>mask_out</b>, and port(s) (if any)
  441. * in <b>port_min_out</b> and <b>port_max_out</b>.
  442. *
  443. * The syntax is:
  444. * Address OptMask OptPortRange
  445. * Address ::= IPv4Address / "[" IPv6Address "]" / "*"
  446. * OptMask ::= "/" Integer /
  447. * OptPortRange ::= ":*" / ":" Integer / ":" Integer "-" Integer /
  448. *
  449. * - If mask, minport, or maxport are NULL, we do not want these
  450. * options to be set; treat them as an error if present.
  451. * - If the string has no mask, the mask is set to /32 (IPv4) or /128 (IPv6).
  452. * - If the string has one port, it is placed in both min and max port
  453. * variables.
  454. * - If the string has no port(s), port_(min|max)_out are set to 1 and 65535.
  455. *
  456. * Return an address family on success, or -1 if an invalid address string is
  457. * provided.
  458. */
  459. int
  460. tor_addr_parse_mask_ports(const char *s, tor_addr_t *addr_out,
  461. maskbits_t *maskbits_out,
  462. uint16_t *port_min_out, uint16_t *port_max_out)
  463. {
  464. char *base = NULL, *address, *mask = NULL, *port = NULL, *rbracket = NULL;
  465. char *endptr;
  466. int any_flag=0, v4map=0;
  467. sa_family_t family;
  468. struct in6_addr in6_tmp;
  469. struct in_addr in_tmp;
  470. tor_assert(s);
  471. tor_assert(addr_out);
  472. /** Longest possible length for an address, mask, and port-range combination.
  473. * Includes IP, [], /mask, :, ports */
  474. #define MAX_ADDRESS_LENGTH (TOR_ADDR_BUF_LEN+2+(1+INET_NTOA_BUF_LEN)+12+1)
  475. if (strlen(s) > MAX_ADDRESS_LENGTH) {
  476. log_warn(LD_GENERAL, "Impossibly long IP %s; rejecting", escaped(s));
  477. goto err;
  478. }
  479. base = tor_strdup(s);
  480. /* Break 'base' into separate strings. */
  481. address = base;
  482. if (*address == '[') { /* Probably IPv6 */
  483. address++;
  484. rbracket = strchr(address, ']');
  485. if (!rbracket) {
  486. log_warn(LD_GENERAL,
  487. "No closing IPv6 bracket in address pattern; rejecting.");
  488. goto err;
  489. }
  490. }
  491. mask = strchr((rbracket?rbracket:address),'/');
  492. port = strchr((mask?mask:(rbracket?rbracket:address)), ':');
  493. if (port)
  494. *port++ = '\0';
  495. if (mask)
  496. *mask++ = '\0';
  497. if (rbracket)
  498. *rbracket = '\0';
  499. if (port && mask)
  500. tor_assert(port > mask);
  501. if (mask && rbracket)
  502. tor_assert(mask > rbracket);
  503. /* Now "address" is the a.b.c.d|'*'|abcd::1 part...
  504. * "mask" is the Mask|Maskbits part...
  505. * and "port" is the *|port|min-max part.
  506. */
  507. /* Process the address portion */
  508. memset(addr_out, 0, sizeof(tor_addr_t));
  509. if (!strcmp(address, "*")) {
  510. family = AF_INET; /* AF_UNSPEC ???? XXXX_IP6 */
  511. tor_addr_from_ipv4h(addr_out, 0);
  512. any_flag = 1;
  513. } else if (tor_inet_pton(AF_INET6, address, &in6_tmp) > 0) {
  514. family = AF_INET6;
  515. tor_addr_from_in6(addr_out, &in6_tmp);
  516. } else if (tor_inet_pton(AF_INET, address, &in_tmp) > 0) {
  517. family = AF_INET;
  518. tor_addr_from_in(addr_out, &in_tmp);
  519. } else {
  520. log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
  521. escaped(address));
  522. goto err;
  523. }
  524. v4map = tor_addr_is_v4(addr_out);
  525. /* Parse mask */
  526. if (maskbits_out) {
  527. int bits = 0;
  528. struct in_addr v4mask;
  529. if (mask) { /* the caller (tried to) specify a mask */
  530. bits = (int) strtol(mask, &endptr, 10);
  531. if (!*endptr) { /* strtol converted everything, so it was an integer */
  532. if ((bits<0 || bits>128) ||
  533. (family == AF_INET && bits > 32)) {
  534. log_warn(LD_GENERAL,
  535. "Bad number of mask bits (%d) on address range; rejecting.",
  536. bits);
  537. goto err;
  538. }
  539. } else { /* mask might still be an address-style mask */
  540. if (tor_inet_pton(AF_INET, mask, &v4mask) > 0) {
  541. bits = addr_mask_get_bits(ntohl(v4mask.s_addr));
  542. if (bits < 0) {
  543. log_warn(LD_GENERAL,
  544. "IPv4-style mask %s is not a prefix address; rejecting.",
  545. escaped(mask));
  546. goto err;
  547. }
  548. } else { /* Not IPv4; we don't do address-style IPv6 masks. */
  549. log_warn(LD_GENERAL,
  550. "Malformed mask on address range %s; rejecting.",
  551. escaped(s));
  552. goto err;
  553. }
  554. }
  555. if (family == AF_INET6 && v4map) {
  556. if (bits > 32 && bits < 96) { /* Crazy */
  557. log_warn(LD_GENERAL,
  558. "Bad mask bits %i for V4-mapped V6 address; rejecting.",
  559. bits);
  560. goto err;
  561. }
  562. /* XXXX_IP6 is this really what we want? */
  563. bits = 96 + bits%32; /* map v4-mapped masks onto 96-128 bits */
  564. }
  565. } else { /* pick an appropriate mask, as none was given */
  566. if (any_flag)
  567. bits = 0; /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */
  568. else if (tor_addr_family(addr_out) == AF_INET)
  569. bits = 32;
  570. else if (tor_addr_family(addr_out) == AF_INET6)
  571. bits = 128;
  572. }
  573. *maskbits_out = (maskbits_t) bits;
  574. } else {
  575. if (mask) {
  576. log_warn(LD_GENERAL,
  577. "Unexpected mask in address %s; rejecting", escaped(s));
  578. goto err;
  579. }
  580. }
  581. /* Parse port(s) */
  582. if (port_min_out) {
  583. uint16_t port2;
  584. if (!port_max_out) /* caller specified one port; fake the second one */
  585. port_max_out = &port2;
  586. if (parse_port_range(port, port_min_out, port_max_out) < 0) {
  587. goto err;
  588. } else if ((*port_min_out != *port_max_out) && port_max_out == &port2) {
  589. log_warn(LD_GENERAL,
  590. "Wanted one port from address range, but there are two.");
  591. port_max_out = NULL; /* caller specified one port, so set this back */
  592. goto err;
  593. }
  594. } else {
  595. if (port) {
  596. log_warn(LD_GENERAL,
  597. "Unexpected ports in address %s; rejecting", escaped(s));
  598. goto err;
  599. }
  600. }
  601. tor_free(base);
  602. return tor_addr_family(addr_out);
  603. err:
  604. tor_free(base);
  605. return -1;
  606. }
  607. /** Determine whether an address is IPv4, either native or IPv4-mapped IPv6.
  608. * Note that this is about representation only, as any decent stack will
  609. * reject IPv4-mapped addresses received on the wire (and won't use them
  610. * on the wire either).
  611. */
  612. int
  613. tor_addr_is_v4(const tor_addr_t *addr)
  614. {
  615. tor_assert(addr);
  616. if (tor_addr_family(addr) == AF_INET)
  617. return 1;
  618. if (tor_addr_family(addr) == AF_INET6) {
  619. /* First two don't need to be ordered */
  620. uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  621. if (a32[0] == 0 && a32[1] == 0 && ntohl(a32[2]) == 0x0000ffffu)
  622. return 1;
  623. }
  624. return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */
  625. }
  626. /** Determine whether an address <b>addr</b> is null, either all zeroes or
  627. * belonging to family AF_UNSPEC.
  628. */
  629. int
  630. tor_addr_is_null(const tor_addr_t *addr)
  631. {
  632. tor_assert(addr);
  633. switch (tor_addr_family(addr)) {
  634. case AF_INET6: {
  635. uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  636. return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 0);
  637. }
  638. case AF_INET:
  639. return (tor_addr_to_ipv4n(addr) == 0);
  640. case AF_UNSPEC:
  641. return 1;
  642. default:
  643. log_warn(LD_BUG, "Called with unknown address family %d",
  644. (int)tor_addr_family(addr));
  645. return 0;
  646. }
  647. //return 1;
  648. }
  649. /** Return true iff <b>addr</b> is a loopback address */
  650. int
  651. tor_addr_is_loopback(const tor_addr_t *addr)
  652. {
  653. tor_assert(addr);
  654. switch (tor_addr_family(addr)) {
  655. case AF_INET6: {
  656. /* ::1 */
  657. uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  658. return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 1);
  659. }
  660. case AF_INET:
  661. /* 127.0.0.1 */
  662. return (tor_addr_to_ipv4h(addr) & 0xff000000) == 0x7f000000;
  663. case AF_UNSPEC:
  664. return 0;
  665. default:
  666. tor_fragile_assert();
  667. return 0;
  668. }
  669. }
  670. /** Set <b>dest</b> to equal the IPv4 address in <b>v4addr</b> (given in
  671. * network order). */
  672. void
  673. tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
  674. {
  675. tor_assert(dest);
  676. memset(dest, 0, sizeof(tor_addr_t));
  677. dest->family = AF_INET;
  678. dest->addr.in_addr.s_addr = v4addr;
  679. }
  680. /** Set <b>dest</b> to equal the IPv6 address in the 16 bytes at
  681. * <b>ipv6_bytes</b>. */
  682. void
  683. tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
  684. {
  685. tor_assert(dest);
  686. tor_assert(ipv6_bytes);
  687. memset(dest, 0, sizeof(tor_addr_t));
  688. dest->family = AF_INET6;
  689. memcpy(dest->addr.in6_addr.s6_addr, ipv6_bytes, 16);
  690. }
  691. /** Set <b>dest</b> equal to the IPv6 address in the in6_addr <b>in6</b>. */
  692. void
  693. tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
  694. {
  695. tor_addr_from_ipv6_bytes(dest, (const char*)in6->s6_addr);
  696. }
  697. /** Copy a tor_addr_t from <b>src</b> to <b>dest</b>.
  698. */
  699. void
  700. tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
  701. {
  702. if (src == dest)
  703. return;
  704. tor_assert(src);
  705. tor_assert(dest);
  706. memcpy(dest, src, sizeof(tor_addr_t));
  707. }
  708. /** Given two addresses <b>addr1</b> and <b>addr2</b>, return 0 if the two
  709. * addresses are equivalent under the mask mbits, less than 0 if addr1
  710. * precedes addr2, and greater than 0 otherwise.
  711. *
  712. * Different address families (IPv4 vs IPv6) are always considered unequal if
  713. * <b>how</b> is CMP_EXACT; otherwise, IPv6-mapped IPv4 addresses are
  714. * considered equivalent to their IPv4 equivalents.
  715. */
  716. int
  717. tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2,
  718. tor_addr_comparison_t how)
  719. {
  720. return tor_addr_compare_masked(addr1, addr2, 128, how);
  721. }
  722. /** As tor_addr_compare(), but only looks at the first <b>mask</b> bits of
  723. * the address.
  724. *
  725. * Reduce over-specific masks (>128 for ipv6, >32 for ipv4) to 128 or 32.
  726. *
  727. * The mask is interpreted relative to <b>addr1</b>, so that if a is
  728. * \::ffff:1.2.3.4, and b is 3.4.5.6,
  729. * tor_addr_compare_masked(a,b,100,CMP_SEMANTIC) is the same as
  730. * -tor_addr_compare_masked(b,a,4,CMP_SEMANTIC).
  731. *
  732. * We guarantee that the ordering from tor_addr_compare_masked is a total
  733. * order on addresses, but not that it is any particular order, or that it
  734. * will be the same from one version to the next.
  735. */
  736. int
  737. tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2,
  738. maskbits_t mbits, tor_addr_comparison_t how)
  739. {
  740. /** Helper: Evaluates to -1 if a is less than b, 0 if a equals b, or 1 if a
  741. * is greater than b. May evaluate a and b more than once. */
  742. #define TRISTATE(a,b) (((a)<(b))?-1: (((a)==(b))?0:1))
  743. sa_family_t family1, family2, v_family1, v_family2;
  744. tor_assert(addr1 && addr2);
  745. v_family1 = family1 = tor_addr_family(addr1);
  746. v_family2 = family2 = tor_addr_family(addr2);
  747. if (family1==family2) {
  748. /* When the families are the same, there's only one way to do the
  749. * comparison: exactly. */
  750. int r;
  751. switch (family1) {
  752. case AF_UNSPEC:
  753. return 0; /* All unspecified addresses are equal */
  754. case AF_INET: {
  755. uint32_t a1 = tor_addr_to_ipv4h(addr1);
  756. uint32_t a2 = tor_addr_to_ipv4h(addr2);
  757. if (mbits <= 0)
  758. return 0;
  759. if (mbits > 32)
  760. mbits = 32;
  761. a1 >>= (32-mbits);
  762. a2 >>= (32-mbits);
  763. r = TRISTATE(a1, a2);
  764. return r;
  765. }
  766. case AF_INET6: {
  767. const uint8_t *a1 = tor_addr_to_in6_addr8(addr1);
  768. const uint8_t *a2 = tor_addr_to_in6_addr8(addr2);
  769. const int bytes = mbits >> 3;
  770. const int leftover_bits = mbits & 7;
  771. if (bytes && (r = memcmp(a1, a2, bytes))) {
  772. return r;
  773. } else if (leftover_bits) {
  774. uint8_t b1 = a1[bytes] >> (8-leftover_bits);
  775. uint8_t b2 = a2[bytes] >> (8-leftover_bits);
  776. return TRISTATE(b1, b2);
  777. } else {
  778. return 0;
  779. }
  780. }
  781. default:
  782. tor_fragile_assert();
  783. return 0;
  784. }
  785. } else if (how == CMP_EXACT) {
  786. /* Unequal families and an exact comparison? Stop now! */
  787. return TRISTATE(family1, family2);
  788. }
  789. if (mbits == 0)
  790. return 0;
  791. if (family1 == AF_INET6 && tor_addr_is_v4(addr1))
  792. v_family1 = AF_INET;
  793. if (family2 == AF_INET6 && tor_addr_is_v4(addr2))
  794. v_family2 = AF_INET;
  795. if (v_family1 == v_family2) {
  796. /* One or both addresses are a mapped ipv4 address. */
  797. uint32_t a1, a2;
  798. if (family1 == AF_INET6) {
  799. a1 = tor_addr_to_mapped_ipv4h(addr1);
  800. if (mbits <= 96)
  801. return 0;
  802. mbits -= 96; /* We just decided that the first 96 bits of a1 "match". */
  803. } else {
  804. a1 = tor_addr_to_ipv4h(addr1);
  805. }
  806. if (family2 == AF_INET6) {
  807. a2 = tor_addr_to_mapped_ipv4h(addr2);
  808. } else {
  809. a2 = tor_addr_to_ipv4h(addr2);
  810. }
  811. if (mbits <= 0) return 0;
  812. if (mbits > 32) mbits = 32;
  813. a1 >>= (32-mbits);
  814. a2 >>= (32-mbits);
  815. return TRISTATE(a1, a2);
  816. } else {
  817. /* Unequal families, and semantic comparison, and no semantic family
  818. * matches. */
  819. return TRISTATE(family1, family2);
  820. }
  821. }
  822. /** Return a hash code based on the address addr */
  823. unsigned int
  824. tor_addr_hash(const tor_addr_t *addr)
  825. {
  826. switch (tor_addr_family(addr)) {
  827. case AF_INET:
  828. return tor_addr_to_ipv4h(addr);
  829. case AF_UNSPEC:
  830. return 0x4e4d5342;
  831. case AF_INET6: {
  832. const uint32_t *u = tor_addr_to_in6_addr32(addr);
  833. return u[0] + u[1] + u[2] + u[3];
  834. }
  835. default:
  836. tor_fragile_assert();
  837. return 0;
  838. }
  839. }
  840. /** Return a newly allocated string with a representation of <b>addr</b>. */
  841. char *
  842. tor_dup_addr(const tor_addr_t *addr)
  843. {
  844. char buf[TOR_ADDR_BUF_LEN];
  845. tor_addr_to_str(buf, addr, sizeof(buf), 0);
  846. return tor_strdup(buf);
  847. }
  848. /** Return a string representing the address <b>addr</b>. This string is
  849. * statically allocated, and must not be freed. Each call to
  850. * <b>fmt_addr</b> invalidates the last result of the function. This
  851. * function is not thread-safe. */
  852. const char *
  853. fmt_addr(const tor_addr_t *addr)
  854. {
  855. static char buf[TOR_ADDR_BUF_LEN];
  856. if (!addr) return "<null>";
  857. tor_addr_to_str(buf, addr, sizeof(buf), 0);
  858. return buf;
  859. }
  860. /** Like fmt_addr(), but takes <b>addr</b> as a host-order IPv4
  861. * addresses. Also not thread-safe, also clobbers its return buffer on
  862. * repeated calls. */
  863. const char *
  864. fmt_addr32(uint32_t addr)
  865. {
  866. static char buf[INET_NTOA_BUF_LEN];
  867. struct in_addr in;
  868. in.s_addr = htonl(addr);
  869. tor_inet_ntoa(&in, buf, sizeof(buf));
  870. return buf;
  871. }
  872. /** Convert the string in <b>src</b> to a tor_addr_t <b>addr</b>. The string
  873. * may be an IPv4 address, an IPv6 address, or an IPv6 address surrounded by
  874. * square brackets.
  875. *
  876. * Return an address family on success, or -1 if an invalid address string is
  877. * provided. */
  878. int
  879. tor_addr_from_str(tor_addr_t *addr, const char *src)
  880. {
  881. char *tmp = NULL; /* Holds substring if we got a dotted quad. */
  882. int result;
  883. struct in_addr in_tmp;
  884. struct in6_addr in6_tmp;
  885. tor_assert(addr && src);
  886. if (src[0] == '[' && src[1])
  887. src = tmp = tor_strndup(src+1, strlen(src)-2);
  888. if (tor_inet_pton(AF_INET6, src, &in6_tmp) > 0) {
  889. result = AF_INET6;
  890. tor_addr_from_in6(addr, &in6_tmp);
  891. } else if (tor_inet_pton(AF_INET, src, &in_tmp) > 0) {
  892. result = AF_INET;
  893. tor_addr_from_in(addr, &in_tmp);
  894. } else {
  895. result = -1;
  896. }
  897. tor_free(tmp);
  898. return result;
  899. }
  900. /** Parse an address or address-port combination from <b>s</b>, resolve the
  901. * address as needed, and put the result in <b>addr_out</b> and (optionally)
  902. * <b>port_out</b>. Return 0 on success, negative on failure. */
  903. int
  904. tor_addr_port_parse(const char *s, tor_addr_t *addr_out, uint16_t *port_out)
  905. {
  906. const char *port;
  907. tor_addr_t addr;
  908. uint16_t portval;
  909. char *tmp = NULL;
  910. tor_assert(s);
  911. tor_assert(addr_out);
  912. s = eat_whitespace(s);
  913. if (*s == '[') {
  914. port = strstr(s, "]");
  915. if (!port)
  916. goto err;
  917. tmp = tor_strndup(s+1, port-(s+1));
  918. port = port+1;
  919. if (*port == ':')
  920. port++;
  921. else
  922. port = NULL;
  923. } else {
  924. port = strchr(s, ':');
  925. if (port)
  926. tmp = tor_strndup(s, port-s);
  927. else
  928. tmp = tor_strdup(s);
  929. if (port)
  930. ++port;
  931. }
  932. if (tor_addr_lookup(tmp, AF_UNSPEC, &addr) < 0)
  933. goto err;
  934. tor_free(tmp);
  935. if (port) {
  936. portval = (int) tor_parse_long(port, 10, 1, 65535, NULL, NULL);
  937. if (!portval)
  938. goto err;
  939. } else {
  940. portval = 0;
  941. }
  942. if (port_out)
  943. *port_out = portval;
  944. tor_addr_copy(addr_out, &addr);
  945. return 0;
  946. err:
  947. tor_free(tmp);
  948. return -1;
  949. }
  950. /** Set *<b>addr</b> to the IP address (if any) of whatever interface
  951. * connects to the Internet. This address should only be used in checking
  952. * whether our address has changed. Return 0 on success, -1 on failure.
  953. */
  954. int
  955. get_interface_address6(int severity, sa_family_t family, tor_addr_t *addr)
  956. {
  957. int sock=-1, r=-1;
  958. struct sockaddr_storage my_addr, target_addr;
  959. socklen_t addr_len;
  960. tor_assert(addr);
  961. memset(addr, 0, sizeof(tor_addr_t));
  962. memset(&target_addr, 0, sizeof(target_addr));
  963. /* Don't worry: no packets are sent. We just need to use a real address
  964. * on the actual Internet. */
  965. if (family == AF_INET6) {
  966. struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&target_addr;
  967. /* Use the "discard" service port */
  968. sin6->sin6_port = htons(9);
  969. sock = tor_open_socket(PF_INET6,SOCK_DGRAM,IPPROTO_UDP);
  970. addr_len = (socklen_t)sizeof(struct sockaddr_in6);
  971. sin6->sin6_family = AF_INET6;
  972. S6_ADDR16(sin6->sin6_addr)[0] = htons(0x2002); /* 2002:: */
  973. } else if (family == AF_INET) {
  974. struct sockaddr_in *sin = (struct sockaddr_in*)&target_addr;
  975. /* Use the "discard" service port */
  976. sin->sin_port = htons(9);
  977. sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
  978. addr_len = (socklen_t)sizeof(struct sockaddr_in);
  979. sin->sin_family = AF_INET;
  980. sin->sin_addr.s_addr = htonl(0x12000001); /* 18.0.0.1 */
  981. } else {
  982. return -1;
  983. }
  984. if (sock < 0) {
  985. int e = tor_socket_errno(-1);
  986. log_fn(severity, LD_NET, "unable to create socket: %s",
  987. tor_socket_strerror(e));
  988. goto err;
  989. }
  990. if (connect(sock,(struct sockaddr *)&target_addr, addr_len) < 0) {
  991. int e = tor_socket_errno(sock);
  992. log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e));
  993. goto err;
  994. }
  995. if (getsockname(sock,(struct sockaddr*)&my_addr, &addr_len)) {
  996. int e = tor_socket_errno(sock);
  997. log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s",
  998. tor_socket_strerror(e));
  999. goto err;
  1000. }
  1001. tor_addr_from_sockaddr(addr, (struct sockaddr*)&my_addr, NULL);
  1002. r=0;
  1003. err:
  1004. if (sock >= 0)
  1005. tor_close_socket(sock);
  1006. return r;
  1007. }
  1008. /* ======
  1009. * IPv4 helpers
  1010. * XXXX022 IPv6 deprecate some of these.
  1011. */
  1012. /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
  1013. * or reserved for local networks by RFC 1918.
  1014. */
  1015. int
  1016. is_internal_IP(uint32_t ip, int for_listening)
  1017. {
  1018. tor_addr_t myaddr;
  1019. myaddr.family = AF_INET;
  1020. myaddr.addr.in_addr.s_addr = htonl(ip);
  1021. return tor_addr_is_internal(&myaddr, for_listening);
  1022. }
  1023. /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
  1024. * <b>address</b> is provided, set *<b>address</b> to a copy of the
  1025. * host portion of the string. If <b>addr</b> is provided, try to
  1026. * resolve the host portion of the string and store it into
  1027. * *<b>addr</b> (in host byte order). If <b>port_out</b> is provided,
  1028. * store the port number into *<b>port_out</b>, or 0 if no port is given.
  1029. * If <b>port_out</b> is NULL, then there must be no port number in
  1030. * <b>addrport</b>.
  1031. * Return 0 on success, -1 on failure.
  1032. */
  1033. int
  1034. parse_addr_port(int severity, const char *addrport, char **address,
  1035. uint32_t *addr, uint16_t *port_out)
  1036. {
  1037. const char *colon;
  1038. char *_address = NULL;
  1039. int _port;
  1040. int ok = 1;
  1041. tor_assert(addrport);
  1042. colon = strchr(addrport, ':');
  1043. if (colon) {
  1044. _address = tor_strndup(addrport, colon-addrport);
  1045. _port = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
  1046. if (!_port) {
  1047. log_fn(severity, LD_GENERAL, "Port %s out of range", escaped(colon+1));
  1048. ok = 0;
  1049. }
  1050. if (!port_out) {
  1051. char *esc_addrport = esc_for_log(addrport);
  1052. log_fn(severity, LD_GENERAL,
  1053. "Port %s given on %s when not required",
  1054. escaped(colon+1), esc_addrport);
  1055. tor_free(esc_addrport);
  1056. ok = 0;
  1057. }
  1058. } else {
  1059. _address = tor_strdup(addrport);
  1060. _port = 0;
  1061. }
  1062. if (addr) {
  1063. /* There's an addr pointer, so we need to resolve the hostname. */
  1064. if (tor_lookup_hostname(_address,addr)) {
  1065. log_fn(severity, LD_NET, "Couldn't look up %s", escaped(_address));
  1066. ok = 0;
  1067. *addr = 0;
  1068. }
  1069. }
  1070. if (address && ok) {
  1071. *address = _address;
  1072. } else {
  1073. if (address)
  1074. *address = NULL;
  1075. tor_free(_address);
  1076. }
  1077. if (port_out)
  1078. *port_out = ok ? ((uint16_t) _port) : 0;
  1079. return ok ? 0 : -1;
  1080. }
  1081. /** If <b>mask</b> is an address mask for a bit-prefix, return the number of
  1082. * bits. Otherwise, return -1. */
  1083. int
  1084. addr_mask_get_bits(uint32_t mask)
  1085. {
  1086. int i;
  1087. if (mask == 0)
  1088. return 0;
  1089. if (mask == 0xFFFFFFFFu)
  1090. return 32;
  1091. for (i=0; i<=32; ++i) {
  1092. if (mask == (uint32_t) ~((1u<<(32-i))-1)) {
  1093. return i;
  1094. }
  1095. }
  1096. return -1;
  1097. }
  1098. /** Compare two addresses <b>a1</b> and <b>a2</b> for equality under a
  1099. * netmask of <b>mbits</b> bits. Return -1, 0, or 1.
  1100. *
  1101. * XXXX_IP6 Temporary function to allow masks as bitcounts everywhere. This
  1102. * will be replaced with an IPv6-aware version as soon as 32-bit addresses are
  1103. * no longer passed around.
  1104. */
  1105. int
  1106. addr_mask_cmp_bits(uint32_t a1, uint32_t a2, maskbits_t bits)
  1107. {
  1108. if (bits > 32)
  1109. bits = 32;
  1110. else if (bits == 0)
  1111. return 0;
  1112. a1 >>= (32-bits);
  1113. a2 >>= (32-bits);
  1114. if (a1 < a2)
  1115. return -1;
  1116. else if (a1 > a2)
  1117. return 1;
  1118. else
  1119. return 0;
  1120. }
  1121. /** Parse a string <b>s</b> in the format of (*|port(-maxport)?)?, setting the
  1122. * various *out pointers as appropriate. Return 0 on success, -1 on failure.
  1123. */
  1124. int
  1125. parse_port_range(const char *port, uint16_t *port_min_out,
  1126. uint16_t *port_max_out)
  1127. {
  1128. int port_min, port_max, ok;
  1129. tor_assert(port_min_out);
  1130. tor_assert(port_max_out);
  1131. if (!port || *port == '\0' || strcmp(port, "*") == 0) {
  1132. port_min = 1;
  1133. port_max = 65535;
  1134. } else {
  1135. char *endptr = NULL;
  1136. port_min = (int)tor_parse_long(port, 10, 0, 65535, &ok, &endptr);
  1137. if (!ok) {
  1138. log_warn(LD_GENERAL,
  1139. "Malformed port %s on address range; rejecting.",
  1140. escaped(port));
  1141. return -1;
  1142. } else if (endptr && *endptr == '-') {
  1143. port = endptr+1;
  1144. endptr = NULL;
  1145. port_max = (int)tor_parse_long(port, 10, 1, 65536, &ok, &endptr);
  1146. if (!ok) {
  1147. log_warn(LD_GENERAL,
  1148. "Malformed port %s on address range; rejecting.",
  1149. escaped(port));
  1150. return -1;
  1151. }
  1152. } else {
  1153. port_max = port_min;
  1154. }
  1155. if (port_min > port_max) {
  1156. log_warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
  1157. return -1;
  1158. }
  1159. }
  1160. if (port_min < 1)
  1161. port_min = 1;
  1162. if (port_max > 65535)
  1163. port_max = 65535;
  1164. *port_min_out = (uint16_t) port_min;
  1165. *port_max_out = (uint16_t) port_max;
  1166. return 0;
  1167. }
  1168. /** Parse a string <b>s</b> in the format of
  1169. * (IP(/mask|/mask-bits)?|*)(:(*|port(-maxport))?)?, setting the various
  1170. * *out pointers as appropriate. Return 0 on success, -1 on failure.
  1171. */
  1172. int
  1173. parse_addr_and_port_range(const char *s, uint32_t *addr_out,
  1174. maskbits_t *maskbits_out, uint16_t *port_min_out,
  1175. uint16_t *port_max_out)
  1176. {
  1177. char *address;
  1178. char *mask, *port, *endptr;
  1179. struct in_addr in;
  1180. int bits;
  1181. tor_assert(s);
  1182. tor_assert(addr_out);
  1183. tor_assert(maskbits_out);
  1184. tor_assert(port_min_out);
  1185. tor_assert(port_max_out);
  1186. address = tor_strdup(s);
  1187. /* Break 'address' into separate strings.
  1188. */
  1189. mask = strchr(address,'/');
  1190. port = strchr(mask?mask:address,':');
  1191. if (mask)
  1192. *mask++ = '\0';
  1193. if (port)
  1194. *port++ = '\0';
  1195. /* Now "address" is the IP|'*' part...
  1196. * "mask" is the Mask|Maskbits part...
  1197. * and "port" is the *|port|min-max part.
  1198. */
  1199. if (strcmp(address,"*")==0) {
  1200. *addr_out = 0;
  1201. } else if (tor_inet_aton(address, &in) != 0) {
  1202. *addr_out = ntohl(in.s_addr);
  1203. } else {
  1204. log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
  1205. escaped(address));
  1206. goto err;
  1207. }
  1208. if (!mask) {
  1209. if (strcmp(address,"*")==0)
  1210. *maskbits_out = 0;
  1211. else
  1212. *maskbits_out = 32;
  1213. } else {
  1214. endptr = NULL;
  1215. bits = (int) strtol(mask, &endptr, 10);
  1216. if (!*endptr) {
  1217. /* strtol handled the whole mask. */
  1218. if (bits < 0 || bits > 32) {
  1219. log_warn(LD_GENERAL,
  1220. "Bad number of mask bits on address range; rejecting.");
  1221. goto err;
  1222. }
  1223. *maskbits_out = bits;
  1224. } else if (tor_inet_aton(mask, &in) != 0) {
  1225. bits = addr_mask_get_bits(ntohl(in.s_addr));
  1226. if (bits < 0) {
  1227. log_warn(LD_GENERAL,
  1228. "Mask %s on address range isn't a prefix; dropping",
  1229. escaped(mask));
  1230. goto err;
  1231. }
  1232. *maskbits_out = bits;
  1233. } else {
  1234. log_warn(LD_GENERAL,
  1235. "Malformed mask %s on address range; rejecting.",
  1236. escaped(mask));
  1237. goto err;
  1238. }
  1239. }
  1240. if (parse_port_range(port, port_min_out, port_max_out)<0)
  1241. goto err;
  1242. tor_free(address);
  1243. return 0;
  1244. err:
  1245. tor_free(address);
  1246. return -1;
  1247. }
  1248. /** Given an IPv4 in_addr struct *<b>in</b> (in network order, as usual),
  1249. * write it as a string into the <b>buf_len</b>-byte buffer in
  1250. * <b>buf</b>.
  1251. */
  1252. int
  1253. tor_inet_ntoa(const struct in_addr *in, char *buf, size_t buf_len)
  1254. {
  1255. uint32_t a = ntohl(in->s_addr);
  1256. return tor_snprintf(buf, buf_len, "%d.%d.%d.%d",
  1257. (int)(uint8_t)((a>>24)&0xff),
  1258. (int)(uint8_t)((a>>16)&0xff),
  1259. (int)(uint8_t)((a>>8 )&0xff),
  1260. (int)(uint8_t)((a )&0xff));
  1261. }
  1262. /** Given a host-order <b>addr</b>, call tor_inet_ntop() on it
  1263. * and return a strdup of the resulting address.
  1264. */
  1265. char *
  1266. tor_dup_ip(uint32_t addr)
  1267. {
  1268. char buf[TOR_ADDR_BUF_LEN];
  1269. struct in_addr in;
  1270. in.s_addr = htonl(addr);
  1271. tor_inet_ntop(AF_INET, &in, buf, sizeof(buf));
  1272. return tor_strdup(buf);
  1273. }
  1274. /**
  1275. * Set *<b>addr</b> to the host-order IPv4 address (if any) of whatever
  1276. * interface connects to the Internet. This address should only be used in
  1277. * checking whether our address has changed. Return 0 on success, -1 on
  1278. * failure.
  1279. */
  1280. int
  1281. get_interface_address(int severity, uint32_t *addr)
  1282. {
  1283. tor_addr_t local_addr;
  1284. int r;
  1285. r = get_interface_address6(severity, AF_INET, &local_addr);
  1286. if (r>=0)
  1287. *addr = tor_addr_to_ipv4h(&local_addr);
  1288. return r;
  1289. }