rtflow-http 0.7.0

Minimal bounded HTTP/1.1 server and router used by rtflow protocol adapters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
pub mod auth_middleware;
pub mod cors;
mod request;
pub mod response;
mod router;

pub use request::{HttpRequest, Method};
#[doc(hidden)]
pub use request::{ParseError, parse_request, parse_request_with_limits, resolve_body_limit};
pub use response::ResponseWriter;
pub use router::ConnWriter;
pub use router::{Handler, Router};

use rtflow_core::error::{Error, Result};
use rtflow_security::SecurityConfig;
use std::{net::SocketAddr, sync::Arc, time::Duration};
use tokio::{net::TcpListener, sync::RwLock};
use tokio_util::sync::CancellationToken;

const DEFAULT_MAX_CONNECTIONS: usize = 1024;
/// 单 IP HTTP 并发上限:浏览器一次开 6~8 条,24 留足余量又不让单 IP 占满槽位。
const DEFAULT_MAX_CONNECTIONS_PER_IP: usize = 24;
const READ_BUF_SIZE: usize = 8192;

#[derive(Clone)]
pub struct HttpConfig {
    pub listen: SocketAddr,
    pub max_connections: usize,
    /// 单 IP 的 HTTP 并发连接上限(0 = 不限制;默认 24,与 C 版一致)。
    pub max_connections_per_ip: usize,
    pub read_timeout: Duration,
    /// Total budget for receiving one request's **headers** (slowloris guard,
    /// aligned with the C implementation): a peer that drips one byte per
    /// second is disconnected after this instead of holding a slot forever.
    pub header_timeout: Duration,
    /// Total budget for receiving one request's **body**.
    pub body_timeout: Duration,
    pub shutdown_timeout: Duration,
    pub max_header_bytes: usize,
    pub max_body_bytes: usize,
    /// 按路径前缀覆盖 `max_body_bytes`(第一个匹配生效,未匹配用全局值)。
    ///
    /// 固件/配置导入这类本来就要上传大包的接口才需要大额度;其余接口保持
    /// 小额度,未认证的请求在读完头之后就被挡掉,不会先把整个包读进内存。
    pub route_body_limits: Vec<(String, usize)>,
    /// Per-write deadline for response bodies. A peer that stops reading
    /// (slow/frozen client) is disconnected after this, instead of
    /// pinning a connection slot forever (R22).
    pub response_timeout: Duration,
    pub security: SecurityConfig,
    /// Optional global metrics registry for request counting.
    pub metrics: Option<Arc<rtflow_core::metrics::MetricsRegistry>>,
    /// Serve HTTPS when a certificate/key is configured.
    #[cfg(feature = "tls")]
    pub tls: Option<rtflow_security::TlsServerConfig>,
    /// TLS handshake deadline (defaults to 5 s).
    #[cfg(feature = "tls")]
    pub tls_handshake_timeout: Duration,
}

impl HttpConfig {
    pub fn new(listen: SocketAddr) -> Self {
        Self {
            listen,
            max_connections: DEFAULT_MAX_CONNECTIONS,
            max_connections_per_ip: DEFAULT_MAX_CONNECTIONS_PER_IP,
            read_timeout: Duration::from_secs(30),
            header_timeout: Duration::from_secs(10),
            body_timeout: Duration::from_secs(60),
            shutdown_timeout: Duration::from_secs(5),
            max_header_bytes: 8 * 1024,
            max_body_bytes: 256 * 1024,
            route_body_limits: Vec::new(),
            response_timeout: Duration::from_secs(60),
            security: SecurityConfig::default(),
            metrics: None,
            #[cfg(feature = "tls")]
            tls: None,
            #[cfg(feature = "tls")]
            tls_handshake_timeout: Duration::from_secs(5),
        }
    }

    /// Serve HTTPS with the given certificate and key.
    #[cfg(feature = "tls")]
    pub fn with_tls(mut self, tls: rtflow_security::TlsServerConfig) -> Self {
        self.tls = Some(tls);
        self
    }

    pub fn validate(&self) -> Result<()> {
        if self.max_connections == 0 {
            return Err(Error::Limit("HTTP max connections"));
        }
        if self.read_timeout == Duration::ZERO
            || self.header_timeout == Duration::ZERO
            || self.body_timeout == Duration::ZERO
            || self.response_timeout == Duration::ZERO
            || self.shutdown_timeout == Duration::ZERO
        {
            return Err(Error::Limit("HTTP timeout"));
        }
        if self.max_header_bytes == 0 || self.max_body_bytes == 0 {
            return Err(Error::Limit("HTTP message size"));
        }
        if self
            .route_body_limits
            .iter()
            .any(|(prefix, limit)| prefix.is_empty() || *limit == 0)
        {
            return Err(Error::Limit("HTTP route body limit"));
        }
        Ok(())
    }

    /// Attach a global metrics registry (request/segment counters).
    pub fn with_metrics(mut self, metrics: Arc<rtflow_core::metrics::MetricsRegistry>) -> Self {
        self.metrics = Some(metrics);
        self
    }
}

/// 活跃 HTTP 连接数(accept 时 +1、连接任务结束时 -1)。
static ACTIVE_CONNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// 连接任务结束时把活跃计数减回去(panic/提前返回也不漏)。
struct ActiveConn;

impl Drop for ActiveConn {
    fn drop(&mut self) {
        ACTIVE_CONNS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
    }
}

/// 当前活跃的 HTTP 连接数(供 /api/status 的 guard.http 字段使用)。
pub fn active_connections() -> usize {
    ACTIVE_CONNS.load(std::sync::atomic::Ordering::Relaxed)
}

/// 单 IP 的 HTTP 并发连接配额(与 C 版 guard 的 HTTP 24 对齐)。
///
/// 速率限制拦不住"开 24 条连接慢慢耗"的做法:每次连接都在预算内,
/// 但会把 max_connections 的槽全占掉,控制面就没法用了。
struct PerIpConnections {
    limit: usize,
    counts: std::sync::Mutex<std::collections::HashMap<std::net::IpAddr, usize>>,
}

impl PerIpConnections {
    fn new(limit: usize) -> Self {
        Self {
            limit,
            counts: std::sync::Mutex::new(std::collections::HashMap::new()),
        }
    }

    fn acquire(self: &std::sync::Arc<Self>, ip: std::net::IpAddr) -> Option<PerIpLease> {
        if self.limit == 0 {
            return Some(PerIpLease {
                owner: self.clone(),
                ip,
            });
        }
        let mut counts = self
            .counts
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let used = counts.entry(ip).or_insert(0);
        if *used >= self.limit {
            return None;
        }
        *used += 1;
        drop(counts);
        Some(PerIpLease {
            owner: self.clone(),
            ip,
        })
    }
}

struct PerIpLease {
    owner: std::sync::Arc<PerIpConnections>,
    ip: std::net::IpAddr,
}

impl Drop for PerIpLease {
    fn drop(&mut self) {
        let mut counts = self
            .owner
            .counts
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(used) = counts.get_mut(&self.ip) {
            *used = used.saturating_sub(1);
            if *used == 0 {
                counts.remove(&self.ip);
            }
        }
    }
}
pub struct HttpServer {
    listener: Option<TcpListener>,
    router: Arc<RwLock<Router>>,
    cancel: CancellationToken,
    config: HttpConfig,
    local_addr: SocketAddr,
}

impl HttpServer {
    pub async fn bind(config: HttpConfig) -> Result<Self> {
        config.validate()?;
        let listener = TcpListener::bind(config.listen).await?;
        let local_addr = listener.local_addr()?;
        Ok(Self {
            listener: Some(listener),
            router: Arc::new(RwLock::new(Router::new())),
            cancel: CancellationToken::new(),
            config,
            local_addr,
        })
    }

    pub fn local_addr(&self) -> SocketAddr {
        self.local_addr
    }

    pub async fn add_route(&self, method: Method, pattern: &str, handler: Handler) {
        let mut router = self.router.write().await;
        router.add(method, pattern, handler);
    }

    pub async fn run(&mut self) -> Result<()> {
        let Some(listener) = self.listener.take() else {
            return Err(Error::InvalidConfig(
                "HTTP server run() can only be called once".into(),
            ));
        };
        let router = self.router.clone();
        let cancel = self.cancel.clone();
        let security = self.config.security.clone();
        let metrics = self.config.metrics.clone();
        let read_timeout = self.config.read_timeout;
        let header_timeout = self.config.header_timeout;
        let body_timeout = self.config.body_timeout;
        let shutdown_timeout = self.config.shutdown_timeout;
        let max_header_bytes = self.config.max_header_bytes;
        let max_body_bytes = self.config.max_body_bytes;
        let route_body_limits = Arc::new(self.config.route_body_limits.clone());
        let response_timeout = self.config.response_timeout;
        #[cfg(feature = "tls")]
        let tls = self.config.tls.clone();
        #[cfg(feature = "tls")]
        let tls_handshake_timeout = self.config.tls_handshake_timeout;
        let connections = Arc::new(tokio::sync::Semaphore::new(self.config.max_connections));
        let per_ip = Arc::new(PerIpConnections::new(self.config.max_connections_per_ip));
        let rate_limiter = Arc::new(rtflow_security::ConnectionRateLimiter::new(
            self.config.security.connection_rate_limit,
        )?);

        tokio::spawn(async move {
            let mut tasks = tokio::task::JoinSet::new();
            loop {
                tokio::select! {
                    result = listener.accept() => {
                        let (stream, addr) = match result {
                            Ok(value) => value,
                            Err(_) => {
                                // EMFILE/ENFILE must not turn into a tight
                                // accept-error spin that burns a core.
                                tokio::time::sleep(Duration::from_millis(10)).await;
                                continue;
                            }
                        };
                        // Low-latency streaming: disable Nagle so small FLV
                        // tags are not delayed behind unrelated segments
                        // (tokio defaults to true, but be explicit).
                        let _ = stream.set_nodelay(true);
                        if !security.ip_acl.permits(addr.ip()) {
                            tracing::warn!(peer = %addr, "HTTP connection rejected by IP ACL");
                            continue;
                        }
                        if !rate_limiter.admit(addr.ip(), std::time::Instant::now()) {
                            tracing::warn!(peer = %addr, "HTTP connection rejected by rate limit");
                            // Reply 429 so clients can distinguish rate
                            // limiting from a network failure.
                            tokio::spawn(async move {
                                let mut writer = ResponseWriter::new(stream);
                                let _ = writer
                                    .write_body(429, "text/plain", b"Too Many Requests")
                                    .await;
                            });
                            continue;
                        }
                        let Some(ip_lease) = per_ip.clone().acquire(addr.ip()) else {
                            tracing::warn!(peer = %addr, "HTTP connection rejected: per-IP limit");
                            tokio::spawn(async move {
                                let mut writer = ResponseWriter::new(stream);
                                let _ = writer
                                    .write_body(503, "text/plain", b"Too Many Connections")
                                    .await;
                            });
                            continue;
                        };
                        let Ok(permit) = connections.clone().try_acquire_owned() else {
                            // Connection capacity exhausted: same 429
                            // semantics as rate limiting.
                            tokio::spawn(async move {
                                let mut writer = ResponseWriter::new(stream);
                                let _ = writer
                                    .write_body(429, "text/plain", b"Too Many Requests")
                                    .await;
                            });
                            continue;
                        };
                        let router = router.clone();
                        let security = security.clone();
                        let metrics = metrics.clone();
                        let route_body_limits = route_body_limits.clone();
                        #[cfg(feature = "tls")]
                        let tls = tls.clone();
                        tasks.spawn(async move {
                            let _permit = permit;
                            let _ip_lease = ip_lease;
                            ACTIVE_CONNS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                            let _active = ActiveConn;
                            if let Some(metrics) = &metrics {
                                use std::sync::atomic::Ordering;
                                metrics.http_requests_total.fetch_add(1, Ordering::Relaxed);
                            }
                            let result = {
                                #[cfg(feature = "tls")]
                                {
                                    if let Some(tls) = tls {
                                        let acceptor = tokio_rustls::TlsAcceptor::from(tls.config);
                                        match tokio::time::timeout(
                                            tls_handshake_timeout,
                                            acceptor.accept(stream),
                                        )
                                        .await
                                        {
                                            Ok(Ok(tls_stream)) => {
                                                let (reader, writer) = tokio::io::split(tls_stream);
                                                handle_connection(
                                                    Some(addr),
                                                    reader,
                                                    ConnWriter::Tls(writer),
                                                    router,
                                                    security,
                                                    read_timeout,
                                                    header_timeout,
                                                    body_timeout,
                                                    max_header_bytes,
                                                    max_body_bytes,
                                                    &route_body_limits,
                                                    response_timeout,
                                                )
                                                .await
                                            }
                                            Ok(Err(error)) => Err(Error::Tls(error.to_string())),
                                            Err(_) => Err(Error::Tls("TLS handshake timeout".into())),
                                        }
                                    } else {
                                        let (reader, writer) = stream.into_split();
                                        handle_connection(
                                            Some(addr),
                                            reader,
                                            ConnWriter::Tcp(writer),
                                            router,
                                            security,
                                            read_timeout,
                                            header_timeout,
                                            body_timeout,
                                            max_header_bytes,
                                            max_body_bytes,
                                            &route_body_limits,
                                            response_timeout,
                                        )
                                        .await
                                    }
                                }
                                #[cfg(not(feature = "tls"))]
                                {
                                    let (reader, writer) = stream.into_split();
                                    handle_connection(
                                        Some(addr),
                                        reader,
                                        ConnWriter::Tcp(writer),
                                        router,
                                        security,
                                        read_timeout,
                                        header_timeout,
                                        body_timeout,
                                    max_header_bytes,
                                    max_body_bytes,
                                    &route_body_limits,
                                    response_timeout,
                                    )
                                    .await
                                }
                            };
                            if let Err(e) = result {
                                tracing::debug!("http connection error: {e}");
                            }
                        });
                    }
                    _ = cancel.cancelled() => break,
                }
                // 回收已结束的连接任务。
                //
                // **不能把 `join_next()` 放进 select!**:实测那样会让 TLS 握手卡死
                // (同一台板上 accept 18 次只有 6 次握手完成,curl 约 50% 失败;
                // 去掉这个分支后 6/6 全部成功)。改成每轮循环末尾同步抽干已完成的
                // 任务 —— `try_join_next()` 不会注册 waker,不影响 accept。
                //
                // 不回收的话,完成的任务会一直留在 JoinSet 里(每个任务带着自己的
                // 分配,实测约 10 KB/连接),表现为「每来一个连接就涨 10 KB」。
                while tasks.try_join_next().is_some() {}
            }
            let _ = tokio::time::timeout(shutdown_timeout, async {
                while tasks.join_next().await.is_some() {}
            })
            .await;
            tasks.abort_all();
        });

        tracing::info!("http server listening on {}", self.local_addr);
        Ok(())
    }

    pub fn shutdown(&self) {
        self.cancel.cancel();
    }

    /// Cancellation token shared with the accept loop, for supervisors that
    /// need to stop HTTP together with other protocol servers.
    pub fn cancellation_token(&self) -> tokio_util::sync::CancellationToken {
        self.cancel.clone()
    }
}

#[allow(clippy::too_many_arguments)]
async fn handle_connection<R>(
    peer: Option<SocketAddr>,
    mut read_half: R,
    write_half: ConnWriter,
    router: Arc<RwLock<Router>>,
    security: SecurityConfig,
    read_timeout: Duration,
    header_timeout: Duration,
    body_timeout: Duration,
    max_header_bytes: usize,
    max_body_bytes: usize,
    route_body_limits: &[(String, usize)],
    response_timeout: Duration,
) -> Result<()>
where
    R: tokio::io::AsyncRead + Unpin,
{
    // ACL check
    if let Some(peer_addr) = peer
        && !security.ip_acl.permits(peer_addr.ip())
    {
        return Err(Error::Unauthorized);
    }

    let mut writer =
        Some(ResponseWriter::new(write_half).with_write_timeout(Some(response_timeout)));
    let mut buf = Vec::with_capacity(READ_BUF_SIZE);
    // 慢速攻击(slowloris)防护:从这里开始算这一条请求的总预算,
    // 而不是每次 recv 单独计时 —— 每秒挤一个字节的连接也会被断开。
    let mut request_started: Option<std::time::Instant> = None;

    loop {
        let started = *request_started.get_or_insert_with(std::time::Instant::now);
        let limit = if buf.windows(4).any(|w| w == b"\r\n\r\n") {
            body_timeout
        } else {
            header_timeout
        };
        let elapsed = started.elapsed();
        if elapsed >= limit {
            // 半截请求 + 超预算:断开,别让它占着连接槽。
            if let Some(writer) = writer.as_mut() {
                let _ = writer
                    .write_body(408, "text/plain", b"Request Timeout")
                    .await;
            }
            return Err(Error::Limit("request timeout"));
        }
        let budget = (limit - elapsed).min(read_timeout);
        // Read request
        let mut temp = [0u8; READ_BUF_SIZE];
        let n = tokio::time::timeout(
            budget,
            tokio::io::AsyncReadExt::read(&mut read_half, &mut temp),
        )
        .await
        .map_err(|_| Error::Limit("read timeout"))?
        .map_err(Error::Io)?;

        if n == 0 {
            break;
        }
        buf.extend_from_slice(&temp[..n]);

        // Try to parse request
        let req = match request::parse_request_with_limits(
            &buf,
            max_header_bytes,
            max_body_bytes,
            route_body_limits,
        ) {
            Ok(Some((req, consumed))) => {
                buf.drain(..consumed);
                request_started = None;
                let mut req = req;
                req.peer = peer;
                req
            }
            Ok(None) => {
                if buf.len() > max_header_bytes {
                    return Err(Error::Limit("request headers too large"));
                }
                continue;
            }
            Err(request::ParseError::Incomplete) => continue,
            Err(request::ParseError::TooLarge) => {
                // 用 413 明确告诉客户端是「包太大」,而不是让它以为连接坏了。
                if let Some(writer) = writer.as_mut() {
                    let _ = writer
                        .write_body(413, "text/plain", b"Payload Too Large")
                        .await;
                }
                return Err(Error::Limit("request too large"));
            }
            Err(request::ParseError::Invalid) => {
                // Reply 400 instead of dropping the connection so the
                // client can distinguish a protocol error from a network
                // failure.
                if let Some(writer) = writer.as_mut() {
                    let _ = writer.write_body(400, "text/plain", b"Bad Request").await;
                }
                return Err(Error::Http("invalid HTTP request".into()));
            }
        };

        tracing::trace!(peer = ?peer, method = ?req.method, path = %req.path, "HTTP request");
        let keep_alive = !req
            .header("connection")
            .is_some_and(|value| value.eq_ignore_ascii_case("close"));

        let req_method = req.method.clone();
        let req_path = req.path.clone();
        let mut w = writer.take().expect("writer should be available");
        // Keep-alive: the same writer serves multiple requests; clear the
        // previous response's state (headers_written/connection_close)
        // before handing it to the next handler.
        w.reset();
        let guard = router.read().await;
        let (handler, params) = guard.route(&req.method, &req.path.clone());
        let handler = handler.clone();
        let mut req = req;
        // Route matching uses the encoded path; handlers should see the
        // decoded form so names containing `/` (encoded as %2F) work.
        req.path = request::percent_decode(&req.path);
        req.path_params = params
            .into_iter()
            .map(|param| request::percent_decode(&param))
            .collect();
        drop(guard);

        match handler(req, w).await {
            Ok(returned_writer) => {
                let close = returned_writer.should_close();
                writer = Some(returned_writer);
                if close {
                    break;
                }
            }
            Err(e) => {
                // 播放器(VLC/ffmpeg/浏览器)切换码流、拖动、关页面时会直接断开正在下载的连接,
                // 这类「对端已关闭」不是设备的问题,用 debug 记,别拿 WARN 刷日志。
                let msg = e.to_string();
                let peer_gone = msg.contains("Connection reset by peer")
                    || msg.contains("Broken pipe")
                    || msg.contains("connection closed")
                    || msg.contains("UnexpectedEof");
                if peer_gone {
                    tracing::debug!(peer = ?peer, method = ?req_method, path = %req_path, %e, "客户端提前断开");
                } else {
                    tracing::warn!(peer = ?peer, method = ?req_method, path = %req_path, %e, "HTTP handler error");
                }
                break;
            }
        }

        if !keep_alive {
            break;
        }
    }

    // 收尾:优雅关闭写半边(TLS 走 close_notify、TCP 走 FIN)。
    // 直接 drop 掉 socket 时,内核会把「已发出但客户端还没读走」的数据连同
    // RST 一起丢掉 —— 实测 HTTPS 下 20 次请求只有 6 次能拿到响应。
    if let Some(mut w) = writer.take() {
        let _ = w.flush().await;
        let mut inner = w.into_inner();
        let _ = tokio::io::AsyncWriteExt::shutdown(&mut inner).await;
    }

    Ok(())
}