// SPDX-License-Identifier: GPL-3.0-or-later import Foundation import CryptoKit /// A bounded interpretation of catalog data, not executable host instructions. /// Preparation reads only the installed Working tree and never changes the machine. struct SoftwareLibraryLaunchPlan: Sendable { enum Profile: String, Sendable { case diskBasic = "disk-basic", romCartridge = "rom-cartridge", cocoSDC = "coco-sdc" } enum CartridgeDevice: String, Sendable { case rom, orchestra90 } struct Candidate: Identifiable, Equatable, Sendable { let path: String let mediaType: String var id: String { path } var label: String { path } } enum Failure: LocalizedError { case invalidRecipe(String), unsafeMedia(String), missingMedia(String), unsupported(String), needsSelection([Candidate]) var errorDescription: String? { switch self { case .invalidRecipe(let detail): return "This edition’s setup needs attention. " + detail case .unsafeMedia(let detail): return "The installed media contains an unsafe file reference. " + detail case .missingMedia(let detail): return "An installed file is missing. " + detail case .unsupported(let detail): return detail case .needsSelection: return "Choose the installed file to mount first. The catalog does not identify a startup file." } } } let workingDirectory: URL private let canonicalWorkingDirectory: URL let releaseID: String let title: String let profile: Profile let use6309: Bool let ramKiB: Int let ramIndex: Int let videoOutput: Int? let controllerSlot: Int let cartridgeDevice: CartridgeDevice let floppyURLs: [Int: URL] let cassetteURL: URL? let cartridgeURL: URL? let sdcFolderURL: URL? let sdcInitialImages: [Int: String] /// Plain BASIC lines without CR; the machine controller waits for readiness between lines. let commands: [String] let manualInstructions: String let compatibilityNotes: [String] let automaticallyStarts: Bool let controls: LibraryJSON private let curatedStartup: SoftwareLibraryOwnedGame? var usesCuratedStartup: Bool { curatedStartup != nil } private static func supportsDisk(_ ext: String, profile: Profile) -> Bool { switch profile { case .diskBasic: return DiskFiles.extensions.contains(ext) case .cocoSDC: return ["dsk", "jvc", "os9"].contains(ext) case .romCartridge: return false } } /// Presentation only: downloaded files still undergo full preparation before /// a restart is offered. Missing or ambiguous startup media remains Set Up. static func hasAutomaticStartup(for release: SoftwareLibraryRelease) -> Bool { guard let name = release.setup.configuration["profile"].string, let profile = Profile(rawValue: name), case .array(let members) = release.setup.selectedMembers, !members.isEmpty, members.count <= 4 else { return false } guard (try? recommendedCartridgeDevice(release.setup.configuration, profile: profile)) != nil else { return false } var targets = Set() for member in members { guard let path = member["path"].string, validRelative(path), let target = member["target"].string, targets.insert(target).inserted else { return false } let ext = (path as NSString).pathExtension.lowercased() switch profile { case .romCartridge: guard members.count == 1, target == "cartridge", ["ccc", "rom"].contains(ext) else { return false } case .diskBasic: guard (target == "media" && ["cas", "wav"].contains(ext)) || (["disk0", "disk1", "disk2", "disk3"].contains(target) && Self.supportsDisk(ext, profile: profile)) else { return false } case .cocoSDC: guard ["disk0", "disk1"].contains(target), Self.supportsDisk(ext, profile: profile) else { return false } } } return profile == .romCartridge || decodeCommands(release.setup.command)?.contains(where: startsSoftware) == true } static func prepare(release: SoftwareLibraryRelease, receipt: SoftwareLibraryInstallationReceipt, selectedMember: String? = nil) throws -> Self { try release.validatePresentationMetadata() guard receipt.releaseID == release.id, receipt.packageSHA256 == release.packageSHA256, receipt.workingDirectory.isFileURL, receipt.workingDirectory.host.map({ $0.isEmpty || $0 == "localhost" }) != false, receipt.workingDirectory.query == nil, receipt.workingDirectory.fragment == nil, receipt.workingDirectory.lastPathComponent == "Working" else { throw Failure.invalidRecipe("The installation does not match this catalog edition.") } let config = release.setup.configuration guard let profileName = config["profile"].string, let profile = Profile(rawValue: profileName) else { throw Failure.unsupported("This edition needs a custom machine setup. Its installed files and loading notes remain available.") } let cartridgeDevice = try recommendedCartridgeDevice(config, profile: profile) for key in ["processor", "video"] where config[key] != .null { guard config[key].string != nil else { throw Failure.invalidRecipe("Invalid " + key + " recommendation.") } } for key in ["ram_kib", "controller_slot", "cartridge_slot"] where config[key] != .null { guard config[key].integer != nil else { throw Failure.invalidRecipe("Invalid " + key + " recommendation.") } } let cpu = config["processor"].string ?? "6809" guard cpu == "6809" || cpu == "6309" else { throw Failure.invalidRecipe("Unsupported processor recommendation.") } let ram = config["ram_kib"].integer ?? 2048 guard let ramIndex = [128, 512, 2048, 8192].firstIndex(of: ram) else { throw Failure.invalidRecipe("Unsupported memory recommendation.") } let slot = (profile == .romCartridge ? config["cartridge_slot"].integer : nil) ?? config["controller_slot"].integer ?? 4 guard (1...4).contains(slot) else { throw Failure.invalidRecipe("The startup slot must be 1 through 4.") } let video: Int? switch config["video"].string { case "rgb": video = 0 case "composite": video = 1 case nil: video = nil default: throw Failure.invalidRecipe("Unsupported video recommendation.") } let root = receipt.workingDirectory.standardizedFileURL try checkDirectory(root) let known = Set(receipt.relativeFiles) guard known.count == receipt.relativeFiles.count, receipt.relativeFiles.count <= 20_000, receipt.relativeFiles.allSatisfy(validRelative) else { throw Failure.unsafeMedia("The installation inventory is invalid.") } var selected: [(target: String, path: String)] = [] guard case .array(let members) = release.setup.selectedMembers else { throw Failure.invalidRecipe("The startup media list is invalid.") } for member in members { guard let path = member["path"].string, let target = member["target"].string, validRelative(path), known.contains(path) else { throw Failure.invalidRecipe("The startup file is not in this installation.") } selected.append((target, path)) } // A user chooses only when the recipe has no selected startup media. // Unlabelled .bin files are never guessed to be ROM cartridges. if selected.isEmpty { let candidates = receipt.relativeFiles.compactMap { path -> Candidate? in let ext = (path as NSString).pathExtension.lowercased() let type: String? switch release.mediaType { case "cartridge": type = ext == "ccc" ? "cartridge" : nil case "cassette": type = ["cas", "wav"].contains(ext) ? "cassette" : nil case "disk", "sdc": type = Self.supportsDisk(ext, profile: profile) ? "disk" : nil default: type = nil } return type.map { Candidate(path: path, mediaType: $0) } }.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending } let choice: Candidate if let selectedMember { guard let match = candidates.first(where: { $0.path == selectedMember }) else { throw Failure.invalidRecipe("Choose a compatible file from this installation.") } choice = match } else if candidates.count == 1 { choice = candidates[0] } else if !candidates.isEmpty { throw Failure.needsSelection(candidates) } else { throw Failure.unsupported("No supported startup media has been identified for this edition. Open its installed files and use the loading notes to configure it manually.") } selected = [(choice.mediaType == "cartridge" ? "cartridge" : choice.mediaType == "cassette" ? "media" : "disk0", choice.path)] } else if selectedMember != nil { throw Failure.invalidRecipe("This edition already identifies its startup media.") } guard selected.count <= 4, Set(selected.map(\.target)).count == selected.count else { throw Failure.invalidRecipe("Conflicting startup media assignments.") } var floppies: [Int: URL] = [:] var cassette: URL?, cartridge: URL? var selectedSDC: [Int: URL] = [:] for member in selected { let url = try file(member.path, root: root) let ext = url.pathExtension.lowercased() switch member.target { case "cartridge": guard profile == .romCartridge, ["ccc", "rom"].contains(ext) else { throw Failure.invalidRecipe("The selected file is not a supported ROM cartridge.") } cartridge = url case "media": guard profile == .diskBasic, ["cas", "wav"].contains(ext) else { throw Failure.invalidRecipe("The selected file is not a supported cassette.") } cassette = url case "disk0", "disk1", "disk2", "disk3": guard Self.supportsDisk(ext, profile: profile), let drive = Int(member.target.suffix(1)) else { throw Failure.invalidRecipe("Unsupported disk assignment.") } if profile == .cocoSDC { guard drive < 2 else { throw Failure.invalidRecipe("CoCo SDC has two drives.") } selectedSDC[drive] = url } else { floppies[drive] = url } default: throw Failure.invalidRecipe("Unknown media target: " + member.target) } } if profile == .romCartridge && cartridge == nil { throw Failure.invalidRecipe("A startup cartridge is required.") } var sdcFolder: URL?, sdcNames: [Int: String] = [:] if profile == .cocoSDC { guard let first = selectedSDC.keys.sorted().first.flatMap({ selectedSDC[$0] }) else { throw Failure.invalidRecipe("Select an SDC startup image.") } let folder: URL if let relative = config["sd_working_directory"].string { folder = try directory(relative, root: root) } else { folder = first.deletingLastPathComponent() } try inspectSDCTree(folder) for (drive, url) in selectedSDC { guard url.path.hasPrefix(folder.path + "/") else { throw Failure.invalidRecipe("The selected SDC image is outside its SD card folder.") } let name = String(url.path.dropFirst(folder.path.count + 1)) guard name.utf8.count <= 220, name.unicodeScalars.allSatisfy({ (32...126).contains($0.value) }), !name.contains("\"") else { throw Failure.unsupported("This SD card image needs manual selection because its name cannot be entered safely in SDC-DOS.") } sdcNames[drive] = name } sdcFolder = folder } let decoded = members.isEmpty ? nil : decodeCommands(release.setup.command) let canStart = cartridge != nil || (decoded?.contains(where: startsSoftware) == true) var commands = canStart ? (decoded ?? []) : [] // Mounting an image is separate from executing its program. Manual SDC // editions still get their chosen image mounted before guidance appears. if sdcFolder != nil { commands = sdcNames.keys.sorted().map { "DRIVE \($0),\"\(sdcNames[$0]!)\"" } + commands } var instructions = release.setup.instructions.trimmingCharacters(in: .whitespacesAndNewlines) if instructions.isEmpty { instructions = "The selected media is mounted. Follow its manual or directory listing to choose a program; no startup command has been established." } if !canStart, let command = release.setup.command, !command.isEmpty { instructions += "\n\nThe catalog’s loading sequence needs manual entry. Review it before typing: " + command.replacingOccurrences(of: "\\r", with: " → ") } return Self(workingDirectory: root, canonicalWorkingDirectory: root.resolvingSymlinksInPath(), releaseID: release.id, title: release.metadata["title"].string ?? release.name, profile: profile, use6309: cpu == "6309", ramKiB: ram, ramIndex: ramIndex, videoOutput: video, controllerSlot: slot, cartridgeDevice: cartridgeDevice, floppyURLs: floppies, cassetteURL: cassette, cartridgeURL: cartridge, sdcFolderURL: sdcFolder, sdcInitialImages: sdcNames, commands: commands, manualInstructions: instructions, compatibilityNotes: release.setup.compatibilityNotes + release.setup.configurationRequirements, automaticallyStarts: canStart, controls: release.setup.controls, curatedStartup: release.ownedGame.flatMap { $0.firstPlayColdDOS ? $0 : nil }) } private static func recommendedCartridgeDevice(_ config: LibraryJSON, profile: Profile) throws -> CartridgeDevice { let value = config["cartridge_device"] guard value != .null else { return .rom } guard let name = value.string, let device = CartridgeDevice(rawValue: name), profile == .romCartridge else { throw Failure.unsupported("This edition specifies a cartridge device that automatic setup does not support. Its installed files and loading notes remain available for manual configuration.") } return device } /// Recheck after a preview/dialog; a user or another process may have changed files. func validateMedia() throws { try Self.checkDirectory(workingDirectory) guard workingDirectory.resolvingSymlinksInPath() == canonicalWorkingDirectory else { throw Failure.unsafeMedia("The working folder changed after setup was prepared.") } if let curatedStartup { // Verify the published original; working disks may contain saves/scores. let original = try Self.file("Original/Files/" + curatedStartup.diskPath, root: workingDirectory.deletingLastPathComponent()) let bytes = try Data(contentsOf: original, options: .mappedIfSafe) guard bytes.count == curatedStartup.diskByteSize, SHA256.hash(data: bytes).map({ String(format: "%02x", $0) }).joined() == curatedStartup.diskSHA256 else { throw Failure.invalidRecipe("The original game disk no longer matches its verified startup recipe. Your working files are kept.") } } for url in Array(floppyURLs.values) + [cassetteURL, cartridgeURL].compactMap({ $0 }) { guard url.path.hasPrefix(workingDirectory.path + "/") else { throw Failure.unsafeMedia(url.lastPathComponent) } _ = try Self.file(String(url.path.dropFirst(workingDirectory.path.count + 1)), root: workingDirectory) } if let sdcFolderURL { guard sdcFolderURL == workingDirectory || sdcFolderURL.path.hasPrefix(workingDirectory.path + "/") else { throw Failure.unsafeMedia("The SD card folder left its installation.") } if sdcFolderURL != workingDirectory { _ = try Self.directory(String(sdcFolderURL.path.dropFirst(workingDirectory.path.count + 1)), root: workingDirectory) } try Self.inspectSDCTree(sdcFolderURL) for name in sdcInitialImages.values { _ = try Self.file(name, root: sdcFolderURL) } } } private static func validRelative(_ path: String) -> Bool { !path.isEmpty && path.utf8.count <= 4096 && !path.hasPrefix("/") && !path.contains("\\") && !path.contains(":") && !path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) && path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." } } private static func checkDirectory(_ url: URL) throws { guard let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]), values.isDirectory == true, values.isSymbolicLink != true else { throw Failure.unsafeMedia(url.lastPathComponent) } } private static func checked(_ relative: String, root: URL, isDirectory: Bool) throws -> URL { guard validRelative(relative) else { throw Failure.unsafeMedia(relative) } var url = root let components = relative.split(separator: "/") for (index, component) in components.enumerated() { url.appendPathComponent(String(component)) guard let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey, .isRegularFileKey]), values.isSymbolicLink != true else { throw Failure.missingMedia(relative) } if index < components.count - 1 || isDirectory { guard values.isDirectory == true else { throw Failure.unsafeMedia(relative) } } else { guard values.isRegularFile == true else { throw Failure.unsafeMedia(relative) } } } guard url.resolvingSymlinksInPath().path.hasPrefix(root.resolvingSymlinksInPath().path + "/") else { throw Failure.unsafeMedia(relative) } return url } private static func file(_ relative: String, root: URL) throws -> URL { try checked(relative, root: root, isDirectory: false) } private static func directory(_ relative: String, root: URL) throws -> URL { try checked(relative, root: root, isDirectory: true) } private static func inspectSDCTree(_ root: URL) throws { try checkDirectory(root) let keys: [URLResourceKey] = [.isSymbolicLinkKey, .isDirectoryKey, .isRegularFileKey] var scanFailed = false guard let entries = FileManager.default.enumerator(at: root, includingPropertiesForKeys: keys, errorHandler: { _, _ in scanFailed = true; return false }) else { throw Failure.unsafeMedia("The SD card folder cannot be read.") } var count = 0 for case let url as URL in entries { count += 1 guard count <= 20_000 else { throw Failure.unsafeMedia("The SD card folder has too many entries.") } let value = try url.resourceValues(forKeys: Set(keys)) guard value.isSymbolicLink != true, value.isDirectory == true || value.isRegularFile == true else { throw Failure.unsafeMedia("The SD card folder contains a link or special file.") } } guard !scanFailed else { throw Failure.unsafeMedia("Part of the SD card folder cannot be read.") } } /// Recognize the bounded BASIC loading vocabulary used by reviewed recipes. /// Unknown guest programs remain manual; nothing is passed to a host shell. static func decodeCommands(_ input: String?) -> [String]? { guard let input, input.utf8.count <= 4096 else { return nil } let normalized = input.replacingOccurrences(of: "\\r", with: "\r").replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n") guard normalized.unicodeScalars.allSatisfy({ $0.value == 10 || (32...126).contains($0.value) }) else { return nil } let lines = normalized.split(separator: "\n", omittingEmptySubsequences: true).map { String($0).trimmingCharacters(in: .whitespaces) } guard !lines.isEmpty, lines.count <= 16, lines.allSatisfy({ !$0.isEmpty && $0.utf8.count <= 255 && validLine($0) }) else { return nil } // Once software runs, later keystrokes could reach that program instead // of BASIC. Same-line loader chains remain one guest BASIC statement. guard !lines.dropLast().contains(where: startsSoftware) else { return nil } return lines } private static func statements(_ line: String) -> [String]? { var result: [String] = [], current = "", quoted = false for character in line { if character == "\"" { quoted.toggle() } if character == ":" && !quoted { result.append(current.trimmingCharacters(in: .whitespaces)); current = "" } else { current.append(character) } } guard !quoted else { return nil } result.append(current.trimmingCharacters(in: .whitespaces)); return result } private static func validLine(_ line: String) -> Bool { guard let parts = statements(line) else { return false } let number = "(?:[0-9]+|&H[0-9A-F]+)" let filename = "\\\"[^\\\"\\\\]{1,64}\\\"" let patterns = ["(?:CLOADM?|RUN)(?: *" + filename + ")?", "LOADM *" + filename, "LOAD *" + filename + " *, *R", "LOAD +CHR\\$\\(42\\) *, *R", "EXEC(?: *" + number + ")?", "DOS(?: +[0-9]+)?", "DIR(?: +[0-3])?", "PCLEAR *[0-9]+", "CLEAR *" + number + "(?: *, *" + number + ")?", "POKE *" + number + " *, *" + number, "NEW"] return parts.allSatisfy { part in patterns.contains { part.range(of: "^(?:" + $0 + ")$", options: [.regularExpression, .caseInsensitive]) != nil } } } private static func startsSoftware(_ line: String) -> Bool { guard let parts = statements(line.uppercased()) else { return false } return parts.contains { $0.hasPrefix("RUN") || $0.hasPrefix("EXEC") || $0.hasPrefix("DOS") || ($0.hasPrefix("LOAD") && $0.range(of: ", *R$", options: .regularExpression) != nil) } } }