提交 Haven Android 仓库源码 v5.87.79

This commit is contained in:
ali
2026-09-10 13:45:36 +08:00
parent 87b452c4dc
commit 22f4ca5830
2524 changed files with 599455 additions and 1 deletions
+39
View File
@@ -0,0 +1,39 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.hilt)
alias(libs.plugins.ksp)
}
android {
namespace = "sh.haven.core.knock"
compileSdk = 37
defaultConfig {
minSdk = 26
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
testOptions {
unitTests.isReturnDefaultValues = true
}
}
dependencies {
implementation(libs.coroutines.core)
implementation(libs.coroutines.android)
implementation(libs.hilt.android)
ksp(libs.hilt.compiler)
testImplementation(libs.junit)
testImplementation(libs.coroutines.test)
}
kotlin {
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
}
}
@@ -0,0 +1,15 @@
package sh.haven.core.knock
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
abstract class KnockHiltModule {
@Binds
@Singleton
abstract fun bindPortKnocker(impl: DefaultPortKnocker): PortKnocker
}
@@ -0,0 +1,88 @@
package sh.haven.core.knock
/**
* A single packet to send during port knocking.
*
* `knockd` and friends watch for SYNs (TCP) or datagrams (UDP) on
* specific ports in a specific order; this models one such hit.
*/
data class KnockStep(
val port: Int,
val protocol: Protocol,
) {
enum class Protocol { TCP, UDP }
init {
require(port in 1..65535) { "port out of range: $port" }
}
override fun toString(): String = "$port/${protocol.name.lowercase()}"
}
/**
* Ordered sequence of knock steps plus the gap to wait between them.
* Empty / null user input parses to `null`, which means "knocking
* disabled for this profile".
*/
data class KnockSequence(
val steps: List<KnockStep>,
val interKnockDelayMs: Int,
) {
init {
require(steps.isNotEmpty()) { "empty knock sequence" }
require(interKnockDelayMs in 0..60_000) {
"delay out of range: $interKnockDelayMs"
}
}
/** Render the sequence in the same syntax `parse` accepts. */
fun format(): String = steps.joinToString(" ") { it.toString() }
companion object {
/** Default gap between packets — enough for `knockd`'s default `seq_timeout`. */
const val DEFAULT_DELAY_MS = 100
/**
* Parse a user-supplied knock string.
*
* Format: tokens separated by whitespace and/or commas. Each token is
* either `port` (defaults to TCP) or `port/proto` where `proto` is
* `tcp` or `udp` (case-insensitive).
*
* Returns `Result.success(null)` for blank/null input ("knocking off").
* Returns `Result.failure(IllegalArgumentException)` for any malformed
* token, out-of-range port, or unknown protocol.
*/
fun parse(raw: String?, delayMs: Int = DEFAULT_DELAY_MS): Result<KnockSequence?> {
val trimmed = raw?.trim().orEmpty()
if (trimmed.isEmpty()) return Result.success(null)
return runCatching {
val tokens = trimmed.split(',', ' ', '\t', '\n')
.map { it.trim() }
.filter { it.isNotEmpty() }
require(tokens.isNotEmpty()) { "no knock tokens" }
val steps = tokens.map { parseToken(it) }
KnockSequence(steps, delayMs)
}
}
private fun parseToken(token: String): KnockStep {
val (portPart, protoPart) = when {
'/' in token -> token.substringBefore('/') to token.substringAfter('/')
':' in token -> token.substringBefore(':') to token.substringAfter(':')
else -> token to "tcp"
}
val port = portPart.toIntOrNull()
?: throw IllegalArgumentException("not a port: '$portPart' in '$token'")
require(port in 1..65535) { "port out of range: $port (token '$token')" }
val proto = when (protoPart.trim().lowercase()) {
"tcp" -> KnockStep.Protocol.TCP
"udp" -> KnockStep.Protocol.UDP
else -> throw IllegalArgumentException(
"unknown protocol '$protoPart' in '$token' (expected tcp or udp)"
)
}
return KnockStep(port, proto)
}
}
}
@@ -0,0 +1,100 @@
package sh.haven.core.knock
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.io.IOException
import java.net.ConnectException
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Socket
import java.net.SocketTimeoutException
import javax.inject.Inject
import javax.inject.Singleton
/** Outcome of a knock attempt. Carries the list of steps actually sent and timing. */
data class KnockResult(
val sentSteps: Int,
val totalDurationMs: Long,
val error: Throwable? = null,
) {
val ok: Boolean get() = error == null
}
/**
* Sends a port-knock sequence to a host. Implementations open and immediately
* close raw TCP/UDP sockets to each port in order — the SYN (TCP) or datagram
* (UDP) is what the remote firewall watches for; we don't expect a response.
*
* Failures during knocking are returned in [KnockResult.error] rather than
* thrown, so the caller can decide whether to abort the real connect or
* continue regardless.
*/
interface PortKnocker {
suspend fun knock(host: String, sequence: KnockSequence): KnockResult
}
@Singleton
class DefaultPortKnocker @Inject constructor() : PortKnocker {
/** Per-knock connect attempt — short enough that we don't block the UI on a stale host. */
private val perKnockTimeoutMs = 250
/** Wait after the last packet so the firewall has time to install its rule. */
private val postKnockSettleMs = 200L
override suspend fun knock(host: String, sequence: KnockSequence): KnockResult =
withContext(Dispatchers.IO) {
val started = System.currentTimeMillis()
var sent = 0
try {
val addr = InetAddress.getByName(host)
for ((index, step) in sequence.steps.withIndex()) {
sendOne(addr, step)
sent++
if (index < sequence.steps.lastIndex && sequence.interKnockDelayMs > 0) {
delay(sequence.interKnockDelayMs.toLong())
}
}
delay(postKnockSettleMs)
KnockResult(sent, System.currentTimeMillis() - started)
} catch (t: Throwable) {
KnockResult(sent, System.currentTimeMillis() - started, t)
}
}
private fun sendOne(addr: InetAddress, step: KnockStep) {
when (step.protocol) {
KnockStep.Protocol.TCP -> sendTcp(addr, step.port)
KnockStep.Protocol.UDP -> sendUdp(addr, step.port)
}
}
private fun sendTcp(addr: InetAddress, port: Int) {
val socket = Socket()
try {
socket.connect(InetSocketAddress(addr, port), perKnockTimeoutMs)
} catch (_: SocketTimeoutException) {
// Expected: knockd doesn't accept the connection, the SYN is what matters.
} catch (_: ConnectException) {
// Expected: port is closed, the SYN reached the firewall.
} catch (_: IOException) {
// Other I/O errors (e.g. ECONNRESET) — also fine, the packet went out.
} finally {
try { socket.close() } catch (_: IOException) { /* ignore */ }
}
}
private fun sendUdp(addr: InetAddress, port: Int) {
val socket = DatagramSocket()
try {
// A single zero byte is enough for knockd to register the packet.
val payload = byteArrayOf(0)
socket.send(DatagramPacket(payload, payload.size, addr, port))
} finally {
socket.close()
}
}
}
@@ -0,0 +1,101 @@
package sh.haven.core.knock
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class KnockSequenceTest {
@Test
fun `blank input parses to null - knocking disabled`() {
assertNull(KnockSequence.parse(null).getOrThrow())
assertNull(KnockSequence.parse("").getOrThrow())
assertNull(KnockSequence.parse(" ").getOrThrow())
assertNull(KnockSequence.parse("\t\n").getOrThrow())
}
@Test
fun `space-separated ports default to tcp`() {
val seq = KnockSequence.parse("7000 8000 9000").getOrThrow()
assertNotNull(seq)
assertEquals(
listOf(
KnockStep(7000, KnockStep.Protocol.TCP),
KnockStep(8000, KnockStep.Protocol.TCP),
KnockStep(9000, KnockStep.Protocol.TCP),
),
seq!!.steps,
)
}
@Test
fun `comma-separated ports work`() {
val seq = KnockSequence.parse("7000,8000,9000").getOrThrow()!!
assertEquals(3, seq.steps.size)
assertTrue(seq.steps.all { it.protocol == KnockStep.Protocol.TCP })
}
@Test
fun `mixed whitespace and commas tolerated`() {
val seq = KnockSequence.parse("7000, 8000,9000 , 10000").getOrThrow()!!
assertEquals(listOf(7000, 8000, 9000, 10000), seq.steps.map { it.port })
}
@Test
fun `protocol suffix is honoured`() {
val seq = KnockSequence.parse("7000/tcp 8000/udp 9000/TCP").getOrThrow()!!
assertEquals(KnockStep.Protocol.TCP, seq.steps[0].protocol)
assertEquals(KnockStep.Protocol.UDP, seq.steps[1].protocol)
assertEquals(KnockStep.Protocol.TCP, seq.steps[2].protocol)
}
@Test
fun `colon separator also accepted (knockd style)`() {
val seq = KnockSequence.parse("7000:tcp,8000:udp").getOrThrow()!!
assertEquals(KnockStep.Protocol.TCP, seq.steps[0].protocol)
assertEquals(KnockStep.Protocol.UDP, seq.steps[1].protocol)
}
@Test
fun `delay is carried through`() {
val seq = KnockSequence.parse("7000", delayMs = 250).getOrThrow()!!
assertEquals(250, seq.interKnockDelayMs)
}
@Test
fun `non-numeric port fails`() {
assertTrue(KnockSequence.parse("abc").isFailure)
assertTrue(KnockSequence.parse("7000 abc 9000").isFailure)
}
@Test
fun `port out of range fails`() {
assertTrue(KnockSequence.parse("0").isFailure)
assertTrue(KnockSequence.parse("70000").isFailure)
assertTrue(KnockSequence.parse("-1").isFailure)
}
@Test
fun `unknown protocol fails`() {
val r = KnockSequence.parse("22/sctp")
assertTrue(r.isFailure)
assertTrue(r.exceptionOrNull()?.message?.contains("sctp", ignoreCase = true) == true)
}
@Test
fun `format roundtrips through parse`() {
val original = KnockSequence.parse("7000/tcp 8000/udp 9000/tcp").getOrThrow()!!
val reparsed = KnockSequence.parse(original.format()).getOrThrow()!!
assertEquals(original.steps, reparsed.steps)
}
@Test
fun `negative delay fails construction`() {
val r = runCatching {
KnockSequence(listOf(KnockStep(7000, KnockStep.Protocol.TCP)), -1)
}
assertTrue(r.isFailure)
}
}
@@ -0,0 +1,148 @@
package sh.haven.core.knock
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.ServerSocket
import java.util.concurrent.CopyOnWriteArrayList
class PortKnockerTest {
private val tcpListeners = mutableListOf<ServerSocket>()
private val udpListeners = mutableListOf<DatagramSocket>()
@After
fun tearDown() {
tcpListeners.forEach { runCatching { it.close() } }
udpListeners.forEach { runCatching { it.close() } }
}
@Test
fun `tcp knocks land on every port in the sequence`() = runBlocking {
// We deliberately don't assert the order of the recorded ports —
// each accept() runs in its own coroutine on Dispatchers.IO and
// the relative timing of "kernel hands SYN to listening socket"
// vs "JVM schedules the +=" is not deterministic across hosts
// (CI runners are notably more sensitive than dev machines).
// The knocker's contract is "fire every step in order"; the
// mixed-protocol test below uses one socket per type and covers
// the ordering aspect.
val ports = (1..3).map {
ServerSocket(0).also { tcpListeners += it; it.soTimeout = 2000 }.localPort
}
val acceptedPorts = CopyOnWriteArrayList<Int>()
val accepts = tcpListeners.map { server ->
async(Dispatchers.IO) {
runCatching {
server.accept().use { acceptedPorts += server.localPort }
}
}
}
val sequence = KnockSequence(
ports.map { KnockStep(it, KnockStep.Protocol.TCP) },
interKnockDelayMs = 0,
)
val result = withTimeout(5000) {
DefaultPortKnocker().knock("127.0.0.1", sequence)
}
// Wait for the accept side to finish recording.
withTimeout(2000) { accepts.forEach { it.await() } }
assertNull("knock returned error: ${result.error}", result.error)
assertEquals(ports.size, result.sentSteps)
assertEquals(ports.toSet(), acceptedPorts.toSet())
}
@Test
fun `udp knocks deliver a datagram to every port in the sequence`() = runBlocking {
// Same ordering caveat as the TCP test above.
val sockets = (1..3).map {
DatagramSocket(0).also { udpListeners += it; it.soTimeout = 2000 }
}
val ports = sockets.map { it.localPort }
val received = CopyOnWriteArrayList<Int>()
val receivers = sockets.map { sock ->
async(Dispatchers.IO) {
val buf = ByteArray(16)
val pkt = DatagramPacket(buf, buf.size)
runCatching {
sock.receive(pkt)
received += sock.localPort
}
}
}
val sequence = KnockSequence(
ports.map { KnockStep(it, KnockStep.Protocol.UDP) },
interKnockDelayMs = 0,
)
val result = withTimeout(5000) {
DefaultPortKnocker().knock("127.0.0.1", sequence)
}
withTimeout(2000) { receivers.forEach { it.await() } }
assertNull("knock returned error: ${result.error}", result.error)
assertEquals(ports.size, result.sentSteps)
assertEquals(ports.toSet(), received.toSet())
}
@Test
fun `mixed tcp and udp both delivered`() = runBlocking {
val tcp = ServerSocket(0).also { tcpListeners += it; it.soTimeout = 2000 }
val udp = DatagramSocket(0).also { udpListeners += it; it.soTimeout = 2000 }
val tcpAccepted = async(Dispatchers.IO) {
runCatching { tcp.accept().use { } }.isSuccess
}
val udpReceived = async(Dispatchers.IO) {
val buf = ByteArray(16)
runCatching { udp.receive(DatagramPacket(buf, buf.size)) }.isSuccess
}
val sequence = KnockSequence(
listOf(
KnockStep(tcp.localPort, KnockStep.Protocol.TCP),
KnockStep(udp.localPort, KnockStep.Protocol.UDP),
),
interKnockDelayMs = 0,
)
val result = withTimeout(5000) {
DefaultPortKnocker().knock("127.0.0.1", sequence)
}
assertTrue("tcp not accepted", withTimeout(2000) { tcpAccepted.await() })
assertTrue("udp not received", withTimeout(2000) { udpReceived.await() })
assertNull(result.error)
assertEquals(2, result.sentSteps)
}
@Test
fun `unresolvable host returns error in result, does not throw`() = runBlocking {
val sequence = KnockSequence(
listOf(KnockStep(7000, KnockStep.Protocol.TCP)),
interKnockDelayMs = 0,
)
val result = withContext(Dispatchers.IO) {
DefaultPortKnocker().knock(
"no-such-host.invalid.example.test.haven.local-fail",
sequence,
)
}
assertTrue("expected error for unresolvable host, got $result", !result.ok)
assertEquals(0, result.sentSteps)
}
}