tor

The Tor anonymity network
git clone https://git.dasho.dev/tor.git
Log | Files | Refs | README | LICENSE

geoip_stats.c (48143B)


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