geoip.c 47 KB

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