geoip.c 16 KB

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