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)
}
struct ActiveConnGuard;
impl Drop for ActiveConnGuard {
fn drop(&mut self) {
HTTP_ACTIVE_CONNECTIONS.fetch_sub(1, Ordering::Relaxed);
}
}
#[allow(dead_code)]
pub fn active_http_connections() -> usize {
HTTP_ACTIVE_CONNECTIONS.load(Ordering::Relaxed)
}
type LoopbackHttp = (
SocketAddr,
Arc<AtomicBool>,
thread::JoinHandle<Result<(), ServerError>>,
);
pub type ListenRebindSlot = Arc<Mutex<Option<SocketAddr>>>;
pub type PageHandler = Arc<dyn Fn(&HttpRequest) -> Option<HttpResponse> + Send + Sync>;
#[derive(Clone, Default)]
pub struct ServeHttpOptions {
pub dumb_only: bool,
pub basic_auth: Option<BasicAuthConfig>,
pub rebind_desired: Option<ListenRebindSlot>,
pub tls: Option<Arc<ServerConfig>>,
pub pages: Option<PageHandler>,
pub disable_lfs: bool,
pub multi_repo_root: bool,
}
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)
.finish()
}
}
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 mut listener = TcpListener::bind(addr)?;
listener.set_nonblocking(true)?;
let mut current = addr;
let mut draining: Vec<(TcpListener, SocketAddr, Instant)> = Vec::new();
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, _)) => {
let dir = git_dir.clone();
let opts = opts.clone();
thread::spawn(move || {
let _ = handle_connection(stream, &dir, &opts);
});
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(std::time::Duration::from_millis(1));
}
Err(e) => return Err(e.into()),
}
for (old_listener, _, _) in &draining {
match old_listener.accept() {
Ok((stream, _)) => {
let dir = git_dir.clone();
let opts = opts.clone();
thread::spawn(move || {
let _ = handle_connection(stream, &dir, &opts);
});
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
Err(e) => eprintln!("arks serve-http: draining listener accept error: {e}"),
}
}
}
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(())
}
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 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 || {
while !stop2.load(Ordering::SeqCst) {
match listener.accept() {
Ok((stream, _)) => {
let dir = git_dir.clone();
let opts = opts.clone();
thread::spawn(move || {
let _ = handle_connection(stream, &dir, &opts);
});
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(std::time::Duration::from_millis(1));
}
Err(e) => return Err(e.into()),
}
}
Ok(())
});
Ok((addr, stop, handle))
}
pub fn serve_http_scheme(opts: &ServeHttpOptions) -> &'static str {
if opts.tls.is_some() { "https" } else { "http" }
}
fn handle_connection(
mut stream: TcpStream,
git_dir: &Path,
opts: &ServeHttpOptions,
) -> Result<(), ServerError> {
let _ = SERVER_START.get_or_init(Instant::now);
HTTP_REQUESTS_TOTAL.fetch_add(1, Ordering::Relaxed);
let prev = HTTP_ACTIVE_CONNECTIONS.fetch_add(1, Ordering::Relaxed);
let _guard = ActiveConnGuard;
if prev >= max_http_concurrency() {
let _ = stream.set_nonblocking(false);
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())],
};
return write_http_response(&mut stream, &resp);
}
stream.set_nonblocking(false)?;
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);
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: Read + Write>(
stream: &mut S,
git_dir: &Path,
opts: &ServeHttpOptions,
) -> Result<(), ServerError> {
let mut buf = Vec::new();
let mut tmp = [0u8; 8192];
loop {
let n = stream.read(&mut tmp)?;
if n == 0 {
break;
}
buf.extend_from_slice(&tmp[..n]);
if buf.windows(4).any(|w| w == b"\r\n\r\n") {
break;
}
if buf.len() > 1024 * 1024 {
return Err(ServerError::Protocol("headers too large".into()));
}
}
let header_end = buf
.windows(4)
.position(|w| w == b"\r\n\r\n")
.ok_or_else(|| ServerError::Protocol("incomplete headers".into()))?;
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 (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 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 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") {
expect_continue = true;
}
if let Some(v) = lower.strip_prefix("content-encoding:") {
content_encoding = v.trim().to_string();
}
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());
}
}
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() {
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());
}
}
}
}
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())],
};
return write_http_response(stream, &resp);
}
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())],
};
return write_http_response(stream, &resp);
}
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 mut body = buf[header_end + 4..].to_vec();
while body.len() < content_length {
let n = stream.read(&mut tmp)?;
if n == 0 {
break;
}
body.extend_from_slice(&tmp[..n]);
}
body.truncate(content_length);
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 mut decoder = GzDecoder::new(body.as_slice());
let mut decoded = Vec::new();
decoder
.read_to_end(&mut decoded)
.map_err(|e| ServerError::Protocol(format!("gzip body: {e}")))?;
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()))?;
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) => {
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(),
}
}
}
};
write_http_response_with_scheme(stream, &resp, req.is_https())
}
fn write_http_response<S: Write>(stream: &mut S, resp: &HttpResponse) -> Result<(), ServerError> {
write_http_response_with_scheme(stream, resp, false)
}
fn write_http_response_with_scheme<S: Write>(
stream: &mut S,
resp: &HttpResponse,
is_https: bool,
) -> 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",
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 mut header = format!(
"HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n",
resp.status,
status_text,
resp.content_type,
resp.body.len()
);
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");
stream.write_all(header.as_bytes())?;
stream.write_all(&resp.body)?;
stream.flush()?;
Ok(())
}