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 if let Some(stream) = accept_or_fast_reject_503(stream) {
174 let dir = git_dir.clone();
175 let opts = opts.clone();
176 thread::spawn(move || {
177 let _ = handle_connection(stream, &dir, &opts);
178 });
179 }
180 }
181 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
182 thread::sleep(std::time::Duration::from_millis(1));
183 }
184 Err(e) => return Err(e.into()),
185 }
186 for (old_listener, _, _) in &draining {
187 match old_listener.accept() {
188 Ok((stream, _)) => {
189 if let Some(stream) = accept_or_fast_reject_503(stream) {
190 let dir = git_dir.clone();
191 let opts = opts.clone();
192 thread::spawn(move || {
193 let _ = handle_connection(stream, &dir, &opts);
194 });
195 }
196 }
197 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
198 Err(e) => eprintln!("arks serve-http: draining listener accept error: {e}"),
199 }
200 }
201 }
202 let drain_secs = std::env::var("ARKS_SHUTDOWN_DRAIN_SECS")
204 .ok()
205 .and_then(|v| v.trim().parse::<u64>().ok())
206 .unwrap_or(10);
207 let drain_deadline = Instant::now() + Duration::from_secs(drain_secs);
208 while active_http_connections() > 0 && Instant::now() < drain_deadline {
209 thread::sleep(Duration::from_millis(25));
210 }
211 Ok(())
212}
213
214pub fn spawn_loopback(git_dir: PathBuf) -> Result<LoopbackHttp, ServerError> {
216 spawn_loopback_with_opts(git_dir, ServeHttpOptions::default())
217}
218
219pub fn spawn_loopback_with_opts(
220 git_dir: PathBuf,
221 opts: ServeHttpOptions,
222) -> Result<LoopbackHttp, ServerError> {
223 let listener = TcpListener::bind("127.0.0.1:0")?;
224 let addr = listener.local_addr()?;
225 listener.set_nonblocking(true)?;
226 let stop = Arc::new(AtomicBool::new(false));
227 let stop2 = stop.clone();
228 let handle = thread::spawn(move || {
229 while !stop2.load(Ordering::SeqCst) {
230 match listener.accept() {
231 Ok((stream, _)) => {
232 if let Some(stream) = accept_or_fast_reject_503(stream) {
233 let dir = git_dir.clone();
234 let opts = opts.clone();
235 thread::spawn(move || {
236 let _ = handle_connection(stream, &dir, &opts);
237 });
238 }
239 }
240 Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
241 thread::sleep(std::time::Duration::from_millis(1));
242 }
243 Err(e) => return Err(e.into()),
244 }
245 }
246 Ok(())
247 });
248 Ok((addr, stop, handle))
249}
250
251fn accept_or_fast_reject_503(mut stream: TcpStream) -> Option<TcpStream> {
253 if active_http_connections() >= max_http_concurrency() {
254 let _ = stream.set_nonblocking(false);
255 let _ = stream.set_write_timeout(Some(Duration::from_secs(2)));
256 let resp = HttpResponse {
257 status: 503,
258 content_type: "text/plain; charset=utf-8".into(),
259 body: b"Service Unavailable: max concurrent connections reached\n".to_vec(),
260 www_authenticate: None,
261 extra_headers: vec![("Retry-After".into(), "1".into())],
262 };
263 let _ = write_http_response(&mut stream, &resp);
264 return None;
265 }
266 Some(stream)
267}
268
269pub fn serve_http_scheme(opts: &ServeHttpOptions) -> &'static str {
271 if opts.tls.is_some() { "https" } else { "http" }
272}
273
274const MAX_KEEP_ALIVE_REQUESTS: usize = 64;
275const KEEP_ALIVE_IDLE_SECS: u64 = 5;
276
277trait HttpStream: Read + Write {
278 fn set_stream_read_timeout(&mut self, timeout: Duration);
279}
280
281impl HttpStream for TcpStream {
282 fn set_stream_read_timeout(&mut self, timeout: Duration) {
283 let _ = self.set_read_timeout(Some(timeout));
284 }
285}
286
287impl HttpStream for rustls::StreamOwned<rustls::ServerConnection, TcpStream> {
288 fn set_stream_read_timeout(&mut self, timeout: Duration) {
289 let _ = self.sock.set_read_timeout(Some(timeout));
290 }
291}
292
293fn handle_connection(
294 mut stream: TcpStream,
295 git_dir: &Path,
296 opts: &ServeHttpOptions,
297) -> Result<(), ServerError> {
298 let _ = SERVER_START.get_or_init(Instant::now);
299 let prev = HTTP_ACTIVE_CONNECTIONS.fetch_add(1, Ordering::Relaxed);
300 let _guard = ActiveConnGuard;
301 if prev >= max_http_concurrency() {
302 let _ = stream.set_nonblocking(false);
303 let resp = HttpResponse {
304 status: 503,
305 content_type: "text/plain; charset=utf-8".into(),
306 body: b"Service Unavailable: max concurrent connections reached\n".to_vec(),
307 www_authenticate: None,
308 extra_headers: vec![("Retry-After".into(), "1".into())],
309 };
310 return write_http_response(&mut stream, &resp);
311 }
312 stream.set_nonblocking(false)?;
314 let _ = stream.set_nodelay(true);
315 stream.set_read_timeout(Some(std::time::Duration::from_secs(30)))?;
316 stream.set_write_timeout(Some(std::time::Duration::from_secs(30)))?;
317 if let Some(tls_cfg) = &opts.tls {
318 let conn = rustls::ServerConnection::new(tls_cfg.clone())
319 .map_err(|e| ServerError::Msg(format!("tls ServerConnection: {e}")))?;
320 let mut tls = rustls::StreamOwned::new(conn, stream);
321 tls.conn
323 .complete_io(&mut tls.sock)
324 .map_err(|e| ServerError::Msg(format!("tls handshake: {e}")))?;
325 handle_connection_io(&mut tls, git_dir, opts)
326 } else {
327 handle_connection_io(&mut stream, git_dir, opts)
328 }
329}
330
331fn handle_connection_io<S: HttpStream>(
332 stream: &mut S,
333 git_dir: &Path,
334 opts: &ServeHttpOptions,
335) -> Result<(), ServerError> {
336 let mut buf = Vec::with_capacity(4096);
337 let mut tmp = [0u8; 8192];
338 for req_idx in 0..MAX_KEEP_ALIVE_REQUESTS {
339 if req_idx > 0 {
340 stream.set_stream_read_timeout(Duration::from_secs(KEEP_ALIVE_IDLE_SECS));
341 }
342 let mut header_end = buf.windows(4).position(|w| w == b"\r\n\r\n");
343 while header_end.is_none() {
345 let prev_len = buf.len();
346 match stream.read(&mut tmp) {
347 Ok(0) => {
348 if req_idx > 0 && buf.is_empty() {
349 return Ok(());
350 }
351 break;
352 }
353 Ok(n) => {
354 if req_idx > 0 && prev_len == 0 {
355 stream.set_stream_read_timeout(Duration::from_secs(30));
356 }
357 buf.extend_from_slice(&tmp[..n]);
358 let search_from = prev_len.saturating_sub(3);
359 if let Some(rel) = buf[search_from..].windows(4).position(|w| w == b"\r\n\r\n")
360 {
361 header_end = Some(search_from + rel);
362 break;
363 }
364 if buf.len() > 1024 * 1024 {
365 return Err(ServerError::Protocol("headers too large".into()));
366 }
367 }
368 Err(e)
369 if req_idx > 0
370 && buf.is_empty()
371 && matches!(
372 e.kind(),
373 std::io::ErrorKind::WouldBlock
374 | std::io::ErrorKind::TimedOut
375 | std::io::ErrorKind::ConnectionReset
376 | std::io::ErrorKind::UnexpectedEof
377 ) =>
378 {
379 return Ok(());
380 }
381 Err(e) => return Err(e.into()),
382 }
383 }
384 let Some(header_end) = header_end else {
385 if req_idx > 0 && buf.is_empty() {
386 return Ok(());
387 }
388 return Err(ServerError::Protocol("incomplete headers".into()));
389 };
390 HTTP_REQUESTS_TOTAL.fetch_add(1, Ordering::Relaxed);
391 let header_bytes = &buf[..header_end];
392 let header_text = std::str::from_utf8(header_bytes)
393 .map_err(|_| ServerError::Protocol("headers not utf-8".into()))?;
394 let mut lines = header_text.split("\r\n");
395 let request_line = lines
396 .next()
397 .ok_or_else(|| ServerError::Protocol("missing request line".into()))?;
398 let mut parts = request_line.split_whitespace();
399 let method = parts
400 .next()
401 .ok_or_else(|| ServerError::Protocol("bad request line".into()))?
402 .to_string();
403 let target = parts
404 .next()
405 .ok_or_else(|| ServerError::Protocol("bad request line".into()))?;
406 let http_version = parts.next().unwrap_or("HTTP/1.1");
407 let (path, query) = match target.split_once('?') {
408 Some((p, q)) => (p.to_string(), q.to_string()),
409 None => (target.to_string(), String::new()),
410 };
411 let mut content_length = 0usize;
412 let mut expect_continue = false;
413 let mut content_encoding = String::new();
414 let mut connection_close = false;
415 let mut connection_keep_alive = false;
416 let mut git_protocol = None;
417 let mut authorization = None;
418 let mut destination = None;
419 let mut lock_token = None;
420 let mut host = None;
421 let mut cookie = None;
422 let mut origin = None;
423 let mut forwarded_proto = None;
424 for line in lines {
425 let lower = line.to_ascii_lowercase();
426 if let Some(v) = lower.strip_prefix("content-length:") {
427 content_length = v.trim().parse().unwrap_or(0);
428 }
429 if let Some(v) = lower.strip_prefix("connection:") {
430 if v.contains("close") {
431 connection_close = true;
432 }
433 if v.contains("keep-alive") {
434 connection_keep_alive = true;
435 }
436 }
437 if lower.starts_with("host:") {
438 if let Some((_, v)) = line.split_once(':') {
439 host = Some(v.trim().to_string());
440 }
441 }
442 if lower.starts_with("cookie:") {
443 if let Some((_, v)) = line.split_once(':') {
444 cookie = Some(v.trim().to_string());
445 }
446 }
447 if lower.starts_with("origin:") {
448 if let Some((_, v)) = line.split_once(':') {
449 origin = Some(v.trim().to_string());
450 }
451 }
452 if lower.starts_with("x-forwarded-proto:") {
453 if let Some((_, v)) = line.split_once(':') {
454 forwarded_proto = Some(v.trim().to_string());
455 }
456 }
457 if lower.starts_with("expect:") && lower.contains("100-continue") {
458 expect_continue = true;
461 }
462 if let Some(v) = lower.strip_prefix("content-encoding:") {
463 content_encoding = v.trim().to_string();
464 }
465 if lower.starts_with("git-protocol:") {
467 if let Some((_, v)) = line.split_once(':') {
468 git_protocol = Some(v.trim().to_string());
469 }
470 }
471 if lower.starts_with("authorization:") {
472 if let Some((_, v)) = line.split_once(':') {
473 authorization = Some(v.trim().to_string());
474 }
475 }
476 if lower.starts_with("destination:") {
478 if let Some((_, v)) = line.split_once(':') {
479 destination = Some(v.trim().to_string());
480 }
481 }
482 if lower.starts_with("lock-token:") {
483 if let Some((_, v)) = line.split_once(':') {
484 lock_token = Some(v.trim().to_string());
485 }
486 }
487 if lower.starts_with("if:") && lock_token.is_none() {
488 if let Some((_, v)) = line.split_once(':') {
490 let v = v.trim();
491 if let Some(start) = v.find("opaquelocktoken:") {
492 let rest = &v[start..];
493 let end = rest
494 .find(|c: char| c == ')' || c == '>' || c.is_whitespace())
495 .unwrap_or(rest.len());
496 lock_token = Some(rest[..end].to_string());
497 }
498 }
499 }
500 }
501 let want_keep_alive = if http_version.eq_ignore_ascii_case("HTTP/1.0") {
502 connection_keep_alive && !connection_close
503 } else {
504 !connection_close
505 };
506 let keep_alive_rem = if want_keep_alive && req_idx + 1 < MAX_KEEP_ALIVE_REQUESTS {
507 Some(MAX_KEEP_ALIVE_REQUESTS - req_idx - 1)
508 } else {
509 None
510 };
511 let body_start = header_end + 4;
512 if path == "/healthz" || path == "/readyz" {
513 let body = b"{\"status\":\"ok\"}\n";
514 let resp = HttpResponse {
515 status: 200,
516 content_type: "application/json; charset=utf-8".into(),
517 body: body.to_vec(),
518 www_authenticate: None,
519 extra_headers: vec![("Cache-Control".into(), "no-store".into())],
520 };
521 buf.drain(..body_start.min(buf.len()));
522 write_http_response_with_options(stream, &resp, opts.tls.is_some(), keep_alive_rem)?;
523 if keep_alive_rem.is_some() {
524 continue;
525 }
526 return Ok(());
527 }
528 if path == "/metrics" {
529 let total = HTTP_REQUESTS_TOTAL.load(Ordering::Relaxed);
530 let active = HTTP_ACTIVE_CONNECTIONS.load(Ordering::Relaxed);
531 let uptime = SERVER_START.get_or_init(Instant::now).elapsed().as_secs();
532 let metrics = format!(
533 "# HELP arks_http_requests_total Total HTTP requests handled by arks serve.\n\
534 # TYPE arks_http_requests_total counter\n\
535 arks_http_requests_total {total}\n\
536 # HELP arks_http_active_connections Currently active HTTP worker connections.\n\
537 # TYPE arks_http_active_connections gauge\n\
538 arks_http_active_connections {active}\n\
539 # HELP arks_uptime_seconds Server process uptime in seconds.\n\
540 # TYPE arks_uptime_seconds gauge\n\
541 arks_uptime_seconds {uptime}\n"
542 );
543 let resp = HttpResponse {
544 status: 200,
545 content_type: "text/plain; version=0.0.4; charset=utf-8".into(),
546 body: metrics.into_bytes(),
547 www_authenticate: None,
548 extra_headers: vec![("Cache-Control".into(), "no-store".into())],
549 };
550 buf.drain(..body_start.min(buf.len()));
551 write_http_response_with_options(stream, &resp, opts.tls.is_some(), keep_alive_rem)?;
552 if keep_alive_rem.is_some() {
553 continue;
554 }
555 return Ok(());
556 }
557 let max_body = max_http_body_bytes();
558 if content_length > max_body {
559 let resp = HttpResponse {
560 status: 413,
561 content_type: "text/plain; charset=utf-8".into(),
562 body: format!("Payload Too Large (max {max_body} bytes)\n").into_bytes(),
563 www_authenticate: None,
564 extra_headers: Vec::new(),
565 };
566 return write_http_response(stream, &resp);
567 }
568 if expect_continue && content_length > 0 {
569 stream.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?;
570 stream.flush()?;
571 }
572 let total_needed = body_start.saturating_add(content_length);
573 while buf.len() < total_needed {
574 let n = stream.read(&mut tmp)?;
575 if n == 0 {
576 break;
577 }
578 buf.extend_from_slice(&tmp[..n]);
579 }
580 let avail_end = total_needed.min(buf.len());
581 let mut body = buf[body_start..avail_end].to_vec();
582 buf.drain(..avail_end);
583 let is_lfs = crate::lfs::is_lfs_path(&path);
587 let gzip_magic = !is_lfs && body.len() >= 2 && body[0] == 0x1f && body[1] == 0x8b;
588 if content_encoding.contains("gzip") || gzip_magic {
589 use flate2::read::GzDecoder;
590 use std::io::Read as _;
591 let decoder = GzDecoder::new(body.as_slice());
592 let mut decoded = Vec::new();
593 decoder
594 .take((max_body as u64).saturating_add(1))
595 .read_to_end(&mut decoded)
596 .map_err(|e| ServerError::Protocol(format!("gzip body: {e}")))?;
597 if decoded.len() > max_body {
598 let resp = HttpResponse {
599 status: 413,
600 content_type: "text/plain; charset=utf-8".into(),
601 body: format!(
602 "Payload Too Large (decompressed exceeds max {max_body} bytes)\n"
603 )
604 .into_bytes(),
605 www_authenticate: None,
606 extra_headers: Vec::new(),
607 };
608 return write_http_response(stream, &resp);
609 }
610 body = decoded;
611 }
612
613 let mut req = HttpRequest {
614 method,
615 path: path.clone(),
616 query: query.clone(),
617 body,
618 git_protocol,
619 authorization,
620 destination,
621 lock_token,
622 host,
623 cookie,
624 origin,
625 forwarded_proto: forwarded_proto.or_else(|| {
626 if opts.tls.is_some() {
627 Some("https".into())
628 } else {
629 None
630 }
631 }),
632 };
633 let resp = if opts.multi_repo_root {
634 match opts.pages.as_ref().and_then(|p| p(&req)) {
635 Some(r) => r,
636 None => HttpResponse {
637 status: 404,
638 content_type: "text/plain; charset=utf-8".into(),
639 body: b"repository or path not found\n".to_vec(),
640 www_authenticate: None,
641 extra_headers: Vec::new(),
642 },
643 }
644 } else {
645 let mut repo =
646 Repository::open(git_dir).map_err(|e| ServerError::Msg(e.to_string()))?;
647 if opts.dumb_only
649 && (req.path.ends_with("info/refs") || req.path.ends_with("/info/refs"))
650 {
651 req.query = String::new();
652 }
653 let is_git_rpc = req.path.contains("/git-upload-pack")
654 || req.path.contains("/git-receive-pack")
655 || req.path.contains("/info/refs");
656 let page = match &opts.pages {
657 Some(pages)
658 if matches!(req.method.as_str(), "GET" | "POST" | "PATCH" | "DELETE")
659 && !is_lfs
660 && !is_git_rpc =>
661 {
662 pages(&req)
663 }
664 _ => None,
665 };
666 let scheme = serve_http_scheme(opts);
667 let is_git_write = req.path.contains("/git-receive-pack")
668 || (req.path.contains("/info/refs") && req.query.contains("git-receive-pack"))
669 || (req.path.contains("/info/lfs/") && req.method == "PUT");
670 let auth_denied = if page.is_none() && opts.basic_auth.is_none() {
671 crate::web_ui::check_git_http_auth(git_dir, &req, is_git_write).err()
672 } else {
673 None
674 };
675 match page.or(auth_denied).map(Ok).unwrap_or_else(|| {
676 handle_smart_http_auth_opts(
677 &mut repo,
678 &req,
679 opts.basic_auth.as_ref(),
680 !opts.disable_lfs,
681 scheme,
682 )
683 }) {
684 Ok(r) => r,
685 Err(e) => {
686 let msg = e.to_string();
688 let hex: String = req
689 .body
690 .iter()
691 .take(32)
692 .map(|b| format!("{b:02x}"))
693 .collect::<Vec<_>>()
694 .join(" ");
695 eprintln!(
696 "arks serve-http error path={path} query={query} body_len={} hex32=[{hex}] : {msg}",
697 req.body.len()
698 );
699 HttpResponse {
700 status: 500,
701 content_type: "text/plain".into(),
702 body: msg.into_bytes(),
703 www_authenticate: None,
704 extra_headers: Vec::new(),
705 }
706 }
707 }
708 };
709 let keep_alive = if matches!(resp.status, 413 | 503) {
710 None
711 } else {
712 keep_alive_rem
713 };
714 write_http_response_with_options(stream, &resp, req.is_https(), keep_alive)?;
715 if keep_alive.is_none() {
716 return Ok(());
717 }
718 }
719 Ok(())
720}
721
722fn write_http_response<S: Write>(stream: &mut S, resp: &HttpResponse) -> Result<(), ServerError> {
723 write_http_response_with_options(stream, resp, false, None)
724}
725
726fn write_http_response_with_options<S: Write>(
727 stream: &mut S,
728 resp: &HttpResponse,
729 is_https: bool,
730 keep_alive_remaining: Option<usize>,
731) -> Result<(), ServerError> {
732 let status_text = match resp.status {
733 200 => "OK",
734 201 => "Created",
735 204 => "No Content",
736 207 => "Multi-Status",
737 302 => "Found",
738 303 => "See Other",
739 400 => "Bad Request",
740 401 => "Unauthorized",
741 403 => "Forbidden",
742 404 => "Not Found",
743 405 => "Method Not Allowed",
744 409 => "Conflict",
745 413 => "Payload Too Large",
746 422 => "Unprocessable Entity",
747 423 => "Locked",
748 429 => "Too Many Requests",
749 500 => "Internal Server Error",
750 501 => "Not Implemented",
751 503 => "Service Unavailable",
752 _ => "Error",
753 };
754 let conn_header = match keep_alive_remaining {
755 Some(rem) => format!(
756 "Connection: keep-alive\r\nKeep-Alive: timeout={KEEP_ALIVE_IDLE_SECS}, max={rem}\r\n"
757 ),
758 None => "Connection: close\r\n".to_string(),
759 };
760 let mut header = format!(
761 "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\n{}",
762 resp.status,
763 status_text,
764 resp.content_type,
765 resp.body.len(),
766 conn_header
767 );
768 if let Some(ref wa) = resp.www_authenticate {
769 header.push_str(&format!("WWW-Authenticate: {wa}\r\n"));
770 }
771 let mut has_xfo = false;
772 let mut has_rp = false;
773 let mut has_hsts = false;
774 for (k, v) in &resp.extra_headers {
775 if k.eq_ignore_ascii_case("x-frame-options") {
776 has_xfo = true;
777 } else if k.eq_ignore_ascii_case("referrer-policy") {
778 has_rp = true;
779 } else if k.eq_ignore_ascii_case("strict-transport-security") {
780 has_hsts = true;
781 }
782 header.push_str(&format!("{k}: {v}\r\n"));
783 }
784 if resp.content_type.starts_with("text/html") {
785 if !has_xfo {
786 header.push_str("X-Frame-Options: DENY\r\n");
787 }
788 if !has_rp {
789 header.push_str("Referrer-Policy: same-origin\r\n");
790 }
791 }
792 if is_https && !has_hsts {
793 header.push_str("Strict-Transport-Security: max-age=31536000; includeSubDomains\r\n");
794 }
795 header.push_str("\r\n");
796 if resp.body.len() <= 64 * 1024 {
797 let mut combined = Vec::with_capacity(header.len() + resp.body.len());
798 combined.extend_from_slice(header.as_bytes());
799 combined.extend_from_slice(&resp.body);
800 stream.write_all(&combined)?;
801 } else {
802 stream.write_all(header.as_bytes())?;
803 stream.write_all(&resp.body)?;
804 }
805 stream.flush()?;
806 Ok(())
807}