diff --git a/.github/workflows/meshcore-portability.yml b/.github/workflows/meshcore-portability.yml new file mode 100644 index 0000000000..b330416342 --- /dev/null +++ b/.github/workflows/meshcore-portability.yml @@ -0,0 +1,32 @@ +name: MeshCore Portability + +on: + pull_request: + branches: + - main + - dev + paths: + - 'MeshCore/**' + - '.github/workflows/meshcore-portability.yml' + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + linux-build: + name: Build MeshCore on Linux + runs-on: ubuntu-latest + container: + image: swift:6.2-noble + timeout-minutes: 15 + + steps: + - name: Checkout + uses: actions/checkout@v6 + with: + submodules: recursive + + - name: Build MeshCore library target + run: swift build --package-path MeshCore --target MeshCore diff --git a/.gitignore b/.gitignore index 8ce74d4cb0..73fd52cab3 100644 --- a/.gitignore +++ b/.gitignore @@ -113,3 +113,6 @@ __pycache__ .idea/ # Brainstorming visual companion mockups .superpowers/ + +# Local +radio-dev.env diff --git a/.swiftformat b/.swiftformat index 0a8cbbf13b..000f338b18 100644 --- a/.swiftformat +++ b/.swiftformat @@ -4,7 +4,7 @@ --swiftversion 6.2 # Match .swiftlint.yml exclusions ---exclude .build,.worktrees,build,tmp,MC1.xcodeproj,MC1/Resources/Generated,MeshCore/.build,mc-ref,MC1Services/.build,fastlane,scripts +--exclude .build,.worktrees,build,tmp,MC1.xcodeproj,MC1/Resources/Generated,MeshCore/.build,MeshCoreBridge/.build,mc-ref,MC1Services/.build,fastlane,scripts # Indentation — 2 spaces, no tabs --indent 2 diff --git a/.swiftlint.yml b/.swiftlint.yml index b4fb161bff..8959cc8113 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -8,6 +8,7 @@ excluded: - MC1.xcodeproj - MC1/Resources/Generated - MeshCore/.build + - MeshCoreBridge/.build - mc-ref - MC1Services/.build - fastlane diff --git a/Makefile b/Makefile index 5b10e87df7..cab7f80f14 100644 --- a/Makefile +++ b/Makefile @@ -78,7 +78,7 @@ XCSIFT_WITH_HEARTBEAT = { \ .NOTPARALLEL: help: ## List available targets - @grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) \ + @grep -h -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) \ | awk 'BEGIN {FS = ":.*?## "}; {printf " %-14s %s\n", $$1, $$2}' define DEV_YML_STUB @@ -132,3 +132,6 @@ test-store: generate ## Run every StoreKit/IAP SKTestSession suite on iOS 18.x -collect-test-diagnostics never \ 2>&1 | { if [ -n "$(TEST_LOG)" ]; then tee "$(TEST_LOG)"; else cat; fi; } \ | $(XCSIFT_WITH_HEARTBEAT) + +# Optional branch-local targets (e.g. Android port parity/bridge helpers on multiplatform). +-include multiplatform/Makefile diff --git a/MeshCore/Package.swift b/MeshCore/Package.swift index 3e02fdaf65..72ca3b64b2 100644 --- a/MeshCore/Package.swift +++ b/MeshCore/Package.swift @@ -18,11 +18,27 @@ let package = Package( ) ], dependencies: [ - .package(url: "https://github.com/apple/swift-docc-plugin", from: "1.4.0") + .package(url: "https://github.com/apple/swift-docc-plugin", from: "1.4.0"), + // swift-crypto backs CryptoKit off Apple. CryptoExtras emulates AES-128-ECB. + // The portability fixture passed against 5.0.0. Apple builds use CryptoKit + // and CommonCrypto, so those products are not linked there. + .package(url: "https://github.com/apple/swift-crypto.git", exact: "5.0.0") ], targets: [ .target( - name: "MeshCore" + name: "MeshCore", + dependencies: [ + .product( + name: "Crypto", + package: "swift-crypto", + condition: .when(platforms: [.android, .linux, .windows]) + ), + .product( + name: "CryptoExtras", + package: "swift-crypto", + condition: .when(platforms: [.android, .linux, .windows]) + ) + ] ), .target( name: "MeshCoreTestSupport", diff --git a/MeshCore/Sources/MeshCore/Compat/OSAllocatedUnfairLock.swift b/MeshCore/Sources/MeshCore/Compat/OSAllocatedUnfairLock.swift new file mode 100644 index 0000000000..b31311d385 --- /dev/null +++ b/MeshCore/Sources/MeshCore/Compat/OSAllocatedUnfairLock.swift @@ -0,0 +1,25 @@ +#if !canImport(os) + import Foundation + + /// Source-compatible replacement for `os.OSAllocatedUnfairLock`, compiled only + /// where `os` is unavailable. Backed by `NSLock`. Exposes `init(initialState:)`, + /// closure `withLock`, and a key-path read. + final class OSAllocatedUnfairLock: @unchecked Sendable { + private let lock = NSLock() + private var state: State + + init(initialState: State) { + state = initialState + } + + func withLock(_ body: (inout State) throws -> R) rethrows -> R { + lock.lock() + defer { lock.unlock() } + return try body(&state) + } + + func withLock(_ keyPath: KeyPath) -> Member { + withLock { $0[keyPath: keyPath] } + } + } +#endif diff --git a/MeshCore/Sources/MeshCore/Compat/OSLogCompat.swift b/MeshCore/Sources/MeshCore/Compat/OSLogCompat.swift new file mode 100644 index 0000000000..3bf1f31cea --- /dev/null +++ b/MeshCore/Sources/MeshCore/Compat/OSLogCompat.swift @@ -0,0 +1,181 @@ +/// Renders one log interpolation the way unified logging does when no debugger is attached. +/// Numbers and booleans stay visible at the default privacy. Strings and other values do not. +enum MeshCoreLogRendering { + static func render(_ value: Any, privacy: MeshCoreLogPrivacy) -> String { + switch privacy { + case .public: + return String(describing: value) + case .private, .sensitive: + return redacted + case .auto: + guard isPublicByDefault(value) else { return redacted } + return String(describing: value) + } + } + + private static let redacted = "" + + private static func isPublicByDefault(_ value: Any) -> Bool { + switch value { + case is Bool, + is Int, is Int8, is Int16, is Int32, is Int64, + is UInt, is UInt8, is UInt16, is UInt32, is UInt64, + is Float, is Double: + true + default: + false + } + } +} + +enum MeshCoreLogPrivacy: Equatable { + case auto + case `public` + case `private` + case sensitive +} + +#if !canImport(os) + import Foundation + + // Source-compatible stand-ins for the Apple `os` logging API, compiled only + // where `os` is unavailable (Linux/Android). Call sites keep their + // `Logger(subsystem:category:)` / `logger.info("...")` shape unchanged; here + // those calls render the message and hand it to ``MeshCoreLog/sink``, which the + // Android bridge repoints at logcat. Defaults to stderr so nothing is silently lost. + + /// Global destination for rendered log lines on non-Apple platforms. + public enum MeshCoreLog { + private static let lock = NSLock() + private nonisolated(unsafe) static var handler: @Sendable (String) -> Void = { line in + FileHandle.standardError.write(Data((line + "\n").utf8)) + } + + /// The sink every ``Logger`` and ``OSSignposter`` message is delivered to. + /// Defaults to stderr; the Android bridge replaces it to route into logcat. + public static var sink: @Sendable (String) -> Void { + get { lock.withLock { handler } } + set { lock.withLock { handler = newValue } } + } + + static func emit(_ line: String) { + sink(line) + } + } + + /// Privacy markers so `\(value, privacy: .public)` interpolation compiles unchanged. + /// `.public` shows the value. `.private` and `.sensitive` do not. + struct OSLogPrivacy: Sendable { + fileprivate let level: MeshCoreLogPrivacy + + static let `public` = OSLogPrivacy(level: .public) + static let `private` = OSLogPrivacy(level: .private) + static let sensitive = OSLogPrivacy(level: .sensitive) + static let auto = OSLogPrivacy(level: .auto) + } + + /// A rendered log message. Interpolation keeps source order. + /// Values that unified logging would redact are replaced before the line is emitted. + struct OSLogMessage: ExpressibleByStringInterpolation, ExpressibleByStringLiteral, Sendable { + let rendered: String + + struct StringInterpolation: StringInterpolationProtocol { + var text = "" + init(literalCapacity: Int, interpolationCount: Int) { + text.reserveCapacity(literalCapacity) + } + + mutating func appendLiteral(_ literal: String) { + text += literal + } + + mutating func appendInterpolation( + _ value: @autoclosure () -> Any, + privacy: OSLogPrivacy = .auto + ) { + text += MeshCoreLogRendering.render(value(), privacy: privacy.level) + } + } + + init(stringLiteral value: String) { + rendered = value + } + + init(stringInterpolation: StringInterpolation) { + rendered = stringInterpolation.text + } + } + + /// Minimal `os.Logger` replacement that renders each message to ``MeshCoreLog``. + struct Logger: Sendable { + private let category: String + + init() { + category = "" + } + + init(subsystem: String, category: String) { + self.category = category + } + + func trace(_ message: OSLogMessage) { + emit("TRACE", message) + } + + func debug(_ message: OSLogMessage) { + emit("DEBUG", message) + } + + func info(_ message: OSLogMessage) { + emit("INFO", message) + } + + func notice(_ message: OSLogMessage) { + emit("NOTICE", message) + } + + func warning(_ message: OSLogMessage) { + emit("WARNING", message) + } + + func error(_ message: OSLogMessage) { + emit("ERROR", message) + } + + func critical(_ message: OSLogMessage) { + emit("CRITICAL", message) + } + + func fault(_ message: OSLogMessage) { + emit("FAULT", message) + } + + func log(_ message: OSLogMessage) { + emit("LOG", message) + } + + private func emit(_ level: String, _ message: OSLogMessage) { + let prefix = category.isEmpty ? "" : "[\(category)] " + MeshCoreLog.emit("\(prefix)\(level) \(message.rendered)") + } + } + + /// Minimal `OSSignposter` replacement. Instruments has no equivalent off Apple, + /// so events are routed to the same recoverable log sink. + struct OSSignposter: Sendable { + private let category: String + + init() { + category = "" + } + + init(subsystem: String, category: String) { + self.category = category + } + + func emitEvent(_ name: StaticString, _ message: OSLogMessage) { + let prefix = category.isEmpty ? "" : "[\(category)] " + MeshCoreLog.emit("\(prefix)SIGNPOST \(name) \(message.rendered)") + } + } +#endif diff --git a/MeshCore/Sources/MeshCore/Events/EventDispatcher.swift b/MeshCore/Sources/MeshCore/Events/EventDispatcher.swift index 8ef8521faf..2e3b890cee 100644 --- a/MeshCore/Sources/MeshCore/Events/EventDispatcher.swift +++ b/MeshCore/Sources/MeshCore/Events/EventDispatcher.swift @@ -1,5 +1,7 @@ import Foundation -import os +#if canImport(os) + import os +#endif private let dispatcherLogger = Logger(subsystem: "MeshCore", category: "EventDispatcher") private let dispatcherSignposter = OSSignposter(subsystem: "MeshCore", category: "EventDispatcher") diff --git a/MeshCore/Sources/MeshCore/Models/Destination.swift b/MeshCore/Sources/MeshCore/Models/Destination.swift index 920fc16c6b..5b205b7048 100644 --- a/MeshCore/Sources/MeshCore/Models/Destination.swift +++ b/MeshCore/Sources/MeshCore/Models/Destination.swift @@ -1,4 +1,8 @@ -import CryptoKit +#if canImport(CryptoKit) + import CryptoKit +#else + import Crypto +#endif import Foundation /// Defines the destination for a message or command in the mesh network. diff --git a/MeshCore/Sources/MeshCore/Protocol/AES128ECBFallback.swift b/MeshCore/Sources/MeshCore/Protocol/AES128ECBFallback.swift new file mode 100644 index 0000000000..d1c202a580 --- /dev/null +++ b/MeshCore/Sources/MeshCore/Protocol/AES128ECBFallback.swift @@ -0,0 +1,49 @@ +#if !canImport(CommonCrypto) + import Crypto + import CryptoExtras + import Foundation + + /// AES-128-ECB decryption built from CryptoExtras AES-CBC where CommonCrypto is absent. + /// ECB decrypts each 16-byte block on its own. CBC over one block with a zero IV reduces + /// to ECB for that block, because the plaintext is the decrypted block XORed with zero. + /// + /// Guards match the CommonCrypto path. A short key or a non-block length returns nil, + /// and empty input returns empty data. + enum AES128ECBFallback { + /// AES-128 key length in bytes. + static let keySize = 16 + + /// AES block size in bytes. + static let blockSize = 16 + + static func decrypt(ciphertext: Data, key: Data) -> Data? { + guard key.count >= keySize else { return nil } + guard ciphertext.count % blockSize == 0 else { return nil } + + let symmetricKey = SymmetricKey(data: key.prefix(keySize)) + guard let zeroIV = try? AES._CBC.IV(ivBytes: Array(repeating: UInt8(0), count: blockSize)) else { + return nil + } + + var plaintext = Data() + plaintext.reserveCapacity(ciphertext.count) + + var index = ciphertext.startIndex + while index < ciphertext.endIndex { + let blockEnd = ciphertext.index(index, offsetBy: blockSize) + guard let block = try? AES._CBC.decrypt( + ciphertext[index.. Data? { - guard key.count >= kCCKeySizeAES128 else { return nil } - guard ciphertext.count % kCCBlockSizeAES128 == 0 else { return nil } - - let keyBytes = key.prefix(kCCKeySizeAES128) - let bufferSize = ciphertext.count - var decrypted = Data(count: bufferSize) - var numBytesDecrypted: size_t = 0 - - let status = decrypted.withUnsafeMutableBytes { decryptedPtr in - ciphertext.withUnsafeBytes { ciphertextPtr in - keyBytes.withUnsafeBytes { keyPtr in - CCCrypt( - CCOperation(kCCDecrypt), - CCAlgorithm(kCCAlgorithmAES), - CCOptions(kCCOptionECBMode), - keyPtr.baseAddress, kCCKeySizeAES128, - nil, // No IV for ECB - ciphertextPtr.baseAddress, bufferSize, - decryptedPtr.baseAddress, bufferSize, - &numBytesDecrypted - ) + /// + /// Internal rather than private so cross-backend fixtures can pin its output. + /// The non-Apple backend must reproduce that output byte for byte. + static func decryptAES128ECB(ciphertext: Data, key: Data) -> Data? { + #if canImport(CommonCrypto) + guard key.count >= kCCKeySizeAES128 else { return nil } + guard ciphertext.count % kCCBlockSizeAES128 == 0 else { return nil } + + let keyBytes = key.prefix(kCCKeySizeAES128) + let bufferSize = ciphertext.count + var decrypted = Data(count: bufferSize) + var numBytesDecrypted: size_t = 0 + + let status = decrypted.withUnsafeMutableBytes { decryptedPtr in + ciphertext.withUnsafeBytes { ciphertextPtr in + keyBytes.withUnsafeBytes { keyPtr in + CCCrypt( + CCOperation(kCCDecrypt), + CCAlgorithm(kCCAlgorithmAES), + CCOptions(kCCOptionECBMode), + keyPtr.baseAddress, kCCKeySizeAES128, + nil, // No IV for ECB + ciphertextPtr.baseAddress, bufferSize, + decryptedPtr.baseAddress, bufferSize, + &numBytesDecrypted + ) + } } } - } - guard status == kCCSuccess else { return nil } - return Data(decrypted.prefix(numBytesDecrypted)) + guard status == kCCSuccess else { return nil } + return Data(decrypted.prefix(numBytesDecrypted)) + #else + return AES128ECBFallback.decrypt(ciphertext: ciphertext, key: key) + #endif } } diff --git a/MeshCore/Sources/MeshCore/Protocol/DirectMessageCrypto.swift b/MeshCore/Sources/MeshCore/Protocol/DirectMessageCrypto.swift index 89e20c019c..869bb93309 100644 --- a/MeshCore/Sources/MeshCore/Protocol/DirectMessageCrypto.swift +++ b/MeshCore/Sources/MeshCore/Protocol/DirectMessageCrypto.swift @@ -1,5 +1,11 @@ -import CommonCrypto -import CryptoKit +#if canImport(CommonCrypto) + import CommonCrypto +#endif +#if canImport(CryptoKit) + import CryptoKit +#else + import Crypto +#endif import Foundation /// Cryptographic operations for MeshCore direct (peer-to-peer) messages. @@ -165,32 +171,39 @@ public enum DirectMessageCrypto { } /// Decrypt data using AES-128 ECB mode. - private static func decryptAES128ECB(ciphertext: Data, key: Data) -> Data? { - guard key.count >= kCCKeySizeAES128 else { return nil } - guard ciphertext.count % kCCBlockSizeAES128 == 0 else { return nil } - - let keyBytes = key.prefix(kCCKeySizeAES128) - var decrypted = Data(count: ciphertext.count) - var numBytesDecrypted: size_t = 0 - - let status = decrypted.withUnsafeMutableBytes { decryptedPtr in - ciphertext.withUnsafeBytes { ciphertextPtr in - keyBytes.withUnsafeBytes { keyPtr in - CCCrypt( - CCOperation(kCCDecrypt), - CCAlgorithm(kCCAlgorithmAES), - CCOptions(kCCOptionECBMode), - keyPtr.baseAddress, kCCKeySizeAES128, - nil, - ciphertextPtr.baseAddress, ciphertext.count, - decryptedPtr.baseAddress, ciphertext.count, - &numBytesDecrypted - ) + /// + /// Internal rather than private so cross-backend fixtures can pin its output. + /// The non-Apple backend must reproduce that output byte for byte. + static func decryptAES128ECB(ciphertext: Data, key: Data) -> Data? { + #if canImport(CommonCrypto) + guard key.count >= kCCKeySizeAES128 else { return nil } + guard ciphertext.count % kCCBlockSizeAES128 == 0 else { return nil } + + let keyBytes = key.prefix(kCCKeySizeAES128) + var decrypted = Data(count: ciphertext.count) + var numBytesDecrypted: size_t = 0 + + let status = decrypted.withUnsafeMutableBytes { decryptedPtr in + ciphertext.withUnsafeBytes { ciphertextPtr in + keyBytes.withUnsafeBytes { keyPtr in + CCCrypt( + CCOperation(kCCDecrypt), + CCAlgorithm(kCCAlgorithmAES), + CCOptions(kCCOptionECBMode), + keyPtr.baseAddress, kCCKeySizeAES128, + nil, + ciphertextPtr.baseAddress, ciphertext.count, + decryptedPtr.baseAddress, ciphertext.count, + &numBytesDecrypted + ) + } } } - } - guard status == kCCSuccess else { return nil } - return Data(decrypted.prefix(numBytesDecrypted)) + guard status == kCCSuccess else { return nil } + return Data(decrypted.prefix(numBytesDecrypted)) + #else + return AES128ECBFallback.decrypt(ciphertext: ciphertext, key: key) + #endif } } diff --git a/MeshCore/Sources/MeshCore/Protocol/Parsers+Channels.swift b/MeshCore/Sources/MeshCore/Protocol/Parsers+Channels.swift index 9a2b51e52b..2cc421b571 100644 --- a/MeshCore/Sources/MeshCore/Protocol/Parsers+Channels.swift +++ b/MeshCore/Sources/MeshCore/Protocol/Parsers+Channels.swift @@ -1,5 +1,7 @@ import Foundation -import os +#if canImport(os) + import os +#endif extension Parsers { // MARK: - DefaultFloodScope diff --git a/MeshCore/Sources/MeshCore/Protocol/Parsers+Messaging.swift b/MeshCore/Sources/MeshCore/Protocol/Parsers+Messaging.swift index 12edb8d6a2..46ee599219 100644 --- a/MeshCore/Sources/MeshCore/Protocol/Parsers+Messaging.swift +++ b/MeshCore/Sources/MeshCore/Protocol/Parsers+Messaging.swift @@ -1,5 +1,7 @@ import Foundation -import os +#if canImport(os) + import os +#endif extension Parsers { // MARK: - ContactMessage diff --git a/MeshCore/Sources/MeshCore/Protocol/Parsers.swift b/MeshCore/Sources/MeshCore/Protocol/Parsers.swift index d40aa72919..bdac534cde 100644 --- a/MeshCore/Sources/MeshCore/Protocol/Parsers.swift +++ b/MeshCore/Sources/MeshCore/Protocol/Parsers.swift @@ -1,5 +1,7 @@ import Foundation -import os +#if canImport(os) + import os +#endif // MARK: - Parser Logger diff --git a/MeshCore/Sources/MeshCore/Protocol/RxLogTypes.swift b/MeshCore/Sources/MeshCore/Protocol/RxLogTypes.swift index 754125ca58..891fdc7122 100644 --- a/MeshCore/Sources/MeshCore/Protocol/RxLogTypes.swift +++ b/MeshCore/Sources/MeshCore/Protocol/RxLogTypes.swift @@ -1,4 +1,8 @@ -import CryptoKit +#if canImport(CryptoKit) + import CryptoKit +#else + import Crypto +#endif import Foundation /// Route type extracted from header byte bits 0-1. diff --git a/MeshCore/Sources/MeshCore/Protocol/TransportCodeRegionResolver.swift b/MeshCore/Sources/MeshCore/Protocol/TransportCodeRegionResolver.swift index ea38f4ec8b..5e03e3c0c5 100644 --- a/MeshCore/Sources/MeshCore/Protocol/TransportCodeRegionResolver.swift +++ b/MeshCore/Sources/MeshCore/Protocol/TransportCodeRegionResolver.swift @@ -1,4 +1,8 @@ -import CryptoKit +#if canImport(CryptoKit) + import CryptoKit +#else + import Crypto +#endif import Foundation /// Resolves the per-message flood region a packet was transmitted under, by diff --git a/MeshCore/Sources/MeshCore/Session/ContactManager.swift b/MeshCore/Sources/MeshCore/Session/ContactManager.swift index 4449da0ec3..d4dd683610 100644 --- a/MeshCore/Sources/MeshCore/Session/ContactManager.swift +++ b/MeshCore/Sources/MeshCore/Session/ContactManager.swift @@ -1,5 +1,7 @@ import Foundation -import os +#if canImport(os) + import os +#endif /// Manages contact storage, caching, and lifecycle. /// @@ -49,7 +51,8 @@ struct ContactManager { /// /// - Parameters: /// - name: The name to search for. - /// - exactMatch: If true, requires an exact case-insensitive match; otherwise, uses localized search. + /// - exactMatch: If true, requires an exact case-insensitive match. + /// Otherwise uses localized search. /// - Returns: The matching `MeshContact`, or `nil` if not found. func getByName(_ name: String, exactMatch: Bool = false) -> MeshContact? { if exactMatch { diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+BinaryProtocol.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+BinaryProtocol.swift index 1a962d121b..5bea2b1ce5 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+BinaryProtocol.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+BinaryProtocol.swift @@ -1,5 +1,7 @@ import Foundation -import os +#if canImport(os) + import os +#endif public extension MeshCoreSession { // MARK: - Status Requests diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift index 00487b29dc..0a7751522a 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+ChannelSending.swift @@ -1,5 +1,7 @@ import Foundation -import Synchronization +#if canImport(Synchronization) + import Synchronization +#endif public extension MeshCoreSession { /// Sends a message to a channel. @@ -29,6 +31,56 @@ public extension MeshCoreSession { try await performChannelSend(channel: channel, text: text, timestamp: timestamp, floodScope: floodScope) } + /// Reads the channel and sends while holding one command slot, so another command cannot land between them. + func sendVerifiedChannelMessage( + channel: UInt8, + text: String, + timestamp: Date, + floodScope: ResolvedFloodScope?, + expectedSecret: Data + ) async throws { + let cancelled = Mutex(false) + let isCancelled: @Sendable () -> Bool = { cancelled.withLock { $0 } } + let message = PacketBuilder.sendChannelMessage(channel: channel, text: text, timestamp: timestamp) + try await withTaskCancellationHandler { + try await requestResponseSerializer.withSerialization(resumeCallerOnCancel: false) { [self] in + let _: Bool = try await sendAndMatchHoldingSerialization( + PacketBuilder.getChannel(index: channel), + beforeSend: { + if isCancelled() { throw CancellationError() } + } + ) { event in + if case let .error(code) = event, code == ErrorCode.notFound.rawValue { + return .failure(Self.channelOccupancyMismatch) + } + if let error = Self.deviceErrorMatcher(event) { return .failure(error) } + guard case let .channelInfo(info) = event, info.index == channel else { return .ignore } + guard info.secret == expectedSecret, + !info.name.isEmpty || info.secret.contains(where: { $0 != 0 }) else { + return .failure(Self.channelOccupancyMismatch) + } + return .success(true) + } + if isCancelled() { throw CancellationError() } + if let floodScope { + try await sendWithTemporaryFloodScope( + message: message, floodScope: floodScope, isCancelled: isCancelled + ) + } else { + let _: Bool = try await sendAndMatchHoldingSerialization(message, beforeSend: { + if isCancelled() { throw CancellationError() } + }) { event in + if let error = Self.deviceErrorMatcher(event) { return .failure(error) } + if case .ok(nil) = event { return .success(true) } + return .ignore + } + } + } + } onCancel: { + cancelled.withLock { $0 = true } + } + } + private func performChannelSend( channel: UInt8, text: String, @@ -108,6 +160,10 @@ public extension MeshCoreSession { _ = await settleChannelCommand(Self.floodScopeBaselineCommand) } + private static let channelOccupancyMismatch = MeshCoreError.invalidResponse( + expected: "unchanged channel occupancy", got: "different or missing channel occupancy" + ) + private static let floodScopeBaselineCommand = PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey()) private static func temporaryScopeCommand(_ floodScope: ResolvedFloodScope) -> (command: Data, restoresBaseline: Bool) { diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift index ef135c0a3a..737320314e 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+Messaging.swift @@ -1,5 +1,7 @@ import Foundation -import os +#if canImport(os) + import os +#endif public extension MeshCoreSession { // MARK: - Messaging Commands diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+TransportWrites.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+TransportWrites.swift index 6e5f1250c9..6e209f6161 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession+TransportWrites.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession+TransportWrites.swift @@ -46,13 +46,17 @@ extension MeshCoreSession { static func linkRejectedWriteBeforeSubmission(_ error: Error) -> Bool { switch error { case MeshTransportError.notConnected, - WiFiTransportError.notConnected, MeshCoreError.notConnected, MeshCoreError.bluetoothUnavailable, MeshCoreError.bluetoothUnauthorized, MeshCoreError.bluetoothPoweredOff, MeshCoreError.sessionNotStarted: return true + // WiFiTransportError is compiled only with Network, so this case is too. + #if canImport(Network) + case WiFiTransportError.notConnected: + return true + #endif default: if case MeshCoreError.connectionLost = error { return true } return false diff --git a/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift b/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift index be9fb83761..929082a9e0 100644 --- a/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift +++ b/MeshCore/Sources/MeshCore/Session/MeshCoreSession.swift @@ -1,5 +1,7 @@ import Foundation -import os +#if canImport(os) + import os +#endif /// Main session actor for MeshCore device communication. /// diff --git a/MeshCore/Sources/MeshCore/Session/PowerOffExchange.swift b/MeshCore/Sources/MeshCore/Session/PowerOffExchange.swift index 131e201c46..97505f4518 100644 --- a/MeshCore/Sources/MeshCore/Session/PowerOffExchange.swift +++ b/MeshCore/Sources/MeshCore/Session/PowerOffExchange.swift @@ -1,5 +1,9 @@ +// Android's Foundation overlay does not re-export CFAbsoluteTime. +import CoreFoundation import Foundation -import os +#if canImport(os) + import os +#endif /// Silence is the only submitted result that means the radio powered off. /// A reply, rejection, write error, or stopped session does not. diff --git a/MeshCore/Sources/MeshCore/Session/RadioCLICorrelationScope.swift b/MeshCore/Sources/MeshCore/Session/RadioCLICorrelationScope.swift index bf1b8f004c..7d02d20bdf 100644 --- a/MeshCore/Sources/MeshCore/Session/RadioCLICorrelationScope.swift +++ b/MeshCore/Sources/MeshCore/Session/RadioCLICorrelationScope.swift @@ -1,5 +1,7 @@ import Foundation -import Synchronization +#if canImport(Synchronization) + import Synchronization +#endif /// CLI request tags remain reserved until their connection request retires. public final class RadioCLICorrelationScope: Sendable { diff --git a/MeshCore/Sources/MeshCore/Session/RequestContext.swift b/MeshCore/Sources/MeshCore/Session/RequestContext.swift index c2fd270970..2b882bf21f 100644 --- a/MeshCore/Sources/MeshCore/Session/RequestContext.swift +++ b/MeshCore/Sources/MeshCore/Session/RequestContext.swift @@ -1,5 +1,7 @@ import Foundation -import os +#if canImport(os) + import os +#endif /// Serializes every command-response exchange that relies on event matching. /// diff --git a/MeshCore/Sources/MeshCore/Session/SubmittedCommandWindow.swift b/MeshCore/Sources/MeshCore/Session/SubmittedCommandWindow.swift index dd2521a1f3..877df815fb 100644 --- a/MeshCore/Sources/MeshCore/Session/SubmittedCommandWindow.swift +++ b/MeshCore/Sources/MeshCore/Session/SubmittedCommandWindow.swift @@ -1,4 +1,6 @@ -import Synchronization +#if canImport(Synchronization) + import Synchronization +#endif /// Replies dispatched before `begin` do not prove the write that opens this window. final class SubmittedCommandWindow: Sendable { diff --git a/MeshCore/Sources/MeshCore/Transport/SessionTransportBinding.swift b/MeshCore/Sources/MeshCore/Transport/SessionTransportBinding.swift index 5305e8eec1..8e56ee3b23 100644 --- a/MeshCore/Sources/MeshCore/Transport/SessionTransportBinding.swift +++ b/MeshCore/Sources/MeshCore/Transport/SessionTransportBinding.swift @@ -1,4 +1,6 @@ -import Synchronization +#if canImport(Synchronization) + import Synchronization +#endif /// Revocable command admission for one session over a caller-owned transport. public final class SessionTransportBinding: Sendable { diff --git a/MeshCore/Sources/MeshCore/Transport/WiFiTransport.swift b/MeshCore/Sources/MeshCore/Transport/WiFiTransport.swift index 2b3fbe2723..1e953e7748 100644 --- a/MeshCore/Sources/MeshCore/Transport/WiFiTransport.swift +++ b/MeshCore/Sources/MeshCore/Transport/WiFiTransport.swift @@ -1,411 +1,413 @@ -import Foundation -import Network -import os - -/// Errors that can occur during WiFi transport operations. -public enum WiFiTransportError: Error, Sendable, Equatable { - case connectionFailed(String) - case connectionTimeout - case notConnected - case sendFailed(String) - case sendTimeout - case invalidHost - case invalidPort - case notConfigured -} - -/// TCP transport for connecting to MeshCore devices over WiFi. -/// -/// Configure connection info before calling `connect()`: -/// ```swift -/// let transport = WiFiTransport() -/// await transport.setConnectionInfo(host: "192.168.1.50", port: 5000) -/// try await transport.connect() -/// ``` -public actor WiFiTransport: MeshTransport { - private let logger = Logger(subsystem: "MeshCore", category: "WiFiTransport") - - private var connection: NWConnection? - private var frameDecoder = WiFiFrameDecoder() - - // AsyncStream created in init so receivedData is valid before connect() - private let dataStream: AsyncStream - private let dataContinuation: AsyncStream.Continuation - - private var _isConnected = false - - // Connection configuration (set before connect()) - private var configuredHost: String? - private var configuredPort: UInt16? - - /// Thread-safe continuation state (protects against multiple resumes) - private var connectContinuation: CheckedContinuation? - - /// Disconnection notification - private var disconnectionHandler: (@Sendable (Error?, CFAbsoluteTime) -> Void)? - - // MARK: - Configuration - - /// Connection timeout duration - public static let connectionTimeout: Duration = .seconds(10) - - /// Write timeout duration - public static let writeTimeout: Duration = .seconds(5) - - // MARK: - MeshTransport Protocol - - public var receivedData: AsyncStream { - dataStream +#if canImport(Network) + import Foundation + import Network + import os + + /// Errors that can occur during WiFi transport operations. + public enum WiFiTransportError: Error, Sendable, Equatable { + case connectionFailed(String) + case connectionTimeout + case notConnected + case sendFailed(String) + case sendTimeout + case invalidHost + case invalidPort + case notConfigured } - public var isConnected: Bool { - _isConnected - } + /// TCP transport for connecting to MeshCore devices over WiFi. + /// + /// Configure connection info before calling `connect()`: + /// ```swift + /// let transport = WiFiTransport() + /// await transport.setConnectionInfo(host: "192.168.1.50", port: 5000) + /// try await transport.connect() + /// ``` + public actor WiFiTransport: MeshTransport { + private let logger = Logger(subsystem: "MeshCore", category: "WiFiTransport") - /// TCP streams pipeline natively: back-to-back sends queue in the socket buffer and the radio - /// drains them at its loop cadence, so windowed channel reads avoid the per-round-trip stall - /// that serial reads pay over WiFi. There is no ATT write characteristic, so - /// `supportsWriteWithoutResponse` stays false and `sendWithoutResponse` routes to `send`. - public var supportsPipelinedReads: Bool { - true - } + private var connection: NWConnection? + private var frameDecoder = WiFiFrameDecoder() - public init() { - // Create stream in init so receivedData is valid before connect() - let (stream, continuation) = AsyncStream.makeStream() - dataStream = stream - dataContinuation = continuation - } + // AsyncStream created in init so receivedData is valid before connect() + private let dataStream: AsyncStream + private let dataContinuation: AsyncStream.Continuation - /// Configures the connection target. Must be called before `connect()`. - public func setConnectionInfo(host: String, port: UInt16) { - configuredHost = host - configuredPort = port - } + private var _isConnected = false - /// Sets a handler to be called when the connection is unexpectedly lost. - public func setDisconnectionHandler(_ handler: @escaping @Sendable (Error?, CFAbsoluteTime) -> Void) { - disconnectionHandler = handler - } + // Connection configuration (set before connect()) + private var configuredHost: String? + private var configuredPort: UInt16? - /// Clears the disconnection handler (call before user-initiated disconnect) - public func clearDisconnectionHandler() { - disconnectionHandler = nil - } + /// Thread-safe continuation state (protects against multiple resumes) + private var connectContinuation: CheckedContinuation? - /// Returns the configured connection info, if set. - public var connectionInfo: (host: String, port: UInt16)? { - guard let host = configuredHost, let port = configuredPort else { return nil } - return (host, port) - } + /// Disconnection notification + private var disconnectionHandler: (@Sendable (Error?, CFAbsoluteTime) -> Void)? - /// Establishes a TCP connection to the configured host and port. - /// Call `setConnectionInfo(host:port:)` first. - public func connect() async throws { - try await performConnect(sessionBinding: nil) - } + // MARK: - Configuration - public func connect(sessionBinding: SessionTransportBinding) async throws { - try await performConnect(sessionBinding: sessionBinding) - } + /// Connection timeout duration + public static let connectionTimeout: Duration = .seconds(10) + + /// Write timeout duration + public static let writeTimeout: Duration = .seconds(5) + + // MARK: - MeshTransport Protocol + + public var receivedData: AsyncStream { + dataStream + } + + public var isConnected: Bool { + _isConnected + } - private func performConnect(sessionBinding: SessionTransportBinding?) async throws { - try sessionBinding?.checkActive() - // Idempotent: skip if already connected. Without this guard, - // session.start() orphans the TCP connection the caller already established. - if _isConnected { - logger.info("Already connected, skipping redundant connect()") - return + /// TCP streams pipeline natively: back-to-back sends queue in the socket buffer and the radio + /// drains them at its loop cadence, so windowed channel reads avoid the per-round-trip stall + /// that serial reads pay over WiFi. There is no ATT write characteristic, so + /// `supportsWriteWithoutResponse` stays false and `sendWithoutResponse` routes to `send`. + public var supportsPipelinedReads: Bool { + true } - guard let host = configuredHost, let port = configuredPort else { - throw WiFiTransportError.notConfigured + public init() { + // Create stream in init so receivedData is valid before connect() + let (stream, continuation) = AsyncStream.makeStream() + dataStream = stream + dataContinuation = continuation } - logger.info("Connecting to \(host):\(port)") + /// Configures the connection target. Must be called before `connect()`. + public func setConnectionInfo(host: String, port: UInt16) { + configuredHost = host + configuredPort = port + } - let hostEndpoint = NWEndpoint.Host(host) - guard let portEndpoint = NWEndpoint.Port(rawValue: port) else { - throw WiFiTransportError.invalidPort + /// Sets a handler to be called when the connection is unexpectedly lost. + public func setDisconnectionHandler(_ handler: @escaping @Sendable (Error?, CFAbsoluteTime) -> Void) { + disconnectionHandler = handler } - let endpoint = NWEndpoint.hostPort(host: hostEndpoint, port: portEndpoint) + /// Clears the disconnection handler (call before user-initiated disconnect) + public func clearDisconnectionHandler() { + disconnectionHandler = nil + } - // Disable Nagle's algorithm. The companion protocol is small-frame request-response - // (each getChannel is one command and one reply), and Nagle interacting with the peer's - // delayed-ACK injects a fixed per-round-trip stall that serial channel reads pay once per - // channel. Streamed traffic such as contacts coalesces and hides it; ping-pong reads do not. - let tcpOptions = NWProtocolTCP.Options() - tcpOptions.noDelay = true - let parameters = NWParameters(tls: nil, tcp: tcpOptions) + /// Returns the configured connection info, if set. + public var connectionInfo: (host: String, port: UInt16)? { + guard let host = configuredHost, let port = configuredPort else { return nil } + return (host, port) + } - let newConnection = NWConnection(to: endpoint, using: parameters) - connection = newConnection + /// Establishes a TCP connection to the configured host and port. + /// Call `setConnectionInfo(host:port:)` first. + public func connect() async throws { + try await performConnect(sessionBinding: nil) + } + + public func connect(sessionBinding: SessionTransportBinding) async throws { + try await performConnect(sessionBinding: sessionBinding) + } - // Race connection against timeout - try await withThrowingTaskGroup(of: Void.self) { group in - group.addTask { - try await self.performConnection(newConnection, sessionBinding: sessionBinding) + private func performConnect(sessionBinding: SessionTransportBinding?) async throws { + try sessionBinding?.checkActive() + // Idempotent: skip if already connected. Without this guard, + // session.start() orphans the TCP connection the caller already established. + if _isConnected { + logger.info("Already connected, skipping redundant connect()") + return } - group.addTask { - try await Task.sleep(for: Self.connectionTimeout) - throw WiFiTransportError.connectionTimeout + guard let host = configuredHost, let port = configuredPort else { + throw WiFiTransportError.notConfigured } - // Wait for first task to complete or throw - do { - try await group.next() - group.cancelAll() - } catch { - group.cancelAll() - // Resume the parked connection continuation on every failure path, - // including caller-task cancellation; the group cannot finish - // tearing down while that child stays suspended. - self.cancelPendingConnection(throwing: error) - throw error + logger.info("Connecting to \(host):\(port)") + + let hostEndpoint = NWEndpoint.Host(host) + guard let portEndpoint = NWEndpoint.Port(rawValue: port) else { + throw WiFiTransportError.invalidPort } - } - startReceiving() - } + let endpoint = NWEndpoint.hostPort(host: hostEndpoint, port: portEndpoint) - /// Performs the actual connection wait via continuation. - private func performConnection(_ newConnection: NWConnection, sessionBinding: SessionTransportBinding?) async throws { - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - self.connectContinuation = continuation + // Disable Nagle's algorithm. The companion protocol is small-frame request-response + // (each getChannel is one command and one reply), and Nagle interacting with the peer's + // delayed-ACK injects a fixed per-round-trip stall that serial channel reads pay once per + // channel. Streamed traffic such as contacts coalesces and hides it; ping-pong reads do not. + let tcpOptions = NWProtocolTCP.Options() + tcpOptions.noDelay = true + let parameters = NWParameters(tls: nil, tcp: tcpOptions) - newConnection.stateUpdateHandler = { [weak self] state in - Task { [weak self] in - await self?.handleStateChange(state) + let newConnection = NWConnection(to: endpoint, using: parameters) + connection = newConnection + + // Race connection against timeout + try await withThrowingTaskGroup(of: Void.self) { group in + group.addTask { + try await self.performConnection(newConnection, sessionBinding: sessionBinding) + } + + group.addTask { + try await Task.sleep(for: Self.connectionTimeout) + throw WiFiTransportError.connectionTimeout + } + + // Wait for first task to complete or throw + do { + try await group.next() + group.cancelAll() + } catch { + group.cancelAll() + // Resume the parked connection continuation on every failure path, + // including caller-task cancellation; the group cannot finish + // tearing down while that child stays suspended. + self.cancelPendingConnection(throwing: error) + throw error } } - do { - if let sessionBinding { - try sessionBinding.performIfActive { + startReceiving() + } + + /// Performs the actual connection wait via continuation. + private func performConnection(_ newConnection: NWConnection, sessionBinding: SessionTransportBinding?) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + self.connectContinuation = continuation + + newConnection.stateUpdateHandler = { [weak self] state in + Task { [weak self] in + await self?.handleStateChange(state) + } + } + + do { + if let sessionBinding { + try sessionBinding.performIfActive { + newConnection.start(queue: .global(qos: .userInitiated)) + } + } else { newConnection.start(queue: .global(qos: .userInitiated)) } - } else { - newConnection.start(queue: .global(qos: .userInitiated)) + } catch { + connectContinuation = nil + continuation.resume(throwing: error) } - } catch { + } + } + + /// Cancels a pending connection attempt, resuming the parked + /// continuation with the error that caused the failure. + private func cancelPendingConnection(throwing error: Error) { + connection?.stateUpdateHandler = nil + connection?.cancel() + connection = nil + _isConnected = false + + if let continuation = connectContinuation { connectContinuation = nil continuation.resume(throwing: error) } } - } - /// Cancels a pending connection attempt, resuming the parked - /// continuation with the error that caused the failure. - private func cancelPendingConnection(throwing error: Error) { - connection?.stateUpdateHandler = nil - connection?.cancel() - connection = nil - _isConnected = false - - if let continuation = connectContinuation { - connectContinuation = nil - continuation.resume(throwing: error) - } - } + public func disconnect() async { + logger.info("Disconnecting") + disconnectionHandler = nil // Clear BEFORE cancel to prevent spurious callback + connection?.stateUpdateHandler = nil + connection?.cancel() + connection = nil + _isConnected = false + frameDecoder.reset() + dataContinuation.finish() - public func disconnect() async { - logger.info("Disconnecting") - disconnectionHandler = nil // Clear BEFORE cancel to prevent spurious callback - connection?.stateUpdateHandler = nil - connection?.cancel() - connection = nil - _isConnected = false - frameDecoder.reset() - dataContinuation.finish() - - // Clear any pending continuation - if let continuation = connectContinuation { - continuation.resume(throwing: WiFiTransportError.connectionFailed("Disconnected")) - connectContinuation = nil + // Clear any pending continuation + if let continuation = connectContinuation { + continuation.resume(throwing: WiFiTransportError.connectionFailed("Disconnected")) + connectContinuation = nil + } } - } - public func send(_ data: Data) async throws { - try await performSend(data, sessionBinding: nil) - } - - public func send(_ data: Data, sessionBinding: SessionTransportBinding) async throws { - try await performSend(data, sessionBinding: sessionBinding) - } + public func send(_ data: Data) async throws { + try await performSend(data, sessionBinding: nil) + } - public func sendWithoutResponse(_ data: Data, sessionBinding: SessionTransportBinding) async throws { - try await performSend(data, sessionBinding: sessionBinding) - } + public func send(_ data: Data, sessionBinding: SessionTransportBinding) async throws { + try await performSend(data, sessionBinding: sessionBinding) + } - private func performSend(_ data: Data, sessionBinding: SessionTransportBinding?) async throws { - try sessionBinding?.checkActive() - guard let connection, _isConnected else { - throw WiFiTransportError.notConnected + public func sendWithoutResponse(_ data: Data, sessionBinding: SessionTransportBinding) async throws { + try await performSend(data, sessionBinding: sessionBinding) } - let frame = WiFiFrameCodec.encode(data) + private func performSend(_ data: Data, sessionBinding: SessionTransportBinding?) async throws { + try sessionBinding?.checkActive() + guard let connection, _isConnected else { + throw WiFiTransportError.notConnected + } + + let frame = WiFiFrameCodec.encode(data) - try await withThrowingTaskGroup(of: Void.self) { group in - group.addTask { - // Lock-protected continuation prevents double-resume when both - // contentProcessed and onCancel fire - let state = OSAllocatedUnfairLock?>(initialState: nil) + try await withThrowingTaskGroup(of: Void.self) { group in + group.addTask { + // Lock-protected continuation prevents double-resume when both + // contentProcessed and onCancel fire + let state = OSAllocatedUnfairLock?>(initialState: nil) - try await withTaskCancellationHandler { - try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in - let alreadyCancelled = state.withLock { stored -> Bool in - if Task.isCancelled { - return true + try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + let alreadyCancelled = state.withLock { stored -> Bool in + if Task.isCancelled { + return true + } + stored = continuation + return false + } + if alreadyCancelled { + continuation.resume(throwing: WiFiTransportError.sendTimeout) + return } - stored = continuation - return false - } - if alreadyCancelled { - continuation.resume(throwing: WiFiTransportError.sendTimeout) - return - } - let submit = { - connection.send(content: frame, completion: .contentProcessed { error in - sessionBinding?.endOperation() - if let cont = state.withLock({ let cont = $0; $0 = nil; return cont }) { - if let error { - cont.resume(throwing: WiFiTransportError.sendFailed(error.localizedDescription)) - } else { - cont.resume() + let submit = { + connection.send(content: frame, completion: .contentProcessed { error in + sessionBinding?.endOperation() + if let cont = state.withLock({ let cont = $0; $0 = nil; return cont }) { + if let error { + cont.resume(throwing: WiFiTransportError.sendFailed(error.localizedDescription)) + } else { + cont.resume() + } + } + }) + } + do { + if let sessionBinding { + try sessionBinding.beginOperation() + do { + try sessionBinding.performIfActive(submit) + } catch { + sessionBinding.endOperation() + throw error } + } else { + submit() } - }) - } - do { - if let sessionBinding { - try sessionBinding.beginOperation() - do { - try sessionBinding.performIfActive(submit) - } catch { - sessionBinding.endOperation() - throw error + } catch { + let waiting = state.withLock { stored -> CheckedContinuation? in + let waiting = stored + stored = nil + return waiting } - } else { - submit() - } - } catch { - let waiting = state.withLock { stored -> CheckedContinuation? in - let waiting = stored - stored = nil - return waiting + waiting?.resume(throwing: error) } - waiting?.resume(throwing: error) } - } - } onCancel: { - if let cont = state.withLock({ let cont = $0; $0 = nil; return cont }) { - cont.resume(throwing: WiFiTransportError.sendTimeout) + } onCancel: { + if let cont = state.withLock({ let cont = $0; $0 = nil; return cont }) { + cont.resume(throwing: WiFiTransportError.sendTimeout) + } } } - } - group.addTask { - try await Task.sleep(for: Self.writeTimeout) - throw WiFiTransportError.sendTimeout - } + group.addTask { + try await Task.sleep(for: Self.writeTimeout) + throw WiFiTransportError.sendTimeout + } - try await group.next() - group.cancelAll() + try await group.next() + group.cancelAll() + } } - } - // MARK: - Private + // MARK: - Private + + /// Handles NWConnection state changes with safe one-time continuation resume. + private func handleStateChange(_ state: NWConnection.State) { + switch state { + case .ready: + logger.info("Connection ready") + _isConnected = true + // Safe one-time resume: consume and nil the continuation + if let continuation = connectContinuation { + connectContinuation = nil + continuation.resume() + } - /// Handles NWConnection state changes with safe one-time continuation resume. - private func handleStateChange(_ state: NWConnection.State) { - switch state { - case .ready: - logger.info("Connection ready") - _isConnected = true - // Safe one-time resume: consume and nil the continuation - if let continuation = connectContinuation { - connectContinuation = nil - continuation.resume() - } + case let .failed(error): + logger.error("Connection failed: \(error.localizedDescription)") + if let continuation = connectContinuation { + _isConnected = false + connectContinuation = nil + continuation.resume(throwing: WiFiTransportError.connectionFailed(error.localizedDescription)) + } else { + handleReceiveTermination(error) + } - case let .failed(error): - logger.error("Connection failed: \(error.localizedDescription)") - if let continuation = connectContinuation { - _isConnected = false - connectContinuation = nil - continuation.resume(throwing: WiFiTransportError.connectionFailed(error.localizedDescription)) - } else { - handleReceiveTermination(error) - } + case .cancelled: + logger.info("Connection cancelled") + handleReceiveTermination(nil) - case .cancelled: - logger.info("Connection cancelled") - handleReceiveTermination(nil) + case let .waiting(error): + logger.warning("Connection waiting: \(error.localizedDescription)") + // For invalid addresses, the connection goes to waiting state with an error + // Treat this as a connection failure + _isConnected = false + if let continuation = connectContinuation { + connectContinuation = nil + continuation.resume(throwing: WiFiTransportError.connectionFailed(error.localizedDescription)) + } - case let .waiting(error): - logger.warning("Connection waiting: \(error.localizedDescription)") - // For invalid addresses, the connection goes to waiting state with an error - // Treat this as a connection failure - _isConnected = false - if let continuation = connectContinuation { - connectContinuation = nil - continuation.resume(throwing: WiFiTransportError.connectionFailed(error.localizedDescription)) + default: + break } - - default: - break } - } - private func startReceiving() { - guard let connection else { return } + private func startReceiving() { + guard let connection else { return } - connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] content, _, isComplete, error in - Task { [weak self] in - guard let self else { return } + connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] content, _, isComplete, error in + Task { [weak self] in + guard let self else { return } - if let data = content { - await processReceivedData(data) - } + if let data = content { + await processReceivedData(data) + } - if let error { - logger.error("Receive error: \(error.localizedDescription)") - await handleReceiveTermination(error) - return - } + if let error { + logger.error("Receive error: \(error.localizedDescription)") + await handleReceiveTermination(error) + return + } - if isComplete { - logger.info("Connection closed by peer") - await handleReceiveTermination(nil) - return - } + if isComplete { + logger.info("Connection closed by peer") + await handleReceiveTermination(nil) + return + } - guard await _isConnected else { return } - await startReceiving() + guard await _isConnected else { return } + await startReceiving() + } } } - } - /// Finishes the stream on connection loss. The connected guard makes state and - /// receive callbacks share one teardown and one disconnection notification. - private func handleReceiveTermination(_ error: Error?) { - guard _isConnected else { return } - _isConnected = false - connection?.stateUpdateHandler = nil - connection?.cancel() - connection = nil - frameDecoder.reset() - dataContinuation.finish() - disconnectionHandler?(error, CFAbsoluteTimeGetCurrent()) - } + /// Finishes the stream on connection loss. The connected guard makes state and + /// receive callbacks share one teardown and one disconnection notification. + private func handleReceiveTermination(_ error: Error?) { + guard _isConnected else { return } + _isConnected = false + connection?.stateUpdateHandler = nil + connection?.cancel() + connection = nil + frameDecoder.reset() + dataContinuation.finish() + disconnectionHandler?(error, CFAbsoluteTimeGetCurrent()) + } - private func processReceivedData(_ data: Data) { - let frames = frameDecoder.decode(data) - for frame in frames { - dataContinuation.yield(frame) + private func processReceivedData(_ data: Data) { + let frames = frameDecoder.decode(data) + for frame in frames { + dataContinuation.yield(frame) + } } } -} +#endif diff --git a/MeshCore/Tests/MeshCoreTests/AES128ECBPortabilityTests.swift b/MeshCore/Tests/MeshCoreTests/AES128ECBPortabilityTests.swift new file mode 100644 index 0000000000..ef4abc6d3d --- /dev/null +++ b/MeshCore/Tests/MeshCoreTests/AES128ECBPortabilityTests.swift @@ -0,0 +1,120 @@ +import Foundation +@testable import MeshCore +import Testing + +/// Golden vectors for the AES-128-ECB decrypt path. +/// +/// Each build runs the backend it ships. Apple runs CommonCrypto. Other platforms +/// run the CryptoExtras fallback. Every expectation is a hardcoded value, so both +/// backends are held to the same bytes. +@Suite("AES128ECB portability") +struct AES128ECBPortabilityTests { + /// Decode a lowercase hex string into raw bytes. + private func bytes(_ hex: String) -> Data { + var data = Data(capacity: hex.count / 2) + var index = hex.startIndex + while index < hex.endIndex { + let next = hex.index(index, offsetBy: 2) + data.append(UInt8(hex[index.. String { + data.map { String(format: "%02x", $0) }.joined() + } + + // MARK: - Golden decrypt vectors (full public API) + + @Test + func `Channel golden vector decrypts to Alice's message`() { + let secret = bytes("8b3387e9c5cdea6ac9e5edbaa115cd72") + let payload = bytes("a0e6215565cf0555d9e4a5e4824dc70018a6021e8232bb0509500bdf22a90e97978f") + + let result = ChannelCrypto.decrypt(payload: payload, secret: secret) + + guard case let .success(timestamp, txtType, text) = result else { + Issue.record("Expected success, got \(result)") + return + } + #expect(timestamp == 1_703_123_456) + #expect(txtType == 0) + #expect(text == "Alice: Hello mesh!") + } + + @Test + func `Direct-message golden vector decrypts to Bob's message`() { + // Deterministic vector generated on macOS against the CommonCrypto backend: + // recipient private key + sender public key + packet, ECDH Curve25519 + AES-128-ECB. + let recipientPrivateKey = bytes("404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f") + let senderPublicKey = bytes("493e82fc74464a59268817623d2053c5eb8e2cc4a988b4fee179ec6b010d531d") + let payload = bytes("7949de3e62023be8bf381289cbcac08ab1806843471af02034b07334c365c90be841bb86") + + let result = DirectMessageCrypto.decrypt( + payload: payload, + myPrivateKey: recipientPrivateKey, + senderPublicKey: senderPublicKey + ) + + #expect(result == .success(timestamp: 1_703_123_456, typeAttempt: 0, text: "Bob: DM golden vector")) + } + + // MARK: - Edge-case semantics pinned against the CommonCrypto backend + + /// Any 16-byte block and the two keys used across the edge cases. + private let block = Data(repeating: 0xAB, count: 16) + private let key16 = Data((0..<16).map { UInt8($0) }) + private let key15 = Data((0..<15).map { UInt8($0) }) + private let key32 = Data((0..<32).map { UInt8($0) }) + /// Decryption of `block` under the first 16 bytes of the key sequence. + private let blockPlaintext = "ee237802b6ecc7c37391f79115ba0d6a" + + @Test + func `Empty ciphertext yields empty data, not nil`() { + let result = ChannelCrypto.decryptAES128ECB(ciphertext: Data(), key: key16) + #expect(result == Data()) + } + + @Test + func `Ciphertext length not a multiple of the block size yields nil`() { + let result = ChannelCrypto.decryptAES128ECB(ciphertext: Data(repeating: 0x01, count: 17), key: key16) + #expect(result == nil) + } + + @Test + func `Key shorter than the AES key length yields nil`() { + let result = ChannelCrypto.decryptAES128ECB(ciphertext: block, key: key15) + #expect(result == nil) + } + + @Test + func `Key longer than the AES key length uses only the first 16 bytes`() { + let result = ChannelCrypto.decryptAES128ECB(ciphertext: block, key: key32) + #expect(result.map(hex) == blockPlaintext) + #expect(ChannelCrypto.decryptAES128ECB(ciphertext: block, key: key32.prefix(16)).map(hex) == blockPlaintext) + } + + @Test + func `Direct-message backend shares the same edge-case semantics`() { + #expect(DirectMessageCrypto.decryptAES128ECB(ciphertext: Data(), key: key16) == Data()) + #expect(DirectMessageCrypto.decryptAES128ECB(ciphertext: Data(repeating: 0x01, count: 17), key: key16) == nil) + #expect(DirectMessageCrypto.decryptAES128ECB(ciphertext: block, key: key15) == nil) + #expect(DirectMessageCrypto.decryptAES128ECB(ciphertext: block, key: key32).map(hex) == blockPlaintext) + } + + /// Raw ECB plaintext for the 32-byte channel ciphertext, including the timestamp, + /// text type, message, and zero padding. Both backends must produce these bytes. + private let twoBlockPlaintext = "009a836500416c6963653a2048656c6c6f206d65736821000000000000000000" + + @Test + func `Two-block channel ciphertext matches the pinned plaintext`() { + let secret = bytes("8b3387e9c5cdea6ac9e5edbaa115cd72") + let payload = bytes("a0e6215565cf0555d9e4a5e4824dc70018a6021e8232bb0509500bdf22a90e97978f") + let ciphertext = Data(payload.dropFirst(ChannelCrypto.macSize)) + + #expect(ciphertext.count == 32) + let plaintext = ChannelCrypto.decryptAES128ECB(ciphertext: ciphertext, key: secret) + #expect(plaintext.map(hex) == twoBlockPlaintext) + } +} diff --git a/MeshCore/Tests/MeshCoreTests/LogPrivacyTests.swift b/MeshCore/Tests/MeshCoreTests/LogPrivacyTests.swift new file mode 100644 index 0000000000..593ebd5ff3 --- /dev/null +++ b/MeshCore/Tests/MeshCoreTests/LogPrivacyTests.swift @@ -0,0 +1,19 @@ +import Foundation +@testable import MeshCore +import Testing + +@Suite("Log privacy") +struct LogPrivacyTests { + @Test + func `Default privacy shows numbers and redacts strings`() { + #expect(MeshCoreLogRendering.render("radio", privacy: .public) == "radio") + #expect(MeshCoreLogRendering.render("radio", privacy: .private) == "") + #expect(MeshCoreLogRendering.render("radio", privacy: .sensitive) == "") + #expect(MeshCoreLogRendering.render("radio", privacy: .auto) == "") + #expect(MeshCoreLogRendering.render(7, privacy: .auto) == "7") + #expect(MeshCoreLogRendering.render(7, privacy: .private) == "") + #expect(MeshCoreLogRendering.render(true, privacy: .auto) == "true") + #expect(MeshCoreLogRendering.render(UInt(3), privacy: .auto) == "3") + #expect(MeshCoreLogRendering.render(1.5, privacy: .auto) == "1.5") + } +} diff --git a/MeshCore/Tests/MeshCoreTests/Protocol/V112ProtocolTests.swift b/MeshCore/Tests/MeshCoreTests/Protocol/V112ProtocolTests.swift index caf52799ab..01f12688db 100644 --- a/MeshCore/Tests/MeshCoreTests/Protocol/V112ProtocolTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Protocol/V112ProtocolTests.swift @@ -182,6 +182,29 @@ struct V112ProtocolTests { #expect(manager.needsRefresh) } + @Test + func `contactManager localized name search matches diacritics`() { + var manager = ContactManager() + let publicKey = Data(repeating: 0x22, count: 32) + let contact = MeshContact( + id: publicKey.hexString, + publicKey: publicKey, + type: .chat, + flags: [], + outPathLength: 0, + outPath: Data(), + advertisedName: "José", + lastAdvertisement: Date(), + latitude: 0, + longitude: 0, + lastModified: Date() + ) + manager.store(contact) + + #expect(manager.getByName("jose")?.advertisedName == "José") + #expect(manager.getByName("jose", exactMatch: true) == nil) + } + // MARK: - Auto-Add Config PacketBuilder Tests @Test diff --git a/MeshCore/Tests/MeshCoreTests/Session/CLIProvenanceScopeTests.swift b/MeshCore/Tests/MeshCoreTests/Session/CLIProvenanceScopeTests.swift index 2e409f01e0..ee3feb94f8 100644 --- a/MeshCore/Tests/MeshCoreTests/Session/CLIProvenanceScopeTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Session/CLIProvenanceScopeTests.swift @@ -1,8 +1,10 @@ import Foundation @testable import MeshCore import MeshCoreTestSupport -import Synchronization import Testing +#if canImport(Synchronization) + import Synchronization +#endif @Suite("CLI correlation scope lifetime", .timeLimit(.minutes(1))) @MainActor diff --git a/MeshCore/Tests/MeshCoreTests/Session/ConnectionStateTests.swift b/MeshCore/Tests/MeshCoreTests/Session/ConnectionStateTests.swift index 61223f6545..7bd708981f 100644 --- a/MeshCore/Tests/MeshCoreTests/Session/ConnectionStateTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Session/ConnectionStateTests.swift @@ -1,8 +1,10 @@ import Foundation @testable import MeshCore import MeshCoreTestSupport -import os import Testing +#if canImport(os) + import os +#endif @Suite("MeshCoreSession connection state", .timeLimit(.minutes(1))) struct ConnectionStateTests { diff --git a/MeshCore/Tests/MeshCoreTests/Session/VerifiedChannelSendTests.swift b/MeshCore/Tests/MeshCoreTests/Session/VerifiedChannelSendTests.swift new file mode 100644 index 0000000000..10e380cd06 --- /dev/null +++ b/MeshCore/Tests/MeshCoreTests/Session/VerifiedChannelSendTests.swift @@ -0,0 +1,221 @@ +import Foundation +@testable import MeshCore +import MeshCoreTestSupport +import Testing + +@Suite("Verified channel send", .timeLimit(.minutes(1))) +struct VerifiedChannelSendTests { + private static let timestamp = Date(timeIntervalSince1970: 1_700_000_000) + private static let channel: UInt8 = 1 + private static let channelName = "Ops" + private static let expectedSecret = Data(repeating: 0xAA, count: 16) + private static let otherSecret = Data(repeating: 0xBB, count: 16) + private static let namedScope = FloodScope.region("Alpha") + private static let commandTimeout: TimeInterval = 5 + + @Test + func `matching channel occupancy sends unscoped message`() async throws { + let harness = try await Harness.started() + defer { Task { await harness.session.stop() } } + + let send = harness.send(floodScope: nil) + try await harness.expectGetChannelAndReply( + channelInfoPacket(index: Self.channel, name: Self.channelName, secret: Self.expectedSecret) + ) + try await harness.ack(Self.channelMessage) + try await send.value + + let sent = await harness.transport.sentData + #expect(sent.contains(Self.channelMessage)) + #expect(sent.allSatisfy { $0.first != CommandCode.setFloodScope.rawValue }) + } + + @Test + func `matching channel occupancy sends scoped message and restores baseline`() async throws { + let harness = try await Harness.started() + defer { Task { await harness.session.stop() } } + + let send = harness.send(floodScope: .scope(Self.namedScope)) + try await harness.expectGetChannelAndReply( + channelInfoPacket(index: Self.channel, name: Self.channelName, secret: Self.expectedSecret) + ) + try await harness.ack(PacketBuilder.setFloodScope(Self.namedScope.scopeKey())) + try await harness.ack(Self.channelMessage) + try await harness.ack(Self.baselineReset) + try await send.value + + let scopeFrames = await harness.transport.sentData.filter { + $0.first == CommandCode.setFloodScope.rawValue + } + #expect(scopeFrames == [ + PacketBuilder.setFloodScope(Self.namedScope.scopeKey()), + Self.baselineReset + ]) + } + + @Test + func `wrong channel secret fails with occupancy mismatch without sending message`() async throws { + let harness = try await Harness.started() + defer { Task { await harness.session.stop() } } + + let send = harness.send(floodScope: nil) + try await harness.expectGetChannelAndReply( + channelInfoPacket(index: Self.channel, name: Self.channelName, secret: Self.otherSecret) + ) + + let error = await #expect(throws: MeshCoreError.self) { try await send.value } + guard case let .invalidResponse(expected, got) = error else { + Issue.record("Expected invalidResponse, got \(String(describing: error))") + return + } + #expect(expected == "unchanged channel occupancy") + #expect(got == "different or missing channel occupancy") + #expect(await harness.transport.sentData.allSatisfy { + $0.first != CommandCode.sendChannelMessage.rawValue + }) + } + + @Test + func `notFound on getChannel fails with occupancy mismatch without sending message`() async throws { + let harness = try await Harness.started() + defer { Task { await harness.session.stop() } } + + let send = harness.send(floodScope: nil) + try await harness.expectGetChannel() + await harness.transport.simulateError(code: ErrorCode.notFound.rawValue) + + let error = await #expect(throws: MeshCoreError.self) { try await send.value } + guard case let .invalidResponse(expected, got) = error else { + Issue.record("Expected invalidResponse, got \(String(describing: error))") + return + } + #expect(expected == "unchanged channel occupancy") + #expect(got == "different or missing channel occupancy") + #expect(await harness.transport.sentData.allSatisfy { + $0.first != CommandCode.sendChannelMessage.rawValue + }) + } + + @Test + func `cancellation before send stops before writing channel message`() async throws { + let harness = try await Harness.started() + defer { Task { await harness.session.stop() } } + + await harness.transport.holdNextSend() + let blocker = Task { + try await harness.session.sendLogin(to: Data(repeating: 0x11, count: 32), password: "room") + } + try await waitUntil("blocker login send should park in transport") { + await harness.transport.sendIsWaiting + } + + let send = harness.send(floodScope: nil) + try await waitUntil("verified send should queue behind blocker") { + await harness.session.requestResponseSerializer.waiterCountForTest == 1 + } + send.cancel() + + await harness.transport.releaseHeldSend() + try await waitUntil("login command subscriber should register") { + await harness.session.subscriberCountForTest >= 1 + } + await harness.transport.simulateReceive(Self.messageSent) + _ = try await blocker.value + + await #expect(throws: CancellationError.self) { try await send.value } + #expect(await harness.transport.sentData.allSatisfy { + $0.first != CommandCode.getChannel.rawValue + && $0.first != CommandCode.sendChannelMessage.rawValue + }) + } + + private static var channelMessage: Data { + PacketBuilder.sendChannelMessage(channel: channel, text: "hello", timestamp: timestamp) + } + + private static var baselineReset: Data { + PacketBuilder.setFloodScope(FloodScope.disabled.scopeKey()) + } + + private static var messageSent: Data { + Data([ResponseCode.messageSent.rawValue, 1, 2, 3, 4, 5, 50, 0, 0, 0]) + } + + private func channelInfoPacket(index: UInt8, name: String, secret: Data) -> Data { + var packet = Data([ResponseCode.channelInfo.rawValue, index]) + var nameBytes = Array(name.utf8.prefix(32)) + while nameBytes.count < 32 { + nameBytes.append(0) + } + packet.append(contentsOf: nameBytes) + packet.append(secret) + return packet + } + + private struct Harness { + let session: MeshCoreSession + let transport: MockTransport + + static func started() async throws -> Harness { + let transport = MockTransport() + let session = MeshCoreSession( + transport: transport, + configuration: SessionConfiguration(defaultTimeout: commandTimeout, clientIdentifier: "MCTst") + ) + let harness = Harness(session: session, transport: transport) + let start = Task { try await session.start() } + try await waitUntil("appStart frame should send") { await transport.sentData.count >= 1 } + await transport.simulateReceive(selfInfoPacket) + try await start.value + return harness + } + + func send(floodScope: ResolvedFloodScope?) -> Task { + Task { + try await session.sendVerifiedChannelMessage( + channel: VerifiedChannelSendTests.channel, + text: "hello", + timestamp: VerifiedChannelSendTests.timestamp, + floodScope: floodScope, + expectedSecret: VerifiedChannelSendTests.expectedSecret + ) + } + } + + func expectGetChannel() async throws { + let expected = PacketBuilder.getChannel(index: VerifiedChannelSendTests.channel) + try await waitUntil("getChannel frame should send") { + await transport.sentData.last == expected + } + try await waitUntil("event subscriber should register") { + await session.subscriberCountForTest >= 1 + } + } + + func expectGetChannelAndReply(_ packet: Data) async throws { + try await expectGetChannel() + await transport.simulateReceive(packet) + } + + func ack(_ expected: Data) async throws { + try await waitUntil("Expected frame should send") { + await transport.sentData.last == expected + } + try await waitUntil("event subscriber should register") { + await session.subscriberCountForTest >= 1 + } + await transport.simulateOK() + } + } +} + +private let selfInfoPacket: Data = { + var packet = Data([ResponseCode.selfInfo.rawValue, 1, 22, 22]) + packet.append(Data(repeating: 1, count: 32)) + packet.append(Data(repeating: 0, count: 12)) + packet.append(contentsOf: withUnsafeBytes(of: UInt32(915_000).littleEndian) { Array($0) }) + packet.append(contentsOf: withUnsafeBytes(of: UInt32(125_000).littleEndian) { Array($0) }) + packet.append(contentsOf: [7, 5]) + packet.append(contentsOf: "Test".utf8) + return packet +}() diff --git a/MeshCore/Tests/MeshCoreTests/Transport/WiFiTransportTests.swift b/MeshCore/Tests/MeshCoreTests/Transport/WiFiTransportTests.swift index 3e9a908e93..7ca93b1e03 100644 --- a/MeshCore/Tests/MeshCoreTests/Transport/WiFiTransportTests.swift +++ b/MeshCore/Tests/MeshCoreTests/Transport/WiFiTransportTests.swift @@ -1,194 +1,180 @@ -import Foundation -@testable import MeshCore -import MeshCoreTestSupport -import Network -import os -import Testing - -@Suite("WiFiTransport Tests") -struct WiFiTransportTests { - @Test - func `Initial state is disconnected`() async { - let transport = WiFiTransport() - let isConnected = await transport.isConnected - #expect(!isConnected) - } - - @Test - func `Advertises pipelined reads without a Write-Without-Response characteristic`() async { - let transport = WiFiTransport() - let pipelined = await transport.supportsPipelinedReads - let writeWithoutResponse = await transport.supportsWriteWithoutResponse - #expect(pipelined) - #expect(!writeWithoutResponse) - } - - @Test - func `Connect without configuration throws notConfigured`() async { - let transport = WiFiTransport() +#if canImport(Network) + import Foundation + @testable import MeshCore + import MeshCoreTestSupport + import Network + import os + import Testing + + @Suite("WiFiTransport Tests") + struct WiFiTransportTests { + @Test + func `Initial state is disconnected`() async { + let transport = WiFiTransport() + let isConnected = await transport.isConnected + #expect(!isConnected) + } - await #expect(throws: WiFiTransportError.notConfigured) { - try await transport.connect() + @Test + func `Advertises pipelined reads without a Write-Without-Response characteristic`() async { + let transport = WiFiTransport() + let pipelined = await transport.supportsPipelinedReads + let writeWithoutResponse = await transport.supportsWriteWithoutResponse + #expect(pipelined) + #expect(!writeWithoutResponse) } - } - @Test - func `Connection to invalid host fails`() async { - let transport = WiFiTransport() - await transport.setConnectionInfo(host: "999.999.999.999", port: 5000) + @Test + func `Connect without configuration throws notConfigured`() async { + let transport = WiFiTransport() - await #expect(throws: WiFiTransportError.self) { - try await transport.connect() + await #expect(throws: WiFiTransportError.notConfigured) { + try await transport.connect() + } } - } - @Test - func `Send without connection throws notConnected`() async { - let transport = WiFiTransport() + @Test + func `Connection to invalid host fails`() async { + let transport = WiFiTransport() + await transport.setConnectionInfo(host: "999.999.999.999", port: 5000) - await #expect(throws: WiFiTransportError.notConnected) { - try await transport.send(Data([0x01, 0x02, 0x03])) + await #expect(throws: WiFiTransportError.self) { + try await transport.connect() + } } - } - @Test - func `Disconnect when not connected is safe`() async { - let transport = WiFiTransport() - await transport.disconnect() - // Should not throw or crash - let isConnected = await transport.isConnected - #expect(!isConnected) - } + @Test + func `Send without connection throws notConnected`() async { + let transport = WiFiTransport() - @Test - func `connectionInfo returns configured host and port`() async { - let transport = WiFiTransport() + await #expect(throws: WiFiTransportError.notConnected) { + try await transport.send(Data([0x01, 0x02, 0x03])) + } + } - // Initially nil - let initialInfo = await transport.connectionInfo - #expect(initialInfo == nil) + @Test + func `Disconnect when not connected is safe`() async { + let transport = WiFiTransport() + await transport.disconnect() + // Should not throw or crash + let isConnected = await transport.isConnected + #expect(!isConnected) + } - // After configuration - await transport.setConnectionInfo(host: "192.168.1.50", port: 5000) - let info = await transport.connectionInfo - #expect(info?.host == "192.168.1.50") - #expect(info?.port == 5000) - } + @Test + func `connectionInfo returns configured host and port`() async { + let transport = WiFiTransport() - @Test - func `Disconnection handler not called on user-initiated disconnect`() async { - let transport = WiFiTransport() - let callTracker = CallTracker() + // Initially nil + let initialInfo = await transport.connectionInfo + #expect(initialInfo == nil) - await transport.setDisconnectionHandler { _, _ in - callTracker.markCalled() + // After configuration + await transport.setConnectionInfo(host: "192.168.1.50", port: 5000) + let info = await transport.connectionInfo + #expect(info?.host == "192.168.1.50") + #expect(info?.port == 5000) } - // User-initiated disconnect should NOT trigger handler - await transport.disconnect() + @Test + func `Disconnection handler not called on user-initiated disconnect`() async { + let transport = WiFiTransport() + let callTracker = CallTracker() - // Give any async callbacks time to fire - try? await Task.sleep(for: .milliseconds(100)) + await transport.setDisconnectionHandler { _, _ in + callTracker.markCalled() + } - #expect(!callTracker.wasCalled, "Handler should not be called on user disconnect") - } + // User-initiated disconnect should NOT trigger handler + await transport.disconnect() - @Test - func `Disconnection handler not called on initial connect failure`() async { - let transport = WiFiTransport() - let callTracker = CallTracker() + // Give any async callbacks time to fire + try? await Task.sleep(for: .milliseconds(100)) - await transport.setDisconnectionHandler { _, _ in - callTracker.markCalled() + #expect(!callTracker.wasCalled, "Handler should not be called on user disconnect") } - // Configure to invalid host - await transport.setConnectionInfo(host: "999.999.999.999", port: 5000) + @Test + func `Disconnection handler not called on initial connect failure`() async { + let transport = WiFiTransport() + let callTracker = CallTracker() - // Initial connect failure should NOT trigger disconnection handler - do { - try await transport.connect() - } catch { - // Expected to fail - } + await transport.setDisconnectionHandler { _, _ in + callTracker.markCalled() + } - try? await Task.sleep(for: .milliseconds(100)) + // Configure to invalid host + await transport.setConnectionInfo(host: "999.999.999.999", port: 5000) - #expect(!callTracker.wasCalled, "Handler should not be called on initial connect failure") - } + // Initial connect failure should NOT trigger disconnection handler + do { + try await transport.connect() + } catch { + // Expected to fail + } - @Test - func `connect() is idempotent — second call does not create new TCP connection`() async throws { - let listener = try NWListener(using: .tcp) - let acceptCount = OSAllocatedUnfairLock(initialState: 0) - let acceptedConnections = OSAllocatedUnfairLock<[NWConnection]>(initialState: []) + try? await Task.sleep(for: .milliseconds(100)) - listener.newConnectionHandler = { conn in - acceptCount.withLock { $0 += 1 } - acceptedConnections.withLock { $0.append(conn) } - conn.start(queue: .global()) + #expect(!callTracker.wasCalled, "Handler should not be called on initial connect failure") } - let listenerReady = AsyncStream.makeStream() - listener.stateUpdateHandler = { state in - listenerReady.continuation.yield(state) - } - listener.start(queue: .global(qos: .userInitiated)) + @Test + func `connect() is idempotent — second call does not create new TCP connection`() async throws { + let listener = try NWListener(using: .tcp) + let acceptCount = OSAllocatedUnfairLock(initialState: 0) + let acceptedConnections = OSAllocatedUnfairLock<[NWConnection]>(initialState: []) - for await state in listenerReady.stream { - if state == .ready { break } - if case .failed = state { Issue.record("Listener failed to start"); return } - } - listenerReady.continuation.finish() + listener.newConnectionHandler = { conn in + acceptCount.withLock { $0 += 1 } + acceptedConnections.withLock { $0.append(conn) } + conn.start(queue: .global()) + } - guard let port = listener.port?.rawValue else { - Issue.record("Listener has no port") - return - } + let listenerReady = AsyncStream.makeStream() + listener.stateUpdateHandler = { state in + listenerReady.continuation.yield(state) + } + listener.start(queue: .global(qos: .userInitiated)) - let transport = WiFiTransport() - await transport.setConnectionInfo(host: "127.0.0.1", port: port) + for await state in listenerReady.stream { + if state == .ready { break } + if case .failed = state { Issue.record("Listener failed to start"); return } + } + listenerReady.continuation.finish() - // First connect — should establish TCP connection - try await transport.connect() - let connected = await transport.isConnected - #expect(connected, "Transport should be connected after first connect()") + guard let port = listener.port?.rawValue else { + Issue.record("Listener has no port") + return + } - // Wait for the accept to register - try await waitUntil(timeout: .seconds(2), "First connection should be accepted") { - acceptCount.withLock { $0 } >= 1 - } + let transport = WiFiTransport() + await transport.setConnectionInfo(host: "127.0.0.1", port: port) - // Second connect — should be a no-op - try await transport.connect() - let stillConnected = await transport.isConnected - #expect(stillConnected, "Transport should still be connected after second connect()") + // First connect — should establish TCP connection + try await transport.connect() + let connected = await transport.isConnected + #expect(connected, "Transport should be connected after first connect()") + + // Wait for the accept to register + try await waitUntil(timeout: .seconds(2), "First connection should be accepted") { + acceptCount.withLock { $0 } >= 1 + } - // Give time for any spurious second accept to arrive. - // A fixed sleep is correct here: we're waiting for something that should NOT - // happen, so there's no condition to poll for. - try await Task.sleep(for: .milliseconds(500)) + // Second connect — should be a no-op + try await transport.connect() + let stillConnected = await transport.isConnected + #expect(stillConnected, "Transport should still be connected after second connect()") - let finalCount = acceptCount.withLock { $0 } - #expect(finalCount == 1, "Expected 1 TCP accept, got \(finalCount) — second connect() should be a no-op") + // Give time for any spurious second accept to arrive. + // A fixed sleep is correct here: we're waiting for something that should NOT + // happen, so there's no condition to poll for. + try await Task.sleep(for: .milliseconds(500)) - // Cleanup - await transport.disconnect() - acceptedConnections.withLock { conns in - for conn in conns { - conn.cancel() - } - } - listener.cancel() - } + let finalCount = acceptCount.withLock { $0 } + #expect(finalCount == 1, "Expected 1 TCP accept, got \(finalCount) — second connect() should be a no-op") - @Test(arguments: [false, true]) - func `Peer close finishes the stream and fires the disconnection handler`(reset: Bool) async throws { - let acceptedConnections = OSAllocatedUnfairLock<[NWConnection]>(initialState: []) - let listener = try await startLocalListener { conn in - acceptedConnections.withLock { $0.append(conn) } - } - defer { + // Cleanup + await transport.disconnect() acceptedConnections.withLock { conns in for conn in conns { conn.cancel() @@ -197,102 +183,118 @@ struct WiFiTransportTests { listener.cancel() } - guard let port = listener.port?.rawValue else { - Issue.record("Listener has no port") - return - } + @Test(arguments: [false, true]) + func `Peer close finishes the stream and fires the disconnection handler`(reset: Bool) async throws { + let acceptedConnections = OSAllocatedUnfairLock<[NWConnection]>(initialState: []) + let listener = try await startLocalListener { conn in + acceptedConnections.withLock { $0.append(conn) } + } + defer { + acceptedConnections.withLock { conns in + for conn in conns { + conn.cancel() + } + } + listener.cancel() + } - let transport = WiFiTransport() - let disconnectionTracker = CallTracker() - await transport.setDisconnectionHandler { _, _ in - disconnectionTracker.markCalled() - } - await transport.setConnectionInfo(host: "127.0.0.1", port: port) - try await transport.connect() + guard let port = listener.port?.rawValue else { + Issue.record("Listener has no port") + return + } - let streamEnded = CallTracker() - let consumeTask = Task { - for await _ in await transport.receivedData {} - streamEnded.markCalled() - } - defer { consumeTask.cancel() } + let transport = WiFiTransport() + let disconnectionTracker = CallTracker() + await transport.setDisconnectionHandler { _, _ in + disconnectionTracker.markCalled() + } + await transport.setConnectionInfo(host: "127.0.0.1", port: port) + try await transport.connect() - try await waitUntil(timeout: .seconds(2), "Server should accept the connection") { - acceptedConnections.withLock { !$0.isEmpty } - } + let streamEnded = CallTracker() + let consumeTask = Task { + for await _ in await transport.receivedData {} + streamEnded.markCalled() + } + defer { consumeTask.cancel() } - let serverSide = acceptedConnections.withLock { $0.first } - if reset { - serverSide?.forceCancel() - } else { - serverSide?.send( - content: nil, - contentContext: .finalMessage, - isComplete: true, - completion: .contentProcessed { _ in } - ) - } + try await waitUntil(timeout: .seconds(2), "Server should accept the connection") { + acceptedConnections.withLock { !$0.isEmpty } + } - try await waitUntil(timeout: .seconds(2), "Peer close should fire the disconnection handler") { - disconnectionTracker.wasCalled - } - try await waitUntil(timeout: .seconds(2), "Peer close should finish the receivedData stream") { - streamEnded.wasCalled - } - #expect(await transport.isConnected == false, "Peer close should mark the transport disconnected") - #expect(disconnectionTracker.callCount == 1) + let serverSide = acceptedConnections.withLock { $0.first } + if reset { + serverSide?.forceCancel() + } else { + serverSide?.send( + content: nil, + contentContext: .finalMessage, + isComplete: true, + completion: .contentProcessed { _ in } + ) + } - await transport.disconnect() - } + try await waitUntil(timeout: .seconds(2), "Peer close should fire the disconnection handler") { + disconnectionTracker.wasCalled + } + try await waitUntil(timeout: .seconds(2), "Peer close should finish the receivedData stream") { + streamEnded.wasCalled + } + #expect(await transport.isConnected == false, "Peer close should mark the transport disconnected") + #expect(disconnectionTracker.callCount == 1) - @Test - func `Cancelling connect() does not leave it parked`() async throws { - let transport = WiFiTransport() - // TEST-NET-1 (RFC 5737) is unrouted: the SYN is dropped, so without - // cancellation support connect() would park until the system TCP timeout. - await transport.setConnectionInfo(host: "192.0.2.1", port: 9) - - let connectTask = Task { try await transport.connect() } - try? await Task.sleep(for: .milliseconds(200)) - connectTask.cancel() - - let completed = CallTracker() - Task { - _ = await connectTask.result - completed.markCalled() - } - try await waitUntil(timeout: .seconds(3), "connect() should return promptly after cancellation") { - completed.wasCalled + await transport.disconnect() } - await #expect(throws: (any Error).self) { try await connectTask.value } - #expect(await transport.isConnected == false) - } -} - -/// Starts an `NWListener` on an ephemeral localhost port and waits until it is ready. -private func startLocalListener( - onAccept: @escaping @Sendable (NWConnection) -> Void -) async throws -> NWListener { - let listener = try NWListener(using: .tcp) - listener.newConnectionHandler = { conn in - onAccept(conn) - conn.start(queue: .global()) - } + @Test + func `Cancelling connect() does not leave it parked`() async throws { + let transport = WiFiTransport() + // TEST-NET-1 (RFC 5737) is unrouted: the SYN is dropped, so without + // cancellation support connect() would park until the system TCP timeout. + await transport.setConnectionInfo(host: "192.0.2.1", port: 9) + + let connectTask = Task { try await transport.connect() } + try? await Task.sleep(for: .milliseconds(200)) + connectTask.cancel() + + let completed = CallTracker() + Task { + _ = await connectTask.result + completed.markCalled() + } + try await waitUntil(timeout: .seconds(3), "connect() should return promptly after cancellation") { + completed.wasCalled + } - let listenerReady = AsyncStream.makeStream() - listener.stateUpdateHandler = { state in - listenerReady.continuation.yield(state) + await #expect(throws: (any Error).self) { try await connectTask.value } + #expect(await transport.isConnected == false) + } } - listener.start(queue: .global(qos: .userInitiated)) - for await state in listenerReady.stream { - if state == .ready { break } - if case let .failed(error) = state { - listenerReady.continuation.finish() - throw error + /// Starts an `NWListener` on an ephemeral localhost port and waits until it is ready. + private func startLocalListener( + onAccept: @escaping @Sendable (NWConnection) -> Void + ) async throws -> NWListener { + let listener = try NWListener(using: .tcp) + listener.newConnectionHandler = { conn in + onAccept(conn) + conn.start(queue: .global()) } + + let listenerReady = AsyncStream.makeStream() + listener.stateUpdateHandler = { state in + listenerReady.continuation.yield(state) + } + listener.start(queue: .global(qos: .userInitiated)) + + for await state in listenerReady.stream { + if state == .ready { break } + if case let .failed(error) = state { + listenerReady.continuation.finish() + throw error + } + } + listenerReady.continuation.finish() + return listener } - listenerReady.continuation.finish() - return listener -} +#endif diff --git a/MeshCore/Tests/MeshCoreTests/TransportCodeRegionResolverTests.swift b/MeshCore/Tests/MeshCoreTests/TransportCodeRegionResolverTests.swift index 404e682f45..904d4c22cb 100644 --- a/MeshCore/Tests/MeshCoreTests/TransportCodeRegionResolverTests.swift +++ b/MeshCore/Tests/MeshCoreTests/TransportCodeRegionResolverTests.swift @@ -228,6 +228,27 @@ struct TransportCodeRegionResolverTests { #expect(forwardMatch == reverseMatch) } + @Test + func `Ambiguous names sort with localized standard compare`() throws { + let scopeKey = try #require(TransportCodeRegionResolver.deriveScopeKey(regionName: "Germany")) + let expectedCode = TransportCodeRegionResolver.calcTransportCode( + scopeKey: scopeKey, + payloadTypeBits: groupTextPayloadBits, + payload: samplePayload + ) + let names = ["Beta", "alpha"] + let match = TransportCodeRegionResolver.matchRegions( + scopeKeys: names.map { ($0, scopeKey) }, + expectedTransportCode0: expectedCode, + payloadTypeBits: groupTextPayloadBits, + payload: samplePayload + ) + let localized = names.sorted { $0.localizedStandardCompare($1) == .orderedAscending } + + #expect(localized != names.sorted()) + #expect(match == .ambiguous(localized)) + } + @Test func `Dollar-prefixed private regions never match via empty scope key`() { // deriveScopeKey returns nil for $ names, so callers never put them in the