git clone https://garage44.eu/jeroen/pinnacle.git.. /net/src/http.rs
//! HTTP/1.1 as the client speaks it, with no I/O of its own: a request
//! written to bytes, and a response read from bytes as they arrive, its body
//! handed on in pieces whether it came with a length, in chunks, or until
//! the server closed. [`Events`] reads server-sent events out of such a
//! body, as a model provider streams its answer.
//!
//! One request a connection (`Connection: close`): what Pinnacle's
//! programs ask is a page, a package or a model's answer, and a connection
//! kept open is state nobody needs.
use alloc::string::String;
use alloc::vec::Vec;
/// A request to send.
#[derive(Clone, Debug)]
pub struct Request<'a> {
pub method: &'a str,
pub host: &'a str,
/// From the first `/`, query included.
pub path: &'a str,
pub headers: &'a [(&'a str, &'a str)],
pub body: &'a [u8],
}
impl Request<'_> {
/// The request's bytes. A header that would end the head early (a line
/// break in a name or value) is left out: headers come from settings
/// a person typed, and must not become a second request.
pub fn encode(&self) -> Vec<u8> {
let mut out = String::new();
out += self.method;
out += " ";
out += self.path;
out += " HTTP/1.1\r\nHost: ";
out += self.host;
out += "\r\nUser-Agent: Pinnacle\r\nConnection: close\r\n";
for (name, value) in self.headers {
if [name, value].iter().any(|s| s.contains(['\r', '\n'])) || name.contains(':') {
continue;
}
out += name;
out += ": ";
out += value;
out += "\r\n";
}
if !self.body.is_empty() || self.method != "GET" {
out += "Content-Length: ";
out += &alloc::format!("{}", self.body.len());
out += "\r\n";
}
out += "\r\n";
let mut bytes = out.into_bytes();
bytes.extend_from_slice(self.body);
bytes
}
}
/// A response's status line and headers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Head {
pub status: u16,
pub headers: Vec<(String, String)>,
/// Whether it came over HTTP/2 ([`crate::http2`]), else HTTP/1.1.
pub http2: bool,
}
impl Head {
/// The first header of that name, any case.
pub fn header(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.find(|(n, _)| n.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_str())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
/// Not an HTTP/1 status line or header.
BadHead,
/// A chunk's size that is not hex, or a chunk not ended by CRLF.
BadChunk,
/// The server closed before the body it announced was whole.
Truncated,
/// A head larger than [`MAX_HEAD`].
TooLarge,
}
/// The longest head read.
pub const MAX_HEAD: usize = 64 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Body {
/// Before the head is whole.
Head,
Length(u64),
/// In a chunk's size line.
ChunkSize,
/// Inside a chunk, this much of it left.
Chunk(u64),
/// The CRLF after a chunk's data.
ChunkEnd,
/// The trailer after the last chunk, up to its empty line.
Trailer,
UntilClose,
Done,
}
/// A response, read from bytes as they arrive.
#[derive(Debug)]
pub struct Response {
pending: Vec<u8>,
head: Option<Head>,
state: Body,
body: Vec<u8>,
}
impl Default for Response {
fn default() -> Self {
Self::new()
}
}
impl Response {
pub fn new() -> Response {
Response {
pending: Vec::new(),
head: None,
state: Body::Head,
body: Vec::new(),
}
}
/// The status and headers, once they have all arrived.
pub fn head(&self) -> Option<&Head> {
self.head.as_ref()
}
/// Whether the whole body has arrived.
pub fn done(&self) -> bool {
self.state == Body::Done
}
/// The body that arrived since the last call, without chunk framing.
pub fn take_body(&mut self) -> Vec<u8> {
core::mem::take(&mut self.body)
}
/// The server closed the connection: the end of a body that runs until
/// then, and an error for one that announced more.
pub fn close(&mut self) -> Result<(), Error> {
match self.state {
Body::UntilClose | Body::Done => {
self.state = Body::Done;
Ok(())
}
_ => Err(Error::Truncated),
}
}
/// Takes bytes from the connection.
pub fn receive(&mut self, mut bytes: &[u8]) -> Result<(), Error> {
if self.state == Body::Head {
self.pending.extend_from_slice(bytes);
let Some(end) = self.pending.windows(4).position(|w| w == b"\r\n\r\n") else {
return match self.pending.len() > MAX_HEAD {
true => Err(Error::TooLarge),
false => Ok(()),
};
};
let head = parse_head(&self.pending[..end])?;
self.state = if (100..200).contains(&head.status) || head.status == 204 || head.status == 304 {
Body::Done
} else if head
.header("transfer-encoding")
.is_some_and(|t| t.trim().eq_ignore_ascii_case("chunked"))
{
Body::ChunkSize
} else if let Some(length) = head.header("content-length") {
match length.trim().parse::<u64>().map_err(|_| Error::BadHead)? {
0 => Body::Done,
n => Body::Length(n),
}
} else {
Body::UntilClose
};
self.head = Some(head);
let rest = self.pending.split_off(end + 4);
self.pending.clear();
return self.body_bytes(&rest);
}
if !self.pending.is_empty() {
// A chunk-size or trailer line that began in an earlier piece.
let mut joined = core::mem::take(&mut self.pending);
joined.extend_from_slice(bytes);
return self.body_bytes(&joined);
}
self.body_bytes(core::mem::take(&mut bytes))
}
fn body_bytes(&mut self, mut bytes: &[u8]) -> Result<(), Error> {
while !bytes.is_empty() {
match self.state {
Body::Head => unreachable!(),
Body::Done => return Ok(()),
Body::UntilClose => {
self.body.extend_from_slice(bytes);
return Ok(());
}
Body::Length(left) | Body::Chunk(left) => {
let n = (left as usize).min(bytes.len());
self.body.extend_from_slice(&bytes[..n]);
bytes = &bytes[n..];
let left = left - n as u64;
self.state = match (self.state, left) {
(Body::Length(_), 0) => Body::Done,
(Body::Length(_), _) => Body::Length(left),
(_, 0) => Body::ChunkEnd,
_ => Body::Chunk(left),
};
}
Body::ChunkEnd => {
if bytes.len() < 2 {
self.pending.extend_from_slice(bytes);
return Ok(());
}
if &bytes[..2] != b"\r\n" {
return Err(Error::BadChunk);
}
bytes = &bytes[2..];
self.state = Body::ChunkSize;
}
Body::ChunkSize | Body::Trailer => {
let Some(end) = bytes.windows(2).position(|w| w == b"\r\n") else {
if bytes.len() > 1024 {
return Err(Error::BadChunk);
}
self.pending.extend_from_slice(bytes);
return Ok(());
};
let line = &bytes[..end];
bytes = &bytes[end + 2..];
if self.state == Body::Trailer {
if line.is_empty() {
self.state = Body::Done;
}
continue;
}
// The size, before any extension (";name=value").
let size = line.split(|&b| b == b';').next().unwrap_or(line);
let size = core::str::from_utf8(size).map_err(|_| Error::BadChunk)?;
let size = u64::from_str_radix(size.trim(), 16).map_err(|_| Error::BadChunk)?;
self.state = if size == 0 {
Body::Trailer
} else {
Body::Chunk(size)
};
}
}
}
Ok(())
}
}
fn parse_head(bytes: &[u8]) -> Result<Head, Error> {
let text = core::str::from_utf8(bytes).map_err(|_| Error::BadHead)?;
let mut lines = text.split("\r\n");
let status_line = lines.next().ok_or(Error::BadHead)?;
let mut parts = status_line.splitn(3, ' ');
if !parts.next().is_some_and(|v| v.starts_with("HTTP/1.")) {
return Err(Error::BadHead);
}
let status = parts
.next()
.and_then(|s| s.parse().ok())
.filter(|s| (100..600).contains(s))
.ok_or(Error::BadHead)?;
let mut headers = Vec::new();
for line in lines {
let (name, value) = line.split_once(':').ok_or(Error::BadHead)?;
headers.push((String::from(name.trim()), String::from(value.trim())));
}
Ok(Head {
status,
headers,
http2: false,
})
}
/// One server-sent event.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Event {
/// The `event:` field; empty for the default, "message".
pub event: String,
/// The `data:` lines, joined by line breaks.
pub data: String,
}
/// Server-sent events (the WHATWG's `text/event-stream`), read from a body
/// as it arrives.
#[derive(Debug, Default)]
pub struct Events {
line: Vec<u8>,
current: Event,
has_data: bool,
ready: Vec<Event>,
}
impl Events {
pub fn new() -> Events {
Events::default()
}
/// Takes body bytes; whole events then come out of [`Events::take`].
pub fn receive(&mut self, bytes: &[u8]) {
for &b in bytes {
if b != b'\n' {
self.line.push(b);
continue;
}
if self.line.last() == Some(&b'\r') {
self.line.pop();
}
let line = core::mem::take(&mut self.line);
self.field(&String::from_utf8_lossy(&line));
}
}
fn field(&mut self, line: &str) {
if line.is_empty() {
// A blank line ends an event; one with no data is no event.
let event = core::mem::take(&mut self.current);
if core::mem::take(&mut self.has_data) {
self.ready.push(event);
}
return;
}
if line.starts_with(':') {
return; // a comment, as servers send to keep a connection alive
}
let (name, value) = line.split_once(':').unwrap_or((line, ""));
let value = value.strip_prefix(' ').unwrap_or(value);
match name {
"event" => self.current.event = String::from(value),
"data" => {
if self.has_data {
self.current.data.push('\n');
}
self.current.data.push_str(value);
self.has_data = true;
}
_ => {} // id, retry: one request, so nothing to resume
}
}
/// The next whole event, in the order they came.
pub fn take(&mut self) -> Option<Event> {
(!self.ready.is_empty()).then(|| self.ready.remove(0))
}
}
/// A `Date` header's time, seconds since 1970: the form every server must
/// send (RFC 9110, 5.6.7), `Sun, 29 Nov 2026 12:00:00 GMT`.
pub fn date(text: &str) -> Option<i64> {
const MONTHS: [&str; 12] = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
let mut parts = text.trim().split(' ');
let (_weekday, day, month, year, time, zone) = (
parts.next()?,
parts.next()?,
parts.next()?,
parts.next()?,
parts.next()?,
parts.next()?,
);
if zone != "GMT" || parts.next().is_some() {
return None;
}
let day: i64 = day.parse().ok()?;
let month = MONTHS.iter().position(|m| *m == month)? as i64 + 1;
let year: i64 = year.parse().ok()?;
let mut hms = time.split(':').map(|n| n.parse::<i64>().ok());
let (h, m, s) = (hms.next()??, hms.next()??, hms.next()??);
if !(1..=31).contains(&day) || h > 23 || m > 59 || s > 60 {
return None;
}
// Days from 1970 by the civil calendar (Howard Hinnant's
// days-from-civil).
let y = if month <= 2 { year - 1 } else { year };
let (era, yoe) = (y.div_euclid(400), y.rem_euclid(400));
let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1;
let days = era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468;
Some(days * 86_400 + h * 3600 + m * 60 + s)
}
#[cfg(test)]
mod tests {
extern crate std;
use super::*;
use alloc::vec;
#[test]
fn dates() {
assert_eq!(date("Sun, 29 Nov 2026 12:00:00 GMT"), Some(1_795_953_600));
assert_eq!(date("Thu, 01 Jan 1970 00:00:00 GMT"), Some(0));
assert_eq!(date("Tue, 29 Feb 2028 23:59:59 GMT"), Some(1_835_481_599));
for bad in [
"",
"Sun, 29 Nov 2026 12:00:00",
"Sun, 29 Nov 2026 12:00:00 CET",
"Sun, 29 Foo 2026 12:00:00 GMT",
"Sun, 29 Nov 2026 24:00:00 GMT",
"Sunday, 29-Nov-26 12:00:00 GMT",
] {
assert_eq!(date(bad), None, "{bad:?}");
}
}
fn read_in_pieces(bytes: &[u8], piece: usize) -> (Response, Vec<u8>) {
let mut r = Response::new();
let mut body = Vec::new();
for p in bytes.chunks(piece) {
r.receive(p).unwrap();
body.extend(r.take_body());
}
(r, body)
}
#[test]
fn a_request_has_its_head_and_body() {
let r = Request {
method: "POST",
host: "api.example",
path: "/v1/messages",
headers: &[("x-api-key", "k"), ("Evil", "a\r\nGET / HTTP/1.1"), ("a:b", "c")],
body: b"{}",
};
let text = String::from_utf8(r.encode()).unwrap();
assert_eq!(
text,
"POST /v1/messages HTTP/1.1\r\nHost: api.example\r\nUser-Agent: Pinnacle\r\n\
Connection: close\r\nx-api-key: k\r\nContent-Length: 2\r\n\r\n{}"
);
}
#[test]
fn a_body_by_length_in_any_pieces() {
let wire = b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\nX: y\r\n\r\nhelloextra";
for piece in 1..wire.len() {
let (r, body) = read_in_pieces(wire, piece);
assert!(r.done());
assert_eq!(body, b"hello");
assert_eq!(r.head().unwrap().status, 200);
assert_eq!(r.head().unwrap().header("x"), Some("y"));
}
}
#[test]
fn a_chunked_body_in_any_pieces() {
let wire = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n\
4\r\nWiki\r\n6;ext=1\r\npedia \r\nE\r\nin \r\n\r\nchunks.\r\n0\r\nT: x\r\n\r\n";
for piece in 1..wire.len() {
let (r, body) = read_in_pieces(wire, piece);
assert!(r.done(), "piece {piece}");
assert_eq!(body, b"Wikipedia in \r\n\r\nchunks.");
}
}
#[test]
fn a_body_until_close() {
let (mut r, body) = read_in_pieces(b"HTTP/1.0 404 Not Found\r\n\r\ngone", 3);
assert!(!r.done());
assert_eq!(body, b"gone");
r.close().unwrap();
assert!(r.done());
assert_eq!(r.head().unwrap().status, 404);
}
#[test]
fn short_and_bad_responses() {
let (mut r, _) = read_in_pieces(b"HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc", 4);
assert_eq!(r.close(), Err(Error::Truncated));
let mut r = Response::new();
assert_eq!(r.receive(b"SSH-2.0\r\n\r\n"), Err(Error::BadHead));
let mut r = Response::new();
assert_eq!(
r.receive(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nzz\r\n"),
Err(Error::BadChunk)
);
let mut r = Response::new();
assert_eq!(r.receive(&vec![b'a'; MAX_HEAD + 1]), Err(Error::TooLarge));
}
#[test]
fn server_sent_events() {
let stream = b": keep-alive\r\nevent: message_start\r\ndata: {\"a\":1}\r\n\r\n\
data: one\ndata: two\n\nevent: ping\n\nevent: done\ndata:\n\n";
for piece in 1..stream.len() {
let mut e = Events::new();
for p in stream.chunks(piece) {
e.receive(p);
}
let event = |event: &str, data: &str| Event {
event: event.into(),
data: data.into(),
};
assert_eq!(e.take(), Some(event("message_start", "{\"a\":1}")));
assert_eq!(e.take(), Some(event("", "one\ntwo")));
assert_eq!(e.take(), Some(event("done", "")));
assert_eq!(e.take(), None);
}
}
}