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.
@@ -0,0 +1,759 @@
1
+ //! Where extracted entries go on disk, whatever they are read from.
2
+ //!
3
+ //! A `Placer` is given one spec per entry and, for a file, something that
4
+ //! writes its data into the handle it opens. It creates each parent
5
+ //! directory once, writes every file through a single handle and stamps
6
+ //! times and permissions on that handle.
7
+ //!
8
+ //! The path check is the one `Entry#extract` makes, re-done here on the
9
+ //! same terms: the entry name is joined onto the absolute destination and
10
+ //! normalised lexically (as `File.absolute_path` does), and the result must
11
+ //! start with the destination plus a separator. Nothing is created for an
12
+ //! entry that fails it; Ruby prints the same warning it would have.
13
+ //!
14
+ //! Below the destination nothing is followed through a link already on
15
+ //! disk (a symlink, or on Windows a junction): every directory on the way
16
+ //! to an entry, and the entry's own path, must be a real directory or
17
+ //! file, or the entry is skipped with a warning. The destination itself is
18
+ //! taken as given, link or not. This is checked before each path is used;
19
+ //! on Linux, `place.rs` also opens each file's directory beneath the
20
+ //! destination so that the kernel refuses a link swapped in meanwhile.
21
+
22
+ use std::collections::HashSet;
23
+ use std::fs::{self, FileTimes};
24
+ use std::io;
25
+ use std::path::{Path, PathBuf};
26
+ use std::time::SystemTime;
27
+
28
+ use zip::result::ZipError;
29
+
30
+ use crate::place::{is_link_error, Beneath};
31
+
32
+ /// One entry to extract, as Ruby describes it:
33
+ /// `[entry, index, name, mtime_sec, mtime_nsec, mode, directory?]`.
34
+ pub(crate) struct Spec {
35
+ /// What the entry is known by in notices.
36
+ pub(crate) index: usize,
37
+ pub(crate) name: String,
38
+ /// `None` when times are not restored.
39
+ pub(crate) mtime: Option<SystemTime>,
40
+ /// Unix mode to apply, already masked by Ruby; `None` to leave alone.
41
+ pub(crate) mode: Option<u32>,
42
+ pub(crate) directory: bool,
43
+ }
44
+
45
+ /// Why an entry could not be extracted; turned into a Ruby exception once
46
+ /// the GVL is held again.
47
+ pub(crate) enum Failure {
48
+ Exists(String),
49
+ SizeLimit,
50
+ Zip(ZipError),
51
+ /// Reading the entry failed.
52
+ Io(io::Error),
53
+ /// Creating or writing `path` failed: raised as the matching `Errno`
54
+ /// with the path in the message, as Ruby's own File calls do.
55
+ IoAt(String, io::Error),
56
+ }
57
+
58
+ /// Attaches `path` to an IO error from a filesystem call on it.
59
+ fn at(path: &Path) -> impl Fn(io::Error) -> Failure + '_ {
60
+ move |e| Failure::IoAt(path_string(path), e)
61
+ }
62
+
63
+ impl From<ZipError> for Failure {
64
+ fn from(e: ZipError) -> Self {
65
+ match e {
66
+ ZipError::DecompressedSizeLimitExceeded { .. } => Failure::SizeLimit,
67
+ other => Failure::Zip(other),
68
+ }
69
+ }
70
+ }
71
+
72
+ impl From<io::Error> for Failure {
73
+ fn from(e: io::Error) -> Self {
74
+ // The crate reports a header that understates the size either as
75
+ // its own error behind an io::Error, or (crc32.rs) as plain
76
+ // InvalidData with a message.
77
+ let limit = e
78
+ .get_ref()
79
+ .and_then(|inner| inner.downcast_ref::<ZipError>())
80
+ .is_some_and(|z| matches!(z, ZipError::DecompressedSizeLimitExceeded { .. }))
81
+ || crate::errors::is_size_limit(&e);
82
+ if limit {
83
+ Failure::SizeLimit
84
+ } else {
85
+ Failure::Io(e)
86
+ }
87
+ }
88
+ }
89
+
90
+ /// Something Ruby should warn about afterwards.
91
+ pub(crate) enum Notice {
92
+ /// The entry resolved outside the destination; nothing was written.
93
+ Unsafe(String),
94
+ /// A link on disk stands at this path on the way to the entry, or at
95
+ /// the entry's own path; nothing was written.
96
+ Link(String),
97
+ /// Without size enforcement, more bytes came out than declared.
98
+ Oversize,
99
+ }
100
+
101
+ /// What to do about a file or directory already at an entry's path.
102
+ #[derive(Clone, Copy)]
103
+ pub(crate) enum OnExists {
104
+ Raise,
105
+ Overwrite,
106
+ Skip,
107
+ }
108
+
109
+ /// What stands at a path, looked at without following a link there.
110
+ enum OnDisk {
111
+ Missing,
112
+ Directory,
113
+ /// A symlink, or on Windows a junction or other name-surrogate
114
+ /// reparse point (what `FileType::is_symlink` counts).
115
+ Link,
116
+ /// A file, or anything else that is neither a directory nor a link.
117
+ Other,
118
+ }
119
+
120
+ fn on_disk(path: &Path) -> io::Result<OnDisk> {
121
+ match fs::symlink_metadata(path) {
122
+ Ok(meta) if meta.file_type().is_symlink() => Ok(OnDisk::Link),
123
+ Ok(meta) if meta.is_dir() => Ok(OnDisk::Directory),
124
+ Ok(_) => Ok(OnDisk::Other),
125
+ Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(OnDisk::Missing),
126
+ Err(e) => Err(e),
127
+ }
128
+ }
129
+
130
+ /// Puts entries under one destination. The data of a file comes from the
131
+ /// caller, so the same rules hold whatever the archive is.
132
+ pub(crate) struct Placer {
133
+ dest: String,
134
+ /// `dest` as `resolve` has it, with one trailing separator: what every
135
+ /// entry path starts with.
136
+ prefix: String,
137
+ /// `dest` as `resolve` has it.
138
+ root: String,
139
+ on_exists: OnExists,
140
+ /// Directories known to exist, so each parent is created once.
141
+ made: HashSet<PathBuf>,
142
+ /// Directories made for an entry, with the times and mode to give
143
+ /// them once their files are in.
144
+ stamp: Vec<(usize, PathBuf, Option<SystemTime>, Option<u32>)>,
145
+ /// The destination opened for kernel-checked lookups beneath it;
146
+ /// made once the destination exists.
147
+ beneath: Option<Beneath>,
148
+ /// The place in the batch of the spec being placed.
149
+ at: usize,
150
+ notices: Vec<(usize, Notice)>,
151
+ /// The file about to be replaced is one this run wrote (see
152
+ /// `set_own`).
153
+ own: bool,
154
+ }
155
+
156
+ impl Placer {
157
+ pub(crate) fn new(dest: &str, on_exists: OnExists) -> Self {
158
+ let root = resolve(dest, "");
159
+ let prefix = if root.ends_with('/') {
160
+ root.clone()
161
+ } else {
162
+ format!("{root}/")
163
+ };
164
+ Self {
165
+ dest: dest.to_string(),
166
+ prefix,
167
+ root,
168
+ on_exists,
169
+ made: HashSet::new(),
170
+ stamp: Vec::new(),
171
+ beneath: None,
172
+ at: 0,
173
+ notices: Vec::new(),
174
+ own: false,
175
+ }
176
+ }
177
+
178
+ /// Another placer for the same destination, for a worker thread: it
179
+ /// starts out knowing the directories this one has made.
180
+ pub(crate) fn fork(&self) -> Self {
181
+ let mut other = Self::new(&self.dest, self.on_exists);
182
+ other.made.clone_from(&self.made);
183
+ other
184
+ }
185
+
186
+ /// Says where in the batch the next spec stands, which is how a
187
+ /// failure to stamp a directory names its entry.
188
+ pub(crate) fn set_at(&mut self, at: usize) {
189
+ self.at = at;
190
+ }
191
+
192
+ /// Changes what is done about a path already taken, for the entries
193
+ /// placed from here on.
194
+ pub(crate) fn set_on_exists(&mut self, on_exists: OnExists) {
195
+ self.on_exists = on_exists;
196
+ }
197
+
198
+ /// Says whether a file the next entry replaces is one this run wrote
199
+ /// itself. It then gives way even if the archive marked it read-only,
200
+ /// which on Windows would otherwise refuse the replacement.
201
+ pub(crate) fn set_own(&mut self, own: bool) {
202
+ self.own = own;
203
+ }
204
+
205
+ pub(crate) fn on_exists(&self) -> OnExists {
206
+ self.on_exists
207
+ }
208
+
209
+ pub(crate) fn note(&mut self, index: usize, notice: Notice) {
210
+ self.notices.push((index, notice));
211
+ }
212
+
213
+ /// The notices so far, which are then forgotten.
214
+ pub(crate) fn take_notices(&mut self) -> Vec<(usize, Notice)> {
215
+ std::mem::take(&mut self.notices)
216
+ }
217
+
218
+ /// Places the entry `spec` describes. A directory is created; for a
219
+ /// file, `write` is called with the open handle and returns how many
220
+ /// bytes it wrote, which is what comes back. `None` means nothing was
221
+ /// written: a directory, or an entry left out (with a notice when a
222
+ /// warning is due).
223
+ pub(crate) fn place(
224
+ &mut self,
225
+ spec: &Spec,
226
+ write: impl FnOnce(&mut fs::File) -> Result<u64, Failure>,
227
+ ) -> Result<Option<u64>, Failure> {
228
+ let Some(path) = safe_path(&self.dest, &spec.name) else {
229
+ let shown = resolve(&self.dest, &spec.name);
230
+ self.notices.push((spec.index, Notice::Unsafe(shown)));
231
+ return Ok(None);
232
+ };
233
+ if spec.directory {
234
+ self.create_directory(&path, spec)?;
235
+ Ok(None)
236
+ } else {
237
+ self.create_file(&path, spec, write)
238
+ }
239
+ }
240
+
241
+ /// `dir` relative to the destination, `/`-separated; empty for the
242
+ /// destination itself.
243
+ fn below<'p>(&self, dir: &'p str) -> &'p str {
244
+ if dir == self.root || format!("{dir}/") == self.prefix {
245
+ return "";
246
+ }
247
+ dir.strip_prefix(self.prefix.as_str()).unwrap_or(dir)
248
+ }
249
+
250
+ /// The destination, opened on first use (it exists by then).
251
+ fn beneath(&mut self) -> &Beneath {
252
+ let root = &self.root;
253
+ self.beneath
254
+ .get_or_insert_with(|| Beneath::new(Path::new(root)))
255
+ }
256
+
257
+ /// Makes sure every directory between the destination and `path` (not
258
+ /// `path` itself) is a real directory, creating the missing ones.
259
+ /// Returns false, having noted why if it is a link, when the entry is
260
+ /// to be left out.
261
+ fn prepare_parents(&mut self, path: &str, spec: &Spec) -> Result<bool, Failure> {
262
+ let Some((parent, _)) = path.rsplit_once('/') else {
263
+ return Ok(true);
264
+ };
265
+ if self.made.contains(Path::new(parent)) {
266
+ return Ok(true);
267
+ }
268
+ // The destination is taken as given, a link or not, and made if
269
+ // it is not there yet.
270
+ if !self.made.contains(Path::new(&self.root)) {
271
+ let root = PathBuf::from(&self.root);
272
+ fs::create_dir_all(&root).map_err(at(&root))?;
273
+ self.made.insert(root);
274
+ }
275
+ let Some(below) = format!("{parent}/")
276
+ .strip_prefix(&self.prefix)
277
+ .map(str::to_string)
278
+ else {
279
+ return Ok(true);
280
+ };
281
+ let mut walked = self.prefix.clone();
282
+ for component in below.split('/').filter(|c| !c.is_empty()) {
283
+ if !walked.ends_with('/') {
284
+ walked.push('/');
285
+ }
286
+ walked.push_str(component);
287
+ let step = PathBuf::from(&walked);
288
+ if self.made.contains(&step) {
289
+ continue;
290
+ }
291
+ match on_disk(&step).map_err(at(&step))? {
292
+ OnDisk::Directory => {}
293
+ OnDisk::Missing => match fs::create_dir(&step) {
294
+ Ok(()) => {}
295
+ // Another thread made it meanwhile.
296
+ Err(e)
297
+ if e.kind() == io::ErrorKind::AlreadyExists
298
+ && matches!(on_disk(&step), Ok(OnDisk::Directory)) => {}
299
+ Err(e) => return Err(at(&step)(e)),
300
+ },
301
+ OnDisk::Link => {
302
+ self.notices.push((spec.index, Notice::Link(walked)));
303
+ return Ok(false);
304
+ }
305
+ // A file where a directory should be: the entry cannot go
306
+ // there. Skipped under `:skip`, an error otherwise (a
307
+ // directory entry, when there is one, has already had its
308
+ // say under `:overwrite`).
309
+ OnDisk::Other => {
310
+ return match self.on_exists {
311
+ OnExists::Skip => Ok(false),
312
+ _ => Err(Failure::Exists(walked)),
313
+ };
314
+ }
315
+ }
316
+ self.made.insert(step);
317
+ }
318
+ Ok(true)
319
+ }
320
+
321
+ fn create_directory(&mut self, path: &str, spec: &Spec) -> Result<(), Failure> {
322
+ let dir = PathBuf::from(path);
323
+ if self.made.contains(&dir) || !self.prepare_parents(path, spec)? {
324
+ return Ok(());
325
+ }
326
+ match on_disk(&dir).map_err(at(&dir))? {
327
+ OnDisk::Directory => {
328
+ self.made.insert(dir);
329
+ return Ok(());
330
+ }
331
+ OnDisk::Link => {
332
+ self.notices
333
+ .push((spec.index, Notice::Link(path.to_string())));
334
+ return Ok(());
335
+ }
336
+ OnDisk::Other => match self.on_exists {
337
+ OnExists::Raise => return Err(Failure::Exists(path_string(&dir))),
338
+ OnExists::Skip => return Ok(()),
339
+ OnExists::Overwrite => fs::remove_file(&dir).map_err(at(&dir))?,
340
+ },
341
+ OnDisk::Missing => {}
342
+ }
343
+ fs::create_dir(&dir).map_err(at(&dir))?;
344
+ let path = dir.as_path();
345
+ self.made.insert(path.to_path_buf());
346
+ if spec.mtime.is_some() || spec.mode.is_some() {
347
+ self.stamp
348
+ .push((self.at, path.to_path_buf(), spec.mtime, spec.mode));
349
+ }
350
+ Ok(())
351
+ }
352
+
353
+ /// Gives the directories made their times and modes, deepest first,
354
+ /// so that stamping a parent comes after everything inside it.
355
+ pub(crate) fn stamp_directories(&mut self) -> Result<(), (usize, Failure)> {
356
+ let mut stamp = std::mem::take(&mut self.stamp);
357
+ stamp.sort_by_key(|(_, path, _, _)| std::cmp::Reverse(path.components().count()));
358
+ for (i, path, mtime, mode) in stamp {
359
+ let below = self.below(&path_string(&path)).to_string();
360
+ let path = path.as_path();
361
+ // Through a handle opened beneath the destination where the
362
+ // OS can, so a link swapped in cannot redirect a chmod.
363
+ let dir = self
364
+ .beneath()
365
+ .directory_handle(path, &below)
366
+ .map_err(|e| (i, at(path)(e)))?;
367
+ if let Some(mtime) = mtime {
368
+ let times = FileTimes::new().set_accessed(mtime).set_modified(mtime);
369
+ dir.set_times(times).map_err(|e| (i, at(path)(e)))?;
370
+ }
371
+ if let Some(mode) = mode {
372
+ set_directory_mode(&dir, path, mode).map_err(|e| (i, at(path)(e)))?;
373
+ }
374
+ }
375
+ Ok(())
376
+ }
377
+
378
+ fn create_file(
379
+ &mut self,
380
+ name: &str,
381
+ spec: &Spec,
382
+ write: impl FnOnce(&mut fs::File) -> Result<u64, Failure>,
383
+ ) -> Result<Option<u64>, Failure> {
384
+ if !self.prepare_parents(name, spec)? {
385
+ return Ok(None);
386
+ }
387
+ let path = Path::new(name);
388
+ let replace = match (on_disk(path).map_err(at(path))?, self.on_exists) {
389
+ // Never written through, whatever the policy.
390
+ (OnDisk::Link, _) => {
391
+ self.notices
392
+ .push((spec.index, Notice::Link(name.to_string())));
393
+ return Ok(None);
394
+ }
395
+ (OnDisk::Missing, _) => false,
396
+ (_, OnExists::Raise) => return Err(Failure::Exists(path_string(path))),
397
+ (_, OnExists::Skip) => return Ok(None),
398
+ // A directory in the way is not overwritten by a file.
399
+ (OnDisk::Directory, OnExists::Overwrite) => {
400
+ return Err(Failure::Exists(path_string(path)))
401
+ }
402
+ (OnDisk::Other, OnExists::Overwrite) => true,
403
+ };
404
+ // The directory it goes in, opened beneath the destination where
405
+ // the OS can: a link swapped in since the walk is refused here.
406
+ let (parent, leaf) = name.rsplit_once('/').unwrap_or(("", name));
407
+ let parent = if parent.is_empty() { "/" } else { parent };
408
+ let own = self.own;
409
+ let below = self.below(parent).to_string();
410
+ let place = match self.beneath().place(Path::new(parent), &below) {
411
+ Ok(place) => place,
412
+ Err(e) if is_link_error(&e) => {
413
+ self.notices
414
+ .push((spec.index, Notice::Link(parent.to_string())));
415
+ return Ok(None);
416
+ }
417
+ Err(e) => return Err(at(Path::new(parent))(e)),
418
+ };
419
+ // A file being replaced is written beside it and renamed over it
420
+ // once complete, so a failure part-way leaves the original as it
421
+ // was; a new one is written in place.
422
+ let (target, mut file) = if replace {
423
+ place.staging(leaf).map_err(at(path))?
424
+ } else {
425
+ match place.create_new(leaf) {
426
+ Ok(f) => (leaf.to_string(), f),
427
+ Err(e) if is_link_error(&e) => {
428
+ self.notices
429
+ .push((spec.index, Notice::Link(name.to_string())));
430
+ return Ok(None);
431
+ }
432
+ Err(e) if e.kind() == io::ErrorKind::AlreadyExists || path.exists() => {
433
+ return Err(Failure::Exists(path_string(path)));
434
+ }
435
+ Err(e) => return Err(at(path)(e)),
436
+ }
437
+ };
438
+ let outcome = write(&mut file).and_then(|written| {
439
+ if let Some(mtime) = spec.mtime {
440
+ file.set_times(FileTimes::new().set_accessed(mtime).set_modified(mtime))
441
+ .map_err(at(path))?;
442
+ }
443
+ if let Some(mode) = spec.mode {
444
+ set_file_mode(&file, mode).map_err(at(path))?;
445
+ }
446
+ Ok(written)
447
+ });
448
+ drop(file);
449
+ let outcome = outcome.and_then(|written| {
450
+ if replace {
451
+ if own {
452
+ make_replaceable(path);
453
+ }
454
+ place.rename(&target, leaf).map_err(at(path))?;
455
+ }
456
+ Ok(written)
457
+ });
458
+ let written = match outcome {
459
+ Ok(n) => n,
460
+ Err(failure) => {
461
+ // Interrupted or failed part-way: a half-written file
462
+ // would pass for the entry, and stand in the way of a
463
+ // second run. What it replaces is still there.
464
+ let _ = place.remove(&target);
465
+ return Err(match failure {
466
+ // Reading the entry is the entry's problem; writing is
467
+ // the path's.
468
+ Failure::Io(e)
469
+ if e.kind() == io::ErrorKind::WriteZero
470
+ || e.kind() == io::ErrorKind::StorageFull =>
471
+ {
472
+ at(path)(e)
473
+ }
474
+ other => other,
475
+ });
476
+ }
477
+ };
478
+ Ok(Some(written))
479
+ }
480
+ }
481
+
482
+ /// Windows does not rename over a read-only file: the attribute comes
483
+ /// off first. Elsewhere a rename asks nothing of the file it replaces.
484
+ #[cfg(windows)]
485
+ fn make_replaceable(path: &Path) {
486
+ if let Ok(meta) = fs::symlink_metadata(path) {
487
+ let mut perms = meta.permissions();
488
+ if meta.is_file() && perms.readonly() {
489
+ perms.set_readonly(false);
490
+ let _ = fs::set_permissions(path, perms);
491
+ }
492
+ }
493
+ }
494
+
495
+ #[cfg(not(windows))]
496
+ fn make_replaceable(_path: &Path) {}
497
+
498
+ fn path_string(path: &Path) -> String {
499
+ path.to_string_lossy().replace('\\', "/")
500
+ }
501
+
502
+ /// The absolute path `name` lands on under `dest`, as `File.absolute_path`
503
+ /// resolves `File.join(dest, name)`, or `None` when it is not strictly
504
+ /// inside `dest`. The one exception, as in Ruby, is a destination that is
505
+ /// the root directory itself.
506
+ ///
507
+ /// On Windows a name with a colon is not inside either: it names a
508
+ /// stream of a file ("a.txt:x" writes into `a.txt`, there before or not,
509
+ /// without replacing it) or a drive.
510
+ fn safe_path(dest: &str, name: &str) -> Option<String> {
511
+ if cfg!(windows) && has_colon(name) {
512
+ return None;
513
+ }
514
+ let resolved = resolve(dest, name);
515
+ if dest == "/" {
516
+ return Some(resolved);
517
+ }
518
+ let dest = resolve(dest, "");
519
+ let prefix = if dest.ends_with('/') {
520
+ dest
521
+ } else {
522
+ format!("{dest}/")
523
+ };
524
+ resolved.starts_with(&prefix).then_some(resolved)
525
+ }
526
+
527
+ /// Lexical `File.absolute_path(File.join(dest, name))` for an absolute
528
+ /// `dest`: either separator, `.` and empty components dropped, `..`
529
+ /// popping the previous component but never the root (`/`, a drive or a
530
+ /// UNC share).
531
+ fn resolve(dest: &str, name: &str) -> String {
532
+ let mut parts: Vec<&str> = Vec::new();
533
+ let mut components = dest.split(['/', '\\']).peekable();
534
+ match components.peek().copied() {
535
+ Some("") => {
536
+ parts.push("");
537
+ components.next();
538
+ if components.peek() == Some(&"") && is_unc(dest) {
539
+ // "//server/share/...": the share is the root.
540
+ components.next();
541
+ parts.push("");
542
+ parts.extend(components.by_ref().take(2));
543
+ }
544
+ }
545
+ Some(c) if is_drive(c) => {
546
+ parts.push(c);
547
+ components.next();
548
+ }
549
+ _ => {}
550
+ }
551
+ let root_len = parts.len();
552
+ for c in components.chain(name.split(['/', '\\'])) {
553
+ match c {
554
+ "" | "." => {}
555
+ ".." => {
556
+ if parts.len() > root_len {
557
+ parts.pop();
558
+ }
559
+ }
560
+ c => parts.push(c),
561
+ }
562
+ }
563
+ let joined = parts.join("/");
564
+ if parts.len() == root_len {
565
+ // Only the root is left: "/" rather than "", "C:/" rather than "C:".
566
+ if joined.is_empty() {
567
+ "/".to_string()
568
+ } else {
569
+ format!("{joined}/")
570
+ }
571
+ } else {
572
+ joined
573
+ }
574
+ }
575
+
576
+ fn has_colon(name: &str) -> bool {
577
+ name.contains(':')
578
+ }
579
+
580
+ fn is_drive(c: &str) -> bool {
581
+ let b = c.as_bytes();
582
+ b.len() == 2 && b[0].is_ascii_alphabetic() && b[1] == b':'
583
+ }
584
+
585
+ /// "//server/..." (or with backslashes), as opposed to a bare "//".
586
+ fn is_unc(path: &str) -> bool {
587
+ let b = path.as_bytes();
588
+ b.len() > 2 && is_sep(b[0]) && is_sep(b[1]) && !is_sep(b[2])
589
+ }
590
+
591
+ fn is_sep(b: u8) -> bool {
592
+ b == b'/' || b == b'\\'
593
+ }
594
+
595
+ #[cfg(unix)]
596
+ fn set_file_mode(file: &fs::File, mode: u32) -> io::Result<()> {
597
+ use std::os::unix::fs::PermissionsExt;
598
+ file.set_permissions(fs::Permissions::from_mode(mode))
599
+ }
600
+
601
+ /// Sets a directory's mode through its handle (fchmod).
602
+ #[cfg(unix)]
603
+ fn set_directory_mode(dir: &fs::File, _path: &Path, mode: u32) -> io::Result<()> {
604
+ set_file_mode(dir, mode)
605
+ }
606
+
607
+ /// Ruby's `File.chmod` on Windows only knows the read-only attribute,
608
+ /// set when the owner-write bit is clear.
609
+ #[cfg(not(unix))]
610
+ fn set_file_mode(file: &fs::File, mode: u32) -> io::Result<()> {
611
+ if mode & 0o200 == 0 {
612
+ let mut perms = file.metadata()?.permissions();
613
+ perms.set_readonly(true);
614
+ file.set_permissions(perms)?;
615
+ }
616
+ Ok(())
617
+ }
618
+
619
+ /// On Windows by path: the handle opened for times cannot change the
620
+ /// read-only attribute.
621
+ #[cfg(not(unix))]
622
+ fn set_directory_mode(_dir: &fs::File, path: &Path, mode: u32) -> io::Result<()> {
623
+ if mode & 0o200 == 0 {
624
+ let mut perms = fs::metadata(path)?.permissions();
625
+ perms.set_readonly(true);
626
+ fs::set_permissions(path, perms)?;
627
+ }
628
+ Ok(())
629
+ }
630
+
631
+ #[cfg(test)]
632
+ mod tests {
633
+ use super::*;
634
+
635
+ #[test]
636
+ fn resolves_like_absolute_path() {
637
+ assert_eq!(resolve("/p/dest", "a/b"), "/p/dest/a/b");
638
+ assert_eq!(resolve("/p/dest", "/tmp/moo"), "/p/dest/tmp/moo");
639
+ assert_eq!(resolve("/p/dest", "//tmp/moo"), "/p/dest/tmp/moo");
640
+ assert_eq!(resolve("/p/dest", "../moo"), "/p/moo");
641
+ assert_eq!(resolve("/p/dest", "tmp/../../moo"), "/p/moo");
642
+ assert_eq!(resolve("/p/dest", "a/../b"), "/p/dest/b");
643
+ assert_eq!(resolve("/p/dest", "../dest/y"), "/p/dest/y");
644
+ assert_eq!(resolve("/p/dest", "dir/"), "/p/dest/dir");
645
+ assert_eq!(resolve("/p/dest", "."), "/p/dest");
646
+ assert_eq!(resolve("/p/dest", "../../../../x"), "/x");
647
+ assert_eq!(resolve("/", "../x"), "/x");
648
+ assert_eq!(resolve("/", ""), "/");
649
+ assert_eq!(resolve("C:/dest", "a\\b"), "C:/dest/a/b");
650
+ assert_eq!(resolve("C:/dest", "../../x"), "C:/x");
651
+ assert_eq!(resolve("C:/", ".."), "C:/");
652
+ assert_eq!(resolve("//srv/share/d", "../../../x"), "//srv/share/x");
653
+ assert_eq!(resolve("//", "x"), "/x");
654
+ }
655
+
656
+ #[test]
657
+ fn checks_prefix() {
658
+ assert_eq!(safe_path("/p/dest", "a").as_deref(), Some("/p/dest/a"));
659
+ assert_eq!(safe_path("/p/dest/", "a").as_deref(), Some("/p/dest/a"));
660
+ assert!(safe_path("/p/dest", "../moo").is_none());
661
+ assert!(safe_path("/p/dest", "tmp/../../moo").is_none());
662
+ assert!(safe_path("/p/dest", ".").is_none());
663
+ assert!(safe_path("/p/dest", "").is_none());
664
+ assert!(safe_path("/p/dest", "../dest_evil/x").is_none());
665
+ assert_eq!(safe_path("/", "../x").as_deref(), Some("/x"));
666
+ assert_eq!(
667
+ safe_path("C:/dest", "/tmp/moo").as_deref(),
668
+ Some("C:/dest/tmp/moo")
669
+ );
670
+ assert_eq!(safe_path("C:/", "x").as_deref(), Some("C:/x"));
671
+ // Only Windows reads a colon as a stream or a drive.
672
+ for name in ["a.txt:evil", "a.txt::$DATA", "C:x", "d/e:f/g"] {
673
+ assert!(has_colon(name));
674
+ assert_eq!(safe_path("/p/dest", name).is_none(), cfg!(windows));
675
+ }
676
+ }
677
+
678
+ /// A name made of the pieces that matter to the check: separators of
679
+ /// both kinds, `.`, `..`, empty components, drive letters and plain
680
+ /// names.
681
+ fn random_name(rng: &mut crate::test_rng::Rng) -> String {
682
+ const PIECES: &[&str] = &[
683
+ "a",
684
+ "b",
685
+ "dest",
686
+ "dest_evil",
687
+ "..",
688
+ ".",
689
+ "",
690
+ "/",
691
+ "\\",
692
+ "C:",
693
+ "x.txt",
694
+ ];
695
+ let len = rng.below(8);
696
+ let mut name = String::new();
697
+ for _ in 0..len {
698
+ name.push_str(rng.pick(PIECES));
699
+ name.push(*rng.pick(&['/', '\\', '/']));
700
+ }
701
+ name.push_str(rng.pick(PIECES));
702
+ name
703
+ }
704
+
705
+ #[test]
706
+ fn property_a_safe_path_is_strictly_inside_and_normal() {
707
+ const DESTS: &[&str] = &["/p/dest", "/p/dest/", "C:/p/dest", "//srv/share/dest", "/"];
708
+ let mut rng = crate::test_rng::Rng::new(1);
709
+ for case in 0..crate::test_rng::CASES {
710
+ let dest = *rng.pick(DESTS);
711
+ let name = random_name(&mut rng);
712
+ let resolved = resolve(dest, &name);
713
+ // Normalised: nothing a second pass would change.
714
+ assert_eq!(
715
+ resolve(&resolved, ""),
716
+ resolved,
717
+ "case {case}: {dest:?} + {name:?}"
718
+ );
719
+ assert!(!resolved.contains('\\'), "case {case}: {resolved:?}");
720
+ let Some(path) = safe_path(dest, &name) else {
721
+ continue;
722
+ };
723
+ assert_eq!(path, resolved);
724
+ if dest != "/" {
725
+ let root = resolve(dest, "");
726
+ let prefix = format!("{}/", root.trim_end_matches('/'));
727
+ assert!(
728
+ path.starts_with(&prefix),
729
+ "case {case}: {path:?} not under {prefix:?}"
730
+ );
731
+ assert!(
732
+ path.len() > prefix.len(),
733
+ "case {case}: the destination itself"
734
+ );
735
+ }
736
+ let below = &path[resolve(dest, "").len()..];
737
+ assert!(
738
+ below.split('/').all(|c| c != ".." && c != "."),
739
+ "case {case}: {path:?}"
740
+ );
741
+ }
742
+ }
743
+
744
+ #[test]
745
+ fn property_a_name_without_dot_dot_stays_inside() {
746
+ let mut rng = crate::test_rng::Rng::new(2);
747
+ for case in 0..crate::test_rng::CASES {
748
+ let name = random_name(&mut rng);
749
+ let climbs = name.split(['/', '\\']).any(|c| c == "..");
750
+ let empty = name.split(['/', '\\']).all(|c| c.is_empty() || c == ".");
751
+ if !climbs && !empty {
752
+ assert!(
753
+ safe_path("/p/dest", &name).is_some(),
754
+ "case {case}: {name:?}"
755
+ );
756
+ }
757
+ }
758
+ }
759
+ }