use serde_json::{Map, Value};
use std::path::PathBuf;
pub const PROTOCOL_VERSION: u32 = 1;
pub const MAX_LINE_BYTES: usize = 1 << 20;
pub const MAX_CHANGES: usize = 4096;
pub const ALLOWED_MODES: [u32; 3] = [0o100_644, 0o100_755, 0o120_000];
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Change {
pub path: String,
pub mode: u32,
pub blob: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CommitRequest {
pub id: String,
pub repository: PathBuf,
pub common_dir: PathBuf,
pub reference: String,
pub base: String,
pub changes: Vec<Change>,
pub message: String,
pub author: Option<String>,
pub committer: String,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FailureCode {
RepositoryFull,
RepositoryReadOnly,
IndexInUse,
Rejected,
BranchKeepsChanging,
Unavailable,
}
impl FailureCode {
pub fn word(self) -> &'static str {
return match self {
Self::RepositoryFull => "repository-full",
Self::RepositoryReadOnly => "repository-read-only",
Self::IndexInUse => "index-in-use",
Self::Rejected => "rejected",
Self::BranchKeepsChanging => "branch-keeps-changing",
Self::Unavailable => "unavailable",
};
}
pub const ALL: [Self; 6] = [
Self::RepositoryFull,
Self::RepositoryReadOnly,
Self::IndexInUse,
Self::Rejected,
Self::BranchKeepsChanging,
Self::Unavailable,
];
pub fn from_word(word: &str) -> Option<Self> {
return Self::ALL.into_iter().find(|code| { return code.word() == word; });
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ClientMessage {
Commit(Box<CommitRequest>),
Retire,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ServiceMessage {
Welcome { version: u32 },
Position { number: usize, of: usize },
Landed { id: String, commit: String, already: bool },
RetryPrepare { id: String, base: String },
Failed { id: String, code: FailureCode },
}
fn field<'a>(value: &'a Value, name: &str) -> Result<&'a str, String> {
return value.get(name).and_then(Value::as_str).ok_or_else(|| { return format!("field {name} is missing or not text"); });
}
pub fn is_object_name(text: &str) -> bool {
return (text.len() == 40 || text.len() == 64) && text.bytes().all(|byte| { return byte.is_ascii_hexdigit(); });
}
pub fn is_plain_path(path: &str) -> bool {
return !path.is_empty()
&& !path.starts_with('/')
&& !path.contains(['\0', '\n'])
&& path.split('/').all(|part| { return !part.is_empty() && part != "." && part != ".." && part != ".git"; });
}
fn object(entries: Vec<(&str, Value)>) -> String {
let mut map: Map<String, Value> = Map::new();
for (key, value) in entries {
map.insert(key.to_string(), value);
}
return Value::Object(map).to_string();
}
pub fn encode_client(message: &ClientMessage) -> String {
return match message {
ClientMessage::Retire => object(vec![("type", Value::from("retire")), ("version", Value::from(PROTOCOL_VERSION))]),
ClientMessage::Commit(request) => object(vec![
("type", Value::from("commit")),
("version", Value::from(PROTOCOL_VERSION)),
("id", Value::from(request.id.as_str())),
("repository", Value::from(request.repository.to_string_lossy().as_ref())),
("commonDir", Value::from(request.common_dir.to_string_lossy().as_ref())),
("reference", Value::from(request.reference.as_str())),
("base", Value::from(request.base.as_str())),
(
"changes",
Value::Array(
request
.changes
.iter()
.map(|change| {
return Value::Object(Map::from_iter([
(String::from("path"), Value::from(change.path.as_str())),
(String::from("mode"), Value::from(change.mode)),
(String::from("blob"), change.blob.as_deref().map_or(Value::Null, Value::from)),
]));
})
.collect(),
),
),
("message", Value::from(request.message.as_str())),
("author", request.author.as_deref().map_or(Value::Null, Value::from)),
("committer", Value::from(request.committer.as_str())),
]),
};
}
pub fn decode_client(line: &str) -> Result<ClientMessage, String> {
if line.len() > MAX_LINE_BYTES {
return Err(String::from("line is too long"));
}
let value: Value = serde_json::from_str(line).map_err(|error| { return error.to_string(); })?;
if value.get("version").and_then(Value::as_u64) != Some(u64::from(PROTOCOL_VERSION)) {
return Err(String::from("unsupported version"));
}
match field(&value, "type")? {
"retire" => return Ok(ClientMessage::Retire),
"commit" => {}
other => return Err(format!("unknown message type {other}")),
}
let mut changes: Vec<Change> = Vec::new();
for entry in value.get("changes").and_then(Value::as_array).ok_or("changes is missing")? {
let path: &str = field(entry, "path")?;
let mode: u32 = u32::try_from(entry.get("mode").and_then(Value::as_u64).ok_or("mode is missing")?)
.map_err(|_| { return String::from("mode is out of range"); })?;
let blob: Option<String> = entry.get("blob").and_then(Value::as_str).map(str::to_string);
if !is_plain_path(path) || !ALLOWED_MODES.contains(&mode) || blob.as_deref().is_some_and(|name| { return !is_object_name(name); }) {
return Err(format!("change for {path:?} is not acceptable"));
}
changes.push(Change { path: path.to_string(), mode, blob });
}
if changes.is_empty() || changes.len() > MAX_CHANGES {
return Err(String::from("number of changes is not acceptable"));
}
let request = CommitRequest {
id: field(&value, "id")?.to_string(),
repository: PathBuf::from(field(&value, "repository")?),
common_dir: PathBuf::from(field(&value, "commonDir")?),
reference: field(&value, "reference")?.to_string(),
base: field(&value, "base")?.to_string(),
changes,
message: field(&value, "message")?.to_string(),
author: value.get("author").and_then(Value::as_str).map(str::to_string),
committer: field(&value, "committer")?.to_string(),
};
let well_formed: bool = !request.id.is_empty()
&& request.id.bytes().all(|byte| { return byte.is_ascii_alphanumeric() || byte == b'-'; })
&& request.reference.starts_with("refs/")
&& !request.reference.contains(['\0', '\n', ' '])
&& is_object_name(&request.base)
&& request.repository.is_absolute()
&& request.common_dir.is_absolute()
&& !request.committer.contains(['\0', '\n'])
&& request.author.as_deref().is_none_or(|author| { return !author.contains(['\0', '\n']); });
if !well_formed {
return Err(String::from("request is not acceptable"));
}
return Ok(ClientMessage::Commit(Box::new(request)));
}
pub fn encode_service(message: &ServiceMessage) -> String {
return match message {
ServiceMessage::Welcome { version } => object(vec![("type", Value::from("welcome")), ("version", Value::from(*version))]),
ServiceMessage::Position { number, of } => {
object(vec![("type", Value::from("position")), ("number", Value::from(*number)), ("of", Value::from(*of))])
}
ServiceMessage::Landed { id, commit, already } => object(vec![
("type", Value::from("landed")),
("id", Value::from(id.as_str())),
("commit", Value::from(commit.as_str())),
("already", Value::from(*already)),
]),
ServiceMessage::RetryPrepare { id, base } => {
object(vec![("type", Value::from("retry-prepare")), ("id", Value::from(id.as_str())), ("base", Value::from(base.as_str()))])
}
ServiceMessage::Failed { id, code } => {
object(vec![("type", Value::from("failed")), ("id", Value::from(id.as_str())), ("code", Value::from(code.word()))])
}
};
}
pub fn decode_service(line: &str) -> Result<ServiceMessage, String> {
if line.len() > MAX_LINE_BYTES {
return Err(String::from("line is too long"));
}
let value: Value = serde_json::from_str(line).map_err(|error| { return error.to_string(); })?;
let number = |name: &str| -> Result<usize, String> {
return value.get(name).and_then(Value::as_u64).and_then(|n| { return usize::try_from(n).ok(); })
.ok_or_else(|| { return format!("field {name} is missing"); });
};
return match field(&value, "type")? {
"welcome" => Ok(ServiceMessage::Welcome {
version: u32::try_from(number("version")?).map_err(|_| { return String::from("version is out of range"); })?,
}),
"position" => Ok(ServiceMessage::Position { number: number("number")?, of: number("of")? }),
"landed" => Ok(ServiceMessage::Landed {
id: field(&value, "id")?.to_string(),
commit: field(&value, "commit")?.to_string(),
already: value.get("already").and_then(Value::as_bool).unwrap_or(false),
}),
"retry-prepare" => Ok(ServiceMessage::RetryPrepare { id: field(&value, "id")?.to_string(), base: field(&value, "base")?.to_string() }),
"failed" => Ok(ServiceMessage::Failed {
id: field(&value, "id")?.to_string(),
code: FailureCode::from_word(field(&value, "code")?).ok_or("unknown failure code")?,
}),
other => Err(format!("unknown message type {other}")),
};
}
#[cfg(test)]
#[path = "service_protocol_tests.rs"]
mod tests;