profile_manager.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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::NewUUID;
  15. struct UserRaw {
  16. NewUUID uuid{};
  17. NewUUID uuid2{};
  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(NewUUID::MakeRandom(), "yuzu");
  38. }
  39. auto current =
  40. std::clamp<int>(static_cast<s32>(Settings::values.current_user), 0, MAX_USERS - 1);
  41. // If user index don't exist. Load the first user and change the active user
  42. if (!UserExistsIndex(current)) {
  43. current = 0;
  44. Settings::values.current_user = 0;
  45. }
  46. OpenUser(*GetUser(current));
  47. }
  48. ProfileManager::~ProfileManager() {
  49. WriteUserSaveFile();
  50. }
  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. ResultCode 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. ResultCode ProfileManager::CreateNewUser(NewUUID 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. return AddUser({
  96. .user_uuid = uuid,
  97. .username = username,
  98. .creation_time = 0,
  99. .data = {},
  100. .is_open = false,
  101. });
  102. }
  103. /// Creates a new user on the system. This function allows a much simpler method of registration
  104. /// specifically by allowing an std::string for the username. This is required specifically since
  105. /// we're loading a string straight from the config
  106. ResultCode ProfileManager::CreateNewUser(NewUUID uuid, const std::string& username) {
  107. ProfileUsername username_output{};
  108. if (username.size() > username_output.size()) {
  109. std::copy_n(username.begin(), username_output.size(), username_output.begin());
  110. } else {
  111. std::copy(username.begin(), username.end(), username_output.begin());
  112. }
  113. return CreateNewUser(uuid, username_output);
  114. }
  115. std::optional<NewUUID> ProfileManager::GetUser(std::size_t index) const {
  116. if (index >= MAX_USERS) {
  117. return std::nullopt;
  118. }
  119. return profiles[index].user_uuid;
  120. }
  121. /// Returns a users profile index based on their user id.
  122. std::optional<std::size_t> ProfileManager::GetUserIndex(const NewUUID& uuid) const {
  123. if (uuid.IsInvalid()) {
  124. return std::nullopt;
  125. }
  126. const auto iter = std::find_if(profiles.begin(), profiles.end(),
  127. [&uuid](const ProfileInfo& p) { return p.user_uuid == uuid; });
  128. if (iter == profiles.end()) {
  129. return std::nullopt;
  130. }
  131. return static_cast<std::size_t>(std::distance(profiles.begin(), iter));
  132. }
  133. /// Returns a users profile index based on their profile
  134. std::optional<std::size_t> ProfileManager::GetUserIndex(const ProfileInfo& user) const {
  135. return GetUserIndex(user.user_uuid);
  136. }
  137. /// Returns the data structure used by the switch when GetProfileBase is called on acc:*
  138. bool ProfileManager::GetProfileBase(std::optional<std::size_t> index, ProfileBase& profile) const {
  139. if (!index || index >= MAX_USERS) {
  140. return false;
  141. }
  142. const auto& prof_info = profiles[*index];
  143. profile.user_uuid = prof_info.user_uuid;
  144. profile.username = prof_info.username;
  145. profile.timestamp = prof_info.creation_time;
  146. return true;
  147. }
  148. /// Returns the data structure used by the switch when GetProfileBase is called on acc:*
  149. bool ProfileManager::GetProfileBase(NewUUID uuid, ProfileBase& profile) const {
  150. const auto idx = GetUserIndex(uuid);
  151. return GetProfileBase(idx, profile);
  152. }
  153. /// Returns the data structure used by the switch when GetProfileBase is called on acc:*
  154. bool ProfileManager::GetProfileBase(const ProfileInfo& user, ProfileBase& profile) const {
  155. return GetProfileBase(user.user_uuid, profile);
  156. }
  157. /// Returns the current user count on the system. We keep a variable which tracks the count so we
  158. /// don't have to loop the internal profile array every call.
  159. std::size_t ProfileManager::GetUserCount() const {
  160. return user_count;
  161. }
  162. /// Lists the current "opened" users on the system. Users are typically not open until they sign
  163. /// into something or pick a profile. As of right now users should all be open until qlaunch is
  164. /// booting
  165. std::size_t ProfileManager::GetOpenUserCount() const {
  166. return std::count_if(profiles.begin(), profiles.end(),
  167. [](const ProfileInfo& p) { return p.is_open; });
  168. }
  169. /// Checks if a user id exists in our profile manager
  170. bool ProfileManager::UserExists(NewUUID uuid) const {
  171. return GetUserIndex(uuid).has_value();
  172. }
  173. bool ProfileManager::UserExistsIndex(std::size_t index) const {
  174. if (index >= MAX_USERS) {
  175. return false;
  176. }
  177. return profiles[index].user_uuid.IsValid();
  178. }
  179. /// Opens a specific user
  180. void ProfileManager::OpenUser(NewUUID uuid) {
  181. const auto idx = GetUserIndex(uuid);
  182. if (!idx) {
  183. return;
  184. }
  185. profiles[*idx].is_open = true;
  186. last_opened_user = uuid;
  187. }
  188. /// Closes a specific user
  189. void ProfileManager::CloseUser(NewUUID uuid) {
  190. const auto idx = GetUserIndex(uuid);
  191. if (!idx) {
  192. return;
  193. }
  194. profiles[*idx].is_open = false;
  195. }
  196. /// Gets all valid user ids on the system
  197. UserIDArray ProfileManager::GetAllUsers() const {
  198. UserIDArray output{};
  199. std::ranges::transform(profiles, output.begin(),
  200. [](const ProfileInfo& p) { return p.user_uuid; });
  201. return output;
  202. }
  203. /// Get all the open users on the system and zero out the rest of the data. This is specifically
  204. /// needed for GetOpenUsers and we need to ensure the rest of the output buffer is zero'd out
  205. UserIDArray ProfileManager::GetOpenUsers() const {
  206. UserIDArray output{};
  207. std::ranges::transform(profiles, output.begin(), [](const ProfileInfo& p) {
  208. if (p.is_open)
  209. return p.user_uuid;
  210. return Common::InvalidUUID;
  211. });
  212. std::stable_partition(output.begin(), output.end(),
  213. [](const NewUUID& uuid) { return uuid.IsValid(); });
  214. return output;
  215. }
  216. /// Returns the last user which was opened
  217. NewUUID ProfileManager::GetLastOpenedUser() const {
  218. return last_opened_user;
  219. }
  220. /// Return the users profile base and the unknown arbitary data.
  221. bool ProfileManager::GetProfileBaseAndData(std::optional<std::size_t> index, ProfileBase& profile,
  222. ProfileData& data) const {
  223. if (GetProfileBase(index, profile)) {
  224. data = profiles[*index].data;
  225. return true;
  226. }
  227. return false;
  228. }
  229. /// Return the users profile base and the unknown arbitary data.
  230. bool ProfileManager::GetProfileBaseAndData(NewUUID uuid, ProfileBase& profile,
  231. ProfileData& data) const {
  232. const auto idx = GetUserIndex(uuid);
  233. return GetProfileBaseAndData(idx, profile, data);
  234. }
  235. /// Return the users profile base and the unknown arbitary data.
  236. bool ProfileManager::GetProfileBaseAndData(const ProfileInfo& user, ProfileBase& profile,
  237. ProfileData& data) const {
  238. return GetProfileBaseAndData(user.user_uuid, profile, data);
  239. }
  240. /// Returns if the system is allowing user registrations or not
  241. bool ProfileManager::CanSystemRegisterUser() const {
  242. return false; // TODO(ogniK): Games shouldn't have
  243. // access to user registration, when we
  244. // emulate qlaunch. Update this to dynamically change.
  245. }
  246. bool ProfileManager::RemoveUser(NewUUID uuid) {
  247. const auto index = GetUserIndex(uuid);
  248. if (!index) {
  249. return false;
  250. }
  251. profiles[*index] = ProfileInfo{};
  252. std::stable_partition(profiles.begin(), profiles.end(),
  253. [](const ProfileInfo& profile) { return profile.user_uuid.IsValid(); });
  254. return true;
  255. }
  256. bool ProfileManager::SetProfileBase(NewUUID uuid, const ProfileBase& profile_new) {
  257. const auto index = GetUserIndex(uuid);
  258. if (!index || profile_new.user_uuid.IsInvalid()) {
  259. return false;
  260. }
  261. auto& profile = profiles[*index];
  262. profile.user_uuid = profile_new.user_uuid;
  263. profile.username = profile_new.username;
  264. profile.creation_time = profile_new.timestamp;
  265. return true;
  266. }
  267. bool ProfileManager::SetProfileBaseAndData(Common::NewUUID uuid, const ProfileBase& profile_new,
  268. const ProfileData& data_new) {
  269. const auto index = GetUserIndex(uuid);
  270. if (index.has_value() && SetProfileBase(uuid, profile_new)) {
  271. profiles[*index].data = data_new;
  272. return true;
  273. }
  274. return false;
  275. }
  276. void ProfileManager::ParseUserSaveFile() {
  277. const auto save_path(FS::GetYuzuPath(FS::YuzuPath::NANDDir) / ACC_SAVE_AVATORS_BASE_PATH /
  278. "profiles.dat");
  279. const FS::IOFile save(save_path, FS::FileAccessMode::Read, FS::FileType::BinaryFile);
  280. if (!save.IsOpen()) {
  281. LOG_WARNING(Service_ACC, "Failed to load profile data from save data... Generating new "
  282. "user 'yuzu' with random NewUUID.");
  283. return;
  284. }
  285. ProfileDataRaw data;
  286. if (!save.ReadObject(data)) {
  287. LOG_WARNING(Service_ACC, "profiles.dat is smaller than expected... Generating new user "
  288. "'yuzu' with random NewUUID.");
  289. return;
  290. }
  291. for (const auto& user : data.users) {
  292. if (user.uuid.IsInvalid()) {
  293. continue;
  294. }
  295. AddUser({
  296. .user_uuid = user.uuid,
  297. .username = user.username,
  298. .creation_time = user.timestamp,
  299. .data = user.extra_data,
  300. .is_open = false,
  301. });
  302. }
  303. std::stable_partition(profiles.begin(), profiles.end(),
  304. [](const ProfileInfo& profile) { return profile.user_uuid.IsValid(); });
  305. }
  306. void ProfileManager::WriteUserSaveFile() {
  307. ProfileDataRaw raw{};
  308. for (std::size_t i = 0; i < MAX_USERS; ++i) {
  309. raw.users[i] = {
  310. .uuid = profiles[i].user_uuid,
  311. .uuid2 = profiles[i].user_uuid,
  312. .timestamp = profiles[i].creation_time,
  313. .username = profiles[i].username,
  314. .extra_data = profiles[i].data,
  315. };
  316. }
  317. const auto raw_path(FS::GetYuzuPath(FS::YuzuPath::NANDDir) / "system/save/8000000000000010");
  318. if (FS::IsFile(raw_path) && !FS::RemoveFile(raw_path)) {
  319. return;
  320. }
  321. const auto save_path(FS::GetYuzuPath(FS::YuzuPath::NANDDir) / ACC_SAVE_AVATORS_BASE_PATH /
  322. "profiles.dat");
  323. if (!FS::CreateParentDirs(save_path)) {
  324. LOG_WARNING(Service_ACC, "Failed to create full path of profiles.dat. Create the directory "
  325. "nand/system/save/8000000000000010/su/avators to mitigate this "
  326. "issue.");
  327. return;
  328. }
  329. FS::IOFile save(save_path, FS::FileAccessMode::Write, FS::FileType::BinaryFile);
  330. if (!save.IsOpen() || !save.SetSize(sizeof(ProfileDataRaw)) || !save.WriteObject(raw)) {
  331. LOG_WARNING(Service_ACC, "Failed to write save data to file... No changes to user data "
  332. "made in current session will be saved.");
  333. }
  334. }
  335. }; // namespace Service::Account