VirtualFileSystem.cs 22 KB

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