geoip.c 57 KB

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