VirtualFileSystem.cs 22 KB

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