1use crate::auth::BasicAuthConfig;
12use crate::dav::{handle_dav, is_dav_method};
13use crate::dumb::serve_dumb_path;
14use crate::error::ServerError;
15use crate::push_policy::Pusher;
16use crate::receive::{receive_advertisement, receive_pack_as};
17use crate::upload::{upload_advertisement, upload_pack_result};
18use crate::v2::{handle_v2_request, v2_capability_advertisement};
19use arks_repo::Repository;
20
21const UPLOAD_AD: &str = "application/x-git-upload-pack-advertisement";
22const UPLOAD_RES: &str = "application/x-git-upload-pack-result";
23const RECEIVE_AD: &str = "application/x-git-receive-pack-advertisement";
24const RECEIVE_RES: &str = "application/x-git-receive-pack-result";
25
26#[derive(Debug, Clone)]
27pub struct HttpRequest {
28 pub method: String,
29 pub path: String,
30 pub query: String,
31 pub body: Vec<u8>,
32 pub git_protocol: Option<String>,
34 pub authorization: Option<String>,
36 pub destination: Option<String>,
38 pub lock_token: Option<String>,
40 pub host: Option<String>,
42}
43
44impl HttpRequest {
45 pub fn new(
46 method: impl Into<String>,
47 path: impl Into<String>,
48 query: impl Into<String>,
49 body: Vec<u8>,
50 ) -> Self {
51 Self {
52 method: method.into(),
53 path: path.into(),
54 query: query.into(),
55 body,
56 git_protocol: None,
57 authorization: None,
58 destination: None,
59 lock_token: None,
60 host: None,
61 }
62 }
63}
64
65#[derive(Debug, Clone)]
66pub struct HttpResponse {
67 pub status: u16,
68 pub content_type: String,
69 pub body: Vec<u8>,
70 pub www_authenticate: Option<String>,
72 pub extra_headers: Vec<(String, String)>,
74}
75
76pub fn handle_smart_http(
78 repo: &mut Repository,
79 req: &HttpRequest,
80) -> Result<HttpResponse, ServerError> {
81 handle_smart_http_auth(repo, req, None)
82}
83
84pub fn handle_smart_http_auth(
86 repo: &mut Repository,
87 req: &HttpRequest,
88 basic: Option<&BasicAuthConfig>,
89) -> Result<HttpResponse, ServerError> {
90 handle_smart_http_auth_opts(repo, req, basic, true, "http")
91}
92
93pub fn handle_smart_http_auth_opts(
95 repo: &mut Repository,
96 req: &HttpRequest,
97 basic: Option<&BasicAuthConfig>,
98 enable_lfs: bool,
99 scheme: &str,
100) -> Result<HttpResponse, ServerError> {
101 if let Some(cfg) = basic {
102 if !cfg.check_authorization(req.authorization.as_deref()) {
103 return Ok(HttpResponse {
104 status: 401,
105 content_type: "text/plain".into(),
106 body: b"unauthorized\n".to_vec(),
107 www_authenticate: Some(cfg.challenge_header()),
108 extra_headers: Vec::new(),
109 });
110 }
111 }
112 if crate::lfs::is_lfs_path(&req.path) {
113 if enable_lfs {
114 return crate::lfs::handle_lfs(repo, req, scheme);
115 }
116 return Ok(text(404, b"LFS disabled\n"));
117 }
118 if is_dav_method(&req.method) {
119 return handle_dav(repo, req);
120 }
121 let path = req.path.as_str();
122 let wants_v2 = req
123 .git_protocol
124 .as_deref()
125 .map(|v| {
126 v.split(':')
127 .any(|p| p.trim() == "version=2" || p.trim().starts_with("version=2"))
128 })
129 .unwrap_or(false)
130 || req
131 .git_protocol
132 .as_deref()
133 .map(|v| v.contains("version=2"))
134 .unwrap_or(false);
135
136 if path.ends_with("/info/refs") || path == "/info/refs" || path.ends_with("info/refs") {
137 let service = query_param(&req.query, "service").unwrap_or("");
138 if service.is_empty() {
139 return match serve_dumb_path(repo, "info/refs")? {
141 Some((ct, body)) => Ok(typed(200, &ct, body)),
142 None => Ok(text(404, b"not found")),
143 };
144 }
145 if wants_v2 && service == "git-upload-pack" {
146 let mut body = arks_protocol::encode_text_line("# service=git-upload-pack")
149 .map_err(|e| ServerError::Protocol(e.to_string()))?;
150 body.extend(
151 arks_protocol::encode_packet(&arks_protocol::Packet::Flush)
152 .map_err(|e| ServerError::Protocol(e.to_string()))?,
153 );
154 body.extend(v2_capability_advertisement()?);
155 return Ok(typed(200, UPLOAD_AD, body));
156 }
157 return match service {
159 "git-upload-pack" => Ok(typed(200, UPLOAD_AD, upload_advertisement(repo)?)),
160 "git-receive-pack" => Ok(typed(200, RECEIVE_AD, receive_advertisement(repo)?)),
161 _ => Ok(text(403, b"unknown service")),
162 };
163 }
164 if req.method.eq_ignore_ascii_case("POST")
165 && (path.ends_with("/git-upload-pack") || path.ends_with("git-upload-pack"))
166 {
167 if looks_like_v2_command(&req.body) {
168 return Ok(typed(
169 200,
170 UPLOAD_RES,
171 handle_v2_request(repo, &req.body, true)?,
172 ));
173 }
174 return Ok(typed(200, UPLOAD_RES, upload_pack_result(repo, &req.body)?));
175 }
176 if req.method.eq_ignore_ascii_case("POST")
177 && (path.ends_with("/git-receive-pack") || path.ends_with("git-receive-pack"))
178 {
179 let pusher = Pusher {
180 transport: "http",
181 verified_user: basic.and_then(|cfg| cfg.authorized_user(req.authorization.as_deref())),
182 authorization: req.authorization.clone(),
183 };
184 return Ok(typed(
185 200,
186 RECEIVE_RES,
187 receive_pack_as(repo, &req.body, &pusher)?,
188 ));
189 }
190 if req.method.eq_ignore_ascii_case("GET") || req.method.eq_ignore_ascii_case("HEAD") {
192 let rel = path.trim_start_matches('/');
193 if let Some((ct, body)) = serve_dumb_path(repo, rel)? {
194 return Ok(typed(200, &ct, body));
195 }
196 if let Some(idx) = rel.find("objects/") {
198 if let Some((ct, body)) = serve_dumb_path(repo, &rel[idx..])? {
199 return Ok(typed(200, &ct, body));
200 }
201 }
202 if let Some(idx) = rel.find("info/refs") {
203 if let Some((ct, body)) = serve_dumb_path(repo, &rel[idx..])? {
204 return Ok(typed(200, &ct, body));
205 }
206 }
207 }
208 Ok(text(404, b"not found"))
209}
210
211fn looks_like_v2_command(body: &[u8]) -> bool {
212 body.len() >= 4 && {
214 let s = String::from_utf8_lossy(body);
215 s.contains("command=")
216 }
217}
218
219fn query_param<'a>(query: &'a str, key: &str) -> Option<&'a str> {
220 for part in query.split('&') {
221 if let Some((k, v)) = part.split_once('=') {
222 if k == key {
223 return Some(v);
224 }
225 }
226 }
227 None
228}
229
230fn typed(status: u16, ct: &str, body: Vec<u8>) -> HttpResponse {
231 HttpResponse {
232 status,
233 content_type: ct.into(),
234 body,
235 www_authenticate: None,
236 extra_headers: Vec::new(),
237 }
238}
239
240fn text(status: u16, body: &[u8]) -> HttpResponse {
241 HttpResponse {
242 status,
243 content_type: "text/plain".into(),
244 body: body.to_vec(),
245 www_authenticate: None,
246 extra_headers: Vec::new(),
247 }
248}