Skip to main content

yaiko_core/
static_files.rs

1use crate::{Handler, Request, Response};
2use async_trait::async_trait;
3use std::path::Path;
4use tokio::fs;
5
6pub struct StaticFiles {
7    dir: String,
8    prefix: String,
9}
10
11impl StaticFiles {
12    pub fn new(dir: &str, prefix: &str) -> Self {
13        StaticFiles {
14            dir: dir.to_string(),
15            prefix: prefix.to_string(),
16        }
17    }
18
19    pub fn matches(&self, path: &str) -> bool {
20        path.starts_with(&self.prefix)
21    }
22
23    pub fn prefix(&self) -> &str {
24        &self.prefix
25    }
26
27    async fn serve_file(
28        &self,
29        path: &str,
30    ) -> Result<Response, Box<dyn std::error::Error + Send + Sync>> {
31        let relative_path = path.trim_start_matches('/');
32        let mut file_path = Path::new(&self.dir).join(relative_path);
33        if file_path.is_dir() {
34            file_path = file_path.join("index.html");
35        }
36
37        // Security check: prevent directory traversal
38        let canonical_dir = std::fs::canonicalize(&self.dir)?;
39        let canonical_file = match file_path.canonicalize() {
40            Ok(path) => path,
41            Err(_) => {
42                return Ok(Response::new()
43                    .status(hyper::StatusCode::NOT_FOUND)
44                    .text("File not found"));
45            }
46        };
47
48        if !canonical_file.starts_with(&canonical_dir) {
49            return Ok(Response::new()
50                .status(hyper::StatusCode::FORBIDDEN)
51                .text("Forbidden"));
52        }
53
54        match fs::read(&file_path).await {
55            Ok(contents) => {
56                let mime_type = mime_guess::from_path(&file_path)
57                    .first_or_octet_stream()
58                    .to_string();
59
60                Ok(Response::new()
61                    .header("Content-Type", &mime_type)
62                    .header("Content-Length", &contents.len().to_string())
63                    .header("Cache-Control", "public, max-age=3600") // 1 hour cache
64                    .status(hyper::StatusCode::OK)
65                    .body(hyper::Body::from(contents)))
66            }
67            Err(_) => Ok(Response::new()
68                .status(hyper::StatusCode::NOT_FOUND)
69                .text("File not found")),
70        }
71    }
72}
73
74#[async_trait]
75impl Handler for StaticFiles {
76    async fn handle(
77        &self,
78        req: Request,
79    ) -> Result<Response, Box<dyn std::error::Error + Send + Sync>> {
80        let path = req.uri.path();
81        if path.starts_with(&self.prefix) {
82            let file_path = &path[self.prefix.len()..];
83            self.serve_file(file_path).await
84        } else {
85            Ok(Response::new()
86                .status(hyper::StatusCode::NOT_FOUND)
87                .text("Not Found"))
88        }
89    }
90}