geoip.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. /* Copyright (c) 2007-2018, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file geoip.c
  5. * \brief Functions related to maintaining an IP-to-country database;
  6. * to summarizing client connections by country to entry guards, bridges,
  7. * and directory servers; and for statistics on answering network status
  8. * requests.
  9. *
  10. * There are two main kinds of functions in this module: geoip functions,
  11. * which map groups of IPv4 and IPv6 addresses to country codes, and
  12. * statistical functions, which collect statistics about different kinds of
  13. * per-country usage.
  14. *
  15. * The geoip lookup tables are implemented as sorted lists of disjoint address
  16. * ranges, each mapping to a singleton geoip_country_t. These country objects
  17. * are also indexed by their names in a hashtable.
  18. *
  19. * The tables are populated from disk at startup by the geoip_load_file()
  20. * function. For more information on the file format they read, see that
  21. * function. See the scripts and the README file in src/config for more
  22. * information about how those files are generated.
  23. *
  24. * Tor uses GeoIP information in order to implement user requests (such as
  25. * ExcludeNodes {cc}), and to keep track of how much usage relays are getting
  26. * for each country.
  27. */
  28. #define GEOIP_PRIVATE
  29. #include "lib/cc/torint.h"
  30. /** A signed integer representing a country code. */
  31. typedef int16_t country_t; // XXXX duplicate in or.h
  32. #include "feature/stats/geoip.h"
  33. #include "lib/container/map.h"
  34. #include "lib/container/order.h"
  35. #include "lib/container/smartlist.h"
  36. #include "lib/crypt_ops/crypto_digest.h"
  37. #include "lib/ctime/di_ops.h"
  38. #include "lib/encoding/binascii.h"
  39. #include "lib/fs/files.h"
  40. #include "lib/log/escape.h"
  41. #include "lib/malloc/malloc.h"
  42. #include "lib/net/address.h" //????
  43. #include "lib/net/inaddr.h"
  44. #include "lib/string/compat_ctype.h"
  45. #include "lib/string/compat_string.h"
  46. #include "lib/string/scanf.h"
  47. #include "lib/string/util_string.h"
  48. #include "lib/time/tvdiff.h"
  49. #include <stdio.h>
  50. #include <string.h>
  51. static void init_geoip_countries(void);
  52. /** An entry from the GeoIP IPv4 file: maps an IPv4 range to a country. */
  53. typedef struct geoip_ipv4_entry_t {
  54. uint32_t ip_low; /**< The lowest IP in the range, in host order */
  55. uint32_t ip_high; /**< The highest IP in the range, in host order */
  56. intptr_t country; /**< An index into geoip_countries */
  57. } geoip_ipv4_entry_t;
  58. /** An entry from the GeoIP IPv6 file: maps an IPv6 range to a country. */
  59. typedef struct geoip_ipv6_entry_t {
  60. struct in6_addr ip_low; /**< The lowest IP in the range, in host order */
  61. struct in6_addr ip_high; /**< The highest IP in the range, in host order */
  62. intptr_t country; /**< An index into geoip_countries */
  63. } geoip_ipv6_entry_t;
  64. /** A list of geoip_country_t */
  65. static smartlist_t *geoip_countries = NULL;
  66. /** A map from lowercased country codes to their position in geoip_countries.
  67. * The index is encoded in the pointer, and 1 is added so that NULL can mean
  68. * not found. */
  69. static strmap_t *country_idxplus1_by_lc_code = NULL;
  70. /** Lists of all known geoip_ipv4_entry_t and geoip_ipv6_entry_t, sorted
  71. * by their respective ip_low. */
  72. static smartlist_t *geoip_ipv4_entries = NULL, *geoip_ipv6_entries = NULL;
  73. /** SHA1 digest of the GeoIP files to include in extra-info descriptors. */
  74. static char geoip_digest[DIGEST_LEN];
  75. static char geoip6_digest[DIGEST_LEN];
  76. /** Return a list of geoip_country_t for all known countries. */
  77. const smartlist_t *
  78. geoip_get_countries(void)
  79. {
  80. if (geoip_countries == NULL) {
  81. init_geoip_countries();
  82. }
  83. return geoip_countries;
  84. }
  85. /** Return the index of the <b>country</b>'s entry in the GeoIP
  86. * country list if it is a valid 2-letter country code, otherwise
  87. * return -1. */
  88. MOCK_IMPL(country_t,
  89. geoip_get_country,(const char *country))
  90. {
  91. void *idxplus1_;
  92. intptr_t idx;
  93. idxplus1_ = strmap_get_lc(country_idxplus1_by_lc_code, country);
  94. if (!idxplus1_)
  95. return -1;
  96. idx = ((uintptr_t)idxplus1_)-1;
  97. return (country_t)idx;
  98. }
  99. /** Add an entry to a GeoIP table, mapping all IP addresses between <b>low</b>
  100. * and <b>high</b>, inclusive, to the 2-letter country code <b>country</b>. */
  101. static void
  102. geoip_add_entry(const tor_addr_t *low, const tor_addr_t *high,
  103. const char *country)
  104. {
  105. intptr_t idx;
  106. void *idxplus1_;
  107. IF_BUG_ONCE(tor_addr_family(low) != tor_addr_family(high))
  108. return;
  109. IF_BUG_ONCE(tor_addr_compare(high, low, CMP_EXACT) < 0)
  110. return;
  111. idxplus1_ = strmap_get_lc(country_idxplus1_by_lc_code, country);
  112. if (!idxplus1_) {
  113. geoip_country_t *c = tor_malloc_zero(sizeof(geoip_country_t));
  114. strlcpy(c->countrycode, country, sizeof(c->countrycode));
  115. tor_strlower(c->countrycode);
  116. smartlist_add(geoip_countries, c);
  117. idx = smartlist_len(geoip_countries) - 1;
  118. strmap_set_lc(country_idxplus1_by_lc_code, country, (void*)(idx+1));
  119. } else {
  120. idx = ((uintptr_t)idxplus1_)-1;
  121. }
  122. {
  123. geoip_country_t *c = smartlist_get(geoip_countries, (int)idx);
  124. tor_assert(!strcasecmp(c->countrycode, country));
  125. }
  126. if (tor_addr_family(low) == AF_INET) {
  127. geoip_ipv4_entry_t *ent = tor_malloc_zero(sizeof(geoip_ipv4_entry_t));
  128. ent->ip_low = tor_addr_to_ipv4h(low);
  129. ent->ip_high = tor_addr_to_ipv4h(high);
  130. ent->country = idx;
  131. smartlist_add(geoip_ipv4_entries, ent);
  132. } else if (tor_addr_family(low) == AF_INET6) {
  133. geoip_ipv6_entry_t *ent = tor_malloc_zero(sizeof(geoip_ipv6_entry_t));
  134. ent->ip_low = *tor_addr_to_in6_assert(low);
  135. ent->ip_high = *tor_addr_to_in6_assert(high);
  136. ent->country = idx;
  137. smartlist_add(geoip_ipv6_entries, ent);
  138. }
  139. }
  140. /** Add an entry to the GeoIP table indicated by <b>family</b>,
  141. * parsing it from <b>line</b>. The format is as for geoip_load_file(). */
  142. STATIC int
  143. geoip_parse_entry(const char *line, sa_family_t family)
  144. {
  145. tor_addr_t low_addr, high_addr;
  146. char c[3];
  147. char *country = NULL;
  148. if (!geoip_countries)
  149. init_geoip_countries();
  150. if (family == AF_INET) {
  151. if (!geoip_ipv4_entries)
  152. geoip_ipv4_entries = smartlist_new();
  153. } else if (family == AF_INET6) {
  154. if (!geoip_ipv6_entries)
  155. geoip_ipv6_entries = smartlist_new();
  156. } else {
  157. log_warn(LD_GENERAL, "Unsupported family: %d", family);
  158. return -1;
  159. }
  160. while (TOR_ISSPACE(*line))
  161. ++line;
  162. if (*line == '#')
  163. return 0;
  164. char buf[512];
  165. if (family == AF_INET) {
  166. unsigned int low, high;
  167. if (tor_sscanf(line,"%u,%u,%2s", &low, &high, c) == 3 ||
  168. tor_sscanf(line,"\"%u\",\"%u\",\"%2s\",", &low, &high, c) == 3) {
  169. tor_addr_from_ipv4h(&low_addr, low);
  170. tor_addr_from_ipv4h(&high_addr, high);
  171. } else
  172. goto fail;
  173. country = c;
  174. } else { /* AF_INET6 */
  175. char *low_str, *high_str;
  176. struct in6_addr low, high;
  177. char *strtok_state;
  178. strlcpy(buf, line, sizeof(buf));
  179. low_str = tor_strtok_r(buf, ",", &strtok_state);
  180. if (!low_str)
  181. goto fail;
  182. high_str = tor_strtok_r(NULL, ",", &strtok_state);
  183. if (!high_str)
  184. goto fail;
  185. country = tor_strtok_r(NULL, "\n", &strtok_state);
  186. if (!country)
  187. goto fail;
  188. if (strlen(country) != 2)
  189. goto fail;
  190. if (tor_inet_pton(AF_INET6, low_str, &low) <= 0)
  191. goto fail;
  192. tor_addr_from_in6(&low_addr, &low);
  193. if (tor_inet_pton(AF_INET6, high_str, &high) <= 0)
  194. goto fail;
  195. tor_addr_from_in6(&high_addr, &high);
  196. }
  197. geoip_add_entry(&low_addr, &high_addr, country);
  198. return 0;
  199. fail:
  200. log_warn(LD_GENERAL, "Unable to parse line from GEOIP %s file: %s",
  201. family == AF_INET ? "IPv4" : "IPv6", escaped(line));
  202. return -1;
  203. }
  204. /** Sorting helper: return -1, 1, or 0 based on comparison of two
  205. * geoip_ipv4_entry_t */
  206. static int
  207. geoip_ipv4_compare_entries_(const void **_a, const void **_b)
  208. {
  209. const geoip_ipv4_entry_t *a = *_a, *b = *_b;
  210. if (a->ip_low < b->ip_low)
  211. return -1;
  212. else if (a->ip_low > b->ip_low)
  213. return 1;
  214. else
  215. return 0;
  216. }
  217. /** bsearch helper: return -1, 1, or 0 based on comparison of an IP (a pointer
  218. * to a uint32_t in host order) to a geoip_ipv4_entry_t */
  219. static int
  220. geoip_ipv4_compare_key_to_entry_(const void *_key, const void **_member)
  221. {
  222. /* No alignment issue here, since _key really is a pointer to uint32_t */
  223. const uint32_t addr = *(uint32_t *)_key;
  224. const geoip_ipv4_entry_t *entry = *_member;
  225. if (addr < entry->ip_low)
  226. return -1;
  227. else if (addr > entry->ip_high)
  228. return 1;
  229. else
  230. return 0;
  231. }
  232. /** Sorting helper: return -1, 1, or 0 based on comparison of two
  233. * geoip_ipv6_entry_t */
  234. static int
  235. geoip_ipv6_compare_entries_(const void **_a, const void **_b)
  236. {
  237. const geoip_ipv6_entry_t *a = *_a, *b = *_b;
  238. return fast_memcmp(a->ip_low.s6_addr, b->ip_low.s6_addr,
  239. sizeof(struct in6_addr));
  240. }
  241. /** bsearch helper: return -1, 1, or 0 based on comparison of an IPv6
  242. * (a pointer to a in6_addr) to a geoip_ipv6_entry_t */
  243. static int
  244. geoip_ipv6_compare_key_to_entry_(const void *_key, const void **_member)
  245. {
  246. const struct in6_addr *addr = (struct in6_addr *)_key;
  247. const geoip_ipv6_entry_t *entry = *_member;
  248. if (fast_memcmp(addr->s6_addr, entry->ip_low.s6_addr,
  249. sizeof(struct in6_addr)) < 0)
  250. return -1;
  251. else if (fast_memcmp(addr->s6_addr, entry->ip_high.s6_addr,
  252. sizeof(struct in6_addr)) > 0)
  253. return 1;
  254. else
  255. return 0;
  256. }
  257. /** Set up a new list of geoip countries with no countries (yet) set in it,
  258. * except for the unknown country.
  259. */
  260. static void
  261. init_geoip_countries(void)
  262. {
  263. geoip_country_t *geoip_unresolved;
  264. geoip_countries = smartlist_new();
  265. /* Add a geoip_country_t for requests that could not be resolved to a
  266. * country as first element (index 0) to geoip_countries. */
  267. geoip_unresolved = tor_malloc_zero(sizeof(geoip_country_t));
  268. strlcpy(geoip_unresolved->countrycode, "??",
  269. sizeof(geoip_unresolved->countrycode));
  270. smartlist_add(geoip_countries, geoip_unresolved);
  271. country_idxplus1_by_lc_code = strmap_new();
  272. strmap_set_lc(country_idxplus1_by_lc_code, "??", (void*)(1));
  273. }
  274. /** Clear appropriate GeoIP database, based on <b>family</b>, and
  275. * reload it from the file <b>filename</b>. Return 0 on success, -1 on
  276. * failure.
  277. *
  278. * Recognized line formats for IPv4 are:
  279. * INTIPLOW,INTIPHIGH,CC
  280. * and
  281. * "INTIPLOW","INTIPHIGH","CC","CC3","COUNTRY NAME"
  282. * where INTIPLOW and INTIPHIGH are IPv4 addresses encoded as 4-byte unsigned
  283. * integers, and CC is a country code.
  284. *
  285. * Recognized line format for IPv6 is:
  286. * IPV6LOW,IPV6HIGH,CC
  287. * where IPV6LOW and IPV6HIGH are IPv6 addresses and CC is a country code.
  288. *
  289. * It also recognizes, and skips over, blank lines and lines that start
  290. * with '#' (comments).
  291. */
  292. int
  293. geoip_load_file(sa_family_t family, const char *filename, int severity)
  294. {
  295. FILE *f;
  296. crypto_digest_t *geoip_digest_env = NULL;
  297. tor_assert(family == AF_INET || family == AF_INET6);
  298. if (!(f = tor_fopen_cloexec(filename, "r"))) {
  299. log_fn(severity, LD_GENERAL, "Failed to open GEOIP file %s.",
  300. filename);
  301. return -1;
  302. }
  303. if (!geoip_countries)
  304. init_geoip_countries();
  305. if (family == AF_INET) {
  306. if (geoip_ipv4_entries) {
  307. SMARTLIST_FOREACH(geoip_ipv4_entries, geoip_ipv4_entry_t *, e,
  308. tor_free(e));
  309. smartlist_free(geoip_ipv4_entries);
  310. }
  311. geoip_ipv4_entries = smartlist_new();
  312. } else { /* AF_INET6 */
  313. if (geoip_ipv6_entries) {
  314. SMARTLIST_FOREACH(geoip_ipv6_entries, geoip_ipv6_entry_t *, e,
  315. tor_free(e));
  316. smartlist_free(geoip_ipv6_entries);
  317. }
  318. geoip_ipv6_entries = smartlist_new();
  319. }
  320. geoip_digest_env = crypto_digest_new();
  321. log_notice(LD_GENERAL, "Parsing GEOIP %s file %s.",
  322. (family == AF_INET) ? "IPv4" : "IPv6", filename);
  323. while (!feof(f)) {
  324. char buf[512];
  325. if (fgets(buf, (int)sizeof(buf), f) == NULL)
  326. break;
  327. crypto_digest_add_bytes(geoip_digest_env, buf, strlen(buf));
  328. /* FFFF track full country name. */
  329. geoip_parse_entry(buf, family);
  330. }
  331. /*XXXX abort and return -1 if no entries/illformed?*/
  332. fclose(f);
  333. /* Sort list and remember file digests so that we can include it in
  334. * our extra-info descriptors. */
  335. if (family == AF_INET) {
  336. smartlist_sort(geoip_ipv4_entries, geoip_ipv4_compare_entries_);
  337. crypto_digest_get_digest(geoip_digest_env, geoip_digest, DIGEST_LEN);
  338. } else {
  339. /* AF_INET6 */
  340. smartlist_sort(geoip_ipv6_entries, geoip_ipv6_compare_entries_);
  341. crypto_digest_get_digest(geoip_digest_env, geoip6_digest, DIGEST_LEN);
  342. }
  343. crypto_digest_free(geoip_digest_env);
  344. return 0;
  345. }
  346. /** Given an IP address in host order, return a number representing the
  347. * country to which that address belongs, -1 for "No geoip information
  348. * available", or 0 for the 'unknown country'. The return value will always
  349. * be less than geoip_get_n_countries(). To decode it, call
  350. * geoip_get_country_name().
  351. */
  352. int
  353. geoip_get_country_by_ipv4(uint32_t ipaddr)
  354. {
  355. geoip_ipv4_entry_t *ent;
  356. if (!geoip_ipv4_entries)
  357. return -1;
  358. ent = smartlist_bsearch(geoip_ipv4_entries, &ipaddr,
  359. geoip_ipv4_compare_key_to_entry_);
  360. return ent ? (int)ent->country : 0;
  361. }
  362. /** Given an IPv6 address, return a number representing the country to
  363. * which that address belongs, -1 for "No geoip information available", or
  364. * 0 for the 'unknown country'. The return value will always be less than
  365. * geoip_get_n_countries(). To decode it, call geoip_get_country_name().
  366. */
  367. int
  368. geoip_get_country_by_ipv6(const struct in6_addr *addr)
  369. {
  370. geoip_ipv6_entry_t *ent;
  371. if (!geoip_ipv6_entries)
  372. return -1;
  373. ent = smartlist_bsearch(geoip_ipv6_entries, addr,
  374. geoip_ipv6_compare_key_to_entry_);
  375. return ent ? (int)ent->country : 0;
  376. }
  377. /** Given an IP address, return a number representing the country to which
  378. * that address belongs, -1 for "No geoip information available", or 0 for
  379. * the 'unknown country'. The return value will always be less than
  380. * geoip_get_n_countries(). To decode it, call geoip_get_country_name().
  381. */
  382. MOCK_IMPL(int,
  383. geoip_get_country_by_addr,(const tor_addr_t *addr))
  384. {
  385. if (tor_addr_family(addr) == AF_INET) {
  386. return geoip_get_country_by_ipv4(tor_addr_to_ipv4h(addr));
  387. } else if (tor_addr_family(addr) == AF_INET6) {
  388. return geoip_get_country_by_ipv6(tor_addr_to_in6(addr));
  389. } else {
  390. return -1;
  391. }
  392. }
  393. /** Return the number of countries recognized by the GeoIP country list. */
  394. MOCK_IMPL(int,
  395. geoip_get_n_countries,(void))
  396. {
  397. if (!geoip_countries)
  398. init_geoip_countries();
  399. return (int) smartlist_len(geoip_countries);
  400. }
  401. /** Return the two-letter country code associated with the number <b>num</b>,
  402. * or "??" for an unknown value. */
  403. const char *
  404. geoip_get_country_name(country_t num)
  405. {
  406. if (geoip_countries && num >= 0 && num < smartlist_len(geoip_countries)) {
  407. geoip_country_t *c = smartlist_get(geoip_countries, num);
  408. return c->countrycode;
  409. } else
  410. return "??";
  411. }
  412. /** Return true iff we have loaded a GeoIP database.*/
  413. MOCK_IMPL(int,
  414. geoip_is_loaded,(sa_family_t family))
  415. {
  416. tor_assert(family == AF_INET || family == AF_INET6);
  417. if (geoip_countries == NULL)
  418. return 0;
  419. if (family == AF_INET)
  420. return geoip_ipv4_entries != NULL;
  421. else /* AF_INET6 */
  422. return geoip_ipv6_entries != NULL;
  423. }
  424. /** Return the hex-encoded SHA1 digest of the loaded GeoIP file. The
  425. * result does not need to be deallocated, but will be overwritten by the
  426. * next call of hex_str(). */
  427. const char *
  428. geoip_db_digest(sa_family_t family)
  429. {
  430. tor_assert(family == AF_INET || family == AF_INET6);
  431. if (family == AF_INET)
  432. return hex_str(geoip_digest, DIGEST_LEN);
  433. else /* AF_INET6 */
  434. return hex_str(geoip6_digest, DIGEST_LEN);
  435. }
  436. /** Release all storage held by the GeoIP databases and country list. */
  437. STATIC void
  438. clear_geoip_db(void)
  439. {
  440. if (geoip_countries) {
  441. SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, tor_free(c));
  442. smartlist_free(geoip_countries);
  443. }
  444. strmap_free(country_idxplus1_by_lc_code, NULL);
  445. if (geoip_ipv4_entries) {
  446. SMARTLIST_FOREACH(geoip_ipv4_entries, geoip_ipv4_entry_t *, ent,
  447. tor_free(ent));
  448. smartlist_free(geoip_ipv4_entries);
  449. }
  450. if (geoip_ipv6_entries) {
  451. SMARTLIST_FOREACH(geoip_ipv6_entries, geoip_ipv6_entry_t *, ent,
  452. tor_free(ent));
  453. smartlist_free(geoip_ipv6_entries);
  454. }
  455. geoip_countries = NULL;
  456. country_idxplus1_by_lc_code = NULL;
  457. geoip_ipv4_entries = NULL;
  458. geoip_ipv6_entries = NULL;
  459. }
  460. /** Release all storage held in this file. */
  461. void
  462. geoip_free_all(void)
  463. {
  464. clear_geoip_db();
  465. memset(geoip_digest, 0, sizeof(geoip_digest));
  466. memset(geoip6_digest, 0, sizeof(geoip6_digest));
  467. }