1use super::*;
2
3impl Hasher for FxHasher {
5 #[inline(always)]
11 fn finish(&self) -> u64 {
12 let Self { state } = *self;
13 state
14 }
15
16 #[inline(always)]
22 fn write(&mut self, bytes: &[u8]) {
23 let Self { state } = self;
24 let mut h: u64 = *state;
25 let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
26 for chunk in chunks {
27 h = (h.rotate_left(5) ^ u64::from_ne_bytes(*chunk)).wrapping_mul(FX_HASH_K);
28 }
29 let mut tail: &[u8] = rem;
30 if tail.len() >= 4 {
31 let word: u32 = u32::from_ne_bytes([tail[0], tail[1], tail[2], tail[3]]);
32 h = (h.rotate_left(5) ^ u64::from(word)).wrapping_mul(FX_HASH_K);
33 tail = &tail[4..];
34 }
35 if tail.len() >= 2 {
36 let half: u16 = u16::from_ne_bytes([tail[0], tail[1]]);
37 h = (h.rotate_left(5) ^ u64::from(half)).wrapping_mul(FX_HASH_K);
38 tail = &tail[2..];
39 }
40 if let Some(&b) = tail.first() {
41 h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(FX_HASH_K);
42 }
43 *state = h;
44 }
45
46 #[inline(always)]
52 fn write_u8(&mut self, i: u8) {
53 let Self { state } = self;
54 *state = (state.rotate_left(5) ^ u64::from(i)).wrapping_mul(FX_HASH_K);
55 }
56}
57
58impl CachedFile {
60 fn build_wire(&self, status: HttpStatus, cache_control: &str, include_body: bool) -> Arc<[u8]> {
72 let Self {
73 bytes,
74 etag,
75 content_type,
76 content_encoding,
77 ..
78 } = self;
79 let mut resp: Response = Response::default();
80 resp.set_status_code(status.code())
81 .set_header(CONTENT_TYPE, *content_type)
82 .set_header(ETAG, etag)
83 .set_header(ACCEPT_RANGES, ACCEPT_RANGES_BYTES);
84 if !cache_control.is_empty() {
85 resp.set_header(CACHE_CONTROL, cache_control);
86 }
87 if let Some(enc) = *content_encoding {
88 resp.set_header(CONTENT_ENCODING, enc)
89 .set_header(VARY, VARY_ACCEPT_ENCODING);
90 }
91 if include_body {
92 resp.set_body(bytes.as_ref());
93 }
94 let wire: Vec<u8> = resp.build();
95 Arc::from(wire.into_boxed_slice())
96 }
97
98 #[inline]
108 pub(crate) fn get_wire_ok(&self, cache_control: &str) -> &[u8] {
109 let Self { wire_ok, .. } = self;
110 wire_ok
111 .get_or_init(|| self.build_wire(HttpStatus::Ok, cache_control, true))
112 .as_ref()
113 }
114
115 #[inline]
125 pub(crate) fn get_wire_head(&self, cache_control: &str) -> &[u8] {
126 let Self { wire_head, .. } = self;
127 wire_head
128 .get_or_init(|| self.build_wire(HttpStatus::Ok, cache_control, false))
129 .as_ref()
130 }
131
132 #[inline]
142 pub(crate) fn get_wire_304(&self, cache_control: &str) -> &[u8] {
143 let Self { wire_304, .. } = self;
144 wire_304
145 .get_or_init(|| self.build_wire(HttpStatus::NotModified, cache_control, false))
146 .as_ref()
147 }
148}
149
150impl StaticFilesConfig {
152 pub fn new<P>(root_dir: P) -> Self
162 where
163 P: Into<PathBuf>,
164 {
165 Self {
166 root_dir: root_dir.into(),
167 mount_prefix: DEFAULT_STATIC_MOUNT_PREFIX.to_owned(),
168 index_file: DEFAULT_STATIC_INDEX_FILE.to_owned(),
169 spa_fallback: None,
170 cache_control: DEFAULT_STATIC_CACHE_CONTROL.to_owned(),
171 serve_precompressed: true,
172 allow_dotfiles: false,
173 max_cache_bytes: DEFAULT_STATIC_MAX_CACHE_BYTES,
174 max_file_cache_bytes: DEFAULT_STATIC_MAX_FILE_CACHE_BYTES,
175 }
176 }
177
178 pub fn with_mount_prefix<P>(mut self, prefix: P) -> Self
188 where
189 P: Into<String>,
190 {
191 self.set_mount_prefix(prefix.into());
192 self
193 }
194
195 pub fn with_spa_fallback<F>(mut self, fallback: F) -> Self
205 where
206 F: Into<String>,
207 {
208 self.set_spa_fallback(Some(fallback.into()));
209 self
210 }
211
212 pub fn with_cache_control<C>(mut self, cache_control: C) -> Self
222 where
223 C: Into<String>,
224 {
225 self.set_cache_control(cache_control.into());
226 self
227 }
228
229 pub fn with_serve_precompressed(mut self, enabled: bool) -> Self {
239 self.set_serve_precompressed(enabled);
240 self
241 }
242}
243
244impl StaticFilesRuntime {
246 pub fn new(config: StaticFilesConfig) -> Result<Self, String> {
256 let canonical_root: PathBuf =
257 canonicalize(config.get_root_dir()).map_err(|err: io::Error| err.to_string())?;
258 let trimmed: &str = config.get_mount_prefix().trim();
259 let normalized_prefix: String = if trimmed.is_empty() || trimmed == "/" {
260 "/".to_owned()
261 } else if trimmed.starts_with('/') {
262 trimmed.trim_end_matches('/').to_owned()
263 } else {
264 format!("/{}", trimmed.trim_end_matches('/'))
265 };
266 let cache_shards: Box<[StaticCacheShard; STATIC_CACHE_SHARDS]> =
267 Box::new(from_fn(|_: usize| StaticCacheShard {
268 map: RwLock::new(HashMap::default()),
269 }));
270 Ok(Self {
271 inner: Arc::new(StaticFilesRuntimeInner {
272 config,
273 canonical_root,
274 normalized_prefix,
275 cached_bytes: AtomicUsize::new(0),
276 cache_shards,
277 }),
278 })
279 }
280
281 pub fn get_config(&self) -> &StaticFilesConfig {
287 let Self { inner } = self;
288 &inner.config
289 }
290
291 pub fn cached_bytes(&self) -> usize {
297 let Self { inner } = self;
298 inner.cached_bytes.load(Ordering::Relaxed)
299 }
300
301 pub(crate) fn strip_mount<'a>(&self, path: &'a str) -> Option<&'a str> {
311 let Self { inner } = self;
312 if inner.normalized_prefix == "/" {
313 return Some(path);
314 }
315 let rest: &'a str = path.strip_prefix(inner.normalized_prefix.as_str())?;
316 if rest.is_empty() || rest.starts_with('/') {
317 Some(rest)
318 } else {
319 None
320 }
321 }
322
323 #[inline]
334 fn select_cached_variant(entry: &CachedRouteEntry, enc_mask: u8) -> Arc<CachedFile> {
335 if (enc_mask & ENCODING_MASK_BR) != 0
336 && let Some(br_file) = &entry.br
337 {
338 return Arc::clone(br_file);
339 }
340 if (enc_mask & ENCODING_MASK_GZIP) != 0
341 && let Some(gz_file) = &entry.gz
342 {
343 return Arc::clone(gz_file);
344 }
345 Arc::clone(&entry.raw)
346 }
347
348 async fn read_disk_file(
360 disk_path: &Path,
361 content_type: &'static str,
362 content_encoding: Option<&'static str>,
363 ) -> Option<Arc<CachedFile>> {
364 let meta: Metadata = fs::metadata(disk_path).await.ok()?;
365 if !meta.is_file() {
366 return None;
367 }
368 let modified_ms: u64 = metadata_modified_ms(&meta);
369 let raw_bytes: Vec<u8> = fs::read(disk_path).await.ok()?;
370 let etag: String = compute_file_etag(raw_bytes.len() as u64, modified_ms);
371 Some(Arc::new(CachedFile {
372 bytes: Arc::from(raw_bytes),
373 etag,
374 content_type,
375 content_encoding,
376 wire_ok: OnceLock::new(),
377 wire_head: OnceLock::new(),
378 wire_304: OnceLock::new(),
379 }))
380 }
381
382 async fn load_sidecar(
395 &self,
396 canonical_base: &Path,
397 ext: &str,
398 mime: &'static str,
399 encoding: &'static str,
400 ) -> Option<Arc<CachedFile>> {
401 let Self { inner } = self;
402 let mut sidecar_os: OsString = canonical_base.as_os_str().to_os_string();
403 sidecar_os.push(ext);
404 let sidecar_path: PathBuf = PathBuf::from(sidecar_os);
405 let canon_sidecar: PathBuf = fs::canonicalize(&sidecar_path).await.ok()?;
406 if !canon_sidecar.starts_with(&inner.canonical_root) {
407 return None;
408 }
409 Self::read_disk_file(&canon_sidecar, mime, Some(encoding)).await
410 }
411
412 async fn resolve_and_cache_miss(
424 &self,
425 cache_key: &str,
426 shard_idx: usize,
427 enc_mask: u8,
428 ) -> Option<Arc<CachedFile>> {
429 let Self { inner } = self;
430 let candidate: PathBuf = resolve_safe_path(
431 &inner.canonical_root,
432 cache_key,
433 inner.config.get_allow_dotfiles(),
434 )?;
435 let resolved_base: PathBuf = match fs::metadata(&candidate).await {
436 Ok(meta) if meta.is_dir() => candidate.join(inner.config.get_index_file()),
437 Ok(meta) if meta.is_file() => candidate,
438 _ => match inner.config.get_spa_fallback() {
439 Some(fallback) => inner.canonical_root.join(fallback),
440 None => return None,
441 },
442 };
443 let canonical_base: PathBuf = fs::canonicalize(&resolved_base).await.ok()?;
444 if !canonical_base.starts_with(&inner.canonical_root) {
445 return None;
446 }
447 let mime: &'static str = mime_for_path(&canonical_base);
448 let max_cache: usize = inner.config.get_max_cache_bytes();
449 let max_file_cache: usize = inner.config.get_max_file_cache_bytes();
450 let serve_precompressed: bool = inner.config.get_serve_precompressed();
451 if max_cache == 0 {
452 if serve_precompressed
453 && (enc_mask & ENCODING_MASK_BR) != 0
454 && let Some(br_file) = self
455 .load_sidecar(&canonical_base, SIDECAR_BR_EXT, mime, ENCODING_BR)
456 .await
457 {
458 return Some(br_file);
459 }
460 if serve_precompressed
461 && (enc_mask & ENCODING_MASK_GZIP) != 0
462 && let Some(gz_file) = self
463 .load_sidecar(&canonical_base, SIDECAR_GZ_EXT, mime, ENCODING_GZIP)
464 .await
465 {
466 return Some(gz_file);
467 }
468 return Self::read_disk_file(&canonical_base, mime, None).await;
469 }
470 let raw_file: Arc<CachedFile> = Self::read_disk_file(&canonical_base, mime, None).await?;
471 let br_file: Option<Arc<CachedFile>> = if serve_precompressed {
472 self.load_sidecar(&canonical_base, SIDECAR_BR_EXT, mime, ENCODING_BR)
473 .await
474 } else {
475 None
476 };
477 let gz_file: Option<Arc<CachedFile>> = if serve_precompressed {
478 self.load_sidecar(&canonical_base, SIDECAR_GZ_EXT, mime, ENCODING_GZIP)
479 .await
480 } else {
481 None
482 };
483 let entry: Arc<CachedRouteEntry> = Arc::new(CachedRouteEntry {
484 raw: raw_file,
485 br: br_file,
486 gz: gz_file,
487 });
488 let entry_bytes: usize = entry.raw.bytes.len()
489 + entry
490 .br
491 .as_ref()
492 .map_or(0, |f: &Arc<CachedFile>| f.bytes.len())
493 + entry
494 .gz
495 .as_ref()
496 .map_or(0, |f: &Arc<CachedFile>| f.bytes.len());
497 if entry.raw.bytes.len() <= max_file_cache
498 && inner.cached_bytes.load(Ordering::Relaxed) + entry_bytes <= max_cache
499 && let Ok(mut guard) = inner.cache_shards[shard_idx].map.write()
500 {
501 if let Some(prev) = guard.insert(cache_key.to_owned(), Arc::clone(&entry)) {
502 let prev_bytes: usize = prev.raw.bytes.len()
503 + prev
504 .br
505 .as_ref()
506 .map_or(0, |f: &Arc<CachedFile>| f.bytes.len())
507 + prev
508 .gz
509 .as_ref()
510 .map_or(0, |f: &Arc<CachedFile>| f.bytes.len());
511 inner.cached_bytes.fetch_sub(prev_bytes, Ordering::Relaxed);
512 }
513 inner.cached_bytes.fetch_add(entry_bytes, Ordering::Relaxed);
514 }
515 Some(Self::select_cached_variant(&entry, enc_mask))
516 }
517
518 #[inline]
528 async fn resolve_file_for_context(&self, ctx: &Context) -> Option<(Arc<CachedFile>, bool)> {
529 let Self { inner } = self;
530 let request: &Request = ctx.get_request();
531 let is_get: bool = request.get_method().is_get();
532 let is_head: bool = !is_get && request.get_method().is_head();
533 if !is_get && !is_head {
534 return None;
535 }
536 let relative_url: &str = self.strip_mount(request.get_path())?;
537 let safe_rel: Cow<'_, str> =
538 validate_and_decode_relative(relative_url, inner.config.get_allow_dotfiles())?;
539 let cache_key: &str = safe_rel.as_ref();
540 let enc_mask: u8 = if inner.config.get_serve_precompressed() {
541 get_request_header_back_ref(request, ACCEPT_ENCODING).map_or(0, accept_encoding_mask)
542 } else {
543 0
544 };
545 let shard_idx: usize = static_cache_shard_index(cache_key);
546 let cached_hit: Option<Arc<CachedFile>> = if inner.config.get_max_cache_bytes() > 0 {
547 inner.cache_shards[shard_idx].map.read().ok().and_then(
548 |guard: RwLockReadGuard<'_, StaticCacheShardMap>| {
549 guard.get(cache_key).map(|entry: &Arc<CachedRouteEntry>| {
550 Self::select_cached_variant(entry, enc_mask)
551 })
552 },
553 )
554 } else {
555 None
556 };
557 let file: Arc<CachedFile> = if let Some(hit) = cached_hit {
558 hit
559 } else {
560 self.resolve_and_cache_miss(cache_key, shard_idx, enc_mask)
561 .await?
562 };
563 Some((file, is_head))
564 }
565
566 #[inline]
574 fn populate_response(&self, ctx: &mut Context, file: &CachedFile, is_head: bool) {
575 let Self { inner } = self;
576 let is_not_modified: bool = get_request_header_back_ref(ctx.get_request(), IF_NONE_MATCH)
577 .is_some_and(|inm: &str| if_none_match_matches(inm, &file.etag));
578 let total: usize = file.bytes.len();
579 let range_eval: Option<Option<(usize, usize)>> = if is_not_modified {
580 None
581 } else {
582 get_request_header_back_ref(ctx.get_request(), RANGE)
583 .map(|range_val: &str| parse_byte_range(range_val, total))
584 };
585 let cache_control: &str = inner.config.get_cache_control();
586 let response: &mut Response = ctx.get_mut_response();
587 response
588 .set_header(CONTENT_TYPE, file.content_type)
589 .set_header(ETAG, &file.etag)
590 .set_header(ACCEPT_RANGES, ACCEPT_RANGES_BYTES);
591 if !cache_control.is_empty() {
592 response.set_header(CACHE_CONTROL, cache_control);
593 }
594 if let Some(enc) = file.content_encoding {
595 response
596 .set_header(CONTENT_ENCODING, enc)
597 .set_header(VARY, VARY_ACCEPT_ENCODING);
598 }
599 if is_not_modified {
600 response.set_status_code(HttpStatus::NotModified.code());
601 response.get_mut_body().clear();
602 return;
603 }
604 if let Some(parsed_range) = range_eval {
605 let mut cr_buf: [u8; CONTENT_RANGE_STACK_CAP] = [0u8; CONTENT_RANGE_STACK_CAP];
606 match parsed_range {
607 Some((start, end)) => {
608 let cr_str: &str = format_content_range_stack(start, end, total, &mut cr_buf);
609 response
610 .set_status_code(HttpStatus::PartialContent.code())
611 .set_header(CONTENT_RANGE, cr_str);
612 let body_buf: &mut Vec<u8> = response.get_mut_body();
613 body_buf.clear();
614 if !is_head {
615 body_buf.extend_from_slice(&file.bytes[start..=end]);
616 }
617 }
618 None => {
619 let cr_str: &str = format_unsatisfiable_range_stack(total, &mut cr_buf);
620 response
621 .set_status_code(HttpStatus::RangeNotSatisfiable.code())
622 .set_header(CONTENT_RANGE, cr_str);
623 response.get_mut_body().clear();
624 }
625 }
626 return;
627 }
628 response.set_status_code(HttpStatus::Ok.code());
629 let body_buf: &mut Vec<u8> = response.get_mut_body();
630 body_buf.clear();
631 if !is_head {
632 body_buf.extend_from_slice(file.bytes.as_ref());
633 }
634 }
635
636 pub async fn serve_context(&self, ctx: &mut Context) -> bool {
646 let Some((file, is_head)) = self.resolve_file_for_context(ctx).await else {
647 return false;
648 };
649 self.populate_response(ctx, &file, is_head);
650 true
651 }
652
653 #[inline]
664 pub(crate) async fn serve_and_send_hook(
665 &self,
666 stream: &mut Stream,
667 ctx: &mut Context,
668 ) -> Status {
669 let Self { inner } = self;
670 let Some((file, is_head)) = self.resolve_file_for_context(ctx).await else {
671 return Status::Continue;
672 };
673 let resp: &Response = ctx.get_response();
674 let can_fast_wire: bool = ctx.get_request().get_version().is_http1_1()
675 && resp.get_version().is_http1_1()
676 && resp.get_headers().is_empty()
677 && (resp.get_reason_phrase().is_empty() || resp.get_reason_phrase().as_str() == OK);
678 if can_fast_wire {
679 let cache_control: &str = inner.config.get_cache_control();
680 let is_not_modified: bool =
681 get_request_header_back_ref(ctx.get_request(), IF_NONE_MATCH)
682 .is_some_and(|inm: &str| if_none_match_matches(inm, &file.etag));
683 if is_not_modified {
684 let wire: &[u8] = file.get_wire_304(cache_control);
685 let _: Result<(), ResponseError> = stream.try_send(wire).await;
686 return Status::Reject;
687 }
688 if get_request_header_back_ref(ctx.get_request(), RANGE).is_none() {
689 let wire: &[u8] = if is_head {
690 file.get_wire_head(cache_control)
691 } else {
692 file.get_wire_ok(cache_control)
693 };
694 let _: Result<(), ResponseError> = stream.try_send(wire).await;
695 return Status::Reject;
696 }
697 }
698 self.populate_response(ctx, &file, is_head);
699 let wire: Vec<u8> = ctx.get_mut_response().build();
700 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
701 Status::Reject
702 }
703}
704
705impl StaticFilesPlugin {
707 pub fn init(config: StaticFilesConfig) -> Result<&'static Self, String> {
717 let runtime: StaticFilesRuntime = StaticFilesRuntime::new(config)?;
718 Ok(STATIC_FILES_PLUGIN.get_or_init(|| Self { runtime }))
719 }
720
721 pub fn get() -> Option<&'static Self> {
727 STATIC_FILES_PLUGIN.get()
728 }
729
730 pub fn get_runtime(&self) -> &StaticFilesRuntime {
736 let Self { runtime } = self;
737 runtime
738 }
739}
740
741impl ServerHook for StaticFilesHook {
743 async fn new(_: &mut Stream, _: &mut Context) -> Self {
754 Self
755 }
756
757 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
769 let Some(plugin) = StaticFilesPlugin::get() else {
770 return Status::Continue;
771 };
772 plugin.get_runtime().serve_and_send_hook(stream, ctx).await
773 }
774}