VirtualFileSystem.cs 22 KB

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