registered_cache.cpp 17 KB

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