Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_steel/src/srv/loopback.rs

4.3 KiB, 1 run

created by r1870400018:71568, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! The loopback plain-HTTP listener.
2//!
3//! `ServerConfig::loopback_http_port` binds 127.0.0.1 and ::1 and serves every vhost over plain
4//! HTTP through `handle_https` in its `plain` mode, which takes the vhost from each request's Host
5//! header and sends no HSTS. The bind goes through `bind_loopback`, which refuses any address that
6//! is not loopback, so no config value can put an unencrypted listener on a public interface.
7
8use crate::srv::{
9 context::ServerContext,
10 stop,
11};
12
13use oxedyne_fe2o3_core::prelude::*;
14use oxedyne_fe2o3_iop_crypto::enc::Encrypter;
15use oxedyne_fe2o3_iop_db::api::Database;
16use oxedyne_fe2o3_iop_hash::api::Hasher;
17use oxedyne_fe2o3_jdat::id::NumIdDat;
18use oxedyne_fe2o3_net::{
19 http::handler::WebHandler,
20 ws::handler::WebSocketHandler,
21};
22
23use std::{
24 net::{
25 IpAddr,
26 Ipv4Addr,
27 Ipv6Addr,
28 SocketAddr,
29 },
30 sync::{
31 atomic::{
32 AtomicUsize,
33 Ordering,
34 },
35 Arc,
36 },
37};
38
39use tokio::net::TcpListener;
40
41/// Binds `addr` only when it is a loopback address.
42pub async fn bind_loopback(addr: SocketAddr) -> Outcome<TcpListener> {
43 if !addr.ip().is_loopback() {
44 return Err(err!(
45 "The loopback HTTP listener was asked to bind {}, which is not a loopback address; \
46 it serves plain HTTP and binds 127.0.0.1 and ::1 alone.", addr;
47 Invalid, Input, Network));
48 }
49 Ok(res!(TcpListener::bind(&addr).await, IO, Network))
50}
51
52impl<
53 const UIDL: usize,
54 UID: NumIdDat<UIDL> + 'static,
55 ENC: Encrypter + 'static,
56 KH: Hasher + 'static,
57 DB: Database<UIDL, UID, ENC, KH> + 'static,
58 WH: WebHandler + 'static,
59 WSH: WebSocketHandler + 'static,
60>
61 ServerContext<UIDL, UID, ENC, KH, DB, WH, WSH>
62{
63 /// Serves plain HTTP on `port` at 127.0.0.1 and, where the host has IPv6, ::1. Each
64 /// connection counts in `inflight`, the TLS port's count, so a stop waits for it and
65 /// `max_conn` caps both together. Returns only when neither address could be bound.
66 pub async fn run_loopback_http(
67 self,
68 port: u16,
69 inflight: Arc<AtomicUsize>,
70 )
71 -> Outcome<()>
72 {
73 let mut listeners = Vec::new();
74 for ip in [IpAddr::V4(Ipv4Addr::LOCALHOST), IpAddr::V6(Ipv6Addr::LOCALHOST)] {
75 let addr = SocketAddr::new(ip, port);
76 match bind_loopback(addr).await {
77 Ok(l) => {
78 info!("Loopback HTTP listener bound to {}", addr);
79 listeners.push(l);
80 }
81 // A host without IPv6 has no ::1; 127.0.0.1 alone still serves.
82 Err(e) => warn!("Loopback HTTP listener could not bind {}: {}", addr, e),
83 }
84 }
85 if listeners.is_empty() {
86 return Err(err!(
87 "The loopback HTTP listener bound neither 127.0.0.1:{} nor [::1]:{}.", port, port;
88 IO, Network, Init));
89 }
90 let mut tasks = Vec::new();
91 for listener in listeners {
92 tasks.push(tokio::spawn(self.clone().serve_loopback(listener, inflight.clone())));
93 }
94 for t in tasks {
95 let _ = t.await;
96 }
97 Ok(())
98 }
99
100 /// Serves one bound listener; also what a test drives.
101 pub async fn serve_loopback(
102 self,
103 listener: TcpListener,
104 inflight: Arc<AtomicUsize>,
105 ) {
106 let max_conn = self.cfg.max_conn as usize;
107 loop {
108 let (stream, peer) = match listener.accept().await {
109 Ok(pair) => pair,
110 Err(e) => {
111 error!(err!(e, "Loopback HTTP listener: accept failed."; IO, Network));
112 continue;
113 }
114 };
115 if max_conn != 0 && inflight.load(Ordering::Relaxed) >= max_conn {
116 debug!("total-connection cap {} reached; dropping loopback TCP from {}.",
117 max_conn, peer);
118 continue;
119 }
120 let counted = stop::InFlight::begin(&inflight);
121 let ctx = self.clone();
122 tokio::spawn(async move {
123 let _counted = counted;
124 if let Err(e) = ctx.handle_https(stream, None, peer, true).await {
125 error!(err!(e, "Error handling a loopback HTTP connection."; IO, Network));
126 }
127 });
128 }
129 }
130}