1
//! An iterator to resolve and canonicalize a filename.
2

            
3
use crate::{Error, Result};
4
use std::{
5
    collections::HashMap,
6
    ffi::OsString,
7
    fs::Metadata,
8
    io,
9
    iter::FusedIterator,
10
    path::{Path, PathBuf},
11
    sync::Arc,
12
};
13

            
14
/// The type of a single path inspected by [`Verifier`](crate::Verifier).
15
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
16
#[allow(clippy::exhaustive_enums)]
17
pub(crate) enum PathType {
18
    /// This is indeed the final canonical path we were trying to resolve.
19
    Final,
20
    /// This is an intermediary canonical path.  It _should_ be a directory, but
21
    /// it might not be if the path resolution is about to fail.
22
    Intermediate,
23
    /// This is a symbolic link.
24
    Symlink,
25
    /// This is a file _inside_ the target directory.
26
    Content,
27
}
28

            
29
/// A single piece of a path.
30
///
31
/// We would use [`std::path::Component`] directly here, but we want an owned
32
/// type.
33
#[derive(Clone, Debug)]
34
struct Component {
35
    /// Is this a prefix of a windows path?
36
    ///
37
    /// We need to keep track of these, because we expect stat() to fail for
38
    /// them.
39
    #[cfg(target_family = "windows")]
40
    is_windows_prefix: bool,
41
    /// The textual value of the component.
42
    text: OsString,
43
}
44

            
45
/// Windows error code that we expect to get when calling stat() on a prefix.
46
#[cfg(target_family = "windows")]
47
const INVALID_FUNCTION: i32 = 1;
48

            
49
impl<'a> From<std::path::Component<'a>> for Component {
50
111837
    fn from(c: std::path::Component<'a>) -> Self {
51
111837
        #[cfg(target_family = "windows")]
52
111837
        let is_windows_prefix = matches!(c, std::path::Component::Prefix(_));
53
111837
        let text = c.as_os_str().to_owned();
54
111837
        Component {
55
111837
            #[cfg(target_family = "windows")]
56
111837
            is_windows_prefix,
57
111837
            text,
58
111837
        }
59
111837
    }
60
}
61

            
62
/// An iterator to resolve and canonicalize a filename, imitating the actual
63
/// filesystem's lookup behavior.
64
///
65
/// A `ResolvePath` looks up a filename by visiting all intermediate steps in
66
/// turn, starting from the root directory, and following symlinks.  It
67
/// suppresses duplicates.  Every path that it yields will _either_ be:
68
///   * A directory in canonical[^1] [^2] form.
69
///   * `dir/link` where dir is a directory in canonical form, and `link` is a
70
///     symlink in that directory.
71
///   * `dir/file` where dir is a directory in canonical form, and `file` is a
72
///     file in that directory.
73
///
74
/// [^1]: We define "canonical" in the same way as `Path::canonicalize`: a
75
///   canonical path is an absolute path containing no "." or ".." elements, and
76
///   no symlinks.
77
/// [^2]: Strictly speaking, this iterator on its own cannot guarantee that the
78
///   paths it yields are truly canonical.  or that they even represent the
79
///   target.  It is possible that in between checking one path and the next,
80
///   somebody will modify the first path to replace a directory with a symlink,
81
///   or replace one symlink with another. To get this kind of guarantee, you
82
///   have to use a [`Mistrust`](crate::Mistrust) to check the permissions on
83
///   the directories as you go.  Even then, your guarantee is conditional on
84
///   none of the intermediary directories having been changed by a trusted user
85
///   at the wrong time.
86
///   
87
///
88
/// # Implementation notes
89
///
90
/// Abstractly, at any given point, the directory that we're resolving looks
91
/// like `"resolved"/"remaining"`, where `resolved` is the part that we've
92
/// already looked at (in canonical form, with all symlinks resolved) and
93
/// `remaining` is the part that we're still trying to resolve.
94
///
95
/// We represent `resolved` as a nice plain PathBuf, and  `remaining` as a stack
96
/// of strings that we want to push on to the end of the path.  We initialize
97
/// the algorithm with `resolved` empty and `remaining` seeded with the path we
98
/// want to resolve.  Once there are no more parts to push, the path resolution
99
/// is done.
100
///
101
/// The following invariants apply whenever we are outside of the `next`
102
/// function:
103
///    * `resolved.join(remaining)` is an alias for our target path.
104
///    * `resolved` is in canonical form.
105
///    * Every ancestor of `resolved` is a key of `already_inspected`.
106
///
107
/// # Limitations
108
///
109
/// Because we're using `Path::metadata` rather than something that would use
110
/// `openat()` and `fstat()` under the hood, the permissions returned here are
111
/// potentially susceptible to TOCTOU issues.  In this crate we address these
112
/// issues by checking each yielded path immediately to make sure that only
113
/// _trusted_ users can change it after it is checked.
114
//
115
// TODO: This code is potentially of use outside this crate.  Maybe it should be
116
// public?
117
#[derive(Clone, Debug)]
118
pub(crate) struct ResolvePath {
119
    /// The path that we have resolved so far.  It is always[^1] an absolute
120
    /// path in canonical form: it contains no ".." or "." entries, and no
121
    /// symlinks.
122
    ///
123
    /// [^1]: See note on [`ResolvePath`] about time-of-check/time-of-use
124
    ///     issues.
125
    resolved: PathBuf,
126

            
127
    /// The parts of the path that we have _not yet resolved_.  The item on the
128
    /// top of the stack (that is, the end), is the next element that we'd like
129
    /// to add to `resolved`.
130
    ///
131
    /// This is in reverse order: later path components at the start of the `Vec` (bottom of stack)
132
    //
133
    // TODO: I'd like to have a more efficient representation of this; the
134
    // current one has a lot of tiny little allocations.
135
    stack: Vec<Component>,
136

            
137
    /// If true, we have encountered a nonrecoverable error and cannot yield any
138
    /// more items.
139
    ///
140
    /// We have a flag for this so that we know to stop when we've encountered
141
    /// an error for `lstat()` or `readlink()`: If we can't do those, we can't
142
    /// continue resolving the path.
143
    terminated: bool,
144

            
145
    /// How many more steps are we willing to take in resolving this path?  We
146
    /// decrement this by 1 every time we pop an element from the stack.  If we
147
    /// ever realize that we've run out of steps, we abort, since that's
148
    /// probably a symlink loop.
149
    steps_remaining: usize,
150

            
151
    /// A cache of the paths that we have already yielded to the caller.  We keep
152
    /// this cache so that we don't have to `lstat()` or `readlink()` any path
153
    /// more than once.  If the path was a symlink, then the value associated
154
    /// with it is the target of that symlink.  Otherwise, the value associated
155
    /// with it is None.
156
    already_inspected: HashMap<PathBuf, Option<PathBuf>>,
157
}
158

            
159
/// How many steps are we willing to take in resolving a path?
160
const MAX_STEPS: usize = 1024;
161

            
162
impl ResolvePath {
163
    /// Create a new empty ResolvePath.
164
23335
    fn empty() -> Self {
165
23335
        ResolvePath {
166
23335
            resolved: PathBuf::new(),
167
23335
            stack: Vec::new(),
168
23335
            terminated: false,
169
23335
            steps_remaining: MAX_STEPS,
170
23335
            already_inspected: HashMap::new(),
171
23335
        }
172
23335
    }
173
    /// Construct a new `ResolvePath` iterator to resolve the provided `path`.
174
23335
    pub(crate) fn new(path: impl AsRef<Path>) -> Result<Self> {
175
23335
        let mut resolve = Self::empty();
176
23335
        let path = path.as_ref();
177
23335
        // The path resolution algorithm will _end_ with resolving the path we
178
23335
        // were provided...
179
23335
        push_prefix(&mut resolve.stack, path);
180
23335
        // ...and if if the path is relative, we will first resolve the current
181
23335
        // directory.
182
23335
        if path.is_relative() {
183
            // This can fail, sadly.
184
713
            let cwd = std::env::current_dir().map_err(|e| Error::CurrentDirectory(Arc::new(e)))?;
185
713
            if !cwd.is_absolute() {
186
                // This should be impossible, but let's make sure.
187
                let ioe =
188
                    io::Error::other(format!("Current directory {:?} was not absolute.", cwd));
189
                return Err(Error::CurrentDirectory(Arc::new(ioe)));
190
713
            }
191
713
            push_prefix(&mut resolve.stack, cwd.as_ref());
192
22622
        }
193

            
194
23335
        Ok(resolve)
195
23335
    }
196

            
197
    /// Consume this ResolvePath and return as much work as it was able to
198
    /// complete.
199
    ///
200
    /// If the path was completely resolved, then we return the resolved
201
    /// canonical path, and None.
202
    ///
203
    /// If the path was _not_ completely resolved (the loop terminated early, or
204
    /// ended with an error), we return the part that we were able to resolve,
205
    /// and a path that would need to be joined onto it to reach the intended
206
    /// destination.
207
245
    pub(crate) fn into_result(self) -> (PathBuf, Option<PathBuf>) {
208
245
        let remainder = if self.stack.is_empty() {
209
4
            None
210
        } else {
211
487
            Some(self.stack.into_iter().rev().map(|c| c.text).collect())
212
        };
213

            
214
245
        (self.resolved, remainder)
215
245
    }
216
}
217

            
218
/// Push the string representation of each component of `path` onto `stack`,
219
/// from last to first, so that the first component of `path` winds up on the
220
/// top of the stack.
221
///
222
/// (This is a separate function rather than a method for borrow-checker
223
/// reasons.)
224
25502
fn push_prefix(stack: &mut Vec<Component>, path: &Path) {
225
112961
    stack.extend(path.components().rev().map(|component| component.into()));
226
25502
}
227

            
228
impl Iterator for ResolvePath {
229
    type Item = Result<(PathBuf, PathType, Metadata)>;
230

            
231
123450
    fn next(&mut self) -> Option<Self::Item> {
232
        // Usually we'll return a value from our first attempt at this loop; we
233
        // only call "continue" if we encounter a path that we have already
234
        // given the caller.
235
        loop {
236
            // If we're fused, we're fused.  Nothing more to do.
237
128118
            if self.terminated {
238
8
                return None;
239
128110
            }
240
128110
            // We will necessarily take at least `stack.len()` more steps: if we
241
128110
            // don't have that many steps left, we cannot succeed.  Probably
242
128110
            // this indicates a symlink loop, though it could also be a maze of
243
128110
            // some kind.
244
128110
            //
245
128110
            // TODO: Arguably, we should keep taking steps until we run out, but doing
246
128110
            // so might potentially lead to our stack getting huge.  This way we
247
128110
            // keep the stack depth under control.
248
128110
            if self.steps_remaining < self.stack.len() {
249
4
                self.terminated = true;
250
4
                return Some(Err(Error::StepsExceeded));
251
128106
            }
252

            
253
            // Look at the next component on the stack...
254
128106
            let next_part = match self.stack.pop() {
255
110363
                Some(p) => p,
256
                None => {
257
                    // This is the successful case: we have finished resolving every component on the stack.
258
17743
                    self.terminated = true;
259
17743
                    return None;
260
                }
261
            };
262
110363
            self.steps_remaining -= 1;
263

            
264
            // ..and add that component to our resolved path to see what we
265
            // should inspect next.
266
110363
            let inspecting: std::borrow::Cow<'_, Path> = if next_part.text == "." {
267
                // Do nothing.
268
1490
                self.resolved.as_path().into()
269
108873
            } else if next_part.text == ".." {
270
                // We can safely remove the last part of our path: We know it is
271
                // canonical, so ".." will not give surprising results.  (If we
272
                // are already at the root, "PathBuf::pop" will do nothing.)
273
868
                self.resolved
274
868
                    .parent()
275
868
                    .unwrap_or(self.resolved.as_path())
276
868
                    .into()
277
            } else {
278
                // We extend our path.  This may _temporarily_ make `resolved`
279
                // non-canonical if next_part is the name of a symlink; we'll
280
                // fix that in a minute.
281
                //
282
                // This is the only thing that can ever make `resolved` longer.
283
108005
                self.resolved.join(&next_part.text).into()
284
            };
285

            
286
            // Now "inspecting" is the path we want to look at.  Later in this
287
            // function, we should replace "self.resolved" with "inspecting" if we
288
            // find that "inspecting" is a good canonical path.
289

            
290
110363
            match self.already_inspected.get(inspecting.as_ref()) {
291
1424
                Some(Some(link_target)) => {
292
1424
                    // We already inspected this path, and it is a symlink.
293
1424
                    // Follow it, and loop.
294
1424
                    //
295
1424
                    // (See notes below starting with "This is a symlink!" for
296
1424
                    // more explanation of what we're doing here.)
297
1424
                    push_prefix(&mut self.stack, link_target.as_path());
298
1424
                    continue;
299
                }
300
                Some(None) => {
301
                    // We've already inspected this path, and it's canonical.
302
                    // We told the caller about it once before, so we just loop.
303
3244
                    self.resolved = inspecting.into_owned();
304
3244
                    continue;
305
                }
306
105695
                None => {
307
105695
                    // We haven't seen this path before. Carry on.
308
105695
                }
309
            }
310

            
311
            // Look up the lstat() of the file, to see if it's a symlink.
312
105695
            let metadata = match inspecting.symlink_metadata() {
313
100935
                Ok(m) => m,
314
                #[cfg(target_family = "windows")]
315
                Err(e)
316
                    if next_part.is_windows_prefix
317
                        && e.raw_os_error() == Some(INVALID_FUNCTION) =>
318
                {
319
                    // We expected an error here, and we got one. Skip over this
320
                    // path component and look at the next.
321
                    self.resolved = inspecting.into_owned();
322
                    continue;
323
                }
324
4760
                Err(e) => {
325
4760
                    // Oops: can't lstat.  Move the last component back on to the stack, and terminate.
326
4760
                    self.stack.push(next_part);
327
4760
                    self.terminated = true;
328
4760
                    return Some(Err(Error::inspecting(e, inspecting)));
329
                }
330
            };
331

            
332
100935
            if metadata.file_type().is_symlink() {
333
                // This is a symlink!
334
                //
335
                // We have to find out where it leads us...
336
30
                let link_target = match inspecting.read_link() {
337
30
                    Ok(t) => t,
338
                    Err(e) => {
339
                        // Oops: can't readlink.  Move the last component back on to the stack, and terminate.
340
                        self.stack.push(next_part);
341
                        self.terminated = true;
342
                        return Some(Err(Error::inspecting(e, inspecting)));
343
                    }
344
                };
345

            
346
                // We don't modify self.resolved here: we would be putting a
347
                // symlink onto it, and symlinks aren't canonical.  (If the
348
                // symlink is relative, then we'll continue resolving it from
349
                // its target on the next iteration.  If the symlink is
350
                // absolute, its first component will be "/" or the equivalent,
351
                // which will replace self.resolved.)
352
30
                push_prefix(&mut self.stack, link_target.as_path());
353
30
                self.already_inspected
354
30
                    .insert(inspecting.to_path_buf(), Some(link_target));
355
30
                // We yield the link name, not the value of resolved.
356
30
                return Some(Ok((inspecting.into_owned(), PathType::Symlink, metadata)));
357
            } else {
358
                // It's not a symlink: Therefore it is a real canonical
359
                // directory or file that exists.
360
100905
                self.already_inspected
361
100905
                    .insert(inspecting.to_path_buf(), None);
362
100905
                self.resolved = inspecting.into_owned();
363
100905
                let path_type = if self.stack.is_empty() {
364
18314
                    PathType::Final
365
                } else {
366
82591
                    PathType::Intermediate
367
                };
368
100905
                return Some(Ok((self.resolved.clone(), path_type, metadata)));
369
            }
370
        }
371
123450
    }
372
}
373

            
374
impl FusedIterator for ResolvePath {}
375

            
376
/*
377
   Not needed, but can be a big help with debugging.
378
impl std::fmt::Display for ResolvePath {
379
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
380
        let remaining: PathBuf = self.stack.iter().rev().collect();
381
        write!(f, "{{ {:?} }}/{{ {:?} }}", &self.resolved, remaining,)
382
    }
383
}
384
*/
385

            
386
#[cfg(test)]
387
mod test {
388
    // @@ begin test lint list maintained by maint/add_warning @@
389
    #![allow(clippy::bool_assert_comparison)]
390
    #![allow(clippy::clone_on_copy)]
391
    #![allow(clippy::dbg_macro)]
392
    #![allow(clippy::mixed_attributes_style)]
393
    #![allow(clippy::print_stderr)]
394
    #![allow(clippy::print_stdout)]
395
    #![allow(clippy::single_char_pattern)]
396
    #![allow(clippy::unwrap_used)]
397
    #![allow(clippy::unchecked_duration_subtraction)]
398
    #![allow(clippy::useless_vec)]
399
    #![allow(clippy::needless_pass_by_value)]
400
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
401
    use super::*;
402
    use crate::testing;
403

            
404
    #[cfg(target_family = "unix")]
405
    use crate::testing::LinkType;
406

            
407
    /// Helper: skip `r` past the first occurrence of the path `p` in a
408
    /// successful return.
409
    fn skip_past(r: &mut ResolvePath, p: impl AsRef<Path>) {
410
        #[allow(clippy::manual_flatten)]
411
        for item in r {
412
            if let Ok((name, _, _)) = item {
413
                if name == p.as_ref() {
414
                    break;
415
                }
416
            }
417
        }
418
    }
419

            
420
    /// Helper: change the prefix on `path` (if any) to a verbatim prefix.
421
    ///
422
    /// We do this to match the output of `fs::canonicalize` on Windows, for
423
    /// testing.
424
    ///
425
    /// If this function proves to be hard-to-maintain, we should consider
426
    /// alternative ways of testing what it provides.
427
    fn make_prefix_verbatim(path: PathBuf) -> PathBuf {
428
        let mut components = path.components();
429
        if let Some(std::path::Component::Prefix(prefix)) = components.next() {
430
            use std::path::Prefix as P;
431
            let verbatim = match prefix.kind() {
432
                P::UNC(server, share) => {
433
                    let mut p = OsString::from(r"\\?\UNC\");
434
                    p.push(server);
435
                    p.push("/");
436
                    p.push(share);
437
                    p
438
                }
439
                P::Disk(disk) => format!(r"\\?\{}:", disk as char).into(),
440
                _ => return path, // original prefix is fine.
441
            };
442
            let mut newpath = PathBuf::from(verbatim);
443
            newpath.extend(components.map(|c| c.as_os_str()));
444
            newpath
445
        } else {
446
            path // nothing to do.
447
        }
448
    }
449

            
450
    #[test]
451
    fn simple_path() {
452
        let d = testing::Dir::new();
453
        let root = d.canonical_root();
454

            
455
        // Try resolving a simple path that exists.
456
        d.file("a/b/c");
457
        let mut r = ResolvePath::new(d.path("a/b/c")).unwrap();
458
        skip_past(&mut r, root);
459
        let mut so_far = root.to_path_buf();
460
        for (c, p) in Path::new("a/b/c").components().zip(&mut r) {
461
            let (p, pt, meta) = p.unwrap();
462
            if pt == PathType::Final {
463
                assert_eq!(c.as_os_str(), "c");
464
                assert!(meta.is_file());
465
            } else {
466
                assert_eq!(pt, PathType::Intermediate);
467
                assert!(meta.is_dir());
468
            }
469
            so_far.push(c);
470
            assert_eq!(so_far, p);
471
        }
472
        let (canonical, rest) = r.into_result();
473
        assert_eq!(canonical, d.path("a/b/c").canonicalize().unwrap());
474
        assert!(rest.is_none());
475

            
476
        // Same as above, starting from a relative path to the target.
477
        let mut r = ResolvePath::new(d.relative_root().join("a/b/c")).unwrap();
478
        skip_past(&mut r, root);
479
        let mut so_far = root.to_path_buf();
480
        for (c, p) in Path::new("a/b/c").components().zip(&mut r) {
481
            let (p, pt, meta) = p.unwrap();
482
            if pt == PathType::Final {
483
                assert_eq!(c.as_os_str(), "c");
484
                assert!(meta.is_file());
485
            } else {
486
                assert_eq!(pt, PathType::Intermediate);
487
                assert!(meta.is_dir());
488
            }
489
            so_far.push(c);
490
            assert_eq!(so_far, p);
491
        }
492
        let (canonical, rest) = r.into_result();
493
        let canonical = make_prefix_verbatim(canonical);
494
        assert_eq!(canonical, d.path("a/b/c").canonicalize().unwrap());
495
        assert!(rest.is_none());
496

            
497
        // Try resolving a simple path that doesn't exist.
498
        let mut r = ResolvePath::new(d.path("a/xxx/yyy")).unwrap();
499
        skip_past(&mut r, root);
500
        let (p, pt, _) = r.next().unwrap().unwrap();
501
        assert_eq!(p, root.join("a"));
502
        assert_eq!(pt, PathType::Intermediate);
503
        let e = r.next().unwrap();
504
        match e {
505
            Err(Error::NotFound(p)) => assert_eq!(p, root.join("a/xxx")),
506
            other => panic!("{:?}", other),
507
        }
508
        let (start, rest) = r.into_result();
509
        assert_eq!(start, d.path("a").canonicalize().unwrap());
510
        assert_eq!(rest.unwrap(), Path::new("xxx/yyy"));
511
    }
512

            
513
    #[test]
514
    #[cfg(target_family = "unix")]
515
    fn repeats() {
516
        let d = testing::Dir::new();
517
        let root = d.canonical_root();
518

            
519
        // We're going to try a path with ..s in it, and make sure that we only
520
        // get each given path once.
521
        d.dir("a/b/c/d");
522
        let mut r = ResolvePath::new(root.join("a/b/../b/../b/c/../c/d")).unwrap();
523
        skip_past(&mut r, root);
524
        let paths: Vec<_> = r.map(|item| item.unwrap().0).collect();
525
        assert_eq!(
526
            paths,
527
            vec![
528
                root.join("a"),
529
                root.join("a/b"),
530
                root.join("a/b/c"),
531
                root.join("a/b/c/d"),
532
            ]
533
        );
534

            
535
        // Now try a symlink to a higher directory, and make sure we only get
536
        // each path once.
537
        d.link_rel(LinkType::Dir, "../../", "a/b/c/rel_lnk");
538
        let mut r = ResolvePath::new(root.join("a/b/c/rel_lnk/b/c/d")).unwrap();
539
        skip_past(&mut r, root);
540
        let paths: Vec<_> = r.map(|item| item.unwrap().0).collect();
541
        assert_eq!(
542
            paths,
543
            vec![
544
                root.join("a"),
545
                root.join("a/b"),
546
                root.join("a/b/c"),
547
                root.join("a/b/c/rel_lnk"),
548
                root.join("a/b/c/d"),
549
            ]
550
        );
551

            
552
        // Once more, with an absolute symlink.
553
        d.link_abs(LinkType::Dir, "a", "a/b/c/abs_lnk");
554
        let mut r = ResolvePath::new(root.join("a/b/c/abs_lnk/b/c/d")).unwrap();
555
        skip_past(&mut r, root);
556
        let paths: Vec<_> = r.map(|item| item.unwrap().0).collect();
557
        assert_eq!(
558
            paths,
559
            vec![
560
                root.join("a"),
561
                root.join("a/b"),
562
                root.join("a/b/c"),
563
                root.join("a/b/c/abs_lnk"),
564
                root.join("a/b/c/d"),
565
            ]
566
        );
567

            
568
        // One more, with multiple links.
569
        let mut r = ResolvePath::new(root.join("a/b/c/abs_lnk/b/c/rel_lnk/b/c/d")).unwrap();
570
        skip_past(&mut r, root);
571
        let paths: Vec<_> = r.map(|item| item.unwrap().0).collect();
572
        assert_eq!(
573
            paths,
574
            vec![
575
                root.join("a"),
576
                root.join("a/b"),
577
                root.join("a/b/c"),
578
                root.join("a/b/c/abs_lnk"),
579
                root.join("a/b/c/rel_lnk"),
580
                root.join("a/b/c/d"),
581
            ]
582
        );
583

            
584
        // Last time, visiting the same links more than once.
585
        let mut r =
586
            ResolvePath::new(root.join("a/b/c/abs_lnk/b/c/rel_lnk/b/c/rel_lnk/b/c/abs_lnk/b/c/d"))
587
                .unwrap();
588
        skip_past(&mut r, root);
589
        let paths: Vec<_> = r.map(|item| item.unwrap().0).collect();
590
        assert_eq!(
591
            paths,
592
            vec![
593
                root.join("a"),
594
                root.join("a/b"),
595
                root.join("a/b/c"),
596
                root.join("a/b/c/abs_lnk"),
597
                root.join("a/b/c/rel_lnk"),
598
                root.join("a/b/c/d"),
599
            ]
600
        );
601
    }
602

            
603
    #[test]
604
    #[cfg(target_family = "unix")]
605
    fn looping() {
606
        let d = testing::Dir::new();
607
        let root = d.canonical_root();
608

            
609
        d.dir("a/b/c");
610
        // This file links to itself.  We should hit our loop detector and barf.
611
        d.link_rel(LinkType::File, "../../b/c/d", "a/b/c/d");
612
        let mut r = ResolvePath::new(root.join("a/b/c/d")).unwrap();
613
        skip_past(&mut r, root);
614
        assert_eq!(r.next().unwrap().unwrap().0, root.join("a"));
615
        assert_eq!(r.next().unwrap().unwrap().0, root.join("a/b"));
616
        assert_eq!(r.next().unwrap().unwrap().0, root.join("a/b/c"));
617
        assert_eq!(r.next().unwrap().unwrap().0, root.join("a/b/c/d"));
618
        assert!(matches!(
619
            r.next().unwrap().unwrap_err(),
620
            Error::StepsExceeded
621
        ));
622
        assert!(r.next().is_none());
623

            
624
        // These directories link to each other.
625
        d.link_rel(LinkType::Dir, "./f", "a/b/c/e");
626
        d.link_rel(LinkType::Dir, "./e", "a/b/c/f");
627
        let mut r = ResolvePath::new(root.join("a/b/c/e/413")).unwrap();
628
        skip_past(&mut r, root);
629
        assert_eq!(r.next().unwrap().unwrap().0, root.join("a"));
630
        assert_eq!(r.next().unwrap().unwrap().0, root.join("a/b"));
631
        assert_eq!(r.next().unwrap().unwrap().0, root.join("a/b/c"));
632
        assert_eq!(r.next().unwrap().unwrap().0, root.join("a/b/c/e"));
633
        assert_eq!(r.next().unwrap().unwrap().0, root.join("a/b/c/f"));
634
        assert!(matches!(
635
            r.next().unwrap().unwrap_err(),
636
            Error::StepsExceeded
637
        ));
638
        assert!(r.next().is_none());
639
    }
640

            
641
    #[cfg(target_family = "unix")]
642
    #[test]
643
    fn unix_permissions() {
644
        use std::os::unix::prelude::PermissionsExt;
645

            
646
        let d = testing::Dir::new();
647
        let root = d.canonical_root();
648
        d.dir("a/b/c/d/e");
649
        d.chmod("a", 0o751);
650
        d.chmod("a/b", 0o711);
651
        d.chmod("a/b/c", 0o715);
652
        d.chmod("a/b/c/d", 0o000);
653

            
654
        let mut r = ResolvePath::new(root.join("a/b/c/d/e/413")).unwrap();
655
        skip_past(&mut r, root);
656
        let resolvable: Vec<_> = (&mut r)
657
            .take(4)
658
            .map(|item| {
659
                let (p, _, m) = item.unwrap();
660
                (
661
                    p.strip_prefix(root).unwrap().to_string_lossy().into_owned(),
662
                    m.permissions().mode() & 0o777,
663
                )
664
            })
665
            .collect();
666
        let expected = vec![
667
            ("a", 0o751),
668
            ("a/b", 0o711),
669
            ("a/b/c", 0o715),
670
            ("a/b/c/d", 0o000),
671
        ];
672
        for ((p1, m1), (p2, m2)) in resolvable.iter().zip(expected.iter()) {
673
            assert_eq!(p1, p2);
674
            assert_eq!(m1, m2);
675
        }
676

            
677
        #[cfg(not(target_os = "android"))]
678
        if pwd_grp::getuid() == 0 {
679
            // We won't actually get a CouldNotInspect if we're running as root,
680
            // since root can read directories that are mode 000.
681
            return;
682
        }
683

            
684
        let err = r.next().unwrap();
685
        assert!(matches!(err, Err(Error::CouldNotInspect(_, _))));
686

            
687
        assert!(r.next().is_none());
688
    }
689

            
690
    #[test]
691
    fn past_root() {
692
        let d = testing::Dir::new();
693
        let root = d.canonical_root();
694
        d.dir("a/b");
695
        d.chmod("a", 0o700);
696
        d.chmod("a/b", 0o700);
697

            
698
        let root_as_relative: PathBuf = root
699
            .components()
700
            .filter(|c| matches!(c, std::path::Component::Normal(_)))
701
            .collect();
702
        let n = root.components().count();
703
        // Start with our the "root" directory of our Dir...
704
        let mut inspect_path = root.to_path_buf();
705
        // Then go way past the root of the filesystem
706
        for _ in 0..n * 2 {
707
            inspect_path.push("..");
708
        }
709
        // Then back down to the "root" directory of the dir..
710
        inspect_path.push(root_as_relative);
711
        // Then to a/b.
712
        inspect_path.push("a/b");
713

            
714
        let r = ResolvePath::new(inspect_path.clone()).unwrap();
715
        let final_path = r.last().unwrap().unwrap().0;
716
        assert_eq!(final_path, inspect_path.canonicalize().unwrap());
717
    }
718
}