profile_manager.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <cstring>
  5. #include <random>
  6. #include <fmt/format.h>
  7. #include "common/file_util.h"
  8. #include "core/hle/service/acc/profile_manager.h"
  9. #include "core/settings.h"
  10. namespace Service::Account {
  11. namespace FS = Common::FS;
  12. using Common::UUID;
  13. struct UserRaw {
  14. UUID uuid{Common::INVALID_UUID};
  15. UUID uuid2{Common::INVALID_UUID};
  16. u64 timestamp{};
  17. ProfileUsername username{};
  18. ProfileData extra_data{};
  19. };
  20. static_assert(sizeof(UserRaw) == 0xC8, "UserRaw has incorrect size.");
  21. struct ProfileDataRaw {
  22. INSERT_PADDING_BYTES(0x10);
  23. std::array<UserRaw, MAX_USERS> users{};
  24. };
  25. static_assert(sizeof(ProfileDataRaw) == 0x650, "ProfileDataRaw has incorrect size.");
  26. // TODO(ogniK): Get actual error codes
  27. constexpr ResultCode ERROR_TOO_MANY_USERS(ErrorModule::Account, u32(-1));
  28. constexpr ResultCode ERROR_USER_ALREADY_EXISTS(ErrorModule::Account, u32(-2));
  29. constexpr ResultCode ERROR_ARGUMENT_IS_NULL(ErrorModule::Account, 20);
  30. constexpr char ACC_SAVE_AVATORS_BASE_PATH[] = "/system/save/8000000000000010/su/avators/";
  31. ProfileManager::ProfileManager() {
  32. ParseUserSaveFile();
  33. // Create an user if none are present
  34. if (user_count == 0) {
  35. CreateNewUser(UUID::Generate(), "yuzu");
  36. }
  37. auto current = std::clamp<int>(Settings::values.current_user, 0, MAX_USERS - 1);
  38. // If user index don't exist. Load the first user and change the active user
  39. if (!UserExistsIndex(current)) {
  40. current = 0;
  41. Settings::values.current_user = 0;
  42. }
  43. OpenUser(*GetUser(current));
  44. }
  45. ProfileManager::~ProfileManager() {
  46. WriteUserSaveFile();
  47. }
  48. /// After a users creation it needs to be "registered" to the system. AddToProfiles handles the
  49. /// internal management of the users profiles
  50. std::optional<std::size_t> ProfileManager::AddToProfiles(const ProfileInfo& profile) {
  51. if (user_count >= MAX_USERS) {
  52. return std::nullopt;
  53. }
  54. profiles[user_count] = profile;
  55. return user_count++;
  56. }
  57. /// Deletes a specific profile based on it's profile index
  58. bool ProfileManager::RemoveProfileAtIndex(std::size_t index) {
  59. if (index >= MAX_USERS || index >= user_count) {
  60. return false;
  61. }
  62. if (index < user_count - 1) {
  63. std::rotate(profiles.begin() + index, profiles.begin() + index + 1, profiles.end());
  64. }
  65. profiles.back() = {};
  66. user_count--;
  67. return true;
  68. }
  69. /// Helper function to register a user to the system
  70. ResultCode ProfileManager::AddUser(const ProfileInfo& user) {
  71. if (!AddToProfiles(user)) {
  72. return ERROR_TOO_MANY_USERS;
  73. }
  74. return RESULT_SUCCESS;
  75. }
  76. /// Create a new user on the system. If the uuid of the user already exists, the user is not
  77. /// created.
  78. ResultCode ProfileManager::CreateNewUser(UUID uuid, const ProfileUsername& username) {
  79. if (user_count == MAX_USERS) {
  80. return ERROR_TOO_MANY_USERS;
  81. }
  82. if (!uuid) {
  83. return ERROR_ARGUMENT_IS_NULL;
  84. }
  85. if (username[0] == 0x0) {
  86. return ERROR_ARGUMENT_IS_NULL;
  87. }
  88. if (std::any_of(profiles.begin(), profiles.end(),
  89. [&uuid](const ProfileInfo& profile) { return uuid == profile.user_uuid; })) {
  90. return ERROR_USER_ALREADY_EXISTS;
  91. }
  92. return AddUser({
  93. .user_uuid = uuid,
  94. .username = username,
  95. .creation_time = 0,
  96. .data = {},
  97. .is_open = false,
  98. });
  99. }
  100. /// Creates a new user on the system. This function allows a much simpler method of registration
  101. /// specifically by allowing an std::string for the username. This is required specifically since
  102. /// we're loading a string straight from the config
  103. ResultCode ProfileManager::CreateNewUser(UUID uuid, const std::string& username) {
  104. ProfileUsername username_output{};
  105. if (username.size() > username_output.size()) {
  106. std::copy_n(username.begin(), username_output.size(), username_output.begin());
  107. } else {
  108. std::copy(username.begin(), username.end(), username_output.begin());
  109. }
  110. return CreateNewUser(uuid, username_output);
  111. }
  112. std::optional<UUID> ProfileManager::GetUser(std::size_t index) const {
  113. if (index >= MAX_USERS) {
  114. return std::nullopt;
  115. }
  116. return profiles[index].user_uuid;
  117. }
  118. /// Returns a users profile index based on their user id.
  119. std::optional<std::size_t> ProfileManager::GetUserIndex(const UUID& uuid) const {
  120. if (!uuid) {
  121. return std::nullopt;
  122. }
  123. const auto iter = std::find_if(profiles.begin(), profiles.end(),
  124. [&uuid](const ProfileInfo& p) { return p.user_uuid == uuid; });
  125. if (iter == profiles.end()) {
  126. return std::nullopt;
  127. }
  128. return static_cast<std::size_t>(std::distance(profiles.begin(), iter));
  129. }
  130. /// Returns a users profile index based on their profile
  131. std::optional<std::size_t> ProfileManager::GetUserIndex(const ProfileInfo& user) const {
  132. return GetUserIndex(user.user_uuid);
  133. }
  134. /// Returns the data structure used by the switch when GetProfileBase is called on acc:*
  135. bool ProfileManager::GetProfileBase(std::optional<std::size_t> index, ProfileBase& profile) const {
  136. if (!index || index >= MAX_USERS) {
  137. return false;
  138. }
  139. const auto& prof_info = profiles[*index];
  140. profile.user_uuid = prof_info.user_uuid;
  141. profile.username = prof_info.username;
  142. profile.timestamp = prof_info.creation_time;
  143. return true;
  144. }
  145. /// Returns the data structure used by the switch when GetProfileBase is called on acc:*
  146. bool ProfileManager::GetProfileBase(UUID uuid, ProfileBase& profile) const {
  147. const auto idx = GetUserIndex(uuid);
  148. return GetProfileBase(idx, profile);
  149. }
  150. /// Returns the data structure used by the switch when GetProfileBase is called on acc:*
  151. bool ProfileManager::GetProfileBase(const ProfileInfo& user, ProfileBase& profile) const {
  152. return GetProfileBase(user.user_uuid, profile);
  153. }
  154. /// Returns the current user count on the system. We keep a variable which tracks the count so we
  155. /// don't have to loop the internal profile array every call.
  156. std::size_t ProfileManager::GetUserCount() const {
  157. return user_count;
  158. }
  159. /// Lists the current "opened" users on the system. Users are typically not open until they sign
  160. /// into something or pick a profile. As of right now users should all be open until qlaunch is
  161. /// booting
  162. std::size_t ProfileManager::GetOpenUserCount() const {
  163. return std::count_if(profiles.begin(), profiles.end(),
  164. [](const ProfileInfo& p) { return p.is_open; });
  165. }
  166. /// Checks if a user id exists in our profile manager
  167. bool ProfileManager::UserExists(UUID uuid) const {
  168. return GetUserIndex(uuid).has_value();
  169. }
  170. bool ProfileManager::UserExistsIndex(std::size_t index) const {
  171. if (index >= MAX_USERS)
  172. return false;
  173. return profiles[index].user_uuid.uuid != Common::INVALID_UUID;
  174. }
  175. /// Opens a specific user
  176. void ProfileManager::OpenUser(UUID uuid) {
  177. const auto idx = GetUserIndex(uuid);
  178. if (!idx) {
  179. return;
  180. }
  181. profiles[*idx].is_open = true;
  182. last_opened_user = uuid;
  183. }
  184. /// Closes a specific user
  185. void ProfileManager::CloseUser(UUID uuid) {
  186. const auto idx = GetUserIndex(uuid);
  187. if (!idx) {
  188. return;
  189. }
  190. profiles[*idx].is_open = false;
  191. }
  192. /// Gets all valid user ids on the system
  193. UserIDArray ProfileManager::GetAllUsers() const {
  194. UserIDArray output{};
  195. std::ranges::transform(profiles, output.begin(),
  196. [](const ProfileInfo& p) { return p.user_uuid; });
  197. return output;
  198. }
  199. /// Get all the open users on the system and zero out the rest of the data. This is specifically
  200. /// needed for GetOpenUsers and we need to ensure the rest of the output buffer is zero'd out
  201. UserIDArray ProfileManager::GetOpenUsers() const {
  202. UserIDArray output{};
  203. std::ranges::transform(profiles, output.begin(), [](const ProfileInfo& p) {
  204. if (p.is_open)
  205. return p.user_uuid;
  206. return UUID{Common::INVALID_UUID};
  207. });
  208. std::stable_partition(output.begin(), output.end(), [](const UUID& uuid) { return uuid; });
  209. return output;
  210. }
  211. /// Returns the last user which was opened
  212. UUID ProfileManager::GetLastOpenedUser() const {
  213. return last_opened_user;
  214. }
  215. /// Return the users profile base and the unknown arbitary data.
  216. bool ProfileManager::GetProfileBaseAndData(std::optional<std::size_t> index, ProfileBase& profile,
  217. ProfileData& data) const {
  218. if (GetProfileBase(index, profile)) {
  219. data = profiles[*index].data;
  220. return true;
  221. }
  222. return false;
  223. }
  224. /// Return the users profile base and the unknown arbitary data.
  225. bool ProfileManager::GetProfileBaseAndData(UUID uuid, ProfileBase& profile,
  226. ProfileData& data) const {
  227. const auto idx = GetUserIndex(uuid);
  228. return GetProfileBaseAndData(idx, profile, data);
  229. }
  230. /// Return the users profile base and the unknown arbitary data.
  231. bool ProfileManager::GetProfileBaseAndData(const ProfileInfo& user, ProfileBase& profile,
  232. ProfileData& data) const {
  233. return GetProfileBaseAndData(user.user_uuid, profile, data);
  234. }
  235. /// Returns if the system is allowing user registrations or not
  236. bool ProfileManager::CanSystemRegisterUser() const {
  237. return false; // TODO(ogniK): Games shouldn't have
  238. // access to user registration, when we
  239. // emulate qlaunch. Update this to dynamically change.
  240. }
  241. bool ProfileManager::RemoveUser(UUID uuid) {
  242. const auto index = GetUserIndex(uuid);
  243. if (!index) {
  244. return false;
  245. }
  246. profiles[*index] = ProfileInfo{};
  247. std::stable_partition(profiles.begin(), profiles.end(),
  248. [](const ProfileInfo& profile) { return profile.user_uuid; });
  249. return true;
  250. }
  251. bool ProfileManager::SetProfileBase(UUID uuid, const ProfileBase& profile_new) {
  252. const auto index = GetUserIndex(uuid);
  253. if (!index || profile_new.user_uuid == UUID(Common::INVALID_UUID)) {
  254. return false;
  255. }
  256. auto& profile = profiles[*index];
  257. profile.user_uuid = profile_new.user_uuid;
  258. profile.username = profile_new.username;
  259. profile.creation_time = profile_new.timestamp;
  260. return true;
  261. }
  262. bool ProfileManager::SetProfileBaseAndData(Common::UUID uuid, const ProfileBase& profile_new,
  263. const ProfileData& data_new) {
  264. const auto index = GetUserIndex(uuid);
  265. if (index.has_value() && SetProfileBase(uuid, profile_new)) {
  266. profiles[*index].data = data_new;
  267. return true;
  268. }
  269. return false;
  270. }
  271. void ProfileManager::ParseUserSaveFile() {
  272. const FS::IOFile save(
  273. FS::GetUserPath(FS::UserPath::NANDDir) + ACC_SAVE_AVATORS_BASE_PATH + "profiles.dat", "rb");
  274. if (!save.IsOpen()) {
  275. LOG_WARNING(Service_ACC, "Failed to load profile data from save data... Generating new "
  276. "user 'yuzu' with random UUID.");
  277. return;
  278. }
  279. ProfileDataRaw data;
  280. if (save.ReadBytes(&data, sizeof(ProfileDataRaw)) != sizeof(ProfileDataRaw)) {
  281. LOG_WARNING(Service_ACC, "profiles.dat is smaller than expected... Generating new user "
  282. "'yuzu' with random UUID.");
  283. return;
  284. }
  285. for (const auto& user : data.users) {
  286. if (user.uuid == UUID(Common::INVALID_UUID)) {
  287. continue;
  288. }
  289. AddUser({
  290. .user_uuid = user.uuid,
  291. .username = user.username,
  292. .creation_time = user.timestamp,
  293. .data = user.extra_data,
  294. .is_open = false,
  295. });
  296. }
  297. std::stable_partition(profiles.begin(), profiles.end(),
  298. [](const ProfileInfo& profile) { return profile.user_uuid; });
  299. }
  300. void ProfileManager::WriteUserSaveFile() {
  301. ProfileDataRaw raw{};
  302. for (std::size_t i = 0; i < MAX_USERS; ++i) {
  303. raw.users[i] = {
  304. .uuid = profiles[i].user_uuid,
  305. .uuid2 = profiles[i].user_uuid,
  306. .timestamp = profiles[i].creation_time,
  307. .username = profiles[i].username,
  308. .extra_data = profiles[i].data,
  309. };
  310. }
  311. const auto raw_path = FS::GetUserPath(FS::UserPath::NANDDir) + "/system/save/8000000000000010";
  312. if (FS::Exists(raw_path) && !FS::IsDirectory(raw_path)) {
  313. FS::Delete(raw_path);
  314. }
  315. const auto path =
  316. FS::GetUserPath(FS::UserPath::NANDDir) + ACC_SAVE_AVATORS_BASE_PATH + "profiles.dat";
  317. if (!FS::CreateFullPath(path)) {
  318. LOG_WARNING(Service_ACC, "Failed to create full path of profiles.dat. Create the directory "
  319. "nand/system/save/8000000000000010/su/avators to mitigate this "
  320. "issue.");
  321. return;
  322. }
  323. FS::IOFile save(path, "wb");
  324. if (!save.IsOpen()) {
  325. LOG_WARNING(Service_ACC, "Failed to write save data to file... No changes to user data "
  326. "made in current session will be saved.");
  327. return;
  328. }
  329. save.Resize(sizeof(ProfileDataRaw));
  330. save.WriteBytes(&raw, sizeof(ProfileDataRaw));
  331. }
  332. }; // namespace Service::Account