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

+5 -3
View File
@@ -175,7 +175,9 @@ service, sockets and Bluetooth, Android's VPN and files. Its tests run on
the JVM and natively: `./gradlew :shared:allTests`.
The iOS app (`ios/DModem`, SwiftUI, iOS 16) is the modem on a SIP
account: Home (its state, the rates and what the CONNECT was, start, hang
account, or on the line to another phone with the app (Android or iOS)
on the same Wi-Fi: the shared PeerLine on POSIX sockets (its PIN too),
offered and found with Bonjour (`_dmodem._tcp`, as Android's NSD). It has Home (its state, the rates and what the CONNECT was, start, hang
up, stop, an AT command line), the terminal (the shared emulator drawn in
SwiftUI, CP437 and the VGA colours, Esc/Ctrl/Tab/arrows), the log and the
settings. Its modem keeps going in the background on the audio session
@@ -190,8 +192,8 @@ build:
DMODEM_HOST_BUILD=$PWD/build-host swift test --package-path ios/DModemKit # Linux or macOS
Still to come on iOS: the line to another phone (Bonjour), CallKit, the
Keychain for the password, fax, transfers and PPP's screens.
Still to come on iOS: CallKit, the Keychain for the password, fax,
transfers and PPP's screens.
D-Modem-RE's `portable.h` has Apple's ways where Linux has its own
(close-on-exec sockets, SIGPIPE, a monotonic sleep, a peer's hang-up);
+44 -5
View File
@@ -16,6 +16,9 @@ final class AppModel: ObservableObject {
@Published private(set) var error: String?
/// when the call came online (for its time on Home)
@Published private(set) var onlineSince: Date?
/// the line to another phone: what it's doing, what went wrong last (nil on a SIP line)
@Published private(set) var peerState: String?
@Published private(set) var peerError: String?
@Published var settings: ModemSettings {
didSet { store.settings = settings }
}
@@ -24,7 +27,8 @@ final class AppModel: ObservableObject {
let terminal = TerminalModel()
private let store = SettingsStore()
private let audio = ModemAudio()
private var pending = false
private let peer = PeerLineController()
private var peerTimer: Timer?
init() {
settings = store.settings
@@ -51,18 +55,44 @@ final class AppModel: ObservableObject {
return url.appendingPathComponent("modem-data").path
} ?? ""
let s = settings
Task.detached { [session, audio] in
Task.detached { [session, audio, peer] in
// (the background audio first: the call keeps the app running)
audio.begin()
if !session.start(s, dns: SystemDNS.servers(), dataFile: dataFile) { audio.end() }
// (the line to another phone first: the modem's start commands may dial)
if s.peer { peer.start(s, session: session) } else { session.onLine = nil }
if !session.start(s, dns: SystemDNS.servers(), dataFile: dataFile) {
peer.stop()
audio.end()
}
}
watchPeer(s.peer)
}
func stop() {
Task.detached { [session, audio] in
Task.detached { [session, audio, peer] in
session.stop()
peer.stop()
audio.end()
}
watchPeer(false)
}
/// the peer line's state, twice a second while there's one
private func watchPeer(_ on: Bool) {
peerTimer?.invalidate()
peerTimer = nil
peerState = nil
peerError = nil
guard on else { return }
peerTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in
Task { @MainActor [weak self] in
guard let self else { return }
let st = self.peer.stateText
let err = self.peer.lastError
if st != self.peerState { self.peerState = st }
if err != self.peerError { self.peerError = err }
}
}
}
func hangUp() {
@@ -74,6 +104,7 @@ final class AppModel: ObservableObject {
private func refresh() {
let wasOnline = status.link == .online
let wasRunning = run == .running
run = session.run
status = session.status
log = session.log
@@ -81,6 +112,14 @@ final class AppModel: ObservableObject {
error = session.error
if status.link == .online && !wasOnline { onlineSince = Date() }
if status.link != .online { onlineSince = nil }
if run == .stopped { audio.end() }
// (the modem stopped by itself: the call over, the line to the other phone too. Only a stop
// after it ran: while it starts, its log comes before it's running)
if wasRunning && run == .stopped {
audio.end()
if peerTimer != nil {
peer.stop()
watchPeer(false)
}
}
}
}
+10 -2
View File
@@ -43,9 +43,17 @@ struct HomeView: View {
.padding(.vertical, 6)
}
Section("Line") {
LabeledContent("SIP account", value: model.settings.complete ? "\(model.settings.user)@\(model.settings.domain)" : "not set up")
if model.settings.line == .wifi {
LabeledContent("Another phone", value: model.settings.peerAddress.isEmpty ? "none chosen" : model.settings.peerAddress)
Text(model.peerState ?? "Starts with the modem").foregroundStyle(.secondary)
if let e = model.peerError {
Text(e).foregroundStyle(.red).font(.callout)
}
} else {
LabeledContent("SIP account", value: model.settings.complete ? "\(model.settings.user)@\(model.settings.domain)" : "not set up")
LabeledContent("Fax", value: model.settings.t38 ? "audio or T.38" : "audio")
}
LabeledContent("Incoming calls", value: model.settings.listen ? "taken" : "off")
LabeledContent("Fax", value: model.settings.t38 ? "audio or T.38" : "audio")
}
if model.run == .running {
Section("AT command") {
+125
View File
@@ -0,0 +1,125 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (C) 2026 Neo-Desktop
import DModemKit
import DModemShared
import Foundation
import UIKit
/// The line to another phone with the app over Wi-Fi (the settings' line
/// .wifi): the shared Kotlin's PeerLine (PeerHost) while the modem runs,
/// the engine's line handed to it, offered on the network with Bonjour
/// (_dmodem._tcp, as the Android app's NSD) when it takes calls.
final class PeerLineController: NSObject, NetServiceDelegate, @unchecked Sendable {
private let lock = NSLock()
private var host: PeerHost?
private var service: NetService?
/// why it can't take calls (it can still call), or nil
private(set) var error: String?
/// the line for [settings], the modem's peer lines to it ([session].onLine)
func start(_ settings: ModemSettings, session: ModemSession) {
stop()
let h = PeerHost(
port: Int32(settings.peerPort),
callTo: settings.peerAddress,
pin: settings.peerPin,
events: { e in Engine.shared.peerEvent(e) },
log: { [weak session] l in session?.engineLog("line: " + l) },
ringMs: 3000)
let err = h.start(listen: settings.listen)
lock.lock()
host = h
error = err
lock.unlock()
session.onLine = { caller, dial, fd in h.lineStarted(caller: caller, dial: dial, fd: fd) }
if settings.listen && err == nil {
DispatchQueue.main.async { self.advertise(port: Int(h.localPort)) }
}
}
func stop() {
lock.lock()
let h = host
host = nil
lock.unlock()
h?.stop()
DispatchQueue.main.async {
self.service?.stop()
self.service = nil
}
}
/// what the line is doing (nil while there's none)
var stateText: String? {
lock.lock(); defer { lock.unlock() }
return host?.stateText
}
/// what went wrong last: a call that failed, or the calls it can't take
var lastError: String? {
lock.lock(); defer { lock.unlock() }
return host?.lastError ?? error
}
private func advertise(port: Int) {
let s = NetService(domain: "local.", type: PeerFinder.type, name: "D-Modem on \(UIDevice.current.name)", port: Int32(port))
s.delegate = self
s.publish()
service = s
}
}
/// Phones with the app taking calls on this network (Bonjour, as the
/// Android app's NSD finds them): each to [found] as (its name, host:port).
final class PeerFinder: NSObject, NetServiceBrowserDelegate, NetServiceDelegate {
static let type = "_dmodem._tcp."
private let browser = NetServiceBrowser()
private var resolving: [NetService] = []
private let found: (String, String) -> Void
init(found: @escaping (String, String) -> Void) {
self.found = found
super.init()
browser.delegate = self
}
func start() { browser.searchForServices(ofType: Self.type, inDomain: "local.") }
func stop() {
browser.stop()
resolving.forEach { $0.stop() }
resolving.removeAll()
}
func netServiceBrowser(_ browser: NetServiceBrowser, didFind service: NetService, moreComing: Bool) {
service.delegate = self
resolving.append(service)
service.resolve(withTimeout: 5)
}
func netServiceDidResolveAddress(_ sender: NetService) {
// (an IPv4 address of it, else its host name; its port)
let host = sender.addresses?.compactMap(Self.ipv4).first ?? sender.hostName
if let host, sender.port > 0 { found(sender.name, "\(host):\(sender.port)") }
resolving.removeAll { $0 === sender }
}
func netService(_ sender: NetService, didNotResolve errorDict: [String: NSNumber]) {
resolving.removeAll { $0 === sender }
}
/// a sockaddr's IPv4 address, dotted; nil for another family
private static func ipv4(_ data: Data) -> String? {
data.withUnsafeBytes { raw -> String? in
guard raw.count >= MemoryLayout<sockaddr_in>.size,
let sa = raw.baseAddress?.assumingMemoryBound(to: sockaddr_in.self),
sa.pointee.sin_family == sa_family_t(AF_INET) else { return nil }
var addr = sa.pointee.sin_addr
var buf = [CChar](repeating: 0, count: Int(INET_ADDRSTRLEN))
guard inet_ntop(AF_INET, &addr, &buf, socklen_t(buf.count)) != nil else { return nil }
return String(cString: buf)
}
}
}
+124 -38
View File
@@ -13,50 +13,136 @@ struct SettingsView: View {
var body: some View {
Form {
Section {
TextField("User", text: $model.settings.user)
.textInputAutocapitalization(.never).autocorrectionDisabled()
SecureField("Password", text: $model.settings.password)
TextField("Server (host[:port])", text: $model.settings.domain)
.textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.URL)
TextField("Or paste user:password@host", text: $login)
.textInputAutocapitalization(.never).autocorrectionDisabled()
.onSubmit {
if let l = ModemSettings.parseLogin(login) {
model.settings.user = l.user
model.settings.password = l.password
model.settings.domain = l.domain
login = ""
}
}
} header: {
Text("SIP account")
Picker("Line", selection: $model.settings.line) {
Text("SIP account").tag(ModemSettings.Line.sip)
Text("Another phone (Wi-Fi)").tag(ModemSettings.Line.wifi)
}
} footer: {
Text("The provider must carry G.711 (PCMU/PCMA) to the phone network.")
Text(model.settings.line == .sip
? "The modem calls through a SIP provider to the phone network."
: "The two phones' modems call each other as on a perfect phone line, no SIP account: each dials (ATD) or answers as usual. The other phone needs D-Modem (Android or iOS) on the same Wi-Fi, taking calls.")
}
if model.settings.line == .wifi {
PeerSection(model: model)
} else {
sipSection
}
Section("Calls") {
Toggle("Take incoming calls", isOn: $model.settings.listen)
Toggle("Fax over T.38", isOn: $model.settings.t38)
Toggle("Speaker (the dialling and the handshake)", isOn: $model.settings.speaker)
Stepper("Local SIP port: \(model.settings.sipPort)", value: $model.settings.sipPort, in: 1024...65535)
}
Section {
TextField("AT commands at start", text: $model.settings.initCommands)
.textInputAutocapitalization(.characters).autocorrectionDisabled().font(.body.monospaced())
} header: {
Text("Modem")
} footer: {
Text("ATX3 by default: a SIP line has no dial tone.")
}
Section("Log") {
Stepper("Modem's level: \(model.settings.logLevel)", value: $model.settings.logLevel, in: 0...5)
Stepper("SIP's level: \(model.settings.sipLogLevel)", value: $model.settings.sipLogLevel, in: 0...4)
}
if model.run == .running {
Section {
Text("Changes apply when the modem starts again.").foregroundStyle(.secondary)
Toggle(model.settings.line == .sip ? "Take incoming calls" : "Take calls from the other phone", isOn: $model.settings.listen)
if model.settings.line == .sip {
Toggle("Fax over T.38", isOn: $model.settings.t38)
Stepper("Local SIP port: \(model.settings.sipPort)", value: $model.settings.sipPort, in: 1024...65535)
}
Toggle("Speaker (the dialling and the handshake)", isOn: $model.settings.speaker)
}
modemSections
}
.navigationTitle("Settings")
}
@ViewBuilder private var sipSection: some View {
Section {
TextField("User", text: $model.settings.user)
.textInputAutocapitalization(.never).autocorrectionDisabled()
SecureField("Password", text: $model.settings.password)
TextField("Server (host[:port])", text: $model.settings.domain)
.textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.URL)
TextField("Or paste user:password@host", text: $login)
.textInputAutocapitalization(.never).autocorrectionDisabled()
.onSubmit {
if let l = ModemSettings.parseLogin(login) {
model.settings.user = l.user
model.settings.password = l.password
model.settings.domain = l.domain
login = ""
}
}
} header: {
Text("SIP account")
} footer: {
Text("The provider must carry G.711 (PCMU/PCMA) to the phone network.")
}
}
@ViewBuilder private var modemSections: some View {
Section {
TextField("AT commands at start", text: $model.settings.initCommands)
.textInputAutocapitalization(.characters).autocorrectionDisabled().font(.body.monospaced())
} header: {
Text("Modem")
} footer: {
Text("ATX3 by default: a SIP line has no dial tone.")
}
Section("Log") {
Stepper("Modem's level: \(model.settings.logLevel)", value: $model.settings.logLevel, in: 0...5)
Stepper("SIP's level: \(model.settings.sipLogLevel)", value: $model.settings.sipLogLevel, in: 0...4)
}
if model.run == .running {
Section {
Text("Changes apply when the modem starts again.").foregroundStyle(.secondary)
}
}
}
}
/// a phone found taking calls
private struct Found: Identifiable {
let name: String
let address: String
var id: String { address }
}
/// the other phone: whom ATD calls (or found on the network), the port, the PIN
private struct PeerSection: View {
@ObservedObject var model: AppModel
@State private var finding = false
@State private var found: [Found] = []
@State private var finder: PeerFinder?
var body: some View {
Section {
TextField("Phone to call (host[:port])", text: $model.settings.peerAddress)
.textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.URL)
Button(finding ? "Stop looking" : "Find phones on this network") { finding ? stop() : find() }
if finding {
if found.isEmpty {
Text("Looking… (phones taking calls on this Wi-Fi show here)").foregroundStyle(.secondary)
}
ForEach(found) { p in
Button {
model.settings.peerAddress = p.address
stop()
} label: {
VStack(alignment: .leading) {
Text(p.name)
Text(p.address).font(.caption).foregroundStyle(.secondary)
}
}
}
}
Stepper("Port calls come in on: \(model.settings.peerPort)", value: $model.settings.peerPort, in: 1024...65535)
SecureField("PIN (optional)", text: $model.settings.peerPin)
} header: {
Text("The other phone")
} footer: {
Text("ATD with any number calls this phone; ATD192*168*1*20 calls that address instead. Set the same PIN on both phones: calls without it are turned down.")
}
.onDisappear(perform: stop)
}
private func find() {
found = []
let f = PeerFinder { name, address in
if !found.contains(where: { $0.address == address }) { found.append(Found(name: name, address: address)) }
}
finder = f
finding = true
f.start()
}
private func stop() {
finder?.stop()
finder = nil
finding = false
}
}
@@ -29,6 +29,9 @@ public final class ModemSession: EngineListener, @unchecked Sendable {
/// the speaker's level and sound (the app's audio)
public var onSpeaker: ((Int) -> Void)?
public var onSound: ((UnsafeBufferPointer<Int16>) -> Void)?
/// a peer line's modem off hook (the app's line to the other phone takes it): dialling [dial] if
/// caller; fd its samples, the handler's to close. Without one the line is closed (the dial fails)
public var onLine: ((_ caller: Bool, _ dial: String, _ fd: Int32) -> Void)?
private let engine: Engine
@@ -145,6 +148,10 @@ public final class ModemSession: EngineListener, @unchecked Sendable {
changed()
}
public func engineLine(caller: Bool, dial: String, fd: Int32) {
if let h = onLine { h(caller, dial, fd) } else { close(fd) }
}
public func engineSpeaker(_ level: Int) { onSpeaker?(level) }
public func engineSound(_ pcm: UnsafeBufferPointer<Int16>) { onSound?(pcm) }
@@ -83,6 +83,28 @@ final class DModemKitTests: XCTestCase {
Engine.shared.stop()
}
func testThePeerLineGoesToTheApp() {
signal(SIGPIPE, SIG_IGN)
let session = ModemSession()
let got = NSLock()
var line: (Bool, String, Int32)?
session.onLine = { caller, dial, fd in got.lock(); line = (caller, dial, fd); got.unlock() }
var settings = ModemSettings()
settings.line = .wifi
settings.initCommands = "ATE0X3"
XCTAssertTrue(session.start(settings))
XCTAssertTrue(waitFor { session.console.contains("OK") })
session.command("ATD192*168*1*20")
XCTAssertTrue(waitFor { got.lock(); defer { got.unlock() }; return line != nil })
XCTAssertEqual(line?.0, true)
XCTAssertEqual(line?.1, "192*168*1*20")
// the app's line gone: the call's NO CARRIER
Engine.shared.peerEvent("FAILED 480")
close(line!.2)
XCTAssertTrue(waitFor { session.console.contains("NO ") }, session.console)
session.stop()
}
func testIncompleteSettingsDontStart() {
let session = ModemSession()
XCTAssertFalse(session.start(ModemSettings()))
@@ -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))
}
}