registered_cache.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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/hex_util.h"
  8. #include "common/logging/log.h"
  9. #include "core/crypto/encryption_layer.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 static_cast<NCAContentType>(0x05): ///< Seems to be used on some system archives
  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& file : section0->GetFiles()) {
  187. if (file->GetExtension() != "cnmt")
  188. continue;
  189. meta.insert_or_assign(nca->GetTitleId(), CNMT(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. bool RegisteredCache::HasEntry(u64 title_id, ContentRecordType type) const {
  218. return GetEntryRaw(title_id, type) != nullptr;
  219. }
  220. bool RegisteredCache::HasEntry(RegisteredCacheEntry entry) const {
  221. return GetEntryRaw(entry) != nullptr;
  222. }
  223. VirtualFile RegisteredCache::GetEntryRaw(u64 title_id, ContentRecordType type) const {
  224. const auto id = GetNcaIDFromMetadata(title_id, type);
  225. if (id == boost::none)
  226. return nullptr;
  227. return parser(GetFileAtID(id.get()), id.get());
  228. }
  229. VirtualFile RegisteredCache::GetEntryRaw(RegisteredCacheEntry entry) const {
  230. return GetEntryRaw(entry.title_id, entry.type);
  231. }
  232. std::shared_ptr<NCA> RegisteredCache::GetEntry(u64 title_id, ContentRecordType type) const {
  233. const auto raw = GetEntryRaw(title_id, type);
  234. if (raw == nullptr)
  235. return nullptr;
  236. return std::make_shared<NCA>(raw);
  237. }
  238. std::shared_ptr<NCA> RegisteredCache::GetEntry(RegisteredCacheEntry entry) const {
  239. return GetEntry(entry.title_id, entry.type);
  240. }
  241. template <typename T>
  242. void RegisteredCache::IterateAllMetadata(
  243. std::vector<T>& out, std::function<T(const CNMT&, const ContentRecord&)> proc,
  244. std::function<bool(const CNMT&, const ContentRecord&)> filter) const {
  245. for (const auto& kv : meta) {
  246. const auto& cnmt = kv.second;
  247. if (filter(cnmt, EMPTY_META_CONTENT_RECORD))
  248. out.push_back(proc(cnmt, EMPTY_META_CONTENT_RECORD));
  249. for (const auto& rec : cnmt.GetContentRecords()) {
  250. if (GetFileAtID(rec.nca_id) != nullptr && filter(cnmt, rec)) {
  251. out.push_back(proc(cnmt, rec));
  252. }
  253. }
  254. }
  255. for (const auto& kv : yuzu_meta) {
  256. const auto& cnmt = kv.second;
  257. for (const auto& rec : cnmt.GetContentRecords()) {
  258. if (GetFileAtID(rec.nca_id) != nullptr && filter(cnmt, rec)) {
  259. out.push_back(proc(cnmt, rec));
  260. }
  261. }
  262. }
  263. }
  264. std::vector<RegisteredCacheEntry> RegisteredCache::ListEntries() const {
  265. std::vector<RegisteredCacheEntry> out;
  266. IterateAllMetadata<RegisteredCacheEntry>(
  267. out,
  268. [](const CNMT& c, const ContentRecord& r) {
  269. return RegisteredCacheEntry{c.GetTitleID(), r.type};
  270. },
  271. [](const CNMT& c, const ContentRecord& r) { return true; });
  272. return out;
  273. }
  274. std::vector<RegisteredCacheEntry> RegisteredCache::ListEntriesFilter(
  275. boost::optional<TitleType> title_type, boost::optional<ContentRecordType> record_type,
  276. boost::optional<u64> title_id) const {
  277. std::vector<RegisteredCacheEntry> out;
  278. IterateAllMetadata<RegisteredCacheEntry>(
  279. out,
  280. [](const CNMT& c, const ContentRecord& r) {
  281. return RegisteredCacheEntry{c.GetTitleID(), r.type};
  282. },
  283. [&title_type, &record_type, &title_id](const CNMT& c, const ContentRecord& r) {
  284. if (title_type != boost::none && title_type.get() != c.GetType())
  285. return false;
  286. if (record_type != boost::none && record_type.get() != r.type)
  287. return false;
  288. if (title_id != boost::none && title_id.get() != c.GetTitleID())
  289. return false;
  290. return true;
  291. });
  292. return out;
  293. }
  294. static std::shared_ptr<NCA> GetNCAFromXCIForID(std::shared_ptr<XCI> xci, const NcaID& id) {
  295. const auto filename = fmt::format("{}.nca", Common::HexArrayToString(id, false));
  296. const auto iter =
  297. std::find_if(xci->GetNCAs().begin(), xci->GetNCAs().end(),
  298. [&filename](std::shared_ptr<NCA> nca) { return nca->GetName() == filename; });
  299. return iter == xci->GetNCAs().end() ? nullptr : *iter;
  300. }
  301. InstallResult RegisteredCache::InstallEntry(std::shared_ptr<XCI> xci, bool overwrite_if_exists,
  302. const VfsCopyFunction& copy) {
  303. const auto& ncas = xci->GetNCAs();
  304. const auto& meta_iter = std::find_if(ncas.begin(), ncas.end(), [](std::shared_ptr<NCA> nca) {
  305. return nca->GetType() == NCAContentType::Meta;
  306. });
  307. if (meta_iter == ncas.end()) {
  308. LOG_ERROR(Loader, "The XCI you are attempting to install does not have a metadata NCA and "
  309. "is therefore malformed. Double check your encryption keys.");
  310. return InstallResult::ErrorMetaFailed;
  311. }
  312. // Install Metadata File
  313. const auto meta_id_raw = (*meta_iter)->GetName().substr(0, 32);
  314. const auto meta_id = Common::HexStringToArray<16>(meta_id_raw);
  315. const auto res = RawInstallNCA(*meta_iter, copy, overwrite_if_exists, meta_id);
  316. if (res != InstallResult::Success)
  317. return res;
  318. // Install all the other NCAs
  319. const auto section0 = (*meta_iter)->GetSubdirectories()[0];
  320. const auto cnmt_file = section0->GetFiles()[0];
  321. const CNMT cnmt(cnmt_file);
  322. for (const auto& record : cnmt.GetContentRecords()) {
  323. const auto nca = GetNCAFromXCIForID(xci, record.nca_id);
  324. if (nca == nullptr)
  325. return InstallResult::ErrorCopyFailed;
  326. const auto res2 = RawInstallNCA(nca, copy, overwrite_if_exists, record.nca_id);
  327. if (res2 != InstallResult::Success)
  328. return res2;
  329. }
  330. Refresh();
  331. return InstallResult::Success;
  332. }
  333. InstallResult RegisteredCache::InstallEntry(std::shared_ptr<NCA> nca, TitleType type,
  334. bool overwrite_if_exists, const VfsCopyFunction& copy) {
  335. CNMTHeader header{
  336. nca->GetTitleId(), ///< Title ID
  337. 0, ///< Ignore/Default title version
  338. type, ///< Type
  339. {}, ///< Padding
  340. 0x10, ///< Default table offset
  341. 1, ///< 1 Content Entry
  342. 0, ///< No Meta Entries
  343. {}, ///< Padding
  344. };
  345. OptionalHeader opt_header{0, 0};
  346. ContentRecord c_rec{{}, {}, {}, GetCRTypeFromNCAType(nca->GetType()), {}};
  347. const auto& data = nca->GetBaseFile()->ReadBytes(0x100000);
  348. mbedtls_sha256(data.data(), data.size(), c_rec.hash.data(), 0);
  349. memcpy(&c_rec.nca_id, &c_rec.hash, 16);
  350. const CNMT new_cnmt(header, opt_header, {c_rec}, {});
  351. if (!RawInstallYuzuMeta(new_cnmt))
  352. return InstallResult::ErrorMetaFailed;
  353. return RawInstallNCA(nca, copy, overwrite_if_exists, c_rec.nca_id);
  354. }
  355. InstallResult RegisteredCache::RawInstallNCA(std::shared_ptr<NCA> nca, const VfsCopyFunction& copy,
  356. bool overwrite_if_exists,
  357. boost::optional<NcaID> override_id) {
  358. const auto in = nca->GetBaseFile();
  359. Core::Crypto::SHA256Hash hash{};
  360. // Calculate NcaID
  361. // NOTE: Because computing the SHA256 of an entire NCA is quite expensive (especially if the
  362. // game is massive), we're going to cheat and only hash the first MB of the NCA.
  363. // Also, for XCIs the NcaID matters, so if the override id isn't none, use that.
  364. NcaID id{};
  365. if (override_id == boost::none) {
  366. const auto& data = in->ReadBytes(0x100000);
  367. mbedtls_sha256(data.data(), data.size(), hash.data(), 0);
  368. memcpy(id.data(), hash.data(), 16);
  369. } else {
  370. id = override_id.get();
  371. }
  372. std::string path = GetRelativePathFromNcaID(id, false, true);
  373. if (GetFileAtID(id) != nullptr && !overwrite_if_exists) {
  374. LOG_WARNING(Loader, "Attempting to overwrite existing NCA. Skipping...");
  375. return InstallResult::ErrorAlreadyExists;
  376. }
  377. if (GetFileAtID(id) != nullptr) {
  378. LOG_WARNING(Loader, "Overwriting existing NCA...");
  379. VirtualDir c_dir;
  380. { c_dir = dir->GetFileRelative(path)->GetContainingDirectory(); }
  381. c_dir->DeleteFile(FileUtil::GetFilename(path));
  382. }
  383. auto out = dir->CreateFileRelative(path);
  384. if (out == nullptr)
  385. return InstallResult::ErrorCopyFailed;
  386. return copy(in, out) ? InstallResult::Success : InstallResult::ErrorCopyFailed;
  387. }
  388. bool RegisteredCache::RawInstallYuzuMeta(const CNMT& cnmt) {
  389. // Reasoning behind this method can be found in the comment for InstallEntry, NCA overload.
  390. const auto dir = this->dir->CreateDirectoryRelative("yuzu_meta");
  391. const auto filename = GetCNMTName(cnmt.GetType(), cnmt.GetTitleID());
  392. if (dir->GetFile(filename) == nullptr) {
  393. auto out = dir->CreateFile(filename);
  394. const auto buffer = cnmt.Serialize();
  395. out->Resize(buffer.size());
  396. out->WriteBytes(buffer);
  397. } else {
  398. auto out = dir->GetFile(filename);
  399. CNMT old_cnmt(out);
  400. // Returns true on change
  401. if (old_cnmt.UnionRecords(cnmt)) {
  402. out->Resize(0);
  403. const auto buffer = old_cnmt.Serialize();
  404. out->Resize(buffer.size());
  405. out->WriteBytes(buffer);
  406. }
  407. }
  408. Refresh();
  409. return std::find_if(yuzu_meta.begin(), yuzu_meta.end(),
  410. [&cnmt](const std::pair<u64, CNMT>& kv) {
  411. return kv.second.GetType() == cnmt.GetType() &&
  412. kv.second.GetTitleID() == cnmt.GetTitleID();
  413. }) != yuzu_meta.end();
  414. }
  415. } // namespace FileSys