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