geoip.c 56 KB

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