profile_manager.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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/fs/file.h"
  8. #include "common/fs/fs.h"
  9. #include "common/fs/path_util.h"
  10. #include "common/settings.h"
  11. #include "core/hle/service/acc/profile_manager.h"
  12. namespace Service::Account {
  13. namespace FS = Common::FS;
  14. using Common::UUID;
  15. struct UserRaw {
  16. UUID uuid{Common::INVALID_UUID};
  17. UUID uuid2{Common::INVALID_UUID};
  18. u64 timestamp{};
  19. ProfileUsername username{};
  20. ProfileData extra_data{};
  21. };
  22. static_assert(sizeof(UserRaw) == 0xC8, "UserRaw has incorrect size.");
  23. struct ProfileDataRaw {
  24. INSERT_PADDING_BYTES(0x10);
  25. std::array<UserRaw, MAX_USERS> users{};
  26. };
  27. static_assert(sizeof(ProfileDataRaw) == 0x650, "ProfileDataRaw has incorrect size.");
  28. // TODO(ogniK): Get actual error codes
  29. constexpr ResultCode ERROR_TOO_MANY_USERS(ErrorModule::Account, u32(-1));
  30. constexpr ResultCode ERROR_USER_ALREADY_EXISTS(ErrorModule::Account, u32(-2));
  31. constexpr ResultCode ERROR_ARGUMENT_IS_NULL(ErrorModule::Account, 20);
  32. constexpr char ACC_SAVE_AVATORS_BASE_PATH[] = "system/save/8000000000000010/su/avators";
  33. ProfileManager::ProfileManager() {
  34. ParseUserSaveFile();
  35. // Create an user if none are present
  36. if (user_count == 0) {
  37. CreateNewUser(UUID::Generate(), "yuzu");
  38. }
  39. auto current = std::clamp<int>(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. ResultCode 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. ResultCode ProfileManager::CreateNewUser(UUID uuid, const ProfileUsername& username) {
  81. if (user_count == MAX_USERS) {
  82. return ERROR_TOO_MANY_USERS;
  83. }
  84. if (!uuid) {
  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. ResultCode 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) {
  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. return profiles[index].user_uuid.uuid != Common::INVALID_UUID;
  176. }
  177. /// Opens a specific user
  178. void ProfileManager::OpenUser(UUID uuid) {
  179. const auto idx = GetUserIndex(uuid);
  180. if (!idx) {
  181. return;
  182. }
  183. profiles[*idx].is_open = true;
  184. last_opened_user = uuid;
  185. }
  186. /// Closes a specific user
  187. void ProfileManager::CloseUser(UUID uuid) {
  188. const auto idx = GetUserIndex(uuid);
  189. if (!idx) {
  190. return;
  191. }
  192. profiles[*idx].is_open = false;
  193. }
  194. /// Gets all valid user ids on the system
  195. UserIDArray ProfileManager::GetAllUsers() const {
  196. UserIDArray output{};
  197. std::ranges::transform(profiles, output.begin(),
  198. [](const ProfileInfo& p) { return p.user_uuid; });
  199. return output;
  200. }
  201. /// Get all the open users on the system and zero out the rest of the data. This is specifically
  202. /// needed for GetOpenUsers and we need to ensure the rest of the output buffer is zero'd out
  203. UserIDArray ProfileManager::GetOpenUsers() const {
  204. UserIDArray output{};
  205. std::ranges::transform(profiles, output.begin(), [](const ProfileInfo& p) {
  206. if (p.is_open)
  207. return p.user_uuid;
  208. return UUID{Common::INVALID_UUID};
  209. });
  210. std::stable_partition(output.begin(), output.end(), [](const UUID& uuid) { return uuid; });
  211. return output;
  212. }
  213. /// Returns the last user which was opened
  214. UUID ProfileManager::GetLastOpenedUser() const {
  215. return last_opened_user;
  216. }
  217. /// Return the users profile base and the unknown arbitary data.
  218. bool ProfileManager::GetProfileBaseAndData(std::optional<std::size_t> index, ProfileBase& profile,
  219. ProfileData& data) const {
  220. if (GetProfileBase(index, profile)) {
  221. data = profiles[*index].data;
  222. return true;
  223. }
  224. return false;
  225. }
  226. /// Return the users profile base and the unknown arbitary data.
  227. bool ProfileManager::GetProfileBaseAndData(UUID uuid, ProfileBase& profile,
  228. ProfileData& data) const {
  229. const auto idx = GetUserIndex(uuid);
  230. return GetProfileBaseAndData(idx, profile, data);
  231. }
  232. /// Return the users profile base and the unknown arbitary data.
  233. bool ProfileManager::GetProfileBaseAndData(const ProfileInfo& user, ProfileBase& profile,
  234. ProfileData& data) const {
  235. return GetProfileBaseAndData(user.user_uuid, profile, data);
  236. }
  237. /// Returns if the system is allowing user registrations or not
  238. bool ProfileManager::CanSystemRegisterUser() const {
  239. return false; // TODO(ogniK): Games shouldn't have
  240. // access to user registration, when we
  241. // emulate qlaunch. Update this to dynamically change.
  242. }
  243. bool ProfileManager::RemoveUser(UUID uuid) {
  244. const auto index = GetUserIndex(uuid);
  245. if (!index) {
  246. return false;
  247. }
  248. profiles[*index] = ProfileInfo{};
  249. std::stable_partition(profiles.begin(), profiles.end(),
  250. [](const ProfileInfo& profile) { return profile.user_uuid; });
  251. return true;
  252. }
  253. bool ProfileManager::SetProfileBase(UUID uuid, const ProfileBase& profile_new) {
  254. const auto index = GetUserIndex(uuid);
  255. if (!index || profile_new.user_uuid == UUID(Common::INVALID_UUID)) {
  256. return false;
  257. }
  258. auto& profile = profiles[*index];
  259. profile.user_uuid = profile_new.user_uuid;
  260. profile.username = profile_new.username;
  261. profile.creation_time = profile_new.timestamp;
  262. return true;
  263. }
  264. bool ProfileManager::SetProfileBaseAndData(Common::UUID uuid, const ProfileBase& profile_new,
  265. const ProfileData& data_new) {
  266. const auto index = GetUserIndex(uuid);
  267. if (index.has_value() && SetProfileBase(uuid, profile_new)) {
  268. profiles[*index].data = data_new;
  269. return true;
  270. }
  271. return false;
  272. }
  273. void ProfileManager::ParseUserSaveFile() {
  274. const auto save_path(FS::GetYuzuPath(FS::YuzuPath::NANDDir) / ACC_SAVE_AVATORS_BASE_PATH /
  275. "profiles.dat");
  276. const FS::IOFile save(save_path, FS::FileAccessMode::Read, FS::FileType::BinaryFile);
  277. if (!save.IsOpen()) {
  278. LOG_WARNING(Service_ACC, "Failed to load profile data from save data... Generating new "
  279. "user 'yuzu' with random UUID.");
  280. return;
  281. }
  282. ProfileDataRaw data;
  283. if (!save.ReadObject(data)) {
  284. LOG_WARNING(Service_ACC, "profiles.dat is smaller than expected... Generating new user "
  285. "'yuzu' with random UUID.");
  286. return;
  287. }
  288. for (const auto& user : data.users) {
  289. if (user.uuid == UUID(Common::INVALID_UUID)) {
  290. continue;
  291. }
  292. AddUser({
  293. .user_uuid = user.uuid,
  294. .username = user.username,
  295. .creation_time = user.timestamp,
  296. .data = user.extra_data,
  297. .is_open = false,
  298. });
  299. }
  300. std::stable_partition(profiles.begin(), profiles.end(),
  301. [](const ProfileInfo& profile) { return profile.user_uuid; });
  302. }
  303. void ProfileManager::WriteUserSaveFile() {
  304. ProfileDataRaw raw{};
  305. for (std::size_t i = 0; i < MAX_USERS; ++i) {
  306. raw.users[i] = {
  307. .uuid = profiles[i].user_uuid,
  308. .uuid2 = profiles[i].user_uuid,
  309. .timestamp = profiles[i].creation_time,
  310. .username = profiles[i].username,
  311. .extra_data = profiles[i].data,
  312. };
  313. }
  314. const auto raw_path(FS::GetYuzuPath(FS::YuzuPath::NANDDir) / "system/save/8000000000000010");
  315. if (FS::IsFile(raw_path) && !FS::RemoveFile(raw_path)) {
  316. return;
  317. }
  318. const auto save_path(FS::GetYuzuPath(FS::YuzuPath::NANDDir) / ACC_SAVE_AVATORS_BASE_PATH /
  319. "profiles.dat");
  320. if (!FS::CreateParentDirs(save_path)) {
  321. LOG_WARNING(Service_ACC, "Failed to create full path of profiles.dat. Create the directory "
  322. "nand/system/save/8000000000000010/su/avators to mitigate this "
  323. "issue.");
  324. return;
  325. }
  326. FS::IOFile save(save_path, FS::FileAccessMode::Write, FS::FileType::BinaryFile);
  327. if (!save.IsOpen() || !save.SetSize(sizeof(ProfileDataRaw)) || !save.WriteObject(raw)) {
  328. LOG_WARNING(Service_ACC, "Failed to write save data to file... No changes to user data "
  329. "made in current session will be saved.");
  330. }
  331. }
  332. }; // namespace Service::Account