use std::collections::{HashMap, HashSet};
use std::io::Write;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};
use futures_lite::AsyncReadExt;
use ostrya_core::{
Checksum, Commit, ContentHasher, DirTree, ObjectName, ObjectType, Ref, RepoMode, Value,
};
use crate::config::repo;
use crate::error::{Error, Result, io_error};
use crate::file::FileKind;
use crate::refs::{ref_relpath, refspec_ref};
use crate::related::{self, RelatedRule};
use crate::repo::Repo;
use crate::repo_fs::{FsError, FsResultExt, Publish, RepoDir, RepoLayout, RootFile};
use crate::summary::AdvertisedDelta;
use crate::transaction::Transaction;
use crate::traverse::reaches_at_least;
use crate::verify::Payload;
use crate::write::FileMeta;
mod attachment;
mod chain;
mod collection;
mod delta;
pub(crate) mod drive;
#[doc(hidden)]
pub mod http;
mod source;
mod subpath;
mod verify;
pub(crate) use collection::collection_refs;
pub use collection::{
CollectionPullEvent, CollectionPullOptions, CollectionPullRef, CollectionPullStats,
};
use subpath::{Scope, Subpaths};
const READ_CHUNK: usize = 128 * 1024;
#[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>,
}
#[derive(Debug, Clone, Default)]
pub struct PullOptions {
pub refs: Vec<String>,
pub remote: Option<String>,
pub no_ref_writes: bool,
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 trust_group: Option<String>,
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, PartialEq, Eq)]
#[non_exhaustive]
pub struct RefChange {
pub name: Ref,
pub old: Option<Checksum>,
pub new: Checksum,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PullReport {
pub stats: PullStats,
pub changed_refs: Vec<RefChange>,
}
#[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, opts: PullOptions) -> Result<PullStats> {
self.pull_local_named(src, opts, false)
.await
.map(|report| report.stats)
}
pub async fn pull_local_with_report(
&self,
src: &Repo,
opts: PullOptions,
) -> Result<PullReport> {
self.pull_local_named(src, opts, true).await
}
async fn pull_local_named(
&self,
src: &Repo,
mut opts: PullOptions,
record: bool,
) -> Result<PullReport> {
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_remote_option(&opts)?;
check_static_deltas(&opts)?;
let related = RelatedRule::of(self.config())?;
let refs = std::mem::take(&mut opts.refs);
let operands = local_operands(&refs)?;
check_local_places(self, &opts, &operands)?;
check_commit_operand_deltas(
self,
&opts,
operands.iter().filter_map(|(_, operand)| match operand {
Operand::Commit(commit) => Some(*commit),
_ => None,
}),
)
.await?;
let edges = take_static_deltas(&mut opts).await?;
let trust = crate::verify::PullTrust::resolve(
self,
opts.remote.as_deref(),
&opts.verify,
opts.trust_group
.as_deref()
.map(crate::verify::trust::FieldGroup::new)
.as_mut(),
crate::verify::Defaults::Section,
false,
)
.await?;
self.pull_local_from(
src,
trust,
related,
opts,
None,
LocalWanted::Named(&operands),
edges,
started,
record,
)
.await
}
#[allow(clippy::too_many_arguments)]
async fn pull_local_from(
&self,
src: &Repo,
trust: crate::verify::PullTrust,
related: RelatedRule,
opts: PullOptions,
subpaths: Option<Subpaths>,
wanted: LocalWanted<'_>,
edges: Option<chain::Edges>,
started: Instant,
record: bool,
) -> Result<PullReport> {
let verification = verify::Verification::from_trust(trust).caching_crls(self);
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 commits_alone = match wanted {
LocalWanted::Named(operands) => {
!operands.is_empty()
&& !operands
.iter()
.any(|(_, operand)| matches!(operand, Operand::Name(_)))
}
LocalWanted::Config { .. } => commit_operands_alone(&opts.refs),
LocalWanted::Pinned(pinned) => pinned.commits_alone,
};
let by_config = matches!(wanted, LocalWanted::Config { .. });
let reads_refs = !matches!(wanted, LocalWanted::Pinned(_));
let mirror = by_config && opts.flags.contains(PullFlags::MIRROR);
let copies_summary = mirror && opts.refs.is_empty() && !opts.no_ref_writes;
let needs_summary = fetching && edges.is_none() && !commits_alone;
let probed = match wanted {
LocalWanted::Pinned(pinned) => {
if let Some(dict) = &pinned.summary_dict {
verification.keep_summary_dict(Arc::clone(dict));
}
pinned
.summary
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
}
_ => None,
};
let (summary, signature) = if commits_alone {
(None, None)
} else if probed.is_some() {
(probed, None)
} else {
read_checked_local_summary(
src,
&verification,
needs_summary || reads_refs,
copies_summary,
)
.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 (parsed, picked, mut advert, summary) =
match summary.filter(|_| needs_summary || reads_refs) {
Some(bytes) if reads_refs => {
let pick = match wanted {
LocalWanted::Config {
remote,
commit_collection,
} => http::SummaryPick::of(
self,
http::Wanted::Config {
remote,
commit_collection,
},
&opts,
),
_ => None,
};
let (parsed, bytes) = ostrya_rt::unblock(move || {
let parsed = crate::summary::Summary::parse(&bytes).map(|summary| {
let picked = pick.map(|pick| pick.targets(&summary));
(http::IndexedSummary::new(summary), picked)
});
(parsed, copies_summary.then(|| Arc::unwrap_or_clone(bytes)))
})
.await;
let (parsed, picked) = parsed?;
(Some(parsed), picked, None, bytes)
}
Some(bytes) => {
let advert = ostrya_rt::unblock(move || {
crate::summary::Summary::parse(&bytes).map(delta::DeltaAdvert::from_summary)
})
.await?;
(None, None, Some(advert), None)
}
None => (None, None, None, None),
};
let by_name = fetching && edges.is_none() && commits_alone;
let place = match wanted {
LocalWanted::Pinned(pinned) => pinned.place,
_ => RefPlace::Operands {
remote: opts.remote.as_deref().filter(|_| !mirror),
own: self.config().collection_id(),
},
};
let ref_files = (!verification.checks_summary()).then_some(http::RefFiles::Local(src));
let resolved;
let mut by_checksum;
let (targets, pinned) = match wanted {
LocalWanted::Named(operands) => {
let read = resolve_targets(src, operands, parsed.as_ref(), ref_files).await;
(resolved, by_checksum) = match read {
Ok(read) => read,
Err(err) => return Err(http::drop_unblocked(parsed, err).await),
};
(resolved.as_slice(), None)
}
LocalWanted::Config {
remote,
commit_collection,
} => {
let read = self
.remote_targets(
http::Wanted::Config {
remote,
commit_collection,
},
&opts,
place,
parsed.as_ref(),
picked,
src.config().collection_id(),
ref_files,
)
.await;
(resolved, by_checksum) = match read {
Ok(read) => read,
Err(err) => return Err(http::drop_unblocked(parsed, err).await),
};
(resolved.as_slice(), None)
}
LocalWanted::Pinned(pinned) => {
by_checksum = ChecksumTargets {
bare: pinned.bare.clone(),
..ChecksumTargets::default()
};
(pinned.targets.as_slice(), Some(pinned))
}
};
by_checksum.all = commits_alone;
if let Some(parsed) = parsed {
advert = ostrya_rt::unblock(move || {
needs_summary.then(|| delta::DeltaAdvert::from_summary(parsed.into_summary()))
})
.await;
}
let advert = match advert {
Some(advert) => Some(advert),
None if by_name
&& matches!(
src.config().file_value::<repo::IndexedDeltas>(),
Ok(Some(true))
) =>
{
Some(delta::DeltaAdvert::index_alone())
}
None => None,
};
let flags = opts.flags;
let collection = pinned.map(|pinned| (pinned.collection, pinned.allow_unbound));
let timestamp = if pinned.is_some() || (by_config && !targets.is_empty()) {
TimestampBase::resolve(self, &opts.timestamp_check).await?
} else {
TimestampBase::Off
};
let tip_checks = TipChecks {
collection: collection.map(|(id, _)| id),
allow_unbound: collection.is_some_and(|(_, allow_unbound)| allow_unbound),
operand_collections: pinned.is_none() && !opts.no_ref_writes,
listed: pinned.map(|pinned| &pinned.listed),
by_checksum: Some(&by_checksum),
..TipChecks::new(flags, timestamp, place)
};
let counters = PullCounters::new(None);
let deltas = if advert.is_some() || edges.is_some() || by_name {
check_source_commits(src, targets).await?;
delta::discover(
self,
&delta::DeltaSource::Local(src),
advert.as_ref(),
targets,
&opts,
tip_checks,
edges,
&verification,
related,
&counters,
)
.await?
} else {
delta::DeltaPlan::default()
};
let mut deltas = deltas;
let edges = deltas.take_edges();
let mut done: HashSet<Checksum> = deltas.levels().iter().flatten().copied().collect();
let mut level_attachments = deltas.take_attachments();
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 follows = !flags.contains(PullFlags::COMMIT_ONLY) && subpaths.is_none();
let mut atts = follows.then(|| ChainAttachments {
inner: attachment::Attachments::new(!reads_deltas),
parents: HashMap::new(),
});
let mut appended: Vec<Checksum> = Vec::new();
let mut skipped: Vec<SkippedAttachment> = Vec::new();
let mut commits: Vec<ChainCommit> = Vec::new();
let mut seen: HashMap<Checksum, i32> = HashMap::new();
let mut tips: Vec<(Checksum, Vec<&str>)> = Vec::new();
let mut slots: HashMap<Checksum, usize> = HashMap::new();
for (ref_name, tip) in targets {
let slot = *slots.entry(*tip).or_insert_with(|| {
tips.push((*tip, Vec::new()));
tips.len() - 1
});
tips[slot].1.push(ref_name.as_str());
}
let untrusted = flags.contains(PullFlags::UNTRUSTED);
for (tip, refs) in &tips {
let loaded = load_commit(src, tip, untrusted).await?;
if !deltas.checked(tip) {
check_tip_refs(self, tip_checks, tip, &loaded.commit, refs).await?;
}
collect_chain(
src,
*tip,
loaded,
opts.depth,
untrusted,
&mut commits,
&mut seen,
check.as_mut(),
atts.as_mut(),
)
.await?;
}
if let Some(atts) = atts.as_mut() {
for commit in deltas.levels().iter().flatten() {
if let Some(entries) = level_attachments.remove(commit) {
atts.inner.record(*commit, entries);
}
}
(appended, skipped) = collect_attachments(
self,
&sources,
atts,
&mut done,
untrusted,
&mut commits,
&mut seen,
)
.await?;
}
if let Some(ChainCheck {
failed: Some(err), ..
}) = check
{
return Err(err);
}
let mut attachment_deltas = match atts.take() {
Some(atts) if reads_deltas && !appended.is_empty() => {
let checked: HashMap<Checksum, bool> =
appended.iter().map(|checksum| (*checksum, false)).collect();
let named = attachment::pair_targets(
targets,
opts.depth,
&atts.parents,
atts.inner.naming(),
&attachment::Level::First,
appended,
);
drop(atts);
let (lookups, known) =
attachment::lookups(self, targets, place, named, checked).await?;
delta::discover_attachments(
self,
&delta::DeltaSource::Local(src),
advert.as_ref(),
edges.as_ref(),
lookups,
&known,
&opts,
&counters,
)
.await?
}
_ => delta::AttachmentDeltas::default(),
};
drop(advert);
drop(edges);
let mut txn = self.transaction().await?;
let level_commits: Vec<Checksum> = deltas.levels().iter().flatten().copied().collect();
let checks: Vec<Checksum> = level_commits
.iter()
.copied()
.chain(skipped.iter().map(|skip| skip.checksum))
.collect();
let mut states = chain::check_complete(self, &checks).await?;
let skipped_states = states.split_off(level_commits.len());
if let Some((skip, _)) = skipped
.iter()
.zip(skipped_states)
.find(|(_, (_, complete))| !complete)
{
return Err(skip.no_longer_complete());
}
let mut held_levels: HashSet<Checksum> = HashSet::new();
let mut level_marks = Vec::new();
for (commit, held) in states {
if held {
held_levels.insert(commit);
} else {
level_marks.push(commit);
}
}
apply_durability(&mut txn, &opts);
let marker_fsync = txn.fsync_flags().0;
let mut marked: Vec<Checksum> = Vec::new();
let published = async {
marked.extend_from_slice(&level_marks);
self.create_partial_markers(level_marks, &[], marker_fsync)
.await?;
let walked: Vec<Checksum> = commits
.iter()
.map(|commit| commit.checksum)
.filter(|checksum| !done.contains(checksum))
.collect();
let states = chain::check_complete(self, &walked).await?;
let walked = commits
.iter_mut()
.filter(|commit| !done.contains(&commit.checksum));
let mut to_mark = Vec::new();
for (commit, (_, held)) in walked.zip(states) {
commit.held = held;
if !held {
to_mark.push(commit.checksum);
}
}
marked.extend_from_slice(&to_mark);
self.create_partial_markers(to_mark, &[], marker_fsync)
.await?;
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::new(subpaths);
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,
attachment: false,
detached: deltas.checked_detached(commit),
});
}
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,
chain_commit.detached,
related,
None,
)
.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?;
}
for chain_commit in &commits {
if attachment_deltas.is_empty() {
break;
}
let attachment = &chain_commit.checksum;
let Some(job) = attachment_deltas
.take_job(self, &delta_source, attachment)
.await?
else {
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(attachment), &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?;
if !(chain_commit.attachment && chain_commit.held) {
self.import_detached_metadata(
&txn,
&sources,
commit,
chain_commit.detached,
related,
count,
)
.await?;
}
}
if !opts.no_ref_writes {
for (ref_name, tip) in targets {
if !tip_checks.is_bare(ref_name, tip) {
place.queue(&txn, ref_name, tip);
}
}
}
txn.commit_reporting(record).await
}
.await;
let (stats, changed_refs) = match published {
Ok(published) => published,
Err(e) => {
self.clear_markers_for_absent_commits(&marked, marker_fsync)
.await;
return Err(e);
}
};
if completes_marked(&opts) {
self.clear_markers(std::mem::take(&mut marked), marker_fsync)
.await?;
}
if let Some(bytes) = summary {
self.write_mirror_summary(bytes, signature, &opts).await?;
}
Ok(PullReport {
stats: 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(),
},
changed_refs,
})
}
async fn write_mirror_summary(
&self,
summary: Vec<u8>,
signature: Option<Vec<u8>>,
opts: &PullOptions,
) -> Result<()> {
let fsync = self.config().get::<repo::Fsync>()? && !opts.disable_fsync;
self.write_locked(move |repo| {
let root = repo.root_dir();
let temp = root.stage_root_file(&RootFile::Summary, &summary, fsync)?;
temp.publish(root, RootFile::Summary.name(), Publish::Replace, false)?;
if let Some(sig) = signature {
let temp = root.stage_root_file(&RootFile::SummarySig, &sig, fsync)?;
temp.publish(root, RootFile::SummarySig.name(), Publish::Replace, false)?;
}
if fsync {
root.sync()?;
}
Ok(())
})
.await
}
#[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<()> {
let names = plan_commit(txn, sources, commit, flags, plan).await?;
#[cfg(test)]
import_seam::run(self.repo_fd());
for name in names {
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) = src.held_object_size(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) {
let bytes = src
.load_object_bytes(name.ty, &name.checksum)
.await
.map_err(|e| source_object_error(src, name, e))?;
#[cfg(test)]
import_seam::run(self.repo_fd());
txn.write_metadata_owned(name.ty, Some(&name.checksum), bytes)
.await?;
return Ok(());
}
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() {
let file = src
.load_file(&name.checksum)
.await
.map_err(|e| source_object_error(src, name, e))?;
checks.check(&name.checksum, &file.meta())?;
Some(file)
} else {
None
};
if same_mode && link_import(txn, src, name, flags).await? {
if untrusted {
verify_staged_content(txn, name, checks, verify_buf)
.await
.map_err(|e| source_object_error(src, name, e))?;
}
return Ok(());
}
let file = match loaded {
Some(file) => file,
None => src
.load_file(&name.checksum)
.await
.map_err(|e| source_object_error(src, name, e))?,
};
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_staged_content(txn, name, checks, verify_buf)
.await
.map_err(|e| source_object_error(src, name, e))?;
}
return Ok(());
}
txn.write_symlink(target, &meta, Some(&name.checksum))
.await?;
}
FileKind::Regular { size } => {
if payload_shared(src.mode(), self.mode()) {
txn.stage_clone_content(src, name.checksum, meta.regular_header(), *size)
.await?;
if untrusted {
verify_staged_content(txn, name, checks, verify_buf).await?;
}
return Ok(());
}
if src.mode().is_archive() && self.mode().is_archive() {
return import_filez(txn, src, name, &meta, verify_buf).await;
}
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,
checked: CheckedDetached,
rule: RelatedRule,
count: Option<&PullCounters>,
) -> Result<()> {
let owned: Vec<Repo> = sources.iter().map(|src| (*src).clone()).collect();
let key = *commit;
let read = ostrya_rt::unblock(move || -> Result<_> {
let held = detached_bytes_from_blocking(&owned, &key)?;
if !checked.matches(held.as_ref().map(|(_, bytes)| bytes.as_slice())) {
return Err(Error::Pull(format!(
"the .commitmeta of commit {key} changed after its signature check"
)));
}
let Some((at, bytes)) = held else {
return Ok(None);
};
let len = bytes.len() as u64;
Ok(Some((at, len, rule.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(())
}
pub(crate) async fn create_partial_markers(
&self,
commits: Vec<Checksum>,
content: &'static [u8],
fsync: bool,
) -> Result<()> {
if commits.is_empty() {
return Ok(());
}
let repo = self.clone();
ostrya_rt::unblock(move || {
let state = repo.root_dir().ensure_layout(RepoLayout::State, fsync)?;
for commit in &commits {
create_partial_marker(&state, commit, content, fsync)?;
}
Ok(())
})
.await
}
fn partial_marker_job(
&self,
commit: &Checksum,
fsync: bool,
) -> ostrya_rt::JoinHandle<Result<()>> {
let commit = *commit;
let repo = self.clone();
#[cfg(test)]
let gate =
crate::jobs::job_gate::key(self.repo_fd(), format!("marker {}", commit.to_hex()));
ostrya_rt::unblock_task(move || {
#[cfg(test)]
let _gate = crate::jobs::job_gate::pass(&gate, repo.repo_fd())?;
let state = repo.root_dir().ensure_layout(RepoLayout::State, fsync)?;
create_partial_marker(&state, &commit, &[], fsync)
})
}
pub(crate) async fn remove_partial_markers(
&self,
commits: Vec<Checksum>,
fsync: bool,
) -> Result<Vec<(Checksum, Error)>> {
if commits.is_empty() {
return Ok(Vec::new());
}
let repo = self.clone();
ostrya_rt::unblock(move || {
let Some(state) = repo.root_dir().open_layout(RepoLayout::State).optional()? else {
return Ok(Vec::new());
};
let mut removed = false;
let mut failed = Vec::new();
for commit in commits {
match state.remove_file(&partial_name(&commit), false) {
Ok(unlinked) => removed |= unlinked,
Err(e) => failed.push((commit, Error::from(e))),
}
}
if removed && fsync {
state.sync()?;
}
Ok(failed)
})
.await
}
async fn clear_markers(&self, marked: Vec<Checksum>, fsync: bool) -> Result<()> {
let failed = self.remove_partial_markers(marked, fsync).await?;
match failed.into_iter().next() {
Some((_, e)) => Err(e),
None => Ok(()),
}
}
async fn clear_markers_for_absent_commits(&self, marked: &[Checksum], fsync: bool) {
let mut absent = Vec::new();
for commit in marked {
if matches!(self.has_object(ObjectType::Commit, commit).await, Ok(false)) {
absent.push(*commit);
}
}
let _ = self.remove_partial_markers(absent, fsync).await;
#[cfg(test)]
crate::jobs::job_gate::release(self.repo_fd());
}
}
pub(crate) fn completes_marked(opts: &PullOptions) -> bool {
!opts.flags.contains(PullFlags::COMMIT_ONLY) && opts.subpaths.is_empty()
}
pub(crate) fn partial_path(commit: &Checksum) -> String {
format!("state/{}.commitpartial", commit.to_hex())
}
pub(crate) fn partial_name(commit: &Checksum) -> String {
format!("{}.commitpartial", commit.to_hex())
}
fn create_partial_marker(
state: &RepoDir,
commit: &Checksum,
content: &[u8],
fsync: bool,
) -> Result<()> {
match state.create_exclusive(&partial_name(commit), fsync) {
Ok(mut file) => file.write_all(content).map_err(Error::Io),
Err(FsError::Exists) => Ok(()),
Err(e) => Err(e.into()),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RefPlace<'a> {
Heads,
Collection(&'a str),
Operands {
remote: Option<&'a str>,
own: Option<&'a str>,
},
}
impl<'a> RefPlace<'a> {
pub(crate) fn of_collection(repo: &Repo, id: &'a str) -> RefPlace<'a> {
if repo.config().collection_id() == Some(id) {
RefPlace::Heads
} else {
RefPlace::Collection(id)
}
}
pub(crate) fn ref_path(self, name: &str) -> Result<String> {
ref_relpath(None, &self.named(name))
}
pub(crate) fn queue(self, txn: &Transaction, name: &str, tip: &Checksum) {
txn.set_ref(&self.named(name), Some(tip));
}
fn named(self, name: &str) -> Ref {
match self {
RefPlace::Heads => refspec_ref(name),
RefPlace::Collection(id) => Ref::collection(id, name),
RefPlace::Operands { remote, own } => match operand_collection(name) {
Some((id, name)) => Ref::collection(id, name).canonical(own),
None => match remote {
Some(remote) => Ref::remote(remote, name),
None => refspec_ref(name),
},
},
}
}
}
async fn resolve_targets(
src: &Repo,
operands: &[(&str, Operand<'_>)],
summary: Option<&http::IndexedSummary>,
refs: Option<http::RefFiles<'_>>,
) -> Result<(Vec<(String, Checksum)>, ChecksumTargets)> {
let mut by_checksum = ChecksumTargets::default();
if operands.is_empty() {
let wanted = src
.list_head_names()
.await?
.into_iter()
.map(|name| (name.clone(), name, http::Resolved::Lookup(None)))
.collect();
let out = http::resolve_tips(wanted, summary, src.config().collection_id(), refs).await?;
return Ok((out, by_checksum));
}
let mut own_name = HashSet::new();
let mut wanted = Vec::with_capacity(operands.len());
for (name, operand) in operands {
let (target, resolved) = match *operand {
Operand::Commit(commit) => {
by_checksum.bare.insert(commit);
(commit.to_hex(), http::Resolved::Bare(commit))
}
Operand::NameAt { name: r, commit } => {
if operand_collection(r).is_none() {
by_checksum.named.insert(r.to_owned());
}
if Checksum::from_hex_lower(r) == Ok(commit) {
own_name.insert(commit);
}
(r.to_owned(), http::Resolved::At(commit))
}
Operand::Name(r) => {
let operand = operand_collection(r)
.map(|(id, ref_name)| (id.to_owned(), ref_name.to_owned()));
(r.to_owned(), http::Resolved::Lookup(operand))
}
};
wanted.push(((*name).to_owned(), target, resolved));
}
let mut out = http::resolve_tips(wanted, summary, src.config().collection_id(), refs).await?;
if !own_name.is_empty() {
by_checksum.bare.retain(|commit| !own_name.contains(commit));
let mut kept = HashSet::new();
out.retain(|(name, commit)| {
!own_name.contains(commit) || kept.insert((name.clone(), *commit))
});
}
Ok((out, by_checksum))
}
fn operand_collection(name: &str) -> Option<(&str, &str)> {
ostrya_core::split_collection(name)
}
#[allow(clippy::too_many_arguments)]
async fn collect_chain(
src: &Repo,
tip: Checksum,
tip_commit: LoadedCommit,
depth: i32,
untrusted: bool,
out: &mut Vec<ChainCommit>,
seen: &mut HashMap<Checksum, i32>,
mut check: Option<&mut ChainCheck<'_>>,
mut atts: Option<&mut ChainAttachments>,
) -> Result<()> {
let mut current = Some((tip, tip_commit));
let mut remaining = depth;
while let Some((
checksum,
LoadedCommit {
bytes,
commit,
attachments,
},
)) = current
{
if let Some(atts) = atts.as_deref_mut()
&& !atts.inner.keys_only()
{
atts.parents.insert(checksum, commit.parent);
}
if let Some(&prev) = seen.get(&checksum)
&& reaches_at_least(prev, remaining)
{
return Ok(());
}
if seen.insert(checksum, remaining).is_none() {
let attachments = attachments?;
let detached = match check.as_deref_mut() {
Some(check) => check.check(&checksum, &bytes).await,
None => CheckedDetached::Unchecked,
};
out.push(ChainCommit {
checksum,
root_dirtree: commit.root_dirtree,
root_dirmeta: commit.root_dirmeta,
held: false,
attachment: false,
detached,
});
if let Some(atts) = atts.as_deref_mut() {
atts.inner.record(checksum, attachments);
}
}
drop(bytes);
if remaining == 0 {
return Ok(());
}
let Some(parent) = commit.parent else {
return Ok(());
};
current = try_load_commit(src, &parent, untrusted)
.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,
attachment: bool,
detached: CheckedDetached,
}
#[derive(Clone, Copy)]
enum CheckedDetached {
Unchecked,
Absent,
Read {
at: usize,
len: u64,
digest: Checksum,
},
}
impl CheckedDetached {
fn matches(&self, held: Option<&[u8]>) -> bool {
match (self, held) {
(CheckedDetached::Unchecked, _) => true,
(CheckedDetached::Absent, held) => held.is_none(),
(CheckedDetached::Read { digest, .. }, Some(bytes)) => {
Checksum::sha256(bytes) == *digest
}
(CheckedDetached::Read { .. }, None) => false,
}
}
}
struct ChainAttachments {
inner: attachment::Attachments,
parents: HashMap<Checksum, Option<Checksum>>,
}
struct SkippedAttachment {
checksum: Checksum,
commit: Checksum,
name: String,
}
impl SkippedAttachment {
fn no_longer_complete(&self) -> Error {
Error::InvalidRelations {
commit: Some(self.commit),
field: related::RelationField::Attachments,
reason: related::attachment_reason(
&self.name,
&self.checksum,
related::NO_LONGER_COMPLETE_REASON,
),
}
}
}
async fn collect_attachments(
repo: &Repo,
sources: &[&Repo],
atts: &mut ChainAttachments,
made: &mut HashSet<Checksum>,
untrusted: bool,
out: &mut Vec<ChainCommit>,
seen: &mut HashMap<Checksum, i32>,
) -> Result<(Vec<Checksum>, Vec<SkippedAttachment>)> {
if atts
.inner
.order()
.iter()
.all(|attachment| seen.contains_key(attachment) || made.contains(attachment))
{
return Ok((Vec::new(), Vec::new()));
}
let holders: Vec<Repo> = sources
.iter()
.map(|src| (*src).clone())
.chain(std::iter::once(repo.clone()))
.collect();
let mut inner = std::mem::take(&mut atts.inner);
let walked = std::mem::take(seen);
let made_here = std::mem::take(made);
let (inner, walked, made_here, walk) = ostrya_rt::unblock(move || {
let walk = walk_attachments_blocking(&holders, &mut inner, &walked, &made_here, untrusted);
(inner, walked, made_here, walk)
})
.await;
atts.inner = inner;
*seen = walked;
*made = made_here;
let AttachmentWalk { loaded, skipped } = walk?;
let skipped = skipped
.into_iter()
.map(|checksum| {
let (commit, name) = atts
.inner
.named(&checksum)
.expect("a commit names each attachment of the walk");
SkippedAttachment {
checksum,
commit,
name: name.to_owned(),
}
})
.collect();
let mut appended = Vec::with_capacity(loaded.len());
for (checksum, attachment) in loaded {
seen.insert(checksum, 0);
appended.push(checksum);
out.push(ChainCommit {
checksum,
root_dirtree: attachment.root_dirtree,
root_dirmeta: attachment.root_dirmeta,
held: false,
attachment: true,
detached: CheckedDetached::Unchecked,
});
}
Ok((appended, skipped))
}
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: &Arc<Vec<u8>>) -> CheckedDetached {
if self.failed.is_some() {
return CheckedDetached::Unchecked;
}
match self.check_one(commit, bytes).await {
Ok(detached) => detached,
Err(err) => {
self.failed = Some(err);
CheckedDetached::Unchecked
}
}
}
async fn check_one(&self, commit: &Checksum, bytes: &Arc<Vec<u8>>) -> Result<CheckedDetached> {
if self.plan.checked(commit) {
return Ok(self.plan.checked_detached(commit));
}
let sources: Vec<Repo> = self.sources.iter().map(|src| (*src).clone()).collect();
check_local_commit_signatures(self.repo, self.verification, sources, commit, bytes.into())
.await
}
}
async fn check_commit_signatures(
repo: &Repo,
verification: &verify::Verification,
commit: &Checksum,
bytes: Payload<'_>,
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
.held_object_bytes(ObjectType::CommitMeta, commit)
.await?
{
Some(held) => (parse_detached(held).await.0?, None),
None => (None, None),
},
};
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: Payload<'_>,
) -> Result<CheckedDetached> {
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)?;
let read = CheckedDetached::Read {
at,
len: held.len() as u64,
digest: Checksum::sha256(&held),
};
return Ok((read, dict));
}
let dict = match repo.held_object_bytes_blocking(ObjectType::CommitMeta, &key)? {
Some(held) => crate::summary::parse_signature_dict(&held)?,
None => None,
};
Ok((CheckedDetached::Absent, dict))
})
.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, rule: RelatedRule, commit: &Checksum) -> Result<Option<Vec<u8>>> {
match self {
CheckedMeta::Source(bytes) => rule.apply_on_pool(commit, bytes).await,
CheckedMeta::Filtered(kept) => Ok(kept),
}
}
}
async fn check_commit_signatures_filtered(
repo: &Repo,
verification: &verify::Verification,
rule: RelatedRule,
commit: &Checksum,
bytes: Payload<'_>,
detached: Option<Vec<u8>>,
) -> Result<Option<CheckedMeta>> {
match detached {
Some(detached) if verification.checks_commits() && rule.drop_related => {
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 commit = *commit;
let kept =
ostrya_rt::unblock(move || rule.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
}
struct PlanState {
seen: HashSet<ObjectName>,
subpaths: Option<Subpaths>,
root: Scope,
partial: HashMap<Checksum, PartialTree>,
}
struct PartialTree {
scope: Scope,
walked: bool,
}
struct Met {
name: ObjectName,
held: bool,
again: bool,
}
impl PlanState {
fn new(subpaths: Option<Subpaths>) -> PlanState {
PlanState {
seen: HashSet::new(),
root: subpaths.as_ref().map(Subpaths::root).unwrap_or_default(),
subpaths,
partial: HashMap::new(),
}
}
fn meet(&mut self, name: ObjectName, scope: Scope, out: &mut Vec<Met>) {
if self.seen.insert(name) {
if name.ty == ObjectType::DirTree && scope != Scope::All {
self.partial.insert(
name.checksum,
PartialTree {
scope,
walked: false,
},
);
}
out.push(Met {
name,
held: false,
again: false,
});
return;
}
if name.ty != ObjectType::DirTree {
return;
}
let Some(tree) = self.partial.get_mut(&name.checksum) else {
return;
};
if tree.scope.covers(&scope) {
return;
}
tree.scope.widen(&scope);
if tree.walked {
tree.walked = false;
out.push(Met {
name,
held: false,
again: true,
});
}
}
fn meet_children(&mut self, checksum: &Checksum, dirtree: &DirTree, out: &mut Vec<Met>) {
if let Some(subpaths) = &self.subpaths {
let scope = match self.partial.get_mut(checksum) {
Some(tree) => {
tree.walked = true;
tree.scope.clone()
}
None => Scope::All,
};
if let Scope::Along(_) = scope {
for (name, scope) in subpaths.children(dirtree, &scope) {
self.meet(name, scope, out);
}
return;
}
}
for (_, file) in &dirtree.files {
self.meet(ObjectName::new(*file, ObjectType::File), Scope::All, out);
}
for (_, subtree, submeta) in &dirtree.dirs {
self.meet(
ObjectName::new(*submeta, ObjectType::DirMeta),
Scope::All,
out,
);
self.meet(
ObjectName::new(*subtree, ObjectType::DirTree),
Scope::All,
out,
);
}
}
}
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<Met> = Vec::new();
state.meet(
ObjectName::new(commit.root_dirmeta, ObjectType::DirMeta),
Scope::All,
&mut met,
);
let root = state.root.clone();
state.meet(
ObjectName::new(commit.root_dirtree, ObjectType::DirTree),
root,
&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, flags.contains(PullFlags::UNTRUSTED))
.await?
{
Some(dirtree) => dirtree,
None => continue,
}
};
let mut met: Vec<Met> = Vec::new();
state.meet_children(&checksum, &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<Met>,
names: &mut Vec<ObjectName>,
stack: &mut Vec<(Checksum, bool)>,
) -> Result<()> {
let mut unstaged = false;
for entry in &mut met {
entry.held = txn.is_staged(&entry.name.checksum, entry.name.ty);
unstaged |= !entry.held;
}
if unstaged {
let repo = txn.repo().clone();
met = ostrya_rt::unblock(move || -> Result<Vec<Met>> {
for entry in &mut met {
if !entry.held {
entry.held = repo.has_object_blocking(entry.name.ty, &entry.name.checksum)?;
}
}
Ok(met)
})
.await?;
}
for Met { name, held, again } in met {
if name.ty == ObjectType::DirTree {
stack.push((name.checksum, held));
}
if !held && !again {
names.push(name);
}
}
Ok(())
}
fn count_fetched(counters: &PullCounters, ty: ObjectType, size: u64) {
match ty {
ObjectType::File => counters.content_fetched(),
_ => counters.metadata_fetched(),
}
counters.add_transferred(size);
}
struct LoadedCommit {
bytes: Arc<Vec<u8>>,
commit: Commit,
attachments: Result<Vec<(String, Checksum)>>,
}
struct LoadedAttachment {
root_dirtree: Checksum,
root_dirmeta: Checksum,
}
fn parse_loaded(checksum: Checksum, bytes: Arc<Vec<u8>>) -> Result<LoadedCommit> {
let mut commit = Commit::parse(&bytes)?;
let related = std::mem::take(&mut commit.related);
Ok(LoadedCommit {
bytes,
commit,
attachments: related::checked_attachments(&checksum, related),
})
}
async fn load_commit(repo: &Repo, checksum: &Checksum, hash: bool) -> Result<LoadedCommit> {
let repo = repo.clone();
let checksum = *checksum;
ostrya_rt::unblock(move || {
let bytes = repo.load_object_bytes_blocking(ObjectType::Commit, &checksum)?;
if hash {
check_hash(&checksum, &bytes)?;
}
parse_loaded(checksum, Arc::new(bytes))
})
.await
}
async fn check_source_commits(src: &Repo, targets: &[(String, Checksum)]) -> Result<()> {
let mut seen = HashSet::new();
let commits: Vec<Checksum> = targets
.iter()
.map(|(_, commit)| *commit)
.filter(|commit| seen.insert(*commit))
.collect();
let src = src.clone();
ostrya_rt::unblock(move || {
for checksum in commits {
if !src.has_object_blocking(ObjectType::Commit, &checksum)? {
return Err(Error::ObjectNotFound {
checksum,
ty: ObjectType::Commit,
});
}
}
Ok(())
})
.await
}
async fn try_load_commit(
repo: &Repo,
checksum: &Checksum,
hash: bool,
) -> Result<Option<LoadedCommit>> {
match load_commit(repo, checksum, hash).await {
Ok(loaded) => Ok(Some(loaded)),
Err(Error::ObjectNotFound { .. }) => Ok(None),
Err(e) => Err(e),
}
}
#[derive(Default)]
struct AttachmentWalk {
loaded: Vec<(Checksum, LoadedAttachment)>,
skipped: Vec<Checksum>,
}
fn walk_attachments_blocking(
holders: &[Repo],
atts: &mut attachment::Attachments,
seen: &HashMap<Checksum, i32>,
made: &HashSet<Checksum>,
untrusted: bool,
) -> Result<AttachmentWalk> {
let (repo, sources) = holders
.split_last()
.expect("the holders end with this repository");
let mut walk = AttachmentWalk::default();
let mut next = 0;
while let Some(&checksum) = atts.order().get(next) {
next += 1;
if seen.contains_key(&checksum) || made.contains(&checksum) {
continue;
}
if delta::complete_here_blocking(repo, &checksum)? {
walk.skipped.push(checksum);
let Some(bytes) = repo.held_object_bytes_blocking(ObjectType::Commit, &checksum)?
else {
return Err(atts
.named_error(&checksum, related::NO_LONGER_COMPLETE_REASON)
.expect("a commit names each attachment of the walk"));
};
let entries = related::parse_attachments(&bytes)?;
atts.record(
checksum,
related::checked_entries(
related::RelationField::Attachments,
Some(checksum),
entries,
)?,
);
continue;
}
let error = |end: &str| {
atts.named_error(&checksum, end)
.expect("a commit names each attachment of the walk")
};
let mut bytes = None;
for (position, held) in holders.iter().enumerate() {
if let Some(read) = held.held_object_bytes_blocking(ObjectType::Commit, &checksum)? {
if position < sources.len() {
if held.commit_state_blocking(&checksum)? == crate::read::CommitState::Partial {
return Err(error(related::PARTIAL_REASON));
}
if untrusted {
check_hash(&checksum, &read)?;
}
}
bytes = Some(read);
break;
}
}
let Some(bytes) = bytes else {
return Err(error(related::UNHELD_REASON));
};
let LoadedCommit {
commit,
attachments,
..
} = parse_loaded(checksum, Arc::new(bytes))?;
atts.record(checksum, attachments?);
walk.loaded.push((
checksum,
LoadedAttachment {
root_dirtree: commit.root_dirtree,
root_dirmeta: commit.root_dirmeta,
},
));
}
Ok(walk)
}
fn detached_bytes_from_blocking(
sources: &[Repo],
commit: &Checksum,
) -> Result<Option<(usize, Vec<u8>)>> {
for (at, src) in sources.iter().enumerate() {
if let Some(bytes) = src.held_object_bytes_blocking(ObjectType::CommitMeta, commit)? {
return Ok(Some((at, bytes)));
}
}
Ok(None)
}
fn check_hash(expected: &Checksum, bytes: &[u8]) -> Result<()> {
let actual = Checksum::sha256(bytes);
if actual != *expected {
return Err(Error::ChecksumMismatch {
expected: *expected,
actual,
});
}
Ok(())
}
async fn load_dirtree_from(
sources: &[&Repo],
checksum: &Checksum,
untrusted: bool,
) -> Result<Option<DirTree>> {
for src in sources {
let loaded = if untrusted {
let src = (*src).clone();
let checksum = *checksum;
ostrya_rt::unblock(move || {
let bytes = src.load_object_bytes_blocking(ObjectType::DirTree, &checksum)?;
check_hash(&checksum, &bytes)?;
Ok(DirTree::parse(&bytes)?)
})
.await
} else {
src.load_dirtree(checksum).await
};
match loaded {
Ok(dirtree) => return Ok(Some(dirtree)),
Err(Error::ObjectNotFound { .. }) => continue,
Err(e) => return Err(e),
}
}
Ok(None)
}
struct Pinned<'a> {
targets: Vec<(String, Checksum)>,
listed: HashMap<String, (Checksum, u64)>,
bare: HashSet<Checksum>,
commits_alone: bool,
collection: &'a str,
allow_unbound: bool,
place: RefPlace<'a>,
summary: Mutex<Option<Arc<Vec<u8>>>>,
summary_dict: Option<Arc<Value>>,
}
enum LocalWanted<'a> {
Named(&'a [(&'a str, Operand<'a>)]),
Config {
remote: &'a str,
commit_collection: Option<&'a str>,
},
Pinned(&'a Pinned<'a>),
}
impl Repo {
pub(crate) async fn pull_local_pinned(
&self,
src: &Repo,
collection: &str,
targets: Vec<(String, Checksum)>,
listed: HashMap<String, u64>,
trust: crate::verify::PullTrust,
timestamp_check: TimestampCheck,
) -> Result<PullStats> {
let listed = targets
.iter()
.filter_map(|(name, commit)| Some((name.clone(), (*commit, *listed.get(name)?))))
.collect();
let pinned = Pinned {
targets,
listed,
bare: HashSet::new(),
commits_alone: false,
collection,
allow_unbound: false,
place: RefPlace::of_collection(self, collection),
summary: Mutex::new(None),
summary_dict: None,
};
let flags = if trust.checks_signatures() {
PullFlags::UNTRUSTED
} else {
PullFlags::default()
};
let opts = PullOptions {
disable_static_deltas: true,
flags,
timestamp_check,
..PullOptions::default()
};
self.pull_local_from(
src,
trust,
RelatedRule::of(self.config())?,
opts,
None,
LocalWanted::Pinned(&pinned),
None,
Instant::now(),
false,
)
.await
.map(|report| report.stats)
}
}
fn local_operands(refs: &[String]) -> Result<Vec<(&str, Operand<'_>)>> {
let mut seen = HashSet::new();
let mut out = Vec::with_capacity(refs.len());
for name in refs {
let operand = Operand::parse(name)?;
let valid = match operand {
Operand::Commit(_) => true,
Operand::NameAt { name: r, .. } => r.parse::<Ref>().is_ok(),
Operand::Name(r) => matches!(
r.parse::<Ref>(),
Ok(Ref::Local { .. } | Ref::Collection { .. })
),
};
if !valid {
return Err(Error::InvalidRefspec(name.clone()));
}
if seen.insert(name.as_str()) {
out.push((name.as_str(), operand));
}
}
Ok(out)
}
fn check_local_places(
repo: &Repo,
opts: &PullOptions,
operands: &[(&str, Operand<'_>)],
) -> Result<()> {
if opts.no_ref_writes {
return Ok(());
}
let place = RefPlace::Operands {
remote: opts.remote.as_deref(),
own: repo.config().collection_id(),
};
check_one_place(
place,
operands
.iter()
.filter_map(|(name, operand)| match *operand {
Operand::Commit(_) => None,
Operand::NameAt { name: r, .. } | Operand::Name(r) => Some((*name, r)),
}),
)
}
fn check_one_place<'a>(
place: RefPlace<'_>,
refs: impl Iterator<Item = (&'a str, &'a str)>,
) -> Result<()> {
let mut paths: HashMap<String, &str> = HashMap::new();
for (name, target) in refs {
let path = place.ref_path(target)?;
if let Some(first) = paths.get(path.as_str()) {
return Err(Error::Pull(format!(
"the refs {first} and {name} write one ref {path}"
)));
}
paths.insert(path, name);
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Operand<'a> {
Name(&'a str),
NameAt {
name: &'a str,
commit: Checksum,
},
Commit(Checksum),
}
impl<'a> Operand<'a> {
pub(crate) fn parse(text: &'a str) -> Result<Operand<'a>> {
match text.rfind('@').filter(|at| *at > 0) {
Some(at) => match Checksum::from_hex_lower(&text[at + 1..]) {
Ok(commit) => Ok(Operand::NameAt {
name: &text[..at],
commit,
}),
Err(_) => Err(Error::InvalidRefspec(text.to_owned())),
},
None => match Checksum::from_hex_lower(text) {
Ok(commit) => Ok(Operand::Commit(commit)),
Err(_) => Ok(Operand::Name(text)),
},
}
}
}
pub(crate) fn commit_operands_alone(refs: &[String]) -> bool {
!refs.is_empty()
&& !refs
.iter()
.any(|name| matches!(Operand::parse(name), Ok(Operand::Name(_))))
}
pub fn commit_operand(r: &Ref, commit: &Checksum) -> String {
format!("{r}@{commit}")
}
#[derive(Default)]
pub(crate) struct ChecksumTargets {
bare: HashSet<Checksum>,
named: HashSet<String>,
bare_collection: Option<String>,
all: bool,
}
impl ChecksumTargets {
pub(crate) fn is_bare(&self, name: &str, commit: &Checksum) -> bool {
self.bare.contains(commit)
&& Checksum::from_hex_lower(name).is_ok_and(|named| named == *commit)
}
}
fn check_remote_operands(opts: &PullOptions) -> Result<()> {
for name in &opts.refs {
let r = match Operand::parse(name)? {
Operand::Commit(_) => continue,
Operand::Name(r) | Operand::NameAt { name: r, .. } => r,
};
match r.parse::<Ref>() {
Ok(Ref::Local { .. } | Ref::Collection { .. }) => {}
_ => return Err(Error::InvalidRefspec(name.clone())),
}
}
Ok(())
}
async fn check_commit_operands(repo: &Repo, opts: &PullOptions) -> Result<()> {
let bare = || {
opts.refs
.iter()
.filter_map(|name| match Operand::parse(name) {
Ok(Operand::Commit(commit)) => Some(commit),
_ => None,
})
};
if opts.timestamp_check == TimestampCheck::CurrentRef
&& let Some(commit) = bare().next()
{
return Err(Error::InvalidInput(format!(
"the timestamp check against the current ref takes no commit named by its checksum \
with no ref: {commit}"
)));
}
check_commit_operand_deltas(repo, opts, bare()).await
}
async fn check_commit_operand_deltas(
repo: &Repo,
opts: &PullOptions,
bare: impl IntoIterator<Item = Checksum>,
) -> Result<()> {
if !opts.require_static_deltas
|| opts.disable_static_deltas
|| opts.flags.contains(PullFlags::COMMIT_ONLY)
{
return Ok(());
}
let mut seen = HashSet::new();
let commits: Vec<Checksum> = bare
.into_iter()
.filter(|commit| seen.insert(*commit))
.collect();
if let Some((commit, _)) = chain::check_complete(repo, &commits)
.await?
.into_iter()
.find(|(_, complete)| !complete)
{
return Err(Error::Pull(format!(
"Static deltas required, but a commit named by its checksum takes none: {commit}"
)));
}
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)
}
async fn read_checked_local_summary(
src: &Repo,
verification: &verify::Verification,
needed: bool,
keep_signature: bool,
) -> Result<(Option<Arc<Vec<u8>>>, Option<Vec<u8>>)> {
let checks_summary = verification.checks_summary();
let root = src.root_dir().clone();
let (summary, signature) = ostrya_rt::unblock(move || {
let summary = if checks_summary || needed {
crate::summary::read_root_file_blocking(&root, RootFile::Summary.name())?
} else {
None
};
let signature = if (checks_summary || keep_signature) && summary.is_some() {
crate::summary::read_root_file_blocking(&root, RootFile::SummarySig.name())?
} else {
None
};
Ok::<_, Error>((summary, signature))
})
.await?;
verification.check_summary_files(summary.is_some(), signature.is_some())?;
let summary = summary.map(Arc::new);
let signature = if checks_summary {
verification
.check_summary(summary.as_ref(), signature)
.await?
} else {
signature
};
Ok((summary, signature.filter(|_| keep_signature)))
}
pub(crate) 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>,
operand_collections: bool,
allow_unbound: bool,
listed: Option<&'a HashMap<String, (Checksum, u64)>>,
by_checksum: Option<&'a ChecksumTargets>,
}
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,
operand_collections: false,
allow_unbound: false,
listed: None,
by_checksum: None,
}
}
fn is_bare(&self, name: &str, commit: &Checksum) -> bool {
self.by_checksum
.is_some_and(|targets| targets.is_bare(name, commit))
}
}
async fn check_tip_refs(
repo: &Repo,
checks: TipChecks<'_>,
tip: &Checksum,
commit: &Commit,
refs: &[&str],
) -> Result<()> {
for ref_name in refs {
if let Some(targets) = checks
.by_checksum
.filter(|targets| targets.is_bare(ref_name, tip))
{
if let Some(id) = checks.collection.or(targets.bare_collection.as_deref()) {
check_collection_binding(tip, commit, id, checks.allow_unbound)?;
}
if matches!(checks.timestamp, TimestampBase::Rev { .. }) {
check_timestamp(repo, checks.timestamp, checks.place, ref_name, tip, commit)
.await?;
}
continue;
}
let operand = operand_collection(ref_name);
if checks.bindings {
let bound = operand.map_or(*ref_name, |(_, name)| name);
check_ref_binding(tip, commit, bound)?;
}
let operand_id = operand
.filter(|_| checks.operand_collections)
.map(|(id, _)| id);
if let Some(id) = checks.collection.or(operand_id) {
check_collection_binding(tip, commit, id, checks.allow_unbound)?;
}
if operand.is_none()
&& checks.operand_collections
&& checks
.by_checksum
.is_some_and(|targets| targets.named.contains(*ref_name))
&& let RefPlace::Operands { own, .. } = checks.place
{
check_own_collection_binding(tip, commit, own)?;
}
if let Some((_, listed)) = checks
.listed
.and_then(|listed| listed.get(*ref_name))
.filter(|(listed, _)| listed == tip)
{
check_listed_timestamp(tip, commit, ref_name, *listed)?;
}
check_timestamp(repo, checks.timestamp, checks.place, ref_name, tip, commit).await?;
}
Ok(())
}
pub(crate) fn check_collection_binding(
checksum: &Checksum,
commit: &Commit,
id: &str,
allow_unbound: bool,
) -> 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 => match commit.metadata_value("ostree.collection-binding") {
Some(_) => Err(Error::Pull(format!(
"commit {checksum}: collection binding metadata is not a string"
))),
None if allow_unbound => Ok(()),
None => Err(Error::Pull(format!(
"commit {checksum}: no collection binding metadata for the requested \
collection '{id}'"
))),
},
}
}
pub(crate) fn check_own_collection_binding(
checksum: &Checksum,
commit: &Commit,
own: Option<&str>,
) -> Result<()> {
match own {
Some(id) => check_collection_binding(checksum, commit, id, false),
None if commit.metadata_value("ostree.collection-binding").is_none() => Ok(()),
None => Err(Error::Pull(format!(
"commit {checksum}: collection binding metadata for a ref of a repository with no \
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.ref_path(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,
name.checksum,
name.ty,
flags.contains(PullFlags::FORCE_COPY),
)
.await
}
fn source_object_error(src: &Repo, name: ObjectName, err: Error) -> Error {
match err {
Error::Io(e) if e.raw_os_error().is_some() => io_error(
&src.path().join("objects").join(name.loose_path(src.mode())),
e,
),
other => other,
}
}
async fn import_filez(
txn: &Transaction,
src: &Repo,
name: ObjectName,
meta: &FileMeta,
buf: &mut Vec<u8>,
) -> Result<()> {
let path = name.loose_path(src.mode());
let repo = src.clone();
let opened = ostrya_rt::unblock(move || {
repo.objects()
.open_regular(&path)
.map_err(|e| e.into_object_error(&name.checksum, ObjectType::File))
})
.await?;
let (header, declared, framed, body) = http::read_archive_header(
ostrya_rt::FileReader::with_len_hint(opened.file, opened.stat.size),
)
.await?;
http::store_filez_payload(
txn,
&name.checksum,
&header,
meta,
declared,
&framed,
body,
buf,
)
.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_staged_content(
txn: &Transaction,
name: ObjectName,
checks: ModeChecks,
buf: &mut Vec<u8>,
) -> Result<()> {
#[cfg(test)]
import_seam::run(txn.repo().repo_fd());
let file = txn.load_file_staged_first(&name.checksum).await?;
if checks.any() {
checks.check(&name.checksum, &file.meta())?;
}
verify_content(&name.checksum, &file, buf).await
}
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)]
pub(crate) mod import_seam {
use std::os::fd::BorrowedFd;
use std::sync::{Mutex, PoisonError};
type Root = (u64, u64);
type Action = Box<dyn FnOnce() + Send>;
static ACTIONS: Mutex<Vec<(Root, Action)>> = Mutex::new(Vec::new());
pub(crate) fn arm(root: &std::path::Path, f: impl FnOnce() + Send + 'static) {
use std::os::unix::fs::MetadataExt;
let meta = std::fs::metadata(root).unwrap();
ACTIONS
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(((meta.dev(), meta.ino()), Box::new(f)));
}
pub(crate) fn run(repo_fd: BorrowedFd<'_>) {
let stat = rustix::fs::fstat(repo_fd).unwrap();
let root = (stat.st_dev, stat.st_ino);
let action = {
let mut actions = ACTIONS.lock().unwrap_or_else(PoisonError::into_inner);
actions
.iter()
.position(|(at, _)| *at == root)
.map(|at| actions.remove(at).1)
};
if let Some(action) = action {
action();
}
}
pub(crate) fn disarm(root: &std::path::Path) -> bool {
use std::os::unix::fs::MetadataExt;
let meta = std::fs::metadata(root).unwrap();
let root = (meta.dev(), meta.ino());
let mut actions = ACTIONS.lock().unwrap_or_else(PoisonError::into_inner);
let before = actions.len();
actions.retain(|(at, _)| *at != root);
actions.len() != before
}
}
#[cfg(test)]
mod tests {
use rustix::fs::{AtFlags, Mode, OFlags};
use super::*;
#[test]
fn an_operand_names_a_ref_a_commit_or_both() {
let hex = "5a".repeat(32);
let commit = Checksum::from_hex(&hex).unwrap();
let upper = hex.to_uppercase();
let at = |name: &str| format!("{name}@{hex}");
for (text, expected) in [
("os/stable".to_owned(), Operand::Name("os/stable")),
(
"@org.example.Os:os/stable".to_owned(),
Operand::Name("@org.example.Os:os/stable"),
),
("os/stable^".to_owned(), Operand::Name("os/stable^")),
(upper.clone(), Operand::Name(&upper)),
(hex[..63].to_owned(), Operand::Name(&hex[..63])),
(format!("@{hex}"), Operand::Name(&format!("@{hex}"))),
(hex.clone(), Operand::Commit(commit)),
(
at("os/stable"),
Operand::NameAt {
name: "os/stable",
commit,
},
),
(
at("@org.example.Os:os/stable"),
Operand::NameAt {
name: "@org.example.Os:os/stable",
commit,
},
),
(
at("origin:os/stable"),
Operand::NameAt {
name: "origin:os/stable",
commit,
},
),
(at(&hex), Operand::NameAt { name: &hex, commit }),
(
at("a@b"),
Operand::NameAt {
name: "a@b",
commit,
},
),
] {
assert_eq!(Operand::parse(&text).unwrap(), expected, "{text}");
}
for text in [
"os/stable@".to_owned(),
format!("os/stable@{}", &hex[..10]),
format!("os/stable@{}", &hex[..63]),
format!("os/stable@{upper}"),
format!("os/stable@{hex}^"),
format!("os/stable@{hex}x"),
format!("os/stable@{hex}0"),
format!("os/stable@{hex}@"),
] {
match Operand::parse(&text) {
Err(Error::InvalidRefspec(given)) => assert_eq!(given, text),
other => panic!("{text}: {other:?}"),
}
}
}
#[test]
fn a_pull_from_a_remote_checks_each_operand() {
let hex = "5a".repeat(32);
let upper = hex.to_uppercase();
let check = |name: &str| {
check_remote_operands(&PullOptions {
refs: vec![name.to_owned()],
..PullOptions::default()
})
};
for name in [
"os/stable".to_owned(),
"@org.example.Os:os/stable".to_owned(),
hex.clone(),
upper.clone(),
format!("os/stable@{hex}"),
format!("@org.example.Os:os/stable@{hex}"),
format!("{hex}@{hex}"),
] {
check(&name).unwrap_or_else(|e| panic!("{name}: {e:?}"));
}
for name in [
"os/stable@".to_owned(),
format!("@{hex}"),
format!("os/stable@{}", &hex[..10]),
format!("os/stable@{}", &hex[..63]),
format!("os/stable@{upper}"),
format!("a@b@{hex}"),
format!("os/stable@{hex}^"),
format!("os/stable@{hex}x"),
format!("os/stable@{hex}0"),
format!("origin:os/stable@{hex}"),
format!("@:os/stable@{hex}"),
format!("@org.example.Os:@{hex}"),
"origin:os/stable".to_owned(),
"os/stable^".to_owned(),
] {
match check(&name) {
Err(Error::InvalidRefspec(given)) => assert_eq!(given, name),
other => panic!("{name}: {other:?}"),
}
}
}
#[test]
fn a_local_pull_checks_each_operand() {
let hex = "5a".repeat(32);
let upper = hex.to_uppercase();
let check = |name: &str| local_operands(&[name.to_owned()]).map(|_| ());
let commit = Checksum::from_hex_lower(&hex).unwrap();
let named = format!("main@{hex}");
let refs = [
"main".to_owned(),
hex.clone(),
"main".to_owned(),
named.clone(),
hex.clone(),
];
assert_eq!(
local_operands(&refs).unwrap(),
[
("main", Operand::Name("main")),
(hex.as_str(), Operand::Commit(commit)),
(
named.as_str(),
Operand::NameAt {
name: "main",
commit
}
),
]
);
let refs = ["@bad".to_owned(), "main@zz".to_owned()];
match local_operands(&refs) {
Err(Error::InvalidRefspec(given)) => assert_eq!(given, "@bad"),
other => panic!("{other:?}"),
}
for name in [
"os/stable".to_owned(),
"@org.example.Os:os/stable".to_owned(),
hex[..10].to_owned(),
hex.clone(),
upper.clone(),
format!("os/stable@{hex}"),
format!("origin:os/stable@{hex}"),
format!("@org.example.Os:os/stable@{hex}"),
format!("{hex}@{hex}"),
] {
check(&name).unwrap_or_else(|e| panic!("{name}: {e:?}"));
}
for name in [
"os/stable^".to_owned(),
"origin:os/stable".to_owned(),
"@org.example.Os:os/stable^".to_owned(),
"os stable".to_owned(),
"os/stable@".to_owned(),
format!("@{hex}"),
format!("os/stable@{}", &hex[..10]),
format!("os/stable@{upper}"),
format!("a@b@{hex}"),
format!("os/stable@{hex}^"),
format!("os/stable^@{hex}"),
format!("@:os/stable@{hex}"),
format!("@org.example.Os:@{hex}"),
"@org.example.Os".to_owned(),
] {
match check(&name) {
Err(Error::InvalidRefspec(given)) => assert_eq!(given, name),
other => panic!("{name}: {other:?}"),
}
}
}
#[test]
fn a_local_pull_checks_the_ref_of_each_commit_operand() {
let dir = std::env::temp_dir().join(format!(
"ostrya-pull-local-places-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
let hex = "5a".repeat(32);
let at = |name: &str| format!("{name}@{hex}");
ostrya_rt::block_on(async {
let opts =
crate::CreateOptions::new(crate::RepoMode::Archive).collection_id("org.example.Os");
let repo = Repo::create(&dir.join("repo"), opts).await.unwrap();
let check = |refs: &[&str], no_ref_writes: bool| {
let refs: Vec<String> = refs.iter().map(|name| (*name).to_owned()).collect();
check_local_places(
&repo,
&PullOptions {
no_ref_writes,
..PullOptions::default()
},
&local_operands(&refs)?,
)
};
for refs in [
vec![hex.clone(), at(&hex)],
vec![hex.clone(), at("main")],
vec![at("main"), at("main")],
vec![at("main"), at("origin:main")],
] {
let refs: Vec<&str> = refs.iter().map(String::as_str).collect();
check(&refs, false).unwrap_or_else(|e| panic!("{refs:?}: {e:?}"));
}
for (first, second) in [
("main".to_owned(), at("main")),
(at("main"), at("@org.example.Os:main")),
("main".to_owned(), at("@org.example.Os:main")),
] {
let refs = [first.as_str(), second.as_str()];
match check(&refs, false) {
Err(Error::Pull(message)) => assert_eq!(
message,
format!("the refs {first} and {second} write one ref refs/heads/main")
),
other => panic!("{refs:?}: {other:?}"),
}
check(&refs, true).unwrap();
}
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn commit_operand_writes_what_the_parser_reads() {
let commit = Checksum::from_bytes([0x5a; 32]);
for (r, name) in [
(Ref::local("os/stable"), "os/stable"),
(
Ref::collection("org.example.Os", "os/stable"),
"@org.example.Os:os/stable",
),
(Ref::remote("origin", "os/stable"), "origin:os/stable"),
] {
let text = commit_operand(&r, &commit);
assert_eq!(text, format!("{name}@{}", commit.to_hex()));
assert_eq!(
Operand::parse(&text).unwrap(),
Operand::NameAt { name, commit }
);
}
}
#[test]
fn a_ref_place_gives_the_path_of_its_refs() {
assert_eq!(
RefPlace::Heads.ref_path("os/stable").unwrap(),
"refs/heads/os/stable"
);
assert_eq!(
RefPlace::Collection("org.example.Os")
.ref_path("os/stable")
.unwrap(),
"refs/mirrors/org.example.Os/os/stable"
);
let operands = RefPlace::Operands {
remote: Some("origin"),
own: Some("org.example.Own"),
};
for (name, path) in [
("os/stable", "refs/remotes/origin/os/stable"),
(
"@org.example.Os:os/stable",
"refs/mirrors/org.example.Os/os/stable",
),
("@org.example.Own:os/stable", "refs/heads/os/stable"),
] {
assert_eq!(operands.ref_path(name).unwrap(), path, "{name}");
}
for name in ["../x", "origin:x"] {
assert!(
matches!(
RefPlace::Collection("org.example.Os").ref_path(name),
Err(Error::InvalidRefspec(_))
),
"{name}"
);
}
}
#[test]
fn a_collection_place_follows_the_collection_id_of_the_repository() {
let dir = std::env::temp_dir().join(format!(
"ostrya-pull-place-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
ostrya_rt::block_on(async {
for (name, own, place) in [
("own", Some("org.example.Os"), RefPlace::Heads),
(
"other",
Some("org.example.Other"),
RefPlace::Collection("org.example.Os"),
),
("none", None, RefPlace::Collection("org.example.Os")),
] {
let mut opts = crate::CreateOptions::new(crate::RepoMode::Archive);
if let Some(id) = own {
opts = opts.collection_id(id);
}
let repo = Repo::create(&dir.join(name), opts).await.unwrap();
assert_eq!(
RefPlace::of_collection(&repo, "org.example.Os"),
place,
"{name}"
);
}
});
let _ = std::fs::remove_dir_all(&dir);
}
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, false).unwrap();
let other = commit_with(&[(
"ostree.collection-binding",
"s",
Value::Str("org.example.Other".into()),
)]);
for allow_unbound in [false, true] {
let err = check_collection_binding(&tip, &other, id, allow_unbound).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, false),
Err(Error::Pull(_))
));
check_collection_binding(&tip, &none, id, true).unwrap();
let malformed = commit_with(&[(
"ostree.collection-binding",
"as",
Value::Array(vec![Value::Str(id.into())]),
)]);
for allow_unbound in [false, true] {
let err = check_collection_binding(&tip, &malformed, id, allow_unbound).unwrap_err();
assert!(
matches!(&err, Error::Pull(m) if m.contains("collection binding metadata is not a string")),
"{allow_unbound}: {err:?}"
);
}
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));
}
fn strict_fixture(
tag: &str,
src_mode: RepoMode,
dst_mode: RepoMode,
) -> (std::path::PathBuf, Repo, [ObjectName; 3], FileMeta, Repo) {
let dir = std::env::temp_dir().join(format!(
"ostrya-pull-{tag}-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
ostrya_rt::block_on(async {
let src = Repo::create(&dir.join("src"), crate::CreateOptions::new(src_mode))
.await
.unwrap();
let txn = src.transaction().await.unwrap();
let file = txn
.write_regfile_inline(None, &FileMeta::regular(0, 0, 0o644), b"inside\n")
.await
.unwrap();
let dirmeta = txn
.write_dirmeta(&ostrya_core::DirMeta {
uid: 0,
gid: 0,
mode: 0o40755,
xattrs: Default::default(),
})
.await
.unwrap();
let symlink = txn
.write_symlink("target", &FileMeta::regular(0, 0, 0o777), None)
.await
.unwrap();
txn.commit().await.unwrap();
let parent = std::fs::File::open(&dir).unwrap();
let strict = Repo::open_at_strict(
std::os::fd::AsFd::as_fd(&parent),
std::path::Path::new("src"),
)
.await
.unwrap();
let meta = strict.load_file(&file).await.unwrap().meta();
let dst = Repo::create(&dir.join("dst"), crate::CreateOptions::new(dst_mode))
.await
.unwrap();
let names = [
(file, ObjectType::File),
(dirmeta, ObjectType::DirMeta),
(symlink, ObjectType::File),
]
.map(|(checksum, ty)| ObjectName { checksum, ty });
(dir, strict, names, meta, dst)
})
}
fn swap_in_symlink(path: &std::path::Path, moved: &std::path::Path) {
std::fs::rename(path, moved).unwrap();
std::os::unix::fs::symlink(moved, path).unwrap();
}
fn swap_in_fifo(path: &std::path::Path) {
std::fs::remove_file(path).unwrap();
rustix::fs::mknodat(
rustix::fs::CWD,
path,
rustix::fs::FileType::Fifo,
Mode::from_raw_mode(0o644),
0,
)
.unwrap();
}
#[test]
fn a_filez_copy_refuses_a_fanout_symlinked_after_the_load() {
let (dir, strict, [name, ..], meta, dst) =
strict_fixture("filez-fanout", RepoMode::Archive, RepoMode::Archive);
let plain = ostrya_rt::block_on(Repo::open(&dir.join("src"))).unwrap();
let hex = name.checksum.to_hex();
let fanout = dir.join("src/objects").join(&hex[..2]);
let moved = dir.join("moved");
std::fs::rename(&fanout, &moved).unwrap();
std::os::unix::fs::symlink(&moved, &fanout).unwrap();
let results = ostrya_rt::block_on(async {
let txn = dst.transaction().await.unwrap();
[
import_filez(&txn, &strict, name, &meta, &mut Vec::new()).await,
import_filez(&txn, &plain, name, &meta, &mut Vec::new()).await,
]
});
let _ = std::fs::remove_dir_all(&dir);
let expected = format!(
"objects/{} passes through a symlink; ostrya refuses a symlink in the repository",
name.loose_path(RepoMode::Archive)
);
for result in results {
match result {
Err(Error::InvalidFormat(m)) => assert_eq!(m, expected),
other => panic!("{other:?}"),
}
}
}
#[test]
fn a_filez_copy_refuses_a_fifo_swapped_in_after_the_load() {
let (dir, strict, [name, ..], meta, dst) =
strict_fixture("filez-fifo", RepoMode::Archive, RepoMode::Archive);
let filez = dir
.join("src/objects")
.join(name.loose_path(RepoMode::Archive));
std::fs::remove_file(&filez).unwrap();
rustix::fs::mknodat(
rustix::fs::CWD,
&filez,
rustix::fs::FileType::Fifo,
Mode::from_raw_mode(0o644),
0,
)
.unwrap();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let result = ostrya_rt::block_on(async {
let txn = dst.transaction().await.unwrap();
import_filez(&txn, &strict, name, &meta, &mut Vec::new()).await
});
let _ = tx.send(result);
});
let result = match rx.recv_timeout(Duration::from_secs(10)) {
Ok(result) => result,
Err(_) => {
let _ = rustix::fs::open(
&filez,
OFlags::WRONLY | OFlags::NONBLOCK | OFlags::CLOEXEC,
Mode::empty(),
);
let _ = rx.recv_timeout(Duration::from_secs(10));
let _ = std::fs::remove_dir_all(&dir);
panic!("the copy waits on the FIFO");
}
};
let _ = std::fs::remove_dir_all(&dir);
match result {
Err(Error::InvalidFormat(m)) => {
assert!(m.ends_with(".filez is not a regular file"), "{m}");
}
other => panic!("{other:?}"),
}
}
fn both_modes(dir: &std::path::Path, strict: &Repo) -> [Repo; 2] {
let plain = ostrya_rt::block_on(Repo::open(&dir.join("src"))).unwrap();
[strict.clone(), plain]
}
fn symlink_refusal(name: ObjectName, mode: RepoMode) -> String {
format!(
"objects/{} passes through a symlink; ostrya refuses a symlink in the repository",
name.loose_path(mode)
)
}
fn invalid_format<T: std::fmt::Debug>(result: Result<T>) -> String {
match result {
Err(Error::InvalidFormat(m)) => m,
other => panic!("{other:?}"),
}
}
#[test]
fn a_link_refuses_a_fanout_symlinked_after_the_load() {
for (index, flags) in [
(0, PullFlags::empty()),
(1, PullFlags::empty()),
(1, PullFlags::FORCE_COPY),
] {
let (dir, strict, names, _, dst) =
strict_fixture("link-fanout", RepoMode::Archive, RepoMode::Archive);
let name = names[index];
let object = dir
.join("src/objects")
.join(name.loose_path(RepoMode::Archive));
swap_in_symlink(object.parent().unwrap(), &dir.join("moved"));
let results = both_modes(&dir, &strict).map(|src| {
ostrya_rt::block_on(async {
let txn = dst.transaction().await.unwrap();
link_import(&txn, &src, name, flags).await
})
});
let _ = std::fs::remove_dir_all(&dir);
for result in results {
assert_eq!(
invalid_format(result),
symlink_refusal(name, RepoMode::Archive),
"{:?} {flags:?}",
name.ty
);
}
}
}
#[test]
fn a_payload_clone_refuses_a_fanout_symlinked_after_the_load() {
let (dir, strict, [name, ..], meta, dst) =
strict_fixture("clone-fanout", RepoMode::BareUser, RepoMode::BareUserOnly);
let object = dir
.join("src/objects")
.join(name.loose_path(RepoMode::BareUser));
swap_in_symlink(object.parent().unwrap(), &dir.join("moved"));
let results = both_modes(&dir, &strict).map(|src| {
ostrya_rt::block_on(async {
let txn = dst.transaction().await.unwrap();
txn.stage_clone_content(&src, name.checksum, meta.regular_header(), 0)
.await
})
});
let _ = std::fs::remove_dir_all(&dir);
for result in results {
assert_eq!(
invalid_format(result),
symlink_refusal(name, RepoMode::BareUser)
);
}
}
#[test]
fn a_copy_refuses_a_fifo_swapped_in_after_the_load() {
for (clone, plain) in [(false, false), (false, true), (true, false), (true, true)] {
let (dir, strict, [file, dirmeta, _], meta, dst) =
strict_fixture("copy-fifo", RepoMode::BareUser, RepoMode::BareUserOnly);
let [strict, plain_src] = both_modes(&dir, &strict);
let src = if plain { plain_src } else { strict };
let name = if clone { file } else { dirmeta };
let object = dir
.join("src/objects")
.join(name.loose_path(RepoMode::BareUser));
swap_in_fifo(&object);
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let result = ostrya_rt::block_on(async {
let txn = dst.transaction().await.unwrap();
if clone {
txn.stage_clone_content(&src, name.checksum, meta.regular_header(), 0)
.await
} else {
link_import(&txn, &src, name, PullFlags::FORCE_COPY)
.await
.map(drop)
}
});
let _ = tx.send(result);
});
let result = match rx.recv_timeout(Duration::from_secs(10)) {
Ok(result) => result,
Err(_) => {
let _ = rustix::fs::open(
&object,
OFlags::WRONLY | OFlags::NONBLOCK | OFlags::CLOEXEC,
Mode::empty(),
);
let _ = rx.recv_timeout(Duration::from_secs(10));
let _ = std::fs::remove_dir_all(&dir);
panic!("{:?}: the copy waits on the FIFO", name.ty);
}
};
let _ = std::fs::remove_dir_all(&dir);
let expected = format!(
"objects/{} is not a regular file",
name.loose_path(RepoMode::BareUser)
);
assert_eq!(invalid_format(result), expected, "{:?} {plain}", name.ty);
}
}
fn link_and_probe(src: &Repo, dst: &Repo, name: ObjectName) -> (Result<bool>, bool) {
ostrya_rt::block_on(async {
let txn = dst.transaction().await.unwrap();
let result = link_import(&txn, src, name, PullFlags::empty()).await;
let staging = crate::write::flat_name(&name.checksum, name.ty, dst.mode());
let staged = rustix::fs::statat(
txn.staging_dir(),
staging.as_str(),
AtFlags::SYMLINK_NOFOLLOW,
)
.is_ok();
(result, staged)
})
}
#[test]
fn a_link_refuses_an_object_symlinked_after_the_load() {
for index in [0, 1] {
let (dir, strict, names, _, dst) =
strict_fixture("link-object", RepoMode::Archive, RepoMode::Archive);
let name = names[index];
let object = dir
.join("src/objects")
.join(name.loose_path(RepoMode::Archive));
swap_in_symlink(&object, &dir.join("moved"));
let results = both_modes(&dir, &strict).map(|src| link_and_probe(&src, &dst, name));
let _ = std::fs::remove_dir_all(&dir);
for (result, staged) in results {
assert_eq!(
invalid_format(result),
symlink_refusal(name, RepoMode::Archive),
"{:?}",
name.ty
);
assert!(!staged, "{:?}", name.ty);
}
}
}
#[test]
fn a_link_refuses_a_fifo_swapped_in_after_the_load() {
for index in [0, 1] {
let (dir, strict, names, _, dst) =
strict_fixture("link-fifo", RepoMode::Archive, RepoMode::Archive);
let name = names[index];
swap_in_fifo(
&dir.join("src/objects")
.join(name.loose_path(RepoMode::Archive)),
);
let results = both_modes(&dir, &strict).map(|src| link_and_probe(&src, &dst, name));
let _ = std::fs::remove_dir_all(&dir);
let expected = format!(
"objects/{} is not a regular file",
name.loose_path(RepoMode::Archive)
);
for (result, staged) in results {
assert_eq!(invalid_format(result), expected, "{:?}", name.ty);
assert!(!staged, "{:?}", name.ty);
}
}
}
#[test]
fn a_link_keeps_a_symlink_object_of_bare_user_only() {
let (dir, strict, [_, _, symlink], _, dst) = strict_fixture(
"link-symlink",
RepoMode::BareUserOnly,
RepoMode::BareUserOnly,
);
let results = both_modes(&dir, &strict).map(|src| link_and_probe(&src, &dst, symlink));
let _ = std::fs::remove_dir_all(&dir);
for (result, staged) in results {
assert!(matches!(result, Ok(true)), "{result:?}");
assert!(staged);
}
}
#[test]
fn an_untrusted_import_stages_only_the_bytes_that_it_hashes() {
let (untrusted, copy) = (
PullFlags::UNTRUSTED,
PullFlags::UNTRUSTED | PullFlags::FORCE_COPY,
);
for (src_mode, dst_mode, flags, index) in [
(RepoMode::Archive, RepoMode::Archive, untrusted, 0),
(RepoMode::Archive, RepoMode::Archive, untrusted, 1),
(RepoMode::BareUser, RepoMode::BareUserOnly, untrusted, 0),
(RepoMode::BareUser, RepoMode::BareUser, copy, 0),
(RepoMode::BareUser, RepoMode::BareUser, untrusted, 0),
(RepoMode::BareUser, RepoMode::BareUserShared, untrusted, 2),
(
RepoMode::BareUserPrivate,
RepoMode::BareUserPrivate,
untrusted,
0,
),
(
RepoMode::BareUserPrivate,
RepoMode::BareUserPrivate,
untrusted,
2,
),
(RepoMode::BareUser, RepoMode::BareUserPrivate, untrusted, 0),
] {
for goes_bad in [true, false] {
let (dir, strict, names, _, dst) = strict_fixture("untrusted", src_mode, dst_mode);
let name = names[index];
let other = ostrya_rt::block_on(async {
let src = Repo::open(&dir.join("src")).await.unwrap();
let txn = src.transaction().await.unwrap();
let other = match index {
0 => {
let meta = FileMeta::regular(0, 0, 0o644);
txn.write_regfile_inline(None, &meta, b"outside\n").await
}
1 => {
txn.write_dirmeta(&ostrya_core::DirMeta {
uid: 0,
gid: 0,
mode: 0o40700,
xattrs: Default::default(),
})
.await
}
_ => {
let meta = FileMeta::regular(0, 0, 0o777);
txn.write_symlink("outside", &meta, None).await
}
};
txn.commit().await.unwrap();
other.unwrap()
});
let objects = dir.join("src/objects");
let object = objects.join(name.loose_path(src_mode));
let other = ObjectName {
checksum: other,
ty: name.ty,
};
let other = objects.join(other.loose_path(src_mode));
let good = std::fs::read(&object).unwrap();
let (tmp, aside) = (dir.join("tmp"), dir.join("aside"));
let at = object.clone();
let put_bad = move || {
std::fs::hard_link(&other, &tmp).unwrap();
std::fs::rename(&tmp, &at).unwrap();
};
if goes_bad {
import_seam::arm(&dir.join("dst"), put_bad);
} else {
std::fs::rename(&object, &aside).unwrap();
put_bad();
let at = object.clone();
import_seam::arm(&dir.join("dst"), move || {
std::fs::rename(&aside, &at).unwrap()
});
}
let (result, staged) = ostrya_rt::block_on(async {
let txn = dst.transaction().await.unwrap();
let result = dst
.import_from(&txn, &strict, name, flags, &mut Vec::new())
.await;
let staged = crate::write::flat_name(&name.checksum, name.ty, dst_mode);
let staged = rustix::fs::openat(
txn.staging_dir(),
staged.as_str(),
OFlags::RDONLY | OFlags::CLOEXEC,
Mode::empty(),
)
.ok()
.map(|fd| {
let mut bytes = Vec::new();
std::io::Read::read_to_end(&mut std::fs::File::from(fd), &mut bytes)
.unwrap();
bytes
});
(result, staged)
});
let ran = (std::fs::read(&object).unwrap() == good) != goes_bad;
let _ = std::fs::remove_dir_all(&dir);
let row = format!("{src_mode:?} -> {dst_mode:?} {flags:?} goes_bad={goes_bad}");
assert!(ran, "{row}: the seam did not run");
if goes_bad {
assert!(result.is_ok(), "{row}: {result:?}");
assert!(
staged.as_deref() == Some(&good[..]),
"{row}: bad bytes staged"
);
} else {
match result {
Err(Error::ChecksumMismatch { expected, .. }) => {
assert_eq!(expected, name.checksum, "{row}")
}
other => panic!("{row}: {other:?}"),
}
}
}
}
}
#[test]
fn an_untrusted_link_checks_the_modes_of_the_staged_object() {
use std::os::unix::fs::PermissionsExt;
let (dir, strict, _, _, dst) = strict_fixture(
"staged-modes",
RepoMode::BareUserOnly,
RepoMode::BareUserOnly,
);
let payload = b"setuid\n";
let plain = ostrya_rt::block_on(async {
let src = Repo::open(&dir.join("src")).await.unwrap();
let txn = src.transaction().await.unwrap();
let plain = txn
.write_regfile_inline(None, &FileMeta::regular(0, 0, 0o755), payload)
.await
.unwrap();
txn.commit().await.unwrap();
ObjectName {
checksum: plain,
ty: ObjectType::File,
}
});
let mut hasher =
ContentHasher::new(&FileMeta::regular(0, 0, 0o4755).regular_header()).unwrap();
hasher.update(payload);
let name = ObjectName {
checksum: hasher.finish(),
ty: ObjectType::File,
};
let objects = dir.join("src/objects");
let object = objects.join(name.loose_path(RepoMode::BareUserOnly));
std::fs::create_dir_all(object.parent().unwrap()).unwrap();
std::fs::hard_link(
objects.join(plain.loose_path(RepoMode::BareUserOnly)),
&object,
)
.unwrap();
let at = object.clone();
import_seam::arm(&dir.join("dst"), move || {
std::fs::set_permissions(&at, std::fs::Permissions::from_mode(0o4755)).unwrap()
});
let result = ostrya_rt::block_on(async {
let txn = dst.transaction().await.unwrap();
dst.import_from(&txn, &strict, name, PullFlags::UNTRUSTED, &mut Vec::new())
.await
});
let mode = std::fs::metadata(&object).unwrap().permissions().mode();
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(mode & 0o7777, 0o4755, "the seam did not run");
match result {
Err(Error::Pull(message)) => {
assert!(message.contains("cannot be imported"), "{message}")
}
other => panic!("{other:?}"),
}
}
}