geoip.c 62 KB

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