VirtualFileSystem.cs 21 KB

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