geoip.c 47 KB

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