1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use std::cell::OnceCell;
use std::ffi::CStr;
use std::ffi::c_char;
use std::os::unix::ffi::OsStringExt;
use std::path::Path;

use crate::Tag;

type Result<T> = std::result::Result<T, std::io::Error>;

pub(crate) struct FileType(u8);

impl FileType {
    /// Whether a file is a directory.
    ///
    /// According to glibc's documentation:
    ///
    ///   Currently, only some filesystems (among them: Btrfs, ext2,
    ///   ext3, and ext4) have full support for returning the file type
    ///   in d_type.  All applications must properly handle a re‐ turn
    ///   of DT_UNKNOWN.
    pub fn is_dir(&self) -> bool {
        self.0 == libc::DT_DIR
    }

    /// Whether a file's type is not known.
    pub fn is_unknown(&self) -> bool {
        self.0 == libc::DT_UNKNOWN
    }
}

// Not all Unix platforms have 64-bit variants of stat64, etc.  Rust's
// libc doesn't define a nice way to figure out if those functions are
// available.  Eventually, we can use something like:
//
//   #[cfg_accessible(libc::stat64)]
//
// (See https://github.com/rust-lang/rust/issues/64797), but that
// hasn't been stabilized yet.
//
// For now, we copy Rust's libc's strategy:
//
//   https://github.com/rust-lang/rust/blob/96df4943409564a187894018f15f795426dc2e1f/library/std/src/sys/unix/fs.rs#L67
#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "hurd"))]
mod libc64 {
    pub(super) use libc::stat64 as stat;
    pub(super) use libc::fstatat64 as fstatat;
    pub(super) use libc::dirent64 as dirent;
    pub(super) use libc::readdir64 as readdir;
}
#[cfg(not(any(all(target_os = "linux", not(target_env = "musl")), target_os = "hurd")))]
mod libc64 {
    pub(super) use libc::stat;
    pub(super) use libc::fstatat;
    pub(super) use libc::dirent;
    pub(super) use libc::readdir;
}

/// A thin wrapper around a `libc::stat64`.
pub(crate) struct Metadata(libc64::stat);

impl Metadata {
    /// The size.
    pub fn size(&self) -> u64 {
        self.0.st_size as u64
    }

    /// The modification time as the time since the Unix epoch.
    pub fn modified(&self) -> std::time::Duration {
        // Netbsd-like systems.  See:
        // https://github.com/rust-lang/libc/blob/a0f5b4b21391252fe38b2df9310dc65e37b07d9f/src/unix/bsd/mod.rs#L931
        #[cfg(any(target_os = "openbsd", target_os = "netbsd"))]
        return std::time::Duration::new(
            self.0.st_mtime as u64,
            self.0.st_mtimensec as u32);

        #[cfg(not(any(target_os = "openbsd", target_os = "netbsd")))]
        return std::time::Duration::new(
            self.0.st_mtime as u64,
            self.0.st_mtime_nsec as u32);
    }

    /// Whether a file is a directory.
    pub fn is_dir(&self) -> bool {
        (self.0.st_mode & libc::S_IFMT) == libc::S_IFDIR
    }
}

impl std::convert::From<&crate::unixdir::Metadata> for Tag {
    fn from(m: &Metadata) -> Self {
        let d = m.modified();
        let size = m.size();

        Tag::new(d.as_secs(), d.subsec_nanos(), size, m.is_dir())
    }
}

impl Metadata {
    fn fstat(dir: *mut libc::DIR,
             nul_terminated_filename: &[u8])
             -> Result<Self>
    {
        // The last character must be a NUL, i.e., this has to be a c string.
        assert_eq!(nul_terminated_filename[nul_terminated_filename.len() - 1],
                   0);

        let dirfd = unsafe { libc::dirfd(dir) };
        if dirfd == -1 {
            return Err(std::io::Error::last_os_error());
        }

        let mut statbuf = std::mem::MaybeUninit::<libc64::stat>::uninit();

        let result = unsafe {
            libc64::fstatat(
                dirfd,
                nul_terminated_filename.as_ptr() as *const c_char,
                statbuf.as_mut_ptr(),
                libc::AT_SYMLINK_NOFOLLOW,
            )
        };
        if result == -1 {
            return Err(std::io::Error::last_os_error());
        }

        Ok(Metadata(unsafe { statbuf.assume_init() }))
    }
}

/// A thin wrapper for a `libc::dirent64`.
///
/// [`libc::dirent64`](https://docs.rs/libc/latest/libc/struct.dirent64.html)
pub(crate) struct DirEntry {
    dir: *mut libc::DIR,
    entry: *mut libc64::dirent,
    name_len: OnceCell<usize>,
    // We save the metadata inline to avoid a heap allocation.
    metadata: OnceCell<Result<Metadata>>,
}

impl DirEntry {
    /// Returns the file's type, as recorded in the directory.
    pub fn file_type(&self) -> FileType {
        FileType(unsafe { *self.entry }.d_type)
    }

    /// Returns the filename.
    ///
    /// Note: this is not NUL terminated.
    pub fn file_name(&self) -> &[u8] {
        unsafe {
            let name = (*self.entry).d_name.as_ptr() as *const c_char;

            let name_len = *self.name_len.get_or_init(|| {
                // According to the Single Unix Specification:
                //
                //   The character array d_name is of unspecified
                //   size, but the number of bytes preceding the
                //   terminating null byte will not exceed {NAME_MAX}.
                //
                // https://pubs.opengroup.org/onlinepubs/007908799/xsh/dirent.h.html
                //
                // All platforms that I check use 256 bytes. Don't
                // hard code that (but do sanity check it).
                let max_len = std::mem::size_of_val(&(*self.entry).d_name);
                assert!(max_len >= 128);
                libc::strnlen(name, max_len)
            });

            std::slice::from_raw_parts(
                name as *const u8,
                name_len)
        }
    }

    /// Stats the file.
    ///
    /// To avoid a heap allocation, the data struct is stored inline.
    /// To avoid races, the lifetime is bound to self.
    pub fn metadata(&self) -> Result<&Metadata> {
        // Rewrite this to use OnceCell::get_or_try_init once that has
        // stabilized.  Until then we do a little dance with the
        // Result.
        let result = self.metadata.get_or_init(|| {
            let dirfd = unsafe { libc::dirfd(self.dir) };
            if dirfd == -1 {
                return Err(std::io::Error::last_os_error());
            }

            let mut statbuf = std::mem::MaybeUninit::<libc64::stat>::uninit();

            let result = unsafe {
                libc64::fstatat(
                    dirfd,
                    (*self.entry).d_name.as_ptr() as *const c_char,
                    statbuf.as_mut_ptr(),
                    libc::AT_SYMLINK_NOFOLLOW,
                )
            };
            if result == -1 {
                return Err(std::io::Error::last_os_error());
            }

            Ok(Metadata(unsafe { statbuf.assume_init() }))
        });

        match result {
            Ok(metadata) => Ok(metadata),
            Err(err) => {
                if let Some(underlying) = err.get_ref() {
                    // We can't clone the error, so we clone the error
                    // kind and turn the error into a string.  It's
                    // not great, but its good enough for us.
                    Err(std::io::Error::new(
                        err.kind(),
                        underlying.to_string()))
                } else {
                    Err(std::io::Error::from(err.kind()))
                }
            },
        }
    }
}

pub(crate) struct Dir {
    dir: Option<*mut libc::DIR>,
    entry: Option<DirEntry>,
}

impl Drop for Dir {
    fn drop(&mut self) {
        if let Some(dir) = self.dir.take() {
            unsafe { libc::closedir(dir) };
        }
    }
}

impl Dir {
    pub fn open(dir: &Path) -> Result<Self> {
        let mut dir = dir.as_os_str().to_os_string().into_vec();
        // NUL-terminate it.
        dir.push(0);
        let dir = unsafe { CStr::from_ptr(dir.as_ptr() as *const c_char) };
        let dir = unsafe { libc::opendir(dir.as_ptr().cast()) };
        if dir.is_null() {
            return Err(std::io::Error::last_os_error());
        }

        let dir = Dir {
            dir: Some(dir),
            entry: None,
        };
        Ok(dir)
    }

    /// Get the next directory entry.
    ///
    /// Returns None, if the end of directory has been reached.
    ///
    /// DirEntry is deallocated when the directory pointer is
    /// advanced.  Hence, the lifetime of the returned DirEntry is
    /// tied to the lifetime of the &mut to self.
    pub fn readdir(&mut self) -> Option<&mut DirEntry> {
       let dir = self.dir?;

        let entry = unsafe { libc64::readdir(dir) };
        if entry.is_null() {
            unsafe { libc::closedir(dir) };
            self.dir = None;
            return None;
        }

        self.entry = Some(DirEntry {
            dir,
            entry,
            name_len: OnceCell::default(),
            metadata: OnceCell::default(),
        });
        self.entry.as_mut()
    }

    /// Stat an entry in the directory.
    pub fn fstat(&mut self, nul_terminated_filename: &[u8]) -> Result<Metadata> {
        let dir = self.dir.ok_or_else(|| {
            std::io::Error::new(std::io::ErrorKind::Other, "Directory closed")
        })?;

        Metadata::fstat(dir, nul_terminated_filename)
    }
}