geoip.c 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745
  1. /* Copyright (c) 2007-2017, 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;
  6. * to summarizing client connections by country to entry guards, bridges,
  7. * and directory servers; and for statistics on answering network status
  8. * requests.
  9. *
  10. * There are two main kinds of functions in this module: geoip functions,
  11. * which map groups of IPv4 and IPv6 addresses to country codes, and
  12. * statistical functions, which collect statistics about different kinds of
  13. * per-country usage.
  14. *
  15. * The geoip lookup tables are implemented as sorted lists of disjoint address
  16. * ranges, each mapping to a singleton geoip_country_t. These country objects
  17. * are also indexed by their names in a hashtable.
  18. *
  19. * The tables are populated from disk at startup by the geoip_load_file()
  20. * function. For more information on the file format they read, see that
  21. * function. See the scripts and the README file in src/config for more
  22. * information about how those files are generated.
  23. *
  24. * Tor uses GeoIP information in order to implement user requests (such as
  25. * ExcludeNodes {cc}), and to keep track of how much usage relays are getting
  26. * for each country.
  27. */
  28. #define GEOIP_PRIVATE
  29. #include "or.h"
  30. #include "ht.h"
  31. #include "buffers.h"
  32. #include "config.h"
  33. #include "control.h"
  34. #include "dnsserv.h"
  35. #include "geoip.h"
  36. #include "routerlist.h"
  37. static void init_geoip_countries(void);
  38. /** An entry from the GeoIP IPv4 file: maps an IPv4 range to a country. */
  39. typedef struct geoip_ipv4_entry_t {
  40. uint32_t ip_low; /**< The lowest IP in the range, in host order */
  41. uint32_t ip_high; /**< The highest IP in the range, in host order */
  42. intptr_t country; /**< An index into geoip_countries */
  43. } geoip_ipv4_entry_t;
  44. /** An entry from the GeoIP IPv6 file: maps an IPv6 range to a country. */
  45. typedef struct geoip_ipv6_entry_t {
  46. struct in6_addr ip_low; /**< The lowest IP in the range, in host order */
  47. struct in6_addr ip_high; /**< The highest IP in the range, in host order */
  48. intptr_t country; /**< An index into geoip_countries */
  49. } geoip_ipv6_entry_t;
  50. /** A per-country record for GeoIP request history. */
  51. typedef struct geoip_country_t {
  52. char countrycode[3];
  53. uint32_t n_v3_ns_requests;
  54. } geoip_country_t;
  55. /** A list of geoip_country_t */
  56. static smartlist_t *geoip_countries = NULL;
  57. /** A map from lowercased country codes to their position in geoip_countries.
  58. * The index is encoded in the pointer, and 1 is added so that NULL can mean
  59. * not found. */
  60. static strmap_t *country_idxplus1_by_lc_code = NULL;
  61. /** Lists of all known geoip_ipv4_entry_t and geoip_ipv6_entry_t, sorted
  62. * by their respective ip_low. */
  63. static smartlist_t *geoip_ipv4_entries = NULL, *geoip_ipv6_entries = NULL;
  64. /** SHA1 digest of the GeoIP files to include in extra-info descriptors. */
  65. static char geoip_digest[DIGEST_LEN];
  66. static char geoip6_digest[DIGEST_LEN];
  67. /** Return the index of the <b>country</b>'s entry in the GeoIP
  68. * country list if it is a valid 2-letter country code, otherwise
  69. * return -1. */
  70. MOCK_IMPL(country_t,
  71. geoip_get_country,(const char *country))
  72. {
  73. void *idxplus1_;
  74. intptr_t idx;
  75. idxplus1_ = strmap_get_lc(country_idxplus1_by_lc_code, country);
  76. if (!idxplus1_)
  77. return -1;
  78. idx = ((uintptr_t)idxplus1_)-1;
  79. return (country_t)idx;
  80. }
  81. /** Add an entry to a GeoIP table, mapping all IP addresses between <b>low</b>
  82. * and <b>high</b>, inclusive, to the 2-letter country code <b>country</b>. */
  83. static void
  84. geoip_add_entry(const tor_addr_t *low, const tor_addr_t *high,
  85. const char *country)
  86. {
  87. intptr_t idx;
  88. void *idxplus1_;
  89. IF_BUG_ONCE(tor_addr_family(low) != tor_addr_family(high))
  90. return;
  91. IF_BUG_ONCE(tor_addr_compare(high, low, CMP_EXACT) < 0)
  92. return;
  93. idxplus1_ = strmap_get_lc(country_idxplus1_by_lc_code, country);
  94. if (!idxplus1_) {
  95. geoip_country_t *c = tor_malloc_zero(sizeof(geoip_country_t));
  96. strlcpy(c->countrycode, country, sizeof(c->countrycode));
  97. tor_strlower(c->countrycode);
  98. smartlist_add(geoip_countries, c);
  99. idx = smartlist_len(geoip_countries) - 1;
  100. strmap_set_lc(country_idxplus1_by_lc_code, country, (void*)(idx+1));
  101. } else {
  102. idx = ((uintptr_t)idxplus1_)-1;
  103. }
  104. {
  105. geoip_country_t *c = smartlist_get(geoip_countries, idx);
  106. tor_assert(!strcasecmp(c->countrycode, country));
  107. }
  108. if (tor_addr_family(low) == AF_INET) {
  109. geoip_ipv4_entry_t *ent = tor_malloc_zero(sizeof(geoip_ipv4_entry_t));
  110. ent->ip_low = tor_addr_to_ipv4h(low);
  111. ent->ip_high = tor_addr_to_ipv4h(high);
  112. ent->country = idx;
  113. smartlist_add(geoip_ipv4_entries, ent);
  114. } else if (tor_addr_family(low) == AF_INET6) {
  115. geoip_ipv6_entry_t *ent = tor_malloc_zero(sizeof(geoip_ipv6_entry_t));
  116. ent->ip_low = *tor_addr_to_in6_assert(low);
  117. ent->ip_high = *tor_addr_to_in6_assert(high);
  118. ent->country = idx;
  119. smartlist_add(geoip_ipv6_entries, ent);
  120. }
  121. }
  122. /** Add an entry to the GeoIP table indicated by <b>family</b>,
  123. * parsing it from <b>line</b>. The format is as for geoip_load_file(). */
  124. STATIC int
  125. geoip_parse_entry(const char *line, sa_family_t family)
  126. {
  127. tor_addr_t low_addr, high_addr;
  128. char c[3];
  129. char *country = NULL;
  130. if (!geoip_countries)
  131. init_geoip_countries();
  132. if (family == AF_INET) {
  133. if (!geoip_ipv4_entries)
  134. geoip_ipv4_entries = smartlist_new();
  135. } else if (family == AF_INET6) {
  136. if (!geoip_ipv6_entries)
  137. geoip_ipv6_entries = smartlist_new();
  138. } else {
  139. log_warn(LD_GENERAL, "Unsupported family: %d", family);
  140. return -1;
  141. }
  142. while (TOR_ISSPACE(*line))
  143. ++line;
  144. if (*line == '#')
  145. return 0;
  146. char buf[512];
  147. if (family == AF_INET) {
  148. unsigned int low, high;
  149. if (tor_sscanf(line,"%u,%u,%2s", &low, &high, c) == 3 ||
  150. tor_sscanf(line,"\"%u\",\"%u\",\"%2s\",", &low, &high, c) == 3) {
  151. tor_addr_from_ipv4h(&low_addr, low);
  152. tor_addr_from_ipv4h(&high_addr, high);
  153. } else
  154. goto fail;
  155. country = c;
  156. } else { /* AF_INET6 */
  157. char *low_str, *high_str;
  158. struct in6_addr low, high;
  159. char *strtok_state;
  160. strlcpy(buf, line, sizeof(buf));
  161. low_str = tor_strtok_r(buf, ",", &strtok_state);
  162. if (!low_str)
  163. goto fail;
  164. high_str = tor_strtok_r(NULL, ",", &strtok_state);
  165. if (!high_str)
  166. goto fail;
  167. country = tor_strtok_r(NULL, "\n", &strtok_state);
  168. if (!country)
  169. goto fail;
  170. if (strlen(country) != 2)
  171. goto fail;
  172. if (tor_inet_pton(AF_INET6, low_str, &low) <= 0)
  173. goto fail;
  174. tor_addr_from_in6(&low_addr, &low);
  175. if (tor_inet_pton(AF_INET6, high_str, &high) <= 0)
  176. goto fail;
  177. tor_addr_from_in6(&high_addr, &high);
  178. }
  179. geoip_add_entry(&low_addr, &high_addr, country);
  180. return 0;
  181. fail:
  182. log_warn(LD_GENERAL, "Unable to parse line from GEOIP %s file: %s",
  183. family == AF_INET ? "IPv4" : "IPv6", escaped(line));
  184. return -1;
  185. }
  186. /** Sorting helper: return -1, 1, or 0 based on comparison of two
  187. * geoip_ipv4_entry_t */
  188. static int
  189. geoip_ipv4_compare_entries_(const void **_a, const void **_b)
  190. {
  191. const geoip_ipv4_entry_t *a = *_a, *b = *_b;
  192. if (a->ip_low < b->ip_low)
  193. return -1;
  194. else if (a->ip_low > b->ip_low)
  195. return 1;
  196. else
  197. return 0;
  198. }
  199. /** bsearch helper: return -1, 1, or 0 based on comparison of an IP (a pointer
  200. * to a uint32_t in host order) to a geoip_ipv4_entry_t */
  201. static int
  202. geoip_ipv4_compare_key_to_entry_(const void *_key, const void **_member)
  203. {
  204. /* No alignment issue here, since _key really is a pointer to uint32_t */
  205. const uint32_t addr = *(uint32_t *)_key;
  206. const geoip_ipv4_entry_t *entry = *_member;
  207. if (addr < entry->ip_low)
  208. return -1;
  209. else if (addr > entry->ip_high)
  210. return 1;
  211. else
  212. return 0;
  213. }
  214. /** Sorting helper: return -1, 1, or 0 based on comparison of two
  215. * geoip_ipv6_entry_t */
  216. static int
  217. geoip_ipv6_compare_entries_(const void **_a, const void **_b)
  218. {
  219. const geoip_ipv6_entry_t *a = *_a, *b = *_b;
  220. return fast_memcmp(a->ip_low.s6_addr, b->ip_low.s6_addr,
  221. sizeof(struct in6_addr));
  222. }
  223. /** bsearch helper: return -1, 1, or 0 based on comparison of an IPv6
  224. * (a pointer to a in6_addr) to a geoip_ipv6_entry_t */
  225. static int
  226. geoip_ipv6_compare_key_to_entry_(const void *_key, const void **_member)
  227. {
  228. const struct in6_addr *addr = (struct in6_addr *)_key;
  229. const geoip_ipv6_entry_t *entry = *_member;
  230. if (fast_memcmp(addr->s6_addr, entry->ip_low.s6_addr,
  231. sizeof(struct in6_addr)) < 0)
  232. return -1;
  233. else if (fast_memcmp(addr->s6_addr, entry->ip_high.s6_addr,
  234. sizeof(struct in6_addr)) > 0)
  235. return 1;
  236. else
  237. return 0;
  238. }
  239. /** Return 1 if we should collect geoip stats on bridge users, and
  240. * include them in our extrainfo descriptor. Else return 0. */
  241. int
  242. should_record_bridge_info(const or_options_t *options)
  243. {
  244. return options->BridgeRelay && options->BridgeRecordUsageByCountry;
  245. }
  246. /** Set up a new list of geoip countries with no countries (yet) set in it,
  247. * except for the unknown country.
  248. */
  249. static void
  250. init_geoip_countries(void)
  251. {
  252. geoip_country_t *geoip_unresolved;
  253. geoip_countries = smartlist_new();
  254. /* Add a geoip_country_t for requests that could not be resolved to a
  255. * country as first element (index 0) to geoip_countries. */
  256. geoip_unresolved = tor_malloc_zero(sizeof(geoip_country_t));
  257. strlcpy(geoip_unresolved->countrycode, "??",
  258. sizeof(geoip_unresolved->countrycode));
  259. smartlist_add(geoip_countries, geoip_unresolved);
  260. country_idxplus1_by_lc_code = strmap_new();
  261. strmap_set_lc(country_idxplus1_by_lc_code, "??", (void*)(1));
  262. }
  263. /** Clear appropriate GeoIP database, based on <b>family</b>, and
  264. * reload it from the file <b>filename</b>. Return 0 on success, -1 on
  265. * failure.
  266. *
  267. * Recognized line formats for IPv4 are:
  268. * INTIPLOW,INTIPHIGH,CC
  269. * and
  270. * "INTIPLOW","INTIPHIGH","CC","CC3","COUNTRY NAME"
  271. * where INTIPLOW and INTIPHIGH are IPv4 addresses encoded as 4-byte unsigned
  272. * integers, and CC is a country code.
  273. *
  274. * Recognized line format for IPv6 is:
  275. * IPV6LOW,IPV6HIGH,CC
  276. * where IPV6LOW and IPV6HIGH are IPv6 addresses and CC is a country code.
  277. *
  278. * It also recognizes, and skips over, blank lines and lines that start
  279. * with '#' (comments).
  280. */
  281. int
  282. geoip_load_file(sa_family_t family, const char *filename)
  283. {
  284. FILE *f;
  285. const char *msg = "";
  286. const or_options_t *options = get_options();
  287. int severity = options_need_geoip_info(options, &msg) ? LOG_WARN : LOG_INFO;
  288. crypto_digest_t *geoip_digest_env = NULL;
  289. tor_assert(family == AF_INET || family == AF_INET6);
  290. if (!(f = tor_fopen_cloexec(filename, "r"))) {
  291. log_fn(severity, LD_GENERAL, "Failed to open GEOIP file %s. %s",
  292. filename, msg);
  293. return -1;
  294. }
  295. if (!geoip_countries)
  296. init_geoip_countries();
  297. if (family == AF_INET) {
  298. if (geoip_ipv4_entries) {
  299. SMARTLIST_FOREACH(geoip_ipv4_entries, geoip_ipv4_entry_t *, e,
  300. tor_free(e));
  301. smartlist_free(geoip_ipv4_entries);
  302. }
  303. geoip_ipv4_entries = smartlist_new();
  304. } else { /* AF_INET6 */
  305. if (geoip_ipv6_entries) {
  306. SMARTLIST_FOREACH(geoip_ipv6_entries, geoip_ipv6_entry_t *, e,
  307. tor_free(e));
  308. smartlist_free(geoip_ipv6_entries);
  309. }
  310. geoip_ipv6_entries = smartlist_new();
  311. }
  312. geoip_digest_env = crypto_digest_new();
  313. log_notice(LD_GENERAL, "Parsing GEOIP %s file %s.",
  314. (family == AF_INET) ? "IPv4" : "IPv6", filename);
  315. while (!feof(f)) {
  316. char buf[512];
  317. if (fgets(buf, (int)sizeof(buf), f) == NULL)
  318. break;
  319. crypto_digest_add_bytes(geoip_digest_env, buf, strlen(buf));
  320. /* FFFF track full country name. */
  321. geoip_parse_entry(buf, family);
  322. }
  323. /*XXXX abort and return -1 if no entries/illformed?*/
  324. fclose(f);
  325. /* Sort list and remember file digests so that we can include it in
  326. * our extra-info descriptors. */
  327. if (family == AF_INET) {
  328. smartlist_sort(geoip_ipv4_entries, geoip_ipv4_compare_entries_);
  329. /* Okay, now we need to maybe change our mind about what is in
  330. * which country. We do this for IPv4 only since that's what we
  331. * store in node->country. */
  332. refresh_all_country_info();
  333. crypto_digest_get_digest(geoip_digest_env, geoip_digest, DIGEST_LEN);
  334. } else {
  335. /* AF_INET6 */
  336. smartlist_sort(geoip_ipv6_entries, geoip_ipv6_compare_entries_);
  337. crypto_digest_get_digest(geoip_digest_env, geoip6_digest, DIGEST_LEN);
  338. }
  339. crypto_digest_free(geoip_digest_env);
  340. return 0;
  341. }
  342. /** Given an IP address in host order, return a number representing the
  343. * country to which that address belongs, -1 for "No geoip information
  344. * available", or 0 for the 'unknown country'. The return value will always
  345. * be less than geoip_get_n_countries(). To decode it, call
  346. * geoip_get_country_name().
  347. */
  348. STATIC int
  349. geoip_get_country_by_ipv4(uint32_t ipaddr)
  350. {
  351. geoip_ipv4_entry_t *ent;
  352. if (!geoip_ipv4_entries)
  353. return -1;
  354. ent = smartlist_bsearch(geoip_ipv4_entries, &ipaddr,
  355. geoip_ipv4_compare_key_to_entry_);
  356. return ent ? (int)ent->country : 0;
  357. }
  358. /** Given an IPv6 address, return a number representing the country to
  359. * which that address belongs, -1 for "No geoip information available", or
  360. * 0 for the 'unknown country'. The return value will always be less than
  361. * geoip_get_n_countries(). To decode it, call geoip_get_country_name().
  362. */
  363. STATIC int
  364. geoip_get_country_by_ipv6(const struct in6_addr *addr)
  365. {
  366. geoip_ipv6_entry_t *ent;
  367. if (!geoip_ipv6_entries)
  368. return -1;
  369. ent = smartlist_bsearch(geoip_ipv6_entries, addr,
  370. geoip_ipv6_compare_key_to_entry_);
  371. return ent ? (int)ent->country : 0;
  372. }
  373. /** Given an IP address, return a number representing the country to which
  374. * that address belongs, -1 for "No geoip information available", or 0 for
  375. * the 'unknown country'. The return value will always be less than
  376. * geoip_get_n_countries(). To decode it, call geoip_get_country_name().
  377. */
  378. MOCK_IMPL(int,
  379. geoip_get_country_by_addr,(const tor_addr_t *addr))
  380. {
  381. if (tor_addr_family(addr) == AF_INET) {
  382. return geoip_get_country_by_ipv4(tor_addr_to_ipv4h(addr));
  383. } else if (tor_addr_family(addr) == AF_INET6) {
  384. return geoip_get_country_by_ipv6(tor_addr_to_in6(addr));
  385. } else {
  386. return -1;
  387. }
  388. }
  389. /** Return the number of countries recognized by the GeoIP country list. */
  390. MOCK_IMPL(int,
  391. geoip_get_n_countries,(void))
  392. {
  393. if (!geoip_countries)
  394. init_geoip_countries();
  395. return (int) smartlist_len(geoip_countries);
  396. }
  397. /** Return the two-letter country code associated with the number <b>num</b>,
  398. * or "??" for an unknown value. */
  399. const char *
  400. geoip_get_country_name(country_t num)
  401. {
  402. if (geoip_countries && num >= 0 && num < smartlist_len(geoip_countries)) {
  403. geoip_country_t *c = smartlist_get(geoip_countries, num);
  404. return c->countrycode;
  405. } else
  406. return "??";
  407. }
  408. /** Return true iff we have loaded a GeoIP database.*/
  409. MOCK_IMPL(int,
  410. geoip_is_loaded,(sa_family_t family))
  411. {
  412. tor_assert(family == AF_INET || family == AF_INET6);
  413. if (geoip_countries == NULL)
  414. return 0;
  415. if (family == AF_INET)
  416. return geoip_ipv4_entries != NULL;
  417. else /* AF_INET6 */
  418. return geoip_ipv6_entries != NULL;
  419. }
  420. /** Return the hex-encoded SHA1 digest of the loaded GeoIP file. The
  421. * result does not need to be deallocated, but will be overwritten by the
  422. * next call of hex_str(). */
  423. const char *
  424. geoip_db_digest(sa_family_t family)
  425. {
  426. tor_assert(family == AF_INET || family == AF_INET6);
  427. if (family == AF_INET)
  428. return hex_str(geoip_digest, DIGEST_LEN);
  429. else /* AF_INET6 */
  430. return hex_str(geoip6_digest, DIGEST_LEN);
  431. }
  432. /** Entry in a map from IP address to the last time we've seen an incoming
  433. * connection from that IP address. Used by bridges only, to track which
  434. * countries have them blocked. */
  435. typedef struct clientmap_entry_t {
  436. HT_ENTRY(clientmap_entry_t) node;
  437. tor_addr_t addr;
  438. /* Name of pluggable transport used by this client. NULL if no
  439. pluggable transport was used. */
  440. char *transport_name;
  441. /** Time when we last saw this IP address, in MINUTES since the epoch.
  442. *
  443. * (This will run out of space around 4011 CE. If Tor is still in use around
  444. * 4000 CE, please remember to add more bits to last_seen_in_minutes.) */
  445. unsigned int last_seen_in_minutes:30;
  446. unsigned int action:2;
  447. } clientmap_entry_t;
  448. /** Largest allowable value for last_seen_in_minutes. (It's a 30-bit field,
  449. * so it can hold up to (1u<<30)-1, or 0x3fffffffu.
  450. */
  451. #define MAX_LAST_SEEN_IN_MINUTES 0X3FFFFFFFu
  452. /** Map from client IP address to last time seen. */
  453. static HT_HEAD(clientmap, clientmap_entry_t) client_history =
  454. HT_INITIALIZER();
  455. /** Hashtable helper: compute a hash of a clientmap_entry_t. */
  456. static inline unsigned
  457. clientmap_entry_hash(const clientmap_entry_t *a)
  458. {
  459. unsigned h = (unsigned) tor_addr_hash(&a->addr);
  460. if (a->transport_name)
  461. h += (unsigned) siphash24g(a->transport_name, strlen(a->transport_name));
  462. return h;
  463. }
  464. /** Hashtable helper: compare two clientmap_entry_t values for equality. */
  465. static inline int
  466. clientmap_entries_eq(const clientmap_entry_t *a, const clientmap_entry_t *b)
  467. {
  468. if (strcmp_opt(a->transport_name, b->transport_name))
  469. return 0;
  470. return !tor_addr_compare(&a->addr, &b->addr, CMP_EXACT) &&
  471. a->action == b->action;
  472. }
  473. HT_PROTOTYPE(clientmap, clientmap_entry_t, node, clientmap_entry_hash,
  474. clientmap_entries_eq)
  475. HT_GENERATE2(clientmap, clientmap_entry_t, node, clientmap_entry_hash,
  476. clientmap_entries_eq, 0.6, tor_reallocarray_, tor_free_)
  477. /** Free all storage held by <b>ent</b>. */
  478. static void
  479. clientmap_entry_free(clientmap_entry_t *ent)
  480. {
  481. if (!ent)
  482. return;
  483. tor_free(ent->transport_name);
  484. tor_free(ent);
  485. }
  486. /** Clear history of connecting clients used by entry and bridge stats. */
  487. static void
  488. client_history_clear(void)
  489. {
  490. clientmap_entry_t **ent, **next, *this;
  491. for (ent = HT_START(clientmap, &client_history); ent != NULL;
  492. ent = next) {
  493. if ((*ent)->action == GEOIP_CLIENT_CONNECT) {
  494. this = *ent;
  495. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  496. clientmap_entry_free(this);
  497. } else {
  498. next = HT_NEXT(clientmap, &client_history, ent);
  499. }
  500. }
  501. }
  502. /** Note that we've seen a client connect from the IP <b>addr</b>
  503. * at time <b>now</b>. Ignored by all but bridges and directories if
  504. * configured accordingly. */
  505. void
  506. geoip_note_client_seen(geoip_client_action_t action,
  507. const tor_addr_t *addr,
  508. const char *transport_name,
  509. time_t now)
  510. {
  511. const or_options_t *options = get_options();
  512. clientmap_entry_t lookup, *ent;
  513. memset(&lookup, 0, sizeof(clientmap_entry_t));
  514. if (action == GEOIP_CLIENT_CONNECT) {
  515. /* Only remember statistics as entry guard or as bridge. */
  516. if (!options->EntryStatistics &&
  517. (!(options->BridgeRelay && options->BridgeRecordUsageByCountry)))
  518. return;
  519. } else {
  520. /* Only gather directory-request statistics if configured, and
  521. * forcibly disable them on bridge authorities. */
  522. if (!options->DirReqStatistics || options->BridgeAuthoritativeDir)
  523. return;
  524. }
  525. log_debug(LD_GENERAL, "Seen client from '%s' with transport '%s'.",
  526. safe_str_client(fmt_addr((addr))),
  527. transport_name ? transport_name : "<no transport>");
  528. tor_addr_copy(&lookup.addr, addr);
  529. lookup.action = (int)action;
  530. lookup.transport_name = (char*) transport_name;
  531. ent = HT_FIND(clientmap, &client_history, &lookup);
  532. if (! ent) {
  533. ent = tor_malloc_zero(sizeof(clientmap_entry_t));
  534. tor_addr_copy(&ent->addr, addr);
  535. if (transport_name)
  536. ent->transport_name = tor_strdup(transport_name);
  537. ent->action = (int)action;
  538. HT_INSERT(clientmap, &client_history, ent);
  539. }
  540. if (now / 60 <= (int)MAX_LAST_SEEN_IN_MINUTES && now >= 0)
  541. ent->last_seen_in_minutes = (unsigned)(now/60);
  542. else
  543. ent->last_seen_in_minutes = 0;
  544. if (action == GEOIP_CLIENT_NETWORKSTATUS) {
  545. int country_idx = geoip_get_country_by_addr(addr);
  546. if (country_idx < 0)
  547. country_idx = 0; /** unresolved requests are stored at index 0. */
  548. if (country_idx >= 0 && country_idx < smartlist_len(geoip_countries)) {
  549. geoip_country_t *country = smartlist_get(geoip_countries, country_idx);
  550. ++country->n_v3_ns_requests;
  551. }
  552. }
  553. }
  554. /** HT_FOREACH helper: remove a clientmap_entry_t from the hashtable if it's
  555. * older than a certain time. */
  556. static int
  557. remove_old_client_helper_(struct clientmap_entry_t *ent, void *_cutoff)
  558. {
  559. time_t cutoff = *(time_t*)_cutoff / 60;
  560. if (ent->last_seen_in_minutes < cutoff) {
  561. clientmap_entry_free(ent);
  562. return 1;
  563. } else {
  564. return 0;
  565. }
  566. }
  567. /** Forget about all clients that haven't connected since <b>cutoff</b>. */
  568. void
  569. geoip_remove_old_clients(time_t cutoff)
  570. {
  571. clientmap_HT_FOREACH_FN(&client_history,
  572. remove_old_client_helper_,
  573. &cutoff);
  574. }
  575. /** How many responses are we giving to clients requesting v3 network
  576. * statuses? */
  577. static uint32_t ns_v3_responses[GEOIP_NS_RESPONSE_NUM];
  578. /** Note that we've rejected a client's request for a v3 network status
  579. * for reason <b>reason</b> at time <b>now</b>. */
  580. void
  581. geoip_note_ns_response(geoip_ns_response_t response)
  582. {
  583. static int arrays_initialized = 0;
  584. if (!get_options()->DirReqStatistics)
  585. return;
  586. if (!arrays_initialized) {
  587. memset(ns_v3_responses, 0, sizeof(ns_v3_responses));
  588. arrays_initialized = 1;
  589. }
  590. tor_assert(response < GEOIP_NS_RESPONSE_NUM);
  591. ns_v3_responses[response]++;
  592. }
  593. /** Do not mention any country from which fewer than this number of IPs have
  594. * connected. This conceivably avoids reporting information that could
  595. * deanonymize users, though analysis is lacking. */
  596. #define MIN_IPS_TO_NOTE_COUNTRY 1
  597. /** Do not report any geoip data at all if we have fewer than this number of
  598. * IPs to report about. */
  599. #define MIN_IPS_TO_NOTE_ANYTHING 1
  600. /** When reporting geoip data about countries, round up to the nearest
  601. * multiple of this value. */
  602. #define IP_GRANULARITY 8
  603. /** Helper type: used to sort per-country totals by value. */
  604. typedef struct c_hist_t {
  605. char country[3]; /**< Two-letter country code. */
  606. unsigned total; /**< Total IP addresses seen in this country. */
  607. } c_hist_t;
  608. /** Sorting helper: return -1, 1, or 0 based on comparison of two
  609. * geoip_ipv4_entry_t. Sort in descending order of total, and then by country
  610. * code. */
  611. static int
  612. c_hist_compare_(const void **_a, const void **_b)
  613. {
  614. const c_hist_t *a = *_a, *b = *_b;
  615. if (a->total > b->total)
  616. return -1;
  617. else if (a->total < b->total)
  618. return 1;
  619. else
  620. return strcmp(a->country, b->country);
  621. }
  622. /** When there are incomplete directory requests at the end of a 24-hour
  623. * period, consider those requests running for longer than this timeout as
  624. * failed, the others as still running. */
  625. #define DIRREQ_TIMEOUT (10*60)
  626. /** Entry in a map from either chan->global_identifier for direct requests
  627. * or a unique circuit identifier for tunneled requests to request time,
  628. * response size, and completion time of a network status request. Used to
  629. * measure download times of requests to derive average client
  630. * bandwidths. */
  631. typedef struct dirreq_map_entry_t {
  632. HT_ENTRY(dirreq_map_entry_t) node;
  633. /** Unique identifier for this network status request; this is either the
  634. * chan->global_identifier of the dir channel (direct request) or a new
  635. * locally unique identifier of a circuit (tunneled request). This ID is
  636. * only unique among other direct or tunneled requests, respectively. */
  637. uint64_t dirreq_id;
  638. unsigned int state:3; /**< State of this directory request. */
  639. unsigned int type:1; /**< Is this a direct or a tunneled request? */
  640. unsigned int completed:1; /**< Is this request complete? */
  641. /** When did we receive the request and started sending the response? */
  642. struct timeval request_time;
  643. size_t response_size; /**< What is the size of the response in bytes? */
  644. struct timeval completion_time; /**< When did the request succeed? */
  645. } dirreq_map_entry_t;
  646. /** Map of all directory requests asking for v2 or v3 network statuses in
  647. * the current geoip-stats interval. Values are
  648. * of type *<b>dirreq_map_entry_t</b>. */
  649. static HT_HEAD(dirreqmap, dirreq_map_entry_t) dirreq_map =
  650. HT_INITIALIZER();
  651. static int
  652. dirreq_map_ent_eq(const dirreq_map_entry_t *a,
  653. const dirreq_map_entry_t *b)
  654. {
  655. return a->dirreq_id == b->dirreq_id && a->type == b->type;
  656. }
  657. /* DOCDOC dirreq_map_ent_hash */
  658. static unsigned
  659. dirreq_map_ent_hash(const dirreq_map_entry_t *entry)
  660. {
  661. unsigned u = (unsigned) entry->dirreq_id;
  662. u += entry->type << 20;
  663. return u;
  664. }
  665. HT_PROTOTYPE(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash,
  666. dirreq_map_ent_eq)
  667. HT_GENERATE2(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash,
  668. dirreq_map_ent_eq, 0.6, tor_reallocarray_, tor_free_)
  669. /** Helper: Put <b>entry</b> into map of directory requests using
  670. * <b>type</b> and <b>dirreq_id</b> as key parts. If there is
  671. * already an entry for that key, print out a BUG warning and return. */
  672. static void
  673. dirreq_map_put_(dirreq_map_entry_t *entry, dirreq_type_t type,
  674. uint64_t dirreq_id)
  675. {
  676. dirreq_map_entry_t *old_ent;
  677. tor_assert(entry->type == type);
  678. tor_assert(entry->dirreq_id == dirreq_id);
  679. /* XXXX we could switch this to HT_INSERT some time, since it seems that
  680. * this bug doesn't happen. But since this function doesn't seem to be
  681. * critical-path, it's sane to leave it alone. */
  682. old_ent = HT_REPLACE(dirreqmap, &dirreq_map, entry);
  683. if (old_ent && old_ent != entry) {
  684. log_warn(LD_BUG, "Error when putting directory request into local "
  685. "map. There was already an entry for the same identifier.");
  686. return;
  687. }
  688. }
  689. /** Helper: Look up and return an entry in the map of directory requests
  690. * using <b>type</b> and <b>dirreq_id</b> as key parts. If there
  691. * is no such entry, return NULL. */
  692. static dirreq_map_entry_t *
  693. dirreq_map_get_(dirreq_type_t type, uint64_t dirreq_id)
  694. {
  695. dirreq_map_entry_t lookup;
  696. lookup.type = type;
  697. lookup.dirreq_id = dirreq_id;
  698. return HT_FIND(dirreqmap, &dirreq_map, &lookup);
  699. }
  700. /** Note that an either direct or tunneled (see <b>type</b>) directory
  701. * request for a v3 network status with unique ID <b>dirreq_id</b> of size
  702. * <b>response_size</b> has started. */
  703. void
  704. geoip_start_dirreq(uint64_t dirreq_id, size_t response_size,
  705. dirreq_type_t type)
  706. {
  707. dirreq_map_entry_t *ent;
  708. if (!get_options()->DirReqStatistics)
  709. return;
  710. ent = tor_malloc_zero(sizeof(dirreq_map_entry_t));
  711. ent->dirreq_id = dirreq_id;
  712. tor_gettimeofday(&ent->request_time);
  713. ent->response_size = response_size;
  714. ent->type = type;
  715. dirreq_map_put_(ent, type, dirreq_id);
  716. }
  717. /** Change the state of the either direct or tunneled (see <b>type</b>)
  718. * directory request with <b>dirreq_id</b> to <b>new_state</b> and
  719. * possibly mark it as completed. If no entry can be found for the given
  720. * key parts (e.g., if this is a directory request that we are not
  721. * measuring, or one that was started in the previous measurement period),
  722. * or if the state cannot be advanced to <b>new_state</b>, do nothing. */
  723. void
  724. geoip_change_dirreq_state(uint64_t dirreq_id, dirreq_type_t type,
  725. dirreq_state_t new_state)
  726. {
  727. dirreq_map_entry_t *ent;
  728. if (!get_options()->DirReqStatistics)
  729. return;
  730. ent = dirreq_map_get_(type, dirreq_id);
  731. if (!ent)
  732. return;
  733. if (new_state == DIRREQ_IS_FOR_NETWORK_STATUS)
  734. return;
  735. if (new_state - 1 != ent->state)
  736. return;
  737. ent->state = new_state;
  738. if ((type == DIRREQ_DIRECT &&
  739. new_state == DIRREQ_FLUSHING_DIR_CONN_FINISHED) ||
  740. (type == DIRREQ_TUNNELED &&
  741. new_state == DIRREQ_CHANNEL_BUFFER_FLUSHED)) {
  742. tor_gettimeofday(&ent->completion_time);
  743. ent->completed = 1;
  744. }
  745. }
  746. /** Return the bridge-ip-transports string that should be inserted in
  747. * our extra-info descriptor. Return NULL if the bridge-ip-transports
  748. * line should be empty. */
  749. char *
  750. geoip_get_transport_history(void)
  751. {
  752. unsigned granularity = IP_GRANULARITY;
  753. /** String hash table (name of transport) -> (number of users). */
  754. strmap_t *transport_counts = strmap_new();
  755. /** Smartlist that contains copies of the names of the transports
  756. that have been used. */
  757. smartlist_t *transports_used = smartlist_new();
  758. /* Special string to signify that no transport was used for this
  759. connection. Pluggable transport names can't have symbols in their
  760. names, so this string will never collide with a real transport. */
  761. static const char* no_transport_str = "<OR>";
  762. clientmap_entry_t **ent;
  763. smartlist_t *string_chunks = smartlist_new();
  764. char *the_string = NULL;
  765. /* If we haven't seen any clients yet, return NULL. */
  766. if (HT_EMPTY(&client_history))
  767. goto done;
  768. /** We do the following steps to form the transport history string:
  769. * a) Foreach client that uses a pluggable transport, we increase the
  770. * times that transport was used by one. If the client did not use
  771. * a transport, we increase the number of times someone connected
  772. * without obfuscation.
  773. * b) Foreach transport we observed, we write its transport history
  774. * string and push it to string_chunks. So, for example, if we've
  775. * seen 665 obfs2 clients, we write "obfs2=665".
  776. * c) We concatenate string_chunks to form the final string.
  777. */
  778. log_debug(LD_GENERAL,"Starting iteration for transport history. %d clients.",
  779. HT_SIZE(&client_history));
  780. /* Loop through all clients. */
  781. HT_FOREACH(ent, clientmap, &client_history) {
  782. uintptr_t val;
  783. void *ptr;
  784. const char *transport_name = (*ent)->transport_name;
  785. if (!transport_name)
  786. transport_name = no_transport_str;
  787. /* Increase the count for this transport name. */
  788. ptr = strmap_get(transport_counts, transport_name);
  789. val = (uintptr_t)ptr;
  790. val++;
  791. ptr = (void*)val;
  792. strmap_set(transport_counts, transport_name, ptr);
  793. /* If it's the first time we see this transport, note it. */
  794. if (val == 1)
  795. smartlist_add_strdup(transports_used, transport_name);
  796. log_debug(LD_GENERAL, "Client from '%s' with transport '%s'. "
  797. "I've now seen %d clients.",
  798. safe_str_client(fmt_addr(&(*ent)->addr)),
  799. transport_name ? transport_name : "<no transport>",
  800. (int)val);
  801. }
  802. /* Sort the transport names (helps with unit testing). */
  803. smartlist_sort_strings(transports_used);
  804. /* Loop through all seen transports. */
  805. SMARTLIST_FOREACH_BEGIN(transports_used, const char *, transport_name) {
  806. void *transport_count_ptr = strmap_get(transport_counts, transport_name);
  807. uintptr_t transport_count = (uintptr_t) transport_count_ptr;
  808. log_debug(LD_GENERAL, "We got "U64_FORMAT" clients with transport '%s'.",
  809. U64_PRINTF_ARG((uint64_t)transport_count), transport_name);
  810. smartlist_add_asprintf(string_chunks, "%s="U64_FORMAT,
  811. transport_name,
  812. U64_PRINTF_ARG(round_uint64_to_next_multiple_of(
  813. (uint64_t)transport_count,
  814. granularity)));
  815. } SMARTLIST_FOREACH_END(transport_name);
  816. the_string = smartlist_join_strings(string_chunks, ",", 0, NULL);
  817. log_debug(LD_GENERAL, "Final bridge-ip-transports string: '%s'", the_string);
  818. done:
  819. strmap_free(transport_counts, NULL);
  820. SMARTLIST_FOREACH(transports_used, char *, s, tor_free(s));
  821. smartlist_free(transports_used);
  822. SMARTLIST_FOREACH(string_chunks, char *, s, tor_free(s));
  823. smartlist_free(string_chunks);
  824. return the_string;
  825. }
  826. /** Return a newly allocated comma-separated string containing statistics
  827. * on network status downloads. The string contains the number of completed
  828. * requests, timeouts, and still running requests as well as the download
  829. * times by deciles and quartiles. Return NULL if we have not observed
  830. * requests for long enough. */
  831. static char *
  832. geoip_get_dirreq_history(dirreq_type_t type)
  833. {
  834. char *result = NULL;
  835. buf_t *buf = NULL;
  836. smartlist_t *dirreq_completed = NULL;
  837. uint32_t complete = 0, timeouts = 0, running = 0;
  838. dirreq_map_entry_t **ptr, **next;
  839. struct timeval now;
  840. tor_gettimeofday(&now);
  841. dirreq_completed = smartlist_new();
  842. for (ptr = HT_START(dirreqmap, &dirreq_map); ptr; ptr = next) {
  843. dirreq_map_entry_t *ent = *ptr;
  844. if (ent->type != type) {
  845. next = HT_NEXT(dirreqmap, &dirreq_map, ptr);
  846. continue;
  847. } else {
  848. if (ent->completed) {
  849. smartlist_add(dirreq_completed, ent);
  850. complete++;
  851. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr);
  852. } else {
  853. if (tv_mdiff(&ent->request_time, &now) / 1000 > DIRREQ_TIMEOUT)
  854. timeouts++;
  855. else
  856. running++;
  857. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr);
  858. tor_free(ent);
  859. }
  860. }
  861. }
  862. #define DIR_REQ_GRANULARITY 4
  863. complete = round_uint32_to_next_multiple_of(complete,
  864. DIR_REQ_GRANULARITY);
  865. timeouts = round_uint32_to_next_multiple_of(timeouts,
  866. DIR_REQ_GRANULARITY);
  867. running = round_uint32_to_next_multiple_of(running,
  868. DIR_REQ_GRANULARITY);
  869. buf = buf_new_with_capacity(1024);
  870. buf_add_printf(buf, "complete=%u,timeout=%u,"
  871. "running=%u", complete, timeouts, running);
  872. #define MIN_DIR_REQ_RESPONSES 16
  873. if (complete >= MIN_DIR_REQ_RESPONSES) {
  874. uint32_t *dltimes;
  875. /* We may have rounded 'completed' up. Here we want to use the
  876. * real value. */
  877. complete = smartlist_len(dirreq_completed);
  878. dltimes = tor_calloc(complete, sizeof(uint32_t));
  879. SMARTLIST_FOREACH_BEGIN(dirreq_completed, dirreq_map_entry_t *, ent) {
  880. uint32_t bytes_per_second;
  881. uint32_t time_diff = (uint32_t) tv_mdiff(&ent->request_time,
  882. &ent->completion_time);
  883. if (time_diff == 0)
  884. time_diff = 1; /* Avoid DIV/0; "instant" answers are impossible
  885. * by law of nature or something, but a millisecond
  886. * is a bit greater than "instantly" */
  887. bytes_per_second = (uint32_t)(1000 * ent->response_size / time_diff);
  888. dltimes[ent_sl_idx] = bytes_per_second;
  889. } SMARTLIST_FOREACH_END(ent);
  890. median_uint32(dltimes, complete); /* sorts as a side effect. */
  891. buf_add_printf(buf,
  892. ",min=%u,d1=%u,d2=%u,q1=%u,d3=%u,d4=%u,md=%u,"
  893. "d6=%u,d7=%u,q3=%u,d8=%u,d9=%u,max=%u",
  894. dltimes[0],
  895. dltimes[1*complete/10-1],
  896. dltimes[2*complete/10-1],
  897. dltimes[1*complete/4-1],
  898. dltimes[3*complete/10-1],
  899. dltimes[4*complete/10-1],
  900. dltimes[5*complete/10-1],
  901. dltimes[6*complete/10-1],
  902. dltimes[7*complete/10-1],
  903. dltimes[3*complete/4-1],
  904. dltimes[8*complete/10-1],
  905. dltimes[9*complete/10-1],
  906. dltimes[complete-1]);
  907. tor_free(dltimes);
  908. }
  909. result = buf_extract(buf, NULL);
  910. SMARTLIST_FOREACH(dirreq_completed, dirreq_map_entry_t *, ent,
  911. tor_free(ent));
  912. smartlist_free(dirreq_completed);
  913. buf_free(buf);
  914. return result;
  915. }
  916. /** Store a newly allocated comma-separated string in
  917. * *<a>country_str</a> containing entries for all the countries from
  918. * which we've seen enough clients connect as a bridge, directory
  919. * server, or entry guard. The entry format is cc=num where num is the
  920. * number of IPs we've seen connecting from that country, and cc is a
  921. * lowercased country code. *<a>country_str</a> is set to NULL if
  922. * we're not ready to export per country data yet.
  923. *
  924. * Store a newly allocated comma-separated string in <a>ipver_str</a>
  925. * containing entries for clients connecting over IPv4 and IPv6. The
  926. * format is family=num where num is the nubmer of IPs we've seen
  927. * connecting over that protocol family, and family is 'v4' or 'v6'.
  928. *
  929. * Return 0 on success and -1 if we're missing geoip data. */
  930. int
  931. geoip_get_client_history(geoip_client_action_t action,
  932. char **country_str, char **ipver_str)
  933. {
  934. unsigned granularity = IP_GRANULARITY;
  935. smartlist_t *entries = NULL;
  936. int n_countries = geoip_get_n_countries();
  937. int i;
  938. clientmap_entry_t **cm_ent;
  939. unsigned *counts = NULL;
  940. unsigned total = 0;
  941. unsigned ipv4_count = 0, ipv6_count = 0;
  942. if (!geoip_is_loaded(AF_INET) && !geoip_is_loaded(AF_INET6))
  943. return -1;
  944. counts = tor_calloc(n_countries, sizeof(unsigned));
  945. HT_FOREACH(cm_ent, clientmap, &client_history) {
  946. int country;
  947. if ((*cm_ent)->action != (int)action)
  948. continue;
  949. country = geoip_get_country_by_addr(&(*cm_ent)->addr);
  950. if (country < 0)
  951. country = 0; /** unresolved requests are stored at index 0. */
  952. tor_assert(0 <= country && country < n_countries);
  953. ++counts[country];
  954. ++total;
  955. switch (tor_addr_family(&(*cm_ent)->addr)) {
  956. case AF_INET:
  957. ipv4_count++;
  958. break;
  959. case AF_INET6:
  960. ipv6_count++;
  961. break;
  962. }
  963. }
  964. if (ipver_str) {
  965. smartlist_t *chunks = smartlist_new();
  966. smartlist_add_asprintf(chunks, "v4=%u",
  967. round_to_next_multiple_of(ipv4_count, granularity));
  968. smartlist_add_asprintf(chunks, "v6=%u",
  969. round_to_next_multiple_of(ipv6_count, granularity));
  970. *ipver_str = smartlist_join_strings(chunks, ",", 0, NULL);
  971. SMARTLIST_FOREACH(chunks, char *, c, tor_free(c));
  972. smartlist_free(chunks);
  973. }
  974. /* Don't record per country data if we haven't seen enough IPs. */
  975. if (total < MIN_IPS_TO_NOTE_ANYTHING) {
  976. tor_free(counts);
  977. if (country_str)
  978. *country_str = NULL;
  979. return 0;
  980. }
  981. /* Make a list of c_hist_t */
  982. entries = smartlist_new();
  983. for (i = 0; i < n_countries; ++i) {
  984. unsigned c = counts[i];
  985. const char *countrycode;
  986. c_hist_t *ent;
  987. /* Only report a country if it has a minimum number of IPs. */
  988. if (c >= MIN_IPS_TO_NOTE_COUNTRY) {
  989. c = round_to_next_multiple_of(c, granularity);
  990. countrycode = geoip_get_country_name(i);
  991. ent = tor_malloc(sizeof(c_hist_t));
  992. strlcpy(ent->country, countrycode, sizeof(ent->country));
  993. ent->total = c;
  994. smartlist_add(entries, ent);
  995. }
  996. }
  997. /* Sort entries. Note that we must do this _AFTER_ rounding, or else
  998. * the sort order could leak info. */
  999. smartlist_sort(entries, c_hist_compare_);
  1000. if (country_str) {
  1001. smartlist_t *chunks = smartlist_new();
  1002. SMARTLIST_FOREACH(entries, c_hist_t *, ch, {
  1003. smartlist_add_asprintf(chunks, "%s=%u", ch->country, ch->total);
  1004. });
  1005. *country_str = smartlist_join_strings(chunks, ",", 0, NULL);
  1006. SMARTLIST_FOREACH(chunks, char *, c, tor_free(c));
  1007. smartlist_free(chunks);
  1008. }
  1009. SMARTLIST_FOREACH(entries, c_hist_t *, c, tor_free(c));
  1010. smartlist_free(entries);
  1011. tor_free(counts);
  1012. return 0;
  1013. }
  1014. /** Return a newly allocated string holding the per-country request history
  1015. * for v3 network statuses in a format suitable for an extra-info document,
  1016. * or NULL on failure. */
  1017. char *
  1018. geoip_get_request_history(void)
  1019. {
  1020. smartlist_t *entries, *strings;
  1021. char *result;
  1022. unsigned granularity = IP_GRANULARITY;
  1023. if (!geoip_countries)
  1024. return NULL;
  1025. entries = smartlist_new();
  1026. SMARTLIST_FOREACH_BEGIN(geoip_countries, geoip_country_t *, c) {
  1027. uint32_t tot = 0;
  1028. c_hist_t *ent;
  1029. tot = c->n_v3_ns_requests;
  1030. if (!tot)
  1031. continue;
  1032. ent = tor_malloc_zero(sizeof(c_hist_t));
  1033. strlcpy(ent->country, c->countrycode, sizeof(ent->country));
  1034. ent->total = round_to_next_multiple_of(tot, granularity);
  1035. smartlist_add(entries, ent);
  1036. } SMARTLIST_FOREACH_END(c);
  1037. smartlist_sort(entries, c_hist_compare_);
  1038. strings = smartlist_new();
  1039. SMARTLIST_FOREACH(entries, c_hist_t *, ent, {
  1040. smartlist_add_asprintf(strings, "%s=%u", ent->country, ent->total);
  1041. });
  1042. result = smartlist_join_strings(strings, ",", 0, NULL);
  1043. SMARTLIST_FOREACH(strings, char *, cp, tor_free(cp));
  1044. SMARTLIST_FOREACH(entries, c_hist_t *, ent, tor_free(ent));
  1045. smartlist_free(strings);
  1046. smartlist_free(entries);
  1047. return result;
  1048. }
  1049. /** Start time of directory request stats or 0 if we're not collecting
  1050. * directory request statistics. */
  1051. static time_t start_of_dirreq_stats_interval;
  1052. /** Initialize directory request stats. */
  1053. void
  1054. geoip_dirreq_stats_init(time_t now)
  1055. {
  1056. start_of_dirreq_stats_interval = now;
  1057. }
  1058. /** Reset counters for dirreq stats. */
  1059. void
  1060. geoip_reset_dirreq_stats(time_t now)
  1061. {
  1062. SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, {
  1063. c->n_v3_ns_requests = 0;
  1064. });
  1065. {
  1066. clientmap_entry_t **ent, **next, *this;
  1067. for (ent = HT_START(clientmap, &client_history); ent != NULL;
  1068. ent = next) {
  1069. if ((*ent)->action == GEOIP_CLIENT_NETWORKSTATUS) {
  1070. this = *ent;
  1071. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  1072. clientmap_entry_free(this);
  1073. } else {
  1074. next = HT_NEXT(clientmap, &client_history, ent);
  1075. }
  1076. }
  1077. }
  1078. memset(ns_v3_responses, 0, sizeof(ns_v3_responses));
  1079. {
  1080. dirreq_map_entry_t **ent, **next, *this;
  1081. for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) {
  1082. this = *ent;
  1083. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent);
  1084. tor_free(this);
  1085. }
  1086. }
  1087. start_of_dirreq_stats_interval = now;
  1088. }
  1089. /** Stop collecting directory request stats in a way that we can re-start
  1090. * doing so in geoip_dirreq_stats_init(). */
  1091. void
  1092. geoip_dirreq_stats_term(void)
  1093. {
  1094. geoip_reset_dirreq_stats(0);
  1095. }
  1096. /** Return a newly allocated string containing the dirreq statistics
  1097. * until <b>now</b>, or NULL if we're not collecting dirreq stats. Caller
  1098. * must ensure start_of_dirreq_stats_interval is in the past. */
  1099. char *
  1100. geoip_format_dirreq_stats(time_t now)
  1101. {
  1102. char t[ISO_TIME_LEN+1];
  1103. int i;
  1104. char *v3_ips_string = NULL, *v3_reqs_string = NULL,
  1105. *v3_direct_dl_string = NULL, *v3_tunneled_dl_string = NULL;
  1106. char *result = NULL;
  1107. if (!start_of_dirreq_stats_interval)
  1108. return NULL; /* Not initialized. */
  1109. tor_assert(now >= start_of_dirreq_stats_interval);
  1110. format_iso_time(t, now);
  1111. geoip_get_client_history(GEOIP_CLIENT_NETWORKSTATUS, &v3_ips_string, NULL);
  1112. v3_reqs_string = geoip_get_request_history();
  1113. #define RESPONSE_GRANULARITY 8
  1114. for (i = 0; i < GEOIP_NS_RESPONSE_NUM; i++) {
  1115. ns_v3_responses[i] = round_uint32_to_next_multiple_of(
  1116. ns_v3_responses[i], RESPONSE_GRANULARITY);
  1117. }
  1118. #undef RESPONSE_GRANULARITY
  1119. v3_direct_dl_string = geoip_get_dirreq_history(DIRREQ_DIRECT);
  1120. v3_tunneled_dl_string = geoip_get_dirreq_history(DIRREQ_TUNNELED);
  1121. /* Put everything together into a single string. */
  1122. tor_asprintf(&result, "dirreq-stats-end %s (%d s)\n"
  1123. "dirreq-v3-ips %s\n"
  1124. "dirreq-v3-reqs %s\n"
  1125. "dirreq-v3-resp ok=%u,not-enough-sigs=%u,unavailable=%u,"
  1126. "not-found=%u,not-modified=%u,busy=%u\n"
  1127. "dirreq-v3-direct-dl %s\n"
  1128. "dirreq-v3-tunneled-dl %s\n",
  1129. t,
  1130. (unsigned) (now - start_of_dirreq_stats_interval),
  1131. v3_ips_string ? v3_ips_string : "",
  1132. v3_reqs_string ? v3_reqs_string : "",
  1133. ns_v3_responses[GEOIP_SUCCESS],
  1134. ns_v3_responses[GEOIP_REJECT_NOT_ENOUGH_SIGS],
  1135. ns_v3_responses[GEOIP_REJECT_UNAVAILABLE],
  1136. ns_v3_responses[GEOIP_REJECT_NOT_FOUND],
  1137. ns_v3_responses[GEOIP_REJECT_NOT_MODIFIED],
  1138. ns_v3_responses[GEOIP_REJECT_BUSY],
  1139. v3_direct_dl_string ? v3_direct_dl_string : "",
  1140. v3_tunneled_dl_string ? v3_tunneled_dl_string : "");
  1141. /* Free partial strings. */
  1142. tor_free(v3_ips_string);
  1143. tor_free(v3_reqs_string);
  1144. tor_free(v3_direct_dl_string);
  1145. tor_free(v3_tunneled_dl_string);
  1146. return result;
  1147. }
  1148. /** If 24 hours have passed since the beginning of the current dirreq
  1149. * stats period, write dirreq stats to $DATADIR/stats/dirreq-stats
  1150. * (possibly overwriting an existing file) and reset counters. Return
  1151. * when we would next want to write dirreq stats or 0 if we never want to
  1152. * write. */
  1153. time_t
  1154. geoip_dirreq_stats_write(time_t now)
  1155. {
  1156. char *str = NULL;
  1157. if (!start_of_dirreq_stats_interval)
  1158. return 0; /* Not initialized. */
  1159. if (start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL > now)
  1160. goto done; /* Not ready to write. */
  1161. /* Discard all items in the client history that are too old. */
  1162. geoip_remove_old_clients(start_of_dirreq_stats_interval);
  1163. /* Generate history string .*/
  1164. str = geoip_format_dirreq_stats(now);
  1165. if (! str)
  1166. goto done;
  1167. /* Write dirreq-stats string to disk. */
  1168. if (!check_or_create_data_subdir("stats")) {
  1169. write_to_data_subdir("stats", "dirreq-stats", str, "dirreq statistics");
  1170. /* Reset measurement interval start. */
  1171. geoip_reset_dirreq_stats(now);
  1172. }
  1173. done:
  1174. tor_free(str);
  1175. return start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL;
  1176. }
  1177. /** Start time of bridge stats or 0 if we're not collecting bridge
  1178. * statistics. */
  1179. static time_t start_of_bridge_stats_interval;
  1180. /** Initialize bridge stats. */
  1181. void
  1182. geoip_bridge_stats_init(time_t now)
  1183. {
  1184. start_of_bridge_stats_interval = now;
  1185. }
  1186. /** Stop collecting bridge stats in a way that we can re-start doing so in
  1187. * geoip_bridge_stats_init(). */
  1188. void
  1189. geoip_bridge_stats_term(void)
  1190. {
  1191. client_history_clear();
  1192. start_of_bridge_stats_interval = 0;
  1193. }
  1194. /** Validate a bridge statistics string as it would be written to a
  1195. * current extra-info descriptor. Return 1 if the string is valid and
  1196. * recent enough, or 0 otherwise. */
  1197. static int
  1198. validate_bridge_stats(const char *stats_str, time_t now)
  1199. {
  1200. char stats_end_str[ISO_TIME_LEN+1], stats_start_str[ISO_TIME_LEN+1],
  1201. *eos;
  1202. const char *BRIDGE_STATS_END = "bridge-stats-end ";
  1203. const char *BRIDGE_IPS = "bridge-ips ";
  1204. const char *BRIDGE_IPS_EMPTY_LINE = "bridge-ips\n";
  1205. const char *BRIDGE_TRANSPORTS = "bridge-ip-transports ";
  1206. const char *BRIDGE_TRANSPORTS_EMPTY_LINE = "bridge-ip-transports\n";
  1207. const char *tmp;
  1208. time_t stats_end_time;
  1209. int seconds;
  1210. tor_assert(stats_str);
  1211. /* Parse timestamp and number of seconds from
  1212. "bridge-stats-end YYYY-MM-DD HH:MM:SS (N s)" */
  1213. tmp = find_str_at_start_of_line(stats_str, BRIDGE_STATS_END);
  1214. if (!tmp)
  1215. return 0;
  1216. tmp += strlen(BRIDGE_STATS_END);
  1217. if (strlen(tmp) < ISO_TIME_LEN + 6)
  1218. return 0;
  1219. strlcpy(stats_end_str, tmp, sizeof(stats_end_str));
  1220. if (parse_iso_time(stats_end_str, &stats_end_time) < 0)
  1221. return 0;
  1222. if (stats_end_time < now - (25*60*60) ||
  1223. stats_end_time > now + (1*60*60))
  1224. return 0;
  1225. seconds = (int)strtol(tmp + ISO_TIME_LEN + 2, &eos, 10);
  1226. if (!eos || seconds < 23*60*60)
  1227. return 0;
  1228. format_iso_time(stats_start_str, stats_end_time - seconds);
  1229. /* Parse: "bridge-ips CC=N,CC=N,..." */
  1230. tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS);
  1231. if (!tmp) {
  1232. /* Look if there is an empty "bridge-ips" line */
  1233. tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS_EMPTY_LINE);
  1234. if (!tmp)
  1235. return 0;
  1236. }
  1237. /* Parse: "bridge-ip-transports PT=N,PT=N,..." */
  1238. tmp = find_str_at_start_of_line(stats_str, BRIDGE_TRANSPORTS);
  1239. if (!tmp) {
  1240. /* Look if there is an empty "bridge-ip-transports" line */
  1241. tmp = find_str_at_start_of_line(stats_str, BRIDGE_TRANSPORTS_EMPTY_LINE);
  1242. if (!tmp)
  1243. return 0;
  1244. }
  1245. return 1;
  1246. }
  1247. /** Most recent bridge statistics formatted to be written to extra-info
  1248. * descriptors. */
  1249. static char *bridge_stats_extrainfo = NULL;
  1250. /** Return a newly allocated string holding our bridge usage stats by country
  1251. * in a format suitable for inclusion in an extrainfo document. Return NULL on
  1252. * failure. */
  1253. char *
  1254. geoip_format_bridge_stats(time_t now)
  1255. {
  1256. char *out = NULL;
  1257. char *country_data = NULL, *ipver_data = NULL, *transport_data = NULL;
  1258. long duration = now - start_of_bridge_stats_interval;
  1259. char written[ISO_TIME_LEN+1];
  1260. if (duration < 0)
  1261. return NULL;
  1262. if (!start_of_bridge_stats_interval)
  1263. return NULL; /* Not initialized. */
  1264. format_iso_time(written, now);
  1265. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data);
  1266. transport_data = geoip_get_transport_history();
  1267. tor_asprintf(&out,
  1268. "bridge-stats-end %s (%ld s)\n"
  1269. "bridge-ips %s\n"
  1270. "bridge-ip-versions %s\n"
  1271. "bridge-ip-transports %s\n",
  1272. written, duration,
  1273. country_data ? country_data : "",
  1274. ipver_data ? ipver_data : "",
  1275. transport_data ? transport_data : "");
  1276. tor_free(country_data);
  1277. tor_free(ipver_data);
  1278. tor_free(transport_data);
  1279. return out;
  1280. }
  1281. /** Return a newly allocated string holding our bridge usage stats by country
  1282. * in a format suitable for the answer to a controller request. Return NULL on
  1283. * failure. */
  1284. static char *
  1285. format_bridge_stats_controller(time_t now)
  1286. {
  1287. char *out = NULL, *country_data = NULL, *ipver_data = NULL;
  1288. char started[ISO_TIME_LEN+1];
  1289. (void) now;
  1290. format_iso_time(started, start_of_bridge_stats_interval);
  1291. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data);
  1292. tor_asprintf(&out,
  1293. "TimeStarted=\"%s\" CountrySummary=%s IPVersions=%s",
  1294. started,
  1295. country_data ? country_data : "",
  1296. ipver_data ? ipver_data : "");
  1297. tor_free(country_data);
  1298. tor_free(ipver_data);
  1299. return out;
  1300. }
  1301. /** Return a newly allocated string holding our bridge usage stats by
  1302. * country in a format suitable for inclusion in our heartbeat
  1303. * message. Return NULL on failure. */
  1304. char *
  1305. format_client_stats_heartbeat(time_t now)
  1306. {
  1307. const int n_hours = 6;
  1308. char *out = NULL;
  1309. int n_clients = 0;
  1310. clientmap_entry_t **ent;
  1311. unsigned cutoff = (unsigned)( (now-n_hours*3600)/60 );
  1312. if (!start_of_bridge_stats_interval)
  1313. return NULL; /* Not initialized. */
  1314. /* count unique IPs */
  1315. HT_FOREACH(ent, clientmap, &client_history) {
  1316. /* only count directly connecting clients */
  1317. if ((*ent)->action != GEOIP_CLIENT_CONNECT)
  1318. continue;
  1319. if ((*ent)->last_seen_in_minutes < cutoff)
  1320. continue;
  1321. n_clients++;
  1322. }
  1323. tor_asprintf(&out, "Heartbeat: "
  1324. "In the last %d hours, I have seen %d unique clients.",
  1325. n_hours,
  1326. n_clients);
  1327. return out;
  1328. }
  1329. /** Write bridge statistics to $DATADIR/stats/bridge-stats and return
  1330. * when we should next try to write statistics. */
  1331. time_t
  1332. geoip_bridge_stats_write(time_t now)
  1333. {
  1334. char *val = NULL;
  1335. /* Check if 24 hours have passed since starting measurements. */
  1336. if (now < start_of_bridge_stats_interval + WRITE_STATS_INTERVAL)
  1337. return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL;
  1338. /* Discard all items in the client history that are too old. */
  1339. geoip_remove_old_clients(start_of_bridge_stats_interval);
  1340. /* Generate formatted string */
  1341. val = geoip_format_bridge_stats(now);
  1342. if (val == NULL)
  1343. goto done;
  1344. /* Update the stored value. */
  1345. tor_free(bridge_stats_extrainfo);
  1346. bridge_stats_extrainfo = val;
  1347. start_of_bridge_stats_interval = now;
  1348. /* Write it to disk. */
  1349. if (!check_or_create_data_subdir("stats")) {
  1350. write_to_data_subdir("stats", "bridge-stats",
  1351. bridge_stats_extrainfo, "bridge statistics");
  1352. /* Tell the controller, "hey, there are clients!" */
  1353. {
  1354. char *controller_str = format_bridge_stats_controller(now);
  1355. if (controller_str)
  1356. control_event_clients_seen(controller_str);
  1357. tor_free(controller_str);
  1358. }
  1359. }
  1360. done:
  1361. return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL;
  1362. }
  1363. /** Try to load the most recent bridge statistics from disk, unless we
  1364. * have finished a measurement interval lately, and check whether they
  1365. * are still recent enough. */
  1366. static void
  1367. load_bridge_stats(time_t now)
  1368. {
  1369. char *fname, *contents;
  1370. if (bridge_stats_extrainfo)
  1371. return;
  1372. fname = get_datadir_fname2("stats", "bridge-stats");
  1373. contents = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
  1374. if (contents && validate_bridge_stats(contents, now)) {
  1375. bridge_stats_extrainfo = contents;
  1376. } else {
  1377. tor_free(contents);
  1378. }
  1379. tor_free(fname);
  1380. }
  1381. /** Return most recent bridge statistics for inclusion in extra-info
  1382. * descriptors, or NULL if we don't have recent bridge statistics. */
  1383. const char *
  1384. geoip_get_bridge_stats_extrainfo(time_t now)
  1385. {
  1386. load_bridge_stats(now);
  1387. return bridge_stats_extrainfo;
  1388. }
  1389. /** Return a new string containing the recent bridge statistics to be returned
  1390. * to controller clients, or NULL if we don't have any bridge statistics. */
  1391. char *
  1392. geoip_get_bridge_stats_controller(time_t now)
  1393. {
  1394. return format_bridge_stats_controller(now);
  1395. }
  1396. /** Start time of entry stats or 0 if we're not collecting entry
  1397. * statistics. */
  1398. static time_t start_of_entry_stats_interval;
  1399. /** Initialize entry stats. */
  1400. void
  1401. geoip_entry_stats_init(time_t now)
  1402. {
  1403. start_of_entry_stats_interval = now;
  1404. }
  1405. /** Reset counters for entry stats. */
  1406. void
  1407. geoip_reset_entry_stats(time_t now)
  1408. {
  1409. client_history_clear();
  1410. start_of_entry_stats_interval = now;
  1411. }
  1412. /** Stop collecting entry stats in a way that we can re-start doing so in
  1413. * geoip_entry_stats_init(). */
  1414. void
  1415. geoip_entry_stats_term(void)
  1416. {
  1417. geoip_reset_entry_stats(0);
  1418. }
  1419. /** Return a newly allocated string containing the entry statistics
  1420. * until <b>now</b>, or NULL if we're not collecting entry stats. Caller
  1421. * must ensure start_of_entry_stats_interval lies in the past. */
  1422. char *
  1423. geoip_format_entry_stats(time_t now)
  1424. {
  1425. char t[ISO_TIME_LEN+1];
  1426. char *data = NULL;
  1427. char *result;
  1428. if (!start_of_entry_stats_interval)
  1429. return NULL; /* Not initialized. */
  1430. tor_assert(now >= start_of_entry_stats_interval);
  1431. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &data, NULL);
  1432. format_iso_time(t, now);
  1433. tor_asprintf(&result,
  1434. "entry-stats-end %s (%u s)\n"
  1435. "entry-ips %s\n",
  1436. t, (unsigned) (now - start_of_entry_stats_interval),
  1437. data ? data : "");
  1438. tor_free(data);
  1439. return result;
  1440. }
  1441. /** If 24 hours have passed since the beginning of the current entry stats
  1442. * period, write entry stats to $DATADIR/stats/entry-stats (possibly
  1443. * overwriting an existing file) and reset counters. Return when we would
  1444. * next want to write entry stats or 0 if we never want to write. */
  1445. time_t
  1446. geoip_entry_stats_write(time_t now)
  1447. {
  1448. char *str = NULL;
  1449. if (!start_of_entry_stats_interval)
  1450. return 0; /* Not initialized. */
  1451. if (start_of_entry_stats_interval + WRITE_STATS_INTERVAL > now)
  1452. goto done; /* Not ready to write. */
  1453. /* Discard all items in the client history that are too old. */
  1454. geoip_remove_old_clients(start_of_entry_stats_interval);
  1455. /* Generate history string .*/
  1456. str = geoip_format_entry_stats(now);
  1457. /* Write entry-stats string to disk. */
  1458. if (!check_or_create_data_subdir("stats")) {
  1459. write_to_data_subdir("stats", "entry-stats", str, "entry statistics");
  1460. /* Reset measurement interval start. */
  1461. geoip_reset_entry_stats(now);
  1462. }
  1463. done:
  1464. tor_free(str);
  1465. return start_of_entry_stats_interval + WRITE_STATS_INTERVAL;
  1466. }
  1467. /** Helper used to implement GETINFO ip-to-country/... controller command. */
  1468. int
  1469. getinfo_helper_geoip(control_connection_t *control_conn,
  1470. const char *question, char **answer,
  1471. const char **errmsg)
  1472. {
  1473. (void)control_conn;
  1474. if (!strcmpstart(question, "ip-to-country/")) {
  1475. int c;
  1476. sa_family_t family;
  1477. tor_addr_t addr;
  1478. question += strlen("ip-to-country/");
  1479. if (!strcmp(question, "ipv4-available") ||
  1480. !strcmp(question, "ipv6-available")) {
  1481. family = !strcmp(question, "ipv4-available") ? AF_INET : AF_INET6;
  1482. const int available = geoip_is_loaded(family);
  1483. tor_asprintf(answer, "%d", !! available);
  1484. return 0;
  1485. }
  1486. family = tor_addr_parse(&addr, question);
  1487. if (family != AF_INET && family != AF_INET6) {
  1488. *errmsg = "Invalid address family";
  1489. return -1;
  1490. }
  1491. if (!geoip_is_loaded(family)) {
  1492. *errmsg = "GeoIP data not loaded";
  1493. return -1;
  1494. }
  1495. if (family == AF_INET)
  1496. c = geoip_get_country_by_ipv4(tor_addr_to_ipv4h(&addr));
  1497. else /* AF_INET6 */
  1498. c = geoip_get_country_by_ipv6(tor_addr_to_in6(&addr));
  1499. *answer = tor_strdup(geoip_get_country_name(c));
  1500. }
  1501. return 0;
  1502. }
  1503. /** Release all storage held by the GeoIP databases and country list. */
  1504. STATIC void
  1505. clear_geoip_db(void)
  1506. {
  1507. if (geoip_countries) {
  1508. SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, tor_free(c));
  1509. smartlist_free(geoip_countries);
  1510. }
  1511. strmap_free(country_idxplus1_by_lc_code, NULL);
  1512. if (geoip_ipv4_entries) {
  1513. SMARTLIST_FOREACH(geoip_ipv4_entries, geoip_ipv4_entry_t *, ent,
  1514. tor_free(ent));
  1515. smartlist_free(geoip_ipv4_entries);
  1516. }
  1517. if (geoip_ipv6_entries) {
  1518. SMARTLIST_FOREACH(geoip_ipv6_entries, geoip_ipv6_entry_t *, ent,
  1519. tor_free(ent));
  1520. smartlist_free(geoip_ipv6_entries);
  1521. }
  1522. geoip_countries = NULL;
  1523. country_idxplus1_by_lc_code = NULL;
  1524. geoip_ipv4_entries = NULL;
  1525. geoip_ipv6_entries = NULL;
  1526. }
  1527. /** Release all storage held in this file. */
  1528. void
  1529. geoip_free_all(void)
  1530. {
  1531. {
  1532. clientmap_entry_t **ent, **next, *this;
  1533. for (ent = HT_START(clientmap, &client_history); ent != NULL; ent = next) {
  1534. this = *ent;
  1535. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  1536. clientmap_entry_free(this);
  1537. }
  1538. HT_CLEAR(clientmap, &client_history);
  1539. }
  1540. {
  1541. dirreq_map_entry_t **ent, **next, *this;
  1542. for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) {
  1543. this = *ent;
  1544. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent);
  1545. tor_free(this);
  1546. }
  1547. HT_CLEAR(dirreqmap, &dirreq_map);
  1548. }
  1549. clear_geoip_db();
  1550. tor_free(bridge_stats_extrainfo);
  1551. }