geoip.c 56 KB

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