eggfetch_http_connect/
response.rs1use tokio::io::{AsyncRead, AsyncReadExt, BufReader};
9
10use crate::error::ConnectError;
11
12#[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 pub max_status_line: usize,
26 pub max_header_line: usize,
28 pub max_headers_bytes: usize,
30 pub max_header_count: usize,
32}
33
34impl Default for ConnectResponseLimits {
35 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 #[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#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct ConnectResponseHead {
71 pub status: u16,
73 pub headers: Vec<(String, Vec<u8>)>,
75 pub reason_phrase: Option<Vec<u8>>,
77}
78
79pub 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 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
164async 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
197fn 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
210fn 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
223fn 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}