use std::{
fs::Metadata,
io::Read as _,
path::{Path, PathBuf},
};
use rho_protocol::{
methods::{GitHead, GitRepo},
ClientEnvironment,
};
use super::canonical;
use crate::git::{is_missing, open_regular, read_small};
#[derive(Debug, PartialEq, Eq)]
pub(super) struct AskGit;
#[derive(Debug, PartialEq, Eq)]
pub(super) struct Checkout {
pub(super) top: PathBuf,
pub(super) repo: GitRepo,
}
const GIT_READS_OTHERWISE: &[&str] = &[
"GIT_CEILING_DIRECTORIES",
"GIT_CONFIG",
"GIT_CONFIG_COUNT",
"GIT_CONFIG_PARAMETERS",
"GIT_DISCOVERY_ACROSS_FILESYSTEM",
"GIT_TEST_ASSUME_DIFFERENT_OWNER",
"SUDO_UID",
];
const CONFIG_BYTES: u64 = 1 << 20;
#[derive(Clone, Copy, Debug)]
pub(super) struct Files(());
impl Files {
pub(super) fn for_environment(environment: &ClientEnvironment) -> Option<Self> {
let moved = environment
.iter()
.any(|(name, _)| GIT_READS_OTHERWISE.contains(&name));
(cfg!(unix) && !moved).then_some(Self(()))
}
pub(super) fn read(self, folder: &Path) -> Result<Option<Checkout>, AskGit> {
let real = match canonical(folder) {
Ok(real) => real,
Err(error) if is_missing(&error) => return Ok(None),
Err(_) => return Err(AskGit),
};
let Some(start) = stat(&real.join("."))? else {
return Ok(None);
};
for dir in real.ancestors() {
let here = stat(dir)?.ok_or(AskGit)?;
if !same_device(&here, &start) {
return Ok(None);
}
if let Some(dot_git) = stat(&dir.join(".git"))? {
return checkout(dir, &here, &dot_git).map(Some);
}
if stat(&dir.join("HEAD"))?.is_some() {
return Err(AskGit);
}
}
Ok(None)
}
}
fn checkout(top: &Path, top_metadata: &Metadata, dot_git: &Metadata) -> Result<Checkout, AskGit> {
let dot_git_path = top.join(".git");
if !owned_by_me(top_metadata) || !is_mine(&dot_git_path)? {
return Err(AskGit);
}
let git_dir = if dot_git.is_dir() {
dot_git_path.clone()
} else {
top.join(pointer(&dot_git_path, "gitdir: ")?)
};
stat(&git_dir)?.filter(Metadata::is_dir).ok_or(AskGit)?;
if !is_mine(&git_dir)? {
return Err(AskGit);
}
let commondir = git_dir.join("commondir");
let linked = stat(&commondir)?.is_some();
let common_dir = if linked {
git_dir.join(pointer(&commondir, "")?)
} else {
git_dir.clone()
};
for part in ["objects", "refs"] {
stat(&common_dir.join(part))?
.filter(Metadata::is_dir)
.ok_or(AskGit)?;
}
let head = head(&git_dir, &common_dir)?;
let config_path = common_dir.join("config");
let config = match stat(&config_path)? {
None => Config::default(),
Some(_) => {
let (file, metadata) = open_regular(&config_path)
.map_err(|_| AskGit)?
.ok_or(AskGit)?;
if metadata.len() > CONFIG_BYTES {
return Err(AskGit);
}
let mut text = String::new();
file.take(CONFIG_BYTES)
.read_to_string(&mut text)
.map_err(|_| AskGit)?;
parse_config(&text).ok_or(AskGit)?
}
};
let not_bare = config.bare.as_deref().is_none_or(|bare| {
["false", "no", "off", "0"].contains(&bare.to_ascii_lowercase().as_str())
});
let format_known = config
.format_version
.as_deref()
.is_none_or(|version| version == "0" || version == "1");
let work_tree_here = match &config.work_tree {
None => true,
Some(work_tree) => {
!linked && canonical(&git_dir.join(work_tree)).is_ok_and(|work_tree| work_tree == top)
}
};
if !(linked || not_bare) || !format_known || config.extensions || !work_tree_here {
return Err(AskGit);
}
Ok(Checkout {
top: top.to_path_buf(),
repo: GitRepo::new(Some(head), config.origin_url),
})
}
fn pointer(path: &Path, tag: &str) -> Result<String, AskGit> {
let text = read_small(path).ok_or(AskGit)?;
let line = text.strip_suffix('\n').unwrap_or(&text);
let target = line.strip_prefix(tag).ok_or(AskGit)?;
let plain = !target.is_empty()
&& !target.contains(['\n', '\r'])
&& target.trim_matches([' ', '\t']) == target;
plain.then(|| target.to_owned()).ok_or(AskGit)
}
fn head(git_dir: &Path, common_dir: &Path) -> Result<GitHead, AskGit> {
let path = git_dir.join("HEAD");
if is_symlink(&path)? {
return Err(AskGit);
}
let text = read_small(&path).ok_or(AskGit)?;
let head = head_as_written(&text).ok_or(AskGit)?;
if let GitHead::Branch { reference } = &head {
let dirs: &[&Path] = if git_dir == common_dir {
&[git_dir]
} else {
&[git_dir, common_dir]
};
for dir in dirs {
if !is_plain_branch(&dir.join(reference))? {
return Err(AskGit);
}
}
}
Ok(head)
}
fn is_plain_branch(path: &Path) -> Result<bool, AskGit> {
let metadata = match std::fs::symlink_metadata(path) {
Ok(metadata) => metadata,
Err(error) if is_missing(&error) => return Ok(true),
Err(_) => return Err(AskGit),
};
if metadata.is_dir() {
return Ok(true);
}
if !metadata.is_file() {
return Ok(false);
}
let text = read_small(path).ok_or(AskGit)?;
Ok(matches!(
head_as_written(&text),
Some(GitHead::Detached { .. })
))
}
fn head_as_written(text: &str) -> Option<GitHead> {
let line = text.strip_suffix('\n').unwrap_or(text);
if let Some(reference) = line.strip_prefix("ref: ") {
return is_plain_ref(reference).then(|| GitHead::Branch {
reference: reference.to_owned(),
});
}
let commit = line.len() == 40 && line.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
commit.then(|| GitHead::Detached {
commit: line.to_owned(),
})
}
fn is_plain_ref(reference: &str) -> bool {
reference.starts_with("refs/")
&& !reference.contains("..")
&& reference.split('/').all(|part| {
!part.is_empty()
&& !part.starts_with('.')
&& !part.ends_with('.')
&& !part.ends_with(".lock")
&& part
.chars()
.all(|c| c.is_ascii_alphanumeric() || "-_+.".contains(c))
})
}
#[derive(Debug, Default, PartialEq, Eq)]
struct Config {
format_version: Option<String>,
bare: Option<String>,
work_tree: Option<String>,
extensions: bool,
origin_url: Option<String>,
}
fn parse_config(text: &str) -> Option<Config> {
let mut config = Config::default();
let mut section: Option<(String, Option<&str>)> = None;
for line in text.lines() {
let line = line.trim_start_matches([' ', '\t']);
if is_blank(line) {
continue;
}
if let Some(header) = line.strip_prefix('[') {
let (header, rest) = header.split_once(']')?;
if !is_blank(rest) {
return None;
}
let (name, subsection) = match header.split_once([' ', '\t']) {
None => (header, None),
Some((name, quoted)) => {
let quoted = quoted.trim_start_matches([' ', '\t']);
let subsection = quoted.strip_prefix('"')?.strip_suffix('"')?;
if subsection.contains(['"', '\\']) {
return None;
}
(name, Some(subsection))
}
};
if name.is_empty() || !name.chars().all(is_name_char) {
return None;
}
let name = name.to_ascii_lowercase();
if name == "include" || name == "includeif" {
return None;
}
config.extensions |= name == "extensions";
section = Some((name, subsection));
continue;
}
let end = line.find(|c| !is_name_char(c)).unwrap_or(line.len());
let (key, rest) = line.split_at(end);
if !key.starts_with(|c: char| c.is_ascii_alphabetic()) {
return None;
}
let (name, subsection) = section.as_ref()?;
let rest = rest.trim_start_matches([' ', '\t']);
let value = if rest.is_empty() {
None
} else {
Some(plain_value(rest.strip_prefix('=')?)?)
};
let slot = match (
name.as_str(),
*subsection,
key.to_ascii_lowercase().as_str(),
) {
("core", None, "repositoryformatversion") => &mut config.format_version,
("core", None, "bare") => &mut config.bare,
("core", None, "worktree") => &mut config.work_tree,
("remote", Some("origin"), "url") => &mut config.origin_url,
_ => continue,
};
*slot = Some(value?);
}
Some(config)
}
fn plain_value(value: &str) -> Option<String> {
let value = value.split(['#', ';']).next().unwrap_or_default();
let value = value.trim_matches([' ', '\t']);
if value.contains(['"', '\\']) || value.contains(char::is_control) {
return None;
}
Some(value.to_owned())
}
fn is_blank(rest: &str) -> bool {
let rest = rest.trim_start_matches([' ', '\t']);
rest.is_empty() || rest.starts_with(['#', ';'])
}
fn is_name_char(c: char) -> bool {
c.is_ascii_alphanumeric() || c == '-'
}
fn stat(path: &Path) -> Result<Option<Metadata>, AskGit> {
match std::fs::metadata(path) {
Ok(metadata) => Ok(Some(metadata)),
Err(error) if is_missing(&error) => Ok(None),
Err(_) => Err(AskGit),
}
}
fn is_symlink(path: &Path) -> Result<bool, AskGit> {
match std::fs::symlink_metadata(path) {
Ok(metadata) => Ok(metadata.is_symlink()),
Err(error) if is_missing(&error) => Ok(false),
Err(_) => Err(AskGit),
}
}
fn is_mine(path: &Path) -> Result<bool, AskGit> {
let link = std::fs::symlink_metadata(path).map_err(|_| AskGit)?;
let target = stat(path)?.ok_or(AskGit)?;
Ok(owned_by_me(&link) && owned_by_me(&target))
}
#[cfg(unix)]
fn owned_by_me(metadata: &Metadata) -> bool {
use std::os::unix::fs::MetadataExt as _;
metadata.uid() == unsafe { libc::geteuid() }
}
#[cfg(not(unix))]
fn owned_by_me(_: &Metadata) -> bool {
false
}
#[cfg(unix)]
fn same_device(one: &Metadata, other: &Metadata) -> bool {
use std::os::unix::fs::MetadataExt as _;
one.dev() == other.dev()
}
#[cfg(not(unix))]
fn same_device(_: &Metadata, _: &Metadata) -> bool {
false
}
#[cfg(test)]
#[path = "dot_git_tests.rs"]
mod tests;