Example #1
0
        public IPacket ReadNextPacket()
        {
            AbstractBlock block;
            long          prevPosition = 0;

            while (this.binaryReader.BaseStream.Position < this.binaryReader.BaseStream.Length)
            {
                lock (this.syncRoot)
                {
                    prevPosition = this.binaryReader.BaseStream.Position;
                    block        = AbstractBlockFactory.ReadNextBlock(this.binaryReader, this.ReverseByteOrder, OnException);
                }

                if (block == null)
                {
                    throw new Exception($"[ReadPackets] AbstractBlockFactory cannot read packet on position {prevPosition}");
                }

                switch (block.BlockType)
                {
                case BaseBlock.Types.EnhancedPacket:
                    if (!(block is EnhancedPacketBlock enhancedBlock))
                    {
                        throw new Exception($"[ReadPackets] system cannot cast block to EnhancedPacketBlock. Block start on position: {prevPosition}.");
                    }
                    else
                    {
                        return(enhancedBlock);
                    }
Example #2
0
        public EnhancedPacketBlock GetPacketAt(long packetBlockOffset)
        {
            // TODO:
            bool reverseByteOrder = false;

            using (FileStream fileStream = File.Open(Path, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
                using (BinaryReader binReader = new BinaryReader(fileStream)) {
                    // Navigate to the overridden block start
                    long actualOffset = fileStream.Seek(packetBlockOffset, SeekOrigin.Begin);
                    // Make sure seek succeeded
                    if (actualOffset != packetBlockOffset)
                    {
                        throw new Exception($"Couldn't seek to offset {packetBlockOffset}");
                    }

                    // Read next 8 bytes of the block we are overriding:
                    BaseBlock.Types type = (BaseBlock.Types)binReader.ReadUInt32();
                    if (type != BaseBlock.Types.EnhancedPacket)
                    {
                        throw new Exception($"Expected an ENHANCED PACKET BLOCK (val:{BaseBlock.Types.EnhancedPacket}) in the given offset but got: {type}");
                    }
                    fileStream.Seek(-4, SeekOrigin.Current);

                    var block = AbstractBlockFactory.ReadNextBlock(binReader, reverseByteOrder, (ex) => Debug.WriteLine("Kek!" + ex));
                    if (block == null || block.BlockType != BaseBlock.Types.EnhancedPacket)
                    {
                        throw new Exception("Block at given position was not parsed to a ENHANCED PACKET BLOCK");
                    }
                    return(block as EnhancedPacketBlock);
                }
        }
Example #3
0
        public List <InterfaceDescriptionBlock> GetInterfaces()
        {
            if (_cachedIfacesBlock == null)
            {
                // TODO:
                bool reverseByteOrder = false;

                _cachedIfacesBlock = new List <InterfaceDescriptionBlock>();


                // Checking until first packet block or end of file
                using (FileStream fileStream = File.OpenRead(Path))
                    using (BinaryReader binReader = new BinaryReader(fileStream)) {
                        while (fileStream.Position != fileStream.Length)
                        {
                            // Read next 8 bytes of block:
                            BaseBlock.Types type = (BaseBlock.Types)binReader.ReadUInt32();
                            uint            len  = binReader.ReadUInt32();
                            if (type == BaseBlock.Types.EnhancedPacket)
                            {
                                // Found a packet block, stopping search
                                break;
                            }

                            if (type == BaseBlock.Types.InterfaceDescription)
                            {
                                fileStream.Seek(-8, SeekOrigin.Current);
                                var block = AbstractBlockFactory.ReadNextBlock(binReader, reverseByteOrder, (ex) => Debug.WriteLine("Kek!" + ex));
                                if (block == null || block.BlockType != BaseBlock.Types.InterfaceDescription)
                                {
                                    throw new Exception("Block at given position was not parsed to a INTERFACE DESCRIPTION BLOCK");
                                }
                                _cachedIfacesBlock.Add(block as InterfaceDescriptionBlock);
                            }
                            else
                            {
                                // Advance to next block start
                                fileStream.Seek(len - 8, SeekOrigin.Current);
                            }
                        }
                    }
            }
            return(_cachedIfacesBlock);
        }
Example #4
0
        private void Initialize(Stream stream, bool reverseByteOrder)
        {
            CustomContract.Requires <ArgumentNullException>(stream != null, "stream cannot be null");
            CustomContract.Requires <Exception>(stream.CanRead == true, "cannot read stream");
            Action <Exception> ReThrowException = (exc) =>
            {
                ExceptionDispatchInfo.Capture(exc).Throw();
            };

            this.ReverseByteOrder = reverseByteOrder;
            this.stream           = stream;
            this.binaryReader     = new BinaryReader(stream);
            var preHeadersWithInterface = new List <KeyValuePair <SectionHeaderBlock, List <InterfaceDescriptionBlock> > >();

            while (this.binaryReader.BaseStream.Position < this.binaryReader.BaseStream.Length && this.basePosition == 0)
            {
                AbstractBlock block = AbstractBlockFactory.ReadNextBlock(binaryReader, this.ReverseByteOrder, ReThrowException);
                if (block == null)
                {
                    break;
                }

                switch (block.BlockType)
                {
                case BaseBlock.Types.SectionHeader:
                    if (block is SectionHeaderBlock)
                    {
                        SectionHeaderBlock headerBlock = block as SectionHeaderBlock;
                        preHeadersWithInterface.Add(new KeyValuePair <SectionHeaderBlock, List <InterfaceDescriptionBlock> >(headerBlock, new List <InterfaceDescriptionBlock>()));
                    }
                    break;

                case BaseBlock.Types.InterfaceDescription:
                    if (block is InterfaceDescriptionBlock)
                    {
                        InterfaceDescriptionBlock interfaceBlock = block as InterfaceDescriptionBlock;
                        if (preHeadersWithInterface.Any())
                        {
                            preHeadersWithInterface.Last().Value.Add(interfaceBlock);
                        }
                        else
                        {
                            throw new Exception(string.Format("[PcapNgReader.Initialize] stream must contains SectionHeaderBlock before any InterfaceDescriptionBlock"));
                        }
                    }
                    break;

                default:
                    this.basePosition = block.PositionInStream;
                    break;
                }
            }
            if (this.basePosition <= 0)
            {
                this.basePosition = this.binaryReader.BaseStream.Position;
            }

            if (!preHeadersWithInterface.Any())
            {
                throw new ArgumentException(string.Format("[PcapNgReader.Initialize] Stream don't contains any SectionHeaderBlock"));
            }

            if (!(from item in preHeadersWithInterface where (item.Value.Any()) select item).Any())
            {
                throw new ArgumentException(string.Format("[PcapNgReader.Initialize] Stream don't contains any InterfaceDescriptionBlock"));
            }

            this.headersWithInterface = (from item in preHeadersWithInterface
                                         where (item.Value.Any())
                                         select item)
                                        .Select(x => new HeaderWithInterfacesDescriptions(x.Key, x.Value))
                                        .ToList();

            Rewind();
        }
Example #5
0
        public void ReadPackets(System.Threading.CancellationToken cancellationToken)
        {
            AbstractBlock block;
            long          prevPosition = 0;

            while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length && !cancellationToken.IsCancellationRequested)
            {
                try
                {
                    lock (syncRoot)
                    {
                        prevPosition = binaryReader.BaseStream.Position;
                        block        = AbstractBlockFactory.ReadNextBlock(binaryReader, this.ReverseByteOrder, OnException);
                    }

                    if (block == null)
                    {
                        throw new Exception(string.Format("[ReadPackets] AbstractBlockFactory cannot read packet on position {0}", prevPosition));
                    }

                    switch (block.BlockType)
                    {
                    case BaseBlock.Types.EnhancedPacket:
                    {
                        EnchantedPacketBlock enchantedBlock = block as EnchantedPacketBlock;
                        if (enchantedBlock == null)
                        {
                            throw new Exception(string.Format("[ReadPackets] system cannot cast block to EnchantedPacketBlock. Block start on position: {0}.", prevPosition));
                        }
                        else
                        {
                            OnReadPacket(enchantedBlock);
                        }
                    }
                    break;

                    case BaseBlock.Types.Packet:
                    {
                        PacketBlock packetBlock = block as PacketBlock;
                        if (packetBlock == null)
                        {
                            throw new Exception(string.Format("[ReadPackets] system cannot cast block to PacketBlock. Block start on position: {0}.", prevPosition));
                        }
                        else
                        {
                            OnReadPacket(packetBlock);
                        }
                    }
                    break;

                    case BaseBlock.Types.SimplePacket:
                    {
                        SimplePacketBlock simpleBlock = block as SimplePacketBlock;
                        if (simpleBlock == null)
                        {
                            throw new Exception(string.Format("[ReadPackets] system cannot cast block to SimplePacketBlock. Block start on position: {0}.", prevPosition));
                        }
                        else
                        {
                            OnReadPacket(simpleBlock);
                        }
                    }
                    break;

                    default:
                        break;
                    }
                }
                catch (Exception exc)
                {
                    OnException(exc);
                    lock (syncRoot)
                    {
                        if (prevPosition == binaryReader.BaseStream.Position)
                        {
                            break;
                        }
                    }
                    continue;
                }
            }
        }