address.c 40 KB

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