registered_cache.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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. }
  98. const auto nca_dir = dir->GetDirectoryRelative(path);
  99. if (nca_dir == nullptr) {
  100. return nullptr;
  101. }
  102. const auto files = nca_dir->GetFiles();
  103. if (files.size() == 1 && files[0]->GetName() == "00") {
  104. return files[0];
  105. }
  106. std::vector<VirtualFile> concat;
  107. // Since the files are a two-digit hex number, max is FF.
  108. for (std::size_t i = 0; i < 0x100; ++i) {
  109. auto next = nca_dir->GetFile(fmt::format("{:02X}", i));
  110. if (next != nullptr) {
  111. concat.push_back(std::move(next));
  112. } else {
  113. next = nca_dir->GetFile(fmt::format("{:02x}", i));
  114. if (next != nullptr) {
  115. concat.push_back(std::move(next));
  116. } else {
  117. break;
  118. }
  119. }
  120. }
  121. if (concat.empty()) {
  122. return nullptr;
  123. }
  124. return ConcatenatedVfsFile::MakeConcatenatedFile(concat, concat.front()->GetName());
  125. }
  126. VirtualFile RegisteredCache::GetFileAtID(NcaID id) const {
  127. VirtualFile file;
  128. // Try all four modes of file storage:
  129. // (bit 1 = uppercase/lower, bit 0 = within a two-digit dir)
  130. // 00: /000000**/{:032X}.nca
  131. // 01: /{:032X}.nca
  132. // 10: /000000**/{:032x}.nca
  133. // 11: /{:032x}.nca
  134. for (u8 i = 0; i < 4; ++i) {
  135. const auto path = GetRelativePathFromNcaID(id, (i & 0b10) == 0, (i & 0b01) == 0);
  136. file = OpenFileOrDirectoryConcat(dir, path);
  137. if (file != nullptr)
  138. return file;
  139. }
  140. return file;
  141. }
  142. static std::optional<NcaID> CheckMapForContentRecord(
  143. const boost::container::flat_map<u64, CNMT>& map, u64 title_id, ContentRecordType type) {
  144. if (map.find(title_id) == map.end())
  145. return {};
  146. const auto& cnmt = map.at(title_id);
  147. const auto iter = std::find_if(cnmt.GetContentRecords().begin(), cnmt.GetContentRecords().end(),
  148. [type](const ContentRecord& rec) { return rec.type == type; });
  149. if (iter == cnmt.GetContentRecords().end())
  150. return {};
  151. return std::make_optional(iter->nca_id);
  152. }
  153. std::optional<NcaID> RegisteredCache::GetNcaIDFromMetadata(u64 title_id,
  154. ContentRecordType type) const {
  155. if (type == ContentRecordType::Meta && meta_id.find(title_id) != meta_id.end())
  156. return meta_id.at(title_id);
  157. const auto res1 = CheckMapForContentRecord(yuzu_meta, title_id, type);
  158. if (res1)
  159. return res1;
  160. return CheckMapForContentRecord(meta, title_id, type);
  161. }
  162. std::vector<NcaID> RegisteredCache::AccumulateFiles() const {
  163. std::vector<NcaID> ids;
  164. for (const auto& d2_dir : dir->GetSubdirectories()) {
  165. if (FollowsNcaIdFormat(d2_dir->GetName())) {
  166. ids.push_back(Common::HexStringToArray<0x10, true>(d2_dir->GetName().substr(0, 0x20)));
  167. continue;
  168. }
  169. if (!FollowsTwoDigitDirFormat(d2_dir->GetName()))
  170. continue;
  171. for (const auto& nca_dir : d2_dir->GetSubdirectories()) {
  172. if (!FollowsNcaIdFormat(nca_dir->GetName()))
  173. continue;
  174. ids.push_back(Common::HexStringToArray<0x10, true>(nca_dir->GetName().substr(0, 0x20)));
  175. }
  176. for (const auto& nca_file : d2_dir->GetFiles()) {
  177. if (!FollowsNcaIdFormat(nca_file->GetName()))
  178. continue;
  179. ids.push_back(
  180. Common::HexStringToArray<0x10, true>(nca_file->GetName().substr(0, 0x20)));
  181. }
  182. }
  183. for (const auto& d2_file : dir->GetFiles()) {
  184. if (FollowsNcaIdFormat(d2_file->GetName()))
  185. ids.push_back(Common::HexStringToArray<0x10, true>(d2_file->GetName().substr(0, 0x20)));
  186. }
  187. return ids;
  188. }
  189. void RegisteredCache::ProcessFiles(const std::vector<NcaID>& ids) {
  190. for (const auto& id : ids) {
  191. const auto file = GetFileAtID(id);
  192. if (file == nullptr)
  193. continue;
  194. const auto nca = std::make_shared<NCA>(parser(file, id), nullptr, 0, keys);
  195. if (nca->GetStatus() != Loader::ResultStatus::Success ||
  196. nca->GetType() != NCAContentType::Meta) {
  197. continue;
  198. }
  199. const auto section0 = nca->GetSubdirectories()[0];
  200. for (const auto& section0_file : section0->GetFiles()) {
  201. if (section0_file->GetExtension() != "cnmt")
  202. continue;
  203. meta.insert_or_assign(nca->GetTitleId(), CNMT(section0_file));
  204. meta_id.insert_or_assign(nca->GetTitleId(), id);
  205. break;
  206. }
  207. }
  208. }
  209. void RegisteredCache::AccumulateYuzuMeta() {
  210. const auto dir = this->dir->GetSubdirectory("yuzu_meta");
  211. if (dir == nullptr)
  212. return;
  213. for (const auto& file : dir->GetFiles()) {
  214. if (file->GetExtension() != "cnmt")
  215. continue;
  216. CNMT cnmt(file);
  217. yuzu_meta.insert_or_assign(cnmt.GetTitleID(), std::move(cnmt));
  218. }
  219. }
  220. void RegisteredCache::Refresh() {
  221. if (dir == nullptr)
  222. return;
  223. const auto ids = AccumulateFiles();
  224. ProcessFiles(ids);
  225. AccumulateYuzuMeta();
  226. }
  227. RegisteredCache::RegisteredCache(VirtualDir dir_, RegisteredCacheParsingFunction parsing_function)
  228. : dir(std::move(dir_)), parser(std::move(parsing_function)) {
  229. Refresh();
  230. }
  231. RegisteredCache::~RegisteredCache() = default;
  232. bool RegisteredCache::HasEntry(u64 title_id, ContentRecordType type) const {
  233. return GetEntryRaw(title_id, type) != nullptr;
  234. }
  235. bool RegisteredCache::HasEntry(RegisteredCacheEntry entry) const {
  236. return GetEntryRaw(entry) != nullptr;
  237. }
  238. VirtualFile RegisteredCache::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
  239. const auto id = GetNcaIDFromMetadata(title_id, type);
  240. return id ? GetFileAtID(*id) : nullptr;
  241. }
  242. VirtualFile RegisteredCache::GetEntryUnparsed(RegisteredCacheEntry entry) const {
  243. return GetEntryUnparsed(entry.title_id, entry.type);
  244. }
  245. std::optional<u32> RegisteredCache::GetEntryVersion(u64 title_id) const {
  246. const auto meta_iter = meta.find(title_id);
  247. if (meta_iter != meta.end())
  248. return meta_iter->second.GetTitleVersion();
  249. const auto yuzu_meta_iter = yuzu_meta.find(title_id);
  250. if (yuzu_meta_iter != yuzu_meta.end())
  251. return yuzu_meta_iter->second.GetTitleVersion();
  252. return {};
  253. }
  254. VirtualFile RegisteredCache::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  255. const auto id = GetNcaIDFromMetadata(title_id, type);
  256. return id ? parser(GetFileAtID(*id), *id) : nullptr;
  257. }
  258. VirtualFile RegisteredCache::GetEntryRaw(RegisteredCacheEntry entry) const {
  259. return GetEntryRaw(entry.title_id, entry.type);
  260. }
  261. std::unique_ptr<NCA> RegisteredCache::GetEntry(u64 title_id, ContentRecordType type) const {
  262. const auto raw = GetEntryRaw(title_id, type);
  263. if (raw == nullptr)
  264. return nullptr;
  265. return std::make_unique<NCA>(raw, nullptr, 0, keys);
  266. }
  267. std::unique_ptr<NCA> RegisteredCache::GetEntry(RegisteredCacheEntry entry) const {
  268. return GetEntry(entry.title_id, entry.type);
  269. }
  270. template <typename T>
  271. void RegisteredCache::IterateAllMetadata(
  272. std::vector<T>& out, std::function<T(const CNMT&, const ContentRecord&)> proc,
  273. std::function<bool(const CNMT&, const ContentRecord&)> filter) const {
  274. for (const auto& kv : meta) {
  275. const auto& cnmt = kv.second;
  276. if (filter(cnmt, EMPTY_META_CONTENT_RECORD))
  277. out.push_back(proc(cnmt, EMPTY_META_CONTENT_RECORD));
  278. for (const auto& rec : cnmt.GetContentRecords()) {
  279. if (GetFileAtID(rec.nca_id) != nullptr && filter(cnmt, rec)) {
  280. out.push_back(proc(cnmt, rec));
  281. }
  282. }
  283. }
  284. for (const auto& kv : yuzu_meta) {
  285. const auto& cnmt = kv.second;
  286. for (const auto& rec : cnmt.GetContentRecords()) {
  287. if (GetFileAtID(rec.nca_id) != nullptr && filter(cnmt, rec)) {
  288. out.push_back(proc(cnmt, rec));
  289. }
  290. }
  291. }
  292. }
  293. std::vector<RegisteredCacheEntry> RegisteredCache::ListEntries() const {
  294. std::vector<RegisteredCacheEntry> out;
  295. IterateAllMetadata<RegisteredCacheEntry>(
  296. out,
  297. [](const CNMT& c, const ContentRecord& r) {
  298. return RegisteredCacheEntry{c.GetTitleID(), r.type};
  299. },
  300. [](const CNMT& c, const ContentRecord& r) { return true; });
  301. return out;
  302. }
  303. std::vector<RegisteredCacheEntry> RegisteredCache::ListEntriesFilter(
  304. std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
  305. std::optional<u64> title_id) const {
  306. std::vector<RegisteredCacheEntry> out;
  307. IterateAllMetadata<RegisteredCacheEntry>(
  308. out,
  309. [](const CNMT& c, const ContentRecord& r) {
  310. return RegisteredCacheEntry{c.GetTitleID(), r.type};
  311. },
  312. [&title_type, &record_type, &title_id](const CNMT& c, const ContentRecord& r) {
  313. if (title_type && *title_type != c.GetType())
  314. return false;
  315. if (record_type && *record_type != r.type)
  316. return false;
  317. if (title_id && *title_id != c.GetTitleID())
  318. return false;
  319. return true;
  320. });
  321. return out;
  322. }
  323. static std::shared_ptr<NCA> GetNCAFromNSPForID(const NSP& nsp, const NcaID& id) {
  324. const auto file = nsp.GetFile(fmt::format("{}.nca", Common::HexArrayToString(id, false)));
  325. if (file == nullptr)
  326. return nullptr;
  327. return std::make_shared<NCA>(file);
  328. }
  329. InstallResult RegisteredCache::InstallEntry(const XCI& xci, bool overwrite_if_exists,
  330. const VfsCopyFunction& copy) {
  331. return InstallEntry(*xci.GetSecurePartitionNSP(), overwrite_if_exists, copy);
  332. }
  333. InstallResult RegisteredCache::InstallEntry(const NSP& nsp, bool overwrite_if_exists,
  334. const VfsCopyFunction& copy) {
  335. const auto ncas = nsp.GetNCAsCollapsed();
  336. const auto meta_iter = std::find_if(ncas.begin(), ncas.end(), [](const auto& nca) {
  337. return nca->GetType() == NCAContentType::Meta;
  338. });
  339. if (meta_iter == ncas.end()) {
  340. LOG_ERROR(Loader, "The XCI you are attempting to install does not have a metadata NCA and "
  341. "is therefore malformed. Double check your encryption keys.");
  342. return InstallResult::ErrorMetaFailed;
  343. }
  344. // Install Metadata File
  345. const auto meta_id_raw = (*meta_iter)->GetName().substr(0, 32);
  346. const auto meta_id = Common::HexStringToArray<16>(meta_id_raw);
  347. const auto res = RawInstallNCA(**meta_iter, copy, overwrite_if_exists, meta_id);
  348. if (res != InstallResult::Success)
  349. return res;
  350. // Install all the other NCAs
  351. const auto section0 = (*meta_iter)->GetSubdirectories()[0];
  352. const auto cnmt_file = section0->GetFiles()[0];
  353. const CNMT cnmt(cnmt_file);
  354. for (const auto& record : cnmt.GetContentRecords()) {
  355. const auto nca = GetNCAFromNSPForID(nsp, record.nca_id);
  356. if (nca == nullptr)
  357. return InstallResult::ErrorCopyFailed;
  358. const auto res2 = RawInstallNCA(*nca, copy, overwrite_if_exists, record.nca_id);
  359. if (res2 != InstallResult::Success)
  360. return res2;
  361. }
  362. Refresh();
  363. return InstallResult::Success;
  364. }
  365. InstallResult RegisteredCache::InstallEntry(const NCA& nca, TitleType type,
  366. bool overwrite_if_exists, const VfsCopyFunction& copy) {
  367. CNMTHeader header{
  368. nca.GetTitleId(), ///< Title ID
  369. 0, ///< Ignore/Default title version
  370. type, ///< Type
  371. {}, ///< Padding
  372. 0x10, ///< Default table offset
  373. 1, ///< 1 Content Entry
  374. 0, ///< No Meta Entries
  375. {}, ///< Padding
  376. };
  377. OptionalHeader opt_header{0, 0};
  378. ContentRecord c_rec{{}, {}, {}, GetCRTypeFromNCAType(nca.GetType()), {}};
  379. const auto& data = nca.GetBaseFile()->ReadBytes(0x100000);
  380. mbedtls_sha256(data.data(), data.size(), c_rec.hash.data(), 0);
  381. memcpy(&c_rec.nca_id, &c_rec.hash, 16);
  382. const CNMT new_cnmt(header, opt_header, {c_rec}, {});
  383. if (!RawInstallYuzuMeta(new_cnmt))
  384. return InstallResult::ErrorMetaFailed;
  385. return RawInstallNCA(nca, copy, overwrite_if_exists, c_rec.nca_id);
  386. }
  387. InstallResult RegisteredCache::RawInstallNCA(const NCA& nca, const VfsCopyFunction& copy,
  388. bool overwrite_if_exists,
  389. std::optional<NcaID> override_id) {
  390. const auto in = nca.GetBaseFile();
  391. Core::Crypto::SHA256Hash hash{};
  392. // Calculate NcaID
  393. // NOTE: Because computing the SHA256 of an entire NCA is quite expensive (especially if the
  394. // game is massive), we're going to cheat and only hash the first MB of the NCA.
  395. // Also, for XCIs the NcaID matters, so if the override id isn't none, use that.
  396. NcaID id{};
  397. if (override_id) {
  398. id = *override_id;
  399. } else {
  400. const auto& data = in->ReadBytes(0x100000);
  401. mbedtls_sha256(data.data(), data.size(), hash.data(), 0);
  402. memcpy(id.data(), hash.data(), 16);
  403. }
  404. std::string path = GetRelativePathFromNcaID(id, false, true);
  405. if (GetFileAtID(id) != nullptr && !overwrite_if_exists) {
  406. LOG_WARNING(Loader, "Attempting to overwrite existing NCA. Skipping...");
  407. return InstallResult::ErrorAlreadyExists;
  408. }
  409. if (GetFileAtID(id) != nullptr) {
  410. LOG_WARNING(Loader, "Overwriting existing NCA...");
  411. VirtualDir c_dir;
  412. { c_dir = dir->GetFileRelative(path)->GetContainingDirectory(); }
  413. c_dir->DeleteFile(FileUtil::GetFilename(path));
  414. }
  415. auto out = dir->CreateFileRelative(path);
  416. if (out == nullptr)
  417. return InstallResult::ErrorCopyFailed;
  418. return copy(in, out, VFS_RC_LARGE_COPY_BLOCK) ? InstallResult::Success
  419. : InstallResult::ErrorCopyFailed;
  420. }
  421. bool RegisteredCache::RawInstallYuzuMeta(const CNMT& cnmt) {
  422. // Reasoning behind this method can be found in the comment for InstallEntry, NCA overload.
  423. const auto dir = this->dir->CreateDirectoryRelative("yuzu_meta");
  424. const auto filename = GetCNMTName(cnmt.GetType(), cnmt.GetTitleID());
  425. if (dir->GetFile(filename) == nullptr) {
  426. auto out = dir->CreateFile(filename);
  427. const auto buffer = cnmt.Serialize();
  428. out->Resize(buffer.size());
  429. out->WriteBytes(buffer);
  430. } else {
  431. auto out = dir->GetFile(filename);
  432. CNMT old_cnmt(out);
  433. // Returns true on change
  434. if (old_cnmt.UnionRecords(cnmt)) {
  435. out->Resize(0);
  436. const auto buffer = old_cnmt.Serialize();
  437. out->Resize(buffer.size());
  438. out->WriteBytes(buffer);
  439. }
  440. }
  441. Refresh();
  442. return std::find_if(yuzu_meta.begin(), yuzu_meta.end(),
  443. [&cnmt](const std::pair<u64, CNMT>& kv) {
  444. return kv.second.GetType() == cnmt.GetType() &&
  445. kv.second.GetTitleID() == cnmt.GetTitleID();
  446. }) != yuzu_meta.end();
  447. }
  448. RegisteredCacheUnion::RegisteredCacheUnion(std::vector<RegisteredCache*> caches)
  449. : caches(std::move(caches)) {}
  450. void RegisteredCacheUnion::Refresh() {
  451. for (const auto& c : caches)
  452. c->Refresh();
  453. }
  454. bool RegisteredCacheUnion::HasEntry(u64 title_id, ContentRecordType type) const {
  455. return std::any_of(caches.begin(), caches.end(), [title_id, type](const auto& cache) {
  456. return cache->HasEntry(title_id, type);
  457. });
  458. }
  459. bool RegisteredCacheUnion::HasEntry(RegisteredCacheEntry entry) const {
  460. return HasEntry(entry.title_id, entry.type);
  461. }
  462. std::optional<u32> RegisteredCacheUnion::GetEntryVersion(u64 title_id) const {
  463. for (const auto& c : caches) {
  464. const auto res = c->GetEntryVersion(title_id);
  465. if (res)
  466. return res;
  467. }
  468. return {};
  469. }
  470. VirtualFile RegisteredCacheUnion::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
  471. for (const auto& c : caches) {
  472. const auto res = c->GetEntryUnparsed(title_id, type);
  473. if (res != nullptr)
  474. return res;
  475. }
  476. return nullptr;
  477. }
  478. VirtualFile RegisteredCacheUnion::GetEntryUnparsed(RegisteredCacheEntry entry) const {
  479. return GetEntryUnparsed(entry.title_id, entry.type);
  480. }
  481. VirtualFile RegisteredCacheUnion::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  482. for (const auto& c : caches) {
  483. const auto res = c->GetEntryRaw(title_id, type);
  484. if (res != nullptr)
  485. return res;
  486. }
  487. return nullptr;
  488. }
  489. VirtualFile RegisteredCacheUnion::GetEntryRaw(RegisteredCacheEntry entry) const {
  490. return GetEntryRaw(entry.title_id, entry.type);
  491. }
  492. std::unique_ptr<NCA> RegisteredCacheUnion::GetEntry(u64 title_id, ContentRecordType type) const {
  493. const auto raw = GetEntryRaw(title_id, type);
  494. if (raw == nullptr)
  495. return nullptr;
  496. return std::make_unique<NCA>(raw);
  497. }
  498. std::unique_ptr<NCA> RegisteredCacheUnion::GetEntry(RegisteredCacheEntry entry) const {
  499. return GetEntry(entry.title_id, entry.type);
  500. }
  501. std::vector<RegisteredCacheEntry> RegisteredCacheUnion::ListEntries() const {
  502. std::vector<RegisteredCacheEntry> out;
  503. for (const auto& c : caches) {
  504. c->IterateAllMetadata<RegisteredCacheEntry>(
  505. out,
  506. [](const CNMT& c, const ContentRecord& r) {
  507. return RegisteredCacheEntry{c.GetTitleID(), r.type};
  508. },
  509. [](const CNMT& c, const ContentRecord& r) { return true; });
  510. }
  511. std::sort(out.begin(), out.end());
  512. out.erase(std::unique(out.begin(), out.end()), out.end());
  513. return out;
  514. }
  515. std::vector<RegisteredCacheEntry> RegisteredCacheUnion::ListEntriesFilter(
  516. std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
  517. std::optional<u64> title_id) const {
  518. std::vector<RegisteredCacheEntry> out;
  519. for (const auto& c : caches) {
  520. c->IterateAllMetadata<RegisteredCacheEntry>(
  521. out,
  522. [](const CNMT& c, const ContentRecord& r) {
  523. return RegisteredCacheEntry{c.GetTitleID(), r.type};
  524. },
  525. [&title_type, &record_type, &title_id](const CNMT& c, const ContentRecord& r) {
  526. if (title_type && *title_type != c.GetType())
  527. return false;
  528. if (record_type && *record_type != r.type)
  529. return false;
  530. if (title_id && *title_id != c.GetTitleID())
  531. return false;
  532. return true;
  533. });
  534. }
  535. std::sort(out.begin(), out.end());
  536. out.erase(std::unique(out.begin(), out.end()), out.end());
  537. return out;
  538. }
  539. } // namespace FileSys