sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
//! Parsing and state updates for HTTP headers with protocol-level semantics.

use core::mem;

use crate::{
    field::{
        head::{Error, Flags, Name},
        scan::{Bytes, Outcome},
        text::{Ascii, IntError},
        trim_ows_start,
    },
    h1::{
        field,
        head::{line::Version, request},
        target,
    },
    uri,
};

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Known {
    AcceptEncoding,
    ContentLength,
    TransferEncoding,
    Expect,
    Host,
    Connection,
    Upgrade,
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Bounds {
    tail: usize,
    start: usize,
    end: usize,
}

impl Bounds {
    const fn new(tail: usize, start: usize, end: usize) -> Self {
        Self { tail, start, end }
    }

    fn literal<const N: usize>(raw: &[u8], expected: &[u8; N]) -> Option<Self> {
        let start = usize::from(raw.first() == Some(&b' '));
        let end = start + N;
        if raw.len() < end + 2
            || !raw[start..end].eq_ignore_ascii_case(expected)
            || raw[end] != b'\r'
            || raw[end + 1] != b'\n'
        {
            return None;
        }
        Some(Self::new(end, start, end))
    }

    pub(super) fn trim(raw: &[u8]) -> Result<Option<Self>, Error> {
        let rest = trim_ows_start(raw);
        let start = raw.len() - rest.len();
        Self::suffix(rest, start, start)
    }

    fn suffix(rest: &[u8], start: usize, base: usize) -> Result<Option<Self>, Error> {
        let cr = match Bytes::new(rest).value(0) {
            Outcome::Found(cr) => cr,
            Outcome::Partial => return Ok(None),
            Outcome::Invalid { .. } => return Err(Error::Value),
        };
        let mut end = cr;
        while end > 0 && matches!(rest.get(end - 1), Some(b' ' | b'\t')) {
            end -= 1;
        }
        Ok(Some(Self::new(base + cr, start, base + end)))
    }

    pub const fn tail(self) -> usize {
        self.tail
    }

    pub const fn start(self) -> usize {
        self.start
    }

    pub const fn end(self) -> usize {
        self.end
    }

    pub(super) fn value(self, raw: &[u8]) -> &[u8] {
        // SAFETY: private parser continuations use the same immutable raw that
        // just produced these bounds. No caller substitutes another source.
        unsafe { raw.get_unchecked(self.start..self.end) }
    }
}

const _: () = {
    assert!(mem::size_of::<Bounds>() == 3 * mem::size_of::<usize>());
    assert!(mem::size_of::<Option<Bounds>>() == 4 * mem::size_of::<usize>());
    assert!(!mem::needs_drop::<Bounds>());
};

fn parse_connection(raw: &[u8]) -> Result<field::Connection, Error> {
    field::Connection::default()
        .try_push(raw)
        .map_err(Error::Connection)
}

impl Known {
    pub fn from_name(name: &[u8]) -> Option<Self> {
        Self::from_kind(Name::from_h1(name)?)
    }

    /// Recognizes a complete canonical field name and its following colon.
    /// The exact literal match also establishes the name's token grammar.
    pub fn from_prefix(raw: &[u8]) -> Option<(Self, usize)> {
        match raw.first()?.to_ascii_lowercase() {
            b'h' => Self::Host.prefix(raw, Name::Host.wire()),
            b'c' => match raw.get(3)?.to_ascii_lowercase() {
                b'n' => Self::Connection.prefix(raw, Name::Connection.wire()),
                b't' => Self::ContentLength.prefix(raw, Name::ContentLength.wire()),
                _ => None,
            },
            b't' => Self::TransferEncoding.prefix(raw, Name::TransferEncoding.wire()),
            b'e' => Self::Expect.prefix(raw, Name::Expect.wire()),
            b'a' => Self::AcceptEncoding.prefix(raw, Name::AcceptEncoding.wire()),
            b'u' => Self::Upgrade.prefix(raw, Name::Upgrade.wire()),
            _ => None,
        }
    }

    fn prefix(self, raw: &[u8], wire: &[u8]) -> Option<(Self, usize)> {
        let len = wire.len();
        (raw.get(len) == Some(&b':') && raw[..len].eq_ignore_ascii_case(wire))
            .then_some((self, len))
    }

    fn from_kind(name: Name) -> Option<Self> {
        match name {
            Name::AcceptEncoding => Some(Self::AcceptEncoding),
            Name::ContentLength => Some(Self::ContentLength),
            Name::TransferEncoding => Some(Self::TransferEncoding),
            Name::Expect => Some(Self::Expect),
            Name::Host => Some(Self::Host),
            Name::Connection => Some(Self::Connection),
            Name::Upgrade => Some(Self::Upgrade),
            Name::Invalid
            | Name::Method
            | Name::Scheme
            | Name::Path
            | Name::Status
            | Name::Authority
            | Name::Protocol
            | Name::Te
            | Name::KeepAlive
            | Name::ProxyConnection
            | Name::Regular => None,
        }
    }

    pub fn apply(
        self,
        scan: &mut request::Fields,
        flags: &mut Flags,
        value: &[u8],
        version: Version,
    ) -> Result<(), Error> {
        match self {
            Self::AcceptEncoding => flags.try_apply(&mut scan.message, value),
            Self::ContentLength => {
                let len = Ascii::new(crate::field::Error::trim_ows(value))
                    .parse_usize()
                    .map_err(Error::ContentLength)?;
                scan.message = scan.message.try_length(len).map_err(Error::Message)?;
                Ok(())
            }
            Self::TransferEncoding => {
                let parsed = field::Transfer::default()
                    .parse(value)
                    .map_err(Error::TransferEncoding)?;
                scan.message = scan.message.try_append(parsed).map_err(Error::Message)?;
                Ok(())
            }
            Self::Expect => {
                scan.message = scan.message.with_expect(value);
                Ok(())
            }
            Self::Host => {
                scan.routing.authority = scan
                    .routing
                    .authority
                    .try_host(value)
                    .map_err(Error::Host)?;
                Ok(())
            }
            Self::Connection => {
                let value = parse_connection(value)?;
                scan.routing.connection.append(value);
                Ok(())
            }
            Self::Upgrade => {
                scan.routing = scan
                    .routing
                    .try_upgrade(value, version)
                    .map_err(Error::Upgrade)?;
                Ok(())
            }
        }
    }

    pub fn scan_line(
        self,
        scan: &mut request::Fields,
        flags: &mut Flags,
        raw: &[u8],
        version: Version,
    ) -> Result<Option<Bounds>, Error> {
        match self {
            Self::AcceptEncoding => {
                let bounds = Bounds::trim(raw)?;
                if let Some(bounds) = bounds {
                    flags.try_apply(&mut scan.message, bounds.value(raw))?;
                }
                Ok(bounds)
            }
            Self::Upgrade => {
                let bounds = Bounds::trim(raw)?;
                if let Some(bounds) = bounds {
                    scan.routing = scan
                        .routing
                        .try_upgrade(bounds.value(raw), version)
                        .map_err(Error::Upgrade)?;
                }
                Ok(bounds)
            }
            Self::ContentLength => {
                let rest = trim_ows_start(raw);
                if rest.is_empty() {
                    return Ok(None);
                }
                let start = raw.len() - rest.len();
                let (value, len) = Ascii::new(rest)
                    .parse_prefix()
                    .map_err(Error::ContentLength)?;
                // SAFETY: parse_prefix counted only digits in this immutable suffix.
                let tail = trim_ows_start(unsafe { rest.get_unchecked(len..) });
                match tail {
                    [b'\r', b'\n', ..] => {
                        scan.message = scan.message.try_length(value).map_err(Error::Message)?;
                        Ok(Some(Bounds::new(
                            raw.len() - tail.len(),
                            start,
                            start + len,
                        )))
                    }
                    [] | [b'\r'] => Ok(None),
                    _ => Err(Error::ContentLength(IntError::InvalidByte)),
                }
            }
            Self::TransferEncoding => {
                let (bounds, message) = match Bounds::literal(raw, b"chunked") {
                    Some(bounds) => (bounds, scan.message.try_append(field::Transfer::CHUNKED)),
                    None => {
                        let Some(bounds) = Bounds::trim(raw)? else {
                            return Ok(None);
                        };
                        (bounds, scan.message.try_coding(bounds.value(raw)))
                    }
                };
                scan.message = message.map_err(Error::Message)?;
                Ok(Some(bounds))
            }
            Self::Expect => expect_line(scan, raw),
            Self::Host => host_line(&mut scan.routing.authority, raw),
            Self::Connection => conn_line(scan, raw),
        }
    }
}

fn host_line(state: &mut target::Request, raw: &[u8]) -> Result<Option<Bounds>, Error> {
    let value = trim_ows_start(raw);
    let mut rest = value.iter();
    let port = uri::registered::<true>(&mut rest);
    let rest = rest.as_slice();
    let start = raw.len() - value.len();
    let end = raw.len() - rest.len();
    let bounds = if rest.starts_with(b"\r\n") {
        Bounds::new(end, start, end)
    } else {
        let Some(bounds) = Bounds::suffix(rest, start, end)? else {
            return Ok(None);
        };
        bounds
    };
    let host = if bounds.end == end {
        if start == end {
            target::Host::Empty
        } else {
            target::Host::Authority
        }
    } else if value.starts_with(b"[") {
        target::Host::parse_trimmed(bounds.value(raw))
            .map_err(|e| Error::Host(target::HostError::Authority(e)))?
    } else {
        let cause =
            uri::registered_error(port.is_some(), rest.iter().copied().take(bounds.end - end));
        return Err(Error::Host(target::HostError::Authority(cause)));
    };
    *state = state.with_host(host).map_err(Error::Host)?;
    Ok(Some(bounds))
}

fn expect_line(scan: &mut request::Fields, raw: &[u8]) -> Result<Option<Bounds>, Error> {
    let (bounds, value) = match Bounds::literal(raw, b"100-continue") {
        Some(bounds) => (bounds, b"100-continue".as_slice()),
        None => {
            let Some(bounds) = Bounds::trim(raw)? else {
                return Ok(None);
            };
            (bounds, bounds.value(raw))
        }
    };
    scan.message = scan.message.with_expect(value);
    Ok(Some(bounds))
}

fn conn_line(scan: &mut request::Fields, raw: &[u8]) -> Result<Option<Bounds>, Error> {
    let (value, bounds) = if let Some(bounds) = Bounds::literal(raw, b"keep-alive") {
        (field::Connection::KEEP_ALIVE, bounds)
    } else if let Some(bounds) = Bounds::literal(raw, b"close") {
        (field::Connection::CLOSE, bounds)
    } else {
        let Some(bounds) = Bounds::trim(raw)? else {
            return Ok(None);
        };
        let value = parse_connection(bounds.value(raw))?;
        (value, bounds)
    };
    scan.routing.connection.append(value);
    Ok(Some(bounds))
}