use std::io::{Read, Write};
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use ostrya_core::Checksum;
use rustix::fs::{AtFlags, FileType, Mode, OFlags};
use rustix::io::Errno;
use crate::error::{Error, Result};
use crate::repo::Repo;
use crate::transaction::Transaction;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CollectionRef {
pub collection_id: Option<String>,
pub ref_name: String,
}
impl CollectionRef {
pub fn new(collection_id: impl Into<String>, ref_name: impl Into<String>) -> CollectionRef {
CollectionRef {
collection_id: Some(collection_id.into()),
ref_name: ref_name.into(),
}
}
pub fn local(ref_name: impl Into<String>) -> CollectionRef {
CollectionRef {
collection_id: None,
ref_name: ref_name.into(),
}
}
}
enum QueuedRef {
Ref(String),
Collection(CollectionRef),
}
impl QueuedRef {
fn relpath(&self) -> Result<String> {
match self {
QueuedRef::Ref(refspec) => refspec_to_relpath(refspec),
QueuedRef::Collection(cref) => collection_ref_to_relpath(cref),
}
}
}
pub(crate) struct RefWrite {
target: QueuedRef,
checksum: Option<Checksum>,
}
impl Transaction {
pub fn set_ref(&self, refspec: &str, checksum: Option<&Checksum>) {
self.refs.lock().unwrap().push(RefWrite {
target: QueuedRef::Ref(refspec.to_owned()),
checksum: checksum.copied(),
});
}
pub fn set_collection_ref(&self, cref: &CollectionRef, checksum: Option<&Checksum>) {
self.refs.lock().unwrap().push(RefWrite {
target: QueuedRef::Collection(cref.clone()),
checksum: checksum.copied(),
});
}
pub(crate) fn resolve_ref_queue(&self) -> Result<Vec<(String, Option<Checksum>)>> {
let queue = self.refs.lock().unwrap();
queue
.iter()
.map(|w| Ok((w.target.relpath()?, w.checksum)))
.collect()
}
pub(crate) async fn write_resolved_refs(
&self,
refs: &[(String, Option<Checksum>)],
) -> Result<()> {
if refs.is_empty() {
return Ok(());
}
let fsync = self.repo().config().fsync()?;
let repo_fd = self.repo().repo_fd().try_clone_to_owned()?;
let refs = refs.to_vec();
ostrya_rt::unblock(move || {
for (relpath, checksum) in &refs {
write_ref_blocking(repo_fd.as_fd(), relpath, *checksum, fsync)?;
}
Ok(())
})
.await
}
}
const REF_READ_CAP: u64 = 4096;
impl Repo {
pub async fn resolve_rev(&self, refspec: &str, allow_noent: bool) -> Result<Option<Checksum>> {
if refspec.len() == 64
&& let Ok(checksum) = Checksum::from_hex(refspec)
{
return Ok(Some(checksum));
}
let relpath = refspec_to_relpath(refspec)?;
let repo = self.clone();
let bytes = ostrya_rt::unblock(move || read_ref_file(repo.repo_fd(), &relpath)).await?;
match bytes {
Some(bytes) => Ok(Some(parse_ref_content(&bytes)?)),
None if allow_noent => Ok(None),
None => Err(Error::RefNotFound(refspec.to_owned())),
}
}
pub async fn list_refs(&self, prefix: Option<&str>) -> Result<Vec<(String, Checksum)>> {
let repo = self.clone();
let mut refs = ostrya_rt::unblock(move || collect_heads(&repo)).await?;
if let Some(prefix) = prefix {
let nested = format!("{prefix}/");
refs.retain(|(name, _)| name == prefix || name.starts_with(&nested));
}
refs.sort_by(|a, b| a.0.cmp(&b.0));
Ok(refs)
}
pub async fn set_ref_immediate(
&self,
refspec: &str,
checksum: Option<&Checksum>,
) -> Result<()> {
let relpath = refspec_to_relpath(refspec)?;
let fsync = self.config().fsync()?;
let checksum = checksum.copied();
let repo_fd = self.repo_fd().try_clone_to_owned()?;
ostrya_rt::unblock(move || write_ref_blocking(repo_fd.as_fd(), &relpath, checksum, fsync))
.await
}
}
fn collect_heads(repo: &Repo) -> Result<Vec<(String, Checksum)>> {
let heads = match rustix::fs::openat(
repo.repo_fd(),
"refs/heads",
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(fd) => fd,
Err(Errno::NOENT) => return Ok(Vec::new()),
Err(e) => return Err(Error::Io(e.into())),
};
let mut out = Vec::new();
walk_refs(heads, "", &mut out)?;
Ok(out)
}
fn walk_refs(dir: OwnedFd, prefix: &str, out: &mut Vec<(String, Checksum)>) -> Result<()> {
let mut names: Vec<Vec<u8>> = Vec::new();
let reader = rustix::fs::Dir::read_from(&dir).map_err(|e| Error::Io(e.into()))?;
for entry in reader {
let entry = entry.map_err(|e| Error::Io(e.into()))?;
let name = entry.file_name().to_bytes();
if name == b"." || name == b".." {
continue;
}
names.push(name.to_vec());
}
for name_bytes in names {
let Ok(name) = std::str::from_utf8(&name_bytes) else {
continue;
};
let stat = match rustix::fs::statat(&dir, name, AtFlags::empty()) {
Ok(stat) => stat,
Err(Errno::NOENT) => continue, Err(e) => return Err(Error::Io(e.into())),
};
let child = if prefix.is_empty() {
name.to_owned()
} else {
format!("{prefix}/{name}")
};
if FileType::from_raw_mode(stat.st_mode) == FileType::Directory {
let sub = rustix::fs::openat(
&dir,
name,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)
.map_err(|e| Error::Io(e.into()))?;
walk_refs(sub, &child, out)?;
} else if let Some(bytes) = read_ref_file(dir.as_fd(), name)? {
out.push((child, parse_ref_content(&bytes)?));
}
}
Ok(())
}
fn read_ref_file(
dir: rustix::fd::BorrowedFd<'_>,
relpath: &str,
) -> std::io::Result<Option<Vec<u8>>> {
let fd = match rustix::fs::openat(
dir,
relpath,
OFlags::RDONLY | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(fd) => fd,
Err(Errno::NOENT) => return Ok(None),
Err(e) => return Err(e.into()),
};
let mut buf = Vec::new();
std::fs::File::from(fd)
.take(REF_READ_CAP)
.read_to_end(&mut buf)?;
Ok(Some(buf))
}
fn parse_ref_content(bytes: &[u8]) -> Result<Checksum> {
let text = std::str::from_utf8(bytes)
.map_err(|_| Error::InvalidFormat("ref content is not valid UTF-8".into()))?;
Ok(Checksum::from_hex(text.trim())?)
}
fn refspec_to_relpath(refspec: &str) -> Result<String> {
if let Some((remote, name)) = refspec.split_once(':') {
check_component(remote)?;
check_ref_path(name)?;
Ok(format!("refs/remotes/{remote}/{name}"))
} else {
check_ref_path(refspec)?;
Ok(format!("refs/heads/{refspec}"))
}
}
fn check_ref_path(name: &str) -> Result<()> {
if name.is_empty() || name.contains('\0') {
return Err(Error::InvalidFormat(format!("invalid refspec '{name}'")));
}
for component in name.split('/') {
check_component(component)?;
}
Ok(())
}
fn check_component(component: &str) -> Result<()> {
if component.is_empty() || component == "." || component == ".." || component.contains('\0') {
return Err(Error::InvalidFormat(format!(
"invalid refspec component '{component}'"
)));
}
Ok(())
}
fn collection_ref_to_relpath(cref: &CollectionRef) -> Result<String> {
check_ref_path(&cref.ref_name)?;
match &cref.collection_id {
Some(collection_id) => {
check_component(collection_id)?;
Ok(format!("refs/mirrors/{collection_id}/{}", cref.ref_name))
}
None => Ok(format!("refs/heads/{}", cref.ref_name)),
}
}
const REF_FILE_MODE: u32 = 0o644;
const REF_DIR_MODE: u32 = 0o777;
fn write_ref_blocking(
repo_fd: BorrowedFd<'_>,
relpath: &str,
checksum: Option<Checksum>,
fsync: bool,
) -> Result<()> {
let Some(checksum) = checksum else {
return match rustix::fs::unlinkat(repo_fd, relpath, AtFlags::empty()) {
Ok(()) | Err(Errno::NOENT) => Ok(()),
Err(e) => Err(e.into()),
};
};
create_ref_parents(repo_fd, relpath)?;
let content = format!("{}\n", checksum.to_hex());
let tmp = format!(
"{relpath}.tmp-{}-{}",
std::process::id(),
crate::write::unique()
);
let fd = rustix::fs::openat(
repo_fd,
tmp.as_str(),
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC | OFlags::NOFOLLOW,
Mode::from_raw_mode(REF_FILE_MODE),
)?;
let write_and_rename = || -> Result<()> {
let mut file = std::fs::File::from(fd);
file.write_all(content.as_bytes())?;
file.flush()?;
rustix::fs::fchmod(file.as_fd(), Mode::from_raw_mode(REF_FILE_MODE))?;
if fsync {
rustix::fs::fdatasync(file.as_fd())?;
}
drop(file);
rustix::fs::renameat(repo_fd, tmp.as_str(), repo_fd, relpath)?;
Ok(())
};
write_and_rename().inspect_err(|_| {
let _ = rustix::fs::unlinkat(repo_fd, tmp.as_str(), AtFlags::empty());
})
}
fn create_ref_parents(repo_fd: BorrowedFd<'_>, relpath: &str) -> Result<()> {
let mut acc = String::new();
let mut components: Vec<&str> = relpath.split('/').collect();
components.pop(); for component in components {
if !acc.is_empty() {
acc.push('/');
}
acc.push_str(component);
match rustix::fs::mkdirat(repo_fd, acc.as_str(), Mode::from_raw_mode(REF_DIR_MODE)) {
Ok(()) | Err(Errno::EXIST) => {}
Err(e) => return Err(e.into()),
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn refspec_maps_local_and_remote() {
assert_eq!(
refspec_to_relpath("test/main").unwrap(),
"refs/heads/test/main"
);
assert_eq!(
refspec_to_relpath("origin:test/main").unwrap(),
"refs/remotes/origin/test/main"
);
}
#[test]
fn refspec_rejects_traversal() {
for bad in ["", "..", "a/../b", "/a", "a/", "a//b", "a/.."] {
assert!(refspec_to_relpath(bad).is_err(), "should reject {bad:?}");
}
assert!(refspec_to_relpath("origin:../escape").is_err());
}
#[test]
fn parses_ref_content_with_newline() {
let hex = "b3c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89";
let checksum = parse_ref_content(format!("{hex}\n").as_bytes()).unwrap();
assert_eq!(checksum.to_hex(), hex);
assert!(parse_ref_content(b"not-a-checksum\n").is_err());
}
}