address.c 40 KB

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