ContentManager.cs 35 KB

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