File transfers: XMODEM, YMODEM, ZMODEM and Kermit (work in progress)

Protocols in the transfer package with lrzsz and Kermit interop tests,
the session routing the line to a running transfer, auto-start on a
remote sz or kermit -s, and Send/Receive files in the terminal menu
with a progress banner. Received files go to Download/D-Modem.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs
This commit is contained in:
Claude committed 2026-10-16 22:46:13 +00:00
1 parent 38e45cb1c6
commit 0cbb7aae29
14 files changed
+2794

No files matched your search

@@ -68,6 +68,7 @@ object Terminal {
fun init(context: Context, box: SecretBox = KeystoreBox()) {
app = context.applicationContext
session = TerminalSession(ModemState.dte) { app.getExternalFilesDir("captures") }
session.incoming = ::downloads
_sessions.value = listOf(session)
_active.value = session
directory = JsonListStore(
@@ -81,6 +82,9 @@ object Terminal {
passwords = PasswordStore(File(app.filesDir, "ssh/passwords.json"), box)
}
/** where files a remote sends go */
fun downloads(): com.neodesktop.dmodem.transfer.Incoming = com.neodesktop.dmodem.transfer.DownloadsIncoming(app)
fun select(s: TerminalSession) {
if (s in _sessions.value) _active.value = s
}
@@ -132,6 +136,7 @@ object Terminal {
s.charset = e.charset ?: (if (e.kind == EntryKind.SSH) TermCharset.UTF8 else t.charset)
s.keys.backspace = e.backspace ?: (if (e.kind == EntryKind.SSH) BackspaceMode.DEL else t.backspace)
s.keys.enter = t.enter
s.incoming = ::downloads
_sessions.value = _sessions.value + s
_active.value = s
directory.put(e.copy(lastDialed = System.currentTimeMillis(), dialCount = e.dialCount + 1))
@@ -171,6 +176,7 @@ object Terminal {
s.charset = TermCharset.UTF8
s.keys.backspace = BackspaceMode.DEL
s.keys.enter = com.neodesktop.dmodem.terminal.EnterMode.CR
s.incoming = ::downloads
_sessions.value = _sessions.value + s
_active.value = s
ConnectionService.update(app)
@@ -200,6 +206,7 @@ object Terminal {
s.charset = TermCharset.UTF8
s.keys.backspace = BackspaceMode.DEL
s.keys.enter = com.neodesktop.dmodem.terminal.EnterMode.CR
s.incoming = ::downloads
_sessions.value = _sessions.value + s
_active.value = s
ConnectionService.update(app)
@@ -2,6 +2,11 @@
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.terminal
import com.neodesktop.dmodem.transfer.Incoming
import com.neodesktop.dmodem.transfer.Outgoing
import com.neodesktop.dmodem.transfer.Protocol
import com.neodesktop.dmodem.transfer.Transfer
import com.neodesktop.dmodem.transfer.TransferState
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
@@ -77,6 +82,29 @@ class TerminalSession(
synchronized(emulator) { emulator.decoder.charset = v; emulator.decoder.reset() }
}
// file transfers
@Volatile
private var transfer: Transfer? = null
private val transferLock = Any()
private val _transferState = MutableStateFlow<TransferState?>(null)
/** the transfer running, or the last one's end (until [dismissTransfer]) */
val transferState: StateFlow<TransferState?> = _transferState.asStateFlow()
/** where files the remote starts sending go (its sz, kermit -s): null, they aren't taken */
@Volatile
var incoming: (() -> Incoming?)? = null
/** the remote's rz is waiting for files: pick some for [sendFiles] */
@Volatile
var onSendWanted: ((Protocol) -> Unit)? = null
/** the remote's own starts (ZMODEM's, Kermit's) noticed */
@Volatile
var autoTransfers = true
val transferRunning: Boolean get() = transfer != null
private val listener = TerminalLink.Listener { data, length ->
synchronized(captureLock) {
try {
@@ -85,10 +113,86 @@ class TerminalSession(
stopCapture()
}
}
transfer?.let {
it.io.feed(data, 0, length)
return@Listener
}
if (autoTransfers && length >= 4) {
val d = Transfer.detect(data, length)
when (d?.second) {
Transfer.Detected.ZMODEM_SEND, Transfer.Detected.KERMIT_SEND -> {
val into = incoming?.invoke()
if (into != null) {
synchronized(emulator) { emulator.append(data, d.first) }
val proto = if (d.second == Transfer.Detected.KERMIT_SEND) Protocol.KERMIT else Protocol.ZMODEM
startTransfer(proto, sending = false)?.let { t ->
t.io.feed(data, d.first, length - d.first)
t.receive(into)
onChange?.invoke()
return@Listener
}
}
}
Transfer.Detected.ZMODEM_RECEIVE -> onSendWanted?.invoke(Protocol.ZMODEM)
null -> {}
}
}
synchronized(emulator) { emulator.append(data, length) }
onChange?.invoke()
}
private fun startTransfer(protocol: Protocol, sending: Boolean): Transfer? = synchronized(transferLock) {
if (transfer != null) return null
val t = Transfer(
protocol, sending,
send = { b -> if (!link.write(b)) throw IOException("the line is closed") },
sendRaw = { b -> link.write(b) },
onState = { s -> _transferState.value = s },
onEnd = { s, rest -> endTransfer(s, rest) },
)
transfer = t
t
}
private fun endTransfer(s: TransferState, rest: ByteArray) {
synchronized(transferLock) { transfer = null }
val what = s.protocol.label
val msg = when {
s.result != "" -> "$what: ${s.result}"
s.sending -> "$what: sent ${s.progress.files} file(s)"
else -> "$what: received ${s.received.size} file(s)"
}
synchronized(emulator) {
emulator.appendText("\r\n[$msg]\r\n")
if (rest.isNotEmpty()) emulator.append(rest, rest.size)
}
onChange?.invoke()
}
/** files from the remote ([name]: XMODEM's, which has none): false if one is already running */
fun receiveFiles(protocol: Protocol, into: Incoming, name: String = "received.bin"): Boolean {
val t = startTransfer(protocol, sending = false) ?: return false
t.receive(into, name)
return true
}
/** [files] to the remote (which must be receiving: its rz, rb, rx, kermit -r) */
fun sendFiles(protocol: Protocol, files: List<Outgoing>): Boolean {
if (files.isEmpty()) return false
val t = startTransfer(protocol, sending = true) ?: return false
t.send(files)
return true
}
fun cancelTransfer() {
transfer?.cancel()
}
/** the last transfer's end no longer shown */
fun dismissTransfer() {
if (transfer == null) _transferState.value = null
}
init {
emulator.listener = object : TerminalEmulator.Listener {
override fun onTitle(title: String) {
@@ -114,6 +218,8 @@ class TerminalSession(
/** text to the modem in the session's set (and on the screen, with local echo) */
fun send(text: String): Boolean {
if (text.isEmpty()) return true
// (nothing typed gets into a transfer's packets)
if (transfer != null) return false
if (localEcho) {
synchronized(emulator) { emulator.appendText(text.replace("\r", "\r\n")) }
onChange?.invoke()
@@ -189,6 +295,7 @@ class TerminalSession(
/** the session over: its listener off the link, the link closed, the capture ended */
fun close() {
cancelTransfer()
link.removeListener(listener)
stopCapture()
if (kind != Kind.MODEM) link.close()
@@ -0,0 +1,88 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.transfer
import android.content.ContentValues
import android.content.Context
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import android.provider.OpenableColumns
import java.io.IOException
import java.io.OutputStream
/**
* Received files into Downloads/D-Modem (MediaStore's, from Android 10;
* before, the app's own Downloads folder, which needs no permission).
*/
class DownloadsIncoming(context: Context) : Incoming {
private val ctx = context.applicationContext
private val pending = HashMap<String, Uri>()
private val folder: FolderIncoming? =
if (Build.VERSION.SDK_INT < 29) FolderIncoming(ctx.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) ?: ctx.filesDir) else null
override fun create(name: String, size: Long): Pair<OutputStream, String> {
folder?.let { return it.create(name, size) }
val safe = FolderIncoming.safeName(name)
val v = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, safe)
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + "/" + FOLDER)
put(MediaStore.MediaColumns.IS_PENDING, 1)
}
val uri = ctx.contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, v)
?: throw IOException("can't make $safe in Downloads")
val out = ctx.contentResolver.openOutputStream(uri) ?: throw IOException("can't write $safe")
// the name it got (MediaStore makes it "name (1).ext" when it's taken)
val actual = ctx.contentResolver.query(uri, arrayOf(MediaStore.MediaColumns.DISPLAY_NAME), null, null, null)?.use { c ->
if (c.moveToFirst()) c.getString(0) else null
} ?: safe
synchronized(pending) { pending[actual] = uri }
return out to actual
}
override fun done(name: String, mtime: Long) {
folder?.let { return it.done(name, mtime) }
val uri = synchronized(pending) { pending.remove(name) } ?: return
val v = ContentValues().apply {
put(MediaStore.MediaColumns.IS_PENDING, 0)
if (mtime > 0) put(MediaStore.MediaColumns.DATE_MODIFIED, mtime)
}
runCatching { ctx.contentResolver.update(uri, v, null, null) }
}
override fun abandon(name: String) {
folder?.let { return it.abandon(name) }
val uri = synchronized(pending) { pending.remove(name) } ?: return
runCatching { ctx.contentResolver.delete(uri, null, null) }
}
companion object {
const val FOLDER = "D-Modem"
/** where files go, for saying so */
fun where(context: Context): String =
if (Build.VERSION.SDK_INT >= 29) "Download/$FOLDER"
else context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.path ?: "the app's files"
}
}
/** a document picked (the system's file picker's) to send */
fun outgoingOf(context: Context, uri: Uri): Outgoing {
val r = context.contentResolver
var name = uri.lastPathSegment?.substringAfterLast('/') ?: "file"
var size = -1L
var mtime = 0L
runCatching {
r.query(uri, null, null, null, null)?.use { c ->
if (c.moveToFirst()) {
c.getColumnIndex(OpenableColumns.DISPLAY_NAME).takeIf { it >= 0 }?.let { i -> c.getString(i)?.let { name = it } }
c.getColumnIndex(OpenableColumns.SIZE).takeIf { it >= 0 && !c.isNull(it) }?.let { i -> size = c.getLong(i) }
c.getColumnIndex(DocumentsContract.Document.COLUMN_LAST_MODIFIED).takeIf { it >= 0 && !c.isNull(it) }
?.let { i -> mtime = c.getLong(i) / 1000 }
}
}
}
return Outgoing(name, size, mtime) { r.openInputStream(uri) ?: throw IOException("can't read $name") }
}
@@ -0,0 +1,35 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.transfer
/** The checks XMODEM, YMODEM and ZMODEM use: CRC-16/XMODEM (CCITT, 0x1021, from 0) and CRC-32 (IEEE). */
object Crc {
private val table16 = IntArray(256) { i ->
var c = i shl 8
repeat(8) { c = if (c and 0x8000 != 0) (c shl 1) xor 0x1021 else c shl 1 }
c and 0xffff
}
fun crc16(crc: Int, b: Int): Int = ((crc shl 8) xor table16[((crc ushr 8) xor b) and 0xff]) and 0xffff
fun crc16(data: ByteArray, off: Int = 0, len: Int = data.size, start: Int = 0): Int {
var c = start
for (i in off until off + len) c = crc16(c, data[i].toInt() and 0xff)
return c
}
private val table32 = IntArray(256) { i ->
var c = i
repeat(8) { c = if (c and 1 != 0) (c ushr 1) xor 0xEDB88320.toInt() else c ushr 1 }
c
}
/** CRC-32 kept inverted as ZMODEM keeps it: start at 0xffffffff, invert at the end */
fun crc32(crc: Int, b: Int): Int = table32[(crc xor b) and 0xff] xor (crc ushr 8)
fun crc32(data: ByteArray, off: Int = 0, len: Int = data.size, start: Int = -1): Int {
var c = start
for (i in off until off + len) c = crc32(c, data[i].toInt() and 0xff)
return c
}
}
@@ -0,0 +1,81 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.transfer
import java.io.File
import java.io.InputStream
import java.io.OutputStream
/** A file to send: its name, size (-1 unknown), time (seconds, 0 unknown), contents. */
class Outgoing(val name: String, val size: Long, val mtime: Long, val open: () -> InputStream) {
companion object {
fun of(f: File) = Outgoing(f.name, f.length(), f.lastModified() / 1000, f::inputStream)
}
}
/** Where received files go. */
interface Incoming {
/** a new file named [name] (made safe, and unique there) to write: its stream and the name it got */
fun create(name: String, size: Long): Pair<OutputStream, String>
/** a file finished: [mtime] its time, if known (seconds) */
fun done(name: String, mtime: Long) {}
/** a file not finished (an error, a cancel): what was written, removed */
fun abandon(name: String) {}
}
/** received files into a directory */
class FolderIncoming(private val dir: File) : Incoming {
val received = ArrayList<File>()
override fun create(name: String, size: Long): Pair<OutputStream, String> {
dir.mkdirs()
val f = unique(dir, safeName(name))
return f.outputStream() to f.name
}
override fun done(name: String, mtime: Long) {
val f = File(dir, name)
if (mtime > 0) f.setLastModified(mtime * 1000)
received.add(f)
}
override fun abandon(name: String) {
File(dir, name).delete()
}
companion object {
/** a name with no path in it, nothing a file system minds */
fun safeName(name: String): String {
val base = name.replace('\\', '/').substringAfterLast('/')
.replace(Regex("[\\x00-\\x1f:*?\"<>|]"), "_").trim().trimStart('.')
return base.ifEmpty { "received" }.take(200)
}
/** [name] in [dir], or "name (2).ext" when it's taken */
fun unique(dir: File, name: String): File {
var f = File(dir, name)
if (!f.exists()) return f
val dot = name.lastIndexOf('.').takeIf { it > 0 } ?: name.length
var n = 2
while (f.exists()) {
f = File(dir, name.substring(0, dot) + " ($n)" + name.substring(dot))
n++
}
return f
}
}
}
/** How far a transfer has got. */
data class Progress(
val file: String = "",
val bytes: Long = 0,
/** the file's size, -1 unknown */
val size: Long = -1,
/** files finished so far */
val files: Int = 0,
/** errors corrected on the line (blocks repeated) */
val errors: Int = 0,
)
@@ -0,0 +1,647 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.transfer
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.Calendar
import java.util.TimeZone
/**
* Kermit, both ways, stop-and-wait: packets of printable characters (so it
* goes over lines nothing else does), control characters prefixed, the
* 8th bit prefixed when the line is 7-bit, runs of a byte counted; long
* packets, 1-, 2- and 3-character (CRC) checks, file attributes (size and
* time), as both sides agree in the S/Y exchange. A bad or missing packet
* is asked for again (NAK), up to [MAX_RETRIES] times; an E packet ends it.
*/
class Kermit(
private val io: TransferIo,
private val progress: (Progress) -> Unit = {},
/** how long to wait for each packet */
private val timeoutMs: Long = 10_000,
/** the line passes only 7 bits: the 8th asked to be prefixed */
private val sevenBit: Boolean = false,
) {
private var p = Progress()
private fun report(f: (Progress) -> Progress) {
p = f(p)
progress(p)
}
// what's agreed: the defaults, until the S/Y exchange
/** the longest packet the other side takes (its LEN, or its long packets' length) */
private var sendMax = 80
private var sendLong = 0
private var eol = CR
private var npad = 0
private var padc = 0
/** the other side's control prefix: what it sends with */
private var theirQctl = '#'.code
private var qbin = 0
private var rept = 0
private var check = 1
private var attributes = false
/** what the next packet goes out with: an E packet sent on a cancel uses it */
private var seq = 0
class Packet(val seq: Int, val type: Char, val data: ByteArray) {
override fun toString() = "Packet($type $seq, ${data.size})"
}
// ------------------------------------------------------------------
// packets
private fun checkLen(type: Char) = if (type == 'S' || type == 'I' || type == 'R') 1 else if (forceCheck1) 1 else check
/** (during the S/Y exchange, both sides on type 1) */
private var forceCheck1 = true
private fun sendPacket(seq: Int, type: Char, data: ByteArray) {
val ct = checkLen(type)
val out = ByteArrayOutputStream()
repeat(npad) { out.write(padc) }
out.write(MARK)
val body = ByteArrayOutputStream()
if (data.size + 2 + ct <= 94) {
body.write(tochar(data.size + 2 + ct))
body.write(tochar(seq))
body.write(type.code)
} else {
val lx = data.size + ct
body.write(tochar(0))
body.write(tochar(seq))
body.write(type.code)
body.write(tochar(lx / 95))
body.write(tochar(lx % 95))
val h = body.toByteArray()
body.write(check1(h, 0, h.size))
}
body.write(data)
val b = body.toByteArray()
out.write(b)
out.write(checkChars(ct, b, 0, b.size))
out.write(eol)
io.write(out.toByteArray())
}
private fun checkChars(type: Int, b: ByteArray, off: Int, len: Int): ByteArray {
var s = 0
for (i in off until off + len) s += b[i].toInt() and 0xff
return when (type) {
1 -> byteArrayOf(tochar((s + ((s and 192) shr 6)) and 63).toByte())
2 -> byteArrayOf(tochar((s shr 6) and 63).toByte(), tochar(s and 63).toByte())
else -> {
val c = crc(b, off, len)
byteArrayOf(tochar((c shr 12) and 0x0f).toByte(), tochar((c shr 6) and 63).toByte(), tochar(c and 63).toByte())
}
}
}
private fun check1(b: ByteArray, off: Int, len: Int): Int = checkChars(1, b, off, len)[0].toInt()
/**
* the next good packet, or null on a timeout or a bad one (garbage
* before its mark skipped; a mark in the middle starts over)
*/
private fun readPacket(wait: Long = timeoutMs): Packet? {
val deadline = System.currentTimeMillis() + wait
fun next(): Int {
val left = deadline - System.currentTimeMillis()
if (left <= 0) return -1
return io.read(left)
}
var c = next()
outer@ while (true) {
while (c != MARK) {
if (c < 0) return null
c = next()
}
val buf = ByteArrayOutputStream()
fun take(): Int {
val v = next()
if (v >= 0) buf.write(v)
return v
}
// LEN SEQ TYPE
val hdr = IntArray(3)
for (i in 0 until 3) {
val v = take()
if (v < 0) return null
if (v == MARK) { c = v; continue@outer }
hdr[i] = v
}
val len = unchar(hdr[0])
val pseq = unchar(hdr[1])
val type = hdr[2].toChar()
val rest: Int
if (len == 0) {
// extended: LENX1 LENX2 HCHECK
val x = IntArray(3)
for (i in 0 until 3) {
val v = take()
if (v < 0) return null
if (v == MARK) { c = v; continue@outer }
x[i] = v
}
val h = buf.toByteArray()
if (check1(h, 0, 5) != x[2]) return null
rest = unchar(x[0]) * 95 + unchar(x[1])
} else {
if (len < 3) return null
rest = len - 2
}
if (rest > 9100) return null
val headerLen = buf.size()
for (i in 0 until rest) {
val v = take()
if (v < 0) return null
if (v == MARK) { c = v; continue@outer }
}
val all = buf.toByteArray()
val ct = if (type == 'S' || type == 'I' || type == 'R' || forceCheck1) 1
// (an S or I packet's ACK: type 1 too)
else if (type == 'Y' && pseq == 0 && lastSentType == 'S') 1
// a NAK or an error: the check its length makes plain
else check
if (rest < ct) return null
val dataEnd = all.size - ct
val want = checkChars(ct, all, 0, dataEnd)
for (i in 0 until ct) {
if (all[dataEnd + i] != want[i]) {
// (an E or N packet sent before the check type changed: type 1)
if ((type == 'N' || type == 'E') && ct != 1 && rest >= 1) {
val w1 = checkChars(1, all, 0, all.size - 1)
if (all[all.size - 1] == w1[0]) return Packet(pseq, type, all.copyOfRange(headerLen, all.size - 1))
}
return null
}
}
return Packet(pseq, type, all.copyOfRange(headerLen, dataEnd))
}
}
private var lastSentType = ' '
private fun error(why: String): Nothing {
runCatching { sendPacket(seq, 'E', encodeText(why)) }
throw IOException(why)
}
/** an E packet ending the transfer, for sending when the user cancels */
fun cancelBytes(): ByteArray {
val out = ByteArrayOutputStream()
val tmp = TransferIo { out.write(it) }
Kermit(tmp).also {
it.check = check
it.forceCheck1 = forceCheck1
it.eol = eol
}.sendPacket(seq, 'E', "cancelled".toByteArray())
return out.toByteArray()
}
// ------------------------------------------------------------------
// the S/Y exchange
private fun ourParams(): ByteArray {
val b = ByteArrayOutputStream()
b.write(tochar(94)) // MAXL
b.write(tochar((timeoutMs / 1000).toInt().coerceIn(1, 94))) // TIME
b.write(tochar(0)) // NPAD
b.write(ctl(0)) // PADC
b.write(tochar(CR)) // EOL
b.write(OUR_QCTL) // QCTL
b.write(if (sevenBit) '&'.code else 'Y'.code) // QBIN
b.write('3'.code) // CHKT
b.write(REPT) // REPT
b.write(tochar(CAP_LP or CAP_AT)) // CAPAS
b.write(tochar(1)) // WINDO
b.write(tochar(OUR_LONG / 95)) // MAXLX1
b.write(tochar(OUR_LONG % 95)) // MAXLX2
return b.toByteArray()
}
/** their parameters, agreed with ours ([sender]: we're the one that sent the S) */
@Suppress("UNUSED_PARAMETER")
private fun agree(d: ByteArray, sender: Boolean) {
fun at(i: Int): Int = if (i < d.size) d[i].toInt() and 0xff else -1
at(0).takeIf { it > 32 }?.let { sendMax = unchar(it).coerceIn(10, 94) }
npad = at(2).takeIf { it > 32 }?.let { unchar(it) } ?: 0
padc = at(3).takeIf { it >= 0 }?.let { ctl(it) } ?: 0
eol = at(4).takeIf { it > 32 }?.let { unchar(it) } ?: CR
theirQctl = at(5).takeIf { it > 32 } ?: '#'.code
val ourQbin = if (sevenBit) '&'.code else 'Y'.code
val theirQbin = at(6)
qbin = when {
theirQbin == 'Y'.code && ourQbin != 'Y'.code -> ourQbin
isPrefix(theirQbin) && (ourQbin == 'Y'.code || ourQbin == theirQbin) -> theirQbin
else -> 0
}
val theirCheck = at(7).takeIf { it in '1'.code..'3'.code }?.let { it - '0'.code } ?: 1
check = if (theirCheck == 3) 3 else if (theirCheck == 2) 2 else 1
rept = if (at(8) == REPT) REPT else 0
// capabilities (more bytes follow while the lowest bit is set)
var i = 9
var caps = 0
if (at(i) > 32) {
caps = unchar(at(i))
while (at(i) >= 0 && (unchar(at(i)) and 1) != 0) i++
}
i++
attributes = (caps and CAP_AT) != 0
sendLong = 0
if ((caps and CAP_LP) != 0) {
// WINDO, then MAXLX1 MAXLX2 (none: 500)
val x1 = at(i + 1)
val x2 = at(i + 2)
sendLong = if (x1 > 32 || x2 > 32) unchar(maxOf(x1, 32)) * 95 + unchar(maxOf(x2, 32)) else 500
if (sendLong < 95) sendLong = 0
sendLong = minOf(sendLong, OUR_LONG)
}
if (qbin != 0 && qbin == rept) rept = 0
}
private fun isPrefix(c: Int) = c in 33..62 || c in 96..126
// ------------------------------------------------------------------
// the data's encoding
/** room for data in a packet (an encoded byte is up to 5 characters: kept whole) */
private fun room(): Int {
val ct = check
return if (sendLong > 0) sendLong - 5 - ct - 2 else sendMax - 2 - ct
}
private fun encodeByte(out: ByteArrayOutputStream, v: Int) {
var b = v
if (qbin != 0 && b and 0x80 != 0) {
out.write(qbin)
b = b and 0x7f
}
val b7 = b and 0x7f
when {
b7 < 32 || b7 == 127 -> {
out.write(OUR_QCTL)
out.write(ctl(b))
}
b7 == OUR_QCTL || (qbin != 0 && b7 == qbin) || (rept != 0 && b7 == rept) -> {
out.write(OUR_QCTL)
out.write(b)
}
else -> out.write(b)
}
}
/** [src] from [off], encoded into at most [max] characters: the characters and the bytes they hold */
private fun encode(src: ByteArray, off: Int, len: Int, max: Int): Pair<ByteArray, Int> {
val out = ByteArrayOutputStream()
var i = off
val end = off + len
val unit = ByteArrayOutputStream()
while (i < end) {
val v = src[i].toInt() and 0xff
var n = 1
if (rept != 0) while (i + n < end && n < 94 && src[i + n] == src[i]) n++
unit.reset()
if (n >= 3) {
unit.write(rept)
unit.write(tochar(n))
encodeByte(unit, v)
} else {
n = 1
encodeByte(unit, v)
}
if (out.size() + unit.size() > max) break
unit.writeTo(out)
i += n
}
return out.toByteArray() to (i - off)
}
private fun encodeText(s: String): ByteArray {
val b = s.toByteArray(Charsets.UTF_8)
return encode(b, 0, b.size, Int.MAX_VALUE).first
}
/** a packet's data decoded */
private fun decode(d: ByteArray, out: OutputStream) {
var i = 0
while (i < d.size) {
var n = 1
var c = d[i++].toInt() and 0xff
if (rept != 0 && c == rept && i < d.size) {
n = unchar(d[i++].toInt() and 0xff)
if (i >= d.size) break
c = d[i++].toInt() and 0xff
}
var hi = 0
if (qbin != 0 && c == qbin && i < d.size) {
hi = 0x80
c = d[i++].toInt() and 0xff
}
if (c == theirQctl && i < d.size) {
c = d[i++].toInt() and 0xff
val c7 = c and 0x7f
if (c7 in 63..95) c = ctl(c)
}
c = c or hi
repeat(n) { out.write(c) }
}
}
private fun decodeText(d: ByteArray): String = ByteArrayOutputStream().also { decode(d, it) }.toString(Charsets.UTF_8.name())
// ------------------------------------------------------------------
// sending
/** a packet sent until its ACK comes (a NAK of the next one counts): the ACK's data */
private fun exchange(type: Char, data: ByteArray): ByteArray {
var tries = 0
lastSentType = type
while (true) {
sendPacket(seq, type, data)
while (true) {
val r = readPacket() ?: break
when {
r.type == 'E' -> throw IOException("the receiver: " + decodeText(r.data))
r.type == 'Y' && r.seq == seq -> {
seq = (seq + 1) and 63
return r.data
}
r.type == 'N' && r.seq == ((seq + 1) and 63) -> {
seq = (seq + 1) and 63
return ByteArray(0)
}
r.type == 'N' -> break
// (an old ACK, repeated: the next one waited for)
}
}
if (++tries > MAX_RETRIES) error("too many retries")
report { it.copy(errors = it.errors + 1) }
}
}
/** [files] sent: the S/Y exchange, then each file (F, A, D…, Z), then B */
fun send(files: List<Outgoing>) {
seq = 0
forceCheck1 = true
val their = exchange('S', ourParams())
agree(their, sender = true)
forceCheck1 = false
for (f in files) sendFile(f)
exchange('B', ByteArray(0))
}
private fun sendFile(f: Outgoing) {
report { it.copy(file = f.name, bytes = 0, size = f.size) }
val nameAck = exchange('F', encodeText(f.name))
if (nameAck.isNotEmpty()) decodeText(nameAck)
if (attributes) {
val a = ByteArrayOutputStream()
fun attr(tag: Char, v: String) {
a.write(tag.code)
a.write(tochar(v.length))
a.write(v.toByteArray(Charsets.US_ASCII))
}
attr('"', "B8") // binary, 8-bit
if (f.size >= 0) {
attr('!', ((f.size + 1023) / 1024).toString())
attr('1', f.size.toString())
}
if (f.mtime > 0) attr('#', formatDate(f.mtime))
val r = exchange('A', a.toByteArray())
if (r.isNotEmpty() && r[0] == 'N'.code.toByte()) {
// refused: the file skipped
exchange('Z', byteArrayOf('D'.code.toByte()))
return
}
}
val buf = ByteArray(OUR_LONG)
var have = 0
var sent = 0L
f.open().use { input: InputStream ->
var eof = false
while (true) {
while (!eof && have < buf.size) {
val n = input.read(buf, have, buf.size - have)
if (n < 0) eof = true else have += n
}
if (have == 0) break
val (chars, used) = encode(buf, 0, have, room())
val ack = exchange('D', chars)
System.arraycopy(buf, used, buf, 0, have - used)
have -= used
sent += used
report { it.copy(bytes = sent) }
if (ack.isNotEmpty() && (ack[0] == 'X'.code.toByte() || ack[0] == 'Z'.code.toByte())) {
// the receiver wants no more of this file (or of any)
exchange('Z', byteArrayOf('D'.code.toByte()))
if (ack[0] == 'Z'.code.toByte()) throw TransferCancelled("cancelled by the receiver")
return
}
}
}
exchange('Z', ByteArray(0))
report { it.copy(files = it.files + 1) }
}
// ------------------------------------------------------------------
// receiving
private fun ack(seq: Int, data: ByteArray = ByteArray(0)) {
lastSentType = 'Y'
sendPacket(seq, 'Y', data)
}
private fun nak(seq: Int) {
lastSentType = 'N'
sendPacket(seq, 'N', ByteArray(0))
}
/** files received into [into] until the sender's B: the names they got */
fun receive(into: Incoming): List<String> {
val names = ArrayList<String>()
seq = 0
forceCheck1 = true
var tries = 0
// waiting for the S (a NAK now and then, for a sender waiting for one)
var init: Packet
while (true) {
val r = readPacket()
if (r != null && r.type == 'S') { init = r; break }
if (r != null && r.type == 'E') throw IOException("the sender: " + decodeText(r.data))
if (++tries > MAX_RETRIES) throw IOException("the sender didn't start")
nak(0)
}
agree(init.data, sender = false)
val ours = ourParams()
ack(init.seq, ours)
var lastAck: Pair<Int, ByteArray> = init.seq to ours
forceCheck1 = false
seq = (init.seq + 1) and 63
var out: OutputStream? = null
var current: String? = null
var mtime = 0L
var got = 0L
tries = 0
try {
while (true) {
val r = readPacket()
if (r == null || r.seq != seq) {
if (r != null && r.seq == lastAck.first) {
// our ACK lost: sent again
if (r.type == 'S') forceCheck1 = true
ack(lastAck.first, lastAck.second)
forceCheck1 = false
} else if (r != null && r.type == 'E') {
throw IOException("the sender: " + decodeText(r.data))
} else {
nak(seq)
}
if (++tries > MAX_RETRIES) error("too many retries")
report { it.copy(errors = it.errors + 1) }
continue
}
tries = 0
var reply = ByteArray(0)
when (r.type) {
'F' -> {
val name = decodeText(r.data)
val (o, actual) = into.create(name, -1)
out = o.buffered()
current = actual
mtime = 0
got = 0
report { it.copy(file = actual, bytes = 0, size = -1) }
reply = encodeText(actual)
}
'A' -> {
val a = r.data
var i = 0
while (i + 1 < a.size) {
val tag = a[i].toInt().toChar()
val n = unchar(a[i + 1].toInt() and 0xff)
if (i + 2 + n > a.size) break
val v = String(a, i + 2, n, Charsets.US_ASCII)
when (tag) {
'1' -> v.trim().toLongOrNull()?.let { s -> report { it.copy(size = s) } }
'!' -> if (p.size < 0) v.trim().toLongOrNull()?.let { k -> report { it.copy(size = k * 1024) } }
'#' -> mtime = parseDate(v)
}
i += 2 + n
}
reply = "Y".toByteArray()
}
'D' -> {
val o = out ?: error("data before a file's name")
val counted = CountingStream(o)
decode(r.data, counted)
got += counted.n
report { it.copy(bytes = got) }
}
'Z' -> {
val o = out
val name = current
out = null
current = null
if (o != null && name != null) {
o.close()
if (r.data.isNotEmpty() && r.data[0] == 'D'.code.toByte()) {
into.abandon(name)
} else {
into.done(name, mtime)
names.add(name)
report { it.copy(files = it.files + 1) }
}
}
}
'B' -> {
ack(r.seq)
return names
}
'E' -> throw IOException("the sender: " + decodeText(r.data))
'X' -> {
// text to show (a server's): taken like a file with no name
reply = ByteArray(0)
}
else -> error("unexpected ${r.type} packet")
}
ack(r.seq, reply)
lastAck = r.seq to reply
seq = (seq + 1) and 63
}
} catch (e: IOException) {
runCatching { out?.close() }
current?.let { into.abandon(it) }
throw e
}
}
private class CountingStream(private val o: OutputStream) : OutputStream() {
var n = 0L
override fun write(b: Int) { o.write(b); n++ }
}
companion object {
const val MARK = 1
const val CR = 13
const val OUR_QCTL = '#'.code
const val REPT = '~'.code
const val CAP_LP = 2
const val CAP_AT = 8
/** the long packets asked for */
const val OUR_LONG = 4000
const val MAX_RETRIES = 10
fun tochar(x: Int) = x + 32
fun unchar(x: Int) = x - 32
fun ctl(x: Int) = x xor 64
/** CRC-16/KERMIT (CCITT, bits reflected, from 0) */
fun crc(b: ByteArray, off: Int, len: Int): Int {
var c = 0
for (i in off until off + len) {
c = c xor (b[i].toInt() and 0xff)
repeat(8) { c = if (c and 1 != 0) (c ushr 1) xor 0x8408 else c ushr 1 }
}
return c
}
/** a send's start: a Send-Init packet (sequence 0), as kermit -s sends it, in [b] */
fun looksLikeStart(b: ByteArray, off: Int = 0, len: Int = b.size - off): Boolean {
for (i in off until off + len - 3) {
if (b[i].toInt() == MARK && b[i + 2].toInt() == tochar(0) && b[i + 3] == 'S'.code.toByte()) {
val l = (b[i + 1].toInt() and 0xff) - 32
if (l in 4..94) return true
}
}
return false
}
private fun formatDate(sec: Long): String {
val c = Calendar.getInstance(TimeZone.getDefault())
c.timeInMillis = sec * 1000
return "%04d%02d%02d %02d:%02d:%02d".format(
c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH),
c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c.get(Calendar.SECOND),
)
}
/** "[yy]yymmdd[ hh:mm[:ss]]", local time: seconds, 0 when it isn't one */
private fun parseDate(v: String): Long {
val m = Regex("""^(\d{6}|\d{8})(?:\s+(\d{1,2}):(\d{2})(?::(\d{2}))?)?""").find(v.trim()) ?: return 0
val d = m.groupValues[1]
val year = if (d.length == 8) d.substring(0, 4).toInt() else 1900 + d.substring(0, 2).toInt().let { if (it < 70) it + 100 else it }
val rest = d.takeLast(4)
val c = Calendar.getInstance(TimeZone.getDefault())
c.clear()
c.set(year, rest.substring(0, 2).toInt() - 1, rest.substring(2).toInt(),
m.groupValues[2].toIntOrNull() ?: 0, m.groupValues[3].toIntOrNull() ?: 0, m.groupValues[4].toIntOrNull() ?: 0)
return c.timeInMillis / 1000
}
}
}
@@ -0,0 +1,154 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.transfer
import java.io.IOException
/** The file transfer protocols. */
enum class Protocol(val label: String, val batch: Boolean) {
ZMODEM("ZMODEM", true),
YMODEM("YMODEM", true),
XMODEM("XMODEM", false),
XMODEM_1K("XMODEM-1K", false),
KERMIT("Kermit", true),
;
/** what to type at the remote's shell for it to send (the files' names after it), or to receive */
fun remoteCommand(remoteSends: Boolean): String = when (this) {
ZMODEM -> if (remoteSends) "sz -b " else "rz -b"
YMODEM -> if (remoteSends) "sb " else "rb"
XMODEM -> if (remoteSends) "sx " else "rx -c "
XMODEM_1K -> if (remoteSends) "sx -k " else "rx -c "
KERMIT -> if (remoteSends) "kermit -i -s " else "kermit -i -r"
}
}
/** A transfer's state as it goes, and how it ended. */
data class TransferState(
val protocol: Protocol,
/** true: files to the remote */
val sending: Boolean,
val progress: Progress = Progress(),
/** null while it runs; then "" when it went well, else why it didn't */
val result: String? = null,
/** the names the received files got */
val received: List<String> = emptyList(),
) {
val running: Boolean get() = result == null
}
/**
* One transfer on a line, on its own thread: the session feeds it the
* remote's bytes ([io]) while it runs; [onEnd] has what it didn't read.
*/
class Transfer(
val protocol: Protocol,
val sending: Boolean,
send: (ByteArray) -> Unit,
/** the session's raw write (around a cancel, which [io] refuses) */
private val sendRaw: (ByteArray) -> Unit,
private val onState: (TransferState) -> Unit,
private val onEnd: (TransferState, ByteArray) -> Unit,
) {
val io = TransferIo(send)
@Volatile var state = TransferState(protocol, sending)
private set
private var kermit: Kermit? = null
private var thread: Thread? = null
private fun update(s: TransferState) {
state = s
onState(s)
}
private val progress: (Progress) -> Unit = { p -> update(state.copy(progress = p)) }
/** files received into [into] ([name]: XMODEM's, which sends none) */
fun receive(into: Incoming, name: String = "received.bin") = start {
when (protocol) {
Protocol.ZMODEM -> ZModem(io, progress).receive(into)
Protocol.YMODEM -> XYModem(io, progress).receiveY(into)
Protocol.XMODEM, Protocol.XMODEM_1K -> listOf(XYModem(io, progress).receiveX(into, name))
Protocol.KERMIT -> Kermit(io, progress).also { kermit = it }.receive(into)
}
}
/** [files] sent ([files]' first only, for XMODEM) */
fun send(files: List<Outgoing>) = start {
when (protocol) {
Protocol.ZMODEM -> ZModem(io, progress).send(files)
Protocol.YMODEM -> XYModem(io, progress).sendY(files)
Protocol.XMODEM -> XYModem(io, progress).sendX(files.first(), oneK = false)
Protocol.XMODEM_1K -> XYModem(io, progress).sendX(files.first(), oneK = true)
Protocol.KERMIT -> Kermit(io, progress).also { kermit = it }.send(files)
}
emptyList()
}
private fun start(body: () -> List<String>) {
update(state)
thread = Thread({
val end = try {
val names = body()
state.copy(result = "", received = names)
} catch (e: TransferCancelled) {
state.copy(result = e.message ?: "cancelled")
} catch (e: IOException) {
state.copy(result = e.message ?: e.toString())
} catch (e: RuntimeException) {
state.copy(result = e.toString())
}
// (what the other side still sends of the protocol settles first)
if (end.result != "") Thread.sleep(300)
update(end)
onEnd(end, io.leftover())
}, "transfer-${protocol.name.lowercase()}").apply {
isDaemon = true
start()
}
}
/** stopped: the other side told (CANs; Kermit's E packet), the thread ends at its next read */
fun cancel() {
if (!state.running) return
runCatching {
sendRaw(
when (protocol) {
Protocol.KERMIT -> kermit?.cancelBytes() ?: ByteArray(0)
else -> ZModem.CANCEL
},
)
}
io.cancel("cancelled")
}
/** for tests: until it ends */
fun join(ms: Long) = thread?.join(ms)
companion object {
/**
* where in [b] a remote starts a transfer of its own: sz (ZMODEM
* receive here), rz (it waits for files: pick them), kermit -s
*/
fun detect(b: ByteArray, len: Int): Pair<Int, Detected>? {
val z = indexOf(b, len, ZModem.SZ_START)
if (z >= 0) return z to Detected.ZMODEM_SEND
val r = indexOf(b, len, ZModem.RZ_START)
if (r >= 0) return r to Detected.ZMODEM_RECEIVE
if (Kermit.looksLikeStart(b, 0, len)) {
for (i in 0 until len) if (b[i].toInt() == Kermit.MARK) return i to Detected.KERMIT_SEND
}
return null
}
private fun indexOf(b: ByteArray, len: Int, pat: ByteArray): Int {
outer@ for (i in 0..len - pat.size) {
for (j in pat.indices) if (b[i + j] != pat[j]) continue@outer
return i
}
return -1
}
}
enum class Detected { ZMODEM_SEND, ZMODEM_RECEIVE, KERMIT_SEND }
}
@@ -0,0 +1,77 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.transfer
import java.io.IOException
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
/** The transfer was stopped: by the user, or the other side. */
class TransferCancelled(msg: String) : IOException(msg)
/**
* A transfer's line: what comes from the remote (fed by the session,
* instead of to the terminal), read with timeouts; what it sends, to the
* remote. [cancel] makes the next read throw.
*/
class TransferIo(private val send: (ByteArray) -> Unit) {
/** each way's bytes as they go (true: from the remote), for finding faults */
@Volatile var trace: ((Boolean, ByteArray) -> Unit)? = null
private val queue = LinkedBlockingQueue<ByteArray>()
private var cur: ByteArray? = null
private var pos = 0
@Volatile private var cancelled: String? = null
/** bytes from the remote */
fun feed(data: ByteArray, off: Int = 0, len: Int = data.size - off) {
if (len > 0) queue.put(data.copyOfRange(off, off + len).also { b -> trace?.invoke(true, b) })
}
fun write(b: ByteArray) {
if (cancelled != null) throw TransferCancelled(cancelled!!)
trace?.invoke(false, b)
send(b)
}
fun write(vararg b: Int) = write(ByteArray(b.size) { b[it].toByte() })
/** a byte (0-255), or -1 when none came within [timeoutMs] (the cancel looked at every quarter second) */
fun read(timeoutMs: Long): Int {
val deadline = System.nanoTime() + timeoutMs * 1_000_000
while (true) {
cancelled?.let { throw TransferCancelled(it) }
val c = cur
if (c != null && pos < c.size) return c[pos++].toInt() and 0xff
val left = (deadline - System.nanoTime()) / 1_000_000
if (left <= 0) return -1
val next = queue.poll(minOf(left, 250L), TimeUnit.MILLISECONDS) ?: continue
cur = next
pos = 0
}
}
/** whether bytes are waiting (without waiting for any) */
fun available(): Boolean = (cur?.let { pos < it.size } == true) || queue.isNotEmpty()
/** everything waiting dropped (to resynchronise) */
fun purge() {
cur = null
queue.clear()
}
/** what came but wasn't read: back to the terminal when the transfer ends */
fun leftover(): ByteArray {
val out = java.io.ByteArrayOutputStream()
cur?.let { if (pos < it.size) out.write(it, pos, it.size - pos) }
cur = null
while (true) out.write(queue.poll() ?: break)
return out.toByteArray()
}
fun cancel(why: String) {
cancelled = why
}
val isCancelled: Boolean get() = cancelled != null
}
@@ -0,0 +1,348 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.transfer
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
/**
* XMODEM (128-byte blocks, checksum or CRC; 1K blocks) and YMODEM (1K
* blocks, CRC, a batch of files each named and sized in block 0), both
* ways. Errors are repeated (NAK) up to [MAX_ERRORS] times; CAN CAN
* from the other side ends it.
*/
class XYModem(
private val io: TransferIo,
private val progress: (Progress) -> Unit = {},
/** how long to wait for each answer (longer on a slow modem line) */
private val timeoutMs: Long = 10_000,
) {
private var p = Progress()
private fun report(f: (Progress) -> Progress) {
p = f(p)
progress(p)
}
// ------------------------------------------------------------------
// receiving
/**
* XMODEM received into [name] in [into] (its size isn't sent: the last
* block's padding, SUB characters, taken off). Returns the name used.
*/
fun receiveX(into: Incoming, name: String): String {
val (out, actual) = into.create(name, -1)
report { it.copy(file = actual) }
try {
out.use { o ->
val trailing = java.io.ByteArrayOutputStream()
receiveFile(o, -1, ymodem = false, first = null, holdLast = trailing)
// the last block, its padding off
val last = trailing.toByteArray()
var end = last.size
while (end > 0 && last[end - 1] == SUB.toByte()) end--
o.write(last, 0, end)
}
into.done(actual, 0)
report { it.copy(files = it.files + 1) }
return actual
} catch (e: IOException) {
into.abandon(actual)
throw e
}
}
/** a YMODEM batch received: the names the files got */
fun receiveY(into: Incoming): List<String> {
val names = ArrayList<String>()
while (true) {
// block 0: the file's name and size, or an empty one (the batch over)
val b0 = startAndRead(ymodem = true) ?: throw IOException("the sender didn't start")
if (b0.number != 0) throw IOException("no YMODEM header block")
val data = b0.data
if (data[0] == 0.toByte()) {
io.write(ACK)
return names
}
val nul = data.indexOf(0.toByte())
val name = String(data, 0, nul, Charsets.UTF_8)
val meta = String(data, nul + 1, data.size - nul - 1, Charsets.ISO_8859_1).trimEnd('\u0000').split(' ')
val size = meta.getOrNull(0)?.toLongOrNull() ?: -1
val mtime = meta.getOrNull(1)?.toLongOrNull(8) ?: 0
io.write(ACK)
val (out, actual) = into.create(name, size)
report { it.copy(file = actual, bytes = 0, size = size) }
try {
out.use { o ->
io.write(C)
receiveFile(o, size, ymodem = true, first = null, holdLast = null)
}
into.done(actual, mtime)
} catch (e: IOException) {
into.abandon(actual)
throw e
}
names.add(actual)
report { it.copy(files = it.files + 1) }
}
}
private class Block(val number: Int, val data: ByteArray)
/** the first block, asked for with C (CRC) and, for XMODEM, NAK (a checksum) when C isn't answered */
private fun startAndRead(ymodem: Boolean): Block? {
var crc = true
for (attempt in 0 until 10) {
if (attempt == 4 && !ymodem) crc = false
io.write(if (crc) C else NAK)
val b = readBlock(crc, 3000) ?: continue
this.crc = crc
return b
}
return null
}
private var crc = true
/**
* a block: (number, data); null on a timeout or a bad block (the line
* purged); throws on EOT handled by the caller via [eot], or CAN
*/
private var eot = false
private fun readBlock(useCrc: Boolean, waitMs: Long): Block? {
eot = false
// (what isn't a block's start let go by: the sender's own messages, line noise)
val deadline = System.currentTimeMillis() + waitMs
var size = 0
while (size == 0) {
val left = deadline - System.currentTimeMillis()
if (left <= 0) return null
when (io.read(left)) {
-1 -> return null
SOH -> size = 128
STX -> size = 1024
EOT -> { eot = true; return null }
CAN -> if (io.read(1000) == CAN) throw TransferCancelled("cancelled by the sender")
}
}
val n = io.read(1000)
val nn = io.read(1000)
if (n < 0 || nn < 0) return null
val data = ByteArray(size)
for (i in 0 until size) {
val c = io.read(1000)
if (c < 0) return null
data[i] = c.toByte()
}
val ok = if (useCrc) {
val hi = io.read(1000)
val lo = io.read(1000)
hi >= 0 && lo >= 0 && Crc.crc16(data) == ((hi shl 8) or lo)
} else {
val sum = io.read(1000)
sum >= 0 && (data.sumOf { it.toInt() and 0xff } and 0xff) == sum
}
if (!ok || (n xor nn) != 0xff) return badBlock()
return Block(n, data)
}
private fun badBlock(): Block? {
// (what's left of the bad block: let it go by)
while (io.read(200) >= 0) { /* drop */ }
return null
}
/**
* a file's blocks into [o] (all but the last one into [holdLast], if
* given: XMODEM takes its padding off): up to [size] bytes if known
*/
private fun receiveFile(o: OutputStream, size: Long, ymodem: Boolean, first: Block?, holdLast: java.io.ByteArrayOutputStream?) {
var expect = 1
var written = 0L
var errors = 0
var held: ByteArray? = null
var block = first ?: if (!ymodem) startAndRead(false) else null
var eots = 0
while (true) {
if (block == null) {
block = readBlock(crc, timeoutMs)
if (block == null) {
if (eot) {
// YMODEM: the first EOT answered NAK, the second ACK (to be sure it was one)
eots++
if (ymodem && eots == 1) {
io.write(NAK)
continue
}
io.write(ACK)
break
}
if (++errors > MAX_ERRORS) throw IOException("too many errors on the line")
report { it.copy(errors = it.errors + 1) }
io.write(NAK)
continue
}
}
val b = block
block = null
when (b.number) {
expect and 0xff -> {
var data = b.data
if (size >= 0 && written + data.size > size) data = data.copyOf((size - written).toInt().coerceAtLeast(0))
if (holdLast != null) {
held?.let { o.write(it) }
held = data
} else {
o.write(data)
}
written += data.size
expect++
errors = 0
io.write(ACK)
report { it.copy(bytes = written) }
}
(expect - 1) and 0xff -> io.write(ACK) // a repeat of one already had (our ACK lost)
else -> {
io.write(CAN, CAN, CAN)
throw IOException("blocks out of order")
}
}
}
held?.let { holdLast?.write(it) }
}
// ------------------------------------------------------------------
// sending
/** one file by XMODEM (1K blocks if [oneK]) */
fun sendX(file: Outgoing, oneK: Boolean) {
val useCrc = waitForStart() ?: throw IOException("the receiver didn't start")
report { it.copy(file = file.name, bytes = 0, size = file.size) }
file.open().use { sendData(it, if (oneK) 1024 else 128, useCrc, ymodem = false) }
report { it.copy(files = it.files + 1) }
}
/** a YMODEM batch */
fun sendY(files: List<Outgoing>) {
for (f in files) {
if (waitForStart() != true) throw IOException("the receiver didn't start")
val head = ByteArray(128)
val meta = (f.name.substringAfterLast('/').toByteArray(Charsets.UTF_8) + 0) +
("${if (f.size >= 0) f.size else 0} ${java.lang.Long.toOctalString(f.mtime.coerceAtLeast(0))} 0").toByteArray()
val block0 = if (meta.size > 128) ByteArray(1024) else head
meta.copyInto(block0, 0, 0, minOf(meta.size, block0.size))
sendBlock(0, block0, true)
report { it.copy(file = f.name, bytes = 0, size = f.size) }
if (waitForStart() != true) throw IOException("the receiver didn't ask for the data")
f.open().use { sendData(it, 1024, useCrc = true, ymodem = true) }
report { it.copy(files = it.files + 1) }
}
// the batch over: an empty block 0
if (waitForStart() != true) throw IOException("the receiver didn't ask for the end")
sendBlock(0, ByteArray(128), true)
}
/** C (CRC: true) or NAK (checksum: false) from the receiver; null if neither came */
private fun waitForStart(): Boolean? {
val end = System.currentTimeMillis() + 60_000
while (System.currentTimeMillis() < end) {
when (io.read(timeoutMs)) {
C -> return true
NAK -> return false
CAN -> if (io.read(1000) == CAN) throw TransferCancelled("cancelled by the receiver")
}
}
return null
}
private fun sendData(input: InputStream, blockSize: Int, useCrc: Boolean, ymodem: Boolean) {
var n = 1
var sent = 0L
val buf = ByteArray(blockSize)
while (true) {
var len = 0
while (len < blockSize) {
val r = input.read(buf, len, blockSize - len)
if (r < 0) break
len += r
}
if (len == 0) break
// a short last block in 128 when it fits (less padding), padded with SUB
val size = if (len <= 128) 128 else blockSize
val data = buf.copyOf(size)
for (i in len until size) data[i] = SUB.toByte()
sendBlock(n, data, useCrc)
sent += len
n++
report { it.copy(bytes = sent) }
if (len < blockSize) break
}
// the end: EOT until it's answered ACK (YMODEM answers the first NAK)
var tries = 0
while (true) {
io.write(EOT)
if (answer(allowC = false) == ACK) return
if (++tries > MAX_ERRORS) throw IOException("the end not acknowledged")
}
}
/** a block sent until it's acknowledged */
private fun sendBlock(n: Int, data: ByteArray, useCrc: Boolean) {
val out = java.io.ByteArrayOutputStream()
out.write(if (data.size == 1024) STX else SOH)
out.write(n and 0xff)
out.write(0xff - (n and 0xff))
out.write(data)
if (useCrc) {
val c = Crc.crc16(data)
out.write(c shr 8)
out.write(c and 0xff)
} else {
out.write(data.sumOf { it.toInt() and 0xff } and 0xff)
}
val bytes = out.toByteArray()
var errors = 0
while (true) {
io.write(bytes)
if (answer(allowC = n == 0) == ACK) return
if (++errors > MAX_ERRORS) throw IOException("too many errors on the line")
report { it.copy(errors = it.errors + 1) }
}
}
/**
* the receiver's answer to what was sent: ACK, or NAK (also for a
* timeout); other bytes (its messages, noise) let go by; C taken as
* an ACK for block 0 when [allowC] (receivers that ask for the data
* straight away)
*/
private fun answer(allowC: Boolean): Int {
val deadline = System.currentTimeMillis() + timeoutMs
while (true) {
val left = deadline - System.currentTimeMillis()
if (left <= 0) return NAK
when (io.read(left)) {
-1 -> return NAK
ACK -> return ACK
NAK -> return NAK
C -> if (allowC) return ACK
CAN -> if (io.read(1000) == CAN) throw TransferCancelled("cancelled by the receiver")
}
}
}
companion object {
const val SOH = 0x01
const val STX = 0x02
const val EOT = 0x04
const val ACK = 0x06
const val NAK = 0x15
const val CAN = 0x18
const val SUB = 0x1a
const val C = 'C'.code
const val MAX_ERRORS = 10
}
}
@@ -0,0 +1,661 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.transfer
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
/**
* ZMODEM (Forsberg's, as lrzsz's sz and rz speak it), both ways: hex and
* binary headers (CRC-16, and CRC-32 when both sides can), ZDLE escaping,
* data in subpackets streamed (ZCRCG) with the receiver's ZRPOS putting
* the sender back where the line went wrong, files offered by name, size
* and time, and ended with ZFIN and "OO".
*/
class ZModem(
private val io: TransferIo,
private val progress: (Progress) -> Unit = {},
private val timeoutMs: Long = 10_000,
) {
private var p = Progress()
private fun report(f: (Progress) -> Progress) {
p = f(p)
progress(p)
}
// ------------------------------------------------------------------
// the frames
class Header(val type: Int, val p: ByteArray = ByteArray(4)) {
/** ZP0..ZP3 as a number (positions) */
val pos: Long get() = (p[0].toLong() and 0xff) or ((p[1].toLong() and 0xff) shl 8) or
((p[2].toLong() and 0xff) shl 16) or ((p[3].toLong() and 0xff) shl 24)
/** ZF0 (ZF0 is p[3], as the spec numbers the flags) */
val f0: Int get() = p[3].toInt() and 0xff
override fun toString() = "Header(${NAMES.getOrElse(type) { "$type" }}, $pos)"
companion object {
fun pos(type: Int, pos: Long) = Header(type, ByteArray(4) { ((pos shr (8 * it)) and 0xff).toByte() })
fun flags(type: Int, f0: Int, f1: Int = 0, f2: Int = 0, f3: Int = 0) =
Header(type, byteArrayOf(f3.toByte(), f2.toByte(), f1.toByte(), f0.toByte()))
}
}
/** whether the receiver can take CRC-32 (we use it then) */
private var crc32 = false
/** a header in hex (the first ones, and the receiver's) */
private fun sendHex(h: Header) {
val b = ByteArrayOutputStream()
b.write(ZPAD); b.write(ZPAD); b.write(ZDLE); b.write('B'.code)
val raw = byteArrayOf(h.type.toByte()) + h.p
for (x in raw) b.write(hex2(x.toInt() and 0xff))
val crc = Crc.crc16(raw)
b.write(hex2(crc shr 8)); b.write(hex2(crc and 0xff))
b.write(0x0d); b.write(0x8a)
// (an XON after all but ZACK and ZFIN, as sz does: a line stopped by flow control started again)
if (h.type != ZACK && h.type != ZFIN) b.write(XON)
io.write(b.toByteArray())
}
private fun hex2(v: Int): ByteArray = "%02x".format(v).toByteArray()
/** a header in binary (the sender's): CRC-32 when the receiver can */
private fun sendBin(h: Header) {
val b = ByteArrayOutputStream()
b.write(ZPAD); b.write(ZDLE); b.write(if (crc32) 'C'.code else 'A'.code)
val raw = byteArrayOf(h.type.toByte()) + h.p
for (x in raw) escape(b, x.toInt() and 0xff)
if (crc32) {
val c = Crc.crc32(raw).inv()
for (i in 0 until 4) escape(b, (c ushr (8 * i)) and 0xff)
} else {
val c = Crc.crc16(raw)
escape(b, c shr 8); escape(b, c and 0xff)
}
io.write(b.toByteArray())
}
/** a data subpacket ended by [end] (ZCRCE, ZCRCG, ZCRCQ, ZCRCW) */
private fun sendData(data: ByteArray, len: Int, end: Int) {
val b = ByteArrayOutputStream(len + len / 8 + 16)
for (i in 0 until len) escape(b, data[i].toInt() and 0xff)
b.write(ZDLE); b.write(end)
if (crc32) {
val c = Crc.crc32(Crc.crc32(data, 0, len), end).inv()
for (i in 0 until 4) escape(b, (c ushr (8 * i)) and 0xff)
} else {
val c = Crc.crc16(Crc.crc16(data, 0, len), end)
escape(b, c shr 8); escape(b, c and 0xff)
}
if (end == ZCRCW) b.write(XON)
io.write(b.toByteArray())
}
private var lastSent = 0
/** ZDLE escaping: ZDLE, XON/XOFF, DLE (and their high-bit forms), and CR after @ (a Telnet escape) */
private fun escape(b: ByteArrayOutputStream, c: Int) {
val esc = when (c) {
ZDLE, 0x10, 0x90, 0x11, 0x91, 0x13, 0x93 -> true
0x0d, 0x8d -> (lastSent and 0x7f) == '@'.code
0x7f -> false
0xff -> false
else -> false
}
if (esc) {
b.write(ZDLE)
b.write(c xor 0x40)
} else {
b.write(c)
}
lastSent = c
}
/** a byte with ZDLE's escapes undone; GOT_* (over 0xff) for a frame end, and CANs counted */
private fun readEscaped(): Int {
while (true) {
val c = readByte()
if (c == XON || c == XOFF || c == XON or 0x80 || c == XOFF or 0x80) continue
if (c != ZDLE) return c
var cans = 1
while (true) {
val d = readByte()
when {
d == XON || d == XOFF || d == XON or 0x80 || d == XOFF or 0x80 -> continue
d == CAN -> {
if (++cans >= 5) throw TransferCancelled("cancelled by the other side")
continue
}
d == ZCRCE || d == ZCRCG || d == ZCRCQ || d == ZCRCW -> return d or GOT_END
d == 'l'.code -> return 0x7f
d == 'm'.code -> return 0xff
(d and 0x60) == 0x40 -> return d xor 0x40
else -> return BAD
}
}
}
}
private fun readByte(): Int {
val c = io.read(timeoutMs)
if (c < 0) throw IOException("the other side went quiet")
return c
}
/**
* the next header: skipping what isn't one ("**" or ZPAD, ZDLE, then
* A, B or C); null when one came damaged (its check failed)
*/
private fun readHeader(): Header? {
var garbage = 0
var cans = 0
while (true) {
val c = readByte()
if (c == CAN) {
if (++cans >= 5) throw TransferCancelled("cancelled by the other side")
} else {
cans = 0
}
if (c != ZDLE && c != ZDLE or 0x80) {
if (++garbage > 64 * 1024) throw IOException("no ZMODEM header")
continue
}
val kind = readByte() and 0x7f
// (the ZDLE before a header is also a CAN: one isn't a cancel)
if (kind == CAN) { cans = 2; continue }
return when (kind) {
'A'.code -> readBinHeader(false)
'C'.code -> readBinHeader(true)
'B'.code -> readHexHeader()
else -> continue
}
}
}
private fun readBinHeader(c32: Boolean): Header? {
val raw = ByteArray(5)
for (i in 0 until 5) {
val c = readEscaped()
if (c > 0xff) return null
raw[i] = c.toByte()
}
if (c32) {
var crc = 0L
for (i in 0 until 4) {
val c = readEscaped()
if (c > 0xff) return null
crc = crc or (c.toLong() shl (8 * i))
}
if (Crc.crc32(raw).inv().toLong() and 0xffffffffL != crc) return null
} else {
val hi = readEscaped()
val lo = readEscaped()
if (hi > 0xff || lo > 0xff || Crc.crc16(raw) != ((hi shl 8) or lo)) return null
}
rxCrc32 = c32
return Header(raw[0].toInt() and 0xff, raw.copyOfRange(1, 5))
}
/** how the sender's data comes: CRC-32 when its headers did */
private var rxCrc32 = false
private fun readHexHeader(): Header? {
val raw = ByteArray(7)
for (i in 0 until 7) {
val hi = hexDigit(readByte() and 0x7f)
val lo = hexDigit(readByte() and 0x7f)
if (hi < 0 || lo < 0) return null
raw[i] = ((hi shl 4) or lo).toByte()
}
// CR LF (or CR with its high bit) after it; then maybe an XON
val crc = ((raw[5].toInt() and 0xff) shl 8) or (raw[6].toInt() and 0xff)
if (Crc.crc16(raw, 0, 5) != crc) return null
// CR LF after every hex header (an XON after most: let go by with the next header's garbage)
readByte(); readByte()
return Header(raw[0].toInt() and 0xff, raw.copyOfRange(1, 5))
}
private fun hexDigit(c: Int): Int = when (c) {
in '0'.code..'9'.code -> c - '0'.code
in 'a'.code..'f'.code -> c - 'a'.code + 10
in 'A'.code..'F'.code -> c - 'A'.code + 10
else -> -1
}
/** a data subpacket: its bytes and how it ended (ZCRCx); null if its check failed or it ran over [max] */
private fun readData(max: Int): Pair<ByteArray, Int>? {
val b = ByteArrayOutputStream()
while (true) {
val c = readEscaped()
if (c == BAD) return null
if (c > 0xff) {
val end = c and 0xff
val data = b.toByteArray()
if (rxCrc32) {
var crc = 0L
for (i in 0 until 4) {
val x = readEscaped()
if (x > 0xff) return null
crc = crc or (x.toLong() shl (8 * i))
}
if (Crc.crc32(Crc.crc32(data), end).inv().toLong() and 0xffffffffL != crc) return null
} else {
val hi = readEscaped()
val lo = readEscaped()
if (hi > 0xff || lo > 0xff || Crc.crc16(Crc.crc16(data), end) != ((hi shl 8) or lo)) return null
}
return data to end
}
b.write(c)
if (b.size() > max) return null
}
}
// ------------------------------------------------------------------
// receiving (the other side runs sz)
/** files received into [into] until the sender ends (ZFIN): their names */
fun receive(into: Incoming): List<String> {
val names = ArrayList<String>()
var errors = 0
fun zrinit() = sendHex(Header.flags(ZRINIT, CANFDX or CANOVIO or CANFC32))
zrinit()
var lastHeaderAt = System.currentTimeMillis()
while (true) {
val h = try {
readHeader()
} catch (e: IOException) {
if (e is TransferCancelled) throw e
// quiet: ask again (the sender may not have heard us)
if (System.currentTimeMillis() - lastHeaderAt > 60_000 || ++errors > MAX_ERRORS) throw e
zrinit()
continue
}
if (h == null) {
if (++errors > MAX_ERRORS) throw IOException("too many errors on the line")
zrinit()
continue
}
lastHeaderAt = System.currentTimeMillis()
when (h.type) {
ZRQINIT -> zrinit()
ZSINIT -> {
readData(1024)
sendHex(Header.pos(ZACK, 0))
}
ZFILE -> {
val d = readData(4096)
if (d == null) {
sendHex(Header(ZNAK))
continue
}
val name = receiveFile(d.first, into) ?: continue
names.add(name)
report { it.copy(files = it.files + 1) }
zrinit()
}
ZFIN -> {
sendHex(Header(ZFIN))
// "OO" (over and out) follows: read past it if it comes
repeat(2) { if (io.read(500) < 0) return names }
return names
}
ZCAN, ZABORT -> throw TransferCancelled("cancelled by the sender")
ZCOMMAND -> {
// commands are never run here
readData(4096)
sendHex(Header.pos(ZCOMPL, 0))
}
ZFREECNT -> sendHex(Header.pos(ZACK, 0))
else -> {}
}
}
}
/** a file's data received after its ZFILE: its name, or null when it was skipped */
private fun receiveFile(info: ByteArray, into: Incoming): String? {
val nul = info.indexOf(0.toByte()).takeIf { it >= 0 } ?: info.size
val name = String(info, 0, nul, Charsets.UTF_8)
val meta = if (nul + 1 < info.size) String(info, nul + 1, info.size - nul - 1, Charsets.ISO_8859_1).trimEnd('\u0000').trim().split(' ') else emptyList()
val size = meta.getOrNull(0)?.toLongOrNull() ?: -1
val mtime = meta.getOrNull(1)?.toLongOrNull(8) ?: 0
val (out, actual) = into.create(name, size)
report { it.copy(file = actual, bytes = 0, size = size) }
var pos = 0L
var errors = 0
var ok = false
try {
out.use { o ->
sendHex(Header.pos(ZRPOS, pos))
loop@ while (true) {
val h = readHeader()
if (h == null) {
if (++errors > MAX_ERRORS) throw IOException("too many errors on the line")
sendHex(Header.pos(ZRPOS, pos))
continue
}
when (h.type) {
ZDATA -> {
if (h.pos != pos) {
// not where we are: back to it (the data in between let go by)
sendHex(Header.pos(ZRPOS, pos))
continue@loop
}
while (true) {
val d = readData(8192)
if (d == null) {
if (++errors > MAX_ERRORS) throw IOException("too many errors on the line")
report { it.copy(errors = it.errors + 1) }
io.purge()
sendHex(Header.pos(ZRPOS, pos))
continue@loop
}
o.write(d.first)
pos += d.first.size
errors = 0
report { it.copy(bytes = pos) }
when (d.second) {
ZCRCW -> { sendHex(Header.pos(ZACK, pos)); continue@loop }
ZCRCQ -> sendHex(Header.pos(ZACK, pos))
ZCRCE -> continue@loop
// ZCRCG: more follows
}
}
}
ZEOF -> {
if (h.pos != pos) continue@loop
ok = true
break@loop
}
ZFILE -> {
// our ZRPOS lost: the same file offered again
readData(4096)
sendHex(Header.pos(ZRPOS, pos))
}
ZSKIP -> break@loop
ZCAN, ZABORT -> throw TransferCancelled("cancelled by the sender")
ZFIN -> throw IOException("the sender ended in the middle of a file")
else -> {}
}
}
}
} catch (e: IOException) {
into.abandon(actual)
throw e
}
if (!ok) {
into.abandon(actual)
return null
}
into.done(actual, mtime)
return actual
}
// ------------------------------------------------------------------
// sending (the other side runs rz)
/**
* [files] sent: "rz\r" first when [startRz] (as sz does, for a shell
* at the other end), then ZRQINIT until the receiver's ZRINIT; each
* file until the receiver's next ZRINIT says it has it
*/
fun send(files: List<Outgoing>, startRz: Boolean = false) {
if (startRz) io.write("rz\r".toByteArray())
val r = waitForZrinit()
crc32 = r.f0 and CANFC32 != 0
var left = files.sumOf { it.size.coerceAtLeast(0) }
for ((i, f) in files.withIndex()) {
report { it.copy(file = f.name, bytes = 0, size = f.size) }
val skipped = sendFile(f, files.size - i, left)
left -= f.size.coerceAtLeast(0)
if (!skipped) report { it.copy(files = it.files + 1) }
}
// the end: ZFIN, its answer, "OO"
for (attempt in 0 until MAX_ERRORS) {
sendHex(Header(ZFIN))
if (readHeaderOrNull()?.type == ZFIN) break
}
io.write("OO".toByteArray())
}
private fun waitForZrinit(): Header {
var tries = 0
sendHex(Header(ZRQINIT))
while (true) {
val h = try {
readHeader()
} catch (e: TransferCancelled) {
throw e
} catch (e: IOException) {
if (++tries > MAX_ERRORS) throw IOException("the receiver didn't answer")
sendHex(Header(ZRQINIT))
continue
}
when (h?.type) {
ZRINIT -> return h
ZCHALLENGE -> sendHex(Header(ZACK, h.p))
ZCAN, ZABORT -> throw TransferCancelled("cancelled by the receiver")
ZRQINIT -> throw IOException("the other side is sending, not receiving")
else -> if (++tries > MAX_ERRORS * 3) throw IOException("the receiver didn't answer")
}
}
}
private fun readHeaderOrNull(): Header? =
try { readHeader() } catch (e: TransferCancelled) { throw e } catch (_: IOException) { null }
/** a file sent, until the receiver's ZRINIT: true if it skipped it */
private fun sendFile(f: Outgoing, filesLeft: Int, bytesLeft: Long): Boolean {
val info = (f.name.substringAfterLast('/').toByteArray(Charsets.UTF_8) + 0) +
("${f.size.coerceAtLeast(0)} ${java.lang.Long.toOctalString(f.mtime.coerceAtLeast(0))} 0 0 $filesLeft $bytesLeft").toByteArray() + 0
var start = -1L
var tries = 0
while (start < 0) {
sendBin(Header.flags(ZFILE, ZCBIN))
sendData(info, info.size, ZCRCW)
val h = readHeaderOrNull()
when (h?.type) {
ZRPOS -> start = h.pos
ZSKIP -> return true
ZCRC -> sendHex(Header.pos(ZCRC, 0))
ZCAN, ZABORT -> throw TransferCancelled("cancelled by the receiver")
ZFERR -> throw IOException("the receiver couldn't write the file")
else -> if (++tries > MAX_ERRORS) throw IOException("the receiver didn't answer the file")
}
}
val reader = Reader(f)
try {
stream(reader, start)
} finally {
reader.close()
}
return false
}
/** a file read from where the receiver wants it (reopened to go back) */
private class Reader(private val f: Outgoing) {
private var input: InputStream = f.open()
var pos = 0L
private set
fun seek(to: Long) {
if (to < pos) {
input.close()
input = f.open()
pos = 0
}
while (pos < to) {
val n = input.skip(to - pos)
if (n > 0) {
pos += n
} else {
if (input.read() < 0) throw IOException("can't go to $to in ${f.name}")
pos++
}
}
}
fun read(buf: ByteArray): Int {
var len = 0
while (len < buf.size) {
val n = input.read(buf, len, buf.size - len)
if (n < 0) break
len += n
}
pos += len
return len
}
fun close() = input.close()
}
/**
* the file's data from [start] in ZCRCG subpackets, a ZCRCQ every
* [WINDOW] bytes to hear how it goes, ZCRCE and ZEOF at the end; a
* ZRPOS from the receiver (in the stream or after ZEOF) puts it back
* there; done at the receiver's ZRINIT
*/
private fun stream(r: Reader, start: Long) {
val buf = ByteArray(BLOCK)
var errors = 0
var at = start
// (errors counted while no progress is made: a long noisy file still gets there)
var lastBack = -1L
fun back(to: Long) {
if (to > lastBack) errors = 0
lastBack = to
if (++errors > MAX_ERRORS) throw IOException("too many errors on the line")
report { it.copy(errors = it.errors + 1) }
at = to
}
resend@ while (true) {
r.seek(at)
sendBin(Header.pos(ZDATA, r.pos))
var sinceAck = 0
while (true) {
// the receiver's word in between, if any: a ZRPOS (an error: back to it)
if (io.available()) {
val h = readHeaderOrNull()
when (h?.type) {
ZRPOS -> {
back(h.pos)
continue@resend
}
ZCAN, ZABORT -> throw TransferCancelled("cancelled by the receiver")
ZSKIP -> return
else -> {}
}
}
val len = r.read(buf)
sinceAck += len
val end = when {
len < BLOCK -> ZCRCE
sinceAck >= WINDOW -> ZCRCQ
else -> ZCRCG
}
sendData(buf, len, end)
report { it.copy(bytes = r.pos) }
if (end == ZCRCE) break
if (end == ZCRCQ) {
sinceAck = 0
val to = waitForAck(r.pos)
if (to != null) {
back(to)
continue@resend
}
}
}
// ZEOF until the receiver's ZRINIT (it has the file), or a ZRPOS (it wants some again)
while (true) {
sendBin(Header.pos(ZEOF, r.pos))
val h = readHeaderOrNull()
when (h?.type) {
ZRINIT -> return
ZRPOS -> {
back(h.pos)
continue@resend
}
ZSKIP -> return
ZCAN, ZABORT -> throw TransferCancelled("cancelled by the receiver")
ZACK -> {}
else -> if (++errors > MAX_ERRORS) throw IOException("the end of the file wasn't answered")
}
}
}
}
/** a ZCRCQ's answer: null for its ACK, else the position a ZRPOS asks for */
private fun waitForAck(pos: Long): Long? {
repeat(MAX_ERRORS) {
val h = readHeaderOrNull() ?: return@repeat
when (h.type) {
ZACK -> return null
ZRPOS -> return h.pos
ZCAN, ZABORT -> throw TransferCancelled("cancelled by the receiver")
}
}
throw IOException("no answer at $pos")
}
companion object {
const val ZPAD = '*'.code
const val ZDLE = 0x18
const val CAN = 0x18
const val XON = 0x11
const val XOFF = 0x13
const val ZRQINIT = 0
const val ZRINIT = 1
const val ZSINIT = 2
const val ZACK = 3
const val ZFILE = 4
const val ZSKIP = 5
const val ZNAK = 6
const val ZABORT = 7
const val ZFIN = 8
const val ZRPOS = 9
const val ZDATA = 10
const val ZEOF = 11
const val ZFERR = 12
const val ZCRC = 13
const val ZCHALLENGE = 14
const val ZCOMPL = 15
const val ZCAN = 16
const val ZFREECNT = 17
const val ZCOMMAND = 18
val NAMES = listOf(
"ZRQINIT", "ZRINIT", "ZSINIT", "ZACK", "ZFILE", "ZSKIP", "ZNAK", "ZABORT", "ZFIN", "ZRPOS",
"ZDATA", "ZEOF", "ZFERR", "ZCRC", "ZCHALLENGE", "ZCOMPL", "ZCAN", "ZFREECNT", "ZCOMMAND",
)
const val ZCRCE = 'h'.code
const val ZCRCG = 'i'.code
const val ZCRCQ = 'j'.code
const val ZCRCW = 'k'.code
private const val GOT_END = 0x100
private const val BAD = 0x200
const val CANFDX = 0x01
const val CANOVIO = 0x02
const val CANFC32 = 0x20
const val ZCBIN = 1
const val BLOCK = 1024
/** bytes between the sender's ZCRCQs (its window) */
const val WINDOW = 16 * 1024
const val MAX_ERRORS = 10
/** a remote sz starting (ZRQINIT) */
val SZ_START = byteArrayOf(ZPAD.toByte(), ZPAD.toByte(), ZDLE.toByte(), 'B'.code.toByte(), '0'.code.toByte(), '0'.code.toByte())
/** a remote rz waiting (ZRINIT) */
val RZ_START = byteArrayOf(ZPAD.toByte(), ZPAD.toByte(), ZDLE.toByte(), 'B'.code.toByte(), '0'.code.toByte(), '1'.code.toByte())
/** what stops a transfer at the other end: CANs, then backspaces over them */
val CANCEL = ByteArray(10) { CAN.toByte() } + ByteArray(10) { 8 }
}
}
@@ -81,6 +81,11 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.Dispatchers
import java.io.File
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import com.neodesktop.dmodem.transfer.DownloadsIncoming
import com.neodesktop.dmodem.transfer.Protocol
import com.neodesktop.dmodem.transfer.outgoingOf
/** The terminal on the modem: the screen, a bar of what's going on and its actions, the extra keys. */
@Composable
@@ -109,6 +114,35 @@ fun TerminalScreen(
var showLinuxInstall by remember { mutableStateOf(false) }
var pickLinux by remember { mutableStateOf<List<com.neodesktop.dmodem.local.LinuxSystem>?>(null) }
val ssh = session.link as? com.neodesktop.dmodem.ssh.SshLink
val transfer by session.transferState.collectAsStateWithLifecycle()
// the transfer dialog (true: sending), and a send waiting for its files to be picked
var askTransfer by remember { mutableStateOf<Boolean?>(null) }
var pendingSend by remember { mutableStateOf<Pair<Protocol, String>?>(null) }
val pickFiles = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->
val (proto, command) = pendingSend ?: return@rememberLauncherForActivityResult
pendingSend = null
if (uris.isEmpty()) return@rememberLauncherForActivityResult
val files = uris.map { outgoingOf(context, it) }.let { if (proto.batch) it else it.take(1) }
scope.launch {
if (command.isNotEmpty()) {
session.sendBytes((command + "\r").toByteArray())
delay(800)
}
if (!session.sendFiles(proto, files)) Toast.makeText(context, "A transfer is running already", Toast.LENGTH_SHORT).show()
}
}
// the remote's rz waiting: files to pick for it
DisposableEffect(session) {
session.onSendWanted = { proto ->
scope.launch(Dispatchers.Main) {
if (pendingSend == null && !session.transferRunning) {
pendingSend = proto to ""
pickFiles.launch(arrayOf("*/*"))
}
}
}
onDispose { session.onSendWanted = null }
}
// the modem session's character set follows the settings (a directory entry's own while its call
// lasts); an SSH or Telnet session keeps its entry's
@@ -160,6 +194,8 @@ fun TerminalScreen(
scope.launch { Terminal.openLocal(context)?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() } }
},
onSsh = if (ssh != null && linkState == TerminalLink.State.Open) ({ showSsh = true }) else null,
onSendFiles = { askTransfer = true },
onReceiveFiles = { askTransfer = false },
onCapture = {
if (capture != null) {
val f = session.stopCapture()
@@ -221,6 +257,14 @@ fun TerminalScreen(
modifier = Modifier.align(Alignment.BottomCenter),
)
}
transfer?.let { t ->
TransferBanner(
t, DownloadsIncoming.where(context),
onCancel = { session.cancelTransfer() },
onDismiss = { session.dismissTransfer() },
modifier = Modifier.align(Alignment.BottomCenter),
)
}
}
if (s.extraKeys) {
ExtraKeys(
@@ -252,6 +296,27 @@ fun TerminalScreen(
onDismiss = { pickLinux = null },
)
}
askTransfer?.let { sending ->
TransferDialog(
sending,
onStart = { proto, command ->
askTransfer = null
if (sending) {
pendingSend = proto to command
pickFiles.launch(arrayOf("*/*"))
} else {
// (XMODEM sends no name: the last word typed, if any)
val name = command.substringAfterLast(' ').substringAfterLast('/').ifBlank { "received.bin" }
if (session.receiveFiles(proto, Terminal.downloads(), name)) {
if (command.isNotEmpty() && !command.endsWith(' ')) session.sendBytes((command + "\r").toByteArray())
} else {
Toast.makeText(context, "A transfer is running already", Toast.LENGTH_SHORT).show()
}
}
},
onDismiss = { askTransfer = null },
)
}
if (showSsh && ssh != null) {
SshSessionDialog(ssh) { showSsh = false }
}
@@ -371,6 +436,8 @@ private fun TopBar(
onNewLinux: () -> Unit,
/** an SSH connection's forwards, agent and keys (null: not one) */
onSsh: (() -> Unit)?,
onSendFiles: () -> Unit,
onReceiveFiles: () -> Unit,
onCapture: () -> Unit,
onHangUp: () -> Unit,
onClear: () -> Unit,
@@ -401,6 +468,8 @@ private fun TopBar(
if (onSsh != null) {
DropdownMenuItem(text = { Text("Port forwards, agent, keys") }, onClick = { menu = false; onSsh() })
}
DropdownMenuItem(text = { Text("Send files…") }, onClick = { menu = false; onSendFiles() })
DropdownMenuItem(text = { Text("Receive files…") }, onClick = { menu = false; onReceiveFiles() })
HorizontalDivider()
for (cs in TermCharset.entries) {
DropdownMenuItem(
@@ -0,0 +1,135 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.neodesktop.dmodem.transfer.Protocol
import com.neodesktop.dmodem.transfer.TransferState
/**
* A transfer to start: the protocol, and what to type at the remote to
* start its end (its rz, sz with the files' names, kermit…; empty: it's
* started already). [sending]: files from here.
*/
@Composable
fun TransferDialog(
sending: Boolean,
onStart: (protocol: Protocol, command: String) -> Unit,
onDismiss: () -> Unit,
) {
var protocol by remember { mutableStateOf(Protocol.ZMODEM) }
var command by remember { mutableStateOf(protocol.remoteCommand(remoteSends = !sending)) }
AlertDialog(
onDismissRequest = onDismiss,
title = { Text(if (sending) "Send files" else "Receive files") },
text = {
Column {
for (p in Protocol.entries) {
Row(
Modifier.fillMaxWidth().clickable {
protocol = p
command = p.remoteCommand(remoteSends = !sending)
},
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(selected = p == protocol, onClick = null)
Text(
p.label + if (!p.batch) " (one file)" else "",
Modifier.padding(start = 8.dp, top = 6.dp, bottom = 6.dp),
)
}
}
Spacer(Modifier.height(8.dp))
OutlinedTextField(
value = command,
onValueChange = { command = it },
label = { Text(if (sending) "Typed at the remote first" else "Typed at the remote first (add the files)") },
singleLine = true,
textStyle = MaterialTheme.typography.bodyMedium.copy(fontFamily = FontFamily.Monospace),
modifier = Modifier.fillMaxWidth(),
)
Text(
if (sending) "Then pick the files to send. Empty: the remote is already receiving."
else "Empty: start the remote's end yourself. A remote sz or kermit -s is noticed by itself.",
style = MaterialTheme.typography.bodySmall,
modifier = Modifier.padding(top = 4.dp),
)
}
},
confirmButton = {
Button(onClick = { onStart(protocol, command.trim()) }) { Text(if (sending) "Pick files…" else "Receive") }
},
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
)
}
/** a transfer as it goes (cancel it), or how it ended (dismissed) */
@Composable
fun TransferBanner(t: TransferState, savedTo: String, onCancel: () -> Unit, onDismiss: () -> Unit, modifier: Modifier = Modifier) {
Surface(modifier.fillMaxWidth().padding(12.dp), tonalElevation = 6.dp, shape = RoundedCornerShape(12.dp), shadowElevation = 6.dp) {
Column(Modifier.padding(start = 16.dp, end = 8.dp, top = 10.dp, bottom = 6.dp)) {
val p = t.progress
val what = t.protocol.label + if (t.sending) " sending" else " receiving"
Text(
when {
t.running -> if (p.file.isNotEmpty()) "$what ${p.file}" else "$what: waiting for the other side…"
t.result == "" -> if (t.sending) "${t.protocol.label}: sent ${p.files} file(s)" else "${t.protocol.label}: received ${t.received.size} file(s)"
else -> "${t.protocol.label} stopped: ${t.result}"
},
style = MaterialTheme.typography.titleSmall, maxLines = 2, overflow = TextOverflow.Ellipsis,
)
if (t.running) {
Spacer(Modifier.height(6.dp))
if (p.size > 0) {
LinearProgressIndicator(progress = { (p.bytes.toFloat() / p.size).coerceIn(0f, 1f) }, modifier = Modifier.fillMaxWidth().padding(end = 8.dp))
} else {
LinearProgressIndicator(Modifier.fillMaxWidth().padding(end = 8.dp))
}
}
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
when {
t.running -> sizeText(p.bytes) + (if (p.size > 0) " of " + sizeText(p.size) else "") +
(if (p.files > 0) " · ${p.files} done" else "") + (if (p.errors > 0) " · ${p.errors} retried" else "")
!t.sending && t.received.isNotEmpty() -> "In $savedTo"
else -> ""
},
style = MaterialTheme.typography.bodySmall, modifier = Modifier.weight(1f),
)
if (t.running) TextButton(onClick = onCancel) { Text("Cancel") } else TextButton(onClick = onDismiss) { Text("OK") }
}
}
}
}
private fun sizeText(n: Long): String = when {
n < 1024 -> "$n B"
n < 1024 * 1024 -> "%.1f KB".format(n / 1024.0)
else -> "%.1f MB".format(n / 1048576.0)
}
@@ -0,0 +1,182 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.transfer
import com.neodesktop.dmodem.local.LocalLink
import com.neodesktop.dmodem.local.LocalShellTest
import com.neodesktop.dmodem.local.Pty
import com.neodesktop.dmodem.terminal.TerminalLink
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.BeforeClass
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.util.concurrent.atomic.AtomicInteger
import kotlin.random.Random
/**
* Kermit against G-Kermit and C-Kermit on a pseudo-terminal, as on a
* remote's shell: files each way (binary, every byte value, runs for the
* repeat counts), on a 7-bit line (the 8th bit prefixed), and with bytes
* damaged on the line (packets asked for again).
*/
class KermitInteropTest {
@get:Rule
val tmp = TemporaryFolder()
private val links = ArrayList<LocalLink>()
companion object {
@BeforeClass
@JvmStatic
fun setUp() {
assumeTrue("gkermit isn't installed", File("/usr/bin/gkermit").canExecute())
Pty.load(LocalShellTest.hostPty())
}
}
@After
fun tearDown() = links.forEach { it.close() }
private fun line(dir: File, cmd: List<String>, damageIn: Int = 0, damageOut: Int = 0, strip8: Boolean = false): Pair<LocalLink, TransferIo> {
val l = LocalLink(cmd, mapOf("PATH" to "/usr/bin:/bin", "HOME" to dir.path), dir.path, 80, 24)
links.add(l)
val outCount = AtomicInteger()
val io = TransferIo { b ->
if (damageOut > 0) {
for (i in b.indices) if (outCount.incrementAndGet() % damageOut == 0) b[i] = (b[i].toInt() xor 0x55).toByte()
}
l.write(b)
}
val inCount = AtomicInteger()
l.addListener { data, n ->
val b = data.copyOf(n)
for (i in 0 until n) {
if (strip8) b[i] = (b[i].toInt() and 0x7f).toByte()
if (damageIn > 0 && inCount.incrementAndGet() % damageIn == 0) b[i] = (b[i].toInt() xor 0x55).toByte()
}
io.feed(b)
}
val trace = File("build/kermit-trace.txt").apply { delete() }
io.trace = { inbound, b ->
synchronized(trace) {
trace.appendText((if (inbound) "<< " else ">> ") + b.joinToString("") { c ->
val v = c.toInt() and 0xff
if (v in 0x20..0x7e) v.toChar().toString() else "\\x%02x".format(v)
} + "\n")
}
}
assertTrue(l.start())
return l to io
}
private fun waitExit(l: LocalLink): Int? {
val end = System.currentTimeMillis() + 30_000
while (l.state.value !is TerminalLink.State.Closed && System.currentTimeMillis() < end) Thread.sleep(20)
return l.exitStatus
}
private fun files(dir: File): List<File> {
dir.mkdirs()
val big = File(dir, "binary.bin").apply { writeBytes(Random(7).nextBytes(200_000)) }
val every = File(dir, "every-byte.dat").apply {
writeBytes(ByteArray(4096) { it.toByte() } + ByteArray(3000) { '~'.code.toByte() } + ByteArray(2048) { '#'.code.toByte() } + ByteArray(500) { 0x80.toByte() })
}
val text = File(dir, "notes.txt").apply { writeText("hello from the other side\n".repeat(100)) }
return listOf(big, every, text)
}
private fun received(src: List<File>, into: FolderIncoming, names: List<String>) {
assertEquals(src.map { it.name }, names)
for (f in src) assertArrayEquals(f.name, f.readBytes(), into.received.first { it.name == f.name }.readBytes())
}
@Test
fun receivedFromGkermit() {
val src = files(tmp.newFolder("src"))
val (l, io) = line(src[0].parentFile!!, listOf("/usr/bin/gkermit", "-q", "-i", "-P", "-s") + src.map { it.name })
val into = FolderIncoming(tmp.newFolder("into"))
var last = Progress()
val names = Kermit(io, { last = it }).receive(into)
received(src, into, names)
assertEquals(0, waitExit(l))
assertEquals(3, last.files)
}
@Test
fun sentToGkermit() {
val src = files(tmp.newFolder("src"))
val dest = tmp.newFolder("dest")
val (l, io) = line(dest, listOf("/usr/bin/gkermit", "-q", "-i", "-P", "-r"))
Kermit(io).send(src.map { Outgoing.of(it) })
assertEquals(0, waitExit(l))
for (f in src) assertArrayEquals(f.name, f.readBytes(), File(dest, f.name).readBytes())
}
@Test
fun bothWaysOnANoisyLine() {
val src = files(tmp.newFolder("src"))
val (l, io) = line(src[0].parentFile!!, listOf("/usr/bin/gkermit", "-q", "-i", "-P", "-b", "2", "-s") + src.map { it.name }, damageIn = 7_001)
val into = FolderIncoming(tmp.newFolder("into"))
var last = Progress()
received(src, into, Kermit(io, { last = it }, timeoutMs = 2_000).receive(into))
assertEquals(0, waitExit(l))
assertTrue("errors corrected: ${last.errors}", last.errors > 0)
val dest = tmp.newFolder("dest")
val (l2, io2) = line(dest, listOf("/usr/bin/gkermit", "-q", "-i", "-P", "-b", "2", "-r"), damageOut = 7_001)
var last2 = Progress()
Kermit(io2, { last2 = it }, timeoutMs = 2_000).send(src.map { Outgoing.of(it) })
assertEquals(0, waitExit(l2))
for (f in src) assertArrayEquals(f.name, f.readBytes(), File(dest, f.name).readBytes())
assertTrue("errors corrected: ${last2.errors}", last2.errors > 0)
}
@Test
fun aSevenBitLine() {
val src = files(tmp.newFolder("src"))
// gkermit -p s: space parity, so it prefixes the 8th bit
val (l, io) = line(src[0].parentFile!!, listOf("/usr/bin/gkermit", "-q", "-i", "-P", "-p", "s", "-s") + src.map { it.name }, strip8 = true)
val into = FolderIncoming(tmp.newFolder("into"))
received(src, into, Kermit(io, sevenBit = true).receive(into))
assertEquals(0, waitExit(l))
}
@Test
fun ckermitBothWays() {
assumeTrue("C-Kermit isn't installed", File("/usr/bin/kermit").canExecute())
val src = files(tmp.newFolder("src"))
// (-Y: no init file; -i binary)
val (l, io) = line(src[0].parentFile!!, listOf("/usr/bin/kermit", "-Y", "-q", "-i", "-s") + src.map { it.name })
val into = FolderIncoming(tmp.newFolder("into"))
received(src, into, Kermit(io).receive(into))
assertEquals(0, waitExit(l))
val dest = tmp.newFolder("dest")
val (l2, io2) = line(dest, listOf("/usr/bin/kermit", "-Y", "-q", "-i", "-r"))
Kermit(io2).send(src.map { Outgoing.of(it) })
assertEquals(0, waitExit(l2))
for (f in src) {
assertArrayEquals(f.name, f.readBytes(), File(dest, f.name).readBytes())
}
// the attributes kept the time (to the second)
assertEquals(src[0].lastModified() / 1000, File(dest, src[0].name).lastModified() / 1000)
}
@Test
fun theStartIsRecognised() {
// what kermit -s sends first
val s = "\u0001/ S~* @-#Y3~^>J)0___F\"U1@\r".toByteArray()
assertTrue(Kermit.looksLikeStart(s))
assertFalse(Kermit.looksLikeStart("plain text\r\n".toByteArray()))
// CRC-16/KERMIT's check value
assertEquals(0x2189, Kermit.crc("123456789".toByteArray(), 0, 9))
}
}
@@ -0,0 +1,203 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.transfer
import com.neodesktop.dmodem.local.LocalLink
import com.neodesktop.dmodem.local.LocalShellTest
import com.neodesktop.dmodem.local.Pty
import com.neodesktop.dmodem.terminal.TerminalLink
import org.junit.After
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.BeforeClass
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.util.concurrent.atomic.AtomicInteger
import kotlin.random.Random
/**
* XMODEM, YMODEM and ZMODEM against lrzsz (sz, rz, sx, rx, sb, rb) on a
* pseudo-terminal, as on a remote's shell: files each way, binary and
* empty ones, several at once; and with bytes damaged on the line, both
* ways (the protocols' repeats and ZRPOS putting it right).
*/
class LrzszInteropTest {
@get:Rule
val tmp = TemporaryFolder()
private val links = ArrayList<LocalLink>()
companion object {
@BeforeClass
@JvmStatic
fun setUp() {
assumeTrue("lrzsz isn't installed", File("/usr/bin/sz").canExecute() && File("/usr/bin/rz").canExecute())
Pty.load(LocalShellTest.hostPty())
}
}
@After
fun tearDown() = links.forEach { it.close() }
/** [cmd] on a pty in [dir], and a TransferIo on it; [damageIn] / [damageOut] spoil a byte every so many */
private fun line(dir: File, cmd: List<String>, damageIn: Int = 0, damageOut: Int = 0): Pair<LocalLink, TransferIo> {
val l = LocalLink(cmd, mapOf("PATH" to "/usr/bin:/bin", "HOME" to dir.path), dir.path, 80, 24)
links.add(l)
val outCount = AtomicInteger()
val io = TransferIo { b ->
if (damageOut > 0) {
for (i in b.indices) if (outCount.incrementAndGet() % damageOut == 0) b[i] = (b[i].toInt() xor 0x55).toByte()
}
l.write(b)
}
val inCount = AtomicInteger()
l.addListener { data, n ->
val b = data.copyOf(n)
if (damageIn > 0) {
for (i in 0 until n) if (inCount.incrementAndGet() % damageIn == 0) b[i] = (b[i].toInt() xor 0x55).toByte()
}
io.feed(b)
}
// (the bytes each way, for a failing run: build/transfer-trace.txt)
val trace = File("build/transfer-trace.txt").apply { delete() }
io.trace = { inbound, b ->
synchronized(trace) {
trace.appendText((if (inbound) "<< " else ">> ") + b.joinToString("") { c ->
val v = c.toInt() and 0xff
if (v in 0x20..0x7e) v.toChar().toString() else "\\x%02x".format(v)
} + "\n")
}
}
assertTrue(l.start())
return l to io
}
private fun waitExit(l: LocalLink): Int? {
val end = System.currentTimeMillis() + 30_000
while (l.state.value !is TerminalLink.State.Closed && System.currentTimeMillis() < end) Thread.sleep(20)
return l.exitStatus
}
private fun files(dir: File): List<File> {
dir.mkdirs()
val big = File(dir, "binary.bin").apply { writeBytes(Random(7).nextBytes(300_000)) }
// every byte value, the ZDLE-escaped ones many times over
val every = File(dir, "every byte.dat").apply { writeBytes(ByteArray(4096) { it.toByte() } + ByteArray(2048) { 0x18 } + ByteArray(2048) { 0x11 }) }
val text = File(dir, "notes.txt").apply { writeText("hello from the other side\n".repeat(100)) }
val empty = File(dir, "empty").apply { writeBytes(ByteArray(0)) }
return listOf(big, every, text, empty)
}
// ZMODEM ------------------------------------------------------------
@Test
fun zmodemReceivedFromSz() = receivedFromSz(damage = 0)
@Test
fun zmodemReceivedFromSzOnANoisyLine() = receivedFromSz(damage = 20_011)
private fun receivedFromSz(damage: Int) {
val src = files(tmp.newFolder("src"))
val (l, io) = line(src[0].parentFile!!, listOf("/usr/bin/sz", "-b") + src.map { it.path }, damageIn = damage)
val into = FolderIncoming(tmp.newFolder("into"))
var last = Progress()
val names = ZModem(io, { last = it }).receive(into)
assertEquals(src.map { it.name }, names)
for (f in src) assertArrayEquals(f.name, f.readBytes(), File(into.received.first { it.name == f.name }.path).readBytes())
assertEquals(0, waitExit(l))
if (damage > 0) assertTrue("errors corrected: ${last.errors}", last.errors > 0)
assertEquals(4, last.files)
}
@Test
fun zmodemSentToRz() = sentToRz(damage = 0)
@Test
fun zmodemSentToRzOnANoisyLine() = sentToRz(damage = 30_011)
private fun sentToRz(damage: Int) {
val src = files(tmp.newFolder("src"))
val dest = tmp.newFolder("dest")
val (l, io) = line(dest, listOf("/usr/bin/rz", "-b", "-y"), damageOut = damage)
var last = Progress()
ZModem(io, { last = it }).send(src.map { Outgoing.of(it) })
assertEquals(0, waitExit(l))
for (f in src) assertArrayEquals(f.name, f.readBytes(), File(dest, f.name).readBytes())
// the times kept (to the second)
assertEquals(src[0].lastModified() / 1000, File(dest, src[0].name).lastModified() / 1000)
if (damage > 0) assertTrue("errors corrected: ${last.errors}", last.errors > 0)
}
@Test
fun aCancelFromTheOtherSideStopsIt() {
val src = File(tmp.newFolder("src"), "big").apply { writeBytes(Random(1).nextBytes(2_000_000)) }
val (l, io) = line(src.parentFile!!, listOf("/usr/bin/sz", "-b", src.path))
val into = FolderIncoming(tmp.newFolder("into"))
val t = Thread { Thread.sleep(300); l.write(ZModem.CANCEL) }
t.start()
val e = runCatching { ZModem(io).receive(object : Incoming by into {
// (slowly: the cancel comes in the middle)
override fun create(name: String, size: Long) = into.create(name, size).let { (o, n) ->
object : java.io.FilterOutputStream(o) {
override fun write(b: ByteArray, off: Int, len: Int) { Thread.sleep(5); out.write(b, off, len) }
} to n
}
}) }.exceptionOrNull()
// the sender's own cancel echoed back, or the line going quiet
assertTrue("$e", e != null)
assertTrue("half a file not kept", into.received.isEmpty())
}
// YMODEM and XMODEM ---------------------------------------------------
@Test
fun ymodemReceivedFromSb() {
val src = files(tmp.newFolder("src")).filter { it.length() > 0 }
val (l, io) = line(src[0].parentFile!!, listOf("/usr/bin/sb") + src.map { it.path })
val into = FolderIncoming(tmp.newFolder("into"))
val names = XYModem(io).receiveY(into)
assertEquals(src.map { it.name }, names)
for (f in src) assertArrayEquals(f.name, f.readBytes(), into.received.first { it.name == f.name }.readBytes())
assertEquals(0, waitExit(l))
}
@Test
fun ymodemSentToRb() {
val src = files(tmp.newFolder("src")).filter { it.length() > 0 }
val dest = tmp.newFolder("dest")
val (l, io) = line(dest, listOf("/usr/bin/rb", "-y"))
XYModem(io).sendY(src.map { Outgoing.of(it) })
assertEquals(0, waitExit(l))
for (f in src) assertArrayEquals(f.name, f.readBytes(), File(dest, f.name).readBytes())
}
@Test
fun xmodemBothWaysWithOneKBlocksAndNoise() {
val data = Random(3).nextBytes(100_000)
// from sx (1K blocks, CRC), the line damaged: our NAKs make it repeat
val src = File(tmp.newFolder("src"), "x.bin").apply { writeBytes(data) }
val (l, io) = line(src.parentFile!!, listOf("/usr/bin/sx", "-k", src.path), damageIn = 15_013)
val into = FolderIncoming(tmp.newFolder("into"))
var last = Progress()
val name = XYModem(io, { last = it }).receiveX(into, "x.bin")
assertEquals(0, waitExit(l))
// (XMODEM pads the last block: the padding taken off, the file as it was)
assertArrayEquals(data, into.received.first { it.name == name }.readBytes())
assertTrue("errors corrected", last.errors > 0)
// to rx (128-byte blocks)
val dest = tmp.newFolder("dest")
val (l2, io2) = line(dest, listOf("/usr/bin/rx", "-c", "got.bin"))
XYModem(io2).sendX(Outgoing.of(src), oneK = false)
assertEquals(0, waitExit(l2))
// (rx keeps the padding: XMODEM has no size)
val got = File(dest, "got.bin").readBytes()
assertArrayEquals(data, got.copyOf(data.size))
assertTrue(got.drop(data.size).all { it == 0x1a.toByte() })
}
}