hyperlane_plugin_static_files/
fn.rs1use super::*;
2
3#[inline]
15pub fn resolve_safe_path(
16 root_dir: &Path,
17 relative_url: &str,
18 allow_dotfiles: bool,
19) -> Option<PathBuf> {
20 let (safe_rel, has_special): (Cow<'_, str>, bool) =
21 validate_and_decode_relative_with_special(relative_url, allow_dotfiles)?;
22 let rel_str: &str = safe_rel.as_ref();
23 let mut candidate: PathBuf =
24 PathBuf::with_capacity(root_dir.as_os_str().len() + rel_str.len() + 1);
25 candidate.push(root_dir);
26 if rel_str.is_empty() {
27 return Some(candidate);
28 }
29 if !has_special {
30 candidate.push(rel_str);
31 return Some(candidate);
32 }
33 for component in Path::new(rel_str).components() {
34 match component {
35 Component::Normal(seg) => {
36 let seg_str: &str = seg.to_str()?;
37 if seg_str.is_empty() || (!allow_dotfiles && seg_str.as_bytes()[0] == BYTE_DOT) {
38 return None;
39 }
40 candidate.push(seg);
41 }
42 Component::CurDir => {}
43 Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
44 }
45 }
46 Some(candidate)
47}
48
49#[inline]
59pub fn mime_for_path(path: &Path) -> &'static str {
60 let Some(ext_str) = path.extension().and_then(OsStr::to_str) else {
61 return APPLICATION_OCTET_STREAM;
62 };
63 let bytes: &[u8] = ext_str.as_bytes();
64 if bytes.is_empty() {
65 return APPLICATION_OCTET_STREAM;
66 }
67 if let Some(fast_mime) = fast_web_mime(bytes) {
68 return fast_mime;
69 }
70 let parsed: FileExtension = if !bytes.iter().any(|b: &u8| b.is_ascii_uppercase()) {
71 FileExtension::parse(ext_str)
72 } else if bytes.len() <= MIME_EXT_STACK_CAP {
73 let mut stack_buf: [u8; MIME_EXT_STACK_CAP] = [0u8; MIME_EXT_STACK_CAP];
74 for (dst, &src) in stack_buf.iter_mut().zip(bytes.iter()) {
75 *dst = src.to_ascii_lowercase();
76 }
77 match from_utf8(&stack_buf[..bytes.len()]) {
78 Ok(lower) => FileExtension::parse(lower),
79 Err(_) => FileExtension::parse(ext_str.to_ascii_lowercase()),
80 }
81 } else {
82 FileExtension::parse(ext_str.to_ascii_lowercase())
83 };
84 let mime: &'static str = parsed.get_content_type();
85 if mime.is_empty() {
86 APPLICATION_OCTET_STREAM
87 } else {
88 mime
89 }
90}
91
92#[inline]
103pub fn if_none_match_matches(header: &str, etag: &str) -> bool {
104 let trimmed: &str = header.trim();
105 if trimmed == ETAG_WILDCARD || trimmed == etag {
106 return true;
107 }
108 trimmed.split(',').any(|token: &str| {
109 let candidate: &str = token.trim();
110 let normalized: &str = candidate
111 .strip_prefix(WEAK_ETAG_PREFIX)
112 .unwrap_or(candidate);
113 normalized == etag
114 })
115}
116
117#[inline]
128pub fn parse_byte_range(header: &str, total_len: usize) -> Option<(usize, usize)> {
129 if total_len == 0 {
130 return None;
131 }
132 let trimmed: &str = header.trim();
133 let spec: &str = trimmed.strip_prefix(RANGE_BYTES_PREFIX)?;
134 if spec.as_bytes().contains(&BYTE_COMMA) {
135 return None;
136 }
137 let (start_str, end_str): (&str, &str) = spec.split_once('-')?;
138 let start_bytes: &[u8] = start_str.trim().as_bytes();
139 let end_bytes: &[u8] = end_str.trim().as_bytes();
140 if start_bytes.is_empty() {
141 let suffix: usize = parse_ascii_usize(end_bytes)?;
142 if suffix == 0 {
143 return None;
144 }
145 let start: usize = total_len.saturating_sub(suffix);
146 return Some((start, total_len - 1));
147 }
148 let start: usize = parse_ascii_usize(start_bytes)?;
149 if start >= total_len {
150 return None;
151 }
152 let end: usize = if end_bytes.is_empty() {
153 total_len - 1
154 } else {
155 parse_ascii_usize(end_bytes)?.min(total_len - 1)
156 };
157 if start > end {
158 return None;
159 }
160 Some((start, end))
161}
162
163#[inline(always)]
173pub(crate) fn fast_web_mime(bytes: &[u8]) -> Option<&'static str> {
174 match bytes.len() {
175 2 => {
176 let lower: [u8; 2] = [bytes[0].to_ascii_lowercase(), bytes[1].to_ascii_lowercase()];
177 if lower == EXT_JS {
178 return Some(APPLICATION_JAVASCRIPT);
179 }
180 None
181 }
182 3 => {
183 let lower: [u8; 3] = [
184 bytes[0].to_ascii_lowercase(),
185 bytes[1].to_ascii_lowercase(),
186 bytes[2].to_ascii_lowercase(),
187 ];
188 match lower {
189 EXT_CSS => Some(TEXT_CSS),
190 EXT_PNG => Some(IMAGE_PNG),
191 EXT_JPG => Some(IMAGE_JPEG),
192 EXT_SVG => Some(IMAGE_SVG_XML),
193 EXT_GIF => Some(IMAGE_GIF),
194 EXT_ICO => Some(IMAGE_X_ICON),
195 EXT_HTM => Some(TEXT_HTML),
196 EXT_TXT => Some(TEXT_PLAIN),
197 EXT_XML => Some(APPLICATION_XML),
198 EXT_PDF => Some(APPLICATION_PDF),
199 EXT_TTF => Some(FONT_TTF),
200 EXT_OTF => Some(FONT_OTF),
201 EXT_MP4 => Some(VIDEO_MP4),
202 EXT_MP3 => Some(AUDIO_MPEG),
203 _ => None,
204 }
205 }
206 4 => {
207 let lower: [u8; 4] = [
208 bytes[0].to_ascii_lowercase(),
209 bytes[1].to_ascii_lowercase(),
210 bytes[2].to_ascii_lowercase(),
211 bytes[3].to_ascii_lowercase(),
212 ];
213 match lower {
214 EXT_HTML => Some(TEXT_HTML),
215 EXT_JSON => Some(APPLICATION_JSON),
216 EXT_WASM => Some(APPLICATION_WASM),
217 EXT_WEBP => Some(IMAGE_WEBP),
218 EXT_JPEG => Some(IMAGE_JPEG),
219 EXT_WOFF => Some(FONT_WOFF),
220 EXT_WEBM => Some(VIDEO_WEBM),
221 _ => None,
222 }
223 }
224 5 => {
225 let lower: [u8; 5] = [
226 bytes[0].to_ascii_lowercase(),
227 bytes[1].to_ascii_lowercase(),
228 bytes[2].to_ascii_lowercase(),
229 bytes[3].to_ascii_lowercase(),
230 bytes[4].to_ascii_lowercase(),
231 ];
232 if lower == EXT_WOFF2 {
233 return Some(FONT_WOFF2);
234 }
235 None
236 }
237 _ => None,
238 }
239}
240
241#[inline(always)]
251pub(crate) fn static_cache_shard_index(key: &str) -> usize {
252 let mut hasher: FxHasher = FxHasher::default();
253 hasher.write(key.as_bytes());
254 let h: u64 = hasher.finish();
255 (((h >> 32) ^ h) as usize) & (STATIC_CACHE_SHARDS - 1)
256}
257
258#[inline(always)]
268pub(crate) fn hex_nibble(byte: u8) -> Option<u8> {
269 let val: u8 = HEX_DECODE_LUT[byte as usize];
270 if val < 16 { Some(val) } else { None }
271}
272
273pub(crate) fn percent_decode_path(raw: &str) -> Option<String> {
283 let bytes: &[u8] = raw.as_bytes();
284 let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
285 let mut i: usize = 0;
286 while i < bytes.len() {
287 let b: u8 = bytes[i];
288 if b == 0 || b == BYTE_BACKSLASH {
289 return None;
290 }
291 if b == BYTE_PERCENT {
292 if i + 2 >= bytes.len() {
293 return None;
294 }
295 let hi: u8 = hex_nibble(bytes[i + 1])?;
296 let lo: u8 = hex_nibble(bytes[i + 2])?;
297 let decoded: u8 = (hi << 4) | lo;
298 if decoded == 0 || decoded == BYTE_BACKSLASH {
299 return None;
300 }
301 out.push(decoded);
302 i += 3;
303 } else {
304 out.push(b);
305 i += 1;
306 }
307 }
308 String::from_utf8(out).ok()
309}
310
311#[inline]
322pub(crate) fn scan_decoded_segments(bytes: &[u8], allow_dotfiles: bool) -> Option<bool> {
323 if bytes.is_empty() {
324 return Some(false);
325 }
326 let mut has_special: bool = false;
327 let mut seg_start: usize = 0;
328 let len: usize = bytes.len();
329 for i in 0..=len {
330 if i < len && bytes[i] != BYTE_SLASH {
331 continue;
332 }
333 let seg: &[u8] = &bytes[seg_start..i];
334 if seg.is_empty() {
335 if i < len {
336 has_special = true;
337 }
338 } else if seg.len() == 1 && seg[0] == BYTE_DOT {
339 has_special = true;
340 } else if (seg.len() == 2 && seg[0] == BYTE_DOT && seg[1] == BYTE_DOT)
341 || (!allow_dotfiles && seg[0] == BYTE_DOT)
342 {
343 return None;
344 }
345 seg_start = i + 1;
346 }
347 Some(has_special)
348}
349
350#[inline]
361pub(crate) fn validate_and_decode_relative_with_special<'a>(
362 relative_url: &'a str,
363 allow_dotfiles: bool,
364) -> Option<(Cow<'a, str>, bool)> {
365 let bytes: &[u8] = relative_url.as_bytes();
366 let mut start: usize = 0;
367 while start < bytes.len() && bytes[start] == BYTE_SLASH {
368 start += 1;
369 }
370 let trimmed_bytes: &[u8] = &bytes[start..];
371 let len: usize = trimmed_bytes.len();
372 if len == 0 {
373 return Some((Cow::Borrowed(&relative_url[start..]), false));
374 }
375 let mut has_special: bool = false;
376 let mut seg_start: usize = 0;
377 for i in 0..=len {
378 if i < len {
379 let b: u8 = trimmed_bytes[i];
380 if b == 0 || b == BYTE_BACKSLASH {
381 return None;
382 }
383 if b == BYTE_PERCENT {
384 let decoded: String = percent_decode_path(relative_url)?;
385 let trimmed: &str = decoded.trim_start_matches('/');
386 let special: bool = scan_decoded_segments(trimmed.as_bytes(), allow_dotfiles)?;
387 return Some((Cow::Owned(trimmed.to_owned()), special));
388 }
389 if b != BYTE_SLASH {
390 continue;
391 }
392 }
393 let seg: &[u8] = &trimmed_bytes[seg_start..i];
394 if seg.is_empty() {
395 if i < len {
396 has_special = true;
397 }
398 } else if seg.len() == 1 && seg[0] == BYTE_DOT {
399 has_special = true;
400 } else if (seg.len() == 2 && seg[0] == BYTE_DOT && seg[1] == BYTE_DOT)
401 || (!allow_dotfiles && seg[0] == BYTE_DOT)
402 {
403 return None;
404 }
405 seg_start = i + 1;
406 }
407 Some((Cow::Borrowed(&relative_url[start..]), has_special))
408}
409
410#[inline]
421pub(crate) fn validate_and_decode_relative<'a>(
422 relative_url: &'a str,
423 allow_dotfiles: bool,
424) -> Option<Cow<'a, str>> {
425 validate_and_decode_relative_with_special(relative_url, allow_dotfiles)
426 .map(|(cow, _): (Cow<'a, str>, bool)| cow)
427}
428
429#[inline]
441pub(crate) fn write_hex_u64_compact(mut value: u64, buf: &mut [u8], pos: usize) -> usize {
442 if value == 0 {
443 buf[pos] = BYTE_ZERO;
444 return pos + 1;
445 }
446 let mut tmp: [u8; 16] = [0u8; 16];
447 let mut idx: usize = 16;
448 while value > 0 {
449 idx -= 1;
450 tmp[idx] = HEX_DIGITS[(value & 0x0F) as usize];
451 value >>= 4;
452 }
453 let slice: &[u8] = &tmp[idx..];
454 buf[pos..pos + slice.len()].copy_from_slice(slice);
455 pos + slice.len()
456}
457
458#[inline]
469pub(crate) fn compute_file_etag(size: u64, modified_ms: u64) -> String {
470 let mut buf: [u8; ETAG_STACK_CAP] = [0u8; ETAG_STACK_CAP];
471 buf[0] = BYTE_QUOTE;
472 let mut pos: usize = write_hex_u64_compact(size, &mut buf, 1);
473 buf[pos] = BYTE_DASH;
474 pos = write_hex_u64_compact(modified_ms, &mut buf, pos + 1);
475 buf[pos] = BYTE_QUOTE;
476 pos += 1;
477 from_utf8(&buf[..pos]).unwrap_or_default().to_owned()
478}
479
480#[inline]
490pub(crate) fn metadata_modified_ms(meta: &Metadata) -> u64 {
491 meta.modified()
492 .ok()
493 .and_then(|ts: SystemTime| ts.duration_since(UNIX_EPOCH).ok())
494 .map(|dur: Duration| dur.as_millis() as u64)
495 .unwrap_or(0)
496}
497
498#[inline]
508pub(crate) fn parse_ascii_usize(bytes: &[u8]) -> Option<usize> {
509 if bytes.is_empty() {
510 return None;
511 }
512 let mut acc: usize = 0;
513 for &b in bytes {
514 if !b.is_ascii_digit() {
515 return None;
516 }
517 acc = acc.checked_mul(10)?.checked_add((b - BYTE_ZERO) as usize)?;
518 }
519 Some(acc)
520}
521
522#[inline]
534pub(crate) fn write_usize_decimal(mut value: usize, buf: &mut [u8], pos: usize) -> usize {
535 if value < 10 {
536 buf[pos] = BYTE_ZERO + value as u8;
537 return pos + 1;
538 }
539 let mut digits: [u8; 20] = [0u8; 20];
540 let mut idx: usize = 20;
541 while value >= 100 {
542 let pair: usize = (value % 100) * 2;
543 value /= 100;
544 idx -= 2;
545 digits[idx] = DEC_DIGITS_LUT[pair];
546 digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
547 }
548 if value >= 10 {
549 let pair: usize = value * 2;
550 idx -= 2;
551 digits[idx] = DEC_DIGITS_LUT[pair];
552 digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
553 } else {
554 idx -= 1;
555 digits[idx] = BYTE_ZERO + value as u8;
556 }
557 let slice: &[u8] = &digits[idx..];
558 buf[pos..pos + slice.len()].copy_from_slice(slice);
559 pos + slice.len()
560}
561
562#[inline]
575pub(crate) fn format_content_range_stack(
576 start: usize,
577 end: usize,
578 total: usize,
579 buf: &mut [u8; CONTENT_RANGE_STACK_CAP],
580) -> &str {
581 let prefix: &[u8] = CONTENT_RANGE_BYTES_PREFIX.as_bytes();
582 buf[..prefix.len()].copy_from_slice(prefix);
583 let mut pos: usize = write_usize_decimal(start, buf, prefix.len());
584 buf[pos] = BYTE_DASH;
585 pos = write_usize_decimal(end, buf, pos + 1);
586 buf[pos] = BYTE_SLASH;
587 pos = write_usize_decimal(total, buf, pos + 1);
588 from_utf8(&buf[..pos]).unwrap_or_default()
589}
590
591#[inline]
602pub(crate) fn format_unsatisfiable_range_stack(
603 total: usize,
604 buf: &mut [u8; CONTENT_RANGE_STACK_CAP],
605) -> &str {
606 let prefix: &[u8] = CONTENT_RANGE_UNSAT_PREFIX.as_bytes();
607 buf[..prefix.len()].copy_from_slice(prefix);
608 let pos: usize = write_usize_decimal(total, buf, prefix.len());
609 from_utf8(&buf[..pos]).unwrap_or_default()
610}
611
612#[inline]
622pub(crate) fn accept_encoding_mask(accept_encoding: &str) -> u8 {
623 let mut mask: u8 = 0;
624 for part in accept_encoding.split(',') {
625 let trimmed_part: &str = part.trim();
626 if !trimmed_part.as_bytes().contains(&BYTE_SEMICOLON) {
627 if trimmed_part.eq_ignore_ascii_case(ENCODING_BR) {
628 mask |= ENCODING_MASK_BR;
629 } else if trimmed_part.eq_ignore_ascii_case(ENCODING_GZIP) {
630 mask |= ENCODING_MASK_GZIP;
631 }
632 if mask == (ENCODING_MASK_BR | ENCODING_MASK_GZIP) {
633 break;
634 }
635 continue;
636 }
637 let mut segments: Split<'_, char> = trimmed_part.split(';');
638 let coding: &str = segments.next().unwrap_or_default().trim();
639 let bit: u8 = if coding.eq_ignore_ascii_case(ENCODING_BR) {
640 ENCODING_MASK_BR
641 } else if coding.eq_ignore_ascii_case(ENCODING_GZIP) {
642 ENCODING_MASK_GZIP
643 } else {
644 continue;
645 };
646 let mut rejected: bool = false;
647 for param in segments {
648 let trimmed: &str = param.trim();
649 if let Some(qval) = trimmed
650 .strip_prefix(QUALITY_PREFIX_LOWER)
651 .or_else(|| trimmed.strip_prefix(QUALITY_PREFIX_UPPER))
652 && qval.trim().parse::<f32>().ok() == Some(0.0)
653 {
654 rejected = true;
655 }
656 }
657 if !rejected {
658 mask |= bit;
659 }
660 }
661 mask
662}
663
664#[inline]
675pub(crate) fn get_request_header_back_ref<'a>(request: &'a Request, name: &str) -> Option<&'a str> {
676 request
677 .get_headers()
678 .get(name)
679 .and_then(|values: &VecDeque<String>| values.back())
680 .map(String::as_str)
681}