Origin.h 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/String.h>
  9. namespace Web {
  10. class Origin {
  11. public:
  12. Origin() { }
  13. Origin(const String& protocol, const String& host, u16 port)
  14. : m_protocol(protocol)
  15. , m_host(host)
  16. , m_port(port)
  17. {
  18. }
  19. // https://html.spec.whatwg.org/multipage/origin.html#concept-origin-opaque
  20. bool is_opaque() const { return m_protocol.is_null() && m_host.is_null() && m_port == 0; }
  21. const String& protocol() const { return m_protocol; }
  22. const String& host() const { return m_host; }
  23. u16 port() const { return m_port; }
  24. // https://html.spec.whatwg.org/multipage/origin.html#same-origin
  25. bool is_same_origin(Origin const& other) const
  26. {
  27. // 1. If A and B are the same opaque origin, then return true.
  28. if (is_opaque() && other.is_opaque())
  29. return true;
  30. // 2. If A and B are both tuple origins and their schemes, hosts, and port are identical, then return true.
  31. // 3. Return false.
  32. return protocol() == other.protocol()
  33. && host() == other.host()
  34. && port() == other.port();
  35. }
  36. // https://html.spec.whatwg.org/multipage/origin.html#same-origin-domain
  37. bool is_same_origin_domain(Origin const& other) const
  38. {
  39. // 1. If A and B are the same opaque origin, then return true.
  40. if (is_opaque() && other.is_opaque())
  41. return true;
  42. // 2. If A and B are both tuple origins, run these substeps:
  43. if (!is_opaque() && !other.is_opaque()) {
  44. // 1. If A and B's schemes are identical, and their domains are identical and non-null, then return true.
  45. // FIXME: Check domains once supported.
  46. if (protocol() == other.protocol())
  47. return true;
  48. // 2. Otherwise, if A and B are same origin and their domains are identical and null, then return true.
  49. // FIXME: Check domains once supported.
  50. if (is_same_origin(other))
  51. return true;
  52. }
  53. // 3. Return false.
  54. return false;
  55. }
  56. bool operator==(Origin const& other) const { return is_same_origin(other); }
  57. bool operator!=(Origin const& other) const { return !is_same_origin(other); }
  58. private:
  59. String m_protocol;
  60. String m_host;
  61. u16 m_port { 0 };
  62. };
  63. }
  64. namespace AK {
  65. template<>
  66. struct Traits<Web::Origin> : public GenericTraits<Web::Origin> {
  67. static unsigned hash(Web::Origin const& origin)
  68. {
  69. return pair_int_hash(origin.protocol().hash(), pair_int_hash(int_hash(origin.port()), origin.host().hash()));
  70. }
  71. };
  72. } // namespace AK