address.c 41 KB

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