geoip.c 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738
  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. /** Entry in a map from IP address to the last time we've seen an incoming
  432. * connection from that IP address. Used by bridges only, to track which
  433. * countries have them blocked. */
  434. typedef struct clientmap_entry_t {
  435. HT_ENTRY(clientmap_entry_t) node;
  436. tor_addr_t addr;
  437. /* Name of pluggable transport used by this client. NULL if no
  438. pluggable transport was used. */
  439. char *transport_name;
  440. /** Time when we last saw this IP address, in MINUTES since the epoch.
  441. *
  442. * (This will run out of space around 4011 CE. If Tor is still in use around
  443. * 4000 CE, please remember to add more bits to last_seen_in_minutes.) */
  444. unsigned int last_seen_in_minutes:30;
  445. unsigned int action:2;
  446. } clientmap_entry_t;
  447. /** Largest allowable value for last_seen_in_minutes. (It's a 30-bit field,
  448. * so it can hold up to (1u<<30)-1, or 0x3fffffffu.
  449. */
  450. #define MAX_LAST_SEEN_IN_MINUTES 0X3FFFFFFFu
  451. /** Map from client IP address to last time seen. */
  452. static HT_HEAD(clientmap, clientmap_entry_t) client_history =
  453. HT_INITIALIZER();
  454. /** Hashtable helper: compute a hash of a clientmap_entry_t. */
  455. static inline unsigned
  456. clientmap_entry_hash(const clientmap_entry_t *a)
  457. {
  458. unsigned h = (unsigned) tor_addr_hash(&a->addr);
  459. if (a->transport_name)
  460. h += (unsigned) siphash24g(a->transport_name, strlen(a->transport_name));
  461. return h;
  462. }
  463. /** Hashtable helper: compare two clientmap_entry_t values for equality. */
  464. static inline int
  465. clientmap_entries_eq(const clientmap_entry_t *a, const clientmap_entry_t *b)
  466. {
  467. if (strcmp_opt(a->transport_name, b->transport_name))
  468. return 0;
  469. return !tor_addr_compare(&a->addr, &b->addr, CMP_EXACT) &&
  470. a->action == b->action;
  471. }
  472. HT_PROTOTYPE(clientmap, clientmap_entry_t, node, clientmap_entry_hash,
  473. clientmap_entries_eq)
  474. HT_GENERATE2(clientmap, clientmap_entry_t, node, clientmap_entry_hash,
  475. clientmap_entries_eq, 0.6, tor_reallocarray_, tor_free_)
  476. /** Free all storage held by <b>ent</b>. */
  477. static void
  478. clientmap_entry_free(clientmap_entry_t *ent)
  479. {
  480. if (!ent)
  481. return;
  482. tor_free(ent->transport_name);
  483. tor_free(ent);
  484. }
  485. /** Clear history of connecting clients used by entry and bridge stats. */
  486. static void
  487. client_history_clear(void)
  488. {
  489. clientmap_entry_t **ent, **next, *this;
  490. for (ent = HT_START(clientmap, &client_history); ent != NULL;
  491. ent = next) {
  492. if ((*ent)->action == GEOIP_CLIENT_CONNECT) {
  493. this = *ent;
  494. next = HT_NEXT_RMV(clientmap, &client_history, ent);
  495. clientmap_entry_free(this);
  496. } else {
  497. next = HT_NEXT(clientmap, &client_history, ent);
  498. }
  499. }
  500. }
  501. /** Note that we've seen a client connect from the IP <b>addr</b>
  502. * at time <b>now</b>. Ignored by all but bridges and directories if
  503. * configured accordingly. */
  504. void
  505. geoip_note_client_seen(geoip_client_action_t action,
  506. const tor_addr_t *addr,
  507. const char *transport_name,
  508. time_t now)
  509. {
  510. const or_options_t *options = get_options();
  511. clientmap_entry_t lookup, *ent;
  512. memset(&lookup, 0, sizeof(clientmap_entry_t));
  513. if (action == GEOIP_CLIENT_CONNECT) {
  514. /* Only remember statistics as entry guard or as bridge. */
  515. if (!options->EntryStatistics &&
  516. (!(options->BridgeRelay && options->BridgeRecordUsageByCountry)))
  517. return;
  518. } else {
  519. /* Only gather directory-request statistics if configured, and
  520. * forcibly disable them on bridge authorities. */
  521. if (!options->DirReqStatistics || options->BridgeAuthoritativeDir)
  522. return;
  523. }
  524. log_debug(LD_GENERAL, "Seen client from '%s' with transport '%s'.",
  525. safe_str_client(fmt_addr((addr))),
  526. transport_name ? transport_name : "<no transport>");
  527. tor_addr_copy(&lookup.addr, addr);
  528. lookup.action = (int)action;
  529. lookup.transport_name = (char*) transport_name;
  530. ent = HT_FIND(clientmap, &client_history, &lookup);
  531. if (! ent) {
  532. ent = tor_malloc_zero(sizeof(clientmap_entry_t));
  533. tor_addr_copy(&ent->addr, addr);
  534. if (transport_name)
  535. ent->transport_name = tor_strdup(transport_name);
  536. ent->action = (int)action;
  537. HT_INSERT(clientmap, &client_history, ent);
  538. }
  539. if (now / 60 <= (int)MAX_LAST_SEEN_IN_MINUTES && now >= 0)
  540. ent->last_seen_in_minutes = (unsigned)(now/60);
  541. else
  542. ent->last_seen_in_minutes = 0;
  543. if (action == GEOIP_CLIENT_NETWORKSTATUS) {
  544. int country_idx = geoip_get_country_by_addr(addr);
  545. if (country_idx < 0)
  546. country_idx = 0; /** unresolved requests are stored at index 0. */
  547. if (country_idx >= 0 && country_idx < smartlist_len(geoip_countries)) {
  548. geoip_country_t *country = smartlist_get(geoip_countries, country_idx);
  549. ++country->n_v3_ns_requests;
  550. }
  551. }
  552. }
  553. /** HT_FOREACH helper: remove a clientmap_entry_t from the hashtable if it's
  554. * older than a certain time. */
  555. static int
  556. remove_old_client_helper_(struct clientmap_entry_t *ent, void *_cutoff)
  557. {
  558. time_t cutoff = *(time_t*)_cutoff / 60;
  559. if (ent->last_seen_in_minutes < cutoff) {
  560. clientmap_entry_free(ent);
  561. return 1;
  562. } else {
  563. return 0;
  564. }
  565. }
  566. /** Forget about all clients that haven't connected since <b>cutoff</b>. */
  567. void
  568. geoip_remove_old_clients(time_t cutoff)
  569. {
  570. clientmap_HT_FOREACH_FN(&client_history,
  571. remove_old_client_helper_,
  572. &cutoff);
  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. }