geoip.c 57 KB

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