registered_cache.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <regex>
  6. #include <mbedtls/sha256.h>
  7. #include "common/assert.h"
  8. #include "common/file_util.h"
  9. #include "common/hex_util.h"
  10. #include "common/logging/log.h"
  11. #include "core/crypto/key_manager.h"
  12. #include "core/file_sys/card_image.h"
  13. #include "core/file_sys/content_archive.h"
  14. #include "core/file_sys/nca_metadata.h"
  15. #include "core/file_sys/registered_cache.h"
  16. #include "core/file_sys/submission_package.h"
  17. #include "core/file_sys/vfs_concat.h"
  18. #include "core/loader/loader.h"
  19. namespace FileSys {
  20. // The size of blocks to use when vfs raw copying into nand.
  21. constexpr size_t VFS_RC_LARGE_COPY_BLOCK = 0x400000;
  22. std::string RegisteredCacheEntry::DebugInfo() const {
  23. return fmt::format("title_id={:016X}, content_type={:02X}", title_id, static_cast<u8>(type));
  24. }
  25. bool operator<(const RegisteredCacheEntry& lhs, const RegisteredCacheEntry& rhs) {
  26. return (lhs.title_id < rhs.title_id) || (lhs.title_id == rhs.title_id && lhs.type < rhs.type);
  27. }
  28. bool operator==(const RegisteredCacheEntry& lhs, const RegisteredCacheEntry& rhs) {
  29. return std::tie(lhs.title_id, lhs.type) == std::tie(rhs.title_id, rhs.type);
  30. }
  31. bool operator!=(const RegisteredCacheEntry& lhs, const RegisteredCacheEntry& rhs) {
  32. return !operator==(lhs, rhs);
  33. }
  34. static bool FollowsTwoDigitDirFormat(std::string_view name) {
  35. static const std::regex two_digit_regex("000000[0-9A-F]{2}", std::regex_constants::ECMAScript |
  36. std::regex_constants::icase);
  37. return std::regex_match(name.begin(), name.end(), two_digit_regex);
  38. }
  39. static bool FollowsNcaIdFormat(std::string_view name) {
  40. static const std::regex nca_id_regex("[0-9A-F]{32}\\.nca", std::regex_constants::ECMAScript |
  41. std::regex_constants::icase);
  42. return name.size() == 36 && std::regex_match(name.begin(), name.end(), nca_id_regex);
  43. }
  44. static std::string GetRelativePathFromNcaID(const std::array<u8, 16>& nca_id, bool second_hex_upper,
  45. bool within_two_digit) {
  46. if (!within_two_digit)
  47. return fmt::format("/{}.nca", Common::HexArrayToString(nca_id, second_hex_upper));
  48. Core::Crypto::SHA256Hash hash{};
  49. mbedtls_sha256(nca_id.data(), nca_id.size(), hash.data(), 0);
  50. return fmt::format("/000000{:02X}/{}.nca", hash[0],
  51. Common::HexArrayToString(nca_id, second_hex_upper));
  52. }
  53. static std::string GetCNMTName(TitleType type, u64 title_id) {
  54. constexpr std::array<const char*, 9> TITLE_TYPE_NAMES{
  55. "SystemProgram",
  56. "SystemData",
  57. "SystemUpdate",
  58. "BootImagePackage",
  59. "BootImagePackageSafe",
  60. "Application",
  61. "Patch",
  62. "AddOnContent",
  63. "" ///< Currently unknown 'DeltaTitle'
  64. };
  65. auto index = static_cast<std::size_t>(type);
  66. // If the index is after the jump in TitleType, subtract it out.
  67. if (index >= static_cast<std::size_t>(TitleType::Application)) {
  68. index -= static_cast<std::size_t>(TitleType::Application) -
  69. static_cast<std::size_t>(TitleType::FirmwarePackageB);
  70. }
  71. return fmt::format("{}_{:016x}.cnmt", TITLE_TYPE_NAMES[index], title_id);
  72. }
  73. static ContentRecordType GetCRTypeFromNCAType(NCAContentType type) {
  74. switch (type) {
  75. case NCAContentType::Program:
  76. // TODO(DarkLordZach): Differentiate between Program and Patch
  77. return ContentRecordType::Program;
  78. case NCAContentType::Meta:
  79. return ContentRecordType::Meta;
  80. case NCAContentType::Control:
  81. return ContentRecordType::Control;
  82. case NCAContentType::Data:
  83. case NCAContentType::Data_Unknown5:
  84. return ContentRecordType::Data;
  85. case NCAContentType::Manual:
  86. // TODO(DarkLordZach): Peek at NCA contents to differentiate Manual and Legal.
  87. return ContentRecordType::Manual;
  88. default:
  89. UNREACHABLE_MSG("Invalid NCAContentType={:02X}", static_cast<u8>(type));
  90. }
  91. }
  92. VirtualFile RegisteredCache::OpenFileOrDirectoryConcat(const VirtualDir& dir,
  93. std::string_view path) const {
  94. const auto file = dir->GetFileRelative(path);
  95. if (file != nullptr)
  96. return file;
  97. const auto nca_dir = dir->GetDirectoryRelative(path);
  98. if (nca_dir != nullptr) {
  99. const auto nca_dir = dir->GetDirectoryRelative(path);
  100. VirtualFile file = nullptr;
  101. const auto files = nca_dir->GetFiles();
  102. if (files.size() == 1 && files[0]->GetName() == "00") {
  103. file = files[0];
  104. } else {
  105. std::vector<VirtualFile> concat;
  106. // Since the files are a two-digit hex number, max is FF.
  107. for (std::size_t i = 0; i < 0x100; ++i) {
  108. auto next = nca_dir->GetFile(fmt::format("{:02X}", i));
  109. if (next != nullptr) {
  110. concat.push_back(std::move(next));
  111. } else {
  112. next = nca_dir->GetFile(fmt::format("{:02x}", i));
  113. if (next != nullptr)
  114. concat.push_back(std::move(next));
  115. else
  116. break;
  117. }
  118. }
  119. if (concat.empty())
  120. return nullptr;
  121. file = ConcatenatedVfsFile::MakeConcatenatedFile(concat, concat.front()->GetName());
  122. }
  123. return file;
  124. }
  125. return nullptr;
  126. }
  127. VirtualFile RegisteredCache::GetFileAtID(NcaID id) const {
  128. VirtualFile file;
  129. // Try all four modes of file storage:
  130. // (bit 1 = uppercase/lower, bit 0 = within a two-digit dir)
  131. // 00: /000000**/{:032X}.nca
  132. // 01: /{:032X}.nca
  133. // 10: /000000**/{:032x}.nca
  134. // 11: /{:032x}.nca
  135. for (u8 i = 0; i < 4; ++i) {
  136. const auto path = GetRelativePathFromNcaID(id, (i & 0b10) == 0, (i & 0b01) == 0);
  137. file = OpenFileOrDirectoryConcat(dir, path);
  138. if (file != nullptr)
  139. return file;
  140. }
  141. return file;
  142. }
  143. static std::optional<NcaID> CheckMapForContentRecord(
  144. const boost::container::flat_map<u64, CNMT>& map, u64 title_id, ContentRecordType type) {
  145. if (map.find(title_id) == map.end())
  146. return {};
  147. const auto& cnmt = map.at(title_id);
  148. const auto iter = std::find_if(cnmt.GetContentRecords().begin(), cnmt.GetContentRecords().end(),
  149. [type](const ContentRecord& rec) { return rec.type == type; });
  150. if (iter == cnmt.GetContentRecords().end())
  151. return {};
  152. return std::make_optional(iter->nca_id);
  153. }
  154. std::optional<NcaID> RegisteredCache::GetNcaIDFromMetadata(u64 title_id,
  155. ContentRecordType type) const {
  156. if (type == ContentRecordType::Meta && meta_id.find(title_id) != meta_id.end())
  157. return meta_id.at(title_id);
  158. const auto res1 = CheckMapForContentRecord(yuzu_meta, title_id, type);
  159. if (res1)
  160. return res1;
  161. return CheckMapForContentRecord(meta, title_id, type);
  162. }
  163. std::vector<NcaID> RegisteredCache::AccumulateFiles() const {
  164. std::vector<NcaID> ids;
  165. for (const auto& d2_dir : dir->GetSubdirectories()) {
  166. if (FollowsNcaIdFormat(d2_dir->GetName())) {
  167. ids.push_back(Common::HexStringToArray<0x10, true>(d2_dir->GetName().substr(0, 0x20)));
  168. continue;
  169. }
  170. if (!FollowsTwoDigitDirFormat(d2_dir->GetName()))
  171. continue;
  172. for (const auto& nca_dir : d2_dir->GetSubdirectories()) {
  173. if (!FollowsNcaIdFormat(nca_dir->GetName()))
  174. continue;
  175. ids.push_back(Common::HexStringToArray<0x10, true>(nca_dir->GetName().substr(0, 0x20)));
  176. }
  177. for (const auto& nca_file : d2_dir->GetFiles()) {
  178. if (!FollowsNcaIdFormat(nca_file->GetName()))
  179. continue;
  180. ids.push_back(
  181. Common::HexStringToArray<0x10, true>(nca_file->GetName().substr(0, 0x20)));
  182. }
  183. }
  184. for (const auto& d2_file : dir->GetFiles()) {
  185. if (FollowsNcaIdFormat(d2_file->GetName()))
  186. ids.push_back(Common::HexStringToArray<0x10, true>(d2_file->GetName().substr(0, 0x20)));
  187. }
  188. return ids;
  189. }
  190. void RegisteredCache::ProcessFiles(const std::vector<NcaID>& ids) {
  191. for (const auto& id : ids) {
  192. const auto file = GetFileAtID(id);
  193. if (file == nullptr)
  194. continue;
  195. const auto nca = std::make_shared<NCA>(parser(file, id), nullptr, 0, keys);
  196. if (nca->GetStatus() != Loader::ResultStatus::Success ||
  197. nca->GetType() != NCAContentType::Meta) {
  198. continue;
  199. }
  200. const auto section0 = nca->GetSubdirectories()[0];
  201. for (const auto& section0_file : section0->GetFiles()) {
  202. if (section0_file->GetExtension() != "cnmt")
  203. continue;
  204. meta.insert_or_assign(nca->GetTitleId(), CNMT(section0_file));
  205. meta_id.insert_or_assign(nca->GetTitleId(), id);
  206. break;
  207. }
  208. }
  209. }
  210. void RegisteredCache::AccumulateYuzuMeta() {
  211. const auto dir = this->dir->GetSubdirectory("yuzu_meta");
  212. if (dir == nullptr)
  213. return;
  214. for (const auto& file : dir->GetFiles()) {
  215. if (file->GetExtension() != "cnmt")
  216. continue;
  217. CNMT cnmt(file);
  218. yuzu_meta.insert_or_assign(cnmt.GetTitleID(), std::move(cnmt));
  219. }
  220. }
  221. void RegisteredCache::Refresh() {
  222. if (dir == nullptr)
  223. return;
  224. const auto ids = AccumulateFiles();
  225. ProcessFiles(ids);
  226. AccumulateYuzuMeta();
  227. }
  228. RegisteredCache::RegisteredCache(VirtualDir dir_, RegisteredCacheParsingFunction parsing_function)
  229. : dir(std::move(dir_)), parser(std::move(parsing_function)) {
  230. Refresh();
  231. }
  232. RegisteredCache::~RegisteredCache() = default;
  233. bool RegisteredCache::HasEntry(u64 title_id, ContentRecordType type) const {
  234. return GetEntryRaw(title_id, type) != nullptr;
  235. }
  236. bool RegisteredCache::HasEntry(RegisteredCacheEntry entry) const {
  237. return GetEntryRaw(entry) != nullptr;
  238. }
  239. VirtualFile RegisteredCache::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
  240. const auto id = GetNcaIDFromMetadata(title_id, type);
  241. return id ? GetFileAtID(*id) : nullptr;
  242. }
  243. VirtualFile RegisteredCache::GetEntryUnparsed(RegisteredCacheEntry entry) const {
  244. return GetEntryUnparsed(entry.title_id, entry.type);
  245. }
  246. std::optional<u32> RegisteredCache::GetEntryVersion(u64 title_id) const {
  247. const auto meta_iter = meta.find(title_id);
  248. if (meta_iter != meta.end())
  249. return meta_iter->second.GetTitleVersion();
  250. const auto yuzu_meta_iter = yuzu_meta.find(title_id);
  251. if (yuzu_meta_iter != yuzu_meta.end())
  252. return yuzu_meta_iter->second.GetTitleVersion();
  253. return {};
  254. }
  255. VirtualFile RegisteredCache::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  256. const auto id = GetNcaIDFromMetadata(title_id, type);
  257. return id ? parser(GetFileAtID(*id), *id) : nullptr;
  258. }
  259. VirtualFile RegisteredCache::GetEntryRaw(RegisteredCacheEntry entry) const {
  260. return GetEntryRaw(entry.title_id, entry.type);
  261. }
  262. std::unique_ptr<NCA> RegisteredCache::GetEntry(u64 title_id, ContentRecordType type) const {
  263. const auto raw = GetEntryRaw(title_id, type);
  264. if (raw == nullptr)
  265. return nullptr;
  266. return std::make_unique<NCA>(raw, nullptr, 0, keys);
  267. }
  268. std::unique_ptr<NCA> RegisteredCache::GetEntry(RegisteredCacheEntry entry) const {
  269. return GetEntry(entry.title_id, entry.type);
  270. }
  271. template <typename T>
  272. void RegisteredCache::IterateAllMetadata(
  273. std::vector<T>& out, std::function<T(const CNMT&, const ContentRecord&)> proc,
  274. std::function<bool(const CNMT&, const ContentRecord&)> filter) const {
  275. for (const auto& kv : meta) {
  276. const auto& cnmt = kv.second;
  277. if (filter(cnmt, EMPTY_META_CONTENT_RECORD))
  278. out.push_back(proc(cnmt, EMPTY_META_CONTENT_RECORD));
  279. for (const auto& rec : cnmt.GetContentRecords()) {
  280. if (GetFileAtID(rec.nca_id) != nullptr && filter(cnmt, rec)) {
  281. out.push_back(proc(cnmt, rec));
  282. }
  283. }
  284. }
  285. for (const auto& kv : yuzu_meta) {
  286. const auto& cnmt = kv.second;
  287. for (const auto& rec : cnmt.GetContentRecords()) {
  288. if (GetFileAtID(rec.nca_id) != nullptr && filter(cnmt, rec)) {
  289. out.push_back(proc(cnmt, rec));
  290. }
  291. }
  292. }
  293. }
  294. std::vector<RegisteredCacheEntry> RegisteredCache::ListEntries() const {
  295. std::vector<RegisteredCacheEntry> out;
  296. IterateAllMetadata<RegisteredCacheEntry>(
  297. out,
  298. [](const CNMT& c, const ContentRecord& r) {
  299. return RegisteredCacheEntry{c.GetTitleID(), r.type};
  300. },
  301. [](const CNMT& c, const ContentRecord& r) { return true; });
  302. return out;
  303. }
  304. std::vector<RegisteredCacheEntry> RegisteredCache::ListEntriesFilter(
  305. std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
  306. std::optional<u64> title_id) const {
  307. std::vector<RegisteredCacheEntry> out;
  308. IterateAllMetadata<RegisteredCacheEntry>(
  309. out,
  310. [](const CNMT& c, const ContentRecord& r) {
  311. return RegisteredCacheEntry{c.GetTitleID(), r.type};
  312. },
  313. [&title_type, &record_type, &title_id](const CNMT& c, const ContentRecord& r) {
  314. if (title_type && *title_type != c.GetType())
  315. return false;
  316. if (record_type && *record_type != r.type)
  317. return false;
  318. if (title_id && *title_id != c.GetTitleID())
  319. return false;
  320. return true;
  321. });
  322. return out;
  323. }
  324. static std::shared_ptr<NCA> GetNCAFromNSPForID(std::shared_ptr<NSP> nsp, const NcaID& id) {
  325. const auto file = nsp->GetFile(fmt::format("{}.nca", Common::HexArrayToString(id, false)));
  326. if (file == nullptr)
  327. return nullptr;
  328. return std::make_shared<NCA>(file);
  329. }
  330. InstallResult RegisteredCache::InstallEntry(std::shared_ptr<XCI> xci, bool overwrite_if_exists,
  331. const VfsCopyFunction& copy) {
  332. return InstallEntry(xci->GetSecurePartitionNSP(), overwrite_if_exists, copy);
  333. }
  334. InstallResult RegisteredCache::InstallEntry(std::shared_ptr<NSP> nsp, bool overwrite_if_exists,
  335. const VfsCopyFunction& copy) {
  336. const auto& ncas = nsp->GetNCAsCollapsed();
  337. const auto& meta_iter = std::find_if(ncas.begin(), ncas.end(), [](std::shared_ptr<NCA> nca) {
  338. return nca->GetType() == NCAContentType::Meta;
  339. });
  340. if (meta_iter == ncas.end()) {
  341. LOG_ERROR(Loader, "The XCI you are attempting to install does not have a metadata NCA and "
  342. "is therefore malformed. Double check your encryption keys.");
  343. return InstallResult::ErrorMetaFailed;
  344. }
  345. // Install Metadata File
  346. const auto meta_id_raw = (*meta_iter)->GetName().substr(0, 32);
  347. const auto meta_id = Common::HexStringToArray<16>(meta_id_raw);
  348. const auto res = RawInstallNCA(*meta_iter, copy, overwrite_if_exists, meta_id);
  349. if (res != InstallResult::Success)
  350. return res;
  351. // Install all the other NCAs
  352. const auto section0 = (*meta_iter)->GetSubdirectories()[0];
  353. const auto cnmt_file = section0->GetFiles()[0];
  354. const CNMT cnmt(cnmt_file);
  355. for (const auto& record : cnmt.GetContentRecords()) {
  356. const auto nca = GetNCAFromNSPForID(nsp, record.nca_id);
  357. if (nca == nullptr)
  358. return InstallResult::ErrorCopyFailed;
  359. const auto res2 = RawInstallNCA(nca, copy, overwrite_if_exists, record.nca_id);
  360. if (res2 != InstallResult::Success)
  361. return res2;
  362. }
  363. Refresh();
  364. return InstallResult::Success;
  365. }
  366. InstallResult RegisteredCache::InstallEntry(std::shared_ptr<NCA> nca, TitleType type,
  367. bool overwrite_if_exists, const VfsCopyFunction& copy) {
  368. CNMTHeader header{
  369. nca->GetTitleId(), ///< Title ID
  370. 0, ///< Ignore/Default title version
  371. type, ///< Type
  372. {}, ///< Padding
  373. 0x10, ///< Default table offset
  374. 1, ///< 1 Content Entry
  375. 0, ///< No Meta Entries
  376. {}, ///< Padding
  377. };
  378. OptionalHeader opt_header{0, 0};
  379. ContentRecord c_rec{{}, {}, {}, GetCRTypeFromNCAType(nca->GetType()), {}};
  380. const auto& data = nca->GetBaseFile()->ReadBytes(0x100000);
  381. mbedtls_sha256(data.data(), data.size(), c_rec.hash.data(), 0);
  382. memcpy(&c_rec.nca_id, &c_rec.hash, 16);
  383. const CNMT new_cnmt(header, opt_header, {c_rec}, {});
  384. if (!RawInstallYuzuMeta(new_cnmt))
  385. return InstallResult::ErrorMetaFailed;
  386. return RawInstallNCA(nca, copy, overwrite_if_exists, c_rec.nca_id);
  387. }
  388. InstallResult RegisteredCache::RawInstallNCA(std::shared_ptr<NCA> nca, const VfsCopyFunction& copy,
  389. bool overwrite_if_exists,
  390. std::optional<NcaID> override_id) {
  391. const auto in = nca->GetBaseFile();
  392. Core::Crypto::SHA256Hash hash{};
  393. // Calculate NcaID
  394. // NOTE: Because computing the SHA256 of an entire NCA is quite expensive (especially if the
  395. // game is massive), we're going to cheat and only hash the first MB of the NCA.
  396. // Also, for XCIs the NcaID matters, so if the override id isn't none, use that.
  397. NcaID id{};
  398. if (override_id) {
  399. id = *override_id;
  400. } else {
  401. const auto& data = in->ReadBytes(0x100000);
  402. mbedtls_sha256(data.data(), data.size(), hash.data(), 0);
  403. memcpy(id.data(), hash.data(), 16);
  404. }
  405. std::string path = GetRelativePathFromNcaID(id, false, true);
  406. if (GetFileAtID(id) != nullptr && !overwrite_if_exists) {
  407. LOG_WARNING(Loader, "Attempting to overwrite existing NCA. Skipping...");
  408. return InstallResult::ErrorAlreadyExists;
  409. }
  410. if (GetFileAtID(id) != nullptr) {
  411. LOG_WARNING(Loader, "Overwriting existing NCA...");
  412. VirtualDir c_dir;
  413. { c_dir = dir->GetFileRelative(path)->GetContainingDirectory(); }
  414. c_dir->DeleteFile(FileUtil::GetFilename(path));
  415. }
  416. auto out = dir->CreateFileRelative(path);
  417. if (out == nullptr)
  418. return InstallResult::ErrorCopyFailed;
  419. return copy(in, out, VFS_RC_LARGE_COPY_BLOCK) ? InstallResult::Success
  420. : InstallResult::ErrorCopyFailed;
  421. }
  422. bool RegisteredCache::RawInstallYuzuMeta(const CNMT& cnmt) {
  423. // Reasoning behind this method can be found in the comment for InstallEntry, NCA overload.
  424. const auto dir = this->dir->CreateDirectoryRelative("yuzu_meta");
  425. const auto filename = GetCNMTName(cnmt.GetType(), cnmt.GetTitleID());
  426. if (dir->GetFile(filename) == nullptr) {
  427. auto out = dir->CreateFile(filename);
  428. const auto buffer = cnmt.Serialize();
  429. out->Resize(buffer.size());
  430. out->WriteBytes(buffer);
  431. } else {
  432. auto out = dir->GetFile(filename);
  433. CNMT old_cnmt(out);
  434. // Returns true on change
  435. if (old_cnmt.UnionRecords(cnmt)) {
  436. out->Resize(0);
  437. const auto buffer = old_cnmt.Serialize();
  438. out->Resize(buffer.size());
  439. out->WriteBytes(buffer);
  440. }
  441. }
  442. Refresh();
  443. return std::find_if(yuzu_meta.begin(), yuzu_meta.end(),
  444. [&cnmt](const std::pair<u64, CNMT>& kv) {
  445. return kv.second.GetType() == cnmt.GetType() &&
  446. kv.second.GetTitleID() == cnmt.GetTitleID();
  447. }) != yuzu_meta.end();
  448. }
  449. RegisteredCacheUnion::RegisteredCacheUnion(std::vector<RegisteredCache*> caches)
  450. : caches(std::move(caches)) {}
  451. void RegisteredCacheUnion::Refresh() {
  452. for (const auto& c : caches)
  453. c->Refresh();
  454. }
  455. bool RegisteredCacheUnion::HasEntry(u64 title_id, ContentRecordType type) const {
  456. return std::any_of(caches.begin(), caches.end(), [title_id, type](const auto& cache) {
  457. return cache->HasEntry(title_id, type);
  458. });
  459. }
  460. bool RegisteredCacheUnion::HasEntry(RegisteredCacheEntry entry) const {
  461. return HasEntry(entry.title_id, entry.type);
  462. }
  463. std::optional<u32> RegisteredCacheUnion::GetEntryVersion(u64 title_id) const {
  464. for (const auto& c : caches) {
  465. const auto res = c->GetEntryVersion(title_id);
  466. if (res)
  467. return res;
  468. }
  469. return {};
  470. }
  471. VirtualFile RegisteredCacheUnion::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
  472. for (const auto& c : caches) {
  473. const auto res = c->GetEntryUnparsed(title_id, type);
  474. if (res != nullptr)
  475. return res;
  476. }
  477. return nullptr;
  478. }
  479. VirtualFile RegisteredCacheUnion::GetEntryUnparsed(RegisteredCacheEntry entry) const {
  480. return GetEntryUnparsed(entry.title_id, entry.type);
  481. }
  482. VirtualFile RegisteredCacheUnion::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  483. for (const auto& c : caches) {
  484. const auto res = c->GetEntryRaw(title_id, type);
  485. if (res != nullptr)
  486. return res;
  487. }
  488. return nullptr;
  489. }
  490. VirtualFile RegisteredCacheUnion::GetEntryRaw(RegisteredCacheEntry entry) const {
  491. return GetEntryRaw(entry.title_id, entry.type);
  492. }
  493. std::unique_ptr<NCA> RegisteredCacheUnion::GetEntry(u64 title_id, ContentRecordType type) const {
  494. const auto raw = GetEntryRaw(title_id, type);
  495. if (raw == nullptr)
  496. return nullptr;
  497. return std::make_unique<NCA>(raw);
  498. }
  499. std::unique_ptr<NCA> RegisteredCacheUnion::GetEntry(RegisteredCacheEntry entry) const {
  500. return GetEntry(entry.title_id, entry.type);
  501. }
  502. std::vector<RegisteredCacheEntry> RegisteredCacheUnion::ListEntries() const {
  503. std::vector<RegisteredCacheEntry> out;
  504. for (const auto& c : caches) {
  505. c->IterateAllMetadata<RegisteredCacheEntry>(
  506. out,
  507. [](const CNMT& c, const ContentRecord& r) {
  508. return RegisteredCacheEntry{c.GetTitleID(), r.type};
  509. },
  510. [](const CNMT& c, const ContentRecord& r) { return true; });
  511. }
  512. std::sort(out.begin(), out.end());
  513. out.erase(std::unique(out.begin(), out.end()), out.end());
  514. return out;
  515. }
  516. std::vector<RegisteredCacheEntry> RegisteredCacheUnion::ListEntriesFilter(
  517. std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
  518. std::optional<u64> title_id) const {
  519. std::vector<RegisteredCacheEntry> out;
  520. for (const auto& c : caches) {
  521. c->IterateAllMetadata<RegisteredCacheEntry>(
  522. out,
  523. [](const CNMT& c, const ContentRecord& r) {
  524. return RegisteredCacheEntry{c.GetTitleID(), r.type};
  525. },
  526. [&title_type, &record_type, &title_id](const CNMT& c, const ContentRecord& r) {
  527. if (title_type && *title_type != c.GetType())
  528. return false;
  529. if (record_type && *record_type != r.type)
  530. return false;
  531. if (title_id && *title_id != c.GetTitleID())
  532. return false;
  533. return true;
  534. });
  535. }
  536. std::sort(out.begin(), out.end());
  537. out.erase(std::unique(out.begin(), out.end()), out.end());
  538. return out;
  539. }
  540. } // namespace FileSys