Phase 6: Lüftersteuerung über privilegierten Helfer
Das Sicherheitsnetz kommt zuerst und liegt als reine Funktion vor — 17 Tests, kein Hardwarezugriff nötig. Es sitzt im Helfer, nicht in der Oberfläche: die kann abstürzen, hängen oder beendet sein, während die Lüfter auf einem festen Wert stehen. Genau dafür ist es da. Vier Regeln, nicht abschaltbar: nie unter das Firmware-Minimum, Rückfall auf Automatik ab 95 °C, Rückfall wenn der Herzschlag fünf Sekunden ausbleibt, Rückfall beim Beenden. Ohne lesbare Temperatur wird gar nicht gesteuert — blind eine feste Drehzahl zu halten wäre die falsche Antwort auf fehlende Information. Die App sagt dem Helfer NICHT, wie warm es ist. Er misst selbst. Sonst hinge das Netz an der Ehrlichkeit eines Prozesses, der abstürzen, hängen oder — bei einer manipulierten Kopie — schlicht lügen kann. Der Herzschlag sagt nur "ich lebe noch". Der Helfer entscheidet jede Sekunde neu, nicht nur beim Setzen: nur so greifen Wachhund und Temperaturwächter auch dann, wenn von der App nie wieder etwas kommt. Geschrieben wird nur bei Änderung — jeder SMC-Schreibvorgang ist ein Eingriff. Der Schreibpfad existiert ausschließlich im Helfer, als eigene Kopie statt geteilter Bibliothek. Was im App-Prozess nicht vorhanden ist, kann dort auch nicht versehentlich aufgerufen werden. XPC prüft die Signatur in BEIDE Richtungen. Ohne das könnte jedes Programm auf dem Rechner die Lüfter eines root-Dienstes steuern — der Mach-Dienst ist systemweit sichtbar. Drei Fallstricke beim Einbetten, alle nachgemessen: Xcode signiert Kommandozeilenprogramme unter dem Dateinamen. Der Helfer hieß damit "OnyxHelper" statt com.scarriffleservices.onyx.helper, und die App hätte ihren eigenen Helfer abgelehnt. Behoben über eine in die Binary eingebettete Info.plist (CREATE_INFOPLIST_SECTION_IN_BINARY). Der Build-Schritt läuft nach Xcodes Signatur; das Kopieren bricht das Siegel des App-Bundles. Also wird zum Schluss neu signiert — mit denselben Entitlements, sonst gingen App-Group, WeatherKit und die TCC-Berechtigungen verloren. Mit deklarierten outputFiles übersprang Xcode den Schritt, obwohl sich das Programm geändert hatte. Geprüft: App-Siegel gültig (deep), beide Signaturanforderungen erfüllt, alle sieben Entitlements erhalten. 162 Tests grün.
This commit is contained in:
18
OnyxHelper/Info.plist
Normal file
18
OnyxHelper/Info.plist
Normal file
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!-- Wird als __TEXT,__info_plist in die Binary eingebettet.
|
||||
Ohne sie leitet codesign den Bezeichner aus dem Dateinamen ab
|
||||
("OnyxHelper"), und die Signaturprüfung zwischen App und Helfer
|
||||
schlägt fehl — die App würde ihren eigenen Helfer ablehnen. -->
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>com.scarriffleservices.onyx.helper</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>OnyxHelper</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
</dict>
|
||||
</plist>
|
||||
170
OnyxHelper/SMCAccess.swift
Normal file
170
OnyxHelper/SMCAccess.swift
Normal file
@@ -0,0 +1,170 @@
|
||||
import Foundation
|
||||
import IOKit
|
||||
|
||||
/// SMC-Zugriff **mit** Schreibpfad — nur im privilegierten Helfer.
|
||||
///
|
||||
/// Bewusst eine eigene Kopie und keine geteilte Bibliothek mit der App: der
|
||||
/// Schreibpfad soll gar nicht erst in einem Prozess vorhanden sein, der ohne
|
||||
/// Sonderrechte läuft und in dem jedes Widget Code ausführt. Was nicht da ist,
|
||||
/// kann auch nicht versehentlich aufgerufen werden.
|
||||
///
|
||||
/// Byte-Reihenfolge und Struktur stammen aus `docs/spikes/A-smc.md`.
|
||||
final class SMCAccess {
|
||||
|
||||
private struct Version { var major: UInt8 = 0; var minor: UInt8 = 0
|
||||
var build: UInt8 = 0; var reserved: UInt8 = 0
|
||||
var release: UInt16 = 0 }
|
||||
private struct PLimitData { var version: UInt16 = 0; var length: UInt16 = 0
|
||||
var cpuPLimit: UInt32 = 0; var gpuPLimit: UInt32 = 0
|
||||
var memPLimit: UInt32 = 0 }
|
||||
private struct KeyInfo { var dataSize: UInt32 = 0; var dataType: UInt32 = 0
|
||||
var dataAttributes: UInt8 = 0 }
|
||||
|
||||
private struct Param {
|
||||
var key: UInt32 = 0
|
||||
var vers = Version()
|
||||
var pLimitData = PLimitData()
|
||||
var keyInfo = KeyInfo()
|
||||
var padding: UInt16 = 0
|
||||
var result: UInt8 = 0
|
||||
var status: UInt8 = 0
|
||||
var data8: UInt8 = 0
|
||||
var data32: UInt32 = 0
|
||||
var bytes: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
|
||||
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
|
||||
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
|
||||
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) =
|
||||
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
|
||||
}
|
||||
|
||||
private static let handleYPCEvent: UInt32 = 2
|
||||
private static let readKey: UInt8 = 5
|
||||
private static let writeKey: UInt8 = 6
|
||||
private static let getKeyFromIndex: UInt8 = 8
|
||||
private static let getKeyInfo: UInt8 = 9
|
||||
|
||||
private var connection: io_connect_t = 0
|
||||
private var keyInfoCache: [String: KeyInfo] = [:]
|
||||
|
||||
init?() {
|
||||
let service = IOServiceGetMatchingService(kIOMainPortDefault,
|
||||
IOServiceMatching("AppleSMC"))
|
||||
guard service != 0 else { return nil }
|
||||
defer { IOObjectRelease(service) }
|
||||
guard IOServiceOpen(service, mach_task_self_, 0, &connection) == kIOReturnSuccess
|
||||
else { return nil }
|
||||
}
|
||||
|
||||
deinit { if connection != 0 { IOServiceClose(connection) } }
|
||||
|
||||
// MARK: - Lesen
|
||||
|
||||
func float(_ key: String) -> Double? {
|
||||
guard let value = read(key), value.bytes.count >= 4 else { return nil }
|
||||
let bits = UInt32(value.bytes[3]) << 24 | UInt32(value.bytes[2]) << 16
|
||||
| UInt32(value.bytes[1]) << 8 | UInt32(value.bytes[0])
|
||||
return Double(Float(bitPattern: bits))
|
||||
}
|
||||
|
||||
func uint8(_ key: String) -> UInt8? { read(key)?.bytes.first }
|
||||
|
||||
func keys(withPrefix prefix: String) -> [String] {
|
||||
guard let value = read("#KEY"), value.bytes.count >= 4 else { return [] }
|
||||
// Big-endian, anders als die Messwerte — siehe Spike A.
|
||||
let total = UInt32(value.bytes[0]) << 24 | UInt32(value.bytes[1]) << 16
|
||||
| UInt32(value.bytes[2]) << 8 | UInt32(value.bytes[3])
|
||||
guard total > 0, total < 100_000 else { return [] }
|
||||
|
||||
var found: [String] = []
|
||||
for index in 0..<total {
|
||||
var command = Param()
|
||||
command.data8 = Self.getKeyFromIndex
|
||||
command.data32 = index
|
||||
guard let output = call(command) else { continue }
|
||||
let name = Self.fourCCString(output.key)
|
||||
if name.hasPrefix(prefix) { found.append(name) }
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
// MARK: - Schreiben
|
||||
|
||||
/// Schreibt einen `flt`-Wert (Zieldrehzahl).
|
||||
@discardableResult
|
||||
func writeFloat(_ key: String, _ value: Double) -> Bool {
|
||||
let bits = Float(value).bitPattern
|
||||
return write(key, bytes: [UInt8(bits & 0xFF), UInt8((bits >> 8) & 0xFF),
|
||||
UInt8((bits >> 16) & 0xFF), UInt8((bits >> 24) & 0xFF)])
|
||||
}
|
||||
|
||||
/// Schreibt ein einzelnes Byte (Betriebsart).
|
||||
@discardableResult
|
||||
func writeUInt8(_ key: String, _ value: UInt8) -> Bool {
|
||||
write(key, bytes: [value])
|
||||
}
|
||||
|
||||
private func write(_ key: String, bytes: [UInt8]) -> Bool {
|
||||
guard let info = keyInfo(for: key) else { return false }
|
||||
// Nur schreiben, wenn die Größe zur Firmware passt. Ein zu kurzer oder
|
||||
// zu langer Schreibvorgang landet sonst in benachbarten Feldern.
|
||||
guard Int(info.dataSize) == bytes.count else { return false }
|
||||
|
||||
var command = Param()
|
||||
command.key = Self.fourCC(key)
|
||||
command.keyInfo = info
|
||||
command.data8 = Self.writeKey
|
||||
withUnsafeMutableBytes(of: &command.bytes) { raw in
|
||||
for (index, byte) in bytes.enumerated() { raw[index] = byte }
|
||||
}
|
||||
return call(command) != nil
|
||||
}
|
||||
|
||||
// MARK: - Innereien
|
||||
|
||||
private struct Value { let bytes: [UInt8] }
|
||||
|
||||
private func keyInfo(for key: String) -> KeyInfo? {
|
||||
if let cached = keyInfoCache[key] { return cached }
|
||||
var command = Param()
|
||||
command.key = Self.fourCC(key)
|
||||
command.data8 = Self.getKeyInfo
|
||||
guard let output = call(command) else { return nil }
|
||||
keyInfoCache[key] = output.keyInfo
|
||||
return output.keyInfo
|
||||
}
|
||||
|
||||
private func read(_ key: String) -> Value? {
|
||||
guard let info = keyInfo(for: key) else { return nil }
|
||||
var command = Param()
|
||||
command.key = Self.fourCC(key)
|
||||
command.keyInfo = info
|
||||
command.data8 = Self.readKey
|
||||
guard let output = call(command) else { return nil }
|
||||
let all = withUnsafeBytes(of: output.bytes) { Array($0) }
|
||||
return Value(bytes: Array(all.prefix(Int(min(info.dataSize, 32)))))
|
||||
}
|
||||
|
||||
private func call(_ input: Param) -> Param? {
|
||||
var input = input
|
||||
var output = Param()
|
||||
var size = MemoryLayout<Param>.stride
|
||||
let result = IOConnectCallStructMethod(connection, Self.handleYPCEvent,
|
||||
&input, MemoryLayout<Param>.stride,
|
||||
&output, &size)
|
||||
guard result == kIOReturnSuccess, output.result == 0 else { return nil }
|
||||
return output
|
||||
}
|
||||
|
||||
private static func fourCC(_ string: String) -> UInt32 {
|
||||
var value: UInt32 = 0
|
||||
for character in string.utf8.prefix(4) { value = value << 8 | UInt32(character) }
|
||||
return value
|
||||
}
|
||||
|
||||
private static func fourCCString(_ value: UInt32) -> String {
|
||||
let bytes = [UInt8((value >> 24) & 0xFF), UInt8((value >> 16) & 0xFF),
|
||||
UInt8((value >> 8) & 0xFF), UInt8(value & 0xFF)]
|
||||
return String(bytes: bytes, encoding: .ascii) ?? "????"
|
||||
}
|
||||
}
|
||||
31
OnyxHelper/com.scarriffleservices.onyx.helper.plist
Normal file
31
OnyxHelper/com.scarriffleservices.onyx.helper.plist
Normal file
@@ -0,0 +1,31 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>com.scarriffleservices.onyx.helper</string>
|
||||
|
||||
<!-- Relativ zum App-Bundle. SMAppService löst den Pfad selbst auf; ein
|
||||
absoluter Pfad würde brechen, sobald die App verschoben wird. -->
|
||||
<key>BundleProgram</key>
|
||||
<string>Contents/MacOS/OnyxHelper</string>
|
||||
|
||||
<key>MachServices</key>
|
||||
<dict>
|
||||
<key>com.scarriffleservices.onyx.helper</key>
|
||||
<true/>
|
||||
</dict>
|
||||
|
||||
<!-- Auf Abruf starten, nicht dauerhaft laufen: der Helfer wird erst
|
||||
gebraucht, wenn jemand die Lüfter steuern will. -->
|
||||
<key>KeepAlive</key>
|
||||
<false/>
|
||||
<key>RunAtLoad</key>
|
||||
<false/>
|
||||
|
||||
<key>AssociatedBundleIdentifiers</key>
|
||||
<array>
|
||||
<string>com.scarriffleservices.onyx</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
198
OnyxHelper/main.swift
Normal file
198
OnyxHelper/main.swift
Normal file
@@ -0,0 +1,198 @@
|
||||
import Foundation
|
||||
import OSLog
|
||||
import OnyxHelperProtocol
|
||||
|
||||
private let log = Logger(subsystem: "com.scarriffleservices.onyx.helper", category: "Helper")
|
||||
|
||||
/// Der privilegierte Helfer.
|
||||
///
|
||||
/// Läuft als root und tut genau eine Sache: Lüfterdrehzahlen setzen. Kein
|
||||
/// Netzwerk, keine Oberfläche, kein Dateizugriff. Je weniger hier steht, desto
|
||||
/// kleiner die Angriffsfläche eines Dienstes mit Systemrechten.
|
||||
///
|
||||
/// **Er entscheidet selbst, was zulässig ist.** Die App darf einen Wunsch
|
||||
/// äußern; ob er ausgeführt wird, prüft ausschließlich `FanSafety` hier — mit
|
||||
/// Temperaturen, die der Helfer selbst misst.
|
||||
final class FanService: NSObject, OnyxHelperProtocol {
|
||||
|
||||
private let smc: SMCAccess?
|
||||
/// Wunschdrehzahl je Lüfter. Leer heißt Automatik.
|
||||
private var requests: [Int: FanRequest] = [:]
|
||||
private var lastHeartbeat = Date.distantPast
|
||||
private var lastDecision: [Int: FanDecision] = [:]
|
||||
private let queue = DispatchQueue(label: "com.scarriffleservices.onyx.helper.fans")
|
||||
|
||||
private lazy var temperatureKeys: [String] = smc?.keys(withPrefix: "Tp") ?? []
|
||||
private lazy var fanCount: Int = {
|
||||
guard let value = smc?.float("FNum") else { return Int(smc?.uint8("FNum") ?? 0) }
|
||||
return Int(value)
|
||||
}()
|
||||
|
||||
override init() {
|
||||
smc = SMCAccess()
|
||||
super.init()
|
||||
startControlLoop()
|
||||
}
|
||||
|
||||
// MARK: - Regelschleife
|
||||
|
||||
/// Läuft ununterbrochen, solange der Helfer lebt.
|
||||
///
|
||||
/// Die Entscheidung wird **jede Sekunde neu** getroffen, nicht nur beim
|
||||
/// Setzen. Nur so greifen Wachhund und Temperaturwächter auch dann, wenn
|
||||
/// von der App nie wieder etwas kommt.
|
||||
private func startControlLoop() {
|
||||
queue.async { [weak self] in
|
||||
let timer = Timer(timeInterval: 1, repeats: true) { _ in self?.apply() }
|
||||
RunLoop.current.add(timer, forMode: .common)
|
||||
RunLoop.current.run()
|
||||
}
|
||||
}
|
||||
|
||||
private func apply() {
|
||||
guard let smc, fanCount > 0 else { return }
|
||||
let hottest = hottestTemperature()
|
||||
|
||||
for index in 0..<fanCount {
|
||||
let limits = FanLimits(minimum: smc.float("F\(index)Mn") ?? 0,
|
||||
maximum: smc.float("F\(index)Mx") ?? 0)
|
||||
let decision = FanSafety.decide(request: requests[index],
|
||||
lastHeartbeat: lastHeartbeat,
|
||||
now: Date(),
|
||||
hottestCelsius: hottest,
|
||||
limits: limits)
|
||||
|
||||
// Nur schreiben, wenn sich etwas ändert: jeder SMC-Schreibvorgang
|
||||
// ist ein Eingriff, und eine Sekunde später denselben Wert erneut
|
||||
// zu setzen bringt nichts.
|
||||
guard decision != lastDecision[index] else { continue }
|
||||
lastDecision[index] = decision
|
||||
|
||||
switch decision {
|
||||
case .manual(let rpm):
|
||||
smc.writeUInt8("F\(index)md", 1)
|
||||
smc.writeFloat("F\(index)Tg", rpm)
|
||||
log.notice("Lüfter \(index): manuell \(Int(rpm)) U/min")
|
||||
case .automatic(let reason):
|
||||
smc.writeUInt8("F\(index)md", 0)
|
||||
if reason != .noRequest {
|
||||
// Ein erzwungener Rückfall ist ein Ereignis, das man später
|
||||
// nachvollziehen können muss.
|
||||
log.error("Lüfter \(index): Rückfall auf Automatik — \(reason.rawValue, privacy: .public)")
|
||||
requests[index] = nil
|
||||
} else {
|
||||
log.notice("Lüfter \(index): Automatik")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func hottestTemperature() -> Double? {
|
||||
guard let smc, !temperatureKeys.isEmpty else { return nil }
|
||||
return temperatureKeys.compactMap { key -> Double? in
|
||||
guard let value = smc.float(key), value > 5, value < 150 else { return nil }
|
||||
return value
|
||||
}.max()
|
||||
}
|
||||
|
||||
/// Beim Beenden alles zurückstellen.
|
||||
///
|
||||
/// Ohne das blieben die Lüfter nach einem Abmelden oder Neustart des
|
||||
/// Dienstes auf ihrem letzten Wert stehen — bis zum nächsten Neustart des
|
||||
/// Rechners.
|
||||
func restoreAutomatic() {
|
||||
guard let smc else { return }
|
||||
for index in 0..<fanCount { smc.writeUInt8("F\(index)md", 0) }
|
||||
log.notice("Alle Lüfter auf Automatik zurückgestellt")
|
||||
}
|
||||
|
||||
// MARK: - Schnittstelle
|
||||
|
||||
func version(reply: @escaping (String) -> Void) { reply(OnyxHelper.version) }
|
||||
|
||||
func heartbeat(reply: @escaping (Bool) -> Void) {
|
||||
lastHeartbeat = Date()
|
||||
reply(true)
|
||||
}
|
||||
|
||||
func fanStatus(reply: @escaping (Data?) -> Void) { reply(report()) }
|
||||
|
||||
func setFan(index: Int, targetRPM: Double, reply: @escaping (Data?) -> Void) {
|
||||
lastHeartbeat = Date()
|
||||
requests[index] = FanRequest(targetRPM: targetRPM)
|
||||
apply()
|
||||
reply(report())
|
||||
}
|
||||
|
||||
func setFanAutomatic(index: Int, reply: @escaping (Data?) -> Void) {
|
||||
lastHeartbeat = Date()
|
||||
requests[index] = nil
|
||||
apply()
|
||||
reply(report())
|
||||
}
|
||||
|
||||
private func report() -> Data? {
|
||||
guard let smc else { return nil }
|
||||
let fans = (0..<fanCount).map { index -> FanStatus in
|
||||
let decision = lastDecision[index]
|
||||
var reason: String?
|
||||
var manual = false
|
||||
if case .manual = decision { manual = true }
|
||||
if case .automatic(let value) = decision { reason = value.rawValue }
|
||||
|
||||
return FanStatus(index: index,
|
||||
currentRPM: smc.float("F\(index)Ac") ?? 0,
|
||||
targetRPM: smc.float("F\(index)Tg") ?? 0,
|
||||
limits: FanLimits(minimum: smc.float("F\(index)Mn") ?? 0,
|
||||
maximum: smc.float("F\(index)Mx") ?? 0),
|
||||
isManual: manual,
|
||||
automaticReason: reason)
|
||||
}
|
||||
return try? JSONEncoder().encode(
|
||||
FanStatusReport(fans: fans, hottestCelsius: hottestTemperature(),
|
||||
helperVersion: OnyxHelper.version))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - XPC
|
||||
|
||||
final class Listener: NSObject, NSXPCListenerDelegate {
|
||||
let service = FanService()
|
||||
|
||||
func listener(_ listener: NSXPCListener,
|
||||
shouldAcceptNewConnection connection: NSXPCConnection) -> Bool {
|
||||
// Ohne diese Prüfung könnte **jedes** Programm auf dem Rechner die
|
||||
// Lüfter steuern: der Mach-Dienst eines root-Daemons ist systemweit
|
||||
// sichtbar, und wer ihn anspricht, spricht mit root.
|
||||
do {
|
||||
try connection.setCodeSigningRequirement(OnyxHelper.clientRequirement)
|
||||
} catch {
|
||||
log.error("Verbindung abgelehnt: Signaturanforderung nicht setzbar")
|
||||
return false
|
||||
}
|
||||
|
||||
connection.exportedInterface = NSXPCInterface(with: OnyxHelperProtocol.self)
|
||||
connection.exportedObject = service
|
||||
connection.resume()
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
let listener = NSXPCListener(machServiceName: OnyxHelper.machServiceName)
|
||||
let delegate = Listener()
|
||||
listener.delegate = delegate
|
||||
listener.resume()
|
||||
|
||||
// Beim Beenden — auch durch launchd — die Lüfter freigeben.
|
||||
for signalNumber in [SIGTERM, SIGINT] {
|
||||
signal(signalNumber, SIG_IGN)
|
||||
let source = DispatchSource.makeSignalSource(signal: signalNumber, queue: .main)
|
||||
source.setEventHandler {
|
||||
delegate.service.restoreAutomatic()
|
||||
exit(0)
|
||||
}
|
||||
source.resume()
|
||||
}
|
||||
|
||||
log.notice("Onyx-Helfer bereit")
|
||||
RunLoop.main.run()
|
||||
Reference in New Issue
Block a user