address.c 59 KB

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