forge
Explore
Log in

Don't you dare go Hollow

Refuse the headers hound refuses, and say so honestly

Browse files at this commit

30d372e461d4e2e07cec9b2bc0acd2dbf213b646Ahmet Kaan GümüşParent: acb0d04
  • fix
    • refuse the headers hound refuses, and say so honestly
Show full message
fix(riff): refuse the headers hound refuses, and say so honestly

The WAV reader accepted three files hound rejects, each one a silent misread
rather than an error: a `data` chunk shorter than its declared size read as a
complete file, a padded container (8-bit samples in 2-byte slots) read at the
wrong stride so every frame after the first came from the wrong offset, and a
depth that is not a whole number of bytes (12-, 20-bit) taken as if it were.

The stride and depth checks live in `ec-riff`'s `parse_fmt`, where every reader
routes through; the odd depth is `corrupt` and the padded container
`unsupported`, which the shim maps to hound's `FormatError` and `Unsupported`
respectively. Truncation is checked in the shim instead: `ec-riff` deliberately
reads what is there and reports it, so the shim compares the sample count
against the frame count the `data` header promised and yields hound's
`UnexpectedEof`. The write path is untouched.

The shim's header claimed its differences were "all in the strict direction",
which was true of writing and false of reading; it now lists the reader
divergences that remain -- single-item error iterators where hound repeats the
refusal per sample, and its own wording.

Checks: `cargo test -p hound` (5 tests) covers a truncated file, a padded
container, 12- and 20-bit depths and a well-formed control; `cargo test -p
ec-riff` is unchanged, its truncation-tolerance test included.
crates/ec-riff/src/read.rsmodified+18 -0
@@ -175,6 +175,7 @@ fn parse_fmt<R: Read>(r: &mut R, size: u64) -> Result<WavSpec> {
175175 let mut tag = u16::from_le_bytes([f[0], f[1]]);
176176 let channels = u16::from_le_bytes([f[2], f[3]]);
177177 let sample_rate = u32::from_le_bytes([f[4], f[5], f[6], f[7]]);
178+ let block_align = u16::from_le_bytes([f[12], f[13]]);
178179 let bits_per_sample = u16::from_le_bytes([f[14], f[15]]);
179180 let mut rest = size - 16;
180181
@@ -203,6 +204,14 @@ fn parse_fmt<R: Read>(r: &mut R, size: u64) -> Result<WavSpec> {
203204 ));
204205 }
205206 };
207+ // A depth that is not a whole number of bytes (12-bit, 20-bit) is
208+ // ill-formed for these tags, not merely unimplemented: nothing in the
209+ // header says how the odd bits sit in their container.
210+ if bits_per_sample % 8 != 0 {
211+ return Err(Error::corrupt(format!(
212+ "WAVE fmt: {bits_per_sample} bits per sample is not a multiple of eight"
213+ )));
214+ }
206215 let spec = WavSpec {
207216 channels,
208217 sample_rate,
@@ -210,5 +219,14 @@ fn parse_fmt<R: Read>(r: &mut R, size: u64) -> Result<WavSpec> {
210219 sample_format,
211220 };
212221 spec.validate()?;
222+ // The stride the file declares must be the stride the depth implies —
223+ // otherwise every frame after the first is read from the wrong offset.
224+ // Padded containers (8-bit samples in 2-byte slots) live here.
225+ if usize::from(block_align) != spec.block_align() {
226+ return Err(Error::unsupported(
227+ format!("a WAVE block align of {block_align} for {channels}x{bits_per_sample}-bit"),
228+ "ec-riff reads samples packed at their declared depth, without container padding",
229+ ));
230+ }
213231 Ok(spec)
214232 }
shims/hound/src/lib.rsmodified+39 -5
@@ -8,10 +8,20 @@
88 //! — because a shim that grows a surface nobody calls is a second
99 //! implementation to keep honest.
1010 //!
11-//! Behaviour differences from the incumbent, all in the strict direction:
12-//! files with more than two channels or more than 16 bits get a
11+//! Behaviour differences from the incumbent. Writing is stricter only: files
12+//! with more than two channels or more than 16 bits get a
1313 //! `WAVE_FORMAT_EXTENSIBLE` header (hound writes one only above 16 bits), and
14-//! a `fact` chunk goes with it.
14+//! a `fact` chunk goes with it. Reading diverges in shape, not in verdict —
15+//! the refusals are hound's, the reporting is not:
16+//!
17+//! * [`WavReader::samples`] reads the `data` chunk whole before yielding, so a
18+//! file that ends early yields one [`Error::IoError`] and nothing else,
19+//! where hound yields the samples it did read and then the `UnexpectedEof`.
20+//! [`Error::TooWide`] and [`Error::InvalidSampleFormat`] are single-item for
21+//! the same reason; hound repeats them per sample.
22+//! * `bits_per_sample` outside 8/16/24/32 is [`Error::FormatError`] when it is
23+//! not a whole number of bytes and [`Error::Unsupported`] otherwise, which
24+//! splits hound's refusals along the same line but not with its wording.
1525
1626 #![forbid(unsafe_code)]
1727 #![warn(missing_docs)]
@@ -275,18 +285,31 @@ impl<R: Read> WavReader<R> {
275285 pub fn samples<S: Sample>(&mut self) -> WavSamples<S> {
276286 let spec = self.inner.spec();
277287 let float_file = spec.sample_format == ec_riff::SampleType::Float;
288+ // What the `data` header promised. `ec-riff` stops at the end of the
289+ // file without complaint; hound hands the caller the `UnexpectedEof`,
290+ // so the promise is compared against what arrived.
291+ let promised = self
292+ .inner
293+ .duration()
294+ .map(|frames| frames as usize * usize::from(spec.channels));
278295 let items = if float_file != S::FLOAT {
279296 vec![Err(Error::InvalidSampleFormat)]
280297 } else if spec.bits_per_sample > S::BITS {
281298 vec![Err(Error::TooWide)]
282299 } else if float_file {
283300 match self.inner.read_all_f32() {
284- Ok(v) => v.into_iter().map(|s| Ok(S::from_f32(s))).collect(),
301+ Ok(v) => match short_read(v.len(), promised) {
302+ Some(e) => vec![Err(e)],
303+ None => v.into_iter().map(|s| Ok(S::from_f32(s))).collect(),
304+ },
285305 Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))],
286306 }
287307 } else {
288308 match self.inner.read_all_i32() {
289- Ok(v) => v.into_iter().map(|s| Ok(S::from_i32(s))).collect(),
309+ Ok(v) => match short_read(v.len(), promised) {
310+ Some(e) => vec![Err(e)],
311+ None => v.into_iter().map(|s| Ok(S::from_i32(s))).collect(),
312+ },
290313 Err(e) => vec![Err(map(e, Error::FormatError("truncated WAVE data")))],
291314 }
292315 };
@@ -294,6 +317,17 @@ impl<R: Read> WavReader<R> {
294317 }
295318 }
296319
320+/// The `UnexpectedEof` hound reports when the `data` chunk ends before the
321+/// length its header declares, or `None` when the file kept its promise (or
322+/// made none: a streamed placeholder size leaves the file itself the bound).
323+fn short_read(got: usize, promised: Option<usize>) -> Option<Error> {
324+ let want = promised.filter(|&n| got < n)?;
325+ Some(Error::IoError(io::Error::new(
326+ io::ErrorKind::UnexpectedEof,
327+ format!("WAVE data chunk ends after {got} of {want} samples"),
328+ )))
329+}
330+
297331 /// The iterator [`WavReader::samples`] returns.
298332 pub struct WavSamples<S>(std::vec::IntoIter<Result<S>>);
299333
shims/hound/tests/edith_surface.rsmodified+75 -0
@@ -85,6 +85,81 @@ fn edith_read_wav_round_trips() {
8585 ));
8686 }
8787
88+/// A `data` chunk that ends before its header said is hound's `IoError`
89+/// (`UnexpectedEof`), never a short read the caller mistakes for the whole file.
90+#[test]
91+fn truncated_data_chunk_errors() {
92+ let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"));
93+ std::fs::create_dir_all(dir).unwrap();
94+ let path = dir.join("truncated.wav");
95+ let samples: Vec<i32> = (0..1024).map(|i| (i * 17) % 4096).collect();
96+ write_wav(&path, &samples, 2, 48000).unwrap();
97+
98+ // Half the samples away, the header still promising all of them.
99+ let bytes = std::fs::read(&path).unwrap();
100+ std::fs::write(&path, &bytes[..bytes.len() - 1024]).unwrap();
101+
102+ let mut r = hound::WavReader::open(&path).unwrap();
103+ let first = r.samples::<i16>().next();
104+ assert!(
105+ matches!(&first, Some(Err(hound::Error::IoError(e))) if e.kind() == std::io::ErrorKind::UnexpectedEof),
106+ "expected UnexpectedEof, got {first:?}"
107+ );
108+}
109+
110+/// A minimal PCM WAVE header with `block_align` and `bits_per_sample` stated
111+/// independently, so a padded container can be handed to the reader.
112+fn wav_bytes(channels: u16, bits: u16, block_align: u16, data: &[u8]) -> Vec<u8> {
113+ let mut v = Vec::new();
114+ v.extend_from_slice(b"RIFF");
115+ v.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
116+ v.extend_from_slice(b"WAVEfmt ");
117+ v.extend_from_slice(&16u32.to_le_bytes());
118+ v.extend_from_slice(&1u16.to_le_bytes()); // WAVE_FORMAT_PCM
119+ v.extend_from_slice(&channels.to_le_bytes());
120+ v.extend_from_slice(&48000u32.to_le_bytes());
121+ v.extend_from_slice(&(48000 * u32::from(block_align)).to_le_bytes());
122+ v.extend_from_slice(&block_align.to_le_bytes());
123+ v.extend_from_slice(&bits.to_le_bytes());
124+ v.extend_from_slice(b"data");
125+ v.extend_from_slice(&(data.len() as u32).to_le_bytes());
126+ v.extend_from_slice(data);
127+ v
128+}
129+
130+/// The header pair the reader must not paper over: a container wider than the
131+/// depth (hound: `Unsupported`) and a depth that is not whole bytes (hound:
132+/// `FormatError`). Reading either as if it were packed would silently double
133+/// the sample count and halve the duration.
134+#[test]
135+fn container_width_and_odd_depths_are_refused() {
136+ let padded = wav_bytes(1, 8, 2, &[0x80, 0x00, 0x90, 0x00]);
137+ assert!(
138+ matches!(
139+ hound::WavReader::new(std::io::Cursor::new(padded)),
140+ Err(hound::Error::Unsupported)
141+ ),
142+ "8-bit samples in a 2-byte container must be refused"
143+ );
144+
145+ for bits in [12u16, 20] {
146+ let odd = wav_bytes(1, bits, bits.div_ceil(8), &[0; 8]);
147+ assert!(
148+ matches!(
149+ hound::WavReader::new(std::io::Cursor::new(odd)),
150+ Err(hound::Error::FormatError(_))
151+ ),
152+ "{bits}-bit must be a FormatError"
153+ );
154+ }
155+
156+ // The well-formed shape of the same helper still opens, so the refusals
157+ // above are about the fields under test and not about the fixture.
158+ let ok = wav_bytes(2, 16, 4, &[0; 16]);
159+ let r = hound::WavReader::new(std::io::Cursor::new(ok)).expect("a packed 16-bit stereo header");
160+ assert_eq!(r.spec().bits_per_sample, 16);
161+}
162+
88163 #[test]
89164 fn errors_carry_the_incumbent_variants() {
90165 let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR"));