diff --git a/Documentation/Packager.md b/Documentation/Packager.md index 05db173..ed3dfc2 100644 --- a/Documentation/Packager.md +++ b/Documentation/Packager.md @@ -35,7 +35,7 @@ again at every launch, since it may have changed since. | … at the same version or later | warning: methods added later resolve as absent | | The bundle has `_CodeSignature/CodeResources`, and it matches every file's SHA-256 | error: the runner loads no library its bundle doesn't vouch for | | `lib//libapp.so` is there, and is a shared library for the target's machine and word size | error | -| A declared capability this host has no contract for (motion, NFC, …) | warning | +| A declared capability this host has no contract for (notifications, …) | warning | `guest.py` has checked the rest of the library when it built it: that it names no other library, binds as it loads, exports the three guest exports diff --git a/Documentation/Plan.md b/Documentation/Plan.md index cc09348..615002f 100644 --- a/Documentation/Plan.md +++ b/Documentation/Plan.md @@ -52,7 +52,7 @@ contracts. D-Bus is PureSwift/DBus, in Swift, without libdbus. | arm64 and x86_64 Linux with glibc (Debian 13, Ubuntu 24.04+) | armv7, musl | | Native slices, loaded by the runner | `App.wasm`, in an engine in the runner; wasm2c for a target a bundle lacks, before it's installed | | Wayland and X11 through SDL3; a headless driver for tests | Multiple windows | -| `Renderer`, `BluetoothCentral` and friends, GL surfaces, web views, files, settings, model stores, date and number formatting, HTTP, the device, location, documents, motion, the built-ins | NFC (neard) | +| `Renderer`, `BluetoothCentral` and friends, GL surfaces, web views, files, settings, model stores, date and number formatting, HTTP, the device, location, documents, motion, NFC tags, the built-ins | | ## 2. Process model @@ -104,8 +104,9 @@ timers for `schedule`. | `LinuxLocation` | `LocationManager`, `Location` and `Heading` over GeoClue 2 (§11) | | `LinuxDocuments` | `Documents`: AppRuntime's `HostDocuments` with the desktop portal's file chooser, and bookmarks (§12) | | `LinuxMotion` | `MotionManager` and `Altimeter` over the kernel's IIO sensors in sysfs, and an unavailable `Pedometer` and `ActivityRecognizer` (§13) | +| `LinuxNFC` | `NFCReader`, `NFCTag`, `NDEFMessage` and `NDEFRecord` over neard (§14) | | `LinuxHostApp` | `main`: reads the app's keys, starts the host, and runs Cacao's SDL loop with one window showing the guest's first renderer | -| `LinuxPackager`, `linux-app` | The packager (§15, [Packager.md](Packager.md)) | +| `LinuxPackager`, `linux-app` | The packager (§16, [Packager.md](Packager.md)) | The package depends on AppRuntime without its `GuestExports` trait, like DarwinAppRuntime, so the slice's `rt_dispatch` and `rt_finalize` are the @@ -513,7 +514,7 @@ of its own, made when it first needs one: ### 11.1 D-Bus `LinuxDBus` is what Bluetooth, Location, the device's orientation and -proximity (iio-sensor-proxy) and the desktop portal, and later NFC (neard), +proximity (iio-sensor-proxy), NFC (neard) and the desktop portal share. `Bus.system` and `Bus.session` are one connection each per process, made on first use through PureSwift/DBus, which speaks D-Bus in Swift, without libdbus; its @@ -641,7 +642,60 @@ polls. Reading them needs no permission. noticed until it's started again, and the magnetometer isn't calibrated. None of it has run on real sensors. -## 14. Testing +## 14. NFC + +`LinuxNFC` is the NFC contracts (AppRuntime's `NFC.md`) over neard, the +Linux NFC daemon (`org.neard` on the system bus), which drives the +kernel's NFC adapters: the reader role, reading and writing NDEF. neard +publishes its adapters (`/org/neard/nfc0`), the tags in their field +(`…/tag0`) and each tag's records (`…/tag0/record0`) through +`org.freedesktop.DBus.ObjectManager` at `/`. `NeardBus` abstracts the +connection, so the contract is tested with a fake neard. What follows is +from neard's source, not its documentation, which differs in places (the +ISO 15693 protocol is `ISO-15693`, and there's no `TagFound` signal). + +| | neard | +|---|---| +| `availability` | No neard, or no adapter: `unsupported`; adapters all off (`Powered`): `disabled`. Asked with `GetManagedObjects`, waited for | +| `begin` | The first adapter that's on: `StartPollLoop("Initiator")`, then `didBecomeActive`. A tag already in the field is found as it is, since neard won't poll over one. One session at a time in the process: neard has one poll loop per adapter | +| A tag | `InterfacesAdded` of `org.neard.Tag` under the adapter, then neard's own signal that it read the records, `org.neard.Tag.PropertyChanged("Records", …)`, which can come first; then `didDetect`, with the records as they are then. A tag with no NDEF gets no such signal, so it's found after a second without one. A kind not asked for is left out | +| Polling | neard stops polling when it finds a tag, and doesn't start again, with a tag in the field or after one leaves, so `restartPolling`, and a tag left out, poll again once the field is empty | +| `connect` | neard keeps a tag it found connected: the tag in the field | +| `type` | `Protocol`: `ISO-DEP` `iso7816`, `MIFARE` `miFare` (`Jewel`, NFC Forum Type 1, is `unknown`, and also ISO 14443), `Felica` `feliCa`, `ISO-15693` `iso15693`; all `ndef` in an NDEF session | +| `identifier` | `Uid`; empty in an NDEF session, as on iOS | +| `queryNDEFStatus` | `ReadOnly`: `readOnly` or `readWrite`. neard doesn't say how much a tag holds, so the capacity is 0 | +| `readNDEF` | The tag's records (below); nil for none | +| `writeNDEF` | `Tag.Write(a{sv})`: one record's fields, or each record's under `Records`. neard reads the tag again after a write, and a read after it waits for that (or a second) | +| `writeLock`, `transceive` | neard has no way to lock a tag or send it a raw command: `unsupported` (an NDEF session's `transceive` is `notAvailableInNDEFSession`) | +| `invalidate` | `StopPollLoop`; the delegate told once, on the next turn | + +- **Records.** neard parses a tag's message itself and publishes each + record it knows as properties, not bytes, and writes only what it can + make from such properties. So reading gives text (re-encoded as UTF-8), + URIs, MIME types with their payload, Smart Posters (as an `Sp` record + holding the URI and the title) and Android application records + (`android.com:pkg`), and leaves out handovers. Writing takes text, URI + and MIME records, without identifiers, and refuses anything else, an + empty message, and the Wi-Fi type (`application/vnd.wfa.wsc`), for which + neard makes a record of its own, with `invalidParameter`. +- **Operations** run one at a time per tag, in order, each with one + callback on the next turn. A tag leaving (`InterfacesRemoved`) fails what + waits with `tagConnectionLost`; one from an earlier detection, or not + connected, is `tagNotConnected`. +- **Errors.** neard answers most failures as `org.neard.Error.Failed` + with `strerror`'s text: busy is `systemBusy`, no such device `disabled`. + A write it can't make or that fails is `InvalidArguments`, so a failed + write is `unknown`, and logged; `PermissionDenied` is `tagReadOnly`, + `InProgress` `systemBusy`. The adapter turned off or gone, or the bus + closing, ends the session. +- **`nfc`** asks for nothing: NFC has no prompt on any platform. +- **Not yet**: raw commands. The kernel has them (`AF_NFC` raw sockets), + but neard holds the tag it found, so they'd need neard stopped or a + version of it that passes them on. Card emulation (neard's + `StartEmulation`) and peer-to-peer aren't part of the contract. It + hasn't run against real neard and an adapter. + +## 15. Testing - `LinuxUI`: DarwinUI's tests, on Cacao (§5). - `LinuxBluetooth`: the contract against a fake `BlueZBus` that plays @@ -712,6 +766,18 @@ polls. Reading them needs no permission. kept; the files the app is opened with. The packager accepts the contracts with `userFiles`, and writes `MimeType=`. It hasn't run against a real portal. +- `LinuxNFC`: the contract against a fake `NeardBus` that plays neard's + adapter, tags, records and signals, and answers on the main loop: + availability; a session that finds a tag, reads it and ends; the + records' signal before the tag; a tag without NDEF; kinds not asked for, + and polling again once the field is empty; an NDEF session; a tag already + in the field; sessions that can't begin, one at a time, and invalidating + before neard answers; the adapter turned off or gone, and the bus + closing; operations before a connection, and a tag leaving; writing, and + reading after neard read the tag again, or gave up; what neard can't + write, a read-only tag, locking and raw commands. neard's records as NDEF + and back, and the NDEF encoding. The packager accepts the contracts with + `nfc`. - End to end: AppRuntime's `ExampleUI`, `ExampleGL` and `ExampleModel` bundles, their `linux-arm64` `libapp.so` loaded by `linux-app-host` and run headless with SDL's `offscreen` driver, each first frame saved with @@ -724,7 +790,7 @@ polls. Reading them needs no permission. `bluetoothd`. Real GeoClue needs a session with an agent, or the app allowed in `geoclue.conf`. -## 15. Phases +## 16. Phases 1. **Host runtime and player**: `LinuxHost`, `LinuxUI`, `LinuxBluetooth`, `LinuxHostApp`; `ExampleUI` runs in Docker. @@ -732,14 +798,15 @@ polls. Reading them needs no permission. thinned to the target's `libapp.so`, a `.desktop` file and icon, for the runner; later Flatpak and AppImage, whose manifests carry the capabilities (`--system-talk-name=org.bluez` for `bluetooth`). -3. **More contracts**: NFC (neard). Formatting and HTTP are done: - AppRuntime's `RuntimeFormatting` and `RuntimeNetworking` (§3), and so - are the device (§10), location (§11), over GeoClue2, documents (§12), - over the desktop portal, and motion (§13), over IIO. +3. **More contracts**: formatting and HTTP are done: AppRuntime's + `RuntimeFormatting` and `RuntimeNetworking` (§3), and so are the + device (§10), location (§11), over GeoClue2, documents (§12), over + the desktop portal, motion (§13), over IIO, and NFC (§14), over + neard. 4. **Player**: what DarwinUI and Cacao add: Cacao's AT-SPI bridge, input replay for end-to-end tests. -## 16. Open questions +## 17. Open questions - **Permissions.** Desktop Linux has no prompts for Bluetooth; Flatpak's portals cover location and the camera. `Permissions.request` answers from diff --git a/Package.swift b/Package.swift index d85fc40..5fedb54 100644 --- a/Package.swift +++ b/Package.swift @@ -70,6 +70,7 @@ let package = Package( .library(name: "LinuxDBus", targets: ["LinuxDBus"]), .library(name: "LinuxLocation", targets: ["LinuxLocation"]), .library(name: "LinuxMotion", targets: ["LinuxMotion"]), + .library(name: "LinuxNFC", targets: ["LinuxNFC"]), .library(name: "LinuxHostApp", targets: ["LinuxHostApp"]), .executable(name: "linux-app-host", targets: ["LinuxAppHost"]), .executable(name: "linux-app", targets: ["LinuxAppTool"]), @@ -210,6 +211,16 @@ let package = Package( swiftSettings: host ), + // MARK: - NFC + + // neard on the system bus. + .target( + name: "LinuxNFC", + dependencies: ["LinuxHost", "LinuxDBus", runtime("DynamicNFC"), runtime("DynamicRuntime"), runtime("RuntimeNative"), + .product(name: "DBus", package: "DBus")], + swiftSettings: host + ), + // MARK: - App // What the runner's process supplies that libc may not @@ -217,7 +228,7 @@ let package = Package( .target(name: "CLinuxHost"), .target( name: "LinuxHostApp", - dependencies: ["LinuxHost", "LinuxUI", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", "CLinuxHost", runtime("CRuntime"), runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), + dependencies: ["LinuxHost", "LinuxUI", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", "LinuxNFC", "CLinuxHost", runtime("CRuntime"), runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), runtime("DynamicGraphics"), .product(name: "CacaoSDL", package: "Cacao")], swiftSettings: host ), @@ -241,7 +252,7 @@ let package = Package( // doesn't build Cacao. .target( name: "LinuxPackager", - dependencies: ["LinuxHost", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), runtime("DynamicUI"), + dependencies: ["LinuxHost", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", "LinuxNFC", runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), runtime("DynamicUI"), .product(name: "Crypto", package: "swift-crypto")] ), .executableTarget( @@ -271,6 +282,8 @@ let package = Package( .testTarget(name: "LinuxDBusTests", dependencies: ["LinuxDBus", .product(name: "DBus", package: "DBus")], swiftSettings: host), .testTarget(name: "LinuxLocationTests", dependencies: ["LinuxLocation", "LinuxDBus", runtime("DynamicLocation"), .product(name: "DBus", package: "DBus")], swiftSettings: host), + .testTarget(name: "LinuxNFCTests", dependencies: ["LinuxNFC", "LinuxDBus", runtime("DynamicNFC"), .product(name: "DBus", package: "DBus")], + swiftSettings: host), .testTarget(name: "LinuxDocumentsTests", dependencies: ["LinuxDocuments", "LinuxDBus", runtime("DynamicDocuments"), runtime("RuntimeDocuments"), runtime("DynamicFiles"), runtime("RuntimeHost"), runtime("RuntimeNative"), .product(name: "DBus", package: "DBus")], diff --git a/README.md b/README.md index 8856cc3..3827284 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,7 @@ added to its database between launches: | `LinuxLocation` | `LocationManager`: the device's location from GeoClue 2 on the system bus, which its agent authorizes by the app's desktop ID; no heading ([plan](Documentation/Plan.md) §11) | | `LinuxDocuments` | `Documents`: AppRuntime's `HostDocuments` with the desktop portal's file chooser on the session bus, for opening, folders and saving, and bookmarks in the app's data ([plan](Documentation/Plan.md) §12) | | `LinuxMotion` | Motion: the accelerometer, gyroscope, magnetometer and barometer from the kernel's IIO sensors in sysfs, device motion fused from them, and a pedometer and activity recognizer that are unavailable ([plan](Documentation/Plan.md) §13) | +| `LinuxNFC` | `NFCReader`, `NFCTag`, `NDEFMessage`, `NDEFRecord`: reading and writing NDEF tags through neard on the system bus; no raw commands or locking ([plan](Documentation/Plan.md) §14) | | `LinuxHostApp`, `linux-app-host` | The app's `main`: the host, and Cacao's window and loop. It also registers AppRuntime's `RuntimeFormatting`, dates and numbers over Swift Foundation, and `RuntimeNetworking`, HTTP over `URLSession` and libcurl ([plan](Documentation/Plan.md) §3) | | `LinuxPackager`, `linux-app` | The packager: validation, thinning a bundle to one target, the install tree, PortMaster ports | diff --git a/Sources/LinuxHostApp/HostApp.swift b/Sources/LinuxHostApp/HostApp.swift index e1cb370..9ea6b50 100644 --- a/Sources/LinuxHostApp/HostApp.swift +++ b/Sources/LinuxHostApp/HostApp.swift @@ -11,6 +11,7 @@ import LinuxDocuments import LinuxGraphics import LinuxLocation import LinuxMotion +import LinuxNFC import LinuxWebKit import LinuxUI import RuntimeFormatting @@ -38,11 +39,11 @@ public enum HostApp { /// Bluetooth, GL surfaces and web pages, which the player shows, the /// app's files, settings and model stores, AppRuntime's date and number /// formatting and its HTTP client over Swift Foundation, the device, - /// location, the user's documents, and motion sensors. + /// location, the user's documents, motion sensors and NFC tags. public static let modules: [any HostModule.Type] = [ DarwinUI.self, LinuxBluetooth.self, LinuxGraphics.self, LinuxWebKit.self, LinuxFiles.self, LinuxDefaults.self, LinuxModelStore.self, HostFormattingModule.self, HostNetworkingModule.self, LinuxDeviceModule.self, LinuxLocation.self, - LinuxDocuments.self, LinuxMotion.self, + LinuxDocuments.self, LinuxMotion.self, LinuxNFC.self, ] /// Points AppRuntime's modules at this host: networking's callbacks, diff --git a/Sources/LinuxNFC/LinuxNFC.swift b/Sources/LinuxNFC/LinuxNFC.swift new file mode 100644 index 0000000..2746850 --- /dev/null +++ b/Sources/LinuxNFC/LinuxNFC.swift @@ -0,0 +1,54 @@ +import DynamicNFC +import DynamicRuntime +import LinuxHost +import RuntimeNative + +/// The NFC contracts over neard (`Plan.md` §14): the reader role, reading +/// and writing NDEF. Main loop only. +public enum LinuxNFC: HostModule { + + public static var contracts: [ContractDescriptor] { + [ + NFCReaderProxy.descriptor, + NFCReaderDelegateProxy.descriptor, + NFCTagProxy.descriptor, + NDEFMessageProxy.descriptor, + NDEFRecordProxy.descriptor, + ] + } + + public static func register(in registrar: some ContractRegistrar) { + NFCReaderProxy.register(LinuxNFCReader.self, in: registrar) + NFCReaderDelegateProxy.registerInterface(in: registrar) + NFCTagProxy.register(LinuxNFCTag.self, in: registrar) + NDEFMessageProxy.register(LinuxNDEFMessage.self, in: registrar) + NDEFRecordProxy.register(LinuxNDEFRecord.self, in: registrar) + } + + /// NFC has no prompt anywhere: a declared `nfc` capability is granted, + /// and the reader says whether there's hardware. + public static func permissionProviders() -> [Capability: any PermissionProvider] { + [.nfc: GrantedPermission()] + } + + // MARK: Objects passed back + + /// Finds the Swift object behind a proxy the guest passed back. Replace + /// it if the host runs on a `NativeRuntime` other than `shared`. + nonisolated(unsafe) public static var objectResolver: (DynamicObject) -> AnyObject? = { proxy in + NativeRuntime.shared.swiftObject(for: proxy) + } + + /// The implementation object behind a contract object: itself when the + /// caller is Swift, or the object a proxy stands for. Nil for an object + /// the guest made itself. + static func resolve(_ object: AnyObject, as type: T.Type) -> T? { + if let object = object as? T { + return object + } + if let proxy = object as? DynamicObject { + return objectResolver(proxy) as? T + } + return nil + } +} diff --git a/Sources/LinuxNFC/LinuxNFCReader.swift b/Sources/LinuxNFC/LinuxNFCReader.swift new file mode 100644 index 0000000..0689f50 --- /dev/null +++ b/Sources/LinuxNFC/LinuxNFCReader.swift @@ -0,0 +1,396 @@ +import DBus +import DynamicNFC +import DynamicRuntime +import LinuxDBus +import LinuxHost + +/// The `NFCReader` contract over neard (`Plan.md` §14): one adapter's poll +/// loop, and the tags it finds. Linux shows no scan sheet, so the alert +/// message is ignored, and there's no time limit. Main loop only. +public final class LinuxNFCReader: NFCReader { + + /// neard, or a fake one in tests. + nonisolated(unsafe) public static var neard: any NeardBus = SystemNeard() + + /// How long a tag that's found waits for neard to read its records, + /// in nanoseconds: one without NDEF has none to read, and neard doesn't + /// say so. + nonisolated(unsafe) public static var recordsTimeout: Int64 = 1_000_000_000 + + /// The session that's polling: neard has one poll loop per adapter. + nonisolated(unsafe) static weak var polling: LinuxNFCReader? + + /// Kept strongly, as every host keeps a delegate. + let delegate: any NFCReaderDelegate + + private enum Phase { + case idle, starting, active, invalidated + } + + private var phase = Phase.idle + + private var types = NFCTagTypes() + + private(set) var ndefSession = false + + /// The adapter's path, once the session has one. + private var adapter: String? + + private var subscription: BusSubscription? + + /// Polling paused after a detection, until `restartPolling`. + private var paused = false + + /// Polling should start again once the field is empty: neard won't + /// start it with a tag there, nor by itself after one leaves. + private var resumeWhenEmpty = false + + /// The adapter's tags in the field, by path. + private var present: Set = [] + + /// Tags reported or left out, so each is decided once while it stays. + private var decided: Set = [] + + /// Tags found and waiting for their records. + private var waiting: [String: MainLoop.TimerToken] = [:] + + /// The tags of the last detection, and the one connected. + private(set) var tags: [LinuxNFCTag] = [] + + private(set) var connected: LinuxNFCTag? + + init(delegate: any NFCReaderDelegate) { + self.delegate = delegate + } + + deinit { + if Self.polling === self, let adapter { + Self.neard.call(adapter, Neard.adapter, "StopPollLoop", [], signature: nil) { _ in } + } + if let subscription { + Self.neard.unsubscribe(subscription) + } + for timer in waiting.values { + MainLoop.shared.cancel(timer) + } + } + + public static func make(_ delegate: any NFCReaderDelegate) -> LinuxNFCReader { + LinuxNFCReader(delegate: delegate) + } + + // MARK: Availability + + /// No neard, or no adapter: `unsupported`; adapters all off: `disabled`. + public static func availability() -> Int32 { + switch neard.objectsAndWait() { + case .success(let objects): + guard let adapter = adapter(in: objects) else { + return NFCAvailability.unsupported.rawValue + } + return (adapter.powered ? NFCAvailability.available : .disabled).rawValue + case .failure(let error): + if !error.isServiceMissing { + HostLog.error("nfc: can't ask neard: \(error)") + } + return NFCAvailability.unsupported.rawValue + } + } + + /// The first adapter that's on, else the first. + static func adapter(in objects: [String: NeardInterfaces]) -> (path: String, powered: Bool)? { + let adapters = objects.compactMap { path, interfaces in + interfaces[Neard.adapter].map { (path: path, powered: $0["Powered"]?.flag == true) } + }.sorted { $0.path < $1.path } + return adapters.first { $0.powered } ?? adapters.first + } + + // MARK: Session + + public func begin(_ tagTypes: Int32, alertMessage: String?) { + switch phase { + case .invalidated: + let delegate = delegate + MainLoop.shared.post { [self] in + delegate.didInvalidate(self, error: NFCError.systemBusy.rawValue, message: "This reader was invalidated; make a new one.") + } + return + case .starting, .active: + return + case .idle: + break + } + let types = NFCTagTypes(rawValue: tagTypes) + guard !types.isDisjoint(with: [.ndef, .iso14443, .iso15693, .iso18092]), !types.contains(.ndef) || types == .ndef else { + invalidate(with: .invalidParameter, message: "NDEF can't be combined with other tag types.") + return + } + self.types = types + ndefSession = types == .ndef + phase = .starting + Self.neard.objects { [weak self] result in + self?.start(result) + } + } + + private func start(_ result: Result<[String: NeardInterfaces], BusError>) { + guard phase == .starting else { return } + let objects: [String: NeardInterfaces] + switch result { + case .success(let all): + objects = all + case .failure(let error): + invalidate(with: .unsupported, message: "neard isn't running (\(error)).") + return + } + guard let adapter = Self.adapter(in: objects) else { + invalidate(with: .unsupported, message: "This computer has no NFC adapter.") + return + } + guard adapter.powered else { + invalidate(with: .disabled, message: "NFC is turned off.") + return + } + guard Self.polling == nil else { + invalidate(with: .systemBusy, message: "Another NFC session is active.") + return + } + self.adapter = adapter.path + Self.polling = self + present = Set(objects.keys.filter { isTag($0) && objects[$0]?[Neard.tag] != nil }) + subscription = Self.neard.subscribe { [weak self] event in + self?.handle(event) + } + let begun = { [self] in + phase = .active + delegate.didBecomeActive(self) + } + // A tag already in the field is found as it is; neard won't poll + // over it. + if let tag = present.sorted().first { + begun() + detect(tag) + return + } + startPolling { [weak self] error in + guard let self, self.phase == .starting else { return } + if let error { + self.invalidate(with: error, message: nil) + } else { + begun() + } + } + } + + public func setAlertMessage(_ message: String) {} + + public func restartPolling() { + guard phase == .active else { return } + dropTags() + paused = false + if present.isEmpty { + startPolling { error in + if let error { + HostLog.error("nfc: can't poll again: \(error)") + } + } + } else { + resumeWhenEmpty = true + } + } + + public func connect(_ tag: any NFCTag) { + guard let tag = LinuxNFC.resolve(tag, as: LinuxNFCTag.self) else { return } + let error: NFCError? + if tag.reader !== self || phase != .active || !tags.contains(where: { $0 === tag }) { + error = .tagNotConnected + } else if !tag.present { + error = .tagConnectionLost + } else { + error = nil + connected = tag + } + let delegate = delegate + MainLoop.shared.post { [self] in + delegate.didConnect(self, tag: tag, error: error?.rawValue ?? 0) + } + } + + public func invalidate(_ errorMessage: String?) { + invalidate(with: nil, message: errorMessage) + } + + public func isActive() -> Bool { + phase == .active + } + + /// Ends the session and tells the delegate once, on the next turn. + func invalidate(with error: NFCError?, message: String?) { + guard phase != .invalidated else { return } + phase = .invalidated + for timer in waiting.values { + MainLoop.shared.cancel(timer) + } + waiting = [:] + if let subscription { + Self.neard.unsubscribe(subscription) + self.subscription = nil + } + if Self.polling === self { + Self.polling = nil + if let adapter { + // Not polling, after a detection, is an error to ignore. + Self.neard.call(adapter, Neard.adapter, "StopPollLoop", [], signature: nil) { _ in } + } + } + dropTags() + let delegate = delegate + MainLoop.shared.post { [self] in + delegate.didInvalidate(self, error: error?.rawValue ?? 0, message: error == nil ? nil : message) + } + } + + private func dropTags() { + for tag in tags { + tag.drop() + } + tags = [] + connected = nil + } + + private func startPolling(_ done: @escaping (NFCError?) -> Void) { + guard let adapter else { return } + Self.neard.call(adapter, Neard.adapter, "StartPollLoop", [.string("Initiator")], signature: "s") { result in + switch result { + case .success: + done(nil) + case .failure(let error): + done(Self.error(polling: error)) + } + } + } + + // MARK: neard's changes + + private func handle(_ event: NeardEvent) { + switch event { + case .added(let path, let interfaces): + guard isTag(path), interfaces[Neard.tag] != nil else { return } + present.insert(path) + guard phase == .active, !paused, !decided.contains(path), waiting[path] == nil else { return } + waiting[path] = MainLoop.shared.schedule(after: Self.recordsTimeout) { [weak self] in + self?.waiting[path] = nil + self?.detect(path) + } + case .recordsRead(let path): + guard isTag(path) else { return } + if let tag = tags.first(where: { $0.path == path }) { + tag.recordsRead() + return + } + // neard says so before it publishes the tag, sometimes. + present.insert(path) + if let timer = waiting.removeValue(forKey: path) { + MainLoop.shared.cancel(timer) + } + guard phase == .active, !paused, !decided.contains(path) else { return } + detect(path) + case .removed(let path, let interfaces): + if path == adapter, interfaces.contains(Neard.adapter) { + invalidate(with: .unsupported, message: "The NFC adapter went away.") + return + } + guard isTag(path), interfaces.contains(Neard.tag) else { return } + present.remove(path) + decided.remove(path) + if let timer = waiting.removeValue(forKey: path) { + MainLoop.shared.cancel(timer) + } + tags.first { $0.path == path }?.leave() + if present.isEmpty, resumeWhenEmpty, phase == .active { + resumeWhenEmpty = false + startPolling { error in + if let error { + HostLog.error("nfc: can't poll again: \(error)") + } + } + } + case .changed(let path, let interface, let changed): + if path == adapter, interface == Neard.adapter, changed["Powered"]?.flag == false { + invalidate(with: .disabled, message: "NFC was turned off.") + } + case .closed: + invalidate(with: .unknown, message: "neard's bus closed.") + } + } + + /// A tag of the session's adapter: `/tagN`. + private func isTag(_ path: String) -> Bool { + guard let adapter, path.hasPrefix(adapter + "/tag") else { return false } + return !path.dropFirst(adapter.count + 1).contains("/") + } + + /// Reports the tag at `path`, with its records, if it's a kind asked + /// for. + private func detect(_ path: String) { + decided.insert(path) + Self.neard.objects { [weak self] result in + guard let self, self.phase == .active, !self.paused, + case .success(let objects) = result, let properties = objects[path]?[Neard.tag] else { + return + } + let kind = Self.kind(properties["Protocol"]?.text) + guard let kind, self.ndefSession || self.types.contains(kind.family) else { + HostLog.debug("nfc: \(path) (\(properties["Protocol"]?.text ?? "no protocol")) isn't a kind asked for") + self.resumeWhenEmpty = true + return + } + let tag = LinuxNFCTag( + path: path, + type: self.ndefSession ? .ndef : kind.type, + properties: properties, + records: NeardRecords.records(of: path, in: objects), + reader: self + ) + self.dropTags() + self.tags = [tag] + self.paused = true + self.delegate.didDetect(self, tags: self.tags) + } + } + + // MARK: Mapping + + /// A tag's `Protocol`, as the contract has it, and the polling option + /// that finds it. + static func kind(_ name: String?) -> (type: NFCTagType, family: NFCTagTypes)? { + switch name { + case "ISO-DEP": (.iso7816, .iso14443) + case "MIFARE": (.miFare, .iso14443) + // NFC Forum Type 1 (Topaz), also ISO 14443-A. + case "Jewel": (.unknown, .iso14443) + case "Felica": (.feliCa, .iso18092) + case "ISO-15693", "ISO15693": (.iso15693, .iso15693) + default: nil + } + } + + /// `StartPollLoop`'s errors. neard answers most as `Failed`, with + /// `strerror`'s text. + static func error(polling error: BusError) -> NFCError { + switch error.name { + case "org.neard.Error.InProgress": + return .systemBusy + case "org.neard.Error.Failed" where error.message.contains("busy"): + return .systemBusy + case "org.neard.Error.Failed" where error.message.contains("No such device"): + return .disabled + default: + if error.isServiceMissing { + return .unsupported + } + HostLog.error("nfc: can't poll: \(error)") + return .unknown + } + } +} diff --git a/Sources/LinuxNFC/LinuxNFCTag.swift b/Sources/LinuxNFC/LinuxNFCTag.swift new file mode 100644 index 0000000..1c51aa1 --- /dev/null +++ b/Sources/LinuxNFC/LinuxNFCTag.swift @@ -0,0 +1,273 @@ +import DBus +import DynamicNFC +import LinuxDBus +import LinuxHost + +/// The `NFCTag` contract: one of neard's tags (`Plan.md` §14). Operations +/// run one at a time, in order, and each gets one delegate callback. +/// +/// neard reads a tag's message when it finds it, and again after each +/// write, so reading answers with the records it read; it has no raw +/// commands and can't lock a tag, so those fail with `unsupported`. +public final class LinuxNFCTag: NFCTag { + + let path: String + + let tagType: NFCTagType + + let uid: [UInt8] + + private(set) var readOnly: Bool + + private(set) var records: [LinuxNDEFRecord] + + private(set) weak var reader: LinuxNFCReader? + + /// In the field. neard removes a tag that's gone. + private(set) var present = true + + enum Operation { + case queryNDEF, readNDEF, writeNDEF(LinuxNDEFMessage), lock, transceive + } + + /// Operations asked for and not answered, the first running. + private var operations: [Operation] = [] + + private var running = false + + /// Counts drops, so an answer to an operation that was dropped is + /// ignored. + private var generation = 0 + + /// neard is reading the records again after a write: the timer that + /// stops waiting for it. + private var rereading: MainLoop.TimerToken? + + /// An operation that waits for the records read again. + private var afterReading: (() -> Void)? + + init(path: String, type: NFCTagType, properties: [String: DBusMessageArgument], records: [LinuxNDEFRecord], reader: LinuxNFCReader) { + self.path = path + self.tagType = type + self.uid = properties["Uid"]?.bytes ?? [] + self.readOnly = properties["ReadOnly"]?.flag ?? false + self.records = records + self.reader = reader + } + + deinit { + if let rereading { + MainLoop.shared.cancel(rereading) + } + } + + public func type() -> Int32 { tagType.rawValue } + + public func identifier() -> [UInt8] { reader?.ndefSession == true ? [] : uid } + + public func isAvailable() -> Bool { + present && reader?.connected === self + } + + public func historicalBytes() -> [UInt8]? { nil } + + public func selectedApplicationIdentifier() -> String? { nil } + + /// No raw commands through neard. + public func maximumTransceiveLength() -> Int32 { 0 } + + public func queryNDEFStatus() { perform(.queryNDEF) } + + public func readNDEF() { perform(.readNDEF) } + + public func writeNDEF(_ message: any NDEFMessage) { + perform(.writeNDEF(LinuxNDEFMessage.copy(of: message))) + } + + public func writeLock() { perform(.lock) } + + public func transceive(_ data: [UInt8]) { + guard reader?.ndefSession != true else { + answer(.transceive, error: .notAvailableInNDEFSession) + return + } + perform(.transceive) + } + + // MARK: Operations + + /// Queues an operation if the tag's connected; otherwise its callback + /// fails on the next turn. + private func perform(_ operation: Operation) { + guard let reader, reader.connected === self, reader.isActive() else { + answer(operation, error: .tagNotConnected) + return + } + guard present else { + answer(operation, error: .tagConnectionLost) + return + } + operations.append(operation) + runNext() + } + + private func runNext() { + guard !running, let operation = operations.first else { return } + running = true + let generation = generation + let finish = { [weak self] (error: NFCError?) in + guard let self, self.generation == generation else { return } + self.operations.removeFirst() + self.running = false + self.answer(operation, error: error) + self.runNext() + } + afterRecords { [self] in + switch operation { + case .queryNDEF, .readNDEF: + finish(nil) + case .writeNDEF(let message): + write(message, finish) + case .lock, .transceive: + finish(.unsupported) + } + } + } + + private func write(_ message: LinuxNDEFMessage, _ finish: @escaping (NFCError?) -> Void) { + guard !readOnly else { + finish(.tagReadOnly) + return + } + guard let attributes = NeardRecords.attributes(message) else { + HostLog.error("nfc: neard writes text, URI and MIME records only, and at least one") + finish(.invalidParameter) + return + } + LinuxNFCReader.neard.call(path, Neard.tag, "Write", [.vardict(attributes)], signature: "a{sv}") { [weak self] result in + switch result { + case .success: + self?.startRereading() + finish(nil) + case .failure(let error): + finish(Self.error(writing: error)) + } + } + } + + /// The delegate's callback for `operation`, on the next turn, so it's + /// never inside the guest's own call, and in order. + private func answer(_ operation: Operation, error: NFCError?) { + guard let reader else { return } + let delegate = reader.delegate + let code = error?.rawValue ?? 0 + let status = readOnly ? NDEFStatus.readOnly : .readWrite + let message = records.isEmpty ? nil : LinuxNDEFMessage(records) + MainLoop.shared.post { [self] in + switch operation { + case .queryNDEF: + // neard doesn't say how much a tag holds. + delegate.didQueryNDEF(reader, tag: self, status: (error == nil ? status : .notSupported).rawValue, capacity: 0, error: code) + case .readNDEF: + delegate.didReadNDEF(reader, tag: self, message: error == nil ? message : nil, error: code) + case .writeNDEF: + delegate.didWriteNDEF(reader, tag: self, error: code) + case .lock: + delegate.didLock(reader, tag: self, error: code) + case .transceive: + delegate.didTransceive(reader, tag: self, response: [], error: code) + } + } + } + + // MARK: Records + + /// Runs `body` now, or once neard has read the records again after a + /// write. + private func afterRecords(_ body: @escaping () -> Void) { + if rereading == nil { + body() + } else { + afterReading = body + } + } + + private func startRereading() { + if let rereading { + MainLoop.shared.cancel(rereading) + } + rereading = MainLoop.shared.schedule(after: LinuxNFCReader.recordsTimeout) { [weak self] in + self?.rereading = nil + self?.refresh() + } + } + + /// neard read the records again. + func recordsRead() { + guard let rereading else { return } + MainLoop.shared.cancel(rereading) + self.rereading = nil + refresh() + } + + /// Reads the records and `ReadOnly` from neard again, then runs what + /// waited for them. + private func refresh() { + let generation = generation + LinuxNFCReader.neard.objects { [weak self] result in + guard let self, self.generation == generation else { return } + if case .success(let objects) = result, let properties = objects[self.path]?[Neard.tag] { + self.records = NeardRecords.records(of: self.path, in: objects) + self.readOnly = properties["ReadOnly"]?.flag ?? self.readOnly + } + let waiting = self.afterReading + self.afterReading = nil + waiting?() + } + } + + // MARK: Leaving + + /// The tag left the field. + func leave() { + present = false + drop() + } + + /// Every operation waiting fails: the tag or the session went. + func drop() { + generation += 1 + if let rereading { + MainLoop.shared.cancel(rereading) + self.rereading = nil + } + afterReading = nil + let waiting = operations + operations = [] + running = false + for operation in waiting { + answer(operation, error: .tagConnectionLost) + } + } + + /// `Write`'s errors. + static func error(writing error: BusError) -> NFCError { + switch error.name { + case "org.neard.Error.PermissionDenied": + return .tagReadOnly + case "org.neard.Error.InProgress": + return .systemBusy + case "org.neard.Error.NotSupported": + return .ndefNotSupported + case "org.freedesktop.DBus.Error.UnknownObject", "org.freedesktop.DBus.Error.UnknownMethod": + return .tagConnectionLost + default: + if error.isServiceMissing || error == .disconnected { + return .tagConnectionLost + } + // neard answers a failed write as InvalidArguments. + HostLog.error("nfc: can't write: \(error)") + return .unknown + } + } +} diff --git a/Sources/LinuxNFC/NDEF.swift b/Sources/LinuxNFC/NDEF.swift new file mode 100644 index 0000000..1d0a8b6 --- /dev/null +++ b/Sources/LinuxNFC/NDEF.swift @@ -0,0 +1,298 @@ +import DynamicNFC +import Foundation +import LinuxHost + +/// The `NDEFRecord` contract: one record as plain bytes, as the Android +/// host keeps them. neard has records of its own kinds instead, which +/// `NeardRecords` turns these into and back. The well-known URI and text +/// records follow the NFC Forum RTDs. +public final class LinuxNDEFRecord: NDEFRecord { + + let format: NDEFTypeNameFormat + + let recordType: [UInt8] + + let recordIdentifier: [UInt8] + + let recordPayload: [UInt8] + + /// The type and identifier hold at most 255 bytes, since their lengths + /// are one byte in the encoding; longer ones are cut and logged. + init(format: NDEFTypeNameFormat, type: [UInt8], identifier: [UInt8], payload: [UInt8]) { + self.format = format + self.recordType = Self.limited(type, "type") + self.recordIdentifier = Self.limited(identifier, "identifier") + self.recordPayload = payload + } + + /// An unknown `format` is logged and recorded as `unknown`. + public static func make(format: Int32, type: [UInt8], identifier: [UInt8], payload: [UInt8]) -> LinuxNDEFRecord { + let typeNameFormat = NDEFTypeNameFormat(rawValue: format) ?? { + HostLog.error("NDEFRecord.make: unknown type name format \(format); using unknown") + return .unknown + }() + return LinuxNDEFRecord(format: typeNameFormat, type: type, identifier: identifier, payload: payload) + } + + /// Nil unless `uri` has a scheme (RFC 3986) and no spaces or control + /// characters. The longest matching URI prefix is abbreviated to its + /// code. + public static func makeURI(_ uri: String) -> LinuxNDEFRecord? { + guard isValidURI(uri) else { + return nil + } + var code = 0 + var prefixLength = 0 + for (index, prefix) in uriPrefixes.enumerated() where prefix.count > prefixLength && uri.hasPrefix(prefix) { + code = index + prefixLength = prefix.count + } + let rest = uri.dropFirst(prefixLength) + return LinuxNDEFRecord( + format: .wellKnown, + type: uriType, + identifier: [], + payload: [UInt8(code)] + Array(rest.utf8) + ) + } + + /// UTF-8 text. A language code longer than the 63 bytes the status byte + /// can count is cut and logged. + public static func makeText(_ text: String, locale: String) -> LinuxNDEFRecord { + var language = Array(locale.utf8) + if language.count > 63 { + HostLog.error("NDEFRecord.makeText: language code longer than 63 bytes; cut") + language = Array(language.prefix(63)) + } + return LinuxNDEFRecord( + format: .wellKnown, + type: textType, + identifier: [], + payload: [UInt8(language.count)] + language + Array(text.utf8) + ) + } + + /// A copy of any `NDEFRecord`: this module's own, or one the guest + /// implemented, read through the protocol. + static func copy(of record: any NDEFRecord) -> LinuxNDEFRecord { + if let own = LinuxNFC.resolve(record, as: LinuxNDEFRecord.self) { + return own + } + return make( + format: record.typeNameFormat(), + type: record.type(), + identifier: record.identifier(), + payload: record.payload() + ) + } + + public func typeNameFormat() -> Int32 { + format.rawValue + } + + public func type() -> [UInt8] { + recordType + } + + public func identifier() -> [UInt8] { + recordIdentifier + } + + public func payload() -> [UInt8] { + recordPayload + } + + public func uri() -> String? { + guard format == .wellKnown, recordType == Self.uriType, + let code = recordPayload.first, Int(code) < Self.uriPrefixes.count, + let rest = String(bytes: recordPayload.dropFirst(), encoding: .utf8) else { + return nil + } + return Self.uriPrefixes[Int(code)] + rest + } + + /// UTF-8 or UTF-16 text; UTF-16 is big-endian unless it starts with a + /// byte order mark. + public func text() -> String? { + guard format == .wellKnown, recordType == Self.textType, let status = recordPayload.first else { + return nil + } + let languageLength = Int(status & 0x3F) + guard recordPayload.count >= 1 + languageLength else { + return nil + } + let bytes = Array(recordPayload.dropFirst(1 + languageLength)) + guard status & 0x80 != 0 else { + return String(bytes: bytes, encoding: .utf8) + } + if bytes.starts(with: [0xFF, 0xFE]) { + return String(bytes: bytes.dropFirst(2), encoding: .utf16LittleEndian) + } + if bytes.starts(with: [0xFE, 0xFF]) { + return String(bytes: bytes.dropFirst(2), encoding: .utf16BigEndian) + } + return String(bytes: bytes, encoding: .utf16BigEndian) + } + + /// The language code of a well-known text record. + var textLanguage: String? { + guard format == .wellKnown, recordType == Self.textType, let status = recordPayload.first else { + return nil + } + let languageLength = Int(status & 0x3F) + guard recordPayload.count >= 1 + languageLength else { + return nil + } + return String(bytes: recordPayload[1 ..< 1 + languageLength], encoding: .ascii) + } + + // MARK: Well-known types + + /// "U" + static let uriType: [UInt8] = [0x55] + + /// "T" + static let textType: [UInt8] = [0x54] + + /// The NFC Forum URI RTD's abbreviations, indexed by code. + static let uriPrefixes = [ + "", "http://www.", "https://www.", "http://", "https://", "tel:", "mailto:", + "ftp://anonymous:anonymous@", "ftp://ftp.", "ftps://", "sftp://", "smb://", "nfs://", + "ftp://", "dav://", "news:", "telnet://", "imap:", "rtsp://", "urn:", "pop:", "sip:", + "sips:", "tftp:", "btspp://", "btl2cap://", "btgoep://", "tcpobex://", "irdaobex://", + "file://", "urn:epc:id:", "urn:epc:tag:", "urn:epc:pat:", "urn:epc:raw:", "urn:epc:", + "urn:nfc:", + ] + + /// A scheme (a letter, then letters, digits, `+`, `-` or `.`) before the + /// first colon, and no spaces or control characters anywhere. + static func isValidURI(_ uri: String) -> Bool { + guard let colon = uri.firstIndex(of: ":") else { + return false + } + let scheme = uri[.. [UInt8] { + guard bytes.count > 255 else { + return bytes + } + HostLog.error("NDEFRecord: \(field) longer than 255 bytes; cut") + return Array(bytes.prefix(255)) + } +} + +/// The `NDEFMessage` contract: an ordered list of `LinuxNDEFRecord`s. +public final class LinuxNDEFMessage: NDEFMessage { + + let recordList: [LinuxNDEFRecord] + + init(_ records: [LinuxNDEFRecord]) { + self.recordList = records + } + + public static func make(_ records: [any NDEFRecord]) -> LinuxNDEFMessage { + LinuxNDEFMessage(records.map(LinuxNDEFRecord.copy(of:))) + } + + /// A copy of any `NDEFMessage`, as `copy(of:)` does for records. + static func copy(of message: any NDEFMessage) -> LinuxNDEFMessage { + if let own = LinuxNFC.resolve(message, as: LinuxNDEFMessage.self) { + return own + } + return make(message.records()) + } + + public func records() -> [any NDEFRecord] { + recordList + } + + public func length() -> Int32 { + Int32(clamping: encoded().count) + } + + /// The message in the NFC Forum NDEF encoding, unchunked. An empty + /// message is one empty record (`D0 00 00`), as NFC Forum tags store it. + func encoded() -> [UInt8] { + let records = recordList.isEmpty + ? [LinuxNDEFRecord(format: .empty, type: [], identifier: [], payload: [])] + : recordList + var bytes = [UInt8]() + for (index, record) in records.enumerated() { + let short = record.recordPayload.count < 256 + var header = UInt8(truncatingIfNeeded: record.format.rawValue) & 0x07 + if index == 0 { header |= 0x80 } // MB + if index == records.count - 1 { header |= 0x40 } // ME + if short { header |= 0x10 } // SR + if !record.recordIdentifier.isEmpty { header |= 0x08 } // IL + bytes.append(header) + bytes.append(UInt8(record.recordType.count)) + if short { + bytes.append(UInt8(record.recordPayload.count)) + } else { + let length = UInt32(clamping: record.recordPayload.count) + bytes += [24, 16, 8, 0].map { UInt8(truncatingIfNeeded: length >> $0) } + } + if !record.recordIdentifier.isEmpty { + bytes.append(UInt8(record.recordIdentifier.count)) + } + bytes += record.recordType + record.recordIdentifier + record.recordPayload + } + return bytes + } + + /// Decodes an unchunked NDEF message; nil if `bytes` isn't one. + static func decode(_ bytes: [UInt8]) -> LinuxNDEFMessage? { + var records = [LinuxNDEFRecord]() + var index = 0 + func take(_ count: Int) -> ArraySlice? { + guard count >= 0, index + count <= bytes.count else { return nil } + defer { index += count } + return bytes[index ..< index + count] + } + while index < bytes.count { + guard let header = take(1)?.first, header & 0x20 == 0, // CF: chunks aren't supported + let typeLength = take(1)?.first else { + return nil + } + let payloadLength: Int + if header & 0x10 != 0 { + guard let length = take(1)?.first else { return nil } + payloadLength = Int(length) + } else { + guard let length = take(4) else { return nil } + payloadLength = length.reduce(0) { $0 << 8 | Int($1) } + } + var identifierLength = 0 + if header & 0x08 != 0 { + guard let length = take(1)?.first else { return nil } + identifierLength = Int(length) + } + guard let type = take(Int(typeLength)), + let identifier = take(identifierLength), + let payload = take(payloadLength) else { + return nil + } + let format = NDEFTypeNameFormat(rawValue: Int32(header & 0x07)) ?? .unknown + records.append(LinuxNDEFRecord(format: format, type: Array(type), identifier: Array(identifier), payload: Array(payload))) + if header & 0x40 != 0 { + break + } + } + guard index == bytes.count else { + return nil + } + // One empty record is the empty message. + if records.count == 1, records[0].format == .empty, records[0].recordPayload.isEmpty { + records = [] + } + return LinuxNDEFMessage(records) + } +} diff --git a/Sources/LinuxNFC/NeardBus.swift b/Sources/LinuxNFC/NeardBus.swift new file mode 100644 index 0000000..cb12366 --- /dev/null +++ b/Sources/LinuxNFC/NeardBus.swift @@ -0,0 +1,157 @@ +import DBus +import LinuxDBus +import LinuxHost + +/// An object's interfaces, each with its properties (variants unwrapped). +public typealias NeardInterfaces = [String: [String: DBusMessageArgument]] + +/// What neard reports, on the main loop. +public enum NeardEvent { + case added(path: String, interfaces: NeardInterfaces) + case removed(path: String, interfaces: [String]) + case changed(path: String, interface: String, changed: [String: DBusMessageArgument]) + /// A tag's records were read: after it was found, and again after each + /// write. neard says so with a signal of its own, + /// `org.neard.Tag.PropertyChanged("Records", …)`. + case recordsRead(tag: String) + /// The bus closed. + case closed +} + +/// The connection to neard (`Plan.md` §14): the real system bus, or a fake +/// one in tests. Everything it answers arrives on the main loop. +public protocol NeardBus: AnyObject { + + /// Every object neard manages (`GetManagedObjects`). + func objects(reply: @escaping (Result<[String: NeardInterfaces], BusError>) -> Void) + + /// The same, waiting for them: for `availability`, which answers at once. + func objectsAndWait() -> Result<[String: NeardInterfaces], BusError> + + /// Calls a method of one of neard's objects. + func call( + _ path: String, + _ interface: String, + _ method: String, + _ arguments: [DBusMessageArgument], + signature: String?, + reply: @escaping (Result) -> Void + ) + + /// Calls `handler` with each change to neard's objects. + func subscribe(_ handler: @escaping (NeardEvent) -> Void) -> BusSubscription + + func unsubscribe(_ subscription: BusSubscription) +} + +/// neard's names. +enum Neard { + static let service = "org.neard" + static let adapter = "org.neard.Adapter" + static let tag = "org.neard.Tag" + static let record = "org.neard.Record" + static let objectManager = "org.freedesktop.DBus.ObjectManager" + static let properties = "org.freedesktop.DBus.Properties" +} + +/// neard on the system bus, through LinuxDBus's `Bus.system`. Main loop +/// only. +public final class SystemNeard: NeardBus { + + private let bus: Bus + + private var subscriptions: [UInt64: [BusSubscription]] = [:] + + private var next: UInt64 = 0 + + public init(bus: Bus = .system) { + self.bus = bus + } + + public func objects(reply: @escaping (Result<[String: NeardInterfaces], BusError>) -> Void) { + bus.call(Neard.service, "/", Neard.objectManager, "GetManagedObjects") { result in + reply(result.map(Self.objects)) + } + } + + public func objectsAndWait() -> Result<[String: NeardInterfaces], BusError> { + bus.callAndWait(Neard.service, "/", Neard.objectManager, "GetManagedObjects").map(Self.objects) + } + + public func call( + _ path: String, + _ interface: String, + _ method: String, + _ arguments: [DBusMessageArgument], + signature: String?, + reply: @escaping (Result) -> Void + ) { + bus.call(Neard.service, path, interface, method, arguments, signature: signature) { result in + reply(result.map { _ in }) + } + } + + public func subscribe(_ handler: @escaping (NeardEvent) -> Void) -> BusSubscription { + next += 1 + subscriptions[next] = [ + bus.subscribe(MatchRule(sender: Neard.service, path: "/", interface: Neard.objectManager, member: "InterfacesAdded")) { signal in + guard signal.body.count >= 2, let path = signal.body[0].text else { return } + handler(.added(path: path, interfaces: Self.interfaces(signal.body[1]))) + }, + bus.subscribe(MatchRule(sender: Neard.service, path: "/", interface: Neard.objectManager, member: "InterfacesRemoved")) { signal in + guard signal.body.count >= 2, let path = signal.body[0].text else { return } + handler(.removed(path: path, interfaces: signal.body[1].elements?.compactMap(\.text) ?? [])) + }, + bus.subscribe(MatchRule(sender: Neard.service, interface: Neard.properties, member: "PropertiesChanged")) { signal in + guard signal.body.count >= 2, let interface = signal.body[0].text else { return } + handler(.changed(path: signal.path, interface: interface, changed: signal.body[1].entries)) + }, + bus.subscribe(MatchRule(sender: Neard.service, interface: Neard.tag, member: "PropertyChanged", arg0: "Records")) { signal in + handler(.recordsRead(tag: signal.path)) + }, + bus.subscribe(.disconnected) { _ in + handler(.closed) + }, + ] + return BusSubscription(id: next) + } + + public func unsubscribe(_ subscription: BusSubscription) { + subscriptions.removeValue(forKey: subscription.id)?.forEach(bus.unsubscribe) + } + + /// `a{oa{sa{sv}}}`. + private static func objects(_ reply: [DBusMessageArgument]) -> [String: NeardInterfaces] { + var objects: [String: NeardInterfaces] = [:] + for (path, interfaces) in reply.first?.pairs ?? [] { + guard let path = path.text else { continue } + objects[path] = Self.interfaces(interfaces) + } + return objects + } + + /// `a{sa{sv}}`. + private static func interfaces(_ argument: DBusMessageArgument) -> NeardInterfaces { + var interfaces: NeardInterfaces = [:] + for (name, properties) in argument.pairs ?? [] { + guard let name = name.text else { continue } + interfaces[name] = properties.entries + } + return interfaces + } +} + +// MARK: - Values + +extension DBusMessageArgument { + + /// `ay`. + var bytes: [UInt8]? { + elements?.compactMap { if case .byte(let byte) = $0.contents { byte } else { nil } } + } + + /// `ay`. + static func byteArray(_ bytes: [UInt8]) -> DBusMessageArgument { + .list(of: .byte, bytes.map { .byte($0) }) + } +} diff --git a/Sources/LinuxNFC/NeardRecords.swift b/Sources/LinuxNFC/NeardRecords.swift new file mode 100644 index 0000000..57d6dff --- /dev/null +++ b/Sources/LinuxNFC/NeardRecords.swift @@ -0,0 +1,100 @@ +import DBus +import DynamicNFC +import Foundation +import LinuxDBus +import LinuxHost + +/// neard's records and NDEF records, each way (`Plan.md` §14). +/// +/// neard parses a tag's message itself and publishes each record it knows +/// as an object of its own (`org.neard.Record`) with the record's fields as +/// properties, not as bytes; it writes only records it can make from such +/// fields. So a message holds what neard can say: text, URIs, MIME types, +/// Smart Posters and Android application records read, and text, URIs and +/// MIME types written. +enum NeardRecords { + + /// The records under `tag`, in neard's order (`record0`, `record1`, …). + static func records(of tag: String, in objects: [String: NeardInterfaces]) -> [LinuxNDEFRecord] { + let prefix = tag + "/record" + let found = objects.compactMap { path, interfaces -> (Int, [String: DBusMessageArgument])? in + guard path.hasPrefix(prefix), let index = Int(path.dropFirst(prefix.count)), + let properties = interfaces[Neard.record] else { + return nil + } + return (index, properties) + } + return found.sorted { $0.0 < $1.0 }.compactMap { record($0.1) } + } + + /// One of neard's records, or nil for a kind neard publishes but the + /// contract has no way to say (a Bluetooth or Wi-Fi handover). + static func record(_ properties: [String: DBusMessageArgument]) -> LinuxNDEFRecord? { + let kind = properties["Type"]?.text + switch kind { + case "Text": + return .makeText(properties["Representation"]?.text ?? "", locale: properties["Language"]?.text ?? "") + case "URI": + return properties["URI"]?.text.flatMap(LinuxNDEFRecord.makeURI) + case "MIME": + guard let type = properties["MIME"]?.text else { return nil } + return LinuxNDEFRecord(format: .media, type: Array(type.utf8), identifier: [], payload: properties["MIMEPayload"]?.bytes ?? []) + case "SmartPoster": + // The poster's URI, and its title, in a message of their own. + var inside: [LinuxNDEFRecord] = [] + if let uri = properties["URI"]?.text.flatMap(LinuxNDEFRecord.makeURI) { + inside.append(uri) + } + if let title = properties["Representation"]?.text { + inside.append(.makeText(title, locale: properties["Language"]?.text ?? "")) + } + return LinuxNDEFRecord(format: .wellKnown, type: smartPosterType, identifier: [], payload: LinuxNDEFMessage(inside).encoded()) + case "AAR": + guard let package = (properties["AAR"] ?? properties["AndroidPackage"])?.text else { return nil } + return LinuxNDEFRecord(format: .external, type: Array("android.com:pkg".utf8), identifier: [], payload: Array(package.utf8)) + default: + HostLog.debug("nfc: neard's \(kind ?? "untyped") record left out") + return nil + } + } + + /// `Tag.Write`'s argument for `message`: one record's fields, or every + /// record's under `Records`. Nil for an empty message, or a record + /// neard can't make. + static func attributes(_ message: LinuxNDEFMessage) -> [String: DBusMessageArgument]? { + let records = message.recordList.map(attributes) + guard !records.isEmpty, records.allSatisfy({ $0 != nil }) else { + return nil + } + let each = records.compactMap { $0 } + if each.count == 1 { + return each[0] + } + let dictionary = DBusSignature.ValueType.dictionary(DBusSignature.DictionaryType(key: .string, value: .variant)!) + return ["Records": .list(of: dictionary, each.map(DBusMessageArgument.vardict))] + } + + /// One record's fields, as neard takes them. + static func attributes(_ record: LinuxNDEFRecord) -> [String: DBusMessageArgument]? { + if let uri = record.uri() { + return ["Type": .string("URI"), "URI": .string(uri)] + } + if let text = record.text(), let language = record.textLanguage { + return [ + "Type": .string("Text"), "Encoding": .string("UTF-8"), + "Language": .string(language), "Representation": .string(text), + ] + } + // neard makes a Wi-Fi configuration of its own for the WSC type, out + // of other fields. + if record.format == .media, record.recordIdentifier.isEmpty, + let type = String(bytes: record.recordType, encoding: .utf8), !type.isEmpty, + type.lowercased() != "application/vnd.wfa.wsc" { + return ["Type": .string("MIME"), "MIME": .string(type), "Payload": .byteArray(record.recordPayload)] + } + return nil + } + + /// "Sp" + static let smartPosterType: [UInt8] = [0x53, 0x70] +} diff --git a/Sources/LinuxPackager/Validator.swift b/Sources/LinuxPackager/Validator.swift index 5ebe06b..a55cfd3 100644 --- a/Sources/LinuxPackager/Validator.swift +++ b/Sources/LinuxPackager/Validator.swift @@ -7,6 +7,7 @@ import LinuxDocuments import LinuxGraphics import LinuxLocation import LinuxMotion +import LinuxNFC import LinuxWebKit import LinuxHost import DynamicUI @@ -20,11 +21,11 @@ public enum HostContracts { /// The modules `linux-app-host` registers (`HostApp.modules`): the /// player's contracts, without building the player, Bluetooth, /// graphics, web views, files, settings, model stores, formatting, HTTP, - /// the device, location, documents and motion. + /// the device, location, documents, motion and NFC. nonisolated(unsafe) public static let modules: [any HostModule.Type] = [ PlayerContracts.self, LinuxBluetooth.self, LinuxGraphics.self, LinuxWebKit.self, LinuxFiles.self, LinuxDefaults.self, LinuxModelStore.self, HostFormattingModule.self, HostNetworkingModule.self, LinuxDeviceModule.self, LinuxLocation.self, - LinuxDocuments.self, LinuxMotion.self, + LinuxDocuments.self, LinuxMotion.self, LinuxNFC.self, ] public static var provided: [String: ContractDescriptor] { @@ -33,9 +34,9 @@ public enum HostContracts { /// Capabilities some contract here serves: `network` is what lets an /// HTTP session or a web view's page reach the network, `location` - /// GeoClue's, `userFiles` the documents' pickers, and `motion` the - /// altimeter, which asks nothing. - public static let capabilities: Set = [.bluetooth, .graphics, .network, .location, .userFiles, .motion] + /// GeoClue's, `userFiles` the documents' pickers, `motion` the + /// altimeter, which asks nothing, and `nfc` neard's. + public static let capabilities: Set = [.bluetooth, .graphics, .network, .location, .userFiles, .motion, .nfc] } /// The checks of `Packager.md` §1, which install makes before it copies an diff --git a/Tests/LinuxNFCTests/FakeNeard.swift b/Tests/LinuxNFCTests/FakeNeard.swift new file mode 100644 index 0000000..1ca9859 --- /dev/null +++ b/Tests/LinuxNFCTests/FakeNeard.swift @@ -0,0 +1,175 @@ +import DBus +import DynamicNFC +import LinuxDBus +import LinuxHost +@testable import LinuxNFC + +/// Plays neard: its objects, the methods called on them, and its signals, +/// answering on the main loop as the bus does. +final class FakeNeard: NeardBus { + + var objects: [String: NeardInterfaces] = [:] + + /// Fails every call, as the bus does without neard. + var unavailable: BusError? + + /// Errors to answer a method with, by name, once each. + var errors: [String: BusError] = [:] + + struct Call: Equatable { + var path: String + var method: String + var arguments: [DBusMessageArgument] + } + + private(set) var calls: [Call] = [] + + private var handlers: [UInt64: (NeardEvent) -> Void] = [:] + + private var next: UInt64 = 0 + + var subscribers: Int { handlers.count } + + static let adapter = "/org/neard/nfc0" + + /// An adapter, on or off. + init(powered: Bool = true) { + objects[Self.adapter] = [Neard.adapter: ["Powered": .boolean(powered), "Mode": .string("Idle"), "Polling": .boolean(false)]] + } + + var methods: [String] { calls.map(\.method) } + + func objects(reply: @escaping (Result<[String: NeardInterfaces], BusError>) -> Void) { + let answer: Result<[String: NeardInterfaces], BusError> = unavailable.map { .failure($0) } ?? .success(objects) + MainLoop.shared.post { reply(answer) } + } + + func objectsAndWait() -> Result<[String: NeardInterfaces], BusError> { + unavailable.map { .failure($0) } ?? .success(objects) + } + + func call( + _ path: String, + _ interface: String, + _ method: String, + _ arguments: [DBusMessageArgument], + signature: String?, + reply: @escaping (Result) -> Void + ) { + calls.append(Call(path: path, method: method, arguments: arguments)) + let answer: Result + if let error = unavailable ?? errors.removeValue(forKey: method) { + answer = .failure(error) + } else { + answer = .success(()) + } + MainLoop.shared.post { reply(answer) } + } + + func subscribe(_ handler: @escaping (NeardEvent) -> Void) -> BusSubscription { + next += 1 + handlers[next] = handler + return BusSubscription(id: next) + } + + func unsubscribe(_ subscription: BusSubscription) { + handlers[subscription.id] = nil + } + + /// Sends an event to every subscriber, on the main loop. + func emit(_ event: NeardEvent) { + MainLoop.shared.post { [handlers] in + for id in handlers.keys.sorted() { + handlers[id]?(event) + } + } + } + + // MARK: Tags + + static func tagPath(_ index: Int = 0) -> String { adapter + "/tag\(index)" } + + /// A tag in the field, and its records, as neard publishes them once it + /// has read them: the tag, then the records' signal. + func addTag( + _ index: Int = 0, + protocol name: String = "ISO-DEP", + uid: [UInt8] = [0x04, 0xA2, 0x1B, 0x7C], + readOnly: Bool = false, + records: [[String: DBusMessageArgument]] = [], + signalRecords: Bool = true + ) { + let path = Self.tagPath(index) + let tag: [String: DBusMessageArgument] = [ + "Type": .string("Type 4A"), "Protocol": .string(name), "ReadOnly": .boolean(readOnly), + "Adapter": .path(Self.adapter), "Uid": .byteArray(uid), + ] + objects[path] = [Neard.tag: tag] + setRecords(records, of: path) + emit(.added(path: path, interfaces: [Neard.tag: tag])) + if signalRecords { + emit(.recordsRead(tag: path)) + } + } + + /// Replaces a tag's records, as neard does when it reads it again. + func setRecords(_ records: [[String: DBusMessageArgument]], of path: String) { + for key in objects.keys where key.hasPrefix(path + "/record") { + objects[key] = nil + } + for (index, record) in records.enumerated() { + objects[path + "/record\(index)"] = [Neard.record: record] + } + } + + func removeTag(_ index: Int = 0) { + let path = Self.tagPath(index) + for key in objects.keys where key.hasPrefix(path) { + objects[key] = nil + } + emit(.removed(path: path, interfaces: [Neard.tag])) + } +} + +/// Records what the reader tells its delegate, and keeps the tags it found. +final class RecordingReaderDelegate: NFCReaderDelegate { + + var events: [String] = [] + + var tags: [any NFCTag] = [] + + var messages: [(any NDEFMessage)?] = [] + + var invalidations: [(error: Int32, message: String?)] = [] + + func didBecomeActive(_ reader: any NFCReader) { events.append("active") } + + func didDetect(_ reader: any NFCReader, tags: [any NFCTag]) { + self.tags = tags + events.append("detect \(tags.count)") + } + + func didConnect(_ reader: any NFCReader, tag: any NFCTag, error: Int32) { events.append("connect \(error)") } + + func didQueryNDEF(_ reader: any NFCReader, tag: any NFCTag, status: Int32, capacity: Int32, error: Int32) { + events.append("query \(status) \(capacity) \(error)") + } + + func didReadNDEF(_ reader: any NFCReader, tag: any NFCTag, message: (any NDEFMessage)?, error: Int32) { + messages.append(message) + events.append("read \(message?.records().count ?? -1) \(error)") + } + + func didWriteNDEF(_ reader: any NFCReader, tag: any NFCTag, error: Int32) { events.append("write \(error)") } + + func didLock(_ reader: any NFCReader, tag: any NFCTag, error: Int32) { events.append("lock \(error)") } + + func didTransceive(_ reader: any NFCReader, tag: any NFCTag, response: [UInt8], error: Int32) { + events.append("transceive \(response.count) \(error)") + } + + func didInvalidate(_ reader: any NFCReader, error: Int32, message: String?) { + invalidations.append((error, message)) + events.append("invalidate \(error)") + } +} diff --git a/Tests/LinuxNFCTests/LinuxNFCTests.swift b/Tests/LinuxNFCTests/LinuxNFCTests.swift new file mode 100644 index 0000000..7d2de40 --- /dev/null +++ b/Tests/LinuxNFCTests/LinuxNFCTests.swift @@ -0,0 +1,450 @@ +import DBus +import DynamicNFC +import DynamicRuntime +import Foundation +import LinuxDBus +import LinuxHost +import Testing +@testable import LinuxNFC + +let uriRecord: [String: DBusMessageArgument] = ["Type": .string("URI"), "URI": .string("https://example.com/tag")] + +let textRecord: [String: DBusMessageArgument] = [ + "Type": .string("Text"), "Encoding": .string("UTF-8"), "Language": .string("en"), "Representation": .string("Hello"), +] + +/// `LinuxNFCReader.neard` is every test's, so one at a time. +@Suite(.serialized) struct LinuxNFCTests { + + func with(_ neard: FakeNeard, timeout: Int64 = 50_000_000, _ body: () throws -> T) rethrows -> T { + let previous = LinuxNFCReader.neard + let previousTimeout = LinuxNFCReader.recordsTimeout + LinuxNFCReader.neard = neard + LinuxNFCReader.recordsTimeout = timeout + defer { + MainLoop.shared.drain() + LinuxNFCReader.neard = previous + LinuxNFCReader.recordsTimeout = previousTimeout + } + return try body() + } + + /// Runs the main loop until `done`, for up to five seconds: a timer + /// wakes it then, since nothing else may. + func run(until done: () -> Bool) { + var expired = false + let timer = MainLoop.shared.schedule(after: 5_000_000_000) { expired = true } + defer { MainLoop.shared.cancel(timer) } + MainLoop.shared.run { done() || expired } + } + + /// A session polling for ISO 14443 tags, and a tag found and connected. + func connected(_ neard: FakeNeard, records: [[String: DBusMessageArgument]] = [uriRecord, textRecord], readOnly: Bool = false, + types: NFCTagTypes = .iso14443) throws -> (LinuxNFCReader, RecordingReaderDelegate, any NFCTag) { + let delegate = RecordingReaderDelegate() + let reader = LinuxNFCReader.make(delegate) + reader.begin(types.rawValue, alertMessage: "Hold a tag near the reader") + MainLoop.shared.drain() + neard.addTag(readOnly: readOnly, records: records) + MainLoop.shared.drain() + let tag = try #require(delegate.tags.first) + reader.connect(tag) + MainLoop.shared.drain() + #expect(delegate.events == ["active", "detect 1", "connect 0"]) + delegate.events = [] + return (reader, delegate, tag) + } + + // MARK: Availability + + @Test func availability() { + with(FakeNeard()) { + #expect(LinuxNFCReader.availability() == NFCAvailability.available.rawValue) + } + with(FakeNeard(powered: false)) { + #expect(LinuxNFCReader.availability() == NFCAvailability.disabled.rawValue) + } + let none = FakeNeard() + none.objects = [:] + with(none) { + #expect(LinuxNFCReader.availability() == NFCAvailability.unsupported.rawValue, "no adapter") + } + let missing = FakeNeard() + missing.unavailable = BusError(name: "org.freedesktop.DBus.Error.ServiceUnknown") + with(missing) { + #expect(LinuxNFCReader.availability() == NFCAvailability.unsupported.rawValue, "no neard") + } + // One adapter on of two is enough. + let two = FakeNeard(powered: false) + two.objects["/org/neard/nfc1"] = [Neard.adapter: ["Powered": .boolean(true)]] + #expect(LinuxNFCReader.adapter(in: two.objects)?.path == "/org/neard/nfc1") + } + + @Test func protocolsAsTheContractHasThem() { + #expect(LinuxNFCReader.kind("ISO-DEP")?.type == .iso7816) + #expect(LinuxNFCReader.kind("MIFARE")?.type == .miFare) + #expect(LinuxNFCReader.kind("Jewel")?.family == .iso14443) + #expect(LinuxNFCReader.kind("Felica")?.family == .iso18092) + #expect(LinuxNFCReader.kind("ISO-15693")?.type == .iso15693) + #expect(LinuxNFCReader.kind("NFC-DEP") == nil) + } + + // MARK: Sessions + + @Test func aSessionFindsATagAndReadsIt() throws { + let neard = FakeNeard() + try with(neard) { + let (reader, delegate, tag) = try connected(neard) + #expect(neard.calls.first == .init(path: FakeNeard.adapter, method: "StartPollLoop", arguments: [.string("Initiator")])) + #expect(reader.isActive()) + #expect(tag.type() == NFCTagType.iso7816.rawValue) + #expect(tag.identifier() == [0x04, 0xA2, 0x1B, 0x7C]) + #expect(tag.isAvailable()) + #expect(tag.maximumTransceiveLength() == 0 && tag.historicalBytes() == nil) + + tag.queryNDEFStatus() + tag.readNDEF() + MainLoop.shared.drain() + #expect(delegate.events == ["query \(NDEFStatus.readWrite.rawValue) 0 0", "read 2 0"]) + let records = try #require(delegate.messages.first??.records()) + #expect(records[0].uri() == "https://example.com/tag") + #expect(records[1].text() == "Hello") + + reader.invalidate(nil) + MainLoop.shared.drain() + #expect(neard.methods == ["StartPollLoop", "StopPollLoop"]) + #expect(delegate.events.last == "invalidate 0" && delegate.invalidations.last?.message == nil) + #expect(!reader.isActive() && !tag.isAvailable()) + #expect(neard.subscribers == 0) + } + } + + @Test func theRecordsSignalCanComeFirst() throws { + let neard = FakeNeard() + try with(neard) { + let delegate = RecordingReaderDelegate() + let reader = LinuxNFCReader.make(delegate) + reader.begin(NFCTagTypes.iso14443.rawValue, alertMessage: nil) + MainLoop.shared.drain() + neard.objects[FakeNeard.tagPath()] = [Neard.tag: ["Protocol": .string("MIFARE")]] + neard.emit(.recordsRead(tag: FakeNeard.tagPath())) + neard.emit(.added(path: FakeNeard.tagPath(), interfaces: [Neard.tag: [:]])) + MainLoop.shared.drain() + #expect(delegate.events == ["active", "detect 1"], "once") + let tag = try #require(delegate.tags.first) + #expect(tag.type() == NFCTagType.miFare.rawValue) + reader.invalidate(nil) + } + } + + @Test func aTagWithoutRecordsIsFoundAfterAWhile() throws { + let neard = FakeNeard() + try with(neard, timeout: 20_000_000) { + let delegate = RecordingReaderDelegate() + let reader = LinuxNFCReader.make(delegate) + reader.begin(NFCTagTypes.iso14443.rawValue, alertMessage: nil) + MainLoop.shared.drain() + neard.addTag(signalRecords: false) + MainLoop.shared.drain() + #expect(delegate.events == ["active"], "waiting for records") + run { delegate.events.count > 1 } + #expect(delegate.events == ["active", "detect 1"]) + let tag = try #require(delegate.tags.first) + reader.connect(tag) + tag.readNDEF() + MainLoop.shared.drain() + #expect(delegate.events.suffix(2) == ["connect 0", "read -1 0"], "an empty tag reads nil") + reader.invalidate(nil) + } + } + + @Test func kindsNotAskedForAreLeftOut() throws { + let neard = FakeNeard() + with(neard) { + let delegate = RecordingReaderDelegate() + let reader = LinuxNFCReader.make(delegate) + reader.begin(NFCTagTypes.iso15693.rawValue, alertMessage: nil) + MainLoop.shared.drain() + neard.addTag(protocol: "MIFARE") + MainLoop.shared.drain() + #expect(delegate.events == ["active"]) + // neard polls again only once the field is empty. + neard.removeTag() + MainLoop.shared.drain() + #expect(neard.methods == ["StartPollLoop", "StartPollLoop"]) + neard.addTag(1, protocol: "ISO-15693") + MainLoop.shared.drain() + #expect(delegate.events == ["active", "detect 1"]) + reader.invalidate(nil) + } + } + + @Test func anNDEFSessionFindsEveryKind() throws { + let neard = FakeNeard() + try with(neard) { + let (reader, delegate, tag) = try connected(neard, types: .ndef) + #expect(tag.type() == NFCTagType.ndef.rawValue) + #expect(tag.identifier().isEmpty, "no UID in an NDEF session, as on iOS") + tag.transceive([0x00, 0xA4]) + MainLoop.shared.drain() + #expect(delegate.events == ["transceive 0 \(NFCError.notAvailableInNDEFSession.rawValue)"]) + reader.invalidate(nil) + } + } + + @Test func restartingPollingWaitsForTheFieldToEmpty() throws { + let neard = FakeNeard() + try with(neard) { + let (reader, delegate, tag) = try connected(neard) + // The same tag isn't found again while it stays. + reader.restartPolling() + MainLoop.shared.drain() + #expect(neard.methods == ["StartPollLoop"]) + #expect(!tag.isAvailable(), "the detection's tags are dropped") + tag.readNDEF() + MainLoop.shared.drain() + #expect(delegate.events == ["read -1 \(NFCError.tagNotConnected.rawValue)"]) + + neard.removeTag() + MainLoop.shared.drain() + #expect(neard.methods == ["StartPollLoop", "StartPollLoop"]) + neard.addTag(1, records: [textRecord]) + MainLoop.shared.drain() + #expect(delegate.events.last == "detect 1") + reader.invalidate(nil) + } + } + + @Test func aTagAlreadyInTheFieldIsFound() throws { + let neard = FakeNeard() + neard.objects[FakeNeard.tagPath()] = [Neard.tag: ["Protocol": .string("ISO-DEP")]] + neard.objects[FakeNeard.tagPath() + "/record0"] = [Neard.record: uriRecord] + with(neard) { + let delegate = RecordingReaderDelegate() + let reader = LinuxNFCReader.make(delegate) + reader.begin(NFCTagTypes.iso14443.rawValue, alertMessage: nil) + MainLoop.shared.drain() + #expect(delegate.events == ["active", "detect 1"]) + #expect(neard.methods.isEmpty, "neard won't poll over a tag") + reader.invalidate(nil) + } + } + + @Test func sessionsThatCantBegin() throws { + func outcome(_ neard: FakeNeard, _ types: NFCTagTypes = .iso14443) -> [Int32] { + with(neard) { + let delegate = RecordingReaderDelegate() + let reader = LinuxNFCReader.make(delegate) + reader.begin(types.rawValue, alertMessage: nil) + MainLoop.shared.drain() + #expect(!reader.isActive()) + return delegate.invalidations.map(\.error) + } + } + let missing = FakeNeard() + missing.unavailable = BusError(name: "org.freedesktop.DBus.Error.ServiceUnknown") + #expect(outcome(missing) == [NFCError.unsupported.rawValue]) + let none = FakeNeard() + none.objects = [:] + #expect(outcome(none) == [NFCError.unsupported.rawValue]) + #expect(outcome(FakeNeard(powered: false)) == [NFCError.disabled.rawValue]) + #expect(outcome(FakeNeard(), [.ndef, .iso14443]) == [NFCError.invalidParameter.rawValue]) + #expect(outcome(FakeNeard(), []) == [NFCError.invalidParameter.rawValue]) + let busy = FakeNeard() + busy.errors["StartPollLoop"] = BusError(name: "org.neard.Error.Failed", message: "Device or resource busy") + #expect(outcome(busy) == [NFCError.systemBusy.rawValue]) + #expect(busy.subscribers == 0) + } + + @Test func oneSessionAtATime() throws { + let neard = FakeNeard() + with(neard) { + let first = RecordingReaderDelegate() + let reader = LinuxNFCReader.make(first) + reader.begin(NFCTagTypes.iso14443.rawValue, alertMessage: nil) + let second = RecordingReaderDelegate() + let other = LinuxNFCReader.make(second) + other.begin(NFCTagTypes.iso14443.rawValue, alertMessage: nil) + MainLoop.shared.drain() + #expect(first.events == ["active"]) + #expect(second.invalidations.map(\.error) == [NFCError.systemBusy.rawValue]) + + reader.invalidate("Couldn't read the tag") + MainLoop.shared.drain() + #expect(first.invalidations.map(\.error) == [0]) + // A reader is single-use; the next can begin. + reader.begin(NFCTagTypes.iso14443.rawValue, alertMessage: nil) + MainLoop.shared.drain() + #expect(first.invalidations.map(\.error) == [0, NFCError.systemBusy.rawValue]) + let third = RecordingReaderDelegate() + let next = LinuxNFCReader.make(third) + next.begin(NFCTagTypes.iso14443.rawValue, alertMessage: nil) + MainLoop.shared.drain() + #expect(third.events == ["active"]) + next.invalidate(nil) + } + } + + @Test func invalidatingBeforeNeardAnswers() { + let neard = FakeNeard() + with(neard) { + let delegate = RecordingReaderDelegate() + let reader = LinuxNFCReader.make(delegate) + reader.begin(NFCTagTypes.iso14443.rawValue, alertMessage: nil) + reader.invalidate(nil) + MainLoop.shared.drain() + #expect(delegate.events == ["invalidate 0"]) + #expect(neard.calls.isEmpty && neard.subscribers == 0) + } + } + + @Test func theAdapterGoingEndsTheSession() throws { + for event in [ + NeardEvent.changed(path: FakeNeard.adapter, interface: Neard.adapter, changed: ["Powered": .boolean(false)]), + .removed(path: FakeNeard.adapter, interfaces: [Neard.adapter]), + .closed, + ] { + let neard = FakeNeard() + try with(neard) { + let (reader, delegate, tag) = try connected(neard) + tag.readNDEF() + neard.emit(event) + MainLoop.shared.drain() + #expect(!reader.isActive()) + #expect(delegate.events.count == 2 && delegate.events[1].hasPrefix("invalidate ")) + #expect(delegate.invalidations.first.map { $0.error != 0 && $0.message != nil } == true) + } + } + } + + // MARK: Tags + + @Test func operationsNeedAConnection() throws { + let neard = FakeNeard() + try with(neard) { + let delegate = RecordingReaderDelegate() + let reader = LinuxNFCReader.make(delegate) + reader.begin(NFCTagTypes.iso14443.rawValue, alertMessage: nil) + MainLoop.shared.drain() + neard.addTag(records: [uriRecord]) + MainLoop.shared.drain() + let tag = try #require(delegate.tags.first) + delegate.events = [] + tag.readNDEF() + tag.writeLock() + MainLoop.shared.drain() + #expect(delegate.events == ["read -1 \(NFCError.tagNotConnected.rawValue)", "lock \(NFCError.tagNotConnected.rawValue)"]) + reader.invalidate(nil) + } + } + + @Test func aTagLeavingFailsWhatWaits() throws { + let neard = FakeNeard() + try with(neard) { + let (reader, delegate, tag) = try connected(neard) + let message = LinuxNDEFMessage.make([LinuxNDEFRecord.makeText("Bye", locale: "en")]) + tag.writeNDEF(message) + tag.readNDEF() + neard.removeTag() + MainLoop.shared.drain() + // The write was answered; the read waited for neard to read the + // tag again. + #expect(delegate.events == ["write 0", "read -1 \(NFCError.tagConnectionLost.rawValue)"]) + #expect(!tag.isAvailable()) + tag.queryNDEFStatus() + reader.connect(tag) + MainLoop.shared.drain() + #expect(delegate.events.suffix(2) == ["query 0 0 \(NFCError.tagConnectionLost.rawValue)", "connect \(NFCError.tagConnectionLost.rawValue)"]) + reader.invalidate(nil) + } + } + + @Test func writingAndReadingAgain() throws { + let neard = FakeNeard() + try with(neard) { + let (reader, delegate, tag) = try connected(neard) + let message = LinuxNDEFMessage.make([ + try #require(LinuxNDEFRecord.makeURI("https://example.org/")), + LinuxNDEFRecord.makeText("Written", locale: "en"), + ]) + tag.writeNDEF(message) + tag.readNDEF() + MainLoop.shared.drain() + #expect(delegate.events == ["write 0"], "the read waits for neard to read the tag again") + let write = try #require(neard.calls.last) + #expect(write.path == FakeNeard.tagPath() && write.method == "Write") + let records = try #require(write.arguments.first?.entries["Records"]?.elements) + #expect(records.map(\.entries) == [ + ["Type": .string("URI"), "URI": .string("https://example.org/")], + ["Type": .string("Text"), "Encoding": .string("UTF-8"), "Language": .string("en"), "Representation": .string("Written")], + ]) + + neard.setRecords([["Type": .string("URI"), "URI": .string("https://example.org/")], textRecord], of: FakeNeard.tagPath()) + neard.emit(.recordsRead(tag: FakeNeard.tagPath())) + MainLoop.shared.drain() + #expect(delegate.events == ["write 0", "read 2 0"]) + #expect(delegate.messages.last??.records().first?.uri() == "https://example.org/") + + // One record is written as itself. + tag.writeNDEF(LinuxNDEFMessage.make([LinuxNDEFRecord.makeText("One", locale: "fr")])) + MainLoop.shared.drain() + #expect(neard.calls.last?.arguments.first?.entries["Language"] == .string("fr")) + reader.invalidate(nil) + } + } + + @Test func readingAgainGivesUpAfterAWhile() throws { + let neard = FakeNeard() + try with(neard, timeout: 20_000_000) { + let (reader, delegate, tag) = try connected(neard) + tag.writeNDEF(LinuxNDEFMessage.make([LinuxNDEFRecord.makeText("Bye", locale: "en")])) + tag.readNDEF() + neard.setRecords([textRecord], of: FakeNeard.tagPath()) + run { delegate.events.count == 2 } + #expect(delegate.events == ["write 0", "read 1 0"]) + reader.invalidate(nil) + } + } + + @Test func writesNeardCantMake() throws { + let neard = FakeNeard() + try with(neard) { + let (reader, delegate, tag) = try connected(neard) + tag.writeNDEF(LinuxNDEFMessage.make([])) + tag.writeNDEF(LinuxNDEFMessage.make([LinuxNDEFRecord.make(format: NDEFTypeNameFormat.external.rawValue, type: Array("example.com:t".utf8), identifier: [], payload: [1])])) + neard.errors["Write"] = BusError(name: "org.neard.Error.InProgress") + tag.writeNDEF(LinuxNDEFMessage.make([LinuxNDEFRecord.makeText("Hi", locale: "en")])) + tag.writeLock() + tag.transceive([0x30, 0x04]) + MainLoop.shared.drain() + let invalid = NFCError.invalidParameter.rawValue + let unsupported = NFCError.unsupported.rawValue + #expect(delegate.events == ["write \(invalid)", "write \(invalid)", "write \(NFCError.systemBusy.rawValue)", + "lock \(unsupported)", "transceive 0 \(unsupported)"]) + #expect(neard.methods.filter { $0 == "Write" }.count == 1) + reader.invalidate(nil) + } + let locked = FakeNeard() + try with(locked) { + let (reader, delegate, tag) = try connected(locked, readOnly: true) + tag.queryNDEFStatus() + tag.writeNDEF(LinuxNDEFMessage.make([LinuxNDEFRecord.makeText("Hi", locale: "en")])) + MainLoop.shared.drain() + #expect(delegate.events == ["query \(NDEFStatus.readOnly.rawValue) 0 0", "write \(NFCError.tagReadOnly.rawValue)"]) + #expect(!locked.methods.contains("Write")) + reader.invalidate(nil) + } + #expect(LinuxNFCTag.error(writing: BusError(name: "org.neard.Error.PermissionDenied")) == .tagReadOnly) + #expect(LinuxNFCTag.error(writing: .disconnected) == .tagConnectionLost) + } + + // MARK: Module + + @Test func moduleRegistersTheContracts() { + #expect(LinuxNFC.contracts.map(\.name) == [ + "org.pureswift.nfc.Reader", "org.pureswift.nfc.ReaderDelegate", "org.pureswift.nfc.Tag", + "org.pureswift.nfc.NDEFMessage", "org.pureswift.nfc.NDEFRecord", + ]) + #expect(LinuxNFC.permissionProviders().keys.contains(.nfc)) + } +} diff --git a/Tests/LinuxNFCTests/NDEFTests.swift b/Tests/LinuxNFCTests/NDEFTests.swift new file mode 100644 index 0000000..a655818 --- /dev/null +++ b/Tests/LinuxNFCTests/NDEFTests.swift @@ -0,0 +1,83 @@ +import DBus +import DynamicNFC +import LinuxDBus +import Testing +@testable import LinuxNFC + +@Suite struct NDEFTests { + + @Test func wellKnownRecords() throws { + let uri = try #require(LinuxNDEFRecord.makeURI("https://www.example.com/a")) + #expect(uri.payload() == [0x02] + Array("example.com/a".utf8), "the longest prefix's code") + #expect(uri.uri() == "https://www.example.com/a") + #expect(LinuxNDEFRecord.makeURI("not a uri") == nil) + let text = LinuxNDEFRecord.makeText("Hej", locale: "sv") + #expect(text.payload() == [2] + Array("sv".utf8) + Array("Hej".utf8)) + #expect(text.text() == "Hej" && text.textLanguage == "sv") + } + + @Test func messagesEncodeAndDecode() throws { + let message = LinuxNDEFMessage.make([ + try #require(LinuxNDEFRecord.makeURI("https://example.com")), + LinuxNDEFRecord.make(format: NDEFTypeNameFormat.media.rawValue, type: Array("text/plain".utf8), identifier: [7], + payload: [UInt8](repeating: 0x41, count: 300)), + ]) + let bytes = message.encoded() + #expect(bytes[0] == 0x91, "MB, SR, well-known") + #expect(message.length() == Int32(bytes.count)) + let decoded = try #require(LinuxNDEFMessage.decode(bytes)) + #expect(decoded.recordList.map(\.recordPayload) == message.recordList.map(\.recordPayload)) + #expect(decoded.recordList[1].recordIdentifier == [7]) + #expect(LinuxNDEFMessage.make([]).encoded() == [0xD0, 0x00, 0x00]) + #expect(LinuxNDEFMessage.decode([0xD0, 0x00, 0x00])?.recordList.isEmpty == true) + #expect(LinuxNDEFMessage.decode([0x91, 0x01]) == nil) + } + + // MARK: neard's records + + @Test func neardsRecordsAsNDEF() throws { + let objects: [String: NeardInterfaces] = [ + "/org/neard/nfc0/tag0": [Neard.tag: [:]], + "/org/neard/nfc0/tag0/record10": [Neard.record: ["Type": .string("HandoverSelect")]], + "/org/neard/nfc0/tag0/record2": [Neard.record: [ + "Type": .string("MIME"), "MIME": .string("application/json"), "MIMEPayload": .byteArray(Array("{}".utf8)), + ]], + "/org/neard/nfc0/tag0/record0": [Neard.record: ["Type": .string("URI"), "URI": .string("tel:+15551234")]], + "/org/neard/nfc0/tag0/record1": [Neard.record: [ + "Type": .string("Text"), "Language": .string("de"), "Representation": .string("Hallo"), + ]], + "/org/neard/nfc0/tag0/record3": [Neard.record: [ + "Type": .string("SmartPoster"), "URI": .string("https://example.com"), "Representation": .string("Example"), + "Language": .string("en"), + ]], + "/org/neard/nfc0/tag0/record4": [Neard.record: ["Type": .string("AAR"), "AAR": .string("com.example.app")]], + "/org/neard/nfc0/tag1/record0": [Neard.record: ["Type": .string("URI"), "URI": .string("https://other.example")]], + ] + let records = NeardRecords.records(of: "/org/neard/nfc0/tag0", in: objects) + #expect(records.count == 5, "in order, the handover left out, and only this tag's") + #expect(records[0].uri() == "tel:+15551234" && records[0].payload().first == 0x05) + #expect(records[1].text() == "Hallo" && records[1].textLanguage == "de") + #expect(records[2].format == .media && records[2].type() == Array("application/json".utf8) && records[2].payload() == Array("{}".utf8)) + #expect(records[3].type() == NeardRecords.smartPosterType) + let poster = try #require(LinuxNDEFMessage.decode(records[3].payload())) + #expect(poster.recordList.map { $0.uri() ?? $0.text() } == ["https://example.com", "Example"]) + #expect(records[4].format == .external && records[4].type() == Array("android.com:pkg".utf8)) + #expect(records[4].payload() == Array("com.example.app".utf8)) + } + + @Test func ndefAsNeardWritesIt() throws { + let uri = try #require(LinuxNDEFRecord.makeURI("mailto:someone@example.com")) + #expect(NeardRecords.attributes(uri) == ["Type": .string("URI"), "URI": .string("mailto:someone@example.com")]) + let mime = LinuxNDEFRecord.make(format: NDEFTypeNameFormat.media.rawValue, type: Array("image/png".utf8), identifier: [], + payload: [0x89, 0x50]) + #expect(NeardRecords.attributes(mime) == ["Type": .string("MIME"), "MIME": .string("image/png"), "Payload": .byteArray([0x89, 0x50])]) + // neard makes its own Wi-Fi record for this type. + let wifi = LinuxNDEFRecord.make(format: NDEFTypeNameFormat.media.rawValue, type: Array("application/vnd.wfa.wsc".utf8), + identifier: [], payload: [1]) + #expect(NeardRecords.attributes(wifi) == nil) + let poster = LinuxNDEFRecord.make(format: NDEFTypeNameFormat.wellKnown.rawValue, type: NeardRecords.smartPosterType, + identifier: [], payload: []) + #expect(NeardRecords.attributes(poster) == nil) + #expect(NeardRecords.attributes(LinuxNDEFMessage.make([uri, poster])) == nil, "every record or none") + } +} diff --git a/Tests/LinuxPackagerTests/PackagerTests.swift b/Tests/LinuxPackagerTests/PackagerTests.swift index c3e9652..62d568d 100644 --- a/Tests/LinuxPackagerTests/PackagerTests.swift +++ b/Tests/LinuxPackagerTests/PackagerTests.swift @@ -33,13 +33,13 @@ import Testing @Test func contractsThisHostLacks() throws { let fixture = try Fixture(contracts: [ - ("org.pureswift.nfc.Reader", 1, "contract"), + ("org.pureswift.notifications.Notifications", 1, "contract"), ("org.pureswift.ui.Renderer", 99, "contract"), ("org.pureswift.ui.RendererDelegate", 1, "contract"), ]) let strict = try diagnostics(fixture) #expect(strict.filter { $0.severity == .error }.map(\.message) == [ - "org.pureswift.nfc.Reader isn't implemented on Linux", + "org.pureswift.notifications.Notifications isn't implemented on Linux", "org.pureswift.ui.RendererDelegate is a different kind of interface on Linux", ]) #expect(strict.contains { $0.severity == .warning && $0.message.contains("Renderer is version") }) @@ -98,6 +98,18 @@ import Testing #expect(try diagnostics(fixture).map(\.message) == []) } + @Test func nfcIsImplemented() throws { + let fixture = try Fixture(contracts: [ + ("org.pureswift.ui.Renderer", 1, "contract"), + ("org.pureswift.nfc.Reader", 1, "contract"), + ("org.pureswift.nfc.ReaderDelegate", 1, "callback"), + ("org.pureswift.nfc.Tag", 1, "contract"), + ("org.pureswift.nfc.NDEFMessage", 1, "contract"), + ("org.pureswift.nfc.NDEFRecord", 1, "contract"), + ], capabilities: ["nfc"]) + #expect(try diagnostics(fixture).map(\.message) == []) + } + /// AppRuntime's `RuntimeNetworking`, over `FoundationNetworking`. @Test func networkingIsImplemented() throws { let fixture = try Fixture(contracts: [ @@ -168,8 +180,8 @@ import Testing } @Test func capabilitiesWithoutSupportWarn() throws { - let messages = try diagnostics(Fixture(capabilities: ["bluetooth", "location", "motion", "nfc"])) - #expect(messages == [.warning("the app declares nfc, which the Linux host doesn't support yet")]) + let messages = try diagnostics(Fixture(capabilities: ["bluetooth", "location", "motion", "nfc", "notifications"])) + #expect(messages == [.warning("the app declares notifications, which the Linux host doesn't support yet")]) } @Test func theHostAndThePackagerAgreeOnModules() {