summaryrefslogtreecommitdiff
path: root/src/frontend_common/content_manager.h
diff options
context:
space:
mode:
Diffstat (limited to 'src/frontend_common/content_manager.h')
-rw-r--r--src/frontend_common/content_manager.h379
1 files changed, 379 insertions, 0 deletions
diff --git a/src/frontend_common/content_manager.h b/src/frontend_common/content_manager.h
new file mode 100644
index 000000000..f3efe3465
--- /dev/null
+++ b/src/frontend_common/content_manager.h
@@ -0,0 +1,379 @@
1// SPDX-FileCopyrightText: 2024 yuzu Emulator Project
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#pragma once
5
6#include <boost/algorithm/string.hpp>
7#include "common/common_types.h"
8#include "common/literals.h"
9#include "core/core.h"
10#include "core/file_sys/common_funcs.h"
11#include "core/file_sys/content_archive.h"
12#include "core/file_sys/fs_filesystem.h"
13#include "core/file_sys/nca_metadata.h"
14#include "core/file_sys/patch_manager.h"
15#include "core/file_sys/registered_cache.h"
16#include "core/file_sys/submission_package.h"
17#include "core/hle/service/filesystem/filesystem.h"
18#include "core/loader/loader.h"
19#include "core/loader/nca.h"
20
21namespace ContentManager {
22
23enum class InstallResult {
24 Success,
25 Overwrite,
26 Failure,
27 BaseInstallAttempted,
28};
29
30enum class GameVerificationResult {
31 Success,
32 Failed,
33 NotImplemented,
34};
35
36/**
37 * \brief Removes a single installed DLC
38 * \param fs_controller [FileSystemController] reference from the Core::System instance
39 * \param title_id Unique title ID representing the DLC which will be removed
40 * \return 'true' if successful
41 */
42inline bool RemoveDLC(const Service::FileSystem::FileSystemController& fs_controller,
43 const u64 title_id) {
44 return fs_controller.GetUserNANDContents()->RemoveExistingEntry(title_id) ||
45 fs_controller.GetSDMCContents()->RemoveExistingEntry(title_id);
46}
47
48/**
49 * \brief Removes all DLC for a game
50 * \param system Reference to the system instance
51 * \param program_id Program ID for the game that will have all of its DLC removed
52 * \return Number of DLC removed
53 */
54inline size_t RemoveAllDLC(Core::System& system, const u64 program_id) {
55 size_t count{};
56 const auto& fs_controller = system.GetFileSystemController();
57 const auto dlc_entries = system.GetContentProvider().ListEntriesFilter(
58 FileSys::TitleType::AOC, FileSys::ContentRecordType::Data);
59 std::vector<u64> program_dlc_entries;
60
61 for (const auto& entry : dlc_entries) {
62 if (FileSys::GetBaseTitleID(entry.title_id) == program_id) {
63 program_dlc_entries.push_back(entry.title_id);
64 }
65 }
66
67 for (const auto& entry : program_dlc_entries) {
68 if (RemoveDLC(fs_controller, entry)) {
69 ++count;
70 }
71 }
72 return count;
73}
74
75/**
76 * \brief Removes the installed update for a game
77 * \param fs_controller [FileSystemController] reference from the Core::System instance
78 * \param program_id Program ID for the game that will have its installed update removed
79 * \return 'true' if successful
80 */
81inline bool RemoveUpdate(const Service::FileSystem::FileSystemController& fs_controller,
82 const u64 program_id) {
83 const auto update_id = program_id | 0x800;
84 return fs_controller.GetUserNANDContents()->RemoveExistingEntry(update_id) ||
85 fs_controller.GetSDMCContents()->RemoveExistingEntry(update_id);
86}
87
88/**
89 * \brief Removes the base content for a game
90 * \param fs_controller [FileSystemController] reference from the Core::System instance
91 * \param program_id Program ID for the game that will have its base content removed
92 * \return 'true' if successful
93 */
94inline bool RemoveBaseContent(const Service::FileSystem::FileSystemController& fs_controller,
95 const u64 program_id) {
96 return fs_controller.GetUserNANDContents()->RemoveExistingEntry(program_id) ||
97 fs_controller.GetSDMCContents()->RemoveExistingEntry(program_id);
98}
99
100/**
101 * \brief Removes a mod for a game
102 * \param fs_controller [FileSystemController] reference from the Core::System instance
103 * \param program_id Program ID for the game where [mod_name] will be removed
104 * \param mod_name The name of a mod as given by FileSys::PatchManager::GetPatches. This corresponds
105 * with the name of the mod's directory in a game's load folder.
106 * \return 'true' if successful
107 */
108inline bool RemoveMod(const Service::FileSystem::FileSystemController& fs_controller,
109 const u64 program_id, const std::string& mod_name) {
110 // Check general Mods (LayeredFS and IPS)
111 const auto mod_dir = fs_controller.GetModificationLoadRoot(program_id);
112 if (mod_dir != nullptr) {
113 return mod_dir->DeleteSubdirectoryRecursive(mod_name);
114 }
115
116 // Check SDMC mod directory (RomFS LayeredFS)
117 const auto sdmc_mod_dir = fs_controller.GetSDMCModificationLoadRoot(program_id);
118 if (sdmc_mod_dir != nullptr) {
119 return sdmc_mod_dir->DeleteSubdirectoryRecursive(mod_name);
120 }
121
122 return false;
123}
124
125/**
126 * \brief Installs an NSP
127 * \param system Reference to the system instance
128 * \param vfs Reference to the VfsFilesystem instance in Core::System
129 * \param filename Path to the NSP file
130 * \param callback Callback to report the progress of the installation. The first size_t
131 * parameter is the total size of the virtual file and the second is the current progress. If you
132 * return true to the callback, it will cancel the installation as soon as possible.
133 * \return [InstallResult] representing how the installation finished
134 */
135inline InstallResult InstallNSP(Core::System& system, FileSys::VfsFilesystem& vfs,
136 const std::string& filename,
137 const std::function<bool(size_t, size_t)>& callback) {
138 const auto copy = [callback](const FileSys::VirtualFile& src, const FileSys::VirtualFile& dest,
139 std::size_t block_size) {
140 if (src == nullptr || dest == nullptr) {
141 return false;
142 }
143 if (!dest->Resize(src->GetSize())) {
144 return false;
145 }
146
147 using namespace Common::Literals;
148 std::vector<u8> buffer(1_MiB);
149
150 for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
151 if (callback(src->GetSize(), i)) {
152 dest->Resize(0);
153 return false;
154 }
155 const auto read = src->Read(buffer.data(), buffer.size(), i);
156 dest->Write(buffer.data(), read, i);
157 }
158 return true;
159 };
160
161 std::shared_ptr<FileSys::NSP> nsp;
162 FileSys::VirtualFile file = vfs.OpenFile(filename, FileSys::OpenMode::Read);
163 if (boost::to_lower_copy(file->GetName()).ends_with(std::string("nsp"))) {
164 nsp = std::make_shared<FileSys::NSP>(file);
165 if (nsp->IsExtractedType()) {
166 return InstallResult::Failure;
167 }
168 } else {
169 return InstallResult::Failure;
170 }
171
172 if (nsp->GetStatus() != Loader::ResultStatus::Success) {
173 return InstallResult::Failure;
174 }
175 const auto res =
176 system.GetFileSystemController().GetUserNANDContents()->InstallEntry(*nsp, true, copy);
177 switch (res) {
178 case FileSys::InstallResult::Success:
179 return InstallResult::Success;
180 case FileSys::InstallResult::OverwriteExisting:
181 return InstallResult::Overwrite;
182 case FileSys::InstallResult::ErrorBaseInstall:
183 return InstallResult::BaseInstallAttempted;
184 default:
185 return InstallResult::Failure;
186 }
187}
188
189/**
190 * \brief Installs an NCA
191 * \param vfs Reference to the VfsFilesystem instance in Core::System
192 * \param filename Path to the NCA file
193 * \param registered_cache Reference to the registered cache that the NCA will be installed to
194 * \param title_type Type of NCA package to install
195 * \param callback Callback to report the progress of the installation. The first size_t
196 * parameter is the total size of the virtual file and the second is the current progress. If you
197 * return true to the callback, it will cancel the installation as soon as possible.
198 * \return [InstallResult] representing how the installation finished
199 */
200inline InstallResult InstallNCA(FileSys::VfsFilesystem& vfs, const std::string& filename,
201 FileSys::RegisteredCache& registered_cache,
202 const FileSys::TitleType title_type,
203 const std::function<bool(size_t, size_t)>& callback) {
204 const auto copy = [callback](const FileSys::VirtualFile& src, const FileSys::VirtualFile& dest,
205 std::size_t block_size) {
206 if (src == nullptr || dest == nullptr) {
207 return false;
208 }
209 if (!dest->Resize(src->GetSize())) {
210 return false;
211 }
212
213 using namespace Common::Literals;
214 std::vector<u8> buffer(1_MiB);
215
216 for (std::size_t i = 0; i < src->GetSize(); i += buffer.size()) {
217 if (callback(src->GetSize(), i)) {
218 dest->Resize(0);
219 return false;
220 }
221 const auto read = src->Read(buffer.data(), buffer.size(), i);
222 dest->Write(buffer.data(), read, i);
223 }
224 return true;
225 };
226
227 const auto nca =
228 std::make_shared<FileSys::NCA>(vfs.OpenFile(filename, FileSys::OpenMode::Read));
229 const auto id = nca->GetStatus();
230
231 // Game updates necessary are missing base RomFS
232 if (id != Loader::ResultStatus::Success &&
233 id != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
234 return InstallResult::Failure;
235 }
236
237 const auto res = registered_cache.InstallEntry(*nca, title_type, true, copy);
238 if (res == FileSys::InstallResult::Success) {
239 return InstallResult::Success;
240 } else if (res == FileSys::InstallResult::OverwriteExisting) {
241 return InstallResult::Overwrite;
242 } else {
243 return InstallResult::Failure;
244 }
245}
246
247/**
248 * \brief Verifies the installed contents for a given ManualContentProvider
249 * \param system Reference to the system instance
250 * \param provider Reference to the content provider that's tracking indexed games
251 * \param callback Callback to report the progress of the installation. The first size_t
252 * parameter is the total size of the installed contents and the second is the current progress. If
253 * you return true to the callback, it will cancel the installation as soon as possible.
254 * \return A list of entries that failed to install. Returns an empty vector if successful.
255 */
256inline std::vector<std::string> VerifyInstalledContents(
257 Core::System& system, FileSys::ManualContentProvider& provider,
258 const std::function<bool(size_t, size_t)>& callback) {
259 // Get content registries.
260 auto bis_contents = system.GetFileSystemController().GetSystemNANDContents();
261 auto user_contents = system.GetFileSystemController().GetUserNANDContents();
262
263 std::vector<FileSys::RegisteredCache*> content_providers;
264 if (bis_contents) {
265 content_providers.push_back(bis_contents);
266 }
267 if (user_contents) {
268 content_providers.push_back(user_contents);
269 }
270
271 // Get associated NCA files.
272 std::vector<FileSys::VirtualFile> nca_files;
273
274 // Get all installed IDs.
275 size_t total_size = 0;
276 for (auto nca_provider : content_providers) {
277 const auto entries = nca_provider->ListEntriesFilter();
278
279 for (const auto& entry : entries) {
280 auto nca_file = nca_provider->GetEntryRaw(entry.title_id, entry.type);
281 if (!nca_file) {
282 continue;
283 }
284
285 total_size += nca_file->GetSize();
286 nca_files.push_back(std::move(nca_file));
287 }
288 }
289
290 // Declare a list of file names which failed to verify.
291 std::vector<std::string> failed;
292
293 size_t processed_size = 0;
294 bool cancelled = false;
295 auto nca_callback = [&](size_t nca_processed, size_t nca_total) {
296 cancelled = callback(total_size, processed_size + nca_processed);
297 return !cancelled;
298 };
299
300 // Using the NCA loader, determine if all NCAs are valid.
301 for (auto& nca_file : nca_files) {
302 Loader::AppLoader_NCA nca_loader(nca_file);
303
304 auto status = nca_loader.VerifyIntegrity(nca_callback);
305 if (cancelled) {
306 break;
307 }
308 if (status != Loader::ResultStatus::Success) {
309 FileSys::NCA nca(nca_file);
310 const auto title_id = nca.GetTitleId();
311 std::string title_name = "unknown";
312
313 const auto control = provider.GetEntry(FileSys::GetBaseTitleID(title_id),
314 FileSys::ContentRecordType::Control);
315 if (control && control->GetStatus() == Loader::ResultStatus::Success) {
316 const FileSys::PatchManager pm{title_id, system.GetFileSystemController(),
317 provider};
318 const auto [nacp, logo] = pm.ParseControlNCA(*control);
319 if (nacp) {
320 title_name = nacp->GetApplicationName();
321 }
322 }
323
324 if (title_id > 0) {
325 failed.push_back(
326 fmt::format("{} ({:016X}) ({})", nca_file->GetName(), title_id, title_name));
327 } else {
328 failed.push_back(fmt::format("{} (unknown)", nca_file->GetName()));
329 }
330 }
331
332 processed_size += nca_file->GetSize();
333 }
334 return failed;
335}
336
337/**
338 * \brief Verifies the contents of a given game
339 * \param system Reference to the system instance
340 * \param game_path Patch to the game file
341 * \param callback Callback to report the progress of the installation. The first size_t
342 * parameter is the total size of the installed contents and the second is the current progress. If
343 * you return true to the callback, it will cancel the installation as soon as possible.
344 * \return GameVerificationResult representing how the verification process finished
345 */
346inline GameVerificationResult VerifyGameContents(
347 Core::System& system, const std::string& game_path,
348 const std::function<bool(size_t, size_t)>& callback) {
349 const auto loader = Loader::GetLoader(
350 system, system.GetFilesystem()->OpenFile(game_path, FileSys::OpenMode::Read));
351 if (loader == nullptr) {
352 return GameVerificationResult::NotImplemented;
353 }
354
355 bool cancelled = false;
356 auto loader_callback = [&](size_t processed, size_t total) {
357 cancelled = callback(total, processed);
358 return !cancelled;
359 };
360
361 const auto status = loader->VerifyIntegrity(loader_callback);
362 if (cancelled || status == Loader::ResultStatus::ErrorIntegrityVerificationNotImplemented) {
363 return GameVerificationResult::NotImplemented;
364 }
365
366 if (status == Loader::ResultStatus::ErrorIntegrityVerificationFailed) {
367 return GameVerificationResult::Failed;
368 }
369 return GameVerificationResult::Success;
370}
371
372/**
373 * Checks if the keys required for decrypting firmware and games are available
374 */
375inline bool AreKeysPresent() {
376 return !Core::Crypto::KeyManager::Instance().BaseDeriveNecessary();
377}
378
379} // namespace ContentManager