geoip.c 46 KB

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