Neuer Tab: eine Tabelle pro physischem Ethernet/WLAN-Port mit den dort gefundenen Geräten (Name, IP, MAC, Fest/Dynamisch/Kein-DHCP), gebaut aus DHCP-Leases + ARP + Bridge-Host-Tabelle. Rechtsklick auf ein dynamisches Gerät -> "Feste IP zuweisen" (RouterOS' "Make Static", per /ip dhcp-server lease make-static), mit Bestätigungsdialog und Session-Backup vor dem ersten Schreibvorgang (geteilter Mechanismus mit dem Experte-Tab). Vier reale Bugs live gefunden und gefixt (siehe HANDOFF.md Bug 14-17): - "print terse" gibt das "dynamic"-Feld von /ip dhcp-server lease nie aus, in keinem Zustand -> Status kommt jetzt über RouterOS' find/get gegen die interne Eigenschaft, nicht aus gelesenen Feldern. - fetchMenuItems' .id-Positionsüberlagerung ordnete für dieses Menü die falsche .id der falschen Zeile zu -> Erkennung und make-static-Ziel laufen jetzt über die MAC-Adresse statt .id. - Ein SwiftUI-.confirmationDialog löschte sein eigenes Ziel-Objekt vor der Ausführung der bestätigten Aktion (Setter feuert bei jedem Knopfdruck, nicht nur Abbrechen) -> Dialog-Sichtbarkeit und Nutzlast entkoppelt, wie in BackupListView. - Die eigene Verifikations-Abfrage (get [find ...] feld als ein kombinierter Befehl) war selbst eine nie verifizierte Annahme und lieferte falsche Negative -> ersetzt durch :foreach aus zwei einzeln bestätigten Bausteinen (find, get <id> feld). RouterOSCommand bekommt einen neuen .action-Operationstyp für RouterOS-"Menü-spezifische Befehle" jenseits von add/set/remove (aktuell nur make-static). HANDOFF.md/CHATLOG.md mit allen vier Bugs, neuen Milestones M11/M12 und offenen Punkten aktualisiert. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CTgRxJTzaQwaRkngbaE1GJ
233 lines
11 KiB
Swift
233 lines
11 KiB
Swift
import Foundation
|
|
|
|
/// REST-API transport for RouterOS >= 7.1 (JSON over HTTPS, `/rest/...`).
|
|
final class RestTransport: NSObject, RouterOSTransport {
|
|
let kind: RouterOSTransportKind = .rest
|
|
|
|
private let credentials: RouterOSCredentials
|
|
private let certificateTrust: CertificateTrustStore
|
|
private var lastRejectedFingerprint: String?
|
|
|
|
private lazy var session: URLSession = URLSession(
|
|
configuration: .ephemeral,
|
|
delegate: self,
|
|
delegateQueue: nil
|
|
)
|
|
|
|
init(credentials: RouterOSCredentials, certificateTrust: CertificateTrustStore) {
|
|
self.credentials = credentials
|
|
self.certificateTrust = certificateTrust
|
|
}
|
|
|
|
private var baseURL: URL {
|
|
URL(string: "https://\(credentials.host):\(credentials.httpsPort)/rest")!
|
|
}
|
|
|
|
func connect() async throws {
|
|
_ = try await fetchDeviceInfo()
|
|
}
|
|
|
|
func fetchDeviceInfo() async throws -> RouterDeviceInfo {
|
|
let json = try await getJSONObject(path: "system/resource")
|
|
guard
|
|
let boardName = json["board-name"] as? String,
|
|
let version = json["version"] as? String,
|
|
let arch = json["architecture-name"] as? String
|
|
else {
|
|
throw RouterOSError.invalidResponse("system/resource")
|
|
}
|
|
let uptime = json["uptime"] as? String ?? "-"
|
|
return RouterDeviceInfo(boardName: boardName, routerOSVersion: version, architecture: arch, uptime: uptime)
|
|
}
|
|
|
|
func fetchInterfaces() async throws -> [NetworkInterface] {
|
|
let array = try await getJSONArray(path: "interface")
|
|
return array.compactMap { item in
|
|
guard let name = item["name"] as? String, let type = item["type"] as? String else {
|
|
return nil
|
|
}
|
|
return NetworkInterface(
|
|
name: name,
|
|
type: type,
|
|
running: (item["running"] as? String) == "true",
|
|
disabled: (item["disabled"] as? String) == "true",
|
|
macAddress: item["mac-address"] as? String
|
|
)
|
|
}
|
|
}
|
|
|
|
func fetchFirewallRuleCounts() async throws -> FirewallRuleCounts {
|
|
let filterItems = try await getJSONArray(path: "ip/firewall/filter")
|
|
let natItems = try await getJSONArray(path: "ip/firewall/nat")
|
|
return FirewallRuleCounts(filterRuleCount: filterItems.count, natRuleCount: natItems.count)
|
|
}
|
|
|
|
/// Creates or modifies the item described by `command`. `.add` is a plain
|
|
/// `POST /rest/<restPath>`. `.set` has no CLI-style inline lookup on REST, so it first
|
|
/// `GET`s the collection to find the item whose `matchField` equals `matchValue`, reads
|
|
/// its RouterOS-internal `.id`, then `PATCH`es `restPath/<id>`.
|
|
func fetchMenuItems(menuPath: String, restPath: String) async throws -> [RouterOSMenuItem] {
|
|
let data = try await send(path: restPath, method: "GET", jsonBody: nil)
|
|
if let array = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] {
|
|
return array.map { Self.menuItem(from: $0) }
|
|
}
|
|
// Singleton menu (e.g. "/ip dns") — REST returns one JSON object, not an array.
|
|
if let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
|
|
return [Self.menuItem(from: object)]
|
|
}
|
|
throw RouterOSError.invalidResponse(restPath)
|
|
}
|
|
|
|
/// Unverified against real hardware (this app's REST write/query paths in general are —
|
|
/// see HANDOFF.md). RouterOS REST's general convention is that a GET accepts query-string
|
|
/// property filters (`?field=value`), mirroring the console's `find field=value` — used here
|
|
/// on the same assumption, not confirmed for this exact property. Unlike SSH, REST's GET
|
|
/// already returns full objects, so no separate id-overlay is involved here at all.
|
|
func fetchFieldValues(menuPath: String, restPath: String, whereField: String, whereValue: String, returnField: String) async throws -> Set<String> {
|
|
let data = try await send(path: "\(restPath)?\(whereField)=\(whereValue)", method: "GET", jsonBody: nil)
|
|
guard let array = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else {
|
|
return []
|
|
}
|
|
return Set(array.compactMap { $0[returnField] as? String })
|
|
}
|
|
|
|
private static func menuItem(from item: [String: Any]) -> RouterOSMenuItem {
|
|
var fields: [String: String] = [:]
|
|
var id = ""
|
|
for (key, value) in item {
|
|
let stringValue = (value as? String) ?? String(describing: value)
|
|
if key == ".id" {
|
|
id = stringValue
|
|
} else {
|
|
fields[key] = stringValue
|
|
}
|
|
}
|
|
return RouterOSMenuItem(id: id.isEmpty ? "singleton" : id, fields: fields)
|
|
}
|
|
|
|
func apply(_ command: RouterOSCommand) async throws {
|
|
switch command.operation {
|
|
case .add:
|
|
_ = try await send(path: command.restPath, method: "POST", jsonBody: command.arguments)
|
|
case .set(let matchField, let matchValue):
|
|
// Empty matchField = singleton menu (e.g. "/ip dns") — PATCH the resource directly,
|
|
// there's no list/id to look up. See RouterOSCommand.cliLine for the SSH counterpart.
|
|
if matchField.isEmpty {
|
|
_ = try await send(path: command.restPath, method: "PATCH", jsonBody: command.arguments)
|
|
} else {
|
|
let itemID = try await findItemID(path: command.restPath, matchField: matchField, matchValue: matchValue)
|
|
_ = try await send(path: "\(command.restPath)/\(itemID)", method: "PATCH", jsonBody: command.arguments)
|
|
}
|
|
case .remove(let matchField, let matchValue):
|
|
let itemID = try await findItemID(path: command.restPath, matchField: matchField, matchValue: matchValue)
|
|
_ = try await send(path: "\(command.restPath)/\(itemID)", method: "DELETE", jsonBody: nil)
|
|
case .action(let name, let matchField, let matchValue):
|
|
// Community-reported shape (not MikroTik-documented, see RouterOSCommand.Operation)
|
|
// — POST to the action's own sub-path with the matched item's id under "numbers",
|
|
// mirroring the console's own `<path> <name> numbers=<id>` argument name.
|
|
let itemID = try await findItemID(path: command.restPath, matchField: matchField, matchValue: matchValue)
|
|
_ = try await send(path: "\(command.restPath)/\(name)", method: "POST", jsonBody: ["numbers": itemID])
|
|
}
|
|
}
|
|
|
|
private func findItemID(path: String, matchField: String, matchValue: String) async throws -> String {
|
|
let items = try await getJSONArray(path: path)
|
|
guard let match = items.first(where: { ($0[matchField] as? String) == matchValue }) else {
|
|
throw RouterOSError.invalidResponse("Kein Eintrag mit \(matchField)=\(matchValue) unter \(path) gefunden")
|
|
}
|
|
guard let id = match[".id"] as? String else {
|
|
throw RouterOSError.invalidResponse("Eintrag unter \(path) hat keine .id")
|
|
}
|
|
return id
|
|
}
|
|
|
|
func disconnect() async {
|
|
session.invalidateAndCancel()
|
|
}
|
|
|
|
private func getJSONObject(path: String) async throws -> [String: Any] {
|
|
let data = try await send(path: path, method: "GET", jsonBody: nil)
|
|
guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
|
throw RouterOSError.invalidResponse(path)
|
|
}
|
|
return object
|
|
}
|
|
|
|
private func getJSONArray(path: String) async throws -> [[String: Any]] {
|
|
let data = try await send(path: path, method: "GET", jsonBody: nil)
|
|
guard let array = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] else {
|
|
throw RouterOSError.invalidResponse(path)
|
|
}
|
|
return array
|
|
}
|
|
|
|
private func send(path: String, method: String, jsonBody: [String: String]?) async throws -> Data {
|
|
// `URL(string:relativeTo:)` (not `appendingPathComponent`, which percent-encodes "?")
|
|
// so a path carrying a query string (e.g. "ip/dhcp-server/lease?dynamic=no" from
|
|
// `fetchItemIDs`) is actually sent as a query, not a literal "?"-containing path segment.
|
|
guard let url = URL(string: path, relativeTo: baseURL) else {
|
|
throw RouterOSError.invalidResponse(path)
|
|
}
|
|
var request = URLRequest(url: url)
|
|
request.httpMethod = method
|
|
|
|
let authString = "\(credentials.username):\(credentials.password)"
|
|
guard let authData = authString.data(using: .utf8) else {
|
|
throw RouterOSError.invalidResponse("credentials")
|
|
}
|
|
request.setValue("Basic \(authData.base64EncodedString())", forHTTPHeaderField: "Authorization")
|
|
request.timeoutInterval = 5
|
|
|
|
if let jsonBody {
|
|
request.httpBody = try JSONSerialization.data(withJSONObject: jsonBody)
|
|
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
|
|
}
|
|
|
|
lastRejectedFingerprint = nil
|
|
do {
|
|
let (data, response) = try await session.data(for: request)
|
|
guard let httpResponse = response as? HTTPURLResponse else {
|
|
throw RouterOSError.invalidResponse(path)
|
|
}
|
|
if httpResponse.statusCode == 401 {
|
|
throw RouterOSError.authenticationFailed
|
|
}
|
|
guard (200...299).contains(httpResponse.statusCode) else {
|
|
throw RouterOSError.invalidResponse("HTTP \(httpResponse.statusCode)")
|
|
}
|
|
return data
|
|
} catch let error as RouterOSError {
|
|
throw error
|
|
} catch {
|
|
if let fingerprint = lastRejectedFingerprint {
|
|
throw RouterOSError.untrustedCertificate(fingerprint: fingerprint)
|
|
}
|
|
throw RouterOSError.transportUnavailable("REST-Verbindung fehlgeschlagen: \(error.localizedDescription)")
|
|
}
|
|
}
|
|
}
|
|
|
|
extension RestTransport: URLSessionDelegate {
|
|
func urlSession(
|
|
_ session: URLSession,
|
|
didReceive challenge: URLAuthenticationChallenge,
|
|
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
|
|
) {
|
|
guard
|
|
challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
|
|
let serverTrust = challenge.protectionSpace.serverTrust
|
|
else {
|
|
completionHandler(.performDefaultHandling, nil)
|
|
return
|
|
}
|
|
|
|
let fingerprint = CertificateFingerprint.sha256(of: serverTrust)
|
|
if certificateTrust.isTrusted(host: credentials.host, fingerprint: fingerprint) {
|
|
completionHandler(.useCredential, URLCredential(trust: serverTrust))
|
|
} else {
|
|
lastRejectedFingerprint = fingerprint
|
|
completionHandler(.cancelAuthenticationChallenge, nil)
|
|
}
|
|
}
|
|
}
|