Skip to main content

zip/extra_fields/
zipinfo_utf8.rs

1use crate::result::{ZipResult, invalid};
2use crate::unstable::LittleEndianReadExt;
3use core::mem::size_of;
4use std::io::Read;
5
6/// Info-ZIP Unicode Path Extra Field (0x7075) or Unicode Comment Extra Field (0x6375), as
7/// specified in APPNOTE 4.6.8 and 4.6.9
8#[derive(Clone, Debug)]
9pub struct UnicodeExtraField {
10    crc32: u32,
11    content: Box<[u8]>,
12}
13
14impl UnicodeExtraField {
15    /// Verifies the checksum and returns the content.
16    ///
17    /// # Errors
18    ///
19    /// Returns an error when the crc32 from the extra field does not match the crc32 of the
20    /// `ascii_field`.
21    pub fn unwrap_valid(self, ascii_field: &[u8]) -> ZipResult<Box<[u8]>> {
22        let computed_crc32 = crc32fast::hash(ascii_field);
23        if self.crc32 != computed_crc32 {
24            return Err(invalid!(
25                "CRC32 checksum failed on Unicode extra field, it is '{:#08X}' and it should be '{:#08X}'",
26                self.crc32,
27                computed_crc32
28            ));
29        }
30        Ok(self.content)
31    }
32}
33
34impl UnicodeExtraField {
35    pub(crate) fn try_from_reader<R: Read>(reader: &mut R, len: u16) -> ZipResult<Self> {
36        // Read and discard version byte
37        reader.read_exact(&mut [0u8])?;
38
39        let crc32 = reader.read_u32_le()?;
40        let content_len = (len as usize)
41            .checked_sub(size_of::<u8>() + size_of::<u32>())
42            .ok_or(invalid!("Unicode extra field is too small"))?;
43        let mut content = vec![0u8; content_len].into_boxed_slice();
44        reader.read_exact(&mut content)?;
45        Ok(Self { crc32, content })
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use crate::extra_fields::UnicodeExtraField;
52    #[test]
53    fn unicode_extra_field_crc32_correct() {
54        let data = [
55            0x01, 0xef, 0x39, 0x8e, 0x4b, 'u' as u8, 't' as u8, 'f' as u8, '-' as u8, '8' as u8,
56        ];
57        let extra =
58            UnicodeExtraField::try_from_reader(&mut std::io::Cursor::new(data), 10).unwrap();
59        let res = extra.unwrap_valid(b"abcdef");
60        assert!(res.is_ok());
61        let content = res.unwrap();
62        assert_eq!(content.as_ref(), b"utf-8");
63    }
64
65    #[test]
66    fn unicode_extra_field_crc32_incorrect() {
67        let data = [
68            0x01, 0x00, 0x00, 0x00, 0x00, 'u' as u8, 't' as u8, 'f' as u8, '-' as u8, '8' as u8,
69        ];
70        let extra =
71            UnicodeExtraField::try_from_reader(&mut std::io::Cursor::new(data), 10).unwrap();
72        let res = extra.unwrap_valid(b"abcdef");
73        assert!(res.is_err());
74    }
75}