geoip.c 47 KB

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