ContentManager.cs 35 KB

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