address.c 39 KB

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