示例#1
0
        public void Extract(ref Dictionary <string, FileStream> streamCache, string destinationFolder, bool extractAsRaw)
        {
            string destinationFile = Path.Combine(Path.Combine(destinationFolder, this.ParentDirectoryName), this.FileName);

            byte[] magicBytes;

            if (!streamCache.ContainsKey(this.SourceFilePath))
            {
                streamCache[this.SourceFilePath] = File.OpenRead(this.SourceFilePath);
            }

            // check for CRILAYLA signature since file size is not always reliable,
            //    this will be a little slower, but hopefully the stream caching will minimize
            //    the impact
            magicBytes = ParseFile.ParseSimpleOffset(streamCache[this.SourceFilePath], (long)this.Offset, CriCpkArchive.CRILAYLA_SIGNATURE.Length);

            if (ParseFile.CompareSegment(magicBytes, 0, CriCpkArchive.CRILAYLA_SIGNATURE))
            {
                CriCpkArchive.Uncompress(streamCache[this.SourceFilePath], (long)this.Offset, this.Size, destinationFile);
            }
            else
            {
                ParseFile.ExtractChunkToFile64(streamCache[this.SourceFilePath], (ulong)this.Offset, (ulong)this.Size, destinationFile, false, false);
            }
        }
示例#2
0
        private void ValidateIvfcContainer(FileStream fs, long offset) // thanks to neimod's ctrtool
        {
            StringBuilder hashFailures = new StringBuilder();

            ulong blockCount;

            byte[]        blockToHash;
            byte[]        calculatedHash;
            byte[]        testHash;
            HashAlgorithm cryptoHash = SHA256.Create();

            uint badHashCount = 0, goodHashCount = 0;

            // only check level 1 and 2 hash on load, level 3 takes too long and can be performed on extraction
            for (ulong i = 0; i < 3; i++)
            {
                // verify hash block to data size
                blockCount = this.IvfcLevels[i].DataSize / this.IvfcLevels[i].HashBlockSize;

                if ((blockCount * this.IvfcLevels[i].HashBlockSize) != this.IvfcLevels[i].DataSize)
                {
                    throw new Exception("Error, IVFC block mismatch.");
                }

                // calculate hash and compare
                for (ulong j = 0; j < blockCount; j++)
                {
                    testHash = ParseFile.ParseSimpleOffset(fs, offset + (long)this.IvfcLevels[i].HashOffset + (long)(0x20 * j), 0x20);

                    blockToHash    = ParseFile.ParseSimpleOffset(fs, offset + (long)this.IvfcLevels[i].DataOffset + ((long)this.IvfcLevels[i].HashBlockSize * (long)j), (int)this.IvfcLevels[i].HashBlockSize);
                    calculatedHash = cryptoHash.ComputeHash(blockToHash);

                    if (!ParseFile.CompareSegment(calculatedHash, 0, testHash))
                    {
                        badHashCount++;
                    }
                    else
                    {
                        goodHashCount++;
                    }
                }

                if (badHashCount > 0)
                {
                    hashFailures.AppendFormat("IVFC hash failure(s) in Level {0}.  Good Blocks: {1}  Bad Blocks: {2}{3}", i + 1, goodHashCount.ToString(), badHashCount.ToString(), Environment.NewLine);
                }
                else
                {
                    hashFailures.AppendFormat("No IVFC hash failures found in Level {0} check.{1}", i + 1, Environment.NewLine);
                }
            } // for (ulong i = 0;...

            // display warning about hash failures
            if (hashFailures.Length > 0)
            {
                //hashFailures.Insert(0, String.Format("Hash Failures when Validating .3DS file.  This file is corrupted.{0}{0}", Environment.NewLine));
                //MessageBox.Show(hashFailures.ToString(), "Warning: Hash Failures in .3DS file.");
                MessageBox.Show(hashFailures.ToString(), "Hash Validation Results");
            }
        }
示例#3
0
        public static bool IsSonyAdpcmRow(Stream inputStream, long offset, ref Dictionary <long, bool> rowCheckHash)
        {
            bool ret = true;

            if (rowCheckHash.ContainsKey(offset))
            {
                ret = rowCheckHash[offset];
            }
            else
            {
                byte[] potentialAdpcm = new byte[SONY_ADPCM_ROW_SIZE];
                int    bytesRead;

                inputStream.Position = offset;
                bytesRead            = inputStream.Read(potentialAdpcm, 0, SONY_ADPCM_ROW_SIZE);

                if ((bytesRead != SONY_ADPCM_ROW_SIZE) ||
                    (potentialAdpcm[1] > 7) ||
                    (potentialAdpcm[0] > 0x4C) ||
                    ((potentialAdpcm[0] == 0) && (potentialAdpcm[1] != 2) && (GetCountOfZeroBytes(potentialAdpcm) > 14)) ||
                    (ParseFile.CompareSegment(potentialAdpcm, 0, VB_START_BYTES))
                    )
                {
                    ret = false;
                }

                // update hash table
                rowCheckHash[offset] = ret;
            }

            return(ret);
        }
示例#4
0
        public static DateTime GetIsoDateTime(byte[] isoDateArray)
        {
            DateTime dateValue = new DateTime();
            string   dateString;

            if (ParseFile.CompareSegment(isoDateArray, 0, EMPTY_DATETIME))
            {
                dateValue = DateTime.MinValue;
            }
            // Easy CD Creator v4.2 (310), and maybe others,
            //  doesn't set the Grenwich Mean Time offset to zero as it should
            else if (ParseFile.CompareSegmentUsingSourceOffset(isoDateArray, 0, EMPTY_DATETIME_HACK.Length, EMPTY_DATETIME_HACK))
            {
                dateValue = DateTime.MinValue;
            }
            else
            {
                dateString = ByteConversion.GetAsciiText(isoDateArray);
                dateValue  = new DateTime(Int32.Parse(dateString.Substring(0, 4).Replace("0000", "2000")),
                                          Int16.Parse(dateString.Substring(4, 2)),
                                          Int16.Parse(dateString.Substring(6, 2)),
                                          Int16.Parse(dateString.Substring(8, 2)),
                                          Int16.Parse(dateString.Substring(10, 2)),
                                          Int16.Parse(dateString.Substring(12, 2)),
                                          Int16.Parse(dateString.Substring(14, 2)));
            }

            return(dateValue);
        }
示例#5
0
        protected override string GetAudioFileExtension(Stream readStream, long currentOffset)
        {
            string fileExtension;

            byte[] checkBytes, checkBytesAc3;

            int headerSize = this.GetAudioPacketHeaderSize(readStream, currentOffset);

            checkBytes = ParseFile.ParseSimpleOffset(readStream, (currentOffset + 6 + headerSize), 4);

            if (ParseFile.CompareSegment(checkBytes, 0, AixSignatureBytes))
            {
                fileExtension = AixAudioExtension;
            }
            else if (checkBytes[0] == 0x80)
            {
                fileExtension = AdxAudioExtension;
            }
            else
            {
                checkBytesAc3 = ParseFile.ParseSimpleOffset(readStream, (currentOffset + 6 + headerSize), 2);

                if (ParseFile.CompareSegment(checkBytesAc3, 0, Ac3SignatureBytes))
                {
                    fileExtension = Ac3AudioExtension;
                }
                else
                {
                    fileExtension = ".bin";
                }
            }

            return(fileExtension);
        }
 protected bool IsThisAnAudioBlock(byte[] blockToCheck)
 {
     return(ParseFile.CompareSegment(blockToCheck, 0, ElectronicArtsVp6Stream.SCxx_BYTES) ||
            ParseFile.CompareSegment(blockToCheck, 0, ElectronicArtsVp6Stream.SHEN_BYTES) ||
            ParseFile.CompareSegment(blockToCheck, 0, ElectronicArtsVp6Stream.SCEN_BYTES) ||
            ParseFile.CompareSegment(blockToCheck, 0, ElectronicArtsVp6Stream.SDEN_BYTES) ||
            ParseFile.CompareSegment(blockToCheck, 0, ElectronicArtsVp6Stream.SEEN_BYTES));
 }
示例#7
0
 private void parseBankChunk()
 {
     foreach (ChunkStruct c in chunks)
     {
         if (ParseFile.CompareSegment(c.chunkIdentifier, 0, BANK_SIGNATURE))
         {
             this.bankSwitchInit = c.chunkData;
         }
     }
 }
示例#8
0
 private void parseDataChunk()
 {
     foreach (ChunkStruct c in chunks)
     {
         if (ParseFile.CompareSegment(c.chunkIdentifier, 0, DATA_SIGNATURE))
         {
             this.data = c.chunkData;
         }
     }
 }
示例#9
0
        public static bool IsUtfTable(FileStream fs, long offset,
                                      bool useIncomingKeys = false,
                                      Dictionary <string, byte> incomingLcgEncryptionKeys = null)
        {
            bool        ret = false;
            CriUtfTable utf = new CriUtfTable();

            utf.SourceFile = fs.Name;
            utf.BaseOffset = offset;

            try
            {
                utf.MagicBytes = ParseFile.ParseSimpleOffset(fs, utf.BaseOffset, 4);

                // check if file is decrypted and get decryption keys if needed
                utf.checkEncryption(fs, useIncomingKeys, incomingLcgEncryptionKeys);

                if (utf.IsEncrypted)
                {
                    // write (decrypted) utf header to file
                    utf.UtfTableFile = utf.WriteTableToTempFile(fs, offset, 4);

                    using (FileStream checkFs = File.Open(utf.UtfTableFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        utf.MagicBytes = ParseFile.ParseSimpleOffset(checkFs, utf.BaseOffset, 4);
                    }


                    //utf.IsEncrypted = false; // since we've decrypted to a temp file
                    // utf.UtfReader.IsEncrypted = false;
                }

                if (ParseFile.CompareSegment(utf.MagicBytes, 0, SIGNATURE_BYTES))
                {
                    ret = true;
                }
                else
                {
                    ret = false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (!String.IsNullOrEmpty(utf.UtfTableFile))
                {
                    File.Delete(utf.UtfTableFile);
                }
            }

            return(ret);
        }
示例#10
0
        public void Initialize(Stream pStream, string pFilePath)
        {
            this.filePath       = pFilePath;
            this.asciiSignature = this.getAsciiSignature(pStream);
            this.dummy26        = this.getDummy26(pStream);
            this.headerHasId666 = this.getHeaderHasId666(pStream);
            this.versionMinor   = this.getVersionMinor(pStream);
            this.registerPc     = this.getRegisterPc(pStream);
            this.registerA      = this.getRegisterA(pStream);
            this.registerX      = this.getRegisterX(pStream);
            this.registerY      = this.getRegisterY(pStream);
            this.registerPSW    = this.getRegisterPSW(pStream);
            this.registerSP     = this.getRegisterSP(pStream);
            this.reserved       = this.getReserved(pStream);

            // ID666
            if (ParseFile.CompareSegment(this.headerHasId666, 0, ID666_IN_HEADER_VAL))
            {
                this.id666 = this.getId666(pStream);

                this.id_songTitle        = this.getIdSongTitle(this.id666);
                this.id_gameTitle        = this.getIdGameTitle(this.id666);
                this.id_nameOfDumper     = this.getIdNameOfDumper(this.id666);
                this.id_comments         = this.getIdComments(this.id666);
                this.id_dumpDate         = this.getIdDumpDate(this.id666);
                this.id_numSecondsToPlay = this.getIdNumSecondsToPlay(this.id666);
                this.id_lengthOfFade     = this.getIdLengthOfFade(this.id666);
                this.id_songArtist       = this.getIdSongArtist(this.id666);
                this.id_defaultChanDisab = this.getIdDefaultChanDisab(this.id666);
                this.id_emulatorUsed     = this.getIdEmulatorUsed(this.id666);
                this.id_reserved         = this.getIdReserved(this.id666);
            }

            this.ram64k       = this.getRam64k(pStream);
            this.dspRegisters = this.getDspRegisters(pStream);
            this.unused       = this.getUnused(pStream);
            this.extraRam     = this.getExtraRam(pStream);
            this.extendedInfo = this.getExtendedInfo(pStream);

            this.initializeTagHash();
            this.initializeExId666Hash();

            // Extended ID666
            if (this.extendedInfo.Length > 0 &&
                ParseFile.CompareSegment(this.extendedInfo, 0, EXTENDED_ID666_SIGNATURE))
            {
                exidHeaderChunkSize = this.getExidHeaderChunkSize(this.extendedInfo);
                if (BitConverter.ToInt32(exidHeaderChunkSize, 0) > 0)
                {
                    exidFullChunk = ParseFile.ParseSimpleOffset(this.extendedInfo, EX_ID666_CHUNK_DATA_OFFSET, BitConverter.ToInt32(exidHeaderChunkSize, 0));
                }
                this.parseExtendedChunk(exidFullChunk);
            }
        }
示例#11
0
        public void Initialize(FileStream fs, long offset)
        {
            this.SourceFile = fs.Name;
            this.BaseOffset = offset;

            try
            {
                this.MagicBytes = ParseFile.ParseSimpleOffset(fs, this.BaseOffset, 4);

                // check if file is decrypted and get decryption keys if needed
                this.checkEncryption(fs);

                // write (decrypted) utf header to file
                this.UtfTableFile = this.WriteTableToTempFile(fs, offset);

                this.IsEncrypted           = false; // since we've decrypted to a temp file
                this.UtfReader.IsEncrypted = false;

                if (ParseFile.CompareSegment(this.MagicBytes, 0, SIGNATURE_BYTES))
                {
                    using (FileStream utfTableStream = File.Open(this.UtfTableFile, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        // read header
                        this.initializeUtfHeader(utfTableStream);

                        // initialize rows
                        this.Rows = new Dictionary <string, CriField> [this.NumberOfRows];

                        // read schema
                        if (this.TableSize > 0)
                        {
                            this.initializeUtfSchema(fs, utfTableStream, 0x20);
                        }
                    }
                }
                else
                {
                    //Dictionary<string, byte> foo = GetKeysForEncryptedUtfTable(this.MagicBytes);
                    throw new FormatException(String.Format("@UTF signature not found at offset <0x{0}>.", offset.ToString("X8")));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (!String.IsNullOrEmpty(this.UtfTableFile))
                {
                    File.Delete(this.UtfTableFile);
                }
            }
        }
示例#12
0
        public static bool IsCriAfs2Archive(FileStream fs, long offset)
        {
            var ret        = false;
            var checkBytes = ParseFile.ParseSimpleOffset(fs, offset, SIGNATURE.Length);

            if (ParseFile.CompareSegment(checkBytes, 0, SIGNATURE))
            {
                ret = true;
            }

            return(ret);
        }
示例#13
0
        }                                                              // for use by ACB extraction

        public static bool IsCriCpkArchive(FileStream fs, long offset)
        {
            var ret        = false;
            var checkBytes = ParseFile.ParseSimpleOffset(fs, offset, STANDARD_IDENTIFIER.Length);

            if (ParseFile.CompareSegment(checkBytes, 0, STANDARD_IDENTIFIER))
            {
                ret = true;
            }

            return(ret);
        }
        protected override void DoTaskForFile(string pPath, IVgmtWorkerStruct pExtractStruct, DoWorkEventArgs e)
        {
            ExtractCriAcbAwbStruct extractStruct = (ExtractCriAcbAwbStruct)pExtractStruct;

            byte[] magicBytes;
            long   awbOffset = 0;

            using (FileStream fs = File.Open(pPath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                magicBytes = ParseFile.ParseSimpleOffset(fs, 0, 4);

                this.progressStruct.Clear();

                // ACB
                if (ParseFile.CompareSegment(magicBytes, 0, CriAcbFile.SIGNATURE_BYTES))
                {
                    this.progressStruct.GenericMessage = String.Format("Processing ACB file: '{0}'.{1}", Path.GetFileName(pPath), Environment.NewLine);
                    ReportProgress(Constants.ProgressMessageOnly, this.progressStruct);

                    CriAcbFile acb = new CriAcbFile(fs, 0, extractStruct.IncludeCueIdInFileName);
                    acb.ExtractAll();
                }
                else if (ParseFile.CompareSegment(magicBytes, 0, CriAfs2Archive.SIGNATURE))
                {
                    this.progressStruct.GenericMessage = String.Format("Processing AWB file: '{0}'.{1}", Path.GetFileName(pPath), Environment.NewLine);
                    ReportProgress(Constants.ProgressMessageOnly, this.progressStruct);

                    CriAfs2Archive afs2 = new CriAfs2Archive(fs, 0);
                    afs2.ExtractAll();
                }
                else
                {
                    this.progressStruct.GenericMessage = String.Format("ACB/AWB signature not found at offset 0...scanning for AWB signature: '{0}'.{1}", Path.GetFileName(pPath), Environment.NewLine);
                    ReportProgress(Constants.ProgressMessageOnly, this.progressStruct);

                    awbOffset = ParseFile.GetNextOffset(fs, 0, CriAfs2Archive.SIGNATURE);

                    if (awbOffset > 0)
                    {
                        CriAfs2Archive afs2 = new CriAfs2Archive(fs, awbOffset);
                        afs2.ExtractAll();
                    }
                    else
                    {
                        this.progressStruct.GenericMessage = String.Format("File is not an ACB or AWB...skipping: '{0}'.{1}", Path.GetFileName(pPath), Environment.NewLine);
                        ReportProgress(Constants.ProgressMessageOnly, this.progressStruct);
                    }
                }
            }
        }
示例#15
0
 private void parsePlaylistChunk()
 {
     foreach (ChunkStruct c in chunks)
     {
         if (ParseFile.CompareSegment(c.chunkIdentifier, 0, PLST_SIGNATURE))
         {
             for (int i = 0; i < c.chunkData.Length; i++)
             {
                 this.playlist += c.chunkData[i].ToString() + ", ";
             }
             this.playlist = this.playlist.Substring(0, this.playlist.Length - 2);
         }
     }
 }
示例#16
0
        private void parseAuthChunk()
        {
            foreach (ChunkStruct c in chunks)
            {
                if (ParseFile.CompareSegment(c.chunkIdentifier, 0, AUTH_SIGNATURE))
                {
                    System.Text.Encoding enc = System.Text.Encoding.ASCII;
                    byte[] authBlock;
                    int    offset = 0;
                    int    labelLength;


                    if (offset < c.chunkData.Length)
                    {
                        labelLength   = ParseFile.GetSegmentLength(c.chunkData, offset, NULL_TERMINATOR);
                        authBlock     = ParseFile.ParseSimpleOffset(c.chunkData, offset, labelLength);
                        songName      = enc.GetString(authBlock);
                        songNameBytes = authBlock;
                        offset       += labelLength + 1;
                    }

                    if (offset < c.chunkData.Length)
                    {
                        labelLength     = ParseFile.GetSegmentLength(c.chunkData, offset, NULL_TERMINATOR);
                        authBlock       = ParseFile.ParseSimpleOffset(c.chunkData, offset, labelLength);
                        songArtist      = enc.GetString(authBlock);
                        songArtistBytes = authBlock;
                        offset         += labelLength + 1;
                    }

                    if (offset < c.chunkData.Length)
                    {
                        labelLength        = ParseFile.GetSegmentLength(c.chunkData, offset, NULL_TERMINATOR);
                        authBlock          = ParseFile.ParseSimpleOffset(c.chunkData, offset, labelLength);
                        songCopyright      = enc.GetString(authBlock);
                        songCopyrightBytes = authBlock;
                        offset            += labelLength + 1;
                    }

                    if (offset < c.chunkData.Length)
                    {
                        labelLength    = ParseFile.GetSegmentLength(c.chunkData, offset, NULL_TERMINATOR);
                        authBlock      = ParseFile.ParseSimpleOffset(c.chunkData, offset, labelLength);
                        nsfRipper      = enc.GetString(authBlock);
                        nsfRipperBytes = authBlock;
                        offset        += labelLength + 1;
                    }
                }
            }
        }
示例#17
0
 private void parseInfoChunk()
 {
     foreach (ChunkStruct c in chunks)
     {
         if (ParseFile.CompareSegment(c.chunkIdentifier, 0, INFO_SIGNATURE))
         {
             this.loadAddress    = ParseFile.ParseSimpleOffset(c.chunkData, LOAD_ADDRESS_OFFSET, LOAD_ADDRESS_LENGTH);
             this.initAddress    = ParseFile.ParseSimpleOffset(c.chunkData, INIT_ADDRESS_OFFSET, INIT_ADDRESS_LENGTH);
             this.playAddress    = ParseFile.ParseSimpleOffset(c.chunkData, PLAY_ADDRESS_OFFSET, PLAY_ADDRESS_LENGTH);
             this.palNtscBits    = ParseFile.ParseSimpleOffset(c.chunkData, PAL_NTSC_BITS_OFFSET, PAL_NTSC_BITS_LENGTH);
             this.extraChipsBits = ParseFile.ParseSimpleOffset(c.chunkData, EXTRA_SOUND_BITS_OFFSET, EXTRA_SOUND_BITS_LENGTH);
             this.totalSongs     = ParseFile.ParseSimpleOffset(c.chunkData, TOTAL_SONGS_OFFSET, TOTAL_SONGS_LENGTH);
             this.startingSong   = ParseFile.ParseSimpleOffset(c.chunkData, STARTING_SONG_OFFSET, STARTING_SONG_LENGTH);
         }
     }
 }
示例#18
0
        public static bool IsGzipFile(Stream pFileStream)
        {
            bool ret           = false;
            long currentOffset = pFileStream.Position;

            byte[] signatureBytes = ParseFile.ParseSimpleOffset(pFileStream, HEADER_OFFSET,
                                                                GZIP_SIGNATURE.Length);

            if (ParseFile.CompareSegment(signatureBytes, HEADER_OFFSET, GZIP_SIGNATURE))
            {
                ret = true;
            }

            pFileStream.Position = currentOffset;

            return(ret);
        }
示例#19
0
        private void parseFadesChunk()
        {
            foreach (ChunkStruct c in chunks)
            {
                if (ParseFile.CompareSegment(c.chunkIdentifier, 0, FADE_SIGNATURE))
                {
                    this.fades = new Int32[c.chunkData.Length / 4];
                    int j = 0;

                    for (int i = 0; i < c.chunkData.Length; i += 4)
                    {
                        byte[] tempTime = ParseFile.ParseSimpleOffset(c.chunkData, i, 4);
                        this.fades[j] = BitConverter.ToInt32(tempTime, 0);
                        j++;
                    }
                }
            }
        }
示例#20
0
        /// <summary>
        /// Checks for WAD file Magic Bytes.
        /// </summary>
        /// <param name="sourceFile">Full path to file to check.</param>
        /// <returns>Boolean value indicating if input file has WAD magic bytes.</returns>
        public static bool IsWadFile(string sourceFile)
        {
            bool isWad = false;

            byte[] magicBytes = new byte[NintendoWad.STANDARD_IDENTIFIER.Length];

            using (FileStream fs = File.OpenRead(sourceFile))
            {
                magicBytes = ParseFile.ParseSimpleOffset(fs, NintendoWad.IDENTIFIER_OFFSET, NintendoWad.STANDARD_IDENTIFIER.Length);

                if (ParseFile.CompareSegment(magicBytes, 0, NintendoWad.STANDARD_IDENTIFIER))
                {
                    isWad = true;
                }
            }

            return(isWad);
        }
示例#21
0
        public static bool IsGzipFile(string pFilePath)
        {
            bool ret = false;

            byte[] signatureBytes = null;
            using (FileStream fs = File.OpenRead(pFilePath))
            {
                signatureBytes = ParseFile.ParseSimpleOffset(fs, HEADER_OFFSET, GZIP_SIGNATURE.Length);
            }

            if ((signatureBytes != null) &&
                (ParseFile.CompareSegment(signatureBytes, HEADER_OFFSET, GZIP_SIGNATURE)))
            {
                ret = true;
            }

            return(ret);
        }
示例#22
0
        public static bool IsSeqTypeSequence(string fileName)
        {
            bool ret = false;
            int  numBytesRead;

            byte[] checkBytes = new byte[PsxSequence.ASCII_SIGNATURE_SEQ.Length];

            using (FileStream fs = File.OpenRead(fileName))
            {
                numBytesRead = fs.Read(checkBytes, 0, PsxSequence.ASCII_SIGNATURE_SEQ.Length);

                if (numBytesRead == PsxSequence.ASCII_SIGNATURE_SEQ.Length)
                {
                    ret = ParseFile.CompareSegment(checkBytes, 0, PsxSequence.ASCII_SIGNATURE_SEQ);
                }
            }

            return(ret);
        }
示例#23
0
        public static bool IsSonyAdpcmRow(byte[] potentialAdpcm, bool doAdditionalChecks)
        {
            bool ret = true;

            if ((potentialAdpcm.Length != SONY_ADPCM_ROW_SIZE) ||
                (potentialAdpcm[1] > 7) ||
                (potentialAdpcm[0] > 0x4C) ||
                (ParseFile.CompareSegment(potentialAdpcm, 0, VB_START_BYTES))
                )
            {
                ret = false;
            }
            else if (doAdditionalChecks &&
                     ((potentialAdpcm[0] == 0) && (potentialAdpcm[1] != 2) && (GetCountOfZeroBytes(potentialAdpcm) > 14)))
            {
                ret = false;
            }
            return(ret);
        }
示例#24
0
        protected override string GetVideoFileExtension(Stream readStream, long currentOffset)
        {
            string fileExtension;

            byte[] checkBytes;
            int    videoHeaderSize = this.GetVideoPacketHeaderSize(readStream, currentOffset);

            checkBytes = ParseFile.ParseSimpleOffset(readStream, (currentOffset + videoHeaderSize + 6), 4);

            if (ParseFile.CompareSegment(checkBytes, 0, AvcBytes))
            {
                fileExtension = AvcVideoExtension;
            }
            else
            {
                fileExtension = ".bin";
            }

            return(fileExtension);
        }
示例#25
0
        public static MovieType GetMobiclipStreamType(string path)
        {
            MovieType streamType = MovieType.Unknown;

            using (FileStream fs = File.OpenRead(path))
            {
                byte[] typeBytes = ParseFile.ParseSimpleOffset(fs, 2, 2);

                if (ParseFile.CompareSegment(typeBytes, 0, MobiclipNdsStream.StreamTypeBytes))
                {
                    streamType = MovieType.NintendoDs;
                }
                else if (ParseFile.CompareSegment(typeBytes, 0, MobiclipWiiStream.StreamTypeBytes))
                {
                    streamType = MovieType.Wii;
                }
            }

            return(streamType);
        }
示例#26
0
        private void parseTrackLabelsChunk()
        {
            foreach (ChunkStruct c in chunks)
            {
                if (ParseFile.CompareSegment(c.chunkIdentifier, 0, TRACK_LABELS_SIGNATURE))
                {
                    System.Text.Encoding enc = System.Text.Encoding.ASCII;
                    int offset = 0;

                    while (offset < c.chunkData.Length)
                    {
                        int    labelLength = ParseFile.GetSegmentLength(c.chunkData, offset, NULL_TERMINATOR);
                        byte[] trackLabel  = ParseFile.ParseSimpleOffset(c.chunkData, offset, labelLength);
                        this.trackLabels.Add(enc.GetString(trackLabel));

                        offset += labelLength + 1;
                    }
                }
            }
        }
示例#27
0
        private void checkEncryption(FileStream fs, bool useIncomingKeys = false,
                                     Dictionary <string, byte> incomingLcgEncryptionKeys = null)
        {
            if (ParseFile.CompareSegment(MagicBytes, 0, SIGNATURE_BYTES) ||
                useIncomingKeys && incomingLcgEncryptionKeys == null
                )
            {
                IsEncrypted = false;
                UtfReader   = new CriUtfReader();
            }
            else
            {
                IsEncrypted = true;

                if (useIncomingKeys) // use incoming keys if available
                {
                    if (incomingLcgEncryptionKeys != null)
                    {
                        LcgEncryptionKeys = incomingLcgEncryptionKeys;
                    }
                }
                else if (LcgEncryptionKeys == null) // use keys found earlier, assume same keys for entire file
                {
                    LcgEncryptionKeys = GetKeysForEncryptedUtfTable(MagicBytes);
                }

                if (LcgEncryptionKeys.Count != 2)
                {
                    throw new FormatException(string.Format("Unable to decrypt UTF table at offset: 0x{0}",
                                                            BaseOffset.ToString("X8")));
                }
                else
                {
                    UtfReader = new CriUtfReader(LcgEncryptionKeys[LCG_SEED_KEY],
                                                 LcgEncryptionKeys[LCG_INCREMENT_KEY], IsEncrypted);
                }

                MagicBytes = UtfReader.GetBytes(fs, BaseOffset, 4, 0);
            }
        }
示例#28
0
        public static bool IsSonyAdpcmRow(Stream inputStream, long offset)
        {
            bool ret = true;

            byte[] potentialAdpcm = new byte[SONY_ADPCM_ROW_SIZE];
            int    bytesRead;

            inputStream.Position = offset;
            bytesRead            = inputStream.Read(potentialAdpcm, 0, SONY_ADPCM_ROW_SIZE);

            if ((bytesRead != SONY_ADPCM_ROW_SIZE) ||
                (potentialAdpcm[1] > 7) ||
                (potentialAdpcm[0] > 0x4C) ||
                ((potentialAdpcm[0] == 0) && (potentialAdpcm[1] != 2) && (GetCountOfZeroBytes(potentialAdpcm) > 14)) ||
                (ParseFile.CompareSegment(potentialAdpcm, 0, VB_START_BYTES))
                )
            {
                ret = false;
            }

            return(ret);
        }
示例#29
0
        public void Extract(ref Dictionary <string, FileStream> streamCache, string destinationFolder, bool extractAsRaw)
        {
            string destinationFile = Path.Combine(Path.Combine(destinationFolder, this.ParentDirectoryName), this.FileName);

            if (!streamCache.ContainsKey(this.SourceFilePath))
            {
                streamCache[this.SourceFilePath] = File.OpenRead(this.SourceFilePath);
            }

            //-----------------------------------------------------------
            // ExeFS
            //-----------------------------------------------------------
            if (this.FileSystem == Nintendo3dsCtr.FileSystemType.ExeFS)
            {
                // write file while calculating hash
                HashAlgorithm cryptoHash = SHA256.Create();
                byte[]        outputHash = ParseFile.ExtractChunkToFile64ReturningHash(streamCache[this.SourceFilePath], (ulong)this.Offset, (ulong)this.Size,
                                                                                       destinationFile, cryptoHash, false, false);

                if (!ParseFile.CompareSegment(outputHash, 0, this.Sha256Hash))
                {
                    // @TODO: only show error once per file
                    //if (!sha1ErrorDisplayed)
                    {
                        MessageBox.Show(String.Format("Warning: '{0},' failed SHA256 verification in ExeFS at offset 0x{1} during extraction.{2}",
                                                      Path.GetFileName(destinationFile), this.Offset, Environment.NewLine), "Warning - SHA256 Failure");
                    }
                }
            }
            //---------------
            // RomFS
            //---------------
            else
            {
                // @TODO: Modify to verify on extraction
                ParseFile.ExtractChunkToFile64(streamCache[this.SourceFilePath], (ulong)this.Offset,
                                               (ulong)this.Size, destinationFile, false, false);
            }
        }
示例#30
0
        private void ReadHeader(FileStream thpStream, long currentOffset)
        {
            byte[] magicBytes = ParseFile.ParseSimpleOffset(thpStream, currentOffset, MAGIC_BYTES.Length);
            byte[] tempChunk;

            if (ParseFile.CompareSegment(magicBytes, 0, MAGIC_BYTES))
            {
                tempChunk = ParseFile.ParseSimpleOffset(thpStream, currentOffset + 4, 4);

                if (ParseFile.CompareSegment(tempChunk, 0, VERSON_10))
                {
                    this.Version = ThpVersion.Version10;
                }
                else
                {
                    this.Version = ThpVersion.Version11;
                }

                this.MaxBufferSize   = ByteConversion.GetUInt32BigEndian(ParseFile.ParseSimpleOffset(thpStream, currentOffset + 8, 4));
                this.MaxAudioSamples = ByteConversion.GetUInt32BigEndian(ParseFile.ParseSimpleOffset(thpStream, currentOffset + 0xC, 4));
                this.ContainsAudio   = (this.MaxAudioSamples > 0);

                // public float Fps { set; get; }
                this.NumberOfFrames = ByteConversion.GetUInt32BigEndian(ParseFile.ParseSimpleOffset(thpStream, currentOffset + 0x14, 4));
                this.FirstFrameSize = ByteConversion.GetUInt32BigEndian(ParseFile.ParseSimpleOffset(thpStream, currentOffset + 0x18, 4));

                this.DataSize            = ByteConversion.GetUInt32BigEndian(ParseFile.ParseSimpleOffset(thpStream, currentOffset + 0x1C, 4));
                this.ComponentDataOffset = ByteConversion.GetUInt32BigEndian(ParseFile.ParseSimpleOffset(thpStream, currentOffset + 0x20, 4));
                this.ComponentTypes      = ParseFile.ParseSimpleOffset(thpStream, currentOffset + 0x24, 16);

                this.FirstFrameOffset = ByteConversion.GetUInt32BigEndian(ParseFile.ParseSimpleOffset(thpStream, currentOffset + 0x28, 4));
                this.LastFrameOffset  = ByteConversion.GetUInt32BigEndian(ParseFile.ParseSimpleOffset(thpStream, currentOffset + 0x2C, 4));
            }
            else
            {
                throw new FormatException("Magic bytes 'THP\\0' not found.");
            }
        }