lib.rs 31 KB

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