1use std::io::{Read, Seek, Write};
6
7use base::id::PipelineId;
8use crossbeam_channel::Sender;
9use cssparser::SourceLocation;
10use encoding_rs::UTF_8;
11use net_traits::mime_classifier::MimeClassifier;
12use net_traits::request::{CorsSettings, Destination, RequestId};
13use net_traits::{
14 FetchMetadata, FilteredMetadata, LoadContext, Metadata, NetworkError, ReferrerPolicy,
15 ResourceFetchTiming,
16};
17use servo_arc::Arc;
18use servo_config::pref;
19use servo_url::ServoUrl;
20use style::context::QuirksMode;
21use style::global_style_data::STYLE_THREAD_POOL;
22use style::media_queries::MediaList;
23use style::shared_lock::{Locked, SharedRwLock};
24use style::stylesheets::import_rule::{ImportLayer, ImportSheet, ImportSupportsCondition};
25use style::stylesheets::{
26 ImportRule, Origin, Stylesheet, StylesheetLoader as StyleStylesheetLoader, UrlExtraData,
27};
28use style::values::CssUrl;
29
30use crate::document_loader::LoadType;
31use crate::dom::bindings::inheritance::Castable;
32use crate::dom::bindings::refcounted::Trusted;
33use crate::dom::bindings::reflector::DomGlobal;
34use crate::dom::bindings::root::DomRoot;
35use crate::dom::csp::{GlobalCspReporting, Violation};
36use crate::dom::document::Document;
37use crate::dom::element::Element;
38use crate::dom::eventtarget::EventTarget;
39use crate::dom::globalscope::GlobalScope;
40use crate::dom::html::htmlelement::HTMLElement;
41use crate::dom::html::htmllinkelement::{HTMLLinkElement, RequestGenerationId};
42use crate::dom::node::NodeTraits;
43use crate::dom::performance::performanceresourcetiming::InitiatorType;
44use crate::dom::shadowroot::ShadowRoot;
45use crate::dom::window::CSSErrorReporter;
46use crate::fetch::{RequestWithGlobalScope, create_a_potential_cors_request};
47use crate::messaging::{CommonScriptMsg, MainThreadScriptMsg};
48use crate::network_listener::{self, FetchResponseListener, ResourceTimingListener};
49use crate::script_runtime::{CanGc, ScriptThreadEventCategory};
50use crate::task_source::TaskSourceName;
51use crate::unminify::{
52 BeautifyFileType, create_output_file, create_temp_files, execute_js_beautify,
53};
54
55pub(crate) trait StylesheetOwner {
56 fn parser_inserted(&self) -> bool;
59
60 fn potentially_render_blocking(&self) -> bool;
62
63 fn referrer_policy(&self) -> ReferrerPolicy;
65
66 fn increment_pending_loads_count(&self);
68
69 fn load_finished(&self, successful: bool) -> Option<bool>;
72
73 fn set_origin_clean(&self, origin_clean: bool);
75}
76
77pub(crate) enum StylesheetContextSource {
78 LinkElement,
79 Import(Arc<Locked<ImportRule>>),
80}
81
82struct StylesheetContext {
84 element: Trusted<HTMLElement>,
86 source: StylesheetContextSource,
87 media: Arc<Locked<MediaList>>,
88 url: ServoUrl,
89 metadata: Option<Metadata>,
90 data: Vec<u8>,
92 document: Trusted<Document>,
94 shadow_root: Option<Trusted<ShadowRoot>>,
95 origin_clean: bool,
96 request_generation_id: Option<RequestGenerationId>,
99 is_script_blocking: bool,
101 is_render_blocking: bool,
103}
104
105impl StylesheetContext {
106 fn unminify_css(&mut self, file_url: ServoUrl) {
107 let Some(unminified_dir) = self.document.root().window().unminified_css_dir() else {
108 return;
109 };
110
111 let mut style_content = std::mem::take(&mut self.data);
112 if let Some((input, mut output)) = create_temp_files() {
113 if execute_js_beautify(
114 input.path(),
115 output.try_clone().unwrap(),
116 BeautifyFileType::Css,
117 ) {
118 output.seek(std::io::SeekFrom::Start(0)).unwrap();
119 output.read_to_end(&mut style_content).unwrap();
120 }
121 }
122 match create_output_file(unminified_dir, &file_url, None) {
123 Ok(mut file) => {
124 file.write_all(&style_content).unwrap();
125 },
126 Err(why) => {
127 log::warn!("Could not store script {:?}", why);
128 },
129 }
130
131 self.data = style_content;
132 }
133
134 fn empty_stylesheet(&self, document: &Document) -> Arc<Stylesheet> {
135 let shared_lock = document.style_shared_lock().clone();
136 let quirks_mode = document.quirks_mode();
137
138 Arc::new(Stylesheet::from_bytes(
139 &[],
140 UrlExtraData(self.url.get_arc()),
141 None,
142 None,
143 Origin::Author,
144 self.media.clone(),
145 shared_lock,
146 None,
147 None,
148 quirks_mode,
149 ))
150 }
151
152 fn parse(
153 &self,
154 quirks_mode: QuirksMode,
155 shared_lock: SharedRwLock,
156 css_error_reporter: &CSSErrorReporter,
157 loader: ElementStylesheetLoader<'_>,
158 ) -> Arc<Stylesheet> {
159 let metadata = self
160 .metadata
161 .as_ref()
162 .expect("Should never call parse without metadata.");
163
164 let _span = profile_traits::trace_span!("ParseStylesheet").entered();
165 Arc::new(Stylesheet::from_bytes(
166 &self.data,
167 UrlExtraData(metadata.final_url.get_arc()),
168 metadata.charset.as_deref(),
169 Some(UTF_8),
175 Origin::Author,
176 self.media.clone(),
177 shared_lock,
178 Some(&loader),
179 Some(css_error_reporter),
180 quirks_mode,
181 ))
182 }
183
184 fn contributes_to_the_styling_processing_model(&self, element: &HTMLElement) -> bool {
185 if !element.upcast::<Element>().is_connected() {
186 return false;
187 }
188
189 if !matches!(&self.source, StylesheetContextSource::LinkElement) {
196 return true;
197 }
198 let link = element.downcast::<HTMLLinkElement>().unwrap();
199 self.request_generation_id
200 .is_none_or(|generation| generation == link.get_request_generation_id())
201 }
202
203 fn contributes_a_script_blocking_style_sheet(
205 &self,
206 element: &HTMLElement,
207 owner: &dyn StylesheetOwner,
208 document: &Document,
209 ) -> bool {
210 owner.parser_inserted()
212 && element.downcast::<HTMLLinkElement>().is_none_or(|link|
215 self.contributes_to_the_styling_processing_model(element)
216 && !link.is_effectively_disabled()
218 )
219 && element.media_attribute_matches_media_environment()
221 && *element.owner_document() == *document
223 }
228
229 fn decrement_load_and_render_blockers(&self, document: &Document) {
230 if self.is_script_blocking {
231 document.decrement_script_blocking_stylesheet_count();
232 }
233
234 if self.is_render_blocking {
235 document.decrement_render_blocking_element_count();
236 }
237 }
238
239 fn do_post_parse_tasks(self, success: bool, stylesheet: Arc<Stylesheet>) {
240 let element = self.element.root();
241 let document = self.document.root();
242 let owner = element
243 .upcast::<Element>()
244 .as_stylesheet_owner()
245 .expect("Stylesheet not loaded by <style> or <link> element!");
246
247 match &self.source {
248 StylesheetContextSource::LinkElement => {
250 let link = element
251 .downcast::<HTMLLinkElement>()
252 .expect("Should be HTMLinkElement due to StylesheetContextSource");
253 if link.is_effectively_disabled() {
257 stylesheet.set_disabled(true);
258 }
259 link.set_stylesheet(stylesheet);
266 },
267 StylesheetContextSource::Import(import_rule) => {
268 let window = element.owner_window();
270 let document_context = window.web_font_context();
271
272 document.load_web_fonts_from_stylesheet(&stylesheet, &document_context);
275
276 let mut guard = document.style_shared_lock().write();
277 import_rule.write_with(&mut guard).stylesheet = ImportSheet::Sheet(stylesheet);
278 },
279 }
280
281 if let Some(ref shadow_root) = self.shadow_root {
282 shadow_root.root().invalidate_stylesheets();
283 } else {
284 document.invalidate_stylesheets();
285 }
286 owner.set_origin_clean(self.origin_clean);
287
288 if let Some(any_failed) = owner.load_finished(success) {
295 let event = match any_failed {
298 true => atom!("error"),
299 false => atom!("load"),
300 };
301 element
302 .upcast::<EventTarget>()
303 .fire_event(event, CanGc::note());
304 }
305 self.decrement_load_and_render_blockers(&document);
311 document.finish_load(LoadType::Stylesheet(self.url), CanGc::note());
312 }
313}
314
315impl FetchResponseListener for StylesheetContext {
316 fn process_request_body(&mut self, _: RequestId) {}
317
318 fn process_request_eof(&mut self, _: RequestId) {}
319
320 fn process_response(&mut self, _: RequestId, metadata: Result<FetchMetadata, NetworkError>) {
321 if let Ok(FetchMetadata::Filtered {
322 filtered: FilteredMetadata::Opaque | FilteredMetadata::OpaqueRedirect(_),
323 ..
324 }) = metadata
325 {
326 self.origin_clean = false;
327 }
328
329 self.metadata = metadata.ok().map(|m| match m {
330 FetchMetadata::Unfiltered(m) => m,
331 FetchMetadata::Filtered { unsafe_, .. } => unsafe_,
332 });
333 }
334
335 fn process_response_chunk(&mut self, _: RequestId, mut payload: Vec<u8>) {
336 self.data.append(&mut payload);
337 }
338
339 fn process_response_eof(
340 mut self,
341 _: RequestId,
342 status: Result<(), NetworkError>,
343 timing: ResourceFetchTiming,
344 ) {
345 network_listener::submit_timing(&self, &status, &timing, CanGc::note());
346
347 let document = self.document.root();
348 let Some(metadata) = self.metadata.as_ref() else {
349 let empty_stylesheet = self.empty_stylesheet(&document);
350 self.do_post_parse_tasks(false, empty_stylesheet);
351 return;
352 };
353
354 let element = self.element.root();
355
356 if element.downcast::<HTMLLinkElement>().is_some() {
358 let is_css = MimeClassifier::is_css(
360 &metadata.resource_content_type_metadata(LoadContext::Style, &self.data),
361 ) || (
362 document.quirks_mode() == QuirksMode::Quirks &&
368 document.origin().immutable().clone() == metadata.final_url.origin()
369 );
370
371 if !is_css {
372 let empty_stylesheet = self.empty_stylesheet(&document);
373 self.do_post_parse_tasks(false, empty_stylesheet);
374 return;
375 }
376
377 if !self.contributes_to_the_styling_processing_model(&element) {
380 self.decrement_load_and_render_blockers(&document);
382 document.finish_load(LoadType::Stylesheet(self.url), CanGc::note());
383 return;
385 }
386 }
387
388 if metadata.status != http::StatusCode::OK {
389 let empty_stylesheet = self.empty_stylesheet(&document);
390 self.do_post_parse_tasks(false, empty_stylesheet);
391 return;
392 }
393
394 self.unminify_css(metadata.final_url.clone());
395
396 let loader = if pref!(dom_parallel_css_parsing_enabled) {
397 ElementStylesheetLoader::Asynchronous(AsynchronousStylesheetLoader::new(&element))
398 } else {
399 ElementStylesheetLoader::Synchronous { element: &element }
400 };
401 loader.parse(self, &element, &document);
402 }
403
404 fn process_csp_violations(&mut self, _request_id: RequestId, violations: Vec<Violation>) {
405 let global = &self.resource_timing_global();
406 global.report_csp_violations(violations, None, None);
407 }
408}
409
410impl ResourceTimingListener for StylesheetContext {
411 fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
412 let initiator_type = InitiatorType::LocalName(
413 self.element
414 .root()
415 .upcast::<Element>()
416 .local_name()
417 .to_string(),
418 );
419 (initiator_type, self.url.clone())
420 }
421
422 fn resource_timing_global(&self) -> DomRoot<GlobalScope> {
423 self.element.root().owner_document().global()
424 }
425}
426
427pub(crate) enum ElementStylesheetLoader<'a> {
428 Synchronous { element: &'a HTMLElement },
429 Asynchronous(AsynchronousStylesheetLoader),
430}
431
432impl<'a> ElementStylesheetLoader<'a> {
433 pub(crate) fn new(element: &'a HTMLElement) -> Self {
434 ElementStylesheetLoader::Synchronous { element }
435 }
436}
437
438impl ElementStylesheetLoader<'_> {
439 pub(crate) fn load(
440 &self,
441 source: StylesheetContextSource,
442 media: Arc<Locked<MediaList>>,
443 url: ServoUrl,
444 cors_setting: Option<CorsSettings>,
445 integrity_metadata: String,
446 ) {
447 match self {
448 ElementStylesheetLoader::Synchronous { element } => Self::load_with_element(
449 element,
450 source,
451 media,
452 url,
453 cors_setting,
454 integrity_metadata,
455 ),
456 ElementStylesheetLoader::Asynchronous { .. } => unreachable!(
457 "Should never call load directly on an asynchronous ElementStylesheetLoader"
458 ),
459 }
460 }
461
462 fn load_with_element(
463 element: &HTMLElement,
464 source: StylesheetContextSource,
465 media: Arc<Locked<MediaList>>,
466 url: ServoUrl,
467 cors_setting: Option<CorsSettings>,
468 integrity_metadata: String,
469 ) {
470 let document = element.owner_document();
471 let shadow_root = element
472 .containing_shadow_root()
473 .map(|sr| Trusted::new(&*sr));
474 let generation = element
475 .downcast::<HTMLLinkElement>()
476 .map(HTMLLinkElement::get_request_generation_id);
477 let mut context = StylesheetContext {
478 element: Trusted::new(element),
479 source,
480 media,
481 url: url.clone(),
482 metadata: None,
483 data: vec![],
484 document: Trusted::new(&*document),
485 shadow_root,
486 origin_clean: true,
487 request_generation_id: generation,
488 is_script_blocking: false,
489 is_render_blocking: false,
490 };
491
492 let owner = element
493 .upcast::<Element>()
494 .as_stylesheet_owner()
495 .expect("Stylesheet not loaded by <style> or <link> element!");
496 let referrer_policy = owner.referrer_policy();
497 owner.increment_pending_loads_count();
498
499 context.is_script_blocking =
504 context.contributes_a_script_blocking_style_sheet(element, owner, &document);
505 if context.is_script_blocking {
506 document.increment_script_blocking_stylesheet_count();
507 }
508
509 context.is_render_blocking = element.media_attribute_matches_media_environment() &&
512 owner.potentially_render_blocking();
513 if context.is_render_blocking {
514 document.increment_render_blocking_element_count();
515 }
516
517 let global = element.global();
519 let request = create_a_potential_cors_request(
520 Some(document.webview_id()),
521 url.clone(),
522 Destination::Style,
523 cors_setting,
524 None,
525 global.get_referrer(),
526 )
527 .with_global_scope(&global)
528 .referrer_policy(referrer_policy)
529 .integrity_metadata(integrity_metadata);
530
531 document.fetch(LoadType::Stylesheet(url), request, context);
532 }
533
534 fn parse(self, listener: StylesheetContext, element: &HTMLElement, document: &Document) {
535 let shared_lock = document.style_shared_lock().clone();
536 let quirks_mode = document.quirks_mode();
537 let window = element.owner_window();
538
539 match self {
540 ElementStylesheetLoader::Synchronous { .. } => {
541 let stylesheet =
542 listener.parse(quirks_mode, shared_lock, window.css_error_reporter(), self);
543 listener.do_post_parse_tasks(true, stylesheet);
544 },
545 ElementStylesheetLoader::Asynchronous(asynchronous_loader) => {
546 let css_error_reporter = window.css_error_reporter().clone();
547 let thread_pool = STYLE_THREAD_POOL.pool();
548 let thread_pool = thread_pool.as_ref().unwrap();
549
550 thread_pool.spawn(move || {
551 let pipeline_id = asynchronous_loader.pipeline_id;
552 let main_thread_sender = asynchronous_loader.main_thread_sender.clone();
553
554 let loader = ElementStylesheetLoader::Asynchronous(asynchronous_loader);
555 let stylesheet =
556 listener.parse(quirks_mode, shared_lock, &css_error_reporter, loader);
557
558 let task = task!(finish_parsing_of_stylesheet_on_main_thread: move || {
559 listener.do_post_parse_tasks(true, stylesheet);
560 });
561
562 let _ = main_thread_sender.send(MainThreadScriptMsg::Common(
563 CommonScriptMsg::Task(
564 ScriptThreadEventCategory::StylesheetLoad,
565 Box::new(task),
566 Some(pipeline_id),
567 TaskSourceName::Networking,
568 ),
569 ));
570 });
571 },
572 };
573 }
574}
575
576impl StyleStylesheetLoader for ElementStylesheetLoader<'_> {
577 fn request_stylesheet(
580 &self,
581 url: CssUrl,
582 source_location: SourceLocation,
583 lock: &SharedRwLock,
584 media: Arc<Locked<MediaList>>,
585 supports: Option<ImportSupportsCondition>,
586 layer: ImportLayer,
587 ) -> Arc<Locked<ImportRule>> {
588 if supports.as_ref().is_some_and(|s| !s.enabled) {
590 return Arc::new(lock.wrap(ImportRule {
591 url,
592 stylesheet: ImportSheet::new_refused(),
593 supports,
594 layer,
595 source_location,
596 }));
597 }
598
599 let resolved_url = match url.url().cloned() {
600 Some(url) => url,
601 None => {
602 return Arc::new(lock.wrap(ImportRule {
603 url,
604 stylesheet: ImportSheet::new_refused(),
605 supports,
606 layer,
607 source_location,
608 }));
609 },
610 };
611
612 let import_rule = Arc::new(lock.wrap(ImportRule {
613 url,
614 stylesheet: ImportSheet::new_pending(),
615 supports,
616 layer,
617 source_location,
618 }));
619
620 let source = StylesheetContextSource::Import(import_rule.clone());
623
624 match self {
625 ElementStylesheetLoader::Synchronous { element } => {
626 Self::load_with_element(
627 element,
628 source,
629 media,
630 resolved_url.into(),
631 None,
632 "".to_owned(),
633 );
634 },
635 ElementStylesheetLoader::Asynchronous(AsynchronousStylesheetLoader {
636 element,
637 main_thread_sender,
638 pipeline_id,
639 }) => {
640 let element = element.clone();
641 let task = task!(load_import_stylesheet_on_main_thread: move || {
642 Self::load_with_element(
643 &element.root(),
644 source,
645 media,
646 resolved_url.into(),
647 None,
648 "".to_owned()
649 );
650 });
651 let _ =
652 main_thread_sender.send(MainThreadScriptMsg::Common(CommonScriptMsg::Task(
653 ScriptThreadEventCategory::StylesheetLoad,
654 Box::new(task),
655 Some(*pipeline_id),
656 TaskSourceName::Networking,
657 )));
658 },
659 }
660
661 import_rule
662 }
663}
664
665pub(crate) struct AsynchronousStylesheetLoader {
666 element: Trusted<HTMLElement>,
667 main_thread_sender: Sender<MainThreadScriptMsg>,
668 pipeline_id: PipelineId,
669}
670
671impl AsynchronousStylesheetLoader {
672 pub(crate) fn new(element: &HTMLElement) -> Self {
673 let window = element.owner_window();
674 Self {
675 element: Trusted::new(element),
676 main_thread_sender: window.main_thread_script_chan().clone(),
677 pipeline_id: window.pipeline_id(),
678 }
679 }
680}