cfg_u.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. // Copyright 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include "common/file_util.h"
  5. #include "common/log.h"
  6. #include "common/string_util.h"
  7. #include "core/file_sys/archive_systemsavedata.h"
  8. #include "core/hle/hle.h"
  9. #include "core/hle/service/cfg_u.h"
  10. ////////////////////////////////////////////////////////////////////////////////////////////////////
  11. // Namespace CFG_U
  12. namespace CFG_U {
  13. enum SystemModel {
  14. NINTENDO_3DS,
  15. NINTENDO_3DS_XL,
  16. NEW_NINTENDO_3DS,
  17. NINTENDO_2DS,
  18. NEW_NINTENDO_3DS_XL
  19. };
  20. enum SystemLanguage {
  21. LANGUAGE_JP,
  22. LANGUAGE_EN,
  23. LANGUAGE_FR,
  24. LANGUAGE_DE,
  25. LANGUAGE_IT,
  26. LANGUAGE_ES,
  27. LANGUAGE_ZH,
  28. LANGUAGE_KO,
  29. LANGUAGE_NL,
  30. LANGUAGE_PT,
  31. LANGUAGE_RU
  32. };
  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, "Size of UsernameBlock must be 0x1C");
  39. static std::unique_ptr<FileSys::Archive_SystemSaveData> cfg_system_save_data;
  40. static const u64 CFG_SAVE_ID = 0x00010017;
  41. static const u64 CONSOLE_UNIQUE_ID = 0xDEADC0DE;
  42. static const u32 CONSOLE_MODEL = NINTENDO_3DS_XL;
  43. static const u8 CONSOLE_LANGUAGE = LANGUAGE_EN;
  44. static const char CONSOLE_USERNAME[0x14] = "CITRA";
  45. /// This will be initialized in the Interface constructor, and will be used when creating the block
  46. static UsernameBlock CONSOLE_USERNAME_BLOCK;
  47. /// TODO(Subv): Find out what this actually is
  48. static const u8 SOUND_OUTPUT_MODE = 2;
  49. static const u32 CONFIG_SAVEFILE_SIZE = 0x8000;
  50. static std::array<u8, CONFIG_SAVEFILE_SIZE> cfg_config_file_buffer = { };
  51. /// TODO(Subv): Find out what this actually is
  52. /// Thanks Normmatt for providing this information
  53. static const u8 STEREO_CAMERA_SETTINGS[32] = {
  54. 0x00, 0x00, 0x78, 0x42, 0x00, 0x80, 0x90, 0x43, 0x9A, 0x99, 0x99, 0x42, 0xEC, 0x51, 0x38, 0x42,
  55. 0x00, 0x00, 0x20, 0x41, 0x00, 0x00, 0xA0, 0x40, 0xEC, 0x51, 0x5E, 0x42, 0x5C, 0x8F, 0xAC, 0x41
  56. };
  57. // TODO(Link Mauve): use a constexpr once MSVC starts supporting it.
  58. #define C(code) ((code)[0] | ((code)[1] << 8))
  59. /// TODO(Subv): Find what the other bytes are
  60. static const std::array<u8, 4> COUNTRY_INFO = { 0, 0, 0, C("US") };
  61. static const std::array<u16, 187> country_codes = {
  62. 0, C("JP"), 0, 0, 0, 0, 0, 0, // 0-7
  63. C("AI"), C("AG"), C("AR"), C("AW"), C("BS"), C("BB"), C("BZ"), C("BO"), // 8-15
  64. C("BR"), C("VG"), C("CA"), C("KY"), C("CL"), C("CO"), C("CR"), C("DM"), // 16-23
  65. C("DO"), C("EC"), C("SV"), C("GF"), C("GD"), C("GP"), C("GT"), C("GY"), // 24-31
  66. C("HT"), C("HN"), C("JM"), C("MQ"), C("MX"), C("MS"), C("AN"), C("NI"), // 32-39
  67. C("PA"), C("PY"), C("PE"), C("KN"), C("LC"), C("VC"), C("SR"), C("TT"), // 40-47
  68. C("TC"), C("US"), C("UY"), C("VI"), C("VE"), 0, 0, 0, // 48-55
  69. 0, 0, 0, 0, 0, 0, 0, 0, // 56-63
  70. C("AL"), C("AU"), C("AT"), C("BE"), C("BA"), C("BW"), C("BG"), C("HR"), // 64-71
  71. C("CY"), C("CZ"), C("DK"), C("EE"), C("FI"), C("FR"), C("DE"), C("GR"), // 72-79
  72. C("HU"), C("IS"), C("IE"), C("IT"), C("LV"), C("LS"), C("LI"), C("LT"), // 80-87
  73. C("LU"), C("MK"), C("MT"), C("ME"), C("MZ"), C("NA"), C("NL"), C("NZ"), // 88-95
  74. C("NO"), C("PL"), C("PT"), C("RO"), C("RU"), C("RS"), C("SK"), C("SI"), // 96-103
  75. C("ZA"), C("ES"), C("SZ"), C("SE"), C("CH"), C("TR"), C("GB"), C("ZM"), // 104-111
  76. C("ZW"), C("AZ"), C("MR"), C("ML"), C("NE"), C("TD"), C("SD"), C("ER"), // 112-119
  77. C("DJ"), C("SO"), C("AD"), C("GI"), C("GG"), C("IM"), C("JE"), C("MC"), // 120-127
  78. C("TW"), 0, 0, 0, 0, 0, 0, 0, // 128-135
  79. C("KR"), 0, 0, 0, 0, 0, 0, 0, // 136-143
  80. C("HK"), C("MO"), 0, 0, 0, 0, 0, 0, // 144-151
  81. C("ID"), C("SG"), C("TH"), C("PH"), C("MY"), 0, 0, 0, // 152-159
  82. C("CN"), 0, 0, 0, 0, 0, 0, 0, // 160-167
  83. C("AE"), C("IN"), C("EG"), C("OM"), C("QA"), C("KW"), C("SA"), C("SY"), // 168-175
  84. C("BH"), C("JO"), 0, 0, 0, 0, 0, 0, // 176-183
  85. C("SM"), C("VA"), C("BM") // 184-186
  86. };
  87. #undef C
  88. /**
  89. * CFG_User::GetCountryCodeString service function
  90. * Inputs:
  91. * 1 : Country Code ID
  92. * Outputs:
  93. * 1 : Result of function, 0 on success, otherwise error code
  94. * 2 : Country's 2-char string
  95. */
  96. static void GetCountryCodeString(Service::Interface* self) {
  97. u32* cmd_buffer = Kernel::GetCommandBuffer();
  98. u32 country_code_id = cmd_buffer[1];
  99. if (country_code_id >= country_codes.size() || 0 == country_codes[country_code_id]) {
  100. LOG_ERROR(Service_CFG, "requested country code id=%d is invalid", country_code_id);
  101. cmd_buffer[1] = ResultCode(ErrorDescription::NotFound, ErrorModule::Config, ErrorSummary::WrongArgument, ErrorLevel::Permanent).raw;
  102. return;
  103. }
  104. cmd_buffer[1] = 0;
  105. cmd_buffer[2] = country_codes[country_code_id];
  106. }
  107. /**
  108. * CFG_User::GetCountryCodeID service function
  109. * Inputs:
  110. * 1 : Country Code 2-char string
  111. * Outputs:
  112. * 1 : Result of function, 0 on success, otherwise error code
  113. * 2 : Country Code ID
  114. */
  115. static void GetCountryCodeID(Service::Interface* self) {
  116. u32* cmd_buffer = Kernel::GetCommandBuffer();
  117. u16 country_code = cmd_buffer[1];
  118. u16 country_code_id = 0;
  119. // The following algorithm will fail if the first country code isn't 0.
  120. _dbg_assert_(Service_CFG, country_codes[0] == 0);
  121. for (size_t id = 0; id < country_codes.size(); ++id) {
  122. if (country_codes[id] == country_code) {
  123. country_code_id = id;
  124. break;
  125. }
  126. }
  127. if (0 == country_code_id) {
  128. LOG_ERROR(Service_CFG, "requested country code name=%c%c is invalid", country_code & 0xff, country_code >> 8);
  129. cmd_buffer[1] = ResultCode(ErrorDescription::NotFound, ErrorModule::Config, ErrorSummary::WrongArgument, ErrorLevel::Permanent).raw;
  130. cmd_buffer[2] = 0xFFFF;
  131. return;
  132. }
  133. cmd_buffer[1] = 0;
  134. cmd_buffer[2] = country_code_id;
  135. }
  136. /// Block header in the config savedata file
  137. struct SaveConfigBlockEntry {
  138. u32 block_id;
  139. u32 offset_or_data;
  140. u16 size;
  141. u16 flags;
  142. };
  143. /// The header of the config savedata file,
  144. /// contains information about the blocks in the file
  145. struct SaveFileConfig {
  146. u16 total_entries;
  147. u16 data_entries_offset;
  148. SaveConfigBlockEntry block_entries[1479];
  149. u32 unknown;
  150. };
  151. /**
  152. * Reads a block with the specified id and flag from the Config savegame buffer
  153. * and writes the output to output.
  154. * The input size must match exactly the size of the requested block
  155. * TODO(Subv): This should actually be in some file common to the CFG process
  156. * @param block_id The id of the block we want to read
  157. * @param size The size of the block we want to read
  158. * @param flag The requested block must have this flag set
  159. * @param output A pointer where we will write the read data
  160. * @returns ResultCode indicating the result of the operation, 0 on success
  161. */
  162. ResultCode GetConfigInfoBlock(u32 block_id, u32 size, u32 flag, u8* output) {
  163. // Read the header
  164. SaveFileConfig* config = reinterpret_cast<SaveFileConfig*>(cfg_config_file_buffer.data());
  165. auto itr = std::find_if(std::begin(config->block_entries), std::end(config->block_entries),
  166. [&](SaveConfigBlockEntry const& entry) {
  167. return entry.block_id == block_id && entry.size == size && (entry.flags & flag);
  168. });
  169. if (itr == std::end(config->block_entries)) {
  170. LOG_ERROR(Service_CFG, "Config block %u with size %u and flags %u not found", block_id, size, flag);
  171. return ResultCode(-1); // TODO(Subv): Find the correct error code
  172. }
  173. // The data is located in the block header itself if the size is less than 4 bytes
  174. if (itr->size <= 4)
  175. memcpy(output, &itr->offset_or_data, itr->size);
  176. else
  177. memcpy(output, &cfg_config_file_buffer[itr->offset_or_data], itr->size);
  178. return RESULT_SUCCESS;
  179. }
  180. /**
  181. * Creates a block with the specified id and writes the input data to the cfg savegame buffer in memory.
  182. * The config savegame file in the filesystem is not updated.
  183. * TODO(Subv): This should actually be in some file common to the CFG process
  184. * @param block_id The id of the block we want to create
  185. * @param size The size of the block we want to create
  186. * @param flag The flags of the new block
  187. * @param data A pointer containing the data we will write to the new block
  188. * @returns ResultCode indicating the result of the operation, 0 on success
  189. */
  190. ResultCode CreateConfigInfoBlk(u32 block_id, u32 size, u32 flags, u8 const* data) {
  191. SaveFileConfig* config = reinterpret_cast<SaveFileConfig*>(cfg_config_file_buffer.data());
  192. // Insert the block header with offset 0 for now
  193. config->block_entries[config->total_entries] = { block_id, 0, size, flags };
  194. if (size > 4) {
  195. s32 total_entries = config->total_entries - 1;
  196. u32 offset = config->data_entries_offset;
  197. // Perform a search to locate the next offset for the new data
  198. while (total_entries >= 0) {
  199. // Ignore the blocks that don't have a separate data offset
  200. if (config->block_entries[total_entries].size <= 4) {
  201. --total_entries;
  202. continue;
  203. }
  204. offset = config->block_entries[total_entries].offset_or_data +
  205. config->block_entries[total_entries].size;
  206. break;
  207. }
  208. config->block_entries[config->total_entries].offset_or_data = offset;
  209. // Write the data at the new offset
  210. memcpy(&cfg_config_file_buffer[offset], data, size);
  211. } else {
  212. // The offset_or_data field in the header contains the data itself if it's 4 bytes or less
  213. memcpy(&config->block_entries[config->total_entries].offset_or_data, data, size);
  214. }
  215. ++config->total_entries;
  216. return RESULT_SUCCESS;
  217. }
  218. /**
  219. * Deletes the config savegame file from the filesystem, the buffer in memory is not affected
  220. * TODO(Subv): This should actually be in some file common to the CFG process
  221. * @returns ResultCode indicating the result of the operation, 0 on success
  222. */
  223. ResultCode DeleteConfigNANDSaveFile() {
  224. FileSys::Path path("config");
  225. if (cfg_system_save_data->DeleteFile(path))
  226. return RESULT_SUCCESS;
  227. return ResultCode(-1); // TODO(Subv): Find the right error code
  228. }
  229. /**
  230. * Writes the config savegame memory buffer to the config savegame file in the filesystem
  231. * TODO(Subv): This should actually be in some file common to the CFG process
  232. * @returns ResultCode indicating the result of the operation, 0 on success
  233. */
  234. ResultCode UpdateConfigNANDSavegame() {
  235. FileSys::Mode mode;
  236. mode.hex = 0;
  237. mode.write_flag = 1;
  238. mode.create_flag = 1;
  239. FileSys::Path path("config");
  240. auto file = cfg_system_save_data->OpenFile(path, mode);
  241. _dbg_assert_msg_(Service_CFG, file != nullptr, "could not open file");
  242. file->Write(0, CONFIG_SAVEFILE_SIZE, 1, cfg_config_file_buffer.data());
  243. return RESULT_SUCCESS;
  244. }
  245. /**
  246. * Re-creates the config savegame file in memory and the filesystem with the default blocks
  247. * TODO(Subv): This should actually be in some file common to the CFG process
  248. * @returns ResultCode indicating the result of the operation, 0 on success
  249. */
  250. ResultCode FormatConfig() {
  251. ResultCode res = DeleteConfigNANDSaveFile();
  252. if (!res.IsSuccess())
  253. return res;
  254. // Delete the old data
  255. std::fill(cfg_config_file_buffer.begin(), cfg_config_file_buffer.end(), 0);
  256. // Create the header
  257. SaveFileConfig* config = reinterpret_cast<SaveFileConfig*>(cfg_config_file_buffer.data());
  258. config->data_entries_offset = 0x455C;
  259. // Insert the default blocks
  260. res = CreateConfigInfoBlk(0x00050005, 0x20, 0xE, STEREO_CAMERA_SETTINGS);
  261. if (!res.IsSuccess())
  262. return res;
  263. res = CreateConfigInfoBlk(0x00090001, 0x8, 0xE, reinterpret_cast<u8 const*>(&CONSOLE_UNIQUE_ID));
  264. if (!res.IsSuccess())
  265. return res;
  266. res = CreateConfigInfoBlk(0x000F0004, 0x4, 0x8, reinterpret_cast<u8 const*>(&CONSOLE_MODEL));
  267. if (!res.IsSuccess())
  268. return res;
  269. res = CreateConfigInfoBlk(0x000A0002, 0x1, 0xA, &CONSOLE_LANGUAGE);
  270. if (!res.IsSuccess())
  271. return res;
  272. res = CreateConfigInfoBlk(0x00070001, 0x1, 0xE, &SOUND_OUTPUT_MODE);
  273. if (!res.IsSuccess())
  274. return res;
  275. res = CreateConfigInfoBlk(0x000B0000, 0x4, 0xE, COUNTRY_INFO.data());
  276. if (!res.IsSuccess())
  277. return res;
  278. res = CreateConfigInfoBlk(0x000A0000, 0x1C, 0xE, reinterpret_cast<u8*>(&CONSOLE_USERNAME_BLOCK));
  279. if (!res.IsSuccess())
  280. return res;
  281. // Save the buffer to the file
  282. res = UpdateConfigNANDSavegame();
  283. if (!res.IsSuccess())
  284. return res;
  285. return RESULT_SUCCESS;
  286. }
  287. /**
  288. * CFG_User::GetConfigInfoBlk2 service function
  289. * Inputs:
  290. * 1 : Size
  291. * 2 : Block ID
  292. * 3 : Descriptor for the output buffer
  293. * 4 : Output buffer pointer
  294. * Outputs:
  295. * 1 : Result of function, 0 on success, otherwise error code
  296. */
  297. static void GetConfigInfoBlk2(Service::Interface* self) {
  298. u32* cmd_buffer = Kernel::GetCommandBuffer();
  299. u32 size = cmd_buffer[1];
  300. u32 block_id = cmd_buffer[2];
  301. u8* data_pointer = Memory::GetPointer(cmd_buffer[4]);
  302. if (data_pointer == nullptr) {
  303. cmd_buffer[1] = -1; // TODO(Subv): Find the right error code
  304. return;
  305. }
  306. cmd_buffer[1] = GetConfigInfoBlock(block_id, size, 0x2, data_pointer).raw;
  307. }
  308. /**
  309. * CFG_User::GetSystemModel service function
  310. * Outputs:
  311. * 1 : Result of function, 0 on success, otherwise error code
  312. * 2 : Model of the console
  313. */
  314. static void GetSystemModel(Service::Interface* self) {
  315. u32* cmd_buffer = Kernel::GetCommandBuffer();
  316. u32 data;
  317. cmd_buffer[1] = GetConfigInfoBlock(0x000F0004, 4, 0x8,
  318. reinterpret_cast<u8*>(&data)).raw; // TODO(Subv): Find out the correct error codes
  319. cmd_buffer[2] = data & 0xFF;
  320. }
  321. /**
  322. * CFG_User::GetModelNintendo2DS service function
  323. * Outputs:
  324. * 1 : Result of function, 0 on success, otherwise error code
  325. * 2 : 0 if the system is a Nintendo 2DS, 1 otherwise
  326. */
  327. static void GetModelNintendo2DS(Service::Interface* self) {
  328. u32* cmd_buffer = Kernel::GetCommandBuffer();
  329. u32 data;
  330. cmd_buffer[1] = GetConfigInfoBlock(0x000F0004, 4, 0x8,
  331. reinterpret_cast<u8*>(&data)).raw; // TODO(Subv): Find out the correct error codes
  332. u8 model = data & 0xFF;
  333. if (model == NINTENDO_2DS)
  334. cmd_buffer[2] = 0;
  335. else
  336. cmd_buffer[2] = 1;
  337. }
  338. const Interface::FunctionInfo FunctionTable[] = {
  339. {0x00010082, GetConfigInfoBlk2, "GetConfigInfoBlk2"},
  340. {0x00020000, nullptr, "SecureInfoGetRegion"},
  341. {0x00030000, nullptr, "GenHashConsoleUnique"},
  342. {0x00040000, nullptr, "GetRegionCanadaUSA"},
  343. {0x00050000, GetSystemModel, "GetSystemModel"},
  344. {0x00060000, GetModelNintendo2DS, "GetModelNintendo2DS"},
  345. {0x00070040, nullptr, "unknown"},
  346. {0x00080080, nullptr, "unknown"},
  347. {0x00090040, GetCountryCodeString, "GetCountryCodeString"},
  348. {0x000A0040, GetCountryCodeID, "GetCountryCodeID"},
  349. };
  350. ////////////////////////////////////////////////////////////////////////////////////////////////////
  351. // Interface class
  352. Interface::Interface() {
  353. Register(FunctionTable, ARRAY_SIZE(FunctionTable));
  354. // TODO(Subv): In the future we should use the FS service to query this archive,
  355. // currently it is not possible because you can only have one open archive of the same type at any time
  356. std::string syssavedata_directory = FileUtil::GetUserPath(D_SYSSAVEDATA_IDX);
  357. cfg_system_save_data = std::make_unique<FileSys::Archive_SystemSaveData>(syssavedata_directory,
  358. CFG_SAVE_ID);
  359. if (!cfg_system_save_data->Initialize()) {
  360. LOG_CRITICAL(Service_CFG, "Could not initialize SystemSaveData archive for the CFG:U service");
  361. return;
  362. }
  363. // TODO(Subv): All this code should be moved to cfg:i,
  364. // it's only here because we do not currently emulate the lower level code that uses that service
  365. // Try to open the file in read-only mode to check its existence
  366. FileSys::Mode mode;
  367. mode.hex = 0;
  368. mode.read_flag = 1;
  369. FileSys::Path path("config");
  370. auto file = cfg_system_save_data->OpenFile(path, mode);
  371. // Load the config if it already exists
  372. if (file != nullptr) {
  373. file->Read(0, CONFIG_SAVEFILE_SIZE, cfg_config_file_buffer.data());
  374. return;
  375. }
  376. // Initialize the Username block
  377. // TODO(Subv): Do this somewhere else, or in another way
  378. CONSOLE_USERNAME_BLOCK.ng_word = 0;
  379. CONSOLE_USERNAME_BLOCK.zero = 0;
  380. std::fill(std::begin(CONSOLE_USERNAME_BLOCK.username) +
  381. Common::UTF8ToUTF16(CONSOLE_USERNAME).copy(CONSOLE_USERNAME_BLOCK.username, 0x14),
  382. std::end(CONSOLE_USERNAME_BLOCK.username), 0);
  383. FormatConfig();
  384. }
  385. Interface::~Interface() {
  386. }
  387. } // namespace