Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .github/workflows/meshcore-portability.yml
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,6 @@ __pycache__
.idea/
# Brainstorming visual companion mockups
.superpowers/

# Local
radio-dev.env
2 changes: 1 addition & 1 deletion .swiftformat
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ excluded:
- MC1.xcodeproj
- MC1/Resources/Generated
- MeshCore/.build
- MeshCoreBridge/.build
- mc-ref
- MC1Services/.build
- fastlane
Expand Down
5 changes: 4 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
20 changes: 18 additions & 2 deletions MeshCore/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
25 changes: 25 additions & 0 deletions MeshCore/Sources/MeshCore/Compat/OSAllocatedUnfairLock.swift
Original file line number Diff line number Diff line change
@@ -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<State>: @unchecked Sendable {
private let lock = NSLock()
private var state: State

init(initialState: State) {
state = initialState
}

func withLock<R>(_ body: (inout State) throws -> R) rethrows -> R {
lock.lock()
defer { lock.unlock() }
return try body(&state)
}

func withLock<Member>(_ keyPath: KeyPath<State, Member>) -> Member {
withLock { $0[keyPath: keyPath] }
}
}
#endif
181 changes: 181 additions & 0 deletions MeshCore/Sources/MeshCore/Compat/OSLogCompat.swift
Original file line number Diff line number Diff line change
@@ -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>"

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
4 changes: 3 additions & 1 deletion MeshCore/Sources/MeshCore/Events/EventDispatcher.swift
Original file line number Diff line number Diff line change
@@ -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")
Expand Down
6 changes: 5 additions & 1 deletion MeshCore/Sources/MeshCore/Models/Destination.swift
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
49 changes: 49 additions & 0 deletions MeshCore/Sources/MeshCore/Protocol/AES128ECBFallback.swift
Original file line number Diff line number Diff line change
@@ -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..<blockEnd],
using: symmetricKey,
iv: zeroIV,
noPadding: true
) else {
return nil
}
plaintext.append(block)
index = blockEnd
}

return plaintext
}
}
#endif
Loading