forked from kay/RouterOS
Verbinden-Tab zeigt jetzt die volle Routerboard-Info (Modell/Revision/ Seriennummer/Firmware, aus /system routerboard) sowie einen RouterOS-Software-Update-Check (/system package update: Kanal/ installierte/neueste Version/Status, "Jetzt pruefen"/"Update installieren"), dazu "Firmware aktualisieren" fuer die Routerboard-Bootloader-Firmware und "Jetzt neu starten" danach. Alle vier Aktionen live bestaetigt, inklusive der zuvor unsicheren Frage, ob /system routerboard upgrade's normalerweise interaktive Bestaetigung den nicht-interaktiven SSH-Weg dieser App blockiert (tut es nicht). Bug 20 gefunden und gefixt: fetchMenuItems' Singleton-Fallback (Bug 8) reagierte nur auf eine geworfene Exception fuer "bad parameter terse", aber RouterOS liefert diesen Fehler fuer /system routerboard mit Exit-Code 0 zurueck (dasselbe Bug-10-Muster, diesmal beim Lesen statt Schreiben) - die Routerboard-Sektion blieb dadurch leer, ohne Fehler. Fix: zusaetzlich den Output-Text selbst pruefen, nicht nur die Exception. Design-Durchgang: Verbinden-Detailseite/Sicherungen/Geraete liefen auf nackter List ohne Rahmen - umgestellt auf Form+.formStyle(.grouped), denselben nativen macOS-Karten-Look, den Wizard und Experte-Tab schon hatten, fuer eine einheitliche App. Dark Mode auf Nachfrage gepueft und ohne Codeaenderung bestaetigt funktionierend. HANDOFF.md/CHATLOG.md aktualisiert: M14, Bug 20, Design-Durchgang, Dark-Mode-Bestaetigung. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CTgRxJTzaQwaRkngbaE1GJ
156 lines
7.0 KiB
Swift
156 lines
7.0 KiB
Swift
import Foundation
|
|
|
|
/// Drives the REST-first, SSH-fallback connection flow and holds the connected device's state.
|
|
@MainActor
|
|
final class ConnectionService: ObservableObject {
|
|
enum State: Equatable {
|
|
case idle
|
|
case connecting
|
|
case connected(kind: RouterOSTransportKind)
|
|
case needsCertificateConfirmation(fingerprint: String)
|
|
case needsSSHHostKeyConfirmation(fingerprint: String)
|
|
case failed(String)
|
|
}
|
|
|
|
@Published private(set) var state: State = .idle
|
|
@Published private(set) var deviceInfo: RouterDeviceInfo?
|
|
@Published private(set) var routerBoardInfo: RouterBoardInfo?
|
|
@Published private(set) var interfaces: [NetworkInterface] = []
|
|
/// Credentials of the current (or last attempted) connection, shared with features
|
|
/// that need their own dedicated connection, e.g. BackupService's SSH export.
|
|
@Published private(set) var credentials: RouterOSCredentials?
|
|
|
|
private let certificateTrust: CertificateTrustStore
|
|
private let sshHostKeyTrust: SSHHostKeyTrustStore
|
|
private var activeTransport: RouterOSTransport?
|
|
/// Whether the Expert tool has already made its one automatic safety backup for this
|
|
/// connection — it backs up before its first write, not before every single edit (unlike
|
|
/// the Einrichten-Wizard, which backs up before every "Jetzt anwenden"). Reset on
|
|
/// `disconnect()` so a new connection gets a fresh backup again.
|
|
private(set) var hasExpertToolBackedUpThisSession = false
|
|
|
|
func markExpertToolBackedUpThisSession() {
|
|
hasExpertToolBackedUpThisSession = true
|
|
}
|
|
|
|
init(
|
|
certificateTrust: CertificateTrustStore = CertificateTrustStore(),
|
|
sshHostKeyTrust: SSHHostKeyTrustStore = SSHHostKeyTrustStore()
|
|
) {
|
|
self.certificateTrust = certificateTrust
|
|
self.sshHostKeyTrust = sshHostKeyTrust
|
|
}
|
|
|
|
/// Injection point for tests: bypasses the real REST/SSH transports.
|
|
func connect(with credentials: RouterOSCredentials, makeRestTransport: () -> RouterOSTransport, makeSSHTransport: () -> RouterOSTransport) async {
|
|
state = .connecting
|
|
self.credentials = credentials
|
|
|
|
let rest = makeRestTransport()
|
|
do {
|
|
try await rest.connect()
|
|
await finishConnecting(using: rest)
|
|
return
|
|
} catch RouterOSError.untrustedCertificate(let fingerprint) {
|
|
state = .needsCertificateConfirmation(fingerprint: fingerprint)
|
|
return
|
|
} catch {
|
|
// REST fehlgeschlagen (z.B. altes RouterOS ohne REST-API) -> SSH-Fallback versuchen.
|
|
}
|
|
|
|
let ssh = makeSSHTransport()
|
|
do {
|
|
try await ssh.connect()
|
|
await finishConnecting(using: ssh)
|
|
} catch RouterOSError.untrustedSSHHostKey(let fingerprint) {
|
|
state = .needsSSHHostKeyConfirmation(fingerprint: fingerprint)
|
|
} catch {
|
|
state = .failed(error.localizedDescription)
|
|
}
|
|
}
|
|
|
|
func connect(with credentials: RouterOSCredentials) async {
|
|
await connect(
|
|
with: credentials,
|
|
makeRestTransport: { RestTransport(credentials: credentials, certificateTrust: self.certificateTrust) },
|
|
makeSSHTransport: { SSHTransport(credentials: credentials, hostKeyTrust: self.sshHostKeyTrust) }
|
|
)
|
|
}
|
|
|
|
func trustCurrentCertificateAndRetry(fingerprint: String) async {
|
|
guard let credentials else { return }
|
|
certificateTrust.trust(host: credentials.host, fingerprint: fingerprint)
|
|
await connect(with: credentials)
|
|
}
|
|
|
|
func trustCurrentSSHHostKeyAndRetry(fingerprint: String) async {
|
|
guard let credentials else { return }
|
|
sshHostKeyTrust.trust(host: credentials.host, fingerprint: fingerprint)
|
|
await connect(with: credentials)
|
|
}
|
|
|
|
/// Applies a single configuration change on the active transport (REST or SSH).
|
|
func apply(_ command: RouterOSCommand) async throws {
|
|
guard let activeTransport else { throw RouterOSError.notConnected }
|
|
try await activeTransport.apply(command)
|
|
}
|
|
|
|
func fetchFirewallRuleCounts() async throws -> FirewallRuleCounts {
|
|
guard let activeTransport else { throw RouterOSError.notConnected }
|
|
return try await activeTransport.fetchFirewallRuleCounts()
|
|
}
|
|
|
|
/// Generic read for the Expert tool — lists existing items under any RouterOS menu path.
|
|
func fetchMenuItems(menuPath: String, restPath: String) async throws -> [RouterOSMenuItem] {
|
|
guard let activeTransport else { throw RouterOSError.notConnected }
|
|
return try await activeTransport.fetchMenuItems(menuPath: menuPath, restPath: restPath)
|
|
}
|
|
|
|
/// Field values matching an internal-property filter — see `RouterOSTransport.fetchFieldValues`.
|
|
func fetchFieldValues(menuPath: String, restPath: String, whereField: String, whereValue: String, returnField: String) async throws -> Set<String> {
|
|
guard let activeTransport else { throw RouterOSError.notConnected }
|
|
return try await activeTransport.fetchFieldValues(menuPath: menuPath, restPath: restPath, whereField: whereField, whereValue: whereValue, returnField: returnField)
|
|
}
|
|
|
|
private func finishConnecting(using transport: RouterOSTransport) async {
|
|
activeTransport = transport
|
|
do {
|
|
deviceInfo = try await transport.fetchDeviceInfo()
|
|
interfaces = try await transport.fetchInterfaces()
|
|
// Best-effort: some devices (e.g. CHR/x86 virtual routers) have no physical
|
|
// RouterBOARD at all, so this menu can legitimately be absent — must not fail the
|
|
// whole connection over it.
|
|
routerBoardInfo = try? await Self.fetchRouterBoardInfo(using: transport)
|
|
state = .connected(kind: transport.kind)
|
|
} catch {
|
|
state = .failed(error.localizedDescription)
|
|
}
|
|
}
|
|
|
|
/// Field names confirmed live (hEX, RouterOS 6.49.16, see `RouterBoardInfo`'s doc comment).
|
|
private static func fetchRouterBoardInfo(using transport: RouterOSTransport) async throws -> RouterBoardInfo {
|
|
let items = try await transport.fetchMenuItems(menuPath: "/system routerboard", restPath: "system/routerboard")
|
|
guard let fields = items.first?.fields else { throw RouterOSError.invalidResponse("system/routerboard") }
|
|
return RouterBoardInfo(
|
|
model: fields["model"] ?? "unbekannt",
|
|
revision: fields["revision"] ?? "unbekannt",
|
|
serialNumber: fields["serial-number"] ?? "unbekannt",
|
|
firmwareType: fields["firmware-type"] ?? "unbekannt",
|
|
currentFirmware: fields["current-firmware"] ?? "unbekannt",
|
|
minimumFirmware: fields["minimum-firmware"] ?? "unbekannt",
|
|
upgradeFirmware: fields["upgrade-firmware"] ?? "unbekannt"
|
|
)
|
|
}
|
|
|
|
func disconnect() async {
|
|
await activeTransport?.disconnect()
|
|
activeTransport = nil
|
|
deviceInfo = nil
|
|
routerBoardInfo = nil
|
|
interfaces = []
|
|
credentials = nil
|
|
hasExpertToolBackedUpThisSession = false
|
|
state = .idle
|
|
}
|
|
}
|