VirtualFileSystem.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  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. rc = FixExtraDataInSpaceId(hos, SaveDataSpaceId.SdCache);
  224. if (rc.IsFailure()) return rc;
  225. return Result.Success;
  226. }
  227. private static Result FixExtraDataInSpaceId(HorizonClient hos, SaveDataSpaceId spaceId)
  228. {
  229. Span<SaveDataInfo> info = stackalloc SaveDataInfo[8];
  230. Result rc = hos.Fs.OpenSaveDataIterator(out var iterator, spaceId);
  231. if (rc.IsFailure()) return rc;
  232. while (true)
  233. {
  234. rc = iterator.ReadSaveDataInfo(out long count, info);
  235. if (rc.IsFailure()) return rc;
  236. if (count == 0)
  237. return Result.Success;
  238. for (int i = 0; i < count; i++)
  239. {
  240. rc = FixExtraData(out bool wasFixNeeded, hos, in info[i]);
  241. if (ResultFs.TargetNotFound.Includes(rc))
  242. {
  243. // If the save wasn't found, try to create the directory for its save data ID
  244. rc = CreateSaveDataDirectory(hos, in info[i]);
  245. if (rc.IsFailure())
  246. {
  247. Logger.Warning?.Print(LogClass.Application, $"Error {rc.ToStringWithName()} when creating save data 0x{info[i].SaveDataId:x} in the {spaceId} save data space");
  248. // Don't bother fixing the extra data if we couldn't create the directory
  249. continue;
  250. }
  251. Logger.Info?.Print(LogClass.Application, $"Recreated directory for save data 0x{info[i].SaveDataId:x} in the {spaceId} save data space");
  252. // Try to fix the extra data in the new directory
  253. rc = FixExtraData(out wasFixNeeded, hos, in info[i]);
  254. }
  255. if (rc.IsFailure())
  256. {
  257. 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");
  258. }
  259. else if (wasFixNeeded)
  260. {
  261. Logger.Info?.Print(LogClass.Application, $"Fixed extra data for save data 0x{info[i].SaveDataId:x} in the {spaceId} save data space");
  262. }
  263. }
  264. }
  265. }
  266. private static Result CreateSaveDataDirectory(HorizonClient hos, in SaveDataInfo info)
  267. {
  268. if (info.SpaceId != SaveDataSpaceId.User && info.SpaceId != SaveDataSpaceId.System)
  269. return Result.Success;
  270. const string mountName = "SaveDir";
  271. var mountNameU8 = mountName.ToU8Span();
  272. BisPartitionId partitionId = info.SpaceId switch
  273. {
  274. SaveDataSpaceId.System => BisPartitionId.System,
  275. SaveDataSpaceId.User => BisPartitionId.User,
  276. _ => throw new ArgumentOutOfRangeException()
  277. };
  278. Result rc = hos.Fs.MountBis(mountNameU8, partitionId);
  279. if (rc.IsFailure()) return rc;
  280. try
  281. {
  282. var path = $"{mountName}:/save/{info.SaveDataId:x16}".ToU8Span();
  283. rc = hos.Fs.GetEntryType(out _, path);
  284. if (ResultFs.PathNotFound.Includes(rc))
  285. {
  286. rc = hos.Fs.CreateDirectory(path);
  287. }
  288. return rc;
  289. }
  290. finally
  291. {
  292. hos.Fs.Unmount(mountNameU8);
  293. }
  294. }
  295. // Gets a list of all the save data files or directories in the system partition.
  296. private static Result GetSystemSaveList(HorizonClient hos, out List<ulong> list)
  297. {
  298. list = null;
  299. var mountName = "system".ToU8Span();
  300. DirectoryHandle handle = default;
  301. List<ulong> localList = new List<ulong>();
  302. try
  303. {
  304. Result rc = hos.Fs.MountBis(mountName, BisPartitionId.System);
  305. if (rc.IsFailure()) return rc;
  306. rc = hos.Fs.OpenDirectory(out handle, "system:/save".ToU8Span(), OpenDirectoryMode.All);
  307. if (rc.IsFailure()) return rc;
  308. DirectoryEntry entry = new DirectoryEntry();
  309. while (true)
  310. {
  311. rc = hos.Fs.ReadDirectory(out long readCount, SpanHelpers.AsSpan(ref entry), handle);
  312. if (rc.IsFailure()) return rc;
  313. if (readCount == 0)
  314. break;
  315. if (Utf8Parser.TryParse(entry.Name, out ulong saveDataId, out int bytesRead, 'x') &&
  316. bytesRead == 16 && (long)saveDataId < 0)
  317. {
  318. localList.Add(saveDataId);
  319. }
  320. }
  321. list = localList;
  322. return Result.Success;
  323. }
  324. finally
  325. {
  326. if (handle.IsValid)
  327. {
  328. hos.Fs.CloseDirectory(handle);
  329. }
  330. if (hos.Fs.IsMounted(mountName))
  331. {
  332. hos.Fs.Unmount(mountName);
  333. }
  334. }
  335. }
  336. // Adds system save data that isn't in the save data indexer to the indexer and creates extra data for it.
  337. // Only save data IDs added to SystemExtraDataFixInfo will be fixed.
  338. private static Result FixUnindexedSystemSaves(HorizonClient hos, List<ulong> existingSaveIds)
  339. {
  340. foreach (var fixInfo in SystemExtraDataFixInfo)
  341. {
  342. if (!existingSaveIds.Contains(fixInfo.StaticSaveDataId))
  343. {
  344. continue;
  345. }
  346. Result rc = FixSystemExtraData(out bool wasFixNeeded, hos, in fixInfo);
  347. if (rc.IsFailure())
  348. {
  349. Logger.Warning?.Print(LogClass.Application,
  350. $"Error {rc.ToStringWithName()} when fixing extra data for system save data 0x{fixInfo.StaticSaveDataId:x}");
  351. }
  352. else if (wasFixNeeded)
  353. {
  354. Logger.Info?.Print(LogClass.Application,
  355. $"Tried to rebuild extra data for system save data 0x{fixInfo.StaticSaveDataId:x}");
  356. }
  357. }
  358. return Result.Success;
  359. }
  360. private static Result FixSystemExtraData(out bool wasFixNeeded, HorizonClient hos, in ExtraDataFixInfo info)
  361. {
  362. wasFixNeeded = true;
  363. Result rc = hos.Fs.Impl.ReadSaveDataFileSystemExtraData(out SaveDataExtraData extraData, info.StaticSaveDataId);
  364. if (!rc.IsSuccess())
  365. {
  366. if (!ResultFs.TargetNotFound.Includes(rc))
  367. return rc;
  368. // We'll reach this point only if the save data directory exists but it's not in the save data indexer.
  369. // Creating the save will add it to the indexer while leaving its existing contents intact.
  370. return hos.Fs.CreateSystemSaveData(info.StaticSaveDataId, UserId.InvalidId, info.OwnerId, info.DataSize,
  371. info.JournalSize, info.Flags);
  372. }
  373. if (extraData.Attribute.StaticSaveDataId != 0 && extraData.OwnerId != 0)
  374. {
  375. wasFixNeeded = false;
  376. return Result.Success;
  377. }
  378. extraData = new SaveDataExtraData
  379. {
  380. Attribute = { StaticSaveDataId = info.StaticSaveDataId },
  381. OwnerId = info.OwnerId,
  382. Flags = info.Flags,
  383. DataSize = info.DataSize,
  384. JournalSize = info.JournalSize
  385. };
  386. // Make a mask for writing the entire extra data
  387. Unsafe.SkipInit(out SaveDataExtraData extraDataMask);
  388. SpanHelpers.AsByteSpan(ref extraDataMask).Fill(0xFF);
  389. return hos.Fs.Impl.WriteSaveDataFileSystemExtraData(SaveDataSpaceId.System, info.StaticSaveDataId,
  390. in extraData, in extraDataMask);
  391. }
  392. private static Result FixExtraData(out bool wasFixNeeded, HorizonClient hos, in SaveDataInfo info)
  393. {
  394. wasFixNeeded = true;
  395. Result rc = hos.Fs.Impl.ReadSaveDataFileSystemExtraData(out SaveDataExtraData extraData, info.SpaceId,
  396. info.SaveDataId);
  397. if (rc.IsFailure()) return rc;
  398. // The extra data should have program ID or static save data ID set if it's valid.
  399. // 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.
  400. bool canFixByProgramId = extraData.Attribute.ProgramId == ProgramId.InvalidId &&
  401. info.ProgramId != ProgramId.InvalidId;
  402. bool canFixBySaveDataId = extraData.Attribute.StaticSaveDataId == 0 && info.StaticSaveDataId != 0;
  403. if (!canFixByProgramId && !canFixBySaveDataId)
  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 != LibHac.Fs.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 Unload()
  469. {
  470. RomFs?.Dispose();
  471. }
  472. public void Dispose()
  473. {
  474. Dispose(true);
  475. }
  476. protected virtual void Dispose(bool disposing)
  477. {
  478. if (disposing)
  479. {
  480. Unload();
  481. }
  482. }
  483. public static VirtualFileSystem CreateInstance()
  484. {
  485. if (_isInitialized)
  486. {
  487. throw new InvalidOperationException("VirtualFileSystem can only be instantiated once!");
  488. }
  489. _isInitialized = true;
  490. return new VirtualFileSystem();
  491. }
  492. }
  493. }