Skip to main content

arks_protocol/
capabilities.rs

1//! Capability advertise / parse helpers.
2//!
3//! v1 trailer prose: <https://git-scm.com/docs/gitprotocol-capabilities>
4//! (first ref is followed by NUL and a space-delimited capability list).
5//! v2 advertisement shape: <https://git-scm.com/docs/gitprotocol-v2>
6//! (Capability Advertisement).
7//!
8//! This module does not invent capability names. Tokens are caller-supplied
9//! and unknown peer tokens stay opaque strings.
10
11use crate::error::ProtocolError;
12use crate::pkt_line::{Packet, decode_packet, decode_text_line, encode_packets, encode_text_line};
13
14/// Split a space-separated capability trailer into opaque tokens.
15///
16/// One trailing LF is removed when present (the v1 `capability-list LF` trailer
17/// and the v2 per-line LF). Tokens are not checked against a name list.
18/// Repeated SP separators do not produce empty tokens. Order is preserved,
19/// including duplicates (documented forms such as repeated `symref` / `object-format`).
20pub fn parse_capabilities(s: &str) -> Vec<String> {
21    let s = s.strip_suffix('\n').unwrap_or(s);
22    s.split(' ')
23        .filter(|token| !token.is_empty())
24        .map(str::to_string)
25        .collect()
26}
27
28/// Join capability tokens with a single SP, in caller order.
29///
30/// Empty tokens are skipped so the result does not gain extra separators.
31/// Names are not added or rewritten. A token that itself contains SP will
32/// split again in [`parse_capabilities`]; the protocol list is SP-delimited
33/// and this helper does not quote.
34pub fn advertise_capabilities(caps: &[impl AsRef<str>]) -> String {
35    caps.iter()
36        .map(|cap| cap.as_ref())
37        .filter(|cap| !cap.is_empty())
38        .collect::<Vec<_>>()
39        .join(" ")
40}
41
42/// Payload (not yet length-prefixed) of a v1 first-ref / `capabilities^{}` line.
43///
44/// Shape from gitprotocol-capabilities / gitprotocol-pack: `head NUL capability-list LF`.
45/// `head` is caller-supplied (`obj-id SP refname`, or `zero-id SP capabilities^{}`).
46/// The capability list is [`advertise_capabilities`]; this function adds no names.
47pub fn v1_advertisement_payload(head: &str, caps: &[impl AsRef<str>]) -> Vec<u8> {
48    let trailer = advertise_capabilities(caps);
49    let mut out = Vec::with_capacity(head.len() + 1 + trailer.len() + 1);
50    out.extend_from_slice(head.as_bytes());
51    out.push(0);
52    out.extend_from_slice(trailer.as_bytes());
53    out.push(b'\n');
54    out
55}
56
57/// Split a v1 advertisement payload at the first NUL.
58///
59/// Returns `(head, tokens)`. `head` is the bytes before NUL. Tokens come from
60/// the trailer after NUL via [`parse_capabilities`]. A line with no NUL is a
61/// non-capability ref line: head is the payload with one optional trailing LF
62/// removed, and the token list is empty.
63pub fn parse_v1_advertisement_payload(
64    payload: &[u8],
65) -> Result<(Vec<u8>, Vec<String>), ProtocolError> {
66    match payload.iter().position(|&b| b == 0) {
67        Some(nul) => {
68            let head = payload[..nul].to_vec();
69            let trailer = std::str::from_utf8(&payload[nul + 1..])
70                .map_err(|_| ProtocolError::CapabilityUtf8)?;
71            Ok((head, parse_capabilities(trailer)))
72        }
73        None => {
74            let text = std::str::from_utf8(payload).map_err(|_| ProtocolError::CapabilityUtf8)?;
75            let head = text.strip_suffix('\n').unwrap_or(text).as_bytes().to_vec();
76            Ok((head, Vec::new()))
77        }
78    }
79}
80
81/// Encode a v2 capability advertisement.
82///
83/// gitprotocol-v2:
84/// `capability-advertisement = protocol-version capability-list flush-pkt`,
85/// `protocol-version = PKT-LINE("version 2" LF)`,
86/// `capability = PKT-LINE(key[=value] LF)`.
87///
88/// `version 2` is the protocol-version line, not a caller capability.
89/// Each entry of `caps` is one capability line. delim-pkt and response-end-pkt
90/// are not part of this advertisement; callers append those packets themselves.
91pub fn encode_v2_capability_advertisement(
92    caps: &[impl AsRef<str>],
93) -> Result<Vec<u8>, ProtocolError> {
94    let mut packets = Vec::with_capacity(caps.len() + 2);
95    packets.push(text_packet("version 2")?);
96    for cap in caps {
97        let cap = cap.as_ref();
98        if cap.is_empty() {
99            continue;
100        }
101        let line = cap.strip_suffix('\n').unwrap_or(cap);
102        packets.push(text_packet(line)?);
103    }
104    packets.push(Packet::Flush);
105    encode_packets(&packets)
106}
107
108/// Parse a v2 capability advertisement, stopping after its flush-pkt.
109///
110/// Returns `(capability tokens, bytes consumed)`. Bytes after the flush-pkt
111/// are left unconsumed so a later delim-pkt or response-end-pkt can be decoded
112/// separately. The `version 2` line is required and is not returned as a capability.
113pub fn parse_v2_capability_advertisement(
114    input: &[u8],
115) -> Result<(Vec<String>, usize), ProtocolError> {
116    let mut offset = 0;
117    let mut caps = Vec::new();
118    let mut saw_version = false;
119    let mut saw_flush = false;
120    while offset < input.len() {
121        let (packet, n) = decode_packet(&input[offset..])?;
122        offset += n;
123        match packet {
124            Packet::Data(payload) => {
125                let text = decode_text_line(&payload)?;
126                if !saw_version {
127                    if text != "version 2" {
128                        return Err(ProtocolError::MissingProtocolVersion);
129                    }
130                    saw_version = true;
131                } else if !text.is_empty() {
132                    caps.push(text);
133                }
134            }
135            Packet::Flush => {
136                saw_flush = true;
137                break;
138            }
139            Packet::Delim | Packet::ResponseEnd => {
140                return Err(ProtocolError::UnexpectedSpecial);
141            }
142        }
143    }
144    if !saw_version {
145        return Err(ProtocolError::MissingProtocolVersion);
146    }
147    if !saw_flush {
148        return Err(ProtocolError::MissingFlush);
149    }
150    Ok((caps, offset))
151}
152
153fn text_packet(text: &str) -> Result<Packet, ProtocolError> {
154    let wire = encode_text_line(text)?;
155    // encode_text_line writes one data pkt-line; the payload follows the 4 length bytes.
156    Ok(Packet::Data(wire[4..].to_vec()))
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    #[test]
164    fn advertise_parse_roundtrip_preserves_order_and_unknowns() {
165        // Names below are either documented (gitprotocol-capabilities) or an
166        // opaque unknown used to prove there is no allow-list.
167        let caps = [
168            "ofs-delta",
169            "side-band-64k",
170            "agent=git/2.46.0",
171            "not-a-documented-token",
172            "symref=HEAD:refs/heads/master",
173            "symref=refs/remotes/origin/HEAD:refs/heads/master",
174        ];
175        let advertised = advertise_capabilities(&caps);
176        assert_eq!(advertised, caps.join(" "));
177        assert!(!advertised.ends_with(' '));
178        assert_eq!(
179            parse_capabilities(&advertised),
180            caps.iter().map(|s| (*s).to_string()).collect::<Vec<_>>()
181        );
182        assert_eq!(
183            parse_capabilities(&format!("{advertised}\n")),
184            parse_capabilities(&advertised)
185        );
186    }
187
188    #[test]
189    fn empty_and_duplicate_tokens() {
190        assert_eq!(advertise_capabilities(&[] as &[&str]), "");
191        assert!(parse_capabilities("").is_empty());
192        assert!(parse_capabilities("\n").is_empty());
193        assert_eq!(
194            parse_capabilities("ofs-delta  side-band-64k "),
195            vec!["ofs-delta".to_string(), "side-band-64k".to_string()]
196        );
197        let dup = advertise_capabilities(&["object-format=sha1", "object-format=sha256"]);
198        assert_eq!(
199            parse_capabilities(&dup),
200            vec![
201                "object-format=sha1".to_string(),
202                "object-format=sha256".to_string()
203            ]
204        );
205    }
206}