address.c 54 KB

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