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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
|
//! Git Smart HTTP Protocol Implementation
//!
//! This module implements the Git pkt-line format and protocol utilities.
//!
//! # Pkt-line Format
//!
//! A pkt-line is a variable length binary string with a 4-byte length prefix:
//! - First 4 bytes: hex digits representing total length (including these 4 bytes)
//! - Remaining bytes: payload data
//! - Special case "0000": flush packet (end of section)
//!
//! # References
//! - https://git-scm.com/docs/protocol-common#_pkt_line_format
use std::fmt;
/// Represents a Git pkt-line packet
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PktLine {
/// Data packet with payload
Data(Vec<u8>),
/// Flush packet (0000)
Flush,
}
impl PktLine {
/// Create a data packet from bytes
pub fn data(data: impl Into<Vec<u8>>) -> Self {
Self::Data(data.into())
}
/// Create a flush packet
pub fn flush() -> Self {
Self::Flush
}
/// Encode this packet to wire format
pub fn encode(&self) -> Vec<u8> {
match self {
PktLine::Flush => b"0000".to_vec(),
PktLine::Data(data) => {
let len = data.len() + 4;
let mut result = Vec::with_capacity(len);
result.extend_from_slice(format!("{:04x}", len).as_bytes());
result.extend_from_slice(data);
result
}
}
}
/// Parse a single pkt-line from bytes
/// Returns (packet, remaining_bytes)
pub fn parse(input: &[u8]) -> Result<(Self, &[u8]), ProtocolError> {
if input.len() < 4 {
return Err(ProtocolError::InsufficientData);
}
let len_str = std::str::from_utf8(&input[0..4])
.map_err(|_| ProtocolError::InvalidLength)?;
let len = u16::from_str_radix(len_str, 16)
.map_err(|_| ProtocolError::InvalidLength)? as usize;
if len == 0 {
// Flush packet
return Ok((PktLine::Flush, &input[4..]));
}
if len < 4 {
return Err(ProtocolError::InvalidLength);
}
if input.len() < len {
return Err(ProtocolError::InsufficientData);
}
let data = input[4..len].to_vec();
Ok((PktLine::Data(data), &input[len..]))
}
/// Parse all pkt-lines from bytes
pub fn parse_all(mut input: &[u8]) -> Result<Vec<Self>, ProtocolError> {
let mut packets = Vec::new();
while !input.is_empty() {
let (packet, remaining) = Self::parse(input)?;
let is_flush = matches!(packet, PktLine::Flush);
packets.push(packet);
input = remaining;
// Stop at flush packet
if is_flush {
break;
}
}
Ok(packets)
}
}
/// Errors that can occur during protocol parsing
#[derive(Debug)]
pub enum ProtocolError {
/// Not enough data to parse a complete packet
InsufficientData,
/// Invalid length prefix
InvalidLength,
/// Invalid UTF-8 in packet data
InvalidUtf8,
/// IO error
Io(std::io::Error),
}
impl fmt::Display for ProtocolError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InsufficientData => write!(f, "insufficient data for pkt-line"),
Self::InvalidLength => write!(f, "invalid pkt-line length"),
Self::InvalidUtf8 => write!(f, "invalid UTF-8 in pkt-line"),
Self::Io(e) => write!(f, "IO error: {}", e),
}
}
}
impl std::error::Error for ProtocolError {}
impl From<std::io::Error> for ProtocolError {
fn from(e: std::io::Error) -> Self {
Self::Io(e)
}
}
/// Git service type
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GitService {
/// Upload pack (clone/fetch)
UploadPack,
/// Receive pack (push)
ReceivePack,
}
impl GitService {
/// Parse service from query parameter
pub fn from_query_param(service: &str) -> Option<Self> {
match service {
"git-upload-pack" => Some(Self::UploadPack),
"git-receive-pack" => Some(Self::ReceivePack),
_ => None,
}
}
/// Get the service name as used in Git protocol
pub fn as_str(&self) -> &'static str {
match self {
Self::UploadPack => "git-upload-pack",
Self::ReceivePack => "git-receive-pack",
}
}
/// Get the content type for the service advertisement
pub fn advertisement_content_type(&self) -> &'static str {
match self {
Self::UploadPack => "application/x-git-upload-pack-advertisement",
Self::ReceivePack => "application/x-git-receive-pack-advertisement",
}
}
/// Get the content type for the service result
pub fn result_content_type(&self) -> &'static str {
match self {
Self::UploadPack => "application/x-git-upload-pack-result",
Self::ReceivePack => "application/x-git-receive-pack-result",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pktline_encode_flush() {
let pkt = PktLine::flush();
assert_eq!(pkt.encode(), b"0000");
}
#[test]
fn test_pktline_encode_data() {
let pkt = PktLine::data(b"hello");
assert_eq!(pkt.encode(), b"0009hello");
}
#[test]
fn test_pktline_parse_flush() {
let (pkt, remaining) = PktLine::parse(b"0000extra").unwrap();
assert_eq!(pkt, PktLine::Flush);
assert_eq!(remaining, b"extra");
}
#[test]
fn test_pktline_parse_data() {
let (pkt, remaining) = PktLine::parse(b"0009helloworld").unwrap();
assert_eq!(pkt, PktLine::data(b"hello"));
assert_eq!(remaining, b"world");
}
#[test]
fn test_pktline_parse_insufficient_data() {
let result = PktLine::parse(b"000");
assert!(matches!(result, Err(ProtocolError::InsufficientData)));
}
#[test]
fn test_pktline_parse_invalid_length() {
let result = PktLine::parse(b"xxxx");
assert!(matches!(result, Err(ProtocolError::InvalidLength)));
}
#[test]
fn test_pktline_parse_all() {
let input = b"0009hello000aworld\n0000";
let packets = PktLine::parse_all(input).unwrap();
assert_eq!(packets.len(), 3);
assert_eq!(packets[0], PktLine::data(b"hello"));
assert_eq!(packets[1], PktLine::data(b"world\n"));
assert_eq!(packets[2], PktLine::Flush);
}
#[test]
fn test_git_service_from_query() {
assert_eq!(
GitService::from_query_param("git-upload-pack"),
Some(GitService::UploadPack)
);
assert_eq!(
GitService::from_query_param("git-receive-pack"),
Some(GitService::ReceivePack)
);
assert_eq!(GitService::from_query_param("invalid"), None);
}
#[test]
fn test_git_service_content_types() {
let upload = GitService::UploadPack;
assert_eq!(
upload.advertisement_content_type(),
"application/x-git-upload-pack-advertisement"
);
assert_eq!(
upload.result_content_type(),
"application/x-git-upload-pack-result"
);
}
}
|