Skip to main content

arks_server/
upload.rs

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