Преглед на файлове

Split the disk image class and fixed four bugs in it

- There are separate classes for the table of releases, the identification of a disk, the extraction of its files and of its videos, and the file lookup.
- The ISO9660 reader that the identification and the extraction each had is one class.
- An error while extracting a file was only logged. The extraction fails now.
- Names in an image that lead outside of the destination folder are rejected.
- A damaged image could make the ISO9660 reader recurse forever or allocate any amount of memory.
- The French releases warned about the Spanish language, and a space was missing in the message about the PlayStation releases.
- Added tests for the releases, the paths, the file lookup and the ISO9660 reader.
Iñigo Valentin преди 4 дни
родител
ревизия
8e5039c92f

+ 6 - 0
src/installer/formats/CMakeLists.txt

@@ -4,6 +4,12 @@ vgears_sources(
     BattleSceneFile.cpp
     BinGZipFile.cpp
     DaFile.cpp
+    DiskExtractor.cpp
+    DiskIdentifier.cpp
     DiskImage.cpp
+    DiskPaths.cpp
+    DiskReleases.cpp
+    DiskVideoExtractor.cpp
+    Iso9660Reader.cpp
     TexFile.cpp
 )

+ 191 - 0
src/installer/formats/DiskExtractor.cpp

@@ -0,0 +1,191 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <algorithm>
+#include <fstream>
+#include <iostream>
+#include <memory>
+#include <archive.h>
+#include <archive_entry.h>
+#include <QtCore/qdir.h>
+#include <QtCore/qfileinfo.h>
+#include "DiskExtractor.h"
+#include "DiskIdentifier.h"
+#include "Iso9660Reader.h"
+
+namespace{
+
+    /**
+     * Pointer to a libarchive reader or writer, freed when it goes out of scope.
+     */
+    using ArchivePointer = std::unique_ptr<struct archive, int(*)(struct archive*)>;
+
+    /**
+     * Copies the contents of the current file of an image to the disk.
+     *
+     * @param[in] image The image.
+     * @param[in] disk The disk writer.
+     * @param[in] report Called after each block.
+     * @param[out] error_message Why the file could not be copied.
+     * @return True if the file was copied.
+     */
+    bool CopyData(
+      struct archive* image, struct archive* disk, const std::function<void()>& report,
+      std::string& error_message
+    ){
+        const void* buffer;
+        size_t size;
+        la_int64_t offset;
+        while (true){
+            const int read = archive_read_data_block(image, &buffer, &size, &offset);
+            if (read == ARCHIVE_EOF) return true;
+            if (read < ARCHIVE_WARN){
+                error_message = std::string("Error reading data block: ") + archive_error_string(image);
+                return false;
+            }
+            if (archive_write_data_block(disk, buffer, size, offset) < ARCHIVE_WARN){
+                error_message = std::string("Error writing data block: ") + archive_error_string(disk);
+                return false;
+            }
+            report();
+        }
+    }
+}
+
+DiskExtractor::DiskExtractor(
+  const std::string& image_path, const std::function<void(float)>& progress
+):
+  image_path_(image_path), progress_(progress),
+  image_size_(QFileInfo(QString::fromStdString(image_path)).size()), last_percent_(-1)
+{}
+
+bool DiskExtractor::Extract(const std::string& output_dir, std::string& error_message){
+    Report(0);
+    if (!QDir().mkpath(QString::fromStdString(output_dir))){
+        error_message = "Failed to create extraction directory: " + output_dir;
+        return false;
+    }
+    bool has_entries = false;
+    if (!ExtractArchive(output_dir, has_entries, error_message)) return false;
+    if (!has_entries && !ExtractFolders(output_dir, error_message)) return false;
+    if (progress_) progress_(100);
+    return true;
+}
+
+bool DiskExtractor::ExtractArchive(
+  const std::string& output_dir, bool& has_entries, std::string& error_message
+){
+    ArchivePointer image(archive_read_new(), archive_read_free);
+    archive_read_support_format_all(image.get());
+    archive_read_support_filter_all(image.get());
+    ArchivePointer disk(archive_write_disk_new(), archive_write_free);
+    archive_write_disk_set_options(
+      disk.get(),
+      ARCHIVE_EXTRACT_TIME | ARCHIVE_EXTRACT_PERM | ARCHIVE_EXTRACT_ACL | ARCHIVE_EXTRACT_FFLAGS
+      | ARCHIVE_EXTRACT_SECURE_NODOTDOT
+    );
+    archive_write_disk_set_standard_lookup(disk.get());
+    if (archive_read_open_filename(image.get(), image_path_.c_str(), 10240) != ARCHIVE_OK){
+        error_message = std::string("Could not open image file: ") + archive_error_string(image.get());
+        return false;
+    }
+    const auto report = [this, &image](){Report(archive_filter_bytes(image.get(), -1));};
+    struct archive_entry* entry;
+    int status;
+    while (
+      (status = archive_read_next_header(image.get(), &entry)) == ARCHIVE_OK || status == ARCHIVE_WARN
+    ){
+        has_entries = true;
+        if (status == ARCHIVE_WARN){
+            std::cerr << "archive_read_next_header warning during extraction: "
+              << archive_error_string(image.get()) << std::endl;
+        }
+        const char* name = archive_entry_pathname(entry);
+        if (name == nullptr){
+            std::cerr << "Skipping entry without a pathname" << std::endl;
+            continue;
+        }
+        const std::string path = output_dir + "/" + name;
+        archive_entry_set_pathname(entry, path.c_str());
+        const int written = archive_write_header(disk.get(), entry);
+        if (written < ARCHIVE_OK)
+            std::cerr << "Warning (Header): " << archive_error_string(disk.get()) << std::endl;
+        if (written < ARCHIVE_WARN){
+            error_message = "Could not create " + path;
+            return false;
+        }
+        if (
+          archive_entry_size(entry) > 0
+          && !CopyData(image.get(), disk.get(), report, error_message)
+        ) return false;
+        archive_write_finish_entry(disk.get());
+    }
+    if (status != ARCHIVE_EOF){
+        error_message = std::string("Error reading the image: ") + archive_error_string(image.get());
+        return false;
+    }
+    return true;
+}
+
+bool DiskExtractor::ExtractFolders(const std::string& output_dir, std::string& error_message){
+    Iso9660Reader reader(image_path_);
+    if (!reader.IsValid()){
+        error_message = "Direct ISO9660 fallback failed: invalid primary volume descriptor.";
+        return false;
+    }
+    bool ok = true;
+    const auto extract = [&](const Iso9660Reader::Entry& entry){
+        const QString path = QString::fromStdString(output_dir + "/" + entry.path);
+        if (entry.directory){
+            ok = QDir().mkpath(path);
+            return ok;
+        }
+        if (!QDir().mkpath(QFileInfo(path).absolutePath())){
+            ok = false;
+            return false;
+        }
+        std::ofstream file(path.toStdString(), std::ios::binary);
+        ok = file && reader.Read(entry, [&](const char* data, size_t size){
+            file.write(data, static_cast<std::streamsize>(size));
+            Report(reader.Position());
+            return file.good();
+        });
+        file.close();
+        ok = ok && !file.fail();
+        return ok;
+    };
+    // Only the version suffix and the trailing dots are removed: the files keep their case.
+    const Iso9660Reader::Result result = reader.Walk(
+      [](const std::string& name){
+          std::string normalized = name;
+          std::replace(normalized.begin(), normalized.end(), '\\', '/');
+          return DiskIdentifier::RemoveVersion(normalized);
+      },
+      extract
+    );
+    if (!ok || result == Iso9660Reader::Result::READ_ERROR){
+        error_message = "Direct ISO9660 fallback failed while extracting files.";
+        return false;
+    }
+    return true;
+}
+
+void DiskExtractor::Report(const int64_t position){
+    if (!progress_ || image_size_ <= 0) return;
+    const int percent = static_cast<int>(std::min<int64_t>(100, 100 * position / image_size_));
+    if (percent <= last_percent_) return;
+    last_percent_ = percent;
+    progress_(static_cast<float>(percent));
+}

+ 95 - 0
src/installer/formats/DiskExtractor.h

@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <functional>
+#include <string>
+
+/**
+ * Copies all the files of a disk image to a folder.
+ */
+class DiskExtractor{
+
+    public:
+
+        /**
+         * Constructor.
+         *
+         * @param[in] image_path Path of the image.
+         * @param[in] progress Called with the percentage of the image that has been read, each
+         * time it goes up by one. It can be empty.
+         */
+        DiskExtractor(const std::string& image_path, const std::function<void(float)>& progress);
+
+        /**
+         * Extracts the image.
+         *
+         * @param[in] output_dir Folder to extract to. It is created if needed.
+         * @param[out] error_message Why the image could not be extracted.
+         * @return True if all the files were extracted.
+         */
+        bool Extract(const std::string& output_dir, std::string& error_message);
+
+    private:
+
+        /**
+         * Extracts the image with libarchive.
+         *
+         * @param[in] output_dir Folder to extract to.
+         * @param[out] has_entries False if libarchive lists no files in the image.
+         * @param[out] error_message Why the image could not be extracted.
+         * @return True if all the files were extracted.
+         */
+        bool ExtractArchive(const std::string& output_dir, bool& has_entries, std::string& error_message);
+
+        /**
+         * Extracts the image reading the ISO9660 folders directly.
+         *
+         * @param[in] output_dir Folder to extract to.
+         * @param[out] error_message Why the image could not be extracted.
+         * @return True if all the files were extracted.
+         */
+        bool ExtractFolders(const std::string& output_dir, std::string& error_message);
+
+        /**
+         * Reports the progress, if it went up.
+         *
+         * The reader can go back to read some parts again, so the progress only goes up.
+         *
+         * @param[in] position How much of the image has been read.
+         */
+        void Report(const int64_t position);
+
+        /**
+         * Path of the image.
+         */
+        std::string image_path_;
+
+        /**
+         * Function to report the progress.
+         */
+        std::function<void(float)> progress_;
+
+        /**
+         * Size of the image.
+         */
+        int64_t image_size_;
+
+        /**
+         * Last percentage reported.
+         */
+        int last_percent_;
+};

+ 140 - 0
src/installer/formats/DiskIdentifier.cpp

@@ -0,0 +1,140 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <algorithm>
+#include <cctype>
+#include <iostream>
+#include <memory>
+#include <regex>
+#include <vector>
+#include <archive.h>
+#include <archive_entry.h>
+#include "DiskIdentifier.h"
+#include "Iso9660Reader.h"
+
+namespace{
+
+    /**
+     * Converts a string to upper case.
+     */
+    std::string ToUpper(std::string value){
+        std::transform(value.begin(), value.end(), value.begin(), [](unsigned char c){
+            return std::toupper(c);
+        });
+        return value;
+    }
+
+    /**
+     * Reads the game ID from the entry of the SYSTEM.CNF file.
+     */
+    std::string ReadGameId(struct archive* image, struct archive_entry* entry){
+        const size_t size = archive_entry_size(entry);
+        if (size == 0) return "";
+        std::vector<char> contents(size);
+        const la_ssize_t read = archive_read_data(image, contents.data(), size);
+        if (read <= 0) return "";
+        return DiskIdentifier::FindGameId(std::string(contents.begin(), contents.begin() + read));
+    }
+
+    /**
+     * Looks for the files that identify the PC disks, reading the ISO9660 folders directly.
+     */
+    const DiskReleases::Release* FindInFolders(const std::string& path){
+        const DiskReleases::Release* release = nullptr;
+        Iso9660Reader reader(path);
+        reader.Walk(DiskIdentifier::NormalizePath, [&release](const Iso9660Reader::Entry& entry){
+            release = DiskReleases::FindPcRelease(entry.path);
+            return release == nullptr;
+        });
+        return release;
+    }
+}
+
+namespace DiskIdentifier{
+
+    Identification Identify(const std::string& path){
+        Identification result;
+        std::unique_ptr<struct archive, int(*)(struct archive*)> image(
+          archive_read_new(), archive_read_free
+        );
+        archive_read_support_format_all(image.get());
+        archive_read_support_filter_all(image.get());
+        if (archive_read_open_filename(image.get(), path.c_str(), 2048) != ARCHIVE_OK){
+            const char* error = archive_error_string(image.get());
+            result.open_error = error ? error : "Unknown archive error";
+            return result;
+        }
+        struct archive_entry* entry;
+        bool has_entries = false;
+        int status;
+        while ((status = archive_read_next_header(image.get(), &entry)) != ARCHIVE_EOF){
+            if (status != ARCHIVE_OK && status != ARCHIVE_WARN){
+                std::cerr << "archive_read_next_header error: " << archive_error_string(image.get())
+                  << " (code=" << status << ")" << std::endl;
+                break;
+            }
+            if (status == ARCHIVE_WARN){
+                std::cerr << "archive_read_next_header warning: "
+                  << archive_error_string(image.get()) << std::endl;
+            }
+            has_entries = true;
+            const std::string name = archive_entry_pathname(entry);
+            // Look for known files of the PC disks.
+            result.release = DiskReleases::FindPcRelease(NormalizePath(name));
+            if (result.release != nullptr) return result;
+            // PlayStation disks have their ID in SYSTEM.CNF.
+            const std::string upper = ToUpper(name);
+            if (
+              upper == "SYSTEM.CNF" || upper == "/SYSTEM.CNF"
+              || upper.find("SYSTEM.CNF;") != std::string::npos
+            ){
+                result.game_id = ReadGameId(image.get(), entry);
+                result.release = DiskReleases::FindPlayStationRelease(result.game_id);
+                return result;
+            }
+        }
+        if (!has_entries && status == ARCHIVE_EOF) result.release = FindInFolders(path);
+        return result;
+    }
+
+    std::string NormalizePath(std::string path){
+        std::replace(path.begin(), path.end(), '\\', '/');
+        while (!path.empty() && std::string("\n\r \t").find(path.back()) != std::string::npos)
+            path.pop_back();
+        while (!path.empty() && (path.front() == ' ' || path.front() == '\t')) path.erase(path.begin());
+        path = RemoveVersion(path);
+        if (!path.empty() && path.front() == '/') path.erase(path.begin());
+        return ToUpper(path);
+    }
+
+    std::string RemoveVersion(std::string name){
+        const size_t separator = name.find(';');
+        if (
+          separator != std::string::npos
+          && std::all_of(name.begin() + separator + 1, name.end(), [](unsigned char c){
+              return std::isdigit(c) != 0;
+          })
+        ) name.erase(separator);
+        while (!name.empty() && name.back() == '.') name.pop_back();
+        return name;
+    }
+
+    std::string FindGameId(const std::string& system_cnf){
+        static const std::regex code(R"(([A-Z]{4})_(\d{3})\.(\d{2}))");
+        std::smatch match;
+        if (!std::regex_search(system_cnf, match, code)) return "";
+        return match[1].str() + "-" + match[2].str() + match[3].str();
+    }
+}

+ 80 - 0
src/installer/formats/DiskIdentifier.h

@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <string>
+#include "DiskReleases.h"
+
+/**
+ * Finds out which disk of the game an image is.
+ */
+namespace DiskIdentifier{
+
+    /**
+     * What was found in an image.
+     */
+    struct Identification{
+
+        /**
+         * The disk, or null if it's not a known one.
+         */
+        const DiskReleases::Release* release = nullptr;
+
+        /**
+         * The game ID of a PlayStation image. Empty for the others.
+         */
+        std::string game_id;
+
+        /**
+         * Why the image could not be opened. Empty if it was.
+         */
+        std::string open_error;
+    };
+
+    /**
+     * Identifies an image.
+     *
+     * @param[in] path Path of the image.
+     * @return What was found.
+     */
+    Identification Identify(const std::string& path);
+
+    /**
+     * Normalizes a path of a disk image: slashes, no surrounding spaces, no version suffix, no
+     * trailing dots, upper case.
+     *
+     * @param[in] path The path.
+     * @return The normalized path.
+     */
+    std::string NormalizePath(std::string path);
+
+    /**
+     * Removes the version suffix of an ISO9660 name (";1") and the trailing dots of the short
+     * names.
+     *
+     * @param[in] name The name.
+     * @return The name without them.
+     */
+    std::string RemoveVersion(std::string name);
+
+    /**
+     * Finds the game ID of a PlayStation disk.
+     *
+     * @param[in] system_cnf Contents of the SYSTEM.CNF file of the disk.
+     * @return The ID, like "SCUS-94163", or an empty string if there is none.
+     */
+    std::string FindGameId(const std::string& system_cnf);
+}

Файловите разлики са ограничени, защото са твърде много
+ 53 - 961
src/installer/formats/DiskImage.cpp


+ 16 - 1
src/installer/formats/DiskImage.h

@@ -18,8 +18,15 @@
 #include <memory>
 #include <string>
 
+namespace DiskReleases{
+    struct Release;
+}
+
 /**
- * Information about a Final Fantasy VII disk image.
+ * An image of a disk of the game.
+ *
+ * The work is done by {@see DiskIdentifier}, {@see DiskExtractor}, {@see DiskVideoExtractor} and
+ * {@see DiskPaths}.
  */
 struct DiskImage{
 
@@ -211,6 +218,14 @@ struct DiskImage{
 
     private:
 
+        /**
+         * Sets the data of the disk that was identified.
+         *
+         * @param[in] release The disk.
+         * @param[in] image_path Path of the image.
+         */
+        void SetRelease(const DiskReleases::Release& release, const std::string& image_path);
+
         /**
          * The path to the image file.
          */

+ 111 - 0
src/installer/formats/DiskPaths.cpp

@@ -0,0 +1,111 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <algorithm>
+#include <QtCore/qdir.h>
+#include <QtCore/qdiriterator.h>
+#include <QtCore/qfileinfo.h>
+#include "DiskPaths.h"
+
+namespace{
+
+    /**
+     * Normalizes a part of a path: upper case, without version suffix, trailing dots or spaces.
+     */
+    QString NormalizeSegment(QString segment){
+        segment = segment.trimmed();
+        while (!segment.isEmpty() && (segment.endsWith('.') || segment.endsWith(' '))) segment.chop(1);
+        const int separator = segment.indexOf(';');
+        if (separator >= 0){
+            const bool version = std::all_of(
+              segment.begin() + separator + 1, segment.end(), [](QChar c){return c.isDigit();}
+            );
+            if (version) segment = segment.left(separator);
+        }
+        return segment.toUpper();
+    }
+
+    /**
+     * Splits a path into its normalized parts.
+     */
+    QStringList SplitSegments(QString path){
+        path.replace('\\', '/');
+        while (path.startsWith('/')) path.remove(0, 1);
+        QStringList segments;
+        for (const QString& part : QDir::cleanPath(path).split('/', Qt::SkipEmptyParts)){
+            if (part != ".") segments.push_back(NormalizeSegment(part));
+        }
+        return segments;
+    }
+
+    /**
+     * Splits a name into its base name and its extension.
+     */
+    QPair<QString, QString> SplitExtension(const QString& name){
+        const int dot = name.lastIndexOf('.');
+        if (dot <= 0 || dot == name.size() - 1) return qMakePair(name, QString());
+        return qMakePair(name.left(dot), name.mid(dot + 1));
+    }
+
+    /**
+     * Checks if two names can be of the same file: the same extension, and base names that begin
+     * the same way, without the number of the short names.
+     */
+    bool SegmentMatches(const QString& requested, const QString& actual){
+        if (requested == actual) return true;
+        const auto wanted = SplitExtension(requested);
+        const auto found = SplitExtension(actual);
+        if (wanted.second != found.second) return false;
+        const QString wanted_base = wanted.first.section('~', 0, 0);
+        const QString found_base = found.first.section('~', 0, 0);
+        if (wanted_base.isEmpty() || found_base.isEmpty()) return false;
+        return wanted_base.startsWith(found_base) || found_base.startsWith(wanted_base);
+    }
+}
+
+namespace DiskPaths{
+
+    std::unique_ptr<std::string> Find(const std::string& base_dir, const std::string& path){
+        const QString base = QDir::cleanPath(QString::fromStdString(base_dir).replace('\\', '/'));
+        const QString requested_path = QString::fromStdString(path);
+        const QFileInfo direct(QDir(base).filePath(requested_path));
+        if (direct.exists() && direct.isFile())
+            return std::make_unique<std::string>(direct.absoluteFilePath().toStdString());
+        const QStringList requested = SplitSegments(requested_path);
+        if (requested.isEmpty()) return nullptr;
+        std::unique_ptr<std::string> similar;
+        QDirIterator it(base, QDir::Files, QDirIterator::Subdirectories);
+        while (it.hasNext()){
+            const QString file = it.next();
+            const QStringList actual = SplitSegments(QDir(base).relativeFilePath(file));
+            if (actual.size() < requested.size()) continue;
+            // The last parts of the path of the file have to match.
+            const int offset = actual.size() - requested.size();
+            bool matches = true;
+            bool exact = true;
+            for (int i = 0; i < requested.size() && matches; ++ i){
+                matches = SegmentMatches(requested[i], actual[offset + i]);
+                if (requested[i] != actual[offset + i]) exact = false;
+            }
+            if (!matches) continue;
+            const std::string found = QFileInfo(file).absoluteFilePath().toStdString();
+            // A file with the same name wins. The names that only begin the same way (like
+            // FF7INST.EXE for ff7.exe) are used only if there is no other one.
+            if (exact) return std::make_unique<std::string>(found);
+            if (!similar) similar = std::make_unique<std::string>(found);
+        }
+        return similar;
+    }
+}

+ 37 - 0
src/installer/formats/DiskPaths.h

@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <memory>
+#include <string>
+
+/**
+ * Finds files of an extracted disk, whose names depend on how the image stored them.
+ */
+namespace DiskPaths{
+
+    /**
+     * Finds a file.
+     *
+     * The case, the ISO9660 version suffixes, the trailing dots and the short names are ignored.
+     * The path may be found in a subfolder of the base folder.
+     *
+     * @param[in] base_dir Folder to search in.
+     * @param[in] path Path of the file, relative to the folder.
+     * @return The absolute path of the file, or null if there is none.
+     */
+    std::unique_ptr<std::string> Find(const std::string& base_dir, const std::string& path);
+}

+ 148 - 0
src/installer/formats/DiskReleases.cpp

@@ -0,0 +1,148 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <algorithm>
+#include <iterator>
+#include "DiskReleases.h"
+
+namespace{
+
+    /**
+     * The PC disks. The game disks only have the videos; the rest of the game is installed from
+     * the install disk.
+     */
+    const DiskReleases::Release PC_RELEASES[] = {
+      {"FF7CONFIG.EXE", "Final Fantasy VII (PC, 1998, USA) Install Disk",
+        DiskImage::PLATFORM_PC, DiskImage::REGION_NORTH_AMERICA, DiskImage::LANGUAGE_ENGLISH,
+        DiskImage::DISK_INSTALL, true, ""},
+      {"FF7CONFI.EXE", "Final Fantasy VII (PC, 1998, USA) Install Disk",
+        DiskImage::PLATFORM_PC, DiskImage::REGION_NORTH_AMERICA, DiskImage::LANGUAGE_ENGLISH,
+        DiskImage::DISK_INSTALL, true, ""},
+      {"FF7CON~1.EXE", "Final Fantasy VII (PC, 1998, USA) Install Disk",
+        DiskImage::PLATFORM_PC, DiskImage::REGION_NORTH_AMERICA, DiskImage::LANGUAGE_ENGLISH,
+        DiskImage::DISK_INSTALL, true, ""},
+      {"FF7INST.EXE", "Final Fantasy VII (PC, 1998, USA) Install Disk",
+        DiskImage::PLATFORM_PC, DiskImage::REGION_NORTH_AMERICA, DiskImage::LANGUAGE_ENGLISH,
+        DiskImage::DISK_INSTALL, true, ""},
+      {"FF7/MOVIES/BIKE.AVI", "Final Fantasy VII (PC, 1998, USA) Disk 1",
+        DiskImage::PLATFORM_PC, DiskImage::REGION_NORTH_AMERICA, DiskImage::LANGUAGE_ENGLISH,
+        DiskImage::DISK_1, true, ""},
+      {"FF7/MOVIES/BIGLIGHT.AVI", "Final Fantasy VII (PC, 1998, USA) Disk 2",
+        DiskImage::PLATFORM_PC, DiskImage::REGION_NORTH_AMERICA, DiskImage::LANGUAGE_ENGLISH,
+        DiskImage::DISK_2, true, ""},
+      {"FF7/MOVIES/ENDING1.AVI", "Final Fantasy VII (PC, 1998, USA) Disk 3",
+        DiskImage::PLATFORM_PC, DiskImage::REGION_NORTH_AMERICA, DiskImage::LANGUAGE_ENGLISH,
+        DiskImage::DISK_3, true, ""}
+    };
+
+    /**
+     * The PlayStation disks.
+     */
+    const DiskReleases::Release PLAYSTATION_RELEASES[] = {
+      {"SCUS-94163", "Final Fantasy VII (USA) Disc 1",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_NORTH_AMERICA, DiskImage::LANGUAGE_ENGLISH,
+        DiskImage::DISK_1, true,
+        ""},
+      {"SCUS-94164", "Final Fantasy VII (USA) Disc 2",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_NORTH_AMERICA, DiskImage::LANGUAGE_ENGLISH,
+        DiskImage::DISK_2, true,
+        ""},
+      {"SCUS-94165", "Final Fantasy VII (USA) Disc 3",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_NORTH_AMERICA, DiskImage::LANGUAGE_ENGLISH,
+        DiskImage::DISK_3, true,
+        ""},
+      {"SCES-00867", "Final Fantasy VII (Europe, English) Disc 1",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_EUROPE, DiskImage::LANGUAGE_ENGLISH,
+        DiskImage::DISK_1, true,
+        ""},
+      {"SCES-10867", "Final Fantasy VII (Europe, English) Disc 2",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_EUROPE, DiskImage::LANGUAGE_ENGLISH,
+        DiskImage::DISK_2, true,
+        ""},
+      {"SCES-20867", "Final Fantasy VII (Europe, English) Disc 3",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_EUROPE, DiskImage::LANGUAGE_ENGLISH,
+        DiskImage::DISK_3, true,
+        ""},
+      {"SCES-00868", "Final Fantasy VII (Europe, French) Disc 1",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_EUROPE, DiskImage::LANGUAGE_FRENCH,
+        DiskImage::DISK_1, false,
+        "French language is not fully supported in V-Gears."},
+      {"SCES-10868", "Final Fantasy VII (Europe, French) Disc 2",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_EUROPE, DiskImage::LANGUAGE_FRENCH,
+        DiskImage::DISK_2, false,
+        "French language is not fully supported in V-Gears."},
+      {"SCES-20868", "Final Fantasy VII (Europe, French) Disc 3",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_EUROPE, DiskImage::LANGUAGE_FRENCH,
+        DiskImage::DISK_3, false,
+        "French language is not fully supported in V-Gears."},
+      {"SCES-00900", "Final Fantasy VII (Europe, Spanish) Disc 1",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_EUROPE, DiskImage::LANGUAGE_SPANISH,
+        DiskImage::DISK_1, true,
+        "Spanish language is not fully supported in V-Gears."},
+      {"SCES-10900", "Final Fantasy VII (Europe, Spanish) Disc 2",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_EUROPE, DiskImage::LANGUAGE_SPANISH,
+        DiskImage::DISK_2, false,
+        "Spanish language is not fully supported in V-Gears."},
+      {"SCES-20900", "Final Fantasy VII (Europe, Spanish) Disc 3",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_EUROPE, DiskImage::LANGUAGE_SPANISH,
+        DiskImage::DISK_3, false,
+        "Spanish language is not fully supported in V-Gears."},
+      {"SCES-00869", "Final Fantasy VII (Europe, German) Disc 1",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_EUROPE, DiskImage::LANGUAGE_GERMAN,
+        DiskImage::DISK_1, true,
+        "German language is not fully supported in V-Gears."},
+      {"SCES-10869", "Final Fantasy VII (Europe, German) Disc 2",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_EUROPE, DiskImage::LANGUAGE_GERMAN,
+        DiskImage::DISK_2, false,
+        "German language is not fully supported in V-Gears."},
+      {"SCES-20869", "Final Fantasy VII (Europe, German) Disc 3",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_EUROPE, DiskImage::LANGUAGE_GERMAN,
+        DiskImage::DISK_3, false,
+        "German language is not fully supported in V-Gears."},
+      {"SCES-00901", "Final Fantasy VII (Europe, Italian) Disc 1",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_EUROPE, DiskImage::LANGUAGE_ITALIAN,
+        DiskImage::DISK_1, true,
+        "Italian language is not fully supported in V-Gears."},
+      {"SCES-10901", "Final Fantasy VII (Europe, Italian) Disc 2",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_EUROPE, DiskImage::LANGUAGE_ITALIAN,
+        DiskImage::DISK_2, false,
+        "Italian language is not fully supported in V-Gears."},
+      {"SCES-20901", "Final Fantasy VII (Europe, Italian) Disc 3",
+        DiskImage::PLATFORM_PS1, DiskImage::REGION_EUROPE, DiskImage::LANGUAGE_ITALIAN,
+        DiskImage::DISK_3, false,
+        "Italian language is not fully supported in V-Gears."}
+    };
+
+    /**
+     * Finds the release with a marker.
+     */
+    template<typename Releases>
+    const DiskReleases::Release* Find(const Releases& releases, const std::string& marker){
+        const auto found = std::find_if(
+          std::begin(releases), std::end(releases),
+          [&marker](const DiskReleases::Release& release){return marker == release.marker;}
+        );
+        return found == std::end(releases) ? nullptr : &*found;
+    }
+}
+
+namespace DiskReleases{
+
+    const Release* FindPcRelease(const std::string& path){return Find(PC_RELEASES, path);}
+
+    const Release* FindPlayStationRelease(const std::string& game_id){
+        return Find(PLAYSTATION_RELEASES, game_id);
+    }
+}

+ 89 - 0
src/installer/formats/DiskReleases.h

@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <string>
+#include "DiskImage.h"
+
+/**
+ * The releases of the game that can be identified.
+ */
+namespace DiskReleases{
+
+    /**
+     * A disk of a release of the game.
+     */
+    struct Release{
+
+        /**
+         * What identifies the disk: for PC disks, the path of a file only that disk has; for
+         * PlayStation disks, the game ID.
+         */
+        const char* marker;
+
+        /**
+         * Human readable name of the disk.
+         */
+        const char* name;
+
+        /**
+         * Platform of the release.
+         */
+        DiskImage::Platform platform;
+
+        /**
+         * Region of the release.
+         */
+        DiskImage::Region region;
+
+        /**
+         * Language of the release.
+         */
+        DiskImage::Language language;
+
+        /**
+         * Disk number.
+         */
+        DiskImage::Disk disk;
+
+        /**
+         * If the release is supported.
+         */
+        bool supported;
+
+        /**
+         * Warning about the release. Empty if there is none.
+         */
+        const char* warning;
+    };
+
+    /**
+     * Finds the PC disk that a file belongs to.
+     *
+     * @param[in] path Path of a file of the disk, normalized with
+     * {@see DiskIdentifier::NormalizePath}.
+     * @return The disk, or null if the file doesn't identify any.
+     */
+    const Release* FindPcRelease(const std::string& path);
+
+    /**
+     * Finds a PlayStation disk.
+     *
+     * @param[in] game_id The game ID, like "SCUS-94163".
+     * @return The disk, or null if the ID is unknown.
+     */
+    const Release* FindPlayStationRelease(const std::string& game_id);
+}

+ 166 - 0
src/installer/formats/DiskVideoExtractor.cpp

@@ -0,0 +1,166 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <algorithm>
+#include <cstdio>
+#include <fstream>
+#include <memory>
+#include <sys/stat.h>
+#include <archive.h>
+#include <archive_entry.h>
+#include <QtCore/qdir.h>
+#include "DiskVideoExtractor.h"
+#include "installer/steps/VideoFiles.h"
+
+namespace{
+
+    /**
+     * Pointer to a libarchive reader, freed when it goes out of scope.
+     */
+    using ArchivePointer = std::unique_ptr<struct archive, int(*)(struct archive*)>;
+
+    /**
+     * Opens a disk image.
+     *
+     * @param[in] path Path of the image.
+     * @param[in] log Function to write the error to.
+     * @return The image, or null if it can't be opened.
+     */
+    ArchivePointer Open(const std::string& path, const std::function<void(const std::string&)>& log){
+        ArchivePointer image(archive_read_new(), archive_read_free);
+        archive_read_support_format_all(image.get());
+        archive_read_support_filter_all(image.get());
+        if (archive_read_open_filename(image.get(), path.c_str(), 10240) != ARCHIVE_OK){
+            log("[ERROR] Could not open the disk image: " + std::string(archive_error_string(image.get())));
+            image.reset();
+        }
+        return image;
+    }
+
+    /**
+     * Moves to the next video of a disk.
+     *
+     * @param[in] image The disk image.
+     * @param[out] name Name of the video.
+     * @return The entry of the video, or null if there are no more.
+     */
+    struct archive_entry* NextVideo(struct archive* image, std::string& name){
+        struct archive_entry* entry;
+        while (archive_read_next_header(image, &entry) == ARCHIVE_OK){
+            const char* path = archive_entry_pathname(entry);
+            if (path && archive_entry_filetype(entry) == AE_IFREG && VideoFiles::IsMovie(path, &name))
+                return entry;
+        }
+        return nullptr;
+    }
+}
+
+DiskVideoExtractor::DiskVideoExtractor(
+  const std::string& image_path, const std::function<void(float)>& progress,
+  const std::function<void(const std::string&)>& log
+):
+  image_path_(image_path), progress_(progress), log_(log), total_bytes_(0), done_bytes_(0),
+  extracted_(0), skipped_(0)
+{}
+
+bool DiskVideoExtractor::Extract(const std::string& video_dir){
+    extracted_ = 0;
+    skipped_ = 0;
+    done_bytes_ = 0;
+    if (!QDir().mkpath(QString::fromStdString(video_dir))){
+        log_("[ERROR] Could not create " + video_dir);
+        return false;
+    }
+    // First pass: which videos the disk has, and their total size, to report the progress.
+    total_bytes_ = TotalSize();
+    if (total_bytes_ == 0) return false;
+    // Second pass: copy them.
+    ArchivePointer image = Open(image_path_, log_);
+    if (!image) return false;
+    bool ok = true;
+    std::string name;
+    while (struct archive_entry* entry = NextVideo(image.get(), name)){
+        const uint64_t size = archive_entry_size(entry);
+        const std::string destination = video_dir + name;
+        // Several disks have the same videos: skip the ones that are already there.
+        struct stat existing;
+        if (stat(destination.c_str(), &existing) == 0 && static_cast<uint64_t>(existing.st_size) == size){
+            ++ skipped_;
+            Advance(size);
+        }
+        else if (Copy(image.get(), name, destination)){
+            log_("Extracted " + name);
+            ++ extracted_;
+        }
+        else ok = false;
+    }
+    progress_(100);
+    return ok;
+}
+
+uint64_t DiskVideoExtractor::TotalSize(){
+    ArchivePointer image = Open(image_path_, log_);
+    if (!image) return 0;
+    uint64_t total = 0;
+    std::string name;
+    while (struct archive_entry* entry = NextVideo(image.get(), name))
+        total += archive_entry_size(entry);
+    if (total == 0) log_("[ERROR] The disk image has no videos.");
+    return total;
+}
+
+bool DiskVideoExtractor::Copy(
+  struct archive* image, const std::string& name, const std::string& destination
+){
+    const std::string partial = destination + ".part";
+    std::ofstream out(partial, std::ios::binary | std::ios::trunc);
+    if (!out){
+        log_("[ERROR] Could not write " + destination);
+        return false;
+    }
+    const void* buffer;
+    size_t length;
+    la_int64_t offset;
+    bool read_ok = true;
+    while (true){
+        const int status = archive_read_data_block(image, &buffer, &length, &offset);
+        if (status == ARCHIVE_EOF) break;
+        if (status < ARCHIVE_OK){
+            log_("[ERROR] Could not read " + name + ": " + archive_error_string(image));
+            read_ok = false;
+            break;
+        }
+        out.seekp(offset);
+        out.write(static_cast<const char*>(buffer), length);
+        Advance(length);
+    }
+    out.close();
+    if (!read_ok || !out){
+        if (read_ok) log_("[ERROR] Could not write " + destination);
+        std::remove(partial.c_str());
+        return false;
+    }
+    std::remove(destination.c_str());
+    if (std::rename(partial.c_str(), destination.c_str()) != 0){
+        log_("[ERROR] Could not create " + destination);
+        return false;
+    }
+    return true;
+}
+
+void DiskVideoExtractor::Advance(const uint64_t bytes){
+    done_bytes_ += bytes;
+    progress_(100.0f * std::min<uint64_t>(done_bytes_, total_bytes_) / total_bytes_);
+}

+ 123 - 0
src/installer/formats/DiskVideoExtractor.h

@@ -0,0 +1,123 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <functional>
+#include <string>
+
+struct archive;
+
+/**
+ * Copies the videos of a game disk.
+ */
+class DiskVideoExtractor{
+
+    public:
+
+        /**
+         * Constructor.
+         *
+         * @param[in] image_path Path of the disk image.
+         * @param[in] progress Called with the percentage of the videos that has been copied.
+         * @param[in] log Function to write a line to the installation log.
+         */
+        DiskVideoExtractor(
+          const std::string& image_path, const std::function<void(float)>& progress,
+          const std::function<void(const std::string&)>& log
+        );
+
+        /**
+         * Copies the videos.
+         *
+         * The videos that are already there, with the same size, are not copied again.
+         *
+         * @param[in] video_dir Folder to copy the videos to, ending in a slash.
+         * @return True if all the videos were copied or were already there.
+         */
+        bool Extract(const std::string& video_dir);
+
+        /**
+         * Retrieves the number of videos copied by {@see Extract}.
+         */
+        int Extracted() const{return extracted_;}
+
+        /**
+         * Retrieves the number of videos that {@see Extract} found already there.
+         */
+        int Skipped() const{return skipped_;}
+
+    private:
+
+        /**
+         * Adds up the size of the videos of the disk.
+         *
+         * @return The size, or 0 if the disk has no videos or can't be read.
+         */
+        uint64_t TotalSize();
+
+        /**
+         * Copies the current file of the disk.
+         *
+         * It is written under a temporary name, so an interrupted copy is never taken for a video.
+         *
+         * @param[in] image The disk image.
+         * @param[in] name Name of the video.
+         * @param[in] destination Path of the copy.
+         * @return True if the video was copied.
+         */
+        bool Copy(struct archive* image, const std::string& name, const std::string& destination);
+
+        /**
+         * Counts bytes of the videos as done, and reports the progress.
+         */
+        void Advance(const uint64_t bytes);
+
+        /**
+         * Path of the disk image.
+         */
+        std::string image_path_;
+
+        /**
+         * Function to report the progress.
+         */
+        std::function<void(float)> progress_;
+
+        /**
+         * Function to write a line to the installation log.
+         */
+        std::function<void(const std::string&)> log_;
+
+        /**
+         * Size of all the videos.
+         */
+        uint64_t total_bytes_;
+
+        /**
+         * Size of the videos done.
+         */
+        uint64_t done_bytes_;
+
+        /**
+         * Number of videos copied.
+         */
+        int extracted_;
+
+        /**
+         * Number of videos that were already there.
+         */
+        int skipped_;
+};

+ 151 - 0
src/installer/formats/Iso9660Reader.cpp

@@ -0,0 +1,151 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <algorithm>
+#include "Iso9660Reader.h"
+
+const size_t Iso9660Reader::SECTOR_SIZE = 2048;
+
+namespace{
+
+    /**
+     * Sector of the primary volume descriptor.
+     */
+    const uint64_t DESCRIPTOR_SECTOR = 16;
+
+    /**
+     * Size of a folder record without its name.
+     */
+    const size_t RECORD_HEADER_SIZE = 33;
+
+    /**
+     * Deepest folder that is read. ISO9660 allows 8 levels; a damaged image could have a folder
+     * inside itself.
+     */
+    const int MAX_DEPTH = 32;
+
+    /**
+     * Reads a little endian 32 bit value.
+     */
+    uint32_t ReadLe32(const uint8_t* bytes){
+        return static_cast<uint32_t>(bytes[0]) | (static_cast<uint32_t>(bytes[1]) << 8)
+          | (static_cast<uint32_t>(bytes[2]) << 16) | (static_cast<uint32_t>(bytes[3]) << 24);
+    }
+}
+
+Iso9660Reader::Iso9660Reader(const std::string& path):
+  file_(path, std::ios::binary), file_size_(0), root_sector_(0), root_size_(0), valid_(false)
+{
+    if (!file_) return;
+    file_.seekg(0, std::ios::end);
+    file_size_ = static_cast<uint64_t>(file_.tellg());
+    const std::vector<uint8_t> descriptor = ReadBytes(DESCRIPTOR_SECTOR * SECTOR_SIZE, SECTOR_SIZE);
+    if (
+      descriptor.size() != SECTOR_SIZE || descriptor[0] != 1
+      || std::string(descriptor.begin() + 1, descriptor.begin() + 6) != "CD001"
+    ) return;
+    // The record of the root folder starts at the byte 156.
+    root_sector_ = ReadLe32(&descriptor[156 + 2]);
+    root_size_ = ReadLe32(&descriptor[156 + 10]);
+    valid_ = true;
+}
+
+bool Iso9660Reader::IsValid() const{return valid_;}
+
+Iso9660Reader::Result Iso9660Reader::Walk(
+  const std::function<std::string(const std::string&)>& normalize,
+  const std::function<bool(const Entry&)>& visit
+){
+    if (!valid_) return Result::READ_ERROR;
+    return WalkFolder(root_sector_, root_size_, "", 0, normalize, visit);
+}
+
+bool Iso9660Reader::Read(
+  const Entry& entry, const std::function<bool(const char*, size_t)>& write
+){
+    file_.clear();
+    file_.seekg(static_cast<std::streamoff>(entry.sector) * SECTOR_SIZE, std::ios::beg);
+    std::vector<char> chunk(64 * 1024);
+    uint32_t remaining = entry.size;
+    while (remaining > 0){
+        file_.read(chunk.data(), std::min<size_t>(chunk.size(), remaining));
+        const std::streamsize got = file_.gcount();
+        if (got <= 0 || !write(chunk.data(), static_cast<size_t>(got))) return false;
+        remaining -= static_cast<uint32_t>(got);
+    }
+    return true;
+}
+
+int64_t Iso9660Reader::Position(){
+    file_.clear();
+    return static_cast<int64_t>(file_.tellg());
+}
+
+std::vector<uint8_t> Iso9660Reader::ReadBytes(const uint64_t offset, const size_t size){
+    // A damaged image could give any size: not more than what is left is allocated.
+    if (offset >= file_size_) return {};
+    std::vector<uint8_t> bytes(std::min<uint64_t>(size, file_size_ - offset));
+    file_.clear();
+    file_.seekg(static_cast<std::streamoff>(offset), std::ios::beg);
+    file_.read(reinterpret_cast<char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()));
+    bytes.resize(static_cast<size_t>(file_.gcount()));
+    return bytes;
+}
+
+Iso9660Reader::Result Iso9660Reader::WalkFolder(
+  const uint32_t sector, const uint32_t size, const std::string& prefix, const int depth,
+  const std::function<std::string(const std::string&)>& normalize,
+  const std::function<bool(const Entry&)>& visit
+){
+    if (size == 0) return Result::COMPLETE;
+    if (depth > MAX_DEPTH) return Result::READ_ERROR;
+    const std::vector<uint8_t> records
+      = ReadBytes(static_cast<uint64_t>(sector) * SECTOR_SIZE, size);
+    if (records.empty()) return Result::READ_ERROR;
+    size_t offset = 0;
+    while (offset < records.size()){
+        const uint8_t record_size = records[offset];
+        // Records don't cross sectors: the rest of the sector is empty.
+        if (record_size == 0){
+            offset = ((offset / SECTOR_SIZE) + 1) * SECTOR_SIZE;
+            continue;
+        }
+        if (offset + record_size > records.size() || offset + RECORD_HEADER_SIZE > records.size()) break;
+        const uint8_t* record = &records[offset];
+        const size_t name_size = record[32];
+        offset += record_size;
+        const size_t name_offset = (record - records.data()) + RECORD_HEADER_SIZE;
+        if (name_size == 0 || name_offset + name_size > records.size()) continue;
+        // The entries of the folder itself and of its parent.
+        if (name_size == 1 && (records[name_offset] == 0x00 || records[name_offset] == 0x01)) continue;
+        const std::string name = normalize(std::string(
+          reinterpret_cast<const char*>(records.data()) + name_offset, name_size
+        ));
+        if (name.empty() || name == "." || name == ".." || name.find('/') != std::string::npos) continue;
+        Entry entry;
+        entry.path = prefix.empty() ? name : prefix + "/" + name;
+        entry.directory = (record[25] & 0x02) != 0;
+        entry.sector = ReadLe32(record + 2);
+        entry.size = ReadLe32(record + 10);
+        if (!visit(entry)) return Result::STOPPED;
+        if (entry.directory){
+            const Result result = WalkFolder(
+              entry.sector, entry.size, entry.path, depth + 1, normalize, visit
+            );
+            if (result != Result::COMPLETE) return result;
+        }
+    }
+    return Result::COMPLETE;
+}

+ 162 - 0
src/installer/formats/Iso9660Reader.h

@@ -0,0 +1,162 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <fstream>
+#include <functional>
+#include <string>
+#include <vector>
+
+/**
+ * Reads the folders and files of an ISO9660 image.
+ *
+ * It's used for the images that libarchive lists no files of.
+ */
+class Iso9660Reader{
+
+    public:
+
+        /**
+         * Size of a sector of the image.
+         */
+        static const size_t SECTOR_SIZE;
+
+        /**
+         * A file or folder of the image.
+         */
+        struct Entry{
+
+            /**
+             * Path from the root: the names of the folders, as returned by the name filter, and
+             * the name, separated by slashes.
+             */
+            std::string path;
+
+            /**
+             * True for folders.
+             */
+            bool directory;
+
+            /**
+             * First sector of the contents.
+             */
+            uint32_t sector;
+
+            /**
+             * Size of the contents, in bytes.
+             */
+            uint32_t size;
+        };
+
+        /**
+         * Result of a walk through the image.
+         */
+        enum class Result{
+            COMPLETE, /**< All the entries were visited. */
+            STOPPED, /**< A function asked to stop. */
+            READ_ERROR /**< A folder could not be read. */
+        };
+
+        /**
+         * Constructor.
+         *
+         * @param[in] path Path of the image.
+         */
+        explicit Iso9660Reader(const std::string& path);
+
+        /**
+         * Checks if the file is an ISO9660 image.
+         *
+         * @return True if it could be opened and has a primary volume descriptor.
+         */
+        bool IsValid() const;
+
+        /**
+         * Visits every file and folder of the image, each folder before its contents.
+         *
+         * Entries whose name could lead outside of their folder are skipped.
+         *
+         * @param[in] normalize Converts the names of the image to the ones used in the paths.
+         * @param[in] visit Called for each entry. It returns false to stop.
+         * @return How the walk ended.
+         */
+        Result Walk(
+          const std::function<std::string(const std::string&)>& normalize,
+          const std::function<bool(const Entry&)>& visit
+        );
+
+        /**
+         * Reads the contents of a file in pieces.
+         *
+         * @param[in] entry The file.
+         * @param[in] write Called with each piece. It returns false to stop.
+         * @return False if the file could not be read or written completely.
+         */
+        bool Read(const Entry& entry, const std::function<bool(const char*, size_t)>& write);
+
+        /**
+         * Retrieves how far into the image the last read was.
+         *
+         * @return The position, in bytes.
+         */
+        int64_t Position();
+
+    private:
+
+        /**
+         * Reads a part of the image.
+         *
+         * @param[in] offset Where to start.
+         * @param[in] size How many bytes to read.
+         * @return The bytes. Fewer than requested if the image ends before.
+         */
+        std::vector<uint8_t> ReadBytes(const uint64_t offset, const size_t size);
+
+        /**
+         * Visits the entries of a folder.
+         */
+        Result WalkFolder(
+          const uint32_t sector, const uint32_t size, const std::string& prefix, const int depth,
+          const std::function<std::string(const std::string&)>& normalize,
+          const std::function<bool(const Entry&)>& visit
+        );
+
+        /**
+         * The image.
+         */
+        std::ifstream file_;
+
+        /**
+         * Size of the image.
+         */
+        uint64_t file_size_;
+
+        /**
+         * First sector of the root folder.
+         */
+        uint32_t root_sector_;
+
+        /**
+         * Size of the root folder.
+         */
+        uint32_t root_size_;
+
+        /**
+         * True if the image has a primary volume descriptor.
+         */
+        bool valid_;
+};

+ 1 - 0
test/installer/CMakeLists.txt

@@ -1,4 +1,5 @@
 # Tests of this folder (see vgears_tests and vgears_installer_tests in test/CMakeLists.txt).
 add_subdirectory(decompiler)
 add_subdirectory(extractors)
+add_subdirectory(formats)
 add_subdirectory(steps)

+ 4 - 0
test/installer/formats/CMakeLists.txt

@@ -0,0 +1,4 @@
+# Tests of this folder (see vgears_tests and vgears_installer_tests in test/CMakeLists.txt).
+vgears_tests(
+    DiskImage.cpp
+)

+ 145 - 0
test/installer/formats/DiskImage.cpp

@@ -0,0 +1,145 @@
+/*
+ * Copyright (C) 2022 The V-Gears Team
+ *
+ * This file is part of V-Gears
+ *
+ * V-Gears is free software: you can redistribute it and/or modify it under
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation, version 3.0 (GPLv3) of the License.
+ *
+ * V-Gears is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ */
+
+#include <fstream>
+#include <boost/filesystem.hpp>
+#include <boost/test/unit_test.hpp>
+#include "installer/formats/DiskIdentifier.h"
+#include "installer/formats/DiskPaths.h"
+#include "installer/formats/DiskReleases.h"
+#include "installer/formats/Iso9660Reader.h"
+
+namespace{
+
+    /**
+     * A folder that is removed when the test ends.
+     */
+    struct TempFolder{
+        const boost::filesystem::path path
+          = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
+        TempFolder(){boost::filesystem::create_directories(path);}
+        ~TempFolder(){boost::filesystem::remove_all(path);}
+    };
+
+    /**
+     * Adds a folder record to a sector of an image.
+     */
+    void AddRecord(
+      std::vector<char>& image, size_t& offset, const std::string& name, const uint32_t sector,
+      const uint32_t size, const bool directory
+    ){
+        const size_t length = 33 + name.size() + (name.size() % 2 == 0 ? 1 : 0);
+        image[offset] = static_cast<char>(length);
+        for (int byte = 0; byte < 4; ++ byte){
+            image[offset + 2 + byte] = static_cast<char>(sector >> (8 * byte));
+            image[offset + 10 + byte] = static_cast<char>(size >> (8 * byte));
+        }
+        image[offset + 25] = directory ? 2 : 0;
+        image[offset + 32] = static_cast<char>(name.size());
+        std::copy(name.begin(), name.end(), image.begin() + offset + 33);
+        offset += length;
+    }
+}
+
+BOOST_AUTO_TEST_CASE(TestDiskReleases){
+    const DiskReleases::Release* install = DiskReleases::FindPcRelease("FF7INST.EXE");
+    BOOST_REQUIRE(install);
+    BOOST_CHECK_EQUAL(install->disk, DiskImage::DISK_INSTALL);
+    const DiskReleases::Release* disk_2 = DiskReleases::FindPcRelease("FF7/MOVIES/BIGLIGHT.AVI");
+    BOOST_REQUIRE(disk_2);
+    BOOST_CHECK_EQUAL(disk_2->disk, DiskImage::DISK_2);
+    BOOST_CHECK(!DiskReleases::FindPcRelease("FF7/MOVIES/OTHER.AVI"));
+    const DiskReleases::Release* french = DiskReleases::FindPlayStationRelease("SCES-10868");
+    BOOST_REQUIRE(french);
+    BOOST_CHECK_EQUAL(french->platform, DiskImage::PLATFORM_PS1);
+    BOOST_CHECK_EQUAL(french->language, DiskImage::LANGUAGE_FRENCH);
+    BOOST_CHECK_EQUAL(french->disk, DiskImage::DISK_2);
+    BOOST_CHECK_EQUAL(std::string(french->warning), "French language is not fully supported in V-Gears.");
+    BOOST_CHECK(!DiskReleases::FindPlayStationRelease("SCUS-00000"));
+}
+
+BOOST_AUTO_TEST_CASE(TestDiskPathsAreNormalized){
+    BOOST_CHECK_EQUAL(DiskIdentifier::NormalizePath("/ff7\\movies/bike.avi;1 \n"), "FF7/MOVIES/BIKE.AVI");
+    BOOST_CHECK_EQUAL(DiskIdentifier::RemoveVersion("Readme.;1"), "Readme");
+    BOOST_CHECK_EQUAL(DiskIdentifier::RemoveVersion("a;b"), "a;b");
+    BOOST_CHECK_EQUAL(DiskIdentifier::FindGameId("BOOT = cdrom:\\SCUS_941.63;1"), "SCUS-94163");
+    BOOST_CHECK_EQUAL(DiskIdentifier::FindGameId("BOOT = cdrom:\\PSX.EXE;1"), "");
+}
+
+BOOST_AUTO_TEST_CASE(TestDiskFilesAreFound){
+    TempFolder folder;
+    boost::filesystem::create_directories(folder.path / "DATA" / "WM");
+    std::ofstream((folder.path / "DATA" / "WM" / "WORLD_US.LGP").string()) << "x";
+    std::ofstream((folder.path / "FF7INST.EXE").string()) << "x";
+    const std::string base = folder.path.string();
+    const auto world = DiskPaths::Find(base, "data/wm/world_us.lgp");
+    BOOST_REQUIRE(world);
+    BOOST_CHECK(world->find("DATA/WM/WORLD_US.LGP") != std::string::npos);
+    // A name that begins the same way is used if there is no other.
+    BOOST_CHECK(DiskPaths::Find(base, "ff7.exe"));
+    std::ofstream((folder.path / "FF7.EXE").string()) << "x";
+    BOOST_CHECK(DiskPaths::Find(base, "ff7.exe")->find("FF7.EXE") != std::string::npos);
+    BOOST_CHECK(!DiskPaths::Find(base, "data/wm/world_us.bin"));
+}
+
+BOOST_AUTO_TEST_CASE(TestIso9660FilesAreRead){
+    // The descriptor in the sector 16, the root folder in the 17, a folder in the 18 and a file
+    // in the 19.
+    const size_t sector = Iso9660Reader::SECTOR_SIZE;
+    std::vector<char> image(20 * sector, 0);
+    image[16 * sector] = 1;
+    const std::string standard = "CD001";
+    std::copy(standard.begin(), standard.end(), image.begin() + 16 * sector + 1);
+    size_t offset = 16 * sector + 156;
+    AddRecord(image, offset, std::string(1, '\0'), 17, sector, true);
+    offset = 17 * sector;
+    AddRecord(image, offset, std::string(1, '\0'), 17, sector, true);
+    AddRecord(image, offset, "..", 17, sector, true);
+    AddRecord(image, offset, "DATA", 18, sector, true);
+    offset = 18 * sector;
+    AddRecord(image, offset, "FILE.TXT;1", 19, 5, false);
+    const std::string text = "hello";
+    std::copy(text.begin(), text.end(), image.begin() + 19 * sector);
+    TempFolder folder;
+    const std::string path = (folder.path / "image.iso").string();
+    std::ofstream(path, std::ios::binary).write(image.data(), image.size());
+
+    Iso9660Reader reader(path);
+    BOOST_REQUIRE(reader.IsValid());
+    std::vector<std::string> paths;
+    std::string contents;
+    const Iso9660Reader::Result result = reader.Walk(
+      DiskIdentifier::RemoveVersion,
+      [&](const Iso9660Reader::Entry& entry){
+          paths.push_back(entry.path);
+          if (!entry.directory){
+              reader.Read(entry, [&contents](const char* data, size_t size){
+                  contents.append(data, size);
+                  return true;
+              });
+          }
+          return true;
+      }
+    );
+    // The ".." folder, which would lead outside, is skipped.
+    BOOST_CHECK(result == Iso9660Reader::Result::COMPLETE);
+    BOOST_REQUIRE_EQUAL(paths.size(), 2u);
+    BOOST_CHECK_EQUAL(paths[0], "DATA");
+    BOOST_CHECK_EQUAL(paths[1], "DATA/FILE.TXT");
+    BOOST_CHECK_EQUAL(contents, "hello");
+    // A file past the end of the image can't be read.
+    Iso9660Reader::Entry missing{"x", false, 100, 5};
+    BOOST_CHECK(!reader.Read(missing, [](const char*, size_t){return true;}));
+}

Някои файлове не бяха показани, защото твърде много файлове са промени