address.c 62 KB

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