ContentManager.cs 36 KB

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