Skip to main content

rhash_rs/
lib.rs

1#![allow(unused, dead_code)]
2use rhash_sys as ffi;
3
4mod error;
5mod util;
6
7use std::ffi::{CStr, CString, c_char, c_int, c_uchar, c_uint, c_void};
8use std::fmt::{self, Debug, Display, Formatter};
9use std::io::{self, Read};
10use std::path::Path;
11use std::str::FromStr;
12
13pub use error::Error;
14use error::{Result, err, error};
15use pathstr::PathStr;
16
17bitflags::bitflags! {
18    #[repr(transparent)]
19    #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
20    pub struct Hash: i64
21    {
22        const CRC32 = ffi::rhash_ids::RHASH_CRC32 as i64;
23        const CRC32C = ffi::rhash_ids::RHASH_CRC32C as i64;
24        const MD4 = ffi::rhash_ids::RHASH_MD4 as i64;
25        const MD5 = ffi::rhash_ids::RHASH_MD5 as i64;
26        const SHA1 = ffi::rhash_ids::RHASH_SHA1 as i64;
27        const TIGER = ffi::rhash_ids::RHASH_TIGER as i64;
28        const TTH = ffi::rhash_ids::RHASH_TTH as i64;
29        const BTIH = ffi::rhash_ids::RHASH_BTIH as i64;
30        const ED2K = ffi::rhash_ids::RHASH_ED2K as i64;
31        const AICH = ffi::rhash_ids::RHASH_AICH as i64;
32        const WHIRLPOOL = ffi::rhash_ids::RHASH_WHIRLPOOL as i64;
33        const RIPEMD160 = ffi::rhash_ids::RHASH_RIPEMD160 as i64;
34        const GOST94 = ffi::rhash_ids::RHASH_GOST94 as i64;
35        const GOST94_CRYPTOPRO = ffi::rhash_ids::RHASH_GOST94_CRYPTOPRO as i64;
36        const HAS160 = ffi::rhash_ids::RHASH_HAS160 as i64;
37        const GOST12_256 = ffi::rhash_ids::RHASH_GOST12_256 as i64;
38        const GOST12_512 = ffi::rhash_ids::RHASH_GOST12_512 as i64;
39        const EDONR256 = ffi::rhash_ids::RHASH_EDONR256 as i64;
40        const EDONR512 = ffi::rhash_ids::RHASH_EDONR512 as i64;
41        const SNEFRU128 = ffi::rhash_ids::RHASH_SNEFRU128 as i64;
42        const SNEFRU256 = ffi::rhash_ids::RHASH_SNEFRU256 as i64;
43        const BLAKE2S = ffi::rhash_ids::RHASH_BLAKE2S as i64;
44        const BLAKE2B = ffi::rhash_ids::RHASH_BLAKE2B as i64;
45        const BLAKE3 = ffi::rhash_ids::RHASH_BLAKE3 as i64;
46        const SHA224 = ffi::rhash_ids::RHASH_SHA224 as i64;
47        const SHA256 = ffi::rhash_ids::RHASH_SHA256 as i64;
48        const SHA384 = ffi::rhash_ids::RHASH_SHA384 as i64;
49        const SHA512 = ffi::rhash_ids::RHASH_SHA512 as i64;
50        const SHA3_224 = ffi::rhash_ids::RHASH_SHA3_224 as i64;
51        const SHA3_256 = ffi::rhash_ids::RHASH_SHA3_256 as i64;
52        const SHA3_384 = ffi::rhash_ids::RHASH_SHA3_384 as i64;
53        const SHA3_512 = ffi::rhash_ids::RHASH_SHA3_512 as i64;
54        const COUNT = ffi::rhash_ids::RHASH_HASH_COUNT as i64;
55        const ALL = ffi::rhash_ids::RHASH_ALL_HASHES as i64;
56        const _ = !0;
57    }
58
59    #[repr(transparent)]
60    #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Hash)]
61    pub struct PrintFlag: u32
62    {
63        const DEFAULT = ffi::rhash_print_sum_flags::RHPR_DEFAULT as u32;
64        const RAW = ffi::rhash_print_sum_flags::RHPR_RAW as u32;
65        const HEX = ffi::rhash_print_sum_flags::RHPR_HEX as u32;
66        const BASE32 = ffi::rhash_print_sum_flags::RHPR_BASE32 as u32;
67        const BASE64 = ffi::rhash_print_sum_flags::RHPR_BASE64 as u32;
68        const UPPERCASE = ffi::rhash_print_sum_flags::RHPR_UPPERCASE as u32;
69        const REVERSE = ffi::rhash_print_sum_flags::RHPR_REVERSE as u32;
70        const NO_MAGNET = ffi::rhash_print_sum_flags::RHPR_NO_MAGNET as u32;
71        const FILESIZE = ffi::rhash_print_sum_flags::RHPR_FILESIZE as u32;
72        const URLENCODE = ffi::rhash_print_sum_flags::RHPR_URLENCODE as u32;
73        const _ = !0;
74    }
75}
76
77impl Hash
78{
79    pub fn by_name(s: &str) -> Result<Self>
80    {
81        Self::from_str(s)
82    }
83}
84
85impl FromStr for Hash
86{
87    type Err = Error;
88    fn from_str(s: &str) -> Result<Self>
89    {
90        match s.to_ascii_lowercase().replace("_", "-").as_str()
91        {
92            "crc32" => Ok(Self::CRC32),
93            "crc32c" => Ok(Self::CRC32C),
94            "sha1" | "sha-1" => Ok(Self::SHA1),
95            "sha224" | "sha-224" => Ok(Self::SHA224),
96            "sha256" | "sha-256" => Ok(Self::SHA256),
97            "sha384" | "sha-384" => Ok(Self::SHA384),
98            "sha512" | "sha-512" => Ok(Self::SHA512),
99            "sha3-224" | "sha3224" => Ok(Self::SHA3_224),
100            "sha3-256" | "sha3256" => Ok(Self::SHA3_256),
101            "sha3-384" | "sha3384" => Ok(Self::SHA3_384),
102            "sha3-512" | "sha3512" => Ok(Self::SHA3_512),
103            "blake2s" | "b2s" => Ok(Self::BLAKE2S),
104            "blake2b" | "b2b" | "b2" => Ok(Self::BLAKE2B),
105            "blake3" | "b3" => Ok(Self::BLAKE3),
106            "md4" => Ok(Self::MD4),
107            "md5" => Ok(Self::MD5),
108            "tiger" => Ok(Self::TIGER),
109            "ed2k" | "ed2000" => Ok(Self::ED2K),
110            "tth" => Ok(Self::TTH),
111            "btih" => Ok(Self::BTIH),
112            "aich" => Ok(Self::AICH),
113            "whirlpool" => Ok(Self::WHIRLPOOL),
114            "ripemd160" | "ripemd-160" | "rmd160" | "rmd-160" => Ok(Self::RIPEMD160),
115            "has160" | "has-160" => Ok(Self::HAS160),
116            "gost94" | "gost-94" => Ok(Self::GOST94),
117            "gost94-cryptopro" | "gost-94-cryptopro" => Ok(Self::GOST94),
118            "gost12-256" | "gost-12-256" => Ok(Self::GOST12_256),
119            "gost12-512" | "gost-12-512" => Ok(Self::GOST12_512),
120            "edonr256" | "edonr-256" => Ok(Self::EDONR256),
121            "edonr512" | "edonr-512" => Ok(Self::EDONR512),
122            "snefru128" | "snefru-128" => Ok(Self::SNEFRU128),
123            "snefru256" | "snefru-256" => Ok(Self::SNEFRU256),
124            x => error!("'{x}' is not a recognized hash algorithm")
125        }
126    }
127}
128
129impl Display for Hash
130{
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
132    {
133        let bits = self.bits();
134        let bitstring = format!("{bits}");
135        write!(
136            f,
137            "{}",
138            match *self
139            {
140                Self::AICH => "aich",
141                Self::BLAKE2B => "blake2b",
142                Self::BLAKE2S => "blake2s",
143                Self::BLAKE3 => "blake3",
144                Self::BTIH => "btih",
145                Self::CRC32 => "crc32",
146                Self::CRC32C => "crc32c",
147                Self::ED2K => "ed2k",
148                Self::EDONR256 => "edonr256",
149                Self::EDONR512 => "edonr512",
150                Self::GOST12_256 => "gost12-256",
151                Self::GOST12_512 => "gost12-512",
152                Self::GOST94 => "gost94",
153                Self::GOST94_CRYPTOPRO => "gost94-cryptopro",
154                Self::HAS160 => "has160",
155                Self::RIPEMD160 => "ripemd160",
156                Self::MD4 => "md4",
157                Self::MD5 => "md5",
158                Self::SHA1 => "sha1",
159                Self::SHA224 => "sha224",
160                Self::SHA256 => "sha256",
161                Self::SHA384 => "sha384",
162                Self::SHA512 => "sha512",
163                Self::SHA3_224 => "sha3-224",
164                Self::SHA3_256 => "sha3-256",
165                Self::SHA3_384 => "sha3-384",
166                Self::SHA3_512 => "sha3-512",
167                Self::TIGER => "tiger",
168                Self::TTH => "tth",
169                Self::WHIRLPOOL => "whirlpool",
170                Self::SNEFRU128 => "snefru128",
171                Self::SNEFRU256 => "snefru256",
172                other => bitstring.as_str()
173            }
174        )
175    }
176}
177
178pub fn hash_length(hash: Hash) -> c_int
179{
180    unsafe { ffi::rhash_get_hash_length(hash.bits() as c_uint) }
181}
182
183pub fn hash_name(hash: Hash) -> String
184{
185    let s = unsafe { ffi::rhash_get_name(hash.bits() as c_uint) };
186    util::cstr_to_string(s)
187}
188
189pub struct Context
190{
191    handle: ffi::rhash,
192    hash: Hash,
193    print_flags: PrintFlag,
194    _filename_set: bool
195}
196
197impl Drop for Context
198{
199    fn drop(&mut self)
200    {
201        unsafe { ffi::rhash_free(self.handle) }
202    }
203}
204
205impl Context
206{
207    pub fn new(hash: Hash) -> Result<Self>
208    {
209        if hash == Hash::BTIH
210        {
211            error!("The BTIH hash algorithm requires special treatment, such as knowing the file name, and getting its' length ahead of time. Use the `Context::btih(path)` contructor instead")
212        }
213        unsafe { ffi::rhash_library_init() };
214        let handle = unsafe { ffi::rhash_init(hash.bits() as c_uint) };
215
216        if handle.is_null()
217        {
218            error!("rhash_init returned a null pointer")
219        }
220
221        Ok(Self {
222            handle,
223            hash,
224            print_flags: PrintFlag::HEX,
225            _filename_set: false
226        })
227    }
228
229    pub fn btih<P>(file: P) -> Result<Self>
230    where P: AsRef<Path>
231    {
232        let path = PathStr::from(file.as_ref());
233        let hash = Hash::BTIH;
234        unsafe { ffi::rhash_library_init() };
235        let handle = unsafe { ffi::rhash_init(hash.bits() as c_uint) };
236        if handle.is_null()
237        {
238            error!("rhash_init returned a null pointer")
239        }
240        let mut r = Self {
241            handle,
242            hash,
243            print_flags: PrintFlag::HEX,
244            _filename_set: false
245        };
246        r.with_filename(&path)?;
247        r.update_from(&path)?;
248        Ok(r)
249    }
250
251    fn with_filename<P>(&mut self, path: P) -> Result<&mut Self>
252    where P: AsRef<Path>
253    {
254        let path = PathStr::new(path);
255        let cpath = path.cstr()?;
256        unsafe { ffi::rhash_torrent_add_file(self.handle, cpath.as_ptr(), std::fs::metadata(&path)?.len() as std::ffi::c_ulonglong) };
257        self._filename_set = true;
258        Ok(self)
259    }
260
261    pub fn print_flags(&mut self, flags: PrintFlag) -> &mut Self
262    {
263        self.print_flags = flags;
264        self
265    }
266
267    pub fn update_from<P>(&mut self, path: P) -> Result<&mut Self>
268    where P: AsRef<Path>
269    {
270        use std::fs::File;
271        use std::io::prelude;
272        let path = PathStr::new(path);
273        let mut buf = Vec::new();
274        let read = File::open(&path)?.read_to_end(&mut buf)?;
275        let voids = buf.as_ptr().cast::<c_void>();
276        if unsafe { ffi::rhash_update(self.handle, voids, read) } != 0
277        {
278            error!("Failed to update rhash context")
279        }
280        Ok(self)
281    }
282
283    pub fn update(&mut self, input: &[u8]) -> Result<&mut Self>
284    {
285        if unsafe { ffi::rhash_update(self.handle, input.as_ptr().cast::<c_void>(), input.len()) } != 0
286        {
287            error!("Failed to update rhash context")
288        }
289        Ok(self)
290    }
291
292    pub fn digest_size(&self) -> usize
293    {
294        unsafe { ffi::rhash_get_digest_size(self.hash.bits() as c_uint) as usize }
295    }
296
297    pub fn calculate(&mut self) -> Result<String>
298    {
299        if self.hash == Hash::BTIH && !self._filename_set
300        {
301            error!("hash type is BTIH, but file name has not been set!")
302        }
303
304        let mut digest = [0u8; 128];
305        let mut output = [0i8; 128];
306        let rc = unsafe { ffi::rhash_final(self.handle, digest.as_mut_ptr()) };
307        if rc != 0
308        {
309            error!("Failed call to rhash_final")
310        }
311        let size = self.digest_size();
312        let wr = unsafe { ffi::rhash_print_bytes(output.as_mut_ptr(), digest.as_ptr(), size, self.print_flags.bits() as i32) };
313        let mut s = String::from_utf8(output.into_iter().filter(|b| *b != '\0' as c_char).map(|b| b as u8).collect()).map_err(|e| err!("{e}"))?;
314        Ok(s)
315    }
316}