address.c 60 KB

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