itsybitsy/bin/src/proto/nex.rs

58 lines
2.1 KiB
Rust
Raw Normal View History

//! Nex: a bare path in, bytes out, no status line and no headers.
//!
//! There is nothing to signal an error with, so a failure is a plain-text body,
//! and nothing to redirect with either, which is why resolution follows the
//! canonical target server-side rather than bouncing the client.
use std::io::{BufReader, Write};
use std::net::TcpStream;
use anyhow::Result;
use itsybitsy_core::site::{Resolution, Resource};
use crate::proto::{for_log, read_line_capped};
use crate::serve::Listener;
/// Nex requests are a single path; the cap is smolweb's.
const MAX_REQUEST: usize = 2048;
pub fn serve(listener: &Listener, mut stream: TcpStream) -> Result<()> {
let selector = {
let mut reader = BufReader::new(stream.try_clone()?);
read_line_capped(&mut reader, MAX_REQUEST)
};
let Some(selector) = selector else {
log::warn!("{}: unreadable or oversized request", listener.name);
stream.write_all(b"Bad request\n")?;
return Ok(());
};
// Nex carries no hostname, so the listener names its site outright and
// configuration validation has already proved it exists.
let site = listener.only_site();
let path = if selector.is_empty() { "/" } else { &selector };
log::info!("{} nex {}", listener.name, for_log(path));
match site.resolve_flat(path) {
Ok(Resolution::Found(Resource::Document { url, page })) => {
match page.body(&listener.formats[0]) {
Some(body) => stream.write_all(body)?,
None => stream.write_all(b"Internal error\n")?,
}
let _ = url;
}
Ok(Resolution::Found(Resource::Raw { path, .. })) => {
let mut file = std::fs::File::open(&path)?;
std::io::copy(&mut file, &mut stream)?;
}
// resolve_flat follows redirects and sub-documents to real content, so
// neither reaches here; they are matched for completeness.
Ok(_) => stream.write_all(b"Not found\n")?,
Err(err) => {
log::warn!("{} nex {}: {err}", listener.name, for_log(path));
stream.write_all(b"Internal error\n")?;
}
}
Ok(())
}