2 * Copyright (C) 2004 Apple Computer, 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 COMPUTER, 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.
30 #include "PlatformString.h"
31 #include "RegularExpression.h"
32 #include "TextEncoding.h"
33 #include <wtf/Vector.h>
34 #include <unicode/uidna.h>
41 enum URLCharacterClasses {
43 SchemeFirstChar = 1 << 0,
45 // ( alpha | digit | "+" | "-" | "." )
48 // mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
49 // unreserved = alphanum | mark
50 // ( unreserved | escaped | ";" | ":" | "&" | "=" | "+" | "$" | "," )
51 UserInfoChar = 1 << 2,
53 // alnum | "." | "-" | "%"
54 // The above is what the specification says, but we are lenient to
55 // match existing practice and also allow:
57 HostnameChar = 1 << 3,
59 // hexdigit | ":" | "%"
62 // "#" | "?" | "/" | nul
63 PathSegmentEndChar = 1 << 5,
65 // digit | "A" | "B" | "C" | "D" | "E" | "F" | "a" | "b" | "c" | "d" | "e" | "f"
66 HexDigitChar = 1 << 6,
68 // not allowed in path
73 static const char hexDigits[17] = "0123456789ABCDEF";
75 static const unsigned char characterClassTable[256] = {
76 /* 0 nul */ PathSegmentEndChar, /* 1 soh */ BadChar,
77 /* 2 stx */ BadChar, /* 3 etx */ BadChar,
78 /* 4 eot */ BadChar, /* 5 enq */ BadChar, /* 6 ack */ BadChar, /* 7 bel */ BadChar,
79 /* 8 bs */ BadChar, /* 9 ht */ BadChar, /* 10 nl */ BadChar, /* 11 vt */ BadChar,
80 /* 12 np */ BadChar, /* 13 cr */ BadChar, /* 14 so */ BadChar, /* 15 si */ BadChar,
81 /* 16 dle */ BadChar, /* 17 dc1 */ BadChar, /* 18 dc2 */ BadChar, /* 19 dc3 */ BadChar,
82 /* 20 dc4 */ BadChar, /* 21 nak */ BadChar, /* 22 syn */ BadChar, /* 23 etb */ BadChar,
83 /* 24 can */ BadChar, /* 25 em */ BadChar, /* 26 sub */ BadChar, /* 27 esc */ BadChar,
84 /* 28 fs */ BadChar, /* 29 gs */ BadChar, /* 30 rs */ BadChar, /* 31 us */ BadChar,
85 /* 32 sp */ BadChar, /* 33 ! */ UserInfoChar,
86 /* 34 " */ BadChar, /* 35 # */ PathSegmentEndChar | BadChar,
87 /* 36 $ */ UserInfoChar, /* 37 % */ UserInfoChar | HostnameChar | IPv6Char | BadChar,
88 /* 38 & */ UserInfoChar, /* 39 ' */ UserInfoChar,
89 /* 40 ( */ UserInfoChar, /* 41 ) */ UserInfoChar,
90 /* 42 * */ UserInfoChar, /* 43 + */ SchemeChar | UserInfoChar,
91 /* 44 , */ UserInfoChar,
92 /* 45 - */ SchemeChar | UserInfoChar | HostnameChar,
93 /* 46 . */ SchemeChar | UserInfoChar | HostnameChar,
94 /* 47 / */ PathSegmentEndChar,
95 /* 48 0 */ SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
96 /* 49 1 */ SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
97 /* 50 2 */ SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
98 /* 51 3 */ SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
99 /* 52 4 */ SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
100 /* 53 5 */ SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
101 /* 54 6 */ SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
102 /* 55 7 */ SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
103 /* 56 8 */ SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
104 /* 57 9 */ SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
105 /* 58 : */ UserInfoChar | IPv6Char, /* 59 ; */ UserInfoChar,
106 /* 60 < */ BadChar, /* 61 = */ UserInfoChar,
107 /* 62 > */ BadChar, /* 63 ? */ PathSegmentEndChar | BadChar,
109 /* 65 A */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
110 /* 66 B */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
111 /* 67 C */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
112 /* 68 D */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
113 /* 69 E */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
114 /* 70 F */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
115 /* 71 G */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
116 /* 72 H */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
117 /* 73 I */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
118 /* 74 J */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
119 /* 75 K */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
120 /* 76 L */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
121 /* 77 M */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
122 /* 78 N */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
123 /* 79 O */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
124 /* 80 P */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
125 /* 81 Q */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
126 /* 82 R */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
127 /* 83 S */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
128 /* 84 T */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
129 /* 85 U */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
130 /* 86 V */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
131 /* 87 W */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
132 /* 88 X */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
133 /* 89 Y */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
134 /* 90 Z */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
136 /* 92 \ */ 0, /* 93 ] */ 0,
138 /* 95 _ */ UserInfoChar | HostnameChar,
140 /* 97 a */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
141 /* 98 b */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
142 /* 99 c */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
143 /* 100 d */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
144 /* 101 e */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
145 /* 102 f */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | HexDigitChar | IPv6Char,
146 /* 103 g */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
147 /* 104 h */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
148 /* 105 i */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
149 /* 106 j */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
150 /* 107 k */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
151 /* 108 l */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
152 /* 109 m */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
153 /* 110 n */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
154 /* 111 o */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
155 /* 112 p */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
156 /* 113 q */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
157 /* 114 r */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
158 /* 115 s */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
159 /* 116 t */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
160 /* 117 u */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
161 /* 118 v */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
162 /* 119 w */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
163 /* 120 x */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
164 /* 121 y */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
165 /* 122 z */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
167 /* 124 | */ 0, /* 125 } */ 0, /* 126 ~ */ UserInfoChar, /* 127 del */ BadChar,
168 /* 128 */ BadChar, /* 129 */ BadChar, /* 130 */ BadChar, /* 131 */ BadChar,
169 /* 132 */ BadChar, /* 133 */ BadChar, /* 134 */ BadChar, /* 135 */ BadChar,
170 /* 136 */ BadChar, /* 137 */ BadChar, /* 138 */ BadChar, /* 139 */ BadChar,
171 /* 140 */ BadChar, /* 141 */ BadChar, /* 142 */ BadChar, /* 143 */ BadChar,
172 /* 144 */ BadChar, /* 145 */ BadChar, /* 146 */ BadChar, /* 147 */ BadChar,
173 /* 148 */ BadChar, /* 149 */ BadChar, /* 150 */ BadChar, /* 151 */ BadChar,
174 /* 152 */ BadChar, /* 153 */ BadChar, /* 154 */ BadChar, /* 155 */ BadChar,
175 /* 156 */ BadChar, /* 157 */ BadChar, /* 158 */ BadChar, /* 159 */ BadChar,
176 /* 160 */ BadChar, /* 161 */ BadChar, /* 162 */ BadChar, /* 163 */ BadChar,
177 /* 164 */ BadChar, /* 165 */ BadChar, /* 166 */ BadChar, /* 167 */ BadChar,
178 /* 168 */ BadChar, /* 169 */ BadChar, /* 170 */ BadChar, /* 171 */ BadChar,
179 /* 172 */ BadChar, /* 173 */ BadChar, /* 174 */ BadChar, /* 175 */ BadChar,
180 /* 176 */ BadChar, /* 177 */ BadChar, /* 178 */ BadChar, /* 179 */ BadChar,
181 /* 180 */ BadChar, /* 181 */ BadChar, /* 182 */ BadChar, /* 183 */ BadChar,
182 /* 184 */ BadChar, /* 185 */ BadChar, /* 186 */ BadChar, /* 187 */ BadChar,
183 /* 188 */ BadChar, /* 189 */ BadChar, /* 190 */ BadChar, /* 191 */ BadChar,
184 /* 192 */ BadChar, /* 193 */ BadChar, /* 194 */ BadChar, /* 195 */ BadChar,
185 /* 196 */ BadChar, /* 197 */ BadChar, /* 198 */ BadChar, /* 199 */ BadChar,
186 /* 200 */ BadChar, /* 201 */ BadChar, /* 202 */ BadChar, /* 203 */ BadChar,
187 /* 204 */ BadChar, /* 205 */ BadChar, /* 206 */ BadChar, /* 207 */ BadChar,
188 /* 208 */ BadChar, /* 209 */ BadChar, /* 210 */ BadChar, /* 211 */ BadChar,
189 /* 212 */ BadChar, /* 213 */ BadChar, /* 214 */ BadChar, /* 215 */ BadChar,
190 /* 216 */ BadChar, /* 217 */ BadChar, /* 218 */ BadChar, /* 219 */ BadChar,
191 /* 220 */ BadChar, /* 221 */ BadChar, /* 222 */ BadChar, /* 223 */ BadChar,
192 /* 224 */ BadChar, /* 225 */ BadChar, /* 226 */ BadChar, /* 227 */ BadChar,
193 /* 228 */ BadChar, /* 229 */ BadChar, /* 230 */ BadChar, /* 231 */ BadChar,
194 /* 232 */ BadChar, /* 233 */ BadChar, /* 234 */ BadChar, /* 235 */ BadChar,
195 /* 236 */ BadChar, /* 237 */ BadChar, /* 238 */ BadChar, /* 239 */ BadChar,
196 /* 240 */ BadChar, /* 241 */ BadChar, /* 242 */ BadChar, /* 243 */ BadChar,
197 /* 244 */ BadChar, /* 245 */ BadChar, /* 246 */ BadChar, /* 247 */ BadChar,
198 /* 248 */ BadChar, /* 249 */ BadChar, /* 250 */ BadChar, /* 251 */ BadChar,
199 /* 252 */ BadChar, /* 253 */ BadChar, /* 254 */ BadChar, /* 255 */ BadChar
202 static int copyPathRemovingDots(char* dst, const char* src, int srcStart, int srcEnd);
203 static char* encodeRelativeString(const KURL &base, const DeprecatedString& rel, const TextEncoding&);
204 static DeprecatedString substituteBackslashes(const DeprecatedString &string);
206 static inline bool isSchemeFirstChar(unsigned char c) { return characterClassTable[c] & SchemeFirstChar; }
207 static inline bool isSchemeChar(unsigned char c) { return characterClassTable[c] & SchemeChar; }
208 static inline bool isUserInfoChar(unsigned char c) { return characterClassTable[c] & UserInfoChar; }
209 static inline bool isHostnameChar(unsigned char c) { return characterClassTable[c] & HostnameChar; }
210 static inline bool isIPv6Char(unsigned char c) { return characterClassTable[c] & IPv6Char; }
211 static inline bool isPathSegmentEndChar(unsigned char c) { return characterClassTable[c] & PathSegmentEndChar; }
212 static inline bool isBadChar(unsigned char c) { return characterClassTable[c] & BadChar; }
213 static inline bool isHexDigit(unsigned char c) { return characterClassTable[c] & HexDigitChar; }
215 static inline int hexDigitValue(unsigned char c)
217 ASSERT(isHexDigit(c));
220 return (c - 'A' + 10) & 0xF; // handle both upper and lower case without a branch
225 KURL::KURL() : m_isValid(false)
229 KURL::KURL(const char *url)
231 if (url && url[0] == '/') {
232 // 5 for "file:", 1 for terminator
233 size_t urlLength = strlen(url) + 1;
234 Vector<char, 2048> buffer(urlLength + 5);
240 memcpy(&buffer[5], url, urlLength);
246 KURL::KURL(const DeprecatedString &url)
248 if (!url.isEmpty() && url[0] == '/') {
249 // 5 for "file:", 1 for terminator
250 Vector<char, 2048> buffer(url.length() + 6);
256 url.copyLatin1(&buffer[5]);
259 parse(url.ascii(), &url);
262 KURL::KURL(const KURL& base, const DeprecatedString& relative)
264 init(base, relative, UTF8Encoding());
267 KURL::KURL(const KURL& base, const DeprecatedString& relative, const TextEncoding& encoding)
269 init(base, relative, encoding);
272 void KURL::init(const KURL &base, const DeprecatedString &relative, const TextEncoding& encoding)
274 // Allow at lest absolute URLs to resolve against an empty URL.
275 if (!base.m_isValid && !base.isEmpty()) {
280 bool absolute = false;
282 // for compatibility with Win IE, we must treat backslashes as if they were slashes, as long as we're not dealing with the javascript: schema
283 DeprecatedString substitutedRelative;
284 bool shouldSubstituteBackslashes = relative.contains('\\') && !relative.startsWith("javascript:", false);
285 if (shouldSubstituteBackslashes) {
286 substitutedRelative = substituteBackslashes(relative);
289 const DeprecatedString &rel = shouldSubstituteBackslashes ? substitutedRelative : relative;
291 bool allASCII = rel.isAllASCII();
298 strBuffer = encodeRelativeString(base, rel, encoding);
302 // workaround for sites that put leading whitespace whitespace on
304 bool strippedStart = false;
305 while (*str == ' ') {
307 strippedStart = true;
310 // workaround for trailing whitespace - a bit more complicated cause we have to copy
311 // it would be even better to replace null-termination with a length parameter
312 int len = strlen(str);
313 int charsToChopOffEnd = 0;
314 for (int pos = len - 1; pos >= 0 && str[pos] == ' '; pos--) {
317 if (charsToChopOffEnd > 0) {
318 char *newStrBuffer = (char *)fastMalloc((len + 1) - charsToChopOffEnd);
319 strncpy(newStrBuffer, str, len - charsToChopOffEnd);
320 newStrBuffer[len - charsToChopOffEnd] = '\0';
322 strBuffer = newStrBuffer;
326 // According to the RFC, the reference should be interpreted as an
327 // absolute URI if possible, using the "leftmost, longest"
328 // algorithm. If the URI reference is absolute it will have a
329 // scheme, meaning that it will have a colon before the first
330 // non-scheme element.
332 if (isSchemeFirstChar(*p)) {
334 while (isSchemeChar(*p)) {
338 if (p[1] != '/' && base.protocol().lower() == DeprecatedString(str, p - str).lower() && base.isHierarchical())
346 parse(str, (allASCII && !strippedStart && (charsToChopOffEnd == 0)) ? &rel : 0);
348 // if the base is invalid, just append the relative
349 // portion. The RFC does not specify what to do in this case.
350 if (!base.m_isValid) {
351 DeprecatedString newURL = base.urlString + str;
352 parse(newURL.ascii(), &newURL);
361 // the reference must be empty - the RFC says this is a
362 // reference to the same document
368 // must be fragment-only reference
370 DeprecatedString newURL = base.urlString.left(base.queryEndPos) + str;
371 parse(newURL.ascii(), &newURL);
375 // query-only reference, special case needed for non-URL results
377 DeprecatedString newURL = base.urlString.left(base.pathEndPos) + str;
378 parse(newURL.ascii(), &newURL);
382 // must be net-path or absolute-path reference
386 DeprecatedString newURL = base.urlString.left(base.schemeEndPos + 1) + str;
387 parse(newURL.ascii(), &newURL);
390 DeprecatedString newURL = base.urlString.left(base.portEndPos) + str;
391 parse(newURL.ascii(), &newURL);
397 // must be relative-path reference
399 // Base part plus relative part plus one possible slash added in between plus terminating \0 byte.
400 Vector<char, 2048> buffer(base.pathEndPos + 1 + strlen(str) + 1);
402 char *bufferPos = buffer;
404 // first copy everything before the path from the base
405 const char *baseString = base.urlString.ascii();
406 const char *baseStringStart = baseString;
407 const char *pathStart = baseStringStart + base.portEndPos;
408 while (baseStringStart < pathStart) {
409 *bufferPos++ = *baseStringStart++;
411 char *bufferPathStart = bufferPos;
413 // now copy the base path
414 const char *baseStringEnd = baseString + base.pathEndPos;
416 // go back to the last slash
417 while (baseStringEnd > baseStringStart && baseStringEnd[-1] != '/') {
421 if (baseStringEnd == baseStringStart) {
422 // no path in base, add a path separator if necessary
423 if (base.schemeEndPos + 1 != base.pathEndPos && *str != '\0' && *str != '?' && *str != '#') {
427 bufferPos += copyPathRemovingDots(bufferPos, baseStringStart, 0, baseStringEnd - baseStringStart);
430 const char *relStringStart = str;
431 const char *relStringPos = relStringStart;
433 while (*relStringPos != '\0' && *relStringPos != '?' && *relStringPos != '#') {
434 if (relStringPos[0] == '.' && bufferPos[-1] == '/') {
435 if (isPathSegmentEndChar(relStringPos[1])) {
436 // skip over "." segment
438 if (relStringPos[0] == '/') {
442 } else if (relStringPos[1] == '.' && isPathSegmentEndChar(relStringPos[2])) {
443 // skip over ".." segment and rewind the last segment
444 // the RFC leaves it up to the app to decide what to do with excess
445 // ".." segments - we choose to drop them since some web content
448 if (relStringPos[0] == '/') {
451 if (bufferPos > bufferPathStart + 1) {
454 while (bufferPos > bufferPathStart + 1 && bufferPos[-1] != '/') {
461 *bufferPos = *relStringPos;
466 // all done with the path work, now copy any remainder
467 // of the relative reference; this will also add a null terminator
468 strcpy(bufferPos, relStringPos);
472 ASSERT(strlen(buffer) + 1 <= buffer.size());
483 bool KURL::hasPath() const
485 return m_isValid && pathEndPos != portEndPos;
488 DeprecatedString KURL::protocol() const
491 return DeprecatedString();
494 return urlString.left(schemeEndPos);
497 DeprecatedString KURL::host() const
500 return DeprecatedString();
503 int start = (passwordEndPos == userStartPos) ? passwordEndPos : passwordEndPos + 1;
504 return decode_string(urlString.mid(start, hostEndPos - start));
507 unsigned short int KURL::port() const
513 if (hostEndPos != portEndPos) {
515 unsigned short result = urlString.mid(hostEndPos + 1, portEndPos - hostEndPos - 1).toUShort(&ok);
525 DeprecatedString KURL::pass() const
528 return DeprecatedString();
531 if (passwordEndPos == userEndPos) {
532 return DeprecatedString();
535 return decode_string(urlString.mid(userEndPos + 1, passwordEndPos - userEndPos - 1));
538 DeprecatedString KURL::user() const
541 return DeprecatedString();
544 return decode_string(urlString.mid(userStartPos, userEndPos - userStartPos));
547 DeprecatedString KURL::ref() const
549 if (!m_isValid || fragmentEndPos == queryEndPos) {
550 return DeprecatedString();
553 return urlString.mid(queryEndPos + 1, fragmentEndPos - (queryEndPos + 1));
556 bool KURL::hasRef() const
558 return m_isValid && fragmentEndPos != queryEndPos;
561 DeprecatedString KURL::query() const
564 return DeprecatedString();
567 return urlString.mid(pathEndPos, queryEndPos - pathEndPos);
570 DeprecatedString KURL::path() const
573 return DeprecatedString();
576 return decode_string(urlString.mid(portEndPos, pathEndPos - portEndPos));
579 void KURL::setProtocol(const DeprecatedString &s)
582 DeprecatedString newURL = s + ":" + urlString;
583 parse(newURL.ascii(), &newURL);
587 DeprecatedString newURL = s + urlString.mid(schemeEndPos);
588 parse(newURL.ascii(), &newURL);
591 void KURL::setHost(const DeprecatedString &s)
594 bool slashSlashNeeded = userStartPos == schemeEndPos + 1;
595 int hostStart = (passwordEndPos == userStartPos) ? passwordEndPos : passwordEndPos + 1;
597 DeprecatedString newURL = urlString.left(hostStart) + (slashSlashNeeded ? "//" : DeprecatedString()) + s + urlString.mid(hostEndPos);
598 parse(newURL.ascii(), &newURL);
602 void KURL::setPort(unsigned short i)
605 bool colonNeeded = portEndPos == hostEndPos;
606 int portStart = (colonNeeded ? hostEndPos : hostEndPos + 1);
607 DeprecatedString newURL = urlString.left(portStart) + (colonNeeded ? ":" : DeprecatedString()) + DeprecatedString::number(i) + urlString.mid(portEndPos);
608 parse(newURL.ascii(), &newURL);
612 void KURL::setUser(const DeprecatedString &user)
616 int end = userEndPos;
617 if (!user.isEmpty()) {
619 if (userStartPos == schemeEndPos + 1)
621 // Add '@' if we didn't have one before.
622 if (end == hostEndPos || (end == passwordEndPos && urlString[end] != '@'))
625 // Remove '@' if we now have neither user nor password.
626 if (userEndPos == passwordEndPos && end != hostEndPos && urlString[end] == '@')
629 const DeprecatedString newURL = urlString.left(userStartPos) + u + urlString.mid(end);
630 parse(newURL.ascii(), &newURL);
634 void KURL::setPass(const DeprecatedString &password)
638 int end = passwordEndPos;
639 if (!password.isEmpty()) {
640 p = ':' + password + '@';
641 if (userEndPos == schemeEndPos + 1)
643 // Eat the existing '@' since we are going to add our own.
644 if (end != hostEndPos && urlString[end] == '@')
647 // Remove '@' if we now have neither user nor password.
648 if (userStartPos == userEndPos && end != hostEndPos && urlString[end] == '@')
651 const DeprecatedString newURL = urlString.left(userEndPos) + p + urlString.mid(end);
652 parse(newURL.ascii(), &newURL);
656 void KURL::setRef(const DeprecatedString &s)
659 DeprecatedString newURL = urlString.left(queryEndPos) + (s.isEmpty() ? DeprecatedString() : "#" + s);
660 parse(newURL.ascii(), &newURL);
664 void KURL::setQuery(const DeprecatedString &query)
668 if (!query.isNull() && (query.isEmpty() || query[0] != '?')) {
674 DeprecatedString newURL = urlString.left(pathEndPos) + q + urlString.mid(queryEndPos);
675 parse(newURL.ascii(), &newURL);
679 void KURL::setPath(const DeprecatedString &s)
682 DeprecatedString newURL = urlString.left(portEndPos) + encode_string(s) + urlString.mid(pathEndPos);
683 parse(newURL.ascii(), &newURL);
687 DeprecatedString KURL::prettyURL() const
693 DeprecatedString result = protocol() + ":";
695 DeprecatedString authority;
697 if (hostEndPos != passwordEndPos) {
698 if (userEndPos != userStartPos) {
705 authority += DeprecatedString::number(port());
709 if (!authority.isEmpty())
710 result += "//" + authority;
711 else if (protocol() == "file")
717 if (fragmentEndPos != queryEndPos) {
718 result += "#" + ref();
724 DeprecatedString KURL::decode_string(const DeprecatedString& urlString)
726 return decode_string(urlString, UTF8Encoding());
729 DeprecatedString KURL::decode_string(const DeprecatedString& urlString, const TextEncoding& encoding)
731 DeprecatedString result("");
733 Vector<char, 2048> buffer(0);
735 int length = urlString.length();
736 int decodedPosition = 0;
737 int searchPosition = 0;
738 int encodedRunPosition;
739 while ((encodedRunPosition = urlString.find('%', searchPosition)) >= 0) {
740 // Find the sequence of %-escape codes.
741 int encodedRunEnd = encodedRunPosition;
742 while (length - encodedRunEnd >= 3
743 && urlString[encodedRunEnd] == '%'
744 && isHexDigit(urlString[encodedRunEnd + 1].latin1())
745 && isHexDigit(urlString[encodedRunEnd + 2].latin1()))
747 if (encodedRunEnd == encodedRunPosition) {
751 searchPosition = encodedRunEnd;
753 // Copy the entire %-escape sequence into an 8-bit buffer.
754 int encodedRunLength = encodedRunEnd - encodedRunPosition;
756 buffer.resize(encodedRunLength + 1);
757 urlString.copyLatin1(buffer, encodedRunPosition, encodedRunLength);
759 // Decode the %-escapes into bytes.
761 const char *q = buffer;
763 *p++ = (hexDigitValue(q[1]) << 4) | hexDigitValue(q[2]);
767 // Decode the bytes into Unicode characters.
768 String decoded = (encoding.isValid() ? encoding : UTF8Encoding()).decode(buffer, p - buffer);
769 if (decoded.isEmpty())
772 // Build up the string with what we just skipped and what we just decoded.
773 result.append(urlString.mid(decodedPosition, encodedRunPosition - decodedPosition));
774 result.append(reinterpret_cast<const DeprecatedChar*>(decoded.characters()), decoded.length());
775 decodedPosition = encodedRunEnd;
778 result.append(urlString.mid(decodedPosition, length - decodedPosition));
782 bool KURL::isLocalFile() const
784 // FIXME - include feed: here too?
785 return protocol() == "file";
788 static void appendEscapingBadChars(char*& buffer, const char *strStart, size_t length)
792 const char *str = strStart;
793 const char *strEnd = strStart + length;
794 while (str < strEnd) {
795 unsigned char c = *str++;
797 if (c == '%' || c == '?') {
799 } else if (c != 0x09 && c != 0x0a && c != 0x0d) {
801 *p++ = hexDigits[c >> 4];
802 *p++ = hexDigits[c & 0xF];
812 // copy a path, accounting for "." and ".." segments
813 static int copyPathRemovingDots(char *dst, const char *src, int srcStart, int srcEnd)
815 char *bufferPathStart = dst;
817 // empty path is a special case, and need not have a leading slash
818 if (srcStart != srcEnd) {
819 const char *baseStringStart = src + srcStart;
820 const char *baseStringEnd = src + srcEnd;
821 const char *baseStringPos = baseStringStart;
823 // this code is unprepared for paths that do not begin with a
824 // slash and we should always have one in the source string
825 ASSERT(baseStringPos[0] == '/');
827 // copy the leading slash into the destination
828 *dst = *baseStringPos;
832 while (baseStringPos < baseStringEnd) {
833 if (baseStringPos[0] == '.' && dst[-1] == '/') {
834 if (baseStringPos[1] == '/' || baseStringPos + 1 == baseStringEnd) {
835 // skip over "." segment
838 } else if (baseStringPos[1] == '.' && (baseStringPos[2] == '/' ||
839 baseStringPos + 2 == baseStringEnd)) {
840 // skip over ".." segment and rewind the last segment
841 // the RFC leaves it up to the app to decide what to do with excess
842 // ".." segments - we choose to drop them since some web content
845 if (dst > bufferPathStart + 1) {
848 // Note that these two while blocks differ subtly.
849 // The first helps to remove multiple adjoining slashes as we rewind.
850 // The +1 to bufferPathStart in the first while block prevents eating a leading slash
851 while (dst > bufferPathStart + 1 && dst[-1] == '/') {
854 while (dst > bufferPathStart && dst[-1] != '/') {
861 *dst = *baseStringPos;
867 return dst - bufferPathStart;
870 static inline bool hasSlashDotOrDotDot(const char *str)
872 const unsigned char *p = reinterpret_cast<const unsigned char *>(str);
875 unsigned char pc = *p;
876 while (unsigned char c = *++p) {
877 if (c == '.' && (pc == '/' || pc == '.'))
884 static inline bool matchLetter(char c, char lowercaseLetter)
886 return (c | 0x20) == lowercaseLetter;
889 void KURL::parse(const char *url, const DeprecatedString *originalString)
893 if (!url || url[0] == '\0') {
894 // valid URL must be non-empty
900 if (!isSchemeFirstChar(url[0])) {
901 // scheme must start with an alphabetic character
909 while (isSchemeChar(url[schemeEnd])) {
913 if (url[schemeEnd] != ':') {
919 int userStart = schemeEnd + 1;
928 bool hierarchical = url[schemeEnd + 1] == '/';
930 if (hierarchical && url[schemeEnd + 2] == '/') {
931 // part after the scheme must be a net_path, parse the authority section
933 // FIXME: authority characters may be scanned twice
938 while (isUserInfoChar(url[userEnd])) {
939 if (url[userEnd] == ':' && colonPos == 0) {
945 if (url[userEnd] == '@') {
946 // actual end of the userinfo, start on the host
948 passwordEnd = userEnd;
950 passwordStart = colonPos + 1;
952 passwordStart = passwordEnd = userEnd;
954 hostStart = passwordEnd + 1;
955 } else if (url[userEnd] == '[' || isPathSegmentEndChar(url[userEnd])) {
956 // hit the end of the authority, must have been no user
957 // or looks like an IPv6 hostname
958 // either way, try to parse it as a hostname
960 passwordStart = passwordEnd = userEnd;
961 hostStart = userStart;
972 if (url[hostEnd] == '[') {
974 while (isIPv6Char(url[hostEnd])) {
977 if (url[hostEnd] == ']') {
986 while (isHostnameChar(url[hostEnd])) {
991 if (url[hostEnd] == ':') {
992 portStart = portEnd = hostEnd + 1;
994 // possible start of port
996 while (isdigit(url[portEnd])) {
1000 portStart = portEnd = hostEnd;
1003 if (!isPathSegmentEndChar(url[portEnd])) {
1004 // invalid character
1010 // the part after the scheme must be an opaque_part or an abs_path
1011 userEnd = userStart;
1012 passwordStart = passwordEnd = userEnd;
1013 hostStart = hostEnd = passwordEnd;
1014 portStart = portEnd = hostEnd;
1017 int pathStart = portEnd;
1018 int pathEnd = pathStart;
1024 if (!hierarchical) {
1025 while (url[pathEnd] != '\0' && url[pathEnd] != '?') {
1028 queryStart = queryEnd = pathEnd;
1030 while (url[queryEnd] != '\0') {
1034 fragmentStart = fragmentEnd = queryEnd;
1037 while (url[pathEnd] != '\0' && url[pathEnd] != '?' && url[pathEnd] != '#') {
1041 queryStart = pathEnd;
1042 queryEnd = queryStart;
1043 if (url[queryStart] == '?') {
1044 while (url[queryEnd] != '\0' && url[queryEnd] != '#') {
1049 fragmentStart = queryEnd;
1050 fragmentEnd = fragmentStart;
1051 if (url[fragmentStart] == '#') {
1053 fragmentEnd = fragmentStart;
1054 while(url[fragmentEnd] != '\0') {
1060 // assemble it all, remembering the real ranges
1062 Vector<char, 4096> buffer(fragmentEnd * 3 + 1);
1065 const char *strPtr = url;
1067 // copy in the scheme
1068 const char *schemeEndPtr = url + schemeEnd;
1069 while (strPtr < schemeEndPtr) {
1072 schemeEndPos = p - buffer;
1074 // Check if we're http or https.
1075 bool isHTTPorHTTPS = matchLetter(url[0], 'h')
1076 && matchLetter(url[1], 't')
1077 && matchLetter(url[2], 't')
1078 && matchLetter(url[3], 'p')
1080 || (matchLetter(url[4], 's') && url[5] == ':'));
1082 bool hostIsLocalHost = portEnd - userStart == 9
1083 && matchLetter(url[userStart], 'l')
1084 && matchLetter(url[userStart+1], 'o')
1085 && matchLetter(url[userStart+2], 'c')
1086 && matchLetter(url[userStart+3], 'a')
1087 && matchLetter(url[userStart+4], 'l')
1088 && matchLetter(url[userStart+5], 'h')
1089 && matchLetter(url[userStart+6], 'o')
1090 && matchLetter(url[userStart+7], 's')
1091 && matchLetter(url[userStart+8], 't');
1093 bool isFile = matchLetter(url[0], 'f')
1094 && matchLetter(url[1], 'i')
1095 && matchLetter(url[2], 'l')
1096 && matchLetter(url[3], 'e')
1099 // File URLs need a host part unless it is just file:// or file://localhost
1100 bool degenFilePath = pathStart == pathEnd
1101 && (hostStart == hostEnd
1102 || hostIsLocalHost);
1104 bool haveNonHostAuthorityPart = userStart != userEnd || passwordStart != passwordEnd || portStart != portEnd;
1106 // add ":" after scheme
1109 // if we have at least one authority part or a file URL - add "//" and authority
1110 if (isFile ? !degenFilePath
1111 : (haveNonHostAuthorityPart || hostStart != hostEnd)) {
1113 //if ((isFile && !degenFilePath) || haveNonHostAuthorityPart || hostStart != hostEnd) {
1114 // still adds // for file://localhost, file://
1116 //if (!(isFile && degenFilePath) && (haveNonHostAuthorityPart || hostStart != hostEnd)) {
1117 //doesn't add // for things like file:///foo
1122 userStartPos = p - buffer;
1125 strPtr = url + userStart;
1126 const char *userEndPtr = url + userEnd;
1127 while (strPtr < userEndPtr) {
1130 userEndPos = p - buffer;
1132 // copy in the password
1133 if (passwordEnd != passwordStart) {
1135 strPtr = url + passwordStart;
1136 const char *passwordEndPtr = url + passwordEnd;
1137 while (strPtr < passwordEndPtr) {
1141 passwordEndPos = p - buffer;
1143 // If we had any user info, add "@"
1144 if (p - buffer != userStartPos) {
1148 // copy in the host, except in the case of a file URL with authority="localhost"
1149 if (!(isFile && hostIsLocalHost && !haveNonHostAuthorityPart)) {
1150 strPtr = url + hostStart;
1151 const char *hostEndPtr = url + hostEnd;
1152 while (strPtr < hostEndPtr) {
1156 hostEndPos = p - buffer;
1159 if (portEnd != portStart) {
1161 strPtr = url + portStart;
1162 const char *portEndPtr = url + portEnd;
1163 while (strPtr < portEndPtr) {
1167 portEndPos = p - buffer;
1169 userStartPos = userEndPos = passwordEndPos = hostEndPos = portEndPos = p - buffer;
1172 // For canonicalization, ensure we have a '/' for no path.
1173 // Only do this for http and https.
1174 if (isHTTPorHTTPS && pathEnd - pathStart == 0) {
1178 // add path, escaping bad characters
1180 if (hierarchical && hasSlashDotOrDotDot(url)) {
1181 Vector<char, 4096> path_buffer(pathEnd - pathStart + 1);
1182 copyPathRemovingDots(path_buffer, url, pathStart, pathEnd);
1183 appendEscapingBadChars(p, path_buffer, strlen(path_buffer));
1185 appendEscapingBadChars(p, url + pathStart, pathEnd - pathStart);
1187 pathEndPos = p - buffer;
1190 // add query, escaping bad characters
1191 appendEscapingBadChars(p, url + queryStart, queryEnd - queryStart);
1192 queryEndPos = p - buffer;
1194 // add fragment, escaping bad characters
1195 if (fragmentEnd != queryEnd) {
1197 appendEscapingBadChars(p, url + fragmentStart, fragmentEnd - fragmentStart);
1199 fragmentEndPos = p - buffer;
1201 // If we didn't end up actually changing the original string and
1202 // it started as a DeprecatedString, just reuse it, to avoid extra
1204 if (originalString && strncmp(buffer, url, fragmentEndPos) == 0) {
1205 urlString = *originalString;
1207 urlString = DeprecatedString(buffer, fragmentEndPos);
1209 ASSERT(p - buffer <= (int)buffer.size());
1212 bool operator==(const KURL &a, const KURL &b)
1214 return a.urlString == b.urlString;
1217 bool equalIgnoringRef(const KURL& a, const KURL& b)
1219 return a.urlString.left(a.queryEndPos) == b.urlString.left(b.queryEndPos);
1222 DeprecatedString KURL::encode_string(const DeprecatedString& notEncodedString)
1224 DeprecatedCString asUTF8 = notEncodedString.utf8();
1226 Vector<char, 4096> buffer(asUTF8.length() * 3 + 1);
1229 const char *str = asUTF8;
1230 const char *strEnd = str + asUTF8.length();
1231 while (str < strEnd) {
1232 unsigned char c = *str++;
1235 *p++ = hexDigits[c >> 4];
1236 *p++ = hexDigits[c & 0xF];
1241 DeprecatedString result(buffer, p - buffer);
1243 ASSERT(p - buffer <= (int)buffer.size());
1248 static DeprecatedString encodeHostname(const DeprecatedString &s)
1250 // Needs to be big enough to hold an IDN-encoded name.
1251 // For host names bigger than this, we won't do IDN encoding, which is almost certainly OK.
1252 const unsigned hostnameBufferLength = 2048;
1254 if (s.isAllASCII() || s.length() > hostnameBufferLength)
1257 UChar buffer[hostnameBufferLength];
1258 UErrorCode error = U_ZERO_ERROR;
1259 int32_t numCharactersConverted = uidna_IDNToASCII
1260 (reinterpret_cast<const UChar *>(s.unicode()), s.length(), buffer, hostnameBufferLength, UIDNA_ALLOW_UNASSIGNED, 0, &error);
1261 if (error != U_ZERO_ERROR) {
1264 return DeprecatedString(reinterpret_cast<DeprecatedChar *>(buffer), numCharactersConverted);
1267 static Vector<pair<int, int> > findHostnamesInMailToURL(const DeprecatedString &s)
1269 // In a mailto: URL, host names come after a '@' character and end with a '>' or ',' or '?' or end of string character.
1270 // Skip quoted strings so that characters in them don't confuse us.
1271 // When we find a '?' character, we are past the part of the URL that contains host names.
1273 Vector<pair<int, int> > a;
1277 // Find start of host name or of quoted string.
1278 int hostnameOrStringStart = s.find(RegularExpression("[\"@?]"), p);
1279 if (hostnameOrStringStart == -1) {
1282 DeprecatedChar c = s[hostnameOrStringStart];
1283 p = hostnameOrStringStart + 1;
1290 // Find end of host name.
1291 int hostnameStart = p;
1292 int hostnameEnd = s.find(RegularExpression("[>,?]"), p);
1294 if (hostnameEnd == -1) {
1295 hostnameEnd = s.length();
1302 a.append(make_pair(hostnameStart, hostnameEnd));
1307 // Skip quoted string.
1310 int escapedCharacterOrStringEnd = s.find(RegularExpression("[\"\\]"), p);
1311 if (escapedCharacterOrStringEnd == -1)
1314 c = s[escapedCharacterOrStringEnd];
1315 p = escapedCharacterOrStringEnd + 1;
1317 // If we are the end of the string, then break from the string loop back to the host name loop.
1321 // Skip escaped character.
1323 if (p == static_cast<int>(s.length()))
1332 static bool findHostnameInHierarchicalURL(const DeprecatedString &s, int &startOffset, int &endOffset)
1334 // Find the host name in a hierarchical URL.
1335 // It comes after a "://" sequence, with scheme characters preceding.
1336 // If ends with the end of the string or a ":" or a path segment ending character.
1337 // If there is a "@" character, the host part is just the part after the "@".
1338 int separator = s.find("://");
1339 if (separator <= 0) {
1343 // Check that all characters before the :// are valid scheme characters.
1344 if (!isSchemeFirstChar(s[0].latin1())) {
1347 for (int i = 1; i < separator; ++i) {
1348 if (!isSchemeChar(s[i].latin1())) {
1353 // Start after the separator.
1354 int authorityStart = separator + 3;
1356 // Find terminating character.
1357 int length = s.length();
1358 int hostnameEnd = length;
1359 for (int i = authorityStart; i < length; ++i) {
1360 char c = s[i].latin1();
1361 if (c == ':' || (isPathSegmentEndChar(c) && c != '\0')) {
1367 // Find "@" for the start of the host name.
1368 int userInfoTerminator = s.find('@', authorityStart);
1370 if (userInfoTerminator == -1 || userInfoTerminator > hostnameEnd) {
1371 hostnameStart = authorityStart;
1373 hostnameStart = userInfoTerminator + 1;
1376 startOffset = hostnameStart;
1377 endOffset = hostnameEnd;
1381 static DeprecatedString encodeHostnames(const DeprecatedString &s)
1383 if (s.startsWith("mailto:", false)) {
1384 const Vector<pair<int, int> > hostnameRanges = findHostnamesInMailToURL(s);
1385 int n = hostnameRanges.size();
1387 DeprecatedString result;
1389 for (int i = 0; i < n; ++i) {
1390 const pair<int, int> &r = hostnameRanges[i];
1391 result += s.mid(p, r.first);
1392 result += encodeHostname(s.mid(r.first, r.second - r.first));
1399 int hostStart, hostEnd;
1400 if (findHostnameInHierarchicalURL(s, hostStart, hostEnd)) {
1401 return s.left(hostStart) + encodeHostname(s.mid(hostStart, hostEnd - hostStart)) + s.mid(hostEnd);
1407 static char *encodeRelativeString(const KURL &base, const DeprecatedString &rel, const TextEncoding& encoding)
1409 DeprecatedString s = encodeHostnames(rel);
1413 TextEncoding pathEncoding(UTF8Encoding());
1414 TextEncoding otherEncoding = encoding.isValid() ? encoding : UTF8Encoding();
1417 if (pathEncoding != otherEncoding) {
1418 pathEnd = s.find(RegularExpression("[?#]"));
1420 if (pathEnd == -1) {
1421 CString decoded = pathEncoding.encode(reinterpret_cast<const UChar*>(s.unicode()), s.length());
1422 int decodedLength = decoded.length();
1423 strBuffer = static_cast<char *>(fastMalloc(decodedLength + 1));
1424 memcpy(strBuffer, decoded, decodedLength);
1425 strBuffer[decodedLength] = 0;
1427 int length = s.length();
1428 CString pathDecoded = pathEncoding.encode(reinterpret_cast<const UChar*>(s.unicode()), pathEnd);
1429 CString otherDecoded = otherEncoding.encode(reinterpret_cast<const UChar*>(s.unicode()) + pathEnd, length - pathEnd);
1430 int pathDecodedLength = pathDecoded.length();
1431 int otherDecodedLength = otherDecoded.length();
1432 strBuffer = static_cast<char *>(fastMalloc(pathDecodedLength + otherDecodedLength + 1));
1433 memcpy(strBuffer, pathDecoded, pathDecodedLength);
1434 memcpy(strBuffer + pathDecodedLength, otherDecoded, otherDecodedLength);
1435 strBuffer[pathDecodedLength + otherDecodedLength] = 0;
1441 static DeprecatedString substituteBackslashes(const DeprecatedString &string)
1443 int questionPos = string.find('?');
1444 int hashPos = string.find('#');
1447 if (hashPos >= 0 && (questionPos < 0 || questionPos > hashPos)) {
1449 } else if (questionPos >= 0) {
1450 pathEnd = questionPos;
1452 pathEnd = string.length();
1455 return string.left(pathEnd).replace('\\','/') + string.mid(pathEnd);
1458 bool KURL::isHierarchical() const
1462 assert(urlString[schemeEndPos] == ':');
1463 return urlString[schemeEndPos + 1] == '/';