geoip.c 48 KB

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