registered_cache.cpp 25 KB

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