lib.rs 28 KB

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