summaryrefslogtreecommitdiff
path: root/Source/Core/DiscIO/NFSBlob.cpp
blob: 6e13c709551abc31c07947df69d52fb3cbba3e92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// Copyright 2022 Dolphin Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "DiscIO/NFSBlob.h"

#include <algorithm>
#include <array>
#include <cstring>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>

#include <fmt/format.h>

#include "Common/Align.h"
#include "Common/BitUtils.h"
#include "Common/CommonTypes.h"
#include "Common/Crypto/AES.h"
#include "Common/Logging/Log.h"
#include "Common/StringUtil.h"
#include "Common/Swap.h"

namespace DiscIO
{
bool NFSFileReader::ReadKey(const std::string& path, const std::string& directory, Key* key_out)
{
  const std::string_view directory_without_trailing_slash =
      std::string_view(directory).substr(0, directory.size() - 1);

  std::string parent, parent_name, parent_extension;
  SplitPath(directory_without_trailing_slash, &parent, &parent_name, &parent_extension);

  if (parent_name + parent_extension != "content")
  {
    ERROR_LOG_FMT(DISCIO, "hif_000000.nfs is not in a directory named 'content': {}", path);
    return false;
  }

  const std::string key_path = parent + "code/htk.bin";
  File::DirectIOFile key_file(key_path, File::AccessMode::Read);
  if (!key_file.Read(*key_out))
  {
    ERROR_LOG_FMT(DISCIO, "Failed to read from {}", key_path);
    return false;
  }

  return true;
}

std::vector<NFSLBARange> NFSFileReader::GetLBARanges(const NFSHeader& header)
{
  const size_t lba_range_count =
      std::min<size_t>(Common::swap32(header.lba_range_count), header.lba_ranges.size());

  std::vector<NFSLBARange> lba_ranges;
  lba_ranges.reserve(lba_range_count);

  for (size_t i = 0; i < lba_range_count; ++i)
  {
    const NFSLBARange& unswapped_lba_range = header.lba_ranges[i];
    lba_ranges.push_back(NFSLBARange{Common::swap32(unswapped_lba_range.start_block),
                                     Common::swap32(unswapped_lba_range.num_blocks)});
  }

  return lba_ranges;
}

std::vector<File::DirectIOFile> NFSFileReader::OpenFiles(const std::string& directory,
                                                         File::DirectIOFile first_file,
                                                         u64 expected_raw_size, u64* raw_size_out)
{
  const u64 file_count = Common::AlignUp(expected_raw_size, MAX_FILE_SIZE) / MAX_FILE_SIZE;

  std::vector<File::DirectIOFile> files;
  files.reserve(file_count);

  *raw_size_out = first_file.GetSize();
  files.emplace_back(std::move(first_file));

  for (u64 i = 1; i < file_count; ++i)
  {
    const std::string child_path = fmt::format("{}hif_{:06}.nfs", directory, i);
    File::DirectIOFile child(child_path, File::AccessMode::Read);
    if (!child.IsOpen())
    {
      ERROR_LOG_FMT(DISCIO, "Failed to open {}", child_path);
      return {};
    }

    *raw_size_out += child.GetSize();
    files.emplace_back(std::move(child));
  }

  if (*raw_size_out < expected_raw_size)
  {
    ERROR_LOG_FMT(
        DISCIO,
        "Expected sum of NFS file sizes for {} to be at least {} bytes, but it was {} bytes",
        directory, expected_raw_size, *raw_size_out);
    return {};
  }

  return files;
}

u64 NFSFileReader::CalculateExpectedRawSize(std::span<const NFSLBARange> lba_ranges)
{
  u64 total_blocks = 0;
  for (const NFSLBARange& range : lba_ranges)
    total_blocks += range.num_blocks;

  return sizeof(NFSHeader) + total_blocks * BLOCK_SIZE;
}

u64 NFSFileReader::CalculateExpectedDataSize(std::span<const NFSLBARange> lba_ranges)
{
  u32 greatest_block_index = 0;
  for (const NFSLBARange& range : lba_ranges)
    greatest_block_index = std::max(greatest_block_index, range.start_block + range.num_blocks);

  return u64(greatest_block_index) * BLOCK_SIZE;
}

std::unique_ptr<NFSFileReader> NFSFileReader::Create(File::DirectIOFile first_file,
                                                     const std::string& path)
{
  std::string directory, filename, extension;
  SplitPath(path, &directory, &filename, &extension);
  if (filename + extension != "hif_000000.nfs")
    return nullptr;

  std::array<u8, 16> key;
  if (!ReadKey(path, directory, &key))
    return nullptr;

  NFSHeader header;
  if (!first_file.OffsetRead(0, Common::AsWritableU8Span(header)) || header.magic != NFS_MAGIC)
    return nullptr;

  std::vector<NFSLBARange> lba_ranges = GetLBARanges(header);

  const u64 expected_raw_size = CalculateExpectedRawSize(lba_ranges);

  u64 raw_size;
  std::vector<File::DirectIOFile> files =
      OpenFiles(directory, std::move(first_file), expected_raw_size, &raw_size);

  if (files.empty())
    return nullptr;

  return std::unique_ptr<NFSFileReader>(
      new NFSFileReader(std::move(lba_ranges), std::move(files), key, raw_size));
}

NFSFileReader::NFSFileReader(std::vector<NFSLBARange> lba_ranges,
                             std::vector<File::DirectIOFile> files, Key key, u64 raw_size)
    : m_lba_ranges(std::move(lba_ranges)), m_files(std::move(files)),
      m_aes_context(Common::AES::CreateContextDecrypt(key.data())), m_raw_size(raw_size), m_key(key)
{
  m_data_size = CalculateExpectedDataSize(m_lba_ranges);
}

std::unique_ptr<BlobReader> NFSFileReader::CopyReader() const
{
  return std::unique_ptr<BlobReader>{new NFSFileReader(m_lba_ranges, m_files, m_key, m_raw_size)};
}

u64 NFSFileReader::GetDataSize() const
{
  return m_data_size;
}

u64 NFSFileReader::GetRawSize() const
{
  return m_raw_size;
}

u64 NFSFileReader::ToPhysicalBlockIndex(u64 logical_block_index) const
{
  u64 physical_blocks_so_far = 0;

  for (const NFSLBARange& range : m_lba_ranges)
  {
    if (logical_block_index >= range.start_block &&
        logical_block_index < range.start_block + range.num_blocks)
    {
      return physical_blocks_so_far + (logical_block_index - range.start_block);
    }

    physical_blocks_so_far += range.num_blocks;
  }

  return std::numeric_limits<u64>::max();
}

bool NFSFileReader::ReadEncryptedBlock(u64 physical_block_index)
{
  constexpr u64 BLOCKS_PER_FILE = MAX_FILE_SIZE / BLOCK_SIZE;

  const u64 file_index = physical_block_index / BLOCKS_PER_FILE;
  const u64 block_in_file = physical_block_index % BLOCKS_PER_FILE;
  const u64 offset_in_file = sizeof(NFSHeader) + block_in_file * BLOCK_SIZE;

  if (block_in_file == BLOCKS_PER_FILE - 1)
  {
    // Special case. Because of the 0x200 byte header at the very beginning,
    // the last block of each file has its last 0x200 bytes stored in the next file.

    constexpr size_t PART_1_SIZE = BLOCK_SIZE - sizeof(NFSHeader);
    constexpr size_t PART_2_SIZE = sizeof(NFSHeader);

    File::DirectIOFile& file_1 = m_files[file_index];
    File::DirectIOFile& file_2 = m_files[file_index + 1];

    if (!file_1.OffsetRead(offset_in_file, m_current_block_encrypted.data(), PART_1_SIZE))
      return false;

    if (!file_2.OffsetRead(0, m_current_block_encrypted.data() + PART_1_SIZE, PART_2_SIZE))
      return false;
  }
  else
  {
    // Normal case. The read is offset by 0x200 bytes, but it's all within one file.

    File::DirectIOFile& file = m_files[file_index];

    if (!file.OffsetRead(offset_in_file, m_current_block_encrypted.data(), BLOCK_SIZE))
    {
      return false;
    }
  }

  return true;
}

void NFSFileReader::DecryptBlock(u64 logical_block_index)
{
  std::array<u8, 16> iv{};
  const u64 swapped_block_index = Common::swap64(logical_block_index);
  std::memcpy(iv.data() + iv.size() - sizeof(swapped_block_index), &swapped_block_index,
              sizeof(swapped_block_index));

  m_aes_context->Crypt(iv.data(), m_current_block_encrypted.data(),
                       m_current_block_decrypted.data(), BLOCK_SIZE);
}

bool NFSFileReader::ReadAndDecryptBlock(u64 logical_block_index)
{
  const u64 physical_block_index = ToPhysicalBlockIndex(logical_block_index);

  if (physical_block_index == std::numeric_limits<u64>::max())
  {
    // The block isn't physically present. Treat its contents as all zeroes.
    m_current_block_decrypted.fill(0);
  }
  else
  {
    if (!ReadEncryptedBlock(physical_block_index))
      return false;

    DecryptBlock(logical_block_index);
  }

  // Small hack: Set 0x61 of the header to 1 so that VolumeWii realizes that the disc is unencrypted
  if (logical_block_index == 0)
    m_current_block_decrypted[0x61] = 1;

  return true;
}

bool NFSFileReader::Read(u64 offset, u64 nbytes, u8* out_ptr)
{
  while (nbytes != 0)
  {
    const u64 logical_block_index = offset / BLOCK_SIZE;
    const u64 offset_in_block = offset % BLOCK_SIZE;

    if (logical_block_index != m_current_logical_block_index)
    {
      if (!ReadAndDecryptBlock(logical_block_index))
        return false;

      m_current_logical_block_index = logical_block_index;
    }

    const u64 bytes_to_copy = std::min(nbytes, BLOCK_SIZE - offset_in_block);
    std::memcpy(out_ptr, m_current_block_decrypted.data() + offset_in_block, bytes_to_copy);

    offset += bytes_to_copy;
    nbytes -= bytes_to_copy;
    out_ptr += bytes_to_copy;
  }

  return true;
}

}  // namespace DiscIO