profile_manager.cpp 12 KB

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