lib.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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. /// If we have a key for the requested day, return the secret part.
  355. pub fn get_negative_report_secret_key(db: &Db, date: u32) -> Option<StaticSecret> {
  356. if db.contains_key("nr-keys").unwrap() {
  357. let nr_keys: BTreeMap<u32, StaticSecret> =
  358. match bincode::deserialize(&db.get("nr-keys").unwrap().unwrap()) {
  359. Ok(map) => map,
  360. Err(_) => {
  361. return None;
  362. }
  363. };
  364. if nr_keys.contains_key(&date) {
  365. let secret = nr_keys.get(&date).unwrap();
  366. Some(secret.clone())
  367. } else {
  368. None
  369. }
  370. } else {
  371. None
  372. }
  373. }
  374. /// If we have a key for the requested day, return the public part.
  375. pub fn get_negative_report_public_key(db: &Db, date: u32) -> Option<PublicKey> {
  376. match get_negative_report_secret_key(&db, date) {
  377. Some(secret) => Some(PublicKey::from(&secret)),
  378. None => None,
  379. }
  380. }
  381. /// Receive an encrypted negative report. Attempt to decrypt it and if
  382. /// successful, add it to the database to be processed later.
  383. pub fn handle_encrypted_negative_report(db: &Db, enc_report: EncryptedNegativeReport) {
  384. match get_negative_report_secret_key(&db, enc_report.date) {
  385. Some(secret) => match enc_report.decrypt(&secret) {
  386. Ok(nr) => {
  387. save_negative_report_to_process(&db, nr);
  388. }
  389. Err(_) => {}
  390. },
  391. None => {}
  392. }
  393. }
  394. /// We store to-be-processed negative reports as a vector. Add this NR
  395. /// to that vector (or create a new vector if necessary)
  396. pub fn save_negative_report_to_process(db: &Db, nr: NegativeReport) {
  397. // TODO: Purge these database entries sometimes
  398. let mut nonces = match db.get(format!("nonces_{}", &nr.date)).unwrap() {
  399. Some(v) => bincode::deserialize(&v).unwrap(),
  400. None => HashSet::<[u8; 32]>::new(),
  401. };
  402. // Just ignore the report if we've seen the nonce before
  403. if nonces.insert(nr.nonce) {
  404. db.insert(
  405. format!("nonces_{}", &nr.date),
  406. bincode::serialize(&nonces).unwrap(),
  407. )
  408. .unwrap();
  409. let mut reports = match db.get("nrs-to-process").unwrap() {
  410. Some(v) => bincode::deserialize(&v).unwrap(),
  411. None => BTreeMap::<String, Vec<SerializableNegativeReport>>::new(),
  412. };
  413. // Store to-be-processed reports with key [fingerprint]_[country]_[date]
  414. let map_key = format!(
  415. "{}_{}_{}",
  416. array_bytes::bytes2hex("", &nr.fingerprint),
  417. &nr.country,
  418. &nr.date,
  419. );
  420. if reports.contains_key(&map_key) {
  421. reports
  422. .get_mut(&map_key)
  423. .unwrap()
  424. .push(nr.to_serializable_report());
  425. } else {
  426. let mut nrs = Vec::<SerializableNegativeReport>::new();
  427. nrs.push(nr.to_serializable_report());
  428. reports.insert(map_key, nrs);
  429. }
  430. // Commit changes to database
  431. db.insert("nrs-to-process", bincode::serialize(&reports).unwrap())
  432. .unwrap();
  433. }
  434. }
  435. /// Sends a collection of negative reports to the Lox Authority and returns the
  436. /// number of valid reports returned by the server. The negative reports in the
  437. /// collection should all have the same bridge fingerprint, date, country, and
  438. /// distributor.
  439. pub async fn verify_negative_reports(
  440. distributors: &BTreeMap<BridgeDistributor, String>,
  441. reports: &Vec<SerializableNegativeReport>,
  442. ) -> u32 {
  443. // Don't make a network call if we don't have any reports anyway
  444. if reports.is_empty() {
  445. return 0;
  446. }
  447. // Get one report, assume the rest have the same distributor
  448. let first_report = &reports[0];
  449. let distributor = first_report.distributor;
  450. let client = Client::new();
  451. let uri: String = (distributors.get(&distributor).unwrap().to_owned() + "/verifynegative")
  452. .parse()
  453. .unwrap();
  454. let req = Request::builder()
  455. .method(Method::POST)
  456. .uri(uri)
  457. .body(Body::from(serde_json::to_string(&reports).unwrap()))
  458. .unwrap();
  459. let resp = client.request(req).await.unwrap();
  460. let buf = hyper::body::to_bytes(resp).await.unwrap();
  461. serde_json::from_slice(&buf).unwrap()
  462. }
  463. /// Process today's negative reports and store the count of verified reports in
  464. /// the database.
  465. pub async fn update_negative_reports(db: &Db, distributors: &BTreeMap<BridgeDistributor, String>) {
  466. let all_negative_reports = match db.get("nrs-to-process").unwrap() {
  467. Some(v) => bincode::deserialize(&v).unwrap(),
  468. None => BTreeMap::<String, Vec<SerializableNegativeReport>>::new(),
  469. };
  470. // Key is [fingerprint]_[country]_[date]
  471. for bridge_country_date in all_negative_reports.keys() {
  472. let reports = all_negative_reports.get(bridge_country_date).unwrap();
  473. if !reports.is_empty() {
  474. let first_report = &reports[0];
  475. let fingerprint = first_report.fingerprint;
  476. let date = first_report.date;
  477. let country = first_report.country.clone();
  478. let count_valid = verify_negative_reports(&distributors, reports).await;
  479. // Get bridge info or make new one
  480. let mut bridge_info = match db.get(fingerprint).unwrap() {
  481. Some(v) => bincode::deserialize(&v).unwrap(),
  482. None => {
  483. // This case shouldn't happen unless the bridge hasn't
  484. // published any bridge stats.
  485. add_bridge_to_db(&db, fingerprint);
  486. BridgeInfo::new(fingerprint, &String::default())
  487. }
  488. };
  489. // Add the new report count to it
  490. if bridge_info.info_by_country.contains_key(&country) {
  491. let bridge_country_info = bridge_info.info_by_country.get_mut(&country).unwrap();
  492. bridge_country_info.add_info(BridgeInfoType::NegativeReports, date, count_valid);
  493. } else {
  494. // No existing entry; make a new one.
  495. let mut bridge_country_info = BridgeCountryInfo::new(date);
  496. bridge_country_info.add_info(BridgeInfoType::NegativeReports, date, count_valid);
  497. bridge_info
  498. .info_by_country
  499. .insert(country, bridge_country_info);
  500. }
  501. // Commit changes to database
  502. db.insert(fingerprint, bincode::serialize(&bridge_info).unwrap())
  503. .unwrap();
  504. }
  505. }
  506. // Remove the now-processed reports from the database
  507. db.insert(
  508. "nrs-to-process",
  509. bincode::serialize(&BTreeMap::<String, Vec<SerializableNegativeReport>>::new()).unwrap(),
  510. )
  511. .unwrap();
  512. }
  513. // Process positive reports
  514. /// We store to-be-processed positive reports as a vector. Add this PR
  515. /// to that vector (or create a new vector if necessary).
  516. pub fn save_positive_report_to_process(db: &Db, pr: PositiveReport) {
  517. let mut reports = match db.get("prs-to-process").unwrap() {
  518. Some(v) => bincode::deserialize(&v).unwrap(),
  519. None => BTreeMap::<String, Vec<SerializablePositiveReport>>::new(),
  520. };
  521. // Store to-be-processed reports with key [fingerprint]_[country]_[date]
  522. let map_key = format!(
  523. "{}_{}_{}",
  524. array_bytes::bytes2hex("", &pr.fingerprint),
  525. &pr.country,
  526. &pr.date,
  527. );
  528. if reports.contains_key(&map_key) {
  529. reports
  530. .get_mut(&map_key)
  531. .unwrap()
  532. .push(pr.to_serializable_report());
  533. } else {
  534. let mut prs = Vec::<SerializablePositiveReport>::new();
  535. prs.push(pr.to_serializable_report());
  536. reports.insert(map_key, prs);
  537. }
  538. // Commit changes to database
  539. db.insert("prs-to-process", bincode::serialize(&reports).unwrap())
  540. .unwrap();
  541. }
  542. /// Sends a collection of positive reports to the Lox Authority and returns the
  543. /// number of valid reports returned by the server. The positive reports in the
  544. /// collection should all have the same bridge fingerprint, date, and country.
  545. pub async fn verify_positive_reports(
  546. distributors: &BTreeMap<BridgeDistributor, String>,
  547. reports: &Vec<SerializablePositiveReport>,
  548. ) -> u32 {
  549. // Don't make a network call if we don't have any reports anyway
  550. if reports.is_empty() {
  551. return 0;
  552. }
  553. let client = Client::new();
  554. let uri: String = (distributors
  555. .get(&BridgeDistributor::Lox)
  556. .unwrap()
  557. .to_owned()
  558. + "/verifypositive")
  559. .parse()
  560. .unwrap();
  561. let req = Request::builder()
  562. .method(Method::POST)
  563. .uri(uri)
  564. .body(Body::from(serde_json::to_string(&reports).unwrap()))
  565. .unwrap();
  566. let resp = client.request(req).await.unwrap();
  567. let buf = hyper::body::to_bytes(resp).await.unwrap();
  568. serde_json::from_slice(&buf).unwrap()
  569. }
  570. /// Process today's positive reports and store the count of verified reports in
  571. /// the database.
  572. pub async fn update_positive_reports(db: &Db, distributors: &BTreeMap<BridgeDistributor, String>) {
  573. let all_positive_reports = match db.get("prs-to-process").unwrap() {
  574. Some(v) => bincode::deserialize(&v).unwrap(),
  575. None => BTreeMap::<String, Vec<SerializablePositiveReport>>::new(),
  576. };
  577. // Key is [fingerprint]_[country]_[date]
  578. for bridge_country_date in all_positive_reports.keys() {
  579. let reports = all_positive_reports.get(bridge_country_date).unwrap();
  580. if !reports.is_empty() {
  581. let first_report = &reports[0];
  582. let fingerprint = first_report.fingerprint;
  583. let date = first_report.date;
  584. let country = first_report.country.clone();
  585. let count_valid = verify_positive_reports(&distributors, reports).await;
  586. // Get bridge info or make new one
  587. let mut bridge_info = match db.get(fingerprint).unwrap() {
  588. Some(v) => bincode::deserialize(&v).unwrap(),
  589. None => {
  590. // This case shouldn't happen unless the bridge hasn't
  591. // published any bridge stats.
  592. add_bridge_to_db(&db, fingerprint);
  593. BridgeInfo::new(fingerprint, &String::default())
  594. }
  595. };
  596. // Add the new report count to it
  597. if bridge_info.info_by_country.contains_key(&country) {
  598. let bridge_country_info = bridge_info.info_by_country.get_mut(&country).unwrap();
  599. bridge_country_info.add_info(BridgeInfoType::PositiveReports, date, count_valid);
  600. } else {
  601. // No existing entry; make a new one.
  602. let mut bridge_country_info = BridgeCountryInfo::new(date);
  603. bridge_country_info.add_info(BridgeInfoType::PositiveReports, date, count_valid);
  604. bridge_info
  605. .info_by_country
  606. .insert(country, bridge_country_info);
  607. }
  608. // Commit changes to database
  609. db.insert(fingerprint, bincode::serialize(&bridge_info).unwrap())
  610. .unwrap();
  611. }
  612. }
  613. // Remove the now-processed reports from the database
  614. db.insert(
  615. "prs-to-process",
  616. bincode::serialize(&BTreeMap::<String, Vec<SerializablePositiveReport>>::new()).unwrap(),
  617. )
  618. .unwrap();
  619. }
  620. // Verdict on bridge reachability
  621. /// Guess which countries block a bridge. This function returns a map of new
  622. /// blockages (fingerprint : set of countries which block the bridge)
  623. pub fn guess_blockages(
  624. db: &Db,
  625. analyzer: &dyn Analyzer,
  626. confidence: f64,
  627. ) -> HashMap<[u8; 20], HashSet<String>> {
  628. // Map of bridge fingerprint to set of countries which newly block it
  629. let mut blockages = HashMap::<[u8; 20], HashSet<String>>::new();
  630. // Get list of bridges from database
  631. let bridges = match db.get("bridges").unwrap() {
  632. Some(v) => bincode::deserialize(&v).unwrap(),
  633. None => HashSet::<[u8; 20]>::new(),
  634. };
  635. // Guess for each bridge
  636. for fingerprint in bridges {
  637. let mut bridge_info: BridgeInfo =
  638. bincode::deserialize(&db.get(fingerprint).unwrap().unwrap()).unwrap();
  639. let mut new_blockages = HashSet::<String>::new();
  640. // Re-evaluate the last MAX_BACKDATE + 1 days in case we received new
  641. // reports for those days. For efficiency, we could instead keep track
  642. // of which bridges received new reports and only re-evaluate those.
  643. for i in 0..MAX_BACKDATE + 1 {
  644. let blocked_in = analysis::blocked_in(
  645. analyzer,
  646. &bridge_info,
  647. confidence,
  648. get_date() - MAX_BACKDATE - 1 + i,
  649. );
  650. for country in blocked_in {
  651. let bridge_country_info = bridge_info.info_by_country.get_mut(&country).unwrap();
  652. if !bridge_country_info.blocked {
  653. new_blockages.insert(country.to_string());
  654. // Mark bridge as blocked when db gets updated
  655. bridge_country_info.blocked = true;
  656. }
  657. }
  658. }
  659. blockages.insert(fingerprint, new_blockages);
  660. // Commit changes to database
  661. db.insert(fingerprint, bincode::serialize(&bridge_info).unwrap())
  662. .unwrap();
  663. }
  664. // Return map of new blockages
  665. blockages
  666. }
  667. /// Report blocked bridges to bridge distributor
  668. pub async fn report_blockages(
  669. distributors: &BTreeMap<BridgeDistributor, String>,
  670. blockages: HashMap<[u8; 20], HashSet<String>>,
  671. ) {
  672. // For now, only report to Lox
  673. // TODO: Support more distributors
  674. let uri: String = (distributors
  675. .get(&BridgeDistributor::Lox)
  676. .unwrap()
  677. .to_owned()
  678. + "/reportblocked")
  679. .parse()
  680. .unwrap();
  681. // Convert map keys from [u8; 20] to 40-character hex strings
  682. let mut blockages_str = HashMap::<String, HashSet<String>>::new();
  683. for (fingerprint, countries) in blockages {
  684. let fpr_string = array_bytes::bytes2hex("", fingerprint);
  685. blockages_str.insert(fpr_string, countries);
  686. }
  687. // Report blocked bridges to bridge distributor
  688. let client = Client::new();
  689. let req = Request::builder()
  690. .method(Method::POST)
  691. .uri(uri)
  692. .body(Body::from(serde_json::to_string(&blockages_str).unwrap()))
  693. .unwrap();
  694. let resp = client.request(req).await.unwrap();
  695. let buf = hyper::body::to_bytes(resp).await.unwrap();
  696. let resp_str: String = serde_json::from_slice(&buf).unwrap();
  697. assert_eq!("OK", resp_str);
  698. }
  699. // Unit tests
  700. #[cfg(test)]
  701. mod tests;