decryptune 1.1.3__tar.gz → 1.1.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. {decryptune-1.1.3 → decryptune-1.1.5}/Cargo.lock +5 -5
  2. {decryptune-1.1.3 → decryptune-1.1.5}/Cargo.toml +1 -1
  3. {decryptune-1.1.3 → decryptune-1.1.5}/PKG-INFO +2 -2
  4. {decryptune-1.1.3 → decryptune-1.1.5}/README.md +1 -1
  5. {decryptune-1.1.3 → decryptune-1.1.5}/python/decryptune/__init__.py +1 -1
  6. {decryptune-1.1.3 → decryptune-1.1.5}/src/boxes.rs +36 -7
  7. {decryptune-1.1.3 → decryptune-1.1.5}/src/cover.rs +6 -0
  8. {decryptune-1.1.3 → decryptune-1.1.5}/src/error.rs +4 -2
  9. {decryptune-1.1.3 → decryptune-1.1.5}/src/input.rs +7 -4
  10. {decryptune-1.1.3 → decryptune-1.1.5}/src/jpeg/decode.rs +31 -9
  11. {decryptune-1.1.3 → decryptune-1.1.5}/src/jpeg/tests.rs +36 -0
  12. {decryptune-1.1.3 → decryptune-1.1.5}/src/lib.rs +93 -36
  13. {decryptune-1.1.3 → decryptune-1.1.5}/src/meta.rs +7 -3
  14. {decryptune-1.1.3 → decryptune-1.1.5}/src/process.rs +279 -61
  15. decryptune-1.1.5/tests/fixtures/odd420.jpg +0 -0
  16. {decryptune-1.1.3 → decryptune-1.1.5}/tests/test_decryptune.py +168 -5
  17. {decryptune-1.1.3 → decryptune-1.1.5}/.gitattributes +0 -0
  18. {decryptune-1.1.3 → decryptune-1.1.5}/.github/workflows/build.yml +0 -0
  19. {decryptune-1.1.3 → decryptune-1.1.5}/.gitignore +0 -0
  20. {decryptune-1.1.3 → decryptune-1.1.5}/LICENSE +0 -0
  21. {decryptune-1.1.3 → decryptune-1.1.5}/pyproject.toml +0 -0
  22. {decryptune-1.1.3 → decryptune-1.1.5}/src/jpeg/encode.rs +0 -0
  23. {decryptune-1.1.3 → decryptune-1.1.5}/src/jpeg/mod.rs +0 -0
  24. {decryptune-1.1.3 → decryptune-1.1.5}/tests/fixtures/big.jpg +0 -0
  25. {decryptune-1.1.3 → decryptune-1.1.5}/tests/fixtures/tiny.jpg +0 -0
@@ -68,7 +68,7 @@ dependencies = [
68
68
 
69
69
  [[package]]
70
70
  name = "decryptune"
71
- version = "1.1.3"
71
+ version = "1.1.5"
72
72
  dependencies = [
73
73
  "aes",
74
74
  "ctr",
@@ -139,9 +139,9 @@ dependencies = [
139
139
 
140
140
  [[package]]
141
141
  name = "inout"
142
- version = "0.2.4"
142
+ version = "0.2.5"
143
143
  source = "registry+https://github.com/rust-lang/crates.io-index"
144
- checksum = "3ce983bb6fb399067d101fbfc9e74174e07e9f29a2bc679efefeb8c645819c3f"
144
+ checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f"
145
145
  dependencies = [
146
146
  "hybrid-array",
147
147
  ]
@@ -295,9 +295,9 @@ checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
295
295
 
296
296
  [[package]]
297
297
  name = "tokio"
298
- version = "1.53.3"
298
+ version = "1.54.0"
299
299
  source = "registry+https://github.com/rust-lang/crates.io-index"
300
- checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e"
300
+ checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc"
301
301
  dependencies = [
302
302
  "pin-project-lite",
303
303
  ]
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "decryptune"
3
- version = "1.1.3"
3
+ version = "1.1.5"
4
4
  edition = "2021"
5
5
  rust-version = "1.85"
6
6
  description = "Fast native M4A/fMP4 CENC decryptor, MP4 sanitizer and iTunes tagger, sync & async Python"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: decryptune
3
- Version: 1.1.3
3
+ Version: 1.1.5
4
4
  Classifier: Development Status :: 5 - Production/Stable
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: Programming Language :: Rust
@@ -60,7 +60,7 @@ Rules that hold for both `proc` and `aproc`:
60
60
  - `out` is a path → the file is written **atomically** (tmp + rename) and `None` is returned; `out` is `None` → the processed `bytes` are returned.
61
61
  - `key=None` → **fix-only pass**: headers sanitized, audio payload untouched.
62
62
  - A `meta` **wipes** the existing tag block and rebuilds it solely from the given fields — `None` / `0` / empty values are skipped; without `meta` the original metadata passes through untouched.
63
- - Any problem raises `DecrypTuneError` with a stable numeric code (1–13) and a message authored in the native core: `1` invalid key · `2` invalid kid · `3` input not found · `4` not an MP4 · `6` write failed · `7` KID mismatch · `8` corrupt audio detected · `9` bad input type · `10` bad out type · `11` tags need a fragmented file · `12` bad cover · `13` cover file not found.
63
+ - Any problem raises `DecrypTuneError` with a stable numeric code (1–14) and a message authored in the native core: `1` invalid key · `2` invalid kid · `3` input not found · `4` not an MP4 · `6` write failed · `7` KID mismatch · `8` corrupt audio detected · `9` bad input type · `10` bad out type · `11` tags need a fragmented file · `12` bad cover · `13` cover file not found · `14` cover too large (max 32 MB).
64
64
 
65
65
  ## Benchmark
66
66
 
@@ -43,7 +43,7 @@ Rules that hold for both `proc` and `aproc`:
43
43
  - `out` is a path → the file is written **atomically** (tmp + rename) and `None` is returned; `out` is `None` → the processed `bytes` are returned.
44
44
  - `key=None` → **fix-only pass**: headers sanitized, audio payload untouched.
45
45
  - A `meta` **wipes** the existing tag block and rebuilds it solely from the given fields — `None` / `0` / empty values are skipped; without `meta` the original metadata passes through untouched.
46
- - Any problem raises `DecrypTuneError` with a stable numeric code (1–13) and a message authored in the native core: `1` invalid key · `2` invalid kid · `3` input not found · `4` not an MP4 · `6` write failed · `7` KID mismatch · `8` corrupt audio detected · `9` bad input type · `10` bad out type · `11` tags need a fragmented file · `12` bad cover · `13` cover file not found.
46
+ - Any problem raises `DecrypTuneError` with a stable numeric code (1–14) and a message authored in the native core: `1` invalid key · `2` invalid kid · `3` input not found · `4` not an MP4 · `6` write failed · `7` KID mismatch · `8` corrupt audio detected · `9` bad input type · `10` bad out type · `11` tags need a fragmented file · `12` bad cover · `13` cover file not found · `14` cover too large (max 32 MB).
47
47
 
48
48
  ## Benchmark
49
49
 
@@ -29,7 +29,7 @@ except ImportError:
29
29
  _native = importlib.util.module_from_spec(importlib.util.spec_from_loader("decryptune", _loader))
30
30
  _loader.exec_module(_native)
31
31
 
32
- __version__ = "1.1.3"
32
+ __version__ = "1.1.5"
33
33
  __all__ = ["DecrypTune", "DecrypTuneError", "TuneMeta", "__version__"]
34
34
 
35
35
 
@@ -11,10 +11,18 @@ impl Box {
11
11
  pub fn is(&self, t: &[u8; 4]) -> bool { &self.typ == t }
12
12
  }
13
13
 
14
+ // hostile box spam: each parsed box costs 32 bytes of vec, so an absurd
15
+ // structure would multiply the input size many-fold. Parsing stops at the cap;
16
+ // callers check saturation via len() == MAX_BOXES and treat the input as
17
+ // invalid or pass it through rather than copying a structure no real file has.
18
+ // 2M top-level boxes would already be a 64MB vec for a 16MB input.
19
+ pub const MAX_BOXES: usize = 2_000_000;
20
+
14
21
  pub fn parse(data: &[u8], start: usize, end: usize) -> Vec<Box> {
15
22
  let mut out: Vec<Box> = Vec::new();
16
23
  let mut pos: usize = start;
17
24
  while pos + 8 <= end {
25
+ if out.len() >= MAX_BOXES { break; }
18
26
  let (size, hlen): (usize, usize) = match u32::from_be_bytes(data[pos..pos + 4].try_into().unwrap()) {
19
27
  0 => (end - pos, 8),
20
28
  1 if pos + 16 <= end => (u64::from_be_bytes(data[pos + 8..pos + 16].try_into().unwrap()) as usize, 16),
@@ -30,10 +38,23 @@ pub fn parse(data: &[u8], start: usize, end: usize) -> Vec<Box> {
30
38
  out
31
39
  }
32
40
 
41
+ // header length a box with this content size needs — content beyond the u32
42
+ // range switches to the 64-bit largesize form instead of wrapping the size
43
+ #[inline]
44
+ pub fn header_len(content_len: usize) -> usize {
45
+ if content_len + 8 > u32::MAX as usize { 16 } else { 8 }
46
+ }
47
+
33
48
  #[inline]
34
49
  pub fn write_header(out: &mut Vec<u8>, typ: &[u8; 4], content_len: usize) {
35
- out.extend_from_slice(&((content_len + 8) as u32).to_be_bytes());
36
- out.extend_from_slice(typ);
50
+ if content_len + 8 > u32::MAX as usize {
51
+ out.extend_from_slice(&1u32.to_be_bytes());
52
+ out.extend_from_slice(typ);
53
+ out.extend_from_slice(&((content_len as u64) + 16).to_be_bytes());
54
+ } else {
55
+ out.extend_from_slice(&((content_len + 8) as u32).to_be_bytes());
56
+ out.extend_from_slice(typ);
57
+ }
37
58
  }
38
59
 
39
60
  // output sink — Buf writes into an exactly-sized buffer, Count only measures.
@@ -59,15 +80,23 @@ impl Writer<'_> {
59
80
  }
60
81
  }
61
82
 
62
- // 32-bit box header (size + fourcc)
83
+ // 32-bit box header (size + fourcc) — or the 64-bit largesize form when the
84
+ // content cannot be expressed in 32 bits (rebuilt >4GB containers)
63
85
  pub fn header(&mut self, typ: &[u8; 4], content_len: usize) {
64
86
  match self {
65
87
  Writer::Buf { buf, pos } => {
66
- buf[*pos..*pos + 4].copy_from_slice(&((content_len + 8) as u32).to_be_bytes());
67
- buf[*pos + 4..*pos + 8].copy_from_slice(typ);
68
- *pos += 8;
88
+ if content_len + 8 > u32::MAX as usize {
89
+ buf[*pos..*pos + 4].copy_from_slice(&1u32.to_be_bytes());
90
+ buf[*pos + 4..*pos + 8].copy_from_slice(typ);
91
+ buf[*pos + 8..*pos + 16].copy_from_slice(&((content_len as u64) + 16).to_be_bytes());
92
+ *pos += 16;
93
+ } else {
94
+ buf[*pos..*pos + 4].copy_from_slice(&((content_len + 8) as u32).to_be_bytes());
95
+ buf[*pos + 4..*pos + 8].copy_from_slice(typ);
96
+ *pos += 8;
97
+ }
69
98
  }
70
- Writer::Count(n) => *n += 8
99
+ Writer::Count(n) => *n += header_len(content_len)
71
100
  }
72
101
  }
73
102
  }
@@ -9,12 +9,18 @@ use crate::meta::Cover;
9
9
  use crate::Err;
10
10
 
11
11
  const MAX_EDGE: u32 = 1000;
12
+ // a cover lands inside the ilst whole — 32MB is far above any real art and
13
+ // keeps a hostile "cover" from bloating the output file without bound
14
+ const MAX_COVER_BYTES: usize = 32 * 1024 * 1024;
12
15
 
13
16
  pub(crate) fn is_jpeg(b: &[u8]) -> bool { b.len() >= 2 && b[0] == 0xFF && b[1] == 0xD8 }
14
17
  pub(crate) fn is_png(b: &[u8]) -> bool { b.len() >= 8 && b[0..4] == [0x89, 0x50, 0x4E, 0x47] }
15
18
 
16
19
  /// Validate and (when needed) downscale a cover image to fit MAX_EDGE.
17
20
  pub(crate) fn prepare(raw: &[u8]) -> Result<Cover<'_>, Err> {
21
+ if raw.len() > MAX_COVER_BYTES {
22
+ return Err(Err::CoverTooLarge);
23
+ }
18
24
  if is_png(raw) {
19
25
  return Ok(Cover { data: Cow::Borrowed(raw), kind: 14 });
20
26
  }
@@ -19,7 +19,8 @@ pub(crate) enum Err {
19
19
  BadOutput = 10,
20
20
  MetaNeedsFragmented = 11,
21
21
  BadCover = 12,
22
- CoverNotFound = 13 // additive: a missing cover path must not read as a missing input
22
+ CoverNotFound = 13, // additive: a missing cover path must not read as a missing input
23
+ CoverTooLarge = 14 // additive: an absurd cover must not flow into the ilst whole
23
24
  }
24
25
 
25
26
  impl Err {
@@ -37,7 +38,8 @@ impl Err {
37
38
  Err::BadInput => "invalid input: expected bytes, bytearray, memoryview, or a path",
38
39
  Err::BadOutput => "invalid out: expected a path or None",
39
40
  Err::MetaNeedsFragmented => "metadata write requires a fragmented file (non-empty chunk offsets)",
40
- Err::BadCover => "unsupported cover format: expected JPEG or PNG"
41
+ Err::BadCover => "unsupported cover format: expected JPEG or PNG",
42
+ Err::CoverTooLarge => "cover too large (max 32 MB)"
41
43
  }
42
44
  }
43
45
  }
@@ -60,11 +60,13 @@ pub(crate) fn extract_bytes_or_path(value: &Bound<'_, PyAny>, bad: Err) -> PyRes
60
60
  } else if let Ok(b) = value.cast::<PyByteArray>() {
61
61
  Extracted::Bytes(b.to_vec()) // mutable — a copy is mandatory
62
62
  } else if let Ok(s) = value.cast::<PyString>() {
63
- Extracted::Path(s.to_str()?.to_string())
63
+ // to_str fails only on lone surrogates (real on Windows via os.fsdecode) —
64
+ // the Rust core takes String paths only, so that input has no valid encoding
65
+ Extracted::Path(s.to_str().map_err(|_| bad)?.to_string())
64
66
  } else if let Ok(p) = value.call_method0("__fspath__") { // os.PathLike
65
67
  // fspath may legally return bytes — map that here, never a raw downcast error
66
68
  Extracted::Path(if let Ok(s) = p.cast::<PyString>() {
67
- s.to_str()?.to_string()
69
+ s.to_str().map_err(|_| bad)?.to_string()
68
70
  } else if let Ok(b) = p.cast::<PyBytes>() {
69
71
  String::from_utf8_lossy(b.as_bytes()).into_owned()
70
72
  } else {
@@ -96,11 +98,12 @@ pub(crate) fn parse_output(out: Option<&Bound<'_, PyAny>>) -> PyResult<Output> {
96
98
  None => Ok(Output::Return),
97
99
  Some(v) => {
98
100
  let path: String = if let Ok(s) = v.cast::<PyString>() {
99
- s.to_str()?.to_string()
101
+ // lone surrogates have no Rust-side String encoding — coded error, not a leak
102
+ s.to_str().map_err(|_| Err::BadOutput)?.to_string()
100
103
  } else if let Ok(p) = v.call_method0("__fspath__") { // os.PathLike
101
104
  // same fspath-bytes rule as input — a coded error, not a raw downcast
102
105
  if let Ok(s) = p.cast::<PyString>() {
103
- s.to_str()?.to_string()
106
+ s.to_str().map_err(|_| Err::BadOutput)?.to_string()
104
107
  } else if let Ok(b) = p.cast::<PyBytes>() {
105
108
  String::from_utf8_lossy(b.as_bytes()).into_owned()
106
109
  } else {
@@ -5,6 +5,12 @@
5
5
  use super::ZIGZAG;
6
6
  use crate::Err;
7
7
 
8
+ // hostile SOF dimensions can demand multi-GB coefficient buffers before any
9
+ // entropy byte is read — covers are downscaled to 1000px anyway, so 64MP
10
+ // (8192²) is far beyond anything legitimate; at the old 256MP cap a ~1MB
11
+ // hostile JPEG forced ~1GB of buffers and seconds of IDCT
12
+ const MAX_PIXELS: usize = 67_108_864; // 64 megapixels
13
+
8
14
  struct HuffTable {
9
15
  counts : [u8; 17], // symbols per code length 1..=16
10
16
  first_code: [u16; 17],
@@ -13,15 +19,20 @@ struct HuffTable {
13
19
  }
14
20
 
15
21
  impl HuffTable {
16
- fn build(counts: &[u8; 17], symbols: Vec<u8>) -> HuffTable {
17
- let (mut first_code, mut val_off, mut code, mut k): ([u16; 17], [usize; 17], u16, usize) = ([0; 17], [0; 17], 0, 0);
22
+ // canonical code assignment with an overfull check: a table claiming more
23
+ // codes than a length's code space holds would overflow the u16 code and
24
+ // decode garbage downstream
25
+ fn build(counts: &[u8; 17], symbols: Vec<u8>) -> Result<HuffTable, Err> {
26
+ let (mut first_code, mut val_off, mut code, mut k): ([u16; 17], [usize; 17], u32, usize) = ([0; 17], [0; 17], 0, 0);
18
27
  for len in 1..=16 {
19
- first_code[len] = code;
28
+ first_code[len] = code as u16;
20
29
  val_off[len] = k;
21
30
  k += counts[len] as usize;
22
- code = (code + counts[len] as u16) << 1;
31
+ code += counts[len] as u32;
32
+ if code > (1u32 << len) { return Err(Err::BadCover); }
33
+ code <<= 1;
23
34
  }
24
- HuffTable { counts: *counts, first_code, val_off, symbols }
35
+ Ok(HuffTable { counts: *counts, first_code, val_off, symbols })
25
36
  }
26
37
 
27
38
  fn decode(&self, br: &mut BitReader<'_>) -> Result<u8, Err> {
@@ -29,7 +40,9 @@ impl HuffTable {
29
40
  for len in 1..=16 {
30
41
  code = (code << 1) | br.bit()? as i32;
31
42
  let (fc, cnt): (i32, i32) = (self.first_code[len] as i32, self.counts[len] as i32);
32
- if code - fc < cnt {
43
+ // cnt > 0 keeps an empty length from matching via a negative diff
44
+ // (code below the canonical first code of a longer prefix)
45
+ if cnt > 0 && code >= fc && code - fc < cnt {
33
46
  return Ok(self.symbols[self.val_off[len] + (code - fc) as usize]);
34
47
  }
35
48
  }
@@ -310,7 +323,7 @@ pub(crate) fn decode(raw: &[u8]) -> Result<(usize, usize, usize, Vec<u8>), Err>
310
323
  h = u16::from_be_bytes([raw[pos + 3], raw[pos + 4]]) as usize;
311
324
  w = u16::from_be_bytes([raw[pos + 5], raw[pos + 6]]) as usize;
312
325
  let nc: usize = raw[pos + 7] as usize;
313
- if w == 0 || h == 0 || (nc != 1 && nc != 3) || seg != 8 + nc * 3 { return Err(Err::BadCover); }
326
+ if w == 0 || h == 0 || w * h > MAX_PIXELS || (nc != 1 && nc != 3) || seg != 8 + nc * 3 { return Err(Err::BadCover); }
314
327
  comps.clear();
315
328
  for c in 0..nc {
316
329
  let b: usize = pos + 8 + c * 3;
@@ -360,7 +373,12 @@ pub(crate) fn decode(raw: &[u8]) -> Result<(usize, usize, usize, Vec<u8>), Err>
360
373
  counts[1..].copy_from_slice(&raw[p + 1..p + 17]);
361
374
  let total: usize = counts[1..].iter().map(|&c| c as usize).sum();
362
375
  if p + 17 + total > pos + seg { return Err(Err::BadCover); }
363
- let table: HuffTable = HuffTable::build(&counts, raw[p + 17..p + 17 + total].to_vec());
376
+ // a DC symbol is a magnitude category (0..=15): anything
377
+ // larger would underflow the bit reader's bit count
378
+ if tc == 0 && raw[p + 17..p + 17 + total].iter().any(|&s| s > 15) {
379
+ return Err(Err::BadCover);
380
+ }
381
+ let table: HuffTable = HuffTable::build(&counts, raw[p + 17..p + 17 + total].to_vec())?;
364
382
  if tc == 0 { dcs[th] = Some(table); } else { acs[th] = Some(table); }
365
383
  p += 17 + total;
366
384
  }
@@ -587,9 +605,13 @@ fn upsample_h2v2(plane: &[u8], pw: usize, ph: usize, w: usize, oh: usize) -> Vec
587
605
  for j in 0..oh.div_ceil(2) {
588
606
  let cur = &plane[j.min(ph - 1) * pw..];
589
607
  for dy in 0..2 {
608
+ // an odd output height ends on a dy=0 row; the below-blend pass
609
+ // would write row `oh` past the buffer, so it lands on `oh - 1`
610
+ // (libjpeg's bottom-edge replication)
611
+ let dst: usize = (2 * j + dy).min(oh - 1);
590
612
  let orow: usize = if dy == 0 { j.saturating_sub(1).min(ph - 1) } else { (j + 1).min(ph - 1) };
591
613
  let oth = &plane[orow * pw..];
592
- let orow_out = &mut out[(2 * j + dy) * w..(2 * j + dy) * w + w];
614
+ let orow_out = &mut out[dst * w..dst * w + w];
593
615
  let colsum = |i: usize| -> u32 { (cur[i.min(pw - 1)] as u32) * 3 + (oth[i.min(pw - 1)] as u32) };
594
616
  let (c0, c1): (u32, u32) = (colsum(0), colsum(1));
595
617
  orow_out[0] = ((c0 * 4 + 8) >> 4) as u8;
@@ -116,6 +116,42 @@ fn encode_edge_blocks() {
116
116
  assert_eq!((dw, dh, dch), (w, h, 3));
117
117
  }
118
118
 
119
+ #[test]
120
+ fn hostile_huge_sof_rejected() {
121
+ // SOF claims must fail validation before any buffer is allocated — a
122
+ // 65535x65535 claim wants ~8GB of coefficient buffers, and 16384x16384
123
+ // (the old 256MP cap's boundary) still wants ~1GB
124
+ for (w, h) in [(0xFFFFu16, 0xFFFFu16), (16384u16, 16384u16)] {
125
+ let sof: [u8; 11] = [0, 11, 8, (h >> 8) as u8, h as u8, (w >> 8) as u8, w as u8, 1, 1, 0x11, 0];
126
+ let jpg: Vec<u8> = [&[0xFF, 0xD8, 0xFF, 0xC0][..], &sof, &[0xFF, 0xD9][..]].concat();
127
+ assert!(decode(&jpg).is_err(), "{w}x{h} not rejected");
128
+ }
129
+ }
130
+
131
+ #[test]
132
+ fn hostile_dht_rejected() {
133
+ // DC magnitude symbols above 15 would underflow the bit reader's count and
134
+ // overfull canonical tables would overflow the code book — both rejected
135
+ // at DHT parse time (a debug build once panicked on the first)
136
+ let dqt: Vec<u8> = [[0xFFu8, 0xDB].as_slice(), &67u16.to_be_bytes(), &[0x00], &[1u8; 64]].concat();
137
+ let sof: Vec<u8> = [[0xFFu8, 0xC0].as_slice(), &11u16.to_be_bytes(), &[8u8, 0, 16, 0, 16, 1, 1, 0x11, 0]].concat();
138
+ let ac: Vec<u8> = [[0xFFu8, 0xC4].as_slice(), &20u16.to_be_bytes(), &[0x10], &[1u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], &[0]].concat();
139
+ let sos: Vec<u8> = [[0xFFu8, 0xDA].as_slice(), &8u16.to_be_bytes(), &[1u8, 1, 0, 0, 63, 0]].concat();
140
+ let dht = |class: u8, counts: &[u8], symbols: &[u8]| -> Vec<u8> {
141
+ [[0xFFu8, 0xC4].as_slice(), &((2 + 1 + 16 + symbols.len()) as u16).to_be_bytes(), &[class], counts, symbols].concat()
142
+ };
143
+ let counts_len1: [u8; 16] = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
144
+ let counts_overfull: [u8; 16] = [3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
145
+ let entropy_and_eoi = &[0x00u8, 0x00, 0xFF, 0xD9][..];
146
+ for bad_dht in [
147
+ dht(0x00, &counts_len1, &[200]), // DC symbol 200
148
+ dht(0x00, &counts_overfull, &[0, 1, 2, 3]), // 3 one-bit codes
149
+ ] {
150
+ let jpg: Vec<u8> = [&[0xFF, 0xD8][..], &dqt, &sof, &bad_dht, &ac, &sos, entropy_and_eoi].concat();
151
+ assert!(decode(&jpg).is_err());
152
+ }
153
+ }
154
+
119
155
  // DUMP_ENC=1 + JPEG_FIXTURES: write our encode of the p444 reference so the
120
156
  // local Pillow PSNR checker can score it against the same pristine source
121
157
  #[test]
@@ -10,17 +10,32 @@ use pyo3::exceptions::PyException;
10
10
  use pyo3::prelude::*;
11
11
  use pyo3::types::PyBytes;
12
12
 
13
+ use std::io::Write;
13
14
  use std::sync::atomic::{AtomicU64, Ordering};
14
15
 
15
16
  use error::Err;
16
17
  use input::{parse_input, parse_output, InputData, Output};
17
18
 
19
+ // strict [0-9a-fA-F] nibbles, decoded byte-wise: a multi-byte UTF-8 char can
20
+ // neither panic a char-boundary slice nor slip through from_str_radix, which
21
+ // would happily accept a sign-prefixed pair like "+f" as 0x0f
22
+ fn hex_nibble(b: u8) -> Option<u8> {
23
+ match b {
24
+ b'0'..=b'9' => Some(b - b'0'),
25
+ b'a'..=b'f' => Some(b - b'a' + 10),
26
+ b'A'..=b'F' => Some(b - b'A' + 10),
27
+ _ => None
28
+ }
29
+ }
30
+
18
31
  fn parse_hex16(hex: &str) -> Result<[u8; 16], Err> {
19
- let hex: &str = hex.trim();
32
+ let hex: &[u8] = hex.trim().as_bytes();
20
33
  if hex.len() != 32 { return Err(Err::InvalidKey); }
21
34
  let mut key: [u8; 16] = [0u8; 16];
22
35
  for (i, b) in key.iter_mut().enumerate() {
23
- *b = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).map_err(|_| Err::InvalidKey)?;
36
+ let hi: u8 = hex_nibble(hex[i * 2]).ok_or(Err::InvalidKey)?;
37
+ let lo: u8 = hex_nibble(hex[i * 2 + 1]).ok_or(Err::InvalidKey)?;
38
+ *b = (hi << 4) | lo;
24
39
  }
25
40
  Ok(key)
26
41
  }
@@ -43,21 +58,27 @@ fn tmp_path(out_path: &str) -> String {
43
58
  format!("{}.{}.{}.tmp", out_path, std::process::id(), N.fetch_add(1, Ordering::Relaxed))
44
59
  }
45
60
 
46
- // write to <out>.<n>.tmp then rename — no partial outputs on crash;
47
- // a failed rename removes the tmp file (no litter in the output directory)
61
+ // write to <out>.<n>.tmp, flush it to disk, then rename — no partial outputs
62
+ // on crash, and the rename cannot expose unflushed data after a power loss.
63
+ // create_new (O_CREAT|O_EXCL) refuses a symlink pre-placed at the predictable
64
+ // tmp name and fails on collision instead of clobbering an existing file
48
65
  fn write_atomic(out_path: &str, data: &[u8]) -> Result<(), Err> {
49
66
  let tmp: String = tmp_path(out_path);
50
- std::fs::write(&tmp, data).map_err(|_| Err::WriteFailed)?;
51
- if std::fs::rename(&tmp, out_path).is_err() {
67
+ let mut file: std::fs::File = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)
68
+ .map_err(|_| Err::WriteFailed)?;
69
+ if file.write_all(data).is_err()
70
+ || file.sync_data().is_err()
71
+ || std::fs::rename(&tmp, out_path).is_err() {
52
72
  let _ = std::fs::remove_file(&tmp);
53
73
  return Err(Err::WriteFailed);
54
74
  }
55
75
  Ok(())
56
76
  }
57
77
 
58
- // strict evidence check, shared by the sync and async tails
59
- fn check_strict(fragments: &[process::FragmentStat], key: Option<[u8; 16]>, strict: bool) -> PyResult<()> {
60
- if strict && key.is_some() {
78
+ // strict evidence check, shared by the sync and async tails; `guarded` is
79
+ // precomputed (strict && key given) because the key copy dies in its worker
80
+ fn check_strict(fragments: &[process::FragmentStat], guarded: bool) -> PyResult<()> {
81
+ if guarded {
61
82
  let bad_frags: Vec<String> = fragments.iter()
62
83
  .filter(|f| f.corrupt == Some(true))
63
84
  .map(|f| format!("#{} chi2={:.0} ({}B)", f.index, f.chi2, f.bytes))
@@ -72,13 +93,22 @@ fn check_strict(fragments: &[process::FragmentStat], key: Option<[u8; 16]>, stri
72
93
  Ok(())
73
94
  }
74
95
 
96
+ // best-effort key hygiene: volatile writes defeat dead-store elimination so
97
+ // the worker's AES key copy is cleared instead of lingering in freed memory
98
+ fn wipe_key(key: &mut Option<[u8; 16]>) {
99
+ if let Some(k) = key.as_mut() {
100
+ for b in k.iter_mut() { unsafe { std::ptr::write_volatile(b, 0u8); } }
101
+ }
102
+ }
103
+
75
104
  // pass 1, shared by proc/aproc: load input, guard kid, measure the exact
76
105
  // output length — all off the GIL; the loaded data and the metadata must
77
- // survive to pass 2, so the metadata comes back out
78
- fn load_and_measure(input: input::Input, key: Option<[u8; 16]>, kid: Option<String>, meta: Option<meta::CoreMeta>)
106
+ // survive to pass 2, so the metadata comes back out. Only `has_key` crosses
107
+ // here — the key itself never needs to reach the measure phase
108
+ fn load_and_measure(input: input::Input, has_key: bool, kid: Option<String>, meta: Option<meta::CoreMeta>)
79
109
  -> Result<(InputData, usize, Option<meta::CoreMeta>), Err> {
80
110
  let d: InputData = input.load()?;
81
- if key.is_some() { guard_kid(d.bytes(), kid.as_deref())?; }
111
+ if has_key { guard_kid(d.bytes(), kid.as_deref())?; }
82
112
  let mut meta = meta;
83
113
  if let Some(m) = meta.as_mut() { meta::pre_resolve_cover(m)?; } // cover codec work once
84
114
  let len: usize = process::measure(d.bytes(), meta.as_ref())?;
@@ -142,16 +172,6 @@ impl TuneMeta {
142
172
  }
143
173
  }
144
174
 
145
- // parsed proc/aproc arguments — every Send piece is resolved under the GIL
146
- // once, then moved wholesale into the worker
147
- struct Args {
148
- input : input::Input,
149
- output : Output,
150
- key : Option<[u8; 16]>,
151
- kid : Option<String>,
152
- core_meta: Option<meta::CoreMeta>
153
- }
154
-
155
175
  fn parse_args(
156
176
  py : Python<'_>,
157
177
  input: &Bound<'_, PyAny>,
@@ -169,6 +189,25 @@ fn parse_args(
169
189
  })
170
190
  }
171
191
 
192
+ // parse_args product with the has_key flag precomputed — measure/load never
193
+ // needs the key itself, only whether one was supplied (for the KID guard)
194
+ struct Args {
195
+ input : input::Input,
196
+ output : Output,
197
+ key : Option<[u8; 16]>,
198
+ kid : Option<String>,
199
+ core_meta: Option<meta::CoreMeta>
200
+ }
201
+
202
+ type ParsedArgs = (input::Input, Output, Option<[u8; 16]>, Option<String>, Option<meta::CoreMeta>, bool);
203
+
204
+ impl Args {
205
+ fn into_parts(self) -> ParsedArgs {
206
+ let has_key: bool = self.key.is_some();
207
+ (self.input, self.output, self.key, self.kid, self.core_meta, has_key)
208
+ }
209
+ }
210
+
172
211
  // Python TuneMeta → Send CoreMeta: only raw byte copies and path strings happen under
173
212
  // the GIL — cover disk read + JPEG prepare (decode/resize/encode) run in the worker
174
213
  // None/0/empty fields mean "keep whatever the file already carries".
@@ -218,17 +257,20 @@ fn proc<'py>(
218
257
  meta : Option<&TuneMeta>,
219
258
  strict : bool
220
259
  ) -> PyResult<Option<Bound<'py, PyAny>>> {
221
- let Args { input, output, key, kid, core_meta }: Args = parse_args(py, input, out, key, kid, meta)?;
260
+ let (input, output, key, kid, core_meta, has_key): ParsedArgs = parse_args(py, input, out, key, kid, meta)?.into_parts();
222
261
  let (data, len, core_meta): (InputData, usize, Option<meta::CoreMeta>) =
223
- py.detach(move || load_and_measure(input, key, kid, core_meta)).map_err(PyErr::from)?;
262
+ py.detach(move || load_and_measure(input, has_key, kid, core_meta)).map_err(PyErr::from)?;
263
+ let guarded: bool = strict && key.is_some();
224
264
 
225
265
  match output {
226
266
  Output::Path(p) => {
227
267
  py.detach(move || -> PyResult<()> {
268
+ let mut key: Option<[u8; 16]> = key;
228
269
  let mut buf: Vec<u8> = vec![0u8; len]; // exact-size output, no over-allocation
229
270
  let fragments: Vec<process::FragmentStat> =
230
271
  process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), &mut buf)?;
231
- check_strict(&fragments, key, strict)?;
272
+ wipe_key(&mut key);
273
+ check_strict(&fragments, guarded)?;
232
274
  write_atomic(&p, &buf)?;
233
275
  Ok(())
234
276
  })?;
@@ -243,10 +285,14 @@ fn proc<'py>(
243
285
  // pointer would break Send (disjoint capture hoists it out)
244
286
  let base: usize = bytes.as_bytes().as_ptr() as usize;
245
287
  let fragments: Vec<process::FragmentStat> = py.detach(move || -> PyResult<Vec<process::FragmentStat>> {
288
+ let mut key: Option<[u8; 16]> = key;
246
289
  let buf: &mut [u8] = unsafe { std::slice::from_raw_parts_mut(base as *mut u8, len) };
247
- Ok(process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), buf)?)
290
+ let fragments: Vec<process::FragmentStat> =
291
+ process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), buf)?;
292
+ wipe_key(&mut key);
293
+ Ok(fragments)
248
294
  })?;
249
- check_strict(&fragments, key, strict)?;
295
+ check_strict(&fragments, guarded)?;
250
296
  Ok(Some(bytes.into_any()))
251
297
  }
252
298
  }
@@ -273,21 +319,24 @@ fn aproc<'py>(
273
319
  meta : Option<&TuneMeta>,
274
320
  strict : bool
275
321
  ) -> PyResult<Bound<'py, PyAny>> {
276
- let Args { input, output, key, kid, core_meta }: Args = parse_args(py, input, out, key, kid, meta)?;
322
+ let (input, output, key, kid, core_meta, has_key): ParsedArgs = parse_args(py, input, out, key, kid, meta)?.into_parts();
323
+ let guarded: bool = strict && key.is_some();
277
324
 
278
325
  pyo3_async_runtimes::tokio::future_into_py(py, async move {
279
326
  let (data, len, core_meta): (InputData, usize, Option<meta::CoreMeta>) = tokio::task::spawn_blocking(
280
- move || load_and_measure(input, key, kid, core_meta),
327
+ move || load_and_measure(input, has_key, kid, core_meta),
281
328
  ).await.map_err(join_err)??;
282
329
  match output {
283
330
  Output::Path(p) => {
284
331
  // write+rename run inside ONE blocking task with the build — a
285
332
  // cancelled future cannot split the pair and leave a tmp behind
286
333
  tokio::task::spawn_blocking(move || -> PyResult<()> {
334
+ let mut key: Option<[u8; 16]> = key;
287
335
  let mut buf: Vec<u8> = vec![0u8; len];
288
336
  let fragments: Vec<process::FragmentStat> =
289
337
  process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), &mut buf)?;
290
- check_strict(&fragments, key, strict)?;
338
+ wipe_key(&mut key);
339
+ check_strict(&fragments, guarded)?;
291
340
  write_atomic(&p, &buf)?;
292
341
  Ok(())
293
342
  }).await.map_err(join_err)??;
@@ -295,16 +344,24 @@ fn aproc<'py>(
295
344
  }
296
345
  Output::Return => {
297
346
  // allocate the result under a brief GIL attach, then build off-GIL
298
- // straight into its buffer — no intermediate copy
347
+ // straight into its buffer — no intermediate copy. The PyBytes
348
+ // owner moves INTO the build task: a cancelled future drops its
349
+ // own references but the buffer stays referenced for the whole
350
+ // write (dropping it early would free the object under the writer)
299
351
  let (base, result): (usize, Py<PyBytes>) = Python::attach(|py| -> PyResult<(usize, Py<PyBytes>)> {
300
352
  let b: Bound<'_, PyBytes> = PyBytes::new_with(py, len, |_buf: &mut [u8]| Ok(()))?;
301
353
  Ok((b.as_bytes().as_ptr() as usize, b.unbind()))
302
354
  })?;
303
- let fragments: Vec<process::FragmentStat> = tokio::task::spawn_blocking(move || -> PyResult<Vec<process::FragmentStat>> {
304
- let buf: &mut [u8] = unsafe { std::slice::from_raw_parts_mut(base as *mut u8, len) };
305
- Ok(process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), buf)?)
306
- }).await.map_err(join_err)??;
307
- check_strict(&fragments, key, strict)?;
355
+ let (fragments, result): (Vec<process::FragmentStat>, Py<PyBytes>) =
356
+ tokio::task::spawn_blocking(move || -> PyResult<(Vec<process::FragmentStat>, Py<PyBytes>)> {
357
+ let mut key: Option<[u8; 16]> = key;
358
+ let buf: &mut [u8] = unsafe { std::slice::from_raw_parts_mut(base as *mut u8, len) };
359
+ let fragments: Vec<process::FragmentStat> =
360
+ process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), buf)?;
361
+ wipe_key(&mut key);
362
+ Ok((fragments, result))
363
+ }).await.map_err(join_err)??;
364
+ check_strict(&fragments, guarded)?;
308
365
  Ok(Some(result))
309
366
  }
310
367
  }
@@ -3,7 +3,7 @@
3
3
 
4
4
  use std::borrow::Cow;
5
5
 
6
- use crate::boxes::{parse, write_header, Writer};
6
+ use crate::boxes::{parse, write_header, Box, Writer};
7
7
  use crate::Err;
8
8
 
9
9
  pub(crate) struct Cover<'a> {
@@ -145,8 +145,12 @@ fn hdlr_box() -> Vec<u8> {
145
145
  pub(crate) fn append_moov_with_meta(out: &mut Writer<'_>, children: &[u8], meta: &CoreMeta) -> Result<(), Err> {
146
146
  // every old udta goes — keeping any would both leak stale tags and shadow the
147
147
  // fresh subtree for the Windows handler (it reads only the first udta/meta)
148
- let udta: Vec<(usize, usize)> = parse(children, 0, children.len())
149
- .iter().filter(|c| c.is(b"udta")).map(|c| (c.start, c.end)).collect();
148
+ let top: Vec<Box> = parse(children, 0, children.len());
149
+ if top.len() >= crate::boxes::MAX_BOXES {
150
+ return Err(Err::InvalidMp4); // saturated parse: the udta map would be wrong
151
+ }
152
+ let udta: Vec<(usize, usize)> = top.iter().filter(|c| c.is(b"udta"))
153
+ .map(|c| (c.start, c.end)).collect();
150
154
 
151
155
  let mut ilst: Vec<u8> = Vec::new();
152
156
  build_items(&mut ilst, meta)?;