geoip.c 53 KB

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