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