Skip to main content

script/dom/window/
dissimilaroriginwindow.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#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use dom_struct::dom_struct;
8use js::context::JSContext;
9use js::jsapi::JSObject;
10use js::jsval::UndefinedValue;
11use js::rust::{CustomAutoRooterGuard, HandleValue, MutableHandleValue};
12use script_bindings::interfaces::HasOrigin;
13use servo_base::generic_channel;
14use servo_base::id::PipelineId;
15use servo_constellation_traits::{
16    RemoteFocusOperation, ScriptToConstellationMessage, StructuredSerializedData,
17};
18use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl};
19
20use crate::dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding;
21use crate::dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding::DissimilarOriginWindowMethods;
22use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowPostMessageOptions;
23use crate::dom::bindings::error::{Error, ErrorResult};
24use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
25use crate::dom::bindings::str::USVString;
26use crate::dom::bindings::structuredclone;
27use crate::dom::globalscope::GlobalScope;
28use crate::dom::location::Location;
29use crate::dom::windowproxy::WindowProxy;
30
31/// Represents a dissimilar-origin `Window` that exists in another script thread.
32///
33/// Since the `Window` is in a different script thread, we cannot access it
34/// directly, but some of its accessors (for example `window.parent`)
35/// still need to function.
36///
37/// In `windowproxy.rs`, we create a custom window proxy for these windows,
38/// that throws security exceptions for most accessors. This is not a replacement
39/// for XOWs, but provides belt-and-braces security.
40#[dom_struct]
41pub(crate) struct DissimilarOriginWindow {
42    /// The global for this window.
43    globalscope: GlobalScope,
44
45    /// The window proxy for this window.
46    window_proxy: Dom<WindowProxy>,
47
48    /// The location of this window, initialized lazily.
49    location: MutNullableDom<Location>,
50
51    #[no_trace]
52    pipeline_id: PipelineId,
53
54    #[no_trace]
55    origin: MutableOrigin,
56}
57
58impl DissimilarOriginWindow {
59    pub(crate) fn new(
60        cx: &mut js::context::JSContext,
61        global_to_clone_from: &GlobalScope,
62        window_proxy: &WindowProxy,
63    ) -> DomRoot<Self> {
64        // TODO: We do not know the origin of this new window at this point in the execution
65        // and we *really* don't want to use the origin of `global_to_clone_from`. The whole
66        // point is that this is a window with a *different* origin. Just use an opaque origin
67        // here which is guaranteed to never be equal to `global_to_clone_from`'s origin.
68        let opaque_origin = MutableOrigin::new(ImmutableOrigin::new_opaque());
69        let win = Box::new(Self {
70            globalscope: GlobalScope::new_inherited(
71                #[cfg(feature = "devtools")]
72                global_to_clone_from.devtools_chan().cloned(),
73                global_to_clone_from.mem_profiler_chan().clone(),
74                global_to_clone_from.time_profiler_chan().clone(),
75                global_to_clone_from.script_to_constellation_chan().sender,
76                global_to_clone_from.script_to_embedder_chan().clone(),
77                global_to_clone_from.resource_threads().clone(),
78                global_to_clone_from.storage_threads().clone(),
79                global_to_clone_from.creation_url(),
80                global_to_clone_from.top_level_creation_url(),
81                #[cfg(feature = "webgpu")]
82                global_to_clone_from.wgpu_id_hub(),
83                Some(global_to_clone_from.is_secure_context()),
84                global_to_clone_from
85                    .upgrade_insecure_navigations_set()
86                    .clone(),
87                false,
88            ),
89            window_proxy: Dom::from_ref(window_proxy),
90            location: Default::default(),
91            pipeline_id: PipelineId::new(),
92            origin: opaque_origin.clone(),
93        });
94        DissimilarOriginWindowBinding::Wrap::<crate::DomTypeHolder>(cx, &opaque_origin, win)
95    }
96
97    pub(crate) fn origin(&self) -> MutableOrigin {
98        self.origin.clone()
99    }
100
101    pub(crate) fn window_proxy(&self) -> DomRoot<WindowProxy> {
102        DomRoot::from_ref(&*self.window_proxy)
103    }
104
105    pub(crate) fn pipeline_id(&self) -> PipelineId {
106        self.pipeline_id
107    }
108}
109
110impl DissimilarOriginWindowMethods<crate::DomTypeHolder> for DissimilarOriginWindow {
111    /// <https://html.spec.whatwg.org/multipage/#dom-window>
112    fn Window(&self) -> DomRoot<WindowProxy> {
113        self.window_proxy()
114    }
115
116    /// <https://html.spec.whatwg.org/multipage/#dom-self>
117    fn Self_(&self) -> DomRoot<WindowProxy> {
118        self.window_proxy()
119    }
120
121    /// <https://html.spec.whatwg.org/multipage/#dom-frames>
122    fn Frames(&self) -> DomRoot<WindowProxy> {
123        self.window_proxy()
124    }
125
126    /// <https://html.spec.whatwg.org/multipage/#dom-parent>
127    fn GetParent(&self) -> Option<DomRoot<WindowProxy>> {
128        // Steps 1-3.
129        if self.window_proxy.is_browsing_context_discarded() {
130            return None;
131        }
132        // Step 4.
133        if let Some(parent) = self.window_proxy.parent() {
134            return Some(DomRoot::from_ref(parent));
135        }
136        // Step 5.
137        Some(DomRoot::from_ref(&*self.window_proxy))
138    }
139
140    /// <https://html.spec.whatwg.org/multipage/#dom-top>
141    fn GetTop(&self) -> Option<DomRoot<WindowProxy>> {
142        // Steps 1-3.
143        if self.window_proxy.is_browsing_context_discarded() {
144            return None;
145        }
146        // Steps 4-5.
147        Some(DomRoot::from_ref(self.window_proxy.top()))
148    }
149
150    /// <https://html.spec.whatwg.org/multipage/#dom-length>
151    fn Length(&self) -> u32 {
152        // First try to access the document directly if it is in the same event loop.
153        if let Some(document) = self.window_proxy.document() {
154            return document.iframes().active_iframe_count() as u32;
155        }
156
157        // Fall back to using messaging to get the count from another event loop.
158        let parent_browsing_context_id = self.window_proxy.browsing_context_id();
159        let (result_sender, result_receiver) = generic_channel::channel().unwrap();
160        let _ = self.globalscope.script_to_constellation_chan().send(
161            ScriptToConstellationMessage::GetChildBrowsingContextCount(
162                parent_browsing_context_id,
163                result_sender,
164            ),
165        );
166        result_receiver.recv().unwrap_or_default() as u32
167    }
168
169    /// <https://html.spec.whatwg.org/multipage/#dom-window-close>
170    fn Close(&self) {
171        // TODO: Implement x-origin close
172    }
173
174    /// <https://html.spec.whatwg.org/multipage/#dom-window-closed>
175    fn Closed(&self) -> bool {
176        // TODO: Implement x-origin close
177        false
178    }
179
180    /// <https://html.spec.whatwg.org/multipage/#dom-window-postmessage>
181    fn PostMessage(
182        &self,
183        cx: &mut JSContext,
184        message: HandleValue,
185        target_origin: USVString,
186        transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
187    ) -> ErrorResult {
188        self.post_message_impl(&target_origin, cx, message, transfer)
189    }
190
191    /// <https://html.spec.whatwg.org/multipage/#dom-window-postmessage-options>
192    fn PostMessage_(
193        &self,
194        cx: &mut JSContext,
195        message: HandleValue,
196        options: &WindowPostMessageOptions,
197    ) -> ErrorResult {
198        auto_root!(&in(cx) let transfer =
199            options
200                .parent
201                .transfer
202                .iter()
203                .map(|js| js.get())
204                .collect::<Vec<_>>());
205
206        self.post_message_impl(&options.targetOrigin, cx, message, transfer)
207    }
208
209    /// <https://html.spec.whatwg.org/multipage/#dom-opener>
210    fn Opener(&self, _: &mut JSContext, mut retval: MutableHandleValue) {
211        // TODO: Implement x-origin opener
212        retval.set(UndefinedValue());
213    }
214
215    /// <https://html.spec.whatwg.org/multipage/#dom-opener>
216    fn SetOpener(&self, _: &mut JSContext, _: HandleValue) {
217        // TODO: Implement x-origin opener
218    }
219
220    /// <https://html.spec.whatwg.org/multipage/#dom-window-blur>
221    fn Blur(&self) {
222        // > User agents are encouraged to ignore calls to this `blur()` method
223        // > entirely.
224    }
225
226    /// <https://html.spec.whatwg.org/multipage/#dom-window-focus>
227    fn Focus(&self) {
228        let browsing_context_id = self.window_proxy.browsing_context_id();
229        debug!("Initiating a focus operation for {browsing_context_id:?}");
230        let _ = self.globalscope.script_to_constellation_chan().send(
231            ScriptToConstellationMessage::FocusRemoteBrowsingContext(
232                browsing_context_id,
233                RemoteFocusOperation::Viewport,
234            ),
235        );
236    }
237
238    /// <https://html.spec.whatwg.org/multipage/#dom-location>
239    fn Location(&self, cx: &mut js::context::JSContext) -> DomRoot<Location> {
240        self.location
241            .or_init(|| Location::new_dissimilar_origin(cx, self))
242    }
243}
244
245impl DissimilarOriginWindow {
246    /// <https://html.spec.whatwg.org/multipage/#window-post-message-steps>
247    fn post_message_impl(
248        &self,
249        target_origin: &USVString,
250        cx: &mut JSContext,
251        message: HandleValue,
252        transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
253    ) -> ErrorResult {
254        // Step 6-7.
255        let data = structuredclone::write(cx, message, Some(transfer))?;
256
257        self.post_message(target_origin, data)
258    }
259
260    /// <https://html.spec.whatwg.org/multipage/#window-post-message-steps>
261    pub(crate) fn post_message(
262        &self,
263        target_origin: &USVString,
264        data: StructuredSerializedData,
265    ) -> ErrorResult {
266        // Step 1.
267        let target = self.window_proxy.browsing_context_id();
268        // Step 2.
269        let incumbent = match GlobalScope::incumbent() {
270            None => panic!("postMessage called with no incumbent global"),
271            Some(incumbent) => incumbent,
272        };
273
274        let source_origin = incumbent.origin().immutable().clone();
275
276        // Step 3-5.
277        let target_origin = match target_origin.0[..].as_ref() {
278            "*" => None,
279            "/" => Some(source_origin.clone()),
280            url => match ServoUrl::parse(url) {
281                Ok(url) => Some(url.origin()),
282                Err(_) => return Err(Error::Syntax(Some("Invalid target origin".into()))),
283            },
284        };
285        let msg = ScriptToConstellationMessage::PostMessage {
286            target,
287            source: incumbent.pipeline_id(),
288            source_origin,
289            target_origin,
290            data,
291        };
292        // Step 8
293        let _ = incumbent.script_to_constellation_chan().send(msg);
294        Ok(())
295    }
296}
297
298impl HasOrigin for DissimilarOriginWindow {
299    fn origin(&self) -> MutableOrigin {
300        DissimilarOriginWindow::origin(self)
301    }
302}