geoip.c 39 KB

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