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
|
use axum::body::{Body, Bytes};
use axum::extract::{Path, Query, State};
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use serde::Deserialize;
use std::io::Read;
use std::process::Stdio;
use tokio::io::AsyncWriteExt;
use tokio::process::Command;
use tokio_util::io::ReaderStream;
use crate::web::Shared;
pub const MAX_REQUEST_BYTES: usize = 32 * 1024 * 1024;
#[derive(Deserialize)]
pub struct ServiceQuery {
service: Option<String>,
}
fn plain(status: StatusCode, msg: &str) -> Response {
(status, [(header::CONTENT_TYPE, "text/plain; charset=utf-8")], format!("{msg}\n")).into_response()
}
pub fn pkt_line(data: &str) -> String {
format!("{:04x}{data}", data.len() + 4)
}
fn git_protocol(headers: &HeaderMap) -> Option<String> {
let v = headers.get("git-protocol")?.to_str().ok()?;
let ok = v.len() < 256 && v.chars().all(|c| c.is_ascii_alphanumeric() || "=:._-".contains(c));
ok.then(|| v.to_string())
}
pub async fn info_refs(
State(st): State<Shared>,
Path(repo): Path<String>,
Query(q): Query<ServiceQuery>,
headers: HeaderMap,
) -> Response {
let Ok(rc) = st.repo(&repo) else {
return plain(StatusCode::NOT_FOUND, "repository not found");
};
match q.service.as_deref() {
Some("git-upload-pack") => {}
Some("git-receive-pack") => return plain(StatusCode::FORBIDDEN, "push is not supported"),
_ => {
return plain(
StatusCode::FORBIDDEN,
"only the smart HTTP protocol is supported (use git >= 1.6.6)",
)
}
}
let protocol = git_protocol(&headers);
let mut cmd = Command::new("git");
cmd.args(["upload-pack", "--stateless-rpc", "--advertise-refs"])
.arg(&rc.path)
.stdin(Stdio::null())
.kill_on_drop(true);
if let Some(p) = &protocol {
cmd.env("GIT_PROTOCOL", p);
}
let out = match cmd.output().await {
Ok(o) if o.status.success() => o,
Ok(o) => {
eprintln!("upload-pack --advertise-refs failed: {}", String::from_utf8_lossy(&o.stderr));
return plain(StatusCode::INTERNAL_SERVER_ERROR, "git upload-pack failed");
}
Err(e) => {
eprintln!("could not run git: {e}");
return plain(StatusCode::INTERNAL_SERVER_ERROR, "could not run git");
}
};
let mut body = Vec::new();
let is_v2 = protocol.as_deref().is_some_and(|p| p.contains("version=2"));
if !is_v2 {
body.extend_from_slice(pkt_line("# service=git-upload-pack\n").as_bytes());
body.extend_from_slice(b"0000");
}
body.extend_from_slice(&out.stdout);
let mut res = (StatusCode::OK, body).into_response();
let h = res.headers_mut();
h.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/x-git-upload-pack-advertisement"));
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
res
}
pub async fn upload_pack(
State(st): State<Shared>,
Path(repo): Path<String>,
headers: HeaderMap,
body: Bytes,
) -> Response {
let Ok(rc) = st.repo(&repo) else {
return plain(StatusCode::NOT_FOUND, "repository not found");
};
let ctype = headers.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok());
if ctype != Some("application/x-git-upload-pack-request") {
return plain(StatusCode::UNSUPPORTED_MEDIA_TYPE, "expected application/x-git-upload-pack-request");
}
let gzipped = headers
.get(header::CONTENT_ENCODING)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.eq_ignore_ascii_case("gzip") || v.eq_ignore_ascii_case("x-gzip"));
let input: Vec<u8> = if gzipped {
let mut out = Vec::new();
let decoder = flate2::read::GzDecoder::new(&body[..]);
if decoder.take(MAX_REQUEST_BYTES as u64 + 1).read_to_end(&mut out).is_err()
|| out.len() > MAX_REQUEST_BYTES
{
return plain(StatusCode::BAD_REQUEST, "bad or oversized gzip body");
}
out
} else {
body.to_vec()
};
let mut cmd = Command::new("git");
cmd.args(["upload-pack", "--stateless-rpc"])
.arg(&rc.path)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true);
if let Some(p) = git_protocol(&headers) {
cmd.env("GIT_PROTOCOL", p);
}
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(e) => {
eprintln!("could not run git: {e}");
return plain(StatusCode::INTERNAL_SERVER_ERROR, "could not run git");
}
};
let mut stdin = child.stdin.take().expect("stdin was piped");
let stdout = child.stdout.take().expect("stdout was piped");
tokio::spawn(async move {
let _ = stdin.write_all(&input).await;
drop(stdin); let _ = child.wait().await;
});
let mut res = Response::new(Body::from_stream(ReaderStream::new(stdout)));
let h = res.headers_mut();
h.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/x-git-upload-pack-result"));
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
res
}
pub async fn receive_pack_refused() -> Response {
plain(StatusCode::FORBIDDEN, "push is not supported")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pkt_line_format() {
assert_eq!(pkt_line("# service=git-upload-pack\n"), "001e# service=git-upload-pack\n");
assert_eq!(pkt_line(""), "0004");
}
#[test]
fn protocol_header_is_filtered() {
let mut h = HeaderMap::new();
h.insert("git-protocol", HeaderValue::from_static("version=2"));
assert_eq!(git_protocol(&h).as_deref(), Some("version=2"));
h.insert("git-protocol", HeaderValue::from_static("version=2; rm -rf /"));
assert_eq!(git_protocol(&h), None);
}
}
|