ApplicationHelper.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. using Avalonia.Platform.Storage;
  2. using Avalonia.Threading;
  3. using Gommon;
  4. using LibHac;
  5. using LibHac.Account;
  6. using LibHac.Common;
  7. using LibHac.Fs;
  8. using LibHac.Fs.Fsa;
  9. using LibHac.Fs.Shim;
  10. using LibHac.FsSystem;
  11. using LibHac.Ns;
  12. using LibHac.Tools.Fs;
  13. using LibHac.Tools.FsSystem;
  14. using LibHac.Tools.FsSystem.NcaUtils;
  15. using Ryujinx.Ava.Common.Locale;
  16. using Ryujinx.Ava.UI.Controls;
  17. using Ryujinx.Ava.UI.Helpers;
  18. using Ryujinx.Ava.Utilities;
  19. using Ryujinx.Ava.Utilities.Configuration;
  20. using Ryujinx.Common.Helper;
  21. using Ryujinx.Common.Logging;
  22. using Ryujinx.HLE.FileSystem;
  23. using Ryujinx.HLE.HOS.Services.Account.Acc;
  24. using Ryujinx.HLE.Loaders.Processes.Extensions;
  25. using System;
  26. using System.Buffers;
  27. using System.IO;
  28. using System.Threading;
  29. using System.Threading.Tasks;
  30. using ApplicationId = LibHac.Ncm.ApplicationId;
  31. using Path = System.IO.Path;
  32. namespace Ryujinx.Ava.Common
  33. {
  34. internal static class ApplicationHelper
  35. {
  36. private static HorizonClient _horizonClient;
  37. private static AccountManager _accountManager;
  38. private static VirtualFileSystem _virtualFileSystem;
  39. public static void Initialize(VirtualFileSystem virtualFileSystem, AccountManager accountManager, HorizonClient horizonClient)
  40. {
  41. _virtualFileSystem = virtualFileSystem;
  42. _horizonClient = horizonClient;
  43. _accountManager = accountManager;
  44. }
  45. private static bool TryFindSaveData(string titleName, ulong titleId, BlitStruct<ApplicationControlProperty> controlHolder, in SaveDataFilter filter, out ulong saveDataId)
  46. {
  47. saveDataId = default;
  48. Result result = _horizonClient.Fs.FindSaveDataWithFilter(out SaveDataInfo saveDataInfo, SaveDataSpaceId.User, in filter);
  49. if (ResultFs.TargetNotFound.Includes(result))
  50. {
  51. ref ApplicationControlProperty control = ref controlHolder.Value;
  52. Logger.Info?.Print(LogClass.Application, $"Creating save directory for Title: {titleName} [{titleId:x16}]");
  53. if (controlHolder.ByteSpan.IsZeros())
  54. {
  55. // If the current application doesn't have a loaded control property, create a dummy one
  56. // and set the savedata sizes so a user savedata will be created.
  57. control = ref new BlitStruct<ApplicationControlProperty>(1).Value;
  58. // The set sizes don't actually matter as long as they're non-zero because we use directory savedata.
  59. control.UserAccountSaveDataSize = 0x4000;
  60. control.UserAccountSaveDataJournalSize = 0x4000;
  61. Logger.Warning?.Print(LogClass.Application, "No control file was found for this game. Using a dummy one instead. This may cause inaccuracies in some games.");
  62. }
  63. Uid user = _accountManager.LastOpenedUser.UserId.ToLibHacUid();
  64. result = _horizonClient.Fs.EnsureApplicationSaveData(out _, new ApplicationId(titleId), in control, in user);
  65. if (result.IsFailure())
  66. {
  67. Dispatcher.UIThread.InvokeAsync(async () =>
  68. {
  69. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogMessageCreateSaveErrorMessage, result.ToStringWithName()));
  70. });
  71. return false;
  72. }
  73. // Try to find the savedata again after creating it
  74. result = _horizonClient.Fs.FindSaveDataWithFilter(out saveDataInfo, SaveDataSpaceId.User, in filter);
  75. }
  76. if (result.IsSuccess())
  77. {
  78. saveDataId = saveDataInfo.SaveDataId;
  79. return true;
  80. }
  81. Dispatcher.UIThread.InvokeAsync(async () =>
  82. {
  83. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogMessageFindSaveErrorMessage, result.ToStringWithName()));
  84. });
  85. return false;
  86. }
  87. public static void OpenSaveDir(in SaveDataFilter saveDataFilter, ulong titleId, BlitStruct<ApplicationControlProperty> controlData, string titleName)
  88. {
  89. if (!TryFindSaveData(titleName, titleId, controlData, in saveDataFilter, out ulong saveDataId))
  90. {
  91. return;
  92. }
  93. OpenSaveDir(saveDataId);
  94. }
  95. public static void OpenSaveDir(ulong saveDataId)
  96. {
  97. string saveRootPath = Path.Combine(VirtualFileSystem.GetNandPath(), $"user/save/{saveDataId:x16}");
  98. if (!Directory.Exists(saveRootPath))
  99. {
  100. // Inconsistent state. Create the directory
  101. Directory.CreateDirectory(saveRootPath);
  102. }
  103. string committedPath = Path.Combine(saveRootPath, "0");
  104. string workingPath = Path.Combine(saveRootPath, "1");
  105. // If the committed directory exists, that path will be loaded the next time the savedata is mounted
  106. if (Directory.Exists(committedPath))
  107. {
  108. OpenHelper.OpenFolder(committedPath);
  109. }
  110. else
  111. {
  112. // If the working directory exists and the committed directory doesn't,
  113. // the working directory will be loaded the next time the savedata is mounted
  114. if (!Directory.Exists(workingPath))
  115. {
  116. Directory.CreateDirectory(workingPath);
  117. }
  118. OpenHelper.OpenFolder(workingPath);
  119. }
  120. }
  121. public static void ExtractSection(string destination, NcaSectionType ncaSectionType, string titleFilePath, string titleName, int programIndex = 0)
  122. {
  123. CancellationTokenSource cancellationToken = new();
  124. UpdateWaitWindow waitingDialog = new(
  125. RyujinxApp.FormatTitle(LocaleKeys.DialogNcaExtractionTitle),
  126. LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogNcaExtractionMessage, ncaSectionType, Path.GetFileName(titleFilePath)),
  127. cancellationToken);
  128. Thread extractorThread = new(() =>
  129. {
  130. Dispatcher.UIThread.Post(waitingDialog.Show);
  131. using FileStream file = new(titleFilePath, FileMode.Open, FileAccess.Read);
  132. Nca mainNca = null;
  133. Nca patchNca = null;
  134. string extension = Path.GetExtension(titleFilePath).ToLower();
  135. if (extension is ".nsp" or ".pfs0" or ".xci")
  136. {
  137. IFileSystem pfs;
  138. if (extension is ".xci")
  139. {
  140. pfs = new Xci(_virtualFileSystem.KeySet, file.AsStorage()).OpenPartition(XciPartitionType.Secure);
  141. }
  142. else
  143. {
  144. PartitionFileSystem pfsTemp = new();
  145. pfsTemp.Initialize(file.AsStorage()).ThrowIfFailure();
  146. pfs = pfsTemp;
  147. }
  148. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  149. {
  150. using UniqueRef<IFile> ncaFile = new();
  151. pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  152. Nca nca = new(_virtualFileSystem.KeySet, ncaFile.Get.AsStorage());
  153. if (nca.Header.ContentType is NcaContentType.Program)
  154. {
  155. int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);
  156. if (nca.SectionExists(NcaSectionType.Data) && nca.Header.GetFsHeader(dataIndex).IsPatchSection())
  157. {
  158. patchNca = nca;
  159. }
  160. else
  161. {
  162. mainNca = nca;
  163. }
  164. }
  165. }
  166. }
  167. else if (extension is ".nca")
  168. {
  169. mainNca = new Nca(_virtualFileSystem.KeySet, file.AsStorage());
  170. }
  171. if (mainNca is null)
  172. {
  173. Logger.Error?.Print(LogClass.Application, "Extraction failure. The main NCA was not present in the selected file");
  174. Dispatcher.UIThread.InvokeAsync(async () =>
  175. {
  176. waitingDialog.Close();
  177. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogNcaExtractionMainNcaNotFoundErrorMessage]);
  178. });
  179. return;
  180. }
  181. IntegrityCheckLevel checkLevel = ConfigurationState.Instance.System.EnableFsIntegrityChecks
  182. ? IntegrityCheckLevel.ErrorOnInvalid
  183. : IntegrityCheckLevel.None;
  184. (Nca updatePatchNca, _) = mainNca.GetUpdateData(_virtualFileSystem, checkLevel, programIndex, out _);
  185. if (updatePatchNca is not null)
  186. {
  187. patchNca = updatePatchNca;
  188. }
  189. int index = Nca.GetSectionIndexFromType(ncaSectionType, mainNca.Header.ContentType);
  190. try
  191. {
  192. bool sectionExistsInPatch = false;
  193. if (patchNca is not null)
  194. {
  195. sectionExistsInPatch = patchNca.CanOpenSection(index);
  196. }
  197. IFileSystem ncaFileSystem = sectionExistsInPatch ? mainNca.OpenFileSystemWithPatch(patchNca, index, IntegrityCheckLevel.ErrorOnInvalid)
  198. : mainNca.OpenFileSystem(index, IntegrityCheckLevel.ErrorOnInvalid);
  199. FileSystemClient fsClient = _horizonClient.Fs;
  200. string source = DateTime.Now.ToFileTime().ToString()[10..];
  201. string output = DateTime.Now.ToFileTime().ToString()[10..];
  202. using UniqueRef<IFileSystem> uniqueSourceFs = new(ncaFileSystem);
  203. using UniqueRef<IFileSystem> uniqueOutputFs = new(new LocalFileSystem(destination));
  204. fsClient.Register(source.ToU8Span(), ref uniqueSourceFs.Ref);
  205. fsClient.Register(output.ToU8Span(), ref uniqueOutputFs.Ref);
  206. (Result? resultCode, bool canceled) = CopyDirectory(fsClient, $"{source}:/", $"{output}:/", cancellationToken.Token);
  207. if (!canceled)
  208. {
  209. if (resultCode.Value.IsFailure())
  210. {
  211. Logger.Error?.Print(LogClass.Application, $"LibHac returned error code: {resultCode.Value.ErrorCode}");
  212. Dispatcher.UIThread.InvokeAsync(async () =>
  213. {
  214. waitingDialog.Close();
  215. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogNcaExtractionCheckLogErrorMessage]);
  216. });
  217. }
  218. else if (resultCode.Value.IsSuccess())
  219. {
  220. Dispatcher.UIThread.Post(waitingDialog.Close);
  221. NotificationHelper.ShowInformation(
  222. RyujinxApp.FormatTitle(LocaleKeys.DialogNcaExtractionTitle),
  223. $"{titleName}\n\n{LocaleManager.Instance[LocaleKeys.DialogNcaExtractionSuccessMessage]}");
  224. }
  225. }
  226. fsClient.Unmount(source.ToU8Span());
  227. fsClient.Unmount(output.ToU8Span());
  228. }
  229. catch (ArgumentException ex)
  230. {
  231. Logger.Error?.Print(LogClass.Application, $"{ex.Message}");
  232. Dispatcher.UIThread.InvokeAsync(async () =>
  233. {
  234. waitingDialog.Close();
  235. await ContentDialogHelper.CreateErrorDialog(ex.Message);
  236. });
  237. }
  238. })
  239. {
  240. Name = "GUI.NcaSectionExtractorThread",
  241. IsBackground = true,
  242. };
  243. extractorThread.Start();
  244. }
  245. public static void ExtractAoc(string destination, string updateFilePath, string updateName)
  246. {
  247. CancellationTokenSource cancellationToken = new();
  248. UpdateWaitWindow waitingDialog = new(
  249. RyujinxApp.FormatTitle(LocaleKeys.DialogNcaExtractionTitle),
  250. LocaleManager.Instance.UpdateAndGetDynamicValue(LocaleKeys.DialogNcaExtractionMessage, NcaSectionType.Data, Path.GetFileName(updateFilePath)),
  251. cancellationToken);
  252. Thread extractorThread = new(() =>
  253. {
  254. Dispatcher.UIThread.Post(waitingDialog.Show);
  255. using FileStream file = new(updateFilePath, FileMode.Open, FileAccess.Read);
  256. Nca publicDataNca = null;
  257. string extension = Path.GetExtension(updateFilePath).ToLower();
  258. if (extension is ".nsp")
  259. {
  260. PartitionFileSystem pfsTemp = new();
  261. pfsTemp.Initialize(file.AsStorage()).ThrowIfFailure();
  262. IFileSystem pfs = pfsTemp;
  263. foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
  264. {
  265. using UniqueRef<IFile> ncaFile = new();
  266. pfs.OpenFile(ref ncaFile.Ref, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();
  267. Nca nca = new(_virtualFileSystem.KeySet, ncaFile.Get.AsStorage());
  268. if (nca.Header.ContentType is NcaContentType.PublicData && nca.SectionExists(NcaSectionType.Data))
  269. {
  270. publicDataNca = nca;
  271. }
  272. }
  273. }
  274. if (publicDataNca is null)
  275. {
  276. Logger.Error?.Print(LogClass.Application, "Extraction failure. The PublicData NCA was not present in the selected file");
  277. Dispatcher.UIThread.InvokeAsync(async () =>
  278. {
  279. waitingDialog.Close();
  280. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogNcaExtractionMainNcaNotFoundErrorMessage]);
  281. });
  282. return;
  283. }
  284. IntegrityCheckLevel checkLevel = ConfigurationState.Instance.System.EnableFsIntegrityChecks
  285. ? IntegrityCheckLevel.ErrorOnInvalid
  286. : IntegrityCheckLevel.None;
  287. int index = Nca.GetSectionIndexFromType(NcaSectionType.Data, publicDataNca.Header.ContentType);
  288. try
  289. {
  290. IFileSystem ncaFileSystem = publicDataNca.OpenFileSystem(index, IntegrityCheckLevel.ErrorOnInvalid);
  291. FileSystemClient fsClient = _horizonClient.Fs;
  292. string source = DateTime.Now.ToFileTime().ToString()[10..];
  293. string output = DateTime.Now.ToFileTime().ToString()[10..];
  294. using UniqueRef<IFileSystem> uniqueSourceFs = new(ncaFileSystem);
  295. using UniqueRef<IFileSystem> uniqueOutputFs = new(new LocalFileSystem(destination));
  296. fsClient.Register(source.ToU8Span(), ref uniqueSourceFs.Ref);
  297. fsClient.Register(output.ToU8Span(), ref uniqueOutputFs.Ref);
  298. (Result? resultCode, bool canceled) = CopyDirectory(fsClient, $"{source}:/", $"{output}:/", cancellationToken.Token);
  299. if (!canceled)
  300. {
  301. if (resultCode.Value.IsFailure())
  302. {
  303. Logger.Error?.Print(LogClass.Application, $"LibHac returned error code: {resultCode.Value.ErrorCode}");
  304. Dispatcher.UIThread.InvokeAsync(async () =>
  305. {
  306. waitingDialog.Close();
  307. await ContentDialogHelper.CreateErrorDialog(LocaleManager.Instance[LocaleKeys.DialogNcaExtractionCheckLogErrorMessage]);
  308. });
  309. }
  310. else if (resultCode.Value.IsSuccess())
  311. {
  312. Dispatcher.UIThread.Post(waitingDialog.Close);
  313. NotificationHelper.ShowInformation(
  314. RyujinxApp.FormatTitle(LocaleKeys.DialogNcaExtractionTitle),
  315. $"{updateName}\n\n{LocaleManager.Instance[LocaleKeys.DialogNcaExtractionSuccessMessage]}");
  316. }
  317. }
  318. fsClient.Unmount(source.ToU8Span());
  319. fsClient.Unmount(output.ToU8Span());
  320. }
  321. catch (ArgumentException ex)
  322. {
  323. Logger.Error?.Print(LogClass.Application, $"{ex.Message}");
  324. Dispatcher.UIThread.InvokeAsync(async () =>
  325. {
  326. waitingDialog.Close();
  327. await ContentDialogHelper.CreateErrorDialog(ex.Message);
  328. });
  329. }
  330. })
  331. {
  332. Name = "GUI.AocExtractorThread",
  333. IsBackground = true,
  334. };
  335. extractorThread.Start();
  336. }
  337. public static async Task ExtractAoc(IStorageProvider storageProvider, string updateFilePath, string updateName)
  338. {
  339. Optional<IStorageFolder> result = await storageProvider.OpenSingleFolderPickerAsync(new FolderPickerOpenOptions
  340. {
  341. Title = LocaleManager.Instance[LocaleKeys.FolderDialogExtractTitle]
  342. });
  343. if (!result.HasValue) return;
  344. ExtractAoc(result.Value.Path.LocalPath, updateFilePath, updateName);
  345. }
  346. public static async Task ExtractSection(IStorageProvider storageProvider, NcaSectionType ncaSectionType, string titleFilePath, string titleName, int programIndex = 0)
  347. {
  348. Optional<IStorageFolder> result = await storageProvider.OpenSingleFolderPickerAsync(new FolderPickerOpenOptions
  349. {
  350. Title = LocaleManager.Instance[LocaleKeys.FolderDialogExtractTitle]
  351. });
  352. if (!result.HasValue) return;
  353. ExtractSection(result.Value.Path.LocalPath, ncaSectionType, titleFilePath, titleName, programIndex);
  354. }
  355. public static (Result? result, bool canceled) CopyDirectory(FileSystemClient fs, string sourcePath, string destPath, CancellationToken token)
  356. {
  357. Result rc = fs.OpenDirectory(out DirectoryHandle sourceHandle, sourcePath.ToU8Span(), OpenDirectoryMode.All);
  358. if (rc.IsFailure())
  359. {
  360. return (rc, false);
  361. }
  362. using (sourceHandle)
  363. {
  364. foreach (DirectoryEntryEx entry in fs.EnumerateEntries(sourcePath, "*", SearchOptions.Default))
  365. {
  366. if (token.IsCancellationRequested)
  367. {
  368. return (null, true);
  369. }
  370. string subSrcPath = PathTools.Normalize(PathTools.Combine(sourcePath, entry.Name));
  371. string subDstPath = PathTools.Normalize(PathTools.Combine(destPath, entry.Name));
  372. if (entry.Type == DirectoryEntryType.Directory)
  373. {
  374. fs.EnsureDirectoryExists(subDstPath);
  375. (Result? result, bool canceled) = CopyDirectory(fs, subSrcPath, subDstPath, token);
  376. if (canceled || result.Value.IsFailure())
  377. {
  378. return (result, canceled);
  379. }
  380. }
  381. if (entry.Type == DirectoryEntryType.File)
  382. {
  383. fs.CreateOrOverwriteFile(subDstPath, entry.Size);
  384. rc = CopyFile(fs, subSrcPath, subDstPath);
  385. if (rc.IsFailure())
  386. {
  387. return (rc, false);
  388. }
  389. }
  390. }
  391. }
  392. return (Result.Success, false);
  393. }
  394. public static Result CopyFile(FileSystemClient fs, string sourcePath, string destPath)
  395. {
  396. Result rc = fs.OpenFile(out FileHandle sourceHandle, sourcePath.ToU8Span(), OpenMode.Read);
  397. if (rc.IsFailure())
  398. {
  399. return rc;
  400. }
  401. using (sourceHandle)
  402. {
  403. rc = fs.OpenFile(out FileHandle destHandle, destPath.ToU8Span(), OpenMode.Write | OpenMode.AllowAppend);
  404. if (rc.IsFailure())
  405. {
  406. return rc;
  407. }
  408. using (destHandle)
  409. {
  410. const int MaxBufferSize = 1024 * 1024;
  411. rc = fs.GetFileSize(out long fileSize, sourceHandle);
  412. if (rc.IsFailure())
  413. {
  414. return rc;
  415. }
  416. int bufferSize = (int)Math.Min(MaxBufferSize, fileSize);
  417. byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
  418. try
  419. {
  420. for (long offset = 0; offset < fileSize; offset += bufferSize)
  421. {
  422. int toRead = (int)Math.Min(fileSize - offset, bufferSize);
  423. Span<byte> buf = buffer.AsSpan(0, toRead);
  424. rc = fs.ReadFile(out long _, sourceHandle, offset, buf);
  425. if (rc.IsFailure())
  426. {
  427. return rc;
  428. }
  429. rc = fs.WriteFile(destHandle, offset, buf, WriteOption.None);
  430. if (rc.IsFailure())
  431. {
  432. return rc;
  433. }
  434. }
  435. }
  436. finally
  437. {
  438. ArrayPool<byte>.Shared.Return(buffer);
  439. }
  440. rc = fs.FlushFile(destHandle);
  441. if (rc.IsFailure())
  442. {
  443. return rc;
  444. }
  445. }
  446. }
  447. return Result.Success;
  448. }
  449. }
  450. }