geoip.c 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  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 = (unsigned) tor_addr_hash(&a->addr);
  442. if (a->transport_name)
  443. h += (unsigned) siphash24g(a->transport_name, strlen(a->transport_name));
  444. return 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. /** Free all storage held by <b>ent</b>. */
  460. static void
  461. clientmap_entry_free(clientmap_entry_t *ent)
  462. {
  463. if (!ent)
  464. return;
  465. tor_free(ent->transport_name);
  466. tor_free(ent);
  467. }
  468. /** Clear history of connecting clients used by entry and bridge stats. */
  469. static void
  470. client_history_clear(void)
  471. {
  472. clientmap_entry_t **ent, **next, *this;
  473. for (ent = HT_START(clientmap, &client_history); ent != NULL;
  474. ent = next) {
  475. if ((*ent)->action == GEOIP_CLIENT_CONNECT) {
  476. this = *ent;
  477. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  478. clientmap_entry_free(this);
  479. } else {
  480. next = HT_NEXT(clientmap, &client_history, ent);
  481. }
  482. }
  483. }
  484. /** Note that we've seen a client connect from the IP <b>addr</b>
  485. * at time <b>now</b>. Ignored by all but bridges and directories if
  486. * configured accordingly. */
  487. void
  488. geoip_note_client_seen(geoip_client_action_t action,
  489. const tor_addr_t *addr,
  490. const char *transport_name,
  491. time_t now)
  492. {
  493. const or_options_t *options = get_options();
  494. clientmap_entry_t lookup, *ent;
  495. memset(&lookup, 0, sizeof(clientmap_entry_t));
  496. if (action == GEOIP_CLIENT_CONNECT) {
  497. /* Only remember statistics as entry guard or as bridge. */
  498. if (!options->EntryStatistics &&
  499. (!(options->BridgeRelay && options->BridgeRecordUsageByCountry)))
  500. return;
  501. } else {
  502. /* Only gather directory-request statistics if configured, and
  503. * forcibly disable them on bridge authorities. */
  504. if (!options->DirReqStatistics || options->BridgeAuthoritativeDir)
  505. return;
  506. }
  507. log_debug(LD_GENERAL, "Seen client from '%s' with transport '%s'.",
  508. safe_str_client(fmt_addr((addr))),
  509. transport_name ? transport_name : "<no transport>");
  510. tor_addr_copy(&lookup.addr, addr);
  511. lookup.action = (int)action;
  512. lookup.transport_name = (char*) transport_name;
  513. ent = HT_FIND(clientmap, &client_history, &lookup);
  514. if (! ent) {
  515. ent = tor_malloc_zero(sizeof(clientmap_entry_t));
  516. tor_addr_copy(&ent->addr, addr);
  517. if (transport_name)
  518. ent->transport_name = tor_strdup(transport_name);
  519. ent->action = (int)action;
  520. HT_INSERT(clientmap, &client_history, ent);
  521. }
  522. if (now / 60 <= (int)MAX_LAST_SEEN_IN_MINUTES && now >= 0)
  523. ent->last_seen_in_minutes = (unsigned)(now/60);
  524. else
  525. ent->last_seen_in_minutes = 0;
  526. if (action == GEOIP_CLIENT_NETWORKSTATUS) {
  527. int country_idx = geoip_get_country_by_addr(addr);
  528. if (country_idx < 0)
  529. country_idx = 0; /** unresolved requests are stored at index 0. */
  530. if (country_idx >= 0 && country_idx < smartlist_len(geoip_countries)) {
  531. geoip_country_t *country = smartlist_get(geoip_countries, country_idx);
  532. ++country->n_v3_ns_requests;
  533. }
  534. }
  535. }
  536. /** HT_FOREACH helper: remove a clientmap_entry_t from the hashtable if it's
  537. * older than a certain time. */
  538. static int
  539. remove_old_client_helper_(struct clientmap_entry_t *ent, void *_cutoff)
  540. {
  541. time_t cutoff = *(time_t*)_cutoff / 60;
  542. if (ent->last_seen_in_minutes < cutoff) {
  543. clientmap_entry_free(ent);
  544. return 1;
  545. } else {
  546. return 0;
  547. }
  548. }
  549. /** Forget about all clients that haven't connected since <b>cutoff</b>. */
  550. void
  551. geoip_remove_old_clients(time_t cutoff)
  552. {
  553. clientmap_HT_FOREACH_FN(&client_history,
  554. remove_old_client_helper_,
  555. &cutoff);
  556. }
  557. /** How many responses are we giving to clients requesting v3 network
  558. * statuses? */
  559. static uint32_t ns_v3_responses[GEOIP_NS_RESPONSE_NUM];
  560. /** Note that we've rejected a client's request for a v3 network status
  561. * for reason <b>reason</b> at time <b>now</b>. */
  562. void
  563. geoip_note_ns_response(geoip_ns_response_t response)
  564. {
  565. static int arrays_initialized = 0;
  566. if (!get_options()->DirReqStatistics)
  567. return;
  568. if (!arrays_initialized) {
  569. memset(ns_v3_responses, 0, sizeof(ns_v3_responses));
  570. arrays_initialized = 1;
  571. }
  572. tor_assert(response < GEOIP_NS_RESPONSE_NUM);
  573. ns_v3_responses[response]++;
  574. }
  575. /** Do not mention any country from which fewer than this number of IPs have
  576. * connected. This conceivably avoids reporting information that could
  577. * deanonymize users, though analysis is lacking. */
  578. #define MIN_IPS_TO_NOTE_COUNTRY 1
  579. /** Do not report any geoip data at all if we have fewer than this number of
  580. * IPs to report about. */
  581. #define MIN_IPS_TO_NOTE_ANYTHING 1
  582. /** When reporting geoip data about countries, round up to the nearest
  583. * multiple of this value. */
  584. #define IP_GRANULARITY 8
  585. /** Helper type: used to sort per-country totals by value. */
  586. typedef struct c_hist_t {
  587. char country[3]; /**< Two-letter country code. */
  588. unsigned total; /**< Total IP addresses seen in this country. */
  589. } c_hist_t;
  590. /** Sorting helper: return -1, 1, or 0 based on comparison of two
  591. * geoip_ipv4_entry_t. Sort in descending order of total, and then by country
  592. * code. */
  593. static int
  594. c_hist_compare_(const void **_a, const void **_b)
  595. {
  596. const c_hist_t *a = *_a, *b = *_b;
  597. if (a->total > b->total)
  598. return -1;
  599. else if (a->total < b->total)
  600. return 1;
  601. else
  602. return strcmp(a->country, b->country);
  603. }
  604. /** When there are incomplete directory requests at the end of a 24-hour
  605. * period, consider those requests running for longer than this timeout as
  606. * failed, the others as still running. */
  607. #define DIRREQ_TIMEOUT (10*60)
  608. /** Entry in a map from either chan->global_identifier for direct requests
  609. * or a unique circuit identifier for tunneled requests to request time,
  610. * response size, and completion time of a network status request. Used to
  611. * measure download times of requests to derive average client
  612. * bandwidths. */
  613. typedef struct dirreq_map_entry_t {
  614. HT_ENTRY(dirreq_map_entry_t) node;
  615. /** Unique identifier for this network status request; this is either the
  616. * chan->global_identifier of the dir channel (direct request) or a new
  617. * locally unique identifier of a circuit (tunneled request). This ID is
  618. * only unique among other direct or tunneled requests, respectively. */
  619. uint64_t dirreq_id;
  620. unsigned int state:3; /**< State of this directory request. */
  621. unsigned int type:1; /**< Is this a direct or a tunneled request? */
  622. unsigned int completed:1; /**< Is this request complete? */
  623. /** When did we receive the request and started sending the response? */
  624. struct timeval request_time;
  625. size_t response_size; /**< What is the size of the response in bytes? */
  626. struct timeval completion_time; /**< When did the request succeed? */
  627. } dirreq_map_entry_t;
  628. /** Map of all directory requests asking for v2 or v3 network statuses in
  629. * the current geoip-stats interval. Values are
  630. * of type *<b>dirreq_map_entry_t</b>. */
  631. static HT_HEAD(dirreqmap, dirreq_map_entry_t) dirreq_map =
  632. HT_INITIALIZER();
  633. static int
  634. dirreq_map_ent_eq(const dirreq_map_entry_t *a,
  635. const dirreq_map_entry_t *b)
  636. {
  637. return a->dirreq_id == b->dirreq_id && a->type == b->type;
  638. }
  639. /* DOCDOC dirreq_map_ent_hash */
  640. static unsigned
  641. dirreq_map_ent_hash(const dirreq_map_entry_t *entry)
  642. {
  643. unsigned u = (unsigned) entry->dirreq_id;
  644. u += entry->type << 20;
  645. return u;
  646. }
  647. HT_PROTOTYPE(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash,
  648. dirreq_map_ent_eq);
  649. HT_GENERATE(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash,
  650. dirreq_map_ent_eq, 0.6, malloc, realloc, free);
  651. /** Helper: Put <b>entry</b> into map of directory requests using
  652. * <b>type</b> and <b>dirreq_id</b> as key parts. If there is
  653. * already an entry for that key, print out a BUG warning and return. */
  654. static void
  655. dirreq_map_put_(dirreq_map_entry_t *entry, dirreq_type_t type,
  656. uint64_t dirreq_id)
  657. {
  658. dirreq_map_entry_t *old_ent;
  659. tor_assert(entry->type == type);
  660. tor_assert(entry->dirreq_id == dirreq_id);
  661. /* XXXX we could switch this to HT_INSERT some time, since it seems that
  662. * this bug doesn't happen. But since this function doesn't seem to be
  663. * critical-path, it's sane to leave it alone. */
  664. old_ent = HT_REPLACE(dirreqmap, &dirreq_map, entry);
  665. if (old_ent && old_ent != entry) {
  666. log_warn(LD_BUG, "Error when putting directory request into local "
  667. "map. There was already an entry for the same identifier.");
  668. return;
  669. }
  670. }
  671. /** Helper: Look up and return an entry in the map of directory requests
  672. * using <b>type</b> and <b>dirreq_id</b> as key parts. If there
  673. * is no such entry, return NULL. */
  674. static dirreq_map_entry_t *
  675. dirreq_map_get_(dirreq_type_t type, uint64_t dirreq_id)
  676. {
  677. dirreq_map_entry_t lookup;
  678. lookup.type = type;
  679. lookup.dirreq_id = dirreq_id;
  680. return HT_FIND(dirreqmap, &dirreq_map, &lookup);
  681. }
  682. /** Note that an either direct or tunneled (see <b>type</b>) directory
  683. * request for a v3 network status with unique ID <b>dirreq_id</b> of size
  684. * <b>response_size</b> has started. */
  685. void
  686. geoip_start_dirreq(uint64_t dirreq_id, size_t response_size,
  687. dirreq_type_t type)
  688. {
  689. dirreq_map_entry_t *ent;
  690. if (!get_options()->DirReqStatistics)
  691. return;
  692. ent = tor_malloc_zero(sizeof(dirreq_map_entry_t));
  693. ent->dirreq_id = dirreq_id;
  694. tor_gettimeofday(&ent->request_time);
  695. ent->response_size = response_size;
  696. ent->type = type;
  697. dirreq_map_put_(ent, type, dirreq_id);
  698. }
  699. /** Change the state of the either direct or tunneled (see <b>type</b>)
  700. * directory request with <b>dirreq_id</b> to <b>new_state</b> and
  701. * possibly mark it as completed. If no entry can be found for the given
  702. * key parts (e.g., if this is a directory request that we are not
  703. * measuring, or one that was started in the previous measurement period),
  704. * or if the state cannot be advanced to <b>new_state</b>, do nothing. */
  705. void
  706. geoip_change_dirreq_state(uint64_t dirreq_id, dirreq_type_t type,
  707. dirreq_state_t new_state)
  708. {
  709. dirreq_map_entry_t *ent;
  710. if (!get_options()->DirReqStatistics)
  711. return;
  712. ent = dirreq_map_get_(type, dirreq_id);
  713. if (!ent)
  714. return;
  715. if (new_state == DIRREQ_IS_FOR_NETWORK_STATUS)
  716. return;
  717. if (new_state - 1 != ent->state)
  718. return;
  719. ent->state = new_state;
  720. if ((type == DIRREQ_DIRECT &&
  721. new_state == DIRREQ_FLUSHING_DIR_CONN_FINISHED) ||
  722. (type == DIRREQ_TUNNELED &&
  723. new_state == DIRREQ_CHANNEL_BUFFER_FLUSHED)) {
  724. tor_gettimeofday(&ent->completion_time);
  725. ent->completed = 1;
  726. }
  727. }
  728. /** Return the bridge-ip-transports string that should be inserted in
  729. * our extra-info descriptor. Return NULL if the bridge-ip-transports
  730. * line should be empty. */
  731. char *
  732. geoip_get_transport_history(void)
  733. {
  734. unsigned granularity = IP_GRANULARITY;
  735. /** String hash table (name of transport) -> (number of users). */
  736. strmap_t *transport_counts = strmap_new();
  737. /** Smartlist that contains copies of the names of the transports
  738. that have been used. */
  739. smartlist_t *transports_used = smartlist_new();
  740. /* Special string to signify that no transport was used for this
  741. connection. Pluggable transport names can't have symbols in their
  742. names, so this string will never collide with a real transport. */
  743. static const char* no_transport_str = "<OR>";
  744. clientmap_entry_t **ent;
  745. const char *transport_name = NULL;
  746. smartlist_t *string_chunks = smartlist_new();
  747. char *the_string = NULL;
  748. /* If we haven't seen any clients yet, return NULL. */
  749. if (HT_EMPTY(&client_history))
  750. goto done;
  751. /** We do the following steps to form the transport history string:
  752. * a) Foreach client that uses a pluggable transport, we increase the
  753. * times that transport was used by one. If the client did not use
  754. * a transport, we increase the number of times someone connected
  755. * without obfuscation.
  756. * b) Foreach transport we observed, we write its transport history
  757. * string and push it to string_chunks. So, for example, if we've
  758. * seen 665 obfs2 clients, we write "obfs2=665".
  759. * c) We concatenate string_chunks to form the final string.
  760. */
  761. log_debug(LD_GENERAL,"Starting iteration for transport history. %d clients.",
  762. HT_SIZE(&client_history));
  763. /* Loop through all clients. */
  764. HT_FOREACH(ent, clientmap, &client_history) {
  765. uintptr_t val;
  766. void *ptr;
  767. transport_name = (*ent)->transport_name;
  768. if (!transport_name)
  769. transport_name = no_transport_str;
  770. /* Increase the count for this transport name. */
  771. ptr = strmap_get(transport_counts, transport_name);
  772. val = (uintptr_t)ptr;
  773. val++;
  774. ptr = (void*)val;
  775. strmap_set(transport_counts, transport_name, ptr);
  776. /* If it's the first time we see this transport, note it. */
  777. if (val == 1)
  778. smartlist_add(transports_used, tor_strdup(transport_name));
  779. log_debug(LD_GENERAL, "Client from '%s' with transport '%s'. "
  780. "I've now seen %d clients.",
  781. safe_str_client(fmt_addr(&(*ent)->addr)),
  782. transport_name ? transport_name : "<no transport>",
  783. (int)val);
  784. }
  785. /* Sort the transport names (helps with unit testing). */
  786. smartlist_sort_strings(transports_used);
  787. /* Loop through all seen transports. */
  788. SMARTLIST_FOREACH_BEGIN(transports_used, const char *, transport_name) {
  789. void *transport_count_ptr = strmap_get(transport_counts, transport_name);
  790. uintptr_t transport_count = (uintptr_t) transport_count_ptr;
  791. log_debug(LD_GENERAL, "We got "U64_FORMAT" clients with transport '%s'.",
  792. U64_PRINTF_ARG((uint64_t)transport_count), transport_name);
  793. smartlist_add_asprintf(string_chunks, "%s="U64_FORMAT,
  794. transport_name,
  795. U64_PRINTF_ARG(round_uint64_to_next_multiple_of(
  796. (uint64_t)transport_count,
  797. granularity)));
  798. } SMARTLIST_FOREACH_END(transport_name);
  799. the_string = smartlist_join_strings(string_chunks, ",", 0, NULL);
  800. log_debug(LD_GENERAL, "Final bridge-ip-transports string: '%s'", the_string);
  801. done:
  802. strmap_free(transport_counts, NULL);
  803. SMARTLIST_FOREACH(transports_used, char *, s, tor_free(s));
  804. smartlist_free(transports_used);
  805. SMARTLIST_FOREACH(string_chunks, char *, s, tor_free(s));
  806. smartlist_free(string_chunks);
  807. return the_string;
  808. }
  809. /** Return a newly allocated comma-separated string containing statistics
  810. * on network status downloads. The string contains the number of completed
  811. * requests, timeouts, and still running requests as well as the download
  812. * times by deciles and quartiles. Return NULL if we have not observed
  813. * requests for long enough. */
  814. static char *
  815. geoip_get_dirreq_history(dirreq_type_t type)
  816. {
  817. char *result = NULL;
  818. smartlist_t *dirreq_completed = NULL;
  819. uint32_t complete = 0, timeouts = 0, running = 0;
  820. int bufsize = 1024, written;
  821. dirreq_map_entry_t **ptr, **next, *ent;
  822. struct timeval now;
  823. tor_gettimeofday(&now);
  824. dirreq_completed = smartlist_new();
  825. for (ptr = HT_START(dirreqmap, &dirreq_map); ptr; ptr = next) {
  826. ent = *ptr;
  827. if (ent->type != type) {
  828. next = HT_NEXT(dirreqmap, &dirreq_map, ptr);
  829. continue;
  830. } else {
  831. if (ent->completed) {
  832. smartlist_add(dirreq_completed, ent);
  833. complete++;
  834. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr);
  835. } else {
  836. if (tv_mdiff(&ent->request_time, &now) / 1000 > DIRREQ_TIMEOUT)
  837. timeouts++;
  838. else
  839. running++;
  840. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr);
  841. tor_free(ent);
  842. }
  843. }
  844. }
  845. #define DIR_REQ_GRANULARITY 4
  846. complete = round_uint32_to_next_multiple_of(complete,
  847. DIR_REQ_GRANULARITY);
  848. timeouts = round_uint32_to_next_multiple_of(timeouts,
  849. DIR_REQ_GRANULARITY);
  850. running = round_uint32_to_next_multiple_of(running,
  851. DIR_REQ_GRANULARITY);
  852. result = tor_malloc_zero(bufsize);
  853. written = tor_snprintf(result, bufsize, "complete=%u,timeout=%u,"
  854. "running=%u", complete, timeouts, running);
  855. if (written < 0) {
  856. tor_free(result);
  857. goto done;
  858. }
  859. #define MIN_DIR_REQ_RESPONSES 16
  860. if (complete >= MIN_DIR_REQ_RESPONSES) {
  861. uint32_t *dltimes;
  862. /* We may have rounded 'completed' up. Here we want to use the
  863. * real value. */
  864. complete = smartlist_len(dirreq_completed);
  865. dltimes = tor_malloc_zero(sizeof(uint32_t) * complete);
  866. SMARTLIST_FOREACH_BEGIN(dirreq_completed, dirreq_map_entry_t *, ent) {
  867. uint32_t bytes_per_second;
  868. uint32_t time_diff = (uint32_t) tv_mdiff(&ent->request_time,
  869. &ent->completion_time);
  870. if (time_diff == 0)
  871. time_diff = 1; /* Avoid DIV/0; "instant" answers are impossible
  872. * by law of nature or something, but a milisecond
  873. * is a bit greater than "instantly" */
  874. bytes_per_second = (uint32_t)(1000 * ent->response_size / time_diff);
  875. dltimes[ent_sl_idx] = bytes_per_second;
  876. } SMARTLIST_FOREACH_END(ent);
  877. median_uint32(dltimes, complete); /* sorts as a side effect. */
  878. written = tor_snprintf(result + written, bufsize - written,
  879. ",min=%u,d1=%u,d2=%u,q1=%u,d3=%u,d4=%u,md=%u,"
  880. "d6=%u,d7=%u,q3=%u,d8=%u,d9=%u,max=%u",
  881. dltimes[0],
  882. dltimes[1*complete/10-1],
  883. dltimes[2*complete/10-1],
  884. dltimes[1*complete/4-1],
  885. dltimes[3*complete/10-1],
  886. dltimes[4*complete/10-1],
  887. dltimes[5*complete/10-1],
  888. dltimes[6*complete/10-1],
  889. dltimes[7*complete/10-1],
  890. dltimes[3*complete/4-1],
  891. dltimes[8*complete/10-1],
  892. dltimes[9*complete/10-1],
  893. dltimes[complete-1]);
  894. if (written<0)
  895. tor_free(result);
  896. tor_free(dltimes);
  897. }
  898. done:
  899. SMARTLIST_FOREACH(dirreq_completed, dirreq_map_entry_t *, ent,
  900. tor_free(ent));
  901. smartlist_free(dirreq_completed);
  902. return result;
  903. }
  904. /** Store a newly allocated comma-separated string in
  905. * *<a>country_str</a> containing entries for all the countries from
  906. * which we've seen enough clients connect as a bridge, directory
  907. * server, or entry guard. The entry format is cc=num where num is the
  908. * number of IPs we've seen connecting from that country, and cc is a
  909. * lowercased country code. *<a>country_str</a> is set to NULL if
  910. * we're not ready to export per country data yet.
  911. *
  912. * Store a newly allocated comma-separated string in <a>ipver_str</a>
  913. * containing entries for clients connecting over IPv4 and IPv6. The
  914. * format is family=num where num is the nubmer of IPs we've seen
  915. * connecting over that protocol family, and family is 'v4' or 'v6'.
  916. *
  917. * Return 0 on success and -1 if we're missing geoip data. */
  918. int
  919. geoip_get_client_history(geoip_client_action_t action,
  920. char **country_str, char **ipver_str)
  921. {
  922. unsigned granularity = IP_GRANULARITY;
  923. smartlist_t *entries = NULL;
  924. int n_countries = geoip_get_n_countries();
  925. int i;
  926. clientmap_entry_t **ent;
  927. unsigned *counts = NULL;
  928. unsigned total = 0;
  929. unsigned ipv4_count = 0, ipv6_count = 0;
  930. if (!geoip_is_loaded(AF_INET) && !geoip_is_loaded(AF_INET6))
  931. return -1;
  932. counts = tor_malloc_zero(sizeof(unsigned)*n_countries);
  933. HT_FOREACH(ent, clientmap, &client_history) {
  934. int country;
  935. if ((*ent)->action != (int)action)
  936. continue;
  937. country = geoip_get_country_by_addr(&(*ent)->addr);
  938. if (country < 0)
  939. country = 0; /** unresolved requests are stored at index 0. */
  940. tor_assert(0 <= country && country < n_countries);
  941. ++counts[country];
  942. ++total;
  943. switch (tor_addr_family(&(*ent)->addr)) {
  944. case AF_INET:
  945. ipv4_count++;
  946. break;
  947. case AF_INET6:
  948. ipv6_count++;
  949. break;
  950. }
  951. }
  952. if (ipver_str) {
  953. smartlist_t *chunks = smartlist_new();
  954. smartlist_add_asprintf(chunks, "v4=%u",
  955. round_to_next_multiple_of(ipv4_count, granularity));
  956. smartlist_add_asprintf(chunks, "v6=%u",
  957. round_to_next_multiple_of(ipv6_count, granularity));
  958. *ipver_str = smartlist_join_strings(chunks, ",", 0, NULL);
  959. SMARTLIST_FOREACH(chunks, char *, c, tor_free(c));
  960. smartlist_free(chunks);
  961. }
  962. /* Don't record per country data if we haven't seen enough IPs. */
  963. if (total < MIN_IPS_TO_NOTE_ANYTHING) {
  964. tor_free(counts);
  965. if (country_str)
  966. *country_str = NULL;
  967. return 0;
  968. }
  969. /* Make a list of c_hist_t */
  970. entries = smartlist_new();
  971. for (i = 0; i < n_countries; ++i) {
  972. unsigned c = counts[i];
  973. const char *countrycode;
  974. c_hist_t *ent;
  975. /* Only report a country if it has a minimum number of IPs. */
  976. if (c >= MIN_IPS_TO_NOTE_COUNTRY) {
  977. c = round_to_next_multiple_of(c, granularity);
  978. countrycode = geoip_get_country_name(i);
  979. ent = tor_malloc(sizeof(c_hist_t));
  980. strlcpy(ent->country, countrycode, sizeof(ent->country));
  981. ent->total = c;
  982. smartlist_add(entries, ent);
  983. }
  984. }
  985. /* Sort entries. Note that we must do this _AFTER_ rounding, or else
  986. * the sort order could leak info. */
  987. smartlist_sort(entries, c_hist_compare_);
  988. if (country_str) {
  989. smartlist_t *chunks = smartlist_new();
  990. SMARTLIST_FOREACH(entries, c_hist_t *, ch, {
  991. smartlist_add_asprintf(chunks, "%s=%u", ch->country, ch->total);
  992. });
  993. *country_str = smartlist_join_strings(chunks, ",", 0, NULL);
  994. SMARTLIST_FOREACH(chunks, char *, c, tor_free(c));
  995. smartlist_free(chunks);
  996. }
  997. SMARTLIST_FOREACH(entries, c_hist_t *, c, tor_free(c));
  998. smartlist_free(entries);
  999. tor_free(counts);
  1000. return 0;
  1001. }
  1002. /** Return a newly allocated string holding the per-country request history
  1003. * for v3 network statuses in a format suitable for an extra-info document,
  1004. * or NULL on failure. */
  1005. char *
  1006. geoip_get_request_history(void)
  1007. {
  1008. smartlist_t *entries, *strings;
  1009. char *result;
  1010. unsigned granularity = IP_GRANULARITY;
  1011. if (!geoip_countries)
  1012. return NULL;
  1013. entries = smartlist_new();
  1014. SMARTLIST_FOREACH_BEGIN(geoip_countries, geoip_country_t *, c) {
  1015. uint32_t tot = 0;
  1016. c_hist_t *ent;
  1017. tot = c->n_v3_ns_requests;
  1018. if (!tot)
  1019. continue;
  1020. ent = tor_malloc_zero(sizeof(c_hist_t));
  1021. strlcpy(ent->country, c->countrycode, sizeof(ent->country));
  1022. ent->total = round_to_next_multiple_of(tot, granularity);
  1023. smartlist_add(entries, ent);
  1024. } SMARTLIST_FOREACH_END(c);
  1025. smartlist_sort(entries, c_hist_compare_);
  1026. strings = smartlist_new();
  1027. SMARTLIST_FOREACH(entries, c_hist_t *, ent, {
  1028. smartlist_add_asprintf(strings, "%s=%u", ent->country, ent->total);
  1029. });
  1030. result = smartlist_join_strings(strings, ",", 0, NULL);
  1031. SMARTLIST_FOREACH(strings, char *, cp, tor_free(cp));
  1032. SMARTLIST_FOREACH(entries, c_hist_t *, ent, tor_free(ent));
  1033. smartlist_free(strings);
  1034. smartlist_free(entries);
  1035. return result;
  1036. }
  1037. /** Start time of directory request stats or 0 if we're not collecting
  1038. * directory request statistics. */
  1039. static time_t start_of_dirreq_stats_interval;
  1040. /** Initialize directory request stats. */
  1041. void
  1042. geoip_dirreq_stats_init(time_t now)
  1043. {
  1044. start_of_dirreq_stats_interval = now;
  1045. }
  1046. /** Reset counters for dirreq stats. */
  1047. void
  1048. geoip_reset_dirreq_stats(time_t now)
  1049. {
  1050. SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, {
  1051. c->n_v3_ns_requests = 0;
  1052. });
  1053. {
  1054. clientmap_entry_t **ent, **next, *this;
  1055. for (ent = HT_START(clientmap, &client_history); ent != NULL;
  1056. ent = next) {
  1057. if ((*ent)->action == GEOIP_CLIENT_NETWORKSTATUS) {
  1058. this = *ent;
  1059. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  1060. clientmap_entry_free(this);
  1061. } else {
  1062. next = HT_NEXT(clientmap, &client_history, ent);
  1063. }
  1064. }
  1065. }
  1066. memset(ns_v3_responses, 0, sizeof(ns_v3_responses));
  1067. {
  1068. dirreq_map_entry_t **ent, **next, *this;
  1069. for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) {
  1070. this = *ent;
  1071. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent);
  1072. tor_free(this);
  1073. }
  1074. }
  1075. start_of_dirreq_stats_interval = now;
  1076. }
  1077. /** Stop collecting directory request stats in a way that we can re-start
  1078. * doing so in geoip_dirreq_stats_init(). */
  1079. void
  1080. geoip_dirreq_stats_term(void)
  1081. {
  1082. geoip_reset_dirreq_stats(0);
  1083. }
  1084. /** Return a newly allocated string containing the dirreq statistics
  1085. * until <b>now</b>, or NULL if we're not collecting dirreq stats. Caller
  1086. * must ensure start_of_dirreq_stats_interval is in the past. */
  1087. char *
  1088. geoip_format_dirreq_stats(time_t now)
  1089. {
  1090. char t[ISO_TIME_LEN+1];
  1091. int i;
  1092. char *v3_ips_string, *v3_reqs_string, *v3_direct_dl_string,
  1093. *v3_tunneled_dl_string;
  1094. char *result;
  1095. if (!start_of_dirreq_stats_interval)
  1096. return NULL; /* Not initialized. */
  1097. tor_assert(now >= start_of_dirreq_stats_interval);
  1098. format_iso_time(t, now);
  1099. geoip_get_client_history(GEOIP_CLIENT_NETWORKSTATUS, &v3_ips_string, NULL);
  1100. v3_reqs_string = geoip_get_request_history();
  1101. #define RESPONSE_GRANULARITY 8
  1102. for (i = 0; i < GEOIP_NS_RESPONSE_NUM; i++) {
  1103. ns_v3_responses[i] = round_uint32_to_next_multiple_of(
  1104. ns_v3_responses[i], RESPONSE_GRANULARITY);
  1105. }
  1106. #undef RESPONSE_GRANULARITY
  1107. v3_direct_dl_string = geoip_get_dirreq_history(DIRREQ_DIRECT);
  1108. v3_tunneled_dl_string = geoip_get_dirreq_history(DIRREQ_TUNNELED);
  1109. /* Put everything together into a single string. */
  1110. tor_asprintf(&result, "dirreq-stats-end %s (%d s)\n"
  1111. "dirreq-v3-ips %s\n"
  1112. "dirreq-v3-reqs %s\n"
  1113. "dirreq-v3-resp ok=%u,not-enough-sigs=%u,unavailable=%u,"
  1114. "not-found=%u,not-modified=%u,busy=%u\n"
  1115. "dirreq-v3-direct-dl %s\n"
  1116. "dirreq-v3-tunneled-dl %s\n",
  1117. t,
  1118. (unsigned) (now - start_of_dirreq_stats_interval),
  1119. v3_ips_string ? v3_ips_string : "",
  1120. v3_reqs_string ? v3_reqs_string : "",
  1121. ns_v3_responses[GEOIP_SUCCESS],
  1122. ns_v3_responses[GEOIP_REJECT_NOT_ENOUGH_SIGS],
  1123. ns_v3_responses[GEOIP_REJECT_UNAVAILABLE],
  1124. ns_v3_responses[GEOIP_REJECT_NOT_FOUND],
  1125. ns_v3_responses[GEOIP_REJECT_NOT_MODIFIED],
  1126. ns_v3_responses[GEOIP_REJECT_BUSY],
  1127. v3_direct_dl_string ? v3_direct_dl_string : "",
  1128. v3_tunneled_dl_string ? v3_tunneled_dl_string : "");
  1129. /* Free partial strings. */
  1130. tor_free(v3_ips_string);
  1131. tor_free(v3_reqs_string);
  1132. tor_free(v3_direct_dl_string);
  1133. tor_free(v3_tunneled_dl_string);
  1134. return result;
  1135. }
  1136. /** If 24 hours have passed since the beginning of the current dirreq
  1137. * stats period, write dirreq stats to $DATADIR/stats/dirreq-stats
  1138. * (possibly overwriting an existing file) and reset counters. Return
  1139. * when we would next want to write dirreq stats or 0 if we never want to
  1140. * write. */
  1141. time_t
  1142. geoip_dirreq_stats_write(time_t now)
  1143. {
  1144. char *str = NULL;
  1145. if (!start_of_dirreq_stats_interval)
  1146. return 0; /* Not initialized. */
  1147. if (start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL > now)
  1148. goto done; /* Not ready to write. */
  1149. /* Discard all items in the client history that are too old. */
  1150. geoip_remove_old_clients(start_of_dirreq_stats_interval);
  1151. /* Generate history string .*/
  1152. str = geoip_format_dirreq_stats(now);
  1153. /* Write dirreq-stats string to disk. */
  1154. if (!check_or_create_data_subdir("stats")) {
  1155. write_to_data_subdir("stats", "dirreq-stats", str, "dirreq statistics");
  1156. /* Reset measurement interval start. */
  1157. geoip_reset_dirreq_stats(now);
  1158. }
  1159. done:
  1160. tor_free(str);
  1161. return start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL;
  1162. }
  1163. /** Start time of bridge stats or 0 if we're not collecting bridge
  1164. * statistics. */
  1165. static time_t start_of_bridge_stats_interval;
  1166. /** Initialize bridge stats. */
  1167. void
  1168. geoip_bridge_stats_init(time_t now)
  1169. {
  1170. start_of_bridge_stats_interval = now;
  1171. }
  1172. /** Stop collecting bridge stats in a way that we can re-start doing so in
  1173. * geoip_bridge_stats_init(). */
  1174. void
  1175. geoip_bridge_stats_term(void)
  1176. {
  1177. client_history_clear();
  1178. start_of_bridge_stats_interval = 0;
  1179. }
  1180. /** Validate a bridge statistics string as it would be written to a
  1181. * current extra-info descriptor. Return 1 if the string is valid and
  1182. * recent enough, or 0 otherwise. */
  1183. static int
  1184. validate_bridge_stats(const char *stats_str, time_t now)
  1185. {
  1186. char stats_end_str[ISO_TIME_LEN+1], stats_start_str[ISO_TIME_LEN+1],
  1187. *eos;
  1188. const char *BRIDGE_STATS_END = "bridge-stats-end ";
  1189. const char *BRIDGE_IPS = "bridge-ips ";
  1190. const char *BRIDGE_IPS_EMPTY_LINE = "bridge-ips\n";
  1191. const char *BRIDGE_TRANSPORTS = "bridge-ip-transports ";
  1192. const char *BRIDGE_TRANSPORTS_EMPTY_LINE = "bridge-ip-transports\n";
  1193. const char *tmp;
  1194. time_t stats_end_time;
  1195. int seconds;
  1196. tor_assert(stats_str);
  1197. /* Parse timestamp and number of seconds from
  1198. "bridge-stats-end YYYY-MM-DD HH:MM:SS (N s)" */
  1199. tmp = find_str_at_start_of_line(stats_str, BRIDGE_STATS_END);
  1200. if (!tmp)
  1201. return 0;
  1202. tmp += strlen(BRIDGE_STATS_END);
  1203. if (strlen(tmp) < ISO_TIME_LEN + 6)
  1204. return 0;
  1205. strlcpy(stats_end_str, tmp, sizeof(stats_end_str));
  1206. if (parse_iso_time(stats_end_str, &stats_end_time) < 0)
  1207. return 0;
  1208. if (stats_end_time < now - (25*60*60) ||
  1209. stats_end_time > now + (1*60*60))
  1210. return 0;
  1211. seconds = (int)strtol(tmp + ISO_TIME_LEN + 2, &eos, 10);
  1212. if (!eos || seconds < 23*60*60)
  1213. return 0;
  1214. format_iso_time(stats_start_str, stats_end_time - seconds);
  1215. /* Parse: "bridge-ips CC=N,CC=N,..." */
  1216. tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS);
  1217. if (!tmp) {
  1218. /* Look if there is an empty "bridge-ips" line */
  1219. tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS_EMPTY_LINE);
  1220. if (!tmp)
  1221. return 0;
  1222. }
  1223. /* Parse: "bridge-ip-transports PT=N,PT=N,..." */
  1224. tmp = find_str_at_start_of_line(stats_str, BRIDGE_TRANSPORTS);
  1225. if (!tmp) {
  1226. /* Look if there is an empty "bridge-ip-transports" line */
  1227. tmp = find_str_at_start_of_line(stats_str, BRIDGE_TRANSPORTS_EMPTY_LINE);
  1228. if (!tmp)
  1229. return 0;
  1230. }
  1231. return 1;
  1232. }
  1233. /** Most recent bridge statistics formatted to be written to extra-info
  1234. * descriptors. */
  1235. static char *bridge_stats_extrainfo = NULL;
  1236. /** Return a newly allocated string holding our bridge usage stats by country
  1237. * in a format suitable for inclusion in an extrainfo document. Return NULL on
  1238. * failure. */
  1239. char *
  1240. geoip_format_bridge_stats(time_t now)
  1241. {
  1242. char *out = NULL;
  1243. char *country_data = NULL, *ipver_data = NULL, *transport_data = NULL;
  1244. long duration = now - start_of_bridge_stats_interval;
  1245. char written[ISO_TIME_LEN+1];
  1246. if (duration < 0)
  1247. return NULL;
  1248. if (!start_of_bridge_stats_interval)
  1249. return NULL; /* Not initialized. */
  1250. format_iso_time(written, now);
  1251. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data);
  1252. transport_data = geoip_get_transport_history();
  1253. tor_asprintf(&out,
  1254. "bridge-stats-end %s (%ld s)\n"
  1255. "bridge-ips %s\n"
  1256. "bridge-ip-versions %s\n"
  1257. "bridge-ip-transports %s\n",
  1258. written, duration,
  1259. country_data ? country_data : "",
  1260. ipver_data ? ipver_data : "",
  1261. transport_data ? transport_data : "");
  1262. tor_free(country_data);
  1263. tor_free(ipver_data);
  1264. tor_free(transport_data);
  1265. return out;
  1266. }
  1267. /** Return a newly allocated string holding our bridge usage stats by country
  1268. * in a format suitable for the answer to a controller request. Return NULL on
  1269. * failure. */
  1270. static char *
  1271. format_bridge_stats_controller(time_t now)
  1272. {
  1273. char *out = NULL, *country_data = NULL, *ipver_data = NULL;
  1274. char started[ISO_TIME_LEN+1];
  1275. (void) now;
  1276. format_iso_time(started, start_of_bridge_stats_interval);
  1277. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data);
  1278. tor_asprintf(&out,
  1279. "TimeStarted=\"%s\" CountrySummary=%s IPVersions=%s",
  1280. started,
  1281. country_data ? country_data : "",
  1282. ipver_data ? ipver_data : "");
  1283. tor_free(country_data);
  1284. tor_free(ipver_data);
  1285. return out;
  1286. }
  1287. /** Write bridge statistics to $DATADIR/stats/bridge-stats and return
  1288. * when we should next try to write statistics. */
  1289. time_t
  1290. geoip_bridge_stats_write(time_t now)
  1291. {
  1292. char *val = NULL;
  1293. /* Check if 24 hours have passed since starting measurements. */
  1294. if (now < start_of_bridge_stats_interval + WRITE_STATS_INTERVAL)
  1295. return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL;
  1296. /* Discard all items in the client history that are too old. */
  1297. geoip_remove_old_clients(start_of_bridge_stats_interval);
  1298. /* Generate formatted string */
  1299. val = geoip_format_bridge_stats(now);
  1300. if (val == NULL)
  1301. goto done;
  1302. /* Update the stored value. */
  1303. tor_free(bridge_stats_extrainfo);
  1304. bridge_stats_extrainfo = val;
  1305. start_of_bridge_stats_interval = now;
  1306. /* Write it to disk. */
  1307. if (!check_or_create_data_subdir("stats")) {
  1308. write_to_data_subdir("stats", "bridge-stats",
  1309. bridge_stats_extrainfo, "bridge statistics");
  1310. /* Tell the controller, "hey, there are clients!" */
  1311. {
  1312. char *controller_str = format_bridge_stats_controller(now);
  1313. if (controller_str)
  1314. control_event_clients_seen(controller_str);
  1315. tor_free(controller_str);
  1316. }
  1317. }
  1318. done:
  1319. return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL;
  1320. }
  1321. /** Try to load the most recent bridge statistics from disk, unless we
  1322. * have finished a measurement interval lately, and check whether they
  1323. * are still recent enough. */
  1324. static void
  1325. load_bridge_stats(time_t now)
  1326. {
  1327. char *fname, *contents;
  1328. if (bridge_stats_extrainfo)
  1329. return;
  1330. fname = get_datadir_fname2("stats", "bridge-stats");
  1331. contents = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
  1332. if (contents && validate_bridge_stats(contents, now)) {
  1333. bridge_stats_extrainfo = contents;
  1334. } else {
  1335. tor_free(contents);
  1336. }
  1337. tor_free(fname);
  1338. }
  1339. /** Return most recent bridge statistics for inclusion in extra-info
  1340. * descriptors, or NULL if we don't have recent bridge statistics. */
  1341. const char *
  1342. geoip_get_bridge_stats_extrainfo(time_t now)
  1343. {
  1344. load_bridge_stats(now);
  1345. return bridge_stats_extrainfo;
  1346. }
  1347. /** Return a new string containing the recent bridge statistics to be returned
  1348. * to controller clients, or NULL if we don't have any bridge statistics. */
  1349. char *
  1350. geoip_get_bridge_stats_controller(time_t now)
  1351. {
  1352. return format_bridge_stats_controller(now);
  1353. }
  1354. /** Start time of entry stats or 0 if we're not collecting entry
  1355. * statistics. */
  1356. static time_t start_of_entry_stats_interval;
  1357. /** Initialize entry stats. */
  1358. void
  1359. geoip_entry_stats_init(time_t now)
  1360. {
  1361. start_of_entry_stats_interval = now;
  1362. }
  1363. /** Reset counters for entry stats. */
  1364. void
  1365. geoip_reset_entry_stats(time_t now)
  1366. {
  1367. client_history_clear();
  1368. start_of_entry_stats_interval = now;
  1369. }
  1370. /** Stop collecting entry stats in a way that we can re-start doing so in
  1371. * geoip_entry_stats_init(). */
  1372. void
  1373. geoip_entry_stats_term(void)
  1374. {
  1375. geoip_reset_entry_stats(0);
  1376. }
  1377. /** Return a newly allocated string containing the entry statistics
  1378. * until <b>now</b>, or NULL if we're not collecting entry stats. Caller
  1379. * must ensure start_of_entry_stats_interval lies in the past. */
  1380. char *
  1381. geoip_format_entry_stats(time_t now)
  1382. {
  1383. char t[ISO_TIME_LEN+1];
  1384. char *data = NULL;
  1385. char *result;
  1386. if (!start_of_entry_stats_interval)
  1387. return NULL; /* Not initialized. */
  1388. tor_assert(now >= start_of_entry_stats_interval);
  1389. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &data, NULL);
  1390. format_iso_time(t, now);
  1391. tor_asprintf(&result,
  1392. "entry-stats-end %s (%u s)\n"
  1393. "entry-ips %s\n",
  1394. t, (unsigned) (now - start_of_entry_stats_interval),
  1395. data ? data : "");
  1396. tor_free(data);
  1397. return result;
  1398. }
  1399. /** If 24 hours have passed since the beginning of the current entry stats
  1400. * period, write entry stats to $DATADIR/stats/entry-stats (possibly
  1401. * overwriting an existing file) and reset counters. Return when we would
  1402. * next want to write entry stats or 0 if we never want to write. */
  1403. time_t
  1404. geoip_entry_stats_write(time_t now)
  1405. {
  1406. char *str = NULL;
  1407. if (!start_of_entry_stats_interval)
  1408. return 0; /* Not initialized. */
  1409. if (start_of_entry_stats_interval + WRITE_STATS_INTERVAL > now)
  1410. goto done; /* Not ready to write. */
  1411. /* Discard all items in the client history that are too old. */
  1412. geoip_remove_old_clients(start_of_entry_stats_interval);
  1413. /* Generate history string .*/
  1414. str = geoip_format_entry_stats(now);
  1415. /* Write entry-stats string to disk. */
  1416. if (!check_or_create_data_subdir("stats")) {
  1417. write_to_data_subdir("stats", "entry-stats", str, "entry statistics");
  1418. /* Reset measurement interval start. */
  1419. geoip_reset_entry_stats(now);
  1420. }
  1421. done:
  1422. tor_free(str);
  1423. return start_of_entry_stats_interval + WRITE_STATS_INTERVAL;
  1424. }
  1425. /** Helper used to implement GETINFO ip-to-country/... controller command. */
  1426. int
  1427. getinfo_helper_geoip(control_connection_t *control_conn,
  1428. const char *question, char **answer,
  1429. const char **errmsg)
  1430. {
  1431. (void)control_conn;
  1432. if (!strcmpstart(question, "ip-to-country/")) {
  1433. int c;
  1434. sa_family_t family;
  1435. tor_addr_t addr;
  1436. question += strlen("ip-to-country/");
  1437. family = tor_addr_parse(&addr, question);
  1438. if (family != AF_INET && family != AF_INET6) {
  1439. *errmsg = "Invalid address family";
  1440. return -1;
  1441. }
  1442. if (!geoip_is_loaded(family)) {
  1443. *errmsg = "GeoIP data not loaded";
  1444. return -1;
  1445. }
  1446. if (family == AF_INET)
  1447. c = geoip_get_country_by_ipv4(tor_addr_to_ipv4h(&addr));
  1448. else /* AF_INET6 */
  1449. c = geoip_get_country_by_ipv6(tor_addr_to_in6(&addr));
  1450. *answer = tor_strdup(geoip_get_country_name(c));
  1451. }
  1452. return 0;
  1453. }
  1454. /** Release all storage held by the GeoIP databases and country list. */
  1455. static void
  1456. clear_geoip_db(void)
  1457. {
  1458. if (geoip_countries) {
  1459. SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, tor_free(c));
  1460. smartlist_free(geoip_countries);
  1461. }
  1462. strmap_free(country_idxplus1_by_lc_code, NULL);
  1463. if (geoip_ipv4_entries) {
  1464. SMARTLIST_FOREACH(geoip_ipv4_entries, geoip_ipv4_entry_t *, ent,
  1465. tor_free(ent));
  1466. smartlist_free(geoip_ipv4_entries);
  1467. }
  1468. if (geoip_ipv6_entries) {
  1469. SMARTLIST_FOREACH(geoip_ipv6_entries, geoip_ipv6_entry_t *, ent,
  1470. tor_free(ent));
  1471. smartlist_free(geoip_ipv6_entries);
  1472. }
  1473. geoip_countries = NULL;
  1474. country_idxplus1_by_lc_code = NULL;
  1475. geoip_ipv4_entries = NULL;
  1476. geoip_ipv6_entries = NULL;
  1477. }
  1478. /** Release all storage held in this file. */
  1479. void
  1480. geoip_free_all(void)
  1481. {
  1482. {
  1483. clientmap_entry_t **ent, **next, *this;
  1484. for (ent = HT_START(clientmap, &client_history); ent != NULL; ent = next) {
  1485. this = *ent;
  1486. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  1487. clientmap_entry_free(this);
  1488. }
  1489. HT_CLEAR(clientmap, &client_history);
  1490. }
  1491. {
  1492. dirreq_map_entry_t **ent, **next, *this;
  1493. for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) {
  1494. this = *ent;
  1495. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent);
  1496. tor_free(this);
  1497. }
  1498. HT_CLEAR(dirreqmap, &dirreq_map);
  1499. }
  1500. clear_geoip_db();
  1501. tor_free(bridge_stats_extrainfo);
  1502. }