aboutsummaryrefslogblamecommitdiff
path: root/Ryujinx.HLE/FileSystem/Content/ContentManager.cs
blob: b83ae44064334c95030083b2262d1c8b0aa41558 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857

                      
                               
                             
                                    


                                 
                            




                                        

                                                                      
                                                                                  
 
                                                                      
                                                                         
 
                                                                                                  
 
                               
 
                                            
         
                                                                                         
                                                                                        
 
                                                                     




                                                                        
                                                                       
              








                                                                                           
                             
         
                                                                
         
                                                                                         
                                                                                        
 
                                                                              
             

                                                  

                   

                                                                                                            
                 
                                             


                             
                                                               
 
                                                                                         
 
                                                  
                 
                                                
                 
                                                                                                     
                 
                                                                     
                     
                                                                                                             
 
                                                                                                                                         
                         
                                                                                          
 
                                                                                                                                                                       
                                                             
                                                                       
 
                                                                               
                                                                      
                                                                                             
 
                                            
 
                                                                                                          


                         
                                                                                       
                 
                                                              
                     
                                                                                    
 
                                                                                                             
                         
                                                                                          
 
                                                                                                                                                                   
                                                             
                                                                       
 
                                                                               
                                                                      
                                                                                             
 
                                            
 
                                                                                                          


                         
                                                                                                       
                 
                                                       
                 
                                                             
                 
                                                                  
                 
 
                                                             
                                                                     
         
                                                                                             
         
                                                                 
         
                                                                 
         
                                                                                 
                                                                             
 
                                         
             
                                                                                     
 
                                                     
                 
                                                             
                 
                                                  

             
                                                             
         
                                                        
             


                                                                                        
                                                                                                  
 
                                            



                         
                                                                                  
         
                                                                              
             
                                                                                      



                                 
                                                                                                           
         
                                                                                       
 
                                                                                        
         
                                                                                                            
         
                                                                                       
 
                                                              
             
                                                 



                                
                                                                                 
         
                                                                                                         
 
                                                  
             
                                                                                       
             
                                                  
         
                                                                                               
         
                                                  

                             
                                                                                                        
 
                                                          
             
                                               
                 
                                                                                                           
                                                                                   
                                                                                  
 
                                            




                         
                                                                               
         
                                                          
 
                                                        
             
                                                           
             
                                     
             
                                                 
                 
                                               
                 
                                            

             
                                                                                                       
         
                                                          
 
                                                        
             
                                                           
             
                                     
             
                                                                                                          
 
                                              
                 
                                               


                 
                                                                      
         
                                                                                 
         



                                                                                     
                                                                                                        
         
                                                                                 
 
                                                                                                         
         




















































































































































































































































































































































































































































































































































                                                                                                                                                                                
     
using LibHac;
using LibHac.Fs;
using LibHac.FsSystem;
using LibHac.FsSystem.NcaUtils;
using LibHac.Ncm;
using Ryujinx.HLE.Exceptions;
using Ryujinx.HLE.HOS.Services.Time;
using Ryujinx.HLE.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;

namespace Ryujinx.HLE.FileSystem.Content
{
    internal class ContentManager
    {
        private const ulong SystemVersionTitleId = 0x0100000000000809;
        private const ulong SystemUpdateTitleId  = 0x0100000000000816;

        private Dictionary<StorageId, LinkedList<LocationEntry>> _locationEntries;

        private Dictionary<string, long>   _sharedFontTitleDictionary;
        private Dictionary<string, string> _sharedFontFilenameDictionary;

        private SortedDictionary<(ulong titleId, NcaContentType type), string> _contentDictionary;

        private Switch _device;

        public ContentManager(Switch device)
        {
            _contentDictionary = new SortedDictionary<(ulong, NcaContentType), string>();
            _locationEntries   = new Dictionary<StorageId, LinkedList<LocationEntry>>();

            _sharedFontTitleDictionary = new Dictionary<string, long>
            {
                { "FontStandard",                  0x0100000000000811 },
                { "FontChineseSimplified",         0x0100000000000814 },
                { "FontExtendedChineseSimplified", 0x0100000000000814 },
                { "FontKorean",                    0x0100000000000812 },
                { "FontChineseTraditional",        0x0100000000000813 },
                { "FontNintendoExtended",          0x0100000000000810 }
            };

            _sharedFontFilenameDictionary = new Dictionary<string, string>
            {
                { "FontStandard",                  "nintendo_udsg-r_std_003.bfttf" },
                { "FontChineseSimplified",         "nintendo_udsg-r_org_zh-cn_003.bfttf" },
                { "FontExtendedChineseSimplified", "nintendo_udsg-r_ext_zh-cn_003.bfttf" },
                { "FontKorean",                    "nintendo_udsg-r_ko_003.bfttf" },
                { "FontChineseTraditional",        "nintendo_udjxh-db_zh-tw_003.bfttf" },
                { "FontNintendoExtended",          "nintendo_ext_003.bfttf" }
            };

            _device = device;
        }

        public void LoadEntries(bool ignoreMissingFonts = false)
        {
            _contentDictionary = new SortedDictionary<(ulong, NcaContentType), string>();
            _locationEntries   = new Dictionary<StorageId, LinkedList<LocationEntry>>();

            foreach (StorageId storageId in Enum.GetValues(typeof(StorageId)))
            {
                string contentDirectory    = null;
                string contentPathString   = null;
                string registeredDirectory = null;

                try
                {
                    contentPathString   = LocationHelper.GetContentRoot(storageId);
                    contentDirectory    = LocationHelper.GetRealPath(_device.FileSystem, contentPathString);
                    registeredDirectory = Path.Combine(contentDirectory, "registered");
                }
                catch (NotSupportedException)
                {
                    continue;
                }

                Directory.CreateDirectory(registeredDirectory);

                LinkedList<LocationEntry> locationList = new LinkedList<LocationEntry>();

                void AddEntry(LocationEntry entry)
                {
                    locationList.AddLast(entry);
                }

                foreach (string directoryPath in Directory.EnumerateDirectories(registeredDirectory))
                {
                    if (Directory.GetFiles(directoryPath).Length > 0)
                    {
                        string ncaName = new DirectoryInfo(directoryPath).Name.Replace(".nca", string.Empty);

                        using (FileStream ncaFile = new FileStream(Directory.GetFiles(directoryPath)[0], FileMode.Open, FileAccess.Read))
                        {
                            Nca nca = new Nca(_device.System.KeySet, ncaFile.AsStorage());

                            string switchPath = contentPathString + ":/" + ncaFile.Name.Replace(contentDirectory, string.Empty).TrimStart(Path.DirectorySeparatorChar);

                            // Change path format to switch's
                            switchPath = switchPath.Replace('\\', '/');

                            LocationEntry entry = new LocationEntry(switchPath,
                                                                    0,
                                                                    (long)nca.Header.TitleId,
                                                                    nca.Header.ContentType);

                            AddEntry(entry);

                            _contentDictionary.Add((nca.Header.TitleId, nca.Header.ContentType), ncaName);
                        }
                    }
                }

                foreach (string filePath in Directory.EnumerateFiles(contentDirectory))
                {
                    if (Path.GetExtension(filePath) == ".nca")
                    {
                        string ncaName = Path.GetFileNameWithoutExtension(filePath);

                        using (FileStream ncaFile = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                        {
                            Nca nca = new Nca(_device.System.KeySet, ncaFile.AsStorage());

                            string switchPath = contentPathString + ":/" + filePath.Replace(contentDirectory, string.Empty).TrimStart(Path.DirectorySeparatorChar);

                            // Change path format to switch's
                            switchPath = switchPath.Replace('\\', '/');

                            LocationEntry entry = new LocationEntry(switchPath,
                                                                    0,
                                                                    (long)nca.Header.TitleId,
                                                                    nca.Header.ContentType);

                            AddEntry(entry);

                            _contentDictionary.Add((nca.Header.TitleId, nca.Header.ContentType), ncaName);
                        }
                    }
                }

                if (_locationEntries.ContainsKey(storageId) && _locationEntries[storageId]?.Count == 0)
                {
                    _locationEntries.Remove(storageId);
                }

                if (!_locationEntries.ContainsKey(storageId))
                {
                    _locationEntries.Add(storageId, locationList);
                }
            }

            TimeManager.Instance.InitializeTimeZone(_device);

            _device.System.Font.Initialize(this, ignoreMissingFonts);
        }

        public void ClearEntry(long titleId, NcaContentType contentType, StorageId storageId)
        {
            RemoveLocationEntry(titleId, contentType, storageId);
        }

        public void RefreshEntries(StorageId storageId, int flag)
        {
            LinkedList<LocationEntry> locationList = _locationEntries[storageId];
            LinkedListNode<LocationEntry> locationEntry = locationList.First;

            while (locationEntry != null)
            {
                LinkedListNode<LocationEntry> nextLocationEntry = locationEntry.Next;

                if (locationEntry.Value.Flag == flag)
                {
                    locationList.Remove(locationEntry.Value);
                }

                locationEntry = nextLocationEntry;
            }
        }

        public bool HasNca(string ncaId, StorageId storageId)
        {
            if (_contentDictionary.ContainsValue(ncaId))
            {
                var  content = _contentDictionary.FirstOrDefault(x => x.Value == ncaId);
                long titleId = (long)content.Key.Item1;

                NcaContentType contentType = content.Key.type;
                StorageId      storage     = GetInstalledStorage(titleId, contentType, storageId);

                return storage == storageId;
            }

            return false;
        }

        public UInt128 GetInstalledNcaId(long titleId, NcaContentType contentType)
        {
            if (_contentDictionary.ContainsKey(((ulong)titleId, contentType)))
            {
                return new UInt128(_contentDictionary[((ulong)titleId, contentType)]);
            }

            return new UInt128();
        }

        public StorageId GetInstalledStorage(long titleId, NcaContentType contentType, StorageId storageId)
        {
            LocationEntry locationEntry = GetLocation(titleId, contentType, storageId);

            return locationEntry.ContentPath != null ?
                LocationHelper.GetStorageId(locationEntry.ContentPath) : StorageId.None;
        }

        public string GetInstalledContentPath(long titleId, StorageId storageId, NcaContentType contentType)
        {
            LocationEntry locationEntry = GetLocation(titleId, contentType, storageId);

            if (VerifyContentType(locationEntry, contentType))
            {
                return locationEntry.ContentPath;
            }

            return string.Empty;
        }

        public void RedirectLocation(LocationEntry newEntry, StorageId storageId)
        {
            LocationEntry locationEntry = GetLocation(newEntry.TitleId, newEntry.ContentType, storageId);

            if (locationEntry.ContentPath != null)
            {
                RemoveLocationEntry(newEntry.TitleId, newEntry.ContentType, storageId);
            }

            AddLocationEntry(newEntry, storageId);
        }

        private bool VerifyContentType(LocationEntry locationEntry, NcaContentType contentType)
        {
            if (locationEntry.ContentPath == null)
            {
                return false;
            }
            
            string installedPath = _device.FileSystem.SwitchPathToSystemPath(locationEntry.ContentPath);

            if (!string.IsNullOrWhiteSpace(installedPath))
            {
                if (File.Exists(installedPath))
                {
                    using (FileStream file = new FileStream(installedPath, FileMode.Open, FileAccess.Read))
                    {
                        Nca nca = new Nca(_device.System.KeySet, file.AsStorage());
                        bool contentCheck = nca.Header.ContentType == contentType;

                        return contentCheck;
                    }
                }
            }

            return false;
        }

        private void AddLocationEntry(LocationEntry entry, StorageId storageId)
        {
            LinkedList<LocationEntry> locationList = null;

            if (_locationEntries.ContainsKey(storageId))
            {
                locationList = _locationEntries[storageId];
            }

            if (locationList != null)
            {
                if (locationList.Contains(entry))
                {
                    locationList.Remove(entry);
                }

                locationList.AddLast(entry);
            }
        }

        private void RemoveLocationEntry(long titleId, NcaContentType contentType, StorageId storageId)
        {
            LinkedList<LocationEntry> locationList = null;

            if (_locationEntries.ContainsKey(storageId))
            {
                locationList = _locationEntries[storageId];
            }

            if (locationList != null)
            {
                LocationEntry entry =
                    locationList.ToList().Find(x => x.TitleId == titleId && x.ContentType == contentType);

                if (entry.ContentPath != null)
                {
                    locationList.Remove(entry);
                }
            }
        }

        public bool TryGetFontTitle(string fontName, out long titleId)
        {
            return _sharedFontTitleDictionary.TryGetValue(fontName, out titleId);
        }

        public bool TryGetFontFilename(string fontName, out string filename)
        {
            return _sharedFontFilenameDictionary.TryGetValue(fontName, out filename);
        }

        private LocationEntry GetLocation(long titleId, NcaContentType contentType, StorageId storageId)
        {
            LinkedList<LocationEntry> locationList = _locationEntries[storageId];

            return locationList.ToList().Find(x => x.TitleId == titleId && x.ContentType == contentType);
        }

        public void InstallFirmware(string firmwareSource)
        {
            string contentPathString   = LocationHelper.GetContentRoot(StorageId.NandSystem);
            string contentDirectory    = LocationHelper.GetRealPath(_device.FileSystem, contentPathString);
            string registeredDirectory = Path.Combine(contentDirectory, "registered");
            string temporaryDirectory  = Path.Combine(contentDirectory, "temp");

            if (Directory.Exists(temporaryDirectory))
            {
                Directory.Delete(temporaryDirectory, true);
            }

            if (Directory.Exists(firmwareSource))
            {
                InstallFromDirectory(firmwareSource, temporaryDirectory);
                FinishInstallation(temporaryDirectory, registeredDirectory);

                return;
            }

            if (!File.Exists(firmwareSource))
            {
                throw new FileNotFoundException("Firmware file does not exist.");
            }

            FileInfo info = new FileInfo(firmwareSource);

            using (FileStream file = File.OpenRead(firmwareSource))
            {
                switch (info.Extension)
                {
                    case ".zip":
                        using (ZipArchive archive = ZipFile.OpenRead(firmwareSource))
                        {
                            InstallFromZip(archive, temporaryDirectory);
                        }
                        break;
                    case ".xci":
                        Xci xci = new Xci(_device.System.KeySet, file.AsStorage());
                        InstallFromCart(xci, temporaryDirectory);
                        break;
                    default:
                        throw new InvalidFirmwarePackageException("Input file is not a valid firmware package");
                }

                FinishInstallation(temporaryDirectory, registeredDirectory);
            }
        }

        private void FinishInstallation(string temporaryDirectory, string registeredDirectory)
        {
            if (Directory.Exists(registeredDirectory))
            {
                new DirectoryInfo(registeredDirectory).Delete(true);
            }

            Directory.Move(temporaryDirectory, registeredDirectory);

            LoadEntries();
        }

        private void InstallFromDirectory(string firmwareDirectory, string temporaryDirectory)
        {
            InstallFromPartition(new LocalFileSystem(firmwareDirectory), temporaryDirectory);
        }

        private void InstallFromPartition(IFileSystem filesystem, string temporaryDirectory)
        {
            foreach (var entry in filesystem.EnumerateEntries("/", "*.nca"))
            {
                Nca nca = new Nca(_device.System.KeySet, OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage());

                SaveNca(nca, entry.Name.Remove(entry.Name.IndexOf('.')), temporaryDirectory);
            }
        }

        private void InstallFromCart(Xci gameCard, string temporaryDirectory)
        {
            if (gameCard.HasPartition(XciPartitionType.Update))
            {
                XciPartition partition = gameCard.OpenPartition(XciPartitionType.Update);

                InstallFromPartition(partition, temporaryDirectory);
            }
            else
            {
                throw new Exception("Update not found in xci file.");
            }
        }

        private void InstallFromZip(ZipArchive archive, string temporaryDirectory)
        {
            using (archive)
            {
                foreach (var entry in archive.Entries)
                {
                    if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00"))
                    {
                        // Clean up the name and get the NcaId

                        string[] pathComponents = entry.FullName.Replace(".cnmt", "").Split('/');

                        string ncaId = pathComponents[pathComponents.Length - 1];

                        // If this is a fragmented nca, we need to get the previous element.GetZip
                        if (ncaId.Equals("00"))
                        {
                            ncaId = pathComponents[pathComponents.Length - 2];
                        }

                        if (ncaId.Contains(".nca"))
                        {
                            string newPath = Path.Combine(temporaryDirectory, ncaId);

                            Directory.CreateDirectory(newPath);

                            entry.ExtractToFile(Path.Combine(newPath, "00"));
                        }
                    }
                }
            }
        }

        public void SaveNca(Nca nca, string ncaId, string temporaryDirectory)
        {
            string newPath = Path.Combine(temporaryDirectory, ncaId + ".nca");

            Directory.CreateDirectory(newPath);

            using (FileStream file = File.Create(Path.Combine(newPath, "00")))
            {
                nca.BaseStorage.AsStream().CopyTo(file);
            }
        }

        private IFile OpenPossibleFragmentedFile(IFileSystem filesystem, string path, OpenMode mode)
        {
            IFile file;

            if (filesystem.FileExists($"{path}/00"))
            {
                filesystem.OpenFile(out file, $"{path}/00", mode);
            }
            else
            {
                filesystem.OpenFile(out file, path, mode);
            }

            return file;
        }

        private Stream GetZipStream(ZipArchiveEntry entry)
        {
            MemoryStream dest = new MemoryStream();

            Stream src = entry.Open();

            src.CopyTo(dest);
            src.Dispose();

            return dest;
        }

        public SystemVersion VerifyFirmwarePackage(string firmwarePackage)
        {
            Dictionary<ulong, List<(NcaContentType type, string path)>> updateNcas = new Dictionary<ulong, List<(NcaContentType, string)>>();

            if (Directory.Exists(firmwarePackage))
            {
                return VerifyAndGetVersionDirectory(firmwarePackage);
            }

            if (!File.Exists(firmwarePackage))
            {
                throw new FileNotFoundException("Firmware file does not exist.");
            }

            FileInfo info = new FileInfo(firmwarePackage);

            using (FileStream file = File.OpenRead(firmwarePackage))
            {
                switch (info.Extension)
                {
                    case ".zip":
                        using (ZipArchive archive = ZipFile.OpenRead(firmwarePackage))
                        {
                            return VerifyAndGetVersionZip(archive);
                        }
                    case ".xci":
                        Xci xci = new Xci(_device.System.KeySet, file.AsStorage());

                        if (xci.HasPartition(XciPartitionType.Update))
                        {
                            XciPartition partition = xci.OpenPartition(XciPartitionType.Update);

                            return VerifyAndGetVersion(partition);
                        }
                        else
                        {
                            throw new InvalidFirmwarePackageException("Update not found in xci file.");
                        }
                    default:
                        break;
                }
            }

            SystemVersion VerifyAndGetVersionDirectory(string firmwareDirectory)
            {
                return VerifyAndGetVersion(new LocalFileSystem(firmwareDirectory));
            }

            SystemVersion VerifyAndGetVersionZip(ZipArchive archive)
            {
                SystemVersion systemVersion = null;

                foreach (var entry in archive.Entries)
                {
                    if (entry.FullName.EndsWith(".nca") || entry.FullName.EndsWith(".nca/00"))
                    {
                        using (Stream ncaStream = GetZipStream(entry))
                        {
                            IStorage storage = ncaStream.AsStorage();

                            Nca nca = new Nca(_device.System.KeySet, storage);

                            if (updateNcas.ContainsKey(nca.Header.TitleId))
                            {
                                updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullName));
                            }
                            else
                            {
                                updateNcas.Add(nca.Header.TitleId, new List<(NcaContentType, string)>());
                                updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullName));
                            }
                        }
                    }
                }

                if (updateNcas.ContainsKey(SystemUpdateTitleId))
                {
                    var ncaEntry = updateNcas[SystemUpdateTitleId];

                    string metaPath = ncaEntry.Find(x => x.type == NcaContentType.Meta).path;

                    CnmtContentMetaEntry[] metaEntries = null;

                    var fileEntry = archive.GetEntry(metaPath);

                    using (Stream ncaStream = GetZipStream(fileEntry))
                    {
                        Nca metaNca = new Nca(_device.System.KeySet, ncaStream.AsStorage());

                        IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);

                        string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;

                        if (fs.OpenFile(out IFile metaFile, cnmtPath, OpenMode.Read).IsSuccess())
                        {
                            var meta = new Cnmt(metaFile.AsStream());

                            if (meta.Type == ContentMetaType.SystemUpdate)
                            {
                                metaEntries = meta.MetaEntries;

                                updateNcas.Remove(SystemUpdateTitleId);
                            };
                        }
                    }

                    if (metaEntries == null)
                    {
                        throw new FileNotFoundException("System update title was not found in the firmware package.");
                    }

                    if (updateNcas.ContainsKey(SystemVersionTitleId))
                    {
                        string versionEntry = updateNcas[SystemVersionTitleId].Find(x => x.type != NcaContentType.Meta).path;

                        using (Stream ncaStream = GetZipStream(archive.GetEntry(versionEntry)))
                        {
                            Nca nca = new Nca(_device.System.KeySet, ncaStream.AsStorage());

                            var romfs = nca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);

                            if (romfs.OpenFile(out IFile systemVersionFile, "/file", OpenMode.Read).IsSuccess())
                            {
                                systemVersion = new SystemVersion(systemVersionFile.AsStream());
                            }
                        }
                    }

                    foreach (CnmtContentMetaEntry metaEntry in metaEntries)
                    {
                        if (updateNcas.TryGetValue(metaEntry.TitleId, out ncaEntry))
                        {
                            metaPath = ncaEntry.Find(x => x.type == NcaContentType.Meta).path;

                            string contentPath = ncaEntry.Find(x => x.type != NcaContentType.Meta).path;

                            // Nintendo in 9.0.0, removed PPC and only kept the meta nca of it.
                            // This is a perfect valid case, so we should just ignore the missing content nca and continue.
                            if (contentPath == null)
                            {
                                updateNcas.Remove(metaEntry.TitleId);

                                continue;
                            }

                            ZipArchiveEntry metaZipEntry    = archive.GetEntry(metaPath);
                            ZipArchiveEntry contentZipEntry = archive.GetEntry(contentPath);

                            using (Stream metaNcaStream = GetZipStream(metaZipEntry))
                            {
                                using (Stream contentNcaStream = GetZipStream(contentZipEntry))
                                {
                                    Nca metaNca = new Nca(_device.System.KeySet, metaNcaStream.AsStorage());

                                    IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);

                                    string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;

                                    if (fs.OpenFile(out IFile metaFile, cnmtPath, OpenMode.Read).IsSuccess())
                                    {
                                        var meta = new Cnmt(metaFile.AsStream());

                                        IStorage contentStorage = contentNcaStream.AsStorage();
                                        if (contentStorage.GetSize(out long size).IsSuccess())
                                        {
                                            byte[] contentData = new byte[size];

                                            Span<byte> content = new Span<byte>(contentData);

                                            contentStorage.Read(0, content);

                                            Span<byte> hash = new Span<byte>(new byte[32]);

                                            LibHac.Crypto.Sha256.GenerateSha256Hash(content, hash);

                                            if (LibHac.Util.ArraysEqual(hash.ToArray(), meta.ContentEntries[0].Hash))
                                            {
                                                updateNcas.Remove(metaEntry.TitleId);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (updateNcas.Count > 0)
                    {
                        string extraNcas = string.Empty;

                        foreach (var entry in updateNcas)
                        {
                            foreach (var nca in entry.Value)
                            {
                                extraNcas += nca.path + Environment.NewLine;
                            }
                        }

                        throw new InvalidFirmwarePackageException($"Firmware package contains unrelated archives. Please remove these paths: {Environment.NewLine}{extraNcas}");
                    }
                }
                else
                {
                    throw new FileNotFoundException("System update title was not found in the firmware package.");
                }

                return systemVersion;
            }

            SystemVersion VerifyAndGetVersion(IFileSystem filesystem)
            {
                SystemVersion systemVersion = null;

                CnmtContentMetaEntry[] metaEntries = null;

                foreach (var entry in filesystem.EnumerateEntries("/", "*.nca"))
                {
                    IStorage ncaStorage = OpenPossibleFragmentedFile(filesystem, entry.FullPath, OpenMode.Read).AsStorage();

                    Nca nca = new Nca(_device.System.KeySet, ncaStorage);

                    if (nca.Header.TitleId == SystemUpdateTitleId && nca.Header.ContentType == NcaContentType.Meta)
                    {
                        IFileSystem fs = nca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);

                        string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;

                        if (fs.OpenFile(out IFile metaFile, cnmtPath, OpenMode.Read).IsSuccess())
                        {
                            var meta = new Cnmt(metaFile.AsStream());

                            if (meta.Type == ContentMetaType.SystemUpdate)
                            {
                                metaEntries = meta.MetaEntries;
                            }
                        };

                        continue;
                    }
                    else if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data)
                    {
                        var romfs = nca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);

                        if (romfs.OpenFile(out IFile systemVersionFile, "/file", OpenMode.Read).IsSuccess())
                        {
                            systemVersion = new SystemVersion(systemVersionFile.AsStream());
                        }
                    }

                    if (updateNcas.ContainsKey(nca.Header.TitleId))
                    {
                        updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullPath));
                    }
                    else
                    {
                        updateNcas.Add(nca.Header.TitleId, new List<(NcaContentType, string)>());
                        updateNcas[nca.Header.TitleId].Add((nca.Header.ContentType, entry.FullPath));
                    }

                    ncaStorage.Dispose();
                }

                if (metaEntries == null)
                {
                    throw new FileNotFoundException("System update title was not found in the firmware package.");
                }

                foreach (CnmtContentMetaEntry metaEntry in metaEntries)
                {
                    if (updateNcas.TryGetValue(metaEntry.TitleId, out var ncaEntry))
                    {
                        var    metaNcaEntry = ncaEntry.Find(x => x.type == NcaContentType.Meta);
                        string contentPath  = ncaEntry.Find(x => x.type != NcaContentType.Meta).path;

                        // Nintendo in 9.0.0, removed PPC and only kept the meta nca of it.
                        // This is a perfect valid case, so we should just ignore the missing content nca and continue.
                        if (contentPath == null)
                        {
                            updateNcas.Remove(metaEntry.TitleId);

                            continue;
                        }

                        IStorage metaStorage = OpenPossibleFragmentedFile(filesystem, metaNcaEntry.path, OpenMode.Read).AsStorage();
                        IStorage contentStorage = OpenPossibleFragmentedFile(filesystem, contentPath, OpenMode.Read).AsStorage();

                        Nca metaNca = new Nca(_device.System.KeySet, metaStorage);

                        IFileSystem fs = metaNca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);

                        string cnmtPath = fs.EnumerateEntries("/", "*.cnmt").Single().FullPath;

                        if (fs.OpenFile(out IFile metaFile, cnmtPath, OpenMode.Read).IsSuccess())
                        {
                            var meta = new Cnmt(metaFile.AsStream());

                            if (contentStorage.GetSize(out long size).IsSuccess())
                            {
                                byte[] contentData = new byte[size];

                                Span<byte> content = new Span<byte>(contentData);

                                contentStorage.Read(0, content);

                                Span<byte> hash = new Span<byte>(new byte[32]);

                                LibHac.Crypto.Sha256.GenerateSha256Hash(content, hash);

                                if (LibHac.Util.ArraysEqual(hash.ToArray(), meta.ContentEntries[0].Hash))
                                {
                                    updateNcas.Remove(metaEntry.TitleId);
                                }
                            }
                        }
                    }
                }

                if (updateNcas.Count > 0)
                {
                    string extraNcas = string.Empty;

                    foreach (var entry in updateNcas)
                    {
                        foreach (var nca in entry.Value)
                        {
                            extraNcas += nca.path + Environment.NewLine;
                        }
                    }

                    throw new InvalidFirmwarePackageException($"Firmware package contains unrelated archives. Please remove these paths: {Environment.NewLine}{extraNcas}");
                }

                return systemVersion;
            }

            return null;
        }

        public SystemVersion GetCurrentFirmwareVersion()
        {
            LoadEntries(true);

            var locationEnties = _locationEntries[StorageId.NandSystem];

            foreach (var entry in locationEnties)
            {
                if (entry.ContentType == NcaContentType.Data)
                {
                    var path = _device.FileSystem.SwitchPathToSystemPath(entry.ContentPath);

                    using (IStorage ncaStorage = File.Open(path, FileMode.Open).AsStorage())
                    {
                        Nca nca = new Nca(_device.System.KeySet, ncaStorage);

                        if (nca.Header.TitleId == SystemVersionTitleId && nca.Header.ContentType == NcaContentType.Data)
                        {
                            var romfs = nca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);

                            if (romfs.OpenFile(out IFile systemVersionFile, "/file", OpenMode.Read).IsSuccess())
                            {
                                return new SystemVersion(systemVersionFile.AsStream());
                            }
                        }

                    }
                }
            }

            return null;
        }
    }
}