#include "core/or/or.h"
#include "ht.h"
#include "lib/buf/buffers.h"
#include "app/config/config.h"
#include "feature/control/control_events.h"
#include "feature/client/dnsserv.h"
#include "core/or/dos.h"
#include "lib/geoip/geoip.h"
#include "feature/stats/geoip_stats.h"
#include "feature/nodelist/routerlist.h"
#include "lib/container/order.h"
#include "lib/time/tvdiff.h"
static size_t n_v3_ns_requests_len = 0;
static uint32_t *n_v3_ns_requests;
static size_t geoip_client_history_cache_size;
static inline void
geoip_increment_client_history_cache_size(size_t bytes)
{
IF_BUG_ONCE(geoip_client_history_cache_size > (SIZE_MAX - bytes)) {
geoip_client_history_cache_size = SIZE_MAX;
return;
}
geoip_client_history_cache_size += bytes;
}
static inline void
geoip_decrement_client_history_cache_size(size_t bytes)
{
IF_BUG_ONCE(geoip_client_history_cache_size < bytes) {
geoip_client_history_cache_size = 0;
return;
}
geoip_client_history_cache_size -= bytes;
}
static void
increment_v3_ns_request(country_t country)
{
if (country < 0)
return;
if ((size_t)country >= n_v3_ns_requests_len) {
size_t new_len;
if (n_v3_ns_requests_len == 0)
new_len = 256;
else
new_len = n_v3_ns_requests_len * 2;
if (new_len <= (size_t)country)
new_len = ((size_t)country)+1;
n_v3_ns_requests = tor_reallocarray(n_v3_ns_requests, new_len,
sizeof(uint32_t));
memset(n_v3_ns_requests + n_v3_ns_requests_len, 0,
sizeof(uint32_t)*(new_len - n_v3_ns_requests_len));
n_v3_ns_requests_len = new_len;
}
n_v3_ns_requests[country] += 1;
}
int
should_record_bridge_info(const or_options_t *options)
{
return options->BridgeRelay && options->BridgeRecordUsageByCountry;
}
#define MAX_LAST_SEEN_IN_MINUTES 0X3FFFFFFFu
static HT_HEAD(clientmap, clientmap_entry_t) client_history =
HT_INITIALIZER();
static inline unsigned
clientmap_entry_hash(const clientmap_entry_t *a)
{
unsigned h = (unsigned) tor_addr_hash(&a->addr);
if (a->transport_name)
h += (unsigned) siphash24g(a->transport_name, strlen(a->transport_name));
return h;
}
static inline int
clientmap_entries_eq(const clientmap_entry_t *a, const clientmap_entry_t *b)
{
if (strcmp_opt(a->transport_name, b->transport_name))
return 0;
return !tor_addr_compare(&a->addr, &b->addr, CMP_EXACT) &&
a->action == b->action;
}
HT_PROTOTYPE(clientmap, clientmap_entry_t, node, clientmap_entry_hash,
clientmap_entries_eq);
HT_GENERATE2(clientmap, clientmap_entry_t, node, clientmap_entry_hash,
clientmap_entries_eq, 0.6, tor_reallocarray_, tor_free_);
#define clientmap_entry_free(ent) \
FREE_AND_NULL(clientmap_entry_t, clientmap_entry_free_, ent)
static inline size_t
clientmap_entry_size(const clientmap_entry_t *ent)
{
tor_assert(ent);
return (sizeof(clientmap_entry_t) +
(ent->transport_name ? strlen(ent->transport_name) : 0));
}
static void
clientmap_entry_free_(clientmap_entry_t *ent)
{
if (!ent)
return;
dos_geoip_entry_about_to_free(ent);
geoip_decrement_client_history_cache_size(clientmap_entry_size(ent));
tor_free(ent->transport_name);
tor_free(ent);
}
static clientmap_entry_t *
clientmap_entry_new(geoip_client_action_t action, const tor_addr_t *addr,
const char *transport_name)
{
clientmap_entry_t *entry;
tor_assert(action == GEOIP_CLIENT_CONNECT ||
action == GEOIP_CLIENT_NETWORKSTATUS);
tor_assert(addr);
entry = tor_malloc_zero(sizeof(clientmap_entry_t));
entry->action = action;
tor_addr_copy(&entry->addr, addr);
if (transport_name) {
entry->transport_name = tor_strdup(transport_name);
}
dos_geoip_entry_init(entry);
geoip_increment_client_history_cache_size(clientmap_entry_size(entry));
return entry;
}
static void
client_history_clear(void)
{
clientmap_entry_t **ent, **next, *this;
for (ent = HT_START(clientmap, &client_history); ent != NULL;
ent = next) {
if ((*ent)->action == GEOIP_CLIENT_CONNECT) {
this = *ent;
next = HT_NEXT_RMV(clientmap, &client_history, ent);
clientmap_entry_free(this);
} else {
next = HT_NEXT(clientmap, &client_history, ent);
}
}
}
void
geoip_note_client_seen(geoip_client_action_t action,
const tor_addr_t *addr,
const char *transport_name,
time_t now)
{
const or_options_t *options = get_options();
clientmap_entry_t *ent;
if (action == GEOIP_CLIENT_CONNECT) {
if (!dos_enabled()) {
if (!options->EntryStatistics && !should_record_bridge_info(options)) {
return;
}
}
} else {
if (!options->DirReqStatistics || options->BridgeAuthoritativeDir)
return;
}
log_debug(LD_GENERAL, "Seen client from '%s' with transport '%s'.",
safe_str_client(fmt_addr((addr))),
transport_name ? transport_name : "<no transport>");
ent = geoip_lookup_client(addr, transport_name, action);
if (! ent) {
ent = clientmap_entry_new(action, addr, transport_name);
HT_INSERT(clientmap, &client_history, ent);
}
if (now / 60 <= (int)MAX_LAST_SEEN_IN_MINUTES && now >= 0)
ent->last_seen_in_minutes = (unsigned)(now/60);
else
ent->last_seen_in_minutes = 0;
if (action == GEOIP_CLIENT_NETWORKSTATUS) {
int country_idx = geoip_get_country_by_addr(addr);
if (country_idx < 0)
country_idx = 0;
IF_BUG_ONCE(country_idx > COUNTRY_MAX) {
return;
}
increment_v3_ns_request((country_t) country_idx);
}
}
static int
remove_old_client_helper_(struct clientmap_entry_t *ent, void *_cutoff)
{
time_t cutoff = *(time_t*)_cutoff / 60;
if (ent->last_seen_in_minutes < cutoff) {
clientmap_entry_free(ent);
return 1;
} else {
return 0;
}
}
void
geoip_remove_old_clients(time_t cutoff)
{
clientmap_HT_FOREACH_FN(&client_history,
remove_old_client_helper_,
&cutoff);
}
clientmap_entry_t *
geoip_lookup_client(const tor_addr_t *addr, const char *transport_name,
geoip_client_action_t action)
{
clientmap_entry_t lookup;
tor_assert(addr);
tor_addr_copy(&lookup.addr, addr);
lookup.action = action;
lookup.transport_name = (char *) transport_name;
return HT_FIND(clientmap, &client_history, &lookup);
}
static size_t
oom_clean_client_entries(time_t cutoff)
{
size_t bytes = 0;
clientmap_entry_t **ent, **ent_next;
for (ent = HT_START(clientmap, &client_history); ent; ent = ent_next) {
clientmap_entry_t *entry = *ent;
if (entry->last_seen_in_minutes < (cutoff / 60)) {
ent_next = HT_NEXT_RMV(clientmap, &client_history, ent);
bytes += clientmap_entry_size(entry);
clientmap_entry_free(entry);
} else {
ent_next = HT_NEXT(clientmap, &client_history, ent);
}
}
return bytes;
}
#define GEOIP_CLIENT_CACHE_OOM_MIN_CUTOFF (4 * 60 * 60)
#define GEOIP_CLIENT_CACHE_OOM_STEP (15 * 50)
size_t
geoip_client_cache_handle_oom(time_t now, size_t min_remove_bytes)
{
time_t k;
size_t bytes_removed = 0;
tor_assert(min_remove_bytes != 0);
k = WRITE_STATS_INTERVAL;
do {
time_t cutoff;
if (k <= GEOIP_CLIENT_CACHE_OOM_MIN_CUTOFF) {
break;
}
cutoff = now - k;
bytes_removed += oom_clean_client_entries(cutoff);
k -= GEOIP_CLIENT_CACHE_OOM_STEP;
} while (bytes_removed < min_remove_bytes);
return bytes_removed;
}
size_t
geoip_client_cache_total_allocation(void)
{
return geoip_client_history_cache_size;
}
static uint32_t ns_v3_responses[GEOIP_NS_RESPONSE_NUM];
void
geoip_note_ns_response(geoip_ns_response_t response)
{
static int arrays_initialized = 0;
if (!get_options()->DirReqStatistics)
return;
if (!arrays_initialized) {
memset(ns_v3_responses, 0, sizeof(ns_v3_responses));
arrays_initialized = 1;
}
tor_assert(response < GEOIP_NS_RESPONSE_NUM);
ns_v3_responses[response]++;
}
#define MIN_IPS_TO_NOTE_COUNTRY 1
#define MIN_IPS_TO_NOTE_ANYTHING 1
#define IP_GRANULARITY 8
typedef struct c_hist_t {
char country[3];
unsigned total;
} c_hist_t;
static int
c_hist_compare_(const void **_a, const void **_b)
{
const c_hist_t *a = *_a, *b = *_b;
if (a->total > b->total)
return -1;
else if (a->total < b->total)
return 1;
else
return strcmp(a->country, b->country);
}
#define DIRREQ_TIMEOUT (10*60)
typedef struct dirreq_map_entry_t {
HT_ENTRY(dirreq_map_entry_t) node;
uint64_t dirreq_id;
unsigned int state:3;
unsigned int type:1;
unsigned int completed:1;
struct timeval request_time;
size_t response_size;
struct timeval completion_time;
} dirreq_map_entry_t;
static HT_HEAD(dirreqmap, dirreq_map_entry_t) dirreq_map =
HT_INITIALIZER();
static int
dirreq_map_ent_eq(const dirreq_map_entry_t *a,
const dirreq_map_entry_t *b)
{
return a->dirreq_id == b->dirreq_id && a->type == b->type;
}
static unsigned
dirreq_map_ent_hash(const dirreq_map_entry_t *entry)
{
unsigned u = (unsigned) entry->dirreq_id;
u += entry->type << 20;
return u;
}
HT_PROTOTYPE(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash,
dirreq_map_ent_eq);
HT_GENERATE2(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash,
dirreq_map_ent_eq, 0.6, tor_reallocarray_, tor_free_);
static void
dirreq_map_put_(dirreq_map_entry_t *entry, dirreq_type_t type,
uint64_t dirreq_id)
{
dirreq_map_entry_t *old_ent;
tor_assert(entry->type == type);
tor_assert(entry->dirreq_id == dirreq_id);
old_ent = HT_REPLACE(dirreqmap, &dirreq_map, entry);
if (old_ent && old_ent != entry) {
log_warn(LD_BUG, "Error when putting directory request into local "
"map. There was already an entry for the same identifier.");
return;
}
}
static dirreq_map_entry_t *
dirreq_map_get_(dirreq_type_t type, uint64_t dirreq_id)
{
dirreq_map_entry_t lookup;
lookup.type = type;
lookup.dirreq_id = dirreq_id;
return HT_FIND(dirreqmap, &dirreq_map, &lookup);
}
void
geoip_start_dirreq(uint64_t dirreq_id, size_t response_size,
dirreq_type_t type)
{
dirreq_map_entry_t *ent;
if (!get_options()->DirReqStatistics)
return;
ent = tor_malloc_zero(sizeof(dirreq_map_entry_t));
ent->dirreq_id = dirreq_id;
tor_gettimeofday(&ent->request_time);
ent->response_size = response_size;
ent->type = type;
dirreq_map_put_(ent, type, dirreq_id);
}
void
geoip_change_dirreq_state(uint64_t dirreq_id, dirreq_type_t type,
dirreq_state_t new_state)
{
dirreq_map_entry_t *ent;
if (!get_options()->DirReqStatistics)
return;
ent = dirreq_map_get_(type, dirreq_id);
if (!ent)
return;
if (new_state == DIRREQ_IS_FOR_NETWORK_STATUS)
return;
if (new_state - 1 != ent->state)
return;
ent->state = new_state;
if ((type == DIRREQ_DIRECT &&
new_state == DIRREQ_FLUSHING_DIR_CONN_FINISHED) ||
(type == DIRREQ_TUNNELED &&
new_state == DIRREQ_CHANNEL_BUFFER_FLUSHED)) {
tor_gettimeofday(&ent->completion_time);
ent->completed = 1;
}
}
char *
geoip_get_transport_history(void)
{
unsigned granularity = IP_GRANULARITY;
strmap_t *transport_counts = strmap_new();
smartlist_t *transports_used = smartlist_new();
static const char* no_transport_str = "<OR>";
clientmap_entry_t **ent;
smartlist_t *string_chunks = smartlist_new();
char *the_string = NULL;
if (HT_EMPTY(&client_history))
goto done;
log_debug(LD_GENERAL,"Starting iteration for transport history. %d clients.",
HT_SIZE(&client_history));
HT_FOREACH(ent, clientmap, &client_history) {
uintptr_t val;
void *ptr;
const char *transport_name = (*ent)->transport_name;
if (!transport_name)
transport_name = no_transport_str;
ptr = strmap_get(transport_counts, transport_name);
val = (uintptr_t)ptr;
val++;
ptr = (void*)val;
strmap_set(transport_counts, transport_name, ptr);
if (val == 1)
smartlist_add_strdup(transports_used, transport_name);
log_debug(LD_GENERAL, "Client from '%s' with transport '%s'. "
"I've now seen %d clients.",
safe_str_client(fmt_addr(&(*ent)->addr)),
transport_name ? transport_name : "<no transport>",
(int)val);
}
smartlist_sort_strings(transports_used);
SMARTLIST_FOREACH_BEGIN(transports_used, const char *, transport_name) {
void *transport_count_ptr = strmap_get(transport_counts, transport_name);
uintptr_t transport_count = (uintptr_t) transport_count_ptr;
log_debug(LD_GENERAL, "We got %"PRIu64" clients with transport '%s'.",
((uint64_t)transport_count), transport_name);
smartlist_add_asprintf(string_chunks, "%s=%"PRIu64,
transport_name,
(round_uint64_to_next_multiple_of(
(uint64_t)transport_count,
granularity)));
} SMARTLIST_FOREACH_END(transport_name);
the_string = smartlist_join_strings(string_chunks, ",", 0, NULL);
log_debug(LD_GENERAL, "Final bridge-ip-transports string: '%s'", the_string);
done:
strmap_free(transport_counts, NULL);
SMARTLIST_FOREACH(transports_used, char *, s, tor_free(s));
smartlist_free(transports_used);
SMARTLIST_FOREACH(string_chunks, char *, s, tor_free(s));
smartlist_free(string_chunks);
return the_string;
}
static char *
geoip_get_dirreq_history(dirreq_type_t type)
{
char *result = NULL;
buf_t *buf = NULL;
smartlist_t *dirreq_completed = NULL;
uint32_t complete = 0, timeouts = 0, running = 0;
dirreq_map_entry_t **ptr, **next;
struct timeval now;
tor_gettimeofday(&now);
dirreq_completed = smartlist_new();
for (ptr = HT_START(dirreqmap, &dirreq_map); ptr; ptr = next) {
dirreq_map_entry_t *ent = *ptr;
if (ent->type != type) {
next = HT_NEXT(dirreqmap, &dirreq_map, ptr);
continue;
} else {
if (ent->completed) {
smartlist_add(dirreq_completed, ent);
complete++;
next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr);
} else {
if (tv_mdiff(&ent->request_time, &now) / 1000 > DIRREQ_TIMEOUT)
timeouts++;
else
running++;
next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr);
tor_free(ent);
}
}
}
#define DIR_REQ_GRANULARITY 4
complete = round_uint32_to_next_multiple_of(complete,
DIR_REQ_GRANULARITY);
timeouts = round_uint32_to_next_multiple_of(timeouts,
DIR_REQ_GRANULARITY);
running = round_uint32_to_next_multiple_of(running,
DIR_REQ_GRANULARITY);
buf = buf_new_with_capacity(1024);
buf_add_printf(buf, "complete=%u,timeout=%u,"
"running=%u", complete, timeouts, running);
#define MIN_DIR_REQ_RESPONSES 16
if (complete >= MIN_DIR_REQ_RESPONSES) {
uint32_t *dltimes;
complete = smartlist_len(dirreq_completed);
dltimes = tor_calloc(complete, sizeof(uint32_t));
SMARTLIST_FOREACH_BEGIN(dirreq_completed, dirreq_map_entry_t *, ent) {
uint32_t bytes_per_second;
uint32_t time_diff_ = (uint32_t) tv_mdiff(&ent->request_time,
&ent->completion_time);
if (time_diff_ == 0)
time_diff_ = 1;
bytes_per_second = (uint32_t)(1000 * ent->response_size / time_diff_);
dltimes[ent_sl_idx] = bytes_per_second;
} SMARTLIST_FOREACH_END(ent);
median_uint32(dltimes, complete);
buf_add_printf(buf,
",min=%u,d1=%u,d2=%u,q1=%u,d3=%u,d4=%u,md=%u,"
"d6=%u,d7=%u,q3=%u,d8=%u,d9=%u,max=%u",
dltimes[0],
dltimes[1*complete/10-1],
dltimes[2*complete/10-1],
dltimes[1*complete/4-1],
dltimes[3*complete/10-1],
dltimes[4*complete/10-1],
dltimes[5*complete/10-1],
dltimes[6*complete/10-1],
dltimes[7*complete/10-1],
dltimes[3*complete/4-1],
dltimes[8*complete/10-1],
dltimes[9*complete/10-1],
dltimes[complete-1]);
tor_free(dltimes);
}
result = buf_extract(buf, NULL);
SMARTLIST_FOREACH(dirreq_completed, dirreq_map_entry_t *, ent,
tor_free(ent));
smartlist_free(dirreq_completed);
buf_free(buf);
return result;
}
int
geoip_get_client_history(geoip_client_action_t action,
char **country_str, char **ipver_str)
{
unsigned granularity = IP_GRANULARITY;
smartlist_t *entries = NULL;
int n_countries = geoip_get_n_countries();
int i;
clientmap_entry_t **cm_ent;
unsigned *counts = NULL;
unsigned total = 0;
unsigned ipv4_count = 0, ipv6_count = 0;
if (!geoip_is_loaded(AF_INET) && !geoip_is_loaded(AF_INET6))
return -1;
counts = tor_calloc(n_countries, sizeof(unsigned));
HT_FOREACH(cm_ent, clientmap, &client_history) {
int country;
if ((*cm_ent)->action != (int)action)
continue;
country = geoip_get_country_by_addr(&(*cm_ent)->addr);
if (country < 0)
country = 0;
tor_assert(0 <= country && country < n_countries);
++counts[country];
++total;
switch (tor_addr_family(&(*cm_ent)->addr)) {
case AF_INET:
ipv4_count++;
break;
case AF_INET6:
ipv6_count++;
break;
}
}
if (ipver_str) {
smartlist_t *chunks = smartlist_new();
smartlist_add_asprintf(chunks, "v4=%u",
round_to_next_multiple_of(ipv4_count, granularity));
smartlist_add_asprintf(chunks, "v6=%u",
round_to_next_multiple_of(ipv6_count, granularity));
*ipver_str = smartlist_join_strings(chunks, ",", 0, NULL);
SMARTLIST_FOREACH(chunks, char *, c, tor_free(c));
smartlist_free(chunks);
}
if (total < MIN_IPS_TO_NOTE_ANYTHING) {
tor_free(counts);
if (country_str)
*country_str = NULL;
return 0;
}
entries = smartlist_new();
for (i = 0; i < n_countries; ++i) {
unsigned c = counts[i];
const char *countrycode;
c_hist_t *ent;
if (c >= MIN_IPS_TO_NOTE_COUNTRY) {
c = round_to_next_multiple_of(c, granularity);
countrycode = geoip_get_country_name(i);
ent = tor_malloc(sizeof(c_hist_t));
strlcpy(ent->country, countrycode, sizeof(ent->country));
ent->total = c;
smartlist_add(entries, ent);
}
}
smartlist_sort(entries, c_hist_compare_);
if (country_str) {
smartlist_t *chunks = smartlist_new();
SMARTLIST_FOREACH(entries, c_hist_t *, ch, {
smartlist_add_asprintf(chunks, "%s=%u", ch->country, ch->total);
});
*country_str = smartlist_join_strings(chunks, ",", 0, NULL);
SMARTLIST_FOREACH(chunks, char *, c, tor_free(c));
smartlist_free(chunks);
}
SMARTLIST_FOREACH(entries, c_hist_t *, c, tor_free(c));
smartlist_free(entries);
tor_free(counts);
return 0;
}
char *
geoip_get_request_history(void)
{
smartlist_t *entries, *strings;
char *result;
unsigned granularity = IP_GRANULARITY;
entries = smartlist_new();
SMARTLIST_FOREACH_BEGIN(geoip_get_countries(), const geoip_country_t *, c) {
uint32_t tot = 0;
c_hist_t *ent;
if ((size_t)c_sl_idx < n_v3_ns_requests_len)
tot = n_v3_ns_requests[c_sl_idx];
else
tot = 0;
if (!tot)
continue;
ent = tor_malloc_zero(sizeof(c_hist_t));
strlcpy(ent->country, c->countrycode, sizeof(ent->country));
ent->total = round_to_next_multiple_of(tot, granularity);
smartlist_add(entries, ent);
} SMARTLIST_FOREACH_END(c);
smartlist_sort(entries, c_hist_compare_);
strings = smartlist_new();
SMARTLIST_FOREACH(entries, c_hist_t *, ent, {
smartlist_add_asprintf(strings, "%s=%u", ent->country, ent->total);
});
result = smartlist_join_strings(strings, ",", 0, NULL);
SMARTLIST_FOREACH(strings, char *, cp, tor_free(cp));
SMARTLIST_FOREACH(entries, c_hist_t *, ent, tor_free(ent));
smartlist_free(strings);
smartlist_free(entries);
return result;
}
static time_t start_of_dirreq_stats_interval;
void
geoip_dirreq_stats_init(time_t now)
{
start_of_dirreq_stats_interval = now;
}
void
geoip_reset_dirreq_stats(time_t now)
{
memset(n_v3_ns_requests, 0,
n_v3_ns_requests_len * sizeof(uint32_t));
{
clientmap_entry_t **ent, **next, *this;
for (ent = HT_START(clientmap, &client_history); ent != NULL;
ent = next) {
if ((*ent)->action == GEOIP_CLIENT_NETWORKSTATUS) {
this = *ent;
next = HT_NEXT_RMV(clientmap, &client_history, ent);
clientmap_entry_free(this);
} else {
next = HT_NEXT(clientmap, &client_history, ent);
}
}
}
memset(ns_v3_responses, 0, sizeof(ns_v3_responses));
{
dirreq_map_entry_t **ent, **next, *this;
for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) {
this = *ent;
next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent);
tor_free(this);
}
}
start_of_dirreq_stats_interval = now;
}
void
geoip_dirreq_stats_term(void)
{
geoip_reset_dirreq_stats(0);
}
char *
geoip_format_dirreq_stats(time_t now)
{
char t[ISO_TIME_LEN+1];
int i;
char *v3_ips_string = NULL, *v3_reqs_string = NULL,
*v3_direct_dl_string = NULL, *v3_tunneled_dl_string = NULL;
char *result = NULL;
if (!start_of_dirreq_stats_interval)
return NULL;
tor_assert(now >= start_of_dirreq_stats_interval);
format_iso_time(t, now);
geoip_get_client_history(GEOIP_CLIENT_NETWORKSTATUS, &v3_ips_string, NULL);
v3_reqs_string = geoip_get_request_history();
#define RESPONSE_GRANULARITY 8
for (i = 0; i < GEOIP_NS_RESPONSE_NUM; i++) {
ns_v3_responses[i] = round_uint32_to_next_multiple_of(
ns_v3_responses[i], RESPONSE_GRANULARITY);
}
#undef RESPONSE_GRANULARITY
v3_direct_dl_string = geoip_get_dirreq_history(DIRREQ_DIRECT);
v3_tunneled_dl_string = geoip_get_dirreq_history(DIRREQ_TUNNELED);
tor_asprintf(&result, "dirreq-stats-end %s (%d s)\n"
"dirreq-v3-ips %s\n"
"dirreq-v3-reqs %s\n"
"dirreq-v3-resp ok=%u,not-enough-sigs=%u,unavailable=%u,"
"not-found=%u,not-modified=%u,busy=%u\n"
"dirreq-v3-direct-dl %s\n"
"dirreq-v3-tunneled-dl %s\n",
t,
(unsigned) (now - start_of_dirreq_stats_interval),
v3_ips_string ? v3_ips_string : "",
v3_reqs_string ? v3_reqs_string : "",
ns_v3_responses[GEOIP_SUCCESS],
ns_v3_responses[GEOIP_REJECT_NOT_ENOUGH_SIGS],
ns_v3_responses[GEOIP_REJECT_UNAVAILABLE],
ns_v3_responses[GEOIP_REJECT_NOT_FOUND],
ns_v3_responses[GEOIP_REJECT_NOT_MODIFIED],
ns_v3_responses[GEOIP_REJECT_BUSY],
v3_direct_dl_string ? v3_direct_dl_string : "",
v3_tunneled_dl_string ? v3_tunneled_dl_string : "");
tor_free(v3_ips_string);
tor_free(v3_reqs_string);
tor_free(v3_direct_dl_string);
tor_free(v3_tunneled_dl_string);
return result;
}
time_t
geoip_dirreq_stats_write(time_t now)
{
char *str = NULL;
if (!start_of_dirreq_stats_interval)
return 0;
if (start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL > now)
goto done;
geoip_remove_old_clients(start_of_dirreq_stats_interval);
str = geoip_format_dirreq_stats(now);
if (! str)
goto done;
if (!check_or_create_data_subdir("stats")) {
write_to_data_subdir("stats", "dirreq-stats", str, "dirreq statistics");
geoip_reset_dirreq_stats(now);
}
done:
tor_free(str);
return start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL;
}
static time_t start_of_bridge_stats_interval;
void
geoip_bridge_stats_init(time_t now)
{
start_of_bridge_stats_interval = now;
}
void
geoip_bridge_stats_term(void)
{
client_history_clear();
start_of_bridge_stats_interval = 0;
}
static int
validate_bridge_stats(const char *stats_str, time_t now)
{
char stats_end_str[ISO_TIME_LEN+1], stats_start_str[ISO_TIME_LEN+1],
*eos;
const char *BRIDGE_STATS_END = "bridge-stats-end ";
const char *BRIDGE_IPS = "bridge-ips ";
const char *BRIDGE_IPS_EMPTY_LINE = "bridge-ips\n";
const char *BRIDGE_TRANSPORTS = "bridge-ip-transports ";
const char *BRIDGE_TRANSPORTS_EMPTY_LINE = "bridge-ip-transports\n";
const char *tmp;
time_t stats_end_time;
int seconds;
tor_assert(stats_str);
tmp = find_str_at_start_of_line(stats_str, BRIDGE_STATS_END);
if (!tmp)
return 0;
tmp += strlen(BRIDGE_STATS_END);
if (strlen(tmp) < ISO_TIME_LEN + 6)
return 0;
strlcpy(stats_end_str, tmp, sizeof(stats_end_str));
if (parse_iso_time(stats_end_str, &stats_end_time) < 0)
return 0;
if (stats_end_time < now - (25*60*60) ||
stats_end_time > now + (1*60*60))
return 0;
seconds = (int)strtol(tmp + ISO_TIME_LEN + 2, &eos, 10);
if (!eos || seconds < 23*60*60)
return 0;
format_iso_time(stats_start_str, stats_end_time - seconds);
tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS);
if (!tmp) {
tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS_EMPTY_LINE);
if (!tmp)
return 0;
}
tmp = find_str_at_start_of_line(stats_str, BRIDGE_TRANSPORTS);
if (!tmp) {
tmp = find_str_at_start_of_line(stats_str, BRIDGE_TRANSPORTS_EMPTY_LINE);
if (!tmp)
return 0;
}
return 1;
}
static char *bridge_stats_extrainfo = NULL;
char *
geoip_format_bridge_stats(time_t now)
{
char *out = NULL;
char *country_data = NULL, *ipver_data = NULL, *transport_data = NULL;
long duration = now - start_of_bridge_stats_interval;
char written[ISO_TIME_LEN+1];
if (duration < 0)
return NULL;
if (!start_of_bridge_stats_interval)
return NULL;
format_iso_time(written, now);
geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data);
transport_data = geoip_get_transport_history();
tor_asprintf(&out,
"bridge-stats-end %s (%ld s)\n"
"bridge-ips %s\n"
"bridge-ip-versions %s\n"
"bridge-ip-transports %s\n",
written, duration,
country_data ? country_data : "",
ipver_data ? ipver_data : "",
transport_data ? transport_data : "");
tor_free(country_data);
tor_free(ipver_data);
tor_free(transport_data);
return out;
}
static char *
format_bridge_stats_controller(time_t now)
{
char *out = NULL, *country_data = NULL, *ipver_data = NULL;
char started[ISO_TIME_LEN+1];
(void) now;
format_iso_time(started, start_of_bridge_stats_interval);
geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data);
tor_asprintf(&out,
"TimeStarted=\"%s\" CountrySummary=%s IPVersions=%s",
started,
country_data ? country_data : "",
ipver_data ? ipver_data : "");
tor_free(country_data);
tor_free(ipver_data);
return out;
}
char *
format_client_stats_heartbeat(time_t now)
{
const int n_hours = 6;
char *out = NULL;
int n_clients = 0;
clientmap_entry_t **ent;
unsigned cutoff = (unsigned)( (now-n_hours*3600)/60 );
if (!start_of_bridge_stats_interval)
return NULL;
HT_FOREACH(ent, clientmap, &client_history) {
if ((*ent)->action != GEOIP_CLIENT_CONNECT)
continue;
if ((*ent)->last_seen_in_minutes < cutoff)
continue;
n_clients++;
}
tor_asprintf(&out, "Heartbeat: "
"In the last %d hours, I have seen %d unique clients.",
n_hours,
n_clients);
return out;
}
time_t
geoip_bridge_stats_write(time_t now)
{
char *val = NULL;
if (now < start_of_bridge_stats_interval + WRITE_STATS_INTERVAL)
return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL;
geoip_remove_old_clients(start_of_bridge_stats_interval);
val = geoip_format_bridge_stats(now);
if (val == NULL)
goto done;
tor_free(bridge_stats_extrainfo);
bridge_stats_extrainfo = val;
start_of_bridge_stats_interval = now;
if (!check_or_create_data_subdir("stats")) {
write_to_data_subdir("stats", "bridge-stats",
bridge_stats_extrainfo, "bridge statistics");
{
char *controller_str = format_bridge_stats_controller(now);
if (controller_str)
control_event_clients_seen(controller_str);
tor_free(controller_str);
}
}
done:
return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL;
}
static void
load_bridge_stats(time_t now)
{
char *fname, *contents;
if (bridge_stats_extrainfo)
return;
fname = get_datadir_fname2("stats", "bridge-stats");
contents = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
if (contents && validate_bridge_stats(contents, now)) {
bridge_stats_extrainfo = contents;
} else {
tor_free(contents);
}
tor_free(fname);
}
const char *
geoip_get_bridge_stats_extrainfo(time_t now)
{
load_bridge_stats(now);
return bridge_stats_extrainfo;
}
char *
geoip_get_bridge_stats_controller(time_t now)
{
return format_bridge_stats_controller(now);
}
static time_t start_of_entry_stats_interval;
void
geoip_entry_stats_init(time_t now)
{
start_of_entry_stats_interval = now;
}
void
geoip_reset_entry_stats(time_t now)
{
client_history_clear();
start_of_entry_stats_interval = now;
}
void
geoip_entry_stats_term(void)
{
geoip_reset_entry_stats(0);
}
char *
geoip_format_entry_stats(time_t now)
{
char t[ISO_TIME_LEN+1];
char *data = NULL;
char *result;
if (!start_of_entry_stats_interval)
return NULL;
tor_assert(now >= start_of_entry_stats_interval);
geoip_get_client_history(GEOIP_CLIENT_CONNECT, &data, NULL);
format_iso_time(t, now);
tor_asprintf(&result,
"entry-stats-end %s (%u s)\n"
"entry-ips %s\n",
t, (unsigned) (now - start_of_entry_stats_interval),
data ? data : "");
tor_free(data);
return result;
}
time_t
geoip_entry_stats_write(time_t now)
{
char *str = NULL;
if (!start_of_entry_stats_interval)
return 0;
if (start_of_entry_stats_interval + WRITE_STATS_INTERVAL > now)
goto done;
geoip_remove_old_clients(start_of_entry_stats_interval);
str = geoip_format_entry_stats(now);
if (!check_or_create_data_subdir("stats")) {
write_to_data_subdir("stats", "entry-stats", str, "entry statistics");
geoip_reset_entry_stats(now);
}
done:
tor_free(str);
return start_of_entry_stats_interval + WRITE_STATS_INTERVAL;
}
void
geoip_stats_free_all(void)
{
{
clientmap_entry_t **ent, **next, *this;
for (ent = HT_START(clientmap, &client_history); ent != NULL; ent = next) {
this = *ent;
next = HT_NEXT_RMV(clientmap, &client_history, ent);
clientmap_entry_free(this);
}
HT_CLEAR(clientmap, &client_history);
}
{
dirreq_map_entry_t **ent, **next, *this;
for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) {
this = *ent;
next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent);
tor_free(this);
}
HT_CLEAR(dirreqmap, &dirreq_map);
}
tor_free(bridge_stats_extrainfo);
tor_free(n_v3_ns_requests);
}