• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2004, 2007, 2008 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
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.
12  *
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.
24  */
25 
26 #include "config.h"
27 
28 #if !USE(GOOGLEURL)
29 
30 #include "KURL.h"
31 
32 #include "CString.h"
33 #include "PlatformString.h"
34 #include "TextEncoding.h"
35 #include <wtf/StdLibExtras.h>
36 
37 #if USE(ICU_UNICODE)
38 #include <unicode/uidna.h>
39 #elif USE(QT4_UNICODE)
40 #include <QUrl>
41 #endif
42 
43 #include <stdio.h>
44 
45 using namespace std;
46 using namespace WTF;
47 
48 namespace WebCore {
49 
50 typedef Vector<char, 512> CharBuffer;
51 typedef Vector<UChar, 512> UCharBuffer;
52 
53 // FIXME: This file makes too much use of the + operator on String.
54 // We either have to optimize that operator so it doesn't involve
55 // so many allocations, or change this to use Vector<UChar> instead.
56 
57 enum URLCharacterClasses {
58     // alpha
59     SchemeFirstChar = 1 << 0,
60 
61     // ( alpha | digit | "+" | "-" | "." )
62     SchemeChar = 1 << 1,
63 
64     // mark        = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
65     // unreserved  = alphanum | mark
66     // ( unreserved | escaped | ";" | ":" | "&" | "=" | "+" | "$" | "," )
67     UserInfoChar = 1 << 2,
68 
69     // alnum | "." | "-" | "%"
70     // The above is what the specification says, but we are lenient to
71     // match existing practice and also allow:
72     // "_"
73     HostnameChar = 1 << 3,
74 
75     // hexdigit | ":" | "%"
76     IPv6Char = 1 << 4,
77 
78     // "#" | "?" | "/" | nul
79     PathSegmentEndChar = 1 << 5,
80 
81     // not allowed in path
82     BadChar = 1 << 6
83 };
84 
85 static const char hexDigits[17] = "0123456789ABCDEF";
86 
87 static const unsigned char characterClassTable[256] = {
88     /* 0 nul */ PathSegmentEndChar,    /* 1 soh */ BadChar,
89     /* 2 stx */ BadChar,    /* 3 etx */ BadChar,
90     /* 4 eot */ BadChar,    /* 5 enq */ BadChar,    /* 6 ack */ BadChar,    /* 7 bel */ BadChar,
91     /* 8 bs */ BadChar,     /* 9 ht */ BadChar,     /* 10 nl */ BadChar,    /* 11 vt */ BadChar,
92     /* 12 np */ BadChar,    /* 13 cr */ BadChar,    /* 14 so */ BadChar,    /* 15 si */ BadChar,
93     /* 16 dle */ BadChar,   /* 17 dc1 */ BadChar,   /* 18 dc2 */ BadChar,   /* 19 dc3 */ BadChar,
94     /* 20 dc4 */ BadChar,   /* 21 nak */ BadChar,   /* 22 syn */ BadChar,   /* 23 etb */ BadChar,
95     /* 24 can */ BadChar,   /* 25 em */ BadChar,    /* 26 sub */ BadChar,   /* 27 esc */ BadChar,
96     /* 28 fs */ BadChar,    /* 29 gs */ BadChar,    /* 30 rs */ BadChar,    /* 31 us */ BadChar,
97     /* 32 sp */ BadChar,    /* 33  ! */ UserInfoChar,
98     /* 34  " */ BadChar,    /* 35  # */ PathSegmentEndChar | BadChar,
99     /* 36  $ */ UserInfoChar,    /* 37  % */ UserInfoChar | HostnameChar | IPv6Char | BadChar,
100     /* 38  & */ UserInfoChar,    /* 39  ' */ UserInfoChar,
101     /* 40  ( */ UserInfoChar,    /* 41  ) */ UserInfoChar,
102     /* 42  * */ UserInfoChar,    /* 43  + */ SchemeChar | UserInfoChar,
103     /* 44  , */ UserInfoChar,
104     /* 45  - */ SchemeChar | UserInfoChar | HostnameChar,
105     /* 46  . */ SchemeChar | UserInfoChar | HostnameChar,
106     /* 47  / */ PathSegmentEndChar,
107     /* 48  0 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
108     /* 49  1 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
109     /* 50  2 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
110     /* 51  3 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
111     /* 52  4 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
112     /* 53  5 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
113     /* 54  6 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
114     /* 55  7 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
115     /* 56  8 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
116     /* 57  9 */ SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
117     /* 58  : */ UserInfoChar | IPv6Char,    /* 59  ; */ UserInfoChar,
118     /* 60  < */ BadChar,    /* 61  = */ UserInfoChar,
119     /* 62  > */ BadChar,    /* 63  ? */ PathSegmentEndChar | BadChar,
120     /* 64  @ */ 0,
121     /* 65  A */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
122     /* 66  B */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
123     /* 67  C */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
124     /* 68  D */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
125     /* 69  E */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
126     /* 70  F */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
127     /* 71  G */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
128     /* 72  H */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
129     /* 73  I */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
130     /* 74  J */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
131     /* 75  K */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
132     /* 76  L */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
133     /* 77  M */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
134     /* 78  N */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
135     /* 79  O */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
136     /* 80  P */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
137     /* 81  Q */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
138     /* 82  R */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
139     /* 83  S */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
140     /* 84  T */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
141     /* 85  U */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
142     /* 86  V */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
143     /* 87  W */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
144     /* 88  X */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
145     /* 89  Y */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
146     /* 90  Z */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
147     /* 91  [ */ 0,
148     /* 92  \ */ 0,    /* 93  ] */ 0,
149     /* 94  ^ */ 0,
150     /* 95  _ */ UserInfoChar | HostnameChar,
151     /* 96  ` */ 0,
152     /* 97  a */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
153     /* 98  b */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
154     /* 99  c */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
155     /* 100  d */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
156     /* 101  e */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
157     /* 102  f */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar | IPv6Char,
158     /* 103  g */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
159     /* 104  h */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
160     /* 105  i */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
161     /* 106  j */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
162     /* 107  k */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
163     /* 108  l */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
164     /* 109  m */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
165     /* 110  n */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
166     /* 111  o */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
167     /* 112  p */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
168     /* 113  q */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
169     /* 114  r */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
170     /* 115  s */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
171     /* 116  t */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
172     /* 117  u */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
173     /* 118  v */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
174     /* 119  w */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
175     /* 120  x */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
176     /* 121  y */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
177     /* 122  z */ SchemeFirstChar | SchemeChar | UserInfoChar | HostnameChar,
178     /* 123  { */ 0,
179     /* 124  | */ 0,   /* 125  } */ 0,   /* 126  ~ */ UserInfoChar,   /* 127 del */ BadChar,
180     /* 128 */ BadChar, /* 129 */ BadChar, /* 130 */ BadChar, /* 131 */ BadChar,
181     /* 132 */ BadChar, /* 133 */ BadChar, /* 134 */ BadChar, /* 135 */ BadChar,
182     /* 136 */ BadChar, /* 137 */ BadChar, /* 138 */ BadChar, /* 139 */ BadChar,
183     /* 140 */ BadChar, /* 141 */ BadChar, /* 142 */ BadChar, /* 143 */ BadChar,
184     /* 144 */ BadChar, /* 145 */ BadChar, /* 146 */ BadChar, /* 147 */ BadChar,
185     /* 148 */ BadChar, /* 149 */ BadChar, /* 150 */ BadChar, /* 151 */ BadChar,
186     /* 152 */ BadChar, /* 153 */ BadChar, /* 154 */ BadChar, /* 155 */ BadChar,
187     /* 156 */ BadChar, /* 157 */ BadChar, /* 158 */ BadChar, /* 159 */ BadChar,
188     /* 160 */ BadChar, /* 161 */ BadChar, /* 162 */ BadChar, /* 163 */ BadChar,
189     /* 164 */ BadChar, /* 165 */ BadChar, /* 166 */ BadChar, /* 167 */ BadChar,
190     /* 168 */ BadChar, /* 169 */ BadChar, /* 170 */ BadChar, /* 171 */ BadChar,
191     /* 172 */ BadChar, /* 173 */ BadChar, /* 174 */ BadChar, /* 175 */ BadChar,
192     /* 176 */ BadChar, /* 177 */ BadChar, /* 178 */ BadChar, /* 179 */ BadChar,
193     /* 180 */ BadChar, /* 181 */ BadChar, /* 182 */ BadChar, /* 183 */ BadChar,
194     /* 184 */ BadChar, /* 185 */ BadChar, /* 186 */ BadChar, /* 187 */ BadChar,
195     /* 188 */ BadChar, /* 189 */ BadChar, /* 190 */ BadChar, /* 191 */ BadChar,
196     /* 192 */ BadChar, /* 193 */ BadChar, /* 194 */ BadChar, /* 195 */ BadChar,
197     /* 196 */ BadChar, /* 197 */ BadChar, /* 198 */ BadChar, /* 199 */ BadChar,
198     /* 200 */ BadChar, /* 201 */ BadChar, /* 202 */ BadChar, /* 203 */ BadChar,
199     /* 204 */ BadChar, /* 205 */ BadChar, /* 206 */ BadChar, /* 207 */ BadChar,
200     /* 208 */ BadChar, /* 209 */ BadChar, /* 210 */ BadChar, /* 211 */ BadChar,
201     /* 212 */ BadChar, /* 213 */ BadChar, /* 214 */ BadChar, /* 215 */ BadChar,
202     /* 216 */ BadChar, /* 217 */ BadChar, /* 218 */ BadChar, /* 219 */ BadChar,
203     /* 220 */ BadChar, /* 221 */ BadChar, /* 222 */ BadChar, /* 223 */ BadChar,
204     /* 224 */ BadChar, /* 225 */ BadChar, /* 226 */ BadChar, /* 227 */ BadChar,
205     /* 228 */ BadChar, /* 229 */ BadChar, /* 230 */ BadChar, /* 231 */ BadChar,
206     /* 232 */ BadChar, /* 233 */ BadChar, /* 234 */ BadChar, /* 235 */ BadChar,
207     /* 236 */ BadChar, /* 237 */ BadChar, /* 238 */ BadChar, /* 239 */ BadChar,
208     /* 240 */ BadChar, /* 241 */ BadChar, /* 242 */ BadChar, /* 243 */ BadChar,
209     /* 244 */ BadChar, /* 245 */ BadChar, /* 246 */ BadChar, /* 247 */ BadChar,
210     /* 248 */ BadChar, /* 249 */ BadChar, /* 250 */ BadChar, /* 251 */ BadChar,
211     /* 252 */ BadChar, /* 253 */ BadChar, /* 254 */ BadChar, /* 255 */ BadChar
212 };
213 
214 static int copyPathRemovingDots(char* dst, const char* src, int srcStart, int srcEnd);
215 static void encodeRelativeString(const String& rel, const TextEncoding&, CharBuffer& ouput);
216 static String substituteBackslashes(const String&);
217 
isSchemeFirstChar(char c)218 static inline bool isSchemeFirstChar(char c) { return characterClassTable[static_cast<unsigned char>(c)] & SchemeFirstChar; }
isSchemeFirstChar(UChar c)219 static inline bool isSchemeFirstChar(UChar c) { return c <= 0xff && (characterClassTable[c] & SchemeFirstChar); }
isSchemeChar(char c)220 static inline bool isSchemeChar(char c) { return characterClassTable[static_cast<unsigned char>(c)] & SchemeChar; }
isSchemeChar(UChar c)221 static inline bool isSchemeChar(UChar c) { return c <= 0xff && (characterClassTable[c] & SchemeChar); }
isUserInfoChar(unsigned char c)222 static inline bool isUserInfoChar(unsigned char c) { return characterClassTable[c] & UserInfoChar; }
isHostnameChar(unsigned char c)223 static inline bool isHostnameChar(unsigned char c) { return characterClassTable[c] & HostnameChar; }
isIPv6Char(unsigned char c)224 static inline bool isIPv6Char(unsigned char c) { return characterClassTable[c] & IPv6Char; }
isPathSegmentEndChar(char c)225 static inline bool isPathSegmentEndChar(char c) { return characterClassTable[static_cast<unsigned char>(c)] & PathSegmentEndChar; }
isPathSegmentEndChar(UChar c)226 static inline bool isPathSegmentEndChar(UChar c) { return c <= 0xff && (characterClassTable[c] & PathSegmentEndChar); }
isBadChar(unsigned char c)227 static inline bool isBadChar(unsigned char c) { return characterClassTable[c] & BadChar; }
228 
hexDigitValue(UChar c)229 static inline int hexDigitValue(UChar c)
230 {
231     ASSERT(isASCIIHexDigit(c));
232     if (c < 'A')
233         return c - '0';
234     return (c - 'A' + 10) & 0xF; // handle both upper and lower case without a branch
235 }
236 
237 // Copies the source to the destination, assuming all the source characters are
238 // ASCII. The destination buffer must be large enough. Null characters are allowed
239 // in the source string, and no attempt is made to null-terminate the result.
copyASCII(const UChar * src,int length,char * dest)240 static void copyASCII(const UChar* src, int length, char* dest)
241 {
242     for (int i = 0; i < length; i++)
243         dest[i] = static_cast<char>(src[i]);
244 }
245 
appendASCII(const String & base,const char * rel,size_t len,CharBuffer & buffer)246 static void appendASCII(const String& base, const char* rel, size_t len, CharBuffer& buffer)
247 {
248     buffer.resize(base.length() + len + 1);
249     copyASCII(base.characters(), base.length(), buffer.data());
250     memcpy(buffer.data() + base.length(), rel, len);
251     buffer[buffer.size() - 1] = '\0';
252 }
253 
254 // FIXME: Move to PlatformString.h eventually.
255 // Returns the index of the first index in string |s| of any of the characters
256 // in |toFind|. |toFind| should be a null-terminated string, all characters up
257 // to the null will be searched. Returns int if not found.
findFirstOf(const UChar * s,int sLen,int startPos,const char * toFind)258 static int findFirstOf(const UChar* s, int sLen, int startPos, const char* toFind)
259 {
260     for (int i = startPos; i < sLen; i++) {
261         const char* cur = toFind;
262         while (*cur) {
263             if (s[i] == *(cur++))
264                 return i;
265         }
266     }
267     return -1;
268 }
269 
270 #ifndef NDEBUG
checkEncodedString(const String & url)271 static void checkEncodedString(const String& url)
272 {
273     for (unsigned i = 0; i < url.length(); ++i)
274         ASSERT(!(url[i] & ~0x7F));
275 
276     ASSERT(!url.length() || isSchemeFirstChar(url[0]));
277 }
278 #else
checkEncodedString(const String &)279 static inline void checkEncodedString(const String&)
280 {
281 }
282 #endif
283 
protocolIs(const String & string,const char * protocol)284 inline bool KURL::protocolIs(const String& string, const char* protocol)
285 {
286     return WebCore::protocolIs(string, protocol);
287 }
288 
invalidate()289 void KURL::invalidate()
290 {
291     m_isValid = false;
292     m_protocolInHTTPFamily = false;
293     m_schemeEnd = 0;
294     m_userStart = 0;
295     m_userEnd = 0;
296     m_passwordEnd = 0;
297     m_hostEnd = 0;
298     m_portEnd = 0;
299     m_pathEnd = 0;
300     m_pathAfterLastSlash = 0;
301     m_queryEnd = 0;
302     m_fragmentEnd = 0;
303 }
304 
KURL(const char * url)305 KURL::KURL(const char* url)
306 {
307     parse(url, 0);
308     ASSERT(url == m_string);
309 }
310 
KURL(const String & url)311 KURL::KURL(const String& url)
312 {
313     parse(url);
314     ASSERT(url == m_string);
315 }
316 
KURL(const KURL & base,const String & relative)317 KURL::KURL(const KURL& base, const String& relative)
318 {
319     init(base, relative, UTF8Encoding());
320 }
321 
KURL(const KURL & base,const String & relative,const TextEncoding & encoding)322 KURL::KURL(const KURL& base, const String& relative, const TextEncoding& encoding)
323 {
324     // For UTF-{7,16,32}, we want to use UTF-8 for the query part as
325     // we do when submitting a form. A form with GET method
326     // has its contents added to a URL as query params and it makes sense
327     // to be consistent.
328     init(base, relative, encoding.encodingForFormSubmission());
329 }
330 
init(const KURL & base,const String & relative,const TextEncoding & encoding)331 void KURL::init(const KURL& base, const String& relative, const TextEncoding& encoding)
332 {
333     // Allow resolutions with a null or empty base URL, but not with any other invalid one.
334     // FIXME: Is this a good rule?
335     if (!base.m_isValid && !base.isEmpty()) {
336         m_string = relative;
337         invalidate();
338         return;
339     }
340 
341     // For compatibility with Win IE, treat backslashes as if they were slashes,
342     // as long as we're not dealing with javascript: or data: URLs.
343     String rel = relative;
344     if (rel.contains('\\') && !(protocolIsJavaScript(rel) || protocolIs(rel, "data")))
345         rel = substituteBackslashes(rel);
346 
347     String* originalString = &rel;
348 
349     bool allASCII = charactersAreAllASCII(rel.characters(), rel.length());
350     CharBuffer strBuffer;
351     char* str;
352     size_t len;
353     if (allASCII) {
354         len = rel.length();
355         strBuffer.resize(len + 1);
356         copyASCII(rel.characters(), len, strBuffer.data());
357         strBuffer[len] = 0;
358         str = strBuffer.data();
359     } else {
360         originalString = 0;
361         encodeRelativeString(rel, encoding, strBuffer);
362         str = strBuffer.data();
363         len = strlen(str);
364     }
365 
366     // Get rid of leading whitespace.
367     while (*str == ' ') {
368         originalString = 0;
369         str++;
370         --len;
371     }
372 
373     // Get rid of trailing whitespace.
374     while (len && str[len - 1] == ' ') {
375         originalString = 0;
376         str[--len] = '\0';
377     }
378 
379     // According to the RFC, the reference should be interpreted as an
380     // absolute URI if possible, using the "leftmost, longest"
381     // algorithm. If the URI reference is absolute it will have a
382     // scheme, meaning that it will have a colon before the first
383     // non-scheme element.
384     bool absolute = false;
385     char* p = str;
386     if (isSchemeFirstChar(*p)) {
387         ++p;
388         while (isSchemeChar(*p)) {
389             ++p;
390         }
391         if (*p == ':') {
392             if (p[1] != '/' && equalIgnoringCase(base.protocol(), String(str, p - str)) && base.isHierarchical()) {
393                 str = p + 1;
394                 originalString = 0;
395             } else
396                 absolute = true;
397         }
398     }
399 
400     CharBuffer parseBuffer;
401 
402     if (absolute) {
403         parse(str, originalString);
404     } else {
405         // If the base is empty or opaque (e.g. data: or javascript:), then the URL is invalid
406         // unless the relative URL is a single fragment.
407         if (!base.isHierarchical()) {
408             if (str[0] == '#') {
409                 appendASCII(base.m_string.left(base.m_queryEnd), str, len, parseBuffer);
410                 parse(parseBuffer.data(), 0);
411             } else {
412                 m_string = relative;
413                 invalidate();
414             }
415             return;
416         }
417 
418         switch (str[0]) {
419         case '\0':
420             // the reference must be empty - the RFC says this is a
421             // reference to the same document
422             *this = base;
423             break;
424         case '#': {
425             // must be fragment-only reference
426             appendASCII(base.m_string.left(base.m_queryEnd), str, len, parseBuffer);
427             parse(parseBuffer.data(), 0);
428             break;
429         }
430         case '?': {
431             // query-only reference, special case needed for non-URL results
432             appendASCII(base.m_string.left(base.m_pathEnd), str, len, parseBuffer);
433             parse(parseBuffer.data(), 0);
434             break;
435         }
436         case '/':
437             // must be net-path or absolute-path reference
438             if (str[1] == '/') {
439                 // net-path
440                 appendASCII(base.m_string.left(base.m_schemeEnd + 1), str, len, parseBuffer);
441                 parse(parseBuffer.data(), 0);
442             } else {
443                 // abs-path
444                 appendASCII(base.m_string.left(base.m_portEnd), str, len, parseBuffer);
445                 parse(parseBuffer.data(), 0);
446             }
447             break;
448         default:
449             {
450                 // must be relative-path reference
451 
452                 // Base part plus relative part plus one possible slash added in between plus terminating \0 byte.
453                 parseBuffer.resize(base.m_pathEnd + 1 + len + 1);
454 
455                 char* bufferPos = parseBuffer.data();
456 
457                 // first copy everything before the path from the base
458                 unsigned baseLength = base.m_string.length();
459                 const UChar* baseCharacters = base.m_string.characters();
460                 CharBuffer baseStringBuffer(baseLength);
461                 copyASCII(baseCharacters, baseLength, baseStringBuffer.data());
462                 const char* baseString = baseStringBuffer.data();
463                 const char* baseStringStart = baseString;
464                 const char* pathStart = baseStringStart + base.m_portEnd;
465                 while (baseStringStart < pathStart)
466                     *bufferPos++ = *baseStringStart++;
467                 char* bufferPathStart = bufferPos;
468 
469                 // now copy the base path
470                 const char* baseStringEnd = baseString + base.m_pathEnd;
471 
472                 // go back to the last slash
473                 while (baseStringEnd > baseStringStart && baseStringEnd[-1] != '/')
474                     baseStringEnd--;
475 
476                 if (baseStringEnd == baseStringStart) {
477                     // no path in base, add a path separator if necessary
478                     if (base.m_schemeEnd + 1 != base.m_pathEnd && *str && *str != '?' && *str != '#')
479                         *bufferPos++ = '/';
480                 } else {
481                     bufferPos += copyPathRemovingDots(bufferPos, baseStringStart, 0, baseStringEnd - baseStringStart);
482                 }
483 
484                 const char* relStringStart = str;
485                 const char* relStringPos = relStringStart;
486 
487                 while (*relStringPos && *relStringPos != '?' && *relStringPos != '#') {
488                     if (relStringPos[0] == '.' && bufferPos[-1] == '/') {
489                         if (isPathSegmentEndChar(relStringPos[1])) {
490                             // skip over "." segment
491                             relStringPos += 1;
492                             if (relStringPos[0] == '/')
493                                 relStringPos++;
494                             continue;
495                         } else if (relStringPos[1] == '.' && isPathSegmentEndChar(relStringPos[2])) {
496                             // skip over ".." segment and rewind the last segment
497                             // the RFC leaves it up to the app to decide what to do with excess
498                             // ".." segments - we choose to drop them since some web content
499                             // relies on this.
500                             relStringPos += 2;
501                             if (relStringPos[0] == '/')
502                                 relStringPos++;
503                             if (bufferPos > bufferPathStart + 1)
504                                 bufferPos--;
505                             while (bufferPos > bufferPathStart + 1  && bufferPos[-1] != '/')
506                                 bufferPos--;
507                             continue;
508                         }
509                     }
510 
511                     *bufferPos = *relStringPos;
512                     relStringPos++;
513                     bufferPos++;
514                 }
515 
516                 // all done with the path work, now copy any remainder
517                 // of the relative reference; this will also add a null terminator
518                 strcpy(bufferPos, relStringPos);
519 
520                 parse(parseBuffer.data(), 0);
521 
522                 ASSERT(strlen(parseBuffer.data()) + 1 <= parseBuffer.size());
523                 break;
524             }
525         }
526     }
527 }
528 
copy() const529 KURL KURL::copy() const
530 {
531     KURL result = *this;
532     result.m_string = result.m_string.copy();
533     return result;
534 }
535 
hasPath() const536 bool KURL::hasPath() const
537 {
538     return m_pathEnd != m_portEnd;
539 }
540 
lastPathComponent() const541 String KURL::lastPathComponent() const
542 {
543     if (!hasPath())
544         return String();
545 
546     int end = m_pathEnd - 1;
547     if (m_string[end] == '/')
548         --end;
549 
550     int start = m_string.reverseFind('/', end);
551     if (start < m_portEnd)
552         return String();
553     ++start;
554 
555     return m_string.substring(start, end - start + 1);
556 }
557 
protocol() const558 String KURL::protocol() const
559 {
560     return m_string.left(m_schemeEnd);
561 }
562 
host() const563 String KURL::host() const
564 {
565     int start = hostStart();
566     return decodeURLEscapeSequences(m_string.substring(start, m_hostEnd - start));
567 }
568 
port() const569 unsigned short KURL::port() const
570 {
571     if (m_hostEnd == m_portEnd)
572         return 0;
573 
574     int number = m_string.substring(m_hostEnd + 1, m_portEnd - m_hostEnd - 1).toInt();
575     if (number < 0 || number > 0xFFFF)
576         return 0;
577     return number;
578 }
579 
pass() const580 String KURL::pass() const
581 {
582     if (m_passwordEnd == m_userEnd)
583         return String();
584 
585     return decodeURLEscapeSequences(m_string.substring(m_userEnd + 1, m_passwordEnd - m_userEnd - 1));
586 }
587 
user() const588 String KURL::user() const
589 {
590     return decodeURLEscapeSequences(m_string.substring(m_userStart, m_userEnd - m_userStart));
591 }
592 
fragmentIdentifier() const593 String KURL::fragmentIdentifier() const
594 {
595     if (m_fragmentEnd == m_queryEnd)
596         return String();
597 
598     return m_string.substring(m_queryEnd + 1, m_fragmentEnd - (m_queryEnd + 1));
599 }
600 
hasFragmentIdentifier() const601 bool KURL::hasFragmentIdentifier() const
602 {
603     return m_fragmentEnd != m_queryEnd;
604 }
605 
baseAsString() const606 String KURL::baseAsString() const
607 {
608     return m_string.left(m_pathAfterLastSlash);
609 }
610 
611 #ifdef NDEBUG
612 
assertProtocolIsGood(const char *)613 static inline void assertProtocolIsGood(const char*)
614 {
615 }
616 
617 #else
618 
assertProtocolIsGood(const char * protocol)619 static void assertProtocolIsGood(const char* protocol)
620 {
621     const char* p = protocol;
622     while (*p) {
623         ASSERT(*p > ' ' && *p < 0x7F && !(*p >= 'A' && *p <= 'Z'));
624         ++p;
625     }
626 }
627 
628 #endif
629 
protocolIs(const char * protocol) const630 bool KURL::protocolIs(const char* protocol) const
631 {
632     assertProtocolIsGood(protocol);
633 
634     // JavaScript URLs are "valid" and should be executed even if KURL decides they are invalid.
635     // The free function protocolIsJavaScript() should be used instead.
636     ASSERT(strcmp(protocol, "javascript") != 0);
637 
638     if (!m_isValid)
639         return false;
640 
641     // Do the comparison without making a new string object.
642     for (int i = 0; i < m_schemeEnd; ++i) {
643         if (!protocol[i] || toASCIILower(m_string[i]) != protocol[i])
644             return false;
645     }
646     return !protocol[m_schemeEnd]; // We should have consumed all characters in the argument.
647 }
648 
query() const649 String KURL::query() const
650 {
651     if (m_queryEnd == m_pathEnd)
652         return String();
653 
654     return m_string.substring(m_pathEnd + 1, m_queryEnd - (m_pathEnd + 1));
655 }
656 
path() const657 String KURL::path() const
658 {
659     return decodeURLEscapeSequences(m_string.substring(m_portEnd, m_pathEnd - m_portEnd));
660 }
661 
setProtocol(const String & s)662 void KURL::setProtocol(const String& s)
663 {
664     // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations,
665     // and to avoid changing more than just the protocol.
666 
667     if (!m_isValid) {
668         parse(s + ":" + m_string);
669         return;
670     }
671 
672     parse(s + m_string.substring(m_schemeEnd));
673 }
674 
setHost(const String & s)675 void KURL::setHost(const String& s)
676 {
677     if (!m_isValid)
678         return;
679 
680     // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations,
681     // and to avoid changing more than just the host.
682 
683     bool slashSlashNeeded = m_userStart == m_schemeEnd + 1;
684 
685     parse(m_string.left(hostStart()) + (slashSlashNeeded ? "//" : "") + s + m_string.substring(m_hostEnd));
686 }
687 
setPort(unsigned short i)688 void KURL::setPort(unsigned short i)
689 {
690     if (!m_isValid)
691         return;
692 
693     if (i) {
694         bool colonNeeded = m_portEnd == m_hostEnd;
695         int portStart = (colonNeeded ? m_hostEnd : m_hostEnd + 1);
696 
697         parse(m_string.left(portStart) + (colonNeeded ? ":" : "") + String::number(i) + m_string.substring(m_portEnd));
698     } else
699         parse(m_string.left(m_hostEnd) + m_string.substring(m_portEnd));
700 }
701 
setHostAndPort(const String & hostAndPort)702 void KURL::setHostAndPort(const String& hostAndPort)
703 {
704     if (!m_isValid)
705         return;
706 
707     // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations,
708     // and to avoid changing more than just host and port.
709 
710     bool slashSlashNeeded = m_userStart == m_schemeEnd + 1;
711 
712     parse(m_string.left(hostStart()) + (slashSlashNeeded ? "//" : "") + hostAndPort + m_string.substring(m_portEnd));
713 }
714 
setUser(const String & user)715 void KURL::setUser(const String& user)
716 {
717     if (!m_isValid)
718         return;
719 
720     // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations,
721     // and to avoid changing more than just the user login.
722     String u;
723     int end = m_userEnd;
724     if (!user.isEmpty()) {
725         u = user;
726         if (m_userStart == m_schemeEnd + 1)
727             u = "//" + u;
728         // Add '@' if we didn't have one before.
729         if (end == m_hostEnd || (end == m_passwordEnd && m_string[end] != '@'))
730             u.append('@');
731     } else {
732         // Remove '@' if we now have neither user nor password.
733         if (m_userEnd == m_passwordEnd && end != m_hostEnd && m_string[end] == '@')
734             end += 1;
735     }
736     parse(m_string.left(m_userStart) + u + m_string.substring(end));
737 }
738 
setPass(const String & password)739 void KURL::setPass(const String& password)
740 {
741     if (!m_isValid)
742         return;
743 
744     // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations,
745     // and to avoid changing more than just the user password.
746     String p;
747     int end = m_passwordEnd;
748     if (!password.isEmpty()) {
749         p = ":" + password + "@";
750         if (m_userEnd == m_schemeEnd + 1)
751             p = "//" + p;
752         // Eat the existing '@' since we are going to add our own.
753         if (end != m_hostEnd && m_string[end] == '@')
754             end += 1;
755     } else {
756         // Remove '@' if we now have neither user nor password.
757         if (m_userStart == m_userEnd && end != m_hostEnd && m_string[end] == '@')
758             end += 1;
759     }
760     parse(m_string.left(m_userEnd) + p + m_string.substring(end));
761 }
762 
setFragmentIdentifier(const String & s)763 void KURL::setFragmentIdentifier(const String& s)
764 {
765     if (!m_isValid)
766         return;
767 
768     // FIXME: Non-ASCII characters must be encoded and escaped to match parse() expectations.
769     parse(m_string.left(m_queryEnd) + "#" + s);
770 }
771 
removeFragmentIdentifier()772 void KURL::removeFragmentIdentifier()
773 {
774     if (!m_isValid)
775         return;
776     parse(m_string.left(m_queryEnd));
777 }
778 
setQuery(const String & query)779 void KURL::setQuery(const String& query)
780 {
781     if (!m_isValid)
782         return;
783 
784     // FIXME: '#' and non-ASCII characters must be encoded and escaped.
785     // Usually, the query is encoded using document encoding, not UTF-8, but we don't have
786     // access to the document in this function.
787     if ((query.isEmpty() || query[0] != '?') && !query.isNull())
788         parse(m_string.left(m_pathEnd) + "?" + query + m_string.substring(m_queryEnd));
789     else
790         parse(m_string.left(m_pathEnd) + query + m_string.substring(m_queryEnd));
791 
792 }
793 
setPath(const String & s)794 void KURL::setPath(const String& s)
795 {
796     if (!m_isValid)
797         return;
798 
799     // FIXME: encodeWithURLEscapeSequences does not correctly escape '#' and '?', so fragment and query parts
800     // may be inadvertently affected.
801     parse(m_string.left(m_portEnd) + encodeWithURLEscapeSequences(s) + m_string.substring(m_pathEnd));
802 }
803 
prettyURL() const804 String KURL::prettyURL() const
805 {
806     if (!m_isValid)
807         return m_string;
808 
809     Vector<UChar> result;
810 
811     append(result, protocol());
812     result.append(':');
813 
814     Vector<UChar> authority;
815 
816     if (m_hostEnd != m_passwordEnd) {
817         if (m_userEnd != m_userStart) {
818             append(authority, user());
819             authority.append('@');
820         }
821         append(authority, host());
822         if (port() != 0) {
823             authority.append(':');
824             append(authority, String::number(port()));
825         }
826     }
827 
828     if (!authority.isEmpty()) {
829         result.append('/');
830         result.append('/');
831         result.append(authority);
832     } else if (protocolIs("file")) {
833         result.append('/');
834         result.append('/');
835     }
836 
837     append(result, path());
838 
839     if (m_pathEnd != m_queryEnd) {
840         result.append('?');
841         append(result, query());
842     }
843 
844     if (m_fragmentEnd != m_queryEnd) {
845         result.append('#');
846         append(result, fragmentIdentifier());
847     }
848 
849     return String::adopt(result);
850 }
851 
decodeURLEscapeSequences(const String & str)852 String decodeURLEscapeSequences(const String& str)
853 {
854     return decodeURLEscapeSequences(str, UTF8Encoding());
855 }
856 
decodeURLEscapeSequences(const String & str,const TextEncoding & encoding)857 String decodeURLEscapeSequences(const String& str, const TextEncoding& encoding)
858 {
859     Vector<UChar> result;
860 
861     CharBuffer buffer;
862 
863     int length = str.length();
864     int decodedPosition = 0;
865     int searchPosition = 0;
866     int encodedRunPosition;
867     while ((encodedRunPosition = str.find('%', searchPosition)) >= 0) {
868         // Find the sequence of %-escape codes.
869         int encodedRunEnd = encodedRunPosition;
870         while (length - encodedRunEnd >= 3
871                 && str[encodedRunEnd] == '%'
872                 && isASCIIHexDigit(str[encodedRunEnd + 1])
873                 && isASCIIHexDigit(str[encodedRunEnd + 2]))
874             encodedRunEnd += 3;
875         if (encodedRunEnd == encodedRunPosition) {
876             ++searchPosition;
877             continue;
878         }
879         searchPosition = encodedRunEnd;
880 
881         // Decode the %-escapes into bytes.
882         unsigned runLength = (encodedRunEnd - encodedRunPosition) / 3;
883         buffer.resize(runLength);
884         char* p = buffer.data();
885         const UChar* q = str.characters() + encodedRunPosition;
886         for (unsigned i = 0; i < runLength; ++i) {
887             *p++ = (hexDigitValue(q[1]) << 4) | hexDigitValue(q[2]);
888             q += 3;
889         }
890 
891         // Decode the bytes into Unicode characters.
892         String decoded = (encoding.isValid() ? encoding : UTF8Encoding()).decode(buffer.data(), p - buffer.data());
893         if (decoded.isEmpty())
894             continue;
895 
896         // Build up the string with what we just skipped and what we just decoded.
897         result.append(str.characters() + decodedPosition, encodedRunPosition - decodedPosition);
898         result.append(decoded.characters(), decoded.length());
899         decodedPosition = encodedRunEnd;
900     }
901 
902     result.append(str.characters() + decodedPosition, length - decodedPosition);
903 
904     return String::adopt(result);
905 }
906 
isLocalFile() const907 bool KURL::isLocalFile() const
908 {
909     // Including feed here might be a bad idea since drag and drop uses this check
910     // and including feed would allow feeds to potentially let someone's blog
911     // read the contents of the clipboard on a drag, even without a drop.
912     // Likewise with using the FrameLoader::shouldTreatURLAsLocal() function.
913     return protocolIs("file");
914 }
915 
appendEscapingBadChars(char * & buffer,const char * strStart,size_t length)916 static void appendEscapingBadChars(char*& buffer, const char* strStart, size_t length)
917 {
918     char* p = buffer;
919 
920     const char* str = strStart;
921     const char* strEnd = strStart + length;
922     while (str < strEnd) {
923         unsigned char c = *str++;
924         if (isBadChar(c)) {
925             if (c == '%' || c == '?') {
926                 *p++ = c;
927             } else if (c != 0x09 && c != 0x0a && c != 0x0d) {
928                 *p++ = '%';
929                 *p++ = hexDigits[c >> 4];
930                 *p++ = hexDigits[c & 0xF];
931             }
932         } else {
933             *p++ = c;
934         }
935     }
936 
937     buffer = p;
938 }
939 
940 // copy a path, accounting for "." and ".." segments
copyPathRemovingDots(char * dst,const char * src,int srcStart,int srcEnd)941 static int copyPathRemovingDots(char* dst, const char* src, int srcStart, int srcEnd)
942 {
943     char* bufferPathStart = dst;
944 
945     // empty path is a special case, and need not have a leading slash
946     if (srcStart != srcEnd) {
947         const char* baseStringStart = src + srcStart;
948         const char* baseStringEnd = src + srcEnd;
949         const char* baseStringPos = baseStringStart;
950 
951         // this code is unprepared for paths that do not begin with a
952         // slash and we should always have one in the source string
953         ASSERT(baseStringPos[0] == '/');
954 
955         // copy the leading slash into the destination
956         *dst = *baseStringPos;
957         baseStringPos++;
958         dst++;
959 
960         while (baseStringPos < baseStringEnd) {
961             if (baseStringPos[0] == '.' && dst[-1] == '/') {
962                 if (baseStringPos[1] == '/' || baseStringPos + 1 == baseStringEnd) {
963                     // skip over "." segment
964                     baseStringPos += 2;
965                     continue;
966                 } else if (baseStringPos[1] == '.' && (baseStringPos[2] == '/' ||
967                                        baseStringPos + 2 == baseStringEnd)) {
968                     // skip over ".." segment and rewind the last segment
969                     // the RFC leaves it up to the app to decide what to do with excess
970                     // ".." segments - we choose to drop them since some web content
971                     // relies on this.
972                     baseStringPos += 3;
973                     if (dst > bufferPathStart + 1)
974                         dst--;
975                     // Note that these two while blocks differ subtly.
976                     // The first helps to remove multiple adjoining slashes as we rewind.
977                     // The +1 to bufferPathStart in the first while block prevents eating a leading slash
978                     while (dst > bufferPathStart + 1 && dst[-1] == '/')
979                         dst--;
980                     while (dst > bufferPathStart && dst[-1] != '/')
981                         dst--;
982                     continue;
983                 }
984             }
985 
986             *dst = *baseStringPos;
987             baseStringPos++;
988             dst++;
989         }
990     }
991     *dst = '\0';
992     return dst - bufferPathStart;
993 }
994 
hasSlashDotOrDotDot(const char * str)995 static inline bool hasSlashDotOrDotDot(const char* str)
996 {
997     const unsigned char* p = reinterpret_cast<const unsigned char*>(str);
998     if (!*p)
999         return false;
1000     unsigned char pc = *p;
1001     while (unsigned char c = *++p) {
1002         if (c == '.' && (pc == '/' || pc == '.'))
1003             return true;
1004         pc = c;
1005     }
1006     return false;
1007 }
1008 
matchLetter(char c,char lowercaseLetter)1009 static inline bool matchLetter(char c, char lowercaseLetter)
1010 {
1011     return (c | 0x20) == lowercaseLetter;
1012 }
1013 
parse(const String & string)1014 void KURL::parse(const String& string)
1015 {
1016     checkEncodedString(string);
1017 
1018     CharBuffer buffer(string.length() + 1);
1019     copyASCII(string.characters(), string.length(), buffer.data());
1020     buffer[string.length()] = '\0';
1021     parse(buffer.data(), &string);
1022 }
1023 
parse(const char * url,const String * originalString)1024 void KURL::parse(const char* url, const String* originalString)
1025 {
1026     if (!url || url[0] == '\0') {
1027         // valid URL must be non-empty
1028         m_string = originalString ? *originalString : url;
1029         invalidate();
1030         return;
1031     }
1032 
1033     if (!isSchemeFirstChar(url[0])) {
1034         // scheme must start with an alphabetic character
1035         m_string = originalString ? *originalString : url;
1036         invalidate();
1037         return;
1038     }
1039 
1040     int schemeEnd = 0;
1041     while (isSchemeChar(url[schemeEnd]))
1042         schemeEnd++;
1043 
1044     if (url[schemeEnd] != ':') {
1045         m_string = originalString ? *originalString : url;
1046         invalidate();
1047         return;
1048     }
1049 
1050     int userStart = schemeEnd + 1;
1051     int userEnd;
1052     int passwordStart;
1053     int passwordEnd;
1054     int hostStart;
1055     int hostEnd;
1056     int portStart;
1057     int portEnd;
1058 
1059     bool hierarchical = url[schemeEnd + 1] == '/';
1060 
1061     bool isFile = schemeEnd == 4
1062         && matchLetter(url[0], 'f')
1063         && matchLetter(url[1], 'i')
1064         && matchLetter(url[2], 'l')
1065         && matchLetter(url[3], 'e');
1066 
1067     m_protocolInHTTPFamily = matchLetter(url[0], 'h')
1068         && matchLetter(url[1], 't')
1069         && matchLetter(url[2], 't')
1070         && matchLetter(url[3], 'p')
1071         && (url[4] == ':' || (matchLetter(url[4], 's') && url[5] == ':'));
1072 
1073     if (hierarchical && url[schemeEnd + 2] == '/') {
1074         // The part after the scheme is either a net_path or an abs_path whose first path segment is empty.
1075         // Attempt to find an authority.
1076 
1077         // FIXME: Authority characters may be scanned twice, and it would be nice to be faster.
1078         userStart += 2;
1079         userEnd = userStart;
1080 
1081         int colonPos = 0;
1082         while (isUserInfoChar(url[userEnd])) {
1083             if (url[userEnd] == ':' && colonPos == 0)
1084                 colonPos = userEnd;
1085             userEnd++;
1086         }
1087 
1088         if (url[userEnd] == '@') {
1089             // actual end of the userinfo, start on the host
1090             if (colonPos != 0) {
1091                 passwordEnd = userEnd;
1092                 userEnd = colonPos;
1093                 passwordStart = colonPos + 1;
1094             } else
1095                 passwordStart = passwordEnd = userEnd;
1096 
1097             hostStart = passwordEnd + 1;
1098         } else if (url[userEnd] == '[' || isPathSegmentEndChar(url[userEnd])) {
1099             // hit the end of the authority, must have been no user
1100             // or looks like an IPv6 hostname
1101             // either way, try to parse it as a hostname
1102             userEnd = userStart;
1103             passwordStart = passwordEnd = userEnd;
1104             hostStart = userStart;
1105         } else {
1106             // invalid character
1107             m_string = originalString ? *originalString : url;
1108             invalidate();
1109             return;
1110         }
1111 
1112         hostEnd = hostStart;
1113 
1114         // IPV6 IP address
1115         if (url[hostEnd] == '[') {
1116             hostEnd++;
1117             while (isIPv6Char(url[hostEnd]))
1118                 hostEnd++;
1119             if (url[hostEnd] == ']')
1120                 hostEnd++;
1121             else {
1122                 // invalid character
1123                 m_string = originalString ? *originalString : url;
1124                 invalidate();
1125                 return;
1126             }
1127         } else {
1128             while (isHostnameChar(url[hostEnd]))
1129                 hostEnd++;
1130         }
1131 
1132         if (url[hostEnd] == ':') {
1133             portStart = portEnd = hostEnd + 1;
1134 
1135             // possible start of port
1136             portEnd = portStart;
1137             while (isASCIIDigit(url[portEnd]))
1138                 portEnd++;
1139         } else
1140             portStart = portEnd = hostEnd;
1141 
1142         if (!isPathSegmentEndChar(url[portEnd])) {
1143             // invalid character
1144             m_string = originalString ? *originalString : url;
1145             invalidate();
1146             return;
1147         }
1148 
1149         if (userStart == portEnd && !m_protocolInHTTPFamily && !isFile) {
1150             // No authority found, which means that this is not a net_path, but rather an abs_path whose first two
1151             // path segments are empty. For file, http and https only, an empty authority is allowed.
1152             userStart -= 2;
1153             userEnd = userStart;
1154             passwordStart = userEnd;
1155             passwordEnd = passwordStart;
1156             hostStart = passwordEnd;
1157             hostEnd = hostStart;
1158             portStart = hostEnd;
1159             portEnd = hostEnd;
1160         }
1161     } else {
1162         // the part after the scheme must be an opaque_part or an abs_path
1163         userEnd = userStart;
1164         passwordStart = passwordEnd = userEnd;
1165         hostStart = hostEnd = passwordEnd;
1166         portStart = portEnd = hostEnd;
1167     }
1168 
1169     int pathStart = portEnd;
1170     int pathEnd = pathStart;
1171     while (url[pathEnd] && url[pathEnd] != '?' && url[pathEnd] != '#')
1172         pathEnd++;
1173 
1174     int queryStart = pathEnd;
1175     int queryEnd = queryStart;
1176     if (url[queryStart] == '?') {
1177         while (url[queryEnd] && url[queryEnd] != '#')
1178             queryEnd++;
1179     }
1180 
1181     int fragmentStart = queryEnd;
1182     int fragmentEnd = fragmentStart;
1183     if (url[fragmentStart] == '#') {
1184         fragmentStart++;
1185         fragmentEnd = fragmentStart;
1186         while (url[fragmentEnd])
1187             fragmentEnd++;
1188     }
1189 
1190     // assemble it all, remembering the real ranges
1191 
1192     Vector<char, 4096> buffer(fragmentEnd * 3 + 1);
1193 
1194     char *p = buffer.data();
1195     const char *strPtr = url;
1196 
1197     // copy in the scheme
1198     const char *schemeEndPtr = url + schemeEnd;
1199     while (strPtr < schemeEndPtr)
1200         *p++ = *strPtr++;
1201     m_schemeEnd = p - buffer.data();
1202 
1203     bool hostIsLocalHost = portEnd - userStart == 9
1204         && matchLetter(url[userStart], 'l')
1205         && matchLetter(url[userStart+1], 'o')
1206         && matchLetter(url[userStart+2], 'c')
1207         && matchLetter(url[userStart+3], 'a')
1208         && matchLetter(url[userStart+4], 'l')
1209         && matchLetter(url[userStart+5], 'h')
1210         && matchLetter(url[userStart+6], 'o')
1211         && matchLetter(url[userStart+7], 's')
1212         && matchLetter(url[userStart+8], 't');
1213 
1214     // File URLs need a host part unless it is just file:// or file://localhost
1215     bool degenFilePath = pathStart == pathEnd && (hostStart == hostEnd || hostIsLocalHost);
1216 
1217     bool haveNonHostAuthorityPart = userStart != userEnd || passwordStart != passwordEnd || portStart != portEnd;
1218 
1219     // add ":" after scheme
1220     *p++ = ':';
1221 
1222     // if we have at least one authority part or a file URL - add "//" and authority
1223     if (isFile ? !degenFilePath : (haveNonHostAuthorityPart || hostStart != hostEnd)) {
1224         *p++ = '/';
1225         *p++ = '/';
1226 
1227         m_userStart = p - buffer.data();
1228 
1229         // copy in the user
1230         strPtr = url + userStart;
1231         const char* userEndPtr = url + userEnd;
1232         while (strPtr < userEndPtr)
1233             *p++ = *strPtr++;
1234         m_userEnd = p - buffer.data();
1235 
1236         // copy in the password
1237         if (passwordEnd != passwordStart) {
1238             *p++ = ':';
1239             strPtr = url + passwordStart;
1240             const char* passwordEndPtr = url + passwordEnd;
1241             while (strPtr < passwordEndPtr)
1242                 *p++ = *strPtr++;
1243         }
1244         m_passwordEnd = p - buffer.data();
1245 
1246         // If we had any user info, add "@"
1247         if (p - buffer.data() != m_userStart)
1248             *p++ = '@';
1249 
1250         // copy in the host, except in the case of a file URL with authority="localhost"
1251         if (!(isFile && hostIsLocalHost && !haveNonHostAuthorityPart)) {
1252             strPtr = url + hostStart;
1253             const char* hostEndPtr = url + hostEnd;
1254             while (strPtr < hostEndPtr)
1255                 *p++ = *strPtr++;
1256         }
1257         m_hostEnd = p - buffer.data();
1258 
1259         // copy in the port
1260         if (hostEnd != portStart) {
1261             *p++ = ':';
1262             strPtr = url + portStart;
1263             const char *portEndPtr = url + portEnd;
1264             while (strPtr < portEndPtr)
1265                 *p++ = *strPtr++;
1266         }
1267         m_portEnd = p - buffer.data();
1268     } else
1269         m_userStart = m_userEnd = m_passwordEnd = m_hostEnd = m_portEnd = p - buffer.data();
1270 
1271     // For canonicalization, ensure we have a '/' for no path.
1272     // Only do this for http and https.
1273     if (m_protocolInHTTPFamily && pathEnd - pathStart == 0)
1274         *p++ = '/';
1275 
1276     // add path, escaping bad characters
1277     if (!hierarchical || !hasSlashDotOrDotDot(url))
1278         appendEscapingBadChars(p, url + pathStart, pathEnd - pathStart);
1279     else {
1280         CharBuffer pathBuffer(pathEnd - pathStart + 1);
1281         size_t length = copyPathRemovingDots(pathBuffer.data(), url, pathStart, pathEnd);
1282         appendEscapingBadChars(p, pathBuffer.data(), length);
1283     }
1284 
1285     m_pathEnd = p - buffer.data();
1286 
1287     // Find the position after the last slash in the path, or
1288     // the position before the path if there are no slashes in it.
1289     int i;
1290     for (i = m_pathEnd; i > m_portEnd; --i) {
1291         if (buffer[i - 1] == '/')
1292             break;
1293     }
1294     m_pathAfterLastSlash = i;
1295 
1296     // add query, escaping bad characters
1297     appendEscapingBadChars(p, url + queryStart, queryEnd - queryStart);
1298     m_queryEnd = p - buffer.data();
1299 
1300     // add fragment, escaping bad characters
1301     if (fragmentEnd != queryEnd) {
1302         *p++ = '#';
1303         appendEscapingBadChars(p, url + fragmentStart, fragmentEnd - fragmentStart);
1304     }
1305     m_fragmentEnd = p - buffer.data();
1306 
1307     ASSERT(p - buffer.data() <= static_cast<int>(buffer.size()));
1308 
1309     // If we didn't end up actually changing the original string and
1310     // it was already in a String, reuse it to avoid extra allocation.
1311     if (originalString && originalString->length() == static_cast<unsigned>(m_fragmentEnd) && strncmp(buffer.data(), url, m_fragmentEnd) == 0)
1312         m_string = *originalString;
1313     else
1314         m_string = String(buffer.data(), m_fragmentEnd);
1315 
1316     m_isValid = true;
1317 }
1318 
equalIgnoringFragmentIdentifier(const KURL & a,const KURL & b)1319 bool equalIgnoringFragmentIdentifier(const KURL& a, const KURL& b)
1320 {
1321     if (a.m_queryEnd != b.m_queryEnd)
1322         return false;
1323     unsigned queryLength = a.m_queryEnd;
1324     for (unsigned i = 0; i < queryLength; ++i)
1325         if (a.string()[i] != b.string()[i])
1326             return false;
1327     return true;
1328 }
1329 
protocolHostAndPortAreEqual(const KURL & a,const KURL & b)1330 bool protocolHostAndPortAreEqual(const KURL& a, const KURL& b)
1331 {
1332     if (a.m_schemeEnd != b.m_schemeEnd)
1333         return false;
1334     int hostStartA = a.hostStart();
1335     int hostStartB = b.hostStart();
1336     if (a.m_hostEnd - hostStartA != b.m_hostEnd - hostStartB)
1337         return false;
1338 
1339     // Check the scheme
1340     for (int i = 0; i < a.m_schemeEnd; ++i)
1341         if (a.string()[i] != b.string()[i])
1342             return false;
1343 
1344     // And the host
1345     for (int i = hostStartA; i < a.m_hostEnd; ++i)
1346         if (a.string()[i] != b.string()[i])
1347             return false;
1348 
1349     if (a.port() != b.port())
1350         return false;
1351 
1352     return true;
1353 }
1354 
1355 
encodeWithURLEscapeSequences(const String & notEncodedString)1356 String encodeWithURLEscapeSequences(const String& notEncodedString)
1357 {
1358     CString asUTF8 = notEncodedString.utf8();
1359 
1360     CharBuffer buffer(asUTF8.length() * 3 + 1);
1361     char* p = buffer.data();
1362 
1363     const char* str = asUTF8.data();
1364     const char* strEnd = str + asUTF8.length();
1365     while (str < strEnd) {
1366         unsigned char c = *str++;
1367         if (isBadChar(c)) {
1368             *p++ = '%';
1369             *p++ = hexDigits[c >> 4];
1370             *p++ = hexDigits[c & 0xF];
1371         } else
1372             *p++ = c;
1373     }
1374 
1375     ASSERT(p - buffer.data() <= static_cast<int>(buffer.size()));
1376 
1377     return String(buffer.data(), p - buffer.data());
1378 }
1379 
1380 // Appends the punycoded hostname identified by the given string and length to
1381 // the output buffer. The result will not be null terminated.
appendEncodedHostname(UCharBuffer & buffer,const UChar * str,unsigned strLen)1382 static void appendEncodedHostname(UCharBuffer& buffer, const UChar* str, unsigned strLen)
1383 {
1384     // Needs to be big enough to hold an IDN-encoded name.
1385     // For host names bigger than this, we won't do IDN encoding, which is almost certainly OK.
1386     const unsigned hostnameBufferLength = 2048;
1387 
1388     if (strLen > hostnameBufferLength || charactersAreAllASCII(str, strLen)) {
1389         buffer.append(str, strLen);
1390         return;
1391     }
1392 
1393 #if USE(ICU_UNICODE)
1394     UChar hostnameBuffer[hostnameBufferLength];
1395     UErrorCode error = U_ZERO_ERROR;
1396     int32_t numCharactersConverted = uidna_IDNToASCII(str, strLen, hostnameBuffer,
1397         hostnameBufferLength, UIDNA_ALLOW_UNASSIGNED, 0, &error);
1398     if (error == U_ZERO_ERROR)
1399         buffer.append(hostnameBuffer, numCharactersConverted);
1400 #elif USE(QT4_UNICODE)
1401     QByteArray result = QUrl::toAce(String(str, strLen));
1402     buffer.append(result.constData(), result.length());
1403 #endif
1404 }
1405 
findHostnamesInMailToURL(const UChar * str,int strLen,Vector<pair<int,int>> & nameRanges)1406 static void findHostnamesInMailToURL(const UChar* str, int strLen, Vector<pair<int, int> >& nameRanges)
1407 {
1408     // In a mailto: URL, host names come after a '@' character and end with a '>' or ',' or '?' or end of string character.
1409     // Skip quoted strings so that characters in them don't confuse us.
1410     // When we find a '?' character, we are past the part of the URL that contains host names.
1411 
1412     nameRanges.clear();
1413 
1414     int p = 0;
1415     while (1) {
1416         // Find start of host name or of quoted string.
1417         int hostnameOrStringStart = findFirstOf(str, strLen, p, "\"@?");
1418         if (hostnameOrStringStart == -1)
1419             return;
1420         UChar c = str[hostnameOrStringStart];
1421         p = hostnameOrStringStart + 1;
1422 
1423         if (c == '?')
1424             return;
1425 
1426         if (c == '@') {
1427             // Find end of host name.
1428             int hostnameStart = p;
1429             int hostnameEnd = findFirstOf(str, strLen, p, ">,?");
1430             bool done;
1431             if (hostnameEnd == -1) {
1432                 hostnameEnd = strLen;
1433                 done = true;
1434             } else {
1435                 p = hostnameEnd;
1436                 done = false;
1437             }
1438 
1439             nameRanges.append(make_pair(hostnameStart, hostnameEnd));
1440 
1441             if (done)
1442                 return;
1443         } else {
1444             // Skip quoted string.
1445             ASSERT(c == '"');
1446             while (1) {
1447                 int escapedCharacterOrStringEnd = findFirstOf(str, strLen, p, "\"\\");
1448                 if (escapedCharacterOrStringEnd == -1)
1449                     return;
1450 
1451                 c = str[escapedCharacterOrStringEnd];
1452                 p = escapedCharacterOrStringEnd + 1;
1453 
1454                 // If we are the end of the string, then break from the string loop back to the host name loop.
1455                 if (c == '"')
1456                     break;
1457 
1458                 // Skip escaped character.
1459                 ASSERT(c == '\\');
1460                 if (p == strLen)
1461                     return;
1462 
1463                 ++p;
1464             }
1465         }
1466     }
1467 }
1468 
findHostnameInHierarchicalURL(const UChar * str,int strLen,int & startOffset,int & endOffset)1469 static bool findHostnameInHierarchicalURL(const UChar* str, int strLen, int& startOffset, int& endOffset)
1470 {
1471     // Find the host name in a hierarchical URL.
1472     // It comes after a "://" sequence, with scheme characters preceding, and
1473     // this should be the first colon in the string.
1474     // It ends with the end of the string or a ":" or a path segment ending character.
1475     // If there is a "@" character, the host part is just the part after the "@".
1476     int separator = findFirstOf(str, strLen, 0, ":");
1477     if (separator == -1 || separator + 2 >= strLen ||
1478         str[separator + 1] != '/' || str[separator + 2] != '/')
1479         return false;
1480 
1481     // Check that all characters before the :// are valid scheme characters.
1482     if (!isSchemeFirstChar(str[0]))
1483         return false;
1484     for (int i = 1; i < separator; ++i) {
1485         if (!isSchemeChar(str[i]))
1486             return false;
1487     }
1488 
1489     // Start after the separator.
1490     int authorityStart = separator + 3;
1491 
1492     // Find terminating character.
1493     int hostnameEnd = strLen;
1494     for (int i = authorityStart; i < strLen; ++i) {
1495         UChar c = str[i];
1496         if (c == ':' || (isPathSegmentEndChar(c) && c != 0)) {
1497             hostnameEnd = i;
1498             break;
1499         }
1500     }
1501 
1502     // Find "@" for the start of the host name.
1503     int userInfoTerminator = findFirstOf(str, strLen, authorityStart, "@");
1504     int hostnameStart;
1505     if (userInfoTerminator == -1 || userInfoTerminator > hostnameEnd)
1506         hostnameStart = authorityStart;
1507     else
1508         hostnameStart = userInfoTerminator + 1;
1509 
1510     startOffset = hostnameStart;
1511     endOffset = hostnameEnd;
1512     return true;
1513 }
1514 
1515 // Converts all hostnames found in the given input to punycode, preserving the
1516 // rest of the URL unchanged. The output will NOT be null-terminated.
encodeHostnames(const String & str,UCharBuffer & output)1517 static void encodeHostnames(const String& str, UCharBuffer& output)
1518 {
1519     output.clear();
1520 
1521     if (protocolIs(str, "mailto")) {
1522         Vector<pair<int, int> > hostnameRanges;
1523         findHostnamesInMailToURL(str.characters(), str.length(), hostnameRanges);
1524         int n = hostnameRanges.size();
1525         int p = 0;
1526         for (int i = 0; i < n; ++i) {
1527             const pair<int, int>& r = hostnameRanges[i];
1528             output.append(&str.characters()[p], r.first - p);
1529             appendEncodedHostname(output, &str.characters()[r.first], r.second - r.first);
1530             p = r.second;
1531         }
1532         // This will copy either everything after the last hostname, or the
1533         // whole thing if there is no hostname.
1534         output.append(&str.characters()[p], str.length() - p);
1535     } else {
1536         int hostStart, hostEnd;
1537         if (findHostnameInHierarchicalURL(str.characters(), str.length(), hostStart, hostEnd)) {
1538             output.append(str.characters(), hostStart); // Before hostname.
1539             appendEncodedHostname(output, &str.characters()[hostStart], hostEnd - hostStart);
1540             output.append(&str.characters()[hostEnd], str.length() - hostEnd); // After hostname.
1541         } else {
1542             // No hostname to encode, return the input.
1543             output.append(str.characters(), str.length());
1544         }
1545     }
1546 }
1547 
encodeRelativeString(const String & rel,const TextEncoding & encoding,CharBuffer & output)1548 static void encodeRelativeString(const String& rel, const TextEncoding& encoding, CharBuffer& output)
1549 {
1550     UCharBuffer s;
1551     encodeHostnames(rel, s);
1552 
1553     TextEncoding pathEncoding(UTF8Encoding()); // Path is always encoded as UTF-8; other parts may depend on the scheme.
1554 
1555     int pathEnd = -1;
1556     if (encoding != pathEncoding && encoding.isValid() && !protocolIs(rel, "mailto") && !protocolIs(rel, "data") && !protocolIsJavaScript(rel)) {
1557         // Find the first instance of either # or ?, keep pathEnd at -1 otherwise.
1558         pathEnd = findFirstOf(s.data(), s.size(), 0, "#?");
1559     }
1560 
1561     if (pathEnd == -1) {
1562         CString decoded = pathEncoding.encode(s.data(), s.size(), URLEncodedEntitiesForUnencodables);
1563         output.resize(decoded.length());
1564         memcpy(output.data(), decoded.data(), decoded.length());
1565     } else {
1566         CString pathDecoded = pathEncoding.encode(s.data(), pathEnd, URLEncodedEntitiesForUnencodables);
1567         // Unencodable characters in URLs are represented by converting
1568         // them to XML entities and escaping non-alphanumeric characters.
1569         CString otherDecoded = encoding.encode(s.data() + pathEnd, s.size() - pathEnd, URLEncodedEntitiesForUnencodables);
1570 
1571         output.resize(pathDecoded.length() + otherDecoded.length());
1572         memcpy(output.data(), pathDecoded.data(), pathDecoded.length());
1573         memcpy(output.data() + pathDecoded.length(), otherDecoded.data(), otherDecoded.length());
1574     }
1575     output.append('\0'); // null-terminate the output.
1576 }
1577 
substituteBackslashes(const String & string)1578 static String substituteBackslashes(const String& string)
1579 {
1580     int questionPos = string.find('?');
1581     int hashPos = string.find('#');
1582     int pathEnd;
1583 
1584     if (hashPos >= 0 && (questionPos < 0 || questionPos > hashPos))
1585         pathEnd = hashPos;
1586     else if (questionPos >= 0)
1587         pathEnd = questionPos;
1588     else
1589         pathEnd = string.length();
1590 
1591     return string.left(pathEnd).replace('\\','/') + string.substring(pathEnd);
1592 }
1593 
isHierarchical() const1594 bool KURL::isHierarchical() const
1595 {
1596     if (!m_isValid)
1597         return false;
1598     ASSERT(m_string[m_schemeEnd] == ':');
1599     return m_string[m_schemeEnd + 1] == '/';
1600 }
1601 
copyToBuffer(CharBuffer & buffer) const1602 void KURL::copyToBuffer(CharBuffer& buffer) const
1603 {
1604     // FIXME: This throws away the high bytes of all the characters in the string!
1605     // That's fine for a valid URL, which is all ASCII, but not for invalid URLs.
1606     buffer.resize(m_string.length());
1607     copyASCII(m_string.characters(), m_string.length(), buffer.data());
1608 }
1609 
protocolIs(const String & url,const char * protocol)1610 bool protocolIs(const String& url, const char* protocol)
1611 {
1612     // Do the comparison without making a new string object.
1613     assertProtocolIsGood(protocol);
1614     for (int i = 0; ; ++i) {
1615         if (!protocol[i])
1616             return url[i] == ':';
1617         if (toASCIILower(url[i]) != protocol[i])
1618             return false;
1619     }
1620 }
1621 
protocolIsJavaScript(const String & url)1622 bool protocolIsJavaScript(const String& url)
1623 {
1624     return protocolIs(url, "javascript");
1625 }
1626 
mimeTypeFromDataURL(const String & url)1627 String mimeTypeFromDataURL(const String& url)
1628 {
1629     ASSERT(protocolIs(url, "data"));
1630     int index = url.find(';');
1631     if (index == -1)
1632         index = url.find(',');
1633     if (index != -1) {
1634         int len = index - 5;
1635         if (len > 0)
1636             return url.substring(5, len);
1637         return "text/plain"; // Data URLs with no MIME type are considered text/plain.
1638     }
1639     return "";
1640 }
1641 
blankURL()1642 const KURL& blankURL()
1643 {
1644     DEFINE_STATIC_LOCAL(KURL, staticBlankURL, ("about:blank"));
1645     return staticBlankURL;
1646 }
1647 
1648 #ifndef NDEBUG
print() const1649 void KURL::print() const
1650 {
1651     printf("%s\n", m_string.utf8().data());
1652 }
1653 #endif
1654 
1655 }
1656 
1657 #endif  // !USE(GOOGLEURL)
1658