Esempio n. 1
0
 public PartitionInfoEx(PartitionFileSystem partitionFileSystem, Information size, IEnumerable <char>?driveLetters, IPhilote <IPartitionInfoEx>?philote)
 {
     PartitionFileSystem = partitionFileSystem;
     Size         = size;
     DriveLetters = driveLetters;
     Philote      = philote;
 }
Esempio n. 2
0
        private void LoadDownloadableContents()
        {
            foreach (DownloadableContentContainer downloadableContentContainer in _downloadableContentContainerList)
            {
                if (File.Exists(downloadableContentContainer.ContainerPath))
                {
                    using FileStream containerFile = File.OpenRead(downloadableContentContainer.ContainerPath);

                    PartitionFileSystem pfs = new PartitionFileSystem(containerFile.AsStorage());

                    VirtualFileSystem.ImportTickets(pfs);

                    foreach (DownloadableContentNca downloadableContentNca in downloadableContentContainer.DownloadableContentNcaList)
                    {
                        using var ncaFile = new UniqueRef <IFile>();

                        pfs.OpenFile(ref ncaFile.Ref(), downloadableContentNca.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();

                        Nca nca = TryCreateNca(ncaFile.Get.AsStorage(), downloadableContentContainer.ContainerPath);
                        if (nca != null)
                        {
                            DownloadableContents.Add(new DownloadableContentModel(nca.Header.TitleId.ToString("X16"),
                                                                                  downloadableContentContainer.ContainerPath,
                                                                                  downloadableContentNca.FullPath,
                                                                                  downloadableContentNca.Enabled));
                        }
                    }
                }
            }

            // NOTE: Save the list again to remove leftovers.
            Save();
        }
Esempio n. 3
0
        private static IFileSystem GetControlFs(PartitionFileSystem Pfs)
        {
            Nca controlNca = null;

            // Add keys to keyset if needed
            foreach (DirectoryEntry ticketEntry in Pfs.EnumerateEntries("*.tik"))
            {
                Ticket ticket = new Ticket(Pfs.OpenFile(ticketEntry.FullPath, OpenMode.Read).AsStream());

                if (!KeySet.TitleKeys.ContainsKey(ticket.RightsId))
                {
                    KeySet.TitleKeys.Add(ticket.RightsId, ticket.GetTitleKey(KeySet));
                }
            }

            // Find the Control NCA and store it in variable called controlNca
            foreach (DirectoryEntry fileEntry in Pfs.EnumerateEntries("*.nca"))
            {
                Nca nca = new Nca(KeySet, Pfs.OpenFile(fileEntry.FullPath, OpenMode.Read).AsStorage());
                if (nca.Header.ContentType == ContentType.Control)
                {
                    controlNca = nca;
                }
            }

            // Return the ControlFS
            return(controlNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None));
        }
Esempio n. 4
0
        private static IFileSystem GetControlFs(PartitionFileSystem Pfs)
        {
            Nca controlNca = null;

            // Add keys to keyset if needed
            foreach (DirectoryEntryEx ticketEntry in Pfs.EnumerateEntries("/", "*.tik"))
            {
                Result result = Pfs.OpenFile(out IFile ticketFile, ticketEntry.FullPath, OpenMode.Read);

                if (result.IsSuccess())
                {
                    Ticket ticket = new Ticket(ticketFile.AsStream());

                    KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
                }
            }

            // Find the Control NCA and store it in variable called controlNca
            foreach (DirectoryEntryEx fileEntry in Pfs.EnumerateEntries("/", "*.nca"))
            {
                Pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath, OpenMode.Read).ThrowIfFailure();

                Nca nca = new Nca(KeySet, ncaFile.AsStorage());

                if (nca.Header.ContentType == NcaContentType.Control)
                {
                    controlNca = nca;
                }
            }

            // Return the ControlFS
            return(controlNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None));
        }
Esempio n. 5
0
        public static void File2Tickets(string inFile, string outDirPath, Keyset keyset, Output Out)
        {
            var inFileExtension = Path.GetExtension(inFile).ToLower();

            using (var inputFile = new FileStream(inFile, FileMode.Open, FileAccess.Read))
            {
                switch (inFileExtension)
                {
                case ".nsp":
                    var pfs = new PartitionFileSystem(inputFile.AsStorage());
                    ProcessNsp.ExtractTickets(pfs, outDirPath, keyset, Out);
                    break;

                case ".xci":
                    var xci = new Xci(keyset, inputFile.AsStorage());
                    ProcessXci.ExtractTickets(xci, outDirPath, keyset, Out);
                    break;

                case ".nspz":
                case ".xciz":
                    var pfsz = new PartitionFileSystem(inputFile.AsStorage());
                    DecompressFs.ExtractTickets(pfsz, outDirPath, keyset, Out);
                    break;

                default:
                    throw new NotImplementedException();
                }
            }
        }
Esempio n. 6
0
        private (Nca main, Nca patch, Nca control) GetGameData(PartitionFileSystem pfs)
        {
            Nca mainNca    = null;
            Nca patchNca   = null;
            Nca controlNca = null;

            _fileSystem.ImportTickets(pfs);

            foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
            {
                pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();

                Nca nca = new Nca(_fileSystem.KeySet, ncaFile.AsStorage());

                if (nca.Header.ContentType == NcaContentType.Program)
                {
                    int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);

                    if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
                    {
                        patchNca = nca;
                    }
                    else
                    {
                        mainNca = nca;
                    }
                }
                else if (nca.Header.ContentType == NcaContentType.Control)
                {
                    controlNca = nca;
                }
            }

            return(mainNca, patchNca, controlNca);
        }
Esempio n. 7
0
        private void AddUpdate(string path, bool showErrorDialog = true)
        {
            if (File.Exists(path))
            {
                using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());

                    foreach (DirectoryEntryEx ticketEntry in nsp.EnumerateEntries("/", "*.tik"))
                    {
                        Result result = nsp.OpenFile(out IFile ticketFile, ticketEntry.FullPath.ToU8Span(), OpenMode.Read);

                        if (result.IsSuccess())
                        {
                            Ticket ticket = new Ticket(ticketFile.AsStream());

                            _virtualFileSystem.KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(_virtualFileSystem.KeySet)));
                        }
                    }

                    foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
                    {
                        nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();

                        try
                        {
                            Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());

                            if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" == _titleId)
Esempio n. 8
0
        public static void Decrypt(PartitionFileSystem pfs, string outDirPath, bool verifyBeforeDecrypting, Keyset keyset, Output Out)
        {
            Out.Log(pfs.Print());
            ProcessNsp.GetTitlekey(pfs, keyset, Out);
            var         OutDirFs   = new LocalFileSystem(outDirPath);
            IDirectory  sourceRoot = pfs.OpenDirectory("/", OpenDirectoryMode.All);
            IDirectory  destRoot   = OutDirFs.OpenDirectory("/", OpenDirectoryMode.All);
            IFileSystem sourceFs   = sourceRoot.ParentFileSystem;
            IFileSystem destFs     = destRoot.ParentFileSystem;

            foreach (var entry in FileIterator(sourceRoot))
            {
                destFs.CreateFile(entry.Name, entry.Size, CreateFileOptions.None);
                using (IFile srcFile = sourceFs.OpenFile(entry.Name, OpenMode.Read))
                    using (IFile dstFile = destFs.OpenFile(entry.Name, OpenMode.Write))
                    {
                        if (entry.Name.EndsWith(".nca"))
                        {
                            ProcessNca.Process(srcFile, dstFile, verifyBeforeDecrypting, keyset, Out);
                        }
                        else
                        {
                            srcFile.CopyTo(dstFile);
                        }
                    }
            }
        }
Esempio n. 9
0
        private static string Print(this PartitionFileSystem pfs)
        {
            const int colLen      = 36;
            const int fileNameLen = 39;

            var sb = new StringBuilder();

            sb.AppendLine();

            sb.AppendLine("PFS0:");

            LibHacControl.Print.PrintItem(sb, colLen, "Magic:", pfs.Header.Magic);
            LibHacControl.Print.PrintItem(sb, colLen, "Number of files:", pfs.Header.NumFiles);

            for (var i = 0; i < pfs.Files.Length; i++)
            {
                var file = pfs.Files[i];

                var label   = i == 0 ? "Files:" : "";
                var offsets = $"{file.Offset:x12}-{file.Offset + file.Size:x12}{file.HashValidity.GetValidityString()}";
                var data    = $"pfs0:/{file.Name}".PadRight(fileNameLen) + offsets;

                LibHacControl.Print.PrintItem(sb, colLen, label, data);
            }

            return(sb.ToString());
        }
        private void LoadDlcs()
        {
            foreach (DlcContainer dlcContainer in _dlcContainerList)
            {
                using FileStream containerFile = File.OpenRead(dlcContainer.Path);

                PartitionFileSystem pfs = new PartitionFileSystem(containerFile.AsStorage());

                VirtualFileSystem.ImportTickets(pfs);

                foreach (DlcNca dlcNca in dlcContainer.DlcNcaList)
                {
                    using var ncaFile = new UniqueRef <IFile>();
                    pfs.OpenFile(ref ncaFile.Ref(), dlcNca.Path.ToU8Span(), OpenMode.Read).ThrowIfFailure();

                    Nca nca = TryCreateNca(ncaFile.Get.AsStorage(), dlcContainer.Path);

                    if (nca != null)
                    {
                        Dlcs.Add(new DlcModel(nca.Header.TitleId.ToString("X16"), dlcContainer.Path, dlcNca.Path,
                                              dlcNca.Enabled));
                    }
                }
            }
        }
Esempio n. 11
0
        private static bool IsUpdateApplied(string titleId, out string version)
        {
            string jsonPath = Path.Combine(_virtualFileSystem.GetBasePath(), "games", titleId, "updates.json");

            if (File.Exists(jsonPath))
            {
                string updatePath = JsonHelper.DeserializeFromFile <TitleUpdateMetadata>(jsonPath).Selected;

                if (!File.Exists(updatePath))
                {
                    version = "";

                    return(false);
                }

                using (FileStream file = new FileStream(updatePath, FileMode.Open, FileAccess.Read))
                {
                    PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());

                    _virtualFileSystem.ImportTickets(nsp);

                    foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
                    {
                        nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();

                        try
                        {
                            Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());

                            if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" != titleId)
Esempio n. 12
0
        public bool GetAocDataStorage(ulong aocTitleId, out IStorage aocStorage, IntegrityCheckLevel integrityCheckLevel)
        {
            aocStorage = null;

            if (_aocData.TryGetValue(aocTitleId, out AocItem aoc) && aoc.Enabled)
            {
                var file = new FileStream(aoc.ContainerPath, FileMode.Open, FileAccess.Read);
                using var ncaFile = new UniqueRef <IFile>();
                PartitionFileSystem pfs;

                switch (Path.GetExtension(aoc.ContainerPath))
                {
                case ".xci":
                    pfs = new Xci(_virtualFileSystem.KeySet, file.AsStorage()).OpenPartition(XciPartitionType.Secure);
                    pfs.OpenFile(ref ncaFile.Ref(), aoc.NcaPath.ToU8Span(), OpenMode.Read);
                    break;

                case ".nsp":
                    pfs = new PartitionFileSystem(file.AsStorage());
                    pfs.OpenFile(ref ncaFile.Ref(), aoc.NcaPath.ToU8Span(), OpenMode.Read);
                    break;

                default:
                    return(false);    // Print error?
                }

                aocStorage = new Nca(_virtualFileSystem.KeySet, ncaFile.Get.AsStorage()).OpenStorage(NcaSectionType.Data, integrityCheckLevel);

                return(true);
            }

            return(false);
        }
Esempio n. 13
0
        public void VerifyCompressedFolder(string nspFile)
        {
            var nspFileNoExtension = Path.GetFileNameWithoutExtension(nspFile);

            Out.Event($"Task VerifyCompressedFolder \"{nspFileNoExtension}\" started\r\n");
            var keyset = ProcessKeyset.OpenKeyset();

            using (var inputFile = new FileStream(nspFile, FileMode.Open, FileAccess.Read))
                using (var inputFileStorage = inputFile.AsStorage())
                {
                    var pfs = new PartitionFileSystem(inputFileStorage);
                    ProcessNsp.GetTitlekey(pfs, keyset, Out);

                    var dirDecryptedReal      = new DirectoryInfo(decryptedDir);
                    var dirDecryptedRealCount = dirDecryptedReal.GetFiles().Length;
                    cleanFolder(decryptedDir);
                    var compressedFs = new LocalFileSystem(compressedDir);
                    var decryptedFs  = new LocalFileSystem(decryptedDir);
                    DecompressFs.ProcessFs(compressedFs, decryptedFs, Out);
                    UntrimDeltaNCA.Process(decryptedDir, pfs, keyset, Out);
                    EncryptNCA.Encrypt(decryptedFs, null, true, keyset, Out);
                }

            Out.Event($"Task VerifyCompressedFolder \"{nspFileNoExtension}\" completed!\r\n");
        }
Esempio n. 14
0
        private void LoadNca(Nca mainNca, Nca patchNca, Nca controlNca)
        {
            if (mainNca.Header.ContentType != NcaContentType.Program)
            {
                Logger.PrintError(LogClass.Loader, "Selected NCA is not a \"Program\" NCA");

                return;
            }

            IStorage    dataStorage = null;
            IFileSystem codeFs      = null;

            // Load Update
            string titleUpdateMetadataPath = Path.Combine(_fileSystem.GetBasePath(), "games", mainNca.Header.TitleId.ToString("x16"), "updates.json");

            if (File.Exists(titleUpdateMetadataPath))
            {
                string updatePath = JsonHelper.DeserializeFromFile <TitleUpdateMetadata>(titleUpdateMetadataPath).Selected;

                if (File.Exists(updatePath))
                {
                    FileStream          file = new FileStream(updatePath, FileMode.Open, FileAccess.Read);
                    PartitionFileSystem nsp  = new PartitionFileSystem(file.AsStorage());

                    _fileSystem.ImportTickets(nsp);

                    foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
                    {
                        nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();

                        Nca nca = new Nca(_fileSystem.KeySet, ncaFile.AsStorage());

                        if ($"{nca.Header.TitleId.ToString("x16")[..^3]}000" != mainNca.Header.TitleId.ToString("x16"))
Esempio n. 15
0
        public NcaWrapper(Keyset keyset, string ncaPath, string updateNcaPath = null)
        {
            // Open the FileStream
            fileStream = File.OpenRead(ncaPath);

            // Create the Nca instance
            baseNca = new Nca(keyset, fileStream.AsStorage(), true);

            // Open the update NCA if it exists
            if (updateNcaPath != null)
            {
                // Open the FileStream
                updateFileStream = File.OpenRead(updateNcaPath);

                // Create the update Nca instance
                updateNca = new Nca(keyset, updateFileStream.AsStorage(), true);

                // Set the baseNca
                updateNca.SetBaseNca(baseNca);
            }

            // Open the exefs
            Exefs = new PartitionFileSystem(nca.OpenSection(ProgramPartitionType.Code, false, IntegrityCheckLevel.ErrorOnInvalid, false));

            // Open the romfs
            Romfs = new RomFsFileSystem(nca.OpenSection(ProgramPartitionType.Data, false, IntegrityCheckLevel.ErrorOnInvalid, false));
        }
Esempio n. 16
0
        private long OpenFileSystemFromInternalFile(ServiceCtx context, string fullPath)
        {
            DirectoryInfo archivePath = new DirectoryInfo(fullPath).Parent;

            while (string.IsNullOrWhiteSpace(archivePath.Extension))
            {
                archivePath = archivePath.Parent;
            }

            if (archivePath.Extension == ".nsp" && File.Exists(archivePath.FullName))
            {
                FileStream pfsFile = new FileStream(
                    archivePath.FullName.TrimEnd(Path.DirectorySeparatorChar),
                    FileMode.Open,
                    FileAccess.Read);

                PartitionFileSystem nsp = new PartitionFileSystem(pfsFile.AsStorage());

                ImportTitleKeysFromNsp(nsp, context.Device.System.KeySet);

                string filename = fullPath.Replace(archivePath.FullName, string.Empty).TrimStart('\\');

                if (nsp.FileExists(filename))
                {
                    return(OpenNcaFs(context, fullPath, nsp.OpenFile(filename, OpenMode.Read).AsStorage()));
                }
            }

            return(MakeError(ErrorModule.Fs, FsErr.PathDoesNotExist));
        }
Esempio n. 17
0
        private static void GetControlFsAndTitleId(PartitionFileSystem pfs, out IFileSystem controlFs, out string titleId)
        {
            Nca controlNca = null;

            // Add keys to key set if needed
            foreach (DirectoryEntryEx ticketEntry in pfs.EnumerateEntries("/", "*.tik"))
            {
                Result result = pfs.OpenFile(out IFile ticketFile, ticketEntry.FullPath.ToU8Span(), OpenMode.Read);

                if (result.IsSuccess())
                {
                    Ticket ticket = new Ticket(ticketFile.AsStream());

                    _virtualFileSystem.KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(_virtualFileSystem.KeySet)));
                }
            }

            // Find the Control NCA and store it in variable called controlNca
            foreach (DirectoryEntryEx fileEntry in pfs.EnumerateEntries("/", "*.nca"))
            {
                pfs.OpenFile(out IFile ncaFile, fileEntry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure();

                Nca nca = new Nca(_virtualFileSystem.KeySet, ncaFile.AsStorage());

                if (nca.Header.ContentType == NcaContentType.Control)
                {
                    controlNca = nca;
                }
            }

            // Return the ControlFS
            controlFs = controlNca?.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None);
            titleId   = controlNca?.Header.TitleId.ToString("x16");
        }
Esempio n. 18
0
        private void GetControlFsAndTitleId(PartitionFileSystem pfs, out IFileSystem controlFs, out string titleId)
        {
            (_, _, Nca controlNca) = ApplicationLoader.GetGameData(_virtualFileSystem, pfs, 0);

            // Return the ControlFS
            controlFs = controlNca?.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None);
            titleId   = controlNca?.Header.TitleId.ToString("x16");
        }
Esempio n. 19
0
 public NspItem(PartitionFileSystem nspPartitionFileSystem, string name, IFile file, KeySet keySet)
     : base(nspPartitionFileSystem)
 {
     NspPartitionFileSystem = nspPartitionFileSystem ?? throw new ArgumentNullException(nameof(nspPartitionFileSystem));
     Name   = name ?? throw new ArgumentNullException(nameof(name));
     _file  = file ?? throw new ArgumentNullException(nameof(file));
     KeySet = keySet ?? throw new ArgumentNullException(nameof(keySet));
 }
Esempio n. 20
0
 public static void Extract(string inFile, string outDirPath, Output Out)
 {
     using (var file = new FileStream(inFile, FileMode.Open, FileAccess.Read))
     {
         var pfs = new PartitionFileSystem(file.AsStorage());
         Out.Log(pfs.Print());
         pfs.Extract(outDirPath);
     }
 }
Esempio n. 21
0
 public PartitionInfoEx(Id <PartitionInfoEx> partitionId, Id <PartitionInfoEx> partitionDbId, IEnumerable <string> driveLetters, PartitionFileSystem partitionFileSystem, IList <Exception> exceptions, long?size)
 {
     PartitionId         = partitionId;
     PartitionDbId       = partitionDbId;
     DriveLetters        = driveLetters ?? throw new ArgumentNullException(nameof(driveLetters));
     PartitionFileSystem = partitionFileSystem;
     Exceptions          = exceptions ?? throw new ArgumentNullException(nameof(exceptions));
     Size = size;
 }
Esempio n. 22
0
        public void LoadNsp(string nspFile)
        {
            FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read);

            PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());

            foreach (DirectoryEntryEx ticketEntry in nsp.EnumerateEntries("/", "*.tik"))
            {
                Result result = nsp.OpenFile(out IFile ticketFile, ticketEntry.FullPath, OpenMode.Read);

                if (result.IsSuccess())
                {
                    Ticket ticket = new Ticket(ticketFile.AsStream());

                    KeySet.ExternalKeySet.Add(new RightsId(ticket.RightsId), new AccessKey(ticket.GetTitleKey(KeySet)));
                }
            }

            Nca mainNca    = null;
            Nca patchNca   = null;
            Nca controlNca = null;

            foreach (DirectoryEntryEx fileEntry in nsp.EnumerateEntries("/", "*.nca"))
            {
                nsp.OpenFile(out IFile ncaFile, fileEntry.FullPath, OpenMode.Read).ThrowIfFailure();

                Nca nca = new Nca(KeySet, ncaFile.AsStorage());

                if (nca.Header.ContentType == NcaContentType.Program)
                {
                    int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, NcaContentType.Program);

                    if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
                    {
                        patchNca = nca;
                    }
                    else
                    {
                        mainNca = nca;
                    }
                }
                else if (nca.Header.ContentType == NcaContentType.Control)
                {
                    controlNca = nca;
                }
            }

            if (mainNca != null)
            {
                LoadNca(mainNca, patchNca, controlNca);

                return;
            }

            // This is not a normal NSP, it's actually a ExeFS as a NSP
            LoadExeFs(nsp, out _);
        }
Esempio n. 23
0
        public static void ExtractRomFS(string inFile, string outDirPath, Keyset keyset, Output Out)
        {
            using (var file = new FileStream(inFile, FileMode.Open, FileAccess.Read))
            {
                var         pfs        = new PartitionFileSystem(file.AsStorage());
                var         OutDirFs   = new LocalFileSystem(outDirPath);
                IDirectory  sourceRoot = pfs.OpenDirectory("/", OpenDirectoryMode.All);
                IFileSystem sourceFs   = sourceRoot.ParentFileSystem;
                Out.Log(pfs.Print());

                foreach (var entry in FileIterator(sourceRoot))
                {
                    if (entry.Name.EndsWith(".nca"))
                    {
                        var fullOutDirPath = $"{outDirPath}/{entry.Name}";
                        Out.Log($"Extracting {entry.Name}...\r\n");
                        using (IFile srcFile = sourceFs.OpenFile(entry.Name, OpenMode.Read))
                        {
                            ProcessNca.Extract(srcFile.AsStream(), fullOutDirPath, true, keyset, Out);
                        }
                    }
                    else if (entry.Name.EndsWith(".nca.nsz"))
                    {
                        var fullOutDirPath = $"{outDirPath}/{entry.Name}";
                        Out.Log($"Extracting {entry.Name}...\r\n");
                        using (IFile srcFile = sourceFs.OpenFile(entry.Name, OpenMode.Read))
                            using (var decompressedFile = new DecompressionStorage(srcFile))
                            {
                                ProcessNca.Extract(decompressedFile.AsStream(), fullOutDirPath, true, keyset, Out, true);

                                // Header can't be patched for now due to OpenSection
                                // and ValidateMasterHash needs to know if AesCtrEx
                                // so Nca.cs was patched and now accepts isDecryptedNca
                                // as constructor argument which disables decryption

                                /*
                                 * var DecryptedHeader = new byte[0xC00];
                                 * decompressedFile.AsStream().Read(DecryptedHeader, 0, 0xC00);
                                 * DecryptedHeader[1028] = (int)NcaEncryptionType.None;
                                 * DecryptedHeader[1540] = (int)NcaEncryptionType.None;
                                 * DecryptedHeader[2052] = (int)NcaEncryptionType.None;
                                 * DecryptedHeader[2564] = (int)NcaEncryptionType.None;
                                 * var HeaderKey1 = new byte[16];
                                 * var HeaderKey2 = new byte[16];
                                 * Buffer.BlockCopy(keyset.HeaderKey, 0, HeaderKey1, 0, 16);
                                 * Buffer.BlockCopy(keyset.HeaderKey, 16, HeaderKey2, 0, 16);
                                 * var headerEncrypted = CryptoInitialisers.AES_XTS(HeaderKey1, HeaderKey2, 0x200, DecryptedHeader, 0);
                                 * var ncaStorageList = new List<IStorage>() { new MemoryStorage(headerEncrypted), decompressedFile.Slice(0xC00) };
                                 * var cleanDecryptedNca = new ConcatenationStorage(ncaStorageList, true);
                                 * ProcessNca.Extract(cleanDecryptedNca.AsStream(), fullOutDirPath, true, keyset, Out);
                                 */
                            }
                    }
                }
            }
        }
Esempio n. 24
0
        public void LoadNsp(string nspFile)
        {
            FileStream file = new FileStream(nspFile, FileMode.Open, FileAccess.Read);

            PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());

            foreach (DirectoryEntry ticketEntry in nsp.EnumerateEntries("*.tik"))
            {
                Ticket ticket = new Ticket(nsp.OpenFile(ticketEntry.FullPath, OpenMode.Read).AsStream());

                if (!KeySet.TitleKeys.ContainsKey(ticket.RightsId))
                {
                    KeySet.TitleKeys.Add(ticket.RightsId, ticket.GetTitleKey(KeySet));
                }
            }

            Nca mainNca    = null;
            Nca patchNca   = null;
            Nca controlNca = null;

            foreach (DirectoryEntry fileEntry in nsp.EnumerateEntries("*.nca"))
            {
                IStorage ncaStorage = nsp.OpenFile(fileEntry.FullPath, OpenMode.Read).AsStorage();

                Nca nca = new Nca(KeySet, ncaStorage);

                if (nca.Header.ContentType == ContentType.Program)
                {
                    int dataIndex = Nca.GetSectionIndexFromType(NcaSectionType.Data, ContentType.Program);

                    if (nca.Header.GetFsHeader(dataIndex).IsPatchSection())
                    {
                        patchNca = nca;
                    }
                    else
                    {
                        mainNca = nca;
                    }
                }
                else if (nca.Header.ContentType == ContentType.Control)
                {
                    controlNca = nca;
                }
            }

            if (mainNca != null)
            {
                LoadNca(mainNca, patchNca, controlNca);

                return;
            }

            // This is not a normal NSP, it's actually a ExeFS as a NSP
            LoadExeFs(nsp, out _);
        }
Esempio n. 25
0
        private void AddUpdate(string path, bool showErrorDialog = true)
        {
            if (File.Exists(path))
            {
                using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    PartitionFileSystem nsp = new PartitionFileSystem(file.AsStorage());

                    try
                    {
                        (Nca patchNca, Nca controlNca) = ApplicationLoader.GetGameUpdateDataFromPartition(_virtualFileSystem, nsp, _titleId, 0);

                        if (controlNca != null && patchNca != null)
                        {
                            ApplicationControlProperty controlData = new ApplicationControlProperty();

                            controlNca.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None).OpenFile(out IFile nacpFile, "/control.nacp".ToU8Span(), OpenMode.Read).ThrowIfFailure();
                            nacpFile.Read(out _, 0, SpanHelpers.AsByteSpan(ref controlData), ReadOption.None).ThrowIfFailure();

                            RadioButton radioButton = new RadioButton($"Version {controlData.DisplayVersion.ToString()} - {path}");
                            radioButton.JoinGroup(_noUpdateRadioButton);

                            _availableUpdatesBox.Add(radioButton);
                            _radioButtonToPathDictionary.Add(radioButton, path);

                            radioButton.Show();
                            radioButton.Active = true;
                        }
                        else
                        {
                            GtkDialog.CreateErrorDialog("The specified file does not contain an update for the selected title!");
                        }
                    }
                    catch (InvalidDataException exception)
                    {
                        Logger.Error?.Print(LogClass.Application, $"{exception.Message}. Errored File: {path}");

                        if (showErrorDialog)
                        {
                            GtkDialog.CreateInfoDialog("Ryujinx - Error", "Add Update Failed!", "The NCA header content type check has failed. This is usually because the header key is incorrect or missing.");
                        }
                    }
                    catch (MissingKeyException exception)
                    {
                        Logger.Error?.Print(LogClass.Application, $"Your key set is missing a key with the name: {exception.Name}. Errored File: {path}");

                        if (showErrorDialog)
                        {
                            GtkDialog.CreateInfoDialog("Ryujinx - Error", "Add Update Failed!", $"Your key set is missing a key with the name: {exception.Name}");
                        }
                    }
                }
            }
        }
Esempio n. 26
0
 public static void Decompress(string inFile, string outDirPath, Output Out)
 {
     using (var file = new FileStream(inFile, FileMode.Open, FileAccess.Read))
         using (var fileStorage = file.AsStorage())
         {
             var pfs = new PartitionFileSystem(fileStorage);
             Out.Log(pfs.Print());
             var decompressedFs = new LocalFileSystem(outDirPath);
             DecompressFs.ProcessFs(pfs, decompressedFs, Out);
         }
 }
Esempio n. 27
0
        private long OpenNsp(ServiceCtx context, string pfsPath)
        {
            LocalStorage        storage = new LocalStorage(pfsPath, FileAccess.Read, FileMode.Open);
            PartitionFileSystem nsp     = new PartitionFileSystem(storage);

            ImportTitleKeysFromNsp(nsp, context.Device.System.KeySet);

            IFileSystem nspFileSystem = new IFileSystem(nsp);

            MakeObject(context, nspFileSystem);

            return(0);
        }
Esempio n. 28
0
        public static void Process(Context ctx)
        {
            using (var file = new LocalStorage(ctx.Options.InFile, FileAccess.Read))
            {
                var pfs = new PartitionFileSystem(file);
                ctx.Logger.LogMessage(pfs.Print());

                if (ctx.Options.OutDir != null)
                {
                    pfs.Extract(ctx.Options.OutDir, ctx.Logger);
                }
            }
        }
Esempio n. 29
0
        public NspItem LoadNsp(string nspFilePath)
        {
            var keySet = _keySetProviderService.GetKeySet(_appSettings.AlwaysReloadKeysBeforeOpen);

            var localFile = new LocalFile(nspFilePath, OpenMode.Read);

            var fileStorage  = new FileStorage(localFile);
            var nspPartition = new PartitionFileSystem(fileStorage);


            var nspItem = new NspItem(nspPartition, System.IO.Path.GetFileName(nspFilePath), localFile, keySet);

            BuildChildItems(nspItem);

            return(nspItem);
        }
Esempio n. 30
0
        public static void GetTitlekey(PartitionFileSystem pfs, Keyset keyset, Output Out)
        {
            IDirectory  sourceRoot = pfs.OpenDirectory("/", OpenDirectoryMode.All);
            IFileSystem sourceFs   = sourceRoot.ParentFileSystem;

            foreach (var entry in FileIterator(sourceRoot))
            {
                if (entry.Name.EndsWith(".tik"))
                {
                    using (var TicketFile = sourceFs.OpenFile(entry.Name, OpenMode.Read).AsStream())
                    {
                        TitleKeyTools.ExtractKey(TicketFile, entry.Name, keyset, Out);
                    }
                }
            }
        }