lib.rs 33 KB

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