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