mirror of
https://github.com/D-Modem/app.git
synced 2026-11-28 17:38:05 -08:00
Shared jobs for iOS: fax calls, file transfers, dial-up internet
The modem's DTE lent to a job as Swift drives it: octets as Latin-1 strings, callbacks through fun interfaces (DteOut, LogOut, Changed) rather than Kotlin lambdas, state read when it says it changed. - FaxJob: send pages to a number, or answer and save the pages as a PDF - TransferJob: ZMODEM/YMODEM/XMODEM/Kermit on the shared Transfer, now in common code (the Android terminal uses the same one) - DialUpJob: ISP dialled, login script, PPP, packets to a PacketTunnel - FaxImage: grey pixels as fax pages, at a threshold or dithered - nativeMain: PosixFiles/PosixFolderIncoming for files by path, and UdpPacketTunnel relaying packets to iOS's packet tunnel extension - PeerHost takes LogOut for its events and log (Swift can't pass a Unit-returning Kotlin lambda as a plain closure) JobsTest runs each job on the JVM and natively (the fax both ways on the fake class 1 line, ZMODEM between two jobs, PPP to a fake ISP); NativeJobsTest covers the files and the UDP relay. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs
This commit is contained in:
14 files changed
+1188
-20
No files matched your search
@@ -0,0 +1,58 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.fax
|
||||
|
||||
import com.neodesktop.dmodem.jobs.Latin1
|
||||
|
||||
/**
|
||||
* Grey images as fax pages (iOS draws its documents into grey pixels at
|
||||
* the fax's size; this makes them black and white): text and drawings at
|
||||
* a threshold, photographs dithered (Floyd–Steinberg), as the Android
|
||||
* app's FaxDocuments does its bitmaps.
|
||||
*/
|
||||
object FaxImage {
|
||||
/** 98 or 196 lines to the inch down (204 pels across, always) */
|
||||
fun lpi(fine: Boolean) = if (fine) 196 else 98
|
||||
|
||||
/** the rows a page [width] by [height] (any units) takes at the fax's width */
|
||||
fun rows(width: Int, height: Int, fine: Boolean): Int =
|
||||
(height.toDouble() / width * FaxPage.WIDTH * lpi(fine) / 204).toInt().coerceIn(1, 4000)
|
||||
|
||||
/**
|
||||
* [gray] (one octet a pixel, 0 black to 255 white, [width] to a row)
|
||||
* as a page [FaxPage.WIDTH] wide: a narrower image's right white, a
|
||||
* wider one's cut off
|
||||
*/
|
||||
fun page(gray: ByteArray, width: Int, height: Int, fine: Boolean, dither: Boolean): FaxPage {
|
||||
require(gray.size >= width * height) { "${gray.size} octets for $width by $height" }
|
||||
val w = FaxPage.WIDTH
|
||||
val page = FaxPage(w, height, fine)
|
||||
fun at(x: Int, y: Int): Int = if (x < width) gray[y * width + x].toInt() and 0xff else 255
|
||||
if (!dither) {
|
||||
for (y in 0 until height) for (x in 0 until w) if (at(x, y) < 128) page.set(x, y, true)
|
||||
return page
|
||||
}
|
||||
var cur = IntArray(w + 2)
|
||||
var next = IntArray(w + 2)
|
||||
for (y in 0 until height) {
|
||||
for (x in 0 until w) cur[x + 1] += at(x, y) * 16
|
||||
for (x in 0 until w) {
|
||||
val v = cur[x + 1]
|
||||
val black = v < 128 * 16
|
||||
if (black) page.set(x, y, true)
|
||||
val e = v - (if (black) 0 else 255 * 16)
|
||||
cur[x + 2] += e * 7 / 16
|
||||
next[x] += e * 3 / 16
|
||||
next[x + 1] += e * 5 / 16
|
||||
next[x + 2] += e / 16
|
||||
}
|
||||
val t = cur; cur = next; next = t
|
||||
next.fill(0)
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
/** [page] with its grey pixels as Latin-1 text (Swift's) */
|
||||
fun pageLatin1(gray: String, width: Int, height: Int, fine: Boolean, dither: Boolean): FaxPage =
|
||||
page(Latin1.bytes(gray), width, height, fine, dither)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import kotlinx.coroutines.IO
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
/**
|
||||
* The threads for blocking work: as many as there is work (I/O's 64, the
|
||||
@@ -29,4 +30,7 @@ class Latch {
|
||||
done.complete(Unit)
|
||||
}
|
||||
fun await() = runBlocking { done.await() }
|
||||
|
||||
/** waited for up to [ms]: whether it was counted down */
|
||||
fun await(ms: Long): Boolean = runBlocking { withTimeoutOrNull(ms) { done.await() } != null }
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.jobs
|
||||
|
||||
import com.neodesktop.dmodem.fax.Class1
|
||||
import com.neodesktop.dmodem.io.IOException
|
||||
import com.neodesktop.dmodem.io.Latch
|
||||
import com.neodesktop.dmodem.io.background
|
||||
import com.neodesktop.dmodem.io.dotted
|
||||
import com.neodesktop.dmodem.io.monotonicMs
|
||||
import com.neodesktop.dmodem.io.sleepMs
|
||||
import com.neodesktop.dmodem.ppp.ChatScript
|
||||
import com.neodesktop.dmodem.ppp.Ppp
|
||||
import com.neodesktop.dmodem.transfer.TransferCancelled
|
||||
import kotlin.concurrent.Volatile
|
||||
|
||||
/** where the link's packets go on the phone (iOS: its packet tunnel) */
|
||||
interface PacketTunnel {
|
||||
/** a packet from the link */
|
||||
fun packet(p: ByteArray)
|
||||
|
||||
/** the link up with [address] and [dns] (dotted): false when it can't take its packets */
|
||||
fun up(address: String, dns: List<String>, mtu: Int): Boolean
|
||||
|
||||
/** the link over (whether or not it came up) */
|
||||
fun close()
|
||||
}
|
||||
|
||||
/**
|
||||
* Dial-up internet on the modem (the Android app's Internet, for iOS):
|
||||
* the ISP dialled, its login script if it has one, PPP; once it has an
|
||||
* address the phone's packets through [PacketTunnel]. [disconnect], the
|
||||
* line dropped ([lineDropped]) or PPP down, it all comes down and the call
|
||||
* hangs up.
|
||||
*/
|
||||
class DialUpJob(out: DteOut, log: LogOut, changed: Changed) : DteJob(out, log, changed) {
|
||||
data class State(
|
||||
/** what it's doing; "" when connected */
|
||||
val phase: String,
|
||||
/** the link's address and DNS servers, once up */
|
||||
val address: String = "",
|
||||
val dns: List<String> = emptyList(),
|
||||
/** the CONNECT the modem said */
|
||||
val connect: String = "",
|
||||
/** when it came up (the monotonic clock's ms) */
|
||||
val since: Long = 0,
|
||||
val bytesIn: Long = 0,
|
||||
val bytesOut: Long = 0,
|
||||
/** why it ended (null while it goes) */
|
||||
val ended: String? = null,
|
||||
) {
|
||||
val connected: Boolean get() = address.isNotEmpty() && ended == null
|
||||
val running: Boolean get() = ended == null
|
||||
}
|
||||
|
||||
@Volatile var state = State("Starting")
|
||||
private set
|
||||
@Volatile private var ppp: Ppp? = null
|
||||
@Volatile private var stopping = false
|
||||
|
||||
private fun set(f: (State) -> State) {
|
||||
state = f(state)
|
||||
changed()
|
||||
}
|
||||
|
||||
override fun feed(latin1: String) {
|
||||
// (the AT commands' answers until CONNECT, then PPP's)
|
||||
val p = ppp
|
||||
if (p != null) p.input(Latin1.bytes(latin1)) else super.feed(latin1)
|
||||
}
|
||||
|
||||
/** milliseconds it has been up (0 while it isn't) */
|
||||
val upMs: Long get() = state.since.let { if (it == 0L || !state.connected) 0 else monotonicMs() - it }
|
||||
|
||||
/**
|
||||
* [number] dialled, [script] run (if not blank) with [user] and
|
||||
* [password], PPP brought up; [initCommands] (";" or lines between)
|
||||
* first
|
||||
*/
|
||||
fun connect(number: String, user: String, password: String, script: String, initCommands: String, tunnel: PacketTunnel) {
|
||||
state = State("Dialling $number")
|
||||
changed()
|
||||
background("internet") {
|
||||
var why: String? = null
|
||||
var online = false
|
||||
try {
|
||||
val c = Class1(io) { log("internet: $it") }
|
||||
// (data mode; X3: a SIP line has no dial tone)
|
||||
if (c.command("E0V1X3+FCLASS=0") != "OK") throw IOException("the modem didn't answer")
|
||||
for (cmd in initCommands.split(Regex("[\\r\\n;]+")).map { it.trim() }.filter { it.isNotEmpty() }) {
|
||||
c.command(cmd.removePrefix("AT").removePrefix("at"))
|
||||
}
|
||||
val r = c.command("D$number", 90_000)
|
||||
if (r == null || !r.startsWith("CONNECT")) throw IOException(dialResult(r, "no modem answered"))
|
||||
online = true
|
||||
set { it.copy(phase = "Logging in", connect = r) }
|
||||
if (script.isNotBlank()) {
|
||||
set { it.copy(phase = "Running the login script") }
|
||||
ChatScript(script, user, password).run(io) { log("script: $it") }
|
||||
set { it.copy(phase = "Logging in") }
|
||||
}
|
||||
val done = Latch()
|
||||
val p = Ppp(
|
||||
send = { b -> io.write(b) },
|
||||
user = user,
|
||||
password = password,
|
||||
events = object : Ppp.Events {
|
||||
override fun up(config: Ppp.IpConfig) {
|
||||
val address = config.address.dotted
|
||||
val dns = config.dns.map { it.dotted }
|
||||
val ok = try { tunnel.up(address, dns, config.mtu) } catch (_: Exception) { false }
|
||||
if (!ok) {
|
||||
why = "the VPN couldn't start"
|
||||
ppp?.stop(why!!)
|
||||
return
|
||||
}
|
||||
set { it.copy(phase = "", address = address, dns = dns, since = monotonicMs()) }
|
||||
}
|
||||
|
||||
override fun ip(packet: ByteArray) = tunnel.packet(packet)
|
||||
|
||||
override fun down(reason: String) {
|
||||
if (why == null) why = reason
|
||||
done.countDown()
|
||||
}
|
||||
|
||||
override fun log(line: String) = this@DialUpJob.log("ppp: $line")
|
||||
},
|
||||
)
|
||||
// (the octets that came after CONNECT, before PPP was there to take them)
|
||||
ppp = p
|
||||
val early = io.leftover()
|
||||
p.start()
|
||||
if (early.isNotEmpty()) p.input(early)
|
||||
if (stopping) p.stop("disconnected")
|
||||
while (!done.await(1000)) {
|
||||
set { it.copy(bytesIn = p.bytesIn, bytesOut = p.bytesOut) }
|
||||
}
|
||||
} catch (e: TransferCancelled) {
|
||||
why = "disconnected"
|
||||
} catch (e: IOException) {
|
||||
why = e.message ?: e.toString()
|
||||
} catch (e: RuntimeException) {
|
||||
why = e.toString()
|
||||
} finally {
|
||||
ppp = null
|
||||
runCatching { tunnel.close() }
|
||||
// the call hung up: +++ between its guard times, ATH
|
||||
if (online) {
|
||||
sleepMs(1200)
|
||||
raw("+++")
|
||||
sleepMs(1200)
|
||||
}
|
||||
raw("\rATH\r")
|
||||
sleepMs(500)
|
||||
leftover = Latin1.string(io.leftover())
|
||||
set { it.copy(phase = "", ended = why ?: "disconnected") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** a packet from the phone to the link: false when it isn't up */
|
||||
fun sendIp(packet: ByteArray): Boolean = ppp?.sendIp(packet) ?: false
|
||||
|
||||
/** the link closed and the call hung up */
|
||||
fun disconnect() = stop("disconnected")
|
||||
|
||||
/** the carrier gone (the modem on hook, or stopped): the link down */
|
||||
fun lineDropped() = stop("the line dropped")
|
||||
|
||||
private fun stop(why: String) {
|
||||
if (stopping) return
|
||||
stopping = true
|
||||
val p = ppp
|
||||
if (p != null) p.stop(why) else io.cancel(why)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.jobs
|
||||
|
||||
import com.neodesktop.dmodem.io.IOException
|
||||
import com.neodesktop.dmodem.io.latin1String
|
||||
import com.neodesktop.dmodem.transfer.TransferIo
|
||||
import kotlin.concurrent.Volatile
|
||||
|
||||
/*
|
||||
* The modem's DTE lent to a job (a fax call, a file transfer, dial-up
|
||||
* internet) as the iOS app's Swift has it: octets cross as Latin-1
|
||||
* strings (one character an octet), the job calls back through the
|
||||
* interfaces here (Swift classes conform to them; a Kotlin lambda's Unit
|
||||
* would be Swift's KotlinUnit), its state read when it says it changed.
|
||||
*/
|
||||
|
||||
/** octets to the modem: false once it has gone */
|
||||
fun interface DteOut {
|
||||
fun write(latin1: String): Boolean
|
||||
}
|
||||
|
||||
/** a line for the log */
|
||||
fun interface LogOut {
|
||||
fun log(line: String)
|
||||
}
|
||||
|
||||
/** the job's state changed (read it); on the job's thread */
|
||||
fun interface Changed {
|
||||
fun changed()
|
||||
}
|
||||
|
||||
/** octets as Latin-1 text and back, for Swift */
|
||||
object Latin1 {
|
||||
fun bytes(s: String): ByteArray = ByteArray(s.length) { s[it].code.toByte() }
|
||||
fun string(b: ByteArray): String = latin1String(b, 0, b.size)
|
||||
}
|
||||
|
||||
/**
|
||||
* A job on the DTE: the modem's octets [feed] to it while it runs, its
|
||||
* own to [out] ([io]'s writes, refused once it's cancelled; [raw]'s, not:
|
||||
* the hang-up after a cancel). Ended, [leftover] has what came that it
|
||||
* didn't read, for the terminal.
|
||||
*/
|
||||
abstract class DteJob(private val out: DteOut, protected val logOut: LogOut, private val changed: Changed) {
|
||||
val io = TransferIo { b -> if (!out.write(Latin1.string(b))) throw IOException("the modem has gone") }
|
||||
|
||||
/** what came but wasn't read, once it has ended */
|
||||
@Volatile var leftover: String = ""
|
||||
protected set
|
||||
|
||||
/** the modem's octets */
|
||||
open fun feed(latin1: String) {
|
||||
if (latin1.isNotEmpty()) io.feed(Latin1.bytes(latin1))
|
||||
}
|
||||
|
||||
/** to the modem, a cancel or not */
|
||||
protected fun raw(s: String) {
|
||||
try {
|
||||
out.write(s)
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
}
|
||||
|
||||
protected fun changed() = changed.changed()
|
||||
|
||||
protected fun log(line: String) = logOut.log(line)
|
||||
|
||||
/** the modem's answer to ATD, as the user reads it */
|
||||
protected fun dialResult(r: String?, nobody: String) = when (r) {
|
||||
null -> "no answer"
|
||||
"BUSY" -> "busy"
|
||||
"NO ANSWER" -> "no answer"
|
||||
"NO CARRIER" -> nobody
|
||||
"NO DIALTONE", "NO DIAL TONE" -> "no line"
|
||||
else -> r.lowercase()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.jobs
|
||||
|
||||
import com.neodesktop.dmodem.fax.Class1
|
||||
import com.neodesktop.dmodem.fax.FaxException
|
||||
import com.neodesktop.dmodem.fax.FaxPage
|
||||
import com.neodesktop.dmodem.fax.FaxPdf
|
||||
import com.neodesktop.dmodem.fax.FaxProgress
|
||||
import com.neodesktop.dmodem.fax.T30
|
||||
import com.neodesktop.dmodem.io.IOException
|
||||
import com.neodesktop.dmodem.io.background
|
||||
import com.neodesktop.dmodem.io.sleepMs
|
||||
import com.neodesktop.dmodem.transfer.Incoming
|
||||
import com.neodesktop.dmodem.transfer.TransferCancelled
|
||||
import kotlin.concurrent.Volatile
|
||||
|
||||
/**
|
||||
* A fax call on the modem (the Android app's Fax, for iOS): pages sent to
|
||||
* a number, or a ringing call answered and its pages saved as a PDF. The
|
||||
* modem to class 1 first, back to data and on hook after.
|
||||
*/
|
||||
class FaxJob(out: DteOut, log: LogOut, changed: Changed) : DteJob(out, log, changed) {
|
||||
data class State(
|
||||
val sending: Boolean,
|
||||
val progress: FaxProgress,
|
||||
/** null while it goes; "" when it went through, else why not */
|
||||
val result: String? = null,
|
||||
/** the received fax's file name */
|
||||
val file: String = "",
|
||||
val number: String = "",
|
||||
) {
|
||||
val running: Boolean get() = result == null
|
||||
}
|
||||
|
||||
@Volatile var state: State? = null
|
||||
private set
|
||||
|
||||
private fun update(p: FaxProgress) {
|
||||
state = state?.copy(progress = p)
|
||||
changed()
|
||||
}
|
||||
|
||||
/** [pages] faxed to [number] */
|
||||
fun send(number: String, pages: List<FaxPage>, ident: String, ecm: Boolean, maxBps: Int) {
|
||||
start(sending = true, number = number.trim(), maxBps = maxBps) { c, rates ->
|
||||
if (pages.isEmpty()) throw FaxException("the document has no pages")
|
||||
update(FaxProgress("Dialling $number", total = pages.size))
|
||||
val r = c.command("D${number.trim()}", 120_000)
|
||||
if (r != "CONNECT") throw FaxException(dialResult(r, "no fax machine answered"))
|
||||
T30.send(c, pages, ident, rates, ecm = ecm) { update(it) } to ""
|
||||
}
|
||||
}
|
||||
|
||||
/** the call ringing answered as a fax, its pages to [into] as [fileName] (a PDF) */
|
||||
fun answer(ident: String, ecm: Boolean, maxBps: Int, into: Incoming, fileName: String) {
|
||||
start(sending = false, number = "", maxBps = maxBps) { c, rates ->
|
||||
update(FaxProgress("Answering"))
|
||||
val r = c.command("A", 30_000)
|
||||
if (r != "CONNECT") throw FaxException(if (r == null) "no fax answered" else "no fax: $r")
|
||||
val got = ArrayList<FaxPage>()
|
||||
val p = try {
|
||||
T30.receive(c, ident, rates, { update(it) }, ecm = ecm) { pg, _ -> got.add(pg) }
|
||||
} catch (e: IOException) {
|
||||
// (the pages that came are kept)
|
||||
if (got.isEmpty()) throw e
|
||||
FaxProgress("Received part", pages = got.size)
|
||||
}
|
||||
p to save(into, fileName, got)
|
||||
}
|
||||
}
|
||||
|
||||
/** the call stopped (hung up) */
|
||||
fun cancel() = io.cancel("cancelled")
|
||||
|
||||
private fun save(into: Incoming, name: String, pages: List<FaxPage>): String {
|
||||
val (out, actual) = into.create(name, -1)
|
||||
try {
|
||||
out.use { FaxPdf.write(pages, it) }
|
||||
into.done(actual, 0)
|
||||
} catch (e: IOException) {
|
||||
into.abandon(actual)
|
||||
throw e
|
||||
}
|
||||
return actual
|
||||
}
|
||||
|
||||
private fun start(sending: Boolean, number: String, maxBps: Int, body: (Class1, List<T30.Rate>) -> Pair<FaxProgress, String>) {
|
||||
state = State(sending, FaxProgress("Starting"), number = number)
|
||||
changed()
|
||||
background("fax") {
|
||||
var result = ""
|
||||
var file = ""
|
||||
var last = FaxProgress()
|
||||
val c = Class1(io) { log("fax: $it") }
|
||||
try {
|
||||
// (X3: a SIP line has no dial tone to wait for)
|
||||
if (c.command("E0V1X3") != "OK" || c.command("+FCLASS=1") != "OK") throw FaxException("the modem has no fax mode")
|
||||
val rates = T30.modemRates(c, maxBps)
|
||||
val (p, f) = body(c, rates)
|
||||
last = p
|
||||
file = f
|
||||
} catch (e: TransferCancelled) {
|
||||
result = "cancelled"
|
||||
} catch (e: IOException) {
|
||||
result = e.message ?: e.toString()
|
||||
} catch (e: RuntimeException) {
|
||||
result = e.toString()
|
||||
} finally {
|
||||
// the call over, the modem back to data
|
||||
raw("\u0018")
|
||||
sleepMs(300)
|
||||
raw("ATH\r")
|
||||
sleepMs(500)
|
||||
raw("AT+FCLASS=0\r")
|
||||
sleepMs(300)
|
||||
leftover = Latin1.string(io.leftover())
|
||||
val st = state
|
||||
state = st?.copy(progress = if (result.isEmpty()) last else st.progress, result = result, file = file)
|
||||
changed()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.jobs
|
||||
|
||||
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 kotlin.concurrent.Volatile
|
||||
|
||||
/**
|
||||
* A file transfer on the modem's line (the Android app's terminal's, for
|
||||
* iOS): files sent to the remote, or received from it, by [protocolName]'s
|
||||
* name (ZMODEM, YMODEM, XMODEM, XMODEM_1K, KERMIT).
|
||||
*/
|
||||
class TransferJob(protocolName: String, sending: Boolean, out: DteOut, log: LogOut, changed: Changed) : DteJob(out, log, changed) {
|
||||
private val transfer = Transfer(
|
||||
Protocol.valueOf(protocolName),
|
||||
sending,
|
||||
send = { b -> io.write(b) },
|
||||
sendRaw = { b -> raw(Latin1.string(b)) },
|
||||
onState = { s ->
|
||||
state = s
|
||||
changed()
|
||||
},
|
||||
onEnd = { s, rest ->
|
||||
leftover = Latin1.string(rest)
|
||||
state = s
|
||||
changed()
|
||||
},
|
||||
)
|
||||
|
||||
@Volatile var state: TransferState = transfer.state
|
||||
private set
|
||||
|
||||
override fun feed(latin1: String) {
|
||||
if (latin1.isNotEmpty()) transfer.io.feed(Latin1.bytes(latin1))
|
||||
}
|
||||
|
||||
/** files received into [into] ([name]: XMODEM's, which sends none) */
|
||||
fun receive(into: Incoming, name: String) = transfer.receive(into, name)
|
||||
|
||||
/** [files] sent ([files]' first only, for XMODEM) */
|
||||
fun send(files: List<Outgoing>) = transfer.send(files)
|
||||
|
||||
fun cancel() = transfer.cancel()
|
||||
|
||||
companion object {
|
||||
/** the protocols' names, and what each is called */
|
||||
val protocols: List<String> = Protocol.entries.map { it.name }
|
||||
|
||||
fun label(protocolName: String): String = Protocol.valueOf(protocolName).label
|
||||
|
||||
/** whether it sends more than one file */
|
||||
fun batch(protocolName: String): Boolean = Protocol.valueOf(protocolName).batch
|
||||
|
||||
/**
|
||||
* what the remote starts in what came ([latin1]): "ZMODEM_SEND" (sz: receive here),
|
||||
* "ZMODEM_RECEIVE" (rz: pick files), "KERMIT_SEND", or "" for nothing
|
||||
*/
|
||||
fun detect(latin1: String): String {
|
||||
val b = Latin1.bytes(latin1)
|
||||
return Transfer.detect(b, b.size)?.second?.name ?: ""
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-11
@@ -2,7 +2,10 @@
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.transfer
|
||||
|
||||
import java.io.IOException
|
||||
import com.neodesktop.dmodem.io.IOException
|
||||
import com.neodesktop.dmodem.io.background
|
||||
import com.neodesktop.dmodem.io.sleepMs
|
||||
import kotlin.concurrent.Volatile
|
||||
|
||||
/** The file transfer protocols. */
|
||||
enum class Protocol(val label: String, val batch: Boolean) {
|
||||
@@ -38,7 +41,8 @@ data class TransferState(
|
||||
}
|
||||
|
||||
/**
|
||||
* One transfer on a line, on its own thread: the session feeds it the
|
||||
* One transfer on a line, on its own thread (the Android app's terminal,
|
||||
* and iOS's TransferJob): the session feeds it the
|
||||
* remote's bytes ([io]) while it runs; [onEnd] has what it didn't read.
|
||||
*/
|
||||
class Transfer(
|
||||
@@ -54,7 +58,6 @@ class Transfer(
|
||||
@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
|
||||
@@ -87,7 +90,7 @@ class Transfer(
|
||||
|
||||
private fun start(body: () -> List<String>) {
|
||||
update(state)
|
||||
thread = Thread({
|
||||
background("transfer-${protocol.name.lowercase()}") {
|
||||
val end = try {
|
||||
val names = body()
|
||||
state.copy(result = "", received = names)
|
||||
@@ -99,12 +102,9 @@ class Transfer(
|
||||
state.copy(result = e.toString())
|
||||
}
|
||||
// (what the other side still sends of the protocol settles first)
|
||||
if (end.result != "") Thread.sleep(300)
|
||||
if (end.result != "") sleepMs(300)
|
||||
update(end)
|
||||
onEnd(end, io.leftover())
|
||||
}, "transfer-${protocol.name.lowercase()}").apply {
|
||||
isDaemon = true
|
||||
start()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,9 +122,6 @@ class Transfer(
|
||||
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
|
||||
@@ -48,6 +48,13 @@ class FakeFaxLine {
|
||||
/** the V.21 frames being received, those left of them */
|
||||
private var receiving: ArrayDeque<ByteArray>? = null
|
||||
@Volatile var stopped = false
|
||||
/** what the modem says, to here instead of [io] (a FaxJob's feed) */
|
||||
@Volatile var tap: ((ByteArray) -> Unit)? = null
|
||||
|
||||
private fun toHost(b: ByteArray) {
|
||||
val t = tap
|
||||
if (t != null) t(b) else io.feed(b)
|
||||
}
|
||||
|
||||
fun deliver(t: Tx) = synchronized(lock) { inbox.add(t) }
|
||||
|
||||
@@ -62,7 +69,7 @@ class FakeFaxLine {
|
||||
return cur[at++].toInt() and 0xff
|
||||
}
|
||||
|
||||
private fun say(s: String) = io.feed("\r\n$s\r\n".encodeToByteArray())
|
||||
private fun say(s: String) = toHost("\r\n$s\r\n".encodeToByteArray())
|
||||
|
||||
/** <DLE> shielded data from the DTE, to <DLE><ETX> */
|
||||
private fun dteData(): ByteArray {
|
||||
@@ -82,7 +89,7 @@ class FakeFaxLine {
|
||||
for (b in d) { o.write(b.toInt()); if (b.toInt() and 0xff == Class1.DLE) o.write(Class1.DLE) }
|
||||
o.write(Class1.DLE)
|
||||
o.write(Class1.ETX)
|
||||
io.feed(o.toByteArray())
|
||||
toHost(o.toByteArray())
|
||||
}
|
||||
|
||||
/** the next transmission come in (left there); null if the DTE stopped the wait (a character) */
|
||||
@@ -159,7 +166,7 @@ class FakeFaxLine {
|
||||
}
|
||||
c.startsWith("+FRM=") -> receiveFast(c.substring(5).toInt())
|
||||
// dialled: CONNECT, then as +FRH=3; answered: CONNECT, then as +FTH=3
|
||||
c == "D" -> { say("CONNECT"); receiveFrame(true) }
|
||||
c.startsWith("D") -> { say("CONNECT"); receiveFrame(true) }
|
||||
c == "A" -> { say("CONNECT"); sendFrames() }
|
||||
else -> say("OK") // (E0, +FCLASS=1, +FTS, +FRS, …)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.jobs
|
||||
|
||||
import com.neodesktop.dmodem.fax.FakeFaxLine
|
||||
import com.neodesktop.dmodem.fax.FaxImage
|
||||
import com.neodesktop.dmodem.fax.FaxPage
|
||||
import com.neodesktop.dmodem.fax.FaxTestPage
|
||||
import com.neodesktop.dmodem.io.ByteQueue
|
||||
import com.neodesktop.dmodem.io.Bytes
|
||||
import com.neodesktop.dmodem.io.Inet4
|
||||
import com.neodesktop.dmodem.io.Sink
|
||||
import com.neodesktop.dmodem.io.Source
|
||||
import com.neodesktop.dmodem.io.background
|
||||
import com.neodesktop.dmodem.io.inet4
|
||||
import com.neodesktop.dmodem.io.monotonicMs
|
||||
import com.neodesktop.dmodem.io.sleepMs
|
||||
import com.neodesktop.dmodem.ppp.Ip
|
||||
import com.neodesktop.dmodem.ppp.Ppp
|
||||
import com.neodesktop.dmodem.transfer.Incoming
|
||||
import com.neodesktop.dmodem.transfer.Outgoing
|
||||
import kotlinx.atomicfu.locks.SynchronizedObject
|
||||
import kotlinx.atomicfu.locks.synchronized
|
||||
import kotlin.concurrent.Volatile
|
||||
import kotlin.random.Random
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertContentEquals
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertNotNull
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
/**
|
||||
* The jobs iOS lends the modem's DTE to, as its Swift drives them (octets
|
||||
* as Latin-1, calls back through the interfaces): a fax both ways on the
|
||||
* fake class 1 line, a ZMODEM transfer between two jobs, dial-up
|
||||
* internet to a fake ISP (PPP's server) with the tunnel's packets both
|
||||
* ways and the hang-up; grey images as fax pages.
|
||||
*/
|
||||
class JobsTest {
|
||||
private class Memory : Incoming {
|
||||
val files = LinkedHashMap<String, Bytes>()
|
||||
override fun create(name: String, size: Long): Pair<Sink, String> = Bytes().let { b -> files[name] = b; b to name }
|
||||
override fun abandon(name: String) { files.remove(name) }
|
||||
}
|
||||
|
||||
private class Log : LogOut {
|
||||
val lock = SynchronizedObject()
|
||||
val lines = ArrayList<String>()
|
||||
override fun log(line: String) { synchronized(lock) { lines.add(line) } }
|
||||
}
|
||||
|
||||
private fun waitFor(what: String, ms: Long = 30_000, cond: () -> Boolean) {
|
||||
val end = monotonicMs() + ms
|
||||
while (!cond()) {
|
||||
if (monotonicMs() > end) throw AssertionError("no $what")
|
||||
sleepMs(20)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aFaxBothWays() {
|
||||
val line = FakeFaxLine()
|
||||
val pages = listOf(FaxTestPage.of(true, rows = 300, seed = 1), FaxTestPage.of(true, rows = 200, seed = 2))
|
||||
var changes = 0
|
||||
val tx = FaxJob({ s -> line.a.io.write(Latin1.bytes(s)); true }, Log(), { changes++ })
|
||||
val rx = FaxJob({ s -> line.b.io.write(Latin1.bytes(s)); true }, Log(), { })
|
||||
line.a.tap = { b -> tx.feed(Latin1.string(b)) }
|
||||
line.b.tap = { b -> rx.feed(Latin1.string(b)) }
|
||||
val into = Memory()
|
||||
try {
|
||||
rx.answer("+1 555 0199", ecm = true, maxBps = 14400, into = into, fileName = "fax.pdf")
|
||||
sleepMs(200)
|
||||
tx.send("5550199", pages, "+1 555 0100", ecm = true, maxBps = 14400)
|
||||
waitFor("the fax sent") { tx.state?.running == false }
|
||||
waitFor("the fax received") { rx.state?.running == false }
|
||||
} finally {
|
||||
line.stop()
|
||||
}
|
||||
val sent = assertNotNull(tx.state)
|
||||
assertEquals("", sent.result, sent.progress.phase)
|
||||
assertEquals(2, sent.progress.pages)
|
||||
assertTrue(sent.progress.ecm)
|
||||
assertEquals("+1 555 0199", sent.progress.remote)
|
||||
val got = assertNotNull(rx.state)
|
||||
assertEquals("", got.result)
|
||||
assertEquals("fax.pdf", got.file)
|
||||
assertEquals(2, got.progress.pages)
|
||||
val pdf = assertNotNull(into.files["fax.pdf"]).toByteArray()
|
||||
assertEquals("%PDF", pdf.copyOf(4).decodeToString())
|
||||
assertTrue(changes > 3)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun noFaxModeAnswered() {
|
||||
// a modem that answers ERROR to everything: why, and the modem back to data
|
||||
lateinit var job: FaxJob
|
||||
val said = ArrayList<String>()
|
||||
job = FaxJob({ s ->
|
||||
said.add(s)
|
||||
if (s.endsWith("\r")) job.feed("\r\nERROR\r\n")
|
||||
true
|
||||
}, Log(), { })
|
||||
job.send("1", listOf(FaxTestPage.of(false, rows = 10)), "", ecm = true, maxBps = 14400)
|
||||
waitFor("its end") { job.state?.running == false }
|
||||
assertEquals("the modem has no fax mode", job.state?.result)
|
||||
assertTrue("AT+FCLASS=0\r" in said, "$said")
|
||||
}
|
||||
|
||||
private fun outgoing(name: String, data: ByteArray) = Outgoing(name, data.size.toLong(), 0) {
|
||||
object : Source {
|
||||
var at = 0
|
||||
override fun read(b: ByteArray, off: Int, len: Int): Int {
|
||||
if (at >= data.size) return -1
|
||||
val n = minOf(len, data.size - at)
|
||||
data.copyInto(b, off, at, at + n)
|
||||
at += n
|
||||
return n
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun aTransferBetweenTwoJobs() {
|
||||
val data = Random(7).nextBytes(40_000)
|
||||
lateinit var tx: TransferJob
|
||||
lateinit var rx: TransferJob
|
||||
tx = TransferJob("ZMODEM", true, { s -> rx.feed(s); true }, Log(), { })
|
||||
rx = TransferJob("ZMODEM", false, { s -> tx.feed(s); true }, Log(), { })
|
||||
val into = Memory()
|
||||
rx.receive(into, "x.bin")
|
||||
tx.send(listOf(outgoing("hello.bin", data)))
|
||||
waitFor("the transfer") { !tx.state.running && !rx.state.running }
|
||||
assertEquals("", tx.state.result)
|
||||
assertEquals("", rx.state.result)
|
||||
assertEquals(listOf("hello.bin"), rx.state.received)
|
||||
assertContentEquals(data, into.files["hello.bin"]!!.toByteArray())
|
||||
assertEquals("ZMODEM_SEND", TransferJob.detect("x" + Latin1.string(byteArrayOf(0x2a, 0x2a, 0x18, 0x42, 0x30, 0x30)) + "y"))
|
||||
assertEquals("", TransferJob.detect("hello"))
|
||||
assertTrue("KERMIT" in TransferJob.protocols)
|
||||
}
|
||||
|
||||
/** a modem dialling an ISP: OK to commands, CONNECT to ATD, then PPP's server; +++ and ATH heard */
|
||||
private class FakeIsp {
|
||||
lateinit var job: DialUpJob
|
||||
val heard = ByteQueue()
|
||||
val said = StringBuilder()
|
||||
@Volatile var online = false
|
||||
@Volatile var stopped = false
|
||||
val lock = SynchronizedObject()
|
||||
val serverPackets = ByteQueue()
|
||||
|
||||
private fun a(vararg b: Int): Inet4 = inet4(ByteArray(4) { b[it].toByte() })
|
||||
|
||||
val server = Ppp({ b -> job.feed(Latin1.string(b)) }, events = object : Ppp.Events {
|
||||
override fun up(config: Ppp.IpConfig) {}
|
||||
override fun ip(packet: ByteArray) = serverPackets.put(packet)
|
||||
override fun down(reason: String) { online = false }
|
||||
}, retryMs = 300, server = Ppp.Server(a(10, 64, 64, 1), a(10, 64, 64, 2), a(10, 64, 64, 1)))
|
||||
|
||||
fun start() = background("isp") {
|
||||
val cmd = StringBuilder()
|
||||
while (!stopped) {
|
||||
val b = heard.poll(50) ?: continue
|
||||
val text = Latin1.string(b)
|
||||
synchronized(lock) { said.append(text) }
|
||||
if (online) { server.input(b); continue }
|
||||
for (c in text) {
|
||||
if (c != '\r') { cmd.append(c); continue }
|
||||
val l = cmd.toString().trim().uppercase()
|
||||
cmd.clear()
|
||||
if (l.isEmpty()) continue
|
||||
if (l.startsWith("ATD")) {
|
||||
job.feed("\r\nCONNECT 33600\r\n")
|
||||
online = true
|
||||
server.start()
|
||||
} else {
|
||||
job.feed("\r\nOK\r\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun said() = synchronized(lock) { said.toString() }
|
||||
}
|
||||
|
||||
private class Tunnel : PacketTunnel {
|
||||
@Volatile var address = ""
|
||||
@Volatile var dns = emptyList<String>()
|
||||
@Volatile var closed = false
|
||||
val packets = ByteQueue()
|
||||
override fun packet(p: ByteArray) = packets.put(p)
|
||||
override fun up(address: String, dns: List<String>, mtu: Int): Boolean { this.address = address; this.dns = dns; return true }
|
||||
override fun close() { closed = true }
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dialUpInternet() {
|
||||
val isp = FakeIsp()
|
||||
val log = Log()
|
||||
val job = DialUpJob({ s -> isp.heard.put(Latin1.bytes(s)); true }, log, { })
|
||||
isp.job = job
|
||||
isp.start()
|
||||
val tunnel = Tunnel()
|
||||
try {
|
||||
job.connect("5551234", "me", "pw", "", "ATM1;ATL2", tunnel)
|
||||
waitFor("the link") { job.state.connected }
|
||||
assertEquals("10.64.64.2", job.state.address)
|
||||
assertEquals("10.64.64.2", tunnel.address)
|
||||
assertEquals(listOf("10.64.64.1"), tunnel.dns)
|
||||
assertEquals("CONNECT 33600", job.state.connect)
|
||||
assertTrue("ATM1\r" in isp.said() && "ATL2\r" in isp.said(), isp.said())
|
||||
// a packet each way
|
||||
val me = byteArrayOf(10, 64, 64, 2)
|
||||
val gw = byteArrayOf(10, 64, 64, 1)
|
||||
assertTrue(job.sendIp(Ip.udp(me, gw, 5000, 53, "up".encodeToByteArray())))
|
||||
assertEquals("up", Ip.udpPayload(assertNotNull(isp.serverPackets.poll(5000))).decodeToString())
|
||||
assertTrue(isp.server.sendIp(Ip.udp(gw, me, 53, 5000, "down".encodeToByteArray())))
|
||||
assertEquals("down", Ip.udpPayload(assertNotNull(tunnel.packets.poll(5000))).decodeToString())
|
||||
waitFor("the counts") { job.state.bytesIn > 0 && job.state.bytesOut > 0 }
|
||||
// hung up: PPP down, +++ and ATH, the tunnel closed
|
||||
job.disconnect()
|
||||
waitFor("its end") { !job.state.running }
|
||||
assertEquals("disconnected", job.state.ended)
|
||||
assertTrue(tunnel.closed)
|
||||
assertTrue("+++" in isp.said() && isp.said().endsWith("\rATH\r"), isp.said())
|
||||
} finally {
|
||||
isp.stopped = true
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun dialUpBusy() {
|
||||
lateinit var job: DialUpJob
|
||||
job = DialUpJob({ s ->
|
||||
if (s.startsWith("ATD")) job.feed("\r\nBUSY\r\n") else if (s.endsWith("\r")) job.feed("\r\nOK\r\n")
|
||||
true
|
||||
}, Log(), { })
|
||||
val tunnel = Tunnel()
|
||||
job.connect("1", "", "", "", "", tunnel)
|
||||
waitFor("its end") { !job.state.running }
|
||||
assertEquals("busy", job.state.ended)
|
||||
assertTrue(tunnel.closed)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun greyAsFaxPages() {
|
||||
// a 4 by 2 image: black, white, dark grey, light grey
|
||||
val g = byteArrayOf(0, 255.toByte(), 60, 200.toByte(), 0, 0, 0, 0)
|
||||
val p = FaxImage.page(g, 4, 2, fine = true, dither = false)
|
||||
assertEquals(FaxPage.WIDTH, p.width)
|
||||
assertEquals(2, p.rows)
|
||||
assertEquals(listOf(true, false, true, false), (0 until 4).map { p.black(it, 0) })
|
||||
// (the rest of the width white)
|
||||
assertTrue((4 until FaxPage.WIDTH).none { p.black(it, 0) })
|
||||
assertTrue((0 until 4).all { p.black(it, 1) })
|
||||
// mid grey dithered: about half black
|
||||
val grey = ByteArray(FaxPage.WIDTH * 20) { 128.toByte() }
|
||||
val d = FaxImage.pageLatin1(Latin1.string(grey), FaxPage.WIDTH, 20, fine = false, dither = true)
|
||||
val black = (0 until 20).sumOf { y -> (0 until FaxPage.WIDTH).count { d.black(it, y) } }
|
||||
assertTrue(black in FaxPage.WIDTH * 20 * 4 / 10..FaxPage.WIDTH * 20 * 6 / 10, "$black")
|
||||
// an A4 page's rows at the fax's width
|
||||
assertEquals(830, FaxImage.rows(FaxPage.WIDTH, FaxPage.WIDTH, fine = false))
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.peer
|
||||
|
||||
import com.neodesktop.dmodem.jobs.LogOut
|
||||
|
||||
/**
|
||||
* The line to another phone over Wi-Fi as the iOS app's Swift has it:
|
||||
* [PeerLine] on [PosixTcpTransport], made from plain values (Swift has
|
||||
@@ -15,17 +17,17 @@ class PeerHost(
|
||||
private val callTo: String,
|
||||
/** the PIN between the two (empty: none) */
|
||||
pin: String,
|
||||
/** to the engine: RING, CANCEL, ANSWERED, FAILED <code>, DROPPED */
|
||||
events: (String) -> Unit,
|
||||
log: (String) -> Unit,
|
||||
/** to the engine: RING, CANCEL, ANSWERED, FAILED <code>, DROPPED (a line each) */
|
||||
events: LogOut,
|
||||
log: LogOut,
|
||||
ringMs: Long = 3000,
|
||||
) {
|
||||
val transport = PosixTcpTransport(port)
|
||||
val line = PeerLine(
|
||||
transport,
|
||||
events = events,
|
||||
events = { e -> events.log(e) },
|
||||
target = { dial -> PeerLine.wifiTarget(dial, callTo) },
|
||||
log = log,
|
||||
log = { l -> log.log(l) },
|
||||
ringMs = ringMs,
|
||||
pin = pin,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.ppp
|
||||
|
||||
import com.neodesktop.dmodem.io.background
|
||||
import com.neodesktop.dmodem.jobs.DialUpJob
|
||||
import com.neodesktop.dmodem.jobs.PacketTunnel
|
||||
import kotlinx.atomicfu.atomic
|
||||
import kotlinx.atomicfu.locks.SynchronizedObject
|
||||
import kotlinx.atomicfu.locks.synchronized
|
||||
import kotlinx.cinterop.ExperimentalForeignApi
|
||||
import kotlinx.cinterop.addressOf
|
||||
import kotlinx.cinterop.alloc
|
||||
import kotlinx.cinterop.convert
|
||||
import kotlinx.cinterop.memScoped
|
||||
import kotlinx.cinterop.ptr
|
||||
import kotlinx.cinterop.reinterpret
|
||||
import kotlinx.cinterop.sizeOf
|
||||
import kotlinx.cinterop.usePinned
|
||||
import kotlinx.cinterop.value
|
||||
import platform.posix.AF_INET
|
||||
import platform.posix.INADDR_LOOPBACK
|
||||
import platform.posix.POLLIN
|
||||
import platform.posix.SOCK_DGRAM
|
||||
import platform.posix.bind
|
||||
import platform.posix.getsockname
|
||||
import platform.posix.poll
|
||||
import platform.posix.pollfd
|
||||
import platform.posix.recvfrom
|
||||
import platform.posix.sendto
|
||||
import platform.posix.sockaddr_in
|
||||
import platform.posix.socket
|
||||
import platform.posix.socklen_tVar
|
||||
|
||||
/** what starts the phone's tunnel (iOS: its packet tunnel extension, told to send its packets to [port]) */
|
||||
interface TunnelStarter {
|
||||
/** the tunnel up with [address], [dns] (comma between), its packets to 127.0.0.1:[port]: whether it started */
|
||||
fun start(address: String, dns: String, mtu: Int, port: Int): Boolean
|
||||
|
||||
fun stop()
|
||||
}
|
||||
|
||||
/**
|
||||
* The dial-up link's packets to the phone's tunnel and back as UDP on the
|
||||
* loopback (each datagram an IPv4 packet): iOS's packet tunnel runs apart
|
||||
* from the app (an extension), and the modem in the app. The extension's
|
||||
* first datagram (any, an empty one) tells where it is.
|
||||
*/
|
||||
@OptIn(ExperimentalForeignApi::class, kotlin.experimental.ExperimentalNativeApi::class)
|
||||
class UdpPacketTunnel(private val job: DialUpJob, private val starter: TunnelStarter) : PacketTunnel {
|
||||
private val fd = socket(AF_INET, SOCK_DGRAM, 0)
|
||||
private val running = atomic(true)
|
||||
private val lock = SynchronizedObject()
|
||||
/** the extension's address, once it has said something */
|
||||
private var peer: ByteArray? = null
|
||||
|
||||
/** the port packets come in on */
|
||||
val port: Int
|
||||
|
||||
/** packets each way (for the tests) */
|
||||
val fromTunnel = atomic(0)
|
||||
val toTunnel = atomic(0)
|
||||
|
||||
init {
|
||||
port = memScoped {
|
||||
val a = alloc<sockaddr_in>()
|
||||
a.sin_family = AF_INET.convert()
|
||||
a.sin_addr.s_addr = htonl(INADDR_LOOPBACK.toUInt())
|
||||
a.sin_port = 0u
|
||||
bind(fd, a.ptr.reinterpret(), sizeOf<sockaddr_in>().convert())
|
||||
val len = alloc<socklen_tVar>()
|
||||
len.value = sizeOf<sockaddr_in>().convert()
|
||||
getsockname(fd, a.ptr.reinterpret(), len.ptr)
|
||||
ntohs(a.sin_port).toInt()
|
||||
}
|
||||
background("tunnel") { receive() }
|
||||
}
|
||||
|
||||
private fun receive() {
|
||||
val buf = ByteArray(65536)
|
||||
while (running.value) {
|
||||
val ready = memScoped {
|
||||
val p = alloc<pollfd>()
|
||||
p.fd = fd
|
||||
p.events = POLLIN.convert()
|
||||
poll(p.ptr, 1.convert(), 200)
|
||||
}
|
||||
if (ready <= 0) continue
|
||||
val (n, from) = memScoped {
|
||||
val a = alloc<sockaddr_in>()
|
||||
val len = alloc<socklen_tVar>()
|
||||
len.value = sizeOf<sockaddr_in>().convert()
|
||||
val n = buf.usePinned { recvfrom(fd, it.addressOf(0), buf.size.convert(), 0, a.ptr.reinterpret(), len.ptr) }.toInt()
|
||||
val raw = ByteArray(sizeOf<sockaddr_in>().toInt())
|
||||
raw.usePinned { platform.posix.memcpy(it.addressOf(0), a.ptr, raw.size.convert()) }
|
||||
n to raw
|
||||
}
|
||||
if (n < 0) continue
|
||||
synchronized(lock) { peer = from }
|
||||
// (an IPv4 packet; anything shorter only says where the extension is)
|
||||
if (n >= 20) {
|
||||
fromTunnel.incrementAndGet()
|
||||
job.sendIp(buf.copyOf(n))
|
||||
}
|
||||
}
|
||||
platform.posix.close(fd)
|
||||
}
|
||||
|
||||
override fun packet(p: ByteArray) {
|
||||
val to = synchronized(lock) { peer } ?: return
|
||||
toTunnel.incrementAndGet()
|
||||
p.usePinned { pp ->
|
||||
to.usePinned { tp ->
|
||||
sendto(fd, pp.addressOf(0), p.size.convert(), 0, tp.addressOf(0).reinterpret(), to.size.convert())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun up(address: String, dns: List<String>, mtu: Int): Boolean =
|
||||
starter.start(address, dns.joinToString(","), mtu, port)
|
||||
|
||||
override fun close() {
|
||||
if (!running.compareAndSet(true, false)) return
|
||||
starter.stop()
|
||||
}
|
||||
|
||||
private fun htonl(v: UInt): UInt = if (bigEndian) v else
|
||||
((v and 0xffu) shl 24) or ((v and 0xff00u) shl 8) or ((v shr 8) and 0xff00u) or (v shr 24)
|
||||
|
||||
private fun ntohs(v: UShort): UShort = if (bigEndian) v else
|
||||
(((v.toInt() and 0xff) shl 8) or (v.toInt() shr 8 and 0xff)).toUShort()
|
||||
|
||||
private val bigEndian: Boolean get() = kotlin.native.Platform.isLittleEndian.not()
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.transfer
|
||||
|
||||
import com.neodesktop.dmodem.io.IOException
|
||||
import com.neodesktop.dmodem.io.Sink
|
||||
import com.neodesktop.dmodem.io.Source
|
||||
import kotlinx.cinterop.CPointer
|
||||
import kotlinx.cinterop.ExperimentalForeignApi
|
||||
import kotlinx.cinterop.addressOf
|
||||
import kotlinx.cinterop.alloc
|
||||
import kotlinx.cinterop.convert
|
||||
import kotlinx.cinterop.memScoped
|
||||
import kotlinx.cinterop.ptr
|
||||
import kotlinx.cinterop.usePinned
|
||||
import platform.posix.F_OK
|
||||
import platform.posix.FILE
|
||||
import platform.posix.SEEK_END
|
||||
import platform.posix.access
|
||||
import platform.posix.fclose
|
||||
import platform.posix.fopen
|
||||
import platform.posix.fread
|
||||
import platform.posix.fseek
|
||||
import platform.posix.ftell
|
||||
import platform.posix.fwrite
|
||||
import platform.posix.mkdir
|
||||
import platform.posix.unlink
|
||||
import platform.posix.utimbuf
|
||||
import platform.posix.utime
|
||||
|
||||
/**
|
||||
* Files for transfers and faxes on iOS (and Linux, the tests), by path:
|
||||
* a file to send, a folder received files go into.
|
||||
*/
|
||||
@OptIn(ExperimentalForeignApi::class)
|
||||
object PosixFiles {
|
||||
/** the file at [path] to send, named as its last part; null when it can't be read (Swift: no exceptions) */
|
||||
fun outgoing(path: String): Outgoing? {
|
||||
val size = size(path)
|
||||
if (size < 0) return null
|
||||
return Outgoing(path.substringAfterLast('/'), size, 0) { source(path) }
|
||||
}
|
||||
|
||||
/** whether there's a file (or folder) at [path] */
|
||||
fun exists(path: String): Boolean = access(path, F_OK) == 0
|
||||
|
||||
/** [path]'s size, -1 when it can't be read */
|
||||
fun size(path: String): Long {
|
||||
val f = fopen(path, "rb") ?: return -1
|
||||
try {
|
||||
if (fseek(f, 0, SEEK_END) != 0) return -1
|
||||
return ftell(f).toLong()
|
||||
} finally {
|
||||
fclose(f)
|
||||
}
|
||||
}
|
||||
|
||||
fun source(path: String): Source {
|
||||
val f = fopen(path, "rb") ?: throw IOException("can't open $path")
|
||||
return FileSource(f)
|
||||
}
|
||||
|
||||
fun sink(path: String): Sink {
|
||||
val f = fopen(path, "wb") ?: throw IOException("can't write $path")
|
||||
return FileSink(f)
|
||||
}
|
||||
|
||||
/** 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: the name */
|
||||
fun unique(dir: String, name: String): String {
|
||||
if (!exists("$dir/$name")) return name
|
||||
val dot = name.lastIndexOf('.').takeIf { it > 0 } ?: name.length
|
||||
var n = 2
|
||||
while (true) {
|
||||
val c = name.substring(0, dot) + " ($n)" + name.substring(dot)
|
||||
if (!exists("$dir/$c")) return c
|
||||
n++
|
||||
}
|
||||
}
|
||||
|
||||
private class FileSource(private var f: CPointer<FILE>?) : Source {
|
||||
override fun read(b: ByteArray, off: Int, len: Int): Int {
|
||||
val file = f ?: return -1
|
||||
if (len <= 0) return 0
|
||||
val n = b.usePinned { fread(it.addressOf(off), 1u, len.convert(), file) }.toInt()
|
||||
return if (n == 0) -1 else n
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
f?.let { fclose(it) }
|
||||
f = null
|
||||
}
|
||||
}
|
||||
|
||||
private class FileSink(private var f: CPointer<FILE>?) : Sink {
|
||||
override fun write(b: ByteArray, off: Int, len: Int) {
|
||||
val file = f ?: throw IOException("closed")
|
||||
if (len <= 0) return
|
||||
val n = b.usePinned { fwrite(it.addressOf(off), 1u, len.convert(), file) }.toInt()
|
||||
if (n != len) throw IOException("the disk is full")
|
||||
}
|
||||
|
||||
override fun close() {
|
||||
val file = f ?: return
|
||||
f = null
|
||||
if (fclose(file) != 0) throw IOException("the disk is full")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** received files into the folder at [dir] (made if it isn't there) */
|
||||
@OptIn(ExperimentalForeignApi::class)
|
||||
class PosixFolderIncoming(private val dir: String) : Incoming {
|
||||
/** the names the files got, those finished */
|
||||
val received = ArrayList<String>()
|
||||
|
||||
override fun create(name: String, size: Long): Pair<Sink, String> {
|
||||
mkdir(dir, 0x1edu.convert())
|
||||
val actual = PosixFiles.unique(dir, PosixFiles.safeName(name))
|
||||
return PosixFiles.sink("$dir/$actual") to actual
|
||||
}
|
||||
|
||||
override fun done(name: String, mtime: Long) {
|
||||
if (mtime > 0) memScoped {
|
||||
val t = alloc<utimbuf>()
|
||||
t.actime = mtime.convert()
|
||||
t.modtime = mtime.convert()
|
||||
utime("$dir/$name", t.ptr)
|
||||
}
|
||||
received.add(name)
|
||||
}
|
||||
|
||||
override fun abandon(name: String) {
|
||||
unlink("$dir/$name")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
// Copyright (C) 2026 Neo-Desktop
|
||||
package com.neodesktop.dmodem.jobs
|
||||
|
||||
import com.neodesktop.dmodem.io.ByteQueue
|
||||
import com.neodesktop.dmodem.io.monotonicMs
|
||||
import com.neodesktop.dmodem.io.read
|
||||
import com.neodesktop.dmodem.io.sleepMs
|
||||
import com.neodesktop.dmodem.ppp.TunnelStarter
|
||||
import com.neodesktop.dmodem.ppp.UdpPacketTunnel
|
||||
import com.neodesktop.dmodem.transfer.PosixFiles
|
||||
import com.neodesktop.dmodem.transfer.PosixFolderIncoming
|
||||
import kotlinx.cinterop.ExperimentalForeignApi
|
||||
import kotlinx.cinterop.addressOf
|
||||
import kotlinx.cinterop.alloc
|
||||
import kotlinx.cinterop.convert
|
||||
import kotlinx.cinterop.memScoped
|
||||
import kotlinx.cinterop.ptr
|
||||
import kotlinx.cinterop.reinterpret
|
||||
import kotlinx.cinterop.sizeOf
|
||||
import kotlinx.cinterop.usePinned
|
||||
import platform.posix.AF_INET
|
||||
import platform.posix.SOCK_DGRAM
|
||||
import platform.posix.getpid
|
||||
import platform.posix.recv
|
||||
import platform.posix.rmdir
|
||||
import platform.posix.sendto
|
||||
import platform.posix.sockaddr_in
|
||||
import platform.posix.socket
|
||||
import platform.posix.unlink
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertContentEquals
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.assertTrue
|
||||
|
||||
/**
|
||||
* What iOS has natively for its jobs: files by path (sent, received into
|
||||
* a folder, names made safe and unique), and the dial-up link's packets
|
||||
* to the packet tunnel as UDP on the loopback.
|
||||
*/
|
||||
@OptIn(ExperimentalForeignApi::class)
|
||||
class NativeJobsTest {
|
||||
@Test
|
||||
fun filesInAFolder() {
|
||||
val dir = "/tmp/dmodem-files-${getpid()}"
|
||||
val into = PosixFolderIncoming(dir)
|
||||
val (s1, n1) = into.create("../evil/a:b.txt", 5)
|
||||
s1.write("hello".encodeToByteArray())
|
||||
s1.close()
|
||||
into.done(n1, 1_700_000_000)
|
||||
assertEquals("a_b.txt", n1)
|
||||
val (s2, n2) = into.create("a:b.txt", 5)
|
||||
s2.write("again".encodeToByteArray())
|
||||
s2.close()
|
||||
assertEquals("a_b (2).txt", n2)
|
||||
val out = PosixFiles.outgoing("$dir/$n1")!!
|
||||
assertEquals("a_b.txt", out.name)
|
||||
assertEquals(5L, out.size)
|
||||
val src = out.open()
|
||||
val b = ByteArray(16)
|
||||
val n = src.read(b, 0, b.size)
|
||||
src.close()
|
||||
assertContentEquals("hello".encodeToByteArray(), b.copyOf(n))
|
||||
into.abandon(n2)
|
||||
assertTrue(!PosixFiles.exists("$dir/$n2"))
|
||||
unlink("$dir/$n1")
|
||||
rmdir(dir)
|
||||
assertEquals(-1L, PosixFiles.size("$dir/none"))
|
||||
assertEquals(null, PosixFiles.outgoing("$dir/none"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun packetsOverTheLoopback() {
|
||||
// the link's job (never connected: its packets only counted), the tunnel's "extension" a UDP socket
|
||||
val job = DialUpJob({ true }, { }, { })
|
||||
var started = ""
|
||||
var stopped = false
|
||||
val t = UdpPacketTunnel(job, object : TunnelStarter {
|
||||
override fun start(address: String, dns: String, mtu: Int, port: Int): Boolean {
|
||||
started = "$address $dns $mtu $port"
|
||||
return true
|
||||
}
|
||||
override fun stop() { stopped = true }
|
||||
})
|
||||
assertTrue(t.port > 0)
|
||||
assertTrue(t.up("10.0.0.2", listOf("1.1.1.1", "8.8.8.8"), 1500))
|
||||
assertEquals("10.0.0.2 1.1.1.1,8.8.8.8 1500 ${t.port}", started)
|
||||
val ext = socket(AF_INET, SOCK_DGRAM, 0)
|
||||
memScoped {
|
||||
val a = alloc<sockaddr_in>()
|
||||
a.sin_family = AF_INET.convert()
|
||||
a.sin_port = (((t.port and 0xff) shl 8) or (t.port shr 8)).toUShort()
|
||||
// (127.0.0.1 in network order, on a little-endian host)
|
||||
a.sin_addr.s_addr = 0x0100007fu
|
||||
// a hello (where it is), then a packet: to the link (not up: dropped there, but counted)
|
||||
val hello = ByteArray(1)
|
||||
hello.usePinned { sendto(ext, it.addressOf(0), 1u, 0, a.ptr.reinterpret(), sizeOf<sockaddr_in>().convert()) }
|
||||
val pkt = ByteArray(40) { it.toByte() }
|
||||
pkt.usePinned { sendto(ext, it.addressOf(0), 40u, 0, a.ptr.reinterpret(), sizeOf<sockaddr_in>().convert()) }
|
||||
}
|
||||
val end = monotonicMs() + 5000
|
||||
while (t.fromTunnel.value < 1 && monotonicMs() < end) sleepMs(20)
|
||||
assertEquals(1, t.fromTunnel.value)
|
||||
// a packet from the link: to the extension
|
||||
val down = ByteArray(60) { (it * 3).toByte() }
|
||||
t.packet(down)
|
||||
val got = ByteArray(2000)
|
||||
val n = got.usePinned { recv(ext, it.addressOf(0), 2000u, 0) }.toInt()
|
||||
assertContentEquals(down, got.copyOf(n))
|
||||
t.close()
|
||||
assertTrue(stopped)
|
||||
platform.posix.close(ext)
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ class PosixPeerTest {
|
||||
private val events = ArrayList<String>()
|
||||
val heardOther = atomic(0)
|
||||
val hungUp = atomic(false)
|
||||
val host = PeerHost(0, callTo, pin, events = { e -> synchronized(lock) { events.add(e) } }, log = {}, ringMs = 300)
|
||||
val host = PeerHost(0, callTo, pin, events = { e -> synchronized(lock) { events.add(e) } }, log = { }, ringMs = 300)
|
||||
|
||||
init {
|
||||
assertEquals(null, host.start(listen))
|
||||
|
||||
Reference in new issue
Block a user