ContentManager.cs 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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.HLE.Exceptions;
  13. using Ryujinx.HLE.HOS.Services.Ssl;
  14. using Ryujinx.HLE.HOS.Services.Time;
  15. using Ryujinx.HLE.Utilities;
  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.Content
  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 = LocationHelper.GetContentRoot(storageId);
  96. contentDirectory = LocationHelper.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 new UInt128(_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 ?
  300. LocationHelper.GetStorageId(locationEntry.ContentPath) : StorageId.None;
  301. }
  302. }
  303. public string GetInstalledContentPath(ulong titleId, StorageId storageId, NcaContentType contentType)
  304. {
  305. lock (_lock)
  306. {
  307. LocationEntry locationEntry = GetLocation(titleId, contentType, storageId);
  308. if (VerifyContentType(locationEntry, contentType))
  309. {
  310. return locationEntry.ContentPath;
  311. }
  312. }
  313. return string.Empty;
  314. }
  315. public void RedirectLocation(LocationEntry newEntry, StorageId storageId)
  316. {
  317. lock (_lock)
  318. {
  319. LocationEntry locationEntry = GetLocation(newEntry.TitleId, newEntry.ContentType, storageId);
  320. if (locationEntry.ContentPath != null)
  321. {
  322. RemoveLocationEntry(newEntry.TitleId, newEntry.ContentType, storageId);
  323. }
  324. AddLocationEntry(newEntry, storageId);
  325. }
  326. }
  327. private bool VerifyContentType(LocationEntry locationEntry, NcaContentType contentType)
  328. {
  329. if (locationEntry.ContentPath == null)
  330. {
  331. return false;
  332. }
  333. string installedPath = _virtualFileSystem.SwitchPathToSystemPath(locationEntry.ContentPath);
  334. if (!string.IsNullOrWhiteSpace(installedPath))
  335. {
  336. if (File.Exists(installedPath))
  337. {
  338. using (FileStream file = new FileStream(installedPath, FileMode.Open, FileAccess.Read))
  339. {
  340. Nca nca = new Nca(_virtualFileSystem.KeySet, file.AsStorage());
  341. bool contentCheck = nca.Header.ContentType == contentType;
  342. return contentCheck;
  343. }
  344. }
  345. }
  346. return false;
  347. }
  348. private void AddLocationEntry(LocationEntry entry, StorageId storageId)
  349. {
  350. LinkedList<LocationEntry> locationList = null;
  351. if (_locationEntries.ContainsKey(storageId))
  352. {
  353. locationList = _locationEntries[storageId];
  354. }
  355. if (locationList != null)
  356. {
  357. if (locationList.Contains(entry))
  358. {
  359. locationList.Remove(entry);
  360. }
  361. locationList.AddLast(entry);
  362. }
  363. }
  364. private void RemoveLocationEntry(ulong titleId, NcaContentType contentType, StorageId storageId)
  365. {
  366. LinkedList<LocationEntry> locationList = null;
  367. if (_locationEntries.ContainsKey(storageId))
  368. {
  369. locationList = _locationEntries[storageId];
  370. }
  371. if (locationList != null)
  372. {
  373. LocationEntry entry =
  374. locationList.ToList().Find(x => x.TitleId == titleId && x.ContentType == contentType);
  375. if (entry.ContentPath != null)
  376. {
  377. locationList.Remove(entry);
  378. }
  379. }
  380. }
  381. public bool TryGetFontTitle(string fontName, out ulong titleId)
  382. {
  383. return _sharedFontTitleDictionary.TryGetValue(fontName, out titleId);
  384. }
  385. public bool TryGetFontFilename(string fontName, out string filename)
  386. {
  387. return _sharedFontFilenameDictionary.TryGetValue(fontName, out filename);
  388. }
  389. public bool TryGetSystemTitlesName(ulong titleId, out string name)
  390. {
  391. return _systemTitlesNameDictionary.TryGetValue(titleId, out name);
  392. }
  393. private LocationEntry GetLocation(ulong titleId, NcaContentType contentType, StorageId storageId)
  394. {
  395. LinkedList<LocationEntry> locationList = _locationEntries[storageId];
  396. return locationList.ToList().Find(x => x.TitleId == titleId && x.ContentType == contentType);
  397. }
  398. public void InstallFirmware(string firmwareSource)
  399. {
  400. string contentPathString = LocationHelper.GetContentRoot(StorageId.NandSystem);
  401. string contentDirectory = LocationHelper.GetRealPath(_virtualFileSystem, contentPathString);
  402. string registeredDirectory = Path.Combine(contentDirectory, "registered");
  403. string temporaryDirectory = Path.Combine(contentDirectory, "temp");
  404. if (Directory.Exists(temporaryDirectory))
  405. {
  406. Directory.Delete(temporaryDirectory, true);
  407. }
  408. if (Directory.Exists(firmwareSource))
  409. {
  410. InstallFromDirectory(firmwareSource, temporaryDirectory);
  411. FinishInstallation(temporaryDirectory, registeredDirectory);
  412. return;
  413. }
  414. if (!File.Exists(firmwareSource))
  415. {
  416. throw new FileNotFoundException("Firmware file does not exist.");
  417. }
  418. FileInfo info = new FileInfo(firmwareSource);
  419. using (FileStream file = File.OpenRead(firmwareSource))
  420. {
  421. switch (info.Extension)
  422. {
  423. case ".zip":
  424. using (ZipArchive archive = ZipFile.OpenRead(firmwareSource))
  425. {
  426. InstallFromZip(archive, temporaryDirectory);
  427. }
  428. break;
  429. case ".xci":
  430. Xci xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage());
  431. InstallFromCart(xci, temporaryDirectory);
  432. break;
  433. default:
  434. throw new InvalidFirmwarePackageException("Input file is not a valid firmware package");
  435. }
  436. FinishInstallation(temporaryDirectory, registeredDirectory);
  437. }
  438. }
  439. private void FinishInstallation(string temporaryDirectory, string registeredDirectory)
  440. {
  441. if (Directory.Exists(registeredDirectory))
  442. {
  443. new DirectoryInfo(registeredDirectory).Delete(true);
  444. }
  445. Directory.Move(temporaryDirectory, registeredDirectory);
  446. LoadEntries();
  447. }
  448. private void InstallFromDirectory(string firmwareDirectory, string temporaryDirectory)
  449. {
  450. InstallFromPartition(new LocalFileSystem(firmwareDirectory), temporaryDirectory);
  451. }
  452. private void InstallFromPartition(IFileSystem filesystem, string temporaryDirectory)
  453. {
  454. foreach (var entry in filesystem.EnumerateEntries("/", "*.nca"))
  455. {
  456. Nca nca = new Nca(_virtualFileSystem.KeySet, OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage());
  457. SaveNca(nca, entry.Name.Remove(entry.Name.IndexOf('.')), temporaryDirectory);
  458. }
  459. }
  460. private void InstallFromCart(Xci gameCard, string temporaryDirectory)
  461. {
  462. if (gameCard.HasPartition(XciPartitionType.Update))
  463. {
  464. XciPartition partition = gameCard.OpenPartition(XciPartitionType.Update);
  465. InstallFromPartition(partition, temporaryDirectory);
  466. }
  467. else
  468. {
  469. throw new Exception("Update not found in xci file.");
  470. }
  471. }
  472. private void InstallFromZip(ZipArchive archive, string temporaryDirectory)
  473. {
  474. using (archive)
  475. {
  476. foreach (var entry in archive.Entries)
  477. {
  478. if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00"))
  479. {
  480. // Clean up the name and get the NcaId
  481. string[] pathComponents = entry.FullName.Replace(".cnmt", "").Split('/');
  482. string ncaId = pathComponents[pathComponents.Length - 1];
  483. // If this is a fragmented nca, we need to get the previous element.GetZip
  484. if (ncaId.Equals("00"))
  485. {
  486. ncaId = pathComponents[pathComponents.Length - 2];
  487. }
  488. if (ncaId.Contains(".nca"))
  489. {
  490. string newPath = Path.Combine(temporaryDirectory, ncaId);
  491. Directory.CreateDirectory(newPath);
  492. entry.ExtractToFile(Path.Combine(newPath, "00"));
  493. }
  494. }
  495. }
  496. }
  497. }
  498. public void SaveNca(Nca nca, string ncaId, string temporaryDirectory)
  499. {
  500. string newPath = Path.Combine(temporaryDirectory, ncaId + ".nca");
  501. Directory.CreateDirectory(newPath);
  502. using (FileStream file = File.Create(Path.Combine(newPath, "00")))
  503. {
  504. nca.BaseStorage.AsStream().CopyTo(file);
  505. }
  506. }
  507. private IFile OpenPossibleFragmentedFile(IFileSystem filesystem, string path, OpenMode mode)
  508. {
  509. using var file = new UniqueRef<IFile>();
  510. if (filesystem.FileExists($"{path}/00"))
  511. {
  512. filesystem.OpenFile(ref file.Ref(), $"{path}/00".ToU8Span(), mode);
  513. }
  514. else
  515. {
  516. filesystem.OpenFile(ref file.Ref(), path.ToU8Span(), mode);
  517. }
  518. return file.Release();
  519. }
  520. private Stream GetZipStream(ZipArchiveEntry entry)
  521. {
  522. MemoryStream dest = new MemoryStream();
  523. Stream src = entry.Open();
  524. src.CopyTo(dest);
  525. src.Dispose();
  526. return dest;
  527. }
  528. public SystemVersion VerifyFirmwarePackage(string firmwarePackage)
  529. {
  530. _virtualFileSystem.ReloadKeySet();
  531. // LibHac.NcaHeader's DecryptHeader doesn't check if HeaderKey is empty and throws InvalidDataException instead
  532. // So, we check it early for a better user experience.
  533. if (_virtualFileSystem.KeySet.HeaderKey.IsZeros())
  534. {
  535. throw new MissingKeyException("HeaderKey is empty. Cannot decrypt NCA headers.");
  536. }
  537. Dictionary<ulong, List<(NcaContentType type, string path)>> updateNcas = new Dictionary<ulong, List<(NcaContentType, string)>>();
  538. if (Directory.Exists(firmwarePackage))
  539. {
  540. return VerifyAndGetVersionDirectory(firmwarePackage);
  541. }
  542. if (!File.Exists(firmwarePackage))
  543. {
  544. throw new FileNotFoundException("Firmware file does not exist.");
  545. }
  546. FileInfo info = new FileInfo(firmwarePackage);
  547. using (FileStream file = File.OpenRead(firmwarePackage))
  548. {
  549. switch (info.Extension)
  550. {
  551. case ".zip":
  552. using (ZipArchive archive = ZipFile.OpenRead(firmwarePackage))
  553. {
  554. return VerifyAndGetVersionZip(archive);
  555. }
  556. case ".xci":
  557. Xci xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage());
  558. if (xci.HasPartition(XciPartitionType.Update))
  559. {
  560. XciPartition partition = xci.OpenPartition(XciPartitionType.Update);
  561. return VerifyAndGetVersion(partition);
  562. }
  563. else
  564. {
  565. throw new InvalidFirmwarePackageException("Update not found in xci file.");
  566. }
  567. default:
  568. break;
  569. }
  570. }
  571. SystemVersion VerifyAndGetVersionDirectory(string firmwareDirectory)
  572. {
  573. return VerifyAndGetVersion(new LocalFileSystem(firmwareDirectory));
  574. }
  575. SystemVersion VerifyAndGetVersionZip(ZipArchive archive)
  576. {
  577. SystemVersion systemVersion = null;
  578. foreach (var entry in archive.Entries)
  579. {
  580. if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00"))
  581. {
  582. using (Stream ncaStream = GetZipStream(entry))
  583. {
  584. IStorage storage = ncaStream.AsStorage();
  585. Nca nca = new Nca(_virtualFileSystem.KeySet, storage);
  586. if (updateNcas.ContainsKey(nca.Header.TitleId))
  587. {
  588. updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullName));
  589. }
  590. else
  591. {
  592. updateNcas.Add(nca.Header.TitleId, new List<(NcaContentType, string)>());
  593. updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullName));
  594. }
  595. }
  596. }
  597. }
  598. if (updateNcas.ContainsKey(SystemUpdateTitleId))
  599. {
  600. var ncaEntry = updateNcas[SystemUpdateTitleId];
  601. string metaPath = ncaEntry.Find(x => x.type == NcaContentType.Meta).path;
  602. CnmtContentMetaEntry[] metaEntries = null;
  603. var fileEntry = archive.GetEntry(metaPath);
  604. using (Stream ncaStream = GetZipStream(fileEntry))
  605. {
  606. Nca metaNca = new Nca(_virtualFileSystem.KeySet, ncaStream.AsStorage());
  607. IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  608. string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
  609. using var metaFile = new UniqueRef<IFile>();
  610. if (fs.OpenFile(ref metaFile.Ref(), cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  611. {
  612. var meta = new Cnmt(metaFile.Get.AsStream());
  613. if (meta.Type == ContentMetaType.SystemUpdate)
  614. {
  615. metaEntries = meta.MetaEntries;
  616. updateNcas.Remove(SystemUpdateTitleId);
  617. };
  618. }
  619. }
  620. if (metaEntries == null)
  621. {
  622. throw new FileNotFoundException("System update title was not found in the firmware package.");
  623. }
  624. if (updateNcas.ContainsKey(SystemVersionTitleId))
  625. {
  626. string versionEntry = updateNcas[SystemVersionTitleId].Find(x => x.type != NcaContentType.Meta).path;
  627. using (Stream ncaStream = GetZipStream(archive.GetEntry(versionEntry)))
  628. {
  629. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaStream.AsStorage());
  630. var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  631. using var systemVersionFile = new UniqueRef<IFile>();
  632. if (romfs.OpenFile(ref systemVersionFile.Ref(), "/file".ToU8Span(), OpenMode.Read).IsSuccess())
  633. {
  634. systemVersion = new SystemVersion(systemVersionFile.Get.AsStream());
  635. }
  636. }
  637. }
  638. foreach (CnmtContentMetaEntry metaEntry in metaEntries)
  639. {
  640. if (updateNcas.TryGetValue(metaEntry.TitleId, out ncaEntry))
  641. {
  642. metaPath = ncaEntry.Find(x => x.type == NcaContentType.Meta).path;
  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. ZipArchiveEntry metaZipEntry = archive.GetEntry(metaPath);
  652. ZipArchiveEntry contentZipEntry = archive.GetEntry(contentPath);
  653. using (Stream metaNcaStream = GetZipStream(metaZipEntry))
  654. {
  655. using (Stream contentNcaStream = GetZipStream(contentZipEntry))
  656. {
  657. Nca metaNca = new Nca(_virtualFileSystem.KeySet, metaNcaStream.AsStorage());
  658. IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  659. string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
  660. using var metaFile = new UniqueRef<IFile>();
  661. if (fs.OpenFile(ref metaFile.Ref(), cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  662. {
  663. var meta = new Cnmt(metaFile.Get.AsStream());
  664. IStorage contentStorage = contentNcaStream.AsStorage();
  665. if (contentStorage.GetSize(out long size).IsSuccess())
  666. {
  667. byte[] contentData = new byte[size];
  668. Span<byte> content = new Span<byte>(contentData);
  669. contentStorage.Read(0, content);
  670. Span<byte> hash = new Span<byte>(new byte[32]);
  671. LibHac.Crypto.Sha256.GenerateSha256Hash(content, hash);
  672. if (LibHac.Common.Utilities.ArraysEqual(hash.ToArray(), meta.ContentEntries[0].Hash))
  673. {
  674. updateNcas.Remove(metaEntry.TitleId);
  675. }
  676. }
  677. }
  678. }
  679. }
  680. }
  681. }
  682. if (updateNcas.Count > 0)
  683. {
  684. string extraNcas = string.Empty;
  685. foreach (var entry in updateNcas)
  686. {
  687. foreach (var nca in entry.Value)
  688. {
  689. extraNcas += nca.path + Environment.NewLine;
  690. }
  691. }
  692. throw new InvalidFirmwarePackageException($"Firmware package contains unrelated archives. Please remove these paths: {Environment.NewLine}{extraNcas}");
  693. }
  694. }
  695. else
  696. {
  697. throw new FileNotFoundException("System update title was not found in the firmware package.");
  698. }
  699. return systemVersion;
  700. }
  701. SystemVersion VerifyAndGetVersion(IFileSystem filesystem)
  702. {
  703. SystemVersion systemVersion = null;
  704. CnmtContentMetaEntry[] metaEntries = null;
  705. foreach (var entry in filesystem.EnumerateEntries("/", "*.nca"))
  706. {
  707. IStorage ncaStorage = OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage();
  708. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaStorage);
  709. if (nca.Header.TitleId == SystemUpdateTitleId && nca.Header.ContentType == NcaContentType.Meta)
  710. {
  711. IFileSystem fs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  712. string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
  713. using var metaFile = new UniqueRef<IFile>();
  714. if (fs.OpenFile(ref metaFile.Ref(), cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  715. {
  716. var meta = new Cnmt(metaFile.Get.AsStream());
  717. if (meta.Type == ContentMetaType.SystemUpdate)
  718. {
  719. metaEntries = meta.MetaEntries;
  720. }
  721. };
  722. continue;
  723. }
  724. else if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data)
  725. {
  726. var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  727. using var systemVersionFile = new UniqueRef<IFile>();
  728. if (romfs.OpenFile(ref systemVersionFile.Ref(), "/file".ToU8Span(), OpenMode.Read).IsSuccess())
  729. {
  730. systemVersion = new SystemVersion(systemVersionFile.Get.AsStream());
  731. }
  732. }
  733. if (updateNcas.ContainsKey(nca.Header.TitleId))
  734. {
  735. updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullPath));
  736. }
  737. else
  738. {
  739. updateNcas.Add(nca.Header.TitleId, new List<(NcaContentType, string)>());
  740. updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullPath));
  741. }
  742. ncaStorage.Dispose();
  743. }
  744. if (metaEntries == null)
  745. {
  746. throw new FileNotFoundException("System update title was not found in the firmware package.");
  747. }
  748. foreach (CnmtContentMetaEntry metaEntry in metaEntries)
  749. {
  750. if (updateNcas.TryGetValue(metaEntry.TitleId, out var ncaEntry))
  751. {
  752. var metaNcaEntry = ncaEntry.Find(x => x.type == NcaContentType.Meta);
  753. string contentPath = ncaEntry.Find(x => x.type != NcaContentType.Meta).path;
  754. // Nintendo in 9.0.0, removed PPC and only kept the meta nca of it.
  755. // This is a perfect valid case, so we should just ignore the missing content nca and continue.
  756. if (contentPath == null)
  757. {
  758. updateNcas.Remove(metaEntry.TitleId);
  759. continue;
  760. }
  761. IStorage metaStorage = OpenPossibleFragmentedFile(filesystem, metaNcaEntry.path, OpenMode.Read).AsStorage();
  762. IStorage contentStorage = OpenPossibleFragmentedFile(filesystem, contentPath, OpenMode.Read).AsStorage();
  763. Nca metaNca = new Nca(_virtualFileSystem.KeySet, metaStorage);
  764. IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  765. string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
  766. using var metaFile = new UniqueRef<IFile>();
  767. if (fs.OpenFile(ref metaFile.Ref(), cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  768. {
  769. var meta = new Cnmt(metaFile.Get.AsStream());
  770. if (contentStorage.GetSize(out long size).IsSuccess())
  771. {
  772. byte[] contentData = new byte[size];
  773. Span<byte> content = new Span<byte>(contentData);
  774. contentStorage.Read(0, content);
  775. Span<byte> hash = new Span<byte>(new byte[32]);
  776. LibHac.Crypto.Sha256.GenerateSha256Hash(content, hash);
  777. if (LibHac.Common.Utilities.ArraysEqual(hash.ToArray(), meta.ContentEntries[0].Hash))
  778. {
  779. updateNcas.Remove(metaEntry.TitleId);
  780. }
  781. }
  782. }
  783. }
  784. }
  785. if (updateNcas.Count > 0)
  786. {
  787. string extraNcas = string.Empty;
  788. foreach (var entry in updateNcas)
  789. {
  790. foreach (var nca in entry.Value)
  791. {
  792. extraNcas += nca.path + Environment.NewLine;
  793. }
  794. }
  795. throw new InvalidFirmwarePackageException($"Firmware package contains unrelated archives. Please remove these paths: {Environment.NewLine}{extraNcas}");
  796. }
  797. return systemVersion;
  798. }
  799. return null;
  800. }
  801. public SystemVersion GetCurrentFirmwareVersion()
  802. {
  803. LoadEntries();
  804. lock (_lock)
  805. {
  806. var locationEnties = _locationEntries[StorageId.NandSystem];
  807. foreach (var entry in locationEnties)
  808. {
  809. if (entry.ContentType == NcaContentType.Data)
  810. {
  811. var path = _virtualFileSystem.SwitchPathToSystemPath(entry.ContentPath);
  812. using (FileStream fileStream = File.OpenRead(path))
  813. {
  814. Nca nca = new Nca(_virtualFileSystem.KeySet, fileStream.AsStorage());
  815. if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data)
  816. {
  817. var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  818. using var systemVersionFile = new UniqueRef<IFile>();
  819. if (romfs.OpenFile(ref systemVersionFile.Ref(), "/file".ToU8Span(), OpenMode.Read).IsSuccess())
  820. {
  821. return new SystemVersion(systemVersionFile.Get.AsStream());
  822. }
  823. }
  824. }
  825. }
  826. }
  827. }
  828. return null;
  829. }
  830. }
  831. }