ziperu 0.2.3 → 0.3.1

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 (54) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +190 -0
  3. data/Cargo.lock +2 -1
  4. data/README.md +35 -7
  5. data/ext/ziperu/Cargo.toml +9 -1
  6. data/ext/ziperu/src/archive.rs +246 -144
  7. data/ext/ziperu/src/entry_options.rs +1 -1
  8. data/ext/ziperu/src/errors.rs +39 -11
  9. data/ext/ziperu/src/extract.rs +332 -104
  10. data/ext/ziperu/src/gvl.rs +45 -26
  11. data/ext/ziperu/src/lib.rs +17 -0
  12. data/ext/ziperu/src/place.rs +379 -0
  13. data/ext/ziperu/src/rb.rs +14 -1
  14. data/ext/ziperu/src/reader.rs +100 -29
  15. data/ext/ziperu/src/sink.rs +2 -7
  16. data/ext/ziperu/src/source.rs +4 -7
  17. data/ext/ziperu/src/stream.rs +89 -11
  18. data/ext/ziperu/src/test_rng.rs +37 -0
  19. data/ext/ziperu/src/writer.rs +71 -25
  20. data/ext/ziperu/src/zipcrypto.rs +40 -12
  21. data/lib/zip.rb +3 -3
  22. data/lib/ziperu/central_directory.rb +4 -8
  23. data/lib/ziperu/constants.rb +8 -0
  24. data/lib/ziperu/crypto.rb +10 -2
  25. data/lib/ziperu/dos_time.rb +1 -1
  26. data/lib/ziperu/entry/source.rb +41 -6
  27. data/lib/ziperu/entry.rb +252 -112
  28. data/lib/ziperu/entry_set.rb +0 -5
  29. data/lib/ziperu/errors.rb +4 -2
  30. data/lib/ziperu/extra_field/zip64.rb +1 -3
  31. data/lib/ziperu/extra_field.rb +10 -10
  32. data/lib/ziperu/file/commit.rb +255 -0
  33. data/lib/ziperu/file/extraction.rb +285 -0
  34. data/lib/ziperu/file.rb +77 -405
  35. data/lib/ziperu/file_split.rb +1 -3
  36. data/lib/ziperu/filesystem/dir.rb +3 -9
  37. data/lib/ziperu/filesystem/file.rb +2 -6
  38. data/lib/ziperu/filesystem/zip_file_name_mapper.rb +2 -2
  39. data/lib/ziperu/input_stream.rb +30 -32
  40. data/lib/ziperu/ioextras/abstract_input_stream.rb +83 -31
  41. data/lib/ziperu/ioextras/abstract_output_stream.rb +1 -3
  42. data/lib/ziperu/ioextras/fake_io.rb +1 -3
  43. data/lib/ziperu/ioextras.rb +6 -0
  44. data/lib/ziperu/limits.rb +48 -0
  45. data/lib/ziperu/null_input_stream.rb +1 -1
  46. data/lib/ziperu/output_stream.rb +118 -31
  47. data/lib/ziperu/pass_thru_decompressor.rb +1 -3
  48. data/lib/ziperu/rails_streaming.rb +5 -5
  49. data/lib/ziperu/remote_io.rb +181 -32
  50. data/lib/ziperu/size_estimator.rb +27 -19
  51. data/lib/ziperu/verify_report.rb +62 -0
  52. data/lib/ziperu/version.rb +2 -2
  53. data/lib/ziperu.rb +19 -17
  54. metadata +8 -1
@@ -10,17 +10,20 @@ use std::fs;
10
10
  use std::io::{self, Read};
11
11
 
12
12
  use magnus::{
13
- gc::Marker, typed_data::DataTypeFunctions, value::Opaque, Error, RArray, RHash, RString, Ruby,
14
- Symbol, TypedData, Value,
13
+ gc::Marker, prelude::*, typed_data::DataTypeFunctions, value::Opaque, Error, RArray, RHash,
14
+ RString, Ruby, Symbol, TypedData, Value,
15
15
  };
16
16
  use zip::read::{ZipFileEntry, ZipReadOptions};
17
17
  use zip::result::{ZipError, ZipResult};
18
18
  use zip::ZipArchive;
19
19
 
20
+ use crate::entry_options::extra_fields;
20
21
  use crate::errors::{busy_error, header_error, read_error, zip_read_error, IntoRuby};
21
22
  use crate::gvl::{maybe_without_gvl, Cancellable};
22
23
  use crate::rb::{bytes_of, read_into_string, size_believable};
23
- use crate::reader::{open_local_entry, EntryInfo, EntryReader};
24
+ use crate::reader::{
25
+ local_header_lens, open_local_entry, EntryInfo, EntryReader, LOCAL_HEADER_LEN,
26
+ };
24
27
  use crate::source::Source;
25
28
 
26
29
  /// Never pre-allocate more than this on the strength of a header field.
@@ -209,14 +212,7 @@ impl Archive {
209
212
  ) -> Result<(), Error> {
210
213
  let password = password.map(bytes_of);
211
214
  let mut source = rb_self.source(ruby)?;
212
- let info = EntryInfo {
213
- index: None,
214
- header_start: header_offset,
215
- size,
216
- compressed_size,
217
- crc32: crc,
218
- method: None,
219
- };
215
+ let info = EntryInfo::at_offset(header_offset, size, compressed_size, crc);
220
216
  maybe_without_gvl(rb_self.needs_gvl, || {
221
217
  let mut entry = open_local_entry(&mut source, &info, password.as_deref(), size)?;
222
218
  io::copy(&mut Cancellable(&mut entry), &mut io::sink())?;
@@ -235,7 +231,8 @@ impl Archive {
235
231
  /// record the crate still addresses carries its index, the others nil.
236
232
  pub fn entries(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
237
233
  let out = ruby.ary_new();
238
- Self::each_meta(ruby, rb_self, |h| out.push(h))?;
234
+ let keys = MetaKeys::new(ruby);
235
+ Self::each_meta(ruby, rb_self, |m| out.push(m.to_hash(ruby, &keys)?))?;
239
236
  Ok(out)
240
237
  }
241
238
 
@@ -243,16 +240,38 @@ impl Archive {
243
240
  /// listing need never be in memory all at once.
244
241
  pub fn each_entry(ruby: &Ruby, rb_self: &Self) -> Result<(), Error> {
245
242
  let block = ruby.block_proc()?;
246
- Self::each_meta(ruby, rb_self, |h| block.call::<_, Value>((h,)).map(|_| ()))
243
+ let keys = MetaKeys::new(ruby);
244
+ Self::each_meta(ruby, rb_self, |m| {
245
+ block
246
+ .call::<_, Value>((m.to_hash(ruby, &keys)?,))
247
+ .map(|_| ())
248
+ })
247
249
  }
248
250
 
249
- /// Hands the Hash for each entry, in central directory order, to
251
+ /// `each_entry` with a row Array for each entry instead of a Hash (see
252
+ /// `Meta::to_row`): opening an archive builds one `Entry` per record,
253
+ /// and a Hash of fifteen keys each costs more than the Entry.
254
+ pub fn each_entry_row(ruby: &Ruby, rb_self: &Self) -> Result<(), Error> {
255
+ if !ruby.block_given() {
256
+ return Err(Error::new(
257
+ ruby.exception_local_jump_error(),
258
+ "no block given",
259
+ ));
260
+ }
261
+ // A plain yield: no Proc made of the block, no Array of arguments
262
+ // built for every row.
263
+ Self::each_meta(ruby, rb_self, |m| {
264
+ ruby.yield_value::<_, Value>(m.to_row(ruby)?).map(|_| ())
265
+ })
266
+ }
267
+
268
+ /// Hands the facts of each entry, in central directory order, to
250
269
  /// `emit`. The archive is not borrowed while `emit` runs, so it may
251
270
  /// call back in.
252
271
  fn each_meta(
253
272
  ruby: &Ruby,
254
273
  rb_self: &Self,
255
- mut emit: impl FnMut(RHash) -> Result<(), Error>,
274
+ mut emit: impl FnMut(Meta<'_>) -> Result<(), Error>,
256
275
  ) -> Result<(), Error> {
257
276
  let archive = rb_self.archive(ruby)?;
258
277
  let meta = archive.metadata();
@@ -261,7 +280,6 @@ impl Archive {
261
280
  let archive_offset = archive.offset();
262
281
  let mut raw = archive.clone().into_inner();
263
282
  drop(archive);
264
- let keys = MetaKeys::new(ruby);
265
283
 
266
284
  if duplicates {
267
285
  let records = maybe_without_gvl(rb_self.needs_gvl, || {
@@ -275,7 +293,7 @@ impl Archive {
275
293
  }
276
294
  for record in &records {
277
295
  let index = by_offset.get(&record.central_offset).copied();
278
- emit(record_hash(ruby, &keys, index, record, archive_offset)?)?;
296
+ emit(Meta::from_record(index, record, archive_offset))?;
279
297
  }
280
298
  return Ok(());
281
299
  }
@@ -288,13 +306,10 @@ impl Archive {
288
306
  })
289
307
  .collect::<ZipResult<Vec<_>>>()
290
308
  })
291
- .map_err(|e| match e {
292
- ZipError::Io(e) => header_error(ruby, e),
293
- other => crate::errors::zip_error(ruby, other),
294
- })?;
309
+ .map_err(|e| zip_header_error(ruby, e))?;
295
310
  for (i, record) in records.iter().enumerate() {
296
311
  let entry = meta.entry(i).rb(ruby)?;
297
- emit(entry_hash(ruby, &keys, i, &entry, record)?)?;
312
+ emit(Meta::from_entry(i, &entry, record))?;
298
313
  }
299
314
  Ok(())
300
315
  }
@@ -308,7 +323,7 @@ impl Archive {
308
323
  let entry = meta.entry(index).rb(ruby)?;
309
324
  let record = raw_central_record(&mut raw, entry.central_header_start())
310
325
  .map_err(|e| header_error(ruby, e))?;
311
- entry_hash(ruby, &MetaKeys::new(ruby), index, &entry, &record)
326
+ Meta::from_entry(index, &entry, &record).to_hash(ruby, &MetaKeys::new(ruby))
312
327
  }
313
328
 
314
329
  /// The Hashes for up to `count` entries from `index` on, in one go:
@@ -331,7 +346,7 @@ impl Archive {
331
346
  let entry = meta.entry(i).rb(ruby)?;
332
347
  let record = raw_central_record(&mut raw, entry.central_header_start())
333
348
  .map_err(|e| header_error(ruby, e))?;
334
- out.push(entry_hash(ruby, &keys, i, &entry, &record)?)?;
349
+ out.push(Meta::from_entry(i, &entry, &record).to_hash(ruby, &keys)?)?;
335
350
  }
336
351
  Ok(out)
337
352
  }
@@ -348,6 +363,46 @@ impl Archive {
348
363
  Ok(ruby.str_from_slice(&extra))
349
364
  }
350
365
 
366
+ /// Which of the entries at `indices` carry, in their local header or
367
+ /// their central record, an extra field with one of the header IDs
368
+ /// `ids`: in one pass and without the GVL, rather than one
369
+ /// `local_extra` call per entry. A commit asks this of every entry it
370
+ /// would copy raw (see `Entry::RAW_COPY_LOSES`).
371
+ pub fn indices_with_extra_fields(
372
+ ruby: &Ruby,
373
+ rb_self: &Self,
374
+ indices: Vec<usize>,
375
+ ids: Vec<u16>,
376
+ ) -> Result<Vec<usize>, Error> {
377
+ let archive = rb_self.archive(ruby)?;
378
+ let meta = archive.metadata();
379
+ // One source for the central records (together, at the end) and
380
+ // another for the local headers (spread through the file): taking
381
+ // turns on one would throw its read buffer away at every seek.
382
+ let mut central_source = archive.clone().into_inner();
383
+ let mut local_source = small_source(&archive);
384
+ drop(archive);
385
+ maybe_without_gvl(rb_self.needs_gvl, || -> ZipResult<Vec<usize>> {
386
+ let mut found = Vec::new();
387
+ for index in indices {
388
+ crate::gvl::check()?;
389
+ let entry = meta.entry(index)?;
390
+ let central =
391
+ raw_central_record(&mut central_source, entry.central_header_start())?;
392
+ let hit = has_extra_field(&central.extra, &ids)
393
+ || has_extra_field(
394
+ &raw_local_extra(&mut local_source, entry.header_start())?,
395
+ &ids,
396
+ );
397
+ if hit {
398
+ found.push(index);
399
+ }
400
+ }
401
+ Ok(found)
402
+ })
403
+ .map_err(|e| zip_header_error(ruby, e))
404
+ }
405
+
351
406
  /// `local_extra` for a record addressed by its local header offset.
352
407
  pub fn local_extra_at(
353
408
  ruby: &Ruby,
@@ -398,14 +453,7 @@ impl Archive {
398
453
  ) -> Result<EntryReader, Error> {
399
454
  let password = password.map(bytes_of);
400
455
  let archive = rb_self.archive(ruby)?.clone();
401
- let info = EntryInfo {
402
- index: None,
403
- header_start: header_offset,
404
- size,
405
- compressed_size,
406
- crc32: crc,
407
- method: None,
408
- };
456
+ let info = EntryInfo::at_offset(header_offset, size, compressed_size, crc);
409
457
  EntryReader::open_at(
410
458
  ruby,
411
459
  archive,
@@ -436,7 +484,7 @@ impl Archive {
436
484
  .map_err(|e| read_error(ruby, e));
437
485
  }
438
486
  // A hint only: the declared size is untrusted and may be a lie.
439
- let mut buf = Vec::with_capacity(entry.size().min(CAPACITY_HINT_MAX) as usize);
487
+ let mut buf = Vec::with_capacity(size.min(CAPACITY_HINT_MAX) as usize);
440
488
  maybe_without_gvl(rb_self.needs_gvl, || {
441
489
  Cancellable(&mut entry).read_to_end(&mut buf)
442
490
  })
@@ -644,64 +692,58 @@ fn le_u32(bytes: &[u8]) -> u32 {
644
692
 
645
693
  /// The extra field bytes of a local file header, exactly as stored.
646
694
  fn raw_local_extra(source: &mut Source, header_offset: u64) -> io::Result<Vec<u8>> {
647
- const SIGNATURE: u32 = 0x0403_4b50;
648
- const HEADER_LEN: usize = 30;
649
-
650
- source.seek_to(header_offset)?;
651
- let mut header = [0u8; HEADER_LEN];
652
- source.read_exact(&mut header)?;
653
- if u32::from_le_bytes([header[0], header[1], header[2], header[3]]) != SIGNATURE {
654
- return Err(io::Error::new(
655
- io::ErrorKind::InvalidData,
656
- "local file header signature not found",
657
- ));
658
- }
659
- let name_len = u16::from_le_bytes([header[26], header[27]]) as u64;
660
- let extra_len = u16::from_le_bytes([header[28], header[29]]) as usize;
661
- source.seek_to(header_offset + HEADER_LEN as u64 + name_len)?;
662
- let mut extra = vec![0u8; extra_len];
695
+ let (name_len, extra_len) = local_header_lens(source, header_offset)?;
696
+ source.seek_to(header_offset + LOCAL_HEADER_LEN + name_len)?;
697
+ let mut extra = vec![0u8; extra_len as usize];
663
698
  source.read_exact(&mut extra)?;
664
699
  Ok(extra)
665
700
  }
666
701
 
667
- /// The Hash keys, interned once per listing rather than once per entry.
668
- struct MetaKeys {
669
- index: Symbol,
670
- name: Symbol,
671
- size: Symbol,
672
- compressed_size: Symbol,
673
- crc: Symbol,
674
- compression_method: Symbol,
675
- flags: Symbol,
676
- external_attributes: Symbol,
677
- fstype: Symbol,
678
- version_made_by: Symbol,
679
- dos_date: Symbol,
680
- dos_time: Symbol,
681
- comment: Symbol,
682
- extra: Symbol,
683
- header_offset: Symbol,
702
+ /// Whether the extra field block `extra` holds a field with one of the
703
+ /// header IDs `ids`.
704
+ fn has_extra_field(extra: &[u8], ids: &[u16]) -> bool {
705
+ extra_fields(extra).any(|(id, _)| ids.contains(&id))
684
706
  }
685
707
 
708
+ /// An error from reading the archive's headers through the crate.
709
+ fn zip_header_error(ruby: &Ruby, err: ZipError) -> Error {
710
+ match err {
711
+ ZipError::Io(e) => header_error(ruby, e),
712
+ other => crate::errors::zip_error(ruby, other),
713
+ }
714
+ }
715
+
716
+ /// The fields of an entry's facts, in row order: the Hash keys of
717
+ /// `to_hash` and the positions of `to_row`. `Native::Archive::ROW_FIELDS`
718
+ /// hands the list to Ruby, where `Entry::ROW_FIELDS` must equal it (a test
719
+ /// checks).
720
+ pub(crate) const ROW_FIELDS: [&str; ROW_LEN] = [
721
+ "index",
722
+ "name",
723
+ "size",
724
+ "compressed_size",
725
+ "crc",
726
+ "compression_method",
727
+ "flags",
728
+ "external_attributes",
729
+ "fstype",
730
+ "version_made_by",
731
+ "dos_date",
732
+ "dos_time",
733
+ "comment",
734
+ "extra",
735
+ "header_offset",
736
+ ];
737
+
738
+ /// The number of fields in a row.
739
+ const ROW_LEN: usize = 15;
740
+
741
+ /// The Hash keys, interned once per listing rather than once per entry.
742
+ struct MetaKeys([Symbol; ROW_LEN]);
743
+
686
744
  impl MetaKeys {
687
745
  fn new(ruby: &Ruby) -> Self {
688
- Self {
689
- index: ruby.to_symbol("index"),
690
- name: ruby.to_symbol("name"),
691
- size: ruby.to_symbol("size"),
692
- compressed_size: ruby.to_symbol("compressed_size"),
693
- crc: ruby.to_symbol("crc"),
694
- compression_method: ruby.to_symbol("compression_method"),
695
- flags: ruby.to_symbol("flags"),
696
- external_attributes: ruby.to_symbol("external_attributes"),
697
- fstype: ruby.to_symbol("fstype"),
698
- version_made_by: ruby.to_symbol("version_made_by"),
699
- dos_date: ruby.to_symbol("dos_date"),
700
- dos_time: ruby.to_symbol("dos_time"),
701
- comment: ruby.to_symbol("comment"),
702
- extra: ruby.to_symbol("extra"),
703
- header_offset: ruby.to_symbol("header_offset"),
704
- }
746
+ Self(ROW_FIELDS.map(|name| ruby.to_symbol(name)))
705
747
  }
706
748
  }
707
749
 
@@ -711,69 +753,129 @@ fn small_source(archive: &ZipArchive<Source>) -> Source {
711
753
  archive.clone().into_inner().clone_small()
712
754
  }
713
755
 
714
- fn entry_hash(
715
- ruby: &Ruby,
716
- keys: &MetaKeys,
717
- index: usize,
718
- entry: &ZipFileEntry<'_>,
719
- raw: &RawCentralRecord,
720
- ) -> Result<RHash, Error> {
721
- let h = ruby.hash_new();
722
- h.aset(keys.index, index)?;
723
- h.aset(keys.name, ruby.str_from_slice(entry.name_raw()))?;
724
- h.aset(keys.size, entry.size())?;
725
- h.aset(keys.compressed_size, entry.compressed_size())?;
726
- h.aset(keys.crc, entry.crc32())?;
727
- h.aset(
728
- keys.compression_method,
729
- compression_code(entry.compression()),
730
- )?;
731
- h.aset(keys.flags, entry.flags().as_u16())?;
732
- h.aset(keys.external_attributes, entry.external_attributes())?;
733
- // "Version made by": high byte is the host system, low byte the spec
734
- // version; rubyzip keeps them as fstype / version.
735
- h.aset(keys.fstype, u8::from(entry.system()))?;
736
- let (major, minor) = entry.version_made_by();
737
- h.aset(keys.version_made_by, major * 10 + minor)?;
738
- h.aset(keys.dos_date, raw.dos_date)?;
739
- h.aset(keys.dos_time, raw.dos_time)?;
740
- // The stored bytes: the crate's `comment()` has already decoded them
741
- // (as CP437 without the UTF-8 flag), which is Ruby's decision to make.
742
- h.aset(keys.comment, ruby.str_from_slice(&raw.comment))?;
743
- h.aset(keys.extra, ruby.str_from_slice(&raw.extra))?;
744
- h.aset(keys.header_offset, entry.header_start())?;
745
- Ok(h)
756
+ /// One entry's facts as Ruby gets them: a Hash (`to_hash`) or a row Array
757
+ /// (`to_row`), both laid out by `ROW_FIELDS`.
758
+ struct Meta<'a> {
759
+ /// The crate's index, or `None` for a record it dropped (one of
760
+ /// several under the same name).
761
+ index: Option<usize>,
762
+ name: &'a [u8],
763
+ size: u64,
764
+ compressed_size: u64,
765
+ crc: u32,
766
+ method: u16,
767
+ flags: u16,
768
+ external_attributes: u32,
769
+ fstype: u8,
770
+ version_made_by: u16,
771
+ dos_date: u16,
772
+ dos_time: u16,
773
+ comment: &'a [u8],
774
+ extra: &'a [u8],
775
+ header_offset: u64,
746
776
  }
747
777
 
748
- /// `entry_hash` from the raw record alone, for an archive the crate's
749
- /// parsed view does not cover; `index` is nil for a record it dropped.
750
- fn record_hash(
751
- ruby: &Ruby,
752
- keys: &MetaKeys,
753
- index: Option<usize>,
754
- record: &RawCentralRecord,
755
- archive_offset: u64,
756
- ) -> Result<RHash, Error> {
757
- let h = ruby.hash_new();
758
- h.aset(keys.index, index)?;
759
- h.aset(keys.name, ruby.str_from_slice(&record.name))?;
760
- h.aset(keys.size, record.size)?;
761
- h.aset(keys.compressed_size, record.compressed_size)?;
762
- h.aset(keys.crc, record.crc32)?;
763
- h.aset(keys.compression_method, record.method)?;
764
- h.aset(keys.flags, record.flags)?;
765
- h.aset(keys.external_attributes, record.external_attributes)?;
766
- h.aset(keys.fstype, (record.version_made_by >> 8) as u8)?;
767
- h.aset(keys.version_made_by, record.version_made_by & 0xFF)?;
768
- h.aset(keys.dos_date, record.dos_date)?;
769
- h.aset(keys.dos_time, record.dos_time)?;
770
- h.aset(keys.comment, ruby.str_from_slice(&record.comment))?;
771
- h.aset(keys.extra, ruby.str_from_slice(&record.extra))?;
772
- h.aset(
773
- keys.header_offset,
774
- record.header_offset.saturating_add(archive_offset),
775
- )?;
776
- Ok(h)
778
+ impl<'a> Meta<'a> {
779
+ /// From the crate's parsed record and the raw one beside it.
780
+ fn from_entry(index: usize, entry: &'a ZipFileEntry<'_>, raw: &'a RawCentralRecord) -> Self {
781
+ // "Version made by": high byte is the host system, low byte the
782
+ // spec version; rubyzip keeps them as fstype / version.
783
+ let (major, minor) = entry.version_made_by();
784
+ Self {
785
+ index: Some(index),
786
+ name: entry.name_raw(),
787
+ size: entry.size(),
788
+ compressed_size: entry.compressed_size(),
789
+ crc: entry.crc32(),
790
+ method: compression_code(entry.compression()),
791
+ flags: entry.flags().as_u16(),
792
+ external_attributes: entry.external_attributes(),
793
+ fstype: u8::from(entry.system()),
794
+ version_made_by: u16::from(major) * 10 + u16::from(minor),
795
+ dos_date: raw.dos_date,
796
+ dos_time: raw.dos_time,
797
+ // The stored bytes: the crate's `comment()` has already decoded
798
+ // them (as CP437 without the UTF-8 flag), which is Ruby's
799
+ // decision to make.
800
+ comment: &raw.comment,
801
+ extra: &raw.extra,
802
+ header_offset: entry.header_start(),
803
+ }
804
+ }
805
+
806
+ /// From the raw record alone, for an archive the crate's parsed view
807
+ /// does not cover; `index` is `None` for a record it dropped.
808
+ fn from_record(
809
+ index: Option<usize>,
810
+ record: &'a RawCentralRecord,
811
+ archive_offset: u64,
812
+ ) -> Self {
813
+ Self {
814
+ index,
815
+ name: &record.name,
816
+ size: record.size,
817
+ compressed_size: record.compressed_size,
818
+ crc: record.crc32,
819
+ method: record.method,
820
+ flags: record.flags,
821
+ external_attributes: record.external_attributes,
822
+ fstype: (record.version_made_by >> 8) as u8,
823
+ version_made_by: record.version_made_by & 0xFF,
824
+ dos_date: record.dos_date,
825
+ dos_time: record.dos_time,
826
+ comment: &record.comment,
827
+ extra: &record.extra,
828
+ header_offset: record.header_offset.saturating_add(archive_offset),
829
+ }
830
+ }
831
+
832
+ /// The fields, in `ROW_FIELDS` order. With `empty_as_nil` an empty
833
+ /// comment or extra field is nil rather than a String of its own.
834
+ fn values(&self, ruby: &Ruby, empty_as_nil: bool) -> [Value; ROW_LEN] {
835
+ let bytes = |b: &[u8]| {
836
+ if empty_as_nil && b.is_empty() {
837
+ ruby.qnil().as_value()
838
+ } else {
839
+ ruby.str_from_slice(b).as_value()
840
+ }
841
+ };
842
+ [
843
+ ruby.into_value(self.index),
844
+ ruby.str_from_slice(self.name).as_value(),
845
+ ruby.into_value(self.size),
846
+ ruby.into_value(self.compressed_size),
847
+ ruby.into_value(self.crc),
848
+ ruby.into_value(self.method),
849
+ ruby.into_value(self.flags),
850
+ ruby.into_value(self.external_attributes),
851
+ ruby.into_value(self.fstype),
852
+ ruby.into_value(self.version_made_by),
853
+ ruby.into_value(self.dos_date),
854
+ ruby.into_value(self.dos_time),
855
+ bytes(self.comment),
856
+ bytes(self.extra),
857
+ ruby.into_value(self.header_offset),
858
+ ]
859
+ }
860
+
861
+ /// The fields as a Hash keyed by `ROW_FIELDS`.
862
+ fn to_hash(&self, ruby: &Ruby, keys: &MetaKeys) -> Result<RHash, Error> {
863
+ let h = ruby.hash_new();
864
+ for (key, value) in keys.0.iter().zip(self.values(ruby, false)) {
865
+ h.aset(*key, value)?;
866
+ }
867
+ Ok(h)
868
+ }
869
+
870
+ /// The same fields as one Array, in `ROW_FIELDS` order, an empty
871
+ /// comment or extra field nil.
872
+ fn to_row(&self, ruby: &Ruby) -> Result<RArray, Error> {
873
+ let row = ruby.ary_new_capa(ROW_LEN);
874
+ for value in self.values(ruby, true) {
875
+ row.push(value)?;
876
+ }
877
+ Ok(row)
878
+ }
777
879
  }
778
880
 
779
881
  /// The on-disk compression method code, as rubyzip exposes it.
@@ -153,7 +153,7 @@ impl EntryOptions {
153
153
  }
154
154
 
155
155
  /// Walks concatenated extra fields (id, length, data) as `(id, data)`.
156
- fn extra_fields(bytes: &[u8]) -> impl Iterator<Item = (u16, &[u8])> {
156
+ pub(crate) fn extra_fields(bytes: &[u8]) -> impl Iterator<Item = (u16, &[u8])> {
157
157
  let mut i = 0;
158
158
  std::iter::from_fn(move || {
159
159
  if i + 4 > bytes.len() {
@@ -95,6 +95,17 @@ pub fn zip_error(ruby: &Ruby, err: ZipError) -> Error {
95
95
  fn invalid_archive_message(msg: &str) -> String {
96
96
  if msg.contains("EOCD") {
97
97
  "Zip end of central directory signature not found".to_string()
98
+ } else if let Some(block) = msg.strip_prefix("Unexpected end of ") {
99
+ // The crate names the Rust type it was reading.
100
+ let what = match block.rsplit("::").next().unwrap_or(block) {
101
+ "Zip32CDEBlock" => "the end of central directory record",
102
+ "Zip64CDEBlock" => "the zip64 end of central directory record",
103
+ "Zip64CDELocatorBlock" => "the zip64 end of central directory locator",
104
+ "ZipCentralEntryBlock" => "a central directory entry",
105
+ "ZipLocalEntryBlock" => "a local file header",
106
+ _ => "a record",
107
+ };
108
+ format!("invalid Zip archive: {what} is cut short")
98
109
  } else {
99
110
  // Some of the crate's messages carry a placeholder it never fills.
100
111
  msg.replace(" of {properties_size}", "")
@@ -226,21 +237,12 @@ pub fn read_error(ruby: &Ruby, err: io::Error) -> Error {
226
237
  /// Interrupt, the exception of a `Thread#raise`), which is what the
227
238
  /// caller should see. Should there be none, a plain `Ziperu::Error`.
228
239
  pub fn interrupted(ruby: &Ruby) -> Error {
229
- use magnus::rb_sys::AsRawValue;
230
240
  if let Some(raised) = crate::gvl::take_raised() {
231
241
  return raised;
232
242
  }
233
- let nil = ruby.qnil().as_raw();
234
- // SAFETY: called with the GVL held; `protect` turns the exception that
235
- // `rb_thread_check_ints` raises into an `Err` rather than a longjmp
236
- // through Rust frames.
237
- let pending = magnus::rb_sys::protect(|| {
238
- unsafe { rb_sys::rb_thread_check_ints() };
239
- nil
240
- });
241
- match pending {
243
+ match crate::gvl::check_ints(ruby) {
242
244
  Err(e) => e,
243
- Ok(_) => Error::new(ruby.get_inner(&ERROR), "interrupted"),
245
+ Ok(()) => Error::new(ruby.get_inner(&ERROR), "interrupted"),
244
246
  }
245
247
  }
246
248
 
@@ -263,3 +265,29 @@ fn decompression_error(ruby: &Ruby, msg: &str) -> Error {
263
265
  Err(e) => e,
264
266
  }
265
267
  }
268
+
269
+ #[cfg(test)]
270
+ mod tests {
271
+ use super::invalid_archive_message;
272
+
273
+ #[test]
274
+ fn no_rust_type_names_in_messages() {
275
+ for block in [
276
+ "Zip32CDEBlock",
277
+ "Zip64CDEBlock",
278
+ "Zip64CDELocatorBlock",
279
+ "ZipCentralEntryBlock",
280
+ "ZipLocalEntryBlock",
281
+ "SomethingNew",
282
+ ] {
283
+ let said =
284
+ invalid_archive_message(&format!("Unexpected end of zip::format::blocks::{block}"));
285
+ assert!(said.ends_with("is cut short"), "{said}");
286
+ assert!(!said.contains("::") && !said.contains("Block"), "{said}");
287
+ }
288
+ assert_eq!(
289
+ invalid_archive_message("Unexpected end of zip::format::blocks::Zip32CDEBlock"),
290
+ "invalid Zip archive: the end of central directory record is cut short"
291
+ );
292
+ }
293
+ }