geoip.c 61 KB

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