geoip.c 47 KB

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