ostrya_server/server.rs
1//! The listeners and the connections of a server.
2
3use std::convert::Infallible;
4use std::net::SocketAddr;
5use std::sync::Arc;
6use std::sync::atomic::AtomicUsize;
7use std::time::Duration;
8
9use futures_lite::future;
10use futures_rustls::TlsAcceptor;
11use futures_rustls::rustls::ServerConfig;
12use hyper::Request;
13use hyper::body::Incoming;
14use hyper::server::conn::{http1, http2};
15use hyper::service::service_fn;
16use ostrya::{ArchiveView, Checksum, Repo};
17use ostrya_fetch::{FuturesIo, RtExecutor, RtTimer};
18use ostrya_rt as rt;
19
20use crate::auth::{FileAuth, Peer};
21use crate::endpoint::{EndpointOptions, ReceiveEndpoint};
22use crate::error::{Error, Result};
23use crate::options::ServeOptions;
24use crate::router;
25use crate::shutdown::{Shutdown, Trigger};
26use crate::stall::Stall;
27
28/// The time a TLS handshake has to complete.
29const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);
30
31/// The time an HTTP/1.1 connection has to send the headers of a request.
32const HEADER_READ_TIMEOUT: Duration = Duration::from_secs(30);
33
34/// The most streams one HTTP/2 connection carries at the same time.
35const MAX_CONCURRENT_STREAMS: u32 = 32;
36
37/// The largest header list of one request that an HTTP/2 connection takes:
38/// 32 KiB.
39///
40/// The size of the list is the sum, for each header field, of the name, the
41/// value, and 32 bytes. The pseudo-header `:path` counts, so the request
42/// target counts. The client of a ref listing sends a target of at most
43/// 16 KiB, which comes after the base path of the mirror. The limit leaves
44/// 16 KiB for the base path and the other fields. A larger list gets 431.
45const MAX_HEADER_LIST_SIZE: u32 = 32 * 1024;
46
47/// The wait after an accept fails, for example when the process is out of
48/// descriptors, before the listener accepts again.
49const ACCEPT_BACKOFF: Duration = Duration::from_millis(100);
50
51/// A server with its listeners bound, ready to [`run`](Server::run).
52///
53/// # HTTP behavior
54///
55/// - The server answers `GET` and `HEAD`, except on the ref listing. Outside
56/// the receive endpoint and the ref listing, another method gets 405 with
57/// `Allow: GET, HEAD`.
58/// - With a receive endpoint, a request under the raw path prefix
59/// `/_ostrya/receive/v1/` goes to the endpoint if its method is not `GET`
60/// or `HEAD`. A `GET` or a `HEAD` under the prefix goes to the archive
61/// view and gets 404.
62/// - A `GET` and a `HEAD` of the archive view, and a `GET` of the ref
63/// listing, ignore `Authorization`.
64/// - The HTTP layer removes a `#` fragment before the routing, so the server
65/// does not see a fragment.
66/// - The server percent-decodes the request path. Outside the ref listing,
67/// it ignores the query. If the path has a bad escape, a NUL, or bytes
68/// that are not UTF-8, the response is 404.
69/// - The server answers the raw path `/_ostrya/refs/v1`, with and without a
70/// receive endpoint, with the bytes of [`Repo::build_ref_listing`]. The
71/// path must match exactly, and the server reads its query. Each pair of
72/// the query is `pattern=VALUE`, with the raw key `pattern` and a
73/// percent-decoded value in which `+` stays `+`. The value is one entry of
74/// a [`ostrya::RefSelector`]: a ref pattern with an optional leading `!`.
75/// An entry has at most [`ostrya::MAX_REF_ENTRY_PARTS`] parts and
76/// [`ostrya::MAX_REF_ENTRY_LEN`] bytes. No query is an empty list, which
77/// selects all refs. The checks come in this order:
78/// 1. A method other than `GET`, `HEAD` included, gets 405 with
79/// `Allow: GET`.
80/// 2. A bad pair, an entry over the limits of one entry, an entry that
81/// [`ostrya::RefSelector::parse`] refuses, and a query of more than 256
82/// pairs ([`ostrya::MAX_REF_PATTERNS`]), get 400. An entry given two
83/// times counts two times, and the server keeps it one time.
84/// 3. If 4 listings are in flight over all connections, the request gets
85/// 503 with `Retry-After: 1`. A listing is in flight from the start of
86/// its build until its response body drops.
87///
88/// Then the server builds the listing. Each error of the build gets 500.
89/// A 400, a 405, a 500, and a 503 have an empty body. A 200 carries
90/// `Content-Length`, and the server sends the body in frames of at most
91/// 64 KiB under the body timeout.
92/// - A path that the view does not find gets 404 with an empty body. A path
93/// that the view refuses gets the same response, so a client cannot tell
94/// a private path from an absent one.
95/// - If the view returns an error, the response is 500 with an empty body.
96/// - A response with a known length carries `Content-Length`. A `.filez`
97/// built on request carries no `Content-Length`.
98/// - The server reads a file of the archive view in frames of at most
99/// 64 KiB, and never collects the file whole. The server builds a ref
100/// listing whole in memory, at most [`ostrya::MAX_REF_LISTING`] bytes, and
101/// sends it in frames of at most 64 KiB.
102/// - A `HEAD` takes the answer of [`ArchiveView::head`], which reads no byte
103/// of the file. For a `.filez` built on request, it reads no xattr and
104/// does no deflate work.
105/// - Plain HTTP serves HTTP/1.1. Over TLS, ALPN selects HTTP/2 or HTTP/1.1.
106/// An HTTP/2 connection carries at most 32 streams at the same time. It
107/// takes a header list of at most 32 KiB for one request, counted as the
108/// name, the value, and 32 bytes of each header field. A larger list gets
109/// 431.
110/// - A TLS handshake has 30 seconds to complete. An HTTP/1.1 connection has
111/// 30 seconds to send the headers of each request.
112/// - With a receive endpoint, the HTTP/2 windows are the windows of
113/// [`ReceiveEndpoint::h2_windows`]. A read-only server keeps the windows
114/// of hyper.
115/// - If a response body waits longer than [`ServeOptions::body_timeout`]
116/// for the client, the server ends its connection. If an HTTP/2 peer does
117/// not answer a ping within that time, the server ends the connection.
118/// - A body that streams gives at most 256 KiB in one run of polls. Then it
119/// yields to the executor.
120/// - With a client CA, the server verifies a client certificate against the
121/// CA. The server also serves a client that presents no certificate.
122pub struct Server {
123 listeners: Vec<rt::TcpListener>,
124 addrs: Vec<SocketAddr>,
125 view: Arc<ArchiveView>,
126 repo: Repo,
127 receive: Option<Arc<ReceiveEndpoint<FileAuth>>>,
128 tls: Option<Arc<ServerConfig>>,
129 body_timeout: Duration,
130}
131
132/// Returns the receive endpoint of `opts` over `repo`, or `None` if `opts`
133/// has no receive policy. With a policy, the function checks the
134/// authentication methods first, with [`FileAuth::new`]. Then it checks the
135/// other options, with [`ReceiveEndpoint::new`]. With no policy, it checks
136/// nothing.
137fn receive(repo: &Repo, opts: &ServeOptions) -> Result<Option<Arc<ReceiveEndpoint<FileAuth>>>> {
138 let Some(policy) = &opts.receive else {
139 return Ok(None);
140 };
141 let auth = FileAuth::new(opts, policy.clone())?;
142 let options = EndpointOptions {
143 parallel_uploads: opts.parallel_uploads,
144 session_idle_timeout: opts.session_idle_timeout,
145 max_sessions: opts.max_sessions,
146 on_report: opts.on_report.clone(),
147 };
148 let endpoint = ReceiveEndpoint::new(repo.clone(), auth, options)?;
149 Ok(Some(Arc::new(endpoint)))
150}
151
152/// Binds the listeners of `opts` and returns a server over `repo`.
153///
154/// The function checks the options and builds the TLS configuration of
155/// `opts`. Then it binds each listen address of `opts`, in order. The server
156/// serves the archive view of `repo`. With [`ServeOptions::receive`], it also
157/// serves the receive endpoint over `repo`.
158///
159/// # Errors
160///
161/// The checks run in this order:
162///
163/// - [`Error::Options`] if `listen` is empty, or if `body_timeout` is zero.
164/// - [`Error::Credentials`] if `receive` is set and a line of `credentials`
165/// is malformed.
166/// - [`Error::Options`] if `receive` is set and the endpoint has no
167/// [authentication method](ServeOptions#authentication).
168/// - [`Error::Options`] if `receive` is set, `tls` is `None`, and both
169/// `allow_anonymous_push` and `allow_cleartext_credentials` are `false`.
170/// - [`Error::Options`] if `receive` is set and `parallel_uploads` is
171/// outside `1..=31`, or `session_idle_timeout` or `max_sessions` is zero.
172/// - [`Error::Tls`] if the TLS files give no server configuration.
173/// - [`Error::Bind`] if a listen address cannot be bound, or if its local
174/// address cannot be read.
175pub async fn bind(repo: Repo, opts: ServeOptions) -> Result<Server> {
176 if opts.listen.is_empty() {
177 return Err(Error::Options("no listen address".into()));
178 }
179 if opts.body_timeout.is_zero() {
180 return Err(Error::Options("a body timeout of zero".into()));
181 }
182 let receive = receive(&repo, &opts)?;
183 let tls = match &opts.tls {
184 Some(tls) => Some(
185 ostrya_fetch::server_config(
186 &tls.cert_chain_pem,
187 &tls.key_pem,
188 tls.key_passphrase.as_deref(),
189 tls.client_ca_pem.as_deref(),
190 )
191 .await
192 .map_err(|e| match e {
193 ostrya_fetch::Error::Fetch(message) => Error::Tls(message),
194 other => Error::Tls(other.to_string()),
195 })?,
196 ),
197 None => None,
198 };
199 let mut listeners = Vec::with_capacity(opts.listen.len());
200 let mut addrs = Vec::with_capacity(opts.listen.len());
201 for addr in opts.listen {
202 let bound = |source| Error::Bind { addr, source };
203 let listener = rt::TcpListener::bind(addr).await.map_err(bound)?;
204 addrs.push(listener.local_addr().map_err(bound)?);
205 listeners.push(listener);
206 }
207 Ok(Server {
208 listeners,
209 addrs,
210 view: Arc::new(ArchiveView::new(repo.clone())),
211 repo,
212 receive,
213 tls,
214 body_timeout: opts.body_timeout,
215 })
216}
217
218/// Binds the listeners of `opts` and runs the server until the future drops.
219///
220/// The function calls [`bind`], then [`Server::run`].
221///
222/// # Errors
223///
224/// The errors of [`bind`](bind#errors). The future of [`Server::run`] never
225/// completes, so it gives no error.
226pub async fn serve(repo: Repo, opts: ServeOptions) -> Result<()> {
227 bind(repo, opts).await?.run().await
228}
229
230impl Server {
231 /// Returns the address of each listener, in the order of the options.
232 ///
233 /// If the options give port 0, the address holds the port that the
234 /// kernel chose.
235 pub fn local_addrs(&self) -> &[SocketAddr] {
236 &self.addrs
237 }
238
239 /// Serves connections until the future drops.
240 ///
241 /// Each listener accepts in a task of its own. The idle sweep of the
242 /// sessions runs in a task of its own. If an accept fails, the listener
243 /// accepts again after 100 ms.
244 ///
245 /// When the future drops, the server closes the listeners and ends each
246 /// connection that it accepted. It also stops the receive endpoint,
247 /// which aborts each session that does not commit. The
248 /// [session rules](ReceiveEndpoint#sessions) of the endpoint state the
249 /// other effects.
250 ///
251 /// # Errors
252 ///
253 /// The future never completes, so it returns no error.
254 pub async fn run(self) -> Result<()> {
255 let shutdown = Arc::new(Shutdown::default());
256 let _trigger = Trigger(shutdown.clone());
257 if let Some(endpoint) = &self.receive {
258 let endpoint = endpoint.clone();
259 let stop = shutdown.wait();
260 drop(rt::spawn(async move {
261 future::or(endpoint.sweep(), stop).await;
262 endpoint.shutdown();
263 }));
264 }
265 let serving = Arc::new(Serving {
266 view: self.view,
267 repo: self.repo,
268 listings: Arc::new(AtomicUsize::new(0)),
269 receive: self.receive,
270 tls: self.tls,
271 body_timeout: self.body_timeout,
272 });
273 for listener in self.listeners {
274 let accept = accept_loop(listener, serving.clone(), shutdown.clone());
275 drop(rt::spawn(future::or(accept, shutdown.wait())));
276 }
277 std::future::pending().await
278 }
279}
280
281/// The state that each connection of a server shares.
282struct Serving {
283 view: Arc<ArchiveView>,
284 repo: Repo,
285 /// The count of ref listings in flight, over all connections.
286 listings: Arc<AtomicUsize>,
287 receive: Option<Arc<ReceiveEndpoint<FileAuth>>>,
288 tls: Option<Arc<ServerConfig>>,
289 body_timeout: Duration,
290}
291
292/// Accepts connections on `listener` and serves each one in a task of its
293/// own, until `shutdown` fires.
294async fn accept_loop(listener: rt::TcpListener, serving: Arc<Serving>, shutdown: Arc<Shutdown>) {
295 loop {
296 match listener.accept().await {
297 Ok((stream, _peer)) => {
298 let connection = connection(stream, serving.clone());
299 let stop = shutdown.wait();
300 drop(rt::spawn(future::or(connection, stop)));
301 }
302 Err(_) => rt::Timer::after(ACCEPT_BACKOFF).await,
303 }
304 }
305}
306
307/// Serves one connection until it ends, or until one of its response bodies
308/// waits longer than the body timeout for the client.
309async fn connection(stream: rt::TcpStream, serving: Arc<Serving>) {
310 let stall = Stall::new(serving.body_timeout);
311 future::or(
312 serve_connection(stream, serving, stall.clone()),
313 async move { stall.expired().await },
314 )
315 .await
316}
317
318/// Serves one connection. An error ends this connection and no other. With
319/// a receive endpoint, each request carries the [`Peer`] of the connection
320/// in its extensions.
321async fn serve_connection(stream: rt::TcpStream, serving: Arc<Serving>, stall: Arc<Stall>) {
322 let shared = serving.clone();
323 let service = move |peer: Peer| {
324 service_fn(move |mut req: Request<Incoming>| {
325 let serving = shared.clone();
326 let stall = stall.clone();
327 if serving.receive.is_some() {
328 req.extensions_mut().insert(peer);
329 }
330 async move {
331 let receive = serving.receive.as_deref();
332 let response = router::handle(
333 &serving.view,
334 &serving.repo,
335 &serving.listings,
336 receive,
337 &stall,
338 req,
339 )
340 .await;
341 Ok::<_, Infallible>(response)
342 }
343 })
344 };
345 let Some(config) = serving.tls.clone() else {
346 let peer = Peer {
347 tls: false,
348 cert: None,
349 };
350 let served = http1::Builder::new()
351 .timer(RtTimer)
352 .header_read_timeout(HEADER_READ_TIMEOUT)
353 .serve_connection(FuturesIo::new(stream), service(peer));
354 let _ = served.await;
355 return;
356 };
357 let handshake = future::or(
358 async { Some(TlsAcceptor::from(config).accept(stream).await) },
359 async {
360 rt::Timer::after(HANDSHAKE_TIMEOUT).await;
361 None
362 },
363 );
364 let Some(Ok(stream)) = handshake.await else {
365 return;
366 };
367 let connection = stream.get_ref().1;
368 let h2 = connection.alpn_protocol() == Some(b"h2".as_slice());
369 let peer = Peer {
370 tls: true,
371 cert: connection
372 .peer_certificates()
373 .and_then(|chain| chain.first())
374 .map(|der| Checksum::sha256(der.as_ref())),
375 };
376 let service = service(peer);
377 let io = FuturesIo::new(stream);
378 if h2 {
379 let mut builder = http2::Builder::new(RtExecutor);
380 builder
381 .timer(RtTimer)
382 .max_concurrent_streams(MAX_CONCURRENT_STREAMS)
383 .max_header_list_size(MAX_HEADER_LIST_SIZE)
384 .keep_alive_interval(Some(serving.body_timeout / 2))
385 .keep_alive_timeout(serving.body_timeout);
386 // With a receive endpoint, the windows bound the bytes of the request
387 // bodies of one connection that the server did not read. A
388 // read-only server keeps the windows of hyper.
389 if let Some((stream, connection)) = serving.receive.as_ref().map(|e| e.h2_windows()) {
390 builder
391 .initial_stream_window_size(stream)
392 .initial_connection_window_size(connection);
393 }
394 let served = builder.serve_connection(io, service);
395 let _ = served.await;
396 } else {
397 let served = http1::Builder::new()
398 .timer(RtTimer)
399 .header_read_timeout(HEADER_READ_TIMEOUT)
400 .serve_connection(io, service);
401 let _ = served.await;
402 }
403}