VirtualFileSystem.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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. if (ticket.TitleKeyType == TitleKeyType.Common)
  216. {
  217. KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
  218. }
  219. }
  220. }
  221. }
  222. // Save data created before we supported extra data in directory save data will not work properly if
  223. // given empty extra data. Luckily some of that extra data can be created using the data from the
  224. // save data indexer, which should be enough to check access permissions for user saves.
  225. // Every single save data's extra data will be checked and fixed if needed each time the emulator is opened.
  226. // Consider removing this at some point in the future when we don't need to worry about old saves.
  227. public static Result FixExtraData(HorizonClient hos)
  228. {
  229. Result rc = GetSystemSaveList(hos, out List<ulong> systemSaveIds);
  230. if (rc.IsFailure()) return rc;
  231. rc = FixUnindexedSystemSaves(hos, systemSaveIds);
  232. if (rc.IsFailure()) return rc;
  233. rc = FixExtraDataInSpaceId(hos, SaveDataSpaceId.System);
  234. if (rc.IsFailure()) return rc;
  235. rc = FixExtraDataInSpaceId(hos, SaveDataSpaceId.User);
  236. if (rc.IsFailure()) return rc;
  237. return Result.Success;
  238. }
  239. private static Result FixExtraDataInSpaceId(HorizonClient hos, SaveDataSpaceId spaceId)
  240. {
  241. Span<SaveDataInfo> info = stackalloc SaveDataInfo[8];
  242. using var iterator = new UniqueRef<SaveDataIterator>();
  243. Result rc = hos.Fs.OpenSaveDataIterator(ref iterator.Ref(), spaceId);
  244. if (rc.IsFailure()) return rc;
  245. while (true)
  246. {
  247. rc = iterator.Get.ReadSaveDataInfo(out long count, info);
  248. if (rc.IsFailure()) return rc;
  249. if (count == 0)
  250. return Result.Success;
  251. for (int i = 0; i < count; i++)
  252. {
  253. rc = FixExtraData(out bool wasFixNeeded, hos, in info[i]);
  254. if (ResultFs.TargetNotFound.Includes(rc))
  255. {
  256. // If the save wasn't found, try to create the directory for its save data ID
  257. rc = CreateSaveDataDirectory(hos, in info[i]);
  258. if (rc.IsFailure())
  259. {
  260. Logger.Warning?.Print(LogClass.Application, $"Error {rc.ToStringWithName()} when creating save data 0x{info[i].SaveDataId:x} in the {spaceId} save data space");
  261. // Don't bother fixing the extra data if we couldn't create the directory
  262. continue;
  263. }
  264. Logger.Info?.Print(LogClass.Application, $"Recreated directory for save data 0x{info[i].SaveDataId:x} in the {spaceId} save data space");
  265. // Try to fix the extra data in the new directory
  266. rc = FixExtraData(out wasFixNeeded, hos, in info[i]);
  267. }
  268. if (rc.IsFailure())
  269. {
  270. 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");
  271. }
  272. else if (wasFixNeeded)
  273. {
  274. Logger.Info?.Print(LogClass.Application, $"Fixed extra data for save data 0x{info[i].SaveDataId:x} in the {spaceId} save data space");
  275. }
  276. }
  277. }
  278. }
  279. private static Result CreateSaveDataDirectory(HorizonClient hos, in SaveDataInfo info)
  280. {
  281. if (info.SpaceId != SaveDataSpaceId.User && info.SpaceId != SaveDataSpaceId.System)
  282. return Result.Success;
  283. const string mountName = "SaveDir";
  284. var mountNameU8 = mountName.ToU8Span();
  285. BisPartitionId partitionId = info.SpaceId switch
  286. {
  287. SaveDataSpaceId.System => BisPartitionId.System,
  288. SaveDataSpaceId.User => BisPartitionId.User,
  289. _ => throw new ArgumentOutOfRangeException()
  290. };
  291. Result rc = hos.Fs.MountBis(mountNameU8, partitionId);
  292. if (rc.IsFailure()) return rc;
  293. try
  294. {
  295. var path = $"{mountName}:/save/{info.SaveDataId:x16}".ToU8Span();
  296. rc = hos.Fs.GetEntryType(out _, path);
  297. if (ResultFs.PathNotFound.Includes(rc))
  298. {
  299. rc = hos.Fs.CreateDirectory(path);
  300. }
  301. return rc;
  302. }
  303. finally
  304. {
  305. hos.Fs.Unmount(mountNameU8);
  306. }
  307. }
  308. // Gets a list of all the save data files or directories in the system partition.
  309. private static Result GetSystemSaveList(HorizonClient hos, out List<ulong> list)
  310. {
  311. list = null;
  312. var mountName = "system".ToU8Span();
  313. DirectoryHandle handle = default;
  314. List<ulong> localList = new List<ulong>();
  315. try
  316. {
  317. Result rc = hos.Fs.MountBis(mountName, BisPartitionId.System);
  318. if (rc.IsFailure()) return rc;
  319. rc = hos.Fs.OpenDirectory(out handle, "system:/save".ToU8Span(), OpenDirectoryMode.All);
  320. if (rc.IsFailure()) return rc;
  321. DirectoryEntry entry = new DirectoryEntry();
  322. while (true)
  323. {
  324. rc = hos.Fs.ReadDirectory(out long readCount, SpanHelpers.AsSpan(ref entry), handle);
  325. if (rc.IsFailure()) return rc;
  326. if (readCount == 0)
  327. break;
  328. if (Utf8Parser.TryParse(entry.Name, out ulong saveDataId, out int bytesRead, 'x') &&
  329. bytesRead == 16 && (long)saveDataId < 0)
  330. {
  331. localList.Add(saveDataId);
  332. }
  333. }
  334. list = localList;
  335. return Result.Success;
  336. }
  337. finally
  338. {
  339. if (handle.IsValid)
  340. {
  341. hos.Fs.CloseDirectory(handle);
  342. }
  343. if (hos.Fs.IsMounted(mountName))
  344. {
  345. hos.Fs.Unmount(mountName);
  346. }
  347. }
  348. }
  349. // Adds system save data that isn't in the save data indexer to the indexer and creates extra data for it.
  350. // Only save data IDs added to SystemExtraDataFixInfo will be fixed.
  351. private static Result FixUnindexedSystemSaves(HorizonClient hos, List<ulong> existingSaveIds)
  352. {
  353. foreach (var fixInfo in SystemExtraDataFixInfo)
  354. {
  355. if (!existingSaveIds.Contains(fixInfo.StaticSaveDataId))
  356. {
  357. continue;
  358. }
  359. Result rc = FixSystemExtraData(out bool wasFixNeeded, hos, in fixInfo);
  360. if (rc.IsFailure())
  361. {
  362. Logger.Warning?.Print(LogClass.Application,
  363. $"Error {rc.ToStringWithName()} when fixing extra data for system save data 0x{fixInfo.StaticSaveDataId:x}");
  364. }
  365. else if (wasFixNeeded)
  366. {
  367. Logger.Info?.Print(LogClass.Application,
  368. $"Tried to rebuild extra data for system save data 0x{fixInfo.StaticSaveDataId:x}");
  369. }
  370. }
  371. return Result.Success;
  372. }
  373. private static Result FixSystemExtraData(out bool wasFixNeeded, HorizonClient hos, in ExtraDataFixInfo info)
  374. {
  375. wasFixNeeded = true;
  376. Result rc = hos.Fs.Impl.ReadSaveDataFileSystemExtraData(out SaveDataExtraData extraData, info.StaticSaveDataId);
  377. if (!rc.IsSuccess())
  378. {
  379. if (!ResultFs.TargetNotFound.Includes(rc))
  380. return rc;
  381. // We'll reach this point only if the save data directory exists but it's not in the save data indexer.
  382. // Creating the save will add it to the indexer while leaving its existing contents intact.
  383. return hos.Fs.CreateSystemSaveData(info.StaticSaveDataId, UserId.InvalidId, info.OwnerId, info.DataSize,
  384. info.JournalSize, info.Flags);
  385. }
  386. if (extraData.Attribute.StaticSaveDataId != 0 && extraData.OwnerId != 0)
  387. {
  388. wasFixNeeded = false;
  389. return Result.Success;
  390. }
  391. extraData = new SaveDataExtraData
  392. {
  393. Attribute = { StaticSaveDataId = info.StaticSaveDataId },
  394. OwnerId = info.OwnerId,
  395. Flags = info.Flags,
  396. DataSize = info.DataSize,
  397. JournalSize = info.JournalSize
  398. };
  399. // Make a mask for writing the entire extra data
  400. Unsafe.SkipInit(out SaveDataExtraData extraDataMask);
  401. SpanHelpers.AsByteSpan(ref extraDataMask).Fill(0xFF);
  402. return hos.Fs.Impl.WriteSaveDataFileSystemExtraData(SaveDataSpaceId.System, info.StaticSaveDataId,
  403. in extraData, in extraDataMask);
  404. }
  405. private static Result FixExtraData(out bool wasFixNeeded, HorizonClient hos, in SaveDataInfo info)
  406. {
  407. wasFixNeeded = true;
  408. Result rc = hos.Fs.Impl.ReadSaveDataFileSystemExtraData(out SaveDataExtraData extraData, info.SpaceId,
  409. info.SaveDataId);
  410. if (rc.IsFailure()) return rc;
  411. // The extra data should have program ID or static save data ID set if it's valid.
  412. // 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.
  413. bool canFixByProgramId = extraData.Attribute.ProgramId == ProgramId.InvalidId &&
  414. info.ProgramId != ProgramId.InvalidId;
  415. bool canFixBySaveDataId = extraData.Attribute.StaticSaveDataId == 0 && info.StaticSaveDataId != 0;
  416. bool hasEmptyOwnerId = extraData.OwnerId == 0 && info.Type != SaveDataType.System;
  417. if (!canFixByProgramId && !canFixBySaveDataId && !hasEmptyOwnerId)
  418. {
  419. wasFixNeeded = false;
  420. return Result.Success;
  421. }
  422. // The save data attribute struct can be completely created from the save data info.
  423. extraData.Attribute.ProgramId = info.ProgramId;
  424. extraData.Attribute.UserId = info.UserId;
  425. extraData.Attribute.StaticSaveDataId = info.StaticSaveDataId;
  426. extraData.Attribute.Type = info.Type;
  427. extraData.Attribute.Rank = info.Rank;
  428. extraData.Attribute.Index = info.Index;
  429. // The rest of the extra data can't be created from the save data info.
  430. // On user saves the owner ID will almost certainly be the same as the program ID.
  431. if (info.Type != SaveDataType.System)
  432. {
  433. extraData.OwnerId = info.ProgramId.Value;
  434. }
  435. else
  436. {
  437. // Try to match the system save with one of the known saves
  438. foreach (ExtraDataFixInfo fixInfo in SystemExtraDataFixInfo)
  439. {
  440. if (extraData.Attribute.StaticSaveDataId == fixInfo.StaticSaveDataId)
  441. {
  442. extraData.OwnerId = fixInfo.OwnerId;
  443. extraData.Flags = fixInfo.Flags;
  444. extraData.DataSize = fixInfo.DataSize;
  445. extraData.JournalSize = fixInfo.JournalSize;
  446. break;
  447. }
  448. }
  449. }
  450. // Make a mask for writing the entire extra data
  451. Unsafe.SkipInit(out SaveDataExtraData extraDataMask);
  452. SpanHelpers.AsByteSpan(ref extraDataMask).Fill(0xFF);
  453. return hos.Fs.Impl.WriteSaveDataFileSystemExtraData(info.SpaceId, info.SaveDataId, in extraData, in extraDataMask);
  454. }
  455. struct ExtraDataFixInfo
  456. {
  457. public ulong StaticSaveDataId;
  458. public ulong OwnerId;
  459. public SaveDataFlags Flags;
  460. public long DataSize;
  461. public long JournalSize;
  462. }
  463. private static readonly ExtraDataFixInfo[] SystemExtraDataFixInfo =
  464. {
  465. new ExtraDataFixInfo()
  466. {
  467. StaticSaveDataId = 0x8000000000000030,
  468. OwnerId = 0x010000000000001F,
  469. Flags = SaveDataFlags.KeepAfterResettingSystemSaveDataWithoutUserSaveData,
  470. DataSize = 0x10000,
  471. JournalSize = 0x10000
  472. },
  473. new ExtraDataFixInfo()
  474. {
  475. StaticSaveDataId = 0x8000000000001040,
  476. OwnerId = 0x0100000000001009,
  477. Flags = SaveDataFlags.None,
  478. DataSize = 0xC000,
  479. JournalSize = 0xC000
  480. }
  481. };
  482. public void Dispose()
  483. {
  484. Dispose(true);
  485. }
  486. protected virtual void Dispose(bool disposing)
  487. {
  488. if (disposing)
  489. {
  490. foreach (var stream in _romFsByPid.Values)
  491. {
  492. stream.Close();
  493. }
  494. _romFsByPid.Clear();
  495. }
  496. }
  497. }
  498. }