use std::cell::Cell;
use std::ptr::{self, NonNull};
use std::rc::Rc;
use content_security_policy::sandboxing_directive::SandboxingFlagSet;
use dom_struct::dom_struct;
use html5ever::local_name;
use indexmap::map::IndexMap;
use itertools::Either;
use js::JSCLASS_IS_GLOBAL;
use js::context::JSContext;
use js::gc::{HandleId, HandleObject, HandleValue, MutableHandleObject};
use js::glue::{
CreateWrapperProxyHandler, DeleteWrapperProxyHandler, GetProxyPrivate, GetProxyReservedSlot,
ProxyTraps, SetProxyReservedSlot,
};
use js::jsapi::{
GCContext, Handle as RawHandle, HandleId as RawHandleId, HandleObject as RawHandleObject,
HandleValue as RawHandleValue, JS_DefinePropertyById, JS_DeletePropertyById,
JS_ForwardSetPropertyTo, JSContext as RawJSContext, JSErrNum, JSITER_HIDDEN, JSITER_OWNONLY,
JSITER_SYMBOLS, JSObject, JSPROP_ENUMERATE, JSPROP_READONLY, JSTracer,
MutableHandle as RawMutableHandle, MutableHandleIdVector as RawMutableHandleIdVector,
MutableHandleObject as RawMutableHandleObject, MutableHandleValue as RawMutableHandleValue,
ObjectOpResult, PropertyDescriptor, jsid,
};
use js::jsval::{NullValue, PrivateValue, UndefinedValue};
use js::realm::{AutoRealm, CurrentRealm};
use js::rust::wrappers2::{
AppendToIdVector, JS_ForwardGetPropertyTo, JS_HasOwnPropertyById, JS_HasPropertyById,
JS_TransplantObject, NewWindowProxy, SetWindowProxy, int_to_jsid,
};
use js::rust::{Handle, MutableHandle, MutableHandleValue, get_object_class};
use js::typedarray::JSObjectStorage;
use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
use net_traits::ReferrerPolicy;
use net_traits::request::Referrer;
use script_bindings::cell::DomRefCell;
use script_bindings::codegen::GenericBindings::DissimilarOriginWindowBinding::{
self, DissimilarOriginWindowMethods,
};
use script_bindings::codegen::GenericBindings::HTMLIFrameElementBinding::HTMLIFrameElementMethods;
use script_bindings::codegen::GenericBindings::WindowBinding::{
self, GetProtoObject, WindowMethods,
};
use script_bindings::conversions::jsid_to_string;
use script_bindings::domstring::TracedDOMString;
use script_bindings::js::{GetPropertyKeys, JS_GetOwnPropertyDescriptorById};
use script_bindings::proxyhandler::{
self, CROSS_ORIGIN_PROPERTY_HOLDER_WEAK_MAP_SLOT, CrossOriginProperties,
cross_origin_get_own_property_helper, cross_origin_own_property_keys,
cross_origin_property_fallback, cross_origin_set, is_extensible,
is_platform_object_same_origin, maybe_cross_origin_get_prototype,
maybe_cross_origin_set_prototype_rawcx, prevent_extensions, report_cross_origin_denial,
set_property_descriptor,
};
use script_bindings::reflector::{DomObject, MutDomObject, Reflector};
use script_traits::{NewPipelineInfo, WebViewState};
use serde::{Deserialize, Serialize};
use servo_base::generic_channel;
use servo_base::generic_channel::GenericSend;
use servo_base::id::{BrowsingContextId, PipelineId, WebViewId};
use servo_constellation_traits::{
AuxiliaryWebViewCreationRequest, LoadData, LoadOrigin, NavigationHistoryBehavior,
ScriptToConstellationMessage, TargetSnapshotParams,
};
use servo_url::{ImmutableOrigin, OriginSnapshot, ServoUrl};
use storage_traits::webstorage_thread::WebStorageThreadMsg;
use style::attr::parse_integer;
use crate::DomTypeHolder;
use crate::dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject};
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::DomGlobal;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::settings_stack::maybe_entry_global;
use crate::dom::bindings::str::{DOMString, USVString};
use crate::dom::bindings::trace::JSTraceable;
use crate::dom::bindings::utils::get_array_index_from_id;
use crate::dom::dissimilaroriginwindow::DissimilarOriginWindow;
use crate::dom::document::Document;
use crate::dom::element::Element;
use crate::dom::globalscope::GlobalScope;
use crate::dom::node::node::NodeTraits;
use crate::dom::window::Window;
use crate::event_loop::script_thread::{ScriptThread, with_script_thread};
use crate::event_loop::script_window_proxies::ScriptWindowProxies;
use crate::navigation::navigate;
#[dom_struct]
pub(crate) struct WindowProxy {
reflector: Reflector,
#[no_trace]
browsing_context_id: BrowsingContextId,
#[no_trace]
opener: Option<BrowsingContextId>,
#[no_trace]
webview_id: WebViewId,
name: DomRefCell<TracedDOMString>,
#[no_trace]
currently_active: Cell<Option<PipelineId>>,
discarded: Cell<bool>,
disowned: Cell<bool>,
is_closing: Cell<bool>,
frame_element: Option<Dom<Element>>,
parent: Option<Dom<WindowProxy>>,
delaying_load_events_mode: Cell<bool>,
#[no_trace]
creator_url: Option<ServoUrl>,
#[no_trace]
creator_origin: Option<ImmutableOrigin>,
#[conditional_malloc_size_of]
script_window_proxies: Rc<ScriptWindowProxies>,
}
impl WindowProxy {
fn new_inherited(
browsing_context_id: BrowsingContextId,
webview_id: WebViewId,
currently_active: Option<PipelineId>,
frame_element: Option<&Element>,
parent: Option<&WindowProxy>,
opener: Option<BrowsingContextId>,
creator: CreatorBrowsingContextInfo,
) -> WindowProxy {
let name = frame_element.map_or(DOMString::new(), |e| {
e.get_string_attribute(&local_name!("name"))
});
WindowProxy {
reflector: Reflector::new(),
browsing_context_id,
webview_id,
name: DomRefCell::new(name.traced()),
currently_active: Cell::new(currently_active),
discarded: Cell::new(false),
disowned: Cell::new(false),
is_closing: Cell::new(false),
frame_element: frame_element.map(Dom::from_ref),
parent: parent.map(Dom::from_ref),
delaying_load_events_mode: Cell::new(false),
opener,
creator_url: creator.url,
creator_origin: creator.origin,
script_window_proxies: ScriptThread::window_proxies(),
}
}
#[expect(unsafe_code)]
#[expect(clippy::too_many_arguments)]
pub(crate) fn new(
cx: &mut JSContext,
window: &Window,
browsing_context_id: BrowsingContextId,
webview_id: WebViewId,
frame_element: Option<&Element>,
parent: Option<&WindowProxy>,
opener: Option<BrowsingContextId>,
creator: CreatorBrowsingContextInfo,
) -> DomRoot<WindowProxy> {
unsafe {
let handler = window.windowproxy_handler();
let window_jsobject = window.reflector().get_jsobject();
assert!(!window_jsobject.get().is_null());
assert_ne!(
((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL),
0
);
let mut realm = AutoRealm::new_from_handle(cx, window_jsobject);
let cx = &mut realm;
rooted!(&in(cx) let js_proxy = handler.new_window_proxy(cx, window_jsobject));
assert!(!js_proxy.is_null());
let current = Some(window.upcast::<GlobalScope>().pipeline_id());
let window_proxy = Box::new(WindowProxy::new_inherited(
browsing_context_id,
webview_id,
current,
frame_element,
parent,
opener,
creator,
));
SetProxyReservedSlot(
js_proxy.get(),
0,
&PrivateValue(&raw const (*window_proxy) as *const libc::c_void),
);
SetWindowProxy(cx, window_jsobject, js_proxy.handle());
debug!(
"Initializing reflector of {:p} to {:p}.",
window_proxy,
js_proxy.get()
);
window_proxy
.reflector
.init_reflector::<WindowProxy>(js_proxy.get());
DomRoot::from_ref(&*Box::into_raw(window_proxy))
}
}
#[expect(unsafe_code)]
pub(crate) fn new_dissimilar_origin(
cx: &mut JSContext,
global_to_clone_from: &GlobalScope,
browsing_context_id: BrowsingContextId,
webview_id: WebViewId,
parent: Option<&WindowProxy>,
opener: Option<BrowsingContextId>,
creator: CreatorBrowsingContextInfo,
) -> DomRoot<WindowProxy> {
unsafe {
let window_proxy = Box::new(WindowProxy::new_inherited(
browsing_context_id,
webview_id,
None,
None,
parent,
opener,
creator,
));
let window = DissimilarOriginWindow::new(cx, global_to_clone_from, &window_proxy);
let window_jsobject = window.reflector().get_jsobject();
assert!(!window_jsobject.get().is_null());
assert_ne!(
((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL),
0
);
let mut realm = AutoRealm::new_from_handle(cx, window_jsobject);
let cx = &mut realm;
let handler = WindowProxyHandler::proxy_handler();
rooted!(&in(cx) let js_proxy = handler.new_window_proxy(cx, window_jsobject));
assert!(!js_proxy.is_null());
SetProxyReservedSlot(
js_proxy.get(),
0,
&PrivateValue(&raw const (*window_proxy) as *const libc::c_void),
);
SetWindowProxy(cx, window_jsobject, js_proxy.handle());
debug!(
"Initializing reflector of {:p} to {:p}.",
window_proxy,
js_proxy.get()
);
window_proxy
.reflector
.init_reflector::<WindowProxy>(js_proxy.get());
DomRoot::from_ref(&*Box::into_raw(window_proxy))
}
}
fn create_auxiliary_browsing_context(
&self,
cx: &mut JSContext,
name: DOMString,
noopener: bool,
) -> Option<DomRoot<WindowProxy>> {
let (response_sender, response_receiver) = generic_channel::channel().unwrap();
let window = self
.currently_active
.get()
.and_then(ScriptThread::find_document)
.map(|doc| DomRoot::from_ref(doc.window()))
.unwrap();
let document = self
.currently_active
.get()
.and_then(ScriptThread::find_document)
.expect("A WindowProxy creating an auxiliary to have an active document");
let sandboxing_flag_set = document.active_sandboxing_flag_set();
let propagate_sandbox = sandboxing_flag_set
.contains(SandboxingFlagSet::SANDBOX_PROPOGATES_TO_AUXILIARY_BROWSING_CONTEXTS_FLAG);
let sandboxing_flag_set = if propagate_sandbox {
sandboxing_flag_set
} else {
SandboxingFlagSet::empty()
};
let blank_url = ServoUrl::parse("about:blank").ok().unwrap();
let mut load_data = LoadData::new(
LoadOrigin::Script(document.origin().snapshot()),
blank_url,
Some(document.base_url()),
Some(window.pipeline_id()),
document.global().get_referrer(),
document.get_referrer_policy(),
None, None,
false,
sandboxing_flag_set,
);
load_data.is_initial_about_blank = true;
let load_info = AuxiliaryWebViewCreationRequest {
load_data: load_data.clone(),
opener_webview_id: window.webview_id(),
opener_pipeline_id: self.currently_active.get().unwrap(),
response_sender,
};
let constellation_msg = ScriptToConstellationMessage::CreateAuxiliaryWebView(load_info);
window.send_to_constellation(constellation_msg);
let response = response_receiver.recv().unwrap()?;
let new_browsing_context_id = BrowsingContextId::from(response.new_webview_id);
let new_pipeline_info = NewPipelineInfo {
webview_state: WebViewState {
id: response.new_webview_id,
theme: Cell::new(window.webview_theme()),
has_system_focus: Cell::new(true),
},
parent_info: None,
new_pipeline_id: response.new_pipeline_id,
browsing_context_id: new_browsing_context_id,
opener: Some(self.browsing_context_id),
load_data,
viewport_details: window.viewport_details(),
user_content_manager_id: response.user_content_manager_id,
target_snapshot_params: TargetSnapshotParams {
sandboxing_flags: sandboxing_flag_set,
iframe_element_referrer_policy: ReferrerPolicy::EmptyString,
},
frame_name: None,
};
with_script_thread(|script_thread| {
script_thread.spawn_pipeline(cx, new_pipeline_info);
});
let new_window_proxy = ScriptThread::find_document(response.new_pipeline_id)
.and_then(|doc| doc.browsing_context())?;
if !name.eq_ignore_ascii_case("_blank") {
new_window_proxy.set_name(name);
}
if noopener {
new_window_proxy.disown();
} else {
let (sender, receiver) = generic_channel::channel().unwrap();
let msg = WebStorageThreadMsg::Clone {
sender,
src: window.window_proxy().webview_id(),
dest: response.new_webview_id,
};
GenericSend::send(document.global().storage_threads(), msg).unwrap();
receiver.recv().unwrap();
}
Some(new_window_proxy)
}
pub(crate) fn start_delaying_load_events_mode(&self) {
self.delaying_load_events_mode.set(true);
}
pub(crate) fn stop_delaying_load_events_mode(&self) {
self.delaying_load_events_mode.set(false);
}
pub(crate) fn disown(&self) {
self.disowned.set(true);
}
pub(crate) fn close(&self) {
self.is_closing.set(true);
}
pub(crate) fn is_closing(&self) -> bool {
self.is_closing.get()
}
pub(crate) fn opener(&self, cx: &mut CurrentRealm, mut retval: MutableHandleValue) {
if self.disowned.get() {
return retval.set(NullValue());
}
let opener_id = match self.opener {
Some(opener_browsing_context_id) => opener_browsing_context_id,
None => return retval.set(NullValue()),
};
let parent_browsing_context = self.parent.as_deref();
let opener_proxy = match self.script_window_proxies.find_window_proxy(opener_id) {
Some(window_proxy) => window_proxy,
None => {
let sender_pipeline_id = self.currently_active().unwrap();
match ScriptThread::get_top_level_for_browsing_context(
self.webview_id(),
sender_pipeline_id,
opener_id,
) {
Some(opener_top_id) => {
let global_to_clone_from = GlobalScope::from_current_realm(cx);
let creator =
CreatorBrowsingContextInfo::from(parent_browsing_context, None);
WindowProxy::new_dissimilar_origin(
cx,
&global_to_clone_from,
opener_id,
opener_top_id,
None,
None,
creator,
)
},
None => return retval.set(NullValue()),
}
},
};
if opener_proxy.is_browsing_context_discarded() {
return retval.set(NullValue());
}
opener_proxy.to_jsval(cx, retval);
}
pub(crate) fn open(
&self,
cx: &mut JSContext,
url: USVString,
target: DOMString,
features: DOMString,
) -> Fallible<Option<DomRoot<WindowProxy>>> {
if self.discarded.get() {
return Ok(None);
}
let source_document = maybe_entry_global()
.map(|global| global.as_window().Document())
.or_else(|| self.document())
.expect("Must have an entry global or active document");
let url_record = if !url.is_empty() {
let Ok(url) = source_document.encoding_parse_a_url(&url) else {
return Err(Error::Syntax(Some(format!(
"Error parsing URL '{url}' relative to '{}'",
source_document.url()
))));
};
Some(url)
} else {
None
};
let non_empty_target = if target.is_empty() {
DOMString::from_static("_blank")
} else {
target
};
let tokenized_features = tokenize_open_features(features);
let noreferrer = parse_open_feature_boolean(&tokenized_features, "noreferrer");
let noopener = if noreferrer {
true
} else {
parse_open_feature_boolean(&tokenized_features, "noopener")
};
let (chosen, new) = match self.choose_a_navigable(cx, non_empty_target, noopener) {
(Some(chosen), new) => (chosen, new),
(None, _) => return Ok(None),
};
let target_document = match chosen.document() {
Some(target_document) => target_document,
None => return Ok(None),
};
let has_trustworthy_ancestor_origin = if new {
target_document.has_trustworthy_ancestor_or_current_origin()
} else {
false
};
let target_window = target_document.window();
let url_record = url_record.unwrap_or(ServoUrl::parse("about:blank").unwrap());
if !url_record.matches_about_blank() {
let referrer = if noreferrer {
Referrer::NoReferrer
} else {
target_window.as_global_scope().get_referrer()
};
let csp_list = source_document.get_csp_list().clone();
target_document.set_csp_list(csp_list);
let mut load_data = LoadData::new(
LoadOrigin::Script(source_document.origin().snapshot()),
url_record,
target_document.about_base_url(),
Some(target_window.pipeline_id()),
referrer,
target_document.get_referrer_policy(),
Some(target_window.as_global_scope().is_secure_context()),
Some(target_document.insecure_requests_policy()),
has_trustworthy_ancestor_origin,
target_document.creation_sandboxing_flag_set_considering_parent_iframe(),
);
if load_data.url.scheme() == "javascript" {
let existing_global = source_document.global();
if !ScriptThread::can_navigate_to_javascript_url(
cx,
&existing_global,
target_window.as_global_scope(),
&mut load_data,
None,
) {
return Ok(target_document.browsing_context());
}
}
let history_handling = if new {
NavigationHistoryBehavior::Replace
} else {
NavigationHistoryBehavior::Push
};
navigate(cx, target_window, history_handling, false, load_data);
}
if noopener {
return Ok(None);
}
Ok(target_document.browsing_context())
}
pub(crate) fn choose_a_navigable(
&self,
cx: &mut JSContext,
name: DOMString,
noopener: bool,
) -> (Option<DomRoot<WindowProxy>>, bool) {
let sandboxing_flag_set = self
.document()
.map(|document| document.active_sandboxing_flag_set())
.unwrap_or_default();
let chosen = if name.is_empty() || name.eq_ignore_ascii_case("_self") {
Some((Some(DomRoot::from_ref(self)), false))
} else if name.eq_ignore_ascii_case("_parent") {
Some(
self.parent()
.map(|parent| (Some(DomRoot::from_ref(parent)), false))
.unwrap_or_else(|| (Some(DomRoot::from_ref(self)), false)),
)
} else if name.eq_ignore_ascii_case("_top") {
Some((Some(DomRoot::from_ref(self.top())), false))
} else if !name.eq_ignore_ascii_case("_blank") {
self.find_navigable_by_target_name(&name)
.map(|proxy| (Some(proxy), false))
} else {
None
};
if let Some(chosen) = chosen {
return chosen;
}
if sandboxing_flag_set
.contains(SandboxingFlagSet::SANDBOXED_AUXILIARY_NAVIGATION_BROWSING_CONTEXT_FLAG)
{
(None, false)
}
else {
(
self.create_auxiliary_browsing_context(cx, name, noopener),
true,
)
}
}
fn find_navigable_by_target_name(&self, name: &DOMString) -> Option<DomRoot<WindowProxy>> {
let top = self.top();
let subtrees_to_search = if top != self {
Either::Left([self, top])
} else {
Either::Right([self])
};
for subtree_to_search in subtrees_to_search.into_iter() {
if let Some(result) =
subtree_to_search.find_navigable_by_target_name_in_descendants(name)
{
return Some(result);
}
}
let mut top_level_window_proxies = self.script_window_proxies.top_level_window_proxies();
top_level_window_proxies
.sort_by_key(|proxy| std::cmp::Reverse(proxy.browsing_context_id()));
for window_proxy in top_level_window_proxies {
if &*window_proxy == top {
continue;
}
if let Some(result) = window_proxy.find_navigable_by_target_name_in_descendants(name) {
return Some(result);
}
}
None
}
fn find_navigable_by_target_name_in_descendants(
&self,
name: &DOMString,
) -> Option<DomRoot<WindowProxy>> {
if self.is_browsing_context_discarded() {
return None;
}
if self.get_name() == *name {
return Some(DomRoot::from_ref(self));
}
let document = self.document()?;
let iframes: Vec<_> = document.iframes().iter().collect();
iframes.iter().find_map(|iframe| {
iframe
.browsing_context_id()
.and_then(|browsing_context_id| {
self.script_window_proxies
.find_window_proxy(browsing_context_id)?
.find_navigable_by_target_name_in_descendants(name)
})
})
}
pub(crate) fn is_auxiliary(&self) -> bool {
self.opener.is_some()
}
pub(crate) fn discard_browsing_context(&self) {
self.discarded.set(true);
}
pub(crate) fn is_browsing_context_discarded(&self) -> bool {
self.discarded.get()
}
pub(crate) fn browsing_context_id(&self) -> BrowsingContextId {
self.browsing_context_id
}
pub(crate) fn webview_id(&self) -> WebViewId {
self.webview_id
}
pub(crate) fn frame_element(&self) -> Option<&Element> {
if self.is_browsing_context_discarded() {
return None;
}
self.frame_element.as_deref()
}
pub(crate) fn document(&self) -> Option<DomRoot<Document>> {
self.currently_active
.get()
.and_then(ScriptThread::find_document)
}
pub(crate) fn parent(&self) -> Option<&WindowProxy> {
self.parent.as_deref()
}
pub(crate) fn top(&self) -> &WindowProxy {
let mut result = self;
while let Some(parent) = result.parent() {
result = parent;
}
result
}
pub(crate) fn document_origin_and_internal_ancestor_origin_objects_list(
&self,
) -> Option<(OriginSnapshot, Vec<ImmutableOrigin>)> {
let pipeline_id = self.currently_active()?;
let (result_sender, result_receiver) = generic_channel::channel().unwrap();
self.global()
.script_to_constellation_chan()
.send(ScriptToConstellationMessage::GetDocumentOriginDetails(
pipeline_id,
result_sender,
))
.ok()?;
result_receiver.recv().ok()?
}
pub(crate) fn parent_origin_and_internal_ancestor_origin_objects_list(
&self,
) -> Option<(OriginSnapshot, Vec<ImmutableOrigin>)> {
if let Some(frame_element) = self.frame_element() {
let parent_document = frame_element.owner_document();
if !parent_document.is_fully_active() {
return None;
}
Some((
parent_document.origin().snapshot(),
parent_document
.internal_ancestor_origin_objects_list()
.clone()
.expect("Must always be fully active"),
))
} else if let Some(parent_proxy) = self.parent() {
assert!(parent_proxy.currently_active().is_some());
parent_proxy.document_origin_and_internal_ancestor_origin_objects_list()
} else {
None
}
}
#[expect(unsafe_code)]
fn set_window(&self, cx: &mut JSContext, window: &GlobalScope) {
unsafe {
debug!("Setting window of {:p}.", self);
let window_jsobject = window.reflector().get_jsobject();
let old_js_proxy = self.reflector.get_jsobject();
assert!(!window_jsobject.get().is_null());
assert_ne!(
((*get_object_class(window_jsobject.get())).flags & JSCLASS_IS_GLOBAL),
0
);
let mut realm = AutoRealm::new_from_handle(cx, window_jsobject);
let cx = &mut realm;
SetProxyReservedSlot(old_js_proxy.get(), 0, &PrivateValue(ptr::null_mut()));
SetProxyReservedSlot(
old_js_proxy.get(),
CROSS_ORIGIN_PROPERTY_HOLDER_WEAK_MAP_SLOT,
&UndefinedValue(),
);
rooted!(&in(cx) let new_js_proxy = WindowProxyHandler::proxy_handler().new_window_proxy(cx, window_jsobject));
SetProxyReservedSlot(new_js_proxy.get(), 0, &PrivateValue(ptr::null_mut()));
debug!(
"Transplanting proxy from {:p} to {:p}.",
old_js_proxy.get(),
new_js_proxy.get()
);
rooted!(&in(cx) let new_js_proxy = JS_TransplantObject(cx, old_js_proxy, new_js_proxy.handle()));
debug!("Transplanted proxy is {:p}.", new_js_proxy.get());
SetProxyReservedSlot(
new_js_proxy.get(),
0,
&PrivateValue(self as *const _ as *const libc::c_void),
);
SetWindowProxy(cx, window_jsobject, new_js_proxy.handle());
debug!(
"Setting reflector of {:p} to {:p}.",
self,
new_js_proxy.get()
);
self.reflector.rootable().set(new_js_proxy.get());
}
}
pub(crate) fn set_pipeline_id(&self, pipeline_id: PipelineId) {
self.currently_active.set(Some(pipeline_id));
}
pub(crate) fn set_currently_active(&self, cx: &mut JSContext, window: &Window) {
if let Some(pipeline_id) = self.currently_active() &&
pipeline_id == window.pipeline_id()
{
return debug!(
"Attempt to set the currently active window to the currently active window."
);
}
let global_scope = window.as_global_scope();
self.set_window(cx, global_scope);
self.currently_active.set(Some(global_scope.pipeline_id()));
}
pub(crate) fn unset_currently_active(&self, cx: &mut JSContext) {
if self.currently_active().is_none() {
return debug!(
"Attempt to unset the currently active window on a windowproxy that does not have one."
);
}
let globalscope = self.global();
let window = DissimilarOriginWindow::new(cx, &globalscope, self);
self.set_window(cx, window.upcast());
self.currently_active.set(None);
}
pub(crate) fn currently_active(&self) -> Option<PipelineId> {
self.currently_active.get()
}
pub(crate) fn get_name(&self) -> DOMString {
self.name.borrow().clone().root()
}
pub(crate) fn set_name(&self, name: DOMString) {
*self.name.borrow_mut() = name.traced();
}
}
#[derive(Debug, Deserialize, Serialize)]
pub(crate) struct CreatorBrowsingContextInfo {
url: Option<ServoUrl>,
origin: Option<ImmutableOrigin>,
}
impl CreatorBrowsingContextInfo {
pub(crate) fn from(
parent: Option<&WindowProxy>,
opener: Option<&WindowProxy>,
) -> CreatorBrowsingContextInfo {
let creator = match (parent, opener) {
(Some(parent), _) => parent.document(),
(None, Some(opener)) => opener.document(),
(None, None) => None,
};
let url = creator.as_deref().map(|document| document.url());
let origin = creator
.as_deref()
.map(|document| document.origin().immutable().clone());
CreatorBrowsingContextInfo { url, origin }
}
}
fn tokenize_open_features(features: DOMString) -> IndexMap<String, String> {
let is_feature_sep = |c: char| c.is_ascii_whitespace() || ['=', ','].contains(&c);
let mut tokenized_features = IndexMap::new();
let features = features.str();
let mut iter = features.chars();
let mut cur = iter.next();
while cur.is_some() {
let mut name = String::new();
let mut value = String::new();
while let Some(cur_char) = cur {
if !is_feature_sep(cur_char) {
break;
}
cur = iter.next();
}
while let Some(cur_char) = cur {
if is_feature_sep(cur_char) {
break;
}
name.push(cur_char.to_ascii_lowercase());
cur = iter.next();
}
let normalized_name = String::from(match name.as_ref() {
"screenx" => "left",
"screeny" => "top",
"innerwidth" => "width",
"innerheight" => "height",
_ => name.as_ref(),
});
while let Some(cur_char) = cur {
if cur_char == '=' || cur_char == ',' || !is_feature_sep(cur_char) {
break;
}
cur = iter.next();
}
if cur.is_some() && is_feature_sep(cur.unwrap()) {
while let Some(cur_char) = cur {
if !is_feature_sep(cur_char) || cur_char == ',' {
break;
}
cur = iter.next();
}
while let Some(cur_char) = cur {
if is_feature_sep(cur_char) {
break;
}
value.push(cur_char.to_ascii_lowercase());
cur = iter.next();
}
}
if !name.is_empty() {
tokenized_features.insert(normalized_name, value);
}
}
tokenized_features
}
fn parse_open_feature_boolean(tokenized_features: &IndexMap<String, String>, name: &str) -> bool {
if let Some(value) = tokenized_features.get(name) {
if value.is_empty() || value == "yes" {
return true;
}
if let Ok(int) = parse_integer(value.chars()) {
return int != 0;
}
}
false
}
#[expect(unsafe_code)]
fn window_proxy_target(proxy: HandleObject) -> *mut JSObject {
let mut slot = UndefinedValue();
unsafe { GetProxyPrivate(proxy.as_raw(), &mut slot) };
slot.to_object()
}
#[expect(unsafe_code)]
unsafe extern "C" fn get_own_property_descriptor(
cx: *mut RawJSContext,
proxy: RawHandleObject,
id: RawHandleId,
property_descriptor: RawMutableHandle<PropertyDescriptor>,
is_none: *mut bool,
) -> bool {
let mut cx = unsafe {
JSContext::from_ptr(NonNull::new(cx).expect("JSContext should not be null in SM hook"))
};
let mut cx = CurrentRealm::assert(&mut cx);
let cx = &mut cx;
let proxy = unsafe { Handle::from_raw(proxy) };
let id = unsafe { Handle::from_raw(id) };
let mut property_descriptor = unsafe { MutableHandle::from_raw(property_descriptor) };
let is_none = unsafe { &mut *is_none };
rooted!(&in(cx) let target = window_proxy_target(proxy));
let window = WindowOrDissimilarOriginWindow::new(cx, target.handle());
if let Some(index) = get_array_index_from_id(id) {
if let Some(window_proxy) = window.window_proxy_for_child_navigable_at_index(index) {
rooted!(&in(cx) let mut window_proxy_jsval = UndefinedValue());
window_proxy.to_jsval(cx, window_proxy_jsval.handle_mut());
set_property_descriptor(
property_descriptor,
window_proxy_jsval.handle(),
(JSPROP_ENUMERATE | JSPROP_READONLY) as u32,
is_none,
);
return true;
} else {
*is_none = true;
if is_platform_object_same_origin(cx, proxy) {
return true;
}
return report_cross_origin_denial::<DomTypeHolder>(cx, id, "get");
}
}
if is_platform_object_same_origin(cx, proxy) {
return JS_GetOwnPropertyDescriptorById(
cx,
target.handle(),
id,
property_descriptor,
is_none,
);
}
if !cross_origin_get_own_property_helper(
cx,
proxy,
window.cross_origin_properties(),
id,
property_descriptor.reborrow(),
is_none,
) {
return false;
}
if !*is_none {
return true;
}
if let Some(named_child_navigable) = window.named_child_navigable(cx, id) {
rooted!(&in(cx) let mut window_proxy_value = UndefinedValue());
named_child_navigable.to_jsval(cx, window_proxy_value.handle_mut());
set_property_descriptor(
property_descriptor.reborrow(),
window_proxy_value.handle(),
JSPROP_READONLY as u32,
is_none,
);
return true;
}
cross_origin_property_fallback::<DomTypeHolder>(
cx,
proxy,
id,
property_descriptor.reborrow(),
is_none,
)
}
#[expect(unsafe_code)]
unsafe extern "C" fn define_property(
cx: *mut RawJSContext,
proxy: RawHandleObject,
id: RawHandleId,
desc: RawHandle<PropertyDescriptor>,
res: *mut ObjectOpResult,
) -> bool {
let mut cx = unsafe {
JSContext::from_ptr(NonNull::new(cx).expect("JSContext should not be null in SM hook"))
};
let mut cx = CurrentRealm::assert(&mut cx);
let cx = &mut cx;
let id = unsafe { Handle::from_raw(id) };
let proxy = unsafe { Handle::from_raw(proxy) };
if is_platform_object_same_origin(cx, proxy) {
if get_array_index_from_id(id).is_some() {
unsafe {
(*res).code_ = JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as usize;
}
return true;
}
rooted!(&in(cx) let target = window_proxy_target(proxy));
return unsafe {
JS_DefinePropertyById(cx.raw_cx(), target.handle().into(), id.into(), desc, res)
};
}
report_cross_origin_denial::<DomTypeHolder>(cx, id, "define")
}
#[expect(unsafe_code)]
unsafe extern "C" fn has(
cx: *mut RawJSContext,
proxy: RawHandleObject,
id: RawHandleId,
bp: *mut bool,
) -> bool {
unsafe { has_or_has_own(cx, proxy, id, bp, IncludePrototypes::Yes) }
}
#[expect(unsafe_code)]
unsafe extern "C" fn has_own(
cx: *mut RawJSContext,
proxy: RawHandleObject,
id: RawHandleId,
bp: *mut bool,
) -> bool {
unsafe { has_or_has_own(cx, proxy, id, bp, IncludePrototypes::No) }
}
enum IncludePrototypes {
Yes,
No,
}
#[expect(unsafe_code)]
unsafe fn has_or_has_own(
cx: *mut RawJSContext,
proxy: RawHandleObject,
id: RawHandleId,
bp: *mut bool,
include_prototypes: IncludePrototypes,
) -> bool {
let mut cx = unsafe { JSContext::from_ptr(ptr::NonNull::new(cx).unwrap()) };
let mut cx = CurrentRealm::assert(&mut cx);
let cx = &mut cx;
let proxy = unsafe { Handle::from_raw(proxy) };
let id = unsafe { Handle::from_raw(id) };
rooted!(&in(cx) let target = window_proxy_target(proxy));
let window = WindowOrDissimilarOriginWindow::new(cx, target.handle());
let (success, found) = if is_platform_object_same_origin(cx, proxy) {
if let Some(array_index) = get_array_index_from_id(id) &&
window
.window_proxy_for_child_navigable_at_index(array_index)
.is_some()
{
unsafe { *bp = true };
return true;
}
let mut found = false;
let success = match include_prototypes {
IncludePrototypes::Yes => unsafe {
JS_HasPropertyById(cx, target.handle(), id, &mut found)
},
IncludePrototypes::No => unsafe {
JS_HasOwnPropertyById(cx, target.handle(), id, &mut found)
},
};
(success, found)
} else {
rooted!(&in(cx) let mut property_descriptor = PropertyDescriptor::default());
let mut is_none = false;
let success = unsafe {
get_own_property_descriptor(
cx.raw_cx(),
proxy.into(),
id.into(),
property_descriptor.handle_mut().into(),
&mut is_none,
)
};
(success, !is_none)
};
if !success {
return false;
}
unsafe { *bp = found };
true
}
#[expect(unsafe_code)]
unsafe extern "C" fn get(
cx: *mut RawJSContext,
proxy: RawHandleObject,
receiver: RawHandleValue,
id: RawHandleId,
return_value: RawMutableHandleValue,
) -> bool {
let mut cx = unsafe {
JSContext::from_ptr(NonNull::new(cx).expect("JSContext should not be null in SM hook"))
};
let mut cx = CurrentRealm::assert(&mut cx);
let cx = &mut cx;
let proxy = unsafe { Handle::from_raw(proxy) };
let receiver = unsafe { Handle::from_raw(receiver) };
let id = unsafe { Handle::from_raw(id) };
let return_value = unsafe { MutableHandle::from_raw(return_value) };
rooted!(&in(cx) let target = window_proxy_target(proxy));
let window = WindowOrDissimilarOriginWindow::new(cx, target.handle());
if is_platform_object_same_origin(cx, proxy) {
if let Some(index) = get_array_index_from_id(id) &&
let Some(window_proxy) = window.window_proxy_for_child_navigable_at_index(index)
{
window_proxy.to_jsval(cx, return_value);
return true;
}
return unsafe { JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, return_value) };
}
proxyhandler::cross_origin_get::<DomTypeHolder>(cx, proxy, receiver, id, return_value)
}
#[expect(unsafe_code)]
unsafe extern "C" fn set(
cx: *mut RawJSContext,
proxy: RawHandleObject,
id: RawHandleId,
v: RawHandleValue,
receiver: RawHandleValue,
res: *mut ObjectOpResult,
) -> bool {
let mut cx = unsafe {
JSContext::from_ptr(NonNull::new(cx).expect("JSContext should not be null in SM hook"))
};
let mut cx = CurrentRealm::assert(&mut cx);
let cx = &mut cx;
let proxy = unsafe { Handle::from_raw(proxy) };
let id = unsafe { Handle::from_raw(id) };
if is_platform_object_same_origin(cx, proxy) {
if get_array_index_from_id(id).is_some() {
unsafe { (*res).code_ = JSErrNum::JSMSG_READ_ONLY as usize };
return true;
}
rooted!(&in(cx) let target = window_proxy_target(proxy));
return unsafe {
JS_ForwardSetPropertyTo(
cx.raw_cx(),
target.handle().into(),
id.into(),
v,
receiver,
res,
)
};
}
let receiver = unsafe { HandleValue::from_raw(receiver) };
unsafe { cross_origin_set::<DomTypeHolder>(cx, proxy, id, v, receiver, res) }
}
#[expect(unsafe_code)]
unsafe extern "C" fn get_prototype_if_ordinary(
_: *mut RawJSContext,
_: RawHandleObject,
is_ordinary: *mut bool,
_: RawMutableHandleObject,
) -> bool {
unsafe { *is_ordinary = false };
true
}
#[expect(unsafe_code)]
unsafe extern "C" fn get_prototype(
cx: *mut RawJSContext,
proxy: RawHandleObject,
result: RawMutableHandleObject,
) -> bool {
let mut cx = unsafe { JSContext::from_ptr(ptr::NonNull::new(cx).unwrap()) };
let mut realm = CurrentRealm::assert(&mut cx);
let proxy = unsafe { Handle::from_raw(proxy) };
let result = unsafe { MutableHandleObject::from_raw(result) };
maybe_cross_origin_get_prototype::<DomTypeHolder>(
&mut realm,
proxy,
GetProtoObject::<DomTypeHolder>,
result,
)
}
#[expect(unsafe_code)]
unsafe extern "C" fn delete(
cx: *mut RawJSContext,
proxy: RawHandleObject,
id: RawHandleId,
result: *mut ObjectOpResult,
) -> bool {
let mut cx = unsafe { JSContext::from_ptr(ptr::NonNull::new(cx).unwrap()) };
let mut cx = CurrentRealm::assert(&mut cx);
let cx = &mut cx;
let proxy = unsafe { Handle::from_raw(proxy) };
let id = unsafe { Handle::from_raw(id) };
rooted!(&in(cx) let target = window_proxy_target(proxy));
let window = WindowOrDissimilarOriginWindow::new(cx, target.handle());
if is_platform_object_same_origin(cx, proxy) {
if let Some(array_index) = get_array_index_from_id(id) {
let code = if window
.window_proxy_for_child_navigable_at_index(array_index)
.is_none()
{
0
} else {
JSErrNum::JSMSG_CANT_DELETE_WINDOW_ELEMENT as usize
};
unsafe { (*result).code_ = code };
return true;
}
rooted!(&in(cx) let target = window_proxy_target(proxy));
return unsafe {
JS_DeletePropertyById(cx.raw_cx(), target.handle().into(), id.into(), result)
};
}
report_cross_origin_denial::<DomTypeHolder>(cx, id, "delete")
}
#[expect(unsafe_code)]
unsafe extern "C" fn own_property_keys(
cx: *mut RawJSContext,
proxy: RawHandleObject,
property_keys: RawMutableHandleIdVector,
) -> bool {
let mut cx = unsafe { JSContext::from_ptr(ptr::NonNull::new(cx).unwrap()) };
let mut cx = CurrentRealm::assert(&mut cx);
let cx = &mut cx;
let proxy = unsafe { Handle::from_raw(proxy) };
rooted!(&in(cx) let target = window_proxy_target(proxy));
let window = WindowOrDissimilarOriginWindow::new(cx, target.handle());
let max_properties = window.iframe_count();
rooted!(&in(cx) let mut rooted_index_jsid: jsid);
for index in 0..max_properties {
unsafe { int_to_jsid(index as i32, rooted_index_jsid.handle_mut()) };
unsafe { AppendToIdVector(property_keys, rooted_index_jsid.handle()) };
}
if is_platform_object_same_origin(cx, proxy) {
return GetPropertyKeys(
cx,
target.handle(),
JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS,
property_keys,
);
}
cross_origin_own_property_keys(cx, proxy, window.cross_origin_properties(), property_keys)
}
#[expect(unsafe_code)]
unsafe extern "C" fn get_own_enumerable_property_keys(
cx: *mut RawJSContext,
proxy: RawHandleObject,
property_keys: RawMutableHandleIdVector,
) -> bool {
let mut cx = unsafe { JSContext::from_ptr(ptr::NonNull::new(cx).unwrap()) };
let mut cx = CurrentRealm::assert(&mut cx);
let cx = &mut cx;
let proxy = unsafe { Handle::from_raw(proxy) };
rooted!(&in(cx) let target = window_proxy_target(proxy));
let window = WindowOrDissimilarOriginWindow::new(cx, target.handle());
let max_properties = window.iframe_count();
rooted!(&in(cx) let mut rooted_index_jsid: jsid);
for index in 0..max_properties {
unsafe { int_to_jsid(index as i32, rooted_index_jsid.handle_mut()) };
unsafe { AppendToIdVector(property_keys, rooted_index_jsid.handle()) };
}
if is_platform_object_same_origin(cx, proxy) {
return GetPropertyKeys(cx, target.handle(), JSITER_OWNONLY, property_keys);
}
true
}
#[expect(unsafe_code)]
unsafe extern "C" fn enumerate(
cx: *mut RawJSContext,
proxy: RawHandleObject,
property_keys: RawMutableHandleIdVector,
) -> bool {
let mut cx = unsafe { JSContext::from_ptr(ptr::NonNull::new(cx).unwrap()) };
let cx = &mut cx;
let proxy = unsafe { Handle::from_raw(proxy) };
GetPropertyKeys(cx, proxy, 0, property_keys)
}
static PROXY_TRAPS: ProxyTraps = ProxyTraps {
enter: None,
getOwnPropertyDescriptor: Some(get_own_property_descriptor),
defineProperty: Some(define_property),
ownPropertyKeys: Some(own_property_keys),
delete_: Some(delete),
enumerate: Some(enumerate),
getPrototypeIfOrdinary: Some(get_prototype_if_ordinary),
getPrototype: Some(get_prototype),
setPrototype: Some(maybe_cross_origin_set_prototype_rawcx),
setImmutablePrototype: None,
preventExtensions: Some(prevent_extensions),
isExtensible: Some(is_extensible),
has: Some(has),
get: Some(get),
set: Some(set),
call: None,
construct: None,
hasOwn: Some(has_own),
getOwnEnumerablePropertyKeys: Some(get_own_enumerable_property_keys),
nativeCall: None,
objectClassIs: None,
className: None,
fun_toString: None,
boxedValue_unbox: None,
defaultValue: None,
trace: Some(trace),
finalize: Some(finalize),
objectMoved: None,
isCallable: None,
isConstructor: None,
};
pub(crate) struct WindowProxyHandler(*const libc::c_void);
impl MallocSizeOf for WindowProxyHandler {
fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
0
}
}
#[expect(unsafe_code)]
unsafe impl Send for WindowProxyHandler {}
#[expect(unsafe_code)]
unsafe impl Sync for WindowProxyHandler {}
#[expect(unsafe_code)]
impl WindowProxyHandler {
fn new(traps: &ProxyTraps) -> Self {
let ptr = unsafe { CreateWrapperProxyHandler(traps) };
assert!(!ptr.is_null());
Self(ptr)
}
pub(crate) fn proxy_handler() -> &'static Self {
use std::sync::OnceLock;
static SINGLETON: OnceLock<WindowProxyHandler> = OnceLock::new();
SINGLETON.get_or_init(|| Self::new(&PROXY_TRAPS))
}
fn new_window_proxy(
&self,
cx: &mut JSContext,
window_jsobject: js::gc::HandleObject,
) -> *mut JSObject {
let obj = unsafe { NewWindowProxy(cx, window_jsobject, self.0) };
assert!(!obj.is_null());
obj
}
}
#[expect(unsafe_code)]
impl Drop for WindowProxyHandler {
fn drop(&mut self) {
unsafe {
DeleteWrapperProxyHandler(self.0);
}
}
}
#[expect(unsafe_code)]
unsafe extern "C" fn finalize(_fop: *mut GCContext, obj: *mut JSObject) {
let mut slot = UndefinedValue();
unsafe { GetProxyReservedSlot(obj, 0, &mut slot) };
let this = slot.to_private() as *mut WindowProxy;
if this.is_null() {
return;
}
unsafe {
(*this).reflector.drop_memory(&*this);
let jsobject = (*this).reflector.get_jsobject().get();
debug!(
"WindowProxy finalize: {:p}, with reflector {:p} from {:p}.",
this, jsobject, obj
);
let _ = Box::from_raw(this);
}
}
#[expect(unsafe_code)]
unsafe extern "C" fn trace(trc: *mut JSTracer, obj: *mut JSObject) {
let mut slot = UndefinedValue();
unsafe { GetProxyReservedSlot(obj, 0, &mut slot) };
let this = slot.to_private() as *const WindowProxy;
if this.is_null() {
return;
}
unsafe { (*this).trace(trc) };
}
enum WindowOrDissimilarOriginWindow {
Window(DomRoot<Window>),
DissimilarOriginWindow(DomRoot<DissimilarOriginWindow>),
}
impl WindowOrDissimilarOriginWindow {
fn new(cx: &mut JSContext, handle_object: HandleObject) -> Self {
if let Ok(window) = root_from_handleobject::<Window>(cx, handle_object) {
Self::Window(window)
} else if let Ok(window) =
root_from_handleobject::<DissimilarOriginWindow>(cx, handle_object)
{
Self::DissimilarOriginWindow(window)
} else {
unreachable!("WindowProxy should always be backed by some kind of window");
}
}
fn global_scope(&self) -> DomRoot<GlobalScope> {
match self {
WindowOrDissimilarOriginWindow::Window(window) => window.global(),
WindowOrDissimilarOriginWindow::DissimilarOriginWindow(window) => window.global(),
}
}
fn window_proxy(&self) -> DomRoot<WindowProxy> {
match self {
WindowOrDissimilarOriginWindow::Window(window) => window.window_proxy(),
WindowOrDissimilarOriginWindow::DissimilarOriginWindow(window) => window.window_proxy(),
}
}
#[expect(unsafe_code)]
fn cross_origin_properties(&self) -> &'static CrossOriginProperties {
match self {
WindowOrDissimilarOriginWindow::Window(..) => unsafe {
WindowBinding::CROSS_ORIGIN_PROPERTIES.get()
},
WindowOrDissimilarOriginWindow::DissimilarOriginWindow(..) => unsafe {
DissimilarOriginWindowBinding::CROSS_ORIGIN_PROPERTIES.get()
},
}
}
fn iframe_count(&self) -> u32 {
match self {
WindowOrDissimilarOriginWindow::Window(window) => window.Length(),
WindowOrDissimilarOriginWindow::DissimilarOriginWindow(window) => window.Length(),
}
}
fn window_proxy_for_child_navigable_at_index(
&self,
index: u32,
) -> Option<DomRoot<WindowProxy>> {
let window_proxy = self.window_proxy();
let browsing_context_id = if let Some(document) = window_proxy.document() {
document.iframes().at_insertion_index(index as usize)?
} else {
let parent_browsing_context_id = window_proxy.browsing_context_id();
let (result_sender, result_receiver) = generic_channel::channel().unwrap();
let _ = self.global_scope().script_to_constellation_chan().send(
ScriptToConstellationMessage::GetChildBrowsingContextId(
parent_browsing_context_id,
index as usize,
result_sender,
),
);
result_receiver.recv().ok().flatten()?
};
ScriptThread::window_proxies().find_window_proxy(browsing_context_id)
}
fn named_child_navigable(
&self,
cx: &mut CurrentRealm,
id: HandleId,
) -> Option<DomRoot<WindowProxy>> {
let Self::Window(window) = &self else {
return None;
};
let name = jsid_to_string(cx, id)?;
if name.is_empty() {
return None;
}
window
.Document()
.iframes()
.iter()
.filter_map(|iframe| iframe.GetContentWindow())
.find(|window_proxy| window_proxy.get_name() == name)
}
}