address.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2008, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  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 "log.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. socklen_t
  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, int 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 = (((inaddr.s_addr & 0x000000fful) << 24)
  354. |((inaddr.s_addr & 0x0000ff00ul) << 8)
  355. |((inaddr.s_addr & 0x00ff0000ul) >> 8)
  356. |((inaddr.s_addr & 0xff000000ul) >> 24));
  357. if (result) {
  358. tor_addr_from_in(result, &inaddr);
  359. }
  360. return 1;
  361. }
  362. if (!strcasecmpend(address, ".ip6.arpa")) {
  363. const char *cp;
  364. int i;
  365. int n0, n1;
  366. struct in6_addr in6;
  367. if (family == AF_INET)
  368. return -1;
  369. cp = address;
  370. for (i = 0; i < 16; ++i) {
  371. n0 = hex_decode_digit(*cp++); /* The low-order nybble appears first. */
  372. if (*cp++ != '.') return -1; /* Then a dot. */
  373. n1 = hex_decode_digit(*cp++); /* The high-order nybble appears first. */
  374. if (*cp++ != '.') return -1; /* Then another dot. */
  375. if (n0<0 || n1 < 0) /* Both nybbles must be hex. */
  376. return -1;
  377. /* We don't check the length of the string in here. But that's okay,
  378. * since we already know that the string ends with ".ip6.arpa", and
  379. * there is no way to frameshift .ip6.arpa so it fits into the pattern
  380. * of hexdigit, period, hexdigit, period that we enforce above.
  381. */
  382. /* Assign from low-byte to high-byte. */
  383. in6.s6_addr[15-i] = n0 | (n1 << 4);
  384. }
  385. if (strcasecmp(cp, "ip6.arpa"))
  386. return -1;
  387. if (result) {
  388. tor_addr_from_in6(result, &in6);
  389. }
  390. return 1;
  391. }
  392. if (accept_regular) {
  393. tor_addr_t tmp;
  394. int r = tor_addr_from_str(&tmp, address);
  395. if (r < 0)
  396. return 0;
  397. if (r != family && family != AF_UNSPEC)
  398. return -1;
  399. if (result)
  400. memcpy(result, &tmp, sizeof(tor_addr_t));
  401. return 1;
  402. }
  403. return 0;
  404. }
  405. /** Convert <b>addr</b> to an in-addr.arpa name or a .ip6.arpa name, and store
  406. * the result in the <b>outlen</b>-byte buffer at <b>out</b>. Return 0 on
  407. * success, -1 on failure. */
  408. int
  409. tor_addr_to_reverse_lookup_name(char *out, size_t outlen,
  410. const tor_addr_t *addr)
  411. {
  412. if (addr->family == AF_INET) {
  413. uint32_t a = tor_addr_to_ipv4h(addr);
  414. return tor_snprintf(out, outlen, "%d.%d.%d.%d.in-addr.arpa",
  415. (int)(uint8_t)((a )&0xff),
  416. (int)(uint8_t)((a>>8 )&0xff),
  417. (int)(uint8_t)((a>>16)&0xff),
  418. (int)(uint8_t)((a>>24)&0xff));
  419. } else if (addr->family == AF_INET6) {
  420. int i;
  421. char *cp = out;
  422. const uint8_t *bytes = tor_addr_to_in6_addr8(addr);
  423. if (outlen < REVERSE_LOOKUP_NAME_BUF_LEN)
  424. return -1;
  425. for (i = 15; i >= 0; --i) {
  426. uint8_t byte = bytes[i];
  427. *cp++ = "0123456789abcdef"[byte & 0x0f];
  428. *cp++ = '.';
  429. *cp++ = "0123456789abcdef"[byte >> 4];
  430. *cp++ = '.';
  431. }
  432. memcpy(cp, "ip6.arpa", 9); /* 8 characters plus nul */
  433. return 0;
  434. }
  435. return -1;
  436. }
  437. /** Parse a string <b>s</b> containing an IPv4/IPv6 address, and possibly
  438. * a mask and port or port range. Store the parsed address in
  439. * <b>addr_out</b>, a mask (if any) in <b>mask_out</b>, and port(s) (if any)
  440. * in <b>port_min_out</b> and <b>port_max_out</b>.
  441. *
  442. * The syntax is:
  443. * Address OptMask OptPortRange
  444. * Address ::= IPv4Address / "[" IPv6Address "]" / "*"
  445. * OptMask ::= "/" Integer /
  446. * OptPortRange ::= ":*" / ":" Integer / ":" Integer "-" Integer /
  447. *
  448. * - If mask, minport, or maxport are NULL, we do not want these
  449. * options to be set; treat them as an error if present.
  450. * - If the string has no mask, the mask is set to /32 (IPv4) or /128 (IPv6).
  451. * - If the string has one port, it is placed in both min and max port
  452. * variables.
  453. * - If the string has no port(s), port_(min|max)_out are set to 1 and 65535.
  454. *
  455. * Return an address family on success, or -1 if an invalid address string is
  456. * provided.
  457. */
  458. int
  459. tor_addr_parse_mask_ports(const char *s, tor_addr_t *addr_out,
  460. maskbits_t *maskbits_out,
  461. uint16_t *port_min_out, uint16_t *port_max_out)
  462. {
  463. char *base = NULL, *address, *mask = NULL, *port = NULL, *rbracket = NULL;
  464. char *endptr;
  465. int any_flag=0, v4map=0;
  466. sa_family_t family;
  467. struct in6_addr in6_tmp;
  468. struct in_addr in_tmp;
  469. tor_assert(s);
  470. tor_assert(addr_out);
  471. /* IP, [], /mask, ports */
  472. #define MAX_ADDRESS_LENGTH (TOR_ADDR_BUF_LEN+2+(1+INET_NTOA_BUF_LEN)+12+1)
  473. if (strlen(s) > MAX_ADDRESS_LENGTH) {
  474. log_warn(LD_GENERAL, "Impossibly long IP %s; rejecting", escaped(s));
  475. goto err;
  476. }
  477. base = tor_strdup(s);
  478. /* Break 'base' into separate strings. */
  479. address = base;
  480. if (*address == '[') { /* Probably IPv6 */
  481. address++;
  482. rbracket = strchr(address, ']');
  483. if (!rbracket) {
  484. log_warn(LD_GENERAL,
  485. "No closing IPv6 bracket in address pattern; rejecting.");
  486. goto err;
  487. }
  488. }
  489. mask = strchr((rbracket?rbracket:address),'/');
  490. port = strchr((mask?mask:(rbracket?rbracket:address)), ':');
  491. if (port)
  492. *port++ = '\0';
  493. if (mask)
  494. *mask++ = '\0';
  495. if (rbracket)
  496. *rbracket = '\0';
  497. if (port && mask)
  498. tor_assert(port > mask);
  499. if (mask && rbracket)
  500. tor_assert(mask > rbracket);
  501. /* Now "address" is the a.b.c.d|'*'|abcd::1 part...
  502. * "mask" is the Mask|Maskbits part...
  503. * and "port" is the *|port|min-max part.
  504. */
  505. /* Process the address portion */
  506. memset(addr_out, 0, sizeof(tor_addr_t));
  507. if (!strcmp(address, "*")) {
  508. family = AF_INET; /* AF_UNSPEC ???? XXXX_IP6 */
  509. tor_addr_from_ipv4h(addr_out, 0);
  510. any_flag = 1;
  511. } else if (tor_inet_pton(AF_INET6, address, &in6_tmp) > 0) {
  512. family = AF_INET6;
  513. tor_addr_from_in6(addr_out, &in6_tmp);
  514. } else if (tor_inet_pton(AF_INET, address, &in_tmp) > 0) {
  515. family = AF_INET;
  516. tor_addr_from_in(addr_out, &in_tmp);
  517. } else {
  518. log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
  519. escaped(address));
  520. goto err;
  521. }
  522. v4map = tor_addr_is_v4(addr_out);
  523. /* Parse mask */
  524. if (maskbits_out) {
  525. int bits = 0;
  526. struct in_addr v4mask;
  527. if (mask) { /* the caller (tried to) specify a mask */
  528. bits = (int) strtol(mask, &endptr, 10);
  529. if (!*endptr) { /* strtol converted everything, so it was an integer */
  530. if ((bits<0 || bits>128) ||
  531. (family == AF_INET && bits > 32)) {
  532. log_warn(LD_GENERAL,
  533. "Bad number of mask bits (%d) on address range; rejecting.",
  534. bits);
  535. goto err;
  536. }
  537. } else { /* mask might still be an address-style mask */
  538. if (tor_inet_pton(AF_INET, mask, &v4mask) > 0) {
  539. bits = addr_mask_get_bits(ntohl(v4mask.s_addr));
  540. if (bits < 0) {
  541. log_warn(LD_GENERAL,
  542. "IPv4-style mask %s is not a prefix address; rejecting.",
  543. escaped(mask));
  544. goto err;
  545. }
  546. } else { /* Not IPv4; we don't do address-style IPv6 masks. */
  547. log_warn(LD_GENERAL,
  548. "Malformed mask on address range %s; rejecting.",
  549. escaped(s));
  550. goto err;
  551. }
  552. }
  553. if (family == AF_INET6 && v4map) {
  554. if (bits > 32 && bits < 96) { /* Crazy */
  555. log_warn(LD_GENERAL,
  556. "Bad mask bits %i for V4-mapped V6 address; rejecting.",
  557. bits);
  558. goto err;
  559. }
  560. /* XXXX_IP6 is this really what we want? */
  561. bits = 96 + bits%32; /* map v4-mapped masks onto 96-128 bits */
  562. }
  563. } else { /* pick an appropriate mask, as none was given */
  564. if (any_flag)
  565. bits = 0; /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */
  566. else if (tor_addr_family(addr_out) == AF_INET)
  567. bits = 32;
  568. else if (tor_addr_family(addr_out) == AF_INET6)
  569. bits = 128;
  570. }
  571. *maskbits_out = (maskbits_t) bits;
  572. } else {
  573. if (mask) {
  574. log_warn(LD_GENERAL,
  575. "Unexpected mask in addrss %s; rejecting", escaped(s));
  576. goto err;
  577. }
  578. }
  579. /* Parse port(s) */
  580. if (port_min_out) {
  581. uint16_t port2;
  582. if (!port_max_out) /* caller specified one port; fake the second one */
  583. port_max_out = &port2;
  584. if (parse_port_range(port, port_min_out, port_max_out) < 0) {
  585. goto err;
  586. } else if ((*port_min_out != *port_max_out) && port_max_out == &port2) {
  587. log_warn(LD_GENERAL,
  588. "Wanted one port from address range, but there are two.");
  589. port_max_out = NULL; /* caller specified one port, so set this back */
  590. goto err;
  591. }
  592. } else {
  593. if (port) {
  594. log_warn(LD_GENERAL,
  595. "Unexpected ports in addrss %s; rejecting", escaped(s));
  596. goto err;
  597. }
  598. }
  599. tor_free(base);
  600. return tor_addr_family(addr_out);
  601. err:
  602. tor_free(base);
  603. return -1;
  604. }
  605. /** Determine whether an address is IPv4, either native or ipv4-mapped ipv6.
  606. * Note that this is about representation only, as any decent stack will
  607. * reject ipv4-mapped addresses received on the wire (and won't use them
  608. * on the wire either).
  609. */
  610. int
  611. tor_addr_is_v4(const tor_addr_t *addr)
  612. {
  613. tor_assert(addr);
  614. if (tor_addr_family(addr) == AF_INET)
  615. return 1;
  616. if (tor_addr_family(addr) == AF_INET6) {
  617. /* First two don't need to be ordered */
  618. uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  619. if (a32[0] == 0 && a32[1] == 0 && ntohl(a32[2]) == 0x0000ffffu)
  620. return 1;
  621. }
  622. return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */
  623. }
  624. /** Determine whether an address <b>addr</b> is null, either all zeroes or
  625. * belonging to family AF_UNSPEC.
  626. */
  627. int
  628. tor_addr_is_null(const tor_addr_t *addr)
  629. {
  630. tor_assert(addr);
  631. switch (tor_addr_family(addr)) {
  632. case AF_INET6: {
  633. uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  634. return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 0);
  635. }
  636. case AF_INET:
  637. return (tor_addr_to_ipv4n(addr) == 0);
  638. case AF_UNSPEC:
  639. return 1;
  640. default:
  641. log_warn(LD_BUG, "Called with unknown address family %d",
  642. (int)tor_addr_family(addr));
  643. return 0;
  644. }
  645. //return 1;
  646. }
  647. /** Return true iff <b>addr</b> is a loopback address */
  648. int
  649. tor_addr_is_loopback(const tor_addr_t *addr)
  650. {
  651. tor_assert(addr);
  652. switch (tor_addr_family(addr)) {
  653. case AF_INET6: {
  654. /* ::1 */
  655. uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  656. return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 1);
  657. }
  658. case AF_INET:
  659. /* 127.0.0.1 */
  660. return (tor_addr_to_ipv4h(addr) & 0xff000000) == 0x7f000000;
  661. case AF_UNSPEC:
  662. return 0;
  663. default:
  664. tor_fragile_assert();
  665. return 0;
  666. }
  667. }
  668. /** Set <b>dest</b> to equal the IPv4 address in <b>v4addr</b> (given in
  669. * network order. */
  670. void
  671. tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
  672. {
  673. tor_assert(dest);
  674. memset(dest, 0, sizeof(tor_addr_t));
  675. dest->family = AF_INET;
  676. dest->addr.in_addr.s_addr = v4addr;
  677. }
  678. /** Set <b>dest</b> to equal the IPv6 address in the 16 bytes at
  679. * <b>ipv6_bytes</b>. */
  680. void
  681. tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
  682. {
  683. tor_assert(dest);
  684. tor_assert(ipv6_bytes);
  685. memset(dest, 0, sizeof(tor_addr_t));
  686. dest->family = AF_INET6;
  687. memcpy(dest->addr.in6_addr.s6_addr, ipv6_bytes, 16);
  688. }
  689. /** Set <b>dest</b> equal to the IPv6 address in the in6_addr <b>in6</b>. */
  690. void
  691. tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
  692. {
  693. tor_addr_from_ipv6_bytes(dest, (const char*)in6->s6_addr);
  694. }
  695. /** Copy a tor_addr_t from <b>src</b> to <b>dest</b>.
  696. */
  697. void
  698. tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
  699. {
  700. tor_assert(src);
  701. tor_assert(dest);
  702. memcpy(dest, src, sizeof(tor_addr_t));
  703. }
  704. /** Given two addresses <b>addr1</b> and <b>addr2</b>, return 0 if the two
  705. * addresses are equivalent under the mask mbits, less than 0 if addr1
  706. * preceeds addr2, and greater than 0 otherwise.
  707. *
  708. * Different address families (IPv4 vs IPv6) are always considered unequal if
  709. * <b>how</b> is CMP_EXACT; otherwise, IPv6-mapped IPv4 addresses are
  710. * cosidered equivalent to their IPv4 equivalents.
  711. */
  712. int
  713. tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2,
  714. tor_addr_comparison_t how)
  715. {
  716. return tor_addr_compare_masked(addr1, addr2, 128, how);
  717. }
  718. /** As tor_addr_compare(), but only looks at the first <b>mask</b> bits of
  719. * the address.
  720. *
  721. * Reduce over-specific masks (>128 for ipv6, >32 for ipv4) to 128 or 32.
  722. *
  723. * The mask is interpreted relative to <b>addr1</b>, so that if a is
  724. * ::ffff:1.2.3.4, and b is 3.4.5.6,
  725. * tor_addr_compare_masked(a,b,100,CMP_SEMANTIC) is the same as
  726. * -tor_addr_compare_masked(b,a,4,CMP_SEMANTIC).
  727. *
  728. * We guarantee that the ordering from tor_addr_compare_masked is a total
  729. * order on addresses, but not that it is any particular order, or that it
  730. * will be the same from one version to the next.
  731. */
  732. int
  733. tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2,
  734. maskbits_t mbits, tor_addr_comparison_t how)
  735. {
  736. #define TRISTATE(a,b) (((a)<(b))?-1: (((a)==(b))?0:1))
  737. sa_family_t family1, family2, v_family1, v_family2;
  738. tor_assert(addr1 && addr2);
  739. v_family1 = family1 = tor_addr_family(addr1);
  740. v_family2 = family2 = tor_addr_family(addr2);
  741. if (family1==family2) {
  742. /* When the families are the same, there's only one way to do the
  743. * comparison: exactly. */
  744. int r;
  745. switch (family1) {
  746. case AF_UNSPEC:
  747. return 0; /* All unspecified addresses are equal */
  748. case AF_INET: {
  749. uint32_t a1 = tor_addr_to_ipv4h(addr1);
  750. uint32_t a2 = tor_addr_to_ipv4h(addr2);
  751. if (mbits <= 0)
  752. return 0;
  753. if (mbits > 32)
  754. mbits = 32;
  755. a1 >>= (32-mbits);
  756. a2 >>= (32-mbits);
  757. r = TRISTATE(a1, a2);
  758. return r;
  759. }
  760. case AF_INET6: {
  761. const uint8_t *a1 = tor_addr_to_in6_addr8(addr1);
  762. const uint8_t *a2 = tor_addr_to_in6_addr8(addr2);
  763. const int bytes = mbits >> 3;
  764. const int leftover_bits = mbits & 7;
  765. if (bytes && (r = memcmp(a1, a2, bytes))) {
  766. return r;
  767. } else if (leftover_bits) {
  768. uint8_t b1 = a1[bytes] >> (8-leftover_bits);
  769. uint8_t b2 = a2[bytes] >> (8-leftover_bits);
  770. return TRISTATE(b1, b2);
  771. } else {
  772. return 0;
  773. }
  774. }
  775. default:
  776. tor_fragile_assert();
  777. return 0;
  778. }
  779. } else if (how == CMP_EXACT) {
  780. /* Unequal families and an exact comparison? Stop now! */
  781. return TRISTATE(family1, family2);
  782. }
  783. if (mbits == 0)
  784. return 0;
  785. if (family1 == AF_INET6 && tor_addr_is_v4(addr1))
  786. v_family1 = AF_INET;
  787. if (family2 == AF_INET6 && tor_addr_is_v4(addr2))
  788. v_family2 = AF_INET;
  789. if (v_family1 == v_family2) {
  790. /* One or both addresses are a mapped ipv4 address. */
  791. uint32_t a1, a2;
  792. if (family1 == AF_INET6) {
  793. a1 = tor_addr_to_mapped_ipv4h(addr1);
  794. if (mbits <= 96)
  795. return 0;
  796. mbits -= 96; /* We just decided that the first 96 bits of a1 "match". */
  797. } else {
  798. a1 = tor_addr_to_ipv4h(addr1);
  799. }
  800. if (family2 == AF_INET6) {
  801. a2 = tor_addr_to_mapped_ipv4h(addr2);
  802. } else {
  803. a2 = tor_addr_to_ipv4h(addr2);
  804. }
  805. if (mbits <= 0) return 0;
  806. if (mbits > 32) mbits = 32;
  807. a1 >>= (32-mbits);
  808. a2 >>= (32-mbits);
  809. return TRISTATE(a1, a2);
  810. } else {
  811. /* Unequal families, and semantic comparison, and no semantic family
  812. * matches. */
  813. return TRISTATE(family1, family2);
  814. }
  815. }
  816. /** Return a hash code based on the address addr */
  817. unsigned int
  818. tor_addr_hash(const tor_addr_t *addr)
  819. {
  820. switch (tor_addr_family(addr)) {
  821. case AF_INET:
  822. return tor_addr_to_ipv4h(addr);
  823. case AF_UNSPEC:
  824. return 0x4e4d5342;
  825. case AF_INET6: {
  826. const uint32_t *u = tor_addr_to_in6_addr32(addr);
  827. return u[0] + u[1] + u[2] + u[3];
  828. }
  829. default:
  830. tor_fragile_assert();
  831. return 0;
  832. }
  833. }
  834. /** Return a newly allocated string with a representation of <b>addr</b>. */
  835. char *
  836. tor_dup_addr(const tor_addr_t *addr)
  837. {
  838. char buf[TOR_ADDR_BUF_LEN];
  839. tor_addr_to_str(buf, addr, sizeof(buf), 0);
  840. return tor_strdup(buf);
  841. }
  842. /** Copy the address in <b>src</b> to <b>dest</b> */
  843. void
  844. tor_addr_assign(tor_addr_t *dest, const tor_addr_t *src)
  845. {
  846. memcpy(dest, src, sizeof(tor_addr_t));
  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. /** Convert the string in <b>src</b> to a tor_addr_t <b>addr</b>. The string
  861. * may be an IPv4 address, an IPv6 address, or an IPv6 address surrounded by
  862. * square brackets.
  863. *
  864. * Return an address family on success, or -1 if an invalid address string is
  865. * provided. */
  866. int
  867. tor_addr_from_str(tor_addr_t *addr, const char *src)
  868. {
  869. char *tmp = NULL; /* Holds substring if we got a dotted quad. */
  870. int result;
  871. struct in_addr in_tmp;
  872. struct in6_addr in6_tmp;
  873. tor_assert(addr && src);
  874. if (src[0] == '[' && src[1])
  875. src = tmp = tor_strndup(src+1, strlen(src)-2);
  876. if (tor_inet_pton(AF_INET6, src, &in6_tmp) > 0) {
  877. result = AF_INET6;
  878. tor_addr_from_in6(addr, &in6_tmp);
  879. } else if (tor_inet_pton(AF_INET, src, &in_tmp) > 0) {
  880. result = AF_INET;
  881. tor_addr_from_in(addr, &in_tmp);
  882. } else {
  883. result = -1;
  884. }
  885. tor_free(tmp);
  886. return result;
  887. }
  888. /** Parse an address or address-port combination from <b>s</b>, and put the
  889. result in <b>addr_out</b> and (optionally) <b>port_out</b>. Return 0 on
  890. success, negative on failure. */
  891. int
  892. tor_addr_port_parse(const char *s, tor_addr_t *addr_out, uint16_t *port_out)
  893. {
  894. const char *port;
  895. tor_addr_t addr;
  896. uint16_t portval;
  897. char *tmp = NULL;
  898. tor_assert(s);
  899. tor_assert(addr_out);
  900. s = eat_whitespace(s);
  901. if (*s == '[') {
  902. port = strstr(s, "]");
  903. if (!port)
  904. goto err;
  905. tmp = tor_strndup(s+1, port-s);
  906. port = port+1;
  907. if (*port == ':')
  908. port++;
  909. else
  910. port = NULL;
  911. } else {
  912. port = strchr(s, ':');
  913. if (port)
  914. tmp = tor_strndup(s, port-s);
  915. else
  916. tmp = tor_strdup(s);
  917. if (port)
  918. ++port;
  919. }
  920. if (tor_addr_lookup(tmp, AF_UNSPEC, &addr) < 0)
  921. goto err;
  922. tor_free(tmp);
  923. if (port) {
  924. portval = (int) tor_parse_long(port, 10, 1, 65535, NULL, NULL);
  925. if (!portval)
  926. goto err;
  927. } else {
  928. portval = 0;
  929. }
  930. if (port_out)
  931. *port_out = portval;
  932. tor_addr_copy(addr_out, &addr);
  933. return 0;
  934. err:
  935. tor_free(tmp);
  936. return -1;
  937. }
  938. /** Set *<b>addr</b> to the IP address (if any) of whatever interface
  939. * connects to the internet. This address should only be used in checking
  940. * whether our address has changed. Return 0 on success, -1 on failure.
  941. */
  942. int
  943. get_interface_address6(int severity, sa_family_t family, tor_addr_t *addr)
  944. {
  945. int sock=-1, r=-1;
  946. struct sockaddr_storage my_addr, target_addr;
  947. socklen_t my_addr_len;
  948. tor_assert(addr);
  949. memset(addr, 0, sizeof(tor_addr_t));
  950. memset(&target_addr, 0, sizeof(target_addr));
  951. my_addr_len = (socklen_t)sizeof(my_addr);
  952. /* Use the "discard" service port */
  953. ((struct sockaddr_in*)&target_addr)->sin_port = 9;
  954. /* Don't worry: no packets are sent. We just need to use a real address
  955. * on the actual internet. */
  956. if (family == AF_INET6) {
  957. struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&target_addr;
  958. sock = tor_open_socket(PF_INET6,SOCK_DGRAM,IPPROTO_UDP);
  959. my_addr_len = (socklen_t)sizeof(struct sockaddr_in6);
  960. sin6->sin6_family = AF_INET6;
  961. S6_ADDR16(sin6->sin6_addr)[0] = htons(0x2002); /* 2002:: */
  962. } else if (family == AF_INET) {
  963. struct sockaddr_in *sin = (struct sockaddr_in*)&target_addr;
  964. sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
  965. my_addr_len = (socklen_t)sizeof(struct sockaddr_in);
  966. sin->sin_family = AF_INET;
  967. sin->sin_addr.s_addr = htonl(0x12000001); /* 18.0.0.1 */
  968. } else {
  969. return -1;
  970. }
  971. if (sock < 0) {
  972. int e = tor_socket_errno(-1);
  973. log_fn(severity, LD_NET, "unable to create socket: %s",
  974. tor_socket_strerror(e));
  975. goto err;
  976. }
  977. if (connect(sock,(struct sockaddr *)&target_addr,
  978. (socklen_t)sizeof(target_addr))<0) {
  979. int e = tor_socket_errno(sock);
  980. log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e));
  981. goto err;
  982. }
  983. if (getsockname(sock,(struct sockaddr*)&my_addr, &my_addr_len)) {
  984. int e = tor_socket_errno(sock);
  985. log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s",
  986. tor_socket_strerror(e));
  987. goto err;
  988. }
  989. tor_addr_from_sockaddr(addr, (struct sockaddr*)&my_addr, NULL);
  990. r=0;
  991. err:
  992. if (sock >= 0)
  993. tor_close_socket(sock);
  994. return r;
  995. }
  996. /* ======
  997. * IPv4 helpers
  998. * XXXX022 IPv6 deprecate some of these.
  999. */
  1000. /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
  1001. * or reserved for local networks by RFC 1918.
  1002. */
  1003. int
  1004. is_internal_IP(uint32_t ip, int for_listening)
  1005. {
  1006. tor_addr_t myaddr;
  1007. myaddr.family = AF_INET;
  1008. myaddr.addr.in_addr.s_addr = htonl(ip);
  1009. return tor_addr_is_internal(&myaddr, for_listening);
  1010. }
  1011. /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
  1012. * <b>address</b> is provided, set *<b>address</b> to a copy of the
  1013. * host portion of the string. If <b>addr</b> is provided, try to
  1014. * resolve the host portion of the string and store it into
  1015. * *<b>addr</b> (in host byte order). If <b>port_out</b> is provided,
  1016. * store the port number into *<b>port_out</b>, or 0 if no port is given.
  1017. * If <b>port_out</b> is NULL, then there must be no port number in
  1018. * <b>addrport</b>.
  1019. * Return 0 on success, -1 on failure.
  1020. */
  1021. int
  1022. parse_addr_port(int severity, const char *addrport, char **address,
  1023. uint32_t *addr, uint16_t *port_out)
  1024. {
  1025. const char *colon;
  1026. char *_address = NULL;
  1027. int _port;
  1028. int ok = 1;
  1029. tor_assert(addrport);
  1030. colon = strchr(addrport, ':');
  1031. if (colon) {
  1032. _address = tor_strndup(addrport, colon-addrport);
  1033. _port = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
  1034. if (!_port) {
  1035. log_fn(severity, LD_GENERAL, "Port %s out of range", escaped(colon+1));
  1036. ok = 0;
  1037. }
  1038. if (!port_out) {
  1039. char *esc_addrport = esc_for_log(addrport);
  1040. log_fn(severity, LD_GENERAL,
  1041. "Port %s given on %s when not required",
  1042. escaped(colon+1), esc_addrport);
  1043. tor_free(esc_addrport);
  1044. ok = 0;
  1045. }
  1046. } else {
  1047. _address = tor_strdup(addrport);
  1048. _port = 0;
  1049. }
  1050. if (addr) {
  1051. /* There's an addr pointer, so we need to resolve the hostname. */
  1052. if (tor_lookup_hostname(_address,addr)) {
  1053. log_fn(severity, LD_NET, "Couldn't look up %s", escaped(_address));
  1054. ok = 0;
  1055. *addr = 0;
  1056. }
  1057. }
  1058. if (address && ok) {
  1059. *address = _address;
  1060. } else {
  1061. if (address)
  1062. *address = NULL;
  1063. tor_free(_address);
  1064. }
  1065. if (port_out)
  1066. *port_out = ok ? ((uint16_t) _port) : 0;
  1067. return ok ? 0 : -1;
  1068. }
  1069. /** If <b>mask</b> is an address mask for a bit-prefix, return the number of
  1070. * bits. Otherwise, return -1. */
  1071. int
  1072. addr_mask_get_bits(uint32_t mask)
  1073. {
  1074. int i;
  1075. if (mask == 0)
  1076. return 0;
  1077. if (mask == 0xFFFFFFFFu)
  1078. return 32;
  1079. for (i=0; i<=32; ++i) {
  1080. if (mask == (uint32_t) ~((1u<<(32-i))-1)) {
  1081. return i;
  1082. }
  1083. }
  1084. return -1;
  1085. }
  1086. /** Compare two addresses <b>a1</b> and <b>a2</b> for equality under a
  1087. * netmask of <b>mbits</b> bits. Return -1, 0, or 1.
  1088. *
  1089. * XXXX_IP6 Temporary function to allow masks as bitcounts everywhere. This
  1090. * will be replaced with an IPv6-aware version as soon as 32-bit addresses are
  1091. * no longer passed around.
  1092. */
  1093. int
  1094. addr_mask_cmp_bits(uint32_t a1, uint32_t a2, maskbits_t bits)
  1095. {
  1096. if (bits > 32)
  1097. bits = 32;
  1098. else if (bits == 0)
  1099. return 0;
  1100. a1 >>= (32-bits);
  1101. a2 >>= (32-bits);
  1102. if (a1 < a2)
  1103. return -1;
  1104. else if (a1 > a2)
  1105. return 1;
  1106. else
  1107. return 0;
  1108. }
  1109. /** Parse a string <b>s</b> in the format of (*|port(-maxport)?)?, setting the
  1110. * various *out pointers as appropriate. Return 0 on success, -1 on failure.
  1111. */
  1112. int
  1113. parse_port_range(const char *port, uint16_t *port_min_out,
  1114. uint16_t *port_max_out)
  1115. {
  1116. int port_min, port_max, ok;
  1117. tor_assert(port_min_out);
  1118. tor_assert(port_max_out);
  1119. if (!port || *port == '\0' || strcmp(port, "*") == 0) {
  1120. port_min = 1;
  1121. port_max = 65535;
  1122. } else {
  1123. char *endptr = NULL;
  1124. port_min = (int)tor_parse_long(port, 10, 0, 65535, &ok, &endptr);
  1125. if (!ok) {
  1126. log_warn(LD_GENERAL,
  1127. "Malformed port %s on address range; rejecting.",
  1128. escaped(port));
  1129. return -1;
  1130. } else if (endptr && *endptr == '-') {
  1131. port = endptr+1;
  1132. endptr = NULL;
  1133. port_max = (int)tor_parse_long(port, 10, 1, 65536, &ok, &endptr);
  1134. if (!ok) {
  1135. log_warn(LD_GENERAL,
  1136. "Malformed port %s on address range; rejecting.",
  1137. escaped(port));
  1138. return -1;
  1139. }
  1140. } else {
  1141. port_max = port_min;
  1142. }
  1143. if (port_min > port_max) {
  1144. log_warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
  1145. return -1;
  1146. }
  1147. }
  1148. if (port_min < 1)
  1149. port_min = 1;
  1150. if (port_max > 65535)
  1151. port_max = 65535;
  1152. *port_min_out = (uint16_t) port_min;
  1153. *port_max_out = (uint16_t) port_max;
  1154. return 0;
  1155. }
  1156. /** Parse a string <b>s</b> in the format of
  1157. * (IP(/mask|/mask-bits)?|*)(:(*|port(-maxport))?)?, setting the various
  1158. * *out pointers as appropriate. Return 0 on success, -1 on failure.
  1159. */
  1160. int
  1161. parse_addr_and_port_range(const char *s, uint32_t *addr_out,
  1162. maskbits_t *maskbits_out, uint16_t *port_min_out,
  1163. uint16_t *port_max_out)
  1164. {
  1165. char *address;
  1166. char *mask, *port, *endptr;
  1167. struct in_addr in;
  1168. int bits;
  1169. tor_assert(s);
  1170. tor_assert(addr_out);
  1171. tor_assert(maskbits_out);
  1172. tor_assert(port_min_out);
  1173. tor_assert(port_max_out);
  1174. address = tor_strdup(s);
  1175. /* Break 'address' into separate strings.
  1176. */
  1177. mask = strchr(address,'/');
  1178. port = strchr(mask?mask:address,':');
  1179. if (mask)
  1180. *mask++ = '\0';
  1181. if (port)
  1182. *port++ = '\0';
  1183. /* Now "address" is the IP|'*' part...
  1184. * "mask" is the Mask|Maskbits part...
  1185. * and "port" is the *|port|min-max part.
  1186. */
  1187. if (strcmp(address,"*")==0) {
  1188. *addr_out = 0;
  1189. } else if (tor_inet_aton(address, &in) != 0) {
  1190. *addr_out = ntohl(in.s_addr);
  1191. } else {
  1192. log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
  1193. escaped(address));
  1194. goto err;
  1195. }
  1196. if (!mask) {
  1197. if (strcmp(address,"*")==0)
  1198. *maskbits_out = 0;
  1199. else
  1200. *maskbits_out = 32;
  1201. } else {
  1202. endptr = NULL;
  1203. bits = (int) strtol(mask, &endptr, 10);
  1204. if (!*endptr) {
  1205. /* strtol handled the whole mask. */
  1206. if (bits < 0 || bits > 32) {
  1207. log_warn(LD_GENERAL,
  1208. "Bad number of mask bits on address range; rejecting.");
  1209. goto err;
  1210. }
  1211. *maskbits_out = bits;
  1212. } else if (tor_inet_aton(mask, &in) != 0) {
  1213. bits = addr_mask_get_bits(ntohl(in.s_addr));
  1214. if (bits < 0) {
  1215. log_warn(LD_GENERAL,
  1216. "Mask %s on address range isn't a prefix; dropping",
  1217. escaped(mask));
  1218. goto err;
  1219. }
  1220. *maskbits_out = bits;
  1221. } else {
  1222. log_warn(LD_GENERAL,
  1223. "Malformed mask %s on address range; rejecting.",
  1224. escaped(mask));
  1225. goto err;
  1226. }
  1227. }
  1228. if (parse_port_range(port, port_min_out, port_max_out)<0)
  1229. goto err;
  1230. tor_free(address);
  1231. return 0;
  1232. err:
  1233. tor_free(address);
  1234. return -1;
  1235. }
  1236. /** Given an IPv4 in_addr struct *<b>in</b> (in network order, as usual),
  1237. * write it as a string into the <b>buf_len</b>-byte buffer in
  1238. * <b>buf</b>.
  1239. */
  1240. int
  1241. tor_inet_ntoa(const struct in_addr *in, char *buf, size_t buf_len)
  1242. {
  1243. uint32_t a = ntohl(in->s_addr);
  1244. return tor_snprintf(buf, buf_len, "%d.%d.%d.%d",
  1245. (int)(uint8_t)((a>>24)&0xff),
  1246. (int)(uint8_t)((a>>16)&0xff),
  1247. (int)(uint8_t)((a>>8 )&0xff),
  1248. (int)(uint8_t)((a )&0xff));
  1249. }
  1250. /** Given a host-order <b>addr</b>, call tor_inet_ntop() on it
  1251. * and return a strdup of the resulting address.
  1252. */
  1253. char *
  1254. tor_dup_ip(uint32_t addr)
  1255. {
  1256. char buf[TOR_ADDR_BUF_LEN];
  1257. struct in_addr in;
  1258. in.s_addr = htonl(addr);
  1259. tor_inet_ntop(AF_INET, &in, buf, sizeof(buf));
  1260. return tor_strdup(buf);
  1261. }
  1262. /**
  1263. * Set *<b>addr</b> to the host-order IPv4 address (if any) of whatever
  1264. * interface connects to the internet. This address should only be used in
  1265. * checking whether our address has changed. Return 0 on success, -1 on
  1266. * failure.
  1267. */
  1268. int
  1269. get_interface_address(int severity, uint32_t *addr)
  1270. {
  1271. tor_addr_t local_addr;
  1272. int r;
  1273. r = get_interface_address6(severity, AF_INET, &local_addr);
  1274. if (r>=0)
  1275. *addr = tor_addr_to_ipv4h(&local_addr);
  1276. return r;
  1277. }