geoip.c 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  1. /* Copyright (c) 2007-2013, 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. #define GEOIP_PRIVATE
  11. #include "or.h"
  12. #include "ht.h"
  13. #include "config.h"
  14. #include "control.h"
  15. #include "dnsserv.h"
  16. #include "geoip.h"
  17. #include "routerlist.h"
  18. static void clear_geoip_db(void);
  19. static void init_geoip_countries(void);
  20. /** An entry from the GeoIP IPv4 file: maps an IPv4 range to a country. */
  21. typedef struct geoip_ipv4_entry_t {
  22. uint32_t ip_low; /**< The lowest IP in the range, in host order */
  23. uint32_t ip_high; /**< The highest IP in the range, in host order */
  24. intptr_t country; /**< An index into geoip_countries */
  25. } geoip_ipv4_entry_t;
  26. /** An entry from the GeoIP IPv6 file: maps an IPv6 range to a country. */
  27. typedef struct geoip_ipv6_entry_t {
  28. struct in6_addr ip_low; /**< The lowest IP in the range, in host order */
  29. struct in6_addr ip_high; /**< The highest IP in the range, in host order */
  30. intptr_t country; /**< An index into geoip_countries */
  31. } geoip_ipv6_entry_t;
  32. /** A per-country record for GeoIP request history. */
  33. typedef struct geoip_country_t {
  34. char countrycode[3];
  35. uint32_t n_v3_ns_requests;
  36. } geoip_country_t;
  37. /** A list of geoip_country_t */
  38. static smartlist_t *geoip_countries = NULL;
  39. /** A map from lowercased country codes to their position in geoip_countries.
  40. * The index is encoded in the pointer, and 1 is added so that NULL can mean
  41. * not found. */
  42. static strmap_t *country_idxplus1_by_lc_code = NULL;
  43. /** Lists of all known geoip_ipv4_entry_t and geoip_ipv6_entry_t, sorted
  44. * by their respective ip_low. */
  45. static smartlist_t *geoip_ipv4_entries = NULL, *geoip_ipv6_entries = NULL;
  46. /** SHA1 digest of the GeoIP files to include in extra-info descriptors. */
  47. static char geoip_digest[DIGEST_LEN];
  48. static char geoip6_digest[DIGEST_LEN];
  49. /** Return the index of the <b>country</b>'s entry in the GeoIP
  50. * country list if it is a valid 2-letter country code, otherwise
  51. * return -1. */
  52. country_t
  53. geoip_get_country(const char *country)
  54. {
  55. void *idxplus1_;
  56. intptr_t idx;
  57. idxplus1_ = strmap_get_lc(country_idxplus1_by_lc_code, country);
  58. if (!idxplus1_)
  59. return -1;
  60. idx = ((uintptr_t)idxplus1_)-1;
  61. return (country_t)idx;
  62. }
  63. /** Add an entry to a GeoIP table, mapping all IP addresses between <b>low</b>
  64. * and <b>high</b>, inclusive, to the 2-letter country code <b>country</b>. */
  65. static void
  66. geoip_add_entry(const tor_addr_t *low, const tor_addr_t *high,
  67. const char *country)
  68. {
  69. intptr_t idx;
  70. void *idxplus1_;
  71. if (tor_addr_family(low) != tor_addr_family(high))
  72. return;
  73. if (tor_addr_compare(high, low, CMP_EXACT) < 0)
  74. return;
  75. idxplus1_ = strmap_get_lc(country_idxplus1_by_lc_code, country);
  76. if (!idxplus1_) {
  77. geoip_country_t *c = tor_malloc_zero(sizeof(geoip_country_t));
  78. strlcpy(c->countrycode, country, sizeof(c->countrycode));
  79. tor_strlower(c->countrycode);
  80. smartlist_add(geoip_countries, c);
  81. idx = smartlist_len(geoip_countries) - 1;
  82. strmap_set_lc(country_idxplus1_by_lc_code, country, (void*)(idx+1));
  83. } else {
  84. idx = ((uintptr_t)idxplus1_)-1;
  85. }
  86. {
  87. geoip_country_t *c = smartlist_get(geoip_countries, idx);
  88. tor_assert(!strcasecmp(c->countrycode, country));
  89. }
  90. if (tor_addr_family(low) == AF_INET) {
  91. geoip_ipv4_entry_t *ent = tor_malloc_zero(sizeof(geoip_ipv4_entry_t));
  92. ent->ip_low = tor_addr_to_ipv4h(low);
  93. ent->ip_high = tor_addr_to_ipv4h(high);
  94. ent->country = idx;
  95. smartlist_add(geoip_ipv4_entries, ent);
  96. } else if (tor_addr_family(low) == AF_INET6) {
  97. geoip_ipv6_entry_t *ent = tor_malloc_zero(sizeof(geoip_ipv6_entry_t));
  98. ent->ip_low = *tor_addr_to_in6(low);
  99. ent->ip_high = *tor_addr_to_in6(high);
  100. ent->country = idx;
  101. smartlist_add(geoip_ipv6_entries, ent);
  102. }
  103. }
  104. /** Add an entry to the GeoIP table indicated by <b>family</b>,
  105. * parsing it from <b>line</b>. The format is as for geoip_load_file(). */
  106. STATIC int
  107. geoip_parse_entry(const char *line, sa_family_t family)
  108. {
  109. tor_addr_t low_addr, high_addr;
  110. char c[3];
  111. char *country = NULL;
  112. if (!geoip_countries)
  113. init_geoip_countries();
  114. if (family == AF_INET) {
  115. if (!geoip_ipv4_entries)
  116. geoip_ipv4_entries = smartlist_new();
  117. } else if (family == AF_INET6) {
  118. if (!geoip_ipv6_entries)
  119. geoip_ipv6_entries = smartlist_new();
  120. } else {
  121. log_warn(LD_GENERAL, "Unsupported family: %d", family);
  122. return -1;
  123. }
  124. while (TOR_ISSPACE(*line))
  125. ++line;
  126. if (*line == '#')
  127. return 0;
  128. if (family == AF_INET) {
  129. unsigned int low, high;
  130. if (tor_sscanf(line,"%u,%u,%2s", &low, &high, c) == 3 ||
  131. tor_sscanf(line,"\"%u\",\"%u\",\"%2s\",", &low, &high, c) == 3) {
  132. tor_addr_from_ipv4h(&low_addr, low);
  133. tor_addr_from_ipv4h(&high_addr, high);
  134. } else
  135. goto fail;
  136. country = c;
  137. } else { /* AF_INET6 */
  138. char buf[512];
  139. char *low_str, *high_str;
  140. struct in6_addr low, high;
  141. char *strtok_state;
  142. strlcpy(buf, line, sizeof(buf));
  143. low_str = tor_strtok_r(buf, ",", &strtok_state);
  144. if (!low_str)
  145. goto fail;
  146. high_str = tor_strtok_r(NULL, ",", &strtok_state);
  147. if (!high_str)
  148. goto fail;
  149. country = tor_strtok_r(NULL, "\n", &strtok_state);
  150. if (!country)
  151. goto fail;
  152. if (strlen(country) != 2)
  153. goto fail;
  154. if (tor_inet_pton(AF_INET6, low_str, &low) <= 0)
  155. goto fail;
  156. tor_addr_from_in6(&low_addr, &low);
  157. if (tor_inet_pton(AF_INET6, high_str, &high) <= 0)
  158. goto fail;
  159. tor_addr_from_in6(&high_addr, &high);
  160. }
  161. geoip_add_entry(&low_addr, &high_addr, country);
  162. return 0;
  163. fail:
  164. log_warn(LD_GENERAL, "Unable to parse line from GEOIP %s file: %s",
  165. family == AF_INET ? "IPv4" : "IPv6", escaped(line));
  166. return -1;
  167. }
  168. /** Sorting helper: return -1, 1, or 0 based on comparison of two
  169. * geoip_ipv4_entry_t */
  170. static int
  171. geoip_ipv4_compare_entries_(const void **_a, const void **_b)
  172. {
  173. const geoip_ipv4_entry_t *a = *_a, *b = *_b;
  174. if (a->ip_low < b->ip_low)
  175. return -1;
  176. else if (a->ip_low > b->ip_low)
  177. return 1;
  178. else
  179. return 0;
  180. }
  181. /** bsearch helper: return -1, 1, or 0 based on comparison of an IP (a pointer
  182. * to a uint32_t in host order) to a geoip_ipv4_entry_t */
  183. static int
  184. geoip_ipv4_compare_key_to_entry_(const void *_key, const void **_member)
  185. {
  186. /* No alignment issue here, since _key really is a pointer to uint32_t */
  187. const uint32_t addr = *(uint32_t *)_key;
  188. const geoip_ipv4_entry_t *entry = *_member;
  189. if (addr < entry->ip_low)
  190. return -1;
  191. else if (addr > entry->ip_high)
  192. return 1;
  193. else
  194. return 0;
  195. }
  196. /** Sorting helper: return -1, 1, or 0 based on comparison of two
  197. * geoip_ipv6_entry_t */
  198. static int
  199. geoip_ipv6_compare_entries_(const void **_a, const void **_b)
  200. {
  201. const geoip_ipv6_entry_t *a = *_a, *b = *_b;
  202. return fast_memcmp(a->ip_low.s6_addr, b->ip_low.s6_addr,
  203. sizeof(struct in6_addr));
  204. }
  205. /** bsearch helper: return -1, 1, or 0 based on comparison of an IPv6
  206. * (a pointer to a in6_addr) to a geoip_ipv6_entry_t */
  207. static int
  208. geoip_ipv6_compare_key_to_entry_(const void *_key, const void **_member)
  209. {
  210. const struct in6_addr *addr = (struct in6_addr *)_key;
  211. const geoip_ipv6_entry_t *entry = *_member;
  212. if (fast_memcmp(addr->s6_addr, entry->ip_low.s6_addr,
  213. sizeof(struct in6_addr)) < 0)
  214. return -1;
  215. else if (fast_memcmp(addr->s6_addr, entry->ip_high.s6_addr,
  216. sizeof(struct in6_addr)) > 0)
  217. return 1;
  218. else
  219. return 0;
  220. }
  221. /** Return 1 if we should collect geoip stats on bridge users, and
  222. * include them in our extrainfo descriptor. Else return 0. */
  223. int
  224. should_record_bridge_info(const or_options_t *options)
  225. {
  226. return options->BridgeRelay && options->BridgeRecordUsageByCountry;
  227. }
  228. /** Set up a new list of geoip countries with no countries (yet) set in it,
  229. * except for the unknown country.
  230. */
  231. static void
  232. init_geoip_countries(void)
  233. {
  234. geoip_country_t *geoip_unresolved;
  235. geoip_countries = smartlist_new();
  236. /* Add a geoip_country_t for requests that could not be resolved to a
  237. * country as first element (index 0) to geoip_countries. */
  238. geoip_unresolved = tor_malloc_zero(sizeof(geoip_country_t));
  239. strlcpy(geoip_unresolved->countrycode, "??",
  240. sizeof(geoip_unresolved->countrycode));
  241. smartlist_add(geoip_countries, geoip_unresolved);
  242. country_idxplus1_by_lc_code = strmap_new();
  243. strmap_set_lc(country_idxplus1_by_lc_code, "??", (void*)(1));
  244. }
  245. /** Clear appropriate GeoIP database, based on <b>family</b>, and
  246. * reload it from the file <b>filename</b>. Return 0 on success, -1 on
  247. * failure.
  248. *
  249. * Recognized line formats for IPv4 are:
  250. * INTIPLOW,INTIPHIGH,CC
  251. * and
  252. * "INTIPLOW","INTIPHIGH","CC","CC3","COUNTRY NAME"
  253. * where INTIPLOW and INTIPHIGH are IPv4 addresses encoded as 4-byte unsigned
  254. * integers, and CC is a country code.
  255. *
  256. * Recognized line format for IPv6 is:
  257. * IPV6LOW,IPV6HIGH,CC
  258. * where IPV6LOW and IPV6HIGH are IPv6 addresses and CC is a country code.
  259. *
  260. * It also recognizes, and skips over, blank lines and lines that start
  261. * with '#' (comments).
  262. */
  263. int
  264. geoip_load_file(sa_family_t family, const char *filename)
  265. {
  266. FILE *f;
  267. const char *msg = "";
  268. const or_options_t *options = get_options();
  269. int severity = options_need_geoip_info(options, &msg) ? LOG_WARN : LOG_INFO;
  270. crypto_digest_t *geoip_digest_env = NULL;
  271. tor_assert(family == AF_INET || family == AF_INET6);
  272. if (!(f = tor_fopen_cloexec(filename, "r"))) {
  273. log_fn(severity, LD_GENERAL, "Failed to open GEOIP file %s. %s",
  274. filename, msg);
  275. return -1;
  276. }
  277. if (!geoip_countries)
  278. init_geoip_countries();
  279. if (family == AF_INET) {
  280. if (geoip_ipv4_entries) {
  281. SMARTLIST_FOREACH(geoip_ipv4_entries, geoip_ipv4_entry_t *, e,
  282. tor_free(e));
  283. smartlist_free(geoip_ipv4_entries);
  284. }
  285. geoip_ipv4_entries = smartlist_new();
  286. } else { /* AF_INET6 */
  287. if (geoip_ipv6_entries) {
  288. SMARTLIST_FOREACH(geoip_ipv6_entries, geoip_ipv6_entry_t *, e,
  289. tor_free(e));
  290. smartlist_free(geoip_ipv6_entries);
  291. }
  292. geoip_ipv6_entries = smartlist_new();
  293. }
  294. geoip_digest_env = crypto_digest_new();
  295. log_notice(LD_GENERAL, "Parsing GEOIP %s file %s.",
  296. (family == AF_INET) ? "IPv4" : "IPv6", filename);
  297. while (!feof(f)) {
  298. char buf[512];
  299. if (fgets(buf, (int)sizeof(buf), f) == NULL)
  300. break;
  301. crypto_digest_add_bytes(geoip_digest_env, buf, strlen(buf));
  302. /* FFFF track full country name. */
  303. geoip_parse_entry(buf, family);
  304. }
  305. /*XXXX abort and return -1 if no entries/illformed?*/
  306. fclose(f);
  307. /* Sort list and remember file digests so that we can include it in
  308. * our extra-info descriptors. */
  309. if (family == AF_INET) {
  310. smartlist_sort(geoip_ipv4_entries, geoip_ipv4_compare_entries_);
  311. /* Okay, now we need to maybe change our mind about what is in
  312. * which country. We do this for IPv4 only since that's what we
  313. * store in node->country. */
  314. refresh_all_country_info();
  315. crypto_digest_get_digest(geoip_digest_env, geoip_digest, DIGEST_LEN);
  316. } else {
  317. /* AF_INET6 */
  318. smartlist_sort(geoip_ipv6_entries, geoip_ipv6_compare_entries_);
  319. crypto_digest_get_digest(geoip_digest_env, geoip6_digest, DIGEST_LEN);
  320. }
  321. crypto_digest_free(geoip_digest_env);
  322. return 0;
  323. }
  324. /** Given an IP address in host order, return a number representing the
  325. * country to which that address belongs, -1 for "No geoip information
  326. * available", or 0 for the 'unknown country'. The return value will always
  327. * be less than geoip_get_n_countries(). To decode it, call
  328. * geoip_get_country_name().
  329. */
  330. STATIC int
  331. geoip_get_country_by_ipv4(uint32_t ipaddr)
  332. {
  333. geoip_ipv4_entry_t *ent;
  334. if (!geoip_ipv4_entries)
  335. return -1;
  336. ent = smartlist_bsearch(geoip_ipv4_entries, &ipaddr,
  337. geoip_ipv4_compare_key_to_entry_);
  338. return ent ? (int)ent->country : 0;
  339. }
  340. /** Given an IPv6 address, return a number representing the country to
  341. * which that address belongs, -1 for "No geoip information available", or
  342. * 0 for the 'unknown country'. The return value will always be less than
  343. * geoip_get_n_countries(). To decode it, call geoip_get_country_name().
  344. */
  345. STATIC int
  346. geoip_get_country_by_ipv6(const struct in6_addr *addr)
  347. {
  348. geoip_ipv6_entry_t *ent;
  349. if (!geoip_ipv6_entries)
  350. return -1;
  351. ent = smartlist_bsearch(geoip_ipv6_entries, addr,
  352. geoip_ipv6_compare_key_to_entry_);
  353. return ent ? (int)ent->country : 0;
  354. }
  355. /** Given an IP address, return a number representing the country to which
  356. * that address belongs, -1 for "No geoip information available", or 0 for
  357. * the 'unknown country'. The return value will always be less than
  358. * geoip_get_n_countries(). To decode it, call geoip_get_country_name().
  359. */
  360. int
  361. geoip_get_country_by_addr(const tor_addr_t *addr)
  362. {
  363. if (tor_addr_family(addr) == AF_INET) {
  364. return geoip_get_country_by_ipv4(tor_addr_to_ipv4h(addr));
  365. } else if (tor_addr_family(addr) == AF_INET6) {
  366. return geoip_get_country_by_ipv6(tor_addr_to_in6(addr));
  367. } else {
  368. return -1;
  369. }
  370. }
  371. /** Return the number of countries recognized by the GeoIP country list. */
  372. int
  373. geoip_get_n_countries(void)
  374. {
  375. if (!geoip_countries)
  376. init_geoip_countries();
  377. return (int) smartlist_len(geoip_countries);
  378. }
  379. /** Return the two-letter country code associated with the number <b>num</b>,
  380. * or "??" for an unknown value. */
  381. const char *
  382. geoip_get_country_name(country_t num)
  383. {
  384. if (geoip_countries && num >= 0 && num < smartlist_len(geoip_countries)) {
  385. geoip_country_t *c = smartlist_get(geoip_countries, num);
  386. return c->countrycode;
  387. } else
  388. return "??";
  389. }
  390. /** Return true iff we have loaded a GeoIP database.*/
  391. int
  392. geoip_is_loaded(sa_family_t family)
  393. {
  394. tor_assert(family == AF_INET || family == AF_INET6);
  395. if (geoip_countries == NULL)
  396. return 0;
  397. if (family == AF_INET)
  398. return geoip_ipv4_entries != NULL;
  399. else /* AF_INET6 */
  400. return geoip_ipv6_entries != NULL;
  401. }
  402. /** Return the hex-encoded SHA1 digest of the loaded GeoIP file. The
  403. * result does not need to be deallocated, but will be overwritten by the
  404. * next call of hex_str(). */
  405. const char *
  406. geoip_db_digest(sa_family_t family)
  407. {
  408. tor_assert(family == AF_INET || family == AF_INET6);
  409. if (family == AF_INET)
  410. return hex_str(geoip_digest, DIGEST_LEN);
  411. else /* AF_INET6 */
  412. return hex_str(geoip6_digest, DIGEST_LEN);
  413. }
  414. /** Entry in a map from IP address to the last time we've seen an incoming
  415. * connection from that IP address. Used by bridges only, to track which
  416. * countries have them blocked. */
  417. typedef struct clientmap_entry_t {
  418. HT_ENTRY(clientmap_entry_t) node;
  419. tor_addr_t addr;
  420. /* Name of pluggable transport used by this client. NULL if no
  421. pluggable transport was used. */
  422. char *transport_name;
  423. /** Time when we last saw this IP address, in MINUTES since the epoch.
  424. *
  425. * (This will run out of space around 4011 CE. If Tor is still in use around
  426. * 4000 CE, please remember to add more bits to last_seen_in_minutes.) */
  427. unsigned int last_seen_in_minutes:30;
  428. unsigned int action:2;
  429. } clientmap_entry_t;
  430. /** Largest allowable value for last_seen_in_minutes. (It's a 30-bit field,
  431. * so it can hold up to (1u<<30)-1, or 0x3fffffffu.
  432. */
  433. #define MAX_LAST_SEEN_IN_MINUTES 0X3FFFFFFFu
  434. /** Map from client IP address to last time seen. */
  435. static HT_HEAD(clientmap, clientmap_entry_t) client_history =
  436. HT_INITIALIZER();
  437. /** Hashtable helper: compute a hash of a clientmap_entry_t. */
  438. static INLINE unsigned
  439. clientmap_entry_hash(const clientmap_entry_t *a)
  440. {
  441. return ht_improve_hash(tor_addr_hash(&a->addr));
  442. }
  443. /** Hashtable helper: compare two clientmap_entry_t values for equality. */
  444. static INLINE int
  445. clientmap_entries_eq(const clientmap_entry_t *a, const clientmap_entry_t *b)
  446. {
  447. return !tor_addr_compare(&a->addr, &b->addr, CMP_EXACT) &&
  448. a->action == b->action;
  449. }
  450. HT_PROTOTYPE(clientmap, clientmap_entry_t, node, clientmap_entry_hash,
  451. clientmap_entries_eq);
  452. HT_GENERATE(clientmap, clientmap_entry_t, node, clientmap_entry_hash,
  453. clientmap_entries_eq, 0.6, malloc, realloc, free);
  454. /** Clear history of connecting clients used by entry and bridge stats. */
  455. static void
  456. client_history_clear(void)
  457. {
  458. clientmap_entry_t **ent, **next, *this;
  459. for (ent = HT_START(clientmap, &client_history); ent != NULL;
  460. ent = next) {
  461. if ((*ent)->action == GEOIP_CLIENT_CONNECT) {
  462. this = *ent;
  463. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  464. tor_free(this);
  465. } else {
  466. next = HT_NEXT(clientmap, &client_history, ent);
  467. }
  468. }
  469. }
  470. /** Note that we've seen a client connect from the IP <b>addr</b>
  471. * at time <b>now</b>. Ignored by all but bridges and directories if
  472. * configured accordingly. */
  473. void
  474. geoip_note_client_seen(geoip_client_action_t action,
  475. const tor_addr_t *addr,
  476. const char *transport_name,
  477. time_t now)
  478. {
  479. const or_options_t *options = get_options();
  480. clientmap_entry_t lookup, *ent;
  481. if (action == GEOIP_CLIENT_CONNECT) {
  482. /* Only remember statistics as entry guard or as bridge. */
  483. if (!options->EntryStatistics &&
  484. (!(options->BridgeRelay && options->BridgeRecordUsageByCountry)))
  485. return;
  486. } else {
  487. if (options->BridgeRelay || options->BridgeAuthoritativeDir ||
  488. !options->DirReqStatistics)
  489. return;
  490. }
  491. log_debug(LD_GENERAL, "Seen client from '%s' with transport '%s'.",
  492. safe_str_client(fmt_addr((addr))),
  493. transport_name ? transport_name : "<no transport>");
  494. tor_addr_copy(&lookup.addr, addr);
  495. lookup.action = (int)action;
  496. ent = HT_FIND(clientmap, &client_history, &lookup);
  497. if (! ent) {
  498. ent = tor_malloc_zero(sizeof(clientmap_entry_t));
  499. tor_addr_copy(&ent->addr, addr);
  500. if (transport_name)
  501. ent->transport_name = tor_strdup(transport_name);
  502. ent->action = (int)action;
  503. HT_INSERT(clientmap, &client_history, ent);
  504. }
  505. if (now / 60 <= (int)MAX_LAST_SEEN_IN_MINUTES && now >= 0)
  506. ent->last_seen_in_minutes = (unsigned)(now/60);
  507. else
  508. ent->last_seen_in_minutes = 0;
  509. if (action == GEOIP_CLIENT_NETWORKSTATUS) {
  510. int country_idx = geoip_get_country_by_addr(addr);
  511. if (country_idx < 0)
  512. country_idx = 0; /** unresolved requests are stored at index 0. */
  513. if (country_idx >= 0 && country_idx < smartlist_len(geoip_countries)) {
  514. geoip_country_t *country = smartlist_get(geoip_countries, country_idx);
  515. ++country->n_v3_ns_requests;
  516. }
  517. }
  518. }
  519. /** HT_FOREACH helper: remove a clientmap_entry_t from the hashtable if it's
  520. * older than a certain time. */
  521. static int
  522. remove_old_client_helper_(struct clientmap_entry_t *ent, void *_cutoff)
  523. {
  524. time_t cutoff = *(time_t*)_cutoff / 60;
  525. if (ent->last_seen_in_minutes < cutoff) {
  526. tor_free(ent->transport_name);
  527. tor_free(ent);
  528. return 1;
  529. } else {
  530. return 0;
  531. }
  532. }
  533. /** Forget about all clients that haven't connected since <b>cutoff</b>. */
  534. void
  535. geoip_remove_old_clients(time_t cutoff)
  536. {
  537. clientmap_HT_FOREACH_FN(&client_history,
  538. remove_old_client_helper_,
  539. &cutoff);
  540. }
  541. /** How many responses are we giving to clients requesting v3 network
  542. * statuses? */
  543. static uint32_t ns_v3_responses[GEOIP_NS_RESPONSE_NUM];
  544. /** Note that we've rejected a client's request for a v3 network status
  545. * for reason <b>reason</b> at time <b>now</b>. */
  546. void
  547. geoip_note_ns_response(geoip_ns_response_t response)
  548. {
  549. static int arrays_initialized = 0;
  550. if (!get_options()->DirReqStatistics)
  551. return;
  552. if (!arrays_initialized) {
  553. memset(ns_v3_responses, 0, sizeof(ns_v3_responses));
  554. arrays_initialized = 1;
  555. }
  556. tor_assert(response < GEOIP_NS_RESPONSE_NUM);
  557. ns_v3_responses[response]++;
  558. }
  559. /** Do not mention any country from which fewer than this number of IPs have
  560. * connected. This conceivably avoids reporting information that could
  561. * deanonymize users, though analysis is lacking. */
  562. #define MIN_IPS_TO_NOTE_COUNTRY 1
  563. /** Do not report any geoip data at all if we have fewer than this number of
  564. * IPs to report about. */
  565. #define MIN_IPS_TO_NOTE_ANYTHING 1
  566. /** When reporting geoip data about countries, round up to the nearest
  567. * multiple of this value. */
  568. #define IP_GRANULARITY 8
  569. /** Helper type: used to sort per-country totals by value. */
  570. typedef struct c_hist_t {
  571. char country[3]; /**< Two-letter country code. */
  572. unsigned total; /**< Total IP addresses seen in this country. */
  573. } c_hist_t;
  574. /** Sorting helper: return -1, 1, or 0 based on comparison of two
  575. * geoip_ipv4_entry_t. Sort in descending order of total, and then by country
  576. * code. */
  577. static int
  578. c_hist_compare_(const void **_a, const void **_b)
  579. {
  580. const c_hist_t *a = *_a, *b = *_b;
  581. if (a->total > b->total)
  582. return -1;
  583. else if (a->total < b->total)
  584. return 1;
  585. else
  586. return strcmp(a->country, b->country);
  587. }
  588. /** When there are incomplete directory requests at the end of a 24-hour
  589. * period, consider those requests running for longer than this timeout as
  590. * failed, the others as still running. */
  591. #define DIRREQ_TIMEOUT (10*60)
  592. /** Entry in a map from either chan->global_identifier for direct requests
  593. * or a unique circuit identifier for tunneled requests to request time,
  594. * response size, and completion time of a network status request. Used to
  595. * measure download times of requests to derive average client
  596. * bandwidths. */
  597. typedef struct dirreq_map_entry_t {
  598. HT_ENTRY(dirreq_map_entry_t) node;
  599. /** Unique identifier for this network status request; this is either the
  600. * chan->global_identifier of the dir channel (direct request) or a new
  601. * locally unique identifier of a circuit (tunneled request). This ID is
  602. * only unique among other direct or tunneled requests, respectively. */
  603. uint64_t dirreq_id;
  604. unsigned int state:3; /**< State of this directory request. */
  605. unsigned int type:1; /**< Is this a direct or a tunneled request? */
  606. unsigned int completed:1; /**< Is this request complete? */
  607. /** When did we receive the request and started sending the response? */
  608. struct timeval request_time;
  609. size_t response_size; /**< What is the size of the response in bytes? */
  610. struct timeval completion_time; /**< When did the request succeed? */
  611. } dirreq_map_entry_t;
  612. /** Map of all directory requests asking for v2 or v3 network statuses in
  613. * the current geoip-stats interval. Values are
  614. * of type *<b>dirreq_map_entry_t</b>. */
  615. static HT_HEAD(dirreqmap, dirreq_map_entry_t) dirreq_map =
  616. HT_INITIALIZER();
  617. static int
  618. dirreq_map_ent_eq(const dirreq_map_entry_t *a,
  619. const dirreq_map_entry_t *b)
  620. {
  621. return a->dirreq_id == b->dirreq_id && a->type == b->type;
  622. }
  623. /* DOCDOC dirreq_map_ent_hash */
  624. static unsigned
  625. dirreq_map_ent_hash(const dirreq_map_entry_t *entry)
  626. {
  627. unsigned u = (unsigned) entry->dirreq_id;
  628. u += entry->type << 20;
  629. return u;
  630. }
  631. HT_PROTOTYPE(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash,
  632. dirreq_map_ent_eq);
  633. HT_GENERATE(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash,
  634. dirreq_map_ent_eq, 0.6, malloc, realloc, free);
  635. /** Helper: Put <b>entry</b> into map of directory requests using
  636. * <b>type</b> and <b>dirreq_id</b> as key parts. If there is
  637. * already an entry for that key, print out a BUG warning and return. */
  638. static void
  639. dirreq_map_put_(dirreq_map_entry_t *entry, dirreq_type_t type,
  640. uint64_t dirreq_id)
  641. {
  642. dirreq_map_entry_t *old_ent;
  643. tor_assert(entry->type == type);
  644. tor_assert(entry->dirreq_id == dirreq_id);
  645. /* XXXX we could switch this to HT_INSERT some time, since it seems that
  646. * this bug doesn't happen. But since this function doesn't seem to be
  647. * critical-path, it's sane to leave it alone. */
  648. old_ent = HT_REPLACE(dirreqmap, &dirreq_map, entry);
  649. if (old_ent && old_ent != entry) {
  650. log_warn(LD_BUG, "Error when putting directory request into local "
  651. "map. There was already an entry for the same identifier.");
  652. return;
  653. }
  654. }
  655. /** Helper: Look up and return an entry in the map of directory requests
  656. * using <b>type</b> and <b>dirreq_id</b> as key parts. If there
  657. * is no such entry, return NULL. */
  658. static dirreq_map_entry_t *
  659. dirreq_map_get_(dirreq_type_t type, uint64_t dirreq_id)
  660. {
  661. dirreq_map_entry_t lookup;
  662. lookup.type = type;
  663. lookup.dirreq_id = dirreq_id;
  664. return HT_FIND(dirreqmap, &dirreq_map, &lookup);
  665. }
  666. /** Note that an either direct or tunneled (see <b>type</b>) directory
  667. * request for a v3 network status with unique ID <b>dirreq_id</b> of size
  668. * <b>response_size</b> has started. */
  669. void
  670. geoip_start_dirreq(uint64_t dirreq_id, size_t response_size,
  671. dirreq_type_t type)
  672. {
  673. dirreq_map_entry_t *ent;
  674. if (!get_options()->DirReqStatistics)
  675. return;
  676. ent = tor_malloc_zero(sizeof(dirreq_map_entry_t));
  677. ent->dirreq_id = dirreq_id;
  678. tor_gettimeofday(&ent->request_time);
  679. ent->response_size = response_size;
  680. ent->type = type;
  681. dirreq_map_put_(ent, type, dirreq_id);
  682. }
  683. /** Change the state of the either direct or tunneled (see <b>type</b>)
  684. * directory request with <b>dirreq_id</b> to <b>new_state</b> and
  685. * possibly mark it as completed. If no entry can be found for the given
  686. * key parts (e.g., if this is a directory request that we are not
  687. * measuring, or one that was started in the previous measurement period),
  688. * or if the state cannot be advanced to <b>new_state</b>, do nothing. */
  689. void
  690. geoip_change_dirreq_state(uint64_t dirreq_id, dirreq_type_t type,
  691. dirreq_state_t new_state)
  692. {
  693. dirreq_map_entry_t *ent;
  694. if (!get_options()->DirReqStatistics)
  695. return;
  696. ent = dirreq_map_get_(type, dirreq_id);
  697. if (!ent)
  698. return;
  699. if (new_state == DIRREQ_IS_FOR_NETWORK_STATUS)
  700. return;
  701. if (new_state - 1 != ent->state)
  702. return;
  703. ent->state = new_state;
  704. if ((type == DIRREQ_DIRECT &&
  705. new_state == DIRREQ_FLUSHING_DIR_CONN_FINISHED) ||
  706. (type == DIRREQ_TUNNELED &&
  707. new_state == DIRREQ_CHANNEL_BUFFER_FLUSHED)) {
  708. tor_gettimeofday(&ent->completion_time);
  709. ent->completed = 1;
  710. }
  711. }
  712. /** Return a newly allocated comma-separated string containing statistics
  713. * on network status downloads. The string contains the number of completed
  714. * requests, timeouts, and still running requests as well as the download
  715. * times by deciles and quartiles. Return NULL if we have not observed
  716. * requests for long enough. */
  717. static char *
  718. geoip_get_dirreq_history(dirreq_type_t type)
  719. {
  720. char *result = NULL;
  721. smartlist_t *dirreq_completed = NULL;
  722. uint32_t complete = 0, timeouts = 0, running = 0;
  723. int bufsize = 1024, written;
  724. dirreq_map_entry_t **ptr, **next, *ent;
  725. struct timeval now;
  726. tor_gettimeofday(&now);
  727. dirreq_completed = smartlist_new();
  728. for (ptr = HT_START(dirreqmap, &dirreq_map); ptr; ptr = next) {
  729. ent = *ptr;
  730. if (ent->type != type) {
  731. next = HT_NEXT(dirreqmap, &dirreq_map, ptr);
  732. continue;
  733. } else {
  734. if (ent->completed) {
  735. smartlist_add(dirreq_completed, ent);
  736. complete++;
  737. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr);
  738. } else {
  739. if (tv_mdiff(&ent->request_time, &now) / 1000 > DIRREQ_TIMEOUT)
  740. timeouts++;
  741. else
  742. running++;
  743. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr);
  744. tor_free(ent);
  745. }
  746. }
  747. }
  748. #define DIR_REQ_GRANULARITY 4
  749. complete = round_uint32_to_next_multiple_of(complete,
  750. DIR_REQ_GRANULARITY);
  751. timeouts = round_uint32_to_next_multiple_of(timeouts,
  752. DIR_REQ_GRANULARITY);
  753. running = round_uint32_to_next_multiple_of(running,
  754. DIR_REQ_GRANULARITY);
  755. result = tor_malloc_zero(bufsize);
  756. written = tor_snprintf(result, bufsize, "complete=%u,timeout=%u,"
  757. "running=%u", complete, timeouts, running);
  758. if (written < 0) {
  759. tor_free(result);
  760. goto done;
  761. }
  762. #define MIN_DIR_REQ_RESPONSES 16
  763. if (complete >= MIN_DIR_REQ_RESPONSES) {
  764. uint32_t *dltimes;
  765. /* We may have rounded 'completed' up. Here we want to use the
  766. * real value. */
  767. complete = smartlist_len(dirreq_completed);
  768. dltimes = tor_malloc_zero(sizeof(uint32_t) * complete);
  769. SMARTLIST_FOREACH_BEGIN(dirreq_completed, dirreq_map_entry_t *, ent) {
  770. uint32_t bytes_per_second;
  771. uint32_t time_diff = (uint32_t) tv_mdiff(&ent->request_time,
  772. &ent->completion_time);
  773. if (time_diff == 0)
  774. time_diff = 1; /* Avoid DIV/0; "instant" answers are impossible
  775. * by law of nature or something, but a milisecond
  776. * is a bit greater than "instantly" */
  777. bytes_per_second = (uint32_t)(1000 * ent->response_size / time_diff);
  778. dltimes[ent_sl_idx] = bytes_per_second;
  779. } SMARTLIST_FOREACH_END(ent);
  780. median_uint32(dltimes, complete); /* sorts as a side effect. */
  781. written = tor_snprintf(result + written, bufsize - written,
  782. ",min=%u,d1=%u,d2=%u,q1=%u,d3=%u,d4=%u,md=%u,"
  783. "d6=%u,d7=%u,q3=%u,d8=%u,d9=%u,max=%u",
  784. dltimes[0],
  785. dltimes[1*complete/10-1],
  786. dltimes[2*complete/10-1],
  787. dltimes[1*complete/4-1],
  788. dltimes[3*complete/10-1],
  789. dltimes[4*complete/10-1],
  790. dltimes[5*complete/10-1],
  791. dltimes[6*complete/10-1],
  792. dltimes[7*complete/10-1],
  793. dltimes[3*complete/4-1],
  794. dltimes[8*complete/10-1],
  795. dltimes[9*complete/10-1],
  796. dltimes[complete-1]);
  797. if (written<0)
  798. tor_free(result);
  799. tor_free(dltimes);
  800. }
  801. done:
  802. SMARTLIST_FOREACH(dirreq_completed, dirreq_map_entry_t *, ent,
  803. tor_free(ent));
  804. smartlist_free(dirreq_completed);
  805. return result;
  806. }
  807. /** Store a newly allocated comma-separated string in
  808. * *<a>country_str</a> containing entries for all the countries from
  809. * which we've seen enough clients connect as a bridge, directory
  810. * server, or entry guard. The entry format is cc=num where num is the
  811. * number of IPs we've seen connecting from that country, and cc is a
  812. * lowercased country code. *<a>country_str</a> is set to NULL if
  813. * we're not ready to export per country data yet.
  814. *
  815. * Store a newly allocated comma-separated string in <a>ipver_str</a>
  816. * containing entries for clients connecting over IPv4 and IPv6. The
  817. * format is family=num where num is the nubmer of IPs we've seen
  818. * connecting over that protocol family, and family is 'v4' or 'v6'.
  819. *
  820. * Return 0 on success and -1 if we're missing geoip data. */
  821. int
  822. geoip_get_client_history(geoip_client_action_t action,
  823. char **country_str, char **ipver_str)
  824. {
  825. unsigned granularity = IP_GRANULARITY;
  826. smartlist_t *entries = NULL;
  827. int n_countries = geoip_get_n_countries();
  828. int i;
  829. clientmap_entry_t **ent;
  830. unsigned *counts = NULL;
  831. unsigned total = 0;
  832. unsigned ipv4_count = 0, ipv6_count = 0;
  833. if (!geoip_is_loaded(AF_INET) && !geoip_is_loaded(AF_INET6))
  834. return -1;
  835. counts = tor_malloc_zero(sizeof(unsigned)*n_countries);
  836. HT_FOREACH(ent, clientmap, &client_history) {
  837. int country;
  838. if ((*ent)->action != (int)action)
  839. continue;
  840. country = geoip_get_country_by_addr(&(*ent)->addr);
  841. if (country < 0)
  842. country = 0; /** unresolved requests are stored at index 0. */
  843. tor_assert(0 <= country && country < n_countries);
  844. ++counts[country];
  845. ++total;
  846. switch (tor_addr_family(&(*ent)->addr)) {
  847. case AF_INET:
  848. ipv4_count++;
  849. break;
  850. case AF_INET6:
  851. ipv6_count++;
  852. break;
  853. }
  854. }
  855. if (ipver_str) {
  856. smartlist_t *chunks = smartlist_new();
  857. smartlist_add_asprintf(chunks, "v4=%u",
  858. round_to_next_multiple_of(ipv4_count, granularity));
  859. smartlist_add_asprintf(chunks, "v6=%u",
  860. round_to_next_multiple_of(ipv6_count, granularity));
  861. *ipver_str = smartlist_join_strings(chunks, ",", 0, NULL);
  862. SMARTLIST_FOREACH(chunks, char *, c, tor_free(c));
  863. smartlist_free(chunks);
  864. }
  865. /* Don't record per country data if we haven't seen enough IPs. */
  866. if (total < MIN_IPS_TO_NOTE_ANYTHING) {
  867. tor_free(counts);
  868. if (country_str)
  869. *country_str = NULL;
  870. return 0;
  871. }
  872. /* Make a list of c_hist_t */
  873. entries = smartlist_new();
  874. for (i = 0; i < n_countries; ++i) {
  875. unsigned c = counts[i];
  876. const char *countrycode;
  877. c_hist_t *ent;
  878. /* Only report a country if it has a minimum number of IPs. */
  879. if (c >= MIN_IPS_TO_NOTE_COUNTRY) {
  880. c = round_to_next_multiple_of(c, granularity);
  881. countrycode = geoip_get_country_name(i);
  882. ent = tor_malloc(sizeof(c_hist_t));
  883. strlcpy(ent->country, countrycode, sizeof(ent->country));
  884. ent->total = c;
  885. smartlist_add(entries, ent);
  886. }
  887. }
  888. /* Sort entries. Note that we must do this _AFTER_ rounding, or else
  889. * the sort order could leak info. */
  890. smartlist_sort(entries, c_hist_compare_);
  891. if (country_str) {
  892. smartlist_t *chunks = smartlist_new();
  893. SMARTLIST_FOREACH(entries, c_hist_t *, ch, {
  894. smartlist_add_asprintf(chunks, "%s=%u", ch->country, ch->total);
  895. });
  896. *country_str = smartlist_join_strings(chunks, ",", 0, NULL);
  897. SMARTLIST_FOREACH(chunks, char *, c, tor_free(c));
  898. smartlist_free(chunks);
  899. }
  900. SMARTLIST_FOREACH(entries, c_hist_t *, c, tor_free(c));
  901. smartlist_free(entries);
  902. tor_free(counts);
  903. return 0;
  904. }
  905. /** Return a newly allocated string holding the per-country request history
  906. * for v3 network statuses in a format suitable for an extra-info document,
  907. * or NULL on failure. */
  908. char *
  909. geoip_get_request_history(void)
  910. {
  911. smartlist_t *entries, *strings;
  912. char *result;
  913. unsigned granularity = IP_GRANULARITY;
  914. if (!geoip_countries)
  915. return NULL;
  916. entries = smartlist_new();
  917. SMARTLIST_FOREACH_BEGIN(geoip_countries, geoip_country_t *, c) {
  918. uint32_t tot = 0;
  919. c_hist_t *ent;
  920. tot = c->n_v3_ns_requests;
  921. if (!tot)
  922. continue;
  923. ent = tor_malloc_zero(sizeof(c_hist_t));
  924. strlcpy(ent->country, c->countrycode, sizeof(ent->country));
  925. ent->total = round_to_next_multiple_of(tot, granularity);
  926. smartlist_add(entries, ent);
  927. } SMARTLIST_FOREACH_END(c);
  928. smartlist_sort(entries, c_hist_compare_);
  929. strings = smartlist_new();
  930. SMARTLIST_FOREACH(entries, c_hist_t *, ent, {
  931. smartlist_add_asprintf(strings, "%s=%u", ent->country, ent->total);
  932. });
  933. result = smartlist_join_strings(strings, ",", 0, NULL);
  934. SMARTLIST_FOREACH(strings, char *, cp, tor_free(cp));
  935. SMARTLIST_FOREACH(entries, c_hist_t *, ent, tor_free(ent));
  936. smartlist_free(strings);
  937. smartlist_free(entries);
  938. return result;
  939. }
  940. /** Start time of directory request stats or 0 if we're not collecting
  941. * directory request statistics. */
  942. static time_t start_of_dirreq_stats_interval;
  943. /** Initialize directory request stats. */
  944. void
  945. geoip_dirreq_stats_init(time_t now)
  946. {
  947. start_of_dirreq_stats_interval = now;
  948. }
  949. /** Reset counters for dirreq stats. */
  950. void
  951. geoip_reset_dirreq_stats(time_t now)
  952. {
  953. SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, {
  954. c->n_v3_ns_requests = 0;
  955. });
  956. {
  957. clientmap_entry_t **ent, **next, *this;
  958. for (ent = HT_START(clientmap, &client_history); ent != NULL;
  959. ent = next) {
  960. if ((*ent)->action == GEOIP_CLIENT_NETWORKSTATUS) {
  961. this = *ent;
  962. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  963. tor_free(this);
  964. } else {
  965. next = HT_NEXT(clientmap, &client_history, ent);
  966. }
  967. }
  968. }
  969. memset(ns_v3_responses, 0, sizeof(ns_v3_responses));
  970. {
  971. dirreq_map_entry_t **ent, **next, *this;
  972. for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) {
  973. this = *ent;
  974. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent);
  975. tor_free(this);
  976. }
  977. }
  978. start_of_dirreq_stats_interval = now;
  979. }
  980. /** Stop collecting directory request stats in a way that we can re-start
  981. * doing so in geoip_dirreq_stats_init(). */
  982. void
  983. geoip_dirreq_stats_term(void)
  984. {
  985. geoip_reset_dirreq_stats(0);
  986. }
  987. /** Return a newly allocated string containing the dirreq statistics
  988. * until <b>now</b>, or NULL if we're not collecting dirreq stats. Caller
  989. * must ensure start_of_dirreq_stats_interval is in the past. */
  990. char *
  991. geoip_format_dirreq_stats(time_t now)
  992. {
  993. char t[ISO_TIME_LEN+1];
  994. int i;
  995. char *v3_ips_string, *v3_reqs_string, *v3_direct_dl_string,
  996. *v3_tunneled_dl_string;
  997. char *result;
  998. if (!start_of_dirreq_stats_interval)
  999. return NULL; /* Not initialized. */
  1000. tor_assert(now >= start_of_dirreq_stats_interval);
  1001. format_iso_time(t, now);
  1002. geoip_get_client_history(GEOIP_CLIENT_NETWORKSTATUS, &v3_ips_string, NULL);
  1003. v3_reqs_string = geoip_get_request_history();
  1004. #define RESPONSE_GRANULARITY 8
  1005. for (i = 0; i < GEOIP_NS_RESPONSE_NUM; i++) {
  1006. ns_v3_responses[i] = round_uint32_to_next_multiple_of(
  1007. ns_v3_responses[i], RESPONSE_GRANULARITY);
  1008. }
  1009. #undef RESPONSE_GRANULARITY
  1010. v3_direct_dl_string = geoip_get_dirreq_history(DIRREQ_DIRECT);
  1011. v3_tunneled_dl_string = geoip_get_dirreq_history(DIRREQ_TUNNELED);
  1012. /* Put everything together into a single string. */
  1013. tor_asprintf(&result, "dirreq-stats-end %s (%d s)\n"
  1014. "dirreq-v3-ips %s\n"
  1015. "dirreq-v3-reqs %s\n"
  1016. "dirreq-v3-resp ok=%u,not-enough-sigs=%u,unavailable=%u,"
  1017. "not-found=%u,not-modified=%u,busy=%u\n"
  1018. "dirreq-v3-direct-dl %s\n"
  1019. "dirreq-v3-tunneled-dl %s\n",
  1020. t,
  1021. (unsigned) (now - start_of_dirreq_stats_interval),
  1022. v3_ips_string ? v3_ips_string : "",
  1023. v3_reqs_string ? v3_reqs_string : "",
  1024. ns_v3_responses[GEOIP_SUCCESS],
  1025. ns_v3_responses[GEOIP_REJECT_NOT_ENOUGH_SIGS],
  1026. ns_v3_responses[GEOIP_REJECT_UNAVAILABLE],
  1027. ns_v3_responses[GEOIP_REJECT_NOT_FOUND],
  1028. ns_v3_responses[GEOIP_REJECT_NOT_MODIFIED],
  1029. ns_v3_responses[GEOIP_REJECT_BUSY],
  1030. v3_direct_dl_string ? v3_direct_dl_string : "",
  1031. v3_tunneled_dl_string ? v3_tunneled_dl_string : "");
  1032. /* Free partial strings. */
  1033. tor_free(v3_ips_string);
  1034. tor_free(v3_reqs_string);
  1035. tor_free(v3_direct_dl_string);
  1036. tor_free(v3_tunneled_dl_string);
  1037. return result;
  1038. }
  1039. /** If 24 hours have passed since the beginning of the current dirreq
  1040. * stats period, write dirreq stats to $DATADIR/stats/dirreq-stats
  1041. * (possibly overwriting an existing file) and reset counters. Return
  1042. * when we would next want to write dirreq stats or 0 if we never want to
  1043. * write. */
  1044. time_t
  1045. geoip_dirreq_stats_write(time_t now)
  1046. {
  1047. char *str = NULL;
  1048. if (!start_of_dirreq_stats_interval)
  1049. return 0; /* Not initialized. */
  1050. if (start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL > now)
  1051. goto done; /* Not ready to write. */
  1052. /* Discard all items in the client history that are too old. */
  1053. geoip_remove_old_clients(start_of_dirreq_stats_interval);
  1054. /* Generate history string .*/
  1055. str = geoip_format_dirreq_stats(now);
  1056. /* Write dirreq-stats string to disk. */
  1057. if (!check_or_create_data_subdir("stats")) {
  1058. write_to_data_subdir("stats", "dirreq-stats", str, "dirreq statistics");
  1059. /* Reset measurement interval start. */
  1060. geoip_reset_dirreq_stats(now);
  1061. }
  1062. done:
  1063. tor_free(str);
  1064. return start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL;
  1065. }
  1066. /** Start time of bridge stats or 0 if we're not collecting bridge
  1067. * statistics. */
  1068. static time_t start_of_bridge_stats_interval;
  1069. /** Initialize bridge stats. */
  1070. void
  1071. geoip_bridge_stats_init(time_t now)
  1072. {
  1073. start_of_bridge_stats_interval = now;
  1074. }
  1075. /** Stop collecting bridge stats in a way that we can re-start doing so in
  1076. * geoip_bridge_stats_init(). */
  1077. void
  1078. geoip_bridge_stats_term(void)
  1079. {
  1080. client_history_clear();
  1081. start_of_bridge_stats_interval = 0;
  1082. }
  1083. /** Validate a bridge statistics string as it would be written to a
  1084. * current extra-info descriptor. Return 1 if the string is valid and
  1085. * recent enough, or 0 otherwise. */
  1086. static int
  1087. validate_bridge_stats(const char *stats_str, time_t now)
  1088. {
  1089. char stats_end_str[ISO_TIME_LEN+1], stats_start_str[ISO_TIME_LEN+1],
  1090. *eos;
  1091. const char *BRIDGE_STATS_END = "bridge-stats-end ";
  1092. const char *BRIDGE_IPS = "bridge-ips ";
  1093. const char *BRIDGE_IPS_EMPTY_LINE = "bridge-ips\n";
  1094. const char *tmp;
  1095. time_t stats_end_time;
  1096. int seconds;
  1097. tor_assert(stats_str);
  1098. /* Parse timestamp and number of seconds from
  1099. "bridge-stats-end YYYY-MM-DD HH:MM:SS (N s)" */
  1100. tmp = find_str_at_start_of_line(stats_str, BRIDGE_STATS_END);
  1101. if (!tmp)
  1102. return 0;
  1103. tmp += strlen(BRIDGE_STATS_END);
  1104. if (strlen(tmp) < ISO_TIME_LEN + 6)
  1105. return 0;
  1106. strlcpy(stats_end_str, tmp, sizeof(stats_end_str));
  1107. if (parse_iso_time(stats_end_str, &stats_end_time) < 0)
  1108. return 0;
  1109. if (stats_end_time < now - (25*60*60) ||
  1110. stats_end_time > now + (1*60*60))
  1111. return 0;
  1112. seconds = (int)strtol(tmp + ISO_TIME_LEN + 2, &eos, 10);
  1113. if (!eos || seconds < 23*60*60)
  1114. return 0;
  1115. format_iso_time(stats_start_str, stats_end_time - seconds);
  1116. /* Parse: "bridge-ips CC=N,CC=N,..." */
  1117. tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS);
  1118. if (!tmp) {
  1119. /* Look if there is an empty "bridge-ips" line */
  1120. tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS_EMPTY_LINE);
  1121. if (!tmp)
  1122. return 0;
  1123. }
  1124. return 1;
  1125. }
  1126. /** Most recent bridge statistics formatted to be written to extra-info
  1127. * descriptors. */
  1128. static char *bridge_stats_extrainfo = NULL;
  1129. /** Return a newly allocated string holding our bridge usage stats by country
  1130. * in a format suitable for inclusion in an extrainfo document. Return NULL on
  1131. * failure. */
  1132. char *
  1133. geoip_format_bridge_stats(time_t now)
  1134. {
  1135. char *out = NULL, *country_data = NULL, *ipver_data = NULL;
  1136. long duration = now - start_of_bridge_stats_interval;
  1137. char written[ISO_TIME_LEN+1];
  1138. if (duration < 0)
  1139. return NULL;
  1140. if (!start_of_bridge_stats_interval)
  1141. return NULL; /* Not initialized. */
  1142. format_iso_time(written, now);
  1143. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data);
  1144. tor_asprintf(&out,
  1145. "bridge-stats-end %s (%ld s)\n"
  1146. "bridge-ips %s\n"
  1147. "bridge-ip-versions %s\n",
  1148. written, duration,
  1149. country_data ? country_data : "",
  1150. ipver_data ? ipver_data : "");
  1151. tor_free(country_data);
  1152. tor_free(ipver_data);
  1153. return out;
  1154. }
  1155. /** Return a newly allocated string holding our bridge usage stats by country
  1156. * in a format suitable for the answer to a controller request. Return NULL on
  1157. * failure. */
  1158. static char *
  1159. format_bridge_stats_controller(time_t now)
  1160. {
  1161. char *out = NULL, *country_data = NULL, *ipver_data = NULL;
  1162. char started[ISO_TIME_LEN+1];
  1163. (void) now;
  1164. format_iso_time(started, start_of_bridge_stats_interval);
  1165. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data);
  1166. tor_asprintf(&out,
  1167. "TimeStarted=\"%s\" CountrySummary=%s IPVersions=%s",
  1168. started,
  1169. country_data ? country_data : "",
  1170. ipver_data ? ipver_data : "");
  1171. tor_free(country_data);
  1172. tor_free(ipver_data);
  1173. return out;
  1174. }
  1175. /** Write bridge statistics to $DATADIR/stats/bridge-stats and return
  1176. * when we should next try to write statistics. */
  1177. time_t
  1178. geoip_bridge_stats_write(time_t now)
  1179. {
  1180. char *val = NULL;
  1181. /* Check if 24 hours have passed since starting measurements. */
  1182. if (now < start_of_bridge_stats_interval + WRITE_STATS_INTERVAL)
  1183. return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL;
  1184. /* Discard all items in the client history that are too old. */
  1185. geoip_remove_old_clients(start_of_bridge_stats_interval);
  1186. /* Generate formatted string */
  1187. val = geoip_format_bridge_stats(now);
  1188. if (val == NULL)
  1189. goto done;
  1190. /* Update the stored value. */
  1191. tor_free(bridge_stats_extrainfo);
  1192. bridge_stats_extrainfo = val;
  1193. start_of_bridge_stats_interval = now;
  1194. /* Write it to disk. */
  1195. if (!check_or_create_data_subdir("stats")) {
  1196. write_to_data_subdir("stats", "bridge-stats",
  1197. bridge_stats_extrainfo, "bridge statistics");
  1198. /* Tell the controller, "hey, there are clients!" */
  1199. {
  1200. char *controller_str = format_bridge_stats_controller(now);
  1201. if (controller_str)
  1202. control_event_clients_seen(controller_str);
  1203. tor_free(controller_str);
  1204. }
  1205. }
  1206. done:
  1207. return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL;
  1208. }
  1209. /** Try to load the most recent bridge statistics from disk, unless we
  1210. * have finished a measurement interval lately, and check whether they
  1211. * are still recent enough. */
  1212. static void
  1213. load_bridge_stats(time_t now)
  1214. {
  1215. char *fname, *contents;
  1216. if (bridge_stats_extrainfo)
  1217. return;
  1218. fname = get_datadir_fname2("stats", "bridge-stats");
  1219. contents = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
  1220. if (contents && validate_bridge_stats(contents, now)) {
  1221. bridge_stats_extrainfo = contents;
  1222. } else {
  1223. tor_free(contents);
  1224. }
  1225. tor_free(fname);
  1226. }
  1227. /** Return most recent bridge statistics for inclusion in extra-info
  1228. * descriptors, or NULL if we don't have recent bridge statistics. */
  1229. const char *
  1230. geoip_get_bridge_stats_extrainfo(time_t now)
  1231. {
  1232. load_bridge_stats(now);
  1233. return bridge_stats_extrainfo;
  1234. }
  1235. /** Return a new string containing the recent bridge statistics to be returned
  1236. * to controller clients, or NULL if we don't have any bridge statistics. */
  1237. char *
  1238. geoip_get_bridge_stats_controller(time_t now)
  1239. {
  1240. return format_bridge_stats_controller(now);
  1241. }
  1242. /** Start time of entry stats or 0 if we're not collecting entry
  1243. * statistics. */
  1244. static time_t start_of_entry_stats_interval;
  1245. /** Initialize entry stats. */
  1246. void
  1247. geoip_entry_stats_init(time_t now)
  1248. {
  1249. start_of_entry_stats_interval = now;
  1250. }
  1251. /** Reset counters for entry stats. */
  1252. void
  1253. geoip_reset_entry_stats(time_t now)
  1254. {
  1255. client_history_clear();
  1256. start_of_entry_stats_interval = now;
  1257. }
  1258. /** Stop collecting entry stats in a way that we can re-start doing so in
  1259. * geoip_entry_stats_init(). */
  1260. void
  1261. geoip_entry_stats_term(void)
  1262. {
  1263. geoip_reset_entry_stats(0);
  1264. }
  1265. /** Return a newly allocated string containing the entry statistics
  1266. * until <b>now</b>, or NULL if we're not collecting entry stats. Caller
  1267. * must ensure start_of_entry_stats_interval lies in the past. */
  1268. char *
  1269. geoip_format_entry_stats(time_t now)
  1270. {
  1271. char t[ISO_TIME_LEN+1];
  1272. char *data = NULL;
  1273. char *result;
  1274. if (!start_of_entry_stats_interval)
  1275. return NULL; /* Not initialized. */
  1276. tor_assert(now >= start_of_entry_stats_interval);
  1277. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &data, NULL);
  1278. format_iso_time(t, now);
  1279. tor_asprintf(&result,
  1280. "entry-stats-end %s (%u s)\n"
  1281. "entry-ips %s\n",
  1282. t, (unsigned) (now - start_of_entry_stats_interval),
  1283. data ? data : "");
  1284. tor_free(data);
  1285. return result;
  1286. }
  1287. /** If 24 hours have passed since the beginning of the current entry stats
  1288. * period, write entry stats to $DATADIR/stats/entry-stats (possibly
  1289. * overwriting an existing file) and reset counters. Return when we would
  1290. * next want to write entry stats or 0 if we never want to write. */
  1291. time_t
  1292. geoip_entry_stats_write(time_t now)
  1293. {
  1294. char *str = NULL;
  1295. if (!start_of_entry_stats_interval)
  1296. return 0; /* Not initialized. */
  1297. if (start_of_entry_stats_interval + WRITE_STATS_INTERVAL > now)
  1298. goto done; /* Not ready to write. */
  1299. /* Discard all items in the client history that are too old. */
  1300. geoip_remove_old_clients(start_of_entry_stats_interval);
  1301. /* Generate history string .*/
  1302. str = geoip_format_entry_stats(now);
  1303. /* Write entry-stats string to disk. */
  1304. if (!check_or_create_data_subdir("stats")) {
  1305. write_to_data_subdir("stats", "entry-stats", str, "entry statistics");
  1306. /* Reset measurement interval start. */
  1307. geoip_reset_entry_stats(now);
  1308. }
  1309. done:
  1310. tor_free(str);
  1311. return start_of_entry_stats_interval + WRITE_STATS_INTERVAL;
  1312. }
  1313. /** Helper used to implement GETINFO ip-to-country/... controller command. */
  1314. int
  1315. getinfo_helper_geoip(control_connection_t *control_conn,
  1316. const char *question, char **answer,
  1317. const char **errmsg)
  1318. {
  1319. (void)control_conn;
  1320. if (!strcmpstart(question, "ip-to-country/")) {
  1321. int c;
  1322. sa_family_t family;
  1323. tor_addr_t addr;
  1324. question += strlen("ip-to-country/");
  1325. family = tor_addr_parse(&addr, question);
  1326. if (family != AF_INET && family != AF_INET6) {
  1327. *errmsg = "Invalid address family";
  1328. return -1;
  1329. }
  1330. if (!geoip_is_loaded(family)) {
  1331. *errmsg = "GeoIP data not loaded";
  1332. return -1;
  1333. }
  1334. if (family == AF_INET)
  1335. c = geoip_get_country_by_ipv4(tor_addr_to_ipv4h(&addr));
  1336. else /* AF_INET6 */
  1337. c = geoip_get_country_by_ipv6(tor_addr_to_in6(&addr));
  1338. *answer = tor_strdup(geoip_get_country_name(c));
  1339. }
  1340. return 0;
  1341. }
  1342. /** Release all storage held by the GeoIP databases and country list. */
  1343. static void
  1344. clear_geoip_db(void)
  1345. {
  1346. if (geoip_countries) {
  1347. SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, tor_free(c));
  1348. smartlist_free(geoip_countries);
  1349. }
  1350. strmap_free(country_idxplus1_by_lc_code, NULL);
  1351. if (geoip_ipv4_entries) {
  1352. SMARTLIST_FOREACH(geoip_ipv4_entries, geoip_ipv4_entry_t *, ent,
  1353. tor_free(ent));
  1354. smartlist_free(geoip_ipv4_entries);
  1355. }
  1356. if (geoip_ipv6_entries) {
  1357. SMARTLIST_FOREACH(geoip_ipv6_entries, geoip_ipv6_entry_t *, ent,
  1358. tor_free(ent));
  1359. smartlist_free(geoip_ipv6_entries);
  1360. }
  1361. geoip_countries = NULL;
  1362. country_idxplus1_by_lc_code = NULL;
  1363. geoip_ipv4_entries = NULL;
  1364. geoip_ipv6_entries = NULL;
  1365. }
  1366. /** Release all storage held in this file. */
  1367. void
  1368. geoip_free_all(void)
  1369. {
  1370. {
  1371. clientmap_entry_t **ent, **next, *this;
  1372. for (ent = HT_START(clientmap, &client_history); ent != NULL; ent = next) {
  1373. this = *ent;
  1374. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  1375. tor_free(this->transport_name);
  1376. tor_free(this);
  1377. }
  1378. HT_CLEAR(clientmap, &client_history);
  1379. }
  1380. {
  1381. dirreq_map_entry_t **ent, **next, *this;
  1382. for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) {
  1383. this = *ent;
  1384. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent);
  1385. tor_free(this);
  1386. }
  1387. HT_CLEAR(dirreqmap, &dirreq_map);
  1388. }
  1389. clear_geoip_db();
  1390. }