lib.rs 29 KB

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