ContentManager.cs 42 KB

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