ContentManager.cs 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. using LibHac.Common;
  2. using LibHac.Common.Keys;
  3. using LibHac.Fs;
  4. using LibHac.Fs.Fsa;
  5. using LibHac.FsSystem;
  6. using LibHac.Ncm;
  7. using LibHac.Tools.Fs;
  8. using LibHac.Tools.FsSystem;
  9. using LibHac.Tools.FsSystem.NcaUtils;
  10. using LibHac.Tools.Ncm;
  11. using Ryujinx.Common.Logging;
  12. using Ryujinx.HLE.Exceptions;
  13. using Ryujinx.HLE.HOS.Services.Time;
  14. using Ryujinx.HLE.Utilities;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.IO;
  18. using System.IO.Compression;
  19. using System.Linq;
  20. using Path = System.IO.Path;
  21. namespace Ryujinx.HLE.FileSystem.Content
  22. {
  23. public class ContentManager
  24. {
  25. private const ulong SystemVersionTitleId = 0x0100000000000809;
  26. private const ulong SystemUpdateTitleId = 0x0100000000000816;
  27. private Dictionary<StorageId, LinkedList<LocationEntry>> _locationEntries;
  28. private Dictionary<string, ulong> _sharedFontTitleDictionary;
  29. private Dictionary<ulong, string> _systemTitlesNameDictionary;
  30. private Dictionary<string, string> _sharedFontFilenameDictionary;
  31. private SortedDictionary<(ulong titleId, NcaContentType type), string> _contentDictionary;
  32. private struct AocItem
  33. {
  34. public readonly string ContainerPath;
  35. public readonly string NcaPath;
  36. public bool Enabled;
  37. public AocItem(string containerPath, string ncaPath, bool enabled)
  38. {
  39. ContainerPath = containerPath;
  40. NcaPath = ncaPath;
  41. Enabled = enabled;
  42. }
  43. }
  44. private SortedList<ulong, AocItem> _aocData { get; }
  45. private VirtualFileSystem _virtualFileSystem;
  46. private readonly object _lock = new object();
  47. public ContentManager(VirtualFileSystem virtualFileSystem)
  48. {
  49. _contentDictionary = new SortedDictionary<(ulong, NcaContentType), string>();
  50. _locationEntries = new Dictionary<StorageId, LinkedList<LocationEntry>>();
  51. _sharedFontTitleDictionary = new Dictionary<string, ulong>
  52. {
  53. { "FontStandard", 0x0100000000000811 },
  54. { "FontChineseSimplified", 0x0100000000000814 },
  55. { "FontExtendedChineseSimplified", 0x0100000000000814 },
  56. { "FontKorean", 0x0100000000000812 },
  57. { "FontChineseTraditional", 0x0100000000000813 },
  58. { "FontNintendoExtended", 0x0100000000000810 }
  59. };
  60. _systemTitlesNameDictionary = new Dictionary<ulong, string>()
  61. {
  62. { 0x010000000000080E, "TimeZoneBinary" },
  63. { 0x0100000000000810, "FontNintendoExtension" },
  64. { 0x0100000000000811, "FontStandard" },
  65. { 0x0100000000000812, "FontKorean" },
  66. { 0x0100000000000813, "FontChineseTraditional" },
  67. { 0x0100000000000814, "FontChineseSimple" },
  68. };
  69. _sharedFontFilenameDictionary = new Dictionary<string, string>
  70. {
  71. { "FontStandard", "nintendo_udsg-r_std_003.bfttf" },
  72. { "FontChineseSimplified", "nintendo_udsg-r_org_zh-cn_003.bfttf" },
  73. { "FontExtendedChineseSimplified", "nintendo_udsg-r_ext_zh-cn_003.bfttf" },
  74. { "FontKorean", "nintendo_udsg-r_ko_003.bfttf" },
  75. { "FontChineseTraditional", "nintendo_udjxh-db_zh-tw_003.bfttf" },
  76. { "FontNintendoExtended", "nintendo_ext_003.bfttf" }
  77. };
  78. _virtualFileSystem = virtualFileSystem;
  79. _aocData = new SortedList<ulong, AocItem>();
  80. }
  81. public void LoadEntries(Switch device = null)
  82. {
  83. lock (_lock)
  84. {
  85. _contentDictionary = new SortedDictionary<(ulong, NcaContentType), string>();
  86. _locationEntries = new Dictionary<StorageId, LinkedList<LocationEntry>>();
  87. foreach (StorageId storageId in Enum.GetValues(typeof(StorageId)))
  88. {
  89. string contentDirectory = null;
  90. string contentPathString = null;
  91. string registeredDirectory = null;
  92. try
  93. {
  94. contentPathString = LocationHelper.GetContentRoot(storageId);
  95. contentDirectory = LocationHelper.GetRealPath(_virtualFileSystem, contentPathString);
  96. registeredDirectory = Path.Combine(contentDirectory, "registered");
  97. }
  98. catch (NotSupportedException)
  99. {
  100. continue;
  101. }
  102. Directory.CreateDirectory(registeredDirectory);
  103. LinkedList<LocationEntry> locationList = new LinkedList<LocationEntry>();
  104. void AddEntry(LocationEntry entry)
  105. {
  106. locationList.AddLast(entry);
  107. }
  108. foreach (string directoryPath in Directory.EnumerateDirectories(registeredDirectory))
  109. {
  110. if (Directory.GetFiles(directoryPath).Length > 0)
  111. {
  112. string ncaName = new DirectoryInfo(directoryPath).Name.Replace(".nca", string.Empty);
  113. using (FileStream ncaFile = File.OpenRead(Directory.GetFiles(directoryPath)[0]))
  114. {
  115. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  116. string switchPath = contentPathString + ":/" + ncaFile.Name.Replace(contentDirectory, string.Empty).TrimStart(Path.DirectorySeparatorChar);
  117. // Change path format to switch's
  118. switchPath = switchPath.Replace('\\', '/');
  119. LocationEntry entry = new LocationEntry(switchPath,
  120. 0,
  121. nca.Header.TitleId,
  122. nca.Header.ContentType);
  123. AddEntry(entry);
  124. _contentDictionary.Add((nca.Header.TitleId, nca.Header.ContentType), ncaName);
  125. }
  126. }
  127. }
  128. foreach (string filePath in Directory.EnumerateFiles(contentDirectory))
  129. {
  130. if (Path.GetExtension(filePath) == ".nca")
  131. {
  132. string ncaName = Path.GetFileNameWithoutExtension(filePath);
  133. using (FileStream ncaFile = new FileStream(filePath, FileMode.Open, FileAccess.Read))
  134. {
  135. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());
  136. string switchPath = contentPathString + ":/" + filePath.Replace(contentDirectory, string.Empty).TrimStart(Path.DirectorySeparatorChar);
  137. // Change path format to switch's
  138. switchPath = switchPath.Replace('\\', '/');
  139. LocationEntry entry = new LocationEntry(switchPath,
  140. 0,
  141. nca.Header.TitleId,
  142. nca.Header.ContentType);
  143. AddEntry(entry);
  144. _contentDictionary.Add((nca.Header.TitleId, nca.Header.ContentType), ncaName);
  145. }
  146. }
  147. }
  148. if (_locationEntries.ContainsKey(storageId) && _locationEntries[storageId]?.Count == 0)
  149. {
  150. _locationEntries.Remove(storageId);
  151. }
  152. if (!_locationEntries.ContainsKey(storageId))
  153. {
  154. _locationEntries.Add(storageId, locationList);
  155. }
  156. }
  157. if (device != null)
  158. {
  159. TimeManager.Instance.InitializeTimeZone(device);
  160. device.System.SharedFontManager.Initialize();
  161. }
  162. }
  163. }
  164. // fs must contain AOC nca files in its root
  165. public void AddAocData(IFileSystem fs, string containerPath, ulong aocBaseId, IntegrityCheckLevel integrityCheckLevel)
  166. {
  167. _virtualFileSystem.ImportTickets(fs);
  168. foreach (var ncaPath in fs.EnumerateEntries("*.cnmt.nca", SearchOptions.Default))
  169. {
  170. using var ncaFile = new UniqueRef<IFile>();
  171. fs.OpenFile(ref ncaFile.Ref(), ncaPath.FullPath.ToU8Span(), OpenMode.Read);
  172. var nca = new Nca(_virtualFileSystem.KeySet, ncaFile.Get.AsStorage());
  173. if (nca.Header.ContentType != NcaContentType.Meta)
  174. {
  175. Logger.Warning?.Print(LogClass.Application, $"{ncaPath} is not a valid metadata file");
  176. continue;
  177. }
  178. using var pfs0 = nca.OpenFileSystem(0, integrityCheckLevel);
  179. using var cnmtFile = new UniqueRef<IFile>();
  180. pfs0.OpenFile(ref cnmtFile.Ref(), pfs0.EnumerateEntries().Single().FullPath.ToU8Span(), OpenMode.Read);
  181. var cnmt = new Cnmt(cnmtFile.Get.AsStream());
  182. if (cnmt.Type != ContentMetaType.AddOnContent || (cnmt.TitleId & 0xFFFFFFFFFFFFE000) != aocBaseId)
  183. {
  184. continue;
  185. }
  186. string ncaId = BitConverter.ToString(cnmt.ContentEntries[0].NcaId).Replace("-", "").ToLower();
  187. if (!_aocData.TryAdd(cnmt.TitleId, new AocItem(containerPath, $"{ncaId}.nca", true)))
  188. {
  189. Logger.Warning?.Print(LogClass.Application, $"Duplicate AddOnContent detected. TitleId {cnmt.TitleId:X16}");
  190. }
  191. else
  192. {
  193. Logger.Info?.Print(LogClass.Application, $"Found AddOnContent with TitleId {cnmt.TitleId:X16}");
  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. using var ncaFile = new UniqueRef<IFile>();
  223. PartitionFileSystem pfs;
  224. switch (Path.GetExtension(aoc.ContainerPath))
  225. {
  226. case ".xci":
  227. pfs = new Xci(_virtualFileSystem.KeySet, file.AsStorage()).OpenPartition(XciPartitionType.Secure);
  228. pfs.OpenFile(ref ncaFile.Ref(), aoc.NcaPath.ToU8Span(), OpenMode.Read);
  229. break;
  230. case ".nsp":
  231. pfs = new PartitionFileSystem(file.AsStorage());
  232. pfs.OpenFile(ref ncaFile.Ref(), aoc.NcaPath.ToU8Span(), OpenMode.Read);
  233. break;
  234. default:
  235. return false; // Print error?
  236. }
  237. aocStorage = new Nca(_virtualFileSystem.KeySet, ncaFile.Get.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. using var file = new UniqueRef<IFile>();
  508. if (filesystem.FileExists($"{path}/00"))
  509. {
  510. filesystem.OpenFile(ref file.Ref(), $"{path}/00".ToU8Span(), mode);
  511. }
  512. else
  513. {
  514. filesystem.OpenFile(ref file.Ref(), path.ToU8Span(), mode);
  515. }
  516. return file.Release();
  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. using var metaFile = new UniqueRef<IFile>();
  608. if (fs.OpenFile(ref metaFile.Ref(), cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  609. {
  610. var meta = new Cnmt(metaFile.Get.AsStream());
  611. if (meta.Type == ContentMetaType.SystemUpdate)
  612. {
  613. metaEntries = meta.MetaEntries;
  614. updateNcas.Remove(SystemUpdateTitleId);
  615. };
  616. }
  617. }
  618. if (metaEntries == null)
  619. {
  620. throw new FileNotFoundException("System update title was not found in the firmware package.");
  621. }
  622. if (updateNcas.ContainsKey(SystemVersionTitleId))
  623. {
  624. string versionEntry = updateNcas[SystemVersionTitleId].Find(x => x.type != NcaContentType.Meta).path;
  625. using (Stream ncaStream = GetZipStream(archive.GetEntry(versionEntry)))
  626. {
  627. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaStream.AsStorage());
  628. var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  629. using var systemVersionFile = new UniqueRef<IFile>();
  630. if (romfs.OpenFile(ref systemVersionFile.Ref(), "/file".ToU8Span(), OpenMode.Read).IsSuccess())
  631. {
  632. systemVersion = new SystemVersion(systemVersionFile.Get.AsStream());
  633. }
  634. }
  635. }
  636. foreach (CnmtContentMetaEntry metaEntry in metaEntries)
  637. {
  638. if (updateNcas.TryGetValue(metaEntry.TitleId, out ncaEntry))
  639. {
  640. metaPath = ncaEntry.Find(x => x.type == NcaContentType.Meta).path;
  641. string contentPath = ncaEntry.Find(x => x.type != NcaContentType.Meta).path;
  642. // Nintendo in 9.0.0, removed PPC and only kept the meta nca of it.
  643. // This is a perfect valid case, so we should just ignore the missing content nca and continue.
  644. if (contentPath == null)
  645. {
  646. updateNcas.Remove(metaEntry.TitleId);
  647. continue;
  648. }
  649. ZipArchiveEntry metaZipEntry = archive.GetEntry(metaPath);
  650. ZipArchiveEntry contentZipEntry = archive.GetEntry(contentPath);
  651. using (Stream metaNcaStream = GetZipStream(metaZipEntry))
  652. {
  653. using (Stream contentNcaStream = GetZipStream(contentZipEntry))
  654. {
  655. Nca metaNca = new Nca(_virtualFileSystem.KeySet, metaNcaStream.AsStorage());
  656. IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  657. string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
  658. using var metaFile = new UniqueRef<IFile>();
  659. if (fs.OpenFile(ref metaFile.Ref(), cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  660. {
  661. var meta = new Cnmt(metaFile.Get.AsStream());
  662. IStorage contentStorage = contentNcaStream.AsStorage();
  663. if (contentStorage.GetSize(out long size).IsSuccess())
  664. {
  665. byte[] contentData = new byte[size];
  666. Span<byte> content = new Span<byte>(contentData);
  667. contentStorage.Read(0, content);
  668. Span<byte> hash = new Span<byte>(new byte[32]);
  669. LibHac.Crypto.Sha256.GenerateSha256Hash(content, hash);
  670. if (LibHac.Common.Utilities.ArraysEqual(hash.ToArray(), meta.ContentEntries[0].Hash))
  671. {
  672. updateNcas.Remove(metaEntry.TitleId);
  673. }
  674. }
  675. }
  676. }
  677. }
  678. }
  679. }
  680. if (updateNcas.Count > 0)
  681. {
  682. string extraNcas = string.Empty;
  683. foreach (var entry in updateNcas)
  684. {
  685. foreach (var nca in entry.Value)
  686. {
  687. extraNcas += nca.path + Environment.NewLine;
  688. }
  689. }
  690. throw new InvalidFirmwarePackageException($"Firmware package contains unrelated archives. Please remove these paths: {Environment.NewLine}{extraNcas}");
  691. }
  692. }
  693. else
  694. {
  695. throw new FileNotFoundException("System update title was not found in the firmware package.");
  696. }
  697. return systemVersion;
  698. }
  699. SystemVersion VerifyAndGetVersion(IFileSystem filesystem)
  700. {
  701. SystemVersion systemVersion = null;
  702. CnmtContentMetaEntry[] metaEntries = null;
  703. foreach (var entry in filesystem.EnumerateEntries("/", "*.nca"))
  704. {
  705. IStorage ncaStorage = OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage();
  706. Nca nca = new Nca(_virtualFileSystem.KeySet, ncaStorage);
  707. if (nca.Header.TitleId == SystemUpdateTitleId && nca.Header.ContentType == NcaContentType.Meta)
  708. {
  709. IFileSystem fs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  710. string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
  711. using var metaFile = new UniqueRef<IFile>();
  712. if (fs.OpenFile(ref metaFile.Ref(), cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  713. {
  714. var meta = new Cnmt(metaFile.Get.AsStream());
  715. if (meta.Type == ContentMetaType.SystemUpdate)
  716. {
  717. metaEntries = meta.MetaEntries;
  718. }
  719. };
  720. continue;
  721. }
  722. else if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data)
  723. {
  724. var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  725. using var systemVersionFile = new UniqueRef<IFile>();
  726. if (romfs.OpenFile(ref systemVersionFile.Ref(), "/file".ToU8Span(), OpenMode.Read).IsSuccess())
  727. {
  728. systemVersion = new SystemVersion(systemVersionFile.Get.AsStream());
  729. }
  730. }
  731. if (updateNcas.ContainsKey(nca.Header.TitleId))
  732. {
  733. updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullPath));
  734. }
  735. else
  736. {
  737. updateNcas.Add(nca.Header.TitleId, new List<(NcaContentType, string)>());
  738. updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullPath));
  739. }
  740. ncaStorage.Dispose();
  741. }
  742. if (metaEntries == null)
  743. {
  744. throw new FileNotFoundException("System update title was not found in the firmware package.");
  745. }
  746. foreach (CnmtContentMetaEntry metaEntry in metaEntries)
  747. {
  748. if (updateNcas.TryGetValue(metaEntry.TitleId, out var ncaEntry))
  749. {
  750. var metaNcaEntry = ncaEntry.Find(x => x.type == NcaContentType.Meta);
  751. string contentPath = ncaEntry.Find(x => x.type != NcaContentType.Meta).path;
  752. // Nintendo in 9.0.0, removed PPC and only kept the meta nca of it.
  753. // This is a perfect valid case, so we should just ignore the missing content nca and continue.
  754. if (contentPath == null)
  755. {
  756. updateNcas.Remove(metaEntry.TitleId);
  757. continue;
  758. }
  759. IStorage metaStorage = OpenPossibleFragmentedFile(filesystem, metaNcaEntry.path, OpenMode.Read).AsStorage();
  760. IStorage contentStorage = OpenPossibleFragmentedFile(filesystem, contentPath, OpenMode.Read).AsStorage();
  761. Nca metaNca = new Nca(_virtualFileSystem.KeySet, metaStorage);
  762. IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  763. string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;
  764. using var metaFile = new UniqueRef<IFile>();
  765. if (fs.OpenFile(ref metaFile.Ref(), cnmtPath.ToU8Span(), OpenMode.Read).IsSuccess())
  766. {
  767. var meta = new Cnmt(metaFile.Get.AsStream());
  768. if (contentStorage.GetSize(out long size).IsSuccess())
  769. {
  770. byte[] contentData = new byte[size];
  771. Span<byte> content = new Span<byte>(contentData);
  772. contentStorage.Read(0, content);
  773. Span<byte> hash = new Span<byte>(new byte[32]);
  774. LibHac.Crypto.Sha256.GenerateSha256Hash(content, hash);
  775. if (LibHac.Common.Utilities.ArraysEqual(hash.ToArray(), meta.ContentEntries[0].Hash))
  776. {
  777. updateNcas.Remove(metaEntry.TitleId);
  778. }
  779. }
  780. }
  781. }
  782. }
  783. if (updateNcas.Count > 0)
  784. {
  785. string extraNcas = string.Empty;
  786. foreach (var entry in updateNcas)
  787. {
  788. foreach (var nca in entry.Value)
  789. {
  790. extraNcas += nca.path + Environment.NewLine;
  791. }
  792. }
  793. throw new InvalidFirmwarePackageException($"Firmware package contains unrelated archives. Please remove these paths: {Environment.NewLine}{extraNcas}");
  794. }
  795. return systemVersion;
  796. }
  797. return null;
  798. }
  799. public SystemVersion GetCurrentFirmwareVersion()
  800. {
  801. LoadEntries();
  802. lock (_lock)
  803. {
  804. var locationEnties = _locationEntries[StorageId.NandSystem];
  805. foreach (var entry in locationEnties)
  806. {
  807. if (entry.ContentType == NcaContentType.Data)
  808. {
  809. var path = _virtualFileSystem.SwitchPathToSystemPath(entry.ContentPath);
  810. using (FileStream fileStream = File.OpenRead(path))
  811. {
  812. Nca nca = new Nca(_virtualFileSystem.KeySet, fileStream.AsStorage());
  813. if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data)
  814. {
  815. var romfs = nca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.ErrorOnInvalid);
  816. using var systemVersionFile = new UniqueRef<IFile>();
  817. if (romfs.OpenFile(ref systemVersionFile.Ref(), "/file".ToU8Span(), OpenMode.Read).IsSuccess())
  818. {
  819. return new SystemVersion(systemVersionFile.Get.AsStream());
  820. }
  821. }
  822. }
  823. }
  824. }
  825. }
  826. return null;
  827. }
  828. }
  829. }