ContentManager.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012
  1. using LibHac.Common;
  2. using LibHac.Common.Keys;
  3. using LibHac.Fs;
  4. using LibHac.Fs.Fsa;
  5. using LibHac.FsSystem;
  6. using LibHac.Ncm;
  7. using LibHac.Tools.Fs;
  8. using LibHac.Tools.FsSystem;
  9. using LibHac.Tools.FsSystem.NcaUtils;
  10. using LibHac.Tools.Ncm;
  11. using Ryujinx.Common.Logging;
  12. using Ryujinx.Common.Memory;
  13. using Ryujinx.Common.Utilities;
  14. using Ryujinx.HLE.Exceptions;
  15. using Ryujinx.HLE.HOS.Services.Ssl;
  16. using Ryujinx.HLE.HOS.Services.Time;
  17. using System;
  18. using System.Collections.Generic;
  19. using System.IO;
  20. using System.IO.Compression;
  21. using System.Linq;
  22. using System.Text;
  23. using Path = System.IO.Path;
  24. namespace Ryujinx.HLE.FileSystem
  25. {
  26. public class ContentManager
  27. {
  28. private const ulong SystemVersionTitleId = 0x0100000000000809;
  29. private const ulong SystemUpdateTitleId = 0x0100000000000816;
  30. private Dictionary<StorageId, LinkedList<LocationEntry>> _locationEntries;
  31. private readonly Dictionary<string, ulong> _sharedFontTitleDictionary;
  32. private readonly Dictionary<ulong, string> _systemTitlesNameDictionary;
  33. private readonly Dictionary<string, string> _sharedFontFilenameDictionary;
  34. private SortedDictionary<(ulong titleId, NcaContentType type), string> _contentDictionary;
  35. private readonly struct AocItem
  36. {
  37. public readonly string ContainerPath;
  38. public readonly string NcaPath;
  39. public AocItem(string containerPath, string ncaPath)
  40. {
  41. ContainerPath = containerPath;
  42. NcaPath = ncaPath;
  43. }
  44. }
  45. private SortedList<ulong, AocItem> AocData { get; }
  46. private readonly VirtualFileSystem _virtualFileSystem;
  47. private readonly object _lock = new();
  48. public ContentManager(VirtualFileSystem virtualFileSystem)
  49. {
  50. _contentDictionary = new SortedDictionary<(ulong, NcaContentType), string>();
  51. _locationEntries = new Dictionary<StorageId, LinkedList<LocationEntry>>();
  52. _sharedFontTitleDictionary = new Dictionary<string, ulong>
  53. {
  54. { "FontStandard", 0x0100000000000811 },
  55. { "FontChineseSimplified", 0x0100000000000814 },
  56. { "FontExtendedChineseSimplified", 0x0100000000000814 },
  57. { "FontKorean", 0x0100000000000812 },
  58. { "FontChineseTraditional", 0x0100000000000813 },
  59. { "FontNintendoExtended", 0x0100000000000810 },
  60. };
  61. _systemTitlesNameDictionary = new Dictionary<ulong, string>()
  62. {
  63. { 0x010000000000080E, "TimeZoneBinary" },
  64. { 0x0100000000000810, "FontNintendoExtension" },
  65. { 0x0100000000000811, "FontStandard" },
  66. { 0x0100000000000812, "FontKorean" },
  67. { 0x0100000000000813, "FontChineseTraditional" },
  68. { 0x0100000000000814, "FontChineseSimple" },
  69. };
  70. _sharedFontFilenameDictionary = new Dictionary<string, string>
  71. {
  72. { "FontStandard", "nintendo_udsg-r_std_003.bfttf" },
  73. { "FontChineseSimplified", "nintendo_udsg-r_org_zh-cn_003.bfttf" },
  74. { "FontExtendedChineseSimplified", "nintendo_udsg-r_ext_zh-cn_003.bfttf" },
  75. { "FontKorean", "nintendo_udsg-r_ko_003.bfttf" },
  76. { "FontChineseTraditional", "nintendo_udjxh-db_zh-tw_003.bfttf" },
  77. { "FontNintendoExtended", "nintendo_ext_003.bfttf" },
  78. };
  79. _virtualFileSystem = virtualFileSystem;
  80. AocData = new SortedList<ulong, AocItem>();
  81. }
  82. public void LoadEntries(Switch device = null)
  83. {
  84. lock (_lock)
  85. {
  86. _contentDictionary = new SortedDictionary<(ulong, NcaContentType), string>();
  87. _locationEntries = new Dictionary<StorageId, LinkedList<LocationEntry>>();
  88. foreach (StorageId storageId in Enum.GetValues<StorageId>())
  89. {
  90. string contentDirectory = null;
  91. string contentPathString = null;
  92. string registeredDirectory = null;
  93. try
  94. {
  95. contentPathString = ContentPath.GetContentPath(storageId);
  96. contentDirectory = ContentPath.GetRealPath(contentPathString);
  97. registeredDirectory = Path.Combine(contentDirectory, "registered");
  98. }
  99. catch (NotSupportedException)
  100. {
  101. continue;
  102. }
  103. Directory.CreateDirectory(registeredDirectory);
  104. LinkedList<LocationEntry> locationList = new();
  105. void AddEntry(LocationEntry entry)
  106. {
  107. locationList.AddLast(entry);
  108. }
  109. foreach (string directoryPath in Directory.EnumerateDirectories(registeredDirectory))
  110. {
  111. if (Directory.GetFiles(directoryPath).Length > 0)
  112. {
  113. string ncaName = new DirectoryInfo(directoryPath).Name.Replace(".nca", string.Empty);
  114. using FileStream ncaFile = File.OpenRead(Directory.GetFiles(directoryPath)[0]);
  115. Nca nca = new(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  116. string switchPath = contentPathString + ":/" + ncaFile.Name.Replace(contentDirectory, string.Empty).TrimStart(Path.DirectorySeparatorChar);
  117. // Change path format to switch's
  118. switchPath = switchPath.Replace('\\', '/');
  119. LocationEntry entry = new(switchPath, 0, nca.Header.TitleId, nca.Header.ContentType);
  120. AddEntry(entry);
  121. _contentDictionary.Add((nca.Header.TitleId, nca.Header.ContentType), ncaName);
  122. }
  123. }
  124. foreach (string filePath in Directory.EnumerateFiles(contentDirectory))
  125. {
  126. if (Path.GetExtension(filePath) == ".nca")
  127. {
  128. string ncaName = Path.GetFileNameWithoutExtension(filePath);
  129. using FileStream ncaFile = new(filePath, FileMode.Open, FileAccess.Read);
  130. Nca nca = new(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  131. string switchPath = contentPathString + ":/" + filePath.Replace(contentDirectory, string.Empty).TrimStart(Path.DirectorySeparatorChar);
  132. // Change path format to switch's
  133. switchPath = switchPath.Replace('\\', '/');
  134. LocationEntry entry = new(switchPath, 0, nca.Header.TitleId, nca.Header.ContentType);
  135. AddEntry(entry);
  136. _contentDictionary.Add((nca.Header.TitleId, nca.Header.ContentType), ncaName);
  137. }
  138. }
  139. if (_locationEntries.TryGetValue(storageId, out var locationEntriesItem) && locationEntriesItem?.Count == 0)
  140. {
  141. _locationEntries.Remove(storageId);
  142. }
  143. _locationEntries.TryAdd(storageId, locationList);
  144. }
  145. if (device != null)
  146. {
  147. TimeManager.Instance.InitializeTimeZone(device);
  148. BuiltInCertificateManager.Instance.Initialize(device);
  149. device.System.SharedFontManager.Initialize();
  150. }
  151. }
  152. }
  153. // fs must contain AOC nca files in its root
  154. public void AddAocData(IFileSystem fs, string containerPath, ulong aocBaseId, IntegrityCheckLevel integrityCheckLevel)
  155. {
  156. _virtualFileSystem.ImportTickets(fs);
  157. foreach (var ncaPath in fs.EnumerateEntries("*.cnmt.nca", SearchOptions.Default))
  158. {
  159. using var ncaFile = new UniqueRef<IFile>();
  160. fs.OpenFile(ref ncaFile.Ref, ncaPath.FullPath.ToU8Span(), OpenMode.Read);
  161. var nca = new Nca(_virtualFileSystem.KeySet, ncaFile.Get.AsStorage());
  162. if (nca.Header.ContentType != NcaContentType.Meta)
  163. {
  164. Logger.Warning?.Print(LogClass.Application, $"{ncaPath} is not a valid metadata file");
  165. continue;
  166. }
  167. using var pfs0 = nca.OpenFileSystem(0, integrityCheckLevel);
  168. using var cnmtFile = new UniqueRef<IFile>();
  169. pfs0.OpenFile(ref cnmtFile.Ref, pfs0.EnumerateEntries().Single().FullPath.ToU8Span(), OpenMode.Read);
  170. var cnmt = new Cnmt(cnmtFile.Get.AsStream());
  171. if (cnmt.Type != ContentMetaType.AddOnContent || (cnmt.TitleId & 0xFFFFFFFFFFFFE000) != aocBaseId)
  172. {
  173. continue;
  174. }
  175. string ncaId = Convert.ToHexString(cnmt.ContentEntries[0].NcaId).ToLower();
  176. AddAocItem(cnmt.TitleId, containerPath, $"{ncaId}.nca", true);
  177. }
  178. }
  179. public void AddAocItem(ulong titleId, string containerPath, string ncaPath, bool mergedToContainer = false)
  180. {
  181. // TODO: Check Aoc version.
  182. if (!AocData.TryAdd(titleId, new AocItem(containerPath, ncaPath)))
  183. {
  184. Logger.Warning?.Print(LogClass.Application, $"Duplicate AddOnContent detected. TitleId {titleId:X16}");
  185. }
  186. else
  187. {
  188. Logger.Info?.Print(LogClass.Application, $"Found AddOnContent with TitleId {titleId:X16}");
  189. if (!mergedToContainer)
  190. {
  191. using FileStream fileStream = File.OpenRead(containerPath);
  192. using PartitionFileSystem partitionFileSystem = new(fileStream.AsStorage());
  193. _virtualFileSystem.ImportTickets(partitionFileSystem);
  194. }
  195. }
  196. }
  197. public void ClearAocData() => AocData.Clear();
  198. public int GetAocCount() => AocData.Count;
  199. public IList<ulong> GetAocTitleIds() => AocData.Select(e => e.Key).ToList();
  200. public bool GetAocDataStorage(ulong aocTitleId, out IStorage aocStorage, IntegrityCheckLevel integrityCheckLevel)
  201. {
  202. aocStorage = null;
  203. if (AocData.TryGetValue(aocTitleId, out AocItem aoc))
  204. {
  205. var file = new FileStream(aoc.ContainerPath, FileMode.Open, FileAccess.Read);
  206. using var ncaFile = new UniqueRef<IFile>();
  207. PartitionFileSystem pfs;
  208. switch (Path.GetExtension(aoc.ContainerPath))
  209. {
  210. case ".xci":
  211. pfs = new Xci(_virtualFileSystem.KeySet, file.AsStorage()).OpenPartition(XciPartitionType.Secure);
  212. pfs.OpenFile(ref ncaFile.Ref, aoc.NcaPath.ToU8Span(), OpenMode.Read);
  213. break;
  214. case ".nsp":
  215. pfs = new PartitionFileSystem(file.AsStorage());
  216. pfs.OpenFile(ref ncaFile.Ref, aoc.NcaPath.ToU8Span(), OpenMode.Read);
  217. break;
  218. default:
  219. return false; // Print error?
  220. }
  221. aocStorage = new Nca(_virtualFileSystem.KeySet, ncaFile.Get.AsStorage()).OpenStorage(NcaSectionType.Data, integrityCheckLevel);
  222. return true;
  223. }
  224. return false;
  225. }
  226. public void ClearEntry(ulong titleId, NcaContentType contentType, StorageId storageId)
  227. {
  228. lock (_lock)
  229. {
  230. RemoveLocationEntry(titleId, contentType, storageId);
  231. }
  232. }
  233. public void RefreshEntries(StorageId storageId, int flag)
  234. {
  235. lock (_lock)
  236. {
  237. LinkedList<LocationEntry> locationList = _locationEntries[storageId];
  238. LinkedListNode<LocationEntry> locationEntry = locationList.First;
  239. while (locationEntry != null)
  240. {
  241. LinkedListNode<LocationEntry> nextLocationEntry = locationEntry.Next;
  242. if (locationEntry.Value.Flag == flag)
  243. {
  244. locationList.Remove(locationEntry.Value);
  245. }
  246. locationEntry = nextLocationEntry;
  247. }
  248. }
  249. }
  250. public bool HasNca(string ncaId, StorageId storageId)
  251. {
  252. lock (_lock)
  253. {
  254. if (_contentDictionary.ContainsValue(ncaId))
  255. {
  256. var content = _contentDictionary.FirstOrDefault(x => x.Value == ncaId);
  257. ulong titleId = content.Key.titleId;
  258. NcaContentType contentType = content.Key.type;
  259. StorageId storage = GetInstalledStorage(titleId, contentType, storageId);
  260. return storage == storageId;
  261. }
  262. }
  263. return false;
  264. }
  265. public UInt128 GetInstalledNcaId(ulong titleId, NcaContentType contentType)
  266. {
  267. lock (_lock)
  268. {
  269. if (_contentDictionary.TryGetValue((titleId, contentType), out var contentDictionaryItem))
  270. {
  271. return UInt128Utils.FromHex(contentDictionaryItem);
  272. }
  273. }
  274. return new UInt128();
  275. }
  276. public StorageId GetInstalledStorage(ulong titleId, NcaContentType contentType, StorageId storageId)
  277. {
  278. lock (_lock)
  279. {
  280. LocationEntry locationEntry = GetLocation(titleId, contentType, storageId);
  281. return locationEntry.ContentPath != null ? ContentPath.GetStorageId(locationEntry.ContentPath) : StorageId.None;
  282. }
  283. }
  284. public string GetInstalledContentPath(ulong titleId, StorageId storageId, NcaContentType contentType)
  285. {
  286. lock (_lock)
  287. {
  288. LocationEntry locationEntry = GetLocation(titleId, contentType, storageId);
  289. if (VerifyContentType(locationEntry, contentType))
  290. {
  291. return locationEntry.ContentPath;
  292. }
  293. }
  294. return string.Empty;
  295. }
  296. public void RedirectLocation(LocationEntry newEntry, StorageId storageId)
  297. {
  298. lock (_lock)
  299. {
  300. LocationEntry locationEntry = GetLocation(newEntry.TitleId, newEntry.ContentType, storageId);
  301. if (locationEntry.ContentPath != null)
  302. {
  303. RemoveLocationEntry(newEntry.TitleId, newEntry.ContentType, storageId);
  304. }
  305. AddLocationEntry(newEntry, storageId);
  306. }
  307. }
  308. private bool VerifyContentType(LocationEntry locationEntry, NcaContentType contentType)
  309. {
  310. if (locationEntry.ContentPath == null)
  311. {
  312. return false;
  313. }
  314. string installedPath = VirtualFileSystem.SwitchPathToSystemPath(locationEntry.ContentPath);
  315. if (!string.IsNullOrWhiteSpace(installedPath))
  316. {
  317. if (File.Exists(installedPath))
  318. {
  319. using FileStream file = new(installedPath, FileMode.Open, FileAccess.Read);
  320. Nca nca = new(_virtualFileSystem.KeySet, file.AsStorage());
  321. bool contentCheck = nca.Header.ContentType == contentType;
  322. return contentCheck;
  323. }
  324. }
  325. return false;
  326. }
  327. private void AddLocationEntry(LocationEntry entry, StorageId storageId)
  328. {
  329. LinkedList<LocationEntry> locationList = null;
  330. if (_locationEntries.TryGetValue(storageId, out LinkedList<LocationEntry> locationEntry))
  331. {
  332. locationList = locationEntry;
  333. }
  334. if (locationList != null)
  335. {
  336. if (locationList.Contains(entry))
  337. {
  338. locationList.Remove(entry);
  339. }
  340. locationList.AddLast(entry);
  341. }
  342. }
  343. private void RemoveLocationEntry(ulong titleId, NcaContentType contentType, StorageId storageId)
  344. {
  345. LinkedList<LocationEntry> locationList = null;
  346. if (_locationEntries.TryGetValue(storageId, out LinkedList<LocationEntry> locationEntry))
  347. {
  348. locationList = locationEntry;
  349. }
  350. if (locationList != null)
  351. {
  352. LocationEntry entry =
  353. locationList.ToList().Find(x => x.TitleId == titleId && x.ContentType == contentType);
  354. if (entry.ContentPath != null)
  355. {
  356. locationList.Remove(entry);
  357. }
  358. }
  359. }
  360. public bool TryGetFontTitle(string fontName, out ulong titleId)
  361. {
  362. return _sharedFontTitleDictionary.TryGetValue(fontName, out titleId);
  363. }
  364. public bool TryGetFontFilename(string fontName, out string filename)
  365. {
  366. return _sharedFontFilenameDictionary.TryGetValue(fontName, out filename);
  367. }
  368. public bool TryGetSystemTitlesName(ulong titleId, out string name)
  369. {
  370. return _systemTitlesNameDictionary.TryGetValue(titleId, out name);
  371. }
  372. private LocationEntry GetLocation(ulong titleId, NcaContentType contentType, StorageId storageId)
  373. {
  374. LinkedList<LocationEntry> locationList = _locationEntries[storageId];
  375. return locationList.ToList().Find(x => x.TitleId == titleId && x.ContentType == contentType);
  376. }
  377. public void InstallFirmware(string firmwareSource)
  378. {
  379. string contentPathString = ContentPath.GetContentPath(StorageId.BuiltInSystem);
  380. string contentDirectory = ContentPath.GetRealPath(contentPathString);
  381. string registeredDirectory = Path.Combine(contentDirectory, "registered");
  382. string temporaryDirectory = Path.Combine(contentDirectory, "temp");
  383. if (Directory.Exists(temporaryDirectory))
  384. {
  385. Directory.Delete(temporaryDirectory, true);
  386. }
  387. if (Directory.Exists(firmwareSource))
  388. {
  389. InstallFromDirectory(firmwareSource, temporaryDirectory);
  390. FinishInstallation(temporaryDirectory, registeredDirectory);
  391. return;
  392. }
  393. if (!File.Exists(firmwareSource))
  394. {
  395. throw new FileNotFoundException("Firmware file does not exist.");
  396. }
  397. FileInfo info = new(firmwareSource);
  398. using FileStream file = File.OpenRead(firmwareSource);
  399. switch (info.Extension)
  400. {
  401. case ".zip":
  402. using (ZipArchive archive = ZipFile.OpenRead(firmwareSource))
  403. {
  404. InstallFromZip(archive, temporaryDirectory);
  405. }
  406. break;
  407. case ".xci":
  408. Xci xci = new(_virtualFileSystem.KeySet, file.AsStorage());
  409. InstallFromCart(xci, temporaryDirectory);
  410. break;
  411. default:
  412. throw new InvalidFirmwarePackageException("Input file is not a valid firmware package");
  413. }
  414. FinishInstallation(temporaryDirectory, registeredDirectory);
  415. }
  416. private void FinishInstallation(string temporaryDirectory, string registeredDirectory)
  417. {
  418. if (Directory.Exists(registeredDirectory))
  419. {
  420. new DirectoryInfo(registeredDirectory).Delete(true);
  421. }
  422. Directory.Move(temporaryDirectory, registeredDirectory);
  423. LoadEntries();
  424. }
  425. private void InstallFromDirectory(string firmwareDirectory, string temporaryDirectory)
  426. {
  427. InstallFromPartition(new LocalFileSystem(firmwareDirectory), temporaryDirectory);
  428. }
  429. private void InstallFromPartition(IFileSystem filesystem, string temporaryDirectory)
  430. {
  431. foreach (var entry in filesystem.EnumerateEntries("/", "*.nca"))
  432. {
  433. Nca nca = new(_virtualFileSystem.KeySet, OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage());
  434. SaveNca(nca, entry.Name.Remove(entry.Name.IndexOf('.')), temporaryDirectory);
  435. }
  436. }
  437. private void InstallFromCart(Xci gameCard, string temporaryDirectory)
  438. {
  439. if (gameCard.HasPartition(XciPartitionType.Update))
  440. {
  441. XciPartition partition = gameCard.OpenPartition(XciPartitionType.Update);
  442. InstallFromPartition(partition, temporaryDirectory);
  443. }
  444. else
  445. {
  446. throw new Exception("Update not found in xci file.");
  447. }
  448. }
  449. private static void InstallFromZip(ZipArchive archive, string temporaryDirectory)
  450. {
  451. foreach (var entry in archive.Entries)
  452. {
  453. if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00"))
  454. {
  455. // Clean up the name and get the NcaId
  456. string[] pathComponents = entry.FullName.Replace(".cnmt", "").Split('/');
  457. string ncaId = pathComponents[^1];
  458. // If this is a fragmented nca, we need to get the previous element.GetZip
  459. if (ncaId.Equals("00"))
  460. {
  461. ncaId = pathComponents[^2];
  462. }
  463. if (ncaId.Contains(".nca"))
  464. {
  465. string newPath = Path.Combine(temporaryDirectory, ncaId);
  466. Directory.CreateDirectory(newPath);
  467. entry.ExtractToFile(Path.Combine(newPath, "00"));
  468. }
  469. }
  470. }
  471. }
  472. public static void SaveNca(Nca nca, string ncaId, string temporaryDirectory)
  473. {
  474. string newPath = Path.Combine(temporaryDirectory, ncaId + ".nca");
  475. Directory.CreateDirectory(newPath);
  476. using FileStream file = File.Create(Path.Combine(newPath, "00"));
  477. nca.BaseStorage.AsStream().CopyTo(file);
  478. }
  479. private static IFile OpenPossibleFragmentedFile(IFileSystem filesystem, string path, OpenMode mode)
  480. {
  481. using var file = new UniqueRef<IFile>();
  482. if (filesystem.FileExists($"{path}/00"))
  483. {
  484. filesystem.OpenFile(ref file.Ref, $"{path}/00".ToU8Span(), mode);
  485. }
  486. else
  487. {
  488. filesystem.OpenFile(ref file.Ref, path.ToU8Span(), mode);
  489. }
  490. return file.Release();
  491. }
  492. private static Stream GetZipStream(ZipArchiveEntry entry)
  493. {
  494. MemoryStream dest = MemoryStreamManager.Shared.GetStream();
  495. using Stream src = entry.Open();
  496. src.CopyTo(dest);
  497. return dest;
  498. }
  499. public SystemVersion VerifyFirmwarePackage(string firmwarePackage)
  500. {
  501. _virtualFileSystem.ReloadKeySet();
  502. // LibHac.NcaHeader's DecryptHeader doesn't check if HeaderKey is empty and throws InvalidDataException instead
  503. // So, we check it early for a better user experience.
  504. if (_virtualFileSystem.KeySet.HeaderKey.IsZeros())
  505. {
  506. throw new MissingKeyException("HeaderKey is empty. Cannot decrypt NCA headers.");
  507. }
  508. Dictionary<ulong, List<(NcaContentType type, string path)>> updateNcas = new();
  509. if (Directory.Exists(firmwarePackage))
  510. {
  511. return VerifyAndGetVersionDirectory(firmwarePackage);
  512. }
  513. if (!File.Exists(firmwarePackage))
  514. {
  515. throw new FileNotFoundException("Firmware file does not exist.");
  516. }
  517. FileInfo info = new(firmwarePackage);
  518. using FileStream file = File.OpenRead(firmwarePackage);
  519. switch (info.Extension)
  520. {
  521. case ".zip":
  522. using (ZipArchive archive = ZipFile.OpenRead(firmwarePackage))
  523. {
  524. return VerifyAndGetVersionZip(archive);
  525. }
  526. case ".xci":
  527. Xci xci = new(_virtualFileSystem.KeySet, file.AsStorage());
  528. if (xci.HasPartition(XciPartitionType.Update))
  529. {
  530. XciPartition partition = xci.OpenPartition(XciPartitionType.Update);
  531. return VerifyAndGetVersion(partition);
  532. }
  533. else
  534. {
  535. throw new InvalidFirmwarePackageException("Update not found in xci file.");
  536. }
  537. default:
  538. break;
  539. }
  540. SystemVersion VerifyAndGetVersionDirectory(string firmwareDirectory)
  541. {
  542. return VerifyAndGetVersion(new LocalFileSystem(firmwareDirectory));
  543. }
  544. SystemVersion VerifyAndGetVersionZip(ZipArchive archive)
  545. {
  546. SystemVersion systemVersion = null;
  547. foreach (var entry in archive.Entries)
  548. {
  549. if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00"))
  550. {
  551. using Stream ncaStream = GetZipStream(entry);
  552. IStorage storage = ncaStream.AsStorage();
  553. Nca nca = new(_virtualFileSystem.KeySet, storage);
  554. if (updateNcas.TryGetValue(nca.Header.TitleId, out var updateNcasItem))
  555. {
  556. updateNcasItem.Add((nca.Header.ContentType, entry.FullName));
  557. }
  558. else
  559. {
  560. updateNcas.Add(nca.Header.TitleId, new List<(NcaContentType, string)>());
  561. updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullName));
  562. }
  563. }
  564. }
  565. if (updateNcas.TryGetValue(SystemUpdateTitleId, out var ncaEntry))
  566. {
  567. string metaPath = ncaEntry.Find(x => x.type == NcaContentType.Meta).path;
  568. CnmtContentMetaEntry[] metaEntries = null;
  569. var fileEntry = archive.GetEntry(metaPath);
  570. using (Stream ncaStream = GetZipStream(fileEntry))
  571. {
  572. Nca metaNca = new(_virtualFileSystem.KeySet, ncaStream.AsStorage());
  573. IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  574. string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
  575. using var metaFile = new UniqueRef<IFile>();
  576. if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  577. {
  578. var meta = new Cnmt(metaFile.Get.AsStream());
  579. if (meta.Type == ContentMetaType.SystemUpdate)
  580. {
  581. metaEntries = meta.MetaEntries;
  582. updateNcas.Remove(SystemUpdateTitleId);
  583. }
  584. }
  585. }
  586. if (metaEntries == null)
  587. {
  588. throw new FileNotFoundException("System update title was not found in the firmware package.");
  589. }
  590. if (updateNcas.TryGetValue(SystemVersionTitleId, out var updateNcasItem))
  591. {
  592. string versionEntry = updateNcasItem.Find(x => x.type != NcaContentType.Meta).path;
  593. using Stream ncaStream = GetZipStream(archive.GetEntry(versionEntry));
  594. Nca nca = new(_virtualFileSystem.KeySet, ncaStream.AsStorage());
  595. var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  596. using var systemVersionFile = new UniqueRef<IFile>();
  597. if (romfs.OpenFile(ref systemVersionFile.Ref, "/file".ToU8Span(), OpenMode.Read).IsSuccess())
  598. {
  599. systemVersion = new SystemVersion(systemVersionFile.Get.AsStream());
  600. }
  601. }
  602. foreach (CnmtContentMetaEntry metaEntry in metaEntries)
  603. {
  604. if (updateNcas.TryGetValue(metaEntry.TitleId, out ncaEntry))
  605. {
  606. metaPath = ncaEntry.Find(x => x.type == NcaContentType.Meta).path;
  607. string contentPath = ncaEntry.Find(x => x.type != NcaContentType.Meta).path;
  608. // Nintendo in 9.0.0, removed PPC and only kept the meta nca of it.
  609. // This is a perfect valid case, so we should just ignore the missing content nca and continue.
  610. if (contentPath == null)
  611. {
  612. updateNcas.Remove(metaEntry.TitleId);
  613. continue;
  614. }
  615. ZipArchiveEntry metaZipEntry = archive.GetEntry(metaPath);
  616. ZipArchiveEntry contentZipEntry = archive.GetEntry(contentPath);
  617. using Stream metaNcaStream = GetZipStream(metaZipEntry);
  618. using Stream contentNcaStream = GetZipStream(contentZipEntry);
  619. Nca metaNca = new(_virtualFileSystem.KeySet, metaNcaStream.AsStorage());
  620. IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  621. string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
  622. using var metaFile = new UniqueRef<IFile>();
  623. if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  624. {
  625. var meta = new Cnmt(metaFile.Get.AsStream());
  626. IStorage contentStorage = contentNcaStream.AsStorage();
  627. if (contentStorage.GetSize(out long size).IsSuccess())
  628. {
  629. byte[] contentData = new byte[size];
  630. Span<byte> content = new(contentData);
  631. contentStorage.Read(0, content);
  632. Span<byte> hash = new(new byte[32]);
  633. LibHac.Crypto.Sha256.GenerateSha256Hash(content, hash);
  634. if (LibHac.Common.Utilities.ArraysEqual(hash.ToArray(), meta.ContentEntries[0].Hash))
  635. {
  636. updateNcas.Remove(metaEntry.TitleId);
  637. }
  638. }
  639. }
  640. }
  641. }
  642. if (updateNcas.Count > 0)
  643. {
  644. StringBuilder extraNcas = new();
  645. foreach (var entry in updateNcas)
  646. {
  647. foreach (var (type, path) in entry.Value)
  648. {
  649. extraNcas.AppendLine(path);
  650. }
  651. }
  652. throw new InvalidFirmwarePackageException($"Firmware package contains unrelated archives. Please remove these paths: {Environment.NewLine}{extraNcas}");
  653. }
  654. }
  655. else
  656. {
  657. throw new FileNotFoundException("System update title was not found in the firmware package.");
  658. }
  659. return systemVersion;
  660. }
  661. SystemVersion VerifyAndGetVersion(IFileSystem filesystem)
  662. {
  663. SystemVersion systemVersion = null;
  664. CnmtContentMetaEntry[] metaEntries = null;
  665. foreach (var entry in filesystem.EnumerateEntries("/", "*.nca"))
  666. {
  667. IStorage ncaStorage = OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage();
  668. Nca nca = new(_virtualFileSystem.KeySet, ncaStorage);
  669. if (nca.Header.TitleId == SystemUpdateTitleId && nca.Header.ContentType == NcaContentType.Meta)
  670. {
  671. IFileSystem fs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  672. string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
  673. using var metaFile = new UniqueRef<IFile>();
  674. if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  675. {
  676. var meta = new Cnmt(metaFile.Get.AsStream());
  677. if (meta.Type == ContentMetaType.SystemUpdate)
  678. {
  679. metaEntries = meta.MetaEntries;
  680. }
  681. }
  682. continue;
  683. }
  684. else if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data)
  685. {
  686. var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  687. using var systemVersionFile = new UniqueRef<IFile>();
  688. if (romfs.OpenFile(ref systemVersionFile.Ref, "/file".ToU8Span(), OpenMode.Read).IsSuccess())
  689. {
  690. systemVersion = new SystemVersion(systemVersionFile.Get.AsStream());
  691. }
  692. }
  693. if (updateNcas.TryGetValue(nca.Header.TitleId, out var updateNcasItem))
  694. {
  695. updateNcasItem.Add((nca.Header.ContentType, entry.FullPath));
  696. }
  697. else
  698. {
  699. updateNcas.Add(nca.Header.TitleId, new List<(NcaContentType, string)>());
  700. updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullPath));
  701. }
  702. ncaStorage.Dispose();
  703. }
  704. if (metaEntries == null)
  705. {
  706. throw new FileNotFoundException("System update title was not found in the firmware package.");
  707. }
  708. foreach (CnmtContentMetaEntry metaEntry in metaEntries)
  709. {
  710. if (updateNcas.TryGetValue(metaEntry.TitleId, out var ncaEntry))
  711. {
  712. string metaNcaPath = ncaEntry.Find(x => x.type == NcaContentType.Meta).path;
  713. string contentPath = ncaEntry.Find(x => x.type != NcaContentType.Meta).path;
  714. // Nintendo in 9.0.0, removed PPC and only kept the meta nca of it.
  715. // This is a perfect valid case, so we should just ignore the missing content nca and continue.
  716. if (contentPath == null)
  717. {
  718. updateNcas.Remove(metaEntry.TitleId);
  719. continue;
  720. }
  721. IStorage metaStorage = OpenPossibleFragmentedFile(filesystem, metaNcaPath, OpenMode.Read).AsStorage();
  722. IStorage contentStorage = OpenPossibleFragmentedFile(filesystem, contentPath, OpenMode.Read).AsStorage();
  723. Nca metaNca = new(_virtualFileSystem.KeySet, metaStorage);
  724. IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  725. string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
  726. using var metaFile = new UniqueRef<IFile>();
  727. if (fs.OpenFile(ref metaFile.Ref, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  728. {
  729. var meta = new Cnmt(metaFile.Get.AsStream());
  730. if (contentStorage.GetSize(out long size).IsSuccess())
  731. {
  732. byte[] contentData = new byte[size];
  733. Span<byte> content = new(contentData);
  734. contentStorage.Read(0, content);
  735. Span<byte> hash = new(new byte[32]);
  736. LibHac.Crypto.Sha256.GenerateSha256Hash(content, hash);
  737. if (LibHac.Common.Utilities.ArraysEqual(hash.ToArray(), meta.ContentEntries[0].Hash))
  738. {
  739. updateNcas.Remove(metaEntry.TitleId);
  740. }
  741. }
  742. }
  743. }
  744. }
  745. if (updateNcas.Count > 0)
  746. {
  747. StringBuilder extraNcas = new();
  748. foreach (var entry in updateNcas)
  749. {
  750. foreach (var (type, path) in entry.Value)
  751. {
  752. extraNcas.AppendLine(path);
  753. }
  754. }
  755. throw new InvalidFirmwarePackageException($"Firmware package contains unrelated archives. Please remove these paths: {Environment.NewLine}{extraNcas}");
  756. }
  757. return systemVersion;
  758. }
  759. return null;
  760. }
  761. public SystemVersion GetCurrentFirmwareVersion()
  762. {
  763. LoadEntries();
  764. lock (_lock)
  765. {
  766. var locationEnties = _locationEntries[StorageId.BuiltInSystem];
  767. foreach (var entry in locationEnties)
  768. {
  769. if (entry.ContentType == NcaContentType.Data)
  770. {
  771. var path = VirtualFileSystem.SwitchPathToSystemPath(entry.ContentPath);
  772. using FileStream fileStream = File.OpenRead(path);
  773. Nca nca = new(_virtualFileSystem.KeySet, fileStream.AsStorage());
  774. if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data)
  775. {
  776. var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  777. using var systemVersionFile = new UniqueRef<IFile>();
  778. if (romfs.OpenFile(ref systemVersionFile.Ref, "/file".ToU8Span(), OpenMode.Read).IsSuccess())
  779. {
  780. return new SystemVersion(systemVersionFile.Get.AsStream());
  781. }
  782. }
  783. }
  784. }
  785. }
  786. return null;
  787. }
  788. }
  789. }