ContentManager.cs 41 KB

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