decryptune 1.1.1__tar.gz → 1.1.2__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.
@@ -68,7 +68,7 @@ dependencies = [
68
68
 
69
69
  [[package]]
70
70
  name = "decryptune"
71
- version = "1.1.1"
71
+ version = "1.1.2"
72
72
  dependencies = [
73
73
  "aes",
74
74
  "ctr",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "decryptune"
3
- version = "1.1.1"
3
+ version = "1.1.2"
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.1
3
+ Version: 1.1.2
4
4
  Classifier: Development Status :: 5 - Production/Stable
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: Programming Language :: Rust
@@ -16,7 +16,7 @@ from importlib.machinery import ModuleSpec
16
16
  from importlib.util import module_from_spec, spec_from_file_location
17
17
  from types import ModuleType
18
18
 
19
- __version__ = "1.1.1"
19
+ __version__ = "1.1.2"
20
20
  __all__ = ["DecrypTune", "DecrypTuneError", "TuneMeta", "__version__"]
21
21
 
22
22
 
@@ -8,7 +8,7 @@ tree. Keep this file in sync with it (same API surface, loader differs).
8
8
 
9
9
  from . import decryptune as _native
10
10
 
11
- __version__ = "1.1.1"
11
+ __version__ = "1.1.2"
12
12
  __all__ = ["DecrypTune", "DecrypTuneError", "TuneMeta", "__version__"]
13
13
 
14
14
 
@@ -330,6 +330,15 @@ fn proc<'py>(
330
330
  Ok(result.map(|bytes| PyBytes::new(py, &bytes).into_any()))
331
331
  }
332
332
 
333
+ // a worker panic must surface with its real message, not a fake error
334
+ fn join_err(join: tokio::task::JoinError) -> PyErr {
335
+ let msg: String = join.try_into_panic().ok()
336
+ .and_then(|p| p.downcast_ref::<&str>().map(|s| s.to_string())
337
+ .or_else(|| p.downcast_ref::<String>().cloned()))
338
+ .unwrap_or_else(|| "internal worker panic".into());
339
+ PyException::new_err(msg)
340
+ }
341
+
333
342
  // async twin of proc: native coroutine, CPU work off-GIL, async file writes
334
343
  #[pyfunction]
335
344
  #[pyo3(signature = (*, input, out=None, key=None, kid=None, meta=None, strict=false))]
@@ -351,24 +360,16 @@ fn aproc<'py>(
351
360
  pyo3_async_runtimes::tokio::future_into_py(py, async move {
352
361
  let processed: process::Processed = tokio::task::spawn_blocking(move || run(input, key, kid, core_meta, strict))
353
362
  .await
354
- .map_err(|join| {
355
- // a worker panic must surface with its real message, not a fake write error
356
- let msg = join.try_into_panic().ok()
357
- .and_then(|p| p.downcast_ref::<&str>().map(|s| s.to_string())
358
- .or_else(|| p.downcast_ref::<String>().cloned()))
359
- .unwrap_or_else(|| "internal worker panic".into());
360
- PyException::new_err(msg)
361
- })??;
363
+ .map_err(join_err)??;
362
364
  check_strict(&processed, key, strict)?;
363
365
  match output {
364
- // true async write — std::fs here would block a runtime worker
366
+ // write+rename run as ONE blocking task — a cancelled future cannot
367
+ // split the pair and leave a tmp behind (tokio::fs is spawn_blocking
368
+ // under the hood anyway, so this frees the worker just as well)
365
369
  Output::Path(p) => {
366
- let tmp: String = tmp_path(&p);
367
- tokio::fs::write(&tmp, &processed.data).await.map_err(|_| Err::WriteFailed)?;
368
- if tokio::fs::rename(&tmp, &p).await.is_err() {
369
- let _ = tokio::fs::remove_file(&tmp).await; // no tmp litter on a failed rename
370
- return Err(Err::WriteFailed.into());
371
- }
370
+ tokio::task::spawn_blocking(move || write_atomic(&p, &processed.data))
371
+ .await
372
+ .map_err(join_err)??;
372
373
  Ok(None)
373
374
  }
374
375
  Output::Return => Ok(Some(processed.data))
@@ -114,10 +114,10 @@ fn visit_moof(out: &mut Vec<u8>, data: &[u8], b: &Box) -> Plan {
114
114
 
115
115
  // gather: tfhd default first so trun fallback works in any order
116
116
  default_size = traf.iter().find(|t| t.is(b"tfhd"))
117
- .and_then(|t| parse_tfhd(data, t.content_start));
117
+ .and_then(|t| parse_tfhd(data, t.content_start, t.end));
118
118
  for t in &traf {
119
119
  match &t.typ {
120
- b"senc" if ivs.is_none() => ivs = parse_senc(data, t.content_start),
120
+ b"senc" if ivs.is_none() => ivs = parse_senc(data, t.content_start, t.end),
121
121
  b"trun" => sizes.extend(parse_trun_sizes(data, t.content_start, t.end, default_size)),
122
122
  _ => {}
123
123
  }
@@ -169,7 +169,15 @@ fn emit_mdat(
169
169
  plan : &Plan,
170
170
  strict : bool
171
171
  ) -> FragmentStat {
172
- write_header(out, b"mdat", m.end - m.content_start);
172
+ // a largesize (64-bit) mdat keeps its 64-bit header — a u32 rewrite would wrap
173
+ let content_len: usize = m.end - m.content_start;
174
+ if content_len + 8 > u32::MAX as usize || u32::from_be_bytes(data[m.start..m.start + 4].try_into().unwrap()) == 1 {
175
+ out.extend_from_slice(&1u32.to_be_bytes());
176
+ out.extend_from_slice(b"mdat");
177
+ out.extend_from_slice(&((content_len as u64) + 16).to_be_bytes());
178
+ } else {
179
+ write_header(out, b"mdat", content_len);
180
+ }
173
181
  let base: usize = out.len();
174
182
  out.extend_from_slice(&data[m.content_start..m.end]);
175
183
  let encrypted: bool = plan.ok;
@@ -211,34 +219,35 @@ fn has_chunk_offsets(children: &[u8], depth: usize) -> bool {
211
219
  false
212
220
  }
213
221
 
214
- // default_sample_size from tfhd (flag 0x10), honoring preceding optional fields
215
- fn parse_tfhd(data: &[u8], start: usize) -> Option<u32> {
216
- if start + 8 > data.len() { return None; }
222
+ // default_sample_size from tfhd (flag 0x10), honoring preceding optional fields;
223
+ // every read stays inside the tfhd box — never spills into a sibling box
224
+ fn parse_tfhd(data: &[u8], start: usize, end: usize) -> Option<u32> {
225
+ if start + 8 > end { return None; }
217
226
  let flags: u32 = u32::from_be_bytes(data[start..start + 4].try_into().ok()?) & 0xFFFFFF;
218
227
  let mut pos: usize = start + 8; // version/flags + track_ID
219
228
  if flags & 0x1 != 0 { pos += 8; } // base_data_offset
220
229
  if flags & 0x2 != 0 { pos += 4; } // sample_description_index
221
230
  if flags & 0x8 != 0 { pos += 4; } // default_sample_duration
222
- if flags & 0x10 == 0 || pos + 4 > data.len() { return None; }
231
+ if flags & 0x10 == 0 || pos + 4 > end { return None; }
223
232
  Some(u32::from_be_bytes(data[pos..pos + 4].try_into().ok()?))
224
233
  }
225
234
 
226
235
  // IVs from senc; subsample entries (flag 0x2) are parsed over for IV alignment,
227
- // not applied — samples are fully encrypted
228
- fn parse_senc(data: &[u8], start: usize) -> Option<Vec<[u8; 16]>> {
229
- if start + 8 > data.len() { return None; }
236
+ // not applied — samples are fully encrypted; bounded by the box end, not the file
237
+ fn parse_senc(data: &[u8], start: usize, end: usize) -> Option<Vec<[u8; 16]>> {
238
+ if start + 8 > end { return None; }
230
239
  let flags: u32 = u32::from_be_bytes(data[start..start + 4].try_into().ok()?) & 0xFFFFFF;
231
240
  let count: usize = u32::from_be_bytes(data[start + 4..start + 8].try_into().ok()?) as usize;
232
- if count > (data.len() - start - 8) / 8 { return None; } // hostile count bound
241
+ if count > (end - start - 8) / 8 { return None; } // hostile count bound
233
242
  let mut pos: usize = start + 8;
234
243
  let mut ivs: Vec<[u8; 16]> = Vec::with_capacity(count);
235
244
  for _ in 0..count {
236
- if pos + 8 > data.len() { return None; }
245
+ if pos + 8 > end { return None; }
237
246
  let mut iv: [u8; 16] = [0u8; 16];
238
247
  iv[..8].copy_from_slice(&data[pos..pos + 8]);
239
248
  pos += 8;
240
249
  if flags & 0x2 != 0 {
241
- if pos + 2 > data.len() { return None; }
250
+ if pos + 2 > end { return None; }
242
251
  let sub: usize = u16::from_be_bytes(data[pos..pos + 2].try_into().ok()?) as usize;
243
252
  pos += 2 + sub * 6;
244
253
  }
@@ -532,6 +532,60 @@ def test_hostile_truncated_sidx(sp, version, content_len):
532
532
  assert isinstance(sp.proc(input=hostile), bytes)
533
533
 
534
534
 
535
+ def test_mdat_largesize_preserved(sp, sample):
536
+ # a 64-bit (largesize) mdat must keep its 64-bit header — a u32 rewrite wraps
537
+ data, expected = sample
538
+ m = find(data, b"mdat")[0]
539
+ content = data[m[1] + 8:m[1] + m[2]]
540
+ large = data[:m[1]] + u32(1) + b"mdat" + struct.pack(">Q", len(content) + 16) + content + data[m[1] + m[2]:]
541
+ out = sp.proc(input=large, key=KEY_HEX)
542
+ pos = out.find(b"mdat") # type word; size field sits right before it
543
+ (size_field,) = struct.unpack_from(">I", out, pos - 4)
544
+ (size64,) = struct.unpack_from(">Q", out, pos + 4)
545
+ assert size_field == 1 and size64 == len(content) + 16
546
+ assert out[pos + 12:pos - 4 + size64] == b"".join(expected[1])
547
+
548
+
549
+ def test_senc_bounded_to_box(sp):
550
+ # senc declares 2 IVs but its box ends before them — the parser must not
551
+ # borrow bytes from the following mdat (would decrypt with garbage IVs
552
+ # and falsely fail strict); instead the fragment counts as partially plain
553
+ enc = ctr_crypt(KEY, bytes(8), bytes([0x5A]) * 40000)
554
+ moof = make_moof(1, [make_tfhd(), make_trun([20000, 20000], 0),
555
+ full_box(b"senc", 0, 0, u32(2))])
556
+ hostile = box(b"ftyp", b"M4A isom") + moof + box(b"mdat", enc) + make_moov()
557
+ out = sp.proc(input=hostile, key=KEY_HEX, strict=True) # must NOT raise code 8
558
+ m = find(out, b"mdat")[0]
559
+ assert out[m[1] + 8:m[1] + m[2]] == enc # untouched passthrough
560
+
561
+
562
+ def test_tfhd_truncated_no_readthrough(sp):
563
+ # tfhd claims the default-size flag but its box ends first — no panic,
564
+ # a coded outcome only (samples fall back to size 0 → undecrypted pass)
565
+ tfhd = full_box(b"tfhd", 0, 0x10, u32(1))
566
+ moof = make_moof(1, [tfhd, make_trun([100] * 4, 0, with_sizes=False),
567
+ make_senc([bytes(8)] * 4)])
568
+ hostile = box(b"ftyp", b"M4A isom") + moof + box(b"mdat", bytes(400))
569
+ try:
570
+ assert isinstance(sp.proc(input=hostile, key=KEY_HEX, strict=True), bytes)
571
+ except DecrypTuneError as e:
572
+ assert e.code in (4, 8)
573
+
574
+
575
+ def test_aproc_cancel_no_tmp_litter(sp, src_file, tmp_path):
576
+ # futures cancelled anywhere in the write path must never leave *.tmp behind
577
+ async def main():
578
+ tasks = [asyncio.create_task(sp.aproc(input=src_file, out=str(tmp_path / f"c{i}.m4a"), key=KEY_HEX))
579
+ for i in range(64)]
580
+ await asyncio.sleep(0.002)
581
+ for t in tasks:
582
+ t.cancel()
583
+ await asyncio.gather(*tasks, return_exceptions=True)
584
+
585
+ asyncio.run(main())
586
+ assert list(tmp_path.glob("*.tmp")) == []
587
+
588
+
535
589
  # ---- metadata ---------------------------------------------------------------
536
590
 
537
591
  def test_udta_first(sp, tagged):
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes