address.c 51 KB

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