address.c 49 KB

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