1use crate::auth::BasicAuthConfig;
8use crate::error::ServerError;
9use crate::http::{HttpRequest, HttpResponse, handle_smart_http_auth};
10use arks_repo::Repository;
11use rustls::ServerConfig;
12use std::io::{Read, Write};
13use std::net::{SocketAddr, TcpListener, TcpStream};
14use std::path::{Path, PathBuf};
15use std::sync::atomic::{AtomicBool, Ordering};
16use std::sync::{Arc, Mutex};
17use std::thread;
18use std::time::{Duration, Instant};
19
20type LoopbackHttp = (
21 SocketAddr,
22 Arc<AtomicBool>,
23 thread::JoinHandle<Result<(), ServerError>>,
24);
25
26pub type ListenRebindSlot = Arc<Mutex<Option<SocketAddr>>>;
30
31pub type PageHandler = Arc<dyn Fn(&HttpRequest) -> Option<HttpResponse> + Send + Sync>;
35
36#[derive(Clone, Default)]
37pub struct ServeHttpOptions {
38 pub dumb_only: bool,
41 pub basic_auth: Option<BasicAuthConfig>,
43 pub rebind_desired: Option<ListenRebindSlot>,
45 pub tls: Option<Arc<ServerConfig>>,
47 pub pages: Option<PageHandler>,
49}
50
51impl std::fmt::Debug for ServeHttpOptions {
52 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53 f.debug_struct("ServeHttpOptions")
54 .field("dumb_only", &self.dumb_only)
55 .field("basic_auth", &self.basic_auth.as_ref().map(|_| "Some(..)"))
56 .field("rebind_desired", &self.rebind_desired.is_some())
57 .field("tls", &self.tls.is_some())
58 .field("pages", &self.pages.is_some())
59 .finish()
60 }
61}
62
63pub fn serve_http(
65 git_dir: impl AsRef<Path>,
66 addr: SocketAddr,
67 stop: Arc<AtomicBool>,
68) -> Result<(), ServerError> {
69 serve_http_with_opts(git_dir, addr, stop, ServeHttpOptions::default())
70}
71
72pub fn serve_http_with_opts(
73 git_dir: impl AsRef<Path>,
74 addr: SocketAddr,
75 stop: Arc<AtomicBool>,
76 opts: ServeHttpOptions,
77) -> Result<(), ServerError> {
78 let git_dir = git_dir.as_ref().to_path_buf();
79 let mut listener = TcpListener::bind(addr)?;
80 listener.set_nonblocking(true)?;
81 let mut current = addr;
82 let mut draining: Vec<(TcpListener, SocketAddr, Instant)> = Vec::new();
85 while !stop.load(Ordering::SeqCst) {
86 if let Some(slot) = &opts.rebind_desired {
87 if let Ok(mut g) = slot.lock() {
88 if let Some(new_addr) = g.take() {
89 if new_addr != current {
90 match TcpListener::bind(new_addr) {
91 Ok(l) => {
92 if let Err(e) = l.set_nonblocking(true) {
93 eprintln!(
94 "arks serve-http: live rebind Partial bind ok but \
95 nonblocking fail ({e}); keeping {current}"
96 );
97 *g = Some(new_addr);
98 } else {
99 eprintln!(
100 "arks serve-http: live rebind dual-bind {current} → {new_addr}; \
101 prior listener draining for 5s"
102 );
103 let old = std::mem::replace(&mut listener, l);
104 draining.push((
105 old,
106 current,
107 Instant::now() + Duration::from_secs(5),
108 ));
109 current = new_addr;
110 }
111 }
112 Err(e) => {
113 eprintln!(
114 "arks serve-http: live rebind Partial fail {current} → \
115 {new_addr} ({e}); keeping prior listen"
116 );
117 }
118 }
119 }
120 }
121 }
122 }
123 draining.retain(|(_, old_addr, deadline)| {
124 if Instant::now() < *deadline {
125 true
126 } else {
127 eprintln!("arks serve-http: rebind drain complete; closing {old_addr}");
128 false
129 }
130 });
131 match listener.accept() {
132 Ok((stream, _)) => {
133 let dir = git_dir.clone();
134 let opts = opts.clone();
135 thread::spawn(move || {
136 let _ = handle_connection(stream, &dir, &opts);
137 });
138 }
139 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
140 thread::sleep(std::time::Duration::from_millis(1));
141 }
142 Err(e) => return Err(e.into()),
143 }
144 for (old_listener, _, _) in &draining {
145 match old_listener.accept() {
146 Ok((stream, _)) => {
147 let dir = git_dir.clone();
148 let opts = opts.clone();
149 thread::spawn(move || {
150 let _ = handle_connection(stream, &dir, &opts);
151 });
152 }
153 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
154 Err(e) => eprintln!("arks serve-http: draining listener accept error: {e}"),
155 }
156 }
157 }
158 Ok(())
159}
160
161pub fn spawn_loopback(git_dir: PathBuf) -> Result<LoopbackHttp, ServerError> {
163 spawn_loopback_with_opts(git_dir, ServeHttpOptions::default())
164}
165
166pub fn spawn_loopback_with_opts(
167 git_dir: PathBuf,
168 opts: ServeHttpOptions,
169) -> Result<LoopbackHttp, ServerError> {
170 let listener = TcpListener::bind("127.0.0.1:0")?;
171 let addr = listener.local_addr()?;
172 listener.set_nonblocking(true)?;
173 let stop = Arc::new(AtomicBool::new(false));
174 let stop2 = stop.clone();
175 let handle = thread::spawn(move || {
176 while !stop2.load(Ordering::SeqCst) {
177 match listener.accept() {
178 Ok((stream, _)) => {
179 let dir = git_dir.clone();
180 let opts = opts.clone();
181 thread::spawn(move || {
182 let _ = handle_connection(stream, &dir, &opts);
183 });
184 }
185 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
186 thread::sleep(std::time::Duration::from_millis(1));
187 }
188 Err(e) => return Err(e.into()),
189 }
190 }
191 Ok(())
192 });
193 Ok((addr, stop, handle))
194}
195
196pub fn serve_http_scheme(opts: &ServeHttpOptions) -> &'static str {
198 if opts.tls.is_some() { "https" } else { "http" }
199}
200
201fn handle_connection(
202 mut stream: TcpStream,
203 git_dir: &Path,
204 opts: &ServeHttpOptions,
205) -> Result<(), ServerError> {
206 stream.set_nonblocking(false)?;
208 stream.set_read_timeout(Some(std::time::Duration::from_secs(30)))?;
209 stream.set_write_timeout(Some(std::time::Duration::from_secs(30)))?;
210 if let Some(tls_cfg) = &opts.tls {
211 let conn = rustls::ServerConnection::new(tls_cfg.clone())
212 .map_err(|e| ServerError::Msg(format!("tls ServerConnection: {e}")))?;
213 let mut tls = rustls::StreamOwned::new(conn, stream);
214 tls.conn
216 .complete_io(&mut tls.sock)
217 .map_err(|e| ServerError::Msg(format!("tls handshake: {e}")))?;
218 handle_connection_io(&mut tls, git_dir, opts)
219 } else {
220 handle_connection_io(&mut stream, git_dir, opts)
221 }
222}
223
224fn handle_connection_io<S: Read + Write>(
225 stream: &mut S,
226 git_dir: &Path,
227 opts: &ServeHttpOptions,
228) -> Result<(), ServerError> {
229 let mut buf = Vec::new();
230 let mut tmp = [0u8; 8192];
231 loop {
233 let n = stream.read(&mut tmp)?;
234 if n == 0 {
235 break;
236 }
237 buf.extend_from_slice(&tmp[..n]);
238 if buf.windows(4).any(|w| w == b"\r\n\r\n") {
239 break;
240 }
241 if buf.len() > 1024 * 1024 {
242 return Err(ServerError::Protocol("headers too large".into()));
243 }
244 }
245 let header_end = buf
246 .windows(4)
247 .position(|w| w == b"\r\n\r\n")
248 .ok_or_else(|| ServerError::Protocol("incomplete headers".into()))?;
249 let header_bytes = &buf[..header_end];
250 let header_text = std::str::from_utf8(header_bytes)
251 .map_err(|_| ServerError::Protocol("headers not utf-8".into()))?;
252 let mut lines = header_text.split("\r\n");
253 let request_line = lines
254 .next()
255 .ok_or_else(|| ServerError::Protocol("missing request line".into()))?;
256 let mut parts = request_line.split_whitespace();
257 let method = parts
258 .next()
259 .ok_or_else(|| ServerError::Protocol("bad request line".into()))?
260 .to_string();
261 let target = parts
262 .next()
263 .ok_or_else(|| ServerError::Protocol("bad request line".into()))?;
264 let (path, query) = match target.split_once('?') {
265 Some((p, q)) => (p.to_string(), q.to_string()),
266 None => (target.to_string(), String::new()),
267 };
268 let mut content_length = 0usize;
269 let mut expect_continue = false;
270 let mut content_encoding = String::new();
271 let mut git_protocol = None;
272 let mut authorization = None;
273 let mut destination = None;
274 let mut lock_token = None;
275 let mut host = None;
276 for line in lines {
277 let lower = line.to_ascii_lowercase();
278 if let Some(v) = lower.strip_prefix("content-length:") {
279 content_length = v.trim().parse().unwrap_or(0);
280 }
281 if lower.starts_with("host:") {
282 if let Some((_, v)) = line.split_once(':') {
283 host = Some(v.trim().to_string());
284 }
285 }
286 if lower.starts_with("expect:") && lower.contains("100-continue") {
287 expect_continue = true;
290 }
291 if let Some(v) = lower.strip_prefix("content-encoding:") {
292 content_encoding = v.trim().to_string();
293 }
294 if lower.starts_with("git-protocol:") {
296 if let Some((_, v)) = line.split_once(':') {
297 git_protocol = Some(v.trim().to_string());
298 }
299 }
300 if lower.starts_with("authorization:") {
301 if let Some((_, v)) = line.split_once(':') {
302 authorization = Some(v.trim().to_string());
303 }
304 }
305 if lower.starts_with("destination:") {
307 if let Some((_, v)) = line.split_once(':') {
308 destination = Some(v.trim().to_string());
309 }
310 }
311 if lower.starts_with("lock-token:") {
312 if let Some((_, v)) = line.split_once(':') {
313 lock_token = Some(v.trim().to_string());
314 }
315 }
316 if lower.starts_with("if:") && lock_token.is_none() {
317 if let Some((_, v)) = line.split_once(':') {
319 let v = v.trim();
320 if let Some(start) = v.find("opaquelocktoken:") {
321 let rest = &v[start..];
322 let end = rest
323 .find(|c: char| c == ')' || c == '>' || c.is_whitespace())
324 .unwrap_or(rest.len());
325 lock_token = Some(rest[..end].to_string());
326 }
327 }
328 }
329 }
330 if expect_continue && content_length > 0 {
331 stream.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?;
332 stream.flush()?;
333 }
334 let mut body = buf[header_end + 4..].to_vec();
335 while body.len() < content_length {
336 let n = stream.read(&mut tmp)?;
337 if n == 0 {
338 break;
339 }
340 body.extend_from_slice(&tmp[..n]);
341 }
342 body.truncate(content_length);
343 let gzip_magic = body.len() >= 2 && body[0] == 0x1f && body[1] == 0x8b;
347 if content_encoding.contains("gzip") || gzip_magic {
348 use flate2::read::GzDecoder;
349 use std::io::Read as _;
350 let mut decoder = GzDecoder::new(body.as_slice());
351 let mut decoded = Vec::new();
352 decoder
353 .read_to_end(&mut decoded)
354 .map_err(|e| ServerError::Protocol(format!("gzip body: {e}")))?;
355 body = decoded;
356 }
357
358 let mut repo = Repository::open(git_dir).map_err(|e| ServerError::Msg(e.to_string()))?;
359 let mut req = HttpRequest {
360 method,
361 path: path.clone(),
362 query: query.clone(),
363 body,
364 git_protocol,
365 authorization,
366 destination,
367 lock_token,
368 host,
369 };
370 if opts.dumb_only && (req.path.ends_with("info/refs") || req.path.ends_with("/info/refs")) {
372 req.query = String::new();
373 }
374 let page = match &opts.pages {
375 Some(pages) if req.method == "GET" => pages(&req),
376 _ => None,
377 };
378 let resp = match page
379 .map(Ok)
380 .unwrap_or_else(|| handle_smart_http_auth(&mut repo, &req, opts.basic_auth.as_ref()))
381 {
382 Ok(r) => r,
383 Err(e) => {
384 let msg = e.to_string();
386 let hex: String = req
387 .body
388 .iter()
389 .take(32)
390 .map(|b| format!("{b:02x}"))
391 .collect::<Vec<_>>()
392 .join(" ");
393 eprintln!(
394 "arks serve-http error path={path} query={query} body_len={} hex32=[{hex}] : {msg}",
395 req.body.len()
396 );
397 HttpResponse {
398 status: 500,
399 content_type: "text/plain".into(),
400 body: msg.into_bytes(),
401 www_authenticate: None,
402 extra_headers: Vec::new(),
403 }
404 }
405 };
406 let status_text = match resp.status {
407 200 => "OK",
408 201 => "Created",
409 204 => "No Content",
410 207 => "Multi-Status",
411 302 => "Found",
412 400 => "Bad Request",
413 401 => "Unauthorized",
414 403 => "Forbidden",
415 404 => "Not Found",
416 405 => "Method Not Allowed",
417 409 => "Conflict",
418 423 => "Locked",
419 500 => "Internal Server Error",
420 501 => "Not Implemented",
421 _ => "Error",
422 };
423 let mut header = format!(
424 "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n",
425 resp.status,
426 status_text,
427 resp.content_type,
428 resp.body.len()
429 );
430 if let Some(ref wa) = resp.www_authenticate {
431 header.push_str(&format!("WWW-Authenticate: {wa}\r\n"));
432 }
433 for (k, v) in &resp.extra_headers {
434 header.push_str(&format!("{k}: {v}\r\n"));
435 }
436 header.push_str("\r\n");
437 stream.write_all(header.as_bytes())?;
438 stream.write_all(&resp.body)?;
439 stream.flush()?;
440 Ok(())
441}