registered_cache.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  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 <random>
  6. #include <regex>
  7. #include <mbedtls/sha256.h>
  8. #include "common/assert.h"
  9. #include "common/file_util.h"
  10. #include "common/hex_util.h"
  11. #include "common/logging/log.h"
  12. #include "core/crypto/key_manager.h"
  13. #include "core/file_sys/card_image.h"
  14. #include "core/file_sys/content_archive.h"
  15. #include "core/file_sys/nca_metadata.h"
  16. #include "core/file_sys/registered_cache.h"
  17. #include "core/file_sys/submission_package.h"
  18. #include "core/file_sys/vfs_concat.h"
  19. #include "core/loader/loader.h"
  20. namespace FileSys {
  21. // The size of blocks to use when vfs raw copying into nand.
  22. constexpr size_t VFS_RC_LARGE_COPY_BLOCK = 0x400000;
  23. std::string ContentProviderEntry::DebugInfo() const {
  24. return fmt::format("title_id={:016X}, content_type={:02X}", title_id, static_cast<u8>(type));
  25. }
  26. bool operator<(const ContentProviderEntry& lhs, const ContentProviderEntry& rhs) {
  27. return (lhs.title_id < rhs.title_id) || (lhs.title_id == rhs.title_id && lhs.type < rhs.type);
  28. }
  29. bool operator==(const ContentProviderEntry& lhs, const ContentProviderEntry& rhs) {
  30. return std::tie(lhs.title_id, lhs.type) == std::tie(rhs.title_id, rhs.type);
  31. }
  32. bool operator!=(const ContentProviderEntry& lhs, const ContentProviderEntry& rhs) {
  33. return !operator==(lhs, rhs);
  34. }
  35. static bool FollowsTwoDigitDirFormat(std::string_view name) {
  36. static const std::regex two_digit_regex("000000[0-9A-F]{2}", std::regex_constants::ECMAScript |
  37. std::regex_constants::icase);
  38. return std::regex_match(name.begin(), name.end(), two_digit_regex);
  39. }
  40. static bool FollowsNcaIdFormat(std::string_view name) {
  41. static const std::regex nca_id_regex("[0-9A-F]{32}\\.nca", std::regex_constants::ECMAScript |
  42. std::regex_constants::icase);
  43. static const std::regex nca_id_cnmt_regex(
  44. "[0-9A-F]{32}\\.cnmt.nca", std::regex_constants::ECMAScript | std::regex_constants::icase);
  45. return (name.size() == 36 && std::regex_match(name.begin(), name.end(), nca_id_regex)) ||
  46. (name.size() == 41 && std::regex_match(name.begin(), name.end(), nca_id_cnmt_regex));
  47. }
  48. static std::string GetRelativePathFromNcaID(const std::array<u8, 16>& nca_id, bool second_hex_upper,
  49. bool within_two_digit, bool cnmt_suffix) {
  50. if (!within_two_digit)
  51. return fmt::format(cnmt_suffix ? "{}.cnmt.nca" : "/{}.nca",
  52. Common::HexToString(nca_id, second_hex_upper));
  53. Core::Crypto::SHA256Hash hash{};
  54. mbedtls_sha256_ret(nca_id.data(), nca_id.size(), hash.data(), 0);
  55. return fmt::format(cnmt_suffix ? "/000000{:02X}/{}.cnmt.nca" : "/000000{:02X}/{}.nca", hash[0],
  56. Common::HexToString(nca_id, second_hex_upper));
  57. }
  58. static std::string GetCNMTName(TitleType type, u64 title_id) {
  59. constexpr std::array<const char*, 9> TITLE_TYPE_NAMES{
  60. "SystemProgram",
  61. "SystemData",
  62. "SystemUpdate",
  63. "BootImagePackage",
  64. "BootImagePackageSafe",
  65. "Application",
  66. "Patch",
  67. "AddOnContent",
  68. "" ///< Currently unknown 'DeltaTitle'
  69. };
  70. auto index = static_cast<std::size_t>(type);
  71. // If the index is after the jump in TitleType, subtract it out.
  72. if (index >= static_cast<std::size_t>(TitleType::Application)) {
  73. index -= static_cast<std::size_t>(TitleType::Application) -
  74. static_cast<std::size_t>(TitleType::FirmwarePackageB);
  75. }
  76. return fmt::format("{}_{:016x}.cnmt", TITLE_TYPE_NAMES[index], title_id);
  77. }
  78. ContentRecordType GetCRTypeFromNCAType(NCAContentType type) {
  79. switch (type) {
  80. case NCAContentType::Program:
  81. // TODO(DarkLordZach): Differentiate between Program and Patch
  82. return ContentRecordType::Program;
  83. case NCAContentType::Meta:
  84. return ContentRecordType::Meta;
  85. case NCAContentType::Control:
  86. return ContentRecordType::Control;
  87. case NCAContentType::Data:
  88. case NCAContentType::PublicData:
  89. return ContentRecordType::Data;
  90. case NCAContentType::Manual:
  91. // TODO(DarkLordZach): Peek at NCA contents to differentiate Manual and Legal.
  92. return ContentRecordType::HtmlDocument;
  93. default:
  94. UNREACHABLE_MSG("Invalid NCAContentType={:02X}", static_cast<u8>(type));
  95. }
  96. }
  97. ContentProvider::~ContentProvider() = default;
  98. bool ContentProvider::HasEntry(ContentProviderEntry entry) const {
  99. return HasEntry(entry.title_id, entry.type);
  100. }
  101. VirtualFile ContentProvider::GetEntryUnparsed(ContentProviderEntry entry) const {
  102. return GetEntryUnparsed(entry.title_id, entry.type);
  103. }
  104. VirtualFile ContentProvider::GetEntryRaw(ContentProviderEntry entry) const {
  105. return GetEntryRaw(entry.title_id, entry.type);
  106. }
  107. std::unique_ptr<NCA> ContentProvider::GetEntry(ContentProviderEntry entry) const {
  108. return GetEntry(entry.title_id, entry.type);
  109. }
  110. std::vector<ContentProviderEntry> ContentProvider::ListEntries() const {
  111. return ListEntriesFilter(std::nullopt, std::nullopt, std::nullopt);
  112. }
  113. PlaceholderCache::PlaceholderCache(VirtualDir dir_) : dir(std::move(dir_)) {}
  114. bool PlaceholderCache::Create(const NcaID& id, u64 size) const {
  115. const auto path = GetRelativePathFromNcaID(id, false, true, false);
  116. if (dir->GetFileRelative(path) != nullptr) {
  117. return false;
  118. }
  119. Core::Crypto::SHA256Hash hash{};
  120. mbedtls_sha256_ret(id.data(), id.size(), hash.data(), 0);
  121. const auto dirname = fmt::format("000000{:02X}", hash[0]);
  122. const auto dir2 = GetOrCreateDirectoryRelative(dir, dirname);
  123. if (dir2 == nullptr)
  124. return false;
  125. const auto file = dir2->CreateFile(fmt::format("{}.nca", Common::HexToString(id, false)));
  126. if (file == nullptr)
  127. return false;
  128. return file->Resize(size);
  129. }
  130. bool PlaceholderCache::Delete(const NcaID& id) const {
  131. const auto path = GetRelativePathFromNcaID(id, false, true, false);
  132. if (dir->GetFileRelative(path) == nullptr) {
  133. return false;
  134. }
  135. Core::Crypto::SHA256Hash hash{};
  136. mbedtls_sha256_ret(id.data(), id.size(), hash.data(), 0);
  137. const auto dirname = fmt::format("000000{:02X}", hash[0]);
  138. const auto dir2 = GetOrCreateDirectoryRelative(dir, dirname);
  139. const auto res = dir2->DeleteFile(fmt::format("{}.nca", Common::HexToString(id, false)));
  140. return res;
  141. }
  142. bool PlaceholderCache::Exists(const NcaID& id) const {
  143. const auto path = GetRelativePathFromNcaID(id, false, true, false);
  144. return dir->GetFileRelative(path) != nullptr;
  145. }
  146. bool PlaceholderCache::Write(const NcaID& id, u64 offset, const std::vector<u8>& data) const {
  147. const auto path = GetRelativePathFromNcaID(id, false, true, false);
  148. const auto file = dir->GetFileRelative(path);
  149. if (file == nullptr)
  150. return false;
  151. return file->WriteBytes(data, offset) == data.size();
  152. }
  153. bool PlaceholderCache::Register(RegisteredCache* cache, const NcaID& placeholder,
  154. const NcaID& install) const {
  155. const auto path = GetRelativePathFromNcaID(placeholder, false, true, false);
  156. const auto file = dir->GetFileRelative(path);
  157. if (file == nullptr)
  158. return false;
  159. const auto res = cache->RawInstallNCA(NCA{file}, &VfsRawCopy, false, install);
  160. if (res != InstallResult::Success)
  161. return false;
  162. return Delete(placeholder);
  163. }
  164. bool PlaceholderCache::CleanAll() const {
  165. return dir->GetParentDirectory()->CleanSubdirectoryRecursive(dir->GetName());
  166. }
  167. std::optional<std::array<u8, 0x10>> PlaceholderCache::GetRightsID(const NcaID& id) const {
  168. const auto path = GetRelativePathFromNcaID(id, false, true, false);
  169. const auto file = dir->GetFileRelative(path);
  170. if (file == nullptr)
  171. return std::nullopt;
  172. NCA nca{file};
  173. if (nca.GetStatus() != Loader::ResultStatus::Success &&
  174. nca.GetStatus() != Loader::ResultStatus::ErrorMissingBKTRBaseRomFS) {
  175. return std::nullopt;
  176. }
  177. const auto rights_id = nca.GetRightsId();
  178. if (rights_id == NcaID{})
  179. return std::nullopt;
  180. return rights_id;
  181. }
  182. u64 PlaceholderCache::Size(const NcaID& id) const {
  183. const auto path = GetRelativePathFromNcaID(id, false, true, false);
  184. const auto file = dir->GetFileRelative(path);
  185. if (file == nullptr)
  186. return 0;
  187. return file->GetSize();
  188. }
  189. bool PlaceholderCache::SetSize(const NcaID& id, u64 new_size) const {
  190. const auto path = GetRelativePathFromNcaID(id, false, true, false);
  191. const auto file = dir->GetFileRelative(path);
  192. if (file == nullptr)
  193. return false;
  194. return file->Resize(new_size);
  195. }
  196. std::vector<NcaID> PlaceholderCache::List() const {
  197. std::vector<NcaID> out;
  198. for (const auto& sdir : dir->GetSubdirectories()) {
  199. for (const auto& file : sdir->GetFiles()) {
  200. const auto name = file->GetName();
  201. if (name.length() == 36 && name[32] == '.' && name[33] == 'n' && name[34] == 'c' &&
  202. name[35] == 'a') {
  203. out.push_back(Common::HexStringToArray<0x10>(name.substr(0, 32)));
  204. }
  205. }
  206. }
  207. return out;
  208. }
  209. NcaID PlaceholderCache::Generate() {
  210. std::random_device device;
  211. std::mt19937 gen(device());
  212. std::uniform_int_distribution<u64> distribution(1, std::numeric_limits<u64>::max());
  213. NcaID out{};
  214. const auto v1 = distribution(gen);
  215. const auto v2 = distribution(gen);
  216. std::memcpy(out.data(), &v1, sizeof(u64));
  217. std::memcpy(out.data() + sizeof(u64), &v2, sizeof(u64));
  218. return out;
  219. }
  220. VirtualFile RegisteredCache::OpenFileOrDirectoryConcat(const VirtualDir& dir,
  221. std::string_view path) const {
  222. const auto file = dir->GetFileRelative(path);
  223. if (file != nullptr) {
  224. return file;
  225. }
  226. const auto nca_dir = dir->GetDirectoryRelative(path);
  227. if (nca_dir == nullptr) {
  228. return nullptr;
  229. }
  230. const auto files = nca_dir->GetFiles();
  231. if (files.size() == 1 && files[0]->GetName() == "00") {
  232. return files[0];
  233. }
  234. std::vector<VirtualFile> concat;
  235. // Since the files are a two-digit hex number, max is FF.
  236. for (std::size_t i = 0; i < 0x100; ++i) {
  237. auto next = nca_dir->GetFile(fmt::format("{:02X}", i));
  238. if (next != nullptr) {
  239. concat.push_back(std::move(next));
  240. } else {
  241. next = nca_dir->GetFile(fmt::format("{:02x}", i));
  242. if (next != nullptr) {
  243. concat.push_back(std::move(next));
  244. } else {
  245. break;
  246. }
  247. }
  248. }
  249. if (concat.empty()) {
  250. return nullptr;
  251. }
  252. return ConcatenatedVfsFile::MakeConcatenatedFile(concat, concat.front()->GetName());
  253. }
  254. VirtualFile RegisteredCache::GetFileAtID(NcaID id) const {
  255. VirtualFile file;
  256. // Try all five relevant modes of file storage:
  257. // (bit 2 = uppercase/lower, bit 1 = within a two-digit dir, bit 0 = .cnmt suffix)
  258. // 000: /000000**/{:032X}.nca
  259. // 010: /{:032X}.nca
  260. // 100: /000000**/{:032x}.nca
  261. // 110: /{:032x}.nca
  262. // 111: /{:032x}.cnmt.nca
  263. for (u8 i = 0; i < 8; ++i) {
  264. if ((i % 2) == 1 && i != 7)
  265. continue;
  266. const auto path =
  267. GetRelativePathFromNcaID(id, (i & 0b100) == 0, (i & 0b010) == 0, (i & 0b001) == 0b001);
  268. file = OpenFileOrDirectoryConcat(dir, path);
  269. if (file != nullptr)
  270. return file;
  271. }
  272. return file;
  273. }
  274. static std::optional<NcaID> CheckMapForContentRecord(const std::map<u64, CNMT>& map, u64 title_id,
  275. ContentRecordType type) {
  276. if (map.find(title_id) == map.end())
  277. return {};
  278. const auto& cnmt = map.at(title_id);
  279. const auto iter = std::find_if(cnmt.GetContentRecords().begin(), cnmt.GetContentRecords().end(),
  280. [type](const ContentRecord& rec) { return rec.type == type; });
  281. if (iter == cnmt.GetContentRecords().end())
  282. return {};
  283. return std::make_optional(iter->nca_id);
  284. }
  285. std::optional<NcaID> RegisteredCache::GetNcaIDFromMetadata(u64 title_id,
  286. ContentRecordType type) const {
  287. if (type == ContentRecordType::Meta && meta_id.find(title_id) != meta_id.end())
  288. return meta_id.at(title_id);
  289. const auto res1 = CheckMapForContentRecord(yuzu_meta, title_id, type);
  290. if (res1)
  291. return res1;
  292. return CheckMapForContentRecord(meta, title_id, type);
  293. }
  294. std::vector<NcaID> RegisteredCache::AccumulateFiles() const {
  295. std::vector<NcaID> ids;
  296. for (const auto& d2_dir : dir->GetSubdirectories()) {
  297. if (FollowsNcaIdFormat(d2_dir->GetName())) {
  298. ids.push_back(Common::HexStringToArray<0x10, true>(d2_dir->GetName().substr(0, 0x20)));
  299. continue;
  300. }
  301. if (!FollowsTwoDigitDirFormat(d2_dir->GetName()))
  302. continue;
  303. for (const auto& nca_dir : d2_dir->GetSubdirectories()) {
  304. if (!FollowsNcaIdFormat(nca_dir->GetName()))
  305. continue;
  306. ids.push_back(Common::HexStringToArray<0x10, true>(nca_dir->GetName().substr(0, 0x20)));
  307. }
  308. for (const auto& nca_file : d2_dir->GetFiles()) {
  309. if (!FollowsNcaIdFormat(nca_file->GetName()))
  310. continue;
  311. ids.push_back(
  312. Common::HexStringToArray<0x10, true>(nca_file->GetName().substr(0, 0x20)));
  313. }
  314. }
  315. for (const auto& d2_file : dir->GetFiles()) {
  316. if (FollowsNcaIdFormat(d2_file->GetName()))
  317. ids.push_back(Common::HexStringToArray<0x10, true>(d2_file->GetName().substr(0, 0x20)));
  318. }
  319. return ids;
  320. }
  321. void RegisteredCache::ProcessFiles(const std::vector<NcaID>& ids) {
  322. for (const auto& id : ids) {
  323. const auto file = GetFileAtID(id);
  324. if (file == nullptr)
  325. continue;
  326. const auto nca = std::make_shared<NCA>(parser(file, id), nullptr, 0);
  327. if (nca->GetStatus() != Loader::ResultStatus::Success ||
  328. nca->GetType() != NCAContentType::Meta) {
  329. continue;
  330. }
  331. const auto section0 = nca->GetSubdirectories()[0];
  332. for (const auto& section0_file : section0->GetFiles()) {
  333. if (section0_file->GetExtension() != "cnmt")
  334. continue;
  335. meta.insert_or_assign(nca->GetTitleId(), CNMT(section0_file));
  336. meta_id.insert_or_assign(nca->GetTitleId(), id);
  337. break;
  338. }
  339. }
  340. }
  341. void RegisteredCache::AccumulateYuzuMeta() {
  342. const auto dir = this->dir->GetSubdirectory("yuzu_meta");
  343. if (dir == nullptr)
  344. return;
  345. for (const auto& file : dir->GetFiles()) {
  346. if (file->GetExtension() != "cnmt")
  347. continue;
  348. CNMT cnmt(file);
  349. yuzu_meta.insert_or_assign(cnmt.GetTitleID(), std::move(cnmt));
  350. }
  351. }
  352. void RegisteredCache::Refresh() {
  353. if (dir == nullptr)
  354. return;
  355. const auto ids = AccumulateFiles();
  356. ProcessFiles(ids);
  357. AccumulateYuzuMeta();
  358. }
  359. RegisteredCache::RegisteredCache(VirtualDir dir_, ContentProviderParsingFunction parsing_function)
  360. : dir(std::move(dir_)), parser(std::move(parsing_function)) {
  361. Refresh();
  362. }
  363. RegisteredCache::~RegisteredCache() = default;
  364. bool RegisteredCache::HasEntry(u64 title_id, ContentRecordType type) const {
  365. return GetEntryRaw(title_id, type) != nullptr;
  366. }
  367. VirtualFile RegisteredCache::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
  368. const auto id = GetNcaIDFromMetadata(title_id, type);
  369. return id ? GetFileAtID(*id) : nullptr;
  370. }
  371. std::optional<u32> RegisteredCache::GetEntryVersion(u64 title_id) const {
  372. const auto meta_iter = meta.find(title_id);
  373. if (meta_iter != meta.end())
  374. return meta_iter->second.GetTitleVersion();
  375. const auto yuzu_meta_iter = yuzu_meta.find(title_id);
  376. if (yuzu_meta_iter != yuzu_meta.end())
  377. return yuzu_meta_iter->second.GetTitleVersion();
  378. return {};
  379. }
  380. VirtualFile RegisteredCache::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  381. const auto id = GetNcaIDFromMetadata(title_id, type);
  382. return id ? parser(GetFileAtID(*id), *id) : nullptr;
  383. }
  384. std::unique_ptr<NCA> RegisteredCache::GetEntry(u64 title_id, ContentRecordType type) const {
  385. const auto raw = GetEntryRaw(title_id, type);
  386. if (raw == nullptr)
  387. return nullptr;
  388. return std::make_unique<NCA>(raw, nullptr, 0);
  389. }
  390. template <typename T>
  391. void RegisteredCache::IterateAllMetadata(
  392. std::vector<T>& out, std::function<T(const CNMT&, const ContentRecord&)> proc,
  393. std::function<bool(const CNMT&, const ContentRecord&)> filter) const {
  394. for (const auto& kv : meta) {
  395. const auto& cnmt = kv.second;
  396. if (filter(cnmt, EMPTY_META_CONTENT_RECORD))
  397. out.push_back(proc(cnmt, EMPTY_META_CONTENT_RECORD));
  398. for (const auto& rec : cnmt.GetContentRecords()) {
  399. if (GetFileAtID(rec.nca_id) != nullptr && filter(cnmt, rec)) {
  400. out.push_back(proc(cnmt, rec));
  401. }
  402. }
  403. }
  404. for (const auto& kv : yuzu_meta) {
  405. const auto& cnmt = kv.second;
  406. for (const auto& rec : cnmt.GetContentRecords()) {
  407. if (GetFileAtID(rec.nca_id) != nullptr && filter(cnmt, rec)) {
  408. out.push_back(proc(cnmt, rec));
  409. }
  410. }
  411. }
  412. }
  413. std::vector<ContentProviderEntry> RegisteredCache::ListEntriesFilter(
  414. std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
  415. std::optional<u64> title_id) const {
  416. std::vector<ContentProviderEntry> out;
  417. IterateAllMetadata<ContentProviderEntry>(
  418. out,
  419. [](const CNMT& c, const ContentRecord& r) {
  420. return ContentProviderEntry{c.GetTitleID(), r.type};
  421. },
  422. [&title_type, &record_type, &title_id](const CNMT& c, const ContentRecord& r) {
  423. if (title_type && *title_type != c.GetType())
  424. return false;
  425. if (record_type && *record_type != r.type)
  426. return false;
  427. if (title_id && *title_id != c.GetTitleID())
  428. return false;
  429. return true;
  430. });
  431. return out;
  432. }
  433. static std::shared_ptr<NCA> GetNCAFromNSPForID(const NSP& nsp, const NcaID& id) {
  434. auto file = nsp.GetFile(fmt::format("{}.nca", Common::HexToString(id, false)));
  435. if (file == nullptr) {
  436. return nullptr;
  437. }
  438. return std::make_shared<NCA>(std::move(file));
  439. }
  440. InstallResult RegisteredCache::InstallEntry(const XCI& xci, bool overwrite_if_exists,
  441. const VfsCopyFunction& copy) {
  442. return InstallEntry(*xci.GetSecurePartitionNSP(), overwrite_if_exists, copy);
  443. }
  444. InstallResult RegisteredCache::InstallEntry(const NSP& nsp, bool overwrite_if_exists,
  445. const VfsCopyFunction& copy) {
  446. const auto ncas = nsp.GetNCAsCollapsed();
  447. const auto meta_iter = std::find_if(ncas.begin(), ncas.end(), [](const auto& nca) {
  448. return nca->GetType() == NCAContentType::Meta;
  449. });
  450. if (meta_iter == ncas.end()) {
  451. LOG_ERROR(Loader, "The file you are attempting to install does not have a metadata NCA and "
  452. "is therefore malformed. Check your encryption keys.");
  453. return InstallResult::ErrorMetaFailed;
  454. }
  455. // Install Metadata File
  456. const auto meta_id_raw = (*meta_iter)->GetName().substr(0, 32);
  457. const auto meta_id = Common::HexStringToArray<16>(meta_id_raw);
  458. const auto res = RawInstallNCA(**meta_iter, copy, overwrite_if_exists, meta_id);
  459. if (res != InstallResult::Success)
  460. return res;
  461. // Install all the other NCAs
  462. const auto section0 = (*meta_iter)->GetSubdirectories()[0];
  463. const auto cnmt_file = section0->GetFiles()[0];
  464. const CNMT cnmt(cnmt_file);
  465. for (const auto& record : cnmt.GetContentRecords()) {
  466. // Ignore DeltaFragments, they are not useful to us
  467. if (record.type == ContentRecordType::DeltaFragment)
  468. continue;
  469. const auto nca = GetNCAFromNSPForID(nsp, record.nca_id);
  470. if (nca == nullptr)
  471. return InstallResult::ErrorCopyFailed;
  472. const auto res2 = RawInstallNCA(*nca, copy, overwrite_if_exists, record.nca_id);
  473. if (res2 != InstallResult::Success)
  474. return res2;
  475. }
  476. Refresh();
  477. return InstallResult::Success;
  478. }
  479. InstallResult RegisteredCache::InstallEntry(const NCA& nca, TitleType type,
  480. bool overwrite_if_exists, const VfsCopyFunction& copy) {
  481. CNMTHeader header{
  482. nca.GetTitleId(), // Title ID
  483. 0, // Ignore/Default title version
  484. type, // Type
  485. {}, // Padding
  486. 0x10, // Default table offset
  487. 1, // 1 Content Entry
  488. 0, // No Meta Entries
  489. {}, // Padding
  490. {}, // Reserved 1
  491. 0, // Is committed
  492. 0, // Required download system version
  493. {}, // Reserved 2
  494. };
  495. OptionalHeader opt_header{0, 0};
  496. ContentRecord c_rec{{}, {}, {}, GetCRTypeFromNCAType(nca.GetType()), {}};
  497. const auto& data = nca.GetBaseFile()->ReadBytes(0x100000);
  498. mbedtls_sha256_ret(data.data(), data.size(), c_rec.hash.data(), 0);
  499. memcpy(&c_rec.nca_id, &c_rec.hash, 16);
  500. const CNMT new_cnmt(header, opt_header, {c_rec}, {});
  501. if (!RawInstallYuzuMeta(new_cnmt))
  502. return InstallResult::ErrorMetaFailed;
  503. return RawInstallNCA(nca, copy, overwrite_if_exists, c_rec.nca_id);
  504. }
  505. InstallResult RegisteredCache::RawInstallNCA(const NCA& nca, const VfsCopyFunction& copy,
  506. bool overwrite_if_exists,
  507. std::optional<NcaID> override_id) {
  508. const auto in = nca.GetBaseFile();
  509. Core::Crypto::SHA256Hash hash{};
  510. // Calculate NcaID
  511. // NOTE: Because computing the SHA256 of an entire NCA is quite expensive (especially if the
  512. // game is massive), we're going to cheat and only hash the first MB of the NCA.
  513. // Also, for XCIs the NcaID matters, so if the override id isn't none, use that.
  514. NcaID id{};
  515. if (override_id) {
  516. id = *override_id;
  517. } else {
  518. const auto& data = in->ReadBytes(0x100000);
  519. mbedtls_sha256_ret(data.data(), data.size(), hash.data(), 0);
  520. memcpy(id.data(), hash.data(), 16);
  521. }
  522. std::string path = GetRelativePathFromNcaID(id, false, true, false);
  523. if (GetFileAtID(id) != nullptr && !overwrite_if_exists) {
  524. LOG_WARNING(Loader, "Attempting to overwrite existing NCA. Skipping...");
  525. return InstallResult::ErrorAlreadyExists;
  526. }
  527. if (GetFileAtID(id) != nullptr) {
  528. LOG_WARNING(Loader, "Overwriting existing NCA...");
  529. VirtualDir c_dir;
  530. { c_dir = dir->GetFileRelative(path)->GetContainingDirectory(); }
  531. c_dir->DeleteFile(FileUtil::GetFilename(path));
  532. }
  533. auto out = dir->CreateFileRelative(path);
  534. if (out == nullptr)
  535. return InstallResult::ErrorCopyFailed;
  536. return copy(in, out, VFS_RC_LARGE_COPY_BLOCK) ? InstallResult::Success
  537. : InstallResult::ErrorCopyFailed;
  538. }
  539. bool RegisteredCache::RawInstallYuzuMeta(const CNMT& cnmt) {
  540. // Reasoning behind this method can be found in the comment for InstallEntry, NCA overload.
  541. const auto dir = this->dir->CreateDirectoryRelative("yuzu_meta");
  542. const auto filename = GetCNMTName(cnmt.GetType(), cnmt.GetTitleID());
  543. if (dir->GetFile(filename) == nullptr) {
  544. auto out = dir->CreateFile(filename);
  545. const auto buffer = cnmt.Serialize();
  546. out->Resize(buffer.size());
  547. out->WriteBytes(buffer);
  548. } else {
  549. auto out = dir->GetFile(filename);
  550. CNMT old_cnmt(out);
  551. // Returns true on change
  552. if (old_cnmt.UnionRecords(cnmt)) {
  553. out->Resize(0);
  554. const auto buffer = old_cnmt.Serialize();
  555. out->Resize(buffer.size());
  556. out->WriteBytes(buffer);
  557. }
  558. }
  559. Refresh();
  560. return std::find_if(yuzu_meta.begin(), yuzu_meta.end(),
  561. [&cnmt](const std::pair<u64, CNMT>& kv) {
  562. return kv.second.GetType() == cnmt.GetType() &&
  563. kv.second.GetTitleID() == cnmt.GetTitleID();
  564. }) != yuzu_meta.end();
  565. }
  566. ContentProviderUnion::~ContentProviderUnion() = default;
  567. void ContentProviderUnion::SetSlot(ContentProviderUnionSlot slot, ContentProvider* provider) {
  568. providers[slot] = provider;
  569. }
  570. void ContentProviderUnion::ClearSlot(ContentProviderUnionSlot slot) {
  571. providers[slot] = nullptr;
  572. }
  573. void ContentProviderUnion::Refresh() {
  574. for (auto& provider : providers) {
  575. if (provider.second == nullptr)
  576. continue;
  577. provider.second->Refresh();
  578. }
  579. }
  580. bool ContentProviderUnion::HasEntry(u64 title_id, ContentRecordType type) const {
  581. for (const auto& provider : providers) {
  582. if (provider.second == nullptr)
  583. continue;
  584. if (provider.second->HasEntry(title_id, type))
  585. return true;
  586. }
  587. return false;
  588. }
  589. std::optional<u32> ContentProviderUnion::GetEntryVersion(u64 title_id) const {
  590. for (const auto& provider : providers) {
  591. if (provider.second == nullptr)
  592. continue;
  593. const auto res = provider.second->GetEntryVersion(title_id);
  594. if (res != std::nullopt)
  595. return res;
  596. }
  597. return std::nullopt;
  598. }
  599. VirtualFile ContentProviderUnion::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
  600. for (const auto& provider : providers) {
  601. if (provider.second == nullptr)
  602. continue;
  603. const auto res = provider.second->GetEntryUnparsed(title_id, type);
  604. if (res != nullptr)
  605. return res;
  606. }
  607. return nullptr;
  608. }
  609. VirtualFile ContentProviderUnion::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  610. for (const auto& provider : providers) {
  611. if (provider.second == nullptr)
  612. continue;
  613. const auto res = provider.second->GetEntryRaw(title_id, type);
  614. if (res != nullptr)
  615. return res;
  616. }
  617. return nullptr;
  618. }
  619. std::unique_ptr<NCA> ContentProviderUnion::GetEntry(u64 title_id, ContentRecordType type) const {
  620. for (const auto& provider : providers) {
  621. if (provider.second == nullptr)
  622. continue;
  623. auto res = provider.second->GetEntry(title_id, type);
  624. if (res != nullptr)
  625. return res;
  626. }
  627. return nullptr;
  628. }
  629. std::vector<ContentProviderEntry> ContentProviderUnion::ListEntriesFilter(
  630. std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
  631. std::optional<u64> title_id) const {
  632. std::vector<ContentProviderEntry> out;
  633. for (const auto& provider : providers) {
  634. if (provider.second == nullptr)
  635. continue;
  636. const auto vec = provider.second->ListEntriesFilter(title_type, record_type, title_id);
  637. std::copy(vec.begin(), vec.end(), std::back_inserter(out));
  638. }
  639. std::sort(out.begin(), out.end());
  640. out.erase(std::unique(out.begin(), out.end()), out.end());
  641. return out;
  642. }
  643. std::vector<std::pair<ContentProviderUnionSlot, ContentProviderEntry>>
  644. ContentProviderUnion::ListEntriesFilterOrigin(std::optional<ContentProviderUnionSlot> origin,
  645. std::optional<TitleType> title_type,
  646. std::optional<ContentRecordType> record_type,
  647. std::optional<u64> title_id) const {
  648. std::vector<std::pair<ContentProviderUnionSlot, ContentProviderEntry>> out;
  649. for (const auto& provider : providers) {
  650. if (provider.second == nullptr)
  651. continue;
  652. if (origin.has_value() && *origin != provider.first)
  653. continue;
  654. const auto vec = provider.second->ListEntriesFilter(title_type, record_type, title_id);
  655. std::transform(vec.begin(), vec.end(), std::back_inserter(out),
  656. [&provider](const ContentProviderEntry& entry) {
  657. return std::make_pair(provider.first, entry);
  658. });
  659. }
  660. std::sort(out.begin(), out.end());
  661. out.erase(std::unique(out.begin(), out.end()), out.end());
  662. return out;
  663. }
  664. std::optional<ContentProviderUnionSlot> ContentProviderUnion::GetSlotForEntry(
  665. u64 title_id, ContentRecordType type) const {
  666. const auto iter =
  667. std::find_if(providers.begin(), providers.end(), [title_id, type](const auto& provider) {
  668. return provider.second != nullptr && provider.second->HasEntry(title_id, type);
  669. });
  670. if (iter == providers.end()) {
  671. return std::nullopt;
  672. }
  673. return iter->first;
  674. }
  675. ManualContentProvider::~ManualContentProvider() = default;
  676. void ManualContentProvider::AddEntry(TitleType title_type, ContentRecordType content_type,
  677. u64 title_id, VirtualFile file) {
  678. entries.insert_or_assign({title_type, content_type, title_id}, file);
  679. }
  680. void ManualContentProvider::ClearAllEntries() {
  681. entries.clear();
  682. }
  683. void ManualContentProvider::Refresh() {}
  684. bool ManualContentProvider::HasEntry(u64 title_id, ContentRecordType type) const {
  685. return GetEntryRaw(title_id, type) != nullptr;
  686. }
  687. std::optional<u32> ManualContentProvider::GetEntryVersion(u64 title_id) const {
  688. return std::nullopt;
  689. }
  690. VirtualFile ManualContentProvider::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
  691. return GetEntryRaw(title_id, type);
  692. }
  693. VirtualFile ManualContentProvider::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  694. const auto iter =
  695. std::find_if(entries.begin(), entries.end(), [title_id, type](const auto& entry) {
  696. const auto content_type = std::get<1>(entry.first);
  697. const auto e_title_id = std::get<2>(entry.first);
  698. return content_type == type && e_title_id == title_id;
  699. });
  700. if (iter == entries.end())
  701. return nullptr;
  702. return iter->second;
  703. }
  704. std::unique_ptr<NCA> ManualContentProvider::GetEntry(u64 title_id, ContentRecordType type) const {
  705. const auto res = GetEntryRaw(title_id, type);
  706. if (res == nullptr)
  707. return nullptr;
  708. return std::make_unique<NCA>(res, nullptr, 0);
  709. }
  710. std::vector<ContentProviderEntry> ManualContentProvider::ListEntriesFilter(
  711. std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
  712. std::optional<u64> title_id) const {
  713. std::vector<ContentProviderEntry> out;
  714. for (const auto& entry : entries) {
  715. const auto [e_title_type, e_content_type, e_title_id] = entry.first;
  716. if ((title_type == std::nullopt || e_title_type == *title_type) &&
  717. (record_type == std::nullopt || e_content_type == *record_type) &&
  718. (title_id == std::nullopt || e_title_id == *title_id)) {
  719. out.emplace_back(ContentProviderEntry{e_title_id, e_content_type});
  720. }
  721. }
  722. std::sort(out.begin(), out.end());
  723. out.erase(std::unique(out.begin(), out.end()), out.end());
  724. return out;
  725. }
  726. } // namespace FileSys