gravityfile-ops 0.4.1

File operations engine for gravityfile
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//! Blocking copy engine shared by copy and cross-filesystem move.
//!
//! A transfer copies one top-level item into a private staging directory on
//! the destination filesystem and publishes it with a single no-clobber
//! rename, so a cancelled or failed transfer never leaves a partial item at
//! the user-visible path. Problems with individual entries inside a directory
//! (unreadable files, sockets, FIFOs) are recorded and skipped rather than
//! discarding everything that did copy.

use std::collections::{HashMap, HashSet};
use std::fs::{self, File};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

use tokio_util::sync::CancellationToken;

use crate::OperationError;
use crate::fs::{RenameError, cancelled, rename_noreplace, staging_dir, unchanged_file};

const CHUNK: usize = 1024 * 1024;
const MAX_RETAINED_ERRORS: usize = 1000;

/// How an existing destination is disposed of when the user chooses to
/// overwrite it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ReplacePolicy {
    /// Move the existing item to the system Trash first (recoverable).
    #[default]
    Trash,
    /// Delete the existing item permanently.
    Permanent,
}

/// Metadata preservation settings for a transfer.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Preserve {
    pub times: bool,
    pub xattrs: bool,
}

/// One transfer's state: cancellation, live byte counter, and the non-fatal
/// per-entry errors collected along the way.
pub(crate) struct Transfer<'a> {
    token: &'a CancellationToken,
    bytes: &'a AtomicU64,
    preserve: Preserve,
    errors: Vec<OperationError>,
    omitted_errors: usize,
    /// First destination path for each multiply-linked source inode.
    links: HashMap<(u64, u64), PathBuf>,
}

impl<'a> Transfer<'a> {
    pub fn new(token: &'a CancellationToken, bytes: &'a AtomicU64, preserve: Preserve) -> Self {
        Self {
            token,
            bytes,
            preserve,
            errors: Vec::new(),
            omitted_errors: 0,
            links: HashMap::new(),
        }
    }

    /// Non-fatal errors, with an omission record when the list was capped.
    pub fn into_errors(self) -> Vec<OperationError> {
        let mut errors = self.errors;
        if self.omitted_errors > 0 {
            errors.push(OperationError::omitted(self.omitted_errors));
        }
        errors
    }

    fn record(&mut self, path: &Path, message: impl Into<String>) {
        if self.errors.len() < MAX_RETAINED_ERRORS {
            self.errors
                .push(OperationError::new(path.to_path_buf(), message));
        } else {
            self.omitted_errors += 1;
        }
    }

    fn check(&self) -> io::Result<()> {
        if self.token.is_cancelled() {
            Err(cancelled())
        } else {
            Ok(())
        }
    }

    /// Copy `source` to the not-yet-existing `destination` through staging.
    ///
    /// With `replace`, an existing destination is disposed of (per the
    /// policy) only after the new copy is complete.
    pub fn copy_staged(
        &mut self,
        source: &Path,
        destination: &Path,
        replace: Option<ReplacePolicy>,
    ) -> io::Result<()> {
        let staging = staging_dir(destination, ".gravityfile-copy-")?;
        let payload = staging.path().join("payload");
        self.copy_entry(source, &payload)?;
        self.check()?;
        if let Some(policy) = replace
            && fs::symlink_metadata(destination).is_ok()
        {
            dispose(destination, policy)?;
        }
        rename_noreplace(&payload, destination).map_err(|error| match error {
            RenameError::DestinationExists => io::Error::new(
                io::ErrorKind::AlreadyExists,
                format!("'{}' appeared while copying", destination.display()),
            ),
            other => other.into(),
        })?;
        if let Err(error) = staging.close() {
            tracing::warn!(%error, "copy published; staging cleanup incomplete");
        }
        Ok(())
    }

    /// Copy one entry of any type. Errors returned here are fatal for the
    /// whole top-level item; problems with nested entries are recorded.
    fn copy_entry(&mut self, source: &Path, destination: &Path) -> io::Result<()> {
        self.check()?;
        let metadata = fs::symlink_metadata(source)?;
        let file_type = metadata.file_type();
        if file_type.is_symlink() {
            self.copy_symlink(source, destination)
        } else if file_type.is_dir() {
            self.copy_tree(source, destination)
        } else if file_type.is_file() {
            self.copy_file(source, destination, &metadata)
        } else {
            Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "sockets, FIFOs and device files cannot be copied",
            ))
        }
    }

    fn copy_symlink(&mut self, source: &Path, destination: &Path) -> io::Result<()> {
        let target = fs::read_link(source)?;
        crate::fs::symlink(&target, source, destination)?;
        if self.preserve.times {
            let metadata = fs::symlink_metadata(source)?;
            filetime::set_symlink_file_times(
                destination,
                filetime::FileTime::from_last_access_time(&metadata),
                filetime::FileTime::from_last_modification_time(&metadata),
            )?;
        }
        Ok(())
    }

    fn copy_tree(&mut self, source: &Path, destination: &Path) -> io::Result<()> {
        let mut pending = vec![(source.to_path_buf(), destination.to_path_buf())];
        let mut finished: Vec<(PathBuf, PathBuf, fs::Metadata)> = Vec::new();
        let mut visited: HashSet<(u64, u64)> = HashSet::new();
        let mut is_root = true;

        while let Some((source_dir, dest_dir)) = pending.pop() {
            self.check()?;
            let metadata = match fs::symlink_metadata(&source_dir) {
                Ok(metadata) if metadata.is_dir() => metadata,
                Ok(_) if !is_root => {
                    self.record(&source_dir, "changed type while copying; skipped");
                    continue;
                }
                Ok(_) => return Err(io::Error::other("source directory changed type")),
                Err(error) if !is_root => {
                    self.record(&source_dir, error.to_string());
                    continue;
                }
                Err(error) => return Err(error),
            };
            if let Some(identity) = identity(&metadata)
                && !visited.insert(identity)
            {
                self.record(&source_dir, "directory reached twice (mount loop); skipped");
                continue;
            }
            // The root must be created; nested directories that fail are
            // recorded and skipped.
            match fs::create_dir(&dest_dir) {
                Ok(()) => {}
                Err(error) if is_root => return Err(error),
                Err(error) => {
                    self.record(&dest_dir, format!("cannot create directory: {error}"));
                    continue;
                }
            }
            is_root = false;
            finished.push((source_dir.clone(), dest_dir.clone(), metadata));

            let entries = match fs::read_dir(&source_dir) {
                Ok(entries) => entries,
                Err(error) => {
                    self.record(&source_dir, format!("cannot read directory: {error}"));
                    continue;
                }
            };
            for entry in entries {
                self.check()?;
                let entry = match entry {
                    Ok(entry) => entry,
                    Err(error) => {
                        self.record(&source_dir, format!("cannot read entry: {error}"));
                        continue;
                    }
                };
                let path = entry.path();
                let target = dest_dir.join(entry.file_name());
                let file_type = match entry.file_type() {
                    Ok(file_type) => file_type,
                    Err(error) => {
                        self.record(&path, error.to_string());
                        continue;
                    }
                };
                if file_type.is_dir() {
                    pending.push((path, target));
                    continue;
                }
                let result = if file_type.is_symlink() {
                    self.copy_symlink(&path, &target)
                } else if file_type.is_file() {
                    fs::symlink_metadata(&path)
                        .and_then(|metadata| self.copy_file(&path, &target, &metadata))
                } else {
                    self.record(&path, "special file (socket, FIFO or device) skipped");
                    continue;
                };
                match result {
                    Ok(()) => {}
                    Err(error) if error.kind() == io::ErrorKind::Interrupted => return Err(error),
                    Err(error) => {
                        let _ = fs::remove_file(&target);
                        self.record(&path, error.to_string());
                    }
                }
            }
        }

        // Apply modes and times bottom-up, after contents exist: a read-only
        // directory must not prevent its own population.
        for (source_dir, directory, metadata) in finished.into_iter().rev() {
            self.check()?;
            if self.preserve.xattrs {
                copy_xattrs(&source_dir, &directory);
            }
            if self.preserve.times {
                let _ = filetime::set_file_times(
                    &directory,
                    filetime::FileTime::from_last_access_time(&metadata),
                    filetime::FileTime::from_last_modification_time(&metadata),
                );
            }
            if let Err(error) = fs::set_permissions(&directory, metadata.permissions()) {
                self.record(&directory, format!("cannot restore permissions: {error}"));
            }
        }
        Ok(())
    }

    fn copy_file(
        &mut self,
        source: &Path,
        destination: &Path,
        metadata: &fs::Metadata,
    ) -> io::Result<()> {
        if let Some(key) = identity(metadata).filter(|_| link_count(metadata) > 1) {
            if let Some(first) = self.links.get(&key) {
                if fs::hard_link(first, destination).is_ok() {
                    return Ok(());
                }
            } else {
                self.links.insert(key, destination.to_path_buf());
            }
        }

        // Copy-on-write clone: instant on APFS, Btrfs, XFS, ReFS. The
        // destination lives in private staging, so cleanup after a failed
        // attempt cannot touch anything else.
        if metadata.len() > 0 && reflink_copy::reflink(source, destination).is_ok() {
            self.bytes.fetch_add(metadata.len(), Ordering::Relaxed);
            self.finish_file(source, destination, metadata, cfg!(target_vendor = "apple"))?;
            return Ok(());
        }
        let _ = fs::remove_file(destination);

        let mut input = open_regular(source)?;
        let opened = input.metadata()?;
        if !unchanged_file(metadata, &opened) {
            return Err(io::Error::other("file changed while opening"));
        }
        let mut output = fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(destination)?;
        self.copy_contents(&mut input, &mut output, opened.len())?;
        if !unchanged_file(&opened, &input.metadata()?) {
            return Err(io::Error::other("file changed while copying"));
        }
        output.set_permissions(opened.permissions())?;
        drop(output);
        self.finish_file(source, destination, &opened, false)
    }

    fn finish_file(
        &self,
        source: &Path,
        destination: &Path,
        metadata: &fs::Metadata,
        metadata_cloned: bool,
    ) -> io::Result<()> {
        if self.preserve.xattrs && !metadata_cloned {
            copy_xattrs(source, destination);
        }
        if self.preserve.times {
            filetime::set_file_times(
                destination,
                filetime::FileTime::from_last_access_time(metadata),
                filetime::FileTime::from_last_modification_time(metadata),
            )?;
        }
        Ok(())
    }

    /// Copy exactly `length` bytes in cancellable chunks.
    fn copy_contents(&self, input: &mut File, output: &mut File, length: u64) -> io::Result<()> {
        let mut remaining = length;
        #[cfg(any(target_os = "linux", target_os = "android"))]
        {
            // `io::copy` between files uses copy_file_range/sendfile.
            while remaining > 0 {
                self.check()?;
                let chunk = remaining.min(CHUNK as u64);
                let copied = io::copy(&mut Read::by_ref(input).take(chunk), output)?;
                if copied == 0 {
                    return Err(io::Error::other("file shrank while copying"));
                }
                remaining -= copied;
                self.bytes.fetch_add(copied, Ordering::Relaxed);
            }
        }
        #[cfg(not(any(target_os = "linux", target_os = "android")))]
        {
            use std::io::{Seek, Write};
            let mut buffer = vec![0u8; (length.clamp(1, CHUNK as u64)) as usize];
            let mut sparse = cfg!(unix);
            while remaining > 0 {
                self.check()?;
                let amount = remaining.min(buffer.len() as u64) as usize;
                input.read_exact(&mut buffer[..amount])?;
                if sparse && buffer[..amount].iter().all(|byte| *byte == 0) {
                    if output.seek(io::SeekFrom::Current(amount as i64)).is_err() {
                        sparse = false;
                        output.write_all(&buffer[..amount])?;
                    }
                } else {
                    output.write_all(&buffer[..amount])?;
                }
                remaining -= amount as u64;
                self.bytes.fetch_add(amount as u64, Ordering::Relaxed);
            }
            // A trailing hole is only materialized by extending the length.
            output.set_len(length)?;
        }
        let mut probe = [0u8; 1];
        if input.read(&mut probe)? != 0 {
            return Err(io::Error::other("file grew while copying"));
        }
        Ok(())
    }
}

/// Dispose of an existing destination before replacing it.
pub(crate) fn dispose(path: &Path, policy: ReplacePolicy) -> io::Result<()> {
    match policy {
        ReplacePolicy::Trash => crate::delete::trash_context()
            .delete(path)
            .map_err(|error| {
                io::Error::other(format!(
                    "could not move the existing item to the Trash ({error}); it was left in place"
                ))
            }),
        ReplacePolicy::Permanent => crate::fs::remove_path(path),
    }
}

fn open_regular(path: &Path) -> io::Result<File> {
    let mut options = fs::OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        // Never follow a symlink swapped in after inspection, and never block
        // on a FIFO swapped in for a regular file.
        options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
    }
    let file = options.open(path)?;
    if !file.metadata()?.is_file() {
        return Err(io::Error::other("not a regular file"));
    }
    Ok(file)
}

#[cfg(unix)]
fn identity(metadata: &fs::Metadata) -> Option<(u64, u64)> {
    use std::os::unix::fs::MetadataExt;
    Some((metadata.dev(), metadata.ino()))
}

#[cfg(not(unix))]
fn identity(_metadata: &fs::Metadata) -> Option<(u64, u64)> {
    None
}

#[cfg(unix)]
fn link_count(metadata: &fs::Metadata) -> u64 {
    use std::os::unix::fs::MetadataExt;
    metadata.nlink()
}

#[cfg(not(unix))]
fn link_count(_metadata: &fs::Metadata) -> u64 {
    1
}

/// Best-effort extended attribute copy (Finder tags, quarantine, SELinux
/// labels...). Filesystems without xattr support are silently skipped.
#[cfg(unix)]
fn copy_xattrs(source: &Path, destination: &Path) {
    let Ok(names) = xattr::list(source) else {
        return;
    };
    for name in names {
        if let Ok(Some(value)) = xattr::get(source, &name)
            && let Err(error) = xattr::set(destination, &name, &value)
        {
            tracing::debug!(path = %destination.display(), ?name, %error, "xattr not copied");
        }
    }
}

#[cfg(not(unix))]
fn copy_xattrs(_source: &Path, _destination: &Path) {}

#[cfg(test)]
mod tests {
    use super::*;

    fn run(source: &Path, destination: &Path) -> (io::Result<()>, Vec<OperationError>, u64) {
        let token = CancellationToken::new();
        let bytes = AtomicU64::new(0);
        let mut transfer = Transfer::new(
            &token,
            &bytes,
            Preserve {
                times: true,
                xattrs: true,
            },
        );
        let result = transfer.copy_staged(source, destination, None);
        (result, transfer.into_errors(), bytes.into_inner())
    }

    #[test]
    fn copies_tree_with_contents_and_counts_bytes() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("src");
        fs::create_dir_all(source.join("a/b")).unwrap();
        fs::write(source.join("a/b/file"), vec![7u8; 3 * CHUNK + 5]).unwrap();
        fs::write(source.join("top"), "x").unwrap();
        let destination = dir.path().join("dst");
        let (result, errors, bytes) = run(&source, &destination);
        result.unwrap();
        assert!(errors.is_empty(), "{errors:?}");
        assert_eq!(bytes, 3 * CHUNK as u64 + 6);
        assert_eq!(
            fs::read(destination.join("a/b/file")).unwrap().len(),
            3 * CHUNK + 5
        );
        assert_eq!(fs::read_to_string(destination.join("top")).unwrap(), "x");
        assert!(!dir.path().read_dir().unwrap().any(|entry| {
            entry
                .unwrap()
                .file_name()
                .to_string_lossy()
                .starts_with(".gravityfile-")
        }));
    }

    #[cfg(unix)]
    #[test]
    fn unreadable_and_special_entries_are_skipped_not_fatal() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("src");
        fs::create_dir(&source).unwrap();
        fs::write(source.join("ok"), "fine").unwrap();
        let secret = source.join("secret");
        fs::write(&secret, "no").unwrap();
        fs::set_permissions(&secret, fs::Permissions::from_mode(0o000)).unwrap();
        let fifo =
            std::ffi::CString::new(source.join("fifo").into_os_string().into_encoded_bytes())
                .unwrap();
        // SAFETY: valid NUL-terminated path.
        assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o600) }, 0);
        let destination = dir.path().join("dst");
        let (result, errors, _) = run(&source, &destination);
        fs::set_permissions(&secret, fs::Permissions::from_mode(0o600)).unwrap();
        result.unwrap();
        assert_eq!(fs::read_to_string(destination.join("ok")).unwrap(), "fine");
        assert!(fs::symlink_metadata(destination.join("fifo")).is_err());
        assert!(errors.iter().any(|error| error.path.ends_with("fifo")));
        // Root may read anything; only assert the skip when it actually failed.
        if !destination.join("secret").exists() {
            assert!(errors.iter().any(|error| error.path.ends_with("secret")));
        }
    }

    #[cfg(unix)]
    #[test]
    fn hard_links_and_read_only_directories_are_preserved() {
        use std::os::unix::fs::{MetadataExt, PermissionsExt};
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("src");
        let locked = source.join("locked");
        fs::create_dir_all(&locked).unwrap();
        fs::write(locked.join("a"), "shared").unwrap();
        fs::hard_link(locked.join("a"), locked.join("b")).unwrap();
        fs::set_permissions(&locked, fs::Permissions::from_mode(0o555)).unwrap();
        let destination = dir.path().join("dst");
        let (result, errors, _) = run(&source, &destination);
        fs::set_permissions(&locked, fs::Permissions::from_mode(0o755)).unwrap();
        result.unwrap();
        assert!(errors.is_empty(), "{errors:?}");
        let copied = destination.join("locked");
        assert_eq!(
            fs::metadata(&copied).unwrap().permissions().mode() & 0o777,
            0o555
        );
        assert_eq!(
            fs::metadata(copied.join("a")).unwrap().ino(),
            fs::metadata(copied.join("b")).unwrap().ino()
        );
        fs::set_permissions(&copied, fs::Permissions::from_mode(0o755)).unwrap();
    }

    #[test]
    fn cancellation_leaves_nothing_at_the_destination() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("src");
        fs::create_dir(&source).unwrap();
        fs::write(source.join("file"), "x").unwrap();
        let token = CancellationToken::new();
        token.cancel();
        let bytes = AtomicU64::new(0);
        let mut transfer = Transfer::new(
            &token,
            &bytes,
            Preserve {
                times: false,
                xattrs: false,
            },
        );
        let destination = dir.path().join("dst");
        let error = transfer
            .copy_staged(&source, &destination, None)
            .unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::Interrupted);
        assert!(!destination.exists());
        assert_eq!(dir.path().read_dir().unwrap().count(), 1);
    }

    #[test]
    fn replace_disposes_existing_item_only_after_copy_completes() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("new");
        let destination = dir.path().join("old");
        fs::write(&source, "new").unwrap();
        fs::write(&destination, "old").unwrap();
        let token = CancellationToken::new();
        let bytes = AtomicU64::new(0);
        let mut transfer = Transfer::new(
            &token,
            &bytes,
            Preserve {
                times: true,
                xattrs: false,
            },
        );
        transfer
            .copy_staged(&source, &destination, Some(ReplacePolicy::Permanent))
            .unwrap();
        assert_eq!(fs::read_to_string(&destination).unwrap(), "new");
    }
}