//! 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 = 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 { 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, request: Option, ) -> 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() }