Scoop API

scoop:scoop.http:0.1.0

src/cookie/public_suffix_parse.scoop

Selected production source · src/cookie/public_suffix_parse.scoop

1package scoop.http
3import scoop.collections.*
4import scoop.idna.*
5import scoop.text.*
7/**
8 * A malformed public-suffix rule with source line and optional cause.
9 */
10public class PublicSuffixParseException public constructor(
11 /**
12 * The one-based input line containing the invalid rule.
13 */
14 public val line: Long,
15 /**
16 * The parse or negotiation failure explanation.
17 */
18 public val detail: String,
19 /**
20 * The underlying failure when available.
21 */
22 public val cause: Throwable? = None
23) : Exception(Some("public suffix list at line " + line.toString() + ": " + detail))
25internal fun parsePublicSuffixList(text: String): PublicSuffixList {
26 val rules = HashMap<String, Int>()
27 var privateRules = false
28 var version: String? = None
29 var revision: String? = None
30 var count = 0L
31 var number = 0L
32 for (input in text.split('\n')) {
33 number += 1L
34 val line = input.trim()
35 if (line.charLength == 0L) continue
36 if (line.startsWith("//")) {
37 if (line == "// ===BEGIN PRIVATE DOMAINS===") privateRules = true
38 if (line == "// ===BEGIN ICANN DOMAINS===") privateRules = false
39 if (line.startsWith("// VERSION:")) version = Some(line.slice(11L, line.charLength).trim())
40 if (line.startsWith("// COMMIT:")) revision = Some(line.slice(10L, line.charLength).trim())
41 continue
42 }
43 val token = line.substringBefore(' ').substringBefore('\t')
44 val wildcard = token == "*" || token.startsWith("*.")
45 val exception = token.startsWith("!")
46 val bare = if (token == "*") "" else if (wildcard) token.slice(2L, token.charLength)
47 else if (exception) token.slice(1L, token.charLength) else token
48 val name = if (token == "*") "" else publicSuffixRuleName(bare, number)
49 if (exception && !name.contains('.')) throw PublicSuffixParseException(number, "exception requires at least two labels")
50 val bit = (if (wildcard) 2 else if (exception) 4 else 1) shl (if (privateRules) 3 else 0)
51 val previous = rules.getOrDefault(name, 0)
52 if ((previous and bit) == 0) count += 1L
53 rules.put(name, previous or bit)
54 }
55 return PublicSuffixList(rules, count, version, revision)
58private fun publicSuffixRuleName(text: String, line: Long): String {
59 val normalized = try { Idna.toAscii(text) } catch (error: IdnaException) {
60 if (error.kind == IdnaFailureKind.Backend) throw error
61 throw PublicSuffixParseException(line, "invalid rule domain", Some(error))
62 }
63 if (normalized.endsWith(".")) throw PublicSuffixParseException(line, "rule cannot end with a root dot")
64 return normalized