ContentManager.cs 35 KB

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