ContentManager.cs 34 KB

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