geoip.c 56 KB

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