registered_cache.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  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::HtmlDocument;
  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 file you are attempting to install does not have a metadata NCA and "
  337. "is therefore malformed. 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. // Ignore DeltaFragments, they are not useful to us
  352. if (record.type == ContentRecordType::DeltaFragment)
  353. continue;
  354. const auto nca = GetNCAFromNSPForID(nsp, record.nca_id);
  355. if (nca == nullptr)
  356. return InstallResult::ErrorCopyFailed;
  357. const auto res2 = RawInstallNCA(*nca, copy, overwrite_if_exists, record.nca_id);
  358. if (res2 != InstallResult::Success)
  359. return res2;
  360. }
  361. Refresh();
  362. return InstallResult::Success;
  363. }
  364. InstallResult RegisteredCache::InstallEntry(const NCA& nca, TitleType type,
  365. bool overwrite_if_exists, const VfsCopyFunction& copy) {
  366. CNMTHeader header{
  367. nca.GetTitleId(), ///< Title ID
  368. 0, ///< Ignore/Default title version
  369. type, ///< Type
  370. {}, ///< Padding
  371. 0x10, ///< Default table offset
  372. 1, ///< 1 Content Entry
  373. 0, ///< No Meta Entries
  374. {}, ///< Padding
  375. };
  376. OptionalHeader opt_header{0, 0};
  377. ContentRecord c_rec{{}, {}, {}, GetCRTypeFromNCAType(nca.GetType()), {}};
  378. const auto& data = nca.GetBaseFile()->ReadBytes(0x100000);
  379. mbedtls_sha256(data.data(), data.size(), c_rec.hash.data(), 0);
  380. memcpy(&c_rec.nca_id, &c_rec.hash, 16);
  381. const CNMT new_cnmt(header, opt_header, {c_rec}, {});
  382. if (!RawInstallYuzuMeta(new_cnmt))
  383. return InstallResult::ErrorMetaFailed;
  384. return RawInstallNCA(nca, copy, overwrite_if_exists, c_rec.nca_id);
  385. }
  386. InstallResult RegisteredCache::RawInstallNCA(const NCA& nca, const VfsCopyFunction& copy,
  387. bool overwrite_if_exists,
  388. std::optional<NcaID> override_id) {
  389. const auto in = nca.GetBaseFile();
  390. Core::Crypto::SHA256Hash hash{};
  391. // Calculate NcaID
  392. // NOTE: Because computing the SHA256 of an entire NCA is quite expensive (especially if the
  393. // game is massive), we're going to cheat and only hash the first MB of the NCA.
  394. // Also, for XCIs the NcaID matters, so if the override id isn't none, use that.
  395. NcaID id{};
  396. if (override_id) {
  397. id = *override_id;
  398. } else {
  399. const auto& data = in->ReadBytes(0x100000);
  400. mbedtls_sha256(data.data(), data.size(), hash.data(), 0);
  401. memcpy(id.data(), hash.data(), 16);
  402. }
  403. std::string path = GetRelativePathFromNcaID(id, false, true);
  404. if (GetFileAtID(id) != nullptr && !overwrite_if_exists) {
  405. LOG_WARNING(Loader, "Attempting to overwrite existing NCA. Skipping...");
  406. return InstallResult::ErrorAlreadyExists;
  407. }
  408. if (GetFileAtID(id) != nullptr) {
  409. LOG_WARNING(Loader, "Overwriting existing NCA...");
  410. VirtualDir c_dir;
  411. { c_dir = dir->GetFileRelative(path)->GetContainingDirectory(); }
  412. c_dir->DeleteFile(FileUtil::GetFilename(path));
  413. }
  414. auto out = dir->CreateFileRelative(path);
  415. if (out == nullptr)
  416. return InstallResult::ErrorCopyFailed;
  417. return copy(in, out, VFS_RC_LARGE_COPY_BLOCK) ? InstallResult::Success
  418. : InstallResult::ErrorCopyFailed;
  419. }
  420. bool RegisteredCache::RawInstallYuzuMeta(const CNMT& cnmt) {
  421. // Reasoning behind this method can be found in the comment for InstallEntry, NCA overload.
  422. const auto dir = this->dir->CreateDirectoryRelative("yuzu_meta");
  423. const auto filename = GetCNMTName(cnmt.GetType(), cnmt.GetTitleID());
  424. if (dir->GetFile(filename) == nullptr) {
  425. auto out = dir->CreateFile(filename);
  426. const auto buffer = cnmt.Serialize();
  427. out->Resize(buffer.size());
  428. out->WriteBytes(buffer);
  429. } else {
  430. auto out = dir->GetFile(filename);
  431. CNMT old_cnmt(out);
  432. // Returns true on change
  433. if (old_cnmt.UnionRecords(cnmt)) {
  434. out->Resize(0);
  435. const auto buffer = old_cnmt.Serialize();
  436. out->Resize(buffer.size());
  437. out->WriteBytes(buffer);
  438. }
  439. }
  440. Refresh();
  441. return std::find_if(yuzu_meta.begin(), yuzu_meta.end(),
  442. [&cnmt](const std::pair<u64, CNMT>& kv) {
  443. return kv.second.GetType() == cnmt.GetType() &&
  444. kv.second.GetTitleID() == cnmt.GetTitleID();
  445. }) != yuzu_meta.end();
  446. }
  447. ContentProviderUnion::~ContentProviderUnion() = default;
  448. void ContentProviderUnion::SetSlot(ContentProviderUnionSlot slot, ContentProvider* provider) {
  449. providers[slot] = provider;
  450. }
  451. void ContentProviderUnion::ClearSlot(ContentProviderUnionSlot slot) {
  452. providers[slot] = nullptr;
  453. }
  454. void ContentProviderUnion::Refresh() {
  455. for (auto& provider : providers) {
  456. if (provider.second == nullptr)
  457. continue;
  458. provider.second->Refresh();
  459. }
  460. }
  461. bool ContentProviderUnion::HasEntry(u64 title_id, ContentRecordType type) const {
  462. for (const auto& provider : providers) {
  463. if (provider.second == nullptr)
  464. continue;
  465. if (provider.second->HasEntry(title_id, type))
  466. return true;
  467. }
  468. return false;
  469. }
  470. std::optional<u32> ContentProviderUnion::GetEntryVersion(u64 title_id) const {
  471. for (const auto& provider : providers) {
  472. if (provider.second == nullptr)
  473. continue;
  474. const auto res = provider.second->GetEntryVersion(title_id);
  475. if (res != std::nullopt)
  476. return res;
  477. }
  478. return std::nullopt;
  479. }
  480. VirtualFile ContentProviderUnion::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
  481. for (const auto& provider : providers) {
  482. if (provider.second == nullptr)
  483. continue;
  484. const auto res = provider.second->GetEntryUnparsed(title_id, type);
  485. if (res != nullptr)
  486. return res;
  487. }
  488. return nullptr;
  489. }
  490. VirtualFile ContentProviderUnion::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  491. for (const auto& provider : providers) {
  492. if (provider.second == nullptr)
  493. continue;
  494. const auto res = provider.second->GetEntryRaw(title_id, type);
  495. if (res != nullptr)
  496. return res;
  497. }
  498. return nullptr;
  499. }
  500. std::unique_ptr<NCA> ContentProviderUnion::GetEntry(u64 title_id, ContentRecordType type) const {
  501. for (const auto& provider : providers) {
  502. if (provider.second == nullptr)
  503. continue;
  504. auto res = provider.second->GetEntry(title_id, type);
  505. if (res != nullptr)
  506. return res;
  507. }
  508. return nullptr;
  509. }
  510. std::vector<ContentProviderEntry> ContentProviderUnion::ListEntriesFilter(
  511. std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
  512. std::optional<u64> title_id) const {
  513. std::vector<ContentProviderEntry> out;
  514. for (const auto& provider : providers) {
  515. if (provider.second == nullptr)
  516. continue;
  517. const auto vec = provider.second->ListEntriesFilter(title_type, record_type, title_id);
  518. std::copy(vec.begin(), vec.end(), std::back_inserter(out));
  519. }
  520. std::sort(out.begin(), out.end());
  521. out.erase(std::unique(out.begin(), out.end()), out.end());
  522. return out;
  523. }
  524. std::vector<std::pair<ContentProviderUnionSlot, ContentProviderEntry>>
  525. ContentProviderUnion::ListEntriesFilterOrigin(std::optional<ContentProviderUnionSlot> origin,
  526. std::optional<TitleType> title_type,
  527. std::optional<ContentRecordType> record_type,
  528. std::optional<u64> title_id) const {
  529. std::vector<std::pair<ContentProviderUnionSlot, ContentProviderEntry>> out;
  530. for (const auto& provider : providers) {
  531. if (provider.second == nullptr)
  532. continue;
  533. if (origin.has_value() && *origin != provider.first)
  534. continue;
  535. const auto vec = provider.second->ListEntriesFilter(title_type, record_type, title_id);
  536. std::transform(vec.begin(), vec.end(), std::back_inserter(out),
  537. [&provider](const ContentProviderEntry& entry) {
  538. return std::make_pair(provider.first, entry);
  539. });
  540. }
  541. std::sort(out.begin(), out.end());
  542. out.erase(std::unique(out.begin(), out.end()), out.end());
  543. return out;
  544. }
  545. std::optional<ContentProviderUnionSlot> ContentProviderUnion::GetSlotForEntry(
  546. u64 title_id, ContentRecordType type) const {
  547. const auto iter =
  548. std::find_if(providers.begin(), providers.end(), [title_id, type](const auto& provider) {
  549. return provider.second != nullptr && provider.second->HasEntry(title_id, type);
  550. });
  551. if (iter == providers.end()) {
  552. return std::nullopt;
  553. }
  554. return iter->first;
  555. }
  556. ManualContentProvider::~ManualContentProvider() = default;
  557. void ManualContentProvider::AddEntry(TitleType title_type, ContentRecordType content_type,
  558. u64 title_id, VirtualFile file) {
  559. entries.insert_or_assign({title_type, content_type, title_id}, file);
  560. }
  561. void ManualContentProvider::ClearAllEntries() {
  562. entries.clear();
  563. }
  564. void ManualContentProvider::Refresh() {}
  565. bool ManualContentProvider::HasEntry(u64 title_id, ContentRecordType type) const {
  566. return GetEntryRaw(title_id, type) != nullptr;
  567. }
  568. std::optional<u32> ManualContentProvider::GetEntryVersion(u64 title_id) const {
  569. return std::nullopt;
  570. }
  571. VirtualFile ManualContentProvider::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
  572. return GetEntryRaw(title_id, type);
  573. }
  574. VirtualFile ManualContentProvider::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  575. const auto iter =
  576. std::find_if(entries.begin(), entries.end(), [title_id, type](const auto& entry) {
  577. const auto [title_type, content_type, e_title_id] = entry.first;
  578. return content_type == type && e_title_id == title_id;
  579. });
  580. if (iter == entries.end())
  581. return nullptr;
  582. return iter->second;
  583. }
  584. std::unique_ptr<NCA> ManualContentProvider::GetEntry(u64 title_id, ContentRecordType type) const {
  585. const auto res = GetEntryRaw(title_id, type);
  586. if (res == nullptr)
  587. return nullptr;
  588. return std::make_unique<NCA>(res, nullptr, 0, keys);
  589. }
  590. std::vector<ContentProviderEntry> ManualContentProvider::ListEntriesFilter(
  591. std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
  592. std::optional<u64> title_id) const {
  593. std::vector<ContentProviderEntry> out;
  594. for (const auto& entry : entries) {
  595. const auto [e_title_type, e_content_type, e_title_id] = entry.first;
  596. if ((title_type == std::nullopt || e_title_type == *title_type) &&
  597. (record_type == std::nullopt || e_content_type == *record_type) &&
  598. (title_id == std::nullopt || e_title_id == *title_id)) {
  599. out.emplace_back(ContentProviderEntry{e_title_id, e_content_type});
  600. }
  601. }
  602. std::sort(out.begin(), out.end());
  603. out.erase(std::unique(out.begin(), out.end()), out.end());
  604. return out;
  605. }
  606. } // namespace FileSys