hyperlane_plugin_static_files/impl.rs
1use super::*;
2
3impl Default for StaticFilesConfig {
4 /// Builds the configuration the plugin uses when none is given.
5 ///
6 /// # Returns
7 ///
8 /// - `Self` - The default configuration.
9 fn default() -> Self {
10 Self {
11 root: PathBuf::from("."),
12 index: INDEX_DEFAULT.to_owned(),
13 }
14 }
15}
16
17impl StaticFilesConfig {
18 /// The file a path names under the root, when the path is allowed.
19 ///
20 /// A path that climbs out of the root is refused, so a request cannot
21 /// reach a file the root does not hold.
22 ///
23 /// # Arguments
24 ///
25 /// - `&str` - The path of the file, relative to the root.
26 ///
27 /// # Returns
28 ///
29 /// - `Option<PathBuf>` - The file, when the path is allowed.
30 pub fn resolve(&self, path: &str) -> Option<PathBuf> {
31 let mut file: PathBuf = self.get_root().clone();
32 if path.is_empty() {
33 file.push(self.get_index());
34 return Some(file);
35 }
36 for segment in path.split(SEPARATOR_SLASH) {
37 if segment.is_empty()
38 || segment == SEGMENT_CURRENT
39 || segment == SEGMENT_PARENT
40 || segment.contains(SEPARATOR_BACKSLASH)
41 {
42 return None;
43 }
44 file.push(segment);
45 }
46 Some(file)
47 }
48
49 /// The content type of a file, by the extension of its name.
50 ///
51 /// A file whose extension the framework does not know is served as a
52 /// stream of bytes.
53 ///
54 /// # Arguments
55 ///
56 /// - `&Path` - The file that is served.
57 ///
58 /// # Returns
59 ///
60 /// - `String` - The content type of the file.
61 pub fn content_type(&self, file: &Path) -> String {
62 let path: String = file.to_string_lossy().to_string();
63 let extension: String = FileExtension::get_extension_name(path);
64 let content_type: &str = FileExtension::parse(extension).get_content_type();
65 if content_type.is_empty() {
66 return APPLICATION_OCTET_STREAM.to_owned();
67 }
68 content_type.to_owned()
69 }
70}
71
72impl StaticFilesPlugin {
73 /// Stores the configuration the plugin works from.
74 ///
75 /// # Arguments
76 ///
77 /// - `StaticFilesConfig` - The configuration to store.
78 ///
79 /// # Returns
80 ///
81 /// - `Result<(), String>` - Nothing, or the reason the configuration was
82 /// refused.
83 pub fn init(config: StaticFilesConfig) -> Result<(), String> {
84 CONFIG.set(config).map_err(|_: StaticFilesConfig| {
85 "the static file configuration was already set".to_owned()
86 })
87 }
88
89 /// The configuration the plugin works from.
90 ///
91 /// # Returns
92 ///
93 /// - `Option<&'static StaticFilesConfig>` - The configuration, when it was
94 /// set.
95 pub fn get() -> Option<&'static StaticFilesConfig> {
96 CONFIG.get()
97 }
98
99 /// The route pattern that serves the files under a prefix.
100 ///
101 /// # Arguments
102 ///
103 /// - `&str` - The path the files are served under.
104 ///
105 /// # Returns
106 ///
107 /// - `String` - The pattern of the route.
108 pub fn pattern(prefix: &str) -> String {
109 PATTERN_FORMAT.replace("{prefix}", prefix)
110 }
111}
112
113impl ServerHook for StaticFilesRoute {
114 /// Builds the route.
115 ///
116 /// # Arguments
117 ///
118 /// - `&mut Stream` - The stream the request arrived on.
119 /// - `&mut Context` - The context of the request.
120 ///
121 /// # Returns
122 ///
123 /// - `Self` - The route.
124 async fn new(_: &mut Stream, _: &mut Context) -> Self {
125 Self
126 }
127
128 /// Answers with the file the path names.
129 ///
130 /// A path that names no file is answered with the status of a missing
131 /// file.
132 ///
133 /// # Arguments
134 ///
135 /// - `Self` - The route.
136 /// - `&mut Stream` - The stream the request arrived on.
137 /// - `&mut Context` - The context of the request.
138 ///
139 /// # Returns
140 ///
141 /// - `Status` - Whether the pipeline continues.
142 async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
143 let config: &StaticFilesConfig = match CONFIG.get() {
144 Some(config) => config,
145 None => return Status::Continue,
146 };
147 let path: String = ctx.get_route_param(PARAM_PATH);
148 let file: Option<PathBuf> = config.resolve(&path);
149 let file: PathBuf = match file {
150 Some(file) => file,
151 None => return Self::not_found(ctx),
152 };
153 let data: Vec<u8> = match fs::read(&file).await {
154 Ok(data) => data,
155 Err(_) => return Self::not_found(ctx),
156 };
157 let content_type: String = config.content_type(&file);
158 let response: &mut Response = ctx.get_mut_response();
159 response.set_status_code(HttpStatus::Ok.code());
160 response.set_header(CONTENT_TYPE, content_type);
161 response.set_body(data);
162 Status::Continue
163 }
164}
165
166impl StaticFilesRoute {
167 /// Answers with the status of a file that is not there.
168 ///
169 /// # Arguments
170 ///
171 /// - `&mut Context` - The context of the request.
172 ///
173 /// # Returns
174 ///
175 /// - `Status` - Whether the pipeline continues.
176 fn not_found(ctx: &mut Context) -> Status {
177 let response: &mut Response = ctx.get_mut_response();
178 response.set_status_code(HttpStatus::NotFound.code());
179 Status::Continue
180 }
181}