Skip to main content

script/dom/document/
favicon.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::sync::Arc;
6
7use bytes::Bytes;
8use embedder_traits::{Image as EmbedderImage, PixelFormat as EmbedderPixelFormat};
9use js::context::JSContext;
10use net_traits::blob_url_store::UrlWithBlobClaim;
11use net_traits::image_cache::{
12    Image, ImageCache, ImageCacheResponseCallback, ImageCacheResult, ImageLoadListener,
13    ImageOrMetadataAvailable, ImageResponse, PendingImageId, RasterizationResult,
14};
15use net_traits::request::{Destination, RequestId};
16use net_traits::{FetchMetadata, FetchResponseMsg, NetworkError, ResourceFetchTiming};
17use pixels::PixelFormat;
18use servo_base::generic_channel::GenericSharedMemory;
19use servo_url::ServoUrl;
20use webrender_api::units::DeviceIntSize;
21
22use crate::dom::bindings::refcounted::Trusted;
23use crate::dom::csp::{GlobalCspReporting, Violation};
24use crate::dom::document::Document;
25use crate::dom::globalscope::GlobalScope;
26use crate::dom::node::NodeTraits;
27use crate::dom::performance::performanceresourcetiming::InitiatorType;
28use crate::fetch::fetch::create_a_potential_cors_request_with_claim;
29use crate::fetch::network_listener::{
30    FetchResponseListener, ResourceTimingListener, submit_timing,
31};
32
33pub(crate) struct FaviconFetchContext {
34    /// A handle to the image cache for the [`Document`] of this context.
35    pub(crate) image_cache: Arc<dyn ImageCache>,
36    /// The [`PendingImageId`] of the favicon we are fetching.
37    pub(crate) id: PendingImageId,
38    /// The URL of the favicon that this context is fetching.
39    pub(crate) url: ServoUrl,
40    /// Whether or not the load of this favicon was successful (received a 2xx status code).
41    pub(crate) successful: bool,
42    /// Whether this is a fallback fetch for `/favicon.ico` rather than an explicit `<link rel="icon">`.
43    pub(crate) is_fallback: bool,
44}
45
46impl FaviconFetchContext {
47    pub(crate) fn new(
48        image_cache: Arc<dyn ImageCache>,
49        id: PendingImageId,
50        url: ServoUrl,
51        is_fallback: bool,
52    ) -> Self {
53        Self {
54            image_cache,
55            id,
56            url,
57            successful: true,
58            is_fallback,
59        }
60    }
61}
62
63impl FetchResponseListener for FaviconFetchContext {
64    fn process_request_body(&mut self, _: &GlobalScope, _: RequestId) {}
65
66    fn process_response(
67        &mut self,
68        _: &mut JSContext,
69        _: &GlobalScope,
70        request_id: RequestId,
71        metadata: Result<FetchMetadata, NetworkError>,
72    ) {
73        if let Ok(ref metadata) = metadata &&
74            !metadata.metadata().status.is_success()
75        {
76            self.successful = false;
77        }
78
79        self.image_cache.notify_pending_response(
80            self.id,
81            FetchResponseMsg::ProcessResponse(request_id, metadata),
82        );
83    }
84
85    fn process_response_chunk(
86        &mut self,
87        _: &mut JSContext,
88        _: &GlobalScope,
89        request_id: RequestId,
90        chunk: Bytes,
91    ) {
92        self.image_cache.notify_pending_response(
93            self.id,
94            FetchResponseMsg::ProcessResponseChunk(request_id, chunk),
95        );
96    }
97
98    fn process_response_eof(
99        self,
100        cx: &mut JSContext,
101        global: &GlobalScope,
102        request_id: RequestId,
103        response: Result<(), NetworkError>,
104        timing: ResourceFetchTiming,
105    ) {
106        let response = if !self.successful {
107            Err(NetworkError::HttpError("Not an OK response".into()))
108        } else {
109            response
110        };
111        self.image_cache.notify_pending_response(
112            self.id,
113            FetchResponseMsg::ProcessResponseEOF(request_id, response.clone(), timing.clone()),
114        );
115        if !self.is_fallback {
116            submit_timing(cx, global, &self, &response, &timing);
117        }
118    }
119
120    fn process_csp_violations(
121        &mut self,
122        cx: &mut JSContext,
123        global: &GlobalScope,
124        _request_id: RequestId,
125        violations: Vec<Violation>,
126    ) {
127        if !self.is_fallback {
128            global.report_csp_violations(cx, violations, None, None);
129        }
130    }
131
132    fn process_content_length(&mut self, request_id: RequestId, size: usize) {
133        self.image_cache.notify_pending_response(
134            self.id,
135            FetchResponseMsg::ProcessContentLength(request_id, size),
136        );
137    }
138}
139
140impl ResourceTimingListener for FaviconFetchContext {
141    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
142        (InitiatorType::LocalName("link".into()), self.url.clone())
143    }
144}
145
146impl Document {
147    /// Rasterizes a loaded favicon file if necessary and notifies the embedder about it.
148    pub(crate) fn process_favicon_image(&self, image: Image, is_fallback: bool) {
149        // If an icon link has been added in the meantime or a favicon is already present,
150        // do not apply the fallback icon.
151        if is_fallback && (self.ever_had_favicon_link() || self.favicon().is_some()) {
152            return;
153        }
154
155        // TODO: Include the size attribute here
156        let window = self.window();
157
158        let send_rasterized_favicon_to_embedder = |raster_image: &pixels::RasterImage| {
159            // Let's not worry about animated favicons...
160            let frame = raster_image.first_frame();
161
162            let format = match raster_image.format {
163                PixelFormat::K8 => EmbedderPixelFormat::K8,
164                PixelFormat::KA8 => EmbedderPixelFormat::KA8,
165                PixelFormat::RGB8 => EmbedderPixelFormat::RGB8,
166                PixelFormat::RGBA8 => EmbedderPixelFormat::RGBA8,
167                PixelFormat::BGRA8 => EmbedderPixelFormat::BGRA8,
168            };
169
170            let embedder_image = EmbedderImage::new(
171                frame.width,
172                frame.height,
173                Arc::new(GenericSharedMemory::from_arc_vec(
174                    raster_image.bytes.clone(),
175                )),
176                raster_image.frames[0].byte_range.clone(),
177                format,
178            );
179            self.set_favicon(embedder_image);
180        };
181
182        match image {
183            Image::Raster(raster_image) => send_rasterized_favicon_to_embedder(&raster_image),
184            Image::Vector(vector_image) => {
185                // This size is completely arbitrary.
186                let size = DeviceIntSize::new(250, 250);
187
188                let image_cache = window.image_cache();
189                match image_cache.rasterize_vector_image(vector_image.id, size, None) {
190                    RasterizationResult::Image(raster_image) => {
191                        send_rasterized_favicon_to_embedder(&raster_image);
192                    },
193                    RasterizationResult::PendingRasterization => {
194                        // The rasterization callback will end up calling "process_favicon_image" again,
195                        // but this time with a raster image.
196                        let image_cache_sender = self
197                            .register_favicon_image_cache_callback(vector_image.id, is_fallback);
198                        image_cache.add_rasterization_complete_listener(
199                            window.pipeline_id(),
200                            vector_image.id,
201                            size,
202                            image_cache_sender,
203                        );
204                    },
205                    RasterizationResult::InvalidSvgParameters => {},
206                }
207            },
208        }
209    }
210
211    fn register_favicon_image_cache_callback(
212        &self,
213        id: PendingImageId,
214        is_fallback: bool,
215    ) -> ImageCacheResponseCallback {
216        let trusted_doc = Trusted::new(self);
217        let window = self.window();
218        window.register_image_cache_listener(id, move |response, _| {
219            let trusted_doc = trusted_doc.clone();
220            let document = trusted_doc.root();
221            let window = document.window();
222
223            let ImageResponse::Loaded(image, _) = response.response else {
224                return;
225            };
226
227            window
228                .as_global_scope()
229                .task_manager()
230                .networking_task_source()
231                .queue(task!(process_favicon_response: move || {
232                    let document = trusted_doc.root();
233                    document.process_favicon_image(image, is_fallback);
234                }));
235        })
236    }
237
238    /// Fetches `/favicon.ico` from the document's URL as a fallback when no
239    /// `<link rel="icon">` was found in the page.
240    ///
241    /// From <https://html.spec.whatwg.org/multipage/#rel-icon>:
242    ///
243    /// > In the absence of a link with the icon keyword, for Document objects whose URL's scheme is
244    /// > an HTTP(S) scheme, user agents may instead run these steps:
245    /// > 1. Let request be a new request whose URL is the URL record obtained by resolving the URL
246    /// >    "/favicon.ico" against the Document object's URL, client is the Document object's relevant
247    /// >    settings object, destination is "image", credentials mode is "include", and whose
248    /// >    use-URL-credentials flag is set.
249    /// > 2. Fetch request, with processResponse set to the following steps given response response:
250    /// >    - 2.1. Use response's unsafe response as an icon as if it had been declared using the icon
251    /// >      keyword.
252    pub(crate) fn maybe_fetch_fallback_favicon(&self) {
253        if !self.window().is_top_level() {
254            return;
255        }
256        if self.ever_had_favicon_link() {
257            return;
258        }
259        if self.favicon().is_some() {
260            return;
261        }
262        let document_url = self.url();
263        if !matches!(document_url.scheme(), "http" | "https") {
264            return;
265        }
266
267        let Ok(favicon_url) = document_url.join("/favicon.ico") else {
268            return;
269        };
270
271        let window = self.window();
272        let image_cache = window.image_cache();
273        let cache_result = image_cache.get_cached_image_status(
274            favicon_url.clone(),
275            window.origin().immutable(),
276            None,
277        );
278
279        match cache_result {
280            ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
281                image, ..
282            }) => {
283                self.process_favicon_image(image, true);
284            },
285            ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(_, id)) |
286            ImageCacheResult::Pending(id) => {
287                let sender = self.register_favicon_image_cache_callback(id, true);
288                image_cache.add_listener(ImageLoadListener::new(sender, window.pipeline_id(), id));
289            },
290            ImageCacheResult::ReadyForRequest(id) => {
291                let referrer = self.owner_global().get_referrer();
292                let request = create_a_potential_cors_request_with_claim(
293                    Some(self.webview_id()),
294                    UrlWithBlobClaim::from_url_without_having_claimed_blob(favicon_url.clone()),
295                    Destination::Image,
296                    None,
297                    None,
298                    referrer,
299                )
300                .policy_container((*self.policy_container()).clone())
301                .origin(window.origin().immutable().to_owned())
302                .pipeline_id(Some(window.pipeline_id()))
303                .synchronous(true);
304
305                let sender = self.register_favicon_image_cache_callback(id, true);
306                image_cache.add_listener(ImageLoadListener::new(sender, window.pipeline_id(), id));
307
308                let fetch_context = FaviconFetchContext::new(image_cache, id, favicon_url, true);
309                self.fetch_favicon(request, fetch_context);
310            },
311            ImageCacheResult::FailedToLoadOrDecode => {},
312        };
313    }
314}