1 // Copyright 2013 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.
16 #include "base/logging.h"
17 #include "url/url_canon_stdstring.h"
18 #include "url/url_util.h"
22 static std::string
* empty_string
= NULL
;
23 static GURL
* empty_gurl
= NULL
;
27 // Returns a static reference to an empty string for returning a reference
28 // when there is no underlying string.
29 const std::string
& EmptyStringForGURL() {
30 // Avoid static object construction/destruction on startup/shutdown.
32 // Create the string. Be careful that we don't break in the case that this
33 // is being called from multiple threads. Statics are not threadsafe.
34 std::string
* new_empty_string
= new std::string
;
35 if (InterlockedCompareExchangePointer(
36 reinterpret_cast<PVOID
*>(&empty_string
), new_empty_string
, NULL
)) {
37 // The old value was non-NULL, so no replacement was done. Another
38 // thread did the initialization out from under us.
39 delete new_empty_string
;
47 static pthread_once_t empty_string_once
= PTHREAD_ONCE_INIT
;
48 static pthread_once_t empty_gurl_once
= PTHREAD_ONCE_INIT
;
50 void EmptyStringForGURLOnce(void) {
51 empty_string
= new std::string
;
54 const std::string
& EmptyStringForGURL() {
55 // Avoid static object construction/destruction on startup/shutdown.
56 pthread_once(&empty_string_once
, EmptyStringForGURLOnce
);
64 GURL::GURL() : is_valid_(false) {
67 GURL::GURL(const GURL
& other
)
69 is_valid_(other
.is_valid_
),
70 parsed_(other
.parsed_
) {
72 inner_url_
.reset(new GURL(*other
.inner_url_
));
73 // Valid filesystem urls should always have an inner_url_.
74 DCHECK(!is_valid_
|| !SchemeIsFileSystem() || inner_url_
);
77 GURL::GURL(const std::string
& url_string
) {
78 InitCanonical(url_string
, true);
81 GURL::GURL(const base::string16
& url_string
) {
82 InitCanonical(url_string
, true);
85 GURL::GURL(const std::string
& url_string
, RetainWhiteSpaceSelector
) {
86 InitCanonical(url_string
, false);
89 GURL::GURL(const char* canonical_spec
,
90 size_t canonical_spec_len
,
91 const url::Parsed
& parsed
,
93 : spec_(canonical_spec
, canonical_spec_len
),
96 InitializeFromCanonicalSpec();
99 GURL::GURL(std::string canonical_spec
, const url::Parsed
& parsed
, bool is_valid
)
100 : is_valid_(is_valid
),
102 spec_
.swap(canonical_spec
);
103 InitializeFromCanonicalSpec();
106 template<typename STR
>
107 void GURL::InitCanonical(const STR
& input_spec
, bool trim_path_end
) {
108 // Reserve enough room in the output for the input, plus some extra so that
109 // we have room if we have to escape a few things without reallocating.
110 spec_
.reserve(input_spec
.size() + 32);
111 url::StdStringCanonOutput
output(&spec_
);
112 is_valid_
= url::Canonicalize(
113 input_spec
.data(), static_cast<int>(input_spec
.length()), trim_path_end
,
114 NULL
, &output
, &parsed_
);
116 output
.Complete(); // Must be done before using string.
117 if (is_valid_
&& SchemeIsFileSystem()) {
118 inner_url_
.reset(new GURL(spec_
.data(), parsed_
.Length(),
119 *parsed_
.inner_parsed(), true));
123 void GURL::InitializeFromCanonicalSpec() {
124 if (is_valid_
&& SchemeIsFileSystem()) {
126 new GURL(spec_
.data(), parsed_
.Length(),
127 *parsed_
.inner_parsed(), true));
131 // For testing purposes, check that the parsed canonical URL is identical to
132 // what we would have produced. Skip checking for invalid URLs have no meaning
133 // and we can't always canonicalize then reproducabely.
135 url::Component scheme
;
136 // We can't do this check on the inner_url of a filesystem URL, as
137 // canonical_spec actually points to the start of the outer URL, so we'd
138 // end up with infinite recursion in this constructor.
139 if (!url::FindAndCompareScheme(spec_
.data(), spec_
.length(),
140 url::kFileSystemScheme
, &scheme
) ||
141 scheme
.begin
== parsed_
.scheme
.begin
) {
142 // We need to retain trailing whitespace on path URLs, as the |parsed_|
143 // spec we originally received may legitimately contain trailing white-
144 // space on the path or components e.g. if the #ref has been
145 // removed from a "foo:hello #ref" URL (see http://crbug.com/291747).
146 GURL
test_url(spec_
, RETAIN_TRAILING_PATH_WHITEPACE
);
148 DCHECK(test_url
.is_valid_
== is_valid_
);
149 DCHECK(test_url
.spec_
== spec_
);
151 DCHECK(test_url
.parsed_
.scheme
== parsed_
.scheme
);
152 DCHECK(test_url
.parsed_
.username
== parsed_
.username
);
153 DCHECK(test_url
.parsed_
.password
== parsed_
.password
);
154 DCHECK(test_url
.parsed_
.host
== parsed_
.host
);
155 DCHECK(test_url
.parsed_
.port
== parsed_
.port
);
156 DCHECK(test_url
.parsed_
.path
== parsed_
.path
);
157 DCHECK(test_url
.parsed_
.query
== parsed_
.query
);
158 DCHECK(test_url
.parsed_
.ref
== parsed_
.ref
);
167 GURL
& GURL::operator=(GURL other
) {
172 const std::string
& GURL::spec() const {
173 if (is_valid_
|| spec_
.empty())
176 DCHECK(false) << "Trying to get the spec of an invalid URL!";
177 return EmptyStringForGURL();
180 GURL
GURL::Resolve(const std::string
& relative
) const {
181 return ResolveWithCharsetConverter(relative
, NULL
);
183 GURL
GURL::Resolve(const base::string16
& relative
) const {
184 return ResolveWithCharsetConverter(relative
, NULL
);
187 // Note: code duplicated below (it's inconvenient to use a template here).
188 GURL
GURL::ResolveWithCharsetConverter(
189 const std::string
& relative
,
190 url::CharsetConverter
* charset_converter
) const {
191 // Not allowed for invalid URLs.
197 // Reserve enough room in the output for the input, plus some extra so that
198 // we have room if we have to escape a few things without reallocating.
199 result
.spec_
.reserve(spec_
.size() + 32);
200 url::StdStringCanonOutput
output(&result
.spec_
);
202 if (!url::ResolveRelative(spec_
.data(), static_cast<int>(spec_
.length()),
203 parsed_
, relative
.data(),
204 static_cast<int>(relative
.length()),
205 charset_converter
, &output
, &result
.parsed_
)) {
206 // Error resolving, return an empty URL.
211 result
.is_valid_
= true;
212 if (result
.SchemeIsFileSystem()) {
213 result
.inner_url_
.reset(
214 new GURL(result
.spec_
.data(), result
.parsed_
.Length(),
215 *result
.parsed_
.inner_parsed(), true));
220 // Note: code duplicated above (it's inconvenient to use a template here).
221 GURL
GURL::ResolveWithCharsetConverter(
222 const base::string16
& relative
,
223 url::CharsetConverter
* charset_converter
) const {
224 // Not allowed for invalid URLs.
230 // Reserve enough room in the output for the input, plus some extra so that
231 // we have room if we have to escape a few things without reallocating.
232 result
.spec_
.reserve(spec_
.size() + 32);
233 url::StdStringCanonOutput
output(&result
.spec_
);
235 if (!url::ResolveRelative(spec_
.data(), static_cast<int>(spec_
.length()),
236 parsed_
, relative
.data(),
237 static_cast<int>(relative
.length()),
238 charset_converter
, &output
, &result
.parsed_
)) {
239 // Error resolving, return an empty URL.
244 result
.is_valid_
= true;
245 if (result
.SchemeIsFileSystem()) {
246 result
.inner_url_
.reset(
247 new GURL(result
.spec_
.data(), result
.parsed_
.Length(),
248 *result
.parsed_
.inner_parsed(), true));
253 // Note: code duplicated below (it's inconvenient to use a template here).
254 GURL
GURL::ReplaceComponents(
255 const url::Replacements
<char>& replacements
) const {
258 // Not allowed for invalid URLs.
262 // Reserve enough room in the output for the input, plus some extra so that
263 // we have room if we have to escape a few things without reallocating.
264 result
.spec_
.reserve(spec_
.size() + 32);
265 url::StdStringCanonOutput
output(&result
.spec_
);
267 result
.is_valid_
= url::ReplaceComponents(
268 spec_
.data(), static_cast<int>(spec_
.length()), parsed_
, replacements
,
269 NULL
, &output
, &result
.parsed_
);
272 if (result
.is_valid_
&& result
.SchemeIsFileSystem()) {
273 result
.inner_url_
.reset(new GURL(spec_
.data(), result
.parsed_
.Length(),
274 *result
.parsed_
.inner_parsed(), true));
279 // Note: code duplicated above (it's inconvenient to use a template here).
280 GURL
GURL::ReplaceComponents(
281 const url::Replacements
<base::char16
>& replacements
) const {
284 // Not allowed for invalid URLs.
288 // Reserve enough room in the output for the input, plus some extra so that
289 // we have room if we have to escape a few things without reallocating.
290 result
.spec_
.reserve(spec_
.size() + 32);
291 url::StdStringCanonOutput
output(&result
.spec_
);
293 result
.is_valid_
= url::ReplaceComponents(
294 spec_
.data(), static_cast<int>(spec_
.length()), parsed_
, replacements
,
295 NULL
, &output
, &result
.parsed_
);
298 if (result
.is_valid_
&& result
.SchemeIsFileSystem()) {
299 result
.inner_url_
.reset(new GURL(spec_
.data(), result
.parsed_
.Length(),
300 *result
.parsed_
.inner_parsed(), true));
305 GURL
GURL::GetOrigin() const {
306 // This doesn't make sense for invalid or nonstandard URLs, so return
308 if (!is_valid_
|| !IsStandard())
311 if (SchemeIsFileSystem())
312 return inner_url_
->GetOrigin();
314 url::Replacements
<char> replacements
;
315 replacements
.ClearUsername();
316 replacements
.ClearPassword();
317 replacements
.ClearPath();
318 replacements
.ClearQuery();
319 replacements
.ClearRef();
321 return ReplaceComponents(replacements
);
324 GURL
GURL::GetAsReferrer() const {
325 if (!is_valid_
|| !SchemeIsHTTPOrHTTPS())
328 if (!has_ref() && !has_username() && !has_password())
331 url::Replacements
<char> replacements
;
332 replacements
.ClearRef();
333 replacements
.ClearUsername();
334 replacements
.ClearPassword();
335 return ReplaceComponents(replacements
);
338 GURL
GURL::GetWithEmptyPath() const {
339 // This doesn't make sense for invalid or nonstandard URLs, so return
341 if (!is_valid_
|| !IsStandard())
344 // We could optimize this since we know that the URL is canonical, and we are
345 // appending a canonical path, so avoiding re-parsing.
347 if (parsed_
.path
.len
== 0)
350 // Clear everything after the path.
351 other
.parsed_
.query
.reset();
352 other
.parsed_
.ref
.reset();
354 // Set the path, since the path is longer than one, we can just set the
355 // first character and resize.
356 other
.spec_
[other
.parsed_
.path
.begin
] = '/';
357 other
.parsed_
.path
.len
= 1;
358 other
.spec_
.resize(other
.parsed_
.path
.begin
+ 1);
362 bool GURL::IsStandard() const {
363 return url::IsStandard(spec_
.data(), parsed_
.scheme
);
366 bool GURL::SchemeIs(const char* lower_ascii_scheme
) const {
367 if (parsed_
.scheme
.len
<= 0)
368 return lower_ascii_scheme
== NULL
;
369 return url::LowerCaseEqualsASCII(spec_
.data() + parsed_
.scheme
.begin
,
370 spec_
.data() + parsed_
.scheme
.end(),
374 bool GURL::SchemeIsHTTPOrHTTPS() const {
375 return SchemeIs(url::kHttpScheme
) || SchemeIs(url::kHttpsScheme
);
378 bool GURL::SchemeIsWSOrWSS() const {
379 return SchemeIs(url::kWsScheme
) || SchemeIs(url::kWssScheme
);
382 int GURL::IntPort() const {
383 if (parsed_
.port
.is_nonempty())
384 return url::ParsePort(spec_
.data(), parsed_
.port
);
385 return url::PORT_UNSPECIFIED
;
388 int GURL::EffectiveIntPort() const {
389 int int_port
= IntPort();
390 if (int_port
== url::PORT_UNSPECIFIED
&& IsStandard())
391 return url::DefaultPortForScheme(spec_
.data() + parsed_
.scheme
.begin
,
396 std::string
GURL::ExtractFileName() const {
397 url::Component file_component
;
398 url::ExtractFileName(spec_
.data(), parsed_
.path
, &file_component
);
399 return ComponentString(file_component
);
402 std::string
GURL::PathForRequest() const {
403 DCHECK(parsed_
.path
.len
> 0) << "Canonical path for requests should be non-empty";
404 if (parsed_
.ref
.len
>= 0) {
405 // Clip off the reference when it exists. The reference starts after the #
406 // sign, so we have to subtract one to also remove it.
407 return std::string(spec_
, parsed_
.path
.begin
,
408 parsed_
.ref
.begin
- parsed_
.path
.begin
- 1);
410 // Compute the actual path length, rather than depending on the spec's
411 // terminator. If we're an inner_url, our spec continues on into our outer
412 // url's path/query/ref.
413 int path_len
= parsed_
.path
.len
;
414 if (parsed_
.query
.is_valid())
415 path_len
= parsed_
.query
.end() - parsed_
.path
.begin
;
417 return std::string(spec_
, parsed_
.path
.begin
, path_len
);
420 std::string
GURL::HostNoBrackets() const {
421 // If host looks like an IPv6 literal, strip the square brackets.
422 url::Component
h(parsed_
.host
);
423 if (h
.len
>= 2 && spec_
[h
.begin
] == '[' && spec_
[h
.end() - 1] == ']') {
427 return ComponentString(h
);
430 std::string
GURL::GetContent() const {
431 return is_valid_
? ComponentString(parsed_
.GetContent()) : std::string();
434 bool GURL::HostIsIPAddress() const {
435 if (!is_valid_
|| spec_
.empty())
438 url::RawCanonOutputT
<char, 128> ignored_output
;
439 url::CanonHostInfo host_info
;
440 url::CanonicalizeIPAddress(spec_
.c_str(), parsed_
.host
, &ignored_output
,
442 return host_info
.IsIPAddress();
447 const GURL
& GURL::EmptyGURL() {
448 // Avoid static object construction/destruction on startup/shutdown.
450 // Create the string. Be careful that we don't break in the case that this
451 // is being called from multiple threads.
452 GURL
* new_empty_gurl
= new GURL
;
453 if (InterlockedCompareExchangePointer(
454 reinterpret_cast<PVOID
*>(&empty_gurl
), new_empty_gurl
, NULL
)) {
455 // The old value was non-NULL, so no replacement was done. Another
456 // thread did the initialization out from under us.
457 delete new_empty_gurl
;
465 void EmptyGURLOnce(void) {
466 empty_gurl
= new GURL
;
469 const GURL
& GURL::EmptyGURL() {
470 // Avoid static object construction/destruction on startup/shutdown.
471 pthread_once(&empty_gurl_once
, EmptyGURLOnce
);
477 bool GURL::DomainIs(const char* lower_ascii_domain
,
478 int domain_len
) const {
479 // Return false if this URL is not valid or domain is empty.
480 if (!is_valid_
|| !domain_len
)
483 // FileSystem URLs have empty parsed_.host, so check this first.
484 if (SchemeIsFileSystem() && inner_url_
)
485 return inner_url_
->DomainIs(lower_ascii_domain
, domain_len
);
487 if (!parsed_
.host
.is_nonempty())
490 // Check whether the host name is end with a dot. If yes, treat it
491 // the same as no-dot unless the input comparison domain is end
493 const char* last_pos
= spec_
.data() + parsed_
.host
.end() - 1;
494 int host_len
= parsed_
.host
.len
;
495 if ('.' == *last_pos
&& '.' != lower_ascii_domain
[domain_len
- 1]) {
500 // Return false if host's length is less than domain's length.
501 if (host_len
< domain_len
)
504 // Compare this url whether belong specific domain.
505 const char* start_pos
= spec_
.data() + parsed_
.host
.begin
+
506 host_len
- domain_len
;
508 if (!url::LowerCaseEqualsASCII(start_pos
,
511 lower_ascii_domain
+ domain_len
))
514 // Check whether host has right domain start with dot, make sure we got
515 // right domain range. For example www.google.com has domain
516 // "google.com" but www.iamnotgoogle.com does not.
517 if ('.' != lower_ascii_domain
[0] && host_len
> domain_len
&&
518 '.' != *(start_pos
- 1))
524 void GURL::Swap(GURL
* other
) {
525 spec_
.swap(other
->spec_
);
526 std::swap(is_valid_
, other
->is_valid_
);
527 std::swap(parsed_
, other
->parsed_
);
528 inner_url_
.swap(other
->inner_url_
);
531 std::ostream
& operator<<(std::ostream
& out
, const GURL
& url
) {
532 return out
<< url
.possibly_invalid_spec();