Skip to main content

url/
origin.rs

1// Copyright 2016 The rust-url developers.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use crate::host::Host;
10use crate::parser::default_port;
11use crate::Url;
12use alloc::borrow::ToOwned;
13use alloc::format;
14use alloc::string::String;
15use core::sync::atomic::{AtomicUsize, Ordering};
16
17pub fn url_origin(url: &Url) -> Origin {
18    let scheme = url.scheme();
19    match scheme {
20        "blob" => {
21            let result = Url::parse(url.path());
22            match result {
23                // https://url.spec.whatwg.org/#concept-url-origin
24                // The URL Standard takes the origin of the inner URL only for these schemes.
25                Ok(ref url) if #[allow(non_exhaustive_omitted_patterns)] match url.scheme() {
    "http" | "https" | "file" => true,
    _ => false,
}matches!(url.scheme(), "http" | "https" | "file") => url_origin(url),
26                _ => Origin::new_opaque(),
27            }
28        }
29        "ftp" | "http" | "https" | "ws" | "wss" => Origin::Tuple(
30            scheme.to_owned(),
31            url.host().unwrap().to_owned(),
32            url.port_or_known_default().unwrap(),
33        ),
34        // TODO: Figure out what to do if the scheme is a file
35        "file" => Origin::new_opaque(),
36        _ => Origin::new_opaque(),
37    }
38}
39
40/// The origin of an URL
41///
42/// Two URLs with the same origin are considered
43/// to originate from the same entity and can therefore trust
44/// each other.
45///
46/// The origin is determined based on the scheme as follows:
47///
48/// - If the scheme is "blob" and the path component contains a URL
49///   with the scheme "http", "https", or "file", the origin is the
50///   origin of that URL. Otherwise it is an opaque origin.
51/// - If the scheme is "ftp", "http", "https", "ws", or "wss",
52///   then the origin is a tuple of the scheme, host, and port.
53/// - If the scheme is anything else, the origin is opaque, meaning
54///   the URL does not have the same origin as any other URL.
55///
56/// For more information see <https://url.spec.whatwg.org/#origin>
57#[derive(#[automatically_derived]impl ::core::marker::StructuralPartialEq for Origin {
}
#[automatically_derived]impl ::core::cmp::PartialEq for Origin {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        ::core::intrinsics::discriminant_value(self) ==
                ::core::intrinsics::discriminant_value(other) &&
            match (self, other) {
                (Self::Opaque(__self_0), Self::Opaque(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Self::Tuple(__self_0, __self_1, __self_2),
                    Self::Tuple(__arg1_0, __arg1_1, __arg1_2)) =>
                    __self_2 == __arg1_2 && __self_0 == __arg1_0 &&
                        __self_1 == __arg1_1,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for Origin {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<OpaqueOrigin>;
        let _: ::core::cmp::AssertParamIsEq<String>;
        let _: ::core::cmp::AssertParamIsEq<Host<String>>;
        let _: ::core::cmp::AssertParamIsEq<u16>;
    }
}Eq, #[automatically_derived]impl ::core::hash::Hash for Origin {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
            state);
        match self {
            Self::Opaque(__self_0) =>
                ::core::hash::Hash::hash(__self_0, state),
            Self::Tuple(__self_0, __self_1, __self_2) => {
                ::core::hash::Hash::hash(__self_0, state);
                ::core::hash::Hash::hash(__self_1, state);
                ::core::hash::Hash::hash(__self_2, state)
            }
        }
    }
}Hash, #[automatically_derived]impl ::core::clone::Clone for Origin {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::Opaque(__self_0) =>
                Origin::Opaque(::core::clone::Clone::clone(__self_0)),
            Self::Tuple(__self_0, __self_1, __self_2) =>
                Origin::Tuple(::core::clone::Clone::clone(__self_0),
                    ::core::clone::Clone::clone(__self_1),
                    ::core::clone::Clone::clone(__self_2)),
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for Origin {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Opaque(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Opaque", &__self_0),
            Self::Tuple(__self_0, __self_1, __self_2) =>
                ::core::fmt::Formatter::debug_struct_field3_finish(f, "Tuple",
                    __self_0, __self_1, &__self_2),
        }
    }
}Debug)]
58pub enum Origin {
59    /// A globally unique identifier
60    Opaque(OpaqueOrigin),
61
62    /// Consists of the URL's scheme, host and port
63    Tuple(String, Host<String>, u16),
64}
65
66impl Origin {
67    /// Creates a new opaque origin that is only equal to itself.
68    pub fn new_opaque() -> Self {
69        static COUNTER: AtomicUsize = AtomicUsize::new(0);
70        Self::Opaque(OpaqueOrigin(COUNTER.fetch_add(1, Ordering::SeqCst)))
71    }
72
73    /// Return whether this origin is a (scheme, host, port) tuple
74    /// (as opposed to an opaque origin).
75    pub fn is_tuple(&self) -> bool {
76        #[allow(non_exhaustive_omitted_patterns)] match *self {
    Self::Tuple(..) => true,
    _ => false,
}matches!(*self, Self::Tuple(..))
77    }
78
79    /// <https://html.spec.whatwg.org/multipage/#ascii-serialisation-of-an-origin>
80    pub fn ascii_serialization(&self) -> String {
81        match *self {
82            Self::Opaque(_) => "null".to_owned(),
83            Self::Tuple(ref scheme, ref host, port) => {
84                if default_port(scheme) == Some(port) {
85                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}://{1}", scheme, host))
    })format!("{scheme}://{host}")
86                } else {
87                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}://{1}:{2}", scheme, host,
                port))
    })format!("{scheme}://{host}:{port}")
88                }
89            }
90        }
91    }
92
93    /// <https://html.spec.whatwg.org/multipage/#unicode-serialisation-of-an-origin>
94    pub fn unicode_serialization(&self) -> String {
95        match *self {
96            Self::Opaque(_) => "null".to_owned(),
97            Self::Tuple(ref scheme, ref host, port) => {
98                let host = match *host {
99                    Host::Domain(ref domain) => {
100                        let (domain, _errors) = idna::domain_to_unicode(domain);
101                        Host::Domain(domain)
102                    }
103                    _ => host.clone(),
104                };
105                if default_port(scheme) == Some(port) {
106                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}://{1}", scheme, host))
    })format!("{scheme}://{host}")
107                } else {
108                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}://{1}:{2}", scheme, host,
                port))
    })format!("{scheme}://{host}:{port}")
109                }
110            }
111        }
112    }
113}
114
115/// Opaque identifier for URLs that have file or other schemes
116#[derive(#[automatically_derived]impl ::core::cmp::Eq for OpaqueOrigin {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<usize>;
    }
}Eq, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
    OpaqueOrigin {
}
#[automatically_derived]impl ::core::cmp::PartialEq for OpaqueOrigin {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]impl ::core::hash::Hash for OpaqueOrigin {
    #[inline]
    fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
        ::core::hash::Hash::hash(&self.0, state)
    }
}Hash, #[automatically_derived]impl ::core::clone::Clone for OpaqueOrigin {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        OpaqueOrigin(::core::clone::Clone::clone(&self.0))
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for OpaqueOrigin {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f, "OpaqueOrigin",
            &&self.0)
    }
}Debug)]
117pub struct OpaqueOrigin(usize);