lib.rs 29 KB

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