registered_cache.cpp 15 KB

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