geoip.c 57 KB

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