Skip to main content

grit_protocol/
lib.rs

1//! Git smart protocol handlers for HTTP transport.
2//!
3//! Runs upload-pack and receive-pack in-process via [`grit_lib::remote::serve`], with
4//! no subprocess or external `grit` binary.
5
6pub mod receive_pack;
7pub mod upload_pack;
8
9use std::io::Read;
10use std::path::{Path, PathBuf};
11
12use grit_lib::config::environment::Environment;
13use grit_lib::config::git_path::path_for_error_message;
14use grit_lib::config::ConfigSet;
15
16pub use grit_lib::config::environment::RepositoryOptions;
17use grit_lib::remote::serve::{self, ProtocolVersion, ReceivePolicy, ServeOptions};
18use grit_lib::repo::Repository;
19
20/// Errors from smart-protocol handlers.
21#[derive(Debug, thiserror::Error)]
22pub enum Error {
23    /// The path does not look like a git repository.
24    #[error("not a git repository: {0}")]
25    NotARepository(String),
26    /// Serving the wire protocol failed.
27    #[error(transparent)]
28    Serve(#[from] serve::ServeError),
29    /// Opening or reading repository state failed.
30    #[error(transparent)]
31    Repository(#[from] grit_lib::error::Error),
32    /// Buffered I/O failed while collecting the response.
33    #[error(transparent)]
34    Io(#[from] std::io::Error),
35}
36
37impl Error {
38    /// The I/O error from reading the client's request stream, for a failed
39    /// [`receive_pack::stateless_rpc_from_reader`] exchange.
40    ///
41    /// Servers use this to answer a request body that could not be read (truncated,
42    /// badly encoded, or rejected by the server's own decoding limits) with a client
43    /// error rather than a server error. During receive-pack that is the only source of
44    /// stream errors: the response is collected in memory, and repository failures are
45    /// reported as other [`serve::ServeError`] variants or inside the status report.
46    /// Upload-pack can
47    /// also return stream errors while reading repository data, so do not use this to
48    /// classify upload-pack failures.
49    ///
50    /// # Returns
51    ///
52    /// `Some` with the request read error, or `None` for every other failure.
53    #[must_use]
54    pub fn request_stream_error(&self) -> Option<&std::io::Error> {
55        match self {
56            Self::Serve(serve::ServeError::Io(e)) => Some(e),
57            _ => None,
58        }
59    }
60}
61
62/// Result alias for protocol handlers.
63pub type Result<T> = std::result::Result<T, Error>;
64
65/// Build [`RepositoryOptions`] from the current process environment.
66///
67/// Captures `HOME`, `GIT_CONFIG_*`, and the other variables [`ConfigSet::load`]
68/// uses for global and system config. Call once at server startup and pass the
69/// same options into every handler so receive policy and hide-ref rules match
70/// a `grit receive-pack` / `grit upload-pack` subprocess.
71#[must_use]
72pub fn repository_options_from_process() -> RepositoryOptions {
73    RepositoryOptions::with_environment(Environment::capture_process())
74}
75
76/// Map an explicit smart-HTTP protocol version header to a wire version.
77#[must_use]
78pub fn protocol_version_from_header(version: Option<u8>) -> ProtocolVersion {
79    match version {
80        Some(2) => ProtocolVersion::V2,
81        Some(1) => ProtocolVersion::V1,
82        _ => ProtocolVersion::V0,
83    }
84}
85
86/// Validate that a path looks like a git repository (bare or non-bare).
87///
88/// # Errors
89///
90/// Returns [`Error::NotARepository`] when neither `HEAD` nor `.git/HEAD` exists.
91pub fn validate_repo_path(path: &Path) -> Result<PathBuf> {
92    if path.join("HEAD").is_file() {
93        return Ok(path.to_path_buf());
94    }
95    let dot_git = path.join(".git");
96    if dot_git.join("HEAD").is_file() {
97        return Ok(path.to_path_buf());
98    }
99    Err(Error::NotARepository(path_for_error_message(path)))
100}
101
102pub(crate) fn run_upload_pack(
103    repo_path: &Path,
104    protocol_version: Option<u8>,
105    stateless_rpc: bool,
106    advertise_refs: bool,
107    input: &[u8],
108    repository_options: &RepositoryOptions,
109) -> Result<Vec<u8>> {
110    let repo = Repository::open(repo_path, &repository_options.clone().for_serving())?;
111    let config =
112        ConfigSet::load(repo.environment(), Some(repo.git_dir()), true).unwrap_or_default();
113    let hidden_refs = grit_lib::refs::hide_refs::hide_ref_patterns_uploadpack(&config);
114    let opts = ServeOptions {
115        protocol: protocol_version_from_header(protocol_version),
116        stateless_rpc,
117        advertise_refs,
118        agent: format!("grit/{}", env!("CARGO_PKG_VERSION")),
119        hidden_refs,
120    };
121    let mut output = Vec::new();
122    serve::upload_pack(&repo, &mut &*input, &mut output, &opts)?;
123    Ok(output)
124}
125
126pub(crate) fn run_receive_pack(
127    repo_path: &Path,
128    stateless_rpc: bool,
129    advertise_refs: bool,
130    input: &mut dyn Read,
131    repository_options: &RepositoryOptions,
132) -> Result<Vec<u8>> {
133    let repo = Repository::open(repo_path, &repository_options.clone().for_serving())?;
134    let config =
135        ConfigSet::load(repo.environment(), Some(repo.git_dir()), true).unwrap_or_default();
136    let hidden_refs = grit_lib::refs::hide_refs::hide_ref_patterns_receive(&config);
137    let opts = ServeOptions {
138        protocol: ProtocolVersion::V0,
139        stateless_rpc,
140        advertise_refs,
141        agent: format!("grit/{}", env!("CARGO_PKG_VERSION")),
142        hidden_refs,
143    };
144    let policy = ReceivePolicy::from_config(&config);
145    let mut output = Vec::new();
146    serve::receive_pack(&repo, input, &mut output, &opts, &policy)?;
147    Ok(output)
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153    use grit_lib::remote::serve::ProtocolVersion;
154
155    #[test]
156    fn protocol_header_maps_versions() {
157        assert_eq!(protocol_version_from_header(None), ProtocolVersion::V0);
158        assert_eq!(protocol_version_from_header(Some(2)), ProtocolVersion::V2);
159    }
160}