geoip.c 46 KB

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