registered_cache.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  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. bool RegisteredCache::RemoveExistingEntry(u64 title_id) {
  445. const auto delete_nca = [this](const NcaID& id) {
  446. const auto path = GetRelativePathFromNcaID(id, false, true, false);
  447. if (dir->GetFileRelative(path) == nullptr) {
  448. return false;
  449. }
  450. Core::Crypto::SHA256Hash hash{};
  451. mbedtls_sha256_ret(id.data(), id.size(), hash.data(), 0);
  452. const auto dirname = fmt::format("000000{:02X}", hash[0]);
  453. const auto dir2 = GetOrCreateDirectoryRelative(dir, dirname);
  454. const auto res = dir2->DeleteFile(fmt::format("{}.nca", Common::HexToString(id, false)));
  455. return res;
  456. };
  457. // If an update exists, remove
  458. if (HasEntry(title_id, ContentRecordType::Meta)) {
  459. LOG_INFO(Loader,
  460. "Previous Update (v{}) for title_id={:016X} detected! Attempting to remove...",
  461. GetEntryVersion(title_id).value_or(0), title_id);
  462. // Get all the ncas associated with the current update CNMT and delete them
  463. const auto meta_old_id =
  464. GetNcaIDFromMetadata(title_id, ContentRecordType::Meta).value_or(NcaID{});
  465. const auto program_id =
  466. GetNcaIDFromMetadata(title_id, ContentRecordType::Program).value_or(NcaID{});
  467. const auto data_id =
  468. GetNcaIDFromMetadata(title_id, ContentRecordType::Data).value_or(NcaID{});
  469. const auto control_id =
  470. GetNcaIDFromMetadata(title_id, ContentRecordType::Control).value_or(NcaID{});
  471. const auto html_id =
  472. GetNcaIDFromMetadata(title_id, ContentRecordType::HtmlDocument).value_or(NcaID{});
  473. const auto legal_id =
  474. GetNcaIDFromMetadata(title_id, ContentRecordType::LegalInformation).value_or(NcaID{});
  475. delete_nca(meta_old_id);
  476. delete_nca(program_id);
  477. delete_nca(data_id);
  478. delete_nca(control_id);
  479. delete_nca(html_id);
  480. delete_nca(legal_id);
  481. return true;
  482. }
  483. return false;
  484. }
  485. InstallResult RegisteredCache::InstallEntry(const NSP& nsp, bool overwrite_if_exists,
  486. const VfsCopyFunction& copy) {
  487. const auto ncas = nsp.GetNCAsCollapsed();
  488. const auto meta_iter = std::find_if(ncas.begin(), ncas.end(), [](const auto& nca) {
  489. return nca->GetType() == NCAContentType::Meta;
  490. });
  491. if (meta_iter == ncas.end()) {
  492. LOG_ERROR(Loader, "The file you are attempting to install does not have a metadata NCA and "
  493. "is therefore malformed. Check your encryption keys.");
  494. return InstallResult::ErrorMetaFailed;
  495. }
  496. const auto meta_id_raw = (*meta_iter)->GetName().substr(0, 32);
  497. const auto meta_id = Common::HexStringToArray<16>(meta_id_raw);
  498. const auto section0 = (*meta_iter)->GetSubdirectories()[0];
  499. const auto cnmt_file = section0->GetFiles()[0];
  500. const CNMT cnmt(cnmt_file);
  501. const auto title_id = cnmt.GetTitleID();
  502. const auto result = RemoveExistingEntry(title_id);
  503. // Install Metadata File
  504. const auto res = RawInstallNCA(**meta_iter, copy, overwrite_if_exists, meta_id);
  505. if (res != InstallResult::Success) {
  506. return res;
  507. }
  508. // Install all the other NCAs
  509. for (const auto& record : cnmt.GetContentRecords()) {
  510. // Ignore DeltaFragments, they are not useful to us
  511. if (record.type == ContentRecordType::DeltaFragment) {
  512. continue;
  513. }
  514. const auto nca = GetNCAFromNSPForID(nsp, record.nca_id);
  515. if (nca == nullptr) {
  516. return InstallResult::ErrorCopyFailed;
  517. }
  518. const auto res2 = RawInstallNCA(*nca, copy, overwrite_if_exists, record.nca_id);
  519. if (res2 != InstallResult::Success) {
  520. return res2;
  521. }
  522. }
  523. Refresh();
  524. if (result) {
  525. return InstallResult::ErrorAlreadyExists;
  526. }
  527. return InstallResult::Success;
  528. }
  529. InstallResult RegisteredCache::InstallEntry(const NCA& nca, TitleType type,
  530. bool overwrite_if_exists, const VfsCopyFunction& copy) {
  531. CNMTHeader header{
  532. nca.GetTitleId(), // Title ID
  533. 0, // Ignore/Default title version
  534. type, // Type
  535. {}, // Padding
  536. 0x10, // Default table offset
  537. 1, // 1 Content Entry
  538. 0, // No Meta Entries
  539. {}, // Padding
  540. {}, // Reserved 1
  541. 0, // Is committed
  542. 0, // Required download system version
  543. {}, // Reserved 2
  544. };
  545. OptionalHeader opt_header{0, 0};
  546. ContentRecord c_rec{{}, {}, {}, GetCRTypeFromNCAType(nca.GetType()), {}};
  547. const auto& data = nca.GetBaseFile()->ReadBytes(0x100000);
  548. mbedtls_sha256_ret(data.data(), data.size(), c_rec.hash.data(), 0);
  549. memcpy(&c_rec.nca_id, &c_rec.hash, 16);
  550. const CNMT new_cnmt(header, opt_header, {c_rec}, {});
  551. if (!RawInstallYuzuMeta(new_cnmt)) {
  552. return InstallResult::ErrorMetaFailed;
  553. }
  554. return RawInstallNCA(nca, copy, overwrite_if_exists, c_rec.nca_id);
  555. }
  556. InstallResult RegisteredCache::RawInstallNCA(const NCA& nca, const VfsCopyFunction& copy,
  557. bool overwrite_if_exists,
  558. std::optional<NcaID> override_id) {
  559. const auto in = nca.GetBaseFile();
  560. Core::Crypto::SHA256Hash hash{};
  561. // Calculate NcaID
  562. // NOTE: Because computing the SHA256 of an entire NCA is quite expensive (especially if the
  563. // game is massive), we're going to cheat and only hash the first MB of the NCA.
  564. // Also, for XCIs the NcaID matters, so if the override id isn't none, use that.
  565. NcaID id{};
  566. if (override_id) {
  567. id = *override_id;
  568. } else {
  569. const auto& data = in->ReadBytes(0x100000);
  570. mbedtls_sha256_ret(data.data(), data.size(), hash.data(), 0);
  571. memcpy(id.data(), hash.data(), 16);
  572. }
  573. std::string path = GetRelativePathFromNcaID(id, false, true, false);
  574. if (GetFileAtID(id) != nullptr && !overwrite_if_exists) {
  575. LOG_WARNING(Loader, "Attempting to overwrite existing NCA. Skipping...");
  576. return InstallResult::ErrorAlreadyExists;
  577. }
  578. if (GetFileAtID(id) != nullptr) {
  579. LOG_WARNING(Loader, "Overwriting existing NCA...");
  580. VirtualDir c_dir;
  581. { c_dir = dir->GetFileRelative(path)->GetContainingDirectory(); }
  582. c_dir->DeleteFile(FileUtil::GetFilename(path));
  583. }
  584. auto out = dir->CreateFileRelative(path);
  585. if (out == nullptr) {
  586. return InstallResult::ErrorCopyFailed;
  587. }
  588. return copy(in, out, VFS_RC_LARGE_COPY_BLOCK) ? InstallResult::Success
  589. : InstallResult::ErrorCopyFailed;
  590. }
  591. bool RegisteredCache::RawInstallYuzuMeta(const CNMT& cnmt) {
  592. // Reasoning behind this method can be found in the comment for InstallEntry, NCA overload.
  593. const auto dir = this->dir->CreateDirectoryRelative("yuzu_meta");
  594. const auto filename = GetCNMTName(cnmt.GetType(), cnmt.GetTitleID());
  595. if (dir->GetFile(filename) == nullptr) {
  596. auto out = dir->CreateFile(filename);
  597. const auto buffer = cnmt.Serialize();
  598. out->Resize(buffer.size());
  599. out->WriteBytes(buffer);
  600. } else {
  601. auto out = dir->GetFile(filename);
  602. CNMT old_cnmt(out);
  603. // Returns true on change
  604. if (old_cnmt.UnionRecords(cnmt)) {
  605. out->Resize(0);
  606. const auto buffer = old_cnmt.Serialize();
  607. out->Resize(buffer.size());
  608. out->WriteBytes(buffer);
  609. }
  610. }
  611. Refresh();
  612. return std::find_if(yuzu_meta.begin(), yuzu_meta.end(),
  613. [&cnmt](const std::pair<u64, CNMT>& kv) {
  614. return kv.second.GetType() == cnmt.GetType() &&
  615. kv.second.GetTitleID() == cnmt.GetTitleID();
  616. }) != yuzu_meta.end();
  617. }
  618. ContentProviderUnion::~ContentProviderUnion() = default;
  619. void ContentProviderUnion::SetSlot(ContentProviderUnionSlot slot, ContentProvider* provider) {
  620. providers[slot] = provider;
  621. }
  622. void ContentProviderUnion::ClearSlot(ContentProviderUnionSlot slot) {
  623. providers[slot] = nullptr;
  624. }
  625. void ContentProviderUnion::Refresh() {
  626. for (auto& provider : providers) {
  627. if (provider.second == nullptr)
  628. continue;
  629. provider.second->Refresh();
  630. }
  631. }
  632. bool ContentProviderUnion::HasEntry(u64 title_id, ContentRecordType type) const {
  633. for (const auto& provider : providers) {
  634. if (provider.second == nullptr)
  635. continue;
  636. if (provider.second->HasEntry(title_id, type))
  637. return true;
  638. }
  639. return false;
  640. }
  641. std::optional<u32> ContentProviderUnion::GetEntryVersion(u64 title_id) const {
  642. for (const auto& provider : providers) {
  643. if (provider.second == nullptr)
  644. continue;
  645. const auto res = provider.second->GetEntryVersion(title_id);
  646. if (res != std::nullopt)
  647. return res;
  648. }
  649. return std::nullopt;
  650. }
  651. VirtualFile ContentProviderUnion::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
  652. for (const auto& provider : providers) {
  653. if (provider.second == nullptr)
  654. continue;
  655. const auto res = provider.second->GetEntryUnparsed(title_id, type);
  656. if (res != nullptr)
  657. return res;
  658. }
  659. return nullptr;
  660. }
  661. VirtualFile ContentProviderUnion::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  662. for (const auto& provider : providers) {
  663. if (provider.second == nullptr)
  664. continue;
  665. const auto res = provider.second->GetEntryRaw(title_id, type);
  666. if (res != nullptr)
  667. return res;
  668. }
  669. return nullptr;
  670. }
  671. std::unique_ptr<NCA> ContentProviderUnion::GetEntry(u64 title_id, ContentRecordType type) const {
  672. for (const auto& provider : providers) {
  673. if (provider.second == nullptr)
  674. continue;
  675. auto res = provider.second->GetEntry(title_id, type);
  676. if (res != nullptr)
  677. return res;
  678. }
  679. return nullptr;
  680. }
  681. std::vector<ContentProviderEntry> ContentProviderUnion::ListEntriesFilter(
  682. std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
  683. std::optional<u64> title_id) const {
  684. std::vector<ContentProviderEntry> out;
  685. for (const auto& provider : providers) {
  686. if (provider.second == nullptr)
  687. continue;
  688. const auto vec = provider.second->ListEntriesFilter(title_type, record_type, title_id);
  689. std::copy(vec.begin(), vec.end(), std::back_inserter(out));
  690. }
  691. std::sort(out.begin(), out.end());
  692. out.erase(std::unique(out.begin(), out.end()), out.end());
  693. return out;
  694. }
  695. std::vector<std::pair<ContentProviderUnionSlot, ContentProviderEntry>>
  696. ContentProviderUnion::ListEntriesFilterOrigin(std::optional<ContentProviderUnionSlot> origin,
  697. std::optional<TitleType> title_type,
  698. std::optional<ContentRecordType> record_type,
  699. std::optional<u64> title_id) const {
  700. std::vector<std::pair<ContentProviderUnionSlot, ContentProviderEntry>> out;
  701. for (const auto& provider : providers) {
  702. if (provider.second == nullptr)
  703. continue;
  704. if (origin.has_value() && *origin != provider.first)
  705. continue;
  706. const auto vec = provider.second->ListEntriesFilter(title_type, record_type, title_id);
  707. std::transform(vec.begin(), vec.end(), std::back_inserter(out),
  708. [&provider](const ContentProviderEntry& entry) {
  709. return std::make_pair(provider.first, entry);
  710. });
  711. }
  712. std::sort(out.begin(), out.end());
  713. out.erase(std::unique(out.begin(), out.end()), out.end());
  714. return out;
  715. }
  716. std::optional<ContentProviderUnionSlot> ContentProviderUnion::GetSlotForEntry(
  717. u64 title_id, ContentRecordType type) const {
  718. const auto iter =
  719. std::find_if(providers.begin(), providers.end(), [title_id, type](const auto& provider) {
  720. return provider.second != nullptr && provider.second->HasEntry(title_id, type);
  721. });
  722. if (iter == providers.end()) {
  723. return std::nullopt;
  724. }
  725. return iter->first;
  726. }
  727. ManualContentProvider::~ManualContentProvider() = default;
  728. void ManualContentProvider::AddEntry(TitleType title_type, ContentRecordType content_type,
  729. u64 title_id, VirtualFile file) {
  730. entries.insert_or_assign({title_type, content_type, title_id}, file);
  731. }
  732. void ManualContentProvider::ClearAllEntries() {
  733. entries.clear();
  734. }
  735. void ManualContentProvider::Refresh() {}
  736. bool ManualContentProvider::HasEntry(u64 title_id, ContentRecordType type) const {
  737. return GetEntryRaw(title_id, type) != nullptr;
  738. }
  739. std::optional<u32> ManualContentProvider::GetEntryVersion(u64 title_id) const {
  740. return std::nullopt;
  741. }
  742. VirtualFile ManualContentProvider::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
  743. return GetEntryRaw(title_id, type);
  744. }
  745. VirtualFile ManualContentProvider::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  746. const auto iter =
  747. std::find_if(entries.begin(), entries.end(), [title_id, type](const auto& entry) {
  748. const auto content_type = std::get<1>(entry.first);
  749. const auto e_title_id = std::get<2>(entry.first);
  750. return content_type == type && e_title_id == title_id;
  751. });
  752. if (iter == entries.end())
  753. return nullptr;
  754. return iter->second;
  755. }
  756. std::unique_ptr<NCA> ManualContentProvider::GetEntry(u64 title_id, ContentRecordType type) const {
  757. const auto res = GetEntryRaw(title_id, type);
  758. if (res == nullptr)
  759. return nullptr;
  760. return std::make_unique<NCA>(res, nullptr, 0);
  761. }
  762. std::vector<ContentProviderEntry> ManualContentProvider::ListEntriesFilter(
  763. std::optional<TitleType> title_type, std::optional<ContentRecordType> record_type,
  764. std::optional<u64> title_id) const {
  765. std::vector<ContentProviderEntry> out;
  766. for (const auto& entry : entries) {
  767. const auto [e_title_type, e_content_type, e_title_id] = entry.first;
  768. if ((title_type == std::nullopt || e_title_type == *title_type) &&
  769. (record_type == std::nullopt || e_content_type == *record_type) &&
  770. (title_id == std::nullopt || e_title_id == *title_id)) {
  771. out.emplace_back(ContentProviderEntry{e_title_id, e_content_type});
  772. }
  773. }
  774. std::sort(out.begin(), out.end());
  775. out.erase(std::unique(out.begin(), out.end()), out.end());
  776. return out;
  777. }
  778. } // namespace FileSys