geoip.c 45 KB

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