iOS: the line to another phone over Wi-Fi, found with Bonjour

shared (Kotlin/Native, iOS and Linux): FdDuplex (a socket: the engine's
line, a TCP connection; closing it wakes a blocked read), PosixTcpTransport
(calls taken on a port, polled so close() always ends it; host[:port] and
[IPv6]:port called within 5 s; no SIGPIPE: Linux's send flag, Apple's
socket option), and PeerHost: PeerLine on it from plain values for Swift
(no default arguments or flows there), its state as text. PosixPeerTest
(native): two phones over real TCP on the loopback, the modems socket
pairs: a call rung, answered and heard both ways, busy, the hang-up, a
wrong PIN turned away, nobody there.

DModemKit: ModemSession.onLine, the peer line's modem off hook to the
app (tested: a dial reaches it, its FAILED a NO CARRIER).

The app: the settings' line (a SIP account or another phone on Wi-Fi:
whom ATD calls, the port, the PIN, taking calls), phones found with
Bonjour (_dmodem._tcp, as the Android app's NSD offers them), this one
offered while it takes calls; Home's line its state and last failure.
And a start fixed: the modem's log while it started ended the
background audio (and now the line) before it was running.

The Swift and appleMain's Kotlin aren't built here (no Xcode); the
Kotlin is built and tested for Linux native.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0172Hejd12i4aYikYW9vgpZs
This commit is contained in:
Claude committed 2026-10-18 02:27:41 +00:00
1 parent 133d5acb61
commit befcd0d5ef
12 files changed
+872 -48

No files matched your search

@@ -0,0 +1,27 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.peer
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.IntVar
import kotlinx.cinterop.alloc
import kotlinx.cinterop.convert
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.ptr
import kotlinx.cinterop.sizeOf
import kotlinx.cinterop.value
import platform.posix.SOL_SOCKET
import platform.posix.SO_NOSIGPIPE
import platform.posix.setsockopt
/** (Apple's: the socket's own option, no SIGPIPE for a connection gone) */
@OptIn(ExperimentalForeignApi::class)
internal actual fun noSigpipe(fd: Int) {
memScoped {
val one = alloc<IntVar>()
one.value = 1
setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, one.ptr, sizeOf<IntVar>().convert())
}
}
internal actual val SEND_FLAGS: Int = 0
@@ -0,0 +1,10 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.peer
import platform.posix.MSG_NOSIGNAL
/** (Linux: send()'s flag, no SIGPIPE for a connection gone) */
internal actual fun noSigpipe(fd: Int) {}
internal actual val SEND_FLAGS: Int = MSG_NOSIGNAL
@@ -0,0 +1,64 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.peer
/**
* The line to another phone over Wi-Fi as the iOS app's Swift has it:
* [PeerLine] on [PosixTcpTransport], made from plain values (Swift has
* none of Kotlin's default arguments, nor its flows: the state as text and
* flags, asked for when wanted).
*/
class PeerHost(
/** the port calls come in on (0: the system's, for the tests) */
port: Int,
/** the phone ATD calls when its number isn't an address (host[:port]) */
private val callTo: String,
/** the PIN between the two (empty: none) */
pin: String,
/** to the engine: RING, CANCEL, ANSWERED, FAILED <code>, DROPPED */
events: (String) -> Unit,
log: (String) -> Unit,
ringMs: Long = 3000,
) {
val transport = PosixTcpTransport(port)
val line = PeerLine(
transport,
events = events,
target = { dial -> PeerLine.wifiTarget(dial, callTo) },
log = log,
ringMs = ringMs,
pin = pin,
)
/** the line started, taking calls if [listen]: null, or why it can't take them (it can still call) */
fun start(listen: Boolean): String? = try {
line.start(listen)
null
} catch (e: Exception) {
line.start(false)
"can't take calls: ${e.message ?: e}"
}
fun stop() = line.stop()
/** the modem off hook: its line (the engine's socket), dialling [dial] if [caller] */
fun lineStarted(caller: Boolean, dial: String, fd: Int) = line.lineStarted(caller, dial, FdDuplex(fd, "modem"))
/** the port it takes calls on (for Bonjour) */
val localPort: Int get() = transport.localPort
/** what the line is doing, for the user (the Android app's words) */
val stateText: String
get() = when (val st = line.state.value) {
PeerLine.State.Off -> "Starts with the modem"
is PeerLine.State.Ready -> if (st.listening) "Waiting for the other phone's calls" else "Ready to call"
is PeerLine.State.Ringing -> "Ringing: ${st.from} calls"
is PeerLine.State.Calling -> "Calling ${st.to}…"
is PeerLine.State.Connected -> "On a call with ${st.with}"
}
val connected: Boolean get() = line.state.value is PeerLine.State.Connected
/** what went wrong last (a call that failed), or null */
val lastError: String? get() = line.lastError.value
}
@@ -0,0 +1,287 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.peer
import com.neodesktop.dmodem.io.IOException
import com.neodesktop.dmodem.io.Sink
import com.neodesktop.dmodem.io.Source
import com.neodesktop.dmodem.io.background
import kotlinx.atomicfu.atomic
import kotlinx.cinterop.ByteVar
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.CPointerVar
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.IntVar
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.alloc
import kotlinx.cinterop.allocArray
import kotlinx.cinterop.convert
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.pointed
import kotlinx.cinterop.ptr
import kotlinx.cinterop.reinterpret
import kotlinx.cinterop.sizeOf
import kotlinx.cinterop.toKString
import kotlinx.cinterop.usePinned
import kotlinx.cinterop.value
import platform.posix.AF_INET
import platform.posix.AF_UNSPEC
import platform.posix.AI_PASSIVE
import platform.posix.EINPROGRESS
import platform.posix.EINTR
import platform.posix.F_GETFL
import platform.posix.F_SETFL
import platform.posix.NI_NUMERICHOST
import platform.posix.NI_NUMERICSERV
import platform.posix.O_NONBLOCK
import platform.posix.POLLIN
import platform.posix.POLLOUT
import platform.posix.SHUT_RDWR
import platform.posix.SOCK_STREAM
import platform.posix.SOL_SOCKET
import platform.posix.SO_ERROR
import platform.posix.SO_REUSEADDR
import platform.posix.addrinfo
import platform.posix.errno
import platform.posix.fcntl
import platform.posix.freeaddrinfo
import platform.posix.getaddrinfo
import platform.posix.getnameinfo
import platform.posix.getpeername
import platform.posix.getsockname
import platform.posix.getsockopt
import platform.posix.poll
import platform.posix.pollfd
import platform.posix.recv
import platform.posix.send
import platform.posix.setsockopt
import platform.posix.shutdown
import platform.posix.sockaddr
import platform.posix.sockaddr_storage
import platform.posix.socket
import platform.posix.socklen_tVar
/** (no SIGPIPE when the other end has gone: Linux's send() flag, Apple's socket option) */
internal expect fun noSigpipe(fd: Int)
internal expect val SEND_FLAGS: Int
/**
* A socket as a [Duplex] (Kotlin/Native: iOS, and Linux for the tests):
* a TCP connection, or the engine's line (its socket pair's end). Closing
* it wakes a read blocked on it.
*/
@OptIn(ExperimentalForeignApi::class)
class FdDuplex(private val fd: Int, override val name: String = "modem") : Duplex {
private val closed = atomic(false)
init {
noSigpipe(fd)
}
override val input: Source = object : Source {
override fun read(b: ByteArray, off: Int, len: Int): Int {
if (len <= 0) return 0
while (true) {
val n = b.usePinned { recv(fd, it.addressOf(off), len.convert(), 0) }
if (n < 0 && errno == EINTR) continue
if (n < 0) {
if (closed.value) return -1
throw IOException("the connection ended (errno $errno)")
}
return if (n == 0L) -1 else n.toInt()
}
}
}
override val output: Sink = object : Sink {
override fun write(b: ByteArray, off: Int, len: Int) {
var at = off
var left = len
while (left > 0) {
val w = b.usePinned { send(fd, it.addressOf(at), left.convert(), SEND_FLAGS) }
if (w < 0 && errno == EINTR) continue
if (w <= 0) throw IOException("the connection ended")
at += w.toInt()
left -= w.toInt()
}
}
}
override fun close() {
if (!closed.compareAndSet(false, true)) return
shutdown(fd, SHUT_RDWR)
platform.posix.close(fd)
}
}
/**
* Phones calling each other over TCP (Wi-Fi), as the Android app's
* TcpPeerTransport: [port] offered for calls, host[:port] called (port
* [port] when it has none).
*/
@OptIn(ExperimentalForeignApi::class)
class PosixTcpTransport(private val port: Int) : PeerTransport {
override val label = "Wi-Fi"
private val running = atomic(false)
private val listenFd = atomic(-1)
/** the port it listens on (the one it was given, or the system's for 0) */
val localPort: Int
get() {
val fd = listenFd.value
if (fd < 0) return port
return memScoped {
val sa = alloc<sockaddr_storage>()
val len = alloc<socklen_tVar>()
len.value = sizeOf<sockaddr_storage>().convert()
if (getsockname(fd, sa.ptr.reinterpret(), len.ptr) != 0) return@memScoped port
numeric(sa.ptr.reinterpret(), len.value, service = true)?.toIntOrNull() ?: port
}
}
override fun listen(accept: (Duplex) -> Unit) {
val fd = bound(port) ?: throw IOException("can't take calls on port $port (errno $errno)")
listenFd.value = fd
running.value = true
background("peer: listening") {
while (running.value) {
// (polled, so close() ends it on every system: a blocked accept() isn't always woken)
val ready = memScoped {
val p = alloc<pollfd>()
p.fd = fd
p.events = POLLIN.convert()
poll(p.ptr, 1.convert(), 200)
}
if (ready <= 0 || !running.value) continue
val c = platform.posix.accept(fd, null, null)
if (c < 0) continue
val who = peerName(c)
background("peer: a call") { accept(FdDuplex(c, who)) }
}
platform.posix.close(fd)
}
}
override fun connect(address: String): Duplex {
val (host, p) = parse(address, port)
memScoped {
val hints = alloc<addrinfo>()
hints.ai_family = AF_UNSPEC
hints.ai_socktype = SOCK_STREAM
val res = alloc<CPointerVar<addrinfo>>()
val rc = getaddrinfo(host, p.toString(), hints.ptr, res.ptr)
if (rc != 0) throw IOException("no such host: $host")
try {
var ai = res.value
var why = "nobody answers"
while (ai != null) {
val a = ai.pointed
val fd = socket(a.ai_family, a.ai_socktype, a.ai_protocol)
if (fd >= 0) {
val err = connectWithin(fd, a.ai_addr, a.ai_addrlen, CONNECT_MS)
if (err == 0) return FdDuplex(fd, "$host:$p")
why = if (err == -1) "no answer" else "refused (errno $err)"
platform.posix.close(fd)
}
ai = a.ai_next
}
throw IOException(why)
} finally {
freeaddrinfo(res.value)
}
}
}
override fun close() {
running.value = false
}
/** a listening socket on [port] (IPv4, any address), or null */
private fun bound(port: Int): Int? = memScoped {
val hints = alloc<addrinfo>()
hints.ai_family = AF_INET
hints.ai_socktype = SOCK_STREAM
hints.ai_flags = AI_PASSIVE
val res = alloc<CPointerVar<addrinfo>>()
if (getaddrinfo(null, port.toString(), hints.ptr, res.ptr) != 0) return@memScoped null
try {
val a = res.value?.pointed ?: return@memScoped null
val fd = socket(a.ai_family, a.ai_socktype, a.ai_protocol)
if (fd < 0) return@memScoped null
val one = alloc<IntVar>()
one.value = 1
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, one.ptr, sizeOf<IntVar>().convert())
if (platform.posix.bind(fd, a.ai_addr, a.ai_addrlen) != 0 || platform.posix.listen(fd, 4) != 0) {
platform.posix.close(fd)
return@memScoped null
}
fd
} finally {
freeaddrinfo(res.value)
}
}
/** connect() within [ms]: 0, an errno, or -1 for the time up */
private fun connectWithin(fd: Int, addr: CPointer<sockaddr>?, len: UInt, ms: Int): Int = memScoped {
val flags = fcntl(fd, F_GETFL, 0)
fcntl(fd, F_SETFL, flags or O_NONBLOCK)
var err = 0
if (platform.posix.connect(fd, addr, len) != 0) {
if (errno != EINPROGRESS) return@memScoped errno
val p = alloc<pollfd>()
p.fd = fd
p.events = POLLOUT.convert()
if (poll(p.ptr, 1.convert(), ms) <= 0) return@memScoped -1
val e = alloc<IntVar>()
val elen = alloc<socklen_tVar>()
elen.value = sizeOf<IntVar>().convert()
getsockopt(fd, SOL_SOCKET, SO_ERROR, e.ptr, elen.ptr)
err = e.value
}
fcntl(fd, F_SETFL, flags)
err
}
private fun peerName(fd: Int): String = memScoped {
val sa = alloc<sockaddr_storage>()
val len = alloc<socklen_tVar>()
len.value = sizeOf<sockaddr_storage>().convert()
if (getpeername(fd, sa.ptr.reinterpret(), len.ptr) != 0) return@memScoped "?"
numeric(sa.ptr.reinterpret(), len.value, service = false) ?: "?"
}
/** an address's host (or [service]: its port) as numbers */
private fun numeric(sa: CPointer<sockaddr>, len: UInt, service: Boolean): String? = memScoped {
val buf = allocArray<ByteVar>(64)
val rc = if (service) {
getnameinfo(sa, len, null, 0.convert(), buf, 64.convert(), NI_NUMERICSERV)
} else {
getnameinfo(sa, len, buf, 64.convert(), null, 0.convert(), NI_NUMERICHOST)
}
if (rc != 0) null else buf.toKString()
}
companion object {
/** Android's NSD type, Bonjour's: phones taking calls on the network */
const val SERVICE_TYPE = "_dmodem._tcp."
private const val CONNECT_MS = 5000
/** host[:port], [host]:port (IPv6): its host and port ([port] when it has none) */
fun parse(address: String, port: Int): Pair<String, Int> {
val a = address.trim()
if (a.startsWith("[")) {
val end = a.indexOf(']')
if (end > 0) {
val p = a.substring(end + 1).removePrefix(":").toIntOrNull() ?: port
return a.substring(1, end) to p
}
}
// (more than one colon: an IPv6 address without a port)
if (a.count { it == ':' } == 1) {
val p = a.substringAfter(':').toIntOrNull()
if (p != null) return a.substringBefore(':') to p
}
return a to port
}
}
}
@@ -0,0 +1,147 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
package com.neodesktop.dmodem.peer
import com.neodesktop.dmodem.io.background
import com.neodesktop.dmodem.io.monotonicMs
import com.neodesktop.dmodem.io.sleepMs
import kotlinx.atomicfu.atomic
import kotlinx.atomicfu.locks.SynchronizedObject
import kotlinx.atomicfu.locks.synchronized
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.IntVar
import kotlinx.cinterop.allocArray
import kotlinx.cinterop.get
import kotlinx.cinterop.memScoped
import platform.posix.AF_UNIX
import platform.posix.SOCK_STREAM
import platform.posix.socketpair
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
/**
* The line to another phone as iOS has it ([PeerHost] on
* [PosixTcpTransport], the modem's line an [FdDuplex]), over real TCP on
* the loopback: two phones, each "modem" a socket pair's end answering
* every sample with a byte of its own. A call rung, answered and heard
* both ways; a wrong PIN turned away; a phone in a call busy; the hang-up.
*/
@OptIn(ExperimentalForeignApi::class)
class PosixPeerTest {
private inner class Phone(name: String, listen: Boolean, val mark: Byte, callTo: String = "", pin: String = "") {
private val lock = SynchronizedObject()
private val events = ArrayList<String>()
val heardOther = atomic(0)
val hungUp = atomic(false)
val host = PeerHost(0, callTo, pin, events = { e -> synchronized(lock) { events.add(e) } }, log = {}, ringMs = 300)
init {
assertEquals(null, host.start(listen))
}
fun events() = synchronized(lock) { events.toList() }
/** the modem off hook: a socket pair, our end answering samples with [mark], the other to the line */
fun offHook(caller: Boolean, dial: String) {
val (modemFd, lineFd) = memScoped {
val sv = allocArray<IntVar>(2)
assertEquals(0, socketpair(AF_UNIX, SOCK_STREAM, 0, sv))
sv[0] to sv[1]
}
val modem = FdDuplex(modemFd)
// (the lead silence first, as the native modem writes it)
modem.output.write(ByteArray(320) { mark })
background("modem") {
val buf = ByteArray(4096)
try {
while (true) {
val n = modem.input.read(buf, 0, buf.size)
if (n < 0) break
for (i in 0 until n) if (buf[i] in 1..9 && buf[i] != mark) heardOther.incrementAndGet()
modem.output.write(ByteArray(n) { mark })
}
} catch (_: Exception) {
}
hungUp.value = true
modem.close()
}
host.lineStarted(caller, dial, lineFd)
}
}
private fun waitFor(what: String, ms: Long = 15_000, cond: () -> Boolean) {
val end = monotonicMs() + ms
while (!cond()) {
if (monotonicMs() > end) throw AssertionError("no $what")
sleepMs(20)
}
}
@Test
fun aCallOverTcp() {
val b = Phone("B", listen = true, mark = 2)
val port = b.host.localPort
assertTrue(port > 0)
val a = Phone("A", listen = false, mark = 1, callTo = "127.0.0.1:$port")
val c = Phone("C", listen = false, mark = 3, callTo = "127.0.0.1:$port")
try {
assertEquals("Waiting for the other phone's calls", b.host.stateText)
a.offHook(caller = true, dial = "5551234")
waitFor("RING at B") { "RING" in b.events() }
assertTrue(b.host.stateText.startsWith("Ringing: 127.0.0.1"), b.host.stateText)
b.offHook(caller = false, dial = "")
waitFor("ANSWERED at A") { "ANSWERED" in a.events() }
assertTrue(a.host.connected)
waitFor("B's samples at A") { a.heardOther.value > 1000 }
waitFor("A's samples at B") { b.heardOther.value > 1000 }
// C calls B, in a call: busy
c.offHook(caller = true, dial = "1")
waitFor("C's BUSY") { "FAILED 486" in c.events() }
// A hangs up: B's line ends, ready again
a.host.stop()
waitFor("B's end") { b.hungUp.value }
waitFor("B ready") { b.host.stateText == "Waiting for the other phone's calls" }
} finally {
a.host.stop(); b.host.stop(); c.host.stop()
}
}
@Test
fun aPinOverTcp() {
val b = Phone("B", listen = true, mark = 2, pin = "2468")
val port = b.host.localPort
val wrong = Phone("W", listen = false, mark = 3, callTo = "127.0.0.1:$port", pin = "1357")
val right = Phone("A", listen = false, mark = 1, callTo = "127.0.0.1:$port", pin = "2468")
try {
wrong.offHook(caller = true, dial = "1")
waitFor("W's denial") { "FAILED 403" in wrong.events() }
assertTrue("RING" !in b.events())
right.offHook(caller = true, dial = "1")
waitFor("RING at B") { "RING" in b.events() }
} finally {
b.host.stop(); wrong.host.stop(); right.host.stop()
}
}
@Test
fun nobodyThere() {
// a port nobody listens on: NO ANSWER's FAILED 480, why for the user
val a = Phone("A", listen = false, mark = 1, callTo = "127.0.0.1:1")
try {
a.offHook(caller = true, dial = "1")
waitFor("A's failure") { "FAILED 480" in a.events() }
assertTrue(a.host.lastError!!.startsWith("can't reach 127.0.0.1:1"), a.host.lastError)
} finally {
a.host.stop()
}
}
@Test
fun addresses() {
assertEquals("host" to 5070, PosixTcpTransport.parse("host", 5070))
assertEquals("host" to 6000, PosixTcpTransport.parse("host:6000", 5070))
assertEquals("fe80::1" to 5070, PosixTcpTransport.parse("fe80::1", 5070))
assertEquals("fe80::1" to 6000, PosixTcpTransport.parse("[fe80::1]:6000", 5070))
}
}