geoip.c 55 KB

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