2 * Copyright (C) 2004, 2007, 2008 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #include "StringHash.h"
34 #include "TextEncoding.h"
35 #include <wtf/StdLibExtras.h>
38 #include <unicode/uidna.h>
39 #elif USE(QT4_UNICODE)
50 typedef Vector<char, 512> CharBuffer;
51 typedef Vector<UChar, 512> UCharBuffer;
53 // FIXME: This file makes too much use of the + operator on String.
54 // We either have to optimize that operator so it doesn't involve
55 // so many allocations, or change this to use Vector<UChar> instead.
57 enum URLCharacterClasses {
59 SchemeFirstChar = 1 << 0,
61 // ( alpha | digit | "+" | "-" | "." )
64 // mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
65 // unreserved = alphanum | mark
66 // ( unreserved | escaped | ";" | ":" | "&" | "=" | "+" | "$" | "," )
67 UserInfoChar = 1 << 2,
69 // alnum | "." | "-" | "%"
70 // The above is what the specification says, but we are lenient to
71 // match existing practice and also allow:
73 HostnameChar = 1 << 3,
75 // hexdigit | ":" | "%"
78 // "#" | "?" | "/" | nul
79 PathSegmentEndChar = 1 << 5,
81 // not allowed in path
85 static const char hexDigits[17] = "0123456789ABCDEF";
87 static const unsigned char characterClassTable[256] = {
88 /* 0 nul */ PathSegmentEndChar, /* 1 soh */ BadChar,
89 /* 2 stx */ BadChar, /* 3 etx */ BadChar,
90 /* 4 eot */ BadChar, /* 5 enq */ BadChar, /* 6 ack */ BadChar, /* 7 bel */ BadChar,
91 /* 8 bs */ BadChar, /* 9 ht */ BadChar, /* 10 nl */ BadChar, /* 11 vt */ BadChar,
92 /* 12 np */ BadChar, /* 13 cr */ BadChar, /* 14 so */ BadChar, /* 15 si */ BadChar,
93 /* 16 dle */ BadChar, /* 17 dc1 */ BadChar, /* 18 dc2 */ BadChar, /* 19 dc3 */ BadChar,
94 /* 20 dc4 */ BadChar, /* 21 nak */ BadChar, /* 22 syn */ BadChar, /* 23 etb */ BadChar,
95 /* 24 can */ BadChar, /* 25 em */ BadChar, /* 26 sub */ BadChar, /* 27 esc */ BadChar,
96 /* 28 fs */ BadChar, /* 29 gs */ BadChar, /* 30 rs */ BadChar, /* 31 us */ BadChar,
97 /* 32 sp */ BadChar, /* 33 ! */ UserInfoChar,
98 /* 34 " */ BadChar, /* 35 # */ PathSegmentEndChar | BadChar,
99 /* 36 $ */ UserInfoChar, /* 37 % */ UserInfoChar | HostnameChar | IPv6Char | BadChar,
100 /* 38 & */ UserInfoChar, /* 39 ' */ UserInfoChar,
101 /* 40 ( */ UserInfoChar, /* 41 ) */ UserInfoChar,
102 /* 42 * */ UserInfoChar, /* 43 + */ SchemeChar | UserInfoChar,
103 /* 44 , */ UserInfoChar,
104 /* 45 - */ SchemeChar | UserInfoChar | HostnameChar,
105 /* 46 . */ SchemeChar | UserInfoChar | HostnameChar,
106 /* 47 / */ PathSegmentEndChar,
107 /* 48 0 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
108 /* 49 1 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
109 /* 50 2 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
110 /* 51 3 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
111 /* 52 4 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
112 /* 53 5 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
113 /* 54 6 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
114 /* 55 7 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
115 /* 56 8 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
116 /* 57 9 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
117 /* 58 : */ UserInfoChar | IPv6Char, /* 59 ; */ UserInfoChar,
118 /* 60 < */ BadChar, /* 61 = */ UserInfoChar,
119 /* 62 > */ BadChar, /* 63 ? */ PathSegmentEndChar | BadChar,
121 /* 65 A */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
122 /* 66 B */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
123 /* 67 C */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
124 /* 68 D */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
125 /* 69 E */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
126 /* 70 F */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
127 /* 71 G */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
128 /* 72 H */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
129 /* 73 I */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
130 /* 74 J */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
131 /* 75 K */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
132 /* 76 L */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
133 /* 77 M */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
134 /* 78 N */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
135 /* 79 O */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
136 /* 80 P */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
137 /* 81 Q */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
138 /* 82 R */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
139 /* 83 S */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
140 /* 84 T */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
141 /* 85 U */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
142 /* 86 V */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
143 /* 87 W */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
144 /* 88 X */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
145 /* 89 Y */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
146 /* 90 Z */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
148 /* 92 \ */ 0, /* 93 ] */ 0,
150 /* 95 _ */ UserInfoChar | HostnameChar,
152 /* 97 a */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
153 /* 98 b */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
154 /* 99 c */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
155 /* 100 d */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
156 /* 101 e */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
157 /* 102 f */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
158 /* 103 g */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
159 /* 104 h */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
160 /* 105 i */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
161 /* 106 j */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
162 /* 107 k */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
163 /* 108 l */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
164 /* 109 m */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
165 /* 110 n */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
166 /* 111 o */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
167 /* 112 p */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
168 /* 113 q */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
169 /* 114 r */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
170 /* 115 s */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
171 /* 116 t */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
172 /* 117 u */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
173 /* 118 v */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
174 /* 119 w */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
175 /* 120 x */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
176 /* 121 y */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
177 /* 122 z */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
179 /* 124 | */ 0, /* 125 } */ 0, /* 126 ~ */ UserInfoChar, /* 127 del */ BadChar,
180 /* 128 */ BadChar, /* 129 */ BadChar, /* 130 */ BadChar, /* 131 */ BadChar,
181 /* 132 */ BadChar, /* 133 */ BadChar, /* 134 */ BadChar, /* 135 */ BadChar,
182 /* 136 */ BadChar, /* 137 */ BadChar, /* 138 */ BadChar, /* 139 */ BadChar,
183 /* 140 */ BadChar, /* 141 */ BadChar, /* 142 */ BadChar, /* 143 */ BadChar,
184 /* 144 */ BadChar, /* 145 */ BadChar, /* 146 */ BadChar, /* 147 */ BadChar,
185 /* 148 */ BadChar, /* 149 */ BadChar, /* 150 */ BadChar, /* 151 */ BadChar,
186 /* 152 */ BadChar, /* 153 */ BadChar, /* 154 */ BadChar, /* 155 */ BadChar,
187 /* 156 */ BadChar, /* 157 */ BadChar, /* 158 */ BadChar, /* 159 */ BadChar,
188 /* 160 */ BadChar, /* 161 */ BadChar, /* 162 */ BadChar, /* 163 */ BadChar,
189 /* 164 */ BadChar, /* 165 */ BadChar, /* 166 */ BadChar, /* 167 */ BadChar,
190 /* 168 */ BadChar, /* 169 */ BadChar, /* 170 */ BadChar, /* 171 */ BadChar,
191 /* 172 */ BadChar, /* 173 */ BadChar, /* 174 */ BadChar, /* 175 */ BadChar,
192 /* 176 */ BadChar, /* 177 */ BadChar, /* 178 */ BadChar, /* 179 */ BadChar,
193 /* 180 */ BadChar, /* 181 */ BadChar, /* 182 */ BadChar, /* 183 */ BadChar,
194 /* 184 */ BadChar, /* 185 */ BadChar, /* 186 */ BadChar, /* 187 */ BadChar,
195 /* 188 */ BadChar, /* 189 */ BadChar, /* 190 */ BadChar, /* 191 */ BadChar,
196 /* 192 */ BadChar, /* 193 */ BadChar, /* 194 */ BadChar, /* 195 */ BadChar,
197 /* 196 */ BadChar, /* 197 */ BadChar, /* 198 */ BadChar, /* 199 */ BadChar,
198 /* 200 */ BadChar, /* 201 */ BadChar, /* 202 */ BadChar, /* 203 */ BadChar,
199 /* 204 */ BadChar, /* 205 */ BadChar, /* 206 */ BadChar, /* 207 */ BadChar,
200 /* 208 */ BadChar, /* 209 */ BadChar, /* 210 */ BadChar, /* 211 */ BadChar,
201 /* 212 */ BadChar, /* 213 */ BadChar, /* 214 */ BadChar, /* 215 */ BadChar,
202 /* 216 */ BadChar, /* 217 */ BadChar, /* 218 */ BadChar, /* 219 */ BadChar,
203 /* 220 */ BadChar, /* 221 */ BadChar, /* 222 */ BadChar, /* 223 */ BadChar,
204 /* 224 */ BadChar, /* 225 */ BadChar, /* 226 */ BadChar, /* 227 */ BadChar,
205 /* 228 */ BadChar, /* 229 */ BadChar, /* 230 */ BadChar, /* 231 */ BadChar,
206 /* 232 */ BadChar, /* 233 */ BadChar, /* 234 */ BadChar, /* 235 */ BadChar,
207 /* 236 */ BadChar, /* 237 */ BadChar, /* 238 */ BadChar, /* 239 */ BadChar,
208 /* 240 */ BadChar, /* 241 */ BadChar, /* 242 */ BadChar, /* 243 */ BadChar,
209 /* 244 */ BadChar, /* 245 */ BadChar, /* 246 */ BadChar, /* 247 */ BadChar,
210 /* 248 */ BadChar, /* 249 */ BadChar, /* 250 */ BadChar, /* 251 */ BadChar,
211 /* 252 */ BadChar, /* 253 */ BadChar, /* 254 */ BadChar, /* 255 */ BadChar
214 static int copyPathRemovingDots(char* dst, const char* src, int srcStart, int srcEnd);
215 static void encodeRelativeString(const String& rel, const TextEncoding&, CharBuffer& ouput);
216 static String substituteBackslashes(const String&);
218 static inline bool isSchemeFirstChar(char c) { return characterClassTable[static_cast<unsigned char>(c)] & SchemeFirstChar; }
219 static inline bool isSchemeFirstChar(UChar c) { return c <= 0xff && (characterClassTable[c] & SchemeFirstChar); }
220 static inline bool isSchemeChar(char c) { return characterClassTable[static_cast<unsigned char>(c)] & SchemeChar; }
221 static inline bool isSchemeChar(UChar c) { return c <= 0xff && (characterClassTable[c] & SchemeChar); }
222 static inline bool isUserInfoChar(unsigned char c) { return characterClassTable[c] & UserInfoChar; }
223 static inline bool isHostnameChar(unsigned char c) { return characterClassTable[c] & HostnameChar; }
224 static inline bool isIPv6Char(unsigned char c) { return characterClassTable[c] & IPv6Char; }
225 static inline bool isPathSegmentEndChar(char c) { return characterClassTable[static_cast<unsigned char>(c)] & PathSegmentEndChar; }
226 static inline bool isPathSegmentEndChar(UChar c) { return c <= 0xff && (characterClassTable[c] & PathSegmentEndChar); }
227 static inline bool isBadChar(unsigned char c) { return characterClassTable[c] & BadChar; }
229 static inline int hexDigitValue(UChar c)
231 ASSERT(isASCIIHexDigit(c));
234 return (c - 'A' + 10) & 0xF; // handle both upper and lower case without a branch
237 // Copies the source to the destination, assuming all the source characters are
238 // ASCII. The destination buffer must be large enough. Null characters are allowed
239 // in the source string, and no attempt is made to null-terminate the result.
240 static void copyASCII(const UChar* src, int length, char* dest)
242 for (int i = 0; i < length; i++)
243 dest[i] = static_cast<char>(src[i]);
246 static void appendASCII(const String& base, const char* rel, size_t len, CharBuffer& buffer)
248 buffer.resize(base.length() + len + 1);
249 copyASCII(base.characters(), base.length(), buffer.data());
250 memcpy(buffer.data() + base.length(), rel, len);
251 buffer[buffer.size() - 1] = '\0';
254 // FIXME: Move to PlatformString.h eventually.
255 // Returns the index of the first index in string |s| of any of the characters
256 // in |toFind|. |toFind| should be a null-terminated string, all characters up
257 // to the null will be searched. Returns int if not found.
258 static int findFirstOf(const UChar* s, int sLen, int startPos, const char* toFind)
260 for (int i = startPos; i < sLen; i++) {
261 const char* cur = toFind;
263 if (s[i] == *(cur++))
271 static void checkEncodedString(const String& url)
273 for (unsigned i = 0; i < url.length(); ++i)
274 ASSERT(!(url[i] & ~0x7F));
276 ASSERT(!url.length() || isSchemeFirstChar(url[0]));
279 static inline void checkEncodedString(const String&)
284 inline bool KURL::protocolIs(const String& string, const char* protocol)
286 return WebCore::protocolIs(string, protocol);
289 void KURL::invalidate()
292 m_protocolInHTTPFamily = false;
300 m_pathAfterLastSlash = 0;
305 KURL::KURL(ParsedURLStringTag, const char* url)
308 ASSERT(url == m_string);
311 KURL::KURL(ParsedURLStringTag, const String& url)
314 ASSERT(url == m_string);
317 KURL::KURL(const KURL& base, const String& relative)
319 init(base, relative, UTF8Encoding());
322 KURL::KURL(const KURL& base, const String& relative, const TextEncoding& encoding)
324 // For UTF-{7,16,32}, we want to use UTF-8 for the query part as
325 // we do when submitting a form. A form with GET method
326 // has its contents added to a URL as query params and it makes sense
328 init(base, relative, encoding.encodingForFormSubmission());
331 void KURL::init(const KURL& base, const String& relative, const TextEncoding& encoding)
333 // Allow resolutions with a null or empty base URL, but not with any other invalid one.
334 // FIXME: Is this a good rule?
335 if (!base.m_isValid && !base.isEmpty()) {
341 // For compatibility with Win IE, treat backslashes as if they were slashes,
342 // as long as we're not dealing with javascript: or data: URLs.
343 String rel = relative;
344 if (rel.contains('\\') && !(protocolIsJavaScript(rel) || protocolIs(rel, "data")))
345 rel = substituteBackslashes(rel);
347 String* originalString = &rel;
349 bool allASCII = charactersAreAllASCII(rel.characters(), rel.length());
350 CharBuffer strBuffer;
355 strBuffer.resize(len + 1);
356 copyASCII(rel.characters(), len, strBuffer.data());
358 str = strBuffer.data();
361 encodeRelativeString(rel, encoding, strBuffer);
362 str = strBuffer.data();
366 // Get rid of leading whitespace.
367 while (*str == ' ') {
373 // Get rid of trailing whitespace.
374 while (len && str[len - 1] == ' ') {
379 // According to the RFC, the reference should be interpreted as an
380 // absolute URI if possible, using the "leftmost, longest"
381 // algorithm. If the URI reference is absolute it will have a
382 // scheme, meaning that it will have a colon before the first
383 // non-scheme element.
384 bool absolute = false;
386 if (isSchemeFirstChar(*p)) {
388 while (isSchemeChar(*p)) {
392 if (p[1] != '/' && equalIgnoringCase(base.protocol(), String(str, p - str)) && base.isHierarchical()) {
400 CharBuffer parseBuffer;
403 parse(str, originalString);
405 // If the base is empty or opaque (e.g. data: or javascript:), then the URL is invalid
406 // unless the relative URL is a single fragment.
407 if (!base.isHierarchical()) {
409 appendASCII(base.m_string.left(base.m_queryEnd), str, len, parseBuffer);
410 parse(parseBuffer.data(), 0);
420 // the reference must be empty - the RFC says this is a
421 // reference to the same document
425 // must be fragment-only reference
426 appendASCII(base.m_string.left(base.m_queryEnd), str, len, parseBuffer);
427 parse(parseBuffer.data(), 0);
431 // query-only reference, special case needed for non-URL results
432 appendASCII(base.m_string.left(base.m_pathEnd), str, len, parseBuffer);
433 parse(parseBuffer.data(), 0);
437 // must be net-path or absolute-path reference
440 appendASCII(base.m_string.left(base.m_schemeEnd + 1), str, len, parseBuffer);
441 parse(parseBuffer.data(), 0);
444 appendASCII(base.m_string.left(base.m_portEnd), str, len, parseBuffer);
445 parse(parseBuffer.data(), 0);
450 // must be relative-path reference
452 // Base part plus relative part plus one possible slash added in between plus terminating \0 byte.
453 parseBuffer.resize(base.m_pathEnd + 1 + len + 1);
455 char* bufferPos = parseBuffer.data();
457 // first copy everything before the path from the base
458 unsigned baseLength = base.m_string.length();
459 const UChar* baseCharacters = base.m_string.characters();
460 CharBuffer baseStringBuffer(baseLength);
461 copyASCII(baseCharacters, baseLength, baseStringBuffer.data());
462 const char* baseString = baseStringBuffer.data();
463 const char* baseStringStart = baseString;
464 const char* pathStart = baseStringStart + base.m_portEnd;
465 while (baseStringStart < pathStart)
466 *bufferPos++ = *baseStringStart++;
467 char* bufferPathStart = bufferPos;
469 // now copy the base path
470 const char* baseStringEnd = baseString + base.m_pathEnd;
472 // go back to the last slash
473 while (baseStringEnd > baseStringStart && baseStringEnd[-1] != '/')
476 if (baseStringEnd == baseStringStart) {
477 // no path in base, add a path separator if necessary
478 if (base.m_schemeEnd + 1 != base.m_pathEnd && *str && *str != '?' && *str != '#')
481 bufferPos += copyPathRemovingDots(bufferPos, baseStringStart, 0, baseStringEnd - baseStringStart);
484 const char* relStringStart = str;
485 const char* relStringPos = relStringStart;
487 while (*relStringPos && *relStringPos != '?' && *relStringPos != '#') {
488 if (relStringPos[0] == '.' && bufferPos[-1] == '/') {
489 if (isPathSegmentEndChar(relStringPos[1])) {
490 // skip over "." segment
492 if (relStringPos[0] == '/')
495 } else if (relStringPos[1] == '.' && isPathSegmentEndChar(relStringPos[2])) {
496 // skip over ".." segment and rewind the last segment
497 // the RFC leaves it up to the app to decide what to do with excess
498 // ".." segments - we choose to drop them since some web content
501 if (relStringPos[0] == '/')
503 if (bufferPos > bufferPathStart + 1)
505 while (bufferPos > bufferPathStart + 1 && bufferPos[-1] != '/')
511 *bufferPos = *relStringPos;
516 // all done with the path work, now copy any remainder
517 // of the relative reference; this will also add a null terminator
518 strcpy(bufferPos, relStringPos);
520 parse(parseBuffer.data(), 0);
522 ASSERT(strlen(parseBuffer.data()) + 1 <= parseBuffer.size());
529 KURL KURL::copy() const
532 result.m_string = result.m_string.crossThreadString();
536 bool KURL::hasPath() const
538 return m_pathEnd != m_portEnd;
541 String KURL::lastPathComponent() const
546 int end = m_pathEnd - 1;
547 if (m_string[end] == '/')
550 int start = m_string.reverseFind('/', end);
551 if (start < m_portEnd)
555 return m_string.substring(start, end - start + 1);
558 String KURL::protocol() const
560 return m_string.left(m_schemeEnd);
563 String KURL::host() const
565 int start = hostStart();
566 return decodeURLEscapeSequences(m_string.substring(start, m_hostEnd - start));
569 unsigned short KURL::port() const
571 if (m_hostEnd == m_portEnd)
574 int number = m_string.substring(m_hostEnd + 1, m_portEnd - m_hostEnd - 1).toInt();
575 if (number < 0 || number > 0xFFFF)
580 String KURL::pass() const
582 if (m_passwordEnd == m_userEnd)
585 return decodeURLEscapeSequences(m_string.substring(m_userEnd + 1, m_passwordEnd - m_userEnd - 1));
588 String KURL::user() const
590 return decodeURLEscapeSequences(m_string.substring(m_userStart, m_userEnd - m_userStart));
593 String KURL::fragmentIdentifier() const
595 if (m_fragmentEnd == m_queryEnd)
598 return m_string.substring(m_queryEnd + 1, m_fragmentEnd - (m_queryEnd + 1));
601 bool KURL::hasFragmentIdentifier() const
603 return m_fragmentEnd != m_queryEnd;
606 String KURL::baseAsString() const
608 return m_string.left(m_pathAfterLastSlash);
613 static inline void assertProtocolIsGood(const char*)
619 static void assertProtocolIsGood(const char* protocol)
621 const char* p = protocol;
623 ASSERT(*p > ' ' && *p < 0x7F && !(*p >= 'A' && *p <= 'Z'));
630 bool KURL::protocolIs(const char* protocol) const
632 assertProtocolIsGood(protocol);
634 // JavaScript URLs are "valid" and should be executed even if KURL decides they are invalid.
635 // The free function protocolIsJavaScript() should be used instead.
636 ASSERT(!equalIgnoringCase(protocol, String("javascript")));
641 // Do the comparison without making a new string object.
642 for (int i = 0; i < m_schemeEnd; ++i) {
643 if (!protocol[i] || toASCIILower(m_string[i]) != protocol[i])
646 return !protocol[m_schemeEnd]; // We should have consumed all characters in the argument.
649 String KURL::query() const
651 if (m_queryEnd == m_pathEnd)
654 return m_string.substring(m_pathEnd + 1, m_queryEnd - (m_pathEnd + 1));
657 String KURL::path() const
659 return decodeURLEscapeSequences(m_string.substring(m_portEnd, m_pathEnd - m_portEnd));
662 void KURL::setProtocol(const String& s)
664 // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations,
665 // and to avoid changing more than just the protocol.
668 parse(s + ":" + m_string);
672 parse(s + m_string.substring(m_schemeEnd));
675 void KURL::setHost(const String& s)
680 // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations,
681 // and to avoid changing more than just the host.
683 bool slashSlashNeeded = m_userStart == m_schemeEnd + 1;
685 parse(m_string.left(hostStart()) + (slashSlashNeeded ? "//" : "") + s + m_string.substring(m_hostEnd));
688 void KURL::removePort()
690 if (m_hostEnd == m_portEnd)
692 parse(m_string.left(m_hostEnd) + m_string.substring(m_portEnd));
695 void KURL::setPort(unsigned short i)
700 bool colonNeeded = m_portEnd == m_hostEnd;
701 int portStart = (colonNeeded ? m_hostEnd : m_hostEnd + 1);
703 parse(m_string.left(portStart) + (colonNeeded ? ":" : "") + String::number(i) + m_string.substring(m_portEnd));
706 void KURL::setHostAndPort(const String& hostAndPort)
711 // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations,
712 // and to avoid changing more than just host and port.
714 bool slashSlashNeeded = m_userStart == m_schemeEnd + 1;
716 parse(m_string.left(hostStart()) + (slashSlashNeeded ? "//" : "") + hostAndPort + m_string.substring(m_portEnd));
719 void KURL::setUser(const String& user)
724 // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations,
725 // and to avoid changing more than just the user login.
728 if (!user.isEmpty()) {
730 if (m_userStart == m_schemeEnd + 1)
732 // Add '@' if we didn't have one before.
733 if (end == m_hostEnd || (end == m_passwordEnd && m_string[end] != '@'))
736 // Remove '@' if we now have neither user nor password.
737 if (m_userEnd == m_passwordEnd && end != m_hostEnd && m_string[end] == '@')
740 parse(m_string.left(m_userStart) + u + m_string.substring(end));
743 void KURL::setPass(const String& password)
748 // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations,
749 // and to avoid changing more than just the user password.
751 int end = m_passwordEnd;
752 if (!password.isEmpty()) {
753 p = ":" + password + "@";
754 if (m_userEnd == m_schemeEnd + 1)
756 // Eat the existing '@' since we are going to add our own.
757 if (end != m_hostEnd && m_string[end] == '@')
760 // Remove '@' if we now have neither user nor password.
761 if (m_userStart == m_userEnd && end != m_hostEnd && m_string[end] == '@')
764 parse(m_string.left(m_userEnd) + p + m_string.substring(end));
767 void KURL::setFragmentIdentifier(const String& s)
772 // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations.
773 parse(m_string.left(m_queryEnd) + "#" + s);
776 void KURL::removeFragmentIdentifier()
780 parse(m_string.left(m_queryEnd));
783 void KURL::setQuery(const String& query)
788 // FIXME: '#' and non-ASCII characters must be encoded and escaped.
789 // Usually, the query is encoded using document encoding, not UTF-8, but we don't have
790 // access to the document in this function.
791 if ((query.isEmpty() || query[0] != '?') && !query.isNull())
792 parse(m_string.left(m_pathEnd) + "?" + query + m_string.substring(m_queryEnd));
794 parse(m_string.left(m_pathEnd) + query + m_string.substring(m_queryEnd));
798 void KURL::setPath(const String& s)
803 // FIXME: encodeWithURLEscapeSequences does not correctly escape '#' and '?', so fragment and query parts
804 // may be inadvertently affected.
805 parse(m_string.left(m_portEnd) + encodeWithURLEscapeSequences(s) + m_string.substring(m_pathEnd));
808 String KURL::prettyURL() const
813 Vector<UChar> result;
815 append(result, protocol());
818 Vector<UChar> authority;
820 if (m_hostEnd != m_passwordEnd) {
821 if (m_userEnd != m_userStart) {
822 append(authority, user());
823 authority.append('@');
825 append(authority, host());
827 authority.append(':');
828 append(authority, String::number(port()));
832 if (!authority.isEmpty()) {
835 result.append(authority);
836 } else if (protocolIs("file")) {
841 append(result, path());
843 if (m_pathEnd != m_queryEnd) {
845 append(result, query());
848 if (m_fragmentEnd != m_queryEnd) {
850 append(result, fragmentIdentifier());
853 return String::adopt(result);
856 String decodeURLEscapeSequences(const String& str)
858 return decodeURLEscapeSequences(str, UTF8Encoding());
861 String decodeURLEscapeSequences(const String& str, const TextEncoding& encoding)
863 Vector<UChar> result;
867 int length = str.length();
868 int decodedPosition = 0;
869 int searchPosition = 0;
870 int encodedRunPosition;
871 while ((encodedRunPosition = str.find('%', searchPosition)) >= 0) {
872 // Find the sequence of %-escape codes.
873 int encodedRunEnd = encodedRunPosition;
874 while (length - encodedRunEnd >= 3
875 && str[encodedRunEnd] == '%'
876 && isASCIIHexDigit(str[encodedRunEnd + 1])
877 && isASCIIHexDigit(str[encodedRunEnd + 2]))
879 if (encodedRunEnd == encodedRunPosition) {
883 searchPosition = encodedRunEnd;
885 // Decode the %-escapes into bytes.
886 unsigned runLength = (encodedRunEnd - encodedRunPosition) / 3;
887 buffer.resize(runLength);
888 char* p = buffer.data();
889 const UChar* q = str.characters() + encodedRunPosition;
890 for (unsigned i = 0; i < runLength; ++i) {
891 *p++ = (hexDigitValue(q[1]) << 4) | hexDigitValue(q[2]);
895 // Decode the bytes into Unicode characters.
896 String decoded = (encoding.isValid() ? encoding : UTF8Encoding()).decode(buffer.data(), p - buffer.data());
897 if (decoded.isEmpty())
900 // Build up the string with what we just skipped and what we just decoded.
901 result.append(str.characters() + decodedPosition, encodedRunPosition - decodedPosition);
902 result.append(decoded.characters(), decoded.length());
903 decodedPosition = encodedRunEnd;
906 result.append(str.characters() + decodedPosition, length - decodedPosition);
908 return String::adopt(result);
911 bool KURL::isLocalFile() const
913 // Including feed here might be a bad idea since drag and drop uses this check
914 // and including feed would allow feeds to potentially let someone's blog
915 // read the contents of the clipboard on a drag, even without a drop.
916 // Likewise with using the FrameLoader::shouldTreatURLAsLocal() function.
917 return protocolIs("file");
920 static void appendEscapingBadChars(char*& buffer, const char* strStart, size_t length)
924 const char* str = strStart;
925 const char* strEnd = strStart + length;
926 while (str < strEnd) {
927 unsigned char c = *str++;
929 if (c == '%' || c == '?') {
931 } else if (c != 0x09 && c != 0x0a && c != 0x0d) {
933 *p++ = hexDigits[c >> 4];
934 *p++ = hexDigits[c & 0xF];
944 // copy a path, accounting for "." and ".." segments
945 static int copyPathRemovingDots(char* dst, const char* src, int srcStart, int srcEnd)
947 char* bufferPathStart = dst;
949 // empty path is a special case, and need not have a leading slash
950 if (srcStart != srcEnd) {
951 const char* baseStringStart = src + srcStart;
952 const char* baseStringEnd = src + srcEnd;
953 const char* baseStringPos = baseStringStart;
955 // this code is unprepared for paths that do not begin with a
956 // slash and we should always have one in the source string
957 ASSERT(baseStringPos[0] == '/');
959 // copy the leading slash into the destination
960 *dst = *baseStringPos;
964 while (baseStringPos < baseStringEnd) {
965 if (baseStringPos[0] == '.' && dst[-1] == '/') {
966 if (baseStringPos[1] == '/' || baseStringPos + 1 == baseStringEnd) {
967 // skip over "." segment
970 } else if (baseStringPos[1] == '.' && (baseStringPos[2] == '/' ||
971 baseStringPos + 2 == baseStringEnd)) {
972 // skip over ".." segment and rewind the last segment
973 // the RFC leaves it up to the app to decide what to do with excess
974 // ".." segments - we choose to drop them since some web content
977 if (dst > bufferPathStart + 1)
979 // Note that these two while blocks differ subtly.
980 // The first helps to remove multiple adjoining slashes as we rewind.
981 // The +1 to bufferPathStart in the first while block prevents eating a leading slash
982 while (dst > bufferPathStart + 1 && dst[-1] == '/')
984 while (dst > bufferPathStart && dst[-1] != '/')
990 *dst = *baseStringPos;
996 return dst - bufferPathStart;
999 static inline bool hasSlashDotOrDotDot(const char* str)
1001 const unsigned char* p = reinterpret_cast<const unsigned char*>(str);
1004 unsigned char pc = *p;
1005 while (unsigned char c = *++p) {
1006 if (c == '.' && (pc == '/' || pc == '.'))
1013 static inline bool matchLetter(char c, char lowercaseLetter)
1015 return (c | 0x20) == lowercaseLetter;
1018 void KURL::parse(const String& string)
1020 checkEncodedString(string);
1022 CharBuffer buffer(string.length() + 1);
1023 copyASCII(string.characters(), string.length(), buffer.data());
1024 buffer[string.length()] = '\0';
1025 parse(buffer.data(), &string);
1028 void KURL::parse(const char* url, const String* originalString)
1030 if (!url || url[0] == '\0') {
1031 // valid URL must be non-empty
1032 m_string = originalString ? *originalString : url;
1037 if (!isSchemeFirstChar(url[0])) {
1038 // scheme must start with an alphabetic character
1039 m_string = originalString ? *originalString : url;
1045 while (isSchemeChar(url[schemeEnd]))
1048 if (url[schemeEnd] != ':') {
1049 m_string = originalString ? *originalString : url;
1054 int userStart = schemeEnd + 1;
1063 bool hierarchical = url[schemeEnd + 1] == '/';
1065 bool isFile = schemeEnd == 4
1066 && matchLetter(url[0], 'f')
1067 && matchLetter(url[1], 'i')
1068 && matchLetter(url[2], 'l')
1069 && matchLetter(url[3], 'e');
1071 m_protocolInHTTPFamily = matchLetter(url[0], 'h')
1072 && matchLetter(url[1], 't')
1073 && matchLetter(url[2], 't')
1074 && matchLetter(url[3], 'p')
1075 && (url[4] == ':' || (matchLetter(url[4], 's') && url[5] == ':'));
1077 if (hierarchical && url[schemeEnd + 2] == '/') {
1078 // The part after the scheme is either a net_path or an abs_path whose first path segment is empty.
1079 // Attempt to find an authority.
1081 // FIXME: Authority characters may be scanned twice, and it would be nice to be faster.
1083 userEnd = userStart;
1086 while (isUserInfoChar(url[userEnd])) {
1087 if (url[userEnd] == ':' && colonPos == 0)
1092 if (url[userEnd] == '@') {
1093 // actual end of the userinfo, start on the host
1094 if (colonPos != 0) {
1095 passwordEnd = userEnd;
1097 passwordStart = colonPos + 1;
1099 passwordStart = passwordEnd = userEnd;
1101 hostStart = passwordEnd + 1;
1102 } else if (url[userEnd] == '[' || isPathSegmentEndChar(url[userEnd])) {
1103 // hit the end of the authority, must have been no user
1104 // or looks like an IPv6 hostname
1105 // either way, try to parse it as a hostname
1106 userEnd = userStart;
1107 passwordStart = passwordEnd = userEnd;
1108 hostStart = userStart;
1110 // invalid character
1111 m_string = originalString ? *originalString : url;
1116 hostEnd = hostStart;
1119 if (url[hostEnd] == '[') {
1121 while (isIPv6Char(url[hostEnd]))
1123 if (url[hostEnd] == ']')
1126 // invalid character
1127 m_string = originalString ? *originalString : url;
1132 while (isHostnameChar(url[hostEnd]))
1136 if (url[hostEnd] == ':') {
1137 portStart = portEnd = hostEnd + 1;
1139 // possible start of port
1140 portEnd = portStart;
1141 while (isASCIIDigit(url[portEnd]))
1144 portStart = portEnd = hostEnd;
1146 if (!isPathSegmentEndChar(url[portEnd])) {
1147 // invalid character
1148 m_string = originalString ? *originalString : url;
1153 if (userStart == portEnd && !m_protocolInHTTPFamily && !isFile) {
1154 // No authority found, which means that this is not a net_path, but rather an abs_path whose first two
1155 // path segments are empty. For file, http and https only, an empty authority is allowed.
1157 userEnd = userStart;
1158 passwordStart = userEnd;
1159 passwordEnd = passwordStart;
1160 hostStart = passwordEnd;
1161 hostEnd = hostStart;
1162 portStart = hostEnd;
1166 // the part after the scheme must be an opaque_part or an abs_path
1167 userEnd = userStart;
1168 passwordStart = passwordEnd = userEnd;
1169 hostStart = hostEnd = passwordEnd;
1170 portStart = portEnd = hostEnd;
1173 int pathStart = portEnd;
1174 int pathEnd = pathStart;
1175 while (url[pathEnd] && url[pathEnd] != '?' && url[pathEnd] != '#')
1178 int queryStart = pathEnd;
1179 int queryEnd = queryStart;
1180 if (url[queryStart] == '?') {
1181 while (url[queryEnd] && url[queryEnd] != '#')
1185 int fragmentStart = queryEnd;
1186 int fragmentEnd = fragmentStart;
1187 if (url[fragmentStart] == '#') {
1189 fragmentEnd = fragmentStart;
1190 while (url[fragmentEnd])
1194 // assemble it all, remembering the real ranges
1196 Vector<char, 4096> buffer(fragmentEnd * 3 + 1);
1198 char *p = buffer.data();
1199 const char *strPtr = url;
1201 // copy in the scheme
1202 const char *schemeEndPtr = url + schemeEnd;
1203 while (strPtr < schemeEndPtr)
1205 m_schemeEnd = p - buffer.data();
1207 bool hostIsLocalHost = portEnd - userStart == 9
1208 && matchLetter(url[userStart], 'l')
1209 && matchLetter(url[userStart+1], 'o')
1210 && matchLetter(url[userStart+2], 'c')
1211 && matchLetter(url[userStart+3], 'a')
1212 && matchLetter(url[userStart+4], 'l')
1213 && matchLetter(url[userStart+5], 'h')
1214 && matchLetter(url[userStart+6], 'o')
1215 && matchLetter(url[userStart+7], 's')
1216 && matchLetter(url[userStart+8], 't');
1218 // File URLs need a host part unless it is just file:// or file://localhost
1219 bool degenFilePath = pathStart == pathEnd && (hostStart == hostEnd || hostIsLocalHost);
1221 bool haveNonHostAuthorityPart = userStart != userEnd || passwordStart != passwordEnd || portStart != portEnd;
1223 // add ":" after scheme
1226 // if we have at least one authority part or a file URL - add "//" and authority
1227 if (isFile ? !degenFilePath : (haveNonHostAuthorityPart || hostStart != hostEnd)) {
1231 m_userStart = p - buffer.data();
1234 strPtr = url + userStart;
1235 const char* userEndPtr = url + userEnd;
1236 while (strPtr < userEndPtr)
1238 m_userEnd = p - buffer.data();
1240 // copy in the password
1241 if (passwordEnd != passwordStart) {
1243 strPtr = url + passwordStart;
1244 const char* passwordEndPtr = url + passwordEnd;
1245 while (strPtr < passwordEndPtr)
1248 m_passwordEnd = p - buffer.data();
1250 // If we had any user info, add "@"
1251 if (p - buffer.data() != m_userStart)
1254 // copy in the host, except in the case of a file URL with authority="localhost"
1255 if (!(isFile && hostIsLocalHost && !haveNonHostAuthorityPart)) {
1256 strPtr = url + hostStart;
1257 const char* hostEndPtr = url + hostEnd;
1258 while (strPtr < hostEndPtr)
1261 m_hostEnd = p - buffer.data();
1264 if (hostEnd != portStart) {
1266 strPtr = url + portStart;
1267 const char *portEndPtr = url + portEnd;
1268 while (strPtr < portEndPtr)
1271 m_portEnd = p - buffer.data();
1273 m_userStart = m_userEnd = m_passwordEnd = m_hostEnd = m_portEnd = p - buffer.data();
1275 // For canonicalization, ensure we have a '/' for no path.
1276 // Do this only for hierarchical URL with protocol http or https.
1277 if (m_protocolInHTTPFamily && hierarchical && pathEnd == pathStart)
1280 // add path, escaping bad characters
1281 if (!hierarchical || !hasSlashDotOrDotDot(url))
1282 appendEscapingBadChars(p, url + pathStart, pathEnd - pathStart);
1284 CharBuffer pathBuffer(pathEnd - pathStart + 1);
1285 size_t length = copyPathRemovingDots(pathBuffer.data(), url, pathStart, pathEnd);
1286 appendEscapingBadChars(p, pathBuffer.data(), length);
1289 m_pathEnd = p - buffer.data();
1291 // Find the position after the last slash in the path, or
1292 // the position before the path if there are no slashes in it.
1294 for (i = m_pathEnd; i > m_portEnd; --i) {
1295 if (buffer[i - 1] == '/')
1298 m_pathAfterLastSlash = i;
1300 // add query, escaping bad characters
1301 appendEscapingBadChars(p, url + queryStart, queryEnd - queryStart);
1302 m_queryEnd = p - buffer.data();
1304 // add fragment, escaping bad characters
1305 if (fragmentEnd != queryEnd) {
1307 appendEscapingBadChars(p, url + fragmentStart, fragmentEnd - fragmentStart);
1309 m_fragmentEnd = p - buffer.data();
1311 ASSERT(p - buffer.data() <= static_cast<int>(buffer.size()));
1313 // If we didn't end up actually changing the original string and
1314 // it was already in a String, reuse it to avoid extra allocation.
1315 if (originalString && originalString->length() == static_cast<unsigned>(m_fragmentEnd) && strncmp(buffer.data(), url, m_fragmentEnd) == 0)
1316 m_string = *originalString;
1318 m_string = String(buffer.data(), m_fragmentEnd);
1323 bool equalIgnoringFragmentIdentifier(const KURL& a, const KURL& b)
1325 if (a.m_queryEnd != b.m_queryEnd)
1327 unsigned queryLength = a.m_queryEnd;
1328 for (unsigned i = 0; i < queryLength; ++i)
1329 if (a.string()[i] != b.string()[i])
1334 bool protocolHostAndPortAreEqual(const KURL& a, const KURL& b)
1336 if (a.m_schemeEnd != b.m_schemeEnd)
1338 int hostStartA = a.hostStart();
1339 int hostStartB = b.hostStart();
1340 if (a.m_hostEnd - hostStartA != b.m_hostEnd - hostStartB)
1344 for (int i = 0; i < a.m_schemeEnd; ++i)
1345 if (a.string()[i] != b.string()[i])
1349 for (int i = hostStartA; i < a.m_hostEnd; ++i)
1350 if (a.string()[i] != b.string()[i])
1353 if (a.port() != b.port())
1360 String encodeWithURLEscapeSequences(const String& notEncodedString)
1362 CString asUTF8 = notEncodedString.utf8();
1364 CharBuffer buffer(asUTF8.length() * 3 + 1);
1365 char* p = buffer.data();
1367 const char* str = asUTF8.data();
1368 const char* strEnd = str + asUTF8.length();
1369 while (str < strEnd) {
1370 unsigned char c = *str++;
1373 *p++ = hexDigits[c >> 4];
1374 *p++ = hexDigits[c & 0xF];
1379 ASSERT(p - buffer.data() <= static_cast<int>(buffer.size()));
1381 return String(buffer.data(), p - buffer.data());
1384 // Appends the punycoded hostname identified by the given string and length to
1385 // the output buffer. The result will not be null terminated.
1386 static void appendEncodedHostname(UCharBuffer& buffer, const UChar* str, unsigned strLen)
1388 // Needs to be big enough to hold an IDN-encoded name.
1389 // For host names bigger than this, we won't do IDN encoding, which is almost certainly OK.
1390 const unsigned hostnameBufferLength = 2048;
1392 if (strLen > hostnameBufferLength || charactersAreAllASCII(str, strLen)) {
1393 buffer.append(str, strLen);
1397 #if USE(ICU_UNICODE)
1398 UChar hostnameBuffer[hostnameBufferLength];
1399 UErrorCode error = U_ZERO_ERROR;
1400 int32_t numCharactersConverted = uidna_IDNToASCII(str, strLen, hostnameBuffer,
1401 hostnameBufferLength, UIDNA_ALLOW_UNASSIGNED, 0, &error);
1402 if (error == U_ZERO_ERROR)
1403 buffer.append(hostnameBuffer, numCharactersConverted);
1404 #elif USE(QT4_UNICODE)
1405 QByteArray result = QUrl::toAce(String(str, strLen));
1406 buffer.append(result.constData(), result.length());
1410 static void findHostnamesInMailToURL(const UChar* str, int strLen, Vector<pair<int, int> >& nameRanges)
1412 // In a mailto: URL, host names come after a '@' character and end with a '>' or ',' or '?' or end of string character.
1413 // Skip quoted strings so that characters in them don't confuse us.
1414 // When we find a '?' character, we are past the part of the URL that contains host names.
1420 // Find start of host name or of quoted string.
1421 int hostnameOrStringStart = findFirstOf(str, strLen, p, "\"@?");
1422 if (hostnameOrStringStart == -1)
1424 UChar c = str[hostnameOrStringStart];
1425 p = hostnameOrStringStart + 1;
1431 // Find end of host name.
1432 int hostnameStart = p;
1433 int hostnameEnd = findFirstOf(str, strLen, p, ">,?");
1435 if (hostnameEnd == -1) {
1436 hostnameEnd = strLen;
1443 nameRanges.append(make_pair(hostnameStart, hostnameEnd));
1448 // Skip quoted string.
1451 int escapedCharacterOrStringEnd = findFirstOf(str, strLen, p, "\"\\");
1452 if (escapedCharacterOrStringEnd == -1)
1455 c = str[escapedCharacterOrStringEnd];
1456 p = escapedCharacterOrStringEnd + 1;
1458 // If we are the end of the string, then break from the string loop back to the host name loop.
1462 // Skip escaped character.
1473 static bool findHostnameInHierarchicalURL(const UChar* str, int strLen, int& startOffset, int& endOffset)
1475 // Find the host name in a hierarchical URL.
1476 // It comes after a "://" sequence, with scheme characters preceding, and
1477 // this should be the first colon in the string.
1478 // It ends with the end of the string or a ":" or a path segment ending character.
1479 // If there is a "@" character, the host part is just the part after the "@".
1480 int separator = findFirstOf(str, strLen, 0, ":");
1481 if (separator == -1 || separator + 2 >= strLen ||
1482 str[separator + 1] != '/' || str[separator + 2] != '/')
1485 // Check that all characters before the :// are valid scheme characters.
1486 if (!isSchemeFirstChar(str[0]))
1488 for (int i = 1; i < separator; ++i) {
1489 if (!isSchemeChar(str[i]))
1493 // Start after the separator.
1494 int authorityStart = separator + 3;
1496 // Find terminating character.
1497 int hostnameEnd = strLen;
1498 for (int i = authorityStart; i < strLen; ++i) {
1500 if (c == ':' || (isPathSegmentEndChar(c) && c != 0)) {
1506 // Find "@" for the start of the host name.
1507 int userInfoTerminator = findFirstOf(str, strLen, authorityStart, "@");
1509 if (userInfoTerminator == -1 || userInfoTerminator > hostnameEnd)
1510 hostnameStart = authorityStart;
1512 hostnameStart = userInfoTerminator + 1;
1514 startOffset = hostnameStart;
1515 endOffset = hostnameEnd;
1519 // Converts all hostnames found in the given input to punycode, preserving the
1520 // rest of the URL unchanged. The output will NOT be null-terminated.
1521 static void encodeHostnames(const String& str, UCharBuffer& output)
1525 if (protocolIs(str, "mailto")) {
1526 Vector<pair<int, int> > hostnameRanges;
1527 findHostnamesInMailToURL(str.characters(), str.length(), hostnameRanges);
1528 int n = hostnameRanges.size();
1530 for (int i = 0; i < n; ++i) {
1531 const pair<int, int>& r = hostnameRanges[i];
1532 output.append(&str.characters()[p], r.first - p);
1533 appendEncodedHostname(output, &str.characters()[r.first], r.second - r.first);
1536 // This will copy either everything after the last hostname, or the
1537 // whole thing if there is no hostname.
1538 output.append(&str.characters()[p], str.length() - p);
1540 int hostStart, hostEnd;
1541 if (findHostnameInHierarchicalURL(str.characters(), str.length(), hostStart, hostEnd)) {
1542 output.append(str.characters(), hostStart); // Before hostname.
1543 appendEncodedHostname(output, &str.characters()[hostStart], hostEnd - hostStart);
1544 output.append(&str.characters()[hostEnd], str.length() - hostEnd); // After hostname.
1546 // No hostname to encode, return the input.
1547 output.append(str.characters(), str.length());
1552 static void encodeRelativeString(const String& rel, const TextEncoding& encoding, CharBuffer& output)
1555 encodeHostnames(rel, s);
1557 TextEncoding pathEncoding(UTF8Encoding()); // Path is always encoded as UTF-8; other parts may depend on the scheme.
1560 if (encoding != pathEncoding && encoding.isValid() && !protocolIs(rel, "mailto") && !protocolIs(rel, "data") && !protocolIsJavaScript(rel)) {
1561 // Find the first instance of either # or ?, keep pathEnd at -1 otherwise.
1562 pathEnd = findFirstOf(s.data(), s.size(), 0, "#?");
1565 if (pathEnd == -1) {
1566 CString decoded = pathEncoding.encode(s.data(), s.size(), URLEncodedEntitiesForUnencodables);
1567 output.resize(decoded.length());
1568 memcpy(output.data(), decoded.data(), decoded.length());
1570 CString pathDecoded = pathEncoding.encode(s.data(), pathEnd, URLEncodedEntitiesForUnencodables);
1571 // Unencodable characters in URLs are represented by converting
1572 // them to XML entities and escaping non-alphanumeric characters.
1573 CString otherDecoded = encoding.encode(s.data() + pathEnd, s.size() - pathEnd, URLEncodedEntitiesForUnencodables);
1575 output.resize(pathDecoded.length() + otherDecoded.length());
1576 memcpy(output.data(), pathDecoded.data(), pathDecoded.length());
1577 memcpy(output.data() + pathDecoded.length(), otherDecoded.data(), otherDecoded.length());
1579 output.append('\0'); // null-terminate the output.
1582 static String substituteBackslashes(const String& string)
1584 int questionPos = string.find('?');
1585 int hashPos = string.find('#');
1588 if (hashPos >= 0 && (questionPos < 0 || questionPos > hashPos))
1590 else if (questionPos >= 0)
1591 pathEnd = questionPos;
1593 pathEnd = string.length();
1595 return string.left(pathEnd).replace('\\','/') + string.substring(pathEnd);
1598 bool KURL::isHierarchical() const
1602 ASSERT(m_string[m_schemeEnd] == ':');
1603 return m_string[m_schemeEnd + 1] == '/';
1606 void KURL::copyToBuffer(CharBuffer& buffer) const
1608 // FIXME: This throws away the high bytes of all the characters in the string!
1609 // That's fine for a valid URL, which is all ASCII, but not for invalid URLs.
1610 buffer.resize(m_string.length());
1611 copyASCII(m_string.characters(), m_string.length(), buffer.data());
1614 bool protocolIs(const String& url, const char* protocol)
1616 // Do the comparison without making a new string object.
1617 assertProtocolIsGood(protocol);
1618 for (int i = 0; ; ++i) {
1620 return url[i] == ':';
1621 if (toASCIILower(url[i]) != protocol[i])
1626 bool protocolIsJavaScript(const String& url)
1628 return protocolIs(url, "javascript");
1631 bool isValidProtocol(const String& protocol)
1633 if (!isSchemeFirstChar(protocol[0]))
1635 unsigned protocolLength = protocol.length();
1636 for (unsigned i = 1; i < protocolLength; i++) {
1637 if (!isSchemeChar(protocol[i]))
1643 bool isDefaultPortForProtocol(unsigned short port, const String& protocol)
1645 if (protocol.isEmpty())
1648 typedef HashMap<String, unsigned, CaseFoldingHash> DefaultPortsMap;
1649 DEFINE_STATIC_LOCAL(DefaultPortsMap, defaultPorts, ());
1650 if (defaultPorts.isEmpty()) {
1651 defaultPorts.set("http", 80);
1652 defaultPorts.set("https", 443);
1653 defaultPorts.set("ftp", 21);
1654 defaultPorts.set("ftps", 990);
1656 return defaultPorts.get(protocol) == port;
1659 bool portAllowed(const KURL& url)
1661 unsigned short port = url.port();
1663 // Since most URLs don't have a port, return early for the "no port" case.
1667 // This blocked port list matches the port blocking that Mozilla implements.
1668 // See http://www.mozilla.org/projects/netlib/PortBanning.html for more information.
1669 static const unsigned short blockedPortList[] = {
1703 135, // loc-srv / epmap
1709 512, // print / exec
1726 3659, // apple-sasl / PasswordServer [Apple addition]
1730 const unsigned short* const blockedPortListEnd = blockedPortList + sizeof(blockedPortList) / sizeof(blockedPortList[0]);
1733 // The port list must be sorted for binary_search to work.
1734 static bool checkedPortList = false;
1735 if (!checkedPortList) {
1736 for (const unsigned short* p = blockedPortList; p != blockedPortListEnd - 1; ++p)
1737 ASSERT(*p < *(p + 1));
1738 checkedPortList = true;
1742 // If the port is not in the blocked port list, allow it.
1743 if (!binary_search(blockedPortList, blockedPortListEnd, port))
1746 // Allow ports 21 and 22 for FTP URLs, as Mozilla does.
1747 if ((port == 21 || port == 22) && url.protocolIs("ftp"))
1750 // Allow any port number in a file URL, since the port number is ignored.
1751 if (url.protocolIs("file"))
1757 String mimeTypeFromDataURL(const String& url)
1759 ASSERT(protocolIs(url, "data"));
1760 int index = url.find(';');
1762 index = url.find(',');
1764 int len = index - 5;
1766 return url.substring(5, len);
1767 return "text/plain"; // Data URLs with no MIME type are considered text/plain.
1772 const KURL& blankURL()
1774 DEFINE_STATIC_LOCAL(KURL, staticBlankURL, (ParsedURLString, "about:blank"));
1775 return staticBlankURL;
1779 void KURL::print() const
1781 printf("%s\n", m_string.utf8().data());
1787 #endif // !USE(GOOGLEURL)