geoip.c 57 KB

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