use super::*;
pub(crate) fn prepare_h2_request(
config: &RequestConfig,
parts: &mut Parts,
has_body_stream: bool,
request: &mut Request,
target: &mut String,
) -> Result<H2PreparedRequest, RequestError> {
let max_body_size: usize = config.get_max_body_size();
let max_header_count: usize = config.get_max_header_count();
let max_header_key_size: usize = config.get_max_header_key_size();
let max_header_value_size: usize = config.get_max_header_value_size();
let mut declared_content_length: Option<usize> = None;
let mut cl_error: Option<RequestError> = None;
let mut expect_continue: bool = false;
let mut host_count: usize = 0;
let mut host_val: Option<&str> = None;
let mut host_invalid: bool = false;
let mut colon_authority_val: Option<&str> = None;
let mut colon_authority_invalid: bool = false;
let mut header_count: usize = 0;
let mut header_error: Option<RequestError> = None;
let target_headers: &mut RequestHeaders = request.get_mut_headers();
let forbidden_res: Result<(), RequestError> =
PROTOCOL_HEADER_POOL.with(|pool: &RefCell<Vec<(String, VecDeque<String>)>>| {
let mut pool_guard: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
for (name, value) in parts.headers.iter() {
let key: &str = name.as_str();
if key.starts_with(PSEUDO_HEADER_PREFIX) {
if key == COLON_AUTHORITY
&& colon_authority_val.is_none()
&& !colon_authority_invalid
{
match value.to_str() {
Ok(val) => colon_authority_val = Some(val),
Err(_) => colon_authority_invalid = true,
}
}
continue;
}
if is_forbidden_h2_header(key, value.as_bytes()) {
return Err(RequestError::HttpRead(HttpStatus::BadRequest));
}
if key == CONTENT_LENGTH {
if declared_content_length.is_some() {
if cl_error.is_none() {
cl_error =
Some(RequestError::InvalidContentLength(HttpStatus::BadRequest));
}
} else if cl_error.is_none() {
match value.to_str() {
Ok(val_str) => match parse_ascii_length(val_str) {
Ok(parsed) => {
if parsed > max_body_size
&& max_body_size != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE
{
cl_error = Some(RequestError::ContentLengthTooLarge(
HttpStatus::PayloadTooLarge,
));
} else {
declared_content_length = Some(parsed);
}
}
Err(err) => cl_error = Some(err),
},
Err(_) => {
cl_error = Some(RequestError::InvalidContentLength(
HttpStatus::BadRequest,
));
}
}
}
} else if key == HOST {
host_count += 1;
if host_count == 1 {
match value.to_str() {
Ok(val_str) => host_val = Some(val_str),
Err(_) => host_invalid = true,
}
}
} else if has_body_stream
&& !expect_continue
&& key == EXPECT
&& contains_continue_member(value.as_bytes())
{
expect_continue = true;
}
let Ok(val_str) = value.to_str() else {
if header_error.is_none() {
header_error = Some(RequestError::HttpRead(HttpStatus::BadRequest));
}
continue;
};
header_count += 1;
if header_count > max_header_count
&& max_header_count != DEFAULT_LOW_SECURITY_MAX_HEADER_COUNT
{
if header_error.is_none() {
header_error = Some(RequestError::TooManyHeaders(
HttpStatus::RequestHeaderFieldsTooLarge,
));
}
continue;
}
if key.len() > max_header_key_size
&& max_header_key_size != DEFAULT_LOW_SECURITY_MAX_HEADER_KEY_SIZE
{
if header_error.is_none() {
header_error = Some(RequestError::HeaderKeyTooLong(HttpStatus::BadRequest));
}
continue;
}
if val_str.len() > max_header_value_size
&& max_header_value_size != DEFAULT_LOW_SECURITY_MAX_HEADER_VALUE_SIZE
{
if header_error.is_none() {
header_error =
Some(RequestError::HeaderValueTooLong(HttpStatus::BadRequest));
}
continue;
}
insert_pooled_map_entry(target_headers, &mut pool_guard, key, val_str);
}
Ok(())
});
forbidden_res?;
if let Some(error) = cl_error {
return Err(error);
}
let uri: &Uri = &parts.uri;
let raw_path: &str = uri.path();
let raw_query: Option<&str> = uri.query();
write_request_target(raw_path, raw_query, target);
let max_path_size: usize = config.get_max_path_size();
let mut deferred_error: Option<RequestError> =
if target.len() > max_path_size && max_path_size != DEFAULT_LOW_SECURITY_MAX_PATH_SIZE {
Some(RequestError::PathTooLong(HttpStatus::URITooLong))
} else {
None
};
let authority: Option<&str> = uri
.authority()
.map(|authority: &Authority| authority.as_str());
let effective_host: Option<&str> = if host_count > 0 {
host_val
} else {
colon_authority_val
};
if deferred_error.is_none() {
let authority_bad: bool = match authority {
Some(val) => !is_valid_authority_value(val),
None => false,
};
let effective_host_bad: bool = match effective_host {
Some(val) => !is_valid_authority_value(val),
None => false,
};
let authority_mismatch: bool = match (authority, effective_host) {
(Some(auth), Some(host)) => !same_authority(auth, host, uri.scheme_str()),
_ => false,
};
let host_bad: bool = host_count > 1
|| host_invalid
|| (host_count == 0 && colon_authority_invalid)
|| authority_bad
|| effective_host_bad
|| authority_mismatch;
if host_bad {
deferred_error = Some(RequestError::InvalidUrlHost(HttpStatus::BadRequest));
} else {
deferred_error = header_error;
}
}
if deferred_error.is_none() {
request.get_mut_querys().clear();
let (clean_path, clean_query): (&str, &str) = match raw_path.find(HASH) {
Some(hash_index) => (&raw_path[..hash_index], EMPTY_STR),
None => match raw_query {
Some(query) => match query.find(HASH) {
Some(hash_index) => (raw_path, &query[..hash_index]),
None => (raw_path, query),
},
None => (raw_path, EMPTY_STR),
},
};
if !clean_query.is_empty() {
fill_request_querys(clean_query, request.get_mut_querys());
}
let req_path: &mut String = request.get_mut_path();
req_path.clear();
req_path.push_str(clean_path);
request.set_method(protocol_method(mem::take(&mut parts.method)));
request.set_version(HttpVersion::Http2);
let host_out: &mut String = request.get_mut_host();
host_out.clear();
if let Some(auth) = authority {
host_out.push_str(auth);
} else if let Some(host) = effective_host {
host_out.push_str(host);
}
}
Ok(H2PreparedRequest {
declared_content_length,
expect_continue: expect_continue && declared_content_length != Some(0),
deferred_error,
})
}
#[inline(always)]
pub(crate) fn insert_pooled_map_entry(
map: &mut RequestHeaders,
pool: &mut Vec<(String, VecDeque<String>)>,
key: &str,
value: &str,
) {
if let Some(existing) = map.get_mut(key) {
existing.push_back(value.to_owned());
return;
}
let (mut pooled_key, mut pooled_values): (String, VecDeque<String>) = pool
.pop()
.unwrap_or_else(|| (String::new(), VecDeque::new()));
pooled_key.clear();
pooled_key.push_str(key);
while pooled_values.len() > 1 {
pooled_values.pop_back();
}
if let Some(slot) = pooled_values.front_mut() {
slot.clear();
slot.push_str(value);
} else {
pooled_values.push_back(value.to_owned());
}
map.insert(pooled_key, pooled_values);
}
#[inline(always)]
pub(crate) fn insert_pooled_empty_query_entry(
map: &mut RequestQuerys,
pool: &mut Vec<(String, VecDeque<String>)>,
key: &str,
) {
if map.contains_key(key) {
return;
}
let (mut pooled_key, mut pooled_values): (String, VecDeque<String>) = pool
.pop()
.unwrap_or_else(|| (String::new(), VecDeque::new()));
pooled_key.clear();
pooled_key.push_str(key);
pooled_values.clear();
map.insert(pooled_key, pooled_values);
}
pub(crate) fn write_request_target(path: &str, query: Option<&str>, target: &mut String) {
target.clear();
match query {
Some(query) => {
target.reserve(path.len() + query.len() + 1);
target.push_str(path);
target.push(QUESTION_MARK);
target.push_str(query);
}
None => {
target.push_str(path);
}
}
}
pub(crate) fn is_valid_authority_value(value: &str) -> bool {
if value.is_empty() {
return false;
}
for byte in value.bytes() {
if byte <= 0x20 || byte >= 0x7f || FORBIDDEN_AUTHORITY_BYTES.contains(&byte) {
return false;
}
}
let (host, port): (&str, Option<&str>) = split_authority_port(value);
if host.is_empty() {
return false;
}
if host.starts_with('[') {
let Some(inner) = host
.strip_prefix('[')
.and_then(|s: &str| s.strip_suffix(']'))
else {
return false;
};
if inner.is_empty()
|| !inner
.bytes()
.all(|b: u8| b.is_ascii_hexdigit() || b == b':' || b == b'.')
{
return false;
}
} else if host.contains('[') || host.contains(']') || host.contains(':') {
return false;
}
if let Some(port) = port {
let all_digits: bool = port.bytes().all(|b: u8| b.is_ascii_digit());
if port.is_empty() || !all_digits {
return false;
}
if port.parse::<u16>().is_err() {
return false;
}
}
true
}
fn is_forbidden_h2_header(name: &str, value: &[u8]) -> bool {
match name {
CONNECTION | KEEP_ALIVE | PROXY_CONNECTION | TRANSFER_ENCODING | UPGRADE => true,
TE => !value.eq_ignore_ascii_case(HTTP_TE_TRAILERS.as_bytes()),
_ => false,
}
}
#[cfg(test)]
pub fn check_request_authority(headers: &ProtocolHeaders, uri: &Uri) -> Result<(), RequestError> {
let host_count: usize = headers.get_all(HOST).iter().count();
if host_count > 1 {
return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest));
}
let authority: Option<&str> = uri
.authority()
.map(|authority: &Authority| authority.as_str());
let host: Option<&str> = match headers.get(HOST) {
Some(value) => match value.to_str() {
Ok(value) => Some(value),
Err(_) => return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest)),
},
None => match headers.get(COLON_AUTHORITY) {
Some(value) => match value.to_str() {
Ok(value) => Some(value),
Err(_) => return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest)),
},
None => None,
},
};
if let Some(authority) = authority
&& !is_valid_authority_value(authority)
{
return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest));
}
if let Some(host) = host
&& !is_valid_authority_value(host)
{
return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest));
}
let (Some(authority), Some(host)) = (authority, host) else {
return Ok(());
};
let scheme: Option<&str> = uri.scheme_str();
if !same_authority(authority, host, scheme) {
return Err(RequestError::InvalidUrlHost(HttpStatus::BadRequest));
}
Ok(())
}
pub fn same_authority(authority: &str, host: &str, scheme: Option<&str>) -> bool {
if authority.eq_ignore_ascii_case(host) {
return true;
}
let (auth_host, auth_port): (&str, Option<&str>) = split_authority_port(authority);
let (host_host, host_port): (&str, Option<&str>) = split_authority_port(host);
if !auth_host.eq_ignore_ascii_case(host_host) {
return false;
}
let default_port: Option<&str> = match scheme {
Some(HTTP_SCHEME) => Some(DEFAULT_HTTP_PORT_STR),
Some(HTTPS_SCHEME) => Some(DEFAULT_HTTPS_PORT_STR),
_ => None,
};
let effective_auth_port: Option<&str> = match (auth_port, default_port) {
(Some(port), Some(default_port)) if port == default_port => None,
(port, _) => port,
};
let effective_host_port: Option<&str> = match (host_port, default_port) {
(Some(port), Some(default_port)) if port == default_port => None,
(port, _) => port,
};
effective_auth_port == effective_host_port
}
#[cfg(test)]
pub fn normalize_authority(authority: &str, scheme: Option<&str>) -> (String, Option<String>) {
let (host, port): (&str, Option<&str>) = split_authority_port(authority);
let host: String = host.to_ascii_lowercase();
let port: Option<String> = port.map(|port: &str| port.to_owned());
let default_port: Option<&str> = match scheme {
Some(HTTP_SCHEME) => Some(DEFAULT_HTTP_PORT_STR),
Some(HTTPS_SCHEME) => Some(DEFAULT_HTTPS_PORT_STR),
_ => None,
};
match (port, default_port) {
(Some(port), Some(default_port)) if port == default_port => (host, None),
(port, _) => (host, port),
}
}
pub fn split_authority_port(authority: &str) -> (&str, Option<&str>) {
let authority: &str = authority.trim();
if authority.starts_with('[') {
return match authority.find(']') {
Some(end) => match authority[end + 1..].strip_prefix(':') {
Some(port) => (&authority[..end + 1], Some(port)),
None => (authority, None),
},
None => (authority, None),
};
}
match authority.rsplit_once(':') {
Some((host, port)) if !host.is_empty() && !host.contains(':') => (host, Some(port)),
_ => (authority, None),
}
}
pub fn fill_request_querys(query: &str, querys: &mut RequestQuerys) {
if query.is_empty() {
return;
}
PROTOCOL_HEADER_POOL.with(|pool: &RefCell<Vec<(String, VecDeque<String>)>>| {
let mut pool_guard: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
let mut param_count: usize = 0;
for pair in query.split(AND) {
if param_count >= PROTOCOL_MAX_QUERY_PARAM_COUNT {
break;
}
if let Some((key, value)) = pair.split_once(EQUAL) {
if !key.is_empty() {
param_count += 1;
insert_pooled_map_entry(querys, &mut pool_guard, key, value);
}
} else if !pair.is_empty() {
param_count += 1;
insert_pooled_empty_query_entry(querys, &mut pool_guard, pair);
}
}
});
}
pub fn protocol_method(method: ProtocolMethod) -> RequestMethod {
if method == ProtocolMethod::GET {
return Method::Get;
}
if method == ProtocolMethod::POST {
return Method::Post;
}
if method == ProtocolMethod::PUT {
return Method::Put;
}
if method == ProtocolMethod::DELETE {
return Method::Delete;
}
if method == ProtocolMethod::PATCH {
return Method::Patch;
}
if method == ProtocolMethod::HEAD {
return Method::Head;
}
if method == ProtocolMethod::OPTIONS {
return Method::Options;
}
if method == ProtocolMethod::CONNECT {
return Method::Connect;
}
if method == ProtocolMethod::TRACE {
return Method::Trace;
}
Method::Unknown(method.as_str().to_owned())
}
pub fn is_hop_by_hop(name: &str) -> bool {
matches!(
name,
CONNECTION
| KEEP_ALIVE
| PROXY_AUTHENTICATE
| PROXY_AUTHORIZATION
| TE
| TRAILER_HEADER
| TRANSFER_ENCODING
| UPGRADE
)
}
pub(crate) fn contains_continue_member(value: &[u8]) -> bool {
let token: &[u8] = CONTINUE_EXPECT.as_bytes();
let mut start: usize = 0;
let mut quoted: bool = false;
let mut escaped: bool = false;
for (offset, byte) in value.iter().copied().enumerate() {
match byte {
_ if escaped => escaped = false,
HTTP_QUOTED_FIELD_ESCAPE if quoted => escaped = true,
HTTP_QUOTED_FIELD_QUOTE => quoted = !quoted,
COMMA_U8 if !quoted => {
if value[start..offset]
.trim_ascii()
.eq_ignore_ascii_case(token)
{
return true;
}
start = offset + 1;
}
_ => {}
}
}
value[start..].trim_ascii().eq_ignore_ascii_case(token)
}
pub(crate) fn parse_ascii_length(value: &str) -> Result<usize, RequestError> {
let digits: &str = value.trim();
if digits.is_empty() || !digits.bytes().all(|byte: u8| byte.is_ascii_digit()) {
return Err(RequestError::InvalidContentLength(HttpStatus::BadRequest));
}
digits
.parse::<usize>()
.map_err(|_: ParseIntError| RequestError::InvalidContentLength(HttpStatus::BadRequest))
}
pub fn is_bodyless_status(status_code: usize, is_head: bool) -> bool {
is_head
|| status_code < 200
|| status_code == HttpStatus::NoContent.code()
|| status_code == HttpStatus::ResetContent.code()
|| status_code == HttpStatus::NotModified.code()
}
pub fn push_bounded_body(
limit: usize,
body: &mut Vec<u8>,
chunk: Bytes,
) -> Result<(), RequestError> {
if limit != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE && chunk.len() > limit.saturating_sub(body.len())
{
return Err(RequestError::ContentLengthTooLarge(
HttpStatus::PayloadTooLarge,
));
}
body.extend_from_slice(chunk.as_ref());
Ok(())
}
#[cfg(test)]
pub fn request_target(path: &str, query: Option<&str>) -> String {
match query {
Some(query) => {
let mut target: String = String::with_capacity(path.len() + query.len() + 1);
target.push_str(path);
target.push(QUESTION_MARK);
target.push_str(query);
target
}
None => path.to_owned(),
}
}