garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /net/src/http2.rs

raw

//! HTTP/2 (RFC 9113) as the client speaks it, with no I/O of its own:
//! requests written as frames, the server's frames read as they arrive,
//! each stream's head and body handed on as [`crate::http`] hands them on
//! for HTTP/1.1. Several requests share one connection, each its stream;
//! what goes out is held to the server's flow-control windows, and what
//! comes in is acknowledged as it arrives (it is handed on at once).
//!
//! Spoken over TLS once ALPN chose "h2"; no server push (switched off in
//! the first SETTINGS), no priorities, and HPACK's encoder adds nothing to
//! the server's table (`hpack`).

use crate::hpack;
use crate::http::Head;
use alloc::string::String;
use alloc::vec::Vec;

/// What a connection begins with, before its SETTINGS.
const PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";

const DATA: u8 = 0;
const HEADERS: u8 = 1;
const RST_STREAM: u8 = 3;
const SETTINGS: u8 = 4;
const PUSH_PROMISE: u8 = 5;
const PING: u8 = 6;
const GOAWAY: u8 = 7;
const WINDOW_UPDATE: u8 = 8;
const CONTINUATION: u8 = 9;

const END_STREAM: u8 = 0x1;
const ACK: u8 = 0x1;
const END_HEADERS: u8 = 0x4;
const PADDED: u8 = 0x8;
const PRIORITY: u8 = 0x20;

const SETTINGS_HEADER_TABLE_SIZE: u16 = 1;
const SETTINGS_ENABLE_PUSH: u16 = 2;
const SETTINGS_INITIAL_WINDOW_SIZE: u16 = 4;
const SETTINGS_MAX_FRAME_SIZE: u16 = 5;

/// Error codes (RFC 9113, 7).
pub const NO_ERROR: u32 = 0;
pub const PROTOCOL_ERROR: u32 = 1;
pub const FLOW_CONTROL_ERROR: u32 = 3;
pub const FRAME_SIZE_ERROR: u32 = 6;
pub const REFUSED_STREAM: u32 = 7;
pub const COMPRESSION_ERROR: u32 = 9;

/// The largest frame either side sends before the other says more: the
/// protocol's default, which this client keeps for what it receives.
const DEFAULT_FRAME: usize = 16_384;
/// The window a new stream starts with, by the protocol.
const DEFAULT_WINDOW: i64 = 65_535;
/// What this client lets the server send ahead, a stream and in all: it
/// hands bytes on as they arrive, so it need not hold the server back.
const STREAM_WINDOW: i64 = 1 << 20;
const CONNECTION_WINDOW: i64 = 1 << 24;
/// The largest window the protocol allows.
const MAX_WINDOW: i64 = (1 << 31) - 1;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
    /// The server broke the protocol (the code sent it on GOAWAY).
    Protocol(&'static str),
    Compression(hpack::Error),
    /// The server reset the stream, with this code.
    Reset(u32),
    /// The server is closing the connection, and this stream was not
    /// taken (REFUSED: it may be asked again elsewhere), or the
    /// connection ended with this code.
    GoAway(u32),
    /// The connection ended before the response was whole.
    Truncated,
}

struct Stream {
    id: u32,
    head: Option<Head>,
    body: Vec<u8>,
    /// The server sent END_STREAM.
    ended: bool,
    error: Option<Error>,
    /// The request's body not yet sent, and whether END_STREAM follows it.
    unsent: Vec<u8>,
    finish: bool,
    /// What may still be sent on it, and received before acknowledging.
    send_window: i64,
    received: i64,
}

/// One HTTP/2 connection, as the client.
pub struct Connection {
    out: Vec<u8>,
    pending: Vec<u8>,
    decoder: hpack::Decoder,
    streams: Vec<Stream>,
    next_id: u32,
    /// The server's frame limit and new streams' window.
    max_frame: usize,
    initial_window: i64,
    send_window: i64,
    /// Received on the connection since it was last acknowledged.
    received: i64,
    /// A header block arriving in pieces: its stream, so far, END_STREAM.
    continuation: Option<(u32, Vec<u8>, bool)>,
    /// The last stream the server said it will answer, after GOAWAY.
    going_away: Option<u32>,
    error: Option<Error>,
}

impl Default for Connection {
    fn default() -> Self {
        Self::new()
    }
}

impl Connection {
    /// A connection: its preface and SETTINGS queued to send first.
    pub fn new() -> Connection {
        let mut c = Connection {
            out: PREFACE.to_vec(),
            pending: Vec::new(),
            decoder: hpack::Decoder::new(),
            streams: Vec::new(),
            next_id: 1,
            max_frame: DEFAULT_FRAME,
            initial_window: DEFAULT_WINDOW,
            send_window: DEFAULT_WINDOW,
            received: 0,
            continuation: None,
            going_away: None,
            error: None,
        };
        let mut settings = Vec::new();
        for (id, value) in [
            (SETTINGS_ENABLE_PUSH, 0),
            (SETTINGS_INITIAL_WINDOW_SIZE, STREAM_WINDOW as u32),
        ] {
            settings.extend_from_slice(&id.to_be_bytes());
            settings.extend_from_slice(&value.to_be_bytes());
        }
        c.frame(SETTINGS, 0, 0, &settings);
        c.window_update(0, (CONNECTION_WINDOW - DEFAULT_WINDOW) as u32);
        c
    }

    /// Sends a request on a new stream, and returns the stream. `scheme`
    /// is "https" (or "http"), `authority` the host and any port. Headers
    /// HTTP/2 does not carry (`Connection`, `Host`, …) are left out, as are
    /// ones with a line break, as [`crate::http::Request::encode`] leaves
    /// them out.
    pub fn request(
        &mut self,
        method: &str,
        scheme: &str,
        authority: &str,
        path: &str,
        headers: &[(&str, &str)],
        body: &[u8],
    ) -> u32 {
        let id = self.next_id;
        self.next_id += 2;
        // Header names are lower-case in HTTP/2.
        let mut kept: Vec<(String, &str)> = Vec::new();
        for &(name, value) in headers {
            let lower = name.to_ascii_lowercase();
            let dropped = matches!(
                lower.as_str(),
                "connection" | "host" | "keep-alive" | "proxy-connection" | "transfer-encoding" | "upgrade"
            ) || (lower == "te" && !value.eq_ignore_ascii_case("trailers"))
                || name.is_empty()
                || name.contains([':', '\r', '\n'])
                || value.contains(['\r', '\n']);
            if !dropped {
                kept.push((lower, value));
            }
        }
        let has = |name: &str| kept.iter().any(|(n, _)| n == name);
        let length = alloc::format!("{}", body.len());
        let mut fields: Vec<(&str, &str)> = alloc::vec![
            (":method", method),
            (":scheme", scheme),
            (":authority", authority),
            (":path", path),
        ];
        if !has("user-agent") {
            fields.push(("user-agent", "Pinnacle"));
        }
        if (!body.is_empty() || method != "GET") && !has("content-length") {
            fields.push(("content-length", &length));
        }
        fields.extend(kept.iter().map(|(n, v)| (n.as_str(), *v)));
        let block = hpack::encode(&fields);
        let finish = body.is_empty();
        // The block in frames no larger than the server takes.
        let mut pieces = block.chunks(self.max_frame).peekable();
        let mut kind = HEADERS;
        while let Some(piece) = pieces.next() {
            let last = pieces.peek().is_none();
            let mut flags = if last { END_HEADERS } else { 0 };
            if kind == HEADERS && finish {
                flags |= END_STREAM;
            }
            self.frame(kind, flags, id, piece);
            kind = CONTINUATION;
        }
        self.streams.push(Stream {
            id,
            head: None,
            body: Vec::new(),
            ended: false,
            error: None,
            unsent: body.to_vec(),
            finish: !finish,
            send_window: self.initial_window,
            received: 0,
        });
        self.flush();
        id
    }

    /// What to send to the server, since the last call.
    pub fn take_output(&mut self) -> Vec<u8> {
        core::mem::take(&mut self.out)
    }

    /// The response's status and headers, once they have arrived.
    pub fn head(&self, stream: u32) -> Option<&Head> {
        self.stream(stream)?.head.as_ref()
    }

    /// The body that arrived on `stream` since the last call.
    pub fn take_body(&mut self, stream: u32) -> Vec<u8> {
        match self.streams.iter_mut().find(|s| s.id == stream) {
            Some(s) => core::mem::take(&mut s.body),
            None => Vec::new(),
        }
    }

    /// Whether the response on `stream` is whole, or will never be (see
    /// [`Connection::result`]).
    pub fn done(&self, stream: u32) -> bool {
        self.error.is_some() || self.stream(stream).is_none_or(|s| s.ended || s.error.is_some())
    }

    /// How `stream` went: `Ok` once whole, its error if it failed.
    pub fn result(&self, stream: u32) -> Result<(), Error> {
        let s = self.stream(stream).ok_or(Error::Protocol("no such stream"))?;
        match (s.error, self.error) {
            (Some(e), _) if !s.ended => Err(e),
            (_, Some(e)) if !s.ended => Err(e),
            _ => Ok(()),
        }
    }

    /// Forgets a stream whose response was taken.
    pub fn forget(&mut self, stream: u32) {
        self.streams.retain(|s| s.id != stream);
    }

    /// The server closed the connection: every response not yet whole is
    /// cut short.
    pub fn close(&mut self) {
        if self.error.is_none() {
            self.error = Some(Error::Truncated);
        }
    }

    /// Bytes from the server, as they arrive. An error is the connection's
    /// (a GOAWAY with its code is queued to send); a stream's own error
    /// shows in [`Connection::result`].
    pub fn receive(&mut self, bytes: &[u8]) -> Result<(), Error> {
        if let Some(e) = self.error {
            return Err(e);
        }
        self.pending.extend_from_slice(bytes);
        let mut at = 0;
        while self.pending.len() - at >= 9 {
            let h = &self.pending[at..at + 9];
            let len = (usize::from(h[0]) << 16) | (usize::from(h[1]) << 8) | usize::from(h[2]);
            let (kind, flags) = (h[3], h[4]);
            let stream = u32::from_be_bytes([h[5], h[6], h[7], h[8]]) & 0x7fff_ffff;
            if len > DEFAULT_FRAME {
                return self.fail(FRAME_SIZE_ERROR, Error::Protocol("a frame larger than allowed"));
            }
            if self.pending.len() - at < 9 + len {
                break;
            }
            let payload = self.pending[at + 9..at + 9 + len].to_vec();
            at += 9 + len;
            if let Err(e) = self.frame_received(kind, flags, stream, &payload) {
                self.pending.clear();
                return Err(e);
            }
        }
        self.pending.drain(..at);
        self.flush();
        Ok(())
    }

    fn frame_received(&mut self, kind: u8, flags: u8, stream: u32, p: &[u8]) -> Result<(), Error> {
        if let Some((waiting, ..)) = self.continuation
            && (kind != CONTINUATION || stream != waiting)
        {
            return self.fail(PROTOCOL_ERROR, Error::Protocol("a frame inside a header block"));
        }
        match kind {
            DATA => {
                if stream == 0 {
                    return self.fail(PROTOCOL_ERROR, Error::Protocol("DATA on stream 0"));
                }
                let data = unpadded(flags, p).ok_or(Error::Protocol("bad padding"));
                let Ok(data) = data else {
                    return self.fail(PROTOCOL_ERROR, Error::Protocol("bad padding"));
                };
                // The whole frame counts against the windows, padding too.
                self.received += p.len() as i64;
                if self.received > CONNECTION_WINDOW {
                    return self.fail(
                        FLOW_CONTROL_ERROR,
                        Error::Protocol("past the connection's window"),
                    );
                }
                let mut reset = None;
                if let Some(s) = self.streams.iter_mut().find(|s| s.id == stream) {
                    s.received += p.len() as i64;
                    if s.received > STREAM_WINDOW {
                        reset = Some(FLOW_CONTROL_ERROR);
                    } else if !s.ended && s.head.is_some() {
                        s.body.extend_from_slice(data);
                        s.ended = flags & END_STREAM != 0;
                    }
                }
                if let Some(code) = reset {
                    self.reset(stream, code, Error::Protocol("past a stream's window"));
                }
                self.acknowledge(stream);
            }
            HEADERS => {
                let Some(mut block) = unpadded(flags, p) else {
                    return self.fail(PROTOCOL_ERROR, Error::Protocol("bad padding"));
                };
                if flags & PRIORITY != 0 {
                    let Some(rest) = block.get(5..) else {
                        return self.fail(PROTOCOL_ERROR, Error::Protocol("a short HEADERS"));
                    };
                    block = rest;
                }
                let end_stream = flags & END_STREAM != 0;
                if flags & END_HEADERS != 0 {
                    return self.headers(stream, block, end_stream);
                }
                self.continuation = Some((stream, block.to_vec(), end_stream));
            }
            CONTINUATION => {
                let Some((stream, mut block, end_stream)) = self.continuation.take() else {
                    return self.fail(PROTOCOL_ERROR, Error::Protocol("CONTINUATION out of place"));
                };
                block.extend_from_slice(p);
                if block.len() > hpack::MAX_LIST {
                    return self.fail(PROTOCOL_ERROR, Error::Protocol("a header block too large"));
                }
                if flags & END_HEADERS != 0 {
                    return self.headers(stream, &block, end_stream);
                }
                self.continuation = Some((stream, block, end_stream));
            }
            RST_STREAM if p.len() == 4 => {
                let code = u32::from_be_bytes(p.try_into().unwrap());
                if let Some(s) = self.streams.iter_mut().find(|s| s.id == stream) {
                    // NO_ERROR after the whole response: the server needs
                    // no more of the request.
                    if !(code == NO_ERROR && s.ended) {
                        s.error = Some(Error::Reset(code));
                    }
                    s.unsent.clear();
                    s.finish = false;
                }
            }
            SETTINGS if flags & ACK == 0 => {
                if stream != 0 || !p.len().is_multiple_of(6) {
                    return self.fail(FRAME_SIZE_ERROR, Error::Protocol("a malformed SETTINGS"));
                }
                for setting in p.chunks(6) {
                    let id = u16::from_be_bytes([setting[0], setting[1]]);
                    let value = u32::from_be_bytes(setting[2..6].try_into().unwrap());
                    match id {
                        SETTINGS_INITIAL_WINDOW_SIZE => {
                            if i64::from(value) > MAX_WINDOW {
                                return self.fail(FLOW_CONTROL_ERROR, Error::Protocol("a window too large"));
                            }
                            let delta = i64::from(value) - self.initial_window;
                            self.initial_window = i64::from(value);
                            for s in &mut self.streams {
                                s.send_window += delta;
                            }
                        }
                        SETTINGS_MAX_FRAME_SIZE => {
                            if !(16_384..=16_777_215).contains(&value) {
                                return self
                                    .fail(PROTOCOL_ERROR, Error::Protocol("a frame size out of range"));
                            }
                            self.max_frame = value as usize;
                        }
                        // The encoder keeps no table: any size suits it.
                        SETTINGS_HEADER_TABLE_SIZE => {}
                        _ => {}
                    }
                }
                self.frame(SETTINGS, ACK, 0, &[]);
            }
            PING if flags & ACK == 0 && p.len() == 8 => self.frame(PING, ACK, 0, p),
            GOAWAY if p.len() >= 8 => {
                let last = u32::from_be_bytes(p[..4].try_into().unwrap()) & 0x7fff_ffff;
                let code = u32::from_be_bytes(p[4..8].try_into().unwrap());
                self.going_away = Some(last);
                for s in &mut self.streams {
                    if s.id > last && s.error.is_none() {
                        s.error = Some(Error::GoAway(REFUSED_STREAM));
                    } else if code != NO_ERROR && !s.ended && s.error.is_none() {
                        s.error = Some(Error::GoAway(code));
                    }
                }
            }
            WINDOW_UPDATE if p.len() == 4 => {
                let increment = i64::from(u32::from_be_bytes(p.try_into().unwrap()) & 0x7fff_ffff);
                if stream == 0 {
                    self.send_window += increment;
                    if self.send_window > MAX_WINDOW {
                        return self.fail(FLOW_CONTROL_ERROR, Error::Protocol("a window past 2^31"));
                    }
                } else if let Some(s) = self.streams.iter_mut().find(|s| s.id == stream) {
                    s.send_window += increment;
                    if s.send_window > MAX_WINDOW {
                        self.reset(stream, FLOW_CONTROL_ERROR, Error::Protocol("a window past 2^31"));
                    }
                }
            }
            PUSH_PROMISE => {
                return self.fail(PROTOCOL_ERROR, Error::Protocol("a push, which was switched off"));
            }
            // PRIORITY, SETTINGS acknowledgements, PING answers, and kinds
            // this client does not know, which it must ignore.
            _ => {}
        }
        Ok(())
    }

    /// A whole header block for `stream`: the response's head, an
    /// informational one (1xx) passed over, or trailers.
    fn headers(&mut self, stream: u32, block: &[u8], end_stream: bool) -> Result<(), Error> {
        // Decoded whatever the stream, or the tables would disagree.
        let fields = match self.decoder.decode(block) {
            Ok(f) => f,
            Err(e) => return self.fail(COMPRESSION_ERROR, Error::Compression(e)),
        };
        let Some(s) = self.streams.iter_mut().find(|s| s.id == stream) else {
            return Ok(());
        };
        if s.head.is_none() {
            let status = fields
                .iter()
                .find(|(n, _)| n == ":status")
                .and_then(|(_, v)| v.parse::<u16>().ok());
            let Some(status) = status else {
                self.reset(
                    stream,
                    PROTOCOL_ERROR,
                    Error::Protocol("a response with no :status"),
                );
                return Ok(());
            };
            if (100..200).contains(&status) {
                return Ok(());
            }
            let headers = fields.into_iter().filter(|(n, _)| !n.starts_with(':')).collect();
            s.head = Some(Head {
                status,
                headers,
                http2: true,
            });
        }
        // Trailers add nothing a program reads.
        if end_stream {
            s.ended = true;
        }
        Ok(())
    }

    /// Lets the server send as much again as arrived, once half a window
    /// has: on the connection, and on `stream` while it is open.
    fn acknowledge(&mut self, stream: u32) {
        if self.received >= CONNECTION_WINDOW / 2 {
            let n = core::mem::take(&mut self.received);
            self.window_update(0, n as u32);
        }
        let due = self.streams.iter_mut().find(|s| s.id == stream).and_then(|s| {
            (s.received >= STREAM_WINDOW / 2 && !s.ended && s.error.is_none())
                .then(|| core::mem::take(&mut s.received))
        });
        if let Some(n) = due {
            self.window_update(stream, n as u32);
        }
    }

    /// Sends what the windows let go of each request's body.
    fn flush(&mut self) {
        let mut frames = Vec::new();
        for s in &mut self.streams {
            loop {
                let room = s.send_window.min(self.send_window).max(0) as usize;
                let n = s.unsent.len().min(room).min(self.max_frame);
                if n == 0 && !(s.unsent.is_empty() && s.finish) {
                    break;
                }
                let piece: Vec<u8> = s.unsent.drain(..n).collect();
                s.send_window -= n as i64;
                self.send_window -= n as i64;
                let last = s.unsent.is_empty() && s.finish;
                if last {
                    s.finish = false;
                }
                frames.push((s.id, if last { END_STREAM } else { 0 }, piece));
                if last {
                    break;
                }
            }
        }
        for (id, flags, piece) in frames {
            self.frame(DATA, flags, id, &piece);
        }
    }

    fn reset(&mut self, stream: u32, code: u32, error: Error) {
        if let Some(s) = self.streams.iter_mut().find(|s| s.id == stream) {
            s.error = Some(error);
            s.unsent.clear();
            s.finish = false;
        }
        self.frame(RST_STREAM, 0, stream, &code.to_be_bytes());
    }

    /// Ends the connection for a protocol error: GOAWAY with its code.
    fn fail(&mut self, code: u32, error: Error) -> Result<(), Error> {
        let last = self.streams.iter().map(|s| s.id).max().unwrap_or(0);
        let mut p = last.to_be_bytes().to_vec();
        p.extend_from_slice(&code.to_be_bytes());
        self.frame(GOAWAY, 0, 0, &p);
        self.error = Some(error);
        Err(error)
    }

    fn window_update(&mut self, stream: u32, increment: u32) {
        self.frame(WINDOW_UPDATE, 0, stream, &increment.to_be_bytes());
    }

    fn frame(&mut self, kind: u8, flags: u8, stream: u32, payload: &[u8]) {
        let len = payload.len() as u32;
        self.out.extend_from_slice(&len.to_be_bytes()[1..]);
        self.out.push(kind);
        self.out.push(flags);
        self.out.extend_from_slice(&stream.to_be_bytes());
        self.out.extend_from_slice(payload);
    }

    fn stream(&self, id: u32) -> Option<&Stream> {
        self.streams.iter().find(|s| s.id == id)
    }
}

/// A DATA or HEADERS payload without its padding.
fn unpadded(flags: u8, p: &[u8]) -> Option<&[u8]> {
    if flags & PADDED == 0 {
        return Some(p);
    }
    let (&pad, rest) = p.split_first()?;
    rest.len().checked_sub(usize::from(pad)).map(|end| &rest[..end])
}

#[cfg(test)]
mod tests;