embedder_traits/resources.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::path::PathBuf;
6use std::sync::LazyLock;
7
8use bytes::Bytes;
9#[doc(hidden)]
10pub use inventory as _inventory;
11use malloc_size_of::MallocSizeOf;
12use serde::{Deserialize, Serialize};
13
14/// A static reference to a ResourceReader
15///
16/// If you need to initialize the resource reader at runtime, use interior mutability.
17///
18/// # Examples
19///
20/// ```
21/// pub(crate) struct ResourceReaderImpl {
22/// resource_dir: OnceLock<PathBuf>,
23/// }
24/// static RESOURCE_READER: ResourceReaderImpl = ResourceReaderImpl {
25/// resource_dir: OnceLock::new(),
26/// };
27///
28/// servo::submit_resource_reader!(&RESOURCE_READER);
29///
30/// /// This can be called during initialization, e.g. after parsing commandline flags.
31/// pub(crate) fn set_resource_dir(resource_dir: PathBuf) {
32/// RESOURCE_READER.resource_dir.set(resource_dir).expect("Already initialized.")
33/// }
34/// impl ResourceReaderMethods for ResourceReaderImpl {
35/// //
36/// }
37/// ```
38pub type ResourceReader = &'static (dyn ResourceReaderMethods + Sync + Send);
39
40/// Register the [`ResourceReader`] implementation.
41///
42/// This should be added at most once in the whole project.
43/// In particular this means you should make sure to disable the (default)
44/// `baked-in-resources` feature of servo if you want to override the default reader.
45///
46/// # Examples
47///
48/// Put `submit_resource_reader` invocations **outside** any function body:
49/// ```
50/// servo_embedder_traits::submit_resource_reader!(my_resource_reader);
51/// ```
52#[macro_export]
53macro_rules! submit_resource_reader {
54 ($resource_reader:expr) => {
55 $crate::resources::_inventory::submit! {
56 $resource_reader as $crate::resources::ResourceReader
57 }
58 };
59}
60
61// The embedder may register a resource reader via `submit_resource_reader!()`
62// Note: A weak symbol would perhaps be preferable, but that isn't available in stable rust yet.
63inventory::collect!(ResourceReader);
64
65static RESOURCE_READER: LazyLock<ResourceReader> = {
66 LazyLock::new(|| {
67 let mut resource_reader_iterator = inventory::iter::<ResourceReader>.into_iter();
68 let Some(resource_reader) = resource_reader_iterator.next() else {
69 panic!("No resource reader registered");
70 };
71 if resource_reader_iterator.next().is_some() {
72 log::error!(
73 "Multiple resource readers registered. Taking the first implementation \
74 (random, non deterministic order). This is a bug! Check usages of \
75 `submit_resource_reader!()`. Perhaps you meant to disable the default resource reader \
76 (selected by depending on the `servo-default-resources` crate) ?"
77 );
78 }
79 *resource_reader
80 })
81};
82
83pub fn read_bytes(res: Resource) -> ResourceBytes {
84 RESOURCE_READER.read(res)
85}
86
87/// Consider using [`read_bytes`] with `str::from_utf8` if you can use a `&str`.
88pub fn read_string(res: Resource) -> String {
89 String::from_utf8(read_bytes(res).into_vec()).unwrap()
90}
91
92pub fn sandbox_access_files() -> Vec<PathBuf> {
93 RESOURCE_READER.sandbox_access_files()
94}
95
96pub fn sandbox_access_files_dirs() -> Vec<PathBuf> {
97 RESOURCE_READER.sandbox_access_files_dirs()
98}
99
100pub enum Resource {
101 /// A list of GATT services that are blocked from being used by web bluetooth.
102 /// The format of the file is a list of UUIDs, one per line, with an optional second word to specify the
103 /// type of blocklist.
104 /// It can be empty but then all GATT services will be allowed.
105 BluetoothBlocklist,
106 /// A list of domain names that are considered public suffixes, typically obtained from <https://publicsuffix.org/list/>.
107 /// The Public Suffix List is a cross-vendor initiative to provide an accurate list of domain name suffixes
108 /// that are under the control of a registry. This is used to prevent cookies from being set for top-level
109 /// domains that are not controlled by the same entity as the website.
110 /// It can be empty but all domain names will be considered not public suffixes.
111 DomainList,
112 /// A preloaded list of HTTP Strict Transport Security. It can be an empty list and
113 /// `HstsList::default()` will be called.
114 HstsPreloadList,
115 /// A HTML page to display when `net_traits::NetworkError::SslValidation` network error is
116 /// reported.
117 /// The page contains placeholder `${reason}` for the error code and `${bytes}` for the certificate bytes,
118 /// and also `${secret}` for the privileged secret.
119 /// It can be empty but then nothing will be displayed when a certificate error occurs.
120 BadCertHTML,
121 /// A HTML page to display when any network error occurs that is not related to SSL validation.
122 /// The message can contain a placeholder `${reason}` for the error code.
123 /// It can be empty but then nothing will be displayed when an internal error occurs.
124 NetErrorHTML,
125 /// A placeholder image to display if we couldn't get the requested image.
126 ///
127 /// ## Panic
128 ///
129 /// If the resource is not provided, servo will fallback to a baked in default (See resources/rippy.png).
130 /// However, if the image is provided but invalid, Servo will crash.
131 BrokenImageIcon,
132 /// A placeholder HTML page to display when the code responsible for rendering a page panics and the original
133 /// page can no longer be displayed.
134 /// The message can contain a placeholder `${details}` for the error details.
135 /// It can be empty but then nothing will be displayed when a crash occurs.
136 CrashHTML,
137 /// A HTML page to display when a directory listing is requested.
138 /// The page contains a js function `setData` that will then be used to build the list of directory.
139 /// It can be empty but then nothing will be displayed when a directory listing is requested.
140 DirectoryListingHTML,
141 /// A HTML page that is used for the about:memory url.
142 AboutMemoryHTML,
143 /// RPC script for the Debugger API on behalf of devtools.
144 DebuggerJS,
145 /// A HTML page to display a pretty printed view of a json document.
146 JsonViewerHTML,
147}
148
149impl Resource {
150 pub fn filename(&self) -> &'static str {
151 match self {
152 Resource::BluetoothBlocklist => "gatt_blocklist.txt",
153 Resource::DomainList => "public_domains.txt",
154 Resource::HstsPreloadList => "hsts_preload.fstmap",
155 Resource::BadCertHTML => "badcert.html",
156 Resource::NetErrorHTML => "neterror.html",
157 Resource::BrokenImageIcon => "rippy.png",
158 Resource::CrashHTML => "crash.html",
159 Resource::DirectoryListingHTML => "directory-listing.html",
160 Resource::AboutMemoryHTML => "about-memory.html",
161 Resource::DebuggerJS => "debugger.js",
162 Resource::JsonViewerHTML => "json-viewer.html",
163 }
164 }
165}
166
167/// Struct for efficiently referencing bytes from [`ResourceReaderMethods`].
168/// Can be treated as `&[u8]`.
169#[derive(Clone, Debug, Deserialize, Serialize)]
170pub struct ResourceBytes {
171 bytes: Bytes,
172}
173
174impl AsRef<[u8]> for ResourceBytes {
175 fn as_ref(&self) -> &[u8] {
176 &self.bytes
177 }
178}
179
180impl MallocSizeOf for ResourceBytes {
181 fn size_of(&self, ops: &mut malloc_size_of::MallocSizeOfOps) -> usize {
182 self.bytes.size_of(ops)
183 }
184}
185
186impl ResourceBytes {
187 /// Construct from static. Does not allocate.
188 pub fn from_static(bytes: &'static [u8]) -> Self {
189 ResourceBytes {
190 bytes: Bytes::from_static(bytes),
191 }
192 }
193
194 /// Construct from vec. Takes the allocation
195 pub fn from_vec(bytes: Vec<u8>) -> Self {
196 ResourceBytes {
197 bytes: bytes.into(),
198 }
199 }
200
201 /// Construct from owner. Useful for mmap'ed files or similar. Takes the owner.
202 pub fn from_owner<T: AsRef<[u8]> + Send + Sync + 'static>(owner: T) -> Self {
203 ResourceBytes {
204 bytes: Bytes::from_owner(owner),
205 }
206 }
207
208 /// Returns the constructed bytes. This might involve a copy
209 pub fn into_vec(self) -> Vec<u8> {
210 self.bytes.into()
211 }
212}
213
214pub trait ResourceReaderMethods {
215 /// Read a named [`Resource`].
216 ///
217 /// The implementation must be functional in all Servo processes.
218 fn read(&self, res: Resource) -> ResourceBytes;
219 /// Files that should remain accessible after sandboxing the content process.
220 ///
221 /// If the resources are shipped as files, then the files should be listed here,
222 /// or the parent directory in [sandbox_access_files_dirs].
223 fn sandbox_access_files(&self) -> Vec<PathBuf>;
224 /// Directories that should remain accessible after sandboxing the content process.
225 ///
226 /// If resources are shipped as files, then the directory containing them be listed
227 /// here to ensure the content process can access the files.
228 fn sandbox_access_files_dirs(&self) -> Vec<PathBuf>;
229}