address.c 49 KB

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