lib.rs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. use http::status::StatusCode;
  2. use http_body_util::{BodyExt, Empty};
  3. use hyper::{body::Bytes, Body, Client, Method, Request};
  4. use hyper_util::rt::TokioExecutor;
  5. use lazy_static::lazy_static;
  6. //use select::{document::Document, predicate::Name};
  7. use serde::{Deserialize, Serialize};
  8. use sled::Db;
  9. use std::{
  10. collections::{btree_map, hash_map, BTreeMap, HashMap, HashSet},
  11. fmt,
  12. };
  13. use x25519_dalek::{PublicKey, StaticSecret};
  14. #[cfg(any(feature = "simulation", test))]
  15. use {
  16. chrono::{DateTime, Utc},
  17. julianday::JulianDay,
  18. std::{path::Path, time::UNIX_EPOCH},
  19. };
  20. pub mod analysis;
  21. pub mod bridge_verification_info;
  22. pub mod crypto;
  23. pub mod extra_info;
  24. pub mod negative_report;
  25. pub mod positive_report;
  26. pub mod request_handler;
  27. #[cfg(feature = "simulation")]
  28. pub mod simulation {
  29. pub mod bridge;
  30. pub mod censor;
  31. pub mod config;
  32. pub mod extra_infos_server;
  33. pub mod user;
  34. }
  35. #[cfg(test)]
  36. pub mod simulation {
  37. pub mod extra_infos_server;
  38. }
  39. use analysis::Analyzer;
  40. use extra_info::*;
  41. use negative_report::*;
  42. use positive_report::*;
  43. lazy_static! {
  44. // known country codes based on Tor geoIP database
  45. // Produced with `cat /usr/share/tor/geoip{,6} | grep -v ^# | grep -o ..$ | sort | uniq | tr '[:upper:]' '[:lower:]' | tr '\n' ',' | sed 's/,/","/g'`
  46. pub static ref COUNTRY_CODES: HashSet<&'static str> = HashSet::from(["??","ac","ad","ae","af","ag","ai","al","am","an","ao","ap","aq","ar","as","at","au","aw","ax","az","ba","bb","bd","be","bf","bg","bh","bi","bj","bl","bm","bn","bo","bq","br","bs","bt","bv","bw","by","bz","ca","cc","cd","cf","cg","ch","ci","ck","cl","cm","cn","co","cr","cs","cu","cv","cw","cx","cy","cz","de","dg","dj","dk","dm","do","dz","ea","ec","ee","eg","eh","er","es","et","eu","fi","fj","fk","fm","fo","fr","ga","gb","gd","ge","gf","gg","gh","gi","gl","gm","gn","gp","gq","gr","gs","gt","gu","gw","gy","hk","hm","hn","hr","ht","hu","ic","id","ie","il","im","in","io","iq","ir","is","it","je","jm","jo","jp","ke","kg","kh","ki","km","kn","kp","kr","kw","ky","kz","la","lb","lc","li","lk","lr","ls","lt","lu","lv","ly","ma","mc","md","me","mf","mg","mh","mk","ml","mm","mn","mo","mp","mq","mr","ms","mt","mu","mv","mw","mx","my","mz","na","nc","ne","nf","ng","ni","nl","no","np","nr","nu","nz","om","pa","pe","pf","pg","ph","pk","pl","pm","pn","pr","ps","pt","pw","py","qa","re","ro","rs","ru","rw","sa","sb","sc","sd","se","sg","sh","si","sj","sk","sl","sm","sn","so","sr","ss","st","sv","sx","sy","sz","ta","tc","td","tf","tg","th","tj","tk","tl","tm","tn","to","tr","tt","tv","tw","tz","ua","ug","uk","um","un","us","uy","uz","va","vc","ve","vg","vi","vn","vu","wf","ws","ye","yt","za","zm","zw"]);
  47. }
  48. /// We will accept reports up to this many days old.
  49. pub const MAX_BACKDATE: u32 = 3;
  50. #[cfg(any(feature = "simulation", test))]
  51. const FAKETIME_FILE: &str = "/tmp/troll-patrol-faketime";
  52. /// Get real or simulated Julian date
  53. pub fn get_date() -> u32 {
  54. // If this is a simulation, get the simulated date
  55. #[cfg(any(feature = "simulation", test))]
  56. return get_simulated_date();
  57. // If we're not running a simulation, return today's date
  58. #[allow(unreachable_code)]
  59. get_real_date()
  60. }
  61. fn get_real_date() -> u32 {
  62. time::OffsetDateTime::now_utc()
  63. .date()
  64. .to_julian_day()
  65. .try_into()
  66. .unwrap()
  67. }
  68. #[cfg(any(feature = "simulation", test))]
  69. fn get_simulated_date() -> u32 {
  70. faketime::enable(Path::new(FAKETIME_FILE));
  71. JulianDay::from(DateTime::<Utc>::from(UNIX_EPOCH + faketime::unix_time()).date_naive())
  72. .inner()
  73. .try_into()
  74. .unwrap()
  75. }
  76. #[cfg(any(feature = "simulation", test))]
  77. pub fn set_simulated_date(date: u32) {
  78. faketime::enable(Path::new(FAKETIME_FILE));
  79. let unix_date_ms = DateTime::<Utc>::from_naive_utc_and_offset(
  80. JulianDay::new(date.try_into().unwrap()).to_date().into(),
  81. Utc,
  82. )
  83. .timestamp_millis();
  84. //str.push_str(format!("\nbridge-stats-end {} 23:59:59 (86400 s)", date).as_str());
  85. faketime::write_millis(Path::new(FAKETIME_FILE), unix_date_ms.try_into().unwrap()).unwrap();
  86. }
  87. #[cfg(any(feature = "simulation", test))]
  88. pub fn increment_simulated_date() {
  89. let date = get_date();
  90. set_simulated_date(date + 1);
  91. }
  92. #[cfg(any(feature = "simulation", test))]
  93. pub fn reset_simulated_date() {
  94. set_simulated_date(get_real_date());
  95. }
  96. #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
  97. pub enum BridgeDistributor {
  98. Lox,
  99. }
  100. /// All the info for a bridge, to be stored in the database
  101. #[derive(Serialize, Deserialize)]
  102. pub struct BridgeInfo {
  103. /// hashed fingerprint (SHA-1 hash of 20-byte bridge ID)
  104. pub fingerprint: [u8; 20],
  105. /// nickname of bridge (probably not necessary)
  106. pub nickname: String,
  107. /// map of countries to data for this bridge in that country
  108. pub info_by_country: HashMap<String, BridgeCountryInfo>,
  109. }
  110. impl BridgeInfo {
  111. pub fn new(fingerprint: [u8; 20], nickname: &String) -> Self {
  112. Self {
  113. fingerprint,
  114. nickname: nickname.to_string(),
  115. info_by_country: HashMap::<String, BridgeCountryInfo>::new(),
  116. }
  117. }
  118. }
  119. impl fmt::Display for BridgeInfo {
  120. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  121. let mut str = format!(
  122. "fingerprint:{}\n",
  123. array_bytes::bytes2hex("", self.fingerprint).as_str()
  124. );
  125. str.push_str(format!("nickname: {}\n", self.nickname).as_str());
  126. //str.push_str(format!("first_seen: {}\n", self.first_seen).as_str());
  127. str.push_str("info_by_country:");
  128. for country in self.info_by_country.keys() {
  129. str.push_str(format!("\n country: {}", country).as_str());
  130. let country_info = self.info_by_country.get(country).unwrap();
  131. for line in country_info.to_string().lines() {
  132. str.push_str(format!("\n {}", line).as_str());
  133. }
  134. }
  135. write!(f, "{}", str)
  136. }
  137. }
  138. #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
  139. pub enum BridgeInfoType {
  140. BridgeIps,
  141. NegativeReports,
  142. PositiveReports,
  143. }
  144. /// Information about bridge reachability from a given country
  145. #[derive(Serialize, Deserialize)]
  146. pub struct BridgeCountryInfo {
  147. pub info_by_day: BTreeMap<u32, BTreeMap<BridgeInfoType, u32>>,
  148. pub blocked: bool,
  149. /// first Julian date we saw data from this country for this bridge
  150. pub first_seen: u32,
  151. /// first Julian date we saw a positive report from this country for this bridge
  152. pub first_pr: Option<u32>,
  153. }
  154. impl BridgeCountryInfo {
  155. pub fn new(first_seen: u32) -> Self {
  156. Self {
  157. info_by_day: BTreeMap::<u32, BTreeMap<BridgeInfoType, u32>>::new(),
  158. blocked: false,
  159. first_seen,
  160. first_pr: None,
  161. }
  162. }
  163. pub fn add_info(&mut self, info_type: BridgeInfoType, date: u32, count: u32) {
  164. if let btree_map::Entry::Vacant(e) = self.info_by_day.entry(date) {
  165. let mut info = BTreeMap::<BridgeInfoType, u32>::new();
  166. info.insert(info_type, count);
  167. e.insert(info);
  168. } else {
  169. let info = self.info_by_day.get_mut(&date).unwrap();
  170. if !info.contains_key(&info_type) {
  171. info.insert(info_type, count);
  172. } else if info_type == BridgeInfoType::BridgeIps {
  173. if *info.get(&info_type).unwrap() < count {
  174. // Use highest value we've seen today
  175. info.insert(info_type, count);
  176. }
  177. } else {
  178. // Add count to previous count for reports
  179. let new_count = info.get(&info_type).unwrap() + count;
  180. info.insert(info_type, new_count);
  181. }
  182. }
  183. // If this is the first instance of positive reports, save the date
  184. if self.first_pr.is_none() && info_type == BridgeInfoType::PositiveReports && count > 0 {
  185. self.first_pr = Some(date);
  186. }
  187. }
  188. }
  189. impl fmt::Display for BridgeCountryInfo {
  190. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  191. let mut str = format!("blocked: {}\n", self.blocked);
  192. str.push_str(format!("first seen: {}\n", self.first_seen).as_str());
  193. let first_pr = if self.first_pr.is_none() {
  194. "never".to_string()
  195. } else {
  196. self.first_pr.unwrap().to_string()
  197. };
  198. str.push_str(format!("first positive report observed: {}\n", first_pr).as_str());
  199. str.push_str("info:");
  200. for date in self.info_by_day.keys() {
  201. let info = self.info_by_day.get(date).unwrap();
  202. let ip_count = match info.get(&BridgeInfoType::BridgeIps) {
  203. Some(&v) => v,
  204. None => 0,
  205. };
  206. let nr_count = match info.get(&BridgeInfoType::NegativeReports) {
  207. Some(&v) => v,
  208. None => 0,
  209. };
  210. let pr_count = match info.get(&BridgeInfoType::PositiveReports) {
  211. Some(&v) => v,
  212. None => 0,
  213. };
  214. if ip_count > 0 || nr_count > 0 || pr_count > 0 {
  215. str.push_str(
  216. format!(
  217. "\n date: {}\n connections: {}\n negative reports: {}\n positive reports: {}",
  218. date,
  219. ip_count,
  220. nr_count,
  221. pr_count,
  222. )
  223. .as_str(),
  224. );
  225. }
  226. }
  227. write!(f, "{}", str)
  228. }
  229. }
  230. /// We store a set of all known bridges so that we can later iterate over them.
  231. /// This function just adds a bridge fingerprint to that set.
  232. pub fn add_bridge_to_db(db: &Db, fingerprint: [u8; 20]) {
  233. let mut bridges = match db.get("bridges").unwrap() {
  234. Some(v) => bincode::deserialize(&v).unwrap(),
  235. None => HashSet::<[u8; 20]>::new(),
  236. };
  237. bridges.insert(fingerprint);
  238. db.insert("bridges", bincode::serialize(&bridges).unwrap())
  239. .unwrap();
  240. }
  241. // Download a webpage and return it as a string
  242. pub async fn download(url: &str) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
  243. if url.starts_with("https://") {
  244. let https = hyper_rustls::HttpsConnectorBuilder::new()
  245. .with_native_roots()
  246. .expect("no native root CA certificates found")
  247. .https_only()
  248. .enable_http1()
  249. .build();
  250. let client: hyper_util::client::legacy::Client<_, Empty<Bytes>> =
  251. hyper_util::client::legacy::Client::builder(TokioExecutor::new()).build(https);
  252. println!("Downloading {}", url);
  253. let mut res = client.get(url.parse()?).await?;
  254. assert_eq!(res.status(), StatusCode::OK);
  255. let mut body_str = String::default();
  256. while let Some(next) = res.frame().await {
  257. let frame = next?;
  258. if let Some(chunk) = frame.data_ref() {
  259. body_str.push_str(&String::from_utf8(chunk.to_vec())?);
  260. }
  261. }
  262. Ok(body_str)
  263. } else {
  264. let client: hyper_util::client::legacy::Client<_, Empty<Bytes>> =
  265. hyper_util::client::legacy::Client::builder(TokioExecutor::new()).build_http();
  266. println!("Downloading {}", url);
  267. let mut res = client.get(url.parse()?).await?;
  268. assert_eq!(res.status(), StatusCode::OK);
  269. let mut body_str = String::default();
  270. while let Some(next) = res.frame().await {
  271. let frame = next?;
  272. if let Some(chunk) = frame.data_ref() {
  273. body_str.push_str(&String::from_utf8(chunk.to_vec())?);
  274. }
  275. }
  276. Ok(body_str)
  277. }
  278. }
  279. // Process extra-infos
  280. /// Adds the extra-info data for a single bridge to the database. If the
  281. /// database already contains an extra-info for this bridge for thid date,
  282. /// but this extra-info contains different data for some reason, use the
  283. /// greater count of connections from each country.
  284. pub fn add_extra_info_to_db(db: &Db, extra_info: ExtraInfo) {
  285. let fingerprint = extra_info.fingerprint;
  286. let mut bridge_info = match db.get(fingerprint).unwrap() {
  287. Some(v) => bincode::deserialize(&v).unwrap(),
  288. None => {
  289. add_bridge_to_db(db, fingerprint);
  290. BridgeInfo::new(fingerprint, &extra_info.nickname)
  291. }
  292. };
  293. for country in extra_info.bridge_ips.keys() {
  294. if bridge_info.info_by_country.contains_key::<String>(country) {
  295. bridge_info
  296. .info_by_country
  297. .get_mut(country)
  298. .unwrap()
  299. .add_info(
  300. BridgeInfoType::BridgeIps,
  301. extra_info.date,
  302. *extra_info.bridge_ips.get(country).unwrap(),
  303. );
  304. } else {
  305. // No existing entry; make a new one.
  306. let mut bridge_country_info = BridgeCountryInfo::new(extra_info.date);
  307. bridge_country_info.add_info(
  308. BridgeInfoType::BridgeIps,
  309. extra_info.date,
  310. *extra_info.bridge_ips.get(country).unwrap(),
  311. );
  312. bridge_info
  313. .info_by_country
  314. .insert(country.to_string(), bridge_country_info);
  315. }
  316. }
  317. // Commit changes to database
  318. db.insert(fingerprint, bincode::serialize(&bridge_info).unwrap())
  319. .unwrap();
  320. }
  321. /// Download new extra-infos files and add their data to the database
  322. pub async fn update_extra_infos(
  323. db: &Db,
  324. base_url: &str,
  325. ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
  326. // Track which files have been processed. This is slightly redundant
  327. // because we're only downloading files we don't already have, but it
  328. // might be a good idea to check in case we downloaded a file but didn't
  329. // process it for some reason.
  330. let mut processed_extra_infos_files = match db.get(b"extra_infos_files").unwrap() {
  331. Some(v) => bincode::deserialize(&v).unwrap(),
  332. None => HashSet::<String>::new(),
  333. };
  334. let dir_page = download(base_url).await?;
  335. // Causes Send issues, so use solution below instead
  336. //let doc = Document::from(dir_page.as_str());
  337. //let links = doc.find(Name("a")).filter_map(|n| n.attr("href"));
  338. // Alternative, less robust solution
  339. let mut links = HashSet::<String>::new();
  340. for line in dir_page.lines() {
  341. let begin_match = "<a href=\"";
  342. let end_match = "\">";
  343. if line.contains(begin_match) {
  344. let link = &line[line.find(begin_match).unwrap() + begin_match.len()..];
  345. if link.contains(end_match) {
  346. let link = &link[0..link.find(end_match).unwrap()];
  347. links.insert(link.to_string());
  348. }
  349. }
  350. }
  351. let mut new_extra_infos = HashSet::<ExtraInfo>::new();
  352. // We should now have an iterable collection of links to consider downloading.
  353. for link in links {
  354. if link.ends_with("-extra-infos") && !processed_extra_infos_files.contains(&link) {
  355. let extra_infos_url = format!("{}{}", base_url, link);
  356. let extra_info_str = download(&extra_infos_url).await?;
  357. //ExtraInfo::parse_file(&extra_info_str, &mut new_extra_infos);
  358. let extra_infos = ExtraInfo::parse_file(&extra_info_str);
  359. new_extra_infos.extend(extra_infos);
  360. processed_extra_infos_files.insert(link);
  361. }
  362. }
  363. // Add new extra-infos data to database
  364. for extra_info in new_extra_infos {
  365. add_extra_info_to_db(db, extra_info);
  366. }
  367. // Store which files we've already downloaded and processed
  368. db.insert(
  369. b"extra_infos_files",
  370. bincode::serialize(&processed_extra_infos_files).unwrap(),
  371. )
  372. .unwrap();
  373. Ok(())
  374. }
  375. // Process negative reports
  376. /// If there is already a negative report ECDH key for this date, return None.
  377. /// Otherwise, generate a new keypair, save the secret part in the db, and
  378. /// return the public part.
  379. pub fn new_negative_report_key(db: &Db, date: u32) -> Option<PublicKey> {
  380. let mut nr_keys = if !db.contains_key("nr-keys").unwrap() {
  381. BTreeMap::<u32, StaticSecret>::new()
  382. } else {
  383. match bincode::deserialize(&db.get("nr-keys").unwrap().unwrap()) {
  384. Ok(v) => v,
  385. Err(_) => BTreeMap::<u32, StaticSecret>::new(),
  386. }
  387. };
  388. if let btree_map::Entry::Vacant(_e) = nr_keys.entry(date) {
  389. let rng = rand::thread_rng();
  390. let secret = StaticSecret::random_from_rng(rng);
  391. let public = PublicKey::from(&secret);
  392. nr_keys.insert(date, secret);
  393. db.insert("nr-keys", bincode::serialize(&nr_keys).unwrap())
  394. .unwrap();
  395. Some(public)
  396. } else {
  397. None
  398. }
  399. }
  400. /// If we have a key for the requested day, return the secret part.
  401. pub fn get_negative_report_secret_key(db: &Db, date: u32) -> Option<StaticSecret> {
  402. if db.contains_key("nr-keys").unwrap() {
  403. let nr_keys: BTreeMap<u32, StaticSecret> =
  404. match bincode::deserialize(&db.get("nr-keys").unwrap().unwrap()) {
  405. Ok(map) => map,
  406. Err(_) => {
  407. return None;
  408. }
  409. };
  410. if nr_keys.contains_key(&date) {
  411. let secret = nr_keys.get(&date).unwrap();
  412. Some(secret.clone())
  413. } else {
  414. None
  415. }
  416. } else {
  417. None
  418. }
  419. }
  420. /// If we have a key for the requested day, return the public part.
  421. pub fn get_negative_report_public_key(db: &Db, date: u32) -> Option<PublicKey> {
  422. get_negative_report_secret_key(db, date).map(|secret| PublicKey::from(&secret))
  423. }
  424. /// Receive an encrypted negative report. Attempt to decrypt it and if
  425. /// successful, add it to the database to be processed later.
  426. pub fn handle_encrypted_negative_report(db: &Db, enc_report: EncryptedNegativeReport) {
  427. if let Some(secret) = get_negative_report_secret_key(db, enc_report.date) {
  428. if let Ok(nr) = enc_report.decrypt(&secret) {
  429. save_negative_report_to_process(db, nr);
  430. }
  431. }
  432. }
  433. /// We store to-be-processed negative reports as a vector. Add this NR
  434. /// to that vector (or create a new vector if necessary)
  435. pub fn save_negative_report_to_process(db: &Db, nr: NegativeReport) {
  436. // TODO: Purge these database entries sometimes
  437. let mut nonces = match db.get(format!("nonces_{}", &nr.date)).unwrap() {
  438. Some(v) => bincode::deserialize(&v).unwrap(),
  439. None => HashSet::<[u8; 32]>::new(),
  440. };
  441. // Just ignore the report if we've seen the nonce before
  442. if nonces.insert(nr.nonce) {
  443. db.insert(
  444. format!("nonces_{}", &nr.date),
  445. bincode::serialize(&nonces).unwrap(),
  446. )
  447. .unwrap();
  448. let mut reports = match db.get("nrs-to-process").unwrap() {
  449. Some(v) => bincode::deserialize(&v).unwrap(),
  450. None => BTreeMap::<String, Vec<SerializableNegativeReport>>::new(),
  451. };
  452. // Store to-be-processed reports with key [fingerprint]_[country]_[date]
  453. let map_key = format!(
  454. "{}_{}_{}",
  455. array_bytes::bytes2hex("", nr.fingerprint),
  456. &nr.country,
  457. &nr.date,
  458. );
  459. if let btree_map::Entry::Vacant(e) = reports.entry(map_key.clone()) {
  460. let nrs = vec![nr.to_serializable_report()];
  461. e.insert(nrs);
  462. } else {
  463. reports
  464. .get_mut(&map_key)
  465. .unwrap()
  466. .push(nr.to_serializable_report());
  467. }
  468. // Commit changes to database
  469. db.insert("nrs-to-process", bincode::serialize(&reports).unwrap())
  470. .unwrap();
  471. }
  472. }
  473. /// Sends a collection of negative reports to the Lox Authority and returns the
  474. /// number of valid reports returned by the server. The negative reports in the
  475. /// collection should all have the same bridge fingerprint, date, country, and
  476. /// distributor.
  477. pub async fn verify_negative_reports(
  478. distributors: &BTreeMap<BridgeDistributor, String>,
  479. reports: &Vec<SerializableNegativeReport>,
  480. ) -> u32 {
  481. // Don't make a network call if we don't have any reports anyway
  482. if reports.is_empty() {
  483. return 0;
  484. }
  485. // Get one report, assume the rest have the same distributor
  486. let first_report = &reports[0];
  487. let distributor = first_report.distributor;
  488. let client = Client::new();
  489. let uri: String = (distributors.get(&distributor).unwrap().to_owned() + "/verifynegative")
  490. .parse()
  491. .unwrap();
  492. let req = Request::builder()
  493. .method(Method::POST)
  494. .uri(uri)
  495. .body(Body::from(serde_json::to_string(&reports).unwrap()))
  496. .unwrap();
  497. let resp = client.request(req).await.unwrap();
  498. let buf = hyper::body::to_bytes(resp).await.unwrap();
  499. serde_json::from_slice(&buf).unwrap()
  500. }
  501. /// Process today's negative reports and store the count of verified reports in
  502. /// the database.
  503. pub async fn update_negative_reports(db: &Db, distributors: &BTreeMap<BridgeDistributor, String>) {
  504. let all_negative_reports = match db.get("nrs-to-process").unwrap() {
  505. Some(v) => bincode::deserialize(&v).unwrap(),
  506. None => BTreeMap::<String, Vec<SerializableNegativeReport>>::new(),
  507. };
  508. let mut bridges_to_re_evaluate = match db.get("bridges-to-re-evaluate").unwrap() {
  509. Some(v) => bincode::deserialize(&v).unwrap(),
  510. None => HashMap::<String, u32>::new(),
  511. // We map fingerprint:date where date is the earliest date for
  512. // which we have new reports
  513. };
  514. let today = get_date();
  515. // Key is [fingerprint]_[country]_[date]
  516. for bridge_country_date in all_negative_reports.keys() {
  517. let reports = all_negative_reports.get(bridge_country_date).unwrap();
  518. if !reports.is_empty() {
  519. let first_report = &reports[0];
  520. let fingerprint = first_report.fingerprint;
  521. let date = first_report.date;
  522. let country = first_report.country.clone();
  523. let count_valid = verify_negative_reports(distributors, reports).await;
  524. // If we have new historical data, re-evaluate this bridge
  525. if count_valid > 0 && date < today {
  526. let fpr_str = array_bytes::bytes2hex("", fingerprint);
  527. if bridges_to_re_evaluate.contains_key(&fpr_str) {
  528. if *bridges_to_re_evaluate.get(&fpr_str).unwrap() > date {
  529. bridges_to_re_evaluate.insert(fpr_str, date);
  530. }
  531. } else {
  532. bridges_to_re_evaluate.insert(fpr_str, date);
  533. }
  534. }
  535. // Get bridge info or make new one
  536. let mut bridge_info = match db.get(fingerprint).unwrap() {
  537. Some(v) => bincode::deserialize(&v).unwrap(),
  538. None => {
  539. // This case shouldn't happen unless the bridge hasn't
  540. // published any bridge stats.
  541. add_bridge_to_db(db, fingerprint);
  542. BridgeInfo::new(fingerprint, &String::default())
  543. }
  544. };
  545. // Add the new report count to it
  546. if let hash_map::Entry::Vacant(_e) = bridge_info.info_by_country.entry(country.clone())
  547. {
  548. // No existing entry; make a new one.
  549. let mut bridge_country_info = BridgeCountryInfo::new(date);
  550. bridge_country_info.add_info(BridgeInfoType::NegativeReports, date, count_valid);
  551. bridge_info
  552. .info_by_country
  553. .insert(country, bridge_country_info);
  554. } else {
  555. let bridge_country_info = bridge_info.info_by_country.get_mut(&country).unwrap();
  556. bridge_country_info.add_info(BridgeInfoType::NegativeReports, date, count_valid);
  557. }
  558. // Commit changes to database
  559. db.insert(fingerprint, bincode::serialize(&bridge_info).unwrap())
  560. .unwrap();
  561. }
  562. }
  563. // Remove the now-processed reports from the database
  564. db.insert(
  565. "nrs-to-process",
  566. bincode::serialize(&BTreeMap::<String, Vec<SerializableNegativeReport>>::new()).unwrap(),
  567. )
  568. .unwrap();
  569. // Commit new set of bridges to re-evaluate
  570. db.insert(
  571. "bridges-to-re-evaluate",
  572. bincode::serialize(&bridges_to_re_evaluate).unwrap(),
  573. )
  574. .unwrap();
  575. }
  576. // Process positive reports
  577. /// We store to-be-processed positive reports as a vector. Add this PR
  578. /// to that vector (or create a new vector if necessary).
  579. pub fn save_positive_report_to_process(db: &Db, pr: PositiveReport) {
  580. let mut reports = match db.get("prs-to-process").unwrap() {
  581. Some(v) => bincode::deserialize(&v).unwrap(),
  582. None => BTreeMap::<String, Vec<SerializablePositiveReport>>::new(),
  583. };
  584. // Store to-be-processed reports with key [fingerprint]_[country]_[date]
  585. let map_key = format!(
  586. "{}_{}_{}",
  587. array_bytes::bytes2hex("", pr.fingerprint),
  588. &pr.country,
  589. &pr.date,
  590. );
  591. if let btree_map::Entry::Vacant(e) = reports.entry(map_key.clone()) {
  592. let prs = vec![pr.to_serializable_report()];
  593. e.insert(prs);
  594. } else {
  595. reports
  596. .get_mut(&map_key)
  597. .unwrap()
  598. .push(pr.to_serializable_report());
  599. }
  600. // Commit changes to database
  601. db.insert("prs-to-process", bincode::serialize(&reports).unwrap())
  602. .unwrap();
  603. }
  604. /// Sends a collection of positive reports to the Lox Authority and returns the
  605. /// number of valid reports returned by the server. The positive reports in the
  606. /// collection should all have the same bridge fingerprint, date, and country.
  607. pub async fn verify_positive_reports(
  608. distributors: &BTreeMap<BridgeDistributor, String>,
  609. reports: &Vec<SerializablePositiveReport>,
  610. ) -> u32 {
  611. // Don't make a network call if we don't have any reports anyway
  612. if reports.is_empty() {
  613. return 0;
  614. }
  615. let client = Client::new();
  616. let uri: String = (distributors
  617. .get(&BridgeDistributor::Lox)
  618. .unwrap()
  619. .to_owned()
  620. + "/verifypositive")
  621. .parse()
  622. .unwrap();
  623. let req = Request::builder()
  624. .method(Method::POST)
  625. .uri(uri)
  626. .body(Body::from(serde_json::to_string(&reports).unwrap()))
  627. .unwrap();
  628. let resp = client.request(req).await.unwrap();
  629. let buf = hyper::body::to_bytes(resp).await.unwrap();
  630. serde_json::from_slice(&buf).unwrap()
  631. }
  632. /// Process today's positive reports and store the count of verified reports in
  633. /// the database.
  634. pub async fn update_positive_reports(db: &Db, distributors: &BTreeMap<BridgeDistributor, String>) {
  635. let all_positive_reports = match db.get("prs-to-process").unwrap() {
  636. Some(v) => bincode::deserialize(&v).unwrap(),
  637. None => BTreeMap::<String, Vec<SerializablePositiveReport>>::new(),
  638. };
  639. let mut bridges_to_re_evaluate = match db.get("bridges-to-re-evaluate").unwrap() {
  640. Some(v) => bincode::deserialize(&v).unwrap(),
  641. None => HashMap::<String, u32>::new(),
  642. // We map fingerprint:date where date is the earliest date for
  643. // which we have new reports
  644. };
  645. let today = get_date();
  646. // Key is [fingerprint]_[country]_[date]
  647. for bridge_country_date in all_positive_reports.keys() {
  648. let reports = all_positive_reports.get(bridge_country_date).unwrap();
  649. if !reports.is_empty() {
  650. let first_report = &reports[0];
  651. let fingerprint = first_report.fingerprint;
  652. let date = first_report.date;
  653. let country = first_report.country.clone();
  654. let count_valid = verify_positive_reports(distributors, reports).await;
  655. // If we have new historical data, re-evaluate this bridge
  656. if count_valid > 0 && date < today {
  657. let fpr_str = array_bytes::bytes2hex("", fingerprint);
  658. if bridges_to_re_evaluate.contains_key(&fpr_str) {
  659. if *bridges_to_re_evaluate.get(&fpr_str).unwrap() > date {
  660. bridges_to_re_evaluate.insert(fpr_str, date);
  661. }
  662. } else {
  663. bridges_to_re_evaluate.insert(fpr_str, date);
  664. }
  665. }
  666. // Get bridge info or make new one
  667. let mut bridge_info = match db.get(fingerprint).unwrap() {
  668. Some(v) => bincode::deserialize(&v).unwrap(),
  669. None => {
  670. // This case shouldn't happen unless the bridge hasn't
  671. // published any bridge stats.
  672. add_bridge_to_db(db, fingerprint);
  673. BridgeInfo::new(fingerprint, &String::default())
  674. }
  675. };
  676. // Add the new report count to it
  677. if let hash_map::Entry::Vacant(e) = bridge_info.info_by_country.entry(country.clone()) {
  678. // No existing entry; make a new one.
  679. let mut bridge_country_info = BridgeCountryInfo::new(date);
  680. bridge_country_info.add_info(BridgeInfoType::PositiveReports, date, count_valid);
  681. e.insert(bridge_country_info);
  682. } else {
  683. let bridge_country_info = bridge_info.info_by_country.get_mut(&country).unwrap();
  684. bridge_country_info.add_info(BridgeInfoType::PositiveReports, date, count_valid);
  685. }
  686. // Commit changes to database
  687. db.insert(fingerprint, bincode::serialize(&bridge_info).unwrap())
  688. .unwrap();
  689. }
  690. }
  691. // Remove the now-processed reports from the database
  692. db.insert(
  693. "prs-to-process",
  694. bincode::serialize(&BTreeMap::<String, Vec<SerializablePositiveReport>>::new()).unwrap(),
  695. )
  696. .unwrap();
  697. // Commit new set of bridges to re-evaluate
  698. db.insert(
  699. "bridges-to-re-evaluate",
  700. bincode::serialize(&bridges_to_re_evaluate).unwrap(),
  701. )
  702. .unwrap();
  703. }
  704. // Verdict on bridge reachability
  705. /// Guess which countries block a bridge. This function returns a map of new
  706. /// blockages (fingerprint : set of countries which block the bridge)
  707. pub fn guess_blockages(
  708. db: &Db,
  709. analyzer: &dyn Analyzer,
  710. confidence: f64,
  711. min_historical_days: u32,
  712. max_historical_days: u32,
  713. ) -> HashMap<[u8; 20], HashSet<String>> {
  714. // Map of bridge fingerprint to set of countries which newly block it
  715. let mut blockages = HashMap::<[u8; 20], HashSet<String>>::new();
  716. // Get list of bridges from database
  717. let bridges = match db.get("bridges").unwrap() {
  718. Some(v) => bincode::deserialize(&v).unwrap(),
  719. None => HashSet::<[u8; 20]>::new(),
  720. };
  721. // Get list of bridges with historical data to re-evaluate
  722. let bridges_to_re_evaluate = match db.get("bridges-to-re-evaluate").unwrap() {
  723. Some(v) => bincode::deserialize(&v).unwrap(),
  724. None => HashMap::<String, u32>::new(),
  725. };
  726. // Guess for each bridge
  727. for fingerprint in bridges {
  728. let today = get_date();
  729. let mut bridge_info: BridgeInfo =
  730. bincode::deserialize(&db.get(fingerprint).unwrap().unwrap()).unwrap();
  731. let mut new_blockages = HashSet::<String>::new();
  732. let fpr_str = array_bytes::bytes2hex("", fingerprint);
  733. let first_date = if bridges_to_re_evaluate.contains_key(&fpr_str) {
  734. *bridges_to_re_evaluate.get(&fpr_str).unwrap()
  735. } else {
  736. today
  737. };
  738. // Re-evaluate the last days from first_date to today.
  739. // (This approach is still suboptimal because we re-evaluate for
  740. // countries that don't have new reports.)
  741. for i in first_date..=today {
  742. let blocked_in = analysis::blocked_in(
  743. analyzer,
  744. &bridge_info,
  745. confidence,
  746. i,
  747. min_historical_days,
  748. max_historical_days,
  749. );
  750. for country in blocked_in {
  751. let bridge_country_info = bridge_info.info_by_country.get_mut(&country).unwrap();
  752. if !bridge_country_info.blocked {
  753. new_blockages.insert(country.to_string());
  754. // Mark bridge as blocked when db gets updated
  755. bridge_country_info.blocked = true;
  756. }
  757. }
  758. }
  759. blockages.insert(fingerprint, new_blockages);
  760. // Commit changes to database
  761. db.insert(fingerprint, bincode::serialize(&bridge_info).unwrap())
  762. .unwrap();
  763. }
  764. // Remove all bridges to re-evaluate from DB
  765. db.insert(
  766. "bridges-to-re-evaluate",
  767. bincode::serialize(&HashMap::<String, u32>::new()).unwrap(),
  768. )
  769. .unwrap();
  770. // Return map of new blockages
  771. blockages
  772. }
  773. /// Report blocked bridges to bridge distributor
  774. pub async fn report_blockages(
  775. distributors: &BTreeMap<BridgeDistributor, String>,
  776. blockages: HashMap<[u8; 20], HashSet<String>>,
  777. ) {
  778. // For now, only report to Lox
  779. // TODO: Support more distributors
  780. let uri: String = (distributors
  781. .get(&BridgeDistributor::Lox)
  782. .unwrap()
  783. .to_owned()
  784. + "/reportblocked")
  785. .parse()
  786. .unwrap();
  787. // Convert map keys from [u8; 20] to 40-character hex strings
  788. let mut blockages_str = HashMap::<String, HashSet<String>>::new();
  789. for (fingerprint, countries) in blockages {
  790. let fpr_string = array_bytes::bytes2hex("", fingerprint);
  791. if !countries.is_empty() {
  792. blockages_str.insert(fpr_string, countries);
  793. }
  794. }
  795. if !blockages_str.is_empty() {
  796. // Report blocked bridges to bridge distributor
  797. let client = Client::new();
  798. let req = Request::builder()
  799. .method(Method::POST)
  800. .uri(uri)
  801. .body(Body::from(serde_json::to_string(&blockages_str).unwrap()))
  802. .unwrap();
  803. let resp = client.request(req).await.unwrap();
  804. let buf = hyper::body::to_bytes(resp).await.unwrap();
  805. let resp_str = String::from_utf8(buf.to_vec()).unwrap();
  806. assert_eq!("OK", resp_str);
  807. }
  808. }
  809. // Unit tests
  810. #[cfg(test)]
  811. mod tests;