From 757bf302b090c45a08f86add67e1104ee4a6791c Mon Sep 17 00:00:00 2001 From: Marcin Beczynski Date: Wed, 2 Dec 2026 09:12:40 +0100 Subject: [PATCH] =?UTF-8?q?fix-destination:=20cel=20nazwa=20zast=C4=99puje?= =?UTF-8?q?=20cel=20pod=20adresem=20(te=C5=BC=20aliasem)=20i=20zwalnia=20w?= =?UTF-8?q?pis=20z=20/etc/bootptab?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Przy celu Target.name adres statyczny (alias) był uznawany za poprawny (reserveOnly), więc polecenie nic nie robiło. Teraz alias liczy się tylko dla celu adresowego; cel nazwa daje replace(id). To samo okno administratora usuwa linię z MAC maszyny z /etc/bootptab (na końcu łańcucha). Co-Authored-By: Claude Opus 5.5 --- .../TimeMachineDestinationFix.swift | 57 +++++-- .../VMMdnsNameTests.swift | 158 ++++++++++++++++++ 2 files changed, 205 insertions(+), 10 deletions(-) diff --git a/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift b/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift index eeaa8f1..959d5bd 100644 --- a/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift +++ b/mac-app/Sources/CloudMachineCore/TimeMachineDestinationFix.swift @@ -39,13 +39,16 @@ public enum TimeMachineDestinationFix { /// The machine's destination among Time Machine's decides. /// A destination at the machine's static `alias` (`VMAddressLease`) is - /// correct too: only the reservation is made, the destination stays. + /// correct too when the target is an address: only the reservation is made, the + /// destination stays. When the target is a NAME (`Target.name`), the alias does not count: + /// an address in the destination is exactly what the name replaces. static func plan( destinations: [TimeMachineStatus.Destination], address: String, alias: String? = nil ) -> Plan { guard let ours = VMStatus.machineDestination(in: destinations, address: nil) else { return .add } + let alias = VMAddressLease.isIPv4(address) ? alias : nil if let url = ours.url, VMStatus.isMachineShare(url, address: address, alias: alias) { return .reserveOnly } @@ -70,11 +73,11 @@ public enum TimeMachineDestinationFix { return .address(address) } - /// `run`, by name when that works (`target`): no reservation is written, so the one - /// administrator dialog only changes Time Machine. By address otherwise, as before. + /// `run`, by name when that works (`target`): no reservation is written, and the machine's + /// entry (its MAC) is removed from `/etc/bootptab` in the same administrator dialog. By address otherwise, as before. public static func runPreferringName(address: String?, mac: String?) async -> CMActionResult { switch target(address: address) { - case .name(let name): return await run(address: name, mac: nil) + case .name(let name): return await run(address: name, mac: nil, releaseMac: mac) case .address, .none: return await run(address: address, mac: mac) } } @@ -149,9 +152,15 @@ public enum TimeMachineDestinationFix { static func shellCommand( address: String, passwordFile: String, uid: uid_t = getuid(), mac: String? = nil, name: String = defaultName, plan: Plan = .add, quotaGB: Int? = nil, - oldHost: String? = nil + oldHost: String? = nil, releaseMac: String? = nil ) -> String? { var steps: [String] = [] + // Last: a failed Time Machine step stops the chain before the reservation is given up. + var release: String? + if let releaseMac { + guard let command = releaseReservationCommand(mac: releaseMac) else { return nil } + release = command + } if let mac { guard let reservation = reservationCommand(mac: mac, address: address, name: name) else { return nil @@ -171,6 +180,7 @@ public enum TimeMachineDestinationFix { steps.append(addCommand(address: address, passwordFile: passwordFile, uid: uid)) if let quotaGB { steps.append(quotaCommand(address: address, quotaGB: quotaGB)) } } + if let release { steps.append(release) } return steps.isEmpty ? nil : steps.joined(separator: " && ") } @@ -203,6 +213,24 @@ public enum TimeMachineDestinationFix { ].joined(separator: " && ") } + /// Removes the machine's line (its MAC, any address) from the second section of + /// `/etc/bootptab`; the rest of the file stays, a file left with only its header stays too. + /// Used when Time Machine points at the NAME: no reservation is needed then. + static let releaseAwkProgram = "/^%%/{s=1} s && NF>=4 && !/^#/ && tolower($3)==m{next} {print}" + + static func releaseReservationCommand(mac: String) -> String? { + guard matches(mac, "^[0-9a-f]{2}(:[0-9a-f]{2}){5}$") else { return nil } + let file = "/etc/bootptab" + let new = "/etc/bootptab.cloudmachine" + let awk = "/usr/bin/awk -v m='\(mac)' '\(releaseAwkProgram)'" + return [ + "[ -f \(file) ]", + "\(awk) \(file) > \(new)", + "/bin/mv \(new) \(file)", + "{ /usr/bin/pkill -HUP -x bootpd || true; }", + ].joined(separator: " && ") + } + static func appleScriptQuoted(_ text: String) -> String { "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences( @@ -238,8 +266,8 @@ public enum TimeMachineDestinationFix { /// nor root. `limitGB` is the space limit, whose quota is set again after a /// destination was replaced. public static func run( - address: String?, mac: String? = nil, name: String = defaultName, - passwordFile: URL = VMLayout.passwordFile, uid: uid_t = getuid(), + address: String?, mac: String? = nil, releaseMac: String? = nil, + name: String = defaultName, passwordFile: URL = VMLayout.passwordFile, uid: uid_t = getuid(), limitGB: Int? = MachineBudget.limitGB(), execute: @Sendable (String, [String]) async throws -> ProcessResult = { executable, arguments in try await ProcessRunner.run(executable, arguments, timeout: 600) @@ -273,9 +301,14 @@ public enum TimeMachineDestinationFix { guard let before = await readDestinations() else { return couldNot("tmutil did not answer") } - let alias = await readAlias() + // The alias is an address like the DHCP one: it only counts for an address target. + let alias = VMAddressLease.isIPv4(address) ? await readAlias() : nil let plan = plan(destinations: before, address: address, alias: alias) - if plan == .reserveOnly && mac == nil { + // Only when the file still binds that MAC is there something to release. + let release: String? = releaseMac.flatMap { mac in + readBootptab().flatMap { DHCPPool.bootptabAddress($0, mac: mac) } == nil ? nil : mac + } + if plan == .reserveOnly && mac == nil && release == nil { return CMActionResult( succeeded: true, message: L10n.tr("Time Machine already points at the machine (%@).", address)) @@ -285,7 +318,8 @@ public enum TimeMachineDestinationFix { let shell = shellCommand( address: address, passwordFile: passwordFile.path, uid: uid, mac: mac, name: name, plan: plan, quotaGB: quota, - oldHost: VMStatus.machineDestination(in: before, address: nil)?.url.flatMap(host(ofURL:))) + oldHost: VMStatus.machineDestination(in: before, address: nil)?.url.flatMap(host(ofURL:)), + releaseMac: release) else { return couldNot("invalid MAC address, name or destination id") } let script = appleScript( @@ -318,6 +352,9 @@ public enum TimeMachineDestinationFix { if let mac, !DHCPPool.bootptabReserves(readBootptab() ?? "", mac: mac, address: address) { return fail(L10n.tr("The address reservation was not written to /etc/bootptab.")) } + if let release, DHCPPool.bootptabAddress(readBootptab() ?? "", mac: release) != nil { + return couldNot("the reservation was not removed from /etc/bootptab") + } let said = scrubbed(result.stdout).trimmingCharacters(in: .whitespacesAndNewlines) if !said.isEmpty { CMLogger.log("fix-destination: \(said.replacingOccurrences(of: "\n", with: "; "))") diff --git a/mac-app/Tests/CloudMachineAppTests/VMMdnsNameTests.swift b/mac-app/Tests/CloudMachineAppTests/VMMdnsNameTests.swift index 334b5a8..0295d5a 100644 --- a/mac-app/Tests/CloudMachineAppTests/VMMdnsNameTests.swift +++ b/mac-app/Tests/CloudMachineAppTests/VMMdnsNameTests.swift @@ -67,6 +67,164 @@ final class VMMdnsNameTests: XCTestCase { .reserveOnly) } + func testDestinationAtTheStaticAliasIsReplacedByTheName() { + XCTAssertEqual( + TimeMachineDestinationFix.plan( + destinations: [dest("192.168.64.10")], address: "lima-cmsmb.local", + alias: "192.168.64.10"), + .replace(id: "ID-1")) + } + + func testDestinationAtTheNameIsKeptEvenWhenAnAliasExists() { + XCTAssertEqual( + TimeMachineDestinationFix.plan( + destinations: [dest("lima-cmsmb.local")], address: "lima-cmsmb.local", + alias: "192.168.64.10"), + .reserveOnly) + } + + func testAddressTargetStillKeepsADestinationAtTheAlias() { + XCTAssertEqual( + TimeMachineDestinationFix.plan( + destinations: [dest("192.168.64.10")], address: "192.168.64.29", alias: "192.168.64.10"), + .reserveOnly) + } + + func testRunReplacesADestinationAtTheAliasWhenTargetIsTheName() async throws { + let executed = ExecutedScript() + let password = FileManager.default.temporaryDirectory.appendingPathComponent( + "tm-pass-\(UUID().uuidString)") + try "secret".write(to: password, atomically: true, encoding: .utf8) + chmod(password.path, 0o600) + defer { try? FileManager.default.removeItem(at: password) } + let result = await TimeMachineDestinationFix.run( + address: "lima-cmsmb.local", mac: nil, passwordFile: password, uid: getuid(), limitGB: nil, + execute: { _, arguments in + executed.script = arguments.joined(separator: " ") + return ProcessResult(stdout: "", stderr: "", exitCode: 0) + }, + readDestinations: { + executed.reads += 1 + return executed.reads == 1 ? [self.dest("192.168.64.10")] : [self.dest("lima-cmsmb.local")] + }, + readBootptab: { nil }, readAlias: { "192.168.64.10" }) + XCTAssertTrue(result.succeeded, result.message) + XCTAssertTrue(executed.script.contains("removedestination ID-1"), executed.script) + XCTAssertTrue(executed.script.contains("@lima-cmsmb.local/CloudMachine"), executed.script) + XCTAssertFalse(result.message.contains("already points")) + } + + // MARK: the name target releases the bootptab reservation + + private let tabMac = "52:55:55:ff:eb:94" + private let tab = + "# CloudMachine\n%%\n# manual\nlima-cmsmb\t1\t52:55:55:ff:eb:94\t192.168.64.10\n" + + "other\t1\t52:55:55:00:00:01\t192.168.64.20\n" + + func testReleaseCommandRemovesOnlyTheMachinesLine() throws { + let shell = try XCTUnwrap(TimeMachineDestinationFix.releaseReservationCommand(mac: tabMac)) + XCTAssertTrue(shell.contains("/etc/bootptab")) + XCTAssertTrue(shell.contains("tolower($3)==m")) + XCTAssertFalse(shell.contains("printf '%s\\t1"), "must not add an entry") + XCTAssertNil(TimeMachineDestinationFix.releaseReservationCommand(mac: "x; rm -rf /")) + } + + func testReleaseAwkDropsOnlyTheMachinesLine() throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/awk") + process.arguments = ["-v", "m=\(tabMac)", TimeMachineDestinationFix.releaseAwkProgram] + let input = Pipe() + let output = Pipe() + process.standardInput = input + process.standardOutput = output + try process.run() + input.fileHandleForWriting.write(Data(tab.utf8)) + input.fileHandleForWriting.closeFile() + let text = String(decoding: output.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + process.waitUntilExit() + XCTAssertEqual( + text, "# CloudMachine\n%%\n# manual\nother\t1\t52:55:55:00:00:01\t192.168.64.20\n") + } + + func testReleaseIsTheLastStepAfterTheTimeMachineChange() throws { + let shell = try XCTUnwrap( + TimeMachineDestinationFix.shellCommand( + address: "lima-cmsmb.local", passwordFile: "/tmp/p", uid: 501, mac: nil, + plan: .replace(id: "ID-1"), releaseMac: tabMac)) + let remove = try XCTUnwrap(shell.range(of: "removedestination")) + let release = try XCTUnwrap(shell.range(of: "tolower($3)==m")) + XCTAssertLessThan(remove.lowerBound, release.lowerBound) + } + + func testShellCommandWithReleaseMacHasNoReservationAndKeepsReserveOnlyAlone() throws { + let shell = try XCTUnwrap( + TimeMachineDestinationFix.shellCommand( + address: "lima-cmsmb.local", passwordFile: "/tmp/p", uid: 501, mac: nil, + plan: .reserveOnly, releaseMac: tabMac)) + XCTAssertTrue(shell.contains("tolower($3)==m")) + XCTAssertFalse(shell.contains("tmutil")) + } + + func testShellCommandReplaceAndReleaseInOneCommand() throws { + let shell = try XCTUnwrap( + TimeMachineDestinationFix.shellCommand( + address: "lima-cmsmb.local", passwordFile: "/tmp/p", uid: 501, mac: nil, + plan: .replace(id: "ID-1"), releaseMac: tabMac)) + XCTAssertTrue(shell.contains("removedestination ID-1")) + XCTAssertTrue(shell.contains("tolower($3)==m")) + } + + func testRunWithNameDoesNotNoOpWhenTheReservationIsStillThere() async throws { + let executed = ExecutedScript() + let password = FileManager.default.temporaryDirectory.appendingPathComponent( + "tm-pass-\(UUID().uuidString)") + try "secret".write(to: password, atomically: true, encoding: .utf8) + chmod(password.path, 0o600) + defer { try? FileManager.default.removeItem(at: password) } + let tabText = tab + let mac = tabMac + let result = await TimeMachineDestinationFix.run( + address: "lima-cmsmb.local", mac: nil, releaseMac: mac, passwordFile: password, + uid: getuid(), limitGB: nil, + execute: { _, arguments in + executed.script = arguments.joined(separator: " ") + executed.released = true + return ProcessResult(stdout: "", stderr: "", exitCode: 0) + }, + readDestinations: { [self] in [dest("lima-cmsmb.local")] }, + readBootptab: { executed.released ? "# CloudMachine\n%%\n" : tabText }, + readAlias: { nil }) + XCTAssertTrue(result.succeeded, result.message) + XCTAssertTrue(executed.script.contains("tolower($3)==m"), executed.script) + } + + func testRunWithNameIsANoOpWhenNothingToRelease() async throws { + let executed = ExecutedScript() + let password = FileManager.default.temporaryDirectory.appendingPathComponent( + "tm-pass-\(UUID().uuidString)") + try "secret".write(to: password, atomically: true, encoding: .utf8) + chmod(password.path, 0o600) + defer { try? FileManager.default.removeItem(at: password) } + let mac = tabMac + let result = await TimeMachineDestinationFix.run( + address: "lima-cmsmb.local", mac: nil, releaseMac: mac, passwordFile: password, + uid: getuid(), limitGB: nil, + execute: { _, _ in + executed.script = "ran" + return ProcessResult(stdout: "", stderr: "", exitCode: 0) + }, + readDestinations: { [self] in [dest("lima-cmsmb.local")] }, + readBootptab: { "# CloudMachine\n%%\n" }, readAlias: { nil }) + XCTAssertTrue(result.succeeded) + XCTAssertEqual(executed.script, "", "no dialog when nothing changes") + } + + private final class ExecutedScript: @unchecked Sendable { + var script = "" + var reads = 0 + var released = false + } + func testNoDestinationIsAdded() { XCTAssertEqual( TimeMachineDestinationFix.plan(