rtflow-http 0.7.0

Minimal bounded HTTP/1.1 server and router used by rtflow protocol adapters
Documentation
use bytes::Bytes;
use std::collections::HashMap;

const MAX_HEADERS: usize = 64;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Method {
    Get,
    Post,
    Put,
    Delete,
    Head,
    Options,
    Patch,
}

impl Method {
    pub fn parse(s: &str) -> Option<Self> {
        match s {
            "GET" => Some(Self::Get),
            "POST" => Some(Self::Post),
            "PUT" => Some(Self::Put),
            "DELETE" => Some(Self::Delete),
            "HEAD" => Some(Self::Head),
            "OPTIONS" => Some(Self::Options),
            "PATCH" => Some(Self::Patch),
            _ => None,
        }
    }
}

#[derive(Clone, Debug)]
pub struct HttpRequest {
    pub method: Method,
    pub path: String,
    /// 客户端地址(accept 时已知;解析阶段为 None)。
    /// 接入防护需要按来源 IP 限制并发与速率,所以必须一路传下来。
    pub peer: Option<std::net::SocketAddr>,
    pub query: HashMap<String, String>,
    pub headers: Vec<(String, String)>,
    pub body: Bytes,
    /// Values captured by `{name}` route segments, in declaration order.
    pub path_params: Vec<String>,
}

impl HttpRequest {
    pub fn header(&self, name: &str) -> Option<&str> {
        let lower = name.to_ascii_lowercase();
        self.headers
            .iter()
            .find(|(k, _)| k.to_ascii_lowercase() == lower)
            .map(|(_, v)| v.as_str())
    }
}

pub enum ParseError {
    Incomplete,
    TooLarge,
    Invalid,
}

pub fn parse_request(
    buf: &[u8],
    max_header_bytes: usize,
    max_body_bytes: usize,
) -> Result<Option<(HttpRequest, usize)>, ParseError> {
    parse_request_with_limits(buf, max_header_bytes, max_body_bytes, &[])
}

/// 按路径取请求体上限:第一个前缀匹配的限额生效,没匹配上就用全局上限。
///
/// 固件上传这类大包走单独额度,其余接口保持小额度 —— 未认证的请求
/// 在读完头之后就被 413 挡掉,不会先把几十 MB 读进内存。
pub fn resolve_body_limit(
    path: &str,
    global: usize,
    route_body_limits: &[(String, usize)],
) -> usize {
    route_body_limits
        .iter()
        .find(|(prefix, _)| path.starts_with(prefix.as_str()))
        .map(|(_, limit)| *limit)
        .unwrap_or(global)
}

pub fn parse_request_with_limits(
    buf: &[u8],
    max_header_bytes: usize,
    max_body_bytes: usize,
    route_body_limits: &[(String, usize)],
) -> Result<Option<(HttpRequest, usize)>, ParseError> {
    // Find end of headers
    let header_end = find_header_end(buf).ok_or({
        if buf.len() > max_header_bytes {
            ParseError::TooLarge
        } else {
            ParseError::Incomplete
        }
    })?;

    let header_str = std::str::from_utf8(&buf[..header_end]).map_err(|_| ParseError::Invalid)?;
    let mut lines = header_str.split("\r\n");

    // Request line
    let request_line = lines.next().ok_or(ParseError::Invalid)?;
    let mut parts = request_line.splitn(3, ' ');
    let method_str = parts.next().ok_or(ParseError::Invalid)?;
    let path_str = parts.next().ok_or(ParseError::Invalid)?;
    let version = parts.next().ok_or(ParseError::Invalid)?;
    if version != "HTTP/1.1" && version != "HTTP/1.0" {
        return Err(ParseError::Invalid);
    }

    let method = Method::parse(method_str).ok_or(ParseError::Invalid)?;

    // Split path and query
    let (path, query) = parse_path_query(path_str);

    // Headers
    let mut headers = Vec::new();
    for line in lines {
        if line.is_empty() {
            continue;
        }
        if headers.len() >= MAX_HEADERS {
            return Err(ParseError::TooLarge);
        }
        let Some((key, value)) = line.split_once(':') else {
            return Err(ParseError::Invalid);
        };
        let key = key.trim();
        let value = value.trim();
        if key.is_empty() || key.bytes().any(|byte| byte <= 0x20 || byte >= 0x7f) {
            return Err(ParseError::Invalid);
        }
        headers.push((key.to_string(), value.to_string()));
    }

    let content_lengths: Vec<_> = headers
        .iter()
        .filter(|(key, _)| key.eq_ignore_ascii_case("content-length"))
        .map(|(_, value)| value.parse::<usize>().map_err(|_| ParseError::Invalid))
        .collect::<Result<_, _>>()?;
    if content_lengths
        .windows(2)
        .any(|values| values[0] != values[1])
    {
        return Err(ParseError::Invalid);
    }
    let content_length = content_lengths.first().copied().unwrap_or(0);
    let body_limit = resolve_body_limit(&path, max_body_bytes, route_body_limits);
    if content_length > body_limit {
        return Err(ParseError::TooLarge);
    }
    if headers.iter().any(|(key, value)| {
        key.eq_ignore_ascii_case("transfer-encoding") && !value.eq_ignore_ascii_case("identity")
    }) {
        return Err(ParseError::Invalid);
    }

    let total = header_end + 4 + content_length; // +4 for \r\n\r\n
    if buf.len() < total {
        return Err(ParseError::Incomplete);
    }

    let body = if content_length > 0 {
        Bytes::copy_from_slice(&buf[header_end + 4..total])
    } else {
        Bytes::new()
    };

    Ok(Some((
        HttpRequest {
            method,
            path,
            peer: None,
            query,
            headers,
            body,
            path_params: Vec::new(),
        },
        total,
    )))
}

fn find_header_end(buf: &[u8]) -> Option<usize> {
    for i in 0..buf.len().saturating_sub(3) {
        if &buf[i..i + 4] == b"\r\n\r\n" {
            return Some(i);
        }
    }
    None
}

pub(crate) fn percent_decode(value: &str) -> String {
    let bytes = value.as_bytes();
    let mut output = Vec::with_capacity(bytes.len());
    let mut index = 0;
    while index < bytes.len() {
        match bytes[index] {
            b'+' => {
                output.push(b' ');
                index += 1;
            }
            b'%' if index + 2 < bytes.len() => {
                let hex = |byte: u8| match byte {
                    b'0'..=b'9' => Some(byte - b'0'),
                    b'a'..=b'f' => Some(byte - b'a' + 10),
                    b'A'..=b'F' => Some(byte - b'A' + 10),
                    _ => None,
                };
                match (hex(bytes[index + 1]), hex(bytes[index + 2])) {
                    (Some(high), Some(low)) => {
                        output.push((high << 4) | low);
                        index += 3;
                    }
                    _ => {
                        output.push(bytes[index]);
                        index += 1;
                    }
                }
            }
            byte => {
                output.push(byte);
                index += 1;
            }
        }
    }
    String::from_utf8_lossy(&output).into_owned()
}

fn parse_path_query(raw: &str) -> (String, HashMap<String, String>) {
    if let Some((path, qs)) = raw.split_once('?') {
        let query = qs
            .split('&')
            .filter_map(|p| p.split_once('='))
            .map(|(k, v)| (percent_decode(k), percent_decode(v)))
            .collect();
        (path.to_string(), query)
    } else {
        (raw.to_string(), HashMap::new())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse(wire: &[u8]) -> Result<Option<(HttpRequest, usize)>, ParseError> {
        parse_request(wire, 8 * 1024, 256)
    }

    #[test]
    fn query_values_are_percent_decoded() {
        let (path, query) = parse_path_query("/x?path=%2Fa%20b&form=1+2");
        assert_eq!(path, "/x");
        assert_eq!(query.get("path").map(String::as_str), Some("/a b"));
        assert_eq!(query.get("form").map(String::as_str), Some("1 2"));
    }

    #[test]
    fn parser_rejects_invalid_version_and_header_lines() {
        // HTTP/1.0 is accepted (answered with HTTP/1.1 framing).
        assert!(parse(b"GET / HTTP/1.0\r\n\r\n").is_ok());
        assert!(parse(b"GET / HTTP/1.1\r\nBroken\r\n\r\n").is_err());
    }

    #[test]
    fn parser_rejects_conflicting_lengths_and_unsupported_transfer_encoding() {
        assert!(
            parse(b"POST / HTTP/1.1\r\nContent-Length: 1\r\nContent-Length: 2\r\n\r\nx").is_err()
        );
        assert!(parse(b"POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n").is_err());
    }

    #[test]
    fn parser_enforces_body_limit() {
        assert!(parse(b"POST / HTTP/1.1\r\nContent-Length: 257\r\n\r\n").is_err());
    }

    #[test]
    fn route_limit_raises_only_the_matching_prefix() {
        let limits = vec![("/api/firmware".to_string(), 4096usize)];
        let parse_with = |wire: &[u8]| parse_request_with_limits(wire, 8 * 1024, 256, &limits);
        // 未匹配前缀:仍按全局 256 字节拒绝
        assert!(matches!(
            parse_with(b"POST /api/config HTTP/1.1\r\nContent-Length: 257\r\n\r\n"),
            Err(ParseError::TooLarge)
        ));
        // 匹配前缀:按 4096 字节放行(正文没到齐 → Incomplete,不再 TooLarge)
        assert!(matches!(
            parse_with(b"POST /api/firmware HTTP/1.1\r\nContent-Length: 2048\r\n\r\n"),
            Err(ParseError::Incomplete)
        ));
        // 超过该路径上限仍然拒绝
        assert!(matches!(
            parse_with(b"POST /api/firmware HTTP/1.1\r\nContent-Length: 4097\r\n\r\n"),
            Err(ParseError::TooLarge)
        ));
    }

    #[test]
    fn route_limit_uses_first_match_and_wins_over_global() {
        assert_eq!(
            resolve_body_limit("/api/firmware", 64, &[("/api/firmware".into(), 1024)]),
            1024
        );
        assert_eq!(
            resolve_body_limit(
                "/api/firmware/x",
                64,
                &[("/api/firmware".into(), 1024), ("/api".into(), 32)]
            ),
            1024,
            "前缀按声明顺序取第一个匹配"
        );
        assert_eq!(resolve_body_limit("/api/status", 64, &[]), 64);
    }

    #[test]
    fn route_limit_applies_after_query_string_split() {
        let limits = vec![("/api/firmware".to_string(), 1024usize)];
        assert!(matches!(
            parse_request_with_limits(
                b"POST /api/firmware?action=apply HTTP/1.1\r\nContent-Length: 512\r\n\r\n",
                8 * 1024,
                64,
                &limits
            ),
            Err(ParseError::Incomplete)
        ));
    }
}