ContentManager.cs 42 KB

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