Exemplo n.º 1
0
        bool TryDecodePacket(IChannelHandlerContext context, IByteBuffer buffer, out Packet packet)
        {
            if (!buffer.IsReadable(2))
            {
                packet = null;
                return(false);
            }

            byte signature = buffer.ReadByte();

            if (!TryDecodeRemainingLength(buffer, out int remainingLength) || !buffer.IsReadable(remainingLength))
            {
                packet = null;
                return(false);
            }

            packet = DecodePacketInternal(buffer, signature, ref remainingLength);

            if (remainingLength > 0)
            {
                throw new DecoderException($"Declared remaining length is bigger than packet data size by {remainingLength}.");
            }

            return(true);
        }
Exemplo n.º 2
0
        bool TryDecodePacket(IByteBuffer buffer, IChannelHandlerContext context, out Packet packet)
        {
            if (!buffer.IsReadable(2)) // packet consists of at least 2 bytes
            {
                packet = null;
                return(false);
            }

            int signature = buffer.ReadByte();

            if (!TryDecodeRemainingLength(buffer, out var remainingLength) || !buffer.IsReadable(remainingLength))
            {
                packet = null;
                return(false);
            }

            packet = DecodePacketInternal(buffer, signature, ref remainingLength, context);

            if (remainingLength > 0)
            {
                ThrowHelper.ThrowDecoderException_DeclaredRemainingLen(remainingLength);
            }

            return(true);
        }
        /// <summary>
        /// Decodes a game packet from the client.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="input"></param>
        /// <param name="output"></param>
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            while (input.ReadableBytes > 0 && input.IsReadable())
            {
                switch (State)
                {
                case PacketDecoderState.PACKET_ID:
                    id = (input.ReadByte() /* - isaac.val()*/) & 0xff;
                    if (id >= PacketConstants.PACKET_SIZES.Length || id < 0)
                    {
                        break;
                    }
                    Checkpoint(PacketDecoderState.PACKET_SIZE);
                    break;

                case PacketDecoderState.PACKET_SIZE:
                    size = PacketConstants.PACKET_SIZES[id];
                    if (size < 0)
                    {
                        switch (size)
                        {
                        case -1:
                            if (input.IsReadable())
                            {
                                size = input.ReadByte() & 0xff;
                            }
                            break;

                        case -2:
                            if (input.ReadableBytes >= 2)
                            {
                                size = input.ReadUnsignedShort();
                            }
                            break;

                        default:
                            size = input.ReadableBytes;
                            break;
                        }
                    }
                    Checkpoint(PacketDecoderState.PACKET_PAYLOAD);
                    break;

                case PacketDecoderState.PACKET_PAYLOAD:
                    if (input.ReadableBytes >= size)
                    {
                        if (size < 0)
                        {
                            return;
                        }
                        byte[] payload = new byte[size];
                        input.ReadBytes(payload, 0, size);
                        output.Add(new GamePacketRequest(player, id, Unpooled.WrappedBuffer(payload)));
                    }
                    Checkpoint(PacketDecoderState.PACKET_ID);
                    break;
                }
            }
        }
Exemplo n.º 4
0
        bool TryDecodePacket(IChannelHandlerContext context, IByteBuffer buffer, out Packet packet)
        {
            if (!buffer.IsReadable(2))
            {
                packet = null;
                return(false);
            }

            byte signature = buffer.ReadByte();

            if (!TryDecodeRemainingLength(buffer, out int remainingLength) || !buffer.IsReadable(remainingLength))
            {
                packet = null;
                return(false);
            }

            var fixedHeader = new FixedHeader(signature, remainingLength);

            switch (fixedHeader.PacketType)
            {
            case PacketType.CONNECT: packet = new ConnectPacket(); break;

            case PacketType.CONNACK: packet = new ConnAckPacket(); break;

            case PacketType.DISCONNECT: packet = new DisconnectPacket(); break;

            case PacketType.PINGREQ: packet = new PingReqPacket(); break;

            case PacketType.PINGRESP: packet = new PingRespPacket(); break;

            case PacketType.PUBACK: packet = new PubAckPacket(); break;

            case PacketType.PUBCOMP: packet = new PubCompPacket(); break;

            case PacketType.PUBLISH: packet = new PublishPacket(); break;

            case PacketType.PUBREC: packet = new PubRecPacket(); break;

            case PacketType.PUBREL: packet = new PubRelPacket(); break;

            case PacketType.SUBSCRIBE: packet = new SubscribePacket(); break;

            case PacketType.SUBACK: packet = new SubAckPacket(); break;

            case PacketType.UNSUBSCRIBE: packet = new UnsubscribePacket(); break;

            case PacketType.UNSUBACK: packet = new UnsubscribePacket(); break;

            default:
                throw new DecoderException("Unsupported Message Type");
            }
            packet.FixedHeader = fixedHeader;
            packet.Decode(buffer);

            return(true);
        }
Exemplo n.º 5
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            if (input.ReadableBytes > 0 && input.IsReadable())
            {
                input.MarkReaderIndex();
                int opcode = input.ReadByte();

                Log.Logger.Debug("File Request: Opcode: {0}", opcode);
                if (opcode is 0 or 1)
                {
                    if (input.ReadableBytes < 3)
                    {
                        input.ResetReaderIndex();
                        return;
                    }
                    int  index    = input.ReadByte();
                    int  file     = input.ReadUnsignedShort();
                    bool priority = opcode == 1;
                    Log.Logger.Debug("File Request: Index: {0}, File: {1} Priority: {2}", index, file, priority);
                    _ = context.Channel.WriteAndFlushAsync(new JS5Request(index, file, priority, _encryptionKey));
                }
                else if (opcode is 2 or 3 or 6)
                {
                    input.SkipBytes(3);
                }
Exemplo n.º 6
0
        /// <exception cref="MalformedMessageException">Exception is thrown in case of invalid packet length</exception>
        private static LengthDetails DecodeLength(IByteBuffer buf)
        {
            Int32 length = 0, multiplier = 1;
            Int32 bytesUsed = 0;
            Byte  enc       = 0;

            do
            {
                if (multiplier > 128 * 128 * 128)
                {
                    throw new MalformedMessageException("Encoded length exceeds maximum of 268435455 bytes");
                }

                if (!buf.IsReadable())
                {
                    return(new LengthDetails(0, 0));
                }

                enc         = buf.ReadByte();
                length     += (enc & 0x7f) * multiplier;
                multiplier *= 128;
                bytesUsed++;
            }while ((enc & 0x80) != 0);

            return(new LengthDetails(length, bytesUsed));
        }
Exemplo n.º 7
0
        private bool TryDecodePacket(IChannelHandlerContext context, IByteBuffer buffer, out Packet packet)
        {
            if (!buffer.IsReadable(2))
            {
                packet = default;
                return(false);
            }

            FixedHeader fixedHeader = default;

            fixedHeader.Decode(buffer);
            packet = fixedHeader.PacketType switch
            {
                PacketType.CONNECT => new ConnectPacket(),
                PacketType.CONNACK => new ConnAckPacket(),
                PacketType.DISCONNECT => new DisconnectPacket(),
                PacketType.PINGREQ => new PingReqPacket(),
                PacketType.PINGRESP => new PingRespPacket(),
                PacketType.PUBACK => new PubAckPacket(),
                PacketType.PUBCOMP => new PubCompPacket(),
                PacketType.PUBLISH => new PublishPacket(),
                PacketType.PUBREC => new PubRecPacket(),
                PacketType.PUBREL => new PubRelPacket(),
                PacketType.SUBSCRIBE => new SubscribePacket(),
                PacketType.SUBACK => new SubAckPacket(),
                PacketType.UNSUBSCRIBE => new UnsubscribePacket(),
                PacketType.UNSUBACK => new UnsubscribePacket(),
                _ => throw new DecoderException("Unsupported Message Type"),
            };
            packet.FixedHeader = fixedHeader;
            packet.Decode(buffer);

            return(true);
        }
Exemplo n.º 8
0
 public IByteBuffer Cumulate(IByteBufferAllocator alloc, IByteBuffer cumulation, IByteBuffer input)
 {
     if (!cumulation.IsReadable() && input.IsContiguous)
     {
         // If cumulation is empty and input buffer is contiguous, use it directly
         _ = cumulation.Release();
         return(input);
     }
     try
     {
         int required = input.ReadableBytes;
         if (required > cumulation.MaxWritableBytes ||
             (required > cumulation.MaxFastWritableBytes && cumulation.ReferenceCount > 1) ||
             cumulation.IsReadOnly)
         {
             // Expand cumulation (by replacing it) under the following conditions:
             // - cumulation cannot be resized to accommodate the additional data
             // - cumulation can be expanded with a reallocation operation to accommodate but the buffer is
             //   assumed to be shared (e.g. refCnt() > 1) and the reallocation may not be safe.
             return(ExpandCumulation(alloc, cumulation, input));
         }
         _ = cumulation.WriteBytes(input, input.ReaderIndex, required);
         _ = input.SetReaderIndex(input.WriterIndex);
         return(cumulation);
     }
     finally
     {
         // We must release in in all cases as otherwise it may produce a leak if writeBytes(...) throw
         // for whatever release (for example because of OutOfMemoryError)
         _ = input.Release();
     }
 }
Exemplo n.º 9
0
        /// <summary>
        /// Decodes the handshake.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="input"></param>
        /// <param name="output"></param>
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            if (!input.IsReadable())
            {
                return;
            }

            HandshakeType type = Handshake.GetHandshakeType(input.ReadByte());

            if (type == HandshakeType.NONE)
            {
                return;
            }

            switch (type)
            {
            case HandshakeType.UPDATE_CONNECTION:
                int version = input.ReadInt();
                output.Add(new HandshakeRequest(version));
                break;

            case HandshakeType.LOGIN_CONNECTION:
                context.Channel.WriteAndFlushAsync(new HandshakeResponse(type, ConnectionMessage.SUCCESSFUL));
                break;
            }
        }
Exemplo n.º 10
0
        static void EncodePublishMessage(DataWriter writer, PublishPacket packet)
        {
            IByteBuffer payload = packet.Payload ?? Unpooled.Empty;

            string topicName = packet.TopicName;

            // Util.ValidateTopicName(topicName);
            byte[] topicNameBytes = EncodeStringInUtf8(topicName);

            int variableHeaderBufferSize = STRING_SIZE_LENGTH + topicNameBytes.Length +
                                           (packet.QualityOfService > QualityOfService.AtMostOnce ? PACKET_ID_LENGTH : 0);
            int payloadBufferSize = payload.ReadableBytes;
            int variablePartSize  = variableHeaderBufferSize + payloadBufferSize;

            writer.WriteByte(CalculateFirstByteOfFixedHeader(packet));
            WriteVariableLengthInt(writer, variablePartSize);
            writer.WriteInt16((short)topicNameBytes.Length);
            writer.WriteBytes(topicNameBytes);
            if (packet.QualityOfService > QualityOfService.AtMostOnce)
            {
                writer.WriteInt16((short)packet.PacketId);
            }

            if (payload.IsReadable())
            {
                var payloadBytes = new byte[payload.ReadableBytes];
                payload.ReadBytes(payloadBytes);
                writer.WriteBytes(payloadBytes);
            }
        }
Exemplo n.º 11
0
        public static bool TryReadVarInt32(this IByteBuffer buffer, out int result)
        {
            buffer.MarkReaderIndex();

            var numBytes = (byte)0;

            result = 0;
            byte read;

            do
            {
                if (!buffer.IsReadable())
                {
                    buffer.ResetReaderIndex();
                    return(false);
                }

                read = buffer.ReadByte();
                var value = read & VarIntContentMask;
                result |= value << (VarIntContentBytesCount * numBytes);

                numBytes++;
                if (numBytes <= VarInt32MaxBytes)
                {
                    continue;
                }

                buffer.ResetReaderIndex();
                return(false);
            } while ((read & VarIntIndexMask) != 0);

            return(true);
        }
Exemplo n.º 12
0
        protected override void Decode(IChannelHandlerContext ctx, IByteBuffer buffer, List <object> output)
        {
            if (!buffer.IsReadable())
            {
                return;
            }

            var id            = buffer.ReadByte();
            var handshakeType = (HandshakeType)id;

            _logger.Debug("Incoming Handshake Decoder Opcode: {0} Type: {1}", id, handshakeType);
            switch (handshakeType)
            {
            case HandshakeType.ServiceGame:
                ctx.Channel.Pipeline.AddLast(nameof(LoginEncoder), _loginEncoder);
                ctx.Channel.Pipeline.AddAfter(nameof(LoginEncoder), nameof(LoginDecoder), _loginDecoder);
                break;

            //case HandshakeType.SERVICE_UPDATE:
            //    ctx.Channel.Pipeline.AddFirst("updateEncoder", new UpdateEncoder());
            //    ctx.Channel.Pipeline.AddBefore("handler", "updateDecoder", new UpdateDecoder());

            //    var buf = ctx.Allocator.Buffer(8).WriteLong(0);
            //    ctx.Channel.WriteAndFlushAsync(buf);
            //    break;

            default:
                _logger.Information("Unexpected handshake request received: {0}", id);
                return;
            }

            ctx.Channel.Pipeline.Remove(this);
            output.Add(handshakeType);
        }
        /// <summary>
        /// Decodes a file update.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="input"></param>
        /// <param name="output"></param>
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            if (!input.IsReadable() || input.ReadableBytes < 4)
            {
                return;
            }

            UpdateType type = Update.GetUpdateType(input.ReadByte() & 0xff);

            if (type == UpdateType.NONE)
            {
                input.SkipBytes(3);
                return;
            }

            switch (type)
            {
            case UpdateType.LOW_PRIORITY_UPDATE:
            case UpdateType.HIGH_PRIORITY_UPDATE:
                int index   = input.ReadByte() & 0xff;
                int archive = input.ReadUnsignedShort();

                output.Add(new UpdateRequest(index, archive, type == UpdateType.HIGH_PRIORITY_UPDATE));
                break;

            case UpdateType.ENCRYPTION_UPDATE:
                input.SkipBytes(3);
                break;
            }
        }
Exemplo n.º 14
0
        public IMessage CreateMessage(string address, IByteBuffer payload)
        {
            var message = new IotHubClientMessage(new Message(payload.IsReadable() ? new ReadOnlyByteBufferStream(payload, false) : null), payload);

            message.Address = address;
            return(message);
        }
Exemplo n.º 15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            IByteBuffer buffer = message as IByteBuffer;

            try
            {
                if (buffer.IsReadable())
                {
                    var fun = buffer.ReadByte();
                    if (DataArrived != null)
                    {
                        var vdd = DataArrived(context, fun, buffer);
                        if (vdd != null && vdd.ReferenceCount > 0)
                        {
                            Write(context, vdd);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LoggerService.Service.Warn("Socket Service", ex.Message);
            }
            base.ChannelRead(context, message);
        }
Exemplo n.º 16
0
 protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
 {
     while (input.IsReadable())
     {
         output.Add(decoder.DecodeRequest(input));
     }
 }
Exemplo n.º 17
0
        protected override void Decode(IChannelHandlerContext ctx, IByteBuffer buffer, List <object> output)
        {
            if (!buffer.IsReadable())
            {
                return;
            }

            var id            = buffer.ReadByte();
            var handshakeType = (HandshakeType)id;

            _logger.Debug("Incoming Handshake Decoder Opcode: {0} Type: {1}", id, handshakeType);
            switch (handshakeType)
            {
            case HandshakeType.ServiceGame:
                ctx.Channel.Pipeline.AddLast(nameof(LoginEncoder), _loginEncoder);
                ctx.Channel.Pipeline.AddAfter(nameof(LoginEncoder), nameof(LoginDecoder), _loginDecoder);
                break;

            case HandshakeType.ServiceUpdate:
                int version = buffer.ReadInt();
                ctx.Channel.Pipeline.AddLast(nameof(JS5Decoder), _jS5Decoder);
                ctx.Channel.Pipeline.AddLast(nameof(JS5Encoder), _jS5Encoder);

                //Really should do version checking
                _ = ctx.Channel.WriteAndFlushAsync(ctx.Allocator.Buffer(1).WriteByte((int)FourSevenFourLoginStatus.StatusExchangeData));
                break;

            default:
                _logger.Information("Unexpected handshake request received: {0}", id);
                return;
            }

            ctx.Channel.Pipeline.Remove(this);
            output.Add(handshakeType);
        }
Exemplo n.º 18
0
        static void EncodePublishMessage(IByteBufferAllocator bufferAllocator, PublishPacket packet, List <object> output)
        {
            IByteBuffer payload = packet.Payload ?? Unpooled.Empty;

            string topicName = packet.TopicName;

            Util.ValidateTopicName(topicName);
            byte[] topicNameBytes = EncodeStringInUtf8(topicName);

            int variableHeaderBufferSize = StringSizeLength + topicNameBytes.Length +
                                           (packet.QualityOfService > QualityOfService.AtMostOnce ? PacketIdLength : 0);
            int payloadBufferSize     = payload.ReadableBytes;
            int variablePartSize      = variableHeaderBufferSize + payloadBufferSize;
            int fixedHeaderBufferSize = 1 + MaxVariableLength;

            IByteBuffer buf = bufferAllocator.Buffer(fixedHeaderBufferSize + variablePartSize);

            buf.WriteByte(CalculateFirstByteOfFixedHeader(packet));
            WriteVariableLengthInt(buf, variablePartSize);
            buf.WriteShort(topicNameBytes.Length);
            buf.WriteBytes(topicNameBytes);
            if (packet.QualityOfService > QualityOfService.AtMostOnce)
            {
                buf.WriteShort(packet.PacketId);
            }

            output.Add(buf);

            if (payload.IsReadable())
            {
                output.Add(payload.Retain());
            }
        }
Exemplo n.º 19
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            // pass bytes to SslStream through input -> trigger HandleSslStreamRead. After this call sslStreamReadBuffer may or may not have bytes to read
            this.mediationStream.AcceptBytes(input);

            if (!this.EnsureAuthenticated())
            {
                return;
            }

            IByteBuffer readBuffer = this.sslStreamReadBuffer;

            if (readBuffer == null)
            {
                this.sslStreamReadBuffer = readBuffer = context.Channel.Allocator.Buffer(ReadBufferSize);
                this.ScheduleSslStreamRead();
            }

            if (readBuffer.IsReadable())
            {
                // SslStream parsed at least one full frame and completed read request
                // Pass the buffer to a next handler in pipeline
                output.Add(readBuffer);
                this.sslStreamReadBuffer = null;
            }
        }
Exemplo n.º 20
0
        public void WrapSingleMedium()
        {
            IByteBuffer buffer = CopyMedium(42);

            Assert.Equal(3, buffer.Capacity);
            Assert.Equal(42, buffer.ReadMedium());
            Assert.False(buffer.IsReadable());
        }
Exemplo n.º 21
0
        public void WrapSingleInt()
        {
            IByteBuffer buffer = CopyInt(42);

            //Assert.Equal(4, buffer.Capacity);
            Assert.Equal(42, buffer.ReadInt());
            Assert.False(buffer.IsReadable());
        }
Exemplo n.º 22
0
 public static byte SafeReadByte(this IByteBuffer byteBuffer)
 {
     if (byteBuffer.IsReadable())
     {
         return(byteBuffer.ReadByte());
     }
     return(byte.MinValue);
 }
Exemplo n.º 23
0
        public void WrapSingleShort()
        {
            IByteBuffer buffer = CopyShort(42);

            Assert.Equal(2, buffer.Capacity);
            Assert.Equal(42, buffer.ReadShort());
            Assert.False(buffer.IsReadable());
        }
Exemplo n.º 24
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            if (!input.IsReadable())
            {
                return;
            }

            var bytes = new byte[input.ReadableBytes];

            input.ReadBytes(bytes);
            var type = bytes[0];

            switch (type)
            {
            case 43:
                output.Add(new Debug(bytes));
                break;

            case 65:
                output.Add(new LoginAccepted(bytes));
                break;

            case 74:
                output.Add(new LoginRejected(bytes));
                break;

            case 83:
                output.Add(new SequencedData(bytes, true));
                break;

            case 72:
                output.Add(new ServerHeartbeat(bytes));
                break;

            case 90:
                output.Add(new EndOfSession(bytes));
                break;

            case 76:
                output.Add(new LoginRequest(bytes));
                break;

            case 85:
                output.Add(new UnsequencedData(bytes, true));
                break;

            case 82:
                output.Add(new ClientHeartbeat(bytes));
                break;

            case 79:
                output.Add(new LogoutRequest(bytes));
                break;

            default:
                break;
            }
        }
Exemplo n.º 25
0
 /// <summary>
 /// Is called one last time when the <see cref="IChannelHandlerContext"/> goes in-active. Which means the
 /// <see cref="ChannelInactive(IChannelHandlerContext)"/> was triggered.
 ///
 /// By default this will just call <see cref="Decode(IChannelHandlerContext, IByteBuffer, List{object})"/> but sub-classes may
 /// override this for some special cleanup operation.
 /// </summary>
 /// <param name="context"></param>
 /// <param name="input"></param>
 /// <param name="output"></param>
 protected virtual void DecodeLast(IChannelHandlerContext context, IByteBuffer input, List <object> output)
 {
     if (input.IsReadable())
     {
         // Only call decode() if there is something left in the buffer to decode.
         // See https://github.com/netty/netty/issues/4386
         Decode(context, input, output);
     }
 }
Exemplo n.º 26
0
        protected virtual void CallDecode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            Contract.Requires(context != null);
            Contract.Requires(input != null);
            Contract.Requires(output != null);

            try
            {
                while (input.IsReadable())
                {
                    int initialOutputCount = output.Count;
                    int oldInputLength     = input.ReadableBytes;
                    this.Decode(context, input, output);

                    // Check if this handler was removed before continuing the loop.
                    // If it was removed, it is not safe to continue to operate on the buffer.
                    //
                    // See https://github.com/netty/netty/issues/1664
                    if (context.Removed)
                    {
                        break;
                    }

                    if (initialOutputCount == output.Count)
                    {
                        // no outgoing messages have been produced

                        if (oldInputLength == input.ReadableBytes)
                        {
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    if (oldInputLength == input.ReadableBytes)
                    {
                        throw new DecoderException($"{this.GetType().Name}.Decode() did not read anything but decoded a message.");
                    }

                    if (this.SingleDecode)
                    {
                        break;
                    }
                }
            }
            catch (DecoderException)
            {
                throw;
            }
            catch (Exception cause)
            {
                throw new DecoderException(cause);
            }
        }
Exemplo n.º 27
0
        public void WrapSingleDouble()
        {
            IEqualityComparer <double> comparer = new ApproximateComparer(0.01);
            IByteBuffer buffer = CopyDouble(42);

            Assert.Equal(8, buffer.Capacity);
            Assert.Equal(42, buffer.ReadDouble(), comparer);
            Assert.False(buffer.IsReadable());
        }
Exemplo n.º 28
0
        public void WrapSingleFloat()
        {
            IEqualityComparer <float> comparer = new ApproximateComparer(0.01);
            IByteBuffer buffer = CopyFloat(42);

            Assert.Equal(4, buffer.Capacity);
            Assert.Equal(42, buffer.ReadFloat(), comparer);
            Assert.False(buffer.IsReadable());
        }
Exemplo n.º 29
0
        public void WrapSingleLong()
        {
            IByteBuffer buffer = CopyLong(42);

            Assert.Equal(8, buffer.Capacity);
            Assert.Equal(42, buffer.ReadLong());
            Assert.False(buffer.IsReadable());
            buffer.Release();
        }
Exemplo n.º 30
0
        protected override void DecodeLast(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            base.DecodeLast(context, input, output);

            if (SharedConstants.False < (uint)Volatile.Read(ref _resetRequested))
            {
                // If a reset was requested by decodeLast() we need to do it now otherwise we may produce a
                // LastHttpContent while there was already one.
                ResetNow();
            }

            // Handle the last unfinished message.
            if (_message is object)
            {
                bool chunked = HttpUtil.IsTransferEncodingChunked(_message);
                if (_currentState == State.ReadVariableLengthContent &&
                    !input.IsReadable() && !chunked)
                {
                    // End of connection.
                    output.Add(EmptyLastHttpContent.Default);
                    ResetNow();
                    return;
                }

                if (_currentState == State.ReadHeader)
                {
                    // If we are still in the state of reading headers we need to create a new invalid message that
                    // signals that the connection was closed before we received the headers.
                    output.Add(InvalidMessage(Unpooled.Empty,
                                              new PrematureChannelClosureException("Connection closed before received headers")));
                    ResetNow();
                    return;
                }

                // Check if the closure of the connection signifies the end of the content.
                bool prematureClosure;
                if (IsDecodingRequest() || chunked)
                {
                    // The last request did not wait for a response.
                    prematureClosure = true;
                }
                else
                {
                    // Compare the length of the received content and the 'Content-Length' header.
                    // If the 'Content-Length' header is absent, the length of the content is determined by the end of the
                    // connection, so it is perfectly fine.
                    prematureClosure = ContentLength() > 0;
                }

                if (!prematureClosure)
                {
                    output.Add(EmptyLastHttpContent.Default);
                }
                ResetNow();
            }
        }
 void HandleReadException(IChannelPipeline pipeline, IByteBuffer byteBuf, Exception cause, bool close)
 {
     if (byteBuf != null)
     {
         if (byteBuf.IsReadable())
         {
             this.Channel.ReadPending = false;
             pipeline.FireChannelRead(byteBuf);
         }
         else
         {
             byteBuf.Release();
         }
     }
     pipeline.FireChannelReadComplete();
     pipeline.FireExceptionCaught(cause);
     if (close || cause is SocketException)
     {
         this.CloseOnRead();
     }
 }
Exemplo n.º 32
0
        protected virtual void CallDecode(IChannelHandlerContext context, IByteBuffer input, List<object> output)
        {
            try
            {
                while (input.IsReadable())
                {
                    int initialOutputCount = output.Count;
                    int oldInputLength = input.ReadableBytes;
                    this.Decode(context, input, output);

                    // Check if this handler was removed before continuing the loop.
                    // If it was removed, it is not safe to continue to operate on the buffer.
                    //
                    // See https://github.com/netty/netty/issues/1664
                    if (context.Removed)
                    {
                        break;
                    }

                    if (initialOutputCount == output.Count)
                    {
                        // no outgoing messages have been produced

                        if (oldInputLength == input.ReadableBytes)
                        {
                            break;
                        }
                        else
                        {
                            continue;
                        }
                    }

                    if (oldInputLength == input.ReadableBytes)
                    {
                        throw new DecoderException(string.Format("{0}.Decode() did not read anything but decoded a message.", this.GetType().Name));
                    }

                    if (this.SingleDecode)
                    {
                        break;
                    }
                }
            }
            catch (DecoderException)
            {
                throw;
            }
            catch (Exception cause)
            {
                throw new DecoderException(cause);
            }
        }
Exemplo n.º 33
0
 public bool Equals(IByteBuffer buffer) => buffer != null && !buffer.IsReadable();
Exemplo n.º 34
0
        /// <summary>
        /// Skips the null bytes.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns><c>true</c> if successful, <c>false</c> otherwise.</returns>
        private static bool SkipNullBytes(IByteBuffer input)
        {
            while (input.IsReadable())
            {
                if (input.GetByte(input.ReaderIndex) != 0xFF) return true;
                input.SkipBytes(1);
            }

            return false;
        }
Exemplo n.º 35
0
        /// <summary>
        /// Decodes the byte buffer and builds QuickBlockTransfer packets.
        /// </summary>
        /// <param name="context">The handler context.</param>
        /// <param name="input">The input byte buffer from the socket.</param>
        /// <param name="output">The output packets.</param>
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output)
        {
            switch (State)
            {
                case DecoderState.ReSync:
                    if (!input.IsReadable(QuickBlockV1BodySize + FrameSyncBytes)) break;
                    PerformanceCounters.FrameSyncTotal.Increment();
                    if (!SynchronizeFrame(input)) break;
                    State = DecoderState.StartFrame;
                    goto case DecoderState.StartFrame;

                case DecoderState.StartFrame:
                    if (!SkipNullBytes(input)) break;
                    State = DecoderState.FrameType;
                    goto case DecoderState.FrameType;

                case DecoderState.FrameType:
                    if (!input.IsReadable(QuickBlockHeaderSize)) break;
                    if (IsDataBlockHeader(input))
                    {
                        State = DecoderState.BlockHeader;
                        goto case DecoderState.BlockHeader;
                    }
                    if (IsServerList(input))
                    {
                        PerformanceCounters.ServerListReceivedTotal.Increment();
                        State = DecoderState.ServerList;
                        goto case DecoderState.ServerList;
                    }
                    throw new InvalidOperationException("Unknown frame type");

                case DecoderState.ServerList:
                    var content = ReadString(input);
                    if (content.Length == 0) break;
                    context.FireUserEventTriggered(ParseServerList(content));
                    State = DecoderState.StartFrame;
                    goto case DecoderState.StartFrame;

                case DecoderState.BlockHeader:
                    Packet = ParsePacketHeader(input);
                    PerformanceCounters.BlocksReceivedTotal.Increment();
                    if (Packet.Version == 2)
                        PerformanceCounters.CompressedBlocksReceivedTotal.Increment();
                    State = DecoderState.BlockBody;
                    goto case DecoderState.BlockBody;

                case DecoderState.BlockBody:
                    if (!input.IsReadable(Packet.Length)) break;
                    Packet.Content = ReadPacketBody(input, Packet.Length, Packet.Version);
                    PerformanceCounters.BlocksProcessedPerSecond.Increment();
                    State = DecoderState.Validate;
                    goto case DecoderState.Validate;

                case DecoderState.Validate:
                    if (Packet.TotalBlocks <= 0 || Packet.BlockNumber <= 0)
                    {
                        PerformanceCounters.ChecksumErrorsTotal.Increment();
                        throw new InvalidDataException("Header block values out of range. " + Packet);
                    }

                    if (VerifyChecksum(Packet.Content, Packet.Checksum))
                    {
                        ByteBlasterEventSource.Log.PacketCreated(Packet.ToString());
                        context.FireUserEventTriggered(Packet);
                    }
                    else
                    {
                        PerformanceCounters.ChecksumErrorsTotal.Increment();
                        throw new InvalidDataException("Block Checksum failed. " + Packet);
                    }

                    State = DecoderState.StartFrame;
                    goto case DecoderState.StartFrame;

                default:
                    throw new InvalidOperationException("Unknown Decoder State: " + State);
            }
        }
Exemplo n.º 36
0
        /// <summary>
        /// Synchronizes the frame.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns><c>true</c> if successful, <c>false</c> otherwise.</returns>
        private static bool SynchronizeFrame(IByteBuffer input)
        {
            var count = 0;
            while (input.IsReadable())
            {
                count = (input.ReadByte() == 0xFF) ? count + 1 : 0;
                if (count >= FrameSyncBytes) return true;
            }

            ByteBlasterEventSource.Log.SynchronizationWarning(count);
            return false;
        }
        static void ValidateDelimiter(IByteBuffer delimiter)
        {
            if (delimiter == null)
                throw new NullReferenceException("delimiter");

            if (!delimiter.IsReadable())
                throw new ArgumentException("empty delimiter");
        }
 public IMessage CreateMessage(string address, IByteBuffer payload)
 {
     var message = new IotHubClientMessage(new Message(payload.IsReadable() ? new ReadOnlyByteBufferStream(payload, false) : null), payload);
     message.Address = address;
     return message;
 }
 public IMessage CreateMessage(string address, IByteBuffer payload) => new IotHubClientMessage(address, new Message(payload.IsReadable() ? new ReadOnlyByteBufferStream(payload, true) : null));
Exemplo n.º 40
0
 public int CompareTo(IByteBuffer buffer) => buffer.IsReadable() ? -1 : 0;