geoip.c 54 KB

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