cfg.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include "common/file_util.h"
  6. #include "common/logging/log.h"
  7. #include "common/string_util.h"
  8. #include "common/swap.h"
  9. #include "core/file_sys/archive_systemsavedata.h"
  10. #include "core/file_sys/file_backend.h"
  11. #include "core/settings.h"
  12. #include "core/hle/result.h"
  13. #include "core/hle/service/cfg/cfg.h"
  14. #include "core/hle/service/cfg/cfg_i.h"
  15. #include "core/hle/service/cfg/cfg_s.h"
  16. #include "core/hle/service/cfg/cfg_u.h"
  17. #include "core/hle/service/fs/archive.h"
  18. #include "core/hle/service/service.h"
  19. namespace Service {
  20. namespace CFG {
  21. /// The maximum number of block entries that can exist in the config file
  22. static const u32 CONFIG_FILE_MAX_BLOCK_ENTRIES = 1479;
  23. namespace {
  24. /**
  25. * The header of the config savedata file,
  26. * contains information about the blocks in the file
  27. */
  28. struct SaveFileConfig {
  29. u16 total_entries; ///< The total number of set entries in the config file
  30. u16 data_entries_offset; ///< The offset where the data for the blocks start, this is hardcoded to 0x455C as per hardware
  31. SaveConfigBlockEntry block_entries[CONFIG_FILE_MAX_BLOCK_ENTRIES]; ///< The block headers, the maximum possible value is 1479 as per hardware
  32. u32 unknown; ///< This field is unknown, possibly padding, 0 has been observed in hardware
  33. };
  34. static_assert(sizeof(SaveFileConfig) == 0x455C, "SaveFileConfig header must be exactly 0x455C bytes");
  35. struct UsernameBlock {
  36. char16_t username[10]; ///< Exactly 20 bytes long, padded with zeros at the end if necessary
  37. u32 zero;
  38. u32 ng_word;
  39. };
  40. static_assert(sizeof(UsernameBlock) == 0x1C, "UsernameBlock must be exactly 0x1C bytes");
  41. struct ConsoleModelInfo {
  42. u8 model; ///< The console model (3DS, 2DS, etc)
  43. u8 unknown[3]; ///< Unknown data
  44. };
  45. static_assert(sizeof(ConsoleModelInfo) == 4, "ConsoleModelInfo must be exactly 4 bytes");
  46. struct ConsoleCountryInfo {
  47. u8 unknown[3]; ///< Unknown data
  48. u8 country_code; ///< The country code of the console
  49. };
  50. static_assert(sizeof(ConsoleCountryInfo) == 4, "ConsoleCountryInfo must be exactly 4 bytes");
  51. }
  52. static const u64 CFG_SAVE_ID = 0x00010017;
  53. static const u64 CONSOLE_UNIQUE_ID = 0xDEADC0DE;
  54. static const ConsoleModelInfo CONSOLE_MODEL = { NINTENDO_3DS_XL, { 0, 0, 0 } };
  55. static const u8 CONSOLE_LANGUAGE = LANGUAGE_EN;
  56. static const char CONSOLE_USERNAME[0x14] = "CITRA";
  57. /// This will be initialized in Init, and will be used when creating the block
  58. static UsernameBlock CONSOLE_USERNAME_BLOCK;
  59. /// TODO(Subv): Find out what this actually is
  60. static const u8 SOUND_OUTPUT_MODE = 2;
  61. static const u8 UNITED_STATES_COUNTRY_ID = 49;
  62. /// TODO(Subv): Find what the other bytes are
  63. static const ConsoleCountryInfo COUNTRY_INFO = { { 0, 0, 0 }, UNITED_STATES_COUNTRY_ID };
  64. /**
  65. * TODO(Subv): Find out what this actually is, these values fix some NaN uniforms in some games,
  66. * for example Nintendo Zone
  67. * Thanks Normmatt for providing this information
  68. */
  69. static const std::array<float, 8> STEREO_CAMERA_SETTINGS = {{
  70. 62.0f, 289.0f, 76.80000305175781f, 46.08000183105469f,
  71. 10.0f, 5.0f, 55.58000183105469f, 21.56999969482422f
  72. }};
  73. static_assert(sizeof(STEREO_CAMERA_SETTINGS) == 0x20, "STEREO_CAMERA_SETTINGS must be exactly 0x20 bytes");
  74. static const u32 CONFIG_SAVEFILE_SIZE = 0x8000;
  75. static std::array<u8, CONFIG_SAVEFILE_SIZE> cfg_config_file_buffer;
  76. static Service::FS::ArchiveHandle cfg_system_save_data_archive;
  77. static const std::vector<u8> cfg_system_savedata_id = { 0x00, 0x00, 0x00, 0x00, 0x17, 0x00, 0x01, 0x00 };
  78. void GetCountryCodeString(Service::Interface* self) {
  79. u32* cmd_buff = Kernel::GetCommandBuffer();
  80. u32 country_code_id = cmd_buff[1];
  81. if (country_code_id >= country_codes.size() || 0 == country_codes[country_code_id]) {
  82. LOG_ERROR(Service_CFG, "requested country code id=%d is invalid", country_code_id);
  83. cmd_buff[1] = ResultCode(ErrorDescription::NotFound, ErrorModule::Config, ErrorSummary::WrongArgument, ErrorLevel::Permanent).raw;
  84. return;
  85. }
  86. cmd_buff[1] = 0;
  87. cmd_buff[2] = country_codes[country_code_id];
  88. }
  89. void GetCountryCodeID(Service::Interface* self) {
  90. u32* cmd_buff = Kernel::GetCommandBuffer();
  91. u16 country_code = cmd_buff[1];
  92. u16 country_code_id = 0;
  93. // The following algorithm will fail if the first country code isn't 0.
  94. DEBUG_ASSERT(country_codes[0] == 0);
  95. for (u16 id = 0; id < country_codes.size(); ++id) {
  96. if (country_codes[id] == country_code) {
  97. country_code_id = id;
  98. break;
  99. }
  100. }
  101. if (0 == country_code_id) {
  102. LOG_ERROR(Service_CFG, "requested country code name=%c%c is invalid", country_code & 0xff, country_code >> 8);
  103. cmd_buff[1] = ResultCode(ErrorDescription::NotFound, ErrorModule::Config, ErrorSummary::WrongArgument, ErrorLevel::Permanent).raw;
  104. cmd_buff[2] = 0xFFFF;
  105. return;
  106. }
  107. cmd_buff[1] = 0;
  108. cmd_buff[2] = country_code_id;
  109. }
  110. void SecureInfoGetRegion(Service::Interface* self) {
  111. u32* cmd_buff = Kernel::GetCommandBuffer();
  112. cmd_buff[1] = RESULT_SUCCESS.raw;
  113. cmd_buff[2] = Settings::values.region_value;
  114. }
  115. void GenHashConsoleUnique(Service::Interface* self) {
  116. u32* cmd_buff = Kernel::GetCommandBuffer();
  117. u32 app_id_salt = cmd_buff[1];
  118. cmd_buff[1] = RESULT_SUCCESS.raw;
  119. cmd_buff[2] = 0x33646D6F ^ (app_id_salt & 0xFFFFF); // 3dmoo hash
  120. cmd_buff[3] = 0x6F534841 ^ (app_id_salt & 0xFFFFF);
  121. LOG_WARNING(Service_CFG, "(STUBBED) called app_id_salt=0x%X", app_id_salt);
  122. }
  123. void GetRegionCanadaUSA(Service::Interface* self) {
  124. u32* cmd_buff = Kernel::GetCommandBuffer();
  125. cmd_buff[1] = RESULT_SUCCESS.raw;
  126. u8 canada_or_usa = 1;
  127. if (canada_or_usa == Settings::values.region_value) {
  128. cmd_buff[2] = 1;
  129. } else {
  130. cmd_buff[2] = 0;
  131. }
  132. }
  133. void GetSystemModel(Service::Interface* self) {
  134. u32* cmd_buff = Kernel::GetCommandBuffer();
  135. u32 data;
  136. // TODO(Subv): Find out the correct error codes
  137. cmd_buff[1] = Service::CFG::GetConfigInfoBlock(0x000F0004, 4, 0x8,
  138. reinterpret_cast<u8*>(&data)).raw;
  139. cmd_buff[2] = data & 0xFF;
  140. }
  141. void GetModelNintendo2DS(Service::Interface* self) {
  142. u32* cmd_buff = Kernel::GetCommandBuffer();
  143. u32 data;
  144. // TODO(Subv): Find out the correct error codes
  145. cmd_buff[1] = Service::CFG::GetConfigInfoBlock(0x000F0004, 4, 0x8,
  146. reinterpret_cast<u8*>(&data)).raw;
  147. u8 model = data & 0xFF;
  148. if (model == Service::CFG::NINTENDO_2DS)
  149. cmd_buff[2] = 0;
  150. else
  151. cmd_buff[2] = 1;
  152. }
  153. void GetConfigInfoBlk2(Service::Interface* self) {
  154. u32* cmd_buff = Kernel::GetCommandBuffer();
  155. u32 size = cmd_buff[1];
  156. u32 block_id = cmd_buff[2];
  157. u8* data_pointer = Memory::GetPointer(cmd_buff[4]);
  158. if (data_pointer == nullptr) {
  159. cmd_buff[1] = -1; // TODO(Subv): Find the right error code
  160. return;
  161. }
  162. cmd_buff[1] = Service::CFG::GetConfigInfoBlock(block_id, size, 0x2, data_pointer).raw;
  163. }
  164. void GetConfigInfoBlk8(Service::Interface* self) {
  165. u32* cmd_buff = Kernel::GetCommandBuffer();
  166. u32 size = cmd_buff[1];
  167. u32 block_id = cmd_buff[2];
  168. u8* data_pointer = Memory::GetPointer(cmd_buff[4]);
  169. if (data_pointer == nullptr) {
  170. cmd_buff[1] = -1; // TODO(Subv): Find the right error code
  171. return;
  172. }
  173. cmd_buff[1] = Service::CFG::GetConfigInfoBlock(block_id, size, 0x8, data_pointer).raw;
  174. }
  175. void UpdateConfigNANDSavegame(Service::Interface* self) {
  176. u32* cmd_buff = Kernel::GetCommandBuffer();
  177. cmd_buff[1] = Service::CFG::UpdateConfigNANDSavegame().raw;
  178. }
  179. void FormatConfig(Service::Interface* self) {
  180. u32* cmd_buff = Kernel::GetCommandBuffer();
  181. cmd_buff[1] = Service::CFG::FormatConfig().raw;
  182. }
  183. ResultCode GetConfigInfoBlock(u32 block_id, u32 size, u32 flag, u8* output) {
  184. // Read the header
  185. SaveFileConfig* config = reinterpret_cast<SaveFileConfig*>(cfg_config_file_buffer.data());
  186. auto itr = std::find_if(std::begin(config->block_entries), std::end(config->block_entries),
  187. [&](const SaveConfigBlockEntry& entry) {
  188. return entry.block_id == block_id && (entry.flags & flag);
  189. });
  190. if (itr == std::end(config->block_entries)) {
  191. LOG_ERROR(Service_CFG, "Config block 0x%X with flags %u and size %u was not found", block_id, flag, size);
  192. return ResultCode(ErrorDescription::NotFound, ErrorModule::Config, ErrorSummary::WrongArgument, ErrorLevel::Permanent);
  193. }
  194. if (itr->size != size) {
  195. LOG_ERROR(Service_CFG, "Invalid size %u for config block 0x%X with flags %u", size, block_id, flag);
  196. return ResultCode(ErrorDescription::InvalidSize, ErrorModule::Config, ErrorSummary::WrongArgument, ErrorLevel::Permanent);
  197. }
  198. // The data is located in the block header itself if the size is less than 4 bytes
  199. if (itr->size <= 4)
  200. memcpy(output, &itr->offset_or_data, itr->size);
  201. else
  202. memcpy(output, &cfg_config_file_buffer[itr->offset_or_data], itr->size);
  203. return RESULT_SUCCESS;
  204. }
  205. ResultCode CreateConfigInfoBlk(u32 block_id, u16 size, u16 flags, const void* data) {
  206. SaveFileConfig* config = reinterpret_cast<SaveFileConfig*>(cfg_config_file_buffer.data());
  207. if (config->total_entries >= CONFIG_FILE_MAX_BLOCK_ENTRIES)
  208. return ResultCode(-1); // TODO(Subv): Find the right error code
  209. // Insert the block header with offset 0 for now
  210. config->block_entries[config->total_entries] = { block_id, 0, size, flags };
  211. if (size > 4) {
  212. u32 offset = config->data_entries_offset;
  213. // Perform a search to locate the next offset for the new data
  214. // use the offset and size of the previous block to determine the new position
  215. for (int i = config->total_entries - 1; i >= 0; --i) {
  216. // Ignore the blocks that don't have a separate data offset
  217. if (config->block_entries[i].size > 4) {
  218. offset = config->block_entries[i].offset_or_data +
  219. config->block_entries[i].size;
  220. break;
  221. }
  222. }
  223. config->block_entries[config->total_entries].offset_or_data = offset;
  224. // Write the data at the new offset
  225. memcpy(&cfg_config_file_buffer[offset], data, size);
  226. }
  227. else {
  228. // The offset_or_data field in the header contains the data itself if it's 4 bytes or less
  229. memcpy(&config->block_entries[config->total_entries].offset_or_data, data, size);
  230. }
  231. ++config->total_entries;
  232. return RESULT_SUCCESS;
  233. }
  234. ResultCode DeleteConfigNANDSaveFile() {
  235. FileSys::Path path("config");
  236. return Service::FS::DeleteFileFromArchive(cfg_system_save_data_archive, path);
  237. }
  238. ResultCode UpdateConfigNANDSavegame() {
  239. FileSys::Mode mode = {};
  240. mode.write_flag.Assign(1);
  241. mode.create_flag.Assign(1);
  242. FileSys::Path path("config");
  243. auto config_result = Service::FS::OpenFileFromArchive(cfg_system_save_data_archive, path, mode);
  244. ASSERT_MSG(config_result.Succeeded(), "could not open file");
  245. auto config = config_result.MoveFrom();
  246. config->backend->Write(0, CONFIG_SAVEFILE_SIZE, 1, cfg_config_file_buffer.data());
  247. return RESULT_SUCCESS;
  248. }
  249. ResultCode FormatConfig() {
  250. ResultCode res = DeleteConfigNANDSaveFile();
  251. if (!res.IsSuccess() && res.description != ErrorDescription::FS_NotFound)
  252. return res;
  253. // Delete the old data
  254. cfg_config_file_buffer.fill(0);
  255. // Create the header
  256. SaveFileConfig* config = reinterpret_cast<SaveFileConfig*>(cfg_config_file_buffer.data());
  257. // This value is hardcoded, taken from 3dbrew, verified by hardware, it's always the same value
  258. config->data_entries_offset = 0x455C;
  259. // Insert the default blocks
  260. u8 zero_buffer[0xC0] = {};
  261. // 0x00030001 - Unknown
  262. res = CreateConfigInfoBlk(0x00030001, 0x8, 0xE, zero_buffer);
  263. if (!res.IsSuccess()) return res;
  264. res = CreateConfigInfoBlk(0x00050005, sizeof(STEREO_CAMERA_SETTINGS), 0xE, STEREO_CAMERA_SETTINGS.data());
  265. if (!res.IsSuccess()) return res;
  266. res = CreateConfigInfoBlk(0x00070001, sizeof(SOUND_OUTPUT_MODE), 0xE, &SOUND_OUTPUT_MODE);
  267. if (!res.IsSuccess()) return res;
  268. res = CreateConfigInfoBlk(0x00090001, sizeof(CONSOLE_UNIQUE_ID), 0xE, &CONSOLE_UNIQUE_ID);
  269. if (!res.IsSuccess()) return res;
  270. res = CreateConfigInfoBlk(0x000A0000, sizeof(CONSOLE_USERNAME_BLOCK), 0xE, &CONSOLE_USERNAME_BLOCK);
  271. if (!res.IsSuccess()) return res;
  272. // 0x000A0000 - Profile username
  273. struct {
  274. u16_le username[10];
  275. u8 unused[4];
  276. u32_le wordfilter_version; // Unused by Citra
  277. } profile_username = {};
  278. std::u16string username_string = Common::UTF8ToUTF16("Citra");
  279. std::copy(username_string.cbegin(), username_string.cend(), profile_username.username);
  280. res = CreateConfigInfoBlk(0x000A0000, sizeof(profile_username), 0xE, &profile_username);
  281. if (!res.IsSuccess()) return res;
  282. // 0x000A0001 - Profile birthday
  283. const u8 profile_birthday[2] = {3, 25}; // March 25th, 2014
  284. res = CreateConfigInfoBlk(0x000A0001, sizeof(profile_birthday), 0xE, profile_birthday);
  285. if (!res.IsSuccess()) return res;
  286. res = CreateConfigInfoBlk(0x000A0002, sizeof(CONSOLE_LANGUAGE), 0xE, &CONSOLE_LANGUAGE);
  287. if (!res.IsSuccess()) return res;
  288. res = CreateConfigInfoBlk(0x000B0000, sizeof(COUNTRY_INFO), 0xE, &COUNTRY_INFO);
  289. if (!res.IsSuccess()) return res;
  290. u16_le country_name_buffer[16][0x40] = {};
  291. std::u16string region_name = Common::UTF8ToUTF16("Gensokyo");
  292. for (size_t i = 0; i < 16; ++i) {
  293. std::copy(region_name.cbegin(), region_name.cend(), country_name_buffer[i]);
  294. }
  295. // 0x000B0001 - Localized names for the profile Country
  296. res = CreateConfigInfoBlk(0x000B0001, sizeof(country_name_buffer), 0xE, country_name_buffer);
  297. if (!res.IsSuccess()) return res;
  298. // 0x000B0002 - Localized names for the profile State/Province
  299. res = CreateConfigInfoBlk(0x000B0002, sizeof(country_name_buffer), 0xE, country_name_buffer);
  300. if (!res.IsSuccess()) return res;
  301. // 0x000B0003 - Unknown, related to country/address (zip code?)
  302. res = CreateConfigInfoBlk(0x000B0003, 0x4, 0xE, zero_buffer);
  303. if (!res.IsSuccess()) return res;
  304. // 0x000C0000 - Unknown
  305. res = CreateConfigInfoBlk(0x000C0000, 0xC0, 0xE, zero_buffer);
  306. if (!res.IsSuccess()) return res;
  307. // 0x000C0001 - Unknown
  308. res = CreateConfigInfoBlk(0x000C0001, 0x14, 0xE, zero_buffer);
  309. if (!res.IsSuccess()) return res;
  310. // 0x000D0000 - Accepted EULA version
  311. res = CreateConfigInfoBlk(0x000D0000, 0x4, 0xE, zero_buffer);
  312. if (!res.IsSuccess()) return res;
  313. res = CreateConfigInfoBlk(0x000F0004, sizeof(CONSOLE_MODEL), 0xC, &CONSOLE_MODEL);
  314. if (!res.IsSuccess()) return res;
  315. // Save the buffer to the file
  316. res = UpdateConfigNANDSavegame();
  317. if (!res.IsSuccess())
  318. return res;
  319. return RESULT_SUCCESS;
  320. }
  321. void Init() {
  322. AddService(new CFG_I_Interface);
  323. AddService(new CFG_S_Interface);
  324. AddService(new CFG_U_Interface);
  325. // Open the SystemSaveData archive 0x00010017
  326. FileSys::Path archive_path(cfg_system_savedata_id);
  327. auto archive_result = Service::FS::OpenArchive(Service::FS::ArchiveIdCode::SystemSaveData, archive_path);
  328. // If the archive didn't exist, create the files inside
  329. if (archive_result.Code().description == ErrorDescription::FS_NotFormatted) {
  330. // Format the archive to create the directories
  331. Service::FS::FormatArchive(Service::FS::ArchiveIdCode::SystemSaveData, FileSys::ArchiveFormatInfo(), archive_path);
  332. // Open it again to get a valid archive now that the folder exists
  333. archive_result = Service::FS::OpenArchive(Service::FS::ArchiveIdCode::SystemSaveData, archive_path);
  334. }
  335. ASSERT_MSG(archive_result.Succeeded(), "Could not open the CFG SystemSaveData archive!");
  336. cfg_system_save_data_archive = *archive_result;
  337. FileSys::Path config_path("config");
  338. FileSys::Mode open_mode = {};
  339. open_mode.read_flag.Assign(1);
  340. auto config_result = Service::FS::OpenFileFromArchive(*archive_result, config_path, open_mode);
  341. // Read the file if it already exists
  342. if (config_result.Succeeded()) {
  343. auto config = config_result.MoveFrom();
  344. config->backend->Read(0, CONFIG_SAVEFILE_SIZE, cfg_config_file_buffer.data());
  345. return;
  346. }
  347. // Initialize the Username block
  348. // TODO(Subv): Initialize this directly in the variable when MSVC supports char16_t string literals
  349. memset(&CONSOLE_USERNAME_BLOCK, 0, sizeof(CONSOLE_USERNAME_BLOCK));
  350. CONSOLE_USERNAME_BLOCK.ng_word = 0;
  351. CONSOLE_USERNAME_BLOCK.zero = 0;
  352. // Copy string to buffer and pad with zeros at the end
  353. auto size = Common::UTF8ToUTF16(CONSOLE_USERNAME).copy(CONSOLE_USERNAME_BLOCK.username, 0x14);
  354. std::fill(std::begin(CONSOLE_USERNAME_BLOCK.username) + size,
  355. std::end(CONSOLE_USERNAME_BLOCK.username), 0);
  356. FormatConfig();
  357. }
  358. void Shutdown() {
  359. }
  360. } // namespace CFG
  361. } // namespace Service