scoop:scoop.url:0.1.0
src/host.scoop
Selected production source · src/host.scoop
1
package scoop.url3
import scoop.idna.*4
import scoop.text.*6
/**7
* A validated network host represented as a DNS A-label name or exact IP address bytes.8
*/9
public enum UrlHost : Equals<UrlHost>, Hash, ToString {10
/**11
* A DNS name normalized for network-origin comparison.12
*/13
Dns(val name: String),14
/**15
* Exactly four network-order address bytes.16
*/17
Ipv4(val bytes: Array<Byte>),18
/**19
* Exactly sixteen network-order address bytes; zone identifiers are outside this URL20
* profile.21
*/22
Ipv6(val bytes: Array<Byte>)24
/**25
* Compares normalized DNS names or exact same-family address bytes.26
*/27
public override operator fun equals(other: UrlHost): Boolean = when (this) {28
case Dns(val name) -> when (other) { case Dns(val right) -> name == right; else -> false }29
case Ipv4(val bytes) -> when (other) { case Ipv4(val right) -> urlBytesEqual(bytes, right); else -> false }30
case Ipv6(val bytes) -> when (other) { case Ipv6(val right) -> urlBytesEqual(bytes, right); else -> false }31
}32
/**33
* Hashes the same normalized host identity used by equality.34
*/35
public override fun hash(): Long = when (this) {36
case Dns(val name) -> name.hash()37
case Ipv4(val bytes) -> hashUrlBytes(bytes, 4L)38
case Ipv6(val bytes) -> hashUrlBytes(bytes, 6L)39
}40
/**41
* Serializes the DNS name or IP literal for use in a URI authority.42
*/43
public override fun toString(): String = when (this) {44
case Dns(val name) -> name45
case Ipv4(val bytes) -> formatUrlIp(bytes, false)46
case Ipv6(val bytes) -> formatUrlIp(bytes, true)47
}48
internal fun authorityText(): String = when (this) {49
case Ipv6(_) -> "[" + toString() + "]"50
else -> toString()51
}52
}54
internal fun urlBytesEqual(left: List<Byte>, right: List<Byte>): Boolean {55
if (left.size != right.size) return false56
for (index in 0L..<left.size) { if (left[index] != right[index]) return false }57
return true58
}60
private fun hashUrlBytes(bytes: List<Byte>, seed: Long): Long {61
var result = seed62
for (byte in bytes) { result = result * 31L + byte.toLong() }63
return result64
}66
private fun formatUrlIp(bytes: List<Byte>, ipv6: Boolean): String {67
if (bytes.size != (if (ipv6) 16L else 4L)) throw IllegalArgumentException(Some("invalid IP address byte length"))68
val text = StringBuilder()69
if (ipv6) {70
val hex = bytes.toHexString()71
for (index in 0L..<8L) {72
if (index > 0L) text.append(":")73
text.append(hex.slice(index * 4L, index * 4L + 4L))74
}75
} else {76
for (index in 0L..<4L) {77
if (index > 0L) text.append(".")78
text.append((bytes[index].toInt() and 255).toString())79
}80
}81
return text.toString()82
}84
internal enum HostResolution {85
Dns(val name: IdnaName), Ipv4(val bytes: Array<Byte>), Ipv6(val bytes: Array<Byte>),86
Invalid(val detail: String, val cause: Throwable?)87
}89
internal fun resolveUrlHost(host: String, kind: Int, address: Array<Byte>): HostResolution {90
if (kind == 1) return HostResolution.Ipv4(address)91
if (kind == 2) return HostResolution.Ipv6(address)92
if (kind == 3) return HostResolution.Invalid("IPvFuture is not an HTTP connection target", None)93
val decoded = String.fromUtf8OrNone(PercentEncoding.decode(host))94
if (decoded == None) return HostResolution.Invalid("network host is not UTF-8", None)95
try {96
val name = Idna.parse(decoded!!)97
val canonical = stripRootDot(name.ascii)98
if (canonical.charLength == 0L) return HostResolution.Invalid("network host is empty or the DNS root", None)99
if (numericUrlHost(canonical)) {100
val bytes = urlNativeIpv4(canonical)101
if (!hasUrlValue(bytes)) return HostResolution.Invalid("IPv4 requires four decimal octets without leading zeroes", None)102
return HostResolution.Ipv4(bytes!!)103
}104
return HostResolution.Dns(name)105
} catch (error: IdnaException) {106
if (error.kind == IdnaFailureKind.Backend) throw error107
return HostResolution.Invalid(error.detail, Some(error))108
}109
}111
internal fun stripRootDot(host: String): String = if (host.endsWith(".")) host.slice(0L, host.charLength - 1L) else host113
private fun numericUrlHost(host: String): Boolean {114
for (label in host.split('.')) {115
if (label.charLength == 0L) return false116
if (label.startsWith("0x")) {117
if (label.charLength == 2L) return false118
for (index in 2L..<label.charLength) { if (hexDigit(label.getCharAt(index).code) < 0) return false }119
} else {120
for (character in label) { if (character < '0' || character > '9') return false }121
}122
}123
return true124
}