95 lines
6.1 KiB
Swift
95 lines
6.1 KiB
Swift
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
import Foundation
|
|
import CryptoKit
|
|
|
|
enum HardDiskFiles {
|
|
static let limit = 512 * 1024 * 1024
|
|
struct Image: Sendable { let data: Data; let readOnly: Bool; let digest: String }
|
|
enum Failure: LocalizedError {
|
|
case format, changed, readOnly, patch
|
|
var errorDescription: String? {
|
|
switch self {
|
|
case .format: return "Choose a raw VHD, OS9 or IMG file containing whole 256-byte sectors, from 256 bytes to 512 MiB. PC virtual-machine VHD containers are not supported."
|
|
case .changed: return "The hard disk changed outside this drive. Use Save As to keep your changes separately, or reinsert the image."
|
|
case .readOnly: return "The hard disk file is no longer writable. Restore write access and retry, or use Save As."
|
|
case .patch: return "Invalid hard disk save snapshot. Your in-memory changes are retained."
|
|
}
|
|
}
|
|
}
|
|
private struct Stamp: Equatable {
|
|
let size: UInt64, inode: UInt64
|
|
let modified: Date
|
|
}
|
|
private static func stamp(_ url: URL) throws -> Stamp {
|
|
let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
|
|
guard attributes[.type] as? FileAttributeType == .typeRegular,
|
|
let size = attributes[.size] as? NSNumber, let inode = attributes[.systemFileNumber] as? NSNumber,
|
|
let modified = attributes[.modificationDate] as? Date,
|
|
size.uint64Value > 0, size.uint64Value <= limit, size.uint64Value % 256 == 0 else { throw Failure.format }
|
|
return Stamp(size: size.uint64Value, inode: inode.uint64Value, modified: modified)
|
|
}
|
|
static func digest(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }
|
|
private static func digestFile(_ url: URL) throws -> String {
|
|
let file = try FileHandle(forReadingFrom: url); defer { try? file.close() }
|
|
var hash = SHA256(); var count = 0
|
|
while let data = try file.read(upToCount: 1024 * 1024), !data.isEmpty {
|
|
count += data.count; guard count <= limit else { throw Failure.format }; hash.update(data: data)
|
|
}
|
|
return hash.finalize().map { String(format: "%02x", $0) }.joined()
|
|
}
|
|
static func readImage(_ selected: URL) throws -> Image {
|
|
guard ["vhd", "os9", "img"].contains(selected.pathExtension.lowercased()) else { throw Failure.format }
|
|
let url = selected.resolvingSymlinksInPath(); let before = try stamp(url)
|
|
let file = try FileHandle(forReadingFrom: url); defer { try? file.close() }
|
|
var data = Data(); data.reserveCapacity(Int(before.size))
|
|
while let chunk = try file.read(upToCount: min(1024 * 1024, limit + 1 - data.count)), !chunk.isEmpty {
|
|
data.append(chunk); guard data.count <= limit else { throw Failure.format }
|
|
}
|
|
guard data.count == before.size, before == (try stamp(url)) else { throw Failure.changed }
|
|
// Microsoft VHD uses a footer; these extensions mean raw sector images here.
|
|
if data.count >= 512 && data.suffix(512).starts(with: Data("conectix".utf8)) { throw Failure.format }
|
|
return Image(data: data, readOnly: !FileManager.default.isWritableFile(atPath: url.path), digest: digest(data))
|
|
}
|
|
static func export(_ data: Data, to url: URL) throws -> String {
|
|
guard !data.isEmpty, data.count <= limit, data.count % 256 == 0 else { throw Failure.format }
|
|
try data.write(to: url, options: .atomic); return digest(data)
|
|
}
|
|
// Copy-on-write filesystem copies keep normal saves small on APFS. Hash the
|
|
// entire source to detect external edits, apply only captured dirty sectors,
|
|
// then atomically replace it. No host file I/O runs on the emulation queue.
|
|
static func saveAutomatically(_ patches: Data, length: Int, to url: URL, expected: String) throws -> String {
|
|
guard length > 0, length <= limit, length % 256 == 0, patches.count % 260 == 0 else { throw Failure.patch }
|
|
var coordinationError: NSError?, writeError: Error?, result: String?
|
|
NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &coordinationError) { target in
|
|
let temporary = target.deletingLastPathComponent().appendingPathComponent(".vcc-\(UUID().uuidString).tmp")
|
|
defer { try? FileManager.default.removeItem(at: temporary) }
|
|
do {
|
|
let before = try stamp(target)
|
|
guard length >= before.size else { throw Failure.patch }
|
|
guard FileManager.default.isWritableFile(atPath: target.path) else { throw Failure.readOnly }
|
|
try FileManager.default.copyItem(at: target, to: temporary)
|
|
guard try digestFile(temporary) == expected else { throw Failure.changed }
|
|
let file = try FileHandle(forWritingTo: temporary)
|
|
do {
|
|
try file.truncate(atOffset: UInt64(length))
|
|
for offset in stride(from: 0, to: patches.count, by: 260) {
|
|
let sector = (0..<4).reduce(UInt32(0)) { $0 | (UInt32(patches[offset + $1]) << (8 * $1)) }
|
|
let position = UInt64(sector) * 256
|
|
guard position + 256 <= length else { throw Failure.patch }
|
|
try file.seek(toOffset: position); try file.write(contentsOf: patches[(offset + 4)..<(offset + 260)])
|
|
}
|
|
try file.synchronize(); try file.close()
|
|
} catch { try? file.close(); throw error }
|
|
let next = try digestFile(temporary)
|
|
guard before == (try stamp(target)) else { throw Failure.changed }
|
|
guard FileManager.default.isWritableFile(atPath: target.path) else { throw Failure.readOnly }
|
|
_ = try FileManager.default.replaceItemAt(target, withItemAt: temporary)
|
|
result = next
|
|
} catch { writeError = error }
|
|
}
|
|
if let error = coordinationError { throw error }
|
|
if let error = writeError { throw error }
|
|
guard let result else { throw Failure.patch }; return result
|
|
}
|
|
}
|