scoop:scoop.http:0.1.0
src/cookie/public_suffix_parse.scoop
Selected production source · src/cookie/public_suffix_parse.scoop
1
package scoop.http3
import scoop.collections.*4
import scoop.idna.*5
import scoop.text.*7
/**8
* A malformed public-suffix rule with source line and optional cause.9
*/10
public 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? = None23
) : Exception(Some("public suffix list at line " + line.toString() + ": " + detail))25
internal fun parsePublicSuffixList(text: String): PublicSuffixList {26
val rules = HashMap<String, Int>()27
var privateRules = false28
var version: String? = None29
var revision: String? = None30
var count = 0L31
var number = 0L32
for (input in text.split('\n')) {33
number += 1L34
val line = input.trim()35
if (line.charLength == 0L) continue36
if (line.startsWith("//")) {37
if (line == "// ===BEGIN PRIVATE DOMAINS===") privateRules = true38
if (line == "// ===BEGIN ICANN DOMAINS===") privateRules = false39
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
continue42
}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 token48
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 += 1L53
rules.put(name, previous or bit)54
}55
return PublicSuffixList(rules, count, version, revision)56
}58
private fun publicSuffixRuleName(text: String, line: Long): String {59
val normalized = try { Idna.toAscii(text) } catch (error: IdnaException) {60
if (error.kind == IdnaFailureKind.Backend) throw error61
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 normalized65
}