Inheritance: System.ApplicationException
        /// <summary>
        /// Parses this object out of a stream
        /// </summary>
        /// <param name="input">The stream to read from</param>
        public void Parse(Stream input)
        {
            BinaryReader br = new BinaryReader(input);

            this._numGradients = br.ReadByte();

            if (1 > this._numGradients || 8 < this._numGradients)
            {
                SwfFormatException e = new SwfFormatException("Illegal number of gradients! The number of grad records must be between 1 and 8. This Gradient has " + this._numGradients + " grad records. Skipping.");
                Log.Warn(this, e.Message);
                throw e;
            }

            this._gradientRecords = new MorphGradRecord[this._numGradients];

            for (byte i = 0; i < this._numGradients; i++)
            {
                MorphGradRecord mg = new MorphGradRecord(this._SwfVersion);
                mg.Parse(input);
                this._gradientRecords[i] = mg;
            }
        }
Exemple #2
0
        /// <summary>
        /// Writes this object back to a stream
        /// </summary>
        /// <param name="output">The stream to write to.</param>
        public void Write(Stream output)
        {
            if (this._zoneData.Count != (Int32)this._numZoneData)
            {
                SwfFormatException e = new SwfFormatException("The count of List<ZoneData> and the byte value of zone data differs. ");
               Log.Error(this, e.Message);
                throw e;
            }

            output.WriteByte(this._numZoneData);

            for (int i = 0; i < this._zoneData.Count; i++)
            {
                this._zoneData[i].Write(output);
            }

            BitStream bits = new BitStream(output);
            bits.WriteBits(6, 0); //reserved
            bits.WriteBits(1, Convert.ToInt32(this._zoneMaskY));
            bits.WriteBits(1, Convert.ToInt32(this._zoneMaskX));
        }
Exemple #3
0
        /// <summary>
        /// Reads the header of an Swf file. Defines signature, version and length
        /// </summary>
        /// <param name="input"></param>
        protected void ReadHeader(Stream input)
        {
            BinaryReader br = new BinaryReader(input);

            if (!input.CanSeek)
            {
                Exception e = new ArgumentException("input stream can not seek");
                Log.Error(this, e);
                throw e;
            }

            input.Seek(0, SeekOrigin.Begin);

            byte[] sigbytes = br.ReadBytes(3);

            try
            {
                Signature = System.Text.ASCIIEncoding.ASCII.GetString(sigbytes);
                Version = br.ReadByte();
                Length = br.ReadUInt32();
            }
            catch (EndOfStreamException e)
            {
                Log.Error(this, e.Message);
                throw e;
            }

            // Checking the signature
            if (Signature.Equals("FWS", StringComparison.InvariantCulture))
            {
                Compressed = false;
            }
            else if (Signature.Equals("CWS", StringComparison.InvariantCulture))
            {
                Compressed = true;
            }
            else
            {
                Exception e = new SwfFormatException("Invalid Signature: '" + Signature + "'");
                Log.Error(this, e);
                throw e;
            }

            // Checking the version
            if ((Version > VersionMaximum) || (Version < VersionMinimum))
            {
                Exception e = new SwfFormatException("Invalid / unknown version " + Version.ToString());
                Log.Error(this, e);
                throw e;
            }
            if (Compressed && (Version < 6))
            {
                Log.Warn(this, "Compression is indicated, but version is " + Version.ToString() + " (must at least be 6)");
            }
        }
Exemple #4
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public Stream Read(Stream input)
        {
            _offset = (UInt64)input.Position;

            BinaryReader br = new BinaryReader(input);
            UInt16 TagAndCode = br.ReadUInt16();
            _type = (UInt16)(TagAndCode >> 6);

            // A length field of 0x3F indicates that the next 4 bytes
            // are a 32Bit lenght field (so-called long tag)
            UInt16 len = (UInt16)(TagAndCode & 0x3F);
            if (0x3F == len)
            {
                _length = br.ReadUInt32();
                _longTag = true;
            }
            else
            {
                _length = len;
                _longTag = false;
            }

            if (this.OffsetEnd > (UInt64)input.Length)
            {
                // TODO: Recheck
                // Verify the tag is entirely within the stream
                if (SwfFile.Configuration.HandleTagOversize == Configuration.HandleTagOversizeBy.RaiseError)
                {

                    SwfFormatException e = new SwfFormatException("The end of the tag " + (TagTypes)this._type + " : " + OffsetEnd.ToString() + " is beyond the end of the file stream : " + input.Length.ToString() + ". Header length was : " + SwfFile.HeaderDeclaredLength);
                    Log.Error(this, e);
                    throw e;
                }
                if (SwfFile.Configuration.HandleTagOversize == Configuration.HandleTagOversizeBy.ExpandStreamAndWipe)
                {
                    byte[] buffer = new byte[OffsetEnd];
                    long inputposition = input.Position;

                    input.Seek(0, SeekOrigin.Begin);
                    input.Read(buffer, 0, (int)inputposition);
                    MemoryStream ms = new MemoryStream(buffer);
                    input = ms;
                }

            }

            //if (SwfFile.Configuration.HandleTagOversize == Configuration.HandleTagOversizeBy.ExpandStream)
            //{
            //    throw new NotImplementedException("Implement me!");
            //}
            //
            // now place the stream position at the expected next tag
            //
            if (SwfFile.Configuration.SwfFileParsingMethod == Configuration.FileParsingMethod.Discontinuous)
            {
                input.Seek((long)this.OffsetEnd, SeekOrigin.Begin);
            }

            return input;
        }
Exemple #5
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        public void Parse( Stream input )
        {
            BinaryReader2 br = new BinaryReader2( input );

            _numFilters = br.ReadByte();
            _Filters = new List<AbstractFilter>( _numFilters );

            for ( int i = 0; i < _numFilters; i++ )
            {
                AbstractFilter.FilterTypes nextFilterType = ( AbstractFilter.FilterTypes )br.ReadByte();
                AbstractFilter aFilter;

                switch ( nextFilterType )
                {
                    case AbstractFilter.FilterTypes.DropShadowFilter:
                        aFilter = new Filter.DropShadowFilter( this.Version );
                        break;

                    case AbstractFilter.FilterTypes.BevelFilter:
                        aFilter = new Filter.BevelFilter( this.Version );
                        break;

                    case AbstractFilter.FilterTypes.BlurFilter:
                        aFilter = new Filter.BlurFilter( this.Version );
                        break;

                    case AbstractFilter.FilterTypes.ColorMatrixFilter:
                        aFilter = new Filter.ColorMatrixFilter( this.Version );
                        break;

                    case AbstractFilter.FilterTypes.ConvolutionFilter:
                        aFilter = new Filter.ConvolutionFilter( this.Version );
                        break;

                    case AbstractFilter.FilterTypes.GlowFilter:
                        aFilter = new Filter.GlowFilter( this.Version );
                        break;

                    case AbstractFilter.FilterTypes.GradientBevelFilter:
                        aFilter = new Filter.GradientBevelFilter( this.Version );
                        break;

                    case AbstractFilter.FilterTypes.GradientGlowFilter:
                        aFilter = new Filter.GradientGlowFilter( this.Version );
                        break;

                    default:
                        SwfFormatException e = new SwfFormatException( "Illegal Filter Type ID " + nextFilterType.ToString( "d" ) );
                       Log.Error(this,  e );
                        throw e;
                }

                aFilter.Parse( input );
                _Filters.Add( aFilter );
            }
        }
Exemple #6
0
        /// <summary>
        /// Writes this object back to a stream
        /// </summary>
        /// <param name="output">The stream to write to.</param>
        public void Write(Stream output)
        {
            if (!this._glyphEntries.Count.Equals(this._glyphCount))
            {
                SwfFormatException e = new SwfFormatException("The value of glyph count and the list size of glyphs muste be equal.");
               Log.Error(this, e.Message);
                throw e;
            }
            BitStream bits = new BitStream(output);

            bits.WriteBits(1, 1); // TextRecordType (always 1)
            bits.WriteBits(3, 0); // StyleFlagsReserved (always 0)
            bits.WriteBits(1, Convert.ToInt32(this._StyleFlagsHasFont));
            bits.WriteBits(1, Convert.ToInt32(this._StyleFlagsHasColor));
            bits.WriteBits(1, Convert.ToInt32(this._StyleFlagsHasYOffset));
            bits.WriteBits(1, Convert.ToInt32(this._StyleFlagsHasXOffset));
            bits.WriteFlush();

            if (this._StyleFlagsHasFont)
            {
                byte[] fontID = BitConverter.GetBytes(this._fontID);
                output.Write(fontID, 0, 2);
            }
            if (this._StyleFlagsHasColor)
            {
                this._textColor.Write(output);
            }
            if (this._StyleFlagsHasXOffset)
            {
                byte[] xOffset = BitConverter.GetBytes(this._xOffset);
                output.Write(xOffset, 0, 2);
            }
            if (this._StyleFlagsHasYOffset)
            {
                byte[] yOffset = BitConverter.GetBytes(this._yOffset);
                output.Write(yOffset, 0, 2);
            }
            if (this._StyleFlagsHasFont)
            {
                byte[] textHeight = BitConverter.GetBytes(this._textHeight);
                output.Write(textHeight, 0, 2);
            }

            output.WriteByte(this._glyphCount);

            for (int i = 0; i < this._glyphCount; i++)
            {
                this._glyphEntries[i].Write(bits);

            }
            bits.WriteFlush();
        }
Exemple #7
0
        /// <summary>
        /// Parses this object out of a stream
        /// </summary>
        public void Parse(Stream input, TagTypes caller, byte glyphBits, byte advancedBits, byte firstByte)
        {
            this._textRecordType = GetBit(firstByte, 0);
            bool reserved1 = GetBit(firstByte, 1);
            bool reserved2 = GetBit(firstByte, 2);
            bool reserved3 = GetBit(firstByte, 3);
            this._StyleFlagsHasFont = GetBit(firstByte, 4);
            this._StyleFlagsHasColor = GetBit(firstByte, 5);
            this._StyleFlagsHasYOffset = GetBit(firstByte, 6);
            this._StyleFlagsHasXOffset = GetBit(firstByte, 7);

            if (!this._textRecordType || (reserved1 || reserved2 || reserved3))
            {
                SwfFormatException e = new SwfFormatException("The first four bits have to have the static values {1,0,0,0} but set different.");
               Log.Error(this, e.Message);
                throw e;
            }

            BinaryReader br = new BinaryReader(input);

            if (this._StyleFlagsHasFont)
            {
                this._fontID = br.ReadUInt16();
            }

            if (this._StyleFlagsHasColor)
            {
                if (caller.Equals(TagTypes.DefineFont2) || caller.Equals(TagTypes.DefineText2))
                {
                    this._textColor = new Rgba(this._SwfVersion);
                    this._textColor.Parse(input);
                }
                else
                {
                    this._textColor.Parse(input);
                }
            }
            if (this._StyleFlagsHasXOffset)
            {
                this._xOffset = br.ReadInt16();
            }
            if (this._StyleFlagsHasYOffset)
            {
                this._yOffset = br.ReadInt16();
            }
            if (this._StyleFlagsHasFont)
            {
                this._textHeight = br.ReadUInt16();
            }

            this._glyphCount = br.ReadByte();

            BitStream bits = new BitStream(input);

            GlyphEntry tempGlyph = null;

            for (int i = 0; i < this._glyphCount; i++)
            {
                tempGlyph = new GlyphEntry(this._SwfVersion);
                tempGlyph.Parse(bits, glyphBits, advancedBits);
                this._glyphEntries.Add(tempGlyph);
            }
        }
Exemple #8
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="caller"></param>
        public virtual void Parse(Stream input, TagTypes caller)
        {
            BinaryReader br = new BinaryReader(input);

            this._width = br.ReadUInt16();

            if (caller.Equals(TagTypes.DefineShape) || caller.Equals(TagTypes.DefineShape2))
            {
                this._color = new Rgb(this._SwfVersion);

                try
                {
                    this._color.Parse(input);
                }
                catch(SwfFormatException e)
                {
                    throw e;
                }

            }
            else if (caller.Equals(TagTypes.DefineShape3))
            {
                this._color = new Rgba(this._SwfVersion);

                try
                {
                    this._color.Parse(input);
                }
                catch (SwfFormatException e)
                {
                    throw e;
                }

            }
            else
            {
                SwfFormatException e = new SwfFormatException("LineStyle was called by illegal TagType (" + caller.ToString() +").");
               Log.Error(this, e.Message);
            }
        }
Exemple #9
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="caller"></param>
        public void Parse(Stream input, TagTypes caller)
        {
            BinaryReader br = new BinaryReader(input);

            this._caller = caller;
            this._fillStyleType = (FillStyleType)br.ReadByte();

            if (this._fillStyleType.Equals(FillStyleType.SolidFill))
            {
                if (caller.Equals(TagTypes.DefineShape3) )
                {
                    this._color = new Rgba(this._SwfVersion);

                    try
                    {
                        this._color.Parse(input);
                        //Log.InfoFormat("Valid fill style type. FillstyleType: 0x{0:X2} at address: 0x{1:X2} in {2}", (Int32)this._fillStyleType, ((Int32)input.Position) - 1, caller);
                    }
                    catch (SwfFormatException e)
                    {
                        throw e;
                    }

                }
                else if (caller.Equals(TagTypes.DefineShape4))
                {
                    this._color = new Rgba(this._SwfVersion);

                    try
                    {
                        this._color.Parse(input);
                    }
                    catch (SwfFormatException e)
                    {
                        throw e;
                    }
                }
                else
                {
                    this._color = new Rgb(this._SwfVersion);

                    try
                    {
                        this._color.Parse(input);
                    }
                    catch (SwfFormatException e)
                    {
                        throw e;
                    }
                }
            }
            else if (this._fillStyleType.Equals(FillStyleType.LinearGradientFill) || this._fillStyleType.Equals(FillStyleType.RadialGradientFill))
            {
                this._gradientMatrix = new Matrix(this._SwfVersion);

                try
                {
                    this._gradientMatrix.Parse(input);
                }
                catch (SwfFormatException e)
                {
                    throw e;
                }

                this._gradient = new Gradient(this._SwfVersion);

                try
                {
                    this._gradient.Parse(input, caller);
                    //Log.InfoFormat("Valid fill style type. FillstyleType: 0x{0:X2} at address: 0x{1:X4} in {2}", (Int32)this._fillStyleType, ((Int32)input.Position) - 1, caller);
                }
                catch (SwfFormatException e)
                {
                    throw e;
                }

            }
            else if (this._fillStyleType.Equals(FillStyleType.FocalRadialGradientFill))
            {
                if (this._SwfVersion >= 8)
                {
                    this._gradientMatrix = new Matrix(this._SwfVersion);

                    try
                    {
                        this._gradientMatrix.Parse(input);

                    }
                    catch(SwfFormatException e)
                    {
                        throw e;
                    }

                    this._gradient = new FocalGradient(this._SwfVersion);

                    try
                    {
                        this._gradient.Parse(input, caller);
                        //Log.InfoFormat("Valid fill style type. FillstyleType: 0x{0:X2} at address: 0x{1:X4} in {2}", (Int32)this._fillStyleType, ((Int32)input.Position) - 1, caller);
                    }
                    catch (SwfFormatException e)
                    {
                        throw e;
                    }

                }
                else
                {
                    SwfFormatException e = new SwfFormatException("Focal gradients are supported by Swf 8 and later only. This version is: " + this._SwfVersion.ToString());
                   Log.Error(this, e);
                }
            }
            else if (this._fillStyleType.Equals(FillStyleType.RepeatingBitmapFill) ||
                      this._fillStyleType.Equals(FillStyleType.ClippedBitmapFill) ||
                      this._fillStyleType.Equals(FillStyleType.NonSmoothedRepeatingBitmap) ||
                      this._fillStyleType.Equals(FillStyleType.NonSmoothedClippedBitmap))
            {
                this._bitmapID = br.ReadUInt16();
                this._bitmapMatrix = new Matrix(this._SwfVersion);

                try
                {
                    this._bitmapMatrix.Parse(input);
                    //Log.InfoFormat("Valid fill style type. FillstyleType: 0x{0:X2} at address: 0x{1:X4} in {2}", (Int32)this._fillStyleType, ((Int32)input.Position) - 1, caller);
                }
                catch (SwfFormatException e)
                {
                    throw e;
                }

            }
            else
            {
                SwfFormatException e = new SwfFormatException("Invalid fill style type! (" + this._fillStyleType +")" +" caller: " + caller.ToString());
                Log.Error(this, e);
                throw e;
            }
        }
Exemple #10
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="imageDataSize"></param>
        /// <param name="bitmapFormat"></param>
        public virtual void Parse(Stream input, UInt64 imageDataSize, byte bitmapFormat)
        {
            if (bitmapFormat.Equals(0x04))
            {
                Pix15 temp = null;

                for (UInt64 i = 0; i < imageDataSize; i++)
                {
                    temp = new Pix15(this._SwfVersion);
                    temp.Parse(input);
                    this._bitmapPixelData.Add(temp);
                }

            }
            else if (bitmapFormat.Equals(0x05))
            {
                for (UInt64 i = 0; i < imageDataSize; i++)
                {
                    Pix24 temp = new Pix24(this._SwfVersion);
                    temp.Parse(input);
                    this._bitmapPixelData.Add(temp);
                }
            }
            else
            {
                SwfFormatException e = new SwfFormatException("BITMAPDATA can not contain any other bitmap formats than 15-bit RGB images or 24-bit RGB images ");
               Log.Error(this, e.Message);
                throw e;
            }
        }
Exemple #11
0
        /// <summary>
        /// 
        /// </summary>
        protected override void Parse()
        {
            // Call the code reader
            ParseCode((uint)(_tag.Length - this.CodeOffset));

            uint finalCodeLength = _code.Length;
            if (finalCodeLength > (_tag.Length - this.CodeOffset))
            {
                SwfFormatException e = new SwfFormatException("code length exceeds Tag length");
                Log.Error(this, e);
                throw e;
            }
            //
            // Sanity check: the total length of the code should
            // exactly consume the Tag's payload length.
            //
            else if (finalCodeLength < (_tag.Length - this.CodeOffset))
            {
                Log.Warn(this, "code length " + finalCodeLength.ToString("d") + " less than Tag length " + _tag.Length.ToString("d"));
            }
        }
Exemple #12
0
        /// <summary>
        /// Uncompresses ZLIB compressed files
        /// </summary>
        /// <param name="input">The ZLIB compressed file as stream</param>
        /// <returns>A uncompressed Stream</returns>
        public Stream Uncompress(Stream input)
        {
            MemoryStream returnStream = new MemoryStream();

            byte[] zipData = new byte[input.Length - 8];
            input.Read(zipData, 0, (int)(input.Length - 8));

            byte[] buffer = new byte[input.Length * 4];

            Inflater inflater = new Inflater(false);
            inflater.SetInput(zipData);

            try
            {
                int bytesInflated = inflater.Inflate(buffer);
                WriteHeader(returnStream);
                returnStream.Write(buffer, 0, bytesInflated);
                return returnStream;
            }
            catch (Exception e)
            {
                SwfFormatException s = new SwfFormatException(e.Message);
                Log.Error(this, s.Message);
                throw s;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public bool Parse( Stream input )
        {
            AVM1InstructionSequence bytecode;
            _ParsingFailures = false;

            _ClipEventFlags = new ClipEventFlags( this.Version );
            _ClipEventFlags.Parse( input );

            BinaryReader br = new BinaryReader( input );
            _length = br.ReadUInt32();
            _codeSize = _length;

            if ( _ClipEventFlags.ClipEventKeyPress )
            {
                if ( 1 > _length )
                {
                    throw new SwfFormatException( "ClipActionRecord length=0 but KeyCode indicated by ClipEventKeyPress" );
                }
                _KeyCode = br.ReadByte();
                _codeSize--;
            }

            long before = br.BaseStream.Position;

            try
            {
                bytecode = Helper.SwfCodeReader.GetCode( _codeSize, br, this.Version );

                if ( br.BaseStream.Position != ( before + _codeSize ) )
                {
                    throw new SwfFormatException( "ClipActionRecord code reader consumed more than length indicated (" +
                        ( ( uint )( br.BaseStream.Position - before ) ).ToString() + " consumed, " +
                        _codeSize + " length)" );
                }
            }
            catch ( AVM1ExceptionByteCodeFormat ave )
            {
               Log.Error(this,  ave );
                _ParsingFailures = true;

                if (SwfFile.Configuration.AVM1DeleteInvalidBytecode)
                {
                    bytecode = new AVM1InstructionSequence();
                }
                else
                {
                    SwfFormatException swfe = new SwfFormatException( "ClipActionRecord parsing error", ave );
                    throw swfe;
                }
            }
            finally
            {
                //
                // make sure that the input stream is at the right position
                // it would have if code reading would have been successful
                //
                long diff = ( before + _codeSize ) - br.BaseStream.Position;
                if ( 0 != diff )
                    br.BaseStream.Seek( diff, SeekOrigin.Current );
            }

            _Code = new AVM1Code( bytecode );

            return _ParsingFailures;
        }
Exemple #14
0
        /// <summary>
        /// Parses a Swf file tag by tag
        /// </summary>
        /// <param name="input">The Swf file as stream</param>
        /// <returns>The next tag</returns>
        public Stream Read(Stream input)
        {
            CwsSource = new CwsFile();
            FwsSource = new FwsFile();
            List<Tag> tags = new List<Tag>();

            Stream next = CwsSource.Read(input);

            if (this.CwsSource.Compressed)
            {
                // Fire compressed event
                if (null != SwfFileCompressed)
                    SwfFileCompressed(this, new CompressedEventArgs(true));
            }

            next = FwsSource.Read(next);

            HeaderDeclaredLength = FwsSource.Length;

            #region Reading tags

            Tag t;
            int tagNumber = 1;
            uint tagsLenghts = (uint)next.Position;

            do
            {
                t = new Tag();

                try
                {
                    next = t.Read(next);
                    Log.Debug(this, "Reading Tag #" + tagNumber + "(" + t.TagTypeName +")" + " Offset : 0x" + t.Offset.ToString("X08") + " Total-Length : 0x" + t.LengthTotal.ToString("X08"));
                    // Fire TagReadCompleted, ReadProgressChanged, if protected SwfFileProtected  events
                    if (null != TagReadCompleted)
                        TagReadCompleted(this, new TagHandlerReadCompleteEventArgs(t.TagType));
                    if (null != this.ReadProgressChanged)
                        ReadProgressChanged(this, new SwfReadProgressChangedEventArgs(next.Length, next.Position));
                    if (null != SwfFileProtected && t.TagType == TagTypes.Protect)
                        SwfFileProtected(this, new ProtectionEventArgs(""));

                    // Knowing if the offset end is longer than header declared length is enough to verfiy
                    if (t.OffsetEnd > this.FwsSource.Length)
                    {
                        if ((SwfFile.Configuration.HandleHeadSizeIssue == HandleHeadSizeIssueBy.Fix) && t.OffsetEnd <= (ulong)input.Length)
                        {
                            this.FwsSource.Length = (uint)t.OffsetEnd;
                            Log.Warn(this, "Tag #" + tagNumber + " ends outside (0x" + t.OffsetEnd.ToString("X08") + ") the declared Swf content range 0x" + this.FwsSource.Length.ToString("X08") + " Fixing.");
                        }
                        if ((SwfFile.Configuration.HandleHeadSizeIssue == HandleHeadSizeIssueBy.Ignore) && t.OffsetEnd <= (ulong)input.Length)
                        {
                            Log.Warn(this, "Tag #" + tagNumber + " ends outside (0x" + t.OffsetEnd.ToString("X08") + ") the declared Swf content range 0x" + this.FwsSource.Length.ToString("X08") + " Ignoring.");
                        }
                        else
                        {
                            SwfFormatException e = new SwfFormatException("Tag #" + tagNumber + " ends outside (0x" + t.OffsetEnd.ToString("X08") + ") the declared Swf content range 0x" + this.FwsSource.Length.ToString("X08"));
                            Log.Error(this, e);
                            throw e;
                        }

                    }

                    tagsLenghts += t.LengthTotal;
                    tagNumber++;
                    tags.Add(t);
                }
                catch (IOException ioe)
                {
                    //This is the point where we find no end tag which basically means that a tag declared more memory than the stream actaully has
                    Log.Error(this, ioe);
                    SwfFormatException e = new SwfFormatException("Tag list is incomplete, does not end with an END tag or a tag length exceeds the file size.");
                    Log.Error(this, e);

                    throw e;
                }
            }
            while (t.TagType != TagTypes.End);

            #endregion

            #region Length checking

            // Performing length checks now
            //
            // 1. Do the length of all tags match the stream length
            if (tagsLenghts != next.Length)
            {

                    SwfFormatException e = new SwfFormatException("The length of tags (" + tagsLenghts.ToString() + ") does not match the stream size(" + next.Length.ToString() + ").");
                    Log.Error(this, e);
                    throw e;
            }

            // 2. Does the tags lengths do match the header declared length
            if (tagsLenghts != this.CwsSource.Length)
            {
                if (SwfFile.Configuration.HandleHeadSizeIssue == HandleHeadSizeIssueBy.Fix)
                {
                    this.CwsSource.Length = tagsLenghts;
                    Log.Warn(this, "The length of tags (" + tagsLenghts.ToString() + ") does not match the header declared length(" + this.CwsSource.Length.ToString() + "). Stream size will be fixed.");
                }
                else if (SwfFile.Configuration.HandleHeadSizeIssue == HandleHeadSizeIssueBy.RaiseError)
                {
                    SwfFormatException e = new SwfFormatException("The length of tags (" + tagsLenghts.ToString() + ") does not match the header declared length(" + this.CwsSource.Length.ToString() + ").");
                    Log.Error(this, e);
                    throw e;
                }
                else
                {
                    Log.Warn(this, "The length of tags (" + tagsLenghts.ToString() + ") does not match the header declared length(" + this.CwsSource.Length.ToString() + "). Stream size will be fixed.");
                }

            }

            // 3. If stream and header length match has already been checked in FWSFile class

            // 4. Has the stream been consumed completely
            if (next.Position != next.Length)
            {
                if (SwfFile.Configuration.HandleStreamOversize == HandleStreamOversizeBy.Resize)
                {
                    this.FixIncorrectStreamSize(next, next.Position);
                    Log.Warn(this, "Trailing garbage after END tag detected. Position 0x" + input.Position.ToString("X08") + ", Length " + input.Length.ToString() + ". Dumping Trailing Garbage.");
                }
                else if (SwfFile.Configuration.HandleStreamOversize == HandleStreamOversizeBy.Ignore)
                {
                    Log.Warn(this, "Trailing garbage after END tag detected. Position 0x" + input.Position.ToString("X08") + ", Length " + input.Length.ToString());
                }
                else
                {
                    SwfFormatException e = new SwfFormatException("Trailing garbage after END tag detected. Position 0x" + input.Position.ToString("X08") + ", Length " + input.Length.ToString());
                    Log.Error(this, e);
                }

            }

            #endregion

            #region Producing tag handlers

            TagHandlers = new List<Recurity.Swf.TagHandler.AbstractTagHandler>();
            for (int i = 0; i < tags.Count; i++)
            {
                //
                // Only accept tag types that are documented by Adobe
                //
                if (!tags[i].IsTagTypeKnown)
                {
                    string msg = "Tag type " + ((UInt16)tags[i].TagType).ToString("d") + " not known/documented";

                    if (SwfFile.Configuration.AllowUnknownTagTypes)
                    {
                        Log.Warn(this, msg);
                    }
                    else
                    {
                        SwfFormatException e = new SwfFormatException(msg);
                        Log.Error(this, e);
                        throw e;
                    }
                }

                //
                // The factory automatically fires .Read() on the produced class. Therefore,
                // we catch Exceptions here (Stream too short) and convert them to SwfFormatExceptions
                //
                try
                {
                    TagHandlers.Add(TagHandlerFactory.Create(tags[i], this, next));

                    // Fire TagProduced event
                    if (null != TagProduced)//If a handler is attached
                        TagProduced(this, new TagHandlerProducedEventArgs(tags[i].TagType, (Int64)tags.Count, (Int64)i));
                }
                catch (Exception e)
                {
                    SwfFormatException swfE = new SwfFormatException("Tag handler #" + i + " (" + tags[i].TagTypeName + ") failed parsing: " + e.Message);
                    throw swfE;
                }

                if (tags[i].TagType.Equals(TagTypes.ST_GLYPHNAMES) || tags[i].TagType.Equals(TagTypes.ST_REFLEX))
                {
                    //this.CWSSource._GeneratorSoftware = "SwfTools";
                }

                //
                // Verify the required Version of each Tag against the header declared
                // Version.
                // It may be considered to make failing this test fatal.
                //
                if (TagHandlers[i].MinimumVersionRequired > this.Version)
                {
                    Log.Warn(this, "Tag " + (tags[i].IsTagTypeKnown ? tags[i].TagTypeName : tags[i].TagType.ToString()) +
                        " requires Swf version " + TagHandlers[i].MinimumVersionRequired.ToString() +
                        ", header declares " + this.Version.ToString());
                }
            }
            #endregion

            return next;
        }
Exemple #15
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public bool Parse( Stream input )
        {
            BinaryReader2 br = new BinaryReader2( input );
            bool parsingSuccess = true;

            UInt16 uselessButFiddelingWithBitsThanksAdobe = br.ReadUInt16();
            if ( 0 != uselessButFiddelingWithBitsThanksAdobe )
            {
                SwfFormatException sfe = new SwfFormatException( "Reserved 16Bit Field in CLIPACTION used" );
               Log.Error(this,  sfe );
                throw sfe;
            }

            _ClipEventFlags = new ClipEventFlags( this.Version );
            _ClipEventFlags.Parse( input );

            _ClipActionRecords = new List<ClipActionRecord>();
            //
            // The ClipActionEndFlag is Version dependent!
            //
            while ( 0 != ( this.Version <= 5 ? br.PeekUInt16() : br.PeekUInt32() ) )
            {
                ClipActionRecord record = new ClipActionRecord( this.Version );
                bool recordParsingResult = record.Parse( input );
                _ClipActionRecords.Add( record );
                parsingSuccess = recordParsingResult & parsingSuccess;
            }
            //
            // Get the EndRecord (Version dependent) and ignore
            //
            UInt32 endRecord = this.Version <= 5 ? br.ReadUInt16() : br.ReadUInt32();

            if ( 0 != endRecord )
            {
                SwfFormatException sfe = new SwfFormatException( "endRecord is not 0x00/0x0000" );
               Log.Error(this,  sfe );
                throw sfe;
            }

               //Log.Debug(this,  _ClipActionRecords.Count + " ClipActionRecords added" );

            return parsingSuccess;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="caller"></param>
        public virtual void Parse( Stream input, TagTypes caller )
        {
            BinaryReader br = new BinaryReader(input);

            this._fillStyleCount = br.ReadByte();

            if (this._fillStyleCount.Equals(0xFF))
            {
                if (caller.Equals(TagTypes.DefineShape2) || caller.Equals(TagTypes.DefineShape3))
                {
                    this._fillStyleCountExtended = br.ReadUInt16();

                    //Log.InfoFormat("{0}(0x{0:x4}) fillstyles will be parsed", (int)this._fillStyleCountExtended);

                    for (UInt16 i = 0; i < this._fillStyleCountExtended; i++)
                    {
                        FillStyle temp = new FillStyle(this._SwfVersion);
                        try
                        {
                            temp.Parse(input, caller);
                            this._fillStyles.Add(temp);
                        }
                        catch (SwfFormatException e)
                        {
                           Log.Error(this, e.Message);
                        }
                    }
                }
                else
                {
                    SwfFormatException e = new SwfFormatException("Extended count of fill styles supported only for Shape2 and Shape3.");
                   Log.Error(this, e.Message);
                    throw e;
                }
            }
            else
            {
                //Log.InfoFormat("{0}(0x{0:x4}) fillstyles will be parsed", (int)this._fillStyleCount);

                for (byte i = 0; i < this._fillStyleCount; i++)
                {
                    FillStyle temp = new FillStyle(this._SwfVersion);
                    try
                    {
                        temp.Parse(input, caller);
                    }
                    catch (SwfFormatException e)
                    {
                        throw e;
                    }

                    this._fillStyles.Add( temp);
                }
            }
        }