arks-server 1.3.2

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! upload-pack service (fetch/clone path).

use crate::advertise::{
    encode_http_advertisement, encode_pack_advertisement, is_internal_arks_ref,
};
use crate::error::ServerError;
use crate::walk::collect_closure;
use arks_oid::Oid;
use arks_pack::EncodedPack;
use arks_protocol::{Packet, decode_packet, decode_text_line, encode_packet, encode_text_line};
use arks_refs::RefTarget;
use arks_repo::Repository;
use arks_store::{ObjectFormat, ObjectStore};

type RefsAndCaps = (Vec<(String, Oid)>, Vec<String>);
type RefsAndHead = (Vec<(String, Oid)>, Option<String>);

fn upload_caps(repo: &Repository) -> Result<RefsAndCaps, ServerError> {
    let (refs, head) = list_refs_and_head(repo)?;
    let mut caps = vec![
        "ofs-delta".into(),
        "side-band-64k".into(),
        "no-progress".into(),
        "include-tag".into(),
        "agent=arks/0.0.0".into(),
    ];
    if repo.object_format() == ObjectFormat::Sha256 {
        caps.push("object-format=sha256".into());
    }
    if let Some(h) = &head {
        caps.insert(0, format!("symref=HEAD:{h}"));
    }
    Ok((refs, caps))
}

/// Smart-HTTP upload-pack advertisement (`# service=git-upload-pack`).
pub fn upload_advertisement(repo: &Repository) -> Result<Vec<u8>, ServerError> {
    let (refs, caps) = upload_caps(repo)?;
    encode_http_advertisement("git-upload-pack", &caps, &refs)
}

/// Pack-protocol duplex advertisement (SSH / `git://` / stdio) — no HTTP service line.
pub fn upload_pack_advertisement(repo: &Repository) -> Result<Vec<u8>, ServerError> {
    let (refs, caps) = upload_caps(repo)?;
    encode_pack_advertisement(&caps, &refs)
}

pub fn upload_pack_result(repo: &Repository, body: &[u8]) -> Result<Vec<u8>, ServerError> {
    upload_pack_result_with_nak(repo, body, true)
}

/// Like [`upload_pack_result`], but skip the leading NAK when negotiation already
/// sent one (avoids `bad band #78` when the client has entered side-band mode).
pub fn upload_pack_result_with_nak(
    repo: &Repository,
    body: &[u8],
    include_nak: bool,
) -> Result<Vec<u8>, ServerError> {
    let mut wants = parse_wants(body)?;
    let want_sideband = request_wants_sideband(body);
    if request_has_cap(body, "include-tag") {
        include_tags_for(repo, &mut wants)?;
    }
    if wants.is_empty() {
        return if want_sideband {
            sideband_pack(&[], include_nak)
        } else {
            raw_pack_result(&[], include_nak)
        };
    }
    // J-CLONE-LOCAL / bare clone: tips already live in objects/pack/*.pack.
    // Reuse the on-disk pack instead of re-walking + zlib re-encoding undeltified
    // (profile: cgi_wait ≈26ms was almost entirely pack generate).
    if let Some(pack) = try_reuse_on_disk_pack(repo, &wants)? {
        return if want_sideband {
            sideband_pack(&pack, include_nak)
        } else {
            raw_pack_result(&pack, include_nak)
        };
    }
    let get = |oid: &Oid| match repo.store().get(oid) {
        Ok(obj) => Ok(Some(obj)),
        Err(arks_store::StoreError::NotFound(_)) => Ok(None),
        Err(e) => Err(ServerError::Msg(e.to_string())),
    };
    let objects = collect_closure(&wants, get)?;
    let pack = EncodedPack::from_undeltified(repo.object_format(), &objects)
        .map_err(|e| ServerError::Protocol(format!("pack encode: {e}")))?;
    if want_sideband {
        sideband_pack(&pack.pack, include_nak)
    } else {
        raw_pack_result(&pack.pack, include_nak)
    }
}

/// When every `want` is present in a single on-disk pack+idx, return that pack's
/// bytes. Extra objects in the pack are fine (client did not request thin-pack).
fn try_reuse_on_disk_pack(
    repo: &Repository,
    wants: &[Oid],
) -> Result<Option<Vec<u8>>, ServerError> {
    let pack_dir = repo.store().objects_dir().join("pack");
    if !pack_dir.is_dir() {
        return Ok(None);
    }
    let entries = std::fs::read_dir(&pack_dir).map_err(|e| ServerError::Msg(e.to_string()))?;
    for entry in entries {
        let entry = entry.map_err(|e| ServerError::Msg(e.to_string()))?;
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if !name.ends_with(".pack") {
            continue;
        }
        let pack_path = entry.path();
        let idx_path = pack_path.with_extension("idx");
        if !idx_path.is_file() {
            continue;
        }
        let idx_bytes = std::fs::read(&idx_path).map_err(|e| ServerError::Msg(e.to_string()))?;
        let idx = match arks_pack::PackIndex::decode(&idx_bytes, repo.object_format()) {
            Ok(i) => i,
            Err(_) => continue,
        };
        if wants.iter().all(|w| idx.lookup(w).is_some()) {
            let pack = std::fs::read(&pack_path).map_err(|e| ServerError::Msg(e.to_string()))?;
            if std::env::var_os("ARKS_SERVER_PROFILE").is_some() {
                eprintln!(
                    "UPLOAD_PACK_REUSE path={} wants={} bytes={}",
                    pack_path.display(),
                    wants.len(),
                    pack.len()
                );
            }
            return Ok(Some(pack));
        }
    }
    Ok(None)
}

fn list_refs_and_head(repo: &Repository) -> Result<RefsAndHead, ServerError> {
    let mut refs = repo
        .refs()
        .list_refs("refs/")
        .map_err(|e| ServerError::Msg(e.to_string()))?;
    refs.retain(|(name, _)| !is_internal_arks_ref(name));
    refs.sort_by(|a, b| a.0.cmp(&b.0));
    let head = match repo.head_target() {
        Ok(RefTarget::Symbolic(t)) => {
            if is_internal_arks_ref(&t) {
                None
            } else {
                if let Ok(oid) = repo.refs().resolve("HEAD") {
                    if !refs.iter().any(|(n, _)| n == "HEAD") {
                        refs.insert(0, ("HEAD".into(), oid));
                    }
                }
                Some(t)
            }
        }
        Ok(RefTarget::Direct(oid)) => {
            if !refs.iter().any(|(n, _)| n == "HEAD") {
                refs.insert(0, ("HEAD".into(), oid));
            }
            None
        }
        Err(_) => None,
    };
    Ok((refs, head))
}

fn parse_wants(body: &[u8]) -> Result<Vec<Oid>, ServerError> {
    let mut offset = 0;
    let mut wants = Vec::new();
    while offset < body.len() {
        let (packet, n) =
            decode_packet(&body[offset..]).map_err(|e| ServerError::Protocol(e.to_string()))?;
        offset += n;
        match packet {
            Packet::Flush => {
                // continue for have/done after flush
            }
            Packet::Data(payload) => {
                let text =
                    decode_text_line(&payload).map_err(|e| ServerError::Protocol(e.to_string()))?;
                if let Some(rest) = text.strip_prefix("want ") {
                    let hex = rest.split_whitespace().next().unwrap_or("");
                    let oid = Oid::from_hex(hex)
                        .map_err(|e| ServerError::Protocol(format!("want oid: {e}")))?;
                    if !wants.contains(&oid) {
                        wants.push(oid);
                    }
                } else if text.starts_with("have ") || text == "done" {
                    // ignore negotiation detail for claimed undeltified full pack
                }
            }
            _ => {}
        }
    }
    Ok(wants)
}

/// True when the first `want` line lists `side-band` / `side-band-64k`.
/// gitprotocol-capabilities `include-tag`: send every annotated tag (and the
/// tags it points to) whose peeled object is a commit the pack already holds,
/// so a client that auto-follows tags gets the tag objects in the same pack.
fn include_tags_for(repo: &Repository, wants: &mut Vec<Oid>) -> Result<(), ServerError> {
    let tags = repo
        .refs()
        .list_refs("refs/tags/")
        .map_err(|e| ServerError::Msg(e.to_string()))?;
    let mut annotated: Vec<(Oid, Oid)> = Vec::new();
    for (name, oid) in &tags {
        if is_internal_arks_ref(name) {
            continue;
        }
        if let Some(peeled) = peel_annotated(repo, oid)? {
            annotated.push((*oid, peeled));
        }
    }
    if annotated.is_empty() {
        return Ok(());
    }
    let reachable = reachable_commits(repo, wants)?;
    for (tag, peeled) in annotated {
        if reachable.contains(&peeled) && !wants.contains(&tag) {
            wants.push(tag);
        }
    }
    Ok(())
}

/// The non-tag object an annotated tag (chain) points to; `None` when `oid`
/// is not a tag object (a lightweight tag needs no extra object).
fn peel_annotated(repo: &Repository, oid: &Oid) -> Result<Option<Oid>, ServerError> {
    let mut cur = *oid;
    let mut seen_tag = false;
    for _ in 0..32 {
        let obj = match repo.store().get(&cur) {
            Ok(o) => o,
            Err(arks_store::StoreError::NotFound(_)) => return Ok(None),
            Err(e) => return Err(ServerError::Msg(e.to_string())),
        };
        if obj.kind != arks_object::ObjectKind::Tag {
            return Ok(seen_tag.then_some(cur));
        }
        seen_tag = true;
        let target = std::str::from_utf8(&obj.payload)
            .ok()
            .and_then(|t| t.lines().find_map(|l| l.strip_prefix("object ")))
            .and_then(|h| Oid::from_hex(h.trim()).ok());
        match target {
            Some(t) => cur = t,
            None => return Ok(None),
        }
    }
    Ok(None)
}

/// Commits reachable from `tips` (tag tips peeled), walking parents only.
fn reachable_commits(
    repo: &Repository,
    tips: &[Oid],
) -> Result<std::collections::HashSet<Oid>, ServerError> {
    let mut seen = std::collections::HashSet::new();
    let mut stack: Vec<Oid> = Vec::new();
    for tip in tips {
        stack.push(peel_annotated(repo, tip)?.unwrap_or(*tip));
    }
    while let Some(oid) = stack.pop() {
        if !seen.insert(oid) {
            continue;
        }
        let obj = match repo.store().get(&oid) {
            Ok(o) => o,
            Err(arks_store::StoreError::NotFound(_)) => continue,
            Err(e) => return Err(ServerError::Msg(e.to_string())),
        };
        if obj.kind != arks_object::ObjectKind::Commit {
            continue;
        }
        let commit = arks_object::Commit::decode(&obj.payload)
            .map_err(|e| ServerError::Protocol(e.to_string()))?;
        stack.extend(commit.parents);
    }
    Ok(seen)
}

/// Whether the first `want` line of the request lists capability `cap`.
fn request_has_cap(body: &[u8], cap: &str) -> bool {
    let mut offset = 0;
    while offset < body.len() {
        let Ok((packet, n)) = decode_packet(&body[offset..]) else {
            break;
        };
        offset += n;
        match packet {
            Packet::Flush => break,
            Packet::Data(payload) => {
                let Ok(text) = decode_text_line(&payload) else {
                    continue;
                };
                if let Some(rest) = text.strip_prefix("want ") {
                    return rest.split_whitespace().any(|c| c == cap);
                }
            }
            _ => {}
        }
    }
    false
}

fn request_wants_sideband(body: &[u8]) -> bool {
    let mut offset = 0;
    while offset < body.len() {
        let Ok((packet, n)) = decode_packet(&body[offset..]) else {
            break;
        };
        offset += n;
        match packet {
            Packet::Flush => break,
            Packet::Data(payload) => {
                let Ok(text) = decode_text_line(&payload) else {
                    continue;
                };
                if let Some(rest) = text.strip_prefix("want ") {
                    return rest
                        .split_whitespace()
                        .any(|c| c == "side-band" || c == "side-band-64k");
                }
            }
            _ => {}
        }
    }
    false
}

fn sideband_pack(pack: &[u8], include_nak: bool) -> Result<Vec<u8>, ServerError> {
    // Optional final NAK then side-band-64k pack (gitprotocol-pack).
    let mut out = Vec::new();
    if include_nak {
        out.extend(encode_text_line("NAK").map_err(|e| ServerError::Protocol(e.to_string()))?);
    }
    const CHUNK: usize = 65_514; // 1 band byte + payload ≤ 65516
    for chunk in pack.chunks(CHUNK) {
        let mut payload = Vec::with_capacity(1 + chunk.len());
        payload.push(1); // side-band stream 1 = pack data
        payload.extend_from_slice(chunk);
        out.extend(
            encode_packet(&Packet::Data(payload))
                .map_err(|e| ServerError::Protocol(e.to_string()))?,
        );
    }
    out.extend(encode_packet(&Packet::Flush).map_err(|e| ServerError::Protocol(e.to_string()))?);
    Ok(out)
}

/// NAK (optional) + raw PACK when the client omitted side-band caps.
fn raw_pack_result(pack: &[u8], include_nak: bool) -> Result<Vec<u8>, ServerError> {
    let mut out = Vec::with_capacity(pack.len() + 8);
    if include_nak {
        out.extend(encode_text_line("NAK").map_err(|e| ServerError::Protocol(e.to_string()))?);
    }
    out.extend_from_slice(pack);
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use arks_object::{Commit, ObjectKind, RawObject, Signature, Tree, TreeEntry, TreeMode};
    use tempfile::TempDir;

    fn seed_repo_with_internal_refs() -> (TempDir, Repository, Oid) {
        let dir = TempDir::new().unwrap();
        let git = dir.path();
        std::fs::create_dir_all(git.join("objects")).unwrap();
        std::fs::create_dir_all(git.join("refs/heads")).unwrap();
        std::fs::write(git.join("HEAD"), b"ref: refs/heads/main\n").unwrap();
        let mut repo = Repository::open(git).unwrap();
        let blob = repo
            .store_mut()
            .put(
                ObjectFormat::Sha1,
                &RawObject::new(ObjectKind::Blob, b"hello\n".to_vec()),
            )
            .unwrap();
        let tree = Tree::new(vec![TreeEntry {
            mode: TreeMode::File,
            name: "a.txt".into(),
            oid: blob,
        }])
        .unwrap();
        let tree_oid = repo
            .store_mut()
            .put(
                ObjectFormat::Sha1,
                &RawObject::new(ObjectKind::Tree, tree.encode().unwrap()),
            )
            .unwrap();
        let sig = Signature {
            name: "arks".into(),
            email: "arks@example.invalid".into(),
            timestamp: 1_700_000_000,
            timezone: "+0000".into(),
        };
        let commit = Commit {
            tree: tree_oid,
            parents: Vec::new(),
            author: sig.clone(),
            committer: sig,
            gpgsig: None,
            message: "init\n".into(),
        };
        let oid = repo
            .store_mut()
            .put(
                ObjectFormat::Sha1,
                &RawObject::new(ObjectKind::Commit, commit.encode().unwrap()),
            )
            .unwrap();
        repo.refs_mut()
            .update("refs/heads/main", &oid, None)
            .unwrap();
        repo.refs_mut()
            .update("refs/arks/v2/keep/pin1", &oid, None)
            .unwrap();
        repo.refs_mut()
            .update("refs/arks/internal/alice/change1", &oid, None)
            .unwrap();
        (dir, repo, oid)
    }

    #[test]
    fn upload_advertisements_hide_internal_arks_refs() {
        let (_dir, repo, _oid) = seed_repo_with_internal_refs();
        let http_ad = String::from_utf8_lossy(&upload_advertisement(&repo).unwrap()).into_owned();
        assert!(http_ad.contains("refs/heads/main"), "{http_ad}");
        assert!(!http_ad.contains("refs/arks/"), "{http_ad}");

        let pack_ad =
            String::from_utf8_lossy(&upload_pack_advertisement(&repo).unwrap()).into_owned();
        assert!(pack_ad.contains("refs/heads/main"), "{pack_ad}");
        assert!(!pack_ad.contains("refs/arks/"), "{pack_ad}");
    }
}