Skip to main content

rtflow_http/
response.rs

1use rtflow_core::error::{Error, Result};
2use std::time::Duration;
3use tokio::io::{AsyncWrite, AsyncWriteExt};
4
5pub struct ResponseWriter<W: AsyncWrite + Unpin> {
6    inner: W,
7    headers_written: bool,
8    connection_close: bool,
9    /// Per-write deadline; `None` disables the guard (R22: a frozen peer
10    /// must not pin a connection slot forever).
11    write_timeout: Option<Duration>,
12    /// Bytes written since the last egress flush. The admission guard's
13    /// counter is process-wide, so reporting one atomic per write makes every
14    /// streaming connection contend on the same cache line.
15    egress: u64,
16}
17
18/// Flush accumulated egress bytes at this size.
19const EGRESS_FLUSH_BYTES: u64 = 64 * 1024;
20
21/// 每个响应都带的浏览器安全头(handler 自己写了同名头就以它为准)。
22///
23/// * nosniff:禁止浏览器把 JSON/文本当脚本或样式执行;
24/// * DENY:设备网页不允许被别的站点用 iframe 嵌入(防点击劫持);
25/// * no-referrer:跳转到外部链接时不泄露设备地址与查询串里的 token。
26const SECURITY_HEADERS: &[(&str, &str)] = &[
27    ("X-Content-Type-Options", "nosniff"),
28    ("X-Frame-Options", "DENY"),
29    ("Referrer-Policy", "no-referrer"),
30];
31
32impl<W: AsyncWrite + Unpin> ResponseWriter<W> {
33    pub fn new(writer: W) -> Self {
34        Self {
35            inner: writer,
36            headers_written: false,
37            connection_close: false,
38            write_timeout: None,
39            egress: 0,
40        }
41    }
42
43    /// Enforce a per-write deadline (see `crate::HttpConfig::response_timeout`).
44    pub fn with_write_timeout(mut self, timeout: Option<Duration>) -> Self {
45        self.write_timeout = timeout;
46        self
47    }
48
49    /// Reset per-response state so the same writer can serve the next
50    /// request on a keep-alive connection.
51    pub fn reset(&mut self) {
52        self.headers_written = false;
53        self.connection_close = false;
54    }
55
56    /// Write with the configured deadline (R22).
57    async fn write_all_with_timeout(&mut self, buf: &[u8]) -> Result<()> {
58        match self.write_timeout {
59            Some(timeout) => tokio::time::timeout(timeout, self.inner.write_all(buf))
60                .await
61                .map_err(|_| Error::Http("response write timed out".into()))??,
62            None => self.inner.write_all(buf).await?,
63        }
64        // 出口码率统计:HLS 分片、HTTP-FLV、网页/API 响应都从这里出去,
65        // 统一在这里记账(与 C 版的 guard_note_egress 对齐)。
66        self.record_egress(buf.len());
67        Ok(())
68    }
69
70    fn record_egress(&mut self, bytes: usize) {
71        self.egress = self
72            .egress
73            .saturating_add(u64::try_from(bytes).unwrap_or(u64::MAX));
74        if self.egress >= EGRESS_FLUSH_BYTES {
75            self.flush_egress();
76        }
77    }
78
79    fn flush_egress(&mut self) {
80        if self.egress > 0 {
81            rtflow_security::guard::global().note_egress(self.egress);
82            self.egress = 0;
83        }
84    }
85
86    /// Whether the response indicated the connection should be closed.
87    pub fn should_close(&self) -> bool {
88        self.connection_close
89    }
90
91    pub async fn write_headers(&mut self, status: u16, headers: &[(&str, &str)]) -> Result<()> {
92        if self.headers_written {
93            return Err(Error::Http("HTTP response headers already written".into()));
94        }
95        let reason = status_reason(status);
96        let mut buf = format!("HTTP/1.1 {} {}\r\n", status, reason);
97        for (key, value) in headers {
98            if key.eq_ignore_ascii_case("connection") && value.eq_ignore_ascii_case("close") {
99                self.connection_close = true;
100            }
101            buf.push_str(key);
102            buf.push_str(": ");
103            buf.push_str(value);
104            buf.push_str("\r\n");
105        }
106        for (key, value) in SECURITY_HEADERS {
107            if headers
108                .iter()
109                .any(|(existing, _)| existing.eq_ignore_ascii_case(key))
110            {
111                continue;
112            }
113            buf.push_str(key);
114            buf.push_str(": ");
115            buf.push_str(value);
116            buf.push_str("\r\n");
117        }
118        buf.push_str("\r\n");
119        self.write_all_with_timeout(buf.as_bytes()).await?;
120        self.headers_written = true;
121        Ok(())
122    }
123
124    pub async fn write_chunked_headers(
125        &mut self,
126        content_type: &str,
127        extra_headers: &[(&str, &str)],
128    ) -> Result<()> {
129        let mut headers = vec![
130            ("Transfer-Encoding", "chunked"),
131            ("Content-Type", content_type),
132            ("Cache-Control", "no-cache, no-store"),
133            ("Connection", "keep-alive"),
134        ];
135        for (k, v) in extra_headers {
136            headers.push((k, v));
137        }
138        self.write_headers(200, &headers).await
139    }
140
141    pub async fn write_chunk(&mut self, data: &[u8]) -> Result<()> {
142        if !self.headers_written {
143            return Err(Error::Http("HTTP chunk written before headers".into()));
144        }
145        if data.is_empty() {
146            return Ok(());
147        }
148        let header = format!("{:x}\r\n", data.len());
149        self.write_all_with_timeout(header.as_bytes()).await?;
150        self.write_all_with_timeout(data).await?;
151        self.write_all_with_timeout(b"\r\n").await?;
152        Ok(())
153    }
154
155    /// Write raw bytes directly to the stream (no chunked framing).
156    /// Use with `Transfer-Encoding: none` / `Connection: close` for streaming.
157    pub async fn write_raw(&mut self, data: &[u8]) -> Result<()> {
158        if data.is_empty() {
159            return Ok(());
160        }
161        self.write_all_with_timeout(data).await?;
162        Ok(())
163    }
164
165    pub async fn write_body(&mut self, status: u16, content_type: &str, body: &[u8]) -> Result<()> {
166        let content_length = body.len().to_string();
167        let headers = vec![
168            ("Content-Type", content_type),
169            ("Content-Length", content_length.as_str()),
170            ("Cache-Control", "no-cache"),
171            ("Connection", "close"),
172            // HLS playlists and other bodies are consumed cross-origin by
173            // browser players (hls.js etc).
174            ("Access-Control-Allow-Origin", "*"),
175        ];
176        self.write_headers(status, &headers).await?;
177        self.write_all_with_timeout(body).await?;
178        Ok(())
179    }
180
181    pub async fn write_json(&mut self, status: u16, json: &str) -> Result<()> {
182        self.write_body(status, "application/json", json.as_bytes())
183            .await
184    }
185
186    pub async fn flush(&mut self) -> Result<()> {
187        self.flush_egress();
188        self.inner.flush().await.map_err(Error::from)
189    }
190
191    pub fn into_inner(mut self) -> W {
192        self.flush_egress();
193        self.inner
194    }
195}
196
197fn status_reason(status: u16) -> &'static str {
198    match status {
199        200 => "OK",
200        201 => "Created",
201        204 => "No Content",
202        206 => "Partial Content",
203        301 => "Moved Permanently",
204        302 => "Found",
205        304 => "Not Modified",
206        400 => "Bad Request",
207        401 => "Unauthorized",
208        403 => "Forbidden",
209        404 => "Not Found",
210        405 => "Method Not Allowed",
211        408 => "Request Timeout",
212        409 => "Conflict",
213        416 => "Range Not Satisfiable",
214        429 => "Too Many Requests",
215        500 => "Internal Server Error",
216        502 => "Bad Gateway",
217        503 => "Service Unavailable",
218        _ => "Unknown",
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    async fn render(headers: &[(&str, &str)]) -> String {
227        let mut writer = ResponseWriter::new(Vec::new());
228        writer.write_headers(200, headers).await.expect("headers");
229        String::from_utf8_lossy(&writer.into_inner()).into_owned()
230    }
231
232    #[tokio::test]
233    async fn every_response_carries_security_headers() {
234        let text = render(&[]).await;
235        assert!(
236            text.contains("X-Content-Type-Options: nosniff\r\n"),
237            "{text}"
238        );
239        assert!(text.contains("X-Frame-Options: DENY\r\n"), "{text}");
240        assert!(text.contains("Referrer-Policy: no-referrer\r\n"), "{text}");
241    }
242
243    #[tokio::test]
244    async fn handler_supplied_header_wins_and_is_not_duplicated() {
245        let text = render(&[("X-Frame-Options", "SAMEORIGIN")]).await;
246        assert_eq!(text.matches("X-Frame-Options").count(), 1, "{text}");
247        assert!(text.contains("X-Frame-Options: SAMEORIGIN\r\n"), "{text}");
248        assert!(
249            text.contains("X-Content-Type-Options: nosniff\r\n"),
250            "{text}"
251        );
252    }
253}