address.c 52 KB

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