geoip.c 41 KB

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