generated from ali/HarmonyTemplate
提交 Haven Android 仓库源码 v5.87.79
This commit is contained in:
@@ -0,0 +1,142 @@
|
||||
# Mosh Protocol Implementation
|
||||
|
||||
Pure Kotlin implementation of the mosh (mobile shell) client protocol,
|
||||
replacing the prebuilt C++ `libmoshclient.so` binary.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
SSH bootstrap (ConnectionsViewModel)
|
||||
└─ exec "mosh-server new" → parse MOSH CONNECT <port> <key>
|
||||
|
||||
MoshTransport (pure Kotlin, in-process)
|
||||
├─ MoshCrypto AES-128-OCB via Bouncy Castle
|
||||
├─ MoshConnection UDP socket, timestamps, zlib, fragments
|
||||
├─ WireFormat Hand-coded protobuf (mosh wire format)
|
||||
├─ UserStream Client→server state (keystrokes + resizes)
|
||||
└─ SSP engine State Synchronization Protocol
|
||||
│
|
||||
▼
|
||||
TerminalViewModel.onDataReceived → termlib emulator renders
|
||||
```
|
||||
|
||||
No PTY, no JNI, no native code. The mosh server sends VT100 escape
|
||||
sequences (via `Display::new_frame()`) which are fed directly to
|
||||
connectbot's termlib.
|
||||
|
||||
## Wire Format
|
||||
|
||||
### Packet structure
|
||||
```
|
||||
[8-byte nonce][AES-128-OCB(plaintext) + 16-byte auth tag]
|
||||
```
|
||||
|
||||
### Plaintext structure
|
||||
```
|
||||
[2-byte timestamp][2-byte timestamp_reply][10-byte fragment header][payload]
|
||||
```
|
||||
|
||||
### Fragment header
|
||||
```
|
||||
[8-byte fragment_id (uint64 BE)][2-byte combined (bit15=final, bits0-14=frag_num)]
|
||||
```
|
||||
|
||||
After fragment reassembly, the payload is **zlib decompressed**, then
|
||||
parsed as a `TransportBuffers.Instruction` protobuf.
|
||||
|
||||
### Nonce
|
||||
- 12-byte OCB nonce = `[4 zero bytes][8-byte nonce value]`
|
||||
- Nonce value: bit 63 = direction (0=client→server, 1=server→client),
|
||||
bits 0-62 = monotonic sequence number
|
||||
- The 8-byte nonce value is sent in the packet header
|
||||
|
||||
### Key
|
||||
- 128-bit AES key, base64-encoded (22 chars without padding) as `MOSH_KEY`
|
||||
|
||||
## Protobuf Definitions
|
||||
|
||||
Hand-coded encoder/decoder in `WireFormat.kt`. No protobuf plugin needed.
|
||||
Field numbers match upstream mosh `src/protobufs/`:
|
||||
|
||||
### `TransportBuffers.Instruction`
|
||||
| Field | Type | Number | Notes |
|
||||
|-------|--------|--------|-------|
|
||||
| protocol_version | uint32 | 1 | Always 2 |
|
||||
| old_num | uint64 | 2 | Base state for diff |
|
||||
| new_num | uint64 | 3 | Target state |
|
||||
| ack_num | uint64 | 4 | Latest received remote state |
|
||||
| throwaway_num | uint64 | 5 | Oldest state sender still has |
|
||||
| diff | bytes | 6 | Serialized UserMessage or HostMessage |
|
||||
| chaff | bytes | 7 | Random padding (ignored) |
|
||||
|
||||
**Critical**: All fields must be written explicitly, even when 0.
|
||||
Proto2 `has_xxx()` returns false for absent fields, and the mosh server
|
||||
uses `has_old_num()` to decide whether to apply the diff.
|
||||
|
||||
### `ClientBuffers` (client→server diff)
|
||||
```
|
||||
UserMessage { repeated Instruction instruction = 1; }
|
||||
Instruction { extensions 2 to max; }
|
||||
ext 2: Keystroke { optional bytes keys = 4; }
|
||||
ext 3: ResizeMessage { optional int32 width = 5; optional int32 height = 6; }
|
||||
```
|
||||
|
||||
### `ServerBuffers` (server→client diff)
|
||||
```
|
||||
HostMessage { repeated Instruction instruction = 1; }
|
||||
Instruction { extensions 2 to max; }
|
||||
ext 2: HostBytes { optional bytes hoststring = 4; }
|
||||
ext 3: ResizeMessage { optional int32 width = 5; optional int32 height = 6; }
|
||||
ext 7: EchoAck { optional uint64 echo_ack_num = 8; }
|
||||
```
|
||||
|
||||
## SSP State Machine
|
||||
|
||||
Two state spaces are synchronized independently:
|
||||
|
||||
1. **Client→Server (UserStream)**: keystrokes and resizes
|
||||
- Each byte is a separate action/state increment
|
||||
- `diffFrom(oldNum)` returns serialized `UserMessage` with actions since `oldNum`
|
||||
|
||||
2. **Server→Client (Complete terminal)**: VT100 escape sequences
|
||||
- `HostBytes.hoststring` contains output from `Display::new_frame()`
|
||||
- Fed directly to termlib — no local framebuffer needed
|
||||
|
||||
### Send timing
|
||||
- New keystrokes: send within 20ms
|
||||
- New ack to convey: send within 20ms
|
||||
- Retransmit unacked data: exponential backoff 100ms→200ms→400ms→800ms
|
||||
- Keepalive: every 3 seconds
|
||||
- Poll interval: 100ms max sleep between iterations
|
||||
|
||||
### Key invariants
|
||||
- `throwawayNum` must be from the **UserStream** state space (= `serverAckedOurNum`),
|
||||
NOT the terminal state space. Mixing these causes the server to discard
|
||||
UserStream states the client still references in `oldNum`.
|
||||
- Unconnected UDP socket on Android — connected sockets propagate ICMP errors
|
||||
from stale sessions as `PortUnreachableException`.
|
||||
|
||||
## Bugs Found During Implementation
|
||||
|
||||
1. **Missing `old_num` field**: Proto2 omits fields with default value (0).
|
||||
Mosh server checks `has_old_num()` and silently ignores diffs without it.
|
||||
Fix: always write all TransportInstruction fields.
|
||||
|
||||
2. **Wrong `throwaway_num` state space**: Was set to `remoteStateNum`
|
||||
(terminal states) instead of `serverAckedOurNum` (UserStream states).
|
||||
Server discarded UserStream states the client needed as diff bases.
|
||||
|
||||
3. **Connected UDP socket on Android**: `DatagramSocket.connect()` causes
|
||||
Android to deliver ICMP "port unreachable" as exceptions, killing the
|
||||
session when stale mosh-server processes exist on the same port.
|
||||
|
||||
4. **Main thread network**: `DatagramSocket` creation with DNS resolution
|
||||
triggers Android StrictMode. Socket creation deferred to IO coroutine.
|
||||
|
||||
## Not Implemented
|
||||
|
||||
- **Speculative local echo / prediction**: typed characters are not shown
|
||||
until the server echoes them back. Adds ~100ms perceived latency on LAN.
|
||||
- **Roaming detection**: UDP source address changes are handled by the
|
||||
mosh server automatically, but reconnection UI is not shown.
|
||||
- **RTT estimation**: timestamps are sent but not used for adaptive timing.
|
||||
@@ -0,0 +1,39 @@
|
||||
plugins {
|
||||
alias(libs.plugins.android.library)
|
||||
alias(libs.plugins.hilt)
|
||||
alias(libs.plugins.ksp)
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "sh.haven.core.mosh"
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
minSdk = 26
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
testOptions {
|
||||
unitTests.isReturnDefaultValues = true
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
api("sh.haven:ssp-transport:0.1.0")
|
||||
implementation(libs.coroutines.core)
|
||||
implementation(libs.coroutines.android)
|
||||
implementation(libs.hilt.android)
|
||||
ksp(libs.hilt.compiler)
|
||||
|
||||
testImplementation(libs.junit)
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!--
|
||||
MoshSessionManager.hasNetwork() reads connectivity through
|
||||
ConnectivityManager to gate the #421 dead-session escalation, so an
|
||||
offline device keeps waiting instead of giving up. Declared here so lint
|
||||
sees it when it analyses this library in isolation; the app module already
|
||||
requests it, so the merged permission set is unchanged.
|
||||
-->
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
</manifest>
|
||||
@@ -0,0 +1,246 @@
|
||||
package sh.haven.core.mosh
|
||||
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.launch
|
||||
import sh.haven.mosh.MoshLogger
|
||||
import sh.haven.mosh.network.AndroidUdpAdapter
|
||||
import sh.haven.mosh.network.UdpSocketProvider
|
||||
import sh.haven.mosh.transport.MoshTransport
|
||||
import java.io.Closeable
|
||||
import java.util.concurrent.ConcurrentLinkedQueue
|
||||
|
||||
private const val TAG = "MoshSession"
|
||||
|
||||
/**
|
||||
* Bridges a mosh transport session to the terminal emulator.
|
||||
*
|
||||
* Parallel to ReticulumSession: manages a transport instance and
|
||||
* shuttles terminal data between the mosh server and termlib.
|
||||
* No PTY or native code — the pure Kotlin MoshTransport handles
|
||||
* UDP, encryption, and protocol framing in-process.
|
||||
*/
|
||||
class MoshSession(
|
||||
val sessionId: String,
|
||||
val profileId: String,
|
||||
val label: String,
|
||||
private val serverIp: String,
|
||||
private val moshPort: Int,
|
||||
private val moshKey: String,
|
||||
private val onDataReceived: (ByteArray, Int, Int) -> Unit,
|
||||
private val onDisconnected: ((cleanExit: Boolean) -> Unit)? = null,
|
||||
private val initialCols: Int = 80,
|
||||
private val initialRows: Int = 24,
|
||||
private val verboseBuffer: ConcurrentLinkedQueue<String>? = null,
|
||||
/**
|
||||
* UDP socket factory. Defaults to a plain
|
||||
* [java.net.DatagramSocket] via [AndroidUdpAdapter]. When the
|
||||
* profile selects a tunnel, [MoshSessionManager.connectSession]
|
||||
* supplies a provider that routes UDP through the tunnel
|
||||
* ([sh.haven.core.tunnel.TunneledDatagramSocket]) — fix for #164.
|
||||
*/
|
||||
private val socketProvider: UdpSocketProvider =
|
||||
UdpSocketProvider { AndroidUdpAdapter() },
|
||||
/**
|
||||
* Reports whether the device has a usable network, so the transport can
|
||||
* tell a roaming session apart from one the server no longer has (#421).
|
||||
* Defaults to "assume online"; [MoshSessionManager] supplies the real
|
||||
* ConnectivityManager-backed check.
|
||||
*/
|
||||
private val networkAvailable: () -> Boolean = { true },
|
||||
) : Closeable {
|
||||
|
||||
@Volatile
|
||||
private var closed = false
|
||||
|
||||
private val startTime = System.currentTimeMillis()
|
||||
private val logger = object : MoshLogger {
|
||||
override fun d(tag: String, msg: String) {
|
||||
Log.d(tag, msg)
|
||||
verboseBuffer?.add("+${System.currentTimeMillis() - startTime}ms [$tag] $msg")
|
||||
}
|
||||
override fun e(tag: String, msg: String, throwable: Throwable?) {
|
||||
if (throwable != null) Log.e(tag, msg, throwable) else Log.e(tag, msg)
|
||||
verboseBuffer?.add("+${System.currentTimeMillis() - startTime}ms [$tag] ERROR: $msg${throwable?.let { " (${it.message})" } ?: ""}")
|
||||
}
|
||||
}
|
||||
|
||||
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
|
||||
private var transport: MoshTransport? = null
|
||||
|
||||
/**
|
||||
* Forwarded from [MoshTransport.stallSeconds]: seconds since the last
|
||||
* server packet once the connection has stalled, null while healthy.
|
||||
* The transport retries indefinitely — this is an indicator, not a
|
||||
* countdown to disconnect.
|
||||
*/
|
||||
private val _stallSeconds = MutableStateFlow<Int?>(null)
|
||||
val stallSeconds: StateFlow<Int?> = _stallSeconds.asStateFlow()
|
||||
|
||||
/**
|
||||
* Start the mosh transport: opens UDP socket, begins send/receive loops.
|
||||
*
|
||||
* Before wiring up the transport we also push one synthetic byte
|
||||
* sequence — [DECCKM_ON] — into the client-side emulator. See the
|
||||
* companion comment on that constant for why. This is the fix for
|
||||
* GlassOnTin/Haven#73.
|
||||
*/
|
||||
fun start() {
|
||||
if (closed) return
|
||||
Log.d(TAG, "Starting mosh transport for $sessionId: $serverIp:$moshPort")
|
||||
|
||||
// Put the client-side terminal into application cursor key mode
|
||||
// (DECCKM = on) BEFORE any server diff bytes arrive. Without this,
|
||||
// libvterm stays in normal cursor key mode for the entire mosh
|
||||
// session and Up/Down/Left/Right arrow keys come out as CSI
|
||||
// sequences (ESC [ A) instead of SS3 sequences (ESC O A), which
|
||||
// breaks Mutt, Emacs, less, and anything else that calls `tput
|
||||
// smkx`. See the DECCKM_ON companion for the full causal chain.
|
||||
if (!closed) {
|
||||
onDataReceived(DECCKM_ON, 0, DECCKM_ON.size)
|
||||
Log.d(TAG, "Pushed DECCKM_ON (${DECCKM_ON.size} bytes) to emulator for $sessionId")
|
||||
}
|
||||
|
||||
val t = MoshTransport(
|
||||
serverIp = serverIp,
|
||||
port = moshPort,
|
||||
key = moshKey,
|
||||
onOutput = { data, offset, len ->
|
||||
if (!closed) {
|
||||
onDataReceived(data, offset, len)
|
||||
}
|
||||
},
|
||||
onDisconnect = { cleanExit ->
|
||||
if (!closed) {
|
||||
Log.d(TAG, "Transport disconnected for $sessionId (clean=$cleanExit)")
|
||||
onDisconnected?.invoke(cleanExit)
|
||||
}
|
||||
},
|
||||
logger = logger,
|
||||
initialCols = initialCols,
|
||||
initialRows = initialRows,
|
||||
socketProvider = socketProvider,
|
||||
networkAvailable = networkAvailable,
|
||||
)
|
||||
transport = t
|
||||
t.start(scope)
|
||||
scope.launch {
|
||||
t.stallSeconds.collect { _stallSeconds.value = it }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send keyboard input to the mosh server.
|
||||
* Safe to call from any thread.
|
||||
*/
|
||||
fun sendInput(data: ByteArray) {
|
||||
if (closed) return
|
||||
transport?.sendInput(data)
|
||||
}
|
||||
|
||||
/**
|
||||
* Notify the mosh server of a terminal resize.
|
||||
*/
|
||||
fun resize(cols: Int, rows: Int) {
|
||||
if (closed) return
|
||||
transport?.resize(cols, rows)
|
||||
}
|
||||
|
||||
/**
|
||||
* Detach without closing the transport.
|
||||
* The mosh server keeps the session alive; we can reattach later.
|
||||
*/
|
||||
fun detach() {
|
||||
if (closed) return
|
||||
closed = true
|
||||
transport?.close()
|
||||
transport = null
|
||||
}
|
||||
|
||||
/** Drain captured transport logs. Returns null if verbose logging was not enabled. */
|
||||
fun drainTransportLog(): String? {
|
||||
val buf = verboseBuffer ?: return null
|
||||
if (buf.isEmpty()) return null
|
||||
val sb = StringBuilder()
|
||||
while (true) {
|
||||
val line = buf.poll() ?: break
|
||||
sb.appendLine(line)
|
||||
}
|
||||
return sb.toString().trimEnd()
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
if (closed) return
|
||||
closed = true
|
||||
transport?.close()
|
||||
transport = null
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* DECSET 1 — `ESC [ ? 1 h` — application cursor keys (DECCKM = on).
|
||||
*
|
||||
* We push this into the client-side emulator at session start.
|
||||
* It looks like an odd thing to do because nothing on the wire
|
||||
* ever asked for it, but it's the fix for a fundamental mismatch
|
||||
* between how mosh synchronises terminal state and how Haven's
|
||||
* emulator interprets that state:
|
||||
*
|
||||
* 1. Upstream mosh-server runs a real terminal emulator against
|
||||
* the pty. When mutt or emacs invokes `tput smkx`, the server
|
||||
* parses `ESC [ ? 1 h` and updates `Framebuffer::DrawState::
|
||||
* application_mode_cursor_keys = true`. Those bytes are then
|
||||
* CONSUMED by the server-side emulator; they do not enter the
|
||||
* wire protocol.
|
||||
*
|
||||
* 2. When mosh-server diffs two framebuffer states it uses
|
||||
* `Display::new_frame()` (mosh/src/terminal/terminaldisplay.cc)
|
||||
* to produce the VT100 sequence that transforms the old frame
|
||||
* into the new one. That sequence only emits cursor motion,
|
||||
* cell content, scroll, and window title. It DOES NOT emit
|
||||
* DECCKM, DECKPAM, or any other terminal mode command.
|
||||
*
|
||||
* 3. Upstream mosh-client compensates for this by writing
|
||||
* `display.open()` — which hard-codes `ESC [ ? 1 h` — to its
|
||||
* host terminal's STDOUT at startup (mosh/src/frontend/stmclient.cc
|
||||
* line ~76). Upstream mosh effectively says: "we always run
|
||||
* in application cursor key mode, starting from session
|
||||
* connect, regardless of what the server's DrawState looks
|
||||
* like right now."
|
||||
*
|
||||
* 4. Upstream mosh-client then forwards raw STDIN bytes to the
|
||||
* server as UserBytes (no translation). Because the host
|
||||
* terminal is in application mode, pressing Up produces
|
||||
* `ESC O A`, which travels through the wire, into the pty,
|
||||
* into mutt, and is recognised correctly.
|
||||
*
|
||||
* 5. Haven's mosh port is different: there's no host terminal,
|
||||
* libvterm IS the emulator. Libvterm runs
|
||||
* `vt->state->mode.cursor` as its DECCKM flag (termlib/.../
|
||||
* libvterm/src/keyboard.c `KEYCODE_CSI_CURSOR`). That flag
|
||||
* is only updated when libvterm's parser sees `ESC [ ? 1 h`
|
||||
* on its input stream. Because mosh strips that byte pattern
|
||||
* from the wire (step 2), libvterm never sees it and stays
|
||||
* in normal mode forever.
|
||||
*
|
||||
* 6. Pressing Up in Haven's mosh session therefore produces
|
||||
* `ESC [ A` (normal mode) instead of `ESC O A` (application
|
||||
* mode). Mutt, which `tput smkx`-ed on startup, expected
|
||||
* application mode and reports "Key is not bound".
|
||||
*
|
||||
* The minimal fix is to do what upstream mosh-client does at
|
||||
* step 3: push `ESC [ ? 1 h` into the local emulator at session
|
||||
* start, independently of the wire. Bash's readline binds
|
||||
* previous-history to both `ESC [ A` AND `ESC O A`, so forcing
|
||||
* application mode doesn't break bash either.
|
||||
*/
|
||||
internal val DECCKM_ON: ByteArray = byteArrayOf(
|
||||
0x1B, '['.code.toByte(), '?'.code.toByte(), '1'.code.toByte(), 'h'.code.toByte()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
package sh.haven.core.mosh
|
||||
|
||||
import android.util.Log
|
||||
import dagger.hilt.android.qualifiers.ApplicationContext
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.asStateFlow
|
||||
import kotlinx.coroutines.flow.update
|
||||
import sh.haven.mosh.network.UdpSocketProvider
|
||||
import java.io.Closeable
|
||||
import java.util.UUID
|
||||
import java.util.concurrent.ConcurrentLinkedQueue
|
||||
import java.util.concurrent.Executors
|
||||
import javax.inject.Inject
|
||||
import javax.inject.Singleton
|
||||
|
||||
private const val TAG = "MoshSessionManager"
|
||||
|
||||
/**
|
||||
* Manages active Mosh sessions across the app.
|
||||
* Parallel to ReticulumSessionManager: simple connect/disconnect lifecycle,
|
||||
* no reconnect logic — the transport itself survives network outages of
|
||||
* any length (it keeps re-syncing against the same key/port and rebinds
|
||||
* its socket for IP roaming), so a DISCONNECTED status here always means
|
||||
* the session is genuinely over (shell exited or fatal transport error).
|
||||
*
|
||||
* Uses pure Kotlin MoshTransport — no native binary or PTY needed.
|
||||
*/
|
||||
@Singleton
|
||||
class MoshSessionManager @Inject constructor(
|
||||
@ApplicationContext private val context: android.content.Context,
|
||||
) {
|
||||
|
||||
/**
|
||||
* Invoked with the profile id when a session ends *unexpectedly* — the
|
||||
* transport declared it dead while the device had a network (#421), or hit
|
||||
* a fatal local error. A clean server shutdown (the shell exited) never
|
||||
* fires this. The feature layer wires it to a single silent reconnect
|
||||
* attempt; there is deliberately no retry loop, so a reconnect that itself
|
||||
* fails leaves the session in ERROR rather than spinning.
|
||||
*/
|
||||
var onSessionDied: ((profileId: String, sessionId: String) -> Unit)? = null
|
||||
|
||||
/**
|
||||
* Whether the device currently has a network that is validated for internet
|
||||
* access. Used to gate the transport's #421 dead-session escalation, so a
|
||||
* genuinely offline phone still resumes its session on return (the #92
|
||||
* regression) and only an online-but-silent session is given up on.
|
||||
*/
|
||||
internal fun hasNetwork(): Boolean = try {
|
||||
val cm = context.getSystemService(android.net.ConnectivityManager::class.java)
|
||||
val caps = cm?.activeNetwork?.let { cm.getNetworkCapabilities(it) }
|
||||
caps != null &&
|
||||
caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
|
||||
caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
||||
} catch (e: Exception) {
|
||||
// Treat an unreadable connectivity state as "offline" so we fall back to
|
||||
// the conservative never-give-up behaviour rather than killing a session.
|
||||
Log.w(TAG, "Could not read connectivity state: ${e.message}")
|
||||
false
|
||||
}
|
||||
|
||||
data class SessionState(
|
||||
val sessionId: String,
|
||||
val profileId: String,
|
||||
val label: String,
|
||||
val status: Status,
|
||||
val serverIp: String = "",
|
||||
val moshPort: Int = 0,
|
||||
val moshKey: String = "",
|
||||
val moshSession: MoshSession? = null,
|
||||
/** Shell command to run after mosh connects (e.g. session manager attach). */
|
||||
val initialCommand: String? = null,
|
||||
/** SSH client kept alive from bootstrap for SFTP access (opaque Closeable). */
|
||||
val sshClient: Closeable? = null,
|
||||
/** Buffer for capturing transport logs when verbose logging is enabled. */
|
||||
val verboseBuffer: ConcurrentLinkedQueue<String>? = null,
|
||||
/**
|
||||
* UDP socket factory resolved at connect time. When non-null, the
|
||||
* transport routes packets through it instead of a raw
|
||||
* [java.net.DatagramSocket] — used for Mosh-over-tunnel sessions
|
||||
* per #164. null = direct UDP (pre-#164 behaviour).
|
||||
*/
|
||||
val socketProvider: UdpSocketProvider? = 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 ioExecutor = Executors.newSingleThreadExecutor { r ->
|
||||
Thread(r, "mosh-session-io").apply { isDaemon = true }
|
||||
}
|
||||
|
||||
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): String {
|
||||
val sessionId = UUID.randomUUID().toString()
|
||||
_sessions.update { map ->
|
||||
map + (sessionId to SessionState(
|
||||
sessionId = sessionId,
|
||||
profileId = profileId,
|
||||
label = label,
|
||||
status = SessionState.Status.CONNECTING,
|
||||
))
|
||||
}
|
||||
return sessionId
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect a registered session using the pure Kotlin mosh transport.
|
||||
* Stores connection parameters; the actual transport starts when
|
||||
* [createTerminalSession] is called.
|
||||
*/
|
||||
fun connectSession(
|
||||
sessionId: String,
|
||||
serverIp: String,
|
||||
moshPort: Int,
|
||||
moshKey: String,
|
||||
cols: Int,
|
||||
rows: Int,
|
||||
sshClient: Closeable? = null,
|
||||
verboseBuffer: ConcurrentLinkedQueue<String>? = null,
|
||||
socketProvider: UdpSocketProvider? = null,
|
||||
) {
|
||||
_sessions.value[sessionId]
|
||||
?: throw IllegalStateException("Session $sessionId not found")
|
||||
|
||||
Log.d(
|
||||
TAG,
|
||||
"Connecting mosh session: $serverIp:$moshPort " +
|
||||
"(ssh kept alive: ${sshClient != null}, " +
|
||||
"tunneled: ${socketProvider != null})",
|
||||
)
|
||||
|
||||
_sessions.update { map ->
|
||||
val existing = map[sessionId] ?: return@update map
|
||||
map + (sessionId to existing.copy(
|
||||
status = SessionState.Status.CONNECTED,
|
||||
serverIp = serverIp,
|
||||
moshPort = moshPort,
|
||||
moshKey = moshKey,
|
||||
sshClient = sshClient,
|
||||
verboseBuffer = verboseBuffer,
|
||||
socketProvider = socketProvider,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the SSH client for a connected mosh profile (for SFTP access).
|
||||
* Returns the opaque Closeable — caller must cast to SshClient.
|
||||
*/
|
||||
fun getSshClientForProfile(profileId: String): Closeable? {
|
||||
return _sessions.value.values
|
||||
.filter { it.profileId == profileId && it.status == SessionState.Status.CONNECTED }
|
||||
.firstOrNull { it.sshClient != null }
|
||||
?.sshClient
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a [MoshSession] for a connected session.
|
||||
* The transport starts immediately and terminal output flows via [onDataReceived].
|
||||
*/
|
||||
fun createTerminalSession(
|
||||
sessionId: String,
|
||||
onDataReceived: (ByteArray, Int, Int) -> Unit,
|
||||
): MoshSession? {
|
||||
val session = _sessions.value[sessionId] ?: return null
|
||||
if (session.status != SessionState.Status.CONNECTED) return null
|
||||
if (session.moshSession != null) return null
|
||||
if (session.serverIp.isEmpty()) return null
|
||||
|
||||
val moshSession = MoshSession(
|
||||
sessionId = sessionId,
|
||||
profileId = session.profileId,
|
||||
label = session.label,
|
||||
serverIp = session.serverIp,
|
||||
moshPort = session.moshPort,
|
||||
moshKey = session.moshKey,
|
||||
onDataReceived = onDataReceived,
|
||||
onDisconnected = { cleanExit ->
|
||||
// The transport rides out network silence — it retries with the
|
||||
// same (port, key) until connectivity returns and SSP re-syncs,
|
||||
// so an outage of any length does not reach this callback. It
|
||||
// fires when the server announced shutdown (shell exited,
|
||||
// clean=true), when the transport hit a fatal local error, or
|
||||
// when it declared the session dead because we were online and
|
||||
// silent for a long time (#421 — both clean=false).
|
||||
Log.d(TAG, "Mosh session $sessionId disconnected — " +
|
||||
"clean=$cleanExit, server=${session.serverIp}:${session.moshPort}")
|
||||
updateStatus(sessionId, SessionState.Status.DISCONNECTED)
|
||||
// A clean exit means the user's shell ended — reconnecting
|
||||
// would resurrect a session they deliberately closed. Only the
|
||||
// unexpected endings get a reconnect attempt.
|
||||
if (!cleanExit) onSessionDied?.invoke(session.profileId, sessionId)
|
||||
},
|
||||
verboseBuffer = session.verboseBuffer,
|
||||
socketProvider = session.socketProvider
|
||||
?: UdpSocketProvider { sh.haven.mosh.network.AndroidUdpAdapter() },
|
||||
networkAvailable = ::hasNetwork,
|
||||
)
|
||||
|
||||
_sessions.update { map ->
|
||||
val existing = map[sessionId] ?: return@update map
|
||||
map + (sessionId to existing.copy(moshSession = moshSession))
|
||||
}
|
||||
|
||||
return moshSession
|
||||
}
|
||||
|
||||
fun isReadyForTerminal(sessionId: String): Boolean {
|
||||
val session = _sessions.value[sessionId] ?: return false
|
||||
return session.status == SessionState.Status.CONNECTED &&
|
||||
session.moshSession == null &&
|
||||
session.serverIp.isNotEmpty()
|
||||
}
|
||||
|
||||
/**
|
||||
* Detach a terminal session without killing the mosh transport.
|
||||
*/
|
||||
fun detachTerminalSession(sessionId: String) {
|
||||
val session = _sessions.value[sessionId] ?: return
|
||||
session.moshSession?.detach()
|
||||
_sessions.update { map ->
|
||||
val existing = map[sessionId] ?: return@update map
|
||||
map + (sessionId to existing.copy(moshSession = null))
|
||||
}
|
||||
}
|
||||
|
||||
fun setInitialCommand(sessionId: String, command: String) {
|
||||
_sessions.update { map ->
|
||||
val existing = map[sessionId] ?: return@update map
|
||||
map + (sessionId to existing.copy(initialCommand = command))
|
||||
}
|
||||
}
|
||||
|
||||
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 }
|
||||
ioExecutor.execute {
|
||||
try {
|
||||
session.sshClient?.close()
|
||||
session.moshSession?.close()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "tearDown failed for $sessionId", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send [text] as UTF-8 to the mosh session's input. Throws when no
|
||||
* session exists or its transport is gone — matches the
|
||||
* SshSessionManager/LocalSessionManager sendInput contract so the
|
||||
* agent input dispatcher can chain transports (#366).
|
||||
*/
|
||||
fun sendInput(sessionId: String, text: String) {
|
||||
val session = _sessions.value[sessionId]
|
||||
?: throw IllegalStateException("No mosh session: $sessionId")
|
||||
val mosh = session.moshSession
|
||||
?: throw IllegalStateException("Mosh session $sessionId has no live transport")
|
||||
mosh.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 } }
|
||||
ioExecutor.execute {
|
||||
toRemove.forEach { session ->
|
||||
try {
|
||||
session.sshClient?.close()
|
||||
session.moshSession?.close()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "tearDown failed for ${session.sessionId}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun disconnectAll() {
|
||||
val snapshot = _sessions.value.values.toList()
|
||||
_sessions.update { emptyMap() }
|
||||
ioExecutor.execute {
|
||||
snapshot.forEach { session ->
|
||||
try {
|
||||
session.sshClient?.close()
|
||||
session.moshSession?.close()
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "tearDown failed for ${session.sessionId}", 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
|
||||
}
|
||||
|
||||
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,104 @@
|
||||
package sh.haven.core.mosh
|
||||
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertArrayEquals
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
|
||||
/**
|
||||
* Regression test for [#73](https://github.com/GlassOnTin/Haven/issues/73).
|
||||
*
|
||||
* Pins the fix's load-bearing invariant: `MoshSession.start()` must push
|
||||
* a DECCKM-on byte sequence (`ESC [ ? 1 h`) into the client-side emulator
|
||||
* via [onDataReceived] BEFORE any transport bytes arrive. Without that
|
||||
* init, libvterm stays in normal cursor key mode and arrow keys come
|
||||
* out as `ESC [ A` instead of `ESC O A`, which breaks Mutt/Emacs/less
|
||||
* inside mosh sessions. See the companion doc on
|
||||
* [MoshSession.DECCKM_ON] for the full causal chain.
|
||||
*
|
||||
* The test deliberately points the transport at `127.0.0.1:0` so the
|
||||
* UDP bind may or may not succeed in the test environment — we only
|
||||
* care that the DECCKM init has been delivered **synchronously** before
|
||||
* the transport-start coroutine runs. The session is closed immediately
|
||||
* after the assertion so no network traffic or lingering coroutines
|
||||
* survive.
|
||||
*/
|
||||
class MoshSessionDecckmTest {
|
||||
|
||||
// 16 zero bytes, base64-encoded. Mosh's OCB key length.
|
||||
private val zeroKey = "AAAAAAAAAAAAAAAAAAAAAA=="
|
||||
|
||||
private data class Capture(val bytes: ByteArray, val offset: Int, val length: Int) {
|
||||
fun snapshot(): ByteArray = bytes.copyOfRange(offset, offset + length)
|
||||
}
|
||||
|
||||
private val received = CopyOnWriteArrayList<Capture>()
|
||||
private lateinit var session: MoshSession
|
||||
|
||||
@After
|
||||
fun tearDown() {
|
||||
if (this::session.isInitialized) {
|
||||
session.close()
|
||||
}
|
||||
}
|
||||
|
||||
private fun newSession(): MoshSession = MoshSession(
|
||||
sessionId = "test-session",
|
||||
profileId = "test-profile",
|
||||
label = "test",
|
||||
serverIp = "127.0.0.1",
|
||||
moshPort = 0, // ephemeral; UDP connect won't route but we don't need it to
|
||||
moshKey = zeroKey,
|
||||
onDataReceived = { data, offset, length ->
|
||||
received.add(Capture(data.copyOf(), offset, length))
|
||||
},
|
||||
)
|
||||
|
||||
@Test
|
||||
fun `start pushes DECCKM-on to the emulator synchronously before starting the transport`() {
|
||||
session = newSession()
|
||||
session.start()
|
||||
|
||||
// The DECCKM init is delivered by the synchronous portion of
|
||||
// start() before t.start(scope) launches any coroutines, so it
|
||||
// must already be present the moment start() returns.
|
||||
assertTrue("no onDataReceived call made by start", received.isNotEmpty())
|
||||
val first = received.first()
|
||||
assertArrayEquals(
|
||||
"first bytes delivered to the emulator must be ESC [ ? 1 h " +
|
||||
"(DECCKM on) — see MoshSession.DECCKM_ON for the rationale",
|
||||
MoshSession.DECCKM_ON,
|
||||
first.snapshot(),
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `DECCKM_ON is exactly 5 bytes forming the ESC bracket ? 1 h CSI sequence`() {
|
||||
// Guard against typos in the constant. The literal is small enough
|
||||
// that spelling it out in the assertion is clearer than any indirection.
|
||||
assertEquals(5, MoshSession.DECCKM_ON.size)
|
||||
assertEquals(0x1B.toByte(), MoshSession.DECCKM_ON[0])
|
||||
assertEquals('['.code.toByte(), MoshSession.DECCKM_ON[1])
|
||||
assertEquals('?'.code.toByte(), MoshSession.DECCKM_ON[2])
|
||||
assertEquals('1'.code.toByte(), MoshSession.DECCKM_ON[3])
|
||||
assertEquals('h'.code.toByte(), MoshSession.DECCKM_ON[4])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun `start is a no-op after close — must not emit DECCKM twice`() {
|
||||
session = newSession()
|
||||
session.start()
|
||||
val firstCount = received.size
|
||||
session.close()
|
||||
session.start()
|
||||
// Second start() on a closed session should do nothing, not
|
||||
// push a stale DECCKM init into a torn-down emulator.
|
||||
assertEquals(
|
||||
"start after close must not push additional bytes",
|
||||
firstCount,
|
||||
received.size,
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user