Skip to main content

async_zip/base/read/
cd.rs

1use futures_lite::io::{AsyncRead, AsyncReadExt};
2
3use crate::base::read::counting::Counting;
4use crate::base::read::io::CombinedCentralDirectoryRecord;
5use crate::base::read::{detect_filename, get_combined_sizes, get_zip64_extra_field, io};
6use crate::error::{Result, ZipError};
7use crate::spec::consts::{CDH_SIGNATURE, EOCDR_SIGNATURE, NON_ZIP64_MAX_SIZE, ZIP64_EOCDR_SIGNATURE};
8use crate::spec::header::{
9    CentralDirectoryRecord, EndOfCentralDirectoryHeader, Zip64EndOfCentralDirectoryLocator,
10    Zip64EndOfCentralDirectoryRecord,
11};
12use crate::spec::parse::parse_extra_fields;
13use crate::ZipString;
14
15/// An entry returned by the [`CentralDirectoryReader`].
16pub enum Entry {
17    CentralDirectoryEntry(CentralDirectoryEntry),
18    EndOfCentralDirectoryRecord {
19        /// The combined end-of-central-directory record, which may include ZIP64 information.
20        record: CombinedCentralDirectoryRecord,
21        /// The comment associated with the end-of-central-directory record.
22        comment: ZipString,
23        /// Whether the end-of-central-directory record contains extensible data.
24        extensible: bool,
25    },
26}
27
28/// An entry in the ZIP file's central directory.
29pub struct CentralDirectoryEntry {
30    /// The compressed size of the entry, taking into account ZIP64 if necessary.
31    pub(crate) compressed_size: u64,
32    /// The uncompressed size of the entry, taking into account ZIP64 if necessary.
33    pub(crate) uncompressed_size: u64,
34    /// The file offset of the entry in the ZIP file, taking into account ZIP64 if necessary.
35    pub(crate) lh_offset: u64,
36    /// The end-of-central-directory record header.
37    pub(crate) header: CentralDirectoryRecord,
38    /// The filename of the entry.
39    pub(crate) filename: ZipString,
40}
41
42impl CentralDirectoryEntry {
43    /// Returns the entry's filename.
44    ///
45    /// ## Note
46    /// This will return the raw filename stored during ZIP creation. If calling this method on entries retrieved from
47    /// untrusted ZIP files, the filename should be sanitised before being used as a path to prevent [directory
48    /// traversal attacks](https://en.wikipedia.org/wiki/Directory_traversal_attack).
49    pub fn filename(&self) -> &ZipString {
50        &self.filename
51    }
52
53    /// Returns whether or not the entry represents a directory.
54    pub fn dir(&self) -> Result<bool> {
55        Ok(self.filename.as_str()?.ends_with('/'))
56    }
57
58    /// Returns the entry's integer-based UNIX permissions.
59    pub fn unix_permissions(&self) -> Option<u32> {
60        Some((self.header.exter_attr) >> 16)
61    }
62
63    /// Returns the CRC32 checksum of the entry.
64    pub fn crc32(&self) -> u32 {
65        self.header.crc
66    }
67
68    /// Returns the file offset of the entry in the ZIP file.
69    pub fn file_offset(&self) -> u64 {
70        self.lh_offset
71    }
72
73    /// Returns the entry's compressed size.
74    pub fn compressed_size(&self) -> u64 {
75        self.compressed_size
76    }
77
78    /// Returns the entry's uncompressed size.
79    pub fn uncompressed_size(&self) -> u64 {
80        self.uncompressed_size
81    }
82}
83
84#[derive(Clone)]
85pub struct CentralDirectoryReader<R> {
86    reader: R,
87    initial: bool,
88    offset: u64,
89}
90
91impl<R> CentralDirectoryReader<Counting<R>>
92where
93    R: AsyncRead + Unpin,
94{
95    /// Constructs a new ZIP reader from a non-seekable source.
96    pub fn new(reader: R, offset: u64) -> Self {
97        Self { reader: Counting::new(reader), offset, initial: true }
98    }
99
100    /// Reads the next [`CentralDirectoryEntry`] from the underlying source, advancing the
101    /// reader to the next record.
102    ///
103    /// Returns `Ok(EndOfCentralDirectoryRecord)` if the end of the central directory record has
104    /// been reached.
105    pub async fn next(&mut self) -> Result<Entry> {
106        // Skip the first `CDH_SIGNATURE`. The `CentralDirectoryReader` is assumed to pick up from
107        // where the streaming `ZipFileReader` left off, which means that the first record's
108        // signature has already been read.
109        if self.initial {
110            self.initial = false;
111        } else {
112            let signature = {
113                let mut buffer = [0; 4];
114                self.reader.read_exact(&mut buffer).await?;
115                u32::from_le_bytes(buffer)
116            };
117            let offset = self.offset + self.reader.bytes_read();
118            match signature {
119                CDH_SIGNATURE => (),
120                EOCDR_SIGNATURE => {
121                    // Read the end-of-central-directory header.
122                    let eocdr = EndOfCentralDirectoryHeader::from_reader(&mut self.reader).await?;
123
124                    let observed_directory_size = offset.saturating_sub(self.offset);
125                    if eocdr.size_cent_dir as u64 != observed_directory_size {
126                        return Err(ZipError::InvalidCentralDirectorySize {
127                            expected: eocdr.size_cent_dir as u64,
128                            actual: observed_directory_size,
129                        });
130                    }
131
132                    // Read the EOCDR comment.
133                    let comment =
134                        io::read_string(&mut self.reader, eocdr.file_comm_length.into(), crate::StringEncoding::Utf8)
135                            .await?;
136
137                    // Verify that the EOCDR offset matches the current reader offset.
138                    if eocdr.central_directory_offset() != self.offset {
139                        return Err(ZipError::InvalidEndOfCentralDirectoryOffset(
140                            eocdr.central_directory_offset(),
141                            offset,
142                        ));
143                    }
144
145                    return Ok(Entry::EndOfCentralDirectoryRecord {
146                        record: CombinedCentralDirectoryRecord::try_from(&eocdr)?,
147                        comment,
148                        extensible: false,
149                    });
150                }
151                ZIP64_EOCDR_SIGNATURE => {
152                    // Read the ZIP64 EOCDR.
153                    let zip64_eocdr = Zip64EndOfCentralDirectoryRecord::from_reader(&mut self.reader).await?;
154
155                    // Skip the extensible data field.
156                    let extensible = if zip64_eocdr.size_of_zip64_end_of_cd_record > 44 {
157                        let extensible_data_size = zip64_eocdr.size_of_zip64_end_of_cd_record - 44;
158                        io::skip_bytes(&mut self.reader, extensible_data_size).await?;
159                        true
160                    } else {
161                        false
162                    };
163
164                    // Read the ZIP64 EOCDR locator.
165                    let Some(zip64_eocdl) =
166                        Zip64EndOfCentralDirectoryLocator::try_from_reader(&mut self.reader).await?
167                    else {
168                        return Err(ZipError::MissingZip64EndOfCentralDirectoryLocator);
169                    };
170
171                    // Verify that the ZIP64 EOCDR locator points to the correct offset.
172                    if zip64_eocdl.relative_offset != offset {
173                        return Err(ZipError::InvalidZip64EndOfCentralDirectoryLocatorOffset(
174                            zip64_eocdl.relative_offset,
175                            offset,
176                        ));
177                    }
178
179                    // Read the EOCDR signature.
180                    let signature = {
181                        let mut buffer = [0; 4];
182                        self.reader.read_exact(&mut buffer).await?;
183                        u32::from_le_bytes(buffer)
184                    };
185                    if signature != EOCDR_SIGNATURE {
186                        return Err(ZipError::UnexpectedHeaderError(signature, EOCDR_SIGNATURE));
187                    }
188
189                    // Read the end-of-central-directory header.
190                    let eocdr = EndOfCentralDirectoryHeader::from_reader(&mut self.reader).await?;
191
192                    // Read the EOCDR comment.
193                    let comment =
194                        io::read_string(&mut self.reader, eocdr.file_comm_length.into(), crate::StringEncoding::Utf8)
195                            .await?;
196
197                    // Combine the EOCDR and ZIP64 EOCDR.
198                    let zip64_directory_size = zip64_eocdr.directory_size;
199                    let combined = CombinedCentralDirectoryRecord::combine(eocdr, zip64_eocdr)?;
200
201                    let observed_directory_size = offset.saturating_sub(self.offset);
202                    if zip64_directory_size != observed_directory_size {
203                        return Err(ZipError::InvalidCentralDirectorySize {
204                            expected: zip64_directory_size,
205                            actual: observed_directory_size,
206                        });
207                    }
208
209                    // Verify that the EOCDR offset matches the current reader offset.
210                    if combined.central_directory_offset() != self.offset {
211                        return Err(ZipError::InvalidEndOfCentralDirectoryOffset(
212                            combined.central_directory_offset(),
213                            offset,
214                        ));
215                    }
216
217                    return Ok(Entry::EndOfCentralDirectoryRecord { record: combined, comment, extensible });
218                }
219                actual => return Err(ZipError::UnexpectedHeaderError(actual, CDH_SIGNATURE)),
220            }
221        }
222
223        // Read the record.
224        let header = CentralDirectoryRecord::from_reader(&mut self.reader).await?;
225
226        // Read the file name, extra field, and comment, which also ensures that we advance the
227        // reader to the next record.
228        let filename_basic = io::read_bytes(&mut self.reader, header.file_name_length.into()).await?;
229        let extra_field = io::read_bytes(&mut self.reader, header.extra_field_length.into()).await?;
230        let extra_fields = parse_extra_fields(
231            extra_field,
232            header.uncompressed_size,
233            header.compressed_size,
234            Some(header.lh_offset),
235            Some(header.disk_start),
236        )?;
237        let zip64_extra_field = get_zip64_extra_field(&extra_fields);
238
239        // We read the comment but drop it, since we don't need it for anything.
240        io::skip_bytes(&mut self.reader, header.file_comment_length.into()).await?;
241
242        // Reconcile the compressed size, uncompressed size, and file offset, using ZIP64 if necessary.
243        let (uncompressed_size, compressed_size) =
244            get_combined_sizes(header.uncompressed_size, header.compressed_size, &zip64_extra_field)?;
245        let lh_offset = if let Some(lh_offset) = zip64_extra_field
246            .and_then(|zip64| zip64.relative_header_offset)
247            .filter(|_| header.lh_offset == NON_ZIP64_MAX_SIZE)
248        {
249            lh_offset
250        } else {
251            header.lh_offset as u64
252        };
253
254        // Parse out the filename.
255        let filename = detect_filename(filename_basic, header.flags.filename_unicode, extra_fields.as_ref())?;
256
257        Ok(Entry::CentralDirectoryEntry(CentralDirectoryEntry {
258            header,
259            compressed_size,
260            uncompressed_size,
261            lh_offset,
262            filename,
263        }))
264    }
265}