geoip.c 45 KB

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