Debian Codegraph @

src/base/read/mod.rs

raw symbols SCIP
1 // Copyright (c) 2022-2023 Harry [Majored] [[email protected]]
2 // MIT License (https://github.com/Majored/rs-async-zip/blob/main/LICENSE)
3
4 //! A module which supports reading ZIP files.
5
6 pub mod mem;
7 pub mod seek;
8 pub mod stream;
9
10 pub(crate) mod io;
11
12 use crate::ZipString;
13 // Re-exported as part of the public API.
14 pub use crate::base::read::io::entry::WithEntry;
15 pub use crate::base::read::io::entry::WithoutEntry;
16 pub use crate::base::read::io::entry::ZipEntryReader;
17
18 use crate::date::ZipDateTime;
19 use crate::entry::{StoredZipEntry, ZipEntry};
20 use crate::error::{Result, ZipError};
21 use crate::file::ZipFile;
22 use crate::spec::attribute::AttributeCompatibility;
23 use crate::spec::consts::LFH_LENGTH;
24 use crate::spec::consts::{CDH_SIGNATURE, LFH_SIGNATURE, NON_ZIP64_MAX_SIZE, SIGNATURE_LENGTH, ZIP64_EOCDL_LENGTH};
25 use crate::spec::header::InfoZipUnicodeCommentExtraField;
26 use crate::spec::header::InfoZipUnicodePathExtraField;
27 use crate::spec::header::{
28 CentralDirectoryRecord, EndOfCentralDirectoryHeader, ExtraField, LocalFileHeader,
29 Zip64EndOfCentralDirectoryLocator, Zip64EndOfCentralDirectoryRecord, Zip64ExtendedInformationExtraField,
30 };
31 use crate::spec::Compression;
32 use crate::string::StringEncoding;
33
34 use crate::base::read::io::CombinedCentralDirectoryRecord;
35 use crate::spec::parse::parse_extra_fields;
36
37 use futures_lite::io::{AsyncRead, AsyncReadExt, AsyncSeek, AsyncSeekExt, SeekFrom};
38
39 pub(crate) async fn file<R>(mut reader: R) -> Result<ZipFile>
40 where
41 R: AsyncRead + AsyncSeek + Unpin,
42 {
43 // First find and parse the EOCDR.
44 let eocdr_offset = crate::base::read::io::locator::eocdr(&mut reader).await?;
45
46 reader.seek(SeekFrom::Start(eocdr_offset)).await?;
47 let eocdr = EndOfCentralDirectoryHeader::from_reader(&mut reader).await?;
48
49 let comment = io::read_string(&mut reader, eocdr.file_comm_length.into(), crate::StringEncoding::Utf8).await?;
50
51 // Check the 20 bytes before the EOCDR for the Zip64 EOCDL, plus an extra 4 bytes because the offset
52 // does not include the signature. If the ECODL exists we are dealing with a Zip64 file.
53 let (eocdr, zip64) = match eocdr_offset.checked_sub(ZIP64_EOCDL_LENGTH + SIGNATURE_LENGTH as u64) {
54 None => (CombinedCentralDirectoryRecord::from(&eocdr), false),
55 Some(offset) => {
56 reader.seek(SeekFrom::Start(offset)).await?;
57 let zip64_locator = Zip64EndOfCentralDirectoryLocator::try_from_reader(&mut reader).await?;
58
59 match zip64_locator {
60 Some(locator) => {
61 reader.seek(SeekFrom::Start(locator.relative_offset + SIGNATURE_LENGTH as u64)).await?;
62 let zip64_eocdr = Zip64EndOfCentralDirectoryRecord::from_reader(&mut reader).await?;
63 (CombinedCentralDirectoryRecord::combine(eocdr, zip64_eocdr), true)
64 }
65 None => (CombinedCentralDirectoryRecord::from(&eocdr), false),
66 }
67 }
68 };
69
70 // Outdated feature so unlikely to ever make it into this crate.
71 if eocdr.disk_number != eocdr.disk_number_start_of_cd
72 || eocdr.num_entries_in_directory != eocdr.num_entries_in_directory_on_disk
73 {
74 return Err(ZipError::FeatureNotSupported("Spanned/split files"));
75 }
76
77 // Find and parse the central directory.
78 reader.seek(SeekFrom::Start(eocdr.offset_of_start_of_directory)).await?;
79 let entries = crate::base::read::cd(reader, eocdr.num_entries_in_directory, zip64).await?;
80
81 Ok(ZipFile { entries, comment, zip64 })
82 }
83
84 pub(crate) async fn cd<R>(mut reader: R, num_of_entries: u64, zip64: bool) -> Result<Vec<StoredZipEntry>>
85 where
86 R: AsyncRead + Unpin,
87 {
88 let num_of_entries = num_of_entries.try_into().map_err(|_| ZipError::TargetZip64NotSupported)?;
89 let mut entries = Vec::with_capacity(num_of_entries);
90
91 for _ in 0..num_of_entries {
92 let entry = cd_record(&mut reader, zip64).await?;
93 entries.push(entry);
94 }
95
96 Ok(entries)
97 }
98
99 pub(crate) fn get_zip64_extra_field(extra_fields: &[ExtraField]) -> Option<&Zip64ExtendedInformationExtraField> {
100 for field in extra_fields {
101 if let ExtraField::Zip64ExtendedInformation(zip64field) = field {
102 return Some(zip64field);
103 }
104 }
105 None
106 }
107
108 pub(crate) fn get_zip64_extra_field_mut(
109 extra_fields: &mut [ExtraField],
110 ) -> Option<&mut Zip64ExtendedInformationExtraField> {
111 for field in extra_fields {
112 if let ExtraField::Zip64ExtendedInformation(zip64field) = field {
113 return Some(zip64field);
114 }
115 }
116 None
117 }
118
119 fn get_combined_sizes(
120 uncompressed_size: u32,
121 compressed_size: u32,
122 extra_field: &Option<&Zip64ExtendedInformationExtraField>,
123 ) -> Result<(u64, u64)> {
124 let mut uncompressed_size = uncompressed_size as u64;
125 let mut compressed_size = compressed_size as u64;
126
127 if let Some(extra_field) = extra_field {
128 if let Some(s) = extra_field.uncompressed_size {
129 uncompressed_size = s;
130 }
131 if let Some(s) = extra_field.compressed_size {
132 compressed_size = s;
133 }
134 }
135
136 Ok((uncompressed_size, compressed_size))
137 }
138
139 pub(crate) async fn cd_record<R>(mut reader: R, _zip64: bool) -> Result<StoredZipEntry>
140 where
141 R: AsyncRead + Unpin,
142 {
143 crate::utils::assert_signature(&mut reader, CDH_SIGNATURE).await?;
144
145 let header = CentralDirectoryRecord::from_reader(&mut reader).await?;
146 let header_size = (SIGNATURE_LENGTH + LFH_LENGTH) as u64;
147 let trailing_size = header.file_name_length as u64 + header.extra_field_length as u64;
148 let filename_basic = io::read_bytes(&mut reader, header.file_name_length.into()).await?;
149 let compression = Compression::try_from(header.compression)?;
150 let extra_field = io::read_bytes(&mut reader, header.extra_field_length.into()).await?;
151 let extra_fields = parse_extra_fields(extra_field, header.uncompressed_size, header.compressed_size)?;
152 let comment_basic = io::read_bytes(reader, header.file_comment_length.into()).await?;
153
154 let zip64_extra_field = get_zip64_extra_field(&extra_fields);
155 let (uncompressed_size, compressed_size) =
156 get_combined_sizes(header.uncompressed_size, header.compressed_size, &zip64_extra_field)?;
157
158 let mut file_offset = header.lh_offset as u64;
159 if let Some(zip64_extra_field) = zip64_extra_field {
160 if file_offset == NON_ZIP64_MAX_SIZE as u64 {
161 if let Some(offset) = zip64_extra_field.relative_header_offset {
162 file_offset = offset;
163 }
164 }
165 }
166
167 let filename = detect_filename(filename_basic, header.flags.filename_unicode, extra_fields.as_ref());
168 let comment = detect_comment(comment_basic, header.flags.filename_unicode, extra_fields.as_ref());
169
170 let entry = ZipEntry {
171 filename,
172 compression,
173 #[cfg(any(
174 feature = "deflate",
175 feature = "bzip2",
176 feature = "zstd",
177 feature = "lzma",
178 feature = "xz",
179 feature = "deflate64"
180 ))]
181 compression_level: async_compression::Level::Default,
182 attribute_compatibility: AttributeCompatibility::Unix,
183 // FIXME: Default to Unix for the moment
184 crc32: header.crc,
185 uncompressed_size,
186 compressed_size,
187 last_modification_date: ZipDateTime { date: header.mod_date, time: header.mod_time },
188 internal_file_attribute: header.inter_attr,
189 external_file_attribute: header.exter_attr,
190 extra_fields,
191 comment,
192 data_descriptor: header.flags.data_descriptor,
193 };
194
195 Ok(StoredZipEntry { entry, file_offset, header_size: header_size + trailing_size })
196 }
197
198 pub(crate) async fn lfh<R>(mut reader: R) -> Result<Option<ZipEntry>>
199 where
200 R: AsyncRead + Unpin,
201 {
202 let signature = {
203 let mut buffer = [0; 4];
204 reader.read_exact(&mut buffer).await?;
205 u32::from_le_bytes(buffer)
206 };
207 match signature {
208 actual if actual == LFH_SIGNATURE => (),
209 actual if actual == CDH_SIGNATURE => return Ok(None),
210 actual => return Err(ZipError::UnexpectedHeaderError(actual, LFH_SIGNATURE)),
211 };
212
213 let header = LocalFileHeader::from_reader(&mut reader).await?;
214 let filename_basic = io::read_bytes(&mut reader, header.file_name_length.into()).await?;
215 let compression = Compression::try_from(header.compression)?;
216 let extra_field = io::read_bytes(&mut reader, header.extra_field_length.into()).await?;
217 let extra_fields = parse_extra_fields(extra_field, header.uncompressed_size, header.compressed_size)?;
218
219 let zip64_extra_field = get_zip64_extra_field(&extra_fields);
220 let (uncompressed_size, compressed_size) =
221 get_combined_sizes(header.uncompressed_size, header.compressed_size, &zip64_extra_field)?;
222
223 if header.flags.data_descriptor && compression == Compression::Stored {
224 return Err(ZipError::FeatureNotSupported(
225 "stream reading entries with data descriptors & Stored compression mode",
226 ));
227 }
228 if header.flags.encrypted {
229 return Err(ZipError::FeatureNotSupported("encryption"));
230 }
231
232 let filename = detect_filename(filename_basic, header.flags.filename_unicode, extra_fields.as_ref());
233
234 let entry = ZipEntry {
235 filename,
236 compression,
237 #[cfg(any(
238 feature = "deflate",
239 feature = "bzip2",
240 feature = "zstd",
241 feature = "lzma",
242 feature = "xz",
243 feature = "deflate64"
244 ))]
245 compression_level: async_compression::Level::Default,
246 attribute_compatibility: AttributeCompatibility::Unix,
247 // FIXME: Default to Unix for the moment
248 crc32: header.crc,
249 uncompressed_size,
250 compressed_size,
251 last_modification_date: ZipDateTime { date: header.mod_date, time: header.mod_time },
252 internal_file_attribute: 0,
253 external_file_attribute: 0,
254 extra_fields,
255 comment: String::new().into(),
256 data_descriptor: header.flags.data_descriptor,
257 };
258
259 Ok(Some(entry))
260 }
261
262 fn detect_comment(basic: Vec<u8>, basic_is_utf8: bool, extra_fields: &[ExtraField]) -> ZipString {
263 if basic_is_utf8 {
264 ZipString::new(basic, StringEncoding::Utf8)
265 } else {
266 let unicode_extra = extra_fields.iter().find_map(|field| match field {
267 ExtraField::InfoZipUnicodeComment(InfoZipUnicodeCommentExtraField::V1 { crc32, unicode }) => {
268 if *crc32 == crc32fast::hash(&basic) {
269 Some(std::string::String::from_utf8(unicode.clone()))
270 } else {
271 None
272 }
273 }
274 _ => None,
275 });
276 if let Some(Ok(s)) = unicode_extra {
277 ZipString::new_with_alternative(s, basic)
278 } else {
279 // Do not treat as UTF-8 if UTF-8 flags are not set,
280 // some string in MBCS may be valid UTF-8 in form, but they are not in truth.
281 if basic.is_ascii() {
282 // SAFETY:
283 // a valid ASCII string is always a valid UTF-8 string
284 unsafe { std::string::String::from_utf8_unchecked(basic).into() }
285 } else {
286 ZipString::new(basic, StringEncoding::Raw)
287 }
288 }
289 }
290 }
291
292 fn detect_filename(basic: Vec<u8>, basic_is_utf8: bool, extra_fields: &[ExtraField]) -> ZipString {
293 if basic_is_utf8 {
294 ZipString::new(basic, StringEncoding::Utf8)
295 } else {
296 let unicode_extra = extra_fields.iter().find_map(|field| match field {
297 ExtraField::InfoZipUnicodePath(InfoZipUnicodePathExtraField::V1 { crc32, unicode }) => {
298 if *crc32 == crc32fast::hash(&basic) {
299 Some(std::string::String::from_utf8(unicode.clone()))
300 } else {
301 None
302 }
303 }
304 _ => None,
305 });
306 if let Some(Ok(s)) = unicode_extra {
307 ZipString::new_with_alternative(s, basic)
308 } else {
309 // Do not treat as UTF-8 if UTF-8 flags are not set,
310 // some string in MBCS may be valid UTF-8 in form, but they are not in truth.
311 if basic.is_ascii() {
312 // SAFETY:
313 // a valid ASCII string is always a valid UTF-8 string
314 unsafe { std::string::String::from_utf8_unchecked(basic).into() }
315 } else {
316 ZipString::new(basic, StringEncoding::Raw)
317 }
318 }
319 }
320 }