1use std::ops::Range;
2
3use tokio::io::{AsyncRead, AsyncSeek};
4
5use crate::{
6 Budget, CompressionMethod, EntryKind, Error, HostSystem, IndexPolicy, IndexPolicyViolation,
7 add,
8 constants::{signature, size},
9 extra::CentralExtras,
10 invalid,
11 kind::{ExternalAttributes, UnixFileType},
12 policy_violation,
13 record::{
14 Common, GeneralPurposeFlags, MemberHeader, MemberPayload, PayloadFields, RecordReader,
15 SizeField, array_at, bytes_at, parse_name,
16 },
17};
18
19#[derive(Clone, Copy, Debug)]
22pub struct Entry<'a> {
23 pub(super) indexed: &'a IndexedEntry,
25 pub(super) resolved: &'a ResolvedMember,
27}
28
29impl Entry<'_> {
30 pub fn directory(&self) -> &CentralDirectoryEntry {
32 &self.indexed.directory
33 }
34
35 pub fn record_range(&self) -> Range<u64> {
37 self.indexed.record_range()
38 }
39
40 pub fn kind(&self) -> &EntryKind {
44 &self.resolved.kind
45 }
46
47 pub fn unix_mode(&self) -> u16 {
51 self.resolved.unix_mode
52 }
53
54 pub fn data_offset(&self) -> u64 {
56 self.resolved.data_offset
57 }
58
59 pub fn has_unix_extra(&self) -> bool {
64 self.resolved.has_unix_extra
65 }
66}
67
68#[derive(Debug)]
69pub(super) struct ResolvedMember {
70 data_offset: u64,
71 has_unix_extra: bool,
72 kind: EntryKind,
73 unix_mode: u16,
74}
75
76#[derive(Debug)]
78pub struct CentralDirectoryEntry {
79 path: Box<str>,
81 version_needed: u16,
83 common: Common,
85 payload: MemberPayload,
87 local_offset: u64,
97 made_by: u16,
99 attributes: u32,
104 extra: CentralExtras,
106}
107
108pub(super) enum BufferedEntry {
109 Complete(CentralDirectoryEntry, usize),
110 Incomplete(usize),
112}
113
114impl CentralDirectoryEntry {
115 const RECORD_ORIENTED: u16 = 0x0002;
117
118 pub fn path(&self) -> &str {
120 &self.path
121 }
122
123 pub fn method(&self) -> CompressionMethod {
125 self.common.method
126 }
127
128 pub fn crc32(&self) -> u32 {
130 self.payload.fields().crc
131 }
132
133 pub fn size(&self) -> u64 {
135 self.payload.fields().uncompressed
136 }
137
138 pub fn compressed_size(&self) -> u64 {
140 self.payload.fields().compressed
141 }
142
143 pub fn position(&self) -> u64 {
145 self.local_offset
146 }
147
148 pub fn host_system(&self) -> HostSystem {
152 HostSystem::from((self.made_by >> 8) as u8)
153 }
154
155 pub fn external_attributes(&self) -> u32 {
157 self.attributes
158 }
159
160 pub fn version_needed(&self) -> u16 {
162 self.version_needed
163 }
164
165 #[inline]
168 pub(super) fn parse(
169 bytes: &[u8],
170 position: u64,
171 budget: &mut Budget,
172 policy: &IndexPolicy,
173 ) -> Result<BufferedEntry, Error> {
174 let Some((header, rest)) = bytes.split_first_chunk::<{ size::CENTRAL }>() else {
175 return Ok(BufferedEntry::Incomplete(size::CENTRAL));
176 };
177 if u32::from_le_bytes(array_at::<0, 4, _>(header)) != signature::CENTRAL {
178 return Err(invalid(position, "invalid central header signature"));
179 }
180 let name_length = usize::from(u16::from_le_bytes(array_at::<28, 2, _>(header)));
181 if name_length == 0 {
182 return Err(invalid(position, "empty filename"));
183 }
184 let extra_length = usize::from(u16::from_le_bytes(array_at::<30, 2, _>(header)));
185 let comment_length = usize::from(u16::from_le_bytes(array_at::<32, 2, _>(header)));
186 let length = name_length + extra_length + comment_length;
187 let Some(variable) = rest.get(..length) else {
188 return Ok(BufferedEntry::Incomplete(size::CENTRAL + length));
189 };
190
191 let header_fields =
192 MemberHeader::parse(&array_at::<6, { MemberHeader::SIZE }, _>(header), position)?;
193 let common = header_fields.common;
194 let internal_attributes = u16::from_le_bytes(array_at::<36, 2, _>(header));
195 if internal_attributes & Self::RECORD_ORIENTED != 0 {
196 return Err(Error::Unsupported {
197 position,
198 feature: "record-oriented member",
199 });
200 }
201 let offset = u32::from_le_bytes(array_at::<42, 4, _>(header));
202 let disk = u16::from_le_bytes(array_at::<34, 2, _>(header));
203 let (name, rest) = variable.split_at(name_length);
204 let (raw_extra, comment) = rest.split_at(extra_length);
205 let path = parse_name(name, common.flags, position, policy.allow_backslashes)?;
206 let (extra, payload, local_offset) = CentralExtras::parse(
207 raw_extra,
208 header_fields,
209 (offset, disk),
210 path,
211 comment,
212 policy.extra_fields,
213 position,
214 )?;
215 policy.check_version(
216 header_fields.version,
217 header_fields.minimum_version(extra.has_zip64),
218 position,
219 )?;
220 if common.method == CompressionMethod::Stored
221 && common.flags.contains(GeneralPurposeFlags::DATA_DESCRIPTOR)
222 && !policy.allow_stored_data_descriptors
223 {
224 return Err(policy_violation(
225 position,
226 IndexPolicyViolation::StoredDataDescriptor,
227 ));
228 }
229 if !policy.allow_empty_deflate_streams && payload.has_empty_deflate_stream() {
230 return Err(policy_violation(
231 position,
232 IndexPolicyViolation::EmptyDeflateStream,
233 ));
234 }
235 policy
236 .comments
237 .per_member
238 .check(comment, Some(common.flags), position)?;
239 budget.charge_member(payload.fields().uncompressed)?;
240 let entry = Self {
241 path: path.into(),
242 version_needed: header_fields.version,
243 common,
244 payload,
245 local_offset,
246 made_by: u16::from_le_bytes(array_at::<4, 2, _>(header)),
247 attributes: u32::from_le_bytes(array_at::<38, 4, _>(header)),
248 extra,
249 };
250
251 let mode = (entry.attributes >> ExternalAttributes::UNIX_MODE_SHIFT) as u16;
252 if UnixFileType::from_mode(mode) == UnixFileType::SymbolicLink
253 && entry.host_system() != HostSystem::Unix
254 && !policy.allow_ambiguous_symlink_modes
255 {
256 return Err(policy_violation(
257 position,
258 IndexPolicyViolation::AmbiguousSymlinkMode,
259 ));
260 }
261
262 Ok(BufferedEntry::Complete(entry, size::CENTRAL + length))
263 }
264}
265
266#[derive(Debug)]
273pub struct IndexedEntry {
274 directory: CentralDirectoryEntry,
275 boundary: u64,
278}
279
280impl IndexedEntry {
281 pub fn directory(&self) -> &CentralDirectoryEntry {
283 &self.directory
284 }
285
286 pub fn record_range(&self) -> Range<u64> {
291 self.directory.position()..self.boundary
292 }
293
294 #[inline]
295 pub(super) fn new(directory: CentralDirectoryEntry, boundary: u64) -> Result<Self, Error> {
296 let mut entry = Self {
297 directory,
298 boundary,
299 };
300 entry.set_boundary(boundary)?;
301 Ok(entry)
302 }
303
304 #[inline]
305 pub(super) fn set_boundary(&mut self, boundary: u64) -> Result<(), Error> {
306 let minimum = add(
309 size::LOCAL as u64 + self.directory.path.len() as u64,
310 self.directory.compressed_size(),
311 )?;
312 let minimum = add(
313 minimum,
314 if self
315 .directory
316 .common
317 .flags
318 .contains(GeneralPurposeFlags::DATA_DESCRIPTOR)
319 {
320 size::DESCRIPTOR as u64
321 } else {
322 0
323 },
324 )?;
325 if add(self.directory.position(), minimum)? > boundary {
326 return Err(invalid(
327 self.directory.position(),
328 "member cannot fit before the next record",
329 ));
330 }
331
332 self.boundary = boundary;
333 Ok(())
334 }
335
336 pub(super) async fn read_local<R: AsyncRead + AsyncSeek + Unpin>(
339 &self,
340 reader: &mut RecordReader<'_, R>,
341 budget: &mut Budget,
342 policy: &IndexPolicy,
343 ) -> Result<ResolvedMember, Error> {
344 let directory = &self.directory;
345 let boundary = self.boundary;
346 let position = directory.local_offset;
347 let mut header = [0; size::LOCAL];
348 reader.read_at(position, &mut header, boundary).await?;
349 if u32::from_le_bytes(array_at::<0, 4, _>(&header)) != signature::LOCAL {
350 return Err(invalid(position, "invalid local header signature"));
351 }
352
353 let header_fields =
354 MemberHeader::parse(&array_at::<4, { MemberHeader::SIZE }, _>(&header), position)?;
355 let name_length = usize::from(u16::from_le_bytes(array_at::<26, 2, _>(&header)));
356 let extra_length = usize::from(u16::from_le_bytes(array_at::<28, 2, _>(&header)));
357 budget.charge_metadata((size::LOCAL + name_length + extra_length) as u64)?;
358
359 let variable = reader
360 .read_slice(
361 position + size::LOCAL as u64,
362 name_length + extra_length,
363 boundary,
364 )
365 .await?;
366
367 if &variable[..name_length] != directory.path.as_bytes() {
370 return Err(invalid(position, "local and central filenames disagree"));
371 }
372 let (fields, zip64, unix_data) = directory.extra.resolve_local(
373 &variable[name_length..],
374 header_fields,
375 &directory.path,
376 policy.extra_fields,
377 policy.allow_redundant_zip64_sizes,
378 position,
379 )?;
380 if header_fields.common != directory.common {
381 return Err(invalid(position, "local and central headers disagree"));
382 }
383
384 let has_descriptor = directory
385 .common
386 .flags
387 .contains(GeneralPurposeFlags::DATA_DESCRIPTOR);
388 if has_descriptor {
389 if fields != PayloadFields::default() {
390 return Err(invalid(
391 position,
392 "descriptor member has nonzero local CRC or sizes",
393 ));
394 }
395 } else if fields != directory.payload.fields() {
396 return Err(invalid(position, "local and central CRC or sizes disagree"));
397 }
398
399 let data_offset = add(position, size::LOCAL as u64 + variable.len() as u64)?;
400 let data_end = add(data_offset, directory.compressed_size())?;
401 if data_end > boundary {
402 return Err(invalid(position, "payload overlaps the next record"));
403 }
404
405 if has_descriptor {
406 self.check_descriptor(reader, data_end, zip64).await?;
407 } else if data_end != boundary {
408 return Err(invalid(data_end, "unaccounted bytes after payload"));
409 }
410
411 let attributes =
412 ExternalAttributes::new(directory.host_system(), directory.external_attributes());
413 let resolved = ResolvedMember {
414 data_offset,
415 has_unix_extra: unix_data.is_some(),
416 kind: EntryKind::resolve(directory, unix_data, &attributes)?,
417 unix_mode: attributes.unix_mode,
418 };
419 let minimum = resolved.kind.minimum_version();
420 policy.check_version(directory.version_needed(), minimum, position)?;
421 let local_minimum =
424 header_fields.minimum_version(header_fields.payload.uncompressed == SizeField::Zip64);
425 policy.check_version(header_fields.version, minimum.max(local_minimum), position)?;
426 Ok(resolved)
427 }
428
429 async fn check_descriptor<R: AsyncRead + AsyncSeek + Unpin>(
435 &self,
436 reader: &mut RecordReader<'_, R>,
437 position: u64,
438 zip64: bool,
439 ) -> Result<(), Error> {
440 let directory = &self.directory;
441 let unsigned_length = if zip64 {
442 size::ZIP64_DESCRIPTOR as u64
443 } else {
444 size::DESCRIPTOR as u64
445 };
446 let length = self.boundary - position;
447 if length != unsigned_length && length != unsigned_length + size::SIGNATURE as u64 {
448 return Err(invalid(position, "invalid data descriptor length"));
449 }
450
451 let mut bytes = [0; size::SIGNATURE + size::ZIP64_DESCRIPTOR];
452 reader
453 .read_at(position, &mut bytes[..length as usize], self.boundary)
454 .await?;
455
456 let offset = if length == unsigned_length + size::SIGNATURE as u64 {
459 if u32::from_le_bytes(array_at::<0, 4, _>(&bytes)) != signature::DESCRIPTOR {
460 return Err(invalid(position, "invalid data descriptor signature"));
461 }
462
463 size::SIGNATURE
464 } else {
465 0
466 };
467
468 let crc = u32::from_le_bytes(bytes_at(&bytes, offset, position)?);
469 let (compressed, uncompressed) = if zip64 {
470 (
471 u64::from_le_bytes(bytes_at(&bytes, offset + 4, position)?),
472 u64::from_le_bytes(bytes_at(&bytes, offset + 12, position)?),
473 )
474 } else {
475 (
476 u64::from(u32::from_le_bytes(bytes_at(&bytes, offset + 4, position)?)),
477 u64::from(u32::from_le_bytes(bytes_at(&bytes, offset + 8, position)?)),
478 )
479 };
480 let fields = PayloadFields {
481 crc,
482 compressed,
483 uncompressed,
484 };
485 if fields != directory.payload.fields() {
486 return Err(invalid(
487 position,
488 "data descriptor disagrees with central header",
489 ));
490 }
491
492 Ok(())
493 }
494}