OSDN Git Service

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