GITv
master
smart_http.rs123 lines, 5.1 KB
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
//! Read-only Git smart HTTP, using upload-pack's stateless protocol.
use super::capacity::{Pool, Visitor};
use super::git_stream::Output;
use super::throttle::Client;
use axum::{
    body::Bytes,
    extract::{Path, RawQuery, Request},
    http::{HeaderMap, StatusCode, header},
    response::{IntoResponse, Response},
};
use gitv_core::{git_command, repo_dir};
use std::sync::LazyLock;
use std::{process::Stdio, time::Duration};
use tokio::process::Command;

/// Clones and fetches at once. Git clients send no session cookie, so every transfer is
/// anonymous; each client may run two, so no single address can take them all.
static TRANSFERS: LazyLock<Pool> = LazyLock::new(|| Pool::new(4, 0, 2));

pub async fn refs(
    Path(path): Path<(String, String)>,
    RawQuery(query): RawQuery,
    client: Client,
    headers: HeaderMap,
) -> Response {
    if query.as_deref() != Some("service=git-upload-pack") {
        return StatusCode::NOT_FOUND.into_response();
    }
    transfer(path, client, protocol(&headers), None).await
}

/// The protocol the client asked for in its `Git-Protocol` header (`version=2`, say), when it
/// is well formed, to hand to upload-pack as `GIT_PROTOCOL`, as `git http-backend` does.
fn protocol(headers: &HeaderMap) -> Option<String> {
    gitv_core::git_protocol(headers.get("git-protocol")?.to_str().ok()?).map(str::to_string)
}

pub async fn pack(Path(path): Path<(String, String)>, client: Client, request: Request) -> Response {
    if request.headers().get(header::CONTENT_TYPE).map(|h| h.as_bytes())
        != Some(b"application/x-git-upload-pack-request")
    {
        return StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response();
    }
    let protocol = protocol(request.headers());
    transfer(path, client, protocol, Some(request)).await
}

async fn transfer(
    (owner, name): (String, String),
    client: Client,
    protocol: Option<String>,
    request: Option<Request>,
) -> Response {
    // `https://host/owner/name.git` works as well as the address the pages show.
    let name = name.strip_suffix(".git").unwrap_or(&name);
    let Some(dir) = repo_dir(&owner, name).filter(|dir| dir.is_public()) else {
        return StatusCode::NOT_FOUND.into_response();
    };
    // Taken before the body is read, so memory for bodies stays bounded by the slots; the
    // per-client cap keeps one slow sender from holding them all.
    let Some(permit) = TRANSFERS.try_acquire(Visitor { client, signed_in: false }) else {
        return StatusCode::SERVICE_UNAVAILABLE.into_response();
    };
    const MAX_REQUEST: usize = 2 << 20;
    let input = if let Some(request) = request {
        let gzip = match request.headers().get(header::CONTENT_ENCODING).map(|h| h.as_bytes()) {
            None | Some(b"identity") => false,
            Some(b"gzip") => true,
            _ => return StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response(),
        };
        let bytes =
            match tokio::time::timeout(Duration::from_secs(10), axum::body::to_bytes(request.into_body(), MAX_REQUEST))
                .await
            {
                Err(_) => return StatusCode::REQUEST_TIMEOUT.into_response(),
                Ok(Err(_)) => return StatusCode::PAYLOAD_TOO_LARGE.into_response(),
                Ok(Ok(bytes)) => bytes,
            };
        if gzip {
            use std::io::Read;
            let mut decoded = Vec::new();
            if flate2::read::GzDecoder::new(bytes.as_ref())
                .take(MAX_REQUEST as u64 + 1)
                .read_to_end(&mut decoded)
                .is_err()
            {
                return StatusCode::BAD_REQUEST.into_response();
            }
            if decoded.len() > MAX_REQUEST {
                return StatusCode::PAYLOAD_TOO_LARGE.into_response();
            }
            Some(Bytes::from(decoded))
        } else {
            Some(bytes)
        }
    } else {
        None
    };
    if !dir.is_public() {
        return StatusCode::NOT_FOUND.into_response();
    }
    let advertise = input.is_none();
    let mut cmd = Command::from(git_command(&dir));
    cmd.args(["upload-pack", "--stateless-rpc"]);
    if advertise {
        cmd.arg("--advertise-refs");
    }
    cmd.arg(".").stdin(Stdio::piped());
    // Protocol v2 lets a client ask only for the refs it wants instead of hearing every one.
    let v2 = protocol.as_deref().is_some_and(|p| p.split(':').any(|item| item == "version=2"));
    if let Some(protocol) = &protocol {
        cmd.env("GIT_PROTOCOL", protocol);
    }
    let Ok(output) = Output::start(cmd) else { return StatusCode::INTERNAL_SERVER_ERROR.into_response() };
    // Version 2's capability advertisement stands alone; earlier versions start with the
    // service line (git http-backend does the same).
    let prefix =
        if advertise && !v2 { Bytes::from_static(b"001e# service=git-upload-pack\n0000") } else { Bytes::new() };
    let body = output.body(prefix, input, permit, Duration::from_secs(300));
    let kind =
        if advertise { "application/x-git-upload-pack-advertisement" } else { "application/x-git-upload-pack-result" };
    ([(header::CONTENT_TYPE, kind), (header::CACHE_CONTROL, "no-store")], body).into_response()
}