NFSBlob.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. // Copyright 2022 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "DiscIO/NFSBlob.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <cstring>
  7. #include <memory>
  8. #include <string>
  9. #include <string_view>
  10. #include <utility>
  11. #include <vector>
  12. #include <fmt/format.h>
  13. #include "Common/Align.h"
  14. #include "Common/CommonTypes.h"
  15. #include "Common/Crypto/AES.h"
  16. #include "Common/IOFile.h"
  17. #include "Common/Logging/Log.h"
  18. #include "Common/StringUtil.h"
  19. #include "Common/Swap.h"
  20. namespace DiscIO
  21. {
  22. bool NFSFileReader::ReadKey(const std::string& path, const std::string& directory, Key* key_out)
  23. {
  24. const std::string_view directory_without_trailing_slash =
  25. std::string_view(directory).substr(0, directory.size() - 1);
  26. std::string parent, parent_name, parent_extension;
  27. SplitPath(directory_without_trailing_slash, &parent, &parent_name, &parent_extension);
  28. if (parent_name + parent_extension != "content")
  29. {
  30. ERROR_LOG_FMT(DISCIO, "hif_000000.nfs is not in a directory named 'content': {}", path);
  31. return false;
  32. }
  33. const std::string key_path = parent + "code/htk.bin";
  34. File::IOFile key_file(key_path, "rb");
  35. if (!key_file.ReadBytes(key_out->data(), key_out->size()))
  36. {
  37. ERROR_LOG_FMT(DISCIO, "Failed to read from {}", key_path);
  38. return false;
  39. }
  40. return true;
  41. }
  42. std::vector<NFSLBARange> NFSFileReader::GetLBARanges(const NFSHeader& header)
  43. {
  44. const size_t lba_range_count =
  45. std::min<size_t>(Common::swap32(header.lba_range_count), header.lba_ranges.size());
  46. std::vector<NFSLBARange> lba_ranges;
  47. lba_ranges.reserve(lba_range_count);
  48. for (size_t i = 0; i < lba_range_count; ++i)
  49. {
  50. const NFSLBARange& unswapped_lba_range = header.lba_ranges[i];
  51. lba_ranges.push_back(NFSLBARange{Common::swap32(unswapped_lba_range.start_block),
  52. Common::swap32(unswapped_lba_range.num_blocks)});
  53. }
  54. return lba_ranges;
  55. }
  56. std::vector<File::IOFile> NFSFileReader::OpenFiles(const std::string& directory,
  57. File::IOFile first_file, u64 expected_raw_size,
  58. u64* raw_size_out)
  59. {
  60. const u64 file_count = Common::AlignUp(expected_raw_size, MAX_FILE_SIZE) / MAX_FILE_SIZE;
  61. std::vector<File::IOFile> files;
  62. files.reserve(file_count);
  63. *raw_size_out = first_file.GetSize();
  64. files.emplace_back(std::move(first_file));
  65. for (u64 i = 1; i < file_count; ++i)
  66. {
  67. const std::string child_path = fmt::format("{}hif_{:06}.nfs", directory, i);
  68. File::IOFile child(child_path, "rb");
  69. if (!child)
  70. {
  71. ERROR_LOG_FMT(DISCIO, "Failed to open {}", child_path);
  72. return {};
  73. }
  74. *raw_size_out += child.GetSize();
  75. files.emplace_back(std::move(child));
  76. }
  77. if (*raw_size_out < expected_raw_size)
  78. {
  79. ERROR_LOG_FMT(
  80. DISCIO,
  81. "Expected sum of NFS file sizes for {} to be at least {} bytes, but it was {} bytes",
  82. directory, expected_raw_size, *raw_size_out);
  83. return {};
  84. }
  85. return files;
  86. }
  87. u64 NFSFileReader::CalculateExpectedRawSize(const std::vector<NFSLBARange>& lba_ranges)
  88. {
  89. u64 total_blocks = 0;
  90. for (const NFSLBARange& range : lba_ranges)
  91. total_blocks += range.num_blocks;
  92. return sizeof(NFSHeader) + total_blocks * BLOCK_SIZE;
  93. }
  94. u64 NFSFileReader::CalculateExpectedDataSize(const std::vector<NFSLBARange>& lba_ranges)
  95. {
  96. u32 greatest_block_index = 0;
  97. for (const NFSLBARange& range : lba_ranges)
  98. greatest_block_index = std::max(greatest_block_index, range.start_block + range.num_blocks);
  99. return u64(greatest_block_index) * BLOCK_SIZE;
  100. }
  101. std::unique_ptr<NFSFileReader> NFSFileReader::Create(File::IOFile first_file,
  102. const std::string& path)
  103. {
  104. std::string directory, filename, extension;
  105. SplitPath(path, &directory, &filename, &extension);
  106. if (filename + extension != "hif_000000.nfs")
  107. return nullptr;
  108. std::array<u8, 16> key;
  109. if (!ReadKey(path, directory, &key))
  110. return nullptr;
  111. NFSHeader header;
  112. if (!first_file.Seek(0, File::SeekOrigin::Begin) || !first_file.ReadArray(&header, 1) ||
  113. header.magic != NFS_MAGIC)
  114. {
  115. return nullptr;
  116. }
  117. std::vector<NFSLBARange> lba_ranges = GetLBARanges(header);
  118. const u64 expected_raw_size = CalculateExpectedRawSize(lba_ranges);
  119. u64 raw_size;
  120. std::vector<File::IOFile> files =
  121. OpenFiles(directory, std::move(first_file), expected_raw_size, &raw_size);
  122. if (files.empty())
  123. return nullptr;
  124. return std::unique_ptr<NFSFileReader>(
  125. new NFSFileReader(std::move(lba_ranges), std::move(files), key, raw_size));
  126. }
  127. NFSFileReader::NFSFileReader(std::vector<NFSLBARange> lba_ranges, std::vector<File::IOFile> files,
  128. Key key, u64 raw_size)
  129. : m_lba_ranges(std::move(lba_ranges)), m_files(std::move(files)),
  130. m_aes_context(Common::AES::CreateContextDecrypt(key.data())), m_raw_size(raw_size), m_key(key)
  131. {
  132. m_data_size = CalculateExpectedDataSize(m_lba_ranges);
  133. }
  134. std::unique_ptr<BlobReader> NFSFileReader::CopyReader() const
  135. {
  136. std::vector<File::IOFile> new_files{};
  137. for (const File::IOFile& file : m_files)
  138. new_files.push_back(file.Duplicate("rb"));
  139. return std::unique_ptr<NFSFileReader>(
  140. new NFSFileReader(m_lba_ranges, std::move(new_files), m_key, m_raw_size));
  141. }
  142. u64 NFSFileReader::GetDataSize() const
  143. {
  144. return m_data_size;
  145. }
  146. u64 NFSFileReader::GetRawSize() const
  147. {
  148. return m_raw_size;
  149. }
  150. u64 NFSFileReader::ToPhysicalBlockIndex(u64 logical_block_index)
  151. {
  152. u64 physical_blocks_so_far = 0;
  153. for (const NFSLBARange& range : m_lba_ranges)
  154. {
  155. if (logical_block_index >= range.start_block &&
  156. logical_block_index < range.start_block + range.num_blocks)
  157. {
  158. return physical_blocks_so_far + (logical_block_index - range.start_block);
  159. }
  160. physical_blocks_so_far += range.num_blocks;
  161. }
  162. return std::numeric_limits<u64>::max();
  163. }
  164. bool NFSFileReader::ReadEncryptedBlock(u64 physical_block_index)
  165. {
  166. constexpr u64 BLOCKS_PER_FILE = MAX_FILE_SIZE / BLOCK_SIZE;
  167. const u64 file_index = physical_block_index / BLOCKS_PER_FILE;
  168. const u64 block_in_file = physical_block_index % BLOCKS_PER_FILE;
  169. if (block_in_file == BLOCKS_PER_FILE - 1)
  170. {
  171. // Special case. Because of the 0x200 byte header at the very beginning,
  172. // the last block of each file has its last 0x200 bytes stored in the next file.
  173. constexpr size_t PART_1_SIZE = BLOCK_SIZE - sizeof(NFSHeader);
  174. constexpr size_t PART_2_SIZE = sizeof(NFSHeader);
  175. File::IOFile& file_1 = m_files[file_index];
  176. File::IOFile& file_2 = m_files[file_index + 1];
  177. if (!file_1.Seek(sizeof(NFSHeader) + block_in_file * BLOCK_SIZE, File::SeekOrigin::Begin) ||
  178. !file_1.ReadBytes(m_current_block_encrypted.data(), PART_1_SIZE))
  179. {
  180. file_1.ClearError();
  181. return false;
  182. }
  183. if (!file_2.Seek(0, File::SeekOrigin::Begin) ||
  184. !file_2.ReadBytes(m_current_block_encrypted.data() + PART_1_SIZE, PART_2_SIZE))
  185. {
  186. file_2.ClearError();
  187. return false;
  188. }
  189. }
  190. else
  191. {
  192. // Normal case. The read is offset by 0x200 bytes, but it's all within one file.
  193. File::IOFile& file = m_files[file_index];
  194. if (!file.Seek(sizeof(NFSHeader) + block_in_file * BLOCK_SIZE, File::SeekOrigin::Begin) ||
  195. !file.ReadBytes(m_current_block_encrypted.data(), BLOCK_SIZE))
  196. {
  197. file.ClearError();
  198. return false;
  199. }
  200. }
  201. return true;
  202. }
  203. void NFSFileReader::DecryptBlock(u64 logical_block_index)
  204. {
  205. std::array<u8, 16> iv{};
  206. const u64 swapped_block_index = Common::swap64(logical_block_index);
  207. std::memcpy(iv.data() + iv.size() - sizeof(swapped_block_index), &swapped_block_index,
  208. sizeof(swapped_block_index));
  209. m_aes_context->Crypt(iv.data(), m_current_block_encrypted.data(),
  210. m_current_block_decrypted.data(), BLOCK_SIZE);
  211. }
  212. bool NFSFileReader::ReadAndDecryptBlock(u64 logical_block_index)
  213. {
  214. const u64 physical_block_index = ToPhysicalBlockIndex(logical_block_index);
  215. if (physical_block_index == std::numeric_limits<u64>::max())
  216. {
  217. // The block isn't physically present. Treat its contents as all zeroes.
  218. m_current_block_decrypted.fill(0);
  219. }
  220. else
  221. {
  222. if (!ReadEncryptedBlock(physical_block_index))
  223. return false;
  224. DecryptBlock(logical_block_index);
  225. }
  226. // Small hack: Set 0x61 of the header to 1 so that VolumeWii realizes that the disc is unencrypted
  227. if (logical_block_index == 0)
  228. m_current_block_decrypted[0x61] = 1;
  229. return true;
  230. }
  231. bool NFSFileReader::Read(u64 offset, u64 nbytes, u8* out_ptr)
  232. {
  233. while (nbytes != 0)
  234. {
  235. const u64 logical_block_index = offset / BLOCK_SIZE;
  236. const u64 offset_in_block = offset % BLOCK_SIZE;
  237. if (logical_block_index != m_current_logical_block_index)
  238. {
  239. if (!ReadAndDecryptBlock(logical_block_index))
  240. return false;
  241. m_current_logical_block_index = logical_block_index;
  242. }
  243. const u64 bytes_to_copy = std::min(nbytes, BLOCK_SIZE - offset_in_block);
  244. std::memcpy(out_ptr, m_current_block_decrypted.data() + offset_in_block, bytes_to_copy);
  245. offset += bytes_to_copy;
  246. nbytes -= bytes_to_copy;
  247. out_ptr += bytes_to_copy;
  248. }
  249. return true;
  250. }
  251. } // namespace DiscIO