ostrya 0.2.4

Pure-Rust async reimplementation of the ostree repository library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! Object-integrity and completeness checking.
//!
//! [`Repo::fsck`] enumerates every commit in the store and walks the objects
//! reachable from each, verifying two things (the checks the `ostree fsck` tool
//! performs, recovered by black-box observation):
//!
//! - Integrity: each object's recomputed checksum equals its name. A metadata
//!   object is hashed over its serialized bytes; a content object is hashed over
//!   its framed uncompressed header and uncompressed payload, so a corrupt
//!   `.filez` or a tampered `.file` is caught in every mode.
//! - Completeness: every referenced object is present. A referenced object that
//!   is absent is reported, and the commit that referenced it is marked partial
//!   by writing its `state/<commit>.commitpartial` marker, matching the tool.
//!
//! The result is a [`FsckReport`]; a corrupt repository does not fail the call,
//! it populates [`errors`](FsckReport::errors). A caller (or the CLI) turns a
//! non-empty report into a failure.

use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::io::Write;
use std::os::fd::BorrowedFd;
use std::pin::Pin;

use futures_lite::AsyncReadExt;
use ostrya_core::{Checksum, Commit, ContentHasher, DirTree, ObjectName, ObjectType, RepoMode};
use rustix::fs::{Mode, OFlags};
use rustix::io::Errno;

use crate::error::{Error, Result};
use crate::perm;
use crate::repo::Repo;

/// The single byte the tool writes into a `.commitpartial` marker when fsck
/// finds a commit incomplete (recovered by observation).
const PARTIAL_STATE_BYTE: u8 = 0x66;

/// The chunk size for streaming a content object's payload through the hasher.
const READ_CHUNK: usize = 128 * 1024;

/// Options controlling [`Repo::fsck`].
#[derive(Debug, Clone)]
pub struct FsckOptions {
    /// Write a `state/<commit>.commitpartial` marker for any commit found to be
    /// missing a referenced object, matching the tool. Enabled by default.
    pub mark_partial: bool,
}

impl Default for FsckOptions {
    fn default() -> Self {
        FsckOptions { mark_partial: true }
    }
}

impl FsckOptions {
    /// The default options (partial-marking enabled).
    pub fn new() -> FsckOptions {
        FsckOptions::default()
    }
}

/// Why one object failed fsck.
#[derive(Debug, Clone)]
pub enum FsckErrorKind {
    /// The object is referenced but absent from the store.
    Missing,
    /// The object is present but its recomputed checksum differs from its name.
    ChecksumMismatch {
        /// The checksum the object's bytes actually hash to.
        actual: Checksum,
    },
    /// The object is present but could not be parsed or read.
    Corrupt(String),
}

/// One fsck finding: the object at fault and why.
#[derive(Debug, Clone)]
pub struct FsckError {
    /// The object the finding concerns.
    pub object: ObjectName,
    /// The nature of the fault.
    pub kind: FsckErrorKind,
}

impl std::fmt::Display for FsckError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.kind {
            FsckErrorKind::Missing => write!(f, "missing object {}", self.object),
            FsckErrorKind::ChecksumMismatch { actual } => write!(
                f,
                "corrupted object {}: checksum expected {}, computed {}",
                self.object, self.object.checksum, actual
            ),
            FsckErrorKind::Corrupt(detail) => {
                write!(f, "corrupted object {}: {detail}", self.object)
            }
        }
    }
}

/// The outcome of a [`Repo::fsck`] run.
#[derive(Debug, Clone)]
pub struct FsckReport {
    /// The number of commit objects walked.
    pub commits_checked: usize,
    /// The number of distinct objects examined.
    pub objects_checked: usize,
    /// The findings, one per faulty object.
    pub errors: Vec<FsckError>,
}

impl FsckReport {
    /// Whether the repository passed with no findings.
    pub fn is_ok(&self) -> bool {
        self.errors.is_empty()
    }
}

/// The mutable state threaded through one fsck run.
#[derive(Default)]
struct Ctx {
    /// Every referenced object, present or not (the examined-object count).
    seen: HashSet<ObjectName>,
    /// Metadata objects whose checksum was recomputed and matched, so they are
    /// not re-hashed when reached again from another commit.
    checked_ok: HashSet<ObjectName>,
    /// Memoized per content object: whether it is missing. A content object
    /// reached again from another commit returns its cached outcome instead of
    /// being re-read and re-hashed, whether it passed, failed, or was absent.
    content_examined: HashMap<Checksum, bool>,
    /// Memoized per dirtree: whether its subtree (the dirtree, its dirmetas,
    /// files, and nested subtrees) references any missing object. A subtree
    /// shared between commits is walked once but still contributes its missing
    /// state to every commit that reaches it.
    dirtree_missing: HashMap<Checksum, bool>,
    /// Objects a finding has already been recorded for, to report each once.
    reported: HashSet<ObjectName>,
    /// The findings.
    errors: Vec<FsckError>,
}

/// The result of verifying one metadata object during the walk.
enum VerifyMeta {
    /// The object is present; its serialized bytes are returned for parsing. Its
    /// checksum has been verified (a mismatch is already recorded).
    Present(Vec<u8>),
    /// The object is referenced but absent, which makes the referencing commit
    /// partial.
    Missing,
    /// The object is present but could not be read; recorded as corruption,
    /// which does not make the commit partial.
    Unreadable,
}

impl Ctx {
    /// Record one finding, at most once per object.
    fn record(&mut self, object: ObjectName, kind: FsckErrorKind) {
        if self.reported.insert(object) {
            self.errors.push(FsckError { object, kind });
        }
    }
}

impl Repo {
    /// Verify object integrity and completeness across every commit in the
    /// store.
    pub async fn fsck(&self, opts: &FsckOptions) -> Result<FsckReport> {
        let all = self.list_objects().await?;
        let mut ctx = Ctx::default();

        // Validate refs: a ref pointing at an absent commit is a finding.
        for target in self.list_all_ref_targets().await? {
            let name = ObjectName::new(target, ObjectType::Commit);
            if !all.contains(&name) {
                ctx.seen.insert(name);
                ctx.record(name, FsckErrorKind::Missing);
            }
        }

        // The roots are every commit object present, walked in a deterministic
        // order.
        let mut commit_roots: Vec<Checksum> = all
            .iter()
            .filter(|o| o.ty == ObjectType::Commit)
            .map(|o| o.checksum)
            .collect();
        commit_roots.sort();

        let commits_checked = commit_roots.len();
        for commit in commit_roots {
            self.fsck_walk_commit(commit, opts, &mut ctx).await?;
        }

        Ok(FsckReport {
            commits_checked,
            objects_checked: ctx.seen.len(),
            errors: ctx.errors,
        })
    }

    /// Walk one commit's reachable objects, verifying each. A commit that turns
    /// out to be missing a referenced object is marked partial when the option
    /// is set.
    async fn fsck_walk_commit(
        &self,
        commit: Checksum,
        opts: &FsckOptions,
        ctx: &mut Ctx,
    ) -> Result<()> {
        let mut had_missing = false;
        let commit_name = ObjectName::new(commit, ObjectType::Commit);

        match self.fsck_verify_metadata(commit_name, ctx).await? {
            VerifyMeta::Present(bytes) => match Commit::parse(&bytes) {
                Ok(parsed) => {
                    let root_dirmeta = ObjectName::new(parsed.root_dirmeta, ObjectType::DirMeta);
                    if matches!(
                        self.fsck_verify_metadata(root_dirmeta, ctx).await?,
                        VerifyMeta::Missing
                    ) {
                        had_missing = true;
                    }
                    if fsck_walk_subtree(self, parsed.root_dirtree, ctx).await? {
                        had_missing = true;
                    }
                }
                Err(e) => ctx.record(commit_name, FsckErrorKind::Corrupt(e.to_string())),
            },
            VerifyMeta::Missing => had_missing = true,
            VerifyMeta::Unreadable => {}
        }

        if had_missing && opts.mark_partial {
            self.mark_commit_partial(&commit).await?;
        }
        Ok(())
    }

    /// Verify one metadata object's checksum, reporting a mismatch, a missing
    /// object, or an unreadable one.
    async fn fsck_verify_metadata(&self, name: ObjectName, ctx: &mut Ctx) -> Result<VerifyMeta> {
        ctx.seen.insert(name);
        match self.load_object_bytes(name.ty, &name.checksum).await {
            Ok(bytes) => {
                if !ctx.checked_ok.contains(&name) {
                    let actual = Checksum::sha256(&bytes);
                    if actual == name.checksum {
                        ctx.checked_ok.insert(name);
                    } else {
                        ctx.record(name, FsckErrorKind::ChecksumMismatch { actual });
                    }
                }
                Ok(VerifyMeta::Present(bytes))
            }
            Err(Error::ObjectNotFound { .. }) => {
                ctx.record(name, FsckErrorKind::Missing);
                Ok(VerifyMeta::Missing)
            }
            // A read failure is reported as corruption rather than aborting the
            // whole check.
            Err(Error::Io(e)) => {
                ctx.record(name, FsckErrorKind::Corrupt(e.to_string()));
                Ok(VerifyMeta::Unreadable)
            }
            Err(e) => Err(e),
        }
    }

    /// Verify one content object, returning whether it is missing (which makes
    /// the referencing commit partial). The outcome is memoized, so a content
    /// object reached again from another commit is not re-read and re-hashed.
    async fn fsck_verify_content(&self, checksum: Checksum, ctx: &mut Ctx) -> Result<bool> {
        let name = ObjectName::new(checksum, ObjectType::File);
        ctx.seen.insert(name);
        if let Some(&missing) = ctx.content_examined.get(&checksum) {
            return Ok(missing);
        }
        let missing = self.fsck_hash_content(name, ctx).await?;
        ctx.content_examined.insert(checksum, missing);
        Ok(missing)
    }

    /// Load a content object, hash its framed header and streamed payload, and
    /// compare with its name, recording any fault. Returns whether the object is
    /// missing.
    async fn fsck_hash_content(&self, name: ObjectName, ctx: &mut Ctx) -> Result<bool> {
        let checksum = name.checksum;
        let file = match self.load_file(&checksum).await {
            Ok(file) => file,
            Err(Error::ObjectNotFound { .. }) => {
                ctx.record(name, FsckErrorKind::Missing);
                return Ok(true);
            }
            Err(Error::Io(e)) => {
                ctx.record(name, FsckErrorKind::Corrupt(e.to_string()));
                return Ok(false);
            }
            Err(Error::InvalidFormat(m)) => {
                ctx.record(name, FsckErrorKind::Corrupt(m));
                return Ok(false);
            }
            Err(Error::Core(e)) => {
                ctx.record(name, FsckErrorKind::Corrupt(e.to_string()));
                return Ok(false);
            }
            Err(e) => return Err(e),
        };

        let mut hasher = ContentHasher::new(&file.header())?;

        let mut reader = file.reader().await?;
        let mut buf = vec![0u8; READ_CHUNK];
        loop {
            match reader.read(&mut buf).await {
                Ok(0) => break,
                Ok(n) => hasher.update(&buf[..n]),
                Err(e) => {
                    ctx.record(
                        name,
                        FsckErrorKind::Corrupt(format!("payload read failed: {e}")),
                    );
                    return Ok(false);
                }
            }
        }

        let actual = hasher.finish();
        if actual != checksum {
            ctx.record(name, FsckErrorKind::ChecksumMismatch { actual });
        }
        Ok(false)
    }

    /// Write a commit's `state/<commit>.commitpartial` marker.
    async fn mark_commit_partial(&self, commit: &Checksum) -> Result<()> {
        let path = crate::pull::partial_path(commit);
        let repo = self.clone();
        ostrya_rt::unblock(move || write_partial_marker(repo.repo_fd(), &path, repo.mode())).await
    }
}

/// The boxed future type for the recursive subtree walk. Async recursion needs
/// indirection, so each level returns a boxed future.
type SubtreeFuture<'a> = Pin<Box<dyn Future<Output = Result<bool>> + Send + 'a>>;

/// Verify a dirtree and everything beneath it, returning whether the subtree
/// references any missing object. Each dirtree's result is memoized so a subtree
/// shared between commits is verified once, yet its missing state still reaches
/// every commit that references it. A missing dirtree makes its subtree missing;
/// a present-but-corrupt one is recorded and its subtree treated as complete,
/// since its children cannot be enumerated.
fn fsck_walk_subtree<'a>(repo: &'a Repo, dt: Checksum, ctx: &'a mut Ctx) -> SubtreeFuture<'a> {
    Box::pin(async move {
        if let Some(&missing) = ctx.dirtree_missing.get(&dt) {
            return Ok(missing);
        }
        let name = ObjectName::new(dt, ObjectType::DirTree);
        let missing = match repo.fsck_verify_metadata(name, ctx).await? {
            VerifyMeta::Missing => true,
            VerifyMeta::Unreadable => false,
            VerifyMeta::Present(bytes) => match DirTree::parse(&bytes) {
                Ok(dirtree) => {
                    let mut missing = false;
                    for (_, file) in dirtree.files {
                        missing |= repo.fsck_verify_content(file, ctx).await?;
                    }
                    for (_, subtree, submeta) in dirtree.dirs {
                        let sub_meta = ObjectName::new(submeta, ObjectType::DirMeta);
                        if matches!(
                            repo.fsck_verify_metadata(sub_meta, ctx).await?,
                            VerifyMeta::Missing
                        ) {
                            missing = true;
                        }
                        missing |= fsck_walk_subtree(repo, subtree, ctx).await?;
                    }
                    missing
                }
                Err(e) => {
                    ctx.record(name, FsckErrorKind::Corrupt(e.to_string()));
                    false
                }
            },
        };
        ctx.dirtree_missing.insert(dt, missing);
        Ok(missing)
    })
}

/// Create or truncate a `.commitpartial` marker holding the single state byte
/// the tool writes.
///
/// A marker this call creates in a `bare-user-shared` repository is forced to
/// [`perm::SHARED_FILE_MODE`]. The create attempt therefore carries `O_EXCL`,
/// which separates the arm that made the file from the arm that found one: a
/// marker another member of the repository group owns keeps the mode it has and
/// is truncated in place. The second open carries `O_CREAT` as well, because a
/// concurrent pull or prune removes the marker of a commit it completes or
/// deletes, and the name is free again by the time this call reaches it.
fn write_partial_marker(repo_fd: BorrowedFd<'_>, path: &str, repo_mode: RepoMode) -> Result<()> {
    let mode = Mode::from_raw_mode(crate::pull::PARTIAL_MARKER_MODE);
    let fd = match rustix::fs::openat(
        repo_fd,
        path,
        OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC,
        mode,
    ) {
        Ok(fd) => {
            perm::force_created_mode(&fd, repo_mode, perm::SHARED_FILE_MODE)?;
            fd
        }
        Err(Errno::EXIST) => rustix::fs::openat(
            repo_fd,
            path,
            OFlags::WRONLY | OFlags::CREATE | OFlags::TRUNC | OFlags::CLOEXEC,
            mode,
        )?,
        Err(e) => return Err(e.into()),
    };
    std::fs::File::from(fd)
        .write_all(&[PARTIAL_STATE_BYTE])
        .map_err(Error::Io)
}