1use serde_json::{Map, Value};
15use std::path::PathBuf;
16
17pub const PROTOCOL_VERSION: u32 = 2;
19
20pub const MAX_LINE_BYTES: usize = 1 << 20;
22
23pub const MAX_CHANGES: usize = 4096;
25
26pub const ALLOWED_MODES: [u32; 3] = [0o100_644, 0o100_755, 0o120_000];
28
29#[derive(Clone, Debug, Eq, PartialEq)]
40pub struct Change {
41 pub path: String,
43 pub mode: u32,
45 pub blob: Option<String>,
47}
48
49#[derive(Clone, Debug, Eq, PartialEq)]
59pub struct CommitRequest {
60 pub id: String,
62 pub repository: PathBuf,
64 pub common_dir: PathBuf,
66 pub reference: String,
68 pub base: String,
70 pub changes: Vec<Change>,
72 pub message: String,
74 pub author: Option<String>,
76 pub committer: String,
78}
79
80#[derive(Clone, Copy, Debug, Eq, PartialEq)]
82pub enum FailureCode {
83 RepositoryFull,
85 RepositoryReadOnly,
87 IndexInUse,
89 Rejected,
91 BranchKeepsChanging,
93 Unavailable,
95}
96
97impl FailureCode {
98 pub fn word(self) -> &'static str {
100 return match self {
101 Self::RepositoryFull => "repository-full",
102 Self::RepositoryReadOnly => "repository-read-only",
103 Self::IndexInUse => "index-in-use",
104 Self::Rejected => "rejected",
105 Self::BranchKeepsChanging => "branch-keeps-changing",
106 Self::Unavailable => "unavailable",
107 };
108 }
109
110 pub const ALL: [Self; 6] = [
112 Self::RepositoryFull,
113 Self::RepositoryReadOnly,
114 Self::IndexInUse,
115 Self::Rejected,
116 Self::BranchKeepsChanging,
117 Self::Unavailable,
118 ];
119
120 pub fn from_word(word: &str) -> Option<Self> {
122 return Self::ALL.into_iter().find(|code| { return code.word() == word; });
123 }
124}
125
126#[derive(Clone, Debug, Eq, PartialEq)]
128pub enum ClientMessage {
129 Commit(Box<CommitRequest>),
131 Retire,
133 Work {
135 common_dir: PathBuf,
137 },
138}
139
140#[derive(Clone, Debug, Eq, PartialEq)]
142pub enum ServiceMessage {
143 Welcome { version: u32 },
145 Position { number: usize, of: usize },
147 Landed { id: String, commit: String, already: bool },
149 RetryPrepare { id: String, base: String },
151 Failed { id: String, code: FailureCode },
153}
154
155fn field<'a>(value: &'a Value, name: &str) -> Result<&'a str, String> {
156 return value.get(name).and_then(Value::as_str).ok_or_else(|| { return format!("field {name} is missing or not text"); });
157}
158
159pub fn is_object_name(text: &str) -> bool {
161 return (text.len() == 40 || text.len() == 64) && text.bytes().all(|byte| { return byte.is_ascii_hexdigit(); });
162}
163
164pub fn is_plain_path(path: &str) -> bool {
166 return !path.is_empty()
167 && !path.starts_with('/')
168 && !path.contains(['\0', '\n'])
169 && path.split('/').all(|part| { return !part.is_empty() && part != "." && part != ".." && part != ".git"; });
170}
171
172fn object(entries: Vec<(&str, Value)>) -> String {
174 let mut map: Map<String, Value> = Map::new();
175 for (key, value) in entries {
176 map.insert(key.to_string(), value);
177 }
178 return Value::Object(map).to_string();
179}
180
181pub fn encode_client(message: &ClientMessage) -> String {
191 return match message {
192 ClientMessage::Retire => object(vec![("type", Value::from("retire")), ("version", Value::from(PROTOCOL_VERSION))]),
193 ClientMessage::Work { common_dir } => object(vec![
194 ("type", Value::from("work")),
195 ("version", Value::from(PROTOCOL_VERSION)),
196 ("commonDir", Value::from(common_dir.to_string_lossy().as_ref())),
197 ]),
198 ClientMessage::Commit(request) => object(vec![
199 ("type", Value::from("commit")),
200 ("version", Value::from(PROTOCOL_VERSION)),
201 ("id", Value::from(request.id.as_str())),
202 ("repository", Value::from(request.repository.to_string_lossy().as_ref())),
203 ("commonDir", Value::from(request.common_dir.to_string_lossy().as_ref())),
204 ("reference", Value::from(request.reference.as_str())),
205 ("base", Value::from(request.base.as_str())),
206 (
207 "changes",
208 Value::Array(
209 request
210 .changes
211 .iter()
212 .map(|change| {
213 return Value::Object(Map::from_iter([
214 (String::from("path"), Value::from(change.path.as_str())),
215 (String::from("mode"), Value::from(change.mode)),
216 (String::from("blob"), change.blob.as_deref().map_or(Value::Null, Value::from)),
217 ]));
218 })
219 .collect(),
220 ),
221 ),
222 ("message", Value::from(request.message.as_str())),
223 ("author", request.author.as_deref().map_or(Value::Null, Value::from)),
224 ("committer", Value::from(request.committer.as_str())),
225 ]),
226 };
227}
228
229pub fn decode_client(line: &str) -> Result<ClientMessage, String> {
239 if line.len() > MAX_LINE_BYTES {
240 return Err(String::from("line is too long"));
241 }
242 let value: Value = serde_json::from_str(line).map_err(|error| { return error.to_string(); })?;
243 if value.get("version").and_then(Value::as_u64) != Some(u64::from(PROTOCOL_VERSION)) {
244 return Err(String::from("unsupported version"));
245 }
246 match field(&value, "type")? {
247 "retire" => return Ok(ClientMessage::Retire),
248 "work" => {
249 let common_dir: PathBuf = PathBuf::from(field(&value, "commonDir")?);
250 if !common_dir.is_absolute() || common_dir.to_string_lossy().contains('\0') {
251 return Err(String::from("work request is not acceptable"));
252 }
253 return Ok(ClientMessage::Work { common_dir });
254 }
255 "commit" => {}
256 other => return Err(format!("unknown message type {other}")),
257 }
258 let mut changes: Vec<Change> = Vec::new();
259 for entry in value.get("changes").and_then(Value::as_array).ok_or("changes is missing")? {
260 let path: &str = field(entry, "path")?;
261 let mode: u32 = u32::try_from(entry.get("mode").and_then(Value::as_u64).ok_or("mode is missing")?)
262 .map_err(|_| { return String::from("mode is out of range"); })?;
263 let blob: Option<String> = entry.get("blob").and_then(Value::as_str).map(str::to_string);
264 if !is_plain_path(path) || !ALLOWED_MODES.contains(&mode) || blob.as_deref().is_some_and(|name| { return !is_object_name(name); }) {
265 return Err(format!("change for {path:?} is not acceptable"));
266 }
267 changes.push(Change { path: path.to_string(), mode, blob });
268 }
269 if changes.len() > MAX_CHANGES {
270 return Err(String::from("number of changes is not acceptable"));
271 }
272 let request = CommitRequest {
273 id: field(&value, "id")?.to_string(),
274 repository: PathBuf::from(field(&value, "repository")?),
275 common_dir: PathBuf::from(field(&value, "commonDir")?),
276 reference: field(&value, "reference")?.to_string(),
277 base: field(&value, "base")?.to_string(),
278 changes,
279 message: field(&value, "message")?.to_string(),
280 author: value.get("author").and_then(Value::as_str).map(str::to_string),
281 committer: field(&value, "committer")?.to_string(),
282 };
283 let well_formed: bool = !request.id.is_empty()
284 && request.id.bytes().all(|byte| { return byte.is_ascii_alphanumeric() || byte == b'-'; })
285 && request.reference.starts_with("refs/")
286 && !request.reference.contains(['\0', '\n', ' '])
287 && is_object_name(&request.base)
288 && request.repository.is_absolute()
289 && request.common_dir.is_absolute()
290 && !request.committer.contains(['\0', '\n'])
291 && request.author.as_deref().is_none_or(|author| { return !author.contains(['\0', '\n']); });
292 if !well_formed {
293 return Err(String::from("request is not acceptable"));
294 }
295 return Ok(ClientMessage::Commit(Box::new(request)));
296}
297
298pub fn encode_service(message: &ServiceMessage) -> String {
308 return match message {
309 ServiceMessage::Welcome { version } => object(vec![("type", Value::from("welcome")), ("version", Value::from(*version))]),
310 ServiceMessage::Position { number, of } => {
311 object(vec![("type", Value::from("position")), ("number", Value::from(*number)), ("of", Value::from(*of))])
312 }
313 ServiceMessage::Landed { id, commit, already } => object(vec![
314 ("type", Value::from("landed")),
315 ("id", Value::from(id.as_str())),
316 ("commit", Value::from(commit.as_str())),
317 ("already", Value::from(*already)),
318 ]),
319 ServiceMessage::RetryPrepare { id, base } => {
320 object(vec![("type", Value::from("retry-prepare")), ("id", Value::from(id.as_str())), ("base", Value::from(base.as_str()))])
321 }
322 ServiceMessage::Failed { id, code } => {
323 object(vec![("type", Value::from("failed")), ("id", Value::from(id.as_str())), ("code", Value::from(code.word()))])
324 }
325 };
326}
327
328pub fn decode_service(line: &str) -> Result<ServiceMessage, String> {
338 if line.len() > MAX_LINE_BYTES {
339 return Err(String::from("line is too long"));
340 }
341 let value: Value = serde_json::from_str(line).map_err(|error| { return error.to_string(); })?;
342 let number = |name: &str| -> Result<usize, String> {
343 return value.get(name).and_then(Value::as_u64).and_then(|n| { return usize::try_from(n).ok(); })
344 .ok_or_else(|| { return format!("field {name} is missing"); });
345 };
346 return match field(&value, "type")? {
347 "welcome" => Ok(ServiceMessage::Welcome {
348 version: u32::try_from(number("version")?).map_err(|_| { return String::from("version is out of range"); })?,
349 }),
350 "position" => Ok(ServiceMessage::Position { number: number("number")?, of: number("of")? }),
351 "landed" => Ok(ServiceMessage::Landed {
352 id: field(&value, "id")?.to_string(),
353 commit: field(&value, "commit")?.to_string(),
354 already: value.get("already").and_then(Value::as_bool).unwrap_or(false),
355 }),
356 "retry-prepare" => Ok(ServiceMessage::RetryPrepare { id: field(&value, "id")?.to_string(), base: field(&value, "base")?.to_string() }),
357 "failed" => Ok(ServiceMessage::Failed {
358 id: field(&value, "id")?.to_string(),
359 code: FailureCode::from_word(field(&value, "code")?).ok_or("unknown failure code")?,
360 }),
361 other => Err(format!("unknown message type {other}")),
362 };
363}
364
365#[cfg(test)]
367#[path = "service_protocol_tests.rs"]
368mod tests;