ContentManager.cs 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. using LibHac;
  2. using LibHac.Common;
  3. using LibHac.Fs;
  4. using LibHac.FsSystem;
  5. using LibHac.FsSystem.NcaUtils;
  6. using LibHac.Ncm;
  7. using LibHac.Spl;
  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, long> _sharedFontTitleDictionary;
  25. private Dictionary<long, 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, long>
  48. {
  49. { "FontStandard", 0x0100000000000811 },
  50. { "FontChineseSimplified", 0x0100000000000814 },
  51. { "FontExtendedChineseSimplified", 0x0100000000000814 },
  52. { "FontKorean", 0x0100000000000812 },
  53. { "FontChineseTraditional", 0x0100000000000813 },
  54. { "FontNintendoExtended", 0x0100000000000810 }
  55. };
  56. _systemTitlesNameDictionary = new Dictionary<long, 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. (long)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. (long)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.Font.Initialize(this);
  157. }
  158. }
  159. }
  160. // fs must contain AOC nca files in its root
  161. public void AddAocData(IFileSystem fs, string containerPath, ulong aocBaseId)
  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.PrintWarning(LogClass.Application, $"{ncaPath} is not a valid metadata file");
  173. continue;
  174. }
  175. using var pfs0 = nca.OpenFileSystem(0, Switch.GetIntegrityCheckLevel());
  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.PrintWarning(LogClass.Application, $"Duplicate AddOnContent detected. TitleId {cnmt.TitleId:X16}");
  188. }
  189. else
  190. {
  191. Logger.PrintInfo(LogClass.Application, $"Found AddOnContent with TitleId {cnmt.TitleId:X16}");
  192. }
  193. }
  194. }
  195. }
  196. }
  197. public void ClearAocData() => _aocData.Clear();
  198. public int GetAocCount() => _aocData.Where(e => e.Value.Enabled).Count();
  199. public IList<ulong> GetAocTitleIds() => _aocData.Where(e => e.Value.Enabled).Select(e => e.Key).ToList();
  200. public bool GetAocDataStorage(ulong aocTitleId, out IStorage aocStorage)
  201. {
  202. aocStorage = null;
  203. if (_aocData.TryGetValue(aocTitleId, out AocItem aoc) && aoc.Enabled)
  204. {
  205. var file = new FileStream(aoc.ContainerPath, FileMode.Open, FileAccess.Read);
  206. PartitionFileSystem pfs;
  207. IFile ncaFile;
  208. switch (Path.GetExtension(aoc.ContainerPath))
  209. {
  210. case ".xci":
  211. pfs = new Xci(_virtualFileSystem.KeySet, file.AsStorage()).OpenPartition(XciPartitionType.Secure);
  212. pfs.OpenFile(out ncaFile, aoc.NcaPath.ToU8Span(), OpenMode.Read);
  213. break;
  214. case ".nsp":
  215. pfs = new PartitionFileSystem(file.AsStorage());
  216. pfs.OpenFile(out ncaFile, aoc.NcaPath.ToU8Span(), OpenMode.Read);
  217. break;
  218. default:
  219. return false; // Print error?
  220. }
  221. aocStorage = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage()).OpenStorage(NcaSectionType.Data, Switch.GetIntegrityCheckLevel());
  222. return true;
  223. }
  224. return false;
  225. }
  226. public void ClearEntry(long titleId, NcaContentType contentType, StorageId storageId)
  227. {
  228. lock (_lock)
  229. {
  230. RemoveLocationEntry(titleId, contentType, storageId);
  231. }
  232. }
  233. public void RefreshEntries(StorageId storageId, int flag)
  234. {
  235. lock (_lock)
  236. {
  237. LinkedList<LocationEntry> locationList = _locationEntries[storageId];
  238. LinkedListNode<LocationEntry> locationEntry = locationList.First;
  239. while (locationEntry != null)
  240. {
  241. LinkedListNode<LocationEntry> nextLocationEntry = locationEntry.Next;
  242. if (locationEntry.Value.Flag == flag)
  243. {
  244. locationList.Remove(locationEntry.Value);
  245. }
  246. locationEntry = nextLocationEntry;
  247. }
  248. }
  249. }
  250. public bool HasNca(string ncaId, StorageId storageId)
  251. {
  252. lock (_lock)
  253. {
  254. if (_contentDictionary.ContainsValue(ncaId))
  255. {
  256. var content = _contentDictionary.FirstOrDefault(x => x.Value == ncaId);
  257. long titleId = (long)content.Key.Item1;
  258. NcaContentType contentType = content.Key.type;
  259. StorageId storage = GetInstalledStorage(titleId, contentType, storageId);
  260. return storage == storageId;
  261. }
  262. }
  263. return false;
  264. }
  265. public UInt128 GetInstalledNcaId(long titleId, NcaContentType contentType)
  266. {
  267. lock (_lock)
  268. {
  269. if (_contentDictionary.ContainsKey(((ulong)titleId, contentType)))
  270. {
  271. return new UInt128(_contentDictionary[((ulong)titleId, contentType)]);
  272. }
  273. }
  274. return new UInt128();
  275. }
  276. public StorageId GetInstalledStorage(long titleId, NcaContentType contentType, StorageId storageId)
  277. {
  278. lock (_lock)
  279. {
  280. LocationEntry locationEntry = GetLocation(titleId, contentType, storageId);
  281. return locationEntry.ContentPath != null ?
  282. LocationHelper.GetStorageId(locationEntry.ContentPath) : StorageId.None;
  283. }
  284. }
  285. public string GetInstalledContentPath(long titleId, StorageId storageId, NcaContentType contentType)
  286. {
  287. lock (_lock)
  288. {
  289. LocationEntry locationEntry = GetLocation(titleId, contentType, storageId);
  290. if (VerifyContentType(locationEntry, contentType))
  291. {
  292. return locationEntry.ContentPath;
  293. }
  294. }
  295. return string.Empty;
  296. }
  297. public void RedirectLocation(LocationEntry newEntry, StorageId storageId)
  298. {
  299. lock (_lock)
  300. {
  301. LocationEntry locationEntry = GetLocation(newEntry.TitleId, newEntry.ContentType, storageId);
  302. if (locationEntry.ContentPath != null)
  303. {
  304. RemoveLocationEntry(newEntry.TitleId, newEntry.ContentType, storageId);
  305. }
  306. AddLocationEntry(newEntry, storageId);
  307. }
  308. }
  309. private bool VerifyContentType(LocationEntry locationEntry, NcaContentType contentType)
  310. {
  311. if (locationEntry.ContentPath == null)
  312. {
  313. return false;
  314. }
  315. string installedPath = _virtualFileSystem.SwitchPathToSystemPath(locationEntry.ContentPath);
  316. if (!string.IsNullOrWhiteSpace(installedPath))
  317. {
  318. if (File.Exists(installedPath))
  319. {
  320. using (FileStream file = new FileStream(installedPath, FileMode.Open, FileAccess.Read))
  321. {
  322. Nca nca = new Nca(_virtualFileSystem.KeySet, file.AsStorage());
  323. bool contentCheck = nca.Header.ContentType == contentType;
  324. return contentCheck;
  325. }
  326. }
  327. }
  328. return false;
  329. }
  330. private void AddLocationEntry(LocationEntry entry, StorageId storageId)
  331. {
  332. LinkedList<LocationEntry> locationList = null;
  333. if (_locationEntries.ContainsKey(storageId))
  334. {
  335. locationList = _locationEntries[storageId];
  336. }
  337. if (locationList != null)
  338. {
  339. if (locationList.Contains(entry))
  340. {
  341. locationList.Remove(entry);
  342. }
  343. locationList.AddLast(entry);
  344. }
  345. }
  346. private void RemoveLocationEntry(long titleId, NcaContentType contentType, 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. LocationEntry entry =
  356. locationList.ToList().Find(x => x.TitleId == titleId && x.ContentType == contentType);
  357. if (entry.ContentPath != null)
  358. {
  359. locationList.Remove(entry);
  360. }
  361. }
  362. }
  363. public bool TryGetFontTitle(string fontName, out long titleId)
  364. {
  365. return _sharedFontTitleDictionary.TryGetValue(fontName, out titleId);
  366. }
  367. public bool TryGetFontFilename(string fontName, out string filename)
  368. {
  369. return _sharedFontFilenameDictionary.TryGetValue(fontName, out filename);
  370. }
  371. public bool TryGetSystemTitlesName(long titleId, out string name)
  372. {
  373. return _systemTitlesNameDictionary.TryGetValue(titleId, out name);
  374. }
  375. private LocationEntry GetLocation(long titleId, NcaContentType contentType, StorageId storageId)
  376. {
  377. LinkedList<LocationEntry> locationList = _locationEntries[storageId];
  378. return locationList.ToList().Find(x => x.TitleId == titleId && x.ContentType == contentType);
  379. }
  380. public void InstallFirmware(string firmwareSource)
  381. {
  382. string contentPathString = LocationHelper.GetContentRoot(StorageId.NandSystem);
  383. string contentDirectory = LocationHelper.GetRealPath(_virtualFileSystem, contentPathString);
  384. string registeredDirectory = Path.Combine(contentDirectory, "registered");
  385. string temporaryDirectory = Path.Combine(contentDirectory, "temp");
  386. if (Directory.Exists(temporaryDirectory))
  387. {
  388. Directory.Delete(temporaryDirectory, true);
  389. }
  390. if (Directory.Exists(firmwareSource))
  391. {
  392. InstallFromDirectory(firmwareSource, temporaryDirectory);
  393. FinishInstallation(temporaryDirectory, registeredDirectory);
  394. return;
  395. }
  396. if (!File.Exists(firmwareSource))
  397. {
  398. throw new FileNotFoundException("Firmware file does not exist.");
  399. }
  400. FileInfo info = new FileInfo(firmwareSource);
  401. using (FileStream file = File.OpenRead(firmwareSource))
  402. {
  403. switch (info.Extension)
  404. {
  405. case ".zip":
  406. using (ZipArchive archive = ZipFile.OpenRead(firmwareSource))
  407. {
  408. InstallFromZip(archive, temporaryDirectory);
  409. }
  410. break;
  411. case ".xci":
  412. Xci xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage());
  413. InstallFromCart(xci, temporaryDirectory);
  414. break;
  415. default:
  416. throw new InvalidFirmwarePackageException("Input file is not a valid firmware package");
  417. }
  418. FinishInstallation(temporaryDirectory, registeredDirectory);
  419. }
  420. }
  421. private void FinishInstallation(string temporaryDirectory, string registeredDirectory)
  422. {
  423. if (Directory.Exists(registeredDirectory))
  424. {
  425. new DirectoryInfo(registeredDirectory).Delete(true);
  426. }
  427. Directory.Move(temporaryDirectory, registeredDirectory);
  428. LoadEntries();
  429. }
  430. private void InstallFromDirectory(string firmwareDirectory, string temporaryDirectory)
  431. {
  432. InstallFromPartition(new LocalFileSystem(firmwareDirectory), temporaryDirectory);
  433. }
  434. private void InstallFromPartition(IFileSystem filesystem, string temporaryDirectory)
  435. {
  436. foreach (var entry in filesystem.EnumerateEntries("/", "*.nca"))
  437. {
  438. Nca nca = new Nca(_virtualFileSystem.KeySet, OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage());
  439. SaveNca(nca, entry.Name.Remove(entry.Name.IndexOf('.')), temporaryDirectory);
  440. }
  441. }
  442. private void InstallFromCart(Xci gameCard, string temporaryDirectory)
  443. {
  444. if (gameCard.HasPartition(XciPartitionType.Update))
  445. {
  446. XciPartition partition = gameCard.OpenPartition(XciPartitionType.Update);
  447. InstallFromPartition(partition, temporaryDirectory);
  448. }
  449. else
  450. {
  451. throw new Exception("Update not found in xci file.");
  452. }
  453. }
  454. private void InstallFromZip(ZipArchive archive, string temporaryDirectory)
  455. {
  456. using (archive)
  457. {
  458. foreach (var entry in archive.Entries)
  459. {
  460. if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00"))
  461. {
  462. // Clean up the name and get the NcaId
  463. string[] pathComponents = entry.FullName.Replace(".cnmt", "").Split('/');
  464. string ncaId = pathComponents[pathComponents.Length - 1];
  465. // If this is a fragmented nca, we need to get the previous element.GetZip
  466. if (ncaId.Equals("00"))
  467. {
  468. ncaId = pathComponents[pathComponents.Length - 2];
  469. }
  470. if (ncaId.Contains(".nca"))
  471. {
  472. string newPath = Path.Combine(temporaryDirectory, ncaId);
  473. Directory.CreateDirectory(newPath);
  474. entry.ExtractToFile(Path.Combine(newPath, "00"));
  475. }
  476. }
  477. }
  478. }
  479. }
  480. public void SaveNca(Nca nca, string ncaId, string temporaryDirectory)
  481. {
  482. string newPath = Path.Combine(temporaryDirectory, ncaId + ".nca");
  483. Directory.CreateDirectory(newPath);
  484. using (FileStream file = File.Create(Path.Combine(newPath, "00")))
  485. {
  486. nca.BaseStorage.AsStream().CopyTo(file);
  487. }
  488. }
  489. private IFile OpenPossibleFragmentedFile(IFileSystem filesystem, string path, OpenMode mode)
  490. {
  491. IFile file;
  492. if (filesystem.FileExists($"{path}/00"))
  493. {
  494. filesystem.OpenFile(out file, $"{path}/00".ToU8Span(), mode);
  495. }
  496. else
  497. {
  498. filesystem.OpenFile(out file, path.ToU8Span(), mode);
  499. }
  500. return file;
  501. }
  502. private Stream GetZipStream(ZipArchiveEntry entry)
  503. {
  504. MemoryStream dest = new MemoryStream();
  505. Stream src = entry.Open();
  506. src.CopyTo(dest);
  507. src.Dispose();
  508. return dest;
  509. }
  510. public SystemVersion VerifyFirmwarePackage(string firmwarePackage)
  511. {
  512. Dictionary<ulong, List<(NcaContentType type, string path)>> updateNcas = new Dictionary<ulong, List<(NcaContentType, string)>>();
  513. if (Directory.Exists(firmwarePackage))
  514. {
  515. return VerifyAndGetVersionDirectory(firmwarePackage);
  516. }
  517. if (!File.Exists(firmwarePackage))
  518. {
  519. throw new FileNotFoundException("Firmware file does not exist.");
  520. }
  521. FileInfo info = new FileInfo(firmwarePackage);
  522. using (FileStream file = File.OpenRead(firmwarePackage))
  523. {
  524. switch (info.Extension)
  525. {
  526. case ".zip":
  527. using (ZipArchive archive = ZipFile.OpenRead(firmwarePackage))
  528. {
  529. return VerifyAndGetVersionZip(archive);
  530. }
  531. case ".xci":
  532. Xci xci = new Xci(_virtualFileSystem.KeySet, file.AsStorage());
  533. if (xci.HasPartition(XciPartitionType.Update))
  534. {
  535. XciPartition partition = xci.OpenPartition(XciPartitionType.Update);
  536. return VerifyAndGetVersion(partition);
  537. }
  538. else
  539. {
  540. throw new InvalidFirmwarePackageException("Update not found in xci file.");
  541. }
  542. default:
  543. break;
  544. }
  545. }
  546. SystemVersion VerifyAndGetVersionDirectory(string firmwareDirectory)
  547. {
  548. return VerifyAndGetVersion(new LocalFileSystem(firmwareDirectory));
  549. }
  550. SystemVersion VerifyAndGetVersionZip(ZipArchive archive)
  551. {
  552. IntegrityCheckLevel integrityCheckLevel = Switch.GetIntegrityCheckLevel();
  553. SystemVersion systemVersion = null;
  554. foreach (var entry in archive.Entries)
  555. {
  556. if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00"))
  557. {
  558. using (Stream ncaStream = GetZipStream(entry))
  559. {
  560. IStorage storage = ncaStream.AsStorage();
  561. Nca nca = new Nca(_virtualFileSystem.KeySet, storage);
  562. if (updateNcas.ContainsKey(nca.Header.TitleId))
  563. {
  564. updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullName));
  565. }
  566. else
  567. {
  568. updateNcas.Add(nca.Header.TitleId, new List<(NcaContentType, string)>());
  569. updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullName));
  570. }
  571. }
  572. }
  573. }
  574. if (updateNcas.ContainsKey(SystemUpdateTitleId))
  575. {
  576. var ncaEntry = updateNcas[SystemUpdateTitleId];
  577. string metaPath = ncaEntry.Find(x => x.type == NcaContentType.Meta).path;
  578. CnmtContentMetaEntry[] metaEntries = null;
  579. var fileEntry = archive.GetEntry(metaPath);
  580. using (Stream ncaStream = GetZipStream(fileEntry))
  581. {
  582. Nca metaNca = new Nca(_virtualFileSystem.KeySet, ncaStream.AsStorage());
  583. IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, integrityCheckLevel);
  584. string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
  585. if (fs.OpenFile(out IFile metaFile, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  586. {
  587. var meta = new Cnmt(metaFile.AsStream());
  588. if (meta.Type == ContentMetaType.SystemUpdate)
  589. {
  590. metaEntries = meta.MetaEntries;
  591. updateNcas.Remove(SystemUpdateTitleId);
  592. };
  593. }
  594. }
  595. if (metaEntries == null)
  596. {
  597. throw new FileNotFoundException("System update title was not found in the firmware package.");
  598. }
  599. if (updateNcas.ContainsKey(SystemVersionTitleId))
  600. {
  601. string versionEntry = updateNcas[SystemVersionTitleId].Find(x => x.type != NcaContentType.Meta).path;
  602. using (Stream ncaStream = GetZipStream(archive.GetEntry(versionEntry)))
  603. {
  604. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaStream.AsStorage());
  605. var romfs = nca.OpenFileSystem(NcaSectionType.Data, integrityCheckLevel);
  606. if (romfs.OpenFile(out IFile systemVersionFile, "/file".ToU8Span(), OpenMode.Read).IsSuccess())
  607. {
  608. systemVersion = new SystemVersion(systemVersionFile.AsStream());
  609. }
  610. }
  611. }
  612. foreach (CnmtContentMetaEntry metaEntry in metaEntries)
  613. {
  614. if (updateNcas.TryGetValue(metaEntry.TitleId, out ncaEntry))
  615. {
  616. metaPath = ncaEntry.Find(x => x.type == NcaContentType.Meta).path;
  617. string contentPath = ncaEntry.Find(x => x.type != NcaContentType.Meta).path;
  618. // Nintendo in 9.0.0, removed PPC and only kept the meta nca of it.
  619. // This is a perfect valid case, so we should just ignore the missing content nca and continue.
  620. if (contentPath == null)
  621. {
  622. updateNcas.Remove(metaEntry.TitleId);
  623. continue;
  624. }
  625. ZipArchiveEntry metaZipEntry = archive.GetEntry(metaPath);
  626. ZipArchiveEntry contentZipEntry = archive.GetEntry(contentPath);
  627. using (Stream metaNcaStream = GetZipStream(metaZipEntry))
  628. {
  629. using (Stream contentNcaStream = GetZipStream(contentZipEntry))
  630. {
  631. Nca metaNca = new Nca(_virtualFileSystem.KeySet, metaNcaStream.AsStorage());
  632. IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, integrityCheckLevel);
  633. string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
  634. if (fs.OpenFile(out IFile metaFile, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  635. {
  636. var meta = new Cnmt(metaFile.AsStream());
  637. IStorage contentStorage = contentNcaStream.AsStorage();
  638. if (contentStorage.GetSize(out long size).IsSuccess())
  639. {
  640. byte[] contentData = new byte[size];
  641. Span<byte> content = new Span<byte>(contentData);
  642. contentStorage.Read(0, content);
  643. Span<byte> hash = new Span<byte>(new byte[32]);
  644. LibHac.Crypto.Sha256.GenerateSha256Hash(content, hash);
  645. if (LibHac.Util.ArraysEqual(hash.ToArray(), meta.ContentEntries[0].Hash))
  646. {
  647. updateNcas.Remove(metaEntry.TitleId);
  648. }
  649. }
  650. }
  651. }
  652. }
  653. }
  654. }
  655. if (updateNcas.Count > 0)
  656. {
  657. string extraNcas = string.Empty;
  658. foreach (var entry in updateNcas)
  659. {
  660. foreach (var nca in entry.Value)
  661. {
  662. extraNcas += nca.path + Environment.NewLine;
  663. }
  664. }
  665. throw new InvalidFirmwarePackageException($"Firmware package contains unrelated archives. Please remove these paths: {Environment.NewLine}{extraNcas}");
  666. }
  667. }
  668. else
  669. {
  670. throw new FileNotFoundException("System update title was not found in the firmware package.");
  671. }
  672. return systemVersion;
  673. }
  674. SystemVersion VerifyAndGetVersion(IFileSystem filesystem)
  675. {
  676. IntegrityCheckLevel integrityCheckLevel = Switch.GetIntegrityCheckLevel();
  677. SystemVersion systemVersion = null;
  678. CnmtContentMetaEntry[] metaEntries = null;
  679. foreach (var entry in filesystem.EnumerateEntries("/", "*.nca"))
  680. {
  681. IStorage ncaStorage = OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage();
  682. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaStorage);
  683. if (nca.Header.TitleId == SystemUpdateTitleId && nca.Header.ContentType == NcaContentType.Meta)
  684. {
  685. IFileSystem fs = nca.OpenFileSystem(NcaSectionType.Data, integrityCheckLevel);
  686. string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
  687. if (fs.OpenFile(out IFile metaFile, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  688. {
  689. var meta = new Cnmt(metaFile.AsStream());
  690. if (meta.Type == ContentMetaType.SystemUpdate)
  691. {
  692. metaEntries = meta.MetaEntries;
  693. }
  694. };
  695. continue;
  696. }
  697. else if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data)
  698. {
  699. var romfs = nca.OpenFileSystem(NcaSectionType.Data, integrityCheckLevel);
  700. if (romfs.OpenFile(out IFile systemVersionFile, "/file".ToU8Span(), OpenMode.Read).IsSuccess())
  701. {
  702. systemVersion = new SystemVersion(systemVersionFile.AsStream());
  703. }
  704. }
  705. if (updateNcas.ContainsKey(nca.Header.TitleId))
  706. {
  707. updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullPath));
  708. }
  709. else
  710. {
  711. updateNcas.Add(nca.Header.TitleId, new List<(NcaContentType, string)>());
  712. updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullPath));
  713. }
  714. ncaStorage.Dispose();
  715. }
  716. if (metaEntries == null)
  717. {
  718. throw new FileNotFoundException("System update title was not found in the firmware package.");
  719. }
  720. foreach (CnmtContentMetaEntry metaEntry in metaEntries)
  721. {
  722. if (updateNcas.TryGetValue(metaEntry.TitleId, out var ncaEntry))
  723. {
  724. var metaNcaEntry = ncaEntry.Find(x => x.type == NcaContentType.Meta);
  725. string contentPath = ncaEntry.Find(x => x.type != NcaContentType.Meta).path;
  726. // Nintendo in 9.0.0, removed PPC and only kept the meta nca of it.
  727. // This is a perfect valid case, so we should just ignore the missing content nca and continue.
  728. if (contentPath == null)
  729. {
  730. updateNcas.Remove(metaEntry.TitleId);
  731. continue;
  732. }
  733. IStorage metaStorage = OpenPossibleFragmentedFile(filesystem, metaNcaEntry.path, OpenMode.Read).AsStorage();
  734. IStorage contentStorage = OpenPossibleFragmentedFile(filesystem, contentPath, OpenMode.Read).AsStorage();
  735. Nca metaNca = new Nca(_virtualFileSystem.KeySet, metaStorage);
  736. IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, integrityCheckLevel);
  737. string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
  738. if (fs.OpenFile(out IFile metaFile, cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  739. {
  740. var meta = new Cnmt(metaFile.AsStream());
  741. if (contentStorage.GetSize(out long size).IsSuccess())
  742. {
  743. byte[] contentData = new byte[size];
  744. Span<byte> content = new Span<byte>(contentData);
  745. contentStorage.Read(0, content);
  746. Span<byte> hash = new Span<byte>(new byte[32]);
  747. LibHac.Crypto.Sha256.GenerateSha256Hash(content, hash);
  748. if (LibHac.Util.ArraysEqual(hash.ToArray(), meta.ContentEntries[0].Hash))
  749. {
  750. updateNcas.Remove(metaEntry.TitleId);
  751. }
  752. }
  753. }
  754. }
  755. }
  756. if (updateNcas.Count > 0)
  757. {
  758. string extraNcas = string.Empty;
  759. foreach (var entry in updateNcas)
  760. {
  761. foreach (var nca in entry.Value)
  762. {
  763. extraNcas += nca.path + Environment.NewLine;
  764. }
  765. }
  766. throw new InvalidFirmwarePackageException($"Firmware package contains unrelated archives. Please remove these paths: {Environment.NewLine}{extraNcas}");
  767. }
  768. return systemVersion;
  769. }
  770. return null;
  771. }
  772. public SystemVersion GetCurrentFirmwareVersion()
  773. {
  774. IntegrityCheckLevel integrityCheckLevel = Switch.GetIntegrityCheckLevel();
  775. LoadEntries();
  776. lock (_lock)
  777. {
  778. var locationEnties = _locationEntries[StorageId.NandSystem];
  779. foreach (var entry in locationEnties)
  780. {
  781. if (entry.ContentType == NcaContentType.Data)
  782. {
  783. var path = _virtualFileSystem.SwitchPathToSystemPath(entry.ContentPath);
  784. using (FileStream fileStream = File.OpenRead(path))
  785. {
  786. Nca nca = new Nca(_virtualFileSystem.KeySet, fileStream.AsStorage());
  787. if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data)
  788. {
  789. var romfs = nca.OpenFileSystem(NcaSectionType.Data, integrityCheckLevel);
  790. if (romfs.OpenFile(out IFile systemVersionFile, "/file".ToU8Span(), OpenMode.Read).IsSuccess())
  791. {
  792. return new SystemVersion(systemVersionFile.AsStream());
  793. }
  794. }
  795. }
  796. }
  797. }
  798. }
  799. return null;
  800. }
  801. }
  802. }