Skip to main content

arks_server/
serve.rs

1//! Loopback smart-HTTP listener for clean-room / local serve.
2//!
3//! Optional in-process TLS terminate via operator-supplied PEMs
4//! ([[sot:root/arks-claimed-residual-gates]] B9). Dual-bind drain on rebind
5//! supports B7 Claimed evidence when harnessed.
6
7use crate::auth::BasicAuthConfig;
8use crate::error::ServerError;
9use crate::http::{HttpRequest, HttpResponse, handle_smart_http_auth_opts};
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, AtomicU64, AtomicUsize, Ordering};
16use std::sync::{Arc, Mutex, OnceLock};
17use std::thread;
18use std::time::{Duration, Instant};
19
20static HTTP_REQUESTS_TOTAL: AtomicU64 = AtomicU64::new(0);
21static HTTP_ACTIVE_CONNECTIONS: AtomicUsize = AtomicUsize::new(0);
22static SERVER_START: OnceLock<Instant> = OnceLock::new();
23
24fn max_http_body_bytes() -> usize {
25    std::env::var("ARKS_HTTP_MAX_BODY_BYTES")
26        .ok()
27        .and_then(|v| v.trim().parse::<usize>().ok())
28        .filter(|&n| n > 0)
29        .unwrap_or(64 * 1024 * 1024)
30}
31
32fn max_http_concurrency() -> usize {
33    std::env::var("ARKS_HTTP_MAX_CONCURRENCY")
34        .ok()
35        .and_then(|v| v.trim().parse::<usize>().ok())
36        .filter(|&n| n > 0)
37        .unwrap_or(128)
38}
39
40fn max_http_header_timeout() -> Duration {
41    let secs = std::env::var("ARKS_HTTP_HEADER_TIMEOUT_SECS")
42        .ok()
43        .and_then(|v| v.trim().parse::<u64>().ok())
44        .filter(|&n| n > 0)
45        .unwrap_or(10);
46    Duration::from_secs(secs)
47}
48
49/// Returns true for transient `accept()` errors (FD exhaustion `EMFILE`/`ENFILE`,
50/// aborted handshake, or interrupt) where the listener must back off rather than exit.
51pub(crate) fn is_transient_accept_error(err: &std::io::Error) -> bool {
52    if matches!(
53        err.kind(),
54        std::io::ErrorKind::WouldBlock
55            | std::io::ErrorKind::Interrupted
56            | std::io::ErrorKind::ConnectionAborted
57            | std::io::ErrorKind::ConnectionReset
58    ) {
59        return true;
60    }
61    #[cfg(unix)]
62    {
63        // ENOMEM (12), ENFILE (23), EMFILE (24), macOS ENOBUFS (55), Linux ENOBUFS (105).
64        if matches!(err.raw_os_error(), Some(12 | 23 | 24 | 55 | 105)) {
65            return true;
66        }
67    }
68    #[cfg(windows)]
69    {
70        // WSAEMFILE (10024), WSAECONNRESET (10054), WSAENOBUFS (10055).
71        if matches!(err.raw_os_error(), Some(10024 | 10054 | 10055)) {
72            return true;
73        }
74    }
75    false
76}
77
78pub(crate) struct ActiveConnGuard;
79impl Drop for ActiveConnGuard {
80    fn drop(&mut self) {
81        HTTP_ACTIVE_CONNECTIONS.fetch_sub(1, Ordering::Release);
82    }
83}
84
85/// Atomically reserve an HTTP concurrency slot up to `limit` before spawning a worker thread.
86pub(crate) fn try_reserve_http_slot_with_limit(limit: usize) -> Option<ActiveConnGuard> {
87    let mut cur = HTTP_ACTIVE_CONNECTIONS.load(Ordering::Acquire);
88    loop {
89        if cur >= limit {
90            return None;
91        }
92        match HTTP_ACTIVE_CONNECTIONS.compare_exchange_weak(
93            cur,
94            cur + 1,
95            Ordering::AcqRel,
96            Ordering::Acquire,
97        ) {
98            Ok(_) => return Some(ActiveConnGuard),
99            Err(observed) => cur = observed,
100        }
101    }
102}
103
104/// Atomically reserve an HTTP concurrency slot before spawning a worker thread.
105fn try_reserve_http_slot() -> Option<ActiveConnGuard> {
106    try_reserve_http_slot_with_limit(max_http_concurrency())
107}
108
109/// Returns the number of currently active in-flight HTTP requests (for graceful drain).
110#[allow(dead_code)]
111pub fn active_http_connections() -> usize {
112    HTTP_ACTIVE_CONNECTIONS.load(Ordering::Acquire)
113}
114
115type LoopbackHttp = (
116    SocketAddr,
117    Arc<AtomicBool>,
118    thread::JoinHandle<Result<(), ServerError>>,
119);
120
121/// Shared slot: when set to `Some(addr)`, the HTTP accept loop performs a
122/// bounded dual-bind rebind. B7 is Claimed for the evidenced HTTP scenario;
123/// SSH/forge rebind and OpenSSH-class interop are separate gates.
124pub type ListenRebindSlot = Arc<Mutex<Option<SocketAddr>>>;
125
126/// Optional page handler consulted for `GET` requests before git HTTP; it
127/// answers `Some(response)` for the paths it owns and `None` for the rest
128/// (used by `instaweb` for its repository browser pages).
129pub type PageHandler = Arc<dyn Fn(&HttpRequest) -> Option<HttpResponse> + Send + Sync>;
130
131#[derive(Clone, Default)]
132pub struct ServeHttpOptions {
133    /// When true, answer `info/refs` (even with `service=`) as dumb text/plain so
134    /// smart clients fall back to dumb HTTP (gitprotocol-http). Used by G29.
135    pub dumb_only: bool,
136    /// Optional in-process HTTP Basic (G36). Unset = unauthenticated (G15).
137    pub basic_auth: Option<BasicAuthConfig>,
138    /// Optional live listen rebind target (Partial; polled in accept loop).
139    pub rebind_desired: Option<ListenRebindSlot>,
140    /// Optional rustls server config for in-process TLS terminate (B9).
141    pub tls: Option<Arc<ServerConfig>>,
142    /// Optional browser pages served beside git HTTP.
143    pub pages: Option<PageHandler>,
144    /// When true, disable the built-in `/info/lfs` Batch + Basic Transfer server (`--no-lfs`).
145    pub disable_lfs: bool,
146    /// When true, `git_dir` is a multi-repository root directory and `pages` handles all routes
147    /// (Web UI + `/<repo>.git/...` Smart HTTP/LFS) without opening a single repo at `git_dir`.
148    pub multi_repo_root: bool,
149    /// Optional cumulative HTTP header-read deadline override (falls back to
150    /// `ARKS_HTTP_HEADER_TIMEOUT_SECS`, default 10s).
151    pub header_timeout: Option<Duration>,
152}
153
154impl std::fmt::Debug for ServeHttpOptions {
155    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156        f.debug_struct("ServeHttpOptions")
157            .field("dumb_only", &self.dumb_only)
158            .field("basic_auth", &self.basic_auth.as_ref().map(|_| "Some(..)"))
159            .field("rebind_desired", &self.rebind_desired.is_some())
160            .field("tls", &self.tls.is_some())
161            .field("pages", &self.pages.is_some())
162            .field("disable_lfs", &self.disable_lfs)
163            .field("multi_repo_root", &self.multi_repo_root)
164            .field("header_timeout", &self.header_timeout)
165            .finish()
166    }
167}
168
169/// Bind `addr` and serve `git_dir` over smart HTTP until `stop` is set or accept fails.
170pub fn serve_http(
171    git_dir: impl AsRef<Path>,
172    addr: SocketAddr,
173    stop: Arc<AtomicBool>,
174) -> Result<(), ServerError> {
175    serve_http_with_opts(git_dir, addr, stop, ServeHttpOptions::default())
176}
177
178pub fn serve_http_with_opts(
179    git_dir: impl AsRef<Path>,
180    addr: SocketAddr,
181    stop: Arc<AtomicBool>,
182    opts: ServeHttpOptions,
183) -> Result<(), ServerError> {
184    let git_dir = git_dir.as_ref().to_path_buf();
185    let _ = crate::web_ui::store::sweep_stale_temps(&git_dir, opts.multi_repo_root);
186    let mut listener = TcpListener::bind(addr)?;
187    listener.set_nonblocking(true)?;
188    let mut current = addr;
189    // A successful rebind keeps prior listeners accepting for this bounded
190    // overlap. Accepted handlers are independently owned and always drain.
191    let mut draining: Vec<(TcpListener, SocketAddr, Instant)> = Vec::new();
192    let mut last_accept_err_log: Option<Instant> = None;
193    while !stop.load(Ordering::SeqCst) {
194        if let Some(slot) = &opts.rebind_desired {
195            if let Ok(mut g) = slot.lock() {
196                if let Some(new_addr) = g.take() {
197                    if new_addr != current {
198                        match TcpListener::bind(new_addr) {
199                            Ok(l) => {
200                                if let Err(e) = l.set_nonblocking(true) {
201                                    eprintln!(
202                                        "arks serve-http: live rebind Partial bind ok but \
203                                         nonblocking fail ({e}); keeping {current}"
204                                    );
205                                    *g = Some(new_addr);
206                                } else {
207                                    eprintln!(
208                                        "arks serve-http: live rebind dual-bind {current} → {new_addr}; \
209                                         prior listener draining for 5s"
210                                    );
211                                    let old = std::mem::replace(&mut listener, l);
212                                    draining.push((
213                                        old,
214                                        current,
215                                        Instant::now() + Duration::from_secs(5),
216                                    ));
217                                    current = new_addr;
218                                }
219                            }
220                            Err(e) => {
221                                eprintln!(
222                                    "arks serve-http: live rebind Partial fail {current} → \
223                                     {new_addr} ({e}); keeping prior listen"
224                                );
225                            }
226                        }
227                    }
228                }
229            }
230        }
231        draining.retain(|(_, old_addr, deadline)| {
232            if Instant::now() < *deadline {
233                true
234            } else {
235                eprintln!("arks serve-http: rebind drain complete; closing {old_addr}");
236                false
237            }
238        });
239        match listener.accept() {
240            Ok((stream, _)) => {
241                dispatch_accepted_stream(stream, &git_dir, &opts);
242            }
243            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
244                thread::sleep(std::time::Duration::from_millis(1));
245            }
246            Err(e) if is_transient_accept_error(&e) => {
247                if last_accept_err_log
248                    .map(|t| t.elapsed() >= Duration::from_secs(1))
249                    .unwrap_or(true)
250                {
251                    eprintln!(
252                        "arks serve-http: transient accept error on {current} ({e}); backing off"
253                    );
254                    last_accept_err_log = Some(Instant::now());
255                }
256                thread::sleep(std::time::Duration::from_millis(25));
257            }
258            Err(e) => return Err(e.into()),
259        }
260        for (old_listener, _, _) in &draining {
261            match old_listener.accept() {
262                Ok((stream, _)) => {
263                    dispatch_accepted_stream(stream, &git_dir, &opts);
264                }
265                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
266                Err(e) => {
267                    if last_accept_err_log
268                        .map(|t| t.elapsed() >= Duration::from_secs(1))
269                        .unwrap_or(true)
270                    {
271                        eprintln!("arks serve-http: draining listener accept error: {e}");
272                        last_accept_err_log = Some(Instant::now());
273                    }
274                }
275            }
276        }
277    }
278    // Graceful shutdown: wait for in-flight HTTP/Git requests to finish (up to 10s).
279    let drain_secs = std::env::var("ARKS_SHUTDOWN_DRAIN_SECS")
280        .ok()
281        .and_then(|v| v.trim().parse::<u64>().ok())
282        .unwrap_or(10);
283    let drain_deadline = Instant::now() + Duration::from_secs(drain_secs);
284    while active_http_connections() > 0 && Instant::now() < drain_deadline {
285        thread::sleep(Duration::from_millis(25));
286    }
287    Ok(())
288}
289
290/// Bind an ephemeral port; return (bound addr, join handle, stop flag).
291pub fn spawn_loopback(git_dir: PathBuf) -> Result<LoopbackHttp, ServerError> {
292    spawn_loopback_with_opts(git_dir, ServeHttpOptions::default())
293}
294
295pub fn spawn_loopback_with_opts(
296    git_dir: PathBuf,
297    opts: ServeHttpOptions,
298) -> Result<LoopbackHttp, ServerError> {
299    let _ = crate::web_ui::store::sweep_stale_temps(&git_dir, opts.multi_repo_root);
300    let listener = TcpListener::bind("127.0.0.1:0")?;
301    let addr = listener.local_addr()?;
302    listener.set_nonblocking(true)?;
303    let stop = Arc::new(AtomicBool::new(false));
304    let stop2 = stop.clone();
305    let handle = thread::spawn(move || {
306        let mut last_accept_err_log: Option<Instant> = None;
307        while !stop2.load(Ordering::SeqCst) {
308            match listener.accept() {
309                Ok((stream, _)) => {
310                    dispatch_accepted_stream(stream, &git_dir, &opts);
311                }
312                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
313                    thread::sleep(std::time::Duration::from_millis(1));
314                }
315                Err(e) if is_transient_accept_error(&e) => {
316                    if last_accept_err_log
317                        .map(|t| t.elapsed() >= Duration::from_secs(1))
318                        .unwrap_or(true)
319                    {
320                        eprintln!(
321                            "arks serve-http: transient loopback accept error ({e}); backing off"
322                        );
323                        last_accept_err_log = Some(Instant::now());
324                    }
325                    thread::sleep(std::time::Duration::from_millis(25));
326                }
327                Err(e) => return Err(e.into()),
328            }
329        }
330        Ok(())
331    });
332    Ok((addr, stop, handle))
333}
334
335fn send_fast_503(stream: &mut TcpStream) {
336    let _ = stream.set_nonblocking(false);
337    let _ = stream.set_write_timeout(Some(Duration::from_secs(2)));
338    let resp = HttpResponse {
339        status: 503,
340        content_type: "text/plain; charset=utf-8".into(),
341        body: b"Service Unavailable: max concurrent connections reached\n".to_vec(),
342        www_authenticate: None,
343        extra_headers: vec![("Retry-After".into(), "1".into())],
344    };
345    let _ = write_http_response(stream, &resp);
346    let _ = stream.shutdown(std::net::Shutdown::Write);
347}
348
349fn send_fast_408<S: HttpStream>(stream: &mut S) {
350    let resp = HttpResponse {
351        status: 408,
352        content_type: "text/plain; charset=utf-8".into(),
353        body: b"Request Timeout: HTTP header deadline exceeded\n".to_vec(),
354        www_authenticate: None,
355        extra_headers: Vec::new(),
356    };
357    let _ = write_http_response(stream, &resp);
358    stream.shutdown_write();
359}
360
361/// Atomically reserve a concurrency slot and dispatch a worker thread (fail-closed on saturation
362/// or OS thread exhaustion — never panics and never spawns above `ARKS_HTTP_MAX_CONCURRENCY`).
363fn dispatch_accepted_stream(mut stream: TcpStream, git_dir: &Path, opts: &ServeHttpOptions) {
364    let Some(guard) = try_reserve_http_slot() else {
365        send_fast_503(&mut stream);
366        return;
367    };
368    let dir = git_dir.to_path_buf();
369    let opts = opts.clone();
370    if let Err(e) = thread::Builder::new()
371        .name("arks-http-worker".into())
372        .spawn(move || {
373            let _ = handle_connection(stream, &dir, &opts, guard);
374        })
375    {
376        // Dropping the closure automatically drops `guard` (freeing the slot) and `stream`.
377        eprintln!("arks serve-http: worker thread spawn failed ({e}); rejecting connection");
378        thread::sleep(Duration::from_millis(10));
379    }
380}
381
382/// Scheme label for listen banners (`http` or `https`).
383pub fn serve_http_scheme(opts: &ServeHttpOptions) -> &'static str {
384    if opts.tls.is_some() { "https" } else { "http" }
385}
386
387const MAX_KEEP_ALIVE_REQUESTS: usize = 64;
388const KEEP_ALIVE_IDLE_SECS: u64 = 5;
389
390trait HttpStream: Read + Write {
391    fn set_stream_read_timeout(&mut self, timeout: Duration);
392    fn shutdown_write(&mut self);
393}
394
395impl HttpStream for TcpStream {
396    fn set_stream_read_timeout(&mut self, timeout: Duration) {
397        let _ = self.set_read_timeout(Some(timeout));
398    }
399    fn shutdown_write(&mut self) {
400        let _ = self.shutdown(std::net::Shutdown::Write);
401    }
402}
403
404impl HttpStream for rustls::StreamOwned<rustls::ServerConnection, TcpStream> {
405    fn set_stream_read_timeout(&mut self, timeout: Duration) {
406        let _ = self.sock.set_read_timeout(Some(timeout));
407    }
408    fn shutdown_write(&mut self) {
409        let _ = self.sock.shutdown(std::net::Shutdown::Write);
410    }
411}
412
413fn handle_connection(
414    mut stream: TcpStream,
415    git_dir: &Path,
416    opts: &ServeHttpOptions,
417    _guard: ActiveConnGuard,
418) -> Result<(), ServerError> {
419    let _ = SERVER_START.get_or_init(Instant::now);
420    // Listener is nonblocking; accepted sockets may inherit that on Windows.
421    stream.set_nonblocking(false)?;
422    let _ = stream.set_nodelay(true);
423    stream.set_read_timeout(Some(std::time::Duration::from_secs(30)))?;
424    stream.set_write_timeout(Some(std::time::Duration::from_secs(30)))?;
425    if let Some(tls_cfg) = &opts.tls {
426        let conn = rustls::ServerConnection::new(tls_cfg.clone())
427            .map_err(|e| ServerError::Msg(format!("tls ServerConnection: {e}")))?;
428        let mut tls = rustls::StreamOwned::new(conn, stream);
429        // Complete handshake before HTTP parse.
430        tls.conn
431            .complete_io(&mut tls.sock)
432            .map_err(|e| ServerError::Msg(format!("tls handshake: {e}")))?;
433        handle_connection_io(&mut tls, git_dir, opts)
434    } else {
435        handle_connection_io(&mut stream, git_dir, opts)
436    }
437}
438
439fn handle_connection_io<S: HttpStream>(
440    stream: &mut S,
441    git_dir: &Path,
442    opts: &ServeHttpOptions,
443) -> Result<(), ServerError> {
444    let mut buf = Vec::with_capacity(4096);
445    let mut tmp = [0u8; 8192];
446    let header_timeout = opts.header_timeout.unwrap_or_else(max_http_header_timeout);
447    for req_idx in 0..MAX_KEEP_ALIVE_REQUESTS {
448        let mut header_deadline = if req_idx == 0 {
449            Some(Instant::now() + header_timeout)
450        } else {
451            stream.set_stream_read_timeout(Duration::from_secs(KEEP_ALIVE_IDLE_SECS));
452            None
453        };
454        let mut header_end = buf.windows(4).position(|w| w == b"\r\n\r\n");
455        // Read headers in O(N) by scanning only newly arrived bytes (plus 3-byte overlap),
456        // bounded by a cumulative header deadline to defeat Slowloris dribbles.
457        while header_end.is_none() {
458            if let Some(dl) = header_deadline {
459                let now = Instant::now();
460                if now >= dl {
461                    send_fast_408(stream);
462                    return Ok(());
463                }
464                let rem = dl
465                    .saturating_duration_since(now)
466                    .max(Duration::from_millis(1));
467                stream.set_stream_read_timeout(rem);
468            }
469            let prev_len = buf.len();
470            match stream.read(&mut tmp) {
471                Ok(0) => {
472                    if req_idx > 0 && buf.is_empty() {
473                        return Ok(());
474                    }
475                    break;
476                }
477                Ok(n) => {
478                    if header_deadline.is_none() {
479                        header_deadline = Some(Instant::now() + header_timeout);
480                    }
481                    buf.extend_from_slice(&tmp[..n]);
482                    let search_from = prev_len.saturating_sub(3);
483                    if let Some(rel) = buf[search_from..].windows(4).position(|w| w == b"\r\n\r\n")
484                    {
485                        header_end = Some(search_from + rel);
486                        break;
487                    }
488                    if buf.len() > 1024 * 1024 {
489                        return Err(ServerError::Protocol("headers too large".into()));
490                    }
491                    if header_deadline.is_some_and(|dl| Instant::now() >= dl) {
492                        send_fast_408(stream);
493                        return Ok(());
494                    }
495                }
496                Err(e)
497                    if req_idx > 0
498                        && buf.is_empty()
499                        && matches!(
500                            e.kind(),
501                            std::io::ErrorKind::WouldBlock
502                                | std::io::ErrorKind::TimedOut
503                                | std::io::ErrorKind::ConnectionReset
504                                | std::io::ErrorKind::UnexpectedEof
505                        ) =>
506                {
507                    return Ok(());
508                }
509                Err(e)
510                    if header_deadline.is_some()
511                        && matches!(
512                            e.kind(),
513                            std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
514                        ) =>
515                {
516                    send_fast_408(stream);
517                    return Ok(());
518                }
519                Err(e) => return Err(e.into()),
520            }
521        }
522        let Some(header_end) = header_end else {
523            if req_idx > 0 && buf.is_empty() {
524                return Ok(());
525            }
526            return Err(ServerError::Protocol("incomplete headers".into()));
527        };
528        // Restore full body-streaming read timeout once HTTP headers are complete.
529        stream.set_stream_read_timeout(Duration::from_secs(30));
530        HTTP_REQUESTS_TOTAL.fetch_add(1, Ordering::Relaxed);
531        let header_bytes = &buf[..header_end];
532        let header_text = std::str::from_utf8(header_bytes)
533            .map_err(|_| ServerError::Protocol("headers not utf-8".into()))?;
534        let mut lines = header_text.split("\r\n");
535        let request_line = lines
536            .next()
537            .ok_or_else(|| ServerError::Protocol("missing request line".into()))?;
538        let mut parts = request_line.split_whitespace();
539        let method = parts
540            .next()
541            .ok_or_else(|| ServerError::Protocol("bad request line".into()))?
542            .to_string();
543        let target = parts
544            .next()
545            .ok_or_else(|| ServerError::Protocol("bad request line".into()))?;
546        let http_version = parts.next().unwrap_or("HTTP/1.1");
547        let (path, query) = match target.split_once('?') {
548            Some((p, q)) => (p.to_string(), q.to_string()),
549            None => (target.to_string(), String::new()),
550        };
551        let mut content_length = 0usize;
552        let mut expect_continue = false;
553        let mut content_encoding = String::new();
554        let mut connection_close = false;
555        let mut connection_keep_alive = false;
556        let mut git_protocol = None;
557        let mut authorization = None;
558        let mut destination = None;
559        let mut lock_token = None;
560        let mut host = None;
561        let mut cookie = None;
562        let mut origin = None;
563        let mut forwarded_proto = None;
564        for line in lines {
565            let lower = line.to_ascii_lowercase();
566            if let Some(v) = lower.strip_prefix("content-length:") {
567                content_length = v.trim().parse().unwrap_or(0);
568            }
569            if let Some(v) = lower.strip_prefix("connection:") {
570                if v.contains("close") {
571                    connection_close = true;
572                }
573                if v.contains("keep-alive") {
574                    connection_keep_alive = true;
575                }
576            }
577            if lower.starts_with("host:") {
578                if let Some((_, v)) = line.split_once(':') {
579                    host = Some(v.trim().to_string());
580                }
581            }
582            if lower.starts_with("cookie:") {
583                if let Some((_, v)) = line.split_once(':') {
584                    cookie = Some(v.trim().to_string());
585                }
586            }
587            if lower.starts_with("origin:") {
588                if let Some((_, v)) = line.split_once(':') {
589                    origin = Some(v.trim().to_string());
590                }
591            }
592            if lower.starts_with("x-forwarded-proto:") {
593                if let Some((_, v)) = line.split_once(':') {
594                    forwarded_proto = Some(v.trim().to_string());
595                }
596            }
597            if lower.starts_with("expect:") && lower.contains("100-continue") {
598                // git/curl POST often waits for 100 before sending the pack body
599                // (gitprotocol-http / HTTP/1.1). Without this, clients see empty replies.
600                expect_continue = true;
601            }
602            if let Some(v) = lower.strip_prefix("content-encoding:") {
603                content_encoding = v.trim().to_string();
604            }
605            // gitprotocol-v2: clients send `Git-Protocol: version=2`.
606            if lower.starts_with("git-protocol:") {
607                if let Some((_, v)) = line.split_once(':') {
608                    git_protocol = Some(v.trim().to_string());
609                }
610            }
611            if lower.starts_with("authorization:") {
612                if let Some((_, v)) = line.split_once(':') {
613                    authorization = Some(v.trim().to_string());
614                }
615            }
616            // WebDAV (RFC 4918) — dumb HTTP push (git-http-push).
617            if lower.starts_with("destination:") {
618                if let Some((_, v)) = line.split_once(':') {
619                    destination = Some(v.trim().to_string());
620                }
621            }
622            if lower.starts_with("lock-token:") {
623                if let Some((_, v)) = line.split_once(':') {
624                    lock_token = Some(v.trim().to_string());
625                }
626            }
627            if lower.starts_with("if:") && lock_token.is_none() {
628                // git-http-push sends `If: (<opaquelocktoken:…>)` with the lock.
629                if let Some((_, v)) = line.split_once(':') {
630                    let v = v.trim();
631                    if let Some(start) = v.find("opaquelocktoken:") {
632                        let rest = &v[start..];
633                        let end = rest
634                            .find(|c: char| c == ')' || c == '>' || c.is_whitespace())
635                            .unwrap_or(rest.len());
636                        lock_token = Some(rest[..end].to_string());
637                    }
638                }
639            }
640        }
641        let want_keep_alive = if http_version.eq_ignore_ascii_case("HTTP/1.0") {
642            connection_keep_alive && !connection_close
643        } else {
644            !connection_close
645        };
646        let keep_alive_rem = if want_keep_alive && req_idx + 1 < MAX_KEEP_ALIVE_REQUESTS {
647            Some(MAX_KEEP_ALIVE_REQUESTS - req_idx - 1)
648        } else {
649            None
650        };
651        let body_start = header_end + 4;
652        if path == "/healthz" || path == "/readyz" {
653            let body = b"{\"status\":\"ok\"}\n";
654            let resp = HttpResponse {
655                status: 200,
656                content_type: "application/json; charset=utf-8".into(),
657                body: body.to_vec(),
658                www_authenticate: None,
659                extra_headers: vec![("Cache-Control".into(), "no-store".into())],
660            };
661            buf.drain(..body_start.min(buf.len()));
662            write_http_response_with_options(stream, &resp, opts.tls.is_some(), keep_alive_rem)?;
663            if keep_alive_rem.is_some() {
664                continue;
665            }
666            return Ok(());
667        }
668        if path == "/metrics" {
669            let total = HTTP_REQUESTS_TOTAL.load(Ordering::Relaxed);
670            let active = HTTP_ACTIVE_CONNECTIONS.load(Ordering::Relaxed);
671            let uptime = SERVER_START.get_or_init(Instant::now).elapsed().as_secs();
672            let metrics = format!(
673                "# HELP arks_http_requests_total Total HTTP requests handled by arks serve.\n\
674                 # TYPE arks_http_requests_total counter\n\
675                 arks_http_requests_total {total}\n\
676                 # HELP arks_http_active_connections Currently active HTTP worker connections.\n\
677                 # TYPE arks_http_active_connections gauge\n\
678                 arks_http_active_connections {active}\n\
679                 # HELP arks_uptime_seconds Server process uptime in seconds.\n\
680                 # TYPE arks_uptime_seconds gauge\n\
681                 arks_uptime_seconds {uptime}\n"
682            );
683            let resp = HttpResponse {
684                status: 200,
685                content_type: "text/plain; version=0.0.4; charset=utf-8".into(),
686                body: metrics.into_bytes(),
687                www_authenticate: None,
688                extra_headers: vec![("Cache-Control".into(), "no-store".into())],
689            };
690            buf.drain(..body_start.min(buf.len()));
691            write_http_response_with_options(stream, &resp, opts.tls.is_some(), keep_alive_rem)?;
692            if keep_alive_rem.is_some() {
693                continue;
694            }
695            return Ok(());
696        }
697        let max_body = max_http_body_bytes();
698        if content_length > max_body {
699            let resp = HttpResponse {
700                status: 413,
701                content_type: "text/plain; charset=utf-8".into(),
702                body: format!("Payload Too Large (max {max_body} bytes)\n").into_bytes(),
703                www_authenticate: None,
704                extra_headers: Vec::new(),
705            };
706            return write_http_response(stream, &resp);
707        }
708        if expect_continue && content_length > 0 {
709            stream.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?;
710            stream.flush()?;
711        }
712        let total_needed = body_start.saturating_add(content_length);
713        while buf.len() < total_needed {
714            let n = stream.read(&mut tmp)?;
715            if n == 0 {
716                break;
717            }
718            buf.extend_from_slice(&tmp[..n]);
719        }
720        let avail_end = total_needed.min(buf.len());
721        let mut body = buf[body_start..avail_end].to_vec();
722        buf.drain(..avail_end);
723        // Stock git/curl may gzip the upload-pack / receive-pack POST once the prior
724        // advertisement is large (observed ~32+ refs). Accept Content-Encoding: gzip
725        // and gzip magic even if the header is omitted — except for raw binary LFS PUTs!
726        let is_lfs = crate::lfs::is_lfs_path(&path);
727        let gzip_magic = !is_lfs && body.len() >= 2 && body[0] == 0x1f && body[1] == 0x8b;
728        if content_encoding.contains("gzip") || gzip_magic {
729            use flate2::read::GzDecoder;
730            use std::io::Read as _;
731            let decoder = GzDecoder::new(body.as_slice());
732            let mut decoded = Vec::new();
733            decoder
734                .take((max_body as u64).saturating_add(1))
735                .read_to_end(&mut decoded)
736                .map_err(|e| ServerError::Protocol(format!("gzip body: {e}")))?;
737            if decoded.len() > max_body {
738                let resp = HttpResponse {
739                    status: 413,
740                    content_type: "text/plain; charset=utf-8".into(),
741                    body: format!(
742                        "Payload Too Large (decompressed exceeds max {max_body} bytes)\n"
743                    )
744                    .into_bytes(),
745                    www_authenticate: None,
746                    extra_headers: Vec::new(),
747                };
748                return write_http_response(stream, &resp);
749            }
750            body = decoded;
751        }
752
753        let mut req = HttpRequest {
754            method,
755            path: path.clone(),
756            query: query.clone(),
757            body,
758            git_protocol,
759            authorization,
760            destination,
761            lock_token,
762            host,
763            cookie,
764            origin,
765            forwarded_proto: forwarded_proto.or_else(|| {
766                if opts.tls.is_some() {
767                    Some("https".into())
768                } else {
769                    None
770                }
771            }),
772        };
773        let resp = if opts.multi_repo_root {
774            match opts.pages.as_ref().and_then(|p| p(&req)) {
775                Some(r) => r,
776                None => HttpResponse {
777                    status: 404,
778                    content_type: "text/plain; charset=utf-8".into(),
779                    body: b"repository or path not found\n".to_vec(),
780                    www_authenticate: None,
781                    extra_headers: Vec::new(),
782                },
783            }
784        } else {
785            let mut repo =
786                Repository::open(git_dir).map_err(|e| ServerError::Msg(e.to_string()))?;
787            // dumb_only: strip service= so discovery uses dumb info/refs (smart clients fall back).
788            if opts.dumb_only
789                && (req.path.ends_with("info/refs") || req.path.ends_with("/info/refs"))
790            {
791                req.query = String::new();
792            }
793            let is_git_rpc = req.path.contains("/git-upload-pack")
794                || req.path.contains("/git-receive-pack")
795                || req.path.contains("/info/refs");
796            let page = match &opts.pages {
797                Some(pages)
798                    if matches!(req.method.as_str(), "GET" | "POST" | "PATCH" | "DELETE")
799                        && !is_lfs
800                        && !is_git_rpc =>
801                {
802                    pages(&req)
803                }
804                _ => None,
805            };
806            let scheme = serve_http_scheme(opts);
807            let is_git_write = req.path.contains("/git-receive-pack")
808                || (req.path.contains("/info/refs") && req.query.contains("git-receive-pack"))
809                || (req.path.contains("/info/lfs/") && req.method == "PUT");
810            let auth_denied = if page.is_none() && opts.basic_auth.is_none() {
811                crate::web_ui::check_git_http_auth(git_dir, &req, is_git_write).err()
812            } else {
813                None
814            };
815            match page.or(auth_denied).map(Ok).unwrap_or_else(|| {
816                handle_smart_http_auth_opts(
817                    &mut repo,
818                    &req,
819                    opts.basic_auth.as_ref(),
820                    !opts.disable_lfs,
821                    scheme,
822                )
823            }) {
824                Ok(r) => r,
825                Err(e) => {
826                    // Fail closed with an HTTP error body (never silent empty close).
827                    let msg = e.to_string();
828                    let hex: String = req
829                        .body
830                        .iter()
831                        .take(32)
832                        .map(|b| format!("{b:02x}"))
833                        .collect::<Vec<_>>()
834                        .join(" ");
835                    eprintln!(
836                        "arks serve-http error path={path} query={query} body_len={} hex32=[{hex}] : {msg}",
837                        req.body.len()
838                    );
839                    HttpResponse {
840                        status: 500,
841                        content_type: "text/plain".into(),
842                        body: msg.into_bytes(),
843                        www_authenticate: None,
844                        extra_headers: Vec::new(),
845                    }
846                }
847            }
848        };
849        let keep_alive = if matches!(resp.status, 408 | 413 | 503) {
850            None
851        } else {
852            keep_alive_rem
853        };
854        write_http_response_with_options(stream, &resp, req.is_https(), keep_alive)?;
855        if keep_alive.is_none() {
856            return Ok(());
857        }
858    }
859    Ok(())
860}
861
862fn write_http_response<S: Write>(stream: &mut S, resp: &HttpResponse) -> Result<(), ServerError> {
863    write_http_response_with_options(stream, resp, false, None)
864}
865
866fn write_http_response_with_options<S: Write>(
867    stream: &mut S,
868    resp: &HttpResponse,
869    is_https: bool,
870    keep_alive_remaining: Option<usize>,
871) -> Result<(), ServerError> {
872    let status_text = match resp.status {
873        200 => "OK",
874        201 => "Created",
875        204 => "No Content",
876        207 => "Multi-Status",
877        302 => "Found",
878        303 => "See Other",
879        400 => "Bad Request",
880        401 => "Unauthorized",
881        403 => "Forbidden",
882        404 => "Not Found",
883        405 => "Method Not Allowed",
884        408 => "Request Timeout",
885        409 => "Conflict",
886        413 => "Payload Too Large",
887        422 => "Unprocessable Entity",
888        423 => "Locked",
889        429 => "Too Many Requests",
890        500 => "Internal Server Error",
891        501 => "Not Implemented",
892        503 => "Service Unavailable",
893        _ => "Error",
894    };
895    let conn_header = match keep_alive_remaining {
896        Some(rem) => format!(
897            "Connection: keep-alive\r\nKeep-Alive: timeout={KEEP_ALIVE_IDLE_SECS}, max={rem}\r\n"
898        ),
899        None => "Connection: close\r\n".to_string(),
900    };
901    let mut header = format!(
902        "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\n{}",
903        resp.status,
904        status_text,
905        resp.content_type,
906        resp.body.len(),
907        conn_header
908    );
909    if let Some(ref wa) = resp.www_authenticate {
910        header.push_str(&format!("WWW-Authenticate: {wa}\r\n"));
911    }
912    let mut has_xfo = false;
913    let mut has_rp = false;
914    let mut has_hsts = false;
915    for (k, v) in &resp.extra_headers {
916        if k.eq_ignore_ascii_case("x-frame-options") {
917            has_xfo = true;
918        } else if k.eq_ignore_ascii_case("referrer-policy") {
919            has_rp = true;
920        } else if k.eq_ignore_ascii_case("strict-transport-security") {
921            has_hsts = true;
922        }
923        header.push_str(&format!("{k}: {v}\r\n"));
924    }
925    if resp.content_type.starts_with("text/html") {
926        if !has_xfo {
927            header.push_str("X-Frame-Options: DENY\r\n");
928        }
929        if !has_rp {
930            header.push_str("Referrer-Policy: same-origin\r\n");
931        }
932    }
933    if is_https && !has_hsts {
934        header.push_str("Strict-Transport-Security: max-age=31536000; includeSubDomains\r\n");
935    }
936    header.push_str("\r\n");
937    if resp.body.len() <= 64 * 1024 {
938        let mut combined = Vec::with_capacity(header.len() + resp.body.len());
939        combined.extend_from_slice(header.as_bytes());
940        combined.extend_from_slice(&resp.body);
941        stream.write_all(&combined)?;
942    } else {
943        stream.write_all(header.as_bytes())?;
944        stream.write_all(&resp.body)?;
945    }
946    stream.flush()?;
947    Ok(())
948}