Skip to main content

arks_server/
receive.rs

1//! receive-pack service (push path).
2//!
3//! Claimed caps: `report-status`, `report-status-v2` (classic ok/ng + FS2
4//! proc-receive option rewrite when diverted), `delete-refs`,
5//! `push-options` (O4; forward to hooks), `proc-receive` (FS2 when hook
6//! present), `agent`.
7//! Cite: <https://git-scm.com/docs/gitprotocol-capabilities>,
8//! <https://git-scm.com/docs/git-receive-pack> (quarantine environment).
9
10use crate::advertise::{encode_http_advertisement, encode_pack_advertisement};
11use crate::error::ServerError;
12use crate::hooks::{
13    HookEnv, HookGate, ProcReceiveCmd, proc_receive_hook_present, proc_receive_ref_prefixes,
14    ref_matches_proc_receive, run_post_receive, run_post_update, run_pre_receive, run_proc_receive,
15    run_update,
16};
17use crate::push_policy::{PushPolicy, Pusher, RefUpdate, installed_push_policy, verdicts};
18use arks_oid::Oid;
19use arks_pack::DecodedPack;
20use arks_protocol::{Packet, decode_packet, decode_text_line, encode_packet};
21use arks_refs::RefTarget;
22use arks_repo::Repository;
23use arks_store::{FilesystemGitStore, ObjectStore};
24use std::fs;
25use std::path::{Path, PathBuf};
26use std::time::{SystemTime, UNIX_EPOCH};
27
28type RefsAndCaps = (Vec<(String, Oid)>, Vec<String>);
29
30fn receive_refs_and_caps(repo: &Repository) -> Result<RefsAndCaps, ServerError> {
31    let mut refs = repo
32        .refs()
33        .list_refs("refs/")
34        .map_err(|e| ServerError::Msg(e.to_string()))?;
35    refs.sort_by(|a, b| a.0.cmp(&b.0));
36    if let Ok(oid) = repo.refs().resolve("HEAD") {
37        if !refs.iter().any(|(n, _)| n == "HEAD") {
38            refs.insert(0, ("HEAD".into(), oid));
39        }
40    } else if let Ok(RefTarget::Direct(oid)) = repo.head_target() {
41        refs.insert(0, ("HEAD".into(), oid));
42    }
43    // Advertise only real caps. FS2: advertise `proc-receive` when hook present.
44    // Cite: https://git-scm.com/docs/gitprotocol-capabilities
45    let mut caps = vec![
46        "report-status".into(),
47        "report-status-v2".into(),
48        "delete-refs".into(),
49        "push-options".into(),
50        "agent=arks/0.0.0".into(),
51    ];
52    if proc_receive_hook_present(repo.git_dir()) {
53        caps.insert(caps.len() - 1, "proc-receive".into());
54    }
55    Ok((refs, caps))
56}
57
58/// Smart-HTTP receive-pack advertisement.
59pub fn receive_advertisement(repo: &Repository) -> Result<Vec<u8>, ServerError> {
60    let (refs, caps) = receive_refs_and_caps(repo)?;
61    encode_http_advertisement("git-receive-pack", &caps, &refs)
62}
63
64/// Pack-protocol duplex receive-pack advertisement (SSH / stdio).
65pub fn receive_pack_advertisement(repo: &Repository) -> Result<Vec<u8>, ServerError> {
66    let (refs, caps) = receive_refs_and_caps(repo)?;
67    encode_pack_advertisement(&caps, &refs)
68}
69
70/// receive-pack with the installed push policy and a local pusher.
71pub fn receive_pack(repo: &mut Repository, body: &[u8]) -> Result<Vec<u8>, ServerError> {
72    receive_pack_as(repo, body, &Pusher::local())
73}
74
75/// receive-pack with the installed push policy ([`crate::install_push_policy`]).
76pub fn receive_pack_as(
77    repo: &mut Repository,
78    body: &[u8],
79    pusher: &Pusher,
80) -> Result<Vec<u8>, ServerError> {
81    let policy = installed_push_policy();
82    receive_pack_with(repo, body, pusher, policy.as_deref())
83}
84
85/// receive-pack gated by an explicit push policy: each refused ref is reported
86/// `ng <ref> <reason>` and left unchanged; other refs proceed.
87pub fn receive_pack_with(
88    repo: &mut Repository,
89    body: &[u8],
90    pusher: &Pusher,
91    policy: Option<&dyn PushPolicy>,
92) -> Result<Vec<u8>, ServerError> {
93    let (commands, push_options, pack) = split_commands(body)?;
94    let quarantine = Quarantine::create(repo.git_dir())?;
95    let hook_env = HookEnv {
96        quarantine_path: Some(quarantine.path.clone()),
97        push_options,
98    };
99
100    if !pack.is_empty() {
101        if !pack.starts_with(b"PACK") {
102            quarantine.discard();
103            return encode_report_status("unpack unpacker error", &[]);
104        }
105        let decoded = match DecodedPack::decode(&pack, repo.object_format()) {
106            Ok(d) => d,
107            Err(e) => {
108                quarantine.discard();
109                return encode_report_status(&format!("unpack {e}"), &[]);
110            }
111        };
112        let mut qstore = FilesystemGitStore::new(&quarantine.path)
113            .map_err(|e| ServerError::Msg(e.to_string()))?;
114        for object in decoded.objects {
115            qstore
116                .put(repo.object_format(), &object.object)
117                .map_err(|e| ServerError::Msg(e.to_string()))?;
118        }
119    }
120
121    // Honor list: pre-receive once after unpack, before any ref update.
122    // Cite: https://git-scm.com/docs/githooks , https://git-scm.com/docs/git-receive-pack
123    let pre_stdin = hook_stdin_lines(&commands);
124    if run_pre_receive(repo.git_dir(), &pre_stdin, &hook_env)? == HookGate::Decline {
125        quarantine.discard();
126        let declined: Vec<(String, Result<(), String>)> = commands
127            .iter()
128            .map(|cmd| (cmd.name.clone(), Err("pre-receive hook declined".into())))
129            .collect();
130        return encode_report_status_owned("ok", &declined);
131    }
132
133    // Migrate quarantined objects into the main store only after pre-receive.
134    quarantine.migrate_into(repo).map_err(ServerError::Msg)?;
135
136    let prefixes = proc_receive_ref_prefixes(repo.git_dir());
137    let use_proc = proc_receive_hook_present(repo.git_dir()) && !prefixes.is_empty();
138
139    // Push policy (forge rulesets): decided per ref after unpack, before any ref moves.
140    let updates: Vec<RefUpdate> = commands
141        .iter()
142        .map(|c| RefUpdate {
143            name: c.name.clone(),
144            old: c.old,
145            new: c.new,
146        })
147        .collect();
148    let refused = verdicts(policy, repo, pusher, &updates);
149
150    let mut results: Vec<(String, Result<(), String>)> = Vec::new();
151    let mut success_cmds: Vec<ReceiveCommand> = Vec::new();
152    let mut diverted: Vec<ReceiveCommand> = Vec::new();
153    let mut ordinary: Vec<&ReceiveCommand> = Vec::new();
154    for (cmd, refusal) in commands.iter().zip(refused) {
155        if let Some(reason) = refusal {
156            results.push((cmd.name.clone(), Err(reason)));
157            continue;
158        }
159        if use_proc && ref_matches_proc_receive(&cmd.name, &prefixes) {
160            diverted.push(cmd.clone());
161        } else {
162            ordinary.push(cmd);
163        }
164    }
165
166    for cmd in ordinary {
167        let old = repo.refs().resolve(&cmd.name).ok();
168        // Expect old matches when peer sent non-zero old (fast-forward check deferred:
169        // accept if old is None or matches cmd.old, else refuse).
170        if !cmd.old.as_bytes().iter().all(|b| *b == 0) {
171            match old {
172                Some(oid) if oid != cmd.old => {
173                    results.push((cmd.name.clone(), Err("non-fast-forward".into())));
174                    continue;
175                }
176                None => {
177                    results.push((cmd.name.clone(), Err("old oid mismatch".into())));
178                    continue;
179                }
180                _ => {}
181            }
182        }
183        let old_hex = cmd.old.to_hex();
184        let new_hex = cmd.new.to_hex();
185        if run_update(repo.git_dir(), &cmd.name, &old_hex, &new_hex, &hook_env)?
186            == HookGate::Decline
187        {
188            results.push((cmd.name.clone(), Err("hook declined".into())));
189            continue;
190        }
191        if is_delete(cmd) {
192            match repo.refs_mut().delete(&cmd.name, old.as_ref()) {
193                Ok(()) => {
194                    results.push((cmd.name.clone(), Ok(())));
195                    success_cmds.push(cmd.clone());
196                }
197                Err(e) => results.push((cmd.name.clone(), Err(e.to_string()))),
198            }
199            continue;
200        }
201        match repo.refs_mut().update(&cmd.name, &cmd.new, old.as_ref()) {
202            Ok(()) => {
203                results.push((cmd.name.clone(), Ok(())));
204                success_cmds.push(cmd.clone());
205            }
206            Err(e) => results.push((cmd.name.clone(), Err(e.to_string()))),
207        }
208    }
209
210    if !diverted.is_empty() {
211        // FS8 / HOOK-008 closest: refuse concurrent proc-receive under lock.
212        let pr_lock = repo.git_dir().join("hooks").join("proc-receive.lock");
213        if pr_lock.is_file() {
214            return Err(ServerError::Msg(format!(
215                "{} (HOOK-008 — concurrent proc-receive refuse; serialize push-options/proc-receive; lease ≠ skip)",
216                pr_lock.display()
217            )));
218        }
219        let _ = fs::write(&pr_lock, b"arks-proc-receive\n");
220        let pr_cmds: Vec<ProcReceiveCmd> = diverted
221            .iter()
222            .map(|c| ProcReceiveCmd {
223                old_hex: c.old.to_hex(),
224                new_hex: c.new.to_hex(),
225                name: c.name.clone(),
226            })
227            .collect();
228        let pr_results = match run_proc_receive(repo.git_dir(), &pr_cmds, &hook_env) {
229            Ok(r) => {
230                let _ = fs::remove_file(&pr_lock);
231                r
232            }
233            Err(e) => {
234                let _ = fs::remove_file(&pr_lock);
235                return Err(e);
236            }
237        };
238        for pr in pr_results {
239            if !pr.ok {
240                results.push((
241                    pr.name,
242                    Err(pr.error.unwrap_or_else(|| "proc-receive declined".into())),
243                ));
244                continue;
245            }
246            // Apply rewrite if hook provided option refname / new-oid; else
247            // treat ok as "hook handled ref" without receive-pack updating the
248            // original name (stock git behavior for successful proc-receive).
249            let target_name = pr.rewrite_ref.clone().unwrap_or_else(|| pr.name.clone());
250            let new_oid = if let Some(hex) = &pr.rewrite_new {
251                Oid::from_hex(hex).map_err(|e| ServerError::Msg(e.to_string()))?
252            } else {
253                diverted
254                    .iter()
255                    .find(|c| c.name == pr.name)
256                    .map(|c| c.new)
257                    .ok_or_else(|| ServerError::Msg("proc-receive missing cmd".into()))?
258            };
259            let old_hint = if let Some(hex) = &pr.rewrite_old {
260                Some(Oid::from_hex(hex).map_err(|e| ServerError::Msg(e.to_string()))?)
261            } else {
262                repo.refs().resolve(&target_name).ok()
263            };
264            if new_oid.as_bytes().iter().all(|b| *b == 0) {
265                match repo.refs_mut().delete(&target_name, old_hint.as_ref()) {
266                    Ok(()) => {
267                        results.push((pr.name, Ok(())));
268                        success_cmds.push(ReceiveCommand {
269                            old: old_hint.unwrap_or_else(zero_oid),
270                            new: new_oid,
271                            name: target_name,
272                        });
273                    }
274                    Err(e) => results.push((pr.name, Err(e.to_string()))),
275                }
276            } else {
277                match repo
278                    .refs_mut()
279                    .update(&target_name, &new_oid, old_hint.as_ref())
280                {
281                    Ok(()) => {
282                        results.push((pr.name, Ok(())));
283                        success_cmds.push(ReceiveCommand {
284                            old: old_hint.unwrap_or_else(zero_oid),
285                            new: new_oid,
286                            name: target_name,
287                        });
288                    }
289                    Err(e) => results.push((pr.name, Err(e.to_string()))),
290                }
291            }
292        }
293    }
294
295    if !success_cmds.is_empty() {
296        let post_stdin = hook_stdin_lines_refs(success_cmds.iter());
297        run_post_receive(repo.git_dir(), &post_stdin, &hook_env);
298        let names: Vec<&str> = success_cmds.iter().map(|c| c.name.as_str()).collect();
299        run_post_update(repo.git_dir(), &names, &hook_env);
300    }
301
302    encode_report_status_owned("ok", &results)
303}
304
305/// Quarantine object dir under `$GIT_DIR/objects` (git-receive-pack).
306struct Quarantine {
307    path: PathBuf,
308}
309
310impl Quarantine {
311    fn create(git_dir: &Path) -> Result<Self, ServerError> {
312        let objects = git_dir.join("objects");
313        fs::create_dir_all(&objects)?;
314        let nanos = SystemTime::now()
315            .duration_since(UNIX_EPOCH)
316            .map(|d| d.as_nanos())
317            .unwrap_or(0);
318        let path = objects.join(format!("incoming-{nanos}-{}", std::process::id()));
319        fs::create_dir_all(&path)?;
320        Ok(Self { path })
321    }
322
323    fn discard(self) {
324        let _ = fs::remove_dir_all(&self.path);
325    }
326
327    fn migrate_into(self, repo: &mut Repository) -> Result<(), String> {
328        // Walk quarantine loose objects and put into the main store.
329        let Ok(entries) = fs::read_dir(&self.path) else {
330            let _ = fs::remove_dir_all(&self.path);
331            return Ok(());
332        };
333        for entry in entries.flatten() {
334            let name = entry.file_name();
335            let name = name.to_string_lossy();
336            if name.len() != 2 {
337                continue;
338            }
339            let fanout = entry.path();
340            let Ok(objs) = fs::read_dir(&fanout) else {
341                continue;
342            };
343            for obj in objs.flatten() {
344                let fname = obj.file_name();
345                let rest = fname.to_string_lossy();
346                let hex = format!("{name}{rest}");
347                let Ok(oid) = Oid::from_hex(&hex) else {
348                    continue;
349                };
350                // Read via a store rooted at quarantine so packed/overlay stays honest.
351                let qstore = FilesystemGitStore::open(&self.path);
352                match qstore.get(&oid) {
353                    Ok(raw) => {
354                        let format = repo.object_format();
355                        repo.store_mut()
356                            .put(format, &raw)
357                            .map_err(|e| e.to_string())?;
358                    }
359                    Err(_) => continue,
360                }
361            }
362        }
363        let _ = fs::remove_dir_all(&self.path);
364        Ok(())
365    }
366}
367
368fn is_delete(cmd: &ReceiveCommand) -> bool {
369    cmd.new.as_bytes().iter().all(|b| *b == 0)
370}
371
372fn zero_oid() -> Oid {
373    Oid::from_hex("0000000000000000000000000000000000000000").expect("zero oid")
374}
375
376fn hook_stdin_lines(commands: &[ReceiveCommand]) -> Vec<u8> {
377    hook_stdin_lines_refs(commands.iter())
378}
379
380fn hook_stdin_lines_refs<'a, I>(commands: I) -> Vec<u8>
381where
382    I: IntoIterator<Item = &'a ReceiveCommand>,
383{
384    let mut out = Vec::new();
385    for cmd in commands {
386        out.extend(format!("{} {} {}\n", cmd.old.to_hex(), cmd.new.to_hex(), cmd.name).as_bytes());
387    }
388    out
389}
390
391#[derive(Debug, Clone)]
392struct ReceiveCommand {
393    old: Oid,
394    new: Oid,
395    name: String,
396}
397
398type SplitCommands = (Vec<ReceiveCommand>, Vec<String>, Vec<u8>);
399
400fn split_commands(body: &[u8]) -> Result<SplitCommands, ServerError> {
401    let mut offset = 0;
402    let mut commands = Vec::new();
403    let mut saw_push_options_cap = false;
404    while offset < body.len() {
405        let (packet, n) =
406            decode_packet(&body[offset..]).map_err(|e| ServerError::Protocol(e.to_string()))?;
407        offset += n;
408        match packet {
409            Packet::Flush => break,
410            Packet::Data(payload) => {
411                let owned = if let Some(nul) = payload.iter().position(|b| *b == 0) {
412                    let text = std::str::from_utf8(&payload[..nul])
413                        .map_err(|_| ServerError::Protocol("command not utf-8".into()))?
414                        .to_string();
415                    let caps = std::str::from_utf8(&payload[nul + 1..]).unwrap_or("");
416                    if caps.split_whitespace().any(|c| c == "push-options") {
417                        saw_push_options_cap = true;
418                    }
419                    text
420                } else {
421                    decode_text_line(&payload).map_err(|e| ServerError::Protocol(e.to_string()))?
422                };
423                let text = owned.trim_end_matches('\n');
424                let mut parts = text.splitn(3, ' ');
425                let old_hex = parts
426                    .next()
427                    .ok_or_else(|| ServerError::Protocol("bad command".into()))?;
428                let new_hex = parts
429                    .next()
430                    .ok_or_else(|| ServerError::Protocol("bad command".into()))?;
431                let name = parts
432                    .next()
433                    .ok_or_else(|| ServerError::Protocol("bad command".into()))?;
434                // Capability list may trail the first command after a NUL already handled;
435                // also accept space-separated caps after the refname on some peers.
436                if name.contains("push-options") || text.contains(" push-options") {
437                    saw_push_options_cap = true;
438                }
439                let refname = name.split('\0').next().unwrap_or(name).to_string();
440                commands.push(ReceiveCommand {
441                    old: Oid::from_hex(old_hex)
442                        .map_err(|e| ServerError::Protocol(e.to_string()))?,
443                    new: Oid::from_hex(new_hex)
444                        .map_err(|e| ServerError::Protocol(e.to_string()))?,
445                    name: refname,
446                });
447            }
448            _ => {}
449        }
450    }
451    let mut push_options = Vec::new();
452    if saw_push_options_cap {
453        while offset < body.len() {
454            if body[offset..].starts_with(b"PACK") {
455                break;
456            }
457            let (packet, n) =
458                decode_packet(&body[offset..]).map_err(|e| ServerError::Protocol(e.to_string()))?;
459            offset += n;
460            match packet {
461                Packet::Flush => break,
462                Packet::Data(payload) => {
463                    let line = decode_text_line(&payload)
464                        .map_err(|e| ServerError::Protocol(e.to_string()))?;
465                    let line = line.trim_end_matches('\n');
466                    if let Some(rest) = line.strip_prefix("push-option ") {
467                        push_options.push(rest.to_string());
468                    } else if line == "push-option" {
469                        push_options.push(String::new());
470                    } else {
471                        return Err(ServerError::Protocol(format!(
472                            "expected push-option line, got {line}"
473                        )));
474                    }
475                }
476                _ => {}
477            }
478        }
479    }
480    Ok((commands, push_options, body[offset..].to_vec()))
481}
482
483fn encode_report_status_owned(
484    unpack: &str,
485    refs: &[(String, Result<(), String>)],
486) -> Result<Vec<u8>, ServerError> {
487    let borrowed: Vec<(&str, Result<(), &str>)> = refs
488        .iter()
489        .map(|(n, r)| {
490            (
491                n.as_str(),
492                match r {
493                    Ok(()) => Ok(()),
494                    Err(e) => Err(e.as_str()),
495                },
496            )
497        })
498        .collect();
499    encode_report_status(unpack, &borrowed)
500}
501
502fn encode_report_status(
503    unpack: &str,
504    refs: &[(&str, Result<(), &str>)],
505) -> Result<Vec<u8>, ServerError> {
506    // Classic unpack/ok/ng lines are valid report-status and report-status-v2
507    // when no proc-receive rewrite options are needed.
508    let mut out = Vec::new();
509    out.extend(text_pkt(&format!("unpack {unpack}"))?);
510    for (name, result) in refs {
511        match result {
512            Ok(()) => out.extend(text_pkt(&format!("ok {name}"))?),
513            Err(err) => out.extend(text_pkt(&format!("ng {name} {err}"))?),
514        }
515    }
516    out.extend(encode_packet(&Packet::Flush).map_err(|e| ServerError::Protocol(e.to_string()))?);
517    Ok(out)
518}
519
520fn text_pkt(text: &str) -> Result<Vec<u8>, ServerError> {
521    let mut payload = text.as_bytes().to_vec();
522    if !payload.ends_with(b"\n") {
523        payload.push(b'\n');
524    }
525    encode_packet(&Packet::Data(payload)).map_err(|e| ServerError::Protocol(e.to_string()))
526}