use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::time::{Duration, Instant};
use futures_lite::AsyncReadExt;
use ostrya_core::{
Checksum, Commit, ContentHasher, DirTree, ObjectName, ObjectType, RepoMode, Value,
};
use rustix::fs::{AtFlags, Mode, OFlags};
use sha2::{Digest, Sha256};
use crate::composefs::recorded_digest;
use crate::error::{Error, Result};
use crate::file::FileKind;
use crate::modifier::FilterResult;
use crate::perm;
use crate::refs::{CollectionRef, collection_ref_to_relpath, refspec_to_relpath};
use crate::repo::Repo;
use crate::summary::AdvertisedDelta;
use crate::transaction::Transaction;
use crate::traverse::reaches_at_least;
use crate::write::FileMeta;
mod chain;
mod collection;
mod delta;
mod drive;
#[doc(hidden)]
pub mod http;
mod source;
mod subpath;
mod verify;
pub use collection::{
CollectionPullEvent, CollectionPullOptions, CollectionPullRef, CollectionPullStats,
};
const READ_CHUNK: usize = 128 * 1024;
pub(crate) const PARTIAL_MARKER_MODE: u32 = 0o644;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PullFlags(u32);
impl PullFlags {
pub const NONE: PullFlags = PullFlags(0);
pub const UNTRUSTED: PullFlags = PullFlags(1 << 0);
pub const COMMIT_ONLY: PullFlags = PullFlags(1 << 1);
pub const BAREUSERONLY_FILES: PullFlags = PullFlags(1 << 2);
pub const DISABLE_VERIFY_BINDINGS: PullFlags = PullFlags(1 << 3);
pub const FORCE_COPY: PullFlags = PullFlags(1 << 4);
pub const MIRROR: PullFlags = PullFlags(1 << 5);
pub const fn empty() -> PullFlags {
PullFlags(0)
}
pub const fn contains(self, other: PullFlags) -> bool {
self.0 & other.0 == other.0
}
pub const fn bits(self) -> u32 {
self.0
}
}
impl std::ops::BitOr for PullFlags {
type Output = PullFlags;
fn bitor(self, rhs: PullFlags) -> PullFlags {
PullFlags(self.0 | rhs.0)
}
}
impl std::ops::BitOrAssign for PullFlags {
fn bitor_assign(&mut self, rhs: PullFlags) {
self.0 |= rhs.0;
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum TimestampCheck {
#[default]
Off,
CurrentRef,
Rev(Checksum),
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PullVerify {
pub gpg: Option<bool>,
pub gpg_summary: Option<bool>,
pub sign: Option<bool>,
pub sign_summary: Option<bool>,
}
pub type DetachedMetadataFilterFn =
Arc<dyn Fn(&Checksum, &str, &Value) -> FilterResult + Send + Sync>;
#[derive(Clone, Default)]
pub struct DetachedMetadataFilter(Option<DetachedMetadataFilterFn>);
impl DetachedMetadataFilter {
pub fn new<F>(f: F) -> DetachedMetadataFilter
where
F: Fn(&Checksum, &str, &Value) -> FilterResult + Send + Sync + 'static,
{
DetachedMetadataFilter(Some(Arc::new(f)))
}
pub fn from_fn(f: DetachedMetadataFilterFn) -> DetachedMetadataFilter {
DetachedMetadataFilter(Some(f))
}
pub fn excluding<I, S>(names: I) -> DetachedMetadataFilter
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
let names: Vec<String> = names.into_iter().map(Into::into).collect();
DetachedMetadataFilter::new(move |_, key, _| {
if names.iter().any(|name| name == key) {
FilterResult::Skip
} else {
FilterResult::Allow
}
})
}
pub(crate) fn apply(&self, commit: &Checksum, bytes: Vec<u8>) -> Result<Option<Vec<u8>>> {
if self.0.is_none() {
return Ok(Some(bytes));
}
let Some(dict) = crate::summary::parse_signature_dict(&bytes)? else {
return Ok(Some(bytes));
};
self.apply_parsed(commit, bytes, dict)
}
pub(crate) async fn apply_on_pool(
&self,
commit: &Checksum,
bytes: Vec<u8>,
) -> Result<Option<Vec<u8>>> {
if self.0.is_none() || bytes.is_empty() {
return Ok(Some(bytes));
}
let filter = self.clone();
let commit = *commit;
ostrya_rt::unblock(move || filter.apply(&commit, bytes)).await
}
pub(crate) fn apply_parsed(
&self,
commit: &Checksum,
bytes: Vec<u8>,
dict: Value,
) -> Result<Option<Vec<u8>>> {
let Some(filter) = &self.0 else {
return Ok(Some(bytes));
};
match kept_entries(filter, commit, dict)? {
Kept::All(_) => Ok(Some(bytes)),
Kept::Nothing => Ok(None),
Kept::Part(kept) => {
drop(bytes);
crate::summary::serialize_signature_dict(&Value::Array(kept)).map(Some)
}
}
}
#[cfg_attr(not(feature = "push"), allow(dead_code))]
pub(crate) fn apply_value(&self, commit: &Checksum, dict: Value) -> Result<Option<Value>> {
let Some(filter) = &self.0 else {
return Ok(Some(dict));
};
match kept_entries(filter, commit, dict)? {
Kept::All(dict) => Ok(Some(dict)),
Kept::Nothing => Ok(None),
Kept::Part(kept) => Ok(Some(Value::Array(kept))),
}
}
}
enum Kept {
All(Value),
Part(Vec<Value>),
Nothing,
}
fn kept_entries(filter: &DetachedMetadataFilterFn, commit: &Checksum, dict: Value) -> Result<Kept> {
let Value::Array(entries) = dict else {
return Err(Error::InvalidFormat(format!(
"detached metadata of {commit} is not a dict"
)));
};
let mut allowed = Vec::with_capacity(entries.len());
for entry in &entries {
let (key, value) = entry
.as_tuple()
.and_then(|fields| match fields {
[key, value] => key.as_str().map(|key| (key, value)),
_ => None,
})
.ok_or_else(|| {
Error::InvalidFormat(format!(
"detached metadata of {commit} holds an entry that is not `{{sv}}`"
))
})?;
allowed.push(filter(commit, key, value) == FilterResult::Allow);
}
if allowed.iter().all(|allow| *allow) {
return Ok(Kept::All(Value::Array(entries)));
}
if !allowed.iter().any(|allow| *allow) {
return Ok(Kept::Nothing);
}
let kept = entries
.into_iter()
.zip(allowed)
.filter_map(|(entry, allow)| allow.then_some(entry))
.collect();
Ok(Kept::Part(kept))
}
impl std::fmt::Debug for DetachedMetadataFilter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0 {
Some(_) => f.write_str("DetachedMetadataFilter(set)"),
None => f.write_str("DetachedMetadataFilter(unset)"),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct PullOptions {
pub refs: Vec<String>,
pub remote: Option<String>,
pub no_ref_writes: bool,
pub collection_id: Option<String>,
pub flags: PullFlags,
pub depth: i32,
pub localcache_repos: Vec<Repo>,
pub disable_fsync: bool,
pub per_object_fsync: bool,
pub subpaths: Vec<String>,
pub overrides: crate::endpoint::EndpointOverrides,
pub max_outstanding_fetches: Option<usize>,
pub timestamp_check: TimestampCheck,
pub disable_static_deltas: bool,
pub require_static_deltas: bool,
pub static_deltas: Option<Vec<AdvertisedDelta>>,
pub verify: PullVerify,
pub detached_metadata_filter: DetachedMetadataFilter,
pub progress: Option<PullProgress>,
}
fn apply_durability(txn: &mut Transaction, opts: &PullOptions) {
if opts.disable_fsync {
txn.set_fsync(false);
}
if opts.per_object_fsync {
txn.set_per_object_fsync(true);
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PullStats {
pub metadata_imported: u32,
pub content_imported: u32,
pub content_bytes_written: u64,
pub content_bytes_unpacked: u64,
pub metadata_fetched: u32,
pub content_fetched: u32,
pub delta_parts: u32,
pub bytes_transferred: u64,
pub elapsed: Duration,
}
#[derive(Debug, Clone, Default)]
pub struct PullProgress {
inner: Arc<ProgressCounters>,
}
#[derive(Debug, Default)]
pub(crate) struct ProgressCounters {
transferred: Arc<AtomicU64>,
metadata_fetched: AtomicU32,
content_fetched: AtomicU32,
objects_done: AtomicU32,
objects_total: AtomicU32,
scanning: AtomicU32,
delta_parts_fetched: AtomicU32,
delta_parts_total: AtomicU32,
delta_bytes_fetched: AtomicU64,
delta_bytes_total: AtomicU64,
}
pub(crate) struct PullCounters {
own: ProgressCounters,
caller: Option<Arc<ProgressCounters>>,
}
impl PullCounters {
pub(crate) fn new(caller: Option<&PullProgress>) -> PullCounters {
let counters = PullCounters {
own: ProgressCounters::default(),
caller: caller.map(|progress| Arc::clone(&progress.inner)),
};
counters.each(|c| {
c.scanning.fetch_add(1, Ordering::Relaxed);
});
counters
}
fn each(&self, f: impl Fn(&ProgressCounters)) {
f(&self.own);
if let Some(caller) = &self.caller {
f(caller);
}
}
pub(crate) fn transferred_sinks(&self) -> Vec<Arc<AtomicU64>> {
let mut sinks = vec![Arc::clone(&self.own.transferred)];
if let Some(caller) = &self.caller {
sinks.push(Arc::clone(&caller.transferred));
}
sinks
}
pub(crate) fn restart_transferred(&self) {
let counted = self.own.transferred.swap(0, Ordering::Relaxed);
if let Some(caller) = &self.caller {
caller.transferred.fetch_sub(counted, Ordering::Relaxed);
}
}
pub(crate) fn metadata_fetched(&self) {
self.each(|c| {
c.metadata_fetched.fetch_add(1, Ordering::Relaxed);
});
}
pub(crate) fn content_fetched(&self) {
self.each(|c| {
c.content_fetched.fetch_add(1, Ordering::Relaxed);
});
}
pub(crate) fn object_done(&self) {
self.each(|c| {
c.objects_done.fetch_add(1, Ordering::Relaxed);
});
}
pub(crate) fn add_transferred(&self, bytes: u64) {
self.each(|c| {
c.transferred.fetch_add(bytes, Ordering::Relaxed);
});
}
pub(crate) fn part_fetched(&self, size: u64) {
self.each(|c| {
c.delta_parts_fetched.fetch_add(1, Ordering::Relaxed);
c.delta_bytes_fetched.fetch_add(size, Ordering::Relaxed);
});
}
pub(crate) fn parts_planned(&self, parts: u32, bytes: u64) {
self.each(|c| {
c.delta_parts_total.fetch_add(parts, Ordering::Relaxed);
c.delta_bytes_total.fetch_add(bytes, Ordering::Relaxed);
});
}
pub(crate) fn report(&self, total: u32, scanning: bool) {
let before = self.own.objects_total.swap(total, Ordering::Relaxed);
let was = self
.own
.scanning
.swap(u32::from(scanning), Ordering::Relaxed);
if let Some(caller) = &self.caller {
caller
.objects_total
.fetch_add(total.wrapping_sub(before), Ordering::Relaxed);
match (was, scanning) {
(0, true) => caller.scanning.fetch_add(1, Ordering::Relaxed),
(1, false) => caller.scanning.fetch_sub(1, Ordering::Relaxed),
_ => 0,
};
}
}
pub(crate) fn metadata(&self) -> u32 {
self.own.metadata_fetched.load(Ordering::Relaxed)
}
pub(crate) fn content(&self) -> u32 {
self.own.content_fetched.load(Ordering::Relaxed)
}
pub(crate) fn parts(&self) -> u32 {
self.own.delta_parts_fetched.load(Ordering::Relaxed)
}
pub(crate) fn bytes(&self) -> u64 {
self.own.transferred.load(Ordering::Relaxed)
}
}
impl Drop for PullCounters {
fn drop(&mut self) {
if let Some(caller) = &self.caller
&& self.own.scanning.load(Ordering::Relaxed) != 0
{
caller.scanning.fetch_sub(1, Ordering::Relaxed);
}
}
}
impl PullProgress {
pub fn new() -> PullProgress {
PullProgress::default()
}
pub fn snapshot(&self) -> PullProgressSnapshot {
let c = &self.inner;
PullProgressSnapshot {
bytes_transferred: c.transferred.load(Ordering::Relaxed),
metadata_fetched: c.metadata_fetched.load(Ordering::Relaxed),
content_fetched: c.content_fetched.load(Ordering::Relaxed),
objects_done: c.objects_done.load(Ordering::Relaxed),
objects_total: c.objects_total.load(Ordering::Relaxed),
scanning: c.scanning.load(Ordering::Relaxed) != 0,
delta_parts_fetched: c.delta_parts_fetched.load(Ordering::Relaxed),
delta_parts_total: c.delta_parts_total.load(Ordering::Relaxed),
delta_bytes_fetched: c.delta_bytes_fetched.load(Ordering::Relaxed),
delta_bytes_total: c.delta_bytes_total.load(Ordering::Relaxed),
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct PullProgressSnapshot {
pub bytes_transferred: u64,
pub metadata_fetched: u32,
pub content_fetched: u32,
pub objects_done: u32,
pub objects_total: u32,
pub scanning: bool,
pub delta_parts_fetched: u32,
pub delta_parts_total: u32,
pub delta_bytes_fetched: u64,
pub delta_bytes_total: u64,
}
impl Repo {
pub async fn pull_local(&self, src: &Repo, mut opts: PullOptions) -> Result<PullStats> {
let started = Instant::now();
if !opts.subpaths.is_empty() {
return Err(Error::Unsupported("a local pull takes no subpath".into()));
}
check_depth(opts.depth)?;
check_static_deltas(&opts)?;
let collection_relpaths = check_local_collection(&opts)?;
let edges = take_static_deltas(&mut opts).await?;
let trust = crate::verify::PullTrust::resolve(
self,
opts.remote.as_deref(),
&opts.verify,
crate::verify::Defaults::Off,
)
.await?;
let verification = verify::Verification::from_trust(trust);
let fetching = opts.require_static_deltas && !opts.disable_static_deltas;
let list_applies = edges.is_some() && !opts.flags.contains(PullFlags::COMMIT_ONLY);
let reads_deltas = fetching || list_applies;
let needs_summary = fetching && edges.is_none();
let summary = if verification.checks_summary() || needs_summary {
delta::read_local(
src,
crate::summary::SUMMARY_FILE,
crate::summary::SUMMARY_READ_CAP,
)
.await?
} else {
None
};
if verification.checks_summary() {
let signature = delta::read_local(
src,
crate::summary::SUMMARY_SIG_FILE,
crate::summary::SUMMARY_READ_CAP,
)
.await?;
verification
.check_summary(summary.as_deref(), signature)
.await?;
}
if needs_summary && summary.is_none() {
return Err(delta::no_summary_error());
}
if reads_deltas && !src.mode().is_archive() {
return Err(Error::Unsupported(format!(
"can't pull from a repository in mode {}: a local pull that reads static \
deltas reads an archive repository",
src.mode().as_mode_str()
)));
}
let summary = match summary {
Some(bytes) if needs_summary => {
Some(ostrya_rt::unblock(move || crate::summary::Summary::parse(&bytes)).await?)
}
_ => None,
};
let targets = resolve_targets(src, &opts, collection_relpaths).await?;
let flags = opts.flags;
let verify_bindings = !flags.contains(PullFlags::DISABLE_VERIFY_BINDINGS);
let counters = PullCounters::new(None);
let deltas = if summary.is_some() || edges.is_some() {
delta::discover(
self,
&delta::DeltaSource::Local(src),
summary.as_ref(),
&targets,
&opts,
TipChecks::new(
flags,
TimestampBase::Off,
RefPlace::of_remote(opts.remote.as_deref()),
),
edges,
&verification,
&counters,
)
.await?
} else {
delta::DeltaPlan::default()
};
drop(summary);
let mut deltas = deltas;
let done: HashSet<Checksum> = deltas.levels().iter().flatten().copied().collect();
let sources: Vec<&Repo> = std::iter::once(src)
.chain(opts.localcache_repos.iter())
.collect();
let mut check = verification.checks_commits().then(|| ChainCheck {
repo: self,
sources: &sources,
verification: &verification,
plan: &deltas,
failed: None,
});
let mut commits: Vec<ChainCommit> = Vec::new();
let mut seen: HashMap<Checksum, i32> = HashMap::new();
for (ref_name, tip) in &targets {
let (bytes, commit) = load_commit(src, tip).await?;
if verify_bindings && !deltas.checked(tip) {
check_ref_binding(tip, &commit, ref_name)?;
}
collect_chain(
src,
*tip,
(bytes, commit),
opts.depth,
&mut commits,
&mut seen,
check.as_mut(),
)
.await?;
}
if let Some(ChainCheck {
failed: Some(err), ..
}) = check
{
return Err(err);
}
let mut txn = self.transaction().await?;
apply_durability(&mut txn, &opts);
let mut marked: Vec<Checksum> = Vec::new();
let published = async {
let level_commits: Vec<Checksum> = deltas.levels().iter().flatten().copied().collect();
let mut held_levels: HashSet<Checksum> = HashSet::new();
for (commit, held) in chain::check_complete(self, &level_commits).await? {
if held {
held_levels.insert(commit);
} else {
self.write_partial_marker(&commit).await?;
marked.push(commit);
}
}
for commit in &mut commits {
if done.contains(&commit.checksum) {
continue;
}
commit.held = delta::complete_here(self, &commit.checksum).await?;
if !commit.held {
self.write_partial_marker(&commit.checksum).await?;
marked.push(commit.checksum);
}
}
let checks = ModeChecks::new(flags, self.mode());
let delta_source = delta::DeltaSource::Local(src);
let count = reads_deltas.then_some(&counters);
let mut plan = PlanState::default();
let mut verify_buf: Vec<u8> = Vec::new();
for level in deltas.levels() {
let mut made: Vec<ChainCommit> = Vec::with_capacity(level.len());
for commit in level {
let job = deltas
.parse_record(self, &delta_source, commit)
.await?
.ok_or_else(|| {
Error::InvalidFormat(format!(
"static delta to {commit}: the plan holds no step for the commit"
))
})?;
let held = held_levels.contains(commit);
if !held {
for index in 0..job.parts() {
delta::apply_job_part(
&txn,
&delta_source,
&job,
index,
checks,
&counters,
)
.await?;
}
txn.write_metadata(ObjectType::Commit, Some(commit), &job.commit_bytes)
.await?;
}
let bytes = Arc::clone(&job.commit_bytes);
let parsed = ostrya_rt::unblock(move || Commit::parse(&bytes)).await?;
made.push(ChainCommit {
checksum: *commit,
root_dirtree: parsed.root_dirtree,
root_dirmeta: parsed.root_dirmeta,
held,
image_key: recorded_digest(&parsed).ok().flatten(),
});
}
for chain_commit in &made {
self.import_planned(
&txn,
&sources,
chain_commit,
flags,
&mut plan,
&mut verify_buf,
count,
)
.await?;
self.import_detached_metadata(
&txn,
&sources,
&chain_commit.checksum,
&opts.detached_metadata_filter,
None,
)
.await?;
Box::pin(self.import_composefs_image(
&txn,
&sources,
chain_commit,
flags,
count,
))
.await?;
}
}
for (_, tip) in &targets {
if done.contains(tip) || txn.is_staged(tip, ObjectType::Commit) {
continue;
}
let job = match deltas.jobs.remove(tip) {
Some(job) => job,
None => match deltas.parse_record(self, &delta_source, tip).await? {
Some(job) => job,
None => continue,
},
};
for index in 0..job.parts() {
delta::apply_job_part(&txn, &delta_source, &job, index, checks, &counters)
.await?;
}
txn.write_metadata(ObjectType::Commit, Some(tip), &job.commit_bytes)
.await?;
}
drop(std::mem::take(&mut deltas));
for chain_commit in &commits {
let commit = &chain_commit.checksum;
if done.contains(commit) {
continue;
}
self.import_planned(
&txn,
&sources,
chain_commit,
flags,
&mut plan,
&mut verify_buf,
count,
)
.await?;
self.import_detached_metadata(
&txn,
&sources,
commit,
&opts.detached_metadata_filter,
count,
)
.await?;
Box::pin(self.import_composefs_image(&txn, &sources, chain_commit, flags, count))
.await?;
}
if !opts.no_ref_writes {
let place = RefPlace::of_remote(opts.remote.as_deref());
for (ref_name, tip) in &targets {
place.queue(&txn, ref_name, tip);
}
}
txn.commit().await
}
.await;
let stats = match published {
Ok(stats) => stats,
Err(e) => {
self.clear_markers_for_absent_commits(&marked).await;
return Err(e);
}
};
if !flags.contains(PullFlags::COMMIT_ONLY) {
for commit in &marked {
self.remove_partial_marker(commit).await?;
}
}
Ok(PullStats {
metadata_imported: stats.metadata_written,
content_imported: stats.content_written,
content_bytes_written: stats.content_bytes_written,
content_bytes_unpacked: stats.content_bytes_unpacked,
metadata_fetched: counters.metadata(),
content_fetched: counters.content(),
delta_parts: counters.parts(),
bytes_transferred: counters.bytes(),
elapsed: started.elapsed(),
})
}
#[allow(clippy::too_many_arguments)]
async fn import_planned(
&self,
txn: &Transaction,
sources: &[&Repo],
commit: &ChainCommit,
flags: PullFlags,
plan: &mut PlanState,
verify_buf: &mut Vec<u8>,
count: Option<&PullCounters>,
) -> Result<()> {
for name in plan_commit(txn, sources, commit, flags, plan).await? {
let imported = self
.import_object(txn, sources, name, flags, verify_buf)
.await?;
if let Some(counters) = count
&& let Some((0, size)) = imported
{
count_fetched(counters, name.ty, size);
}
}
Ok(())
}
async fn import_object(
&self,
txn: &Transaction,
sources: &[&Repo],
name: ObjectName,
flags: PullFlags,
verify_buf: &mut Vec<u8>,
) -> Result<Option<(usize, u64)>> {
if txn.is_staged(&name.checksum, name.ty)
|| self.has_object(name.ty, &name.checksum).await?
{
return Ok(None);
}
for (position, src) in sources.iter().enumerate() {
if let Some(size) = source_size(src, name.ty, &name.checksum).await? {
self.import_from(txn, src, name, flags, verify_buf).await?;
return Ok(Some((position, size)));
}
}
Err(Error::ObjectNotFound {
checksum: name.checksum,
ty: name.ty,
})
}
async fn import_from(
&self,
txn: &Transaction,
src: &Repo,
name: ObjectName,
flags: PullFlags,
verify_buf: &mut Vec<u8>,
) -> Result<()> {
if name.ty != ObjectType::File {
if flags.contains(PullFlags::UNTRUSTED) {
verify_metadata(src, name).await?;
}
link_import(txn, src, name, flags).await?;
return Ok(());
}
let same_mode = src.mode() == self.mode();
let checks = ModeChecks::new(flags, self.mode());
let untrusted = flags.contains(PullFlags::UNTRUSTED);
let loaded = if checks.any() || untrusted {
let file = src.load_file(&name.checksum).await?;
if checks.any() {
checks.check(&name.checksum, &file.meta())?;
}
Some(file)
} else {
None
};
if same_mode && link_import(txn, src, name, flags).await? {
if untrusted && let Some(file) = &loaded {
verify_content(&name.checksum, file, verify_buf).await?;
}
return Ok(());
}
let file = match loaded {
Some(file) => file,
None => src.load_file(&name.checksum).await?,
};
let meta = file.meta();
match &file.kind {
FileKind::Symlink { target } => {
if symlink_shared(src.mode(), self.mode())
&& link_import(txn, src, name, flags).await?
{
if untrusted {
verify_content(&name.checksum, &file, verify_buf).await?;
}
return Ok(());
}
txn.write_symlink(target, &meta, Some(&name.checksum))
.await?;
}
FileKind::Regular { size } => {
if payload_shared(src.mode(), self.mode()) {
if untrusted {
verify_content(&name.checksum, &file, verify_buf).await?;
}
txn.stage_clone_content(
src.objects_fd(),
name.checksum,
src.mode(),
meta.regular_header(),
*size,
)
.await?;
return Ok(());
}
let reader = file.reader().await?;
txn.write_content(Some(&name.checksum), &meta, reader)
.await?;
}
}
Ok(())
}
async fn import_detached_metadata(
&self,
txn: &Transaction,
sources: &[&Repo],
commit: &Checksum,
filter: &DetachedMetadataFilter,
count: Option<&PullCounters>,
) -> Result<()> {
let owned: Vec<Repo> = sources.iter().map(|src| (*src).clone()).collect();
let filter = filter.clone();
let key = *commit;
let read = ostrya_rt::unblock(move || -> Result<_> {
let Some((at, bytes)) = detached_bytes_from_blocking(&owned, &key)? else {
return Ok(None);
};
let len = bytes.len() as u64;
Ok(Some((at, len, filter.apply(&key, bytes))))
})
.await?;
let Some((at, len, kept)) = read else {
return Ok(());
};
if at == 0
&& let Some(counters) = count
{
count_fetched(counters, ObjectType::CommitMeta, len);
}
if let Some(bytes) = kept? {
txn.stage_commit_detached_bytes(commit, bytes).await?;
}
Ok(())
}
async fn import_composefs_image(
&self,
txn: &Transaction,
sources: &[&Repo],
commit: &ChainCommit,
flags: PullFlags,
count: Option<&PullCounters>,
) -> Result<()> {
if flags.contains(PullFlags::COMMIT_ONLY) || commit.image_key.is_none() {
return Ok(());
}
let checksum = &commit.checksum;
if txn.is_staged(checksum, ObjectType::ComposefsImage)
|| self
.has_object(ObjectType::ComposefsImage, checksum)
.await?
{
return Ok(());
}
for (position, src) in sources.iter().enumerate() {
let Some(size) = txn.import_composefs_image(src, checksum).await? else {
continue;
};
if position == 0
&& let Some(counters) = count
{
count_fetched(counters, ObjectType::ComposefsImage, size);
}
return Ok(());
}
Ok(())
}
async fn write_partial_marker(&self, commit: &Checksum) -> Result<()> {
let path = partial_path(commit);
let repo = self.clone();
ostrya_rt::unblock(move || {
match rustix::fs::openat(
repo.repo_fd(),
path.as_str(),
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC,
Mode::from_raw_mode(PARTIAL_MARKER_MODE),
) {
Ok(fd) => {
perm::force_created_mode(&fd, repo.mode(), perm::SHARED_FILE_MODE)?;
Ok(())
}
Err(rustix::io::Errno::EXIST) => Ok(()),
Err(e) => Err(Error::from(e)),
}
})
.await
}
async fn remove_partial_marker(&self, commit: &Checksum) -> Result<()> {
let path = partial_path(commit);
let repo = self.clone();
ostrya_rt::unblock(move || {
match rustix::fs::unlinkat(repo.repo_fd(), path.as_str(), AtFlags::empty()) {
Ok(()) | Err(rustix::io::Errno::NOENT) => Ok(()),
Err(e) => Err(Error::from(e)),
}
})
.await
}
#[cfg(feature = "receive")]
pub(crate) async fn remove_partial_markers(
&self,
commits: Vec<Checksum>,
) -> Vec<(Checksum, Error)> {
let repo = self.clone();
ostrya_rt::unblock(move || {
commits
.into_iter()
.filter_map(|commit| {
let path = partial_path(&commit);
match rustix::fs::unlinkat(repo.repo_fd(), path.as_str(), AtFlags::empty()) {
Ok(()) | Err(rustix::io::Errno::NOENT) => None,
Err(e) => Some((commit, Error::from(e))),
}
})
.collect()
})
.await
}
async fn clear_markers_for_absent_commits(&self, marked: &[Checksum]) {
for commit in marked {
if matches!(self.has_object(ObjectType::Commit, commit).await, Ok(false)) {
let _ = self.remove_partial_marker(commit).await;
}
}
}
}
pub(crate) fn partial_path(commit: &Checksum) -> String {
format!("state/{}.commitpartial", commit.to_hex())
}
fn refspec(remote: Option<&str>, ref_name: &str) -> String {
match remote {
Some(remote) => format!("{remote}:{ref_name}"),
None => ref_name.to_owned(),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RefPlace<'a> {
Heads,
Remote(&'a str),
Collection(&'a str),
}
impl<'a> RefPlace<'a> {
pub(crate) fn of_remote(remote: Option<&'a str>) -> RefPlace<'a> {
match remote {
Some(remote) => RefPlace::Remote(remote),
None => RefPlace::Heads,
}
}
pub(crate) fn relpath(self, name: &str) -> Result<String> {
match self {
RefPlace::Heads => refspec_to_relpath(name),
RefPlace::Remote(remote) => refspec_to_relpath(&refspec(Some(remote), name)),
RefPlace::Collection(id) => collection_ref_to_relpath(&CollectionRef::new(id, name)),
}
}
pub(crate) fn queue(self, txn: &Transaction, name: &str, tip: &Checksum) {
match self {
RefPlace::Heads => txn.set_ref(name, Some(tip)),
RefPlace::Remote(remote) => txn.set_ref(&refspec(Some(remote), name), Some(tip)),
RefPlace::Collection(id) => {
txn.set_collection_ref(&CollectionRef::new(id, name), Some(tip));
}
}
}
}
async fn resolve_targets(
src: &Repo,
opts: &PullOptions,
collection_relpaths: Option<Vec<String>>,
) -> Result<Vec<(String, Checksum)>> {
if opts.refs.is_empty() {
return src.list_refs(None).await;
}
let mut out = Vec::with_capacity(opts.refs.len());
match collection_relpaths {
Some(relpaths) => {
for (name, relpath) in opts.refs.iter().zip(relpaths) {
let checksum = match src.resolve_relpath_tip(relpath.clone()).await {
Err(Error::Io(e))
if matches!(
e.kind(),
std::io::ErrorKind::IsADirectory | std::io::ErrorKind::NotADirectory
) =>
{
None
}
other => other?,
};
out.push((name.clone(), checksum.ok_or(Error::RefNotFound(relpath))?));
}
}
None => {
for name in &opts.refs {
let checksum = src
.resolve_rev(name, false)
.await?
.ok_or_else(|| Error::RefNotFound(name.clone()))?;
out.push((name.clone(), checksum));
}
}
}
Ok(out)
}
async fn collect_chain(
src: &Repo,
tip: Checksum,
tip_commit: (Vec<u8>, Commit),
depth: i32,
out: &mut Vec<ChainCommit>,
seen: &mut HashMap<Checksum, i32>,
mut check: Option<&mut ChainCheck<'_>>,
) -> Result<()> {
let mut current = Some((tip, tip_commit));
let mut remaining = depth;
while let Some((checksum, (bytes, commit))) = current {
if let Some(&prev) = seen.get(&checksum)
&& reaches_at_least(prev, remaining)
{
return Ok(());
}
if seen.insert(checksum, remaining).is_none() {
out.push(ChainCommit {
checksum,
root_dirtree: commit.root_dirtree,
root_dirmeta: commit.root_dirmeta,
held: false,
image_key: recorded_digest(&commit).ok().flatten(),
});
if let Some(check) = check.as_deref_mut() {
check.check(&checksum, &bytes).await;
}
}
drop(bytes);
if remaining == 0 {
return Ok(());
}
let Some(parent) = commit.parent else {
return Ok(());
};
current = try_load_commit(src, &parent)
.await?
.map(|parent_commit| (parent, parent_commit));
if remaining > 0 {
remaining -= 1;
}
}
Ok(())
}
struct ChainCommit {
checksum: Checksum,
root_dirtree: Checksum,
root_dirmeta: Checksum,
held: bool,
image_key: Option<[u8; 32]>,
}
struct ChainCheck<'a> {
repo: &'a Repo,
sources: &'a [&'a Repo],
verification: &'a verify::Verification,
plan: &'a delta::DeltaPlan,
failed: Option<Error>,
}
impl ChainCheck<'_> {
async fn check(&mut self, commit: &Checksum, bytes: &[u8]) {
if self.failed.is_none()
&& let Err(err) = self.check_one(commit, bytes).await
{
self.failed = Some(err);
}
}
async fn check_one(&self, commit: &Checksum, bytes: &[u8]) -> Result<()> {
if self.plan.checked(commit) {
return Ok(());
}
let sources: Vec<Repo> = self.sources.iter().map(|src| (*src).clone()).collect();
check_local_commit_signatures(self.repo, self.verification, sources, commit, bytes)
.await
.map(drop)
}
}
async fn check_commit_signatures(
repo: &Repo,
verification: &verify::Verification,
commit: &Checksum,
bytes: &[u8],
detached: Option<Vec<u8>>,
) -> Result<Option<Vec<u8>>> {
if !verification.checks_commits() {
return Ok(detached);
}
let (dict, detached) = match detached {
Some(detached) => {
let (dict, detached) = parse_detached(detached).await;
(dict?, Some(detached))
}
None => match repo.load_object_bytes(ObjectType::CommitMeta, commit).await {
Ok(held) => (parse_detached(held).await.0?, None),
Err(Error::ObjectNotFound { .. }) => (None, None),
Err(e) => return Err(e),
},
};
verification
.check_commit(commit, bytes, dict.as_ref())
.await?;
Ok(detached)
}
async fn check_local_commit_signatures(
repo: &Repo,
verification: &verify::Verification,
sources: Vec<Repo>,
commit: &Checksum,
bytes: &[u8],
) -> Result<Option<(usize, u64)>> {
let repo = repo.clone();
let key = *commit;
let (read, dict) = ostrya_rt::unblock(move || -> Result<_> {
if let Some((at, held)) = detached_bytes_from_blocking(&sources, &key)? {
let dict = crate::summary::parse_signature_dict(&held)?;
return Ok((Some((at, held.len() as u64)), dict));
}
match repo.load_object_bytes_blocking(ObjectType::CommitMeta, &key) {
Ok(held) => Ok((None, crate::summary::parse_signature_dict(&held)?)),
Err(Error::ObjectNotFound { .. }) => Ok((None, None)),
Err(e) => Err(e),
}
})
.await?;
verification
.check_commit(commit, bytes, dict.as_ref())
.await?;
Ok(read)
}
enum CheckedMeta {
Source(Vec<u8>),
Filtered(Option<Vec<u8>>),
}
impl CheckedMeta {
async fn filtered(
self,
filter: &DetachedMetadataFilter,
commit: &Checksum,
) -> Result<Option<Vec<u8>>> {
match self {
CheckedMeta::Source(bytes) => filter.apply_on_pool(commit, bytes).await,
CheckedMeta::Filtered(kept) => Ok(kept),
}
}
}
async fn check_commit_signatures_filtered(
repo: &Repo,
verification: &verify::Verification,
filter: &DetachedMetadataFilter,
commit: &Checksum,
bytes: &[u8],
detached: Option<Vec<u8>>,
) -> Result<Option<CheckedMeta>> {
match detached {
Some(detached) if verification.checks_commits() && filter.0.is_some() => {
let (dict, detached) = parse_detached(detached).await;
let dict = dict?;
verification
.check_commit(commit, bytes, dict.as_ref())
.await?;
let Some(dict) = dict else {
return Ok(Some(CheckedMeta::Filtered(Some(detached))));
};
let filter = filter.clone();
let commit = *commit;
let kept =
ostrya_rt::unblock(move || filter.apply_parsed(&commit, detached, dict)).await?;
Ok(Some(CheckedMeta::Filtered(kept)))
}
detached => Ok(
check_commit_signatures(repo, verification, commit, bytes, detached)
.await?
.map(CheckedMeta::Source),
),
}
}
async fn parse_detached(bytes: Vec<u8>) -> (Result<Option<Value>>, Vec<u8>) {
ostrya_rt::unblock(move || {
let dict = crate::summary::parse_signature_dict(&bytes);
(dict, bytes)
})
.await
}
#[derive(Default)]
struct PlanState {
seen: HashSet<ObjectName>,
}
impl PlanState {
fn meet(&mut self, name: ObjectName, out: &mut Vec<(ObjectName, bool)>) {
if self.seen.insert(name) {
out.push((name, false));
}
}
}
async fn plan_commit(
txn: &Transaction,
sources: &[&Repo],
commit: &ChainCommit,
flags: PullFlags,
state: &mut PlanState,
) -> Result<Vec<ObjectName>> {
if commit.held {
return Ok(Vec::new());
}
let commit_name = ObjectName::new(commit.checksum, ObjectType::Commit);
if flags.contains(PullFlags::COMMIT_ONLY) {
return Ok(vec![commit_name]);
}
let mut names: Vec<ObjectName> = Vec::new();
let mut stack: Vec<(Checksum, bool)> = Vec::new();
let mut met: Vec<(ObjectName, bool)> = Vec::new();
state.meet(
ObjectName::new(commit.root_dirmeta, ObjectType::DirMeta),
&mut met,
);
state.meet(
ObjectName::new(commit.root_dirtree, ObjectType::DirTree),
&mut met,
);
plan_absent(txn, met, &mut names, &mut stack).await?;
while let Some((checksum, here)) = stack.pop() {
let dirtree = if here {
txn.load_dirtree_staged_first(&checksum).await?
} else {
match load_dirtree_from(sources, &checksum).await? {
Some(dirtree) => dirtree,
None => continue,
}
};
let mut met: Vec<(ObjectName, bool)> = Vec::new();
for (_, file) in dirtree.files {
state.meet(ObjectName::new(file, ObjectType::File), &mut met);
}
for (_, subtree, submeta) in dirtree.dirs {
state.meet(ObjectName::new(submeta, ObjectType::DirMeta), &mut met);
state.meet(ObjectName::new(subtree, ObjectType::DirTree), &mut met);
}
plan_absent(txn, met, &mut names, &mut stack).await?;
}
names.sort_by_key(|name| (name.ty.as_u32(), name.checksum));
names.push(commit_name);
Ok(names)
}
async fn plan_absent(
txn: &Transaction,
mut met: Vec<(ObjectName, bool)>,
names: &mut Vec<ObjectName>,
stack: &mut Vec<(Checksum, bool)>,
) -> Result<()> {
let mut unstaged = false;
for (name, here) in &mut met {
*here = txn.is_staged(&name.checksum, name.ty);
unstaged |= !*here;
}
if unstaged {
let repo = txn.repo().clone();
met = ostrya_rt::unblock(move || -> Result<Vec<(ObjectName, bool)>> {
for (name, here) in &mut met {
if !*here {
*here = repo.has_object_blocking(name.ty, &name.checksum)?;
}
}
Ok(met)
})
.await?;
}
for (name, here) in met {
if name.ty == ObjectType::DirTree {
stack.push((name.checksum, here));
}
if !here {
names.push(name);
}
}
Ok(())
}
fn count_fetched(counters: &PullCounters, ty: ObjectType, size: u64) {
match ty {
ObjectType::File => counters.content_fetched(),
ObjectType::ComposefsImage => {}
_ => counters.metadata_fetched(),
}
counters.add_transferred(size);
}
async fn source_size(repo: &Repo, ty: ObjectType, checksum: &Checksum) -> Result<Option<u64>> {
match repo.loose_object_size(ty, checksum).await {
Ok(size) => Ok(Some(size)),
Err(Error::ObjectNotFound { .. }) => Ok(None),
Err(e) => Err(e),
}
}
async fn load_commit(repo: &Repo, checksum: &Checksum) -> Result<(Vec<u8>, Commit)> {
let repo = repo.clone();
let checksum = *checksum;
ostrya_rt::unblock(move || {
let bytes = repo.load_object_bytes_blocking(ObjectType::Commit, &checksum)?;
let commit = Commit::parse(&bytes)?;
Ok((bytes, commit))
})
.await
}
async fn try_load_commit(repo: &Repo, checksum: &Checksum) -> Result<Option<(Vec<u8>, Commit)>> {
match load_commit(repo, checksum).await {
Ok(loaded) => Ok(Some(loaded)),
Err(Error::ObjectNotFound { .. }) => Ok(None),
Err(e) => Err(e),
}
}
fn detached_bytes_from_blocking(
sources: &[Repo],
commit: &Checksum,
) -> Result<Option<(usize, Vec<u8>)>> {
for (at, src) in sources.iter().enumerate() {
match src.load_object_bytes_blocking(ObjectType::CommitMeta, commit) {
Ok(bytes) => return Ok(Some((at, bytes))),
Err(Error::ObjectNotFound { .. }) => continue,
Err(e) => return Err(e),
}
}
Ok(None)
}
async fn load_dirtree_from(sources: &[&Repo], checksum: &Checksum) -> Result<Option<DirTree>> {
for src in sources {
match src.load_dirtree(checksum).await {
Ok(dirtree) => return Ok(Some(dirtree)),
Err(Error::ObjectNotFound { .. }) => continue,
Err(e) => return Err(e),
}
}
Ok(None)
}
fn check_local_collection(opts: &PullOptions) -> Result<Option<Vec<String>>> {
let Some(id) = &opts.collection_id else {
return Ok(None);
};
if !opts.no_ref_writes {
return Err(Error::Unsupported(
"a local pull with a collection id needs no_ref_writes".into(),
));
}
if opts.refs.is_empty() {
return Err(Error::Unsupported(
"a local pull with a collection id needs at least one ref name".into(),
));
}
opts.refs
.iter()
.map(|name| {
if name.contains(':') {
return Err(Error::InvalidRefspec(format!("{id}:{name}")));
}
collection_ref_to_relpath(&CollectionRef::new(id.as_str(), name.as_str()))
})
.collect::<Result<Vec<_>>>()
.map(Some)
}
fn refuse_remote_collection(opts: &PullOptions) -> Result<()> {
if opts.collection_id.is_some() {
return Err(Error::Unsupported(
"only a local pull takes a collection id".into(),
));
}
Ok(())
}
fn check_remote_option(opts: &PullOptions) -> Result<()> {
match opts.remote.as_deref() {
Some(name) if !crate::config::valid_remote_name(name) => {
Err(Error::InvalidInput(format!("invalid remote name: {name}")))
}
_ => Ok(()),
}
}
fn check_depth(depth: i32) -> Result<()> {
if depth < -1 {
return Err(Error::InvalidInput(format!("depth {depth} is below -1")));
}
Ok(())
}
fn check_static_deltas(opts: &PullOptions) -> Result<()> {
if opts.static_deltas.is_none() {
return Ok(());
}
if opts.disable_static_deltas {
return Err(Error::InvalidInput(
"a pull with static_deltas takes no disable_static_deltas option".into(),
));
}
if !opts.subpaths.is_empty() {
return Err(Error::InvalidInput(
"a pull with static_deltas takes no subpath".into(),
));
}
Ok(())
}
async fn take_static_deltas(opts: &mut PullOptions) -> Result<Option<chain::Edges>> {
let Some(list) = opts.static_deltas.take() else {
return Ok(None);
};
ostrya_rt::unblock(move || chain::Edges::new(list))
.await
.map(Some)
}
fn check_ref_binding(checksum: &Checksum, commit: &Commit, ref_name: &str) -> Result<()> {
if commit.metadata_value("ostree.ref-binding").is_none() {
return Ok(());
}
let bindings = commit.ref_bindings();
if bindings.contains(&ref_name) {
return Ok(());
}
let listed = if bindings.is_empty() {
"no refs".to_owned()
} else {
bindings.join(", ")
};
Err(Error::Pull(format!(
"commit {checksum}: no requested ref '{ref_name}' in ref binding metadata ({listed})"
)))
}
#[derive(Debug, Clone, Copy)]
enum TimestampBase {
Off,
CurrentRef,
Rev {
commit: Checksum,
timestamp: u64,
},
}
impl TimestampBase {
async fn resolve(repo: &Repo, check: &TimestampCheck) -> Result<TimestampBase> {
Ok(match check {
TimestampCheck::Off => TimestampBase::Off,
TimestampCheck::CurrentRef => TimestampBase::CurrentRef,
TimestampCheck::Rev(commit) => TimestampBase::Rev {
commit: *commit,
timestamp: commit_timestamp(repo, commit).await?,
},
})
}
}
async fn commit_timestamp(repo: &Repo, commit: &Checksum) -> Result<u64> {
let repo = repo.clone();
let commit = *commit;
ostrya_rt::unblock(move || {
let bytes = repo.load_object_bytes_blocking(ObjectType::Commit, &commit)?;
Ok(Commit::parse_timestamp(&bytes)?)
})
.await
}
async fn current_ref_timestamp(repo: &Repo, relpath: String) -> Result<Option<(Checksum, u64)>> {
let repo = repo.clone();
ostrya_rt::unblock(move || {
let Some(current) = repo.resolve_relpath_tip_blocking(&relpath)? else {
return Ok(None);
};
let bytes = repo.load_object_bytes_blocking(ObjectType::Commit, ¤t)?;
Ok(Some((current, Commit::parse_timestamp(&bytes)?)))
})
.await
}
#[derive(Clone, Copy)]
struct TipChecks<'a> {
bindings: bool,
timestamp: TimestampBase,
place: RefPlace<'a>,
collection: Option<&'a str>,
listed: Option<&'a HashMap<String, u64>>,
}
impl<'a> TipChecks<'a> {
fn new(flags: PullFlags, timestamp: TimestampBase, place: RefPlace<'a>) -> TipChecks<'a> {
TipChecks {
bindings: !flags.contains(PullFlags::DISABLE_VERIFY_BINDINGS),
timestamp,
place,
collection: None,
listed: None,
}
}
}
async fn check_tip_refs(
repo: &Repo,
checks: TipChecks<'_>,
tip: &Checksum,
commit: &Commit,
refs: &[&str],
) -> Result<()> {
for ref_name in refs {
if checks.bindings {
check_ref_binding(tip, commit, ref_name)?;
}
if let Some(id) = checks.collection {
check_collection_binding(tip, commit, id)?;
}
if let Some(listed) = checks.listed.and_then(|listed| listed.get(*ref_name)) {
check_listed_timestamp(tip, commit, ref_name, *listed)?;
}
check_timestamp(repo, checks.timestamp, checks.place, ref_name, tip, commit).await?;
}
Ok(())
}
fn check_collection_binding(checksum: &Checksum, commit: &Commit, id: &str) -> Result<()> {
match commit.collection_binding() {
Some(bound) if bound == id => Ok(()),
Some(bound) => Err(Error::Pull(format!(
"commit {checksum}: collection binding '{bound}' is not the requested collection \
'{id}'"
))),
None => Err(Error::Pull(format!(
"commit {checksum}: no collection binding metadata for the requested collection \
'{id}'"
))),
}
}
fn check_listed_timestamp(
checksum: &Checksum,
commit: &Commit,
ref_name: &str,
listed: u64,
) -> Result<()> {
if commit.timestamp == listed {
return Ok(());
}
Err(Error::Pull(format!(
"commit {checksum} (timestamp {}) of ref '{ref_name}' does not have the timestamp \
that the remote listed ({listed})",
commit.timestamp
)))
}
async fn check_timestamp(
repo: &Repo,
check: TimestampBase,
place: RefPlace<'_>,
ref_name: &str,
tip: &Checksum,
fetched: &Commit,
) -> Result<()> {
let (against, timestamp) = match check {
TimestampBase::Off => return Ok(()),
TimestampBase::CurrentRef => {
let Some(current) = current_ref_timestamp(repo, place.relpath(ref_name)?).await? else {
return Ok(());
};
current
}
TimestampBase::Rev { commit, timestamp } => (commit, timestamp),
};
if fetched.timestamp >= timestamp {
return Ok(());
}
Err(Error::Pull(format!(
"commit {tip} (timestamp {}) is chronologically older than \
{against} (timestamp {})",
fetched.timestamp, timestamp
)))
}
async fn link_import(
txn: &Transaction,
src: &Repo,
name: ObjectName,
flags: PullFlags,
) -> Result<bool> {
txn.stage_import(
src.objects_fd(),
name.checksum,
name.ty,
src.mode(),
flags.contains(PullFlags::FORCE_COPY),
)
.await
}
fn payload_shared(src: RepoMode, dest: RepoMode) -> bool {
!src.is_archive() && !dest.is_archive()
}
fn symlink_shared(src: RepoMode, dest: RepoMode) -> bool {
matches!(
(src, dest),
(RepoMode::BareUser, RepoMode::BareUserShared)
| (RepoMode::BareUserShared, RepoMode::BareUser)
)
}
#[derive(Clone, Copy)]
pub(crate) struct ModeChecks {
bareuseronly_files: bool,
canonical: bool,
}
impl ModeChecks {
pub(crate) fn new(flags: PullFlags, dest: RepoMode) -> ModeChecks {
ModeChecks {
bareuseronly_files: flags.contains(PullFlags::BAREUSERONLY_FILES),
canonical: dest == RepoMode::BareUserOnly,
}
}
pub(crate) fn any(&self) -> bool {
self.bareuseronly_files || self.canonical
}
pub(crate) fn check(&self, checksum: &Checksum, meta: &FileMeta) -> Result<()> {
if self.bareuseronly_files {
check_bareuseronly(checksum, meta)?;
}
if self.canonical {
check_canonical(checksum, meta)?;
}
Ok(())
}
}
pub(crate) fn check_canonical(checksum: &Checksum, meta: &FileMeta) -> Result<()> {
let extra = if meta.is_symlink() {
0
} else {
meta.mode & !0o100755
};
if extra == 0 && meta.uid == 0 && meta.gid == 0 && meta.xattrs.is_empty() {
return Ok(());
}
Err(Error::Pull(format!(
"content object {checksum}: a bare-user-only repository stores neither \
ownership nor xattrs and reduces the mode to 0755, so this object -- uid \
{}, gid {}, mode 0{:o}, {} xattr(s) -- cannot be imported under its own name",
meta.uid,
meta.gid,
meta.mode,
meta.xattrs.len()
)))
}
fn check_bareuseronly(checksum: &Checksum, meta: &FileMeta) -> Result<()> {
if meta.is_symlink() {
return Ok(());
}
let extra = meta.mode & !0o100775;
if extra == 0 {
return Ok(());
}
Err(Error::Pull(format!(
"content object {checksum}: invalid mode 0{:o} with bits 0{:o}",
meta.mode, extra
)))
}
async fn verify_metadata(src: &Repo, name: ObjectName) -> Result<()> {
let bytes = src.load_object_bytes(name.ty, &name.checksum).await?;
let actual = Checksum::from_bytes(Sha256::digest(&bytes).into());
if actual != name.checksum {
return Err(Error::ChecksumMismatch {
expected: name.checksum,
actual,
});
}
Ok(())
}
async fn verify_content(
checksum: &Checksum,
file: &crate::file::FileObject,
buf: &mut Vec<u8>,
) -> Result<()> {
let mut hasher = ContentHasher::new(&file.header())?;
let mut reader = file.reader().await?;
if buf.len() < READ_CHUNK {
buf.resize(READ_CHUNK, 0);
}
loop {
match reader.read(buf).await? {
0 => break,
n => hasher.update(&buf[..n]),
}
}
let actual = hasher.finish();
if actual != *checksum {
return Err(Error::ChecksumMismatch {
expected: *checksum,
actual,
});
}
Ok(())
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<PullOptions>();
assert_send_sync::<TimestampCheck>();
};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn refspec_uses_the_remote_when_given() {
assert_eq!(refspec(None, "test/main"), "test/main");
assert_eq!(refspec(Some("origin"), "test/main"), "origin:test/main");
}
#[test]
fn a_ref_place_gives_the_path_of_its_refs() {
assert_eq!(
RefPlace::Heads.relpath("os/stable").unwrap(),
"refs/heads/os/stable"
);
assert_eq!(
RefPlace::Remote("origin").relpath("os/stable").unwrap(),
"refs/remotes/origin/os/stable"
);
assert_eq!(
RefPlace::Collection("org.example.Os")
.relpath("os/stable")
.unwrap(),
"refs/mirrors/org.example.Os/os/stable"
);
assert_eq!(RefPlace::of_remote(None), RefPlace::Heads);
assert_eq!(
RefPlace::of_remote(Some("origin")),
RefPlace::Remote("origin")
);
assert!(matches!(
RefPlace::Collection("org.example.Os").relpath("../x"),
Err(Error::InvalidRefspec(_))
));
}
fn commit_with(entries: &[(&str, &str, Value)]) -> Commit {
let metadata = Value::Array(
entries
.iter()
.map(|(key, ty, value)| {
Value::Tuple(vec![
Value::Str((*key).to_owned()),
Value::Variant(Box::new((
ostrya_core::Type::parse(ty).unwrap(),
value.clone(),
))),
])
})
.collect(),
);
Commit {
metadata,
parent: None,
related: Vec::new(),
subject: String::new(),
body: String::new(),
timestamp: 7,
root_dirtree: Checksum::from_bytes([1; 32]),
root_dirmeta: Checksum::from_bytes([2; 32]),
}
}
#[test]
fn the_collection_binding_must_state_the_collection() {
let tip = Checksum::from_bytes([3; 32]);
let id = "org.example.Os";
let bound = commit_with(&[("ostree.collection-binding", "s", Value::Str(id.into()))]);
check_collection_binding(&tip, &bound, id).unwrap();
let other = commit_with(&[(
"ostree.collection-binding",
"s",
Value::Str("org.example.Other".into()),
)]);
let err = check_collection_binding(&tip, &other, id).unwrap_err();
assert!(
matches!(&err, Error::Pull(m) if m.contains("org.example.Other") && m.contains(id)),
"{err:?}"
);
let none = commit_with(&[]);
assert!(matches!(
check_collection_binding(&tip, &none, id),
Err(Error::Pull(_))
));
assert!(check_listed_timestamp(&tip, &none, "os/stable", 7).is_ok());
assert!(matches!(
check_listed_timestamp(&tip, &none, "os/stable", 8),
Err(Error::Pull(_))
));
}
#[test]
fn flags_combine_and_test() {
let flags = PullFlags::UNTRUSTED | PullFlags::COMMIT_ONLY;
assert!(flags.contains(PullFlags::UNTRUSTED));
assert!(flags.contains(PullFlags::COMMIT_ONLY));
assert!(!flags.contains(PullFlags::FORCE_COPY));
assert!(PullFlags::empty().contains(PullFlags::NONE));
}
}