geoip.c 56 KB

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