geoip.c 61 KB

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