content_manager.h 14 KB

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