Files
VCCPlusOSS/platforms/macos/App/CompanionLibraryAuthority.swift
T

214 lines
14 KiB
Swift

// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
import CryptoKit
import Darwin
#if !VCC_COMPANION_CLIENT
/// VCC Plus alone owns catalog loading, install receipts, downloads and caches.
/// The transport authenticates its caller before reaching this disk-only API.
@MainActor
final class CompanionLibraryAuthority {
private let model: SoftwareLibraryModel
init(model: SoftwareLibraryModel) { self.model = model }
func handle(_ request: CompanionLibraryRequest) async throws -> CompanionLibraryResponse {
await model.load()
// Another native window may already be loading this same model.
for _ in 0..<200 where model.loading {
try Task.checkCancellation()
try await Task.sleep(nanoseconds: 50_000_000)
}
guard model.catalog != nil || !model.personalEntries.isEmpty else { throw failure(model.error ?? "VCC Plus's Software Library is unavailable.") }
let available = model.combinedCatalog.companionDisks(includingOwnedTitles: request.ownedTitlesVersion == 1,
includingPersonalTitles: request.personalTitlesVersion == 1)
let privateDisks = Set(model.personalEntries.filter { entry in
entry.files.contains { $0.kind == "disk" && Self.diskMember($0.path) }
}.map(\.releaseID))
// The emulator accepts additional disk containers that this real-CoCo
// handoff cannot offer. Keep those entries in VCC Plus's own library.
let disks = SoftwareLibraryCatalog(titles: available.titles.compactMap { title in
let releases = title.releases.filter { !$0.isPersonal || privateDisks.contains($0.id) }
return releases.isEmpty ? nil : .init(id: title.id, name: title.name,
identityStatus: title.identityStatus, releases: releases)
}, metadata: available.metadata)
func release() throws -> SoftwareLibraryRelease {
guard let id = request.releaseID, let value = disks.releases.first(where: { $0.id == id }) else {
throw failure("Choose a disk edition from VCC Plus's catalog.")
}
return value
}
switch request.operation {
case .snapshot:
return .init(snapshot: snapshot(disks))
case .setFavorite:
guard let id = request.titleID, let enabled = request.enabled,
disks.titles.contains(where: { $0.id == id }) else { throw failure("This disk title is unavailable.") }
if model.state.isFavorite(id) != enabled { model.state.toggleFavorite(id) }
await model.state.flush()
if let message = model.state.saveError { throw failure(message) }
return .init(snapshot: snapshot(disks))
case .setPreferredRelease:
let selected = try release()
guard request.titleID == selected.titleID else { throw failure("This disk edition does not belong to the selected title.") }
model.state.selectRelease(selected.id, for: selected.titleID)
await model.state.flush()
if let message = model.state.saveError { throw failure(message) }
return .init(snapshot: snapshot(disks))
case .install:
let selected = try release()
if selected.isPersonal { return try await installStatus(selected, catalog: disks) }
guard model.installingReleaseID == nil || model.installingReleaseID == selected.id else {
throw failure("VCC Plus is already installing another title. Let it finish or cancel it there.")
}
guard !model.launchBusy, !model.hasPendingLaunch else { throw failure("Finish the current VCC Plus library action first.") }
if model.installingReleaseID == nil && model.state.installedReleases[selected.id] == nil { model.install(selected) }
return try await installStatus(selected, catalog: disks)
case .installStatus:
return try await installStatus(release(), catalog: disks)
case .cancelInstallation:
let selected = try release()
if model.installingReleaseID == selected.id { model.cancelInstallation() }
return .init(snapshot: snapshot(disks), isInstalling: model.installingReleaseID == selected.id)
case .removeInstallation:
let selected = try release()
guard !selected.isPersonal else { throw failure("Manage or remove this private entry in VCC Plus's Personal Library. DriveWire disk copies are separate from its retained files.") }
await model.removeInstallation(selected.id)
if let message = model.installationErrors[selected.id] { throw failure(message) }
return .init(snapshot: snapshot(disks))
case .diskMembers, .exportDisk:
let selected = try release()
let receipt = try await installedReceipt(selected)
let candidates = receipt.relativeFiles.filter(Self.diskMember).map { CompanionLibraryDisk(path: $0, mediaType: "disk") }
.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending }
guard !candidates.isEmpty else { throw failure("This installation contains no supported floppy disk images.") }
if request.operation == .diskMembers { return .init(snapshot: snapshot(disks), receipt: receipt, disks: candidates) }
guard let member = request.memberPath, candidates.contains(where: { $0.path == member }) else {
throw failure("Choose a disk file from this installation.")
}
let destination = model.state.directory.appendingPathComponent("CompanionDisks", isDirectory: true)
let exported = try await Task.detached(priority: .userInitiated) {
try Self.exportDisk(receipt: receipt, member: member, destination: destination)
}.value
return .init(exportedDiskURL: exported)
case .thumbnail, .manual:
guard let id = request.assetID,
let asset = disks.releases.lazy.flatMap({ release in
release.assets + (release.ownedGame == nil ? [] : [release.primaryManualAsset].compactMap { $0 })
}).first(where: { $0.id == id }) else {
throw failure("This supporting asset is unavailable for the disk library.")
}
if request.operation == .thumbnail {
let data = try await SoftwareLibraryArtworkCache.shared.thumbnail(for: asset, directory: model.artworkDirectory)
return .init(assetData: data)
}
guard asset.isManual else { throw failure("Choose a manual or instructions asset.") }
if asset.matchStatus == "personal", let local = asset.manualURL, local.isFileURL {
try await Task.detached(priority: .userInitiated) {
try SoftwareLibraryLocalAsset.validate(asset, url: local,
maximumBytes: local.pathExtension.lowercased() == "txt" ? 1024 * 1024 : 512 * 1024 * 1024)
}.value
return .init(assetFileURL: local)
}
let local = try await SoftwareLibraryManualCache.shared.localCopy(for: asset,
directory: model.state.directory.appendingPathComponent("Manuals", isDirectory: true))
return .init(assetFileURL: local)
}
}
private func failure(_ message: String) -> CompanionLibraryFailure { .init(message: message) }
private func snapshot(_ catalog: SoftwareLibraryCatalog) -> CompanionLibrarySnapshot {
let titleIDs = Set(catalog.titles.map(\.id)), releaseIDs = Set(catalog.releases.map(\.id))
let personal = model.personalEntries.filter { releaseIDs.contains($0.releaseID) }.map {
$0.receipt(in: model.personalDirectory($0))
}.map { SoftwareLibraryState.Installation(releaseID: $0.releaseID, packageSHA256: $0.packageSHA256,
installedAt: $0.installedAt, workingDirectory: $0.workingDirectory) }
return .init(catalog: catalog,
favorites: model.state.favoriteTitleIDs.intersection(titleIDs),
preferredReleaseIDs: model.state.preferredReleaseIDs.filter { titleIDs.contains($0.key) && releaseIDs.contains($0.value) },
installations: model.state.installedReleases.values.filter { releaseIDs.contains($0.releaseID) && !$0.releaseID.hasPrefix("personal:") } + personal)
}
private func installedReceipt(_ release: SoftwareLibraryRelease) async throws -> SoftwareLibraryInstallationReceipt {
if release.isPersonal {
// Reload the store to reject entries hidden since the catalog snapshot.
let entries = try await model.personalStore.entries()
guard let entry = entries.first(where: {
$0.releaseID == release.id && $0.packageSHA256 == release.packageSHA256
}) else { throw failure("This private disk entry is no longer available. Open Personal Library in VCC Plus.") }
let directory = model.personalDirectory(entry)
for location in [directory.deletingLastPathComponent(), directory, directory.appendingPathComponent("Working")] {
let values = try location.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
guard values.isDirectory == true, values.isSymbolicLink != true else { throw failure("The private disk location is not a safe directory. Its retained files were preserved.") }
}
return entry.receipt(in: directory)
}
let receipts = try await model.installer.recoverInstallations()
guard let receipt = receipts.first(where: { $0.releaseID == release.id && $0.packageSHA256 == release.packageSHA256 }) else {
throw failure("Install this disk edition in VCC Plus first.")
}
return receipt
}
private func installStatus(_ release: SoftwareLibraryRelease, catalog: SoftwareLibraryCatalog) async throws -> CompanionLibraryResponse {
if release.isPersonal {
let receipt = try await installedReceipt(release)
return .init(snapshot: snapshot(catalog), receipt: receipt, isInstalling: false)
}
if let message = model.installationErrors[release.id] { throw failure(message) }
let active = model.installingReleaseID == release.id
return .init(snapshot: snapshot(catalog), progress: active ? model.installProgress : nil,
isInstalling: active)
}
nonisolated static func diskMember(_ path: String) -> Bool {
!path.isEmpty && !path.hasPrefix("/") && !path.contains("\\") && !path.contains(":")
&& !path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains)
&& path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." }
&& ["dsk", "os9"].contains((path as NSString).pathExtension.lowercased())
}
/// Every handoff gets a new writable copy. Verified originals and the
/// emulator's working image are never handed to the real CoCo for writing.
nonisolated private static func exportDisk(receipt: SoftwareLibraryInstallationReceipt, member: String, destination: URL) throws -> URL {
guard diskMember(member), receipt.relativeFiles.contains(member) else { throw CompanionLibraryFailure(message: "Invalid disk member.") }
let root = receipt.workingDirectory.standardizedFileURL
guard root.isFileURL else { throw CompanionLibraryFailure(message: "Invalid installation location.") }
// Resolve members relative to opened directories so a swapped symlink
// cannot redirect an intermediate path outside the working tree.
var directory = open(root.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
guard directory >= 0 else { throw CompanionLibraryFailure(message: "The disk working directory could not be read safely.") }
defer { close(directory) }
let components = member.split(separator: "/").map(String.init)
for component in components.dropLast() {
let next = openat(directory, component, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC)
guard next >= 0 else { throw CompanionLibraryFailure(message: "The disk path contains an unavailable directory or symbolic link.") }
close(directory); directory = next
}
let descriptor = openat(directory, components.last!, O_RDONLY | O_NOFOLLOW | O_CLOEXEC)
guard descriptor >= 0 else { throw CompanionLibraryFailure(message: "The installed disk could not be read.") }
let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true)
defer { try? handle.close() }
var info = stat()
guard fstat(descriptor, &info) == 0, (info.st_mode & S_IFMT) == S_IFREG,
info.st_size > 0, info.st_size <= 16 * 1024 * 1024 else {
throw CompanionLibraryFailure(message: "Choose a floppy image within the 16 MiB limit.")
}
let data = try handle.read(upToCount: 16 * 1024 * 1024 + 1) ?? Data()
var after = stat()
guard data.count == Int(info.st_size), fstat(descriptor, &after) == 0,
info.st_size == after.st_size, info.st_mtimespec.tv_sec == after.st_mtimespec.tv_sec,
info.st_mtimespec.tv_nsec == after.st_mtimespec.tv_nsec,
info.st_ctimespec.tv_sec == after.st_ctimespec.tv_sec,
info.st_ctimespec.tv_nsec == after.st_ctimespec.tv_nsec else { throw CompanionLibraryFailure(message: "The installed disk changed while being read.") }
try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
let destinationValues = try destination.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey])
guard destinationValues.isDirectory == true, destinationValues.isSymbolicLink != true else {
throw CompanionLibraryFailure(message: "The DriveWire disk-copy location is not a safe directory.")
}
let folder = destination.appendingPathComponent(UUID().uuidString, isDirectory: true)
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700])
do {
let copy = folder.appendingPathComponent(components.last!)
try data.write(to: copy, options: .atomic)
return copy
} catch { try? FileManager.default.removeItem(at: folder); throw error }
}
}
#endif