Switch ResourceCache from a leveldb to a directory-tree-based backend
[chromium-blink-merge.git] / url / gurl.cc
blob3dd8463c658b243ccef5d5ddabeb51215f1e1197
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.
5 #ifdef WIN32
6 #include <windows.h>
7 #else
8 #include <pthread.h>
9 #endif
11 #include <algorithm>
12 #include <ostream>
14 #include "url/gurl.h"
16 #include "base/logging.h"
17 #include "url/url_canon_stdstring.h"
18 #include "url/url_util.h"
20 namespace {
22 // External template that can handle initialization of either character type.
23 // The input spec is given, and the canonical version will be placed in
24 // |*canonical|, along with the parsing of the canonical spec in |*parsed|.
25 template<typename STR>
26 bool InitCanonical(const STR& input_spec,
27 std::string* canonical,
28 url_parse::Parsed* parsed) {
29 // Reserve enough room in the output for the input, plus some extra so that
30 // we have room if we have to escape a few things without reallocating.
31 canonical->reserve(input_spec.size() + 32);
32 url_canon::StdStringCanonOutput output(canonical);
33 bool success = url_util::Canonicalize(
34 input_spec.data(), static_cast<int>(input_spec.length()),
35 NULL, &output, parsed);
37 output.Complete(); // Must be done before using string.
38 return success;
41 static std::string* empty_string = NULL;
42 static GURL* empty_gurl = NULL;
44 #ifdef WIN32
46 // Returns a static reference to an empty string for returning a reference
47 // when there is no underlying string.
48 const std::string& EmptyStringForGURL() {
49 // Avoid static object construction/destruction on startup/shutdown.
50 if (!empty_string) {
51 // Create the string. Be careful that we don't break in the case that this
52 // is being called from multiple threads. Statics are not threadsafe.
53 std::string* new_empty_string = new std::string;
54 if (InterlockedCompareExchangePointer(
55 reinterpret_cast<PVOID*>(&empty_string), new_empty_string, NULL)) {
56 // The old value was non-NULL, so no replacement was done. Another
57 // thread did the initialization out from under us.
58 delete new_empty_string;
61 return *empty_string;
64 #else
66 static pthread_once_t empty_string_once = PTHREAD_ONCE_INIT;
67 static pthread_once_t empty_gurl_once = PTHREAD_ONCE_INIT;
69 void EmptyStringForGURLOnce(void) {
70 empty_string = new std::string;
73 const std::string& EmptyStringForGURL() {
74 // Avoid static object construction/destruction on startup/shutdown.
75 pthread_once(&empty_string_once, EmptyStringForGURLOnce);
76 return *empty_string;
79 #endif // WIN32
81 } // namespace
83 GURL::GURL() : is_valid_(false), inner_url_(NULL) {
86 GURL::GURL(const GURL& other)
87 : spec_(other.spec_),
88 is_valid_(other.is_valid_),
89 parsed_(other.parsed_),
90 inner_url_(NULL) {
91 if (other.inner_url_)
92 inner_url_ = new GURL(*other.inner_url_);
93 // Valid filesystem urls should always have an inner_url_.
94 DCHECK(!is_valid_ || !SchemeIsFileSystem() || inner_url_);
97 GURL::GURL(const std::string& url_string) : inner_url_(NULL) {
98 is_valid_ = InitCanonical(url_string, &spec_, &parsed_);
99 if (is_valid_ && SchemeIsFileSystem()) {
100 inner_url_ =
101 new GURL(spec_.data(), parsed_.Length(), *parsed_.inner_parsed(), true);
105 GURL::GURL(const base::string16& url_string) : inner_url_(NULL) {
106 is_valid_ = InitCanonical(url_string, &spec_, &parsed_);
107 if (is_valid_ && SchemeIsFileSystem()) {
108 inner_url_ =
109 new GURL(spec_.data(), parsed_.Length(), *parsed_.inner_parsed(), true);
113 GURL::GURL(const char* canonical_spec, size_t canonical_spec_len,
114 const url_parse::Parsed& parsed, bool is_valid)
115 : spec_(canonical_spec, canonical_spec_len),
116 is_valid_(is_valid),
117 parsed_(parsed),
118 inner_url_(NULL) {
119 if (is_valid_ && SchemeIsFileSystem()) {
120 inner_url_ =
121 new GURL(spec_.data(), parsed_.Length(), *parsed_.inner_parsed(), true);
124 #ifndef NDEBUG
125 // For testing purposes, check that the parsed canonical URL is identical to
126 // what we would have produced. Skip checking for invalid URLs have no meaning
127 // and we can't always canonicalize then reproducabely.
128 if (is_valid_) {
129 url_parse::Component scheme;
130 if (!url_util::FindAndCompareScheme(canonical_spec, canonical_spec_len,
131 "filesystem", &scheme) ||
132 scheme.begin == parsed.scheme.begin) {
133 // We can't do this check on the inner_url of a filesystem URL, as
134 // canonical_spec actually points to the start of the outer URL, so we'd
135 // end up with infinite recursion in this constructor.
136 GURL test_url(spec_);
138 DCHECK(test_url.is_valid_ == is_valid_);
139 DCHECK(test_url.spec_ == spec_);
141 DCHECK(test_url.parsed_.scheme == parsed_.scheme);
142 DCHECK(test_url.parsed_.username == parsed_.username);
143 DCHECK(test_url.parsed_.password == parsed_.password);
144 DCHECK(test_url.parsed_.host == parsed_.host);
145 DCHECK(test_url.parsed_.port == parsed_.port);
146 DCHECK(test_url.parsed_.path == parsed_.path);
147 DCHECK(test_url.parsed_.query == parsed_.query);
148 DCHECK(test_url.parsed_.ref == parsed_.ref);
151 #endif
154 GURL::~GURL() {
155 delete inner_url_;
158 GURL& GURL::operator=(const GURL& other) {
159 spec_ = other.spec_;
160 is_valid_ = other.is_valid_;
161 parsed_ = other.parsed_;
162 delete inner_url_;
163 inner_url_ = NULL;
164 if (other.inner_url_)
165 inner_url_ = new GURL(*other.inner_url_);
166 // Valid filesystem urls should always have an inner_url_.
167 DCHECK(!is_valid_ || !SchemeIsFileSystem() || inner_url_);
168 return *this;
171 const std::string& GURL::spec() const {
172 if (is_valid_ || spec_.empty())
173 return spec_;
175 DCHECK(false) << "Trying to get the spec of an invalid URL!";
176 return EmptyStringForGURL();
179 GURL GURL::Resolve(const std::string& relative) const {
180 return ResolveWithCharsetConverter(relative, NULL);
182 GURL GURL::Resolve(const base::string16& relative) const {
183 return ResolveWithCharsetConverter(relative, NULL);
186 // Note: code duplicated below (it's inconvenient to use a template here).
187 GURL GURL::ResolveWithCharsetConverter(
188 const std::string& relative,
189 url_canon::CharsetConverter* charset_converter) const {
190 // Not allowed for invalid URLs.
191 if (!is_valid_)
192 return GURL();
194 GURL result;
196 // Reserve enough room in the output for the input, plus some extra so that
197 // we have room if we have to escape a few things without reallocating.
198 result.spec_.reserve(spec_.size() + 32);
199 url_canon::StdStringCanonOutput output(&result.spec_);
201 if (!url_util::ResolveRelative(
202 spec_.data(), static_cast<int>(spec_.length()), parsed_,
203 relative.data(), static_cast<int>(relative.length()),
204 charset_converter, &output, &result.parsed_)) {
205 // Error resolving, return an empty URL.
206 return GURL();
209 output.Complete();
210 result.is_valid_ = true;
211 if (result.SchemeIsFileSystem()) {
212 result.inner_url_ = new GURL(result.spec_.data(), result.parsed_.Length(),
213 *result.parsed_.inner_parsed(), true);
215 return result;
218 // Note: code duplicated above (it's inconvenient to use a template here).
219 GURL GURL::ResolveWithCharsetConverter(
220 const base::string16& relative,
221 url_canon::CharsetConverter* charset_converter) const {
222 // Not allowed for invalid URLs.
223 if (!is_valid_)
224 return GURL();
226 GURL result;
228 // Reserve enough room in the output for the input, plus some extra so that
229 // we have room if we have to escape a few things without reallocating.
230 result.spec_.reserve(spec_.size() + 32);
231 url_canon::StdStringCanonOutput output(&result.spec_);
233 if (!url_util::ResolveRelative(
234 spec_.data(), static_cast<int>(spec_.length()), parsed_,
235 relative.data(), static_cast<int>(relative.length()),
236 charset_converter, &output, &result.parsed_)) {
237 // Error resolving, return an empty URL.
238 return GURL();
241 output.Complete();
242 result.is_valid_ = true;
243 if (result.SchemeIsFileSystem()) {
244 result.inner_url_ = new GURL(result.spec_.data(), result.parsed_.Length(),
245 *result.parsed_.inner_parsed(), true);
247 return result;
250 // Note: code duplicated below (it's inconvenient to use a template here).
251 GURL GURL::ReplaceComponents(
252 const url_canon::Replacements<char>& replacements) const {
253 GURL result;
255 // Not allowed for invalid URLs.
256 if (!is_valid_)
257 return GURL();
259 // Reserve enough room in the output for the input, plus some extra so that
260 // we have room if we have to escape a few things without reallocating.
261 result.spec_.reserve(spec_.size() + 32);
262 url_canon::StdStringCanonOutput output(&result.spec_);
264 result.is_valid_ = url_util::ReplaceComponents(
265 spec_.data(), static_cast<int>(spec_.length()), parsed_, replacements,
266 NULL, &output, &result.parsed_);
268 output.Complete();
269 if (result.is_valid_ && result.SchemeIsFileSystem()) {
270 result.inner_url_ = new GURL(spec_.data(), result.parsed_.Length(),
271 *result.parsed_.inner_parsed(), true);
273 return result;
276 // Note: code duplicated above (it's inconvenient to use a template here).
277 GURL GURL::ReplaceComponents(
278 const url_canon::Replacements<base::char16>& replacements) const {
279 GURL result;
281 // Not allowed for invalid URLs.
282 if (!is_valid_)
283 return GURL();
285 // Reserve enough room in the output for the input, plus some extra so that
286 // we have room if we have to escape a few things without reallocating.
287 result.spec_.reserve(spec_.size() + 32);
288 url_canon::StdStringCanonOutput output(&result.spec_);
290 result.is_valid_ = url_util::ReplaceComponents(
291 spec_.data(), static_cast<int>(spec_.length()), parsed_, replacements,
292 NULL, &output, &result.parsed_);
294 output.Complete();
295 if (result.is_valid_ && result.SchemeIsFileSystem()) {
296 result.inner_url_ = new GURL(spec_.data(), result.parsed_.Length(),
297 *result.parsed_.inner_parsed(), true);
299 return result;
302 GURL GURL::GetOrigin() const {
303 // This doesn't make sense for invalid or nonstandard URLs, so return
304 // the empty URL
305 if (!is_valid_ || !IsStandard())
306 return GURL();
308 if (SchemeIsFileSystem())
309 return inner_url_->GetOrigin();
311 url_canon::Replacements<char> replacements;
312 replacements.ClearUsername();
313 replacements.ClearPassword();
314 replacements.ClearPath();
315 replacements.ClearQuery();
316 replacements.ClearRef();
318 return ReplaceComponents(replacements);
321 GURL GURL::GetWithEmptyPath() const {
322 // This doesn't make sense for invalid or nonstandard URLs, so return
323 // the empty URL.
324 if (!is_valid_ || !IsStandard())
325 return GURL();
327 // We could optimize this since we know that the URL is canonical, and we are
328 // appending a canonical path, so avoiding re-parsing.
329 GURL other(*this);
330 if (parsed_.path.len == 0)
331 return other;
333 // Clear everything after the path.
334 other.parsed_.query.reset();
335 other.parsed_.ref.reset();
337 // Set the path, since the path is longer than one, we can just set the
338 // first character and resize.
339 other.spec_[other.parsed_.path.begin] = '/';
340 other.parsed_.path.len = 1;
341 other.spec_.resize(other.parsed_.path.begin + 1);
342 return other;
345 bool GURL::IsStandard() const {
346 return url_util::IsStandard(spec_.data(), parsed_.scheme);
349 bool GURL::SchemeIs(const char* lower_ascii_scheme) const {
350 if (parsed_.scheme.len <= 0)
351 return lower_ascii_scheme == NULL;
352 return url_util::LowerCaseEqualsASCII(spec_.data() + parsed_.scheme.begin,
353 spec_.data() + parsed_.scheme.end(),
354 lower_ascii_scheme);
357 int GURL::IntPort() const {
358 if (parsed_.port.is_nonempty())
359 return url_parse::ParsePort(spec_.data(), parsed_.port);
360 return url_parse::PORT_UNSPECIFIED;
363 int GURL::EffectiveIntPort() const {
364 int int_port = IntPort();
365 if (int_port == url_parse::PORT_UNSPECIFIED && IsStandard())
366 return url_canon::DefaultPortForScheme(spec_.data() + parsed_.scheme.begin,
367 parsed_.scheme.len);
368 return int_port;
371 std::string GURL::ExtractFileName() const {
372 url_parse::Component file_component;
373 url_parse::ExtractFileName(spec_.data(), parsed_.path, &file_component);
374 return ComponentString(file_component);
377 std::string GURL::PathForRequest() const {
378 DCHECK(parsed_.path.len > 0) << "Canonical path for requests should be non-empty";
379 if (parsed_.ref.len >= 0) {
380 // Clip off the reference when it exists. The reference starts after the #
381 // sign, so we have to subtract one to also remove it.
382 return std::string(spec_, parsed_.path.begin,
383 parsed_.ref.begin - parsed_.path.begin - 1);
385 // Compute the actual path length, rather than depending on the spec's
386 // terminator. If we're an inner_url, our spec continues on into our outer
387 // url's path/query/ref.
388 int path_len = parsed_.path.len;
389 if (parsed_.query.is_valid())
390 path_len = parsed_.query.end() - parsed_.path.begin;
392 return std::string(spec_, parsed_.path.begin, path_len);
395 std::string GURL::HostNoBrackets() const {
396 // If host looks like an IPv6 literal, strip the square brackets.
397 url_parse::Component h(parsed_.host);
398 if (h.len >= 2 && spec_[h.begin] == '[' && spec_[h.end() - 1] == ']') {
399 h.begin++;
400 h.len -= 2;
402 return ComponentString(h);
405 bool GURL::HostIsIPAddress() const {
406 if (!is_valid_ || spec_.empty())
407 return false;
409 url_canon::RawCanonOutputT<char, 128> ignored_output;
410 url_canon::CanonHostInfo host_info;
411 url_canon::CanonicalizeIPAddress(spec_.c_str(), parsed_.host,
412 &ignored_output, &host_info);
413 return host_info.IsIPAddress();
416 #ifdef WIN32
418 const GURL& GURL::EmptyGURL() {
419 // Avoid static object construction/destruction on startup/shutdown.
420 if (!empty_gurl) {
421 // Create the string. Be careful that we don't break in the case that this
422 // is being called from multiple threads.
423 GURL* new_empty_gurl = new GURL;
424 if (InterlockedCompareExchangePointer(
425 reinterpret_cast<PVOID*>(&empty_gurl), new_empty_gurl, NULL)) {
426 // The old value was non-NULL, so no replacement was done. Another
427 // thread did the initialization out from under us.
428 delete new_empty_gurl;
431 return *empty_gurl;
434 #else
436 void EmptyGURLOnce(void) {
437 empty_gurl = new GURL;
440 const GURL& GURL::EmptyGURL() {
441 // Avoid static object construction/destruction on startup/shutdown.
442 pthread_once(&empty_gurl_once, EmptyGURLOnce);
443 return *empty_gurl;
446 #endif // WIN32
448 bool GURL::DomainIs(const char* lower_ascii_domain,
449 int domain_len) const {
450 // Return false if this URL is not valid or domain is empty.
451 if (!is_valid_ || !domain_len)
452 return false;
454 // FileSystem URLs have empty parsed_.host, so check this first.
455 if (SchemeIsFileSystem() && inner_url_)
456 return inner_url_->DomainIs(lower_ascii_domain, domain_len);
458 if (!parsed_.host.is_nonempty())
459 return false;
461 // Check whether the host name is end with a dot. If yes, treat it
462 // the same as no-dot unless the input comparison domain is end
463 // with dot.
464 const char* last_pos = spec_.data() + parsed_.host.end() - 1;
465 int host_len = parsed_.host.len;
466 if ('.' == *last_pos && '.' != lower_ascii_domain[domain_len - 1]) {
467 last_pos--;
468 host_len--;
471 // Return false if host's length is less than domain's length.
472 if (host_len < domain_len)
473 return false;
475 // Compare this url whether belong specific domain.
476 const char* start_pos = spec_.data() + parsed_.host.begin +
477 host_len - domain_len;
479 if (!url_util::LowerCaseEqualsASCII(start_pos,
480 last_pos + 1,
481 lower_ascii_domain,
482 lower_ascii_domain + domain_len))
483 return false;
485 // Check whether host has right domain start with dot, make sure we got
486 // right domain range. For example www.google.com has domain
487 // "google.com" but www.iamnotgoogle.com does not.
488 if ('.' != lower_ascii_domain[0] && host_len > domain_len &&
489 '.' != *(start_pos - 1))
490 return false;
492 return true;
495 void GURL::Swap(GURL* other) {
496 spec_.swap(other->spec_);
497 std::swap(is_valid_, other->is_valid_);
498 std::swap(parsed_, other->parsed_);
499 std::swap(inner_url_, other->inner_url_);
502 std::ostream& operator<<(std::ostream& out, const GURL& url) {
503 return out << url.possibly_invalid_spec();