use super::*;
#[inline]
pub(crate) fn is_valid_wire_header_value_bytes(bytes: &[u8]) -> bool {
let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
for chunk in chunks {
let word: u64 = u64::from_ne_bytes(*chunk);
let mut mask: u64 = word & SWAR_HI_BITS;
mask |= word.wrapping_sub(SWAR_SPACES) & SWAR_HI_BITS;
mask |= word.wrapping_add(SWAR_LO_BITS) & SWAR_HI_BITS;
if mask != 0 {
for &byte in chunk {
if !HTTP_HEADER_VALUE_VALID_LUT[byte as usize] {
return false;
}
}
}
}
for &byte in rem {
if !HTTP_HEADER_VALUE_VALID_LUT[byte as usize] {
return false;
}
}
true
}
#[inline]
pub(crate) fn has_unsafe_header_chars(value: &str) -> bool {
let (chunks, rem): (&[[u8; 8]], &[u8]) = value.as_bytes().as_chunks::<8>();
for chunk in chunks {
let word: u64 = u64::from_ne_bytes(*chunk);
let z0: u64 = word.wrapping_sub(SWAR_LO_BITS) & !word;
let xlf: u64 = word ^ SWAR_LF_MASK;
let zlf: u64 = xlf.wrapping_sub(SWAR_LO_BITS) & !xlf;
let xcr: u64 = word ^ SWAR_CR_MASK;
let zcr: u64 = xcr.wrapping_sub(SWAR_LO_BITS) & !xcr;
let mut mask: u64 = z0;
mask |= zlf;
mask |= zcr;
if (mask & SWAR_HI_BITS) != 0 {
return true;
}
}
for &b in rem {
if b == BYTE_CR || b == BYTE_LF || b == BYTE_NUL {
return true;
}
}
false
}
#[inline]
pub(crate) fn is_plain_regex_literal(text: &str) -> bool {
!text.bytes().any(|b: u8| REGEX_META_LUT[b as usize])
}
pub(crate) fn try_compile_fast_regex(
pattern: &str,
replacement: &str,
) -> Option<CompiledRegexMatcher> {
let inner: &str = pattern.strip_prefix('^')?.strip_suffix('$')?;
if is_plain_regex_literal(inner) && !replacement.as_bytes().contains(&BYTE_DOLLAR) {
return Some(CompiledRegexMatcher::ExactLiteral {
needle: inner.to_owned(),
replacement: replacement.to_owned(),
});
}
let open: usize = inner.find('(')?;
let close: usize = inner[open..].find(')')? + open;
let prefix: &str = &inner[..open];
let group: &str = &inner[open..=close];
let suffix: &str = &inner[close + 1..];
if !is_plain_regex_literal(prefix) || !is_plain_regex_literal(suffix) {
return None;
}
let kind: CaptureKind = match group {
CAP_PAT_DIGITS_RANGE => CaptureKind::Digits,
CAP_PAT_NON_SLASH => CaptureKind::NonSlash,
CAP_PAT_NON_EMPTY => CaptureKind::NonEmpty,
CAP_PAT_ANY => CaptureKind::Any,
_ => return None,
};
let (repl_prefix, repl_suffix): (&str, &str) =
if let Some((before, after)) = replacement.split_once(REPL_CAP_1_BRACED) {
(before, after)
} else if let Some((before, after)) = replacement.split_once(REPL_CAP_1) {
if after
.as_bytes()
.first()
.is_some_and(|b: &u8| b.is_ascii_alphanumeric() || *b == BYTE_UNDERSCORE)
{
return None;
}
(before, after)
} else {
return None;
};
if repl_prefix.as_bytes().contains(&BYTE_DOLLAR)
|| repl_suffix.as_bytes().contains(&BYTE_DOLLAR)
{
return None;
}
Some(CompiledRegexMatcher::PrefixSuffixCapture {
prefix: prefix.to_owned(),
suffix: suffix.to_owned(),
kind,
repl_prefix: repl_prefix.to_owned(),
repl_suffix: repl_suffix.to_owned(),
})
}
#[inline]
pub(crate) fn matches_capture_kind(captured: &str, kind: CaptureKind) -> bool {
let bytes: &[u8] = captured.as_bytes();
match kind {
CaptureKind::Any => !bytes.contains(&BYTE_LF),
CaptureKind::NonEmpty => !bytes.is_empty() && !bytes.contains(&BYTE_LF),
CaptureKind::NonSlash => !bytes.is_empty() && !bytes.contains(&BYTE_SLASH),
CaptureKind::Digits => !bytes.is_empty() && bytes.iter().all(u8::is_ascii_digit),
}
}
#[inline]
pub(crate) fn match_compiled_regex(matcher: &CompiledRegexMatcher, path: &str) -> Option<String> {
match matcher {
CompiledRegexMatcher::ExactLiteral {
needle,
replacement,
} => {
if path == needle.as_str() {
Some(replacement.clone())
} else {
None
}
}
CompiledRegexMatcher::PrefixSuffixCapture {
prefix,
suffix,
kind,
repl_prefix,
repl_suffix,
} => {
if path.len() < prefix.len() + suffix.len() {
return None;
}
let after_prefix: &str = path.strip_prefix(prefix.as_str())?;
let captured: &str = after_prefix.strip_suffix(suffix.as_str())?;
if !matches_capture_kind(captured, *kind) {
return None;
}
let mut out: String =
String::with_capacity(repl_prefix.len() + captured.len() + repl_suffix.len());
out.push_str(repl_prefix);
out.push_str(captured);
out.push_str(repl_suffix);
Some(out)
}
CompiledRegexMatcher::General {
regex,
replacement,
has_expand,
} => {
let replaced: Cow<'_, str> = if *has_expand {
regex.replace(path, replacement.as_str())
} else {
regex.replace(path, NoExpand(replacement.as_str()))
};
match replaced {
Cow::Owned(s) => Some(s),
Cow::Borrowed(_) => None,
}
}
}
}
#[inline]
pub(crate) fn find_header_back_ref<'a>(
headers: &'a RequestHeaders,
lower_name: &str,
) -> Option<&'a str> {
if let Some(vals) = headers.get(lower_name) {
return vals.back().map(String::as_str);
}
headers
.iter()
.find(|(k, _): &(&String, &VecDeque<String>)| {
k.len() == lower_name.len() && k.eq_ignore_ascii_case(lower_name)
})
.and_then(|(_, v): (&String, &VecDeque<String>)| v.back().map(String::as_str))
}
#[inline]
pub(crate) fn is_request_https(headers: &RequestHeaders, trust_forwarded_proto: bool) -> bool {
if !trust_forwarded_proto {
return false;
}
if let Some(proto) = find_header_back_ref(headers, X_FORWARDED_PROTO) {
let first: &str = proto.split(',').next().unwrap_or(proto).trim();
return first.eq_ignore_ascii_case(SCHEME_HTTPS);
}
if let Some(fwd) = find_header_back_ref(headers, FORWARDED) {
for element in fwd.split(',') {
for param in element.split(';') {
let trimmed: &str = param.trim();
if trimmed.len() > FORWARDED_PROTO_PREFIX.len()
&& trimmed[..FORWARDED_PROTO_PREFIX.len()]
.eq_ignore_ascii_case(FORWARDED_PROTO_PREFIX)
{
let val: &str = trimmed[FORWARDED_PROTO_PREFIX.len()..]
.trim()
.trim_matches('"');
return val.eq_ignore_ascii_case(SCHEME_HTTPS);
}
}
}
}
false
}
#[inline]
pub(crate) fn host_matches_canonical(raw_host: &str, canonical_lower: &str) -> bool {
let trimmed: &str = raw_host.trim();
if trimmed.eq_ignore_ascii_case(canonical_lower) {
return true;
}
let stripped: &str = trimmed
.strip_suffix(DEFAULT_HTTP_PORT)
.or_else(|| trimmed.strip_suffix(DEFAULT_HTTPS_PORT))
.unwrap_or(trimmed);
stripped.eq_ignore_ascii_case(canonical_lower)
}
#[inline]
pub(crate) fn collapse_slashes(path: &str) -> Cow<'_, str> {
let bytes: &[u8] = path.as_bytes();
let len: usize = bytes.len();
let mut first_dup: usize = len;
let mut idx: usize = 0;
while idx + 1 < len {
if bytes[idx] == BYTE_SLASH && bytes[idx + 1] == BYTE_SLASH {
first_dup = idx;
break;
}
idx += 1;
}
if first_dup == len {
return Cow::Borrowed(path);
}
let mut out: String = String::with_capacity(len);
out.push_str(&path[..=first_dup]);
let mut cursor: usize = first_dup + 2;
while cursor < len {
while cursor < len && bytes[cursor] == BYTE_SLASH {
cursor += 1;
}
let seg_start: usize = cursor;
while cursor < len && bytes[cursor] != BYTE_SLASH {
cursor += 1;
}
if cursor > seg_start {
out.push_str(&path[seg_start..cursor]);
}
if cursor < len {
out.push('/');
cursor += 1;
}
}
Cow::Owned(out)
}
#[inline]
pub(crate) fn normalize_trailing_slash_borrowed<'a>(
path: Cow<'a, str>,
mode: TrailingSlashMode,
) -> (Cow<'a, str>, bool) {
let raw: &str = path.as_ref();
if raw.len() <= 1 {
return (path, false);
}
match mode {
TrailingSlashMode::Keep => (path, false),
TrailingSlashMode::Strip => {
if !raw.ends_with('/') {
return (path, false);
}
match path {
Cow::Borrowed(s) => (Cow::Borrowed(&s[..s.len() - 1]), true),
Cow::Owned(mut s) => {
let _: Option<char> = s.pop();
(Cow::Owned(s), true)
}
}
}
TrailingSlashMode::Enforce => {
if raw.ends_with('/') {
return (path, false);
}
match path {
Cow::Borrowed(s) => {
let mut out: String = String::with_capacity(s.len() + 1);
out.push_str(s);
out.push('/');
(Cow::Owned(out), true)
}
Cow::Owned(mut s) => {
s.push('/');
(Cow::Owned(s), true)
}
}
}
}
}
pub(crate) fn normalize_rule_prefix(prefix: &str) -> String {
let trimmed: &str = prefix.trim();
if trimmed == "/" {
return "/".to_owned();
}
trimmed.trim_end_matches('/').to_owned()
}
#[inline]
pub(crate) fn strip_prefix_segment<'a>(path: &'a str, prefix: &str) -> Option<&'a str> {
if prefix == "/" {
return Some(path);
}
if path.len() < prefix.len() {
return None;
}
let rest: &'a str = path.strip_prefix(prefix)?;
if rest.is_empty() || rest.as_bytes()[0] == BYTE_SLASH {
Some(rest)
} else {
None
}
}
#[inline]
pub(crate) fn join_prefix_replacement(to: &str, rest: &str) -> String {
if to.is_empty() {
if rest.is_empty() {
return "/".to_owned();
}
return rest.to_owned();
}
let mut out: String = String::with_capacity(to.len() + rest.len());
out.push_str(to);
out.push_str(rest);
out
}
#[inline]
pub(crate) fn query_suffix_len_from_ctx(
ctx: &Context,
preserve_query: bool,
target_has_query: bool,
) -> usize {
if !preserve_query || target_has_query {
return 0;
}
if let Some(raw_target) = ctx.get_request_target()
&& let Some((_, q)) = raw_target.split_once('?')
&& !q.is_empty()
{
return q.len() + 1;
}
let querys: &RequestQuerys = ctx.get_request().get_querys();
if querys.is_empty() {
return 0;
}
let mut total: usize = 0;
for (k, vals) in querys {
for v in vals {
total += 1 + k.len();
if !v.is_empty() {
total += 1 + v.len();
}
}
}
total
}
#[inline]
pub(crate) fn clone_with_query_from_ctx(
base: &str,
ctx: &Context,
preserve_query: bool,
target_has_query: bool,
) -> String {
let q_len: usize = query_suffix_len_from_ctx(ctx, preserve_query, target_has_query);
let mut out: String = String::with_capacity(base.len() + q_len);
out.push_str(base);
if q_len > 0 {
append_query_from_ctx(&mut out, ctx, preserve_query, target_has_query);
}
out
}
#[inline]
pub(crate) fn append_query_from_ctx(
target: &mut String,
ctx: &Context,
preserve_query: bool,
target_has_query: bool,
) {
if !preserve_query || target_has_query {
return;
}
if let Some(raw_target) = ctx.get_request_target()
&& let Some((_, q)) = raw_target.split_once('?')
&& !q.is_empty()
{
target.reserve(q.len() + 1);
target.push('?');
target.push_str(q);
return;
}
let querys: &RequestQuerys = ctx.get_request().get_querys();
if querys.is_empty() {
return;
}
let mut extra: usize = 0;
for (k, vals) in querys {
for v in vals {
extra += 1 + k.len();
if !v.is_empty() {
extra += 1 + v.len();
}
}
}
target.reserve(extra);
let mut first: bool = true;
for (k, vals) in querys {
for v in vals {
target.push(if first { '?' } else { '&' });
first = false;
target.push_str(k);
if !v.is_empty() {
target.push('=');
target.push_str(v);
}
}
}
}
#[inline]
pub(crate) fn write_query_bytes_from_ctx(
buf: &mut [u8],
mut pos: usize,
ctx: &Context,
preserve_query: bool,
target_has_query: bool,
) -> Option<usize> {
if !preserve_query || target_has_query {
return Some(pos);
}
if let Some(raw_target) = ctx.get_request_target()
&& let Some((_, q)) = raw_target.split_once('?')
&& !q.is_empty()
{
let qb: &[u8] = q.as_bytes();
if pos + 1 + qb.len() > buf.len() {
return None;
}
buf[pos] = BYTE_QUESTION;
pos += 1;
buf[pos..pos + qb.len()].copy_from_slice(qb);
return Some(pos + qb.len());
}
let querys: &RequestQuerys = ctx.get_request().get_querys();
if querys.is_empty() {
return Some(pos);
}
let mut first: bool = true;
for (k, vals) in querys {
let kb: &[u8] = k.as_bytes();
for v in vals {
let vb: &[u8] = v.as_bytes();
let extra: usize = 1 + kb.len() + if vb.is_empty() { 0 } else { 1 + vb.len() };
if pos + extra > buf.len() {
return None;
}
buf[pos] = if first { BYTE_QUESTION } else { BYTE_AMP };
first = false;
pos += 1;
buf[pos..pos + kb.len()].copy_from_slice(kb);
pos += kb.len();
if !vb.is_empty() {
buf[pos] = BYTE_EQ;
pos += 1;
buf[pos..pos + vb.len()].copy_from_slice(vb);
pos += vb.len();
}
}
}
Some(pos)
}
#[inline(always)]
pub(crate) fn redirect_wire_prefix(status: RedirectStatus) -> &'static [u8] {
match status {
RedirectStatus::MovedPermanently301 => WIRE_301_PREFIX,
RedirectStatus::Found302 => WIRE_302_PREFIX,
RedirectStatus::Temporary307 => WIRE_307_PREFIX,
RedirectStatus::Permanent308 => WIRE_308_PREFIX,
}
}
#[inline]
pub(crate) fn store_original_path_attr(ctx: &mut Context, original: String) -> Option<String> {
if let Some(slot) = ctx.get_mut_attributes().get_mut(ATTR_ORIGINAL_PATH_MAP_KEY) {
if let Some(any_mut) = Arc::get_mut(slot)
&& let Some(existing) = any_mut.downcast_mut::<String>()
{
return Some(mem::replace(existing, original));
}
*slot = Arc::new(original);
} else {
ctx.get_mut_attributes()
.insert(ATTR_ORIGINAL_PATH_MAP_KEY.to_owned(), Arc::new(original));
}
None
}
#[inline]
pub(crate) fn apply_internal_rewrite_copy(ctx: &mut Context, target: &str) {
let old_path: String = mem::take(ctx.get_mut_request().get_mut_path());
let next_path: String = if let Some(mut recycled) = store_original_path_attr(ctx, old_path) {
recycled.clear();
recycled.push_str(target);
recycled
} else {
target.to_owned()
};
ctx.get_mut_request().set_path(next_path);
}
#[inline]
pub(crate) fn apply_internal_rewrite_owned(ctx: &mut Context, target: String) {
let old_path: String = mem::replace(ctx.get_mut_request().get_mut_path(), target);
let _: Option<String> = store_original_path_attr(ctx, old_path);
}