address.c 46 KB

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