geoip.c 56 KB

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