提交 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
@@ -0,0 +1,36 @@
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.hilt)
alias(libs.plugins.ksp)
}
android {
namespace = "sh.haven.core.reticulum"
compileSdk = 37
defaultConfig {
minSdk = 26
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
dependencies {
implementation(project(":core:redact"))
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,254 @@
package sh.haven.core.reticulum
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.IOException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.ServerSocket
import java.net.Socket
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
private const val TAG = "ReticulumForward"
/**
* Tunnels local TCP ports through an rnsh destination, giving Reticulum the
* `ssh -L` / `ssh -D` surface SSH already has — but over the mesh. Each
* accepted TCP connection opens its own exec Link running `nc <host> <port>`
* on the remote and bridges the socket to that command's stdin/stdout.
*
* The remote only needs `nc` (busybox `nc <host> <port>` is outbound-capable,
* which is all a forward requires). No listener-side software beyond a shell
* and netcat.
*
* Supports:
* - Local forward (`-L`): localhost:bind → remote `nc target:port`.
* - Dynamic forward (`-D`): a SOCKS5 (CONNECT, no-auth) proxy whose every
* CONNECT spawns `nc <requested host:port>` on the remote.
*
* Not supported (v1): remote forward (`-R`), SOCKS BIND/UDP, SOCKS auth.
*/
@Singleton
class ReticulumForwardServer @Inject constructor(
private val transport: ReticulumTransport,
) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private data class Forward(val bindPort: Int, val socket: ServerSocket, val job: Job)
/** profileId → its active listeners. */
private val forwards = ConcurrentHashMap<String, MutableList<Forward>>()
/**
* Start a local forward. Returns the actually-bound port (useful when
* [bindPort] is 0). The remote target is reached via `nc`.
*/
fun startLocalForward(
profileId: String,
destinationHash: String,
bindAddress: String,
bindPort: Int,
targetHost: String,
targetPort: Int,
): Int = startListener(profileId, bindAddress, bindPort) { client ->
bridge(destinationHash, targetHost, targetPort, client)
}
/**
* Start a dynamic (SOCKS5) forward. Returns the actually-bound port.
*/
fun startDynamicForward(
profileId: String,
destinationHash: String,
bindAddress: String,
bindPort: Int,
): Int = startListener(profileId, bindAddress, bindPort) { client ->
val dest = socks5Handshake(client) ?: return@startListener
bridge(destinationHash, dest.first, dest.second, client)
}
/** Stop a single forward by its bound port. */
fun stopForward(profileId: String, bindPort: Int) {
forwards[profileId]?.let { list ->
list.removeAll { f ->
if (f.bindPort == bindPort) {
f.job.cancel()
runCatching { f.socket.close() }
true
} else false
}
}
}
/** Stop every forward for a profile (called on disconnect). */
fun stopAllForProfile(profileId: String) {
forwards.remove(profileId)?.forEach { f ->
f.job.cancel()
runCatching { f.socket.close() }
}
}
/** Stop everything (called on Disconnect All / service shutdown). */
fun stopAll() {
forwards.keys.toList().forEach { stopAllForProfile(it) }
}
/** Active bound ports for a profile (for the live-tunnels surface). */
fun activePorts(profileId: String): List<Int> =
forwards[profileId]?.map { it.bindPort } ?: emptyList()
// --- internals -------------------------------------------------------
private fun startListener(
profileId: String,
bindAddress: String,
bindPort: Int,
handle: suspend (Socket) -> Unit,
): Int {
val ss = ServerSocket()
ss.reuseAddress = true
ss.bind(InetSocketAddress(bindAddress, bindPort))
val bound = ss.localPort
Log.i(TAG, "forward listening on $bindAddress:$bound (profile=$profileId)")
val job = scope.launch {
while (isActive) {
val client = try {
withContext(Dispatchers.IO) { ss.accept() }
} catch (_: IOException) {
break // socket closed on shutdown
}
launch {
try { handle(client) }
catch (e: Exception) { Log.w(TAG, "connection handler failed", e) }
finally { runCatching { client.close() } }
}
}
Log.i(TAG, "forward accept loop on $bound exited")
}
forwards.getOrPut(profileId) { mutableListOf() }.add(Forward(bound, ss, job))
return bound
}
/**
* Bridge a client socket to a remote `nc host port` over an exec Link,
* with half-close semantics (#208): a client EOF sends stdin EOF to nc
* but keeps reading the remote's response until nc closes.
*/
private suspend fun bridge(destinationHash: String, host: String, port: Int, client: Socket) {
val exec = transport.execCommand(destinationHash, listOf("nc", host, port.toString()))
try {
coroutineScope {
val cout = client.getOutputStream()
val cin = client.getInputStream()
// Downstream: remote stdout → client.
val down = launch {
try {
exec.stdout.collect { cout.write(it); cout.flush() }
} catch (_: Exception) { /* torn down */ }
finally { runCatching { client.shutdownOutput() } }
}
// Upstream: client → remote stdin, chunked under the link MDU.
try {
val buf = ByteArray(STDIN_CHUNK)
while (true) {
val n = withContext(Dispatchers.IO) { cin.read(buf) }
if (n < 0) break
exec.writeStdin(buf.copyOf(n))
}
} catch (_: Exception) { /* torn down */ }
// Client half-closed. Ideally we'd send a stdin EOF to nc here,
// but a stdin-EOF over rnsh currently stalls the exec — so we
// skip it and let the link teardown (below) stop nc. Keeps the
// tunnel working for interactive/keep-alive protocols; degrades
// half-close-dependent ones (e.g. `nc -N`, HTTP/1.0-close).
down.join()
}
} finally {
runCatching { exec.close() }
runCatching { client.close() }
}
}
/**
* Minimal SOCKS5 handshake (no-auth, CONNECT only). Returns the requested
* destination (host, port), or null on any protocol error (socket is left
* for the caller's `finally` to close).
*/
private fun socks5Handshake(client: Socket): Pair<String, Int>? {
client.soTimeout = 30_000
val input = DataInputStream(client.getInputStream())
val output = DataOutputStream(client.getOutputStream())
val dest = parseSocks5Connect(input, output) ?: return null
client.soTimeout = 0 // long-lived tunnels sit idle
return dest
}
/**
* Pure SOCKS5 (no-auth, CONNECT) byte handshake over the given streams.
* Returns the requested (host, port) or null on any protocol error.
* Extracted from the socket path so it is unit-testable.
*/
internal fun parseSocks5Connect(
input: DataInputStream,
output: DataOutputStream,
): Pair<String, Int>? {
if (input.readUnsignedByte() != 5) return null
val nmethods = input.readUnsignedByte()
val methods = ByteArray(nmethods); input.readFully(methods)
if (methods.none { it.toInt() == 0x00 }) {
output.write(byteArrayOf(0x05, 0xFF.toByte())); output.flush(); return null
}
output.write(byteArrayOf(0x05, 0x00)); output.flush()
val ver = input.readUnsignedByte()
val cmd = input.readUnsignedByte()
input.readUnsignedByte() // RSV
val atyp = input.readUnsignedByte()
if (ver != 5 || cmd != 1) { socksReply(output, 0x07); return null }
val host = when (atyp) {
0x01 -> { val a = ByteArray(4); input.readFully(a); InetAddress.getByAddress(a).hostAddress ?: "0.0.0.0" }
0x03 -> { val len = input.readUnsignedByte(); val n = ByteArray(len); input.readFully(n); String(n, Charsets.US_ASCII) }
0x04 -> { val a = ByteArray(16); input.readFully(a); InetAddress.getByAddress(a).hostAddress ?: "::" }
else -> { socksReply(output, 0x08); return null }
}
val port = input.readUnsignedShort()
// Optimistic success — we can't know nc connected until bytes flow,
// but SOCKS clients tolerate this and it avoids a round-trip probe.
socksReply(output, 0x00)
return host to port
}
private fun socksReply(output: DataOutputStream, rep: Int) {
output.write(byteArrayOf(0x05, rep.toByte(), 0x00, 0x01, 0, 0, 0, 0, 0, 0))
output.flush()
}
fun shutdown() {
stopAll()
scope.cancel()
}
companion object {
/** Max stdin chunk per stream-data message (stays under the link MDU). */
private const val STDIN_CHUNK = 400
}
}
@@ -0,0 +1,124 @@
package sh.haven.core.reticulum
import android.util.Log
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.catch
import java.io.Closeable
private const val TAG = "ReticulumSession"
/**
* Bridges an rnsh shell session to a terminal emulator.
*
* Parallel to [sh.haven.core.ssh.TerminalSession]. Consumes the
* [RnshShellSession] Flow-based output and delivers data via
* [onDataReceived].
*/
class ReticulumSession(
val sessionId: String,
val profileId: String,
val label: String,
private val shellSession: RnshShellSession,
private val onDataReceived: (ByteArray, Int, Int) -> Unit,
private val onDisconnected: ((cleanExit: Boolean) -> Unit)? = null,
) : Closeable {
@Volatile
private var closed = false
private val scope = CoroutineScope(
SupervisorJob() + Dispatchers.IO + CoroutineName("rns-session-$sessionId")
)
/**
* Start collecting output from the shell session.
* Call after the session has been opened via [ReticulumTransport.openSession].
*/
fun start() {
// Collect output flow
scope.launch {
shellSession.output
.catch { e ->
if (!closed) {
Log.e(TAG, "Output flow error for $sessionId", e)
}
}
.collect { data ->
if (!closed && data.isNotEmpty()) {
onDataReceived(data, 0, data.size)
}
}
// Flow completed — session disconnected
if (!closed) {
Log.d(TAG, "Output flow ended for $sessionId")
onDisconnected?.invoke(true)
}
}
// Watch for exit code
scope.launch {
try {
val code = shellSession.exitCode.await()
Log.d(TAG, "Session $sessionId exited with code $code")
if (!closed) {
onDisconnected?.invoke(code == 0)
}
} catch (e: Exception) {
if (!closed) {
Log.e(TAG, "Exit code error for $sessionId", e)
onDisconnected?.invoke(false)
}
}
}
}
/**
* Send keyboard input to the remote shell.
* Safe to call from any thread.
*/
fun sendInput(data: ByteArray) {
if (closed) return
Log.d(TAG, "sendInput: ${data.size} bytes, session=$sessionId")
scope.launch {
try {
shellSession.sendInput(data)
Log.d(TAG, "sendInput: delivered ${data.size} bytes")
} catch (e: Exception) {
Log.e(TAG, "sendInput failed", e)
}
}
}
fun resize(cols: Int, rows: Int) {
if (closed) return
scope.launch {
try {
shellSession.resize(rows, cols)
} catch (e: Exception) {
Log.e(TAG, "resize failed", e)
}
}
}
/**
* Detach without closing the underlying rnsh session.
* Stops collecting output but leaves the session alive.
*/
fun detach() {
if (closed) return
closed = true
scope.cancel()
}
override fun close() {
if (closed) return
closed = true
scope.cancel()
try {
shellSession.close()
} catch (e: Exception) {
Log.e(TAG, "close failed", e)
}
}
}
@@ -0,0 +1,347 @@
package sh.haven.core.reticulum
import android.util.Log
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import java.util.UUID
import javax.inject.Inject
import javax.inject.Singleton
import sh.haven.core.redact.LogRedact
private const val TAG = "ReticulumSessionManager"
/**
* Manages active Reticulum/rnsh sessions across the app.
* Parallel to [sh.haven.core.ssh.SshSessionManager] but without
* reconnect, SFTP, or session manager (tmux/zellij) logic.
*
* Uses the coroutines-first [ReticulumTransport] interface backed by
* the native rnsh-kt bridge.
*/
@Singleton
class ReticulumSessionManager @Inject constructor(
private val transport: ReticulumTransport,
private val forwardServer: ReticulumForwardServer,
) {
data class SessionState(
val sessionId: String,
val profileId: String,
val label: String,
val status: Status,
val destinationHash: String,
val reticulumSession: ReticulumSession? = null,
val sftpSession: sh.haven.core.reticulum.sftp.ReticulumSftpSession? = null,
) {
enum class Status { CONNECTING, CONNECTED, DISCONNECTED, ERROR }
}
private val _sessions = MutableStateFlow<Map<String, SessionState>>(emptyMap())
val sessions: StateFlow<Map<String, SessionState>> = _sessions.asStateFlow()
private val scope = CoroutineScope(
SupervisorJob() + Dispatchers.IO + CoroutineName("rns-session-mgr")
)
val activeSessions: List<SessionState>
get() = _sessions.value.values.filter {
it.status == SessionState.Status.CONNECTED ||
it.status == SessionState.Status.CONNECTING
}
/**
* Register a new session. Returns the generated sessionId.
*/
fun registerSession(profileId: String, label: String, destinationHash: String): String {
val sessionId = UUID.randomUUID().toString()
_sessions.update { map ->
map + (sessionId to SessionState(
sessionId = sessionId,
profileId = profileId,
label = label,
status = SessionState.Status.CONNECTING,
destinationHash = destinationHash,
))
}
return sessionId
}
/**
* Connect a registered session. Suspend function — call from a
* coroutine on Dispatchers.IO or similar.
*
* Initialises Reticulum if needed, resolves the destination, creates
* a shell session. Throws on failure.
*/
suspend fun connectSession(
sessionId: String,
configDir: String,
host: String,
port: Int,
ifacNetname: String? = null,
ifacNetkey: String? = null,
socketDialer: ((String, Int, Int) -> java.net.Socket)? = null,
) {
val session = _sessions.value[sessionId]
?: throw IllegalStateException("Session $sessionId not found")
// A failure here must be visible in the sessions StateFlow, not only
// in the thrown exception. `registerSession` marks the entry CONNECTING
// and `activeSessions` counts CONNECTING, so a session whose connect
// throws without updating status stays a permanent ghost: it is
// rendered as a live tab and keeps the stack-shutdown idle check from
// firing (#601, where a failed duplicate-tab connect "is still counted
// as active"). The catch rethrows so callers keep their current
// handling; ConnectionsViewModel's removeSession-on-error then also
// finds the session in ERROR rather than CONNECTING.
val identityHash: String
val shellSession: RnshShellSession
try {
Log.w(TAG, "initReticulum: host=${LogRedact.of(host)} port=$port ifac=${ifacNetname != null} tunnel=${socketDialer != null}")
// Init Reticulum (idempotent — safe to call multiple times)
identityHash = transport.init(configDir, host, port, ifacNetname, ifacNetkey, socketDialer)
Log.w(TAG, "initReticulum OK, identity=$identityHash")
// Open shell session (resolves destination + Link + handshake)
Log.w(TAG, "Opening session to ${session.destinationHash}...")
shellSession = transport.openSession(
destinationHash = session.destinationHash,
)
} catch (e: Exception) {
updateStatus(sessionId, SessionState.Status.ERROR)
throw e
}
// Stash the shell session BEFORE publishing CONNECTED. The sessions
// StateFlow drives TerminalViewModel.syncSessions, whose RNS branch
// calls createTerminalSession exactly once per emission and `continue`s
// on null — so an observer that sees CONNECTED must already be able to
// find the shell, or the tab is never created and the session lingers
// CONNECTED with no terminal (the #601 "no tab, but counted as active"
// ghost). Updating after the stash makes "CONNECTED ⇒ shell available"
// hold for every observer.
shellSessions[sessionId] = shellSession
_sessions.update { map ->
val existing = map[sessionId] ?: return@update map
map + (sessionId to existing.copy(
status = SessionState.Status.CONNECTED,
))
}
Log.w(TAG, "Session $sessionId connected")
}
// Temporary stash for shell sessions between connect and terminal creation
private val shellSessions = mutableMapOf<String, RnshShellSession>()
/**
* Create a [ReticulumSession] for a connected session.
* Returns the session, or null if not ready.
*/
fun createTerminalSession(
sessionId: String,
onDataReceived: (ByteArray, Int, Int) -> Unit,
): ReticulumSession? {
val session = _sessions.value[sessionId] ?: return null
if (session.status != SessionState.Status.CONNECTED) {
Log.w(TAG, "createTerminalSession($sessionId): not attached, status=${session.status}")
return null
}
if (session.reticulumSession != null) {
Log.w(TAG, "createTerminalSession($sessionId): not attached, terminal already present")
return null
}
val shellSession = shellSessions.remove(sessionId)
if (shellSession == null) {
// #601: the CONNECTED-with-no-tab ghost lands here. Log.w (not d)
// so the reason survives the release build's log stripping — the
// reporter's log showed a fully-connected duplicate and nothing
// explaining the missing tab.
Log.w(TAG, "createTerminalSession($sessionId): not attached, no stashed shell session")
return null
}
val reticulumSession = ReticulumSession(
sessionId = sessionId,
profileId = session.profileId,
label = session.label,
shellSession = shellSession,
onDataReceived = onDataReceived,
onDisconnected = { _ ->
Log.d(TAG, "Session $sessionId disconnected")
updateStatus(sessionId, SessionState.Status.DISCONNECTED)
},
)
_sessions.update { map ->
val existing = map[sessionId] ?: return@update map
map + (sessionId to existing.copy(reticulumSession = reticulumSession))
}
return reticulumSession
}
/**
* Detach a terminal session without closing the underlying rnsh session.
*/
fun detachTerminalSession(sessionId: String) {
val session = _sessions.value[sessionId] ?: return
session.reticulumSession?.detach()
_sessions.update { map ->
val existing = map[sessionId] ?: return@update map
map + (sessionId to existing.copy(reticulumSession = null))
}
}
fun isReadyForTerminal(sessionId: String): Boolean {
val session = _sessions.value[sessionId] ?: return false
return session.status == SessionState.Status.CONNECTED &&
session.reticulumSession == null
}
fun updateStatus(sessionId: String, status: SessionState.Status) {
_sessions.update { map ->
val existing = map[sessionId] ?: return@update map
map + (sessionId to existing.copy(status = status))
}
}
fun removeSession(sessionId: String) {
val session = _sessions.value[sessionId] ?: return
_sessions.update { it - sessionId }
shellSessions.remove(sessionId)
// Tear down any port forwards if this was the profile's last session.
if (_sessions.value.values.none { it.profileId == session.profileId }) {
forwardServer.stopAllForProfile(session.profileId)
}
scope.launch {
try {
session.reticulumSession?.close()
session.sftpSession?.close()
} catch (e: Exception) {
Log.e(TAG, "tearDown failed for $sessionId", e)
}
shutdownStackIfIdle()
}
}
/** Send [text] as UTF-8 to the rnsh session's input — sendInput contract, see #366. */
fun sendInput(sessionId: String, text: String) {
val session = _sessions.value[sessionId]
?: throw IllegalStateException("No Reticulum session: $sessionId")
val rns = session.reticulumSession
?: throw IllegalStateException("Reticulum session $sessionId has no live transport")
rns.sendInput(text.toByteArray(Charsets.UTF_8))
}
fun removeAllSessionsForProfile(profileId: String) {
val toRemove = _sessions.value.values.filter { it.profileId == profileId }
_sessions.update { map -> map.filterValues { it.profileId != profileId } }
forwardServer.stopAllForProfile(profileId)
scope.launch {
toRemove.forEach { session ->
try {
session.reticulumSession?.close()
session.sftpSession?.close()
} catch (e: Exception) {
Log.e(TAG, "tearDown failed for ${session.sessionId}", e)
}
}
shutdownStackIfIdle()
}
}
fun disconnectAll() {
val snapshot = _sessions.value.values.toList()
_sessions.update { emptyMap() }
shellSessions.clear()
forwardServer.stopAll()
scope.launch {
snapshot.forEach { session ->
try {
session.reticulumSession?.close()
session.sftpSession?.close()
} catch (e: Exception) {
Log.e(TAG, "tearDown failed for ${session.sessionId}", e)
}
}
shutdownStackIfIdle()
}
}
/**
* Drop the process-wide Reticulum stack once nothing is using it.
*
* The stack is a process singleton whose mode is fixed at start-up: a
* shared instance owns the interfaces on behalf of every app using it, so
* a gateway profile cannot add to one (#588). Nothing used to release it,
* so that choice outlived the session that made it and the next connect
* was refused until the app was force-stopped. Reported against v5.87.59:
* "the banner keeps appearing even after disconnecting the session and
* just closing Haven makes possible to choose again".
*
* Re-reading [_sessions] here rather than trusting the caller's snapshot
* narrows, but does not close, the race with a connect that starts while
* this is in flight; both run on [scope]'s IO dispatcher with no lock
* between them.
*/
private suspend fun shutdownStackIfIdle() {
if (_sessions.value.isNotEmpty()) return
try {
transport.closeAll()
Log.d(TAG, "last session gone: Reticulum stack shut down")
} catch (e: Exception) {
Log.e(TAG, "stack shutdown failed", e)
}
}
fun getSessionsForProfile(profileId: String): List<SessionState> =
_sessions.value.values.filter { it.profileId == profileId }
fun isProfileConnected(profileId: String): Boolean =
_sessions.value.values.any {
it.profileId == profileId && it.status == SessionState.Status.CONNECTED
}
/**
* Lazily open (or reuse) a persistent SFTP session for [profileId] over the
* profile's connected Link, mirroring SSH's `openSftpSession`. The actual
* `sftp-server` Link + handshake happen on first file op, not here. Returns
* null if the profile has no CONNECTED session. Synchronized so concurrent
* resolvers don't double-open.
*/
@Synchronized
fun openSftpSessionForProfile(
profileId: String,
sftpServerPath: String,
): sh.haven.core.reticulum.sftp.ReticulumSftpSession? {
val state = _sessions.value.values.firstOrNull {
it.profileId == profileId && it.status == SessionState.Status.CONNECTED
} ?: return null
state.sftpSession?.let { return it }
val session = sh.haven.core.reticulum.sftp.ReticulumSftpSession(
transport, state.destinationHash, sftpServerPath,
)
_sessions.update { map ->
val cur = map[state.sessionId] ?: return@update map
map + (state.sessionId to cur.copy(sftpSession = session))
}
return session
}
fun getProfileStatus(profileId: String): SessionState.Status? {
val statuses = _sessions.value.values
.filter { it.profileId == profileId }
.map { it.status }
if (statuses.isEmpty()) return null
return when {
SessionState.Status.CONNECTED in statuses -> SessionState.Status.CONNECTED
SessionState.Status.CONNECTING in statuses -> SessionState.Status.CONNECTING
SessionState.Status.ERROR in statuses -> SessionState.Status.ERROR
else -> SessionState.Status.DISCONNECTED
}
}
}
@@ -0,0 +1,209 @@
package sh.haven.core.reticulum
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
/**
* Coroutines-first interface for Reticulum/rnsh transport.
*
* Backed by [NativeReticulumTransport] (rnsh-kt + reticulum-kt).
* Collapses the session lifecycle into a single [openSession] call
* that resolves the destination, establishes the Link, performs the
* version handshake, and returns a [RnshShellSession].
*/
interface ReticulumTransport {
/**
* Initialise Reticulum. Call before any other method.
*
* @param configDir Writable directory for RNS config/identity storage
* @param host Shared-instance or gateway host
* @param port Shared-instance or gateway TCP port
* @param ifacNetname IFAC network name for gateway isolation (optional)
* @param ifacNetkey IFAC passphrase for gateway isolation (optional)
* @param socketDialer Optional `(host, port, timeoutMs) -> Socket`
* used by the gateway TCP interface in place of a direct kernel
* dial. Routes Reticulum's TCP transport through a userspace
* tunnel (WireGuard / Tailscale) or SOCKS/HTTP proxy when the
* connection profile selects one (#149). Ignored in shared-
* instance mode where the local Sideband daemon owns the socket.
* @return Haven's RNS identity hash (hex)
*/
suspend fun init(
configDir: String,
host: String = "127.0.0.1",
port: Int = 37428,
ifacNetname: String? = null,
ifacNetkey: String? = null,
socketDialer: ((String, Int, Int) -> java.net.Socket)? = null,
): String
/** Whether Reticulum has been initialised. */
val isInitialised: Boolean
/**
* Open a shell session to an rnsh destination.
* Resolves the destination, establishes a Link, performs the version
* handshake, and requests command execution.
*
* @param destinationHash Hex-encoded rnsh destination hash
* @param rows Terminal rows
* @param cols Terminal columns
* @return A live shell session
* @throws Exception if resolution, Link, or handshake fails
*/
suspend fun openSession(
destinationHash: String,
rows: Int = 24,
cols: Int = 80,
): RnshShellSession
/**
* Run a single command on an rnsh destination in pipe mode (no PTY),
* over its own Link, with stdout and stderr demultiplexed and an exit
* code. The substrate for file transfer and port forwarding over the
* mesh — see [ReticulumExecSession].
*
* Reticulum must already be initialised (typically by an open shell
* [openSession] to the same destination); the path is reused.
*
* @param destinationHash Hex-encoded rnsh destination hash
* @param command argv to run; use `listOf("sh", "-c", script)` for shell
* features (redirection, pipes, globbing)
* @throws Exception if resolution, Link, or handshake fails
*/
suspend fun execCommand(
destinationHash: String,
command: List<String>,
): ReticulumExecSession
/** Discovered rnsh destinations, sorted by hop count. */
val discoveredDestinations: StateFlow<List<DiscoveredDestination>>
/**
* Request a path to a destination. Non-blocking — returns true if
* path is already known, false if a request was sent.
*/
suspend fun requestPath(destinationHashHex: String): Boolean
/** Probe for Sideband's shared instance. Safe to call repeatedly. */
suspend fun probeSideband(configDir: String): Boolean
/**
* The rnsh client identity hash this device presents, or null if none has
* been created yet.
*
* Reads the stored key; it does not start the stack, so it is safe to call
* from a settings or connection screen before anything is connected.
*/
suspend fun clientIdentityHash(configDir: String): String?
/**
* Install a Reticulum identity the user supplies as this device's client
* identity (#585).
*
* The identity a server whitelists is a private key, so it can only be
* moved as a file — there is no way to adopt one from its hash, which is a
* fingerprint of the key rather than the key itself.
*
* Nothing is replaced unless [source] parses, and the key being replaced is
* kept so a mistaken import can be undone.
*/
suspend fun importClientIdentity(configDir: String, source: java.io.File): ReticulumIdentityImport
/** Close all sessions and shut down. */
suspend fun closeAll()
}
/** Outcome of [ReticulumTransport.importClientIdentity] (#585). */
sealed interface ReticulumIdentityImport {
/**
* The file parsed and is now the stored client identity.
*
* [replacedHexHash] is the hash that was in use before, or null if there was
* none. [takesEffectAfterRestart] is true when Reticulum is already running:
* the stack reads the identity once at start-up, so live sessions and any
* link opened before a restart still present the old one.
*/
data class Installed(
val hexHash: String,
val replacedHexHash: String?,
val takesEffectAfterRestart: Boolean,
) : ReticulumIdentityImport
/** The source is missing, unreadable, or not a Reticulum identity. */
data class NotAnIdentity(val reason: String) : ReticulumIdentityImport
/** The source parsed but could not be installed. The old identity is intact. */
data class InstallFailed(val reason: String) : ReticulumIdentityImport
}
/**
* A live rnsh shell session.
*/
interface RnshShellSession : AutoCloseable {
val sessionId: String
/** Stdout and stderr data as received from the remote shell. */
val output: Flow<ByteArray>
/** Completes when the remote command exits. Value is the exit code. */
val exitCode: CompletableDeferred<Int>
/** Whether the session is still connected. */
val isConnected: Boolean
/** Send keyboard input (stdin) to the remote shell. */
suspend fun sendInput(data: ByteArray)
/** Send a window resize to the remote PTY. */
suspend fun resize(rows: Int, cols: Int)
/** Close the session. */
override fun close()
}
/**
* A live rnsh command-exec session: a single remote command run in pipe
* mode (no PTY) over its own Link, with stdout and stderr demultiplexed and
* an exit code.
*
* stdout/stderr are reliable, single-consumer flows that complete when the
* command exits; bytes are not dropped (unlike the terminal's lossy output).
*/
interface ReticulumExecSession : AutoCloseable {
/** Stdout bytes from the remote process. Single consumer; completes on exit. */
val stdout: Flow<ByteArray>
/** Stderr bytes from the remote process. Single consumer; completes on exit. */
val stderr: Flow<ByteArray>
/**
* Completes with the exit code the rnsh listener reports.
*
* Caveat: some rnsh listeners (incl. current markqvist/rnsh) report 0
* for every non-signal exit (a `& 0xff` waitpid-masking bug), so this
* value cannot distinguish success from failure. Callers needing a
* reliable status should embed `$?` in the command output.
*/
val exitCode: CompletableDeferred<Int>
/** Write bytes to the remote process's stdin. */
suspend fun writeStdin(data: ByteArray)
/** Signal EOF on the remote process's stdin. */
suspend fun closeStdin()
/** Tear down the session and close the underlying Link. */
override fun close()
}
/**
* An rnsh destination discovered via announce.
*/
data class DiscoveredDestination(
val hash: String,
val hops: Int,
val lastSeen: Long = System.currentTimeMillis(),
)
@@ -0,0 +1,254 @@
package sh.haven.core.reticulum.sftp
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import sh.haven.core.reticulum.ReticulumTransport
import java.io.ByteArrayOutputStream
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
import java.io.PipedInputStream
import java.io.PipedOutputStream
/**
* A persistent SFTP session over one Reticulum Link: it exec's `sftp-server`
* once (lazily) and speaks SFTP v3 to it via [SftpV3Client]. All file ops
* share the one Link — no per-op handshake (the throughput win over
* `ReticulumFileBackend`, which opens a fresh Link per command).
*
* Held per-profile in `ReticulumSessionManager.SessionState` and torn down with
* it. Exposes the [SftpEntry]-shaped surface the `feature/sftp` adapter maps to
* the browser's entry type (this module can't depend on `feature/sftp`).
*
* Improvements over the exec backend: real mtime / owner / group / permissions
* from SFTP ATTRS, and true `openInputStream(offset > 0)` (SFTP READ is seekable).
*/
class ReticulumSftpSession(
private val transport: ReticulumTransport,
private val destinationHash: String,
private val sftpServerPath: String,
) {
/** One directory/stat entry, mapped to the browser's `SftpEntry` by the adapter. */
data class Entry(
val name: String,
val path: String,
val isDirectory: Boolean,
val size: Long,
val modifiedTime: Long,
val permissions: String,
val owner: String,
val group: String,
)
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val clientMutex = Mutex()
@Volatile private var client: SftpV3Client? = null
private suspend fun client(): SftpV3Client {
client?.let { if (!it.isClosed) return it }
return clientMutex.withLock {
client?.let { if (!it.isClosed) return it }
// Exec sftp-server directly (binary subsystem, no shell). NOTE: the
// markqvist rnsh listener echoes our stdin back onto stdout even in
// all-pipe mode (process.py: "forward input immediately for
// visibility"), interleaved with the server's responses;
// SftpV3Client strips that echo. See the echo-handling there.
val exec = transport.execCommand(destinationHash, listOf(sftpServerPath))
val c = SftpV3Client(exec)
try {
c.handshake()
} catch (e: Exception) {
c.close()
throw IOException("sftp-server handshake failed ($sftpServerPath): ${e.message}", e)
}
client = c
c
}
}
suspend fun list(path: String): List<Entry> {
val dir = if (path.isBlank()) "/" else path.trimEnd('/').ifEmpty { "/" }
val c = client()
val handle = c.openDir(dir)
val names = ArrayList<SftpV3Codec.SftpName>()
try {
while (true) {
val batch = c.readDir(handle) ?: break
names.addAll(batch)
}
} finally {
c.closeHandle(handle)
}
val entries = ArrayList<Entry>(names.size)
val symlinks = ArrayList<Int>()
for (n in names) {
if (n.filename == "." || n.filename == "..") continue
val full = join(dir, n.filename)
entries.add(n.toEntry(full))
if (n.attrs.isSymlink) symlinks.add(entries.size - 1)
}
// Resolve symlink-to-directory so they navigate (mirror SftpTransport.list).
for (i in symlinks) {
val e = entries[i]
try {
val target = c.stat(e.path)
if (target.isDirectory) entries[i] = e.copy(isDirectory = true)
} catch (_: Exception) { /* dangling symlink — leave as file */ }
}
return entries
}
suspend fun stat(path: String): Entry {
val attrs = client().stat(path)
val name = path.trimEnd('/').substringAfterLast('/').ifEmpty { path }
return attrs.toEntry(name, path, longname = null)
}
suspend fun readBytes(path: String): ByteArray {
val c = client()
val handle = c.openRead(path)
val out = ByteArrayOutputStream()
try {
var offset = 0L
while (true) {
val chunk = c.read(handle, offset, READ_CHUNK) ?: break
if (chunk.isEmpty()) break
out.write(chunk); offset += chunk.size
}
} finally {
c.closeHandle(handle)
}
return out.toByteArray()
}
/** Streaming read from [offset] (SFTP READ is seekable — unlike the exec backend). */
suspend fun openInputStream(path: String, offset: Long): InputStream {
val c = client()
val handle = c.openRead(path)
val pipeIn = PipedInputStream(64 * 1024)
val pipeOut = PipedOutputStream(pipeIn)
scope.launch {
var pos = offset
try {
while (true) {
val chunk = c.read(handle, pos, READ_CHUNK) ?: break
if (chunk.isEmpty()) break
pipeOut.write(chunk); pos += chunk.size
}
pipeOut.flush()
} catch (e: Throwable) {
Log.w(TAG, "openInputStream pump failed for $path", e)
} finally {
runCatching { pipeOut.close() }
c.closeHandle(handle)
}
}
return pipeIn
}
suspend fun writeBytes(path: String, data: ByteArray) {
val c = client()
val handle = c.openWrite(path)
try {
var off = 0
// SFTP WRITE supports a zero-length write to create an empty file.
do {
val n = minOf(WRITE_CHUNK, data.size - off)
c.write(handle, off.toLong(), data, off, n)
off += n
} while (off < data.size)
} finally {
c.closeHandle(handle)
}
}
/** `mkdir -p`: create missing parents; an existing directory is a no-op. */
suspend fun mkdir(path: String) {
val c = client()
val parts = path.trim('/').split('/').filter { it.isNotEmpty() }
var cur = ""
for (p in parts) {
cur += "/$p"
try {
val a = c.stat(cur)
if (!a.isDirectory) throw IOException("$cur exists and is not a directory")
} catch (_: FileNotFoundException) {
c.mkdir(cur)
}
}
}
suspend fun rename(from: String, to: String) = client().rename(from, to)
/** Recursive delete (the FileBackend contract). Symlinks are removed, not followed. */
suspend fun delete(path: String) {
val c = client()
val attrs = try { c.lstat(path) } catch (e: FileNotFoundException) { return }
if (attrs.isDirectory && !attrs.isSymlink) {
val handle = c.openDir(path)
val children = ArrayList<String>()
try {
while (true) {
val batch = c.readDir(handle) ?: break
for (n in batch) if (n.filename != "." && n.filename != "..") children.add(join(path, n.filename))
}
} finally {
c.closeHandle(handle)
}
for (child in children) delete(child)
c.rmdir(path)
} else {
c.remove(path)
}
}
fun close() {
client?.close()
client = null
scope.cancel()
}
// ---- mapping helpers -------------------------------------------------
private fun SftpV3Codec.SftpName.toEntry(fullPath: String): Entry =
attrs.toEntry(filename, fullPath, longname)
private fun SftpV3Codec.SftpAttrs.toEntry(name: String, fullPath: String, longname: String?): Entry {
// owner/group: parse the ls -l-style longname if present (OpenSSH gives
// real names), else fall back to the numeric uid/gid from ATTRS.
var owner = uid.toString()
var group = gid.toString()
if (longname != null) {
val cols = longname.trim().split(Regex("\\s+"))
if (cols.size >= 4 && cols[0].length == 10) { owner = cols[2]; group = cols[3] }
}
return Entry(
name = name,
path = fullPath,
isDirectory = isDirectory,
size = size,
// SftpEntry.modifiedTime is epoch SECONDS (the browser formatter does
// *1000, matching SSH/SCP); SFTP v3 mtime is already epoch seconds.
// Passing millis here produced year-58384 dates.
modifiedTime = modifiedTimeSeconds,
permissions = permString(),
owner = owner,
group = group,
)
}
private fun join(dir: String, name: String): String =
if (dir == "/" || dir.isEmpty()) "/$name" else "${dir.trimEnd('/')}/$name"
companion object {
private const val TAG = "ReticulumSftpSession"
private const val READ_CHUNK = 32 * 1024
private const val WRITE_CHUNK = 16 * 1024
}
}
@@ -0,0 +1,254 @@
package sh.haven.core.reticulum.sftp
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withTimeout
import sh.haven.core.reticulum.ReticulumExecSession
import sh.haven.core.reticulum.sftp.SftpV3Codec.SftpPacket
import java.io.IOException
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
/**
* An SFTP v3 client driven over a single [ReticulumExecSession] (an exec'd
* `sftp-server` over one persistent Reticulum Link). Every file op shares ONE
* Link — no per-op handshake.
*
* **Wire constraints (from the rnsh substrate):**
* - [ReticulumExecSession.writeStdin] sends one MDU-bounded Channel message per
* call, so packets are chunked at [STDIN_CHUNK]; the server reassembles by
* SFTP length-prefix.
* - `stdout` is an UNLIMITED flow of raw byte deltas at arbitrary boundaries; a
* single reader coroutine drains it and re-frames length-prefixed packets.
* - We NEVER call [ReticulumExecSession.closeStdin] (the Python listener kills
* the command ~50 ms after a stdin-EOF). [close] tears down the Link.
* - **The markqvist/rnsh listener echoes stdin onto stdout** (process.py:
* "forward input immediately for visibility"), mirroring every request back —
* as whole, well-framed SFTP packets — interleaved with the server's
* responses in no guaranteed order. SFTP requests and responses occupy
* disjoint msgType ranges, so the reader simply drops any request-typed
* packet (the echo) and dispatches only responses ([SftpV3Codec.isResponseType]).
* A direct pipe (no echo) carries only responses and is unaffected.
*
* **v1 is synchronous** — [requestMutex] serializes each request→response.
*/
class SftpV3Client(private val exec: ReticulumExecSession) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val pending = ConcurrentHashMap<Int, CompletableDeferred<SftpPacket>>()
private val versionDeferred = CompletableDeferred<SftpPacket.Version>()
private val nextId = AtomicInteger(1)
private val requestMutex = Mutex()
@Volatile private var closed = false
init {
startReader()
scope.launch { runCatching { exec.stderr.collect { /* discard */ } } }
}
// ---- public op surface ----------------------------------------------
/** Send FXP_INIT, await FXP_VERSION; require protocol v3. */
suspend fun handshake() {
requestMutex.withLock { send(SftpV3Codec.buildInit()) }
val version = withTimeout(HANDSHAKE_TIMEOUT_MS) { versionDeferred.await() }
if (version.version < SftpV3Codec.PROTOCOL_VERSION) {
throw IOException("sftp-server speaks v${version.version}; need v${SftpV3Codec.PROTOCOL_VERSION}")
}
}
suspend fun realPath(path: String): String =
when (val p = request { SftpV3Codec.buildRealPath(it, path) }) {
is SftpPacket.Name -> p.names.firstOrNull()?.filename ?: path
is SftpPacket.Status -> throw SftpV3Codec.statusToException(p)
else -> throw IOException("realpath: unexpected ${p::class.simpleName}")
}
suspend fun openDir(path: String): ByteArray = expectHandle("opendir") { SftpV3Codec.buildOpenDir(it, path) }
/** Returns the next batch of names, or null at end of directory. */
suspend fun readDir(handle: ByteArray): List<SftpV3Codec.SftpName>? =
when (val p = request { SftpV3Codec.buildReadDir(it, handle) }) {
is SftpPacket.Name -> p.names
is SftpPacket.Status -> if (p.code == SftpV3Codec.FX_EOF) null else throw SftpV3Codec.statusToException(p)
else -> throw IOException("readdir: unexpected ${p::class.simpleName}")
}
suspend fun closeHandle(handle: ByteArray) {
runCatching { expectOk("close") { SftpV3Codec.buildClose(it, handle) } }
}
suspend fun stat(path: String): SftpV3Codec.SftpAttrs = expectAttrs("stat") { SftpV3Codec.buildStat(it, path) }
suspend fun lstat(path: String): SftpV3Codec.SftpAttrs = expectAttrs("lstat") { SftpV3Codec.buildLStat(it, path) }
suspend fun openRead(path: String): ByteArray =
expectHandle("open") { SftpV3Codec.buildOpen(it, path, SftpV3Codec.FXF_READ) }
suspend fun openWrite(path: String): ByteArray =
expectHandle("open") {
SftpV3Codec.buildOpen(it, path, SftpV3Codec.FXF_WRITE or SftpV3Codec.FXF_CREAT or SftpV3Codec.FXF_TRUNC)
}
/** Returns the data read, or null at EOF. */
suspend fun read(handle: ByteArray, offset: Long, len: Int): ByteArray? =
when (val p = request { SftpV3Codec.buildRead(it, handle, offset, len) }) {
is SftpPacket.Data -> p.data
is SftpPacket.Status -> if (p.code == SftpV3Codec.FX_EOF) null else throw SftpV3Codec.statusToException(p)
else -> throw IOException("read: unexpected ${p::class.simpleName}")
}
suspend fun write(handle: ByteArray, offset: Long, data: ByteArray, dataOff: Int, dataLen: Int) =
expectOk("write") { SftpV3Codec.buildWrite(it, handle, offset, data, dataOff, dataLen) }
suspend fun mkdir(path: String) = expectOk("mkdir") { SftpV3Codec.buildMkdir(it, path) }
suspend fun rmdir(path: String) = expectOk("rmdir") { SftpV3Codec.buildRmdir(it, path) }
suspend fun remove(path: String) = expectOk("remove") { SftpV3Codec.buildRemove(it, path) }
suspend fun rename(from: String, to: String) = expectOk("rename") { SftpV3Codec.buildRename(it, from, to) }
/** Tear down the Link (never sends a stdin-EOF) and fail any pending ops. */
fun close() {
if (closed) return
closed = true
runCatching { exec.close() }
failAll(IOException("reticulum sftp session closed"))
scope.cancel()
}
val isClosed: Boolean get() = closed
// ---- request plumbing ------------------------------------------------
private suspend inline fun request(crossinline build: (Int) -> ByteArray): SftpPacket {
if (closed) throw IOException("reticulum sftp session closed")
val id = nextId.getAndIncrement() and 0x7FFFFFFF
val deferred = CompletableDeferred<SftpPacket>()
return requestMutex.withLock {
pending[id] = deferred
try {
send(build(id))
withTimeout(OP_TIMEOUT_MS) { deferred.await() }
} finally {
pending.remove(id)
}
}
}
private suspend inline fun expectHandle(op: String, crossinline build: (Int) -> ByteArray): ByteArray =
when (val p = request(build)) {
is SftpPacket.Handle -> p.handle
is SftpPacket.Status -> throw SftpV3Codec.statusToException(p)
else -> throw IOException("$op: unexpected ${p::class.simpleName}")
}
private suspend inline fun expectAttrs(op: String, crossinline build: (Int) -> ByteArray): SftpV3Codec.SftpAttrs =
when (val p = request(build)) {
is SftpPacket.Attrs -> p.attrs
is SftpPacket.Status -> throw SftpV3Codec.statusToException(p)
else -> throw IOException("$op: unexpected ${p::class.simpleName}")
}
private suspend inline fun expectOk(op: String, crossinline build: (Int) -> ByteArray) {
when (val p = request(build)) {
is SftpPacket.Status -> if (p.code != SftpV3Codec.FX_OK) throw SftpV3Codec.statusToException(p)
else -> throw IOException("$op: unexpected ${p::class.simpleName}")
}
}
/** Chunk a framed packet under the per-writeStdin MDU ceiling. */
private suspend fun send(packet: ByteArray) {
var off = 0
while (off < packet.size) {
val end = minOf(off + STDIN_CHUNK, packet.size)
exec.writeStdin(packet.copyOfRange(off, end))
off = end
}
}
private fun startReader() {
scope.launch {
var acc = ByteArray(0)
try {
exec.stdout.collect { delta ->
acc = if (acc.isEmpty()) delta else acc + delta
var pos = 0
while (acc.size - pos >= 4) {
val len = readU32(acc, pos)
if (len < 1 || len > SftpV3Codec.MAX_PACKET) throw IOException("sftp framing desync: $len")
if (acc.size - pos - 4 < len) break
val type = acc[pos + 4].toInt() and 0xFF
val body = acc.copyOfRange(pos + 4, pos + 4 + len)
pos += 4 + len
// The markqvist rnsh listener echoes our stdin — whole SFTP
// *request* packets — back onto stdout, interleaved with the
// server's responses and in no guaranteed order. Requests and
// responses use disjoint msgType ranges, so drop any
// request-typed packet (the echo) and dispatch only responses.
if (SftpV3Codec.isResponseType(type)) {
dispatch(SftpV3Codec.parsePacket(body))
}
}
acc = if (pos == acc.size) EMPTY else acc.copyOfRange(pos, acc.size)
}
failAll(IOException("reticulum sftp link closed"))
} catch (e: CancellationException) {
failAll(IOException("reticulum sftp session closed"))
} catch (e: Throwable) {
failAll(IOException("reticulum sftp reader error: ${e.message}", e))
}
}
}
private fun dispatch(packet: SftpPacket) {
if (packet is SftpPacket.Version) {
versionDeferred.complete(packet)
return
}
val id = when (packet) {
is SftpPacket.Status -> packet.id
is SftpPacket.Handle -> packet.id
is SftpPacket.Data -> packet.id
is SftpPacket.Name -> packet.id
is SftpPacket.Attrs -> packet.id
is SftpPacket.Version -> return
}
pending.remove(id)?.complete(packet)
}
private fun failAll(cause: IOException) {
if (!versionDeferred.isCompleted) versionDeferred.completeExceptionally(cause)
// Drain the live concurrent map's weakly-consistent value view directly and fail
// each pending op (completeExceptionally is idempotent, so a racing dispatch() that
// already completed one is harmless). The previous `pending.keys.toList()` snapshot
// raced with concurrent pending.remove() in dispatch()/request(): at size==1, Kotlin's
// toList() fast-path calls iterator().next(), which threw NoSuchElementException when
// the sole entry was removed mid-snapshot.
for (deferred in pending.values) deferred.completeExceptionally(cause)
pending.clear()
}
private fun readU32(b: ByteArray, off: Int): Int =
((b[off].toInt() and 0xFF) shl 24) or
((b[off + 1].toInt() and 0xFF) shl 16) or
((b[off + 2].toInt() and 0xFF) shl 8) or
(b[off + 3].toInt() and 0xFF)
companion object {
/** Max bytes per writeStdin call (one Channel message, under link MDU ~423). */
private const val STDIN_CHUNK = 384
private const val HANDSHAKE_TIMEOUT_MS = 30_000L
private const val OP_TIMEOUT_MS = 120_000L
private val EMPTY = ByteArray(0)
}
}
@@ -0,0 +1,298 @@
package sh.haven.core.reticulum.sftp
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.FileNotFoundException
import java.io.IOException
/**
* Minimal SSH File Transfer Protocol **version 3** codec (the OpenSSH default).
*
* Pure and stateless: it builds fully-framed request packets and parses one
* already-complete response packet. It has no I/O and no coroutines — the
* reassembly of length-prefixed packets from an arbitrary byte stream lives in
* [SftpV3Client]. This mirrors `core/usb/UsbProxyProtocol`'s big-endian
* `DataOutputStream`/`DataInputStream` framing idiom.
*
* Wire format (RFC draft-ietf-secsh-filexfer-02 / SFTP v3): every packet is
* `uint32 length · byte type · [uint32 request-id] · type-specific`. All
* integers are big-endian (Java/`DataOutputStream` default). An SFTP "string"
* is `uint32 length · bytes` (NOT NUL-terminated); file handles are opaque
* binary strings kept as [ByteArray] end to end.
*/
object SftpV3Codec {
const val PROTOCOL_VERSION = 3
/** Guard against a desynced stream claiming an absurd packet length. */
const val MAX_PACKET = 1 shl 18 // 256 KiB
// Packet types — requests (client → server)
const val FXP_INIT = 1
const val FXP_VERSION = 2
const val FXP_OPEN = 3
const val FXP_CLOSE = 4
const val FXP_READ = 5
const val FXP_WRITE = 6
const val FXP_LSTAT = 7
const val FXP_FSTAT = 8
const val FXP_OPENDIR = 11
const val FXP_READDIR = 12
const val FXP_REMOVE = 13
const val FXP_MKDIR = 14
const val FXP_RMDIR = 15
const val FXP_REALPATH = 16
const val FXP_STAT = 17
const val FXP_RENAME = 18
// Packet types — responses (server → client)
const val FXP_STATUS = 101
const val FXP_HANDLE = 102
const val FXP_DATA = 103
const val FXP_NAME = 104
const val FXP_ATTRS = 105
// Open flags (pflags)
const val FXF_READ = 0x00000001
const val FXF_WRITE = 0x00000002
const val FXF_APPEND = 0x00000004
const val FXF_CREAT = 0x00000008
const val FXF_TRUNC = 0x00000010
const val FXF_EXCL = 0x00000020
// ATTRS flags
const val ATTR_SIZE = 0x00000001
const val ATTR_UIDGID = 0x00000002
const val ATTR_PERMISSIONS = 0x00000004
const val ATTR_ACMODTIME = 0x00000008
const val ATTR_EXTENDED = -0x80000000 // 0x80000000 as a signed Int
// Status codes
const val FX_OK = 0
const val FX_EOF = 1
const val FX_NO_SUCH_FILE = 2
const val FX_PERMISSION_DENIED = 3
const val FX_FAILURE = 4
const val FX_BAD_MESSAGE = 5
const val FX_NO_CONNECTION = 6
const val FX_CONNECTION_LOST = 7
const val FX_OP_UNSUPPORTED = 8
// POSIX mode type bits (in the ATTRS permissions field)
private const val S_IFMT = 0xF000
private const val S_IFDIR = 0x4000
private const val S_IFLNK = 0xA000
// ---- Models ----------------------------------------------------------
/** SFTP v3 file attributes (only the fields the FileBackend surface needs). */
data class SftpAttrs(
val size: Long = 0,
val uid: Int = 0,
val gid: Int = 0,
val permissions: Int = 0,
val atime: Long = 0,
val mtime: Long = 0,
val flags: Int = 0,
) {
val hasPermissions: Boolean get() = flags and ATTR_PERMISSIONS != 0
val isDirectory: Boolean get() = hasPermissions && (permissions and S_IFMT) == S_IFDIR
val isSymlink: Boolean get() = hasPermissions && (permissions and S_IFMT) == S_IFLNK
/** modified-time as epoch millis (v3 mtime is u32 epoch seconds). */
val modifiedTimeMillis: Long get() = if (flags and ATTR_ACMODTIME != 0) mtime * 1000L else 0L
/** mtime as epoch SECONDS (SFTP v3 native unit; 0 when unknown). */
val modifiedTimeSeconds: Long get() = if (flags and ATTR_ACMODTIME != 0) mtime else 0L
/** A `drwxr-xr-x`-style mode string for display, or "" if unknown. */
fun permString(): String {
if (!hasPermissions) return ""
val type = when (permissions and S_IFMT) {
S_IFDIR -> 'd'
S_IFLNK -> 'l'
0x1000 -> 'p' // FIFO
0x2000 -> 'c' // char dev
0x6000 -> 'b' // block dev
0xC000 -> 's' // socket
else -> '-'
}
val sb = StringBuilder(10).append(type)
var bit = 0x100
"rwxrwxrwx".forEach { ch ->
sb.append(if (permissions and bit != 0) ch else '-')
bit = bit shr 1
}
return sb.toString()
}
}
/** One entry from an FXP_NAME (READDIR / REALPATH) response. */
data class SftpName(
val filename: String,
val longname: String,
val attrs: SftpAttrs,
)
/** A parsed SFTP response packet. */
sealed interface SftpPacket {
data class Version(val version: Int, val extensions: Map<String, String>) : SftpPacket
data class Status(val id: Int, val code: Int, val message: String) : SftpPacket
data class Handle(val id: Int, val handle: ByteArray) : SftpPacket
data class Data(val id: Int, val data: ByteArray) : SftpPacket
data class Name(val id: Int, val names: List<SftpName>) : SftpPacket
data class Attrs(val id: Int, val attrs: SftpAttrs) : SftpPacket
}
/** The request-id a response correlates to, or null for the id-less VERSION. */
fun SftpPacket.requestId(): Int? = when (this) {
is SftpPacket.Version -> null
is SftpPacket.Status -> id
is SftpPacket.Handle -> id
is SftpPacket.Data -> id
is SftpPacket.Name -> id
is SftpPacket.Attrs -> id
}
// ---- Request builders (each returns a fully framed packet) -----------
fun buildInit(): ByteArray = frame {
writeByte(FXP_INIT)
writeInt(PROTOCOL_VERSION)
}
fun buildRealPath(id: Int, path: String) = frame { req(FXP_REALPATH, id); str(path) }
fun buildOpenDir(id: Int, path: String) = frame { req(FXP_OPENDIR, id); str(path) }
fun buildReadDir(id: Int, handle: ByteArray) = frame { req(FXP_READDIR, id); bin(handle) }
fun buildClose(id: Int, handle: ByteArray) = frame { req(FXP_CLOSE, id); bin(handle) }
fun buildStat(id: Int, path: String) = frame { req(FXP_STAT, id); str(path) }
fun buildLStat(id: Int, path: String) = frame { req(FXP_LSTAT, id); str(path) }
fun buildRemove(id: Int, path: String) = frame { req(FXP_REMOVE, id); str(path) }
fun buildRmdir(id: Int, path: String) = frame { req(FXP_RMDIR, id); str(path) }
fun buildMkdir(id: Int, path: String) = frame { req(FXP_MKDIR, id); str(path); writeInt(0) /* empty attrs */ }
fun buildRename(id: Int, from: String, to: String) = frame { req(FXP_RENAME, id); str(from); str(to) }
fun buildOpen(id: Int, path: String, pflags: Int) = frame {
req(FXP_OPEN, id); str(path); writeInt(pflags); writeInt(0) /* empty attrs */
}
fun buildRead(id: Int, handle: ByteArray, offset: Long, len: Int) = frame {
req(FXP_READ, id); bin(handle); writeLong(offset); writeInt(len)
}
fun buildWrite(id: Int, handle: ByteArray, offset: Long, data: ByteArray, dataOff: Int, dataLen: Int) = frame {
req(FXP_WRITE, id); bin(handle); writeLong(offset)
writeInt(dataLen); write(data, dataOff, dataLen)
}
// ---- Response parsing ------------------------------------------------
/**
* Parse one complete packet body — everything after the `uint32 length`
* prefix, i.e. starting with the type byte. The caller ([SftpV3Client]'s
* reader) is responsible for having buffered exactly `length` bytes.
*/
/**
* True for the msgType codes a server SENDS (VERSION + the 101–105 response
* range). Requests and responses occupy disjoint ranges, so this lets the
* client drop echoed *request* packets: the markqvist rnsh listener mirrors
* our stdin onto stdout ("forward input immediately for visibility"), so any
* request-typed packet in the inbound stream is echo and must be ignored.
*/
fun isResponseType(type: Int): Boolean =
type == FXP_VERSION || type in FXP_STATUS..FXP_ATTRS
fun parsePacket(body: ByteArray): SftpPacket {
val din = DataInputStream(ByteArrayInputStream(body))
return when (val type = din.readUnsignedByte()) {
FXP_VERSION -> {
val version = din.readInt()
val ext = LinkedHashMap<String, String>()
while (din.available() > 0) {
val name = readStr(din)
val data = if (din.available() > 0) readStr(din) else ""
ext[name] = data
}
SftpPacket.Version(version, ext)
}
FXP_STATUS -> {
val id = din.readInt()
val code = din.readInt()
val msg = if (din.available() > 0) readStr(din) else ""
SftpPacket.Status(id, code, msg)
}
FXP_HANDLE -> SftpPacket.Handle(din.readInt(), readBin(din))
FXP_DATA -> SftpPacket.Data(din.readInt(), readBin(din))
FXP_NAME -> {
val id = din.readInt()
val count = din.readInt()
require(count in 0..1_000_000) { "absurd FXP_NAME count $count" }
val names = ArrayList<SftpName>(count.coerceAtMost(1024))
repeat(count) {
val filename = readStr(din)
val longname = readStr(din)
val attrs = readAttrs(din)
names.add(SftpName(filename, longname, attrs))
}
SftpPacket.Name(id, names)
}
FXP_ATTRS -> SftpPacket.Attrs(din.readInt(), readAttrs(din))
else -> throw IOException("unexpected SFTP packet type $type")
}
}
/** Map a non-OK/EOF status to the exception the FileBackend contract expects. */
fun statusToException(status: SftpPacket.Status): IOException {
val detail = status.message.ifBlank { "SFTP status ${status.code}" }
return when (status.code) {
FX_NO_SUCH_FILE -> FileNotFoundException(detail)
FX_PERMISSION_DENIED -> IOException("permission denied: $detail")
else -> IOException(detail)
}
}
// ---- internal helpers ------------------------------------------------
private fun readAttrs(din: DataInputStream): SftpAttrs {
val flags = din.readInt()
var size = 0L; var uid = 0; var gid = 0; var perms = 0; var atime = 0L; var mtime = 0L
if (flags and ATTR_SIZE != 0) size = din.readLong()
if (flags and ATTR_UIDGID != 0) { uid = din.readInt(); gid = din.readInt() }
if (flags and ATTR_PERMISSIONS != 0) perms = din.readInt()
if (flags and ATTR_ACMODTIME != 0) {
atime = din.readInt().toLong() and 0xFFFFFFFFL
mtime = din.readInt().toLong() and 0xFFFFFFFFL
}
if (flags and ATTR_EXTENDED != 0) {
val count = din.readInt()
repeat(count.coerceIn(0, 4096)) { readStr(din); readStr(din) }
}
return SftpAttrs(size, uid, gid, perms, atime, mtime, flags)
}
private fun readStr(din: DataInputStream): String = String(readBin(din), Charsets.UTF_8)
private fun readBin(din: DataInputStream): ByteArray {
val n = din.readInt()
require(n in 0..MAX_PACKET) { "SFTP string length $n out of range" }
val b = ByteArray(n)
din.readFully(b)
return b
}
// DSL shims used by the builders.
private fun DataOutputStream.req(type: Int, id: Int) { writeByte(type); writeInt(id) }
private fun DataOutputStream.str(s: String) { val b = s.toByteArray(Charsets.UTF_8); writeInt(b.size); write(b) }
private fun DataOutputStream.bin(b: ByteArray) { writeInt(b.size); write(b) }
/** Build a packet body and prefix it with its `uint32 length`. */
private inline fun frame(block: DataOutputStream.() -> Unit): ByteArray {
val body = ByteArrayOutputStream()
DataOutputStream(body).use { it.block() }
val bodyBytes = body.toByteArray()
val out = ByteArrayOutputStream(bodyBytes.size + 4)
DataOutputStream(out).use { it.writeInt(bodyBytes.size); it.write(bodyBytes) }
return out.toByteArray()
}
}
@@ -0,0 +1,94 @@
package sh.haven.core.reticulum
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.DataOutputStream
/**
* Byte-level tests for the SOCKS5 (no-auth, CONNECT) handshake used by
* [ReticulumForwardServer]'s dynamic forward. No network.
*/
class ReticulumForwardServerTest {
private fun server() = ReticulumForwardServer(StubTransport())
private fun handshake(request: ByteArray): Pair<Pair<String, Int>?, ByteArray> {
val out = ByteArrayOutputStream()
val result = server().parseSocks5Connect(
DataInputStream(ByteArrayInputStream(request)),
DataOutputStream(out),
)
return result to out.toByteArray()
}
@Test
fun `domain CONNECT parses host and port`() {
// greeting: VER=5 NMETHODS=1 METHOD=0
// request: VER=5 CMD=1 RSV=0 ATYP=3 LEN=11 "example.com" PORT=80
val req = byteArrayOf(0x05, 0x01, 0x00) +
byteArrayOf(0x05, 0x01, 0x00, 0x03, 0x0B) + "example.com".toByteArray() +
byteArrayOf(0x00, 0x50)
val (dest, out) = handshake(req)
assertEquals("example.com" to 80, dest)
// method selection then success reply.
assertEquals(0x05.toByte(), out[0]); assertEquals(0x00.toByte(), out[1])
assertEquals(0x05.toByte(), out[2]); assertEquals(0x00.toByte(), out[3])
}
@Test
fun `ipv4 CONNECT parses host and port`() {
val req = byteArrayOf(0x05, 0x01, 0x00) +
byteArrayOf(0x05, 0x01, 0x00, 0x01, 0x7F, 0x00, 0x00, 0x01) +
byteArrayOf(0x1F, 0x90.toByte()) // 8080
val (dest, _) = handshake(req)
assertEquals("127.0.0.1" to 8080, dest)
}
@Test
fun `non-CONNECT command is rejected`() {
// CMD=2 (BIND) → null + reply code 0x07 (command not supported)
val req = byteArrayOf(0x05, 0x01, 0x00) +
byteArrayOf(0x05, 0x02, 0x00, 0x01, 0x7F, 0x00, 0x00, 0x01, 0x00, 0x50)
val (dest, out) = handshake(req)
assertNull(dest)
// reply is [05 07 00 01 ...]
assertEquals(0x05.toByte(), out[2]); assertEquals(0x07.toByte(), out[3])
}
@Test
fun `no acceptable methods is rejected`() {
// only METHOD=2 (user/pass) offered → 05 FF, null
val req = byteArrayOf(0x05, 0x01, 0x02)
val (dest, out) = handshake(req)
assertNull(dest)
assertArrayEquals(byteArrayOf(0x05, 0xFF.toByte()), out)
}
/** Minimal transport stub — the handshake never touches it. */
private class StubTransport : ReticulumTransport {
override suspend fun init(configDir: String, host: String, port: Int, ifacNetname: String?, ifacNetkey: String?, socketDialer: ((String, Int, Int) -> java.net.Socket)?): String = ""
override val isInitialised: Boolean = false
override suspend fun openSession(destinationHash: String, rows: Int, cols: Int): RnshShellSession = throw NotImplementedError()
override suspend fun execCommand(destinationHash: String, command: List<String>): ReticulumExecSession = throw NotImplementedError()
override val discoveredDestinations: StateFlow<List<DiscoveredDestination>> = MutableStateFlow(emptyList())
override suspend fun requestPath(destinationHashHex: String): Boolean = false
override suspend fun probeSideband(configDir: String): Boolean = false
override suspend fun clientIdentityHash(configDir: String): String? =
throw NotImplementedError("identity storage is not part of this test")
override suspend fun importClientIdentity(
configDir: String,
source: java.io.File,
): ReticulumIdentityImport =
throw NotImplementedError("identity storage is not part of this test")
override suspend fun closeAll() {}
}
}
@@ -0,0 +1,144 @@
package sh.haven.core.reticulum
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* The Reticulum stack is a process singleton whose mode — shared instance or
* gateway — is fixed when it starts, and the two are exclusive (#588). Nothing
* released it, so a shared-instance connection made a gateway connection
* impossible for the life of the process: "the banner keeps appearing even
* after disconnecting the session and just closing Haven makes possible to
* choose again" (reported against v5.87.59).
*
* These tests pin the release: the last session going away shuts the stack
* down, and a session that is still there keeps it up.
*/
class ReticulumSessionManagerStackTest {
private fun manager(transport: ReticulumTransport) =
ReticulumSessionManager(transport, ReticulumForwardServer(transport))
@Test
fun `removing the last session shuts the stack down`() {
val transport = LatchTransport()
val manager = manager(transport)
val id = manager.registerSession("profile-a", "a", "aa".repeat(16))
manager.removeSession(id)
assertTrue(
"stack was not released after the last session went away",
transport.closed.await(5, TimeUnit.SECONDS),
)
}
@Test
fun `removing one of two sessions leaves the stack up`() {
val transport = LatchTransport()
val manager = manager(transport)
val first = manager.registerSession("profile-a", "a", "aa".repeat(16))
manager.registerSession("profile-b", "b", "bb".repeat(16))
manager.removeSession(first)
assertFalse(
"stack was released while a session was still open",
transport.closed.await(1, TimeUnit.SECONDS),
)
}
@Test
fun `disconnectAll shuts the stack down`() {
val transport = LatchTransport()
val manager = manager(transport)
manager.registerSession("profile-a", "a", "aa".repeat(16))
manager.registerSession("profile-b", "b", "bb".repeat(16))
manager.disconnectAll()
assertTrue(
"stack was not released after disconnectAll",
transport.closed.await(5, TimeUnit.SECONDS),
)
}
@Test
fun `removing a profile's last session shuts the stack down`() {
val transport = LatchTransport()
val manager = manager(transport)
manager.registerSession("profile-a", "a", "aa".repeat(16))
manager.registerSession("profile-a", "a2", "aa".repeat(16))
manager.removeAllSessionsForProfile("profile-a")
assertTrue(
"stack was not released after the profile's sessions went away",
transport.closed.await(5, TimeUnit.SECONDS),
)
assertEquals(1, transport.closeCount)
}
@Test
fun `a failed connect leaves the session in ERROR, not a CONNECTING ghost`() {
val transport = LatchTransport()
val manager = manager(transport)
val id = manager.registerSession("profile-a", "a", "aa".repeat(16))
val thrown = runCatching {
runBlocking { manager.connectSession(id, "", "bad.host", 1) }
}.exceptionOrNull()
// The exact type is not the contract; any throw must leave ERROR behind.
// In a JVM unit test the `android.util.Log.w` at the top of the try
// throws "not mocked" before transport.init is reached, which exercises
// the same catch-and-mark path a real transport failure would.
assertTrue("connect should have thrown", thrown != null)
assertEquals(
"a failed connect must surface as ERROR so the tab shows dead and " +
"activeSessions stops counting it (#601)",
ReticulumSessionManager.SessionState.Status.ERROR,
manager.sessions.value[id]?.status,
)
}
/** Records [closeAll] so the test can wait for work done on the IO dispatcher. */
private class LatchTransport : ReticulumTransport {
val closed = CountDownLatch(1)
@Volatile
var closeCount: Int = 0
private set
override suspend fun closeAll() {
closeCount++
closed.countDown()
}
// Throws: connectSession must translate this into an ERROR status
// rather than leaving the entry CONNECTING (#601).
override suspend fun init(configDir: String, host: String, port: Int, ifacNetname: String?, ifacNetkey: String?, socketDialer: ((String, Int, Int) -> java.net.Socket)?): String =
throw IllegalStateException("no stack in this test")
override val isInitialised: Boolean = false
override suspend fun openSession(destinationHash: String, rows: Int, cols: Int): RnshShellSession = throw NotImplementedError()
override suspend fun execCommand(destinationHash: String, command: List<String>): ReticulumExecSession = throw NotImplementedError()
override val discoveredDestinations: StateFlow<List<DiscoveredDestination>> = MutableStateFlow(emptyList())
override suspend fun requestPath(destinationHashHex: String): Boolean = false
override suspend fun probeSideband(configDir: String): Boolean = false
override suspend fun clientIdentityHash(configDir: String): String? =
throw NotImplementedError("identity storage is not part of this test")
override suspend fun importClientIdentity(
configDir: String,
source: java.io.File,
): ReticulumIdentityImport =
throw NotImplementedError("identity storage is not part of this test")
}
}
@@ -0,0 +1,227 @@
package sh.haven.core.reticulum.sftp
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import sh.haven.core.reticulum.ReticulumExecSession
import sh.haven.core.reticulum.sftp.SftpV3Codec.ATTR_ACMODTIME
import sh.haven.core.reticulum.sftp.SftpV3Codec.ATTR_PERMISSIONS
import sh.haven.core.reticulum.sftp.SftpV3Codec.ATTR_SIZE
import sh.haven.core.reticulum.sftp.SftpV3Codec.FXP_DATA
import sh.haven.core.reticulum.sftp.SftpV3Codec.FXP_HANDLE
import sh.haven.core.reticulum.sftp.SftpV3Codec.FXP_INIT
import sh.haven.core.reticulum.sftp.SftpV3Codec.FXP_NAME
import sh.haven.core.reticulum.sftp.SftpV3Codec.FXP_STATUS
import sh.haven.core.reticulum.sftp.SftpV3Codec.FXP_VERSION
import sh.haven.core.reticulum.sftp.SftpV3Codec.FX_EOF
import sh.haven.core.reticulum.sftp.SftpV3Codec.FX_NO_SUCH_FILE
import sh.haven.core.reticulum.sftp.SftpV3Codec.FX_OK
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.FileNotFoundException
import java.io.IOException
class SftpV3ClientTest {
private val HANDLE = byteArrayOf(1, 2, 3, 4)
/** A fake exec session: reassembles client request packets, lets the test feed (optionally split) server bytes. */
private class FakeExec : ReticulumExecSession {
private val stdoutChan = Channel<ByteArray>(Channel.UNLIMITED)
override val stdout: Flow<ByteArray> = stdoutChan.receiveAsFlow()
override val stderr: Flow<ByteArray> = emptyFlow()
override val exitCode = CompletableDeferred<Int>()
var closeStdinCalled = false
var closeCalled = false
data class Req(val type: Int, val id: Int)
private val reqChan = Channel<Req>(Channel.UNLIMITED)
private var acc = ByteArray(0)
override suspend fun writeStdin(data: ByteArray) {
acc += data
var pos = 0
while (acc.size - pos >= 4) {
val len = u32(acc, pos)
if (acc.size - pos - 4 < len) break
val body = acc.copyOfRange(pos + 4, pos + 4 + len); pos += 4 + len
val din = DataInputStream(ByteArrayInputStream(body))
val type = din.readUnsignedByte()
val id = din.readInt() // for INIT this is the version field; harmless
reqChan.trySend(Req(type, id))
}
acc = acc.copyOfRange(pos, acc.size)
}
override suspend fun closeStdin() { closeStdinCalled = true }
override fun close() { closeCalled = true; stdoutChan.close() }
suspend fun takeRequest(): Req = reqChan.receive()
fun feed(bytes: ByteArray, chunk: Int = bytes.size) {
var o = 0
while (o < bytes.size) { val e = minOf(o + chunk, bytes.size); stdoutChan.trySend(bytes.copyOfRange(o, e)); o = e }
}
private fun u32(b: ByteArray, o: Int) =
((b[o].toInt() and 0xFF) shl 24) or ((b[o + 1].toInt() and 0xFF) shl 16) or
((b[o + 2].toInt() and 0xFF) shl 8) or (b[o + 3].toInt() and 0xFF)
}
// --- server-side framed packet builders ---
private fun frame(block: DataOutputStream.() -> Unit): ByteArray {
val body = ByteArrayOutputStream(); DataOutputStream(body).use { it.block() }
val bb = body.toByteArray()
val out = ByteArrayOutputStream(); DataOutputStream(out).use { it.writeInt(bb.size); it.write(bb) }
return out.toByteArray()
}
private fun DataOutputStream.sstr(s: String) { val b = s.toByteArray(); writeInt(b.size); write(b) }
private fun DataOutputStream.attrs(size: Long, perms: Int, mtime: Int) {
writeInt(ATTR_SIZE or ATTR_PERMISSIONS or ATTR_ACMODTIME); writeLong(size); writeInt(perms); writeInt(mtime); writeInt(mtime)
}
private fun sVersion(v: Int) = frame { writeByte(FXP_VERSION); writeInt(v) }
private fun sHandle(id: Int) = frame { writeByte(FXP_HANDLE); writeInt(id); writeInt(HANDLE.size); write(HANDLE) }
private fun sStatus(id: Int, code: Int, msg: String = "") = frame { writeByte(FXP_STATUS); writeInt(id); writeInt(code); sstr(msg) }
private fun sData(id: Int, d: ByteArray) = frame { writeByte(FXP_DATA); writeInt(id); writeInt(d.size); write(d) }
private fun sName(id: Int, entries: List<Triple<String, Long, Int>>) = frame {
writeByte(FXP_NAME); writeInt(id); writeInt(entries.size)
for ((name, size, perms) in entries) { sstr(name); sstr("longname $name"); attrs(size, perms, 1_700_000_000) }
}
@Test
fun `handshake completes on VERSION`() = runBlocking {
val fake = FakeExec(); val client = SftpV3Client(fake)
val server = launch { val r = fake.takeRequest(); assertEquals(FXP_INIT, r.type); fake.feed(sVersion(3)) }
withTimeout(5_000) { client.handshake() }
server.cancel(); client.close()
}
@Test
fun `handshake drops the listener's echoed request packets in any order`() = runBlocking {
// The markqvist rnsh listener mirrors our stdin (whole request packets)
// onto stdout; the echoed FXP_INIT can arrive before OR after VERSION.
// Either way it must be ignored (the device-verify regression for #21).
for (echoFirst in listOf(true, false)) {
val fake = FakeExec(); val client = SftpV3Client(fake)
val echoedInit = frame { writeByte(FXP_INIT); writeInt(3) }
val server = launch {
assertEquals(FXP_INIT, fake.takeRequest().type)
if (echoFirst) { fake.feed(echoedInit); fake.feed(sVersion(3)) }
else { fake.feed(sVersion(3)); fake.feed(echoedInit) }
}
withTimeout(5_000) { client.handshake() }
server.cancel(); client.close()
}
}
@Test
fun `readDir loop returns names then null at EOF`() = runBlocking {
val fake = FakeExec(); val client = SftpV3Client(fake)
val server = launch {
assertEquals(FXP_INIT, fake.takeRequest().type); fake.feed(sVersion(3))
fake.feed(sHandle(fake.takeRequest().id)) // OPENDIR -> handle
fake.feed(sName(fake.takeRequest().id, listOf( // READDIR -> 2 names
Triple("sub", 4096L, 0x4000 or 0x1ED),
Triple("f.txt", 123L, 0x8000 or 0x1A4),
)))
fake.feed(sStatus(fake.takeRequest().id, FX_EOF)) // READDIR -> EOF
}
client.handshake()
val handle = client.openDir("/d")
assertArrayEquals(HANDLE, handle)
val first = client.readDir(handle)!!
assertEquals(listOf("sub", "f.txt"), first.map { it.filename })
assertTrue(first[0].attrs.isDirectory)
assertEquals(123L, first[1].attrs.size)
assertEquals(null, client.readDir(handle))
server.cancel(); client.close()
}
@Test
fun `read loop returns data then null at EOF`() = runBlocking {
val fake = FakeExec(); val client = SftpV3Client(fake)
val payload = ByteArray(500) { (it and 0xFF).toByte() }
val server = launch {
assertEquals(FXP_INIT, fake.takeRequest().type); fake.feed(sVersion(3))
fake.feed(sHandle(fake.takeRequest().id)) // OPEN -> handle
fake.feed(sData(fake.takeRequest().id, payload)) // READ -> data
fake.feed(sStatus(fake.takeRequest().id, FX_EOF)) // READ -> EOF
}
client.handshake()
val h = client.openRead("/f")
assertArrayEquals(payload, client.read(h, 0, 32768))
assertEquals(null, client.read(h, 500, 32768))
server.cancel(); client.close()
}
@Test
fun `stat on missing maps to FileNotFoundException`() = runBlocking {
val fake = FakeExec(); val client = SftpV3Client(fake)
val server = launch {
assertEquals(FXP_INIT, fake.takeRequest().type); fake.feed(sVersion(3))
fake.feed(sStatus(fake.takeRequest().id, FX_NO_SUCH_FILE, "No such file"))
}
client.handshake()
var thrown = false
try { client.stat("/nope") } catch (e: FileNotFoundException) { thrown = true }
assertTrue("expected FileNotFoundException", thrown)
server.cancel(); client.close()
}
@Test
fun `reader reassembles a response split across 7-byte deltas`() = runBlocking {
val fake = FakeExec(); val client = SftpV3Client(fake)
val server = launch {
assertEquals(FXP_INIT, fake.takeRequest().type); fake.feed(sVersion(3), chunk = 7)
fake.feed(sHandle(fake.takeRequest().id), chunk = 7)
// a NAME packet (well over 7 bytes) fed 7 bytes at a time
fake.feed(sName(fake.takeRequest().id, listOf(
Triple("alpha", 1L, 0x8000 or 0x1A4),
Triple("beta", 2L, 0x4000 or 0x1ED),
Triple("gamma-with-a-longer-name.bin", 3L, 0x8000 or 0x1A4),
)), chunk = 7)
fake.feed(sStatus(fake.takeRequest().id, FX_EOF), chunk = 7)
}
withTimeout(5_000) { client.handshake() }
val h = client.openDir("/d")
val names = client.readDir(h)!!.map { it.filename }
assertEquals(listOf("alpha", "beta", "gamma-with-a-longer-name.bin"), names)
assertEquals(null, client.readDir(h))
server.cancel(); client.close()
}
@Test
fun `close tears down without a stdin EOF`() = runBlocking {
val fake = FakeExec(); val client = SftpV3Client(fake)
client.close()
assertTrue(fake.closeCalled)
assertFalse("close() must never send a stdin-EOF", fake.closeStdinCalled)
assertTrue(client.isClosed)
}
@Test
fun `pending op fails (not hangs) when the link closes mid-request`() = runBlocking {
val fake = FakeExec(); val client = SftpV3Client(fake)
val server = launch {
assertEquals(FXP_INIT, fake.takeRequest().type); fake.feed(sVersion(3))
fake.takeRequest() // receive the stat request but never respond
client.close() // link drops mid-op
}
client.handshake()
var failed = false
try { withTimeout(5_000) { client.stat("/x") } } catch (e: IOException) { failed = true }
assertTrue("op must fail when link closes", failed)
server.cancel()
}
}
@@ -0,0 +1,167 @@
package sh.haven.core.reticulum.sftp
import sh.haven.core.reticulum.sftp.SftpV3Codec.FXP_ATTRS
import sh.haven.core.reticulum.sftp.SftpV3Codec.FXP_DATA
import sh.haven.core.reticulum.sftp.SftpV3Codec.FXP_HANDLE
import sh.haven.core.reticulum.sftp.SftpV3Codec.FXP_NAME
import sh.haven.core.reticulum.sftp.SftpV3Codec.FXP_OPEN
import sh.haven.core.reticulum.sftp.SftpV3Codec.FXP_STATUS
import sh.haven.core.reticulum.sftp.SftpV3Codec.FXP_VERSION
import sh.haven.core.reticulum.sftp.SftpV3Codec.SftpPacket
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.FileNotFoundException
class SftpV3CodecTest {
// --- helpers: build a server-shaped packet BODY (type + payload, no length prefix) ---
private fun body(block: DataOutputStream.() -> Unit): ByteArray {
val bos = ByteArrayOutputStream()
DataOutputStream(bos).use { it.block() }
return bos.toByteArray()
}
private fun DataOutputStream.sstr(s: String) { val b = s.toByteArray(); writeInt(b.size); write(b) }
private fun DataOutputStream.sbin(b: ByteArray) { writeInt(b.size); write(b) }
@Test
fun `buildInit emits length, type, version`() {
val pkt = SftpV3Codec.buildInit()
val din = DataInputStream(ByteArrayInputStream(pkt))
assertEquals(pkt.size - 4, din.readInt()) // length covers everything after the prefix
assertEquals(SftpV3Codec.FXP_INIT, din.readUnsignedByte())
assertEquals(SftpV3Codec.PROTOCOL_VERSION, din.readInt())
}
@Test
fun `buildOpen frames type, id, path, pflags, empty attrs`() {
val pkt = SftpV3Codec.buildOpen(9, "/a/b", SftpV3Codec.FXF_READ or SftpV3Codec.FXF_WRITE)
val din = DataInputStream(ByteArrayInputStream(pkt))
assertEquals(pkt.size - 4, din.readInt())
assertEquals(FXP_OPEN, din.readUnsignedByte())
assertEquals(9, din.readInt())
val n = din.readInt(); val pb = ByteArray(n); din.readFully(pb)
assertEquals("/a/b", String(pb))
assertEquals(SftpV3Codec.FXF_READ or SftpV3Codec.FXF_WRITE, din.readInt())
assertEquals(0, din.readInt()) // empty attrs
}
@Test
fun `buildRealPath round-trips a UTF-8 multibyte path`() {
val path = "/файл/日本/a.txt"
val pkt = SftpV3Codec.buildRealPath(3, path)
val din = DataInputStream(ByteArrayInputStream(pkt))
din.readInt() // length
assertEquals(SftpV3Codec.FXP_REALPATH, din.readUnsignedByte())
assertEquals(3, din.readInt())
val n = din.readInt(); val pb = ByteArray(n); din.readFully(pb)
assertEquals(path, String(pb, Charsets.UTF_8))
}
@Test
fun `buildWrite carries a data slice at offset`() {
val data = ByteArray(10) { it.toByte() }
val pkt = SftpV3Codec.buildWrite(1, byteArrayOf(0xAB.toByte()), 4096L, data, 2, 5)
val din = DataInputStream(ByteArrayInputStream(pkt))
din.readInt()
assertEquals(SftpV3Codec.FXP_WRITE, din.readUnsignedByte())
assertEquals(1, din.readInt())
val hl = din.readInt(); din.skipBytes(hl)
assertEquals(4096L, din.readLong())
val dl = din.readInt(); val d = ByteArray(dl); din.readFully(d)
assertArrayEquals(byteArrayOf(2, 3, 4, 5, 6), d)
}
@Test
fun `parses VERSION with extensions`() {
val pkt = SftpV3Codec.parsePacket(body {
writeByte(FXP_VERSION); writeInt(3)
sstr("posix-rename@openssh.com"); sstr("1")
sstr("hardlink@openssh.com"); sstr("1")
}) as SftpPacket.Version
assertEquals(3, pkt.version)
assertEquals("1", pkt.extensions["posix-rename@openssh.com"])
assertEquals(2, pkt.extensions.size)
}
@Test
fun `parses STATUS and maps codes to exceptions`() {
val s = SftpV3Codec.parsePacket(body {
writeByte(FXP_STATUS); writeInt(7); writeInt(SftpV3Codec.FX_NO_SUCH_FILE); sstr("No such file")
}) as SftpPacket.Status
assertEquals(7, s.id)
assertTrue(SftpV3Codec.statusToException(s) is FileNotFoundException)
val denied = SftpPacket.Status(1, SftpV3Codec.FX_PERMISSION_DENIED, "nope")
val ex = SftpV3Codec.statusToException(denied)
assertFalse(ex is FileNotFoundException)
assertTrue(ex.message!!.contains("permission denied"))
}
@Test
fun `parses HANDLE and DATA as binary`() {
val h = SftpV3Codec.parsePacket(body { writeByte(FXP_HANDLE); writeInt(1); sbin(byteArrayOf(0, 1, 2, 3)) }) as SftpPacket.Handle
assertArrayEquals(byteArrayOf(0, 1, 2, 3), h.handle)
val payload = ByteArray(300) { (it and 0xFF).toByte() }
val d = SftpV3Codec.parsePacket(body { writeByte(FXP_DATA); writeInt(2); sbin(payload) }) as SftpPacket.Data
assertEquals(2, d.id)
assertArrayEquals(payload, d.data)
}
@Test
fun `parses NAME with attrs - dir vs file, size, mtime`() {
val mtimeDir = 1_700_000_000
val pkt = SftpV3Codec.parsePacket(body {
writeByte(FXP_NAME); writeInt(5); writeInt(2)
// dir "sub", mode 0755
sstr("sub"); sstr("drwxr-xr-x 2 ian ian 4096 sub")
writeInt(SftpV3Codec.ATTR_SIZE or SftpV3Codec.ATTR_PERMISSIONS or SftpV3Codec.ATTR_ACMODTIME)
writeLong(4096L); writeInt(0x4000 or 0x1ED); writeInt(mtimeDir); writeInt(mtimeDir)
// file "f.txt", mode 0644
sstr("f.txt"); sstr("-rw-r--r-- 1 ian ian 123 f.txt")
writeInt(SftpV3Codec.ATTR_SIZE or SftpV3Codec.ATTR_PERMISSIONS or SftpV3Codec.ATTR_ACMODTIME)
writeLong(123L); writeInt(0x8000 or 0x1A4); writeInt(mtimeDir + 1); writeInt(mtimeDir + 1)
}) as SftpPacket.Name
assertEquals(listOf("sub", "f.txt"), pkt.names.map { it.filename })
val dir = pkt.names[0]
assertTrue(dir.attrs.isDirectory)
assertEquals(4096L, dir.attrs.size)
assertEquals("drwxr-xr-x", dir.attrs.permString())
assertEquals(mtimeDir * 1000L, dir.attrs.modifiedTimeMillis)
val file = pkt.names[1]
assertFalse(file.attrs.isDirectory)
assertEquals(123L, file.attrs.size)
assertEquals("-rw-r--r--", file.attrs.permString())
}
@Test
fun `parses ATTRS and detects symlink`() {
val pkt = SftpV3Codec.parsePacket(body {
writeByte(FXP_ATTRS)
writeInt(11)
writeInt(SftpV3Codec.ATTR_SIZE or SftpV3Codec.ATTR_PERMISSIONS)
writeLong(7L); writeInt(0xA000 or 0x1FF)
}) as SftpPacket.Attrs
assertEquals(11, pkt.id)
assertTrue(pkt.attrs.isSymlink)
assertFalse(pkt.attrs.isDirectory)
assertEquals(7L, pkt.attrs.size)
}
@Test
fun `attrs with no flags yields unknown permString and zero mtime`() {
val pkt = SftpV3Codec.parsePacket(body { writeByte(FXP_ATTRS); writeInt(1); writeInt(0) }) as SftpPacket.Attrs
assertEquals("", pkt.attrs.permString())
assertEquals(0L, pkt.attrs.modifiedTimeMillis)
assertFalse(pkt.attrs.isDirectory)
}
}