Skip to main content

arks_server/
upload.rs

1//! upload-pack service (fetch/clone path).
2
3use crate::advertise::{encode_http_advertisement, encode_pack_advertisement};
4use crate::error::ServerError;
5use crate::walk::collect_closure;
6use arks_oid::Oid;
7use arks_pack::EncodedPack;
8use arks_protocol::{Packet, decode_packet, decode_text_line, encode_packet, encode_text_line};
9use arks_refs::RefTarget;
10use arks_repo::Repository;
11use arks_store::ObjectStore;
12
13type RefsAndCaps = (Vec<(String, Oid)>, Vec<String>);
14type RefsAndHead = (Vec<(String, Oid)>, Option<String>);
15
16fn upload_caps(repo: &Repository) -> Result<RefsAndCaps, ServerError> {
17    let (refs, head) = list_refs_and_head(repo)?;
18    let mut caps = vec![
19        "ofs-delta".into(),
20        "side-band-64k".into(),
21        "no-progress".into(),
22        "include-tag".into(),
23        "agent=arks/0.0.0".into(),
24    ];
25    if let Some(h) = &head {
26        caps.insert(0, format!("symref=HEAD:{h}"));
27    }
28    Ok((refs, caps))
29}
30
31/// Smart-HTTP upload-pack advertisement (`# service=git-upload-pack`).
32pub fn upload_advertisement(repo: &Repository) -> Result<Vec<u8>, ServerError> {
33    let (refs, caps) = upload_caps(repo)?;
34    encode_http_advertisement("git-upload-pack", &caps, &refs)
35}
36
37/// Pack-protocol duplex advertisement (SSH / `git://` / stdio) — no HTTP service line.
38pub fn upload_pack_advertisement(repo: &Repository) -> Result<Vec<u8>, ServerError> {
39    let (refs, caps) = upload_caps(repo)?;
40    encode_pack_advertisement(&caps, &refs)
41}
42
43pub fn upload_pack_result(repo: &Repository, body: &[u8]) -> Result<Vec<u8>, ServerError> {
44    upload_pack_result_with_nak(repo, body, true)
45}
46
47/// Like [`upload_pack_result`], but skip the leading NAK when negotiation already
48/// sent one (avoids `bad band #78` when the client has entered side-band mode).
49pub fn upload_pack_result_with_nak(
50    repo: &Repository,
51    body: &[u8],
52    include_nak: bool,
53) -> Result<Vec<u8>, ServerError> {
54    let mut wants = parse_wants(body)?;
55    let want_sideband = request_wants_sideband(body);
56    if request_has_cap(body, "include-tag") {
57        include_tags_for(repo, &mut wants)?;
58    }
59    if wants.is_empty() {
60        return if want_sideband {
61            sideband_pack(&[], include_nak)
62        } else {
63            raw_pack_result(&[], include_nak)
64        };
65    }
66    // J-CLONE-LOCAL / bare clone: tips already live in objects/pack/*.pack.
67    // Reuse the on-disk pack instead of re-walking + zlib re-encoding undeltified
68    // (profile: cgi_wait ≈26ms was almost entirely pack generate).
69    if let Some(pack) = try_reuse_on_disk_pack(repo, &wants)? {
70        return if want_sideband {
71            sideband_pack(&pack, include_nak)
72        } else {
73            raw_pack_result(&pack, include_nak)
74        };
75    }
76    let get = |oid: &Oid| match repo.store().get(oid) {
77        Ok(obj) => Ok(Some(obj)),
78        Err(arks_store::StoreError::NotFound(_)) => Ok(None),
79        Err(e) => Err(ServerError::Msg(e.to_string())),
80    };
81    let objects = collect_closure(&wants, get)?;
82    let pack = EncodedPack::from_undeltified(repo.object_format(), &objects)
83        .map_err(|e| ServerError::Protocol(format!("pack encode: {e}")))?;
84    if want_sideband {
85        sideband_pack(&pack.pack, include_nak)
86    } else {
87        raw_pack_result(&pack.pack, include_nak)
88    }
89}
90
91/// When every `want` is present in a single on-disk pack+idx, return that pack's
92/// bytes. Extra objects in the pack are fine (client did not request thin-pack).
93fn try_reuse_on_disk_pack(
94    repo: &Repository,
95    wants: &[Oid],
96) -> Result<Option<Vec<u8>>, ServerError> {
97    let pack_dir = repo.store().objects_dir().join("pack");
98    if !pack_dir.is_dir() {
99        return Ok(None);
100    }
101    let entries = std::fs::read_dir(&pack_dir).map_err(|e| ServerError::Msg(e.to_string()))?;
102    for entry in entries {
103        let entry = entry.map_err(|e| ServerError::Msg(e.to_string()))?;
104        let name = entry.file_name();
105        let name = name.to_string_lossy();
106        if !name.ends_with(".pack") {
107            continue;
108        }
109        let pack_path = entry.path();
110        let idx_path = pack_path.with_extension("idx");
111        if !idx_path.is_file() {
112            continue;
113        }
114        let idx_bytes = std::fs::read(&idx_path).map_err(|e| ServerError::Msg(e.to_string()))?;
115        let idx = match arks_pack::PackIndex::decode(&idx_bytes, repo.object_format()) {
116            Ok(i) => i,
117            Err(_) => continue,
118        };
119        if wants.iter().all(|w| idx.lookup(w).is_some()) {
120            let pack = std::fs::read(&pack_path).map_err(|e| ServerError::Msg(e.to_string()))?;
121            if std::env::var_os("ARKS_SERVER_PROFILE").is_some() {
122                eprintln!(
123                    "UPLOAD_PACK_REUSE path={} wants={} bytes={}",
124                    pack_path.display(),
125                    wants.len(),
126                    pack.len()
127                );
128            }
129            return Ok(Some(pack));
130        }
131    }
132    Ok(None)
133}
134
135fn list_refs_and_head(repo: &Repository) -> Result<RefsAndHead, ServerError> {
136    let mut refs = repo
137        .refs()
138        .list_refs("refs/")
139        .map_err(|e| ServerError::Msg(e.to_string()))?;
140    refs.sort_by(|a, b| a.0.cmp(&b.0));
141    let head = match repo.head_target() {
142        Ok(RefTarget::Symbolic(t)) => {
143            if let Ok(oid) = repo.refs().resolve("HEAD") {
144                if !refs.iter().any(|(n, _)| n == "HEAD") {
145                    refs.insert(0, ("HEAD".into(), oid));
146                }
147            }
148            Some(t)
149        }
150        Ok(RefTarget::Direct(oid)) => {
151            if !refs.iter().any(|(n, _)| n == "HEAD") {
152                refs.insert(0, ("HEAD".into(), oid));
153            }
154            None
155        }
156        Err(_) => None,
157    };
158    Ok((refs, head))
159}
160
161fn parse_wants(body: &[u8]) -> Result<Vec<Oid>, ServerError> {
162    let mut offset = 0;
163    let mut wants = Vec::new();
164    while offset < body.len() {
165        let (packet, n) =
166            decode_packet(&body[offset..]).map_err(|e| ServerError::Protocol(e.to_string()))?;
167        offset += n;
168        match packet {
169            Packet::Flush => {
170                // continue for have/done after flush
171            }
172            Packet::Data(payload) => {
173                let text =
174                    decode_text_line(&payload).map_err(|e| ServerError::Protocol(e.to_string()))?;
175                if let Some(rest) = text.strip_prefix("want ") {
176                    let hex = rest.split_whitespace().next().unwrap_or("");
177                    let oid = Oid::from_hex(hex)
178                        .map_err(|e| ServerError::Protocol(format!("want oid: {e}")))?;
179                    if !wants.contains(&oid) {
180                        wants.push(oid);
181                    }
182                } else if text.starts_with("have ") || text == "done" {
183                    // ignore negotiation detail for claimed undeltified full pack
184                }
185            }
186            _ => {}
187        }
188    }
189    Ok(wants)
190}
191
192/// True when the first `want` line lists `side-band` / `side-band-64k`.
193/// gitprotocol-capabilities `include-tag`: send every annotated tag (and the
194/// tags it points to) whose peeled object is a commit the pack already holds,
195/// so a client that auto-follows tags gets the tag objects in the same pack.
196fn include_tags_for(repo: &Repository, wants: &mut Vec<Oid>) -> Result<(), ServerError> {
197    let tags = repo
198        .refs()
199        .list_refs("refs/tags/")
200        .map_err(|e| ServerError::Msg(e.to_string()))?;
201    let mut annotated: Vec<(Oid, Oid)> = Vec::new();
202    for (_, oid) in &tags {
203        if let Some(peeled) = peel_annotated(repo, oid)? {
204            annotated.push((*oid, peeled));
205        }
206    }
207    if annotated.is_empty() {
208        return Ok(());
209    }
210    let reachable = reachable_commits(repo, wants)?;
211    for (tag, peeled) in annotated {
212        if reachable.contains(&peeled) && !wants.contains(&tag) {
213            wants.push(tag);
214        }
215    }
216    Ok(())
217}
218
219/// The non-tag object an annotated tag (chain) points to; `None` when `oid`
220/// is not a tag object (a lightweight tag needs no extra object).
221fn peel_annotated(repo: &Repository, oid: &Oid) -> Result<Option<Oid>, ServerError> {
222    let mut cur = *oid;
223    let mut seen_tag = false;
224    for _ in 0..32 {
225        let obj = match repo.store().get(&cur) {
226            Ok(o) => o,
227            Err(arks_store::StoreError::NotFound(_)) => return Ok(None),
228            Err(e) => return Err(ServerError::Msg(e.to_string())),
229        };
230        if obj.kind != arks_object::ObjectKind::Tag {
231            return Ok(seen_tag.then_some(cur));
232        }
233        seen_tag = true;
234        let target = std::str::from_utf8(&obj.payload)
235            .ok()
236            .and_then(|t| t.lines().find_map(|l| l.strip_prefix("object ")))
237            .and_then(|h| Oid::from_hex(h.trim()).ok());
238        match target {
239            Some(t) => cur = t,
240            None => return Ok(None),
241        }
242    }
243    Ok(None)
244}
245
246/// Commits reachable from `tips` (tag tips peeled), walking parents only.
247fn reachable_commits(
248    repo: &Repository,
249    tips: &[Oid],
250) -> Result<std::collections::HashSet<Oid>, ServerError> {
251    let mut seen = std::collections::HashSet::new();
252    let mut stack: Vec<Oid> = Vec::new();
253    for tip in tips {
254        stack.push(peel_annotated(repo, tip)?.unwrap_or(*tip));
255    }
256    while let Some(oid) = stack.pop() {
257        if !seen.insert(oid) {
258            continue;
259        }
260        let obj = match repo.store().get(&oid) {
261            Ok(o) => o,
262            Err(arks_store::StoreError::NotFound(_)) => continue,
263            Err(e) => return Err(ServerError::Msg(e.to_string())),
264        };
265        if obj.kind != arks_object::ObjectKind::Commit {
266            continue;
267        }
268        let commit = arks_object::Commit::decode(&obj.payload)
269            .map_err(|e| ServerError::Protocol(e.to_string()))?;
270        stack.extend(commit.parents);
271    }
272    Ok(seen)
273}
274
275/// Whether the first `want` line of the request lists capability `cap`.
276fn request_has_cap(body: &[u8], cap: &str) -> bool {
277    let mut offset = 0;
278    while offset < body.len() {
279        let Ok((packet, n)) = decode_packet(&body[offset..]) else {
280            break;
281        };
282        offset += n;
283        match packet {
284            Packet::Flush => break,
285            Packet::Data(payload) => {
286                let Ok(text) = decode_text_line(&payload) else {
287                    continue;
288                };
289                if let Some(rest) = text.strip_prefix("want ") {
290                    return rest.split_whitespace().any(|c| c == cap);
291                }
292            }
293            _ => {}
294        }
295    }
296    false
297}
298
299fn request_wants_sideband(body: &[u8]) -> bool {
300    let mut offset = 0;
301    while offset < body.len() {
302        let Ok((packet, n)) = decode_packet(&body[offset..]) else {
303            break;
304        };
305        offset += n;
306        match packet {
307            Packet::Flush => break,
308            Packet::Data(payload) => {
309                let Ok(text) = decode_text_line(&payload) else {
310                    continue;
311                };
312                if let Some(rest) = text.strip_prefix("want ") {
313                    return rest
314                        .split_whitespace()
315                        .any(|c| c == "side-band" || c == "side-band-64k");
316                }
317            }
318            _ => {}
319        }
320    }
321    false
322}
323
324fn sideband_pack(pack: &[u8], include_nak: bool) -> Result<Vec<u8>, ServerError> {
325    // Optional final NAK then side-band-64k pack (gitprotocol-pack).
326    let mut out = Vec::new();
327    if include_nak {
328        out.extend(encode_text_line("NAK").map_err(|e| ServerError::Protocol(e.to_string()))?);
329    }
330    const CHUNK: usize = 65_514; // 1 band byte + payload ≤ 65516
331    for chunk in pack.chunks(CHUNK) {
332        let mut payload = Vec::with_capacity(1 + chunk.len());
333        payload.push(1); // side-band stream 1 = pack data
334        payload.extend_from_slice(chunk);
335        out.extend(
336            encode_packet(&Packet::Data(payload))
337                .map_err(|e| ServerError::Protocol(e.to_string()))?,
338        );
339    }
340    out.extend(encode_packet(&Packet::Flush).map_err(|e| ServerError::Protocol(e.to_string()))?);
341    Ok(out)
342}
343
344/// NAK (optional) + raw PACK when the client omitted side-band caps.
345fn raw_pack_result(pack: &[u8], include_nak: bool) -> Result<Vec<u8>, ServerError> {
346    let mut out = Vec::with_capacity(pack.len() + 8);
347    if include_nak {
348        out.extend(encode_text_line("NAK").map_err(|e| ServerError::Protocol(e.to_string()))?);
349    }
350    out.extend_from_slice(pack);
351    Ok(out)
352}