Skip to main content

rtflow_http/
request.rs

1use bytes::Bytes;
2use std::collections::HashMap;
3
4const MAX_HEADERS: usize = 64;
5
6#[derive(Clone, Debug, PartialEq, Eq)]
7pub enum Method {
8    Get,
9    Post,
10    Put,
11    Delete,
12    Head,
13    Options,
14    Patch,
15}
16
17impl Method {
18    pub fn parse(s: &str) -> Option<Self> {
19        match s {
20            "GET" => Some(Self::Get),
21            "POST" => Some(Self::Post),
22            "PUT" => Some(Self::Put),
23            "DELETE" => Some(Self::Delete),
24            "HEAD" => Some(Self::Head),
25            "OPTIONS" => Some(Self::Options),
26            "PATCH" => Some(Self::Patch),
27            _ => None,
28        }
29    }
30}
31
32#[derive(Clone, Debug)]
33pub struct HttpRequest {
34    pub method: Method,
35    pub path: String,
36    /// 客户端地址(accept 时已知;解析阶段为 None)。
37    /// 接入防护需要按来源 IP 限制并发与速率,所以必须一路传下来。
38    pub peer: Option<std::net::SocketAddr>,
39    pub query: HashMap<String, String>,
40    pub headers: Vec<(String, String)>,
41    pub body: Bytes,
42    /// Values captured by `{name}` route segments, in declaration order.
43    pub path_params: Vec<String>,
44}
45
46impl HttpRequest {
47    pub fn header(&self, name: &str) -> Option<&str> {
48        let lower = name.to_ascii_lowercase();
49        self.headers
50            .iter()
51            .find(|(k, _)| k.to_ascii_lowercase() == lower)
52            .map(|(_, v)| v.as_str())
53    }
54}
55
56pub enum ParseError {
57    Incomplete,
58    TooLarge,
59    Invalid,
60}
61
62pub fn parse_request(
63    buf: &[u8],
64    max_header_bytes: usize,
65    max_body_bytes: usize,
66) -> Result<Option<(HttpRequest, usize)>, ParseError> {
67    parse_request_with_limits(buf, max_header_bytes, max_body_bytes, &[])
68}
69
70/// 按路径取请求体上限:第一个前缀匹配的限额生效,没匹配上就用全局上限。
71///
72/// 固件上传这类大包走单独额度,其余接口保持小额度 —— 未认证的请求
73/// 在读完头之后就被 413 挡掉,不会先把几十 MB 读进内存。
74pub fn resolve_body_limit(
75    path: &str,
76    global: usize,
77    route_body_limits: &[(String, usize)],
78) -> usize {
79    route_body_limits
80        .iter()
81        .find(|(prefix, _)| path.starts_with(prefix.as_str()))
82        .map(|(_, limit)| *limit)
83        .unwrap_or(global)
84}
85
86pub fn parse_request_with_limits(
87    buf: &[u8],
88    max_header_bytes: usize,
89    max_body_bytes: usize,
90    route_body_limits: &[(String, usize)],
91) -> Result<Option<(HttpRequest, usize)>, ParseError> {
92    // Find end of headers
93    let header_end = find_header_end(buf).ok_or({
94        if buf.len() > max_header_bytes {
95            ParseError::TooLarge
96        } else {
97            ParseError::Incomplete
98        }
99    })?;
100
101    let header_str = std::str::from_utf8(&buf[..header_end]).map_err(|_| ParseError::Invalid)?;
102    let mut lines = header_str.split("\r\n");
103
104    // Request line
105    let request_line = lines.next().ok_or(ParseError::Invalid)?;
106    let mut parts = request_line.splitn(3, ' ');
107    let method_str = parts.next().ok_or(ParseError::Invalid)?;
108    let path_str = parts.next().ok_or(ParseError::Invalid)?;
109    let version = parts.next().ok_or(ParseError::Invalid)?;
110    if version != "HTTP/1.1" && version != "HTTP/1.0" {
111        return Err(ParseError::Invalid);
112    }
113
114    let method = Method::parse(method_str).ok_or(ParseError::Invalid)?;
115
116    // Split path and query
117    let (path, query) = parse_path_query(path_str);
118
119    // Headers
120    let mut headers = Vec::new();
121    for line in lines {
122        if line.is_empty() {
123            continue;
124        }
125        if headers.len() >= MAX_HEADERS {
126            return Err(ParseError::TooLarge);
127        }
128        let Some((key, value)) = line.split_once(':') else {
129            return Err(ParseError::Invalid);
130        };
131        let key = key.trim();
132        let value = value.trim();
133        if key.is_empty() || key.bytes().any(|byte| byte <= 0x20 || byte >= 0x7f) {
134            return Err(ParseError::Invalid);
135        }
136        headers.push((key.to_string(), value.to_string()));
137    }
138
139    let content_lengths: Vec<_> = headers
140        .iter()
141        .filter(|(key, _)| key.eq_ignore_ascii_case("content-length"))
142        .map(|(_, value)| value.parse::<usize>().map_err(|_| ParseError::Invalid))
143        .collect::<Result<_, _>>()?;
144    if content_lengths
145        .windows(2)
146        .any(|values| values[0] != values[1])
147    {
148        return Err(ParseError::Invalid);
149    }
150    let content_length = content_lengths.first().copied().unwrap_or(0);
151    let body_limit = resolve_body_limit(&path, max_body_bytes, route_body_limits);
152    if content_length > body_limit {
153        return Err(ParseError::TooLarge);
154    }
155    if headers.iter().any(|(key, value)| {
156        key.eq_ignore_ascii_case("transfer-encoding") && !value.eq_ignore_ascii_case("identity")
157    }) {
158        return Err(ParseError::Invalid);
159    }
160
161    let total = header_end + 4 + content_length; // +4 for \r\n\r\n
162    if buf.len() < total {
163        return Err(ParseError::Incomplete);
164    }
165
166    let body = if content_length > 0 {
167        Bytes::copy_from_slice(&buf[header_end + 4..total])
168    } else {
169        Bytes::new()
170    };
171
172    Ok(Some((
173        HttpRequest {
174            method,
175            path,
176            peer: None,
177            query,
178            headers,
179            body,
180            path_params: Vec::new(),
181        },
182        total,
183    )))
184}
185
186fn find_header_end(buf: &[u8]) -> Option<usize> {
187    for i in 0..buf.len().saturating_sub(3) {
188        if &buf[i..i + 4] == b"\r\n\r\n" {
189            return Some(i);
190        }
191    }
192    None
193}
194
195pub(crate) fn percent_decode(value: &str) -> String {
196    let bytes = value.as_bytes();
197    let mut output = Vec::with_capacity(bytes.len());
198    let mut index = 0;
199    while index < bytes.len() {
200        match bytes[index] {
201            b'+' => {
202                output.push(b' ');
203                index += 1;
204            }
205            b'%' if index + 2 < bytes.len() => {
206                let hex = |byte: u8| match byte {
207                    b'0'..=b'9' => Some(byte - b'0'),
208                    b'a'..=b'f' => Some(byte - b'a' + 10),
209                    b'A'..=b'F' => Some(byte - b'A' + 10),
210                    _ => None,
211                };
212                match (hex(bytes[index + 1]), hex(bytes[index + 2])) {
213                    (Some(high), Some(low)) => {
214                        output.push((high << 4) | low);
215                        index += 3;
216                    }
217                    _ => {
218                        output.push(bytes[index]);
219                        index += 1;
220                    }
221                }
222            }
223            byte => {
224                output.push(byte);
225                index += 1;
226            }
227        }
228    }
229    String::from_utf8_lossy(&output).into_owned()
230}
231
232fn parse_path_query(raw: &str) -> (String, HashMap<String, String>) {
233    if let Some((path, qs)) = raw.split_once('?') {
234        let query = qs
235            .split('&')
236            .filter_map(|p| p.split_once('='))
237            .map(|(k, v)| (percent_decode(k), percent_decode(v)))
238            .collect();
239        (path.to_string(), query)
240    } else {
241        (raw.to_string(), HashMap::new())
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    fn parse(wire: &[u8]) -> Result<Option<(HttpRequest, usize)>, ParseError> {
250        parse_request(wire, 8 * 1024, 256)
251    }
252
253    #[test]
254    fn query_values_are_percent_decoded() {
255        let (path, query) = parse_path_query("/x?path=%2Fa%20b&form=1+2");
256        assert_eq!(path, "/x");
257        assert_eq!(query.get("path").map(String::as_str), Some("/a b"));
258        assert_eq!(query.get("form").map(String::as_str), Some("1 2"));
259    }
260
261    #[test]
262    fn parser_rejects_invalid_version_and_header_lines() {
263        // HTTP/1.0 is accepted (answered with HTTP/1.1 framing).
264        assert!(parse(b"GET / HTTP/1.0\r\n\r\n").is_ok());
265        assert!(parse(b"GET / HTTP/1.1\r\nBroken\r\n\r\n").is_err());
266    }
267
268    #[test]
269    fn parser_rejects_conflicting_lengths_and_unsupported_transfer_encoding() {
270        assert!(
271            parse(b"POST / HTTP/1.1\r\nContent-Length: 1\r\nContent-Length: 2\r\n\r\nx").is_err()
272        );
273        assert!(parse(b"POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n").is_err());
274    }
275
276    #[test]
277    fn parser_enforces_body_limit() {
278        assert!(parse(b"POST / HTTP/1.1\r\nContent-Length: 257\r\n\r\n").is_err());
279    }
280
281    #[test]
282    fn route_limit_raises_only_the_matching_prefix() {
283        let limits = vec![("/api/firmware".to_string(), 4096usize)];
284        let parse_with = |wire: &[u8]| parse_request_with_limits(wire, 8 * 1024, 256, &limits);
285        // 未匹配前缀:仍按全局 256 字节拒绝
286        assert!(matches!(
287            parse_with(b"POST /api/config HTTP/1.1\r\nContent-Length: 257\r\n\r\n"),
288            Err(ParseError::TooLarge)
289        ));
290        // 匹配前缀:按 4096 字节放行(正文没到齐 → Incomplete,不再 TooLarge)
291        assert!(matches!(
292            parse_with(b"POST /api/firmware HTTP/1.1\r\nContent-Length: 2048\r\n\r\n"),
293            Err(ParseError::Incomplete)
294        ));
295        // 超过该路径上限仍然拒绝
296        assert!(matches!(
297            parse_with(b"POST /api/firmware HTTP/1.1\r\nContent-Length: 4097\r\n\r\n"),
298            Err(ParseError::TooLarge)
299        ));
300    }
301
302    #[test]
303    fn route_limit_uses_first_match_and_wins_over_global() {
304        assert_eq!(
305            resolve_body_limit("/api/firmware", 64, &[("/api/firmware".into(), 1024)]),
306            1024
307        );
308        assert_eq!(
309            resolve_body_limit(
310                "/api/firmware/x",
311                64,
312                &[("/api/firmware".into(), 1024), ("/api".into(), 32)]
313            ),
314            1024,
315            "前缀按声明顺序取第一个匹配"
316        );
317        assert_eq!(resolve_body_limit("/api/status", 64, &[]), 64);
318    }
319
320    #[test]
321    fn route_limit_applies_after_query_string_split() {
322        let limits = vec![("/api/firmware".to_string(), 1024usize)];
323        assert!(matches!(
324            parse_request_with_limits(
325                b"POST /api/firmware?action=apply HTTP/1.1\r\nContent-Length: 512\r\n\r\n",
326                8 * 1024,
327                64,
328                &limits
329            ),
330            Err(ParseError::Incomplete)
331        ));
332    }
333}