address.c 62 KB

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