diff --git a/.gitignore b/.gitignore index 15bf8fe..f1243ee 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,11 @@ captures/ # the iOS app's generated project ios/DModem/DModem.xcodeproj/ +# (xcodegen writes these from project.yml) +ios/DModem/Sources/Info.plist +ios/DModem/Sources/DModem.entitlements +ios/DModem/Tunnel/Info.plist +ios/DModem/Tunnel/DModemTunnel.entitlements + +# Swift packages build here +.build/ diff --git a/README.md b/README.md index 6762235..c7cb083 100644 --- a/README.md +++ b/README.md @@ -177,14 +177,35 @@ the JVM and natively: `./gradlew :shared:allTests`. The iOS app (`ios/DModem`, SwiftUI, iOS 16) is the modem on a SIP 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 -(its speaker, or quiet). The modem apart from the views is the -`ios/DModemKit` Swift package (the engine from Swift, its DTE, the -settings, the session), whose tests run on Linux too, against the host -build: +offered and found with Bonjour (`_dmodem._tcp`, as Android's NSD). It has: + +- Home: the modem's state, the rates and what the CONNECT was, start, + hang up, stop, an AT command line, the log +- the terminal (the shared emulator drawn in SwiftUI, CP437 and the VGA + colours, Esc/Ctrl/Tab/arrows) and its file transfers (ZMODEM, YMODEM, + XMODEM, Kermit; a remote's `sz` or `kermit -s` starts one by itself) +- Fax: PDFs, images and text sent; a ringing call answered as a fax, by + hand or each one; the received faxes as PDFs +- Internet: dial-up to an ISP (its login script if it has one, PPP), the + phone's traffic through it as a VPN (the `DModemTunnel` packet tunnel + extension, its packets to the app's PPP on the loopback) +- Settings: the SIP account or the other phone, the modem's commands + +The modem's calls are the phone's own (CallKit): one ringing in rings +as a phone call does, answered or turned down there; one dialled shows +as a call, hung up from the call screen. The passwords and the PIN are +in the Keychain. Received files and faxes are in the Files app (On My +iPhone › D-Modem). The modem keeps going in the background on the audio +session (its speaker, or quiet); calls ring in while the app runs (with +no push service, a call can't wake it). Dial-up's VPN needs the Network +Extensions capability on the app's team. + +What the screens run is the shared Kotlin's jobs (`shared/.../jobs`: a +fax call, a transfer, dial-up, each lent the modem's DTE while it lasts), +tested on the JVM and natively. The modem apart from the views is the +`ios/DModemKit` Swift package (the engine from Swift, its DTE and who +it's lent to, the settings and their secrets, the session), whose tests +run on Linux too, against the host build: ./gradlew :shared:assembleDModemSharedReleaseXCFramework ios/build-native.sh @@ -192,9 +213,6 @@ build: DMODEM_HOST_BUILD=$PWD/build-host swift test --package-path ios/DModemKit # Linux or macOS -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); the Linux build tests them too with `-DDMODEM_PORTABLE_FALLBACKS`. CI diff --git a/ios/DModem/Sources/AppModel.swift b/ios/DModem/Sources/AppModel.swift index 541dc25..54ca6c8 100644 --- a/ios/DModem/Sources/AppModel.swift +++ b/ios/DModem/Sources/AppModel.swift @@ -25,23 +25,100 @@ final class AppModel: ObservableObject { let session = ModemSession() let terminal = TerminalModel() + /// the fax calls, transfers and dial-up the modem is lent to + let jobs: JobsModel private let store = SettingsStore() private let audio = ModemAudio() private let peer = PeerLineController() + private let calls = CallController() private var peerTimer: Timer? + /// the last of what the modem said, looked at for RING and the caller's number + private var ringScan = "" + private var callerId: String? + /// what's typed at the terminal on its line, and the number its last ATD dialled + private var typedLine = "" + private var lastDial = "" init() { settings = store.settings + jobs = JobsModel(session: session) { [store] in store.settings } session.onChange = { [weak self] in // (many changes at once, one update) Task { @MainActor [weak self] in self?.refresh() } } session.onData = { [weak self] data in - Task { @MainActor [weak self] in self?.terminal.feed(data) } + Task { @MainActor [weak self] in self?.received(data) } } session.onSpeaker = { [audio] level in audio.speaker(level) } session.onSound = { [audio] pcm in audio.play(pcm) } - terminal.send = { [weak self] data in self?.session.send(data) } + terminal.send = { [weak self] data in + self?.typed(data) + self?.session.send(data) + } + calls.onAnswer = { [weak self] in self?.session.command("ATA") } + calls.onEnd = { [weak self] in self?.callEndedByUser() } + calls.onAudio = { [audio] on in if on { audio.resume() } } + } + + /// what the modem said (for the terminal): a remote's transfer started, a call ringing + private func received(_ data: Data) { + if jobs.remoteStarts(data) { return } + terminal.feed(data) + ringScan = String((ringScan + Octets.latin1(data)).suffix(256)) + // (caller ID, when the line gives it: NMBR = 5551234) + if let r = ringScan.range(of: "NMBR = ", options: .backwards) { + let n = ringScan[r.upperBound...].prefix { !$0.isNewline } + if !n.isEmpty { callerId = String(n).trimmingCharacters(in: .whitespaces) } + } + if ringScan.contains("RING\r") || ringScan.contains("RING\n") { + ringScan = "" + ring() + } + } + + private func ring() { + if jobs.running { return } + calls.ringing(from: callerId) + if settings.faxAutoAnswer && jobs.answerFax() == nil { calls.answeredHere() } + } + + /// the ringing call answered as a fax (the Fax screen's button) + func answerFax() -> String? { + let r = jobs.answerFax() + if r == nil { calls.answeredHere() } + return r + } + + /// the terminal's typing, looked at for the number an ATD dials + private func typed(_ data: Data) { + for c in Octets.latin1(data) { + if c == "\r" { + let l = typedLine.uppercased().trimmingCharacters(in: .whitespaces) + if let r = l.range(of: "ATD") { + lastDial = String(l[r.upperBound...].drop { $0 == "T" || $0 == "P" }.filter { $0.isNumber || $0 == "*" || $0 == "#" || $0 == "+" }) + } + typedLine = "" + } else if c == "\u{8}" || c == "\u{7f}" { + if !typedLine.isEmpty { typedLine.removeLast() } + } else if typedLine.count < 200 { + typedLine.append(c) + } + } + } + + /// hung up on the phone's call screen: the job's call, or the modem's, over + private func callEndedByUser() { + if jobs.fax?.running == true { jobs.cancelFax() } + if jobs.internet?.running == true { jobs.disconnectInternet() } + if jobs.transfer?.running == true { jobs.cancelTransfer() } + if status.offHook { hangUp() } + } + + /// the number being dialled, for the phone's call screen + private var dialling: String { + if jobs.fax?.running == true, jobs.fax?.sending == true { return jobs.fax?.number ?? "" } + if jobs.internet?.running == true { return settings.ispNumber } + return lastDial } var connectLabel: String { status.link == .online ? ConnectInfo.label(console) : "" } @@ -105,6 +182,7 @@ final class AppModel: ObservableObject { private func refresh() { let wasOnline = status.link == .online let wasRunning = run == .running + let wasOffHook = status.offHook run = session.run status = session.status log = session.log @@ -112,6 +190,13 @@ final class AppModel: ObservableObject { error = session.error if status.link == .online && !wasOnline { onlineSince = Date() } if status.link != .online { onlineSince = nil } + // the phone's call screen: a call ringing answered, one dialled, connected, over + if status.offHook && !wasOffHook { + if calls.inCall { calls.answeredHere() } else { calls.dialling(dialling) } + } + if status.link == .online && !wasOnline { calls.connected() } + if (!status.offHook && wasOffHook) || (wasRunning && run == .stopped) { calls.ended() } + jobs.statusChanged(online: status.link == .online, running: run == .running) // (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 { diff --git a/ios/DModem/Sources/CallController.swift b/ios/DModem/Sources/CallController.swift new file mode 100644 index 0000000..c0aa06e --- /dev/null +++ b/ios/DModem/Sources/CallController.swift @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +import AVFoundation +import CallKit +import Foundation + +/// The modem's calls as the phone's own (CallKit): a call ringing in +/// (the modem's RING) rings as a phone call does, on the lock screen too, +/// answered or turned down there; a call the modem dials shows in the +/// status bar as a call, hung up from the phone's call screen; each in +/// Recents. (Calls come in while the app runs: its background audio keeps +/// it running with the modem. Without a push service, a call can't wake +/// an app that isn't.) +@MainActor +final class CallController: NSObject { + /// the user answered the ringing call (on the phone's screen) + var onAnswer: (() -> Void)? + /// the user hung up (or turned down a ringing call) + var onEnd: (() -> Void)? + /// the call's audio session active (true) or not: the modem's sound resumed on it + var onAudio: ((Bool) -> Void)? + + private let provider: CXProvider + private let calls = CXCallController() + private var current: UUID? + private var incoming = false + private var answered = false + /// the call ended by us (the modem), not the user: no hang-up asked of it + private var endingOurselves = false + private var ringTimer: Timer? + /// the ringing call turned down: its RINGs passed over until they stop + private var declined = false + + override init() { + let c = CXProviderConfiguration() + c.supportsVideo = false + c.maximumCallGroups = 1 + c.maximumCallsPerCallGroup = 1 + c.supportedHandleTypes = [.phoneNumber, .generic] + c.includesCallsInRecents = true + provider = CXProvider(configuration: c) + super.init() + provider.setDelegate(self, queue: nil) + } + + var inCall: Bool { current != nil } + + /// the modem said RING: the phone rings (again: the ring goes on while RINGs come) + func ringing(from caller: String?) { + ringTimer?.invalidate() + // (no RING for 8 s: the caller gave up) + ringTimer = Timer.scheduledTimer(withTimeInterval: 8, repeats: false) { [weak self] _ in + Task { @MainActor [weak self] in self?.ringStopped() } + } + if current != nil || declined { return } + let id = UUID() + current = id + incoming = true + answered = false + let u = CXCallUpdate() + u.remoteHandle = CXHandle(type: caller == nil ? .generic : .phoneNumber, value: caller ?? "Modem call") + u.localizedCallerName = caller.map { "Modem call from \($0)" } ?? "Modem call" + u.hasVideo = false + u.supportsHolding = false + u.supportsGrouping = false + u.supportsUngrouping = false + u.supportsDTMF = false + provider.reportNewIncomingCall(with: id, update: u) { [weak self] err in + if err != nil { Task { @MainActor [weak self] in self?.forget(id) } } + } + } + + /// the ringing call answered by the app itself (a fax answered): the phone's ring stopped, the call on + func answeredHere() { + guard let id = current, incoming, !answered else { return } + answered = true + ringTimer?.invalidate() + calls.request(CXTransaction(action: CXAnswerCallAction(call: id))) { _ in } + } + + /// the modem off hook dialling [number] (not answering): an outgoing call + func dialling(_ number: String) { + guard current == nil else { return } + let id = UUID() + current = id + incoming = false + let h = CXHandle(type: number.isEmpty ? .generic : .phoneNumber, value: number.isEmpty ? "Modem call" : number) + let a = CXStartCallAction(call: id, handle: h) + calls.request(CXTransaction(action: a)) { [weak self] err in + if err != nil { Task { @MainActor [weak self] in self?.forget(id) } } + } + } + + /// the modems connected + func connected() { + guard let id = current else { return } + if !incoming { provider.reportOutgoingCall(with: id, connectedAt: nil) } + } + + /// the modem back on hook: the call over + func ended() { + guard let id = current else { return } + ringTimer?.invalidate() + endingOurselves = true + calls.request(CXTransaction(action: CXEndCallAction(call: id))) { [weak self] err in + if err != nil { + Task { @MainActor [weak self] in + self?.provider.reportCall(with: id, endedAt: nil, reason: .remoteEnded) + self?.forget(id) + } + } + } + } + + private func ringStopped() { + declined = false + guard let id = current, incoming, !answered else { return } + provider.reportCall(with: id, endedAt: nil, reason: .unanswered) + forget(id) + } + + private func forget(_ id: UUID) { + if current == id { + current = nil + endingOurselves = false + } + } +} + +extension CallController: CXProviderDelegate { + nonisolated func providerDidReset(_ provider: CXProvider) { + Task { @MainActor in self.current = nil } + } + + nonisolated func provider(_ provider: CXProvider, perform action: CXStartCallAction) { + provider.reportOutgoingCall(with: action.callUUID, startedConnectingAt: nil) + action.fulfill() + } + + nonisolated func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) { + Task { @MainActor in + // (answered here already, a fax: nothing to tell the modem) + let byUser = !self.answered + self.answered = true + self.ringTimer?.invalidate() + if byUser { self.onAnswer?() } + } + action.fulfill() + } + + nonisolated func provider(_ provider: CXProvider, perform action: CXEndCallAction) { + Task { @MainActor in + let byUser = !self.endingOurselves + if byUser && self.incoming && !self.answered { self.declined = true } + self.forget(action.callUUID) + if byUser { self.onEnd?() } + } + action.fulfill() + } + + nonisolated func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) { + Task { @MainActor in self.onAudio?(true) } + } + + nonisolated func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) { + Task { @MainActor in self.onAudio?(false) } + } +} diff --git a/ios/DModem/Sources/DModemApp.swift b/ios/DModem/Sources/DModemApp.swift index 7aae823..7eb8776 100644 --- a/ios/DModem/Sources/DModemApp.swift +++ b/ios/DModem/Sources/DModemApp.swift @@ -2,7 +2,8 @@ // Copyright (C) 2026 Neo-Desktop import SwiftUI -/// D-Modem for iOS: the modem on a SIP account, its terminal, its log. +/// D-Modem for iOS: the modem on a SIP account (or another phone), its +/// terminal and file transfers, faxes, dial-up internet. @main struct DModemApp: App { @StateObject private var model = AppModel() @@ -12,13 +13,35 @@ struct DModemApp: App { TabView { NavigationStack { HomeView(model: model) } .tabItem { Label("Home", systemImage: "house") } - NavigationStack { TerminalScreen(model: model.terminal) } + NavigationStack { TerminalTab(model: model, jobs: model.jobs) } .tabItem { Label("Terminal", systemImage: "terminal") } - NavigationStack { LogView(model: model) } - .tabItem { Label("Log", systemImage: "list.bullet.rectangle") } + NavigationStack { FaxView(model: model, jobs: model.jobs) } + .tabItem { Label("Fax", systemImage: "printer") } + NavigationStack { InternetView(model: model, jobs: model.jobs) } + .tabItem { Label("Internet", systemImage: "globe") } NavigationStack { SettingsView(model: model) } .tabItem { Label("Settings", systemImage: "gear") } } } } } + +/// the terminal, its file transfers a button away (and shown when the remote starts one) +private struct TerminalTab: View { + @ObservedObject var model: AppModel + @ObservedObject var jobs: JobsModel + @State private var transfers = false + + var body: some View { + TerminalScreen(model: model.terminal) + .toolbar { + ToolbarItem(placement: .primaryAction) { + Button { transfers = true } label: { Image(systemName: "arrow.up.arrow.down.circle") } + .accessibilityLabel("File transfer") + } + } + .sheet(isPresented: $transfers) { TransferView(jobs: jobs) } + .onChange(of: jobs.transfer?.running) { r in if r == true { transfers = true } } + .onChange(of: jobs.filesWanted) { w in if w { transfers = true } } + } +} diff --git a/ios/DModem/Sources/FaxDocuments.swift b/ios/DModem/Sources/FaxDocuments.swift new file mode 100644 index 0000000..5d0c074 --- /dev/null +++ b/ios/DModem/Sources/FaxDocuments.swift @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +import CoreGraphics +import DModemShared +import Foundation +import UIKit +import UniformTypeIdentifiers + +/// Documents as fax pages, as the Android app's FaxDocuments: a PDF's +/// pages, an image, plain text, each drawn in grey at the fax's width +/// (1728 pels, 204 to the inch; 196 or 98 lines to the inch down), made +/// black and white by the shared FaxImage (text and PDFs at a threshold, +/// photographs dithered). +enum FaxDocuments { + enum Failure: LocalizedError { + case unreadable(String) + var errorDescription: String? { + switch self { case .unreadable(let why): return why } + } + } + + static let width = Int(FaxPage.companion.WIDTH) + + /// the pages of the document at [url] (a file the app may read) + static func pages(_ url: URL, fine: Bool) throws -> [FaxPage] { + let type = UTType(filenameExtension: url.pathExtension.lowercased()) + if type?.conforms(to: .pdf) == true { return try pdf(url, fine: fine) } + if type?.conforms(to: .image) == true { + guard let img = UIImage(contentsOfFile: url.path)?.cgImage else { throw Failure.unreadable("can't read the image") } + return [page(fine: fine, dither: true, aspect: CGSize(width: img.width, height: img.height)) { ctx, size in + ctx.interpolationQuality = .high + ctx.draw(img, in: CGRect(origin: .zero, size: size)) + }] + } + if type?.conforms(to: .text) == true || url.pathExtension.lowercased() == "txt" { + guard let d = try? Data(contentsOf: url) else { throw Failure.unreadable("can't read the text") } + return text(String(decoding: d, as: UTF8.self), fine: fine) + } + throw Failure.unreadable("not a PDF, an image or text: \(url.lastPathComponent)") + } + + private static func pdf(_ url: URL, fine: Bool) throws -> [FaxPage] { + guard let doc = CGPDFDocument(url as CFURL) else { throw Failure.unreadable("can't open the PDF") } + guard doc.numberOfPages > 0 else { return [] } + return (1...doc.numberOfPages).compactMap { n in + guard let pg = doc.page(at: n) else { return nil } + let box = pg.getBoxRect(.mediaBox) + return page(fine: fine, dither: false, aspect: box.size) { ctx, size in + ctx.scaleBy(x: size.width / box.width, y: size.height / box.height) + ctx.translateBy(x: -box.minX, y: -box.minY) + ctx.drawPDFPage(pg) + } + } + } + + /// plain text on A4 pages: monospaced, 66 lines and 80 columns to a page + static func text(_ text: String, fine: Bool) -> [FaxPage] { + let lines = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\t", with: " ") + .split(separator: "\n", omittingEmptySubsequences: false) + .flatMap { l -> [String] in + if l.isEmpty { return [""] } + return stride(from: 0, to: l.count, by: 80).map { i in + let a = l.index(l.startIndex, offsetBy: i) + return String(l[a..<(l.index(a, offsetBy: 80, limitedBy: l.endIndex) ?? l.endIndex)]) + } + } + let perPage = 66 + let chunks = stride(from: 0, to: max(lines.count, 1), by: perPage).map { Array(lines[$0.. Void) -> FaxPage { + let rows = Int(FaxImage.shared.rows(width: Int32(max(1, aspect.width)), height: Int32(max(1, aspect.height)), fine: fine)) + var gray = [UInt8](repeating: 255, count: width * rows) + gray.withUnsafeMutableBytes { raw in + guard let ctx = CGContext(data: raw.baseAddress, width: width, height: rows, bitsPerComponent: 8, bytesPerRow: width, + space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue) else { return } + ctx.setFillColor(gray: 1, alpha: 1) + ctx.fill(CGRect(x: 0, y: 0, width: width, height: rows)) + draw(ctx, CGSize(width: width, height: rows)) + } + // (a bitmap context's memory is its top row first, as the fax's) + let latin1 = String(data: Data(gray), encoding: .isoLatin1) ?? "" + return FaxImage.shared.pageLatin1(gray: latin1, width: Int32(width), height: Int32(rows), fine: fine, dither: dither) + } +} diff --git a/ios/DModem/Sources/FaxView.swift b/ios/DModem/Sources/FaxView.swift new file mode 100644 index 0000000..3a72e5e --- /dev/null +++ b/ios/DModem/Sources/FaxView.swift @@ -0,0 +1,131 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +import DModemKit +import DModemShared +import QuickLook +import SwiftUI +import UniformTypeIdentifiers + +/// Faxes: a document (PDF, image, text) sent to a number; the ringing +/// call answered as a fax, by hand or each one; the call as it goes; the +/// faxes received (PDFs in Documents/Faxes), opened or shared. +struct FaxView: View { + @ObservedObject var model: AppModel + @ObservedObject var jobs: JobsModel + @State private var number = "" + @State private var documents: [URL] = [] + @State private var picking = false + @State private var error: String? + @State private var received: [URL] = [] + @State private var preview: URL? + + var body: some View { + Form { + if jobs.preparing || jobs.fax != nil || jobs.faxError != nil { callSection } + Section { + TextField("Fax number", text: $number).keyboardType(.phonePad) + ForEach(documents, id: \.self) { u in + Label(u.lastPathComponent, systemImage: "doc") + } + .onDelete { documents.remove(atOffsets: $0) } + Button(documents.isEmpty ? "Choose a document" : "Add a document") { picking = true } + Button("Send the fax") { + error = jobs.sendFax(number: number, documents: documents) + } + .disabled(number.isEmpty || documents.isEmpty || jobs.running || model.run != .running) + } header: { + Text("Send") + } footer: { + Text("PDFs, images and text, at the fax's width: photographs as dots, the rest black and white.") + } + Section { + Button("Answer the ringing call as a fax") { error = model.answerFax() } + .disabled(jobs.running || model.run != .running) + Toggle("Answer every call as a fax", isOn: $model.settings.faxAutoAnswer) + } header: { + Text("Receive") + } + if let e = error { + Section { Text(e).foregroundStyle(.red) } + } + Section("Received") { + if received.isEmpty { + Text("None yet").foregroundStyle(.secondary) + } + ForEach(received, id: \.self) { u in + HStack { + Button(u.lastPathComponent) { preview = u } + Spacer() + ShareLink(item: u) { Image(systemName: "square.and.arrow.up") }.buttonStyle(.borderless) + } + } + .onDelete { idx in + for i in idx { try? FileManager.default.removeItem(at: received[i]) } + reload() + } + } + Section("Fax settings") { + TextField("Our number (sent to the other machine)", text: $model.settings.faxIdent).keyboardType(.phonePad) + Toggle("Error correction (ECM)", isOn: $model.settings.faxEcm) + Toggle("Fine resolution", isOn: $model.settings.faxFine) + Picker("Fastest rate", selection: $model.settings.faxMaxBps) { + ForEach([14400, 9600, 4800, 2400], id: \.self) { Text("\($0) bit/s").tag($0) } + } + } + } + .navigationTitle("Fax") + .fileImporter(isPresented: $picking, allowedContentTypes: [.pdf, .image, .plainText], allowsMultipleSelection: true) { r in + if case .success(let urls) = r { documents += urls.compactMap(copied) } + } + .quickLookPreview($preview) + .onAppear(perform: reload) + .onChange(of: jobs.fax?.running) { _ in reload() } + } + + @ViewBuilder private var callSection: some View { + Section { + if jobs.preparing { + HStack { ProgressView(); Text("Preparing the document") } + } + if let e = jobs.faxError { + Text(e).foregroundStyle(.red) + Button("Dismiss") { jobs.dismissFax() } + } + if let f = jobs.fax { + let p = f.progress + Text(f.running ? (p.phase.isEmpty ? "Starting" : p.phase) : (f.result == "" ? (f.sending ? "Sent" : "Received") : "Failed")) + .font(.headline) + if p.total > 0 || p.pages > 0 { + Text(p.total > 0 ? "Page \(min(p.pages + (f.running ? 1 : 0), p.total)) of \(p.total)" : "\(p.pages) page\(p.pages == 1 ? "" : "s")") + } + if p.bps > 0 { + Text("\(p.bps) bit/s\(p.fine ? ", fine" : "")\(p.ecm ? ", ECM" : "")").foregroundStyle(.secondary) + } + if !p.remote.isEmpty { LabeledContent("The other machine", value: p.remote) } + if let r = f.result, !r.isEmpty { Text(r).foregroundStyle(.red) } + if f.running { + Button("Hang up", role: .destructive) { jobs.cancelFax() } + } else { + if !f.file.isEmpty { + Button("Open \(f.file)") { preview = AppFolders.faxes.appendingPathComponent(f.file) } + } + Button("Dismiss") { jobs.dismissFax() } + } + } + } header: { + Text(jobs.fax?.sending == false ? "Receiving" : "Sending") + } + } + + private func reload() { received = AppFolders.files(AppFolders.faxes) } + + /// a picked file copied where the app may read it later (a picked one may only be read while open to us) + private func copied(_ u: URL) -> URL? { + let scoped = u.startAccessingSecurityScopedResource() + defer { if scoped { u.stopAccessingSecurityScopedResource() } } + let dir = FileManager.default.temporaryDirectory.appendingPathComponent("fax-\(UUID().uuidString)", isDirectory: true) + try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + let dest = dir.appendingPathComponent(u.lastPathComponent) + return (try? FileManager.default.copyItem(at: u, to: dest)) != nil ? dest : nil + } +} diff --git a/ios/DModem/Sources/HomeView.swift b/ios/DModem/Sources/HomeView.swift index 2d07ec7..30ce58d 100644 --- a/ios/DModem/Sources/HomeView.swift +++ b/ios/DModem/Sources/HomeView.swift @@ -71,6 +71,12 @@ struct HomeView: View { } } .navigationTitle("D-Modem") + .toolbar { + ToolbarItem(placement: .primaryAction) { + NavigationLink { LogView(model: model) } label: { Image(systemName: "list.bullet.rectangle") } + .accessibilityLabel("Log") + } + } } @ViewBuilder private var actions: some View { diff --git a/ios/DModem/Sources/InternetView.swift b/ios/DModem/Sources/InternetView.swift new file mode 100644 index 0000000..308370b --- /dev/null +++ b/ios/DModem/Sources/InternetView.swift @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +import DModemShared +import SwiftUI + +/// Dial-up internet: an ISP dialled on the modem, PPP up, the phone's +/// traffic through it (a VPN, the app's own: iOS asks to allow it the +/// first time); the link as it goes, its address, what's gone each way. +struct InternetView: View { + @ObservedObject var model: AppModel + @ObservedObject var jobs: JobsModel + @State private var error: String? + + var body: some View { + Form { + Section { + if let s = jobs.internet { + status(s) + } else { + Text("Not connected").font(.headline) + } + if jobs.internet?.running == true { + Button("Disconnect", role: .destructive) { jobs.disconnectInternet() } + } else { + Button("Connect") { + jobs.dismissInternet() + error = jobs.connectInternet() + } + .disabled(model.run != .running || model.settings.ispNumber.isEmpty || jobs.running) + } + if let e = error { Text(e).foregroundStyle(.red) } + } footer: { + Text("While it's up the phone's internet goes through the call, at the modem's speed. The first time, iOS asks to add D-Modem's VPN.") + } + Section { + TextField("Number", text: $model.settings.ispNumber).keyboardType(.phonePad) + TextField("User", text: $model.settings.ispUser) + .textInputAutocapitalization(.never).autocorrectionDisabled() + SecureField("Password", text: $model.settings.ispPassword) + TextField("Modem commands first (AT…; between)", text: $model.settings.ispInit) + .textInputAutocapitalization(.characters).autocorrectionDisabled().font(.body.monospaced()) + } header: { + Text("The ISP") + } + Section { + TextEditor(text: $model.settings.ispScript) + .font(.body.monospaced()) + .frame(minHeight: 80) + .textInputAutocapitalization(.never).autocorrectionDisabled() + } header: { + Text("Login script (optional)") + } footer: { + Text("For an ISP that asks for a login before PPP, as chat does it: what's expected, then what's sent, e.g. ogin: \\U assword: \\P. Most need none: PPP logs in with the user and password.") + } + } + .navigationTitle("Internet") + } + + @ViewBuilder private func status(_ s: DialUpJob.State) -> some View { + Text(s.running ? (s.connected ? "Connected" : s.phase) : "Disconnected").font(.headline) + if !s.connect.isEmpty { Text(s.connect).font(.callout.monospaced()).foregroundStyle(.secondary) } + if s.connected { + LabeledContent("Address", value: s.address) + if !s.dns.isEmpty { LabeledContent("DNS", value: s.dns.joined(separator: ", ")) } + TimelineView(.periodic(from: Date(), by: 1)) { _ in + LabeledContent("Up for", value: elapsed(Int(jobs.upMs / 1000))) + } + LabeledContent("In", value: ByteCountFormatter.string(fromByteCount: s.bytesIn, countStyle: .file)) + LabeledContent("Out", value: ByteCountFormatter.string(fromByteCount: s.bytesOut, countStyle: .file)) + } + if let e = s.ended, e != "disconnected" { Text(e).foregroundStyle(.red) } + } + + private func elapsed(_ s: Int) -> String { + s >= 3600 ? String(format: "%d:%02d:%02d", s / 3600, s / 60 % 60, s % 60) : String(format: "%d:%02d", s / 60, s % 60) + } +} diff --git a/ios/DModem/Sources/Jobs.swift b/ios/DModem/Sources/Jobs.swift new file mode 100644 index 0000000..acc79e2 --- /dev/null +++ b/ios/DModem/Sources/Jobs.swift @@ -0,0 +1,73 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +import DModemKit +import DModemShared +import Foundation + +/// What a shared Kotlin job calls back (DteOut, LogOut, Changed): its +/// octets to the modem's DTE (lent to it), its log to the modem's, its +/// changes to the main thread. +final class JobLink: NSObject, DteOut, LogOut, Changed, @unchecked Sendable { + private let session: ModemSession + private let onChange: @MainActor () -> Void + + init(session: ModemSession, onChange: @escaping @MainActor () -> Void) { + self.session = session + self.onChange = onChange + } + + func write(latin1: String) -> Bool { + guard let d = latin1.data(using: .isoLatin1) else { return false } + return session.send(d) + } + + func log(line: String) { session.engineLog(line) } + + func changed() { + let f = onChange + Task { @MainActor in f() } + } +} + +/// a line for the log, from Kotlin +final class LogLink: NSObject, LogOut, @unchecked Sendable { + private let f: (String) -> Void + init(_ f: @escaping (String) -> Void) { self.f = f } + func log(line: String) { f(line) } +} + +/// octets between Swift and Kotlin: Latin-1 text, a character an octet +enum Octets { + static func latin1(_ d: Data) -> String { String(data: d, encoding: .isoLatin1) ?? "" } + static func data(_ s: String) -> Data { s.data(using: .isoLatin1) ?? Data() } +} + +/// where the app keeps files: in its Documents (the Files app shows them, "On My iPhone › D-Modem") +enum AppFolders { + static var documents: URL { + FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + } + + /// received files (transfers) + static var received: URL { folder("Received") } + /// faxes received, as PDFs + static var faxes: URL { folder("Faxes") } + + private static func folder(_ name: String) -> URL { + let u = documents.appendingPathComponent(name, isDirectory: true) + try? FileManager.default.createDirectory(at: u, withIntermediateDirectories: true) + return u + } + + /// the files in [dir], newest first + static func files(_ dir: URL) -> [URL] { + let keys: [URLResourceKey] = [.contentModificationDateKey, .isRegularFileKey] + let all = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: keys)) ?? [] + return all.filter { (try? $0.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true } + .sorted { + let a = (try? $0.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast + let b = (try? $1.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast + return a > b + } + } +} diff --git a/ios/DModem/Sources/JobsModel.swift b/ios/DModem/Sources/JobsModel.swift new file mode 100644 index 0000000..48fbf67 --- /dev/null +++ b/ios/DModem/Sources/JobsModel.swift @@ -0,0 +1,248 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +import DModemKit +import DModemShared +import Foundation + +/// The modem lent to one job at a time, as the shared Kotlin runs them: a +/// fax call, a file transfer, dial-up internet. The DTE is the job's while +/// it lasts (the terminal sees none of it), back to the terminal after +/// with what the job didn't read. +@MainActor +final class JobsModel: ObservableObject { + /// the fax call (going, or how the last one ended) + @Published private(set) var fax: FaxJob.State? + /// the transfer (going, or how the last one ended), and which way + @Published private(set) var transfer: TransferState? + @Published private(set) var transferSending = false + /// the dial-up link (going, or how the last one ended) + @Published private(set) var internet: DialUpJob.State? + /// the remote waits for files (rz): the terminal offers to pick some + @Published var filesWanted = false + /// pages being drawn for a fax + @Published private(set) var preparing = false + /// why the last fax couldn't start (its document unreadable) + @Published var faxError: String? + + private let session: ModemSession + private let settings: () -> ModemSettings + private var faxJob: FaxJob? + private var transferJob: TransferJob? + private var dialUp: DialUpJob? + private var tunnel: UdpPacketTunnel? + private var sawOnline = false + + init(session: ModemSession, settings: @escaping () -> ModemSettings) { + self.session = session + self.settings = settings + } + + var running: Bool { faxJob != nil || transferJob != nil || dialUp != nil || preparing } + + /// why a job can't start now (a call to make: not while the modem's in one), or nil + private func busy(call: Bool) -> String? { + if session.run != .running { return "the modem is off" } + if running || session.claimed { return "the modem is in use" } + if call && session.status.offHook { return "the modem is in a call" } + return nil + } + + /// the DTE to [job]'s feed: false (and nothing started) if it can't be had + private func lend(_ feed: @escaping (String) -> Void) -> Bool { + session.claim { d in feed(Octets.latin1(d)) } + } + + private func link(_ refresh: @escaping @MainActor (JobsModel) -> Void) -> JobLink { + JobLink(session: session) { [weak self] in + guard let self else { return } + refresh(self) + } + } + + // MARK: fax + + /// [documents]' pages faxed to [number]: nil when it's started, else why it can't + func sendFax(number: String, documents: [URL]) -> String? { + if let b = busy(call: true) { return b } + let n = number.trimmingCharacters(in: .whitespaces) + if n.isEmpty { return "no number" } + if documents.isEmpty { return "no document" } + let s = settings() + faxError = nil + preparing = true + Task.detached { [weak self] in + let pages: Result<[FaxPage], Error> = Result { try documents.flatMap { try FaxDocuments.pages($0, fine: s.faxFine) } } + await self?.faxPagesReady(pages, number: n, settings: s) + } + return nil + } + + private func faxPagesReady(_ pages: Result<[FaxPage], Error>, number: String, settings s: ModemSettings) { + preparing = false + let l = link { $0.refreshFax() } + let job = FaxJob(out: l, log: l, changed: l) + switch pages { + case .failure(let e): + faxError = e.localizedDescription + return + case .success(let p): + guard lend({ job.feed(latin1: $0) }) else { + faxError = "the modem is in use" + return + } + faxJob = job + job.send(number: number, pages: p, ident: s.faxIdent, ecm: s.faxEcm, maxBps: Int32(s.faxMaxBps)) + } + } + + /// the call ringing answered as a fax: nil when it's started, else why it can't + func answerFax() -> String? { + if let b = busy(call: false) { return b } + let s = settings() + let l = link { $0.refreshFax() } + let job = FaxJob(out: l, log: l, changed: l) + guard lend({ job.feed(latin1: $0) }) else { return "the modem is in use" } + faxJob = job + let f = DateFormatter() + f.dateFormat = "yyyyMMdd-HHmmss" + f.locale = Locale(identifier: "en_US_POSIX") + job.answer(ident: s.faxIdent, ecm: s.faxEcm, maxBps: Int32(s.faxMaxBps), + into: PosixFolderIncoming(dir: AppFolders.faxes.path), fileName: "fax-\(f.string(from: Date())).pdf") + return nil + } + + func cancelFax() { faxJob?.cancel() } + + func dismissFax() { if faxJob == nil { fax = nil; faxError = nil } } + + private func refreshFax() { + guard let job = faxJob else { return } + fax = job.state + if job.state?.running == false { + faxJob = nil + session.release(leftover: Octets.data(job.leftover)) + } + } + + // MARK: transfers + + /// the protocols' names (ZMODEM …), and what each is called + static var protocols: [String] { TransferJob.companion.protocols } + static func label(_ p: String) -> String { TransferJob.companion.label(protocolName: p) } + static func batch(_ p: String) -> Bool { TransferJob.companion.batch(protocolName: p) } + + /// files received by [proto] into Documents/Received ([first]: what came that started it) + @discardableResult + func receiveFiles(_ proto: String, first: Data = Data()) -> String? { + if let b = busy(call: false) { return b } + let l = link { $0.refreshTransfer() } + let job = TransferJob(protocolName: proto, sending: false, out: l, log: l, changed: l) + guard lend({ job.feed(latin1: $0) }) else { return "the modem is in use" } + transferJob = job + transferSending = false + filesWanted = false + job.receive(into: PosixFolderIncoming(dir: AppFolders.received.path), name: "received.bin") + if !first.isEmpty { job.feed(latin1: Octets.latin1(first)) } + transfer = job.state + return nil + } + + /// [files] sent by [proto] (copied first: a picked file may only be read while it's open to us) + @discardableResult + func sendFiles(_ proto: String, files: [URL]) -> String? { + if let b = busy(call: false) { return b } + let tmp = FileManager.default.temporaryDirectory.appendingPathComponent("send-\(UUID().uuidString)", isDirectory: true) + try? FileManager.default.createDirectory(at: tmp, withIntermediateDirectories: true) + var out: [Outgoing] = [] + for u in files { + let scoped = u.startAccessingSecurityScopedResource() + defer { if scoped { u.stopAccessingSecurityScopedResource() } } + let dest = tmp.appendingPathComponent(u.lastPathComponent) + do { try FileManager.default.copyItem(at: u, to: dest) } catch { return "can't read \(u.lastPathComponent)" } + guard let o = PosixFiles.shared.outgoing(path: dest.path) else { return "can't read \(u.lastPathComponent)" } + out.append(o) + } + if out.isEmpty { return "no files" } + let l = link { $0.refreshTransfer() } + let job = TransferJob(protocolName: proto, sending: true, out: l, log: l, changed: l) + guard lend({ job.feed(latin1: $0) }) else { return "the modem is in use" } + transferJob = job + transferSending = true + filesWanted = false + job.send(files: out) + transfer = job.state + return nil + } + + func cancelTransfer() { transferJob?.cancel() } + + func dismissTransfer() { if transferJob == nil { transfer = nil } } + + private func refreshTransfer() { + guard let job = transferJob else { return } + transfer = job.state + if !job.state.running { + transferJob = nil + session.release(leftover: Octets.data(job.leftover)) + } + } + + /// what came for the terminal, looked at for a remote starting a transfer: true when a job took it + func remoteStarts(_ data: Data) -> Bool { + if running { return false } + switch TransferJob.companion.detect(latin1: Octets.latin1(data)) { + case "ZMODEM_SEND": return receiveFiles("ZMODEM", first: data) == nil + case "KERMIT_SEND": return receiveFiles("KERMIT", first: data) == nil + case "ZMODEM_RECEIVE": + filesWanted = true + return false + default: return false + } + } + + // MARK: dial-up internet + + /// the ISP dialled and PPP up, the phone's traffic through it: nil when it's started, else why not + func connectInternet() -> String? { + if let b = busy(call: true) { return b } + let s = settings() + if s.ispNumber.trimmingCharacters(in: .whitespaces).isEmpty { return "no number for the ISP" } + let l = link { $0.refreshInternet() } + let job = DialUpJob(out: l, log: l, changed: l) + guard lend({ job.feed(latin1: $0) }) else { return "the modem is in use" } + let t = UdpPacketTunnel(job: job, starter: VpnTunnel()) + dialUp = job + tunnel = t + sawOnline = false + job.connect(number: s.ispNumber, user: s.ispUser, password: s.ispPassword, script: s.ispScript, + initCommands: s.ispInit, tunnel: t) + internet = job.state + return nil + } + + func disconnectInternet() { dialUp?.disconnect() } + + /// how long the link has been up (ms) + var upMs: Int64 { dialUp?.upMs ?? 0 } + + func dismissInternet() { if dialUp == nil { internet = nil } } + + /// the modem's status changed: the link down when the call is + func statusChanged(online: Bool, running: Bool) { + guard let d = dialUp else { return } + if !running { d.lineDropped(); return } + // (once the modem has said it's online: one that doesn't say isn't watched) + if online { sawOnline = true } + if sawOnline && !online && d.state.connected { d.lineDropped() } + } + + private func refreshInternet() { + guard let job = dialUp else { return } + internet = job.state + if !job.state.running { + dialUp = nil + tunnel = nil + session.release(leftover: Octets.data(job.leftover)) + } + } +} diff --git a/ios/DModem/Sources/ModemAudio.swift b/ios/DModem/Sources/ModemAudio.swift index fbd1862..71a6077 100644 --- a/ios/DModem/Sources/ModemAudio.swift +++ b/ios/DModem/Sources/ModemAudio.swift @@ -46,6 +46,20 @@ final class ModemAudio: @unchecked Sendable { } } + /// the session given back (CallKit's call activated it): the engine playing again + func resume() { + lock.lock(); defer { lock.unlock() } + guard running, !engine.isRunning else { return } + do { + try engine.start() + // (the quiet re-queued itself as the engine stopped: it plays on) + player.play() + quiet.play() + } catch { + NSLog("modem audio: \(error)") + } + } + func end() { lock.lock(); defer { lock.unlock() } if !running { return } diff --git a/ios/DModem/Sources/PeerLine.swift b/ios/DModem/Sources/PeerLine.swift index 9400696..c45f967 100644 --- a/ios/DModem/Sources/PeerLine.swift +++ b/ios/DModem/Sources/PeerLine.swift @@ -24,8 +24,8 @@ final class PeerLineController: NSObject, NetServiceDelegate, @unchecked Sendabl 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) }, + events: LogLink { e in Engine.shared.peerEvent(e) }, + log: LogLink { [weak session] l in session?.engineLog("line: " + l) }, ringMs: 3000) let err = h.start(listen: settings.listen) lock.lock() diff --git a/ios/DModem/Sources/TransferView.swift b/ios/DModem/Sources/TransferView.swift new file mode 100644 index 0000000..f74a1a0 --- /dev/null +++ b/ios/DModem/Sources/TransferView.swift @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +import DModemShared +import QuickLook +import SwiftUI + +/// File transfers on the call (the terminal's): files sent to the remote +/// or received from it by ZMODEM, YMODEM, XMODEM or Kermit, how far it has +/// got, the files received (Documents/Received). A remote's sz or kermit +/// -s starts one by itself; its rz asks for files here. +struct TransferView: View { + @ObservedObject var jobs: JobsModel + @Environment(\.dismiss) private var dismiss + @AppStorage("transferProtocol") private var proto = "ZMODEM" + @State private var picking = false + @State private var error: String? + @State private var received: [URL] = [] + @State private var preview: URL? + + var body: some View { + NavigationStack { + Form { + if let t = jobs.transfer { progress(t) } + if jobs.filesWanted { + Section { Text("The remote is waiting for files (rz): choose them to send.").foregroundStyle(.orange) } + } + Section { + Picker("Protocol", selection: $proto) { + ForEach(JobsModel.protocols, id: \.self) { Text(JobsModel.label($0)).tag($0) } + } + Button(JobsModel.batch(proto) ? "Send files" : "Send a file") { picking = true } + .disabled(jobs.running) + Button("Receive") { error = jobs.receiveFiles(proto) } + .disabled(jobs.running) + } footer: { + Text("Start the remote's side first: \(remoteHint)") + } + if let e = error { + Section { Text(e).foregroundStyle(.red) } + } + Section("Received") { + if received.isEmpty { Text("None yet").foregroundStyle(.secondary) } + ForEach(received, id: \.self) { u in + HStack { + Button(u.lastPathComponent) { preview = u } + Spacer() + ShareLink(item: u) { Image(systemName: "square.and.arrow.up") }.buttonStyle(.borderless) + } + } + .onDelete { idx in + for i in idx { try? FileManager.default.removeItem(at: received[i]) } + reload() + } + } + } + .navigationTitle("File transfer") + .navigationBarTitleDisplayMode(.inline) + .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } } + .fileImporter(isPresented: $picking, allowedContentTypes: [.item], allowsMultipleSelection: JobsModel.batch(proto)) { r in + if case .success(let urls) = r, !urls.isEmpty { error = jobs.sendFiles(proto, files: urls) } + } + .quickLookPreview($preview) + .onAppear(perform: reload) + .onChange(of: jobs.transfer?.running) { _ in reload() } + } + } + + /// what to type at the remote's shell + private var remoteHint: String { + switch proto { + case "ZMODEM": return "sz file (it sends), rz (it receives; ZMODEM starts by itself either way)" + case "YMODEM": return "sb file, rb" + case "XMODEM": return "sx file, rx -c file" + case "XMODEM_1K": return "sx -k file, rx -c file" + default: return "kermit -i -s file, kermit -i -r" + } + } + + @ViewBuilder private func progress(_ t: TransferState) -> some View { + Section { + let p = t.progress + Text(t.running ? (jobs.transferSending ? "Sending" : "Receiving") : (t.result == "" ? "Done" : "Stopped")) + .font(.headline) + if !p.file.isEmpty { + Text(p.file) + if p.size > 0 { + ProgressView(value: Double(p.bytes), total: Double(p.size)) + Text("\(bytes(p.bytes)) of \(bytes(p.size))").foregroundStyle(.secondary) + } else { + Text(bytes(p.bytes)).foregroundStyle(.secondary) + } + } + if p.files > 0 { Text("\(p.files) file\(p.files == 1 ? "" : "s") done") } + if p.errors > 0 { Text("\(p.errors) block\(p.errors == 1 ? "" : "s") sent again").foregroundStyle(.secondary) } + if let r = t.result, !r.isEmpty { Text(r).foregroundStyle(.red) } + if t.running { + Button("Cancel", role: .destructive) { jobs.cancelTransfer() } + } else { + Button("Dismiss") { jobs.dismissTransfer() } + } + } + } + + private func bytes(_ n: Int64) -> String { ByteCountFormatter.string(fromByteCount: n, countStyle: .file) } + + private func reload() { received = AppFolders.files(AppFolders.received) } +} diff --git a/ios/DModem/Sources/VpnTunnel.swift b/ios/DModem/Sources/VpnTunnel.swift new file mode 100644 index 0000000..c3bfe96 --- /dev/null +++ b/ios/DModem/Sources/VpnTunnel.swift @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +import DModemShared +import Foundation +import NetworkExtension + +/// The phone's traffic through the dial-up link: the app's packet tunnel +/// (the DModemTunnel extension) started with the link's address and DNS, +/// told where the shared Kotlin's UdpPacketTunnel listens for its packets. +/// The first time, iOS asks the user to allow the VPN configuration. +final class VpnTunnel: NSObject, TunnelStarter, @unchecked Sendable { + static let extensionId = "com.neodesktop.dmodem.tunnel" + private var manager: NETunnelProviderManager? + + /// (on the link's thread, never the main one: it waits for the system) + func start(address: String, dns: String, mtu: Int32, port: Int32) -> Bool { + let done = DispatchSemaphore(value: 0) + let result = Started() + Task { + do { + let m = try await Self.manager() + try m.connection.startVPNTunnel(options: [ + "address": address as NSString, "dns": dns as NSString, + "mtu": NSNumber(value: mtu), "port": NSNumber(value: port), + ]) + self.manager = m + result.ok = true + } catch { + NSLog("vpn: \(error)") + } + done.signal() + } + done.wait() + return result.ok + } + + /// (whether it started, set by the task the start waits for) + private final class Started: @unchecked Sendable { var ok = false } + + func stop() { + manager?.connection.stopVPNTunnel() + manager = nil + } + + /// the app's VPN configuration: found, or made (and saved, which the user allows) + private static func manager() async throws -> NETunnelProviderManager { + let all = try await NETunnelProviderManager.loadAllFromPreferences() + let m = all.first { ($0.protocolConfiguration as? NETunnelProviderProtocol)?.providerBundleIdentifier == extensionId } + ?? NETunnelProviderManager() + let p = NETunnelProviderProtocol() + p.providerBundleIdentifier = extensionId + p.serverAddress = "Dial-up" + m.protocolConfiguration = p + m.localizedDescription = "D-Modem dial-up" + m.isEnabled = true + try await m.saveToPreferences() + // (loaded again after a save, or the start fails) + try await m.loadFromPreferences() + return m + } +} diff --git a/ios/DModem/Tunnel/PacketTunnelProvider.swift b/ios/DModem/Tunnel/PacketTunnelProvider.swift new file mode 100644 index 0000000..78bf95f --- /dev/null +++ b/ios/DModem/Tunnel/PacketTunnelProvider.swift @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Copyright (C) 2026 Neo-Desktop +import Foundation +import NetworkExtension + +/// The dial-up link as the phone's VPN: its address and DNS (from the app, +/// which has the modem and PPP), every IPv4 packet to the app as a UDP +/// datagram on the loopback and the app's back to the system. (The +/// extension runs apart from the app; the loopback isn't routed through +/// the tunnel.) +final class PacketTunnelProvider: NEPacketTunnelProvider { + private var fd: Int32 = -1 + private var app = sockaddr_in() + private let lock = NSLock() + private var running = false + + override func startTunnel(options: [String: NSObject]?, completionHandler: @escaping (Error?) -> Void) { + guard let o = options, let address = o["address"] as? String, let port = (o["port"] as? NSNumber)?.uint16Value else { + completionHandler(NSError(domain: "DModemTunnel", code: 1, userInfo: [NSLocalizedDescriptionKey: "start it from D-Modem's Internet screen"])) + return + } + let dns = ((o["dns"] as? String) ?? "").split(separator: ",").map(String.init) + let mtu = (o["mtu"] as? NSNumber)?.intValue ?? 1500 + + let s = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "127.0.0.1") + let v4 = NEIPv4Settings(addresses: [address], subnetMasks: ["255.255.255.255"]) + v4.includedRoutes = [NEIPv4Route.default()] + s.ipv4Settings = v4 + if !dns.isEmpty { s.dnsSettings = NEDNSSettings(servers: dns) } + s.mtu = NSNumber(value: mtu) + + app.sin_len = UInt8(MemoryLayout.size) + app.sin_family = sa_family_t(AF_INET) + app.sin_port = port.bigEndian + app.sin_addr.s_addr = inet_addr("127.0.0.1") + fd = socket(AF_INET, SOCK_DGRAM, 0) + guard fd >= 0 else { + completionHandler(NSError(domain: "DModemTunnel", code: 2, userInfo: [NSLocalizedDescriptionKey: "no socket"])) + return + } + setTunnelNetworkSettings(s) { [weak self] err in + guard let self, err == nil else { completionHandler(err); return } + self.lock.lock(); self.running = true; self.lock.unlock() + // (a hello: the app learns where we are) + self.sendToApp(Data([0])) + self.readFromApp() + self.readPackets() + completionHandler(nil) + } + } + + override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) { + lock.lock() + running = false + let f = fd + fd = -1 + lock.unlock() + if f >= 0 { shutdown(f, SHUT_RDWR); close(f) } + completionHandler() + } + + private var isRunning: Bool { lock.lock(); defer { lock.unlock() }; return running } + + private func sendToApp(_ d: Data) { + var to = app + d.withUnsafeBytes { p in + withUnsafePointer(to: &to) { a in + a.withMemoryRebound(to: sockaddr.self, capacity: 1) { + _ = sendto(fd, p.baseAddress, d.count, 0, $0, socklen_t(MemoryLayout.size)) + } + } + } + } + + /// the system's packets to the app + private func readPackets() { + packetFlow.readPackets { [weak self] packets, protocols in + guard let self, self.isRunning else { return } + for (p, proto) in zip(packets, protocols) where proto.int32Value == AF_INET { + self.sendToApp(p) + } + self.readPackets() + } + } + + /// the app's packets to the system + private func readFromApp() { + let f = fd + Thread.detachNewThread { [weak self] in + var buf = [UInt8](repeating: 0, count: 65536) + while let self, self.isRunning { + let n = buf.withUnsafeMutableBytes { recv(f, $0.baseAddress, $0.count, 0) } + if n <= 0 { break } + // (anything shorter than an IPv4 header: nothing to pass on) + if n >= 20 { self.packetFlow.writePackets([Data(buf[0..