From f370dac330d1afca6ed133bc5f6c895485a3f11c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joakim=20Frosteg=C3=A5rd?= Date: Fri, 15 Oct 2021 10:09:02 +0200 Subject: [PATCH] access list: use hex crate for info hash parsing --- Cargo.lock | 1 + TODO.md | 1 - aquatic_common/Cargo.toml | 1 + aquatic_common/src/lib.rs | 28 ++++++++++++++-------------- 4 files changed, 16 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6eb446c..f96e662 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -76,6 +76,7 @@ version = "0.1.0" dependencies = [ "anyhow", "hashbrown 0.11.2", + "hex", "indexmap", "rand", "serde", diff --git a/TODO.md b/TODO.md index fae3269..a28072c 100644 --- a/TODO.md +++ b/TODO.md @@ -6,7 +6,6 @@ * rename Allow to Require? * serde-rename AccessListTypes to lowercase * serde-rename list_type to type? - * add tests for info hash parsing * implement for aquatic_http and aquatic_ws * Don't unwrap peer_address diff --git a/aquatic_common/Cargo.toml b/aquatic_common/Cargo.toml index 79c4d86..0072453 100644 --- a/aquatic_common/Cargo.toml +++ b/aquatic_common/Cargo.toml @@ -13,6 +13,7 @@ name = "aquatic_common" [dependencies] anyhow = "1" hashbrown = "0.11.2" +hex = "0.4" indexmap = "1" rand = { version = "0.8", features = ["small_rng"] } serde = { version = "1", features = ["derive"] } diff --git a/aquatic_common/src/lib.rs b/aquatic_common/src/lib.rs index 8d34357..f5805cc 100644 --- a/aquatic_common/src/lib.rs +++ b/aquatic_common/src/lib.rs @@ -36,22 +36,9 @@ pub struct AccessList(HashSet<[u8; 20]>); impl AccessList { fn parse_info_hash(line: String) -> anyhow::Result<[u8; 20]> { - if line.len() != 20 { - return Err(anyhow::anyhow!("Info hash is not 20 bytes long: {}", line)); - } - let mut bytes = [0u8; 20]; - for (byte, c) in bytes.iter_mut().zip(line.chars()) { - if c as u32 > 255 { - return Err(anyhow::anyhow!( - "Info hash character is not ASCII: {:#?}", - c - )); - } - - *byte = c as u8; - } + hex::decode_to_slice(line, &mut bytes)?; Ok(bytes) } @@ -170,3 +157,16 @@ pub fn convert_ipv4_mapped_ipv6(ip_address: IpAddr) -> IpAddr { ip_address } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_access_list_parse_info_hash(){ + assert!(AccessList::parse_info_hash("aaaabbbbccccddddeeeeaaaabbbbccccddddeeee".to_owned()).is_ok()); + assert!(AccessList::parse_info_hash("aaaabbbbccccddddeeeeaaaabbbbccccddddeeeef".to_owned()).is_err()); + assert!(AccessList::parse_info_hash("aaaabbbbccccddddeeeeaaaabbbbccccddddeee".to_owned()).is_err()); + assert!(AccessList::parse_info_hash("aaaabbbbccccddddeeeeaaaabbbbccccddddeeeö".to_owned()).is_err()); + } +} \ No newline at end of file