address.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136
  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
  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
  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
  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 /* endif 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
  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. default:
  841. /* LCOV_EXCL_START */
  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. default:
  953. tor_fragile_assert(); // LCOV_EXCL_LINE
  954. }
  955. }
  956. /** Given two addresses <b>addr1</b> and <b>addr2</b>, return 0 if the two
  957. * addresses are equivalent under the mask mbits, less than 0 if addr1
  958. * precedes addr2, and greater than 0 otherwise.
  959. *
  960. * Different address families (IPv4 vs IPv6) are always considered unequal if
  961. * <b>how</b> is CMP_EXACT; otherwise, IPv6-mapped IPv4 addresses are
  962. * considered equivalent to their IPv4 equivalents.
  963. *
  964. * As a special case, all pointer-wise distinct AF_UNIX addresses are always
  965. * considered unequal since tor_addr_t currently does not contain the
  966. * information required to make the comparison.
  967. */
  968. int
  969. tor_addr_compare(const tor_addr_t *addr1, const tor_addr_t *addr2,
  970. tor_addr_comparison_t how)
  971. {
  972. return tor_addr_compare_masked(addr1, addr2, 128, how);
  973. }
  974. /** As tor_addr_compare(), but only looks at the first <b>mask</b> bits of
  975. * the address.
  976. *
  977. * Reduce over-specific masks (>128 for ipv6, >32 for ipv4) to 128 or 32.
  978. *
  979. * The mask is interpreted relative to <b>addr1</b>, so that if a is
  980. * \::ffff:1.2.3.4, and b is 3.4.5.6,
  981. * tor_addr_compare_masked(a,b,100,CMP_SEMANTIC) is the same as
  982. * -tor_addr_compare_masked(b,a,4,CMP_SEMANTIC).
  983. *
  984. * We guarantee that the ordering from tor_addr_compare_masked is a total
  985. * order on addresses, but not that it is any particular order, or that it
  986. * will be the same from one version to the next.
  987. */
  988. int
  989. tor_addr_compare_masked(const tor_addr_t *addr1, const tor_addr_t *addr2,
  990. maskbits_t mbits, tor_addr_comparison_t how)
  991. {
  992. /** Helper: Evaluates to -1 if a is less than b, 0 if a equals b, or 1 if a
  993. * is greater than b. May evaluate a and b more than once. */
  994. #define TRISTATE(a,b) (((a)<(b))?-1: (((a)==(b))?0:1))
  995. sa_family_t family1, family2, v_family1, v_family2;
  996. tor_assert(addr1 && addr2);
  997. v_family1 = family1 = tor_addr_family(addr1);
  998. v_family2 = family2 = tor_addr_family(addr2);
  999. if (family1==family2) {
  1000. /* When the families are the same, there's only one way to do the
  1001. * comparison: exactly. */
  1002. int r;
  1003. switch (family1) {
  1004. case AF_UNSPEC:
  1005. return 0; /* All unspecified addresses are equal */
  1006. case AF_INET: {
  1007. uint32_t a1 = tor_addr_to_ipv4h(addr1);
  1008. uint32_t a2 = tor_addr_to_ipv4h(addr2);
  1009. if (mbits <= 0)
  1010. return 0;
  1011. if (mbits > 32)
  1012. mbits = 32;
  1013. a1 >>= (32-mbits);
  1014. a2 >>= (32-mbits);
  1015. r = TRISTATE(a1, a2);
  1016. return r;
  1017. }
  1018. case AF_INET6: {
  1019. if (mbits > 128)
  1020. mbits = 128;
  1021. const uint8_t *a1 = tor_addr_to_in6_addr8(addr1);
  1022. const uint8_t *a2 = tor_addr_to_in6_addr8(addr2);
  1023. const int bytes = mbits >> 3;
  1024. const int leftover_bits = mbits & 7;
  1025. if (bytes && (r = tor_memcmp(a1, a2, bytes))) {
  1026. return r;
  1027. } else if (leftover_bits) {
  1028. uint8_t b1 = a1[bytes] >> (8-leftover_bits);
  1029. uint8_t b2 = a2[bytes] >> (8-leftover_bits);
  1030. return TRISTATE(b1, b2);
  1031. } else {
  1032. return 0;
  1033. }
  1034. }
  1035. case AF_UNIX:
  1036. /* HACKHACKHACKHACKHACK:
  1037. * tor_addr_t doesn't contain a copy of sun_path, so it's not
  1038. * possible to comapre this at all.
  1039. *
  1040. * Since the only time we currently actually should be comparing
  1041. * 2 AF_UNIX addresses is when dealing with ISO_CLIENTADDR (which
  1042. * is disabled for AF_UNIX SocksPorts anyway), this just does
  1043. * a pointer comparison.
  1044. *
  1045. * See: #20261.
  1046. */
  1047. if (addr1 < addr2)
  1048. return -1;
  1049. else if (addr1 == addr2)
  1050. return 0;
  1051. else
  1052. return 1;
  1053. default:
  1054. /* LCOV_EXCL_START */
  1055. tor_fragile_assert();
  1056. return 0;
  1057. /* LCOV_EXCL_STOP */
  1058. }
  1059. } else if (how == CMP_EXACT) {
  1060. /* Unequal families and an exact comparison? Stop now! */
  1061. return TRISTATE(family1, family2);
  1062. }
  1063. if (mbits == 0)
  1064. return 0;
  1065. if (family1 == AF_INET6 && tor_addr_is_v4(addr1))
  1066. v_family1 = AF_INET;
  1067. if (family2 == AF_INET6 && tor_addr_is_v4(addr2))
  1068. v_family2 = AF_INET;
  1069. if (v_family1 == v_family2) {
  1070. /* One or both addresses are a mapped ipv4 address. */
  1071. uint32_t a1, a2;
  1072. if (family1 == AF_INET6) {
  1073. a1 = tor_addr_to_mapped_ipv4h(addr1);
  1074. if (mbits <= 96)
  1075. return 0;
  1076. mbits -= 96; /* We just decided that the first 96 bits of a1 "match". */
  1077. } else {
  1078. a1 = tor_addr_to_ipv4h(addr1);
  1079. }
  1080. if (family2 == AF_INET6) {
  1081. a2 = tor_addr_to_mapped_ipv4h(addr2);
  1082. } else {
  1083. a2 = tor_addr_to_ipv4h(addr2);
  1084. }
  1085. if (mbits > 32) mbits = 32;
  1086. a1 >>= (32-mbits);
  1087. a2 >>= (32-mbits);
  1088. return TRISTATE(a1, a2);
  1089. } else {
  1090. /* Unequal families, and semantic comparison, and no semantic family
  1091. * matches. */
  1092. return TRISTATE(family1, family2);
  1093. }
  1094. }
  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 0x4e4d5342;
  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_STOP */
  1111. }
  1112. }
  1113. /** Return a newly allocated string with a representation of <b>addr</b>. */
  1114. char *
  1115. tor_addr_to_str_dup(const tor_addr_t *addr)
  1116. {
  1117. char buf[TOR_ADDR_BUF_LEN];
  1118. if (tor_addr_to_str(buf, addr, sizeof(buf), 0)) {
  1119. return tor_strdup(buf);
  1120. } else {
  1121. return tor_strdup("<unknown address type>");
  1122. }
  1123. }
  1124. /** Return a string representing the address <b>addr</b>. This string
  1125. * is statically allocated, and must not be freed. Each call to
  1126. * <b>fmt_addr_impl</b> invalidates the last result of the function.
  1127. * This function is not thread-safe. If <b>decorate</b> is set, add
  1128. * brackets to IPv6 addresses.
  1129. *
  1130. * It's better to use the wrapper macros of this function:
  1131. * <b>fmt_addr()</b> and <b>fmt_and_decorate_addr()</b>.
  1132. */
  1133. const char *
  1134. fmt_addr_impl(const tor_addr_t *addr, int decorate)
  1135. {
  1136. static char buf[TOR_ADDR_BUF_LEN];
  1137. if (!addr) return "<null>";
  1138. if (tor_addr_to_str(buf, addr, sizeof(buf), decorate))
  1139. return buf;
  1140. else
  1141. return "???";
  1142. }
  1143. /** Return a string representing the pair <b>addr</b> and <b>port</b>.
  1144. * This calls fmt_and_decorate_addr internally, so IPv6 addresses will
  1145. * have brackets, and the caveats of fmt_addr_impl apply.
  1146. */
  1147. const char *
  1148. fmt_addrport(const tor_addr_t *addr, uint16_t port)
  1149. {
  1150. /* Add space for a colon and up to 5 digits. */
  1151. static char buf[TOR_ADDR_BUF_LEN + 6];
  1152. tor_snprintf(buf, sizeof(buf), "%s:%u", fmt_and_decorate_addr(addr), port);
  1153. return buf;
  1154. }
  1155. /** Like fmt_addr(), but takes <b>addr</b> as a host-order IPv4
  1156. * addresses. Also not thread-safe, also clobbers its return buffer on
  1157. * repeated calls. */
  1158. const char *
  1159. fmt_addr32(uint32_t addr)
  1160. {
  1161. static char buf[INET_NTOA_BUF_LEN];
  1162. struct in_addr in;
  1163. in.s_addr = htonl(addr);
  1164. tor_inet_ntoa(&in, buf, sizeof(buf));
  1165. return buf;
  1166. }
  1167. /** Convert the string in <b>src</b> to a tor_addr_t <b>addr</b>. The string
  1168. * may be an IPv4 address, an IPv6 address, or an IPv6 address surrounded by
  1169. * square brackets.
  1170. *
  1171. * Return an address family on success, or -1 if an invalid address string is
  1172. * provided. */
  1173. int
  1174. tor_addr_parse(tor_addr_t *addr, const char *src)
  1175. {
  1176. /* Holds substring of IPv6 address after removing square brackets */
  1177. char *tmp = NULL;
  1178. int result;
  1179. struct in_addr in_tmp;
  1180. struct in6_addr in6_tmp;
  1181. tor_assert(addr && src);
  1182. if (src[0] == '[' && src[1])
  1183. src = tmp = tor_strndup(src+1, strlen(src)-2);
  1184. if (tor_inet_pton(AF_INET6, src, &in6_tmp) > 0) {
  1185. result = AF_INET6;
  1186. tor_addr_from_in6(addr, &in6_tmp);
  1187. } else if (tor_inet_pton(AF_INET, src, &in_tmp) > 0) {
  1188. result = AF_INET;
  1189. tor_addr_from_in(addr, &in_tmp);
  1190. } else {
  1191. result = -1;
  1192. }
  1193. tor_free(tmp);
  1194. return result;
  1195. }
  1196. /** Parse an address or address-port combination from <b>s</b>, resolve the
  1197. * address as needed, and put the result in <b>addr_out</b> and (optionally)
  1198. * <b>port_out</b>. Return 0 on success, negative on failure. */
  1199. int
  1200. tor_addr_port_lookup(const char *s, tor_addr_t *addr_out, uint16_t *port_out)
  1201. {
  1202. const char *port;
  1203. tor_addr_t addr;
  1204. uint16_t portval;
  1205. char *tmp = NULL;
  1206. tor_assert(s);
  1207. tor_assert(addr_out);
  1208. s = eat_whitespace(s);
  1209. if (*s == '[') {
  1210. port = strstr(s, "]");
  1211. if (!port)
  1212. goto err;
  1213. tmp = tor_strndup(s+1, port-(s+1));
  1214. port = port+1;
  1215. if (*port == ':')
  1216. port++;
  1217. else
  1218. port = NULL;
  1219. } else {
  1220. port = strchr(s, ':');
  1221. if (port)
  1222. tmp = tor_strndup(s, port-s);
  1223. else
  1224. tmp = tor_strdup(s);
  1225. if (port)
  1226. ++port;
  1227. }
  1228. if (tor_addr_lookup(tmp, AF_UNSPEC, &addr) != 0)
  1229. goto err;
  1230. tor_free(tmp);
  1231. if (port) {
  1232. portval = (int) tor_parse_long(port, 10, 1, 65535, NULL, NULL);
  1233. if (!portval)
  1234. goto err;
  1235. } else {
  1236. portval = 0;
  1237. }
  1238. if (port_out)
  1239. *port_out = portval;
  1240. tor_addr_copy(addr_out, &addr);
  1241. return 0;
  1242. err:
  1243. tor_free(tmp);
  1244. return -1;
  1245. }
  1246. #ifdef _WIN32
  1247. typedef ULONG (WINAPI *GetAdaptersAddresses_fn_t)(
  1248. ULONG, ULONG, PVOID, PIP_ADAPTER_ADDRESSES, PULONG);
  1249. #endif
  1250. #ifdef HAVE_IFADDRS_TO_SMARTLIST
  1251. /*
  1252. * Convert a linked list consisting of <b>ifaddrs</b> structures
  1253. * into smartlist of <b>tor_addr_t</b> structures.
  1254. */
  1255. STATIC smartlist_t *
  1256. ifaddrs_to_smartlist(const struct ifaddrs *ifa, sa_family_t family)
  1257. {
  1258. smartlist_t *result = smartlist_new();
  1259. const struct ifaddrs *i;
  1260. for (i = ifa; i; i = i->ifa_next) {
  1261. tor_addr_t tmp;
  1262. if ((i->ifa_flags & (IFF_UP | IFF_RUNNING)) != (IFF_UP | IFF_RUNNING))
  1263. continue;
  1264. if (!i->ifa_addr)
  1265. continue;
  1266. if (i->ifa_addr->sa_family != AF_INET &&
  1267. i->ifa_addr->sa_family != AF_INET6)
  1268. continue;
  1269. if (family != AF_UNSPEC && i->ifa_addr->sa_family != family)
  1270. continue;
  1271. if (tor_addr_from_sockaddr(&tmp, i->ifa_addr, NULL) < 0)
  1272. continue;
  1273. smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
  1274. }
  1275. return result;
  1276. }
  1277. /** Use getiffaddrs() function to get list of current machine
  1278. * network interface addresses. Represent the result by smartlist of
  1279. * <b>tor_addr_t</b> structures.
  1280. */
  1281. STATIC smartlist_t *
  1282. get_interface_addresses_ifaddrs(int severity, sa_family_t family)
  1283. {
  1284. /* Most free Unixy systems provide getifaddrs, which gives us a linked list
  1285. * of struct ifaddrs. */
  1286. struct ifaddrs *ifa = NULL;
  1287. smartlist_t *result;
  1288. if (getifaddrs(&ifa) < 0) {
  1289. log_fn(severity, LD_NET, "Unable to call getifaddrs(): %s",
  1290. strerror(errno));
  1291. return NULL;
  1292. }
  1293. result = ifaddrs_to_smartlist(ifa, family);
  1294. freeifaddrs(ifa);
  1295. return result;
  1296. }
  1297. #endif
  1298. #ifdef HAVE_IP_ADAPTER_TO_SMARTLIST
  1299. /** Convert a Windows-specific <b>addresses</b> linked list into smartlist
  1300. * of <b>tor_addr_t</b> structures.
  1301. */
  1302. STATIC smartlist_t *
  1303. ip_adapter_addresses_to_smartlist(const IP_ADAPTER_ADDRESSES *addresses)
  1304. {
  1305. smartlist_t *result = smartlist_new();
  1306. const IP_ADAPTER_ADDRESSES *address;
  1307. for (address = addresses; address; address = address->Next) {
  1308. const IP_ADAPTER_UNICAST_ADDRESS *a;
  1309. for (a = address->FirstUnicastAddress; a; a = a->Next) {
  1310. /* Yes, it's a linked list inside a linked list */
  1311. const struct sockaddr *sa = a->Address.lpSockaddr;
  1312. tor_addr_t tmp;
  1313. if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6)
  1314. continue;
  1315. if (tor_addr_from_sockaddr(&tmp, sa, NULL) < 0)
  1316. continue;
  1317. smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
  1318. }
  1319. }
  1320. return result;
  1321. }
  1322. /** Windows only: use GetAdaptersInfo() function to retrieve network interface
  1323. * addresses of current machine and return them to caller as smartlist of
  1324. * <b>tor_addr_t</b> structures.
  1325. */
  1326. STATIC smartlist_t *
  1327. get_interface_addresses_win32(int severity, sa_family_t family)
  1328. {
  1329. /* Windows XP began to provide GetAdaptersAddresses. Windows 2000 had a
  1330. "GetAdaptersInfo", but that's deprecated; let's just try
  1331. GetAdaptersAddresses and fall back to connect+getsockname.
  1332. */
  1333. HANDLE lib = load_windows_system_library(TEXT("iphlpapi.dll"));
  1334. smartlist_t *result = NULL;
  1335. GetAdaptersAddresses_fn_t fn;
  1336. ULONG size, res;
  1337. IP_ADAPTER_ADDRESSES *addresses = NULL;
  1338. (void) severity;
  1339. #define FLAGS (GAA_FLAG_SKIP_ANYCAST | \
  1340. GAA_FLAG_SKIP_MULTICAST | \
  1341. GAA_FLAG_SKIP_DNS_SERVER)
  1342. if (!lib) {
  1343. log_fn(severity, LD_NET, "Unable to load iphlpapi.dll");
  1344. goto done;
  1345. }
  1346. if (!(fn = (GetAdaptersAddresses_fn_t)
  1347. GetProcAddress(lib, "GetAdaptersAddresses"))) {
  1348. log_fn(severity, LD_NET, "Unable to obtain pointer to "
  1349. "GetAdaptersAddresses");
  1350. goto done;
  1351. }
  1352. /* Guess how much space we need. */
  1353. size = 15*1024;
  1354. addresses = tor_malloc(size);
  1355. res = fn(family, FLAGS, NULL, addresses, &size);
  1356. if (res == ERROR_BUFFER_OVERFLOW) {
  1357. /* we didn't guess that we needed enough space; try again */
  1358. tor_free(addresses);
  1359. addresses = tor_malloc(size);
  1360. res = fn(AF_UNSPEC, FLAGS, NULL, addresses, &size);
  1361. }
  1362. if (res != NO_ERROR) {
  1363. log_fn(severity, LD_NET, "GetAdaptersAddresses failed (result: %lu)", res);
  1364. goto done;
  1365. }
  1366. result = ip_adapter_addresses_to_smartlist(addresses);
  1367. done:
  1368. if (lib)
  1369. FreeLibrary(lib);
  1370. tor_free(addresses);
  1371. return result;
  1372. }
  1373. #endif
  1374. #ifdef HAVE_IFCONF_TO_SMARTLIST
  1375. /* Guess how much space we need. There shouldn't be any struct ifreqs
  1376. * larger than this, even on OS X where the struct's size is dynamic. */
  1377. #define IFREQ_SIZE 4096
  1378. /* This is defined on Mac OS X */
  1379. #ifndef _SIZEOF_ADDR_IFREQ
  1380. #define _SIZEOF_ADDR_IFREQ sizeof
  1381. #endif
  1382. /** Convert <b>*buf</b>, an ifreq structure array of size <b>buflen</b>,
  1383. * into smartlist of <b>tor_addr_t</b> structures.
  1384. */
  1385. STATIC smartlist_t *
  1386. ifreq_to_smartlist(char *buf, size_t buflen)
  1387. {
  1388. smartlist_t *result = smartlist_new();
  1389. char *end = buf + buflen;
  1390. /* These acrobatics are due to alignment issues which trigger
  1391. * undefined behaviour traps on OSX. */
  1392. struct ifreq *r = tor_malloc(IFREQ_SIZE);
  1393. while (buf < end) {
  1394. /* Copy up to IFREQ_SIZE bytes into the struct ifreq, but don't overrun
  1395. * buf. */
  1396. memcpy(r, buf, end - buf < IFREQ_SIZE ? end - buf : IFREQ_SIZE);
  1397. const struct sockaddr *sa = &r->ifr_addr;
  1398. tor_addr_t tmp;
  1399. int valid_sa_family = (sa->sa_family == AF_INET ||
  1400. sa->sa_family == AF_INET6);
  1401. int conversion_success = (tor_addr_from_sockaddr(&tmp, sa, NULL) == 0);
  1402. if (valid_sa_family && conversion_success)
  1403. smartlist_add(result, tor_memdup(&tmp, sizeof(tmp)));
  1404. buf += _SIZEOF_ADDR_IFREQ(*r);
  1405. }
  1406. tor_free(r);
  1407. return result;
  1408. }
  1409. /** Use ioctl(.,SIOCGIFCONF,.) to get a list of current machine
  1410. * network interface addresses. Represent the result by smartlist of
  1411. * <b>tor_addr_t</b> structures.
  1412. */
  1413. STATIC smartlist_t *
  1414. get_interface_addresses_ioctl(int severity, sa_family_t family)
  1415. {
  1416. /* Some older unixy systems make us use ioctl(SIOCGIFCONF) */
  1417. struct ifconf ifc;
  1418. ifc.ifc_buf = NULL;
  1419. int fd;
  1420. smartlist_t *result = NULL;
  1421. /* This interface, AFAICT, only supports AF_INET addresses,
  1422. * except on AIX. For Solaris, we could use SIOCGLIFCONF. */
  1423. /* Bail out if family is neither AF_INET nor AF_UNSPEC since
  1424. * ioctl() technique supports non-IPv4 interface addresses on
  1425. * a small number of niche systems only. If family is AF_UNSPEC,
  1426. * fall back to getting AF_INET addresses only. */
  1427. if (family == AF_UNSPEC)
  1428. family = AF_INET;
  1429. else if (family != AF_INET)
  1430. return NULL;
  1431. fd = socket(family, SOCK_DGRAM, 0);
  1432. if (fd < 0) {
  1433. tor_log(severity, LD_NET, "socket failed: %s", strerror(errno));
  1434. goto done;
  1435. }
  1436. int mult = 1;
  1437. do {
  1438. mult *= 2;
  1439. ifc.ifc_len = mult * IFREQ_SIZE;
  1440. ifc.ifc_buf = tor_realloc(ifc.ifc_buf, ifc.ifc_len);
  1441. tor_assert(ifc.ifc_buf);
  1442. if (ioctl(fd, SIOCGIFCONF, &ifc) < 0) {
  1443. tor_log(severity, LD_NET, "ioctl failed: %s", strerror(errno));
  1444. goto done;
  1445. }
  1446. /* Ensure we have least IFREQ_SIZE bytes unused at the end. Otherwise, we
  1447. * don't know if we got everything during ioctl. */
  1448. } while (mult * IFREQ_SIZE - ifc.ifc_len <= IFREQ_SIZE);
  1449. result = ifreq_to_smartlist(ifc.ifc_buf, ifc.ifc_len);
  1450. done:
  1451. if (fd >= 0)
  1452. close(fd);
  1453. tor_free(ifc.ifc_buf);
  1454. return result;
  1455. }
  1456. #endif
  1457. /** Try to ask our network interfaces what addresses they are bound to.
  1458. * Return a new smartlist of tor_addr_t on success, and NULL on failure.
  1459. * (An empty smartlist indicates that we successfully learned that we have no
  1460. * addresses.) Log failure messages at <b>severity</b>. Only return the
  1461. * interface addresses of requested <b>family</b> and ignore the addresses
  1462. * of other address families. */
  1463. MOCK_IMPL(smartlist_t *,
  1464. get_interface_addresses_raw,(int severity, sa_family_t family))
  1465. {
  1466. smartlist_t *result = NULL;
  1467. #if defined(HAVE_IFADDRS_TO_SMARTLIST)
  1468. if ((result = get_interface_addresses_ifaddrs(severity, family)))
  1469. return result;
  1470. #endif
  1471. #if defined(HAVE_IP_ADAPTER_TO_SMARTLIST)
  1472. if ((result = get_interface_addresses_win32(severity, family)))
  1473. return result;
  1474. #endif
  1475. #if defined(HAVE_IFCONF_TO_SMARTLIST)
  1476. if ((result = get_interface_addresses_ioctl(severity, family)))
  1477. return result;
  1478. #endif
  1479. (void) severity;
  1480. (void) result;
  1481. return NULL;
  1482. }
  1483. /** Return true iff <b>a</b> is a multicast address. */
  1484. int
  1485. tor_addr_is_multicast(const tor_addr_t *a)
  1486. {
  1487. sa_family_t family = tor_addr_family(a);
  1488. if (family == AF_INET) {
  1489. uint32_t ipv4h = tor_addr_to_ipv4h(a);
  1490. if ((ipv4h >> 24) == 0xe0)
  1491. return 1; /* Multicast */
  1492. } else if (family == AF_INET6) {
  1493. const uint8_t *a32 = tor_addr_to_in6_addr8(a);
  1494. if (a32[0] == 0xff)
  1495. return 1;
  1496. }
  1497. return 0;
  1498. }
  1499. /** Attempt to retrieve IP address of current host by utilizing some
  1500. * UDP socket trickery. Only look for address of given <b>family</b>
  1501. * (only AF_INET and AF_INET6 are supported). Set result to *<b>addr</b>.
  1502. * Return 0 on success, -1 on failure.
  1503. */
  1504. MOCK_IMPL(int,
  1505. get_interface_address6_via_udp_socket_hack,(int severity,
  1506. sa_family_t family,
  1507. tor_addr_t *addr))
  1508. {
  1509. struct sockaddr_storage my_addr, target_addr;
  1510. int sock=-1, r=-1;
  1511. socklen_t addr_len;
  1512. memset(addr, 0, sizeof(tor_addr_t));
  1513. memset(&target_addr, 0, sizeof(target_addr));
  1514. /* Don't worry: no packets are sent. We just need to use a real address
  1515. * on the actual Internet. */
  1516. if (family == AF_INET6) {
  1517. struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&target_addr;
  1518. /* Use the "discard" service port */
  1519. sin6->sin6_port = htons(9);
  1520. sock = tor_open_socket(PF_INET6,SOCK_DGRAM,IPPROTO_UDP);
  1521. addr_len = (socklen_t)sizeof(struct sockaddr_in6);
  1522. sin6->sin6_family = AF_INET6;
  1523. S6_ADDR16(sin6->sin6_addr)[0] = htons(0x2002); /* 2002:: */
  1524. } else if (family == AF_INET) {
  1525. struct sockaddr_in *sin = (struct sockaddr_in*)&target_addr;
  1526. /* Use the "discard" service port */
  1527. sin->sin_port = htons(9);
  1528. sock = tor_open_socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);
  1529. addr_len = (socklen_t)sizeof(struct sockaddr_in);
  1530. sin->sin_family = AF_INET;
  1531. sin->sin_addr.s_addr = htonl(0x12000001); /* 18.0.0.1 */
  1532. } else {
  1533. return -1;
  1534. }
  1535. if (sock < 0) {
  1536. int e = tor_socket_errno(-1);
  1537. log_fn(severity, LD_NET, "unable to create socket: %s",
  1538. tor_socket_strerror(e));
  1539. goto err;
  1540. }
  1541. if (tor_connect_socket(sock,(struct sockaddr *)&target_addr,
  1542. addr_len) < 0) {
  1543. int e = tor_socket_errno(sock);
  1544. log_fn(severity, LD_NET, "connect() failed: %s", tor_socket_strerror(e));
  1545. goto err;
  1546. }
  1547. if (tor_getsockname(sock,(struct sockaddr*)&my_addr, &addr_len)) {
  1548. int e = tor_socket_errno(sock);
  1549. log_fn(severity, LD_NET, "getsockname() to determine interface failed: %s",
  1550. tor_socket_strerror(e));
  1551. goto err;
  1552. }
  1553. if (tor_addr_from_sockaddr(addr, (struct sockaddr*)&my_addr, NULL) == 0) {
  1554. if (tor_addr_is_loopback(addr) || tor_addr_is_multicast(addr)) {
  1555. log_fn(severity, LD_NET, "Address that we determined via UDP socket"
  1556. " magic is unsuitable for public comms.");
  1557. } else {
  1558. r=0;
  1559. }
  1560. }
  1561. err:
  1562. if (sock >= 0)
  1563. tor_close_socket(sock);
  1564. if (r == -1)
  1565. memset(addr, 0, sizeof(tor_addr_t));
  1566. return r;
  1567. }
  1568. /** Set *<b>addr</b> to an arbitrary IP address (if any) of an interface that
  1569. * connects to the Internet. Prefer public IP addresses to internal IP
  1570. * addresses. This address should only be used in checking whether our
  1571. * address has changed, as it may be an internal IP address. Return 0 on
  1572. * success, -1 on failure.
  1573. * Prefer get_interface_address6_list for a list of all addresses on all
  1574. * interfaces which connect to the Internet.
  1575. */
  1576. MOCK_IMPL(int,
  1577. get_interface_address6,(int severity, sa_family_t family, tor_addr_t *addr))
  1578. {
  1579. smartlist_t *addrs;
  1580. int rv = -1;
  1581. tor_assert(addr);
  1582. memset(addr, 0, sizeof(tor_addr_t));
  1583. /* Get a list of public or internal IPs in arbitrary order */
  1584. addrs = get_interface_address6_list(severity, family, 1);
  1585. /* Find the first non-internal address, or the last internal address
  1586. * Ideally, we want the default route, see #12377 for details */
  1587. SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a) {
  1588. tor_addr_copy(addr, a);
  1589. rv = 0;
  1590. /* If we found a non-internal address, declare success. Otherwise,
  1591. * keep looking. */
  1592. if (!tor_addr_is_internal(a, 0))
  1593. break;
  1594. } SMARTLIST_FOREACH_END(a);
  1595. free_interface_address6_list(addrs);
  1596. return rv;
  1597. }
  1598. /** Free a smartlist of IP addresses returned by get_interface_address6_list.
  1599. */
  1600. void
  1601. free_interface_address6_list(smartlist_t *addrs)
  1602. {
  1603. if (addrs != NULL) {
  1604. SMARTLIST_FOREACH(addrs, tor_addr_t *, a, tor_free(a));
  1605. smartlist_free(addrs);
  1606. }
  1607. }
  1608. /** Return a smartlist of the IP addresses of type family from all interfaces
  1609. * on the server. Excludes loopback and multicast addresses. Only includes
  1610. * internal addresses if include_internal is true. (Note that a relay behind
  1611. * NAT may use an internal address to connect to the Internet.)
  1612. * An empty smartlist means that there are no addresses of the selected type
  1613. * matching these criteria.
  1614. * Returns NULL on failure.
  1615. * Use free_interface_address6_list to free the returned list.
  1616. */
  1617. MOCK_IMPL(smartlist_t *,
  1618. get_interface_address6_list,(int severity,
  1619. sa_family_t family,
  1620. int include_internal))
  1621. {
  1622. smartlist_t *addrs;
  1623. tor_addr_t addr;
  1624. /* Try to do this the smart way if possible. */
  1625. if ((addrs = get_interface_addresses_raw(severity, family))) {
  1626. SMARTLIST_FOREACH_BEGIN(addrs, tor_addr_t *, a)
  1627. {
  1628. if (tor_addr_is_loopback(a) ||
  1629. tor_addr_is_multicast(a)) {
  1630. SMARTLIST_DEL_CURRENT_KEEPORDER(addrs, a);
  1631. tor_free(a);
  1632. continue;
  1633. }
  1634. if (!include_internal && tor_addr_is_internal(a, 0)) {
  1635. SMARTLIST_DEL_CURRENT_KEEPORDER(addrs, a);
  1636. tor_free(a);
  1637. continue;
  1638. }
  1639. } SMARTLIST_FOREACH_END(a);
  1640. }
  1641. if (addrs && smartlist_len(addrs) > 0) {
  1642. return addrs;
  1643. }
  1644. /* if we removed all entries as unsuitable */
  1645. if (addrs) {
  1646. smartlist_free(addrs);
  1647. }
  1648. /* Okay, the smart way is out. */
  1649. addrs = smartlist_new();
  1650. if (family == AF_INET || family == AF_UNSPEC) {
  1651. if (get_interface_address6_via_udp_socket_hack(severity,AF_INET,
  1652. &addr) == 0) {
  1653. if (include_internal || !tor_addr_is_internal(&addr, 0)) {
  1654. smartlist_add(addrs, tor_memdup(&addr, sizeof(addr)));
  1655. }
  1656. }
  1657. }
  1658. if (family == AF_INET6 || family == AF_UNSPEC) {
  1659. if (get_interface_address6_via_udp_socket_hack(severity,AF_INET6,
  1660. &addr) == 0) {
  1661. if (include_internal || !tor_addr_is_internal(&addr, 0)) {
  1662. smartlist_add(addrs, tor_memdup(&addr, sizeof(addr)));
  1663. }
  1664. }
  1665. }
  1666. return addrs;
  1667. }
  1668. /* ======
  1669. * IPv4 helpers
  1670. * XXXX IPv6 deprecate some of these.
  1671. */
  1672. /** Given an address of the form "ip:port", try to divide it into its
  1673. * ip and port portions, setting *<b>address_out</b> to a newly
  1674. * allocated string holding the address portion and *<b>port_out</b>
  1675. * to the port.
  1676. *
  1677. * Don't do DNS lookups and don't allow domain names in the "ip" field.
  1678. *
  1679. * If <b>default_port</b> is less than 0, don't accept <b>addrport</b> of the
  1680. * form "ip" or "ip:0". Otherwise, accept those forms, and set
  1681. * *<b>port_out</b> to <b>default_port</b>.
  1682. *
  1683. * Return 0 on success, -1 on failure. */
  1684. int
  1685. tor_addr_port_parse(int severity, const char *addrport,
  1686. tor_addr_t *address_out, uint16_t *port_out,
  1687. int default_port)
  1688. {
  1689. int retval = -1;
  1690. int r;
  1691. char *addr_tmp = NULL;
  1692. tor_assert(addrport);
  1693. tor_assert(address_out);
  1694. tor_assert(port_out);
  1695. r = tor_addr_port_split(severity, addrport, &addr_tmp, port_out);
  1696. if (r < 0)
  1697. goto done;
  1698. if (!*port_out) {
  1699. if (default_port >= 0)
  1700. *port_out = default_port;
  1701. else
  1702. goto done;
  1703. }
  1704. /* make sure that address_out is an IP address */
  1705. if (tor_addr_parse(address_out, addr_tmp) < 0)
  1706. goto done;
  1707. retval = 0;
  1708. done:
  1709. tor_free(addr_tmp);
  1710. return retval;
  1711. }
  1712. /** Given an address of the form "host[:port]", try to divide it into its host
  1713. * and port portions, setting *<b>address_out</b> to a newly allocated string
  1714. * holding the address portion and *<b>port_out</b> to the port (or 0 if no
  1715. * port is given). Return 0 on success, -1 on failure. */
  1716. int
  1717. tor_addr_port_split(int severity, const char *addrport,
  1718. char **address_out, uint16_t *port_out)
  1719. {
  1720. tor_addr_t a_tmp;
  1721. tor_assert(addrport);
  1722. tor_assert(address_out);
  1723. tor_assert(port_out);
  1724. /* We need to check for IPv6 manually because addr_port_lookup() doesn't
  1725. * do a good job on IPv6 addresses that lack a port. */
  1726. if (tor_addr_parse(&a_tmp, addrport) == AF_INET6) {
  1727. *port_out = 0;
  1728. *address_out = tor_strdup(addrport);
  1729. return 0;
  1730. }
  1731. return addr_port_lookup(severity, addrport, address_out, NULL, port_out);
  1732. }
  1733. /** Parse a string of the form "host[:port]" from <b>addrport</b>. If
  1734. * <b>address</b> is provided, set *<b>address</b> to a copy of the
  1735. * host portion of the string. If <b>addr</b> is provided, try to
  1736. * resolve the host portion of the string and store it into
  1737. * *<b>addr</b> (in host byte order). If <b>port_out</b> is provided,
  1738. * store the port number into *<b>port_out</b>, or 0 if no port is given.
  1739. * If <b>port_out</b> is NULL, then there must be no port number in
  1740. * <b>addrport</b>.
  1741. * Return 0 on success, -1 on failure.
  1742. */
  1743. int
  1744. addr_port_lookup(int severity, const char *addrport, char **address,
  1745. uint32_t *addr, uint16_t *port_out)
  1746. {
  1747. const char *colon;
  1748. char *address_ = NULL;
  1749. int port_;
  1750. int ok = 1;
  1751. tor_assert(addrport);
  1752. colon = strrchr(addrport, ':');
  1753. if (colon) {
  1754. address_ = tor_strndup(addrport, colon-addrport);
  1755. port_ = (int) tor_parse_long(colon+1,10,1,65535,NULL,NULL);
  1756. if (!port_) {
  1757. log_fn(severity, LD_GENERAL, "Port %s out of range", escaped(colon+1));
  1758. ok = 0;
  1759. }
  1760. if (!port_out) {
  1761. char *esc_addrport = esc_for_log(addrport);
  1762. log_fn(severity, LD_GENERAL,
  1763. "Port %s given on %s when not required",
  1764. escaped(colon+1), esc_addrport);
  1765. tor_free(esc_addrport);
  1766. ok = 0;
  1767. }
  1768. } else {
  1769. address_ = tor_strdup(addrport);
  1770. port_ = 0;
  1771. }
  1772. if (addr) {
  1773. /* There's an addr pointer, so we need to resolve the hostname. */
  1774. if (tor_lookup_hostname(address_,addr)) {
  1775. log_fn(severity, LD_NET, "Couldn't look up %s", escaped(address_));
  1776. ok = 0;
  1777. *addr = 0;
  1778. }
  1779. }
  1780. if (address && ok) {
  1781. *address = address_;
  1782. } else {
  1783. if (address)
  1784. *address = NULL;
  1785. tor_free(address_);
  1786. }
  1787. if (port_out)
  1788. *port_out = ok ? ((uint16_t) port_) : 0;
  1789. return ok ? 0 : -1;
  1790. }
  1791. /** If <b>mask</b> is an address mask for a bit-prefix, return the number of
  1792. * bits. Otherwise, return -1. */
  1793. int
  1794. addr_mask_get_bits(uint32_t mask)
  1795. {
  1796. int i;
  1797. if (mask == 0)
  1798. return 0;
  1799. if (mask == 0xFFFFFFFFu)
  1800. return 32;
  1801. for (i=1; i<=32; ++i) {
  1802. if (mask == (uint32_t) ~((1u<<(32-i))-1)) {
  1803. return i;
  1804. }
  1805. }
  1806. return -1;
  1807. }
  1808. /** Parse a string <b>s</b> in the format of (*|port(-maxport)?)?, setting the
  1809. * various *out pointers as appropriate. Return 0 on success, -1 on failure.
  1810. */
  1811. int
  1812. parse_port_range(const char *port, uint16_t *port_min_out,
  1813. uint16_t *port_max_out)
  1814. {
  1815. int port_min, port_max, ok;
  1816. tor_assert(port_min_out);
  1817. tor_assert(port_max_out);
  1818. if (!port || *port == '\0' || strcmp(port, "*") == 0) {
  1819. port_min = 1;
  1820. port_max = 65535;
  1821. } else {
  1822. char *endptr = NULL;
  1823. port_min = (int)tor_parse_long(port, 10, 0, 65535, &ok, &endptr);
  1824. if (!ok) {
  1825. log_warn(LD_GENERAL,
  1826. "Malformed port %s on address range; rejecting.",
  1827. escaped(port));
  1828. return -1;
  1829. } else if (endptr && *endptr == '-') {
  1830. port = endptr+1;
  1831. endptr = NULL;
  1832. port_max = (int)tor_parse_long(port, 10, 1, 65535, &ok, &endptr);
  1833. if (!ok) {
  1834. log_warn(LD_GENERAL,
  1835. "Malformed port %s on address range; rejecting.",
  1836. escaped(port));
  1837. return -1;
  1838. }
  1839. } else {
  1840. port_max = port_min;
  1841. }
  1842. if (port_min > port_max) {
  1843. log_warn(LD_GENERAL, "Insane port range on address policy; rejecting.");
  1844. return -1;
  1845. }
  1846. }
  1847. if (port_min < 1)
  1848. port_min = 1;
  1849. if (port_max > 65535)
  1850. port_max = 65535;
  1851. *port_min_out = (uint16_t) port_min;
  1852. *port_max_out = (uint16_t) port_max;
  1853. return 0;
  1854. }
  1855. /** Given an IPv4 in_addr struct *<b>in</b> (in network order, as usual),
  1856. * write it as a string into the <b>buf_len</b>-byte buffer in
  1857. * <b>buf</b>. Returns a non-negative integer on success.
  1858. * Returns -1 on failure.
  1859. */
  1860. int
  1861. tor_inet_ntoa(const struct in_addr *in, char *buf, size_t buf_len)
  1862. {
  1863. uint32_t a = ntohl(in->s_addr);
  1864. return tor_snprintf(buf, buf_len, "%d.%d.%d.%d",
  1865. (int)(uint8_t)((a>>24)&0xff),
  1866. (int)(uint8_t)((a>>16)&0xff),
  1867. (int)(uint8_t)((a>>8 )&0xff),
  1868. (int)(uint8_t)((a )&0xff));
  1869. }
  1870. /** Given a host-order <b>addr</b>, call tor_inet_ntop() on it
  1871. * and return a strdup of the resulting address.
  1872. */
  1873. char *
  1874. tor_dup_ip(uint32_t addr)
  1875. {
  1876. char buf[TOR_ADDR_BUF_LEN];
  1877. struct in_addr in;
  1878. in.s_addr = htonl(addr);
  1879. tor_inet_ntop(AF_INET, &in, buf, sizeof(buf));
  1880. return tor_strdup(buf);
  1881. }
  1882. /**
  1883. * Set *<b>addr</b> to a host-order IPv4 address (if any) of an
  1884. * interface that connects to the Internet. Prefer public IP addresses to
  1885. * internal IP addresses. This address should only be used in checking
  1886. * whether our address has changed, as it may be an internal IPv4 address.
  1887. * Return 0 on success, -1 on failure.
  1888. * Prefer get_interface_address_list6 for a list of all IPv4 and IPv6
  1889. * addresses on all interfaces which connect to the Internet.
  1890. */
  1891. MOCK_IMPL(int,
  1892. get_interface_address,(int severity, uint32_t *addr))
  1893. {
  1894. tor_addr_t local_addr;
  1895. int r;
  1896. memset(addr, 0, sizeof(uint32_t));
  1897. r = get_interface_address6(severity, AF_INET, &local_addr);
  1898. if (r>=0)
  1899. *addr = tor_addr_to_ipv4h(&local_addr);
  1900. return r;
  1901. }
  1902. /** Return true if we can tell that <b>name</b> is a canonical name for the
  1903. * loopback address. Return true also for *.local hostnames, which are
  1904. * multicast DNS names for hosts on the local network. */
  1905. int
  1906. tor_addr_hostname_is_local(const char *name)
  1907. {
  1908. return !strcasecmp(name, "localhost") ||
  1909. !strcasecmp(name, "local") ||
  1910. !strcasecmpend(name, ".local");
  1911. }
  1912. /** Return a newly allocated tor_addr_port_t with <b>addr</b> and
  1913. <b>port</b> filled in. */
  1914. tor_addr_port_t *
  1915. tor_addr_port_new(const tor_addr_t *addr, uint16_t port)
  1916. {
  1917. tor_addr_port_t *ap = tor_malloc_zero(sizeof(tor_addr_port_t));
  1918. if (addr)
  1919. tor_addr_copy(&ap->addr, addr);
  1920. ap->port = port;
  1921. return ap;
  1922. }
  1923. /** Return true iff <a>a</b> and <b>b</b> are the same address and port */
  1924. int
  1925. tor_addr_port_eq(const tor_addr_port_t *a,
  1926. const tor_addr_port_t *b)
  1927. {
  1928. return tor_addr_eq(&a->addr, &b->addr) && a->port == b->port;
  1929. }