geoip_stats.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425
  1. /* Copyright (c) 2007-2018, 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. * There are two main kinds of functions in this module: geoip functions,
  11. * which map groups of IPv4 and IPv6 addresses to country codes, and
  12. * statistical functions, which collect statistics about different kinds of
  13. * per-country usage.
  14. *
  15. * The geoip lookup tables are implemented as sorted lists of disjoint address
  16. * ranges, each mapping to a singleton geoip_country_t. These country objects
  17. * are also indexed by their names in a hashtable.
  18. *
  19. * The tables are populated from disk at startup by the geoip_load_file()
  20. * function. For more information on the file format they read, see that
  21. * function. See the scripts and the README file in src/config for more
  22. * information about how those files are generated.
  23. *
  24. * Tor uses GeoIP information in order to implement user requests (such as
  25. * ExcludeNodes {cc}), and to keep track of how much usage relays are getting
  26. * for each country.
  27. */
  28. #include "core/or/or.h"
  29. #include "ht.h"
  30. #include "lib/container/buffers.h"
  31. #include "app/config/config.h"
  32. #include "feature/control/control.h"
  33. #include "feature/client/dnsserv.h"
  34. #include "core/or/dos.h"
  35. #include "lib/geoip/geoip.h"
  36. #include "feature/stats/geoip_stats.h"
  37. #include "feature/nodelist/routerlist.h"
  38. #include "lib/container/order.h"
  39. #include "lib/time/tvdiff.h"
  40. /** Number of entries in n_v3_ns_requests */
  41. static size_t n_v3_ns_requests_len = 0;
  42. /** Array, indexed by country index, of number of v3 networkstatus requests
  43. * received from that country */
  44. static uint32_t *n_v3_ns_requests;
  45. /* Total size in bytes of the geoip client history cache. Used by the OOM
  46. * handler. */
  47. static size_t geoip_client_history_cache_size;
  48. /* Increment the geoip client history cache size counter with the given bytes.
  49. * This prevents an overflow and set it to its maximum in that case. */
  50. static inline void
  51. geoip_increment_client_history_cache_size(size_t bytes)
  52. {
  53. /* This is shockingly high, lets log it so it can be reported. */
  54. IF_BUG_ONCE(geoip_client_history_cache_size > (SIZE_MAX - bytes)) {
  55. geoip_client_history_cache_size = SIZE_MAX;
  56. return;
  57. }
  58. geoip_client_history_cache_size += bytes;
  59. }
  60. /* Decrement the geoip client history cache size counter with the given bytes.
  61. * This prevents an underflow and set it to 0 in that case. */
  62. static inline void
  63. geoip_decrement_client_history_cache_size(size_t bytes)
  64. {
  65. /* Going below 0 means that we either allocated an entry without
  66. * incrementing the counter or we have different sizes when allocating and
  67. * freeing. It shouldn't happened so log it. */
  68. IF_BUG_ONCE(geoip_client_history_cache_size < bytes) {
  69. geoip_client_history_cache_size = 0;
  70. return;
  71. }
  72. geoip_client_history_cache_size -= bytes;
  73. }
  74. /** Add 1 to the count of v3 ns requests received from <b>country</b>. */
  75. static void
  76. increment_v3_ns_request(country_t country)
  77. {
  78. if (country < 0)
  79. return;
  80. if ((size_t)country >= n_v3_ns_requests_len) {
  81. /* We need to reallocate the array. */
  82. size_t new_len;
  83. if (n_v3_ns_requests_len == 0)
  84. new_len = 256;
  85. else
  86. new_len = n_v3_ns_requests_len * 2;
  87. if (new_len <= (size_t)country)
  88. new_len = ((size_t)country)+1;
  89. n_v3_ns_requests = tor_reallocarray(n_v3_ns_requests, new_len,
  90. sizeof(uint32_t));
  91. memset(n_v3_ns_requests + n_v3_ns_requests_len, 0,
  92. sizeof(uint32_t)*(new_len - n_v3_ns_requests_len));
  93. n_v3_ns_requests_len = new_len;
  94. }
  95. n_v3_ns_requests[country] += 1;
  96. }
  97. /** Return 1 if we should collect geoip stats on bridge users, and
  98. * include them in our extrainfo descriptor. Else return 0. */
  99. int
  100. should_record_bridge_info(const or_options_t *options)
  101. {
  102. return options->BridgeRelay && options->BridgeRecordUsageByCountry;
  103. }
  104. /** Largest allowable value for last_seen_in_minutes. (It's a 30-bit field,
  105. * so it can hold up to (1u<<30)-1, or 0x3fffffffu.
  106. */
  107. #define MAX_LAST_SEEN_IN_MINUTES 0X3FFFFFFFu
  108. /** Map from client IP address to last time seen. */
  109. static HT_HEAD(clientmap, clientmap_entry_t) client_history =
  110. HT_INITIALIZER();
  111. /** Hashtable helper: compute a hash of a clientmap_entry_t. */
  112. static inline unsigned
  113. clientmap_entry_hash(const clientmap_entry_t *a)
  114. {
  115. unsigned h = (unsigned) tor_addr_hash(&a->addr);
  116. if (a->transport_name)
  117. h += (unsigned) siphash24g(a->transport_name, strlen(a->transport_name));
  118. return h;
  119. }
  120. /** Hashtable helper: compare two clientmap_entry_t values for equality. */
  121. static inline int
  122. clientmap_entries_eq(const clientmap_entry_t *a, const clientmap_entry_t *b)
  123. {
  124. if (strcmp_opt(a->transport_name, b->transport_name))
  125. return 0;
  126. return !tor_addr_compare(&a->addr, &b->addr, CMP_EXACT) &&
  127. a->action == b->action;
  128. }
  129. HT_PROTOTYPE(clientmap, clientmap_entry_t, node, clientmap_entry_hash,
  130. clientmap_entries_eq)
  131. HT_GENERATE2(clientmap, clientmap_entry_t, node, clientmap_entry_hash,
  132. clientmap_entries_eq, 0.6, tor_reallocarray_, tor_free_)
  133. #define clientmap_entry_free(ent) \
  134. FREE_AND_NULL(clientmap_entry_t, clientmap_entry_free_, ent)
  135. /** Return the size of a client map entry. */
  136. static inline size_t
  137. clientmap_entry_size(const clientmap_entry_t *ent)
  138. {
  139. tor_assert(ent);
  140. return (sizeof(clientmap_entry_t) +
  141. (ent->transport_name ? strlen(ent->transport_name) : 0));
  142. }
  143. /** Free all storage held by <b>ent</b>. */
  144. static void
  145. clientmap_entry_free_(clientmap_entry_t *ent)
  146. {
  147. if (!ent)
  148. return;
  149. /* This entry is about to be freed so pass it to the DoS subsystem to see if
  150. * any actions can be taken about it. */
  151. dos_geoip_entry_about_to_free(ent);
  152. geoip_decrement_client_history_cache_size(clientmap_entry_size(ent));
  153. tor_free(ent->transport_name);
  154. tor_free(ent);
  155. }
  156. /* Return a newly allocated clientmap entry with the given action and address
  157. * that are mandatory. The transport_name can be optional. This can't fail. */
  158. static clientmap_entry_t *
  159. clientmap_entry_new(geoip_client_action_t action, const tor_addr_t *addr,
  160. const char *transport_name)
  161. {
  162. clientmap_entry_t *entry;
  163. tor_assert(action == GEOIP_CLIENT_CONNECT ||
  164. action == GEOIP_CLIENT_NETWORKSTATUS);
  165. tor_assert(addr);
  166. entry = tor_malloc_zero(sizeof(clientmap_entry_t));
  167. entry->action = action;
  168. tor_addr_copy(&entry->addr, addr);
  169. if (transport_name) {
  170. entry->transport_name = tor_strdup(transport_name);
  171. }
  172. /* Allocated and initialized, note down its size for the OOM handler. */
  173. geoip_increment_client_history_cache_size(clientmap_entry_size(entry));
  174. return entry;
  175. }
  176. /** Clear history of connecting clients used by entry and bridge stats. */
  177. static void
  178. client_history_clear(void)
  179. {
  180. clientmap_entry_t **ent, **next, *this;
  181. for (ent = HT_START(clientmap, &client_history); ent != NULL;
  182. ent = next) {
  183. if ((*ent)->action == GEOIP_CLIENT_CONNECT) {
  184. this = *ent;
  185. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  186. clientmap_entry_free(this);
  187. } else {
  188. next = HT_NEXT(clientmap, &client_history, ent);
  189. }
  190. }
  191. }
  192. /** Note that we've seen a client connect from the IP <b>addr</b>
  193. * at time <b>now</b>. Ignored by all but bridges and directories if
  194. * configured accordingly. */
  195. void
  196. geoip_note_client_seen(geoip_client_action_t action,
  197. const tor_addr_t *addr,
  198. const char *transport_name,
  199. time_t now)
  200. {
  201. const or_options_t *options = get_options();
  202. clientmap_entry_t *ent;
  203. if (action == GEOIP_CLIENT_CONNECT) {
  204. /* Only remember statistics if the DoS mitigation subsystem is enabled. If
  205. * not, only if as entry guard or as bridge. */
  206. if (!dos_enabled()) {
  207. if (!options->EntryStatistics && !should_record_bridge_info(options)) {
  208. return;
  209. }
  210. }
  211. } else {
  212. /* Only gather directory-request statistics if configured, and
  213. * forcibly disable them on bridge authorities. */
  214. if (!options->DirReqStatistics || options->BridgeAuthoritativeDir)
  215. return;
  216. }
  217. log_debug(LD_GENERAL, "Seen client from '%s' with transport '%s'.",
  218. safe_str_client(fmt_addr((addr))),
  219. transport_name ? transport_name : "<no transport>");
  220. ent = geoip_lookup_client(addr, transport_name, action);
  221. if (! ent) {
  222. ent = clientmap_entry_new(action, addr, transport_name);
  223. HT_INSERT(clientmap, &client_history, ent);
  224. }
  225. if (now / 60 <= (int)MAX_LAST_SEEN_IN_MINUTES && now >= 0)
  226. ent->last_seen_in_minutes = (unsigned)(now/60);
  227. else
  228. ent->last_seen_in_minutes = 0;
  229. if (action == GEOIP_CLIENT_NETWORKSTATUS) {
  230. int country_idx = geoip_get_country_by_addr(addr);
  231. if (country_idx < 0)
  232. country_idx = 0; /** unresolved requests are stored at index 0. */
  233. IF_BUG_ONCE(country_idx > COUNTRY_MAX) {
  234. return;
  235. }
  236. increment_v3_ns_request((country_t) country_idx);
  237. }
  238. }
  239. /** HT_FOREACH helper: remove a clientmap_entry_t from the hashtable if it's
  240. * older than a certain time. */
  241. static int
  242. remove_old_client_helper_(struct clientmap_entry_t *ent, void *_cutoff)
  243. {
  244. time_t cutoff = *(time_t*)_cutoff / 60;
  245. if (ent->last_seen_in_minutes < cutoff) {
  246. clientmap_entry_free(ent);
  247. return 1;
  248. } else {
  249. return 0;
  250. }
  251. }
  252. /** Forget about all clients that haven't connected since <b>cutoff</b>. */
  253. void
  254. geoip_remove_old_clients(time_t cutoff)
  255. {
  256. clientmap_HT_FOREACH_FN(&client_history,
  257. remove_old_client_helper_,
  258. &cutoff);
  259. }
  260. /* Return a client entry object matching the given address, transport name and
  261. * geoip action from the clientmap. NULL if not found. The transport_name can
  262. * be NULL. */
  263. clientmap_entry_t *
  264. geoip_lookup_client(const tor_addr_t *addr, const char *transport_name,
  265. geoip_client_action_t action)
  266. {
  267. clientmap_entry_t lookup;
  268. tor_assert(addr);
  269. /* We always look for a client connection with no transport. */
  270. tor_addr_copy(&lookup.addr, addr);
  271. lookup.action = action;
  272. lookup.transport_name = (char *) transport_name;
  273. return HT_FIND(clientmap, &client_history, &lookup);
  274. }
  275. /* Cleanup client entries older than the cutoff. Used for the OOM. Return the
  276. * number of bytes freed. If 0 is returned, nothing was freed. */
  277. static size_t
  278. oom_clean_client_entries(time_t cutoff)
  279. {
  280. size_t bytes = 0;
  281. clientmap_entry_t **ent, **ent_next;
  282. for (ent = HT_START(clientmap, &client_history); ent; ent = ent_next) {
  283. clientmap_entry_t *entry = *ent;
  284. if (entry->last_seen_in_minutes < (cutoff / 60)) {
  285. ent_next = HT_NEXT_RMV(clientmap, &client_history, ent);
  286. bytes += clientmap_entry_size(entry);
  287. clientmap_entry_free(entry);
  288. } else {
  289. ent_next = HT_NEXT(clientmap, &client_history, ent);
  290. }
  291. }
  292. return bytes;
  293. }
  294. /* Below this minimum lifetime, the OOM won't cleanup any entries. */
  295. #define GEOIP_CLIENT_CACHE_OOM_MIN_CUTOFF (4 * 60 * 60)
  296. /* The OOM moves the cutoff by that much every run. */
  297. #define GEOIP_CLIENT_CACHE_OOM_STEP (15 * 50)
  298. /* Cleanup the geoip client history cache called from the OOM handler. Return
  299. * the amount of bytes removed. This can return a value below or above
  300. * min_remove_bytes but will stop as oon as the min_remove_bytes has been
  301. * reached. */
  302. size_t
  303. geoip_client_cache_handle_oom(time_t now, size_t min_remove_bytes)
  304. {
  305. time_t k;
  306. size_t bytes_removed = 0;
  307. /* Our OOM handler called with 0 bytes to remove is a code flow error. */
  308. tor_assert(min_remove_bytes != 0);
  309. /* Set k to the initial cutoff of an entry. We then going to move it by step
  310. * to try to remove as much as we can. */
  311. k = WRITE_STATS_INTERVAL;
  312. do {
  313. time_t cutoff;
  314. /* If k has reached the minimum lifetime, we have to stop else we might
  315. * remove every single entries which would be pretty bad for the DoS
  316. * mitigation subsystem if by just filling the geoip cache, it was enough
  317. * to trigger the OOM and clean every single entries. */
  318. if (k <= GEOIP_CLIENT_CACHE_OOM_MIN_CUTOFF) {
  319. break;
  320. }
  321. cutoff = now - k;
  322. bytes_removed += oom_clean_client_entries(cutoff);
  323. k -= GEOIP_CLIENT_CACHE_OOM_STEP;
  324. } while (bytes_removed < min_remove_bytes);
  325. return bytes_removed;
  326. }
  327. /* Return the total size in bytes of the client history cache. */
  328. size_t
  329. geoip_client_cache_total_allocation(void)
  330. {
  331. return geoip_client_history_cache_size;
  332. }
  333. /** How many responses are we giving to clients requesting v3 network
  334. * statuses? */
  335. static uint32_t ns_v3_responses[GEOIP_NS_RESPONSE_NUM];
  336. /** Note that we've rejected a client's request for a v3 network status
  337. * for reason <b>reason</b> at time <b>now</b>. */
  338. void
  339. geoip_note_ns_response(geoip_ns_response_t response)
  340. {
  341. static int arrays_initialized = 0;
  342. if (!get_options()->DirReqStatistics)
  343. return;
  344. if (!arrays_initialized) {
  345. memset(ns_v3_responses, 0, sizeof(ns_v3_responses));
  346. arrays_initialized = 1;
  347. }
  348. tor_assert(response < GEOIP_NS_RESPONSE_NUM);
  349. ns_v3_responses[response]++;
  350. }
  351. /** Do not mention any country from which fewer than this number of IPs have
  352. * connected. This conceivably avoids reporting information that could
  353. * deanonymize users, though analysis is lacking. */
  354. #define MIN_IPS_TO_NOTE_COUNTRY 1
  355. /** Do not report any geoip data at all if we have fewer than this number of
  356. * IPs to report about. */
  357. #define MIN_IPS_TO_NOTE_ANYTHING 1
  358. /** When reporting geoip data about countries, round up to the nearest
  359. * multiple of this value. */
  360. #define IP_GRANULARITY 8
  361. /** Helper type: used to sort per-country totals by value. */
  362. typedef struct c_hist_t {
  363. char country[3]; /**< Two-letter country code. */
  364. unsigned total; /**< Total IP addresses seen in this country. */
  365. } c_hist_t;
  366. /** Sorting helper: return -1, 1, or 0 based on comparison of two
  367. * geoip_ipv4_entry_t. Sort in descending order of total, and then by country
  368. * code. */
  369. static int
  370. c_hist_compare_(const void **_a, const void **_b)
  371. {
  372. const c_hist_t *a = *_a, *b = *_b;
  373. if (a->total > b->total)
  374. return -1;
  375. else if (a->total < b->total)
  376. return 1;
  377. else
  378. return strcmp(a->country, b->country);
  379. }
  380. /** When there are incomplete directory requests at the end of a 24-hour
  381. * period, consider those requests running for longer than this timeout as
  382. * failed, the others as still running. */
  383. #define DIRREQ_TIMEOUT (10*60)
  384. /** Entry in a map from either chan->global_identifier for direct requests
  385. * or a unique circuit identifier for tunneled requests to request time,
  386. * response size, and completion time of a network status request. Used to
  387. * measure download times of requests to derive average client
  388. * bandwidths. */
  389. typedef struct dirreq_map_entry_t {
  390. HT_ENTRY(dirreq_map_entry_t) node;
  391. /** Unique identifier for this network status request; this is either the
  392. * chan->global_identifier of the dir channel (direct request) or a new
  393. * locally unique identifier of a circuit (tunneled request). This ID is
  394. * only unique among other direct or tunneled requests, respectively. */
  395. uint64_t dirreq_id;
  396. unsigned int state:3; /**< State of this directory request. */
  397. unsigned int type:1; /**< Is this a direct or a tunneled request? */
  398. unsigned int completed:1; /**< Is this request complete? */
  399. /** When did we receive the request and started sending the response? */
  400. struct timeval request_time;
  401. size_t response_size; /**< What is the size of the response in bytes? */
  402. struct timeval completion_time; /**< When did the request succeed? */
  403. } dirreq_map_entry_t;
  404. /** Map of all directory requests asking for v2 or v3 network statuses in
  405. * the current geoip-stats interval. Values are
  406. * of type *<b>dirreq_map_entry_t</b>. */
  407. static HT_HEAD(dirreqmap, dirreq_map_entry_t) dirreq_map =
  408. HT_INITIALIZER();
  409. static int
  410. dirreq_map_ent_eq(const dirreq_map_entry_t *a,
  411. const dirreq_map_entry_t *b)
  412. {
  413. return a->dirreq_id == b->dirreq_id && a->type == b->type;
  414. }
  415. /* DOCDOC dirreq_map_ent_hash */
  416. static unsigned
  417. dirreq_map_ent_hash(const dirreq_map_entry_t *entry)
  418. {
  419. unsigned u = (unsigned) entry->dirreq_id;
  420. u += entry->type << 20;
  421. return u;
  422. }
  423. HT_PROTOTYPE(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash,
  424. dirreq_map_ent_eq)
  425. HT_GENERATE2(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash,
  426. dirreq_map_ent_eq, 0.6, tor_reallocarray_, tor_free_)
  427. /** Helper: Put <b>entry</b> into map of directory requests using
  428. * <b>type</b> and <b>dirreq_id</b> as key parts. If there is
  429. * already an entry for that key, print out a BUG warning and return. */
  430. static void
  431. dirreq_map_put_(dirreq_map_entry_t *entry, dirreq_type_t type,
  432. uint64_t dirreq_id)
  433. {
  434. dirreq_map_entry_t *old_ent;
  435. tor_assert(entry->type == type);
  436. tor_assert(entry->dirreq_id == dirreq_id);
  437. /* XXXX we could switch this to HT_INSERT some time, since it seems that
  438. * this bug doesn't happen. But since this function doesn't seem to be
  439. * critical-path, it's sane to leave it alone. */
  440. old_ent = HT_REPLACE(dirreqmap, &dirreq_map, entry);
  441. if (old_ent && old_ent != entry) {
  442. log_warn(LD_BUG, "Error when putting directory request into local "
  443. "map. There was already an entry for the same identifier.");
  444. return;
  445. }
  446. }
  447. /** Helper: Look up and return an entry in the map of directory requests
  448. * using <b>type</b> and <b>dirreq_id</b> as key parts. If there
  449. * is no such entry, return NULL. */
  450. static dirreq_map_entry_t *
  451. dirreq_map_get_(dirreq_type_t type, uint64_t dirreq_id)
  452. {
  453. dirreq_map_entry_t lookup;
  454. lookup.type = type;
  455. lookup.dirreq_id = dirreq_id;
  456. return HT_FIND(dirreqmap, &dirreq_map, &lookup);
  457. }
  458. /** Note that an either direct or tunneled (see <b>type</b>) directory
  459. * request for a v3 network status with unique ID <b>dirreq_id</b> of size
  460. * <b>response_size</b> has started. */
  461. void
  462. geoip_start_dirreq(uint64_t dirreq_id, size_t response_size,
  463. dirreq_type_t type)
  464. {
  465. dirreq_map_entry_t *ent;
  466. if (!get_options()->DirReqStatistics)
  467. return;
  468. ent = tor_malloc_zero(sizeof(dirreq_map_entry_t));
  469. ent->dirreq_id = dirreq_id;
  470. tor_gettimeofday(&ent->request_time);
  471. ent->response_size = response_size;
  472. ent->type = type;
  473. dirreq_map_put_(ent, type, dirreq_id);
  474. }
  475. /** Change the state of the either direct or tunneled (see <b>type</b>)
  476. * directory request with <b>dirreq_id</b> to <b>new_state</b> and
  477. * possibly mark it as completed. If no entry can be found for the given
  478. * key parts (e.g., if this is a directory request that we are not
  479. * measuring, or one that was started in the previous measurement period),
  480. * or if the state cannot be advanced to <b>new_state</b>, do nothing. */
  481. void
  482. geoip_change_dirreq_state(uint64_t dirreq_id, dirreq_type_t type,
  483. dirreq_state_t new_state)
  484. {
  485. dirreq_map_entry_t *ent;
  486. if (!get_options()->DirReqStatistics)
  487. return;
  488. ent = dirreq_map_get_(type, dirreq_id);
  489. if (!ent)
  490. return;
  491. if (new_state == DIRREQ_IS_FOR_NETWORK_STATUS)
  492. return;
  493. if (new_state - 1 != ent->state)
  494. return;
  495. ent->state = new_state;
  496. if ((type == DIRREQ_DIRECT &&
  497. new_state == DIRREQ_FLUSHING_DIR_CONN_FINISHED) ||
  498. (type == DIRREQ_TUNNELED &&
  499. new_state == DIRREQ_CHANNEL_BUFFER_FLUSHED)) {
  500. tor_gettimeofday(&ent->completion_time);
  501. ent->completed = 1;
  502. }
  503. }
  504. /** Return the bridge-ip-transports string that should be inserted in
  505. * our extra-info descriptor. Return NULL if the bridge-ip-transports
  506. * line should be empty. */
  507. char *
  508. geoip_get_transport_history(void)
  509. {
  510. unsigned granularity = IP_GRANULARITY;
  511. /** String hash table (name of transport) -> (number of users). */
  512. strmap_t *transport_counts = strmap_new();
  513. /** Smartlist that contains copies of the names of the transports
  514. that have been used. */
  515. smartlist_t *transports_used = smartlist_new();
  516. /* Special string to signify that no transport was used for this
  517. connection. Pluggable transport names can't have symbols in their
  518. names, so this string will never collide with a real transport. */
  519. static const char* no_transport_str = "<OR>";
  520. clientmap_entry_t **ent;
  521. smartlist_t *string_chunks = smartlist_new();
  522. char *the_string = NULL;
  523. /* If we haven't seen any clients yet, return NULL. */
  524. if (HT_EMPTY(&client_history))
  525. goto done;
  526. /** We do the following steps to form the transport history string:
  527. * a) Foreach client that uses a pluggable transport, we increase the
  528. * times that transport was used by one. If the client did not use
  529. * a transport, we increase the number of times someone connected
  530. * without obfuscation.
  531. * b) Foreach transport we observed, we write its transport history
  532. * string and push it to string_chunks. So, for example, if we've
  533. * seen 665 obfs2 clients, we write "obfs2=665".
  534. * c) We concatenate string_chunks to form the final string.
  535. */
  536. log_debug(LD_GENERAL,"Starting iteration for transport history. %d clients.",
  537. HT_SIZE(&client_history));
  538. /* Loop through all clients. */
  539. HT_FOREACH(ent, clientmap, &client_history) {
  540. uintptr_t val;
  541. void *ptr;
  542. const char *transport_name = (*ent)->transport_name;
  543. if (!transport_name)
  544. transport_name = no_transport_str;
  545. /* Increase the count for this transport name. */
  546. ptr = strmap_get(transport_counts, transport_name);
  547. val = (uintptr_t)ptr;
  548. val++;
  549. ptr = (void*)val;
  550. strmap_set(transport_counts, transport_name, ptr);
  551. /* If it's the first time we see this transport, note it. */
  552. if (val == 1)
  553. smartlist_add_strdup(transports_used, transport_name);
  554. log_debug(LD_GENERAL, "Client from '%s' with transport '%s'. "
  555. "I've now seen %d clients.",
  556. safe_str_client(fmt_addr(&(*ent)->addr)),
  557. transport_name ? transport_name : "<no transport>",
  558. (int)val);
  559. }
  560. /* Sort the transport names (helps with unit testing). */
  561. smartlist_sort_strings(transports_used);
  562. /* Loop through all seen transports. */
  563. SMARTLIST_FOREACH_BEGIN(transports_used, const char *, transport_name) {
  564. void *transport_count_ptr = strmap_get(transport_counts, transport_name);
  565. uintptr_t transport_count = (uintptr_t) transport_count_ptr;
  566. log_debug(LD_GENERAL, "We got %"PRIu64" clients with transport '%s'.",
  567. ((uint64_t)transport_count), transport_name);
  568. smartlist_add_asprintf(string_chunks, "%s=%"PRIu64,
  569. transport_name,
  570. (round_uint64_to_next_multiple_of(
  571. (uint64_t)transport_count,
  572. granularity)));
  573. } SMARTLIST_FOREACH_END(transport_name);
  574. the_string = smartlist_join_strings(string_chunks, ",", 0, NULL);
  575. log_debug(LD_GENERAL, "Final bridge-ip-transports string: '%s'", the_string);
  576. done:
  577. strmap_free(transport_counts, NULL);
  578. SMARTLIST_FOREACH(transports_used, char *, s, tor_free(s));
  579. smartlist_free(transports_used);
  580. SMARTLIST_FOREACH(string_chunks, char *, s, tor_free(s));
  581. smartlist_free(string_chunks);
  582. return the_string;
  583. }
  584. /** Return a newly allocated comma-separated string containing statistics
  585. * on network status downloads. The string contains the number of completed
  586. * requests, timeouts, and still running requests as well as the download
  587. * times by deciles and quartiles. Return NULL if we have not observed
  588. * requests for long enough. */
  589. static char *
  590. geoip_get_dirreq_history(dirreq_type_t type)
  591. {
  592. char *result = NULL;
  593. buf_t *buf = NULL;
  594. smartlist_t *dirreq_completed = NULL;
  595. uint32_t complete = 0, timeouts = 0, running = 0;
  596. dirreq_map_entry_t **ptr, **next;
  597. struct timeval now;
  598. tor_gettimeofday(&now);
  599. dirreq_completed = smartlist_new();
  600. for (ptr = HT_START(dirreqmap, &dirreq_map); ptr; ptr = next) {
  601. dirreq_map_entry_t *ent = *ptr;
  602. if (ent->type != type) {
  603. next = HT_NEXT(dirreqmap, &dirreq_map, ptr);
  604. continue;
  605. } else {
  606. if (ent->completed) {
  607. smartlist_add(dirreq_completed, ent);
  608. complete++;
  609. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr);
  610. } else {
  611. if (tv_mdiff(&ent->request_time, &now) / 1000 > DIRREQ_TIMEOUT)
  612. timeouts++;
  613. else
  614. running++;
  615. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr);
  616. tor_free(ent);
  617. }
  618. }
  619. }
  620. #define DIR_REQ_GRANULARITY 4
  621. complete = round_uint32_to_next_multiple_of(complete,
  622. DIR_REQ_GRANULARITY);
  623. timeouts = round_uint32_to_next_multiple_of(timeouts,
  624. DIR_REQ_GRANULARITY);
  625. running = round_uint32_to_next_multiple_of(running,
  626. DIR_REQ_GRANULARITY);
  627. buf = buf_new_with_capacity(1024);
  628. buf_add_printf(buf, "complete=%u,timeout=%u,"
  629. "running=%u", complete, timeouts, running);
  630. #define MIN_DIR_REQ_RESPONSES 16
  631. if (complete >= MIN_DIR_REQ_RESPONSES) {
  632. uint32_t *dltimes;
  633. /* We may have rounded 'completed' up. Here we want to use the
  634. * real value. */
  635. complete = smartlist_len(dirreq_completed);
  636. dltimes = tor_calloc(complete, sizeof(uint32_t));
  637. SMARTLIST_FOREACH_BEGIN(dirreq_completed, dirreq_map_entry_t *, ent) {
  638. uint32_t bytes_per_second;
  639. uint32_t time_diff_ = (uint32_t) tv_mdiff(&ent->request_time,
  640. &ent->completion_time);
  641. if (time_diff_ == 0)
  642. time_diff_ = 1; /* Avoid DIV/0; "instant" answers are impossible
  643. * by law of nature or something, but a millisecond
  644. * is a bit greater than "instantly" */
  645. bytes_per_second = (uint32_t)(1000 * ent->response_size / time_diff_);
  646. dltimes[ent_sl_idx] = bytes_per_second;
  647. } SMARTLIST_FOREACH_END(ent);
  648. median_uint32(dltimes, complete); /* sorts as a side effect. */
  649. buf_add_printf(buf,
  650. ",min=%u,d1=%u,d2=%u,q1=%u,d3=%u,d4=%u,md=%u,"
  651. "d6=%u,d7=%u,q3=%u,d8=%u,d9=%u,max=%u",
  652. dltimes[0],
  653. dltimes[1*complete/10-1],
  654. dltimes[2*complete/10-1],
  655. dltimes[1*complete/4-1],
  656. dltimes[3*complete/10-1],
  657. dltimes[4*complete/10-1],
  658. dltimes[5*complete/10-1],
  659. dltimes[6*complete/10-1],
  660. dltimes[7*complete/10-1],
  661. dltimes[3*complete/4-1],
  662. dltimes[8*complete/10-1],
  663. dltimes[9*complete/10-1],
  664. dltimes[complete-1]);
  665. tor_free(dltimes);
  666. }
  667. result = buf_extract(buf, NULL);
  668. SMARTLIST_FOREACH(dirreq_completed, dirreq_map_entry_t *, ent,
  669. tor_free(ent));
  670. smartlist_free(dirreq_completed);
  671. buf_free(buf);
  672. return result;
  673. }
  674. /** Store a newly allocated comma-separated string in
  675. * *<a>country_str</a> containing entries for all the countries from
  676. * which we've seen enough clients connect as a bridge, directory
  677. * server, or entry guard. The entry format is cc=num where num is the
  678. * number of IPs we've seen connecting from that country, and cc is a
  679. * lowercased country code. *<a>country_str</a> is set to NULL if
  680. * we're not ready to export per country data yet.
  681. *
  682. * Store a newly allocated comma-separated string in <a>ipver_str</a>
  683. * containing entries for clients connecting over IPv4 and IPv6. The
  684. * format is family=num where num is the nubmer of IPs we've seen
  685. * connecting over that protocol family, and family is 'v4' or 'v6'.
  686. *
  687. * Return 0 on success and -1 if we're missing geoip data. */
  688. int
  689. geoip_get_client_history(geoip_client_action_t action,
  690. char **country_str, char **ipver_str)
  691. {
  692. unsigned granularity = IP_GRANULARITY;
  693. smartlist_t *entries = NULL;
  694. int n_countries = geoip_get_n_countries();
  695. int i;
  696. clientmap_entry_t **cm_ent;
  697. unsigned *counts = NULL;
  698. unsigned total = 0;
  699. unsigned ipv4_count = 0, ipv6_count = 0;
  700. if (!geoip_is_loaded(AF_INET) && !geoip_is_loaded(AF_INET6))
  701. return -1;
  702. counts = tor_calloc(n_countries, sizeof(unsigned));
  703. HT_FOREACH(cm_ent, clientmap, &client_history) {
  704. int country;
  705. if ((*cm_ent)->action != (int)action)
  706. continue;
  707. country = geoip_get_country_by_addr(&(*cm_ent)->addr);
  708. if (country < 0)
  709. country = 0; /** unresolved requests are stored at index 0. */
  710. tor_assert(0 <= country && country < n_countries);
  711. ++counts[country];
  712. ++total;
  713. switch (tor_addr_family(&(*cm_ent)->addr)) {
  714. case AF_INET:
  715. ipv4_count++;
  716. break;
  717. case AF_INET6:
  718. ipv6_count++;
  719. break;
  720. }
  721. }
  722. if (ipver_str) {
  723. smartlist_t *chunks = smartlist_new();
  724. smartlist_add_asprintf(chunks, "v4=%u",
  725. round_to_next_multiple_of(ipv4_count, granularity));
  726. smartlist_add_asprintf(chunks, "v6=%u",
  727. round_to_next_multiple_of(ipv6_count, granularity));
  728. *ipver_str = smartlist_join_strings(chunks, ",", 0, NULL);
  729. SMARTLIST_FOREACH(chunks, char *, c, tor_free(c));
  730. smartlist_free(chunks);
  731. }
  732. /* Don't record per country data if we haven't seen enough IPs. */
  733. if (total < MIN_IPS_TO_NOTE_ANYTHING) {
  734. tor_free(counts);
  735. if (country_str)
  736. *country_str = NULL;
  737. return 0;
  738. }
  739. /* Make a list of c_hist_t */
  740. entries = smartlist_new();
  741. for (i = 0; i < n_countries; ++i) {
  742. unsigned c = counts[i];
  743. const char *countrycode;
  744. c_hist_t *ent;
  745. /* Only report a country if it has a minimum number of IPs. */
  746. if (c >= MIN_IPS_TO_NOTE_COUNTRY) {
  747. c = round_to_next_multiple_of(c, granularity);
  748. countrycode = geoip_get_country_name(i);
  749. ent = tor_malloc(sizeof(c_hist_t));
  750. strlcpy(ent->country, countrycode, sizeof(ent->country));
  751. ent->total = c;
  752. smartlist_add(entries, ent);
  753. }
  754. }
  755. /* Sort entries. Note that we must do this _AFTER_ rounding, or else
  756. * the sort order could leak info. */
  757. smartlist_sort(entries, c_hist_compare_);
  758. if (country_str) {
  759. smartlist_t *chunks = smartlist_new();
  760. SMARTLIST_FOREACH(entries, c_hist_t *, ch, {
  761. smartlist_add_asprintf(chunks, "%s=%u", ch->country, ch->total);
  762. });
  763. *country_str = smartlist_join_strings(chunks, ",", 0, NULL);
  764. SMARTLIST_FOREACH(chunks, char *, c, tor_free(c));
  765. smartlist_free(chunks);
  766. }
  767. SMARTLIST_FOREACH(entries, c_hist_t *, c, tor_free(c));
  768. smartlist_free(entries);
  769. tor_free(counts);
  770. return 0;
  771. }
  772. /** Return a newly allocated string holding the per-country request history
  773. * for v3 network statuses in a format suitable for an extra-info document,
  774. * or NULL on failure. */
  775. char *
  776. geoip_get_request_history(void)
  777. {
  778. smartlist_t *entries, *strings;
  779. char *result;
  780. unsigned granularity = IP_GRANULARITY;
  781. entries = smartlist_new();
  782. SMARTLIST_FOREACH_BEGIN(geoip_get_countries(), const geoip_country_t *, c) {
  783. uint32_t tot = 0;
  784. c_hist_t *ent;
  785. if ((size_t)c_sl_idx < n_v3_ns_requests_len)
  786. tot = n_v3_ns_requests[c_sl_idx];
  787. else
  788. tot = 0;
  789. if (!tot)
  790. continue;
  791. ent = tor_malloc_zero(sizeof(c_hist_t));
  792. strlcpy(ent->country, c->countrycode, sizeof(ent->country));
  793. ent->total = round_to_next_multiple_of(tot, granularity);
  794. smartlist_add(entries, ent);
  795. } SMARTLIST_FOREACH_END(c);
  796. smartlist_sort(entries, c_hist_compare_);
  797. strings = smartlist_new();
  798. SMARTLIST_FOREACH(entries, c_hist_t *, ent, {
  799. smartlist_add_asprintf(strings, "%s=%u", ent->country, ent->total);
  800. });
  801. result = smartlist_join_strings(strings, ",", 0, NULL);
  802. SMARTLIST_FOREACH(strings, char *, cp, tor_free(cp));
  803. SMARTLIST_FOREACH(entries, c_hist_t *, ent, tor_free(ent));
  804. smartlist_free(strings);
  805. smartlist_free(entries);
  806. return result;
  807. }
  808. /** Start time of directory request stats or 0 if we're not collecting
  809. * directory request statistics. */
  810. static time_t start_of_dirreq_stats_interval;
  811. /** Initialize directory request stats. */
  812. void
  813. geoip_dirreq_stats_init(time_t now)
  814. {
  815. start_of_dirreq_stats_interval = now;
  816. }
  817. /** Reset counters for dirreq stats. */
  818. void
  819. geoip_reset_dirreq_stats(time_t now)
  820. {
  821. memset(n_v3_ns_requests, 0,
  822. n_v3_ns_requests_len * sizeof(uint32_t));
  823. {
  824. clientmap_entry_t **ent, **next, *this;
  825. for (ent = HT_START(clientmap, &client_history); ent != NULL;
  826. ent = next) {
  827. if ((*ent)->action == GEOIP_CLIENT_NETWORKSTATUS) {
  828. this = *ent;
  829. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  830. clientmap_entry_free(this);
  831. } else {
  832. next = HT_NEXT(clientmap, &client_history, ent);
  833. }
  834. }
  835. }
  836. memset(ns_v3_responses, 0, sizeof(ns_v3_responses));
  837. {
  838. dirreq_map_entry_t **ent, **next, *this;
  839. for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) {
  840. this = *ent;
  841. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent);
  842. tor_free(this);
  843. }
  844. }
  845. start_of_dirreq_stats_interval = now;
  846. }
  847. /** Stop collecting directory request stats in a way that we can re-start
  848. * doing so in geoip_dirreq_stats_init(). */
  849. void
  850. geoip_dirreq_stats_term(void)
  851. {
  852. geoip_reset_dirreq_stats(0);
  853. }
  854. /** Return a newly allocated string containing the dirreq statistics
  855. * until <b>now</b>, or NULL if we're not collecting dirreq stats. Caller
  856. * must ensure start_of_dirreq_stats_interval is in the past. */
  857. char *
  858. geoip_format_dirreq_stats(time_t now)
  859. {
  860. char t[ISO_TIME_LEN+1];
  861. int i;
  862. char *v3_ips_string = NULL, *v3_reqs_string = NULL,
  863. *v3_direct_dl_string = NULL, *v3_tunneled_dl_string = NULL;
  864. char *result = NULL;
  865. if (!start_of_dirreq_stats_interval)
  866. return NULL; /* Not initialized. */
  867. tor_assert(now >= start_of_dirreq_stats_interval);
  868. format_iso_time(t, now);
  869. geoip_get_client_history(GEOIP_CLIENT_NETWORKSTATUS, &v3_ips_string, NULL);
  870. v3_reqs_string = geoip_get_request_history();
  871. #define RESPONSE_GRANULARITY 8
  872. for (i = 0; i < GEOIP_NS_RESPONSE_NUM; i++) {
  873. ns_v3_responses[i] = round_uint32_to_next_multiple_of(
  874. ns_v3_responses[i], RESPONSE_GRANULARITY);
  875. }
  876. #undef RESPONSE_GRANULARITY
  877. v3_direct_dl_string = geoip_get_dirreq_history(DIRREQ_DIRECT);
  878. v3_tunneled_dl_string = geoip_get_dirreq_history(DIRREQ_TUNNELED);
  879. /* Put everything together into a single string. */
  880. tor_asprintf(&result, "dirreq-stats-end %s (%d s)\n"
  881. "dirreq-v3-ips %s\n"
  882. "dirreq-v3-reqs %s\n"
  883. "dirreq-v3-resp ok=%u,not-enough-sigs=%u,unavailable=%u,"
  884. "not-found=%u,not-modified=%u,busy=%u\n"
  885. "dirreq-v3-direct-dl %s\n"
  886. "dirreq-v3-tunneled-dl %s\n",
  887. t,
  888. (unsigned) (now - start_of_dirreq_stats_interval),
  889. v3_ips_string ? v3_ips_string : "",
  890. v3_reqs_string ? v3_reqs_string : "",
  891. ns_v3_responses[GEOIP_SUCCESS],
  892. ns_v3_responses[GEOIP_REJECT_NOT_ENOUGH_SIGS],
  893. ns_v3_responses[GEOIP_REJECT_UNAVAILABLE],
  894. ns_v3_responses[GEOIP_REJECT_NOT_FOUND],
  895. ns_v3_responses[GEOIP_REJECT_NOT_MODIFIED],
  896. ns_v3_responses[GEOIP_REJECT_BUSY],
  897. v3_direct_dl_string ? v3_direct_dl_string : "",
  898. v3_tunneled_dl_string ? v3_tunneled_dl_string : "");
  899. /* Free partial strings. */
  900. tor_free(v3_ips_string);
  901. tor_free(v3_reqs_string);
  902. tor_free(v3_direct_dl_string);
  903. tor_free(v3_tunneled_dl_string);
  904. return result;
  905. }
  906. /** If 24 hours have passed since the beginning of the current dirreq
  907. * stats period, write dirreq stats to $DATADIR/stats/dirreq-stats
  908. * (possibly overwriting an existing file) and reset counters. Return
  909. * when we would next want to write dirreq stats or 0 if we never want to
  910. * write. */
  911. time_t
  912. geoip_dirreq_stats_write(time_t now)
  913. {
  914. char *str = NULL;
  915. if (!start_of_dirreq_stats_interval)
  916. return 0; /* Not initialized. */
  917. if (start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL > now)
  918. goto done; /* Not ready to write. */
  919. /* Discard all items in the client history that are too old. */
  920. geoip_remove_old_clients(start_of_dirreq_stats_interval);
  921. /* Generate history string .*/
  922. str = geoip_format_dirreq_stats(now);
  923. if (! str)
  924. goto done;
  925. /* Write dirreq-stats string to disk. */
  926. if (!check_or_create_data_subdir("stats")) {
  927. write_to_data_subdir("stats", "dirreq-stats", str, "dirreq statistics");
  928. /* Reset measurement interval start. */
  929. geoip_reset_dirreq_stats(now);
  930. }
  931. done:
  932. tor_free(str);
  933. return start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL;
  934. }
  935. /** Start time of bridge stats or 0 if we're not collecting bridge
  936. * statistics. */
  937. static time_t start_of_bridge_stats_interval;
  938. /** Initialize bridge stats. */
  939. void
  940. geoip_bridge_stats_init(time_t now)
  941. {
  942. start_of_bridge_stats_interval = now;
  943. }
  944. /** Stop collecting bridge stats in a way that we can re-start doing so in
  945. * geoip_bridge_stats_init(). */
  946. void
  947. geoip_bridge_stats_term(void)
  948. {
  949. client_history_clear();
  950. start_of_bridge_stats_interval = 0;
  951. }
  952. /** Validate a bridge statistics string as it would be written to a
  953. * current extra-info descriptor. Return 1 if the string is valid and
  954. * recent enough, or 0 otherwise. */
  955. static int
  956. validate_bridge_stats(const char *stats_str, time_t now)
  957. {
  958. char stats_end_str[ISO_TIME_LEN+1], stats_start_str[ISO_TIME_LEN+1],
  959. *eos;
  960. const char *BRIDGE_STATS_END = "bridge-stats-end ";
  961. const char *BRIDGE_IPS = "bridge-ips ";
  962. const char *BRIDGE_IPS_EMPTY_LINE = "bridge-ips\n";
  963. const char *BRIDGE_TRANSPORTS = "bridge-ip-transports ";
  964. const char *BRIDGE_TRANSPORTS_EMPTY_LINE = "bridge-ip-transports\n";
  965. const char *tmp;
  966. time_t stats_end_time;
  967. int seconds;
  968. tor_assert(stats_str);
  969. /* Parse timestamp and number of seconds from
  970. "bridge-stats-end YYYY-MM-DD HH:MM:SS (N s)" */
  971. tmp = find_str_at_start_of_line(stats_str, BRIDGE_STATS_END);
  972. if (!tmp)
  973. return 0;
  974. tmp += strlen(BRIDGE_STATS_END);
  975. if (strlen(tmp) < ISO_TIME_LEN + 6)
  976. return 0;
  977. strlcpy(stats_end_str, tmp, sizeof(stats_end_str));
  978. if (parse_iso_time(stats_end_str, &stats_end_time) < 0)
  979. return 0;
  980. if (stats_end_time < now - (25*60*60) ||
  981. stats_end_time > now + (1*60*60))
  982. return 0;
  983. seconds = (int)strtol(tmp + ISO_TIME_LEN + 2, &eos, 10);
  984. if (!eos || seconds < 23*60*60)
  985. return 0;
  986. format_iso_time(stats_start_str, stats_end_time - seconds);
  987. /* Parse: "bridge-ips CC=N,CC=N,..." */
  988. tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS);
  989. if (!tmp) {
  990. /* Look if there is an empty "bridge-ips" line */
  991. tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS_EMPTY_LINE);
  992. if (!tmp)
  993. return 0;
  994. }
  995. /* Parse: "bridge-ip-transports PT=N,PT=N,..." */
  996. tmp = find_str_at_start_of_line(stats_str, BRIDGE_TRANSPORTS);
  997. if (!tmp) {
  998. /* Look if there is an empty "bridge-ip-transports" line */
  999. tmp = find_str_at_start_of_line(stats_str, BRIDGE_TRANSPORTS_EMPTY_LINE);
  1000. if (!tmp)
  1001. return 0;
  1002. }
  1003. return 1;
  1004. }
  1005. /** Most recent bridge statistics formatted to be written to extra-info
  1006. * descriptors. */
  1007. static char *bridge_stats_extrainfo = NULL;
  1008. /** Return a newly allocated string holding our bridge usage stats by country
  1009. * in a format suitable for inclusion in an extrainfo document. Return NULL on
  1010. * failure. */
  1011. char *
  1012. geoip_format_bridge_stats(time_t now)
  1013. {
  1014. char *out = NULL;
  1015. char *country_data = NULL, *ipver_data = NULL, *transport_data = NULL;
  1016. long duration = now - start_of_bridge_stats_interval;
  1017. char written[ISO_TIME_LEN+1];
  1018. if (duration < 0)
  1019. return NULL;
  1020. if (!start_of_bridge_stats_interval)
  1021. return NULL; /* Not initialized. */
  1022. format_iso_time(written, now);
  1023. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data);
  1024. transport_data = geoip_get_transport_history();
  1025. tor_asprintf(&out,
  1026. "bridge-stats-end %s (%ld s)\n"
  1027. "bridge-ips %s\n"
  1028. "bridge-ip-versions %s\n"
  1029. "bridge-ip-transports %s\n",
  1030. written, duration,
  1031. country_data ? country_data : "",
  1032. ipver_data ? ipver_data : "",
  1033. transport_data ? transport_data : "");
  1034. tor_free(country_data);
  1035. tor_free(ipver_data);
  1036. tor_free(transport_data);
  1037. return out;
  1038. }
  1039. /** Return a newly allocated string holding our bridge usage stats by country
  1040. * in a format suitable for the answer to a controller request. Return NULL on
  1041. * failure. */
  1042. static char *
  1043. format_bridge_stats_controller(time_t now)
  1044. {
  1045. char *out = NULL, *country_data = NULL, *ipver_data = NULL;
  1046. char started[ISO_TIME_LEN+1];
  1047. (void) now;
  1048. format_iso_time(started, start_of_bridge_stats_interval);
  1049. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data);
  1050. tor_asprintf(&out,
  1051. "TimeStarted=\"%s\" CountrySummary=%s IPVersions=%s",
  1052. started,
  1053. country_data ? country_data : "",
  1054. ipver_data ? ipver_data : "");
  1055. tor_free(country_data);
  1056. tor_free(ipver_data);
  1057. return out;
  1058. }
  1059. /** Return a newly allocated string holding our bridge usage stats by
  1060. * country in a format suitable for inclusion in our heartbeat
  1061. * message. Return NULL on failure. */
  1062. char *
  1063. format_client_stats_heartbeat(time_t now)
  1064. {
  1065. const int n_hours = 6;
  1066. char *out = NULL;
  1067. int n_clients = 0;
  1068. clientmap_entry_t **ent;
  1069. unsigned cutoff = (unsigned)( (now-n_hours*3600)/60 );
  1070. if (!start_of_bridge_stats_interval)
  1071. return NULL; /* Not initialized. */
  1072. /* count unique IPs */
  1073. HT_FOREACH(ent, clientmap, &client_history) {
  1074. /* only count directly connecting clients */
  1075. if ((*ent)->action != GEOIP_CLIENT_CONNECT)
  1076. continue;
  1077. if ((*ent)->last_seen_in_minutes < cutoff)
  1078. continue;
  1079. n_clients++;
  1080. }
  1081. tor_asprintf(&out, "Heartbeat: "
  1082. "In the last %d hours, I have seen %d unique clients.",
  1083. n_hours,
  1084. n_clients);
  1085. return out;
  1086. }
  1087. /** Write bridge statistics to $DATADIR/stats/bridge-stats and return
  1088. * when we should next try to write statistics. */
  1089. time_t
  1090. geoip_bridge_stats_write(time_t now)
  1091. {
  1092. char *val = NULL;
  1093. /* Check if 24 hours have passed since starting measurements. */
  1094. if (now < start_of_bridge_stats_interval + WRITE_STATS_INTERVAL)
  1095. return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL;
  1096. /* Discard all items in the client history that are too old. */
  1097. geoip_remove_old_clients(start_of_bridge_stats_interval);
  1098. /* Generate formatted string */
  1099. val = geoip_format_bridge_stats(now);
  1100. if (val == NULL)
  1101. goto done;
  1102. /* Update the stored value. */
  1103. tor_free(bridge_stats_extrainfo);
  1104. bridge_stats_extrainfo = val;
  1105. start_of_bridge_stats_interval = now;
  1106. /* Write it to disk. */
  1107. if (!check_or_create_data_subdir("stats")) {
  1108. write_to_data_subdir("stats", "bridge-stats",
  1109. bridge_stats_extrainfo, "bridge statistics");
  1110. /* Tell the controller, "hey, there are clients!" */
  1111. {
  1112. char *controller_str = format_bridge_stats_controller(now);
  1113. if (controller_str)
  1114. control_event_clients_seen(controller_str);
  1115. tor_free(controller_str);
  1116. }
  1117. }
  1118. done:
  1119. return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL;
  1120. }
  1121. /** Try to load the most recent bridge statistics from disk, unless we
  1122. * have finished a measurement interval lately, and check whether they
  1123. * are still recent enough. */
  1124. static void
  1125. load_bridge_stats(time_t now)
  1126. {
  1127. char *fname, *contents;
  1128. if (bridge_stats_extrainfo)
  1129. return;
  1130. fname = get_datadir_fname2("stats", "bridge-stats");
  1131. contents = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
  1132. if (contents && validate_bridge_stats(contents, now)) {
  1133. bridge_stats_extrainfo = contents;
  1134. } else {
  1135. tor_free(contents);
  1136. }
  1137. tor_free(fname);
  1138. }
  1139. /** Return most recent bridge statistics for inclusion in extra-info
  1140. * descriptors, or NULL if we don't have recent bridge statistics. */
  1141. const char *
  1142. geoip_get_bridge_stats_extrainfo(time_t now)
  1143. {
  1144. load_bridge_stats(now);
  1145. return bridge_stats_extrainfo;
  1146. }
  1147. /** Return a new string containing the recent bridge statistics to be returned
  1148. * to controller clients, or NULL if we don't have any bridge statistics. */
  1149. char *
  1150. geoip_get_bridge_stats_controller(time_t now)
  1151. {
  1152. return format_bridge_stats_controller(now);
  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. /** Reset counters for entry stats. */
  1164. void
  1165. geoip_reset_entry_stats(time_t now)
  1166. {
  1167. client_history_clear();
  1168. start_of_entry_stats_interval = now;
  1169. }
  1170. /** Stop collecting entry stats in a way that we can re-start doing so in
  1171. * geoip_entry_stats_init(). */
  1172. void
  1173. geoip_entry_stats_term(void)
  1174. {
  1175. geoip_reset_entry_stats(0);
  1176. }
  1177. /** Return a newly allocated string containing the entry statistics
  1178. * until <b>now</b>, or NULL if we're not collecting entry stats. Caller
  1179. * must ensure start_of_entry_stats_interval lies in the past. */
  1180. char *
  1181. geoip_format_entry_stats(time_t now)
  1182. {
  1183. char t[ISO_TIME_LEN+1];
  1184. char *data = NULL;
  1185. char *result;
  1186. if (!start_of_entry_stats_interval)
  1187. return NULL; /* Not initialized. */
  1188. tor_assert(now >= start_of_entry_stats_interval);
  1189. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &data, NULL);
  1190. format_iso_time(t, now);
  1191. tor_asprintf(&result,
  1192. "entry-stats-end %s (%u s)\n"
  1193. "entry-ips %s\n",
  1194. t, (unsigned) (now - start_of_entry_stats_interval),
  1195. data ? data : "");
  1196. tor_free(data);
  1197. return result;
  1198. }
  1199. /** If 24 hours have passed since the beginning of the current entry stats
  1200. * period, write entry stats to $DATADIR/stats/entry-stats (possibly
  1201. * overwriting an existing file) and reset counters. Return when we would
  1202. * next want to write entry stats or 0 if we never want to write. */
  1203. time_t
  1204. geoip_entry_stats_write(time_t now)
  1205. {
  1206. char *str = NULL;
  1207. if (!start_of_entry_stats_interval)
  1208. return 0; /* Not initialized. */
  1209. if (start_of_entry_stats_interval + WRITE_STATS_INTERVAL > now)
  1210. goto done; /* Not ready to write. */
  1211. /* Discard all items in the client history that are too old. */
  1212. geoip_remove_old_clients(start_of_entry_stats_interval);
  1213. /* Generate history string .*/
  1214. str = geoip_format_entry_stats(now);
  1215. /* Write entry-stats string to disk. */
  1216. if (!check_or_create_data_subdir("stats")) {
  1217. write_to_data_subdir("stats", "entry-stats", str, "entry statistics");
  1218. /* Reset measurement interval start. */
  1219. geoip_reset_entry_stats(now);
  1220. }
  1221. done:
  1222. tor_free(str);
  1223. return start_of_entry_stats_interval + WRITE_STATS_INTERVAL;
  1224. }
  1225. /** Release all storage held in this file. */
  1226. void
  1227. geoip_stats_free_all(void)
  1228. {
  1229. {
  1230. clientmap_entry_t **ent, **next, *this;
  1231. for (ent = HT_START(clientmap, &client_history); ent != NULL; ent = next) {
  1232. this = *ent;
  1233. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  1234. clientmap_entry_free(this);
  1235. }
  1236. HT_CLEAR(clientmap, &client_history);
  1237. }
  1238. {
  1239. dirreq_map_entry_t **ent, **next, *this;
  1240. for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) {
  1241. this = *ent;
  1242. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent);
  1243. tor_free(this);
  1244. }
  1245. HT_CLEAR(dirreqmap, &dirreq_map);
  1246. }
  1247. tor_free(bridge_stats_extrainfo);
  1248. tor_free(n_v3_ns_requests);
  1249. }