ContentManager.cs 41 KB

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