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 dictionaries;
19pub(crate) mod open_file_cache;
20
21pub struct StaticResourceController;
22
23impl Controller for StaticResourceController {
24 fn is_matching(request: &Request, _connection: &ConnectionInfo) -> bool {
25 let is_get = request.method == METHOD.get;
28 let is_head = request.method == METHOD.head;
29 let is_options = request.method == METHOD.options;
30
31 let is_matching_method = (is_get || is_head || is_options) && (request.request_uri != SYMBOL.slash);
32 if !is_matching_method {
33 return false;
34 }
35
36 let path = match URL::request_target_path(&request.request_uri) {
39 Some(path) => path,
40 None => return false,
41 };
42
43 let boxed_static_filepath = static_fs_path(&os_specific_path(path));
44 if boxed_static_filepath.is_err() {
45 return false
46 }
47
48 let static_filepath = boxed_static_filepath.unwrap();
49
50 let mut is_directory = false;
53
54 let mut is_file = open_file_cache::is_cached_file(&static_filepath);
57 if !is_file {
58 if let Ok(md) = metadata(&static_filepath) {
59 if !inside_root(&static_filepath) {
61 return false;
62 }
63 is_directory = md.is_dir();
64 is_file = md.is_file();
65 }
66 }
67
68 if is_file || is_directory {
69 true
70 } else {
71 if !static_filepath.ends_with(".html") {
73 let html_suffix = ".html";
74 let mut html_file = os_specific_path(path).into_owned();
75 html_file.push_str(html_suffix);
76 if let Ok(html_static_filepath) = static_fs_path(&html_file) {
77 if File::open(&html_static_filepath).is_ok() {
78 return true;
79 }
80 }
81 }
82
83 spa_fallback_url_path(path).is_some()
88 }
89
90 }
91
92 fn process(request: &Request, mut response: Response, _connection: &ConnectionInfo) -> Response {
93 let config = ServerConfig::current();
94 if let Some(served) = StaticResourceController::serve_regular_file(request, &mut response, &config) {
95 return served;
96 }
97 StaticResourceController::process_general(request, response, &config)
98 }
99}
100
101impl StaticResourceController {
102 pub(crate) fn is_directory_without_index(request: &Request) -> bool {
105 let Some(path) = URL::request_target_path(&request.request_uri) else { return false };
106 let Ok(fs_path) = static_fs_path(&os_specific_path(path)) else { return false };
107 let dir = std::path::Path::new(&fs_path);
108 dir.is_dir() && !dir.join("index.html").is_file()
109 }
110
111 pub(crate) fn process_general(request: &Request, mut response: Response, config: &ServerConfig) -> Response {
115 let without_stale_range;
119 let request = if range_is_stale(request) {
120 let mut copy = request.clone();
121 copy.headers.retain(|h| !h.name.eq_ignore_ascii_case(Header::_RANGE));
122 without_stale_range = copy;
123 &without_stale_range
124 } else {
125 request
126 };
127 let boxed_content_range_list = StaticResourceController::process_static_resources(&request);
128 if boxed_content_range_list.is_ok() {
129 let content_range_list = boxed_content_range_list.unwrap();
130
131 if content_range_list.len() != 0 {
132
133 let mut status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok;
134
135 let does_request_include_range_header = request.header(Header::_RANGE).is_some();
136 if does_request_include_range_header {
137 status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n206_partial_content;
138 }
139
140 let is_options_request = request.method == METHOD.options;
141 if is_options_request {
142 status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n204_no_content;
143 }
144
145
146
147 let url = request.request_uri.to_string();
148
149 let boxed_url_components = URL::parse_request_target(&url);
150 if boxed_url_components.is_err() {
151 let message = boxed_url_components.as_ref().err().unwrap().to_string();
152 println!("unexpected error, {}", message);
154 }
155
156 let components = boxed_url_components.unwrap();
157
158 let static_filepath = static_fs_path(&components.path).unwrap_or_default();
161 let boxed_modified_date_time = file_modified_utc(&static_filepath);
162
163 if boxed_modified_date_time.is_ok() {
164 let modified_date_time = boxed_modified_date_time.unwrap();
165 let file_size = metadata(&static_filepath).map(|m| m.len()).unwrap_or(0);
166 let etag_value = format!("\"{}-{}\"", modified_date_time, file_size);
167 set_static_cache_control(&mut response, &config.static_cache_control);
168 if push_validators(request, &mut response, modified_date_time, &etag_value, config.nanos_headers) {
169 response.status_code = *STATUS_CODE_REASON_PHRASE.n304_not_modified.status_code;
170 response.reason_phrase = STATUS_CODE_REASON_PHRASE.n304_not_modified.reason_phrase.to_string();
171 response.headers.push(Header { name: Header::_ETAG.into(), value: etag_value.into() });
172 return response;
173 }
174
175 response.headers.push(Header { name: Header::_ETAG.into(), value: etag_value.into() });
176
177 let is_range_request = request.header(Header::_RANGE).is_some();
180 if file_size > StaticResourceController::STREAM_THRESHOLD && !is_range_request {
181 let mime = MimeType::detect_mime_type(&static_filepath);
182 response.headers.push(Header {
183 name: Header::_CONTENT_TYPE.into(),
184 value: mime.into(),
185 });
186 response.headers.push(Header {
187 name: Header::_CONTENT_LENGTH.into(),
188 value: file_size.to_string().into(),
189 });
190 response.status_code = *status_code_reason_phrase.status_code;
191 response.reason_phrase = status_code_reason_phrase.reason_phrase.to_string();
192 response.stream_file = Some(static_filepath);
193 return response;
194 }
195 }
196
197 response.status_code = *status_code_reason_phrase.status_code;
198 response.reason_phrase = status_code_reason_phrase.reason_phrase.to_string();
199 response.content_range_list = content_range_list;
200
201 }
202 } else {
203 let error : Error = boxed_content_range_list.err().unwrap();
204 let body = error.message;
205
206 let content_range = Range::get_content_range(
207 Vec::from(body.as_bytes()),
208 MimeType::TEXT_HTML.to_string()
209 );
210
211 let content_range_list = vec![content_range];
212
213 response.status_code = *error.status_code_reason_phrase.status_code;
214 response.reason_phrase = error.status_code_reason_phrase.reason_phrase.to_string();
215 response.content_range_list = content_range_list;
216
217 if response.status_code == 416 {
219 let length = URL::parse_request_target(&request.request_uri).ok()
220 .and_then(|c| static_fs_path(&c.path).ok())
221 .and_then(|p| metadata(p).ok())
222 .map(|md| md.len());
223 if let Some(length) = length {
224 response.headers.push(Header { name: Header::_CONTENT_RANGE.into(), value: format!("bytes */{}", length).into() });
225 }
226 }
227 }
228
229
230 response
231 }
232}
233
234impl StaticResourceController {
236
237 pub fn is_matching_request(request: &Request) -> bool {
238 let boxed_static_filepath = static_fs_path(&request.request_uri);
239 if boxed_static_filepath.is_err() {
240 return false
241 }
242
243 let static_filepath = boxed_static_filepath.unwrap();
244
245 let boxed_md = metadata(&static_filepath);
246 if boxed_md.is_err() || !inside_root(&static_filepath) {
247 return false
248 }
249
250 let md = boxed_md.unwrap();
251 if md.is_dir() {
252 return false
253 }
254
255 let boxed_file = File::open(&static_filepath);
256
257 let is_get = request.method == METHOD.get;
258 let is_head = request.method == METHOD.head;
259 let is_options = request.method == METHOD.options;
260 boxed_file.is_ok() && (is_get || is_head || is_options && request.request_uri != SYMBOL.slash)
261 }
262
263 pub fn process_request(request: &Request, mut response: Response) -> Response {
264 let config = ServerConfig::current();
265 if let Some(streamed) = StaticResourceController::serve_regular_file(request, &mut response, &config) {
266 return streamed;
267 }
268 let boxed_content_range_list = StaticResourceController::process_static_resources(&request);
269 if boxed_content_range_list.is_ok() {
270 let content_range_list = boxed_content_range_list.unwrap();
271
272 if content_range_list.len() != 0 {
273
274 let mut status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n200_ok;
275
276 let does_request_include_range_header = request.header(Header::_RANGE).is_some();
277 if does_request_include_range_header {
278 status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n206_partial_content;
279 }
280
281 let is_options_request = request.method == METHOD.options;
282 if is_options_request {
283 status_code_reason_phrase = STATUS_CODE_REASON_PHRASE.n204_no_content;
284 }
285
286
287 let static_filepath = static_fs_path(&request.request_uri).unwrap_or_default();
288 let boxed_modified_date_time = file_modified_utc(&static_filepath);
289
290 if boxed_modified_date_time.is_ok() {
291 let modified_date_time = boxed_modified_date_time.unwrap();
292 let file_size = metadata(&static_filepath).map(|m| m.len()).unwrap_or(0);
293 let etag_value = format!("\"{}-{}\"", modified_date_time, file_size);
294 set_static_cache_control(&mut response, &config.static_cache_control);
295 if push_validators(request, &mut response, modified_date_time, &etag_value, config.nanos_headers) {
296 response.status_code = *STATUS_CODE_REASON_PHRASE.n304_not_modified.status_code;
297 response.reason_phrase = STATUS_CODE_REASON_PHRASE.n304_not_modified.reason_phrase.to_string();
298 response.headers.push(Header { name: Header::_ETAG.into(), value: etag_value.into() });
299 return response;
300 }
301
302 response.headers.push(Header { name: Header::_ETAG.into(), value: etag_value.into() });
303
304 let is_range_request = request.header(Header::_RANGE).is_some();
305 if file_size > StaticResourceController::STREAM_THRESHOLD && !is_range_request {
306 let mime = MimeType::detect_mime_type(&static_filepath);
307 response.headers.push(Header {
308 name: Header::_CONTENT_TYPE.into(),
309 value: mime.into(),
310 });
311 response.headers.push(Header {
312 name: Header::_CONTENT_LENGTH.into(),
313 value: file_size.to_string().into(),
314 });
315 response.status_code = *status_code_reason_phrase.status_code;
316 response.reason_phrase = status_code_reason_phrase.reason_phrase.to_string();
317 response.stream_file = Some(static_filepath);
318 return response;
319 }
320 }
321
322 response.status_code = *status_code_reason_phrase.status_code;
323 response.reason_phrase = status_code_reason_phrase.reason_phrase.to_string();
324 response.content_range_list = content_range_list;
325
326 }
327 } else {
328 let error : Error = boxed_content_range_list.err().unwrap();
329 let body = error.message;
330
331 let content_range = Range::get_content_range(
332 Vec::from(body.as_bytes()),
333 MimeType::TEXT_HTML.to_string()
334 );
335
336 let content_range_list = vec![content_range];
337
338 response.status_code = *error.status_code_reason_phrase.status_code;
339 response.reason_phrase = error.status_code_reason_phrase.reason_phrase.to_string();
340 response.content_range_list = content_range_list;
341
342 }
343
344
345 response
346 }
347
348 pub const STREAM_THRESHOLD: u64 = 256 * 1024;
352
353 pub(crate) fn serve_regular_file(request: &Request, response: &mut Response, config: &ServerConfig) -> Option<Response> {
363 if request.method != METHOD.get && request.method != METHOD.head {
364 return None;
365 }
366 if request.header(Header::_RANGE).is_some() {
367 return None;
368 }
369 let path = URL::request_target_path(&request.request_uri)?;
370 let fs_path = static_fs_path(&os_specific_path(path)).ok()?;
371 let mime = MimeType::mime_type_for(&fs_path);
375 let follow_symlinks = mime != MimeType::APPLICATION_OCTET_STREAM;
376 let file = open_file_cache::open(&fs_path, follow_symlinks)?;
377 let state = file.state()?;
378
379 let encoding = if state.len <= open_file_cache::MAX_GZIPPED_FILE
384 && state.len >= crate::compression::MIN_COMPRESS_SIZE as u64
385 && crate::compression::is_compressible(mime)
386 {
387 crate::compression::negotiate(request, crate::compression::STATIC_PREFERENCE)
388 } else {
389 None
390 };
391 let dictionary_pattern = if config.compression_dictionaries.is_empty()
395 || state.len > crate::compression::dictionary::MAX_SIZE as u64
396 || !crate::compression::is_compressible(mime)
397 {
398 None
399 } else {
400 dictionaries::matching_pattern(&config.compression_dictionaries, path)
401 };
402 let delta = match dictionary_pattern {
403 Some(_) => {
404 let _ = file.dictionary_hash(&state);
405 match (crate::compression::dictionary::available_dictionary(request), crate::compression::dictionary::negotiate(request)) {
406 (Some(held), Some(coding)) => match dictionaries::get(&held) {
407 Some(bytes) => file.delta(&state, coding, held, &bytes).ok()?.map(|delta| (coding, held, delta)),
408 None => None,
409 },
410 _ => None,
411 }
412 }
413 None => None,
414 };
415 let modified = Decimal::new(state.modified);
420 let len = Decimal::new(state.len as u128);
421 let mut etag_value = String::with_capacity(modified.as_str().len() + len.as_str().len() + 8);
422 etag_value.push('"');
423 etag_value.push_str(modified.as_str());
424 etag_value.push('-');
425 etag_value.push_str(len.as_str());
426 if let Some((coding, held, _)) = &delta {
427 etag_value.push('-');
429 etag_value.push_str(coding.token());
430 etag_value.push('-');
431 held[..4].iter().for_each(|b| etag_value.push_str(&format!("{b:02x}")));
432 } else if let Some(encoding) = encoding {
433 etag_value.push('-');
434 etag_value.push_str(encoding.token());
435 }
436 etag_value.push('"');
437 let not_modified = is_not_modified(request, state.modified, &etag_value);
438 let mut sent_encoded = None;
445 let mut sent_delta = None;
446 let large = state.len > StaticResourceController::STREAM_THRESHOLD;
447 let body = if not_modified {
448 None
449 } else if let Some((coding, _, bytes)) = &delta {
450 sent_delta = Some(*coding);
451 Some(bytes.to_vec())
452 } else if let Some(encoding) = encoding {
453 match file.encoded(&state, encoding, &fs_path).ok()? {
454 open_file_cache::Encoded::Smaller(bytes) => {
455 sent_encoded = Some(encoding);
456 Some(bytes.to_vec())
457 }
458 open_file_cache::Encoded::NotSmaller if large => None,
459 open_file_cache::Encoded::NotSmaller => Some(file.contents(&state).ok()?),
460 }
461 } else if large {
462 None
463 } else {
464 Some(file.contents(&state).ok()?)
465 };
466
467 let mut response = std::mem::replace(response, Response::empty());
468 set_static_cache_control(&mut response, &config.static_cache_control);
469 if config.nanos_headers {
470 response.headers.push(Header { name: Header::_LAST_MODIFIED_UNIX_EPOCH_NANOS.into(), value: modified.as_str().to_string().into() });
471 }
472 response.headers.push(Header { name: Header::_LAST_MODIFIED.into(), value: crate::http::date::format((state.modified / 1_000_000_000) as u64).into() });
473 response.headers.push(Header { name: Header::_ETAG.into(), value: etag_value.into() });
474 if not_modified {
475 response.set_status(STATUS_CODE_REASON_PHRASE.n304_not_modified);
476 mark_dictionary(&mut response, dictionary_pattern);
477 return Some(response);
478 }
479 response.set_status(STATUS_CODE_REASON_PHRASE.n200_ok);
480
481 let Some(body) = body else {
482 response.headers.push(Header { name: Header::_CONTENT_TYPE.into(), value: mime.to_string().into() });
483 response.headers.push(Header { name: Header::_CONTENT_LENGTH.into(), value: len.as_str().to_string().into() });
484 response.stream_file = Some(fs_path);
485 mark_dictionary(&mut response, dictionary_pattern);
486 return Some(response);
487 };
488
489 response.content_range_list = vec![Range::get_content_range(body, mime.to_string())];
490 if let Some(coding) = sent_delta {
491 crate::compression::dictionary::mark_encoded(&mut response, coding);
492 } else if let Some(encoding) = sent_encoded {
493 crate::compression::mark_encoded(&mut response, encoding);
494 }
495 mark_dictionary(&mut response, dictionary_pattern);
496 Some(response)
497 }
498
499 pub fn process_static_resources(request: &Request) -> Result<Vec<ContentRange>, Error> {
500
501 let url = request.request_uri.to_string();
502
503 let boxed_url_components = URL::parse_request_target(&url);
504 if boxed_url_components.is_err() {
505 let message = boxed_url_components.as_ref().err().unwrap().to_string();
506 println!("unexpected error, {}", message);
508 }
509
510 let components = boxed_url_components.unwrap();
511
512 let os_specific_separator : String = FileExt::get_path_separator();
513 let os_specific_path = &components.path.replace(SYMBOL.slash, os_specific_separator.as_str());
514
515 let static_filepath = match static_fs_path(&os_specific_path) {
516 Ok(path) => path,
517 Err(message) => {
518 return Err(Error { status_code_reason_phrase: STATUS_CODE_REASON_PHRASE.n404_not_found, message });
519 }
520 };
521
522 let mut content_range_list = Vec::new();
523
524
525 let mut boxed_md = metadata(&static_filepath);
526 if boxed_md.is_err() {
527 let dot_html = format!("{}{}", &static_filepath, ".html");
528 boxed_md = metadata(&dot_html);
529
530 if boxed_md.is_err() {
531 let slash_index_html = format!("{}{}{}", &static_filepath, os_specific_separator, "index.html");
532 boxed_md = metadata(&slash_index_html);
533 }
534 }
535 if boxed_md.is_ok() {
536 let md = boxed_md.unwrap();
537
538 if md.is_dir() {
539 let mut directory_index : String = "index.html".to_string();
540
541 let last_char = components.path.chars().last().unwrap();
542 if last_char != '/' {
543 let index : String = "index.html".to_string();
544 directory_index = format!("{}{}", os_specific_separator, index);
545 }
546 let index_html_in_directory = format!("{}{}", os_specific_path, directory_index);
547 let index_html_fs_path = format!("{}{}", static_filepath, directory_index);
548
549 if File::open(&index_html_fs_path).is_ok() {
550 let mut range_header = &Header {
551 name: Header::_RANGE.into(),
552 value: "bytes=0-".into()
553 };
554
555 let boxed_header = request.header(Header::_RANGE);
556 if boxed_header.is_some() {
557 range_header = boxed_header.unwrap();
558 }
559
560 let boxed_content_range_list = Range::get_content_range_list(&index_html_in_directory, range_header);
561 if boxed_content_range_list.is_ok() {
562 content_range_list = boxed_content_range_list.unwrap();
563 } else {
564 let error = boxed_content_range_list.err().unwrap();
565 return Err(error)
566 }
567 } else {
568 let listing_html = StaticResourceController::render_directory_listing(&static_filepath, &components.path);
569 let content_range = Range::get_content_range(listing_html.into_bytes(), MimeType::TEXT_HTML.to_string());
570 content_range_list = vec![content_range];
571 }
572
573 return Ok(content_range_list);
574 }
575
576 let boxed_file = File::open(&static_filepath);
577 if boxed_file.is_ok() {
578 let md = metadata(&static_filepath).unwrap();
579 if md.is_dir() {
580 let mut range_header = &Header {
581 name: Header::_RANGE.into(),
582 value: "bytes=0-".into()
583 };
584
585 let boxed_header = request.header(Header::_RANGE);
586 if boxed_header.is_some() {
587 range_header = boxed_header.unwrap();
588 }
589
590 let mut directory_index : String = "index.html".to_string();
591
592 let last_char = components.path.chars().last().unwrap();
593 if last_char != '/' {
594 let index : String = "index.html".to_string();
595 directory_index = format!("{}{}", os_specific_separator, index);
596 }
597 let index_html_in_directory = format!("{}{}", os_specific_path, directory_index);
598
599
600 let boxed_content_range_list = Range::get_content_range_list(&index_html_in_directory, range_header);
601 if boxed_content_range_list.is_ok() {
602 content_range_list = boxed_content_range_list.unwrap();
603 } else {
604 let error = boxed_content_range_list.err().unwrap();
605 return Err(error)
606 }
607 }
608
609 if md.is_file() {
610 let mut range_header = &Header {
611 name: Header::_RANGE.into(),
612 value: "bytes=0-".into()
613 };
614
615 let boxed_header = request.header(Header::_RANGE);
616 if boxed_header.is_some() {
617 range_header = boxed_header.unwrap();
618 }
619
620 let boxed_content_range_list = Range::get_content_range_list(&request.request_uri, range_header);
621 if boxed_content_range_list.is_ok() {
622 content_range_list = boxed_content_range_list.unwrap();
623 } else {
624 let error = boxed_content_range_list.err().unwrap();
625 return Err(error)
626 }
627 }
628 }
629
630
631 if boxed_file.is_err() {
632 let static_filepath = static_fs_path(&format!("{}.html", components.path)).unwrap_or_default();
635
636 let boxed_file = File::open(&static_filepath);
637 if boxed_file.is_ok() {
638 let md = metadata(&static_filepath).unwrap();
639 if md.is_file() {
640 let mut range_header = &Header {
641 name: Header::_RANGE.into(),
642 value: "bytes=0-".into()
643 };
644
645 let boxed_header = request.header(Header::_RANGE);
646 if boxed_header.is_some() {
647 range_header = boxed_header.unwrap();
648 }
649
650 let url = request.request_uri.to_string();
651
652 let boxed_url_components = URL::parse_request_target(&url);
653 if boxed_url_components.is_err() {
654 let message = boxed_url_components.as_ref().err().unwrap().to_string();
655 println!("unexpected error, {}", message);
657 }
658
659 let components = boxed_url_components.unwrap();
660
661 let html_file = [components.path.as_str(), ".html"].join(SYMBOL.empty_string);
665 let boxed_content_range_list = Range::get_content_range_list(html_file.as_str(), range_header);
666 if boxed_content_range_list.is_ok() {
667 content_range_list = boxed_content_range_list.unwrap();
668 } else {
669 let error = boxed_content_range_list.err().unwrap();
670 return Err(error)
671 }
672 }
673 }
674 }
675 }
676
677 if content_range_list.is_empty() {
681 if let Some(fallback_url_path) = spa_fallback_url_path(&components.path) {
682 let mut range_header = &Header {
683 name: Header::_RANGE.into(),
684 value: "bytes=0-".into()
685 };
686
687 let boxed_header = request.header(Header::_RANGE);
688 if boxed_header.is_some() {
689 range_header = boxed_header.unwrap();
690 }
691
692 if let Ok(list) = Range::get_content_range_list(&fallback_url_path, range_header) {
693 content_range_list = list;
694 }
695 }
696 }
697
698 Ok(content_range_list)
699 }
700}
701
702impl StaticResourceController {
706 pub fn render_directory_listing(fs_dir_path: &str, request_path: &str) -> String {
711 let normalized_request_path = if request_path.ends_with('/') {
712 request_path.to_string()
713 } else {
714 format!("{}/", request_path)
715 };
716
717 struct Entry {
718 name: String,
719 is_dir: bool,
720 size: u64,
721 modified_epoch_secs: u64,
722 }
723
724 let mut entries: Vec<Entry> = Vec::new();
725 if let Ok(dir_entries) = read_dir(fs_dir_path) {
726 for dir_entry in dir_entries.flatten() {
727 let name = dir_entry.file_name().to_string_lossy().to_string();
728 if name.starts_with('.') {
729 continue;
730 }
731
732 if let Ok(md) = dir_entry.metadata() {
733 let modified_epoch_secs = md.modified()
734 .ok()
735 .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
736 .map(|d| d.as_secs())
737 .unwrap_or(0);
738
739 entries.push(Entry {
740 name,
741 is_dir: md.is_dir(),
742 size: md.len(),
743 modified_epoch_secs,
744 });
745 }
746 }
747 }
748
749 entries.sort_by(|a, b| {
750 match (a.is_dir, b.is_dir) {
751 (true, false) => std::cmp::Ordering::Less,
752 (false, true) => std::cmp::Ordering::Greater,
753 _ => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
754 }
755 });
756
757 let segments: Vec<&str> = normalized_request_path.split('/').filter(|s| !s.is_empty()).collect();
758
759 let mut breadcrumb_html = String::from("<a href=\"/\">~</a>");
760 let mut accumulated_path = String::new();
761 for segment in &segments {
762 accumulated_path.push('/');
763 accumulated_path.push_str(segment);
764 breadcrumb_html.push_str(&format!(
765 " <span class=\"sep\">/</span> <a href=\"{}/\">{}</a>",
766 accumulated_path, html_escape(segment)
767 ));
768 }
769
770 let parent_row = if !segments.is_empty() {
771 let parent_path = if segments.len() > 1 {
772 format!("/{}/", segments[..segments.len() - 1].join("/"))
773 } else {
774 "/".to_string()
775 };
776 format!(
777 "<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",
778 parent_path
779 )
780 } else {
781 String::new()
782 };
783
784 let entry_count = entries.len();
785
786 let mut rows = String::new();
787 for entry in &entries {
788 let escaped_name = html_escape(&entry.name);
789 let encoded_name = URL::percent_encode(&entry.name);
790 let href = if entry.is_dir {
791 format!("{}{}/", normalized_request_path, encoded_name)
792 } else {
793 format!("{}{}", normalized_request_path, encoded_name)
794 };
795 let size_display = if entry.is_dir { "\u{2014}".to_string() } else { human_size(entry.size) };
796 let modified_display = format_modified(entry.modified_epoch_secs);
797 let icon = icon_for(&entry.name, entry.is_dir);
798 let filter_key = html_escape(&entry.name.to_lowercase());
799
800 rows.push_str(&format!(
801 "<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",
802 filter_key, icon, href, escaped_name, if entry.is_dir { "/" } else { "" }, size_display, modified_display
803 ));
804 }
805
806 let mut html = String::new();
807 html.push_str(DIRECTORY_LISTING_HEAD);
808 html.push_str(&format!("<div class=\"breadcrumb\">{}</div>\n", breadcrumb_html));
809 html.push_str(&format!("<h1>Index of {}</h1>\n", html_escape(&normalized_request_path)));
810 html.push_str(DIRECTORY_LISTING_TOOLBAR);
811 html.push_str("<div class=\"card\"><table><thead><tr><th>Name</th><th>Size</th><th>Modified</th></tr></thead><tbody id=\"rows\">\n");
812 html.push_str(&parent_row);
813 html.push_str(&rows);
814 html.push_str("</tbody></table></div>\n");
815 html.push_str(&format!(
816 "<footer>{} item{} · served by rws</footer>\n",
817 entry_count, if entry_count == 1 { "" } else { "s" }
818 ));
819 html.push_str(DIRECTORY_LISTING_TAIL);
820
821 html
822 }
823}
824
825fn path_has_extension(path: &str) -> bool {
832 path.rsplit('/').next().unwrap_or("").contains('.')
833}
834
835fn spa_fallback_url_path(url_path: &str) -> Option<String> {
844 if path_has_extension(url_path) {
845 return None;
846 }
847
848 let fallback_name = crate::entry_point::get_spa_fallback()?;
849
850 let exclude_prefixes = crate::entry_point::get_spa_fallback_exclude_prefixes();
851 if exclude_prefixes.iter().any(|prefix| url_path.starts_with(prefix.as_str())) {
852 return None;
853 }
854
855 let separator = FileExt::get_path_separator();
856 let normalized_name = fallback_name.trim_start_matches('/').replace('/', &separator);
857 let fallback_url_path = format!("{}{}", separator, normalized_name);
858
859 let boxed_fs_path = static_fs_path(&fallback_url_path);
860 let fs_path = boxed_fs_path.ok()?;
861 if File::open(&fs_path).is_ok() {
862 Some(fallback_url_path)
863 } else {
864 None
865 }
866}
867
868fn html_escape(s: &str) -> String {
869 let mut out = String::with_capacity(s.len());
870 for c in s.chars() {
871 match c {
872 '&' => out.push_str("&"),
873 '<' => out.push_str("<"),
874 '>' => out.push_str(">"),
875 '"' => out.push_str("""),
876 '\'' => out.push_str("'"),
877 _ => out.push(c),
878 }
879 }
880 out
881}
882
883fn human_size(bytes: u64) -> String {
884 const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
885 if bytes < 1024 {
886 return format!("{} {}", bytes, UNITS[0]);
887 }
888
889 let mut size = bytes as f64;
890 let mut unit_index = 0;
891 while size >= 1024.0 && unit_index < UNITS.len() - 1 {
892 size /= 1024.0;
893 unit_index += 1;
894 }
895
896 format!("{:.1} {}", size, UNITS[unit_index])
897}
898
899fn format_modified(epoch_secs: u64) -> String {
900 let (sec, min, hour, day, month, _dow) = crate::scheduler::cron::epoch_to_datetime(epoch_secs);
901 let (year, _, _) = crate::scheduler::cron::days_to_ymd(epoch_secs / 86400);
902 format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}", year, month, day, hour, min, sec)
903}
904
905fn icon_for(name: &str, is_dir: bool) -> &'static str {
906 if is_dir {
907 return "\u{1F4C1}";
908 }
909
910 let ext = name.rsplit('.').next().unwrap_or("").to_lowercase();
911 match ext.as_str() {
912 "png" | "jpg" | "jpeg" | "gif" | "svg" | "webp" | "ico" | "bmp" => "\u{1F5BC}\u{FE0F}",
913 "mp4" | "mov" | "avi" | "mkv" | "webm" => "\u{1F3A5}",
914 "mp3" | "wav" | "flac" | "m4a" | "ogg" => "\u{1F3A7}",
915 "zip" | "tar" | "gz" | "rar" | "7z" | "bz2" => "\u{1F4E6}",
916 "pdf" => "\u{1F4D5}",
917 "html" | "htm" | "css" | "js" | "ts" | "rs" | "py" | "json" | "toml" | "yaml" | "yml" | "sh" => "\u{1F9E9}",
918 _ => "\u{1F4C4}",
919 }
920}
921
922const DIRECTORY_LISTING_HEAD: &str = concat!(
927 "<!DOCTYPE html>\n",
928 "<html lang=\"en\">\n",
929 "<head>\n",
930 "<meta charset=\"UTF-8\">\n",
931 "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n",
932 "<title>Directory listing</title>\n",
933 "<link rel=\"stylesheet\" href=\"/rws-directory-listing.css\">\n",
934 "</head>\n",
935 "<body>\n",
936 "<div class=\"wrap\">\n",
937);
938
939const DIRECTORY_LISTING_TOOLBAR: &str = "<div class=\"toolbar\"><input type=\"search\" id=\"filter\" placeholder=\"Filter entries...\" autocomplete=\"off\"></div>\n";
940
941const DIRECTORY_LISTING_TAIL: &str = concat!(
942 "</div>\n",
943 "<script src=\"/rws-directory-listing.js\" defer></script>\n",
944 "</body>\n",
945 "</html>\n",
946);
947
948fn push_validators(request: &Request, response: &mut Response, modified_nanos: u128, etag: &str, nanos_headers: bool) -> bool {
957 if nanos_headers {
958 response.headers.push(Header { name: Header::_LAST_MODIFIED_UNIX_EPOCH_NANOS.into(), value: modified_nanos.to_string().into() });
959 }
960 response.headers.push(Header { name: Header::_LAST_MODIFIED.into(), value: crate::http::date::format((modified_nanos / 1_000_000_000) as u64).into() });
961 is_not_modified(request, modified_nanos, etag)
962}
963
964fn is_not_modified(request: &Request, modified_nanos: u128, etag: &str) -> bool {
968 if let Some(inm) = request.header(Header::_IF_NONE_MATCH) {
969 return if_none_match_matches(&inm.value, etag);
970 }
971 if request.method != METHOD.get && request.method != METHOD.head {
972 return false;
973 }
974 request
975 .header(Header::_IF_MODIFIED_SINCE)
976 .and_then(|ims| crate::http::date::parse(&ims.value))
977 .is_some_and(|since| (modified_nanos / 1_000_000_000) as u64 <= since)
978}
979
980fn set_static_cache_control(response: &mut Response, value: &str) {
983 if value.is_empty() {
984 return;
985 }
986 if let Some(header) = response.headers.iter_mut().find(|h| h.name == Header::_CACHE_CONTROL) {
987 header.value = if value == crate::server_config::STATIC_CACHE_CONTROL_DEFAULT {
988 std::borrow::Cow::Borrowed(crate::server_config::STATIC_CACHE_CONTROL_DEFAULT)
989 } else {
990 std::borrow::Cow::Owned(value.to_string())
991 };
992 }
993}
994
995pub(crate) fn working_directory() -> &'static str {
996 static DIR: std::sync::OnceLock<String> = std::sync::OnceLock::new();
997 DIR.get_or_init(|| {
998 std::env::current_dir()
999 .map(|d| d.to_string_lossy().into_owned())
1000 .unwrap_or_default()
1001 })
1002}
1003
1004pub(crate) fn if_none_match_matches(header_value: &str, etag: &str) -> bool {
1009 let opaque = |tag: &str| tag.trim().strip_prefix("W/").unwrap_or(tag.trim()).to_string();
1010 let current = opaque(etag);
1011 header_value.split(',').any(|candidate| {
1012 let candidate = candidate.trim();
1013 candidate == "*" || (!candidate.is_empty() && opaque(candidate) == current)
1014 })
1015}
1016
1017pub(crate) fn range_is_stale(request: &Request) -> bool {
1025 let Some(if_range) = request.header(Header::_IF_RANGE) else { return false };
1026 if request.header(Header::_RANGE).is_none() {
1027 return false;
1028 }
1029 let validator = if_range.value.trim();
1030 let Some(path) = URL::request_target_path(&request.request_uri) else { return true };
1031 let Ok(fs_path) = static_fs_path(&os_specific_path(path)) else { return true };
1032 let (Ok(modified), Ok(md)) = (file_modified_utc(&fs_path), metadata(&fs_path)) else { return true };
1033 if validator.starts_with('"') {
1034 return validator != format!("\"{}-{}\"", modified, md.len());
1035 }
1036 let modified_secs = (modified / 1_000_000_000) as u64;
1037 let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
1038 match crate::http::date::parse(validator) {
1039 Some(date) => date != modified_secs || now < modified_secs + 1,
1040 None => true,
1041 }
1042}
1043
1044pub(crate) fn static_fs_path(path: &str) -> Result<String, String> {
1059 let path = percent_decode_path(path)?;
1060 check_request_path(&path)?;
1061 let working_directory = working_directory();
1062 let mut fs_path = String::with_capacity(working_directory.len() + path.len());
1063 fs_path.push_str(working_directory);
1064 fs_path.push_str(&path);
1065 Ok(fs_path)
1066}
1067
1068pub(crate) fn os_specific_path(path: &str) -> std::borrow::Cow<'_, str> {
1071 if std::path::MAIN_SEPARATOR == '/' {
1072 std::borrow::Cow::Borrowed(path)
1073 } else {
1074 std::borrow::Cow::Owned(path.replace('/', std::path::MAIN_SEPARATOR_STR))
1075 }
1076}
1077
1078pub(crate) fn percent_decode_path(path: &str) -> Result<std::borrow::Cow<'_, str>, String> {
1083 if !path.contains('%') {
1084 return Ok(std::borrow::Cow::Borrowed(path));
1085 }
1086 let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
1087 let bytes = path.as_bytes();
1088 let mut decoded = Vec::with_capacity(bytes.len());
1089 let mut i = 0;
1090 while i < bytes.len() {
1091 if bytes[i] == b'%' && i + 2 < bytes.len() {
1092 if let (Some(high), Some(low)) = (hex(bytes[i + 1]), hex(bytes[i + 2])) {
1093 decoded.push(high << 4 | low);
1094 i += 3;
1095 continue;
1096 }
1097 }
1098 decoded.push(bytes[i]);
1099 i += 1;
1100 }
1101 String::from_utf8(decoded)
1102 .map(std::borrow::Cow::Owned)
1103 .map_err(|_| "path is not UTF-8 after percent-decoding".to_string())
1104}
1105
1106pub(crate) fn check_request_path(path: &str) -> Result<(), String> {
1109 for segment in path.split(['/', '\\']) {
1110 if segment == ".." {
1111 return Err("path leaves the web root".to_string());
1112 }
1113 if segment.starts_with('.') && segment != "." && segment != ".well-known" && !serve_dotfiles() {
1114 return Err("hidden files are not served".to_string());
1115 }
1116 if segment.contains('\0') {
1117 return Err("invalid path".to_string());
1118 }
1119 }
1120 let name = path.rsplit(['/', '\\']).next().unwrap_or("").to_ascii_lowercase();
1122 if name.ends_with(".pem") || name.ends_with(".key") || name == "rws.config.toml" {
1123 return Err("key and config files are not served".to_string());
1124 }
1125 Ok(())
1126}
1127
1128fn serve_dotfiles() -> bool {
1130 static SERVE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1131 *SERVE.get_or_init(|| {
1132 std::env::var("RWS_CONFIG_SERVE_DOTFILES").is_ok_and(|v| v.trim().eq_ignore_ascii_case("true"))
1133 })
1134}
1135
1136pub(crate) fn inside_root(fs_path: &str) -> bool {
1141 static ROOT: std::sync::OnceLock<Option<std::path::PathBuf>> = std::sync::OnceLock::new();
1142 let Some(root) = ROOT.get_or_init(|| std::fs::canonicalize(working_directory()).ok()) else {
1143 return false;
1144 };
1145 std::fs::canonicalize(fs_path).is_ok_and(|resolved| resolved.starts_with(root))
1146}
1147
1148pub(crate) fn file_modified_utc(path: &str) -> Result<u128, String> {
1151 let modified = metadata(path)
1152 .and_then(|md| md.modified())
1153 .map_err(|e| format!("<p>Unable to open file: {}</p> <p>error: {}</p>", path, e))?;
1154 Ok(modified
1155 .duration_since(std::time::UNIX_EPOCH)
1156 .map(|d| d.as_nanos())
1157 .unwrap_or(0))
1158}
1159
1160
1161fn mark_dictionary(response: &mut Response, pattern: Option<&str>) {
1164 let Some(pattern) = pattern else { return };
1165 response.headers.push(Header { name: "Use-As-Dictionary".into(), value: dictionaries::use_as_dictionary(pattern).into() });
1166 crate::compression::dictionary::add_vary(response, "Accept-Encoding");
1167 crate::compression::dictionary::add_vary(response, "Available-Dictionary");
1168}