geoip.c 57 KB

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