address.c 60 KB

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