コード例 #1
0
        protected override EmbeddedChannel NewContentDecoder(ICharSequence contentEncoding)
        {
            if (HttpHeaderValues.Gzip.ContentEqualsIgnoreCase(contentEncoding) ||
                HttpHeaderValues.XGzip.ContentEqualsIgnoreCase(contentEncoding))
            {
                return(new EmbeddedChannel(
                           this.HandlerContext.Channel.Id,
                           this.HandlerContext.Channel.Metadata.HasDisconnect,
                           this.HandlerContext.Channel.Configuration,
                           ZlibCodecFactory.NewZlibDecoder(ZlibWrapper.Gzip)));
            }

            if (HttpHeaderValues.Deflate.ContentEqualsIgnoreCase(contentEncoding) ||
                HttpHeaderValues.XDeflate.ContentEqualsIgnoreCase(contentEncoding))
            {
                ZlibWrapper wrapper = this.strict ? ZlibWrapper.Zlib : ZlibWrapper.ZlibOrNone;
                return(new EmbeddedChannel(
                           this.HandlerContext.Channel.Id,
                           this.HandlerContext.Channel.Metadata.HasDisconnect,
                           this.HandlerContext.Channel.Configuration,
                           ZlibCodecFactory.NewZlibDecoder(wrapper)));
            }

            // 'identity' or unsupported
            return(null);
        }
コード例 #2
0
        public void CompressedFrame()
        {
            var encoderChannel = new EmbeddedChannel(new PerFrameDeflateEncoder(9, 15, false));
            var decoderChannel = new EmbeddedChannel(
                ZlibCodecFactory.NewZlibDecoder(ZlibWrapper.None));

            var payload = new byte[300];

            this.random.NextBytes(payload);
            var frame = new BinaryWebSocketFrame(true,
                                                 WebSocketRsv.Rsv3, Unpooled.WrappedBuffer(payload));

            encoderChannel.WriteOutbound(frame);
            var compressedFrame = encoderChannel.ReadOutbound <BinaryWebSocketFrame>();

            Assert.NotNull(compressedFrame);
            Assert.NotNull(compressedFrame.Content);
            Assert.IsType <BinaryWebSocketFrame>(compressedFrame);
            Assert.Equal(WebSocketRsv.Rsv1 | WebSocketRsv.Rsv3, compressedFrame.Rsv);

            decoderChannel.WriteInbound(compressedFrame.Content);
            decoderChannel.WriteInbound(DeflateDecoder.FrameTail);
            var uncompressedPayload = decoderChannel.ReadInbound <IByteBuffer>();

            Assert.Equal(300, uncompressedPayload.ReadableBytes);

            var finalPayload = new byte[300];

            uncompressedPayload.ReadBytes(finalPayload);

            Assert.Equal(payload, finalPayload);
            uncompressedPayload.Release();
        }
コード例 #3
0
        static byte[] GzDecompress(byte[] input)
        {
            ZlibDecoder decoder = ZlibCodecFactory.NewZlibDecoder(ZlibWrapper.Gzip);
            var         channel = new EmbeddedChannel(decoder);

            Assert.True(channel.WriteInbound(Unpooled.CopiedBuffer(input)));
            Assert.True(channel.Finish()); // close the channel to indicate end-of-data

            int         outputSize = 0;
            IByteBuffer o;
            var         inbound = new List <IByteBuffer>();

            while ((o = channel.ReadInbound <IByteBuffer>()) != null)
            {
                inbound.Add(o);
                outputSize += o.ReadableBytes;
            }

            var output    = new byte[outputSize];
            int readCount = 0;

            foreach (IByteBuffer b in inbound)
            {
                int readableBytes = b.ReadableBytes;
                b.ReadBytes(output, readCount, readableBytes);
                b.Release();
                readCount += readableBytes;
            }
            Assert.True(channel.InboundMessages.Count == 0 && channel.OutboundMessages.Count == 0);

            return(output);
        }
コード例 #4
0
        public void DecompressionSkip()
        {
            EmbeddedChannel encoderChannel = new EmbeddedChannel(
                ZlibCodecFactory.NewZlibEncoder(ZlibWrapper.None, 9, 15, 8));
            EmbeddedChannel decoderChannel = new EmbeddedChannel(new PerFrameDeflateDecoder(false, AlwaysSkipWebSocketExtensionFilter.Instance));

            byte[] payload = new byte[300];
            _random.NextBytes(payload);

            Assert.True(encoderChannel.WriteOutbound(Unpooled.WrappedBuffer(payload)));
            var compressedPayload = encoderChannel.ReadOutbound <IByteBuffer>();

            BinaryWebSocketFrame compressedBinaryFrame = new BinaryWebSocketFrame(
                true, WebSocketRsv.Rsv1 | WebSocketRsv.Rsv3, compressedPayload);

            Assert.True(decoderChannel.WriteInbound(compressedBinaryFrame));

            var inboundBinaryFrame = decoderChannel.ReadInbound <BinaryWebSocketFrame>();

            Assert.NotNull(inboundBinaryFrame);
            Assert.NotNull(inboundBinaryFrame.Content);
            Assert.Equal(compressedPayload, inboundBinaryFrame.Content);
            Assert.Equal(5, inboundBinaryFrame.Rsv);

            Assert.True(inboundBinaryFrame.Release());

            Assert.True(encoderChannel.FinishAndReleaseAll());
            Assert.False(decoderChannel.Finish());
        }
コード例 #5
0
        public void CompressedFrame()
        {
            var encoderChannel = new EmbeddedChannel(
                ZlibCodecFactory.NewZlibEncoder(ZlibWrapper.None, 9, 15, 8));
            var decoderChannel = new EmbeddedChannel(new PerFrameDeflateDecoder(false));

            // initialize
            var payload = new byte[300];

            _random.NextBytes(payload);

            Assert.True(encoderChannel.WriteOutbound(Unpooled.WrappedBuffer(payload)));
            var compressedPayload = encoderChannel.ReadOutbound <IByteBuffer>();

            var compressedFrame = new BinaryWebSocketFrame(true,
                                                           WebSocketRsv.Rsv1 | WebSocketRsv.Rsv3,
                                                           compressedPayload.Slice(0, compressedPayload.ReadableBytes - 4));

            // execute
            Assert.True(decoderChannel.WriteInbound(compressedFrame));
            var uncompressedFrame = decoderChannel.ReadInbound <BinaryWebSocketFrame>();

            // test
            Assert.NotNull(uncompressedFrame);
            Assert.NotNull(uncompressedFrame.Content);
            Assert.Equal(WebSocketRsv.Rsv3, uncompressedFrame.Rsv);
            Assert.Equal(300, uncompressedFrame.Content.ReadableBytes);

            var finalPayload = new byte[300];

            uncompressedFrame.Content.ReadBytes(finalPayload);
            Assert.Equal(payload, finalPayload);
            uncompressedFrame.Release();
        }
コード例 #6
0
        /// <summary>
        /// Generate a new instance of an <see cref="EmbeddedChannel"/> capable of compressing data
        /// </summary>
        /// <param name="ctx">the context.</param>
        /// <param name="wrapper">Defines what type of encoder should be used</param>
        /// <returns></returns>
        private EmbeddedChannel NewCompressionChannel(IChannelHandlerContext ctx, ZlibWrapper wrapper)
        {
            var channel = ctx.Channel;

            return(new EmbeddedChannel(channel.Id, channel.Metadata.HasDisconnect,
                                       channel.Configuration, ZlibCodecFactory.NewZlibEncoder(wrapper, _compressionLevel, _windowBits,
                                                                                              _memLevel)));
        }
コード例 #7
0
ファイル: DeflateEncoder.cs プロジェクト: wxlonstar/Fenix
        private IByteBuffer CompressContent(IChannelHandlerContext ctx, WebSocketFrame msg)
        {
            if (_encoder is null)
            {
                _encoder = new EmbeddedChannel(
                    ZlibCodecFactory.NewZlibEncoder(
                        ZlibWrapper.None,
                        _compressionLevel,
                        _windowSize,
                        8));
            }

            _ = _encoder.WriteOutbound(msg.Content.Retain());

            CompositeByteBuffer fullCompressedContent = ctx.Allocator.CompositeBuffer();

            while (true)
            {
                var partCompressedContent = _encoder.ReadOutbound <IByteBuffer>();
                if (partCompressedContent is null)
                {
                    break;
                }

                if (!partCompressedContent.IsReadable())
                {
                    _ = partCompressedContent.Release();
                    continue;
                }

                _ = fullCompressedContent.AddComponent(true, partCompressedContent);
            }

            if (fullCompressedContent.NumComponents <= 0)
            {
                _ = fullCompressedContent.Release();
                ThrowHelper.ThrowCodecException_CannotReadCompressedBuf();
            }

            if (msg.IsFinalFragment && _noContext)
            {
                Cleanup();
            }

            IByteBuffer compressedContent;

            if (RemoveFrameTail(msg))
            {
                int realLength = fullCompressedContent.ReadableBytes - FrameTail.ReadableBytes;
                compressedContent = fullCompressedContent.Slice(0, realLength);
            }
            else
            {
                compressedContent = fullCompressedContent;
            }
            return(compressedContent);
        }
コード例 #8
0
        public void FragmentedFrame()
        {
            var encoderChannel = new EmbeddedChannel(
                ZlibCodecFactory.NewZlibEncoder(ZlibWrapper.None, 9, 15, 8));
            var decoderChannel = new EmbeddedChannel(new PerMessageDeflateDecoder(false));

            // initialize
            var payload = new byte[300];

            _random.NextBytes(payload);

            Assert.True(encoderChannel.WriteOutbound(Unpooled.WrappedBuffer(payload)));
            var compressedPayload = encoderChannel.ReadOutbound <IByteBuffer>();

            compressedPayload = compressedPayload.Slice(0, compressedPayload.ReadableBytes - 4);

            int oneThird         = compressedPayload.ReadableBytes / 3;
            var compressedFrame1 = new BinaryWebSocketFrame(false,
                                                            WebSocketRsv.Rsv1 | WebSocketRsv.Rsv3,
                                                            compressedPayload.Slice(0, oneThird));
            var compressedFrame2 = new ContinuationWebSocketFrame(false,
                                                                  WebSocketRsv.Rsv3, compressedPayload.Slice(oneThird, oneThird));
            var compressedFrame3 = new ContinuationWebSocketFrame(true,
                                                                  WebSocketRsv.Rsv3, compressedPayload.Slice(oneThird * 2,
                                                                                                             compressedPayload.ReadableBytes - oneThird * 2));

            // execute
            Assert.True(decoderChannel.WriteInbound(compressedFrame1.Retain()));
            Assert.True(decoderChannel.WriteInbound(compressedFrame2.Retain()));
            Assert.True(decoderChannel.WriteInbound(compressedFrame3));
            var uncompressedFrame1 = decoderChannel.ReadInbound <BinaryWebSocketFrame>();
            var uncompressedFrame2 = decoderChannel.ReadInbound <ContinuationWebSocketFrame>();
            var uncompressedFrame3 = decoderChannel.ReadInbound <ContinuationWebSocketFrame>();

            // test
            Assert.NotNull(uncompressedFrame1);
            Assert.NotNull(uncompressedFrame2);
            Assert.NotNull(uncompressedFrame3);
            Assert.Equal(WebSocketRsv.Rsv3, uncompressedFrame1.Rsv);
            Assert.Equal(WebSocketRsv.Rsv3, uncompressedFrame2.Rsv);
            Assert.Equal(WebSocketRsv.Rsv3, uncompressedFrame3.Rsv);

            IByteBuffer finalPayloadWrapped = Unpooled.WrappedBuffer(uncompressedFrame1.Content,
                                                                     uncompressedFrame2.Content, uncompressedFrame3.Content);

            Assert.Equal(300, finalPayloadWrapped.ReadableBytes);

            var finalPayload = new byte[300];

            finalPayloadWrapped.ReadBytes(finalPayload);
            Assert.Equal(payload, finalPayload);
            finalPayloadWrapped.Release();
        }
コード例 #9
0
        public void IllegalStateWhenDecompressionInProgress()
        {
            var             selectivityDecompressionFilter = new SelectivityDecompressionFilter1();
            EmbeddedChannel encoderChannel = new EmbeddedChannel(
                ZlibCodecFactory.NewZlibEncoder(ZlibWrapper.None, 9, 15, 8));
            EmbeddedChannel decoderChannel = new EmbeddedChannel(
                new PerMessageDeflateDecoder(false, selectivityDecompressionFilter));

            byte[] firstPayload = new byte[200];
            _random.NextBytes(firstPayload);

            byte[] finalPayload = new byte[50];
            _random.NextBytes(finalPayload);

            Assert.True(encoderChannel.WriteOutbound(Unpooled.WrappedBuffer(firstPayload)));
            Assert.True(encoderChannel.WriteOutbound(Unpooled.WrappedBuffer(finalPayload)));
            var compressedFirstPayload = encoderChannel.ReadOutbound <IByteBuffer>();
            var compressedFinalPayload = encoderChannel.ReadOutbound <IByteBuffer>();

            Assert.True(encoderChannel.FinishAndReleaseAll());

            BinaryWebSocketFrame       firstPart = new BinaryWebSocketFrame(false, WebSocketRsv.Rsv1, compressedFirstPayload);
            ContinuationWebSocketFrame finalPart = new ContinuationWebSocketFrame(true, WebSocketRsv.Rsv1, compressedFinalPayload);

            Assert.True(decoderChannel.WriteInbound(firstPart));

            var outboundFirstPart = decoderChannel.ReadInbound <BinaryWebSocketFrame>();

            //first part is decompressed
            Assert.Equal(0, outboundFirstPart.Rsv);
            Assert.Equal(firstPayload, ByteBufferUtil.GetBytes(outboundFirstPart.Content));
            Assert.True(outboundFirstPart.Release());

            //final part throwing exception
            try
            {
                decoderChannel.WriteInbound(finalPart);
                Assert.False(true);
            }
            catch (Exception exc)
            {
                Assert.IsType <DecoderException>(exc);
            }
            finally
            {
                Assert.True(finalPart.Release());
                Assert.False(encoderChannel.FinishAndReleaseAll());
            }
        }
コード例 #10
0
        protected override Result BeginEncode(IHttpResponse httpResponse, ICharSequence acceptEncoding)
        {
            if (this.contentSizeThreshold > 0)
            {
                if (httpResponse is IHttpContent httpContent &&
                    httpContent.Content.ReadableBytes < this.contentSizeThreshold)
                {
                    return(null);
                }
            }

            if (httpResponse.Headers.Contains(HttpHeaderNames.ContentEncoding))
            {
                // Content-Encoding was set, either as something specific or as the IDENTITY encoding
                // Therefore, we should NOT encode here
                return(null);
            }

            ZlibWrapper?wrapper = this.DetermineWrapper(acceptEncoding);

            if (wrapper is null)
            {
                return(null);
            }

            ICharSequence targetContentEncoding = null;

            switch (wrapper.Value)
            {
            case ZlibWrapper.Gzip:
                targetContentEncoding = GZipString;
                break;

            case ZlibWrapper.Zlib:
                targetContentEncoding = DeflateString;
                break;

            default:
                ThrowHelper.ThrowCodecException_InvalidCompression(wrapper.Value); break;
            }

            return(new Result(targetContentEncoding,
                              new EmbeddedChannel(
                                  this.handlerContext.Channel.Id,
                                  this.handlerContext.Channel.Metadata.HasDisconnect,
                                  this.handlerContext.Channel.Configuration,
                                  ZlibCodecFactory.NewZlibEncoder(
                                      wrapper.Value, this.compressionLevel, this.windowBits, this.memLevel))));
        }
コード例 #11
0
        protected override void InitChannel(ISocketChannel channel)
        {
            IChannelPipeline pipeline = channel.Pipeline;

            // Enable stream compression.
            pipeline.AddLast(ZlibCodecFactory.NewZlibEncoder(ZlibWrapper.Gzip));
            pipeline.AddLast(ZlibCodecFactory.NewZlibDecoder(ZlibWrapper.Gzip));

            // Add the number codec first.
            pipeline.AddLast(new BigIntegerDecoder());
            pipeline.AddLast(new BigIntegerEncoder());

            // Add the business logic.
            pipeline.AddLast(new FactorialClientHandler());
        }
コード例 #12
0
        protected override void InitChannel(ISocketChannel channel)
        {
            IChannelPipeline pipeline = channel.Pipeline;

            // Enable stream compresion.
            pipeline.AddLast(ZlibCodecFactory.NewZlibEncoder(ZlibWrapper.Gzip));
            pipeline.AddLast(ZlibCodecFactory.NewZlibDecoder(ZlibWrapper.Gzip));

            // Add the number codec first.
            pipeline.AddLast(new BigIntegerDecoder());
            pipeline.AddLast(new BigIntegerEncoder());

            // Add the business logic.
            // Please note, we create a handler for every new channel, because it has stateful properties.
            pipeline.AddLast(new FactorialServerHandler());
        }
コード例 #13
0
        public void MultiCompressedPayloadWithinFrame()
        {
            var encoderChannel = new EmbeddedChannel(
                ZlibCodecFactory.NewZlibEncoder(ZlibWrapper.None, 9, 15, 8));
            var decoderChannel = new EmbeddedChannel(new PerMessageDeflateDecoder(false));

            var payload1 = new byte[100];

            this.random.NextBytes(payload1);
            var payload2 = new byte[100];

            this.random.NextBytes(payload2);

            encoderChannel.WriteOutbound(Unpooled.WrappedBuffer(payload1));
            var compressedPayload1 = encoderChannel.ReadOutbound <IByteBuffer>();

            encoderChannel.WriteOutbound(Unpooled.WrappedBuffer(payload2));
            var compressedPayload2 = encoderChannel.ReadOutbound <IByteBuffer>();

            var compressedFrame = new BinaryWebSocketFrame(true,
                                                           WebSocketRsv.Rsv1 | WebSocketRsv.Rsv3,
                                                           Unpooled.WrappedBuffer(
                                                               compressedPayload1,
                                                               compressedPayload2.Slice(0, compressedPayload2.ReadableBytes - 4)));

            decoderChannel.WriteInbound(compressedFrame);
            var uncompressedFrame = decoderChannel.ReadInbound <BinaryWebSocketFrame>();

            Assert.NotNull(uncompressedFrame);
            Assert.NotNull(uncompressedFrame.Content);
            Assert.IsType <BinaryWebSocketFrame>(uncompressedFrame);
            Assert.Equal(WebSocketRsv.Rsv3, uncompressedFrame.Rsv);
            Assert.Equal(200, uncompressedFrame.Content.ReadableBytes);

            var finalPayload1 = new byte[100];

            uncompressedFrame.Content.ReadBytes(finalPayload1);
            Assert.Equal(payload1, finalPayload1);
            var finalPayload2 = new byte[100];

            uncompressedFrame.Content.ReadBytes(finalPayload2);
            Assert.Equal(payload2, finalPayload2);
            uncompressedFrame.Release();
        }
コード例 #14
0
        public void SelectivityCompressionSkip()
        {
            var             selectivityCompressionFilter = new SelectivityDecompressionFilter0();
            EmbeddedChannel encoderChannel = new EmbeddedChannel(
                new PerMessageDeflateEncoder(9, 15, false, selectivityCompressionFilter));
            EmbeddedChannel decoderChannel = new EmbeddedChannel(
                ZlibCodecFactory.NewZlibDecoder(ZlibWrapper.None));

            string textPayload = "not compressed payload";

            byte[] binaryPayload = new byte[101];
            _random.NextBytes(binaryPayload);

            WebSocketFrame       textFrame   = new TextWebSocketFrame(textPayload);
            BinaryWebSocketFrame binaryFrame = new BinaryWebSocketFrame(Unpooled.WrappedBuffer(binaryPayload));

            Assert.True(encoderChannel.WriteOutbound(textFrame));
            Assert.True(encoderChannel.WriteOutbound(binaryFrame));

            var outboundTextFrame = encoderChannel.ReadOutbound <WebSocketFrame>();

            //compression skipped for textFrame
            Assert.Equal(0, outboundTextFrame.Rsv);
            Assert.Equal(textPayload, outboundTextFrame.Content.ToString(Encoding.UTF8));
            Assert.True(outboundTextFrame.Release());

            var outboundBinaryFrame = encoderChannel.ReadOutbound <WebSocketFrame>();

            //compression not skipped for binaryFrame
            Assert.Equal(WebSocketRsv.Rsv1, outboundBinaryFrame.Rsv);

            Assert.True(decoderChannel.WriteInbound(outboundBinaryFrame.Content.Retain()));
            var uncompressedBinaryPayload = decoderChannel.ReadInbound <IByteBuffer>();

            Assert.Equal(binaryPayload, ByteBufferUtil.GetBytes(uncompressedBinaryPayload));

            Assert.True(outboundBinaryFrame.Release());
            Assert.True(uncompressedBinaryPayload.Release());

            Assert.False(encoderChannel.Finish());
            Assert.False(decoderChannel.Finish());
        }
コード例 #15
0
        public void CompressedEmptyFrame()
        {
            var encoderChannel = new EmbeddedChannel(
                ZlibCodecFactory.NewZlibEncoder(ZlibWrapper.None, 9, 15, 8));
            var decoderChannel = new EmbeddedChannel(new PerFrameDeflateDecoder(false));

            encoderChannel.WriteOutbound(Unpooled.Empty);
            var compressedPayload = encoderChannel.ReadOutbound <IByteBuffer>();
            var compressedFrame   =
                new BinaryWebSocketFrame(true, WebSocketRsv.Rsv1 | WebSocketRsv.Rsv3, compressedPayload);

            decoderChannel.WriteInbound(compressedFrame);
            var uncompressedFrame = decoderChannel.ReadInbound <BinaryWebSocketFrame>();

            Assert.NotNull(uncompressedFrame);
            Assert.NotNull(uncompressedFrame.Content);
            Assert.IsType <BinaryWebSocketFrame>(uncompressedFrame);
            Assert.Equal(WebSocketRsv.Rsv3, uncompressedFrame.Rsv);
            Assert.Equal(0, uncompressedFrame.Content.ReadableBytes);
            uncompressedFrame.Release();
        }
コード例 #16
0
        /// <summary>
        /// Returns a new <see cref="EmbeddedChannel"/> that decodes the HTTP2 message content encoded in the specified
        /// <paramref name="contentEncoding"/>.
        /// </summary>
        /// <param name="ctx">The context</param>
        /// <param name="contentEncoding">the value of the <c>content-encoding</c> header</param>
        /// <returns>a new <see cref="ByteToMessageDecoder"/> if the specified encoding is supported. <c>null</c> otherwise
        /// (alternatively, you can throw a <see cref="Http2Exception"/> to block unknown encoding).</returns>
        /// <exception cref="Http2Exception">If the specified encoding is not not supported and warrants an exception.</exception>
        protected EmbeddedChannel NewContentDecompressor(IChannelHandlerContext ctx, ICharSequence contentEncoding)
        {
            var channel = ctx.Channel;

            if (HttpHeaderValues.Gzip.ContentEqualsIgnoreCase(contentEncoding) ||
                HttpHeaderValues.XGzip.ContentEqualsIgnoreCase(contentEncoding))
            {
                return(new EmbeddedChannel(channel.Id, channel.Metadata.HasDisconnect,
                                           channel.Configuration, ZlibCodecFactory.NewZlibDecoder(ZlibWrapper.Gzip)));
            }
            if (HttpHeaderValues.Deflate.ContentEqualsIgnoreCase(contentEncoding) ||
                HttpHeaderValues.XDeflate.ContentEqualsIgnoreCase(contentEncoding))
            {
                ZlibWrapper wrapper = _strict ? ZlibWrapper.Zlib : ZlibWrapper.ZlibOrNone;
                // To be strict, 'deflate' means ZLIB, but some servers were not implemented correctly.
                return(new EmbeddedChannel(channel.Id, channel.Metadata.HasDisconnect,
                                           channel.Configuration, ZlibCodecFactory.NewZlibDecoder(wrapper)));
            }
            // 'identity' or unsupported
            return(null);
        }
コード例 #17
0
        protected override Result BeginEncode(IHttpResponse headers, ICharSequence acceptEncoding)
        {
            if (headers.Headers.Contains(HttpHeaderNames.ContentEncoding))
            {
                // Content-Encoding was set, either as something specific or as the IDENTITY encoding
                // Therefore, we should NOT encode here
                return(null);
            }

            ZlibWrapper?wrapper = this.DetermineWrapper(acceptEncoding);

            if (wrapper == null)
            {
                return(null);
            }

            ICharSequence targetContentEncoding;

            switch (wrapper.Value)
            {
            case ZlibWrapper.Gzip:
                targetContentEncoding = GZipString;
                break;

            case ZlibWrapper.Zlib:
                targetContentEncoding = DeflateString;
                break;

            default:
                throw new CodecException($"{wrapper.Value} not supported, only Gzip and Zlib are allowed.");
            }

            return(new Result(targetContentEncoding,
                              new EmbeddedChannel(
                                  this.handlerContext.Channel.Id,
                                  this.handlerContext.Channel.Metadata.HasDisconnect,
                                  this.handlerContext.Channel.Configuration,
                                  ZlibCodecFactory.NewZlibEncoder(
                                      wrapper.Value, this.compressionLevel, this.windowBits, this.memLevel))));
        }
コード例 #18
0
        public void SelectivityDecompressionSkip()
        {
            var             selectivityDecompressionFilter = new SelectivityDecompressionFilter0();
            EmbeddedChannel encoderChannel = new EmbeddedChannel(
                ZlibCodecFactory.NewZlibEncoder(ZlibWrapper.None, 9, 15, 8));
            EmbeddedChannel decoderChannel = new EmbeddedChannel(
                new PerMessageDeflateDecoder(false, selectivityDecompressionFilter));

            string textPayload = "compressed payload";

            byte[] binaryPayload = new byte[300];
            _random.NextBytes(binaryPayload);

            Assert.True(encoderChannel.WriteOutbound(Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes(textPayload))));
            Assert.True(encoderChannel.WriteOutbound(Unpooled.WrappedBuffer(binaryPayload)));
            var compressedTextPayload   = encoderChannel.ReadOutbound <IByteBuffer>();
            var compressedBinaryPayload = encoderChannel.ReadOutbound <IByteBuffer>();

            TextWebSocketFrame   compressedTextFrame   = new TextWebSocketFrame(true, WebSocketRsv.Rsv1, compressedTextPayload);
            BinaryWebSocketFrame compressedBinaryFrame = new BinaryWebSocketFrame(true, WebSocketRsv.Rsv1, compressedBinaryPayload);

            Assert.True(decoderChannel.WriteInbound(compressedTextFrame));
            Assert.True(decoderChannel.WriteInbound(compressedBinaryFrame));

            var inboundTextFrame   = decoderChannel.ReadInbound <TextWebSocketFrame>();
            var inboundBinaryFrame = decoderChannel.ReadInbound <BinaryWebSocketFrame>();

            Assert.Equal(WebSocketRsv.Rsv1, inboundTextFrame.Rsv);
            Assert.Equal(compressedTextPayload, inboundTextFrame.Content);
            Assert.True(inboundTextFrame.Release());

            Assert.Equal(0, inboundBinaryFrame.Rsv);
            Assert.Equal(binaryPayload, ByteBufferUtil.GetBytes(inboundBinaryFrame.Content));
            Assert.True(inboundBinaryFrame.Release());

            Assert.True(encoderChannel.FinishAndReleaseAll());
            Assert.False(decoderChannel.Finish());
        }
コード例 #19
0
        public void FragmentedFrame()
        {
            var encoderChannel = new EmbeddedChannel(new PerMessageDeflateEncoder(9, 15, false, NeverSkipWebSocketExtensionFilter.Instance));
            var decoderChannel = new EmbeddedChannel(
                ZlibCodecFactory.NewZlibDecoder(ZlibWrapper.None));

            // initialize
            var payload1 = new byte[100];

            _random.NextBytes(payload1);
            var payload2 = new byte[100];

            _random.NextBytes(payload2);
            var payload3 = new byte[100];

            _random.NextBytes(payload3);

            var frame1 = new BinaryWebSocketFrame(false,
                                                  WebSocketRsv.Rsv3, Unpooled.WrappedBuffer(payload1));
            var frame2 = new ContinuationWebSocketFrame(false,
                                                        WebSocketRsv.Rsv3, Unpooled.WrappedBuffer(payload2));
            var frame3 = new ContinuationWebSocketFrame(true,
                                                        WebSocketRsv.Rsv3, Unpooled.WrappedBuffer(payload3));

            // execute
            Assert.True(encoderChannel.WriteOutbound(frame1));
            Assert.True(encoderChannel.WriteOutbound(frame2));
            Assert.True(encoderChannel.WriteOutbound(frame3));
            var compressedFrame1 = encoderChannel.ReadOutbound <BinaryWebSocketFrame>();
            var compressedFrame2 = encoderChannel.ReadOutbound <ContinuationWebSocketFrame>();
            var compressedFrame3 = encoderChannel.ReadOutbound <ContinuationWebSocketFrame>();

            // test
            Assert.NotNull(compressedFrame1);
            Assert.NotNull(compressedFrame2);
            Assert.NotNull(compressedFrame3);
            Assert.Equal(WebSocketRsv.Rsv1 | WebSocketRsv.Rsv3, compressedFrame1.Rsv);
            Assert.Equal(WebSocketRsv.Rsv3, compressedFrame2.Rsv);
            Assert.Equal(WebSocketRsv.Rsv3, compressedFrame3.Rsv);
            Assert.False(compressedFrame1.IsFinalFragment);
            Assert.False(compressedFrame2.IsFinalFragment);
            Assert.True(compressedFrame3.IsFinalFragment);

            Assert.True(decoderChannel.WriteInbound(compressedFrame1.Content));
            var uncompressedPayload1 = decoderChannel.ReadInbound <IByteBuffer>();
            var finalPayload1        = new byte[100];

            uncompressedPayload1.ReadBytes(finalPayload1);
            Assert.Equal(payload1, finalPayload1);
            uncompressedPayload1.Release();

            Assert.True(decoderChannel.WriteInbound(compressedFrame2.Content));
            var uncompressedPayload2 = decoderChannel.ReadInbound <IByteBuffer>();
            var finalPayload2        = new byte[100];

            uncompressedPayload2.ReadBytes(finalPayload2);
            Assert.Equal(payload2, finalPayload2);
            uncompressedPayload2.Release();

            Assert.True(decoderChannel.WriteInbound(compressedFrame3.Content));
            Assert.True(decoderChannel.WriteInbound(DeflateDecoder.FrameTail.Duplicate()));
            var uncompressedPayload3 = decoderChannel.ReadInbound <IByteBuffer>();
            var finalPayload3        = new byte[100];

            uncompressedPayload3.ReadBytes(finalPayload3);
            Assert.Equal(payload3, finalPayload3);
            uncompressedPayload3.Release();
        }
コード例 #20
0
        protected internal override void Decode(IChannelHandlerContext ctx, WebSocketFrame msg, List <object> output)
        {
            if (this.decoder == null)
            {
                if (!(msg is TextWebSocketFrame) && !(msg is BinaryWebSocketFrame))
                {
                    throw new CodecException($"unexpected initial frame type: {msg.GetType().Name}");
                }

                this.decoder = new EmbeddedChannel(ZlibCodecFactory.NewZlibDecoder(ZlibWrapper.None));
            }

            bool readable = msg.Content.IsReadable();

            this.decoder.WriteInbound(msg.Content.Retain());
            if (this.AppendFrameTail(msg))
            {
                this.decoder.WriteInbound(Unpooled.WrappedBuffer(FrameTail));
            }

            CompositeByteBuffer compositeUncompressedContent = ctx.Allocator.CompositeDirectBuffer();

            for (;;)
            {
                var partUncompressedContent = this.decoder.ReadInbound <IByteBuffer>();
                if (partUncompressedContent == null)
                {
                    break;
                }

                if (!partUncompressedContent.IsReadable())
                {
                    partUncompressedContent.Release();
                    continue;
                }

                compositeUncompressedContent.AddComponent(true, partUncompressedContent);
            }

            // Correctly handle empty frames
            // See https://github.com/netty/netty/issues/4348
            if (readable && compositeUncompressedContent.NumComponents <= 0)
            {
                compositeUncompressedContent.Release();
                throw new CodecException("cannot read uncompressed buffer");
            }

            if (msg.IsFinalFragment && this.noContext)
            {
                this.Cleanup();
            }

            WebSocketFrame outMsg;

            if (msg is TextWebSocketFrame)
            {
                outMsg = new TextWebSocketFrame(msg.IsFinalFragment, this.NewRsv(msg), compositeUncompressedContent);
            }
            else if (msg is BinaryWebSocketFrame)
            {
                outMsg = new BinaryWebSocketFrame(msg.IsFinalFragment, this.NewRsv(msg), compositeUncompressedContent);
            }
            else if (msg is ContinuationWebSocketFrame)
            {
                outMsg = new ContinuationWebSocketFrame(msg.IsFinalFragment, this.NewRsv(msg), compositeUncompressedContent);
            }
            else
            {
                throw new CodecException($"unexpected frame type: {msg.GetType().Name}");
            }

            output.Add(outMsg);
        }
コード例 #21
0
        public void FramementedFrame()
        {
            var encoderChannel = new EmbeddedChannel(new PerFrameDeflateEncoder(9, 15, false));
            var decoderChannel = new EmbeddedChannel(
                ZlibCodecFactory.NewZlibDecoder(ZlibWrapper.None));

            var payload1 = new byte[100];

            this.random.NextBytes(payload1);
            var payload2 = new byte[100];

            this.random.NextBytes(payload2);
            var payload3 = new byte[100];

            this.random.NextBytes(payload3);

            var frame1 = new BinaryWebSocketFrame(false,
                                                  WebSocketRsv.Rsv3, Unpooled.WrappedBuffer(payload1));
            var frame2 = new ContinuationWebSocketFrame(false,
                                                        WebSocketRsv.Rsv3, Unpooled.WrappedBuffer(payload2));
            var frame3 = new ContinuationWebSocketFrame(true,
                                                        WebSocketRsv.Rsv3, Unpooled.WrappedBuffer(payload3));

            encoderChannel.WriteOutbound(frame1);
            encoderChannel.WriteOutbound(frame2);
            encoderChannel.WriteOutbound(frame3);
            var compressedFrame1 = encoderChannel.ReadOutbound <BinaryWebSocketFrame>();
            var compressedFrame2 = encoderChannel.ReadOutbound <ContinuationWebSocketFrame>();
            var compressedFrame3 = encoderChannel.ReadOutbound <ContinuationWebSocketFrame>();

            Assert.NotNull(compressedFrame1);
            Assert.NotNull(compressedFrame2);
            Assert.NotNull(compressedFrame3);
            Assert.Equal(WebSocketRsv.Rsv1 | WebSocketRsv.Rsv3, compressedFrame1.Rsv);
            Assert.Equal(WebSocketRsv.Rsv1 | WebSocketRsv.Rsv3, compressedFrame2.Rsv);
            Assert.Equal(WebSocketRsv.Rsv1 | WebSocketRsv.Rsv3, compressedFrame3.Rsv);
            Assert.False(compressedFrame1.IsFinalFragment);
            Assert.False(compressedFrame2.IsFinalFragment);
            Assert.True(compressedFrame3.IsFinalFragment);

            decoderChannel.WriteInbound(compressedFrame1.Content);
            decoderChannel.WriteInbound(Unpooled.WrappedBuffer(DeflateDecoder.FrameTail));
            var uncompressedPayload1 = decoderChannel.ReadInbound <IByteBuffer>();
            var finalPayload1        = new byte[100];

            uncompressedPayload1.ReadBytes(finalPayload1);
            Assert.Equal(payload1, finalPayload1);
            uncompressedPayload1.Release();

            decoderChannel.WriteInbound(compressedFrame2.Content);
            decoderChannel.WriteInbound(Unpooled.WrappedBuffer(DeflateDecoder.FrameTail));
            var uncompressedPayload2 = decoderChannel.ReadInbound <IByteBuffer>();
            var finalPayload2        = new byte[100];

            uncompressedPayload2.ReadBytes(finalPayload2);
            Assert.Equal(payload2, finalPayload2);
            uncompressedPayload2.Release();

            decoderChannel.WriteInbound(compressedFrame3.Content);
            decoderChannel.WriteInbound(Unpooled.WrappedBuffer(DeflateDecoder.FrameTail));
            var uncompressedPayload3 = decoderChannel.ReadInbound <IByteBuffer>();
            var finalPayload3        = new byte[100];

            uncompressedPayload3.ReadBytes(finalPayload3);
            Assert.Equal(payload3, finalPayload3);
            uncompressedPayload3.Release();
        }
コード例 #22
0
ファイル: DeflateDecoder.cs プロジェクト: wxlonstar/Fenix
        private IByteBuffer DecompressContent(IChannelHandlerContext ctx, WebSocketFrame msg)
        {
            if (_decoder is null)
            {
                switch (msg.Opcode)
                {
                case Opcode.Text:
                case Opcode.Binary:
                    break;

                default:
                    ThrowHelper.ThrowCodecException_UnexpectedInitialFrameType(msg);
                    break;
                }
                _decoder = new EmbeddedChannel(ZlibCodecFactory.NewZlibDecoder(ZlibWrapper.None));
            }

            var readable          = msg.Content.IsReadable();
            var emptyDeflateBlock = EmptyDeflateBlock.Equals(msg.Content);

            _ = _decoder.WriteInbound(msg.Content.Retain());
            if (AppendFrameTail(msg))
            {
                _ = _decoder.WriteInbound(FrameTail.Duplicate());
            }

            var compositeDecompressedContent = ctx.Allocator.CompositeBuffer();

            for (; ;)
            {
                var partUncompressedContent = _decoder.ReadInbound <IByteBuffer>();
                if (partUncompressedContent is null)
                {
                    break;
                }
                if (!partUncompressedContent.IsReadable())
                {
                    _ = partUncompressedContent.Release();
                    continue;
                }
                _ = compositeDecompressedContent.AddComponent(true, partUncompressedContent);
            }
            // Correctly handle empty frames
            // See https://github.com/netty/netty/issues/4348
            if (!emptyDeflateBlock && readable && compositeDecompressedContent.NumComponents <= 0)
            {
                // Sometimes after fragmentation the last frame
                // May contain left-over data that doesn't affect decompression
                if (!(msg is ContinuationWebSocketFrame))
                {
                    _ = compositeDecompressedContent.Release();
                    ThrowHelper.ThrowCodecException_CannotReadUncompressedBuf();
                }
            }

            if (msg.IsFinalFragment && _noContext)
            {
                Cleanup();
            }

            return(compositeDecompressedContent);
        }
コード例 #23
0
        public void FragmentedFrameWithLeftOverInLastFragment()
        {
            string hexDump = "677170647a777a737574656b707a787a6f6a7561756578756f6b7868616371716c657a6d64697479766d726f6" +
                             "269746c6376777464776f6f72767a726f64667278676764687775786f6762766d776d706b76697773777a7072" +
                             "6a6a737279707a7078697a6c69616d7461656d646278626d786f66666e686e776a7a7461746d7a776668776b6" +
                             "f6f736e73746575637a6d727a7175707a6e74627578687871767771697a71766c64626d78726d6d7675756877" +
                             "62667963626b687a726d676e646263776e67797264706d6c6863626577616967706a78636a72697464756e627" +
                             "977616f79736475676f76736f7178746a7a7479626c64636b6b6778637768746c62";
            EmbeddedChannel encoderChannel = new EmbeddedChannel(
                ZlibCodecFactory.NewZlibEncoder(ZlibWrapper.None, 9, 15, 8));
            EmbeddedChannel decoderChannel = new EmbeddedChannel(new PerMessageDeflateDecoder(false));

            IByteBuffer originPayload = Unpooled.WrappedBuffer(StringUtil.DecodeHexDump(hexDump));

            Assert.True(encoderChannel.WriteOutbound(originPayload.Duplicate().Retain()));

            var compressedPayload = encoderChannel.ReadOutbound <IByteBuffer>();

            compressedPayload = compressedPayload.Slice(0, compressedPayload.ReadableBytes - 4);

            int oneThird = compressedPayload.ReadableBytes / 3;

            TextWebSocketFrame compressedFrame1 = new TextWebSocketFrame(
                false, WebSocketRsv.Rsv1, compressedPayload.Slice(0, oneThird));
            ContinuationWebSocketFrame compressedFrame2 = new ContinuationWebSocketFrame(
                false, WebSocketRsv.Rsv3, compressedPayload.Slice(oneThird, oneThird));
            ContinuationWebSocketFrame compressedFrame3 = new ContinuationWebSocketFrame(
                false, WebSocketRsv.Rsv3, compressedPayload.Slice(oneThird * 2, oneThird));
            int offset = oneThird * 3;
            ContinuationWebSocketFrame compressedFrameWithExtraData = new ContinuationWebSocketFrame(
                true, WebSocketRsv.Rsv3, compressedPayload.Slice(offset,
                                                                 compressedPayload.ReadableBytes - offset));

            // check that last fragment contains only one extra byte
            Assert.Equal(1, compressedFrameWithExtraData.Content.ReadableBytes);
            Assert.Equal(1, compressedFrameWithExtraData.Content.GetByte(0));

            // write compressed frames
            Assert.True(decoderChannel.WriteInbound(compressedFrame1.Retain()));
            Assert.True(decoderChannel.WriteInbound(compressedFrame2.Retain()));
            Assert.True(decoderChannel.WriteInbound(compressedFrame3.Retain()));
            Assert.True(decoderChannel.WriteInbound(compressedFrameWithExtraData));

            // read uncompressed frames
            TextWebSocketFrame         uncompressedFrame1    = decoderChannel.ReadInbound <TextWebSocketFrame>();
            ContinuationWebSocketFrame uncompressedFrame2    = decoderChannel.ReadInbound <ContinuationWebSocketFrame>();
            ContinuationWebSocketFrame uncompressedFrame3    = decoderChannel.ReadInbound <ContinuationWebSocketFrame>();
            ContinuationWebSocketFrame uncompressedExtraData = decoderChannel.ReadInbound <ContinuationWebSocketFrame>();

            Assert.False(uncompressedExtraData.Content.IsReadable());

            var uncompressedPayload = Unpooled.WrappedBuffer(uncompressedFrame1.Content, uncompressedFrame2.Content,
                                                             uncompressedFrame3.Content, uncompressedExtraData.Content);

            Assert.Equal(originPayload, uncompressedPayload);

            Assert.True(originPayload.Release());
            Assert.True(uncompressedPayload.Release());

            Assert.True(encoderChannel.FinishAndReleaseAll());
            Assert.False(decoderChannel.Finish());
        }
コード例 #24
0
        protected internal override void Encode(IChannelHandlerContext ctx, WebSocketFrame msg, List <object> output)
        {
            if (this.encoder == null)
            {
                this.encoder = new EmbeddedChannel(
                    ZlibCodecFactory.NewZlibEncoder(
                        ZlibWrapper.None,
                        this.compressionLevel,
                        this.windowSize,
                        8));
            }

            this.encoder.WriteOutbound(msg.Content.Retain());

            CompositeByteBuffer fullCompressedContent = ctx.Allocator.CompositeBuffer();

            for (;;)
            {
                var partCompressedContent = this.encoder.ReadOutbound <IByteBuffer>();
                if (partCompressedContent == null)
                {
                    break;
                }

                if (!partCompressedContent.IsReadable())
                {
                    partCompressedContent.Release();
                    continue;
                }

                fullCompressedContent.AddComponent(true, partCompressedContent);
            }

            if (fullCompressedContent.NumComponents <= 0)
            {
                fullCompressedContent.Release();
                throw new CodecException("cannot read compressed buffer");
            }

            if (msg.IsFinalFragment && this.noContext)
            {
                this.Cleanup();
            }

            IByteBuffer compressedContent;

            if (this.RemoveFrameTail(msg))
            {
                int realLength = fullCompressedContent.ReadableBytes - FrameTail.Length;
                compressedContent = fullCompressedContent.Slice(0, realLength);
            }
            else
            {
                compressedContent = fullCompressedContent;
            }

            WebSocketFrame outMsg;

            if (msg is TextWebSocketFrame)
            {
                outMsg = new TextWebSocketFrame(msg.IsFinalFragment, this.Rsv(msg), compressedContent);
            }
            else if (msg is BinaryWebSocketFrame)
            {
                outMsg = new BinaryWebSocketFrame(msg.IsFinalFragment, this.Rsv(msg), compressedContent);
            }
            else if (msg is ContinuationWebSocketFrame)
            {
                outMsg = new ContinuationWebSocketFrame(msg.IsFinalFragment, this.Rsv(msg), compressedContent);
            }
            else
            {
                throw new CodecException($"unexpected frame type: {msg.GetType().Name}");
            }

            output.Add(outMsg);
        }