registered_cache.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <regex>
  5. #include <mbedtls/sha256.h>
  6. #include "common/assert.h"
  7. #include "common/file_util.h"
  8. #include "common/hex_util.h"
  9. #include "common/logging/log.h"
  10. #include "core/file_sys/card_image.h"
  11. #include "core/file_sys/nca_metadata.h"
  12. #include "core/file_sys/registered_cache.h"
  13. #include "core/file_sys/vfs_concat.h"
  14. namespace FileSys {
  15. std::string RegisteredCacheEntry::DebugInfo() const {
  16. return fmt::format("title_id={:016X}, content_type={:02X}", title_id, static_cast<u8>(type));
  17. }
  18. bool operator<(const RegisteredCacheEntry& lhs, const RegisteredCacheEntry& rhs) {
  19. return (lhs.title_id < rhs.title_id) || (lhs.title_id == rhs.title_id && lhs.type < rhs.type);
  20. }
  21. static bool FollowsTwoDigitDirFormat(std::string_view name) {
  22. static const std::regex two_digit_regex("000000[0-9A-F]{2}", std::regex_constants::ECMAScript |
  23. std::regex_constants::icase);
  24. return std::regex_match(name.begin(), name.end(), two_digit_regex);
  25. }
  26. static bool FollowsNcaIdFormat(std::string_view name) {
  27. static const std::regex nca_id_regex("[0-9A-F]{32}\\.nca", std::regex_constants::ECMAScript |
  28. std::regex_constants::icase);
  29. return name.size() == 36 && std::regex_match(name.begin(), name.end(), nca_id_regex);
  30. }
  31. static std::string GetRelativePathFromNcaID(const std::array<u8, 16>& nca_id, bool second_hex_upper,
  32. bool within_two_digit) {
  33. if (!within_two_digit)
  34. return fmt::format("/{}.nca", Common::HexArrayToString(nca_id, second_hex_upper));
  35. Core::Crypto::SHA256Hash hash{};
  36. mbedtls_sha256(nca_id.data(), nca_id.size(), hash.data(), 0);
  37. return fmt::format("/000000{:02X}/{}.nca", hash[0],
  38. Common::HexArrayToString(nca_id, second_hex_upper));
  39. }
  40. static std::string GetCNMTName(TitleType type, u64 title_id) {
  41. constexpr std::array<const char*, 9> TITLE_TYPE_NAMES{
  42. "SystemProgram",
  43. "SystemData",
  44. "SystemUpdate",
  45. "BootImagePackage",
  46. "BootImagePackageSafe",
  47. "Application",
  48. "Patch",
  49. "AddOnContent",
  50. "" ///< Currently unknown 'DeltaTitle'
  51. };
  52. auto index = static_cast<size_t>(type);
  53. // If the index is after the jump in TitleType, subtract it out.
  54. if (index >= static_cast<size_t>(TitleType::Application)) {
  55. index -= static_cast<size_t>(TitleType::Application) -
  56. static_cast<size_t>(TitleType::FirmwarePackageB);
  57. }
  58. return fmt::format("{}_{:016x}.cnmt", TITLE_TYPE_NAMES[index], title_id);
  59. }
  60. static ContentRecordType GetCRTypeFromNCAType(NCAContentType type) {
  61. switch (type) {
  62. case NCAContentType::Program:
  63. // TODO(DarkLordZach): Differentiate between Program and Patch
  64. return ContentRecordType::Program;
  65. case NCAContentType::Meta:
  66. return ContentRecordType::Meta;
  67. case NCAContentType::Control:
  68. return ContentRecordType::Control;
  69. case NCAContentType::Data:
  70. case NCAContentType::Data_Unknown5:
  71. return ContentRecordType::Data;
  72. case NCAContentType::Manual:
  73. // TODO(DarkLordZach): Peek at NCA contents to differentiate Manual and Legal.
  74. return ContentRecordType::Manual;
  75. default:
  76. UNREACHABLE_MSG("Invalid NCAContentType={:02X}", static_cast<u8>(type));
  77. }
  78. }
  79. VirtualFile RegisteredCache::OpenFileOrDirectoryConcat(const VirtualDir& dir,
  80. std::string_view path) const {
  81. if (dir->GetFileRelative(path) != nullptr)
  82. return dir->GetFileRelative(path);
  83. if (dir->GetDirectoryRelative(path) != nullptr) {
  84. const auto nca_dir = dir->GetDirectoryRelative(path);
  85. VirtualFile file = nullptr;
  86. const auto files = nca_dir->GetFiles();
  87. if (files.size() == 1 && files[0]->GetName() == "00") {
  88. file = files[0];
  89. } else {
  90. std::vector<VirtualFile> concat;
  91. // Since the files are a two-digit hex number, max is FF.
  92. for (size_t i = 0; i < 0x100; ++i) {
  93. auto next = nca_dir->GetFile(fmt::format("{:02X}", i));
  94. if (next != nullptr) {
  95. concat.push_back(std::move(next));
  96. } else {
  97. next = nca_dir->GetFile(fmt::format("{:02x}", i));
  98. if (next != nullptr)
  99. concat.push_back(std::move(next));
  100. else
  101. break;
  102. }
  103. }
  104. if (concat.empty())
  105. return nullptr;
  106. file = FileSys::ConcatenateFiles(concat);
  107. }
  108. return file;
  109. }
  110. return nullptr;
  111. }
  112. VirtualFile RegisteredCache::GetFileAtID(NcaID id) const {
  113. VirtualFile file;
  114. // Try all four modes of file storage:
  115. // (bit 1 = uppercase/lower, bit 0 = within a two-digit dir)
  116. // 00: /000000**/{:032X}.nca
  117. // 01: /{:032X}.nca
  118. // 10: /000000**/{:032x}.nca
  119. // 11: /{:032x}.nca
  120. for (u8 i = 0; i < 4; ++i) {
  121. const auto path = GetRelativePathFromNcaID(id, (i & 0b10) == 0, (i & 0b01) == 0);
  122. file = OpenFileOrDirectoryConcat(dir, path);
  123. if (file != nullptr)
  124. return file;
  125. }
  126. return file;
  127. }
  128. static boost::optional<NcaID> CheckMapForContentRecord(
  129. const boost::container::flat_map<u64, CNMT>& map, u64 title_id, ContentRecordType type) {
  130. if (map.find(title_id) == map.end())
  131. return boost::none;
  132. const auto& cnmt = map.at(title_id);
  133. const auto iter = std::find_if(cnmt.GetContentRecords().begin(), cnmt.GetContentRecords().end(),
  134. [type](const ContentRecord& rec) { return rec.type == type; });
  135. if (iter == cnmt.GetContentRecords().end())
  136. return boost::none;
  137. return boost::make_optional(iter->nca_id);
  138. }
  139. boost::optional<NcaID> RegisteredCache::GetNcaIDFromMetadata(u64 title_id,
  140. ContentRecordType type) const {
  141. if (type == ContentRecordType::Meta && meta_id.find(title_id) != meta_id.end())
  142. return meta_id.at(title_id);
  143. const auto res1 = CheckMapForContentRecord(yuzu_meta, title_id, type);
  144. if (res1 != boost::none)
  145. return res1;
  146. return CheckMapForContentRecord(meta, title_id, type);
  147. }
  148. std::vector<NcaID> RegisteredCache::AccumulateFiles() const {
  149. std::vector<NcaID> ids;
  150. for (const auto& d2_dir : dir->GetSubdirectories()) {
  151. if (FollowsNcaIdFormat(d2_dir->GetName())) {
  152. ids.push_back(Common::HexStringToArray<0x10, true>(d2_dir->GetName().substr(0, 0x20)));
  153. continue;
  154. }
  155. if (!FollowsTwoDigitDirFormat(d2_dir->GetName()))
  156. continue;
  157. for (const auto& nca_dir : d2_dir->GetSubdirectories()) {
  158. if (!FollowsNcaIdFormat(nca_dir->GetName()))
  159. continue;
  160. ids.push_back(Common::HexStringToArray<0x10, true>(nca_dir->GetName().substr(0, 0x20)));
  161. }
  162. for (const auto& nca_file : d2_dir->GetFiles()) {
  163. if (!FollowsNcaIdFormat(nca_file->GetName()))
  164. continue;
  165. ids.push_back(
  166. Common::HexStringToArray<0x10, true>(nca_file->GetName().substr(0, 0x20)));
  167. }
  168. }
  169. for (const auto& d2_file : dir->GetFiles()) {
  170. if (FollowsNcaIdFormat(d2_file->GetName()))
  171. ids.push_back(Common::HexStringToArray<0x10, true>(d2_file->GetName().substr(0, 0x20)));
  172. }
  173. return ids;
  174. }
  175. void RegisteredCache::ProcessFiles(const std::vector<NcaID>& ids) {
  176. for (const auto& id : ids) {
  177. const auto file = GetFileAtID(id);
  178. if (file == nullptr)
  179. continue;
  180. const auto nca = std::make_shared<NCA>(parser(file, id));
  181. if (nca->GetStatus() != Loader::ResultStatus::Success ||
  182. nca->GetType() != NCAContentType::Meta) {
  183. continue;
  184. }
  185. const auto section0 = nca->GetSubdirectories()[0];
  186. for (const auto& section0_file : section0->GetFiles()) {
  187. if (section0_file->GetExtension() != "cnmt")
  188. continue;
  189. meta.insert_or_assign(nca->GetTitleId(), CNMT(section0_file));
  190. meta_id.insert_or_assign(nca->GetTitleId(), id);
  191. break;
  192. }
  193. }
  194. }
  195. void RegisteredCache::AccumulateYuzuMeta() {
  196. const auto dir = this->dir->GetSubdirectory("yuzu_meta");
  197. if (dir == nullptr)
  198. return;
  199. for (const auto& file : dir->GetFiles()) {
  200. if (file->GetExtension() != "cnmt")
  201. continue;
  202. CNMT cnmt(file);
  203. yuzu_meta.insert_or_assign(cnmt.GetTitleID(), std::move(cnmt));
  204. }
  205. }
  206. void RegisteredCache::Refresh() {
  207. if (dir == nullptr)
  208. return;
  209. const auto ids = AccumulateFiles();
  210. ProcessFiles(ids);
  211. AccumulateYuzuMeta();
  212. }
  213. RegisteredCache::RegisteredCache(VirtualDir dir_, RegisteredCacheParsingFunction parsing_function)
  214. : dir(std::move(dir_)), parser(std::move(parsing_function)) {
  215. Refresh();
  216. }
  217. RegisteredCache::~RegisteredCache() = default;
  218. bool RegisteredCache::HasEntry(u64 title_id, ContentRecordType type) const {
  219. return GetEntryRaw(title_id, type) != nullptr;
  220. }
  221. bool RegisteredCache::HasEntry(RegisteredCacheEntry entry) const {
  222. return GetEntryRaw(entry) != nullptr;
  223. }
  224. VirtualFile RegisteredCache::GetEntryUnparsed(u64 title_id, ContentRecordType type) const {
  225. const auto id = GetNcaIDFromMetadata(title_id, type);
  226. if (id == boost::none)
  227. return nullptr;
  228. return GetFileAtID(id.get());
  229. }
  230. VirtualFile RegisteredCache::GetEntryUnparsed(RegisteredCacheEntry entry) const {
  231. return GetEntryUnparsed(entry.title_id, entry.type);
  232. }
  233. VirtualFile RegisteredCache::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  234. const auto id = GetNcaIDFromMetadata(title_id, type);
  235. if (id == boost::none)
  236. return nullptr;
  237. return parser(GetFileAtID(id.get()), id.get());
  238. }
  239. VirtualFile RegisteredCache::GetEntryRaw(RegisteredCacheEntry entry) const {
  240. return GetEntryRaw(entry.title_id, entry.type);
  241. }
  242. std::shared_ptr<NCA> RegisteredCache::GetEntry(u64 title_id, ContentRecordType type) const {
  243. const auto raw = GetEntryRaw(title_id, type);
  244. if (raw == nullptr)
  245. return nullptr;
  246. return std::make_shared<NCA>(raw);
  247. }
  248. std::shared_ptr<NCA> RegisteredCache::GetEntry(RegisteredCacheEntry entry) const {
  249. return GetEntry(entry.title_id, entry.type);
  250. }
  251. template <typename T>
  252. void RegisteredCache::IterateAllMetadata(
  253. std::vector<T>& out, std::function<T(const CNMT&, const ContentRecord&)> proc,
  254. std::function<bool(const CNMT&, const ContentRecord&)> filter) const {
  255. for (const auto& kv : meta) {
  256. const auto& cnmt = kv.second;
  257. if (filter(cnmt, EMPTY_META_CONTENT_RECORD))
  258. out.push_back(proc(cnmt, EMPTY_META_CONTENT_RECORD));
  259. for (const auto& rec : cnmt.GetContentRecords()) {
  260. if (GetFileAtID(rec.nca_id) != nullptr && filter(cnmt, rec)) {
  261. out.push_back(proc(cnmt, rec));
  262. }
  263. }
  264. }
  265. for (const auto& kv : yuzu_meta) {
  266. const auto& cnmt = kv.second;
  267. for (const auto& rec : cnmt.GetContentRecords()) {
  268. if (GetFileAtID(rec.nca_id) != nullptr && filter(cnmt, rec)) {
  269. out.push_back(proc(cnmt, rec));
  270. }
  271. }
  272. }
  273. }
  274. std::vector<RegisteredCacheEntry> RegisteredCache::ListEntries() const {
  275. std::vector<RegisteredCacheEntry> out;
  276. IterateAllMetadata<RegisteredCacheEntry>(
  277. out,
  278. [](const CNMT& c, const ContentRecord& r) {
  279. return RegisteredCacheEntry{c.GetTitleID(), r.type};
  280. },
  281. [](const CNMT& c, const ContentRecord& r) { return true; });
  282. return out;
  283. }
  284. std::vector<RegisteredCacheEntry> RegisteredCache::ListEntriesFilter(
  285. boost::optional<TitleType> title_type, boost::optional<ContentRecordType> record_type,
  286. boost::optional<u64> title_id) const {
  287. std::vector<RegisteredCacheEntry> out;
  288. IterateAllMetadata<RegisteredCacheEntry>(
  289. out,
  290. [](const CNMT& c, const ContentRecord& r) {
  291. return RegisteredCacheEntry{c.GetTitleID(), r.type};
  292. },
  293. [&title_type, &record_type, &title_id](const CNMT& c, const ContentRecord& r) {
  294. if (title_type != boost::none && title_type.get() != c.GetType())
  295. return false;
  296. if (record_type != boost::none && record_type.get() != r.type)
  297. return false;
  298. if (title_id != boost::none && title_id.get() != c.GetTitleID())
  299. return false;
  300. return true;
  301. });
  302. return out;
  303. }
  304. static std::shared_ptr<NCA> GetNCAFromXCIForID(std::shared_ptr<XCI> xci, const NcaID& id) {
  305. const auto filename = fmt::format("{}.nca", Common::HexArrayToString(id, false));
  306. const auto iter =
  307. std::find_if(xci->GetNCAs().begin(), xci->GetNCAs().end(),
  308. [&filename](std::shared_ptr<NCA> nca) { return nca->GetName() == filename; });
  309. return iter == xci->GetNCAs().end() ? nullptr : *iter;
  310. }
  311. InstallResult RegisteredCache::InstallEntry(std::shared_ptr<XCI> xci, bool overwrite_if_exists,
  312. const VfsCopyFunction& copy) {
  313. const auto& ncas = xci->GetNCAs();
  314. const auto& meta_iter = std::find_if(ncas.begin(), ncas.end(), [](std::shared_ptr<NCA> nca) {
  315. return nca->GetType() == NCAContentType::Meta;
  316. });
  317. if (meta_iter == ncas.end()) {
  318. LOG_ERROR(Loader, "The XCI you are attempting to install does not have a metadata NCA and "
  319. "is therefore malformed. Double check your encryption keys.");
  320. return InstallResult::ErrorMetaFailed;
  321. }
  322. // Install Metadata File
  323. const auto meta_id_raw = (*meta_iter)->GetName().substr(0, 32);
  324. const auto meta_id = Common::HexStringToArray<16>(meta_id_raw);
  325. const auto res = RawInstallNCA(*meta_iter, copy, overwrite_if_exists, meta_id);
  326. if (res != InstallResult::Success)
  327. return res;
  328. // Install all the other NCAs
  329. const auto section0 = (*meta_iter)->GetSubdirectories()[0];
  330. const auto cnmt_file = section0->GetFiles()[0];
  331. const CNMT cnmt(cnmt_file);
  332. for (const auto& record : cnmt.GetContentRecords()) {
  333. const auto nca = GetNCAFromXCIForID(xci, record.nca_id);
  334. if (nca == nullptr)
  335. return InstallResult::ErrorCopyFailed;
  336. const auto res2 = RawInstallNCA(nca, copy, overwrite_if_exists, record.nca_id);
  337. if (res2 != InstallResult::Success)
  338. return res2;
  339. }
  340. Refresh();
  341. return InstallResult::Success;
  342. }
  343. InstallResult RegisteredCache::InstallEntry(std::shared_ptr<NCA> nca, TitleType type,
  344. bool overwrite_if_exists, const VfsCopyFunction& copy) {
  345. CNMTHeader header{
  346. nca->GetTitleId(), ///< Title ID
  347. 0, ///< Ignore/Default title version
  348. type, ///< Type
  349. {}, ///< Padding
  350. 0x10, ///< Default table offset
  351. 1, ///< 1 Content Entry
  352. 0, ///< No Meta Entries
  353. {}, ///< Padding
  354. };
  355. OptionalHeader opt_header{0, 0};
  356. ContentRecord c_rec{{}, {}, {}, GetCRTypeFromNCAType(nca->GetType()), {}};
  357. const auto& data = nca->GetBaseFile()->ReadBytes(0x100000);
  358. mbedtls_sha256(data.data(), data.size(), c_rec.hash.data(), 0);
  359. memcpy(&c_rec.nca_id, &c_rec.hash, 16);
  360. const CNMT new_cnmt(header, opt_header, {c_rec}, {});
  361. if (!RawInstallYuzuMeta(new_cnmt))
  362. return InstallResult::ErrorMetaFailed;
  363. return RawInstallNCA(nca, copy, overwrite_if_exists, c_rec.nca_id);
  364. }
  365. InstallResult RegisteredCache::RawInstallNCA(std::shared_ptr<NCA> nca, const VfsCopyFunction& copy,
  366. bool overwrite_if_exists,
  367. boost::optional<NcaID> override_id) {
  368. const auto in = nca->GetBaseFile();
  369. Core::Crypto::SHA256Hash hash{};
  370. // Calculate NcaID
  371. // NOTE: Because computing the SHA256 of an entire NCA is quite expensive (especially if the
  372. // game is massive), we're going to cheat and only hash the first MB of the NCA.
  373. // Also, for XCIs the NcaID matters, so if the override id isn't none, use that.
  374. NcaID id{};
  375. if (override_id == boost::none) {
  376. const auto& data = in->ReadBytes(0x100000);
  377. mbedtls_sha256(data.data(), data.size(), hash.data(), 0);
  378. memcpy(id.data(), hash.data(), 16);
  379. } else {
  380. id = override_id.get();
  381. }
  382. std::string path = GetRelativePathFromNcaID(id, false, true);
  383. if (GetFileAtID(id) != nullptr && !overwrite_if_exists) {
  384. LOG_WARNING(Loader, "Attempting to overwrite existing NCA. Skipping...");
  385. return InstallResult::ErrorAlreadyExists;
  386. }
  387. if (GetFileAtID(id) != nullptr) {
  388. LOG_WARNING(Loader, "Overwriting existing NCA...");
  389. VirtualDir c_dir;
  390. { c_dir = dir->GetFileRelative(path)->GetContainingDirectory(); }
  391. c_dir->DeleteFile(FileUtil::GetFilename(path));
  392. }
  393. auto out = dir->CreateFileRelative(path);
  394. if (out == nullptr)
  395. return InstallResult::ErrorCopyFailed;
  396. return copy(in, out) ? InstallResult::Success : InstallResult::ErrorCopyFailed;
  397. }
  398. bool RegisteredCache::RawInstallYuzuMeta(const CNMT& cnmt) {
  399. // Reasoning behind this method can be found in the comment for InstallEntry, NCA overload.
  400. const auto dir = this->dir->CreateDirectoryRelative("yuzu_meta");
  401. const auto filename = GetCNMTName(cnmt.GetType(), cnmt.GetTitleID());
  402. if (dir->GetFile(filename) == nullptr) {
  403. auto out = dir->CreateFile(filename);
  404. const auto buffer = cnmt.Serialize();
  405. out->Resize(buffer.size());
  406. out->WriteBytes(buffer);
  407. } else {
  408. auto out = dir->GetFile(filename);
  409. CNMT old_cnmt(out);
  410. // Returns true on change
  411. if (old_cnmt.UnionRecords(cnmt)) {
  412. out->Resize(0);
  413. const auto buffer = old_cnmt.Serialize();
  414. out->Resize(buffer.size());
  415. out->WriteBytes(buffer);
  416. }
  417. }
  418. Refresh();
  419. return std::find_if(yuzu_meta.begin(), yuzu_meta.end(),
  420. [&cnmt](const std::pair<u64, CNMT>& kv) {
  421. return kv.second.GetType() == cnmt.GetType() &&
  422. kv.second.GetTitleID() == cnmt.GetTitleID();
  423. }) != yuzu_meta.end();
  424. }
  425. } // namespace FileSys