geoip.c 60 KB

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