hyperlane_plugin_static_files/
fn.rs1use super::*;
2
3#[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
19pub(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#[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#[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#[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#[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#[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#[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#[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#[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#[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#[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#[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#[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#[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#[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#[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#[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}