geoip.c 47 KB

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