geoip.c 57 KB

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