geoip.c 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748
  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. #define clientmap_entry_free(ent) \
  478. FREE_AND_NULL(clientmap_entry_t, clientmap_entry_free_, ent)
  479. /** Free all storage held by <b>ent</b>. */
  480. static void
  481. clientmap_entry_free_(clientmap_entry_t *ent)
  482. {
  483. if (!ent)
  484. return;
  485. tor_free(ent->transport_name);
  486. tor_free(ent);
  487. }
  488. /** Clear history of connecting clients used by entry and bridge stats. */
  489. static void
  490. client_history_clear(void)
  491. {
  492. clientmap_entry_t **ent, **next, *this;
  493. for (ent = HT_START(clientmap, &client_history); ent != NULL;
  494. ent = next) {
  495. if ((*ent)->action == GEOIP_CLIENT_CONNECT) {
  496. this = *ent;
  497. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  498. clientmap_entry_free(this);
  499. } else {
  500. next = HT_NEXT(clientmap, &client_history, ent);
  501. }
  502. }
  503. }
  504. /** Note that we've seen a client connect from the IP <b>addr</b>
  505. * at time <b>now</b>. Ignored by all but bridges and directories if
  506. * configured accordingly. */
  507. void
  508. geoip_note_client_seen(geoip_client_action_t action,
  509. const tor_addr_t *addr,
  510. const char *transport_name,
  511. time_t now)
  512. {
  513. const or_options_t *options = get_options();
  514. clientmap_entry_t lookup, *ent;
  515. memset(&lookup, 0, sizeof(clientmap_entry_t));
  516. if (action == GEOIP_CLIENT_CONNECT) {
  517. /* Only remember statistics as entry guard or as bridge. */
  518. if (!options->EntryStatistics &&
  519. (!(options->BridgeRelay && options->BridgeRecordUsageByCountry)))
  520. return;
  521. } else {
  522. /* Only gather directory-request statistics if configured, and
  523. * forcibly disable them on bridge authorities. */
  524. if (!options->DirReqStatistics || options->BridgeAuthoritativeDir)
  525. return;
  526. }
  527. log_debug(LD_GENERAL, "Seen client from '%s' with transport '%s'.",
  528. safe_str_client(fmt_addr((addr))),
  529. transport_name ? transport_name : "<no transport>");
  530. tor_addr_copy(&lookup.addr, addr);
  531. lookup.action = (int)action;
  532. lookup.transport_name = (char*) transport_name;
  533. ent = HT_FIND(clientmap, &client_history, &lookup);
  534. if (! ent) {
  535. ent = tor_malloc_zero(sizeof(clientmap_entry_t));
  536. tor_addr_copy(&ent->addr, addr);
  537. if (transport_name)
  538. ent->transport_name = tor_strdup(transport_name);
  539. ent->action = (int)action;
  540. HT_INSERT(clientmap, &client_history, ent);
  541. }
  542. if (now / 60 <= (int)MAX_LAST_SEEN_IN_MINUTES && now >= 0)
  543. ent->last_seen_in_minutes = (unsigned)(now/60);
  544. else
  545. ent->last_seen_in_minutes = 0;
  546. if (action == GEOIP_CLIENT_NETWORKSTATUS) {
  547. int country_idx = geoip_get_country_by_addr(addr);
  548. if (country_idx < 0)
  549. country_idx = 0; /** unresolved requests are stored at index 0. */
  550. if (country_idx >= 0 && country_idx < smartlist_len(geoip_countries)) {
  551. geoip_country_t *country = smartlist_get(geoip_countries, country_idx);
  552. ++country->n_v3_ns_requests;
  553. }
  554. }
  555. }
  556. /** HT_FOREACH helper: remove a clientmap_entry_t from the hashtable if it's
  557. * older than a certain time. */
  558. static int
  559. remove_old_client_helper_(struct clientmap_entry_t *ent, void *_cutoff)
  560. {
  561. time_t cutoff = *(time_t*)_cutoff / 60;
  562. if (ent->last_seen_in_minutes < cutoff) {
  563. clientmap_entry_free(ent);
  564. return 1;
  565. } else {
  566. return 0;
  567. }
  568. }
  569. /** Forget about all clients that haven't connected since <b>cutoff</b>. */
  570. void
  571. geoip_remove_old_clients(time_t cutoff)
  572. {
  573. clientmap_HT_FOREACH_FN(&client_history,
  574. remove_old_client_helper_,
  575. &cutoff);
  576. }
  577. /** How many responses are we giving to clients requesting v3 network
  578. * statuses? */
  579. static uint32_t ns_v3_responses[GEOIP_NS_RESPONSE_NUM];
  580. /** Note that we've rejected a client's request for a v3 network status
  581. * for reason <b>reason</b> at time <b>now</b>. */
  582. void
  583. geoip_note_ns_response(geoip_ns_response_t response)
  584. {
  585. static int arrays_initialized = 0;
  586. if (!get_options()->DirReqStatistics)
  587. return;
  588. if (!arrays_initialized) {
  589. memset(ns_v3_responses, 0, sizeof(ns_v3_responses));
  590. arrays_initialized = 1;
  591. }
  592. tor_assert(response < GEOIP_NS_RESPONSE_NUM);
  593. ns_v3_responses[response]++;
  594. }
  595. /** Do not mention any country from which fewer than this number of IPs have
  596. * connected. This conceivably avoids reporting information that could
  597. * deanonymize users, though analysis is lacking. */
  598. #define MIN_IPS_TO_NOTE_COUNTRY 1
  599. /** Do not report any geoip data at all if we have fewer than this number of
  600. * IPs to report about. */
  601. #define MIN_IPS_TO_NOTE_ANYTHING 1
  602. /** When reporting geoip data about countries, round up to the nearest
  603. * multiple of this value. */
  604. #define IP_GRANULARITY 8
  605. /** Helper type: used to sort per-country totals by value. */
  606. typedef struct c_hist_t {
  607. char country[3]; /**< Two-letter country code. */
  608. unsigned total; /**< Total IP addresses seen in this country. */
  609. } c_hist_t;
  610. /** Sorting helper: return -1, 1, or 0 based on comparison of two
  611. * geoip_ipv4_entry_t. Sort in descending order of total, and then by country
  612. * code. */
  613. static int
  614. c_hist_compare_(const void **_a, const void **_b)
  615. {
  616. const c_hist_t *a = *_a, *b = *_b;
  617. if (a->total > b->total)
  618. return -1;
  619. else if (a->total < b->total)
  620. return 1;
  621. else
  622. return strcmp(a->country, b->country);
  623. }
  624. /** When there are incomplete directory requests at the end of a 24-hour
  625. * period, consider those requests running for longer than this timeout as
  626. * failed, the others as still running. */
  627. #define DIRREQ_TIMEOUT (10*60)
  628. /** Entry in a map from either chan->global_identifier for direct requests
  629. * or a unique circuit identifier for tunneled requests to request time,
  630. * response size, and completion time of a network status request. Used to
  631. * measure download times of requests to derive average client
  632. * bandwidths. */
  633. typedef struct dirreq_map_entry_t {
  634. HT_ENTRY(dirreq_map_entry_t) node;
  635. /** Unique identifier for this network status request; this is either the
  636. * chan->global_identifier of the dir channel (direct request) or a new
  637. * locally unique identifier of a circuit (tunneled request). This ID is
  638. * only unique among other direct or tunneled requests, respectively. */
  639. uint64_t dirreq_id;
  640. unsigned int state:3; /**< State of this directory request. */
  641. unsigned int type:1; /**< Is this a direct or a tunneled request? */
  642. unsigned int completed:1; /**< Is this request complete? */
  643. /** When did we receive the request and started sending the response? */
  644. struct timeval request_time;
  645. size_t response_size; /**< What is the size of the response in bytes? */
  646. struct timeval completion_time; /**< When did the request succeed? */
  647. } dirreq_map_entry_t;
  648. /** Map of all directory requests asking for v2 or v3 network statuses in
  649. * the current geoip-stats interval. Values are
  650. * of type *<b>dirreq_map_entry_t</b>. */
  651. static HT_HEAD(dirreqmap, dirreq_map_entry_t) dirreq_map =
  652. HT_INITIALIZER();
  653. static int
  654. dirreq_map_ent_eq(const dirreq_map_entry_t *a,
  655. const dirreq_map_entry_t *b)
  656. {
  657. return a->dirreq_id == b->dirreq_id && a->type == b->type;
  658. }
  659. /* DOCDOC dirreq_map_ent_hash */
  660. static unsigned
  661. dirreq_map_ent_hash(const dirreq_map_entry_t *entry)
  662. {
  663. unsigned u = (unsigned) entry->dirreq_id;
  664. u += entry->type << 20;
  665. return u;
  666. }
  667. HT_PROTOTYPE(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash,
  668. dirreq_map_ent_eq)
  669. HT_GENERATE2(dirreqmap, dirreq_map_entry_t, node, dirreq_map_ent_hash,
  670. dirreq_map_ent_eq, 0.6, tor_reallocarray_, tor_free_)
  671. /** Helper: Put <b>entry</b> into map of directory requests using
  672. * <b>type</b> and <b>dirreq_id</b> as key parts. If there is
  673. * already an entry for that key, print out a BUG warning and return. */
  674. static void
  675. dirreq_map_put_(dirreq_map_entry_t *entry, dirreq_type_t type,
  676. uint64_t dirreq_id)
  677. {
  678. dirreq_map_entry_t *old_ent;
  679. tor_assert(entry->type == type);
  680. tor_assert(entry->dirreq_id == dirreq_id);
  681. /* XXXX we could switch this to HT_INSERT some time, since it seems that
  682. * this bug doesn't happen. But since this function doesn't seem to be
  683. * critical-path, it's sane to leave it alone. */
  684. old_ent = HT_REPLACE(dirreqmap, &dirreq_map, entry);
  685. if (old_ent && old_ent != entry) {
  686. log_warn(LD_BUG, "Error when putting directory request into local "
  687. "map. There was already an entry for the same identifier.");
  688. return;
  689. }
  690. }
  691. /** Helper: Look up and return an entry in the map of directory requests
  692. * using <b>type</b> and <b>dirreq_id</b> as key parts. If there
  693. * is no such entry, return NULL. */
  694. static dirreq_map_entry_t *
  695. dirreq_map_get_(dirreq_type_t type, uint64_t dirreq_id)
  696. {
  697. dirreq_map_entry_t lookup;
  698. lookup.type = type;
  699. lookup.dirreq_id = dirreq_id;
  700. return HT_FIND(dirreqmap, &dirreq_map, &lookup);
  701. }
  702. /** Note that an either direct or tunneled (see <b>type</b>) directory
  703. * request for a v3 network status with unique ID <b>dirreq_id</b> of size
  704. * <b>response_size</b> has started. */
  705. void
  706. geoip_start_dirreq(uint64_t dirreq_id, size_t response_size,
  707. dirreq_type_t type)
  708. {
  709. dirreq_map_entry_t *ent;
  710. if (!get_options()->DirReqStatistics)
  711. return;
  712. ent = tor_malloc_zero(sizeof(dirreq_map_entry_t));
  713. ent->dirreq_id = dirreq_id;
  714. tor_gettimeofday(&ent->request_time);
  715. ent->response_size = response_size;
  716. ent->type = type;
  717. dirreq_map_put_(ent, type, dirreq_id);
  718. }
  719. /** Change the state of the either direct or tunneled (see <b>type</b>)
  720. * directory request with <b>dirreq_id</b> to <b>new_state</b> and
  721. * possibly mark it as completed. If no entry can be found for the given
  722. * key parts (e.g., if this is a directory request that we are not
  723. * measuring, or one that was started in the previous measurement period),
  724. * or if the state cannot be advanced to <b>new_state</b>, do nothing. */
  725. void
  726. geoip_change_dirreq_state(uint64_t dirreq_id, dirreq_type_t type,
  727. dirreq_state_t new_state)
  728. {
  729. dirreq_map_entry_t *ent;
  730. if (!get_options()->DirReqStatistics)
  731. return;
  732. ent = dirreq_map_get_(type, dirreq_id);
  733. if (!ent)
  734. return;
  735. if (new_state == DIRREQ_IS_FOR_NETWORK_STATUS)
  736. return;
  737. if (new_state - 1 != ent->state)
  738. return;
  739. ent->state = new_state;
  740. if ((type == DIRREQ_DIRECT &&
  741. new_state == DIRREQ_FLUSHING_DIR_CONN_FINISHED) ||
  742. (type == DIRREQ_TUNNELED &&
  743. new_state == DIRREQ_CHANNEL_BUFFER_FLUSHED)) {
  744. tor_gettimeofday(&ent->completion_time);
  745. ent->completed = 1;
  746. }
  747. }
  748. /** Return the bridge-ip-transports string that should be inserted in
  749. * our extra-info descriptor. Return NULL if the bridge-ip-transports
  750. * line should be empty. */
  751. char *
  752. geoip_get_transport_history(void)
  753. {
  754. unsigned granularity = IP_GRANULARITY;
  755. /** String hash table (name of transport) -> (number of users). */
  756. strmap_t *transport_counts = strmap_new();
  757. /** Smartlist that contains copies of the names of the transports
  758. that have been used. */
  759. smartlist_t *transports_used = smartlist_new();
  760. /* Special string to signify that no transport was used for this
  761. connection. Pluggable transport names can't have symbols in their
  762. names, so this string will never collide with a real transport. */
  763. static const char* no_transport_str = "<OR>";
  764. clientmap_entry_t **ent;
  765. smartlist_t *string_chunks = smartlist_new();
  766. char *the_string = NULL;
  767. /* If we haven't seen any clients yet, return NULL. */
  768. if (HT_EMPTY(&client_history))
  769. goto done;
  770. /** We do the following steps to form the transport history string:
  771. * a) Foreach client that uses a pluggable transport, we increase the
  772. * times that transport was used by one. If the client did not use
  773. * a transport, we increase the number of times someone connected
  774. * without obfuscation.
  775. * b) Foreach transport we observed, we write its transport history
  776. * string and push it to string_chunks. So, for example, if we've
  777. * seen 665 obfs2 clients, we write "obfs2=665".
  778. * c) We concatenate string_chunks to form the final string.
  779. */
  780. log_debug(LD_GENERAL,"Starting iteration for transport history. %d clients.",
  781. HT_SIZE(&client_history));
  782. /* Loop through all clients. */
  783. HT_FOREACH(ent, clientmap, &client_history) {
  784. uintptr_t val;
  785. void *ptr;
  786. const char *transport_name = (*ent)->transport_name;
  787. if (!transport_name)
  788. transport_name = no_transport_str;
  789. /* Increase the count for this transport name. */
  790. ptr = strmap_get(transport_counts, transport_name);
  791. val = (uintptr_t)ptr;
  792. val++;
  793. ptr = (void*)val;
  794. strmap_set(transport_counts, transport_name, ptr);
  795. /* If it's the first time we see this transport, note it. */
  796. if (val == 1)
  797. smartlist_add_strdup(transports_used, transport_name);
  798. log_debug(LD_GENERAL, "Client from '%s' with transport '%s'. "
  799. "I've now seen %d clients.",
  800. safe_str_client(fmt_addr(&(*ent)->addr)),
  801. transport_name ? transport_name : "<no transport>",
  802. (int)val);
  803. }
  804. /* Sort the transport names (helps with unit testing). */
  805. smartlist_sort_strings(transports_used);
  806. /* Loop through all seen transports. */
  807. SMARTLIST_FOREACH_BEGIN(transports_used, const char *, transport_name) {
  808. void *transport_count_ptr = strmap_get(transport_counts, transport_name);
  809. uintptr_t transport_count = (uintptr_t) transport_count_ptr;
  810. log_debug(LD_GENERAL, "We got "U64_FORMAT" clients with transport '%s'.",
  811. U64_PRINTF_ARG((uint64_t)transport_count), transport_name);
  812. smartlist_add_asprintf(string_chunks, "%s="U64_FORMAT,
  813. transport_name,
  814. U64_PRINTF_ARG(round_uint64_to_next_multiple_of(
  815. (uint64_t)transport_count,
  816. granularity)));
  817. } SMARTLIST_FOREACH_END(transport_name);
  818. the_string = smartlist_join_strings(string_chunks, ",", 0, NULL);
  819. log_debug(LD_GENERAL, "Final bridge-ip-transports string: '%s'", the_string);
  820. done:
  821. strmap_free(transport_counts, NULL);
  822. SMARTLIST_FOREACH(transports_used, char *, s, tor_free(s));
  823. smartlist_free(transports_used);
  824. SMARTLIST_FOREACH(string_chunks, char *, s, tor_free(s));
  825. smartlist_free(string_chunks);
  826. return the_string;
  827. }
  828. /** Return a newly allocated comma-separated string containing statistics
  829. * on network status downloads. The string contains the number of completed
  830. * requests, timeouts, and still running requests as well as the download
  831. * times by deciles and quartiles. Return NULL if we have not observed
  832. * requests for long enough. */
  833. static char *
  834. geoip_get_dirreq_history(dirreq_type_t type)
  835. {
  836. char *result = NULL;
  837. buf_t *buf = NULL;
  838. smartlist_t *dirreq_completed = NULL;
  839. uint32_t complete = 0, timeouts = 0, running = 0;
  840. dirreq_map_entry_t **ptr, **next;
  841. struct timeval now;
  842. tor_gettimeofday(&now);
  843. dirreq_completed = smartlist_new();
  844. for (ptr = HT_START(dirreqmap, &dirreq_map); ptr; ptr = next) {
  845. dirreq_map_entry_t *ent = *ptr;
  846. if (ent->type != type) {
  847. next = HT_NEXT(dirreqmap, &dirreq_map, ptr);
  848. continue;
  849. } else {
  850. if (ent->completed) {
  851. smartlist_add(dirreq_completed, ent);
  852. complete++;
  853. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr);
  854. } else {
  855. if (tv_mdiff(&ent->request_time, &now) / 1000 > DIRREQ_TIMEOUT)
  856. timeouts++;
  857. else
  858. running++;
  859. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ptr);
  860. tor_free(ent);
  861. }
  862. }
  863. }
  864. #define DIR_REQ_GRANULARITY 4
  865. complete = round_uint32_to_next_multiple_of(complete,
  866. DIR_REQ_GRANULARITY);
  867. timeouts = round_uint32_to_next_multiple_of(timeouts,
  868. DIR_REQ_GRANULARITY);
  869. running = round_uint32_to_next_multiple_of(running,
  870. DIR_REQ_GRANULARITY);
  871. buf = buf_new_with_capacity(1024);
  872. buf_add_printf(buf, "complete=%u,timeout=%u,"
  873. "running=%u", complete, timeouts, running);
  874. #define MIN_DIR_REQ_RESPONSES 16
  875. if (complete >= MIN_DIR_REQ_RESPONSES) {
  876. uint32_t *dltimes;
  877. /* We may have rounded 'completed' up. Here we want to use the
  878. * real value. */
  879. complete = smartlist_len(dirreq_completed);
  880. dltimes = tor_calloc(complete, sizeof(uint32_t));
  881. SMARTLIST_FOREACH_BEGIN(dirreq_completed, dirreq_map_entry_t *, ent) {
  882. uint32_t bytes_per_second;
  883. uint32_t time_diff = (uint32_t) tv_mdiff(&ent->request_time,
  884. &ent->completion_time);
  885. if (time_diff == 0)
  886. time_diff = 1; /* Avoid DIV/0; "instant" answers are impossible
  887. * by law of nature or something, but a millisecond
  888. * is a bit greater than "instantly" */
  889. bytes_per_second = (uint32_t)(1000 * ent->response_size / time_diff);
  890. dltimes[ent_sl_idx] = bytes_per_second;
  891. } SMARTLIST_FOREACH_END(ent);
  892. median_uint32(dltimes, complete); /* sorts as a side effect. */
  893. buf_add_printf(buf,
  894. ",min=%u,d1=%u,d2=%u,q1=%u,d3=%u,d4=%u,md=%u,"
  895. "d6=%u,d7=%u,q3=%u,d8=%u,d9=%u,max=%u",
  896. dltimes[0],
  897. dltimes[1*complete/10-1],
  898. dltimes[2*complete/10-1],
  899. dltimes[1*complete/4-1],
  900. dltimes[3*complete/10-1],
  901. dltimes[4*complete/10-1],
  902. dltimes[5*complete/10-1],
  903. dltimes[6*complete/10-1],
  904. dltimes[7*complete/10-1],
  905. dltimes[3*complete/4-1],
  906. dltimes[8*complete/10-1],
  907. dltimes[9*complete/10-1],
  908. dltimes[complete-1]);
  909. tor_free(dltimes);
  910. }
  911. result = buf_extract(buf, NULL);
  912. SMARTLIST_FOREACH(dirreq_completed, dirreq_map_entry_t *, ent,
  913. tor_free(ent));
  914. smartlist_free(dirreq_completed);
  915. buf_free(buf);
  916. return result;
  917. }
  918. /** Store a newly allocated comma-separated string in
  919. * *<a>country_str</a> containing entries for all the countries from
  920. * which we've seen enough clients connect as a bridge, directory
  921. * server, or entry guard. The entry format is cc=num where num is the
  922. * number of IPs we've seen connecting from that country, and cc is a
  923. * lowercased country code. *<a>country_str</a> is set to NULL if
  924. * we're not ready to export per country data yet.
  925. *
  926. * Store a newly allocated comma-separated string in <a>ipver_str</a>
  927. * containing entries for clients connecting over IPv4 and IPv6. The
  928. * format is family=num where num is the nubmer of IPs we've seen
  929. * connecting over that protocol family, and family is 'v4' or 'v6'.
  930. *
  931. * Return 0 on success and -1 if we're missing geoip data. */
  932. int
  933. geoip_get_client_history(geoip_client_action_t action,
  934. char **country_str, char **ipver_str)
  935. {
  936. unsigned granularity = IP_GRANULARITY;
  937. smartlist_t *entries = NULL;
  938. int n_countries = geoip_get_n_countries();
  939. int i;
  940. clientmap_entry_t **cm_ent;
  941. unsigned *counts = NULL;
  942. unsigned total = 0;
  943. unsigned ipv4_count = 0, ipv6_count = 0;
  944. if (!geoip_is_loaded(AF_INET) && !geoip_is_loaded(AF_INET6))
  945. return -1;
  946. counts = tor_calloc(n_countries, sizeof(unsigned));
  947. HT_FOREACH(cm_ent, clientmap, &client_history) {
  948. int country;
  949. if ((*cm_ent)->action != (int)action)
  950. continue;
  951. country = geoip_get_country_by_addr(&(*cm_ent)->addr);
  952. if (country < 0)
  953. country = 0; /** unresolved requests are stored at index 0. */
  954. tor_assert(0 <= country && country < n_countries);
  955. ++counts[country];
  956. ++total;
  957. switch (tor_addr_family(&(*cm_ent)->addr)) {
  958. case AF_INET:
  959. ipv4_count++;
  960. break;
  961. case AF_INET6:
  962. ipv6_count++;
  963. break;
  964. }
  965. }
  966. if (ipver_str) {
  967. smartlist_t *chunks = smartlist_new();
  968. smartlist_add_asprintf(chunks, "v4=%u",
  969. round_to_next_multiple_of(ipv4_count, granularity));
  970. smartlist_add_asprintf(chunks, "v6=%u",
  971. round_to_next_multiple_of(ipv6_count, granularity));
  972. *ipver_str = smartlist_join_strings(chunks, ",", 0, NULL);
  973. SMARTLIST_FOREACH(chunks, char *, c, tor_free(c));
  974. smartlist_free(chunks);
  975. }
  976. /* Don't record per country data if we haven't seen enough IPs. */
  977. if (total < MIN_IPS_TO_NOTE_ANYTHING) {
  978. tor_free(counts);
  979. if (country_str)
  980. *country_str = NULL;
  981. return 0;
  982. }
  983. /* Make a list of c_hist_t */
  984. entries = smartlist_new();
  985. for (i = 0; i < n_countries; ++i) {
  986. unsigned c = counts[i];
  987. const char *countrycode;
  988. c_hist_t *ent;
  989. /* Only report a country if it has a minimum number of IPs. */
  990. if (c >= MIN_IPS_TO_NOTE_COUNTRY) {
  991. c = round_to_next_multiple_of(c, granularity);
  992. countrycode = geoip_get_country_name(i);
  993. ent = tor_malloc(sizeof(c_hist_t));
  994. strlcpy(ent->country, countrycode, sizeof(ent->country));
  995. ent->total = c;
  996. smartlist_add(entries, ent);
  997. }
  998. }
  999. /* Sort entries. Note that we must do this _AFTER_ rounding, or else
  1000. * the sort order could leak info. */
  1001. smartlist_sort(entries, c_hist_compare_);
  1002. if (country_str) {
  1003. smartlist_t *chunks = smartlist_new();
  1004. SMARTLIST_FOREACH(entries, c_hist_t *, ch, {
  1005. smartlist_add_asprintf(chunks, "%s=%u", ch->country, ch->total);
  1006. });
  1007. *country_str = smartlist_join_strings(chunks, ",", 0, NULL);
  1008. SMARTLIST_FOREACH(chunks, char *, c, tor_free(c));
  1009. smartlist_free(chunks);
  1010. }
  1011. SMARTLIST_FOREACH(entries, c_hist_t *, c, tor_free(c));
  1012. smartlist_free(entries);
  1013. tor_free(counts);
  1014. return 0;
  1015. }
  1016. /** Return a newly allocated string holding the per-country request history
  1017. * for v3 network statuses in a format suitable for an extra-info document,
  1018. * or NULL on failure. */
  1019. char *
  1020. geoip_get_request_history(void)
  1021. {
  1022. smartlist_t *entries, *strings;
  1023. char *result;
  1024. unsigned granularity = IP_GRANULARITY;
  1025. if (!geoip_countries)
  1026. return NULL;
  1027. entries = smartlist_new();
  1028. SMARTLIST_FOREACH_BEGIN(geoip_countries, geoip_country_t *, c) {
  1029. uint32_t tot = 0;
  1030. c_hist_t *ent;
  1031. tot = c->n_v3_ns_requests;
  1032. if (!tot)
  1033. continue;
  1034. ent = tor_malloc_zero(sizeof(c_hist_t));
  1035. strlcpy(ent->country, c->countrycode, sizeof(ent->country));
  1036. ent->total = round_to_next_multiple_of(tot, granularity);
  1037. smartlist_add(entries, ent);
  1038. } SMARTLIST_FOREACH_END(c);
  1039. smartlist_sort(entries, c_hist_compare_);
  1040. strings = smartlist_new();
  1041. SMARTLIST_FOREACH(entries, c_hist_t *, ent, {
  1042. smartlist_add_asprintf(strings, "%s=%u", ent->country, ent->total);
  1043. });
  1044. result = smartlist_join_strings(strings, ",", 0, NULL);
  1045. SMARTLIST_FOREACH(strings, char *, cp, tor_free(cp));
  1046. SMARTLIST_FOREACH(entries, c_hist_t *, ent, tor_free(ent));
  1047. smartlist_free(strings);
  1048. smartlist_free(entries);
  1049. return result;
  1050. }
  1051. /** Start time of directory request stats or 0 if we're not collecting
  1052. * directory request statistics. */
  1053. static time_t start_of_dirreq_stats_interval;
  1054. /** Initialize directory request stats. */
  1055. void
  1056. geoip_dirreq_stats_init(time_t now)
  1057. {
  1058. start_of_dirreq_stats_interval = now;
  1059. }
  1060. /** Reset counters for dirreq stats. */
  1061. void
  1062. geoip_reset_dirreq_stats(time_t now)
  1063. {
  1064. SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, {
  1065. c->n_v3_ns_requests = 0;
  1066. });
  1067. {
  1068. clientmap_entry_t **ent, **next, *this;
  1069. for (ent = HT_START(clientmap, &client_history); ent != NULL;
  1070. ent = next) {
  1071. if ((*ent)->action == GEOIP_CLIENT_NETWORKSTATUS) {
  1072. this = *ent;
  1073. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  1074. clientmap_entry_free(this);
  1075. } else {
  1076. next = HT_NEXT(clientmap, &client_history, ent);
  1077. }
  1078. }
  1079. }
  1080. memset(ns_v3_responses, 0, sizeof(ns_v3_responses));
  1081. {
  1082. dirreq_map_entry_t **ent, **next, *this;
  1083. for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) {
  1084. this = *ent;
  1085. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent);
  1086. tor_free(this);
  1087. }
  1088. }
  1089. start_of_dirreq_stats_interval = now;
  1090. }
  1091. /** Stop collecting directory request stats in a way that we can re-start
  1092. * doing so in geoip_dirreq_stats_init(). */
  1093. void
  1094. geoip_dirreq_stats_term(void)
  1095. {
  1096. geoip_reset_dirreq_stats(0);
  1097. }
  1098. /** Return a newly allocated string containing the dirreq statistics
  1099. * until <b>now</b>, or NULL if we're not collecting dirreq stats. Caller
  1100. * must ensure start_of_dirreq_stats_interval is in the past. */
  1101. char *
  1102. geoip_format_dirreq_stats(time_t now)
  1103. {
  1104. char t[ISO_TIME_LEN+1];
  1105. int i;
  1106. char *v3_ips_string = NULL, *v3_reqs_string = NULL,
  1107. *v3_direct_dl_string = NULL, *v3_tunneled_dl_string = NULL;
  1108. char *result = NULL;
  1109. if (!start_of_dirreq_stats_interval)
  1110. return NULL; /* Not initialized. */
  1111. tor_assert(now >= start_of_dirreq_stats_interval);
  1112. format_iso_time(t, now);
  1113. geoip_get_client_history(GEOIP_CLIENT_NETWORKSTATUS, &v3_ips_string, NULL);
  1114. v3_reqs_string = geoip_get_request_history();
  1115. #define RESPONSE_GRANULARITY 8
  1116. for (i = 0; i < GEOIP_NS_RESPONSE_NUM; i++) {
  1117. ns_v3_responses[i] = round_uint32_to_next_multiple_of(
  1118. ns_v3_responses[i], RESPONSE_GRANULARITY);
  1119. }
  1120. #undef RESPONSE_GRANULARITY
  1121. v3_direct_dl_string = geoip_get_dirreq_history(DIRREQ_DIRECT);
  1122. v3_tunneled_dl_string = geoip_get_dirreq_history(DIRREQ_TUNNELED);
  1123. /* Put everything together into a single string. */
  1124. tor_asprintf(&result, "dirreq-stats-end %s (%d s)\n"
  1125. "dirreq-v3-ips %s\n"
  1126. "dirreq-v3-reqs %s\n"
  1127. "dirreq-v3-resp ok=%u,not-enough-sigs=%u,unavailable=%u,"
  1128. "not-found=%u,not-modified=%u,busy=%u\n"
  1129. "dirreq-v3-direct-dl %s\n"
  1130. "dirreq-v3-tunneled-dl %s\n",
  1131. t,
  1132. (unsigned) (now - start_of_dirreq_stats_interval),
  1133. v3_ips_string ? v3_ips_string : "",
  1134. v3_reqs_string ? v3_reqs_string : "",
  1135. ns_v3_responses[GEOIP_SUCCESS],
  1136. ns_v3_responses[GEOIP_REJECT_NOT_ENOUGH_SIGS],
  1137. ns_v3_responses[GEOIP_REJECT_UNAVAILABLE],
  1138. ns_v3_responses[GEOIP_REJECT_NOT_FOUND],
  1139. ns_v3_responses[GEOIP_REJECT_NOT_MODIFIED],
  1140. ns_v3_responses[GEOIP_REJECT_BUSY],
  1141. v3_direct_dl_string ? v3_direct_dl_string : "",
  1142. v3_tunneled_dl_string ? v3_tunneled_dl_string : "");
  1143. /* Free partial strings. */
  1144. tor_free(v3_ips_string);
  1145. tor_free(v3_reqs_string);
  1146. tor_free(v3_direct_dl_string);
  1147. tor_free(v3_tunneled_dl_string);
  1148. return result;
  1149. }
  1150. /** If 24 hours have passed since the beginning of the current dirreq
  1151. * stats period, write dirreq stats to $DATADIR/stats/dirreq-stats
  1152. * (possibly overwriting an existing file) and reset counters. Return
  1153. * when we would next want to write dirreq stats or 0 if we never want to
  1154. * write. */
  1155. time_t
  1156. geoip_dirreq_stats_write(time_t now)
  1157. {
  1158. char *str = NULL;
  1159. if (!start_of_dirreq_stats_interval)
  1160. return 0; /* Not initialized. */
  1161. if (start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL > now)
  1162. goto done; /* Not ready to write. */
  1163. /* Discard all items in the client history that are too old. */
  1164. geoip_remove_old_clients(start_of_dirreq_stats_interval);
  1165. /* Generate history string .*/
  1166. str = geoip_format_dirreq_stats(now);
  1167. if (! str)
  1168. goto done;
  1169. /* Write dirreq-stats string to disk. */
  1170. if (!check_or_create_data_subdir("stats")) {
  1171. write_to_data_subdir("stats", "dirreq-stats", str, "dirreq statistics");
  1172. /* Reset measurement interval start. */
  1173. geoip_reset_dirreq_stats(now);
  1174. }
  1175. done:
  1176. tor_free(str);
  1177. return start_of_dirreq_stats_interval + WRITE_STATS_INTERVAL;
  1178. }
  1179. /** Start time of bridge stats or 0 if we're not collecting bridge
  1180. * statistics. */
  1181. static time_t start_of_bridge_stats_interval;
  1182. /** Initialize bridge stats. */
  1183. void
  1184. geoip_bridge_stats_init(time_t now)
  1185. {
  1186. start_of_bridge_stats_interval = now;
  1187. }
  1188. /** Stop collecting bridge stats in a way that we can re-start doing so in
  1189. * geoip_bridge_stats_init(). */
  1190. void
  1191. geoip_bridge_stats_term(void)
  1192. {
  1193. client_history_clear();
  1194. start_of_bridge_stats_interval = 0;
  1195. }
  1196. /** Validate a bridge statistics string as it would be written to a
  1197. * current extra-info descriptor. Return 1 if the string is valid and
  1198. * recent enough, or 0 otherwise. */
  1199. static int
  1200. validate_bridge_stats(const char *stats_str, time_t now)
  1201. {
  1202. char stats_end_str[ISO_TIME_LEN+1], stats_start_str[ISO_TIME_LEN+1],
  1203. *eos;
  1204. const char *BRIDGE_STATS_END = "bridge-stats-end ";
  1205. const char *BRIDGE_IPS = "bridge-ips ";
  1206. const char *BRIDGE_IPS_EMPTY_LINE = "bridge-ips\n";
  1207. const char *BRIDGE_TRANSPORTS = "bridge-ip-transports ";
  1208. const char *BRIDGE_TRANSPORTS_EMPTY_LINE = "bridge-ip-transports\n";
  1209. const char *tmp;
  1210. time_t stats_end_time;
  1211. int seconds;
  1212. tor_assert(stats_str);
  1213. /* Parse timestamp and number of seconds from
  1214. "bridge-stats-end YYYY-MM-DD HH:MM:SS (N s)" */
  1215. tmp = find_str_at_start_of_line(stats_str, BRIDGE_STATS_END);
  1216. if (!tmp)
  1217. return 0;
  1218. tmp += strlen(BRIDGE_STATS_END);
  1219. if (strlen(tmp) < ISO_TIME_LEN + 6)
  1220. return 0;
  1221. strlcpy(stats_end_str, tmp, sizeof(stats_end_str));
  1222. if (parse_iso_time(stats_end_str, &stats_end_time) < 0)
  1223. return 0;
  1224. if (stats_end_time < now - (25*60*60) ||
  1225. stats_end_time > now + (1*60*60))
  1226. return 0;
  1227. seconds = (int)strtol(tmp + ISO_TIME_LEN + 2, &eos, 10);
  1228. if (!eos || seconds < 23*60*60)
  1229. return 0;
  1230. format_iso_time(stats_start_str, stats_end_time - seconds);
  1231. /* Parse: "bridge-ips CC=N,CC=N,..." */
  1232. tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS);
  1233. if (!tmp) {
  1234. /* Look if there is an empty "bridge-ips" line */
  1235. tmp = find_str_at_start_of_line(stats_str, BRIDGE_IPS_EMPTY_LINE);
  1236. if (!tmp)
  1237. return 0;
  1238. }
  1239. /* Parse: "bridge-ip-transports PT=N,PT=N,..." */
  1240. tmp = find_str_at_start_of_line(stats_str, BRIDGE_TRANSPORTS);
  1241. if (!tmp) {
  1242. /* Look if there is an empty "bridge-ip-transports" line */
  1243. tmp = find_str_at_start_of_line(stats_str, BRIDGE_TRANSPORTS_EMPTY_LINE);
  1244. if (!tmp)
  1245. return 0;
  1246. }
  1247. return 1;
  1248. }
  1249. /** Most recent bridge statistics formatted to be written to extra-info
  1250. * descriptors. */
  1251. static char *bridge_stats_extrainfo = NULL;
  1252. /** Return a newly allocated string holding our bridge usage stats by country
  1253. * in a format suitable for inclusion in an extrainfo document. Return NULL on
  1254. * failure. */
  1255. char *
  1256. geoip_format_bridge_stats(time_t now)
  1257. {
  1258. char *out = NULL;
  1259. char *country_data = NULL, *ipver_data = NULL, *transport_data = NULL;
  1260. long duration = now - start_of_bridge_stats_interval;
  1261. char written[ISO_TIME_LEN+1];
  1262. if (duration < 0)
  1263. return NULL;
  1264. if (!start_of_bridge_stats_interval)
  1265. return NULL; /* Not initialized. */
  1266. format_iso_time(written, now);
  1267. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data);
  1268. transport_data = geoip_get_transport_history();
  1269. tor_asprintf(&out,
  1270. "bridge-stats-end %s (%ld s)\n"
  1271. "bridge-ips %s\n"
  1272. "bridge-ip-versions %s\n"
  1273. "bridge-ip-transports %s\n",
  1274. written, duration,
  1275. country_data ? country_data : "",
  1276. ipver_data ? ipver_data : "",
  1277. transport_data ? transport_data : "");
  1278. tor_free(country_data);
  1279. tor_free(ipver_data);
  1280. tor_free(transport_data);
  1281. return out;
  1282. }
  1283. /** Return a newly allocated string holding our bridge usage stats by country
  1284. * in a format suitable for the answer to a controller request. Return NULL on
  1285. * failure. */
  1286. static char *
  1287. format_bridge_stats_controller(time_t now)
  1288. {
  1289. char *out = NULL, *country_data = NULL, *ipver_data = NULL;
  1290. char started[ISO_TIME_LEN+1];
  1291. (void) now;
  1292. format_iso_time(started, start_of_bridge_stats_interval);
  1293. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &country_data, &ipver_data);
  1294. tor_asprintf(&out,
  1295. "TimeStarted=\"%s\" CountrySummary=%s IPVersions=%s",
  1296. started,
  1297. country_data ? country_data : "",
  1298. ipver_data ? ipver_data : "");
  1299. tor_free(country_data);
  1300. tor_free(ipver_data);
  1301. return out;
  1302. }
  1303. /** Return a newly allocated string holding our bridge usage stats by
  1304. * country in a format suitable for inclusion in our heartbeat
  1305. * message. Return NULL on failure. */
  1306. char *
  1307. format_client_stats_heartbeat(time_t now)
  1308. {
  1309. const int n_hours = 6;
  1310. char *out = NULL;
  1311. int n_clients = 0;
  1312. clientmap_entry_t **ent;
  1313. unsigned cutoff = (unsigned)( (now-n_hours*3600)/60 );
  1314. if (!start_of_bridge_stats_interval)
  1315. return NULL; /* Not initialized. */
  1316. /* count unique IPs */
  1317. HT_FOREACH(ent, clientmap, &client_history) {
  1318. /* only count directly connecting clients */
  1319. if ((*ent)->action != GEOIP_CLIENT_CONNECT)
  1320. continue;
  1321. if ((*ent)->last_seen_in_minutes < cutoff)
  1322. continue;
  1323. n_clients++;
  1324. }
  1325. tor_asprintf(&out, "Heartbeat: "
  1326. "In the last %d hours, I have seen %d unique clients.",
  1327. n_hours,
  1328. n_clients);
  1329. return out;
  1330. }
  1331. /** Write bridge statistics to $DATADIR/stats/bridge-stats and return
  1332. * when we should next try to write statistics. */
  1333. time_t
  1334. geoip_bridge_stats_write(time_t now)
  1335. {
  1336. char *val = NULL;
  1337. /* Check if 24 hours have passed since starting measurements. */
  1338. if (now < start_of_bridge_stats_interval + WRITE_STATS_INTERVAL)
  1339. return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL;
  1340. /* Discard all items in the client history that are too old. */
  1341. geoip_remove_old_clients(start_of_bridge_stats_interval);
  1342. /* Generate formatted string */
  1343. val = geoip_format_bridge_stats(now);
  1344. if (val == NULL)
  1345. goto done;
  1346. /* Update the stored value. */
  1347. tor_free(bridge_stats_extrainfo);
  1348. bridge_stats_extrainfo = val;
  1349. start_of_bridge_stats_interval = now;
  1350. /* Write it to disk. */
  1351. if (!check_or_create_data_subdir("stats")) {
  1352. write_to_data_subdir("stats", "bridge-stats",
  1353. bridge_stats_extrainfo, "bridge statistics");
  1354. /* Tell the controller, "hey, there are clients!" */
  1355. {
  1356. char *controller_str = format_bridge_stats_controller(now);
  1357. if (controller_str)
  1358. control_event_clients_seen(controller_str);
  1359. tor_free(controller_str);
  1360. }
  1361. }
  1362. done:
  1363. return start_of_bridge_stats_interval + WRITE_STATS_INTERVAL;
  1364. }
  1365. /** Try to load the most recent bridge statistics from disk, unless we
  1366. * have finished a measurement interval lately, and check whether they
  1367. * are still recent enough. */
  1368. static void
  1369. load_bridge_stats(time_t now)
  1370. {
  1371. char *fname, *contents;
  1372. if (bridge_stats_extrainfo)
  1373. return;
  1374. fname = get_datadir_fname2("stats", "bridge-stats");
  1375. contents = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
  1376. if (contents && validate_bridge_stats(contents, now)) {
  1377. bridge_stats_extrainfo = contents;
  1378. } else {
  1379. tor_free(contents);
  1380. }
  1381. tor_free(fname);
  1382. }
  1383. /** Return most recent bridge statistics for inclusion in extra-info
  1384. * descriptors, or NULL if we don't have recent bridge statistics. */
  1385. const char *
  1386. geoip_get_bridge_stats_extrainfo(time_t now)
  1387. {
  1388. load_bridge_stats(now);
  1389. return bridge_stats_extrainfo;
  1390. }
  1391. /** Return a new string containing the recent bridge statistics to be returned
  1392. * to controller clients, or NULL if we don't have any bridge statistics. */
  1393. char *
  1394. geoip_get_bridge_stats_controller(time_t now)
  1395. {
  1396. return format_bridge_stats_controller(now);
  1397. }
  1398. /** Start time of entry stats or 0 if we're not collecting entry
  1399. * statistics. */
  1400. static time_t start_of_entry_stats_interval;
  1401. /** Initialize entry stats. */
  1402. void
  1403. geoip_entry_stats_init(time_t now)
  1404. {
  1405. start_of_entry_stats_interval = now;
  1406. }
  1407. /** Reset counters for entry stats. */
  1408. void
  1409. geoip_reset_entry_stats(time_t now)
  1410. {
  1411. client_history_clear();
  1412. start_of_entry_stats_interval = now;
  1413. }
  1414. /** Stop collecting entry stats in a way that we can re-start doing so in
  1415. * geoip_entry_stats_init(). */
  1416. void
  1417. geoip_entry_stats_term(void)
  1418. {
  1419. geoip_reset_entry_stats(0);
  1420. }
  1421. /** Return a newly allocated string containing the entry statistics
  1422. * until <b>now</b>, or NULL if we're not collecting entry stats. Caller
  1423. * must ensure start_of_entry_stats_interval lies in the past. */
  1424. char *
  1425. geoip_format_entry_stats(time_t now)
  1426. {
  1427. char t[ISO_TIME_LEN+1];
  1428. char *data = NULL;
  1429. char *result;
  1430. if (!start_of_entry_stats_interval)
  1431. return NULL; /* Not initialized. */
  1432. tor_assert(now >= start_of_entry_stats_interval);
  1433. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &data, NULL);
  1434. format_iso_time(t, now);
  1435. tor_asprintf(&result,
  1436. "entry-stats-end %s (%u s)\n"
  1437. "entry-ips %s\n",
  1438. t, (unsigned) (now - start_of_entry_stats_interval),
  1439. data ? data : "");
  1440. tor_free(data);
  1441. return result;
  1442. }
  1443. /** If 24 hours have passed since the beginning of the current entry stats
  1444. * period, write entry stats to $DATADIR/stats/entry-stats (possibly
  1445. * overwriting an existing file) and reset counters. Return when we would
  1446. * next want to write entry stats or 0 if we never want to write. */
  1447. time_t
  1448. geoip_entry_stats_write(time_t now)
  1449. {
  1450. char *str = NULL;
  1451. if (!start_of_entry_stats_interval)
  1452. return 0; /* Not initialized. */
  1453. if (start_of_entry_stats_interval + WRITE_STATS_INTERVAL > now)
  1454. goto done; /* Not ready to write. */
  1455. /* Discard all items in the client history that are too old. */
  1456. geoip_remove_old_clients(start_of_entry_stats_interval);
  1457. /* Generate history string .*/
  1458. str = geoip_format_entry_stats(now);
  1459. /* Write entry-stats string to disk. */
  1460. if (!check_or_create_data_subdir("stats")) {
  1461. write_to_data_subdir("stats", "entry-stats", str, "entry statistics");
  1462. /* Reset measurement interval start. */
  1463. geoip_reset_entry_stats(now);
  1464. }
  1465. done:
  1466. tor_free(str);
  1467. return start_of_entry_stats_interval + WRITE_STATS_INTERVAL;
  1468. }
  1469. /** Helper used to implement GETINFO ip-to-country/... controller command. */
  1470. int
  1471. getinfo_helper_geoip(control_connection_t *control_conn,
  1472. const char *question, char **answer,
  1473. const char **errmsg)
  1474. {
  1475. (void)control_conn;
  1476. if (!strcmpstart(question, "ip-to-country/")) {
  1477. int c;
  1478. sa_family_t family;
  1479. tor_addr_t addr;
  1480. question += strlen("ip-to-country/");
  1481. if (!strcmp(question, "ipv4-available") ||
  1482. !strcmp(question, "ipv6-available")) {
  1483. family = !strcmp(question, "ipv4-available") ? AF_INET : AF_INET6;
  1484. const int available = geoip_is_loaded(family);
  1485. tor_asprintf(answer, "%d", !! available);
  1486. return 0;
  1487. }
  1488. family = tor_addr_parse(&addr, question);
  1489. if (family != AF_INET && family != AF_INET6) {
  1490. *errmsg = "Invalid address family";
  1491. return -1;
  1492. }
  1493. if (!geoip_is_loaded(family)) {
  1494. *errmsg = "GeoIP data not loaded";
  1495. return -1;
  1496. }
  1497. if (family == AF_INET)
  1498. c = geoip_get_country_by_ipv4(tor_addr_to_ipv4h(&addr));
  1499. else /* AF_INET6 */
  1500. c = geoip_get_country_by_ipv6(tor_addr_to_in6(&addr));
  1501. *answer = tor_strdup(geoip_get_country_name(c));
  1502. }
  1503. return 0;
  1504. }
  1505. /** Release all storage held by the GeoIP databases and country list. */
  1506. STATIC void
  1507. clear_geoip_db(void)
  1508. {
  1509. if (geoip_countries) {
  1510. SMARTLIST_FOREACH(geoip_countries, geoip_country_t *, c, tor_free(c));
  1511. smartlist_free(geoip_countries);
  1512. }
  1513. strmap_free(country_idxplus1_by_lc_code, NULL);
  1514. if (geoip_ipv4_entries) {
  1515. SMARTLIST_FOREACH(geoip_ipv4_entries, geoip_ipv4_entry_t *, ent,
  1516. tor_free(ent));
  1517. smartlist_free(geoip_ipv4_entries);
  1518. }
  1519. if (geoip_ipv6_entries) {
  1520. SMARTLIST_FOREACH(geoip_ipv6_entries, geoip_ipv6_entry_t *, ent,
  1521. tor_free(ent));
  1522. smartlist_free(geoip_ipv6_entries);
  1523. }
  1524. geoip_countries = NULL;
  1525. country_idxplus1_by_lc_code = NULL;
  1526. geoip_ipv4_entries = NULL;
  1527. geoip_ipv6_entries = NULL;
  1528. }
  1529. /** Release all storage held in this file. */
  1530. void
  1531. geoip_free_all(void)
  1532. {
  1533. {
  1534. clientmap_entry_t **ent, **next, *this;
  1535. for (ent = HT_START(clientmap, &client_history); ent != NULL; ent = next) {
  1536. this = *ent;
  1537. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  1538. clientmap_entry_free(this);
  1539. }
  1540. HT_CLEAR(clientmap, &client_history);
  1541. }
  1542. {
  1543. dirreq_map_entry_t **ent, **next, *this;
  1544. for (ent = HT_START(dirreqmap, &dirreq_map); ent != NULL; ent = next) {
  1545. this = *ent;
  1546. next = HT_NEXT_RMV(dirreqmap, &dirreq_map, ent);
  1547. tor_free(this);
  1548. }
  1549. HT_CLEAR(dirreqmap, &dirreq_map);
  1550. }
  1551. clear_geoip_db();
  1552. tor_free(bridge_stats_extrainfo);
  1553. }