Skip to main content

rtflow_http/
lib.rs

1pub mod auth_middleware;
2pub mod cors;
3mod request;
4pub mod response;
5mod router;
6
7pub use request::{HttpRequest, Method};
8#[doc(hidden)]
9pub use request::{ParseError, parse_request, parse_request_with_limits, resolve_body_limit};
10pub use response::ResponseWriter;
11pub use router::ConnWriter;
12pub use router::{Handler, Router};
13
14use rtflow_core::error::{Error, Result};
15use rtflow_security::SecurityConfig;
16use std::{net::SocketAddr, sync::Arc, time::Duration};
17use tokio::{net::TcpListener, sync::RwLock};
18use tokio_util::sync::CancellationToken;
19
20const DEFAULT_MAX_CONNECTIONS: usize = 1024;
21/// 单 IP HTTP 并发上限:浏览器一次开 6~8 条,24 留足余量又不让单 IP 占满槽位。
22const DEFAULT_MAX_CONNECTIONS_PER_IP: usize = 24;
23const READ_BUF_SIZE: usize = 8192;
24
25#[derive(Clone)]
26pub struct HttpConfig {
27    pub listen: SocketAddr,
28    pub max_connections: usize,
29    /// 单 IP 的 HTTP 并发连接上限(0 = 不限制;默认 24,与 C 版一致)。
30    pub max_connections_per_ip: usize,
31    pub read_timeout: Duration,
32    /// Total budget for receiving one request's **headers** (slowloris guard,
33    /// aligned with the C implementation): a peer that drips one byte per
34    /// second is disconnected after this instead of holding a slot forever.
35    pub header_timeout: Duration,
36    /// Total budget for receiving one request's **body**.
37    pub body_timeout: Duration,
38    pub shutdown_timeout: Duration,
39    pub max_header_bytes: usize,
40    pub max_body_bytes: usize,
41    /// 按路径前缀覆盖 `max_body_bytes`(第一个匹配生效,未匹配用全局值)。
42    ///
43    /// 固件/配置导入这类本来就要上传大包的接口才需要大额度;其余接口保持
44    /// 小额度,未认证的请求在读完头之后就被挡掉,不会先把整个包读进内存。
45    pub route_body_limits: Vec<(String, usize)>,
46    /// Per-write deadline for response bodies. A peer that stops reading
47    /// (slow/frozen client) is disconnected after this, instead of
48    /// pinning a connection slot forever (R22).
49    pub response_timeout: Duration,
50    pub security: SecurityConfig,
51    /// Optional global metrics registry for request counting.
52    pub metrics: Option<Arc<rtflow_core::metrics::MetricsRegistry>>,
53    /// Serve HTTPS when a certificate/key is configured.
54    #[cfg(feature = "tls")]
55    pub tls: Option<rtflow_security::TlsServerConfig>,
56    /// TLS handshake deadline (defaults to 5 s).
57    #[cfg(feature = "tls")]
58    pub tls_handshake_timeout: Duration,
59}
60
61impl HttpConfig {
62    pub fn new(listen: SocketAddr) -> Self {
63        Self {
64            listen,
65            max_connections: DEFAULT_MAX_CONNECTIONS,
66            max_connections_per_ip: DEFAULT_MAX_CONNECTIONS_PER_IP,
67            read_timeout: Duration::from_secs(30),
68            header_timeout: Duration::from_secs(10),
69            body_timeout: Duration::from_secs(60),
70            shutdown_timeout: Duration::from_secs(5),
71            max_header_bytes: 8 * 1024,
72            max_body_bytes: 256 * 1024,
73            route_body_limits: Vec::new(),
74            response_timeout: Duration::from_secs(60),
75            security: SecurityConfig::default(),
76            metrics: None,
77            #[cfg(feature = "tls")]
78            tls: None,
79            #[cfg(feature = "tls")]
80            tls_handshake_timeout: Duration::from_secs(5),
81        }
82    }
83
84    /// Serve HTTPS with the given certificate and key.
85    #[cfg(feature = "tls")]
86    pub fn with_tls(mut self, tls: rtflow_security::TlsServerConfig) -> Self {
87        self.tls = Some(tls);
88        self
89    }
90
91    pub fn validate(&self) -> Result<()> {
92        if self.max_connections == 0 {
93            return Err(Error::Limit("HTTP max connections"));
94        }
95        if self.read_timeout == Duration::ZERO
96            || self.header_timeout == Duration::ZERO
97            || self.body_timeout == Duration::ZERO
98            || self.response_timeout == Duration::ZERO
99            || self.shutdown_timeout == Duration::ZERO
100        {
101            return Err(Error::Limit("HTTP timeout"));
102        }
103        if self.max_header_bytes == 0 || self.max_body_bytes == 0 {
104            return Err(Error::Limit("HTTP message size"));
105        }
106        if self
107            .route_body_limits
108            .iter()
109            .any(|(prefix, limit)| prefix.is_empty() || *limit == 0)
110        {
111            return Err(Error::Limit("HTTP route body limit"));
112        }
113        Ok(())
114    }
115
116    /// Attach a global metrics registry (request/segment counters).
117    pub fn with_metrics(mut self, metrics: Arc<rtflow_core::metrics::MetricsRegistry>) -> Self {
118        self.metrics = Some(metrics);
119        self
120    }
121}
122
123/// 活跃 HTTP 连接数(accept 时 +1、连接任务结束时 -1)。
124static ACTIVE_CONNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
125
126/// 连接任务结束时把活跃计数减回去(panic/提前返回也不漏)。
127struct ActiveConn;
128
129impl Drop for ActiveConn {
130    fn drop(&mut self) {
131        ACTIVE_CONNS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
132    }
133}
134
135/// 当前活跃的 HTTP 连接数(供 /api/status 的 guard.http 字段使用)。
136pub fn active_connections() -> usize {
137    ACTIVE_CONNS.load(std::sync::atomic::Ordering::Relaxed)
138}
139
140/// 单 IP 的 HTTP 并发连接配额(与 C 版 guard 的 HTTP 24 对齐)。
141///
142/// 速率限制拦不住"开 24 条连接慢慢耗"的做法:每次连接都在预算内,
143/// 但会把 max_connections 的槽全占掉,控制面就没法用了。
144struct PerIpConnections {
145    limit: usize,
146    counts: std::sync::Mutex<std::collections::HashMap<std::net::IpAddr, usize>>,
147}
148
149impl PerIpConnections {
150    fn new(limit: usize) -> Self {
151        Self {
152            limit,
153            counts: std::sync::Mutex::new(std::collections::HashMap::new()),
154        }
155    }
156
157    fn acquire(self: &std::sync::Arc<Self>, ip: std::net::IpAddr) -> Option<PerIpLease> {
158        if self.limit == 0 {
159            return Some(PerIpLease {
160                owner: self.clone(),
161                ip,
162            });
163        }
164        let mut counts = self
165            .counts
166            .lock()
167            .unwrap_or_else(std::sync::PoisonError::into_inner);
168        let used = counts.entry(ip).or_insert(0);
169        if *used >= self.limit {
170            return None;
171        }
172        *used += 1;
173        drop(counts);
174        Some(PerIpLease {
175            owner: self.clone(),
176            ip,
177        })
178    }
179}
180
181struct PerIpLease {
182    owner: std::sync::Arc<PerIpConnections>,
183    ip: std::net::IpAddr,
184}
185
186impl Drop for PerIpLease {
187    fn drop(&mut self) {
188        let mut counts = self
189            .owner
190            .counts
191            .lock()
192            .unwrap_or_else(std::sync::PoisonError::into_inner);
193        if let Some(used) = counts.get_mut(&self.ip) {
194            *used = used.saturating_sub(1);
195            if *used == 0 {
196                counts.remove(&self.ip);
197            }
198        }
199    }
200}
201pub struct HttpServer {
202    listener: Option<TcpListener>,
203    router: Arc<RwLock<Router>>,
204    cancel: CancellationToken,
205    config: HttpConfig,
206    local_addr: SocketAddr,
207}
208
209impl HttpServer {
210    pub async fn bind(config: HttpConfig) -> Result<Self> {
211        config.validate()?;
212        let listener = TcpListener::bind(config.listen).await?;
213        let local_addr = listener.local_addr()?;
214        Ok(Self {
215            listener: Some(listener),
216            router: Arc::new(RwLock::new(Router::new())),
217            cancel: CancellationToken::new(),
218            config,
219            local_addr,
220        })
221    }
222
223    pub fn local_addr(&self) -> SocketAddr {
224        self.local_addr
225    }
226
227    pub async fn add_route(&self, method: Method, pattern: &str, handler: Handler) {
228        let mut router = self.router.write().await;
229        router.add(method, pattern, handler);
230    }
231
232    pub async fn run(&mut self) -> Result<()> {
233        let Some(listener) = self.listener.take() else {
234            return Err(Error::InvalidConfig(
235                "HTTP server run() can only be called once".into(),
236            ));
237        };
238        let router = self.router.clone();
239        let cancel = self.cancel.clone();
240        let security = self.config.security.clone();
241        let metrics = self.config.metrics.clone();
242        let read_timeout = self.config.read_timeout;
243        let header_timeout = self.config.header_timeout;
244        let body_timeout = self.config.body_timeout;
245        let shutdown_timeout = self.config.shutdown_timeout;
246        let max_header_bytes = self.config.max_header_bytes;
247        let max_body_bytes = self.config.max_body_bytes;
248        let route_body_limits = Arc::new(self.config.route_body_limits.clone());
249        let response_timeout = self.config.response_timeout;
250        #[cfg(feature = "tls")]
251        let tls = self.config.tls.clone();
252        #[cfg(feature = "tls")]
253        let tls_handshake_timeout = self.config.tls_handshake_timeout;
254        let connections = Arc::new(tokio::sync::Semaphore::new(self.config.max_connections));
255        let per_ip = Arc::new(PerIpConnections::new(self.config.max_connections_per_ip));
256        let rate_limiter = Arc::new(rtflow_security::ConnectionRateLimiter::new(
257            self.config.security.connection_rate_limit,
258        )?);
259
260        tokio::spawn(async move {
261            let mut tasks = tokio::task::JoinSet::new();
262            loop {
263                tokio::select! {
264                    result = listener.accept() => {
265                        let (stream, addr) = match result {
266                            Ok(value) => value,
267                            Err(_) => {
268                                // EMFILE/ENFILE must not turn into a tight
269                                // accept-error spin that burns a core.
270                                tokio::time::sleep(Duration::from_millis(10)).await;
271                                continue;
272                            }
273                        };
274                        // Low-latency streaming: disable Nagle so small FLV
275                        // tags are not delayed behind unrelated segments
276                        // (tokio defaults to true, but be explicit).
277                        let _ = stream.set_nodelay(true);
278                        if !security.ip_acl.permits(addr.ip()) {
279                            tracing::warn!(peer = %addr, "HTTP connection rejected by IP ACL");
280                            continue;
281                        }
282                        if !rate_limiter.admit(addr.ip(), std::time::Instant::now()) {
283                            tracing::warn!(peer = %addr, "HTTP connection rejected by rate limit");
284                            // Reply 429 so clients can distinguish rate
285                            // limiting from a network failure.
286                            tokio::spawn(async move {
287                                let mut writer = ResponseWriter::new(stream);
288                                let _ = writer
289                                    .write_body(429, "text/plain", b"Too Many Requests")
290                                    .await;
291                            });
292                            continue;
293                        }
294                        let Some(ip_lease) = per_ip.clone().acquire(addr.ip()) else {
295                            tracing::warn!(peer = %addr, "HTTP connection rejected: per-IP limit");
296                            tokio::spawn(async move {
297                                let mut writer = ResponseWriter::new(stream);
298                                let _ = writer
299                                    .write_body(503, "text/plain", b"Too Many Connections")
300                                    .await;
301                            });
302                            continue;
303                        };
304                        let Ok(permit) = connections.clone().try_acquire_owned() else {
305                            // Connection capacity exhausted: same 429
306                            // semantics as rate limiting.
307                            tokio::spawn(async move {
308                                let mut writer = ResponseWriter::new(stream);
309                                let _ = writer
310                                    .write_body(429, "text/plain", b"Too Many Requests")
311                                    .await;
312                            });
313                            continue;
314                        };
315                        let router = router.clone();
316                        let security = security.clone();
317                        let metrics = metrics.clone();
318                        let route_body_limits = route_body_limits.clone();
319                        #[cfg(feature = "tls")]
320                        let tls = tls.clone();
321                        tasks.spawn(async move {
322                            let _permit = permit;
323                            let _ip_lease = ip_lease;
324                            ACTIVE_CONNS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
325                            let _active = ActiveConn;
326                            if let Some(metrics) = &metrics {
327                                use std::sync::atomic::Ordering;
328                                metrics.http_requests_total.fetch_add(1, Ordering::Relaxed);
329                            }
330                            let result = {
331                                #[cfg(feature = "tls")]
332                                {
333                                    if let Some(tls) = tls {
334                                        let acceptor = tokio_rustls::TlsAcceptor::from(tls.config);
335                                        match tokio::time::timeout(
336                                            tls_handshake_timeout,
337                                            acceptor.accept(stream),
338                                        )
339                                        .await
340                                        {
341                                            Ok(Ok(tls_stream)) => {
342                                                let (reader, writer) = tokio::io::split(tls_stream);
343                                                handle_connection(
344                                                    Some(addr),
345                                                    reader,
346                                                    ConnWriter::Tls(writer),
347                                                    router,
348                                                    security,
349                                                    read_timeout,
350                                                    header_timeout,
351                                                    body_timeout,
352                                                    max_header_bytes,
353                                                    max_body_bytes,
354                                                    &route_body_limits,
355                                                    response_timeout,
356                                                )
357                                                .await
358                                            }
359                                            Ok(Err(error)) => Err(Error::Tls(error.to_string())),
360                                            Err(_) => Err(Error::Tls("TLS handshake timeout".into())),
361                                        }
362                                    } else {
363                                        let (reader, writer) = stream.into_split();
364                                        handle_connection(
365                                            Some(addr),
366                                            reader,
367                                            ConnWriter::Tcp(writer),
368                                            router,
369                                            security,
370                                            read_timeout,
371                                            header_timeout,
372                                            body_timeout,
373                                            max_header_bytes,
374                                            max_body_bytes,
375                                            &route_body_limits,
376                                            response_timeout,
377                                        )
378                                        .await
379                                    }
380                                }
381                                #[cfg(not(feature = "tls"))]
382                                {
383                                    let (reader, writer) = stream.into_split();
384                                    handle_connection(
385                                        Some(addr),
386                                        reader,
387                                        ConnWriter::Tcp(writer),
388                                        router,
389                                        security,
390                                        read_timeout,
391                                        header_timeout,
392                                        body_timeout,
393                                    max_header_bytes,
394                                    max_body_bytes,
395                                    &route_body_limits,
396                                    response_timeout,
397                                    )
398                                    .await
399                                }
400                            };
401                            if let Err(e) = result {
402                                tracing::debug!("http connection error: {e}");
403                            }
404                        });
405                    }
406                    _ = cancel.cancelled() => break,
407                }
408                // 回收已结束的连接任务。
409                //
410                // **不能把 `join_next()` 放进 select!**:实测那样会让 TLS 握手卡死
411                // (同一台板上 accept 18 次只有 6 次握手完成,curl 约 50% 失败;
412                // 去掉这个分支后 6/6 全部成功)。改成每轮循环末尾同步抽干已完成的
413                // 任务 —— `try_join_next()` 不会注册 waker,不影响 accept。
414                //
415                // 不回收的话,完成的任务会一直留在 JoinSet 里(每个任务带着自己的
416                // 分配,实测约 10 KB/连接),表现为「每来一个连接就涨 10 KB」。
417                while tasks.try_join_next().is_some() {}
418            }
419            let _ = tokio::time::timeout(shutdown_timeout, async {
420                while tasks.join_next().await.is_some() {}
421            })
422            .await;
423            tasks.abort_all();
424        });
425
426        tracing::info!("http server listening on {}", self.local_addr);
427        Ok(())
428    }
429
430    pub fn shutdown(&self) {
431        self.cancel.cancel();
432    }
433
434    /// Cancellation token shared with the accept loop, for supervisors that
435    /// need to stop HTTP together with other protocol servers.
436    pub fn cancellation_token(&self) -> tokio_util::sync::CancellationToken {
437        self.cancel.clone()
438    }
439}
440
441#[allow(clippy::too_many_arguments)]
442async fn handle_connection<R>(
443    peer: Option<SocketAddr>,
444    mut read_half: R,
445    write_half: ConnWriter,
446    router: Arc<RwLock<Router>>,
447    security: SecurityConfig,
448    read_timeout: Duration,
449    header_timeout: Duration,
450    body_timeout: Duration,
451    max_header_bytes: usize,
452    max_body_bytes: usize,
453    route_body_limits: &[(String, usize)],
454    response_timeout: Duration,
455) -> Result<()>
456where
457    R: tokio::io::AsyncRead + Unpin,
458{
459    // ACL check
460    if let Some(peer_addr) = peer
461        && !security.ip_acl.permits(peer_addr.ip())
462    {
463        return Err(Error::Unauthorized);
464    }
465
466    let mut writer =
467        Some(ResponseWriter::new(write_half).with_write_timeout(Some(response_timeout)));
468    let mut buf = Vec::with_capacity(READ_BUF_SIZE);
469    // 慢速攻击(slowloris)防护:从这里开始算这一条请求的总预算,
470    // 而不是每次 recv 单独计时 —— 每秒挤一个字节的连接也会被断开。
471    let mut request_started: Option<std::time::Instant> = None;
472
473    loop {
474        let started = *request_started.get_or_insert_with(std::time::Instant::now);
475        let limit = if buf.windows(4).any(|w| w == b"\r\n\r\n") {
476            body_timeout
477        } else {
478            header_timeout
479        };
480        let elapsed = started.elapsed();
481        if elapsed >= limit {
482            // 半截请求 + 超预算:断开,别让它占着连接槽。
483            if let Some(writer) = writer.as_mut() {
484                let _ = writer
485                    .write_body(408, "text/plain", b"Request Timeout")
486                    .await;
487            }
488            return Err(Error::Limit("request timeout"));
489        }
490        let budget = (limit - elapsed).min(read_timeout);
491        // Read request
492        let mut temp = [0u8; READ_BUF_SIZE];
493        let n = tokio::time::timeout(
494            budget,
495            tokio::io::AsyncReadExt::read(&mut read_half, &mut temp),
496        )
497        .await
498        .map_err(|_| Error::Limit("read timeout"))?
499        .map_err(Error::Io)?;
500
501        if n == 0 {
502            break;
503        }
504        buf.extend_from_slice(&temp[..n]);
505
506        // Try to parse request
507        let req = match request::parse_request_with_limits(
508            &buf,
509            max_header_bytes,
510            max_body_bytes,
511            route_body_limits,
512        ) {
513            Ok(Some((req, consumed))) => {
514                buf.drain(..consumed);
515                request_started = None;
516                let mut req = req;
517                req.peer = peer;
518                req
519            }
520            Ok(None) => {
521                if buf.len() > max_header_bytes {
522                    return Err(Error::Limit("request headers too large"));
523                }
524                continue;
525            }
526            Err(request::ParseError::Incomplete) => continue,
527            Err(request::ParseError::TooLarge) => {
528                // 用 413 明确告诉客户端是「包太大」,而不是让它以为连接坏了。
529                if let Some(writer) = writer.as_mut() {
530                    let _ = writer
531                        .write_body(413, "text/plain", b"Payload Too Large")
532                        .await;
533                }
534                return Err(Error::Limit("request too large"));
535            }
536            Err(request::ParseError::Invalid) => {
537                // Reply 400 instead of dropping the connection so the
538                // client can distinguish a protocol error from a network
539                // failure.
540                if let Some(writer) = writer.as_mut() {
541                    let _ = writer.write_body(400, "text/plain", b"Bad Request").await;
542                }
543                return Err(Error::Http("invalid HTTP request".into()));
544            }
545        };
546
547        tracing::trace!(peer = ?peer, method = ?req.method, path = %req.path, "HTTP request");
548        let keep_alive = !req
549            .header("connection")
550            .is_some_and(|value| value.eq_ignore_ascii_case("close"));
551
552        let req_method = req.method.clone();
553        let req_path = req.path.clone();
554        let mut w = writer.take().expect("writer should be available");
555        // Keep-alive: the same writer serves multiple requests; clear the
556        // previous response's state (headers_written/connection_close)
557        // before handing it to the next handler.
558        w.reset();
559        let guard = router.read().await;
560        let (handler, params) = guard.route(&req.method, &req.path.clone());
561        let handler = handler.clone();
562        let mut req = req;
563        // Route matching uses the encoded path; handlers should see the
564        // decoded form so names containing `/` (encoded as %2F) work.
565        req.path = request::percent_decode(&req.path);
566        req.path_params = params
567            .into_iter()
568            .map(|param| request::percent_decode(&param))
569            .collect();
570        drop(guard);
571
572        match handler(req, w).await {
573            Ok(returned_writer) => {
574                let close = returned_writer.should_close();
575                writer = Some(returned_writer);
576                if close {
577                    break;
578                }
579            }
580            Err(e) => {
581                // 播放器(VLC/ffmpeg/浏览器)切换码流、拖动、关页面时会直接断开正在下载的连接,
582                // 这类「对端已关闭」不是设备的问题,用 debug 记,别拿 WARN 刷日志。
583                let msg = e.to_string();
584                let peer_gone = msg.contains("Connection reset by peer")
585                    || msg.contains("Broken pipe")
586                    || msg.contains("connection closed")
587                    || msg.contains("UnexpectedEof");
588                if peer_gone {
589                    tracing::debug!(peer = ?peer, method = ?req_method, path = %req_path, %e, "客户端提前断开");
590                } else {
591                    tracing::warn!(peer = ?peer, method = ?req_method, path = %req_path, %e, "HTTP handler error");
592                }
593                break;
594            }
595        }
596
597        if !keep_alive {
598            break;
599        }
600    }
601
602    // 收尾:优雅关闭写半边(TLS 走 close_notify、TCP 走 FIN)。
603    // 直接 drop 掉 socket 时,内核会把「已发出但客户端还没读走」的数据连同
604    // RST 一起丢掉 —— 实测 HTTPS 下 20 次请求只有 6 次能拿到响应。
605    if let Some(mut w) = writer.take() {
606        let _ = w.flush().await;
607        let mut inner = w.into_inner();
608        let _ = tokio::io::AsyncWriteExt::shutdown(&mut inner).await;
609    }
610
611    Ok(())
612}