2 * Copyright (C) 2005, 2007, 2008 Apple Inc. All rights reserved.
3 * Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com)
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15 * its contributors may be used to endorse or promote products derived
16 * from this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 #import "WebNSURLExtras.h"
32 #import "WebKitNSStringExtras.h"
33 #import "WebLocalizableStrings.h"
34 #import "WebNSDataExtras.h"
35 #import "WebNSObjectExtras.h"
36 #import "WebSystemInterface.h"
37 #import <Foundation/NSURLRequest.h>
38 #import <JavaScriptCore/Assertions.h>
39 #import <WebCore/KURL.h>
40 #import <WebCore/LoaderNSURLExtras.h>
41 #import <WebKitSystemInterface.h>
42 #import <unicode/uchar.h>
43 #import <unicode/uidna.h>
44 #import <unicode/uscript.h>
46 using namespace WebCore;
49 typedef void (* StringRangeApplierFunction)(NSString *string, NSRange range, void *context);
51 // Needs to be big enough to hold an IDN-encoded name.
52 // For host names bigger than this, we won't do IDN encoding, which is almost certainly OK.
53 #define HOST_NAME_BUFFER_LENGTH 2048
55 #define URL_BYTES_BUFFER_LENGTH 2048
57 static pthread_once_t IDNScriptWhiteListFileRead = PTHREAD_ONCE_INIT;
58 static uint32_t IDNScriptWhiteList[(USCRIPT_CODE_LIMIT + 31) / 32];
60 static inline BOOL isLookalikeCharacter(int charCode)
62 // FIXME: Move this code down into WebCore so it can be shared with other platforms.
64 // This function treats the following as unsafe, lookalike characters:
65 // any non-printable character, any character considered as whitespace that isn't already converted to a space by ICU,
66 // and any ignorable character.
68 // We also considered the characters in Mozilla's blacklist (http://kb.mozillazine.org/Network.IDN.blacklist_chars),
69 // and included all of these characters that ICU can encode.
71 if (!u_isprint(charCode) || u_isUWhiteSpace(charCode) || u_hasBinaryProperty(charCode, UCHAR_DEFAULT_IGNORABLE_CODE_POINT))
75 case 0x01C3: /* LATIN LETTER RETROFLEX CLICK */
76 case 0x0337: /* COMBINING SHORT SOLIDUS OVERLAY */
77 case 0x0338: /* COMBINING LONG SOLIDUS OVERLAY */
78 case 0x05B4: /* HEBREW POINT HIRIQ */
79 case 0x05BC: /* HEBREW POINT DAGESH OR MAPIQ */
80 case 0x05C3: /* HEBREW PUNCTUATION SOF PASUQ */
81 case 0x05F4: /* HEBREW PUNCTUATION GERSHAYIM */
82 case 0x0660: /* ARABIC INDIC DIGIT ZERO */
83 case 0x06D4: /* ARABIC FULL STOP */
84 case 0x06F0: /* EXTENDED ARABIC INDIC DIGIT ZERO */
85 case 0x2027: /* HYPHENATION POINT */
86 case 0x2039: /* SINGLE LEFT-POINTING ANGLE QUOTATION MARK */
87 case 0x203A: /* SINGLE RIGHT-POINTING ANGLE QUOTATION MARK */
88 case 0x2044: /* FRACTION SLASH */
89 case 0x2215: /* DIVISION SLASH */
90 case 0x23ae: /* INTEGRAL EXTENSION */
91 case 0x2571: /* BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT */
92 case 0x29F8: /* BIG SOLIDUS */
93 case 0x29f6: /* SOLIDUS WITH OVERBAR */
94 case 0x2AFB: /* TRIPLE SOLIDUS BINARY RELATION */
95 case 0x2AFD: /* DOUBLE SOLIDUS OPERATOR */
96 case 0x3008: /* LEFT ANGLE BRACKET */
97 case 0x3014: /* LEFT TORTOISE SHELL BRACKET */
98 case 0x3015: /* RIGHT TORTOISE SHELL BRACKET */
99 case 0x3033: /* VERTICAL KANA REPEAT MARK UPPER HALF */
100 case 0x321D: /* PARENTHESIZED KOREAN CHARACTER OJEON */
101 case 0x321E: /* PARENTHESIZED KOREAN CHARACTER O HU */
102 case 0x33DF: /* SQUARE A OVER M */
103 case 0xFE14: /* PRESENTATION FORM FOR VERTICAL SEMICOLON */
104 case 0xFE15: /* PRESENTATION FORM FOR VERTICAL EXCLAMATION MARK */
105 case 0xFE3F: /* PRESENTATION FORM FOR VERTICAL LEFT ANGLE BRACKET */
106 case 0xFE5D: /* SMALL LEFT TORTOISE SHELL BRACKET */
107 case 0xFE5E: /* SMALL RIGHT TORTOISE SHELL BRACKET */
114 static char hexDigit(int i)
116 if (i < 0 || i > 16) {
117 LOG_ERROR("illegal hex digit");
130 static BOOL isHexDigit(char c)
132 return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f');
135 static int hexDigitValue(char c)
137 if (c >= '0' && c <= '9') {
140 if (c >= 'A' && c <= 'F') {
143 if (c >= 'a' && c <= 'f') {
146 LOG_ERROR("illegal hex digit");
150 static void applyHostNameFunctionToMailToURLString(NSString *string, StringRangeApplierFunction f, void *context)
152 // In a mailto: URL, host names come after a '@' character and end with a '>' or ',' or '?' character.
153 // Skip quoted strings so that characters in them don't confuse us.
154 // When we find a '?' character, we are past the part of the URL that contains host names.
156 static NSCharacterSet *hostNameOrStringStartCharacters;
157 if (hostNameOrStringStartCharacters == nil) {
158 hostNameOrStringStartCharacters = [NSCharacterSet characterSetWithCharactersInString:@"\"@?"];
159 CFRetain(hostNameOrStringStartCharacters);
161 static NSCharacterSet *hostNameEndCharacters;
162 if (hostNameEndCharacters == nil) {
163 hostNameEndCharacters = [NSCharacterSet characterSetWithCharactersInString:@">,?"];
164 CFRetain(hostNameEndCharacters);
166 static NSCharacterSet *quotedStringCharacters;
167 if (quotedStringCharacters == nil) {
168 quotedStringCharacters = [NSCharacterSet characterSetWithCharactersInString:@"\"\\"];
169 CFRetain(quotedStringCharacters);
172 unsigned stringLength = [string length];
173 NSRange remaining = NSMakeRange(0, stringLength);
176 // Find start of host name or of quoted string.
177 NSRange hostNameOrStringStart = [string rangeOfCharacterFromSet:hostNameOrStringStartCharacters options:0 range:remaining];
178 if (hostNameOrStringStart.location == NSNotFound) {
181 unichar c = [string characterAtIndex:hostNameOrStringStart.location];
182 remaining.location = NSMaxRange(hostNameOrStringStart);
183 remaining.length = stringLength - remaining.location;
190 // Find end of host name.
191 unsigned hostNameStart = remaining.location;
192 NSRange hostNameEnd = [string rangeOfCharacterFromSet:hostNameEndCharacters options:0 range:remaining];
194 if (hostNameEnd.location == NSNotFound) {
195 hostNameEnd.location = stringLength;
198 remaining.location = hostNameEnd.location;
199 remaining.length = stringLength - remaining.location;
203 // Process host name range.
204 f(string, NSMakeRange(hostNameStart, hostNameEnd.location - hostNameStart), context);
210 // Skip quoted string.
213 NSRange escapedCharacterOrStringEnd = [string rangeOfCharacterFromSet:quotedStringCharacters options:0 range:remaining];
214 if (escapedCharacterOrStringEnd.location == NSNotFound) {
217 c = [string characterAtIndex:escapedCharacterOrStringEnd.location];
218 remaining.location = NSMaxRange(escapedCharacterOrStringEnd);
219 remaining.length = stringLength - remaining.location;
221 // If we are the end of the string, then break from the string loop back to the host name loop.
226 // Skip escaped character.
228 if (remaining.length == 0) {
231 remaining.location += 1;
232 remaining.length -= 1;
238 static void applyHostNameFunctionToURLString(NSString *string, StringRangeApplierFunction f, void *context)
240 // Find hostnames. Too bad we can't use any real URL-parsing code to do this,
241 // but we have to do it before doing all the %-escaping, and this is the only
242 // code we have that parses mailto URLs anyway.
244 // Maybe we should implement this using a character buffer instead?
246 if ([string _webkit_hasCaseInsensitivePrefix:@"mailto:"]) {
247 applyHostNameFunctionToMailToURLString(string, f, context);
251 // Find the host name in a hierarchical URL.
252 // It comes after a "://" sequence, with scheme characters preceding.
253 // If ends with the end of the string or a ":", "/", or a "?".
254 // If there is a "@" character, the host part is just the part after the "@".
255 NSRange separatorRange = [string rangeOfString:@"://"];
256 if (separatorRange.location == NSNotFound) {
260 // Check that all characters before the :// are valid scheme characters.
261 static NSCharacterSet *nonSchemeCharacters;
262 if (nonSchemeCharacters == nil) {
263 nonSchemeCharacters = [[NSCharacterSet characterSetWithCharactersInString:@"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-."] invertedSet];
264 CFRetain(nonSchemeCharacters);
266 if ([string rangeOfCharacterFromSet:nonSchemeCharacters options:0 range:NSMakeRange(0, separatorRange.location)].location != NSNotFound) {
270 unsigned stringLength = [string length];
272 static NSCharacterSet *hostTerminators;
273 if (hostTerminators == nil) {
274 hostTerminators = [NSCharacterSet characterSetWithCharactersInString:@":/?#"];
275 CFRetain(hostTerminators);
278 // Start after the separator.
279 unsigned authorityStart = NSMaxRange(separatorRange);
281 // Find terminating character.
282 NSRange hostNameTerminator = [string rangeOfCharacterFromSet:hostTerminators options:0 range:NSMakeRange(authorityStart, stringLength - authorityStart)];
283 unsigned hostNameEnd = hostNameTerminator.location == NSNotFound ? stringLength : hostNameTerminator.location;
285 // Find "@" for the start of the host name.
286 NSRange userInfoTerminator = [string rangeOfString:@"@" options:0 range:NSMakeRange(authorityStart, hostNameEnd - authorityStart)];
287 unsigned hostNameStart = userInfoTerminator.location == NSNotFound ? authorityStart : NSMaxRange(userInfoTerminator);
289 f(string, NSMakeRange(hostNameStart, hostNameEnd - hostNameStart), context);
292 @implementation NSURL (WebNSURLExtras)
294 static void collectRangesThatNeedMapping(NSString *string, NSRange range, void *context, BOOL encode)
296 BOOL needsMapping = encode
297 ? [string _web_hostNameNeedsEncodingWithRange:range]
298 : [string _web_hostNameNeedsDecodingWithRange:range];
303 NSMutableArray **array = (NSMutableArray **)context;
305 *array = [[NSMutableArray alloc] init];
308 [*array addObject:[NSValue valueWithRange:range]];
311 static void collectRangesThatNeedEncoding(NSString *string, NSRange range, void *context)
313 return collectRangesThatNeedMapping(string, range, context, YES);
316 static void collectRangesThatNeedDecoding(NSString *string, NSRange range, void *context)
318 return collectRangesThatNeedMapping(string, range, context, NO);
321 static NSString *mapHostNames(NSString *string, BOOL encode)
323 // Generally, we want to optimize for the case where there is one host name that does not need mapping.
325 if (encode && [string canBeConvertedToEncoding:NSASCIIStringEncoding])
328 // Make a list of ranges that actually need mapping.
329 NSMutableArray *hostNameRanges = nil;
330 StringRangeApplierFunction f = encode
331 ? collectRangesThatNeedEncoding
332 : collectRangesThatNeedDecoding;
333 applyHostNameFunctionToURLString(string, f, &hostNameRanges);
334 if (hostNameRanges == nil)
338 NSMutableString *mutableCopy = [string mutableCopy];
339 unsigned i = [hostNameRanges count];
341 NSRange hostNameRange = [[hostNameRanges objectAtIndex:i] rangeValue];
342 NSString *mappedHostName = encode
343 ? [string _web_encodeHostNameWithRange:hostNameRange]
344 : [string _web_decodeHostNameWithRange:hostNameRange];
345 [mutableCopy replaceCharactersInRange:hostNameRange withString:mappedHostName];
347 [hostNameRanges release];
348 return [mutableCopy autorelease];
351 + (NSURL *)_web_URLWithUserTypedString:(NSString *)string relativeToURL:(NSURL *)URL
356 string = mapHostNames([string _webkit_stringByTrimmingWhitespace], YES);
358 NSData *userTypedData = [string dataUsingEncoding:NSUTF8StringEncoding];
359 ASSERT(userTypedData);
361 const UInt8 *inBytes = static_cast<const UInt8 *>([userTypedData bytes]);
362 int inLength = [userTypedData length];
364 return [NSURL URLWithString:@""];
367 char *outBytes = static_cast<char *>(malloc(inLength * 3)); // large enough to %-escape every character
371 for (i = 0; i < inLength; i++) {
372 UInt8 c = inBytes[i];
373 if (c <= 0x20 || c >= 0x7f) {
375 *p++ = hexDigit(c >> 4);
376 *p++ = hexDigit(c & 0xf);
385 NSData *data = [NSData dataWithBytesNoCopy:outBytes length:outLength]; // adopts outBytes
386 return [self _web_URLWithData:data relativeToURL:URL];
389 + (NSURL *)_web_URLWithUserTypedString:(NSString *)string
391 return [self _web_URLWithUserTypedString:string relativeToURL:nil];
394 + (NSURL *)_web_URLWithDataAsString:(NSString *)string
399 return [self _web_URLWithDataAsString:string relativeToURL:nil];
402 + (NSURL *)_web_URLWithDataAsString:(NSString *)string relativeToURL:(NSURL *)baseURL
407 string = [string _webkit_stringByTrimmingWhitespace];
408 NSData *data = [string dataUsingEncoding:NSISOLatin1StringEncoding];
409 return [self _web_URLWithData:data relativeToURL:baseURL];
412 + (NSURL *)_web_URLWithData:(NSData *)data
414 return [NSURL _web_URLWithData:data relativeToURL:nil];
417 + (NSURL *)_web_URLWithData:(NSData *)data relativeToURL:(NSURL *)baseURL
423 size_t length = [data length];
425 // work around <rdar://4470771>: CFURLCreateAbsoluteURLWithBytes(.., TRUE) doesn't remove non-path components.
426 baseURL = [baseURL _webkit_URLByRemovingResourceSpecifier];
428 const UInt8 *bytes = static_cast<const UInt8*>([data bytes]);
429 // NOTE: We use UTF-8 here since this encoding is used when computing strings when returning URL components
430 // (e.g calls to NSURL -path). However, this function is not tolerant of illegal UTF-8 sequences, which
431 // could either be a malformed string or bytes in a different encoding, like shift-jis, so we fall back
432 // onto using ISO Latin 1 in those cases.
433 result = WebCFAutorelease(CFURLCreateAbsoluteURLWithBytes(NULL, bytes, length, kCFStringEncodingUTF8, (CFURLRef)baseURL, YES));
435 result = WebCFAutorelease(CFURLCreateAbsoluteURLWithBytes(NULL, bytes, length, kCFStringEncodingISOLatin1, (CFURLRef)baseURL, YES));
437 result = [NSURL URLWithString:@""];
442 - (NSData *)_web_originalData
444 UInt8 *buffer = (UInt8 *)malloc(URL_BYTES_BUFFER_LENGTH);
445 CFIndex bytesFilled = CFURLGetBytes((CFURLRef)self, buffer, URL_BYTES_BUFFER_LENGTH);
446 if (bytesFilled == -1) {
447 CFIndex bytesToAllocate = CFURLGetBytes((CFURLRef)self, NULL, 0);
448 buffer = (UInt8 *)realloc(buffer, bytesToAllocate);
449 bytesFilled = CFURLGetBytes((CFURLRef)self, buffer, bytesToAllocate);
450 ASSERT(bytesFilled == bytesToAllocate);
453 // buffer is adopted by the NSData
454 NSData *data = [NSData dataWithBytesNoCopy:buffer length:bytesFilled freeWhenDone:YES];
456 NSURL *baseURL = (NSURL *)CFURLGetBaseURL((CFURLRef)self);
458 return [[NSURL _web_URLWithData:data relativeToURL:baseURL] _web_originalData];
462 - (NSString *)_web_originalDataAsString
464 return [[[NSString alloc] initWithData:[self _web_originalData] encoding:NSISOLatin1StringEncoding] autorelease];
467 - (NSString *)_web_userVisibleString
469 NSData *data = [self _web_originalData];
470 const unsigned char *before = static_cast<const unsigned char*>([data bytes]);
471 int length = [data length];
473 bool needsHostNameDecoding = false;
475 const unsigned char *p = before;
476 int bufferLength = (length * 3) + 1;
477 char *after = static_cast<char *>(malloc(bufferLength)); // large enough to %-escape every character
480 for (i = 0; i < length; i++) {
481 unsigned char c = p[i];
482 // escape control characters, space, and delete
483 if (c <= 0x20 || c == 0x7f) {
485 *q++ = hexDigit(c >> 4);
486 *q++ = hexDigit(c & 0xf);
488 // unescape escape sequences that indicate bytes greater than 0x7f
489 else if (c == '%' && (i + 1 < length && isHexDigit(p[i + 1])) && i + 2 < length && isHexDigit(p[i + 2])) {
490 unsigned char u = (hexDigitValue(p[i + 1]) << 4) | hexDigitValue(p[i + 2]);
506 // Check for "xn--" in an efficient, non-case-sensitive, way.
507 if (c == '-' && i >= 3 && !needsHostNameDecoding && (q[-4] | 0x20) == 'x' && (q[-3] | 0x20) == 'n' && q[-2] == '-')
508 needsHostNameDecoding = true;
513 // Check string to see if it can be converted to display using UTF-8
514 NSString *result = [NSString stringWithUTF8String:after];
516 // Could not convert to UTF-8.
517 // Convert characters greater than 0x7f to escape sequences.
518 // Shift current string to the end of the buffer
519 // then we will copy back bytes to the start of the buffer
521 int afterlength = q - after;
522 char *p = after + bufferLength - afterlength - 1;
523 memmove(p, after, afterlength + 1); // copies trailing '\0'
526 unsigned char c = *p;
529 *q++ = hexDigit(c >> 4);
530 *q++ = hexDigit(c & 0xf);
538 result = [NSString stringWithUTF8String:after];
543 // As an optimization, only do host name decoding if we have "xn--" somewhere.
544 return needsHostNameDecoding ? mapHostNames(result, NO) : result;
549 if (!CFURLGetBaseURL((CFURLRef)self))
550 return CFURLGetBytes((CFURLRef)self, NULL, 0) == 0;
551 return [[self _web_originalData] length] == 0;
554 - (const char *)_web_URLCString
556 NSMutableData *data = [NSMutableData data];
557 [data appendData:[self _web_originalData]];
558 [data appendBytes:"\0" length:1];
559 return (const char *)[data bytes];
562 - (NSURL *)_webkit_canonicalize
564 NSURLRequest *request = [[NSURLRequest alloc] initWithURL:self];
565 Class concreteClass = WKNSURLProtocolClassForReqest(request);
566 if (!concreteClass) {
571 // This applies NSURL's concept of canonicalization, but not KURL's concept. It would
572 // make sense to apply both, but when we tried that it caused a performance degradation
573 // (see 5315926). It might make sense to apply only the KURL concept and not the NSURL
574 // concept, but it's too risky to make that change for WebKit 3.0.
575 NSURLRequest *newRequest = [concreteClass canonicalRequestForRequest:request];
576 NSURL *newURL = [newRequest URL];
577 NSURL *result = [[newURL retain] autorelease];
588 CFIndex port; // kCFNotFound means ignore/omit
592 } WebKitURLComponents;
594 - (NSURL *)_webkit_URLByRemovingComponent:(CFURLComponentType)component
596 CFRange fragRg = CFURLGetByteRangeForComponent((CFURLRef)self, component, NULL);
597 // Check to see if a fragment exists before decomposing the URL.
598 if (fragRg.location == kCFNotFound)
601 UInt8 *urlBytes, buffer[2048];
602 CFIndex numBytes = CFURLGetBytes((CFURLRef)self, buffer, 2048);
603 if (numBytes == -1) {
604 numBytes = CFURLGetBytes((CFURLRef)self, NULL, 0);
605 urlBytes = static_cast<UInt8*>(malloc(numBytes));
606 CFURLGetBytes((CFURLRef)self, urlBytes, numBytes);
610 NSURL *result = (NSURL *)CFMakeCollectable(CFURLCreateWithBytes(NULL, urlBytes, fragRg.location - 1, kCFStringEncodingUTF8, NULL));
612 result = (NSURL *)CFMakeCollectable(CFURLCreateWithBytes(NULL, urlBytes, fragRg.location - 1, kCFStringEncodingISOLatin1, NULL));
614 if (urlBytes != buffer) free(urlBytes);
615 return result ? [result autorelease] : self;
618 - (NSURL *)_webkit_URLByRemovingFragment
620 return [self _webkit_URLByRemovingComponent:kCFURLComponentFragment];
623 - (NSURL *)_webkit_URLByRemovingResourceSpecifier
625 return [self _webkit_URLByRemovingComponent:kCFURLComponentResourceSpecifier];
628 - (BOOL)_webkit_isJavaScriptURL
630 return [[self _web_originalDataAsString] _webkit_isJavaScriptURL];
633 - (NSString *)_webkit_scriptIfJavaScriptURL
635 return [[self absoluteString] _webkit_scriptIfJavaScriptURL];
638 - (BOOL)_webkit_isFileURL
640 return [[self _web_originalDataAsString] _webkit_isFileURL];
643 - (BOOL)_webkit_isFTPDirectoryURL
645 return [[self _web_originalDataAsString] _webkit_isFTPDirectoryURL];
648 - (BOOL)_webkit_shouldLoadAsEmptyDocument
650 return [[self _web_originalDataAsString] _webkit_hasCaseInsensitivePrefix:@"about:"] || [self _web_isEmpty];
653 - (NSURL *)_web_URLWithLowercasedScheme
656 CFURLGetByteRangeForComponent((CFURLRef)self, kCFURLComponentScheme, &range);
657 if (range.location == kCFNotFound) {
661 UInt8 static_buffer[URL_BYTES_BUFFER_LENGTH];
662 UInt8 *buffer = static_buffer;
663 CFIndex bytesFilled = CFURLGetBytes((CFURLRef)self, buffer, URL_BYTES_BUFFER_LENGTH);
664 if (bytesFilled == -1) {
665 CFIndex bytesToAllocate = CFURLGetBytes((CFURLRef)self, NULL, 0);
666 buffer = static_cast<UInt8 *>(malloc(bytesToAllocate));
667 bytesFilled = CFURLGetBytes((CFURLRef)self, buffer, bytesToAllocate);
668 ASSERT(bytesFilled == bytesToAllocate);
673 for (i = 0; i < range.length; ++i) {
674 char c = buffer[range.location + i];
675 char lower = toASCIILower(c);
677 buffer[range.location + i] = lower;
682 NSURL *result = changed
683 ? (NSURL *)WebCFAutorelease(CFURLCreateAbsoluteURLWithBytes(NULL, buffer, bytesFilled, kCFStringEncodingUTF8, nil, YES))
686 if (buffer != static_buffer) {
694 -(BOOL)_web_hasQuestionMarkOnlyQueryString
696 CFRange rangeWithSeparators;
697 CFURLGetByteRangeForComponent((CFURLRef)self, kCFURLComponentQuery, &rangeWithSeparators);
698 if (rangeWithSeparators.location != kCFNotFound && rangeWithSeparators.length == 1) {
704 -(NSData *)_web_schemeSeparatorWithoutColon
706 NSData *result = nil;
707 CFRange rangeWithSeparators;
708 CFRange range = CFURLGetByteRangeForComponent((CFURLRef)self, kCFURLComponentScheme, &rangeWithSeparators);
709 if (rangeWithSeparators.location != kCFNotFound) {
710 NSString *absoluteString = [self absoluteString];
711 NSRange separatorsRange = NSMakeRange(range.location + range.length + 1, rangeWithSeparators.length - range.length - 1);
712 if (separatorsRange.location + separatorsRange.length <= [absoluteString length]) {
713 NSString *slashes = [absoluteString substringWithRange:separatorsRange];
714 result = [slashes dataUsingEncoding:NSISOLatin1StringEncoding];
720 #define completeURL (CFURLComponentType)-1
722 -(NSData *)_web_dataForURLComponentType:(CFURLComponentType)componentType
724 static int URLComponentTypeBufferLength = 2048;
726 UInt8 staticAllBytesBuffer[URLComponentTypeBufferLength];
727 UInt8 *allBytesBuffer = staticAllBytesBuffer;
729 CFIndex bytesFilled = CFURLGetBytes((CFURLRef)self, allBytesBuffer, URLComponentTypeBufferLength);
730 if (bytesFilled == -1) {
731 CFIndex bytesToAllocate = CFURLGetBytes((CFURLRef)self, NULL, 0);
732 allBytesBuffer = static_cast<UInt8 *>(malloc(bytesToAllocate));
733 bytesFilled = CFURLGetBytes((CFURLRef)self, allBytesBuffer, bytesToAllocate);
737 if (componentType != completeURL) {
738 range = CFURLGetByteRangeForComponent((CFURLRef)self, componentType, NULL);
739 if (range.location == kCFNotFound) {
745 range.length = bytesFilled;
748 NSData *componentData = [NSData dataWithBytes:allBytesBuffer + range.location length:range.length];
750 const unsigned char *bytes = static_cast<const unsigned char *>([componentData bytes]);
751 NSMutableData *resultData = [NSMutableData data];
752 // NOTE: add leading '?' to query strings non-zero length query strings.
753 // NOTE: retain question-mark only query strings.
754 if (componentType == kCFURLComponentQuery) {
755 if (range.length > 0 || [self _web_hasQuestionMarkOnlyQueryString]) {
756 [resultData appendBytes:"?" length:1];
760 for (i = 0; i < range.length; i++) {
761 unsigned char c = bytes[i];
762 if (c <= 0x20 || c >= 0x7f) {
765 escaped[1] = hexDigit(c >> 4);
766 escaped[2] = hexDigit(c & 0xf);
767 [resultData appendBytes:escaped length:3];
772 [resultData appendBytes:b length:1];
776 if (staticAllBytesBuffer != allBytesBuffer) {
777 free(allBytesBuffer);
783 -(NSData *)_web_schemeData
785 return [self _web_dataForURLComponentType:kCFURLComponentScheme];
788 -(NSData *)_web_hostData
790 NSData *result = [self _web_dataForURLComponentType:kCFURLComponentHost];
791 NSData *scheme = [self _web_schemeData];
792 // Take off localhost for file
793 if ([scheme _web_isCaseInsensitiveEqualToCString:"file"]) {
794 return ([result _web_isCaseInsensitiveEqualToCString:"localhost"]) ? nil : result;
799 - (NSString *)_web_hostString
801 NSData *data = [self _web_hostData];
803 data = [NSData data];
805 return [[[NSString alloc] initWithData:[self _web_hostData] encoding:NSUTF8StringEncoding] autorelease];
808 - (NSString *)_webkit_suggestedFilenameWithMIMEType:(NSString *)MIMEType
810 return suggestedFilenameWithMIMEType(self, MIMEType);
815 @implementation NSString (WebNSURLExtras)
817 - (BOOL)_web_isUserVisibleURL
822 char static_buffer[1024];
824 BOOL success = CFStringGetCString((CFStringRef)self, static_buffer, 1023, kCFStringEncodingUTF8);
828 p = [self UTF8String];
831 int length = strlen(p);
833 // check for characters <= 0x20 or >=0x7f, %-escape sequences of %7f, and xn--, these
834 // are the things that will lead _web_userVisibleString to actually change things.
836 for (i = 0; i < length; i++) {
837 unsigned char c = p[i];
838 // escape control characters, space, and delete
839 if (c <= 0x20 || c == 0x7f) {
842 } else if (c == '%' && (i + 1 < length && isHexDigit(p[i + 1])) && i + 2 < length && isHexDigit(p[i + 2])) {
843 unsigned char u = (hexDigitValue(p[i + 1]) << 4) | hexDigitValue(p[i + 2]);
850 // Check for "xn--" in an efficient, non-case-sensitive, way.
851 if (c == '-' && i >= 3 && (p[i - 3] | 0x20) == 'x' && (p[i - 2] | 0x20) == 'n' && p[i - 1] == '-') {
862 - (BOOL)_webkit_isJavaScriptURL
864 return [self _webkit_hasCaseInsensitivePrefix:@"javascript:"];
867 - (BOOL)_webkit_isFileURL
869 return [self rangeOfString:@"file:" options:(NSCaseInsensitiveSearch | NSAnchoredSearch)].location != NSNotFound;
872 - (NSString *)_webkit_stringByReplacingValidPercentEscapes
874 return decodeURLEscapeSequences(self);
877 - (NSString *)_webkit_scriptIfJavaScriptURL
879 if (![self _webkit_isJavaScriptURL]) {
882 return [[self substringFromIndex:11] _webkit_stringByReplacingValidPercentEscapes];
885 - (BOOL)_webkit_isFTPDirectoryURL
887 int length = [self length];
888 if (length < 5) { // 5 is length of "ftp:/"
891 unichar lastChar = [self characterAtIndex:length - 1];
892 return lastChar == '/' && [self _webkit_hasCaseInsensitivePrefix:@"ftp:"];
896 static BOOL readIDNScriptWhiteListFile(NSString *filename)
901 FILE *file = fopen([filename fileSystemRepresentation], "r");
906 // Read a word at a time.
907 // Allow comments, starting with # character to the end of the line.
909 // Skip a comment if present.
910 int result = fscanf(file, " #%*[^\n\r]%*[\n\r]");
915 // Read a script name if present.
917 result = fscanf(file, " %32[^# \t\n\r]%*[^# \t\n\r] ", word);
922 // Got a word, map to script code and put it into the array.
923 int32_t script = u_getPropertyValueEnum(UCHAR_SCRIPT, word);
924 if (script >= 0 && script < USCRIPT_CODE_LIMIT) {
925 size_t index = script / 32;
926 uint32_t mask = 1 << (script % 32);
927 IDNScriptWhiteList[index] |= mask;
935 static void readIDNScriptWhiteList(void)
937 // Read white list from library.
938 NSArray *dirs = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSAllDomainsMask, YES);
939 int i, numDirs = [dirs count];
940 for (i = 0; i < numDirs; i++) {
941 NSString *dir = [dirs objectAtIndex:i];
942 if (readIDNScriptWhiteListFile([dir stringByAppendingPathComponent:@"IDNScriptWhiteList.txt"])) {
947 // Fall back on white list inside bundle.
948 NSBundle *bundle = [NSBundle bundleWithIdentifier:@"com.apple.WebKit"];
949 readIDNScriptWhiteListFile([bundle pathForResource:@"IDNScriptWhiteList" ofType:@"txt"]);
952 static BOOL allCharactersInIDNScriptWhiteList(const UChar *buffer, int32_t length)
954 pthread_once(&IDNScriptWhiteListFileRead, readIDNScriptWhiteList);
959 U16_NEXT(buffer, i, length, c)
960 UErrorCode error = U_ZERO_ERROR;
961 UScriptCode script = uscript_getScript(c, &error);
962 if (error != U_ZERO_ERROR) {
963 LOG_ERROR("got ICU error while trying to look at scripts: %d", error);
967 LOG_ERROR("got negative number for script code from ICU: %d", script);
970 if (script >= USCRIPT_CODE_LIMIT) {
973 size_t index = script / 32;
974 uint32_t mask = 1 << (script % 32);
975 if (!(IDNScriptWhiteList[index] & mask)) {
979 if (isLookalikeCharacter(c))
985 // Return value of nil means no mapping is necessary.
986 // If makeString is NO, then return value is either nil or self to indicate mapping is necessary.
987 // If makeString is YES, then return value is either nil or the mapped string.
988 - (NSString *)_web_mapHostNameWithRange:(NSRange)range encode:(BOOL)encode makeString:(BOOL)makeString
990 if (range.length > HOST_NAME_BUFFER_LENGTH) {
994 if ([self length] == 0)
997 UChar sourceBuffer[HOST_NAME_BUFFER_LENGTH];
998 UChar destinationBuffer[HOST_NAME_BUFFER_LENGTH];
1000 NSString *string = self;
1001 if (encode && [self rangeOfString:@"%" options:NSLiteralSearch range:range].location != NSNotFound) {
1002 NSString *substring = [self substringWithRange:range];
1003 substring = WebCFAutorelease(CFURLCreateStringByReplacingPercentEscapes(NULL, (CFStringRef)substring, CFSTR("")));
1004 if (substring != nil) {
1006 range = NSMakeRange(0, [string length]);
1010 int length = range.length;
1011 [string getCharacters:sourceBuffer range:range];
1013 UErrorCode error = U_ZERO_ERROR;
1014 int32_t numCharactersConverted = (encode ? uidna_IDNToASCII : uidna_IDNToUnicode)
1015 (sourceBuffer, length, destinationBuffer, HOST_NAME_BUFFER_LENGTH, UIDNA_ALLOW_UNASSIGNED, NULL, &error);
1016 if (error != U_ZERO_ERROR) {
1019 if (numCharactersConverted == length && memcmp(sourceBuffer, destinationBuffer, length * sizeof(UChar)) == 0) {
1022 if (!encode && !allCharactersInIDNScriptWhiteList(destinationBuffer, numCharactersConverted)) {
1025 return makeString ? (NSString *)[NSString stringWithCharacters:destinationBuffer length:numCharactersConverted] : (NSString *)self;
1028 - (BOOL)_web_hostNameNeedsDecodingWithRange:(NSRange)range
1030 return [self _web_mapHostNameWithRange:range encode:NO makeString:NO] != nil;
1033 - (BOOL)_web_hostNameNeedsEncodingWithRange:(NSRange)range
1035 return [self _web_mapHostNameWithRange:range encode:YES makeString:NO] != nil;
1038 - (NSString *)_web_decodeHostNameWithRange:(NSRange)range
1040 return [self _web_mapHostNameWithRange:range encode:NO makeString:YES];
1043 - (NSString *)_web_encodeHostNameWithRange:(NSRange)range
1045 return [self _web_mapHostNameWithRange:range encode:YES makeString:YES];
1048 - (NSString *)_web_decodeHostName
1050 NSString *name = [self _web_mapHostNameWithRange:NSMakeRange(0, [self length]) encode:NO makeString:YES];
1051 return name == nil ? self : name;
1054 - (NSString *)_web_encodeHostName
1056 NSString *name = [self _web_mapHostNameWithRange:NSMakeRange(0, [self length]) encode:YES makeString:YES];
1057 return name == nil ? self : name;
1060 -(NSRange)_webkit_rangeOfURLScheme
1062 NSRange colon = [self rangeOfString:@":"];
1063 if (colon.location != NSNotFound && colon.location > 0) {
1064 NSRange scheme = {0, colon.location};
1065 static NSCharacterSet *InverseSchemeCharacterSet = nil;
1066 if (!InverseSchemeCharacterSet) {
1068 This stuff is very expensive. 10-15 msec on a 2x1.2GHz. If not cached it swamps
1069 everything else when adding items to the autocomplete DB. Makes me wonder if we
1070 even need to enforce the character set here.
1072 NSString *acceptableCharacters = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+.-";
1073 InverseSchemeCharacterSet = [[[NSCharacterSet characterSetWithCharactersInString:acceptableCharacters] invertedSet] retain];
1075 NSRange illegals = [self rangeOfCharacterFromSet:InverseSchemeCharacterSet options:0 range:scheme];
1076 if (illegals.location == NSNotFound)
1079 return NSMakeRange(NSNotFound, 0);
1082 -(BOOL)_webkit_looksLikeAbsoluteURL
1084 // Trim whitespace because _web_URLWithString allows whitespace.
1085 return [[self _webkit_stringByTrimmingWhitespace] _webkit_rangeOfURLScheme].location != NSNotFound;
1088 - (NSString *)_webkit_URLFragment
1090 NSRange fragmentRange;
1092 fragmentRange = [self rangeOfString:@"#" options:NSLiteralSearch];
1093 if (fragmentRange.location == NSNotFound)
1095 return [self substringFromIndex:fragmentRange.location + 1];