Skip to content

Commit

Permalink
Handle escaping literal hosts properly
Browse files Browse the repository at this point in the history
  • Loading branch information
mikeabdullah committed Jul 24, 2013
1 parent f2e0d5e commit 7afd63b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
23 changes: 22 additions & 1 deletion KSURLComponents.m
Original file line number Diff line number Diff line change
Expand Up @@ -317,9 +317,30 @@ - (NSString *)host;
}
- (void)setHost:(NSString *)host;
{
NSRange startBracket = [host rangeOfString:@"[" options:NSAnchoredSearch];
if (startBracket.location != NSNotFound)
{
NSRange endBracket = [host rangeOfString:@"]" options:NSAnchoredSearch|NSBackwardsSearch];
if (endBracket.location != NSNotFound)
{
host = [host substringWithRange:NSMakeRange(startBracket.length, host.length - endBracket.length - startBracket.length)];

CFStringRef escaped = CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)host, NULL, CFSTR("@/?#"), kCFStringEncodingUTF8);
// @ must be escaped so as not to confuse as a username
// Don't escape : as it's within a host literal, and likely part of an IPv6 address
// / ? and # must be escaped so as not to indicate start of path, query or fragment

NSString *encoded = [NSString stringWithFormat:@"[%@]", escaped];

self.percentEncodedHost = encoded;
CFRelease(escaped);
return;
}
}

CFStringRef escaped = CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)host, NULL, CFSTR("@:/?#"), kCFStringEncodingUTF8);
// @ must be escaped so as not to confuse as a username
// Escaping : too to avoid confusion with port. NSURLComponents doesn't do so at present rdar://14387977
// : must be escaped too to avoid confusion with port
// / ? and # must be escaped so as not to indicate start of path, query or fragment

self.percentEncodedHost = (NSString *)escaped;
Expand Down
10 changes: 10 additions & 0 deletions TestKSFileUtilities/TestKSURLComponents.m
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,16 @@ - (void)testHostEscaping;
[components release];
}

- (void)testLiteralHostEscaping;
{
KSURLComponents *components = [[KSURLComponents alloc] init];

components.host = @"[!*'();:@&=+$,/?#[]]";
STAssertEqualObjects(components.percentEncodedHost, @"[!*'();:%40&=+$,%2F%3F%23%5B%5D]", @"Bracketing in [ ] indicates a literal host, which is allowed to contain : characters, e.g. for IPv6 addresses");

[components release];
}

- (void)testPathEscaping;
{
KSURLComponents *components = [[KSURLComponents alloc] init];
Expand Down

0 comments on commit 7afd63b

Please sign in to comment.