address.c 64 KB

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