geoip.c 56 KB

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