arks-server 1.3.4

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
Documentation
//! Pure-Rust source archive downloads (`.tar.gz` and `.zip`) and raw `.patch`/`.diff`
//! endpoints for `arks serve` Web UI (zero stock `git` subprocesses).

use super::{load_blob, load_commit, resolve_rev_oid};
use crate::http::HttpResponse;
use arks_repo::{Repository, commit_tree_map};
use flate2::Compression;
use flate2::write::GzEncoder;
use std::io::Write;

/// Handle `GET /archive/<rev>.tar.gz` or `GET /archive/<rev>.zip`.
pub fn handle_archive_download(repo: &Repository, repo_name: &str, file: &str) -> HttpResponse {
    let (rev, is_zip) = if let Some(r) = file.strip_suffix(".tar.gz") {
        (r, false)
    } else if let Some(r) = file.strip_suffix(".zip") {
        (r, true)
    } else {
        return HttpResponse {
            status: 400,
            content_type: "text/plain; charset=utf-8".into(),
            body: b"Supported archive formats: .tar.gz and .zip\n".to_vec(),
            www_authenticate: None,
            extra_headers: Vec::new(),
        };
    };

    let Some(oid) = resolve_rev_oid(repo, rev) else {
        return HttpResponse {
            status: 404,
            content_type: "text/plain; charset=utf-8".into(),
            body: format!("Revision not found: {rev}\n").into_bytes(),
            www_authenticate: None,
            extra_headers: Vec::new(),
        };
    };
    let Ok(tree_map) = commit_tree_map(repo, &oid) else {
        return HttpResponse {
            status: 500,
            content_type: "text/plain; charset=utf-8".into(),
            body: b"Failed to read repository tree\n".to_vec(),
            www_authenticate: None,
            extra_headers: Vec::new(),
        };
    };

    let safe_prefix = format!(
        "{}-{}",
        repo_name
            .chars()
            .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_')
            .collect::<String>(),
        rev.chars()
            .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_' || *c == '.')
            .collect::<String>()
    );

    let mut entries: Vec<(String, Vec<u8>)> = Vec::with_capacity(tree_map.len());
    for (path, blob_oid) in &tree_map {
        if let Some(bytes) = load_blob(repo, blob_oid) {
            entries.push((format!("{safe_prefix}/{path}"), bytes));
        }
    }

    if is_zip {
        let zip_bytes = build_zip_store(&entries);
        HttpResponse {
            status: 200,
            content_type: "application/zip".into(),
            body: zip_bytes,
            www_authenticate: None,
            extra_headers: vec![
                (
                    "Content-Disposition".into(),
                    format!("attachment; filename=\"{safe_prefix}.zip\""),
                ),
                ("X-Content-Type-Options".into(), "nosniff".into()),
            ],
        }
    } else {
        let targz_bytes = build_tar_gz(&entries);
        HttpResponse {
            status: 200,
            content_type: "application/gzip".into(),
            body: targz_bytes,
            www_authenticate: None,
            extra_headers: vec![
                (
                    "Content-Disposition".into(),
                    format!("attachment; filename=\"{safe_prefix}.tar.gz\""),
                ),
                ("X-Content-Type-Options".into(), "nosniff".into()),
            ],
        }
    }
}

/// Build a pure-Rust USTAR `.tar.gz` archive.
pub fn build_tar_gz(entries: &[(String, Vec<u8>)]) -> Vec<u8> {
    let mut enc = GzEncoder::new(Vec::new(), Compression::default());
    for (name, data) in entries {
        let mut hdr = [0u8; 512];
        let name_bytes = name.as_bytes();
        let copy_len = name_bytes.len().min(100);
        hdr[..copy_len].copy_from_slice(&name_bytes[..copy_len]);
        hdr[100..108].copy_from_slice(b"0000644\0");
        hdr[108..116].copy_from_slice(b"0000000\0");
        hdr[116..124].copy_from_slice(b"0000000\0");
        let size_oct = format!("{:011o}\0", data.len());
        hdr[124..136].copy_from_slice(size_oct.as_bytes());
        hdr[136..148].copy_from_slice(b"00000000000\0");
        hdr[148..156].copy_from_slice(b"        ");
        hdr[156] = b'0';
        hdr[257..263].copy_from_slice(b"ustar\0");
        hdr[263..265].copy_from_slice(b"00");
        let chksum: u32 = hdr.iter().map(|&b| b as u32).sum();
        let chk_oct = format!("{chksum:06o}\0 ");
        hdr[148..156].copy_from_slice(chk_oct.as_bytes());

        let _ = enc.write_all(&hdr);
        let _ = enc.write_all(data);
        let rem = data.len() % 512;
        if rem != 0 {
            let pad = vec![0u8; 512 - rem];
            let _ = enc.write_all(&pad);
        }
    }
    let _ = enc.write_all(&[0u8; 1024]);
    enc.finish().unwrap_or_default()
}

fn crc32_ieee(data: &[u8]) -> u32 {
    let mut crc = 0xFFFF_FFFFu32;
    for &b in data {
        crc ^= b as u32;
        for _ in 0..8 {
            if crc & 1 != 0 {
                crc = (crc >> 1) ^ 0xEDB8_8320;
            } else {
                crc >>= 1;
            }
        }
    }
    !crc
}

/// Build a pure-Rust Store-method (compression=0) `.zip` archive.
pub fn build_zip_store(entries: &[(String, Vec<u8>)]) -> Vec<u8> {
    let mut out = Vec::new();
    let mut central = Vec::new();
    for (name, data) in entries {
        let offset = out.len() as u32;
        let crc = crc32_ieee(data);
        let size = data.len() as u32;
        let name_b = name.as_bytes();
        let name_len = name_b.len() as u16;

        // Local file header
        out.extend_from_slice(&0x0403_4B50u32.to_le_bytes());
        out.extend_from_slice(&20u16.to_le_bytes()); // version needed
        out.extend_from_slice(&0u16.to_le_bytes()); // flags
        out.extend_from_slice(&0u16.to_le_bytes()); // method: store
        out.extend_from_slice(&0u16.to_le_bytes()); // mod time
        out.extend_from_slice(&0u16.to_le_bytes()); // mod date
        out.extend_from_slice(&crc.to_le_bytes());
        out.extend_from_slice(&size.to_le_bytes());
        out.extend_from_slice(&size.to_le_bytes());
        out.extend_from_slice(&name_len.to_le_bytes());
        out.extend_from_slice(&0u16.to_le_bytes()); // extra len
        out.extend_from_slice(name_b);
        out.extend_from_slice(data);

        // Central directory entry
        central.extend_from_slice(&0x0201_4B50u32.to_le_bytes());
        central.extend_from_slice(&20u16.to_le_bytes());
        central.extend_from_slice(&20u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&crc.to_le_bytes());
        central.extend_from_slice(&size.to_le_bytes());
        central.extend_from_slice(&size.to_le_bytes());
        central.extend_from_slice(&name_len.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&0u16.to_le_bytes());
        central.extend_from_slice(&0u32.to_le_bytes());
        central.extend_from_slice(&offset.to_le_bytes());
        central.extend_from_slice(name_b);
    }

    let cd_offset = out.len() as u32;
    let cd_size = central.len() as u32;
    let count = entries.len() as u16;
    out.extend_from_slice(&central);

    // End of central directory record
    out.extend_from_slice(&0x0605_4B50u32.to_le_bytes());
    out.extend_from_slice(&0u16.to_le_bytes());
    out.extend_from_slice(&0u16.to_le_bytes());
    out.extend_from_slice(&count.to_le_bytes());
    out.extend_from_slice(&count.to_le_bytes());
    out.extend_from_slice(&cd_size.to_le_bytes());
    out.extend_from_slice(&cd_offset.to_le_bytes());
    out.extend_from_slice(&0u16.to_le_bytes());
    out
}

/// Render raw unified diff between two commit OIDs (or empty tree if `base_oid` is `None`).
fn render_raw_unified_diff(
    repo: &Repository,
    base_oid: Option<&arks_oid::Oid>,
    head_oid: &arks_oid::Oid,
) -> String {
    let base_map = base_oid
        .and_then(|o| commit_tree_map(repo, o).ok())
        .unwrap_or_default();
    let head_map = commit_tree_map(repo, head_oid).unwrap_or_default();
    let mut all_paths: std::collections::BTreeSet<&String> = std::collections::BTreeSet::new();
    for k in base_map.keys() {
        all_paths.insert(k);
    }
    for k in head_map.keys() {
        all_paths.insert(k);
    }
    let mut out = String::new();
    for path in all_paths {
        let a_oid = base_map.get(path);
        let b_oid = head_map.get(path);
        if a_oid == b_oid {
            continue;
        }
        let a_text = a_oid
            .and_then(|o| load_blob(repo, o))
            .map(|b| String::from_utf8_lossy(&b).into_owned())
            .unwrap_or_default();
        let b_text = b_oid
            .and_then(|o| load_blob(repo, o))
            .map(|b| String::from_utf8_lossy(&b).into_owned())
            .unwrap_or_default();
        out.push_str(&format!("diff --git a/{path} b/{path}\n"));
        out.push_str(&format!("--- a/{path}\n+++ b/{path}\n"));
        for line in a_text.lines() {
            out.push_str(&format!("-{line}\n"));
        }
        for line in b_text.lines() {
            out.push_str(&format!("+{line}\n"));
        }
    }
    out
}

/// Handle `GET /commit/<rev>.patch` or `GET /commit/<rev>.diff`.
pub fn handle_commit_patch(repo: &Repository, rev: &str, as_patch: bool) -> HttpResponse {
    let Some(oid) = resolve_rev_oid(repo, rev) else {
        return HttpResponse {
            status: 404,
            content_type: "text/plain; charset=utf-8".into(),
            body: b"Commit not found\n".to_vec(),
            www_authenticate: None,
            extra_headers: Vec::new(),
        };
    };
    let Some(commit) = load_commit(repo, &oid) else {
        return HttpResponse {
            status: 404,
            content_type: "text/plain; charset=utf-8".into(),
            body: b"Commit object not found\n".to_vec(),
            www_authenticate: None,
            extra_headers: Vec::new(),
        };
    };
    let parent = commit.parents.first();
    let diff = render_raw_unified_diff(repo, parent, &oid);
    let body = if as_patch {
        let subject = commit.message.lines().next().unwrap_or("(no subject)");
        format!(
            "From {} Mon Sep 17 00:00:00 2001\nFrom: {} <{}>\nSubject: [PATCH] {}\n\n---\n{}",
            oid, commit.author.name, commit.author.email, subject, diff
        )
    } else {
        diff
    };
    HttpResponse {
        status: 200,
        content_type: "text/plain; charset=utf-8".into(),
        body: body.into_bytes(),
        www_authenticate: None,
        extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
    }
}

/// Handle `GET /pulls/<branch>.diff` or `GET /pulls/<branch>.patch`.
pub fn handle_pr_patch(
    repo: &Repository,
    default_branch: &str,
    branch: &str,
    as_patch: bool,
) -> HttpResponse {
    let Some(head_oid) = resolve_rev_oid(repo, branch) else {
        return HttpResponse {
            status: 404,
            content_type: "text/plain; charset=utf-8".into(),
            body: b"Branch not found\n".to_vec(),
            www_authenticate: None,
            extra_headers: Vec::new(),
        };
    };
    let base_oid = resolve_rev_oid(repo, default_branch);
    let diff = render_raw_unified_diff(repo, base_oid.as_ref(), &head_oid);
    let body = if as_patch {
        format!(
            "From {} Mon Sep 17 00:00:00 2001\nSubject: [PATCH] Merge branch '{}'\n\n---\n{}",
            head_oid, branch, diff
        )
    } else {
        diff
    };
    HttpResponse {
        status: 200,
        content_type: "text/plain; charset=utf-8".into(),
        body: body.into_bytes(),
        www_authenticate: None,
        extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn builds_valid_targz_and_zip_archives() {
        let entries = vec![
            ("demo-main/README.md".to_string(), b"# Hello\n".to_vec()),
            (
                "demo-main/src/lib.rs".to_string(),
                b"pub fn ok() {}\n".to_vec(),
            ),
        ];
        let tgz = build_tar_gz(&entries);
        assert!(tgz.len() > 20);
        assert_eq!(&tgz[..2], &[0x1f, 0x8b], "must be valid gzip magic");

        let zip = build_zip_store(&entries);
        assert_eq!(&zip[..4], b"PK\x03\x04", "must start with ZIP local header");
        assert!(
            zip.windows(4).any(|w| w == b"PK\x05\x06"),
            "must include ZIP end-of-central-directory"
        );
    }
}