lib.rs 33 KB

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