// SPDX-License-Identifier: GPL-3.0-only #include "modern/ui/mod_library.hpp" #include "modern/ui/demo_files.hpp" #include "content/package.hpp" #include "launch/mods.hpp" #include "launch/game_data.hpp" #include #include #include #include namespace bmh::modern_ui { namespace { constexpr uint64_t limit = 512ull * 1024 * 1024; constexpr const char *selection_file = ".ui-active-mod.json"; constexpr const char *journal_file = ".ui-mod-transaction.json"; void directory(const fs::path &path, bool create = false) { fs::path cursor; for (const auto &part : fs::absolute(path).lexically_normal()) { cursor /= part; const auto status = fs::symlink_status(cursor); if (fs::is_symlink(status) || (fs::exists(status) && !fs::is_directory(status))) throw editor::Error("Unsicheres Mod-Verzeichnis."); } if (create) fs::create_directories(path); } std::string regular(const fs::path &path, uint64_t maximum = limit) { if (fs::is_symlink(fs::symlink_status(path)) || !fs::is_regular_file(path)) throw editor::Error("Die Mod-Datei fehlt oder ist verknüpft."); return editor::read_file(path, maximum); } std::string file_digest(const fs::path &path) { if (fs::is_symlink(fs::symlink_status(path)) || !fs::is_regular_file(path) || fs::file_size(path) > limit) throw editor::Error("Unsichere oder zu große Mod-Datei."); std::ifstream stream(path, std::ios::binary); if (!stream) throw editor::Error("Mod-Datei nicht lesbar."); std::string buffer(1024 * 1024, '\0'), blocks; uint64_t count = 0; while (stream) { stream.read(buffer.data(), std::streamsize(buffer.size())); const auto received = stream.gcount(); if (received > 0) { count += uint64_t(received); if (count > limit) throw editor::Error("Mod-Datei zu groß."); blocks += content::sha256(std::string_view(buffer.data(), size_t(received))); } } if (!stream.eof() || count != fs::file_size(path)) throw editor::Error("Mod-Datei wurde beim Lesen geändert."); return content::sha256(std::to_string(count) + ":" + blocks); } struct Temp { fs::path path; Temp() : path(fs::temp_directory_path() / editor::new_id("openbmh-mod-plan-")) { if (!fs::create_directory(path)) throw editor::Error("Temporärer Mod-Ordner nicht verfügbar."); } ~Temp() { std::error_code error; fs::remove_all(path, error); } }; struct Lock { fs::path path; explicit Lock(const fs::path &root) : path(root / ".ui-mod-lock") { directory(root, true); if (!fs::create_directory(path)) throw editor::Error("Die Mod-Bibliothek ist gerade belegt."); } ~Lock() { std::error_code error; fs::remove(path, error); } }; void member_name(const std::string &name) { try { UiModLibrary::clean_name(name); } catch (const std::exception &) { // Existing 0.2 ASCII names may exceed the new UI's64-character limit. launch::ModLibrary::validate_name(name); } } std::string member_key(const std::string &name) { try { return DemoFiles::name_key(name); } catch (const std::exception &) { member_name(name); return editor::folded(name); } } std::string fingerprint(const fs::path &source) { if (fs::is_symlink(fs::symlink_status(source))) throw editor::Error("Verknüpfte Mod-Quellen werden nicht übernommen."); if (fs::is_regular_file(source)) return content::sha256("file:" + file_digest(source)); if (!fs::is_directory(source)) throw editor::Error("Die Mod-Quelle fehlt."); std::map files; uint64_t bytes = 0; std::set paths; for (const auto &entry : fs::recursive_directory_iterator(source)) { if (entry.is_symlink()) throw editor::Error("Verknüpfte Mod-Inhalte werden nicht übernommen."); if (!entry.is_regular_file()) { if (!entry.is_directory()) throw editor::Error("Nicht unterstützter Dateityp in der Mod."); continue; } const auto name = editor::utf8(entry.path().lexically_relative(source)); if (!editor::safe_name(name) || !paths.insert(editor::folded(name)).second || files.size() >= 12000 || entry.file_size() > limit || (bytes += entry.file_size()) > limit) throw editor::Error("Unsichere, doppelte oder zu große Mod-Inhalte."); files[name] = file_digest(entry.path()); } return content::sha256(Json(files).dump()); } std::string description(const Json &manifest) { auto text = localized(manifest.value("description", Json())); if (text.empty()) text = localized(manifest.value("title", Json())); if (text.size() > 4000) throw editor::Error("Die Mod-Beschreibung ist zu lang."); return text; } bool feature(const Json &manifest, const std::string &name) { const auto required = manifest.value("requires", Json::array()); return required.is_array() && std::find(required.begin(), required.end(), Json(name)) != required.end(); } struct Package { std::shared_ptr archive; UiModEntry metadata; }; Package package(const fs::path &path) { Package value; value.archive = editor::ArchiveStore::open(path); const auto manifest = Json::parse(value.archive->read("manifest.json")); if (manifest.value("format", "") != "openbmh-world" || manifest.value("kind", "") != "world") throw editor::Error("Die Quelle ist kein OpenBMH-Weltpaket."); auto &row = value.metadata; row.name = manifest.value("mod", std::string()); if (row.name.empty()) row.name = localized(manifest.value("title", Json())); try { row.name = UiModLibrary::clean_name(row.name); } catch (...) { row.name = "OpenBMH-Mod"; } row.description = description(manifest); row.version = manifest.value("version", manifest.value("format_version", std::string())); if (row.version.size() > 120) throw editor::Error("Ungültige Mod-Version."); row.format = fs::is_directory(path) ? "obw-directory" : "obw"; Json hashes = Json::object(); for (const auto &name : value.archive->names()) { if (++row.file_count > 12000 || (row.bytes += value.archive->size(name)) > limit) throw editor::Error("Das Weltpaket ist zu groß."); // Reading every entry checks compressed payload integrity, not just JSON. hashes[name] = content::sha256(value.archive->read(name)); } const bool classic = feature(manifest, "runtime:classic-v1"); if (classic) { if (feature(manifest, "runtime:modern-v1")) throw editor::Error("Mehrdeutiges Classic-/Modern-Profil."); Temp temp; const auto packed = temp.path / "content.obw"; value.archive->save(packed, {}, {}); const auto checked = content::open(packed); row.type = "Classic"; row.source = checked->english ? "FTLD" : "BMH"; row.content_id = checked->content_id; } else { const auto required = manifest.value("requires", Json::array()); if (!required.is_array()) throw editor::Error("Ungültige Weltanforderungen."); for (const auto &requirement : required) if (requirement != "editor:world-v1" && requirement != "runtime:modern-v1") throw editor::Error("Diese Weltanforderung wird von der nativen Oberfläche nicht unterstützt."); if (!Catalog::modern_manifest(manifest)) throw editor::Error("Dieses Weltprofil wird nicht unterstützt."); const auto checked = Catalog::open(path); const auto clubs = checked->clubs(); if (std::none_of(clubs.begin(), clubs.end(), [&](const auto *club) { return checked->manageable(club->value("id", "")); })) throw editor::Error("Diese Welt besitzt keinen von der UI-Demo unterstützten Verein."); row.type = "Modern"; row.source = "OpenBMH"; row.content_id = content::sha256(hashes.dump()); } return value; } struct Selection { std::optional active; std::string token, transaction, error; }; Selection selection(const fs::path &root) { Selection out; const auto file = root / selection_file; if (!fs::exists(fs::symlink_status(file))) { out.token = content::sha256("absent"); return out; } try { const auto bytes = regular(file, 1024 * 1024); out.token = content::sha256("file:" + bytes); const auto state = Json::parse(bytes); if (state.at("schema").get() != "openbmh-ui-active-mod@1" || (!state.at("active").is_null() && !state.at("active").is_string())) throw editor::Error("Ungültige aktive Mod-Auswahl."); if (!state.at("active").is_null()) { const auto name = state.at("active").get(); member_name(name); out.active = name; } out.transaction = state.value("transaction", ""); } catch (const std::exception &e) { out.active.reset(); out.error = e.what(); } return out; } void publish_selection(const fs::path &root, const std::optional &active, const std::string &transaction) { editor::write_atomic(root / selection_file, Json{{"schema", "openbmh-ui-active-mod@1"}, {"active", active ? Json(*active) : Json()}, {"transaction", transaction}}.dump(2)); } void selection_matches(const fs::path &root, const std::string &token) { if (token.empty() || selection(root).token != token) throw editor::Error("Die aktive Mod-Auswahl wurde inzwischen geändert."); } void recover(const fs::path &root) { const auto file = root / journal_file; if (!fs::exists(fs::symlink_status(file))) return; const auto journal = Json::parse(regular(file, 1024 * 1024)); if (journal.at("schema").get() != "openbmh-ui-mod-transaction@1") throw editor::Error("Ungültiges Mod-Transaktionsjournal."); const auto from = journal.at("from").get(); member_name(from); const auto to = journal.at("to").get(); const auto nonce = journal.at("nonce").get(); const auto operation = journal.at("operation").get(); if (nonce.empty() || nonce.find_first_not_of("0123456789abcdef") != nonce.npos || nonce.size() != 64) throw editor::Error("Ungültige Mod-Transaktionskennung."); if (operation == "rename") UiModLibrary::clean_name(to); else if (operation != "remove" || to != ".ui-trash-" + nonce) throw editor::Error("Ungültiges Mod-Transaktionsziel."); const auto old_path = root / "mods" / editor::path(from), new_path = root / "mods" / editor::path(to); const auto intermediate = root / "mods" / (".ui-rename-" + nonce); const auto rollback = root / "mods" / (".ui-rollback-" + nonce); directory(root / "mods"); if (fs::is_symlink(fs::symlink_status(old_path)) || fs::is_symlink(fs::symlink_status(new_path)) || fs::is_symlink(fs::symlink_status(intermediate))) throw editor::Error("Unsichere Mod-Wiederherstellung."); const bool committed = selection(root).transaction == nonce; const auto candidate = fs::exists(new_path) ? new_path : fs::exists(intermediate) ? intermediate : rollback; if (!committed && fs::exists(candidate)) { std::error_code equivalent_error; const bool same = fs::equivalent(old_path, candidate, equivalent_error); if ((fs::exists(old_path) && (equivalent_error || !same)) || fingerprint(candidate) != journal.at("token").get()) throw editor::Error("Mod-Wiederherstellung benötigt eine manuelle Prüfung; Daten bleiben erhalten."); if (candidate != rollback) { if (fs::exists(rollback)) throw editor::Error("Mod-Rollback benötigt eine manuelle Prüfung."); fs::rename(candidate, rollback); } fs::rename(rollback, old_path); } if (committed && operation == "remove") { std::error_code error; fs::remove_all(new_path, error); } std::error_code error; fs::remove(file, error); if (error) throw editor::Error("Das Mod-Transaktionsjournal konnte nicht aufgeräumt werden."); } void available(const fs::path &root, const std::string &name, const std::string &except = {}) { directory(root / "mods"); if (!fs::exists(root / "mods")) return; for (const auto &entry : fs::directory_iterator(root / "mods")) { const auto current = editor::utf8(entry.path().filename()); if (current == except || current.starts_with('.')) continue; bool conflict = false; try { conflict = member_key(current) == UiModLibrary::name_key(name); } catch (const std::exception &) {} if (conflict) throw editor::Error("Diese Mod-Bezeichnung wird bereits verwendet."); } } UiModEntry entry(const fs::path &root, const std::string &name) { UiModEntry row; row.id = row.name = name; row.path = root / "mods" / editor::path(name); try { row.token = content::sha256("member:" + name + ":" + fingerprint(row.path)); member_name(name); if (!fs::is_directory(row.path)) throw editor::Error("Kein Mod-Verzeichnis."); for (const auto &file : fs::directory_iterator(row.path)) if (file.path().filename() != "content.obw" && file.path().filename() != "mod.json") throw editor::Error("Unerwartete Datei im Mod-Verzeichnis."); const auto checked = package(row.path / "content.obw"); const auto token = row.token; row = checked.metadata; row.id = row.name = name; row.path = root / "mods" / editor::path(name); row.token = token; if (fs::exists(row.path / "mod.json")) { const auto profile = Json::parse(regular(row.path / "mod.json", 1024 * 1024)); if (profile.value("schema", "") != "openbmh-mod@1.0") throw editor::Error("Ungültiges Mod-Profil."); // Authored profile hints never override the verified package type. if (profile.contains("content_id") && profile.at("content_id").get() != row.content_id) throw editor::Error("Mod-Profil und geprüfter Inhalt stimmen nicht überein."); } } catch (const std::exception &e) { row.error = e.what(); } return row; } UiModEntry owned(const fs::path &root, const UiModEntry &expected, bool require_valid) { if (expected.id != expected.name || expected.path != root / "mods" / editor::path(expected.id)) throw editor::Error("Die Mod gehört nicht zu dieser Bibliothek."); member_name(expected.id); // Library IDs use the spelling actually enumerated on disk, even when the // host filesystem resolves an obsolete differently-cased path to it. bool exact_member = false; for (const auto &file : fs::directory_iterator(root / "mods")) if (editor::utf8(file.path().filename()) == expected.id) { exact_member = true; break; } if (!exact_member) throw editor::Error("Diese Mod-ID wurde inzwischen geändert. Bitte erneut auswählen."); if (fs::is_symlink(fs::symlink_status(expected.path)) || !fs::is_directory(expected.path)) throw editor::Error("Unsicheres oder fehlendes Mod-Verzeichnis."); const auto actual = entry(root, expected.id); if (expected.token.empty() || actual.token != expected.token) throw editor::Error("Diese Mod wurde inzwischen geändert. Bitte erneut auswählen."); if (require_valid && !actual.valid()) throw editor::Error(actual.error); return actual; } void transact(const fs::path &root, const UiModEntry &old, const std::string &to, const std::string &operation, const std::optional &active, const std::string &nonce) { const Json journal = {{"schema", "openbmh-ui-mod-transaction@1"}, {"from", old.name}, {"to", to}, {"operation", operation}, {"nonce", nonce}, {"token", fingerprint(old.path)}}; editor::write_atomic(root / journal_file, journal.dump(2), false); try { if (operation == "rename") { const auto intermediate = root / "mods" / (".ui-rename-" + nonce); fs::rename(old.path, intermediate); fs::rename(intermediate, root / "mods" / editor::path(to)); } else fs::rename(old.path, root / "mods" / editor::path(to)); publish_selection(root, active, nonce); } catch (...) { recover(root); throw; } // The selection nonce is the commit point. Cleanup never undoes that commit. recover(root); } } // namespace struct ModImportPlan::Payload { UiModEntry metadata; fs::path source, original_exe; std::string token; int start_year = 2026; std::shared_ptr archive; }; UiModLibrary::UiModLibrary(fs::path root) : root_(fs::weakly_canonical(fs::absolute(std::move(root)))) {} std::string UiModLibrary::clean_name(const std::string &raw) { const auto name = DemoFiles::clean_name(raw); if (name.size() > 240 || name.front() == '.' || name.back() == '.' || name.find_first_of("/\\:*?\"<>|") != name.npos) throw editor::Error("Bitte einen portablen Mod-Namen ohne Sonderzeichen oder abschließenden Punkt verwenden."); const auto stem = DemoFiles::name_key(name.substr(0, name.find('.'))); const std::set reserved = {"con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4", "lpt5", "lpt6", "lpt7", "lpt8", "lpt9"}; if (reserved.contains(stem)) throw editor::Error("Dieser Mod-Name ist vom Betriebssystem reserviert."); return name; } std::string UiModLibrary::name_key(const std::string &name) { return DemoFiles::name_key(clean_name(name)); } ModSnapshot UiModLibrary::snapshot() const { ModSnapshot result; try { directory(root_); directory(root_ / "mods"); if (fs::exists(root_ / journal_file)) { Lock lock(root_); recover(root_); } if (fs::exists(root_ / ".ui-mod-lock")) throw editor::Error("Die Mod-Bibliothek ist gerade belegt."); const auto selected = selection(root_); result.selection_token = selected.token; result.error = selected.error; if (fs::exists(root_ / "mods")) for (const auto &file : fs::directory_iterator(root_ / "mods")) { const auto name = editor::utf8(file.path().filename()); if (!name.starts_with('.')) result.entries.push_back(entry(root_, name)); } std::sort(result.entries.begin(), result.entries.end(), [](const auto &a, const auto &b) { return a.name < b.name; }); if (selected.active) { auto found = std::find_if(result.entries.begin(), result.entries.end(), [&](const auto &row) { return row.id == *selected.active && row.valid(); }); if (found != result.entries.end()) { found->active = true; result.active = found->id; } else if (result.error.empty()) result.error = "Die gespeicherte aktive Mod fehlt oder ist ungültig; keine Mod ist aktiviert."; } } catch (const std::exception &e) { result.error = e.what(); } return result; } ModImportPlan UiModLibrary::inspect(const fs::path &input, int start_year) const { if (start_year < 1900 || start_year > 9998) throw editor::Error("Ungültiges Startjahr."); const auto source = fs::absolute(input).lexically_normal(); if (fs::is_symlink(fs::symlink_status(source))) throw editor::Error("Verknüpfte Mod-Quellen werden nicht übernommen."); auto state = std::make_shared(); state->source = source; state->start_year = start_year; state->token = fingerprint(source); fs::path content = source; if (fs::is_directory(source) && fs::exists(source / "content.obw")) content /= "content.obw"; const bool world = fs::is_regular_file(content) && editor::folded(editor::utf8(content.extension())) != ".exe"; if (world || (fs::is_directory(content) && fs::exists(content / "manifest.json"))) { auto checked = package(content); state->archive = std::move(checked.archive); state->metadata = checked.metadata; } else { const auto checked = launch::check_game_directory(source); if (checked.family == launch::GameFamily::unknown || checked.family == launch::GameFamily::disk1994 || !checked.unsupported.empty() || !checked.problems.empty()) { std::string error = "Originalinstallation nicht unterstützt oder unvollständig."; if (!checked.unsupported.empty()) error += " " + checked.unsupported; for (const auto &problem : checked.problems) error += "\n" + problem; throw editor::Error(error); } if (fs::is_directory(source) && launch::find_file(checked.directory, "BMH.EXE") && launch::find_file(checked.directory, "FLTD.EXE")) throw editor::Error("Mehrdeutige Originalinstallation; bitte die gewünschte EXE auswählen."); state->source = checked.directory; state->original_exe = checked.exe; state->token = fingerprint(state->source); auto &row = state->metadata; row.type = "Classic"; row.source = checked.family == launch::GameFamily::english ? "FTLD" : "BMH"; row.name = row.source == "FTLD" ? "FLTD-classic" : "BMH-classic"; row.version = "Originalimport"; row.description = checked.title; row.format = "legacy-source"; for (const auto &file : fs::recursive_directory_iterator(state->source)) if (file.is_regular_file()) { ++row.file_count; row.bytes += file.file_size(); } } if (fingerprint(state->source) != state->token) throw editor::Error("Die Quelle wurde während der Prüfung geändert."); ModImportPlan plan; plan.metadata = state->metadata; plan.source = source; plan.source_token = state->token; plan.start_year = start_year; plan.payload_ = std::move(state); return plan; } UiModEntry UiModLibrary::commit(const ModImportPlan &plan, const std::string &raw_name, const ModProgress &progress) { const auto name = clean_name(raw_name); if (!plan.payload_) throw editor::Error("Der Importplan fehlt."); const auto &state = *plan.payload_; if (fingerprint(state.source) != state.token) throw editor::Error("Die Importquelle wurde inzwischen geändert. Bitte erneut auswählen."); directory(root_); available(root_, name); Temp temporary; const auto prepared = temporary.path / "content.obw"; if (progress) progress("Inhalte werden geprüft und vorbereitet …"); if (state.archive) state.archive->save(prepared, {}, {}); else { launch::AddMod request; request.source = state.original_exe; request.name = "prepared"; request.start_year = state.start_year; request.migrate = false; const auto converted = launch::ModLibrary(temporary.path).add(request, {}, progress); fs::copy_file(converted.mod.directory / "content.obw", prepared); } const auto checked = package(prepared); Lock lock(root_); recover(root_); available(root_, name); directory(root_ / "mods", true); const auto staging = root_ / "mods" / editor::path(editor::new_id(".ui-import-")); if (!fs::create_directory(staging)) throw editor::Error("Mod-Zwischenablage konnte nicht angelegt werden."); struct Cleanup { fs::path path; ~Cleanup() { std::error_code error; fs::remove_all(path, error); } } cleanup{staging}; fs::copy_file(prepared, staging / "content.obw"); // The existing Classic launcher owns a content-only directory contract. // Its verified package already contains all metadata needed by this UI. if (checked.metadata.type == "Modern") editor::write_atomic(staging / "mod.json", Json{{"schema", "openbmh-mod@1.0"}, {"name", name}, {"type", checked.metadata.type}, {"content_id", checked.metadata.content_id}, {"source", checked.metadata.source}}.dump(2)); if (progress) progress("Mod wird in die Bibliothek übernommen …"); if (fingerprint(state.source) != state.token) throw editor::Error("Die Importquelle wurde während der Vorbereitung geändert."); available(root_, name); fs::rename(staging, root_ / "mods" / editor::path(name)); return entry(root_, name); } void UiModLibrary::activate(const UiModEntry &expected, const std::string &token) { Lock lock(root_); recover(root_); directory(root_ / "mods"); const auto current = owned(root_, expected, true); selection_matches(root_, token); publish_selection(root_, current.id, content::sha256(editor::new_id("activate-"))); } void UiModLibrary::deactivate(const std::string &token) { Lock lock(root_); recover(root_); selection_matches(root_, token); publish_selection(root_, {}, content::sha256(editor::new_id("deactivate-"))); } UiModEntry UiModLibrary::rename(const UiModEntry &expected, const std::string &raw_name, const std::string &token) { const auto name = clean_name(raw_name); Lock lock(root_); recover(root_); directory(root_ / "mods"); const auto current = owned(root_, expected, false); selection_matches(root_, token); if (name == current.name) return current; available(root_, name, current.name); auto active = selection(root_).active; if (active == current.id) active = name; transact(root_, current, name, "rename", active, content::sha256(editor::new_id("rename-"))); return entry(root_, name); } void UiModLibrary::remove(const UiModEntry &expected, const std::string &token) { Lock lock(root_); recover(root_); directory(root_ / "mods"); const auto current = owned(root_, expected, false); selection_matches(root_, token); auto active = selection(root_).active; if (active == current.id) active.reset(); const auto nonce = content::sha256(editor::new_id("remove-")); transact(root_, current, ".ui-trash-" + nonce, "remove", active, nonce); } } // namespace bmh::modern_ui