geoip_stats.c 47 KB

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