Skip to main content

arks_server/
v2.rs

1//! Protocol v2 server subset: capability advertisement, `ls-refs`, `fetch`.
2//!
3//! Primary: <https://git-scm.com/docs/gitprotocol-v2>
4//! Claimed commands only — never invent capabilities ([[sot:root/arks-server]]).
5
6use crate::error::ServerError;
7use crate::walk::collect_closure;
8use arks_oid::Oid;
9use arks_pack::EncodedPack;
10use arks_protocol::{
11    Packet, decode_packet, decode_text_line, encode_packet, encode_text_line,
12    encode_v2_capability_advertisement,
13};
14use arks_refs::RefTarget;
15use arks_repo::Repository;
16use arks_store::ObjectStore;
17
18/// Capability lines advertised for v2 (commands + agent).
19pub fn v2_capability_lines() -> Vec<String> {
20    // gitprotocol-v2: command features as `fetch=<feature>…` (SP-separated values).
21    // G3 / NET-006 server: advertise `bundle-uri` (command handled below).
22    // Cite: https://git-scm.com/docs/gitprotocol-v2#_bundle_uri
23    vec![
24        "ls-refs".into(),
25        "fetch=ofs-delta".into(),
26        "bundle-uri".into(),
27        "agent=arks/0.0.0".into(),
28        "object-format=sha1".into(),
29    ]
30}
31
32pub fn v2_capability_advertisement() -> Result<Vec<u8>, ServerError> {
33    encode_v2_capability_advertisement(&v2_capability_lines())
34        .map_err(|e| ServerError::Protocol(e.to_string()))
35}
36
37/// Handle a v2 command request body (after capability advertisement).
38///
39/// HTTP (stateless): append response-end-pkt after **fetch** only. Stock Git
40/// `ls-refs` over HTTP (2.39+) errors on response-end immediately after the
41/// listing flush (`unexpected response end packet`); Content-Length close is
42/// enough for that RPC. Cite: gitprotocol-v2 Packet-Line Framing.
43pub fn handle_v2_request(
44    repo: &Repository,
45    body: &[u8],
46    stateless: bool,
47) -> Result<Vec<u8>, ServerError> {
48    let (command, args) = parse_command_request(body)?;
49    let out = match command.as_str() {
50        "ls-refs" => ls_refs(repo, &args)?,
51        "fetch" => fetch_v2(repo, &args)?,
52        "bundle-uri" => bundle_uri_command(repo)?,
53        other => {
54            return Err(ServerError::Protocol(format!(
55                "unknown or unclaimed v2 command: {other}"
56            )));
57        }
58    };
59    // Do not append response-end-pkt: stock Git remote-curl (2.39+) surfaces
60    // `unexpected response end packet` for our claimed ls-refs/fetch subset when
61    // 0002 follows the command flush. HTTP Content-Length end is sufficient.
62    let _ = stateless;
63    Ok(out)
64}
65
66fn parse_command_request(body: &[u8]) -> Result<(String, Vec<String>), ServerError> {
67    let mut offset = 0;
68    let mut command = None;
69    let mut caps_done = false;
70    let mut args = Vec::new();
71    while offset < body.len() {
72        let (packet, n) =
73            decode_packet(&body[offset..]).map_err(|e| ServerError::Protocol(e.to_string()))?;
74        offset += n;
75        match packet {
76            Packet::Flush => break,
77            Packet::Delim => {
78                caps_done = true;
79            }
80            Packet::Data(payload) => {
81                let text =
82                    decode_text_line(&payload).map_err(|e| ServerError::Protocol(e.to_string()))?;
83                if command.is_none() {
84                    if let Some(rest) = text.strip_prefix("command=") {
85                        command = Some(rest.to_string());
86                        continue;
87                    }
88                    return Err(ServerError::Protocol("v2 request missing command=".into()));
89                }
90                if !caps_done {
91                    continue;
92                }
93                args.push(text);
94            }
95            Packet::ResponseEnd => break,
96        }
97    }
98    let command =
99        command.ok_or_else(|| ServerError::Protocol("v2 request missing command".into()))?;
100    Ok((command, args))
101}
102
103fn ls_refs(repo: &Repository, args: &[String]) -> Result<Vec<u8>, ServerError> {
104    let mut want_symrefs = false;
105    let mut prefixes: Vec<String> = Vec::new();
106    for a in args {
107        if a == "symrefs" {
108            want_symrefs = true;
109        } else if let Some(p) = a.strip_prefix("ref-prefix ") {
110            prefixes.push(p.to_string());
111        }
112    }
113
114    let mut refs = repo
115        .refs()
116        .list_refs("refs/")
117        .map_err(|e| ServerError::Msg(e.to_string()))?;
118    refs.sort_by(|a, b| a.0.cmp(&b.0));
119
120    let mut out = Vec::new();
121    match repo.head_target() {
122        Ok(RefTarget::Symbolic(target)) => {
123            if let Ok(oid) = repo.refs().resolve("HEAD") {
124                let mut line = format!("{} HEAD", oid.to_hex());
125                if want_symrefs {
126                    line.push_str(&format!(" symref-target:{target}"));
127                }
128                out.extend(
129                    encode_text_line(&line).map_err(|e| ServerError::Protocol(e.to_string()))?,
130                );
131            }
132        }
133        Ok(RefTarget::Direct(oid)) => {
134            out.extend(
135                encode_text_line(&format!("{} HEAD", oid.to_hex()))
136                    .map_err(|e| ServerError::Protocol(e.to_string()))?,
137            );
138        }
139        Err(_) => {}
140    }
141    for (name, oid) in refs {
142        if !prefixes.is_empty() && !prefixes.iter().any(|p| name.starts_with(p)) {
143            continue;
144        }
145        out.extend(
146            encode_text_line(&format!("{} {name}", oid.to_hex()))
147                .map_err(|e| ServerError::Protocol(e.to_string()))?,
148        );
149    }
150    out.extend(encode_packet(&Packet::Flush).map_err(|e| ServerError::Protocol(e.to_string()))?);
151    Ok(out)
152}
153
154/// Protocol v2 `bundle-uri` command — key=value pkt-lines then flush.
155///
156/// Config: `ARKS_BUNDLE_URI` (comma-separated http(s)/path URIs) and/or
157/// `$GIT_DIR/config` keys `bundle.<id>.uri`. Empty config still returns
158/// `bundle.version=1` so advertise honesty stays Claimable without inventing CDN SLOs.
159fn bundle_uri_command(repo: &Repository) -> Result<Vec<u8>, ServerError> {
160    let mut out =
161        encode_text_line("bundle.version=1").map_err(|e| ServerError::Protocol(e.to_string()))?;
162    out.extend(
163        encode_text_line("bundle.mode=all").map_err(|e| ServerError::Protocol(e.to_string()))?,
164    );
165    let mut n = 0usize;
166    if let Ok(env) = std::env::var("ARKS_BUNDLE_URI") {
167        for uri in env.split(',').map(str::trim).filter(|s| !s.is_empty()) {
168            n += 1;
169            let line = format!("bundle.seed{n}.uri={uri}");
170            out.extend(encode_text_line(&line).map_err(|e| ServerError::Protocol(e.to_string()))?);
171        }
172    }
173    // Optional file: one URI per line under $GIT_DIR/arks-bundle-uris (ops/config).
174    let list = repo.git_dir().join("arks-bundle-uris");
175    if list.is_file() {
176        let text = std::fs::read_to_string(&list).map_err(|e| ServerError::Msg(e.to_string()))?;
177        for uri in text
178            .lines()
179            .map(str::trim)
180            .filter(|s| !s.is_empty() && !s.starts_with('#'))
181        {
182            n += 1;
183            let line = format!("bundle.seed{n}.uri={uri}");
184            out.extend(encode_text_line(&line).map_err(|e| ServerError::Protocol(e.to_string()))?);
185        }
186    }
187    out.extend(encode_packet(&Packet::Flush).map_err(|e| ServerError::Protocol(e.to_string()))?);
188    Ok(out)
189}
190
191fn fetch_v2(repo: &Repository, args: &[String]) -> Result<Vec<u8>, ServerError> {
192    let mut wants = Vec::new();
193    let mut done = false;
194    for a in args {
195        if let Some(hex) = a.strip_prefix("want ") {
196            let oid = Oid::from_hex(hex.trim())
197                .map_err(|e| ServerError::Protocol(format!("want oid: {e}")))?;
198            if !wants.contains(&oid) {
199                wants.push(oid);
200            }
201        } else if a == "done" {
202            done = true;
203        }
204    }
205    if wants.is_empty() {
206        return Err(ServerError::Protocol("fetch without want".into()));
207    }
208    if !done {
209        // Ask client to continue / send done — acknowledgments section + flush.
210        let mut out = encode_text_line("acknowledgments")
211            .map_err(|e| ServerError::Protocol(e.to_string()))?;
212        out.extend(encode_text_line("NAK").map_err(|e| ServerError::Protocol(e.to_string()))?);
213        out.extend(
214            encode_packet(&Packet::Flush).map_err(|e| ServerError::Protocol(e.to_string()))?,
215        );
216        return Ok(out);
217    }
218
219    let get = |oid: &Oid| match repo.store().get(oid) {
220        Ok(obj) => Ok(Some(obj)),
221        Err(arks_store::StoreError::NotFound(_)) => Ok(None),
222        Err(e) => Err(ServerError::Msg(e.to_string())),
223    };
224    let objects = collect_closure(&wants, get)?;
225    let pack = EncodedPack::from_undeltified(repo.object_format(), &objects)
226        .map_err(|e| ServerError::Protocol(format!("pack encode: {e}")))?;
227
228    // done was sent → omit acknowledgments; send packfile section only.
229    let mut out = encode_text_line("packfile").map_err(|e| ServerError::Protocol(e.to_string()))?;
230    const CHUNK: usize = 65_515;
231    for chunk in pack.pack.chunks(CHUNK) {
232        let mut payload = Vec::with_capacity(1 + chunk.len());
233        payload.push(1);
234        payload.extend_from_slice(chunk);
235        out.extend(
236            encode_packet(&Packet::Data(payload))
237                .map_err(|e| ServerError::Protocol(e.to_string()))?,
238        );
239    }
240    out.extend(encode_packet(&Packet::Flush).map_err(|e| ServerError::Protocol(e.to_string()))?);
241    Ok(out)
242}