use tracing::debug;
use super::error::{HttpHeaderError, Result};
use super::types::{
HttpHeaderParseState, HttpResponseHead, MAX_FIELD_NAME_LEN, MAX_FIELD_VALUE_LEN,
MAX_HEADER_SIZE,
};
pub struct HttpHeaderProcessor {
buf: Vec<u8>,
pub(crate) state: HttpHeaderParseState,
last_bytes_processed: usize,
}
impl HttpHeaderProcessor {
pub fn new() -> Self {
Self {
buf: Vec::with_capacity(512),
state: HttpHeaderParseState::ParsingStatusLine,
last_bytes_processed: 0,
}
}
pub fn feed(&mut self, data: &[u8]) -> &HttpHeaderParseState {
self.last_bytes_processed = 0;
if !matches!(
self.state,
HttpHeaderParseState::ParsingStatusLine | HttpHeaderParseState::ParsingHeaders
) {
return &self.state;
}
let prev_len = self.buf.len();
let append_limit = MAX_HEADER_SIZE.saturating_add(4);
let append_len = data.len().min(append_limit.saturating_sub(prev_len));
self.buf.extend_from_slice(&data[..append_len]);
if let Some(pos) = self.find_terminator() {
let header_end = pos + 4; self.buf.truncate(header_end); self.last_bytes_processed = header_end - prev_len;
self.state = HttpHeaderParseState::Complete;
debug!(header_bytes = header_end, "HTTP headers complete");
} else {
self.last_bytes_processed = data.len();
if matches!(self.state, HttpHeaderParseState::ParsingStatusLine)
&& Self::find_crlf(&self.buf, 0).is_some()
{
self.state = HttpHeaderParseState::ParsingHeaders;
}
if append_len < data.len() || self.buf.len() > MAX_HEADER_SIZE {
self.state = HttpHeaderParseState::Error("Too large HTTP header block".to_string());
debug!(buf_len = self.buf.len(), "Header block exceeds size limit");
}
}
&self.state
}
pub fn last_bytes_processed(&self) -> usize {
self.last_bytes_processed
}
pub fn get_result(&self) -> Result<HttpResponseHead> {
if !matches!(self.state, HttpHeaderParseState::Complete) {
return Err(HttpHeaderError("Headers not yet complete".to_string()));
}
let header_str = std::str::from_utf8(&self.buf)
.map_err(|e| HttpHeaderError(format!("Invalid UTF-8 in HTTP headers: {}", e)))?;
Self::parse_header_block(header_str)
}
pub fn get_header_string(&self) -> String {
String::from_utf8_lossy(&self.buf).to_string()
}
pub fn clear(&mut self) {
self.buf.clear();
self.state = HttpHeaderParseState::ParsingStatusLine;
self.last_bytes_processed = 0;
}
fn find_terminator(&self) -> Option<usize> {
self.buf.windows(4).position(|w| w == b"\r\n\r\n")
}
fn find_crlf(data: &[u8], from: usize) -> Option<usize> {
data[from..]
.windows(2)
.position(|w| w == b"\r\n")
.map(|p| from + p)
}
fn parse_header_block(header_str: &str) -> Result<HttpResponseHead> {
let header_str = header_str.strip_suffix("\r\n\r\n").unwrap_or(header_str);
let mut lines = header_str.lines();
let status_line = lines
.next()
.ok_or_else(|| HttpHeaderError("Empty HTTP response".to_string()))?;
let (http_version, status_code, reason_phrase) = Self::parse_status_line(status_line)?;
let headers = Self::parse_headers(lines)?;
let has_te = headers
.iter()
.any(|(k, _)| k.eq_ignore_ascii_case("transfer-encoding"));
let filtered = if has_te {
headers
.into_iter()
.filter(|(k, _)| {
!k.eq_ignore_ascii_case("content-length")
&& !k.eq_ignore_ascii_case("content-range")
})
.collect()
} else {
headers
};
Ok(HttpResponseHead::new(
http_version,
status_code,
reason_phrase,
filtered,
))
}
fn parse_status_line(line: &str) -> Result<(String, u16, String)> {
let mut parts = line.splitn(3, ' ');
let version = parts
.next()
.ok_or_else(|| HttpHeaderError("Bad Status-Line: missing HTTP-version".to_string()))?;
if !version.starts_with("HTTP/") {
return Err(HttpHeaderError(
"Bad Status-Line: missing HTTP-version".to_string(),
));
}
let code_str = parts
.next()
.ok_or_else(|| HttpHeaderError("Bad Status-Line: missing status-code".to_string()))?;
let status_code: u16 = code_str
.parse()
.map_err(|_| HttpHeaderError("Bad status code: invalid status-code".to_string()))?;
if status_code < 100 {
return Err(HttpHeaderError(
"Bad status code: status-code < 100".to_string(),
));
}
let reason_phrase = parts.next().unwrap_or("").to_string();
Ok((version.to_string(), status_code, reason_phrase))
}
fn parse_headers<'a, I: Iterator<Item = &'a str>>(lines: I) -> Result<Vec<(String, String)>> {
let mut headers: Vec<(String, String)> = Vec::new();
let mut current_name: Option<String> = None;
let mut current_value = String::new();
for line in lines {
if line.is_empty() {
continue;
}
if line.starts_with(' ') || line.starts_with('\t') {
if current_name.is_none() {
return Err(HttpHeaderError(
"Bad HTTP header: field name starts with LWS".to_string(),
));
}
if !current_value.is_empty() {
current_value.push(' ');
}
current_value.push_str(line.trim_start());
continue;
}
if let Some(name) = current_name.take() {
let value = current_value.trim().to_string();
Self::validate_field_sizes(&name, &value)?;
headers.push((name, value));
}
current_value.clear();
match line.find(':') {
Some(0) => {
return Err(HttpHeaderError(
"Bad HTTP header: field name starts with ':'".to_string(),
));
}
Some(pos) => {
let name = line[..pos].to_lowercase();
let value = line[pos + 1..].trim_start().to_string();
current_name = Some(name);
current_value = value;
}
None => {
return Err(HttpHeaderError("Bad HTTP header: missing ':'".to_string()));
}
}
}
if let Some(name) = current_name.take() {
let value = current_value.trim().to_string();
Self::validate_field_sizes(&name, &value)?;
headers.push((name, value));
}
Ok(headers)
}
fn validate_field_sizes(name: &str, value: &str) -> Result<()> {
if name.len() > MAX_FIELD_NAME_LEN {
return Err(HttpHeaderError(
"Too large HTTP header: field name exceeds limit".to_string(),
));
}
if value.len() > MAX_FIELD_VALUE_LEN {
return Err(HttpHeaderError(
"Too large HTTP header: field value exceeds limit".to_string(),
));
}
Ok(())
}
}
impl Default for HttpHeaderProcessor {
fn default() -> Self {
Self::new()
}
}