Skip to main content

ostrya/
overlay.rs

1//! The overlay merge of a transaction.
2//!
3//! The doc of `Transaction::merge_overlay_dfd_to_mtree` holds the behavior
4//! that a caller sees.
5//!
6//! The merge is a separate walk. A file system ingest and a tree merge after
7//! it cannot do this work, because a `MutableTree` has no tombstone form. A
8//! whiteout must act on the base tree when the walk gets to it. The walk uses
9//! the helpers of `ingest.rs` (canonical permissions, the filter and callback
10//! hooks, the dirmeta assembly) and the object writers of `write.rs`.
11
12use std::future::Future;
13use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
14use std::path::Path;
15use std::pin::Pin;
16
17use ostrya_core::{RepoMode, Xattrs};
18use ostrya_rt::FileReader;
19use rustix::fs::{AtFlags, Dir, FileType, Mode, OFlags};
20
21use crate::error::{Error, Result};
22use crate::ingest::{adjust_meta, finalize_meta, join_path, to_dirmeta};
23use crate::modifier::{CommitModifier, CommitModifierFlags, FilterResult, Owner};
24use crate::mtree::MutableTree;
25use crate::transaction::Transaction;
26use crate::write::FileMeta;
27
28/// The two xattr namespace prefixes of the overlayfs control attributes.
29///
30/// A privileged overlay uses `trusted.*`, and a rootless `userxattr` overlay
31/// uses `user.*`.
32const OVERLAY_PREFIXES: [&[u8]; 2] = [b"trusted.overlay.", b"user.overlay."];
33
34/// Methods that merge an overlayfs upper directory into a mutable tree.
35impl Transaction {
36    /// Merges the overlayfs upper directory at `dfd` into `mtree`.
37    ///
38    /// `dfd` is the root of the upper directory (the `upperdir` of the mount).
39    /// `mtree` holds the lower layer that the overlay was mounted over. The
40    /// merge applies the upper directory to `mtree` as a changeset. The overlay
41    /// must be unmounted, and the call does not check this.
42    ///
43    /// Each upper entry other than a whiteout becomes an object, and the entry
44    /// replaces or extends the base tree. The merge is an ostrya extension
45    /// with no counterpart in the `ostree` command. It changes no on-disk
46    /// format, because a deletion acts on the in-memory tree during the walk.
47    ///
48    /// # Overlay rules
49    ///
50    /// - A whiteout (a character device with device number 0:0) removes its
51    ///   path from the base tree. If the base tree has no entry at the path,
52    ///   the whiteout has no effect.
53    /// - An opaque directory (`trusted.overlay.opaque` or
54    ///   `user.overlay.opaque` set to `y`) clears the base subtree at its name.
55    ///   The merge then reads the upper entries. An opaque root clears the
56    ///   whole base tree.
57    /// - The merge reads both xattr namespaces. A rootless `userxattr` overlay
58    ///   writes `user.*`, and an unprivileged reader cannot see `trusted.*`.
59    /// - A merged (non-opaque) directory takes its dirmeta from the upper
60    ///   inode, because overlayfs copies a directory up with its metadata. The
61    ///   root of the upper directory is a merged directory too.
62    /// - The merge removes each xattr whose name starts with `trusted.overlay.`
63    ///   or `user.overlay.` from each file, symlink, and directory that it
64    ///   records, dirmeta included. It keeps every other xattr, also an xattr
65    ///   whose name contains `overlay` at another position.
66    /// - An entry with an `overlay.metacopy` or `overlay.redirect` xattr is an
67    ///   error, because such an entry is not self-contained. The overlay must
68    ///   be mounted with these features off (`metacopy=off` and
69    ///   `redirect_dir=off`).
70    /// - An upper entry replaces a base entry of a different type. An upper
71    ///   file or symlink over a base directory removes the directory. An upper
72    ///   directory over a base file or symlink removes the leaf and creates a
73    ///   new directory.
74    ///
75    /// A usrmerge migration changes a directory to a symlink. Overlayfs
76    /// records this change as a plain leaf with no whiteout and no opaque
77    /// marker. A non-directory upper entry hides a lower entry of any type.
78    ///
79    /// # Modifier
80    ///
81    /// A [`CommitModifier`] applies to each recorded entry the steps that
82    /// [`write_dfd_to_mtree`](Transaction::write_dfd_to_mtree) lists under
83    /// its `Modifier` heading. The root of the upper directory goes through
84    /// each step except the filter. The merge does not use a
85    /// [`DevInoCache`](crate::DevInoCache) or
86    /// [`CONSUME`](CommitModifierFlags::CONSUME).
87    ///
88    /// Whiteouts and opaque markers are merge mechanics, and the modifier
89    /// does not see them. The other rules for a modifier are these:
90    ///
91    /// - If the filter returns [`FilterResult::Skip`] for an upper entry, the
92    ///   base entry stays as it is. For a directory, the merge skips the whole
93    ///   upper subtree.
94    /// - The merge removes the overlay xattrs before the filter and the
95    ///   callbacks see the xattr set of an entry. The xattr callback can add a
96    ///   removed name again, and the merge does not remove it a second time.
97    /// - Under [`SKIP_XATTRS`](CommitModifierFlags::SKIP_XATTRS), the merge
98    ///   still reads the xattrs of each entry for the overlay rules. The
99    ///   recorded entry has no xattrs.
100    /// - The merge checks for `overlay.metacopy` and `overlay.redirect` before
101    ///   the filter, so an entry that the filter skips can cause the error.
102    ///
103    /// # Errors
104    ///
105    /// - [`Error::Unsupported`] if the repository mode is `bare-split-xattrs`,
106    ///   or if an upper entry is not a directory, a regular file, a symlink,
107    ///   or a whiteout.
108    /// - [`Error::Unsupported`] if `[ex-integrity] fsverity` is `yes` and the
109    ///   fs-verity seal of an object fails.
110    /// - [`Error::UnsupportedOverlayFeature`] if an upper entry has an
111    ///   `overlay.metacopy` or `overlay.redirect` xattr in one of the two
112    ///   namespaces.
113    /// - [`Error::InvalidFormat`] if an entry name or a symlink target is not
114    ///   valid UTF-8.
115    /// - [`Error::InvalidFormat`] if the label callback returns no label and
116    ///   [`ERROR_ON_UNLABELED`](CommitModifierFlags::ERROR_ON_UNLABELED) is
117    ///   set.
118    /// - [`Error::InvalidFormat`] if `[ex-integrity] fsverity` or
119    ///   `[ex-integrity] composefs` in the repository config is malformed.
120    /// - [`Error::InvalidFormat`] if the repository is in `bare` mode and an
121    ///   xattr name of a symlink is not valid UTF-8.
122    /// - [`Error::InsufficientFreeSpace`] if an object needs more space than
123    ///   the free-space budget of the transaction holds.
124    /// - [`Error::ObjectNotFound`] if a lazy subdirectory of `mtree` names a
125    ///   dirtree that the repository does not hold.
126    /// - [`Error::Core`] if the dirtree of a lazy subdirectory does not parse,
127    ///   or if the xattr set with a label is not valid.
128    /// - [`Error::Core`] if the mode callback returns a file type that the
129    ///   object writer refuses for the entry.
130    /// - [`Error::Core`] if a `[core]` or `[archive]` value in the repository
131    ///   config is malformed.
132    /// - [`Error::Core`] if `dfd` is not a directory: the dirmeta writer
133    ///   refuses the file type of the root.
134    /// - [`Error::Io`] if a file system operation fails.
135    pub async fn merge_overlay_dfd_to_mtree(
136        &self,
137        dfd: BorrowedFd<'_>,
138        mtree: &mut MutableTree,
139        modifier: Option<&mut CommitModifier>,
140    ) -> Result<()> {
141        let mode = self.repo().mode();
142        if mode == RepoMode::BareSplitXattrs {
143            return Err(Error::Unsupported(
144                "bare-split-xattrs is read-only; the port does not write it".into(),
145            ));
146        }
147        let mut modifier = modifier;
148        let flags = modifier
149            .as_deref()
150            .map_or(CommitModifierFlags::empty(), |m| m.flags);
151        let skip_xattrs = flags.contains(CommitModifierFlags::SKIP_XATTRS);
152        if flags.contains(CommitModifierFlags::GENERATE_SIZES) && mode == RepoMode::Archive {
153            self.mark_generate_sizes();
154        }
155
156        // The root of the upper directory is a merged directory. Its metadata
157        // becomes the dirmeta of the base root. An opaque root clears the whole
158        // base.
159        let root_fd = dfd.try_clone_to_owned()?;
160        let (uid, gid, dmode, root_xattrs) = {
161            let fd = root_fd.as_fd().try_clone_to_owned()?;
162            ostrya_rt::unblock(move || read_dir_own(fd.as_fd())).await?
163        };
164        if is_opaque(&root_xattrs) {
165            mtree.clear_children();
166        }
167        let base = FileMeta {
168            uid,
169            gid,
170            mode: dmode,
171            xattrs: content_xattrs(skip_xattrs, &root_xattrs)?,
172        };
173        let adjusted = adjust_meta(flags, Owner::of(modifier.as_deref()), base, false);
174        let root_meta = finalize_meta(modifier.as_deref_mut(), Path::new("/"), adjusted)?;
175        merge_dir(self, root_fd, mtree, modifier, "/".to_owned(), root_meta).await
176    }
177}
178
179/// One entry of an upper directory, read in a blocking snapshot.
180struct OverlayEntry {
181    name: String,
182    kind: OverlayKind,
183    uid: u32,
184    gid: u32,
185    /// The full `st_mode`, including the file-type bits.
186    mode: u32,
187    /// The `st_size` that the snapshot read. It bounds the read-ahead of a
188    /// regular file.
189    size: u64,
190    /// The full xattr set of the entry on disk, with each `trusted.overlay.`
191    /// or `user.overlay.` attribute. The merge reads these attributes for its
192    /// decisions and removes them from the recorded object.
193    xattrs: Xattrs,
194}
195
196/// The kind of an upper directory entry.
197enum OverlayKind {
198    Dir,
199    Regular,
200    Symlink(String),
201    /// A character device with device number 0:0, which marks a deletion.
202    Whiteout,
203}
204
205/// The boxed future of one level of the recursive walk.
206///
207/// Async recursion needs indirection, so each level returns a boxed future.
208type WalkFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
209
210/// Merges one upper directory into `node`.
211///
212/// `dir_meta` is the fully adjusted metadata of this directory. The caller
213/// computes it, so the filter and the user callbacks run once for each
214/// directory. The function writes it as the dirmeta of `node`.
215///
216/// If this directory is opaque, the caller clears the node first: an opaque
217/// child through `remove` and `ensure_dir`, and the opaque root through
218/// `clear_children`. This level only sets the dirmeta and records the entries.
219fn merge_dir<'a>(
220    txn: &'a Transaction,
221    dir_fd: OwnedFd,
222    node: &'a mut MutableTree,
223    mut modifier: Option<&'a mut CommitModifier>,
224    path: String,
225    dir_meta: FileMeta,
226) -> WalkFuture<'a> {
227    Box::pin(async move {
228        let flags = modifier
229            .as_deref()
230            .map_or(CommitModifierFlags::empty(), |m| m.flags);
231        let owner = Owner::of(modifier.as_deref());
232        let skip_xattrs = flags.contains(CommitModifierFlags::SKIP_XATTRS);
233
234        // The dirmeta of this directory comes from the upper inode.
235        let dirmeta = txn.write_dirmeta(&to_dirmeta(&dir_meta)).await?;
236        node.set_metadata_checksum(dirmeta);
237
238        // The merge reads the upper directory in one blocking pass, always with
239        // the xattrs and the device number. The merge decisions use both, also under
240        // SKIP_XATTRS. SKIP_XATTRS controls only the xattr set of the content.
241        let snap = {
242            let dir = dir_fd.as_fd().try_clone_to_owned()?;
243            ostrya_rt::unblock(move || snapshot_overlay(dir.as_fd())).await?
244        };
245
246        for entry in snap {
247            let cb_path = join_path(&path, &entry.name);
248
249            // A whiteout is a merge mechanic. It runs no callback and removes
250            // the base path. If the base has no entry there, nothing changes.
251            if matches!(entry.kind, OverlayKind::Whiteout) {
252                node.remove(&entry.name, true)?;
253                continue;
254            }
255
256            // An entry with `overlay.metacopy` or `overlay.redirect` is not
257            // self-contained.
258            if has_overlay_attr(&entry.xattrs, b"metacopy") {
259                return Err(Error::UnsupportedOverlayFeature(format!(
260                    "overlay.metacopy on {cb_path}; mount the overlay with metacopy=off"
261                )));
262            }
263            if has_overlay_attr(&entry.xattrs, b"redirect") {
264                return Err(Error::UnsupportedOverlayFeature(format!(
265                    "overlay.redirect on {cb_path}; mount the overlay with redirect_dir=off"
266                )));
267            }
268
269            let is_symlink = matches!(entry.kind, OverlayKind::Symlink(_));
270            let base = FileMeta {
271                uid: entry.uid,
272                gid: entry.gid,
273                mode: entry.mode,
274                xattrs: content_xattrs(skip_xattrs, &entry.xattrs)?,
275            };
276            let filter_meta = adjust_meta(flags, owner, base, is_symlink);
277
278            // If the filter returns Skip, the base version stays. The merge does
279            // not apply the upper change and does not touch the base entry.
280            if let Some(m) = modifier.as_deref_mut()
281                && let Some(filter) = &mut m.filter
282                && filter(Path::new(&cb_path), &filter_meta) == FilterResult::Skip
283            {
284                txn.note_filtered();
285                continue;
286            }
287
288            match entry.kind {
289                OverlayKind::Regular => {
290                    let meta =
291                        finalize_meta(modifier.as_deref_mut(), Path::new(&cb_path), filter_meta)?;
292                    let fd = rustix::fs::openat(
293                        dir_fd.as_fd(),
294                        entry.name.as_str(),
295                        OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
296                        Mode::empty(),
297                    )?;
298                    let reader = FileReader::with_len_hint(fd.into(), entry.size);
299                    let checksum = txn.write_content(None, &meta, reader).await?;
300                    // The leaf replaces the base entry at this name (a file, a
301                    // symlink, or a directory). A non-directory upper entry hides
302                    // a lower entry of any type. For this reason, a replacement
303                    // of a directory with a leaf arrives here as a plain entry
304                    // with no whiteout and no opaque marker.
305                    node.remove(&entry.name, true)?;
306                    node.replace_file(&entry.name, checksum)?;
307                }
308                OverlayKind::Symlink(target) => {
309                    let meta =
310                        finalize_meta(modifier.as_deref_mut(), Path::new(&cb_path), filter_meta)?;
311                    let checksum = txn.write_symlink(&target, &meta, None).await?;
312                    // The leaf replaces the base entry at this name.
313                    node.remove(&entry.name, true)?;
314                    node.replace_file(&entry.name, checksum)?;
315                }
316                OverlayKind::Dir => {
317                    // An opaque directory replaces the entry at this name with a
318                    // new directory that holds only the upper entries. A
319                    // non-opaque directory merges over a base directory. If the
320                    // base holds a file or a symlink at the name, the merge
321                    // removes the base leaf and creates a new directory.
322                    // `ensure_dir` cannot merge onto a file entry.
323                    if is_opaque(&entry.xattrs) || node.file_checksum(&entry.name).is_some() {
324                        node.remove(&entry.name, true)?;
325                    }
326                    let meta =
327                        finalize_meta(modifier.as_deref_mut(), Path::new(&cb_path), filter_meta)?;
328                    let child_fd = open_dir(dir_fd.as_fd(), &entry.name)?;
329                    let child = node.ensure_dir(&entry.name).await?;
330                    merge_dir(txn, child_fd, child, modifier.as_deref_mut(), cb_path, meta).await?;
331                }
332                OverlayKind::Whiteout => unreachable!("whiteouts are handled above"),
333            }
334        }
335        Ok(())
336    })
337}
338
339/// Returns `true` if a device number marks an overlayfs whiteout (0:0).
340fn is_whiteout(rdev: u64) -> bool {
341    rustix::fs::major(rdev) == 0 && rustix::fs::minor(rdev) == 0
342}
343
344/// Reads the owner, the mode, and the full xattr set of a directory.
345fn read_dir_own(dir: BorrowedFd<'_>) -> Result<(u32, u32, u32, Xattrs)> {
346    let stat = rustix::fs::fstat(dir)?;
347    let xattrs = crate::object::read_all_xattrs(dir)?;
348    Ok((stat.st_uid, stat.st_gid, stat.st_mode, xattrs))
349}
350
351/// Reads the entries of one upper directory in one blocking pass.
352///
353/// The function always reads the xattrs and the device number of each entry.
354/// The merge needs the `overlay.*` attributes and the device number also
355/// under SKIP_XATTRS. It reads the xattrs of a symlink with no-follow,
356/// from the link itself.
357fn snapshot_overlay(dir: BorrowedFd<'_>) -> Result<Vec<OverlayEntry>> {
358    let mut entries = Vec::new();
359    for entry in Dir::read_from(dir)? {
360        let entry = entry?;
361        let name = entry.file_name();
362        if name == c"." || name == c".." {
363            continue;
364        }
365        let name = name
366            .to_str()
367            .map_err(|_| Error::InvalidFormat("upperdir entry name is not valid UTF-8".into()))?
368            .to_owned();
369
370        let stat = rustix::fs::statat(dir, name.as_str(), AtFlags::SYMLINK_NOFOLLOW)?;
371        let kind = match FileType::from_raw_mode(stat.st_mode) {
372            FileType::CharacterDevice if is_whiteout(stat.st_rdev) => OverlayKind::Whiteout,
373            FileType::Directory => OverlayKind::Dir,
374            FileType::RegularFile => OverlayKind::Regular,
375            FileType::Symlink => {
376                let target = rustix::fs::readlinkat(dir, name.as_str(), Vec::new())?
377                    .into_string()
378                    .map_err(|_| {
379                        Error::InvalidFormat("symlink target is not valid UTF-8".into())
380                    })?;
381                OverlayKind::Symlink(target)
382            }
383            _ => {
384                return Err(Error::Unsupported(format!(
385                    "unsupported upperdir entry type for {name:?}"
386                )));
387            }
388        };
389
390        // A whiteout carries no content, so it needs no xattr read.
391        let xattrs = match kind {
392            OverlayKind::Whiteout => Xattrs::empty(),
393            _ => read_entry_xattrs(dir, name.as_str(), &kind)?,
394        };
395
396        entries.push(OverlayEntry {
397            name,
398            kind,
399            uid: stat.st_uid,
400            gid: stat.st_gid,
401            mode: stat.st_mode,
402            size: stat.st_size as u64,
403            xattrs,
404        });
405    }
406    Ok(entries)
407}
408
409/// Reads the xattrs of one upper directory entry with no-follow.
410///
411/// The function opens a regular file or a directory and reads from its
412/// descriptor. It reads a symlink through the path-based no-follow reader.
413fn read_entry_xattrs(dir: BorrowedFd<'_>, name: &str, kind: &OverlayKind) -> Result<Xattrs> {
414    let oflags = match kind {
415        OverlayKind::Regular => OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
416        OverlayKind::Dir => OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
417        OverlayKind::Symlink(_) => return crate::object::read_link_xattrs(dir, name),
418        OverlayKind::Whiteout => return Ok(Xattrs::empty()),
419    };
420    let fd = rustix::fs::openat(dir, name, oflags, Mode::empty())?;
421    crate::object::read_all_xattrs(fd.as_fd())
422}
423
424/// Opens the subdirectory `name` of `parent` with no-follow.
425fn open_dir(parent: BorrowedFd<'_>, name: &str) -> Result<OwnedFd> {
426    Ok(rustix::fs::openat(
427        parent,
428        name,
429        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
430        Mode::empty(),
431    )?)
432}
433
434/// Returns the xattr set of a recorded object.
435///
436/// The set is the set on disk without each `trusted.overlay.` or
437/// `user.overlay.` attribute. Under SKIP_XATTRS, the set is empty.
438fn content_xattrs(skip: bool, full: &Xattrs) -> Result<Xattrs> {
439    if skip {
440        return Ok(Xattrs::empty());
441    }
442    let pairs: Vec<(Vec<u8>, Vec<u8>)> = full
443        .iter()
444        .filter(|(name, _)| !is_overlay_name(name))
445        .map(|(name, value)| (name.to_vec(), value.to_vec()))
446        .collect();
447    Ok(Xattrs::new(pairs)?)
448}
449
450/// Returns `true` if an xattr name is in one of the overlay control namespaces.
451fn is_overlay_name(name: &[u8]) -> bool {
452    OVERLAY_PREFIXES.iter().any(|p| name.starts_with(p))
453}
454
455/// Returns `true` if the xattr set holds `<ns>.overlay.<suffix>`.
456///
457/// `<ns>` is one of the two namespaces. If `require_y` is set, the value must
458/// be exactly `y` (the opaque marker).
459fn overlay_attr_present(xattrs: &Xattrs, suffix: &[u8], require_y: bool) -> bool {
460    xattrs.iter().any(|(name, value)| {
461        let matches_name = OVERLAY_PREFIXES.iter().any(|p| {
462            let mut want = Vec::with_capacity(p.len() + suffix.len() + 1);
463            want.extend_from_slice(p);
464            want.extend_from_slice(suffix);
465            want.push(0);
466            name == want.as_slice()
467        });
468        matches_name && (!require_y || value == b"y")
469    })
470}
471
472/// Returns `true` if a directory is opaque (`overlay.opaque` set to `y`).
473fn is_opaque(xattrs: &Xattrs) -> bool {
474    overlay_attr_present(xattrs, b"opaque", true)
475}
476
477/// Returns `true` if an entry has the named overlay feature attribute.
478///
479/// The value of the attribute does not matter.
480fn has_overlay_attr(xattrs: &Xattrs, suffix: &[u8]) -> bool {
481    overlay_attr_present(xattrs, suffix, false)
482}