1use std::cell::Cell;
10use std::rc::Rc;
11
12use content_security_policy::sandboxing_directive::SandboxingFlagSet;
13use crossbeam_channel::Sender;
14use embedder_traits::user_contents::UserContentManagerId;
15use embedder_traits::{ViewportDetails, WebDriverLoadStatus};
16use http::header;
17use js::context::JSContext;
18use net_traits::blob_url_store::UrlWithBlobClaim;
19use net_traits::request::{
20 CredentialsMode, InsecureRequestsPolicy, Origin, PreloadedResources, RedirectMode,
21 RequestBuilder, RequestClient, RequestMode,
22};
23use net_traits::response::ResponseInit;
24use net_traits::{
25 BoxedFetchCallback, CoreResourceThread, DOCUMENT_ACCEPT_HEADER_VALUE, FetchResponseMsg,
26 Metadata, ReferrerPolicy, fetch_async, set_default_accept_language,
27};
28use script_bindings::inheritance::Castable;
29use script_traits::{DocumentActivity, NewPipelineInfo, WebViewState};
30use servo_base::cross_process_instant::CrossProcessInstant;
31use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
32use servo_constellation_traits::{
33 LoadData, LoadOrigin, NavigationHistoryBehavior, ScriptToConstellationMessage,
34 TargetSnapshotParams,
35};
36use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
37use url::Position;
38
39use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods;
40use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
41use crate::dom::bindings::refcounted::Trusted;
42use crate::dom::document::AbortReason;
43use crate::dom::element::Element;
44use crate::dom::html::htmliframeelement::HTMLIFrameElement;
45use crate::dom::node::node::NodeTraits;
46use crate::dom::window::Window;
47use crate::dom::windowproxy::WindowProxy;
48use crate::event_loop::script_thread::ScriptThread;
49use crate::fetch::fetch::FetchCanceller;
50use crate::messaging::MainThreadScriptMsg;
51
52#[derive(Clone)]
53pub struct NavigationListener {
54 request_builder: RequestBuilder,
55 main_thread_sender: Sender<MainThreadScriptMsg>,
56 send_results_to_main_thread: Cell<bool>,
59}
60
61impl NavigationListener {
62 pub(crate) fn into_callback(self) -> BoxedFetchCallback {
63 Box::new(move |response_msg| self.notify_fetch(response_msg))
64 }
65
66 pub fn new(
67 request_builder: RequestBuilder,
68 main_thread_sender: Sender<MainThreadScriptMsg>,
69 ) -> NavigationListener {
70 NavigationListener {
71 request_builder,
72 main_thread_sender,
73 send_results_to_main_thread: Cell::new(true),
74 }
75 }
76
77 pub fn initiate_fetch(
78 self,
79 core_resource_thread: &CoreResourceThread,
80 response_init: Option<ResponseInit>,
81 ) {
82 fetch_async(
83 core_resource_thread,
84 self.request_builder.clone(),
85 response_init,
86 self.into_callback(),
87 );
88 }
89
90 fn notify_fetch(&self, message: FetchResponseMsg) {
91 if !self.send_results_to_main_thread.get() {
94 return;
95 }
96
97 if Self::http_redirect_metadata(&message).is_some() {
99 self.send_results_to_main_thread.set(false);
100 }
101
102 let pipeline_id = self
103 .request_builder
104 .pipeline_id
105 .expect("Navigation should always have an associated Pipeline");
106 let result = self
107 .main_thread_sender
108 .send(MainThreadScriptMsg::NavigationResponse {
109 pipeline_id,
110 message: Box::new(message),
111 });
112
113 if let Err(error) = result {
114 warn!(
115 "Failed to send network message to pipeline {:?}: {error:?}",
116 pipeline_id
117 );
118 }
119 }
120
121 pub(crate) fn http_redirect_metadata(message: &FetchResponseMsg) -> Option<&Metadata> {
122 let FetchResponseMsg::ProcessResponse(_, Ok(metadata)) = message else {
123 return None;
124 };
125
126 let metadata = metadata.metadata();
128 if !matches!(
129 metadata.location_url,
130 Some(Ok(ref location_url)) if matches!(location_url.scheme(), "http" | "https")
131 ) {
132 return None;
133 }
134
135 Some(metadata)
136 }
137}
138
139#[derive(JSTraceable)]
144pub(crate) struct InProgressLoad {
145 #[no_trace]
147 pub(crate) pipeline_id: PipelineId,
148 #[no_trace]
150 pub(crate) browsing_context_id: BrowsingContextId,
151 #[no_trace]
153 pub(crate) webview_state: Rc<WebViewState>,
154 #[no_trace]
156 pub(crate) parent_info: Option<PipelineId>,
157 #[no_trace]
159 pub(crate) opener: Option<BrowsingContextId>,
160 #[no_trace]
162 pub(crate) viewport_details: ViewportDetails,
163 #[no_trace]
165 pub(crate) activity: DocumentActivity,
166 pub(crate) throttled: bool,
168 #[no_trace]
170 pub(crate) navigation_start: CrossProcessInstant,
171 pub(crate) canceller: FetchCanceller,
173 #[no_trace]
175 pub(crate) load_data: LoadData,
176 #[no_trace]
179 pub(crate) url_list: Vec<ServoUrl>,
180 #[no_trace]
181 pub(crate) user_content_manager_id: Option<UserContentManagerId>,
183 #[no_trace]
185 pub(crate) target_snapshot_params: TargetSnapshotParams,
186 pub(crate) frame_name: Option<String>,
188}
189
190impl InProgressLoad {
191 pub(crate) fn new(
193 new_pipeline_info: NewPipelineInfo,
194 webview_state: Rc<WebViewState>,
195 ) -> InProgressLoad {
196 let url = new_pipeline_info.load_data.url.clone();
197
198 InProgressLoad {
199 pipeline_id: new_pipeline_info.new_pipeline_id,
200 browsing_context_id: new_pipeline_info.browsing_context_id,
201 webview_state,
202 parent_info: new_pipeline_info.parent_info,
203 opener: new_pipeline_info.opener,
204 viewport_details: new_pipeline_info.viewport_details,
205 activity: DocumentActivity::FullyActive,
206 throttled: false,
207 navigation_start: CrossProcessInstant::now(),
208 canceller: Default::default(),
209 load_data: new_pipeline_info.load_data,
210 url_list: vec![url],
211 user_content_manager_id: new_pipeline_info.user_content_manager_id,
212 target_snapshot_params: new_pipeline_info.target_snapshot_params,
213 frame_name: new_pipeline_info.frame_name,
214 }
215 }
216
217 pub(crate) fn webview_id(&self) -> WebViewId {
218 self.webview_state.id
219 }
220
221 pub(crate) fn request_builder(&mut self) -> RequestBuilder {
222 let client_origin = match self.load_data.load_origin {
223 LoadOrigin::Script(ref initiator_origin) => initiator_origin.immutable().clone(),
224 _ => ImmutableOrigin::new_opaque(),
225 };
226
227 let id = self.pipeline_id;
228 let webview_id = self.webview_state.id;
229
230 let insecure_requests_policy = self
231 .load_data
232 .inherited_insecure_requests_policy
233 .unwrap_or(InsecureRequestsPolicy::DoNotUpgrade);
234
235 let request_client = RequestClient {
236 preloaded_resources: PreloadedResources::default(),
237 policy_container: self.load_data.policy_container.clone().unwrap_or_default(),
238 origin: Origin::Origin(client_origin),
239 is_nested_browsing_context: self.parent_info.is_some(),
240 insecure_requests_policy,
241 has_trustworthy_ancestor_origin: self.load_data.has_trustworthy_ancestor_origin,
242 };
243
244 let mut request_builder = RequestBuilder::new(
245 Some(webview_id),
246 UrlWithBlobClaim::from_url_without_having_claimed_blob(self.load_data.url.clone()),
247 self.load_data.referrer.clone(),
248 )
249 .method(self.load_data.method.clone())
250 .destination(self.load_data.destination)
251 .mode(RequestMode::Navigate)
252 .credentials_mode(CredentialsMode::Include)
253 .use_url_credentials(true)
254 .pipeline_id(Some(id))
255 .referrer_policy(self.load_data.referrer_policy)
256 .policy_container(self.load_data.policy_container.clone().unwrap_or_default())
257 .headers(self.load_data.headers.clone())
258 .body(self.load_data.data.clone())
259 .redirect_mode(RedirectMode::Manual)
260 .crash(self.load_data.crash.clone())
261 .client(request_client)
262 .url_list(self.url_list.clone());
263
264 request_builder.reload_navigation = self.load_data.reload_navigation;
265 request_builder.history_navigation = self.load_data.history_navigation;
266
267 if !request_builder.headers.contains_key(header::ACCEPT) {
268 request_builder
269 .headers
270 .insert(header::ACCEPT, DOCUMENT_ACCEPT_HEADER_VALUE);
271 }
272 set_default_accept_language(&mut request_builder.headers);
273
274 request_builder
275 }
276}
277
278pub(crate) fn determine_the_origin(
280 url: Option<&ServoUrl>,
281 sandbox_flags: SandboxingFlagSet,
282 source_origin: Option<MutableOrigin>,
283) -> MutableOrigin {
284 let is_sandboxed =
286 sandbox_flags.contains(SandboxingFlagSet::SANDBOXED_ORIGIN_BROWSING_CONTEXT_FLAG);
287 if is_sandboxed {
288 return MutableOrigin::new(ImmutableOrigin::new_opaque());
289 }
290
291 let Some(url) = url else {
293 return MutableOrigin::new(ImmutableOrigin::new_opaque());
294 };
295
296 if url.as_str() == "about:srcdoc" {
298 let source_origin =
300 source_origin.expect("Can't have a null source origin for about:srcdoc");
301 return source_origin;
303 }
304
305 if url.as_str() == "about:blank" &&
307 let Some(source_origin) = source_origin
308 {
309 return source_origin;
310 }
311
312 MutableOrigin::new(url.origin())
314}
315
316fn navigate_to_fragment(
318 cx: &mut JSContext,
319 window: &Window,
320 url: &ServoUrl,
321 history_handling: NavigationHistoryBehavior,
322) {
323 let doc = window.Document();
324 window.send_to_constellation(ScriptToConstellationMessage::NavigatedToFragment(
347 url.clone(),
348 history_handling,
349 ));
350 let old_url = doc.url();
352 doc.set_url(url.clone());
353 doc.update_document_for_history_step_application(&old_url, url);
356 let Some(fragment) = url.fragment() else {
358 unreachable!("Must always have a fragment");
359 };
360 doc.scroll_to_the_fragment(cx, fragment);
361 }
366
367pub(crate) fn navigate(
369 cx: &mut JSContext,
370 window: &Window,
371 history_handling: NavigationHistoryBehavior,
372 force_reload: bool,
373 mut load_data: LoadData,
374) {
375 let document = window.Document();
376
377 if force_reload {
379 load_data.reload_navigation = true;
381 }
382
383 let initiator_origin_snapshot = &load_data.load_origin;
385
386 let pipeline_id = window.pipeline_id();
391 let window_proxy = window.window_proxy();
392 if let Some(active) = window_proxy.currently_active() &&
393 pipeline_id == active &&
394 document.is_prompting_or_unloading()
395 {
396 return;
397 }
398
399 let history_handling = if history_handling == NavigationHistoryBehavior::Auto {
401 if let LoadOrigin::Script(initiator_origin) = initiator_origin_snapshot {
408 if load_data.url == document.url() && initiator_origin.same_origin(&*document.origin())
409 {
410 NavigationHistoryBehavior::Replace
411 } else {
412 NavigationHistoryBehavior::Push
414 }
415 } else {
416 NavigationHistoryBehavior::Push
418 }
419 } else {
420 history_handling
421 };
422
423 let history_handling =
428 if load_data.url.scheme() == "javascript" || document.is_initial_about_blank() {
429 NavigationHistoryBehavior::Replace
430 } else {
431 history_handling
432 };
433
434 if !force_reload
438 && load_data.url.as_url()[..Position::AfterQuery] ==
440 document.url().as_url()[..Position::AfterQuery]
441 && load_data.url.fragment().is_some()
443 {
444 let webdriver_sender = window.webdriver_load_status_sender();
447 if let Some(ref sender) = webdriver_sender {
448 let _ = sender.send(WebDriverLoadStatus::NavigationStart);
449 }
450 navigate_to_fragment(cx, window, &load_data.url, history_handling);
451 if let Some(sender) = webdriver_sender {
453 let _ = sender.send(WebDriverLoadStatus::NavigationStop);
454 }
455 return;
456 }
457
458 let window_proxy = window.window_proxy();
460 if window_proxy.parent().is_some() {
461 window_proxy.start_delaying_load_events_mode();
462 }
463
464 let target_snapshot_params = snapshot_target_snapshot_params(&window_proxy);
467
468 if let Some(sender) = window.webdriver_load_status_sender() {
473 let _ = sender.send(WebDriverLoadStatus::NavigationStart);
474 }
475
476 if load_data.url.scheme() == "javascript" {
483 let Some(initiator_pipeline_id) = load_data.creator_pipeline_id else {
489 unreachable!("javascript: URL navigations must have a creator pipeline");
490 };
491 let Some(initiator_window) = ScriptThread::find_window(initiator_pipeline_id) else {
492 warn!("Can't find global for navigation initiator");
493 return;
494 };
495
496 let target_window = Trusted::new(window);
497 let mut load_data = load_data;
498 let initiator_window = Trusted::new(&*initiator_window);
499 let task = task!(navigate_javascript: move |cx| {
500 let target_window = target_window.root();
502 let initiator_window = initiator_window.root();
503 if ScriptThread::navigate_to_javascript_url(cx, initiator_window.upcast(), target_window.upcast(), &mut load_data, None, None) {
504 target_window
505 .as_global_scope()
506 .script_to_constellation_chan()
507 .send(ScriptToConstellationMessage::LoadUrl(load_data, history_handling, target_snapshot_params))
508 .unwrap();
509 } else {
510 let window_proxy = target_window.window_proxy();
514 if window_proxy.parent().is_some() {
515 window_proxy.stop_delaying_load_events_mode();
516 }
517 }
518 });
519 window
520 .as_global_scope()
521 .task_manager()
522 .navigation_and_traversal_task_source()
523 .queue(task);
524 return;
526 }
527
528 let unload_prompt_canceled = document.check_if_unloading_is_cancelled(cx, false);
539 if !unload_prompt_canceled {
544 return;
550 }
551
552 let trusted_document = Trusted::new(&*document);
556 window
557 .task_manager()
558 .navigation_and_traversal_task_source()
559 .queue(task!(abort_a_document_and_its_descendants: move |cx| {
560 trusted_document.root().abort_a_document_and_its_descendants(cx, AbortReason::Navigate);
561 }));
562
563 window.send_to_constellation(ScriptToConstellationMessage::LoadUrl(
568 load_data,
569 history_handling,
570 target_snapshot_params,
571 ));
572}
573
574pub(crate) fn determine_creation_sandboxing_flags(
576 browsing_context: Option<&WindowProxy>,
577 element: Option<&Element>,
578) -> SandboxingFlagSet {
579 match element {
583 None => browsing_context
586 .and_then(|browsing_context| browsing_context.document())
587 .map(|document| document.active_sandboxing_flag_set())
588 .unwrap_or(SandboxingFlagSet::empty()),
589 Some(element) => {
590 element
595 .downcast::<HTMLIFrameElement>()
596 .map(|iframe| iframe.sandboxing_flag_set())
597 .unwrap_or(SandboxingFlagSet::empty())
598 .union(element.owner_document().active_sandboxing_flag_set())
599 },
600 }
601}
602
603pub(crate) fn determine_iframe_element_referrer_policy(
605 element: Option<&Element>,
606) -> ReferrerPolicy {
607 element
610 .and_then(|element| element.downcast::<HTMLIFrameElement>())
611 .map(|iframe| {
612 let token = iframe.ReferrerPolicy();
613 ReferrerPolicy::from(&*token.str())
614 })
615 .unwrap_or(ReferrerPolicy::EmptyString)
617}
618
619pub(crate) fn snapshot_target_snapshot_params(navigable: &WindowProxy) -> TargetSnapshotParams {
621 let container = navigable.frame_element();
623 let sandboxing_flags = determine_creation_sandboxing_flags(Some(navigable), container);
626 let iframe_element_referrer_policy = determine_iframe_element_referrer_policy(container);
629 TargetSnapshotParams {
630 sandboxing_flags,
631 iframe_element_referrer_policy,
632 }
633}