registered_cache.cpp 18 KB

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