/ src / content_fetcher.rs
content_fetcher.rs
 1  use std::fs;
 2  use std::path::{Path, PathBuf};
 3  
 4  use crate::eprintln_red;
 5  use crate::needed::Polar;
 6  
 7  pub(crate) fn path_retriever(uri: String) -> Polar<PathBuf> {
 8      // get root path of website
 9      let local_path = Path::new(".");
10      let resolved_local_path = match local_path.canonicalize() {
11          Ok(path) => path,
12          Err(_) => {
13              eprintln_red!("Error while getting root path of website!");
14              return Polar::Silly(500); // Return 500
15          }
16      };
17  
18      // get fully resolved path of request
19      let path_string = format!(".{}", uri);
20      let path = Path::new(&path_string);
21  
22      let mut resolved_path = match path.canonicalize() {
23          Ok(path) => path,
24          Err(_) => {
25              eprintln_red!("User gave invalid path! || {:?}", path);
26              return Polar::Silly(404); // Return 404
27          }
28      };
29  
30      if resolved_path.is_dir() {
31          resolved_path.push("index.html")
32      }
33  
34      // check if the request is in bounds of the website
35      if !resolved_path.starts_with(resolved_local_path) {
36          eprintln_red!("User tried to access out of bounds path! || {:?}", resolved_path);
37          Polar::Silly(404) // should prob make it return code 403, however it might be a security issue, so 404 will suffice
38      } else {
39          Polar::Some(resolved_path)
40      }
41  }
42  
43  pub(crate) fn file_retriever(path: &PathBuf) -> Polar<Vec<u8>> {
44      if path.is_file() {
45          match fs::read(&path) {
46              Ok(file) => Polar::Some(file),
47              Err(err) => {
48                  eprintln_red!("Error while trying to request {:?} || Msg: {}", path, err);
49                  Polar::Silly(500) // internal server error ig
50              }
51          }
52      } else if path.is_dir() {
53          Polar::Silly(500) // shouldn't happen since we do a check while getting the path, but if it does, oopsie woopsie!
54      } else {
55          Polar::Silly(404) // not found!
56      }
57  }