registered_cache.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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. const auto cmnt_iter = map.find(title_id);
  277. if (cmnt_iter == map.cend()) {
  278. return std::nullopt;
  279. }
  280. const auto& cnmt = cmnt_iter->second;
  281. const auto& content_records = cnmt.GetContentRecords();
  282. const auto iter = std::find_if(content_records.cbegin(), content_records.cend(),
  283. [type](const ContentRecord& rec) { return rec.type == type; });
  284. if (iter == content_records.cend()) {
  285. return std::nullopt;
  286. }
  287. return std::make_optional(iter->nca_id);
  288. }
  289. std::optional<NcaID> RegisteredCache::GetNcaIDFromMetadata(u64 title_id,
  290. ContentRecordType type) const {
  291. if (type == ContentRecordType::Meta && meta_id.find(title_id) != meta_id.end())
  292. return meta_id.at(title_id);
  293. const auto res1 = CheckMapForContentRecord(yuzu_meta, title_id, type);
  294. if (res1)
  295. return res1;
  296. return CheckMapForContentRecord(meta, title_id, type);
  297. }
  298. std::vector<NcaID> RegisteredCache::AccumulateFiles() const {
  299. std::vector<NcaID> ids;
  300. for (const auto& d2_dir : dir->GetSubdirectories()) {
  301. if (FollowsNcaIdFormat(d2_dir->GetName())) {
  302. ids.push_back(Common::HexStringToArray<0x10, true>(d2_dir->GetName().substr(0, 0x20)));
  303. continue;
  304. }
  305. if (!FollowsTwoDigitDirFormat(d2_dir->GetName()))
  306. continue;
  307. for (const auto& nca_dir : d2_dir->GetSubdirectories()) {
  308. if (!FollowsNcaIdFormat(nca_dir->GetName()))
  309. continue;
  310. ids.push_back(Common::HexStringToArray<0x10, true>(nca_dir->GetName().substr(0, 0x20)));
  311. }
  312. for (const auto& nca_file : d2_dir->GetFiles()) {
  313. if (!FollowsNcaIdFormat(nca_file->GetName()))
  314. continue;
  315. ids.push_back(
  316. Common::HexStringToArray<0x10, true>(nca_file->GetName().substr(0, 0x20)));
  317. }
  318. }
  319. for (const auto& d2_file : dir->GetFiles()) {
  320. if (FollowsNcaIdFormat(d2_file->GetName()))
  321. ids.push_back(Common::HexStringToArray<0x10, true>(d2_file->GetName().substr(0, 0x20)));
  322. }
  323. return ids;
  324. }
  325. void RegisteredCache::ProcessFiles(const std::vector<NcaID>& ids) {
  326. for (const auto& id : ids) {
  327. const auto file = GetFileAtID(id);
  328. if (file == nullptr)
  329. continue;
  330. const auto nca = std::make_shared<NCA>(parser(file, id), nullptr, 0);
  331. if (nca->GetStatus() != Loader::ResultStatus::Success ||
  332. nca->GetType() != NCAContentType::Meta) {
  333. continue;
  334. }
  335. const auto section0 = nca->GetSubdirectories()[0];
  336. for (const auto& section0_file : section0->GetFiles()) {
  337. if (section0_file->GetExtension() != "cnmt")
  338. continue;
  339. meta.insert_or_assign(nca->GetTitleId(), CNMT(section0_file));
  340. meta_id.insert_or_assign(nca->GetTitleId(), id);
  341. break;
  342. }
  343. }
  344. }
  345. void RegisteredCache::AccumulateYuzuMeta() {
  346. const auto dir = this->dir->GetSubdirectory("yuzu_meta");
  347. if (dir == nullptr)
  348. return;
  349. for (const auto& file : dir->GetFiles()) {
  350. if (file->GetExtension() != "cnmt")
  351. continue;
  352. CNMT cnmt(file);
  353. yuzu_meta.insert_or_assign(cnmt.GetTitleID(), std::move(cnmt));
  354. }
  355. }
  356. void RegisteredCache::Refresh() {
  357. if (dir == nullptr)
  358. return;
  359. const auto ids = AccumulateFiles();
  360. ProcessFiles(ids);
  361. AccumulateYuzuMeta();
  362. }
  363. RegisteredCache::RegisteredCache(VirtualDir dir_, ContentProviderParsingFunction parsing_function)
  364. : dir(std::move(dir_)), parser(std::move(parsing_function)) {
  365. Refresh();
  366. }
  367. RegisteredCache::~RegisteredCache() = default;
  368. bool RegisteredCache::HasEntry(u64 title_id, ContentRecordType type) const {
  369. return GetEntryRaw(title_id, type) != nullptr;
  370. }
  371. VirtualFile RegisteredCache::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
  372. const auto id = GetNcaIDFromMetadata(title_id, type);
  373. return id ? GetFileAtID(*id) : nullptr;
  374. }
  375. std::optional<u32> RegisteredCache::GetEntryVersion(u64 title_id) const {
  376. const auto meta_iter = meta.find(title_id);
  377. if (meta_iter != meta.cend()) {
  378. return meta_iter->second.GetTitleVersion();
  379. }
  380. const auto yuzu_meta_iter = yuzu_meta.find(title_id);
  381. if (yuzu_meta_iter != yuzu_meta.cend()) {
  382. return yuzu_meta_iter->second.GetTitleVersion();
  383. }
  384. return std::nullopt;
  385. }
  386. VirtualFile RegisteredCache::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  387. const auto id = GetNcaIDFromMetadata(title_id, type);
  388. return id ? parser(GetFileAtID(*id), *id) : nullptr;
  389. }
  390. std::unique_ptr<NCA> RegisteredCache::GetEntry(u64 title_id, ContentRecordType type) const {
  391. const auto raw = GetEntryRaw(title_id, type);
  392. if (raw == nullptr)
  393. return nullptr;
  394. return std::make_unique<NCA>(raw, nullptr, 0);
  395. }
  396. template <typename T>
  397. void RegisteredCache::IterateAllMetadata(
  398. std::vector<T>& out, std::function<T(const CNMT&, const ContentRecord&)> proc,
  399. std::function<bool(const CNMT&, const ContentRecord&)> filter) const {
  400. for (const auto& kv : meta) {
  401. const auto& cnmt = kv.second;
  402. if (filter(cnmt, EMPTY_META_CONTENT_RECORD))
  403. out.push_back(proc(cnmt, EMPTY_META_CONTENT_RECORD));
  404. for (const auto& rec : cnmt.GetContentRecords()) {
  405. if (GetFileAtID(rec.nca_id) != nullptr && filter(cnmt, rec)) {
  406. out.push_back(proc(cnmt, rec));
  407. }
  408. }
  409. }
  410. for (const auto& kv : yuzu_meta) {
  411. const auto& cnmt = kv.second;
  412. for (const auto& rec : cnmt.GetContentRecords()) {
  413. if (GetFileAtID(rec.nca_id) != nullptr && filter(cnmt, rec)) {
  414. out.push_back(proc(cnmt, rec));
  415. }
  416. }
  417. }
  418. }
  419. std::vector<ContentProviderEntry> RegisteredCache::ListEntriesFilter(
  420. std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
  421. std::optional<u64> title_id) const {
  422. std::vector<ContentProviderEntry> out;
  423. IterateAllMetadata<ContentProviderEntry>(
  424. out,
  425. [](const CNMT& c, const ContentRecord& r) {
  426. return ContentProviderEntry{c.GetTitleID(), r.type};
  427. },
  428. [&title_type, &record_type, &title_id](const CNMT& c, const ContentRecord& r) {
  429. if (title_type && *title_type != c.GetType())
  430. return false;
  431. if (record_type && *record_type != r.type)
  432. return false;
  433. if (title_id && *title_id != c.GetTitleID())
  434. return false;
  435. return true;
  436. });
  437. return out;
  438. }
  439. static std::shared_ptr<NCA> GetNCAFromNSPForID(const NSP& nsp, const NcaID& id) {
  440. auto file = nsp.GetFile(fmt::format("{}.nca", Common::HexToString(id, false)));
  441. if (file == nullptr) {
  442. return nullptr;
  443. }
  444. return std::make_shared<NCA>(std::move(file));
  445. }
  446. InstallResult RegisteredCache::InstallEntry(const XCI& xci, bool overwrite_if_exists,
  447. const VfsCopyFunction& copy) {
  448. return InstallEntry(*xci.GetSecurePartitionNSP(), overwrite_if_exists, copy);
  449. }
  450. InstallResult RegisteredCache::InstallEntry(const NSP& nsp, bool overwrite_if_exists,
  451. const VfsCopyFunction& copy) {
  452. const auto ncas = nsp.GetNCAsCollapsed();
  453. const auto meta_iter = std::find_if(ncas.begin(), ncas.end(), [](const auto& nca) {
  454. return nca->GetType() == NCAContentType::Meta;
  455. });
  456. if (meta_iter == ncas.end()) {
  457. LOG_ERROR(Loader, "The file you are attempting to install does not have a metadata NCA and "
  458. "is therefore malformed. Check your encryption keys.");
  459. return InstallResult::ErrorMetaFailed;
  460. }
  461. const auto meta_id_raw = (*meta_iter)->GetName().substr(0, 32);
  462. const auto meta_id = Common::HexStringToArray<16>(meta_id_raw);
  463. if ((*meta_iter)->GetSubdirectories().empty()) {
  464. LOG_ERROR(Loader,
  465. "The file you are attempting to install does not contain a section0 within the "
  466. "metadata NCA and is therefore malformed. Verify that the file is valid.");
  467. return InstallResult::ErrorMetaFailed;
  468. }
  469. const auto section0 = (*meta_iter)->GetSubdirectories()[0];
  470. if (section0->GetFiles().empty()) {
  471. LOG_ERROR(Loader,
  472. "The file you are attempting to install does not contain a CNMT within the "
  473. "metadata NCA and is therefore malformed. Verify that the file is valid.");
  474. return InstallResult::ErrorMetaFailed;
  475. }
  476. const auto cnmt_file = section0->GetFiles()[0];
  477. const CNMT cnmt(cnmt_file);
  478. const auto title_id = cnmt.GetTitleID();
  479. const auto result = RemoveExistingEntry(title_id);
  480. // Install Metadata File
  481. const auto res = RawInstallNCA(**meta_iter, copy, overwrite_if_exists, meta_id);
  482. if (res != InstallResult::Success) {
  483. return res;
  484. }
  485. // Install all the other NCAs
  486. for (const auto& record : cnmt.GetContentRecords()) {
  487. // Ignore DeltaFragments, they are not useful to us
  488. if (record.type == ContentRecordType::DeltaFragment) {
  489. continue;
  490. }
  491. const auto nca = GetNCAFromNSPForID(nsp, record.nca_id);
  492. if (nca == nullptr) {
  493. return InstallResult::ErrorCopyFailed;
  494. }
  495. const auto res2 = RawInstallNCA(*nca, copy, overwrite_if_exists, record.nca_id);
  496. if (res2 != InstallResult::Success) {
  497. return res2;
  498. }
  499. }
  500. Refresh();
  501. if (result) {
  502. return InstallResult::OverwriteExisting;
  503. }
  504. return InstallResult::Success;
  505. }
  506. InstallResult RegisteredCache::InstallEntry(const NCA& nca, TitleType type,
  507. bool overwrite_if_exists, const VfsCopyFunction& copy) {
  508. CNMTHeader header{
  509. nca.GetTitleId(), // Title ID
  510. 0, // Ignore/Default title version
  511. type, // Type
  512. {}, // Padding
  513. 0x10, // Default table offset
  514. 1, // 1 Content Entry
  515. 0, // No Meta Entries
  516. {}, // Padding
  517. {}, // Reserved 1
  518. 0, // Is committed
  519. 0, // Required download system version
  520. {}, // Reserved 2
  521. };
  522. OptionalHeader opt_header{0, 0};
  523. ContentRecord c_rec{{}, {}, {}, GetCRTypeFromNCAType(nca.GetType()), {}};
  524. const auto& data = nca.GetBaseFile()->ReadBytes(0x100000);
  525. mbedtls_sha256_ret(data.data(), data.size(), c_rec.hash.data(), 0);
  526. memcpy(&c_rec.nca_id, &c_rec.hash, 16);
  527. const CNMT new_cnmt(header, opt_header, {c_rec}, {});
  528. if (!RawInstallYuzuMeta(new_cnmt)) {
  529. return InstallResult::ErrorMetaFailed;
  530. }
  531. return RawInstallNCA(nca, copy, overwrite_if_exists, c_rec.nca_id);
  532. }
  533. bool RegisteredCache::RemoveExistingEntry(u64 title_id) const {
  534. const auto delete_nca = [this](const NcaID& id) {
  535. const auto path = GetRelativePathFromNcaID(id, false, true, false);
  536. const bool isFile = dir->GetFileRelative(path) != nullptr;
  537. const bool isDir = dir->GetDirectoryRelative(path) != nullptr;
  538. if (isFile) {
  539. return dir->DeleteFile(path);
  540. } else if (isDir) {
  541. return dir->DeleteSubdirectoryRecursive(path);
  542. }
  543. return false;
  544. };
  545. // If an entry exists in the registered cache, remove it
  546. if (HasEntry(title_id, ContentRecordType::Meta)) {
  547. LOG_INFO(Loader,
  548. "Previously installed entry (v{}) for title_id={:016X} detected! "
  549. "Attempting to remove...",
  550. GetEntryVersion(title_id).value_or(0), title_id);
  551. // Get all the ncas associated with the current CNMT and delete them
  552. const auto meta_old_id =
  553. GetNcaIDFromMetadata(title_id, ContentRecordType::Meta).value_or(NcaID{});
  554. const auto program_id =
  555. GetNcaIDFromMetadata(title_id, ContentRecordType::Program).value_or(NcaID{});
  556. const auto data_id =
  557. GetNcaIDFromMetadata(title_id, ContentRecordType::Data).value_or(NcaID{});
  558. const auto control_id =
  559. GetNcaIDFromMetadata(title_id, ContentRecordType::Control).value_or(NcaID{});
  560. const auto html_id =
  561. GetNcaIDFromMetadata(title_id, ContentRecordType::HtmlDocument).value_or(NcaID{});
  562. const auto legal_id =
  563. GetNcaIDFromMetadata(title_id, ContentRecordType::LegalInformation).value_or(NcaID{});
  564. const auto deleted_meta = delete_nca(meta_old_id);
  565. const auto deleted_program = delete_nca(program_id);
  566. const auto deleted_data = delete_nca(data_id);
  567. const auto deleted_control = delete_nca(control_id);
  568. const auto deleted_html = delete_nca(html_id);
  569. const auto deleted_legal = delete_nca(legal_id);
  570. return deleted_meta && (deleted_meta || deleted_program || deleted_data ||
  571. deleted_control || deleted_html || deleted_legal);
  572. }
  573. return false;
  574. }
  575. InstallResult RegisteredCache::RawInstallNCA(const NCA& nca, const VfsCopyFunction& copy,
  576. bool overwrite_if_exists,
  577. std::optional<NcaID> override_id) {
  578. const auto in = nca.GetBaseFile();
  579. Core::Crypto::SHA256Hash hash{};
  580. // Calculate NcaID
  581. // NOTE: Because computing the SHA256 of an entire NCA is quite expensive (especially if the
  582. // game is massive), we're going to cheat and only hash the first MB of the NCA.
  583. // Also, for XCIs the NcaID matters, so if the override id isn't none, use that.
  584. NcaID id{};
  585. if (override_id) {
  586. id = *override_id;
  587. } else {
  588. const auto& data = in->ReadBytes(0x100000);
  589. mbedtls_sha256_ret(data.data(), data.size(), hash.data(), 0);
  590. memcpy(id.data(), hash.data(), 16);
  591. }
  592. std::string path = GetRelativePathFromNcaID(id, false, true, false);
  593. if (GetFileAtID(id) != nullptr && !overwrite_if_exists) {
  594. LOG_WARNING(Loader, "Attempting to overwrite existing NCA. Skipping...");
  595. return InstallResult::ErrorAlreadyExists;
  596. }
  597. if (GetFileAtID(id) != nullptr) {
  598. LOG_WARNING(Loader, "Overwriting existing NCA...");
  599. VirtualDir c_dir;
  600. { c_dir = dir->GetFileRelative(path)->GetContainingDirectory(); }
  601. c_dir->DeleteFile(Common::FS::GetFilename(path));
  602. }
  603. auto out = dir->CreateFileRelative(path);
  604. if (out == nullptr) {
  605. return InstallResult::ErrorCopyFailed;
  606. }
  607. return copy(in, out, VFS_RC_LARGE_COPY_BLOCK) ? InstallResult::Success
  608. : InstallResult::ErrorCopyFailed;
  609. }
  610. bool RegisteredCache::RawInstallYuzuMeta(const CNMT& cnmt) {
  611. // Reasoning behind this method can be found in the comment for InstallEntry, NCA overload.
  612. const auto dir = this->dir->CreateDirectoryRelative("yuzu_meta");
  613. const auto filename = GetCNMTName(cnmt.GetType(), cnmt.GetTitleID());
  614. if (dir->GetFile(filename) == nullptr) {
  615. auto out = dir->CreateFile(filename);
  616. const auto buffer = cnmt.Serialize();
  617. out->Resize(buffer.size());
  618. out->WriteBytes(buffer);
  619. } else {
  620. auto out = dir->GetFile(filename);
  621. CNMT old_cnmt(out);
  622. // Returns true on change
  623. if (old_cnmt.UnionRecords(cnmt)) {
  624. out->Resize(0);
  625. const auto buffer = old_cnmt.Serialize();
  626. out->Resize(buffer.size());
  627. out->WriteBytes(buffer);
  628. }
  629. }
  630. Refresh();
  631. return std::find_if(yuzu_meta.begin(), yuzu_meta.end(),
  632. [&cnmt](const std::pair<u64, CNMT>& kv) {
  633. return kv.second.GetType() == cnmt.GetType() &&
  634. kv.second.GetTitleID() == cnmt.GetTitleID();
  635. }) != yuzu_meta.end();
  636. }
  637. ContentProviderUnion::~ContentProviderUnion() = default;
  638. void ContentProviderUnion::SetSlot(ContentProviderUnionSlot slot, ContentProvider* provider) {
  639. providers[slot] = provider;
  640. }
  641. void ContentProviderUnion::ClearSlot(ContentProviderUnionSlot slot) {
  642. providers[slot] = nullptr;
  643. }
  644. void ContentProviderUnion::Refresh() {
  645. for (auto& provider : providers) {
  646. if (provider.second == nullptr)
  647. continue;
  648. provider.second->Refresh();
  649. }
  650. }
  651. bool ContentProviderUnion::HasEntry(u64 title_id, ContentRecordType type) const {
  652. for (const auto& provider : providers) {
  653. if (provider.second == nullptr)
  654. continue;
  655. if (provider.second->HasEntry(title_id, type))
  656. return true;
  657. }
  658. return false;
  659. }
  660. std::optional<u32> ContentProviderUnion::GetEntryVersion(u64 title_id) const {
  661. for (const auto& provider : providers) {
  662. if (provider.second == nullptr)
  663. continue;
  664. const auto res = provider.second->GetEntryVersion(title_id);
  665. if (res != std::nullopt)
  666. return res;
  667. }
  668. return std::nullopt;
  669. }
  670. VirtualFile ContentProviderUnion::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
  671. for (const auto& provider : providers) {
  672. if (provider.second == nullptr)
  673. continue;
  674. const auto res = provider.second->GetEntryUnparsed(title_id, type);
  675. if (res != nullptr)
  676. return res;
  677. }
  678. return nullptr;
  679. }
  680. VirtualFile ContentProviderUnion::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  681. for (const auto& provider : providers) {
  682. if (provider.second == nullptr)
  683. continue;
  684. const auto res = provider.second->GetEntryRaw(title_id, type);
  685. if (res != nullptr)
  686. return res;
  687. }
  688. return nullptr;
  689. }
  690. std::unique_ptr<NCA> ContentProviderUnion::GetEntry(u64 title_id, ContentRecordType type) const {
  691. for (const auto& provider : providers) {
  692. if (provider.second == nullptr)
  693. continue;
  694. auto res = provider.second->GetEntry(title_id, type);
  695. if (res != nullptr)
  696. return res;
  697. }
  698. return nullptr;
  699. }
  700. std::vector<ContentProviderEntry> ContentProviderUnion::ListEntriesFilter(
  701. std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
  702. std::optional<u64> title_id) const {
  703. std::vector<ContentProviderEntry> out;
  704. for (const auto& provider : providers) {
  705. if (provider.second == nullptr)
  706. continue;
  707. const auto vec = provider.second->ListEntriesFilter(title_type, record_type, title_id);
  708. std::copy(vec.begin(), vec.end(), std::back_inserter(out));
  709. }
  710. std::sort(out.begin(), out.end());
  711. out.erase(std::unique(out.begin(), out.end()), out.end());
  712. return out;
  713. }
  714. std::vector<std::pair<ContentProviderUnionSlot, ContentProviderEntry>>
  715. ContentProviderUnion::ListEntriesFilterOrigin(std::optional<ContentProviderUnionSlot> origin,
  716. std::optional<TitleType> title_type,
  717. std::optional<ContentRecordType> record_type,
  718. std::optional<u64> title_id) const {
  719. std::vector<std::pair<ContentProviderUnionSlot, ContentProviderEntry>> out;
  720. for (const auto& provider : providers) {
  721. if (provider.second == nullptr)
  722. continue;
  723. if (origin.has_value() && *origin != provider.first)
  724. continue;
  725. const auto vec = provider.second->ListEntriesFilter(title_type, record_type, title_id);
  726. std::transform(vec.begin(), vec.end(), std::back_inserter(out),
  727. [&provider](const ContentProviderEntry& entry) {
  728. return std::make_pair(provider.first, entry);
  729. });
  730. }
  731. std::sort(out.begin(), out.end());
  732. out.erase(std::unique(out.begin(), out.end()), out.end());
  733. return out;
  734. }
  735. std::optional<ContentProviderUnionSlot> ContentProviderUnion::GetSlotForEntry(
  736. u64 title_id, ContentRecordType type) const {
  737. const auto iter =
  738. std::find_if(providers.begin(), providers.end(), [title_id, type](const auto& provider) {
  739. return provider.second != nullptr && provider.second->HasEntry(title_id, type);
  740. });
  741. if (iter == providers.end()) {
  742. return std::nullopt;
  743. }
  744. return iter->first;
  745. }
  746. ManualContentProvider::~ManualContentProvider() = default;
  747. void ManualContentProvider::AddEntry(TitleType title_type, ContentRecordType content_type,
  748. u64 title_id, VirtualFile file) {
  749. entries.insert_or_assign({title_type, content_type, title_id}, file);
  750. }
  751. void ManualContentProvider::ClearAllEntries() {
  752. entries.clear();
  753. }
  754. void ManualContentProvider::Refresh() {}
  755. bool ManualContentProvider::HasEntry(u64 title_id, ContentRecordType type) const {
  756. return GetEntryRaw(title_id, type) != nullptr;
  757. }
  758. std::optional<u32> ManualContentProvider::GetEntryVersion(u64 title_id) const {
  759. return std::nullopt;
  760. }
  761. VirtualFile ManualContentProvider::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
  762. return GetEntryRaw(title_id, type);
  763. }
  764. VirtualFile ManualContentProvider::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  765. const auto iter =
  766. std::find_if(entries.begin(), entries.end(), [title_id, type](const auto& entry) {
  767. const auto content_type = std::get<1>(entry.first);
  768. const auto e_title_id = std::get<2>(entry.first);
  769. return content_type == type && e_title_id == title_id;
  770. });
  771. if (iter == entries.end())
  772. return nullptr;
  773. return iter->second;
  774. }
  775. std::unique_ptr<NCA> ManualContentProvider::GetEntry(u64 title_id, ContentRecordType type) const {
  776. const auto res = GetEntryRaw(title_id, type);
  777. if (res == nullptr)
  778. return nullptr;
  779. return std::make_unique<NCA>(res, nullptr, 0);
  780. }
  781. std::vector<ContentProviderEntry> ManualContentProvider::ListEntriesFilter(
  782. std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
  783. std::optional<u64> title_id) const {
  784. std::vector<ContentProviderEntry> out;
  785. for (const auto& entry : entries) {
  786. const auto [e_title_type, e_content_type, e_title_id] = entry.first;
  787. if ((title_type == std::nullopt || e_title_type == *title_type) &&
  788. (record_type == std::nullopt || e_content_type == *record_type) &&
  789. (title_id == std::nullopt || e_title_id == *title_id)) {
  790. out.emplace_back(ContentProviderEntry{e_title_id, e_content_type});
  791. }
  792. }
  793. std::sort(out.begin(), out.end());
  794. out.erase(std::unique(out.begin(), out.end()), out.end());
  795. return out;
  796. }
  797. } // namespace FileSys