lib.rs 29 KB

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