address.c 41 KB

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