sark-http 0.40.0

HTTP wire types, semantics, codecs, and ownership invariants for Sark
Documentation
pub mod headers;
pub(super) mod known;

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

use crate::{
    field::text::IntError,
    h1::{
        field::{self, TokenError, value},
        head::request::{Coding, Message},
        switch, target,
    },
};

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Error {
    Value,
    Connection(TokenError),
    ContentLength(IntError),
    TransferEncoding(value::Error),
    Host(target::HostError),
    Message(field::Error),
    Routing(target::Invalid),
    Upgrade(switch::UpgradeError),
}

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

#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct Flags(u16);

impl Flags {
    const GZIP_SEEN: u16 = 1 << 3;
    const IDENTITY_SEEN: u16 = 1 << 4;
    const GZIP_EXCLUDED: u16 = 1 << 5;
    const WILDCARD_ALLOWED: u16 = 1 << 6;
    const WILDCARD_EXCLUDED: u16 = 1 << 7;
    const IDENTITY_EXCLUDED: u16 = 1 << 8;

    fn is_set(self, bit: u16) -> bool {
        (self.0 & bit) != 0
    }

    fn set(&mut self, bit: u16) {
        self.0 |= bit;
    }

    /// Accumulates supported coding admission across all field lines. An explicit
    /// gzip member overrides the wildcard, and an explicit zero remains excluded.
    fn try_apply(&mut self, message: &mut Message, raw: &[u8]) -> Result<(), Error> {
        let (next, []) = Qualities::scan::<0>(raw)?;
        message.set_coding(self.append(next));
        Ok(())
    }

    fn append(&mut self, next: Self) -> Coding {
        self.0 |= next.0;
        let gzip = if self.is_set(Self::GZIP_SEEN) {
            !self.is_set(Self::GZIP_EXCLUDED)
        } else {
            self.is_set(Self::WILDCARD_ALLOWED) && !self.is_set(Self::WILDCARD_EXCLUDED)
        };
        let identity = if self.is_set(Self::IDENTITY_SEEN) {
            !self.is_set(Self::IDENTITY_EXCLUDED)
        } else {
            !self.is_set(Self::WILDCARD_EXCLUDED)
        };
        Coding::from_flags(identity, gzip)
    }
}

#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Name {
    Invalid,
    Method,
    Scheme,
    Path,
    Status,
    Authority,
    Protocol,
    Host,
    Connection,
    ContentLength,
    TransferEncoding,
    Expect,
    AcceptEncoding,
    Te,
    KeepAlive,
    ProxyConnection,
    Upgrade,
    Regular,
}

impl Name {
    pub const H1: [Self; 7] = [
        Self::Host,
        Self::Connection,
        Self::ContentLength,
        Self::TransferEncoding,
        Self::Expect,
        Self::AcceptEncoding,
        Self::Upgrade,
    ];

    pub const fn wire(&self) -> &[u8] {
        match self {
            Self::Method => b":method",
            Self::Scheme => b":scheme",
            Self::Path => b":path",
            Self::Status => b":status",
            Self::Authority => b":authority",
            Self::Protocol => b":protocol",
            Self::Host => known::HOST.as_bytes(),
            Self::Connection => known::CONNECTION.as_bytes(),
            Self::ContentLength => known::CONTENT_LENGTH.as_bytes(),
            Self::TransferEncoding => known::TRANSFER_ENCODING.as_bytes(),
            Self::Expect => known::EXPECT.as_bytes(),
            Self::AcceptEncoding => known::ACCEPT_ENCODING.as_bytes(),
            Self::Te => known::TE.as_bytes(),
            Self::KeepAlive => known::KEEP_ALIVE.as_bytes(),
            Self::ProxyConnection => known::PROXY_CONNECTION.as_bytes(),
            Self::Upgrade => known::UPGRADE.as_bytes(),
            Self::Invalid | Self::Regular => b"",
        }
    }

    pub const fn is_required(self) -> bool {
        matches!(
            self,
            Self::Host
                | Self::Connection
                | Self::ContentLength
                | Self::TransferEncoding
                | Self::Expect
                | Self::Upgrade
        )
    }

    pub fn from_h1(name: &[u8]) -> Option<Self> {
        let known = match name.len() {
            4 => Self::Host,
            6 => Self::Expect,
            7 => Self::Upgrade,
            10 if name.first()?.eq_ignore_ascii_case(&b'k') => Self::KeepAlive,
            10 => Self::Connection,
            14 => Self::ContentLength,
            15 => Self::AcceptEncoding,
            17 => Self::TransferEncoding,
            _ => return None,
        };
        name.eq_ignore_ascii_case(known.wire()).then_some(known)
    }
}

pub const MAX_HEADER_LINE_BYTES: usize = 8 * 1024;

const GZIP: usize = 0;
const BR: usize = 1;
const IDENTITY: usize = 2;
const WILDCARD: usize = 3;

/// Coding qualities use 0..=1000; repeated explicit qualities use their minimum.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Qualities([NonZero<u16>; 4]);

impl Default for Qualities {
    fn default() -> Self {
        Self([NonZero::<u16>::MAX; 4])
    }
}

impl Qualities {
    pub fn try_parse(raw: &[u8]) -> Result<Self, Error> {
        let (_, values) = Self::scan::<4>(raw)?;
        Ok(Self(values))
    }

    pub(crate) fn try_apply(
        message: &mut Message,
        flags: &mut Flags,
        raw: &[u8],
    ) -> Result<Self, Error> {
        let (next, values) = Self::scan::<4>(raw)?;
        message.set_coding(flags.append(next));
        Ok(Self(values))
    }

    pub(crate) fn scan_line(
        message: &mut Message,
        flags: &mut Flags,
        raw: &[u8],
    ) -> Result<Option<(Bounds, Self)>, Error> {
        let Some(bounds) = Bounds::trim(raw)? else {
            return Ok(None);
        };
        let encoding = Self::try_apply(message, flags, bounds.value(raw))?;
        Ok(Some((bounds, encoding)))
    }

    pub fn append(&mut self, other: Self) {
        for (target, value) in self.0.iter_mut().zip(other.0) {
            *target = (*target).min(value);
        }
    }

    pub fn gzip(self) -> u16 {
        Self::resolve(self.0[GZIP], self.0[WILDCARD])
    }

    pub fn br(self) -> u16 {
        Self::resolve(self.0[BR], self.0[WILDCARD])
    }

    fn resolve(value: NonZero<u16>, wildcard: NonZero<u16>) -> u16 {
        match value {
            value if value != NonZero::<u16>::MAX => value.get() - 1,
            _ if wildcard != NonZero::<u16>::MAX => wildcard.get() - 1,
            _ => 0,
        }
    }

    pub fn identity(self) -> u16 {
        match self.0[IDENTITY] {
            q if q != NonZero::<u16>::MAX => q.get() - 1,
            _ if self.0[WILDCARD] == NonZero::<u16>::MIN => 0,
            _ => 1000,
        }
    }

    fn scan<const N: usize>(raw: &[u8]) -> Result<(Flags, [NonZero<u16>; N]), Error> {
        let mut next = Flags::default();
        let mut values = [NonZero::<u16>::MAX; N];
        for member in raw.split(|&byte| byte == b',') {
            let member = crate::field::Error::trim_ows(member);
            if member.is_empty() {
                continue;
            }
            let end = member
                .iter()
                .position(|&byte| !crate::field::Error::is_name_byte(byte))
                .unwrap_or(member.len());
            if end == 0 {
                return Err(Error::Value);
            }
            let token = &member[..end];
            let quality = Self::quality::<N>(&member[end..])?;
            let slot = if token.eq_ignore_ascii_case(b"gzip") {
                next.set(Flags::GZIP_SEEN);
                if quality == 0 {
                    next.set(Flags::GZIP_EXCLUDED);
                }
                GZIP
            } else if token == b"*" {
                next.set(if quality != 0 {
                    Flags::WILDCARD_ALLOWED
                } else {
                    Flags::WILDCARD_EXCLUDED
                });
                WILDCARD
            } else if N != 0 && token.eq_ignore_ascii_case(b"br") {
                BR
            } else if token.eq_ignore_ascii_case(b"identity") {
                next.set(Flags::IDENTITY_SEEN);
                if quality == 0 {
                    next.set(Flags::IDENTITY_EXCLUDED);
                }
                IDENTITY
            } else {
                continue;
            };
            if let Some(target) = values.get_mut(slot)
                && let Some(value) = NonZero::new(quality + 1)
            {
                *target = (*target).min(value);
            }
        }
        Ok((next, values))
    }

    /// The quality grammar has only four significant digits; parsing it directly
    /// keeps malformed controls and parameters out of the admitted field value.
    fn quality<const N: usize>(raw: &[u8]) -> Result<u16, Error> {
        let raw = crate::field::Error::trim_ows(raw);
        if raw.is_empty() {
            return Ok(if N != 0 { 1000 } else { 1 });
        }
        let Some(raw) = raw.strip_prefix(b";") else {
            return Err(Error::Value);
        };
        let raw = crate::field::Error::trim_ows(raw);
        let Some((&name, raw)) = raw.split_first() else {
            return Err(Error::Value);
        };
        if !name.eq_ignore_ascii_case(&b'q') {
            return Err(Error::Value);
        }
        let Some(raw) = raw.strip_prefix(b"=") else {
            return Err(Error::Value);
        };
        let Some((&whole, rest)) = raw.split_first() else {
            return Err(Error::Value);
        };
        if !matches!(whole, b'0' | b'1') {
            return Err(Error::Value);
        }
        let fraction = if rest.is_empty() {
            rest
        } else {
            rest.strip_prefix(b".").ok_or(Error::Value)?
        };
        if fraction.len() > 3 {
            return Err(Error::Value);
        }
        let mut quality = u16::from(whole == b'1');
        if N != 0 {
            quality *= 1000;
        }
        let mut scale = 100;
        for &byte in fraction {
            if !byte.is_ascii_digit() || (whole == b'1' && byte != b'0') {
                return Err(Error::Value);
            }
            if N != 0 {
                quality += u16::from(byte - b'0') * scale;
                scale /= 10;
            } else {
                quality |= u16::from(byte != b'0');
            }
        }
        Ok(quality)
    }
}