registered_cache.cpp 34 KB

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