Repository Public License
1import Foundation2import NavigatorCore34// MARK: - Domains56/// Host names as content rules need them: lowercase ASCII (punycode for IDN), validated.7public enum ShieldDomain {8 /// Normalises a user- or list-supplied host. Accepts an optional leading `*.` or `.` (subdomain wildcard,9 /// which is implied anyway) and a trailing dot. Returns `nil` for anything that is not a plain host name:10 /// empty labels, characters outside letters / digits / hyphen, labels over 63 bytes, names over 253,11 /// a single label (`localhost`, `com`), or something carrying a scheme, path, port or user info.12 public static func normalize(_ raw: String) -> String? {13 var text = raw.trimmingCharacters(in: .whitespaces).lowercased()14 if text.hasPrefix("*.") { text.removeFirst(2) } else if text.hasPrefix(".") { text.removeFirst() }15 if text.hasSuffix(".") { text.removeLast() }16 guard !text.isEmpty, text.utf8.count <= 253 else { return nil }17 if !text.utf8.allSatisfy({ $0 < 0x80 }) {18 // IDN: let Foundation produce the punycode form. Anything it refuses is rejected.19 guard text.unicodeScalars.allSatisfy({ !CharacterSet.whitespacesAndNewlines.contains($0) && !"/:@?#[]\\%".unicodeScalars.contains($0) }) else { return nil }20 var components = URLComponents()21 components.scheme = "https"22 components.host = text23 guard let encoded = components.encodedHost?.lowercased(), !encoded.isEmpty, encoded.utf8.allSatisfy({ $0 < 0x80 }),24 !encoded.contains("%") else { return nil }25 text = encoded26 }27 guard text.utf8.count <= 253 else { return nil }28 let labels = text.split(separator: ".", omittingEmptySubsequences: false)29 guard labels.count >= 2 else { return nil }30 for label in labels {31 guard !label.isEmpty, label.utf8.count <= 63, !label.hasPrefix("-"), !label.hasSuffix("-"),32 label.utf8.allSatisfy({ ($0 >= 0x61 && $0 <= 0x7A) || ($0 >= 0x30 && $0 <= 0x39) || $0 == 0x2D }) else { return nil }33 }34 // An all-numeric last label is an IP address (or nonsense), not a domain a list should block by name.35 guard let last = labels.last, !last.utf8.allSatisfy({ $0 >= 0x30 && $0 <= 0x39 }) else { return nil }36 return text37 }3839 /// The host of a URL, normalised; `nil` for hosts `normalize` rejects (IP addresses, single labels).40 public static func site(of url: URL) -> String? {41 URLComponents(url: url, resolvingAgainstBaseURL: true)?.encodedHost.flatMap(normalize)42 }4344 /// `host` and its parent domains, most specific first: `a.b.example.com`, `b.example.com`, `example.com`.45 /// The bare top-level label is not included.46 public static func selfAndParents(of host: String) -> [String] {47 var result: [String] = []48 var rest = Substring(host)49 while rest.contains(".") {50 result.append(String(rest))51 rest = rest[rest.index(after: rest.firstIndex(of: ".")!)...]52 }53 return result54 }5556 /// Whether `host` is `domain` or one of its subdomains.57 public static func host(_ host: String, isWithin domain: String) -> Bool {58 host == domain || host.hasSuffix("." + domain)59 }60}6162// MARK: - Rule model6364public enum ShieldCategory: String, Sendable, Codable, CaseIterable {65 case trackers, ads66 /// Domains from lists the user imported.67 case custom68}6970/// "Block third-party requests to this domain and its subdomains."71public struct BlockedDomain: Sendable, Hashable, Codable {72 public var domain: String73 public var category: ShieldCategory74 /// Sites (and their subdomains) on which the rule does not apply — typically the same owner's own sites.75 public var exceptOnSites: [String]7677 public init(domain: String, category: ShieldCategory, exceptOnSites: [String] = []) {78 self.domain = domain; self.category = category; self.exceptOnSites = exceptOnSites79 }80}8182/// "Hide the elements matching this CSS selector."83public struct CosmeticRule: Sendable, Hashable, Codable {84 public enum Scope: Sendable, Hashable, Codable {85 /// On every site except the listed ones.86 case everywhere(except: [String])87 /// Only on the listed sites (and their subdomains).88 case only([String])89 }9091 public var selector: String92 public var scope: Scope9394 public init(selector: String, scope: Scope = .everywhere(except: [])) {95 self.selector = selector; self.scope = scope96 }9798 /// Conservative check of a selector before it is put in a rule list: WebKit rejects the *whole* list when99 /// one selector does not parse, so anything unusual is refused here. Allowed outside quotes: ASCII letters,100 /// digits, spaces and `# . - _ [ ] = ^ $ * ~ | : ( ) > + ,`; inside a quoted string: any printable ASCII101 /// character except a backslash. Brackets, parentheses and quotes must balance; at most 512 characters.102 /// Returns a reason when the selector is refused.103 public static func validate(selector: String) -> String? {104 let trimmed = selector.trimmingCharacters(in: .whitespaces)105 guard !trimmed.isEmpty else { return "empty selector" }106 guard trimmed.count <= 512 else { return "selector longer than 512 characters" }107 let allowed = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 #.-_[]=^$*~|:()>+,")108 var stack: [Character] = []109 var quote: Character?110 for character in trimmed {111 guard character.unicodeScalars.count == 1, let scalar = character.unicodeScalars.first else {112 return "selector contains an unsupported character"113 }114 if let open = quote {115 guard scalar.value >= 0x20, scalar.value < 0x7F, character != "\\" else { return "selector contains an unsupported character" }116 if character == open { quote = nil }117 continue118 }119 switch character {120 case "\"", "'": quote = character121 case "[", "(": stack.append(character)122 case "]": guard stack.popLast() == "[" else { return "unbalanced brackets" }123 case ")": guard stack.popLast() == "(" else { return "unbalanced parentheses" }124 default: guard allowed.contains(scalar) else { return "selector contains an unsupported character" }125 }126 }127 guard quote == nil else { return "unterminated quote" }128 guard stack.isEmpty else { return "unbalanced brackets" }129 guard let last = trimmed.last, !">+~,".contains(last), let first = trimmed.first, !">+~,".contains(first) else {130 return "selector starts or ends with a combinator"131 }132 return nil133 }134}135136/// A set of rules with a name and a version: the built-in list or a list the user imported.137public struct ShieldList: Sendable, Hashable, Codable {138 public var title: String139 public var version: String140 public var blocked: [BlockedDomain]141 /// Domains the list asks to leave alone (`@@||domain^`): removed from every list when rules are generated.142 public var unblocked: [String]143 public var cosmetic: [CosmeticRule]144145 public init(title: String = "", version: String = "", blocked: [BlockedDomain] = [], unblocked: [String] = [],146 cosmetic: [CosmeticRule] = []) {147 self.title = title; self.version = version; self.blocked = blocked; self.unblocked = unblocked; self.cosmetic = cosmetic148 }149150 public var ruleCount: Int { blocked.count + cosmetic.count }151 public static let empty = ShieldList()152153 /// The list shipped with the app (`Resources/shield-builtin.txt`). See docs/SHIELD.md: it is a short,154 /// original list, not EasyList, and its coverage is partial.155 public static let builtIn: ShieldList = {156 guard let url = Bundle.module.url(forResource: "shield-builtin", withExtension: "txt"),157 let text = try? String(contentsOf: url, encoding: .utf8) else { return .empty }158 return ShieldListParser.parse(text, defaultCategory: .trackers).list159 }()160}161162// MARK: - Parsing163164public struct ShieldListDiagnostic: Sendable, Hashable, Codable, CustomStringConvertible {165 public enum Severity: String, Sendable, Codable { case rejected, note }166 public var line: Int167 public var severity: Severity168 public var message: String169 /// The offending line, truncated to 120 characters.170 public var text: String171172 public var description: String { "line \(line): \(message)" }173}174175public struct ShieldListParseResult: Sendable, Hashable {176 public var list: ShieldList177 public var diagnostics: [ShieldListDiagnostic]178 /// Lines that produced a rule.179 public var acceptedLines: Int180 public var rejectedLines: Int { diagnostics.filter { $0.severity == .rejected }.count }181}182183/// Reads the documented list format (docs/SHIELD.md). It accepts a deliberately small, unambiguous subset and184/// rejects everything else with a diagnostic instead of guessing what a rule meant:185///186/// - `! comment`, `# comment`, blank lines; `! title: …` and `! version: …` metadata.187/// - `[trackers]`, `[ads]`, `[custom]` section headers; any other `[…]` header (e.g. `[Adblock Plus 2.0]`) is ignored.188/// - `example.com` — block third-party requests to the domain and its subdomains.189/// Optional ` unless=site1.com,site2.com`.190/// - `||example.com^`, optionally with `$third-party` — the same thing in Adblock-Plus syntax.191/// - `@@||example.com^` — never block this domain (overrides every list).192/// - `0.0.0.0 example.com` / `127.0.0.1 example.com` — hosts-file lines.193/// - `##selector` and `site1.com,site2.com##selector` — hide elements (cosmetic rule).194///195/// Not supported, always rejected: path or wildcard patterns (`||example.com/ads/*`), regular expressions196/// (`/…/`), other `$options`, `#@#`, `#?#`, scriptlets (`#%#`, `##+js`), `~site` negations in cosmetic rules.197public enum ShieldListParser {198 public static let maximumBytes = 8 * 1_024 * 1_024199 public static let maximumLineLength = 2_048200 public static let maximumDiagnostics = 500201202 public static func parse(_ text: String, defaultCategory: ShieldCategory = .custom) -> ShieldListParseResult {203 var list = ShieldList()204 var diagnostics: [ShieldListDiagnostic] = []205 var accepted = 0206 var category = defaultCategory207 var seenBlocked = Set<String>(), seenCosmetic = Set<CosmeticRule>(), seenUnblocked = Set<String>()208 var droppedDiagnostics = 0209210 func report(_ line: Int, _ message: String, _ source: Substring, severity: ShieldListDiagnostic.Severity = .rejected) {211 guard diagnostics.count < maximumDiagnostics else { droppedDiagnostics += 1; return }212 diagnostics.append(ShieldListDiagnostic(line: line, severity: severity, message: message, text: String(source.prefix(120))))213 }214215 guard text.utf8.count <= maximumBytes else {216 report(0, "list larger than \(maximumBytes / 1_048_576) MB: nothing imported", "")217 return ShieldListParseResult(list: list, diagnostics: diagnostics, acceptedLines: 0)218 }219220 lines: for (index, rawLine) in text.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline).enumerated() {221 let number = index + 1222 let line = Substring(rawLine.trimmingCharacters(in: .whitespaces))223 guard !line.isEmpty else { continue }224 guard line.count <= maximumLineLength else { report(number, "line too long", line); continue lines }225226 // Comments and metadata.227 if line.hasPrefix("!") || (line.hasPrefix("#") && !line.hasPrefix("##") && !line.hasPrefix("#@#") && !line.hasPrefix("#?#") && !line.hasPrefix("#%#")) {228 let body = line.dropFirst().trimmingCharacters(in: .whitespaces)229 if let value = metadata("title", in: body) { list.title = String(value.prefix(120)) }230 if let value = metadata("version", in: body) { list.version = String(value.prefix(60)) }231 continue232 }233 if line.hasPrefix("[") && line.hasSuffix("]") {234 if let named = ShieldCategory(rawValue: line.dropFirst().dropLast().lowercased()) { category = named }235 continue236 }237238 // Cosmetic rules.239 if line.contains("#@#") || line.contains("#?#") || line.contains("#%#") || line.contains("#$#") {240 report(number, "unsupported cosmetic rule type", line); continue lines241 }242 if let range = line.range(of: "##") {243 let selector = line[range.upperBound...].trimmingCharacters(in: .whitespaces)244 if selector.hasPrefix("+js") || selector.hasPrefix("^") { report(number, "scriptlets and HTML filters are not supported", line); continue lines }245 if let problem = CosmeticRule.validate(selector: selector) { report(number, problem, line); continue lines }246 var sites: [String] = []247 for part in line[..<range.lowerBound].split(separator: ",") {248 let site = part.trimmingCharacters(in: .whitespaces)249 if site.hasPrefix("~") { report(number, "site negation (~) is not supported in cosmetic rules", line); continue lines }250 guard let normalized = ShieldDomain.normalize(site) else { report(number, "invalid site “\(site.prefix(60))”", line); continue lines }251 sites.append(normalized)252 }253 let rule = CosmeticRule(selector: selector, scope: sites.isEmpty ? .everywhere(except: []) : .only(sites))254 if seenCosmetic.insert(rule).inserted { list.cosmetic.append(rule) }255 accepted += 1256 continue257 }258259 // Exceptions.260 if line.hasPrefix("@@") {261 guard let domain = adblockDomain(line.dropFirst(2), allowOptions: false) else {262 report(number, "only “@@||domain^” exceptions are supported", line); continue lines263 }264 if seenUnblocked.insert(domain).inserted { list.unblocked.append(domain) }265 accepted += 1266 continue267 }268269 // Adblock-Plus domain rule.270 if line.hasPrefix("||") {271 guard let domain = adblockDomain(line, allowOptions: true) else {272 report(number, "only “||domain^” (optionally with $third-party) is supported", line); continue lines273 }274 if seenBlocked.insert(domain).inserted { list.blocked.append(BlockedDomain(domain: domain, category: category)) }275 accepted += 1276 continue277 }278 if line.hasPrefix("|") || line.hasPrefix("/") || line.contains("*") || line.contains("$") || line.contains("^") {279 report(number, "URL patterns, wildcards, regular expressions and options are not supported", line); continue lines280 }281282 // Plain domain, hosts-file line, or domain with `unless=`.283 // A trailing "# comment" is common in hosts files.284 let content = line.range(of: " #").map { line[..<$0.lowerBound] } ?? line285 var fields = content.split(whereSeparator: \.isWhitespace).map(String.init)286 if fields.count == 2, ["0.0.0.0", "127.0.0.1", "::", "::1"].contains(fields[0]) { fields.removeFirst() }287 var exceptions: [String] = []288 if fields.count == 2, fields[1].hasPrefix("unless=") {289 for part in fields[1].dropFirst(7).split(separator: ",") {290 guard let site = ShieldDomain.normalize(String(part)) else { report(number, "invalid site in unless=", line); continue lines }291 exceptions.append(site)292 }293 fields.removeLast()294 }295 guard fields.count == 1 else { report(number, "not a domain", line); continue lines }296 if ["localhost", "localhost.localdomain", "broadcasthost", "local"].contains(fields[0].lowercased()) { continue lines }297 guard let domain = ShieldDomain.normalize(fields[0]) else { report(number, "not a valid domain", line); continue lines }298 if seenBlocked.insert(domain).inserted {299 list.blocked.append(BlockedDomain(domain: domain, category: category, exceptOnSites: exceptions))300 }301 accepted += 1302 }303 if droppedDiagnostics > 0 {304 diagnostics.append(ShieldListDiagnostic(line: 0, severity: .note,305 message: "\(droppedDiagnostics) more rejected lines not listed", text: ""))306 }307 return ShieldListParseResult(list: list, diagnostics: diagnostics, acceptedLines: accepted)308 }309310 private static func metadata(_ key: String, in body: String) -> String? {311 let prefix = key + ":"312 guard body.lowercased().hasPrefix(prefix) else { return nil }313 let value = body.dropFirst(prefix.count).trimmingCharacters(in: .whitespaces)314 return value.isEmpty ? nil : value315 }316317 /// Domain of `||domain^` (with an optional `$third-party`), or `nil` for anything else.318 private static func adblockDomain(_ rule: Substring, allowOptions: Bool) -> String? {319 guard rule.hasPrefix("||") else { return nil }320 var body = rule.dropFirst(2)321 if let dollar = body.firstIndex(of: "$") {322 let options = body[body.index(after: dollar)...]323 guard allowOptions, options == "third-party" || options == "3p" else { return nil }324 body = body[..<dollar]325 }326 guard body.hasSuffix("^") else { return nil }327 body = body.dropLast()328 guard !body.contains("/"), !body.contains("*"), !body.contains("^"), !body.contains("|") else { return nil }329 return ShieldDomain.normalize(String(body))330 }331}332