VirtualFileSystem.cs 21 KB

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