use tokio::io::{AsyncRead, AsyncReadExt, BufReader};
use crate::error::ConnectError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(
clippy::struct_field_names,
reason = "bounds share the `max_` prefix by domain convention; the four limits are always configured together"
)]
pub struct ConnectResponseLimits {
pub max_status_line: usize,
pub max_header_line: usize,
pub max_headers_bytes: usize,
pub max_header_count: usize,
}
impl Default for ConnectResponseLimits {
fn default() -> Self {
Self {
max_status_line: 4096,
max_header_line: 8192,
max_headers_bytes: 65_536,
max_header_count: 100,
}
}
}
impl ConnectResponseLimits {
#[must_use]
pub fn new(
max_status_line: usize,
max_header_line: usize,
max_headers_bytes: usize,
max_header_count: usize,
) -> Self {
Self {
max_status_line,
max_header_line,
max_headers_bytes,
max_header_count,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConnectResponseHead {
pub status: u16,
pub headers: Vec<(String, Vec<u8>)>,
pub reason_phrase: Option<Vec<u8>>,
}
pub async fn read_connect_response_head<S>(
stream: &mut BufReader<S>,
limits: &ConnectResponseLimits,
) -> Result<ConnectResponseHead, ConnectError>
where
S: AsyncRead + Unpin,
{
let status_line = read_bounded_line(stream, limits.max_status_line)
.await
.map_err(|error| match error {
ConnectError::HeaderLineTooLarge { .. } => ConnectError::StatusLineTooLarge {
max: limits.max_status_line,
},
other => other,
})?;
if status_line.is_empty() {
return Err(ConnectError::MalformedStatus);
}
let mut parts = status_line.splitn(3, |byte| *byte == b' ');
let _version = parts.next();
let status = parts
.next()
.and_then(|token| std::str::from_utf8(token).ok())
.and_then(|text| text.parse::<u16>().ok())
.ok_or(ConnectError::MalformedStatus)?;
let reason_phrase = parts.next().map(<[u8]>::to_vec);
let reason_phrase = reason_phrase.filter(|phrase| !phrase.is_empty());
let mut headers = Vec::new();
let mut total_header_bytes: usize = 0;
loop {
let line = read_bounded_line(stream, limits.max_header_line).await?;
if line.is_empty() {
break;
}
total_header_bytes = total_header_bytes.checked_add(line.len()).ok_or(
ConnectError::ResponseHeadTooLarge {
max: limits.max_headers_bytes,
},
)?;
if total_header_bytes > limits.max_headers_bytes {
return Err(ConnectError::ResponseHeadTooLarge {
max: limits.max_headers_bytes,
});
}
if headers.len() >= limits.max_header_count {
return Err(ConnectError::TooManyHeaders {
max: limits.max_header_count,
});
}
let colon = line
.iter()
.position(|byte| *byte == b':')
.ok_or(ConnectError::MalformedHeader)?;
let name_bytes = trim_ows(&line[..colon]);
let value_bytes = trim_ows(&line[colon + 1..]);
let name = std::str::from_utf8(name_bytes).map_err(|_| ConnectError::MalformedHeader)?;
validate_response_header_name(name)?;
headers.push((name.to_owned(), value_bytes.to_vec()));
}
Ok(ConnectResponseHead {
status,
headers,
reason_phrase,
})
}
async fn read_bounded_line<S>(
stream: &mut BufReader<S>,
max_len: usize,
) -> Result<Vec<u8>, ConnectError>
where
S: AsyncRead + Unpin,
{
let mut buf = Vec::with_capacity(256.min(max_len.saturating_add(1)));
let mut byte = [0_u8; 1];
loop {
let n = stream.read(&mut byte).await?;
if n == 0 {
return Err(ConnectError::UnexpectedEof);
}
if byte[0] == b'\n' {
break;
}
buf.push(byte[0]);
if buf.len() > max_len {
return Err(ConnectError::HeaderLineTooLarge { max: max_len });
}
}
if buf.last() == Some(&b'\r') {
buf.pop();
}
Ok(buf)
}
fn trim_ows(value: &[u8]) -> &[u8] {
let start = value
.iter()
.position(|byte| !matches!(byte, b' ' | b'\t'))
.unwrap_or(value.len());
let end = value
.iter()
.rposition(|byte| !matches!(byte, b' ' | b'\t'))
.map_or(start, |index| index + 1);
&value[start..end]
}
fn validate_response_header_name(name: &str) -> Result<(), ConnectError> {
if name.is_empty() || name.len() > 256 {
return Err(ConnectError::MalformedHeader);
}
for byte in name.bytes() {
if !is_token_byte(byte) {
return Err(ConnectError::MalformedHeader);
}
}
Ok(())
}
fn is_token_byte(byte: u8) -> bool {
matches!(
byte,
b'!' | b'#'
| b'$'
| b'%'
| b'&'
| b'\''
| b'*'
| b'+'
| b'-'
| b'.'
| b'^'
| b'_'
| b'`'
| b'|'
| b'~'
| b'0'..=b'9'
| b'A'..=b'Z'
| b'a'..=b'z'
)
}