use super::*;
#[inline]
pub fn resolve_safe_path(
root_dir: &Path,
relative_url: &str,
allow_dotfiles: bool,
) -> Option<PathBuf> {
let (safe_rel, has_special): (Cow<'_, str>, bool) =
validate_and_decode_relative_with_special(relative_url, allow_dotfiles)?;
let rel_str: &str = safe_rel.as_ref();
let mut candidate: PathBuf =
PathBuf::with_capacity(root_dir.as_os_str().len() + rel_str.len() + 1);
candidate.push(root_dir);
if rel_str.is_empty() {
return Some(candidate);
}
if !has_special {
candidate.push(rel_str);
return Some(candidate);
}
for component in Path::new(rel_str).components() {
match component {
Component::Normal(seg) => {
let seg_str: &str = seg.to_str()?;
if seg_str.is_empty() || (!allow_dotfiles && seg_str.as_bytes()[0] == BYTE_DOT) {
return None;
}
candidate.push(seg);
}
Component::CurDir => {}
Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
}
}
Some(candidate)
}
#[inline]
pub fn mime_for_path(path: &Path) -> &'static str {
let Some(ext_str) = path.extension().and_then(OsStr::to_str) else {
return APPLICATION_OCTET_STREAM;
};
let bytes: &[u8] = ext_str.as_bytes();
if bytes.is_empty() {
return APPLICATION_OCTET_STREAM;
}
if let Some(fast_mime) = fast_web_mime(bytes) {
return fast_mime;
}
let parsed: FileExtension = if !bytes.iter().any(|b: &u8| b.is_ascii_uppercase()) {
FileExtension::parse(ext_str)
} else if bytes.len() <= MIME_EXT_STACK_CAP {
let mut stack_buf: [u8; MIME_EXT_STACK_CAP] = [0u8; MIME_EXT_STACK_CAP];
for (dst, &src) in stack_buf.iter_mut().zip(bytes.iter()) {
*dst = src.to_ascii_lowercase();
}
match from_utf8(&stack_buf[..bytes.len()]) {
Ok(lower) => FileExtension::parse(lower),
Err(_) => FileExtension::parse(ext_str.to_ascii_lowercase()),
}
} else {
FileExtension::parse(ext_str.to_ascii_lowercase())
};
let mime: &'static str = parsed.get_content_type();
if mime.is_empty() {
APPLICATION_OCTET_STREAM
} else {
mime
}
}
#[inline]
pub fn if_none_match_matches(header: &str, etag: &str) -> bool {
let trimmed: &str = header.trim();
if trimmed == ETAG_WILDCARD || trimmed == etag {
return true;
}
trimmed.split(',').any(|token: &str| {
let candidate: &str = token.trim();
let normalized: &str = candidate
.strip_prefix(WEAK_ETAG_PREFIX)
.unwrap_or(candidate);
normalized == etag
})
}
#[inline]
pub fn parse_byte_range(header: &str, total_len: usize) -> Option<(usize, usize)> {
if total_len == 0 {
return None;
}
let trimmed: &str = header.trim();
let spec: &str = trimmed.strip_prefix(RANGE_BYTES_PREFIX)?;
if spec.as_bytes().contains(&BYTE_COMMA) {
return None;
}
let (start_str, end_str): (&str, &str) = spec.split_once('-')?;
let start_bytes: &[u8] = start_str.trim().as_bytes();
let end_bytes: &[u8] = end_str.trim().as_bytes();
if start_bytes.is_empty() {
let suffix: usize = parse_ascii_usize(end_bytes)?;
if suffix == 0 {
return None;
}
let start: usize = total_len.saturating_sub(suffix);
return Some((start, total_len - 1));
}
let start: usize = parse_ascii_usize(start_bytes)?;
if start >= total_len {
return None;
}
let end: usize = if end_bytes.is_empty() {
total_len - 1
} else {
parse_ascii_usize(end_bytes)?.min(total_len - 1)
};
if start > end {
return None;
}
Some((start, end))
}
#[inline(always)]
pub(crate) fn fast_web_mime(bytes: &[u8]) -> Option<&'static str> {
match bytes.len() {
2 => {
let lower: [u8; 2] = [bytes[0].to_ascii_lowercase(), bytes[1].to_ascii_lowercase()];
if lower == EXT_JS {
return Some(APPLICATION_JAVASCRIPT);
}
None
}
3 => {
let lower: [u8; 3] = [
bytes[0].to_ascii_lowercase(),
bytes[1].to_ascii_lowercase(),
bytes[2].to_ascii_lowercase(),
];
match lower {
EXT_CSS => Some(TEXT_CSS),
EXT_PNG => Some(IMAGE_PNG),
EXT_JPG => Some(IMAGE_JPEG),
EXT_SVG => Some(IMAGE_SVG_XML),
EXT_GIF => Some(IMAGE_GIF),
EXT_ICO => Some(IMAGE_X_ICON),
EXT_HTM => Some(TEXT_HTML),
EXT_TXT => Some(TEXT_PLAIN),
EXT_XML => Some(APPLICATION_XML),
EXT_PDF => Some(APPLICATION_PDF),
EXT_TTF => Some(FONT_TTF),
EXT_OTF => Some(FONT_OTF),
EXT_MP4 => Some(VIDEO_MP4),
EXT_MP3 => Some(AUDIO_MPEG),
_ => None,
}
}
4 => {
let lower: [u8; 4] = [
bytes[0].to_ascii_lowercase(),
bytes[1].to_ascii_lowercase(),
bytes[2].to_ascii_lowercase(),
bytes[3].to_ascii_lowercase(),
];
match lower {
EXT_HTML => Some(TEXT_HTML),
EXT_JSON => Some(APPLICATION_JSON),
EXT_WASM => Some(APPLICATION_WASM),
EXT_WEBP => Some(IMAGE_WEBP),
EXT_JPEG => Some(IMAGE_JPEG),
EXT_WOFF => Some(FONT_WOFF),
EXT_WEBM => Some(VIDEO_WEBM),
_ => None,
}
}
5 => {
let lower: [u8; 5] = [
bytes[0].to_ascii_lowercase(),
bytes[1].to_ascii_lowercase(),
bytes[2].to_ascii_lowercase(),
bytes[3].to_ascii_lowercase(),
bytes[4].to_ascii_lowercase(),
];
if lower == EXT_WOFF2 {
return Some(FONT_WOFF2);
}
None
}
_ => None,
}
}
#[inline(always)]
pub(crate) fn static_cache_shard_index(key: &str) -> usize {
let mut hasher: FxHasher = FxHasher::default();
hasher.write(key.as_bytes());
let h: u64 = hasher.finish();
(((h >> 32) ^ h) as usize) & (STATIC_CACHE_SHARDS - 1)
}
#[inline(always)]
pub(crate) fn hex_nibble(byte: u8) -> Option<u8> {
let val: u8 = HEX_DECODE_LUT[byte as usize];
if val < 16 { Some(val) } else { None }
}
pub(crate) fn percent_decode_path(raw: &str) -> Option<String> {
let bytes: &[u8] = raw.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut i: usize = 0;
while i < bytes.len() {
let b: u8 = bytes[i];
if b == 0 || b == BYTE_BACKSLASH {
return None;
}
if b == BYTE_PERCENT {
if i + 2 >= bytes.len() {
return None;
}
let hi: u8 = hex_nibble(bytes[i + 1])?;
let lo: u8 = hex_nibble(bytes[i + 2])?;
let decoded: u8 = (hi << 4) | lo;
if decoded == 0 || decoded == BYTE_BACKSLASH {
return None;
}
out.push(decoded);
i += 3;
} else {
out.push(b);
i += 1;
}
}
String::from_utf8(out).ok()
}
#[inline]
pub(crate) fn scan_decoded_segments(bytes: &[u8], allow_dotfiles: bool) -> Option<bool> {
if bytes.is_empty() {
return Some(false);
}
let mut has_special: bool = false;
let mut seg_start: usize = 0;
let len: usize = bytes.len();
for i in 0..=len {
if i < len && bytes[i] != BYTE_SLASH {
continue;
}
let seg: &[u8] = &bytes[seg_start..i];
if seg.is_empty() {
if i < len {
has_special = true;
}
} else if seg.len() == 1 && seg[0] == BYTE_DOT {
has_special = true;
} else if (seg.len() == 2 && seg[0] == BYTE_DOT && seg[1] == BYTE_DOT)
|| (!allow_dotfiles && seg[0] == BYTE_DOT)
{
return None;
}
seg_start = i + 1;
}
Some(has_special)
}
#[inline]
pub(crate) fn validate_and_decode_relative_with_special<'a>(
relative_url: &'a str,
allow_dotfiles: bool,
) -> Option<(Cow<'a, str>, bool)> {
let bytes: &[u8] = relative_url.as_bytes();
let mut start: usize = 0;
while start < bytes.len() && bytes[start] == BYTE_SLASH {
start += 1;
}
let trimmed_bytes: &[u8] = &bytes[start..];
let len: usize = trimmed_bytes.len();
if len == 0 {
return Some((Cow::Borrowed(&relative_url[start..]), false));
}
let mut has_special: bool = false;
let mut seg_start: usize = 0;
for i in 0..=len {
if i < len {
let b: u8 = trimmed_bytes[i];
if b == 0 || b == BYTE_BACKSLASH {
return None;
}
if b == BYTE_PERCENT {
let decoded: String = percent_decode_path(relative_url)?;
let trimmed: &str = decoded.trim_start_matches('/');
let special: bool = scan_decoded_segments(trimmed.as_bytes(), allow_dotfiles)?;
return Some((Cow::Owned(trimmed.to_owned()), special));
}
if b != BYTE_SLASH {
continue;
}
}
let seg: &[u8] = &trimmed_bytes[seg_start..i];
if seg.is_empty() {
if i < len {
has_special = true;
}
} else if seg.len() == 1 && seg[0] == BYTE_DOT {
has_special = true;
} else if (seg.len() == 2 && seg[0] == BYTE_DOT && seg[1] == BYTE_DOT)
|| (!allow_dotfiles && seg[0] == BYTE_DOT)
{
return None;
}
seg_start = i + 1;
}
Some((Cow::Borrowed(&relative_url[start..]), has_special))
}
#[inline]
pub(crate) fn validate_and_decode_relative<'a>(
relative_url: &'a str,
allow_dotfiles: bool,
) -> Option<Cow<'a, str>> {
validate_and_decode_relative_with_special(relative_url, allow_dotfiles)
.map(|(cow, _): (Cow<'a, str>, bool)| cow)
}
#[inline]
pub(crate) fn write_hex_u64_compact(mut value: u64, buf: &mut [u8], pos: usize) -> usize {
if value == 0 {
buf[pos] = BYTE_ZERO;
return pos + 1;
}
let mut tmp: [u8; 16] = [0u8; 16];
let mut idx: usize = 16;
while value > 0 {
idx -= 1;
tmp[idx] = HEX_DIGITS[(value & 0x0F) as usize];
value >>= 4;
}
let slice: &[u8] = &tmp[idx..];
buf[pos..pos + slice.len()].copy_from_slice(slice);
pos + slice.len()
}
#[inline]
pub(crate) fn compute_file_etag(size: u64, modified_ms: u64) -> String {
let mut buf: [u8; ETAG_STACK_CAP] = [0u8; ETAG_STACK_CAP];
buf[0] = BYTE_QUOTE;
let mut pos: usize = write_hex_u64_compact(size, &mut buf, 1);
buf[pos] = BYTE_DASH;
pos = write_hex_u64_compact(modified_ms, &mut buf, pos + 1);
buf[pos] = BYTE_QUOTE;
pos += 1;
from_utf8(&buf[..pos]).unwrap_or_default().to_owned()
}
#[inline]
pub(crate) fn metadata_modified_ms(meta: &Metadata) -> u64 {
meta.modified()
.ok()
.and_then(|ts: SystemTime| ts.duration_since(UNIX_EPOCH).ok())
.map(|dur: Duration| dur.as_millis() as u64)
.unwrap_or(0)
}
#[inline]
pub(crate) fn parse_ascii_usize(bytes: &[u8]) -> Option<usize> {
if bytes.is_empty() {
return None;
}
let mut acc: usize = 0;
for &b in bytes {
if !b.is_ascii_digit() {
return None;
}
acc = acc.checked_mul(10)?.checked_add((b - BYTE_ZERO) as usize)?;
}
Some(acc)
}
#[inline]
pub(crate) fn write_usize_decimal(mut value: usize, buf: &mut [u8], pos: usize) -> usize {
if value < 10 {
buf[pos] = BYTE_ZERO + value as u8;
return pos + 1;
}
let mut digits: [u8; 20] = [0u8; 20];
let mut idx: usize = 20;
while value >= 100 {
let pair: usize = (value % 100) * 2;
value /= 100;
idx -= 2;
digits[idx] = DEC_DIGITS_LUT[pair];
digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
}
if value >= 10 {
let pair: usize = value * 2;
idx -= 2;
digits[idx] = DEC_DIGITS_LUT[pair];
digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
} else {
idx -= 1;
digits[idx] = BYTE_ZERO + value as u8;
}
let slice: &[u8] = &digits[idx..];
buf[pos..pos + slice.len()].copy_from_slice(slice);
pos + slice.len()
}
#[inline]
pub(crate) fn format_content_range_stack(
start: usize,
end: usize,
total: usize,
buf: &mut [u8; CONTENT_RANGE_STACK_CAP],
) -> &str {
let prefix: &[u8] = CONTENT_RANGE_BYTES_PREFIX.as_bytes();
buf[..prefix.len()].copy_from_slice(prefix);
let mut pos: usize = write_usize_decimal(start, buf, prefix.len());
buf[pos] = BYTE_DASH;
pos = write_usize_decimal(end, buf, pos + 1);
buf[pos] = BYTE_SLASH;
pos = write_usize_decimal(total, buf, pos + 1);
from_utf8(&buf[..pos]).unwrap_or_default()
}
#[inline]
pub(crate) fn format_unsatisfiable_range_stack(
total: usize,
buf: &mut [u8; CONTENT_RANGE_STACK_CAP],
) -> &str {
let prefix: &[u8] = CONTENT_RANGE_UNSAT_PREFIX.as_bytes();
buf[..prefix.len()].copy_from_slice(prefix);
let pos: usize = write_usize_decimal(total, buf, prefix.len());
from_utf8(&buf[..pos]).unwrap_or_default()
}
#[inline]
pub(crate) fn accept_encoding_mask(accept_encoding: &str) -> u8 {
let mut mask: u8 = 0;
for part in accept_encoding.split(',') {
let trimmed_part: &str = part.trim();
if !trimmed_part.as_bytes().contains(&BYTE_SEMICOLON) {
if trimmed_part.eq_ignore_ascii_case(ENCODING_BR) {
mask |= ENCODING_MASK_BR;
} else if trimmed_part.eq_ignore_ascii_case(ENCODING_GZIP) {
mask |= ENCODING_MASK_GZIP;
}
if mask == (ENCODING_MASK_BR | ENCODING_MASK_GZIP) {
break;
}
continue;
}
let mut segments: Split<'_, char> = trimmed_part.split(';');
let coding: &str = segments.next().unwrap_or_default().trim();
let bit: u8 = if coding.eq_ignore_ascii_case(ENCODING_BR) {
ENCODING_MASK_BR
} else if coding.eq_ignore_ascii_case(ENCODING_GZIP) {
ENCODING_MASK_GZIP
} else {
continue;
};
let mut rejected: bool = false;
for param in segments {
let trimmed: &str = param.trim();
if let Some(qval) = trimmed
.strip_prefix(QUALITY_PREFIX_LOWER)
.or_else(|| trimmed.strip_prefix(QUALITY_PREFIX_UPPER))
&& qval.trim().parse::<f32>().ok() == Some(0.0)
{
rejected = true;
}
}
if !rejected {
mask |= bit;
}
}
mask
}
#[inline]
pub(crate) fn get_request_header_back_ref<'a>(request: &'a Request, name: &str) -> Option<&'a str> {
request
.get_headers()
.get(name)
.and_then(|values: &VecDeque<String>| values.back())
.map(String::as_str)
}