address.c 63 KB

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