Skip to main content

servoshell/desktop/protocols/
resource.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
5//! This protocol handler loads files from the <resources_dir_path()>/protocol/resource directory,
6//! sanitizing the path to prevent path escape attacks.
7//! For security reasons, loads are only allowed if the referrer has a 'resource' or
8//! 'servo' scheme.
9
10use std::fs::File;
11use std::future::Future;
12use std::io::{BufReader, Read};
13use std::pin::Pin;
14
15use flate2::read::GzDecoder;
16use headers::{ContentType, HeaderMapExt};
17use servo::protocol_handler::{
18    DoneChannel, FILE_CHUNK_SIZE, FetchContext, NetworkError, ProtocolHandler, RelativePos,
19    Request, ResourceFetchTiming, Response, ResponseBody,
20};
21use tokio::sync::mpsc::unbounded_channel;
22
23#[derive(Default)]
24pub struct ResourceProtocolHandler {}
25
26impl ResourceProtocolHandler {
27    pub fn response_for_path(
28        request: &mut Request,
29        done_chan: &mut DoneChannel,
30        context: &FetchContext,
31        path: &str,
32    ) -> Pin<Box<dyn Future<Output = Response> + Send>> {
33        if path.contains("..") || !path.starts_with("/") {
34            return Box::pin(std::future::ready(Response::network_error(
35                NetworkError::ResourceLoadError("Invalid path".to_owned()),
36            )));
37        }
38
39        let path = if let Some(path) = path.strip_prefix("/") {
40            path
41        } else {
42            return Box::pin(std::future::ready(Response::network_error(
43                NetworkError::ResourceLoadError("Invalid path".to_owned()),
44            )));
45        };
46
47        let file_path = crate::resources::resource_protocol_dir_path().join(path);
48        // Packaged builds ship some large resources gzip-compressed (see `./mach package`).
49        let (open_path, compressed) = if file_path.is_file() {
50            (file_path.clone(), false)
51        } else {
52            (
53                crate::resources::resource_protocol_dir_path().join(format!("{path}.gz")),
54                true,
55            )
56        };
57
58        if !open_path.is_file() {
59            return Box::pin(std::future::ready(Response::network_error(
60                NetworkError::ResourceLoadError("Invalid path".to_owned()),
61            )));
62        }
63
64        let response = if let Ok(file) = File::open(open_path) {
65            let mut response = Response::new(
66                request.current_url(),
67                ResourceFetchTiming::new(request.timing_type()),
68            );
69            let file: Box<dyn Read + Send> = if compressed {
70                Box::new(GzDecoder::new(file))
71            } else {
72                Box::new(file)
73            };
74            let reader = BufReader::with_capacity(FILE_CHUNK_SIZE, file);
75
76            // Set Content-Type header.
77            let mime = mime_guess::from_path(file_path).first_or_octet_stream();
78            response.headers.typed_insert(ContentType::from(mime));
79
80            // Setup channel to receive cross-thread messages about the file fetch
81            // operation.
82            let (mut done_sender, done_receiver) = unbounded_channel();
83            *done_chan = Some((done_sender.clone(), done_receiver));
84
85            *response.body.lock() = ResponseBody::Receiving(vec![]);
86
87            context.filemanager.fetch_file_in_chunks(
88                &mut done_sender,
89                reader,
90                response.body.clone(),
91                context.cancellation_listener.clone(),
92                RelativePos::full_range(),
93            );
94
95            response
96        } else {
97            Response::network_error(NetworkError::ResourceLoadError(
98                "Opening file failed".to_owned(),
99            ))
100        };
101
102        Box::pin(std::future::ready(response))
103    }
104}
105
106impl ProtocolHandler for ResourceProtocolHandler {
107    fn load(
108        &self,
109        request: &mut Request,
110        done_chan: &mut DoneChannel,
111        context: &FetchContext,
112    ) -> Pin<Box<dyn Future<Output = Response> + Send>> {
113        let url = request.current_url();
114
115        // TODO: Check referrer.
116        //       We unexpectedly get `NoReferrer` for all requests from the newtab page.
117
118        Self::response_for_path(request, done_chan, context, url.path())
119    }
120}