3 * Copyright (c) 2016 Apple Inc. All rights reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 #import "CNDomainBrowserPathUtils.h"
19 #import <CFNetwork/CFHostPriv.h>
20 #include "../../../Clients/ClientCommon.h"
22 static const char *EscapeLabel(const char *cstr, char label[64])
24 // Based on code on clownfish from: DNSName::GetEscapedDNSName
26 while (*cstr) // While we have characters in the label...
29 if (c == '\\' || c == '.') // escape '\' and '.'
31 if (ptr >= label+64-2) return(NULL);
35 else if (c <= ' ') // escape ' ' and lower
37 if (ptr >= label+64-4) return(NULL);
39 *ptr++ = '0' + (c / 100);
40 *ptr++ = '0' + ((c / 10) % 10);
41 *ptr++ = '0' + (c % 10);
45 if (ptr >= label+64-1) return(NULL);
53 NSString * DomainPathToDNSDomain(NSArray * domainPath)
55 NSMutableString * dnsStr = [NSMutableString string];
58 for (NSString * next in domainPath)
61 if (dnsStr.length) nextLabel = [NSString stringWithUTF8String: EscapeLabel([next UTF8String], label)];
62 else nextLabel = next;
63 [dnsStr insertString: [NSString stringWithFormat: @"%@.", nextLabel] atIndex: 0];
69 NSArray * DNSDomainToDomainPath(NSString * domain)
71 int labels = 0, depth = 0;
73 const char * domainStr = domain.UTF8String;
74 const char *label[128];
75 NSString * undottedStr;
76 NSMutableArray *a = [NSMutableArray array];
80 label[labels] = domainStr;
81 domainStr = GetNextLabel(domainStr, text);
83 undottedStr = [[NSString stringWithUTF8String: label[labels]]
84 stringByTrimmingCharactersInSet: [NSCharacterSet punctuationCharacterSet]];
85 if (!*domainStr || _CFHostIsDomainTopLevel((__bridge CFStringRef)undottedStr))
89 labels--; // If not first level then back up one level
90 undottedStr = [[NSString stringWithUTF8String: label[labels]]
91 stringByTrimmingCharactersInSet: [NSCharacterSet punctuationCharacterSet]];
93 [a addObject: undottedStr];
99 // Process the remainder of the hierarchy
100 for (depth = 0 ; depth < labels ; depth++)
102 GetNextLabel(label[labels-1-depth], text);
103 [a addObject: [NSString stringWithUTF8String: text]];
109 NSString * TrimCharactersFromDNSDomain(NSString * domain)
111 NSMutableCharacterSet * trimSet = [NSMutableCharacterSet whitespaceCharacterSet];
112 [trimSet formUnionWithCharacterSet:[NSCharacterSet punctuationCharacterSet]];
113 return([domain stringByTrimmingCharactersInSet:trimSet]);