Skip to main content

eggfetch_http_connect/
response.rs

1//! Bounded CONNECT response-head parser.
2//!
3//! The parser operates on a caller-owned [`tokio::io::BufReader`] so bytes
4//! already read past `\r\n\r\n` stay buffered for the tunnel. It returns
5//! the status without imposing any success policy and never consumes the
6//! response body.
7
8use tokio::io::{AsyncRead, AsyncReadExt, BufReader};
9
10use crate::error::ConnectError;
11
12/// Caller-provided bounds for a CONNECT response head.
13///
14/// `max_header_count` counts actual header fields only; the status line
15/// and the terminal blank line are not counted. Aggregate accounting sums
16/// the lengths of header lines without their trailing `CRLF`, excluding
17/// the status line and terminator.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19#[allow(
20    clippy::struct_field_names,
21    reason = "bounds share the `max_` prefix by domain convention; the four limits are always configured together"
22)]
23pub struct ConnectResponseLimits {
24    /// Maximum status-line length in bytes (without `CRLF`).
25    pub max_status_line: usize,
26    /// Maximum single header-line length in bytes (without `CRLF`).
27    pub max_header_line: usize,
28    /// Maximum aggregate header bytes (sum of header-line lengths).
29    pub max_headers_bytes: usize,
30    /// Maximum number of header fields.
31    pub max_header_count: usize,
32}
33
34impl Default for ConnectResponseLimits {
35    /// Eggfetch-oriented defaults matching the historical proxy parser.
36    fn default() -> Self {
37        Self {
38            max_status_line: 4096,
39            max_header_line: 8192,
40            max_headers_bytes: 65_536,
41            max_header_count: 100,
42        }
43    }
44}
45
46impl ConnectResponseLimits {
47    /// Create explicit limits.
48    #[must_use]
49    pub fn new(
50        max_status_line: usize,
51        max_header_line: usize,
52        max_headers_bytes: usize,
53        max_header_count: usize,
54    ) -> Self {
55        Self {
56            max_status_line,
57            max_header_line,
58            max_headers_bytes,
59            max_header_count,
60        }
61    }
62}
63
64/// Parsed CONNECT response head.
65///
66/// Header values are raw bytes (`obs-text` preserved); no whole-head or
67/// header-value UTF-8 is required. Duplicate response headers are
68/// preserved in order.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct ConnectResponseHead {
71    /// Numeric status code (returned intact; no success policy applied).
72    pub status: u16,
73    /// Response headers as `(name, raw value)` pairs.
74    pub headers: Vec<(String, Vec<u8>)>,
75    /// Raw reason phrase bytes when present.
76    pub reason_phrase: Option<Vec<u8>>,
77}
78
79/// Read one CONNECT response head from a buffered stream.
80///
81/// The stream must already be connected; this function performs no dialing,
82/// TLS, timeout, or retry. Bytes buffered past the head terminator remain
83/// in `stream`'s buffer for the caller to drain. The response body is never
84/// consumed.
85///
86/// # Errors
87///
88/// Returns [`ConnectError`] on I/O failure, truncation, malformed status or
89/// header lines, or when any caller-provided bound is exceeded. Error
90/// messages never echo unbounded proxy-controlled bytes.
91pub async fn read_connect_response_head<S>(
92    stream: &mut BufReader<S>,
93    limits: &ConnectResponseLimits,
94) -> Result<ConnectResponseHead, ConnectError>
95where
96    S: AsyncRead + Unpin,
97{
98    let status_line = read_bounded_line(stream, limits.max_status_line)
99        .await
100        .map_err(|error| match error {
101            ConnectError::HeaderLineTooLarge { .. } => ConnectError::StatusLineTooLarge {
102                max: limits.max_status_line,
103            },
104            other => other,
105        })?;
106
107    if status_line.is_empty() {
108        return Err(ConnectError::MalformedStatus);
109    }
110
111    let mut parts = status_line.splitn(3, |byte| *byte == b' ');
112    let _version = parts.next();
113    let status = parts
114        .next()
115        .and_then(|token| std::str::from_utf8(token).ok())
116        .and_then(|text| text.parse::<u16>().ok())
117        .ok_or(ConnectError::MalformedStatus)?;
118    let reason_phrase = parts.next().map(<[u8]>::to_vec);
119    // Reject empty reason marker? `splitn` yields an empty third part for a
120    // trailing space (e.g. "HTTP/1.1 200 "); normalize it to `None` so
121    // callers see absence rather than an empty phrase.
122    let reason_phrase = reason_phrase.filter(|phrase| !phrase.is_empty());
123
124    let mut headers = Vec::new();
125    let mut total_header_bytes: usize = 0;
126    loop {
127        let line = read_bounded_line(stream, limits.max_header_line).await?;
128        if line.is_empty() {
129            break;
130        }
131        total_header_bytes = total_header_bytes.checked_add(line.len()).ok_or(
132            ConnectError::ResponseHeadTooLarge {
133                max: limits.max_headers_bytes,
134            },
135        )?;
136        if total_header_bytes > limits.max_headers_bytes {
137            return Err(ConnectError::ResponseHeadTooLarge {
138                max: limits.max_headers_bytes,
139            });
140        }
141        if headers.len() >= limits.max_header_count {
142            return Err(ConnectError::TooManyHeaders {
143                max: limits.max_header_count,
144            });
145        }
146        let colon = line
147            .iter()
148            .position(|byte| *byte == b':')
149            .ok_or(ConnectError::MalformedHeader)?;
150        let name_bytes = trim_ows(&line[..colon]);
151        let value_bytes = trim_ows(&line[colon + 1..]);
152        let name = std::str::from_utf8(name_bytes).map_err(|_| ConnectError::MalformedHeader)?;
153        validate_response_header_name(name)?;
154        headers.push((name.to_owned(), value_bytes.to_vec()));
155    }
156
157    Ok(ConnectResponseHead {
158        status,
159        headers,
160        reason_phrase,
161    })
162}
163
164/// Read one CRLF-terminated line without the terminator.
165///
166/// Returns [`ConnectError::UnexpectedEof`] on EOF before `\n`, and
167/// [`ConnectError::HeaderLineTooLarge`] when `max_len` is exceeded. The
168/// caller maps the status-line case to `StatusLineTooLarge`.
169async fn read_bounded_line<S>(
170    stream: &mut BufReader<S>,
171    max_len: usize,
172) -> Result<Vec<u8>, ConnectError>
173where
174    S: AsyncRead + Unpin,
175{
176    let mut buf = Vec::with_capacity(256.min(max_len.saturating_add(1)));
177    let mut byte = [0_u8; 1];
178    loop {
179        let n = stream.read(&mut byte).await?;
180        if n == 0 {
181            return Err(ConnectError::UnexpectedEof);
182        }
183        if byte[0] == b'\n' {
184            break;
185        }
186        buf.push(byte[0]);
187        if buf.len() > max_len {
188            return Err(ConnectError::HeaderLineTooLarge { max: max_len });
189        }
190    }
191    if buf.last() == Some(&b'\r') {
192        buf.pop();
193    }
194    Ok(buf)
195}
196
197/// Strip optional whitespace (`SP`/`HTAB`) around a header field.
198fn trim_ows(value: &[u8]) -> &[u8] {
199    let start = value
200        .iter()
201        .position(|byte| !matches!(byte, b' ' | b'\t'))
202        .unwrap_or(value.len());
203    let end = value
204        .iter()
205        .rposition(|byte| !matches!(byte, b' ' | b'\t'))
206        .map_or(start, |index| index + 1);
207    &value[start..end]
208}
209
210/// Validate a response header name as an HTTP token.
211fn validate_response_header_name(name: &str) -> Result<(), ConnectError> {
212    if name.is_empty() || name.len() > 256 {
213        return Err(ConnectError::MalformedHeader);
214    }
215    for byte in name.bytes() {
216        if !is_token_byte(byte) {
217            return Err(ConnectError::MalformedHeader);
218        }
219    }
220    Ok(())
221}
222
223/// HTTP `tchar` per RFC 9110 ยง5.1.
224fn is_token_byte(byte: u8) -> bool {
225    matches!(
226        byte,
227        b'!' | b'#'
228            | b'$'
229            | b'%'
230            | b'&'
231            | b'\''
232            | b'*'
233            | b'+'
234            | b'-'
235            | b'.'
236            | b'^'
237            | b'_'
238            | b'`'
239            | b'|'
240            | b'~'
241            | b'0'..=b'9'
242            | b'A'..=b'Z'
243            | b'a'..=b'z'
244    )
245}