1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "url/origin.h"
10 #include "base/logging.h"
11 #include "base/strings/string_number_conversions.h"
13 #include "url/url_canon.h"
14 #include "url/url_canon_stdstring.h"
15 #include "url/url_constants.h"
16 #include "url/url_util.h"
20 Origin::Origin() : unique_(true) {}
22 Origin Origin::Create(const GURL& url) {
23 if (!url.is_valid() || (!url.IsStandard() && !url.SchemeIsBlob()))
28 if (url.SchemeIsFileSystem()) {
29 tuple = SchemeHostPort(*url.inner_url());
30 } else if (url.SchemeIsBlob()) {
31 // If we're dealing with a 'blob:' URL, https://url.spec.whatwg.org/#origin
32 // defines the origin as the origin of the URL which results from parsing
33 // the "path", which boils down to everything after the scheme. GURL's
34 // 'GetContent()' gives us exactly that.
35 tuple = SchemeHostPort(GURL(url.GetContent()));
37 tuple = SchemeHostPort(url);
40 if (tuple.IsInvalid())
43 return Origin(std::move(tuple));
46 Origin::Origin(SchemeHostPort tuple)
47 : tuple_(std::move(tuple)), unique_(false) {
48 DCHECK(!tuple_.IsInvalid());
51 Origin::Origin(const Origin&) = default;
52 Origin& Origin::operator=(const Origin&) = default;
53 Origin::Origin(Origin&&) = default;
54 Origin& Origin::operator=(Origin&&) = default;
56 Origin::~Origin() = default;
59 Origin Origin::UnsafelyCreateOriginWithoutNormalization(
60 base::StringPiece scheme,
61 base::StringPiece host,
63 SchemeHostPort tuple(scheme.as_string(), host.as_string(), port,
64 SchemeHostPort::CHECK_CANONICALIZATION);
65 if (tuple.IsInvalid())
67 return Origin(std::move(tuple));
70 Origin Origin::CreateFromNormalizedTuple(std::string scheme,
73 SchemeHostPort tuple(std::move(scheme), std::move(host), port,
74 SchemeHostPort::ALREADY_CANONICALIZED);
75 if (tuple.IsInvalid())
77 return Origin(std::move(tuple));
80 std::string Origin::Serialize() const {
84 if (scheme() == kFileScheme)
87 return tuple_.Serialize();
90 GURL Origin::GetURL() const {
94 if (scheme() == kFileScheme)
95 return GURL("file:///");
97 GURL tuple_url(tuple_.GetURL());
102 bool Origin::IsSameOriginWith(const Origin& other) const {
103 if (unique_ || other.unique_)
106 return tuple_.Equals(other.tuple_);
109 bool Origin::DomainIs(base::StringPiece canonical_domain) const {
110 return !unique_ && url::DomainIs(tuple_.host(), canonical_domain);
113 bool Origin::operator<(const Origin& other) const {
114 return tuple_ < other.tuple_;
117 std::ostream& operator<<(std::ostream& out, const url::Origin& origin) {
118 return out << origin.Serialize();
121 bool IsSameOriginWith(const GURL& a, const GURL& b) {
122 return Origin::Create(a).IsSameOriginWith(Origin::Create(b));