ziperu 0.3.1 → 0.4.0

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.
@@ -2,113 +2,28 @@
2
2
  //!
3
3
  //! Ruby decides which entries qualify (no overwrite decision to make, no
4
4
  //! encryption, no symlinks, no ownership to restore) and hands over one
5
- //! spec per entry; this side creates each parent directory once, writes
6
- //! every file through a single handle and stamps times and permissions on
7
- //! that handle, all with the GVL released when the source allows it.
8
- //!
9
- //! The path check is the one `Entry#extract` makes, re-done here on the
10
- //! same terms: the entry name is joined onto the absolute destination and
11
- //! normalised lexically (as `File.absolute_path` does), and the result must
12
- //! start with the destination plus a separator. Nothing is created for an
13
- //! entry that fails it; Ruby prints the same warning it would have.
14
- //!
15
- //! Below the destination nothing is followed through a link already on
16
- //! disk (a symlink, or on Windows a junction): every directory on the way
17
- //! to an entry, and the entry's own path, must be a real directory or
18
- //! file, or the entry is skipped with a warning. The destination itself is
19
- //! taken as given, link or not. This is checked before each path is used;
20
- //! on Linux, `place.rs` also opens each file's directory beneath the
21
- //! destination so that the kernel refuses a link swapped in meanwhile.
5
+ //! spec per entry; this side reads each entry out of the archive, with
6
+ //! the GVL released when the source allows it. Where an entry goes, and
7
+ //! what is refused on the way there, is `placer.rs`.
22
8
 
23
- use std::collections::HashSet;
24
- use std::fs::{self, FileTimes};
9
+ use std::fs;
25
10
  use std::io::{self, Read, Write};
26
- use std::path::{Path, PathBuf};
27
11
  use std::sync::atomic::{AtomicBool, Ordering};
28
12
  use std::time::{Duration, SystemTime};
29
13
 
30
14
  use magnus::{
31
15
  prelude::*, value::Lazy, Error, ExceptionClass, RArray, RString, Ruby, Symbol, Value,
32
16
  };
33
- use zip::result::ZipError;
34
17
  use zip::ZipArchive;
35
18
 
36
19
  use crate::errors::{io_error, read_error, zip_error, DESTINATION_EXISTS_ERROR, ENTRY_SIZE_ERROR};
37
20
  use crate::gvl::maybe_without_gvl;
38
- use crate::place::{is_link_error, Beneath};
21
+ use crate::placer::{Failure, Notice, OnExists, Placer, Spec};
39
22
  use crate::reader::{open_local_entry, EntryInfo};
40
23
  use crate::source::Source;
41
24
 
42
25
  const CHUNK: usize = 64 * 1024;
43
26
 
44
- /// One entry to extract, as Ruby describes it:
45
- /// `[entry, index, name, mtime_sec, mtime_nsec, mode, directory?]`.
46
- struct Spec {
47
- index: usize,
48
- name: String,
49
- /// `None` when times are not restored.
50
- mtime: Option<SystemTime>,
51
- /// Unix mode to apply, already masked by Ruby; `None` to leave alone.
52
- mode: Option<u32>,
53
- directory: bool,
54
- }
55
-
56
- /// Why an entry could not be extracted; turned into a Ruby exception once
57
- /// the GVL is held again.
58
- enum Failure {
59
- Exists(String),
60
- SizeLimit,
61
- Zip(ZipError),
62
- /// Reading the entry failed.
63
- Io(io::Error),
64
- /// Creating or writing `path` failed: raised as the matching `Errno`
65
- /// with the path in the message, as Ruby's own File calls do.
66
- IoAt(String, io::Error),
67
- }
68
-
69
- /// Attaches `path` to an IO error from a filesystem call on it.
70
- fn at(path: &Path) -> impl Fn(io::Error) -> Failure + '_ {
71
- move |e| Failure::IoAt(path_string(path), e)
72
- }
73
-
74
- impl From<ZipError> for Failure {
75
- fn from(e: ZipError) -> Self {
76
- match e {
77
- ZipError::DecompressedSizeLimitExceeded { .. } => Failure::SizeLimit,
78
- other => Failure::Zip(other),
79
- }
80
- }
81
- }
82
-
83
- impl From<io::Error> for Failure {
84
- fn from(e: io::Error) -> Self {
85
- // The crate reports a header that understates the size either as
86
- // its own error behind an io::Error, or (crc32.rs) as plain
87
- // InvalidData with a message.
88
- let limit = e
89
- .get_ref()
90
- .and_then(|inner| inner.downcast_ref::<ZipError>())
91
- .is_some_and(|z| matches!(z, ZipError::DecompressedSizeLimitExceeded { .. }))
92
- || crate::errors::is_size_limit(&e);
93
- if limit {
94
- Failure::SizeLimit
95
- } else {
96
- Failure::Io(e)
97
- }
98
- }
99
- }
100
-
101
- /// Something Ruby should warn about afterwards.
102
- enum Notice {
103
- /// The entry resolved outside the destination; nothing was written.
104
- Unsafe(String),
105
- /// A link on disk stands at this path on the way to the entry, or at
106
- /// the entry's own path; nothing was written.
107
- Link(String),
108
- /// Without size enforcement, more bytes came out than declared.
109
- Oversize,
110
- }
111
-
112
27
  /// How an extraction is to be done, as Ruby asks for it.
113
28
  pub struct Options {
114
29
  pub enforce_size: bool,
@@ -228,28 +143,22 @@ fn extract_all(
228
143
  let (dirs, files): (Vec<_>, Vec<_>) = specs.iter().enumerate().partition(|(_, s)| s.directory);
229
144
  let mut extractor = Extractor::new(archive, dest, enforce_size, on_exists);
230
145
  extractor.extract_each(&dirs)?;
231
- let outcome = extract_files(&mut extractor, dest, &files, threads);
146
+ let outcome = extract_files(&mut extractor, &files, threads);
232
147
  // A directory's times go on once nothing more is written into it:
233
148
  // creating a file inside would move its mtime again.
234
- let stamped = extractor.stamp_directories();
149
+ let stamped = extractor.placer.stamp_directories();
235
150
  let mut notices = outcome?;
236
151
  stamped?;
237
- notices.append(&mut extractor.notices);
152
+ notices.extend(extractor.placer.take_notices());
238
153
  Ok(notices)
239
154
  }
240
155
 
241
156
  /// The files of `extract_all`: in order on this thread, or shared out
242
157
  /// among `threads`.
243
- fn extract_files(
244
- extractor: &mut Extractor<'_>,
245
- dest: &str,
246
- files: &[(usize, &Spec)],
247
- threads: usize,
248
- ) -> Outcome {
249
- let (enforce_size, on_exists) = (extractor.enforce_size, extractor.on_exists);
158
+ fn extract_files(extractor: &mut Extractor, files: &[(usize, &Spec)], threads: usize) -> Outcome {
250
159
  if threads <= 1 || files.len() <= 1 {
251
160
  extractor.extract_each(files)?;
252
- return Ok(std::mem::take(&mut extractor.notices));
161
+ return Ok(extractor.placer.take_notices());
253
162
  }
254
163
 
255
164
  // Each thread takes every `threads`th file, so a run of large ones
@@ -264,9 +173,7 @@ fn extract_files(
264
173
  let results: Vec<Outcome> = std::thread::scope(|scope| {
265
174
  let workers: Vec<_> = (0..threads)
266
175
  .map(|t| {
267
- let mut worker =
268
- Extractor::new(extractor.archive.clone(), dest, enforce_size, on_exists);
269
- worker.made.clone_from(&extractor.made);
176
+ let mut worker = extractor.worker();
270
177
  let failed = &failed;
271
178
  let token = token.clone();
272
179
  scope.spawn(move || {
@@ -280,7 +187,7 @@ fn extract_files(
280
187
  return Err((i, f));
281
188
  }
282
189
  }
283
- Ok(worker.notices)
190
+ Ok(worker.placer.take_notices())
284
191
  })
285
192
  })
286
193
  })
@@ -293,7 +200,7 @@ fn extract_files(
293
200
  })
294
201
  .collect()
295
202
  });
296
- let mut notices = std::mem::take(&mut extractor.notices);
203
+ let mut notices = extractor.placer.take_notices();
297
204
  let mut first_failure: Option<(usize, Failure)> = None;
298
205
  for result in results {
299
206
  match result {
@@ -310,7 +217,7 @@ fn extract_files(
310
217
  }
311
218
  }
312
219
 
313
- fn system_time(sec: i64, nsec: u32) -> Option<SystemTime> {
220
+ pub(crate) fn system_time(sec: i64, nsec: u32) -> Option<SystemTime> {
314
221
  let nanos = Duration::from_nanos(u64::from(nsec));
315
222
  let base = match u64::try_from(sec) {
316
223
  Ok(s) => SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(s)),
@@ -319,7 +226,7 @@ fn system_time(sec: i64, nsec: u32) -> Option<SystemTime> {
319
226
  base?.checked_add(nanos)
320
227
  }
321
228
 
322
- fn raise(ruby: &Ruby, entry: Value, failure: Failure) -> Error {
229
+ pub(crate) fn raise(ruby: &Ruby, entry: Value, failure: Failure) -> Error {
323
230
  match failure {
324
231
  Failure::Exists(path) => exception(ruby, &DESTINATION_EXISTS_ERROR, (path,)),
325
232
  Failure::SizeLimit => exception(ruby, &ENTRY_SIZE_ERROR, (entry,)),
@@ -342,85 +249,38 @@ fn exception<A: magnus::ArgList>(ruby: &Ruby, class: &Lazy<ExceptionClass>, args
342
249
  }
343
250
  }
344
251
 
345
- /// What to do about a file or directory already at an entry's path.
346
- #[derive(Clone, Copy)]
347
- enum OnExists {
348
- Raise,
349
- Overwrite,
350
- Skip,
351
- }
352
-
353
- /// What stands at a path, looked at without following a link there.
354
- enum OnDisk {
355
- Missing,
356
- Directory,
357
- /// A symlink, or on Windows a junction or other name-surrogate
358
- /// reparse point (what `FileType::is_symlink` counts).
359
- Link,
360
- /// A file, or anything else that is neither a directory nor a link.
361
- Other,
362
- }
363
-
364
- fn on_disk(path: &Path) -> io::Result<OnDisk> {
365
- match fs::symlink_metadata(path) {
366
- Ok(meta) if meta.file_type().is_symlink() => Ok(OnDisk::Link),
367
- Ok(meta) if meta.is_dir() => Ok(OnDisk::Directory),
368
- Ok(_) => Ok(OnDisk::Other),
369
- Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(OnDisk::Missing),
370
- Err(e) => Err(e),
371
- }
372
- }
373
-
374
- struct Extractor<'a> {
252
+ /// Reads entries out of one handle on the archive and has a `Placer` put
253
+ /// them on disk.
254
+ struct Extractor {
375
255
  archive: ZipArchive<Source>,
376
- dest: &'a str,
377
- /// `dest` as `resolve` has it, with one trailing separator: what every
378
- /// entry path starts with.
379
- prefix: String,
380
- /// `dest` as `resolve` has it.
381
- root: String,
256
+ placer: Placer,
382
257
  enforce_size: bool,
383
- on_exists: OnExists,
384
- /// Directories known to exist, so each parent is created once.
385
- made: HashSet<PathBuf>,
386
- /// Directories made for an entry, with the times and mode to give
387
- /// them once their files are in.
388
- stamp: Vec<(usize, PathBuf, Option<SystemTime>, Option<u32>)>,
389
- /// The destination opened for kernel-checked lookups beneath it;
390
- /// made once the destination exists.
391
- beneath: Option<Beneath>,
392
- /// The place in the batch of the spec being extracted.
393
- at: usize,
394
258
  buf: Vec<u8>,
395
- notices: Vec<(usize, Notice)>,
396
259
  }
397
260
 
398
- impl<'a> Extractor<'a> {
261
+ impl Extractor {
399
262
  fn new(
400
263
  archive: ZipArchive<Source>,
401
- dest: &'a str,
264
+ dest: &str,
402
265
  enforce_size: bool,
403
266
  on_exists: OnExists,
404
267
  ) -> Self {
405
- let root = resolve(dest, "");
406
- let prefix = if root.ends_with('/') {
407
- root.clone()
408
- } else {
409
- format!("{root}/")
410
- };
411
268
  Self {
412
269
  archive,
413
- dest,
414
- prefix,
415
- root,
270
+ placer: Placer::new(dest, on_exists),
416
271
  enforce_size,
417
- on_exists,
418
- made: HashSet::new(),
419
- stamp: Vec::new(),
420
- beneath: None,
421
- at: 0,
422
272
  buf: vec![0; CHUNK],
423
- notices: Vec::new(),
273
+ }
274
+ }
275
+
276
+ /// Another extractor for the same destination, for a worker thread,
277
+ /// reading through its own handle on the archive.
278
+ fn worker(&self) -> Self {
279
+ Self {
280
+ archive: self.archive.clone(),
281
+ placer: self.placer.fork(),
282
+ enforce_size: self.enforce_size,
283
+ buf: vec![0; CHUNK],
424
284
  }
425
285
  }
426
286
 
@@ -428,548 +288,76 @@ impl<'a> Extractor<'a> {
428
288
  /// order; a failure names the place.
429
289
  fn extract_each(&mut self, specs: &[(usize, &Spec)]) -> Result<(), (usize, Failure)> {
430
290
  for &(i, spec) in specs {
431
- self.at = i;
291
+ self.placer.set_at(i);
432
292
  self.extract(spec).map_err(|f| (i, f))?;
433
293
  }
434
294
  Ok(())
435
295
  }
436
296
 
437
297
  fn extract(&mut self, spec: &Spec) -> Result<(), Failure> {
438
- let Some(path) = safe_path(self.dest, &spec.name) else {
439
- let shown = resolve(self.dest, &spec.name);
440
- self.notices.push((spec.index, Notice::Unsafe(shown)));
441
- return Ok(());
442
- };
443
- if spec.directory {
444
- self.create_directory(&path, spec)
445
- } else {
446
- self.create_file(&path, spec)
447
- }
448
- }
449
-
450
- /// `dir` relative to the destination, `/`-separated; empty for the
451
- /// destination itself.
452
- fn below<'p>(&self, dir: &'p str) -> &'p str {
453
- if dir == self.root || format!("{dir}/") == self.prefix {
454
- return "";
455
- }
456
- dir.strip_prefix(self.prefix.as_str()).unwrap_or(dir)
457
- }
458
-
459
- /// The destination, opened on first use (it exists by then).
460
- fn beneath(&mut self) -> &Beneath {
461
- let root = &self.root;
462
- self.beneath
463
- .get_or_insert_with(|| Beneath::new(Path::new(root)))
464
- }
465
-
466
- /// Makes sure every directory between the destination and `path` (not
467
- /// `path` itself) is a real directory, creating the missing ones.
468
- /// Returns false, having noted why if it is a link, when the entry is
469
- /// to be left out.
470
- fn prepare_parents(&mut self, path: &str, spec: &Spec) -> Result<bool, Failure> {
471
- let Some((parent, _)) = path.rsplit_once('/') else {
472
- return Ok(true);
473
- };
474
- if self.made.contains(Path::new(parent)) {
475
- return Ok(true);
476
- }
477
- // The destination is taken as given, a link or not, and made if
478
- // it is not there yet.
479
- if !self.made.contains(Path::new(&self.root)) {
480
- let root = PathBuf::from(&self.root);
481
- fs::create_dir_all(&root).map_err(at(&root))?;
482
- self.made.insert(root);
483
- }
484
- let Some(below) = format!("{parent}/")
485
- .strip_prefix(&self.prefix)
486
- .map(str::to_string)
487
- else {
488
- return Ok(true);
489
- };
490
- let mut walked = self.prefix.clone();
491
- for component in below.split('/').filter(|c| !c.is_empty()) {
492
- if !walked.ends_with('/') {
493
- walked.push('/');
494
- }
495
- walked.push_str(component);
496
- let step = PathBuf::from(&walked);
497
- if self.made.contains(&step) {
498
- continue;
499
- }
500
- match on_disk(&step).map_err(at(&step))? {
501
- OnDisk::Directory => {}
502
- OnDisk::Missing => match fs::create_dir(&step) {
503
- Ok(()) => {}
504
- // Another thread made it meanwhile.
505
- Err(e)
506
- if e.kind() == io::ErrorKind::AlreadyExists
507
- && matches!(on_disk(&step), Ok(OnDisk::Directory)) => {}
508
- Err(e) => return Err(at(&step)(e)),
509
- },
510
- OnDisk::Link => {
511
- self.notices.push((spec.index, Notice::Link(walked)));
512
- return Ok(false);
513
- }
514
- // A file where a directory should be: the entry cannot go
515
- // there. Skipped under `:skip`, an error otherwise (a
516
- // directory entry, when there is one, has already had its
517
- // say under `:overwrite`).
518
- OnDisk::Other => {
519
- return match self.on_exists {
520
- OnExists::Skip => Ok(false),
521
- _ => Err(Failure::Exists(walked)),
522
- };
523
- }
524
- }
525
- self.made.insert(step);
526
- }
527
- Ok(true)
528
- }
529
-
530
- fn create_directory(&mut self, path: &str, spec: &Spec) -> Result<(), Failure> {
531
- let dir = PathBuf::from(path);
532
- if self.made.contains(&dir) || !self.prepare_parents(path, spec)? {
533
- return Ok(());
534
- }
535
- match on_disk(&dir).map_err(at(&dir))? {
536
- OnDisk::Directory => {
537
- self.made.insert(dir);
538
- return Ok(());
539
- }
540
- OnDisk::Link => {
541
- self.notices
542
- .push((spec.index, Notice::Link(path.to_string())));
543
- return Ok(());
544
- }
545
- OnDisk::Other => match self.on_exists {
546
- OnExists::Raise => return Err(Failure::Exists(path_string(&dir))),
547
- OnExists::Skip => return Ok(()),
548
- OnExists::Overwrite => fs::remove_file(&dir).map_err(at(&dir))?,
549
- },
550
- OnDisk::Missing => {}
551
- }
552
- fs::create_dir(&dir).map_err(at(&dir))?;
553
- let path = dir.as_path();
554
- self.made.insert(path.to_path_buf());
555
- if spec.mtime.is_some() || spec.mode.is_some() {
556
- self.stamp
557
- .push((self.at, path.to_path_buf(), spec.mtime, spec.mode));
558
- }
559
- Ok(())
560
- }
561
-
562
- /// Gives the directories made their times and modes, deepest first,
563
- /// so that stamping a parent comes after everything inside it.
564
- fn stamp_directories(&mut self) -> Result<(), (usize, Failure)> {
565
- let mut stamp = std::mem::take(&mut self.stamp);
566
- stamp.sort_by_key(|(_, path, _, _)| std::cmp::Reverse(path.components().count()));
567
- for (i, path, mtime, mode) in stamp {
568
- let below = self.below(&path_string(&path)).to_string();
569
- let path = path.as_path();
570
- // Through a handle opened beneath the destination where the
571
- // OS can, so a link swapped in cannot redirect a chmod.
572
- let dir = self
573
- .beneath()
574
- .directory_handle(path, &below)
575
- .map_err(|e| (i, at(path)(e)))?;
576
- if let Some(mtime) = mtime {
577
- let times = FileTimes::new().set_accessed(mtime).set_modified(mtime);
578
- dir.set_times(times).map_err(|e| (i, at(path)(e)))?;
579
- }
580
- if let Some(mode) = mode {
581
- set_directory_mode(&dir, path, mode).map_err(|e| (i, at(path)(e)))?;
582
- }
583
- }
584
- Ok(())
585
- }
586
-
587
- fn create_file(&mut self, name: &str, spec: &Spec) -> Result<(), Failure> {
588
- if !self.prepare_parents(name, spec)? {
589
- return Ok(());
590
- }
591
- let path = Path::new(name);
592
- let replace = match (on_disk(path).map_err(at(path))?, self.on_exists) {
593
- // Never written through, whatever the policy.
594
- (OnDisk::Link, _) => {
595
- self.notices
596
- .push((spec.index, Notice::Link(name.to_string())));
597
- return Ok(());
598
- }
599
- (OnDisk::Missing, _) => false,
600
- (_, OnExists::Raise) => return Err(Failure::Exists(path_string(path))),
601
- (_, OnExists::Skip) => return Ok(()),
602
- // A directory in the way is not overwritten by a file.
603
- (OnDisk::Directory, OnExists::Overwrite) => {
604
- return Err(Failure::Exists(path_string(path)))
605
- }
606
- (OnDisk::Other, OnExists::Overwrite) => true,
607
- };
608
- // The directory it goes in, opened beneath the destination where
609
- // the OS can: a link swapped in since the walk is refused here.
610
- let (parent, leaf) = name.rsplit_once('/').unwrap_or(("", name));
611
- let parent = if parent.is_empty() { "/" } else { parent };
612
- let below = self.below(parent).to_string();
613
- let place = match self.beneath().place(Path::new(parent), &below) {
614
- Ok(place) => place,
615
- Err(e) if is_link_error(&e) => {
616
- self.notices
617
- .push((spec.index, Notice::Link(parent.to_string())));
618
- return Ok(());
619
- }
620
- Err(e) => return Err(at(Path::new(parent))(e)),
621
- };
622
- // A file being replaced is written beside it and renamed over it
623
- // once complete, so a failure part-way leaves the original as it
624
- // was; a new one is written in place.
625
- let (target, mut file) = if replace {
626
- place.staging(leaf).map_err(at(path))?
627
- } else {
628
- match place.create_new(leaf) {
629
- Ok(f) => (leaf.to_string(), f),
630
- Err(e) if is_link_error(&e) => {
631
- self.notices
632
- .push((spec.index, Notice::Link(name.to_string())));
633
- return Ok(());
634
- }
635
- Err(e) if e.kind() == io::ErrorKind::AlreadyExists || path.exists() => {
636
- return Err(Failure::Exists(path_string(path)));
637
- }
638
- Err(e) => return Err(at(path)(e)),
639
- }
640
- };
641
- let outcome = self.copy_entry(spec.index, &mut file).and_then(|written| {
642
- if let Some(mtime) = spec.mtime {
643
- file.set_times(FileTimes::new().set_accessed(mtime).set_modified(mtime))
644
- .map_err(at(path))?;
645
- }
646
- if let Some(mode) = spec.mode {
647
- set_file_mode(&file, mode).map_err(at(path))?;
648
- }
649
- Ok(written)
650
- });
651
- drop(file);
652
- let outcome = outcome.and_then(|written| {
653
- if replace {
654
- place.rename(&target, leaf).map_err(at(path))?;
655
- }
656
- Ok(written)
657
- });
658
- let written = match outcome {
659
- Ok(n) => n,
660
- Err(failure) => {
661
- // Interrupted or failed part-way: a half-written file
662
- // would pass for the entry, and stand in the way of a
663
- // second run. What it replaces is still there.
664
- let _ = place.remove(&target);
665
- return Err(match failure {
666
- // Reading the entry is the entry's problem; writing is
667
- // the path's.
668
- Failure::Io(e)
669
- if e.kind() == io::ErrorKind::WriteZero
670
- || e.kind() == io::ErrorKind::StorageFull =>
671
- {
672
- at(path)(e)
673
- }
674
- other => other,
675
- });
676
- }
677
- };
678
- if !self.enforce_size {
679
- let declared = self.archive.metadata().entry(spec.index)?.size();
298
+ let Self {
299
+ archive,
300
+ placer,
301
+ enforce_size,
302
+ buf,
303
+ } = self;
304
+ let enforce_size = *enforce_size;
305
+ let written = placer.place(spec, |file| {
306
+ copy_entry(archive, buf, enforce_size, spec.index, file)
307
+ })?;
308
+ if let (Some(written), false) = (written, enforce_size) {
309
+ let declared = archive.metadata().entry(spec.index)?.size();
680
310
  if written > declared {
681
- self.notices.push((spec.index, Notice::Oversize));
311
+ placer.note(spec.index, Notice::Oversize);
682
312
  }
683
313
  }
684
314
  Ok(())
685
315
  }
686
-
687
- /// Decompresses entry `index` into `file`, returning the byte count.
688
- fn copy_entry(&mut self, index: usize, file: &mut fs::File) -> Result<u64, Failure> {
689
- let buf = &mut self.buf;
690
- let mut written = 0u64;
691
- let mut copy = |reader: &mut dyn Read| -> Result<(), Failure> {
692
- loop {
693
- crate::gvl::check()?;
694
- let n = reader.read(buf)?;
695
- if n == 0 {
696
- return Ok(());
697
- }
698
- file.write_all(&buf[..n])?;
699
- written += n as u64;
700
- }
701
- };
702
- if self.enforce_size {
703
- // An entry with no data at all is never read, as `EntryReader`
704
- // has it: the file is created and left empty. One declared
705
- // empty that has data goes through the crate's size check.
706
- let metadata = self.archive.metadata();
707
- let meta = metadata.entry(index)?;
708
- if meta.size() == 0 && meta.compressed_size() == 0 {
709
- return Ok(0);
710
- }
711
- drop(metadata);
712
- let mut entry = self.archive.by_index(index)?;
713
- copy(&mut entry)?;
714
- } else {
715
- // Past the declared size to the true end of the data, the way
716
- // `EntryReader` does without enforcement.
717
- let info = {
718
- let meta = self.archive.metadata();
719
- let raw = meta.entry(index)?;
720
- EntryInfo::from_entry(index, &raw)
721
- };
722
- let mut source = self.archive.clone().into_inner();
723
- let mut entry = open_local_entry(&mut source, &info, None, u64::MAX)?;
724
- copy(&mut entry)?;
725
- }
726
- Ok(written)
727
- }
728
- }
729
-
730
- fn path_string(path: &Path) -> String {
731
- path.to_string_lossy().replace('\\', "/")
732
- }
733
-
734
- /// The absolute path `name` lands on under `dest`, as `File.absolute_path`
735
- /// resolves `File.join(dest, name)`, or `None` when it is not strictly
736
- /// inside `dest`. The one exception, as in Ruby, is a destination that is
737
- /// the root directory itself.
738
- fn safe_path(dest: &str, name: &str) -> Option<String> {
739
- let resolved = resolve(dest, name);
740
- if dest == "/" {
741
- return Some(resolved);
742
- }
743
- let dest = resolve(dest, "");
744
- let prefix = if dest.ends_with('/') {
745
- dest
746
- } else {
747
- format!("{dest}/")
748
- };
749
- resolved.starts_with(&prefix).then_some(resolved)
750
316
  }
751
317
 
752
- /// Lexical `File.absolute_path(File.join(dest, name))` for an absolute
753
- /// `dest`: either separator, `.` and empty components dropped, `..`
754
- /// popping the previous component but never the root (`/`, a drive or a
755
- /// UNC share).
756
- fn resolve(dest: &str, name: &str) -> String {
757
- let mut parts: Vec<&str> = Vec::new();
758
- let mut components = dest.split(['/', '\\']).peekable();
759
- match components.peek().copied() {
760
- Some("") => {
761
- parts.push("");
762
- components.next();
763
- if components.peek() == Some(&"") && is_unc(dest) {
764
- // "//server/share/...": the share is the root.
765
- components.next();
766
- parts.push("");
767
- parts.extend(components.by_ref().take(2));
768
- }
769
- }
770
- Some(c) if is_drive(c) => {
771
- parts.push(c);
772
- components.next();
773
- }
774
- _ => {}
775
- }
776
- let root_len = parts.len();
777
- for c in components.chain(name.split(['/', '\\'])) {
778
- match c {
779
- "" | "." => {}
780
- ".." => {
781
- if parts.len() > root_len {
782
- parts.pop();
783
- }
318
+ /// Decompresses entry `index` into `file`, returning the byte count.
319
+ fn copy_entry(
320
+ archive: &mut ZipArchive<Source>,
321
+ buf: &mut [u8],
322
+ enforce_size: bool,
323
+ index: usize,
324
+ file: &mut fs::File,
325
+ ) -> Result<u64, Failure> {
326
+ let mut written = 0u64;
327
+ let mut copy = |reader: &mut dyn Read| -> Result<(), Failure> {
328
+ loop {
329
+ crate::gvl::check()?;
330
+ let n = reader.read(buf)?;
331
+ if n == 0 {
332
+ return Ok(());
784
333
  }
785
- c => parts.push(c),
334
+ file.write_all(&buf[..n])?;
335
+ written += n as u64;
786
336
  }
787
- }
788
- let joined = parts.join("/");
789
- if parts.len() == root_len {
790
- // Only the root is left: "/" rather than "", "C:/" rather than "C:".
791
- if joined.is_empty() {
792
- "/".to_string()
793
- } else {
794
- format!("{joined}/")
337
+ };
338
+ if enforce_size {
339
+ // An entry with no data at all is never read, as `EntryReader`
340
+ // has it: the file is created and left empty. One declared
341
+ // empty that has data goes through the crate's size check.
342
+ let metadata = archive.metadata();
343
+ let meta = metadata.entry(index)?;
344
+ if meta.size() == 0 && meta.compressed_size() == 0 {
345
+ return Ok(0);
795
346
  }
347
+ drop(metadata);
348
+ let mut entry = archive.by_index(index)?;
349
+ copy(&mut entry)?;
796
350
  } else {
797
- joined
798
- }
799
- }
800
-
801
- fn is_drive(c: &str) -> bool {
802
- let b = c.as_bytes();
803
- b.len() == 2 && b[0].is_ascii_alphabetic() && b[1] == b':'
804
- }
805
-
806
- /// "//server/..." (or with backslashes), as opposed to a bare "//".
807
- fn is_unc(path: &str) -> bool {
808
- let b = path.as_bytes();
809
- b.len() > 2 && is_sep(b[0]) && is_sep(b[1]) && !is_sep(b[2])
810
- }
811
-
812
- fn is_sep(b: u8) -> bool {
813
- b == b'/' || b == b'\\'
814
- }
815
-
816
- #[cfg(unix)]
817
- fn set_file_mode(file: &fs::File, mode: u32) -> io::Result<()> {
818
- use std::os::unix::fs::PermissionsExt;
819
- file.set_permissions(fs::Permissions::from_mode(mode))
820
- }
821
-
822
- /// Sets a directory's mode through its handle (fchmod).
823
- #[cfg(unix)]
824
- fn set_directory_mode(dir: &fs::File, _path: &Path, mode: u32) -> io::Result<()> {
825
- set_file_mode(dir, mode)
826
- }
827
-
828
- /// Ruby's `File.chmod` on Windows only knows the read-only attribute,
829
- /// set when the owner-write bit is clear.
830
- #[cfg(not(unix))]
831
- fn set_file_mode(file: &fs::File, mode: u32) -> io::Result<()> {
832
- if mode & 0o200 == 0 {
833
- let mut perms = file.metadata()?.permissions();
834
- perms.set_readonly(true);
835
- file.set_permissions(perms)?;
836
- }
837
- Ok(())
838
- }
839
-
840
- /// On Windows by path: the handle opened for times cannot change the
841
- /// read-only attribute.
842
- #[cfg(not(unix))]
843
- fn set_directory_mode(_dir: &fs::File, path: &Path, mode: u32) -> io::Result<()> {
844
- if mode & 0o200 == 0 {
845
- let mut perms = fs::metadata(path)?.permissions();
846
- perms.set_readonly(true);
847
- fs::set_permissions(path, perms)?;
848
- }
849
- Ok(())
850
- }
851
-
852
- #[cfg(test)]
853
- mod tests {
854
- use super::*;
855
-
856
- #[test]
857
- fn resolves_like_absolute_path() {
858
- assert_eq!(resolve("/p/dest", "a/b"), "/p/dest/a/b");
859
- assert_eq!(resolve("/p/dest", "/tmp/moo"), "/p/dest/tmp/moo");
860
- assert_eq!(resolve("/p/dest", "//tmp/moo"), "/p/dest/tmp/moo");
861
- assert_eq!(resolve("/p/dest", "../moo"), "/p/moo");
862
- assert_eq!(resolve("/p/dest", "tmp/../../moo"), "/p/moo");
863
- assert_eq!(resolve("/p/dest", "a/../b"), "/p/dest/b");
864
- assert_eq!(resolve("/p/dest", "../dest/y"), "/p/dest/y");
865
- assert_eq!(resolve("/p/dest", "dir/"), "/p/dest/dir");
866
- assert_eq!(resolve("/p/dest", "."), "/p/dest");
867
- assert_eq!(resolve("/p/dest", "../../../../x"), "/x");
868
- assert_eq!(resolve("/", "../x"), "/x");
869
- assert_eq!(resolve("/", ""), "/");
870
- assert_eq!(resolve("C:/dest", "a\\b"), "C:/dest/a/b");
871
- assert_eq!(resolve("C:/dest", "../../x"), "C:/x");
872
- assert_eq!(resolve("C:/", ".."), "C:/");
873
- assert_eq!(resolve("//srv/share/d", "../../../x"), "//srv/share/x");
874
- assert_eq!(resolve("//", "x"), "/x");
875
- }
876
-
877
- #[test]
878
- fn checks_prefix() {
879
- assert_eq!(safe_path("/p/dest", "a").as_deref(), Some("/p/dest/a"));
880
- assert_eq!(safe_path("/p/dest/", "a").as_deref(), Some("/p/dest/a"));
881
- assert!(safe_path("/p/dest", "../moo").is_none());
882
- assert!(safe_path("/p/dest", "tmp/../../moo").is_none());
883
- assert!(safe_path("/p/dest", ".").is_none());
884
- assert!(safe_path("/p/dest", "").is_none());
885
- assert!(safe_path("/p/dest", "../dest_evil/x").is_none());
886
- assert_eq!(safe_path("/", "../x").as_deref(), Some("/x"));
887
- assert_eq!(
888
- safe_path("C:/dest", "/tmp/moo").as_deref(),
889
- Some("C:/dest/tmp/moo")
890
- );
891
- assert_eq!(safe_path("C:/", "x").as_deref(), Some("C:/x"));
892
- }
893
-
894
- /// A name made of the pieces that matter to the check: separators of
895
- /// both kinds, `.`, `..`, empty components, drive letters and plain
896
- /// names.
897
- fn random_name(rng: &mut crate::test_rng::Rng) -> String {
898
- const PIECES: &[&str] = &[
899
- "a",
900
- "b",
901
- "dest",
902
- "dest_evil",
903
- "..",
904
- ".",
905
- "",
906
- "/",
907
- "\\",
908
- "C:",
909
- "x.txt",
910
- ];
911
- let len = rng.below(8);
912
- let mut name = String::new();
913
- for _ in 0..len {
914
- name.push_str(rng.pick(PIECES));
915
- name.push(*rng.pick(&['/', '\\', '/']));
916
- }
917
- name.push_str(rng.pick(PIECES));
918
- name
919
- }
920
-
921
- #[test]
922
- fn property_a_safe_path_is_strictly_inside_and_normal() {
923
- const DESTS: &[&str] = &["/p/dest", "/p/dest/", "C:/p/dest", "//srv/share/dest", "/"];
924
- let mut rng = crate::test_rng::Rng::new(1);
925
- for case in 0..crate::test_rng::CASES {
926
- let dest = *rng.pick(DESTS);
927
- let name = random_name(&mut rng);
928
- let resolved = resolve(dest, &name);
929
- // Normalised: nothing a second pass would change.
930
- assert_eq!(
931
- resolve(&resolved, ""),
932
- resolved,
933
- "case {case}: {dest:?} + {name:?}"
934
- );
935
- assert!(!resolved.contains('\\'), "case {case}: {resolved:?}");
936
- let Some(path) = safe_path(dest, &name) else {
937
- continue;
938
- };
939
- assert_eq!(path, resolved);
940
- if dest != "/" {
941
- let root = resolve(dest, "");
942
- let prefix = format!("{}/", root.trim_end_matches('/'));
943
- assert!(
944
- path.starts_with(&prefix),
945
- "case {case}: {path:?} not under {prefix:?}"
946
- );
947
- assert!(
948
- path.len() > prefix.len(),
949
- "case {case}: the destination itself"
950
- );
951
- }
952
- let below = &path[resolve(dest, "").len()..];
953
- assert!(
954
- below.split('/').all(|c| c != ".." && c != "."),
955
- "case {case}: {path:?}"
956
- );
957
- }
958
- }
959
-
960
- #[test]
961
- fn property_a_name_without_dot_dot_stays_inside() {
962
- let mut rng = crate::test_rng::Rng::new(2);
963
- for case in 0..crate::test_rng::CASES {
964
- let name = random_name(&mut rng);
965
- let climbs = name.split(['/', '\\']).any(|c| c == "..");
966
- let empty = name.split(['/', '\\']).all(|c| c.is_empty() || c == ".");
967
- if !climbs && !empty {
968
- assert!(
969
- safe_path("/p/dest", &name).is_some(),
970
- "case {case}: {name:?}"
971
- );
972
- }
973
- }
351
+ // Past the declared size to the true end of the data, the way
352
+ // `EntryReader` does without enforcement.
353
+ let info = {
354
+ let meta = archive.metadata();
355
+ let raw = meta.entry(index)?;
356
+ EntryInfo::from_entry(index, &raw)
357
+ };
358
+ let mut source = archive.clone().into_inner();
359
+ let mut entry = open_local_entry(&mut source, &info, None, u64::MAX)?;
360
+ copy(&mut entry)?;
974
361
  }
362
+ Ok(written)
975
363
  }