Skip to main content

git_internal/protocol/
types.rs

1//! Core enums and error types for the Git smart protocol: service identifiers, transport selection,
2//! capability negotiation, and the shared stream/error aliases used throughout the crate.
3
4use std::{fmt, pin::Pin, str::FromStr};
5
6use bytes::Bytes;
7use futures::stream::Stream;
8
9use crate::hash::HashKind;
10
11/// Type alias for protocol data streams to reduce nesting
12pub type ProtocolStream = Pin<Box<dyn Stream<Item = Result<Bytes, ProtocolError>> + Send>>;
13
14/// Protocol error types
15#[derive(Debug, thiserror::Error)]
16pub enum ProtocolError {
17    #[error("Invalid service: {0}")]
18    InvalidService(String),
19
20    #[error("Repository not found: {0}")]
21    RepositoryNotFound(String),
22
23    #[error("Object not found: {0}")]
24    ObjectNotFound(String),
25
26    #[error("Invalid request: {0}")]
27    InvalidRequest(String),
28
29    #[error("Unauthorized: {0}")]
30    Unauthorized(String),
31
32    #[error("IO error: {0}")]
33    Io(#[from] std::io::Error),
34
35    #[error("Pack error: {0}")]
36    Pack(String),
37
38    #[error("Internal error: {0}")]
39    Internal(String),
40}
41
42impl ProtocolError {
43    pub fn invalid_service(service: &str) -> Self {
44        ProtocolError::InvalidService(service.to_string())
45    }
46
47    pub fn repository_error(msg: String) -> Self {
48        ProtocolError::Internal(msg)
49    }
50
51    pub fn invalid_request(msg: &str) -> Self {
52        ProtocolError::InvalidRequest(msg.to_string())
53    }
54
55    /// The peer's `object-format` capability value is unknown or not the canonical
56    /// lowercase name (`sha1`, `sha256`, or the git-internal / Libra extension `blake3`).
57    pub fn unknown_object_format(value: &str) -> Self {
58        let shown: String = value.chars().take(64).collect();
59        ProtocolError::InvalidRequest(format!(
60            "unknown object-format capability `{shown}` (accepted: {}); refusing to negotiate",
61            HashKind::ACCEPTED_TAGS
62        ))
63    }
64
65    /// The negotiated wire object format, the local kind bound at construction and the
66    /// repository's own `object_hash_kind()` do not agree (ADR-GI-B3-03).
67    pub fn object_format_mismatch(wire: HashKind, local: HashKind, repository: HashKind) -> Self {
68        ProtocolError::InvalidRequest(format!(
69            "object-format mismatch: wire={} local={} repository={}; refusing to serve the \
70             repository under another object format",
71            wire.as_str(),
72            local.as_str(),
73            repository.as_str()
74        ))
75    }
76
77    /// A pkt-line object ID is not raw lowercase hex of the negotiated wire kind (GC-13).
78    pub fn invalid_wire_id(command: &str, id: &str, detail: &dyn fmt::Display) -> Self {
79        let shown: String = id.chars().take(80).collect();
80        ProtocolError::InvalidRequest(format!(
81            "invalid object ID in `{command}` line (`{shown}`): {detail}"
82        ))
83    }
84
85    pub fn unauthorized(msg: &str) -> Self {
86        ProtocolError::Unauthorized(msg.to_string())
87    }
88}
89
90/// Git transport protocol types
91#[derive(Debug, PartialEq, Clone, Copy, Default)]
92pub enum TransportProtocol {
93    Local,
94    #[default]
95    Http,
96    Ssh,
97    Git,
98}
99
100/// Git service types for smart protocol
101#[derive(Debug, PartialEq, Clone, Copy)]
102pub enum ServiceType {
103    UploadPack,
104    ReceivePack,
105}
106
107impl fmt::Display for ServiceType {
108    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109        match self {
110            ServiceType::UploadPack => write!(f, "git-upload-pack"),
111            ServiceType::ReceivePack => write!(f, "git-receive-pack"),
112        }
113    }
114}
115
116impl FromStr for ServiceType {
117    type Err = ProtocolError;
118
119    fn from_str(s: &str) -> Result<Self, Self::Err> {
120        match s {
121            "git-upload-pack" => Ok(ServiceType::UploadPack),
122            "git-receive-pack" => Ok(ServiceType::ReceivePack),
123            _ => Err(ProtocolError::InvalidService(s.to_string())),
124        }
125    }
126}
127
128/// Git protocol capabilities
129///
130/// ## Implementation Status Overview
131///
132/// ### Implemented capabilities:
133/// - **Data transmission**: SideBand, SideBand64k - Multiplexed data streams via side-band formatter
134/// - **Status reporting**: ReportStatus, ReportStatusv2 - Push status feedback via protocol handlers
135/// - **Pack optimization**: OfsDelta, ThinPack, NoThin - Delta compression and efficient transmission
136/// - **Protocol control**: MultiAckDetailed, NoDone - ACK mechanism optimization for upload-pack
137/// - **Push control**: Atomic, DeleteRefs, Quiet - Atomic operations and reference management
138/// - **Tag handling**: IncludeTag - Automatic tag inclusion for upload-pack
139/// - **Client identification**: Agent - Client/server identification in capability negotiation
140/// - **Object format**: ObjectFormat - `object-format=<sha1|sha256|blake3>` negotiation
141///   (`blake3` is a git-internal / Libra extension); recorded after fail-closed validation
142///   against the repository's own format
143///
144/// ### Not yet implemented capabilities:
145/// - **Basic protocol**: MultiAck - Basic multi-ack support (only detailed version implemented)
146/// - **Shallow cloning**: Shallow, DeepenSince, DeepenNot, DeepenRelative - Depth control for shallow clones
147/// - **Progress control**: NoProgress - Progress output suppression
148/// - **Special fetch**: AllowTipSha1InWant, AllowReachableSha1InWant - SHA1 validation in want processing
149/// - **Security**: PushCert - Push certificate verification mechanism
150/// - **Extensions**: PushOptions, Filter, Symref - Extended parameter handling
151/// - **Session management**: SessionId - Session identification
152#[derive(Debug, Clone, PartialEq)]
153pub enum Capability {
154    /// Multi-ack capability for upload-pack protocol
155    MultiAck,
156    /// Multi-ack-detailed capability for more granular acknowledgment
157    MultiAckDetailed,
158    /// No-done capability to optimize upload-pack protocol
159    NoDone,
160    /// Side-band capability for multiplexing data streams
161    SideBand,
162    /// Side-band-64k capability for larger side-band packets
163    SideBand64k,
164    /// Report-status capability for push status reporting
165    ReportStatus,
166    /// Report-status-v2 capability for enhanced push status reporting
167    ReportStatusv2,
168    /// OFS-delta capability for offset-based delta compression
169    OfsDelta,
170    /// Deepen-since capability for shallow clone with time-based depth
171    DeepenSince,
172    /// Deepen-not capability for shallow clone exclusions
173    DeepenNot,
174    /// Deepen-relative capability for relative depth specification
175    DeepenRelative,
176    /// Thin-pack capability for efficient pack transmission
177    ThinPack,
178    /// Shallow capability for shallow clone support
179    Shallow,
180    /// Include-tag capability for automatic tag inclusion
181    IncludeTag,
182    /// Delete-refs capability for reference deletion
183    DeleteRefs,
184    /// Quiet capability to suppress output
185    Quiet,
186    /// Atomic capability for atomic push operations
187    Atomic,
188    /// No-thin capability to disable thin pack
189    NoThin,
190    /// No-progress capability to disable progress reporting
191    NoProgress,
192    /// Allow-tip-sha1-in-want capability for fetching specific commits
193    AllowTipSha1InWant,
194    /// Allow-reachable-sha1-in-want capability for fetching reachable commits
195    AllowReachableSha1InWant,
196    /// Push-cert capability for signed push certificates
197    PushCert(String),
198    /// Push-options capability for additional push metadata
199    PushOptions,
200    /// Object-format capability for specifying hash algorithm
201    ObjectFormat(String),
202    /// Session-id capability for session tracking
203    SessionId(String),
204    /// Filter capability for partial clone support
205    Filter(String),
206    /// Symref capability for symbolic reference information
207    Symref(String),
208    /// Agent capability for client/server identification
209    Agent(String),
210    /// Unknown capability for forward compatibility
211    Unknown(String),
212}
213
214impl FromStr for Capability {
215    type Err = ();
216
217    fn from_str(s: &str) -> Result<Self, Self::Err> {
218        // Parameterized capabilities
219        if let Some(rest) = s.strip_prefix("agent=") {
220            return Ok(Capability::Agent(rest.to_string()));
221        }
222        if let Some(rest) = s.strip_prefix("session-id=") {
223            return Ok(Capability::SessionId(rest.to_string()));
224        }
225        if let Some(rest) = s.strip_prefix("push-cert=") {
226            return Ok(Capability::PushCert(rest.to_string()));
227        }
228        if let Some(rest) = s.strip_prefix("object-format=") {
229            return Ok(Capability::ObjectFormat(rest.to_string()));
230        }
231        if let Some(rest) = s.strip_prefix("filter=") {
232            return Ok(Capability::Filter(rest.to_string()));
233        }
234        if let Some(rest) = s.strip_prefix("symref=") {
235            return Ok(Capability::Symref(rest.to_string()));
236        }
237
238        match s {
239            "multi_ack" => Ok(Capability::MultiAck),
240            "multi_ack_detailed" => Ok(Capability::MultiAckDetailed),
241            "no-done" => Ok(Capability::NoDone),
242            "side-band" => Ok(Capability::SideBand),
243            "side-band-64k" => Ok(Capability::SideBand64k),
244            "report-status" => Ok(Capability::ReportStatus),
245            "report-status-v2" => Ok(Capability::ReportStatusv2),
246            "ofs-delta" => Ok(Capability::OfsDelta),
247            "deepen-since" => Ok(Capability::DeepenSince),
248            "deepen-not" => Ok(Capability::DeepenNot),
249            "deepen-relative" => Ok(Capability::DeepenRelative),
250            "thin-pack" => Ok(Capability::ThinPack),
251            "shallow" => Ok(Capability::Shallow),
252            "include-tag" => Ok(Capability::IncludeTag),
253            "delete-refs" => Ok(Capability::DeleteRefs),
254            "quiet" => Ok(Capability::Quiet),
255            "atomic" => Ok(Capability::Atomic),
256            "no-thin" => Ok(Capability::NoThin),
257            "no-progress" => Ok(Capability::NoProgress),
258            "allow-tip-sha1-in-want" => Ok(Capability::AllowTipSha1InWant),
259            "allow-reachable-sha1-in-want" => Ok(Capability::AllowReachableSha1InWant),
260            "push-options" => Ok(Capability::PushOptions),
261            _ => Ok(Capability::Unknown(s.to_string())),
262        }
263    }
264}
265
266impl std::fmt::Display for Capability {
267    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
268        match self {
269            Capability::MultiAck => write!(f, "multi_ack"),
270            Capability::MultiAckDetailed => write!(f, "multi_ack_detailed"),
271            Capability::NoDone => write!(f, "no-done"),
272            Capability::SideBand => write!(f, "side-band"),
273            Capability::SideBand64k => write!(f, "side-band-64k"),
274            Capability::ReportStatus => write!(f, "report-status"),
275            Capability::ReportStatusv2 => write!(f, "report-status-v2"),
276            Capability::OfsDelta => write!(f, "ofs-delta"),
277            Capability::DeepenSince => write!(f, "deepen-since"),
278            Capability::DeepenNot => write!(f, "deepen-not"),
279            Capability::DeepenRelative => write!(f, "deepen-relative"),
280            Capability::ThinPack => write!(f, "thin-pack"),
281            Capability::Shallow => write!(f, "shallow"),
282            Capability::IncludeTag => write!(f, "include-tag"),
283            Capability::DeleteRefs => write!(f, "delete-refs"),
284            Capability::Quiet => write!(f, "quiet"),
285            Capability::Atomic => write!(f, "atomic"),
286            Capability::NoThin => write!(f, "no-thin"),
287            Capability::NoProgress => write!(f, "no-progress"),
288            Capability::AllowTipSha1InWant => write!(f, "allow-tip-sha1-in-want"),
289            Capability::AllowReachableSha1InWant => write!(f, "allow-reachable-sha1-in-want"),
290            Capability::PushCert(value) => write!(f, "push-cert={value}"),
291            Capability::PushOptions => write!(f, "push-options"),
292            Capability::ObjectFormat(format) => write!(f, "object-format={format}"),
293            Capability::SessionId(id) => write!(f, "session-id={id}"),
294            Capability::Filter(filter) => write!(f, "filter={filter}"),
295            Capability::Symref(symref) => write!(f, "symref={symref}"),
296            Capability::Agent(agent) => write!(f, "agent={agent}"),
297            Capability::Unknown(s) => write!(f, "{s}"),
298        }
299    }
300}
301
302/// Side-band types for multiplexed data streams
303pub enum SideBand {
304    /// Sideband 1 contains packfile data
305    PackfileData,
306    /// Sideband 2 contains progress information
307    ProgressInfo,
308    /// Sideband 3 contains error information
309    Error,
310}
311
312impl SideBand {
313    /// Get the byte value associated with the side-band type
314    pub fn value(&self) -> u8 {
315        match self {
316            Self::PackfileData => b'\x01',
317            Self::ProgressInfo => b'\x02',
318            Self::Error => b'\x03',
319        }
320    }
321}
322
323/// Reference types in Git
324#[derive(Debug, PartialEq, Clone, Copy)]
325pub enum RefTypeEnum {
326    Branch,
327    Tag,
328}
329
330/// Git reference information
331#[derive(Clone, Debug)]
332pub struct GitRef {
333    pub name: String,
334    pub hash: String,
335}
336
337/// Reference command for push operations
338#[derive(Debug, Clone)]
339pub struct RefCommand {
340    pub old_hash: String,
341    pub new_hash: String,
342    pub ref_name: String,
343    pub ref_type: RefTypeEnum,
344    pub default_branch: bool,
345    pub status: CommandStatus,
346    pub error_message: Option<String>,
347}
348
349/// Status of a reference command
350#[derive(Debug, Clone)]
351pub enum CommandStatus {
352    Pending,
353    Success,
354    Failed,
355}
356
357impl RefCommand {
358    /// Create a new reference command
359    pub fn new(old_hash: String, new_hash: String, ref_name: String) -> Self {
360        // Determine ref type based on ref name
361        let ref_type = if ref_name.starts_with("refs/tags/") {
362            RefTypeEnum::Tag
363        } else {
364            RefTypeEnum::Branch
365        };
366
367        Self {
368            old_hash,
369            new_hash,
370            ref_name,
371            ref_type,
372            default_branch: false,
373            status: CommandStatus::Pending,
374            error_message: None,
375        }
376    }
377
378    /// Mark the command as failed with an error message
379    pub fn failed(&mut self, error: String) {
380        self.status = CommandStatus::Failed;
381        self.error_message = Some(error);
382    }
383
384    /// Mark the command as successful
385    pub fn success(&mut self) {
386        self.status = CommandStatus::Success;
387        self.error_message = None;
388    }
389
390    /// Get the status string for the command
391    pub fn get_status(&self) -> String {
392        match &self.status {
393            CommandStatus::Success => format!("ok {}", self.ref_name),
394            CommandStatus::Failed => {
395                let error = self.error_message.as_deref().unwrap_or("unknown error");
396                format!("ng {} {}", self.ref_name, error)
397            }
398            CommandStatus::Pending => format!("ok {}", self.ref_name), // Default to ok for pending
399        }
400    }
401}
402
403/// Command types for reference updates
404#[derive(Debug, PartialEq, Clone)]
405pub enum CommandType {
406    Create,
407    Update,
408    Delete,
409}
410
411/// Protocol constants
412pub const LF: char = '\n';
413pub const SP: char = ' ';
414pub const NUL: char = '\0';
415pub const PKT_LINE_END_MARKER: &[u8; 4] = b"0000";
416
417// Git protocol capability lists
418pub const RECEIVE_CAP_LIST: &str =
419    "report-status report-status-v2 delete-refs quiet atomic no-thin ";
420pub const COMMON_CAP_LIST: &str = "side-band-64k ofs-delta agent=git-internal/0.1.0";
421pub const UPLOAD_CAP_LIST: &str = "multi_ack_detailed no-done include-tag ";
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426
427    /// ServiceType parsing should accept known services and reject unknown.
428    #[test]
429    fn service_type_from_str() {
430        assert_eq!(
431            ServiceType::from_str("git-upload-pack").unwrap(),
432            ServiceType::UploadPack
433        );
434        assert_eq!(
435            ServiceType::from_str("git-receive-pack").unwrap(),
436            ServiceType::ReceivePack
437        );
438        assert!(ServiceType::from_str("git-upload-archive").is_err());
439    }
440
441    /// Capability simple flags should round-trip Display -> FromStr.
442    #[test]
443    fn capability_round_trip_simple() {
444        for cap in [
445            Capability::SideBand,
446            Capability::SideBand64k,
447            Capability::MultiAck,
448            Capability::ReportStatus,
449        ] {
450            let s = cap.to_string();
451            let parsed = Capability::from_str(&s).expect("should parse");
452            assert_eq!(parsed, cap);
453        }
454    }
455
456    /// Parameterized capabilities should preserve their payload strings.
457    #[test]
458    fn capability_parsing_parameterized() {
459        let agent = Capability::from_str("agent=git/2.41").unwrap();
460        assert_eq!(agent, Capability::Agent("git/2.41".to_string()));
461
462        let fmt = Capability::from_str("object-format=sha256").unwrap();
463        assert_eq!(fmt, Capability::ObjectFormat("sha256".to_string()));
464
465        let unknown = Capability::from_str("custom-cap").unwrap();
466        assert_eq!(unknown, Capability::Unknown("custom-cap".to_string()));
467    }
468
469    /// SideBand variants should map to the expected byte tags.
470    #[test]
471    fn sideband_values() {
472        assert_eq!(SideBand::PackfileData.value(), b'\x01');
473        assert_eq!(SideBand::ProgressInfo.value(), b'\x02');
474        assert_eq!(SideBand::Error.value(), b'\x03');
475    }
476
477    /// RefCommand should infer ref type and expose status strings.
478    #[test]
479    fn ref_command_defaults_and_status() {
480        let mut cmd = RefCommand::new(
481            "old".to_string(),
482            "new".to_string(),
483            "refs/tags/v1.0".to_string(),
484        );
485        assert_eq!(cmd.ref_type, RefTypeEnum::Tag);
486        assert_eq!(cmd.get_status(), "ok refs/tags/v1.0");
487
488        cmd.failed("boom".to_string());
489        assert_eq!(cmd.get_status(), "ng refs/tags/v1.0 boom");
490
491        cmd.success();
492        assert_eq!(cmd.get_status(), "ok refs/tags/v1.0");
493    }
494}