address.c 54 KB

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