Skip to main content

rust_web_server/app/controller/static_resource/
mod.rs

1use std::env;
2use std::fs::{File, metadata};
3use file_ext::FileExt;
4use crate::controller::Controller;
5use crate::header::Header;
6use crate::mime_type::MimeType;
7use crate::range::{ContentRange, Range};
8use crate::request::{METHOD, Request};
9use crate::response::{Error, Response, STATUS_CODE_REASON_PHRASE};
10use crate::server::ConnectionInfo;
11use crate::symbol::SYMBOL;
12use crate::url::URL;
13
14#[cfg(test)]
15mod tests;
16
17pub struct StaticResourceController;
18
19impl Controller for StaticResourceController {
20    fn is_matching(request: &Request, _connection: &ConnectionInfo) -> bool {
21        if request.method != METHOD.get {
22            return false;
23        }
24
25        let url_array = ["http://", "localhost", &request.request_uri];
26        let url = url_array.join(SYMBOL.empty_string);
27
28        let boxed_url_components = URL::parse(&url);
29        if boxed_url_components.is_err() {
30            let message = boxed_url_components.as_ref().err().unwrap().to_string();
31            // unfallable
32            println!("unexpected error, {}", message);
33        }
34
35        let components = boxed_url_components.unwrap();
36
37        let os_specific_separator : String = FileExt::get_path_separator();
38        let os_specific_path = &components.path.replace(SYMBOL.slash, os_specific_separator.as_str());
39
40        let boxed_static_filepath = FileExt::get_static_filepath(&os_specific_path);
41        if boxed_static_filepath.is_err() {
42            return false
43        }
44
45        let static_filepath = boxed_static_filepath.unwrap();
46
47        let mut is_directory_with_index_html = false;
48
49        let boxed_md = metadata(&static_filepath);
50        if boxed_md.is_ok() {
51            let md = boxed_md.unwrap();
52            if md.is_dir() {
53                let mut directory_index : String = "index.html".to_string();
54
55                let last_char = components.path.chars().last().unwrap();
56                if last_char != '/' {
57                    let index : String = "index.html".to_string();
58                    directory_index = format!("{}{}", os_specific_separator, index);
59
60                }
61                let index_html_in_directory = format!("{}{}", static_filepath, directory_index);
62
63
64                let boxed_file = File::open(&index_html_in_directory);
65                if boxed_file.is_err() {
66                    return false
67                }
68
69                is_directory_with_index_html = true;
70            }
71        }
72
73
74
75        let boxed_file = File::open(&static_filepath);
76
77        let is_get = request.method == METHOD.get;
78        let is_head = request.method == METHOD.head;
79        let is_options = request.method == METHOD.options;
80
81        let is_matching_method = (is_get || is_head || is_options) && (request.request_uri != SYMBOL.slash);
82
83        if boxed_file.is_ok() || is_directory_with_index_html {
84            is_matching_method
85        } else {
86            // check if file with same name and .html extension exists
87            if static_filepath.ends_with(".html") {
88                return false
89            }
90
91            let html_suffix = ".html";
92            let html_file = [&components.path.replace(SYMBOL.slash, &FileExt::get_path_separator()), html_suffix].join(SYMBOL.empty_string);
93            let boxed_static_filepath = FileExt::get_static_filepath(&html_file);
94            if boxed_static_filepath.is_err() {
95                return false
96            }
97
98            let static_filepath = boxed_static_filepath.unwrap();
99            let boxed_file = File::open(&static_filepath);
100
101            boxed_file.is_ok() && is_matching_method
102        }
103
104    }
105
106    fn process(request: &Request, mut response: Response, _connection: &ConnectionInfo) -> Response {
107        let boxed_content_range_list = StaticResourceController::process_static_resources(&request);
108        if boxed_content_range_list.is_ok() {
109            let content_range_list = boxed_content_range_list.unwrap();
110
111            if content_range_list.len() != 0 {
112
113                let mut status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok;
114
115                let does_request_include_range_header = request.get_header(Header::_RANGE.to_string()).is_some();
116                if does_request_include_range_header {
117                    status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n206_partial_content;
118                }
119
120                let is_options_request = request.method == METHOD.options;
121                if is_options_request {
122                    status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n204_no_content;
123                }
124
125
126                let dir = env::current_dir().unwrap();
127                let working_directory = dir.as_path().to_str().unwrap();
128
129                let url_array = ["http://", "localhost", &request.request_uri];
130                let url = url_array.join(SYMBOL.empty_string);
131
132                let boxed_url_components = URL::parse(&url);
133                if boxed_url_components.is_err() {
134                    let message = boxed_url_components.as_ref().err().unwrap().to_string();
135                    // unfallable
136                    println!("unexpected error, {}", message);
137                }
138
139                let components = boxed_url_components.unwrap();
140
141                let static_filepath = [working_directory, components.path.as_str()].join(SYMBOL.empty_string);
142                let boxed_modified_date_time = FileExt::file_modified_utc(&static_filepath);
143
144                if boxed_modified_date_time.is_ok() {
145                    let modified_date_time = boxed_modified_date_time.unwrap();
146                    let last_modified_unix_nanos = Header{ name: Header::_LAST_MODIFIED_UNIX_EPOCH_NANOS.to_string(), value: modified_date_time.to_string() };
147                    response.headers.push(last_modified_unix_nanos);
148
149                    let file_size = metadata(&static_filepath).map(|m| m.len()).unwrap_or(0);
150                    let etag_value = format!("\"{}-{}\"", modified_date_time, file_size);
151
152                    let if_none_match = request.get_header(Header::_IF_NONE_MATCH.to_string());
153                    if let Some(inm) = if_none_match {
154                        if inm.value == etag_value || inm.value == "*" {
155                            response.status_code = *STATUS_CODE_REASON_PHRASE.n304_not_modified.status_code;
156                            response.reason_phrase = STATUS_CODE_REASON_PHRASE.n304_not_modified.reason_phrase.to_string();
157                            response.headers.push(Header { name: Header::_ETAG.to_string(), value: etag_value });
158                            return response;
159                        }
160                    }
161
162                    response.headers.push(Header { name: Header::_ETAG.to_string(), value: etag_value });
163                }
164
165                response.status_code = *status_code_reason_phrase.status_code;
166                response.reason_phrase = status_code_reason_phrase.reason_phrase.to_string();
167                response.content_range_list = content_range_list;
168
169            }
170        } else {
171            let error : Error = boxed_content_range_list.err().unwrap();
172            let body = error.message;
173
174            let content_range = Range::get_content_range(
175                Vec::from(body.as_bytes()),
176                MimeType::TEXT_HTML.to_string()
177            );
178
179            let content_range_list = vec![content_range];
180
181            response.status_code = *error.status_code_reason_phrase.status_code;
182            response.reason_phrase = error.status_code_reason_phrase.reason_phrase.to_string();
183            response.content_range_list = content_range_list;
184
185        }
186
187
188        response
189    }
190}
191
192//backward compatability
193impl StaticResourceController {
194
195    pub fn is_matching_request(request: &Request) -> bool {
196        let boxed_static_filepath = FileExt::get_static_filepath(&request.request_uri);
197        if boxed_static_filepath.is_err() {
198            return false
199        }
200
201        let static_filepath = boxed_static_filepath.unwrap();
202
203        let boxed_md = metadata(&static_filepath);
204        if boxed_md.is_err() {
205            return false
206        }
207
208        let md = boxed_md.unwrap();
209        if md.is_dir() {
210            return false
211        }
212
213        let boxed_file = File::open(&static_filepath);
214
215        let is_get = request.method == METHOD.get;
216        let is_head = request.method == METHOD.head;
217        let is_options = request.method == METHOD.options;
218        boxed_file.is_ok() && (is_get || is_head || is_options && request.request_uri != SYMBOL.slash)
219    }
220
221    pub fn process_request(request: &Request, mut response: Response) -> Response {
222        let boxed_content_range_list = StaticResourceController::process_static_resources(&request);
223        if boxed_content_range_list.is_ok() {
224            let content_range_list = boxed_content_range_list.unwrap();
225
226            if content_range_list.len() != 0 {
227
228                let mut status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok;
229
230                let does_request_include_range_header = request.get_header(Header::_RANGE.to_string()).is_some();
231                if does_request_include_range_header {
232                    status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n206_partial_content;
233                }
234
235                let is_options_request = request.method == METHOD.options;
236                if is_options_request {
237                    status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n204_no_content;
238                }
239
240
241                let dir = env::current_dir().unwrap();
242                let working_directory = dir.as_path().to_str().unwrap();
243                let static_filepath = [working_directory, request.request_uri.as_str()].join(SYMBOL.empty_string);
244                let boxed_modified_date_time = FileExt::file_modified_utc(&static_filepath);
245
246                if boxed_modified_date_time.is_ok() {
247                    let modified_date_time = boxed_modified_date_time.unwrap();
248                    let last_modified_unix_nanos = Header{ name: Header::_LAST_MODIFIED_UNIX_EPOCH_NANOS.to_string(), value: modified_date_time.to_string() };
249                    response.headers.push(last_modified_unix_nanos);
250
251                    let file_size = metadata(&static_filepath).map(|m| m.len()).unwrap_or(0);
252                    let etag_value = format!("\"{}-{}\"", modified_date_time, file_size);
253
254                    let if_none_match = request.get_header(Header::_IF_NONE_MATCH.to_string());
255                    if let Some(inm) = if_none_match {
256                        if inm.value == etag_value || inm.value == "*" {
257                            response.status_code = *STATUS_CODE_REASON_PHRASE.n304_not_modified.status_code;
258                            response.reason_phrase = STATUS_CODE_REASON_PHRASE.n304_not_modified.reason_phrase.to_string();
259                            response.headers.push(Header { name: Header::_ETAG.to_string(), value: etag_value });
260                            return response;
261                        }
262                    }
263
264                    response.headers.push(Header { name: Header::_ETAG.to_string(), value: etag_value });
265                }
266
267                response.status_code = *status_code_reason_phrase.status_code;
268                response.reason_phrase = status_code_reason_phrase.reason_phrase.to_string();
269                response.content_range_list = content_range_list;
270
271            }
272        } else {
273            let error : Error = boxed_content_range_list.err().unwrap();
274            let body = error.message;
275
276            let content_range = Range::get_content_range(
277                Vec::from(body.as_bytes()),
278                MimeType::TEXT_HTML.to_string()
279            );
280
281            let content_range_list = vec![content_range];
282
283            response.status_code = *error.status_code_reason_phrase.status_code;
284            response.reason_phrase = error.status_code_reason_phrase.reason_phrase.to_string();
285            response.content_range_list = content_range_list;
286
287        }
288
289
290        response
291    }
292
293    pub fn process_static_resources(request: &Request) -> Result<Vec<ContentRange>, Error> {
294        let dir = env::current_dir().unwrap();
295        let working_directory = dir.as_path().to_str().unwrap();
296
297        let url_array = ["http://", "localhost", &request.request_uri];
298        let url = url_array.join(SYMBOL.empty_string);
299
300        let boxed_url_components = URL::parse(&url);
301        if boxed_url_components.is_err() {
302            let message = boxed_url_components.as_ref().err().unwrap().to_string();
303            // unfallable
304            println!("unexpected error, {}", message);
305        }
306
307        let components = boxed_url_components.unwrap();
308
309        let os_specific_separator : String = FileExt::get_path_separator();
310        let os_specific_path = &components.path.replace(SYMBOL.slash, os_specific_separator.as_str());
311
312        let boxed_static_filepath = FileExt::get_static_filepath(&os_specific_path);
313
314        let static_filepath = boxed_static_filepath.unwrap();
315
316        let mut content_range_list = Vec::new();
317
318
319        let mut boxed_md = metadata(&static_filepath);
320        if boxed_md.is_err() {
321            let dot_html = format!("{}{}", &static_filepath, ".html");
322            boxed_md = metadata(&dot_html);
323
324            if boxed_md.is_err() {
325                let slash_index_html = format!("{}{}{}", &static_filepath, os_specific_separator,  "index.html");
326                boxed_md = metadata(&slash_index_html);
327            }
328        }
329        if boxed_md.is_ok() {
330            let md = boxed_md.unwrap();
331
332            if md.is_dir() {
333                let mut range_header = &Header {
334                    name: Header::_RANGE.to_string(),
335                    value: "bytes=0-".to_string()
336                };
337
338                let boxed_header = request.get_header(Header::_RANGE.to_string());
339                if boxed_header.is_some() {
340                    range_header = boxed_header.unwrap();
341                }
342
343                let mut directory_index : String = "index.html".to_string();
344
345                let last_char = components.path.chars().last().unwrap();
346                if last_char != '/' {
347                    let index : String = "index.html".to_string();
348                    directory_index = format!("{}{}", os_specific_separator, index);
349                }
350                let index_html_in_directory = format!("{}{}", os_specific_path, directory_index);
351
352
353                let boxed_content_range_list = Range::get_content_range_list(&index_html_in_directory, range_header);
354                if boxed_content_range_list.is_ok() {
355                    content_range_list = boxed_content_range_list.unwrap();
356                } else {
357                    let error = boxed_content_range_list.err().unwrap();
358                    return Err(error)
359                }
360
361                return Ok(content_range_list);
362            }
363
364            let boxed_file = File::open(&static_filepath);
365            if boxed_file.is_ok()  {
366                let md = metadata(&static_filepath).unwrap();
367                if md.is_dir() {
368                    let mut range_header = &Header {
369                        name: Header::_RANGE.to_string(),
370                        value: "bytes=0-".to_string()
371                    };
372
373                    let boxed_header = request.get_header(Header::_RANGE.to_string());
374                    if boxed_header.is_some() {
375                        range_header = boxed_header.unwrap();
376                    }
377
378                    let mut directory_index : String = "index.html".to_string();
379
380                    let last_char = components.path.chars().last().unwrap();
381                    if last_char != '/' {
382                        let index : String = "index.html".to_string();
383                        directory_index = format!("{}{}", os_specific_separator, index);
384                    }
385                    let index_html_in_directory = format!("{}{}", os_specific_path, directory_index);
386
387
388                    let boxed_content_range_list = Range::get_content_range_list(&index_html_in_directory, range_header);
389                    if boxed_content_range_list.is_ok() {
390                        content_range_list = boxed_content_range_list.unwrap();
391                    } else {
392                        let error = boxed_content_range_list.err().unwrap();
393                        return Err(error)
394                    }
395                }
396
397                if md.is_file() {
398                    let mut range_header = &Header {
399                        name: Header::_RANGE.to_string(),
400                        value: "bytes=0-".to_string()
401                    };
402
403                    let boxed_header = request.get_header(Header::_RANGE.to_string());
404                    if boxed_header.is_some() {
405                        range_header = boxed_header.unwrap();
406                    }
407
408                    let boxed_content_range_list = Range::get_content_range_list(&request.request_uri, range_header);
409                    if boxed_content_range_list.is_ok() {
410                        content_range_list = boxed_content_range_list.unwrap();
411                    } else {
412                        let error = boxed_content_range_list.err().unwrap();
413                        return Err(error)
414                    }
415                }
416            }
417
418
419            if boxed_file.is_err() {
420                //check if .html file exists
421                let static_filepath = [working_directory, components.path.as_str(), ".html"].join(SYMBOL.empty_string);
422
423                let boxed_file = File::open(&static_filepath);
424                if boxed_file.is_ok()  {
425                    let md = metadata(&static_filepath).unwrap();
426                    if md.is_file() {
427                        let mut range_header = &Header {
428                            name: Header::_RANGE.to_string(),
429                            value: "bytes=0-".to_string()
430                        };
431
432                        let boxed_header = request.get_header(Header::_RANGE.to_string());
433                        if boxed_header.is_some() {
434                            range_header = boxed_header.unwrap();
435                        }
436
437                        let url_array = ["http://", "localhost", &request.request_uri];
438                        let url = url_array.join(SYMBOL.empty_string);
439
440                        let boxed_url_components = URL::parse(&url);
441                        if boxed_url_components.is_err() {
442                            let message = boxed_url_components.as_ref().err().unwrap().to_string();
443                            // unfallable
444                            println!("unexpected error, {}", message);
445                        }
446
447                        let components = boxed_url_components.unwrap();
448
449                        // let html_file = [SYMBOL.slash, ].join(SYMBOL.empty_string);
450
451
452                        let html_file = [components.path.as_str(), ".html"].join(SYMBOL.empty_string);
453                        let boxed_content_range_list = Range::get_content_range_list(html_file.as_str(), range_header);
454                        if boxed_content_range_list.is_ok() {
455                            content_range_list = boxed_content_range_list.unwrap();
456                        } else {
457                            let error = boxed_content_range_list.err().unwrap();
458                            return Err(error)
459                        }
460                    }
461                }
462            }
463        }
464
465
466        Ok(content_range_list)
467    }
468}