address.c 59 KB

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