address.c 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2013, 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. #include "container.h"
  15. #include "sandbox.h"
  16. #ifdef _WIN32
  17. #include <process.h>
  18. #include <windows.h>
  19. #include <winsock2.h>
  20. /* For access to structs needed by GetAdaptersAddresses */
  21. #undef _WIN32_WINNT
  22. #define _WIN32_WINNT 0x0501
  23. #include <iphlpapi.h>
  24. #endif
  25. #ifdef HAVE_SYS_TIME_H
  26. #include <sys/time.h>
  27. #endif
  28. #ifdef HAVE_UNISTD_H
  29. #include <unistd.h>
  30. #endif
  31. #ifdef HAVE_ERRNO_H
  32. #include <errno.h>
  33. #endif
  34. #ifdef HAVE_NETINET_IN_H
  35. #include <netinet/in.h>
  36. #endif
  37. #ifdef HAVE_ARPA_INET_H
  38. #include <arpa/inet.h>
  39. #endif
  40. #ifdef HAVE_SYS_SOCKET_H
  41. #include <sys/socket.h>
  42. #endif
  43. #ifdef HAVE_NETDB_H
  44. #include <netdb.h>
  45. #endif
  46. #ifdef HAVE_SYS_PARAM_H
  47. #include <sys/param.h> /* FreeBSD needs this to know what version it is */
  48. #endif
  49. #ifdef HAVE_SYS_UN_H
  50. #include <sys/un.h>
  51. #endif
  52. #ifdef HAVE_IFADDRS_H
  53. #include <ifaddrs.h>
  54. #endif
  55. #ifdef HAVE_SYS_IOCTL_H
  56. #include <sys/ioctl.h>
  57. #endif
  58. #ifdef HAVE_NET_IF_H
  59. #include <net/if.h>
  60. #endif
  61. #include <stdarg.h>
  62. #include <stdio.h>
  63. #include <stdlib.h>
  64. #include <string.h>
  65. #include <assert.h>
  66. /* tor_addr_is_null() and maybe other functions rely on AF_UNSPEC being 0 to
  67. * work correctly. Bail out here if we've found a platform where AF_UNSPEC
  68. * isn't 0. */
  69. #if AF_UNSPEC != 0
  70. #error We rely on AF_UNSPEC being 0. Let us know about your platform, please!
  71. #endif
  72. /** Convert the tor_addr_t in <b>a</b>, with port in <b>port</b>, into a
  73. * sockaddr object in *<b>sa_out</b> of object size <b>len</b>. If not enough
  74. * room is available in sa_out, or on error, return 0. On success, return
  75. * the length of the sockaddr.
  76. *
  77. * Interface note: ordinarily, we return -1 for error. We can't do that here,
  78. * since socklen_t is unsigned on some platforms.
  79. **/
  80. socklen_t
  81. tor_addr_to_sockaddr(const tor_addr_t *a,
  82. uint16_t port,
  83. struct sockaddr *sa_out,
  84. socklen_t len)
  85. {
  86. sa_family_t family = tor_addr_family(a);
  87. if (family == AF_INET) {
  88. struct sockaddr_in *sin;
  89. if (len < (int)sizeof(struct sockaddr_in))
  90. return 0;
  91. sin = (struct sockaddr_in *)sa_out;
  92. memset(sin, 0, sizeof(struct sockaddr_in));
  93. #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
  94. sin->sin_len = sizeof(struct sockaddr_in);
  95. #endif
  96. sin->sin_family = AF_INET;
  97. sin->sin_port = htons(port);
  98. sin->sin_addr.s_addr = tor_addr_to_ipv4n(a);
  99. return sizeof(struct sockaddr_in);
  100. } else if (family == AF_INET6) {
  101. struct sockaddr_in6 *sin6;
  102. if (len < (int)sizeof(struct sockaddr_in6))
  103. return 0;
  104. sin6 = (struct sockaddr_in6 *)sa_out;
  105. memset(sin6, 0, sizeof(struct sockaddr_in6));
  106. #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
  107. sin6->sin6_len = sizeof(struct sockaddr_in6);
  108. #endif
  109. sin6->sin6_family = AF_INET6;
  110. sin6->sin6_port = htons(port);
  111. memcpy(&sin6->sin6_addr, tor_addr_to_in6(a), sizeof(struct in6_addr));
  112. return sizeof(struct sockaddr_in6);
  113. } else {
  114. return 0;
  115. }
  116. }
  117. /** Set the tor_addr_t in <b>a</b> to contain the socket address contained in
  118. * <b>sa</b>. */
  119. int
  120. tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa,
  121. uint16_t *port_out)
  122. {
  123. tor_assert(a);
  124. tor_assert(sa);
  125. if (sa->sa_family == AF_INET) {
  126. struct sockaddr_in *sin = (struct sockaddr_in *) sa;
  127. tor_addr_from_ipv4n(a, sin->sin_addr.s_addr);
  128. if (port_out)
  129. *port_out = ntohs(sin->sin_port);
  130. } else if (sa->sa_family == AF_INET6) {
  131. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
  132. tor_addr_from_in6(a, &sin6->sin6_addr);
  133. if (port_out)
  134. *port_out = ntohs(sin6->sin6_port);
  135. } else {
  136. tor_addr_make_unspec(a);
  137. return -1;
  138. }
  139. return 0;
  140. }
  141. /** Return a newly allocated string holding the address described in
  142. * <b>sa</b>. AF_UNIX, AF_UNSPEC, AF_INET, and AF_INET6 are supported. */
  143. char *
  144. tor_sockaddr_to_str(const struct sockaddr *sa)
  145. {
  146. char address[TOR_ADDR_BUF_LEN];
  147. char *result;
  148. tor_addr_t addr;
  149. uint16_t port;
  150. #ifdef HAVE_SYS_UN_H
  151. if (sa->sa_family == AF_UNIX) {
  152. struct sockaddr_un *s_un = (struct sockaddr_un *)sa;
  153. tor_asprintf(&result, "unix:%s", s_un->sun_path);
  154. return result;
  155. }
  156. #endif
  157. if (sa->sa_family == AF_UNSPEC)
  158. return tor_strdup("unspec");
  159. if (tor_addr_from_sockaddr(&addr, sa, &port) < 0)
  160. return NULL;
  161. if (! tor_addr_to_str(address, &addr, sizeof(address), 1))
  162. return NULL;
  163. tor_asprintf(&result, "%s:%d", address, (int)port);
  164. return result;
  165. }
  166. /** Set address <b>a</b> to the unspecified address. This address belongs to
  167. * no family. */
  168. void
  169. tor_addr_make_unspec(tor_addr_t *a)
  170. {
  171. memset(a, 0, sizeof(*a));
  172. a->family = AF_UNSPEC;
  173. }
  174. /** Set address <b>a</b> to the null address in address family <b>family</b>.
  175. * The null address for AF_INET is 0.0.0.0. The null address for AF_INET6 is
  176. * [::]. AF_UNSPEC is all null. */
  177. void
  178. tor_addr_make_null(tor_addr_t *a, sa_family_t family)
  179. {
  180. memset(a, 0, sizeof(*a));
  181. a->family = family;
  182. }
  183. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  184. * *<b>addr</b> to the proper IP address and family. The <b>family</b>
  185. * argument (which must be AF_INET, AF_INET6, or AF_UNSPEC) declares a
  186. * <i>preferred</i> family, though another one may be returned if only one
  187. * family is implemented for this address.
  188. *
  189. * Return 0 on success, -1 on failure; 1 on transient failure.
  190. */
  191. int
  192. tor_addr_lookup(const char *name, uint16_t family, tor_addr_t *addr)
  193. {
  194. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  195. * something.
  196. */
  197. struct in_addr iaddr;
  198. struct in6_addr iaddr6;
  199. tor_assert(name);
  200. tor_assert(addr);
  201. tor_assert(family == AF_INET || family == AF_INET6 || family == AF_UNSPEC);
  202. if (!*name) {
  203. /* Empty address is an error. */
  204. return -1;
  205. } else if (tor_inet_pton(AF_INET, name, &iaddr)) {
  206. /* It's an IPv4 IP. */
  207. if (family == AF_INET6)
  208. return -1;
  209. tor_addr_from_in(addr, &iaddr);
  210. return 0;
  211. } else if (tor_inet_pton(AF_INET6, name, &iaddr6)) {
  212. if (family == AF_INET)
  213. return -1;
  214. tor_addr_from_in6(addr, &iaddr6);
  215. return 0;
  216. } else {
  217. #ifdef HAVE_GETADDRINFO
  218. int err;
  219. struct addrinfo *res=NULL, *res_p;
  220. struct addrinfo *best=NULL;
  221. struct addrinfo hints;
  222. int result = -1;
  223. memset(&hints, 0, sizeof(hints));
  224. hints.ai_family = family;
  225. hints.ai_socktype = SOCK_STREAM;
  226. err = sandbox_getaddrinfo(name, NULL, &hints, &res);
  227. /* The check for 'res' here shouldn't be necessary, but it makes static
  228. * analysis tools happy. */
  229. if (!err && res) {
  230. best = NULL;
  231. for (res_p = res; res_p; res_p = res_p->ai_next) {
  232. if (family == AF_UNSPEC) {
  233. if (res_p->ai_family == AF_INET) {
  234. best = res_p;
  235. break;
  236. } else if (res_p->ai_family == AF_INET6 && !best) {
  237. best = res_p;
  238. }
  239. } else if (family == res_p->ai_family) {
  240. best = res_p;
  241. break;
  242. }
  243. }
  244. if (!best)
  245. best = res;
  246. if (best->ai_family == AF_INET) {
  247. tor_addr_from_in(addr,
  248. &((struct sockaddr_in*)best->ai_addr)->sin_addr);
  249. result = 0;
  250. } else if (best->ai_family == AF_INET6) {
  251. tor_addr_from_in6(addr,
  252. &((struct sockaddr_in6*)best->ai_addr)->sin6_addr);
  253. result = 0;
  254. }
  255. sandbox_freeaddrinfo(res);
  256. return result;
  257. }
  258. return (err == EAI_AGAIN) ? 1 : -1;
  259. #else
  260. struct hostent *ent;
  261. int err;
  262. #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
  263. char buf[2048];
  264. struct hostent hostent;
  265. int r;
  266. r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err);
  267. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  268. char buf[2048];
  269. struct hostent hostent;
  270. ent = gethostbyname_r(name, &hostent, buf, sizeof(buf), &err);
  271. #elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
  272. struct hostent_data data;
  273. struct hostent hent;
  274. memset(&data, 0, sizeof(data));
  275. err = gethostbyname_r(name, &hent, &data);
  276. ent = err ? NULL : &hent;
  277. #else
  278. ent = gethostbyname(name);
  279. #ifdef _WIN32
  280. err = WSAGetLastError();
  281. #else
  282. err = h_errno;
  283. #endif
  284. #endif /* endif HAVE_GETHOSTBYNAME_R_6_ARG. */
  285. if (ent) {
  286. if (ent->h_addrtype == AF_INET) {
  287. tor_addr_from_in(addr, (struct in_addr*) ent->h_addr);
  288. } else if (ent->h_addrtype == AF_INET6) {
  289. tor_addr_from_in6(addr, (struct in6_addr*) ent->h_addr);
  290. } else {
  291. tor_assert(0); /* gethostbyname() returned a bizarre addrtype */
  292. }
  293. return 0;
  294. }
  295. #ifdef _WIN32
  296. return (err == WSATRY_AGAIN) ? 1 : -1;
  297. #else
  298. return (err == TRY_AGAIN) ? 1 : -1;
  299. #endif
  300. #endif
  301. }
  302. }
  303. /** Return true iff <b>ip</b> is an IP reserved to localhost or local networks
  304. * in RFC1918 or RFC4193 or RFC4291. (fec0::/10, deprecated by RFC3879, is
  305. * also treated as internal for now.)
  306. */
  307. int
  308. tor_addr_is_internal_(const tor_addr_t *addr, int for_listening,
  309. const char *filename, int lineno)
  310. {
  311. uint32_t iph4 = 0;
  312. uint32_t iph6[4];
  313. sa_family_t v_family;
  314. v_family = tor_addr_family(addr);
  315. if (v_family == AF_INET) {
  316. iph4 = tor_addr_to_ipv4h(addr);
  317. } else if (v_family == AF_INET6) {
  318. if (tor_addr_is_v4(addr)) { /* v4-mapped */
  319. v_family = AF_INET;
  320. iph4 = ntohl(tor_addr_to_in6_addr32(addr)[3]);
  321. }
  322. }
  323. if (v_family == AF_INET6) {
  324. const uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  325. iph6[0] = ntohl(a32[0]);
  326. iph6[1] = ntohl(a32[1]);
  327. iph6[2] = ntohl(a32[2]);
  328. iph6[3] = ntohl(a32[3]);
  329. if (for_listening && !iph6[0] && !iph6[1] && !iph6[2] && !iph6[3]) /* :: */
  330. return 0;
  331. if (((iph6[0] & 0xfe000000) == 0xfc000000) || /* fc00/7 - RFC4193 */
  332. ((iph6[0] & 0xffc00000) == 0xfe800000) || /* fe80/10 - RFC4291 */
  333. ((iph6[0] & 0xffc00000) == 0xfec00000)) /* fec0/10 D- RFC3879 */
  334. return 1;
  335. if (!iph6[0] && !iph6[1] && !iph6[2] &&
  336. ((iph6[3] & 0xfffffffe) == 0x00000000)) /* ::/127 */
  337. return 1;
  338. return 0;
  339. } else if (v_family == AF_INET) {
  340. if (for_listening && !iph4) /* special case for binding to 0.0.0.0 */
  341. return 0;
  342. if (((iph4 & 0xff000000) == 0x0a000000) || /* 10/8 */
  343. ((iph4 & 0xff000000) == 0x00000000) || /* 0/8 */
  344. ((iph4 & 0xff000000) == 0x7f000000) || /* 127/8 */
  345. ((iph4 & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  346. ((iph4 & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  347. ((iph4 & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  348. return 1;
  349. return 0;
  350. }
  351. /* unknown address family... assume it's not safe for external use */
  352. /* rather than tor_assert(0) */
  353. log_warn(LD_BUG, "tor_addr_is_internal() called from %s:%d with a "
  354. "non-IP address of type %d", filename, lineno, (int)v_family);
  355. tor_fragile_assert();
  356. return 1;
  357. }
  358. /** Convert a tor_addr_t <b>addr</b> into a string, and store it in
  359. * <b>dest</b> of size <b>len</b>. Returns a pointer to dest on success,
  360. * or NULL on failure. If <b>decorate</b>, surround IPv6 addresses with
  361. * brackets.
  362. */
  363. const char *
  364. tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
  365. {
  366. const char *ptr;
  367. tor_assert(addr && dest);
  368. switch (tor_addr_family(addr)) {
  369. case AF_INET:
  370. /* Shortest addr x.x.x.x + \0 */
  371. if (len < 8)
  372. return NULL;
  373. ptr = tor_inet_ntop(AF_INET, &addr->addr.in_addr, dest, len);
  374. break;
  375. case AF_INET6:
  376. /* Shortest addr [ :: ] + \0 */
  377. if (len < (3 + (decorate ? 2 : 0)))
  378. return NULL;
  379. if (decorate)
  380. ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest+1, len-2);
  381. else
  382. ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest, len);
  383. if (ptr && decorate) {
  384. *dest = '[';
  385. memcpy(dest+strlen(dest), "]", 2);
  386. tor_assert(ptr == dest+1);
  387. ptr = dest;
  388. }
  389. break;
  390. default:
  391. return NULL;
  392. }
  393. return ptr;
  394. }
  395. /** Parse an .in-addr.arpa or .ip6.arpa address from <b>address</b>. Return 0
  396. * if this is not an .in-addr.arpa address or an .ip6.arpa address. Return -1
  397. * if this is an ill-formed .in-addr.arpa address or an .ip6.arpa address.
  398. * Also return -1 if <b>family</b> is not AF_UNSPEC, and the parsed address
  399. * family does not match <b>family</b>. On success, return 1, and store the
  400. * result, if any, into <b>result</b>, if provided.
  401. *
  402. * If <b>accept_regular</b> is set and the address is in neither recognized
  403. * reverse lookup hostname format, try parsing the address as a regular
  404. * IPv4 or IPv6 address too.
  405. */
  406. int
  407. tor_addr_parse_PTR_name(tor_addr_t *result, const char *address,
  408. int family, int accept_regular)
  409. {
  410. if (!strcasecmpend(address, ".in-addr.arpa")) {
  411. /* We have an in-addr.arpa address. */
  412. char buf[INET_NTOA_BUF_LEN];
  413. size_t len;
  414. struct in_addr inaddr;
  415. if (family == AF_INET6)
  416. return -1;
  417. len = strlen(address) - strlen(".in-addr.arpa");
  418. if (len >= INET_NTOA_BUF_LEN)
  419. return -1; /* Too long. */
  420. memcpy(buf, address, len);
  421. buf[len] = '\0';
  422. if (tor_inet_aton(buf, &inaddr) == 0)
  423. return -1; /* malformed. */
  424. /* reverse the bytes */
  425. inaddr.s_addr = (uint32_t)
  426. (((inaddr.s_addr & 0x000000ff) << 24)
  427. |((inaddr.s_addr & 0x0000ff00) << 8)
  428. |((inaddr.s_addr & 0x00ff0000) >> 8)
  429. |((inaddr.s_addr & 0xff000000) >> 24));
  430. if (result) {
  431. tor_addr_from_in(result, &inaddr);
  432. }
  433. return 1;
  434. }
  435. if (!strcasecmpend(address, ".ip6.arpa")) {
  436. const char *cp;
  437. int i;
  438. int n0, n1;
  439. struct in6_addr in6;
  440. if (family == AF_INET)
  441. return -1;
  442. cp = address;
  443. for (i = 0; i < 16; ++i) {
  444. n0 = hex_decode_digit(*cp++); /* The low-order nybble appears first. */
  445. if (*cp++ != '.') return -1; /* Then a dot. */
  446. n1 = hex_decode_digit(*cp++); /* The high-order nybble appears first. */
  447. if (*cp++ != '.') return -1; /* Then another dot. */
  448. if (n0<0 || n1 < 0) /* Both nybbles must be hex. */
  449. return -1;
  450. /* We don't check the length of the string in here. But that's okay,
  451. * since we already know that the string ends with ".ip6.arpa", and
  452. * there is no way to frameshift .ip6.arpa so it fits into the pattern
  453. * of hexdigit, period, hexdigit, period that we enforce above.
  454. */
  455. /* Assign from low-byte to high-byte. */
  456. in6.s6_addr[15-i] = n0 | (n1 << 4);
  457. }
  458. if (strcasecmp(cp, "ip6.arpa"))
  459. return -1;
  460. if (result) {
  461. tor_addr_from_in6(result, &in6);
  462. }
  463. return 1;
  464. }
  465. if (accept_regular) {
  466. tor_addr_t tmp;
  467. int r = tor_addr_parse(&tmp, address);
  468. if (r < 0)
  469. return 0;
  470. if (r != family && family != AF_UNSPEC)
  471. return -1;
  472. if (result)
  473. memcpy(result, &tmp, sizeof(tor_addr_t));
  474. return 1;
  475. }
  476. return 0;
  477. }
  478. /** Convert <b>addr</b> to an in-addr.arpa name or a .ip6.arpa name,
  479. * and store the result in the <b>outlen</b>-byte buffer at
  480. * <b>out</b>. Return the number of chars written to <b>out</b>, not
  481. * including the trailing \0, on success. Returns -1 on failure. */
  482. int
  483. tor_addr_to_PTR_name(char *out, size_t outlen,
  484. const tor_addr_t *addr)
  485. {
  486. tor_assert(out);
  487. tor_assert(addr);
  488. if (addr->family == AF_INET) {
  489. uint32_t a = tor_addr_to_ipv4h(addr);
  490. return tor_snprintf(out, outlen, "%d.%d.%d.%d.in-addr.arpa",
  491. (int)(uint8_t)((a )&0xff),
  492. (int)(uint8_t)((a>>8 )&0xff),
  493. (int)(uint8_t)((a>>16)&0xff),
  494. (int)(uint8_t)((a>>24)&0xff));
  495. } else if (addr->family == AF_INET6) {
  496. int i;
  497. char *cp = out;
  498. const uint8_t *bytes = tor_addr_to_in6_addr8(addr);
  499. if (outlen < REVERSE_LOOKUP_NAME_BUF_LEN)
  500. return -1;
  501. for (i = 15; i >= 0; --i) {
  502. uint8_t byte = bytes[i];
  503. *cp++ = "0123456789abcdef"[byte & 0x0f];
  504. *cp++ = '.';
  505. *cp++ = "0123456789abcdef"[byte >> 4];
  506. *cp++ = '.';
  507. }
  508. memcpy(cp, "ip6.arpa", 9); /* 8 characters plus NUL */
  509. return 32 * 2 + 8;
  510. }
  511. return -1;
  512. }
  513. /** Parse a string <b>s</b> containing an IPv4/IPv6 address, and possibly
  514. * a mask and port or port range. Store the parsed address in
  515. * <b>addr_out</b>, a mask (if any) in <b>mask_out</b>, and port(s) (if any)
  516. * in <b>port_min_out</b> and <b>port_max_out</b>.
  517. *
  518. * The syntax is:
  519. * Address OptMask OptPortRange
  520. * Address ::= IPv4Address / "[" IPv6Address "]" / "*"
  521. * OptMask ::= "/" Integer /
  522. * OptPortRange ::= ":*" / ":" Integer / ":" Integer "-" Integer /
  523. *
  524. * - If mask, minport, or maxport are NULL, we do not want these
  525. * options to be set; treat them as an error if present.
  526. * - If the string has no mask, the mask is set to /32 (IPv4) or /128 (IPv6).
  527. * - If the string has one port, it is placed in both min and max port
  528. * variables.
  529. * - If the string has no port(s), port_(min|max)_out are set to 1 and 65535.
  530. *
  531. * Return an address family on success, or -1 if an invalid address string is
  532. * provided.
  533. *
  534. * If 'flags & TAPMP_EXTENDED_STAR' is false, then the wildcard address '*'
  535. * yield an IPv4 wildcard.
  536. *
  537. * If 'flags & TAPMP_EXTENDED_STAR' is true, then the wildcard address '*'
  538. * yields an AF_UNSPEC wildcard address, and the following change is made
  539. * in the grammar above:
  540. * Address ::= IPv4Address / "[" IPv6Address "]" / "*" / "*4" / "*6"
  541. * with the new "*4" and "*6" productions creating a wildcard to match
  542. * IPv4 or IPv6 addresses.
  543. *
  544. */
  545. int
  546. tor_addr_parse_mask_ports(const char *s,
  547. unsigned flags,
  548. tor_addr_t *addr_out,
  549. maskbits_t *maskbits_out,
  550. uint16_t *port_min_out, uint16_t *port_max_out)
  551. {
  552. char *base = NULL, *address, *mask = NULL, *port = NULL, *rbracket = NULL;
  553. char *endptr;
  554. int any_flag=0, v4map=0;
  555. sa_family_t family;
  556. struct in6_addr in6_tmp;
  557. struct in_addr in_tmp;
  558. tor_assert(s);
  559. tor_assert(addr_out);
  560. /** Longest possible length for an address, mask, and port-range combination.
  561. * Includes IP, [], /mask, :, ports */
  562. #define MAX_ADDRESS_LENGTH (TOR_ADDR_BUF_LEN+2+(1+INET_NTOA_BUF_LEN)+12+1)
  563. if (strlen(s) > MAX_ADDRESS_LENGTH) {
  564. log_warn(LD_GENERAL, "Impossibly long IP %s; rejecting", escaped(s));
  565. goto err;
  566. }
  567. base = tor_strdup(s);
  568. /* Break 'base' into separate strings. */
  569. address = base;
  570. if (*address == '[') { /* Probably IPv6 */
  571. address++;
  572. rbracket = strchr(address, ']');
  573. if (!rbracket) {
  574. log_warn(LD_GENERAL,
  575. "No closing IPv6 bracket in address pattern; rejecting.");
  576. goto err;
  577. }
  578. }
  579. mask = strchr((rbracket?rbracket:address),'/');
  580. port = strchr((mask?mask:(rbracket?rbracket:address)), ':');
  581. if (port)
  582. *port++ = '\0';
  583. if (mask)
  584. *mask++ = '\0';
  585. if (rbracket)
  586. *rbracket = '\0';
  587. if (port && mask)
  588. tor_assert(port > mask);
  589. if (mask && rbracket)
  590. tor_assert(mask > rbracket);
  591. /* Now "address" is the a.b.c.d|'*'|abcd::1 part...
  592. * "mask" is the Mask|Maskbits part...
  593. * and "port" is the *|port|min-max part.
  594. */
  595. /* Process the address portion */
  596. memset(addr_out, 0, sizeof(tor_addr_t));
  597. if (!strcmp(address, "*")) {
  598. if (flags & TAPMP_EXTENDED_STAR) {
  599. family = AF_UNSPEC;
  600. tor_addr_make_unspec(addr_out);
  601. } else {
  602. family = AF_INET;
  603. tor_addr_from_ipv4h(addr_out, 0);
  604. }
  605. any_flag = 1;
  606. } else if (!strcmp(address, "*4") && (flags & TAPMP_EXTENDED_STAR)) {
  607. family = AF_INET;
  608. tor_addr_from_ipv4h(addr_out, 0);
  609. any_flag = 1;
  610. } else if (!strcmp(address, "*6") && (flags & TAPMP_EXTENDED_STAR)) {
  611. static char nil_bytes[16] = { 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 };
  612. family = AF_INET6;
  613. tor_addr_from_ipv6_bytes(addr_out, nil_bytes);
  614. any_flag = 1;
  615. } else if (tor_inet_pton(AF_INET6, address, &in6_tmp) > 0) {
  616. family = AF_INET6;
  617. tor_addr_from_in6(addr_out, &in6_tmp);
  618. } else if (tor_inet_pton(AF_INET, address, &in_tmp) > 0) {
  619. family = AF_INET;
  620. tor_addr_from_in(addr_out, &in_tmp);
  621. } else {
  622. log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
  623. escaped(address));
  624. goto err;
  625. }
  626. v4map = tor_addr_is_v4(addr_out);
  627. /* Parse mask */
  628. if (maskbits_out) {
  629. int bits = 0;
  630. struct in_addr v4mask;
  631. if (mask) { /* the caller (tried to) specify a mask */
  632. bits = (int) strtol(mask, &endptr, 10);
  633. if (!*endptr) { /* strtol converted everything, so it was an integer */
  634. if ((bits<0 || bits>128) ||
  635. (family == AF_INET && bits > 32)) {
  636. log_warn(LD_GENERAL,
  637. "Bad number of mask bits (%d) on address range; rejecting.",
  638. bits);
  639. goto err;
  640. }
  641. } else { /* mask might still be an address-style mask */
  642. if (tor_inet_pton(AF_INET, mask, &v4mask) > 0) {
  643. bits = addr_mask_get_bits(ntohl(v4mask.s_addr));
  644. if (bits < 0) {
  645. log_warn(LD_GENERAL,
  646. "IPv4-style mask %s is not a prefix address; rejecting.",
  647. escaped(mask));
  648. goto err;
  649. }
  650. } else { /* Not IPv4; we don't do address-style IPv6 masks. */
  651. log_warn(LD_GENERAL,
  652. "Malformed mask on address range %s; rejecting.",
  653. escaped(s));
  654. goto err;
  655. }
  656. }
  657. if (family == AF_INET6 && v4map) {
  658. if (bits > 32 && bits < 96) { /* Crazy */
  659. log_warn(LD_GENERAL,
  660. "Bad mask bits %d for V4-mapped V6 address; rejecting.",
  661. bits);
  662. goto err;
  663. }
  664. /* XXXX_IP6 is this really what we want? */
  665. bits = 96 + bits%32; /* map v4-mapped masks onto 96-128 bits */
  666. }
  667. } else { /* pick an appropriate mask, as none was given */
  668. if (any_flag)
  669. bits = 0; /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */
  670. else if (tor_addr_family(addr_out) == AF_INET)
  671. bits = 32;
  672. else if (tor_addr_family(addr_out) == AF_INET6)
  673. bits = 128;
  674. }
  675. *maskbits_out = (maskbits_t) bits;
  676. } else {
  677. if (mask) {
  678. log_warn(LD_GENERAL,
  679. "Unexpected mask in address %s; rejecting", escaped(s));
  680. goto err;
  681. }
  682. }
  683. /* Parse port(s) */
  684. if (port_min_out) {
  685. uint16_t port2;
  686. if (!port_max_out) /* caller specified one port; fake the second one */
  687. port_max_out = &port2;
  688. if (parse_port_range(port, port_min_out, port_max_out) < 0) {
  689. goto err;
  690. } else if ((*port_min_out != *port_max_out) && port_max_out == &port2) {
  691. log_warn(LD_GENERAL,
  692. "Wanted one port from address range, but there are two.");
  693. port_max_out = NULL; /* caller specified one port, so set this back */
  694. goto err;
  695. }
  696. } else {
  697. if (port) {
  698. log_warn(LD_GENERAL,
  699. "Unexpected ports in address %s; rejecting", escaped(s));
  700. goto err;
  701. }
  702. }
  703. tor_free(base);
  704. return tor_addr_family(addr_out);
  705. err:
  706. tor_free(base);
  707. return -1;
  708. }
  709. /** Determine whether an address is IPv4, either native or IPv4-mapped IPv6.
  710. * Note that this is about representation only, as any decent stack will
  711. * reject IPv4-mapped addresses received on the wire (and won't use them
  712. * on the wire either).
  713. */
  714. int
  715. tor_addr_is_v4(const tor_addr_t *addr)
  716. {
  717. tor_assert(addr);
  718. if (tor_addr_family(addr) == AF_INET)
  719. return 1;
  720. if (tor_addr_family(addr) == AF_INET6) {
  721. /* First two don't need to be ordered */
  722. uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  723. if (a32[0] == 0 && a32[1] == 0 && ntohl(a32[2]) == 0x0000ffffu)
  724. return 1;
  725. }
  726. return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */
  727. }
  728. /** Determine whether an address <b>addr</b> is null, either all zeroes or
  729. * belonging to family AF_UNSPEC.
  730. */
  731. int
  732. tor_addr_is_null(const tor_addr_t *addr)
  733. {
  734. tor_assert(addr);
  735. switch (tor_addr_family(addr)) {
  736. case AF_INET6: {
  737. uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  738. return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 0);
  739. }
  740. case AF_INET:
  741. return (tor_addr_to_ipv4n(addr) == 0);
  742. case AF_UNSPEC:
  743. return 1;
  744. default:
  745. log_warn(LD_BUG, "Called with unknown address family %d",
  746. (int)tor_addr_family(addr));
  747. return 0;
  748. }
  749. //return 1;
  750. }
  751. /** Return true iff <b>addr</b> is a loopback address */
  752. int
  753. tor_addr_is_loopback(const tor_addr_t *addr)
  754. {
  755. tor_assert(addr);
  756. switch (tor_addr_family(addr)) {
  757. case AF_INET6: {
  758. /* ::1 */
  759. uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  760. return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) &&
  761. (ntohl(a32[3]) == 1);
  762. }
  763. case AF_INET:
  764. /* 127.0.0.1 */
  765. return (tor_addr_to_ipv4h(addr) & 0xff000000) == 0x7f000000;
  766. case AF_UNSPEC:
  767. return 0;
  768. default:
  769. tor_fragile_assert();
  770. return 0;
  771. }
  772. }
  773. /** Set <b>dest</b> to equal the IPv4 address in <b>v4addr</b> (given in
  774. * network order). */
  775. void
  776. tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
  777. {
  778. tor_assert(dest);
  779. memset(dest, 0, sizeof(tor_addr_t));
  780. dest->family = AF_INET;
  781. dest->addr.in_addr.s_addr = v4addr;
  782. }
  783. /** Set <b>dest</b> to equal the IPv6 address in the 16 bytes at
  784. * <b>ipv6_bytes</b>. */
  785. void
  786. tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
  787. {
  788. tor_assert(dest);
  789. tor_assert(ipv6_bytes);
  790. memset(dest, 0, sizeof(tor_addr_t));
  791. dest->family = AF_INET6;
  792. memcpy(dest->addr.in6_addr.s6_addr, ipv6_bytes, 16);
  793. }
  794. /** Set <b>dest</b> equal to the IPv6 address in the in6_addr <b>in6</b>. */
  795. void
  796. tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
  797. {
  798. tor_addr_from_ipv6_bytes(dest, (const char*)in6->s6_addr);
  799. }
  800. /** Copy a tor_addr_t from <b>src</b> to <b>dest</b>.
  801. */
  802. void
  803. tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
  804. {
  805. if (src == dest)
  806. return;
  807. tor_assert(src);
  808. tor_assert(dest);
  809. memcpy(dest, src, sizeof(tor_addr_t));
  810. }
  811. /** Copy a tor_addr_t from <b>src</b> to <b>dest</b>, taking extra case to
  812. * copy only the well-defined portions. Used for computing hashes of
  813. * addresses.
  814. */
  815. void
  816. tor_addr_copy_tight(tor_addr_t *dest, const tor_addr_t *src)
  817. {
  818. tor_assert(src != dest);
  819. tor_assert(src);
  820. tor_assert(dest);
  821. memset(dest, 0, sizeof(tor_addr_t));
  822. dest->family = src->family;
  823. switch (tor_addr_family(src))
  824. {
  825. case AF_INET:
  826. dest->addr.in_addr.s_addr = src->addr.in_addr.s_addr;
  827. break;
  828. case AF_INET6:
  829. memcpy(dest->addr.in6_addr.s6_addr, src->addr.in6_addr.s6_addr, 16);
  830. case AF_UNSPEC:
  831. break;
  832. default:
  833. tor_fragile_assert();
  834. }
  835. }
  836. /** Given two addresses <b>addr1</b> and <b>addr2</b>, return 0 if the two
  837. * addresses are equivalent under the mask mbits, less than 0 if addr1
  838. * precedes addr2, and greater than 0 otherwise.
  839. *
  840. * Different address families (IPv4 vs IPv6) are always considered unequal if
  841. * <b>how</b> is CMP_EXACT; otherwise, IPv6-mapped IPv4 addresses are
  842. * considered equivalent to their IPv4 equivalents.
  843. */
  844. int
  845. tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2,
  846. tor_addr_comparison_t how)
  847. {
  848. return tor_addr_compare_masked(addr1, addr2, 128, how);
  849. }
  850. /** As tor_addr_compare(), but only looks at the first <b>mask</b> bits of
  851. * the address.
  852. *
  853. * Reduce over-specific masks (>128 for ipv6, >32 for ipv4) to 128 or 32.
  854. *
  855. * The mask is interpreted relative to <b>addr1</b>, so that if a is
  856. * \::ffff:1.2.3.4, and b is 3.4.5.6,
  857. * tor_addr_compare_masked(a,b,100,CMP_SEMANTIC) is the same as
  858. * -tor_addr_compare_masked(b,a,4,CMP_SEMANTIC).
  859. *
  860. * We guarantee that the ordering from tor_addr_compare_masked is a total
  861. * order on addresses, but not that it is any particular order, or that it
  862. * will be the same from one version to the next.
  863. */
  864. int
  865. tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2,
  866. maskbits_t mbits, tor_addr_comparison_t how)
  867. {
  868. /** Helper: Evaluates to -1 if a is less than b, 0 if a equals b, or 1 if a
  869. * is greater than b. May evaluate a and b more than once. */
  870. #define TRISTATE(a,b) (((a)<(b))?-1: (((a)==(b))?0:1))
  871. sa_family_t family1, family2, v_family1, v_family2;
  872. tor_assert(addr1 && addr2);
  873. v_family1 = family1 = tor_addr_family(addr1);
  874. v_family2 = family2 = tor_addr_family(addr2);
  875. if (family1==family2) {
  876. /* When the families are the same, there's only one way to do the
  877. * comparison: exactly. */
  878. int r;
  879. switch (family1) {
  880. case AF_UNSPEC:
  881. return 0; /* All unspecified addresses are equal */
  882. case AF_INET: {
  883. uint32_t a1 = tor_addr_to_ipv4h(addr1);
  884. uint32_t a2 = tor_addr_to_ipv4h(addr2);
  885. if (mbits <= 0)
  886. return 0;
  887. if (mbits > 32)
  888. mbits = 32;
  889. a1 >>= (32-mbits);
  890. a2 >>= (32-mbits);
  891. r = TRISTATE(a1, a2);
  892. return r;
  893. }
  894. case AF_INET6: {
  895. const uint8_t *a1 = tor_addr_to_in6_addr8(addr1);
  896. const uint8_t *a2 = tor_addr_to_in6_addr8(addr2);
  897. const int bytes = mbits >> 3;
  898. const int leftover_bits = mbits & 7;
  899. if (bytes && (r = tor_memcmp(a1, a2, bytes))) {
  900. return r;
  901. } else if (leftover_bits) {
  902. uint8_t b1 = a1[bytes] >> (8-leftover_bits);
  903. uint8_t b2 = a2[bytes] >> (8-leftover_bits);
  904. return TRISTATE(b1, b2);
  905. } else {
  906. return 0;
  907. }
  908. }
  909. default:
  910. tor_fragile_assert();
  911. return 0;
  912. }
  913. } else if (how == CMP_EXACT) {
  914. /* Unequal families and an exact comparison? Stop now! */
  915. return TRISTATE(family1, family2);
  916. }
  917. if (mbits == 0)
  918. return 0;
  919. if (family1 == AF_INET6 && tor_addr_is_v4(addr1))
  920. v_family1 = AF_INET;
  921. if (family2 == AF_INET6 && tor_addr_is_v4(addr2))
  922. v_family2 = AF_INET;
  923. if (v_family1 == v_family2) {
  924. /* One or both addresses are a mapped ipv4 address. */
  925. uint32_t a1, a2;
  926. if (family1 == AF_INET6) {
  927. a1 = tor_addr_to_mapped_ipv4h(addr1);
  928. if (mbits <= 96)
  929. return 0;
  930. mbits -= 96; /* We just decided that the first 96 bits of a1 "match". */
  931. } else {
  932. a1 = tor_addr_to_ipv4h(addr1);
  933. }
  934. if (family2 == AF_INET6) {
  935. a2 = tor_addr_to_mapped_ipv4h(addr2);
  936. } else {
  937. a2 = tor_addr_to_ipv4h(addr2);
  938. }
  939. if (mbits <= 0) return 0;
  940. if (mbits > 32) mbits = 32;
  941. a1 >>= (32-mbits);
  942. a2 >>= (32-mbits);
  943. return TRISTATE(a1, a2);
  944. } else {
  945. /* Unequal families, and semantic comparison, and no semantic family
  946. * matches. */
  947. return TRISTATE(family1, family2);
  948. }
  949. }
  950. /** Return a hash code based on the address addr. DOCDOC extra */
  951. uint64_t
  952. tor_addr_hash(const tor_addr_t *addr)
  953. {
  954. switch (tor_addr_family(addr)) {
  955. case AF_INET:
  956. return siphash24g(&addr->addr.in_addr.s_addr, 4);
  957. case AF_UNSPEC:
  958. return 0x4e4d5342;
  959. case AF_INET6:
  960. return siphash24g(&addr->addr.in6_addr.s6_addr, 16);
  961. default:
  962. tor_fragile_assert();
  963. return 0;
  964. }
  965. }
  966. /** Return a newly allocated string with a representation of <b>addr</b>. */
  967. char *
  968. tor_dup_addr(const tor_addr_t *addr)
  969. {
  970. char buf[TOR_ADDR_BUF_LEN];
  971. if (tor_addr_to_str(buf, addr, sizeof(buf), 0)) {
  972. return tor_strdup(buf);
  973. } else {
  974. return tor_strdup("<unknown address type>");
  975. }
  976. }
  977. /** Return a string representing the address <b>addr</b>. This string
  978. * is statically allocated, and must not be freed. Each call to
  979. * <b>fmt_addr_impl</b> invalidates the last result of the function.
  980. * This function is not thread-safe. If <b>decorate</b> is set, add
  981. * brackets to IPv6 addresses.
  982. *
  983. * It's better to use the wrapper macros of this function:
  984. * <b>fmt_addr()</b> and <b>fmt_and_decorate_addr()</b>.
  985. */
  986. const char *
  987. fmt_addr_impl(const tor_addr_t *addr, int decorate)
  988. {
  989. static char buf[TOR_ADDR_BUF_LEN];
  990. if (!addr) return "<null>";
  991. if (tor_addr_to_str(buf, addr, sizeof(buf), decorate))
  992. return buf;
  993. else
  994. return "???";
  995. }
  996. /** Return a string representing the pair <b>addr</b> and <b>port</b>.
  997. * This calls fmt_and_decorate_addr internally, so IPv6 addresses will
  998. * have brackets, and the caveats of fmt_addr_impl apply.
  999. */
  1000. const char *
  1001. fmt_addrport(const tor_addr_t *addr, uint16_t port)
  1002. {
  1003. /* Add space for a colon and up to 5 digits. */
  1004. static char buf[TOR_ADDR_BUF_LEN + 6];
  1005. tor_snprintf(buf, sizeof(buf), "%s:%u", fmt_and_decorate_addr(addr), port);
  1006. return buf;
  1007. }
  1008. /** Like fmt_addr(), but takes <b>addr</b> as a host-order IPv4
  1009. * addresses. Also not thread-safe, also clobbers its return buffer on
  1010. * repeated calls. */
  1011. const char *
  1012. fmt_addr32(uint32_t addr)
  1013. {
  1014. static char buf[INET_NTOA_BUF_LEN];
  1015. struct in_addr in;
  1016. in.s_addr = htonl(addr);
  1017. tor_inet_ntoa(&in, buf, sizeof(buf));
  1018. return buf;
  1019. }
  1020. /** Convert the string in <b>src</b> to a tor_addr_t <b>addr</b>. The string
  1021. * may be an IPv4 address, an IPv6 address, or an IPv6 address surrounded by
  1022. * square brackets.
  1023. *
  1024. * Return an address family on success, or -1 if an invalid address string is
  1025. * provided. */
  1026. int
  1027. tor_addr_parse(tor_addr_t *addr, const char *src)
  1028. {
  1029. char *tmp = NULL; /* Holds substring if we got a dotted quad. */
  1030. int result;
  1031. struct in_addr in_tmp;
  1032. struct in6_addr in6_tmp;
  1033. tor_assert(addr && src);
  1034. if (src[0] == '[' && src[1])
  1035. src = tmp = tor_strndup(src+1, strlen(src)-2);
  1036. if (tor_inet_pton(AF_INET6, src, &in6_tmp) > 0) {
  1037. result = AF_INET6;
  1038. tor_addr_from_in6(addr, &in6_tmp);
  1039. } else if (tor_inet_pton(AF_INET, src, &in_tmp) > 0) {
  1040. result = AF_INET;
  1041. tor_addr_from_in(addr, &in_tmp);
  1042. } else {
  1043. result = -1;
  1044. }
  1045. tor_free(tmp);
  1046. return result;
  1047. }
  1048. /** Parse an address or address-port combination from <b>s</b>, resolve the
  1049. * address as needed, and put the result in <b>addr_out</b> and (optionally)
  1050. * <b>port_out</b>. Return 0 on success, negative on failure. */
  1051. int
  1052. tor_addr_port_lookup(const char *s, tor_addr_t *addr_out, uint16_t *port_out)
  1053. {
  1054. const char *port;
  1055. tor_addr_t addr;
  1056. uint16_t portval;
  1057. char *tmp = NULL;
  1058. tor_assert(s);
  1059. tor_assert(addr_out);
  1060. s = eat_whitespace(s);
  1061. if (*s == '[') {
  1062. port = strstr(s, "]");
  1063. if (!port)
  1064. goto err;
  1065. tmp = tor_strndup(s+1, port-(s+1));
  1066. port = port+1;
  1067. if (*port == ':')
  1068. port++;
  1069. else
  1070. port = NULL;
  1071. } else {
  1072. port = strchr(s, ':');
  1073. if (port)
  1074. tmp = tor_strndup(s, port-s);
  1075. else
  1076. tmp = tor_strdup(s);
  1077. if (port)
  1078. ++port;
  1079. }
  1080. if (tor_addr_lookup(tmp, AF_UNSPEC, &addr) != 0)
  1081. goto err;
  1082. tor_free(tmp);
  1083. if (port) {
  1084. portval = (int) tor_parse_long(port, 10, 1, 65535, NULL, NULL);
  1085. if (!portval)
  1086. goto err;
  1087. } else {
  1088. portval = 0;
  1089. }
  1090. if (port_out)
  1091. *port_out = portval;
  1092. tor_addr_copy(addr_out, &addr);
  1093. return 0;
  1094. err:
  1095. tor_free(tmp);
  1096. return -1;
  1097. }
  1098. #ifdef _WIN32
  1099. typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)(
  1100. ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
  1101. #endif
  1102. /** Try to ask our network interfaces what addresses they are bound to.
  1103. * Return a new smartlist of tor_addr_t on success, and NULL on failure.
  1104. * (An empty smartlist indicates that we successfully learned that we have no
  1105. * addresses.) Log failure messages at <b>severity</b>. */
  1106. static smartlist_t *
  1107. get_interface_addresses_raw(int severity)
  1108. {
  1109. #if defined(HAVE_GETIFADDRS)
  1110. /* Most free Unixy systems provide getifaddrs, which gives us a linked list
  1111. * of struct ifaddrs. */
  1112. struct ifaddrs *ifa = NULL;
  1113. const struct ifaddrs *i;
  1114. smartlist_t *result;
  1115. if (getifaddrs(&ifa) < 0) {
  1116. log_fn(severity, LD_NET, "Unable to call getifaddrs(): %s",
  1117. strerror(errno));
  1118. return NULL;
  1119. }
  1120. result = smartlist_new();
  1121. for (i = ifa; i; i = i->ifa_next) {
  1122. tor_addr_t tmp;
  1123. if ((i->ifa_flags & (IFF_UP | IFF_RUNNING)) != (IFF_UP | IFF_RUNNING))
  1124. continue;
  1125. if (!i->ifa_addr)
  1126. continue;
  1127. if (i->ifa_addr->sa_family != AF_INET &&
  1128. i->ifa_addr->sa_family != AF_INET6)
  1129. continue;
  1130. if (tor_addr_from_sockaddr(&tmp, i->ifa_addr, NULL) < 0)
  1131. continue;
  1132. smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
  1133. }
  1134. freeifaddrs(ifa);
  1135. return result;
  1136. #elif defined(_WIN32)
  1137. /* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
  1138. "GetAdaptersInfo", but that's deprecated; let's just try
  1139. GetAdaptersAddresses and fall back to connect+getsockname.
  1140. */
  1141. HANDLE lib = load_windows_system_library(TEXT("iphlpapi.dll"));
  1142. smartlist_t *result = NULL;
  1143. GetAdaptersAddresses_fn_t fn;
  1144. ULONG size, res;
  1145. IP_ADAPTER_ADDRESSES *addresses = NULL, *address;
  1146. (void) severity;
  1147. #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
  1148. GAA_FLAG_SKIP_MULTICAST | \
  1149. GAA_FLAG_SKIP_DNS_SERVER)
  1150. if (!lib) {
  1151. log_fn(severity, LD_NET, "Unable to load iphlpapi.dll");
  1152. goto done;
  1153. }
  1154. if (!(fn = (GetAdaptersAddresses_fn_t)
  1155. GetProcAddress(lib, "GetAdaptersAddresses"))) {
  1156. log_fn(severity, LD_NET, "Unable to obtain pointer to "
  1157. "GetAdaptersAddresses");
  1158. goto done;
  1159. }
  1160. /* Guess how much space we need. */
  1161. size = 15*1024;
  1162. addresses = tor_malloc(size);
  1163. res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
  1164. if (res == ERROR_BUFFER_OVERFLOW) {
  1165. /* we didn't guess that we needed enough space; try again */
  1166. tor_free(addresses);
  1167. addresses = tor_malloc(size);
  1168. res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
  1169. }
  1170. if (res != NO_ERROR) {
  1171. log_fn(severity, LD_NET, "GetAdaptersAddresses failed (result: %lu)", res);
  1172. goto done;
  1173. }
  1174. result = smartlist_new();
  1175. for (address = addresses; address; address = address->Next) {
  1176. IP_ADAPTER_UNICAST_ADDRESS *a;
  1177. for (a = address->FirstUnicastAddress; a; a = a->Next) {
  1178. /* Yes, it's a linked list inside a linked list */
  1179. struct sockaddr *sa = a->Address.lpSockaddr;
  1180. tor_addr_t tmp;
  1181. if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
  1182. continue;
  1183. if (tor_addr_from_sockaddr(&tmp, sa, NULL) < 0)
  1184. continue;
  1185. smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
  1186. }
  1187. }
  1188. done:
  1189. if (lib)
  1190. FreeLibrary(lib);
  1191. tor_free(addresses);
  1192. return result;
  1193. #elif defined(SIOCGIFCONF) && defined(HAVE_IOCTL)
  1194. /* Some older unixy systems make us use ioctl(SIOCGIFCONF) */
  1195. struct ifconf ifc;
  1196. int fd, i, sz, n;
  1197. smartlist_t *result = NULL;
  1198. /* This interface, AFAICT, only supports AF_INET addresses */
  1199. fd = socket(AF_INET, SOCK_DGRAM, 0);
  1200. if (fd < 0) {
  1201. tor_log(severity, LD_NET, "socket failed: %s", strerror(errno));
  1202. goto done;
  1203. }
  1204. /* Guess how much space we need. */
  1205. ifc.ifc_len = sz = 15*1024;
  1206. ifc.ifc_ifcu.ifcu_req = tor_malloc(sz);
  1207. if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) {
  1208. tor_log(severity, LD_NET, "ioctl failed: %s", strerror(errno));
  1209. close(fd);
  1210. goto done;
  1211. }
  1212. close(fd);
  1213. result = smartlist_new();
  1214. if (ifc.ifc_len < sz)
  1215. sz = ifc.ifc_len;
  1216. n = sz / sizeof(struct ifreq);
  1217. for (i = 0; i < n ; ++i) {
  1218. struct ifreq *r = &ifc.ifc_ifcu.ifcu_req[i];
  1219. struct sockaddr *sa = &r->ifr_addr;
  1220. tor_addr_t tmp;
  1221. if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
  1222. continue; /* should be impossible */
  1223. if (tor_addr_from_sockaddr(&tmp, sa, NULL) < 0)
  1224. continue;
  1225. smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
  1226. }
  1227. done:
  1228. tor_free(ifc.ifc_ifcu.ifcu_req);
  1229. return result;
  1230. #else
  1231. (void) severity;
  1232. return NULL;
  1233. #endif
  1234. }
  1235. /** Return true iff <b>a</b> is a multicast address. */
  1236. static int
  1237. tor_addr_is_multicast(const tor_addr_t *a)
  1238. {
  1239. sa_family_t family = tor_addr_family(a);
  1240. if (family == AF_INET) {
  1241. uint32_t ipv4h = tor_addr_to_ipv4h(a);
  1242. if ((ipv4h >> 24) == 0xe0)
  1243. return 1; /* Multicast */
  1244. } else if (family == AF_INET6) {
  1245. const uint8_t *a32 = tor_addr_to_in6_addr8(a);
  1246. if (a32[0] == 0xff)
  1247. return 1;
  1248. }
  1249. return 0;
  1250. }
  1251. /** Set *<b>addr</b> to the IP address (if any) of whatever interface
  1252. * connects to the Internet. This address should only be used in checking
  1253. * whether our address has changed. Return 0 on success, -1 on failure.
  1254. */
  1255. int
  1256. get_interface_address6(int severity, sa_family_t family, tor_addr_t *addr)
  1257. {
  1258. /* XXX really, this function should yield a smartlist of addresses. */
  1259. smartlist_t *addrs;
  1260. int sock=-1, r=-1;
  1261. struct sockaddr_storage my_addr, target_addr;
  1262. socklen_t addr_len;
  1263. tor_assert(addr);
  1264. /* Try to do this the smart way if possible. */
  1265. if ((addrs = get_interface_addresses_raw(severity))) {
  1266. int rv = -1;
  1267. SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a) {
  1268. if (family != AF_UNSPEC && family != tor_addr_family(a))
  1269. continue;
  1270. if (tor_addr_is_loopback(a) ||
  1271. tor_addr_is_multicast(a))
  1272. continue;
  1273. tor_addr_copy(addr, a);
  1274. rv = 0;
  1275. /* If we found a non-internal address, declare success. Otherwise,
  1276. * keep looking. */
  1277. if (!tor_addr_is_internal(a, 0))
  1278. break;
  1279. } SMARTLIST_FOREACH_END(a);
  1280. SMARTLIST_FOREACH(addrs, tor_addr_t *, a, tor_free(a));
  1281. smartlist_free(addrs);
  1282. return rv;
  1283. }
  1284. /* Okay, the smart way is out. */
  1285. memset(addr, 0, sizeof(tor_addr_t));
  1286. memset(&target_addr, 0, sizeof(target_addr));
  1287. /* Don't worry: no packets are sent. We just need to use a real address
  1288. * on the actual Internet. */
  1289. if (family == AF_INET6) {
  1290. struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&target_addr;
  1291. /* Use the "discard" service port */
  1292. sin6->sin6_port = htons(9);
  1293. sock = tor_open_socket(PF_INET6,SOCK_DGRAM,IPPROTO_UDP);
  1294. addr_len = (socklen_t)sizeof(struct sockaddr_in6);
  1295. sin6->sin6_family = AF_INET6;
  1296. S6_ADDR16(sin6->sin6_addr)[0] = htons(0x2002); /* 2002:: */
  1297. } else if (family == AF_INET) {
  1298. struct sockaddr_in *sin = (struct sockaddr_in*)&target_addr;
  1299. /* Use the "discard" service port */
  1300. sin->sin_port = htons(9);
  1301. sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
  1302. addr_len = (socklen_t)sizeof(struct sockaddr_in);
  1303. sin->sin_family = AF_INET;
  1304. sin->sin_addr.s_addr = htonl(0x12000001); /* 18.0.0.1 */
  1305. } else {
  1306. return -1;
  1307. }
  1308. if (sock < 0) {
  1309. int e = tor_socket_errno(-1);
  1310. log_fn(severity, LD_NET, "unable to create socket: %s",
  1311. tor_socket_strerror(e));
  1312. goto err;
  1313. }
  1314. if (connect(sock,(struct sockaddr *)&target_addr, addr_len) < 0) {
  1315. int e = tor_socket_errno(sock);
  1316. log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e));
  1317. goto err;
  1318. }
  1319. if (getsockname(sock,(struct sockaddr*)&my_addr, &addr_len)) {
  1320. int e = tor_socket_errno(sock);
  1321. log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s",
  1322. tor_socket_strerror(e));
  1323. goto err;
  1324. }
  1325. tor_addr_from_sockaddr(addr, (struct sockaddr*)&my_addr, NULL);
  1326. r=0;
  1327. err:
  1328. if (sock >= 0)
  1329. tor_close_socket(sock);
  1330. return r;
  1331. }
  1332. /* ======
  1333. * IPv4 helpers
  1334. * XXXX024 IPv6 deprecate some of these.
  1335. */
  1336. /** Given an address of the form "ip:port", try to divide it into its
  1337. * ip and port portions, setting *<b>address_out</b> to a newly
  1338. * allocated string holding the address portion and *<b>port_out</b>
  1339. * to the port.
  1340. *
  1341. * Don't do DNS lookups and don't allow domain names in the "ip" field.
  1342. *
  1343. * If <b>default_port</b> is less than 0, don't accept <b>addrport</b> of the
  1344. * form "ip" or "ip:0". Otherwise, accept those forms, and set
  1345. * *<b>port_out</b> to <b>default_port</b>.
  1346. *
  1347. * Return 0 on success, -1 on failure. */
  1348. int
  1349. tor_addr_port_parse(int severity, const char *addrport,
  1350. tor_addr_t *address_out, uint16_t *port_out,
  1351. int default_port)
  1352. {
  1353. int retval = -1;
  1354. int r;
  1355. char *addr_tmp = NULL;
  1356. tor_assert(addrport);
  1357. tor_assert(address_out);
  1358. tor_assert(port_out);
  1359. r = tor_addr_port_split(severity, addrport, &addr_tmp, port_out);
  1360. if (r < 0)
  1361. goto done;
  1362. if (!*port_out) {
  1363. if (default_port >= 0)
  1364. *port_out = default_port;
  1365. else
  1366. goto done;
  1367. }
  1368. /* make sure that address_out is an IP address */
  1369. if (tor_addr_parse(address_out, addr_tmp) < 0)
  1370. goto done;
  1371. retval = 0;
  1372. done:
  1373. tor_free(addr_tmp);
  1374. return retval;
  1375. }
  1376. /** Given an address of the form "host[:port]", try to divide it into its host
  1377. * ane port portions, setting *<b>address_out</b> to a newly allocated string
  1378. * holding the address portion and *<b>port_out</b> to the port (or 0 if no
  1379. * port is given). Return 0 on success, -1 on failure. */
  1380. int
  1381. tor_addr_port_split(int severity, const char *addrport,
  1382. char **address_out, uint16_t *port_out)
  1383. {
  1384. tor_addr_t a_tmp;
  1385. tor_assert(addrport);
  1386. tor_assert(address_out);
  1387. tor_assert(port_out);
  1388. /* We need to check for IPv6 manually because addr_port_lookup() doesn't
  1389. * do a good job on IPv6 addresses that lack a port. */
  1390. if (tor_addr_parse(&a_tmp, addrport) == AF_INET6) {
  1391. *port_out = 0;
  1392. *address_out = tor_strdup(addrport);
  1393. return 0;
  1394. }
  1395. return addr_port_lookup(severity, addrport, address_out, NULL, port_out);
  1396. }
  1397. /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
  1398. * <b>address</b> is provided, set *<b>address</b> to a copy of the
  1399. * host portion of the string. If <b>addr</b> is provided, try to
  1400. * resolve the host portion of the string and store it into
  1401. * *<b>addr</b> (in host byte order). If <b>port_out</b> is provided,
  1402. * store the port number into *<b>port_out</b>, or 0 if no port is given.
  1403. * If <b>port_out</b> is NULL, then there must be no port number in
  1404. * <b>addrport</b>.
  1405. * Return 0 on success, -1 on failure.
  1406. */
  1407. int
  1408. addr_port_lookup(int severity, const char *addrport, char **address,
  1409. uint32_t *addr, uint16_t *port_out)
  1410. {
  1411. const char *colon;
  1412. char *address_ = NULL;
  1413. int port_;
  1414. int ok = 1;
  1415. tor_assert(addrport);
  1416. colon = strrchr(addrport, ':');
  1417. if (colon) {
  1418. address_ = tor_strndup(addrport, colon-addrport);
  1419. port_ = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
  1420. if (!port_) {
  1421. log_fn(severity, LD_GENERAL, "Port %s out of range", escaped(colon+1));
  1422. ok = 0;
  1423. }
  1424. if (!port_out) {
  1425. char *esc_addrport = esc_for_log(addrport);
  1426. log_fn(severity, LD_GENERAL,
  1427. "Port %s given on %s when not required",
  1428. escaped(colon+1), esc_addrport);
  1429. tor_free(esc_addrport);
  1430. ok = 0;
  1431. }
  1432. } else {
  1433. address_ = tor_strdup(addrport);
  1434. port_ = 0;
  1435. }
  1436. if (addr) {
  1437. /* There's an addr pointer, so we need to resolve the hostname. */
  1438. if (tor_lookup_hostname(address_,addr)) {
  1439. log_fn(severity, LD_NET, "Couldn't look up %s", escaped(address_));
  1440. ok = 0;
  1441. *addr = 0;
  1442. }
  1443. }
  1444. if (address && ok) {
  1445. *address = address_;
  1446. } else {
  1447. if (address)
  1448. *address = NULL;
  1449. tor_free(address_);
  1450. }
  1451. if (port_out)
  1452. *port_out = ok ? ((uint16_t) port_) : 0;
  1453. return ok ? 0 : -1;
  1454. }
  1455. /** If <b>mask</b> is an address mask for a bit-prefix, return the number of
  1456. * bits. Otherwise, return -1. */
  1457. int
  1458. addr_mask_get_bits(uint32_t mask)
  1459. {
  1460. int i;
  1461. if (mask == 0)
  1462. return 0;
  1463. if (mask == 0xFFFFFFFFu)
  1464. return 32;
  1465. for (i=1; i<=32; ++i) {
  1466. if (mask == (uint32_t) ~((1u<<(32-i))-1)) {
  1467. return i;
  1468. }
  1469. }
  1470. return -1;
  1471. }
  1472. /** Parse a string <b>s</b> in the format of (*|port(-maxport)?)?, setting the
  1473. * various *out pointers as appropriate. Return 0 on success, -1 on failure.
  1474. */
  1475. int
  1476. parse_port_range(const char *port, uint16_t *port_min_out,
  1477. uint16_t *port_max_out)
  1478. {
  1479. int port_min, port_max, ok;
  1480. tor_assert(port_min_out);
  1481. tor_assert(port_max_out);
  1482. if (!port || *port == '\0' || strcmp(port, "*") == 0) {
  1483. port_min = 1;
  1484. port_max = 65535;
  1485. } else {
  1486. char *endptr = NULL;
  1487. port_min = (int)tor_parse_long(port, 10, 0, 65535, &ok, &endptr);
  1488. if (!ok) {
  1489. log_warn(LD_GENERAL,
  1490. "Malformed port %s on address range; rejecting.",
  1491. escaped(port));
  1492. return -1;
  1493. } else if (endptr && *endptr == '-') {
  1494. port = endptr+1;
  1495. endptr = NULL;
  1496. port_max = (int)tor_parse_long(port, 10, 1, 65535, &ok, &endptr);
  1497. if (!ok) {
  1498. log_warn(LD_GENERAL,
  1499. "Malformed port %s on address range; rejecting.",
  1500. escaped(port));
  1501. return -1;
  1502. }
  1503. } else {
  1504. port_max = port_min;
  1505. }
  1506. if (port_min > port_max) {
  1507. log_warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
  1508. return -1;
  1509. }
  1510. }
  1511. if (port_min < 1)
  1512. port_min = 1;
  1513. if (port_max > 65535)
  1514. port_max = 65535;
  1515. *port_min_out = (uint16_t) port_min;
  1516. *port_max_out = (uint16_t) port_max;
  1517. return 0;
  1518. }
  1519. /** Given an IPv4 in_addr struct *<b>in</b> (in network order, as usual),
  1520. * write it as a string into the <b>buf_len</b>-byte buffer in
  1521. * <b>buf</b>.
  1522. */
  1523. int
  1524. tor_inet_ntoa(const struct in_addr *in, char *buf, size_t buf_len)
  1525. {
  1526. uint32_t a = ntohl(in->s_addr);
  1527. return tor_snprintf(buf, buf_len, "%d.%d.%d.%d",
  1528. (int)(uint8_t)((a>>24)&0xff),
  1529. (int)(uint8_t)((a>>16)&0xff),
  1530. (int)(uint8_t)((a>>8 )&0xff),
  1531. (int)(uint8_t)((a )&0xff));
  1532. }
  1533. /** Given a host-order <b>addr</b>, call tor_inet_ntop() on it
  1534. * and return a strdup of the resulting address.
  1535. */
  1536. char *
  1537. tor_dup_ip(uint32_t addr)
  1538. {
  1539. char buf[TOR_ADDR_BUF_LEN];
  1540. struct in_addr in;
  1541. in.s_addr = htonl(addr);
  1542. tor_inet_ntop(AF_INET, &in, buf, sizeof(buf));
  1543. return tor_strdup(buf);
  1544. }
  1545. /**
  1546. * Set *<b>addr</b> to the host-order IPv4 address (if any) of whatever
  1547. * interface connects to the Internet. This address should only be used in
  1548. * checking whether our address has changed. Return 0 on success, -1 on
  1549. * failure.
  1550. */
  1551. int
  1552. get_interface_address(int severity, uint32_t *addr)
  1553. {
  1554. tor_addr_t local_addr;
  1555. int r;
  1556. r = get_interface_address6(severity, AF_INET, &local_addr);
  1557. if (r>=0)
  1558. *addr = tor_addr_to_ipv4h(&local_addr);
  1559. return r;
  1560. }
  1561. /** Return true if we can tell that <b>name</b> is a canonical name for the
  1562. * loopback address. */
  1563. int
  1564. tor_addr_hostname_is_local(const char *name)
  1565. {
  1566. return !strcasecmp(name, "localhost") ||
  1567. !strcasecmp(name, "local") ||
  1568. !strcasecmpend(name, ".local");
  1569. }
  1570. /** Return a newly allocated tor_addr_port_t with <b>addr</b> and
  1571. <b>port</b> filled in. */
  1572. tor_addr_port_t *
  1573. tor_addr_port_new(const tor_addr_t *addr, uint16_t port)
  1574. {
  1575. tor_addr_port_t *ap = tor_malloc_zero(sizeof(tor_addr_port_t));
  1576. if (addr)
  1577. tor_addr_copy(&ap->addr, addr);
  1578. ap->port = port;
  1579. return ap;
  1580. }