profile_manager.cpp 14 KB

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