use crate::error::ServerError;
use arks_protocol::{Packet, decode_packet, decode_text_line, encode_packet};
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum HookGate {
Allow,
Decline,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct HookEnv {
pub quarantine_path: Option<PathBuf>,
pub push_options: Vec<String>,
}
pub(crate) fn run_pre_receive(
git_dir: &Path,
stdin_lines: &[u8],
env: &HookEnv,
) -> Result<HookGate, ServerError> {
run_named_hook(git_dir, "pre-receive", &[], Some(stdin_lines), true, env)
}
pub(crate) fn run_update(
git_dir: &Path,
refname: &str,
old_hex: &str,
new_hex: &str,
env: &HookEnv,
) -> Result<HookGate, ServerError> {
run_named_hook(
git_dir,
"update",
&[refname, old_hex, new_hex],
None,
true,
env,
)
}
pub(crate) fn run_post_receive(git_dir: &Path, stdin_lines: &[u8], env: &HookEnv) {
let _ = run_named_hook(git_dir, "post-receive", &[], Some(stdin_lines), false, env);
}
pub(crate) fn run_post_update(git_dir: &Path, updated_refs: &[&str], env: &HookEnv) {
if updated_refs.is_empty() {
return;
}
let _ = run_named_hook(git_dir, "post-update", updated_refs, None, false, env);
}
pub(crate) fn proc_receive_hook_present(git_dir: &Path) -> bool {
is_runnable_hook(&hook_path(git_dir, "proc-receive"))
}
pub(crate) fn proc_receive_ref_prefixes(git_dir: &Path) -> Vec<String> {
let text = fs::read_to_string(git_dir.join("config")).unwrap_or_default();
let mut out = Vec::new();
let mut in_receive = false;
for raw in text.lines() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
continue;
}
if line.starts_with('[') {
in_receive = line.eq_ignore_ascii_case("[receive]");
continue;
}
if !in_receive {
continue;
}
let Some((k, v)) = line.split_once('=') else {
continue;
};
if k.trim().eq_ignore_ascii_case("procReceiveRefs") {
let v = v.trim().trim_matches('"').trim_matches('\'').to_string();
if !v.is_empty() {
out.push(v);
}
}
}
out
}
pub(crate) fn ref_matches_proc_receive(refname: &str, prefixes: &[String]) -> bool {
prefixes
.iter()
.filter(|p| !p.starts_with('!'))
.any(|p| refname.starts_with(p.as_str()))
}
#[derive(Debug, Clone)]
pub(crate) struct ProcReceiveCmd {
pub old_hex: String,
pub new_hex: String,
pub name: String,
}
#[derive(Debug, Clone)]
pub(crate) struct ProcReceiveResult {
pub name: String,
pub ok: bool,
pub error: Option<String>,
pub rewrite_ref: Option<String>,
pub rewrite_old: Option<String>,
pub rewrite_new: Option<String>,
}
pub(crate) fn run_proc_receive(
git_dir: &Path,
commands: &[ProcReceiveCmd],
env: &HookEnv,
) -> Result<Vec<ProcReceiveResult>, ServerError> {
if commands.is_empty() {
return Ok(Vec::new());
}
let path = hook_path(git_dir, "proc-receive");
if !is_runnable_hook(&path) {
return Err(ServerError::Msg(
"proc-receive advertised but hook missing".into(),
));
}
let mut cmd = {
#[cfg(windows)]
{
let mut c = windows_bash();
c.arg(bash_style_path(&path));
c
}
#[cfg(not(windows))]
{
Command::new(&path)
}
};
#[cfg(windows)]
{
cmd.env("GIT_DIR", bash_style_path(git_dir));
if let Some(q) = &env.quarantine_path {
cmd.env("GIT_QUARANTINE_PATH", bash_style_path(q));
}
}
#[cfg(not(windows))]
{
cmd.env("GIT_DIR", git_dir);
if let Some(q) = &env.quarantine_path {
cmd.env("GIT_QUARANTINE_PATH", q);
}
}
cmd.env("GIT_PUSH_OPTION_COUNT", env.push_options.len().to_string());
for (i, opt) in env.push_options.iter().enumerate() {
cmd.env(format!("GIT_PUSH_OPTION_{i}"), opt);
}
cmd.current_dir(git_dir);
cmd.stdin(Stdio::piped());
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::inherit());
let mut child = cmd
.spawn()
.map_err(|e| ServerError::Msg(format!("hook proc-receive: {e}")))?;
let mut request = Vec::new();
request.extend(
encode_packet(&Packet::Data(b"version=0\n".to_vec()))
.map_err(|e| ServerError::Protocol(e.to_string()))?,
);
request
.extend(encode_packet(&Packet::Flush).map_err(|e| ServerError::Protocol(e.to_string()))?);
for c in commands {
let line = format!("{} {} {}\n", c.old_hex, c.new_hex, c.name);
request.extend(
encode_packet(&Packet::Data(line.into_bytes()))
.map_err(|e| ServerError::Protocol(e.to_string()))?,
);
}
request
.extend(encode_packet(&Packet::Flush).map_err(|e| ServerError::Protocol(e.to_string()))?);
if let Some(mut hin) = child.stdin.take() {
match hin.write_all(&request) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {}
Err(e) => {
return Err(ServerError::Msg(format!("hook proc-receive stdin: {e}")));
}
}
}
let mut stdout = child
.stdout
.take()
.ok_or_else(|| ServerError::Msg("hook proc-receive: no stdout".into()))?;
let mut buf = Vec::new();
stdout
.read_to_end(&mut buf)
.map_err(|e| ServerError::Msg(format!("hook proc-receive stdout: {e}")))?;
let status = child
.wait()
.map_err(|e| ServerError::Msg(format!("hook proc-receive: {e}")))?;
if !status.success() {
return Err(ServerError::Msg(format!(
"proc-receive hook exited {}",
status.code().unwrap_or(-1)
)));
}
parse_proc_receive_response(&buf, commands)
}
fn parse_proc_receive_response(
buf: &[u8],
commands: &[ProcReceiveCmd],
) -> Result<Vec<ProcReceiveResult>, ServerError> {
let mut offset = 0;
let mut results: Vec<ProcReceiveResult> = Vec::new();
let mut current: Option<ProcReceiveResult> = None;
let finish_current = |cur: &mut Option<ProcReceiveResult>, out: &mut Vec<ProcReceiveResult>| {
if let Some(r) = cur.take() {
out.push(r);
}
};
while offset < buf.len() {
let (packet, n) =
decode_packet(&buf[offset..]).map_err(|e| ServerError::Protocol(e.to_string()))?;
offset += n;
match packet {
Packet::Flush => {
finish_current(&mut current, &mut results);
}
Packet::Data(payload) => {
let line =
decode_text_line(&payload).map_err(|e| ServerError::Protocol(e.to_string()))?;
let line = line.trim_end_matches('\n');
if line.is_empty() || line.starts_with("version") {
continue;
}
if let Some(rest) = line.strip_prefix("ok ") {
finish_current(&mut current, &mut results);
current = Some(ProcReceiveResult {
name: rest.trim().to_string(),
ok: true,
error: None,
rewrite_ref: None,
rewrite_old: None,
rewrite_new: None,
});
} else if let Some(rest) = line.strip_prefix("ng ") {
finish_current(&mut current, &mut results);
let mut parts = rest.splitn(2, ' ');
let name = parts.next().unwrap_or("").to_string();
let err = parts.next().unwrap_or("declined").to_string();
current = Some(ProcReceiveResult {
name,
ok: false,
error: Some(err),
rewrite_ref: None,
rewrite_old: None,
rewrite_new: None,
});
} else if let Some(rest) = line.strip_prefix("option ") {
let Some(cur) = current.as_mut() else {
return Err(ServerError::Protocol(
"proc-receive option before ok/ng".into(),
));
};
if let Some(v) = rest.strip_prefix("refname ") {
cur.rewrite_ref = Some(v.to_string());
} else if let Some(v) = rest.strip_prefix("old-oid ") {
cur.rewrite_old = Some(v.to_string());
} else if let Some(v) = rest.strip_prefix("new-oid ") {
cur.rewrite_new = Some(v.to_string());
}
} else {
return Err(ServerError::Protocol(format!(
"proc-receive unexpected line: {line}"
)));
}
}
_ => {}
}
}
finish_current(&mut current, &mut results);
for cmd in commands {
if !results.iter().any(|r| r.name == cmd.name) {
results.push(ProcReceiveResult {
name: cmd.name.clone(),
ok: false,
error: Some("proc-receive did not report".into()),
rewrite_ref: None,
rewrite_old: None,
rewrite_new: None,
});
}
}
Ok(results)
}
fn hook_path(git_dir: &Path, name: &str) -> PathBuf {
git_dir.join("hooks").join(name)
}
#[cfg(windows)]
fn windows_bash() -> Command {
const CANDIDATES: &[&str] = &[
r"C:\Program Files\Git\bin\bash.exe",
r"C:\Program Files\Git\usr\bin\bash.exe",
r"C:\Program Files (x86)\Git\bin\bash.exe",
];
for c in CANDIDATES {
if Path::new(c).is_file() {
return Command::new(c);
}
}
Command::new("bash")
}
#[cfg(windows)]
fn bash_style_path(path: &Path) -> String {
let s = path.to_string_lossy().replace('\\', "/");
if let Some((drive, rest)) = s.split_once(':') {
if drive.len() == 1 {
if let Some(ch) = drive.chars().next() {
let d = ch.to_ascii_lowercase();
return format!("/{d}{rest}");
}
}
}
s
}
fn is_runnable_hook(path: &Path) -> bool {
if !path.is_file() {
return false;
}
if path
.file_name()
.and_then(|s| s.to_str())
.is_some_and(|n| n.ends_with(".sample"))
{
return false;
}
let Ok(meta) = fs::metadata(path) else {
return false;
};
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if meta.permissions().mode() & 0o111 == 0 {
return false;
}
}
#[cfg(not(unix))]
{
let _ = meta;
}
true
}
fn run_named_hook(
git_dir: &Path,
name: &str,
args: &[&str],
stdin: Option<&[u8]>,
fail_on_nonzero: bool,
env: &HookEnv,
) -> Result<HookGate, ServerError> {
let path = hook_path(git_dir, name);
if !is_runnable_hook(&path) {
return Ok(HookGate::Allow);
}
let mut cmd = {
#[cfg(windows)]
{
let mut c = windows_bash();
c.arg(bash_style_path(&path));
c.args(args);
c
}
#[cfg(not(windows))]
{
let mut c = Command::new(&path);
c.args(args);
c
}
};
#[cfg(windows)]
{
cmd.env("GIT_DIR", bash_style_path(git_dir));
if let Some(q) = &env.quarantine_path {
cmd.env("GIT_QUARANTINE_PATH", bash_style_path(q));
}
}
#[cfg(not(windows))]
{
cmd.env("GIT_DIR", git_dir);
if let Some(q) = &env.quarantine_path {
cmd.env("GIT_QUARANTINE_PATH", q);
}
}
cmd.env("GIT_PUSH_OPTION_COUNT", env.push_options.len().to_string());
for (i, opt) in env.push_options.iter().enumerate() {
cmd.env(format!("GIT_PUSH_OPTION_{i}"), opt);
}
cmd.current_dir(git_dir);
if stdin.is_some() {
cmd.stdin(Stdio::piped());
} else {
cmd.stdin(Stdio::null());
}
cmd.stdout(Stdio::inherit());
cmd.stderr(Stdio::inherit());
let mut child = cmd
.spawn()
.map_err(|e| ServerError::Msg(format!("hook {name}: {e}")))?;
if let Some(bytes) = stdin {
if let Some(mut hin) = child.stdin.take() {
match hin.write_all(bytes) {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => {}
Err(e) => {
return Err(ServerError::Msg(format!("hook {name} stdin: {e}")));
}
}
}
}
let status = child
.wait()
.map_err(|e| ServerError::Msg(format!("hook {name}: {e}")))?;
if fail_on_nonzero && !status.success() {
return Ok(HookGate::Decline);
}
Ok(HookGate::Allow)
}