address.c 55 KB

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