address.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  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. #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 = (uint32_t)
  356. (((inaddr.s_addr & 0x000000ff) << 24)
  357. |((inaddr.s_addr & 0x0000ff00) << 8)
  358. |((inaddr.s_addr & 0x00ff0000) >> 8)
  359. |((inaddr.s_addr & 0xff000000) >> 24));
  360. if (result) {
  361. tor_addr_from_in(result, &inaddr);
  362. }
  363. return 1;
  364. }
  365. if (!strcasecmpend(address, ".ip6.arpa")) {
  366. const char *cp;
  367. int i;
  368. int n0, n1;
  369. struct in6_addr in6;
  370. if (family == AF_INET)
  371. return -1;
  372. cp = address;
  373. for (i = 0; i < 16; ++i) {
  374. n0 = hex_decode_digit(*cp++); /* The low-order nybble appears first. */
  375. if (*cp++ != '.') return -1; /* Then a dot. */
  376. n1 = hex_decode_digit(*cp++); /* The high-order nybble appears first. */
  377. if (*cp++ != '.') return -1; /* Then another dot. */
  378. if (n0<0 || n1 < 0) /* Both nybbles must be hex. */
  379. return -1;
  380. /* We don't check the length of the string in here. But that's okay,
  381. * since we already know that the string ends with ".ip6.arpa", and
  382. * there is no way to frameshift .ip6.arpa so it fits into the pattern
  383. * of hexdigit, period, hexdigit, period that we enforce above.
  384. */
  385. /* Assign from low-byte to high-byte. */
  386. in6.s6_addr[15-i] = n0 | (n1 << 4);
  387. }
  388. if (strcasecmp(cp, "ip6.arpa"))
  389. return -1;
  390. if (result) {
  391. tor_addr_from_in6(result, &in6);
  392. }
  393. return 1;
  394. }
  395. if (accept_regular) {
  396. tor_addr_t tmp;
  397. int r = tor_addr_from_str(&tmp, address);
  398. if (r < 0)
  399. return 0;
  400. if (r != family && family != AF_UNSPEC)
  401. return -1;
  402. if (result)
  403. memcpy(result, &tmp, sizeof(tor_addr_t));
  404. return 1;
  405. }
  406. return 0;
  407. }
  408. /** Convert <b>addr</b> to an in-addr.arpa name or a .ip6.arpa name, and store
  409. * the result in the <b>outlen</b>-byte buffer at <b>out</b>. Return 0 on
  410. * success, -1 on failure. */
  411. int
  412. tor_addr_to_reverse_lookup_name(char *out, size_t outlen,
  413. const tor_addr_t *addr)
  414. {
  415. if (addr->family == AF_INET) {
  416. uint32_t a = tor_addr_to_ipv4h(addr);
  417. return tor_snprintf(out, outlen, "%d.%d.%d.%d.in-addr.arpa",
  418. (int)(uint8_t)((a )&0xff),
  419. (int)(uint8_t)((a>>8 )&0xff),
  420. (int)(uint8_t)((a>>16)&0xff),
  421. (int)(uint8_t)((a>>24)&0xff));
  422. } else if (addr->family == AF_INET6) {
  423. int i;
  424. char *cp = out;
  425. const uint8_t *bytes = tor_addr_to_in6_addr8(addr);
  426. if (outlen < REVERSE_LOOKUP_NAME_BUF_LEN)
  427. return -1;
  428. for (i = 15; i >= 0; --i) {
  429. uint8_t byte = bytes[i];
  430. *cp++ = "0123456789abcdef"[byte & 0x0f];
  431. *cp++ = '.';
  432. *cp++ = "0123456789abcdef"[byte >> 4];
  433. *cp++ = '.';
  434. }
  435. memcpy(cp, "ip6.arpa", 9); /* 8 characters plus NUL */
  436. return 0;
  437. }
  438. return -1;
  439. }
  440. /** Parse a string <b>s</b> containing an IPv4/IPv6 address, and possibly
  441. * a mask and port or port range. Store the parsed address in
  442. * <b>addr_out</b>, a mask (if any) in <b>mask_out</b>, and port(s) (if any)
  443. * in <b>port_min_out</b> and <b>port_max_out</b>.
  444. *
  445. * The syntax is:
  446. * Address OptMask OptPortRange
  447. * Address ::= IPv4Address / "[" IPv6Address "]" / "*"
  448. * OptMask ::= "/" Integer /
  449. * OptPortRange ::= ":*" / ":" Integer / ":" Integer "-" Integer /
  450. *
  451. * - If mask, minport, or maxport are NULL, we do not want these
  452. * options to be set; treat them as an error if present.
  453. * - If the string has no mask, the mask is set to /32 (IPv4) or /128 (IPv6).
  454. * - If the string has one port, it is placed in both min and max port
  455. * variables.
  456. * - If the string has no port(s), port_(min|max)_out are set to 1 and 65535.
  457. *
  458. * Return an address family on success, or -1 if an invalid address string is
  459. * provided.
  460. */
  461. int
  462. tor_addr_parse_mask_ports(const char *s, tor_addr_t *addr_out,
  463. maskbits_t *maskbits_out,
  464. uint16_t *port_min_out, uint16_t *port_max_out)
  465. {
  466. char *base = NULL, *address, *mask = NULL, *port = NULL, *rbracket = NULL;
  467. char *endptr;
  468. int any_flag=0, v4map=0;
  469. sa_family_t family;
  470. struct in6_addr in6_tmp;
  471. struct in_addr in_tmp;
  472. tor_assert(s);
  473. tor_assert(addr_out);
  474. /** Longest possible length for an address, mask, and port-range combination.
  475. * Includes IP, [], /mask, :, ports */
  476. #define MAX_ADDRESS_LENGTH (TOR_ADDR_BUF_LEN+2+(1+INET_NTOA_BUF_LEN)+12+1)
  477. if (strlen(s) > MAX_ADDRESS_LENGTH) {
  478. log_warn(LD_GENERAL, "Impossibly long IP %s; rejecting", escaped(s));
  479. goto err;
  480. }
  481. base = tor_strdup(s);
  482. /* Break 'base' into separate strings. */
  483. address = base;
  484. if (*address == '[') { /* Probably IPv6 */
  485. address++;
  486. rbracket = strchr(address, ']');
  487. if (!rbracket) {
  488. log_warn(LD_GENERAL,
  489. "No closing IPv6 bracket in address pattern; rejecting.");
  490. goto err;
  491. }
  492. }
  493. mask = strchr((rbracket?rbracket:address),'/');
  494. port = strchr((mask?mask:(rbracket?rbracket:address)), ':');
  495. if (port)
  496. *port++ = '\0';
  497. if (mask)
  498. *mask++ = '\0';
  499. if (rbracket)
  500. *rbracket = '\0';
  501. if (port && mask)
  502. tor_assert(port > mask);
  503. if (mask && rbracket)
  504. tor_assert(mask > rbracket);
  505. /* Now "address" is the a.b.c.d|'*'|abcd::1 part...
  506. * "mask" is the Mask|Maskbits part...
  507. * and "port" is the *|port|min-max part.
  508. */
  509. /* Process the address portion */
  510. memset(addr_out, 0, sizeof(tor_addr_t));
  511. if (!strcmp(address, "*")) {
  512. family = AF_INET; /* AF_UNSPEC ???? XXXX_IP6 */
  513. tor_addr_from_ipv4h(addr_out, 0);
  514. any_flag = 1;
  515. } else if (tor_inet_pton(AF_INET6, address, &in6_tmp) > 0) {
  516. family = AF_INET6;
  517. tor_addr_from_in6(addr_out, &in6_tmp);
  518. } else if (tor_inet_pton(AF_INET, address, &in_tmp) > 0) {
  519. family = AF_INET;
  520. tor_addr_from_in(addr_out, &in_tmp);
  521. } else {
  522. log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
  523. escaped(address));
  524. goto err;
  525. }
  526. v4map = tor_addr_is_v4(addr_out);
  527. /* Parse mask */
  528. if (maskbits_out) {
  529. int bits = 0;
  530. struct in_addr v4mask;
  531. if (mask) { /* the caller (tried to) specify a mask */
  532. bits = (int) strtol(mask, &endptr, 10);
  533. if (!*endptr) { /* strtol converted everything, so it was an integer */
  534. if ((bits<0 || bits>128) ||
  535. (family == AF_INET && bits > 32)) {
  536. log_warn(LD_GENERAL,
  537. "Bad number of mask bits (%d) on address range; rejecting.",
  538. bits);
  539. goto err;
  540. }
  541. } else { /* mask might still be an address-style mask */
  542. if (tor_inet_pton(AF_INET, mask, &v4mask) > 0) {
  543. bits = addr_mask_get_bits(ntohl(v4mask.s_addr));
  544. if (bits < 0) {
  545. log_warn(LD_GENERAL,
  546. "IPv4-style mask %s is not a prefix address; rejecting.",
  547. escaped(mask));
  548. goto err;
  549. }
  550. } else { /* Not IPv4; we don't do address-style IPv6 masks. */
  551. log_warn(LD_GENERAL,
  552. "Malformed mask on address range %s; rejecting.",
  553. escaped(s));
  554. goto err;
  555. }
  556. }
  557. if (family == AF_INET6 && v4map) {
  558. if (bits > 32 && bits < 96) { /* Crazy */
  559. log_warn(LD_GENERAL,
  560. "Bad mask bits %i for V4-mapped V6 address; rejecting.",
  561. bits);
  562. goto err;
  563. }
  564. /* XXXX_IP6 is this really what we want? */
  565. bits = 96 + bits%32; /* map v4-mapped masks onto 96-128 bits */
  566. }
  567. } else { /* pick an appropriate mask, as none was given */
  568. if (any_flag)
  569. bits = 0; /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */
  570. else if (tor_addr_family(addr_out) == AF_INET)
  571. bits = 32;
  572. else if (tor_addr_family(addr_out) == AF_INET6)
  573. bits = 128;
  574. }
  575. *maskbits_out = (maskbits_t) bits;
  576. } else {
  577. if (mask) {
  578. log_warn(LD_GENERAL,
  579. "Unexpected mask in address %s; rejecting", escaped(s));
  580. goto err;
  581. }
  582. }
  583. /* Parse port(s) */
  584. if (port_min_out) {
  585. uint16_t port2;
  586. if (!port_max_out) /* caller specified one port; fake the second one */
  587. port_max_out = &port2;
  588. if (parse_port_range(port, port_min_out, port_max_out) < 0) {
  589. goto err;
  590. } else if ((*port_min_out != *port_max_out) && port_max_out == &port2) {
  591. log_warn(LD_GENERAL,
  592. "Wanted one port from address range, but there are two.");
  593. port_max_out = NULL; /* caller specified one port, so set this back */
  594. goto err;
  595. }
  596. } else {
  597. if (port) {
  598. log_warn(LD_GENERAL,
  599. "Unexpected ports in address %s; rejecting", escaped(s));
  600. goto err;
  601. }
  602. }
  603. tor_free(base);
  604. return tor_addr_family(addr_out);
  605. err:
  606. tor_free(base);
  607. return -1;
  608. }
  609. /** Determine whether an address is IPv4, either native or IPv4-mapped IPv6.
  610. * Note that this is about representation only, as any decent stack will
  611. * reject IPv4-mapped addresses received on the wire (and won't use them
  612. * on the wire either).
  613. */
  614. int
  615. tor_addr_is_v4(const tor_addr_t *addr)
  616. {
  617. tor_assert(addr);
  618. if (tor_addr_family(addr) == AF_INET)
  619. return 1;
  620. if (tor_addr_family(addr) == AF_INET6) {
  621. /* First two don't need to be ordered */
  622. uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  623. if (a32[0] == 0 && a32[1] == 0 && ntohl(a32[2]) == 0x0000ffffu)
  624. return 1;
  625. }
  626. return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */
  627. }
  628. /** Determine whether an address <b>addr</b> is null, either all zeroes or
  629. * belonging to family AF_UNSPEC.
  630. */
  631. int
  632. tor_addr_is_null(const tor_addr_t *addr)
  633. {
  634. tor_assert(addr);
  635. switch (tor_addr_family(addr)) {
  636. case AF_INET6: {
  637. uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  638. return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 0);
  639. }
  640. case AF_INET:
  641. return (tor_addr_to_ipv4n(addr) == 0);
  642. case AF_UNSPEC:
  643. return 1;
  644. default:
  645. log_warn(LD_BUG, "Called with unknown address family %d",
  646. (int)tor_addr_family(addr));
  647. return 0;
  648. }
  649. //return 1;
  650. }
  651. /** Return true iff <b>addr</b> is a loopback address */
  652. int
  653. tor_addr_is_loopback(const tor_addr_t *addr)
  654. {
  655. tor_assert(addr);
  656. switch (tor_addr_family(addr)) {
  657. case AF_INET6: {
  658. /* ::1 */
  659. uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  660. return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 1);
  661. }
  662. case AF_INET:
  663. /* 127.0.0.1 */
  664. return (tor_addr_to_ipv4h(addr) & 0xff000000) == 0x7f000000;
  665. case AF_UNSPEC:
  666. return 0;
  667. default:
  668. tor_fragile_assert();
  669. return 0;
  670. }
  671. }
  672. /** Set <b>dest</b> to equal the IPv4 address in <b>v4addr</b> (given in
  673. * network order). */
  674. void
  675. tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
  676. {
  677. tor_assert(dest);
  678. memset(dest, 0, sizeof(tor_addr_t));
  679. dest->family = AF_INET;
  680. dest->addr.in_addr.s_addr = v4addr;
  681. }
  682. /** Set <b>dest</b> to equal the IPv6 address in the 16 bytes at
  683. * <b>ipv6_bytes</b>. */
  684. void
  685. tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
  686. {
  687. tor_assert(dest);
  688. tor_assert(ipv6_bytes);
  689. memset(dest, 0, sizeof(tor_addr_t));
  690. dest->family = AF_INET6;
  691. memcpy(dest->addr.in6_addr.s6_addr, ipv6_bytes, 16);
  692. }
  693. /** Set <b>dest</b> equal to the IPv6 address in the in6_addr <b>in6</b>. */
  694. void
  695. tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
  696. {
  697. tor_addr_from_ipv6_bytes(dest, (const char*)in6->s6_addr);
  698. }
  699. /** Copy a tor_addr_t from <b>src</b> to <b>dest</b>.
  700. */
  701. void
  702. tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
  703. {
  704. if (src == dest)
  705. return;
  706. tor_assert(src);
  707. tor_assert(dest);
  708. memcpy(dest, src, sizeof(tor_addr_t));
  709. }
  710. /** Given two addresses <b>addr1</b> and <b>addr2</b>, return 0 if the two
  711. * addresses are equivalent under the mask mbits, less than 0 if addr1
  712. * precedes addr2, and greater than 0 otherwise.
  713. *
  714. * Different address families (IPv4 vs IPv6) are always considered unequal if
  715. * <b>how</b> is CMP_EXACT; otherwise, IPv6-mapped IPv4 addresses are
  716. * considered equivalent to their IPv4 equivalents.
  717. */
  718. int
  719. tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2,
  720. tor_addr_comparison_t how)
  721. {
  722. return tor_addr_compare_masked(addr1, addr2, 128, how);
  723. }
  724. /** As tor_addr_compare(), but only looks at the first <b>mask</b> bits of
  725. * the address.
  726. *
  727. * Reduce over-specific masks (>128 for ipv6, >32 for ipv4) to 128 or 32.
  728. *
  729. * The mask is interpreted relative to <b>addr1</b>, so that if a is
  730. * \::ffff:1.2.3.4, and b is 3.4.5.6,
  731. * tor_addr_compare_masked(a,b,100,CMP_SEMANTIC) is the same as
  732. * -tor_addr_compare_masked(b,a,4,CMP_SEMANTIC).
  733. *
  734. * We guarantee that the ordering from tor_addr_compare_masked is a total
  735. * order on addresses, but not that it is any particular order, or that it
  736. * will be the same from one version to the next.
  737. */
  738. int
  739. tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2,
  740. maskbits_t mbits, tor_addr_comparison_t how)
  741. {
  742. /** Helper: Evaluates to -1 if a is less than b, 0 if a equals b, or 1 if a
  743. * is greater than b. May evaluate a and b more than once. */
  744. #define TRISTATE(a,b) (((a)<(b))?-1: (((a)==(b))?0:1))
  745. sa_family_t family1, family2, v_family1, v_family2;
  746. tor_assert(addr1 && addr2);
  747. v_family1 = family1 = tor_addr_family(addr1);
  748. v_family2 = family2 = tor_addr_family(addr2);
  749. if (family1==family2) {
  750. /* When the families are the same, there's only one way to do the
  751. * comparison: exactly. */
  752. int r;
  753. switch (family1) {
  754. case AF_UNSPEC:
  755. return 0; /* All unspecified addresses are equal */
  756. case AF_INET: {
  757. uint32_t a1 = tor_addr_to_ipv4h(addr1);
  758. uint32_t a2 = tor_addr_to_ipv4h(addr2);
  759. if (mbits <= 0)
  760. return 0;
  761. if (mbits > 32)
  762. mbits = 32;
  763. a1 >>= (32-mbits);
  764. a2 >>= (32-mbits);
  765. r = TRISTATE(a1, a2);
  766. return r;
  767. }
  768. case AF_INET6: {
  769. const uint8_t *a1 = tor_addr_to_in6_addr8(addr1);
  770. const uint8_t *a2 = tor_addr_to_in6_addr8(addr2);
  771. const int bytes = mbits >> 3;
  772. const int leftover_bits = mbits & 7;
  773. if (bytes && (r = memcmp(a1, a2, bytes))) {
  774. return r;
  775. } else if (leftover_bits) {
  776. uint8_t b1 = a1[bytes] >> (8-leftover_bits);
  777. uint8_t b2 = a2[bytes] >> (8-leftover_bits);
  778. return TRISTATE(b1, b2);
  779. } else {
  780. return 0;
  781. }
  782. }
  783. default:
  784. tor_fragile_assert();
  785. return 0;
  786. }
  787. } else if (how == CMP_EXACT) {
  788. /* Unequal families and an exact comparison? Stop now! */
  789. return TRISTATE(family1, family2);
  790. }
  791. if (mbits == 0)
  792. return 0;
  793. if (family1 == AF_INET6 && tor_addr_is_v4(addr1))
  794. v_family1 = AF_INET;
  795. if (family2 == AF_INET6 && tor_addr_is_v4(addr2))
  796. v_family2 = AF_INET;
  797. if (v_family1 == v_family2) {
  798. /* One or both addresses are a mapped ipv4 address. */
  799. uint32_t a1, a2;
  800. if (family1 == AF_INET6) {
  801. a1 = tor_addr_to_mapped_ipv4h(addr1);
  802. if (mbits <= 96)
  803. return 0;
  804. mbits -= 96; /* We just decided that the first 96 bits of a1 "match". */
  805. } else {
  806. a1 = tor_addr_to_ipv4h(addr1);
  807. }
  808. if (family2 == AF_INET6) {
  809. a2 = tor_addr_to_mapped_ipv4h(addr2);
  810. } else {
  811. a2 = tor_addr_to_ipv4h(addr2);
  812. }
  813. if (mbits <= 0) return 0;
  814. if (mbits > 32) mbits = 32;
  815. a1 >>= (32-mbits);
  816. a2 >>= (32-mbits);
  817. return TRISTATE(a1, a2);
  818. } else {
  819. /* Unequal families, and semantic comparison, and no semantic family
  820. * matches. */
  821. return TRISTATE(family1, family2);
  822. }
  823. }
  824. /** Return a hash code based on the address addr */
  825. unsigned int
  826. tor_addr_hash(const tor_addr_t *addr)
  827. {
  828. switch (tor_addr_family(addr)) {
  829. case AF_INET:
  830. return tor_addr_to_ipv4h(addr);
  831. case AF_UNSPEC:
  832. return 0x4e4d5342;
  833. case AF_INET6: {
  834. const uint32_t *u = tor_addr_to_in6_addr32(addr);
  835. return u[0] + u[1] + u[2] + u[3];
  836. }
  837. default:
  838. tor_fragile_assert();
  839. return 0;
  840. }
  841. }
  842. /** Return a newly allocated string with a representation of <b>addr</b>. */
  843. char *
  844. tor_dup_addr(const tor_addr_t *addr)
  845. {
  846. char buf[TOR_ADDR_BUF_LEN];
  847. tor_addr_to_str(buf, addr, sizeof(buf), 0);
  848. return tor_strdup(buf);
  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 addr_len;
  950. tor_assert(addr);
  951. memset(addr, 0, sizeof(tor_addr_t));
  952. memset(&target_addr, 0, sizeof(target_addr));
  953. /* Don't worry: no packets are sent. We just need to use a real address
  954. * on the actual Internet. */
  955. if (family == AF_INET6) {
  956. struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&target_addr;
  957. /* Use the "discard" service port */
  958. sin6->sin6_port = htons(9);
  959. sock = tor_open_socket(PF_INET6,SOCK_DGRAM,IPPROTO_UDP);
  960. addr_len = (socklen_t)sizeof(struct sockaddr_in6);
  961. sin6->sin6_family = AF_INET6;
  962. S6_ADDR16(sin6->sin6_addr)[0] = htons(0x2002); /* 2002:: */
  963. } else if (family == AF_INET) {
  964. struct sockaddr_in *sin = (struct sockaddr_in*)&target_addr;
  965. /* Use the "discard" service port */
  966. sin->sin_port = htons(9);
  967. sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
  968. addr_len = (socklen_t)sizeof(struct sockaddr_in);
  969. sin->sin_family = AF_INET;
  970. sin->sin_addr.s_addr = htonl(0x12000001); /* 18.0.0.1 */
  971. } else {
  972. return -1;
  973. }
  974. if (sock < 0) {
  975. int e = tor_socket_errno(-1);
  976. log_fn(severity, LD_NET, "unable to create socket: %s",
  977. tor_socket_strerror(e));
  978. goto err;
  979. }
  980. if (connect(sock,(struct sockaddr *)&target_addr, addr_len) < 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, &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. }