diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index a483127..ed9a177 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -76,6 +76,15 @@
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
android:value="A software dial-up modem: it holds a SIP call's real-time audio (G.711 RTP) and the modem's data connection for as long as the user keeps the modem on, and answers incoming modem calls." />
+
+
+
+
+
+
+ var v = b
+ repeat(8) { v = if (v and 1 != 0) (v ushr 1) xor 0x8408 else v ushr 1 }
+ v
+ }
+
+ fun fcs(data: ByteArray, off: Int = 0, len: Int = data.size - off, start: Int = 0xffff): Int {
+ var f = start
+ for (i in off until off + len) f = (f ushr 8) xor FCS_TABLE[(f xor data[i].toInt()) and 0xff]
+ return f
+ }
+
+ /** what a good frame's FCS over its data and FCS comes to */
+ const val GOOD_FCS = 0xf0b8
+
+ /** [frame] (address, control, protocol, information) framed: escaped as [accm] has it, its FCS after */
+ fun encode(frame: ByteArray, accm: Int): ByteArray {
+ val f = fcs(frame) xor 0xffff
+ val o = ByteArrayOutputStream(frame.size + frame.size / 4 + 8)
+ o.write(FLAG)
+ fun put(b: Int) {
+ if (b == FLAG || b == ESC || (b < 0x20 && (accm ushr b) and 1 != 0)) {
+ o.write(ESC)
+ o.write(b xor 0x20)
+ } else {
+ o.write(b)
+ }
+ }
+ for (b in frame) put(b.toInt() and 0xff)
+ put(f and 0xff)
+ put(f ushr 8)
+ o.write(FLAG)
+ return o.toByteArray()
+ }
+
+ /** octets from the line into frames: each good one (its FCS checked and off) to [onFrame], bad ones counted */
+ class Decoder(private val onFrame: (ByteArray) -> Unit) {
+ private val buf = ByteArrayOutputStream(1600)
+ private var esc = false
+ var bad = 0
+ private set
+
+ fun feed(data: ByteArray, off: Int = 0, len: Int = data.size - off) {
+ for (i in off until off + len) {
+ val c = data[i].toInt() and 0xff
+ when {
+ c == FLAG -> {
+ if (buf.size() >= 4 && !esc) {
+ val f = buf.toByteArray()
+ if (fcs(f) == GOOD_FCS) onFrame(f.copyOf(f.size - 2)) else bad++
+ } else if (buf.size() > 0) {
+ bad++
+ }
+ buf.reset()
+ esc = false
+ }
+ c == ESC -> esc = true
+ else -> {
+ buf.write(if (esc) c xor 0x20 else c)
+ esc = false
+ if (buf.size() > 4000) { buf.reset(); bad++ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/neodesktop/dmodem/ppp/Internet.kt b/app/src/main/java/com/neodesktop/dmodem/ppp/Internet.kt
new file mode 100644
index 0000000..55485aa
--- /dev/null
+++ b/app/src/main/java/com/neodesktop/dmodem/ppp/Internet.kt
@@ -0,0 +1,214 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (C) 2026 Neo-Desktop
+package com.neodesktop.dmodem.ppp
+
+import com.neodesktop.dmodem.NativeModem
+import com.neodesktop.dmodem.bridge.Bridges
+import com.neodesktop.dmodem.fax.Class1
+import com.neodesktop.dmodem.fax.Fax
+import com.neodesktop.dmodem.modem.ModemState
+import com.neodesktop.dmodem.settings.IspSettings
+import com.neodesktop.dmodem.terminal.TerminalLink
+import com.neodesktop.dmodem.transfer.TransferCancelled
+import com.neodesktop.dmodem.transfer.TransferIo
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.launch
+import java.io.IOException
+
+/**
+ * Dial-up internet on the modem: the ISP dialled, PPP on the call
+ * ([Ppp]), and once it has an address the phone's traffic through it
+ * (a [Tunnel]: the VPN service's). The call has the modem's DTE to itself
+ * while it lasts; the carrier lost, or PPP down, it all comes down.
+ */
+object Internet {
+ /** where the link's packets go on the phone: the VPN's interface */
+ interface Tunnel {
+ /** a packet from the link */
+ fun write(packet: ByteArray)
+ fun close()
+ }
+
+ data class State(
+ /** what it's doing; "" when connected */
+ val phase: String,
+ val config: Ppp.IpConfig? = null,
+ /** the CONNECT the modem said ("CONNECT 52000/V92 …") */
+ val connect: String = "",
+ 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() = config != null && ended == null
+ val running: Boolean get() = ended == null
+ }
+
+ private val _state = MutableStateFlow(null)
+ val state: StateFlow = _state.asStateFlow()
+
+ @Volatile private var ppp: Ppp? = null
+ @Volatile private var line: TransferIo? = null
+ @Volatile private var tunnel: Tunnel? = null
+ @Volatile private var stopping = false
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private var watch: Job? = null
+
+ val running: Boolean get() = _state.value?.running == true
+
+ private fun set(f: (State) -> State) {
+ _state.value = _state.value?.let(f)
+ }
+
+ /** why it can't start now, or null */
+ fun busy(): String? = when {
+ ModemState.run.value != ModemState.Run.RUNNING -> "the modem is off"
+ running -> "it's connected already"
+ Fax.running -> "a fax call is going on"
+ ModemState.status.value.offhook -> "the modem is in a call"
+ Bridges.serial.client.value != null -> "the modem is in use by ${Bridges.serial.client.value?.name}"
+ else -> null
+ }
+
+ /**
+ * the ISP dialled and PPP brought up; [openTunnel] gets the link's
+ * address and DNS servers (its packets to [sendIp]): null when it
+ * can't (the link comes down again). Null when it has started, else
+ * why it can't.
+ */
+ fun connect(isp: IspSettings, openTunnel: (Ppp.IpConfig) -> Tunnel?): String? {
+ busy()?.let { return it }
+ if (!isp.complete) return "no number for the ISP"
+ val hub = ModemState.dte
+ lateinit var listener: TerminalLink.Listener
+ val io = TransferIo { b -> if (!hub.writeAs(listener, b)) throw IOException("the modem has gone") }
+ // (the modem's octets: the AT commands' until CONNECT, then PPP's)
+ listener = TerminalLink.Listener { d, n -> ppp?.input(d, 0, n) ?: io.feed(d, 0, n) }
+ if (!hub.claim(listener)) return "the modem is in use"
+ line = io
+ stopping = false
+ _state.value = State("Dialling ${isp.number}")
+ Thread({
+ var why: String? = null
+ var online = false
+ try {
+ val c = Class1(io) { ModemState.log.add("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 isp.initCommands.split(Regex("[\\r\\n;]+")).map { it.trim() }.filter { it.isNotEmpty() }) {
+ c.command(cmd.removePrefix("AT").removePrefix("at"))
+ }
+ val r = c.command("D${isp.number}", 90_000)
+ if (r == null || !r.startsWith("CONNECT")) throw IOException(dialResult(r))
+ online = true
+ set { it.copy(phase = "Logging in", connect = r) }
+ val done = java.util.concurrent.CountDownLatch(1)
+ val p = Ppp(
+ send = { b -> if (!hub.writeAs(listener, b)) throw IOException("the modem has gone") },
+ user = isp.user,
+ password = isp.password,
+ events = object : Ppp.Events {
+ override fun up(config: Ppp.IpConfig) {
+ val t = try { openTunnel(config) } catch (e: Exception) { null }
+ if (t == null) {
+ why = "the VPN couldn't start"
+ ppp?.stop(why!!)
+ return
+ }
+ tunnel = t
+ set { it.copy(phase = "", config = config, since = System.currentTimeMillis()) }
+ }
+ override fun ip(packet: ByteArray) { tunnel?.write(packet) }
+ override fun down(reason: String) {
+ if (why == null) why = reason
+ done.countDown()
+ }
+ override fun log(line: String) { ModemState.log.add("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)
+ watchCarrier()
+ while (!done.await(1, java.util.concurrent.TimeUnit.SECONDS)) {
+ 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 {
+ watch?.cancel()
+ runCatching { tunnel?.close() }
+ tunnel = null
+ ppp = null
+ // the call hung up: +++ between its guard times, ATH
+ if (online) {
+ Thread.sleep(1200)
+ hub.writeAs(listener, "+++".toByteArray())
+ Thread.sleep(1200)
+ }
+ hub.writeAs(listener, "\rATH\r".toByteArray())
+ Thread.sleep(500)
+ line = null
+ hub.release(listener)
+ set { it.copy(phase = "", ended = why ?: "disconnected") }
+ }
+ }, "internet").apply { isDaemon = true; start() }
+ return null
+ }
+
+ /** a packet from the phone (the VPN's) to the link */
+ fun sendIp(packet: ByteArray): Boolean = ppp?.sendIp(packet) ?: false
+
+ /** the link closed and the call hung up */
+ fun disconnect() {
+ if (stopping) return
+ stopping = true
+ val p = ppp
+ if (p != null) p.stop("disconnected") else line?.cancel("disconnected")
+ }
+
+ fun dismiss() {
+ if (!running) _state.value = null
+ }
+
+ /** the carrier gone (the modem back on hook): the link down */
+ private fun watchCarrier() {
+ watch?.cancel()
+ var seen = false
+ watch = scope.launch {
+ // (the modem switched off: the link with it)
+ launch { ModemState.run.collect { r -> if (r != ModemState.Run.RUNNING) ppp?.stop("the modem stopped") } }
+ ModemState.status.collect { s ->
+ if (s.link == NativeModem.Link.ONLINE) seen = true
+ // (once the modem has said it's online: a modem that doesn't say isn't watched)
+ if (seen && s.link != NativeModem.Link.ONLINE && ModemState.run.value == ModemState.Run.RUNNING) {
+ // (a moment: the status catches up with the CONNECT)
+ kotlinx.coroutines.delay(3000)
+ if (ModemState.status.value.link != NativeModem.Link.ONLINE) ppp?.stop("the line dropped")
+ }
+ }
+ }
+ }
+
+ private fun dialResult(r: String?) = when (r) {
+ null -> "no answer"
+ "BUSY" -> "busy"
+ "NO ANSWER" -> "no answer"
+ "NO CARRIER" -> "no modem answered"
+ "NO DIALTONE", "NO DIAL TONE" -> "no line"
+ else -> r.lowercase()
+ }
+}
diff --git a/app/src/main/java/com/neodesktop/dmodem/ppp/Ip.kt b/app/src/main/java/com/neodesktop/dmodem/ppp/Ip.kt
new file mode 100644
index 0000000..82ddab3
--- /dev/null
+++ b/app/src/main/java/com/neodesktop/dmodem/ppp/Ip.kt
@@ -0,0 +1,52 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (C) 2026 Neo-Desktop
+package com.neodesktop.dmodem.ppp
+
+/** IPv4 and UDP packets, as far as the link's checks need them. */
+object Ip {
+ fun checksum(b: ByteArray, off: Int, len: Int, start: Long = 0): Int {
+ var s = start
+ var i = off
+ while (i + 1 < off + len) { s += ((b[i].toInt() and 0xff) shl 8) or (b[i + 1].toInt() and 0xff); i += 2 }
+ if (i < off + len) s += (b[i].toInt() and 0xff) shl 8
+ while (s ushr 16 != 0L) s = (s and 0xffff) + (s ushr 16)
+ return (s.inv() and 0xffff).toInt()
+ }
+
+ /** a UDP datagram in an IPv4 packet, its checksums set */
+ fun udp(src: ByteArray, dst: ByteArray, sport: Int, dport: Int, payload: ByteArray, id: Int = 1): ByteArray {
+ val total = 20 + 8 + payload.size
+ val p = ByteArray(total)
+ p[0] = 0x45
+ p[2] = (total ushr 8).toByte(); p[3] = total.toByte()
+ p[4] = (id ushr 8).toByte(); p[5] = id.toByte()
+ p[8] = 64
+ p[9] = 17
+ System.arraycopy(src, 0, p, 12, 4)
+ System.arraycopy(dst, 0, p, 16, 4)
+ val h = checksum(p, 0, 20)
+ p[10] = (h ushr 8).toByte(); p[11] = h.toByte()
+ val u = 20
+ p[u] = (sport ushr 8).toByte(); p[u + 1] = sport.toByte()
+ p[u + 2] = (dport ushr 8).toByte(); p[u + 3] = dport.toByte()
+ val ul = 8 + payload.size
+ p[u + 4] = (ul ushr 8).toByte(); p[u + 5] = ul.toByte()
+ System.arraycopy(payload, 0, p, u + 8, payload.size)
+ // (the pseudo header's sum: the addresses, the protocol, the length)
+ var pseudo = 17L + ul
+ for (k in 0 until 4 step 2) {
+ pseudo += ((src[k].toInt() and 0xff) shl 8) or (src[k + 1].toInt() and 0xff)
+ pseudo += ((dst[k].toInt() and 0xff) shl 8) or (dst[k + 1].toInt() and 0xff)
+ }
+ val c = checksum(p, u, ul, pseudo).let { if (it == 0) 0xffff else it }
+ p[u + 6] = (c ushr 8).toByte(); p[u + 7] = c.toByte()
+ return p
+ }
+
+ /** a UDP packet's payload */
+ fun udpPayload(p: ByteArray): ByteArray {
+ val ihl = (p[0].toInt() and 0x0f) * 4
+ val ul = ((p[ihl + 4].toInt() and 0xff) shl 8) or (p[ihl + 5].toInt() and 0xff)
+ return p.copyOfRange(ihl + 8, ihl + ul)
+ }
+}
diff --git a/app/src/main/java/com/neodesktop/dmodem/ppp/Ppp.kt b/app/src/main/java/com/neodesktop/dmodem/ppp/Ppp.kt
new file mode 100644
index 0000000..5e7f831
--- /dev/null
+++ b/app/src/main/java/com/neodesktop/dmodem/ppp/Ppp.kt
@@ -0,0 +1,493 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (C) 2026 Neo-Desktop
+package com.neodesktop.dmodem.ppp
+
+import java.io.ByteArrayOutputStream
+import java.net.Inet4Address
+import java.net.InetAddress
+import java.security.MessageDigest
+import java.util.concurrent.Executors
+import java.util.concurrent.ScheduledFuture
+import java.util.concurrent.TimeUnit
+import kotlin.random.Random
+
+/**
+ * A PPP client (RFC 1661) on a dial-up line, as a PC's dialer was: LCP
+ * (MRU, ACCM, magic number, the authentication the server asks for),
+ * PAP or CHAP-MD5 with [user] and [password], IPCP for an address and
+ * the DNS servers; then IPv4 packets both ways. What it doesn't take
+ * (compression, IPv6, the rest) it rejects. [send] gets the line's
+ * octets (framed); [input] takes the line's.
+ */
+class Ppp(
+ private val send: (ByteArray) -> Unit,
+ private val user: String = "",
+ private val password: String = "",
+ private val events: Events,
+ /** how long between retries, and how many before it gives up */
+ private val retryMs: Long = 3000,
+ private val maxRetries: Int = 10,
+) {
+ /** the link's address and DNS servers, once IPCP has them */
+ data class IpConfig(val address: Inet4Address, val peer: Inet4Address?, val dns: List, val mtu: Int)
+
+ interface Events {
+ fun up(config: IpConfig)
+ fun ip(packet: ByteArray)
+ fun down(reason: String)
+ fun log(line: String) {}
+ }
+
+ enum class Phase { DEAD, ESTABLISH, AUTHENTICATE, NETWORK, OPEN, TERMINATE }
+
+ @Volatile var phase = Phase.DEAD
+ private set
+
+ private val timer = Executors.newSingleThreadScheduledExecutor { r -> Thread(r, "ppp-timer").apply { isDaemon = true } }
+ private val lock = Any()
+ private val decoder = Hdlc.Decoder { f -> synchronized(lock) { frame(f) } }
+
+ // what each side asked
+ private var sendAccm = -1 // the peer's: what we escape
+ private var peerMru = 1500
+ private val magic = Random.nextInt().let { if (it == 0) 1 else it }
+ private var authProto = 0 // what the peer asked us to authenticate with (0 none)
+
+ // LCP
+ private var lcpId = 0
+ private var lcpOurAcked = false
+ private var lcpTheirAcked = false
+ private var lcpRetries = 0
+ private var lcpMru = 1500
+ private var lcpAskAccm = true
+ private var lcpAskMagic = true
+ private var lcpTimer: ScheduledFuture<*>? = null
+
+ // authentication
+ private var authId = 0
+ private var authTimer: ScheduledFuture<*>? = null
+ private var authRetries = 0
+
+ // IPCP
+ private var ipcpId = 0
+ private var ipcpOurAcked = false
+ private var ipcpTheirAcked = false
+ private var ipcpRetries = 0
+ private var ipcpTimer: ScheduledFuture<*>? = null
+ private var ourAddr = ByteArray(4)
+ private var dns1 = ByteArray(4)
+ private var dns2 = ByteArray(4)
+ private var askDns1 = true
+ private var askDns2 = true
+ private var peerAddr: ByteArray? = null
+
+ // counts
+ @Volatile var bytesIn = 0L
+ private set
+ @Volatile var bytesOut = 0L
+ private set
+
+ private fun log(s: String) = events.log(s)
+
+ // ------------------------------------------------------------------
+
+ /** the link brought up: LCP's Configure-Request out */
+ fun start() = synchronized(lock) {
+ phase = Phase.ESTABLISH
+ sendLcpConfReq()
+ }
+
+ /** octets from the line */
+ fun input(data: ByteArray, off: Int = 0, len: Int = data.size - off) = decoder.feed(data, off, len)
+
+ /** an IPv4 packet out, when the link is open (false: it isn't) */
+ fun sendIp(packet: ByteArray): Boolean {
+ if (phase != Phase.OPEN) return false
+ bytesOut += packet.size
+ out(PROTO_IP, packet)
+ return true
+ }
+
+ /** the link closed: LCP's Terminate-Request (its Ack waited for a moment), then down */
+ fun stop(reason: String = "disconnected") {
+ synchronized(lock) {
+ if (phase == Phase.DEAD) return
+ if (phase != Phase.ESTABLISH) {
+ phase = Phase.TERMINATE
+ out(PROTO_LCP, packet(TERM_REQ, ++lcpId, ByteArray(0)))
+ }
+ }
+ // (a moment for the Terminate-Ack)
+ timer.schedule({ down(reason) }, if (phase == Phase.TERMINATE) 500 else 0, TimeUnit.MILLISECONDS)
+ }
+
+ private fun down(reason: String) {
+ synchronized(lock) {
+ if (phase == Phase.DEAD) return
+ phase = Phase.DEAD
+ lcpTimer?.cancel(false)
+ authTimer?.cancel(false)
+ ipcpTimer?.cancel(false)
+ }
+ log("down: $reason")
+ events.down(reason)
+ timer.shutdown()
+ }
+
+ // ------------------------------------------------------------------
+ // frames
+
+ private fun out(proto: Int, info: ByteArray) {
+ val f = ByteArray(4 + info.size)
+ f[0] = 0xff.toByte()
+ f[1] = 0x03
+ f[2] = (proto ushr 8).toByte()
+ f[3] = proto.toByte()
+ System.arraycopy(info, 0, f, 4, info.size)
+ // (LCP always with every control character escaped: RFC 1662 7.1)
+ send(Hdlc.encode(f, if (proto == PROTO_LCP) -1 else sendAccm))
+ }
+
+ private fun packet(code: Int, id: Int, data: ByteArray): ByteArray {
+ val p = ByteArray(4 + data.size)
+ p[0] = code.toByte()
+ p[1] = id.toByte()
+ p[2] = (p.size ushr 8).toByte()
+ p[3] = p.size.toByte()
+ System.arraycopy(data, 0, p, 4, data.size)
+ return p
+ }
+
+ private fun frame(f: ByteArray) {
+ // address and control (or not, with ACFC), the protocol (one octet with PFC)
+ var i = 0
+ if (f.size >= 2 && (f[0].toInt() and 0xff) == 0xff && f[1].toInt() == 0x03) i = 2
+ if (i >= f.size) return
+ val proto: Int
+ if ((f[i].toInt() and 1) == 1) {
+ proto = f[i].toInt() and 0xff
+ i += 1
+ } else {
+ if (i + 1 >= f.size) return
+ proto = ((f[i].toInt() and 0xff) shl 8) or (f[i + 1].toInt() and 0xff)
+ i += 2
+ }
+ val info = f.copyOfRange(i, f.size)
+ when (proto) {
+ PROTO_LCP -> lcp(info)
+ PROTO_PAP -> pap(info)
+ PROTO_CHAP -> chap(info)
+ PROTO_IPCP -> ipcp(info)
+ PROTO_IP -> if (phase == Phase.OPEN) { bytesIn += info.size; events.ip(info) }
+ else -> if (phase.ordinal >= Phase.AUTHENTICATE.ordinal && phase != Phase.TERMINATE) {
+ // not ours: rejected (IPv6CP, CCP, …)
+ log("protocol %04x rejected".format(proto))
+ out(PROTO_LCP, packet(PROT_REJ, ++lcpId, byteArrayOf((proto ushr 8).toByte(), proto.toByte()) + info))
+ }
+ }
+ }
+
+ /** a packet's options: (type, data) */
+ private fun options(p: ByteArray): List>? {
+ val out = ArrayList>()
+ var i = 4
+ val end = minOf(p.size, len(p))
+ while (i + 2 <= end) {
+ val t = p[i].toInt() and 0xff
+ val l = p[i + 1].toInt() and 0xff
+ if (l < 2 || i + l > end) return null
+ out.add(t to p.copyOfRange(i + 2, i + l))
+ i += l
+ }
+ return out
+ }
+
+ private fun len(p: ByteArray) = if (p.size >= 4) ((p[2].toInt() and 0xff) shl 8) or (p[3].toInt() and 0xff) else 0
+
+ private fun opts(list: List>): ByteArray {
+ val o = ByteArrayOutputStream()
+ for ((t, d) in list) { o.write(t); o.write(d.size + 2); o.write(d) }
+ return o.toByteArray()
+ }
+
+ private fun int32(v: Int) = byteArrayOf((v ushr 24).toByte(), (v ushr 16).toByte(), (v ushr 8).toByte(), v.toByte())
+ private fun int32(d: ByteArray) = ((d[0].toInt() and 0xff) shl 24) or ((d[1].toInt() and 0xff) shl 16) or
+ ((d[2].toInt() and 0xff) shl 8) or (d[3].toInt() and 0xff)
+ private fun int16(d: ByteArray) = ((d[0].toInt() and 0xff) shl 8) or (d[1].toInt() and 0xff)
+
+ // ------------------------------------------------------------------
+ // LCP
+
+ private fun sendLcpConfReq() {
+ val o = ArrayList>()
+ if (lcpMru != 1500) o.add(1 to byteArrayOf((lcpMru ushr 8).toByte(), lcpMru.toByte()))
+ // nothing of ours escaped (the modem's link is 8-bit clean)
+ if (lcpAskAccm) o.add(2 to int32(0))
+ if (lcpAskMagic) o.add(5 to int32(magic))
+ out(PROTO_LCP, packet(CONF_REQ, ++lcpId, opts(o)))
+ lcpTimer?.cancel(false)
+ lcpTimer = timer.schedule({
+ synchronized(lock) {
+ if (phase != Phase.ESTABLISH || lcpOurAcked) return@synchronized
+ if (++lcpRetries > maxRetries) { down("the other end doesn't talk PPP"); return@synchronized }
+ sendLcpConfReq()
+ }
+ }, retryMs, TimeUnit.MILLISECONDS)
+ }
+
+ private fun lcp(p: ByteArray) {
+ if (p.size < 4) return
+ val code = p[0].toInt() and 0xff
+ val id = p[1].toInt() and 0xff
+ when (code) {
+ CONF_REQ -> {
+ // (a renegotiation once up: from the start)
+ if (phase.ordinal > Phase.ESTABLISH.ordinal && phase != Phase.TERMINATE) restartLcp()
+ val o = options(p) ?: return
+ val reject = ArrayList>()
+ val nak = ArrayList>()
+ var mru = 1500
+ var accm = -1
+ var auth = 0
+ for ((t, d) in o) {
+ when (t) {
+ 1 -> if (d.size == 2) mru = int16(d) else reject.add(t to d)
+ 2 -> if (d.size == 4) accm = int32(d) else reject.add(t to d)
+ 3 -> {
+ val proto = if (d.size >= 2) int16(d) else 0
+ when {
+ proto == PROTO_PAP && d.size == 2 -> auth = PROTO_PAP
+ proto == PROTO_CHAP && d.size == 3 && d[2].toInt() == 5 -> auth = PROTO_CHAP
+ // (MS-CHAP and the rest: CHAP-MD5 asked for instead)
+ else -> nak.add(3 to byteArrayOf((PROTO_CHAP ushr 8).toByte(), PROTO_CHAP.toByte(), 5))
+ }
+ }
+ 5 -> if (d.size == 4 && int32(d) == magic) {
+ // our own magic number: a looped-back line
+ nak.add(5 to int32(Random.nextInt()))
+ }
+ else -> reject.add(t to d)
+ }
+ }
+ when {
+ reject.isNotEmpty() -> out(PROTO_LCP, packet(CONF_REJ, id, opts(reject)))
+ nak.isNotEmpty() -> out(PROTO_LCP, packet(CONF_NAK, id, opts(nak)))
+ else -> {
+ peerMru = mru
+ sendAccm = accm
+ authProto = auth
+ out(PROTO_LCP, packet(CONF_ACK, id, p.copyOfRange(4, len(p).coerceAtMost(p.size))))
+ lcpTheirAcked = true
+ lcpMaybeUp()
+ }
+ }
+ }
+ CONF_ACK -> if (id == lcpId) { lcpOurAcked = true; lcpTimer?.cancel(false); lcpMaybeUp() }
+ CONF_NAK -> if (id == lcpId) {
+ for ((t, d) in options(p) ?: return) {
+ when (t) {
+ 1 -> if (d.size == 2) lcpMru = int16(d)
+ 2 -> lcpAskAccm = false
+ 5 -> lcpAskMagic = d.size == 4
+ }
+ }
+ sendLcpConfReq()
+ }
+ CONF_REJ -> if (id == lcpId) {
+ for ((t, _) in options(p) ?: return) {
+ when (t) { 1 -> lcpMru = 1500; 2 -> lcpAskAccm = false; 5 -> lcpAskMagic = false }
+ }
+ sendLcpConfReq()
+ }
+ TERM_REQ -> {
+ out(PROTO_LCP, packet(TERM_ACK, id, ByteArray(0)))
+ timer.schedule({ down("the other end hung up the link") }, 100, TimeUnit.MILLISECONDS)
+ }
+ TERM_ACK -> if (phase == Phase.TERMINATE) timer.execute { down("disconnected") }
+ ECHO_REQ -> if (phase.ordinal >= Phase.AUTHENTICATE.ordinal && p.size >= 8) {
+ out(PROTO_LCP, packet(ECHO_REP, id, int32(if (lcpAskMagic) magic else 0) + p.copyOfRange(8, len(p).coerceAtMost(p.size))))
+ }
+ PROT_REJ -> log("the other end rejected protocol %04x".format(if (p.size >= 6) int16(p.copyOfRange(4, 6)) else 0))
+ CODE_REJ -> log("the other end rejected an LCP code")
+ ECHO_REP, DISCARD_REQ -> {}
+ else -> out(PROTO_LCP, packet(CODE_REJ, ++lcpId, p.copyOf(len(p).coerceAtMost(p.size))))
+ }
+ }
+
+ private fun restartLcp() {
+ log("LCP again")
+ phase = Phase.ESTABLISH
+ lcpOurAcked = false
+ lcpTheirAcked = false
+ lcpRetries = 0
+ ipcpOurAcked = false
+ ipcpTheirAcked = false
+ sendAccm = -1
+ sendLcpConfReq()
+ }
+
+ private fun lcpMaybeUp() {
+ if (!(lcpOurAcked && lcpTheirAcked) || phase != Phase.ESTABLISH) return
+ log("LCP up (mru $peerMru, accm %08x, auth %04x)".format(sendAccm, authProto))
+ when (authProto) {
+ PROTO_PAP -> { phase = Phase.AUTHENTICATE; sendPap() }
+ // (CHAP: the server's challenge comes)
+ PROTO_CHAP -> phase = Phase.AUTHENTICATE
+ else -> startIpcp()
+ }
+ }
+
+ // ------------------------------------------------------------------
+ // authentication
+
+ private fun sendPap() {
+ val u = user.toByteArray()
+ val pw = password.toByteArray()
+ out(PROTO_PAP, packet(1, ++authId, byteArrayOf(u.size.toByte()) + u + byteArrayOf(pw.size.toByte()) + pw))
+ authTimer?.cancel(false)
+ authTimer = timer.schedule({
+ synchronized(lock) {
+ if (phase != Phase.AUTHENTICATE) return@synchronized
+ if (++authRetries > maxRetries) { stopLocked("no answer to the login"); return@synchronized }
+ sendPap()
+ }
+ }, retryMs, TimeUnit.MILLISECONDS)
+ }
+
+ private fun stopLocked(why: String) {
+ timer.execute { stop(why) }
+ }
+
+ private fun pap(p: ByteArray) {
+ if (p.size < 4 || phase != Phase.AUTHENTICATE) return
+ when (p[0].toInt()) {
+ 2 -> { authTimer?.cancel(false); log("PAP: logged in"); startIpcp() }
+ 3 -> {
+ authTimer?.cancel(false)
+ val msg = if (p.size > 5) String(p, 5, minOf(p[4].toInt() and 0xff, p.size - 5)) else ""
+ stopLocked("the login was refused" + if (msg.isNotBlank()) ": $msg" else "")
+ }
+ }
+ }
+
+ private fun chap(p: ByteArray) {
+ if (p.size < 4) return
+ val id = p[1].toInt() and 0xff
+ when (p[0].toInt()) {
+ 1 -> {
+ // a challenge: MD5 of the id, the secret and the challenge
+ val n = p[4].toInt() and 0xff
+ if (p.size < 5 + n) return
+ val challenge = p.copyOfRange(5, 5 + n)
+ val md = MessageDigest.getInstance("MD5")
+ md.update(id.toByte())
+ md.update(password.toByteArray())
+ md.update(challenge)
+ val r = md.digest()
+ out(PROTO_CHAP, packet(2, id, byteArrayOf(r.size.toByte()) + r + user.toByteArray()))
+ }
+ 3 -> if (phase == Phase.AUTHENTICATE) { log("CHAP: logged in"); startIpcp() }
+ 4 -> stopLocked("the login was refused" + if (p.size > 4) ": " + String(p, 4, len(p).coerceAtMost(p.size) - 4) else "")
+ }
+ }
+
+ // ------------------------------------------------------------------
+ // IPCP
+
+ private fun startIpcp() {
+ phase = Phase.NETWORK
+ ipcpRetries = 0
+ sendIpcpConfReq()
+ }
+
+ private fun sendIpcpConfReq() {
+ val o = ArrayList>()
+ o.add(3 to ourAddr)
+ if (askDns1) o.add(129 to dns1)
+ if (askDns2) o.add(131 to dns2)
+ out(PROTO_IPCP, packet(CONF_REQ, ++ipcpId, opts(o)))
+ ipcpTimer?.cancel(false)
+ ipcpTimer = timer.schedule({
+ synchronized(lock) {
+ if (phase != Phase.NETWORK || ipcpOurAcked) return@synchronized
+ if (++ipcpRetries > maxRetries) { stopLocked("no address came"); return@synchronized }
+ sendIpcpConfReq()
+ }
+ }, retryMs, TimeUnit.MILLISECONDS)
+ }
+
+ private fun ipcp(p: ByteArray) {
+ if (p.size < 4) return
+ if (phase.ordinal < Phase.NETWORK.ordinal || phase == Phase.TERMINATE) {
+ // (before LCP is up: dropped; IPCP comes again)
+ return
+ }
+ val code = p[0].toInt() and 0xff
+ val id = p[1].toInt() and 0xff
+ when (code) {
+ CONF_REQ -> {
+ val o = options(p) ?: return
+ val reject = o.filter { (t, d) -> t != 3 || d.size != 4 }
+ if (reject.isNotEmpty()) {
+ out(PROTO_IPCP, packet(CONF_REJ, id, opts(reject)))
+ } else {
+ peerAddr = o.firstOrNull { it.first == 3 }?.second
+ out(PROTO_IPCP, packet(CONF_ACK, id, p.copyOfRange(4, len(p).coerceAtMost(p.size))))
+ ipcpTheirAcked = true
+ ipcpMaybeUp()
+ }
+ }
+ CONF_NAK -> if (id == ipcpId) {
+ for ((t, d) in options(p) ?: return) {
+ if (d.size != 4) continue
+ when (t) { 3 -> ourAddr = d; 129 -> dns1 = d; 131 -> dns2 = d }
+ }
+ sendIpcpConfReq()
+ }
+ CONF_REJ -> if (id == ipcpId) {
+ for ((t, _) in options(p) ?: return) {
+ when (t) { 129 -> askDns1 = false; 131 -> askDns2 = false }
+ }
+ sendIpcpConfReq()
+ }
+ CONF_ACK -> if (id == ipcpId) { ipcpOurAcked = true; ipcpTimer?.cancel(false); ipcpMaybeUp() }
+ TERM_REQ -> out(PROTO_IPCP, packet(TERM_ACK, id, ByteArray(0)))
+ }
+ }
+
+ private fun ipcpMaybeUp() {
+ if (!(ipcpOurAcked && ipcpTheirAcked) || phase != Phase.NETWORK) return
+ if (ourAddr.all { it.toInt() == 0 }) { stopLocked("no address came"); return }
+ phase = Phase.OPEN
+ val dns = listOf(dns1, dns2).filter { d -> d.any { it.toInt() != 0 } }
+ .map { InetAddress.getByAddress(it) as Inet4Address }
+ val cfg = IpConfig(
+ InetAddress.getByAddress(ourAddr) as Inet4Address,
+ peerAddr?.let { InetAddress.getByAddress(it) as Inet4Address },
+ dns,
+ minOf(peerMru, 1500),
+ )
+ log("IPCP up: ${cfg.address.hostAddress}, dns ${dns.joinToString { it.hostAddress ?: "" }}")
+ timer.execute { events.up(cfg) }
+ }
+
+ companion object {
+ const val PROTO_IP = 0x0021
+ const val PROTO_IPCP = 0x8021
+ const val PROTO_LCP = 0xc021
+ const val PROTO_PAP = 0xc023
+ const val PROTO_CHAP = 0xc223
+
+ const val CONF_REQ = 1
+ const val CONF_ACK = 2
+ const val CONF_NAK = 3
+ const val CONF_REJ = 4
+ const val TERM_REQ = 5
+ const val TERM_ACK = 6
+ const val CODE_REJ = 7
+ const val PROT_REJ = 8
+ const val ECHO_REQ = 9
+ const val ECHO_REP = 10
+ const val DISCARD_REQ = 11
+ }
+}
diff --git a/app/src/main/java/com/neodesktop/dmodem/ppp/PppVpnService.kt b/app/src/main/java/com/neodesktop/dmodem/ppp/PppVpnService.kt
new file mode 100644
index 0000000..bbae084
--- /dev/null
+++ b/app/src/main/java/com/neodesktop/dmodem/ppp/PppVpnService.kt
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (C) 2026 Neo-Desktop
+package com.neodesktop.dmodem.ppp
+
+import android.content.Context
+import android.content.Intent
+import android.net.VpnService
+import android.os.ParcelFileDescriptor
+import java.io.FileInputStream
+import java.io.FileOutputStream
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
+
+/**
+ * The dial-up link as the phone's network: a VPN whose interface has the
+ * link's address and DNS servers and all IPv4 (IPv6 dropped: the link
+ * has none, and apps fall back), its packets to the link and the link's
+ * to it. The app's own traffic (the modem's SIP call itself) stays out of
+ * it. Asked for with VpnService.prepare() first.
+ */
+class PppVpnService : VpnService() {
+
+ private var pfd: ParcelFileDescriptor? = null
+ @Volatile private var out: FileOutputStream? = null
+ private var reader: Thread? = null
+
+ override fun onCreate() {
+ super.onCreate()
+ instance = this
+ ready.countDown()
+ }
+
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+ if (intent?.action == ACTION_STOP) {
+ close()
+ stopSelf()
+ }
+ return START_NOT_STICKY
+ }
+
+ override fun onRevoke() {
+ // the user turned the VPN off (or another took over): the call hung up
+ Internet.disconnect()
+ close()
+ super.onRevoke()
+ }
+
+ override fun onDestroy() {
+ close()
+ if (instance === this) instance = null
+ ready = CountDownLatch(1)
+ super.onDestroy()
+ }
+
+ private fun open(cfg: Ppp.IpConfig): Internet.Tunnel? {
+ close()
+ val b = Builder()
+ .setSession("D-Modem dial-up")
+ .setMtu(cfg.mtu)
+ .addAddress(cfg.address, 32)
+ .addRoute("0.0.0.0", 0)
+ for (d in cfg.dns) b.addDnsServer(d)
+ // (IPv6 into the VPN and dropped there: none of it around the link)
+ runCatching { b.addRoute("::", 0) }
+ runCatching { b.addDisallowedApplication(packageName) }
+ val fd = b.establish() ?: return null
+ pfd = fd
+ val o = FileOutputStream(fd.fileDescriptor)
+ out = o
+ val input = FileInputStream(fd.fileDescriptor)
+ reader = Thread({
+ val buf = ByteArray(32768)
+ while (true) {
+ val n = try { input.read(buf) } catch (_: Exception) { -1 }
+ if (n < 0) break
+ // IPv4 to the link; the rest (IPv6) dropped
+ if (n > 0 && (buf[0].toInt() ushr 4) == 4) Internet.sendIp(buf.copyOf(n))
+ }
+ }, "vpn-reader").apply { isDaemon = true; start() }
+ return object : Internet.Tunnel {
+ override fun write(packet: ByteArray) {
+ runCatching { out?.write(packet) }
+ }
+
+ override fun close() {
+ this@PppVpnService.close()
+ stopSelf()
+ }
+ }
+ }
+
+ private fun close() {
+ runCatching { pfd?.close() }
+ pfd = null
+ out = null
+ reader = null
+ }
+
+ companion object {
+ const val ACTION_STOP = "com.neodesktop.dmodem.VPN_STOP"
+ @Volatile private var instance: PppVpnService? = null
+ @Volatile private var ready = CountDownLatch(1)
+
+ /** the VPN up for [cfg] (the service started first): its tunnel, null if it can't be */
+ fun open(context: Context, cfg: Ppp.IpConfig): Internet.Tunnel? {
+ context.startService(Intent(context, PppVpnService::class.java))
+ if (!ready.await(10, TimeUnit.SECONDS)) return null
+ return instance?.open(cfg)
+ }
+ }
+}
diff --git a/app/src/main/java/com/neodesktop/dmodem/settings/IspSettings.kt b/app/src/main/java/com/neodesktop/dmodem/settings/IspSettings.kt
new file mode 100644
index 0000000..102f62b
--- /dev/null
+++ b/app/src/main/java/com/neodesktop/dmodem/settings/IspSettings.kt
@@ -0,0 +1,49 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (C) 2026 Neo-Desktop
+package com.neodesktop.dmodem.settings
+
+import android.content.Context
+import androidx.datastore.core.DataStore
+import androidx.datastore.preferences.core.Preferences
+import androidx.datastore.preferences.core.edit
+import androidx.datastore.preferences.core.stringPreferencesKey
+import androidx.datastore.preferences.preferencesDataStore
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.map
+
+/** The dial-up ISP: its number, the PPP login, AT commands before the dial. */
+data class IspSettings(
+ val number: String = "",
+ val user: String = "",
+ val password: String = "",
+ val initCommands: String = "",
+) {
+ val complete: Boolean get() = number.isNotBlank()
+}
+
+private val Context.ispStore: DataStore by preferencesDataStore("isp")
+
+class IspSettingsStore(private val context: Context) {
+ private object K {
+ val number = stringPreferencesKey("number")
+ val user = stringPreferencesKey("user")
+ val password = stringPreferencesKey("password")
+ val init = stringPreferencesKey("init")
+ }
+
+ val settings: Flow = context.ispStore.data.map { p ->
+ IspSettings(p[K.number] ?: "", p[K.user] ?: "", p[K.password] ?: "", p[K.init] ?: "")
+ }
+
+ suspend fun current(): IspSettings = settings.first()
+
+ suspend fun save(s: IspSettings) {
+ context.ispStore.edit { p ->
+ p[K.number] = s.number.trim()
+ p[K.user] = s.user.trim()
+ p[K.password] = s.password
+ p[K.init] = s.initCommands.trim()
+ }
+ }
+}
diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/DashboardScreen.kt b/app/src/main/java/com/neodesktop/dmodem/ui/DashboardScreen.kt
index 31476e8..9f1d9b8 100644
--- a/app/src/main/java/com/neodesktop/dmodem/ui/DashboardScreen.kt
+++ b/app/src/main/java/com/neodesktop/dmodem/ui/DashboardScreen.kt
@@ -153,6 +153,9 @@ fun DashboardScreen(
}
}
+ SectionTitle("Internet")
+ InternetCard(onSetUp = onOpenSettings)
+
SectionTitle("Fax")
FaxSection()
diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/InternetUi.kt b/app/src/main/java/com/neodesktop/dmodem/ui/InternetUi.kt
new file mode 100644
index 0000000..6ede01a
--- /dev/null
+++ b/app/src/main/java/com/neodesktop/dmodem/ui/InternetUi.kt
@@ -0,0 +1,154 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (C) 2026 Neo-Desktop
+package com.neodesktop.dmodem.ui
+
+import android.app.Activity
+import android.net.VpnService
+import android.widget.Toast
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.material3.Button
+import androidx.compose.material3.Card
+import androidx.compose.material3.LinearProgressIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableLongStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.text.input.PasswordVisualTransformation
+import androidx.compose.ui.unit.dp
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import com.neodesktop.dmodem.modem.ModemState
+import com.neodesktop.dmodem.ppp.Internet
+import com.neodesktop.dmodem.ppp.PppVpnService
+import com.neodesktop.dmodem.settings.IspSettings
+import com.neodesktop.dmodem.settings.IspSettingsStore
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+
+/** Home's dial-up internet: connect (the VPN asked for first), how it goes, disconnect. */
+@Composable
+fun InternetCard(onSetUp: () -> Unit) {
+ val context = LocalContext.current
+ val scope = rememberCoroutineScope()
+ val store = remember { IspSettingsStore(context.applicationContext) }
+ val isp by store.settings.collectAsStateWithLifecycle(initialValue = IspSettings())
+ val state by Internet.state.collectAsStateWithLifecycle()
+ val run by ModemState.run.collectAsStateWithLifecycle()
+
+ fun dial() {
+ val app = context.applicationContext
+ scope.launch {
+ Internet.connect(store.current()) { cfg -> PppVpnService.open(app, cfg) }
+ ?.let { Toast.makeText(context, it, Toast.LENGTH_LONG).show() }
+ }
+ }
+ // the system's VPN consent, the first time
+ val consent = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
+ if (r.resultCode == Activity.RESULT_OK) dial() else Toast.makeText(context, "The VPN wasn't allowed", Toast.LENGTH_LONG).show()
+ }
+
+ Card(Modifier.fillMaxWidth()) {
+ Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ val st = state
+ when {
+ st == null || !st.running -> {
+ Text("Dial-up internet", style = MaterialTheme.typography.titleSmall)
+ Text(
+ st?.ended?.let { "Disconnected: $it" }
+ ?: if (isp.complete) "Dials ${isp.number}; the phone's traffic goes over the call" else "Set up an ISP's number to dial",
+ style = MaterialTheme.typography.bodySmall,
+ )
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (isp.complete) {
+ Button(onClick = {
+ val ask = VpnService.prepare(context)
+ if (ask != null) consent.launch(ask) else dial()
+ }, enabled = run == ModemState.Run.RUNNING) { Text("Connect") }
+ }
+ TextButton(onClick = onSetUp) { Text(if (isp.complete) "ISP settings" else "Set up") }
+ if (st?.ended != null) TextButton(onClick = { Internet.dismiss() }) { Text("OK") }
+ }
+ }
+ !st.connected -> {
+ Text("Dial-up internet", style = MaterialTheme.typography.titleSmall)
+ Text(st.phase, style = MaterialTheme.typography.bodyMedium)
+ LinearProgressIndicator(Modifier.fillMaxWidth())
+ TextButton(onClick = { Internet.disconnect() }) { Text("Cancel") }
+ }
+ else -> {
+ val cfg = st.config!!
+ var now by remember { mutableLongStateOf(System.currentTimeMillis()) }
+ LaunchedEffect(Unit) { while (true) { now = System.currentTimeMillis(); delay(1000) } }
+ val secs = ((now - st.since) / 1000).coerceAtLeast(0)
+ Text("Connected to the internet", style = MaterialTheme.typography.titleSmall)
+ Text(
+ "${cfg.address.hostAddress} · ${st.connect.removePrefix("CONNECT").trim().ifEmpty { "connected" }} · " +
+ "%d:%02d".format(secs / 60, secs % 60),
+ style = MaterialTheme.typography.bodyMedium,
+ )
+ Text(
+ "↓ ${size(st.bytesIn)} ↑ ${size(st.bytesOut)}" +
+ (if (cfg.dns.isNotEmpty()) " · DNS ${cfg.dns.joinToString { it.hostAddress ?: "" }}" else ""),
+ style = MaterialTheme.typography.bodySmall,
+ )
+ Button(onClick = { Internet.disconnect() }) { Text("Disconnect") }
+ }
+ }
+ }
+ }
+}
+
+private fun size(n: Long) = when {
+ n < 1024 -> "$n B"
+ n < 1024 * 1024 -> "%.1f KB".format(n / 1024.0)
+ else -> "%.1f MB".format(n / 1048576.0)
+}
+
+/** The settings' ISP: its number, the login, AT commands before the dial. */
+@Composable
+fun IspSettingsSection() {
+ val context = LocalContext.current
+ val store = remember { IspSettingsStore(context.applicationContext) }
+ val scope = rememberCoroutineScope()
+ val current by store.settings.collectAsStateWithLifecycle(initialValue = null)
+ val loaded = current ?: return
+ var s by remember(loaded) { mutableStateOf(loaded) }
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text("Dial-up internet (ISP)", style = MaterialTheme.typography.titleMedium)
+ OutlinedTextField(
+ value = s.number, onValueChange = { s = s.copy(number = it) }, label = { Text("The ISP's number") }, singleLine = true,
+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone), modifier = Modifier.fillMaxWidth(),
+ )
+ OutlinedTextField(value = s.user, onValueChange = { s = s.copy(user = it) }, label = { Text("User name") }, singleLine = true, modifier = Modifier.fillMaxWidth())
+ OutlinedTextField(
+ value = s.password, onValueChange = { s = s.copy(password = it) }, label = { Text("Password") }, singleLine = true,
+ visualTransformation = PasswordVisualTransformation(), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
+ modifier = Modifier.fillMaxWidth(),
+ )
+ OutlinedTextField(
+ value = s.initCommands, onValueChange = { s = s.copy(initCommands = it) }, label = { Text("AT commands before the dial (optional)") },
+ singleLine = true, modifier = Modifier.fillMaxWidth(),
+ )
+ Button(onClick = {
+ scope.launch { store.save(s) }
+ Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show()
+ }, enabled = s != loaded) { Text("Save") }
+ }
+}
diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt b/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt
index dca18ba..ba0d115 100644
--- a/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt
+++ b/app/src/main/java/com/neodesktop/dmodem/ui/SettingsScreen.kt
@@ -109,6 +109,8 @@ fun SettingsScreen(modifier: Modifier = Modifier, onOpenTerminal: () -> Unit = {
androidx.compose.material3.HorizontalDivider(Modifier.padding(vertical = 8.dp))
FaxSettingsSection()
androidx.compose.material3.HorizontalDivider(Modifier.padding(vertical = 8.dp))
+ IspSettingsSection()
+ androidx.compose.material3.HorizontalDivider(Modifier.padding(vertical = 8.dp))
AppearanceSection()
androidx.compose.material3.HorizontalDivider(Modifier.padding(vertical = 8.dp))
TerminalSettingsSection()
diff --git a/app/src/test/java/com/neodesktop/dmodem/ppp/InternetLineTest.kt b/app/src/test/java/com/neodesktop/dmodem/ppp/InternetLineTest.kt
new file mode 100644
index 0000000..a670477
--- /dev/null
+++ b/app/src/test/java/com/neodesktop/dmodem/ppp/InternetLineTest.kt
@@ -0,0 +1,142 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (C) 2026 Neo-Desktop
+package com.neodesktop.dmodem.ppp
+
+import com.neodesktop.dmodem.modem.ModemState
+import com.neodesktop.dmodem.settings.IspSettings
+import com.neodesktop.dmodem.transfer.TransferIo
+import com.neodesktop.dmodem.fax.Class1
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Assume.assumeTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+import java.io.File
+import java.io.FileInputStream
+import java.io.FileOutputStream
+import java.util.concurrent.ArrayBlockingQueue
+import java.util.concurrent.CopyOnWriteArrayList
+import java.util.concurrent.TimeUnit
+
+/**
+ * Dial-up internet on a modem call: the app's [Internet] on the DTE
+ * hub, modemA of native-test's fax_line (two of D-Modem's modems back to
+ * back, paced as a line), an ISP on modemB (TestIsp: CHAP, an address,
+ * UDP echoed); the phone's side a tunnel here: a packet out, its answer
+ * back; then disconnected and hung up.
+ */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [28])
+class InternetLineTest {
+ private var line: Process? = null
+ private val log = CopyOnWriteArrayList()
+ private lateinit var a: String
+ private lateinit var b: String
+ private val closers = ArrayList<() -> Unit>()
+
+ private fun faxLine(): File? = listOfNotNull(System.getenv("DMODEM_FAX_LINE"), "../build-host/fax_line", "build-host/fax_line")
+ .map { File(it) }.firstOrNull { it.canExecute() }
+
+ @Before
+ fun setUp() {
+ val fl = faxLine()
+ assumeTrue("fax_line isn't built (native-test)", fl != null)
+ val p = ProcessBuilder(fl!!.path).redirectErrorStream(true).start()
+ line = p
+ Thread { p.inputStream.bufferedReader().forEachLine { log.add(it) } }.apply { isDaemon = true; start() }
+ val end = System.currentTimeMillis() + 10_000
+ while (System.currentTimeMillis() < end && log.none { it.startsWith("created modemB: ") }) Thread.sleep(20)
+ a = log.first { it.startsWith("created modemA: ") }.substringAfter(": ")
+ b = log.first { it.startsWith("created modemB: ") }.substringAfter(": ")
+ ProcessBuilder("stty", "-F", a, "raw", "-echo").start().waitFor()
+ ModemState.dte.attach(FileInputStream(a), FileOutputStream(a))
+ ModemState.setRun(ModemState.Run.RUNNING)
+ }
+
+ @After
+ fun tearDown() {
+ File("build/internet-log.txt").writeText((ModemState.log.flow.value + listOf("----") + log).joinToString("\n"))
+ Internet.disconnect()
+ closers.forEach { runCatching { it() } }
+ ModemState.dte.detach()
+ ModemState.setRun(ModemState.Run.STOPPED)
+ line?.destroy()
+ line?.waitFor(5, TimeUnit.SECONDS)
+ }
+
+ private fun waitLog(what: String, secs: Int = 30): Boolean {
+ val end = System.currentTimeMillis() + secs * 1000L
+ while (System.currentTimeMillis() < end) {
+ if (log.any { it.contains(what) }) return true
+ Thread.sleep(5)
+ }
+ return false
+ }
+
+ private fun dump() = (ModemState.log.flow.value.takeLast(40) + log.takeLast(40)).joinToString("\n")
+
+ @Test
+ fun onlineAndPacketsBothWays() {
+ // the ISP's modem, and its PPP once the call is up
+ ProcessBuilder("stty", "-F", b, "raw", "-echo").start().waitFor()
+ val input = FileInputStream(b)
+ val output = FileOutputStream(b)
+ closers.add { input.close(); output.close() }
+ val io = TransferIo { bytes -> output.write(bytes); output.flush() }
+ var isp: TestIsp? = null
+ Thread {
+ val buf = ByteArray(4096)
+ while (true) {
+ val n = try { input.read(buf) } catch (_: Exception) { -1 }
+ if (n < 0) break
+ isp?.input(buf.copyOf(n)) ?: io.feed(buf, 0, n)
+ }
+ }.apply { isDaemon = true; start() }
+ val c = Class1(io) { log.add("isp: $it") }
+ assertEquals("OK", c.command("E0"))
+
+ // the phone's side: the packets that come
+ val fromLink = ArrayBlockingQueue(100)
+ val tunnels = ArrayBlockingQueue(1)
+ var closed = false
+ val err = Internet.connect(IspSettings("5551000", "alice", "s3cret")) { cfg ->
+ tunnels.add(cfg)
+ object : Internet.Tunnel {
+ override fun write(packet: ByteArray) { fromLink.add(packet) }
+ override fun close() { closed = true }
+ }
+ }
+ assertEquals(null, err)
+ assertTrue(dump(), waitLog("modemA: run cmd: ATD5551000"))
+ assertTrue(c.command("A", 60_000).orEmpty().startsWith("CONNECT"))
+ isp = TestIsp(Ppp.PROTO_CHAP, "alice", "s3cret", echo = true) { f -> output.write(f); output.flush() }
+ isp.start()
+
+ val cfg = tunnels.poll(60, TimeUnit.SECONDS) ?: throw AssertionError("no link:\n${dump()}")
+ assertEquals("192.168.7.42", cfg.address.hostAddress)
+ assertEquals(listOf("192.168.7.1"), cfg.dns.map { it.hostAddress })
+ // (connected once the tunnel is there)
+ val until = System.currentTimeMillis() + 5000
+ while (Internet.state.value?.connected != true && System.currentTimeMillis() < until) Thread.sleep(20)
+ val st = Internet.state.value!!
+ assertTrue(st.toString(), st.connected && st.connect.startsWith("CONNECT"))
+
+ // a packet from the phone, its echo back from the ISP
+ assertTrue(Internet.sendIp(Ip.udp(cfg.address.address, byteArrayOf(192.toByte(), 168.toByte(), 7, 1), 5353, 7, "hello over the modem".toByteArray())))
+ val back = fromLink.poll(20, TimeUnit.SECONDS) ?: throw AssertionError("no answer:\n${dump()}")
+ assertEquals("pong:hello over the modem", String(Ip.udpPayload(back)))
+
+ // disconnected: the tunnel closed, the modem's DTE free again
+ Internet.disconnect()
+ val end = System.currentTimeMillis() + 15_000
+ while (Internet.state.value?.running == true && System.currentTimeMillis() < end) Thread.sleep(100)
+ assertEquals("disconnected", Internet.state.value?.ended)
+ assertTrue(closed)
+ assertTrue(!ModemState.dte.claimed)
+ assertTrue(dump(), log.any { it.contains("modemA: run cmd: ATH") })
+ }
+}
diff --git a/app/src/test/java/com/neodesktop/dmodem/ppp/PppTest.kt b/app/src/test/java/com/neodesktop/dmodem/ppp/PppTest.kt
new file mode 100644
index 0000000..d86e2be
--- /dev/null
+++ b/app/src/test/java/com/neodesktop/dmodem/ppp/PppTest.kt
@@ -0,0 +1,93 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (C) 2026 Neo-Desktop
+package com.neodesktop.dmodem.ppp
+
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.util.concurrent.ArrayBlockingQueue
+import java.util.concurrent.TimeUnit
+import kotlin.random.Random
+
+/**
+ * PPP: its framing; PAP and CHAP-MD5 against a server in the test (a
+ * wrong password said), the address and DNS from IPCP. (The packets
+ * themselves, on a modem call: InternetLineTest.)
+ */
+class PppTest {
+
+ @Test
+ fun framingBothWays() {
+ // FCS-16 of "123456789": 0x906e (RFC 1662's, complemented)
+ assertEquals(0x906e, Hdlc.fcs("123456789".toByteArray()) xor 0xffff)
+ val got = ArrayList()
+ val dec = Hdlc.Decoder { got.add(it) }
+ val frames = (0 until 20).map { Random(it).nextBytes(Random(it).nextInt(4, 1600)) } + listOf(ByteArray(300) { 0x7e }, ByteArray(300) { 0x7d })
+ for ((i, f) in frames.withIndex()) {
+ val e = Hdlc.encode(f, if (i % 2 == 0) -1 else 0)
+ // no flags inside, control characters escaped when asked
+ assertTrue(e.drop(1).dropLast(1).none { it.toInt() == 0x7e })
+ if (i % 2 == 0) assertTrue(e.drop(1).dropLast(1).none { (it.toInt() and 0xff) < 0x20 })
+ // fed a few octets at a time
+ var k = 0
+ while (k < e.size) { val n = minOf(7, e.size - k); dec.feed(e, k, n); k += n }
+ }
+ assertEquals(frames.size, got.size)
+ for (i in frames.indices) assertArrayEquals(frames[i], got[i])
+ // a damaged frame: dropped and counted
+ val bad = Hdlc.encode(frames[0], -1).also { it[5] = (it[5].toInt() xor 1).toByte() }
+ dec.feed(bad)
+ assertEquals(frames.size, got.size)
+ assertEquals(1, dec.bad)
+ }
+
+ private class Events : Ppp.Events {
+ val up = ArrayBlockingQueue(1)
+ val down = ArrayBlockingQueue(1)
+ val packets = ArrayBlockingQueue(100)
+ val lines = ArrayList()
+ override fun up(config: Ppp.IpConfig) { up.add(config) }
+ override fun ip(packet: ByteArray) { packets.add(packet) }
+ override fun down(reason: String) { down.add(reason) }
+ override fun log(line: String) { synchronized(lines) { lines.add(line) } }
+ }
+
+ private fun login(auth: Int, password: String): Pair {
+ val ev = Events()
+ lateinit var isp: TestIsp
+ lateinit var ppp: Ppp
+ // the two joined directly, each on its own thread's turn
+ val toIsp = ArrayBlockingQueue(1000)
+ val toUs = ArrayBlockingQueue(1000)
+ ppp = Ppp({ toIsp.add(it) }, user = "alice", password = password, events = ev, retryMs = 500, maxRetries = 4)
+ isp = TestIsp(auth, "alice", "s3cret") { toUs.add(it) }
+ Thread { while (true) isp.input(toIsp.take()) }.apply { isDaemon = true; start() }
+ Thread { while (true) ppp.input(toUs.take()) }.apply { isDaemon = true; start() }
+ isp.start()
+ ppp.start()
+ return ev to isp
+ }
+
+ @Test
+ fun papAndChap() {
+ for (auth in listOf(Ppp.PROTO_PAP, Ppp.PROTO_CHAP)) {
+ val (ev, isp) = login(auth, "s3cret")
+ val cfg = ev.up.poll(10, TimeUnit.SECONDS) ?: throw AssertionError("%04x: not up: ${ev.lines}".format(auth))
+ assertTrue(isp.loggedIn)
+ assertEquals("192.168.7.42", cfg.address.hostAddress)
+ assertEquals(listOf("192.168.7.1"), cfg.dns.map { it.hostAddress })
+ assertEquals("192.168.7.1", cfg.peer?.hostAddress)
+ }
+ }
+
+ @Test
+ fun aWrongPasswordIsSaid() {
+ for (auth in listOf(Ppp.PROTO_PAP, Ppp.PROTO_CHAP)) {
+ val (ev, _) = login(auth, "wrong")
+ val why = ev.down.poll(10, TimeUnit.SECONDS)
+ assertTrue("%04x: $why".format(auth), why != null && why.startsWith("the login was refused"))
+ assertEquals(null, ev.up.poll())
+ }
+ }
+}
diff --git a/app/src/test/java/com/neodesktop/dmodem/ppp/TestIsp.kt b/app/src/test/java/com/neodesktop/dmodem/ppp/TestIsp.kt
new file mode 100644
index 0000000..e6d92ce
--- /dev/null
+++ b/app/src/test/java/com/neodesktop/dmodem/ppp/TestIsp.kt
@@ -0,0 +1,83 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (C) 2026 Neo-Desktop
+package com.neodesktop.dmodem.ppp
+
+import java.security.MessageDigest
+import kotlin.random.Random
+
+/** a PPP server, just enough: LCP asking for [auth], the login checked, an address given */
+class TestIsp(val auth: Int, val user: String, val password: String, val echo: Boolean = false, val line: (ByteArray) -> Unit) {
+ var loggedIn = false
+ private var challenge = ByteArray(0)
+ private val dec = Hdlc.Decoder { f -> frame(f) }
+
+ fun input(b: ByteArray) = dec.feed(b)
+
+ fun start() {
+ val opt = if (auth == Ppp.PROTO_PAP) byteArrayOf(3, 4, 0xc0.toByte(), 0x23) else byteArrayOf(3, 5, 0xc2.toByte(), 0x23, 5)
+ out(Ppp.PROTO_LCP, pkt(1, 1, opt + byteArrayOf(5, 6, 1, 2, 3, 4)))
+ }
+
+ private fun out(proto: Int, info: ByteArray) =
+ line(Hdlc.encode(byteArrayOf(0xff.toByte(), 3, (proto ushr 8).toByte(), proto.toByte()) + info, -1))
+
+ private fun pkt(code: Int, id: Int, d: ByteArray) = byteArrayOf(code.toByte(), id.toByte(), ((d.size + 4) ushr 8).toByte(), (d.size + 4).toByte()) + d
+
+ private fun frame(f: ByteArray) {
+ val proto = ((f[2].toInt() and 0xff) shl 8) or (f[3].toInt() and 0xff)
+ val p = f.copyOfRange(4, f.size)
+ val code = p[0].toInt()
+ val id = p[1].toInt() and 0xff
+ when (proto) {
+ Ppp.PROTO_LCP -> when (code) {
+ 1 -> {
+ out(Ppp.PROTO_LCP, pkt(2, id, p.copyOfRange(4, p.size)))
+ if (auth == Ppp.PROTO_CHAP) {
+ challenge = Random.nextBytes(16)
+ out(Ppp.PROTO_CHAP, pkt(1, 7, byteArrayOf(16) + challenge + "isp".toByteArray()))
+ }
+ }
+ 9 -> {}
+ }
+ Ppp.PROTO_PAP -> if (code == 1) {
+ val ul = p[4].toInt()
+ val u = String(p, 5, ul)
+ val pw = String(p, 6 + ul, p[5 + ul].toInt())
+ loggedIn = u == user && pw == password
+ out(Ppp.PROTO_PAP, pkt(if (loggedIn) 2 else 3, id, byteArrayOf(0)))
+ if (loggedIn) ipcp()
+ }
+ Ppp.PROTO_CHAP -> if (code == 2) {
+ val r = p.copyOfRange(5, 5 + p[4].toInt())
+ val md = MessageDigest.getInstance("MD5")
+ md.update(id.toByte()); md.update(password.toByteArray()); md.update(challenge)
+ loggedIn = r.contentEquals(md.digest()) && String(p, 5 + 16, p.size - 21) == user
+ out(Ppp.PROTO_CHAP, pkt(if (loggedIn) 3 else 4, id, (if (loggedIn) "Welcome" else "Bad password").toByteArray()))
+ if (loggedIn) ipcp()
+ }
+ Ppp.PROTO_IP -> if (echo) echo(p)
+ Ppp.PROTO_IPCP -> when (code) {
+ // the client's 0.0.0.0 and DNS: our numbers instead; its numbers: taken
+ 1 -> {
+ val wanted = byteArrayOf(3, 6, 192.toByte(), 168.toByte(), 7, 42)
+ val dns = byteArrayOf(129.toByte(), 6, 192.toByte(), 168.toByte(), 7, 1)
+ if (p[6].toInt() == 0) out(Ppp.PROTO_IPCP, pkt(3, id, wanted + dns + byteArrayOf(131.toByte(), 6, 0, 0, 0, 0)))
+ else out(Ppp.PROTO_IPCP, pkt(2, id, p.copyOfRange(4, p.size)))
+ }
+ }
+ }
+ }
+
+ /** a UDP packet to us (192.168.7.1) back to its sender, "pong:" before its payload */
+private fun echo(p: ByteArray) {
+ if (p.size < 28 || p[9].toInt() != 17 || p[16] != 192.toByte() || p[19].toInt() != 1) return
+ val src = p.copyOfRange(12, 16)
+ val sport = ((p[20].toInt() and 0xff) shl 8) or (p[21].toInt() and 0xff)
+ val dport = ((p[22].toInt() and 0xff) shl 8) or (p[23].toInt() and 0xff)
+ val reply = Ip.udp(p.copyOfRange(16, 20), src, dport, sport, "pong:".toByteArray() + Ip.udpPayload(p))
+ out(Ppp.PROTO_IP, reply)
+}
+
+private fun ipcp() = out(Ppp.PROTO_IPCP, pkt(1, 1, byteArrayOf(3, 6, 192.toByte(), 168.toByte(), 7, 1)))
+}
+