address.c 54 KB

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