profile_manager.cpp 15 KB

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