Skip to main content

rust_web_server/app/controller/static_resource/
mod.rs

1use std::fs::{File, metadata, read_dir};
2use std::time::UNIX_EPOCH;
3use file_ext::FileExt;
4use crate::controller::Controller;
5use crate::ext::decimal::Decimal;
6use crate::header::Header;
7use crate::mime_type::MimeType;
8use crate::range::{ContentRange, Range};
9use crate::request::{METHOD, Request};
10use crate::response::{Error, Response, STATUS_CODE_REASON_PHRASE};
11use crate::server::ConnectionInfo;
12use crate::server_config::ServerConfig;
13use crate::symbol::SYMBOL;
14use crate::url::URL;
15
16#[cfg(test)]
17mod tests;
18pub(crate) mod open_file_cache;
19
20pub struct StaticResourceController;
21
22impl Controller for StaticResourceController {
23    fn is_matching(request: &Request, _connection: &ConnectionInfo) -> bool {
24        // Every branch below answers "no" for other methods and for "/":
25        // check that before touching the filesystem.
26        let is_get = request.method == METHOD.get;
27        let is_head = request.method == METHOD.head;
28        let is_options = request.method == METHOD.options;
29
30        let is_matching_method = (is_get || is_head || is_options) && (request.request_uri != SYMBOL.slash);
31        if !is_matching_method {
32            return false;
33        }
34
35        // Only origin-form targets name a file ("*" and anything a caller
36        // built by hand don't).
37        let path = match URL::request_target_path(&request.request_uri) {
38            Some(path) => path,
39            None => return false,
40        };
41
42        let boxed_static_filepath = static_fs_path(&os_specific_path(path));
43        if boxed_static_filepath.is_err() {
44            return false
45        }
46
47        let static_filepath = boxed_static_filepath.unwrap();
48
49        // Any existing directory matches now — with an `index.html` it is served as
50        // before, otherwise `process_static_resources` renders a directory listing.
51        let mut is_directory = false;
52
53        // A file the open-file cache holds needs no stat; otherwise one stat
54        // answers both "exists?" and "directory?" — no open().
55        let mut is_file = open_file_cache::is_cached_file(&static_filepath);
56        if !is_file {
57            if let Ok(md) = metadata(&static_filepath) {
58                // Cached files were checked when opened; the rest here.
59                if !inside_root(&static_filepath) {
60                    return false;
61                }
62                is_directory = md.is_dir();
63                is_file = md.is_file();
64            }
65        }
66
67        if is_file || is_directory {
68            true
69        } else {
70            // check if file with same name and .html extension exists
71            if !static_filepath.ends_with(".html") {
72                let html_suffix = ".html";
73                let mut html_file = os_specific_path(path).into_owned();
74                html_file.push_str(html_suffix);
75                if let Ok(html_static_filepath) = static_fs_path(&html_file) {
76                    if File::open(&html_static_filepath).is_ok() {
77                        return true;
78                    }
79                }
80            }
81
82            // Last resort: the configured SPA fallback file (RWS_CONFIG_SPA_FALLBACK),
83            // for a GET/HEAD request that doesn't look like a missed static asset and
84            // isn't under an excluded prefix. Returns false (unchanged prior behavior)
85            // whenever the fallback isn't configured or doesn't apply.
86            spa_fallback_url_path(path).is_some()
87        }
88
89    }
90
91    fn process(request: &Request, mut response: Response, _connection: &ConnectionInfo) -> Response {
92        let config = ServerConfig::current();
93        if let Some(served) = StaticResourceController::serve_regular_file(request, &mut response, &config) {
94            return served;
95        }
96        StaticResourceController::process_general(request, response, &config)
97    }
98}
99
100impl StaticResourceController {
101    /// [`Controller::process`] minus the [`Self::serve_regular_file`] fast
102    /// path: directories, `.html` resolution, ranges, OPTIONS, symlinks with
103    /// an untyped name, the SPA fallback. For a caller that already tried it.
104    pub(crate) fn process_general(request: &Request, mut response: Response, config: &ServerConfig) -> Response {
105        // A Range with an If-Range that no longer matches is answered as if
106        // there were no Range: the whole, current file (#56). (The fast path
107        // never takes a Range, so only this path needs it.)
108        let without_stale_range;
109        let request = if range_is_stale(request) {
110            let mut copy = request.clone();
111            copy.headers.retain(|h| !h.name.eq_ignore_ascii_case(Header::_RANGE));
112            without_stale_range = copy;
113            &without_stale_range
114        } else {
115            request
116        };
117        let boxed_content_range_list = StaticResourceController::process_static_resources(&request);
118        if boxed_content_range_list.is_ok() {
119            let content_range_list = boxed_content_range_list.unwrap();
120
121            if content_range_list.len() != 0 {
122
123                let mut status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok;
124
125                let does_request_include_range_header = request.header(Header::_RANGE).is_some();
126                if does_request_include_range_header {
127                    status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n206_partial_content;
128                }
129
130                let is_options_request = request.method == METHOD.options;
131                if is_options_request {
132                    status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n204_no_content;
133                }
134
135
136
137                let url = request.request_uri.to_string();
138
139                let boxed_url_components = URL::parse_request_target(&url);
140                if boxed_url_components.is_err() {
141                    let message = boxed_url_components.as_ref().err().unwrap().to_string();
142                    // unfallable
143                    println!("unexpected error, {}", message);
144                }
145
146                let components = boxed_url_components.unwrap();
147
148                // Decoded and checked like the lookup itself (#55): the raw
149                // path names no file when it has escapes.
150                let static_filepath = static_fs_path(&components.path).unwrap_or_default();
151                let boxed_modified_date_time = file_modified_utc(&static_filepath);
152
153                if boxed_modified_date_time.is_ok() {
154                    let modified_date_time = boxed_modified_date_time.unwrap();
155                    let file_size = metadata(&static_filepath).map(|m| m.len()).unwrap_or(0);
156                    let etag_value = format!("\"{}-{}\"", modified_date_time, file_size);
157                    set_static_cache_control(&mut response, &config.static_cache_control);
158                    if push_validators(request, &mut response, modified_date_time, &etag_value, config.nanos_headers) {
159                        response.status_code = *STATUS_CODE_REASON_PHRASE.n304_not_modified.status_code;
160                        response.reason_phrase = STATUS_CODE_REASON_PHRASE.n304_not_modified.reason_phrase.to_string();
161                        response.headers.push(Header { name: Header::_ETAG.into(), value: etag_value.into() });
162                        return response;
163                    }
164
165                    response.headers.push(Header { name: Header::_ETAG.into(), value: etag_value.into() });
166
167                    // Stream large files (> 8 MB) without loading into memory, unless it's
168                    // a range request (which needs precise byte slicing from the loaded body).
169                    let is_range_request = request.header(Header::_RANGE).is_some();
170                    if file_size > StaticResourceController::STREAM_THRESHOLD && !is_range_request {
171                        let mime = MimeType::detect_mime_type(&static_filepath);
172                        response.headers.push(Header {
173                            name: Header::_CONTENT_TYPE.into(),
174                            value: mime.into(),
175                        });
176                        response.headers.push(Header {
177                            name: Header::_CONTENT_LENGTH.into(),
178                            value: file_size.to_string().into(),
179                        });
180                        response.status_code = *status_code_reason_phrase.status_code;
181                        response.reason_phrase = status_code_reason_phrase.reason_phrase.to_string();
182                        response.stream_file = Some(static_filepath);
183                        return response;
184                    }
185                }
186
187                response.status_code = *status_code_reason_phrase.status_code;
188                response.reason_phrase = status_code_reason_phrase.reason_phrase.to_string();
189                response.content_range_list = content_range_list;
190
191            }
192        } else {
193            let error : Error = boxed_content_range_list.err().unwrap();
194            let body = error.message;
195
196            let content_range = Range::get_content_range(
197                Vec::from(body.as_bytes()),
198                MimeType::TEXT_HTML.to_string()
199            );
200
201            let content_range_list = vec![content_range];
202
203            response.status_code = *error.status_code_reason_phrase.status_code;
204            response.reason_phrase = error.status_code_reason_phrase.reason_phrase.to_string();
205            response.content_range_list = content_range_list;
206
207            // A 416 says how long the file is (RFC 9110 §15.5.17, #56).
208            if response.status_code == 416 {
209                let length = URL::parse_request_target(&request.request_uri).ok()
210                    .and_then(|c| static_fs_path(&c.path).ok())
211                    .and_then(|p| metadata(p).ok())
212                    .map(|md| md.len());
213                if let Some(length) = length {
214                    response.headers.push(Header { name: Header::_CONTENT_RANGE.into(), value: format!("bytes */{}", length).into() });
215                }
216            }
217        }
218
219
220        response
221    }
222}
223
224//backward compatability
225impl StaticResourceController {
226
227    pub fn is_matching_request(request: &Request) -> bool {
228        let boxed_static_filepath = static_fs_path(&request.request_uri);
229        if boxed_static_filepath.is_err() {
230            return false
231        }
232
233        let static_filepath = boxed_static_filepath.unwrap();
234
235        let boxed_md = metadata(&static_filepath);
236        if boxed_md.is_err() || !inside_root(&static_filepath) {
237            return false
238        }
239
240        let md = boxed_md.unwrap();
241        if md.is_dir() {
242            return false
243        }
244
245        let boxed_file = File::open(&static_filepath);
246
247        let is_get = request.method == METHOD.get;
248        let is_head = request.method == METHOD.head;
249        let is_options = request.method == METHOD.options;
250        boxed_file.is_ok() && (is_get || is_head || is_options && request.request_uri != SYMBOL.slash)
251    }
252
253    pub fn process_request(request: &Request, mut response: Response) -> Response {
254        let config = ServerConfig::current();
255        if let Some(streamed) = StaticResourceController::serve_regular_file(request, &mut response, &config) {
256            return streamed;
257        }
258        let boxed_content_range_list = StaticResourceController::process_static_resources(&request);
259        if boxed_content_range_list.is_ok() {
260            let content_range_list = boxed_content_range_list.unwrap();
261
262            if content_range_list.len() != 0 {
263
264                let mut status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok;
265
266                let does_request_include_range_header = request.header(Header::_RANGE).is_some();
267                if does_request_include_range_header {
268                    status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n206_partial_content;
269                }
270
271                let is_options_request = request.method == METHOD.options;
272                if is_options_request {
273                    status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n204_no_content;
274                }
275
276
277                let static_filepath = static_fs_path(&request.request_uri).unwrap_or_default();
278                let boxed_modified_date_time = file_modified_utc(&static_filepath);
279
280                if boxed_modified_date_time.is_ok() {
281                    let modified_date_time = boxed_modified_date_time.unwrap();
282                    let file_size = metadata(&static_filepath).map(|m| m.len()).unwrap_or(0);
283                    let etag_value = format!("\"{}-{}\"", modified_date_time, file_size);
284                    set_static_cache_control(&mut response, &config.static_cache_control);
285                    if push_validators(request, &mut response, modified_date_time, &etag_value, config.nanos_headers) {
286                        response.status_code = *STATUS_CODE_REASON_PHRASE.n304_not_modified.status_code;
287                        response.reason_phrase = STATUS_CODE_REASON_PHRASE.n304_not_modified.reason_phrase.to_string();
288                        response.headers.push(Header { name: Header::_ETAG.into(), value: etag_value.into() });
289                        return response;
290                    }
291
292                    response.headers.push(Header { name: Header::_ETAG.into(), value: etag_value.into() });
293
294                    let is_range_request = request.header(Header::_RANGE).is_some();
295                    if file_size > StaticResourceController::STREAM_THRESHOLD && !is_range_request {
296                        let mime = MimeType::detect_mime_type(&static_filepath);
297                        response.headers.push(Header {
298                            name: Header::_CONTENT_TYPE.into(),
299                            value: mime.into(),
300                        });
301                        response.headers.push(Header {
302                            name: Header::_CONTENT_LENGTH.into(),
303                            value: file_size.to_string().into(),
304                        });
305                        response.status_code = *status_code_reason_phrase.status_code;
306                        response.reason_phrase = status_code_reason_phrase.reason_phrase.to_string();
307                        response.stream_file = Some(static_filepath);
308                        return response;
309                    }
310                }
311
312                response.status_code = *status_code_reason_phrase.status_code;
313                response.reason_phrase = status_code_reason_phrase.reason_phrase.to_string();
314                response.content_range_list = content_range_list;
315
316            }
317        } else {
318            let error : Error = boxed_content_range_list.err().unwrap();
319            let body = error.message;
320
321            let content_range = Range::get_content_range(
322                Vec::from(body.as_bytes()),
323                MimeType::TEXT_HTML.to_string()
324            );
325
326            let content_range_list = vec![content_range];
327
328            response.status_code = *error.status_code_reason_phrase.status_code;
329            response.reason_phrase = error.status_code_reason_phrase.reason_phrase.to_string();
330            response.content_range_list = content_range_list;
331
332        }
333
334
335        response
336    }
337
338    /// Files larger than this are streamed from disk (`Response::stream_file`)
339    /// rather than read into memory — 64 concurrent downloads of a 1 MiB file
340    /// otherwise hold ~64 MiB plus copies.
341    pub const STREAM_THRESHOLD: u64 = 256 * 1024;
342
343    /// Fast path for a GET/HEAD of a regular file without a `Range` header:
344    /// one `open` and one `fstat` — size and modified time come from the open
345    /// handle, and a small file is read from that same handle — like nginx.
346    /// (The general path below stats the file five or six times and opens it
347    /// twice.) Files over [`Self::STREAM_THRESHOLD`] are answered with
348    /// `stream_file` before anything is read. The `Content-Type` comes from
349    /// the requested name. `None` = not applicable; the general path handles
350    /// it (directories, `.html` resolution, ranges, OPTIONS, symlinks whose
351    /// name has no known type).
352    pub(crate) fn serve_regular_file(request: &Request, response: &mut Response, config: &ServerConfig) -> Option<Response> {
353        if request.method != METHOD.get && request.method != METHOD.head {
354            return None;
355        }
356        if request.header(Header::_RANGE).is_some() {
357            return None;
358        }
359        let path = URL::request_target_path(&request.request_uri)?;
360        let fs_path = static_fs_path(&os_specific_path(path)).ok()?;
361        // A symlink whose own name has no recognizable type goes to the
362        // general path, which takes the type from the link target: such names
363        // are opened with O_NOFOLLOW, so a symlink simply fails to open.
364        let mime = MimeType::mime_type_for(&fs_path);
365        let follow_symlinks = mime != MimeType::APPLICATION_OCTET_STREAM;
366        let file = open_file_cache::open(&fs_path, follow_symlinks)?;
367        let state = file.state()?;
368
369        // A compressible text file for a client that accepts br, zstd or gzip
370        // is sent from the cached compressed form (or a precompressed
371        // sibling), made once per file version instead of per request. Only
372        // a request with Accept-Encoding pays for the negotiation.
373        let encoding = if state.len <= open_file_cache::MAX_GZIPPED_FILE
374            && state.len >= crate::compression::MIN_COMPRESS_SIZE as u64
375            && crate::compression::is_compressible(mime)
376        {
377            crate::compression::negotiate(request, crate::compression::STATIC_PREFERENCE)
378        } else {
379            None
380        };
381        // ETag "<modified>-<len>", plus "-<coding>" when the file goes out
382        // compressed (each representation needs its own strong ETag), and the
383        // nanosecond Last-Modified, built without format!: this runs for
384        // every request.
385        let modified = Decimal::new(state.modified);
386        let len = Decimal::new(state.len as u128);
387        let mut etag_value = String::with_capacity(modified.as_str().len() + len.as_str().len() + 8);
388        etag_value.push('"');
389        etag_value.push_str(modified.as_str());
390        etag_value.push('-');
391        etag_value.push_str(len.as_str());
392        if let Some(encoding) = encoding {
393            etag_value.push('-');
394            etag_value.push_str(encoding.token());
395        }
396        etag_value.push('"');
397        let not_modified = is_not_modified(request, state.modified, &etag_value);
398        // Everything that can fail happens before `response` is taken: on
399        // `None` the general path carries on with it.
400        // A body of None means: stream the file (sendfile over plain TCP).
401        // Compressible files up to MAX_GZIPPED_FILE (above the streaming
402        // threshold too) go to gzip clients compressed — a JS bundle of a few
403        // hundred KiB used to be sent uncompressed.
404        let mut sent_encoded = None;
405        let large = state.len > StaticResourceController::STREAM_THRESHOLD;
406        let body = if not_modified {
407            None
408        } else if let Some(encoding) = encoding {
409            match file.encoded(&state, encoding, &fs_path).ok()? {
410                open_file_cache::Encoded::Smaller(bytes) => {
411                    sent_encoded = Some(encoding);
412                    Some(bytes.to_vec())
413                }
414                open_file_cache::Encoded::NotSmaller if large => None,
415                open_file_cache::Encoded::NotSmaller => Some(file.contents(&state).ok()?),
416            }
417        } else if large {
418            None
419        } else {
420            Some(file.contents(&state).ok()?)
421        };
422
423        let mut response = std::mem::replace(response, Response::empty());
424        set_static_cache_control(&mut response, &config.static_cache_control);
425        if config.nanos_headers {
426            response.headers.push(Header { name: Header::_LAST_MODIFIED_UNIX_EPOCH_NANOS.into(), value: modified.as_str().to_string().into() });
427        }
428        response.headers.push(Header { name: Header::_LAST_MODIFIED.into(), value: crate::http::date::format((state.modified / 1_000_000_000) as u64).into() });
429        response.headers.push(Header { name: Header::_ETAG.into(), value: etag_value.into() });
430        if not_modified {
431            response.set_status(STATUS_CODE_REASON_PHRASE.n304_not_modified);
432            return Some(response);
433        }
434        response.set_status(STATUS_CODE_REASON_PHRASE.n200_ok);
435
436        let Some(body) = body else {
437            response.headers.push(Header { name: Header::_CONTENT_TYPE.into(), value: mime.to_string().into() });
438            response.headers.push(Header { name: Header::_CONTENT_LENGTH.into(), value: len.as_str().to_string().into() });
439            response.stream_file = Some(fs_path);
440            return Some(response);
441        };
442
443        response.content_range_list = vec![Range::get_content_range(body, mime.to_string())];
444        if let Some(encoding) = sent_encoded {
445            crate::compression::mark_encoded(&mut response, encoding);
446        }
447        Some(response)
448    }
449
450    pub fn process_static_resources(request: &Request) -> Result<Vec<ContentRange>, Error> {
451
452        let url = request.request_uri.to_string();
453
454        let boxed_url_components = URL::parse_request_target(&url);
455        if boxed_url_components.is_err() {
456            let message = boxed_url_components.as_ref().err().unwrap().to_string();
457            // unfallable
458            println!("unexpected error, {}", message);
459        }
460
461        let components = boxed_url_components.unwrap();
462
463        let os_specific_separator : String = FileExt::get_path_separator();
464        let os_specific_path = &components.path.replace(SYMBOL.slash, os_specific_separator.as_str());
465
466        let static_filepath = match static_fs_path(&os_specific_path) {
467            Ok(path) => path,
468            Err(message) => {
469                return Err(Error { status_code_reason_phrase: STATUS_CODE_REASON_PHRASE.n404_not_found, message });
470            }
471        };
472
473        let mut content_range_list = Vec::new();
474
475
476        let mut boxed_md = metadata(&static_filepath);
477        if boxed_md.is_err() {
478            let dot_html = format!("{}{}", &static_filepath, ".html");
479            boxed_md = metadata(&dot_html);
480
481            if boxed_md.is_err() {
482                let slash_index_html = format!("{}{}{}", &static_filepath, os_specific_separator,  "index.html");
483                boxed_md = metadata(&slash_index_html);
484            }
485        }
486        if boxed_md.is_ok() {
487            let md = boxed_md.unwrap();
488
489            if md.is_dir() {
490                let mut directory_index : String = "index.html".to_string();
491
492                let last_char = components.path.chars().last().unwrap();
493                if last_char != '/' {
494                    let index : String = "index.html".to_string();
495                    directory_index = format!("{}{}", os_specific_separator, index);
496                }
497                let index_html_in_directory = format!("{}{}", os_specific_path, directory_index);
498                let index_html_fs_path = format!("{}{}", static_filepath, directory_index);
499
500                if File::open(&index_html_fs_path).is_ok() {
501                    let mut range_header = &Header {
502                        name: Header::_RANGE.into(),
503                        value: "bytes=0-".into()
504                    };
505
506                    let boxed_header = request.header(Header::_RANGE);
507                    if boxed_header.is_some() {
508                        range_header = boxed_header.unwrap();
509                    }
510
511                    let boxed_content_range_list = Range::get_content_range_list(&index_html_in_directory, range_header);
512                    if boxed_content_range_list.is_ok() {
513                        content_range_list = boxed_content_range_list.unwrap();
514                    } else {
515                        let error = boxed_content_range_list.err().unwrap();
516                        return Err(error)
517                    }
518                } else {
519                    let listing_html = StaticResourceController::render_directory_listing(&static_filepath, &components.path);
520                    let content_range = Range::get_content_range(listing_html.into_bytes(), MimeType::TEXT_HTML.to_string());
521                    content_range_list = vec![content_range];
522                }
523
524                return Ok(content_range_list);
525            }
526
527            let boxed_file = File::open(&static_filepath);
528            if boxed_file.is_ok()  {
529                let md = metadata(&static_filepath).unwrap();
530                if md.is_dir() {
531                    let mut range_header = &Header {
532                        name: Header::_RANGE.into(),
533                        value: "bytes=0-".into()
534                    };
535
536                    let boxed_header = request.header(Header::_RANGE);
537                    if boxed_header.is_some() {
538                        range_header = boxed_header.unwrap();
539                    }
540
541                    let mut directory_index : String = "index.html".to_string();
542
543                    let last_char = components.path.chars().last().unwrap();
544                    if last_char != '/' {
545                        let index : String = "index.html".to_string();
546                        directory_index = format!("{}{}", os_specific_separator, index);
547                    }
548                    let index_html_in_directory = format!("{}{}", os_specific_path, directory_index);
549
550
551                    let boxed_content_range_list = Range::get_content_range_list(&index_html_in_directory, range_header);
552                    if boxed_content_range_list.is_ok() {
553                        content_range_list = boxed_content_range_list.unwrap();
554                    } else {
555                        let error = boxed_content_range_list.err().unwrap();
556                        return Err(error)
557                    }
558                }
559
560                if md.is_file() {
561                    let mut range_header = &Header {
562                        name: Header::_RANGE.into(),
563                        value: "bytes=0-".into()
564                    };
565
566                    let boxed_header = request.header(Header::_RANGE);
567                    if boxed_header.is_some() {
568                        range_header = boxed_header.unwrap();
569                    }
570
571                    let boxed_content_range_list = Range::get_content_range_list(&request.request_uri, range_header);
572                    if boxed_content_range_list.is_ok() {
573                        content_range_list = boxed_content_range_list.unwrap();
574                    } else {
575                        let error = boxed_content_range_list.err().unwrap();
576                        return Err(error)
577                    }
578                }
579            }
580
581
582            if boxed_file.is_err() {
583                //check if .html file exists
584                // Decoded like every lookup (#55): `/my%20page` is `my page.html`.
585                let static_filepath = static_fs_path(&format!("{}.html", components.path)).unwrap_or_default();
586
587                let boxed_file = File::open(&static_filepath);
588                if boxed_file.is_ok()  {
589                    let md = metadata(&static_filepath).unwrap();
590                    if md.is_file() {
591                        let mut range_header = &Header {
592                            name: Header::_RANGE.into(),
593                            value: "bytes=0-".into()
594                        };
595
596                        let boxed_header = request.header(Header::_RANGE);
597                        if boxed_header.is_some() {
598                            range_header = boxed_header.unwrap();
599                        }
600
601                        let url = request.request_uri.to_string();
602
603                        let boxed_url_components = URL::parse_request_target(&url);
604                        if boxed_url_components.is_err() {
605                            let message = boxed_url_components.as_ref().err().unwrap().to_string();
606                            // unfallable
607                            println!("unexpected error, {}", message);
608                        }
609
610                        let components = boxed_url_components.unwrap();
611
612                        // let html_file = [SYMBOL.slash, ].join(SYMBOL.empty_string);
613
614
615                        let html_file = [components.path.as_str(), ".html"].join(SYMBOL.empty_string);
616                        let boxed_content_range_list = Range::get_content_range_list(html_file.as_str(), range_header);
617                        if boxed_content_range_list.is_ok() {
618                            content_range_list = boxed_content_range_list.unwrap();
619                        } else {
620                            let error = boxed_content_range_list.err().unwrap();
621                            return Err(error)
622                        }
623                    }
624                }
625            }
626        }
627
628        // Nothing on disk matched — try the configured SPA fallback (a no-op,
629        // returning the untouched empty list, when it's unconfigured or doesn't
630        // apply to this request).
631        if content_range_list.is_empty() {
632            if let Some(fallback_url_path) = spa_fallback_url_path(&components.path) {
633                let mut range_header = &Header {
634                    name: Header::_RANGE.into(),
635                    value: "bytes=0-".into()
636                };
637
638                let boxed_header = request.header(Header::_RANGE);
639                if boxed_header.is_some() {
640                    range_header = boxed_header.unwrap();
641                }
642
643                if let Ok(list) = Range::get_content_range_list(&fallback_url_path, range_header) {
644                    content_range_list = list;
645                }
646            }
647        }
648
649        Ok(content_range_list)
650    }
651}
652
653/// Directory listing generation — used by [`StaticResourceController`] whenever a
654/// requested directory has no `index.html`. Self-contained HTML (inline CSS/JS, no
655/// external requests), dark/light adaptive via `prefers-color-scheme`.
656impl StaticResourceController {
657    /// Renders a directory listing page for `fs_dir_path` (absolute filesystem path)
658    /// requested at `request_path` (the URL path, used to build links and breadcrumbs).
659    /// Hidden entries (dotfiles) are omitted. Directories sort before files;
660    /// each group is sorted case-insensitively by name.
661    pub fn render_directory_listing(fs_dir_path: &str, request_path: &str) -> String {
662        let normalized_request_path = if request_path.ends_with('/') {
663            request_path.to_string()
664        } else {
665            format!("{}/", request_path)
666        };
667
668        struct Entry {
669            name: String,
670            is_dir: bool,
671            size: u64,
672            modified_epoch_secs: u64,
673        }
674
675        let mut entries: Vec<Entry> = Vec::new();
676        if let Ok(dir_entries) = read_dir(fs_dir_path) {
677            for dir_entry in dir_entries.flatten() {
678                let name = dir_entry.file_name().to_string_lossy().to_string();
679                if name.starts_with('.') {
680                    continue;
681                }
682
683                if let Ok(md) = dir_entry.metadata() {
684                    let modified_epoch_secs = md.modified()
685                        .ok()
686                        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
687                        .map(|d| d.as_secs())
688                        .unwrap_or(0);
689
690                    entries.push(Entry {
691                        name,
692                        is_dir: md.is_dir(),
693                        size: md.len(),
694                        modified_epoch_secs,
695                    });
696                }
697            }
698        }
699
700        entries.sort_by(|a, b| {
701            match (a.is_dir, b.is_dir) {
702                (true, false) => std::cmp::Ordering::Less,
703                (false, true) => std::cmp::Ordering::Greater,
704                _ => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
705            }
706        });
707
708        let segments: Vec<&str> = normalized_request_path.split('/').filter(|s| !s.is_empty()).collect();
709
710        let mut breadcrumb_html = String::from("<a href=\"/\">~</a>");
711        let mut accumulated_path = String::new();
712        for segment in &segments {
713            accumulated_path.push('/');
714            accumulated_path.push_str(segment);
715            breadcrumb_html.push_str(&format!(
716                " <span class=\"sep\">/</span> <a href=\"{}/\">{}</a>",
717                accumulated_path, html_escape(segment)
718            ));
719        }
720
721        let parent_row = if !segments.is_empty() {
722            let parent_path = if segments.len() > 1 {
723                format!("/{}/", segments[..segments.len() - 1].join("/"))
724            } else {
725                "/".to_string()
726            };
727            format!(
728                "<tr class=\"entry parent\"><td class=\"name\"><span class=\"icon\">\u{21A9}\u{FE0F}</span><a href=\"{}\">.. (parent directory)</a></td><td class=\"size\">\u{2014}</td><td class=\"modified\">\u{2014}</td></tr>\n",
729                parent_path
730            )
731        } else {
732            String::new()
733        };
734
735        let entry_count = entries.len();
736
737        let mut rows = String::new();
738        for entry in &entries {
739            let escaped_name = html_escape(&entry.name);
740            let encoded_name = URL::percent_encode(&entry.name);
741            let href = if entry.is_dir {
742                format!("{}{}/", normalized_request_path, encoded_name)
743            } else {
744                format!("{}{}", normalized_request_path, encoded_name)
745            };
746            let size_display = if entry.is_dir { "\u{2014}".to_string() } else { human_size(entry.size) };
747            let modified_display = format_modified(entry.modified_epoch_secs);
748            let icon = icon_for(&entry.name, entry.is_dir);
749            let filter_key = html_escape(&entry.name.to_lowercase());
750
751            rows.push_str(&format!(
752                "<tr class=\"entry\" data-name=\"{}\"><td class=\"name\"><span class=\"icon\">{}</span><a href=\"{}\">{}{}</a></td><td class=\"size\">{}</td><td class=\"modified\">{}</td></tr>\n",
753                filter_key, icon, href, escaped_name, if entry.is_dir { "/" } else { "" }, size_display, modified_display
754            ));
755        }
756
757        let mut html = String::new();
758        html.push_str(DIRECTORY_LISTING_HEAD);
759        html.push_str(&format!("<div class=\"breadcrumb\">{}</div>\n", breadcrumb_html));
760        html.push_str(&format!("<h1>Index of {}</h1>\n", html_escape(&normalized_request_path)));
761        html.push_str(DIRECTORY_LISTING_TOOLBAR);
762        html.push_str("<div class=\"card\"><table><thead><tr><th>Name</th><th>Size</th><th>Modified</th></tr></thead><tbody id=\"rows\">\n");
763        html.push_str(&parent_row);
764        html.push_str(&rows);
765        html.push_str("</tbody></table></div>\n");
766        html.push_str(&format!(
767            "<footer>{} item{} &middot; served by rws</footer>\n",
768            entry_count, if entry_count == 1 { "" } else { "s" }
769        ));
770        html.push_str(DIRECTORY_LISTING_TAIL);
771
772        html
773    }
774}
775
776/// `true` if the last `/`-separated segment of `path` has a file extension
777/// (contains a `.` after the final `/`) — the standard heuristic (also used
778/// by webpack-dev-server's `historyApiFallback`, `sirv`, `vite preview`)
779/// distinguishing a client-side route (`/dashboard/settings`, no extension)
780/// from a missed static asset (`/logo.png`, has one), so the SPA fallback
781/// doesn't silently swallow the latter's real 404.
782fn path_has_extension(path: &str) -> bool {
783    path.rsplit('/').next().unwrap_or("").contains('.')
784}
785
786/// Resolves the SPA-fallback "URL path" to pass to [`Range::get_content_range_list`]
787/// for a request at `url_path` — e.g. `"/index.html"` for the common
788/// `RWS_CONFIG_SPA_FALLBACK=index.html` case — or `None` if the fallback doesn't
789/// apply: unconfigured, `url_path` is under an excluded prefix
790/// (`RWS_CONFIG_SPA_FALLBACK_EXCLUDE_PREFIXES`), `url_path` looks like a missed
791/// static asset (see [`path_has_extension`]), or the configured file doesn't
792/// actually exist on disk. Method filtering (GET/HEAD only) is the caller's
793/// responsibility — both call sites already have it via `is_matching_method`.
794fn spa_fallback_url_path(url_path: &str) -> Option<String> {
795    if path_has_extension(url_path) {
796        return None;
797    }
798
799    let fallback_name = crate::entry_point::get_spa_fallback()?;
800
801    let exclude_prefixes = crate::entry_point::get_spa_fallback_exclude_prefixes();
802    if exclude_prefixes.iter().any(|prefix| url_path.starts_with(prefix.as_str())) {
803        return None;
804    }
805
806    let separator = FileExt::get_path_separator();
807    let normalized_name = fallback_name.trim_start_matches('/').replace('/', &separator);
808    let fallback_url_path = format!("{}{}", separator, normalized_name);
809
810    let boxed_fs_path = static_fs_path(&fallback_url_path);
811    let fs_path = boxed_fs_path.ok()?;
812    if File::open(&fs_path).is_ok() {
813        Some(fallback_url_path)
814    } else {
815        None
816    }
817}
818
819fn html_escape(s: &str) -> String {
820    let mut out = String::with_capacity(s.len());
821    for c in s.chars() {
822        match c {
823            '&' => out.push_str("&amp;"),
824            '<' => out.push_str("&lt;"),
825            '>' => out.push_str("&gt;"),
826            '"' => out.push_str("&quot;"),
827            '\'' => out.push_str("&#39;"),
828            _ => out.push(c),
829        }
830    }
831    out
832}
833
834fn human_size(bytes: u64) -> String {
835    const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
836    if bytes < 1024 {
837        return format!("{} {}", bytes, UNITS[0]);
838    }
839
840    let mut size = bytes as f64;
841    let mut unit_index = 0;
842    while size >= 1024.0 && unit_index < UNITS.len() - 1 {
843        size /= 1024.0;
844        unit_index += 1;
845    }
846
847    format!("{:.1} {}", size, UNITS[unit_index])
848}
849
850fn format_modified(epoch_secs: u64) -> String {
851    let (sec, min, hour, day, month, _dow) = crate::scheduler::cron::epoch_to_datetime(epoch_secs);
852    let (year, _, _) = crate::scheduler::cron::days_to_ymd(epoch_secs / 86400);
853    format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}", year, month, day, hour, min, sec)
854}
855
856fn icon_for(name: &str, is_dir: bool) -> &'static str {
857    if is_dir {
858        return "\u{1F4C1}";
859    }
860
861    let ext = name.rsplit('.').next().unwrap_or("").to_lowercase();
862    match ext.as_str() {
863        "png" | "jpg" | "jpeg" | "gif" | "svg" | "webp" | "ico" | "bmp" => "\u{1F5BC}\u{FE0F}",
864        "mp4" | "mov" | "avi" | "mkv" | "webm" => "\u{1F3A5}",
865        "mp3" | "wav" | "flac" | "m4a" | "ogg" => "\u{1F3A7}",
866        "zip" | "tar" | "gz" | "rar" | "7z" | "bz2" => "\u{1F4E6}",
867        "pdf" => "\u{1F4D5}",
868        "html" | "htm" | "css" | "js" | "ts" | "rs" | "py" | "json" | "toml" | "yaml" | "yml" | "sh" => "\u{1F9E9}",
869        _ => "\u{1F4C4}",
870    }
871}
872
873// CSS/JS are served as same-origin `<link>`/`<script src>` assets (see
874// `crate::app::controller::directory_listing::DirectoryListingAssetsController`)
875// rather than inlined here — inline `<style>`/`<script>` would be silently
876// blocked under the framework's default `Content-Security-Policy: default-src 'self'`.
877const DIRECTORY_LISTING_HEAD: &str = concat!(
878    "<!DOCTYPE html>\n",
879    "<html lang=\"en\">\n",
880    "<head>\n",
881    "<meta charset=\"UTF-8\">\n",
882    "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n",
883    "<title>Directory listing</title>\n",
884    "<link rel=\"stylesheet\" href=\"/rws-directory-listing.css\">\n",
885    "</head>\n",
886    "<body>\n",
887    "<div class=\"wrap\">\n",
888);
889
890const DIRECTORY_LISTING_TOOLBAR: &str = "<div class=\"toolbar\"><input type=\"search\" id=\"filter\" placeholder=\"Filter entries...\" autocomplete=\"off\"></div>\n";
891
892const DIRECTORY_LISTING_TAIL: &str = concat!(
893    "</div>\n",
894    "<script src=\"/rws-directory-listing.js\" defer></script>\n",
895    "</body>\n",
896    "</html>\n",
897);
898
899/// The process working directory — the static-file root — read once.
900/// `rws` never changes it after startup, and `std::env::current_dir()` is
901/// several syscalls (on macOS it opens "."): the static-file path used to ask
902/// for it four to six times per request. A library user who changes the
903/// working directory after the first request keeps the original root.
904/// Push `Last-Modified` (and `Last-Modified-Unix-Epoch-Nanos` with
905/// `nanos_headers`), and tell whether the request's validators say the
906/// client's copy is current ([`is_not_modified`]).
907fn push_validators(request: &Request, response: &mut Response, modified_nanos: u128, etag: &str, nanos_headers: bool) -> bool {
908    if nanos_headers {
909        response.headers.push(Header { name: Header::_LAST_MODIFIED_UNIX_EPOCH_NANOS.into(), value: modified_nanos.to_string().into() });
910    }
911    response.headers.push(Header { name: Header::_LAST_MODIFIED.into(), value: crate::http::date::format((modified_nanos / 1_000_000_000) as u64).into() });
912    is_not_modified(request, modified_nanos, etag)
913}
914
915/// RFC 9110 §13.1: `If-None-Match` (the ETag, or `*`) decides when present;
916/// otherwise `If-Modified-Since` for GET/HEAD — the file's modification
917/// second is not after the given date. An unparseable date is ignored.
918fn is_not_modified(request: &Request, modified_nanos: u128, etag: &str) -> bool {
919    if let Some(inm) = request.header(Header::_IF_NONE_MATCH) {
920        return if_none_match_matches(&inm.value, etag);
921    }
922    if request.method != METHOD.get && request.method != METHOD.head {
923        return false;
924    }
925    request
926        .header(Header::_IF_MODIFIED_SINCE)
927        .and_then(|ims| crate::http::date::parse(&ims.value))
928        .is_some_and(|since| (modified_nanos / 1_000_000_000) as u64 <= since)
929}
930
931/// The static-file `Cache-Control` (`RWS_CONFIG_STATIC_CACHE_CONTROL`) in
932/// place of the default `no-store, …`; an empty setting keeps the default.
933fn set_static_cache_control(response: &mut Response, value: &str) {
934    if value.is_empty() {
935        return;
936    }
937    if let Some(header) = response.headers.iter_mut().find(|h| h.name == Header::_CACHE_CONTROL) {
938        header.value = if value == crate::server_config::STATIC_CACHE_CONTROL_DEFAULT {
939            std::borrow::Cow::Borrowed(crate::server_config::STATIC_CACHE_CONTROL_DEFAULT)
940        } else {
941            std::borrow::Cow::Owned(value.to_string())
942        };
943    }
944}
945
946pub(crate) fn working_directory() -> &'static str {
947    static DIR: std::sync::OnceLock<String> = std::sync::OnceLock::new();
948    DIR.get_or_init(|| {
949        std::env::current_dir()
950            .map(|d| d.to_string_lossy().into_owned())
951            .unwrap_or_default()
952    })
953}
954
955/// `If-None-Match` against the current entity tag (RFC 9110 §13.1.2): a
956/// comma-separated list, or `*`, compared weakly — `W/"x"` matches `"x"`
957/// (#56). Before 17.113.2 only a header equal to the tag matched, so a
958/// client sending several tags, or a weak one, never got a `304`.
959pub(crate) fn if_none_match_matches(header_value: &str, etag: &str) -> bool {
960    let opaque = |tag: &str| tag.trim().strip_prefix("W/").unwrap_or(tag.trim()).to_string();
961    let current = opaque(etag);
962    header_value.split(',').any(|candidate| {
963        let candidate = candidate.trim();
964        candidate == "*" || (!candidate.is_empty() && opaque(candidate) == current)
965    })
966}
967
968/// `true` when the request has a `Range` and an `If-Range` that doesn't
969/// match the file as it is now (RFC 9110 §13.1.5): an entity tag must match
970/// the current `ETag` strongly (a weak tag never does); a date must equal the
971/// file's `Last-Modified` and be a strong validator — at least a second
972/// older than now, so a second write within that second can't share it.
973/// Then the `Range` is ignored and the whole file is sent: the client's
974/// piece is out of date.
975pub(crate) fn range_is_stale(request: &Request) -> bool {
976    let Some(if_range) = request.header(Header::_IF_RANGE) else { return false };
977    if request.header(Header::_RANGE).is_none() {
978        return false;
979    }
980    let validator = if_range.value.trim();
981    let Some(path) = URL::request_target_path(&request.request_uri) else { return true };
982    let Ok(fs_path) = static_fs_path(&os_specific_path(path)) else { return true };
983    let (Ok(modified), Ok(md)) = (file_modified_utc(&fs_path), metadata(&fs_path)) else { return true };
984    if validator.starts_with('"') {
985        return validator != format!("\"{}-{}\"", modified, md.len());
986    }
987    let modified_secs = (modified / 1_000_000_000) as u64;
988    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
989    match crate::http::date::parse(validator) {
990        Some(date) => date != modified_secs || now < modified_secs + 1,
991        None => true,
992    }
993}
994
995/// `FileExt::get_static_filepath` without the per-call `current_dir()`:
996/// the working directory followed by `path` — refused (`Err`) when `path`
997/// could leave the web root or names a hidden file (#43):
998///
999/// - a `..` segment (`/../etc/passwd`): served before 17.113.1;
1000/// - a segment starting with `.` (`.git/`, `.env`), except `.well-known`,
1001///   unless `RWS_CONFIG_SERVE_DOTFILES=true`.
1002///
1003/// A symlink inside the root may still point outside it; [`inside_root`]
1004/// checks the resolved path where files are opened.
1005///
1006/// `path` is the request path as sent: it's percent-decoded here, once,
1007/// before those checks (#55) — `/my%20file.txt` is `my file.txt`, and
1008/// `/%2e%2e/` is refused like `/../`.
1009pub(crate) fn static_fs_path(path: &str) -> Result<String, String> {
1010    let path = percent_decode_path(path)?;
1011    check_request_path(&path)?;
1012    let working_directory = working_directory();
1013    let mut fs_path = String::with_capacity(working_directory.len() + path.len());
1014    fs_path.push_str(working_directory);
1015    fs_path.push_str(&path);
1016    Ok(fs_path)
1017}
1018
1019/// A URL path with `/` turned into the OS path separator — borrowed (no
1020/// copy) where the separator is `/`.
1021pub(crate) fn os_specific_path(path: &str) -> std::borrow::Cow<'_, str> {
1022    if std::path::MAIN_SEPARATOR == '/' {
1023        std::borrow::Cow::Borrowed(path)
1024    } else {
1025        std::borrow::Cow::Owned(path.replace('/', std::path::MAIN_SEPARATOR_STR))
1026    }
1027}
1028
1029/// Percent-decode a request path (RFC 3986 §2.1). `+` stays `+` (it means
1030/// a space only in form-encoded queries); a `%` not followed by two hex
1031/// digits is kept as is; a result that isn't UTF-8 is an error. Borrows
1032/// when there is nothing to decode.
1033pub(crate) fn percent_decode_path(path: &str) -> Result<std::borrow::Cow<'_, str>, String> {
1034    if !path.contains('%') {
1035        return Ok(std::borrow::Cow::Borrowed(path));
1036    }
1037    let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
1038    let bytes = path.as_bytes();
1039    let mut decoded = Vec::with_capacity(bytes.len());
1040    let mut i = 0;
1041    while i < bytes.len() {
1042        if bytes[i] == b'%' && i + 2 < bytes.len() {
1043            if let (Some(high), Some(low)) = (hex(bytes[i + 1]), hex(bytes[i + 2])) {
1044                decoded.push(high << 4 | low);
1045                i += 3;
1046                continue;
1047            }
1048        }
1049        decoded.push(bytes[i]);
1050        i += 1;
1051    }
1052    String::from_utf8(decoded)
1053        .map(std::borrow::Cow::Owned)
1054        .map_err(|_| "path is not UTF-8 after percent-decoding".to_string())
1055}
1056
1057/// The segment rules of [`static_fs_path`], on a path using `/` or the
1058/// platform separator.
1059pub(crate) fn check_request_path(path: &str) -> Result<(), String> {
1060    for segment in path.split(['/', '\\']) {
1061        if segment == ".." {
1062            return Err("path leaves the web root".to_string());
1063        }
1064        if segment.starts_with('.') && segment != "." && segment != ".well-known" && !serve_dotfiles() {
1065            return Err("hidden files are not served".to_string());
1066        }
1067        if segment.contains('\0') {
1068            return Err("invalid path".to_string());
1069        }
1070    }
1071    // Keys and the config file, wherever they sit in the root (#45).
1072    let name = path.rsplit(['/', '\\']).next().unwrap_or("").to_ascii_lowercase();
1073    if name.ends_with(".pem") || name.ends_with(".key") || name == "rws.config.toml" {
1074        return Err("key and config files are not served".to_string());
1075    }
1076    Ok(())
1077}
1078
1079/// `RWS_CONFIG_SERVE_DOTFILES` (default `false`), read once.
1080fn serve_dotfiles() -> bool {
1081    static SERVE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1082    *SERVE.get_or_init(|| {
1083        std::env::var("RWS_CONFIG_SERVE_DOTFILES").is_ok_and(|v| v.trim().eq_ignore_ascii_case("true"))
1084    })
1085}
1086
1087/// `true` when `fs_path` exists and, symlinks resolved, lies inside the web
1088/// root (the working directory). A symlink in the root pointing outside it
1089/// (`assets -> /etc`) is not followed out (#43). One `realpath`: done where
1090/// a file is opened, not per request on the cached fast path.
1091pub(crate) fn inside_root(fs_path: &str) -> bool {
1092    static ROOT: std::sync::OnceLock<Option<std::path::PathBuf>> = std::sync::OnceLock::new();
1093    let Some(root) = ROOT.get_or_init(|| std::fs::canonicalize(working_directory()).ok()) else {
1094        return false;
1095    };
1096    std::fs::canonicalize(fs_path).is_ok_and(|resolved| resolved.starts_with(root))
1097}
1098
1099/// `FileExt::file_modified_utc` (nanoseconds since the Unix epoch) from a
1100/// `stat`, without opening the file.
1101pub(crate) fn file_modified_utc(path: &str) -> Result<u128, String> {
1102    let modified = metadata(path)
1103        .and_then(|md| md.modified())
1104        .map_err(|e| format!("<p>Unable to open file: {}</p> <p>error: {}</p>", path, e))?;
1105    Ok(modified
1106        .duration_since(std::time::UNIX_EPOCH)
1107        .map(|d| d.as_nanos())
1108        .unwrap_or(0))
1109}
1110