geoip.c 61 KB

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