Home | History | Annotate | Download | only in weborigin
      1 /*
      2  * Copyright (C) 2004, 2007, 2008, 2011, 2012 Apple Inc. All rights reserved.
      3  * Copyright (C) 2012 Research In Motion Limited. All rights reserved.
      4  * Copyright (C) 2008, 2009, 2011 Google Inc. All rights reserved.
      5  *
      6  * Redistribution and use in source and binary forms, with or without
      7  * modification, are permitted provided that the following conditions
      8  * are met:
      9  * 1. Redistributions of source code must retain the above copyright
     10  *    notice, this list of conditions and the following disclaimer.
     11  * 2. Redistributions in binary form must reproduce the above copyright
     12  *    notice, this list of conditions and the following disclaimer in the
     13  *    documentation and/or other materials provided with the distribution.
     14  *
     15  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
     16  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     18  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
     19  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
     20  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     21  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
     22  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
     23  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     25  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     26  */
     27 
     28 #include "config.h"
     29 #include "weborigin/KURL.h"
     30 
     31 #include "wtf/HashMap.h"
     32 #include "wtf/StdLibExtras.h"
     33 #include "wtf/text/CString.h"
     34 #include "wtf/text/StringHash.h"
     35 #include "wtf/text/StringUTF8Adaptor.h"
     36 #include "wtf/text/TextEncoding.h"
     37 #include <algorithm>
     38 #include <stdio.h>
     39 #include <url/url_util.h>
     40 
     41 namespace WebCore {
     42 
     43 static const unsigned maximumValidPortNumber = 0xFFFE;
     44 static const unsigned invalidPortNumber = 0xFFFF;
     45 
     46 static void assertProtocolIsGood(const char* protocol)
     47 {
     48 #ifndef NDEBUG
     49     const char* p = protocol;
     50     while (*p) {
     51         ASSERT(*p > ' ' && *p < 0x7F && !(*p >= 'A' && *p <= 'Z'));
     52         ++p;
     53     }
     54 #endif
     55 }
     56 
     57 // Note: You must ensure that |spec| is a valid canonicalized URL before calling this function.
     58 static const char* asURLChar8Subtle(const String& spec)
     59 {
     60     ASSERT(spec.is8Bit());
     61     // characters8 really return characters in Latin-1, but because we canonicalize
     62     // URL strings, we know that everything before the fragment identifier will
     63     // actually be ASCII, which means this cast is safe as long as you don't look
     64     // at the fragment component.
     65     return reinterpret_cast<const char*>(spec.characters8());
     66 }
     67 
     68 // Returns the characters for the given string, or a pointer to a static empty
     69 // string if the input string is null. This will always ensure we have a non-
     70 // null character pointer since ReplaceComponents has special meaning for null.
     71 static const char* charactersOrEmpty(const StringUTF8Adaptor& string)
     72 {
     73     static const char zero = 0;
     74     return string.data() ? string.data() : &zero;
     75 }
     76 
     77 static bool isSchemeFirstChar(char c)
     78 {
     79     return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
     80 }
     81 
     82 static bool isSchemeChar(char c)
     83 {
     84     return isSchemeFirstChar(c) || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '+';
     85 }
     86 
     87 static bool isUnicodeEncoding(const WTF::TextEncoding* encoding)
     88 {
     89     return encoding->encodingForFormSubmission() == UTF8Encoding();
     90 }
     91 
     92 namespace {
     93 
     94 class KURLCharsetConverter : public url_canon::CharsetConverter {
     95 public:
     96     // The encoding parameter may be 0, but in this case the object must not be called.
     97     explicit KURLCharsetConverter(const WTF::TextEncoding* encoding)
     98         : m_encoding(encoding)
     99     {
    100     }
    101 
    102     virtual void ConvertFromUTF16(const url_parse::UTF16Char* input, int inputLength, url_canon::CanonOutput* output)
    103     {
    104         CString encoded = m_encoding->normalizeAndEncode(String(input, inputLength), WTF::URLEncodedEntitiesForUnencodables);
    105         output->Append(encoded.data(), static_cast<int>(encoded.length()));
    106     }
    107 
    108 private:
    109     const WTF::TextEncoding* m_encoding;
    110 };
    111 
    112 } // namespace
    113 
    114 bool isValidProtocol(const String& protocol)
    115 {
    116     // RFC3986: ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
    117     if (protocol.isEmpty())
    118         return false;
    119     if (!isSchemeFirstChar(protocol[0]))
    120         return false;
    121     unsigned protocolLength = protocol.length();
    122     for (unsigned i = 1; i < protocolLength; i++) {
    123         if (!isSchemeChar(protocol[i]))
    124             return false;
    125     }
    126     return true;
    127 }
    128 
    129 String KURL::strippedForUseAsReferrer() const
    130 {
    131     KURL referrer(*this);
    132     referrer.setUser(String());
    133     referrer.setPass(String());
    134     referrer.removeFragmentIdentifier();
    135     return referrer.string();
    136 }
    137 
    138 bool KURL::isLocalFile() const
    139 {
    140     // Including feed here might be a bad idea since drag and drop uses this check
    141     // and including feed would allow feeds to potentially let someone's blog
    142     // read the contents of the clipboard on a drag, even without a drop.
    143     // Likewise with using the FrameLoader::shouldTreatURLAsLocal() function.
    144     return protocolIs("file");
    145 }
    146 
    147 bool protocolIsJavaScript(const String& url)
    148 {
    149     return protocolIs(url, "javascript");
    150 }
    151 
    152 const KURL& blankURL()
    153 {
    154     DEFINE_STATIC_LOCAL(KURL, staticBlankURL, (ParsedURLString, "about:blank"));
    155     return staticBlankURL;
    156 }
    157 
    158 bool KURL::isBlankURL() const
    159 {
    160     return protocolIs("about");
    161 }
    162 
    163 String KURL::elidedString() const
    164 {
    165     if (string().length() <= 1024)
    166         return string();
    167 
    168     return string().left(511) + "..." + string().right(510);
    169 }
    170 
    171 // Initializes with a string representing an absolute URL. No encoding
    172 // information is specified. This generally happens when a KURL is converted
    173 // to a string and then converted back. In this case, the URL is already
    174 // canonical and in proper escaped form so needs no encoding. We treat it as
    175 // UTF-8 just in case.
    176 KURL::KURL(ParsedURLStringTag, const String& url)
    177 {
    178     if (!url.isNull())
    179         init(KURL(), url, 0);
    180     else {
    181         // WebCore expects us to preserve the nullness of strings when this
    182         // constructor is used. In all other cases, it expects a non-null
    183         // empty string, which is what init() will create.
    184         m_isValid = false;
    185         m_protocolIsInHTTPFamily = false;
    186     }
    187 }
    188 
    189 KURL KURL::createIsolated(ParsedURLStringTag, const String& url)
    190 {
    191     // FIXME: We should be able to skip this extra copy and created an
    192     // isolated KURL more efficiently.
    193     return KURL(ParsedURLString, url).copy();
    194 }
    195 
    196 // Constructs a new URL given a base URL and a possibly relative input URL.
    197 // This assumes UTF-8 encoding.
    198 KURL::KURL(const KURL& base, const String& relative)
    199 {
    200     init(base, relative, 0);
    201 }
    202 
    203 // Constructs a new URL given a base URL and a possibly relative input URL.
    204 // Any query portion of the relative URL will be encoded in the given encoding.
    205 KURL::KURL(const KURL& base, const String& relative, const WTF::TextEncoding& encoding)
    206 {
    207     init(base, relative, &encoding.encodingForFormSubmission());
    208 }
    209 
    210 KURL::KURL(const AtomicString& canonicalString, const url_parse::Parsed& parsed, bool isValid)
    211     : m_isValid(isValid)
    212     , m_protocolIsInHTTPFamily(false)
    213     , m_parsed(parsed)
    214     , m_string(canonicalString)
    215 {
    216     initProtocolIsInHTTPFamily();
    217     initInnerURL();
    218 }
    219 
    220 KURL::KURL(WTF::HashTableDeletedValueType)
    221     : m_isValid(false)
    222     , m_protocolIsInHTTPFamily(false)
    223     , m_string(WTF::HashTableDeletedValue)
    224 {
    225 }
    226 
    227 KURL::KURL(const KURL& other)
    228     : m_isValid(other.m_isValid)
    229     , m_protocolIsInHTTPFamily(other.m_protocolIsInHTTPFamily)
    230     , m_parsed(other.m_parsed)
    231     , m_string(other.m_string)
    232 {
    233     if (other.m_innerURL.get())
    234         m_innerURL = adoptPtr(new KURL(other.m_innerURL->copy()));
    235 }
    236 
    237 KURL& KURL::operator=(const KURL& other)
    238 {
    239     m_isValid = other.m_isValid;
    240     m_protocolIsInHTTPFamily = other.m_protocolIsInHTTPFamily;
    241     m_parsed = other.m_parsed;
    242     m_string = other.m_string;
    243     if (other.m_innerURL)
    244         m_innerURL = adoptPtr(new KURL(other.m_innerURL->copy()));
    245     else
    246         m_innerURL.clear();
    247     return *this;
    248 }
    249 
    250 KURL KURL::copy() const
    251 {
    252     KURL result;
    253     result.m_isValid = m_isValid;
    254     result.m_protocolIsInHTTPFamily = m_protocolIsInHTTPFamily;
    255     result.m_parsed = m_parsed;
    256     result.m_string = m_string.isolatedCopy();
    257     if (result.m_innerURL)
    258         result.m_innerURL = adoptPtr(new KURL(m_innerURL->copy()));
    259     return result;
    260 }
    261 
    262 bool KURL::isNull() const
    263 {
    264     return m_string.isNull();
    265 }
    266 
    267 bool KURL::isEmpty() const
    268 {
    269     return m_string.isEmpty();
    270 }
    271 
    272 bool KURL::isValid() const
    273 {
    274     return m_isValid;
    275 }
    276 
    277 bool KURL::hasPort() const
    278 {
    279     return hostEnd() < pathStart();
    280 }
    281 
    282 bool KURL::protocolIsInHTTPFamily() const
    283 {
    284     return m_protocolIsInHTTPFamily;
    285 }
    286 
    287 bool KURL::hasPath() const
    288 {
    289     // Note that http://www.google.com/" has a path, the path is "/". This can
    290     // return false only for invalid or nonstandard URLs.
    291     return m_parsed.path.len >= 0;
    292 }
    293 
    294 // We handle "parameters" separated by a semicolon, while KURL.cpp does not,
    295 // which can lead to different results in some cases.
    296 String KURL::lastPathComponent() const
    297 {
    298     if (!m_isValid)
    299         return stringForInvalidComponent();
    300 
    301     // When the output ends in a slash, WebCore has different expectations than
    302     // the GoogleURL library. For "/foo/bar/" the library will return the empty
    303     // string, but WebCore wants "bar".
    304     url_parse::Component path = m_parsed.path;
    305     if (path.len > 0 && m_string[path.end() - 1] == '/')
    306         path.len--;
    307 
    308     url_parse::Component file;
    309     if (!m_string.isNull() && m_string.is8Bit())
    310         url_parse::ExtractFileName(asURLChar8Subtle(m_string), path, &file);
    311     else
    312         url_parse::ExtractFileName(m_string.characters16(), path, &file);
    313 
    314     // Bug: https://bugs.webkit.org/show_bug.cgi?id=21015 this function returns
    315     // a null string when the path is empty, which we duplicate here.
    316     if (!file.is_nonempty())
    317         return String();
    318     return componentString(file);
    319 }
    320 
    321 String KURL::protocol() const
    322 {
    323     return componentString(m_parsed.scheme);
    324 }
    325 
    326 String KURL::host() const
    327 {
    328     return componentString(m_parsed.host);
    329 }
    330 
    331 // Returns 0 when there is no port.
    332 //
    333 // We treat URL's with out-of-range port numbers as invalid URLs, and they will
    334 // be rejected by the canonicalizer. KURL.cpp will allow them in parsing, but
    335 // return invalidPortNumber from this port() function, so we mirror that behavior here.
    336 unsigned short KURL::port() const
    337 {
    338     if (!m_isValid || m_parsed.port.len <= 0)
    339         return 0;
    340     int port = 0;
    341     if (!m_string.isNull() && m_string.is8Bit())
    342         port = url_parse::ParsePort(asURLChar8Subtle(m_string), m_parsed.port);
    343     else
    344         port = url_parse::ParsePort(m_string.characters16(), m_parsed.port);
    345     ASSERT(port != url_parse::PORT_UNSPECIFIED); // Checked port.len <= 0 before.
    346 
    347     if (port == url_parse::PORT_INVALID || port > maximumValidPortNumber) // Mimic KURL::port()
    348         port = invalidPortNumber;
    349 
    350     return static_cast<unsigned short>(port);
    351 }
    352 
    353 String KURL::pass() const
    354 {
    355     // Bug: https://bugs.webkit.org/show_bug.cgi?id=21015 this function returns
    356     // a null string when the password is empty, which we duplicate here.
    357     if (!m_parsed.password.is_nonempty())
    358         return String();
    359     return componentString(m_parsed.password);
    360 }
    361 
    362 String KURL::user() const
    363 {
    364     return componentString(m_parsed.username);
    365 }
    366 
    367 String KURL::fragmentIdentifier() const
    368 {
    369     // Empty but present refs ("foo.com/bar#") should result in the empty
    370     // string, which componentString will produce. Nonexistent refs
    371     // should be the null string.
    372     if (!m_parsed.ref.is_valid())
    373         return String();
    374     return componentString(m_parsed.ref);
    375 }
    376 
    377 bool KURL::hasFragmentIdentifier() const
    378 {
    379     return m_parsed.ref.len >= 0;
    380 }
    381 
    382 String KURL::baseAsString() const
    383 {
    384     // FIXME: There is probably a more efficient way to do this?
    385     return m_string.left(pathAfterLastSlash());
    386 }
    387 
    388 String KURL::query() const
    389 {
    390     if (m_parsed.query.len >= 0)
    391         return componentString(m_parsed.query);
    392 
    393     // Bug: https://bugs.webkit.org/show_bug.cgi?id=21015 this function returns
    394     // an empty string when the query is empty rather than a null (not sure
    395     // which is right).
    396     // Returns a null if the query is not specified, instead of empty.
    397     if (m_parsed.query.is_valid())
    398         return emptyString();
    399     return String();
    400 }
    401 
    402 String KURL::path() const
    403 {
    404     return componentString(m_parsed.path);
    405 }
    406 
    407 bool KURL::setProtocol(const String& protocol)
    408 {
    409     // Firefox and IE remove everything after the first ':'.
    410     int separatorPosition = protocol.find(':');
    411     String newProtocol = protocol.substring(0, separatorPosition);
    412     StringUTF8Adaptor newProtocolUTF8(newProtocol);
    413 
    414     // If KURL is given an invalid scheme, it returns failure without modifying
    415     // the URL at all. This is in contrast to most other setters which modify
    416     // the URL and set "m_isValid."
    417     url_canon::RawCanonOutputT<char> canonProtocol;
    418     url_parse::Component protocolComponent;
    419     if (!url_canon::CanonicalizeScheme(newProtocolUTF8.data(), url_parse::Component(0, newProtocolUTF8.length()), &canonProtocol, &protocolComponent)
    420         || !protocolComponent.is_nonempty())
    421         return false;
    422 
    423     url_canon::Replacements<char> replacements;
    424     replacements.SetScheme(charactersOrEmpty(newProtocolUTF8), url_parse::Component(0, newProtocolUTF8.length()));
    425     replaceComponents(replacements);
    426 
    427     // isValid could be false but we still return true here. This is because
    428     // WebCore or JS scripts can build up a URL by setting individual
    429     // components, and a JS exception is based on the return value of this
    430     // function. We want to throw the exception and stop the script only when
    431     // its trying to set a bad protocol, and not when it maybe just hasn't
    432     // finished building up its final scheme.
    433     return true;
    434 }
    435 
    436 void KURL::setHost(const String& host)
    437 {
    438     StringUTF8Adaptor hostUTF8(host);
    439     url_canon::Replacements<char> replacements;
    440     replacements.SetHost(charactersOrEmpty(hostUTF8), url_parse::Component(0, hostUTF8.length()));
    441     replaceComponents(replacements);
    442 }
    443 
    444 void KURL::setHostAndPort(const String& hostAndPort)
    445 {
    446     String host = hostAndPort;
    447     String port;
    448     int hostEnd = hostAndPort.find(":");
    449     if (hostEnd != -1) {
    450         host = hostAndPort.left(hostEnd);
    451         port = hostAndPort.substring(hostEnd + 1);
    452     }
    453 
    454     StringUTF8Adaptor hostUTF8(host);
    455     StringUTF8Adaptor portUTF8(port);
    456 
    457     url_canon::Replacements<char> replacements;
    458     // Host can't be removed, so we always set.
    459     replacements.SetHost(charactersOrEmpty(hostUTF8), url_parse::Component(0, hostUTF8.length()));
    460 
    461     if (!portUTF8.length()) // Port may be removed, so we support clearing.
    462         replacements.ClearPort();
    463     else
    464         replacements.SetPort(charactersOrEmpty(portUTF8), url_parse::Component(0, portUTF8.length()));
    465 
    466     replaceComponents(replacements);
    467 }
    468 
    469 void KURL::removePort()
    470 {
    471     if (!hasPort())
    472         return;
    473     url_canon::Replacements<char> replacements;
    474     replacements.ClearPort();
    475     replaceComponents(replacements);
    476 }
    477 
    478 void KURL::setPort(unsigned short i)
    479 {
    480     String portString = String::number(i);
    481     ASSERT(portString.is8Bit());
    482 
    483     url_canon::Replacements<char> replacements;
    484     replacements.SetPort(reinterpret_cast<const char*>(portString.characters8()), url_parse::Component(0, portString.length()));
    485     replaceComponents(replacements);
    486 }
    487 
    488 void KURL::setUser(const String& user)
    489 {
    490     // This function is commonly called to clear the username, which we
    491     // normally don't have, so we optimize this case.
    492     if (user.isEmpty() && !m_parsed.username.is_valid())
    493         return;
    494 
    495     // The canonicalizer will clear any usernames that are empty, so we
    496     // don't have to explicitly call ClearUsername() here.
    497     StringUTF8Adaptor userUTF8(user);
    498     url_canon::Replacements<char> replacements;
    499     replacements.SetUsername(charactersOrEmpty(userUTF8), url_parse::Component(0, userUTF8.length()));
    500     replaceComponents(replacements);
    501 }
    502 
    503 void KURL::setPass(const String& pass)
    504 {
    505     // This function is commonly called to clear the password, which we
    506     // normally don't have, so we optimize this case.
    507     if (pass.isEmpty() && !m_parsed.password.is_valid())
    508         return;
    509 
    510     // The canonicalizer will clear any passwords that are empty, so we
    511     // don't have to explicitly call ClearUsername() here.
    512     StringUTF8Adaptor passUTF8(pass);
    513     url_canon::Replacements<char> replacements;
    514     replacements.SetPassword(charactersOrEmpty(passUTF8), url_parse::Component(0, passUTF8.length()));
    515     replaceComponents(replacements);
    516 }
    517 
    518 void KURL::setFragmentIdentifier(const String& fragment)
    519 {
    520     // This function is commonly called to clear the ref, which we
    521     // normally don't have, so we optimize this case.
    522     if (fragment.isNull() && !m_parsed.ref.is_valid())
    523         return;
    524 
    525     StringUTF8Adaptor fragmentUTF8(fragment);
    526 
    527     url_canon::Replacements<char> replacements;
    528     if (fragment.isNull())
    529         replacements.ClearRef();
    530     else
    531         replacements.SetRef(charactersOrEmpty(fragmentUTF8), url_parse::Component(0, fragmentUTF8.length()));
    532     replaceComponents(replacements);
    533 }
    534 
    535 void KURL::removeFragmentIdentifier()
    536 {
    537     url_canon::Replacements<char> replacements;
    538     replacements.ClearRef();
    539     replaceComponents(replacements);
    540 }
    541 
    542 void KURL::setQuery(const String& query)
    543 {
    544     StringUTF8Adaptor queryUTF8(query);
    545     url_canon::Replacements<char> replacements;
    546     if (query.isNull()) {
    547         // KURL.cpp sets to null to clear any query.
    548         replacements.ClearQuery();
    549     } else if (query.length() > 0 && query[0] == '?') {
    550         // WebCore expects the query string to begin with a question mark, but
    551         // GoogleURL doesn't. So we trim off the question mark when setting.
    552         replacements.SetQuery(charactersOrEmpty(queryUTF8), url_parse::Component(1, queryUTF8.length() - 1));
    553     } else {
    554         // When set with the empty string or something that doesn't begin with
    555         // a question mark, KURL.cpp will add a question mark for you. The only
    556         // way this isn't compatible is if you call this function with an empty
    557         // string. KURL.cpp will leave a '?' with nothing following it in the
    558         // URL, whereas we'll clear it.
    559         // FIXME We should eliminate this difference.
    560         replacements.SetQuery(charactersOrEmpty(queryUTF8), url_parse::Component(0, queryUTF8.length()));
    561     }
    562     replaceComponents(replacements);
    563 }
    564 
    565 void KURL::setPath(const String& path)
    566 {
    567     // Empty paths will be canonicalized to "/", so we don't have to worry
    568     // about calling ClearPath().
    569     StringUTF8Adaptor pathUTF8(path);
    570     url_canon::Replacements<char> replacements;
    571     replacements.SetPath(charactersOrEmpty(pathUTF8), url_parse::Component(0, pathUTF8.length()));
    572     replaceComponents(replacements);
    573 }
    574 
    575 String decodeURLEscapeSequences(const String& string)
    576 {
    577     return decodeURLEscapeSequences(string, UTF8Encoding());
    578 }
    579 
    580 // In KURL.cpp's implementation, this is called by every component getter.
    581 // It will unescape every character, including '\0'. This is scary, and may
    582 // cause security holes. We never call this function for components, and
    583 // just return the ASCII versions instead.
    584 //
    585 // This function is also used to decode javascript: URLs and as a general
    586 // purpose unescaping function.
    587 //
    588 // FIXME These should be merged to the KURL.cpp implementation.
    589 String decodeURLEscapeSequences(const String& string, const WTF::TextEncoding& encoding)
    590 {
    591     // FIXME We can probably use KURL.cpp's version of this function
    592     // without modification. However, I'm concerned about
    593     // https://bugs.webkit.org/show_bug.cgi?id=20559 so am keeping this old
    594     // custom code for now. Using their version will also fix the bug that
    595     // we ignore the encoding.
    596     //
    597     // FIXME b/1350291: This does not get called very often. We just convert
    598     // first to 8-bit UTF-8, then unescape, then back to 16-bit. This kind of
    599     // sucks, and we don't use the encoding properly, which will make some
    600     // obscure anchor navigations fail.
    601     StringUTF8Adaptor stringUTF8(string);
    602     url_canon::RawCanonOutputT<url_parse::UTF16Char> unescaped;
    603     url_util::DecodeURLEscapeSequences(stringUTF8.data(), stringUTF8.length(), &unescaped);
    604     return StringImpl::create8BitIfPossible(reinterpret_cast<UChar*>(unescaped.data()), unescaped.length());
    605 }
    606 
    607 String encodeWithURLEscapeSequences(const String& notEncodedString)
    608 {
    609     CString utf8 = UTF8Encoding().normalizeAndEncode(notEncodedString, WTF::URLEncodedEntitiesForUnencodables);
    610 
    611     url_canon::RawCanonOutputT<char> buffer;
    612     int inputLength = utf8.length();
    613     if (buffer.length() < inputLength * 3)
    614         buffer.Resize(inputLength * 3);
    615 
    616     url_util::EncodeURIComponent(utf8.data(), inputLength, &buffer);
    617     String escaped(buffer.data(), buffer.length());
    618     // Unescape '/'; it's safe and much prettier.
    619     escaped.replace("%2F", "/");
    620     return escaped;
    621 }
    622 
    623 bool KURL::isHierarchical() const
    624 {
    625     if (!m_parsed.scheme.is_nonempty())
    626         return false;
    627     if (!m_string.isNull() && m_string.is8Bit())
    628         return url_util::IsStandard(asURLChar8Subtle(m_string), m_parsed.scheme);
    629     return url_util::IsStandard(m_string.characters16(), m_parsed.scheme);
    630 }
    631 
    632 #ifndef NDEBUG
    633 void KURL::print() const
    634 {
    635     printf("%s\n", m_string.utf8().data());
    636 }
    637 #endif
    638 
    639 bool equalIgnoringFragmentIdentifier(const KURL& a, const KURL& b)
    640 {
    641     // Compute the length of each URL without its ref. Note that the reference
    642     // begin (if it exists) points to the character *after* the '#', so we need
    643     // to subtract one.
    644     int aLength = a.m_string.length();
    645     if (a.m_parsed.ref.len >= 0)
    646         aLength = a.m_parsed.ref.begin - 1;
    647 
    648     int bLength = b.m_string.length();
    649     if (b.m_parsed.ref.len >= 0)
    650         bLength = b.m_parsed.ref.begin - 1;
    651 
    652     if (aLength != bLength)
    653         return false;
    654 
    655     const String& aString = a.m_string;
    656     const String& bString = b.m_string;
    657     // FIXME: Abstraction this into a function in WTFString.h.
    658     for (int i = 0; i < aLength; ++i) {
    659         if (aString[i] != bString[i])
    660             return false;
    661     }
    662     return true;
    663 }
    664 
    665 unsigned KURL::hostStart() const
    666 {
    667     return m_parsed.CountCharactersBefore(url_parse::Parsed::HOST, false);
    668 }
    669 
    670 unsigned KURL::hostEnd() const
    671 {
    672     return m_parsed.CountCharactersBefore(url_parse::Parsed::PORT, true);
    673 }
    674 
    675 unsigned KURL::pathStart() const
    676 {
    677     return m_parsed.CountCharactersBefore(url_parse::Parsed::PATH, false);
    678 }
    679 
    680 unsigned KURL::pathEnd() const
    681 {
    682     return m_parsed.CountCharactersBefore(url_parse::Parsed::QUERY, true);
    683 }
    684 
    685 unsigned KURL::pathAfterLastSlash() const
    686 {
    687     if (!m_isValid || !m_parsed.path.is_valid())
    688         return m_parsed.CountCharactersBefore(url_parse::Parsed::PATH, false);
    689 
    690     url_parse::Component filename;
    691     if (!m_string.isNull() && m_string.is8Bit())
    692         url_parse::ExtractFileName(asURLChar8Subtle(m_string), m_parsed.path, &filename);
    693     else
    694         url_parse::ExtractFileName(m_string.characters16(), m_parsed.path, &filename);
    695     return filename.begin;
    696 }
    697 
    698 bool protocolIs(const String& url, const char* protocol)
    699 {
    700     assertProtocolIsGood(protocol);
    701     if (url.isNull())
    702         return false;
    703     if (url.is8Bit())
    704         return url_util::FindAndCompareScheme(asURLChar8Subtle(url), url.length(), protocol, 0);
    705     return url_util::FindAndCompareScheme(url.characters16(), url.length(), protocol, 0);
    706 }
    707 
    708 void KURL::init(const KURL& base, const String& relative, const WTF::TextEncoding* queryEncoding)
    709 {
    710     if (!relative.isNull() && relative.is8Bit()) {
    711         StringUTF8Adaptor relativeUTF8(relative);
    712         init(base, relativeUTF8.data(), relativeUTF8.length(), queryEncoding);
    713     } else
    714         init(base, relative.characters16(), relative.length(), queryEncoding);
    715     initProtocolIsInHTTPFamily();
    716     initInnerURL();
    717 }
    718 
    719 template <typename CHAR>
    720 void KURL::init(const KURL& base, const CHAR* relative, int relativeLength, const WTF::TextEncoding* queryEncoding)
    721 {
    722     // As a performance optimization, we do not use the charset converter
    723     // if encoding is UTF-8 or other Unicode encodings. Note that this is
    724     // per HTML5 2.5.3 (resolving URL). The URL canonicalizer will be more
    725     // efficient with no charset converter object because it can do UTF-8
    726     // internally with no extra copies.
    727 
    728     // We feel free to make the charset converter object every time since it's
    729     // just a wrapper around a reference.
    730     KURLCharsetConverter charsetConverterObject(queryEncoding);
    731     KURLCharsetConverter* charsetConverter = (!queryEncoding || isUnicodeEncoding(queryEncoding)) ? 0 : &charsetConverterObject;
    732 
    733     StringUTF8Adaptor baseUTF8(base.string());
    734 
    735     url_canon::RawCanonOutputT<char> output;
    736     m_isValid = url_util::ResolveRelative(baseUTF8.data(), baseUTF8.length(), base.m_parsed, relative, relativeLength, charsetConverter, &output, &m_parsed);
    737 
    738     // See FIXME in KURLPrivate in the header. If canonicalization has not
    739     // changed the string, we can avoid an extra allocation by using assignment.
    740     m_string = AtomicString::fromUTF8(output.data(), output.length());
    741 }
    742 
    743 void KURL::initInnerURL()
    744 {
    745     if (!m_isValid) {
    746         m_innerURL.clear();
    747         return;
    748     }
    749     if (url_parse::Parsed* innerParsed = m_parsed.inner_parsed())
    750         m_innerURL = adoptPtr(new KURL(ParsedURLString, m_string.substring(innerParsed->scheme.begin, innerParsed->Length() - innerParsed->scheme.begin)));
    751     else
    752         m_innerURL.clear();
    753 }
    754 
    755 template<typename CHAR>
    756 bool internalProtocolIs(const url_parse::Component& scheme, const CHAR* spec, const char* protocol)
    757 {
    758     const CHAR* begin = spec + scheme.begin;
    759     const CHAR* end = begin + scheme.len;
    760 
    761     while (begin != end && *protocol) {
    762         ASSERT(toASCIILower(*protocol) == *protocol);
    763         if (toASCIILower(*begin++) != *protocol++)
    764             return false;
    765     }
    766 
    767     // Both strings are equal (ignoring case) if and only if all of the characters were equal,
    768     // and the end of both has been reached.
    769     return begin == end && !*protocol;
    770 }
    771 
    772 template<typename CHAR>
    773 bool checkIfProtocolIsInHTTPFamily(const url_parse::Component& scheme, const CHAR* spec)
    774 {
    775     if (scheme.len == 4)
    776         return internalProtocolIs(scheme, spec, "http");
    777     if (scheme.len == 5)
    778         return internalProtocolIs(scheme, spec, "https");
    779     return false;
    780 }
    781 
    782 void KURL::initProtocolIsInHTTPFamily()
    783 {
    784     if (!m_isValid) {
    785         m_protocolIsInHTTPFamily = false;
    786         return;
    787     }
    788 
    789     if (!m_string.isNull() && m_string.is8Bit())
    790         m_protocolIsInHTTPFamily = checkIfProtocolIsInHTTPFamily(m_parsed.scheme, m_string.characters8());
    791     else
    792         m_protocolIsInHTTPFamily = checkIfProtocolIsInHTTPFamily(m_parsed.scheme, m_string.characters16());
    793 }
    794 
    795 bool KURL::protocolIs(const char* protocol) const
    796 {
    797     assertProtocolIsGood(protocol);
    798 
    799     // JavaScript URLs are "valid" and should be executed even if KURL decides they are invalid.
    800     // The free function protocolIsJavaScript() should be used instead.
    801     // FIXME: Chromium code needs to be fixed for this assert to be enabled. ASSERT(strcmp(protocol, "javascript"));
    802 
    803     if (m_parsed.scheme.len <= 0)
    804         return !protocol;
    805     if (!m_string.isNull() && m_string.is8Bit())
    806         return internalProtocolIs(m_parsed.scheme, m_string.characters8(), protocol);
    807     return internalProtocolIs(m_parsed.scheme, m_string.characters16(), protocol);
    808 }
    809 
    810 String KURL::stringForInvalidComponent() const
    811 {
    812     if (m_string.isNull())
    813         return String();
    814     return emptyString();
    815 }
    816 
    817 String KURL::componentString(const url_parse::Component& component) const
    818 {
    819     if (!m_isValid || component.len <= 0)
    820         return stringForInvalidComponent();
    821     // begin and len are in terms of bytes which do not match
    822     // if string() is UTF-16 and input contains non-ASCII characters.
    823     // However, the only part in urlString that can contain non-ASCII
    824     // characters is 'ref' at the end of the string. In that case,
    825     // begin will always match the actual value and len (in terms of
    826     // byte) will be longer than what's needed by 'mid'. However, mid
    827     // truncates len to avoid go past the end of a string so that we can
    828     // get away without doing anything here.
    829     return string().substring(component.begin, component.len);
    830 }
    831 
    832 template<typename CHAR>
    833 void KURL::replaceComponents(const url_canon::Replacements<CHAR>& replacements)
    834 {
    835     url_canon::RawCanonOutputT<char> output;
    836     url_parse::Parsed newParsed;
    837 
    838     StringUTF8Adaptor utf8(m_string);
    839     m_isValid = url_util::ReplaceComponents(utf8.data(), utf8.length(), m_parsed, replacements, 0, &output, &newParsed);
    840 
    841     m_parsed = newParsed;
    842     m_string = AtomicString::fromUTF8(output.data(), output.length());
    843 }
    844 
    845 bool KURL::isSafeToSendToAnotherThread() const
    846 {
    847     return m_string.isSafeToSendToAnotherThread()
    848         && (!m_innerURL || m_innerURL->isSafeToSendToAnotherThread());
    849 }
    850 
    851 } // namespace WebCore
    852