1use 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
40struct ActiveConnGuard;
41impl Drop for ActiveConnGuard {
42 fn drop(&mut self) {
43 HTTP_ACTIVE_CONNECTIONS.fetch_sub(1, Ordering::Relaxed);
44 }
45}
46
47#[allow(dead_code)]
49pub fn active_http_connections() -> usize {
50 HTTP_ACTIVE_CONNECTIONS.load(Ordering::Relaxed)
51}
52
53type LoopbackHttp = (
54 SocketAddr,
55 Arc<AtomicBool>,
56 thread::JoinHandle<Result<(), ServerError>>,
57);
58
59pub type ListenRebindSlot = Arc<Mutex<Option<SocketAddr>>>;
63
64pub type PageHandler = Arc<dyn Fn(&HttpRequest) -> Option<HttpResponse> + Send + Sync>;
68
69#[derive(Clone, Default)]
70pub struct ServeHttpOptions {
71 pub dumb_only: bool,
74 pub basic_auth: Option<BasicAuthConfig>,
76 pub rebind_desired: Option<ListenRebindSlot>,
78 pub tls: Option<Arc<ServerConfig>>,
80 pub pages: Option<PageHandler>,
82 pub disable_lfs: bool,
84 pub multi_repo_root: bool,
87}
88
89impl std::fmt::Debug for ServeHttpOptions {
90 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 f.debug_struct("ServeHttpOptions")
92 .field("dumb_only", &self.dumb_only)
93 .field("basic_auth", &self.basic_auth.as_ref().map(|_| "Some(..)"))
94 .field("rebind_desired", &self.rebind_desired.is_some())
95 .field("tls", &self.tls.is_some())
96 .field("pages", &self.pages.is_some())
97 .field("disable_lfs", &self.disable_lfs)
98 .field("multi_repo_root", &self.multi_repo_root)
99 .finish()
100 }
101}
102
103pub fn serve_http(
105 git_dir: impl AsRef<Path>,
106 addr: SocketAddr,
107 stop: Arc<AtomicBool>,
108) -> Result<(), ServerError> {
109 serve_http_with_opts(git_dir, addr, stop, ServeHttpOptions::default())
110}
111
112pub fn serve_http_with_opts(
113 git_dir: impl AsRef<Path>,
114 addr: SocketAddr,
115 stop: Arc<AtomicBool>,
116 opts: ServeHttpOptions,
117) -> Result<(), ServerError> {
118 let git_dir = git_dir.as_ref().to_path_buf();
119 let mut listener = TcpListener::bind(addr)?;
120 listener.set_nonblocking(true)?;
121 let mut current = addr;
122 let mut draining: Vec<(TcpListener, SocketAddr, Instant)> = Vec::new();
125 while !stop.load(Ordering::SeqCst) {
126 if let Some(slot) = &opts.rebind_desired {
127 if let Ok(mut g) = slot.lock() {
128 if let Some(new_addr) = g.take() {
129 if new_addr != current {
130 match TcpListener::bind(new_addr) {
131 Ok(l) => {
132 if let Err(e) = l.set_nonblocking(true) {
133 eprintln!(
134 "arks serve-http: live rebind Partial bind ok but \
135 nonblocking fail ({e}); keeping {current}"
136 );
137 *g = Some(new_addr);
138 } else {
139 eprintln!(
140 "arks serve-http: live rebind dual-bind {current} → {new_addr}; \
141 prior listener draining for 5s"
142 );
143 let old = std::mem::replace(&mut listener, l);
144 draining.push((
145 old,
146 current,
147 Instant::now() + Duration::from_secs(5),
148 ));
149 current = new_addr;
150 }
151 }
152 Err(e) => {
153 eprintln!(
154 "arks serve-http: live rebind Partial fail {current} → \
155 {new_addr} ({e}); keeping prior listen"
156 );
157 }
158 }
159 }
160 }
161 }
162 }
163 draining.retain(|(_, old_addr, deadline)| {
164 if Instant::now() < *deadline {
165 true
166 } else {
167 eprintln!("arks serve-http: rebind drain complete; closing {old_addr}");
168 false
169 }
170 });
171 match listener.accept() {
172 Ok((stream, _)) => {
173 let dir = git_dir.clone();
174 let opts = opts.clone();
175 thread::spawn(move || {
176 let _ = handle_connection(stream, &dir, &opts);
177 });
178 }
179 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
180 thread::sleep(std::time::Duration::from_millis(1));
181 }
182 Err(e) => return Err(e.into()),
183 }
184 for (old_listener, _, _) in &draining {
185 match old_listener.accept() {
186 Ok((stream, _)) => {
187 let dir = git_dir.clone();
188 let opts = opts.clone();
189 thread::spawn(move || {
190 let _ = handle_connection(stream, &dir, &opts);
191 });
192 }
193 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
194 Err(e) => eprintln!("arks serve-http: draining listener accept error: {e}"),
195 }
196 }
197 }
198 let drain_secs = std::env::var("ARKS_SHUTDOWN_DRAIN_SECS")
200 .ok()
201 .and_then(|v| v.trim().parse::<u64>().ok())
202 .unwrap_or(10);
203 let drain_deadline = Instant::now() + Duration::from_secs(drain_secs);
204 while active_http_connections() > 0 && Instant::now() < drain_deadline {
205 thread::sleep(Duration::from_millis(25));
206 }
207 Ok(())
208}
209
210pub fn spawn_loopback(git_dir: PathBuf) -> Result<LoopbackHttp, ServerError> {
212 spawn_loopback_with_opts(git_dir, ServeHttpOptions::default())
213}
214
215pub fn spawn_loopback_with_opts(
216 git_dir: PathBuf,
217 opts: ServeHttpOptions,
218) -> Result<LoopbackHttp, ServerError> {
219 let listener = TcpListener::bind("127.0.0.1:0")?;
220 let addr = listener.local_addr()?;
221 listener.set_nonblocking(true)?;
222 let stop = Arc::new(AtomicBool::new(false));
223 let stop2 = stop.clone();
224 let handle = thread::spawn(move || {
225 while !stop2.load(Ordering::SeqCst) {
226 match listener.accept() {
227 Ok((stream, _)) => {
228 let dir = git_dir.clone();
229 let opts = opts.clone();
230 thread::spawn(move || {
231 let _ = handle_connection(stream, &dir, &opts);
232 });
233 }
234 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
235 thread::sleep(std::time::Duration::from_millis(1));
236 }
237 Err(e) => return Err(e.into()),
238 }
239 }
240 Ok(())
241 });
242 Ok((addr, stop, handle))
243}
244
245pub fn serve_http_scheme(opts: &ServeHttpOptions) -> &'static str {
247 if opts.tls.is_some() { "https" } else { "http" }
248}
249
250fn handle_connection(
251 mut stream: TcpStream,
252 git_dir: &Path,
253 opts: &ServeHttpOptions,
254) -> Result<(), ServerError> {
255 let _ = SERVER_START.get_or_init(Instant::now);
256 HTTP_REQUESTS_TOTAL.fetch_add(1, Ordering::Relaxed);
257 let prev = HTTP_ACTIVE_CONNECTIONS.fetch_add(1, Ordering::Relaxed);
258 let _guard = ActiveConnGuard;
259 if prev >= max_http_concurrency() {
260 let _ = stream.set_nonblocking(false);
261 let resp = HttpResponse {
262 status: 503,
263 content_type: "text/plain; charset=utf-8".into(),
264 body: b"Service Unavailable: max concurrent connections reached\n".to_vec(),
265 www_authenticate: None,
266 extra_headers: vec![("Retry-After".into(), "1".into())],
267 };
268 return write_http_response(&mut stream, &resp);
269 }
270 stream.set_nonblocking(false)?;
272 stream.set_read_timeout(Some(std::time::Duration::from_secs(30)))?;
273 stream.set_write_timeout(Some(std::time::Duration::from_secs(30)))?;
274 if let Some(tls_cfg) = &opts.tls {
275 let conn = rustls::ServerConnection::new(tls_cfg.clone())
276 .map_err(|e| ServerError::Msg(format!("tls ServerConnection: {e}")))?;
277 let mut tls = rustls::StreamOwned::new(conn, stream);
278 tls.conn
280 .complete_io(&mut tls.sock)
281 .map_err(|e| ServerError::Msg(format!("tls handshake: {e}")))?;
282 handle_connection_io(&mut tls, git_dir, opts)
283 } else {
284 handle_connection_io(&mut stream, git_dir, opts)
285 }
286}
287
288fn handle_connection_io<S: Read + Write>(
289 stream: &mut S,
290 git_dir: &Path,
291 opts: &ServeHttpOptions,
292) -> Result<(), ServerError> {
293 let mut buf = Vec::new();
294 let mut tmp = [0u8; 8192];
295 loop {
297 let n = stream.read(&mut tmp)?;
298 if n == 0 {
299 break;
300 }
301 buf.extend_from_slice(&tmp[..n]);
302 if buf.windows(4).any(|w| w == b"\r\n\r\n") {
303 break;
304 }
305 if buf.len() > 1024 * 1024 {
306 return Err(ServerError::Protocol("headers too large".into()));
307 }
308 }
309 let header_end = buf
310 .windows(4)
311 .position(|w| w == b"\r\n\r\n")
312 .ok_or_else(|| ServerError::Protocol("incomplete headers".into()))?;
313 let header_bytes = &buf[..header_end];
314 let header_text = std::str::from_utf8(header_bytes)
315 .map_err(|_| ServerError::Protocol("headers not utf-8".into()))?;
316 let mut lines = header_text.split("\r\n");
317 let request_line = lines
318 .next()
319 .ok_or_else(|| ServerError::Protocol("missing request line".into()))?;
320 let mut parts = request_line.split_whitespace();
321 let method = parts
322 .next()
323 .ok_or_else(|| ServerError::Protocol("bad request line".into()))?
324 .to_string();
325 let target = parts
326 .next()
327 .ok_or_else(|| ServerError::Protocol("bad request line".into()))?;
328 let (path, query) = match target.split_once('?') {
329 Some((p, q)) => (p.to_string(), q.to_string()),
330 None => (target.to_string(), String::new()),
331 };
332 let mut content_length = 0usize;
333 let mut expect_continue = false;
334 let mut content_encoding = String::new();
335 let mut git_protocol = None;
336 let mut authorization = None;
337 let mut destination = None;
338 let mut lock_token = None;
339 let mut host = None;
340 let mut cookie = None;
341 let mut origin = None;
342 let mut forwarded_proto = None;
343 for line in lines {
344 let lower = line.to_ascii_lowercase();
345 if let Some(v) = lower.strip_prefix("content-length:") {
346 content_length = v.trim().parse().unwrap_or(0);
347 }
348 if lower.starts_with("host:") {
349 if let Some((_, v)) = line.split_once(':') {
350 host = Some(v.trim().to_string());
351 }
352 }
353 if lower.starts_with("cookie:") {
354 if let Some((_, v)) = line.split_once(':') {
355 cookie = Some(v.trim().to_string());
356 }
357 }
358 if lower.starts_with("origin:") {
359 if let Some((_, v)) = line.split_once(':') {
360 origin = Some(v.trim().to_string());
361 }
362 }
363 if lower.starts_with("x-forwarded-proto:") {
364 if let Some((_, v)) = line.split_once(':') {
365 forwarded_proto = Some(v.trim().to_string());
366 }
367 }
368 if lower.starts_with("expect:") && lower.contains("100-continue") {
369 expect_continue = true;
372 }
373 if let Some(v) = lower.strip_prefix("content-encoding:") {
374 content_encoding = v.trim().to_string();
375 }
376 if lower.starts_with("git-protocol:") {
378 if let Some((_, v)) = line.split_once(':') {
379 git_protocol = Some(v.trim().to_string());
380 }
381 }
382 if lower.starts_with("authorization:") {
383 if let Some((_, v)) = line.split_once(':') {
384 authorization = Some(v.trim().to_string());
385 }
386 }
387 if lower.starts_with("destination:") {
389 if let Some((_, v)) = line.split_once(':') {
390 destination = Some(v.trim().to_string());
391 }
392 }
393 if lower.starts_with("lock-token:") {
394 if let Some((_, v)) = line.split_once(':') {
395 lock_token = Some(v.trim().to_string());
396 }
397 }
398 if lower.starts_with("if:") && lock_token.is_none() {
399 if let Some((_, v)) = line.split_once(':') {
401 let v = v.trim();
402 if let Some(start) = v.find("opaquelocktoken:") {
403 let rest = &v[start..];
404 let end = rest
405 .find(|c: char| c == ')' || c == '>' || c.is_whitespace())
406 .unwrap_or(rest.len());
407 lock_token = Some(rest[..end].to_string());
408 }
409 }
410 }
411 }
412 if path == "/healthz" || path == "/readyz" {
413 let body = b"{\"status\":\"ok\"}\n";
414 let resp = HttpResponse {
415 status: 200,
416 content_type: "application/json; charset=utf-8".into(),
417 body: body.to_vec(),
418 www_authenticate: None,
419 extra_headers: vec![("Cache-Control".into(), "no-store".into())],
420 };
421 return write_http_response(stream, &resp);
422 }
423 if path == "/metrics" {
424 let total = HTTP_REQUESTS_TOTAL.load(Ordering::Relaxed);
425 let active = HTTP_ACTIVE_CONNECTIONS.load(Ordering::Relaxed);
426 let uptime = SERVER_START.get_or_init(Instant::now).elapsed().as_secs();
427 let metrics = format!(
428 "# HELP arks_http_requests_total Total HTTP requests handled by arks serve.\n\
429 # TYPE arks_http_requests_total counter\n\
430 arks_http_requests_total {total}\n\
431 # HELP arks_http_active_connections Currently active HTTP worker connections.\n\
432 # TYPE arks_http_active_connections gauge\n\
433 arks_http_active_connections {active}\n\
434 # HELP arks_uptime_seconds Server process uptime in seconds.\n\
435 # TYPE arks_uptime_seconds gauge\n\
436 arks_uptime_seconds {uptime}\n"
437 );
438 let resp = HttpResponse {
439 status: 200,
440 content_type: "text/plain; version=0.0.4; charset=utf-8".into(),
441 body: metrics.into_bytes(),
442 www_authenticate: None,
443 extra_headers: vec![("Cache-Control".into(), "no-store".into())],
444 };
445 return write_http_response(stream, &resp);
446 }
447 let max_body = max_http_body_bytes();
448 if content_length > max_body {
449 let resp = HttpResponse {
450 status: 413,
451 content_type: "text/plain; charset=utf-8".into(),
452 body: format!("Payload Too Large (max {max_body} bytes)\n").into_bytes(),
453 www_authenticate: None,
454 extra_headers: Vec::new(),
455 };
456 return write_http_response(stream, &resp);
457 }
458 if expect_continue && content_length > 0 {
459 stream.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?;
460 stream.flush()?;
461 }
462 let mut body = buf[header_end + 4..].to_vec();
463 while body.len() < content_length {
464 let n = stream.read(&mut tmp)?;
465 if n == 0 {
466 break;
467 }
468 body.extend_from_slice(&tmp[..n]);
469 }
470 body.truncate(content_length);
471 let is_lfs = crate::lfs::is_lfs_path(&path);
475 let gzip_magic = !is_lfs && body.len() >= 2 && body[0] == 0x1f && body[1] == 0x8b;
476 if content_encoding.contains("gzip") || gzip_magic {
477 use flate2::read::GzDecoder;
478 use std::io::Read as _;
479 let mut decoder = GzDecoder::new(body.as_slice());
480 let mut decoded = Vec::new();
481 decoder
482 .read_to_end(&mut decoded)
483 .map_err(|e| ServerError::Protocol(format!("gzip body: {e}")))?;
484 body = decoded;
485 }
486
487 let mut req = HttpRequest {
488 method,
489 path: path.clone(),
490 query: query.clone(),
491 body,
492 git_protocol,
493 authorization,
494 destination,
495 lock_token,
496 host,
497 cookie,
498 origin,
499 forwarded_proto: forwarded_proto.or_else(|| {
500 if opts.tls.is_some() {
501 Some("https".into())
502 } else {
503 None
504 }
505 }),
506 };
507 let resp = if opts.multi_repo_root {
508 match opts.pages.as_ref().and_then(|p| p(&req)) {
509 Some(r) => r,
510 None => HttpResponse {
511 status: 404,
512 content_type: "text/plain; charset=utf-8".into(),
513 body: b"repository or path not found\n".to_vec(),
514 www_authenticate: None,
515 extra_headers: Vec::new(),
516 },
517 }
518 } else {
519 let mut repo = Repository::open(git_dir).map_err(|e| ServerError::Msg(e.to_string()))?;
520 if opts.dumb_only && (req.path.ends_with("info/refs") || req.path.ends_with("/info/refs")) {
522 req.query = String::new();
523 }
524 let is_git_rpc = req.path.contains("/git-upload-pack")
525 || req.path.contains("/git-receive-pack")
526 || req.path.contains("/info/refs");
527 let page = match &opts.pages {
528 Some(pages)
529 if matches!(req.method.as_str(), "GET" | "POST" | "PATCH" | "DELETE")
530 && !is_lfs
531 && !is_git_rpc =>
532 {
533 pages(&req)
534 }
535 _ => None,
536 };
537 let scheme = serve_http_scheme(opts);
538 let is_git_write = req.path.contains("/git-receive-pack")
539 || (req.path.contains("/info/refs") && req.query.contains("git-receive-pack"))
540 || (req.path.contains("/info/lfs/") && req.method == "PUT");
541 let auth_denied = if page.is_none() && opts.basic_auth.is_none() {
542 crate::web_ui::check_git_http_auth(git_dir, &req, is_git_write).err()
543 } else {
544 None
545 };
546 match page.or(auth_denied).map(Ok).unwrap_or_else(|| {
547 handle_smart_http_auth_opts(
548 &mut repo,
549 &req,
550 opts.basic_auth.as_ref(),
551 !opts.disable_lfs,
552 scheme,
553 )
554 }) {
555 Ok(r) => r,
556 Err(e) => {
557 let msg = e.to_string();
559 let hex: String = req
560 .body
561 .iter()
562 .take(32)
563 .map(|b| format!("{b:02x}"))
564 .collect::<Vec<_>>()
565 .join(" ");
566 eprintln!(
567 "arks serve-http error path={path} query={query} body_len={} hex32=[{hex}] : {msg}",
568 req.body.len()
569 );
570 HttpResponse {
571 status: 500,
572 content_type: "text/plain".into(),
573 body: msg.into_bytes(),
574 www_authenticate: None,
575 extra_headers: Vec::new(),
576 }
577 }
578 }
579 };
580 write_http_response_with_scheme(stream, &resp, req.is_https())
581}
582
583fn write_http_response<S: Write>(stream: &mut S, resp: &HttpResponse) -> Result<(), ServerError> {
584 write_http_response_with_scheme(stream, resp, false)
585}
586
587fn write_http_response_with_scheme<S: Write>(
588 stream: &mut S,
589 resp: &HttpResponse,
590 is_https: bool,
591) -> Result<(), ServerError> {
592 let status_text = match resp.status {
593 200 => "OK",
594 201 => "Created",
595 204 => "No Content",
596 207 => "Multi-Status",
597 302 => "Found",
598 303 => "See Other",
599 400 => "Bad Request",
600 401 => "Unauthorized",
601 403 => "Forbidden",
602 404 => "Not Found",
603 405 => "Method Not Allowed",
604 409 => "Conflict",
605 413 => "Payload Too Large",
606 422 => "Unprocessable Entity",
607 423 => "Locked",
608 429 => "Too Many Requests",
609 500 => "Internal Server Error",
610 501 => "Not Implemented",
611 503 => "Service Unavailable",
612 _ => "Error",
613 };
614 let mut header = format!(
615 "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n",
616 resp.status,
617 status_text,
618 resp.content_type,
619 resp.body.len()
620 );
621 if let Some(ref wa) = resp.www_authenticate {
622 header.push_str(&format!("WWW-Authenticate: {wa}\r\n"));
623 }
624 let mut has_xfo = false;
625 let mut has_rp = false;
626 let mut has_hsts = false;
627 for (k, v) in &resp.extra_headers {
628 if k.eq_ignore_ascii_case("x-frame-options") {
629 has_xfo = true;
630 } else if k.eq_ignore_ascii_case("referrer-policy") {
631 has_rp = true;
632 } else if k.eq_ignore_ascii_case("strict-transport-security") {
633 has_hsts = true;
634 }
635 header.push_str(&format!("{k}: {v}\r\n"));
636 }
637 if resp.content_type.starts_with("text/html") {
638 if !has_xfo {
639 header.push_str("X-Frame-Options: DENY\r\n");
640 }
641 if !has_rp {
642 header.push_str("Referrer-Policy: same-origin\r\n");
643 }
644 }
645 if is_https && !has_hsts {
646 header.push_str("Strict-Transport-Security: max-age=31536000; includeSubDomains\r\n");
647 }
648 header.push_str("\r\n");
649 stream.write_all(header.as_bytes())?;
650 stream.write_all(&resp.body)?;
651 stream.flush()?;
652 Ok(())
653}