registered_cache.cpp 26 KB

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