VirtualFileSystem.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. using LibHac;
  2. using LibHac.Common;
  3. using LibHac.Common.Keys;
  4. using LibHac.Fs;
  5. using LibHac.Fs.Fsa;
  6. using LibHac.Fs.Shim;
  7. using LibHac.FsSrv;
  8. using LibHac.FsSystem;
  9. using LibHac.Ncm;
  10. using LibHac.Spl;
  11. using LibHac.Tools.Es;
  12. using LibHac.Tools.Fs;
  13. using LibHac.Tools.FsSystem;
  14. using Ryujinx.Common.Configuration;
  15. using Ryujinx.Common.Logging;
  16. using Ryujinx.HLE.HOS;
  17. using System;
  18. using System.Buffers.Text;
  19. using System.Collections.Generic;
  20. using System.IO;
  21. using System.Runtime.CompilerServices;
  22. using Path = System.IO.Path;
  23. using RightsId = LibHac.Fs.RightsId;
  24. namespace Ryujinx.HLE.FileSystem
  25. {
  26. public class VirtualFileSystem : IDisposable
  27. {
  28. public static string SafeNandPath = Path.Combine(AppDataManager.DefaultNandDir, "safe");
  29. public static string SystemNandPath = Path.Combine(AppDataManager.DefaultNandDir, "system");
  30. public static string UserNandPath = Path.Combine(AppDataManager.DefaultNandDir, "user");
  31. public KeySet KeySet { get; private set; }
  32. public EmulatedGameCard GameCard { get; private set; }
  33. public EmulatedSdCard SdCard { get; private set; }
  34. public ModLoader ModLoader { get; private set; }
  35. public Stream RomFs { get; private set; }
  36. private static bool _isInitialized = false;
  37. public static VirtualFileSystem CreateInstance()
  38. {
  39. if (_isInitialized)
  40. {
  41. throw new InvalidOperationException("VirtualFileSystem can only be instantiated once!");
  42. }
  43. _isInitialized = true;
  44. return new VirtualFileSystem();
  45. }
  46. private VirtualFileSystem()
  47. {
  48. ReloadKeySet();
  49. ModLoader = new ModLoader(); // Should only be created once
  50. }
  51. public void LoadRomFs(string fileName)
  52. {
  53. RomFs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  54. }
  55. public void SetRomFs(Stream romfsStream)
  56. {
  57. RomFs?.Close();
  58. RomFs = romfsStream;
  59. }
  60. public string GetFullPath(string basePath, string fileName)
  61. {
  62. if (fileName.StartsWith("//"))
  63. {
  64. fileName = fileName.Substring(2);
  65. }
  66. else if (fileName.StartsWith('/'))
  67. {
  68. fileName = fileName.Substring(1);
  69. }
  70. else
  71. {
  72. return null;
  73. }
  74. string fullPath = Path.GetFullPath(Path.Combine(basePath, fileName));
  75. if (!fullPath.StartsWith(AppDataManager.BaseDirPath))
  76. {
  77. return null;
  78. }
  79. return fullPath;
  80. }
  81. internal string GetSdCardPath() => MakeFullPath(AppDataManager.DefaultSdcardDir);
  82. public string GetNandPath() => MakeFullPath(AppDataManager.DefaultNandDir);
  83. public string SwitchPathToSystemPath(string switchPath)
  84. {
  85. string[] parts = switchPath.Split(":");
  86. if (parts.Length != 2)
  87. {
  88. return null;
  89. }
  90. return GetFullPath(MakeFullPath(parts[0]), parts[1]);
  91. }
  92. public string SystemPathToSwitchPath(string systemPath)
  93. {
  94. string baseSystemPath = AppDataManager.BaseDirPath + Path.DirectorySeparatorChar;
  95. if (systemPath.StartsWith(baseSystemPath))
  96. {
  97. string rawPath = systemPath.Replace(baseSystemPath, "");
  98. int firstSeparatorOffset = rawPath.IndexOf(Path.DirectorySeparatorChar);
  99. if (firstSeparatorOffset == -1)
  100. {
  101. return $"{rawPath}:/";
  102. }
  103. string basePath = rawPath.Substring(0, firstSeparatorOffset);
  104. string fileName = rawPath.Substring(firstSeparatorOffset + 1);
  105. return $"{basePath}:/{fileName}";
  106. }
  107. return null;
  108. }
  109. private string MakeFullPath(string path, bool isDirectory = true)
  110. {
  111. // Handles Common Switch Content Paths
  112. switch (path)
  113. {
  114. case ContentPath.SdCard:
  115. path = AppDataManager.DefaultSdcardDir;
  116. break;
  117. case ContentPath.User:
  118. path = UserNandPath;
  119. break;
  120. case ContentPath.System:
  121. path = SystemNandPath;
  122. break;
  123. case ContentPath.SdCardContent:
  124. path = Path.Combine(AppDataManager.DefaultSdcardDir, "Nintendo", "Contents");
  125. break;
  126. case ContentPath.UserContent:
  127. path = Path.Combine(UserNandPath, "Contents");
  128. break;
  129. case ContentPath.SystemContent:
  130. path = Path.Combine(SystemNandPath, "Contents");
  131. break;
  132. }
  133. string fullPath = Path.Combine(AppDataManager.BaseDirPath, path);
  134. if (isDirectory && !Directory.Exists(fullPath))
  135. {
  136. Directory.CreateDirectory(fullPath);
  137. }
  138. return fullPath;
  139. }
  140. public void InitializeFsServer(LibHac.Horizon horizon, out HorizonClient fsServerClient)
  141. {
  142. LocalFileSystem serverBaseFs = new LocalFileSystem(AppDataManager.BaseDirPath);
  143. fsServerClient = horizon.CreatePrivilegedHorizonClient();
  144. var fsServer = new FileSystemServer(fsServerClient);
  145. RandomDataGenerator randomGenerator = buffer => Random.Shared.NextBytes(buffer);
  146. DefaultFsServerObjects fsServerObjects = DefaultFsServerObjects.GetDefaultEmulatedCreators(serverBaseFs, KeySet, fsServer, randomGenerator);
  147. // Use our own encrypted fs creator that doesn't actually do any encryption
  148. fsServerObjects.FsCreators.EncryptedFileSystemCreator = new EncryptedFileSystemCreator();
  149. GameCard = fsServerObjects.GameCard;
  150. SdCard = fsServerObjects.SdCard;
  151. SdCard.SetSdCardInsertionStatus(true);
  152. var fsServerConfig = new FileSystemServerConfig
  153. {
  154. DeviceOperator = fsServerObjects.DeviceOperator,
  155. ExternalKeySet = KeySet.ExternalKeySet,
  156. FsCreators = fsServerObjects.FsCreators,
  157. RandomGenerator = randomGenerator
  158. };
  159. FileSystemServerInitializer.InitializeWithConfig(fsServerClient, fsServer, fsServerConfig);
  160. }
  161. public void ReloadKeySet()
  162. {
  163. KeySet ??= KeySet.CreateDefaultKeySet();
  164. string keyFile = null;
  165. string titleKeyFile = null;
  166. string consoleKeyFile = null;
  167. if (AppDataManager.Mode == AppDataManager.LaunchMode.UserProfile)
  168. {
  169. LoadSetAtPath(AppDataManager.KeysDirPathUser);
  170. }
  171. LoadSetAtPath(AppDataManager.KeysDirPath);
  172. void LoadSetAtPath(string basePath)
  173. {
  174. string localKeyFile = Path.Combine(basePath, "prod.keys");
  175. string localTitleKeyFile = Path.Combine(basePath, "title.keys");
  176. string localConsoleKeyFile = Path.Combine(basePath, "console.keys");
  177. if (File.Exists(localKeyFile))
  178. {
  179. keyFile = localKeyFile;
  180. }
  181. if (File.Exists(localTitleKeyFile))
  182. {
  183. titleKeyFile = localTitleKeyFile;
  184. }
  185. if (File.Exists(localConsoleKeyFile))
  186. {
  187. consoleKeyFile = localConsoleKeyFile;
  188. }
  189. }
  190. ExternalKeyReader.ReadKeyFile(KeySet, keyFile, titleKeyFile, consoleKeyFile, null);
  191. }
  192. public void ImportTickets(IFileSystem fs)
  193. {
  194. foreach (DirectoryEntryEx ticketEntry in fs.EnumerateEntries("/", "*.tik"))
  195. {
  196. using var ticketFile = new UniqueRef<IFile>();
  197. Result result = fs.OpenFile(ref ticketFile.Ref(), ticketEntry.FullPath.ToU8Span(), OpenMode.Read);
  198. if (result.IsSuccess())
  199. {
  200. Ticket ticket = new Ticket(ticketFile.Get.AsStream());
  201. if (ticket.TitleKeyType == TitleKeyType.Common)
  202. {
  203. KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
  204. }
  205. }
  206. }
  207. }
  208. // Save data created before we supported extra data in directory save data will not work properly if
  209. // given empty extra data. Luckily some of that extra data can be created using the data from the
  210. // save data indexer, which should be enough to check access permissions for user saves.
  211. // Every single save data's extra data will be checked and fixed if needed each time the emulator is opened.
  212. // Consider removing this at some point in the future when we don't need to worry about old saves.
  213. public static Result FixExtraData(HorizonClient hos)
  214. {
  215. Result rc = GetSystemSaveList(hos, out List<ulong> systemSaveIds);
  216. if (rc.IsFailure()) return rc;
  217. rc = FixUnindexedSystemSaves(hos, systemSaveIds);
  218. if (rc.IsFailure()) return rc;
  219. rc = FixExtraDataInSpaceId(hos, SaveDataSpaceId.System);
  220. if (rc.IsFailure()) return rc;
  221. rc = FixExtraDataInSpaceId(hos, SaveDataSpaceId.User);
  222. if (rc.IsFailure()) return rc;
  223. return Result.Success;
  224. }
  225. private static Result FixExtraDataInSpaceId(HorizonClient hos, SaveDataSpaceId spaceId)
  226. {
  227. Span<SaveDataInfo> info = stackalloc SaveDataInfo[8];
  228. using var iterator = new UniqueRef<SaveDataIterator>();
  229. Result rc = hos.Fs.OpenSaveDataIterator(ref iterator.Ref(), spaceId);
  230. if (rc.IsFailure()) return rc;
  231. while (true)
  232. {
  233. rc = iterator.Get.ReadSaveDataInfo(out long count, info);
  234. if (rc.IsFailure()) return rc;
  235. if (count == 0)
  236. return Result.Success;
  237. for (int i = 0; i < count; i++)
  238. {
  239. rc = FixExtraData(out bool wasFixNeeded, hos, in info[i]);
  240. if (ResultFs.TargetNotFound.Includes(rc))
  241. {
  242. // If the save wasn't found, try to create the directory for its save data ID
  243. rc = CreateSaveDataDirectory(hos, in info[i]);
  244. if (rc.IsFailure())
  245. {
  246. Logger.Warning?.Print(LogClass.Application, $"Error {rc.ToStringWithName()} when creating save data 0x{info[i].SaveDataId:x} in the {spaceId} save data space");
  247. // Don't bother fixing the extra data if we couldn't create the directory
  248. continue;
  249. }
  250. Logger.Info?.Print(LogClass.Application, $"Recreated directory for save data 0x{info[i].SaveDataId:x} in the {spaceId} save data space");
  251. // Try to fix the extra data in the new directory
  252. rc = FixExtraData(out wasFixNeeded, hos, in info[i]);
  253. }
  254. if (rc.IsFailure())
  255. {
  256. Logger.Warning?.Print(LogClass.Application, $"Error {rc.ToStringWithName()} when fixing extra data for save data 0x{info[i].SaveDataId:x} in the {spaceId} save data space");
  257. }
  258. else if (wasFixNeeded)
  259. {
  260. Logger.Info?.Print(LogClass.Application, $"Fixed extra data for save data 0x{info[i].SaveDataId:x} in the {spaceId} save data space");
  261. }
  262. }
  263. }
  264. }
  265. private static Result CreateSaveDataDirectory(HorizonClient hos, in SaveDataInfo info)
  266. {
  267. if (info.SpaceId != SaveDataSpaceId.User && info.SpaceId != SaveDataSpaceId.System)
  268. return Result.Success;
  269. const string mountName = "SaveDir";
  270. var mountNameU8 = mountName.ToU8Span();
  271. BisPartitionId partitionId = info.SpaceId switch
  272. {
  273. SaveDataSpaceId.System => BisPartitionId.System,
  274. SaveDataSpaceId.User => BisPartitionId.User,
  275. _ => throw new ArgumentOutOfRangeException()
  276. };
  277. Result rc = hos.Fs.MountBis(mountNameU8, partitionId);
  278. if (rc.IsFailure()) return rc;
  279. try
  280. {
  281. var path = $"{mountName}:/save/{info.SaveDataId:x16}".ToU8Span();
  282. rc = hos.Fs.GetEntryType(out _, path);
  283. if (ResultFs.PathNotFound.Includes(rc))
  284. {
  285. rc = hos.Fs.CreateDirectory(path);
  286. }
  287. return rc;
  288. }
  289. finally
  290. {
  291. hos.Fs.Unmount(mountNameU8);
  292. }
  293. }
  294. // Gets a list of all the save data files or directories in the system partition.
  295. private static Result GetSystemSaveList(HorizonClient hos, out List<ulong> list)
  296. {
  297. list = null;
  298. var mountName = "system".ToU8Span();
  299. DirectoryHandle handle = default;
  300. List<ulong> localList = new List<ulong>();
  301. try
  302. {
  303. Result rc = hos.Fs.MountBis(mountName, BisPartitionId.System);
  304. if (rc.IsFailure()) return rc;
  305. rc = hos.Fs.OpenDirectory(out handle, "system:/save".ToU8Span(), OpenDirectoryMode.All);
  306. if (rc.IsFailure()) return rc;
  307. DirectoryEntry entry = new DirectoryEntry();
  308. while (true)
  309. {
  310. rc = hos.Fs.ReadDirectory(out long readCount, SpanHelpers.AsSpan(ref entry), handle);
  311. if (rc.IsFailure()) return rc;
  312. if (readCount == 0)
  313. break;
  314. if (Utf8Parser.TryParse(entry.Name, out ulong saveDataId, out int bytesRead, 'x') &&
  315. bytesRead == 16 && (long)saveDataId < 0)
  316. {
  317. localList.Add(saveDataId);
  318. }
  319. }
  320. list = localList;
  321. return Result.Success;
  322. }
  323. finally
  324. {
  325. if (handle.IsValid)
  326. {
  327. hos.Fs.CloseDirectory(handle);
  328. }
  329. if (hos.Fs.IsMounted(mountName))
  330. {
  331. hos.Fs.Unmount(mountName);
  332. }
  333. }
  334. }
  335. // Adds system save data that isn't in the save data indexer to the indexer and creates extra data for it.
  336. // Only save data IDs added to SystemExtraDataFixInfo will be fixed.
  337. private static Result FixUnindexedSystemSaves(HorizonClient hos, List<ulong> existingSaveIds)
  338. {
  339. foreach (var fixInfo in SystemExtraDataFixInfo)
  340. {
  341. if (!existingSaveIds.Contains(fixInfo.StaticSaveDataId))
  342. {
  343. continue;
  344. }
  345. Result rc = FixSystemExtraData(out bool wasFixNeeded, hos, in fixInfo);
  346. if (rc.IsFailure())
  347. {
  348. Logger.Warning?.Print(LogClass.Application,
  349. $"Error {rc.ToStringWithName()} when fixing extra data for system save data 0x{fixInfo.StaticSaveDataId:x}");
  350. }
  351. else if (wasFixNeeded)
  352. {
  353. Logger.Info?.Print(LogClass.Application,
  354. $"Tried to rebuild extra data for system save data 0x{fixInfo.StaticSaveDataId:x}");
  355. }
  356. }
  357. return Result.Success;
  358. }
  359. private static Result FixSystemExtraData(out bool wasFixNeeded, HorizonClient hos, in ExtraDataFixInfo info)
  360. {
  361. wasFixNeeded = true;
  362. Result rc = hos.Fs.Impl.ReadSaveDataFileSystemExtraData(out SaveDataExtraData extraData, info.StaticSaveDataId);
  363. if (!rc.IsSuccess())
  364. {
  365. if (!ResultFs.TargetNotFound.Includes(rc))
  366. return rc;
  367. // We'll reach this point only if the save data directory exists but it's not in the save data indexer.
  368. // Creating the save will add it to the indexer while leaving its existing contents intact.
  369. return hos.Fs.CreateSystemSaveData(info.StaticSaveDataId, UserId.InvalidId, info.OwnerId, info.DataSize,
  370. info.JournalSize, info.Flags);
  371. }
  372. if (extraData.Attribute.StaticSaveDataId != 0 && extraData.OwnerId != 0)
  373. {
  374. wasFixNeeded = false;
  375. return Result.Success;
  376. }
  377. extraData = new SaveDataExtraData
  378. {
  379. Attribute = { StaticSaveDataId = info.StaticSaveDataId },
  380. OwnerId = info.OwnerId,
  381. Flags = info.Flags,
  382. DataSize = info.DataSize,
  383. JournalSize = info.JournalSize
  384. };
  385. // Make a mask for writing the entire extra data
  386. Unsafe.SkipInit(out SaveDataExtraData extraDataMask);
  387. SpanHelpers.AsByteSpan(ref extraDataMask).Fill(0xFF);
  388. return hos.Fs.Impl.WriteSaveDataFileSystemExtraData(SaveDataSpaceId.System, info.StaticSaveDataId,
  389. in extraData, in extraDataMask);
  390. }
  391. private static Result FixExtraData(out bool wasFixNeeded, HorizonClient hos, in SaveDataInfo info)
  392. {
  393. wasFixNeeded = true;
  394. Result rc = hos.Fs.Impl.ReadSaveDataFileSystemExtraData(out SaveDataExtraData extraData, info.SpaceId,
  395. info.SaveDataId);
  396. if (rc.IsFailure()) return rc;
  397. // The extra data should have program ID or static save data ID set if it's valid.
  398. // We only try to fix the extra data if the info from the save data indexer has a program ID or static save data ID.
  399. bool canFixByProgramId = extraData.Attribute.ProgramId == ProgramId.InvalidId &&
  400. info.ProgramId != ProgramId.InvalidId;
  401. bool canFixBySaveDataId = extraData.Attribute.StaticSaveDataId == 0 && info.StaticSaveDataId != 0;
  402. bool hasEmptyOwnerId = extraData.OwnerId == 0 && info.Type != SaveDataType.System;
  403. if (!canFixByProgramId && !canFixBySaveDataId && !hasEmptyOwnerId)
  404. {
  405. wasFixNeeded = false;
  406. return Result.Success;
  407. }
  408. // The save data attribute struct can be completely created from the save data info.
  409. extraData.Attribute.ProgramId = info.ProgramId;
  410. extraData.Attribute.UserId = info.UserId;
  411. extraData.Attribute.StaticSaveDataId = info.StaticSaveDataId;
  412. extraData.Attribute.Type = info.Type;
  413. extraData.Attribute.Rank = info.Rank;
  414. extraData.Attribute.Index = info.Index;
  415. // The rest of the extra data can't be created from the save data info.
  416. // On user saves the owner ID will almost certainly be the same as the program ID.
  417. if (info.Type != SaveDataType.System)
  418. {
  419. extraData.OwnerId = info.ProgramId.Value;
  420. }
  421. else
  422. {
  423. // Try to match the system save with one of the known saves
  424. foreach (ExtraDataFixInfo fixInfo in SystemExtraDataFixInfo)
  425. {
  426. if (extraData.Attribute.StaticSaveDataId == fixInfo.StaticSaveDataId)
  427. {
  428. extraData.OwnerId = fixInfo.OwnerId;
  429. extraData.Flags = fixInfo.Flags;
  430. extraData.DataSize = fixInfo.DataSize;
  431. extraData.JournalSize = fixInfo.JournalSize;
  432. break;
  433. }
  434. }
  435. }
  436. // Make a mask for writing the entire extra data
  437. Unsafe.SkipInit(out SaveDataExtraData extraDataMask);
  438. SpanHelpers.AsByteSpan(ref extraDataMask).Fill(0xFF);
  439. return hos.Fs.Impl.WriteSaveDataFileSystemExtraData(info.SpaceId, info.SaveDataId, in extraData, in extraDataMask);
  440. }
  441. struct ExtraDataFixInfo
  442. {
  443. public ulong StaticSaveDataId;
  444. public ulong OwnerId;
  445. public SaveDataFlags Flags;
  446. public long DataSize;
  447. public long JournalSize;
  448. }
  449. private static readonly ExtraDataFixInfo[] SystemExtraDataFixInfo =
  450. {
  451. new ExtraDataFixInfo()
  452. {
  453. StaticSaveDataId = 0x8000000000000030,
  454. OwnerId = 0x010000000000001F,
  455. Flags = SaveDataFlags.KeepAfterResettingSystemSaveDataWithoutUserSaveData,
  456. DataSize = 0x10000,
  457. JournalSize = 0x10000
  458. },
  459. new ExtraDataFixInfo()
  460. {
  461. StaticSaveDataId = 0x8000000000001040,
  462. OwnerId = 0x0100000000001009,
  463. Flags = SaveDataFlags.None,
  464. DataSize = 0xC000,
  465. JournalSize = 0xC000
  466. }
  467. };
  468. public void Dispose()
  469. {
  470. Dispose(true);
  471. }
  472. protected virtual void Dispose(bool disposing)
  473. {
  474. if (disposing)
  475. {
  476. RomFs?.Dispose();
  477. }
  478. }
  479. }
  480. }