arks-server 1.3.0

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
Documentation
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
//! Loopback smart-HTTP listener for clean-room / local serve.
//!
//! Optional in-process TLS terminate via operator-supplied PEMs
//! ([[sot:root/arks-claimed-residual-gates]] B9). Dual-bind drain on rebind
//! supports B7 Claimed evidence when harnessed.

use crate::auth::BasicAuthConfig;
use crate::error::ServerError;
use crate::http::{HttpRequest, HttpResponse, handle_smart_http_auth_opts};
use arks_repo::Repository;
use rustls::ServerConfig;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::thread;
use std::time::{Duration, Instant};

static HTTP_REQUESTS_TOTAL: AtomicU64 = AtomicU64::new(0);
static HTTP_ACTIVE_CONNECTIONS: AtomicUsize = AtomicUsize::new(0);
static SERVER_START: OnceLock<Instant> = OnceLock::new();

fn max_http_body_bytes() -> usize {
    std::env::var("ARKS_HTTP_MAX_BODY_BYTES")
        .ok()
        .and_then(|v| v.trim().parse::<usize>().ok())
        .filter(|&n| n > 0)
        .unwrap_or(64 * 1024 * 1024)
}

fn max_http_concurrency() -> usize {
    std::env::var("ARKS_HTTP_MAX_CONCURRENCY")
        .ok()
        .and_then(|v| v.trim().parse::<usize>().ok())
        .filter(|&n| n > 0)
        .unwrap_or(128)
}

fn max_http_header_timeout() -> Duration {
    let secs = std::env::var("ARKS_HTTP_HEADER_TIMEOUT_SECS")
        .ok()
        .and_then(|v| v.trim().parse::<u64>().ok())
        .filter(|&n| n > 0)
        .unwrap_or(10);
    Duration::from_secs(secs)
}

/// Returns true for transient `accept()` errors (FD exhaustion `EMFILE`/`ENFILE`,
/// aborted handshake, or interrupt) where the listener must back off rather than exit.
pub(crate) fn is_transient_accept_error(err: &std::io::Error) -> bool {
    if matches!(
        err.kind(),
        std::io::ErrorKind::WouldBlock
            | std::io::ErrorKind::Interrupted
            | std::io::ErrorKind::ConnectionAborted
            | std::io::ErrorKind::ConnectionReset
    ) {
        return true;
    }
    #[cfg(unix)]
    {
        // ENOMEM (12), ENFILE (23), EMFILE (24), macOS ENOBUFS (55), Linux ENOBUFS (105).
        if matches!(err.raw_os_error(), Some(12 | 23 | 24 | 55 | 105)) {
            return true;
        }
    }
    #[cfg(windows)]
    {
        // WSAEMFILE (10024), WSAECONNRESET (10054), WSAENOBUFS (10055).
        if matches!(err.raw_os_error(), Some(10024 | 10054 | 10055)) {
            return true;
        }
    }
    false
}

pub(crate) struct ActiveConnGuard;
impl Drop for ActiveConnGuard {
    fn drop(&mut self) {
        HTTP_ACTIVE_CONNECTIONS.fetch_sub(1, Ordering::Release);
    }
}

/// Atomically reserve an HTTP concurrency slot up to `limit` before spawning a worker thread.
pub(crate) fn try_reserve_http_slot_with_limit(limit: usize) -> Option<ActiveConnGuard> {
    let mut cur = HTTP_ACTIVE_CONNECTIONS.load(Ordering::Acquire);
    loop {
        if cur >= limit {
            return None;
        }
        match HTTP_ACTIVE_CONNECTIONS.compare_exchange_weak(
            cur,
            cur + 1,
            Ordering::AcqRel,
            Ordering::Acquire,
        ) {
            Ok(_) => return Some(ActiveConnGuard),
            Err(observed) => cur = observed,
        }
    }
}

/// Atomically reserve an HTTP concurrency slot before spawning a worker thread.
fn try_reserve_http_slot() -> Option<ActiveConnGuard> {
    try_reserve_http_slot_with_limit(max_http_concurrency())
}

/// Returns the number of currently active in-flight HTTP requests (for graceful drain).
#[allow(dead_code)]
pub fn active_http_connections() -> usize {
    HTTP_ACTIVE_CONNECTIONS.load(Ordering::Acquire)
}

type LoopbackHttp = (
    SocketAddr,
    Arc<AtomicBool>,
    thread::JoinHandle<Result<(), ServerError>>,
);

/// Shared slot: when set to `Some(addr)`, the HTTP accept loop performs a
/// bounded dual-bind rebind. B7 is Claimed for the evidenced HTTP scenario;
/// SSH/forge rebind and OpenSSH-class interop are separate gates.
pub type ListenRebindSlot = Arc<Mutex<Option<SocketAddr>>>;

/// Optional page handler consulted for `GET` requests before git HTTP; it
/// answers `Some(response)` for the paths it owns and `None` for the rest
/// (used by `instaweb` for its repository browser pages).
pub type PageHandler = Arc<dyn Fn(&HttpRequest) -> Option<HttpResponse> + Send + Sync>;

#[derive(Clone, Default)]
pub struct ServeHttpOptions {
    /// When true, answer `info/refs` (even with `service=`) as dumb text/plain so
    /// smart clients fall back to dumb HTTP (gitprotocol-http). Used by G29.
    pub dumb_only: bool,
    /// Optional in-process HTTP Basic (G36). Unset = unauthenticated (G15).
    pub basic_auth: Option<BasicAuthConfig>,
    /// Optional live listen rebind target (Partial; polled in accept loop).
    pub rebind_desired: Option<ListenRebindSlot>,
    /// Optional rustls server config for in-process TLS terminate (B9).
    pub tls: Option<Arc<ServerConfig>>,
    /// Optional browser pages served beside git HTTP.
    pub pages: Option<PageHandler>,
    /// When true, disable the built-in `/info/lfs` Batch + Basic Transfer server (`--no-lfs`).
    pub disable_lfs: bool,
    /// When true, `git_dir` is a multi-repository root directory and `pages` handles all routes
    /// (Web UI + `/<repo>.git/...` Smart HTTP/LFS) without opening a single repo at `git_dir`.
    pub multi_repo_root: bool,
    /// Optional cumulative HTTP header-read deadline override (falls back to
    /// `ARKS_HTTP_HEADER_TIMEOUT_SECS`, default 10s).
    pub header_timeout: Option<Duration>,
}

impl std::fmt::Debug for ServeHttpOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ServeHttpOptions")
            .field("dumb_only", &self.dumb_only)
            .field("basic_auth", &self.basic_auth.as_ref().map(|_| "Some(..)"))
            .field("rebind_desired", &self.rebind_desired.is_some())
            .field("tls", &self.tls.is_some())
            .field("pages", &self.pages.is_some())
            .field("disable_lfs", &self.disable_lfs)
            .field("multi_repo_root", &self.multi_repo_root)
            .field("header_timeout", &self.header_timeout)
            .finish()
    }
}

/// Bind `addr` and serve `git_dir` over smart HTTP until `stop` is set or accept fails.
pub fn serve_http(
    git_dir: impl AsRef<Path>,
    addr: SocketAddr,
    stop: Arc<AtomicBool>,
) -> Result<(), ServerError> {
    serve_http_with_opts(git_dir, addr, stop, ServeHttpOptions::default())
}

pub fn serve_http_with_opts(
    git_dir: impl AsRef<Path>,
    addr: SocketAddr,
    stop: Arc<AtomicBool>,
    opts: ServeHttpOptions,
) -> Result<(), ServerError> {
    let git_dir = git_dir.as_ref().to_path_buf();
    let _ = crate::web_ui::store::sweep_stale_temps(&git_dir, opts.multi_repo_root);
    let mut listener = TcpListener::bind(addr)?;
    listener.set_nonblocking(true)?;
    let mut current = addr;
    // A successful rebind keeps prior listeners accepting for this bounded
    // overlap. Accepted handlers are independently owned and always drain.
    let mut draining: Vec<(TcpListener, SocketAddr, Instant)> = Vec::new();
    let mut last_accept_err_log: Option<Instant> = None;
    while !stop.load(Ordering::SeqCst) {
        if let Some(slot) = &opts.rebind_desired {
            if let Ok(mut g) = slot.lock() {
                if let Some(new_addr) = g.take() {
                    if new_addr != current {
                        match TcpListener::bind(new_addr) {
                            Ok(l) => {
                                if let Err(e) = l.set_nonblocking(true) {
                                    eprintln!(
                                        "arks serve-http: live rebind Partial bind ok but \
                                         nonblocking fail ({e}); keeping {current}"
                                    );
                                    *g = Some(new_addr);
                                } else {
                                    eprintln!(
                                        "arks serve-http: live rebind dual-bind {current} → {new_addr}; \
                                         prior listener draining for 5s"
                                    );
                                    let old = std::mem::replace(&mut listener, l);
                                    draining.push((
                                        old,
                                        current,
                                        Instant::now() + Duration::from_secs(5),
                                    ));
                                    current = new_addr;
                                }
                            }
                            Err(e) => {
                                eprintln!(
                                    "arks serve-http: live rebind Partial fail {current} → \
                                     {new_addr} ({e}); keeping prior listen"
                                );
                            }
                        }
                    }
                }
            }
        }
        draining.retain(|(_, old_addr, deadline)| {
            if Instant::now() < *deadline {
                true
            } else {
                eprintln!("arks serve-http: rebind drain complete; closing {old_addr}");
                false
            }
        });
        match listener.accept() {
            Ok((stream, _)) => {
                dispatch_accepted_stream(stream, &git_dir, &opts);
            }
            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                thread::sleep(std::time::Duration::from_millis(1));
            }
            Err(e) if is_transient_accept_error(&e) => {
                if last_accept_err_log
                    .map(|t| t.elapsed() >= Duration::from_secs(1))
                    .unwrap_or(true)
                {
                    eprintln!(
                        "arks serve-http: transient accept error on {current} ({e}); backing off"
                    );
                    last_accept_err_log = Some(Instant::now());
                }
                thread::sleep(std::time::Duration::from_millis(25));
            }
            Err(e) => return Err(e.into()),
        }
        for (old_listener, _, _) in &draining {
            match old_listener.accept() {
                Ok((stream, _)) => {
                    dispatch_accepted_stream(stream, &git_dir, &opts);
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
                Err(e) => {
                    if last_accept_err_log
                        .map(|t| t.elapsed() >= Duration::from_secs(1))
                        .unwrap_or(true)
                    {
                        eprintln!("arks serve-http: draining listener accept error: {e}");
                        last_accept_err_log = Some(Instant::now());
                    }
                }
            }
        }
    }
    // Graceful shutdown: wait for in-flight HTTP/Git requests to finish (up to 10s).
    let drain_secs = std::env::var("ARKS_SHUTDOWN_DRAIN_SECS")
        .ok()
        .and_then(|v| v.trim().parse::<u64>().ok())
        .unwrap_or(10);
    let drain_deadline = Instant::now() + Duration::from_secs(drain_secs);
    while active_http_connections() > 0 && Instant::now() < drain_deadline {
        thread::sleep(Duration::from_millis(25));
    }
    Ok(())
}

/// Bind an ephemeral port; return (bound addr, join handle, stop flag).
pub fn spawn_loopback(git_dir: PathBuf) -> Result<LoopbackHttp, ServerError> {
    spawn_loopback_with_opts(git_dir, ServeHttpOptions::default())
}

pub fn spawn_loopback_with_opts(
    git_dir: PathBuf,
    opts: ServeHttpOptions,
) -> Result<LoopbackHttp, ServerError> {
    let _ = crate::web_ui::store::sweep_stale_temps(&git_dir, opts.multi_repo_root);
    let listener = TcpListener::bind("127.0.0.1:0")?;
    let addr = listener.local_addr()?;
    listener.set_nonblocking(true)?;
    let stop = Arc::new(AtomicBool::new(false));
    let stop2 = stop.clone();
    let handle = thread::spawn(move || {
        let mut last_accept_err_log: Option<Instant> = None;
        while !stop2.load(Ordering::SeqCst) {
            match listener.accept() {
                Ok((stream, _)) => {
                    dispatch_accepted_stream(stream, &git_dir, &opts);
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    thread::sleep(std::time::Duration::from_millis(1));
                }
                Err(e) if is_transient_accept_error(&e) => {
                    if last_accept_err_log
                        .map(|t| t.elapsed() >= Duration::from_secs(1))
                        .unwrap_or(true)
                    {
                        eprintln!(
                            "arks serve-http: transient loopback accept error ({e}); backing off"
                        );
                        last_accept_err_log = Some(Instant::now());
                    }
                    thread::sleep(std::time::Duration::from_millis(25));
                }
                Err(e) => return Err(e.into()),
            }
        }
        Ok(())
    });
    Ok((addr, stop, handle))
}

fn send_fast_503(stream: &mut TcpStream) {
    let _ = stream.set_nonblocking(false);
    let _ = stream.set_write_timeout(Some(Duration::from_secs(2)));
    let resp = HttpResponse {
        status: 503,
        content_type: "text/plain; charset=utf-8".into(),
        body: b"Service Unavailable: max concurrent connections reached\n".to_vec(),
        www_authenticate: None,
        extra_headers: vec![("Retry-After".into(), "1".into())],
    };
    let _ = write_http_response(stream, &resp);
    let _ = stream.shutdown(std::net::Shutdown::Write);
}

fn send_fast_408<S: HttpStream>(stream: &mut S) {
    let resp = HttpResponse {
        status: 408,
        content_type: "text/plain; charset=utf-8".into(),
        body: b"Request Timeout: HTTP header deadline exceeded\n".to_vec(),
        www_authenticate: None,
        extra_headers: Vec::new(),
    };
    let _ = write_http_response(stream, &resp);
    stream.shutdown_write();
}

/// Atomically reserve a concurrency slot and dispatch a worker thread (fail-closed on saturation
/// or OS thread exhaustion — never panics and never spawns above `ARKS_HTTP_MAX_CONCURRENCY`).
fn dispatch_accepted_stream(mut stream: TcpStream, git_dir: &Path, opts: &ServeHttpOptions) {
    let Some(guard) = try_reserve_http_slot() else {
        send_fast_503(&mut stream);
        return;
    };
    let dir = git_dir.to_path_buf();
    let opts = opts.clone();
    if let Err(e) = thread::Builder::new()
        .name("arks-http-worker".into())
        .spawn(move || {
            let _ = handle_connection(stream, &dir, &opts, guard);
        })
    {
        // Dropping the closure automatically drops `guard` (freeing the slot) and `stream`.
        eprintln!("arks serve-http: worker thread spawn failed ({e}); rejecting connection");
        thread::sleep(Duration::from_millis(10));
    }
}

/// Scheme label for listen banners (`http` or `https`).
pub fn serve_http_scheme(opts: &ServeHttpOptions) -> &'static str {
    if opts.tls.is_some() { "https" } else { "http" }
}

const MAX_KEEP_ALIVE_REQUESTS: usize = 64;
const KEEP_ALIVE_IDLE_SECS: u64 = 5;

trait HttpStream: Read + Write {
    fn set_stream_read_timeout(&mut self, timeout: Duration);
    fn shutdown_write(&mut self);
}

impl HttpStream for TcpStream {
    fn set_stream_read_timeout(&mut self, timeout: Duration) {
        let _ = self.set_read_timeout(Some(timeout));
    }
    fn shutdown_write(&mut self) {
        let _ = self.shutdown(std::net::Shutdown::Write);
    }
}

impl HttpStream for rustls::StreamOwned<rustls::ServerConnection, TcpStream> {
    fn set_stream_read_timeout(&mut self, timeout: Duration) {
        let _ = self.sock.set_read_timeout(Some(timeout));
    }
    fn shutdown_write(&mut self) {
        let _ = self.sock.shutdown(std::net::Shutdown::Write);
    }
}

fn handle_connection(
    mut stream: TcpStream,
    git_dir: &Path,
    opts: &ServeHttpOptions,
    _guard: ActiveConnGuard,
) -> Result<(), ServerError> {
    let _ = SERVER_START.get_or_init(Instant::now);
    // Listener is nonblocking; accepted sockets may inherit that on Windows.
    stream.set_nonblocking(false)?;
    let _ = stream.set_nodelay(true);
    stream.set_read_timeout(Some(std::time::Duration::from_secs(30)))?;
    stream.set_write_timeout(Some(std::time::Duration::from_secs(30)))?;
    if let Some(tls_cfg) = &opts.tls {
        let conn = rustls::ServerConnection::new(tls_cfg.clone())
            .map_err(|e| ServerError::Msg(format!("tls ServerConnection: {e}")))?;
        let mut tls = rustls::StreamOwned::new(conn, stream);
        // Complete handshake before HTTP parse.
        tls.conn
            .complete_io(&mut tls.sock)
            .map_err(|e| ServerError::Msg(format!("tls handshake: {e}")))?;
        handle_connection_io(&mut tls, git_dir, opts)
    } else {
        handle_connection_io(&mut stream, git_dir, opts)
    }
}

fn handle_connection_io<S: HttpStream>(
    stream: &mut S,
    git_dir: &Path,
    opts: &ServeHttpOptions,
) -> Result<(), ServerError> {
    let mut buf = Vec::with_capacity(4096);
    let mut tmp = [0u8; 8192];
    let header_timeout = opts.header_timeout.unwrap_or_else(max_http_header_timeout);
    for req_idx in 0..MAX_KEEP_ALIVE_REQUESTS {
        let mut header_deadline = if req_idx == 0 {
            Some(Instant::now() + header_timeout)
        } else {
            stream.set_stream_read_timeout(Duration::from_secs(KEEP_ALIVE_IDLE_SECS));
            None
        };
        let mut header_end = buf.windows(4).position(|w| w == b"\r\n\r\n");
        // Read headers in O(N) by scanning only newly arrived bytes (plus 3-byte overlap),
        // bounded by a cumulative header deadline to defeat Slowloris dribbles.
        while header_end.is_none() {
            if let Some(dl) = header_deadline {
                let now = Instant::now();
                if now >= dl {
                    send_fast_408(stream);
                    return Ok(());
                }
                let rem = dl
                    .saturating_duration_since(now)
                    .max(Duration::from_millis(1));
                stream.set_stream_read_timeout(rem);
            }
            let prev_len = buf.len();
            match stream.read(&mut tmp) {
                Ok(0) => {
                    if req_idx > 0 && buf.is_empty() {
                        return Ok(());
                    }
                    break;
                }
                Ok(n) => {
                    if header_deadline.is_none() {
                        header_deadline = Some(Instant::now() + header_timeout);
                    }
                    buf.extend_from_slice(&tmp[..n]);
                    let search_from = prev_len.saturating_sub(3);
                    if let Some(rel) = buf[search_from..].windows(4).position(|w| w == b"\r\n\r\n")
                    {
                        header_end = Some(search_from + rel);
                        break;
                    }
                    if buf.len() > 1024 * 1024 {
                        return Err(ServerError::Protocol("headers too large".into()));
                    }
                    if header_deadline.is_some_and(|dl| Instant::now() >= dl) {
                        send_fast_408(stream);
                        return Ok(());
                    }
                }
                Err(e)
                    if req_idx > 0
                        && buf.is_empty()
                        && matches!(
                            e.kind(),
                            std::io::ErrorKind::WouldBlock
                                | std::io::ErrorKind::TimedOut
                                | std::io::ErrorKind::ConnectionReset
                                | std::io::ErrorKind::UnexpectedEof
                        ) =>
                {
                    return Ok(());
                }
                Err(e)
                    if header_deadline.is_some()
                        && matches!(
                            e.kind(),
                            std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
                        ) =>
                {
                    send_fast_408(stream);
                    return Ok(());
                }
                Err(e) => return Err(e.into()),
            }
        }
        let Some(header_end) = header_end else {
            if req_idx > 0 && buf.is_empty() {
                return Ok(());
            }
            return Err(ServerError::Protocol("incomplete headers".into()));
        };
        // Restore full body-streaming read timeout once HTTP headers are complete.
        stream.set_stream_read_timeout(Duration::from_secs(30));
        HTTP_REQUESTS_TOTAL.fetch_add(1, Ordering::Relaxed);
        let header_bytes = &buf[..header_end];
        let header_text = std::str::from_utf8(header_bytes)
            .map_err(|_| ServerError::Protocol("headers not utf-8".into()))?;
        let mut lines = header_text.split("\r\n");
        let request_line = lines
            .next()
            .ok_or_else(|| ServerError::Protocol("missing request line".into()))?;
        let mut parts = request_line.split_whitespace();
        let method = parts
            .next()
            .ok_or_else(|| ServerError::Protocol("bad request line".into()))?
            .to_string();
        let target = parts
            .next()
            .ok_or_else(|| ServerError::Protocol("bad request line".into()))?;
        let http_version = parts.next().unwrap_or("HTTP/1.1");
        let (path, query) = match target.split_once('?') {
            Some((p, q)) => (p.to_string(), q.to_string()),
            None => (target.to_string(), String::new()),
        };
        let mut content_length = 0usize;
        let mut expect_continue = false;
        let mut content_encoding = String::new();
        let mut connection_close = false;
        let mut connection_keep_alive = false;
        let mut git_protocol = None;
        let mut authorization = None;
        let mut destination = None;
        let mut lock_token = None;
        let mut host = None;
        let mut cookie = None;
        let mut origin = None;
        let mut forwarded_proto = None;
        for line in lines {
            let lower = line.to_ascii_lowercase();
            if let Some(v) = lower.strip_prefix("content-length:") {
                content_length = v.trim().parse().unwrap_or(0);
            }
            if let Some(v) = lower.strip_prefix("connection:") {
                if v.contains("close") {
                    connection_close = true;
                }
                if v.contains("keep-alive") {
                    connection_keep_alive = true;
                }
            }
            if lower.starts_with("host:") {
                if let Some((_, v)) = line.split_once(':') {
                    host = Some(v.trim().to_string());
                }
            }
            if lower.starts_with("cookie:") {
                if let Some((_, v)) = line.split_once(':') {
                    cookie = Some(v.trim().to_string());
                }
            }
            if lower.starts_with("origin:") {
                if let Some((_, v)) = line.split_once(':') {
                    origin = Some(v.trim().to_string());
                }
            }
            if lower.starts_with("x-forwarded-proto:") {
                if let Some((_, v)) = line.split_once(':') {
                    forwarded_proto = Some(v.trim().to_string());
                }
            }
            if lower.starts_with("expect:") && lower.contains("100-continue") {
                // git/curl POST often waits for 100 before sending the pack body
                // (gitprotocol-http / HTTP/1.1). Without this, clients see empty replies.
                expect_continue = true;
            }
            if let Some(v) = lower.strip_prefix("content-encoding:") {
                content_encoding = v.trim().to_string();
            }
            // gitprotocol-v2: clients send `Git-Protocol: version=2`.
            if lower.starts_with("git-protocol:") {
                if let Some((_, v)) = line.split_once(':') {
                    git_protocol = Some(v.trim().to_string());
                }
            }
            if lower.starts_with("authorization:") {
                if let Some((_, v)) = line.split_once(':') {
                    authorization = Some(v.trim().to_string());
                }
            }
            // WebDAV (RFC 4918) — dumb HTTP push (git-http-push).
            if lower.starts_with("destination:") {
                if let Some((_, v)) = line.split_once(':') {
                    destination = Some(v.trim().to_string());
                }
            }
            if lower.starts_with("lock-token:") {
                if let Some((_, v)) = line.split_once(':') {
                    lock_token = Some(v.trim().to_string());
                }
            }
            if lower.starts_with("if:") && lock_token.is_none() {
                // git-http-push sends `If: (<opaquelocktoken:…>)` with the lock.
                if let Some((_, v)) = line.split_once(':') {
                    let v = v.trim();
                    if let Some(start) = v.find("opaquelocktoken:") {
                        let rest = &v[start..];
                        let end = rest
                            .find(|c: char| c == ')' || c == '>' || c.is_whitespace())
                            .unwrap_or(rest.len());
                        lock_token = Some(rest[..end].to_string());
                    }
                }
            }
        }
        let want_keep_alive = if http_version.eq_ignore_ascii_case("HTTP/1.0") {
            connection_keep_alive && !connection_close
        } else {
            !connection_close
        };
        let keep_alive_rem = if want_keep_alive && req_idx + 1 < MAX_KEEP_ALIVE_REQUESTS {
            Some(MAX_KEEP_ALIVE_REQUESTS - req_idx - 1)
        } else {
            None
        };
        let body_start = header_end + 4;
        if path == "/healthz" || path == "/readyz" {
            let body = b"{\"status\":\"ok\"}\n";
            let resp = HttpResponse {
                status: 200,
                content_type: "application/json; charset=utf-8".into(),
                body: body.to_vec(),
                www_authenticate: None,
                extra_headers: vec![("Cache-Control".into(), "no-store".into())],
            };
            buf.drain(..body_start.min(buf.len()));
            write_http_response_with_options(stream, &resp, opts.tls.is_some(), keep_alive_rem)?;
            if keep_alive_rem.is_some() {
                continue;
            }
            return Ok(());
        }
        if path == "/metrics" {
            let total = HTTP_REQUESTS_TOTAL.load(Ordering::Relaxed);
            let active = HTTP_ACTIVE_CONNECTIONS.load(Ordering::Relaxed);
            let uptime = SERVER_START.get_or_init(Instant::now).elapsed().as_secs();
            let metrics = format!(
                "# HELP arks_http_requests_total Total HTTP requests handled by arks serve.\n\
                 # TYPE arks_http_requests_total counter\n\
                 arks_http_requests_total {total}\n\
                 # HELP arks_http_active_connections Currently active HTTP worker connections.\n\
                 # TYPE arks_http_active_connections gauge\n\
                 arks_http_active_connections {active}\n\
                 # HELP arks_uptime_seconds Server process uptime in seconds.\n\
                 # TYPE arks_uptime_seconds gauge\n\
                 arks_uptime_seconds {uptime}\n"
            );
            let resp = HttpResponse {
                status: 200,
                content_type: "text/plain; version=0.0.4; charset=utf-8".into(),
                body: metrics.into_bytes(),
                www_authenticate: None,
                extra_headers: vec![("Cache-Control".into(), "no-store".into())],
            };
            buf.drain(..body_start.min(buf.len()));
            write_http_response_with_options(stream, &resp, opts.tls.is_some(), keep_alive_rem)?;
            if keep_alive_rem.is_some() {
                continue;
            }
            return Ok(());
        }
        let max_body = max_http_body_bytes();
        if content_length > max_body {
            let resp = HttpResponse {
                status: 413,
                content_type: "text/plain; charset=utf-8".into(),
                body: format!("Payload Too Large (max {max_body} bytes)\n").into_bytes(),
                www_authenticate: None,
                extra_headers: Vec::new(),
            };
            return write_http_response(stream, &resp);
        }
        if expect_continue && content_length > 0 {
            stream.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?;
            stream.flush()?;
        }
        let total_needed = body_start.saturating_add(content_length);
        while buf.len() < total_needed {
            let n = stream.read(&mut tmp)?;
            if n == 0 {
                break;
            }
            buf.extend_from_slice(&tmp[..n]);
        }
        let avail_end = total_needed.min(buf.len());
        let mut body = buf[body_start..avail_end].to_vec();
        buf.drain(..avail_end);
        // Stock git/curl may gzip the upload-pack / receive-pack POST once the prior
        // advertisement is large (observed ~32+ refs). Accept Content-Encoding: gzip
        // and gzip magic even if the header is omitted — except for raw binary LFS PUTs!
        let is_lfs = crate::lfs::is_lfs_path(&path);
        let gzip_magic = !is_lfs && body.len() >= 2 && body[0] == 0x1f && body[1] == 0x8b;
        if content_encoding.contains("gzip") || gzip_magic {
            use flate2::read::GzDecoder;
            use std::io::Read as _;
            let decoder = GzDecoder::new(body.as_slice());
            let mut decoded = Vec::new();
            decoder
                .take((max_body as u64).saturating_add(1))
                .read_to_end(&mut decoded)
                .map_err(|e| ServerError::Protocol(format!("gzip body: {e}")))?;
            if decoded.len() > max_body {
                let resp = HttpResponse {
                    status: 413,
                    content_type: "text/plain; charset=utf-8".into(),
                    body: format!(
                        "Payload Too Large (decompressed exceeds max {max_body} bytes)\n"
                    )
                    .into_bytes(),
                    www_authenticate: None,
                    extra_headers: Vec::new(),
                };
                return write_http_response(stream, &resp);
            }
            body = decoded;
        }

        let mut req = HttpRequest {
            method,
            path: path.clone(),
            query: query.clone(),
            body,
            git_protocol,
            authorization,
            destination,
            lock_token,
            host,
            cookie,
            origin,
            forwarded_proto: forwarded_proto.or_else(|| {
                if opts.tls.is_some() {
                    Some("https".into())
                } else {
                    None
                }
            }),
        };
        let resp = if opts.multi_repo_root {
            match opts.pages.as_ref().and_then(|p| p(&req)) {
                Some(r) => r,
                None => HttpResponse {
                    status: 404,
                    content_type: "text/plain; charset=utf-8".into(),
                    body: b"repository or path not found\n".to_vec(),
                    www_authenticate: None,
                    extra_headers: Vec::new(),
                },
            }
        } else {
            let mut repo =
                Repository::open(git_dir).map_err(|e| ServerError::Msg(e.to_string()))?;
            // dumb_only: strip service= so discovery uses dumb info/refs (smart clients fall back).
            if opts.dumb_only
                && (req.path.ends_with("info/refs") || req.path.ends_with("/info/refs"))
            {
                req.query = String::new();
            }
            let is_git_rpc = req.path.contains("/git-upload-pack")
                || req.path.contains("/git-receive-pack")
                || req.path.contains("/info/refs");
            let page = match &opts.pages {
                Some(pages)
                    if matches!(req.method.as_str(), "GET" | "POST" | "PATCH" | "DELETE")
                        && !is_lfs
                        && !is_git_rpc =>
                {
                    pages(&req)
                }
                _ => None,
            };
            let scheme = serve_http_scheme(opts);
            let is_git_write = req.path.contains("/git-receive-pack")
                || (req.path.contains("/info/refs") && req.query.contains("git-receive-pack"))
                || (req.path.contains("/info/lfs/") && req.method == "PUT");
            let auth_denied = if page.is_none() && opts.basic_auth.is_none() {
                crate::web_ui::check_git_http_auth(git_dir, &req, is_git_write).err()
            } else {
                None
            };
            match page.or(auth_denied).map(Ok).unwrap_or_else(|| {
                handle_smart_http_auth_opts(
                    &mut repo,
                    &req,
                    opts.basic_auth.as_ref(),
                    !opts.disable_lfs,
                    scheme,
                )
            }) {
                Ok(r) => r,
                Err(e) => {
                    // Fail closed with an HTTP error body (never silent empty close).
                    let msg = e.to_string();
                    let hex: String = req
                        .body
                        .iter()
                        .take(32)
                        .map(|b| format!("{b:02x}"))
                        .collect::<Vec<_>>()
                        .join(" ");
                    eprintln!(
                        "arks serve-http error path={path} query={query} body_len={} hex32=[{hex}] : {msg}",
                        req.body.len()
                    );
                    HttpResponse {
                        status: 500,
                        content_type: "text/plain".into(),
                        body: msg.into_bytes(),
                        www_authenticate: None,
                        extra_headers: Vec::new(),
                    }
                }
            }
        };
        let keep_alive = if matches!(resp.status, 408 | 413 | 503) {
            None
        } else {
            keep_alive_rem
        };
        write_http_response_with_options(stream, &resp, req.is_https(), keep_alive)?;
        if keep_alive.is_none() {
            return Ok(());
        }
    }
    Ok(())
}

fn write_http_response<S: Write>(stream: &mut S, resp: &HttpResponse) -> Result<(), ServerError> {
    write_http_response_with_options(stream, resp, false, None)
}

fn write_http_response_with_options<S: Write>(
    stream: &mut S,
    resp: &HttpResponse,
    is_https: bool,
    keep_alive_remaining: Option<usize>,
) -> Result<(), ServerError> {
    let status_text = match resp.status {
        200 => "OK",
        201 => "Created",
        204 => "No Content",
        207 => "Multi-Status",
        302 => "Found",
        303 => "See Other",
        400 => "Bad Request",
        401 => "Unauthorized",
        403 => "Forbidden",
        404 => "Not Found",
        405 => "Method Not Allowed",
        408 => "Request Timeout",
        409 => "Conflict",
        413 => "Payload Too Large",
        422 => "Unprocessable Entity",
        423 => "Locked",
        429 => "Too Many Requests",
        500 => "Internal Server Error",
        501 => "Not Implemented",
        503 => "Service Unavailable",
        _ => "Error",
    };
    let conn_header = match keep_alive_remaining {
        Some(rem) => format!(
            "Connection: keep-alive\r\nKeep-Alive: timeout={KEEP_ALIVE_IDLE_SECS}, max={rem}\r\n"
        ),
        None => "Connection: close\r\n".to_string(),
    };
    let mut header = format!(
        "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\n{}",
        resp.status,
        status_text,
        resp.content_type,
        resp.body.len(),
        conn_header
    );
    if let Some(ref wa) = resp.www_authenticate {
        header.push_str(&format!("WWW-Authenticate: {wa}\r\n"));
    }
    let mut has_xfo = false;
    let mut has_rp = false;
    let mut has_hsts = false;
    for (k, v) in &resp.extra_headers {
        if k.eq_ignore_ascii_case("x-frame-options") {
            has_xfo = true;
        } else if k.eq_ignore_ascii_case("referrer-policy") {
            has_rp = true;
        } else if k.eq_ignore_ascii_case("strict-transport-security") {
            has_hsts = true;
        }
        header.push_str(&format!("{k}: {v}\r\n"));
    }
    if resp.content_type.starts_with("text/html") {
        if !has_xfo {
            header.push_str("X-Frame-Options: DENY\r\n");
        }
        if !has_rp {
            header.push_str("Referrer-Policy: same-origin\r\n");
        }
    }
    if is_https && !has_hsts {
        header.push_str("Strict-Transport-Security: max-age=31536000; includeSubDomains\r\n");
    }
    header.push_str("\r\n");
    if resp.body.len() <= 64 * 1024 {
        let mut combined = Vec::with_capacity(header.len() + resp.body.len());
        combined.extend_from_slice(header.as_bytes());
        combined.extend_from_slice(&resp.body);
        stream.write_all(&combined)?;
    } else {
        stream.write_all(header.as_bytes())?;
        stream.write_all(&resp.body)?;
    }
    stream.flush()?;
    Ok(())
}