address.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2011, 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. #include "orconfig.h"
  10. #include "compat.h"
  11. #include "util.h"
  12. #include "address.h"
  13. #include "torlog.h"
  14. #include "container.h"
  15. #ifdef _WIN32
  16. #include <process.h>
  17. #include <windows.h>
  18. #include <winsock2.h>
  19. /* For access to structs needed by GetAdaptersAddresses */
  20. #undef _WIN32_WINNT
  21. #define _WIN32_WINNT 0x0501
  22. #include <iphlpapi.h>
  23. #endif
  24. #ifdef HAVE_SYS_TIME_H
  25. #include <sys/time.h>
  26. #endif
  27. #ifdef HAVE_UNISTD_H
  28. #include <unistd.h>
  29. #endif
  30. #ifdef HAVE_ERRNO_H
  31. #include <errno.h>
  32. #endif
  33. #ifdef HAVE_NETINET_IN_H
  34. #include <netinet/in.h>
  35. #endif
  36. #ifdef HAVE_ARPA_INET_H
  37. #include <arpa/inet.h>
  38. #endif
  39. #ifdef HAVE_SYS_SOCKET_H
  40. #include <sys/socket.h>
  41. #endif
  42. #ifdef HAVE_NETDB_H
  43. #include <netdb.h>
  44. #endif
  45. #ifdef HAVE_SYS_PARAM_H
  46. #include <sys/param.h> /* FreeBSD needs this to know what version it is */
  47. #endif
  48. #ifdef HAVE_SYS_UN_H
  49. #include <sys/un.h>
  50. #endif
  51. #ifdef HAVE_IFADDRS_H
  52. #include <ifaddrs.h>
  53. #endif
  54. #ifdef HAVE_SYS_IOCTL_H
  55. #include <sys/ioctl.h>
  56. #endif
  57. #ifdef HAVE_NET_IF_H
  58. #include <net/if.h>
  59. #endif
  60. #include <stdarg.h>
  61. #include <stdio.h>
  62. #include <stdlib.h>
  63. #include <string.h>
  64. #include <assert.h>
  65. /* tor_addr_is_null() and maybe other functions rely on AF_UNSPEC being 0 to
  66. * work correctly. Bail out here if we've found a platform where AF_UNSPEC
  67. * isn't 0. */
  68. #if AF_UNSPEC != 0
  69. #error We rely on AF_UNSPEC being 0. Let us know about your platform, please!
  70. #endif
  71. /** Convert the tor_addr_t in <b>a</b>, with port in <b>port</b>, into a
  72. * sockaddr object in *<b>sa_out</b> of object size <b>len</b>. If not enough
  73. * room is available in sa_out, or on error, return 0. On success, return
  74. * the length of the sockaddr.
  75. *
  76. * Interface note: ordinarily, we return -1 for error. We can't do that here,
  77. * since socklen_t is unsigned on some platforms.
  78. **/
  79. socklen_t
  80. tor_addr_to_sockaddr(const tor_addr_t *a,
  81. uint16_t port,
  82. struct sockaddr *sa_out,
  83. socklen_t len)
  84. {
  85. sa_family_t family = tor_addr_family(a);
  86. if (family == AF_INET) {
  87. struct sockaddr_in *sin;
  88. if (len < (int)sizeof(struct sockaddr_in))
  89. return 0;
  90. sin = (struct sockaddr_in *)sa_out;
  91. memset(sin, 0, sizeof(struct sockaddr_in));
  92. #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
  93. sin->sin_len = sizeof(struct sockaddr_in);
  94. #endif
  95. sin->sin_family = AF_INET;
  96. sin->sin_port = htons(port);
  97. sin->sin_addr.s_addr = tor_addr_to_ipv4n(a);
  98. return sizeof(struct sockaddr_in);
  99. } else if (family == AF_INET6) {
  100. struct sockaddr_in6 *sin6;
  101. if (len < (int)sizeof(struct sockaddr_in6))
  102. return 0;
  103. sin6 = (struct sockaddr_in6 *)sa_out;
  104. memset(sin6, 0, sizeof(struct sockaddr_in6));
  105. #ifdef HAVE_STRUCT_SOCKADDR_IN6_SIN6_LEN
  106. sin6->sin6_len = sizeof(struct sockaddr_in6);
  107. #endif
  108. sin6->sin6_family = AF_INET6;
  109. sin6->sin6_port = htons(port);
  110. memcpy(&sin6->sin6_addr, tor_addr_to_in6(a), sizeof(struct in6_addr));
  111. return sizeof(struct sockaddr_in6);
  112. } else {
  113. return 0;
  114. }
  115. }
  116. /** Set the tor_addr_t in <b>a</b> to contain the socket address contained in
  117. * <b>sa</b>. */
  118. int
  119. tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa,
  120. uint16_t *port_out)
  121. {
  122. tor_assert(a);
  123. tor_assert(sa);
  124. if (sa->sa_family == AF_INET) {
  125. struct sockaddr_in *sin = (struct sockaddr_in *) sa;
  126. tor_addr_from_ipv4n(a, sin->sin_addr.s_addr);
  127. if (port_out)
  128. *port_out = ntohs(sin->sin_port);
  129. } else if (sa->sa_family == AF_INET6) {
  130. struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) sa;
  131. tor_addr_from_in6(a, &sin6->sin6_addr);
  132. if (port_out)
  133. *port_out = ntohs(sin6->sin6_port);
  134. } else {
  135. tor_addr_make_unspec(a);
  136. return -1;
  137. }
  138. return 0;
  139. }
  140. /** Return a newly allocated string holding the address described in
  141. * <b>sa</b>. AF_UNIX, AF_UNSPEC, AF_INET, and AF_INET6 are supported. */
  142. char *
  143. tor_sockaddr_to_str(const struct sockaddr *sa)
  144. {
  145. char address[TOR_ADDR_BUF_LEN];
  146. char *result;
  147. tor_addr_t addr;
  148. uint16_t port;
  149. #ifdef HAVE_SYS_UN_H
  150. if (sa->sa_family == AF_UNIX) {
  151. struct sockaddr_un *s_un = (struct sockaddr_un *)sa;
  152. tor_asprintf(&result, "unix:%s", s_un->sun_path);
  153. return result;
  154. }
  155. #endif
  156. if (sa->sa_family == AF_UNSPEC)
  157. return tor_strdup("unspec");
  158. if (tor_addr_from_sockaddr(&addr, sa, &port) < 0)
  159. return NULL;
  160. if (! tor_addr_to_str(address, &addr, sizeof(address), 1))
  161. return NULL;
  162. tor_asprintf(&result, "%s:%d", address, (int)port);
  163. return result;
  164. }
  165. /** Set address <b>a</b> to the unspecified address. This address belongs to
  166. * no family. */
  167. void
  168. tor_addr_make_unspec(tor_addr_t *a)
  169. {
  170. memset(a, 0, sizeof(*a));
  171. a->family = AF_UNSPEC;
  172. }
  173. /** Similar behavior to Unix gethostbyname: resolve <b>name</b>, and set
  174. * *<b>addr</b> to the proper IP address and family. The <b>family</b>
  175. * argument (which must be AF_INET, AF_INET6, or AF_UNSPEC) declares a
  176. * <i>preferred</i> family, though another one may be returned if only one
  177. * family is implemented for this address.
  178. *
  179. * Return 0 on success, -1 on failure; 1 on transient failure.
  180. */
  181. int
  182. tor_addr_lookup(const char *name, uint16_t family, tor_addr_t *addr)
  183. {
  184. /* Perhaps eventually this should be replaced by a tor_getaddrinfo or
  185. * something.
  186. */
  187. struct in_addr iaddr;
  188. struct in6_addr iaddr6;
  189. tor_assert(name);
  190. tor_assert(addr);
  191. tor_assert(family == AF_INET || family == AF_INET6 || family == AF_UNSPEC);
  192. if (!*name) {
  193. /* Empty address is an error. */
  194. return -1;
  195. } else if (tor_inet_pton(AF_INET, name, &iaddr)) {
  196. /* It's an IPv4 IP. */
  197. if (family == AF_INET6)
  198. return -1;
  199. tor_addr_from_in(addr, &iaddr);
  200. return 0;
  201. } else if (tor_inet_pton(AF_INET6, name, &iaddr6)) {
  202. if (family == AF_INET)
  203. return -1;
  204. tor_addr_from_in6(addr, &iaddr6);
  205. return 0;
  206. } else {
  207. #ifdef HAVE_GETADDRINFO
  208. int err;
  209. struct addrinfo *res=NULL, *res_p;
  210. struct addrinfo *best=NULL;
  211. struct addrinfo hints;
  212. int result = -1;
  213. memset(&hints, 0, sizeof(hints));
  214. hints.ai_family = family;
  215. hints.ai_socktype = SOCK_STREAM;
  216. err = getaddrinfo(name, NULL, &hints, &res);
  217. if (!err) {
  218. best = NULL;
  219. for (res_p = res; res_p; res_p = res_p->ai_next) {
  220. if (family == AF_UNSPEC) {
  221. if (res_p->ai_family == AF_INET) {
  222. best = res_p;
  223. break;
  224. } else if (res_p->ai_family == AF_INET6 && !best) {
  225. best = res_p;
  226. }
  227. } else if (family == res_p->ai_family) {
  228. best = res_p;
  229. break;
  230. }
  231. }
  232. if (!best)
  233. best = res;
  234. if (best->ai_family == AF_INET) {
  235. tor_addr_from_in(addr,
  236. &((struct sockaddr_in*)best->ai_addr)->sin_addr);
  237. result = 0;
  238. } else if (best->ai_family == AF_INET6) {
  239. tor_addr_from_in6(addr,
  240. &((struct sockaddr_in6*)best->ai_addr)->sin6_addr);
  241. result = 0;
  242. }
  243. freeaddrinfo(res);
  244. return result;
  245. }
  246. return (err == EAI_AGAIN) ? 1 : -1;
  247. #else
  248. struct hostent *ent;
  249. int err;
  250. #ifdef HAVE_GETHOSTBYNAME_R_6_ARG
  251. char buf[2048];
  252. struct hostent hostent;
  253. int r;
  254. r = gethostbyname_r(name, &hostent, buf, sizeof(buf), &ent, &err);
  255. #elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
  256. char buf[2048];
  257. struct hostent hostent;
  258. ent = gethostbyname_r(name, &hostent, buf, sizeof(buf), &err);
  259. #elif defined(HAVE_GETHOSTBYNAME_R_3_ARG)
  260. struct hostent_data data;
  261. struct hostent hent;
  262. memset(&data, 0, sizeof(data));
  263. err = gethostbyname_r(name, &hent, &data);
  264. ent = err ? NULL : &hent;
  265. #else
  266. ent = gethostbyname(name);
  267. #ifdef _WIN32
  268. err = WSAGetLastError();
  269. #else
  270. err = h_errno;
  271. #endif
  272. #endif /* endif HAVE_GETHOSTBYNAME_R_6_ARG. */
  273. if (ent) {
  274. if (ent->h_addrtype == AF_INET) {
  275. tor_addr_from_in(addr, (struct in_addr*) ent->h_addr);
  276. } else if (ent->h_addrtype == AF_INET6) {
  277. tor_addr_from_in6(addr, (struct in6_addr*) ent->h_addr);
  278. } else {
  279. tor_assert(0); /* gethostbyname() returned a bizarre addrtype */
  280. }
  281. return 0;
  282. }
  283. #ifdef _WIN32
  284. return (err == WSATRY_AGAIN) ? 1 : -1;
  285. #else
  286. return (err == TRY_AGAIN) ? 1 : -1;
  287. #endif
  288. #endif
  289. }
  290. }
  291. /** Return true iff <b>ip</b> is an IP reserved to localhost or local networks
  292. * in RFC1918 or RFC4193 or RFC4291. (fec0::/10, deprecated by RFC3879, is
  293. * also treated as internal for now.)
  294. */
  295. int
  296. tor_addr_is_internal(const tor_addr_t *addr, int for_listening)
  297. {
  298. uint32_t iph4 = 0;
  299. uint32_t iph6[4];
  300. sa_family_t v_family;
  301. v_family = tor_addr_family(addr);
  302. if (v_family == AF_INET) {
  303. iph4 = tor_addr_to_ipv4h(addr);
  304. } else if (v_family == AF_INET6) {
  305. if (tor_addr_is_v4(addr)) { /* v4-mapped */
  306. v_family = AF_INET;
  307. iph4 = ntohl(tor_addr_to_in6_addr32(addr)[3]);
  308. }
  309. }
  310. if (v_family == AF_INET6) {
  311. const uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  312. iph6[0] = ntohl(a32[0]);
  313. iph6[1] = ntohl(a32[1]);
  314. iph6[2] = ntohl(a32[2]);
  315. iph6[3] = ntohl(a32[3]);
  316. if (for_listening && !iph6[0] && !iph6[1] && !iph6[2] && !iph6[3]) /* :: */
  317. return 0;
  318. if (((iph6[0] & 0xfe000000) == 0xfc000000) || /* fc00/7 - RFC4193 */
  319. ((iph6[0] & 0xffc00000) == 0xfe800000) || /* fe80/10 - RFC4291 */
  320. ((iph6[0] & 0xffc00000) == 0xfec00000)) /* fec0/10 D- RFC3879 */
  321. return 1;
  322. if (!iph6[0] && !iph6[1] && !iph6[2] &&
  323. ((iph6[3] & 0xfffffffe) == 0x00000000)) /* ::/127 */
  324. return 1;
  325. return 0;
  326. } else if (v_family == AF_INET) {
  327. if (for_listening && !iph4) /* special case for binding to 0.0.0.0 */
  328. return 0;
  329. if (((iph4 & 0xff000000) == 0x0a000000) || /* 10/8 */
  330. ((iph4 & 0xff000000) == 0x00000000) || /* 0/8 */
  331. ((iph4 & 0xff000000) == 0x7f000000) || /* 127/8 */
  332. ((iph4 & 0xffff0000) == 0xa9fe0000) || /* 169.254/16 */
  333. ((iph4 & 0xfff00000) == 0xac100000) || /* 172.16/12 */
  334. ((iph4 & 0xffff0000) == 0xc0a80000)) /* 192.168/16 */
  335. return 1;
  336. return 0;
  337. }
  338. /* unknown address family... assume it's not safe for external use */
  339. /* rather than tor_assert(0) */
  340. log_warn(LD_BUG, "tor_addr_is_internal() called with a non-IP address.");
  341. return 1;
  342. }
  343. /** Convert a tor_addr_t <b>addr</b> into a string, and store it in
  344. * <b>dest</b> of size <b>len</b>. Returns a pointer to dest on success,
  345. * or NULL on failure. If <b>decorate</b>, surround IPv6 addresses with
  346. * brackets.
  347. */
  348. const char *
  349. tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
  350. {
  351. const char *ptr;
  352. tor_assert(addr && dest);
  353. switch (tor_addr_family(addr)) {
  354. case AF_INET:
  355. /* Shortest addr x.x.x.x + \0 */
  356. if (len < 8)
  357. return NULL;
  358. ptr = tor_inet_ntop(AF_INET, &addr->addr.in_addr, dest, len);
  359. break;
  360. case AF_INET6:
  361. /* Shortest addr [ :: ] + \0 */
  362. if (len < (3 + (decorate ? 2 : 0)))
  363. return NULL;
  364. if (decorate)
  365. ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest+1, len-2);
  366. else
  367. ptr = tor_inet_ntop(AF_INET6, &addr->addr.in6_addr, dest, len);
  368. if (ptr && decorate) {
  369. *dest = '[';
  370. memcpy(dest+strlen(dest), "]", 2);
  371. tor_assert(ptr == dest+1);
  372. ptr = dest;
  373. }
  374. break;
  375. default:
  376. return NULL;
  377. }
  378. return ptr;
  379. }
  380. /** Parse an .in-addr.arpa or .ip6.arpa address from <b>address</b>. Return 0
  381. * if this is not an .in-addr.arpa address or an .ip6.arpa address. Return -1
  382. * if this is an ill-formed .in-addr.arpa address or an .ip6.arpa address.
  383. * Also return -1 if <b>family</b> is not AF_UNSPEC, and the parsed address
  384. * family does not match <b>family</b>. On success, return 1, and store the
  385. * result, if any, into <b>result</b>, if provided.
  386. *
  387. * If <b>accept_regular</b> is set and the address is in neither recognized
  388. * reverse lookup hostname format, try parsing the address as a regular
  389. * IPv4 or IPv6 address too.
  390. */
  391. int
  392. tor_addr_parse_PTR_name(tor_addr_t *result, const char *address,
  393. int family, int accept_regular)
  394. {
  395. if (!strcasecmpend(address, ".in-addr.arpa")) {
  396. /* We have an in-addr.arpa address. */
  397. char buf[INET_NTOA_BUF_LEN];
  398. size_t len;
  399. struct in_addr inaddr;
  400. if (family == AF_INET6)
  401. return -1;
  402. len = strlen(address) - strlen(".in-addr.arpa");
  403. if (len >= INET_NTOA_BUF_LEN)
  404. return -1; /* Too long. */
  405. memcpy(buf, address, len);
  406. buf[len] = '\0';
  407. if (tor_inet_aton(buf, &inaddr) == 0)
  408. return -1; /* malformed. */
  409. /* reverse the bytes */
  410. inaddr.s_addr = (uint32_t)
  411. (((inaddr.s_addr & 0x000000ff) << 24)
  412. |((inaddr.s_addr & 0x0000ff00) << 8)
  413. |((inaddr.s_addr & 0x00ff0000) >> 8)
  414. |((inaddr.s_addr & 0xff000000) >> 24));
  415. if (result) {
  416. tor_addr_from_in(result, &inaddr);
  417. }
  418. return 1;
  419. }
  420. if (!strcasecmpend(address, ".ip6.arpa")) {
  421. const char *cp;
  422. int i;
  423. int n0, n1;
  424. struct in6_addr in6;
  425. if (family == AF_INET)
  426. return -1;
  427. cp = address;
  428. for (i = 0; i < 16; ++i) {
  429. n0 = hex_decode_digit(*cp++); /* The low-order nybble appears first. */
  430. if (*cp++ != '.') return -1; /* Then a dot. */
  431. n1 = hex_decode_digit(*cp++); /* The high-order nybble appears first. */
  432. if (*cp++ != '.') return -1; /* Then another dot. */
  433. if (n0<0 || n1 < 0) /* Both nybbles must be hex. */
  434. return -1;
  435. /* We don't check the length of the string in here. But that's okay,
  436. * since we already know that the string ends with ".ip6.arpa", and
  437. * there is no way to frameshift .ip6.arpa so it fits into the pattern
  438. * of hexdigit, period, hexdigit, period that we enforce above.
  439. */
  440. /* Assign from low-byte to high-byte. */
  441. in6.s6_addr[15-i] = n0 | (n1 << 4);
  442. }
  443. if (strcasecmp(cp, "ip6.arpa"))
  444. return -1;
  445. if (result) {
  446. tor_addr_from_in6(result, &in6);
  447. }
  448. return 1;
  449. }
  450. if (accept_regular) {
  451. tor_addr_t tmp;
  452. int r = tor_addr_parse(&tmp, address);
  453. if (r < 0)
  454. return 0;
  455. if (r != family && family != AF_UNSPEC)
  456. return -1;
  457. if (result)
  458. memcpy(result, &tmp, sizeof(tor_addr_t));
  459. return 1;
  460. }
  461. return 0;
  462. }
  463. /** Convert <b>addr</b> to an in-addr.arpa name or a .ip6.arpa name,
  464. * and store the result in the <b>outlen</b>-byte buffer at
  465. * <b>out</b>. Return the number of chars written to <b>out</b>, not
  466. * including the trailing \0, on success. Returns -1 on failure. */
  467. int
  468. tor_addr_to_PTR_name(char *out, size_t outlen,
  469. const tor_addr_t *addr)
  470. {
  471. tor_assert(out);
  472. tor_assert(addr);
  473. if (addr->family == AF_INET) {
  474. uint32_t a = tor_addr_to_ipv4h(addr);
  475. return tor_snprintf(out, outlen, "%d.%d.%d.%d.in-addr.arpa",
  476. (int)(uint8_t)((a )&0xff),
  477. (int)(uint8_t)((a>>8 )&0xff),
  478. (int)(uint8_t)((a>>16)&0xff),
  479. (int)(uint8_t)((a>>24)&0xff));
  480. } else if (addr->family == AF_INET6) {
  481. int i;
  482. char *cp = out;
  483. const uint8_t *bytes = tor_addr_to_in6_addr8(addr);
  484. if (outlen < REVERSE_LOOKUP_NAME_BUF_LEN)
  485. return -1;
  486. for (i = 15; i >= 0; --i) {
  487. uint8_t byte = bytes[i];
  488. *cp++ = "0123456789abcdef"[byte & 0x0f];
  489. *cp++ = '.';
  490. *cp++ = "0123456789abcdef"[byte >> 4];
  491. *cp++ = '.';
  492. }
  493. memcpy(cp, "ip6.arpa", 9); /* 8 characters plus NUL */
  494. return 32 * 2 + 8;
  495. }
  496. return -1;
  497. }
  498. /** Parse a string <b>s</b> containing an IPv4/IPv6 address, and possibly
  499. * a mask and port or port range. Store the parsed address in
  500. * <b>addr_out</b>, a mask (if any) in <b>mask_out</b>, and port(s) (if any)
  501. * in <b>port_min_out</b> and <b>port_max_out</b>.
  502. *
  503. * The syntax is:
  504. * Address OptMask OptPortRange
  505. * Address ::= IPv4Address / "[" IPv6Address "]" / "*"
  506. * OptMask ::= "/" Integer /
  507. * OptPortRange ::= ":*" / ":" Integer / ":" Integer "-" Integer /
  508. *
  509. * - If mask, minport, or maxport are NULL, we do not want these
  510. * options to be set; treat them as an error if present.
  511. * - If the string has no mask, the mask is set to /32 (IPv4) or /128 (IPv6).
  512. * - If the string has one port, it is placed in both min and max port
  513. * variables.
  514. * - If the string has no port(s), port_(min|max)_out are set to 1 and 65535.
  515. *
  516. * Return an address family on success, or -1 if an invalid address string is
  517. * provided.
  518. */
  519. int
  520. tor_addr_parse_mask_ports(const char *s, tor_addr_t *addr_out,
  521. maskbits_t *maskbits_out,
  522. uint16_t *port_min_out, uint16_t *port_max_out)
  523. {
  524. char *base = NULL, *address, *mask = NULL, *port = NULL, *rbracket = NULL;
  525. char *endptr;
  526. int any_flag=0, v4map=0;
  527. sa_family_t family;
  528. struct in6_addr in6_tmp;
  529. struct in_addr in_tmp;
  530. tor_assert(s);
  531. tor_assert(addr_out);
  532. /** Longest possible length for an address, mask, and port-range combination.
  533. * Includes IP, [], /mask, :, ports */
  534. #define MAX_ADDRESS_LENGTH (TOR_ADDR_BUF_LEN+2+(1+INET_NTOA_BUF_LEN)+12+1)
  535. if (strlen(s) > MAX_ADDRESS_LENGTH) {
  536. log_warn(LD_GENERAL, "Impossibly long IP %s; rejecting", escaped(s));
  537. goto err;
  538. }
  539. base = tor_strdup(s);
  540. /* Break 'base' into separate strings. */
  541. address = base;
  542. if (*address == '[') { /* Probably IPv6 */
  543. address++;
  544. rbracket = strchr(address, ']');
  545. if (!rbracket) {
  546. log_warn(LD_GENERAL,
  547. "No closing IPv6 bracket in address pattern; rejecting.");
  548. goto err;
  549. }
  550. }
  551. mask = strchr((rbracket?rbracket:address),'/');
  552. port = strchr((mask?mask:(rbracket?rbracket:address)), ':');
  553. if (port)
  554. *port++ = '\0';
  555. if (mask)
  556. *mask++ = '\0';
  557. if (rbracket)
  558. *rbracket = '\0';
  559. if (port && mask)
  560. tor_assert(port > mask);
  561. if (mask && rbracket)
  562. tor_assert(mask > rbracket);
  563. /* Now "address" is the a.b.c.d|'*'|abcd::1 part...
  564. * "mask" is the Mask|Maskbits part...
  565. * and "port" is the *|port|min-max part.
  566. */
  567. /* Process the address portion */
  568. memset(addr_out, 0, sizeof(tor_addr_t));
  569. if (!strcmp(address, "*")) {
  570. family = AF_INET; /* AF_UNSPEC ???? XXXX_IP6 */
  571. tor_addr_from_ipv4h(addr_out, 0);
  572. any_flag = 1;
  573. } else if (tor_inet_pton(AF_INET6, address, &in6_tmp) > 0) {
  574. family = AF_INET6;
  575. tor_addr_from_in6(addr_out, &in6_tmp);
  576. } else if (tor_inet_pton(AF_INET, address, &in_tmp) > 0) {
  577. family = AF_INET;
  578. tor_addr_from_in(addr_out, &in_tmp);
  579. } else {
  580. log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
  581. escaped(address));
  582. goto err;
  583. }
  584. v4map = tor_addr_is_v4(addr_out);
  585. /* Parse mask */
  586. if (maskbits_out) {
  587. int bits = 0;
  588. struct in_addr v4mask;
  589. if (mask) { /* the caller (tried to) specify a mask */
  590. bits = (int) strtol(mask, &endptr, 10);
  591. if (!*endptr) { /* strtol converted everything, so it was an integer */
  592. if ((bits<0 || bits>128) ||
  593. (family == AF_INET && bits > 32)) {
  594. log_warn(LD_GENERAL,
  595. "Bad number of mask bits (%d) on address range; rejecting.",
  596. bits);
  597. goto err;
  598. }
  599. } else { /* mask might still be an address-style mask */
  600. if (tor_inet_pton(AF_INET, mask, &v4mask) > 0) {
  601. bits = addr_mask_get_bits(ntohl(v4mask.s_addr));
  602. if (bits < 0) {
  603. log_warn(LD_GENERAL,
  604. "IPv4-style mask %s is not a prefix address; rejecting.",
  605. escaped(mask));
  606. goto err;
  607. }
  608. } else { /* Not IPv4; we don't do address-style IPv6 masks. */
  609. log_warn(LD_GENERAL,
  610. "Malformed mask on address range %s; rejecting.",
  611. escaped(s));
  612. goto err;
  613. }
  614. }
  615. if (family == AF_INET6 && v4map) {
  616. if (bits > 32 && bits < 96) { /* Crazy */
  617. log_warn(LD_GENERAL,
  618. "Bad mask bits %d for V4-mapped V6 address; rejecting.",
  619. bits);
  620. goto err;
  621. }
  622. /* XXXX_IP6 is this really what we want? */
  623. bits = 96 + bits%32; /* map v4-mapped masks onto 96-128 bits */
  624. }
  625. } else { /* pick an appropriate mask, as none was given */
  626. if (any_flag)
  627. bits = 0; /* This is okay whether it's V6 or V4 (FIX V4-mapped V6!) */
  628. else if (tor_addr_family(addr_out) == AF_INET)
  629. bits = 32;
  630. else if (tor_addr_family(addr_out) == AF_INET6)
  631. bits = 128;
  632. }
  633. *maskbits_out = (maskbits_t) bits;
  634. } else {
  635. if (mask) {
  636. log_warn(LD_GENERAL,
  637. "Unexpected mask in address %s; rejecting", escaped(s));
  638. goto err;
  639. }
  640. }
  641. /* Parse port(s) */
  642. if (port_min_out) {
  643. uint16_t port2;
  644. if (!port_max_out) /* caller specified one port; fake the second one */
  645. port_max_out = &port2;
  646. if (parse_port_range(port, port_min_out, port_max_out) < 0) {
  647. goto err;
  648. } else if ((*port_min_out != *port_max_out) && port_max_out == &port2) {
  649. log_warn(LD_GENERAL,
  650. "Wanted one port from address range, but there are two.");
  651. port_max_out = NULL; /* caller specified one port, so set this back */
  652. goto err;
  653. }
  654. } else {
  655. if (port) {
  656. log_warn(LD_GENERAL,
  657. "Unexpected ports in address %s; rejecting", escaped(s));
  658. goto err;
  659. }
  660. }
  661. tor_free(base);
  662. return tor_addr_family(addr_out);
  663. err:
  664. tor_free(base);
  665. return -1;
  666. }
  667. /** Determine whether an address is IPv4, either native or IPv4-mapped IPv6.
  668. * Note that this is about representation only, as any decent stack will
  669. * reject IPv4-mapped addresses received on the wire (and won't use them
  670. * on the wire either).
  671. */
  672. int
  673. tor_addr_is_v4(const tor_addr_t *addr)
  674. {
  675. tor_assert(addr);
  676. if (tor_addr_family(addr) == AF_INET)
  677. return 1;
  678. if (tor_addr_family(addr) == AF_INET6) {
  679. /* First two don't need to be ordered */
  680. uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  681. if (a32[0] == 0 && a32[1] == 0 && ntohl(a32[2]) == 0x0000ffffu)
  682. return 1;
  683. }
  684. return 0; /* Not IPv4 - unknown family or a full-blood IPv6 address */
  685. }
  686. /** Determine whether an address <b>addr</b> is null, either all zeroes or
  687. * belonging to family AF_UNSPEC.
  688. */
  689. int
  690. tor_addr_is_null(const tor_addr_t *addr)
  691. {
  692. tor_assert(addr);
  693. switch (tor_addr_family(addr)) {
  694. case AF_INET6: {
  695. uint32_t *a32 = tor_addr_to_in6_addr32(addr);
  696. return (a32[0] == 0) && (a32[1] == 0) && (a32[2] == 0) && (a32[3] == 0);
  697. }
  698. case AF_INET:
  699. return (tor_addr_to_ipv4n(addr) == 0);
  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) && (a32[3] == 1);
  719. }
  720. case AF_INET:
  721. /* 127.0.0.1 */
  722. return (tor_addr_to_ipv4h(addr) & 0xff000000) == 0x7f000000;
  723. case AF_UNSPEC:
  724. return 0;
  725. default:
  726. tor_fragile_assert();
  727. return 0;
  728. }
  729. }
  730. /** Set <b>dest</b> to equal the IPv4 address in <b>v4addr</b> (given in
  731. * network order). */
  732. void
  733. tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
  734. {
  735. tor_assert(dest);
  736. memset(dest, 0, sizeof(tor_addr_t));
  737. dest->family = AF_INET;
  738. dest->addr.in_addr.s_addr = v4addr;
  739. }
  740. /** Set <b>dest</b> to equal the IPv6 address in the 16 bytes at
  741. * <b>ipv6_bytes</b>. */
  742. void
  743. tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
  744. {
  745. tor_assert(dest);
  746. tor_assert(ipv6_bytes);
  747. memset(dest, 0, sizeof(tor_addr_t));
  748. dest->family = AF_INET6;
  749. memcpy(dest->addr.in6_addr.s6_addr, ipv6_bytes, 16);
  750. }
  751. /** Set <b>dest</b> equal to the IPv6 address in the in6_addr <b>in6</b>. */
  752. void
  753. tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
  754. {
  755. tor_addr_from_ipv6_bytes(dest, (const char*)in6->s6_addr);
  756. }
  757. /** Copy a tor_addr_t from <b>src</b> to <b>dest</b>.
  758. */
  759. void
  760. tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
  761. {
  762. if (src == dest)
  763. return;
  764. tor_assert(src);
  765. tor_assert(dest);
  766. memcpy(dest, src, sizeof(tor_addr_t));
  767. }
  768. /** Given two addresses <b>addr1</b> and <b>addr2</b>, return 0 if the two
  769. * addresses are equivalent under the mask mbits, less than 0 if addr1
  770. * precedes addr2, and greater than 0 otherwise.
  771. *
  772. * Different address families (IPv4 vs IPv6) are always considered unequal if
  773. * <b>how</b> is CMP_EXACT; otherwise, IPv6-mapped IPv4 addresses are
  774. * considered equivalent to their IPv4 equivalents.
  775. */
  776. int
  777. tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2,
  778. tor_addr_comparison_t how)
  779. {
  780. return tor_addr_compare_masked(addr1, addr2, 128, how);
  781. }
  782. /** As tor_addr_compare(), but only looks at the first <b>mask</b> bits of
  783. * the address.
  784. *
  785. * Reduce over-specific masks (>128 for ipv6, >32 for ipv4) to 128 or 32.
  786. *
  787. * The mask is interpreted relative to <b>addr1</b>, so that if a is
  788. * \::ffff:1.2.3.4, and b is 3.4.5.6,
  789. * tor_addr_compare_masked(a,b,100,CMP_SEMANTIC) is the same as
  790. * -tor_addr_compare_masked(b,a,4,CMP_SEMANTIC).
  791. *
  792. * We guarantee that the ordering from tor_addr_compare_masked is a total
  793. * order on addresses, but not that it is any particular order, or that it
  794. * will be the same from one version to the next.
  795. */
  796. int
  797. tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2,
  798. maskbits_t mbits, tor_addr_comparison_t how)
  799. {
  800. /** Helper: Evaluates to -1 if a is less than b, 0 if a equals b, or 1 if a
  801. * is greater than b. May evaluate a and b more than once. */
  802. #define TRISTATE(a,b) (((a)<(b))?-1: (((a)==(b))?0:1))
  803. sa_family_t family1, family2, v_family1, v_family2;
  804. tor_assert(addr1 && addr2);
  805. v_family1 = family1 = tor_addr_family(addr1);
  806. v_family2 = family2 = tor_addr_family(addr2);
  807. if (family1==family2) {
  808. /* When the families are the same, there's only one way to do the
  809. * comparison: exactly. */
  810. int r;
  811. switch (family1) {
  812. case AF_UNSPEC:
  813. return 0; /* All unspecified addresses are equal */
  814. case AF_INET: {
  815. uint32_t a1 = tor_addr_to_ipv4h(addr1);
  816. uint32_t a2 = tor_addr_to_ipv4h(addr2);
  817. if (mbits <= 0)
  818. return 0;
  819. if (mbits > 32)
  820. mbits = 32;
  821. a1 >>= (32-mbits);
  822. a2 >>= (32-mbits);
  823. r = TRISTATE(a1, a2);
  824. return r;
  825. }
  826. case AF_INET6: {
  827. const uint8_t *a1 = tor_addr_to_in6_addr8(addr1);
  828. const uint8_t *a2 = tor_addr_to_in6_addr8(addr2);
  829. const int bytes = mbits >> 3;
  830. const int leftover_bits = mbits & 7;
  831. if (bytes && (r = tor_memcmp(a1, a2, bytes))) {
  832. return r;
  833. } else if (leftover_bits) {
  834. uint8_t b1 = a1[bytes] >> (8-leftover_bits);
  835. uint8_t b2 = a2[bytes] >> (8-leftover_bits);
  836. return TRISTATE(b1, b2);
  837. } else {
  838. return 0;
  839. }
  840. }
  841. default:
  842. tor_fragile_assert();
  843. return 0;
  844. }
  845. } else if (how == CMP_EXACT) {
  846. /* Unequal families and an exact comparison? Stop now! */
  847. return TRISTATE(family1, family2);
  848. }
  849. if (mbits == 0)
  850. return 0;
  851. if (family1 == AF_INET6 && tor_addr_is_v4(addr1))
  852. v_family1 = AF_INET;
  853. if (family2 == AF_INET6 && tor_addr_is_v4(addr2))
  854. v_family2 = AF_INET;
  855. if (v_family1 == v_family2) {
  856. /* One or both addresses are a mapped ipv4 address. */
  857. uint32_t a1, a2;
  858. if (family1 == AF_INET6) {
  859. a1 = tor_addr_to_mapped_ipv4h(addr1);
  860. if (mbits <= 96)
  861. return 0;
  862. mbits -= 96; /* We just decided that the first 96 bits of a1 "match". */
  863. } else {
  864. a1 = tor_addr_to_ipv4h(addr1);
  865. }
  866. if (family2 == AF_INET6) {
  867. a2 = tor_addr_to_mapped_ipv4h(addr2);
  868. } else {
  869. a2 = tor_addr_to_ipv4h(addr2);
  870. }
  871. if (mbits <= 0) return 0;
  872. if (mbits > 32) mbits = 32;
  873. a1 >>= (32-mbits);
  874. a2 >>= (32-mbits);
  875. return TRISTATE(a1, a2);
  876. } else {
  877. /* Unequal families, and semantic comparison, and no semantic family
  878. * matches. */
  879. return TRISTATE(family1, family2);
  880. }
  881. }
  882. /** Return a hash code based on the address addr */
  883. unsigned int
  884. tor_addr_hash(const tor_addr_t *addr)
  885. {
  886. switch (tor_addr_family(addr)) {
  887. case AF_INET:
  888. return tor_addr_to_ipv4h(addr);
  889. case AF_UNSPEC:
  890. return 0x4e4d5342;
  891. case AF_INET6: {
  892. const uint32_t *u = tor_addr_to_in6_addr32(addr);
  893. return u[0] + u[1] + u[2] + u[3];
  894. }
  895. default:
  896. tor_fragile_assert();
  897. return 0;
  898. }
  899. }
  900. /** Return a newly allocated string with a representation of <b>addr</b>. */
  901. char *
  902. tor_dup_addr(const tor_addr_t *addr)
  903. {
  904. char buf[TOR_ADDR_BUF_LEN];
  905. if (tor_addr_to_str(buf, addr, sizeof(buf), 0)) {
  906. return tor_strdup(buf);
  907. } else {
  908. return tor_strdup("<unknown address type>");
  909. }
  910. }
  911. /** Return a string representing the address <b>addr</b>. This string is
  912. * statically allocated, and must not be freed. Each call to
  913. * <b>fmt_addr</b> invalidates the last result of the function. This
  914. * function is not thread-safe. */
  915. const char *
  916. fmt_addr(const tor_addr_t *addr)
  917. {
  918. static char buf[TOR_ADDR_BUF_LEN];
  919. if (!addr) return "<null>";
  920. if (tor_addr_to_str(buf, addr, sizeof(buf), 0))
  921. return buf;
  922. else
  923. return "???";
  924. }
  925. /** Like fmt_addr(), but takes <b>addr</b> as a host-order IPv4
  926. * addresses. Also not thread-safe, also clobbers its return buffer on
  927. * repeated calls. */
  928. const char *
  929. fmt_addr32(uint32_t addr)
  930. {
  931. static char buf[INET_NTOA_BUF_LEN];
  932. struct in_addr in;
  933. in.s_addr = htonl(addr);
  934. tor_inet_ntoa(&in, buf, sizeof(buf));
  935. return buf;
  936. }
  937. /** Convert the string in <b>src</b> to a tor_addr_t <b>addr</b>. The string
  938. * may be an IPv4 address, an IPv6 address, or an IPv6 address surrounded by
  939. * square brackets.
  940. *
  941. * Return an address family on success, or -1 if an invalid address string is
  942. * provided. */
  943. int
  944. tor_addr_parse(tor_addr_t *addr, const char *src)
  945. {
  946. char *tmp = NULL; /* Holds substring if we got a dotted quad. */
  947. int result;
  948. struct in_addr in_tmp;
  949. struct in6_addr in6_tmp;
  950. tor_assert(addr && src);
  951. if (src[0] == '[' && src[1])
  952. src = tmp = tor_strndup(src+1, strlen(src)-2);
  953. if (tor_inet_pton(AF_INET6, src, &in6_tmp) > 0) {
  954. result = AF_INET6;
  955. tor_addr_from_in6(addr, &in6_tmp);
  956. } else if (tor_inet_pton(AF_INET, src, &in_tmp) > 0) {
  957. result = AF_INET;
  958. tor_addr_from_in(addr, &in_tmp);
  959. } else {
  960. result = -1;
  961. }
  962. tor_free(tmp);
  963. return result;
  964. }
  965. /** Parse an address or address-port combination from <b>s</b>, resolve the
  966. * address as needed, and put the result in <b>addr_out</b> and (optionally)
  967. * <b>port_out</b>. Return 0 on success, negative on failure. */
  968. int
  969. tor_addr_port_lookup(const char *s, tor_addr_t *addr_out, uint16_t *port_out)
  970. {
  971. const char *port;
  972. tor_addr_t addr;
  973. uint16_t portval;
  974. char *tmp = NULL;
  975. tor_assert(s);
  976. tor_assert(addr_out);
  977. s = eat_whitespace(s);
  978. if (*s == '[') {
  979. port = strstr(s, "]");
  980. if (!port)
  981. goto err;
  982. tmp = tor_strndup(s+1, port-(s+1));
  983. port = port+1;
  984. if (*port == ':')
  985. port++;
  986. else
  987. port = NULL;
  988. } else {
  989. port = strchr(s, ':');
  990. if (port)
  991. tmp = tor_strndup(s, port-s);
  992. else
  993. tmp = tor_strdup(s);
  994. if (port)
  995. ++port;
  996. }
  997. if (tor_addr_lookup(tmp, AF_UNSPEC, &addr) != 0)
  998. goto err;
  999. tor_free(tmp);
  1000. if (port) {
  1001. portval = (int) tor_parse_long(port, 10, 1, 65535, NULL, NULL);
  1002. if (!portval)
  1003. goto err;
  1004. } else {
  1005. portval = 0;
  1006. }
  1007. if (port_out)
  1008. *port_out = portval;
  1009. tor_addr_copy(addr_out, &addr);
  1010. return 0;
  1011. err:
  1012. tor_free(tmp);
  1013. return -1;
  1014. }
  1015. #ifdef _WIN32
  1016. typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)(
  1017. ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
  1018. #endif
  1019. /** Try to ask our network interfaces what addresses they are bound to.
  1020. * Return a new smartlist of tor_addr_t on success, and NULL on failure.
  1021. * (An empty smartlist indicates that we successfully learned that we have no
  1022. * addresses.) Log failure messages at <b>severity</b>. */
  1023. static smartlist_t *
  1024. get_interface_addresses_raw(int severity)
  1025. {
  1026. #if defined(HAVE_GETIFADDRS)
  1027. /* Most free Unixy systems provide getifaddrs, which gives us a linked list
  1028. * of struct ifaddrs. */
  1029. struct ifaddrs *ifa = NULL;
  1030. const struct ifaddrs *i;
  1031. smartlist_t *result;
  1032. if (getifaddrs(&ifa) < 0) {
  1033. log_fn(severity, LD_NET, "Unable to call getifaddrs(): %s",
  1034. strerror(errno));
  1035. return NULL;
  1036. }
  1037. result = smartlist_new();
  1038. for (i = ifa; i; i = i->ifa_next) {
  1039. tor_addr_t tmp;
  1040. if (!i->ifa_addr)
  1041. continue;
  1042. if (i->ifa_addr->sa_family != AF_INET &&
  1043. i->ifa_addr->sa_family != AF_INET6)
  1044. continue;
  1045. if (tor_addr_from_sockaddr(&tmp, i->ifa_addr, NULL) < 0)
  1046. continue;
  1047. smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
  1048. }
  1049. freeifaddrs(ifa);
  1050. return result;
  1051. #elif defined(_WIN32)
  1052. /* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
  1053. "GetAdaptersInfo", but that's deprecated; let's just try
  1054. GetAdaptersAddresses and fall back to connect+getsockname.
  1055. */
  1056. HANDLE lib = load_windows_system_library(TEXT("iphlpapi.dll"));
  1057. smartlist_t *result = NULL;
  1058. GetAdaptersAddresses_fn_t fn;
  1059. ULONG size, res;
  1060. IP_ADAPTER_ADDRESSES *addresses = NULL, *address;
  1061. (void) severity;
  1062. #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
  1063. GAA_FLAG_SKIP_MULTICAST | \
  1064. GAA_FLAG_SKIP_DNS_SERVER)
  1065. if (!lib) {
  1066. log_fn(severity, LD_NET, "Unable to load iphlpapi.dll");
  1067. goto done;
  1068. }
  1069. if (!(fn = (GetAdaptersAddresses_fn_t)
  1070. GetProcAddress(lib, "GetAdaptersAddresses"))) {
  1071. log_fn(severity, LD_NET, "Unable to obtain pointer to "
  1072. "GetAdaptersAddresses");
  1073. goto done;
  1074. }
  1075. /* Guess how much space we need. */
  1076. size = 15*1024;
  1077. addresses = tor_malloc(size);
  1078. res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
  1079. if (res == ERROR_BUFFER_OVERFLOW) {
  1080. /* we didn't guess that we needed enough space; try again */
  1081. tor_free(addresses);
  1082. addresses = tor_malloc(size);
  1083. res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
  1084. }
  1085. if (res != NO_ERROR) {
  1086. log_fn(severity, LD_NET, "GetAdaptersAddresses failed (result: %lu)", res);
  1087. goto done;
  1088. }
  1089. result = smartlist_new();
  1090. for (address = addresses; address; address = address->Next) {
  1091. IP_ADAPTER_UNICAST_ADDRESS *a;
  1092. for (a = address->FirstUnicastAddress; a; a = a->Next) {
  1093. /* Yes, it's a linked list inside a linked list */
  1094. struct sockaddr *sa = a->Address.lpSockaddr;
  1095. tor_addr_t tmp;
  1096. if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
  1097. continue;
  1098. if (tor_addr_from_sockaddr(&tmp, sa, NULL) < 0)
  1099. continue;
  1100. smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
  1101. }
  1102. }
  1103. done:
  1104. if (lib)
  1105. FreeLibrary(lib);
  1106. tor_free(addresses);
  1107. return result;
  1108. #elif defined(SIOCGIFCONF) && defined(HAVE_IOCTL)
  1109. /* Some older unixy systems make us use ioctl(SIOCGIFCONF) */
  1110. struct ifconf ifc;
  1111. int fd, i, sz, n;
  1112. smartlist_t *result = NULL;
  1113. /* This interface, AFAICT, only supports AF_INET addresses */
  1114. fd = socket(AF_INET, SOCK_DGRAM, 0);
  1115. if (fd < 0) {
  1116. log(severity, LD_NET, "socket failed: %s", strerror(errno));
  1117. goto done;
  1118. }
  1119. /* Guess how much space we need. */
  1120. ifc.ifc_len = sz = 15*1024;
  1121. ifc.ifc_ifcu.ifcu_req = tor_malloc(sz);
  1122. if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) {
  1123. log(severity, LD_NET, "ioctl failed: %s", strerror(errno));
  1124. close(fd);
  1125. goto done;
  1126. }
  1127. close(fd);
  1128. result = smartlist_new();
  1129. if (ifc.ifc_len < sz)
  1130. sz = ifc.ifc_len;
  1131. n = sz / sizeof(struct ifreq);
  1132. for (i = 0; i < n ; ++i) {
  1133. struct ifreq *r = &ifc.ifc_ifcu.ifcu_req[i];
  1134. struct sockaddr *sa = &r->ifr_addr;
  1135. tor_addr_t tmp;
  1136. if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
  1137. continue; /* should be impossible */
  1138. if (tor_addr_from_sockaddr(&tmp, sa, NULL) < 0)
  1139. continue;
  1140. smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
  1141. }
  1142. done:
  1143. tor_free(ifc.ifc_ifcu.ifcu_req);
  1144. return result;
  1145. #else
  1146. (void) severity;
  1147. return NULL;
  1148. #endif
  1149. }
  1150. /** Return true iff <b>a</b> is a multicast address. */
  1151. static int
  1152. tor_addr_is_multicast(const tor_addr_t *a)
  1153. {
  1154. sa_family_t family = tor_addr_family(a);
  1155. if (family == AF_INET) {
  1156. uint32_t ipv4h = tor_addr_to_ipv4h(a);
  1157. if ((ipv4h >> 24) == 0xe0)
  1158. return 1; /* Multicast */
  1159. } else if (family == AF_INET6) {
  1160. const uint8_t *a32 = tor_addr_to_in6_addr8(a);
  1161. if (a32[0] == 0xff)
  1162. return 1;
  1163. }
  1164. return 0;
  1165. }
  1166. /** Set *<b>addr</b> to the IP address (if any) of whatever interface
  1167. * connects to the Internet. This address should only be used in checking
  1168. * whether our address has changed. Return 0 on success, -1 on failure.
  1169. */
  1170. int
  1171. get_interface_address6(int severity, sa_family_t family, tor_addr_t *addr)
  1172. {
  1173. /* XXX really, this function should yield a smartlist of addresses. */
  1174. smartlist_t *addrs;
  1175. int sock=-1, r=-1;
  1176. struct sockaddr_storage my_addr, target_addr;
  1177. socklen_t addr_len;
  1178. tor_assert(addr);
  1179. /* Try to do this the smart way if possible. */
  1180. if ((addrs = get_interface_addresses_raw(severity))) {
  1181. int rv = -1;
  1182. SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a) {
  1183. if (family != AF_UNSPEC && family != tor_addr_family(a))
  1184. continue;
  1185. if (tor_addr_is_loopback(a) ||
  1186. tor_addr_is_multicast(a))
  1187. continue;
  1188. tor_addr_copy(addr, a);
  1189. rv = 0;
  1190. /* If we found a non-internal address, declare success. Otherwise,
  1191. * keep looking. */
  1192. if (!tor_addr_is_internal(a, 0))
  1193. break;
  1194. } SMARTLIST_FOREACH_END(a);
  1195. SMARTLIST_FOREACH(addrs, tor_addr_t *, a, tor_free(a));
  1196. smartlist_free(addrs);
  1197. return rv;
  1198. }
  1199. /* Okay, the smart way is out. */
  1200. memset(addr, 0, sizeof(tor_addr_t));
  1201. memset(&target_addr, 0, sizeof(target_addr));
  1202. /* Don't worry: no packets are sent. We just need to use a real address
  1203. * on the actual Internet. */
  1204. if (family == AF_INET6) {
  1205. struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&target_addr;
  1206. /* Use the "discard" service port */
  1207. sin6->sin6_port = htons(9);
  1208. sock = tor_open_socket(PF_INET6,SOCK_DGRAM,IPPROTO_UDP);
  1209. addr_len = (socklen_t)sizeof(struct sockaddr_in6);
  1210. sin6->sin6_family = AF_INET6;
  1211. S6_ADDR16(sin6->sin6_addr)[0] = htons(0x2002); /* 2002:: */
  1212. } else if (family == AF_INET) {
  1213. struct sockaddr_in *sin = (struct sockaddr_in*)&target_addr;
  1214. /* Use the "discard" service port */
  1215. sin->sin_port = htons(9);
  1216. sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
  1217. addr_len = (socklen_t)sizeof(struct sockaddr_in);
  1218. sin->sin_family = AF_INET;
  1219. sin->sin_addr.s_addr = htonl(0x12000001); /* 18.0.0.1 */
  1220. } else {
  1221. return -1;
  1222. }
  1223. if (sock < 0) {
  1224. int e = tor_socket_errno(-1);
  1225. log_fn(severity, LD_NET, "unable to create socket: %s",
  1226. tor_socket_strerror(e));
  1227. goto err;
  1228. }
  1229. if (connect(sock,(struct sockaddr *)&target_addr, addr_len) < 0) {
  1230. int e = tor_socket_errno(sock);
  1231. log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e));
  1232. goto err;
  1233. }
  1234. if (getsockname(sock,(struct sockaddr*)&my_addr, &addr_len)) {
  1235. int e = tor_socket_errno(sock);
  1236. log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s",
  1237. tor_socket_strerror(e));
  1238. goto err;
  1239. }
  1240. tor_addr_from_sockaddr(addr, (struct sockaddr*)&my_addr, NULL);
  1241. r=0;
  1242. err:
  1243. if (sock >= 0)
  1244. tor_close_socket(sock);
  1245. return r;
  1246. }
  1247. /* ======
  1248. * IPv4 helpers
  1249. * XXXX023 IPv6 deprecate some of these.
  1250. */
  1251. /** Return true iff <b>ip</b> (in host order) is an IP reserved to localhost,
  1252. * or reserved for local networks by RFC 1918.
  1253. */
  1254. int
  1255. is_internal_IP(uint32_t ip, int for_listening)
  1256. {
  1257. tor_addr_t myaddr;
  1258. myaddr.family = AF_INET;
  1259. myaddr.addr.in_addr.s_addr = htonl(ip);
  1260. return tor_addr_is_internal(&myaddr, for_listening);
  1261. }
  1262. /** Given an address of the form "host:port", try to divide it into its host
  1263. * ane port portions, setting *<b>address_out</b> to a newly allocated string
  1264. * holding the address portion and *<b>port_out</b> to the port (or 0 if no
  1265. * port is given). Return 0 on success, -1 on failure. */
  1266. int
  1267. tor_addr_port_split(int severity, const char *addrport,
  1268. char **address_out, uint16_t *port_out)
  1269. {
  1270. tor_assert(addrport);
  1271. tor_assert(address_out);
  1272. tor_assert(port_out);
  1273. return addr_port_lookup(severity, addrport, address_out, NULL, port_out);
  1274. }
  1275. /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
  1276. * <b>address</b> is provided, set *<b>address</b> to a copy of the
  1277. * host portion of the string. If <b>addr</b> is provided, try to
  1278. * resolve the host portion of the string and store it into
  1279. * *<b>addr</b> (in host byte order). If <b>port_out</b> is provided,
  1280. * store the port number into *<b>port_out</b>, or 0 if no port is given.
  1281. * If <b>port_out</b> is NULL, then there must be no port number in
  1282. * <b>addrport</b>.
  1283. * Return 0 on success, -1 on failure.
  1284. */
  1285. int
  1286. addr_port_lookup(int severity, const char *addrport, char **address,
  1287. uint32_t *addr, uint16_t *port_out)
  1288. {
  1289. const char *colon;
  1290. char *_address = NULL;
  1291. int _port;
  1292. int ok = 1;
  1293. tor_assert(addrport);
  1294. colon = strrchr(addrport, ':');
  1295. if (colon) {
  1296. _address = tor_strndup(addrport, colon-addrport);
  1297. _port = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
  1298. if (!_port) {
  1299. log_fn(severity, LD_GENERAL, "Port %s out of range", escaped(colon+1));
  1300. ok = 0;
  1301. }
  1302. if (!port_out) {
  1303. char *esc_addrport = esc_for_log(addrport);
  1304. log_fn(severity, LD_GENERAL,
  1305. "Port %s given on %s when not required",
  1306. escaped(colon+1), esc_addrport);
  1307. tor_free(esc_addrport);
  1308. ok = 0;
  1309. }
  1310. } else {
  1311. _address = tor_strdup(addrport);
  1312. _port = 0;
  1313. }
  1314. if (addr) {
  1315. /* There's an addr pointer, so we need to resolve the hostname. */
  1316. if (tor_lookup_hostname(_address,addr)) {
  1317. log_fn(severity, LD_NET, "Couldn't look up %s", escaped(_address));
  1318. ok = 0;
  1319. *addr = 0;
  1320. }
  1321. }
  1322. if (address && ok) {
  1323. *address = _address;
  1324. } else {
  1325. if (address)
  1326. *address = NULL;
  1327. tor_free(_address);
  1328. }
  1329. if (port_out)
  1330. *port_out = ok ? ((uint16_t) _port) : 0;
  1331. return ok ? 0 : -1;
  1332. }
  1333. /** If <b>mask</b> is an address mask for a bit-prefix, return the number of
  1334. * bits. Otherwise, return -1. */
  1335. int
  1336. addr_mask_get_bits(uint32_t mask)
  1337. {
  1338. int i;
  1339. if (mask == 0)
  1340. return 0;
  1341. if (mask == 0xFFFFFFFFu)
  1342. return 32;
  1343. for (i=0; i<=32; ++i) {
  1344. if (mask == (uint32_t) ~((1u<<(32-i))-1)) {
  1345. return i;
  1346. }
  1347. }
  1348. return -1;
  1349. }
  1350. /** Compare two addresses <b>a1</b> and <b>a2</b> for equality under a
  1351. * netmask of <b>mbits</b> bits. Return -1, 0, or 1.
  1352. *
  1353. * XXXX_IP6 Temporary function to allow masks as bitcounts everywhere. This
  1354. * will be replaced with an IPv6-aware version as soon as 32-bit addresses are
  1355. * no longer passed around.
  1356. */
  1357. int
  1358. addr_mask_cmp_bits(uint32_t a1, uint32_t a2, maskbits_t bits)
  1359. {
  1360. if (bits > 32)
  1361. bits = 32;
  1362. else if (bits == 0)
  1363. return 0;
  1364. a1 >>= (32-bits);
  1365. a2 >>= (32-bits);
  1366. if (a1 < a2)
  1367. return -1;
  1368. else if (a1 > a2)
  1369. return 1;
  1370. else
  1371. return 0;
  1372. }
  1373. /** Parse a string <b>s</b> in the format of (*|port(-maxport)?)?, setting the
  1374. * various *out pointers as appropriate. Return 0 on success, -1 on failure.
  1375. */
  1376. int
  1377. parse_port_range(const char *port, uint16_t *port_min_out,
  1378. uint16_t *port_max_out)
  1379. {
  1380. int port_min, port_max, ok;
  1381. tor_assert(port_min_out);
  1382. tor_assert(port_max_out);
  1383. if (!port || *port == '\0' || strcmp(port, "*") == 0) {
  1384. port_min = 1;
  1385. port_max = 65535;
  1386. } else {
  1387. char *endptr = NULL;
  1388. port_min = (int)tor_parse_long(port, 10, 0, 65535, &ok, &endptr);
  1389. if (!ok) {
  1390. log_warn(LD_GENERAL,
  1391. "Malformed port %s on address range; rejecting.",
  1392. escaped(port));
  1393. return -1;
  1394. } else if (endptr && *endptr == '-') {
  1395. port = endptr+1;
  1396. endptr = NULL;
  1397. port_max = (int)tor_parse_long(port, 10, 1, 65536, &ok, &endptr);
  1398. if (!ok) {
  1399. log_warn(LD_GENERAL,
  1400. "Malformed port %s on address range; rejecting.",
  1401. escaped(port));
  1402. return -1;
  1403. }
  1404. } else {
  1405. port_max = port_min;
  1406. }
  1407. if (port_min > port_max) {
  1408. log_warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
  1409. return -1;
  1410. }
  1411. }
  1412. if (port_min < 1)
  1413. port_min = 1;
  1414. if (port_max > 65535)
  1415. port_max = 65535;
  1416. *port_min_out = (uint16_t) port_min;
  1417. *port_max_out = (uint16_t) port_max;
  1418. return 0;
  1419. }
  1420. /** Parse a string <b>s</b> in the format of
  1421. * (IP(/mask|/mask-bits)?|*)(:(*|port(-maxport))?)?, setting the various
  1422. * *out pointers as appropriate. Return 0 on success, -1 on failure.
  1423. */
  1424. int
  1425. parse_addr_and_port_range(const char *s, uint32_t *addr_out,
  1426. maskbits_t *maskbits_out, uint16_t *port_min_out,
  1427. uint16_t *port_max_out)
  1428. {
  1429. char *address;
  1430. char *mask, *port, *endptr;
  1431. struct in_addr in;
  1432. int bits;
  1433. tor_assert(s);
  1434. tor_assert(addr_out);
  1435. tor_assert(maskbits_out);
  1436. tor_assert(port_min_out);
  1437. tor_assert(port_max_out);
  1438. address = tor_strdup(s);
  1439. /* Break 'address' into separate strings.
  1440. */
  1441. mask = strchr(address,'/');
  1442. port = strchr(mask?mask:address,':');
  1443. if (mask)
  1444. *mask++ = '\0';
  1445. if (port)
  1446. *port++ = '\0';
  1447. /* Now "address" is the IP|'*' part...
  1448. * "mask" is the Mask|Maskbits part...
  1449. * and "port" is the *|port|min-max part.
  1450. */
  1451. if (strcmp(address,"*")==0) {
  1452. *addr_out = 0;
  1453. } else if (tor_inet_aton(address, &in) != 0) {
  1454. *addr_out = ntohl(in.s_addr);
  1455. } else {
  1456. log_warn(LD_GENERAL, "Malformed IP %s in address pattern; rejecting.",
  1457. escaped(address));
  1458. goto err;
  1459. }
  1460. if (!mask) {
  1461. if (strcmp(address,"*")==0)
  1462. *maskbits_out = 0;
  1463. else
  1464. *maskbits_out = 32;
  1465. } else {
  1466. endptr = NULL;
  1467. bits = (int) strtol(mask, &endptr, 10);
  1468. if (!*endptr) {
  1469. /* strtol handled the whole mask. */
  1470. if (bits < 0 || bits > 32) {
  1471. log_warn(LD_GENERAL,
  1472. "Bad number of mask bits on address range; rejecting.");
  1473. goto err;
  1474. }
  1475. *maskbits_out = bits;
  1476. } else if (tor_inet_aton(mask, &in) != 0) {
  1477. bits = addr_mask_get_bits(ntohl(in.s_addr));
  1478. if (bits < 0) {
  1479. log_warn(LD_GENERAL,
  1480. "Mask %s on address range isn't a prefix; dropping",
  1481. escaped(mask));
  1482. goto err;
  1483. }
  1484. *maskbits_out = bits;
  1485. } else {
  1486. log_warn(LD_GENERAL,
  1487. "Malformed mask %s on address range; rejecting.",
  1488. escaped(mask));
  1489. goto err;
  1490. }
  1491. }
  1492. if (parse_port_range(port, port_min_out, port_max_out)<0)
  1493. goto err;
  1494. tor_free(address);
  1495. return 0;
  1496. err:
  1497. tor_free(address);
  1498. return -1;
  1499. }
  1500. /** Given an IPv4 in_addr struct *<b>in</b> (in network order, as usual),
  1501. * write it as a string into the <b>buf_len</b>-byte buffer in
  1502. * <b>buf</b>.
  1503. */
  1504. int
  1505. tor_inet_ntoa(const struct in_addr *in, char *buf, size_t buf_len)
  1506. {
  1507. uint32_t a = ntohl(in->s_addr);
  1508. return tor_snprintf(buf, buf_len, "%d.%d.%d.%d",
  1509. (int)(uint8_t)((a>>24)&0xff),
  1510. (int)(uint8_t)((a>>16)&0xff),
  1511. (int)(uint8_t)((a>>8 )&0xff),
  1512. (int)(uint8_t)((a )&0xff));
  1513. }
  1514. /** Given a host-order <b>addr</b>, call tor_inet_ntop() on it
  1515. * and return a strdup of the resulting address.
  1516. */
  1517. char *
  1518. tor_dup_ip(uint32_t addr)
  1519. {
  1520. char buf[TOR_ADDR_BUF_LEN];
  1521. struct in_addr in;
  1522. in.s_addr = htonl(addr);
  1523. tor_inet_ntop(AF_INET, &in, buf, sizeof(buf));
  1524. return tor_strdup(buf);
  1525. }
  1526. /**
  1527. * Set *<b>addr</b> to the host-order IPv4 address (if any) of whatever
  1528. * interface connects to the Internet. This address should only be used in
  1529. * checking whether our address has changed. Return 0 on success, -1 on
  1530. * failure.
  1531. */
  1532. int
  1533. get_interface_address(int severity, uint32_t *addr)
  1534. {
  1535. tor_addr_t local_addr;
  1536. int r;
  1537. r = get_interface_address6(severity, AF_INET, &local_addr);
  1538. if (r>=0)
  1539. *addr = tor_addr_to_ipv4h(&local_addr);
  1540. return r;
  1541. }