use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::time::{Duration, UNIX_EPOCH};
use futures_io::{AsyncRead, AsyncWrite};
use futures_lite::StreamExt;
use ostrya_core::{Checksum, DirMeta, Xattrs};
use smol_tar::{
AttrList, TarDirectory, TarEntry, TarLink, TarReader, TarRegularFile, TarSymlink, TarWriter,
};
use crate::error::{Error, Result};
use crate::file::{FileKind, FileObject};
use crate::ingest::{adjust_meta, finalize_meta, to_dirmeta};
use crate::modifier::{CommitModifier, CommitModifierFlags, FilterResult, Owner};
use crate::mtree::{ChildKind, MutableTree};
use crate::repo::Repo;
use crate::transaction::{FileMeta, Transaction};
use crate::tree::{RepoTree, TreeEntry};
const S_IFDIR: u32 = 0o040000;
const S_IFLNK: u32 = 0o120000;
const PERM_MASK: u32 = 0o7777;
type BodyReader = Pin<Box<dyn AsyncRead + Send>>;
#[derive(Debug, Default, Clone)]
#[non_exhaustive]
pub struct TarExportOptions {}
impl TarExportOptions {
pub fn new() -> TarExportOptions {
TarExportOptions::default()
}
}
pub type TarRename = Box<dyn FnMut(&str) -> Result<String> + Send>;
#[derive(Default)]
#[non_exhaustive]
pub struct TarImportOptions {
pub etc_to_usr_etc: bool,
pub owner_uid: Option<u32>,
pub owner_gid: Option<u32>,
pub skip_xattrs: bool,
pub autocreate_parents: bool,
pub rename: Option<TarRename>,
}
impl std::fmt::Debug for TarImportOptions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TarImportOptions")
.field("etc_to_usr_etc", &self.etc_to_usr_etc)
.field("owner_uid", &self.owner_uid)
.field("owner_gid", &self.owner_gid)
.field("skip_xattrs", &self.skip_xattrs)
.field("autocreate_parents", &self.autocreate_parents)
.field("rename", &self.rename.is_some())
.finish()
}
}
impl TarImportOptions {
pub fn new() -> TarImportOptions {
TarImportOptions::default()
}
pub fn with_etc_migration(mut self, on: bool) -> TarImportOptions {
self.etc_to_usr_etc = on;
self
}
fn uid(&self, from_header: u32) -> u32 {
self.owner_uid.unwrap_or(from_header)
}
fn gid(&self, from_header: u32) -> u32 {
self.owner_gid.unwrap_or(from_header)
}
}
enum Item {
Dir {
path: String,
meta: DirMeta,
},
Regular {
path: String,
file: FileObject,
size: u64,
},
Symlink {
path: String,
file: FileObject,
target: String,
},
Hardlink {
path: String,
target: String,
},
}
impl Repo {
pub async fn export_tar(
&self,
commit: &Checksum,
_opts: TarExportOptions,
out: impl AsyncWrite,
) -> Result<()> {
let (commit_obj, _) = self.load_commit(commit).await?;
let mtime = UNIX_EPOCH + Duration::from_secs(commit_obj.timestamp);
let root = RepoTree::from_parts(
self.clone(),
commit_obj.root_dirtree,
commit_obj.root_dirmeta,
);
let root_meta = self.load_dirmeta(&commit_obj.root_dirmeta).await?;
let mut items = vec![Item::Dir {
path: "./".to_owned(),
meta: root_meta,
}];
let mut seen: HashMap<Checksum, String> = HashMap::new();
collect(self, root, String::new(), &mut items, &mut seen).await?;
let mut writer = TarWriter::<'_, '_, _, BodyReader>::new(out);
for item in items {
match item {
Item::Dir { path, meta } => {
let entry = TarDirectory::new(path)
.with_uid(meta.uid)
.with_gid(meta.gid)
.with_mode(meta.mode & PERM_MASK)
.with_mtime(mtime)
.with_attrs(xattrs_to_attrs(&meta.xattrs)?);
writer.write(entry.into()).await.map_err(Error::Io)?;
}
Item::Regular { path, file, size } => {
let attrs = xattrs_to_attrs(&file.xattrs)?;
let body: BodyReader = Box::pin(file.reader().await?);
let entry = TarRegularFile::new(path, size, body)
.with_uid(file.uid)
.with_gid(file.gid)
.with_mode(file.mode & PERM_MASK)
.with_mtime(mtime)
.with_attrs(attrs);
writer.write(entry.into()).await.map_err(Error::Io)?;
}
Item::Symlink { path, file, target } => {
let entry = TarSymlink::new(path, target)
.with_uid(file.uid)
.with_gid(file.gid)
.with_mode(file.mode & PERM_MASK)
.with_mtime(mtime)
.with_attrs(xattrs_to_attrs(&file.xattrs)?);
writer.write(entry.into()).await.map_err(Error::Io)?;
}
Item::Hardlink { path, target } => {
writer
.write(TarLink::new(path, target).into())
.await
.map_err(Error::Io)?;
}
}
}
writer.finish().await.map_err(Error::Io)?;
Ok(())
}
pub async fn import_tar(
&self,
txn: &Transaction,
opts: TarImportOptions,
input: impl AsyncRead,
) -> Result<MutableTree> {
let mut mtree = MutableTree::new();
self.import_tar_into(txn, opts, input, &mut mtree, None)
.await?;
Ok(mtree)
}
pub async fn import_tar_into(
&self,
txn: &Transaction,
mut opts: TarImportOptions,
input: impl AsyncRead,
mtree: &mut MutableTree,
mut modifier: Option<&mut CommitModifier>,
) -> Result<()> {
let mut reader = TarReader::new(input);
let flags = modifier
.as_deref()
.map_or(CommitModifierFlags::empty(), |m| m.flags);
let owner = Owner::of(modifier.as_deref());
let mut file_index: HashMap<Vec<String>, Checksum> = HashMap::new();
let mut hardlinks: Vec<(Vec<String>, Vec<String>)> = Vec::new();
let mut synthesized: Option<(u32, u32)> = None;
while let Some(entry) = reader.next().await {
let entry = entry.map_err(read_error)?;
match entry {
TarEntry::Directory(dir) => {
let comps = member_path(dir.path(), true, &mut opts)?;
let base = FileMeta {
uid: opts.uid(dir.uid()),
gid: opts.gid(dir.gid()),
mode: S_IFDIR | (dir.mode() & PERM_MASK),
xattrs: attrs_to_xattrs(dir.attrs(), &opts)?,
};
let Some(meta) = shape(
txn,
modifier.as_deref_mut(),
flags,
owner,
&comps,
base,
false,
)?
else {
continue;
};
let checksum = txn.write_dirmeta(&to_dirmeta(&meta)).await?;
let raw = (opts.uid(dir.uid()), opts.gid(dir.gid()));
place_dir(txn, mtree, &comps, checksum, &opts, raw, &mut synthesized).await?;
}
TarEntry::File(file) => {
let comps = member_path(file.path(), false, &mut opts)?;
require_leaf(&comps, "regular file")?;
let mut base = FileMeta::regular(
opts.uid(file.uid()),
opts.gid(file.gid()),
file.mode() & PERM_MASK,
);
base.xattrs = attrs_to_xattrs(file.attrs(), &opts)?;
let raw = (opts.uid(file.uid()), opts.gid(file.gid()));
let Some(meta) = shape(
txn,
modifier.as_deref_mut(),
flags,
owner,
&comps,
base,
false,
)?
else {
continue;
};
let checksum = txn.write_content(None, &meta, file).await?;
place(txn, mtree, &comps, checksum, &opts, raw, &mut synthesized).await?;
file_index.insert(comps, checksum);
}
TarEntry::Symlink(link) => {
let comps = member_path(link.path(), false, &mut opts)?;
require_leaf(&comps, "symlink")?;
let base = FileMeta {
uid: opts.uid(link.uid()),
gid: opts.gid(link.gid()),
mode: S_IFLNK | (link.mode() & PERM_MASK),
xattrs: attrs_to_xattrs(link.attrs(), &opts)?,
};
let raw = (opts.uid(link.uid()), opts.gid(link.gid()));
let target = link.link().to_owned();
let Some(meta) = shape(
txn,
modifier.as_deref_mut(),
flags,
owner,
&comps,
base,
true,
)?
else {
continue;
};
let checksum = txn.write_symlink(&target, &meta, None).await?;
place(txn, mtree, &comps, checksum, &opts, raw, &mut synthesized).await?;
file_index.insert(comps, checksum);
}
TarEntry::Link(link) => {
let comps = member_path(link.path(), false, &mut opts)?;
require_leaf(&comps, "hardlink")?;
let target = member_path(link.link(), false, &mut opts)?;
let raw = (opts.uid(0), opts.gid(0));
let parents = &comps[..comps.len() - 1];
descend(txn, mtree, parents, &opts, raw, &mut synthesized).await?;
hardlinks.push((comps, target));
}
TarEntry::Device(dev) => {
return Err(Error::Tar(format!(
"cannot import device node {:?}: an ostree tree stores only \
regular files, symlinks, and directories",
dev.path()
)));
}
TarEntry::Fifo(fifo) => {
return Err(Error::Tar(format!(
"cannot import FIFO {:?}: an ostree tree stores only \
regular files, symlinks, and directories",
fifo.path()
)));
}
}
}
for (link, target) in hardlinks {
let checksum = file_index.get(&target).copied().ok_or_else(|| {
Error::Tar(format!(
"hardlink {} has no target {} in the archive",
join(&link),
join(&target)
))
})?;
let (leaf, parents) = link
.split_last()
.expect("a hardlink path has at least one component");
let node = mtree
.dir_at_mut(parents)
.expect("the hardlink's parents were created during the walk");
node.replace_file(leaf, checksum)?;
file_index.insert(link, checksum);
}
if opts.autocreate_parents
&& let Some((uid, gid)) = synthesized.or_else(|| {
mtree
.metadata_checksum()
.is_none()
.then_some((opts.uid(0), opts.gid(0)))
})
{
let meta = DirMeta {
uid,
gid,
mode: S_IFDIR | 0o755,
xattrs: Xattrs::empty(),
};
let checksum = txn.write_dirmeta(&meta).await?;
mtree.set_metadata_checksum(checksum);
}
Ok(())
}
}
fn shape(
txn: &Transaction,
mut modifier: Option<&mut CommitModifier>,
flags: CommitModifierFlags,
owner: Owner,
comps: &[String],
base: FileMeta,
is_symlink: bool,
) -> Result<Option<FileMeta>> {
let path = callback_path(comps);
let xattrs = base.xattrs.clone();
let mut adjusted = adjust_meta(flags, owner, base, is_symlink);
adjusted.xattrs = xattrs;
if let Some(m) = modifier.as_deref_mut()
&& let Some(filter) = &mut m.filter
&& filter(std::path::Path::new(&path), &adjusted) == FilterResult::Skip
{
txn.note_filtered();
return Ok(None);
}
Ok(Some(finalize_meta(
modifier,
std::path::Path::new(&path),
adjusted,
)?))
}
fn callback_path(comps: &[String]) -> String {
if comps.is_empty() {
"/".to_owned()
} else {
format!("/{}", comps.join("/"))
}
}
async fn descend<'a>(
txn: &Transaction,
root: &'a mut MutableTree,
ancestors: &[String],
opts: &TarImportOptions,
raw_owner: (u32, u32),
synthesized: &mut Option<(u32, u32)>,
) -> Result<&'a mut MutableTree> {
let mut node = root;
for name in ancestors {
match node.child_kind(name) {
ChildKind::File(_) => return Err(Error::ReplaceFileWithDir(name.clone())),
ChildKind::Absent => {
if !opts.autocreate_parents {
return Err(Error::TarMissingParent(name.clone()));
}
let meta = DirMeta {
uid: raw_owner.0,
gid: raw_owner.1,
mode: S_IFDIR | 0o755,
xattrs: Xattrs::empty(),
};
let checksum = txn.write_dirmeta(&meta).await?;
*synthesized = Some(raw_owner);
let child = node.ensure_dir(name).await?;
child.set_metadata_checksum(checksum);
node = child;
}
_ => node = node.ensure_dir(name).await?,
}
}
Ok(node)
}
async fn place_dir(
txn: &Transaction,
root: &mut MutableTree,
comps: &[String],
dirmeta: Checksum,
opts: &TarImportOptions,
raw_owner: (u32, u32),
synthesized: &mut Option<(u32, u32)>,
) -> Result<()> {
let Some((leaf, parents)) = comps.split_last() else {
root.set_metadata_checksum(dirmeta);
return Ok(());
};
let node = descend(txn, root, parents, opts, raw_owner, synthesized).await?;
node.ensure_dir(leaf).await?.set_metadata_checksum(dirmeta);
Ok(())
}
async fn place(
txn: &Transaction,
root: &mut MutableTree,
comps: &[String],
checksum: Checksum,
opts: &TarImportOptions,
raw_owner: (u32, u32),
synthesized: &mut Option<(u32, u32)>,
) -> Result<()> {
let (leaf, parents) = comps
.split_last()
.expect("a content member has at least one component");
let node = descend(txn, root, parents, opts, raw_owner, synthesized).await?;
node.replace_file(leaf, checksum)?;
Ok(())
}
fn collect<'a>(
repo: &'a Repo,
tree: RepoTree,
prefix: String,
items: &'a mut Vec<Item>,
seen: &'a mut HashMap<Checksum, String>,
) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
Box::pin(async move {
let mut entries = tree.read_dir().await?;
entries.sort_by(|a, b| entry_name(a).as_bytes().cmp(entry_name(b).as_bytes()));
for entry in entries {
match entry {
TreeEntry::File { name, checksum } => {
let path = format!("{prefix}{name}");
if let Some(target) = seen.get(&checksum) {
items.push(Item::Hardlink {
path,
target: target.clone(),
});
continue;
}
let file = repo.load_file(&checksum).await?;
match &file.kind {
FileKind::Regular { size } => {
let size = *size;
seen.insert(checksum, path.clone());
items.push(Item::Regular { path, file, size });
}
FileKind::Symlink { target } => {
let target = target.clone();
items.push(Item::Symlink { path, file, target });
}
}
}
TreeEntry::Dir {
name,
tree: subtree,
} => {
let path = format!("{prefix}{name}/");
let meta = repo.load_dirmeta(subtree.dirmeta_checksum()).await?;
items.push(Item::Dir {
path: path.clone(),
meta,
});
collect(repo, subtree, path, items, seen).await?;
}
}
}
Ok(())
})
}
fn read_error(err: std::io::Error) -> Error {
if err.kind() == std::io::ErrorKind::InvalidData
&& err.to_string().contains("utf8 in file path")
{
return Error::TarPathname;
}
Error::Io(err)
}
fn entry_name(entry: &TreeEntry) -> &str {
match entry {
TreeEntry::File { name, .. } => name,
TreeEntry::Dir { name, .. } => name,
}
}
fn member_path(raw: &str, is_dir: bool, opts: &mut TarImportOptions) -> Result<Vec<String>> {
let stripped = raw.strip_prefix("./").unwrap_or(raw);
let stripped = stripped.strip_prefix('/').unwrap_or(stripped);
let mut name = if stripped == "." {
String::new()
} else {
stripped.to_owned()
};
if is_dir && !name.is_empty() && !name.ends_with('/') {
name.push('/');
}
if let Some(rename) = &mut opts.rename {
name = rename(&name)?;
}
normalize(&name, opts)
}
fn normalize(raw: &str, opts: &TarImportOptions) -> Result<Vec<String>> {
let mut comps = Vec::new();
for part in raw.split('/') {
match part {
"" | "." => continue,
".." => {
return Err(Error::Tar(format!(
"tar member {raw:?} has a '..' path component"
)));
}
other => comps.push(other.to_owned()),
}
}
if opts.etc_to_usr_etc && comps.first().is_some_and(|c| c == "etc") {
let mut remapped = vec!["usr".to_owned(), "etc".to_owned()];
remapped.extend(comps.into_iter().skip(1));
comps = remapped;
}
Ok(comps)
}
fn require_leaf(comps: &[String], kind: &str) -> Result<()> {
if comps.is_empty() {
return Err(Error::Tar(format!("{kind} entry has an empty path")));
}
Ok(())
}
fn join(comps: &[String]) -> String {
comps.join("/")
}
fn xattrs_to_attrs(xattrs: &Xattrs) -> Result<AttrList> {
let mut attrs = AttrList::new();
for (name, value) in xattrs.iter() {
let name = name.strip_suffix(&[0]).unwrap_or(name);
let name = std::str::from_utf8(name)
.map_err(|_| Error::Tar("xattr name is not valid UTF-8".to_owned()))?;
attrs.push(name.to_owned(), value.to_vec());
}
Ok(attrs)
}
fn attrs_to_xattrs(attrs: &AttrList, opts: &TarImportOptions) -> Result<Xattrs> {
if opts.skip_xattrs || attrs.is_empty() {
return Ok(Xattrs::empty());
}
let mut pairs = Vec::with_capacity(attrs.len());
for (name, value) in attrs.iter() {
let mut stored = name.as_bytes().to_vec();
stored.push(0);
pairs.push((stored, value.to_vec()));
}
Ok(Xattrs::new(pairs)?)
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
fn assert_send<T: Send>() {}
assert_send_sync::<TarExportOptions>();
assert_send::<TarImportOptions>();
};