address.c 59 KB

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