geoip.c 46 KB

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