geoip.c 49 KB

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