geoip.c 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387
  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. /* XXXX we could switch this to HT_INSERT some time, since it seems that
  545. * this bug doesn't happen. But since this function doesn't seem to be
  546. * critical-path, it's sane to leave it alone. */
  547. old_ent = HT_REPLACE(dirreqmap, &dirreq_map, entry);
  548. if (old_ent && old_ent != entry) {
  549. log_warn(LD_BUG, "Error when putting directory request into local "
  550. "map. There was already an entry for the same identifier.");
  551. return;
  552. }
  553. }
  554. /** Helper: Look up and return an entry in the map of directory requests
  555. * using <b>type</b> and <b>dirreq_id</b> as key parts. If there
  556. * is no such entry, return NULL. */
  557. static dirreq_map_entry_t *
  558. _dirreq_map_get(dirreq_type_t type, uint64_t dirreq_id)
  559. {
  560. dirreq_map_entry_t lookup;
  561. lookup.type = type;
  562. lookup.dirreq_id = dirreq_id;
  563. return HT_FIND(dirreqmap, &dirreq_map, &lookup);
  564. }
  565. /** Note that an either direct or tunneled (see <b>type</b>) directory
  566. * request for a network status with unique ID <b>dirreq_id</b> of size
  567. * <b>response_size</b> and action <b>action</b> (either v2 or v3) has
  568. * started. */
  569. void
  570. geoip_start_dirreq(uint64_t dirreq_id, size_t response_size,
  571. geoip_client_action_t action, dirreq_type_t type)
  572. {
  573. dirreq_map_entry_t *ent;
  574. if (!get_options()->DirReqStatistics)
  575. return;
  576. ent = tor_malloc_zero(sizeof(dirreq_map_entry_t));
  577. ent->dirreq_id = dirreq_id;
  578. tor_gettimeofday(&ent->request_time);
  579. ent->response_size = response_size;
  580. ent->action = action;
  581. ent->type = type;
  582. _dirreq_map_put(ent, type, dirreq_id);
  583. }
  584. /** Change the state of the either direct or tunneled (see <b>type</b>)
  585. * directory request with <b>dirreq_id</b> to <b>new_state</b> and
  586. * possibly mark it as completed. If no entry can be found for the given
  587. * key parts (e.g., if this is a directory request that we are not
  588. * measuring, or one that was started in the previous measurement period),
  589. * or if the state cannot be advanced to <b>new_state</b>, do nothing. */
  590. void
  591. geoip_change_dirreq_state(uint64_t dirreq_id, dirreq_type_t type,
  592. dirreq_state_t new_state)
  593. {
  594. dirreq_map_entry_t *ent;
  595. if (!get_options()->DirReqStatistics)
  596. return;
  597. ent = _dirreq_map_get(type, dirreq_id);
  598. if (!ent)
  599. return;
  600. if (new_state == DIRREQ_IS_FOR_NETWORK_STATUS)
  601. return;
  602. if (new_state - 1 != ent->state)
  603. return;
  604. ent->state = new_state;
  605. if ((type == DIRREQ_DIRECT &&
  606. new_state == DIRREQ_FLUSHING_DIR_CONN_FINISHED) ||
  607. (type == DIRREQ_TUNNELED &&
  608. new_state == DIRREQ_OR_CONN_BUFFER_FLUSHED)) {
  609. tor_gettimeofday(&ent->completion_time);
  610. ent->completed = 1;
  611. }
  612. }
  613. /** Return a newly allocated comma-separated string containing statistics
  614. * on network status downloads. The string contains the number of completed
  615. * requests, timeouts, and still running requests as well as the download
  616. * times by deciles and quartiles. Return NULL if we have not observed
  617. * requests for long enough. */
  618. static char *
  619. geoip_get_dirreq_history(geoip_client_action_t action,
  620. dirreq_type_t type)
  621. {
  622. char *result = NULL;
  623. smartlist_t *dirreq_completed = NULL;
  624. uint32_t complete = 0, timeouts = 0, running = 0;
  625. int bufsize = 1024, written;
  626. dirreq_map_entry_t **ptr, **next, *ent;
  627. struct timeval now;
  628. tor_gettimeofday(&now);
  629. if (action != GEOIP_CLIENT_NETWORKSTATUS &&
  630. action != GEOIP_CLIENT_NETWORKSTATUS_V2)
  631. return NULL;
  632. dirreq_completed = smartlist_create();
  633. for (ptr = HT_START(dirreqmap, &dirreq_map); ptr; ptr = next) {
  634. ent = *ptr;
  635. if (ent->action != action || ent->type != type) {
  636. next = HT_NEXT(dirreqmap, &dirreq_map, ptr);
  637. continue;
  638. } else {
  639. if (ent->completed) {
  640. smartlist_add(dirreq_completed, ent);
  641. complete++;
  642. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr);
  643. } else {
  644. if (tv_mdiff(&ent->request_time, &now) / 1000 > DIRREQ_TIMEOUT)
  645. timeouts++;
  646. else
  647. running++;
  648. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr);
  649. tor_free(ent);
  650. }
  651. }
  652. }
  653. #define DIR_REQ_GRANULARITY 4
  654. complete = round_uint32_to_next_multiple_of(complete,
  655. DIR_REQ_GRANULARITY);
  656. timeouts = round_uint32_to_next_multiple_of(timeouts,
  657. DIR_REQ_GRANULARITY);
  658. running = round_uint32_to_next_multiple_of(running,
  659. DIR_REQ_GRANULARITY);
  660. result = tor_malloc_zero(bufsize);
  661. written = tor_snprintf(result, bufsize, "complete=%u,timeout=%u,"
  662. "running=%u", complete, timeouts, running);
  663. if (written < 0) {
  664. tor_free(result);
  665. goto done;
  666. }
  667. #define MIN_DIR_REQ_RESPONSES 16
  668. if (complete >= MIN_DIR_REQ_RESPONSES) {
  669. uint32_t *dltimes;
  670. /* We may have rounded 'completed' up. Here we want to use the
  671. * real value. */
  672. complete = smartlist_len(dirreq_completed);
  673. dltimes = tor_malloc_zero(sizeof(uint32_t) * complete);
  674. SMARTLIST_FOREACH_BEGIN(dirreq_completed, dirreq_map_entry_t *, ent) {
  675. uint32_t bytes_per_second;
  676. uint32_t time_diff = (uint32_t) tv_mdiff(&ent->request_time,
  677. &ent->completion_time);
  678. if (time_diff == 0)
  679. time_diff = 1; /* Avoid DIV/0; "instant" answers are impossible
  680. * by law of nature or something, but a milisecond
  681. * is a bit greater than "instantly" */
  682. bytes_per_second = (uint32_t)(1000 * ent->response_size / time_diff);
  683. dltimes[ent_sl_idx] = bytes_per_second;
  684. } SMARTLIST_FOREACH_END(ent);
  685. median_uint32(dltimes, complete); /* sorts as a side effect. */
  686. written = tor_snprintf(result + written, bufsize - written,
  687. ",min=%u,d1=%u,d2=%u,q1=%u,d3=%u,d4=%u,md=%u,"
  688. "d6=%u,d7=%u,q3=%u,d8=%u,d9=%u,max=%u",
  689. dltimes[0],
  690. dltimes[1*complete/10-1],
  691. dltimes[2*complete/10-1],
  692. dltimes[1*complete/4-1],
  693. dltimes[3*complete/10-1],
  694. dltimes[4*complete/10-1],
  695. dltimes[5*complete/10-1],
  696. dltimes[6*complete/10-1],
  697. dltimes[7*complete/10-1],
  698. dltimes[3*complete/4-1],
  699. dltimes[8*complete/10-1],
  700. dltimes[9*complete/10-1],
  701. dltimes[complete-1]);
  702. if (written<0)
  703. tor_free(result);
  704. tor_free(dltimes);
  705. }
  706. done:
  707. SMARTLIST_FOREACH(dirreq_completed, dirreq_map_entry_t *, ent,
  708. tor_free(ent));
  709. smartlist_free(dirreq_completed);
  710. return result;
  711. }
  712. /** Return a newly allocated comma-separated string containing entries for
  713. * all the countries from which we've seen enough clients connect as a
  714. * bridge, directory server, or entry guard. The entry format is cc=num
  715. * where num is the number of IPs we've seen connecting from that country,
  716. * and cc is a lowercased country code. Returns NULL if we don't want
  717. * to export geoip data yet. */
  718. char *
  719. geoip_get_client_history(geoip_client_action_t action)
  720. {
  721. char *result = NULL;
  722. unsigned granularity = IP_GRANULARITY;
  723. smartlist_t *chunks = NULL;
  724. smartlist_t *entries = NULL;
  725. int n_countries = geoip_get_n_countries();
  726. int i;
  727. clientmap_entry_t **ent;
  728. unsigned *counts = NULL;
  729. unsigned total = 0;
  730. if (!geoip_is_loaded())
  731. return NULL;
  732. counts = tor_malloc_zero(sizeof(unsigned)*n_countries);
  733. HT_FOREACH(ent, clientmap, &client_history) {
  734. int country;
  735. if ((*ent)->action != (int)action)
  736. continue;
  737. country = geoip_get_country_by_ip((*ent)->ipaddr);
  738. if (country < 0)
  739. country = 0; /** unresolved requests are stored at index 0. */
  740. tor_assert(0 <= country && country < n_countries);
  741. ++counts[country];
  742. ++total;
  743. }
  744. /* Don't record anything if we haven't seen enough IPs. */
  745. if (total < MIN_IPS_TO_NOTE_ANYTHING)
  746. goto done;
  747. /* Make a list of c_hist_t */
  748. entries = smartlist_create();
  749. for (i = 0; i < n_countries; ++i) {
  750. unsigned c = counts[i];
  751. const char *countrycode;
  752. c_hist_t *ent;
  753. /* Only report a country if it has a minimum number of IPs. */
  754. if (c >= MIN_IPS_TO_NOTE_COUNTRY) {
  755. c = round_to_next_multiple_of(c, granularity);
  756. countrycode = geoip_get_country_name(i);
  757. ent = tor_malloc(sizeof(c_hist_t));
  758. strlcpy(ent->country, countrycode, sizeof(ent->country));
  759. ent->total = c;
  760. smartlist_add(entries, ent);
  761. }
  762. }
  763. /* Sort entries. Note that we must do this _AFTER_ rounding, or else
  764. * the sort order could leak info. */
  765. smartlist_sort(entries, _c_hist_compare);
  766. /* Build the result. */
  767. chunks = smartlist_create();
  768. SMARTLIST_FOREACH(entries, c_hist_t *, ch, {
  769. char *buf=NULL;
  770. tor_asprintf(&buf, "%s=%u", ch->country, ch->total);
  771. smartlist_add(chunks, buf);
  772. });
  773. result = smartlist_join_strings(chunks, ",", 0, NULL);
  774. done:
  775. tor_free(counts);
  776. if (chunks) {
  777. SMARTLIST_FOREACH(chunks, char *, c, tor_free(c));
  778. smartlist_free(chunks);
  779. }
  780. if (entries) {
  781. SMARTLIST_FOREACH(entries, c_hist_t *, c, tor_free(c));
  782. smartlist_free(entries);
  783. }
  784. return result;
  785. }
  786. /** Return a newly allocated string holding the per-country request history
  787. * for <b>action</b> in a format suitable for an extra-info document, or NULL
  788. * on failure. */
  789. char *
  790. geoip_get_request_history(geoip_client_action_t action)
  791. {
  792. smartlist_t *entries, *strings;
  793. char *result;
  794. unsigned granularity = IP_GRANULARITY;
  795. if (action != GEOIP_CLIENT_NETWORKSTATUS &&
  796. action != GEOIP_CLIENT_NETWORKSTATUS_V2)
  797. return NULL;
  798. if (!geoip_countries)
  799. return NULL;
  800. entries = smartlist_create();
  801. SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, {
  802. uint32_t tot = 0;
  803. c_hist_t *ent;
  804. tot = (action == GEOIP_CLIENT_NETWORKSTATUS) ?
  805. c->n_v3_ns_requests : c->n_v2_ns_requests;
  806. if (!tot)
  807. continue;
  808. ent = tor_malloc_zero(sizeof(c_hist_t));
  809. strlcpy(ent->country, c->countrycode, sizeof(ent->country));
  810. ent->total = round_to_next_multiple_of(tot, granularity);
  811. smartlist_add(entries, ent);
  812. });
  813. smartlist_sort(entries, _c_hist_compare);
  814. strings = smartlist_create();
  815. SMARTLIST_FOREACH(entries, c_hist_t *, ent, {
  816. char *buf = NULL;
  817. tor_asprintf(&buf, "%s=%u", ent->country, ent->total);
  818. smartlist_add(strings, buf);
  819. });
  820. result = smartlist_join_strings(strings, ",", 0, NULL);
  821. SMARTLIST_FOREACH(strings, char *, cp, tor_free(cp));
  822. SMARTLIST_FOREACH(entries, c_hist_t *, ent, tor_free(ent));
  823. smartlist_free(strings);
  824. smartlist_free(entries);
  825. return result;
  826. }
  827. /** Start time of directory request stats or 0 if we're not collecting
  828. * directory request statistics. */
  829. static time_t start_of_dirreq_stats_interval;
  830. /** Initialize directory request stats. */
  831. void
  832. geoip_dirreq_stats_init(time_t now)
  833. {
  834. start_of_dirreq_stats_interval = now;
  835. }
  836. /** Stop collecting directory request stats in a way that we can re-start
  837. * doing so in geoip_dirreq_stats_init(). */
  838. void
  839. geoip_dirreq_stats_term(void)
  840. {
  841. SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, {
  842. c->n_v2_ns_requests = c->n_v3_ns_requests = 0;
  843. });
  844. {
  845. clientmap_entry_t **ent, **next, *this;
  846. for (ent = HT_START(clientmap, &client_history); ent != NULL;
  847. ent = next) {
  848. if ((*ent)->action == GEOIP_CLIENT_NETWORKSTATUS ||
  849. (*ent)->action == GEOIP_CLIENT_NETWORKSTATUS_V2) {
  850. this = *ent;
  851. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  852. tor_free(this);
  853. } else {
  854. next = HT_NEXT(clientmap, &client_history, ent);
  855. }
  856. }
  857. }
  858. v2_share_times_seconds = v3_share_times_seconds = 0.0;
  859. last_time_determined_shares = 0;
  860. share_seconds = 0;
  861. memset(ns_v2_responses, 0, sizeof(ns_v2_responses));
  862. memset(ns_v3_responses, 0, sizeof(ns_v3_responses));
  863. {
  864. dirreq_map_entry_t **ent, **next, *this;
  865. for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) {
  866. this = *ent;
  867. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent);
  868. tor_free(this);
  869. }
  870. }
  871. start_of_dirreq_stats_interval = 0;
  872. }
  873. /** Write dirreq statistics to $DATADIR/stats/dirreq-stats and return when
  874. * we would next want to write. */
  875. time_t
  876. geoip_dirreq_stats_write(time_t now)
  877. {
  878. char *statsdir = NULL, *filename = NULL;
  879. char *data_v2 = NULL, *data_v3 = NULL;
  880. char written[ISO_TIME_LEN+1];
  881. open_file_t *open_file = NULL;
  882. double v2_share = 0.0, v3_share = 0.0;
  883. FILE *out;
  884. int i;
  885. if (!start_of_dirreq_stats_interval)
  886. return 0; /* Not initialized. */
  887. if (start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL > now)
  888. goto done; /* Not ready to write. */
  889. /* Discard all items in the client history that are too old. */
  890. geoip_remove_old_clients(start_of_dirreq_stats_interval);
  891. statsdir = get_datadir_fname("stats");
  892. if (check_private_dir(statsdir, CPD_CREATE) < 0)
  893. goto done;
  894. filename = get_datadir_fname2("stats", "dirreq-stats");
  895. data_v2 = geoip_get_client_history(GEOIP_CLIENT_NETWORKSTATUS_V2);
  896. data_v3 = geoip_get_client_history(GEOIP_CLIENT_NETWORKSTATUS);
  897. format_iso_time(written, now);
  898. out = start_writing_to_stdio_file(filename, OPEN_FLAGS_APPEND,
  899. 0600, &open_file);
  900. if (!out)
  901. goto done;
  902. if (fprintf(out, "dirreq-stats-end %s (%d s)\ndirreq-v3-ips %s\n"
  903. "dirreq-v2-ips %s\n", written,
  904. (unsigned) (now - start_of_dirreq_stats_interval),
  905. data_v3 ? data_v3 : "", data_v2 ? data_v2 : "") < 0)
  906. goto done;
  907. tor_free(data_v2);
  908. tor_free(data_v3);
  909. data_v2 = geoip_get_request_history(GEOIP_CLIENT_NETWORKSTATUS_V2);
  910. data_v3 = geoip_get_request_history(GEOIP_CLIENT_NETWORKSTATUS);
  911. if (fprintf(out, "dirreq-v3-reqs %s\ndirreq-v2-reqs %s\n",
  912. data_v3 ? data_v3 : "", data_v2 ? data_v2 : "") < 0)
  913. goto done;
  914. tor_free(data_v2);
  915. tor_free(data_v3);
  916. SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, {
  917. c->n_v2_ns_requests = c->n_v3_ns_requests = 0;
  918. });
  919. #define RESPONSE_GRANULARITY 8
  920. for (i = 0; i < GEOIP_NS_RESPONSE_NUM; i++) {
  921. ns_v2_responses[i] = round_uint32_to_next_multiple_of(
  922. ns_v2_responses[i], RESPONSE_GRANULARITY);
  923. ns_v3_responses[i] = round_uint32_to_next_multiple_of(
  924. ns_v3_responses[i], RESPONSE_GRANULARITY);
  925. }
  926. #undef RESPONSE_GRANULARITY
  927. if (fprintf(out, "dirreq-v3-resp ok=%u,not-enough-sigs=%u,unavailable=%u,"
  928. "not-found=%u,not-modified=%u,busy=%u\n",
  929. ns_v3_responses[GEOIP_SUCCESS],
  930. ns_v3_responses[GEOIP_REJECT_NOT_ENOUGH_SIGS],
  931. ns_v3_responses[GEOIP_REJECT_UNAVAILABLE],
  932. ns_v3_responses[GEOIP_REJECT_NOT_FOUND],
  933. ns_v3_responses[GEOIP_REJECT_NOT_MODIFIED],
  934. ns_v3_responses[GEOIP_REJECT_BUSY]) < 0)
  935. goto done;
  936. if (fprintf(out, "dirreq-v2-resp ok=%u,unavailable=%u,"
  937. "not-found=%u,not-modified=%u,busy=%u\n",
  938. ns_v2_responses[GEOIP_SUCCESS],
  939. ns_v2_responses[GEOIP_REJECT_UNAVAILABLE],
  940. ns_v2_responses[GEOIP_REJECT_NOT_FOUND],
  941. ns_v2_responses[GEOIP_REJECT_NOT_MODIFIED],
  942. ns_v2_responses[GEOIP_REJECT_BUSY]) < 0)
  943. goto done;
  944. memset(ns_v2_responses, 0, sizeof(ns_v2_responses));
  945. memset(ns_v3_responses, 0, sizeof(ns_v3_responses));
  946. if (!geoip_get_mean_shares(now, &v2_share, &v3_share)) {
  947. if (fprintf(out, "dirreq-v2-share %0.2lf%%\n", v2_share*100) < 0)
  948. goto done;
  949. if (fprintf(out, "dirreq-v3-share %0.2lf%%\n", v3_share*100) < 0)
  950. goto done;
  951. }
  952. data_v2 = geoip_get_dirreq_history(GEOIP_CLIENT_NETWORKSTATUS_V2,
  953. DIRREQ_DIRECT);
  954. data_v3 = geoip_get_dirreq_history(GEOIP_CLIENT_NETWORKSTATUS,
  955. DIRREQ_DIRECT);
  956. if (fprintf(out, "dirreq-v3-direct-dl %s\ndirreq-v2-direct-dl %s\n",
  957. data_v3 ? data_v3 : "", data_v2 ? data_v2 : "") < 0)
  958. goto done;
  959. tor_free(data_v2);
  960. tor_free(data_v3);
  961. data_v2 = geoip_get_dirreq_history(GEOIP_CLIENT_NETWORKSTATUS_V2,
  962. DIRREQ_TUNNELED);
  963. data_v3 = geoip_get_dirreq_history(GEOIP_CLIENT_NETWORKSTATUS,
  964. DIRREQ_TUNNELED);
  965. if (fprintf(out, "dirreq-v3-tunneled-dl %s\ndirreq-v2-tunneled-dl %s\n",
  966. data_v3 ? data_v3 : "", data_v2 ? data_v2 : "") < 0)
  967. goto done;
  968. finish_writing_to_file(open_file);
  969. open_file = NULL;
  970. start_of_dirreq_stats_interval = now;
  971. done:
  972. if (open_file)
  973. abort_writing_to_file(open_file);
  974. tor_free(filename);
  975. tor_free(statsdir);
  976. tor_free(data_v2);
  977. tor_free(data_v3);
  978. return start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL;
  979. }
  980. /** Start time of bridge stats or 0 if we're not collecting bridge
  981. * statistics. */
  982. static time_t start_of_bridge_stats_interval;
  983. /** Initialize bridge stats. */
  984. void
  985. geoip_bridge_stats_init(time_t now)
  986. {
  987. start_of_bridge_stats_interval = now;
  988. }
  989. /** Stop collecting bridge stats in a way that we can re-start doing so in
  990. * geoip_bridge_stats_init(). */
  991. void
  992. geoip_bridge_stats_term(void)
  993. {
  994. client_history_clear();
  995. start_of_bridge_stats_interval = 0;
  996. }
  997. /** Parse the bridge statistics as they are written to extra-info
  998. * descriptors for being returned to controller clients. Return the
  999. * controller string if successful, or NULL otherwise. */
  1000. static char *
  1001. parse_bridge_stats_controller(const char *stats_str, time_t now)
  1002. {
  1003. char stats_end_str[ISO_TIME_LEN+1], stats_start_str[ISO_TIME_LEN+1],
  1004. *controller_str, *eos, *eol, *summary;
  1005. const char *BRIDGE_STATS_END = "bridge-stats-end ";
  1006. const char *BRIDGE_IPS = "bridge-ips ";
  1007. const char *BRIDGE_IPS_EMPTY_LINE = "bridge-ips\n";
  1008. const char *tmp;
  1009. time_t stats_end_time;
  1010. int seconds;
  1011. tor_assert(stats_str);
  1012. /* Parse timestamp and number of seconds from
  1013. "bridge-stats-end YYYY-MM-DD HH:MM:SS (N s)" */
  1014. tmp = find_str_at_start_of_line(stats_str, BRIDGE_STATS_END);
  1015. if (!tmp)
  1016. return NULL;
  1017. tmp += strlen(BRIDGE_STATS_END);
  1018. if (strlen(tmp) < ISO_TIME_LEN + 6)
  1019. return NULL;
  1020. strlcpy(stats_end_str, tmp, sizeof(stats_end_str));
  1021. if (parse_iso_time(stats_end_str, &stats_end_time) < 0)
  1022. return NULL;
  1023. if (stats_end_time < now - (25*60*60) ||
  1024. stats_end_time > now + (1*60*60))
  1025. return NULL;
  1026. seconds = (int)strtol(tmp + ISO_TIME_LEN + 2, &eos, 10);
  1027. if (!eos || seconds < 23*60*60)
  1028. return NULL;
  1029. format_iso_time(stats_start_str, stats_end_time - seconds);
  1030. /* Parse: "bridge-ips CC=N,CC=N,..." */
  1031. tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS);
  1032. if (tmp) {
  1033. tmp += strlen(BRIDGE_IPS);
  1034. tmp = eat_whitespace_no_nl(tmp);
  1035. eol = strchr(tmp, '\n');
  1036. if (eol)
  1037. summary = tor_strndup(tmp, eol-tmp);
  1038. else
  1039. summary = tor_strdup(tmp);
  1040. } else {
  1041. /* Look if there is an empty "bridge-ips" line */
  1042. tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS_EMPTY_LINE);
  1043. if (!tmp)
  1044. return NULL;
  1045. summary = tor_strdup("");
  1046. }
  1047. tor_asprintf(&controller_str,
  1048. "TimeStarted=\"%s\" CountrySummary=%s",
  1049. stats_start_str, summary);
  1050. tor_free(summary);
  1051. return controller_str;
  1052. }
  1053. /** Most recent bridge statistics formatted to be written to extra-info
  1054. * descriptors. */
  1055. static char *bridge_stats_extrainfo = NULL;
  1056. /** Most recent bridge statistics formatted to be returned to controller
  1057. * clients. */
  1058. static char *bridge_stats_controller = NULL;
  1059. /** Write bridge statistics to $DATADIR/stats/bridge-stats and return
  1060. * when we should next try to write statistics. */
  1061. time_t
  1062. geoip_bridge_stats_write(time_t now)
  1063. {
  1064. char *statsdir = NULL, *filename = NULL, *data = NULL,
  1065. written[ISO_TIME_LEN+1], *out = NULL, *controller_str;
  1066. size_t len;
  1067. /* Check if 24 hours have passed since starting measurements. */
  1068. if (now < start_of_bridge_stats_interval + WRITE_STATS_INTERVAL)
  1069. return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL;
  1070. /* Discard all items in the client history that are too old. */
  1071. geoip_remove_old_clients(start_of_bridge_stats_interval);
  1072. statsdir = get_datadir_fname("stats");
  1073. if (check_private_dir(statsdir, CPD_CREATE) < 0)
  1074. goto done;
  1075. filename = get_datadir_fname2("stats", "bridge-stats");
  1076. data = geoip_get_client_history(GEOIP_CLIENT_CONNECT);
  1077. format_iso_time(written, now);
  1078. len = strlen("bridge-stats-end (999999 s)\nbridge-ips \n") +
  1079. ISO_TIME_LEN + (data ? strlen(data) : 0) + 42;
  1080. out = tor_malloc(len);
  1081. if (tor_snprintf(out, len, "bridge-stats-end %s (%u s)\nbridge-ips %s\n",
  1082. written, (unsigned) (now - start_of_bridge_stats_interval),
  1083. data ? data : "") < 0)
  1084. goto done;
  1085. write_str_to_file(filename, out, 0);
  1086. controller_str = parse_bridge_stats_controller(out, now);
  1087. if (!controller_str)
  1088. goto done;
  1089. start_of_bridge_stats_interval = now;
  1090. tor_free(bridge_stats_extrainfo);
  1091. tor_free(bridge_stats_controller);
  1092. bridge_stats_extrainfo = out;
  1093. out = NULL;
  1094. bridge_stats_controller = controller_str;
  1095. control_event_clients_seen(controller_str);
  1096. done:
  1097. tor_free(filename);
  1098. tor_free(statsdir);
  1099. tor_free(data);
  1100. tor_free(out);
  1101. return start_of_bridge_stats_interval +
  1102. WRITE_STATS_INTERVAL;
  1103. }
  1104. /** Try to load the most recent bridge statistics from disk, unless we
  1105. * have finished a measurement interval lately. */
  1106. static void
  1107. load_bridge_stats(time_t now)
  1108. {
  1109. char *statsdir, *fname=NULL, *contents, *controller_str;
  1110. if (bridge_stats_extrainfo)
  1111. return;
  1112. statsdir = get_datadir_fname("stats");
  1113. if (check_private_dir(statsdir, CPD_CREATE) < 0)
  1114. goto done;
  1115. fname = get_datadir_fname2("stats", "bridge-stats");
  1116. contents = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
  1117. if (contents) {
  1118. controller_str = parse_bridge_stats_controller(contents, now);
  1119. if (controller_str) {
  1120. bridge_stats_extrainfo = contents;
  1121. bridge_stats_controller = controller_str;
  1122. } else {
  1123. tor_free(contents);
  1124. }
  1125. }
  1126. done:
  1127. tor_free(fname);
  1128. tor_free(statsdir);
  1129. }
  1130. /** Return most recent bridge statistics for inclusion in extra-info
  1131. * descriptors, or NULL if we don't have recent bridge statistics. */
  1132. const char *
  1133. geoip_get_bridge_stats_extrainfo(time_t now)
  1134. {
  1135. load_bridge_stats(now);
  1136. return bridge_stats_extrainfo;
  1137. }
  1138. /** Return most recent bridge statistics to be returned to controller
  1139. * clients, or NULL if we don't have recent bridge statistics. */
  1140. const char *
  1141. geoip_get_bridge_stats_controller(time_t now)
  1142. {
  1143. load_bridge_stats(now);
  1144. return bridge_stats_controller;
  1145. }
  1146. /** Start time of entry stats or 0 if we're not collecting entry
  1147. * statistics. */
  1148. static time_t start_of_entry_stats_interval;
  1149. /** Initialize entry stats. */
  1150. void
  1151. geoip_entry_stats_init(time_t now)
  1152. {
  1153. start_of_entry_stats_interval = now;
  1154. }
  1155. /** Stop collecting entry stats in a way that we can re-start doing so in
  1156. * geoip_entry_stats_init(). */
  1157. void
  1158. geoip_entry_stats_term(void)
  1159. {
  1160. client_history_clear();
  1161. start_of_entry_stats_interval = 0;
  1162. }
  1163. /** Write entry statistics to $DATADIR/stats/entry-stats and return time
  1164. * when we would next want to write. */
  1165. time_t
  1166. geoip_entry_stats_write(time_t now)
  1167. {
  1168. char *statsdir = NULL, *filename = NULL;
  1169. char *data = NULL;
  1170. char written[ISO_TIME_LEN+1];
  1171. open_file_t *open_file = NULL;
  1172. FILE *out;
  1173. if (!start_of_entry_stats_interval)
  1174. return 0; /* Not initialized. */
  1175. if (start_of_entry_stats_interval + WRITE_STATS_INTERVAL > now)
  1176. goto done; /* Not ready to write. */
  1177. /* Discard all items in the client history that are too old. */
  1178. geoip_remove_old_clients(start_of_entry_stats_interval);
  1179. statsdir = get_datadir_fname("stats");
  1180. if (check_private_dir(statsdir, CPD_CREATE) < 0)
  1181. goto done;
  1182. filename = get_datadir_fname2("stats", "entry-stats");
  1183. data = geoip_get_client_history(GEOIP_CLIENT_CONNECT);
  1184. format_iso_time(written, now);
  1185. out = start_writing_to_stdio_file(filename, OPEN_FLAGS_APPEND,
  1186. 0600, &open_file);
  1187. if (!out)
  1188. goto done;
  1189. if (fprintf(out, "entry-stats-end %s (%u s)\nentry-ips %s\n",
  1190. written, (unsigned) (now - start_of_entry_stats_interval),
  1191. data ? data : "") < 0)
  1192. goto done;
  1193. start_of_entry_stats_interval = now;
  1194. finish_writing_to_file(open_file);
  1195. open_file = NULL;
  1196. done:
  1197. if (open_file)
  1198. abort_writing_to_file(open_file);
  1199. tor_free(filename);
  1200. tor_free(statsdir);
  1201. tor_free(data);
  1202. return start_of_entry_stats_interval + WRITE_STATS_INTERVAL;
  1203. }
  1204. /** Helper used to implement GETINFO ip-to-country/... controller command. */
  1205. int
  1206. getinfo_helper_geoip(control_connection_t *control_conn,
  1207. const char *question, char **answer,
  1208. const char **errmsg)
  1209. {
  1210. (void)control_conn;
  1211. if (!geoip_is_loaded()) {
  1212. *errmsg = "GeoIP data not loaded";
  1213. return -1;
  1214. }
  1215. if (!strcmpstart(question, "ip-to-country/")) {
  1216. int c;
  1217. uint32_t ip;
  1218. struct in_addr in;
  1219. question += strlen("ip-to-country/");
  1220. if (tor_inet_aton(question, &in) != 0) {
  1221. ip = ntohl(in.s_addr);
  1222. c = geoip_get_country_by_ip(ip);
  1223. *answer = tor_strdup(geoip_get_country_name(c));
  1224. }
  1225. }
  1226. return 0;
  1227. }
  1228. /** Release all storage held by the GeoIP database. */
  1229. static void
  1230. clear_geoip_db(void)
  1231. {
  1232. if (geoip_countries) {
  1233. SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, tor_free(c));
  1234. smartlist_free(geoip_countries);
  1235. }
  1236. strmap_free(country_idxplus1_by_lc_code, NULL);
  1237. if (geoip_entries) {
  1238. SMARTLIST_FOREACH(geoip_entries, geoip_entry_t *, ent, tor_free(ent));
  1239. smartlist_free(geoip_entries);
  1240. }
  1241. geoip_countries = NULL;
  1242. country_idxplus1_by_lc_code = NULL;
  1243. geoip_entries = NULL;
  1244. }
  1245. /** Release all storage held in this file. */
  1246. void
  1247. geoip_free_all(void)
  1248. {
  1249. {
  1250. clientmap_entry_t **ent, **next, *this;
  1251. for (ent = HT_START(clientmap, &client_history); ent != NULL; ent = next) {
  1252. this = *ent;
  1253. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  1254. tor_free(this);
  1255. }
  1256. HT_CLEAR(clientmap, &client_history);
  1257. }
  1258. {
  1259. dirreq_map_entry_t **ent, **next, *this;
  1260. for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) {
  1261. this = *ent;
  1262. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent);
  1263. tor_free(this);
  1264. }
  1265. HT_CLEAR(dirreqmap, &dirreq_map);
  1266. }
  1267. clear_geoip_db();
  1268. }