use std::{
io::{self, SeekFrom},
str,
};
use memchr::memchr;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeek, AsyncSeekExt};
use crate::{
CompressionMethod, Error, IndexPolicyViolation, add, constants::version, invalid,
policy_violation,
};
pub(crate) struct RecordReader<'a, R> {
inner: &'a mut R,
buffer: &'a mut Vec<u8>,
start: u64,
capacity: usize,
}
impl<'a, R: AsyncRead + AsyncSeek + Unpin> RecordReader<'a, R> {
pub(crate) fn new(inner: &'a mut R, capacity: usize, buffer: &'a mut Vec<u8>) -> Self {
buffer.clear();
Self {
inner,
buffer,
start: 0,
capacity,
}
}
pub(crate) async fn length(&mut self) -> Result<u64, Error> {
Ok(self.inner.seek(SeekFrom::End(0)).await?)
}
pub(crate) fn buffered(&self, position: u64, end: u64) -> &[u8] {
let window_end = end.min(self.start + self.buffer.len() as u64);
if position < self.start || position >= window_end {
return &[];
}
&self.buffer[(position - self.start) as usize..(window_end - self.start) as usize]
}
pub(crate) async fn read_slice(
&mut self,
position: u64,
length: usize,
end: u64,
) -> Result<&[u8], Error> {
let requested_end = add(position, length as u64)?;
if requested_end > end {
return Err(invalid(position, "record extends beyond its container"));
}
if length == 0 {
return Ok(&[]);
}
if position < self.start || requested_end > self.start + self.buffer.len() as u64 {
self.inner.seek(SeekFrom::Start(position)).await?;
let read_length = (end - position).min(self.capacity.max(length) as u64) as usize;
self.fill(read_length).await?;
self.start = position;
}
let offset = (position - self.start) as usize;
Ok(&self.buffer[offset..offset + length])
}
pub(crate) async fn read_at(
&mut self,
position: u64,
bytes: &mut [u8],
end: u64,
) -> Result<(), Error> {
let requested_end = add(position, bytes.len() as u64)?;
if requested_end > end {
return Err(invalid(position, "record extends beyond its container"));
}
if bytes.is_empty() {
return Ok(());
}
if position >= self.start && requested_end <= self.start + self.buffer.len() as u64 {
let offset = (position - self.start) as usize;
bytes.copy_from_slice(&self.buffer[offset..offset + bytes.len()]);
return Ok(());
}
self.inner.seek(SeekFrom::Start(position)).await?;
if bytes.len() >= self.capacity {
self.inner.read_exact(bytes).await?;
return Ok(());
}
let length = (end - position).min(self.capacity as u64) as usize;
self.fill(length).await?;
self.start = position;
bytes.copy_from_slice(&self.buffer[..bytes.len()]);
Ok(())
}
async fn fill(&mut self, length: usize) -> Result<(), Error> {
self.buffer.clear();
self.buffer.reserve(length);
let mut reader = (&mut *self.inner).take(length as u64);
while reader.limit() != 0 {
if reader.read_buf(self.buffer).await? == 0 {
return Err(io::Error::from(io::ErrorKind::UnexpectedEof).into());
}
}
Ok(())
}
}
pub(crate) fn array_at<const OFFSET: usize, const WIDTH: usize, const LEN: usize>(
bytes: &[u8; LEN],
) -> [u8; WIDTH] {
const { assert!(OFFSET <= LEN && WIDTH <= LEN - OFFSET) };
std::array::from_fn(|index| bytes[OFFSET + index])
}
pub(crate) fn bytes_at<const N: usize>(
bytes: &[u8],
offset: usize,
position: u64,
) -> Result<[u8; N], Error> {
bytes
.get(offset..)
.and_then(<[u8]>::first_chunk)
.copied()
.ok_or_else(|| invalid(position, "truncated integer field"))
}
#[inline]
pub(crate) fn parse_name(
bytes: &[u8],
flags: GeneralPurposeFlags,
position: u64,
allow_backslashes: bool,
) -> Result<&str, Error> {
let name = str::from_utf8(bytes).map_err(|_| invalid(position, "non-UTF-8 filename"))?;
if !flags.contains(GeneralPurposeFlags::UTF8) && !name.is_ascii() {
return Err(invalid(position, "non-ASCII filename without UTF-8 flag"));
}
validate_name(name, position)?;
if !allow_backslashes && memchr(b'\\', bytes).is_some() {
return Err(policy_violation(
position,
IndexPolicyViolation::BackslashInName,
));
}
Ok(name)
}
#[inline]
pub(crate) fn validate_name(name: &str, position: u64) -> Result<(), Error> {
let bytes = name.as_bytes();
if name.starts_with('\u{feff}')
|| memchr(0, bytes).is_some()
|| name.starts_with('/')
|| (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
{
return Err(invalid(position, "invalid ZIP filename"));
}
Ok(())
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct GeneralPurposeFlags(u16);
impl GeneralPurposeFlags {
const ENCRYPTED: Self = Self(0x0001);
const DEFLATE_OPTIONS: Self = Self(0x0006);
pub(crate) const DATA_DESCRIPTOR: Self = Self(0x0008);
const PATCHED_DATA: Self = Self(0x0020);
const STRONG_ENCRYPTION: Self = Self(0x0040);
pub(crate) const UTF8: Self = Self(0x0800);
const MASKED_HEADER: Self = Self(0x2000);
pub(crate) fn parse(bits: u16, position: u64) -> Result<Self, Error> {
let flags = Self(bits);
if flags.contains(Self::ENCRYPTED)
|| flags.contains(Self::STRONG_ENCRYPTION)
|| flags.contains(Self::MASKED_HEADER)
{
return Err(Error::Unsupported {
position,
feature: "encryption",
});
}
if flags.contains(Self::PATCHED_DATA) {
return Err(Error::Unsupported {
position,
feature: "patched data",
});
}
let allowed = Self::UTF8.0 | Self::DATA_DESCRIPTOR.0 | Self::DEFLATE_OPTIONS.0;
if bits & !allowed != 0 {
return Err(invalid(
position,
"reserved or inapplicable general-purpose flags",
));
}
Ok(flags)
}
fn bits(self) -> u16 {
self.0
}
pub(crate) fn contains(self, flags: Self) -> bool {
self.0 & flags.0 == flags.0
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum SizeField {
Value(u32),
Zip64,
}
impl From<u32> for SizeField {
fn from(value: u32) -> Self {
match value {
u32::MAX => Self::Zip64,
_ => Self::Value(value),
}
}
}
impl From<SizeField> for u32 {
fn from(value: SizeField) -> Self {
match value {
SizeField::Value(value) => value,
SizeField::Zip64 => u32::MAX,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct Common {
pub(crate) flags: GeneralPurposeFlags,
pub(crate) method: CompressionMethod,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct PayloadFields<S = u64> {
pub(crate) crc: u32,
pub(crate) compressed: S,
pub(crate) uncompressed: S,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct MemberPayload(PayloadFields);
impl PayloadFields {
pub(crate) fn validate(
self,
method: CompressionMethod,
position: u64,
) -> Result<MemberPayload, Error> {
match method {
CompressionMethod::Stored if self.compressed != self.uncompressed => {
return Err(invalid(position, "stored member sizes differ"));
}
CompressionMethod::Deflate if self.compressed == 0 && self.uncompressed != 0 => {
return Err(invalid(
position,
"nonempty DEFLATE member has zero compressed size",
));
}
CompressionMethod::Stored | CompressionMethod::Deflate => {}
}
if self.uncompressed == 0 && self.crc != 0 {
return Err(invalid(position, "empty member has nonzero CRC"));
}
Ok(MemberPayload(self))
}
}
impl MemberPayload {
pub(crate) fn has_empty_deflate_stream(self) -> bool {
self.0.uncompressed == 0 && self.0.compressed != 0
}
pub(crate) fn fields(self) -> PayloadFields {
self.0
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct MemberHeader {
pub(crate) version: u16,
pub(crate) common: Common,
pub(crate) time: u16,
pub(crate) date: u16,
pub(crate) payload: PayloadFields<SizeField>,
}
impl MemberHeader {
pub(crate) const SIZE: usize = 22;
#[inline]
pub(crate) fn parse(bytes: &[u8; Self::SIZE], position: u64) -> Result<Self, Error> {
let method =
CompressionMethod::parse(u16::from_le_bytes(array_at::<4, 2, _>(bytes)), position)?;
let flags =
GeneralPurposeFlags::parse(u16::from_le_bytes(array_at::<2, 2, _>(bytes)), position)?;
let version = u16::from(bytes[0]);
if version > version::ZIP64 {
return Err(Error::Unsupported {
position,
feature: "extraction version",
});
}
Ok(Self {
version,
common: Common { flags, method },
time: u16::from_le_bytes(array_at::<6, 2, _>(bytes)),
date: u16::from_le_bytes(array_at::<8, 2, _>(bytes)),
payload: PayloadFields {
crc: u32::from_le_bytes(array_at::<10, 4, _>(bytes)),
compressed: SizeField::from(u32::from_le_bytes(array_at::<14, 4, _>(bytes))),
uncompressed: SizeField::from(u32::from_le_bytes(array_at::<18, 4, _>(bytes))),
},
})
}
pub(crate) fn to_bytes(self) -> [u8; Self::SIZE] {
let mut bytes = [0; Self::SIZE];
bytes[0..2].copy_from_slice(&self.version.to_le_bytes());
bytes[2..4].copy_from_slice(&self.common.flags.bits().to_le_bytes());
bytes[4..6].copy_from_slice(&(self.common.method as u16).to_le_bytes());
bytes[6..8].copy_from_slice(&self.time.to_le_bytes());
bytes[8..10].copy_from_slice(&self.date.to_le_bytes());
bytes[10..14].copy_from_slice(&self.payload.crc.to_le_bytes());
bytes[14..18].copy_from_slice(&u32::from(self.payload.compressed).to_le_bytes());
bytes[18..22].copy_from_slice(&u32::from(self.payload.uncompressed).to_le_bytes());
bytes
}
pub(crate) fn minimum_version(self, requires_zip64: bool) -> u16 {
if requires_zip64 {
return version::ZIP64;
}
match self.common.method {
CompressionMethod::Stored => version::BASE,
CompressionMethod::Deflate => version::V2_0,
}
}
}
#[cfg(test)]
mod tests {
use std::io::Cursor;
use super::{
Common, GeneralPurposeFlags, MemberHeader, PayloadFields, RecordReader, SizeField,
array_at, bytes_at,
};
use crate::{CompressionMethod, Error};
#[tokio::test]
async fn bounds_reads_before_allocation() -> Result<(), Error> {
let mut source = Cursor::new([1, 2, 3, 4]);
let mut buffer = Vec::with_capacity(64);
let mut reader = RecordReader::new(&mut source, 4, &mut buffer);
assert!(matches!(
reader.read_slice(0, usize::MAX, 4).await,
Err(Error::Invalid {
position: 0,
reason: "record extends beyond its container",
})
));
assert_eq!(reader.read_slice(1, 2, 4).await?, [2, 3]);
assert_eq!(reader.read_slice(0, 2, 2).await?, [1, 2]);
assert_eq!(reader.inner.position(), 2);
Ok(())
}
#[test]
fn parses_and_serializes_common_header_fields() -> Result<(), Error> {
let bytes = [
20, 0, 0x0a, 0x08, 8, 0, 0x34, 0x12, 0x78, 0x56, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66,
0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc,
];
let header = MemberHeader {
version: 20,
common: Common {
flags: GeneralPurposeFlags::parse(0x080a, 42)?,
method: CompressionMethod::Deflate,
},
time: 0x1234,
date: 0x5678,
payload: PayloadFields {
crc: 0x4433_2211,
compressed: SizeField::Value(0x8877_6655),
uncompressed: SizeField::Value(0xccbb_aa99),
},
};
assert_eq!(MemberHeader::parse(&bytes, 42)?, header);
assert_eq!(header.to_bytes(), bytes);
Ok(())
}
#[test]
fn extracts_fields_from_fixed_arrays() {
let bytes = [1, 2, 3, 4, 5, 6, 7, 8];
assert_eq!(array_at::<0, 8, _>(&bytes), bytes);
assert_eq!(array_at::<1, 2, _>(&bytes), [2, 3]);
assert_eq!(array_at::<4, 4, _>(&bytes), [5, 6, 7, 8]);
assert_eq!(array_at::<8, 0, _>(&bytes), []);
}
#[test]
fn reads_fixed_width_fields_and_rejects_out_of_bounds_offsets() -> Result<(), Error> {
let bytes = [1, 2, 3, 4, 5, 6, 7, 8];
assert_eq!(u16::from_le_bytes(bytes_at(&bytes, 1, 42)?), 0x0302);
assert_eq!(u32::from_le_bytes(bytes_at(&bytes, 2, 42)?), 0x0605_0403);
assert_eq!(
u64::from_le_bytes(bytes_at(&bytes, 0, 42)?),
0x0807_0605_0403_0201
);
for offset in [7, 8, usize::MAX] {
assert!(matches!(
bytes_at::<2>(&bytes, offset, 42),
Err(Error::Invalid {
position: 42,
reason: "truncated integer field"
})
));
}
assert!(bytes_at::<8>(&bytes, 1, 42).is_err());
Ok(())
}
}