mirror of
https://github.com/patchzyy/wiicompiled
synced 2026-09-11 01:23:15 -04:00
Merge branch 'patchzyy:main' into main
This commit is contained in:
@@ -1,38 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include "runtime_config.h"
|
||||
#include "nand_path.h"
|
||||
#include "nand_settings.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cctype>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <optional>
|
||||
#include <random>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
|
||||
namespace RuntimeConsoleIdentity {
|
||||
|
||||
struct Identity {
|
||||
std::string serial;
|
||||
std::string productCode;
|
||||
std::string area;
|
||||
std::string gameRegion;
|
||||
std::array<uint8_t, 6> mac;
|
||||
};
|
||||
|
||||
inline bool IsValidSerial(const std::string& serial) {
|
||||
return serial.size() == 9 &&
|
||||
serial != "000000000" &&
|
||||
std::all_of(serial.begin(), serial.end(),
|
||||
[](unsigned char value) { return std::isdigit(value) != 0; });
|
||||
}
|
||||
|
||||
inline Identity FromSerial(std::string serial) {
|
||||
// Keep Nintendo's Wii OUI. The suffix is derived from the persisted serial
|
||||
// Keep Nintendo's Wii OUI. The suffix is derived from the NAND serial
|
||||
// so every API exposes one coherent, stable virtual-console identity.
|
||||
uint32_t hash = 2166136261u;
|
||||
for (const unsigned char value : serial) {
|
||||
@@ -46,6 +36,7 @@ inline Identity FromSerial(std::string serial) {
|
||||
|
||||
return {
|
||||
std::move(serial),
|
||||
{}, {}, {},
|
||||
{
|
||||
0x00,
|
||||
0x09,
|
||||
@@ -57,83 +48,23 @@ inline Identity FromSerial(std::string serial) {
|
||||
};
|
||||
}
|
||||
|
||||
inline std::optional<std::string> ReadSerial(const std::filesystem::path& path) {
|
||||
std::ifstream input(path);
|
||||
std::string line;
|
||||
if (!input || !std::getline(input, line)) {
|
||||
return std::nullopt;
|
||||
inline Identity LoadFromNand() {
|
||||
const auto root = RuntimeNandPath::DiscoverNandRootPath();
|
||||
const auto settings = RuntimeNandSettings::Read(root);
|
||||
if (!settings || !RuntimeNandSettings::HasIdentity(*settings)) {
|
||||
RuntimeNandPath::FailNandRoot(
|
||||
"NAND setting.txt is missing or has invalid console identity fields (SERNO, CODE, AREA, GAME)",
|
||||
root / "title/00000001/00000002/data/setting.txt");
|
||||
}
|
||||
constexpr std::string_view prefix = "serial=";
|
||||
if (line.rfind(prefix, 0) != 0) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::string serial = line.substr(prefix.size());
|
||||
if (!IsValidSerial(serial)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return serial;
|
||||
}
|
||||
|
||||
inline bool WriteSerial(const std::filesystem::path& path, const std::string& serial) {
|
||||
std::error_code ec;
|
||||
std::filesystem::create_directories(path.parent_path(), ec);
|
||||
if (ec) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::filesystem::path temporary = path;
|
||||
temporary += ".tmp";
|
||||
{
|
||||
std::ofstream output(temporary, std::ios::trunc);
|
||||
if (!output) {
|
||||
return false;
|
||||
}
|
||||
output << "serial=" << serial << '\n';
|
||||
output.close();
|
||||
if (!output) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::filesystem::rename(temporary, path, ec);
|
||||
if (!ec) {
|
||||
return true;
|
||||
}
|
||||
std::filesystem::remove(temporary, ec);
|
||||
return false;
|
||||
}
|
||||
|
||||
inline std::string GenerateSerial() {
|
||||
std::random_device entropy;
|
||||
std::seed_seq seed{
|
||||
entropy(),
|
||||
entropy(),
|
||||
entropy(),
|
||||
entropy(),
|
||||
};
|
||||
std::mt19937 generator(seed);
|
||||
std::uniform_int_distribution<uint32_t> distribution(100000000u, 999999999u);
|
||||
return std::to_string(distribution(generator));
|
||||
}
|
||||
|
||||
inline Identity LoadOrCreate(const std::filesystem::path& path) {
|
||||
if (const auto serial = ReadSerial(path)) {
|
||||
return FromSerial(*serial);
|
||||
}
|
||||
|
||||
const std::string generated = GenerateSerial();
|
||||
if (WriteSerial(path, generated)) {
|
||||
return FromSerial(generated);
|
||||
}
|
||||
|
||||
// Remain operational in a read-only environment. This fallback matches
|
||||
// Dolphin's deterministic serial while keeping the same valid identity shape.
|
||||
return FromSerial("123456789");
|
||||
Identity identity = FromSerial(settings->at("SERNO"));
|
||||
identity.productCode = settings->at("CODE");
|
||||
identity.area = settings->at("AREA");
|
||||
identity.gameRegion = settings->at("GAME");
|
||||
return identity;
|
||||
}
|
||||
|
||||
inline const Identity& Current() {
|
||||
static const Identity identity =
|
||||
LoadOrCreate(RuntimeConfigFile::ApplicationDataDirectory() / "ConsoleIdentity.txt");
|
||||
static const Identity identity = LoadFromNand();
|
||||
return identity;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "runtime_config.h"
|
||||
#include "nand_settings.h"
|
||||
#include "runtime_log.h"
|
||||
#include "system_bridge.h"
|
||||
|
||||
@@ -163,7 +164,7 @@ inline std::filesystem::path CreateManagedNandRoot() {
|
||||
return root;
|
||||
}
|
||||
|
||||
inline std::filesystem::path DiscoverNandRootPath() {
|
||||
inline std::filesystem::path ResolveNandRootPath() {
|
||||
const std::string configPath = RuntimeConfigFile::NandRoot();
|
||||
if (!configPath.empty()) {
|
||||
const auto path = ResolveConfiguredPath(configPath);
|
||||
@@ -179,4 +180,16 @@ inline std::filesystem::path DiscoverNandRootPath() {
|
||||
return CreateManagedNandRoot();
|
||||
}
|
||||
|
||||
inline std::filesystem::path DiscoverNandRootPath() {
|
||||
static const auto root = [] {
|
||||
const auto resolved = ResolveNandRootPath();
|
||||
std::string error;
|
||||
if (!RuntimeNandSettings::Ensure(resolved, error)) {
|
||||
FailNandRoot(error.c_str(), RuntimeNandSettings::FilePath(resolved));
|
||||
}
|
||||
return resolved;
|
||||
}();
|
||||
return root;
|
||||
}
|
||||
|
||||
} // namespace RuntimeNandPath
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
#pragma once
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <istream>
|
||||
|
||||
namespace RuntimeNandSave {
|
||||
|
||||
enum class Contents { Missing, Blank, Nonzero, Error };
|
||||
enum class ReadAction { Proceed, Missing, Error, RecoveryNeeded };
|
||||
|
||||
// A failed read is not evidence that a save is blank. Check badbit before EOF:
|
||||
// an I/O failure may set both, whereas a successful short final read sets EOF.
|
||||
inline Contents InspectStream(std::istream& input) {
|
||||
if (!input) return Contents::Error;
|
||||
char block[4096];
|
||||
for (;;) {
|
||||
input.read(block, sizeof(block));
|
||||
if (input.bad() || (input.fail() && !input.eof())) return Contents::Error;
|
||||
for (std::streamsize i = 0; i < input.gcount(); ++i) {
|
||||
if (block[i] != 0) return Contents::Nonzero;
|
||||
}
|
||||
if (input.eof()) return Contents::Blank;
|
||||
}
|
||||
}
|
||||
|
||||
inline Contents InspectFile(const std::filesystem::path& path) {
|
||||
std::error_code ec;
|
||||
const auto status = std::filesystem::symlink_status(path, ec);
|
||||
if (ec && ec != std::errc::no_such_file_or_directory) return Contents::Error;
|
||||
if (!std::filesystem::exists(status)) return Contents::Missing;
|
||||
if (!std::filesystem::is_regular_file(path, ec) || ec) return Contents::Error;
|
||||
std::ifstream input(path, std::ios::binary);
|
||||
return InspectStream(input);
|
||||
}
|
||||
|
||||
// Probe only read-only opens of the actual save and its exact write shadow.
|
||||
// No probe writes, removes, or repairs data, and backups are not save aliases.
|
||||
inline ReadAction CheckRead(const std::filesystem::path& path, int mode) {
|
||||
const auto name = path.filename();
|
||||
const bool isMain = name == "rksys.dat";
|
||||
if (mode != 1 || (!isMain && name != "rksys.dat.nandsafe.tmp")) return ReadAction::Proceed;
|
||||
const auto contents = InspectFile(path);
|
||||
if (contents == Contents::Error) return ReadAction::Error;
|
||||
if (contents == Contents::Nonzero) return ReadAction::Proceed;
|
||||
if (isMain) {
|
||||
auto shadow = path;
|
||||
shadow += ".nandsafe.tmp";
|
||||
const auto shadowContents = InspectFile(shadow);
|
||||
if (shadowContents == Contents::Error) return ReadAction::Error;
|
||||
// The next write normally discards an old shadow. Preserve a possible
|
||||
// recovery source when there is no usable original, without promoting
|
||||
// an uncommitted (and potentially incomplete) shadow to the real save.
|
||||
if (shadowContents == Contents::Nonzero) return ReadAction::RecoveryNeeded;
|
||||
}
|
||||
return contents == Contents::Blank ? ReadAction::Missing : ReadAction::Proceed;
|
||||
}
|
||||
|
||||
} // namespace RuntimeNandSave
|
||||
@@ -0,0 +1,220 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
namespace RuntimeNandSettings {
|
||||
|
||||
using Settings = std::map<std::string, std::string>;
|
||||
|
||||
inline std::filesystem::path FilePath(const std::filesystem::path& root) {
|
||||
return root / "title/00000001/00000002/data/setting.txt";
|
||||
}
|
||||
|
||||
// Wii setting.txt is a 256-byte buffer encrypted with a rotating XOR key.
|
||||
inline std::optional<Settings> Read(const std::filesystem::path& nandRoot) {
|
||||
std::ifstream input(FilePath(nandRoot), std::ios::binary);
|
||||
std::array<uint8_t, 256> bytes{};
|
||||
if (!input.read(reinterpret_cast<char*>(bytes.data()), bytes.size())) {
|
||||
return std::nullopt;
|
||||
}
|
||||
uint32_t key = 0x73B5DBFAu;
|
||||
std::string decoded;
|
||||
for (const uint8_t byte : bytes) {
|
||||
const char value = static_cast<char>(byte ^ static_cast<uint8_t>(key));
|
||||
key = (key << 1) | (key >> 31);
|
||||
if (value == '\0') {
|
||||
break;
|
||||
}
|
||||
if (value != '\r') {
|
||||
decoded += value;
|
||||
}
|
||||
}
|
||||
Settings settings;
|
||||
for (size_t start = 0; start < decoded.size();) {
|
||||
const size_t end = decoded.find('\n', start);
|
||||
const std::string line = decoded.substr(start, end - start);
|
||||
const size_t equals = line.find('=');
|
||||
if (equals != std::string::npos && equals != 0) {
|
||||
settings.emplace(line.substr(0, equals), line.substr(equals + 1));
|
||||
}
|
||||
if (end == std::string::npos) {
|
||||
break;
|
||||
}
|
||||
start = end + 1;
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
inline bool HasIdentity(const Settings& settings) {
|
||||
const auto serial = settings.find("SERNO");
|
||||
if (serial == settings.end() || serial->second.empty() || serial->second.size() > 9 ||
|
||||
serial->second.find_first_not_of("0123456789") != std::string::npos ||
|
||||
serial->second.find_first_not_of('0') == std::string::npos) {
|
||||
return false;
|
||||
}
|
||||
for (const auto& field : {std::pair{"CODE", 5u}, {"AREA", 3u}, {"GAME", 2u}}) {
|
||||
const auto value = settings.find(field.first);
|
||||
if (value == settings.end() || value->second.empty() ||
|
||||
value->second.size() > field.second) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Dolphin's normal (non-deterministic) first-boot algorithm. It is independent
|
||||
// of the ES device ID. Matching another NAND requires that NAND's saved serial.
|
||||
inline std::string GenerateSerial(std::time_t now) {
|
||||
if (now < 0) {
|
||||
return {};
|
||||
}
|
||||
const auto digits = std::to_string(now % 1000000000);
|
||||
return std::string(9 - digits.size(), '0') + digits;
|
||||
}
|
||||
|
||||
// This recompilation targets the European disc. These are Dolphin's PAL boot
|
||||
// defaults; an existing setting.txt always takes precedence, in every region.
|
||||
inline std::optional<std::array<uint8_t, 256>> EncodeNew(const std::string& serial) {
|
||||
const Settings identity{{"SERNO", serial}, {"CODE", "LEH"}, {"AREA", "EUR"}, {"GAME", "EU"}};
|
||||
if (!HasIdentity(identity)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::array<uint8_t, 256> bytes{};
|
||||
size_t position = 0;
|
||||
uint32_t key = 0x73B5DBFAu;
|
||||
const auto writeByte = [&](char value) {
|
||||
bytes[position++] = static_cast<uint8_t>(value) ^ static_cast<uint8_t>(key);
|
||||
key = (key << 1) | (key >> 31);
|
||||
};
|
||||
for (const std::string& line : {std::string("AREA=EUR\r\n"), std::string("MODEL=RVL-001(EUR)\r\n"),
|
||||
std::string("DVD=0\r\n"), std::string("MPCH=0x7FFE\r\n"), std::string("CODE=LEH\r\n"),
|
||||
"SERNO=" + serial + "\r\n", std::string("VIDEO=PAL\r\n"), std::string("GAME=EU\r\n")}) {
|
||||
for (;;) {
|
||||
if (position + line.size() > bytes.size()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
const auto start = position;
|
||||
const auto savedKey = key;
|
||||
bool hasNull = false;
|
||||
for (const char value : line) {
|
||||
writeByte(value);
|
||||
hasNull |= bytes[position - 1] == 0;
|
||||
}
|
||||
if (!hasNull) {
|
||||
break;
|
||||
}
|
||||
// Nintendo stops at an encoded NUL. Dolphin inserts an extra LF
|
||||
// before this line and retries with the shifted encryption key.
|
||||
position = start;
|
||||
key = savedKey;
|
||||
writeByte('\n');
|
||||
}
|
||||
}
|
||||
return bytes; // The unused tail stays raw zero, as in Dolphin.
|
||||
}
|
||||
|
||||
// Atomically claim our own scratch directory. A collision belongs to another
|
||||
// launch (or a previous crashed launch); leave it untouched and try another name.
|
||||
inline std::optional<std::filesystem::path> CreateScratchDirectory(
|
||||
const std::filesystem::path& parent, const std::string& token, std::error_code& ec) {
|
||||
for (unsigned attempt = 0; attempt < 128; ++attempt) {
|
||||
const auto candidate = parent / (".setting-init-" + token + "-" + std::to_string(attempt));
|
||||
ec.clear();
|
||||
if (std::filesystem::create_directory(candidate, ec)) return candidate;
|
||||
if (ec && ec != std::errc::file_exists) return std::nullopt;
|
||||
}
|
||||
ec = std::make_error_code(std::errc::file_exists);
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Never replace an existing file, including an unreadable or damaged one.
|
||||
// Publish a complete file atomically so simultaneous launches use one identity.
|
||||
inline bool Ensure(const std::filesystem::path& root, std::string& error,
|
||||
std::time_t now = std::time(nullptr)) {
|
||||
const auto path = FilePath(root);
|
||||
std::error_code ec;
|
||||
const auto status = std::filesystem::symlink_status(path, ec);
|
||||
if (ec && ec != std::errc::no_such_file_or_directory) {
|
||||
error = "Cannot inspect NAND setting.txt: " + ec.message();
|
||||
return false;
|
||||
}
|
||||
if (std::filesystem::exists(status)) {
|
||||
const auto existing = Read(root);
|
||||
if (existing && HasIdentity(*existing)) {
|
||||
return true;
|
||||
}
|
||||
error = "Existing NAND setting.txt is unreadable or invalid; restore it from this console's backup";
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto bytes = EncodeNew(GenerateSerial(now));
|
||||
if (!bytes) {
|
||||
error = "Cannot initialize NAND settings: invalid system clock";
|
||||
return false;
|
||||
}
|
||||
ec.clear();
|
||||
std::filesystem::create_directories(path.parent_path(), ec);
|
||||
if (ec) {
|
||||
error = "Cannot create NAND settings directory: " + ec.message();
|
||||
return false;
|
||||
}
|
||||
static std::atomic<unsigned> sequence{0};
|
||||
#ifdef _WIN32
|
||||
const auto processId = GetCurrentProcessId();
|
||||
#else
|
||||
const auto processId = getpid();
|
||||
#endif
|
||||
const auto scratch = CreateScratchDirectory(path.parent_path(),
|
||||
std::to_string(processId) + "-" + std::to_string(
|
||||
std::chrono::steady_clock::now().time_since_epoch().count()) + "-" +
|
||||
std::to_string(sequence++), ec);
|
||||
if (!scratch) {
|
||||
error = "Cannot create temporary NAND settings directory: " + ec.message();
|
||||
return false;
|
||||
}
|
||||
const auto temporary = *scratch / "setting.txt";
|
||||
bool written = false;
|
||||
{
|
||||
std::ofstream output(temporary, std::ios::binary);
|
||||
output.write(reinterpret_cast<const char*>(bytes->data()), bytes->size());
|
||||
output.close();
|
||||
written = static_cast<bool>(output);
|
||||
}
|
||||
bool published = false;
|
||||
if (written) {
|
||||
#ifdef _WIN32
|
||||
published = MoveFileExW(temporary.c_str(), path.c_str(), MOVEFILE_WRITE_THROUGH) != 0;
|
||||
#else
|
||||
published = ::link(temporary.c_str(), path.c_str()) == 0;
|
||||
#endif
|
||||
}
|
||||
std::filesystem::remove(temporary, ec);
|
||||
std::filesystem::remove(*scratch, ec);
|
||||
// A competing launcher may have published its settings first. Always read
|
||||
// the winner from NAND rather than using our unpersisted candidate serial.
|
||||
const auto persisted = Read(root);
|
||||
if (persisted && HasIdentity(*persisted)) {
|
||||
return true;
|
||||
}
|
||||
error = published ? "Cannot read newly initialized NAND setting.txt" :
|
||||
"Cannot persist NAND setting.txt; check NAND directory permissions";
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace RuntimeNandSettings
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <charconv>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string_view>
|
||||
#include <system_error>
|
||||
|
||||
namespace RuntimeScSerial {
|
||||
|
||||
// SCGetProductSN's output is a u32, not a character buffer. DWC loads
|
||||
// that word and formats it with the product code to construct csnum.
|
||||
template <typename RangeValidator, typename WordWriter>
|
||||
uint32_t Write(std::string_view serial, uint32_t address,
|
||||
RangeValidator&& contains, WordWriter&& write32) {
|
||||
if (serial.empty() || serial.size() > 9 ||
|
||||
serial.find_first_not_of("0123456789") != std::string_view::npos) return 0;
|
||||
uint32_t number = 0;
|
||||
const auto parsed = std::from_chars(serial.data(), serial.data() + serial.size(), number);
|
||||
if (parsed.ec != std::errc{} || parsed.ptr != serial.data() + serial.size() ||
|
||||
!address || !contains(address, sizeof(uint32_t))) return 0;
|
||||
write32(address, number);
|
||||
return 1;
|
||||
}
|
||||
|
||||
} // namespace RuntimeScSerial
|
||||
Reference in New Issue
Block a user