Skip to main content

net/
local_directory_listing.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::fmt::Write as _;
6use std::fs::Metadata;
7use std::path::PathBuf;
8
9use chrono::{DateTime, Local};
10use embedder_traits::resources::{Resource, read_bytes};
11use headers::{ContentType, HeaderMapExt};
12use net_traits::request::Request;
13use net_traits::response::{Response, ResponseBody};
14use net_traits::{NetworkError, ResourceFetchTiming};
15use servo_config::pref;
16use servo_url::ServoUrl;
17use url::Url;
18
19pub(crate) async fn fetch(request: &mut Request, url: ServoUrl, path_buf: PathBuf) -> Response {
20    if !pref!(network_local_directory_listing_enabled) {
21        // If you want to be able to browse local directories, configure Servo prefs so that
22        // "network.local_directory_listing.enabled" is set to true.
23        return Response::network_error(NetworkError::LocalDirectoryError);
24    }
25
26    if !request.origin.is_opaque() {
27        // Checking for an opaque origin as a shorthand for user activation
28        // as opposed to a request originating from a script.
29        // TODO(32534): carefully consider security of this approach.
30        return Response::network_error(NetworkError::LocalDirectoryError);
31    }
32
33    let directory_contents = match tokio::fs::read_dir(&path_buf).await {
34        Ok(directory_contents) => directory_contents,
35        Err(error) => {
36            return Response::network_error(NetworkError::ResourceLoadError(format!(
37                "Unable to access directory: {error}"
38            )));
39        },
40    };
41
42    let output = build_html_directory_listing(url.as_url(), path_buf, directory_contents).await;
43
44    let mut response = Response::new(url, ResourceFetchTiming::new(request.timing_type()));
45    response.headers.typed_insert(ContentType::html());
46    *response.body.lock() = ResponseBody::Done(output.into_bytes());
47
48    response
49}
50
51/// Returns an the string of an JavaScript `<script>` tag calling the `setData` function with the
52/// contents of the given [`ReadDir`] directory listing.
53///
54/// # Arguments
55///
56/// * `url` - the original URL of the request that triggered this directory listing.
57/// * `path` - the full path to the local directory.
58/// * `directory_contents` - a [`ReadDir`] with the contents of the directory.
59pub(crate) async fn build_html_directory_listing(
60    url: &Url,
61    path: PathBuf,
62    mut directory_contents: tokio::fs::ReadDir,
63) -> String {
64    let mut page_html = String::with_capacity(1024);
65    page_html.push_str("<!DOCTYPE html>");
66
67    let mut parent_url_string = String::new();
68    if path.parent().is_some() {
69        let mut parent_url = url.clone();
70        if let Ok(mut path_segments) = parent_url.path_segments_mut() {
71            path_segments.pop();
72        }
73        parent_url.as_str().clone_into(&mut parent_url_string);
74    }
75
76    page_html
77        .push_str(str::from_utf8(read_bytes(Resource::DirectoryListingHTML).as_ref()).unwrap());
78
79    page_html.push_str("<script>\n");
80    write!(
81        page_html,
82        "setData({:?}, {:?}, [",
83        url.as_str(),
84        parent_url_string
85    )
86    .unwrap();
87
88    while let Ok(Some(directory_entry)) = directory_contents.next_entry().await {
89        let Ok(metadata) = directory_entry.metadata().await else {
90            continue;
91        };
92        write_directory_entry(directory_entry, metadata, url, &mut page_html);
93    }
94
95    page_html.push_str("]);");
96    page_html.push_str("</script>\n");
97
98    page_html
99}
100
101fn write_directory_entry(
102    entry: tokio::fs::DirEntry,
103    metadata: Metadata,
104    url: &Url,
105    output: &mut String,
106) {
107    let Ok(name) = entry.file_name().into_string() else {
108        return;
109    };
110
111    let mut file_url = url.clone();
112    {
113        let Ok(mut path_segments) = file_url.path_segments_mut() else {
114            return;
115        };
116        path_segments.push(&name);
117    }
118
119    let class = if metadata.is_dir() {
120        "directory"
121    } else if metadata.is_symlink() {
122        "symlink"
123    } else {
124        "file"
125    };
126
127    let file_url_string = file_url.as_str();
128    let file_size = metadata_to_file_size_string(&metadata);
129    let last_modified = metadata
130        .modified()
131        .map(DateTime::<Local>::from)
132        .map(|time| time.format("%F %r").to_string())
133        .unwrap_or_default();
134
135    // The file name is the only value here that reaches the page unencoded; the
136    // url crate percent-encodes `<`/`>` in `file_url_string`, and the remaining
137    // fields are produced by us. `{:?}` is not enough on its own because it
138    // leaves `</script>` intact inside the script element below.
139    let name = script_string_literal(&name);
140    write!(
141        output,
142        "[{class:?}, {name}, {file_url_string:?}, {file_size:?}, {last_modified:?}],"
143    )
144    .unwrap();
145}
146
147/// Serialise `value` as a JavaScript string literal that is safe to embed in the
148/// inline `<script>` element of the directory listing. `{:?}` produces a valid
149/// literal but leaves any `<` (and therefore `</script>`) untouched, which lets a
150/// crafted file name close the script element and inject markup into the page.
151fn script_string_literal(value: &str) -> String {
152    format!("{value:?}").replace('<', "\\u003C")
153}
154
155pub fn metadata_to_file_size_string(metadata: &Metadata) -> String {
156    if !metadata.is_file() {
157        return String::new();
158    }
159
160    let mut float_size = metadata.len() as f64;
161    let mut prefix_power = 0;
162    while float_size > 1000.0 && prefix_power < 3 {
163        float_size /= 1000.0;
164        prefix_power += 1;
165    }
166
167    let prefix = match prefix_power {
168        0 => "B",
169        1 => "KB",
170        2 => "MB",
171        _ => "GB",
172    };
173
174    format!("{:.2} {prefix}", float_size)
175}
176
177#[cfg(test)]
178mod tests {
179    use super::script_string_literal;
180
181    #[test]
182    fn script_string_literal_neutralises_script_close() {
183        let literal = script_string_literal("a</script><img src=x onerror=alert(1)>b");
184        assert!(!literal.contains('<'));
185        assert!(!literal.to_lowercase().contains("</script"));
186    }
187
188    #[test]
189    fn script_string_literal_keeps_debug_escaping() {
190        // Quotes and backslashes from the input stay escaped so the result is
191        // still a valid JavaScript string literal.
192        assert_eq!(script_string_literal("a\"b\\c"), r#""a\"b\\c""#);
193        assert_eq!(script_string_literal("plain"), r#""plain""#);
194    }
195}