Skip to main content

hyperlane_plugin_static_files/
fn.rs

1use super::*;
2
3/// Computes the cache shard index for a normalized URL key using `XxHash3_64`.
4///
5/// # Arguments
6///
7/// - `&str` - Normalized relative URL path.
8///
9/// # Returns
10///
11/// - `usize` - Shard index in `0..STATIC_CACHE_SHARDS`.
12#[inline]
13pub(crate) fn static_cache_shard_index(key: &str) -> usize {
14    let mut hasher: XxHash3_64 = XxHash3_64::default();
15    hasher.write(key.as_bytes());
16    (hasher.finish() as usize) & (STATIC_CACHE_SHARDS - 1)
17}
18
19/// Percent-decodes a URL path segment while rejecting NUL bytes (`%00`) and backslashes.
20///
21/// # Arguments
22///
23/// - `&str` - Raw URL path slice.
24///
25/// # Returns
26///
27/// - `Option<String>` - Decoded UTF-8 relative path, or `None` if malformed or contains NUL/backslash.
28pub(crate) fn percent_decode_path(raw: &str) -> Option<String> {
29    let bytes: &[u8] = raw.as_bytes();
30    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
31    let mut i: usize = 0;
32    while i < bytes.len() {
33        let b: u8 = bytes[i];
34        if b == 0 || b == b'\\' {
35            return None;
36        }
37        if b == b'%' {
38            if i + 2 >= bytes.len() {
39                return None;
40            }
41            let hi: u8 = hex_nibble(bytes[i + 1])?;
42            let lo: u8 = hex_nibble(bytes[i + 2])?;
43            let decoded: u8 = (hi << 4) | lo;
44            if decoded == 0 || decoded == b'\\' {
45                return None;
46            }
47            out.push(decoded);
48            i += 3;
49        } else {
50            out.push(b);
51            i += 1;
52        }
53    }
54    String::from_utf8(out).ok()
55}
56
57/// Converts an ASCII hex digit byte into its 4-bit value.
58///
59/// # Arguments
60///
61/// - `u8` - ASCII byte.
62///
63/// # Returns
64///
65/// - `Option<u8>` - 4-bit value `0..=15`, or `None` when not hex.
66#[inline]
67pub(crate) fn hex_nibble(byte: u8) -> Option<u8> {
68    match byte {
69        b'0'..=b'9' => Some(byte - b'0'),
70        b'a'..=b'f' => Some(byte - b'a' + 10),
71        b'A'..=b'F' => Some(byte - b'A' + 10),
72        _ => None,
73    }
74}
75
76/// Validates every slash-separated segment of a decoded relative path for traversal and dotfiles.
77///
78/// # Arguments
79///
80/// - `&str` - Trimmed relative URL path without leading slashes.
81/// - `bool` - Whether hidden dotfiles/dotdirs are permitted.
82///
83/// # Returns
84///
85/// - `bool` - `true` when every segment is safe.
86#[inline]
87pub(crate) fn is_safe_relative_segments(trimmed: &str, allow_dotfiles: bool) -> bool {
88    if trimmed.is_empty() {
89        return true;
90    }
91    for seg in trimmed.split('/') {
92        if seg.is_empty() || seg == "." {
93            continue;
94        }
95        if seg == ".." || (!allow_dotfiles && seg.starts_with('.')) {
96            return false;
97        }
98    }
99    true
100}
101
102/// Validates and percent-decodes `relative_url` without allocating when no `%` escape is present.
103///
104/// # Arguments
105///
106/// - `&'a str` - Raw relative URL path after stripping mount prefix.
107/// - `bool` - Whether dotfiles are allowed.
108///
109/// # Returns
110///
111/// - `Option<Cow<'a, str>>` - Safe normalized relative path without leading slashes, or `None` on traversal/invalid bytes.
112#[inline]
113pub(crate) fn validate_and_decode_relative<'a>(
114    relative_url: &'a str,
115    allow_dotfiles: bool,
116) -> Option<Cow<'a, str>> {
117    let bytes: &[u8] = relative_url.as_bytes();
118    let mut has_percent: bool = false;
119    for &b in bytes {
120        if b == 0 || b == b'\\' {
121            return None;
122        }
123        if b == b'%' {
124            has_percent = true;
125        }
126    }
127    if !has_percent {
128        let trimmed: &'a str = relative_url.trim_start_matches('/');
129        if !is_safe_relative_segments(trimmed, allow_dotfiles) {
130            return None;
131        }
132        return Some(Cow::Borrowed(trimmed));
133    }
134    let decoded: String = percent_decode_path(relative_url)?;
135    let trimmed: &str = decoded.trim_start_matches('/');
136    if !is_safe_relative_segments(trimmed, allow_dotfiles) {
137        return None;
138    }
139    Some(Cow::Owned(trimmed.to_owned()))
140}
141
142/// Safely joins an untrusted relative URL path onto a canonicalized `root_dir`, rejecting traversal and dotfiles.
143///
144/// # Arguments
145///
146/// - `&Path` - Canonicalized root directory.
147/// - `&str` - Raw URL relative path (after stripping mount prefix).
148/// - `bool` - Whether hidden dotfiles/dotdirs (segments beginning with `.`) are permitted.
149///
150/// # Returns
151///
152/// - `Option<PathBuf>` - Validated filesystem path inside `root_dir`, or `None` on traversal/escape.
153#[inline]
154pub fn resolve_safe_path(
155    root_dir: &Path,
156    relative_url: &str,
157    allow_dotfiles: bool,
158) -> Option<PathBuf> {
159    let safe_rel: Cow<'_, str> = validate_and_decode_relative(relative_url, allow_dotfiles)?;
160    let rel_str: &str = safe_rel.as_ref();
161    let mut candidate: PathBuf =
162        PathBuf::with_capacity(root_dir.as_os_str().len() + rel_str.len() + 1);
163    candidate.push(root_dir);
164    if rel_str.is_empty() {
165        return Some(candidate);
166    }
167    let has_special: bool = rel_str == "."
168        || rel_str.starts_with("./")
169        || rel_str.ends_with("/.")
170        || rel_str.contains("/./")
171        || rel_str.contains("//");
172    if !has_special {
173        candidate.push(rel_str);
174        return Some(candidate);
175    }
176    for component in Path::new(rel_str).components() {
177        match component {
178            Component::Normal(seg) => {
179                let seg_str: &str = seg.to_str()?;
180                if seg_str.is_empty() || (!allow_dotfiles && seg_str.starts_with('.')) {
181                    return None;
182                }
183                candidate.push(seg);
184            }
185            Component::CurDir => {}
186            Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
187        }
188    }
189    Some(candidate)
190}
191
192/// Resolves the MIME `Content-Type` string for `path` using Hyperlane's [`FileExtension`] table without heap allocation.
193///
194/// # Arguments
195///
196/// - `&Path` - Target file path.
197///
198/// # Returns
199///
200/// - `&'static str` - Canonical MIME type (defaults to `application/octet-stream`).
201#[inline]
202pub fn mime_for_path(path: &Path) -> &'static str {
203    let Some(ext_str) = path.extension().and_then(OsStr::to_str) else {
204        return APPLICATION_OCTET_STREAM;
205    };
206    if ext_str.is_empty() {
207        return APPLICATION_OCTET_STREAM;
208    }
209    let bytes: &[u8] = ext_str.as_bytes();
210    let parsed: FileExtension = if !bytes.iter().any(|b: &u8| b.is_ascii_uppercase()) {
211        FileExtension::parse(ext_str)
212    } else if bytes.len() <= MIME_EXT_STACK_CAP {
213        let mut stack_buf: [u8; MIME_EXT_STACK_CAP] = [0u8; MIME_EXT_STACK_CAP];
214        for (dst, &src) in stack_buf.iter_mut().zip(bytes.iter()) {
215            *dst = src.to_ascii_lowercase();
216        }
217        match from_utf8(&stack_buf[..bytes.len()]) {
218            Ok(lower) => FileExtension::parse(lower),
219            Err(_) => FileExtension::parse(ext_str.to_ascii_lowercase()),
220        }
221    } else {
222        FileExtension::parse(ext_str.to_ascii_lowercase())
223    };
224    let mime: &'static str = parsed.get_content_type();
225    if mime.is_empty() {
226        APPLICATION_OCTET_STREAM
227    } else {
228        mime
229    }
230}
231
232/// Appends lowercase hexadecimal digits for `value` into `buf` at `pos` and returns the new offset.
233///
234/// # Arguments
235///
236/// - `u64` - Unsigned integer to format in lowercase hex.
237/// - `&mut [u8]` - Destination byte slice.
238/// - `usize` - Starting write offset.
239///
240/// # Returns
241///
242/// - `usize` - Updated write offset.
243#[inline]
244pub(crate) fn write_hex_u64_compact(mut value: u64, buf: &mut [u8], pos: usize) -> usize {
245    if value == 0 {
246        buf[pos] = b'0';
247        return pos + 1;
248    }
249    let mut tmp: [u8; 16] = [0u8; 16];
250    let mut idx: usize = 16;
251    while value > 0 {
252        idx -= 1;
253        tmp[idx] = HEX_DIGITS[(value & 0x0F) as usize];
254        value >>= 4;
255    }
256    let slice: &[u8] = &tmp[idx..];
257    buf[pos..pos + slice.len()].copy_from_slice(slice);
258    pos + slice.len()
259}
260
261/// Computes a deterministic strong `ETag` from file byte length and modification timestamp.
262///
263/// # Arguments
264///
265/// - `u64` - File size in bytes.
266/// - `u64` - Modification timestamp in milliseconds since Unix epoch.
267///
268/// # Returns
269///
270/// - `String` - Quoted strong ETag (for example `"\"400-18f123ab\""`).
271#[inline]
272pub(crate) fn compute_file_etag(size: u64, modified_ms: u64) -> String {
273    let mut buf: [u8; ETAG_STACK_CAP] = [0u8; ETAG_STACK_CAP];
274    buf[0] = b'"';
275    let mut pos: usize = write_hex_u64_compact(size, &mut buf, 1);
276    buf[pos] = b'-';
277    pos = write_hex_u64_compact(modified_ms, &mut buf, pos + 1);
278    buf[pos] = b'"';
279    pos += 1;
280    from_utf8(&buf[..pos]).unwrap_or_default().to_owned()
281}
282
283/// Extracts modification time in milliseconds since Unix epoch from filesystem [`Metadata`].
284///
285/// # Arguments
286///
287/// - `&Metadata` - File metadata.
288///
289/// # Returns
290///
291/// - `u64` - Modification timestamp in milliseconds, or `0` if unavailable.
292#[inline]
293pub(crate) fn metadata_modified_ms(meta: &Metadata) -> u64 {
294    meta.modified()
295        .ok()
296        .and_then(|ts: SystemTime| ts.duration_since(UNIX_EPOCH).ok())
297        .map(|dur: Duration| dur.as_millis() as u64)
298        .unwrap_or(0)
299}
300
301/// Checks whether an `If-None-Match` header matches `etag` (handling `*`, comma lists, and `W/` weak prefixes).
302///
303/// # Arguments
304///
305/// - `&str` - Incoming `If-None-Match` header value.
306/// - `&str` - Resource strong `ETag`.
307///
308/// # Returns
309///
310/// - `bool` - `true` when the client validator matches (`304 Not Modified`).
311#[inline]
312pub fn if_none_match_matches(header: &str, etag: &str) -> bool {
313    let trimmed: &str = header.trim();
314    if trimmed == ETAG_WILDCARD || trimmed == etag {
315        return true;
316    }
317    trimmed.split(',').any(|token: &str| {
318        let candidate: &str = token.trim();
319        let normalized: &str = candidate
320            .strip_prefix(WEAK_ETAG_PREFIX)
321            .unwrap_or(candidate);
322        normalized == etag
323    })
324}
325
326/// Parses an ASCII unsigned decimal integer from `bytes` without allocating.
327///
328/// # Arguments
329///
330/// - `&[u8]` - Trimmed ASCII digit bytes.
331///
332/// # Returns
333///
334/// - `Option<usize>` - Parsed integer, or `None` on empty, non-digit, or overflow.
335#[inline]
336pub(crate) fn parse_ascii_usize(bytes: &[u8]) -> Option<usize> {
337    if bytes.is_empty() {
338        return None;
339    }
340    let mut acc: usize = 0;
341    for &b in bytes {
342        if !b.is_ascii_digit() {
343            return None;
344        }
345        acc = acc.checked_mul(10)?.checked_add((b - b'0') as usize)?;
346    }
347    Some(acc)
348}
349
350/// Parses a single RFC 9110 byte `Range` header (`bytes=start-end`, `bytes=start-`, `bytes=-suffix`).
351///
352/// # Arguments
353///
354/// - `&str` - Raw `Range` header value.
355/// - `usize` - Total resource length in bytes.
356///
357/// # Returns
358///
359/// - `Option<(usize, usize)>` - Inclusive `(start, end)` byte offsets, or `None` when unsatisfiable/invalid.
360#[inline]
361pub fn parse_byte_range(header: &str, total_len: usize) -> Option<(usize, usize)> {
362    if total_len == 0 {
363        return None;
364    }
365    let trimmed: &str = header.trim();
366    let spec: &str = trimmed.strip_prefix(RANGE_BYTES_PREFIX)?;
367    if spec.as_bytes().contains(&b',') {
368        return None;
369    }
370    let (start_str, end_str): (&str, &str) = spec.split_once('-')?;
371    let start_bytes: &[u8] = start_str.trim().as_bytes();
372    let end_bytes: &[u8] = end_str.trim().as_bytes();
373    if start_bytes.is_empty() {
374        let suffix: usize = parse_ascii_usize(end_bytes)?;
375        if suffix == 0 {
376            return None;
377        }
378        let start: usize = total_len.saturating_sub(suffix);
379        return Some((start, total_len - 1));
380    }
381    let start: usize = parse_ascii_usize(start_bytes)?;
382    if start >= total_len {
383        return None;
384    }
385    let end: usize = if end_bytes.is_empty() {
386        total_len - 1
387    } else {
388        parse_ascii_usize(end_bytes)?.min(total_len - 1)
389    };
390    if start > end {
391        return None;
392    }
393    Some((start, end))
394}
395
396/// Appends decimal digits for `value` into `buf` at `pos` and returns the new offset.
397///
398/// # Arguments
399///
400/// - `usize` - Unsigned integer to format.
401/// - `&mut [u8]` - Destination byte slice.
402/// - `usize` - Starting write offset.
403///
404/// # Returns
405///
406/// - `usize` - Updated write offset.
407#[inline]
408pub(crate) fn write_usize_decimal(mut value: usize, buf: &mut [u8], pos: usize) -> usize {
409    if value == 0 {
410        buf[pos] = b'0';
411        return pos + 1;
412    }
413    let mut digits: [u8; 20] = [0u8; 20];
414    let mut idx: usize = 20;
415    while value > 0 {
416        idx -= 1;
417        digits[idx] = b'0' + (value % 10) as u8;
418        value /= 10;
419    }
420    let slice: &[u8] = &digits[idx..];
421    buf[pos..pos + slice.len()].copy_from_slice(slice);
422    pos + slice.len()
423}
424
425/// Formats `bytes <start>-<end>/<total>` into a stack buffer without heap allocation.
426///
427/// # Arguments
428///
429/// - `usize` - Inclusive range start offset.
430/// - `usize` - Inclusive range end offset.
431/// - `usize` - Total entity length in bytes.
432/// - `&mut [u8; CONTENT_RANGE_STACK_CAP]` - Stack destination buffer.
433///
434/// # Returns
435///
436/// - `&str` - Borrowed formatted `Content-Range` value.
437#[inline]
438pub(crate) fn format_content_range_stack(
439    start: usize,
440    end: usize,
441    total: usize,
442    buf: &mut [u8; CONTENT_RANGE_STACK_CAP],
443) -> &str {
444    let prefix: &[u8] = CONTENT_RANGE_BYTES_PREFIX.as_bytes();
445    buf[..prefix.len()].copy_from_slice(prefix);
446    let mut pos: usize = write_usize_decimal(start, buf, prefix.len());
447    buf[pos] = b'-';
448    pos = write_usize_decimal(end, buf, pos + 1);
449    buf[pos] = b'/';
450    pos = write_usize_decimal(total, buf, pos + 1);
451    from_utf8(&buf[..pos]).unwrap_or_default()
452}
453
454/// Formats `bytes */<total>` into a stack buffer without heap allocation.
455///
456/// # Arguments
457///
458/// - `usize` - Total entity length in bytes.
459/// - `&mut [u8; CONTENT_RANGE_STACK_CAP]` - Stack destination buffer.
460///
461/// # Returns
462///
463/// - `&str` - Borrowed formatted unsatisfiable `Content-Range` value.
464#[inline]
465pub(crate) fn format_unsatisfiable_range_stack(
466    total: usize,
467    buf: &mut [u8; CONTENT_RANGE_STACK_CAP],
468) -> &str {
469    let prefix: &[u8] = CONTENT_RANGE_UNSAT_PREFIX.as_bytes();
470    buf[..prefix.len()].copy_from_slice(prefix);
471    let pos: usize = write_usize_decimal(total, buf, prefix.len());
472    from_utf8(&buf[..pos]).unwrap_or_default()
473}
474
475/// Parses `Accept-Encoding` into a two-bit sidecar acceptance mask (`ENCODING_MASK_BR | ENCODING_MASK_GZIP`) in one pass.
476///
477/// # Arguments
478///
479/// - `&str` - Incoming `Accept-Encoding` header value.
480///
481/// # Returns
482///
483/// - `u8` - Bitmask of accepted precompressed sidecar encodings.
484#[inline]
485pub(crate) fn accept_encoding_mask(accept_encoding: &str) -> u8 {
486    let has_params: bool = accept_encoding.as_bytes().contains(&b';');
487    let mut mask: u8 = 0;
488    for part in accept_encoding.split(',') {
489        if !has_params {
490            let coding: &str = part.trim();
491            if coding.eq_ignore_ascii_case(ENCODING_BR) {
492                mask |= ENCODING_MASK_BR;
493            } else if coding.eq_ignore_ascii_case(ENCODING_GZIP) {
494                mask |= ENCODING_MASK_GZIP;
495            }
496            if mask == (ENCODING_MASK_BR | ENCODING_MASK_GZIP) {
497                break;
498            }
499            continue;
500        }
501        let mut segments: Split<'_, char> = part.trim().split(';');
502        let coding: &str = segments.next().unwrap_or_default().trim();
503        let bit: u8 = if coding.eq_ignore_ascii_case(ENCODING_BR) {
504            ENCODING_MASK_BR
505        } else if coding.eq_ignore_ascii_case(ENCODING_GZIP) {
506            ENCODING_MASK_GZIP
507        } else {
508            continue;
509        };
510        let mut rejected: bool = false;
511        for param in segments {
512            let trimmed: &str = param.trim();
513            if let Some(qval) = trimmed
514                .strip_prefix("q=")
515                .or_else(|| trimmed.strip_prefix("Q="))
516                && qval.trim().parse::<f32>().ok() == Some(0.0)
517            {
518                rejected = true;
519            }
520        }
521        if !rejected {
522            mask |= bit;
523        }
524    }
525    mask
526}
527
528/// Borrows the last value of lowercase request header `name` without allocating.
529///
530/// # Arguments
531///
532/// - `&'a Request` - Incoming HTTP request.
533/// - `&str` - Lowercase header key.
534///
535/// # Returns
536///
537/// - `Option<&'a str>` - Borrowed last header value, if present.
538#[inline]
539pub(crate) fn get_request_header_back_ref<'a>(request: &'a Request, name: &str) -> Option<&'a str> {
540    request
541        .get_headers()
542        .get(name)
543        .and_then(|values: &RequestHeadersValue| values.back())
544        .map(String::as_str)
545}