Debian Codegraph @

Source/Core/DiscIO/NFSBlob.cpp

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