SSH, Telnet and rlogin: rlogin on Android, all three on iOS

- shared: TelnetCodec and RloginCodec (sans-I/O), and LoginBridge for Swift
- Android: rlogin directory entries (RloginLink on the shared codec)
- iOS: a Remote screen from the Terminal tab; SSH on SwiftNIO SSH
  (ios/DModemSSH, tested against a real sshd), Telnet and rlogin on
  Network with the shared codecs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B82eRSV65geuGd6zMt2V6r
This commit is contained in:
Claude committed 2026-11-12 12:41:55 +00:00
1 parent b61fa7f24b
commit f1eb22c591
21 files changed
+1504 -11

No files matched your search

+5
View File
@@ -234,6 +234,11 @@ jobs:
env:
DMODEM_HOST_BUILD: ${{ github.workspace }}/build-host
# the iOS app's SSH client (SwiftNIO SSH); its login tests run when
# DMODEM_SSH_TEST names an sshd (host:port:user:password), else skip
- name: DModemSSH (Swift)
run: swift test --package-path ios/DModemSSH
# (Apple's ways on Linux: the portable fallbacks the iOS build has)
- name: Engine test, Apple's fallbacks
run: |
@@ -0,0 +1,124 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.android.rlogin
import org.dmodem.app.android.terminal.TerminalLink
import org.dmodem.app.net.RloginCodec
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.io.IOException
import java.io.OutputStream
import java.net.InetSocketAddress
import java.net.Socket
import java.util.concurrent.CopyOnWriteArrayList
/**
* An rlogin connection (RFC 1282), the protocol the shared [RloginCodec]:
* the handshake with [user] as both names and [term], the window's size
* once the server asks. Java's sockets can't read urgent data apart, so
* it comes in the stream (the codec's inlineUrgent).
*/
class RloginLink(
val host: String,
val port: Int = 513,
private val user: String,
term: String = "xterm",
cols: Int = 80,
rows: Int = 24,
) : TerminalLink {
private val _state = MutableStateFlow<TerminalLink.State>(TerminalLink.State.Connecting)
override val state: StateFlow<TerminalLink.State> = _state.asStateFlow()
private val listeners = CopyOnWriteArrayList<TerminalLink.Listener>()
private val codec = RloginCodec(user, term, cols, rows, inlineUrgent = true)
@Volatile private var socket: Socket? = null
@Volatile private var out: OutputStream? = null
@Volatile private var closing = false
override fun addListener(l: TerminalLink.Listener) {
listeners.add(l)
}
override fun removeListener(l: TerminalLink.Listener) {
listeners.remove(l)
}
/** the connection made, in a thread of its own */
fun connect() {
Thread({ run() }, "rlogin-$host").apply { isDaemon = true }.start()
}
private fun run() {
try {
val s = Socket()
socket = s
s.connect(InetSocketAddress(host, port), 20_000)
s.tcpNoDelay = true
// (rlogind's urgent byte: in the stream, where we can see it)
s.oobInline = true
out = s.getOutputStream()
synchronized(codec) { codec.connected() }
flush()
_state.value = TerminalLink.State.Open
val inp = s.getInputStream()
val buf = ByteArray(8192)
while (true) {
val n = inp.read(buf)
if (n < 0) break
val screen = synchronized(codec) {
codec.feed(buf, n)
codec.screen()
}
flush()
if (screen.isNotEmpty()) for (l in listeners) l.onData(screen, screen.size)
}
closed(if (closing) null else "connection closed by $host")
} catch (e: IOException) {
closed(if (closing) null else (e.message ?: e.javaClass.simpleName))
}
}
/** what the codec has for the server, written */
private fun flush(): Boolean {
val o = out ?: return false
val b = synchronized(codec) { codec.output() }
if (b.isEmpty()) return true
return try {
synchronized(o) {
o.write(b)
o.flush()
}
true
} catch (_: IOException) {
false
}
}
override fun write(data: ByteArray, offset: Int, length: Int): Boolean {
if (_state.value !is TerminalLink.State.Open) return false
synchronized(codec) { codec.type(data.copyOfRange(offset, offset + length)) }
return flush()
}
/** the new size, sent (on a thread of its own) if the server asked for sizes */
override fun resize(cols: Int, rows: Int) {
synchronized(codec) { codec.resize(cols, rows) }
Thread({ flush() }, "rlogin-size").start()
}
private fun closed(reason: String?) {
if (_state.value is TerminalLink.State.Closed) return
_state.value = TerminalLink.State.Closed(reason)
try {
socket?.close()
} catch (_: IOException) {
}
}
override fun close() {
closing = true
closed(null)
}
}
@@ -14,19 +14,19 @@ import java.io.File
import java.util.UUID
/** How an entry is reached. */
enum class EntryKind(val label: String) { MODEM("Modem (dial)"), SSH("SSH"), TELNET("Telnet") }
enum class EntryKind(val label: String) { MODEM("Modem (dial)"), SSH("SSH"), TELNET("Telnet"), RLOGIN("rlogin") }
/** How an SSH entry logs in. */
enum class SshAuth(val label: String) { PASSWORD("Password"), KEY("Key") }
/** A system to reach: a BBS, a host, an ISP; by the modem, SSH or Telnet. */
/** A system to reach: a BBS, a host, an ISP; by the modem, SSH, Telnet or rlogin. */
data class DialEntry(
val id: String = UUID.randomUUID().toString(),
val name: String = "",
val kind: EntryKind = EntryKind.MODEM,
/** what ATD dials: a number, or a SIP user (MODEM) */
val number: String = "",
/** the host, its port and the user (SSH, TELNET) */
/** the host, its port and the user (SSH, TELNET, RLOGIN) */
val host: String = "",
val port: Int = 0,
val user: String = "",
@@ -52,13 +52,14 @@ data class DialEntry(
val agentConfirm: Boolean = true,
) {
/** the port to connect to: the entry's, or its kind's */
val portOrDefault: Int get() = if (port > 0) port else if (kind == EntryKind.TELNET) 23 else 22
val portOrDefault: Int get() = if (port > 0) port else defaultPort(kind)
/** what it is reached at, as one line */
val address: String get() = when (kind) {
EntryKind.MODEM -> number
EntryKind.SSH -> (if (user.isNotEmpty()) "$user@" else "") + host + (if (port > 0 && port != 22) ":$port" else "")
EntryKind.TELNET -> host + (if (port > 0 && port != 23) ":$port" else "")
EntryKind.RLOGIN -> (if (user.isNotEmpty()) "$user@" else "") + host + (if (port > 0 && port != 513) ":$port" else "")
}
/** enough to reach it */
@@ -66,6 +67,7 @@ data class DialEntry(
EntryKind.MODEM -> number.isNotBlank()
EntryKind.SSH -> host.isNotBlank() && user.isNotBlank() && (auth == SshAuth.PASSWORD || keyId.isNotEmpty())
EntryKind.TELNET -> host.isNotBlank()
EntryKind.RLOGIN -> host.isNotBlank() && user.isNotBlank()
}
/** the entry as stored in directory.json */
@@ -78,6 +80,13 @@ data class DialEntry(
.put("forwards", org.json.JSONArray(forwards)).put("agent", agentForwarding).put("agentConfirm", agentConfirm)
companion object {
/** [kind]'s port: SSH's 22, Telnet's 23, rlogin's 513 */
fun defaultPort(kind: EntryKind): Int = when (kind) {
EntryKind.TELNET -> 23
EntryKind.RLOGIN -> 513
else -> 22
}
/** an entry from its JSON, defaults for what's missing or unknown (a new id if it has none) */
fun fromJson(o: JSONObject) = DialEntry(
id = o.optString("id").ifEmpty { UUID.randomUUID().toString() },
@@ -27,6 +27,7 @@ import org.dmodem.app.android.ssh.PromptBroker
import org.dmodem.app.android.ssh.SecretBox
import org.dmodem.app.android.ssh.SshKeys
import org.dmodem.app.android.ssh.SshLink
import org.dmodem.app.android.rlogin.RloginLink
import org.dmodem.app.android.telnet.TelnetLink
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -96,7 +97,7 @@ object Terminal {
}
/**
* An SSH or Telnet entry opened in a new session (on the screen from
* An SSH, Telnet or rlogin entry opened in a new session (on the screen from
* now): null when it is on its way, else why it can't be.
*/
suspend fun open(context: Context, e: DialEntry): String? {
@@ -135,12 +136,21 @@ object Terminal {
termType = telnetType(profile, charset),
cols = cols, rows = rows,
).also { it.connect() }
EntryKind.RLOGIN -> RloginLink(
e.host.trim(), e.portOrDefault, e.user.trim(),
term = profile.term,
cols = cols, rows = rows,
).also { it.connect() }
EntryKind.MODEM -> return "a modem entry is dialled, not opened"
}
val s = TerminalSession(
link,
label = e.name.ifBlank { e.address },
kind = if (e.kind == EntryKind.SSH) TerminalSession.Kind.SSH else TerminalSession.Kind.TELNET,
kind = when (e.kind) {
EntryKind.SSH -> TerminalSession.Kind.SSH
EntryKind.RLOGIN -> TerminalSession.Kind.RLOGIN
else -> TerminalSession.Kind.TELNET
},
entry = e,
) { app.getExternalFilesDir("captures") }
s.profile = profile
@@ -42,7 +42,7 @@ class TerminalSession(
/** where captures go */
private val captureDir: () -> File?,
) {
enum class Kind { MODEM, SSH, TELNET, LOCAL, LINUX }
enum class Kind { MODEM, SSH, TELNET, RLOGIN, LOCAL, LINUX }
/** a program on this phone (Android's shell, or the Linux system's): not a connection */
val isLocal: Boolean get() = kind == Kind.LOCAL || kind == Kind.LINUX
@@ -72,7 +72,7 @@ fun DirectoryScreen(modifier: Modifier = Modifier, onDialed: () -> Unit) {
Column(Modifier.fillMaxSize().padding(24.dp), verticalArrangement = Arrangement.Center) {
Text("No systems yet", style = MaterialTheme.typography.titleMedium)
Text(
"Add a BBS, a host or an ISP: by the modem (its number or SIP user and the AT commands it needs), SSH or Telnet.",
"Add a BBS, a host or an ISP: by the modem (its number or SIP user and the AT commands it needs), SSH, Telnet or rlogin.",
style = MaterialTheme.typography.bodyMedium,
)
}
@@ -174,14 +174,17 @@ internal fun EntryDialog(entry: DialEntry, onSave: (DialEntry) -> Unit, onDismis
label = { Text("AT commands before dialling (; between)") }, singleLine = true,
)
}
EntryKind.SSH, EntryKind.TELNET -> {
EntryKind.SSH, EntryKind.TELNET, EntryKind.RLOGIN -> {
OutlinedTextField(e.host, { e = e.copy(host = it.trim()) }, label = { Text("Host") }, singleLine = true)
OutlinedTextField(
if (e.port > 0) e.port.toString() else "",
{ v -> e = e.copy(port = v.filter { it.isDigit() }.take(5).toIntOrNull() ?: 0) },
label = { Text("Port (${if (e.kind == EntryKind.SSH) 22 else 23})") }, singleLine = true,
label = { Text("Port (${DialEntry.defaultPort(e.kind)})") }, singleLine = true,
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Number),
)
if (e.kind == EntryKind.RLOGIN) {
OutlinedTextField(e.user, { e = e.copy(user = it.trim()) }, label = { Text("User") }, singleLine = true)
}
if (e.kind == EntryKind.SSH) {
OutlinedTextField(e.user, { e = e.copy(user = it.trim()) }, label = { Text("User") }, singleLine = true)
Choice("Log in with", e.auth.label, SshAuth.entries.map { it.label to it }) { e = e.copy(auth = it) }
@@ -424,7 +424,11 @@ private fun linkText(s: TerminalSession, st: TerminalLink.State, title: String):
}
return if (title.isNotBlank() && st == TerminalLink.State.Open) "$state — $title" else state
}
val what = if (s.kind == TerminalSession.Kind.SSH) "SSH" else "Telnet"
val what = when (s.kind) {
TerminalSession.Kind.SSH -> "SSH"
TerminalSession.Kind.RLOGIN -> "rlogin"
else -> "Telnet"
}
val where = s.entry?.address ?: s.label
val state = when (st) {
TerminalLink.State.Connecting -> "Connecting to $where…"
@@ -0,0 +1,62 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.android.rlogin
import org.dmodem.app.android.terminal.TerminalLink
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Test
import java.io.ByteArrayOutputStream
import java.net.ServerSocket
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
/** An rlogin login against a server on the loopback: the handshake, its urgent window request, data both ways. */
class RloginLinkTest {
@Test
fun logsInAndAnswersTheWindowRequest() {
val server = ServerSocket(0)
val got = LinkedBlockingQueue<ByteArray>()
val t = Thread {
server.accept().use { c ->
val inp = c.getInputStream()
val buf = ByteArray(256)
// the handshake: 4 NUL-ended strings
val hs = ByteArrayOutputStream()
var nuls = 0
while (nuls < 4) {
val b = inp.read()
if (b < 0) return@Thread
hs.write(b)
if (b == 0) nuls++
}
got.put(hs.toByteArray())
c.getOutputStream().write(0)
c.sendUrgentData(0x80)
c.getOutputStream().write("login: ".toByteArray())
// the window's size, then what's typed
val n = inp.read(buf, 0, 12)
got.put(buf.copyOf(n))
val k = inp.read(buf)
got.put(buf.copyOf(k))
}
}.apply { start() }
val link = RloginLink("127.0.0.1", server.localPort, "alice", term = "vt100", cols = 80, rows = 24)
val screen = LinkedBlockingQueue<String>()
link.addListener(TerminalLink.Listener { d, n -> screen.put(String(d, 0, n, Charsets.ISO_8859_1)) })
link.connect()
assertEquals("\u0000alice\u0000alice\u0000vt100/38400\u0000", String(got.poll(10, TimeUnit.SECONDS)!!, Charsets.ISO_8859_1))
assertArrayEquals(
byteArrayOf(-1, -1, 's'.code.toByte(), 's'.code.toByte(), 0, 24, 0, 80, 2, -128, 1, -128),
got.poll(10, TimeUnit.SECONDS),
)
val shown = StringBuilder()
while (!shown.contains("login: ")) shown.append(screen.poll(10, TimeUnit.SECONDS)!!)
assertEquals("login: ", shown.toString())
link.write("alice\r".toByteArray())
assertEquals("alice\r", String(got.poll(10, TimeUnit.SECONDS)!!))
link.close()
t.join(5000)
server.close()
}
}
+8
View File
@@ -152,6 +152,14 @@
- **Dial**: the dialing directory: each system's number (or SIP user), the
AT commands it needs before ATD, its terminal type, character set and backspace; one
tap starts the modem if it is off and dials.
- **Remote logins**: a server reached over the internet instead of the
modem, in a terminal session of its own. On Android a directory entry
connects by SSH, Telnet or rlogin (rlogin: the user's name sent as both
names, the window's size when the server asks). On iOS the Terminal
tab's network button opens the Remote screen: SSH (a password login on
SwiftNIO SSH, `ios/DModemSSH`; the server's key kept the first time
it's trusted; Ed25519 and ECDSA host keys), Telnet or rlogin. Telnet
and rlogin are the shared Kotlin's (`org.dmodem.app.net`).
- **Log**: the modem's and SIP's log (Copy for all of it).
- **AT commands** (Settings, AT commands, and the terminal's menu): the
AT command reference, D-Modem's manual (`docs/at_commands.pdf`, the
+2
View File
@@ -25,6 +25,8 @@ final class AppModel: ObservableObject {
let session = ModemSession()
let terminal = TerminalModel()
/// a login to a server by SSH, Telnet or rlogin, in a terminal of its own
let remote = RemoteModel()
/// the fax calls, transfers and dial-up the modem is lent to
let jobs: JobsModel
private let store = SettingsStore()
+4
View File
@@ -38,6 +38,10 @@ private struct TerminalTab: View {
var body: some View {
TerminalScreen(model: model.terminal)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
NavigationLink { RemoteView(model: model.remote) } label: { Image(systemName: "network") }
.accessibilityLabel("Connect to a server by SSH, Telnet or rlogin")
}
ToolbarItem(placement: .primaryAction) {
Button { transfers = true } label: { Image(systemName: "arrow.up.arrow.down.circle") }
.accessibilityLabel("File transfer")
+271
View File
@@ -0,0 +1,271 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import CryptoKit
import DModemShared
import DModemSSH
import Foundation
import Network
/// A login to a server by SSH, Telnet or rlogin, in a terminal of its own
/// (beside the modem's). SSH is DModemSSH's (SwiftNIO SSH), its host keys
/// kept here the first time they're accepted; Telnet and rlogin a TCP
/// connection (Network) with the shared Kotlin's protocol (LoginBridge).
@MainActor
final class RemoteModel: ObservableObject {
enum Proto: String, CaseIterable, Identifiable {
case ssh = "SSH", telnet = "Telnet", rlogin = "rlogin"
var id: String { rawValue }
var defaultPort: Int {
switch self {
case .ssh: return 22
case .telnet: return 23
case .rlogin: return 513
}
}
}
/// a question for the user, answered with [answer]
enum Question: Identifiable {
case password(host: String, reason: String)
case newHostKey(host: String, fingerprint: String)
var id: String {
switch self {
case .password(let h, let r): return "pw \(h) \(r)"
case .newHostKey(let h, let f): return "key \(h) \(f)"
}
}
}
@Published var proto: Proto { didSet { save() } }
@Published var host: String { didSet { save() } }
/// empty: the protocol's
@Published var port: String { didSet { save() } }
@Published var user: String { didSet { save() } }
@Published private(set) var running = false
@Published private(set) var status = "Not connected"
@Published var question: Question?
let terminal = TerminalModel()
private var answerQuestion: ((String?) -> Void)?
private var ssh: SSHShell?
private var connection: NWConnection?
private var login: LoginBridge?
private var cols = 80, rows = 24
private let defaults = UserDefaults.standard
init() {
proto = Proto(rawValue: defaults.string(forKey: "remoteProtocol") ?? "") ?? .ssh
host = defaults.string(forKey: "remoteHost") ?? ""
port = defaults.string(forKey: "remotePort") ?? ""
user = defaults.string(forKey: "remoteUser") ?? ""
terminal.send = { [weak self] d in self?.send(d) }
terminal.onResize = { [weak self] c, r in self?.resized(c, r) }
}
private func save() {
defaults.set(proto.rawValue, forKey: "remoteProtocol")
defaults.set(host, forKey: "remoteHost")
defaults.set(port, forKey: "remotePort")
defaults.set(user, forKey: "remoteUser")
}
var portNumber: Int { port.isEmpty ? proto.defaultPort : (Int(port) ?? 0) }
/// enough to connect
var complete: Bool {
!host.trimmingCharacters(in: .whitespaces).isEmpty && (1...65535).contains(portNumber) &&
(proto == .telnet || !user.trimmingCharacters(in: .whitespaces).isEmpty)
}
// MARK: - connecting
func connect() {
guard !running, complete else { return }
let h = host.trimmingCharacters(in: .whitespaces)
let u = user.trimmingCharacters(in: .whitespaces)
let p = portNumber
// (a Unix host's UTF-8 over SSH; a BBS's CP437 over Telnet and rlogin)
terminal.bridge.setLook(themeId: "vga", boldBright: true, iceColors: false, charset: proto == .ssh ? "UTF8" : "CP437")
let what = "Connecting to \(h) port \(p) by \(proto.rawValue)"
status = what
show("\u{1b}[0m[\(what)]\r\n")
running = true
cols = terminal.cols
rows = terminal.rows
if proto == .ssh {
startSSH(host: h, port: p, user: u)
} else {
startSocket(host: h, port: p, user: u)
}
}
func disconnect() { ended(nil) }
private func startSSH(host: String, port: Int, user: String) {
let s = SSHShell(host: host, port: port, user: user, term: "xterm-256color", cols: cols, rows: rows)
s.onData = { [weak self] d in Task { @MainActor in self?.terminal.feed(d) } }
s.onClose = { [weak self] why in Task { @MainActor in self?.ended(why) } }
s.verifyHostKey = { [weak self] key, ok in
Task { @MainActor in
guard let self else { return ok(false) }
self.checkHostKey(host: host, port: port, key: key, ok)
}
}
s.askPassword = { [weak self] reason, done in
Task { @MainActor in
guard let self else { return done(nil) }
self.ask(.password(host: "\(user)@\(host)", reason: reason), done)
}
}
ssh = s
status = "Connected by SSH"
s.connect()
}
/// the host's key: the one kept for it, or the user asked to accept a new one; a changed one refused
private func checkHostKey(host: String, port: Int, key: String, _ ok: @escaping (Bool) -> Void) {
let name = port == 22 ? host : "[\(host)]:\(port)"
var known = defaults.dictionary(forKey: "sshKnownHosts") as? [String: String] ?? [:]
if let k = known[name] {
if k != key {
show("\r\n[The host key of \(name) has changed. If that is expected, forget it in the Remote screen's menu.]\r\n")
}
ok(k == key)
return
}
ask(.newHostKey(host: name, fingerprint: Self.fingerprint(key))) { [weak self] yes in
if yes != nil {
known[name] = key
self?.defaults.set(known, forKey: "sshKnownHosts")
}
ok(yes != nil)
}
}
/// forget the kept host key of the server on the screen now
func forgetHostKey() {
let p = portNumber
let name = p == 22 ? host : "[\(host)]:\(p)"
var known = defaults.dictionary(forKey: "sshKnownHosts") as? [String: String] ?? [:]
known[name] = nil
defaults.set(known, forKey: "sshKnownHosts")
}
/// OpenSSH's SHA256 fingerprint of a key in its "type base64" form
static func fingerprint(_ key: String) -> String {
let parts = key.split(separator: " ")
guard parts.count >= 2, let blob = Data(base64Encoded: String(parts[1])) else { return key }
let b64 = Data(SHA256.hash(data: blob)).base64EncodedString().replacingOccurrences(of: "=", with: "")
return "\(parts[0]) SHA256:\(b64)"
}
private func ask(_ q: Question, _ answer: @escaping (String?) -> Void) {
answerQuestion?(nil)
answerQuestion = answer
question = q
}
/// the user's answer to [question]: the password, "yes", or nil for no
func answer(_ a: String?) {
let f = answerQuestion
answerQuestion = nil
question = nil
f?(a)
}
private func startSocket(host: String, port: Int, user: String) {
let kind = proto == .rlogin ? "rlogin" : "telnet"
// (Network can't read urgent data apart: rlogin's comes in the stream)
let l = LoginBridge(kind: kind, user: user, term: proto == .rlogin ? "ansi" : "ANSI",
cols: Int32(cols), rows: Int32(rows), inlineUrgent: true)
login = l
guard let nwPort = NWEndpoint.Port(rawValue: UInt16(port)) else { return ended("the port is not one") }
let c = NWConnection(host: NWEndpoint.Host(host), port: nwPort, using: .tcp)
connection = c
c.stateUpdateHandler = { [weak self, weak c] st in
Task { @MainActor in
guard let self, let c, c === self.connection else { return }
switch st {
case .ready:
self.status = "Connected"
l.connected()
self.pump()
self.receive(c)
case .waiting(let e), .failed(let e):
self.ended("could not connect: \(e.localizedDescription)")
default:
break
}
}
}
c.start(queue: .main)
}
private func receive(_ c: NWConnection) {
c.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] data, _, done, error in
Task { @MainActor in
guard let self, c === self.connection, let l = self.login else { return }
if let data, !data.isEmpty, let s = String(data: data, encoding: .isoLatin1) {
l.feed(latin1: s)
self.pump()
}
if done || error != nil {
self.ended(error.map { "the connection failed: \($0.localizedDescription)" } ?? "Connection closed by the server")
} else {
self.receive(c)
}
}
}
}
/// the protocol's screen octets shown, its output sent
private func pump() {
guard let l = login else { return }
let screen = l.screen()
if !screen.isEmpty, let d = screen.data(using: .isoLatin1) { terminal.feed(d) }
let out = l.output()
if !out.isEmpty, let d = out.data(using: .isoLatin1) { connection?.send(content: d, completion: .idempotent) }
}
// MARK: - the terminal
private func send(_ d: Data) {
guard running else { return }
if let ssh {
ssh.write(d)
} else if let l = login, let s = String(data: d, encoding: .isoLatin1) {
l.type(latin1: s)
pump()
}
}
private func resized(_ c: Int, _ r: Int) {
cols = c
rows = r
guard running else { return }
ssh?.resize(cols: c, rows: r)
if let l = login {
l.resize(cols: Int32(c), rows: Int32(r))
pump()
}
}
private func show(_ s: String) {
terminal.feed(Data(s.utf8))
}
private func ended(_ why: String?) {
guard running else { return }
running = false
if question != nil { answer(nil) }
let s = ssh
ssh = nil
s?.close()
connection?.cancel()
connection = nil
login = nil
show("\r\n\u{1b}[0m[\(why ?? "Disconnected")]\r\n")
status = why ?? "Disconnected"
}
}
+111
View File
@@ -0,0 +1,111 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import SwiftUI
/// The Remote screen: SSH, Telnet or rlogin to a server; its terminal
/// once connected (the same terminal as the modem's, a screen of its own).
struct RemoteView: View {
@ObservedObject var model: RemoteModel
@State private var password = ""
var body: some View {
Group {
if model.running {
TerminalScreen(model: model.terminal)
.safeAreaInset(edge: .top) {
Text(model.status)
.font(.caption)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity)
.background(Color(.secondarySystemBackground))
}
} else {
form
}
}
.navigationTitle("Remote")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .primaryAction) {
if model.running {
Button("Disconnect", role: .destructive) { model.disconnect() }
} else {
Button("Connect") { model.connect() }
.disabled(!model.complete)
}
}
}
.alert(title, isPresented: Binding(get: { model.question != nil }, set: { if !$0 { model.answer(nil) } }), presenting: model.question) { q in
switch q {
case .password:
SecureField("Password", text: $password)
Button("Log In") {
let p = password
password = ""
model.answer(p)
}
Button("Cancel", role: .cancel) {
password = ""
model.answer(nil)
}
case .newHostKey:
Button("Trust") { model.answer("yes") }
Button("Cancel", role: .cancel) { model.answer(nil) }
}
} message: { q in
switch q {
case .password(let host, let reason):
Text(reason.isEmpty ? "The password for \(host)" : "\(reason). The password for \(host)")
case .newHostKey(let host, let fp):
Text("This is the first connection to \(host). Its key is \(fp). Trust it and keep it?")
}
}
}
private var title: String {
switch model.question {
case .password: return "Log in"
case .newHostKey: return "New host"
case nil: return ""
}
}
private var form: some View {
Form {
Section {
Picker("Connect by", selection: $model.proto) {
ForEach(RemoteModel.Proto.allCases) { Text($0.rawValue).tag($0) }
}
.pickerStyle(.segmented)
TextField("Server", text: $model.host)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
.keyboardType(.URL)
TextField("Port (\(model.proto.defaultPort))", text: $model.port)
.keyboardType(.numberPad)
TextField(model.proto == .telnet ? "User (optional)" : "User", text: $model.user)
.textInputAutocapitalization(.never)
.autocorrectionDisabled()
} footer: {
switch model.proto {
case .ssh:
Text("Logs in with a password. The server's key is kept the first time you trust it.")
case .telnet:
Text("For BBSes and older hosts. Nothing is encrypted.")
case .rlogin:
Text("Sends the user name to log in as. Nothing is encrypted.")
}
}
Section {
Button("Connect") { model.connect() }
.disabled(!model.complete)
if model.proto == .ssh {
Button("Forget this server's key", role: .destructive) { model.forgetHostKey() }
}
}
if model.status != "Not connected" {
Section { Text(model.status).foregroundStyle(.secondary) }
}
}
}
}
+3
View File
@@ -22,6 +22,8 @@ final class TerminalModel: ObservableObject {
/// to the modem
var send: ((Data) -> Void)?
/// the screen's new size (a remote login tells its server)
var onResize: ((Int, Int) -> Void)?
/// the emulator set up for BBSes: CP437, bold as bright, the VGA colours
init() {
@@ -133,6 +135,7 @@ final class TerminalModel: ObservableObject {
guard cols > 0, rows > 0, cols != self.cols || rows != self.rows else { return }
bridge.resize(cols: Int32(cols), rows: Int32(rows))
revision = bridge.revision
onResize?(cols, rows)
}
/// a row's runs
+3
View File
@@ -13,6 +13,8 @@ options:
packages:
DModemKit:
path: ../DModemKit
DModemSSH:
path: ../DModemSSH
targets:
DModem:
type: application
@@ -20,6 +22,7 @@ targets:
sources: [Sources]
dependencies:
- package: DModemKit
- package: DModemSSH
- framework: ../../shared/build/XCFrameworks/release/DModemShared.xcframework
embed: false
# the dial-up link's VPN (embedded in the app's PlugIns)
+68
View File
@@ -0,0 +1,68 @@
{
"pins" : [
{
"identity" : "swift-asn1",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-asn1.git",
"state" : {
"revision" : "917b472dbe53ba699cbb0495f9a95a084bc6364d",
"version" : "1.7.4"
}
},
{
"identity" : "swift-atomics",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-atomics.git",
"state" : {
"revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34",
"version" : "1.3.1"
}
},
{
"identity" : "swift-collections",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-collections.git",
"state" : {
"revision" : "a0cb0954ecb21e4e31b0070e6ed5674e8556685a",
"version" : "1.6.0"
}
},
{
"identity" : "swift-crypto",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-crypto.git",
"state" : {
"revision" : "da9d28d69ebe3894b18376c8f2395c2f37b8448f",
"version" : "4.5.2"
}
},
{
"identity" : "swift-nio",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio.git",
"state" : {
"revision" : "2f58d8ef84438d6517fc78bcea2f8527e3c72936",
"version" : "2.105.0"
}
},
{
"identity" : "swift-nio-ssh",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio-ssh.git",
"state" : {
"revision" : "d1985926494b624e751b379009dc83f3395fd88a",
"version" : "0.15.1"
}
},
{
"identity" : "swift-system",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-system.git",
"state" : {
"revision" : "869129b7bf4ecc57b97d0193ad29690ca2134750",
"version" : "1.8.1"
}
}
],
"version" : 2
}
+26
View File
@@ -0,0 +1,26 @@
// swift-tools-version:5.9
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
//
// DModemSSH: the iOS app's SSH client, an interactive shell on a pty, on
// Apple's SwiftNIO SSH. Apart from the app so that it builds and its tests
// run on Linux too (against a local sshd, when DMODEM_SSH_TEST names one).
import PackageDescription
let package = Package(
name: "DModemSSH",
platforms: [.macOS(.v12), .iOS(.v15)],
products: [.library(name: "DModemSSH", targets: ["DModemSSH"])],
dependencies: [
.package(url: "https://github.com/apple/swift-nio.git", from: "2.65.0"),
.package(url: "https://github.com/apple/swift-nio-ssh.git", from: "0.9.0"),
],
targets: [
.target(name: "DModemSSH", dependencies: [
.product(name: "NIOCore", package: "swift-nio"),
.product(name: "NIOPosix", package: "swift-nio"),
.product(name: "NIOSSH", package: "swift-nio-ssh"),
]),
.testTarget(name: "DModemSSHTests", dependencies: ["DModemSSH"]),
]
)
@@ -0,0 +1,295 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import Foundation
import NIOCore
import NIOPosix
import NIOSSH
/// An SSH login's interactive shell: the host's key checked by the caller
/// ([verifyHostKey], its OpenSSH form), the user logged in by password
/// ([askPassword], asked again when one is refused, three times at most),
/// a pty of [term] in the screen's size and a shell on it. What the
/// server says (stdout and stderr) goes to [onData]; [write] sends what
/// is typed; [resize] the window's new size. [onClose] once, with why
/// (nil when it was asked to).
///
/// The callbacks are made on the connection's own thread: hop to the
/// main one to touch views. Host keys: Ed25519 and ECDSA (SwiftNIO SSH
/// has no RSA).
public final class SSHShell: @unchecked Sendable {
public let host: String
public let port: Int
public let user: String
public let term: String
public var onData: (Data) -> Void = { _ in }
public var onClose: (String?) -> Void = { _ in }
/// the host's key ("ssh-ed25519 AAAA..."): call back with true to go on
public var verifyHostKey: (String, @escaping (Bool) -> Void) -> Void = { _, ok in ok(false) }
/// the user's password, asked ("" when it's the first time, else why
/// the last was refused): call back with nil to give up
public var askPassword: (String, @escaping (String?) -> Void) -> Void = { _, done in done(nil) }
private var cols: Int
private var rows: Int
/// (SwiftNIO's shared threads: a shell's owner may let go of it on one)
private let group = MultiThreadedEventLoopGroup.singleton
private var channel: Channel?
private var shell: Channel?
private let lock = NSLock()
private var closed = false
private var closing = false
private var exitStatus: Int?
public init(host: String, port: Int = 22, user: String, term: String = "xterm-256color", cols: Int = 80, rows: Int = 24) {
self.host = host
self.port = port
self.user = user
self.term = term
self.cols = cols
self.rows = rows
}
/// connect, log in and start the shell, on the connection's thread
public func connect() {
let auth = PasswordAuth(user: user) { [weak self] why, done in
guard let self else { return done(nil) }
self.askPassword(why, done)
}
let keys = HostKeyCheck { [weak self] key, done in
guard let self else { return done(false) }
self.verifyHostKey(key, done)
}
let bootstrap = ClientBootstrap(group: group)
.connectTimeout(.seconds(20))
.channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
.channelInitializer { ch in
ch.eventLoop.makeCompletedFuture {
let ssh = NIOSSHHandler(
role: .client(.init(userAuthDelegate: auth, serverAuthDelegate: keys)),
allocator: ch.allocator, inboundChildChannelInitializer: nil)
try ch.pipeline.syncOperations.addHandlers([ssh, ErrorCatcher { [weak self] e in self?.failed(e) }])
}
}
bootstrap.connect(host: host, port: port).flatMap { [weak self] (ch: Channel) -> EventLoopFuture<Channel> in
guard let self else { return ch.eventLoop.makeFailedFuture(ChannelError.ioOnClosedChannel) }
self.lock.withLock { self.channel = ch }
ch.closeFuture.whenComplete { [weak self] _ in self?.finish(nil) }
return ch.pipeline.handler(type: NIOSSHHandler.self).flatMap { ssh in
let p = ch.eventLoop.makePromise(of: Channel.self)
ssh.createChannel(p) { child, type in
guard type == .session else {
return child.eventLoop.makeFailedFuture(SSHShellError.unexpectedChannel)
}
return child.setOption(ChannelOptions.allowRemoteHalfClosure, value: true).flatMap {
child.pipeline.addHandler(ShellHandler(owner: self))
}
}
return p.futureResult
}
}.flatMap { [weak self] (child: Channel) -> EventLoopFuture<Void> in
guard let self else { return child.eventLoop.makeSucceededVoidFuture() }
self.lock.withLock { self.shell = child }
let (c, r) = self.lock.withLock { (self.cols, self.rows) }
let pty = SSHChannelRequestEvent.PseudoTerminalRequest(
wantReply: true, term: self.term, terminalCharacterWidth: c, terminalRowHeight: r,
terminalPixelWidth: 0, terminalPixelHeight: 0, terminalModes: SSHTerminalModes([:]))
return child.triggerUserOutboundEvent(pty).flatMap {
child.triggerUserOutboundEvent(SSHChannelRequestEvent.ShellRequest(wantReply: true))
}
}.whenFailure { [weak self] e in self?.failed(e) }
}
/// what's typed, to the shell
public func write(_ data: Data) {
guard let s = lock.withLock({ shell }), !data.isEmpty else { return }
var b = s.allocator.buffer(capacity: data.count)
b.writeBytes(data)
s.writeAndFlush(SSHChannelData(type: .channel, data: .byteBuffer(b)), promise: nil)
}
/// the screen's new size, to the server
public func resize(cols: Int, rows: Int) {
let s: Channel? = lock.withLock {
guard cols != self.cols || rows != self.rows else { return nil }
self.cols = cols
self.rows = rows
return shell
}
s?.triggerUserOutboundEvent(SSHChannelRequestEvent.WindowChangeRequest(
terminalCharacterWidth: cols, terminalRowHeight: rows, terminalPixelWidth: 0, terminalPixelHeight: 0), promise: nil)
}
/// the connection closed by the user
public func close() {
let ch: Channel? = lock.withLock {
closing = true
return channel
}
if let ch {
ch.close(promise: nil)
} else {
finish(nil)
}
}
fileprivate func received(_ data: Data) { onData(data) }
fileprivate func exited(_ status: Int) { lock.withLock { exitStatus = status } }
fileprivate func shellClosed() {
// (the shell's over: so is the connection)
lock.withLock { channel }?.close(promise: nil)
}
fileprivate func failed(_ e: Error) {
finish(Self.describe(e))
lock.withLock { channel }?.close(promise: nil)
}
private func finish(_ why: String?) {
let (first, asked, status): (Bool, Bool, Int?) = lock.withLock {
defer { closed = true }
return (!closed, closing, exitStatus)
}
guard first else { return }
if asked {
onClose(nil)
} else if let why {
onClose(why)
} else if let status, status != 0 {
onClose("the shell exited with status \(status)")
} else {
onClose("Connection closed")
}
}
static func describe(_ e: Error) -> String {
switch e {
case SSHShellError.hostKeyRefused: return "the host's key was not accepted"
case SSHShellError.noPassword: return "not logged in"
case SSHShellError.unexpectedChannel: return "the server opened an unexpected channel"
default: break
}
if let n = e as? NIOSSHError {
switch n.type {
case .invalidHostKeyForKeyExchange, .keyExchangeNegotiationFailure:
return "no host key or key exchange in common (this app has Ed25519 and ECDSA, not RSA)"
default:
break
}
}
if e is NIOConnectionError || e is IOError { return "could not connect: \(e)" }
return "\(e)"
}
}
public enum SSHShellError: Error {
case hostKeyRefused, noPassword, unexpectedChannel
}
/// the password, asked; again (with why) when the server refuses it, three times at most
private final class PasswordAuth: NIOSSHClientUserAuthenticationDelegate {
let user: String
let ask: (String, @escaping (String?) -> Void) -> Void
var tries = 0
init(user: String, ask: @escaping (String, @escaping (String?) -> Void) -> Void) {
self.user = user
self.ask = ask
}
func nextAuthenticationType(
availableMethods: NIOSSHAvailableUserAuthenticationMethods,
nextChallengePromise: EventLoopPromise<NIOSSHUserAuthenticationOffer?>
) {
guard availableMethods.contains(.password) else {
nextChallengePromise.fail(SSHShellError.noPassword)
return
}
guard tries < 3 else {
nextChallengePromise.fail(SSHShellError.noPassword)
return
}
tries += 1
let user = self.user
ask(tries == 1 ? "" : "The password was not accepted") { pw in
guard let pw else {
nextChallengePromise.fail(SSHShellError.noPassword)
return
}
nextChallengePromise.succeed(NIOSSHUserAuthenticationOffer(
username: user, serviceName: "", offer: .password(.init(password: pw))))
}
}
}
/// the host's key, as OpenSSH writes it, to the caller to accept or not
private final class HostKeyCheck: NIOSSHClientServerAuthenticationDelegate {
let verify: (String, @escaping (Bool) -> Void) -> Void
init(verify: @escaping (String, @escaping (Bool) -> Void) -> Void) {
self.verify = verify
}
func validateHostKey(hostKey: NIOSSHPublicKey, validationCompletePromise: EventLoopPromise<Void>) {
verify(String(openSSHPublicKey: hostKey)) { ok in
if ok {
validationCompletePromise.succeed(())
} else {
validationCompletePromise.fail(SSHShellError.hostKeyRefused)
}
}
}
}
/// the shell's channel: its data (stdout and stderr) to the owner, its exit status kept
private final class ShellHandler: ChannelInboundHandler {
typealias InboundIn = SSHChannelData
private weak var owner: SSHShell?
init(owner: SSHShell) {
self.owner = owner
}
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
let d = unwrapInboundIn(data)
guard case .byteBuffer(var b) = d.data, let bytes = b.readBytes(length: b.readableBytes) else { return }
owner?.received(Data(bytes))
}
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
if let s = event as? SSHChannelRequestEvent.ExitStatus {
owner?.exited(s.exitStatus)
} else if event is ChannelEvent, case .inputClosed = event as! ChannelEvent {
context.close(promise: nil)
}
context.fireUserInboundEventTriggered(event)
}
func channelInactive(context: ChannelHandlerContext) {
owner?.shellClosed()
context.fireChannelInactive()
}
func errorCaught(context: ChannelHandlerContext, error: Error) {
owner?.failed(error)
context.close(promise: nil)
}
}
/// the connection's errors (a refused host key, a failed login) to the owner
private final class ErrorCatcher: ChannelInboundHandler {
typealias InboundIn = Any
let caught: (Error) -> Void
init(caught: @escaping (Error) -> Void) {
self.caught = caught
}
func errorCaught(context: ChannelHandlerContext, error: Error) {
caught(error)
context.close(promise: nil)
}
}
@@ -0,0 +1,94 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import DModemSSH
import Foundation
import XCTest
/// A login to a real sshd, when DMODEM_SSH_TEST names one as
/// host:port:user:password (else skipped).
final class SSHShellTests: XCTestCase {
private func server() throws -> (String, Int, String, String) {
guard let spec = ProcessInfo.processInfo.environment["DMODEM_SSH_TEST"] else {
throw XCTSkip("DMODEM_SSH_TEST is not set")
}
let p = spec.split(separator: ":", maxSplits: 3).map(String.init)
return (p[0], Int(p[1]) ?? 22, p[2], p[3])
}
func testShell() throws {
let (host, port, user, password) = try server()
let shell = SSHShell(host: host, port: port, user: user, term: "vt100", cols: 100, rows: 30)
let lock = NSLock()
var out = Data()
var hostKey = ""
var asks: [String] = []
let closed = expectation(description: "closed")
var why: String?
shell.verifyHostKey = { k, ok in
lock.withLock { hostKey = k }
ok(true)
}
shell.askPassword = { reason, done in
lock.withLock { asks.append(reason) }
// (the first wrong, to see it asked again)
done(asks.count == 1 ? "wrong" : password)
}
shell.onData = { d in
lock.withLock { out.append(d) }
}
shell.onClose = { w in
why = w
closed.fulfill()
}
shell.connect()
// the shell's prompt, then the commands
let deadline = Date().addingTimeInterval(20)
while Date() < deadline && lock.withLock({ out.isEmpty }) { Thread.sleep(forTimeInterval: 0.1) }
shell.resize(cols: 120, rows: 40)
Thread.sleep(forTimeInterval: 0.5)
shell.write(Data("echo TERM=$TERM; stty size; exit 3\r".utf8))
wait(for: [closed], timeout: 20)
let text = String(decoding: lock.withLock { out }, as: UTF8.self)
XCTAssertTrue(hostKey.hasPrefix("ssh-ed25519 ") || hostKey.hasPrefix("ecdsa-"), hostKey)
XCTAssertEqual(asks, ["", "The password was not accepted"])
XCTAssertTrue(text.contains("TERM=vt100"), text)
XCTAssertTrue(text.contains("40 120"), text)
XCTAssertEqual(why, "the shell exited with status 3")
}
func testRefusedHostKey() throws {
let (host, port, user, _) = try server()
let shell = SSHShell(host: host, port: port, user: user)
let closed = expectation(description: "closed")
var why: String?
shell.verifyHostKey = { _, ok in ok(false) }
shell.onClose = { w in
why = w
closed.fulfill()
}
shell.connect()
wait(for: [closed], timeout: 20)
XCTAssertEqual(why, "the host's key was not accepted")
}
func testCloseByUser() throws {
let (host, port, user, password) = try server()
let shell = SSHShell(host: host, port: port, user: user)
let closed = expectation(description: "closed")
let opened = expectation(description: "data")
opened.assertForOverFulfill = false
var why: String? = "unset"
shell.verifyHostKey = { _, ok in ok(true) }
shell.askPassword = { _, done in done(password) }
shell.onData = { _ in opened.fulfill() }
shell.onClose = { w in
why = w
closed.fulfill()
}
shell.connect()
wait(for: [opened], timeout: 20)
shell.close()
wait(for: [closed], timeout: 20)
XCTAssertNil(why)
}
}
@@ -0,0 +1,315 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.net
/**
* A remote login's protocol on a TCP connection someone else makes:
* Telnet (RFC 854) or rlogin (RFC 1282). It does no I/O: hand it what the
* socket read ([feed]), write what [output] gives, show what [screen]
* gives, and pass on what is typed ([type]).
*/
interface LoginCodec {
/** the connection made: rlogin's handshake, Telnet's first offers */
fun connected()
/** octets the socket read */
fun feed(data: ByteArray, length: Int = data.size)
/** an urgent (out-of-band) octet the socket read: rlogin's control byte */
fun urgent(b: Int) {}
/** octets typed */
fun type(data: ByteArray, length: Int = data.size)
/** the screen's new size, told to the server */
fun resize(cols: Int, rows: Int)
/** the octets for the terminal, taken */
fun screen(): ByteArray
/** the octets for the socket, taken */
fun output(): ByteArray
}
private class Octets {
private var b = ByteArray(256)
var size = 0
private set
fun add(v: Int) {
if (size == b.size) b = b.copyOf(b.size * 2)
b[size++] = v.toByte()
}
fun add(v: ByteArray, n: Int = v.size) {
for (i in 0 until n) add(v[i].toInt() and 0xff)
}
fun take(): ByteArray = b.copyOf(size).also { size = 0 }
fun clear() { size = 0 }
fun bytes(): ByteArray = b.copyOf(size)
}
/**
* Telnet: the server's options answered (BINARY, ECHO and
* SUPPRESS-GO-AHEAD taken; TERMINAL-TYPE and NAWS offered; the rest
* refused) once per change, so that no two ends loop; IAC doubled both
* ways; a typed CR as CR NUL outside binary mode; the window's size
* (NAWS) sent as it changes.
*/
class TelnetCodec(
/** what TERMINAL-TYPE says */
private val termType: String = "XTERM-256COLOR",
private var cols: Int = 80,
private var rows: Int = 24,
) : LoginCodec {
private val scr = Octets()
private val out = Octets()
private val sb = Octets()
private val remote = BooleanArray(256)
private val local = BooleanArray(256)
private var naws = false
private var st = 0
private var verb = 0
private var lastCr = false
override fun connected() {
put(IAC, WILL, TTYPE)
put(IAC, WILL, NAWS)
put(IAC, DO, SGA)
// (asked: the server's yes is not answered again)
local[TTYPE] = true
local[NAWS] = true
remote[SGA] = true
}
private fun put(vararg v: Int) = v.forEach { out.add(it) }
private fun sendNaws() {
put(IAC, SB, NAWS)
for (v in intArrayOf(cols, rows)) {
val c = v.coerceIn(0, 65535)
for (b in intArrayOf(c shr 8, c and 0xff)) {
out.add(b)
if (b == IAC) out.add(IAC)
}
}
put(IAC, SE)
}
private fun option(verb: Int, opt: Int) {
when (verb) {
WILL -> {
val ok = opt == BINARY || opt == ECHO || opt == SGA
if (ok != remote[opt] || !ok) {
remote[opt] = ok
put(IAC, if (ok) DO else DONT, opt)
}
}
WONT -> if (remote[opt]) {
remote[opt] = false
put(IAC, DONT, opt)
}
DO -> {
val ok = opt == BINARY || opt == SGA || opt == TTYPE || opt == NAWS
if (ok != local[opt] || !ok) {
local[opt] = ok
put(IAC, if (ok) WILL else WONT, opt)
}
if (ok && opt == NAWS) {
naws = true
sendNaws()
}
}
DONT -> {
if (opt == NAWS) naws = false
if (local[opt]) {
local[opt] = false
put(IAC, WONT, opt)
}
}
}
}
private fun subnegotiation() {
val b = sb.bytes()
if (b.size >= 2 && (b[0].toInt() and 0xff) == TTYPE && b[1].toInt() == 1) {
put(IAC, SB, TTYPE, 0)
termType.forEach { out.add(it.code and 0xff) }
put(IAC, SE)
}
}
override fun feed(data: ByteArray, length: Int) {
for (i in 0 until length) {
val b = data[i].toInt() and 0xff
when (st) {
S_DATA -> when {
b == IAC -> st = S_IAC
// (CR NUL is a CR: the NUL goes)
b == 0 && lastCr && !remote[BINARY] -> {}
else -> scr.add(b)
}
S_IAC -> when (b) {
IAC -> { scr.add(IAC); st = S_DATA }
WILL, WONT, DO, DONT -> { verb = b; st = S_OPT }
SB -> { sb.clear(); st = S_SB }
else -> st = S_DATA
}
S_OPT -> { option(verb, b); st = S_DATA }
S_SB -> if (b == IAC) st = S_SB_IAC else if (sb.size < 1024) sb.add(b)
S_SB_IAC -> when (b) {
SE -> { subnegotiation(); st = S_DATA }
else -> { if (b == IAC && sb.size < 1024) sb.add(IAC); st = S_SB }
}
}
lastCr = st == S_DATA && b == '\r'.code
}
}
override fun type(data: ByteArray, length: Int) {
for (i in 0 until length) {
val b = data[i].toInt() and 0xff
out.add(b)
if (b == IAC) out.add(IAC)
if (b == '\r'.code && !local[BINARY] && (i + 1 >= length || data[i + 1].toInt() != '\n'.code)) out.add(0)
}
}
override fun resize(cols: Int, rows: Int) {
if (cols == this.cols && rows == this.rows) return
this.cols = cols
this.rows = rows
if (naws) sendNaws()
}
override fun screen() = scr.take()
override fun output() = out.take()
companion object {
const val IAC = 255
const val DONT = 254
const val DO = 253
const val WONT = 252
const val WILL = 251
const val SB = 250
const val SE = 240
const val BINARY = 0
const val ECHO = 1
const val SGA = 3
const val TTYPE = 24
const val NAWS = 31
private const val S_DATA = 0
private const val S_IAC = 1
private const val S_OPT = 2
private const val S_SB = 3
private const val S_SB_IAC = 4
}
}
/**
* rlogin: the handshake (NUL, the user as both the local and the remote
* name, "term/speed"), the server's NUL that answers it taken off the
* stream, and the window's size ("\377\377ss" and four 16-bit numbers)
* sent once the server has asked with its urgent byte 0x80.
*
* Where the socket can't read urgent data apart (Java's, Apple's
* Network), [inlineUrgent]: the urgent byte arrives in the stream, and a
* 0x80 straight after the server's NUL is taken as that request.
*/
class RloginCodec(
private val user: String,
private val term: String = "xterm",
private var cols: Int = 80,
private var rows: Int = 24,
private val inlineUrgent: Boolean = false,
) : LoginCodec {
private val scr = Octets()
private val out = Octets()
private var ready = false
private var sawData = false
private var wantSize = false
override fun connected() {
out.add(0)
repeat(2) {
out.add(user.encodeToByteArray())
out.add(0)
}
out.add("$term/38400".encodeToByteArray())
out.add(0)
}
private fun window() {
out.add("ÿÿss".map { it.code.toByte() }.toByteArray())
for (v in intArrayOf(rows, cols, cols * 8, rows * 16)) {
val c = v.coerceIn(0, 65535)
out.add(c shr 8)
out.add(c and 0xff)
}
}
override fun feed(data: ByteArray, length: Int) {
var i = 0
if (!ready && length > 0) {
ready = true
if (data[0].toInt() == 0) i = 1
}
while (i < length) {
val b = data[i++].toInt() and 0xff
if (inlineUrgent && !sawData && b == 0x80) {
urgent(b)
continue
}
sawData = true
scr.add(b)
}
}
override fun urgent(b: Int) {
if (b and 0x80 != 0) {
wantSize = true
window()
}
if (b and 0x02 != 0) scr.clear()
}
override fun type(data: ByteArray, length: Int) = out.add(data, length)
override fun resize(cols: Int, rows: Int) {
if (cols == this.cols && rows == this.rows) return
this.cols = cols
this.rows = rows
if (wantSize) window()
}
override fun screen() = scr.take()
override fun output() = out.take()
}
/**
* A [LoginCodec] for Swift: octets as Latin-1 strings, one character
* each (as TerminalBridge has them). [kind] is "telnet" or "rlogin".
*/
class LoginBridge(kind: String, user: String, term: String, cols: Int, rows: Int, inlineUrgent: Boolean) {
private val codec: LoginCodec =
if (kind == "rlogin") RloginCodec(user, term, cols, rows, inlineUrgent) else TelnetCodec(term, cols, rows)
fun connected() = codec.connected()
fun feed(latin1: String) = codec.feed(octets(latin1))
fun urgent(b: Int) = codec.urgent(b)
fun type(latin1: String) = codec.type(octets(latin1))
fun resize(cols: Int, rows: Int) = codec.resize(cols, rows)
fun screen(): String = latin1(codec.screen())
fun output(): String = latin1(codec.output())
private fun octets(s: String) = ByteArray(s.length) { s[it].code.toByte() }
private fun latin1(b: ByteArray): String {
val sb = StringBuilder(b.size)
for (x in b) sb.append((x.toInt() and 0xff).toChar())
return sb.toString()
}
companion object {
/** the protocol's port: 22, 23, 513 */
fun defaultPort(kind: String): Int = when (kind) {
"telnet" -> 23
"rlogin" -> 513
else -> 22
}
}
}
@@ -0,0 +1,76 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package org.dmodem.app.net
import kotlin.test.Test
import kotlin.test.assertEquals
class RemoteLoginTest {
private fun b(vararg v: Int) = ByteArray(v.size) { v[it].toByte() }
private fun s(t: String) = t.encodeToByteArray()
private fun ints(a: ByteArray) = a.map { it.toInt() and 0xff }
@Test
fun telnetNegotiates() {
val t = TelnetCodec("ANSI", 80, 24)
t.connected()
assertEquals(listOf(255, 251, 24, 255, 251, 31, 255, 253, 3), ints(t.output()))
// DO TTYPE, DO NAWS (our size), WILL ECHO, WILL SGA (asked: not answered), DO LINEMODE (refused), text
t.feed(b(255, 253, 24, 255, 253, 31, 255, 251, 1, 255, 251, 3, 255, 253, 34) + s("Hi") + b(255, 255) + s("!"))
assertEquals(listOf(255, 250, 31, 0, 80, 0, 24, 255, 240, 255, 253, 1, 255, 252, 34), ints(t.output()))
assertEquals(listOf('H'.code, 'i'.code, 255, '!'.code), ints(t.screen()))
// TERMINAL-TYPE SEND, split
t.feed(b(255, 250, 24))
t.feed(b(1, 255, 240))
assertEquals(listOf(255, 250, 24, 0) + ints(s("ANSI")) + listOf(255, 240), ints(t.output()))
// CR NUL is a CR
t.feed(s("a\r") + b(0) + s("b"))
assertEquals("a\rb", t.screen().decodeToString())
// typed: a lone CR as CR NUL, IAC doubled; CR LF as it is
t.type(s("ls\r") + b(255))
assertEquals(ints(s("ls\r")) + listOf(0, 255, 255), ints(t.output()))
t.type(s("\r\n"))
assertEquals("\r\n", t.output().decodeToString())
// resized: NAWS with 0xff doubled, once
t.resize(255, 50)
assertEquals(listOf(255, 250, 31, 0, 255, 255, 0, 50, 255, 240), ints(t.output()))
t.resize(255, 50)
assertEquals(0, t.output().size)
}
@Test
fun rloginHandshakeAndWindow() {
val r = RloginCodec("alice", "xterm", 80, 24)
r.connected()
assertEquals("\u0000alice\u0000alice\u0000xterm/38400\u0000", r.output().decodeToString())
r.feed(b(0) + s("Password:"))
assertEquals("Password:", r.screen().decodeToString())
r.resize(100, 30)
assertEquals(0, r.output().size)
r.urgent(0x80)
assertEquals(listOf(255, 255, 's'.code, 's'.code, 0, 30, 0, 100, 3, 32, 1, 224), ints(r.output()))
r.type(s("\r"))
assertEquals("\r", r.output().decodeToString())
}
@Test
fun rloginInlineUrgent() {
val r = RloginCodec("bob", "ansi", 80, 24, inlineUrgent = true)
r.connected()
r.output()
r.feed(b(0, 0x80) + s("$ "))
assertEquals("$ ", r.screen().decodeToString())
assertEquals(listOf(255, 255, 's'.code, 's'.code, 0, 24, 0, 80, 2, 128, 1, 128), ints(r.output()))
// later 0x80s are data
r.feed(b(0x80))
assertEquals(listOf(0x80), ints(r.screen()))
}
@Test
fun bridgeIsLatin1() {
val l = LoginBridge("telnet", "", "ANSI", 80, 24, false)
l.feed("ÿÿx")
assertEquals("ÿx", l.screen())
assertEquals(513, LoginBridge.defaultPort("rlogin"))
}
}