geoip.c 46 KB

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