address.c 63 KB

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