sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
//! HTTP/1 field syntax and borrow-free field state.

use core::{mem, num::NonZero};

use crate::{
    field::{
        self,
        head::{Error::Routing, Flags, Name, Qualities, headers::Known},
        scan::{self, Match},
        text::{Ascii, IntError},
    },
    h1::head::{self, Admission, line::Version, request::Fields},
    request::{self, span},
};

mod cursor;
pub mod expect;
pub mod syntax;
mod transfer;
pub mod value;

pub use cursor::Cursor;
pub use transfer::Transfer;

#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Entry<'owner> {
    name: &'owner [u8],
    value: &'owner [u8],
    name_span: span::Span,
    value_span: span::Span,
    line_span: span::Span,
}

impl<'owner> Entry<'owner> {
    /// Splits one CRLF-terminated field without validating its name or value.
    /// Admitted sections retain their grammar proof; arbitrary input returns `None`
    /// when a required delimiter is missing. The value retains its original OWS.
    pub fn split(bytes: &[u8]) -> Option<(&[u8], &[u8], &[u8])> {
        let end = Match::find(b'\r', bytes)?;
        let rest = end.suffix().strip_prefix(b"\n")?;
        let colon = Match::find(b':', end.prefix())?;
        Some((colon.prefix(), colon.suffix(), rest))
    }

    pub(crate) fn kind(&self) -> Name {
        match Name::from_h1(self.name()) {
            Some(name) => name,
            None => Name::Regular,
        }
    }

    pub fn name(&self) -> &'owner [u8] {
        self.name
    }

    pub fn value(&self) -> &'owner [u8] {
        self.value
    }

    pub const fn name_span(&self) -> span::Span {
        self.name_span
    }

    pub const fn value_span(&self) -> span::Span {
        self.value_span
    }

    pub const fn line_span(&self) -> span::Span {
        self.line_span
    }

    pub fn apply<R: request::Fields, A: Admission, const NEGOTIATE: bool>(
        self,
        raw: &mut R::RawHeaders,
        permit: &mut A,
        fields: &mut Fields,
        flags: &mut Flags,
        version: Version,
    ) -> Result<(), head::Error<R::Error, A::Error>> {
        let slot = R::slice(self.name);
        let known = Known::from_name(self.name);
        let mut encoding = None;
        if let Some(known) = known {
            let skip =
                matches!(known, Known::AcceptEncoding) && slot.is_none() && !R::FULL && !NEGOTIATE;
            if !skip {
                encoding = if R::ENCODING && matches!(known, Known::AcceptEncoding) {
                    Qualities::try_apply(&mut fields.message, flags, self.value).map(Some)
                } else {
                    known
                        .apply(fields, flags, self.value, version)
                        .map(|()| None)
                }
                .map_err(|cause| head::Error::Field {
                    start: self.line_span.start(),
                    available: self.line_span.len(),
                    cause,
                })?;
            }
            if matches!(known, Known::Host) {
                fields.routing = fields.routing.try_host(self.value_span).map_err(|cause| {
                    head::Error::Field {
                        start: self.line_span.start(),
                        available: self.line_span.len(),
                        cause: Routing(cause),
                    }
                })?;
            }
        }
        if let Some(slot) = slot {
            match encoding {
                Some(encoding) => R::set_encoding(raw, slot, self.value, self.value_span, encoding),
                None => R::set(raw, slot, self.value, self.value_span),
            }
            .map_err(head::Error::Header)?;
        }
        if A::FIELDS {
            permit
                .field(self.name, self.value, self.value_span)
                .map_err(head::Error::Admission)?;
        }
        Ok(())
    }
}

const _: () = assert!(mem::size_of::<Entry<'_>>() == 56);

pub struct Line {
    start: u32,
    raw: u32,
    end: u32,
}

impl Line {
    pub const fn start(&self) -> usize {
        self.start as usize
    }

    pub const fn wire_end(&self) -> usize {
        self.end as usize + 2
    }

    pub fn bind(self, bytes: &[u8]) -> Result<Entry<'_>, syntax::Error> {
        let start = self.start as usize;
        let raw = (self.raw - self.start) as usize;
        let end = (self.end - self.start) as usize;
        let name = bytes.get(..raw - 1).ok_or(syntax::Error::Invalid)?;
        let text = bytes.get(raw..end).ok_or(syntax::Error::Invalid)?;
        let trimmed = text.trim_ascii_start();
        let pos = self.end as usize - trimmed.len();
        let value = crate::field::Error::trim_ows(trimmed);
        Ok(Entry {
            name,
            value,
            name_span: span::Span::from_range(start..self.raw as usize - 1)
                .or(Err(syntax::Error::Invalid))?,
            value_span: span::Span::checked(pos, value.len()).or(Err(syntax::Error::Invalid))?,
            line_span: span::Span::from_range(start..self.end as usize + 2)
                .or(Err(syntax::Error::Invalid))?,
        })
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub struct End {
    fields: u32,
    wire: NonZero<u32>,
}

impl End {
    const fn new(fields: u32, wire: NonZero<u32>) -> Self {
        Self { fields, wire }
    }

    pub const fn fields(self) -> u32 {
        self.fields
    }

    pub const fn wire_len(self) -> NonZero<u32> {
        self.wire
    }
}

const _: () = {
    assert!(mem::size_of::<End>() == 8);
    assert!(mem::size_of::<Option<End>>() == 8);
};

pub enum Progress {
    Field(Line),
    More,
    End(End),
}

const _: () = assert!(mem::size_of::<Progress>() == 16);

#[derive(Clone, Copy, PartialEq, Eq)]
pub(in crate::h1) struct Limit {
    count: u32,
    line_bytes: u32,
}

impl Limit {
    pub(in crate::h1) const fn new(count: usize, line: usize) -> Self {
        Self {
            count: Self::narrow(count),
            line_bytes: Self::narrow(line),
        }
    }

    const fn narrow(value: usize) -> u32 {
        if value > u32::MAX as usize {
            u32::MAX
        } else {
            value as u32
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
    DuplicateContentLength,
    ContentLengthWithTransferEncoding,
    InvalidContentLength(IntError),
    InvalidTransferEncoding(value::Error),
}

/// Accumulated connection-option semantics shared by request and response
/// scanners. Unknown valid tokens are intentionally ignored; malformed token
/// bytes fail admission.
#[repr(transparent)]
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct Connection(u8);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TokenError {
    pub index: usize,
    pub byte: u8,
}

impl Connection {
    pub(crate) const CLOSE: Self = Self(1 << 0);
    pub(crate) const KEEP_ALIVE: Self = Self(1 << 1);
    const UPGRADE: u8 = 1 << 2;

    pub fn try_push(mut self, value: &[u8]) -> Result<Self, TokenError> {
        let mut rest = value;
        while !rest.is_empty() {
            let (token, tail) = scan::split_token(field::trim_ows_start(rest));
            if token.eq_ignore_ascii_case(b"close") {
                self.0 |= Self::CLOSE.0;
            } else if token.eq_ignore_ascii_case(b"keep-alive") {
                self.0 |= Self::KEEP_ALIVE.0;
            } else if token.eq_ignore_ascii_case(b"upgrade") {
                self.0 |= Self::UPGRADE;
            }
            let [first, ..] = tail else { break };
            match field::trim_ows_start(tail) {
                [b',', next @ ..] => rest = next,
                [] => break,
                _ => {
                    return Err(TokenError {
                        index: value.len() - tail.len(),
                        byte: *first,
                    });
                }
            }
        }
        Ok(self)
    }

    /// Merges connection options that were parsed by another scanner branch.
    #[doc(hidden)]
    pub fn append(&mut self, fields: Self) {
        self.0 |= fields.0;
    }

    pub const fn is_close(self) -> bool {
        self.0 & Self::CLOSE.0 != 0
    }

    pub const fn is_keep(self) -> bool {
        self.0 & Self::KEEP_ALIVE.0 != 0
    }

    pub const fn can_persist(self, version: Version) -> bool {
        !self.is_close() && (matches!(version, Version::Eleven) || self.is_keep())
    }

    pub const fn is_upgrade(self) -> bool {
        self.0 & Self::UPGRADE != 0
    }
}

/// Advisory persistence parameters accumulated across every `Keep-Alive`
/// field. Malformed and unknown parameters are ignored because they cannot
/// change message framing; the shortest valid timeout wins deterministically.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct KeepAlive {
    timeout: Option<u64>,
}

impl KeepAlive {
    pub(crate) fn parse(mut prior: Option<u64>, value: &[u8]) -> Option<u64> {
        for raw in value.split(|byte| *byte == b',') {
            let param = field::Error::trim_ows(raw);
            let Some(split) = param.iter().position(|byte| *byte == b'=') else {
                continue;
            };
            let name = field::Error::trim_ows(&param[..split]);
            if !name.eq_ignore_ascii_case(b"timeout") {
                continue;
            }
            let Ok(timeout) = Ascii::new(field::Error::trim_ows(&param[split + 1..])).parse_u64()
            else {
                continue;
            };
            prior = Some(prior.map_or(timeout, |current| current.min(timeout)));
        }
        prior
    }

    pub(crate) const fn new(timeout: Option<u64>) -> Self {
        Self { timeout }
    }

    pub const fn timeout_secs(self) -> Option<u64> {
        self.timeout
    }
}

const _: () = assert!(mem::size_of::<Connection>() == 1);