diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 6f0a969..936114a 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -96,6 +96,14 @@ + + + { + val cm = context.getSystemService(android.net.ConnectivityManager::class.java) ?: return emptyList() + return cm.activeNetwork?.let { cm.getLinkProperties(it) }?.dnsServers.orEmpty() + } + /** "8N1" as a format at [baud] */ fun format(baud: Int, f: String): SerialFormat { val m = Regex("([5-8])([NEOMS])([12])").matchEntire(f.uppercase()) diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/HostService.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/HostService.kt new file mode 100644 index 0000000..db2ddae --- /dev/null +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/HostService.kt @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.bridge + +import android.app.Notification +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.ServiceInfo +import android.os.Build +import android.os.IBinder +import androidx.core.app.NotificationCompat +import androidx.core.app.ServiceCompat +import com.neodesktop.dmodem.DModemApp +import com.neodesktop.dmodem.R +import com.neodesktop.dmodem.settings.BridgeSettingsStore +import com.neodesktop.dmodem.ui.MainActivity +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.launch + +/** + * The bridges in internet mode (the phone as a dial-up ISP for computers + * on its serial ports), in the foreground, the modem and its SIP account + * not needed: on while the settings say so and a way for a computer to + * come is on. + */ +class HostService : Service() { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + private var watching = false + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + ServiceCompat.startForeground( + this, NOTIFICATION_ID, notification("Starting"), + if (Build.VERSION.SDK_INT >= 34) ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE else 0, + ) + if (watching) return START_STICKY + watching = true + scope.launch { + combine(BridgeSettingsStore(this@HostService).settings, Bridges.serial.client) { s, c -> s to c }.collect { (s, c) -> + if (!s.internet || !s.anyOn) { + Bridges.stopAll() + stopSelf() + return@collect + } + Bridges.apply(this@HostService, s) + getSystemService(android.app.NotificationManager::class.java) + .notify(NOTIFICATION_ID, notification(c?.let { "Online: ${it.name} (${it.via})" } ?: "Waiting for a computer to dial")) + } + } + return START_STICKY + } + + override fun onDestroy() { + scope.cancel() + Bridges.stopAll() + super.onDestroy() + } + + private fun notification(text: String): Notification { + val open = PendingIntent.getActivity(this, 0, Intent(this, MainActivity::class.java), PendingIntent.FLAG_IMMUTABLE) + return NotificationCompat.Builder(this, DModemApp.CHANNEL_MODEM) + .setSmallIcon(R.drawable.ic_modem) + .setContentTitle("Internet for serial computers") + .setContentText(text) + .setContentIntent(open) + .setOngoing(true) + .build() + } + + companion object { + private const val NOTIFICATION_ID = 3 + + /** on (or off again) as the settings are */ + fun update(context: Context) { + context.startForegroundService(Intent(context, HostService::class.java)) + } + } +} diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/SerialBridge.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/SerialBridge.kt index 83cc322..894a1b0 100644 --- a/app/src/main/java/com/neodesktop/dmodem/bridge/SerialBridge.kt +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/SerialBridge.kt @@ -40,6 +40,16 @@ class SerialBridge( private val hangUp: () -> Unit, @Volatile var hangUpOnClose: Boolean = true, ) { + /** + * clients given the internet instead of the modem: each its own PPP + * host ([PppHost]: the phone as the ISP, no call), when set + */ + @Volatile var host: (() -> com.neodesktop.dmodem.ppp.PppHost)? = null + @Volatile private var currentHost: com.neodesktop.dmodem.ppp.PppHost? = null + + /** the lines the client sees now: the modem's, or its PPP host's (carrier: its link up) */ + fun lines(): LineSignals = currentHost?.let { h -> LineSignals(ready = true, offhook = h.carrier, carrier = h.carrier) } ?: signals.value + private val _client = MutableStateFlow(null) /** who has the modem now, through which bridge */ val client: StateFlow = _client.asStateFlow() @@ -64,6 +74,10 @@ class SerialBridge( * speaks Telnet (and maybe RFC 2217) */ fun serve(p: Port, telnet: Telnet?) { + // the modem's DTE, or the client's own internet host + val h = host?.invoke() + currentHost = h + val dte: TerminalLink = h ?: this.dte val out = LinkedBlockingQueue() val listener = TerminalLink.Listener { data, n -> val b = data.copyOf(n) @@ -89,7 +103,7 @@ class SerialBridge( Thread({ while (on.get()) { // (null unless they changed, or the client has just asked for RFC 2217) - t.modemState(signals.value)?.let { out.put(it) } + t.modemState(lines())?.let { out.put(it) } try { Thread.sleep(100) } catch (_: InterruptedException) { break } } }, "bridge-lines-${p.via}").apply { isDaemon = true; start() } @@ -120,12 +134,19 @@ class SerialBridge( _client.value = null } } - if (hangUpOnClose) dropDtr() + if (h != null) { + // (its link over with it, whatever the setting) + currentHost = null + h.close() + } else if (hangUpOnClose) { + dropDtr() + } } } /** DTR off: the call over (as AT&D2 has it) */ fun dropDtr() { + currentHost?.let { it.hangUp(); return } val s = signals.value if (s.offhook || s.carrier) Thread({ hangUp() }, "bridge-hangup").apply { isDaemon = true; start() } } diff --git a/app/src/main/java/com/neodesktop/dmodem/bridge/UsbBridge.kt b/app/src/main/java/com/neodesktop/dmodem/bridge/UsbBridge.kt index a8f9896..7bd126b 100644 --- a/app/src/main/java/com/neodesktop/dmodem/bridge/UsbBridge.kt +++ b/app/src/main/java/com/neodesktop/dmodem/bridge/UsbBridge.kt @@ -114,7 +114,7 @@ class UsbPortLink( var computerDtr: Boolean? = null runCatching { port.setRTS(true) } while (open) { - val s = signals.value + val s = bridge.lines() val carrier = if (carrierOnDtr) s.carrier else s.ready if (carrier != lastCarrier) { runCatching { port.setDTR(carrier) } diff --git a/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt b/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt index 3696b3d..51ae916 100644 --- a/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt +++ b/app/src/main/java/com/neodesktop/dmodem/modem/ModemService.kt @@ -97,6 +97,8 @@ class ModemService : Service() { // the TCP and Bluetooth bridges, as their settings are (now and as they change), while the modem is on scope.launch { combine(BridgeSettingsStore(this@ModemService).settings, ModemState.run) { b, r -> b to r }.collect { (b, r) -> + // (in internet mode they're the host service's, the modem not needed) + if (b.internet) return@collect if (r == ModemState.Run.RUNNING) Bridges.apply(this@ModemService, b) else if (r == ModemState.Run.STOPPED) Bridges.stopAll() } @@ -224,7 +226,7 @@ class ModemService : Service() { ModemState.setRun(ModemState.Run.STOPPING) stopNative() } - Bridges.stopAll() + if (!runBlocking { BridgeSettingsStore(this@ModemService).current() }.internet) Bridges.stopAll() unwatchNetwork() releaseLocks() restartPending = false diff --git a/app/src/main/java/com/neodesktop/dmodem/ppp/Ip.kt b/app/src/main/java/com/neodesktop/dmodem/ppp/Ip.kt index 82ddab3..4996fc8 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ppp/Ip.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ppp/Ip.kt @@ -49,4 +49,73 @@ object Ip { val ul = ((p[ihl + 4].toInt() and 0xff) shl 8) or (p[ihl + 5].toInt() and 0xff) return p.copyOfRange(ihl + 8, ihl + ul) } + + const val TCP = 6 + const val UDP = 17 + const val ICMP = 1 + + const val FIN = 0x01 + const val SYN = 0x02 + const val RST = 0x04 + const val PSH = 0x08 + const val ACK = 0x10 + + /** the sum of the pseudo header's (addresses, protocol, length) for a TCP or UDP checksum */ + private fun pseudo(src: ByteArray, dst: ByteArray, proto: Int, len: Int): Long { + var s = proto.toLong() + len + for (k in 0 until 4 step 2) { + s += ((src[k].toInt() and 0xff) shl 8) or (src[k + 1].toInt() and 0xff) + s += ((dst[k].toInt() and 0xff) shl 8) or (dst[k + 1].toInt() and 0xff) + } + return s + } + + /** an IPv4 header around [body] (protocol [proto]), its checksum set */ + fun ipv4(src: ByteArray, dst: ByteArray, proto: Int, body: ByteArray, id: Int = 0, ttl: Int = 64): ByteArray { + val p = ByteArray(20 + body.size) + p[0] = 0x45 + p[2] = (p.size ushr 8).toByte(); p[3] = p.size.toByte() + p[4] = (id ushr 8).toByte(); p[5] = id.toByte() + p[6] = 0x40 // don't fragment + p[8] = ttl.toByte() + p[9] = proto.toByte() + 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() + System.arraycopy(body, 0, p, 20, body.size) + return p + } + + /** a TCP segment in an IPv4 packet */ + fun tcp( + src: ByteArray, dst: ByteArray, sport: Int, dport: Int, seq: Int, ack: Int, flags: Int, window: Int, + payload: ByteArray = ByteArray(0), mss: Int = 0, + ): ByteArray { + val opt = if (mss > 0) byteArrayOf(2, 4, (mss ushr 8).toByte(), mss.toByte()) else ByteArray(0) + val hl = 20 + opt.size + val t = ByteArray(hl + payload.size) + t[0] = (sport ushr 8).toByte(); t[1] = sport.toByte() + t[2] = (dport ushr 8).toByte(); t[3] = dport.toByte() + for (k in 0 until 4) t[4 + k] = (seq ushr (24 - 8 * k)).toByte() + for (k in 0 until 4) t[8 + k] = (ack ushr (24 - 8 * k)).toByte() + t[12] = ((hl / 4) shl 4).toByte() + t[13] = flags.toByte() + t[14] = (window ushr 8).toByte(); t[15] = window.toByte() + System.arraycopy(opt, 0, t, 20, opt.size) + System.arraycopy(payload, 0, t, hl, payload.size) + val c = checksum(t, 0, t.size, pseudo(src, dst, TCP, t.size)) + t[16] = (c ushr 8).toByte(); t[17] = c.toByte() + return ipv4(src, dst, TCP, t) + } + + /** an ICMP message (its checksum set) in an IPv4 packet */ + fun icmp(src: ByteArray, dst: ByteArray, type: Int, code: Int, rest: ByteArray): ByteArray { + val m = ByteArray(4 + rest.size) + m[0] = type.toByte(); m[1] = code.toByte() + System.arraycopy(rest, 0, m, 4, rest.size) + val c = checksum(m, 0, m.size) + m[2] = (c ushr 8).toByte(); m[3] = c.toByte() + return ipv4(src, dst, ICMP, m) + } } diff --git a/app/src/main/java/com/neodesktop/dmodem/ppp/NatStack.kt b/app/src/main/java/com/neodesktop/dmodem/ppp/NatStack.kt new file mode 100644 index 0000000..6fe1c42 --- /dev/null +++ b/app/src/main/java/com/neodesktop/dmodem/ppp/NatStack.kt @@ -0,0 +1,405 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.ppp + +import java.io.IOException +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.Socket +import java.net.SocketTimeoutException +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.Executors +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import kotlin.random.Random + +/** + * A computer's IPv4 on the phone's own network, without a VPN or root, as + * slirp did it for dial-up shells: each TCP connection the computer opens + * is the phone's own socket to the same place (the computer's side of it + * kept here: the handshake, its sequence numbers, retransmission, its + * window, the ends), each UDP flow the phone's own datagram socket, DNS to + * the gateway's address the phone's DNS servers' answer, a ping answered + * when the phone can reach the host. [toClient] gets the packets for the + * computer. + */ +class NatStack( + private val toClient: (ByteArray) -> Unit, + /** this side's address: the computer's gateway, and its DNS server */ + private val gateway: InetAddress, + /** the phone's DNS servers, asked for each query */ + private val dnsServers: () -> List, + /** a socket to where the computer connects (the phone's network's) */ + private val connect: (InetSocketAddress) -> Socket = { a -> Socket().apply { connect(a, 15_000) } }, + private val log: (String) -> Unit = {}, + /** the DNS servers' port (53; the tests' own) */ + private val dnsPort: Int = 53, +) { + private val tcp = ConcurrentHashMap() + private val udp = ConcurrentHashMap() + private val workers = Executors.newCachedThreadPool { r -> Thread(r, "nat").apply { isDaemon = true } } + private val timer = Executors.newSingleThreadScheduledExecutor { r -> Thread(r, "nat-timer").apply { isDaemon = true } } + @Volatile private var closed = false + private val gw = gateway.address + + /** the MSS for segments to the computer (its link's MTU less the headers) */ + @Volatile var mss = 1460 + + init { + timer.scheduleWithFixedDelay({ tick() }, 250, 250, TimeUnit.MILLISECONDS) + } + + fun close() { + closed = true + tcp.values.forEach { it.abort() } + udp.values.forEach { it.close() } + tcp.clear(); udp.clear() + timer.shutdownNow() + workers.shutdownNow() + } + + val connections: Int get() = tcp.size + udp.size + + private fun send(p: ByteArray) { + if (!closed) runCatching { toClient(p) } + } + + /** an IPv4 packet from the computer */ + fun input(p: ByteArray) { + if (closed || p.size < 20 || (p[0].toInt() ushr 4) != 4) return + val ihl = (p[0].toInt() and 0x0f) * 4 + val total = minOf(p.size, ((p[2].toInt() and 0xff) shl 8) or (p[3].toInt() and 0xff)) + // (fragments: none on a link this slow; dropped) + val frag = ((p[6].toInt() and 0x3f) shl 8) or (p[7].toInt() and 0xff) + if (frag != 0 || total < ihl) return + val src = p.copyOfRange(12, 16) + val dst = p.copyOfRange(16, 20) + val body = p.copyOfRange(ihl, total) + when (p[9].toInt() and 0xff) { + Ip.TCP -> tcpIn(src, dst, body) + Ip.UDP -> udpIn(src, dst, body) + Ip.ICMP -> icmpIn(src, dst, body) + } + } + + private fun u16(b: ByteArray, i: Int) = ((b[i].toInt() and 0xff) shl 8) or (b[i + 1].toInt() and 0xff) + private fun u32(b: ByteArray, i: Int) = (u16(b, i) shl 16) or u16(b, i + 2) + private fun addr(b: ByteArray) = InetAddress.getByAddress(b) + + // ------------------------------------------------------------------ + // UDP + + private inner class Udp(val key: String, val client: ByteArray, val cport: Int, val dst: ByteArray, val dport: Int, val dns: Boolean) { + val socket = DatagramSocket() + @Volatile var last = System.currentTimeMillis() + + init { + socket.soTimeout = 1000 + workers.execute { + val buf = ByteArray(65535) + while (!closed && !socket.isClosed) { + val d = DatagramPacket(buf, buf.size) + try { socket.receive(d) } catch (_: SocketTimeoutException) { continue } catch (_: IOException) { break } + last = System.currentTimeMillis() + // (an answer from where it was sent; DNS's as the gateway's) + val from = if (dns) gw else d.address.address + val fport = if (dns) 53 else d.port + this@NatStack.send(Ip.udp(from, client, fport, cport, buf.copyOf(d.length))) + } + } + } + + /** the computer's datagram on (a DNS query: to the phone's DNS server) */ + fun forward(payload: ByteArray) { + last = System.currentTimeMillis() + val to = if (dns) { + // the phone's DNS servers (one, the first that's there) + val s = dnsServers().firstOrNull() ?: InetAddress.getByName("1.1.1.1") + InetSocketAddress(s, dnsPort) + } else InetSocketAddress(addr(dst), dport) + runCatching { socket.send(DatagramPacket(payload, payload.size, to)) } + } + + fun close() = runCatching { socket.close() } + } + + private fun udpIn(src: ByteArray, dst: ByteArray, b: ByteArray) { + if (b.size < 8) return + val sport = u16(b, 0) + val dport = u16(b, 2) + val len = minOf(b.size, u16(b, 4)) + val payload = b.copyOfRange(8, len) + val toGw = dst.contentEquals(gw) + if (toGw && dport != 53) return + val key = "${addr(src).hostAddress}:$sport>${addr(dst).hostAddress}:$dport" + val u = udp[key] ?: try { + Udp(key, src, sport, dst, dport, toGw).also { udp[key] = it } + } catch (e: IOException) { + return + } + workers.execute { u.forward(payload) } + } + + // ------------------------------------------------------------------ + // ICMP: echo + + private fun icmpIn(src: ByteArray, dst: ByteArray, b: ByteArray) { + if (b.size < 8 || b[0].toInt() != 8) return + val rest = b.copyOfRange(4, b.size) + if (dst.contentEquals(gw)) { + send(Ip.icmp(dst, src, 0, 0, rest)) + return + } + workers.execute { + val ok = runCatching { addr(dst).isReachable(3000) }.getOrDefault(false) + if (ok) send(Ip.icmp(dst, src, 0, 0, rest)) + } + } + + // ------------------------------------------------------------------ + // TCP + + private enum class St { CONNECTING, SYN_RCVD, ESTABLISHED, CLOSING, CLOSED } + + private inner class Tcp(val key: String, val client: ByteArray, val cport: Int, val dst: ByteArray, val dport: Int, clientIsn: Int, val peerMss: Int) { + @Volatile var st = St.CONNECTING + val iss = Random.nextInt() + var sndUna = iss // the computer's acknowledged up to + var sndNxt = iss // ours sent up to + var rcvNxt = clientIsn + 1 // the computer's expected next + @Volatile var wnd = 8192 // the computer's window + var socket: Socket? = null + val unacked = java.io.ByteArrayOutputStream() + var finSent = false // our FIN out (at sndNxt - 1) + var finAcked = false + var clientFin = false + var lastSent = 0L + var rto = 1000L + var lastHeard = System.currentTimeMillis() + val toSocket = LinkedBlockingQueue() + val lock = Object() + + fun seg(flags: Int, seq: Int, data: ByteArray = ByteArray(0), mssOpt: Int = 0) = + send(Ip.tcp(dst, client, dport, cport, seq, rcvNxt, flags, window(), data, mssOpt)) + + fun window(): Int = (65535 - toSocket.sumOf { it.size }).coerceIn(0, 65535) + + fun synAck() { + seg(Ip.SYN or Ip.ACK, iss, mssOpt = mss) + lastSent = System.currentTimeMillis() + } + + fun abort() { + st = St.CLOSED + runCatching { socket?.close() } + toSocket.add(ByteArray(0)) + synchronized(lock) { lock.notifyAll() } + tcp.remove(key) + } + + fun reset() { + seg(Ip.RST or Ip.ACK, sndNxt) + abort() + } + + /** the socket's octets to the computer, as its window lets them */ + fun reader(s: Socket) { + val buf = ByteArray(maxOf(536, minOf(peerMss, mss))) + val input = s.getInputStream() + while (st != St.CLOSED) { + synchronized(lock) { + // (the computer's window full: until it acknowledges) + while (st != St.CLOSED && (sndNxt - sndUna) >= wnd.coerceAtLeast(1)) lock.wait(500) + } + if (st == St.CLOSED) return + val room = minOf(buf.size, (wnd - (sndNxt - sndUna)).coerceAtLeast(1)) + val n = try { input.read(buf, 0, room) } catch (_: IOException) { -1 } + synchronized(lock) { + if (st == St.CLOSED) return + if (n < 0) { + // the far end done: our FIN + finSent = true + seg(Ip.FIN or Ip.ACK, sndNxt) + sndNxt += 1 + lastSent = System.currentTimeMillis() + return + } + val d = buf.copyOf(n) + seg(Ip.PSH or Ip.ACK, sndNxt, d) + unacked.write(d) + sndNxt += n + lastSent = System.currentTimeMillis() + } + } + } + + /** the computer's octets to the socket, in order, by their own thread (the socket may be slow) */ + fun writer(s: Socket) { + val out = s.getOutputStream() + while (st != St.CLOSED) { + val d = toSocket.take() + if (d.isEmpty()) { + // its FIN (or the end): the socket's output shut + if (clientFin) runCatching { s.shutdownOutput() } + return + } + try { out.write(d); out.flush() } catch (_: IOException) { synchronized(lock) { reset() }; return } + } + } + + /** what's unacknowledged again (from sndUna, as much as the window takes); the FIN if it's due */ + fun retransmit() { + val all = unacked.toByteArray() + var off = 0 + val chunk = maxOf(536, minOf(peerMss, mss)) + while (off < all.size && off < wnd.coerceAtLeast(chunk)) { + val n = minOf(chunk, all.size - off) + seg(Ip.PSH or Ip.ACK, sndUna + off, all.copyOfRange(off, off + n)) + off += n + } + if (finSent && !finAcked && all.isEmpty()) seg(Ip.FIN or Ip.ACK, sndNxt - 1) + lastSent = System.currentTimeMillis() + } + } + + private fun tcpIn(src: ByteArray, dst: ByteArray, b: ByteArray) { + if (b.size < 20) return + val sport = u16(b, 0) + val dport = u16(b, 2) + val seq = u32(b, 4) + val ack = u32(b, 8) + val off = ((b[12].toInt() and 0xff) ushr 4) * 4 + val flags = b[13].toInt() and 0x3f + val win = u16(b, 14) + if (off < 20 || off > b.size) return + val data = b.copyOfRange(off, b.size) + val key = "${addr(src).hostAddress}:$sport>${addr(dst).hostAddress}:$dport" + var c = tcp[key] + + if (flags and Ip.RST != 0) { c?.abort(); return } + if (c == null) { + if (flags and Ip.SYN == 0 || flags and Ip.ACK != 0) { + // not a connection of ours: reset + if (flags and Ip.ACK != 0) send(Ip.tcp(dst, src, dport, sport, ack, 0, Ip.RST, 0)) + else send(Ip.tcp(dst, src, dport, sport, 0, seq + data.size + 1, Ip.RST or Ip.ACK, 0)) + return + } + // a SYN: its MSS, and the phone's socket to there + var peerMss = 536 + var i = 20 + while (i < off) { + val kind = b[i].toInt() and 0xff + if (kind == 0) break + if (kind == 1) { i++; continue } + if (i + 1 >= off) break + val l = b[i + 1].toInt() and 0xff + if (kind == 2 && l == 4) peerMss = u16(b, i + 2) + i += maxOf(l, 2) + } + if (dst.contentEquals(gw)) { + send(Ip.tcp(dst, src, dport, sport, 0, seq + 1, Ip.RST or Ip.ACK, 0)) + return + } + val t = Tcp(key, src, sport, dst, dport, seq, peerMss) + t.wnd = win + tcp[key] = t + c = t + workers.execute { + val s = try { connect(InetSocketAddress(addr(dst), dport)) } catch (e: IOException) { null } + synchronized(t.lock) { + if (t.st == St.CLOSED) { runCatching { s?.close() }; return@execute } + if (s == null) { + // (refused or unreachable: the computer told, as the host would) + send(Ip.tcp(dst, src, dport, sport, 0, t.rcvNxt, Ip.RST or Ip.ACK, 0)) + t.abort() + return@execute + } + t.socket = s + t.st = St.SYN_RCVD + t.sndNxt = t.iss + 1 + t.sndUna = t.iss + t.synAck() + } + } + return + } + + synchronized(c.lock) { + c.lastHeard = System.currentTimeMillis() + if (flags and Ip.SYN != 0) { + // its SYN again (our SYN-ACK lost) + if (c.st == St.SYN_RCVD) c.synAck() + return + } + if (flags and Ip.ACK != 0) { + if (c.st == St.SYN_RCVD && ack == c.iss + 1) { + c.st = St.ESTABLISHED + c.sndUna = ack + val s = c.socket!! + workers.execute { c.writer(s) } + workers.execute { c.reader(s) } + } + // what it has now: off the unacknowledged + val done = ack - c.sndUna + if (done > 0 && ack - c.sndNxt <= 0) { + val all = c.unacked.toByteArray() + val dataDone = minOf(done, all.size) + c.unacked.reset() + c.unacked.write(all, dataDone, all.size - dataDone) + c.sndUna = ack + c.rto = 1000 + if (c.finSent && ack == c.sndNxt) c.finAcked = true + } + c.wnd = win + c.lock.notifyAll() + } + if (c.st != St.ESTABLISHED && c.st != St.CLOSING) return + // its octets, in order only (the rest: our ACK again for it to resend) + if (data.isNotEmpty() || flags and Ip.FIN != 0) { + if (seq != c.rcvNxt) { + c.seg(Ip.ACK, c.sndNxt) + return + } + if (data.isNotEmpty()) { + c.toSocket.add(data) + c.rcvNxt += data.size + } + if (flags and Ip.FIN != 0) { + c.rcvNxt += 1 + c.clientFin = true + c.st = St.CLOSING + c.toSocket.add(ByteArray(0)) + } + c.seg(Ip.ACK, c.sndNxt) + } + // both ends done: gone + if (c.clientFin && c.finAcked) { + runCatching { c.socket?.close() } + c.st = St.CLOSED + tcp.remove(c.key) + } + } + } + + /** retransmissions due, and connections and flows long idle let go */ + private fun tick() { + val now = System.currentTimeMillis() + for (c in tcp.values) { + synchronized(c.lock) { + when { + c.st == St.SYN_RCVD && now - c.lastSent > c.rto -> { c.synAck(); c.rto = minOf(c.rto * 2, 8000) } + (c.unacked.size() > 0 || (c.finSent && !c.finAcked)) && now - c.lastSent > c.rto -> { + c.retransmit() + c.rto = minOf(c.rto * 2, 8000) + } + } + // (gone quiet for long, or a close never finished) + val idle = now - c.lastHeard + if (idle > 2 * 60 * 60_000L || (c.st == St.CLOSING && idle > 60_000) || (c.finSent && idle > 120_000)) c.abort() + } + } + for ((k, u) in udp) if (now - u.last > if (u.dns) 15_000 else 120_000) { u.close(); udp.remove(k) } + } +} diff --git a/app/src/main/java/com/neodesktop/dmodem/ppp/Ppp.kt b/app/src/main/java/com/neodesktop/dmodem/ppp/Ppp.kt index 5e7f831..6426e29 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ppp/Ppp.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ppp/Ppp.kt @@ -27,7 +27,12 @@ class Ppp( /** how long between retries, and how many before it gives up */ private val retryMs: Long = 3000, private val maxRetries: Int = 10, + /** the server's side instead (no login asked): its address, the peer's to give, the DNS server to name */ + private val server: Server? = null, ) { + /** what a server gives the peer */ + data class Server(val local: Inet4Address, val peer: Inet4Address, val dns: Inet4Address) + /** 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) @@ -81,6 +86,14 @@ class Ppp( private var askDns2 = true private var peerAddr: ByteArray? = null + init { + if (server != null) { + ourAddr = server.local.address + askDns1 = false + askDns2 = false + } + } + // counts @Volatile var bytesIn = 0L private set @@ -425,7 +438,7 @@ class Ppp( val code = p[0].toInt() and 0xff val id = p[1].toInt() and 0xff when (code) { - CONF_REQ -> { + CONF_REQ -> if (server != null) serverIpcpRequest(p, id) else { val o = options(p) ?: return val reject = o.filter { (t, d) -> t != 3 || d.size != 4 } if (reject.isNotEmpty()) { @@ -455,12 +468,38 @@ class Ppp( } } + /** + * a server's answer to the peer's request: other than its address and + * the DNS servers, rejected (compression, NBNS); the address and DNS + * not ours to give, Nak'd with ours; else Ack'd + */ + private fun serverIpcpRequest(p: ByteArray, id: Int) { + val s = server ?: return + val o = options(p) ?: return + val reject = o.filter { (t, d) -> t !in listOf(3, 129, 131) || d.size != 4 } + if (reject.isNotEmpty()) { + out(PROTO_IPCP, packet(CONF_REJ, id, opts(reject))) + return + } + val want = mapOf(3 to s.peer.address, 129 to s.dns.address, 131 to s.dns.address) + val nak = o.filter { (t, d) -> !d.contentEquals(want.getValue(t)) }.map { (t, _) -> t to want.getValue(t) } + if (nak.isNotEmpty()) { + out(PROTO_IPCP, packet(CONF_NAK, id, opts(nak))) + return + } + peerAddr = s.peer.address + dns1 = s.dns.address + out(PROTO_IPCP, packet(CONF_ACK, id, p.copyOfRange(4, len(p).coerceAtMost(p.size)))) + ipcpTheirAcked = true + ipcpMaybeUp() + } + 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 } + .map { InetAddress.getByAddress(it) as Inet4Address }.distinct() val cfg = IpConfig( InetAddress.getByAddress(ourAddr) as Inet4Address, peerAddr?.let { InetAddress.getByAddress(it) as Inet4Address }, diff --git a/app/src/main/java/com/neodesktop/dmodem/ppp/PppHost.kt b/app/src/main/java/com/neodesktop/dmodem/ppp/PppHost.kt new file mode 100644 index 0000000..d13831d --- /dev/null +++ b/app/src/main/java/com/neodesktop/dmodem/ppp/PppHost.kt @@ -0,0 +1,173 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.ppp + +import com.neodesktop.dmodem.terminal.TerminalLink +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import java.net.Inet4Address +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.Socket +import java.util.concurrent.CopyOnWriteArrayList + +/** + * The phone as a dial-up ISP for a computer on a serial line, no call + * made: to the computer a modem (AT commands answered OK, ATD answered + * CONNECT), Windows' direct cable connection's CLIENT answered + * CLIENTSERVER, or PPP straight away; then a PPP server ([Ppp] in its + * server role) giving it [peer] and the DNS at [local], its traffic on + * the phone's own network ([NatStack]). The PPP link over, NO CARRIER and + * commands again. + * + * A [TerminalLink], as the modem's DTE is: what the computer sends is + * written to it, what it says goes to its listeners. + */ +class PppHost( + private val dnsServers: () -> List, + private val connect: (InetSocketAddress) -> Socket = { a -> Socket().apply { connect(a, 15_000) } }, + private val log: (String) -> Unit = {}, + val local: Inet4Address = InetAddress.getByName("10.64.64.1") as Inet4Address, + val peer: Inet4Address = InetAddress.getByName("10.64.64.2") as Inet4Address, + /** what CONNECT says (the speed the computer's dialer shows) */ + private val connectSpeed: Int = 115200, + private val dnsPort: Int = 53, +) : TerminalLink { + private val listeners = CopyOnWriteArrayList() + private val _state = MutableStateFlow(TerminalLink.State.Open) + override val state: StateFlow = _state.asStateFlow() + + @Volatile private var ppp: Ppp? = null + @Volatile private var nat: NatStack? = null + private val line = StringBuilder() + private var echo = true + private var verbose = true + private val lock = Any() + + /** the PPP link up (the computer online: its DCD) */ + val carrier: Boolean get() = ppp != null + + private val _online = MutableStateFlow(false) + /** whether the computer has its address (the link up) */ + val online: StateFlow = _online.asStateFlow() + + override fun addListener(l: TerminalLink.Listener) { listeners.add(l) } + override fun removeListener(l: TerminalLink.Listener) { listeners.remove(l) } + + private fun say(b: ByteArray) { + for (l in listeners) l.onData(b, b.size) + } + + private fun say(s: String) = say(s.toByteArray(Charsets.ISO_8859_1)) + + private fun result(s: String) = say(if (verbose) "\r\n$s\r\n" else "$s\r") + + /** the computer's octets */ + override fun write(data: ByteArray, offset: Int, length: Int): Boolean { + synchronized(lock) { + ppp?.let { it.input(data, offset, length); return true } + for (i in offset until offset + length) { + val c = data[i].toInt() and 0xff + if (c == Hdlc.FLAG) { + // PPP with no dial first (a direct link): it starts now, with this frame + log("PPP from the computer: the link starts") + startPpp() + ppp?.input(data, i, offset + length - i) + return true + } + if (echo && c != '\n'.code) say(byteArrayOf(c.toByte())) + when (c) { + '\r'.code -> { + val l = line.toString().trim() + line.setLength(0) + command(l) + if (ppp != null) { + // (what came after the dial's CR is PPP's) + if (i + 1 < offset + length) ppp?.input(data, i + 1, offset + length - i - 1) + return true + } + } + '\n'.code -> {} + 8, 127 -> if (line.isNotEmpty()) line.setLength(line.length - 1) + else -> if (line.length < 256) line.append(c.toChar()) + } + } + } + return true + } + + private fun command(l: String) { + val u = l.uppercase() + when { + u.isEmpty() -> {} + // Windows' direct cable connection + u == "CLIENT" -> { say("CLIENTSERVER"); startPpp() } + !u.startsWith("AT") -> {} + else -> { + val cmd = u.substring(2).replace(" ", "") + if (cmd.contains("E0")) echo = false + if (cmd.contains("E1")) echo = true + if (cmd.contains("V0")) verbose = false + if (cmd.contains("V1")) verbose = true + if (cmd.startsWith("Z") || cmd.startsWith("&F")) { echo = true; verbose = true } + when { + // a dial: D not &D (DTR's setting), not in a + command + !cmd.contains('+') && Regex("(^|[^&A-Z])D").containsMatchIn(cmd) -> { + log("the computer dials: ${l.substring(2).trim()}") + result("CONNECT $connectSpeed") + startPpp() + } + cmd.startsWith("I") -> { result("D-Modem internet host"); result("OK") } + cmd.startsWith("A") && cmd.length == 1 -> { result("CONNECT $connectSpeed"); startPpp() } + else -> result("OK") + } + } + } + } + + private fun startPpp() { + if (ppp != null) return + lateinit var n: NatStack + val p = Ppp( + send = { b -> say(b) }, + events = object : Ppp.Events { + override fun up(config: Ppp.IpConfig) { + n.mss = config.mtu - 40 + log("the computer is online: ${peer.hostAddress}") + _online.value = true + } + override fun ip(packet: ByteArray) = n.input(packet) + override fun down(reason: String) { + log("the computer's link down: $reason") + synchronized(lock) { + n.close() + if (ppp != null) { + ppp = null + nat = null + _online.value = false + result("NO CARRIER") + } + } + } + override fun log(line: String) = this@PppHost.log("ppp: $line") + }, + server = Ppp.Server(local, peer, local), + ) + n = NatStack({ pk -> p.sendIp(pk) }, local, dnsServers, connect, log, dnsPort) + ppp = p + nat = n + p.start() + } + + /** the computer's DTR dropped (or the line gone): the link over */ + fun hangUp() { + ppp?.stop("the computer hung up") + } + + override fun close() { + hangUp() + nat?.close() + _state.value = TerminalLink.State.Closed(null) + } +} diff --git a/app/src/main/java/com/neodesktop/dmodem/settings/BridgeSettings.kt b/app/src/main/java/com/neodesktop/dmodem/settings/BridgeSettings.kt index c6cbcbe..f886739 100644 --- a/app/src/main/java/com/neodesktop/dmodem/settings/BridgeSettings.kt +++ b/app/src/main/java/com/neodesktop/dmodem/settings/BridgeSettings.kt @@ -40,7 +40,12 @@ data class BridgeSettings( val usbDtrHangsUp: Boolean = true, /** the phone's own USB port as a serial port to a computer (root) */ val usbGadget: Boolean = false, -) + /** clients get the internet (the phone as their dial-up ISP, PPP, no call) instead of the modem */ + val internet: Boolean = false, +) { + /** any way for a client to come */ + val anyOn: Boolean get() = tcp || bluetooth || usb || usbGadget +} private val Context.bridgeStore: DataStore by preferencesDataStore("bridges") @@ -60,6 +65,7 @@ class BridgeSettingsStore(private val context: Context) { val usbCarrierOnDtr = booleanPreferencesKey("usb_carrier_on_dtr") val usbDtrHangsUp = booleanPreferencesKey("usb_dtr_hangs_up") val usbGadget = booleanPreferencesKey("usb_gadget") + val internet = booleanPreferencesKey("internet") } val settings: Flow = context.bridgeStore.data.map { from(it) } @@ -81,6 +87,7 @@ class BridgeSettingsStore(private val context: Context) { usbCarrierOnDtr = p[K.usbCarrierOnDtr] ?: d.usbCarrierOnDtr, usbDtrHangsUp = p[K.usbDtrHangsUp] ?: d.usbDtrHangsUp, usbGadget = p[K.usbGadget] ?: d.usbGadget, + internet = p[K.internet] ?: d.internet, ) } @@ -111,6 +118,7 @@ class BridgeSettingsStore(private val context: Context) { p[K.usbCarrierOnDtr] = s.usbCarrierOnDtr p[K.usbDtrHangsUp] = s.usbDtrHangsUp p[K.usbGadget] = s.usbGadget + p[K.internet] = s.internet } } } diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/BridgeSection.kt b/app/src/main/java/com/neodesktop/dmodem/ui/BridgeSection.kt index a13226c..df27ddd 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/BridgeSection.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/BridgeSection.kt @@ -53,7 +53,12 @@ fun BridgeSection() { val current by store.settings.collectAsStateWithLifecycle(initialValue = null) val s = current ?: return fun change(f: (BridgeSettings) -> BridgeSettings) { - scope.launch { store.update(f) } + scope.launch { + store.update(f) + // (internet mode: its own service, on or off again as the settings now are) + val now = store.current() + if (now.internet && now.anyOn) runCatching { com.neodesktop.dmodem.bridge.HostService.update(context) } + } } val run by ModemState.run.collectAsStateWithLifecycle() val tcpState by Bridges.tcpState.collectAsStateWithLifecycle() @@ -73,10 +78,18 @@ fun BridgeSection() { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { Text("Serial port for other devices", style = MaterialTheme.typography.titleMedium) Text( - "Programs and computers use the modem as if on a serial cable, one at a time, while the modem is on." + - if (run == ModemState.Run.STOPPED) " (The modem is off now.)" else "", + if (s.internet) { + "Computers dial the phone as if it were their ISP's modem (ATDT anything, or a direct cable " + + "connection) and get the internet through it: PPP, no call made, no SIP account needed." + } else { + "Programs and computers use the modem as if on a serial cable, one at a time, while the modem is on." + + if (run == ModemState.Run.STOPPED) " (The modem is off now.)" else "" + }, style = MaterialTheme.typography.bodySmall, ) + Text("Clients get", style = MaterialTheme.typography.bodyMedium) + Choice("The modem (calls over SIP)", !s.internet) { change { it.copy(internet = false) } } + Choice("The internet (the phone is their dial-up ISP)", s.internet) { change { it.copy(internet = true) } } client?.let { c -> Row(verticalAlignment = Alignment.CenterVertically) { Text("In use: ${c.name} (${c.via})", Modifier.weight(1f), style = MaterialTheme.typography.bodyMedium) diff --git a/app/src/main/java/com/neodesktop/dmodem/ui/MainActivity.kt b/app/src/main/java/com/neodesktop/dmodem/ui/MainActivity.kt index 9f63a66..82ede08 100644 --- a/app/src/main/java/com/neodesktop/dmodem/ui/MainActivity.kt +++ b/app/src/main/java/com/neodesktop/dmodem/ui/MainActivity.kt @@ -27,6 +27,8 @@ import androidx.compose.runtime.LaunchedEffect import androidx.activity.SystemBarStyle import android.app.UiModeManager import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.lifecycleScope +import kotlinx.coroutines.launch import com.neodesktop.dmodem.settings.AppearanceStore import com.neodesktop.dmodem.settings.DarkMode import androidx.compose.runtime.getValue @@ -54,6 +56,11 @@ class MainActivity : ComponentActivity() { ) { askNotifications.launch(Manifest.permission.POST_NOTIFICATIONS) } + // the internet host's service, if it was on (the app in the foreground now: it may start) + lifecycleScope.launch { + val b = com.neodesktop.dmodem.settings.BridgeSettingsStore(applicationContext).current() + if (b.internet && b.anyOn) runCatching { com.neodesktop.dmodem.bridge.HostService.update(applicationContext) } + } val appearanceStore = AppearanceStore(applicationContext) setContent { val appearance by appearanceStore.appearance.collectAsStateWithLifecycle(initialValue = null) diff --git a/app/src/test/java/com/neodesktop/dmodem/bridge/InternetHostTest.kt b/app/src/test/java/com/neodesktop/dmodem/bridge/InternetHostTest.kt new file mode 100644 index 0000000..9c0d37f --- /dev/null +++ b/app/src/test/java/com/neodesktop/dmodem/bridge/InternetHostTest.kt @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.bridge + +import com.neodesktop.dmodem.ppp.Ip +import com.neodesktop.dmodem.ppp.Ppp +import com.neodesktop.dmodem.ppp.PppHost +import com.neodesktop.dmodem.terminal.TerminalLink +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.ServerSocket +import java.net.Socket +import java.util.concurrent.ArrayBlockingQueue +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +/** + * The bridges in internet mode: a computer on the TCP bridge dials, gets + * PPP from the phone (no modem touched) and a TCP connection through to + * a server on this host; its DTR dropped (RFC 2217) ends the link. + */ +class InternetHostTest { + private val closers = ArrayList<() -> Unit>() + + @After + fun tearDown() = closers.forEach { runCatching { it() } } + + /** a modem that mustn't be used */ + private class Untouched : TerminalLink { + override val state: StateFlow = MutableStateFlow(TerminalLink.State.Open) + val writes = AtomicInteger() + override fun addListener(l: TerminalLink.Listener) {} + override fun removeListener(l: TerminalLink.Listener) {} + override fun write(data: ByteArray, offset: Int, length: Int): Boolean { writes.incrementAndGet(); return true } + } + + @Test + fun aComputerOnTheTcpBridgeGetsTheInternet() { + val modem = Untouched() + val hangUps = AtomicInteger() + val serial = SerialBridge(modem, MutableStateFlow(LineSignals(ready = true)), { hangUps.incrementAndGet() }) + serial.host = { PppHost({ listOf(InetAddress.getLoopbackAddress()) }) } + val tcp = TcpBridge(serial, 0, telnet = false) + assertTrue(tcp.start()) + closers.add { tcp.stop() } + + // the web server the computer reaches + val web = ServerSocket(0, 1, InetAddress.getLoopbackAddress()) + closers.add { web.close() } + Thread { + val s = web.accept() + val req = ByteArray(64) + val n = s.getInputStream().read(req) + s.getOutputStream().write("HTTP/1.0 200 OK\r\n\r\nhello, ${String(req, 0, n).substringBefore(' ')}".toByteArray()) + s.close() + }.start() + + // the computer: its serial port is the socket + val sock = Socket() + sock.connect(InetSocketAddress(InetAddress.getLoopbackAddress(), tcp.localPort)) + closers.add { sock.close() } + val out = sock.getOutputStream() + val inp = sock.getInputStream() + out.write("ATZ\rATDT18005551000\r".toByteArray()) + val text = StringBuilder() + val buf = ByteArray(4096) + while (!text.contains("CONNECT")) { + val n = inp.read(buf) + text.append(String(buf, 0, n, Charsets.ISO_8859_1)) + } + assertTrue(text.toString(), text.contains("OK") && text.contains("CONNECT 115200")) + assertEquals("tcp", serial.client.value?.via) + + // its PPP, and a TCP connection to the web server through the phone + val up = ArrayBlockingQueue(1) + val packets = LinkedBlockingQueue() + val ppp = Ppp({ b -> synchronized(out) { out.write(b); out.flush() } }, events = object : Ppp.Events { + override fun up(config: Ppp.IpConfig) { up.add(config) } + override fun ip(packet: ByteArray) { packets.add(packet) } + override fun down(reason: String) {} + }, retryMs = 500) + Thread { + while (true) { val n = try { inp.read(buf) } catch (_: Exception) { -1 }; if (n < 0) break; ppp.input(buf, 0, n) } + }.apply { isDaemon = true; start() } + ppp.start() + val cfg = up.poll(10, TimeUnit.SECONDS) ?: throw AssertionError("no link") + assertEquals("10.64.64.2", cfg.address.hostAddress) + assertTrue(serial.lines().carrier) + + val me = cfg.address.address + val dst = byteArrayOf(127, 0, 0, 1) + var seq = 1000 + ppp.sendIp(Ip.tcp(me, dst, 41000, web.localPort, seq, 0, Ip.SYN, 8192, mss = 1460)) + seq++ + val synAck = packets.poll(10, TimeUnit.SECONDS)!! + var ack = java.nio.ByteBuffer.wrap(synAck, 24, 4).int + 1 + ppp.sendIp(Ip.tcp(me, dst, 41000, web.localPort, seq, ack, Ip.ACK, 8192)) + ppp.sendIp(Ip.tcp(me, dst, 41000, web.localPort, seq, ack, Ip.PSH or Ip.ACK, 8192, "GET / HTTP/1.0\r\n\r\n".toByteArray())) + seq += 18 + val page = StringBuilder() + while (!page.contains("hello")) { + val p = packets.poll(10, TimeUnit.SECONDS) ?: break + val d = p.copyOfRange(20 + ((p[32].toInt() and 0xff) ushr 4) * 4, p.size) + if (d.isNotEmpty()) { + page.append(String(d)) + ack += d.size + ppp.sendIp(Ip.tcp(me, dst, 41000, web.localPort, seq, ack, Ip.ACK, 8192)) + } + } + assertTrue(page.toString(), page.contains("200 OK") && page.contains("hello, GET")) + + // the computer hangs up: its link over, NO CARRIER; the modem never used + serial.dropDtr() + val end = System.currentTimeMillis() + 5000 + while (serial.lines().carrier && System.currentTimeMillis() < end) Thread.sleep(20) + assertTrue(!serial.lines().carrier) + assertEquals(0, modem.writes.get()) + assertEquals(0, hangUps.get()) + } +} diff --git a/app/src/test/java/com/neodesktop/dmodem/ppp/PppHostTest.kt b/app/src/test/java/com/neodesktop/dmodem/ppp/PppHostTest.kt new file mode 100644 index 0000000..1c79cfc --- /dev/null +++ b/app/src/test/java/com/neodesktop/dmodem/ppp/PppHostTest.kt @@ -0,0 +1,254 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +package com.neodesktop.dmodem.ppp + +import com.neodesktop.dmodem.terminal.TerminalLink +import org.junit.After +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test +import java.io.ByteArrayOutputStream +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.InetAddress +import java.net.ServerSocket +import java.util.concurrent.ArrayBlockingQueue +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.TimeUnit +import kotlin.random.Random + +/** + * The phone as a dial-up ISP for a serial computer ([PppHost]): the + * computer's dialer (AT, ATD, Windows' CLIENT, PPP straight away), our + * PPP client as the computer's, its address and DNS; TCP to a server on + * this host through the NAT (a segment lost on the way, retransmitted), + * UDP, DNS, a ping to the gateway. + */ +class PppHostTest { + private val closers = ArrayList<() -> Unit>() + + @After + fun tearDown() = closers.forEach { runCatching { it() } } + + /** the computer: what the host says (text, then PPP's frames to its client) */ + private inner class Computer(dnsPort: Int = 53) { + val fromHost = LinkedBlockingQueue() + val host = PppHost({ listOf(InetAddress.getLoopbackAddress()) }, dnsPort = dnsPort) + val packets = LinkedBlockingQueue() + val up = ArrayBlockingQueue(1) + lateinit var ppp: Ppp + @Volatile var pppOn = false + /** packets to the computer dropped, when this says so (a line losing one) */ + @Volatile var drop: (ByteArray) -> Boolean = { false } + + // (each way on its own thread, as a serial line's two ends are) + private val toHost = LinkedBlockingQueue() + private val toComputer = LinkedBlockingQueue() + + init { + closers.add { host.close() } + host.addListener(TerminalLink.Listener { d, n -> toComputer.add(d.copyOf(n)) }) + Thread { + while (true) { + val b = try { toComputer.take() } catch (_: InterruptedException) { break } + if (pppOn) ppp.input(b) else fromHost.add(b) + } + }.apply { isDaemon = true; start() } + Thread { + while (true) { + val b = try { toHost.take() } catch (_: InterruptedException) { break } + host.write(b) + } + }.apply { isDaemon = true; start() } + } + + fun type(s: String) { toHost.add(s.toByteArray()) } + + /** text from the host until [want] */ + fun expect(want: String): String { + val sb = StringBuilder() + val end = System.currentTimeMillis() + 5000 + while (!sb.contains(want) && System.currentTimeMillis() < end) { + val b = fromHost.poll(100, TimeUnit.MILLISECONDS) ?: continue + sb.append(String(b, Charsets.ISO_8859_1)) + } + assertTrue("\"$want\" in \"$sb\"", sb.contains(want)) + return sb.toString() + } + + /** the computer's PPP client started on the line */ + fun startPpp(): Ppp.IpConfig { + ppp = Ppp({ b -> toHost.add(b) }, events = object : Ppp.Events { + override fun up(config: Ppp.IpConfig) { up.add(config) } + override fun ip(packet: ByteArray) { if (!drop(packet)) packets.add(packet) } + override fun down(reason: String) {} + }, retryMs = 500) + pppOn = true + // (what came before PPP was there: its frames too) + while (true) { val b = fromHost.poll() ?: break; ppp.input(b) } + ppp.start() + return up.poll(10, TimeUnit.SECONDS) ?: throw AssertionError("no link") + } + } + + @Test + fun aDialerDialsAndGetsAnAddress() { + val c = Computer() + c.type("ATZ\r") + c.expect("OK") + c.type("AT&F E0 V1 &D2 S0=0\r") + c.expect("OK") + c.type("ATI\r") + c.expect("D-Modem internet host") + c.type("ATDT5551234\r") + c.expect("CONNECT 115200") + val cfg = c.startPpp() + assertEquals("10.64.64.2", cfg.address.hostAddress) + assertEquals(listOf("10.64.64.1"), cfg.dns.map { it.hostAddress }) + assertTrue(c.host.online.value) + // the computer hangs up (DTR): NO CARRIER, and commands again + c.pppOn = false + c.host.hangUp() + c.expect("NO CARRIER") + c.type("AT\r") + c.expect("OK") + } + + @Test + fun windowsDirectCableAndPppStraightAway() { + val c = Computer() + c.type("CLIENT") + c.type("\r") + c.expect("CLIENTSERVER") + assertEquals("10.64.64.2", c.startPpp().address.hostAddress) + // a computer whose PPP just starts (no dial): the host's PPP starts with its first frame + val d = Computer() + assertEquals("10.64.64.2", d.startPpp().address.hostAddress) + } + + /** a TCP connection by hand, from the computer's side */ + private class Tcp(val c: Computer, val dst: ByteArray, val dport: Int) { + val me = byteArrayOf(10, 64, 64, 2) + val sport = 40000 + Random.nextInt(1000) + var seq = Random.nextInt() + var ack = 0 + + fun seg(flags: Int, data: ByteArray = ByteArray(0), window: Int = 8192) = + c.ppp.sendIp(Ip.tcp(me, dst, sport, dport, seq, ack, flags, window, data, if (flags and Ip.SYN != 0) 1460 else 0)) + + fun next(): ByteArray = c.packets.poll(10, TimeUnit.SECONDS) ?: throw AssertionError("nothing came") + fun flags(p: ByteArray) = p[33].toInt() and 0xff + fun pseq(p: ByteArray) = java.nio.ByteBuffer.wrap(p, 24, 4).int + fun data(p: ByteArray): ByteArray = p.copyOfRange(20 + ((p[32].toInt() and 0xff) ushr 4) * 4, p.size) + + fun open() { + seg(Ip.SYN) + seq += 1 + val sa = next() + assertEquals(Ip.SYN or Ip.ACK, flags(sa)) + ack = pseq(sa) + 1 + seg(Ip.ACK) + } + } + + @Test + fun tcpThroughTheNat() { + val c = Computer() + c.type("ATD\r") + c.expect("CONNECT") + c.startPpp() + // a server on this host: "HELLO" back for what it's sent, then 200 KB, then it closes + val server = ServerSocket(0, 1, InetAddress.getLoopbackAddress()) + closers.add { server.close() } + val big = Random(9).nextBytes(200_000) + Thread { + val s = server.accept() + val buf = ByteArray(5) + var n = 0 + while (n < 5) n += s.getInputStream().read(buf, n, 5 - n) + s.getOutputStream().write(String(buf).uppercase().toByteArray() + big) + s.close() + }.start() + val t = Tcp(c, byteArrayOf(127, 0, 0, 1), server.localPort) + t.open() + t.seg(Ip.PSH or Ip.ACK, "hello".toByteArray()) + t.seq += 5 + // what comes, acknowledged; one segment lost on the way (the 4th), and sent again + val got = ByteArrayOutputStream() + var segments = 0 + var lost = false + var fin = false + while (!fin) { + val p = t.next() + val f = t.flags(p) + if (f and Ip.ACK != 0 && t.data(p).isEmpty() && f and Ip.FIN == 0) continue + segments++ + if (segments == 4 && !lost) { lost = true; continue } + if (t.pseq(p) != t.ack) { t.seg(Ip.ACK); continue } + val d = t.data(p) + got.write(d) + t.ack += d.size + if (f and Ip.FIN != 0) { t.ack += 1; fin = true } + t.seg(Ip.ACK) + } + val all = got.toByteArray() + assertEquals("HELLO", String(all, 0, 5)) + assertArrayEquals(big, all.copyOfRange(5, all.size)) + assertTrue(lost) + // our FIN, and the connection's gone + t.seg(Ip.FIN or Ip.ACK) + } + + @Test + fun aRefusedConnectionIsReset() { + val c = Computer() + c.type("ATD\r") + c.expect("CONNECT") + c.startPpp() + val closed = ServerSocket(0).let { val p = it.localPort; it.close(); p } + val t = Tcp(c, byteArrayOf(127, 0, 0, 1), closed) + t.seg(Ip.SYN) + val r = t.next() + assertTrue(t.flags(r) and Ip.RST != 0) + } + + @Test + fun udpDnsAndPing() { + // a "DNS server" on this host (its answer: the query back with "A") + val dns = DatagramSocket(0, InetAddress.getLoopbackAddress()) + closers.add { dns.close() } + Thread { + val d = DatagramPacket(ByteArray(512), 512) + dns.receive(d) + dns.send(DatagramPacket(d.data.copyOf(d.length) + "A".toByteArray(), d.length + 1, d.socketAddress)) + }.start() + val echo = DatagramSocket(0, InetAddress.getLoopbackAddress()) + closers.add { echo.close() } + Thread { + val d = DatagramPacket(ByteArray(512), 512) + echo.receive(d) + echo.send(DatagramPacket("echo:".toByteArray() + d.data.copyOf(d.length), d.length + 5, d.socketAddress)) + }.start() + val c = Computer(dnsPort = dns.localPort) + c.type("ATD\r") + c.expect("CONNECT") + c.startPpp() + val me = byteArrayOf(10, 64, 64, 2) + val gw = byteArrayOf(10, 64, 64, 1) + // DNS to the gateway: the phone's DNS server's answer, from the gateway + c.ppp.sendIp(Ip.udp(me, gw, 5353, 53, "query".toByteArray())) + val a = c.packets.poll(5, TimeUnit.SECONDS)!! + assertEquals("queryA", String(Ip.udpPayload(a))) + assertArrayEquals(gw, a.copyOfRange(12, 16)) + // UDP elsewhere: as it is + c.ppp.sendIp(Ip.udp(me, byteArrayOf(127, 0, 0, 1), 6000, echo.localPort, "hi".toByteArray())) + val e = c.packets.poll(5, TimeUnit.SECONDS)!! + assertEquals("echo:hi", String(Ip.udpPayload(e))) + // a ping to the gateway + c.ppp.sendIp(Ip.icmp(me, gw, 8, 0, byteArrayOf(0, 1, 0, 1) + "ping".toByteArray())) + val pong = c.packets.poll(5, TimeUnit.SECONDS)!! + assertEquals(0, pong[20].toInt()) + assertEquals("ping", String(pong, 28, 4)) + } +}