dua-core 3.1.0

Fast parallel filesystem traversal iterators
Documentation
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! macOS directory enumeration and metadata collection using `getattrlistbulk`.

use std::{
    ffi::OsString,
    fs, io,
    os::{
        fd::{AsRawFd, OwnedFd},
        unix::fs::{MetadataExt, OpenOptionsExt},
    },
    path::{Path, PathBuf},
    sync::Arc,
    time::SystemTime,
};

mod attributes;

use attributes::{
    AlignedBuffer, ParsedRecord, RecordHeader, SF_FIRMLINK, STAT_BLOCK_BYTES, VDIR, VLNK, VNON,
    VREG, invalid_data, parse_record, read_record_length, requested_attributes,
};

const DIRECTORY_BUFFER_BYTES: usize = 64 * 1024;

/// A macOS filesystem entry produced from native directory metadata.
pub struct Entry {
    /// Distance from the walk root: `0` for the root, `1` and highger for its children.
    pub depth: usize,
    /// File name relative to `parent_path`.
    pub file_name: OsString,
    /// Filesystem entry type without following symbolic links.
    pub file_type: FileType,
    /// Metadata returned while enumerating this entry, or an entry-specific I/O error.
    pub metadata: io::Result<Metadata>,
    /// Path containing this entry.
    pub parent_path: Arc<Path>,
}

impl Entry {
    /// Create an entry for an explicitly requested root without following symbolic links.
    pub fn from_path(path: &Path) -> io::Result<Self> {
        let metadata = Metadata::from_std(&fs::symlink_metadata(path)?);
        Ok(Self {
            depth: 0,
            file_name: path.file_name().unwrap_or(path.as_os_str()).to_owned(),
            file_type: metadata.file_type,
            metadata: Ok(metadata),
            parent_path: Arc::from(path.parent().unwrap_or(Path::new(""))),
        })
    }

    /// Return the full path to this entry.
    #[must_use]
    pub fn path(&self) -> PathBuf {
        self.parent_path.join(&self.file_name)
    }
}

/// macOS filesystem entry type obtained without following symbolic links.
#[derive(Clone, Copy)]
pub struct FileType {
    kind: u32,
}

impl FileType {
    fn from_std(file_type: fs::FileType) -> Self {
        let kind = if file_type.is_dir() {
            VDIR
        } else if file_type.is_file() {
            VREG
        } else if file_type.is_symlink() {
            VLNK
        } else {
            VNON
        };
        Self { kind }
    }

    /// Return whether this entry is a directory that may be traversed.
    #[must_use]
    pub fn is_dir(self) -> bool {
        self.kind == VDIR
    }

    /// Return whether this entry is a regular file.
    #[must_use]
    pub fn is_file(self) -> bool {
        self.kind == VREG
    }

    /// Return whether this entry is a symbolic link.
    #[must_use]
    pub fn is_symlink(self) -> bool {
        self.kind == VLNK
    }
}

/// macOS metadata obtained during native directory enumeration.
#[derive(Clone, Copy)]
pub struct Metadata {
    len: u64,
    allocated_size: u64,
    modified: Option<SystemTime>,
    dev: u64,
    ino: u64,
    nlink: u64,
    file_type: FileType,
}

impl Metadata {
    fn from_std(metadata: &fs::Metadata) -> Self {
        let allocated_size = metadata.blocks().saturating_mul(STAT_BLOCK_BYTES);
        Self {
            len: metadata.len(),
            allocated_size,
            modified: metadata.modified().ok(),
            dev: metadata.dev(),
            ino: metadata.ino(),
            nlink: metadata.nlink(),
            file_type: FileType::from_std(metadata.file_type()),
        }
    }

    /// Return the logical file or directory length.
    #[must_use]
    #[allow(clippy::len_without_is_empty)]
    pub fn len(&self) -> u64 {
        self.len
    }

    /// Return the number of bytes physically allocated to the file or directory.
    #[must_use]
    pub fn allocated_size(&self) -> u64 {
        self.allocated_size
    }

    /// Return the allocated size as 512-byte filesystem accounting blocks.
    #[must_use]
    pub fn blocks(&self) -> u64 {
        self.allocated_size.div_ceil(STAT_BLOCK_BYTES)
    }

    /// Return the last modification time.
    pub fn modified(&self) -> io::Result<SystemTime> {
        self.modified
            .ok_or_else(|| invalid_data("macOS modification time is unavailable"))
    }

    /// Return the device number of the filesystem containing this entry.
    #[must_use]
    pub fn dev(&self) -> u64 {
        self.dev
    }

    /// Return the filesystem inode number.
    #[must_use]
    pub fn ino(&self) -> u64 {
        self.ino
    }

    /// Return the number of hard links to this entry.
    ///
    /// Bulk-enumerated directories use `ATTR_DIR_LINKCOUNT`, which `getattrlist(2)` says
    /// excludes historical `.` and `..` links and can therefore differ from `stat(2)`.
    #[must_use]
    pub fn nlink(&self) -> u64 {
        self.nlink
    }

    /// Return whether this metadata describes a regular file.
    #[must_use]
    pub fn is_file(&self) -> bool {
        self.file_type.is_file()
    }
}

pub(crate) struct ReadDir {
    directory: OwnedFd,
    fallback: Option<fs::ReadDir>,
    buffer: Box<AlignedBuffer<DIRECTORY_BUFFER_BYTES>>,
    offset: usize,
    remaining: usize,
    exhausted: bool,
    listing_error: Option<i32>,
    parent_path: Arc<Path>,
    depth: usize,
}

impl ReadDir {
    pub(crate) fn open(path: Arc<Path>, depth: usize) -> io::Result<Self> {
        let directory: OwnedFd = fs::OpenOptions::new()
            .read(true)
            .custom_flags(libc::O_DIRECTORY)
            .open(&path)?
            .into();
        Ok(Self {
            directory,
            fallback: None,
            buffer: Box::new(AlignedBuffer::new()),
            offset: 0,
            remaining: 0,
            exhausted: false,
            listing_error: None,
            parent_path: path,
            depth,
        })
    }

    /// Refill the bulk-record buffer or activate ordinary directory iteration when the filesystem
    /// does not support bulk enumeration.
    ///
    /// Returns `true` when iteration can continue, either because bulk records are available or
    /// because `self.fallback` was initialized. Returns `false` when the directory is exhausted.
    fn refill(&mut self) -> io::Result<bool> {
        loop {
            let mut attributes = requested_attributes(self.listing_error.is_some());
            // SAFETY: the directory descriptor is owned and remains open, `attributes` is a valid
            // initialized Darwin attrlist, and the aligned buffer is writable for its exact size.
            let count = unsafe {
                libc::getattrlistbulk(
                    self.directory.as_raw_fd(),
                    (&raw mut attributes).cast(),
                    self.buffer.as_mut_bytes().as_mut_ptr().cast(),
                    self.buffer.as_bytes().len(),
                    0,
                )
            };
            if count > 0 {
                self.offset = 0;
                self.remaining = usize::try_from(count)
                    .map_err(|_| invalid_data("macOS directory record count is invalid"))?;
                return Ok(true);
            }
            if count == 0 {
                self.exhausted = true;
                return Ok(false);
            }
            let error = io::Error::last_os_error();
            if error.kind() == io::ErrorKind::Interrupted {
                continue;
            }
            if self.listing_error.is_none() && error.raw_os_error() == Some(libc::EACCES) {
                self.listing_error = Some(libc::EACCES);
                continue;
            }
            if error.kind() == io::ErrorKind::Unsupported
                || error.raw_os_error() == Some(libc::ENOTSUP)
                || error.raw_os_error() == Some(libc::EOPNOTSUPP)
            {
                match fs::read_dir(&self.parent_path) {
                    Ok(entries) => {
                        self.fallback = Some(entries);
                        return Ok(true);
                    }
                    Err(error) => {
                        self.exhausted = true;
                        return Err(error);
                    }
                }
            }
            self.exhausted = true;
            return Err(error);
        }
    }

    fn fallback_entry(&self, entry: fs::DirEntry) -> Entry {
        let file_name = entry.file_name();
        let metadata =
            fs::symlink_metadata(entry.path()).map(|metadata| Metadata::from_std(&metadata));
        let file_type = metadata.as_ref().map_or_else(
            |_| {
                entry
                    .file_type()
                    .map_or(FileType { kind: VNON }, FileType::from_std)
            },
            |metadata| metadata.file_type,
        );
        Entry {
            depth: self.depth,
            file_name,
            file_type,
            metadata,
            parent_path: Arc::clone(&self.parent_path),
        }
    }

    fn next_record(&mut self) -> io::Result<Entry> {
        let bytes = self.buffer.as_bytes();
        let buffer_len = bytes.len();
        if self.offset > buffer_len.saturating_sub(size_of::<u32>()) {
            self.exhausted = true;
            return Err(invalid_data("macOS directory record has no length"));
        }
        let length = read_record_length(&bytes[self.offset..])?;
        let Some(end) = self
            .offset
            .checked_add(length)
            .filter(|end| length >= size_of::<RecordHeader>() && *end <= buffer_len)
        else {
            self.exhausted = true;
            return Err(invalid_data("macOS directory record exceeds its buffer"));
        };
        let record = &bytes[self.offset..end];
        self.offset = end;
        self.remaining -= 1;

        let mut parsed = parse_record(record)?;
        let file_name = parsed
            .file_name
            .take()
            .ok_or_else(|| invalid_data("macOS directory record has no filename"))?;
        let metadata_error = if parsed.error != 0 {
            Some(parsed.error.cast_signed())
        } else {
            self.listing_error
        };
        let file_type = FileType {
            kind: parsed.object_type.unwrap_or(VNON),
        };
        let metadata = if let Some(error) = metadata_error {
            Err(io::Error::from_raw_os_error(error))
        } else {
            if parsed.object_type.is_none() {
                return Err(invalid_data("macOS directory record has no object type"));
            }
            let metadata_from_path = || {
                fs::symlink_metadata(self.parent_path.join(&file_name))
                    .map(|metadata| Metadata::from_std(&metadata))
            };
            // XNU uses NOCROSSMOUNT for bulk lookup; stat the visible mount or firmlink.
            let special_mount = parsed.flags & SF_FIRMLINK != 0
                || parsed.mount_status & libc::DIR_MNTSTATUS_MNTPOINT != 0;
            if special_mount {
                metadata_from_path()
            } else {
                parsed.metadata(file_type).or_else(|_| metadata_from_path())
            }
        };
        let file_type = metadata
            .as_ref()
            .map_or(file_type, |metadata| metadata.file_type);
        Ok(Entry {
            depth: self.depth,
            file_name,
            file_type,
            metadata,
            parent_path: Arc::clone(&self.parent_path),
        })
    }
}

impl Iterator for ReadDir {
    type Item = io::Result<Entry>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(fallback) = &mut self.fallback {
                let entry = fallback.next()?;
                return Some(entry.map(|entry| self.fallback_entry(entry)));
            }
            if self.exhausted {
                return None;
            }
            if self.remaining == 0 {
                match self.refill() {
                    Ok(true) => continue,
                    Ok(false) => return None,
                    Err(error) => return Some(Err(error)),
                }
            }
            match self.next_record() {
                Ok(entry) if entry.file_name == "." || entry.file_name == ".." => {}
                Ok(entry) => return Some(Ok(entry)),
                Err(error) => return Some(Err(error)),
            }
        }
    }
}

impl ParsedRecord {
    fn metadata(&self, file_type: FileType) -> io::Result<Metadata> {
        let (len, allocated_size, nlink) = if file_type.is_dir() {
            (
                self.directory_length
                    .ok_or_else(|| invalid_data("missing directory length"))?,
                self.directory_allocated
                    .ok_or_else(|| invalid_data("missing directory allocation"))?,
                self.directory_links
                    .ok_or_else(|| invalid_data("missing directory hard-link count"))?,
            )
        } else {
            (
                self.file_length
                    .ok_or_else(|| invalid_data("missing file length"))?,
                self.file_allocated
                    .ok_or_else(|| invalid_data("missing file allocation"))?,
                self.file_links
                    .ok_or_else(|| invalid_data("missing file hard-link count"))?,
            )
        };

        Ok(Metadata {
            len,
            allocated_size,
            modified: Some(
                self.modified
                    .ok_or_else(|| invalid_data("missing modification timestamp"))?,
            ),
            dev: self
                .device
                .ok_or_else(|| invalid_data("missing device number"))?,
            ino: self
                .inode
                .ok_or_else(|| invalid_data("missing inode number"))?,
            nlink,
            file_type,
        })
    }
}

#[cfg(test)]
mod tests;