cfg.cpp 16 KB

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