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 pub cookie: Option<String>,
44 pub origin: Option<String>,
46 pub forwarded_proto: Option<String>,
48}
49
50impl HttpRequest {
51 pub fn new(
52 method: impl Into<String>,
53 path: impl Into<String>,
54 query: impl Into<String>,
55 body: Vec<u8>,
56 ) -> Self {
57 Self {
58 method: method.into(),
59 path: path.into(),
60 query: query.into(),
61 body,
62 git_protocol: None,
63 authorization: None,
64 destination: None,
65 lock_token: None,
66 host: None,
67 cookie: None,
68 origin: None,
69 forwarded_proto: None,
70 }
71 }
72
73 pub fn is_https(&self) -> bool {
75 self.forwarded_proto.as_deref().is_some_and(|v| {
76 v.split(',')
77 .next()
78 .unwrap_or("")
79 .trim()
80 .eq_ignore_ascii_case("https")
81 })
82 }
83}
84
85#[derive(Debug, Clone)]
86pub struct HttpResponse {
87 pub status: u16,
88 pub content_type: String,
89 pub body: Vec<u8>,
90 pub www_authenticate: Option<String>,
92 pub extra_headers: Vec<(String, String)>,
94}
95
96pub fn handle_smart_http(
98 repo: &mut Repository,
99 req: &HttpRequest,
100) -> Result<HttpResponse, ServerError> {
101 handle_smart_http_auth(repo, req, None)
102}
103
104pub fn handle_smart_http_auth(
106 repo: &mut Repository,
107 req: &HttpRequest,
108 basic: Option<&BasicAuthConfig>,
109) -> Result<HttpResponse, ServerError> {
110 handle_smart_http_auth_opts(repo, req, basic, true, "http")
111}
112
113pub fn handle_smart_http_auth_opts(
115 repo: &mut Repository,
116 req: &HttpRequest,
117 basic: Option<&BasicAuthConfig>,
118 enable_lfs: bool,
119 scheme: &str,
120) -> Result<HttpResponse, ServerError> {
121 if let Some(cfg) = basic {
122 if !cfg.check_authorization(req.authorization.as_deref()) {
123 return Ok(HttpResponse {
124 status: 401,
125 content_type: "text/plain".into(),
126 body: b"unauthorized\n".to_vec(),
127 www_authenticate: Some(cfg.challenge_header()),
128 extra_headers: Vec::new(),
129 });
130 }
131 }
132 if crate::lfs::is_lfs_path(&req.path) {
133 if enable_lfs {
134 return crate::lfs::handle_lfs(repo, req, scheme);
135 }
136 return Ok(text(404, b"LFS disabled\n"));
137 }
138 if is_dav_method(&req.method) {
139 return handle_dav(repo, req);
140 }
141 let path = req.path.as_str();
142 let wants_v2 = req
143 .git_protocol
144 .as_deref()
145 .map(|v| {
146 v.split(':')
147 .any(|p| p.trim() == "version=2" || p.trim().starts_with("version=2"))
148 })
149 .unwrap_or(false)
150 || req
151 .git_protocol
152 .as_deref()
153 .map(|v| v.contains("version=2"))
154 .unwrap_or(false);
155
156 if path.ends_with("/info/refs") || path == "/info/refs" || path.ends_with("info/refs") {
157 let service = query_param(&req.query, "service").unwrap_or("");
158 if service.is_empty() {
159 return match serve_dumb_path(repo, "info/refs")? {
161 Some((ct, body)) => Ok(typed(200, &ct, body)),
162 None => Ok(text(404, b"not found")),
163 };
164 }
165 if wants_v2 && service == "git-upload-pack" {
166 let mut body = arks_protocol::encode_text_line("# service=git-upload-pack")
169 .map_err(|e| ServerError::Protocol(e.to_string()))?;
170 body.extend(
171 arks_protocol::encode_packet(&arks_protocol::Packet::Flush)
172 .map_err(|e| ServerError::Protocol(e.to_string()))?,
173 );
174 body.extend(v2_capability_advertisement()?);
175 return Ok(typed(200, UPLOAD_AD, body));
176 }
177 return match service {
179 "git-upload-pack" => Ok(typed(200, UPLOAD_AD, upload_advertisement(repo)?)),
180 "git-receive-pack" => Ok(typed(200, RECEIVE_AD, receive_advertisement(repo)?)),
181 _ => Ok(text(403, b"unknown service")),
182 };
183 }
184 if req.method.eq_ignore_ascii_case("POST")
185 && (path.ends_with("/git-upload-pack") || path.ends_with("git-upload-pack"))
186 {
187 if looks_like_v2_command(&req.body) {
188 return Ok(typed(
189 200,
190 UPLOAD_RES,
191 handle_v2_request(repo, &req.body, true)?,
192 ));
193 }
194 return Ok(typed(200, UPLOAD_RES, upload_pack_result(repo, &req.body)?));
195 }
196 if req.method.eq_ignore_ascii_case("POST")
197 && (path.ends_with("/git-receive-pack") || path.ends_with("git-receive-pack"))
198 {
199 let pusher = Pusher {
200 transport: "http",
201 verified_user: basic.and_then(|cfg| cfg.authorized_user(req.authorization.as_deref())),
202 authorization: req.authorization.clone(),
203 };
204 return Ok(typed(
205 200,
206 RECEIVE_RES,
207 receive_pack_as(repo, &req.body, &pusher)?,
208 ));
209 }
210 if req.method.eq_ignore_ascii_case("GET") || req.method.eq_ignore_ascii_case("HEAD") {
212 let rel = path.trim_start_matches('/');
213 if let Some((ct, body)) = serve_dumb_path(repo, rel)? {
214 return Ok(typed(200, &ct, body));
215 }
216 if let Some(idx) = rel.find("objects/") {
218 if let Some((ct, body)) = serve_dumb_path(repo, &rel[idx..])? {
219 return Ok(typed(200, &ct, body));
220 }
221 }
222 if let Some(idx) = rel.find("info/refs") {
223 if let Some((ct, body)) = serve_dumb_path(repo, &rel[idx..])? {
224 return Ok(typed(200, &ct, body));
225 }
226 }
227 }
228 Ok(text(404, b"not found"))
229}
230
231fn looks_like_v2_command(body: &[u8]) -> bool {
232 body.len() >= 4 && {
234 let s = String::from_utf8_lossy(body);
235 s.contains("command=")
236 }
237}
238
239fn query_param<'a>(query: &'a str, key: &str) -> Option<&'a str> {
240 for part in query.split('&') {
241 if let Some((k, v)) = part.split_once('=') {
242 if k == key {
243 return Some(v);
244 }
245 }
246 }
247 None
248}
249
250fn typed(status: u16, ct: &str, body: Vec<u8>) -> HttpResponse {
251 HttpResponse {
252 status,
253 content_type: ct.into(),
254 body,
255 www_authenticate: None,
256 extra_headers: Vec::new(),
257 }
258}
259
260fn text(status: u16, body: &[u8]) -> HttpResponse {
261 HttpResponse {
262 status,
263 content_type: "text/plain".into(),
264 body: body.to_vec(),
265 www_authenticate: None,
266 extra_headers: Vec::new(),
267 }
268}