geoip.c 47 KB

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