ctb_io_csc/archive/
cli.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Command-line interface definitions and dispatch for archive operations.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use crate::journal::capture::{
30    CapturedSource, CapturedTree, CommittedHardlinks, attach_environment,
31};
32use crate::journal::{
33    JournalErrorRecord, JournalErrorStage, JournalSessionRecord,
34    JournalWarningRecord, current_platform,
35};
36use crate::journal::{JournalReader, JournalWriter};
37use clap::{Parser, Subcommand};
38use ctb_io::file::apple_double::AppleReadOptions;
39use ctb_io::file::{
40    DiskPayloadSource, FileEntity, FileEntityKind, FileOrigin, LinkPath,
41    MaterializeOptions, PathTraversalPolicy, PayloadSource, SandboxableDir,
42    SymlinkValidationPolicy, TraversalOptions, path_has_trailing_slash,
43    resolve_existing_ancestors,
44};
45use ctb_utilities::cli::ToolResult;
46use std::collections::{HashMap, HashSet};
47use std::fs::{File, OpenOptions};
48use std::io::{BufWriter, Read, Seek, SeekFrom, Write};
49use std::path::{Component, Path, PathBuf};
50
51#[derive(Debug, Clone, Parser)]
52pub struct ArchiveArgs {
53    #[command(subcommand)]
54    pub command: ArchiveCommand,
55}
56
57#[derive(clap::Args, Debug, Clone, PartialEq, Eq, Default)]
58pub struct ArchiveCreateOptions {
59    /// Record full provenance environment information using slow environment detection
60    /// (e.g. network discovery for public IP addresses and server time synchronization).
61    #[arg(long)]
62    pub full_provenance: bool,
63    /// Behavior when a source file is modified during capture.
64    #[arg(long, value_enum, default_value_t = crate::args::SourceChangePolicy::Error)]
65    pub on_source_change: crate::args::SourceChangePolicy,
66    /// Stay on the current filesystem and do not cross mount boundaries.
67    #[arg(short = 'x', long = "one-file-system")]
68    pub one_file_system: bool,
69    /// Optional AppleDouble, AppleSingle, and Windows ADS companion reading flags.
70    #[command(flatten)]
71    pub apple_read: crate::args::AppleReadCliArgs,
72}
73
74#[derive(Debug, Clone, Subcommand)]
75pub enum ArchiveCommand {
76    /// Create a self-contained uncompressed CSC archive.
77    ///
78    /// When writing to `-` (stdout) with shell redirection (for example,
79    /// `> archive.cscarchive`), the shell truncates an existing target file
80    /// before `ctb` starts; that truncation cannot be undone by the program.
81    Create {
82        /// Archive output path, or - for binary stdout.
83        archive: PathBuf,
84        #[arg(required_unless_present = "resume", conflicts_with = "resume", num_args = 1..)]
85        sources: Vec<PathBuf>,
86        /// Resume an interrupted file-output archive using its recorded sources.
87        #[arg(long)]
88        resume: bool,
89        /// Retain source failures, continue capture, and report nonzero status.
90        #[arg(long, conflicts_with = "resume")]
91        continue_on_error: bool,
92        /// Write as journal format (different magic bytes, omits stream or file bodies).
93        #[arg(long)]
94        journal: bool,
95        #[command(flatten)]
96        options: ArchiveCreateOptions,
97    },
98    /// List committed members and capture diagnostics.
99    List { archive: PathBuf },
100    /// Verify archive structure, checksums, and file contents without sources.
101    Verify {
102        archive: PathBuf,
103        /// Allow verification of incomplete archives or archives containing capture errors.
104        #[arg(
105            long,
106            alias = "salvage",
107            alias = "allow-archive-errors",
108            alias = "allow-journal-errors"
109        )]
110        recover: bool,
111    },
112    /// Extract a verified archive beneath a destination directory.
113    Extract {
114        archive: PathBuf,
115        destination: PathBuf,
116        /// Replace existing regular files atomically; merge existing directories.
117        #[arg(long)]
118        overwrite: bool,
119        /// Preserve link targets verbatim, including targets outside destination.
120        #[arg(long)]
121        trust_symlink_targets: bool,
122        /// Report filesystem metadata losses instead of requiring exact restoration.
123        #[arg(long)]
124        best_effort_metadata: bool,
125        /// Require every timestamp check, including hard platform limits.
126        #[arg(long)]
127        strict: bool,
128        /// Verify restored access times.
129        #[arg(long)]
130        check_atime: bool,
131        /// Verify change times even where the platform cannot restore them.
132        #[arg(long)]
133        check_ctime: bool,
134        /// Verify birth times even where the platform cannot restore them.
135        #[arg(long)]
136        check_birthtime: bool,
137        /// Permit restoration of FIFOs and device nodes as special files.
138        #[arg(long)]
139        copy_specials_as_specials: bool,
140        /// Extract committed members from incomplete archives or archives containing capture errors.
141        #[arg(
142            long,
143            alias = "salvage",
144            alias = "allow-archive-errors",
145            alias = "allow-journal-errors"
146        )]
147        recover: bool,
148        /// Optional AppleDouble, AppleSingle, and Windows ADS stream restoration flags.
149        #[command(flatten)]
150        apple_write: crate::args::AppleWriteCliArgs,
151    },
152}
153
154pub fn run_archive(args: &ArchiveArgs) -> Result<ToolResult> {
155    run_archive_with_stdout(args, None)
156}
157
158pub(crate) fn run_archive_with_stdout(
159    args: &ArchiveArgs,
160    stdout_override: Option<File>,
161) -> Result<ToolResult> {
162    match &args.command {
163        ArchiveCommand::Create {
164            archive,
165            sources,
166            resume,
167            continue_on_error,
168            journal,
169            options: create_options,
170        } => {
171            let _scope = if create_options.full_provenance {
172                ctb_io_environment::GlobalEnvironmentScope::enter_full()
173            } else {
174                ctb_io_environment::GlobalEnvironmentScope::enter_fresh()
175            };
176            if *resume {
177                ensure!(
178                    !continue_on_error,
179                    "Cannot combine --resume with --continue-on-error; capture diagnostics cannot be resolved by resume"
180                );
181                ensure!(
182                    archive != Path::new("-"),
183                    "Cannot resume archive output on stdout"
184                );
185                resume_archive_with_options(archive, *journal, create_options)?;
186                return Ok(ToolResult::Immediate {
187                    stdout: Vec::new(),
188                    stderr: b"Archive resumed and completed.\n".to_vec(),
189                    exit_code: 0,
190                });
191            }
192            let stdout_handle = if archive == Path::new("-") {
193                if let Some(ref file) = stdout_override {
194                    Some(file.try_clone()?)
195                } else {
196                    clone_stdout_file()?
197                }
198            } else {
199                None
200            };
201            if let Some(ref output) = stdout_handle {
202                validate_output_identity(output, sources, &[])?;
203            }
204            let plan =
205                plan_sources_with_options(sources, archive, create_options)?;
206            let (error_count, warning_count, completed) = if archive
207                == Path::new("-")
208            {
209                if let Some(ref output) = stdout_handle {
210                    validate_output_identity(output, sources, &plan.members)?;
211                }
212                if let Some(file) = stdout_override {
213                    let outcome = create_archive_with_options(
214                        ForwardFileOutput(file),
215                        sources,
216                        archive,
217                        &plan,
218                        *continue_on_error,
219                        None,
220                        *journal,
221                        create_options,
222                    )?;
223                    (
224                        outcome.error_count,
225                        outcome.warning_count,
226                        outcome.completed,
227                    )
228                } else {
229                    let outcome = create_archive_with_options(
230                        std::io::stdout().lock(),
231                        sources,
232                        archive,
233                        &plan,
234                        *continue_on_error,
235                        None,
236                        *journal,
237                        create_options,
238                    )?;
239                    (
240                        outcome.error_count,
241                        outcome.warning_count,
242                        outcome.completed,
243                    )
244                }
245            } else {
246                let mut options = OpenOptions::new();
247                options.write(true).create_new(true);
248                #[cfg(unix)]
249                {
250                    use std::os::unix::fs::OpenOptionsExt;
251                    options.mode(0o600);
252                }
253                let file = options.open(archive).with_context(|| {
254                    format!("Cannot create {}", archive.display())
255                })?;
256                if let Err(error) =
257                    validate_output_identity(&file, sources, &plan.members)
258                {
259                    drop(file);
260                    let _ = std::fs::remove_file(archive);
261                    return Err(error);
262                }
263                let outcome = create_archive_with_options(
264                    FileArchiveOutput::new(file),
265                    sources,
266                    archive,
267                    &plan,
268                    *continue_on_error,
269                    None,
270                    *journal,
271                    create_options,
272                )?;
273                (
274                    outcome.error_count,
275                    outcome.warning_count,
276                    outcome.completed,
277                )
278            };
279            let clean = completed && error_count == 0 && warning_count == 0;
280            Ok(ToolResult::Immediate {
281                stdout: Vec::new(),
282                stderr: if clean {
283                    b"Archive created.\n".to_vec()
284                } else {
285                    format!("Archive capture {}: {error_count} errors; {warning_count} warnings.\n",
286                        if completed { "finished with diagnostics" } else { "stopped incomplete" }).into_bytes()
287                },
288                exit_code: i32::from(!clean),
289            })
290        }
291        ArchiveCommand::List { archive } => {
292            let reader = JournalReader::recover(File::open(archive)?)?;
293            validate_members(&reader)?;
294            let mut output = String::new();
295            use std::fmt::Write;
296            for member in &reader.members {
297                let size = match &member.entity.kind {
298                    FileEntityKind::Regular { size, .. } => *size,
299                    _ => 0,
300                };
301                let path = member
302                    .entity
303                    .identity
304                    .relative_path
305                    .as_deref()
306                    .context("Archive member has no path")?;
307                writeln!(
308                    output,
309                    "{}\t{size}\t{}",
310                    member.entity.kind.entity_type().as_str(),
311                    path.display()
312                )?;
313            }
314            let mut diagnostics = String::new();
315            if !reader.is_completed() {
316                diagnostics.push_str(
317                    "Archive is incomplete; listing committed members only.\n",
318                );
319            }
320            for member in &reader.members {
321                if let Err(error) =
322                    crate::journal::stream::ensure_clean_metadata(
323                        &member.entity,
324                    )
325                {
326                    writeln!(
327                        diagnostics,
328                        "Member diagnostics {}: {error:#}",
329                        member.entity.identity.display_path()
330                    )?;
331                }
332            }
333            for error in &reader.errors {
334                writeln!(
335                    diagnostics,
336                    "Capture error ({:?}) {}: {}",
337                    error.stage,
338                    error.path.display(),
339                    error.error_message
340                )?;
341            }
342            for warning in &reader.warnings {
343                writeln!(
344                    diagnostics,
345                    "Capture warning ({}): {}",
346                    warning.code, warning.message
347                )?;
348            }
349            if reader.has_diagnostics() {
350                writeln!(
351                    diagnostics,
352                    "Capture errors: {}; warnings: {}. Archive is not a clean capture.",
353                    reader.errors.len(),
354                    reader.warnings.len()
355                )?;
356            }
357            Ok(ToolResult::Immediate {
358                stdout: output.into_bytes(),
359                stderr: diagnostics.into_bytes(),
360                exit_code: i32::from(
361                    !(reader.is_completed() && !reader.has_diagnostics()),
362                ),
363            })
364        }
365        ArchiveCommand::Verify { archive, recover } => {
366            let reader = if *recover {
367                JournalReader::read(
368                    File::open(archive)?,
369                    crate::journal::ReadMode::Recover,
370                    &ctb_formats_dcstring::DcProjectionPolicy::forgiving(),
371                )?
372            } else {
373                JournalReader::new(File::open(archive)?)?
374            };
375            if *recover {
376                reader.verify_recover()?;
377            } else {
378                reader.verify_self_contained()?;
379            }
380            validate_members(&reader)?;
381            let mut diagnostics = String::new();
382            use std::fmt::Write;
383            let member_diagnostics =
384                append_reader_diagnostics(&reader, &mut diagnostics)?;
385            if *recover
386                && (!reader.is_completed()
387                    || reader.has_diagnostics()
388                    || member_diagnostics > 0)
389            {
390                writeln!(
391                    diagnostics,
392                    "Archive verified in recover mode (incomplete: {}; errors: {}; warnings: {}; member_diagnostics: {}). Archive is not a clean capture.",
393                    !reader.is_completed(),
394                    reader.errors.len(),
395                    reader.warnings.len(),
396                    member_diagnostics
397                )?;
398                Ok(ToolResult::Immediate {
399                    stdout: b"Archive verified (with diagnostics).\n".to_vec(),
400                    stderr: diagnostics.into_bytes(),
401                    exit_code: 1,
402                })
403            } else {
404                Ok(ToolResult::immediate_ok(b"Archive verified.\n".to_vec()))
405            }
406        }
407        ArchiveCommand::Extract {
408            archive,
409            destination,
410            overwrite,
411            trust_symlink_targets,
412            best_effort_metadata,
413            strict,
414            check_atime,
415            check_ctime,
416            check_birthtime,
417            copy_specials_as_specials,
418            recover,
419            apple_write,
420        } => {
421            let reader = if *recover {
422                JournalReader::read(
423                    File::open(archive)?,
424                    crate::journal::ReadMode::Recover,
425                    &ctb_formats_dcstring::DcProjectionPolicy::forgiving(),
426                )?
427            } else if *best_effort_metadata && !*strict {
428                JournalReader::read(
429                    File::open(archive)?,
430                    crate::journal::ReadMode::Complete,
431                    &ctb_formats_dcstring::DcProjectionPolicy::forgiving(),
432                )?
433            } else {
434                JournalReader::new(File::open(archive)?)?
435            };
436            let (apple_write_mode, apple_single_write_extension) =
437                apple_write.resolve(*best_effort_metadata && !*strict)?;
438            let options = MaterializeOptions {
439                strict_lossless: *strict || !best_effort_metadata,
440                check_atime: *strict || *check_atime,
441                check_ctime: *strict
442                    || *check_ctime
443                    || (cfg!(windows) && !ctb_utilities::environment::is_wine()),
444                check_birthtime: *strict || *check_birthtime || cfg!(windows),
445                existing_entry_policy: if *overwrite {
446                    ctb_io::file::ExistingEntryPolicy::Replace
447                } else {
448                    ctb_io::file::ExistingEntryPolicy::Refuse
449                },
450                force_overwrite: true,
451                symlink_policy: if *trust_symlink_targets {
452                    SymlinkValidationPolicy::PreserveVerbatim
453                } else {
454                    SymlinkValidationPolicy::RejectEscapingSymlinks
455                },
456                path_policy: PathTraversalPolicy::StrictSandboxed,
457                copy_specials: *copy_specials_as_specials,
458                apple_write_mode,
459                apple_single_write_extension,
460                ..Default::default()
461            };
462            let extraction_losses =
463                extract_archive(&reader, destination, &options, *recover)?;
464            let mut diagnostics = String::new();
465            use std::fmt::Write;
466            let member_diagnostics =
467                append_reader_diagnostics(&reader, &mut diagnostics)?;
468            for loss in &extraction_losses {
469                writeln!(diagnostics, "Extraction loss: {loss}")?;
470            }
471            if *recover
472                && (!reader.is_completed()
473                    || reader.has_diagnostics()
474                    || member_diagnostics > 0
475                    || !extraction_losses.is_empty())
476            {
477                writeln!(
478                    diagnostics,
479                    "Archive extracted in recover mode (incomplete: {}; errors: {}; warnings: {}; member_diagnostics: {}; extraction_losses: {}). Archive is not a clean capture.",
480                    !reader.is_completed(),
481                    reader.errors.len(),
482                    reader.warnings.len(),
483                    member_diagnostics,
484                    extraction_losses.len()
485                )?;
486                Ok(ToolResult::Immediate {
487                    stdout: b"Archive extracted (with diagnostics).\n".to_vec(),
488                    stderr: diagnostics.into_bytes(),
489                    exit_code: 1,
490                })
491            } else {
492                Ok(ToolResult::immediate_ok(b"Archive extracted.\n".to_vec()))
493            }
494        }
495    }
496}
497
498#[derive(Debug)]
499struct SourceMember {
500    source: PathBuf,
501    relative: PathBuf,
502}
503
504#[derive(Default)]
505struct SourcePlan {
506    members: Vec<SourceMember>,
507    diagnostics: Vec<JournalErrorRecord>,
508    tree: CapturedTree,
509}
510
511fn archive_apple_read_options() -> AppleReadOptions {
512    AppleReadOptions {
513        read_apple_double_alongside: false,
514        read_apple_double_zip: false,
515        read_apple_double_netatalk: false,
516        read_apple_single_without_extension: false,
517        read_apple_single: false,
518        read_apple_single_as: false,
519        read_apple_single_asf: false,
520        read_windows_ads_alongside: false,
521    }
522}
523
524fn validate_output_path_overlap(
525    output_path: &Path,
526    sources: &[PathBuf],
527) -> Result<()> {
528    let output = resolve_existing_ancestors(output_path)?;
529    let working_directory = std::env::current_dir()?;
530    for source in sources {
531        let absolute = working_directory.join(source);
532        let resolved = resolve_existing_ancestors(&absolute)?;
533        ensure!(
534            output != resolved && !output.starts_with(&resolved),
535            "Archive output overlaps a source: {}",
536            source.display()
537        );
538    }
539    Ok(())
540}
541
542fn plan_sources(sources: &[PathBuf], archive: &Path) -> Result<SourcePlan> {
543    plan_sources_with_options(
544        sources,
545        archive,
546        &ArchiveCreateOptions::default(),
547    )
548}
549
550fn plan_sources_with_options(
551    sources: &[PathBuf],
552    archive: &Path,
553    options: &ArchiveCreateOptions,
554) -> Result<SourcePlan> {
555    ensure!(!sources.is_empty(), "At least one source is required");
556    if archive != Path::new("-") {
557        validate_output_path_overlap(archive, sources)?;
558    }
559    let working_directory = std::env::current_dir()?;
560    let apple_read_options = options.apple_read.resolve();
561    let best_effort_source_change =
562        options.on_source_change == crate::args::SourceChangePolicy::BestEffort;
563    let mut plan = SourcePlan::default();
564    let mut names = HashSet::new();
565    for source in sources {
566        let absolute = working_directory.join(source);
567        let metadata = match std::fs::symlink_metadata(&absolute) {
568            Ok(metadata) => metadata,
569            Err(error) => {
570                plan.diagnostics.push(JournalErrorRecord::from_error(
571                    &absolute,
572                    JournalErrorStage::MetadataRead,
573                    &error.into(),
574                ));
575                continue;
576            }
577        };
578        let prefix = if metadata.is_dir() && path_has_trailing_slash(source) {
579            PathBuf::from(".")
580        } else {
581            PathBuf::from(source.file_name().context("Source has no basename; use a trailing slash for a directory root")?)
582        };
583        if metadata.is_dir() {
584            let relative = normalized_member(&prefix)?;
585            ensure!(
586                names.insert(relative.clone()),
587                "Duplicate archive member: {}",
588                relative.display()
589            );
590            plan.members.push(SourceMember {
591                source: absolute.clone(),
592                relative,
593            });
594            let traversal_options = TraversalOptions::new()
595                .error_policy(ctb_io::file::OnTraversalError::Capture)
596                .one_file_system(options.one_file_system)
597                .apple_read_options(apple_read_options);
598            let mut directories =
599                ctb_io::file::traverse_dir(&absolute, traversal_options)?
600                    .directories()?;
601            while let Some(directory) = directories.next() {
602                let directory = directory?;
603                if !directory.errors.is_empty() {
604                    let error = anyhow::anyhow!(
605                        "Source traversal errors: {}",
606                        directory.errors.join("; ")
607                    );
608                    plan.diagnostics.push(JournalErrorRecord::from_error(
609                        &directory.path,
610                        JournalErrorStage::Traversal,
611                        &error,
612                    ));
613                    plan.members
614                        .retain(|member| member.source != directory.path);
615                    continue;
616                }
617                let snapshot = ctb_io::file::payload::SourceSnapshot::capture(
618                    &directory.path,
619                    best_effort_source_change,
620                )?;
621                plan.tree.retain(&snapshot);
622                let entries = match directories.read_directory(&directory, Ok) {
623                    Ok(entries) => entries,
624                    Err(error) => {
625                        plan.diagnostics.push(JournalErrorRecord::from_error(
626                            &directory.path,
627                            JournalErrorStage::Traversal,
628                            &error,
629                        ));
630                        plan.members
631                            .retain(|member| member.source != directory.path);
632                        continue;
633                    }
634                };
635                for item in entries {
636                    if !item.errors.is_empty() {
637                        let error = anyhow::anyhow!(
638                            "Source traversal errors: {}",
639                            item.errors.join("; ")
640                        );
641                        plan.diagnostics.push(JournalErrorRecord::from_error(
642                            &item.path,
643                            JournalErrorStage::Traversal,
644                            &error,
645                        ));
646                        plan.members
647                            .retain(|member| member.source != item.path);
648                        continue;
649                    }
650                    let relative = normalized_member(
651                        &prefix.join(item.path.strip_prefix(&absolute)?),
652                    )?;
653                    ensure!(
654                        names.insert(relative.clone()),
655                        "Duplicate archive member: {}",
656                        relative.display()
657                    );
658                    plan.members.push(SourceMember {
659                        source: item.path,
660                        relative,
661                    });
662                }
663                snapshot.retain_changes(snapshot.validate()?)?;
664            }
665        } else {
666            let relative = normalized_member(&prefix)?;
667            ensure!(
668                names.insert(relative.clone()),
669                "Duplicate archive member: {}",
670                relative.display()
671            );
672            plan.members.push(SourceMember {
673                source: absolute,
674                relative,
675            });
676        }
677    }
678    Ok(plan)
679}
680
681fn normalized_member(path: &Path) -> Result<PathBuf> {
682    let mut normalized = PathBuf::new();
683    for component in path.components() {
684        match component {
685            Component::Normal(value) => normalized.push(value),
686            Component::CurDir => {}
687            _ => bail!("Unsafe archive member path: {}", path.display()),
688        }
689    }
690    let bytes = path.as_os_str().as_encoded_bytes();
691    ensure!(
692        !bytes.contains(&0)
693            && !bytes.starts_with(b"\\")
694            && bytes.get(1) != Some(&b':'),
695        "Invalid archive member prefix: {}",
696        path.display()
697    );
698    if normalized.as_os_str().is_empty() {
699        normalized.push(".");
700    }
701    Ok(normalized)
702}
703
704fn clone_stdout_file() -> Result<Option<File>> {
705    #[cfg(unix)]
706    {
707        use std::os::fd::AsFd;
708        Ok(Some(File::from(
709            std::io::stdout().as_fd().try_clone_to_owned()?,
710        )))
711    }
712    #[cfg(windows)]
713    {
714        use std::os::windows::io::AsHandle;
715        Ok(Some(File::from(
716            std::io::stdout().as_handle().try_clone_to_owned()?,
717        )))
718    }
719    #[cfg(not(any(unix, windows)))]
720    {
721        Ok(None)
722    }
723}
724
725fn metadata_is_symlink_or_reparse(metadata: &std::fs::Metadata) -> bool {
726    #[cfg(windows)]
727    {
728        use std::os::windows::fs::MetadataExt;
729        const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0400;
730        metadata.file_type().is_symlink()
731            || (metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT) != 0
732    }
733    #[cfg(not(windows))]
734    {
735        metadata.file_type().is_symlink()
736    }
737}
738
739fn try_query_followed_file_identity(
740    path: &Path,
741) -> Result<Option<ctb_io::file::InodeKey>> {
742    #[cfg(unix)]
743    {
744        match std::fs::metadata(path) {
745            Ok(meta) => {
746                ctb_io::file::extract_file_identity(path, &meta).map(Some)
747            }
748            Err(_) => Ok(None),
749        }
750    }
751    #[cfg(windows)]
752    {
753        use std::os::windows::fs::OpenOptionsExt;
754        const FILE_READ_ATTRIBUTES: u32 = 0x0080;
755        const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
756        let Ok(file) = OpenOptions::new()
757            .access_mode(FILE_READ_ATTRIBUTES)
758            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
759            .open(path)
760        else {
761            return Ok(None);
762        };
763        ctb_io::file::try_query_open_file_identity(&file)
764    }
765    #[cfg(not(any(unix, windows)))]
766    {
767        let _ = path;
768        Ok(None)
769    }
770}
771
772fn ensure_path_not_same_output(
773    path: &Path,
774    output_key: &ctb_io::file::InodeKey,
775) -> Result<()> {
776    let metadata = match std::fs::symlink_metadata(path) {
777        Ok(metadata) => metadata,
778        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
779            return Ok(());
780        }
781        Err(error) => return Err(error.into()),
782    };
783    let source_key = ctb_io::file::extract_file_identity(path, &metadata)?;
784    ensure!(
785        &source_key != output_key,
786        "Archive output is included in the source tree: {}",
787        path.display()
788    );
789    if metadata_is_symlink_or_reparse(&metadata) {
790        if let Some(followed_key) = try_query_followed_file_identity(path)? {
791            ensure!(
792                &followed_key != output_key,
793                "Archive output is included in the source tree: {}",
794                path.display()
795            );
796        }
797        if let Ok(resolved_target) = std::fs::canonicalize(path) {
798            if let Ok(target_key) =
799                ctb_io::file::query_file_identity(&resolved_target)
800            {
801                ensure!(
802                    &target_key != output_key,
803                    "Archive output is included in the source tree: {}",
804                    path.display()
805                );
806            }
807        }
808        let mut current = path.to_path_buf();
809        for _ in 0_u8..64_u8 {
810            let Ok(link_target) = std::fs::read_link(&current) else {
811                break;
812            };
813            let next = if link_target.is_absolute() {
814                link_target
815            } else if let Some(parent) = current.parent() {
816                parent.join(link_target)
817            } else {
818                link_target
819            };
820            let Ok(next_meta) = std::fs::symlink_metadata(&next) else {
821                break;
822            };
823            let next_key =
824                ctb_io::file::extract_file_identity(&next, &next_meta)?;
825            ensure!(
826                &next_key != output_key,
827                "Archive output is included in the source tree: {}",
828                path.display()
829            );
830            if !metadata_is_symlink_or_reparse(&next_meta) {
831                break;
832            }
833            current = next;
834        }
835    }
836    Ok(())
837}
838
839fn validate_output_identity(
840    output: &File,
841    sources: &[PathBuf],
842    plan: &[SourceMember],
843) -> Result<()> {
844    if let Some(output_path) = ctb_io::file::try_query_open_file_path(output) {
845        validate_output_path_overlap(&output_path, sources)?;
846    }
847    if let Some(output_key) =
848        ctb_io::file::try_query_open_file_identity(output)?
849    {
850        let working_directory = std::env::current_dir()?;
851        for source in sources {
852            let absolute = working_directory.join(source);
853            ensure_path_not_same_output(&absolute, &output_key)?;
854        }
855        for member in plan {
856            ensure_path_not_same_output(&member.source, &output_key)?;
857        }
858    }
859    Ok(())
860}
861
862struct ForwardFileOutput(File);
863
864impl Write for ForwardFileOutput {
865    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
866        self.0.write(bytes)
867    }
868    fn flush(&mut self) -> std::io::Result<()> {
869        self.0.flush()
870    }
871}
872
873impl ArchiveOutput for ForwardFileOutput {}
874
875trait ArchiveOutput: Write {
876    fn checkpoint(&mut self) -> Result<Option<u64>> {
877        Ok(None)
878    }
879    fn rollback(&mut self, _position: u64) -> Result<()> {
880        bail!("Archive output cannot roll back")
881    }
882    fn sync(&mut self) -> Result<()> {
883        Ok(())
884    }
885}
886
887impl ArchiveOutput for std::io::StdoutLock<'_> {}
888impl ArchiveOutput for Vec<u8> {}
889impl ArchiveOutput for std::io::Cursor<Vec<u8>> {}
890
891impl ArchiveOutput for File {
892    fn checkpoint(&mut self) -> Result<Option<u64>> {
893        Ok(Some(self.stream_position()?))
894    }
895    fn rollback(&mut self, position: u64) -> Result<()> {
896        self.set_len(position)?;
897        self.seek(SeekFrom::Start(position))?;
898        self.sync_data()?;
899        Ok(())
900    }
901    fn sync(&mut self) -> Result<()> {
902        Ok(self.sync_all()?)
903    }
904}
905
906struct FileArchiveOutput {
907    buffer: Option<BufWriter<File>>,
908}
909
910impl FileArchiveOutput {
911    fn new(file: File) -> Self {
912        Self {
913            buffer: Some(BufWriter::new(file)),
914        }
915    }
916}
917
918impl Write for FileArchiveOutput {
919    fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
920        self.buffer
921            .as_mut()
922            .ok_or_else(|| {
923                std::io::Error::other("Archive file buffer unavailable")
924            })?
925            .write(bytes)
926    }
927    fn flush(&mut self) -> std::io::Result<()> {
928        self.buffer
929            .as_mut()
930            .ok_or_else(|| {
931                std::io::Error::other("Archive file buffer unavailable")
932            })?
933            .flush()
934    }
935}
936
937impl ArchiveOutput for FileArchiveOutput {
938    fn checkpoint(&mut self) -> Result<Option<u64>> {
939        self.flush()?;
940        Ok(Some(
941            self.buffer
942                .as_mut()
943                .context("Archive file buffer unavailable")?
944                .get_mut()
945                .stream_position()?,
946        ))
947    }
948    fn rollback(&mut self, position: u64) -> Result<()> {
949        let (mut file, _) = self
950            .buffer
951            .take()
952            .context("Archive file buffer unavailable")?
953            .into_parts();
954        ArchiveOutput::rollback(&mut file, position)?;
955        self.buffer = Some(BufWriter::new(file));
956        Ok(())
957    }
958    fn sync(&mut self) -> Result<()> {
959        self.flush()?;
960        self.buffer
961            .as_ref()
962            .context("Archive file buffer unavailable")?
963            .get_ref()
964            .sync_all()?;
965        Ok(())
966    }
967}
968
969impl Drop for FileArchiveOutput {
970    fn drop(&mut self) {
971        if let Some(buffer) = self.buffer.take() {
972            drop(buffer.into_parts());
973        }
974    }
975}
976
977struct CaptureOutcome<W> {
978    output: W,
979    error_count: usize,
980    warning_count: usize,
981    completed: bool,
982}
983
984trait CaptureSource {
985    fn capture(&mut self, path: &Path) -> Result<CapturedSource> {
986        let mut source = CapturedSource::capture(
987            path,
988            None,
989            &archive_apple_read_options(),
990            false,
991        )?;
992        source.hash(path)?;
993        Ok(source)
994    }
995    fn open(&mut self, path: &Path) -> Result<Box<dyn PayloadSource>> {
996        Ok(Box::new(DiskPayloadSource::open(path)?))
997    }
998}
999
1000#[derive(Default)]
1001struct FilesystemCapture {
1002    apple_read_options: AppleReadOptions,
1003    best_effort_source_change: bool,
1004}
1005
1006impl FilesystemCapture {
1007    fn from_options(options: &ArchiveCreateOptions) -> Self {
1008        Self {
1009            apple_read_options: options.apple_read.resolve(),
1010            best_effort_source_change: options.on_source_change
1011                == crate::args::SourceChangePolicy::BestEffort,
1012        }
1013    }
1014}
1015
1016impl CaptureSource for FilesystemCapture {
1017    fn capture(&mut self, path: &Path) -> Result<CapturedSource> {
1018        let mut source = CapturedSource::capture(
1019            path,
1020            None,
1021            &self.apple_read_options,
1022            self.best_effort_source_change,
1023        )?;
1024        source.hash(path)?;
1025        Ok(source)
1026    }
1027}
1028
1029struct CaptureRequest<'a> {
1030    sources: &'a [PathBuf],
1031    archive: &'a Path,
1032    plan: &'a SourcePlan,
1033    continue_on_error: bool,
1034    recovered: Option<&'a JournalReader>,
1035    journal: bool,
1036    options: &'a ArchiveCreateOptions,
1037}
1038
1039#[cfg(test)]
1040fn create_archive<W: ArchiveOutput>(
1041    output: W,
1042    sources: &[PathBuf],
1043    archive: &Path,
1044    plan: &SourcePlan,
1045    continue_on_error: bool,
1046    recovered: Option<&JournalReader>,
1047    journal: bool,
1048) -> Result<CaptureOutcome<W>> {
1049    create_archive_with_options(
1050        output,
1051        sources,
1052        archive,
1053        plan,
1054        continue_on_error,
1055        recovered,
1056        journal,
1057        &ArchiveCreateOptions::default(),
1058    )
1059}
1060
1061fn create_archive_with_options<W: ArchiveOutput>(
1062    output: W,
1063    sources: &[PathBuf],
1064    archive: &Path,
1065    plan: &SourcePlan,
1066    continue_on_error: bool,
1067    recovered: Option<&JournalReader>,
1068    journal: bool,
1069    options: &ArchiveCreateOptions,
1070) -> Result<CaptureOutcome<W>> {
1071    let mut capture = FilesystemCapture::from_options(options);
1072    capture_archive(
1073        output,
1074        CaptureRequest {
1075            sources,
1076            archive,
1077            plan,
1078            continue_on_error,
1079            recovered,
1080            journal,
1081            options,
1082        },
1083        &mut capture,
1084    )
1085}
1086
1087fn persist_source_error<W: ArchiveOutput>(
1088    writer: &mut JournalWriter<W>,
1089    record: &JournalErrorRecord,
1090) -> Result<()> {
1091    writer.record_error(record).with_context(|| {
1092        format!("Cannot persist source failure: {}", record.error_message)
1093    })?;
1094    writer.output_mut().flush().with_context(|| {
1095        format!("Cannot flush source failure: {}", record.error_message)
1096    })?;
1097    writer.output_mut().sync().with_context(|| {
1098        format!("Cannot sync source failure: {}", record.error_message)
1099    })
1100}
1101
1102fn persist_warning_record<W: ArchiveOutput>(
1103    writer: &mut JournalWriter<W>,
1104    code: &str,
1105    message: String,
1106    count: &mut usize,
1107) -> Result<()> {
1108    let warning = JournalWarningRecord {
1109        code: code.to_owned(),
1110        message,
1111        timestamp_sec: i64::try_from(
1112            std::time::SystemTime::now()
1113                .duration_since(std::time::UNIX_EPOCH)?
1114                .as_secs(),
1115        )?,
1116    };
1117    writer.record_warning(&warning).with_context(|| {
1118        format!("Cannot persist metadata warning: {}", warning.message)
1119    })?;
1120    writer.output_mut().flush().with_context(|| {
1121        format!("Cannot flush metadata warning: {}", warning.message)
1122    })?;
1123    writer.output_mut().sync().with_context(|| {
1124        format!("Cannot sync metadata warning: {}", warning.message)
1125    })?;
1126    *count = count.saturating_add(1);
1127    Ok(())
1128}
1129
1130fn persist_metadata_warnings<W: ArchiveOutput>(
1131    writer: &mut JournalWriter<W>,
1132    entity: &FileEntity,
1133    path: &Path,
1134    count: &mut usize,
1135) -> Result<()> {
1136    crate::journal::capture::visit_warnings(entity, &mut |_entity, message| {
1137        persist_warning_record(
1138            writer,
1139            "FileReadWarning",
1140            format!("{}: {message}", path.display()),
1141            count,
1142        )
1143    })
1144}
1145
1146fn capture_archive<W: ArchiveOutput>(
1147    output: W,
1148    request: CaptureRequest<'_>,
1149    capture: &mut impl CaptureSource,
1150) -> Result<CaptureOutcome<W>> {
1151    let CaptureRequest {
1152        sources,
1153        archive,
1154        plan,
1155        continue_on_error,
1156        recovered,
1157        journal,
1158        options,
1159    } = request;
1160    let best_effort_source_change =
1161        options.on_source_change == crate::args::SourceChangePolicy::BestEffort;
1162    let apple_read_options = options.apple_read.resolve();
1163    let session = if let Some(recovered) = recovered {
1164        recovered.session.clone()
1165    } else {
1166        let working_directory = std::env::current_dir()?;
1167        let environment = if options.full_provenance {
1168            std::sync::Arc::new(ctb_io_environment::capture())
1169        } else {
1170            ctb_io_environment::capture_quick_arc()
1171        };
1172        JournalSessionRecord {
1173            sources: sources
1174                .iter()
1175                .map(|source| working_directory.join(source))
1176                .collect(),
1177            destination: archive.to_path_buf(),
1178            origin_platform: u32::from(current_platform()),
1179            environment: Some(environment),
1180        }
1181    };
1182    let magic = if journal {
1183        crate::journal::stream::JournalMagic::JournalV5
1184    } else {
1185        crate::journal::stream::JournalMagic::ArchiveV2
1186    };
1187    let mut writer = if let Some(recovered) = recovered {
1188        recovered.resume_writer(output)?
1189    } else {
1190        JournalWriter::new(output, &session, magic)?
1191    };
1192    let mut error_count = 0_usize;
1193    let mut warning_count = 0_usize;
1194    for diagnostic in &plan.diagnostics {
1195        persist_source_error(&mut writer, diagnostic)?;
1196        error_count = error_count.saturating_add(1);
1197    }
1198    if error_count != 0 && !continue_on_error {
1199        return Ok(CaptureOutcome {
1200            output: writer.into_output(),
1201            error_count,
1202            warning_count,
1203            completed: false,
1204        });
1205    }
1206    let mut hardlinks = CommittedHardlinks::default();
1207    let mut tree = plan.tree.clone();
1208    let mut committed_paths = HashSet::new();
1209    if let Some(recovered) = recovered {
1210        for member in &recovered.members {
1211            let relative = member
1212                .entity
1213                .identity
1214                .relative_path
1215                .as_ref()
1216                .context("Committed member missing path")?;
1217            committed_paths.insert(relative.clone());
1218            if matches!(member.entity.kind, FileEntityKind::Regular { .. }) {
1219                hardlinks.commit(&member.entity, relative, None);
1220            }
1221        }
1222    }
1223    for member in &plan.members {
1224        if committed_paths.contains(&member.relative) {
1225            continue;
1226        }
1227        let CapturedSource {
1228            mut entity,
1229            snapshot,
1230        } = match capture.capture(&member.source) {
1231            Ok(source) => source,
1232            Err(error) => {
1233                persist_source_error(
1234                    &mut writer,
1235                    &JournalErrorRecord::from_error(
1236                        &member.source,
1237                        JournalErrorStage::MetadataRead,
1238                        &error,
1239                    ),
1240                )?;
1241                error_count = error_count.saturating_add(1);
1242                if continue_on_error {
1243                    continue;
1244                }
1245                return Ok(CaptureOutcome {
1246                    output: writer.into_output(),
1247                    error_count,
1248                    warning_count,
1249                    completed: false,
1250                });
1251            }
1252        };
1253        tree.retain(&snapshot);
1254        let mut effective_relative = member.relative.clone();
1255        if let Some(name) = member.relative.file_name() {
1256            for (enabled, extension) in [
1257                (
1258                    apple_read_options.read_apple_single_as,
1259                    ctb_io::file::apple_double::AppleSingleExtension::As,
1260                ),
1261                (
1262                    apple_read_options.read_apple_single_asf,
1263                    ctb_io::file::apple_double::AppleSingleExtension::Asf,
1264                ),
1265            ] {
1266                if enabled {
1267                    if let Some(stem) = extension.strip_from_name(name) {
1268                        if entity.identity.filename_bytes()
1269                            == Some(stem.as_encoded_bytes())
1270                        {
1271                            effective_relative =
1272                                member.relative.with_file_name(stem);
1273                            break;
1274                        }
1275                    }
1276                }
1277            }
1278        }
1279        crate::journal::capture::finalize_warnings(
1280            &snapshot,
1281            &mut entity,
1282            &mut |_, _| Ok(()),
1283        )?;
1284        let change_warnings = if best_effort_source_change {
1285            snapshot.change_warnings()?
1286        } else {
1287            Vec::new()
1288        };
1289        if !change_warnings.is_empty() {
1290            entity
1291                .metadata
1292                .warnings
1293                .retain(|w| !change_warnings.contains(w));
1294        }
1295        tree.visit_pending_warnings(&mut |code, message| {
1296            persist_warning_record(
1297                &mut writer,
1298                code,
1299                message.to_owned(),
1300                &mut warning_count,
1301            )
1302        })?;
1303        entity.identity.relative_path = Some(effective_relative.clone());
1304        entity.identity.enclosing_path = None;
1305        if let Some(environment) = &session.environment {
1306            attach_environment(&mut entity, environment);
1307        }
1308        persist_metadata_warnings(
1309            &mut writer,
1310            &entity,
1311            &member.source,
1312            &mut warning_count,
1313        )?;
1314        if let Err(error) =
1315            crate::journal::stream::ensure_clean_metadata(&entity)
1316        {
1317            persist_source_error(
1318                &mut writer,
1319                &JournalErrorRecord::from_error(
1320                    &member.source,
1321                    JournalErrorStage::MetadataRead,
1322                    &error,
1323                ),
1324            )?;
1325            error_count = error_count.saturating_add(1);
1326            if continue_on_error {
1327                continue;
1328            }
1329            return Ok(CaptureOutcome {
1330                output: writer.into_output(),
1331                error_count,
1332                warning_count,
1333                completed: false,
1334            });
1335        }
1336        if matches!(entity.kind, FileEntityKind::Regular { .. })
1337            && entity.identity.nlink > 1
1338        {
1339            match hardlinks.lookup(&entity, &effective_relative) {
1340                Ok(Some(target)) => {
1341                    entity.kind = FileEntityKind::Hardlink {
1342                        target_relative_path: LinkPath::from_relative_path(
1343                            target,
1344                        )?,
1345                    }
1346                }
1347                Ok(None) => {}
1348                Err(error) => {
1349                    persist_source_error(
1350                        &mut writer,
1351                        &JournalErrorRecord::from_error(
1352                            &member.source,
1353                            JournalErrorStage::PostCheck,
1354                            &error,
1355                        ),
1356                    )?;
1357                    error_count = error_count.saturating_add(1);
1358                    if continue_on_error {
1359                        continue;
1360                    }
1361                    return Ok(CaptureOutcome {
1362                        output: writer.into_output(),
1363                        error_count,
1364                        warning_count,
1365                        completed: false,
1366                    });
1367                }
1368            }
1369        }
1370        let mut payload = if matches!(
1371            entity.kind,
1372            FileEntityKind::Regular { .. }
1373        ) && !journal
1374        {
1375            let opened: Result<Box<dyn PayloadSource>> = match snapshot
1376                .interpreted_payload()
1377            {
1378                Ok(Some(interpreted)) => {
1379                    let mut mem =
1380                        ctb_io::file::MemoryPayloadSource::new(interpreted)?;
1381                    mem.bind_snapshot(&snapshot)?;
1382                    Ok(Box::new(mem))
1383                }
1384                Ok(None) => {
1385                    capture.open(&member.source).and_then(|mut payload| {
1386                        payload.bind_snapshot(&snapshot)?;
1387                        Ok(payload)
1388                    })
1389                }
1390                Err(err) => Err(err),
1391            };
1392            match opened {
1393                Ok(payload) => Some(payload),
1394                Err(error) => {
1395                    persist_source_error(
1396                        &mut writer,
1397                        &JournalErrorRecord::from_error(
1398                            &member.source,
1399                            JournalErrorStage::PayloadOpen,
1400                            &error,
1401                        ),
1402                    )?;
1403                    error_count = error_count.saturating_add(1);
1404                    if continue_on_error {
1405                        continue;
1406                    }
1407                    return Ok(CaptureOutcome {
1408                        output: writer.into_output(),
1409                        error_count,
1410                        warning_count,
1411                        completed: false,
1412                    });
1413                }
1414            }
1415        } else {
1416            None
1417        };
1418        let checkpoint = writer.output_mut().checkpoint()?;
1419        let precommit = || {
1420            tree.validate()?;
1421            snapshot.retain_changes(snapshot.validate()?)?;
1422            Ok(())
1423        };
1424        let bodies = if journal {
1425            ctb_io::file::encoding::BodyPolicy::Omit
1426        } else {
1427            ctb_io::file::encoding::BodyPolicy::Include
1428        };
1429        let result = if let Some(payload) = &mut payload {
1430            writer.write_entity_checked(
1431                &entity,
1432                Some(payload.as_mut()),
1433                bodies,
1434                precommit,
1435            )
1436        } else {
1437            writer.write_entity_checked(&entity, None, bodies, precommit)
1438        };
1439        if let Err(error) = result {
1440            if writer.is_failed() {
1441                if !writer.can_rollback_source_failure() {
1442                    return Err(error).context(
1443                        "Archive output or unclassified member failure",
1444                    );
1445                }
1446                let position = checkpoint.with_context(|| format!("Cannot roll back forward-only archive after source failure: {error:#}"))?;
1447                writer.rollback_source_failure(|output| output.rollback(position))
1448                    .with_context(|| format!("Cannot roll back archive after source failure: {error:#}"))?;
1449            }
1450            persist_source_error(
1451                &mut writer,
1452                &JournalErrorRecord::from_error(
1453                    &member.source,
1454                    JournalErrorStage::PayloadRead,
1455                    &error,
1456                ),
1457            )?;
1458            error_count = error_count.saturating_add(1);
1459            if continue_on_error {
1460                continue;
1461            }
1462            return Ok(CaptureOutcome {
1463                output: writer.into_output(),
1464                error_count,
1465                warning_count,
1466                completed: false,
1467            });
1468        }
1469        writer.output_mut().flush()?;
1470        writer.output_mut().sync()?;
1471        if matches!(entity.kind, FileEntityKind::Regular { .. }) {
1472            hardlinks.commit(&entity, &effective_relative, Some(&snapshot));
1473        }
1474    }
1475    if let Err(error) = tree.validate() {
1476        persist_source_error(
1477            &mut writer,
1478            &JournalErrorRecord::from_error(
1479                archive,
1480                JournalErrorStage::PostCheck,
1481                &error,
1482            ),
1483        )?;
1484        error_count = error_count.saturating_add(1);
1485        if !continue_on_error {
1486            return Ok(CaptureOutcome {
1487                output: writer.into_output(),
1488                error_count,
1489                warning_count,
1490                completed: false,
1491            });
1492        }
1493    }
1494    tree.visit_pending_warnings(&mut |code, message| {
1495        persist_warning_record(
1496            &mut writer,
1497            code,
1498            message.to_owned(),
1499            &mut warning_count,
1500        )
1501    })?;
1502    let mut output = writer.finish()?;
1503    output.sync()?;
1504    Ok(CaptureOutcome {
1505        output,
1506        error_count,
1507        warning_count,
1508        completed: true,
1509    })
1510}
1511
1512#[cfg(test)]
1513fn resume_archive(path: &Path, journal: bool) -> Result<()> {
1514    resume_archive_with_options(path, journal, &ArchiveCreateOptions::default())
1515}
1516
1517fn resume_archive_with_options(
1518    path: &Path,
1519    journal: bool,
1520    options: &ArchiveCreateOptions,
1521) -> Result<()> {
1522    let mut file = OpenOptions::new().read(true).write(true).open(path)?;
1523    let mut magic = [0_u8; 8];
1524    file.seek(SeekFrom::Start(0))?;
1525    file.read_exact(&mut magic)?;
1526    let is_journal = &magic == crate::journal::JOURNAL_MAGIC_V5
1527        || &magic == crate::journal::JOURNAL_MAGIC_V4
1528        || &magic == crate::journal::JOURNAL_MAGIC_V1
1529        || journal;
1530    let recovered = JournalReader::recover(file.try_clone()?)?;
1531    ensure!(
1532        !recovered.is_legacy,
1533        "Cannot resume a legacy CSC archive or journal"
1534    );
1535    ensure!(!recovered.completed, "Cannot resume a completed archive");
1536    if is_journal {
1537        recovered.verify_contents()?;
1538    } else {
1539        recovered.verify_self_contained_prefix()?;
1540    }
1541    validate_members(&recovered)?;
1542    let plan =
1543        plan_sources_with_options(&recovered.session.sources, path, options)?;
1544    ensure!(
1545        plan.diagnostics.is_empty(),
1546        "Cannot resume with source planning diagnostics"
1547    );
1548    let planned: HashMap<_, _> = plan
1549        .members
1550        .iter()
1551        .map(|member| (member.relative.as_path(), member.source.as_path()))
1552        .collect();
1553    for committed in &recovered.members {
1554        let relative = committed
1555            .entity
1556            .identity
1557            .relative_path
1558            .as_deref()
1559            .context("Committed member missing path")?;
1560        let source = planned
1561            .get(relative)
1562            .context("Committed source disappeared")?;
1563        let current = FileEntity::from_filesystem(source, None)?;
1564        ensure!(
1565            current.identity.origin == committed.entity.identity.origin,
1566            "Committed source identity changed: {}",
1567            source.display()
1568        );
1569        let mut expected = committed.entity.clone();
1570        if matches!(expected.kind, FileEntityKind::Hardlink { .. }) {
1571            expected.kind = current.kind.clone();
1572        }
1573        ctb_io::file::verify_materialized_entity_ext(
1574            source,
1575            &expected,
1576            true,
1577            false,
1578            false,
1579            cfg!(windows),
1580        )
1581        .with_context(|| {
1582            format!("Committed source changed: {}", source.display())
1583        })?;
1584    }
1585    file.set_len(recovered.valid_length)?;
1586    file.sync_all()?;
1587    file.seek(SeekFrom::End(0))?;
1588    let outcome = create_archive_with_options(
1589        FileArchiveOutput::new(file),
1590        &recovered.session.sources,
1591        path,
1592        &plan,
1593        false,
1594        Some(&recovered),
1595        is_journal,
1596        options,
1597    )?;
1598    ensure!(
1599        outcome.completed
1600            && outcome.error_count == 0
1601            && outcome.warning_count == 0,
1602        "Resumed archive has capture diagnostics"
1603    );
1604    Ok(())
1605}
1606
1607fn validate_members(reader: &JournalReader) -> Result<()> {
1608    let mut names = HashMap::new();
1609    for member in &reader.members {
1610        let path = member
1611            .entity
1612            .identity
1613            .relative_path
1614            .as_deref()
1615            .context("Archive member missing relative path")?;
1616        let normalized = normalized_member(path)?;
1617        ensure!(
1618            names.insert(normalized, &member.entity.kind).is_none(),
1619            "Duplicate archive member: {}",
1620            path.display()
1621        );
1622    }
1623    for (path, kind) in &names {
1624        if path == &PathBuf::from(".") {
1625            ensure!(
1626                matches!(
1627                    kind,
1628                    FileEntityKind::Directory | FileEntityKind::Bundle { .. }
1629                ),
1630                "Archive root is not a directory"
1631            );
1632        }
1633        for parent in path
1634            .ancestors()
1635            .skip(1)
1636            .filter(|parent| !parent.as_os_str().is_empty())
1637        {
1638            if let Some(parent_kind) = names.get(parent) {
1639                ensure!(
1640                    matches!(
1641                        parent_kind,
1642                        FileEntityKind::Directory
1643                            | FileEntityKind::Bundle { .. }
1644                    ),
1645                    "Archive member descends through a non-directory: {}",
1646                    parent.display()
1647                );
1648            }
1649        }
1650        if let FileEntityKind::Hardlink {
1651            target_relative_path,
1652        } = kind
1653        {
1654            let target =
1655                normalized_member(&target_relative_path.to_path_buf()?)?;
1656            ensure!(
1657                matches!(
1658                    names.get(&target),
1659                    Some(FileEntityKind::Regular { .. })
1660                ),
1661                "Hardlink target must name a regular archive member: {}",
1662                target.display()
1663            );
1664        }
1665    }
1666    Ok(())
1667}
1668
1669fn append_reader_diagnostics(
1670    reader: &JournalReader,
1671    diagnostics: &mut String,
1672) -> Result<usize> {
1673    use std::fmt::Write;
1674    let mut member_diagnostics = 0_usize;
1675    for member in &reader.members {
1676        if let Err(error) =
1677            crate::journal::stream::ensure_clean_metadata(&member.entity)
1678        {
1679            writeln!(
1680                diagnostics,
1681                "Member diagnostics {}: {error:#}",
1682                member.entity.identity.display_path()
1683            )?;
1684            member_diagnostics = member_diagnostics.saturating_add(1);
1685        }
1686    }
1687    for error in &reader.errors {
1688        writeln!(
1689            diagnostics,
1690            "Capture error ({:?}) {}: {}",
1691            error.stage,
1692            error.path.display(),
1693            error.error_message
1694        )?;
1695    }
1696    for warning in &reader.warnings {
1697        writeln!(
1698            diagnostics,
1699            "Capture warning ({}): {}",
1700            warning.code, warning.message
1701        )?;
1702    }
1703    Ok(member_diagnostics)
1704}
1705
1706fn extract_archive(
1707    reader: &JournalReader,
1708    destination: &Path,
1709    options: &MaterializeOptions,
1710    recover: bool,
1711) -> Result<Vec<String>> {
1712    ensure!(
1713        cfg!(any(unix, windows)),
1714        "Sandboxed archive extraction is unsupported on this platform"
1715    );
1716    if !recover {
1717        reader.verify_self_contained()?;
1718    }
1719    validate_members(reader)?;
1720    let mut losses = Vec::new();
1721    if let Some(metadata) = existing_metadata(destination)? {
1722        ensure!(
1723            metadata.is_dir() && !metadata.file_type().is_symlink(),
1724            "Extraction destination is not a real directory"
1725        );
1726    }
1727    for member in &reader.members {
1728        let relative = member
1729            .entity
1730            .identity
1731            .relative_path
1732            .as_deref()
1733            .context("Missing archive member path")?;
1734        let path = destination.join(relative);
1735        for ancestor in path
1736            .ancestors()
1737            .take_while(|ancestor| *ancestor != destination)
1738        {
1739            if let Some(metadata) = existing_metadata(ancestor)? {
1740                ensure!(
1741                    !metadata.file_type().is_symlink(),
1742                    "Extraction path contains an existing symlink: {}",
1743                    ancestor.display()
1744                );
1745            }
1746        }
1747        match &member.entity.kind {
1748            FileEntityKind::Fifo
1749            | FileEntityKind::CharDevice { .. }
1750            | FileEntityKind::BlockDevice { .. } => {
1751                ensure!(
1752                    options.copy_specials,
1753                    "Special member requires --copy-specials-as-specials: {}",
1754                    relative.display()
1755                );
1756            }
1757            FileEntityKind::Socket
1758            | FileEntityKind::Door
1759            | FileEntityKind::Inaccessible => {
1760                if recover {
1761                    let msg = format!(
1762                        "Archive member cannot be restored: {}; skipping in recover mode",
1763                        relative.display()
1764                    );
1765                    warn_fmt!("{msg}");
1766                    losses.push(msg);
1767                    continue;
1768                }
1769                bail!(
1770                    "Archive member cannot be restored: {}",
1771                    relative.display()
1772                );
1773            }
1774            FileEntityKind::Symlink { target }
1775                if options.symlink_policy
1776                    != SymlinkValidationPolicy::PreserveVerbatim =>
1777            {
1778                ctb_io::file::validate_symlink_target(
1779                    destination,
1780                    &path,
1781                    target.to_path_buf()?.as_os_str().as_encoded_bytes(),
1782                    options.symlink_policy,
1783                )?;
1784            }
1785            _ => {}
1786        }
1787        if relative != Path::new(".") {
1788            match std::fs::symlink_metadata(&path) {
1789                Ok(metadata) => {
1790                    #[cfg(unix)]
1791                    {
1792                        use std::os::unix::fs::MetadataExt;
1793                        let archive_metadata = reader.file.metadata()?;
1794                        ensure!(
1795                            metadata.dev() != archive_metadata.dev()
1796                                || metadata.ino() != archive_metadata.ino(),
1797                            "Extraction would overwrite the archive itself: {}",
1798                            path.display()
1799                        );
1800                    }
1801                    ensure!(
1802                        options.existing_entry_policy
1803                            == ctb_io::file::ExistingEntryPolicy::Replace,
1804                        "Extraction destination already exists; use --overwrite: {}",
1805                        path.display()
1806                    );
1807                    let existing_is_symlink =
1808                        metadata_is_symlink_or_reparse(&metadata);
1809                    ensure!(
1810                        !existing_is_symlink
1811                            && ((metadata.is_file()
1812                                && matches!(
1813                                    member.entity.kind,
1814                                    FileEntityKind::Regular { .. }
1815                                ))
1816                                || (metadata.is_dir()
1817                                    && member.entity.is_dir())),
1818                        "Cannot overwrite this entry type: {}",
1819                        path.display()
1820                    );
1821                }
1822                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1823                Err(error) => return Err(error.into()),
1824            }
1825        }
1826    }
1827    let sandbox = SandboxableDir::create_or_open(destination)?;
1828    for member in reader
1829        .members
1830        .iter()
1831        .filter(|member| member.entity.is_dir())
1832    {
1833        let orig_relative = member
1834            .entity
1835            .identity
1836            .relative_path
1837            .as_deref()
1838            .context("Missing directory path")?;
1839        let adapted_buf;
1840        let relative = if options.strict_lossless
1841            || orig_relative.as_os_str().is_empty()
1842            || orig_relative == Path::new(".")
1843        {
1844            orig_relative
1845        } else {
1846            let (adapted, _) =
1847                ctb_io::file::adapt_relative_path_for_materialization(
1848                    orig_relative,
1849                    cfg!(windows),
1850                );
1851            adapted_buf = adapted;
1852            &adapted_buf
1853        };
1854        sandbox
1855            .ensure_dir_all(relative, PathTraversalPolicy::StrictSandboxed)?;
1856        if let Err(error) =
1857            sandbox.authorize_metadata(relative, options.existing_entry_policy)
1858        {
1859            if recover {
1860                let msg = format!(
1861                    "Failed to authorize directory metadata for {}: {error:#}; skipping in recover mode",
1862                    relative.display()
1863                );
1864                warn_fmt!("{msg}");
1865                losses.push(msg);
1866            } else {
1867                return Err(error);
1868            }
1869        }
1870    }
1871    for hardlinks in [false, true] {
1872        for member in reader.members.iter().filter(|member| {
1873            !member.entity.is_dir()
1874                && matches!(member.entity.kind, FileEntityKind::Hardlink { .. })
1875                    == hardlinks
1876        }) {
1877            // Reason for fallback: member without explicit relative path defaults to empty path.
1878            let relative = member
1879                .entity
1880                .identity
1881                .relative_path
1882                .as_deref()
1883                .unwrap_or(Path::new(""));
1884            if matches!(
1885                member.entity.kind,
1886                FileEntityKind::Socket
1887                    | FileEntityKind::Door
1888                    | FileEntityKind::Inaccessible
1889            ) {
1890                continue;
1891            }
1892            let materialize_res =
1893                if matches!(member.entity.kind, FileEntityKind::Regular { .. })
1894                {
1895                    match reader.payload(member) {
1896                        Ok(mut payload) => {
1897                            ctb_io::file::materialize_entity_with_stream_source(
1898                                &member.entity,
1899                                Some(&mut payload),
1900                                &sandbox,
1901                                options,
1902                                reader,
1903                            )
1904                        }
1905                        Err(err) => Err(err),
1906                    }
1907                } else {
1908                    ctb_io::file::materialize_entity_with_stream_source(
1909                        &member.entity,
1910                        None,
1911                        &sandbox,
1912                        options,
1913                        reader,
1914                    )
1915                };
1916            let receipt = match materialize_res {
1917                Ok(receipt) => receipt,
1918                Err(error) if recover => {
1919                    let msg = format!(
1920                        "Failed to extract member {}: {error:#}; skipping in recover mode",
1921                        relative.display()
1922                    );
1923                    warn_fmt!("{msg}");
1924                    losses.push(msg);
1925                    continue;
1926                }
1927                Err(error) => return Err(error),
1928            };
1929            for warning in &receipt.warnings {
1930                warn_fmt!("{warning}");
1931            }
1932            if !hardlinks {
1933                let mut expected = member.entity.clone();
1934                receipt.apply_stream_adaptations(&mut expected);
1935                if let Err(error) = ctb_io::file::verify_materialized_entity_ext(
1936                    &receipt.destination_path,
1937                    &expected,
1938                    options.strict_lossless,
1939                    options.check_atime,
1940                    options.check_ctime,
1941                    options.check_birthtime,
1942                ) {
1943                    if recover {
1944                        let msg = format!(
1945                            "Materialized member verification failed for {}: {error:#}; continuing in recover mode",
1946                            relative.display()
1947                        );
1948                        warn_fmt!("{msg}");
1949                        losses.push(msg);
1950                    } else {
1951                        return Err(error);
1952                    }
1953                }
1954            }
1955        }
1956    }
1957    let mut directories: Vec<_> = reader
1958        .members
1959        .iter()
1960        .filter(|member| member.entity.is_dir())
1961        .collect();
1962    directories.sort_by_key(|member| {
1963        std::cmp::Reverse(
1964            member
1965                .entity
1966                .identity
1967                .relative_path
1968                .as_deref()
1969                .map(Path::components)
1970                .map(Iterator::count),
1971        )
1972    });
1973    for member in directories {
1974        let relative = member
1975            .entity
1976            .identity
1977            .relative_path
1978            .as_deref()
1979            .context("Missing directory path")?;
1980        if relative == Path::new(".") {
1981            if let Err(error) = sandbox
1982                .authorize_metadata(relative, options.existing_entry_policy)
1983            {
1984                if recover {
1985                    let msg = format!(
1986                        "Failed to authorize root directory metadata: {error:#}; skipping in recover mode"
1987                    );
1988                    warn_fmt!("{msg}");
1989                    losses.push(msg);
1990                    continue;
1991                }
1992                return Err(error);
1993            }
1994            let mut expected = member.entity.clone();
1995            match ctb_io::file::materialize_directory_streams_and_companions(
1996                &member.entity,
1997                destination,
1998                &sandbox,
1999                options,
2000                reader,
2001            ) {
2002                Ok((stream_adaptations, warnings)) => {
2003                    ctb_io::file::MaterializeReceipt {
2004                        destination_path: destination.to_path_buf(),
2005                        bytes_written: 0,
2006                        sha256: None,
2007                        skipped_identical: false,
2008                        warnings: Vec::new(),
2009                        stream_adaptations,
2010                    }
2011                    .apply_stream_adaptations(&mut expected);
2012                    for warning in warnings {
2013                        warn_fmt!("{warning}");
2014                    }
2015                }
2016                Err(error) if recover => {
2017                    let msg = format!(
2018                        "Failed to materialize root directory streams: {error:#}; skipping in recover mode"
2019                    );
2020                    warn_fmt!("{msg}");
2021                    losses.push(msg);
2022                }
2023                Err(error) => return Err(error),
2024            }
2025            match ctb_io::file::apply_entity_metadata_ext(
2026                destination,
2027                None,
2028                &member.entity.metadata,
2029                false,
2030                true,
2031                options.strict_lossless,
2032                options.check_ctime,
2033                options.check_birthtime,
2034            ) {
2035                Ok(warnings) => {
2036                    for warning in warnings {
2037                        warn_fmt!("{warning}");
2038                    }
2039                }
2040                Err(error) if recover => {
2041                    let msg = format!(
2042                        "Failed to apply root directory metadata: {error:#}; skipping in recover mode"
2043                    );
2044                    warn_fmt!("{msg}");
2045                    losses.push(msg);
2046                }
2047                Err(error) => return Err(error),
2048            }
2049            if let Err(error) = ctb_io::file::verify_materialized_entity_ext(
2050                destination,
2051                &expected,
2052                options.strict_lossless,
2053                options.check_atime,
2054                options.check_ctime,
2055                options.check_birthtime,
2056            ) {
2057                if recover {
2058                    let msg = format!(
2059                        "Directory verification failed for {}: {error:#}; continuing in recover mode",
2060                        relative.display()
2061                    );
2062                    warn_fmt!("{msg}");
2063                    losses.push(msg);
2064                } else {
2065                    return Err(error);
2066                }
2067            }
2068        } else {
2069            let mut verify_path = destination.join(relative);
2070            let mut expected = member.entity.clone();
2071            match ctb_io::file::materialize_entity_with_stream_source(
2072                &member.entity,
2073                None,
2074                &sandbox,
2075                options,
2076                reader,
2077            ) {
2078                Ok(receipt) => {
2079                    receipt.apply_stream_adaptations(&mut expected);
2080                    verify_path = receipt.destination_path;
2081                    for warning in receipt.warnings {
2082                        warn_fmt!("{warning}");
2083                    }
2084                }
2085                Err(error) if recover => {
2086                    let msg = format!(
2087                        "Failed to materialize directory metadata for {}: {error:#}; skipping in recover mode",
2088                        relative.display()
2089                    );
2090                    warn_fmt!("{msg}");
2091                    losses.push(msg);
2092                }
2093                Err(error) => return Err(error),
2094            }
2095            if let Err(error) = ctb_io::file::verify_materialized_entity_ext(
2096                &verify_path,
2097                &expected,
2098                options.strict_lossless,
2099                options.check_atime,
2100                options.check_ctime,
2101                options.check_birthtime,
2102            ) {
2103                if recover {
2104                    let msg = format!(
2105                        "Directory verification failed for {}: {error:#}; continuing in recover mode",
2106                        relative.display()
2107                    );
2108                    warn_fmt!("{msg}");
2109                    losses.push(msg);
2110                } else {
2111                    return Err(error);
2112                }
2113            }
2114        }
2115    }
2116    Ok(losses)
2117}
2118
2119fn existing_metadata(path: &Path) -> Result<Option<std::fs::Metadata>> {
2120    match std::fs::symlink_metadata(path) {
2121        Ok(metadata) => Ok(Some(metadata)),
2122        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2123        Err(error) => Err(error)
2124            .with_context(|| format!("Cannot inspect {}", path.display())),
2125    }
2126}
2127
2128#[cfg(test)]
2129#[allow(
2130    clippy::panic,
2131    clippy::expect_used,
2132    clippy::unwrap_used,
2133    clippy::unwrap_in_result,
2134    clippy::panic_in_result_fn,
2135    clippy::indexing_slicing,
2136    clippy::arithmetic_side_effects,
2137    reason = "Standard repository test boilerplate"
2138)]
2139mod tests {
2140    use super::*;
2141    use crate::args::default_verify_args;
2142    use crate::verifier::run_csc_verify;
2143    use ctb_formats_dcstring::DcMstring;
2144    use std::io::Read;
2145
2146    #[derive(Clone, Copy)]
2147    enum CaptureFault {
2148        None,
2149        Capture,
2150        Open,
2151        Read,
2152        Finish,
2153        Warning,
2154    }
2155
2156    struct FaultCapture {
2157        path: PathBuf,
2158        fault: CaptureFault,
2159        opened: Vec<PathBuf>,
2160    }
2161
2162    impl CaptureSource for FaultCapture {
2163        fn capture(&mut self, path: &Path) -> Result<CapturedSource> {
2164            if path == self.path && matches!(self.fault, CaptureFault::Capture)
2165            {
2166                bail!("injected metadata capture failure");
2167            }
2168            let mut source = FilesystemCapture::default().capture(path)?;
2169            if path == self.path && matches!(self.fault, CaptureFault::Warning)
2170            {
2171                let mut stream = ctb_io::file::AttachedStream::from_data(
2172                    None,
2173                    ctb_io::file::StreamKind::infer_from_name(b"fixture"),
2174                    Vec::new(),
2175                )?;
2176                stream
2177                    .entity
2178                    .metadata
2179                    .warnings
2180                    .push("injected recursive warning".to_owned());
2181                source.entity.streams.push(stream);
2182            }
2183            Ok(source)
2184        }
2185        fn open(&mut self, path: &Path) -> Result<Box<dyn PayloadSource>> {
2186            self.opened.push(path.to_path_buf());
2187            if path == self.path {
2188                if matches!(self.fault, CaptureFault::Open) {
2189                    bail!("injected payload open failure");
2190                }
2191                if matches!(
2192                    self.fault,
2193                    CaptureFault::Read | CaptureFault::Finish
2194                ) {
2195                    return Ok(Box::new(FaultPayload {
2196                        source: DiskPayloadSource::open(path)?,
2197                        bytes: 0,
2198                        finish_failure: matches!(
2199                            self.fault,
2200                            CaptureFault::Finish
2201                        ),
2202                    }));
2203                }
2204            }
2205            Ok(Box::new(DiskPayloadSource::open(path)?))
2206        }
2207    }
2208
2209    struct FaultPayload {
2210        source: DiskPayloadSource,
2211        bytes: usize,
2212        finish_failure: bool,
2213    }
2214
2215    impl Read for FaultPayload {
2216        fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
2217            if !self.finish_failure && self.bytes >= 32_768 {
2218                return Err(std::io::Error::other(
2219                    "injected source read failure after buffer boundary",
2220                ));
2221            }
2222            let limit = if self.finish_failure {
2223                buffer.len()
2224            } else {
2225                buffer.len().min(32_768_usize.saturating_sub(self.bytes))
2226            };
2227            let count =
2228                self.source.read(buffer.get_mut(..limit).ok_or_else(
2229                    || std::io::Error::other("Invalid test read limit"),
2230                )?)?;
2231            self.bytes = self.bytes.saturating_add(count);
2232            Ok(count)
2233        }
2234    }
2235
2236    impl Seek for FaultPayload {
2237        fn seek(&mut self, position: SeekFrom) -> std::io::Result<u64> {
2238            self.source.seek(position)
2239        }
2240    }
2241
2242    impl PayloadSource for FaultPayload {
2243        fn bind_snapshot(
2244            &mut self,
2245            snapshot: &ctb_io::file::payload::SourceSnapshot,
2246        ) -> Result<()> {
2247            self.source.bind_snapshot(snapshot)
2248        }
2249        fn total_size(&self) -> u64 {
2250            self.source.total_size()
2251        }
2252        fn extents(&self) -> &[ctb_io::file::Extent] {
2253            self.source.extents()
2254        }
2255        fn finish(&mut self) -> Result<Vec<String>> {
2256            if self.finish_failure {
2257                bail!("injected source finish failure");
2258            }
2259            self.source.finish()
2260        }
2261    }
2262
2263    #[derive(Clone, Default)]
2264    struct ForwardOutput(std::rc::Rc<std::cell::RefCell<Vec<u8>>>);
2265
2266    impl Write for ForwardOutput {
2267        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
2268            self.0.borrow_mut().extend_from_slice(bytes);
2269            Ok(bytes.len())
2270        }
2271        fn flush(&mut self) -> std::io::Result<()> {
2272            Ok(())
2273        }
2274    }
2275    impl ArchiveOutput for ForwardOutput {}
2276
2277    #[derive(Clone, Copy, Debug)]
2278    enum OutputFault {
2279        Write,
2280        WriteZero,
2281        Flush,
2282        Sync,
2283        Rollback,
2284        Diagnostic,
2285    }
2286
2287    struct FaultOutput {
2288        output: FileArchiveOutput,
2289        fault: OutputFault,
2290        started: bool,
2291        rolled_back: bool,
2292    }
2293
2294    impl Write for FaultOutput {
2295        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
2296            if self.started && matches!(self.fault, OutputFault::Write)
2297                || self.rolled_back
2298                    && matches!(self.fault, OutputFault::Diagnostic)
2299            {
2300                return Err(std::io::Error::other(
2301                    "injected sink write failure",
2302                ));
2303            }
2304            if self.started && matches!(self.fault, OutputFault::WriteZero) {
2305                return Ok(0);
2306            }
2307            self.output.write(bytes)
2308        }
2309        fn flush(&mut self) -> std::io::Result<()> {
2310            if self.started && matches!(self.fault, OutputFault::Flush) {
2311                return Err(std::io::Error::other(
2312                    "injected sink flush failure",
2313                ));
2314            }
2315            self.output.flush()
2316        }
2317    }
2318
2319    impl ArchiveOutput for FaultOutput {
2320        fn checkpoint(&mut self) -> Result<Option<u64>> {
2321            let position = self.output.checkpoint()?;
2322            self.started = true;
2323            Ok(position)
2324        }
2325        fn rollback(&mut self, position: u64) -> Result<()> {
2326            if matches!(self.fault, OutputFault::Rollback) {
2327                bail!("injected rollback failure");
2328            }
2329            self.output.rollback(position)?;
2330            self.rolled_back = true;
2331            Ok(())
2332        }
2333        fn sync(&mut self) -> Result<()> {
2334            if self.started && matches!(self.fault, OutputFault::Sync) {
2335                bail!("injected sink sync failure");
2336            }
2337            self.output.sync()
2338        }
2339    }
2340
2341    static DEFAULT_CREATE_OPTIONS: ArchiveCreateOptions =
2342        ArchiveCreateOptions {
2343            full_provenance: false,
2344            on_source_change: crate::args::SourceChangePolicy::Error,
2345            one_file_system: false,
2346            apple_read: crate::args::AppleReadCliArgs {
2347                read_apple_double: None,
2348                read_apple_double_alongside: false,
2349                no_read_apple_double_alongside: false,
2350                read_apple_double_zip: false,
2351                read_apple_double_netatalk: false,
2352                read_apple_single: false,
2353                read_apple_single_without_extension: false,
2354                no_read_apple_single: false,
2355                read_apple_single_with_extension: Vec::new(),
2356                read_windows_ads: false,
2357                no_read_windows_ads: false,
2358            },
2359        };
2360
2361    fn capture_request<'a>(
2362        sources: &'a [PathBuf],
2363        archive: &'a Path,
2364        plan: &'a SourcePlan,
2365        continue_on_error: bool,
2366    ) -> CaptureRequest<'a> {
2367        CaptureRequest {
2368            sources,
2369            archive,
2370            plan,
2371            continue_on_error,
2372            recovered: None,
2373            journal: false,
2374            options: &DEFAULT_CREATE_OPTIONS,
2375        }
2376    }
2377
2378    #[crate::ctb_test]
2379    fn archive_raw_apple_source_free_roundtrip() -> Result<()> {
2380        let temporary = tempfile::tempdir()?;
2381        let source = temporary.path().join("source");
2382        std::fs::create_dir_all(source.join("__MACOSX"))?;
2383        std::fs::create_dir(source.join(".AppleDouble"))?;
2384        let mut apple = ctb_io::file::AppleArchive {
2385            format: ctb_io::file::AppleFormat::AppleDouble,
2386            version: ctb_io::file::VERSION_2_0_BE,
2387            real_name: None,
2388            comment: None,
2389            timestamps: None,
2390            backup_timestamp_sec: None,
2391            finder_info: None,
2392            extended_attributes: Vec::new(),
2393            data_fork: None,
2394            resource_fork: Some(b"resource".to_vec()),
2395            data_fork_size: None,
2396            resource_fork_size: Some(8),
2397            unrecognized_entries: Vec::new(),
2398            entries: Vec::new(),
2399        };
2400        let double = ctb_io::file::write_apple_single_double(&apple)?;
2401        apple.format = ctb_io::file::AppleFormat::AppleSingle;
2402        apple.data_fork = Some(b"single primary".to_vec());
2403        let single = ctb_io::file::write_apple_single_double(&apple)?;
2404        let originals = [
2405            ("valid", b"primary valid".to_vec()),
2406            ("._valid", double.clone()),
2407            ("malformed", b"primary malformed".to_vec()),
2408            ("._malformed", b"malformed".to_vec()),
2409            ("._orphan", b"ordinary dot underscore".to_vec()),
2410            ("__MACOSX/._valid", double.clone()),
2411            (".AppleDouble/valid", double),
2412            ("single", single.clone()),
2413            ("single.as", single.clone()),
2414            ("single.asf", single),
2415        ];
2416        for (relative, bytes) in &originals {
2417            std::fs::write(source.join(relative), bytes)?;
2418        }
2419        let sources = vec![source.clone()];
2420        let archive = temporary.path().join("backup.cscarchive");
2421        let plan = plan_sources(&sources, &archive)?;
2422        ensure!(plan.diagnostics.is_empty());
2423        let expected: HashSet<_> = originals
2424            .iter()
2425            .map(|(relative, _)| Path::new("source").join(relative))
2426            .chain([
2427                PathBuf::from("source"),
2428                PathBuf::from("source/__MACOSX"),
2429                PathBuf::from("source/.AppleDouble"),
2430            ])
2431            .collect();
2432        ensure!(
2433            plan.members
2434                .iter()
2435                .map(|member| member.relative.clone())
2436                .collect::<HashSet<_>>()
2437                == expected
2438        );
2439        let outcome = create_archive(
2440            FileArchiveOutput::new(File::create(&archive)?),
2441            &sources,
2442            &archive,
2443            &plan,
2444            false,
2445            None,
2446            false,
2447        )?;
2448        ensure!(
2449            outcome.completed
2450                && outcome.error_count == 0
2451                && outcome.warning_count == 0
2452        );
2453        drop(outcome.output);
2454        std::fs::remove_dir_all(&source)?;
2455        let reader = JournalReader::new(File::open(&archive)?)?;
2456        reader.verify()?;
2457        ensure!(
2458            reader
2459                .members
2460                .iter()
2461                .filter_map(|member| member
2462                    .entity
2463                    .identity
2464                    .relative_path
2465                    .clone())
2466                .collect::<HashSet<_>>()
2467                == expected
2468        );
2469        for (relative, bytes) in &originals {
2470            let member = reader
2471                .members
2472                .iter()
2473                .find(|member| {
2474                    member.entity.identity.relative_path.as_deref()
2475                        == Some(Path::new("source").join(relative).as_path())
2476                })
2477                .context("Missing raw Apple member")?;
2478            ensure!(
2479                member.entity.streams.is_empty()
2480                    && member.entity.metadata.apple.is_none()
2481            );
2482            let mut payload = reader.payload(member)?;
2483            let mut archived = Vec::new();
2484            payload.read_to_end(&mut archived)?;
2485            payload.finish()?;
2486            ensure!(
2487                &archived == bytes,
2488                "Raw container bytes changed: {relative}"
2489            );
2490        }
2491        let destination = temporary.path().join("restored");
2492        extract_archive(
2493            &reader,
2494            &destination,
2495            &MaterializeOptions::default(),
2496            false,
2497        )?;
2498        for (relative, bytes) in &originals {
2499            ensure!(
2500                std::fs::read(destination.join("source").join(relative))?
2501                    == *bytes
2502            );
2503        }
2504        Ok(())
2505    }
2506
2507    #[crate::ctb_test]
2508    fn archive_raw_capture_has_no_companion_dependency() -> Result<()> {
2509        let temporary = tempfile::tempdir()?;
2510        let path = temporary.path().join("main");
2511        let companion = temporary.path().join("._main");
2512        std::fs::write(&path, b"primary")?;
2513        std::fs::write(&companion, b"malformed")?;
2514        let raw = FilesystemCapture::default().capture(&path)?;
2515        let read_alongside = AppleReadOptions {
2516            read_apple_double_alongside: true,
2517            ..Default::default()
2518        };
2519        ensure!(
2520            CapturedSource::capture(&path, None, &read_alongside, false)
2521                .is_err()
2522        );
2523        std::fs::write(&companion, b"changed companion")?;
2524        ensure!(raw.snapshot.validate()?.is_empty());
2525        let mut payload = raw.open(&path)?;
2526        let mut bytes = Vec::new();
2527        payload.read_to_end(&mut bytes)?;
2528        payload.finish()?;
2529        ensure!(bytes == b"primary");
2530        #[cfg(unix)]
2531        {
2532            std::fs::remove_file(&companion)?;
2533            std::os::unix::fs::symlink("missing", &companion)?;
2534            FilesystemCapture::default().capture(&path)?;
2535            ensure!(
2536                CapturedSource::capture(&path, None, &read_alongside, false)
2537                    .is_err()
2538            );
2539            ensure!(std::fs::read_link(&companion)? == Path::new("missing"));
2540            ensure!(std::fs::read(&path)? == b"primary");
2541        }
2542        Ok(())
2543    }
2544
2545    #[crate::ctb_test]
2546    fn capture_final_tree_failure_obeys_continue_policy() -> Result<()> {
2547        struct MutatingOutput {
2548            output: FileArchiveOutput,
2549            root: PathBuf,
2550            syncs: usize,
2551        }
2552        impl Write for MutatingOutput {
2553            fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
2554                self.output.write(bytes)
2555            }
2556            fn flush(&mut self) -> std::io::Result<()> {
2557                self.output.flush()
2558            }
2559        }
2560        impl ArchiveOutput for MutatingOutput {
2561            fn checkpoint(&mut self) -> Result<Option<u64>> {
2562                self.output.checkpoint()
2563            }
2564            fn rollback(&mut self, position: u64) -> Result<()> {
2565                self.output.rollback(position)
2566            }
2567            fn sync(&mut self) -> Result<()> {
2568                self.output.sync()?;
2569                self.syncs = self.syncs.saturating_add(1);
2570                if self.syncs == 2 {
2571                    std::fs::write(self.root.join("late"), b"late")?;
2572                }
2573                Ok(())
2574            }
2575        }
2576        for continue_on_error in [false, true] {
2577            let temporary = tempfile::tempdir()?;
2578            let root = temporary.path().join("source");
2579            std::fs::create_dir(&root)?;
2580            std::fs::write(root.join("child"), b"primary")?;
2581            let sources = vec![root.clone()];
2582            let archive = temporary.path().join("output");
2583            let plan = plan_sources(&sources, &archive)?;
2584            let output = MutatingOutput {
2585                output: FileArchiveOutput::new(File::create(&archive)?),
2586                root,
2587                syncs: 0,
2588            };
2589            let outcome = create_archive(
2590                output,
2591                &sources,
2592                &archive,
2593                &plan,
2594                continue_on_error,
2595                None,
2596                false,
2597            )?;
2598            ensure!(
2599                outcome.error_count == 1
2600                    && outcome.completed == continue_on_error
2601            );
2602            drop(outcome.output);
2603            let reader = JournalReader::recover(File::open(&archive)?)?;
2604            ensure!(reader.members.len() == 2 && reader.errors.len() == 1);
2605            ensure!(
2606                reader.is_completed() == continue_on_error
2607                    && reader.verify().is_err()
2608            );
2609        }
2610        Ok(())
2611    }
2612
2613    #[cfg(unix)]
2614    #[crate::ctb_test]
2615    fn capture_archive_retains_snapshot_cleanup_warning() -> Result<()> {
2616        struct CleanupCapture;
2617        impl CaptureSource for CleanupCapture {
2618            fn capture(&mut self, path: &Path) -> Result<CapturedSource> {
2619                let source = FilesystemCapture::default().capture(path)?;
2620                source.snapshot.retain_cleanup_warnings(vec![
2621                    "injected symlink cleanup warning".to_owned(),
2622                ])?;
2623                Ok(source)
2624            }
2625        }
2626        let temporary = tempfile::tempdir()?;
2627        let path = temporary.path().join("link");
2628        std::os::unix::fs::symlink("target", &path)?;
2629        let sources = vec![path];
2630        let archive = temporary.path().join("output");
2631        let plan = plan_sources(&sources, &archive)?;
2632        let outcome = capture_archive(
2633            FileArchiveOutput::new(File::create(&archive)?),
2634            capture_request(&sources, &archive, &plan, false),
2635            &mut CleanupCapture,
2636        )?;
2637        ensure!(
2638            !outcome.completed
2639                && outcome.warning_count > 0
2640                && outcome.error_count == 1
2641        );
2642        drop(outcome.output);
2643        let reader = JournalReader::recover(File::open(&archive)?)?;
2644        ensure!(reader.warnings.iter().any(|warning| {
2645            warning.message.contains("injected symlink cleanup")
2646        }));
2647        ensure!(reader.members.is_empty());
2648        ensure!(reader.errors.iter().any(|error| {
2649            error.error_message.contains("injected symlink cleanup")
2650        }));
2651        ensure!(reader.verify().is_err());
2652        Ok(())
2653    }
2654
2655    #[crate::ctb_test]
2656    fn capture_tree_rejects_planning_and_later_child_changes() -> Result<()> {
2657        struct AddChild {
2658            root: PathBuf,
2659        }
2660        impl CaptureSource for AddChild {
2661            fn capture(&mut self, path: &Path) -> Result<CapturedSource> {
2662                if path != self.root {
2663                    std::fs::write(self.root.join("added"), b"new")?;
2664                }
2665                FilesystemCapture::default().capture(path)
2666            }
2667        }
2668        for during_capture in [false, true] {
2669            for continue_on_error in [false, true] {
2670                let temporary = tempfile::tempdir()?;
2671                let root = temporary.path().join("source");
2672                std::fs::create_dir(&root)?;
2673                std::fs::write(root.join("child"), b"original")?;
2674                let sources = vec![root.clone()];
2675                let archive = temporary.path().join("output");
2676                let plan = plan_sources(&sources, &archive)?;
2677                if !during_capture {
2678                    std::fs::write(root.join("added"), b"new")?;
2679                }
2680                let outcome = capture_archive(
2681                    FileArchiveOutput::new(File::create(&archive)?),
2682                    capture_request(
2683                        &sources,
2684                        &archive,
2685                        &plan,
2686                        continue_on_error,
2687                    ),
2688                    &mut AddChild { root },
2689                )?;
2690                ensure!(outcome.error_count > 0);
2691                ensure!(outcome.completed == continue_on_error);
2692                drop(outcome.output);
2693                let reader = JournalReader::recover(File::open(&archive)?)?;
2694                ensure!(reader.has_diagnostics() && reader.verify().is_err());
2695                if during_capture {
2696                    ensure!(reader.members.len() == 1);
2697                }
2698            }
2699        }
2700        Ok(())
2701    }
2702
2703    #[crate::ctb_test]
2704    fn archive_planning_diagnostics_continue_and_default_stop() -> Result<()> {
2705        let temporary = tempfile::tempdir()?;
2706        let missing = temporary.path().join("missing");
2707        let good = temporary.path().join("good");
2708        std::fs::write(&good, b"good contents")?;
2709        for continue_on_error in [false, true] {
2710            let path = temporary
2711                .path()
2712                .join(format!("{continue_on_error}.cscarchive"));
2713            let result = run_archive(&ArchiveArgs {
2714                command: ArchiveCommand::Create {
2715                    archive: path.clone(),
2716                    sources: vec![missing.clone(), good.clone()],
2717                    resume: false,
2718                    continue_on_error,
2719                    journal: false,
2720                    options: ArchiveCreateOptions::default(),
2721                },
2722            })?;
2723            ensure!(
2724                matches!(result, ToolResult::Immediate { exit_code: 1, stderr, stdout }
2725                if stdout.is_empty() && !String::from_utf8_lossy(&stderr).contains("Archive created."))
2726            );
2727            let reader = JournalReader::recover(File::open(&path)?)?;
2728            ensure!(
2729                reader.errors.len() == 1
2730                    && reader
2731                        .errors
2732                        .first()
2733                        .context("Missing diagnostic")?
2734                        .path
2735                        == missing
2736            );
2737            ensure!(
2738                reader.errors.first().context("Missing diagnostic")?.stage
2739                    == JournalErrorStage::MetadataRead
2740            );
2741            ensure!(reader.is_completed() == continue_on_error);
2742            ensure!(reader.members.len() == usize::from(continue_on_error));
2743            ensure!(reader.verify().is_err());
2744            if continue_on_error {
2745                reader.verify_integrity()?;
2746            }
2747            let before = std::fs::read(&path)?;
2748            ensure!(resume_archive(&path, false).is_err());
2749            ensure!(std::fs::read(&path)? == before);
2750        }
2751        Ok(())
2752    }
2753
2754    #[crate::ctb_test]
2755    fn archive_safety_failures_never_continue() -> Result<()> {
2756        let temporary = tempfile::tempdir()?;
2757        let source = temporary.path().join("source");
2758        std::fs::create_dir(&source)?;
2759        let source_file = source.join("data.txt");
2760        std::fs::write(&source_file, b"important source payload")?;
2761        for sources in
2762            [vec![source.clone()], vec![source.clone(), source.clone()]]
2763        {
2764            let archive = if sources.len() == 1 {
2765                source.join("overlap.cscarchive")
2766            } else {
2767                temporary.path().join("duplicate.cscarchive")
2768            };
2769            ensure!(
2770                run_archive(&ArchiveArgs {
2771                    command: ArchiveCommand::Create {
2772                        archive: archive.clone(),
2773                        sources,
2774                        resume: false,
2775                        continue_on_error: true,
2776                        journal: false,
2777                        options: ArchiveCreateOptions::default(),
2778                    }
2779                })
2780                .is_err()
2781            );
2782            ensure!(!archive.exists());
2783        }
2784
2785        // Redirected stdout (`-`) overlapping source file, file inside source directory,
2786        // hardlink to source file, or symlink source pointing to redirected output must fail
2787        // before emitting a single archive byte.
2788        let nested_dir = source.join("nested");
2789        std::fs::create_dir(&nested_dir)?;
2790        let nested_out = nested_dir.join("redirected.cscarchive");
2791        std::fs::write(&nested_out, b"")?;
2792
2793        let hardlink_out = temporary.path().join("hardlink_out.cscarchive");
2794        std::fs::hard_link(&source_file, &hardlink_out)?;
2795
2796        let symlink_target_out =
2797            temporary.path().join("symlink_target_out.cscarchive");
2798        std::fs::write(&symlink_target_out, b"untouched output")?;
2799        let symlink_source = temporary.path().join("symlink_source");
2800        #[cfg(unix)]
2801        std::os::unix::fs::symlink(&symlink_target_out, &symlink_source)?;
2802        #[cfg(windows)]
2803        std::os::windows::fs::symlink_file(
2804            &symlink_target_out,
2805            &symlink_source,
2806        )?;
2807        let symlink_created = std::fs::symlink_metadata(&symlink_source).is_ok();
2808        #[cfg(windows)]
2809        if !symlink_created {
2810            assert!(
2811                ctb_io_environment::is_wine(),
2812                "Expected symlink_file to create symlink on native Windows"
2813            );
2814        }
2815        #[cfg(not(windows))]
2816        assert!(symlink_created);
2817
2818        for continue_on_error in [false, true] {
2819            // 1. Redirected stdout is the source file itself (opened without truncation here to
2820            //    verify zero bytes are written by ctb; note shell `>` truncates before exec).
2821            let out_handle =
2822                OpenOptions::new().write(true).open(&source_file)?;
2823            ensure!(
2824                run_archive_with_stdout(
2825                    &ArchiveArgs {
2826                        command: ArchiveCommand::Create {
2827                            archive: PathBuf::from("-"),
2828                            sources: vec![source_file.clone()],
2829                            resume: false,
2830                            continue_on_error,
2831                            journal: false,
2832                            options: ArchiveCreateOptions::default(),
2833                        },
2834                    },
2835                    Some(out_handle)
2836                )
2837                .is_err()
2838            );
2839            ensure!(
2840                std::fs::read(&source_file)? == b"important source payload"
2841            );
2842
2843            // 2. Redirected stdout is inside a source directory.
2844            let out_handle =
2845                OpenOptions::new().write(true).open(&nested_out)?;
2846            ensure!(
2847                run_archive_with_stdout(
2848                    &ArchiveArgs {
2849                        command: ArchiveCommand::Create {
2850                            archive: PathBuf::from("-"),
2851                            sources: vec![source.clone()],
2852                            resume: false,
2853                            continue_on_error,
2854                            journal: false,
2855                            options: ArchiveCreateOptions::default(),
2856                        },
2857                    },
2858                    Some(out_handle)
2859                )
2860                .is_err()
2861            );
2862            ensure!(std::fs::read(&nested_out)?.is_empty());
2863
2864            // 3. Redirected stdout is a hardlink to a source file.
2865            let out_handle =
2866                OpenOptions::new().write(true).open(&hardlink_out)?;
2867            ensure!(
2868                run_archive_with_stdout(
2869                    &ArchiveArgs {
2870                        command: ArchiveCommand::Create {
2871                            archive: PathBuf::from("-"),
2872                            sources: vec![source_file.clone()],
2873                            resume: false,
2874                            continue_on_error,
2875                            journal: false,
2876                            options: ArchiveCreateOptions::default(),
2877                        },
2878                    },
2879                    Some(out_handle)
2880                )
2881                .is_err()
2882            );
2883            ensure!(
2884                std::fs::read(&source_file)? == b"important source payload"
2885            );
2886
2887            // 4. Source is a symlink pointing to the redirected stdout file.
2888            #[cfg(any(unix, windows))]
2889            if symlink_created {
2890                let out_handle =
2891                    OpenOptions::new().write(true).open(&symlink_target_out)?;
2892                ensure!(
2893                    run_archive_with_stdout(
2894                        &ArchiveArgs {
2895                            command: ArchiveCommand::Create {
2896                                archive: PathBuf::from("-"),
2897                                sources: vec![symlink_source.clone()],
2898                                resume: false,
2899                                continue_on_error,
2900                                journal: false,
2901                                options: ArchiveCreateOptions::default(),
2902                            },
2903                        },
2904                        Some(out_handle)
2905                    )
2906                    .is_err()
2907                );
2908                ensure!(
2909                    std::fs::read(&symlink_target_out)? == b"untouched output"
2910                );
2911            }
2912        }
2913
2914        // Valid redirected stdout to an external file succeeds and produces a verifiable archive.
2915        let valid_stdout_archive =
2916            temporary.path().join("valid_stdout.cscarchive");
2917        let valid_handle = File::create(&valid_stdout_archive)?;
2918        let res = run_archive_with_stdout(
2919            &ArchiveArgs {
2920                command: ArchiveCommand::Create {
2921                    archive: PathBuf::from("-"),
2922                    sources: vec![source_file.clone()],
2923                    resume: false,
2924                    continue_on_error: false,
2925                    journal: false,
2926                    options: ArchiveCreateOptions::default(),
2927                },
2928            },
2929            Some(valid_handle),
2930        )?;
2931        ensure!(matches!(res, ToolResult::Immediate { exit_code: 0, .. }));
2932        let reader = JournalReader::new(File::open(&valid_stdout_archive)?)?;
2933        reader.verify_self_contained()?;
2934        ensure!(reader.members.len() == 1);
2935
2936        Ok(())
2937    }
2938
2939    #[crate::ctb_test]
2940    fn archive_runtime_removed_capture_open_and_recursive_warning() -> Result<()>
2941    {
2942        let temporary = tempfile::tempdir()?;
2943        let failed = temporary.path().join("failed");
2944        let good = temporary.path().join("good");
2945        std::fs::write(&good, b"good")?;
2946        for fault in [
2947            CaptureFault::None,
2948            CaptureFault::Capture,
2949            CaptureFault::Open,
2950            CaptureFault::Warning,
2951        ] {
2952            for continue_on_error in [false, true] {
2953                std::fs::write(&failed, b"failed")?;
2954                let archive = temporary.path().join("runtime.cscarchive");
2955                let sources = vec![failed.clone(), good.clone()];
2956                let plan = plan_sources(&sources, &archive)?;
2957                if matches!(fault, CaptureFault::None) {
2958                    std::fs::remove_file(&failed)?;
2959                }
2960                let mut capture = FaultCapture {
2961                    path: failed.clone(),
2962                    fault,
2963                    opened: Vec::new(),
2964                };
2965                let outcome = capture_archive(
2966                    FileArchiveOutput::new(File::create(&archive)?),
2967                    capture_request(
2968                        &sources,
2969                        &archive,
2970                        &plan,
2971                        continue_on_error,
2972                    ),
2973                    &mut capture,
2974                )?;
2975                ensure!(
2976                    outcome.error_count == 1
2977                        && outcome.completed == continue_on_error
2978                );
2979                ensure!(
2980                    outcome.warning_count
2981                        == usize::from(matches!(fault, CaptureFault::Warning))
2982                );
2983                drop(outcome.output);
2984                let reader = JournalReader::recover(File::open(&archive)?)?;
2985                ensure!(
2986                    reader.errors.len() == 1
2987                        && reader.members.len()
2988                            == usize::from(continue_on_error)
2989                );
2990                let expected_stage = if matches!(fault, CaptureFault::Open) {
2991                    JournalErrorStage::PayloadOpen
2992                } else {
2993                    JournalErrorStage::MetadataRead
2994                };
2995                ensure!(
2996                    reader
2997                        .errors
2998                        .first()
2999                        .context("Missing runtime diagnostic")?
3000                        .stage
3001                        == expected_stage
3002                );
3003                ensure!(
3004                    reader.warnings.len()
3005                        == usize::from(matches!(fault, CaptureFault::Warning))
3006                );
3007                if matches!(fault, CaptureFault::Warning) {
3008                    ensure!(!capture.opened.contains(&failed));
3009                    ensure!(
3010                        reader
3011                            .warnings
3012                            .first()
3013                            .context("Missing warning")?
3014                            .message
3015                            .contains("injected recursive warning")
3016                    );
3017                }
3018            }
3019        }
3020        Ok(())
3021    }
3022
3023    #[crate::ctb_test]
3024    fn archive_buffered_source_rollback_exact_members_and_sequence()
3025    -> Result<()> {
3026        let temporary = tempfile::tempdir()?;
3027        let first = temporary.path().join("first");
3028        let failed = temporary.path().join("failed");
3029        let last = temporary.path().join("last");
3030        std::fs::write(&first, b"first committed contents")?;
3031        std::fs::write(&failed, vec![0xAC; 131_072])?;
3032        std::fs::write(&last, b"last committed contents")?;
3033        let archive = temporary.path().join("rollback.cscarchive");
3034        let sources = vec![first, failed.clone(), last];
3035        let plan = plan_sources(&sources, &archive)?;
3036        for fault in [CaptureFault::Read, CaptureFault::Finish] {
3037            for continue_on_error in [false, true] {
3038                let mut capture = FaultCapture {
3039                    path: failed.clone(),
3040                    fault,
3041                    opened: Vec::new(),
3042                };
3043                let outcome = capture_archive(
3044                    FileArchiveOutput::new(File::create(&archive)?),
3045                    capture_request(
3046                        &sources,
3047                        &archive,
3048                        &plan,
3049                        continue_on_error,
3050                    ),
3051                    &mut capture,
3052                )?;
3053                ensure!(
3054                    outcome.error_count == 1
3055                        && outcome.warning_count == 0
3056                        && outcome.completed == continue_on_error
3057                );
3058                drop(outcome.output);
3059                let reader = JournalReader::recover(File::open(&archive)?)?;
3060                ensure!(
3061                    reader.errors.len() == 1
3062                        && reader.members.len()
3063                            == if continue_on_error { 2 } else { 1 }
3064                );
3065                ensure!(
3066                    reader.sequence == if continue_on_error { 2 } else { 1 }
3067                );
3068                let mut contents = Vec::new();
3069                reader
3070                    .payload(
3071                        reader
3072                            .members
3073                            .first()
3074                            .context("Missing first member")?,
3075                    )?
3076                    .read_to_end(&mut contents)?;
3077                ensure!(contents == b"first committed contents");
3078                if continue_on_error {
3079                    reader.verify_integrity()?;
3080                    contents.clear();
3081                    reader
3082                        .payload(
3083                            reader
3084                                .members
3085                                .last()
3086                                .context("Missing last member")?,
3087                        )?
3088                        .read_to_end(&mut contents)?;
3089                    ensure!(contents == b"last committed contents");
3090                }
3091                ensure!(reader.verify().is_err());
3092            }
3093        }
3094        Ok(())
3095    }
3096
3097    #[crate::ctb_test]
3098    fn archive_forward_only_source_fault_aborts_without_completion()
3099    -> Result<()> {
3100        let temporary = tempfile::tempdir()?;
3101        let failed = temporary.path().join("failed");
3102        let good = temporary.path().join("good");
3103        std::fs::write(&failed, vec![0xAC; 131_072])?;
3104        std::fs::write(&good, b"not attempted")?;
3105        let archive = temporary.path().join("stdout.cscarchive");
3106        let sources = vec![failed.clone(), good.clone()];
3107        let plan = plan_sources(&sources, &archive)?;
3108        for continue_on_error in [false, true] {
3109            let output = ForwardOutput::default();
3110            let bytes = output.0.clone();
3111            let mut capture = FaultCapture {
3112                path: failed.clone(),
3113                fault: CaptureFault::Read,
3114                opened: Vec::new(),
3115            };
3116            let error = capture_archive(
3117                output,
3118                capture_request(&sources, &archive, &plan, continue_on_error),
3119                &mut capture,
3120            )
3121            .err()
3122            .context("Forward output accepted a source fault")?;
3123            ensure!(
3124                format!("{error:#}").contains("injected source read failure")
3125            );
3126            ensure!(
3127                !capture.opened.contains(&good)
3128                    && bytes.borrow().len() > 32_768
3129            );
3130            std::fs::write(&archive, &*bytes.borrow())?;
3131            let reader = JournalReader::recover(File::open(&archive)?)?;
3132            ensure!(
3133                !reader.is_completed()
3134                    && reader.members.is_empty()
3135                    && reader.errors.is_empty()
3136            );
3137            ensure!(JournalReader::new(File::open(&archive)?).is_err());
3138        }
3139        let mut cursor = std::io::Cursor::new(Vec::new());
3140        ensure!(cursor.checkpoint()?.is_none() && cursor.rollback(0).is_err());
3141        let mut vector = Vec::new();
3142        ensure!(vector.checkpoint()?.is_none() && vector.rollback(0).is_err());
3143        Ok(())
3144    }
3145
3146    #[crate::ctb_test]
3147    fn archive_sink_diagnostic_and_rollback_failures_abort() -> Result<()> {
3148        let temporary = tempfile::tempdir()?;
3149        let failed = temporary.path().join("failed");
3150        let good = temporary.path().join("good");
3151        std::fs::write(&failed, vec![0xAC; 131_072])?;
3152        std::fs::write(&good, b"not attempted")?;
3153        let archive = temporary.path().join("sink.cscarchive");
3154        let sources = vec![failed.clone(), good.clone()];
3155        let plan = plan_sources(&sources, &archive)?;
3156        for fault in [
3157            OutputFault::Write,
3158            OutputFault::WriteZero,
3159            OutputFault::Flush,
3160            OutputFault::Sync,
3161            OutputFault::Rollback,
3162            OutputFault::Diagnostic,
3163        ] {
3164            let output = FaultOutput {
3165                output: FileArchiveOutput::new(File::create(&archive)?),
3166                fault,
3167                started: false,
3168                rolled_back: false,
3169            };
3170            let source_fault = if matches!(
3171                fault,
3172                OutputFault::Rollback | OutputFault::Diagnostic
3173            ) {
3174                CaptureFault::Read
3175            } else {
3176                CaptureFault::None
3177            };
3178            let mut capture = FaultCapture {
3179                path: failed.clone(),
3180                fault: source_fault,
3181                opened: Vec::new(),
3182            };
3183            let error = capture_archive(
3184                output,
3185                capture_request(&sources, &archive, &plan, true),
3186                &mut capture,
3187            )
3188            .err()
3189            .with_context(|| format!("Sink fault accepted: {fault:?}"))?;
3190            if matches!(fault, OutputFault::Rollback | OutputFault::Diagnostic)
3191            {
3192                ensure!(
3193                    format!("{error:#}")
3194                        .contains("injected source read failure")
3195                );
3196            }
3197            ensure!(!capture.opened.contains(&good));
3198            let reader = JournalReader::recover(File::open(&archive)?)?;
3199            ensure!(!reader.is_completed() && reader.errors.is_empty());
3200        }
3201        Ok(())
3202    }
3203
3204    #[crate::ctb_test]
3205    #[cfg(unix)]
3206    fn archive_failed_hardlink_definition_is_never_referenced() -> Result<()> {
3207        let temporary = tempfile::tempdir()?;
3208        let failed = temporary.path().join("failed");
3209        let definition = temporary.path().join("definition");
3210        let reference = temporary.path().join("reference");
3211        std::fs::write(&failed, vec![0xCA; 131_072])?;
3212        std::fs::hard_link(&failed, &definition)?;
3213        std::fs::hard_link(&failed, &reference)?;
3214        let archive = temporary.path().join("hardlinks.cscarchive");
3215        let sources = vec![failed.clone(), definition.clone(), reference];
3216        let plan = plan_sources(&sources, &archive)?;
3217        let mut capture = FaultCapture {
3218            path: failed,
3219            fault: CaptureFault::Read,
3220            opened: Vec::new(),
3221        };
3222        let outcome = capture_archive(
3223            FileArchiveOutput::new(File::create(&archive)?),
3224            capture_request(&sources, &archive, &plan, true),
3225            &mut capture,
3226        )?;
3227        ensure!(outcome.error_count == 1 && outcome.completed);
3228        drop(outcome.output);
3229        let reader = JournalReader::new(File::open(&archive)?)?;
3230        reader.verify_integrity()?;
3231        validate_members(&reader)?;
3232        ensure!(reader.members.len() == 2);
3233        ensure!(matches!(
3234            reader
3235                .members
3236                .first()
3237                .context("Missing definition")?
3238                .entity
3239                .kind,
3240            FileEntityKind::Regular { .. }
3241        ));
3242        let FileEntityKind::Hardlink {
3243            target_relative_path,
3244        } = &reader
3245            .members
3246            .last()
3247            .context("Missing hardlink")?
3248            .entity
3249            .kind
3250        else {
3251            bail!("Expected a committed hardlink reference");
3252        };
3253        ensure!(target_relative_path.to_path_buf()? == Path::new("definition"));
3254        Ok(())
3255    }
3256
3257    #[crate::ctb_test]
3258    fn archive_diagnostic_status_rejects_extraction() -> Result<()> {
3259        let temporary = tempfile::tempdir()?;
3260        let archive = temporary.path().join("failed.cscarchive");
3261        let destination = temporary.path().join("destination");
3262        let source = temporary.path().join("unreadable");
3263        let session = JournalSessionRecord {
3264            sources: vec![source.clone()],
3265            destination: archive.clone(),
3266            origin_platform: u32::from(current_platform()),
3267            environment: None,
3268        };
3269        let mut writer = JournalWriter::new(
3270            File::create(&archive)?,
3271            &session,
3272            crate::journal::stream::JournalMagic::ArchiveV2,
3273        )?;
3274        let mut committed =
3275            FileEntity::from_vec(b"salvaged member payload".to_vec());
3276        committed.identity.relative_path = Some(PathBuf::from("salvaged.txt"));
3277        let mut payload = ctb_io::file::MemoryPayloadSource::new(
3278            b"salvaged member payload".to_vec(),
3279        )?;
3280        writer.write_entity(&committed, Some(&mut payload))?;
3281        let mut unrestorable = FileEntity::from_vec(Vec::new());
3282        unrestorable.identity.relative_path =
3283            Some(PathBuf::from("unrestorable.sock"));
3284        unrestorable.kind = FileEntityKind::Socket;
3285        writer.write_entity(&unrestorable, None)?;
3286        writer.record_error(&crate::journal::JournalErrorRecord {
3287            path: source.clone(),
3288            raw_path: source.as_os_str().as_encoded_bytes().to_vec(),
3289            stage: crate::journal::JournalErrorStage::MetadataRead,
3290            error_message: "Injected capture failure".to_owned(),
3291            os_error: Some(13),
3292            timestamp_sec: 0,
3293        })?;
3294        drop(writer.finish()?);
3295        let listed = run_archive(&ArchiveArgs {
3296            command: ArchiveCommand::List {
3297                archive: archive.clone(),
3298            },
3299        })?;
3300        ensure!(
3301            matches!(listed, ToolResult::Immediate { exit_code: 1, stderr, .. }
3302            if String::from_utf8_lossy(&stderr).contains("Injected capture failure"))
3303        );
3304        ensure!(
3305            run_archive(&ArchiveArgs {
3306                command: ArchiveCommand::Verify {
3307                    archive: archive.clone(),
3308                    recover: false
3309                }
3310            })
3311            .is_err()
3312        );
3313        ensure!(
3314            run_archive(&ArchiveArgs {
3315                command: ArchiveCommand::Extract {
3316                    archive: archive.clone(),
3317                    destination: destination.clone(),
3318                    overwrite: false,
3319                    trust_symlink_targets: false,
3320                    best_effort_metadata: false,
3321                    copy_specials_as_specials: false,
3322                    strict: false,
3323                    check_atime: false,
3324                    check_ctime: false,
3325                    check_birthtime: false,
3326                    recover: false,
3327                    apple_write: Default::default(),
3328                }
3329            })
3330            .is_err()
3331        );
3332        ensure!(
3333            !destination.exists(),
3334            "Failed capture modified extraction destination"
3335        );
3336        let verify_recover = run_archive(&ArchiveArgs {
3337            command: ArchiveCommand::Verify {
3338                archive: archive.clone(),
3339                recover: true,
3340            },
3341        })?;
3342        let ToolResult::Immediate {
3343            exit_code: verify_code,
3344            stderr: verify_stderr,
3345            ..
3346        } = verify_recover
3347        else {
3348            bail!(
3349                "Expected Immediate ToolResult from archive verify --recover"
3350            );
3351        };
3352        let verify_diag = String::from_utf8_lossy(&verify_stderr);
3353        ensure!(
3354            verify_code == 1,
3355            "Recover verify on diagnostic archive must report non-success partial status"
3356        );
3357        ensure!(
3358            verify_diag.contains("Injected capture failure")
3359                && verify_diag.contains("Archive is not a clean capture.")
3360        );
3361
3362        let extract_recover = run_archive(&ArchiveArgs {
3363            command: ArchiveCommand::Extract {
3364                archive,
3365                destination: destination.clone(),
3366                overwrite: false,
3367                trust_symlink_targets: false,
3368                best_effort_metadata: false,
3369                copy_specials_as_specials: false,
3370                strict: false,
3371                check_atime: false,
3372                check_ctime: false,
3373                check_birthtime: false,
3374                recover: true,
3375                apple_write: Default::default(),
3376            },
3377        })?;
3378        let ToolResult::Immediate {
3379            exit_code: extract_code,
3380            stderr: extract_stderr,
3381            ..
3382        } = extract_recover
3383        else {
3384            bail!(
3385                "Expected Immediate ToolResult from archive extract --recover"
3386            );
3387        };
3388        let extract_diag = String::from_utf8_lossy(&extract_stderr);
3389        ensure!(
3390            extract_code == 1,
3391            "Recover extract on diagnostic archive must report non-success partial status"
3392        );
3393        ensure!(extract_diag.contains("Injected capture failure"));
3394        ensure!(extract_diag.contains("Extraction loss: Archive member cannot be restored: unrestorable.sock"));
3395        ensure!(extract_diag.contains("extraction_losses: 1"));
3396        ensure!(
3397            std::fs::read(destination.join("salvaged.txt"))?
3398                == b"salvaged member payload"
3399        );
3400        ensure!(!destination.join("unrestorable.sock").exists());
3401        Ok(())
3402    }
3403
3404    #[crate::ctb_test]
3405    fn archive_stdout_argument_parsing() -> Result<()> {
3406        let args =
3407            ArchiveArgs::try_parse_from(["archive", "create", "-", "source/"])?;
3408        ensure!(
3409            matches!(args.command, ArchiveCommand::Create { archive, sources, resume: false, continue_on_error: false, journal: false, .. }
3410            if archive == Path::new("-") && sources == vec![PathBuf::from("source/")])
3411        );
3412        ensure!(
3413            ArchiveArgs::try_parse_from([
3414                "archive",
3415                "create",
3416                "output",
3417                "--resume",
3418                "--continue-on-error"
3419            ])
3420            .is_err()
3421        );
3422        let stdout_resume = ArchiveArgs::try_parse_from([
3423            "archive", "create", "-", "--resume",
3424        ])?;
3425        ensure!(run_archive(&stdout_resume).is_err());
3426        let extract_recover = ArchiveArgs::try_parse_from([
3427            "archive",
3428            "extract",
3429            "test.cscarchive",
3430            "dest/",
3431            "--recover",
3432        ])?;
3433        ensure!(matches!(
3434            extract_recover.command,
3435            ArchiveCommand::Extract {
3436                recover: true,
3437                best_effort_metadata: false,
3438                strict: false,
3439                ..
3440            }
3441        ));
3442        let targeted = ArchiveArgs::try_parse_from([
3443            "archive",
3444            "extract",
3445            "test.cscarchive",
3446            "dest/",
3447            "--check-birthtime",
3448        ])?;
3449        ensure!(matches!(
3450            targeted.command,
3451            ArchiveCommand::Extract {
3452                check_birthtime: true,
3453                check_atime: false,
3454                check_ctime: false,
3455                best_effort_metadata: false,
3456                strict: false,
3457                ..
3458            }
3459        ));
3460        let full = ArchiveArgs::try_parse_from([
3461            "archive",
3462            "extract",
3463            "test.cscarchive",
3464            "dest/",
3465            "--strict",
3466            "--best-effort-metadata",
3467        ])?;
3468        ensure!(matches!(
3469            full.command,
3470            ArchiveCommand::Extract {
3471                strict: true,
3472                best_effort_metadata: true,
3473                ..
3474            }
3475        ));
3476        let extract_salvage = ArchiveArgs::try_parse_from([
3477            "archive",
3478            "extract",
3479            "test.cscarchive",
3480            "dest/",
3481            "--salvage",
3482        ])?;
3483        ensure!(matches!(
3484            extract_salvage.command,
3485            ArchiveCommand::Extract { recover: true, .. }
3486        ));
3487        let extract_errors = ArchiveArgs::try_parse_from([
3488            "archive",
3489            "extract",
3490            "test.cscarchive",
3491            "dest/",
3492            "--allow-archive-errors",
3493        ])?;
3494        ensure!(matches!(
3495            extract_errors.command,
3496            ArchiveCommand::Extract { recover: true, .. }
3497        ));
3498        let extract_jerrors = ArchiveArgs::try_parse_from([
3499            "archive",
3500            "extract",
3501            "test.cscarchive",
3502            "dest/",
3503            "--allow-journal-errors",
3504        ])?;
3505        ensure!(matches!(
3506            extract_jerrors.command,
3507            ArchiveCommand::Extract { recover: true, .. }
3508        ));
3509        let verify_recover = ArchiveArgs::try_parse_from([
3510            "archive",
3511            "verify",
3512            "test.cscarchive",
3513            "--recover",
3514        ])?;
3515        ensure!(matches!(
3516            verify_recover.command,
3517            ArchiveCommand::Verify { recover: true, .. }
3518        ));
3519        Ok(())
3520    }
3521
3522    #[cfg(target_os = "linux")]
3523    #[crate::ctb_test]
3524    fn archive_directory_timestamp_checks_are_explicit() -> Result<()> {
3525        let temporary = tempfile::tempdir()?;
3526        let source = temporary.path().join("source");
3527        std::fs::create_dir(&source)?;
3528        let archive = temporary.path().join("directory.cscarchive");
3529        let sources = vec![source];
3530        let plan = plan_sources(&sources, &archive)?;
3531        let outcome = create_archive(
3532            File::create(&archive)?,
3533            &sources,
3534            &archive,
3535            &plan,
3536            false,
3537            None,
3538            false,
3539        )?;
3540        ensure!(
3541            outcome.completed
3542                && outcome.error_count == 0
3543                && outcome.warning_count == 0
3544        );
3545        drop(outcome.output);
3546        let mut reader = JournalReader::new(File::open(&archive)?)?;
3547        for member in &mut reader.members {
3548            let timestamps = member
3549                .entity
3550                .metadata
3551                .timestamps
3552                .as_mut()
3553                .context("Missing directory times")?;
3554            timestamps.ctime_sec = 1;
3555            timestamps.ctime_nsec = 0;
3556        }
3557        extract_archive(
3558            &reader,
3559            &temporary.path().join("normal"),
3560            &MaterializeOptions::default(),
3561            false,
3562        )?;
3563        for (name, options, expected) in [
3564            (
3565                "ctime",
3566                MaterializeOptions {
3567                    check_ctime: true,
3568                    ..Default::default()
3569                },
3570                "Ctime mismatch",
3571            ),
3572            (
3573                "full",
3574                MaterializeOptions {
3575                    check_atime: true,
3576                    check_ctime: true,
3577                    check_birthtime: true,
3578                    ..Default::default()
3579                },
3580                "Cannot reproduce birth time",
3581            ),
3582        ] {
3583            let error = extract_archive(
3584                &reader,
3585                &temporary.path().join(name),
3586                &options,
3587                false,
3588            )
3589            .err()
3590            .context("Explicit timestamp checks unexpectedly passed")?;
3591            let formatted = format!("{error:#}");
3592            ensure!(
3593                formatted.contains(expected)
3594                    || formatted.contains("Ctime mismatch"),
3595                "{error:#}"
3596            );
3597        }
3598        Ok(())
3599    }
3600
3601    #[crate::ctb_test]
3602    fn archive_recover_incomplete_archive() -> Result<()> {
3603        let temporary = tempfile::tempdir()?;
3604        let source = temporary.path().join("source");
3605        std::fs::create_dir(&source)?;
3606        std::fs::write(source.join("first"), b"hello first")?;
3607        let archive_path = temporary.path().join("incomplete.cscarchive");
3608        let sources = vec![source.clone()];
3609        let plan = plan_sources(&sources, &archive_path)?;
3610        let file = File::create(&archive_path)?;
3611        let outcome = create_archive(
3612            FileArchiveOutput::new(file),
3613            &sources,
3614            &archive_path,
3615            &plan,
3616            false,
3617            None,
3618            false,
3619        )?;
3620        drop(outcome.output);
3621
3622        let reader = JournalReader::recover(File::open(&archive_path)?)?;
3623        ensure!(reader.is_completed());
3624
3625        // Truncate completion marker
3626        let file = OpenOptions::new()
3627            .read(true)
3628            .write(true)
3629            .open(&archive_path)?;
3630        let marker_size = 1;
3631        let len = file.metadata()?.len();
3632        file.set_len(len.saturating_sub(marker_size))?;
3633
3634        let destination = temporary.path().join("restored");
3635        ensure!(
3636            run_archive(&ArchiveArgs {
3637                command: ArchiveCommand::Extract {
3638                    archive: archive_path.clone(),
3639                    destination: destination.clone(),
3640                    overwrite: false,
3641                    trust_symlink_targets: false,
3642                    best_effort_metadata: false,
3643                    copy_specials_as_specials: false,
3644                    strict: false,
3645                    check_atime: false,
3646                    check_ctime: false,
3647                    check_birthtime: false,
3648                    recover: false,
3649                    apple_write: Default::default(),
3650                }
3651            })
3652            .is_err()
3653        );
3654        ensure!(!destination.exists());
3655
3656        let verify_recover = run_archive(&ArchiveArgs {
3657            command: ArchiveCommand::Verify {
3658                archive: archive_path.clone(),
3659                recover: true,
3660            },
3661        })?;
3662        ensure!(matches!(
3663            verify_recover,
3664            ToolResult::Immediate { exit_code: 1, ref stderr, .. }
3665                if String::from_utf8_lossy(stderr).contains("incomplete: true")
3666        ));
3667
3668        let extract_recover = run_archive(&ArchiveArgs {
3669            command: ArchiveCommand::Extract {
3670                archive: archive_path.clone(),
3671                destination: destination.clone(),
3672                overwrite: false,
3673                trust_symlink_targets: false,
3674                best_effort_metadata: false,
3675                copy_specials_as_specials: false,
3676                strict: false,
3677                check_atime: false,
3678                check_ctime: false,
3679                check_birthtime: false,
3680                recover: true,
3681                apple_write: Default::default(),
3682            },
3683        })?;
3684        ensure!(matches!(
3685            extract_recover,
3686            ToolResult::Immediate { exit_code: 1, ref stderr, .. }
3687                if String::from_utf8_lossy(stderr).contains("incomplete: true")
3688        ));
3689        ensure!(
3690            std::fs::read(destination.join("source/first"))? == b"hello first"
3691        );
3692        Ok(())
3693    }
3694
3695    #[crate::ctb_test]
3696    #[cfg(unix)]
3697    fn archive_raw_names_source_free_roundtrip() -> Result<()> {
3698        use std::os::unix::ffi::OsStringExt;
3699
3700        let temporary = tempfile::tempdir()?;
3701        let source = temporary.path().join("source");
3702        let destination = temporary.path().join("destination");
3703        let archive = temporary.path().join("names.cscarchive");
3704        std::fs::create_dir(&source)?;
3705        let names = [
3706            std::ffi::OsString::from_vec(b"name\xff".to_vec()),
3707            std::ffi::OsString::from_vec(b"name\xfe".to_vec()),
3708            std::ffi::OsString::from("caf\u{e9}"),
3709            std::ffi::OsString::from("cafe\u{301}"),
3710        ];
3711        for name in &names {
3712            std::fs::create_dir(source.join(name))?;
3713            std::fs::write(
3714                source.join(name).join(name),
3715                name.as_encoded_bytes(),
3716            )?;
3717        }
3718        run_archive(&ArchiveArgs {
3719            command: ArchiveCommand::Create {
3720                archive: archive.clone(),
3721                sources: vec![source.join("")],
3722                resume: false,
3723                continue_on_error: false,
3724                journal: false,
3725                options: ArchiveCreateOptions::default(),
3726            },
3727        })?;
3728        for name in &names {
3729            std::fs::remove_file(source.join(name).join(name))?;
3730            std::fs::remove_dir(source.join(name))?;
3731        }
3732        std::fs::remove_dir(source)?;
3733        let reader = JournalReader::new(File::open(&archive)?)?;
3734        reader.verify()?;
3735        extract_archive(
3736            &reader,
3737            &destination,
3738            &MaterializeOptions::default(),
3739            false,
3740        )?;
3741        for name in &names {
3742            ensure!(
3743                std::fs::read(destination.join(name).join(name))?
3744                    == name.as_encoded_bytes()
3745            );
3746        }
3747        ensure!(std::fs::read_dir(destination)?.count() == names.len());
3748        Ok(())
3749    }
3750
3751    #[crate::ctb_test]
3752    fn archive_source_free_tree_roundtrip() -> Result<()> {
3753        let temporary = tempfile::tempdir()?;
3754        let source = temporary.path().join("source");
3755        std::fs::create_dir(&source)?;
3756        let data = vec![0xA5; 131_072];
3757        std::fs::write(source.join("data"), &data)?;
3758        std::fs::write(source.join("empty"), [])?;
3759        let archive_path = temporary.path().join("backup.cscarchive");
3760        let sources = vec![source.clone()];
3761        let plan = plan_sources(&sources, &archive_path)?;
3762        let file = File::create(&archive_path)?;
3763        let outcome = create_archive(
3764            FileArchiveOutput::new(file),
3765            &sources,
3766            &archive_path,
3767            &plan,
3768            false,
3769            None,
3770            false,
3771        )?;
3772        ensure!(
3773            outcome.completed
3774                && outcome.error_count == 0
3775                && outcome.warning_count == 0
3776        );
3777        drop(outcome.output);
3778        std::fs::remove_dir_all(&source)?;
3779        let reader = JournalReader::new(File::open(&archive_path)?)?;
3780        reader.verify()?;
3781        let destination = temporary.path().join("restored");
3782        let options = MaterializeOptions {
3783            force_overwrite: true,
3784            ..Default::default()
3785        };
3786        extract_archive(&reader, &destination, &options, false)?;
3787        ensure!(std::fs::read(destination.join("source/data"))? == data);
3788        ensure!(std::fs::read(destination.join("source/empty"))?.is_empty());
3789        ensure!(
3790            extract_archive(&reader, &destination, &options, false).is_err()
3791        );
3792        Ok(())
3793    }
3794
3795    #[crate::ctb_test]
3796    #[cfg(unix)]
3797    fn archive_existing_root_requires_overwrite() -> Result<()> {
3798        use std::os::unix::fs::PermissionsExt;
3799        let temporary = tempfile::tempdir()?;
3800        let source = temporary.path().join("source");
3801        let destination = temporary.path().join("destination");
3802        let archive = temporary.path().join("backup.cscarchive");
3803        std::fs::create_dir(&source)?;
3804        std::fs::create_dir(&destination)?;
3805        std::fs::write(source.join("data"), b"new payload")?;
3806        std::fs::write(destination.join("data"), b"original payload")?;
3807        std::fs::set_permissions(
3808            &source,
3809            std::fs::Permissions::from_mode(0o700),
3810        )?;
3811        std::fs::set_permissions(
3812            &destination,
3813            std::fs::Permissions::from_mode(0o755),
3814        )?;
3815        run_archive(&ArchiveArgs {
3816            command: ArchiveCommand::Create {
3817                archive: archive.clone(),
3818                sources: vec![source.join("")],
3819                resume: false,
3820                continue_on_error: false,
3821                journal: false,
3822                options: ArchiveCreateOptions::default(),
3823            },
3824        })?;
3825        let reader = JournalReader::new(File::open(archive)?)?;
3826        let options = MaterializeOptions::default();
3827        ensure!(
3828            extract_archive(&reader, &destination, &options, false).is_err()
3829        );
3830        ensure!(
3831            std::fs::read(destination.join("data"))? == b"original payload"
3832        );
3833        ensure!(
3834            std::fs::metadata(&destination)?.permissions().mode() & 0o777
3835                == 0o755
3836        );
3837        std::fs::remove_file(destination.join("data"))?;
3838        ensure!(
3839            extract_archive(&reader, &destination, &options, false).is_err()
3840        );
3841        ensure!(!destination.join("data").exists());
3842        let options = MaterializeOptions {
3843            existing_entry_policy: ctb_io::file::ExistingEntryPolicy::Replace,
3844            ..options
3845        };
3846        extract_archive(&reader, &destination, &options, false)?;
3847        ensure!(std::fs::read(destination.join("data"))? == b"new payload");
3848        ensure!(
3849            std::fs::metadata(destination)?.permissions().mode() & 0o777
3850                == 0o700
3851        );
3852        Ok(())
3853    }
3854
3855    #[crate::ctb_test]
3856    fn archive_resume_rejects_changed_source_before_truncation() -> Result<()> {
3857        let temporary = tempfile::tempdir()?;
3858        let source = temporary.path().join("data");
3859        std::fs::write(&source, b"unchanged")?;
3860        let path = temporary.path().join("backup.cscarchive");
3861        let sources = vec![source.clone()];
3862        let plan = plan_sources(&sources, &path)?;
3863        let outcome = create_archive(
3864            File::create(&path)?,
3865            &sources,
3866            &path,
3867            &plan,
3868            false,
3869            None,
3870            false,
3871        )?;
3872        ensure!(
3873            outcome.completed
3874                && outcome.error_count == 0
3875                && outcome.warning_count == 0
3876        );
3877        drop(outcome.output);
3878        let completed = std::fs::read(&path)?;
3879        let mut marker = DcMstring::new();
3880        marker.push_char(ctb_formats_dcdata::dc::DC_OPERATION_COMPLETED);
3881        let recovered_length = u64::try_from(completed.len())?
3882            .checked_sub(u64::try_from(marker.payload_bytes().len())?)
3883            .context("Archive too short")?;
3884        OpenOptions::new()
3885            .write(true)
3886            .open(&path)?
3887            .set_len(recovered_length)?;
3888        let before = std::fs::read(&path)?;
3889        std::fs::write(&source, b"modified!")?;
3890        ensure!(resume_archive(&path, false).is_err());
3891        ensure!(
3892            std::fs::read(&path)? == before,
3893            "Failed source validation changed the archive"
3894        );
3895        Ok(())
3896    }
3897
3898    #[crate::ctb_test]
3899    fn archive_resume_unclosed_tail_and_complete() -> Result<()> {
3900        let temporary = tempfile::tempdir()?;
3901        let source = temporary.path().join("data");
3902        std::fs::write(&source, vec![0x5A; 16_384])?;
3903        let path = temporary.path().join("backup.cscarchive");
3904        let sources = vec![source];
3905        let plan = plan_sources(&sources, &path)?;
3906        let outcome = create_archive(
3907            File::create(&path)?,
3908            &sources,
3909            &path,
3910            &plan,
3911            false,
3912            None,
3913            false,
3914        )?;
3915        ensure!(
3916            outcome.completed
3917                && outcome.error_count == 0
3918                && outcome.warning_count == 0
3919        );
3920        drop(outcome.output);
3921        let length = std::fs::metadata(&path)?.len();
3922        let mut marker = DcMstring::new();
3923        marker.push_char(ctb_formats_dcdata::dc::DC_OPERATION_COMPLETED);
3924        OpenOptions::new().write(true).open(&path)?.set_len(
3925            length
3926                .checked_sub(u64::try_from(marker.payload_bytes().len())?)
3927                .context("Missing completion marker")?,
3928        )?;
3929        let mut tail = DcMstring::new();
3930        tail.push_char(ctb_formats_dcdata::dc::DC_BEGIN_CHECKSUMMED_SECTION);
3931        OpenOptions::new()
3932            .append(true)
3933            .open(&path)?
3934            .write_all(tail.payload_bytes())?;
3935        resume_archive(&path, false)?;
3936        let reader = JournalReader::new(File::open(&path)?)?;
3937        reader.verify()?;
3938        ensure!(reader.members.len() == 1);
3939        ensure!(
3940            resume_archive(&path, false).is_err(),
3941            "Completed archive accepted append/resume"
3942        );
3943        Ok(())
3944    }
3945
3946    #[crate::ctb_test]
3947    fn archive_preflight_rejects_traversal_and_symlink_ancestors() -> Result<()>
3948    {
3949        ensure!(normalized_member(Path::new("../outside")).is_err());
3950        ensure!(normalized_member(Path::new("/outside")).is_err());
3951        ensure!(normalized_member(Path::new("C:/outside")).is_err());
3952        let temporary = tempfile::tempdir()?;
3953        let source = temporary.path().join("source");
3954        std::fs::create_dir(&source)?;
3955        std::fs::write(source.join("data"), b"archive")?;
3956        let path = temporary.path().join("backup.cscarchive");
3957        let sources = vec![source];
3958        let plan = plan_sources(&sources, &path)?;
3959        let outcome = create_archive(
3960            File::create(&path)?,
3961            &sources,
3962            &path,
3963            &plan,
3964            false,
3965            None,
3966            false,
3967        )?;
3968        ensure!(
3969            outcome.completed
3970                && outcome.error_count == 0
3971                && outcome.warning_count == 0
3972        );
3973        drop(outcome.output);
3974        let reader = JournalReader::new(File::open(&path)?)?;
3975        let destination = temporary.path().join("destination");
3976        std::fs::create_dir(&destination)?;
3977        #[cfg(any(unix, windows))]
3978        {
3979            let outside = temporary.path().join("outside");
3980            std::fs::create_dir(&outside)?;
3981            let link_dest = destination.join("source");
3982            #[cfg(unix)]
3983            std::os::unix::fs::symlink(&outside, &link_dest)?;
3984            #[cfg(windows)]
3985            std::os::windows::fs::symlink_dir(&outside, &link_dest)?;
3986            let symlink_created = std::fs::symlink_metadata(&link_dest).is_ok();
3987            #[cfg(windows)]
3988            if !symlink_created {
3989                assert!(
3990                    ctb_io_environment::is_wine(),
3991                    "Expected symlink_dir to create symlink on native Windows"
3992                );
3993                return Ok(());
3994            }
3995            #[cfg(not(windows))]
3996            assert!(symlink_created);
3997            ensure!(
3998                extract_archive(
3999                    &reader,
4000                    &destination,
4001                    &MaterializeOptions {
4002                        existing_entry_policy:
4003                            ctb_io::file::ExistingEntryPolicy::Replace,
4004                        ..Default::default()
4005                    },
4006                    false
4007                )
4008                .is_err()
4009            );
4010            ensure!(!outside.join("data").exists());
4011        }
4012        Ok(())
4013    }
4014
4015    #[cfg(windows)]
4016    fn windows_qualification_archive(
4017        source: &Path,
4018        archive: &Path,
4019    ) -> Result<JournalReader> {
4020        let sources = vec![source.to_path_buf()];
4021        let plan = plan_sources(&sources, archive)?;
4022        let outcome = create_archive(
4023            FileArchiveOutput::new(File::create(archive)?),
4024            &sources,
4025            archive,
4026            &plan,
4027            false,
4028            None,
4029            false,
4030        )?;
4031        let completed = outcome.completed;
4032        drop(outcome.output);
4033        let reader = JournalReader::recover(File::open(archive)?)?;
4034        ensure!(
4035            completed && reader.errors.is_empty() && reader.warnings.is_empty(),
4036            "Windows capture was not clean: errors {:?}, warnings {:?}",
4037            reader.errors,
4038            reader.warnings
4039        );
4040        reader.verify_self_contained()?;
4041        Ok(reader)
4042    }
4043
4044    #[cfg(windows)]
4045    #[crate::ctb_test]
4046    fn windows_native_qualification_large_ads_source_free_archive() -> Result<()>
4047    {
4048        use ctb_io::file::streams::{
4049            AttachedStreamSource, FilesystemStreamSource,
4050        };
4051        use std::os::windows::ffi::{OsStrExt, OsStringExt};
4052        let temporary = tempfile::tempdir()?;
4053        let source = temporary.path().join("source.bin");
4054        std::fs::write(&source, b"primary payload")?;
4055        let mut surrogate = vec![58_u16, 0xd800];
4056        surrogate.extend(":$DATA".encode_utf16());
4057        let names = [
4058            ":e\u{301}:$DATA".encode_utf16().collect::<Vec<_>>(),
4059            ":\u{e9}:$DATA".encode_utf16().collect::<Vec<_>>(),
4060            surrogate,
4061        ];
4062        let mut expected = Vec::new();
4063        for (index, name) in names.into_iter().enumerate() {
4064            let mut path = source.as_os_str().encode_wide().collect::<Vec<_>>();
4065            path.extend(&name);
4066            let path = PathBuf::from(std::ffi::OsString::from_wide(&path));
4067            let size = 2_097_169_u64;
4068            let byte = u8::try_from(index)?
4069                .checked_add(41)
4070                .context("Fixture byte overflow")?;
4071            let mut output = match File::create(&path) {
4072                Ok(file) => file,
4073                Err(err) if err.raw_os_error() == Some(2) => {
4074                    assert!(
4075                        ctb_io_environment::is_wine(),
4076                        "Unexpected NTFS ADS creation failure on native Windows: {err}"
4077                    );
4078                    return Ok(());
4079                }
4080                Err(err) => return Err(err.into()),
4081            };
4082            ensure!(
4083                std::io::copy(
4084                    &mut std::io::Read::take(std::io::repeat(byte), size),
4085                    &mut output
4086                )? == size
4087            );
4088            output.sync_all()?;
4089            let mut digest = ctb_formats_checksum::Sha256Stream::new();
4090            std::io::copy(
4091                &mut std::io::Read::take(std::io::repeat(byte), size),
4092                &mut digest,
4093            )?;
4094            expected.push((
4095                ctb_io::file::StreamName::from_windows_utf16(&name),
4096                size,
4097                digest.finalize(),
4098            ));
4099        }
4100        let archive = temporary.path().join("ads.cscarchive");
4101        let reader = windows_qualification_archive(&source, &archive)?;
4102        let member = reader
4103            .members
4104            .iter()
4105            .find(|member| {
4106                member.entity.identity.relative_path.as_deref()
4107                    == Some(Path::new("source.bin"))
4108            })
4109            .context("Missing ADS archive member")?;
4110        ensure!(member.entity.streams.len() == expected.len());
4111        for stream in &member.entity.streams {
4112            ensure!(
4113                stream.data.is_none()
4114                    && matches!(
4115                        stream.payload.as_ref().map(|payload| &payload.0),
4116                        Some(
4117                            ctb_formats_dcstring::BinaryPayloadRef::FileSpan { .. }
4118                        )
4119                    ),
4120                "Large ADS was materialized in memory"
4121            );
4122        }
4123        std::fs::remove_file(&source)?;
4124        for strict_lossless in [true, false] {
4125            let destination = temporary.path().join(if strict_lossless {
4126                "default"
4127            } else {
4128                "best-effort"
4129            });
4130            let options = MaterializeOptions {
4131                strict_lossless,
4132                ..Default::default()
4133            };
4134            extract_archive(&reader, &destination, &options, false)
4135                .with_context(|| format!("ADS qualification with strict_lossless={strict_lossless}"))?;
4136            let restored = destination.join("source.bin");
4137            ensure!(std::fs::read(&restored)? == b"primary payload");
4138            let streams =
4139                ctb_io::file::streams::read_and_hash_streams(&restored)?;
4140            ensure!(streams.len() == expected.len());
4141            for (name, size, sha256) in &expected {
4142                let stream = streams
4143                    .iter()
4144                    .find(|stream| stream.name.as_ref() == Some(name))
4145                    .context("ADS name changed during archive round-trip")?;
4146                ensure!(stream.data.is_none());
4147                ensure!(
4148                    matches!(stream.entity.kind, FileEntityKind::Regular { size: actual, sha256: digest, .. } if actual == *size && digest == *sha256)
4149                );
4150                let mut payload = FilesystemStreamSource.open(stream)?;
4151                let mut digest = ctb_formats_checksum::Sha256Stream::new();
4152                ensure!(std::io::copy(&mut payload, &mut digest)? == *size);
4153                ensure!(digest.finalize() == *sha256);
4154            }
4155        }
4156        Ok(())
4157    }
4158
4159    #[cfg(windows)]
4160    #[crate::ctb_test]
4161    fn windows_native_qualification_reparse_source_free_archive() -> Result<()>
4162    {
4163        use ctb_io::file::metadata::{NativeMetadataValue, reparse, windows};
4164        let temporary = tempfile::tempdir()?;
4165        let source = temporary.path().join("source");
4166        std::fs::create_dir_all(source.join("target-dir"))?;
4167        std::fs::write(source.join("target-file"), b"target payload")?;
4168        std::os::windows::fs::symlink_file(
4169            "target-file",
4170            source.join("file-link"),
4171        )?;
4172        std::os::windows::fs::symlink_dir(
4173            "target-dir",
4174            source.join("dir-link"),
4175        )?;
4176        let junction = source.join("junction");
4177        std::fs::create_dir(&junction)?;
4178        let target = std::fs::canonicalize(source.join("target-dir"))?;
4179        let target =
4180            target.to_str().context("Fixture target is not Unicode")?;
4181        let target = target
4182            .strip_prefix(r"\\?\")
4183            .context("Missing native fixture path prefix")?;
4184        let buffer = reparse::build_mount_point_reparse_buffer(
4185            &format!(r"\??\{target}"),
4186            target,
4187        )?;
4188        let mut native = FileEntity::from_filesystem(&junction, None)?
4189            .metadata
4190            .native
4191            .context("Missing native Windows metadata")?;
4192        native
4193            .values
4194            .insert("reparse.data".into(), NativeMetadataValue::Bytes(buffer));
4195        if let Err(err) =
4196            windows::apply_windows_reparse_metadata(&junction, &native, true)
4197        {
4198            assert!(
4199                ctb_io_environment::is_wine(),
4200                "Unexpected junction reparse point failure on native Windows: {err:#}"
4201            );
4202            assert_eq!(
4203                err.downcast_ref::<std::io::Error>()
4204                    .and_then(std::io::Error::raw_os_error),
4205                Some(50)
4206            );
4207            return Ok(());
4208        }
4209        let mut expected = Vec::new();
4210        for name in ["file-link", "dir-link", "junction"] {
4211            let entity = FileEntity::from_filesystem(&source.join(name), None)?;
4212            ensure!(
4213                matches!(entity.kind, FileEntityKind::Symlink { .. }),
4214                "Reparse point was not captured as a link: {name}"
4215            );
4216            let native = entity
4217                .metadata
4218                .native
4219                .context("Missing captured reparse metadata")?;
4220            let bytes = native
4221                .values
4222                .get("reparse.data")
4223                .context("Missing captured reparse buffer")?
4224                .clone();
4225            expected.push((name, entity.kind, bytes));
4226        }
4227        let archive = temporary.path().join("reparse.cscarchive");
4228        let reader = windows_qualification_archive(&source, &archive)?;
4229        for name in ["file-link", "dir-link", "junction"] {
4230            std::fs::remove_file(source.join(name))
4231                .or_else(|_| std::fs::remove_dir(source.join(name)))?;
4232        }
4233        std::fs::remove_dir_all(&source)?;
4234        for strict_lossless in [true, false] {
4235            let destination = temporary.path().join(if strict_lossless {
4236                "default"
4237            } else {
4238                "best-effort"
4239            });
4240            let options = MaterializeOptions {
4241                strict_lossless,
4242                ..Default::default()
4243            };
4244            extract_archive(&reader, &destination, &options, false)
4245                .with_context(|| format!("Reparse qualification with strict_lossless={strict_lossless}"))?;
4246            for (name, kind, bytes) in &expected {
4247                let restored = FileEntity::from_filesystem(
4248                    &destination.join("source").join(name),
4249                    None,
4250                )?;
4251                ensure!(
4252                    &restored.kind == kind,
4253                    "Reparse target changed: {name}"
4254                );
4255                ensure!(
4256                    restored
4257                        .metadata
4258                        .native
4259                        .as_ref()
4260                        .and_then(|native| native.values.get("reparse.data"))
4261                        == Some(bytes),
4262                    "Reparse buffer changed: {name}"
4263                );
4264            }
4265        }
4266        Ok(())
4267    }
4268
4269    #[cfg(unix)]
4270    #[crate::ctb_test]
4271    fn archive_links_and_attached_streams_capture_fidelity_contract()
4272    -> Result<()> {
4273        let temporary = tempfile::tempdir()?;
4274        let source = temporary.path().join("source");
4275        std::fs::create_dir(&source)?;
4276        std::fs::write(source.join("data"), b"linked payload")?;
4277        std::fs::hard_link(source.join("data"), source.join("hardlink"))?;
4278        std::os::unix::fs::symlink("data", source.join("symlink"))?;
4279        xattr::set(source.join("data"), "user.ctb.archive", b"stream payload")?;
4280        let archive_path = temporary.path().join("backup.cscarchive");
4281        let sources = vec![source.clone()];
4282        let plan = plan_sources(&sources, &archive_path)?;
4283        let outcome = create_archive(
4284            File::create(&archive_path)?,
4285            &sources,
4286            &archive_path,
4287            &plan,
4288            false,
4289            None,
4290            false,
4291        )?;
4292        let clean = outcome.completed
4293            && outcome.error_count == 0
4294            && outcome.warning_count == 0;
4295        if !clean {
4296            ensure!(
4297                !outcome.completed
4298                    && outcome.error_count == 1
4299                    && outcome.warning_count > 0
4300            );
4301        }
4302        let error_count = outcome.error_count;
4303        let warning_count = outcome.warning_count;
4304        drop(outcome.output);
4305        std::fs::remove_dir_all(&source)?;
4306        if !clean {
4307            let reader = JournalReader::recover(File::open(&archive_path)?)?;
4308            ensure!(!reader.is_completed());
4309            ensure!(
4310                reader.errors.len() == error_count
4311                    && reader.warnings.len() == warning_count
4312            );
4313            let link = source.join("symlink");
4314            ensure!(reader.warnings.iter().any(|warning| warning.message.contains(&link.display().to_string())
4315                && warning.message.contains("Restoring source access time changed source change time")
4316                && warning.message.contains("Unix cannot restore change time")));
4317            ensure!(reader.errors.iter().any(|error| {
4318                error.path == link
4319                    && error.stage == JournalErrorStage::MetadataRead
4320                    && error
4321                        .error_message
4322                        .contains("Unix cannot restore change time")
4323            }));
4324            ensure!(
4325                !reader.members.iter().any(|member| member
4326                    .entity
4327                    .identity
4328                    .relative_path
4329                    .as_deref()
4330                    == Some(Path::new("source/symlink")))
4331            );
4332            ensure!(reader.verify().is_err());
4333            ensure!(JournalReader::new(File::open(&archive_path)?).is_err());
4334            let listed = run_archive(&ArchiveArgs {
4335                command: ArchiveCommand::List {
4336                    archive: archive_path.clone(),
4337                },
4338            })?;
4339            ensure!(
4340                matches!(listed, ToolResult::Immediate { exit_code: 1, stderr, .. }
4341                if String::from_utf8_lossy(&stderr).contains("Unix cannot restore change time"))
4342            );
4343            ensure!(
4344                run_archive(&ArchiveArgs {
4345                    command: ArchiveCommand::Verify {
4346                        archive: archive_path.clone(),
4347                        recover: false
4348                    }
4349                })
4350                .is_err()
4351            );
4352            let destination = temporary.path().join("refused");
4353            ensure!(
4354                extract_archive(
4355                    &reader,
4356                    &destination,
4357                    &MaterializeOptions {
4358                        ..Default::default()
4359                    },
4360                    false
4361                )
4362                .is_err()
4363            );
4364            ensure!(!destination.exists());
4365        } else {
4366            let reader = JournalReader::new(File::open(&archive_path)?)?;
4367            ensure!(
4368                reader.is_completed()
4369                    && reader.errors.is_empty()
4370                    && reader.warnings.is_empty()
4371            );
4372            assert_links_and_attached_streams_restored(
4373                &reader,
4374                &temporary.path().join("restored"),
4375            )?;
4376        }
4377        Ok(())
4378    }
4379
4380    #[cfg(unix)]
4381    #[crate::ctb_test]
4382    fn archive_links_and_attached_streams_declared_source_free_roundtrip()
4383    -> Result<()> {
4384        let temporary = tempfile::tempdir()?;
4385        let archive_path = temporary.path().join("declared.cscarchive");
4386        let session = JournalSessionRecord {
4387            sources: Vec::new(),
4388            destination: archive_path.clone(),
4389            origin_platform: u32::from(current_platform()),
4390            environment: None,
4391        };
4392        let mut writer = JournalWriter::new(
4393            File::create(&archive_path)?,
4394            &session,
4395            crate::journal::stream::JournalMagic::ArchiveV2,
4396        )?;
4397        let mut data = FileEntity::from_vec(b"linked payload".to_vec());
4398        data.identity.relative_path = Some(PathBuf::from("source/data"));
4399        data.streams.push(ctb_io::file::AttachedStream::from_data(
4400            Some(ctb_io::file::StreamName::from_bytes(b"user.ctb.archive")),
4401            ctb_io::file::StreamKind::infer_from_name(b"user.ctb.archive"),
4402            b"stream payload".to_vec(),
4403        )?);
4404        let mut payload =
4405            ctb_io::file::MemoryPayloadSource::new(b"linked payload".to_vec())?;
4406        writer.write_entity(&data, Some(&mut payload))?;
4407        let mut hardlink = FileEntity::from_vec(Vec::new());
4408        hardlink.identity.relative_path =
4409            Some(PathBuf::from("source/hardlink"));
4410        hardlink.kind = FileEntityKind::Hardlink {
4411            target_relative_path: LinkPath::from_relative_path(Path::new(
4412                "source/data",
4413            ))?,
4414        };
4415        writer.write_entity(&hardlink, None)?;
4416        let mut symlink = FileEntity::from_vec(Vec::new());
4417        symlink.identity.relative_path = Some(PathBuf::from("source/symlink"));
4418        symlink.kind = FileEntityKind::Symlink {
4419            target: LinkPath::from_relative_path(Path::new("data"))?,
4420        };
4421        writer.write_entity(&symlink, None)?;
4422        drop(writer.finish()?);
4423        let reader = JournalReader::new(File::open(&archive_path)?)?;
4424        ensure!(
4425            reader.is_completed()
4426                && reader.errors.is_empty()
4427                && reader.warnings.is_empty()
4428        );
4429        ensure!(reader.members.len() == 3);
4430        assert_links_and_attached_streams_restored(
4431            &reader,
4432            &temporary.path().join("restored"),
4433        )
4434    }
4435
4436    #[cfg(unix)]
4437    fn assert_links_and_attached_streams_restored(
4438        reader: &JournalReader,
4439        destination: &Path,
4440    ) -> Result<()> {
4441        use std::os::unix::fs::MetadataExt;
4442        reader.verify()?;
4443        let options = MaterializeOptions {
4444            force_overwrite: true,
4445            ..Default::default()
4446        };
4447        extract_archive(reader, destination, &options, false)?;
4448        let data = destination.join("source/data");
4449        let hardlink = destination.join("source/hardlink");
4450        ensure!(std::fs::read(&data)? == b"linked payload");
4451        ensure!(std::fs::read(&hardlink)? == b"linked payload");
4452        ensure!(
4453            std::fs::metadata(&data)?.ino()
4454                == std::fs::metadata(&hardlink)?.ino()
4455        );
4456        ensure!(
4457            std::fs::read_link(destination.join("source/symlink"))?
4458                == Path::new("data")
4459        );
4460        ensure!(
4461            xattr::get(&data, "user.ctb.archive")?
4462                == Some(b"stream payload".to_vec())
4463        );
4464        ensure!(
4465            xattr::get(hardlink, "user.ctb.archive")?
4466                == Some(b"stream payload".to_vec())
4467        );
4468        Ok(())
4469    }
4470
4471    #[crate::ctb_test]
4472    fn archive_create_journal_flag_writes_journal_v5_and_omits_bodies()
4473    -> Result<()> {
4474        let temporary = tempfile::tempdir()?;
4475        let source = temporary.path().join("source");
4476        std::fs::create_dir(&source)?;
4477        let file1 = source.join("hello.txt");
4478        std::fs::write(&file1, b"hello world")?;
4479        let sub = source.join("sub");
4480        std::fs::create_dir(&sub)?;
4481        let file2 = sub.join("nested.bin");
4482        std::fs::write(&file2, vec![0x42; 256])?;
4483
4484        #[cfg(unix)]
4485        {
4486            xattr::set(&file1, "user.ctb.test", b"stream body")?;
4487        }
4488
4489        let journal_path = temporary.path().join("manifest.cscjournal");
4490        let result = run_archive(&ArchiveArgs {
4491            command: ArchiveCommand::Create {
4492                archive: journal_path.clone(),
4493                sources: vec![source.join("")],
4494                resume: false,
4495                continue_on_error: false,
4496                journal: true,
4497                options: ArchiveCreateOptions::default(),
4498            },
4499        })?;
4500        ensure!(matches!(result, ToolResult::Immediate { exit_code: 0, .. }));
4501
4502        // 1. Verify leading magic is JOURNAL_MAGIC (b"CTBCSCJ\x05")
4503        let mut f = File::open(&journal_path)?;
4504        let mut magic = [0_u8; 8];
4505        f.read_exact(&mut magic)?;
4506        ensure!(
4507            &magic == crate::journal::JOURNAL_MAGIC,
4508            "Expected JOURNAL_MAGIC magic header"
4509        );
4510
4511        // 2. Read with JournalReader: regular file bodies and stream bodies must be omitted
4512        let reader = JournalReader::new(File::open(&journal_path)?)?;
4513        ensure!(reader.is_completed(), "Journal must be completed");
4514        ensure!(
4515            !reader.members.is_empty(),
4516            "Journal must have committed members"
4517        );
4518        for member in &reader.members {
4519            ensure!(
4520                member.payload.is_none(),
4521                "Journal format must omit file payloads"
4522            );
4523            for stream in &member.entity.streams {
4524                ensure!(
4525                    stream.data.is_none() && stream.payload.is_none(),
4526                    "Journal format must omit stream bodies"
4527                );
4528            }
4529        }
4530
4531        // 3. Verify it can be used with csc-verify against the source directory
4532        let verify_args =
4533            default_verify_args(journal_path.clone(), Some(source.clone()));
4534        let verify_res = run_csc_verify(&verify_args)?;
4535        ensure!(matches!(
4536            verify_res,
4537            ToolResult::Immediate { exit_code: 0, .. }
4538        ));
4539
4540        Ok(())
4541    }
4542
4543    #[crate::ctb_test]
4544    fn csc_verify_supports_default_archive_format_source_free() -> Result<()> {
4545        let temporary = tempfile::tempdir()?;
4546        let source = temporary.path().join("source");
4547        std::fs::create_dir(&source)?;
4548        std::fs::write(source.join("alpha.txt"), b"alpha content")?;
4549        std::fs::write(source.join("beta.txt"), b"beta content")?;
4550
4551        let archive_path = temporary.path().join("test.cscarchive");
4552        let result = run_archive(&ArchiveArgs {
4553            command: ArchiveCommand::Create {
4554                archive: archive_path.clone(),
4555                sources: vec![source.join("")],
4556                resume: false,
4557                continue_on_error: false,
4558                journal: false,
4559                options: ArchiveCreateOptions::default(),
4560            },
4561        })?;
4562        ensure!(matches!(result, ToolResult::Immediate { exit_code: 0, .. }));
4563
4564        // Verify magic is ARCHIVE_MAGIC
4565        let mut f = File::open(&archive_path)?;
4566        let mut magic = [0_u8; 8];
4567        f.read_exact(&mut magic)?;
4568        ensure!(
4569            &magic == crate::journal::ARCHIVE_MAGIC,
4570            "Expected ARCHIVE_MAGIC header"
4571        );
4572
4573        // Extract to destination
4574        let dest = temporary.path().join("extracted");
4575        let extract_res = run_archive(&ArchiveArgs {
4576            command: ArchiveCommand::Extract {
4577                archive: archive_path.clone(),
4578                destination: dest.clone(),
4579                overwrite: false,
4580                trust_symlink_targets: false,
4581                best_effort_metadata: false,
4582                strict: false,
4583                check_atime: false,
4584                check_ctime: false,
4585                check_birthtime: false,
4586                copy_specials_as_specials: false,
4587                recover: false,
4588                apple_write: Default::default(),
4589            },
4590        })?;
4591        ensure!(matches!(
4592            extract_res,
4593            ToolResult::Immediate { exit_code: 0, .. }
4594        ));
4595
4596        // Remove source completely: verify must succeed without touching source filesystem!
4597        std::fs::remove_dir_all(&source)?;
4598        ensure!(!source.exists());
4599
4600        // Verify using positional target directory
4601        let verify_args =
4602            default_verify_args(archive_path.clone(), Some(dest.clone()));
4603        let verify_res = run_csc_verify(&verify_args)?;
4604        ensure!(matches!(
4605            verify_res,
4606            ToolResult::Immediate { exit_code: 0, .. }
4607        ));
4608
4609        // Verify using --dir flag
4610        let mut verify_flag_args =
4611            default_verify_args(archive_path.clone(), None);
4612        verify_flag_args.dir_flag = Some(dest.clone());
4613        let flag_res = run_csc_verify(&verify_flag_args)?;
4614        ensure!(matches!(
4615            flag_res,
4616            ToolResult::Immediate { exit_code: 0, .. }
4617        ));
4618
4619        // Error guidance when verifying archive without specifying directory
4620        let no_dest_args = default_verify_args(archive_path.clone(), None);
4621        let err = match run_csc_verify(&no_dest_args) {
4622            Err(e) => e,
4623            Ok(_) => {
4624                bail!("Expected csc-verify without target directory to fail")
4625            }
4626        };
4627        ensure!(
4628            err.to_string()
4629                .contains("pass target directory as argument or --dir <path>")
4630        );
4631
4632        // Introduce a content corruption in extracted directory
4633        std::fs::write(dest.join("alpha.txt"), b"corrupted content")?;
4634        let corrupt_res = run_csc_verify(&verify_args)?;
4635        ensure!(matches!(
4636            corrupt_res,
4637            ToolResult::Immediate { exit_code: 1, .. }
4638        ));
4639
4640        Ok(())
4641    }
4642
4643    #[crate::ctb_test]
4644    fn archive_legacy_v1_journal_cli_and_resume_refusal_without_truncation()
4645    -> Result<()> {
4646        use crate::journal::legacy::{
4647            JOURNAL_MAGIC_V1, TAG_BATCH_COMMIT, TAG_ENTITY, TAG_JOB_COMPLETED,
4648            TAG_SESSION_HEADER, write_bytes, write_entity_payload, write_u32,
4649            write_u64,
4650        };
4651        use ctb_formats_checksum::{Sha256Stream, xxhash};
4652        use ctb_formats_dcstring::SharedValueContext;
4653
4654        let temporary = tempfile::tempdir()?;
4655        let source = temporary.path().join("source");
4656        std::fs::create_dir(&source)?;
4657        let file_path = source.join("alpha.txt");
4658        std::fs::write(&file_path, b"alpha")?;
4659
4660        let context = SharedValueContext::default();
4661        let mut entity = FileEntity::from_filesystem(&file_path, None)?;
4662        let expected_rel = Path::new("source").join("alpha.txt");
4663        entity.identity.relative_path = Some(expected_rel.clone());
4664        let mut encoded = Vec::new();
4665        write_entity_payload(&mut encoded, &entity, &context)?;
4666
4667        let mut batch_hasher = Sha256Stream::new();
4668        batch_hasher.update(&encoded);
4669        let batch_hash = batch_hasher.finalize();
4670
4671        let mut v1_bytes = JOURNAL_MAGIC_V1.to_vec();
4672        v1_bytes.extend_from_slice(&[
4673            TAG_SESSION_HEADER,
4674            crate::journal::current_platform(),
4675        ]);
4676        write_u32(&mut v1_bytes, 1)?;
4677        write_bytes(&mut v1_bytes, source.as_os_str().as_encoded_bytes())?;
4678        write_bytes(&mut v1_bytes, b"dest")?;
4679        v1_bytes.push(TAG_ENTITY);
4680        write_u32(&mut v1_bytes, u32::try_from(encoded.len())?)?;
4681        v1_bytes.extend_from_slice(&xxhash::xxhash3_64(&encoded));
4682        v1_bytes.extend_from_slice(&encoded);
4683        v1_bytes.push(TAG_BATCH_COMMIT);
4684        write_u64(&mut v1_bytes, 1)?;
4685        v1_bytes.extend_from_slice(&batch_hash);
4686
4687        // Incomplete v1 journal with trailing uncommitted bytes to verify resume does not truncate
4688        let mut incomplete_with_tail = v1_bytes.clone();
4689        incomplete_with_tail.push(TAG_ENTITY);
4690        incomplete_with_tail.extend_from_slice(&[0x01, 0x02]);
4691        let incomplete_path = temporary.path().join("incomplete_v1.cscjournal");
4692        std::fs::write(&incomplete_path, &incomplete_with_tail)?;
4693
4694        for journal_flag in [false, true] {
4695            let err = run_archive(&ArchiveArgs {
4696                command: ArchiveCommand::Create {
4697                    archive: incomplete_path.clone(),
4698                    sources: Vec::new(),
4699                    resume: true,
4700                    continue_on_error: false,
4701                    journal: journal_flag,
4702                    options: ArchiveCreateOptions::default(),
4703                },
4704            })
4705            .err()
4706            .context("Resuming legacy v1 journal must fail")?;
4707            ensure!(
4708                format!("{err:#}")
4709                    .contains("Cannot resume a legacy CSC archive or journal"),
4710                "Unexpected error: {err:#}"
4711            );
4712            ensure!(
4713                std::fs::read(&incomplete_path)? == incomplete_with_tail,
4714                "Refused legacy v1 journal resume must not truncate or modify file"
4715            );
4716        }
4717
4718        // Completed v1 journal supports `archive list` and `archive verify --allow-journal-errors`
4719        v1_bytes.push(TAG_JOB_COMPLETED);
4720        let completed_path = temporary.path().join("completed_v1.cscjournal");
4721        std::fs::write(&completed_path, &v1_bytes)?;
4722
4723        let list_res = run_archive(&ArchiveArgs {
4724            command: ArchiveCommand::List {
4725                archive: completed_path.clone(),
4726            },
4727        })?;
4728        let ToolResult::Immediate {
4729            stdout,
4730            exit_code: 0,
4731            ..
4732        } = list_res
4733        else {
4734            bail!("Expected archive list on completed v1 journal to succeed");
4735        };
4736        ensure!(
4737            String::from_utf8_lossy(&stdout)
4738                .contains(&expected_rel.display().to_string())
4739        );
4740
4741        // Strict verify requires self-contained file payloads, so it errors on nonempty journal members
4742        ensure!(
4743            run_archive(&ArchiveArgs {
4744                command: ArchiveCommand::Verify {
4745                    archive: completed_path.clone(),
4746                    recover: false,
4747                },
4748            })
4749            .is_err()
4750        );
4751
4752        // Recover / --allow-journal-errors verify succeeds on v1 journal
4753        let verify_recover = run_archive(&ArchiveArgs {
4754            command: ArchiveCommand::Verify {
4755                archive: completed_path,
4756                recover: true,
4757            },
4758        })?;
4759        ensure!(matches!(
4760            verify_recover,
4761            ToolResult::Immediate { exit_code: 0, .. }
4762        ));
4763
4764        Ok(())
4765    }
4766
4767    #[crate::ctb_test]
4768    fn archive_extract_best_effort_adapts_overlong_filename_and_verifies()
4769    -> Result<()> {
4770        let temporary = tempfile::tempdir()?;
4771        let archive_path = temporary.path().join("overlong.cscarchive");
4772        let overlong_name = format!("{}.txt", "b".repeat(260));
4773        let payload_bytes = b"archived overlong file payload".to_vec();
4774        let sha256 = ctb_formats_checksum::sha256(&payload_bytes);
4775
4776        {
4777            let file = File::create(&archive_path)?;
4778            let session = crate::journal::JournalSessionRecord {
4779                sources: vec![PathBuf::from("src")],
4780                destination: PathBuf::new(),
4781                origin_platform: u32::from(crate::journal::current_platform()),
4782                environment: None,
4783            };
4784            let mut writer = crate::journal::JournalWriter::new(
4785                file,
4786                &session,
4787                crate::journal::JournalMagic::ArchiveV2,
4788            )?;
4789            let entity = FileEntity {
4790                identity: ctb_io::file::FileIdentity {
4791                    origin: ctb_io::file::FileOrigin::Synthetic,
4792                    relative_path: Some(PathBuf::from(&overlong_name)),
4793                    enclosing_path: None,
4794                    nlink: 1,
4795                    hardlink_group: None,
4796                },
4797                kind: FileEntityKind::Regular {
4798                    size: u64::try_from(payload_bytes.len())?,
4799                    sha256,
4800                    is_sparse: false,
4801                    extents: vec![ctb_io::file::payload::Extent::Data {
4802                        offset: 0,
4803                        length: u64::try_from(payload_bytes.len())?,
4804                    }],
4805                },
4806                metadata: ctb_io::file::FileMetadata::default(),
4807                streams: Vec::new(),
4808            };
4809            let mut payload =
4810                ctb_io::file::MemoryPayloadSource::new(payload_bytes.clone())?;
4811            writer.write_entity_checked(
4812                &entity,
4813                Some(&mut payload),
4814                ctb_io::file::encoding::BodyPolicy::Include,
4815                || Ok(()),
4816            )?;
4817            writer.finish()?;
4818        }
4819
4820        // Strict extraction must fail on >255-byte component.
4821        let strict_dest = temporary.path().join("strict_dest");
4822        ensure!(
4823            run_archive(&ArchiveArgs {
4824                command: ArchiveCommand::Extract {
4825                    archive: archive_path.clone(),
4826                    destination: strict_dest,
4827                    overwrite: false,
4828                    trust_symlink_targets: false,
4829                    best_effort_metadata: false,
4830                    strict: true,
4831                    check_atime: false,
4832                    check_ctime: false,
4833                    check_birthtime: false,
4834                    copy_specials_as_specials: false,
4835                    recover: false,
4836                    apple_write: Default::default(),
4837                },
4838            })
4839            .is_err(),
4840            "Strict extraction must reject overlong filename"
4841        );
4842
4843        // Best-effort extraction must adapt the filename, materialize the file, and pass verification.
4844        let be_dest = temporary.path().join("be_dest");
4845        run_archive(&ArchiveArgs {
4846            command: ArchiveCommand::Extract {
4847                archive: archive_path.clone(),
4848                destination: be_dest.clone(),
4849                overwrite: false,
4850                trust_symlink_targets: false,
4851                best_effort_metadata: true,
4852                strict: false,
4853                check_atime: false,
4854                check_ctime: false,
4855                check_birthtime: false,
4856                copy_specials_as_specials: false,
4857                recover: false,
4858                apple_write: Default::default(),
4859            },
4860        })?;
4861
4862        let (expected_adapted, _) =
4863            ctb_io::file::adapt_relative_path_for_materialization(
4864                Path::new(&overlong_name),
4865                cfg!(windows),
4866            );
4867        ensure!(
4868            std::fs::read(be_dest.join(&expected_adapted))? == payload_bytes,
4869            "Adapted file must exist with intact payload at {}",
4870            expected_adapted.display()
4871        );
4872
4873        // `verify_directory_against_manifest` in best-effort mode must locate the adapted file.
4874        let mut verify_args = default_verify_args(archive_path, Some(be_dest));
4875        verify_args.criteria.best_effort = true;
4876        verify_args.criteria.ignore_owner = true;
4877        verify_args.criteria.ignore_perms = true;
4878        verify_args.criteria.ignore_mtime = true;
4879        let report =
4880            crate::verifier::verify_directory_against_manifest(&verify_args)?;
4881        ensure!(
4882            report.is_clean(),
4883            "Best-effort verification against archive with adapted filename must pass: {report:?}"
4884        );
4885
4886        Ok(())
4887    }
4888
4889    #[crate::ctb_test]
4890    fn archive_csc_option_exposure_apple_streams_and_source_change()
4891    -> Result<()> {
4892        let create_parsed = ArchiveArgs::try_parse_from([
4893            "archive",
4894            "create",
4895            "out.cscarchive",
4896            "src/",
4897            "--full-provenance",
4898            "--on-source-change",
4899            "best-effort",
4900            "-x",
4901            "--read-apple-double-alongside",
4902            "--read-apple-single-with-extension",
4903            "as",
4904            "--read-windows-ads",
4905        ])?;
4906        let ArchiveCommand::Create { options, .. } = create_parsed.command
4907        else {
4908            bail!("Expected ArchiveCommand::Create");
4909        };
4910        ensure!(options.full_provenance);
4911        ensure!(
4912            options.on_source_change
4913                == crate::args::SourceChangePolicy::BestEffort
4914        );
4915        ensure!(options.one_file_system);
4916        let resolved_read = options.apple_read.resolve();
4917        ensure!(resolved_read.read_apple_double_alongside);
4918        ensure!(resolved_read.read_apple_single_as);
4919        ensure!(resolved_read.read_windows_ads_alongside);
4920
4921        let extract_parsed = ArchiveArgs::try_parse_from([
4922            "archive",
4923            "extract",
4924            "out.cscarchive",
4925            "dest/",
4926            "--force-write-apple-double",
4927            "alongside",
4928        ])?;
4929        let ArchiveCommand::Extract { apple_write, .. } =
4930            extract_parsed.command
4931        else {
4932            bail!("Expected ArchiveCommand::Extract");
4933        };
4934        ensure!(
4935            apple_write.force_write_apple_double
4936                == Some(
4937                    ctb_io::file::apple_double::AppleDoubleStyle::Alongside
4938                )
4939        );
4940
4941        // End-to-end AppleDouble + AppleSingle (.as) capture and AppleDouble alongside extraction
4942        let temporary = tempfile::tempdir()?;
4943        let source = temporary.path().join("source");
4944        std::fs::create_dir(&source)?;
4945        std::fs::write(source.join("doc.txt"), b"primary doc")?;
4946        let double_archive = ctb_io::file::AppleArchive {
4947            format: ctb_io::file::AppleFormat::AppleDouble,
4948            version: ctb_io::file::VERSION_2_0_BE,
4949            real_name: None,
4950            comment: Some("doc comment".to_owned()),
4951            timestamps: None,
4952            backup_timestamp_sec: None,
4953            finder_info: None,
4954            extended_attributes: Vec::new(),
4955            data_fork: None,
4956            resource_fork: Some(b"doc rsrc".to_vec()),
4957            data_fork_size: None,
4958            resource_fork_size: Some(8),
4959            unrecognized_entries: Vec::new(),
4960            entries: Vec::new(),
4961        };
4962        std::fs::write(
4963            source.join("._doc.txt"),
4964            ctb_io::file::write_apple_single_double(&double_archive)?,
4965        )?;
4966
4967        let mut single_archive = double_archive.clone();
4968        single_archive.format = ctb_io::file::AppleFormat::AppleSingle;
4969        single_archive.comment = Some("single comment".to_owned());
4970        single_archive.data_fork = Some(b"single data fork".to_vec());
4971        std::fs::write(
4972            source.join("note.txt.as"),
4973            ctb_io::file::write_apple_single_double(&single_archive)?,
4974        )?;
4975
4976        let archive_path = temporary.path().join("apple.cscarchive");
4977        let create_res = run_archive(&ArchiveArgs::try_parse_from([
4978            "archive",
4979            "create",
4980            archive_path.to_str().context("Non-UTF8 path")?,
4981            source.to_str().context("Non-UTF8 path")?,
4982            "--read-apple-double-alongside",
4983            "--read-apple-single-with-extension",
4984            "as",
4985        ])?)?;
4986        ensure!(matches!(
4987            create_res,
4988            ToolResult::Immediate { exit_code: 0, .. }
4989        ));
4990
4991        let reader = JournalReader::new(File::open(&archive_path)?)?;
4992        reader.verify_self_contained()?;
4993        // `._doc.txt` companion is absorbed into `source/doc.txt` and `note.txt.as` is stripped to `source/note.txt`
4994        let rel_paths: HashSet<_> = reader
4995            .members
4996            .iter()
4997            .filter_map(|m| m.entity.identity.relative_path.clone())
4998            .collect();
4999        ensure!(rel_paths.contains(Path::new("source/doc.txt")));
5000        ensure!(rel_paths.contains(Path::new("source/note.txt")));
5001        ensure!(!rel_paths.contains(Path::new("source/._doc.txt")));
5002        ensure!(!rel_paths.contains(Path::new("source/note.txt.as")));
5003
5004        let extracted = temporary.path().join("extracted");
5005        let extract_res = run_archive(&ArchiveArgs::try_parse_from([
5006            "archive",
5007            "extract",
5008            archive_path.to_str().context("Non-UTF8 path")?,
5009            extracted.to_str().context("Non-UTF8 path")?,
5010            "--force-write-apple-double",
5011            "alongside",
5012        ])?)?;
5013        ensure!(matches!(
5014            extract_res,
5015            ToolResult::Immediate { exit_code: 0, .. }
5016        ));
5017        ensure!(
5018            std::fs::read(extracted.join("source/doc.txt"))? == b"primary doc"
5019        );
5020        ensure!(extracted.join("source/._doc.txt").is_file());
5021        ensure!(
5022            std::fs::read(extracted.join("source/note.txt"))?
5023                == b"single data fork"
5024        );
5025        ensure!(extracted.join("source/._note.txt").is_file());
5026
5027        // Verify `--on-source-change best-effort` records `SourceModifiedDuringCopy` warning while committing member
5028        #[cfg(unix)]
5029        {
5030            use std::os::unix::fs::PermissionsExt;
5031            struct ChmodOnCapture {
5032                target: PathBuf,
5033                options: ArchiveCreateOptions,
5034            }
5035            impl CaptureSource for ChmodOnCapture {
5036                fn capture(&mut self, path: &Path) -> Result<CapturedSource> {
5037                    let best_effort = self.options.on_source_change
5038                        == crate::args::SourceChangePolicy::BestEffort;
5039                    let mut source = CapturedSource::capture(
5040                        path,
5041                        None,
5042                        &self.options.apple_read.resolve(),
5043                        best_effort,
5044                    )?;
5045                    if path == self.target {
5046                        let mode =
5047                            std::fs::metadata(path)?.permissions().mode()
5048                                ^ 0o100;
5049                        std::fs::set_permissions(
5050                            path,
5051                            std::fs::Permissions::from_mode(mode),
5052                        )?;
5053                    }
5054                    source.hash(path)?;
5055                    Ok(source)
5056                }
5057            }
5058
5059            let sc_dir = temporary.path().join("sc_source");
5060            std::fs::create_dir(&sc_dir)?;
5061            let sc_sources = vec![sc_dir.clone()];
5062            let sc_archive = temporary.path().join("sc_best_effort.cscarchive");
5063            let sc_options = ArchiveCreateOptions {
5064                on_source_change: crate::args::SourceChangePolicy::BestEffort,
5065                ..Default::default()
5066            };
5067            let sc_plan = plan_sources_with_options(
5068                &sc_sources,
5069                &sc_archive,
5070                &sc_options,
5071            )?;
5072            let outcome = capture_archive(
5073                FileArchiveOutput::new(File::create(&sc_archive)?),
5074                CaptureRequest {
5075                    sources: &sc_sources,
5076                    archive: &sc_archive,
5077                    plan: &sc_plan,
5078                    continue_on_error: false,
5079                    recovered: None,
5080                    journal: false,
5081                    options: &sc_options,
5082                },
5083                &mut ChmodOnCapture {
5084                    target: sc_dir,
5085                    options: sc_options.clone(),
5086                },
5087            )?;
5088            ensure!(
5089                outcome.completed
5090                    && outcome.error_count == 0
5091                    && outcome.warning_count == 1
5092            );
5093            drop(outcome.output);
5094            let sc_reader = JournalReader::recover(File::open(&sc_archive)?)?;
5095            ensure!(sc_reader.is_completed() && sc_reader.members.len() == 1);
5096            ensure!(
5097                sc_reader
5098                    .warnings
5099                    .iter()
5100                    .any(|w| w.code == "SourceModifiedDuringCopy")
5101            );
5102        }
5103
5104        Ok(())
5105    }
5106}