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.
32 #include "TextEncoding.h"
33 #include <wtf/text/CString.h>
34 #include <wtf/HashMap.h>
35 #include <wtf/StdLibExtras.h>
36 #include <wtf/text/StringHash.h>
39 #include <unicode/uidna.h>
40 #elif USE(QT4_UNICODE)
42 #elif USE(GLIB_UNICODE)
54 typedef Vector<char, 512> CharBuffer;
55 typedef Vector<UChar, 512> UCharBuffer;
57 // FIXME: This file makes too much use of the + operator on String.
58 // We either have to optimize that operator so it doesn't involve
59 // so many allocations, or change this to use Vector<UChar> instead.
61 enum URLCharacterClasses {
63 SchemeFirstChar = 1 << 0,
65 // ( alpha | digit | "+" | "-" | "." )
68 // mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
69 // unreserved = alphanum | mark
70 // ( unreserved | escaped | ";" | ":" | "&" | "=" | "+" | "$" | "," )
71 UserInfoChar = 1 << 2,
73 // alnum | "." | "-" | "%"
74 // The above is what the specification says, but we are lenient to
75 // match existing practice and also allow:
77 HostnameChar = 1 << 3,
79 // hexdigit | ":" | "%"
82 // "#" | "?" | "/" | nul
83 PathSegmentEndChar = 1 << 5,
85 // not allowed in path
89 static const char hexDigits[17] = "0123456789ABCDEF";
91 static const unsigned char characterClassTable[256] = {
92 /* 0 nul */ PathSegmentEndChar, /* 1 soh */ BadChar,
93 /* 2 stx */ BadChar, /* 3 etx */ BadChar,
94 /* 4 eot */ BadChar, /* 5 enq */ BadChar, /* 6 ack */ BadChar, /* 7 bel */ BadChar,
95 /* 8 bs */ BadChar, /* 9 ht */ BadChar, /* 10 nl */ BadChar, /* 11 vt */ BadChar,
96 /* 12 np */ BadChar, /* 13 cr */ BadChar, /* 14 so */ BadChar, /* 15 si */ BadChar,
97 /* 16 dle */ BadChar, /* 17 dc1 */ BadChar, /* 18 dc2 */ BadChar, /* 19 dc3 */ BadChar,
98 /* 20 dc4 */ BadChar, /* 21 nak */ BadChar, /* 22 syn */ BadChar, /* 23 etb */ BadChar,
99 /* 24 can */ BadChar, /* 25 em */ BadChar, /* 26 sub */ BadChar, /* 27 esc */ BadChar,
100 /* 28 fs */ BadChar, /* 29 gs */ BadChar, /* 30 rs */ BadChar, /* 31 us */ BadChar,
101 /* 32 sp */ BadChar, /* 33 ! */ UserInfoChar,
102 /* 34 " */ BadChar, /* 35 # */ PathSegmentEndChar | BadChar,
103 /* 36 $ */ UserInfoChar, /* 37 % */ UserInfoChar | HostnameChar | IPv6Char | BadChar,
104 /* 38 & */ UserInfoChar, /* 39 ' */ UserInfoChar,
105 /* 40 ( */ UserInfoChar, /* 41 ) */ UserInfoChar,
106 /* 42 * */ UserInfoChar, /* 43 + */ SchemeChar | UserInfoChar,
107 /* 44 , */ UserInfoChar,
108 /* 45 - */ SchemeChar | UserInfoChar | HostnameChar,
109 /* 46 . */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
110 /* 47 / */ PathSegmentEndChar,
111 /* 48 0 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
112 /* 49 1 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
113 /* 50 2 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
114 /* 51 3 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
115 /* 52 4 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
116 /* 53 5 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
117 /* 54 6 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
118 /* 55 7 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
119 /* 56 8 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
120 /* 57 9 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
121 /* 58 : */ UserInfoChar | IPv6Char, /* 59 ; */ UserInfoChar,
122 /* 60 < */ BadChar, /* 61 = */ UserInfoChar,
123 /* 62 > */ BadChar, /* 63 ? */ PathSegmentEndChar | BadChar,
125 /* 65 A */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
126 /* 66 B */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
127 /* 67 C */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
128 /* 68 D */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
129 /* 69 E */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
130 /* 70 F */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
131 /* 71 G */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
132 /* 72 H */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
133 /* 73 I */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
134 /* 74 J */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
135 /* 75 K */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
136 /* 76 L */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
137 /* 77 M */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
138 /* 78 N */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
139 /* 79 O */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
140 /* 80 P */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
141 /* 81 Q */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
142 /* 82 R */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
143 /* 83 S */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
144 /* 84 T */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
145 /* 85 U */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
146 /* 86 V */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
147 /* 87 W */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
148 /* 88 X */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
149 /* 89 Y */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
150 /* 90 Z */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
152 /* 92 \ */ 0, /* 93 ] */ 0,
154 /* 95 _ */ UserInfoChar | HostnameChar,
156 /* 97 a */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
157 /* 98 b */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
158 /* 99 c */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
159 /* 100 d */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
160 /* 101 e */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
161 /* 102 f */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
162 /* 103 g */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
163 /* 104 h */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
164 /* 105 i */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
165 /* 106 j */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
166 /* 107 k */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
167 /* 108 l */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
168 /* 109 m */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
169 /* 110 n */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
170 /* 111 o */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
171 /* 112 p */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
172 /* 113 q */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
173 /* 114 r */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
174 /* 115 s */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
175 /* 116 t */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
176 /* 117 u */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
177 /* 118 v */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
178 /* 119 w */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
179 /* 120 x */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
180 /* 121 y */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
181 /* 122 z */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
183 /* 124 | */ 0, /* 125 } */ 0, /* 126 ~ */ UserInfoChar, /* 127 del */ BadChar,
184 /* 128 */ BadChar, /* 129 */ BadChar, /* 130 */ BadChar, /* 131 */ BadChar,
185 /* 132 */ BadChar, /* 133 */ BadChar, /* 134 */ BadChar, /* 135 */ BadChar,
186 /* 136 */ BadChar, /* 137 */ BadChar, /* 138 */ BadChar, /* 139 */ BadChar,
187 /* 140 */ BadChar, /* 141 */ BadChar, /* 142 */ BadChar, /* 143 */ BadChar,
188 /* 144 */ BadChar, /* 145 */ BadChar, /* 146 */ BadChar, /* 147 */ BadChar,
189 /* 148 */ BadChar, /* 149 */ BadChar, /* 150 */ BadChar, /* 151 */ BadChar,
190 /* 152 */ BadChar, /* 153 */ BadChar, /* 154 */ BadChar, /* 155 */ BadChar,
191 /* 156 */ BadChar, /* 157 */ BadChar, /* 158 */ BadChar, /* 159 */ BadChar,
192 /* 160 */ BadChar, /* 161 */ BadChar, /* 162 */ BadChar, /* 163 */ BadChar,
193 /* 164 */ BadChar, /* 165 */ BadChar, /* 166 */ BadChar, /* 167 */ BadChar,
194 /* 168 */ BadChar, /* 169 */ BadChar, /* 170 */ BadChar, /* 171 */ BadChar,
195 /* 172 */ BadChar, /* 173 */ BadChar, /* 174 */ BadChar, /* 175 */ BadChar,
196 /* 176 */ BadChar, /* 177 */ BadChar, /* 178 */ BadChar, /* 179 */ BadChar,
197 /* 180 */ BadChar, /* 181 */ BadChar, /* 182 */ BadChar, /* 183 */ BadChar,
198 /* 184 */ BadChar, /* 185 */ BadChar, /* 186 */ BadChar, /* 187 */ BadChar,
199 /* 188 */ BadChar, /* 189 */ BadChar, /* 190 */ BadChar, /* 191 */ BadChar,
200 /* 192 */ BadChar, /* 193 */ BadChar, /* 194 */ BadChar, /* 195 */ BadChar,
201 /* 196 */ BadChar, /* 197 */ BadChar, /* 198 */ BadChar, /* 199 */ BadChar,
202 /* 200 */ BadChar, /* 201 */ BadChar, /* 202 */ BadChar, /* 203 */ BadChar,
203 /* 204 */ BadChar, /* 205 */ BadChar, /* 206 */ BadChar, /* 207 */ BadChar,
204 /* 208 */ BadChar, /* 209 */ BadChar, /* 210 */ BadChar, /* 211 */ BadChar,
205 /* 212 */ BadChar, /* 213 */ BadChar, /* 214 */ BadChar, /* 215 */ BadChar,
206 /* 216 */ BadChar, /* 217 */ BadChar, /* 218 */ BadChar, /* 219 */ BadChar,
207 /* 220 */ BadChar, /* 221 */ BadChar, /* 222 */ BadChar, /* 223 */ BadChar,
208 /* 224 */ BadChar, /* 225 */ BadChar, /* 226 */ BadChar, /* 227 */ BadChar,
209 /* 228 */ BadChar, /* 229 */ BadChar, /* 230 */ BadChar, /* 231 */ BadChar,
210 /* 232 */ BadChar, /* 233 */ BadChar, /* 234 */ BadChar, /* 235 */ BadChar,
211 /* 236 */ BadChar, /* 237 */ BadChar, /* 238 */ BadChar, /* 239 */ BadChar,
212 /* 240 */ BadChar, /* 241 */ BadChar, /* 242 */ BadChar, /* 243 */ BadChar,
213 /* 244 */ BadChar, /* 245 */ BadChar, /* 246 */ BadChar, /* 247 */ BadChar,
214 /* 248 */ BadChar, /* 249 */ BadChar, /* 250 */ BadChar, /* 251 */ BadChar,
215 /* 252 */ BadChar, /* 253 */ BadChar, /* 254 */ BadChar, /* 255 */ BadChar
218 static const unsigned maximumValidPortNumber = 0xFFFE;
219 static const unsigned invalidPortNumber = 0xFFFF;
221 static int copyPathRemovingDots(char* dst, const char* src, int srcStart, int srcEnd);
222 static void encodeRelativeString(const String& rel, const TextEncoding&, CharBuffer& ouput);
223 static String substituteBackslashes(const String&);
224 static bool isValidProtocol(const String&);
226 static inline bool isSchemeFirstChar(char c) { return characterClassTable[static_cast<unsigned char>(c)] & SchemeFirstChar; }
227 static inline bool isSchemeFirstChar(UChar c) { return c <= 0xff && (characterClassTable[c] & SchemeFirstChar); }
228 static inline bool isSchemeChar(char c) { return characterClassTable[static_cast<unsigned char>(c)] & SchemeChar; }
229 static inline bool isSchemeChar(UChar c) { return c <= 0xff && (characterClassTable[c] & SchemeChar); }
230 static inline bool isUserInfoChar(unsigned char c) { return characterClassTable[c] & UserInfoChar; }
231 static inline bool isHostnameChar(unsigned char c) { return characterClassTable[c] & HostnameChar; }
232 static inline bool isIPv6Char(unsigned char c) { return characterClassTable[c] & IPv6Char; }
233 static inline bool isPathSegmentEndChar(char c) { return characterClassTable[static_cast<unsigned char>(c)] & PathSegmentEndChar; }
234 static inline bool isPathSegmentEndChar(UChar c) { return c <= 0xff && (characterClassTable[c] & PathSegmentEndChar); }
235 static inline bool isBadChar(unsigned char c) { return characterClassTable[c] & BadChar; }
237 static inline int hexDigitValue(UChar c)
239 ASSERT(isASCIIHexDigit(c));
242 return (c - 'A' + 10) & 0xF; // handle both upper and lower case without a branch
245 // Copies the source to the destination, assuming all the source characters are
246 // ASCII. The destination buffer must be large enough. Null characters are allowed
247 // in the source string, and no attempt is made to null-terminate the result.
248 static void copyASCII(const UChar* src, int length, char* dest)
250 for (int i = 0; i < length; i++)
251 dest[i] = static_cast<char>(src[i]);
254 static void appendASCII(const String& base, const char* rel, size_t len, CharBuffer& buffer)
256 buffer.resize(base.length() + len + 1);
257 copyASCII(base.characters(), base.length(), buffer.data());
258 memcpy(buffer.data() + base.length(), rel, len);
259 buffer[buffer.size() - 1] = '\0';
262 // FIXME: Move to PlatformString.h eventually.
263 // Returns the index of the first index in string |s| of any of the characters
264 // in |toFind|. |toFind| should be a null-terminated string, all characters up
265 // to the null will be searched. Returns int if not found.
266 static int findFirstOf(const UChar* s, int sLen, int startPos, const char* toFind)
268 for (int i = startPos; i < sLen; i++) {
269 const char* cur = toFind;
271 if (s[i] == *(cur++))
279 static void checkEncodedString(const String& url)
281 for (unsigned i = 0; i < url.length(); ++i)
282 ASSERT(!(url[i] & ~0x7F));
284 ASSERT(!url.length() || isSchemeFirstChar(url[0]));
287 static inline void checkEncodedString(const String&)
292 inline bool KURL::protocolIs(const String& string, const char* protocol)
294 return WebCore::protocolIs(string, protocol);
297 void KURL::invalidate()
300 m_protocolInHTTPFamily = false;
308 m_pathAfterLastSlash = 0;
313 KURL::KURL(ParsedURLStringTag, const char* url)
316 ASSERT(url == m_string);
319 KURL::KURL(ParsedURLStringTag, const String& url)
322 ASSERT(url == m_string);
325 KURL::KURL(ParsedURLStringTag, const URLString& url)
328 ASSERT(url.string() == m_string);
331 KURL::KURL(const KURL& base, const String& relative)
333 init(base, relative, UTF8Encoding());
336 KURL::KURL(const KURL& base, const String& relative, const TextEncoding& encoding)
338 // For UTF-{7,16,32}, we want to use UTF-8 for the query part as
339 // we do when submitting a form. A form with GET method
340 // has its contents added to a URL as query params and it makes sense
342 init(base, relative, encoding.encodingForFormSubmission());
345 void KURL::init(const KURL& base, const String& relative, const TextEncoding& encoding)
347 // Allow resolutions with a null or empty base URL, but not with any other invalid one.
348 // FIXME: Is this a good rule?
349 if (!base.m_isValid && !base.isEmpty()) {
355 // For compatibility with Win IE, treat backslashes as if they were slashes,
356 // as long as we're not dealing with javascript: or data: URLs.
357 String rel = relative;
358 if (rel.contains('\\') && !(protocolIsJavaScript(rel) || protocolIs(rel, "data")))
359 rel = substituteBackslashes(rel);
361 String* originalString = &rel;
363 bool allASCII = charactersAreAllASCII(rel.characters(), rel.length());
364 CharBuffer strBuffer;
369 strBuffer.resize(len + 1);
370 copyASCII(rel.characters(), len, strBuffer.data());
372 str = strBuffer.data();
375 encodeRelativeString(rel, encoding, strBuffer);
376 str = strBuffer.data();
380 // Get rid of leading whitespace.
381 while (*str == ' ') {
387 // Get rid of trailing whitespace.
388 while (len && str[len - 1] == ' ') {
393 // According to the RFC, the reference should be interpreted as an
394 // absolute URI if possible, using the "leftmost, longest"
395 // algorithm. If the URI reference is absolute it will have a
396 // scheme, meaning that it will have a colon before the first
397 // non-scheme element.
398 bool absolute = false;
400 if (isSchemeFirstChar(*p)) {
402 while (isSchemeChar(*p)) {
406 if (p[1] != '/' && equalIgnoringCase(base.protocol(), String(str, p - str)) && base.isHierarchical()) {
414 CharBuffer parseBuffer;
417 parse(str, originalString);
419 // If the base is empty or opaque (e.g. data: or javascript:), then the URL is invalid
420 // unless the relative URL is a single fragment.
421 if (!base.isHierarchical()) {
423 appendASCII(base.m_string.left(base.m_queryEnd), str, len, parseBuffer);
424 parse(parseBuffer.data(), 0);
434 // The reference is empty, so this is a reference to the same document with any fragment identifier removed.
436 removeFragmentIdentifier();
439 // must be fragment-only reference
440 appendASCII(base.m_string.left(base.m_queryEnd), str, len, parseBuffer);
441 parse(parseBuffer.data(), 0);
445 // query-only reference, special case needed for non-URL results
446 appendASCII(base.m_string.left(base.m_pathEnd), str, len, parseBuffer);
447 parse(parseBuffer.data(), 0);
451 // must be net-path or absolute-path reference
454 appendASCII(base.m_string.left(base.m_schemeEnd + 1), str, len, parseBuffer);
455 parse(parseBuffer.data(), 0);
458 appendASCII(base.m_string.left(base.m_portEnd), str, len, parseBuffer);
459 parse(parseBuffer.data(), 0);
464 // must be relative-path reference
466 // Base part plus relative part plus one possible slash added in between plus terminating \0 byte.
467 parseBuffer.resize(base.m_pathEnd + 1 + len + 1);
469 char* bufferPos = parseBuffer.data();
471 // first copy everything before the path from the base
472 unsigned baseLength = base.m_string.length();
473 const UChar* baseCharacters = base.m_string.characters();
474 CharBuffer baseStringBuffer(baseLength);
475 copyASCII(baseCharacters, baseLength, baseStringBuffer.data());
476 const char* baseString = baseStringBuffer.data();
477 const char* baseStringStart = baseString;
478 const char* pathStart = baseStringStart + base.m_portEnd;
479 while (baseStringStart < pathStart)
480 *bufferPos++ = *baseStringStart++;
481 char* bufferPathStart = bufferPos;
483 // now copy the base path
484 const char* baseStringEnd = baseString + base.m_pathEnd;
486 // go back to the last slash
487 while (baseStringEnd > baseStringStart && baseStringEnd[-1] != '/')
490 if (baseStringEnd == baseStringStart) {
491 // no path in base, add a path separator if necessary
492 if (base.m_schemeEnd + 1 != base.m_pathEnd && *str && *str != '?' && *str != '#')
495 bufferPos += copyPathRemovingDots(bufferPos, baseStringStart, 0, baseStringEnd - baseStringStart);
498 const char* relStringStart = str;
499 const char* relStringPos = relStringStart;
501 while (*relStringPos && *relStringPos != '?' && *relStringPos != '#') {
502 if (relStringPos[0] == '.' && bufferPos[-1] == '/') {
503 if (isPathSegmentEndChar(relStringPos[1])) {
504 // skip over "." segment
506 if (relStringPos[0] == '/')
509 } else if (relStringPos[1] == '.' && isPathSegmentEndChar(relStringPos[2])) {
510 // skip over ".." segment and rewind the last segment
511 // the RFC leaves it up to the app to decide what to do with excess
512 // ".." segments - we choose to drop them since some web content
515 if (relStringPos[0] == '/')
517 if (bufferPos > bufferPathStart + 1)
519 while (bufferPos > bufferPathStart + 1 && bufferPos[-1] != '/')
525 *bufferPos = *relStringPos;
530 // all done with the path work, now copy any remainder
531 // of the relative reference; this will also add a null terminator
532 strcpy(bufferPos, relStringPos);
534 parse(parseBuffer.data(), 0);
536 ASSERT(strlen(parseBuffer.data()) + 1 <= parseBuffer.size());
543 KURL KURL::copy() const
546 result.m_string = result.m_string.crossThreadString();
550 bool KURL::hasPath() const
552 return m_pathEnd != m_portEnd;
555 String KURL::lastPathComponent() const
560 unsigned end = m_pathEnd - 1;
561 if (m_string[end] == '/')
564 size_t start = m_string.reverseFind('/', end);
565 if (start < static_cast<unsigned>(m_portEnd))
569 return m_string.substring(start, end - start + 1);
572 String KURL::protocol() const
574 return m_string.left(m_schemeEnd);
577 String KURL::host() const
579 int start = hostStart();
580 return decodeURLEscapeSequences(m_string.substring(start, m_hostEnd - start));
583 unsigned short KURL::port() const
585 // We return a port of 0 if there is no port specified. This can happen in two situations:
586 // 1) The URL contains no colon after the host name and before the path component of the URL.
587 // 2) The URL contains a colon but there's no port number before the path component of the URL begins.
588 if (m_hostEnd == m_portEnd || m_hostEnd == m_portEnd - 1)
591 const UChar* stringData = m_string.characters();
593 unsigned number = charactersToUIntStrict(stringData + m_hostEnd + 1, m_portEnd - m_hostEnd - 1, &ok);
594 if (!ok || number > maximumValidPortNumber)
595 return invalidPortNumber;
599 String KURL::pass() const
601 if (m_passwordEnd == m_userEnd)
604 return decodeURLEscapeSequences(m_string.substring(m_userEnd + 1, m_passwordEnd - m_userEnd - 1));
607 String KURL::user() const
609 return decodeURLEscapeSequences(m_string.substring(m_userStart, m_userEnd - m_userStart));
612 String KURL::fragmentIdentifier() const
614 if (m_fragmentEnd == m_queryEnd)
617 return m_string.substring(m_queryEnd + 1, m_fragmentEnd - (m_queryEnd + 1));
620 bool KURL::hasFragmentIdentifier() const
622 return m_fragmentEnd != m_queryEnd;
625 void KURL::copyParsedQueryTo(ParsedURLParameters& parameters) const
627 const UChar* pos = m_string.characters() + m_pathEnd + 1;
628 const UChar* end = m_string.characters() + m_queryEnd;
630 const UChar* parameterStart = pos;
631 while (pos < end && *pos != '&')
633 const UChar* parameterEnd = pos;
638 if (parameterStart == parameterEnd)
640 const UChar* nameStart = parameterStart;
641 const UChar* equalSign = parameterStart;
642 while (equalSign < parameterEnd && *equalSign != '=')
644 if (equalSign == nameStart)
646 String name(nameStart, equalSign - nameStart);
647 String value = equalSign == parameterEnd ? String() : String(equalSign + 1, parameterEnd - equalSign - 1);
648 parameters.set(name, value);
652 String KURL::baseAsString() const
654 return m_string.left(m_pathAfterLastSlash);
659 static inline void assertProtocolIsGood(const char*)
665 static void assertProtocolIsGood(const char* protocol)
667 const char* p = protocol;
669 ASSERT(*p > ' ' && *p < 0x7F && !(*p >= 'A' && *p <= 'Z'));
676 bool KURL::protocolIs(const char* protocol) const
678 assertProtocolIsGood(protocol);
680 // JavaScript URLs are "valid" and should be executed even if KURL decides they are invalid.
681 // The free function protocolIsJavaScript() should be used instead.
682 ASSERT(!equalIgnoringCase(protocol, String("javascript")));
687 // Do the comparison without making a new string object.
688 for (int i = 0; i < m_schemeEnd; ++i) {
689 if (!protocol[i] || toASCIILower(m_string[i]) != protocol[i])
692 return !protocol[m_schemeEnd]; // We should have consumed all characters in the argument.
695 String KURL::query() const
697 if (m_queryEnd == m_pathEnd)
700 return m_string.substring(m_pathEnd + 1, m_queryEnd - (m_pathEnd + 1));
703 String KURL::path() const
705 return decodeURLEscapeSequences(m_string.substring(m_portEnd, m_pathEnd - m_portEnd));
708 bool KURL::setProtocol(const String& s)
710 // Firefox and IE remove everything after the first ':'.
711 size_t separatorPosition = s.find(':');
712 String newProtocol = s.substring(0, separatorPosition);
714 if (!isValidProtocol(newProtocol))
718 parse(newProtocol + ":" + m_string);
722 parse(newProtocol + m_string.substring(m_schemeEnd));
726 void KURL::setHost(const String& s)
731 // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations,
732 // and to avoid changing more than just the host.
734 bool slashSlashNeeded = m_userStart == m_schemeEnd + 1;
736 parse(m_string.left(hostStart()) + (slashSlashNeeded ? "//" : "") + s + m_string.substring(m_hostEnd));
739 void KURL::removePort()
741 if (m_hostEnd == m_portEnd)
743 parse(m_string.left(m_hostEnd) + m_string.substring(m_portEnd));
746 void KURL::setPort(unsigned short i)
751 bool colonNeeded = m_portEnd == m_hostEnd;
752 int portStart = (colonNeeded ? m_hostEnd : m_hostEnd + 1);
754 parse(m_string.left(portStart) + (colonNeeded ? ":" : "") + String::number(i) + m_string.substring(m_portEnd));
757 void KURL::setHostAndPort(const String& hostAndPort)
762 // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations,
763 // and to avoid changing more than just host and port.
765 bool slashSlashNeeded = m_userStart == m_schemeEnd + 1;
767 parse(m_string.left(hostStart()) + (slashSlashNeeded ? "//" : "") + hostAndPort + m_string.substring(m_portEnd));
770 void KURL::setUser(const String& user)
775 // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations,
776 // and to avoid changing more than just the user login.
779 if (!user.isEmpty()) {
781 if (m_userStart == m_schemeEnd + 1)
783 // Add '@' if we didn't have one before.
784 if (end == m_hostEnd || (end == m_passwordEnd && m_string[end] != '@'))
787 // Remove '@' if we now have neither user nor password.
788 if (m_userEnd == m_passwordEnd && end != m_hostEnd && m_string[end] == '@')
791 parse(m_string.left(m_userStart) + u + m_string.substring(end));
794 void KURL::setPass(const String& password)
799 // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations,
800 // and to avoid changing more than just the user password.
802 int end = m_passwordEnd;
803 if (!password.isEmpty()) {
804 p = ":" + password + "@";
805 if (m_userEnd == m_schemeEnd + 1)
807 // Eat the existing '@' since we are going to add our own.
808 if (end != m_hostEnd && m_string[end] == '@')
811 // Remove '@' if we now have neither user nor password.
812 if (m_userStart == m_userEnd && end != m_hostEnd && m_string[end] == '@')
815 parse(m_string.left(m_userEnd) + p + m_string.substring(end));
818 void KURL::setFragmentIdentifier(const String& s)
823 // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations.
824 parse(m_string.left(m_queryEnd) + "#" + s);
827 void KURL::removeFragmentIdentifier()
831 parse(m_string.left(m_queryEnd));
834 void KURL::setQuery(const String& query)
839 // FIXME: '#' and non-ASCII characters must be encoded and escaped.
840 // Usually, the query is encoded using document encoding, not UTF-8, but we don't have
841 // access to the document in this function.
842 if ((query.isEmpty() || query[0] != '?') && !query.isNull())
843 parse(m_string.left(m_pathEnd) + "?" + query + m_string.substring(m_queryEnd));
845 parse(m_string.left(m_pathEnd) + query + m_string.substring(m_queryEnd));
849 void KURL::setPath(const String& s)
854 // FIXME: encodeWithURLEscapeSequences does not correctly escape '#' and '?', so fragment and query parts
855 // may be inadvertently affected.
856 parse(m_string.left(m_portEnd) + encodeWithURLEscapeSequences(s) + m_string.substring(m_pathEnd));
859 String KURL::prettyURL() const
864 Vector<UChar> result;
866 append(result, protocol());
869 Vector<UChar> authority;
871 if (m_hostEnd != m_passwordEnd) {
872 if (m_userEnd != m_userStart) {
873 append(authority, user());
874 authority.append('@');
876 append(authority, host());
878 authority.append(':');
879 append(authority, String::number(port()));
883 if (!authority.isEmpty()) {
886 result.append(authority);
887 } else if (protocolIs("file")) {
892 append(result, path());
894 if (m_pathEnd != m_queryEnd) {
896 append(result, query());
899 if (m_fragmentEnd != m_queryEnd) {
901 append(result, fragmentIdentifier());
904 return String::adopt(result);
907 String decodeURLEscapeSequences(const String& str)
909 return decodeURLEscapeSequences(str, UTF8Encoding());
912 String decodeURLEscapeSequences(const String& str, const TextEncoding& encoding)
914 Vector<UChar> result;
918 unsigned length = str.length();
919 unsigned decodedPosition = 0;
920 unsigned searchPosition = 0;
921 size_t encodedRunPosition;
922 while ((encodedRunPosition = str.find('%', searchPosition)) != notFound) {
923 // Find the sequence of %-escape codes.
924 unsigned encodedRunEnd = encodedRunPosition;
925 while (length - encodedRunEnd >= 3
926 && str[encodedRunEnd] == '%'
927 && isASCIIHexDigit(str[encodedRunEnd + 1])
928 && isASCIIHexDigit(str[encodedRunEnd + 2]))
930 searchPosition = encodedRunEnd;
931 if (encodedRunEnd == encodedRunPosition) {
936 // Decode the %-escapes into bytes.
937 unsigned runLength = (encodedRunEnd - encodedRunPosition) / 3;
938 buffer.resize(runLength);
939 char* p = buffer.data();
940 const UChar* q = str.characters() + encodedRunPosition;
941 for (unsigned i = 0; i < runLength; ++i) {
942 *p++ = (hexDigitValue(q[1]) << 4) | hexDigitValue(q[2]);
946 // Decode the bytes into Unicode characters.
947 String decoded = (encoding.isValid() ? encoding : UTF8Encoding()).decode(buffer.data(), p - buffer.data());
948 if (decoded.isEmpty())
951 // Build up the string with what we just skipped and what we just decoded.
952 result.append(str.characters() + decodedPosition, encodedRunPosition - decodedPosition);
953 result.append(decoded.characters(), decoded.length());
954 decodedPosition = encodedRunEnd;
957 result.append(str.characters() + decodedPosition, length - decodedPosition);
959 return String::adopt(result);
962 bool KURL::isLocalFile() const
964 // Including feed here might be a bad idea since drag and drop uses this check
965 // and including feed would allow feeds to potentially let someone's blog
966 // read the contents of the clipboard on a drag, even without a drop.
967 // Likewise with using the FrameLoader::shouldTreatURLAsLocal() function.
968 return protocolIs("file");
971 // Caution: This function does not bounds check.
972 static void appendEscapedChar(char*& buffer, unsigned char c)
975 *buffer++ = hexDigits[c >> 4];
976 *buffer++ = hexDigits[c & 0xF];
979 static void appendEscapingBadChars(char*& buffer, const char* strStart, size_t length)
983 const char* str = strStart;
984 const char* strEnd = strStart + length;
985 while (str < strEnd) {
986 unsigned char c = *str++;
988 if (c == '%' || c == '?')
990 else if (c != 0x09 && c != 0x0a && c != 0x0d)
991 appendEscapedChar(p, c);
999 static void escapeAndAppendFragment(char*& buffer, const char* strStart, size_t length)
1003 const char* str = strStart;
1004 const char* strEnd = strStart + length;
1005 while (str < strEnd) {
1006 unsigned char c = *str++;
1007 // Strip CR, LF and Tab from fragments, per:
1008 // https://bugs.webkit.org/show_bug.cgi?id=8770
1009 if (c == 0x09 || c == 0x0a || c == 0x0d)
1012 // Chrome and IE allow non-ascii characters in fragments, however doing
1013 // so would hit an ASSERT in checkEncodedString, so for now we don't.
1014 if (c < 0x20 || c >= 127) {
1015 appendEscapedChar(p, c);
1024 // copy a path, accounting for "." and ".." segments
1025 static int copyPathRemovingDots(char* dst, const char* src, int srcStart, int srcEnd)
1027 char* bufferPathStart = dst;
1029 // empty path is a special case, and need not have a leading slash
1030 if (srcStart != srcEnd) {
1031 const char* baseStringStart = src + srcStart;
1032 const char* baseStringEnd = src + srcEnd;
1033 const char* baseStringPos = baseStringStart;
1035 // this code is unprepared for paths that do not begin with a
1036 // slash and we should always have one in the source string
1037 ASSERT(baseStringPos[0] == '/');
1039 // copy the leading slash into the destination
1040 *dst = *baseStringPos;
1044 while (baseStringPos < baseStringEnd) {
1045 if (baseStringPos[0] == '.' && dst[-1] == '/') {
1046 if (baseStringPos[1] == '/' || baseStringPos + 1 == baseStringEnd) {
1047 // skip over "." segment
1050 } else if (baseStringPos[1] == '.' && (baseStringPos[2] == '/' ||
1051 baseStringPos + 2 == baseStringEnd)) {
1052 // skip over ".." segment and rewind the last segment
1053 // the RFC leaves it up to the app to decide what to do with excess
1054 // ".." segments - we choose to drop them since some web content
1057 if (dst > bufferPathStart + 1)
1059 while (dst > bufferPathStart && dst[-1] != '/')
1065 *dst = *baseStringPos;
1071 return dst - bufferPathStart;
1074 static inline bool hasSlashDotOrDotDot(const char* str)
1076 const unsigned char* p = reinterpret_cast<const unsigned char*>(str);
1079 unsigned char pc = *p;
1080 while (unsigned char c = *++p) {
1081 if (c == '.' && (pc == '/' || pc == '.'))
1088 static inline bool matchLetter(char c, char lowercaseLetter)
1090 return (c | 0x20) == lowercaseLetter;
1093 void KURL::parse(const String& string)
1095 checkEncodedString(string);
1097 CharBuffer buffer(string.length() + 1);
1098 copyASCII(string.characters(), string.length(), buffer.data());
1099 buffer[string.length()] = '\0';
1100 parse(buffer.data(), &string);
1103 static inline bool equal(const char* a, size_t lenA, const char* b, size_t lenB)
1107 return !strncmp(a, b, lenA);
1110 // List of default schemes is taken from google-url:
1111 // http://code.google.com/p/google-url/source/browse/trunk/src/url_canon_stdurl.cc#120
1112 static inline bool isDefaultPortForScheme(const char* port, size_t portLength, const char* scheme, size_t schemeLength)
1114 // This switch is theoretically a performance optimization. It came over when
1115 // the code was moved from google-url, but may be removed later.
1116 switch (schemeLength) {
1118 return equal("ws", 2, scheme, schemeLength) && equal("80", 2, port, portLength);
1120 if (equal("ftp", 3, scheme, schemeLength))
1121 return equal("21", 2, port, portLength);
1122 if (equal("wss", 3, scheme, schemeLength))
1123 return equal("443", 3, port, portLength);
1126 return equal("http", 4, scheme, schemeLength) && equal("80", 2, port, portLength);
1128 return equal("https", 5, scheme, schemeLength) && equal("443", 3, port, portLength);
1130 return equal("gopher", 6, scheme, schemeLength) && equal("70", 2, port, portLength);
1135 void KURL::parse(const char* url, const String* originalString)
1137 if (!url || url[0] == '\0') {
1138 // valid URL must be non-empty
1139 m_string = originalString ? *originalString : url;
1144 if (!isSchemeFirstChar(url[0])) {
1145 // scheme must start with an alphabetic character
1146 m_string = originalString ? *originalString : url;
1152 while (isSchemeChar(url[schemeEnd]))
1155 if (url[schemeEnd] != ':') {
1156 m_string = originalString ? *originalString : url;
1161 int userStart = schemeEnd + 1;
1170 bool hierarchical = url[schemeEnd + 1] == '/';
1172 bool isFile = schemeEnd == 4
1173 && matchLetter(url[0], 'f')
1174 && matchLetter(url[1], 'i')
1175 && matchLetter(url[2], 'l')
1176 && matchLetter(url[3], 'e');
1178 m_protocolInHTTPFamily = matchLetter(url[0], 'h')
1179 && matchLetter(url[1], 't')
1180 && matchLetter(url[2], 't')
1181 && matchLetter(url[3], 'p')
1182 && (url[4] == ':' || (matchLetter(url[4], 's') && url[5] == ':'));
1184 if (hierarchical && url[schemeEnd + 2] == '/') {
1185 // The part after the scheme is either a net_path or an abs_path whose first path segment is empty.
1186 // Attempt to find an authority.
1188 // FIXME: Authority characters may be scanned twice, and it would be nice to be faster.
1190 userEnd = userStart;
1193 while (isUserInfoChar(url[userEnd])) {
1194 if (url[userEnd] == ':' && colonPos == 0)
1199 if (url[userEnd] == '@') {
1200 // actual end of the userinfo, start on the host
1201 if (colonPos != 0) {
1202 passwordEnd = userEnd;
1204 passwordStart = colonPos + 1;
1206 passwordStart = passwordEnd = userEnd;
1208 hostStart = passwordEnd + 1;
1209 } else if (url[userEnd] == '[' || isPathSegmentEndChar(url[userEnd])) {
1210 // hit the end of the authority, must have been no user
1211 // or looks like an IPv6 hostname
1212 // either way, try to parse it as a hostname
1213 userEnd = userStart;
1214 passwordStart = passwordEnd = userEnd;
1215 hostStart = userStart;
1217 // invalid character
1218 m_string = originalString ? *originalString : url;
1223 hostEnd = hostStart;
1226 if (url[hostEnd] == '[') {
1228 while (isIPv6Char(url[hostEnd]))
1230 if (url[hostEnd] == ']')
1233 // invalid character
1234 m_string = originalString ? *originalString : url;
1239 while (isHostnameChar(url[hostEnd]))
1243 if (url[hostEnd] == ':') {
1244 portStart = portEnd = hostEnd + 1;
1246 // possible start of port
1247 portEnd = portStart;
1248 while (isASCIIDigit(url[portEnd]))
1251 portStart = portEnd = hostEnd;
1253 if (!isPathSegmentEndChar(url[portEnd])) {
1254 // invalid character
1255 m_string = originalString ? *originalString : url;
1260 if (userStart == portEnd && !m_protocolInHTTPFamily && !isFile) {
1261 // No authority found, which means that this is not a net_path, but rather an abs_path whose first two
1262 // path segments are empty. For file, http and https only, an empty authority is allowed.
1264 userEnd = userStart;
1265 passwordStart = userEnd;
1266 passwordEnd = passwordStart;
1267 hostStart = passwordEnd;
1268 hostEnd = hostStart;
1269 portStart = hostEnd;
1273 // the part after the scheme must be an opaque_part or an abs_path
1274 userEnd = userStart;
1275 passwordStart = passwordEnd = userEnd;
1276 hostStart = hostEnd = passwordEnd;
1277 portStart = portEnd = hostEnd;
1280 int pathStart = portEnd;
1281 int pathEnd = pathStart;
1282 while (url[pathEnd] && url[pathEnd] != '?' && url[pathEnd] != '#')
1285 int queryStart = pathEnd;
1286 int queryEnd = queryStart;
1287 if (url[queryStart] == '?') {
1288 while (url[queryEnd] && url[queryEnd] != '#')
1292 int fragmentStart = queryEnd;
1293 int fragmentEnd = fragmentStart;
1294 if (url[fragmentStart] == '#') {
1296 fragmentEnd = fragmentStart;
1297 while (url[fragmentEnd])
1301 // assemble it all, remembering the real ranges
1303 Vector<char, 4096> buffer(fragmentEnd * 3 + 1);
1305 char *p = buffer.data();
1306 const char *strPtr = url;
1308 // copy in the scheme
1309 const char *schemeEndPtr = url + schemeEnd;
1310 while (strPtr < schemeEndPtr)
1311 *p++ = toASCIILower(*strPtr++);
1312 m_schemeEnd = p - buffer.data();
1314 bool hostIsLocalHost = portEnd - userStart == 9
1315 && matchLetter(url[userStart], 'l')
1316 && matchLetter(url[userStart+1], 'o')
1317 && matchLetter(url[userStart+2], 'c')
1318 && matchLetter(url[userStart+3], 'a')
1319 && matchLetter(url[userStart+4], 'l')
1320 && matchLetter(url[userStart+5], 'h')
1321 && matchLetter(url[userStart+6], 'o')
1322 && matchLetter(url[userStart+7], 's')
1323 && matchLetter(url[userStart+8], 't');
1325 // File URLs need a host part unless it is just file:// or file://localhost
1326 bool degenFilePath = pathStart == pathEnd && (hostStart == hostEnd || hostIsLocalHost);
1328 bool haveNonHostAuthorityPart = userStart != userEnd || passwordStart != passwordEnd || portStart != portEnd;
1330 // add ":" after scheme
1333 // if we have at least one authority part or a file URL - add "//" and authority
1334 if (isFile ? !degenFilePath : (haveNonHostAuthorityPart || hostStart != hostEnd)) {
1338 m_userStart = p - buffer.data();
1341 strPtr = url + userStart;
1342 const char* userEndPtr = url + userEnd;
1343 while (strPtr < userEndPtr)
1345 m_userEnd = p - buffer.data();
1347 // copy in the password
1348 if (passwordEnd != passwordStart) {
1350 strPtr = url + passwordStart;
1351 const char* passwordEndPtr = url + passwordEnd;
1352 while (strPtr < passwordEndPtr)
1355 m_passwordEnd = p - buffer.data();
1357 // If we had any user info, add "@"
1358 if (p - buffer.data() != m_userStart)
1361 // copy in the host, except in the case of a file URL with authority="localhost"
1362 if (!(isFile && hostIsLocalHost && !haveNonHostAuthorityPart)) {
1363 strPtr = url + hostStart;
1364 const char* hostEndPtr = url + hostEnd;
1365 while (strPtr < hostEndPtr)
1368 m_hostEnd = p - buffer.data();
1370 // Copy in the port if the URL has one (and it's not default).
1371 if (hostEnd != portStart) {
1372 const char* portStr = url + portStart;
1373 size_t portLength = portEnd - portStart;
1374 if (portLength && !isDefaultPortForScheme(portStr, portLength, buffer.data(), m_schemeEnd)) {
1376 const char* portEndPtr = url + portEnd;
1377 while (portStr < portEndPtr)
1381 m_portEnd = p - buffer.data();
1383 m_userStart = m_userEnd = m_passwordEnd = m_hostEnd = m_portEnd = p - buffer.data();
1385 // For canonicalization, ensure we have a '/' for no path.
1386 // Do this only for hierarchical URL with protocol http or https.
1387 if (m_protocolInHTTPFamily && hierarchical && pathEnd == pathStart)
1390 // add path, escaping bad characters
1391 if (!hierarchical || !hasSlashDotOrDotDot(url))
1392 appendEscapingBadChars(p, url + pathStart, pathEnd - pathStart);
1394 CharBuffer pathBuffer(pathEnd - pathStart + 1);
1395 size_t length = copyPathRemovingDots(pathBuffer.data(), url, pathStart, pathEnd);
1396 appendEscapingBadChars(p, pathBuffer.data(), length);
1399 m_pathEnd = p - buffer.data();
1401 // Find the position after the last slash in the path, or
1402 // the position before the path if there are no slashes in it.
1404 for (i = m_pathEnd; i > m_portEnd; --i) {
1405 if (buffer[i - 1] == '/')
1408 m_pathAfterLastSlash = i;
1410 // add query, escaping bad characters
1411 appendEscapingBadChars(p, url + queryStart, queryEnd - queryStart);
1412 m_queryEnd = p - buffer.data();
1414 // add fragment, escaping bad characters
1415 if (fragmentEnd != queryEnd) {
1417 escapeAndAppendFragment(p, url + fragmentStart, fragmentEnd - fragmentStart);
1419 m_fragmentEnd = p - buffer.data();
1421 ASSERT(p - buffer.data() <= static_cast<int>(buffer.size()));
1423 // If we didn't end up actually changing the original string and
1424 // it was already in a String, reuse it to avoid extra allocation.
1425 if (originalString && originalString->length() == static_cast<unsigned>(m_fragmentEnd) && strncmp(buffer.data(), url, m_fragmentEnd) == 0)
1426 m_string = *originalString;
1428 m_string = String(buffer.data(), m_fragmentEnd);
1433 bool equalIgnoringFragmentIdentifier(const KURL& a, const KURL& b)
1435 if (a.m_queryEnd != b.m_queryEnd)
1437 unsigned queryLength = a.m_queryEnd;
1438 for (unsigned i = 0; i < queryLength; ++i)
1439 if (a.string()[i] != b.string()[i])
1444 bool protocolHostAndPortAreEqual(const KURL& a, const KURL& b)
1446 if (a.m_schemeEnd != b.m_schemeEnd)
1449 int hostStartA = a.hostStart();
1450 int hostLengthA = a.hostEnd() - hostStartA;
1451 int hostStartB = b.hostStart();
1452 int hostLengthB = b.hostEnd() - b.hostStart();
1453 if (hostLengthA != hostLengthB)
1457 for (int i = 0; i < a.m_schemeEnd; ++i)
1458 if (a.string()[i] != b.string()[i])
1462 for (int i = 0; i < hostLengthA; ++i)
1463 if (a.string()[hostStartA + i] != b.string()[hostStartB + i])
1466 if (a.port() != b.port())
1472 String encodeWithURLEscapeSequences(const String& notEncodedString)
1474 CString asUTF8 = notEncodedString.utf8();
1476 CharBuffer buffer(asUTF8.length() * 3 + 1);
1477 char* p = buffer.data();
1479 const char* str = asUTF8.data();
1480 const char* strEnd = str + asUTF8.length();
1481 while (str < strEnd) {
1482 unsigned char c = *str++;
1484 appendEscapedChar(p, c);
1489 ASSERT(p - buffer.data() <= static_cast<int>(buffer.size()));
1491 return String(buffer.data(), p - buffer.data());
1494 // Appends the punycoded hostname identified by the given string and length to
1495 // the output buffer. The result will not be null terminated.
1496 static void appendEncodedHostname(UCharBuffer& buffer, const UChar* str, unsigned strLen)
1498 // Needs to be big enough to hold an IDN-encoded name.
1499 // For host names bigger than this, we won't do IDN encoding, which is almost certainly OK.
1500 const unsigned hostnameBufferLength = 2048;
1502 if (strLen > hostnameBufferLength || charactersAreAllASCII(str, strLen)) {
1503 buffer.append(str, strLen);
1507 #if USE(ICU_UNICODE)
1508 UChar hostnameBuffer[hostnameBufferLength];
1509 UErrorCode error = U_ZERO_ERROR;
1510 int32_t numCharactersConverted = uidna_IDNToASCII(str, strLen, hostnameBuffer,
1511 hostnameBufferLength, UIDNA_ALLOW_UNASSIGNED, 0, &error);
1512 if (error == U_ZERO_ERROR)
1513 buffer.append(hostnameBuffer, numCharactersConverted);
1514 #elif USE(QT4_UNICODE)
1515 QByteArray result = QUrl::toAce(String(str, strLen));
1516 buffer.append(result.constData(), result.length());
1517 #elif USE(GLIB_UNICODE)
1518 GOwnPtr<gchar> utf8Hostname;
1519 GOwnPtr<GError> utf8Err;
1520 utf8Hostname.set(g_utf16_to_utf8(str, strLen, 0, 0, &utf8Err.outPtr()));
1524 GOwnPtr<gchar> encodedHostname;
1525 encodedHostname.set(g_hostname_to_ascii(utf8Hostname.get()));
1526 if (!encodedHostname)
1529 buffer.append(encodedHostname.get(), strlen(encodedHostname.get()));
1533 static void findHostnamesInMailToURL(const UChar* str, int strLen, Vector<pair<int, int> >& nameRanges)
1535 // In a mailto: URL, host names come after a '@' character and end with a '>' or ',' or '?' or end of string character.
1536 // Skip quoted strings so that characters in them don't confuse us.
1537 // When we find a '?' character, we are past the part of the URL that contains host names.
1543 // Find start of host name or of quoted string.
1544 int hostnameOrStringStart = findFirstOf(str, strLen, p, "\"@?");
1545 if (hostnameOrStringStart == -1)
1547 UChar c = str[hostnameOrStringStart];
1548 p = hostnameOrStringStart + 1;
1554 // Find end of host name.
1555 int hostnameStart = p;
1556 int hostnameEnd = findFirstOf(str, strLen, p, ">,?");
1558 if (hostnameEnd == -1) {
1559 hostnameEnd = strLen;
1566 nameRanges.append(make_pair(hostnameStart, hostnameEnd));
1571 // Skip quoted string.
1574 int escapedCharacterOrStringEnd = findFirstOf(str, strLen, p, "\"\\");
1575 if (escapedCharacterOrStringEnd == -1)
1578 c = str[escapedCharacterOrStringEnd];
1579 p = escapedCharacterOrStringEnd + 1;
1581 // If we are the end of the string, then break from the string loop back to the host name loop.
1585 // Skip escaped character.
1596 static bool findHostnameInHierarchicalURL(const UChar* str, int strLen, int& startOffset, int& endOffset)
1598 // Find the host name in a hierarchical URL.
1599 // It comes after a "://" sequence, with scheme characters preceding, and
1600 // this should be the first colon in the string.
1601 // It ends with the end of the string or a ":" or a path segment ending character.
1602 // If there is a "@" character, the host part is just the part after the "@".
1603 int separator = findFirstOf(str, strLen, 0, ":");
1604 if (separator == -1 || separator + 2 >= strLen ||
1605 str[separator + 1] != '/' || str[separator + 2] != '/')
1608 // Check that all characters before the :// are valid scheme characters.
1609 if (!isSchemeFirstChar(str[0]))
1611 for (int i = 1; i < separator; ++i) {
1612 if (!isSchemeChar(str[i]))
1616 // Start after the separator.
1617 int authorityStart = separator + 3;
1619 // Find terminating character.
1620 int hostnameEnd = strLen;
1621 for (int i = authorityStart; i < strLen; ++i) {
1623 if (c == ':' || (isPathSegmentEndChar(c) && c != 0)) {
1629 // Find "@" for the start of the host name.
1630 int userInfoTerminator = findFirstOf(str, strLen, authorityStart, "@");
1632 if (userInfoTerminator == -1 || userInfoTerminator > hostnameEnd)
1633 hostnameStart = authorityStart;
1635 hostnameStart = userInfoTerminator + 1;
1637 startOffset = hostnameStart;
1638 endOffset = hostnameEnd;
1642 // Converts all hostnames found in the given input to punycode, preserving the
1643 // rest of the URL unchanged. The output will NOT be null-terminated.
1644 static void encodeHostnames(const String& str, UCharBuffer& output)
1648 if (protocolIs(str, "mailto")) {
1649 Vector<pair<int, int> > hostnameRanges;
1650 findHostnamesInMailToURL(str.characters(), str.length(), hostnameRanges);
1651 int n = hostnameRanges.size();
1653 for (int i = 0; i < n; ++i) {
1654 const pair<int, int>& r = hostnameRanges[i];
1655 output.append(&str.characters()[p], r.first - p);
1656 appendEncodedHostname(output, &str.characters()[r.first], r.second - r.first);
1659 // This will copy either everything after the last hostname, or the
1660 // whole thing if there is no hostname.
1661 output.append(&str.characters()[p], str.length() - p);
1663 int hostStart, hostEnd;
1664 if (findHostnameInHierarchicalURL(str.characters(), str.length(), hostStart, hostEnd)) {
1665 output.append(str.characters(), hostStart); // Before hostname.
1666 appendEncodedHostname(output, &str.characters()[hostStart], hostEnd - hostStart);
1667 output.append(&str.characters()[hostEnd], str.length() - hostEnd); // After hostname.
1669 // No hostname to encode, return the input.
1670 output.append(str.characters(), str.length());
1675 static void encodeRelativeString(const String& rel, const TextEncoding& encoding, CharBuffer& output)
1678 encodeHostnames(rel, s);
1680 TextEncoding pathEncoding(UTF8Encoding()); // Path is always encoded as UTF-8; other parts may depend on the scheme.
1683 if (encoding != pathEncoding && encoding.isValid() && !protocolIs(rel, "mailto") && !protocolIs(rel, "data") && !protocolIsJavaScript(rel)) {
1684 // Find the first instance of either # or ?, keep pathEnd at -1 otherwise.
1685 pathEnd = findFirstOf(s.data(), s.size(), 0, "#?");
1688 if (pathEnd == -1) {
1689 CString decoded = pathEncoding.encode(s.data(), s.size(), URLEncodedEntitiesForUnencodables);
1690 output.resize(decoded.length());
1691 memcpy(output.data(), decoded.data(), decoded.length());
1693 CString pathDecoded = pathEncoding.encode(s.data(), pathEnd, URLEncodedEntitiesForUnencodables);
1694 // Unencodable characters in URLs are represented by converting
1695 // them to XML entities and escaping non-alphanumeric characters.
1696 CString otherDecoded = encoding.encode(s.data() + pathEnd, s.size() - pathEnd, URLEncodedEntitiesForUnencodables);
1698 output.resize(pathDecoded.length() + otherDecoded.length());
1699 memcpy(output.data(), pathDecoded.data(), pathDecoded.length());
1700 memcpy(output.data() + pathDecoded.length(), otherDecoded.data(), otherDecoded.length());
1702 output.append('\0'); // null-terminate the output.
1705 static String substituteBackslashes(const String& string)
1707 size_t questionPos = string.find('?');
1708 size_t hashPos = string.find('#');
1711 if (hashPos != notFound && (questionPos == notFound || questionPos > hashPos))
1713 else if (questionPos != notFound)
1714 pathEnd = questionPos;
1716 pathEnd = string.length();
1718 return string.left(pathEnd).replace('\\','/') + string.substring(pathEnd);
1721 bool KURL::isHierarchical() const
1725 ASSERT(m_string[m_schemeEnd] == ':');
1726 return m_string[m_schemeEnd + 1] == '/';
1729 void KURL::copyToBuffer(CharBuffer& buffer) const
1731 // FIXME: This throws away the high bytes of all the characters in the string!
1732 // That's fine for a valid URL, which is all ASCII, but not for invalid URLs.
1733 buffer.resize(m_string.length());
1734 copyASCII(m_string.characters(), m_string.length(), buffer.data());
1737 bool protocolIs(const String& url, const char* protocol)
1739 // Do the comparison without making a new string object.
1740 assertProtocolIsGood(protocol);
1741 for (int i = 0; ; ++i) {
1743 return url[i] == ':';
1744 if (toASCIILower(url[i]) != protocol[i])
1749 bool protocolIsJavaScript(const String& url)
1751 return protocolIs(url, "javascript");
1754 bool isValidProtocol(const String& protocol)
1756 // RFC3986: ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
1757 if (protocol.isEmpty())
1759 if (!isSchemeFirstChar(protocol[0]))
1761 unsigned protocolLength = protocol.length();
1762 for (unsigned i = 1; i < protocolLength; i++) {
1763 if (!isSchemeChar(protocol[i]))
1769 bool isDefaultPortForProtocol(unsigned short port, const String& protocol)
1771 if (protocol.isEmpty())
1774 typedef HashMap<String, unsigned, CaseFoldingHash> DefaultPortsMap;
1775 DEFINE_STATIC_LOCAL(DefaultPortsMap, defaultPorts, ());
1776 if (defaultPorts.isEmpty()) {
1777 defaultPorts.set("http", 80);
1778 defaultPorts.set("https", 443);
1779 defaultPorts.set("ftp", 21);
1780 defaultPorts.set("ftps", 990);
1782 return defaultPorts.get(protocol) == port;
1785 bool portAllowed(const KURL& url)
1787 unsigned short port = url.port();
1789 // Since most URLs don't have a port, return early for the "no port" case.
1793 // This blocked port list matches the port blocking that Mozilla implements.
1794 // See http://www.mozilla.org/projects/netlib/PortBanning.html for more information.
1795 static const unsigned short blockedPortList[] = {
1829 135, // loc-srv / epmap
1835 512, // print / exec
1852 3659, // apple-sasl / PasswordServer [Apple addition]
1855 6665, // Alternate IRC [Apple addition]
1856 6666, // Alternate IRC [Apple addition]
1857 6667, // Standard IRC [Apple addition]
1858 6668, // Alternate IRC [Apple addition]
1859 6669, // Alternate IRC [Apple addition]
1860 invalidPortNumber, // Used to block all invalid port numbers
1862 const unsigned short* const blockedPortListEnd = blockedPortList + WTF_ARRAY_LENGTH(blockedPortList);
1865 // The port list must be sorted for binary_search to work.
1866 static bool checkedPortList = false;
1867 if (!checkedPortList) {
1868 for (const unsigned short* p = blockedPortList; p != blockedPortListEnd - 1; ++p)
1869 ASSERT(*p < *(p + 1));
1870 checkedPortList = true;
1874 // If the port is not in the blocked port list, allow it.
1875 if (!binary_search(blockedPortList, blockedPortListEnd, port))
1878 // Allow ports 21 and 22 for FTP URLs, as Mozilla does.
1879 if ((port == 21 || port == 22) && url.protocolIs("ftp"))
1882 // Allow any port number in a file URL, since the port number is ignored.
1883 if (url.protocolIs("file"))
1889 String mimeTypeFromDataURL(const String& url)
1891 ASSERT(protocolIs(url, "data"));
1892 size_t index = url.find(';');
1893 if (index == notFound)
1894 index = url.find(',');
1895 if (index != notFound) {
1897 return url.substring(5, index - 5);
1898 return "text/plain"; // Data URLs with no MIME type are considered text/plain.
1903 const KURL& blankURL()
1905 DEFINE_STATIC_LOCAL(KURL, staticBlankURL, (ParsedURLString, "about:blank"));
1906 return staticBlankURL;
1910 void KURL::print() const
1912 printf("%s\n", m_string.utf8().data());
1918 #endif // !USE(GOOGLEURL)