Пример #1
0
        public void TestCopiedBuffer()
        {
            AssertEqualAndRelease(Unpooled.WrappedBuffer(new byte[] { 1, 2, 3 }),
                                  Unpooled.CopiedBuffer(new[] { new byte[] { 1, 2, 3 } }));

            AssertEqualAndRelease(Unpooled.WrappedBuffer(new byte[] { 1, 2, 3 }),
                                  Unpooled.CopiedBuffer(new byte[] { 1 }, new byte[] { 2 }, new byte[] { 3 }));

            AssertEqualAndRelease(Unpooled.WrappedBuffer(new byte[] { 1, 2, 3 }),
                                  Unpooled.CopiedBuffer(new[] { Unpooled.WrappedBuffer(new byte[] { 1, 2, 3 }) }));

            AssertEqualAndRelease(Unpooled.WrappedBuffer(new byte[] { 1, 2, 3 }),
                                  Unpooled.CopiedBuffer(Unpooled.WrappedBuffer(new byte[] { 1 }),
                                                        Unpooled.WrappedBuffer(new byte[] { 2 }), Unpooled.WrappedBuffer(new byte[] { 3 })));
        }
Пример #2
0
 public void ShouldReturnEmptyBufferWhenLengthIsZero()
 {
     AssertSameAndRelease(Unpooled.Empty, Unpooled.WrappedBuffer(EmptyBytes));
     AssertSameAndRelease(Unpooled.Empty, Unpooled.WrappedBuffer(new byte[8], 0, 0));
     AssertSameAndRelease(Unpooled.Empty, Unpooled.WrappedBuffer(new byte[8], 8, 0));
     AssertSameAndRelease(Unpooled.Empty, Unpooled.WrappedBuffer(Unpooled.Empty));
     AssertSameAndRelease(Unpooled.Empty, Unpooled.CopiedBuffer(EmptyBytes));
     AssertSameAndRelease(Unpooled.Empty, Unpooled.CopiedBuffer(new byte[8], 0, 0));
     AssertSameAndRelease(Unpooled.Empty, Unpooled.CopiedBuffer(new byte[8], 8, 0));
     AssertSameAndRelease(Unpooled.Empty, Unpooled.CopiedBuffer(Unpooled.Empty));
     AssertSameAndRelease(Unpooled.Empty, Unpooled.CopiedBuffer(new[] { EmptyBytes }));
     AssertSameAndRelease(Unpooled.Empty, Unpooled.CopiedBuffer(EmptyByteBuffer));
     AssertSameAndRelease(Unpooled.Empty, Unpooled.CopiedBuffer(new[] { Unpooled.Buffer(0) }));
     AssertSameAndRelease(Unpooled.Empty, Unpooled.CopiedBuffer(Unpooled.Buffer(0), Unpooled.Buffer(0)));
 }
Пример #3
0
        public void TooLongLine1()
        {
            EmbeddedChannel ch = new EmbeddedChannel(new LineBasedFrameDecoder(16, false, false));

            Assert.Throws <TooLongFrameException>(() => ch.WriteInbound(Unpooled.CopiedBuffer("12345678901234567890\r\nfirst\nsecond", Encoding.ASCII)));

            var buf  = ch.ReadInbound <IByteBuffer>();
            var buf2 = Unpooled.CopiedBuffer("first\n", Encoding.ASCII);

            AssertEx.Equal(buf, buf2);
            Assert.False(ch.Finish());

            buf.Release();
            buf2.Release();
        }
Пример #4
0
        public void ChannelDataParserTest()
        {
            var eventData          = AppDomain.CurrentDomain.BaseDirectory + "\\Messages\\ChannelData.txt";
            var backgroundJobBytes = File.ReadAllBytes(eventData);
            var byteBuffer         = Unpooled.CopiedBuffer(backgroundJobBytes);
            var channel            = new EmbeddedChannel(new EslFrameDecoder());

            channel.WriteInbound(byteBuffer);

            var message = channel.ReadInbound <EslMessage>();

            Assert.True(message.HasHeader("Event-Name"));
            Assert.Equal("CHANNEL_DATA",
                         message.Headers["Event-Name"]);
        }
Пример #5
0
        public void InitialLineWithLeadingControlChars()
        {
            EmbeddedChannel channel = new EmbeddedChannel(new HttpRequestDecoder());
            string          crlf    = "\r\n";
            string          request = crlf + "GET /some/path HTTP/1.1" + crlf +
                                      "Host: localhost" + crlf + crlf;

            Assert.True(channel.WriteInbound(Unpooled.CopiedBuffer(request, Encoding.ASCII)));
            var req = channel.ReadInbound <IHttpRequest>();

            Assert.Equal(HttpMethod.Get, req.Method);
            Assert.Equal("/some/path", req.Uri);
            Assert.Equal(HttpVersion.Http11, req.ProtocolVersion);
            Assert.True(channel.FinishAndReleaseAll());
        }
Пример #6
0
        public override async void ChannelRead(IChannelHandlerContext context, object message)
        {
            var buffer = (IByteBuffer)message;

            if (buffer == null)
            {
                return;
            }

            var packet = new byte[buffer.ReadableBytes];

            buffer.GetBytes(buffer.ReaderIndex, packet);

            await Device.ProcessAsync(Unpooled.CopiedBuffer(packet));
        }
Пример #7
0
        public void OversizedResponse()
        {
            var aggregator = new HttpObjectAggregator(4);
            var ch         = new EmbeddedChannel(aggregator);
            var message    = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);
            var chunk1     = new DefaultHttpContent(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("test")));
            var chunk2     = new DefaultHttpContent(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("test2")));

            Assert.False(ch.WriteInbound(message));
            Assert.False(ch.WriteInbound(chunk1));
            Assert.Throws <TooLongFrameException>(() => ch.WriteInbound(chunk2));

            Assert.False(ch.IsOpen);
            Assert.False(ch.Finish());
        }
Пример #8
0
        public void Whitespace()
        {
            EmbeddedChannel channel    = new EmbeddedChannel(new HttpResponseDecoder());
            string          requestStr = "HTTP/1.1 200 OK\r\n" +
                                         "Transfer-Encoding : chunked\r\n" +
                                         "Host: netty.io\n\r\n";

            Assert.True(channel.WriteInbound(Unpooled.CopiedBuffer(requestStr, Encoding.ASCII)));
            var response = channel.ReadInbound <IHttpResponse>();

            Assert.False(response.Result.IsFailure);
            Assert.Equal(HttpHeaderValues.Chunked.ToString(), response.Headers.Get(HttpHeaderNames.TransferEncoding, null));
            Assert.Equal("netty.io", response.Headers.Get(HttpHeaderNames.Host, null));
            Assert.False(channel.Finish());
        }
        public void ResponseChunked()
        {
            var ch = new EmbeddedChannel(new HttpResponseDecoder());

            ch.WriteInbound(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n")));

            var res = ch.ReadInbound <IHttpResponse>();

            Assert.Same(HttpVersion.Http11, res.ProtocolVersion);
            Assert.Equal(HttpResponseStatus.OK, res.Status);

            var data = new byte[64];

            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)i;
            }

            for (int i = 0; i < 10; i++)
            {
                Assert.False(ch.WriteInbound(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes($"{Convert.ToString(data.Length, 16)}\r\n"))));
                Assert.True(ch.WriteInbound(Unpooled.WrappedBuffer(data)));
                var content = ch.ReadInbound <IHttpContent>();
                Assert.Equal(data.Length, content.Content.ReadableBytes);

                var decodedData = new byte[data.Length];
                content.Content.ReadBytes(decodedData);
                Assert.True(data.SequenceEqual(decodedData));
                content.Release();

                Assert.False(ch.WriteInbound(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("\r\n"))));
            }

            // Write the last chunk.
            ch.WriteInbound(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("0\r\n\r\n")));

            // Ensure the last chunk was decoded.
            var lastContent = ch.ReadInbound <ILastHttpContent>();

            Assert.False(lastContent.Content.IsReadable());
            lastContent.Release();

            ch.Finish();

            var last = ch.ReadInbound <IByteBufferHolder>();

            Assert.Null(last);
        }
Пример #10
0
        public void ChunkedContentWithTrailingHeader()
        {
            var ch = new EmbeddedChannel(new HttpContentCompressor());

            ch.WriteInbound(NewRequest());

            var res = new DefaultHttpResponse(HttpVersion.Http11, HttpResponseStatus.OK);

            res.Headers.Set(HttpHeaderNames.TransferEncoding, HttpHeaderValues.Chunked);
            ch.WriteOutbound(res);

            AssertEncodedResponse(ch);

            ch.WriteOutbound(new DefaultHttpContent(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("Hell"))));
            ch.WriteOutbound(new DefaultHttpContent(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("o, w"))));
            var content = new DefaultLastHttpContent(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("orld")));

            content.TrailingHeaders.Set((AsciiString)"X-Test", (AsciiString)"Netty");
            ch.WriteOutbound(content);

            var chunk = ch.ReadOutbound <IHttpContent>();

            Assert.Equal($"1f8b08000000000000{Platform}f248cdc901000000ffff", ByteBufferUtil.HexDump(chunk.Content));
            chunk.Release();

            chunk = ch.ReadOutbound <IHttpContent>();
            Assert.Equal("cad7512807000000ffff", ByteBufferUtil.HexDump(chunk.Content));
            chunk.Release();

            chunk = ch.ReadOutbound <IHttpContent>();
            Assert.Equal("ca2fca4901000000ffff", ByteBufferUtil.HexDump(chunk.Content));
            chunk.Release();

            chunk = ch.ReadOutbound <IHttpContent>();
            Assert.Equal("0300c2a99ae70c000000", ByteBufferUtil.HexDump(chunk.Content));
            chunk.Release();

            var lastChunk = ch.ReadOutbound <ILastHttpContent>();

            Assert.NotNull(lastChunk);
            Assert.Equal("Netty", lastChunk.TrailingHeaders.Get((AsciiString)"X-Test", null).ToString());
            Assert.Equal(DecoderResult.Success, chunk.Result);
            lastChunk.Release();

            var last = ch.ReadOutbound();

            Assert.Null(last);
        }
        public void ConnectionClosedBeforeHeadersReceived()
        {
            var          ch = new EmbeddedChannel(new HttpResponseDecoder());
            const string ResponseInitialLine = "HTTP/1.1 200 OK\r\n";

            Assert.False(ch.WriteInbound(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes(ResponseInitialLine))));
            Assert.True(ch.Finish());
            var message = ch.ReadInbound <IHttpMessage>();

            Assert.True(message.Result.IsFailure);
            Assert.IsType <PrematureChannelClosureException>(message.Result.Cause);

            var last = ch.ReadInbound <IByteBufferHolder>();

            Assert.Null(last);
        }
Пример #12
0
        public void ServerReceivingInvalidClientPrefaceStringShouldHandleException()
        {
            _connection.Setup(x => x.IsServer).Returns(true);
            _handler = NewHandler();
            _handler.ChannelRead(_ctx.Object, Unpooled.CopiedBuffer("BAD_PREFACE", Encoding.UTF8));
            var captor = new ArgumentCaptor <IByteBuffer>();

            _frameWriter.Verify(
                x => x.WriteGoAwayAsync(
                    It.Is <IChannelHandlerContext>(v => v == _ctx.Object),
                    It.Is <int>(v => v == 0),
                    It.Is <Http2Error>(v => v == Http2Error.ProtocolError),
                    It.Is <IByteBuffer>(v => captor.Capture(v)),
                    It.Is <IPromise>(v => v == _promise)));
            Assert.Equal(0, captor.GetValue().ReferenceCount);
        }
Пример #13
0
        public void OneBodyLineMessageTest()
        {
            _event = AppDomain.CurrentDomain.BaseDirectory + "\\Messages\\Gateways.txt";
            var charBytes = File.ReadAllBytes(_event);
            var message   = Unpooled.CopiedBuffer(charBytes);
            var channel   = new EmbeddedChannel(new EslFrameDecoder());

            channel.WriteInbound(message);
            var buf = channel.ReadInbound <EslMessage>();

            var body = string.Join("",
                                   buf.BodyLines);

            Assert.Equal("example.com smsghlocalsip",
                         body);
        }
Пример #14
0
        public void ChunkedRequestDecompression()
        {
            HttpResponseDecoder decoder      = new HttpResponseDecoder();
            HttpContentDecoder  decompressor = new HttpContentDecompressor();

            EmbeddedChannel channel = new EmbeddedChannel(decoder, decompressor, null);

            string headers = "HTTP/1.1 200 OK\r\n"
                             + "Transfer-Encoding: chunked\r\n"
                             + "Trailer: My-Trailer\r\n"
                             + "Content-Encoding: gzip\r\n\r\n";

            channel.WriteInbound(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes(headers)));

            string chunkLength = GzHelloWorld.Length.ToString("x2");

            Assert.True(channel.WriteInbound(Unpooled.CopiedBuffer(chunkLength + "\r\n", Encoding.ASCII)));
            Assert.True(channel.WriteInbound(Unpooled.CopiedBuffer(GzHelloWorld)));
            Assert.True(channel.WriteInbound(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("\r\n"))));
            Assert.True(channel.WriteInbound(Unpooled.CopiedBuffer("0\r\n", Encoding.ASCII)));
            Assert.True(channel.WriteInbound(Unpooled.CopiedBuffer("My-Trailer: 42\r\n\r\n\r\n", Encoding.ASCII)));

            object ob1 = channel.ReadInbound <object>();

            Assert.True(ob1 is DefaultHttpResponse);

            object ob2 = channel.ReadInbound <object>();

            Assert.True(ob1 is DefaultHttpResponse);
            IHttpContent content = (IHttpContent)ob2;

            Assert.Equal(HelloWorld, content.Content.ToString(Encoding.ASCII));
            content.Release();

            object ob3 = channel.ReadInbound <object>();

            Assert.True(ob1 is DefaultHttpResponse);
            ILastHttpContent lastContent = (ILastHttpContent)ob3;

            Assert.NotNull(lastContent.Result);
            Assert.True(lastContent.Result.IsSuccess);
            Assert.False(lastContent.TrailingHeaders.IsEmpty);
            Assert.Equal("42", lastContent.TrailingHeaders.Get((AsciiString)"My-Trailer", null));
            AssertHasInboundMessages(channel, false);
            AssertHasOutboundMessages(channel, false);
            Assert.False(channel.Finish());
        }
Пример #15
0
        static void DecodeWholeRequestInMultipleSteps(byte[] content, int fragmentSize)
        {
            var channel      = new EmbeddedChannel(new HttpRequestDecoder());
            int headerLength = content.Length - ContentLength;

            // split up the header
            for (int a = 0; a < headerLength;)
            {
                int amount = fragmentSize;
                if (a + amount > headerLength)
                {
                    amount = headerLength - a;
                }

                // if header is done it should produce an HttpRequest
                channel.WriteInbound(Unpooled.CopiedBuffer(content, a, amount));
                a += amount;
            }

            for (int i = ContentLength; i > 0; i--)
            {
                // Should produce HttpContent
                channel.WriteInbound(Unpooled.CopiedBuffer(content, content.Length - i, 1));
            }

            var req = channel.ReadInbound <IHttpRequest>();

            Assert.NotNull(req);
            CheckHeaders(req.Headers);

            for (int i = ContentLength; i > 1; i--)
            {
                var c = channel.ReadInbound <IHttpContent>();
                Assert.Equal(1, c.Content.ReadableBytes);
                Assert.Equal(content[content.Length - i], c.Content.ReadByte());
                c.Release();
            }

            var last = channel.ReadInbound <ILastHttpContent>();

            Assert.Equal(1, last.Content.ReadableBytes);
            Assert.Equal(content[content.Length - 1], last.Content.ReadByte());
            last.Release();

            Assert.False(channel.Finish());
            Assert.Null(channel.ReadInbound <IHttpObject>());
        }
Пример #16
0
        static void ResponseWithContentLengthFragmented0(byte[] header, int fragmentSize)
        {
            var ch = new EmbeddedChannel(new HttpResponseDecoder());

            // split up the header
            for (int a = 0; a < header.Length;)
            {
                int amount = fragmentSize;
                if (a + amount > header.Length)
                {
                    amount = header.Length - a;
                }

                ch.WriteInbound(Unpooled.CopiedBuffer(header, a, amount));
                a += amount;
            }
            var data = new byte[10];

            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)i;
            }
            ch.WriteInbound(Unpooled.CopiedBuffer(data, 0, data.Length / 2));
            ch.WriteInbound(Unpooled.CopiedBuffer(data, 5, data.Length / 2));

            var res = ch.ReadInbound <IHttpResponse>();

            Assert.Same(HttpVersion.Http11, res.ProtocolVersion);
            Assert.Equal(HttpResponseStatus.OK, res.Status);

            var firstContent = ch.ReadInbound <IHttpContent>();

            Assert.Equal(5, firstContent.Content.ReadableBytes);
            Assert.Equal(Unpooled.WrappedBuffer(data, 0, 5), firstContent.Content);
            firstContent.Release();

            var lastContent = ch.ReadInbound <ILastHttpContent>();

            Assert.Equal(5, lastContent.Content.ReadableBytes);
            Assert.Equal(Unpooled.WrappedBuffer(data, 5, 5), lastContent.Content);
            lastContent.Release();

            Assert.False(ch.Finish());
            var last = ch.ReadInbound <IByteBufferHolder>();

            Assert.Null(last);
        }
Пример #17
0
        public void RequestAfterOversized100ContinueAndDecoder()
        {
            var ch = new EmbeddedChannel(new HttpRequestDecoder(), new HttpObjectAggregator(15));

            // Write first request with Expect: 100-continue.
            var message = new DefaultHttpRequest(HttpVersion.Http11, HttpMethod.Put, "http://localhost");

            HttpUtil.Set100ContinueExpected(message, true);
            HttpUtil.SetContentLength(message, 16);

            var chunk1 = new DefaultHttpContent(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("some")));
            var chunk2 = new DefaultHttpContent(Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("test")));
            EmptyLastHttpContent chunk3 = EmptyLastHttpContent.Default;

            // Send a request with 100-continue + large Content-Length header value.
            Assert.False(ch.WriteInbound(message));

            // The aggregator should respond with '413'.
            var response = ch.ReadOutbound <IFullHttpResponse>();

            Assert.Equal(HttpResponseStatus.RequestEntityTooLarge, response.Status);
            Assert.Equal((AsciiString)"0", response.Headers.Get(HttpHeaderNames.ContentLength, null));

            // An ill-behaving client could continue to send data without a respect, and such data should be discarded.
            Assert.False(ch.WriteInbound(chunk1));

            // The aggregator should not close the connection because keep-alive is on.
            Assert.True(ch.Open);

            // Now send a valid request.
            var message2 = new DefaultHttpRequest(HttpVersion.Http11, HttpMethod.Put, "http://localhost");

            Assert.False(ch.WriteInbound(message2));
            Assert.False(ch.WriteInbound(chunk2));
            Assert.True(ch.WriteInbound(chunk3));

            var fullMsg = ch.ReadInbound <IFullHttpRequest>();

            Assert.NotNull(fullMsg);

            Assert.Equal(chunk2.Content.ReadableBytes + chunk3.Content.ReadableBytes, HttpUtil.GetContentLength(fullMsg));
            Assert.Equal(HttpUtil.GetContentLength(fullMsg), fullMsg.Content.ReadableBytes);

            fullMsg.Release();
            Assert.False(ch.Finish());
        }
Пример #18
0
        public void ServerReceivingHttp1ClientPrefaceStringShouldIncludePreface()
        {
            _connection.Setup(x => x.IsServer).Returns(true);
            _handler = NewHandler();
            _handler.ChannelRead(_ctx.Object, Unpooled.CopiedBuffer("GET /path HTTP/1.1", Encoding.ASCII));
            var captor = new ArgumentCaptor <IByteBuffer>();

            _frameWriter.Verify(
                x => x.WriteGoAwayAsync(
                    It.Is <IChannelHandlerContext>(v => v == _ctx.Object),
                    It.Is <int>(v => v == 0),
                    It.Is <Http2Error>(v => v == Http2Error.ProtocolError),
                    It.Is <IByteBuffer>(v => captor.Capture(v)),
                    It.Is <IPromise>(v => v == _promise)));
            Assert.Equal(0, captor.GetValue().ReferenceCount);
            Assert.Contains("/path", _goAwayDebugCap);
        }
Пример #19
0
        public async Task <bool> SendAsync(byte[] message)
        {
            if (message == null)
            {
                return(false);
            }

            if (_channel == null || !_channel.Active)
            {
                //Logger.Instance.Common.Info($"[ Netty ] SendAsync, Connection Inactive");
                return(false);
            }

            await _channel.WriteAndFlushAsync(Unpooled.CopiedBuffer(message));

            return(true);
        }
Пример #20
0
        public void FullContentWithContentLength()
        {
            var ch = new EmbeddedChannel(new HttpContentCompressor());

            ch.WriteInbound(NewRequest());

            var fullRes = new DefaultFullHttpResponse(
                HttpVersion.Http11,
                HttpResponseStatus.OK,
                Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes("Hello, World")));

            fullRes.Headers.Set(HttpHeaderNames.ContentLength, fullRes.Content.ReadableBytes);
            ch.WriteOutbound(fullRes);

            var res = ch.ReadOutbound <IHttpResponse>();

            Assert.NotNull(res);
            Assert.False(res is IHttpContent, $"{res.GetType()}");

            Assert.False(res.Headers.TryGet(HttpHeaderNames.TransferEncoding, out _));
            Assert.Equal("gzip", res.Headers.Get(HttpHeaderNames.ContentEncoding, null).ToString());

            long contentLengthHeaderValue = HttpUtil.GetContentLength(res);
            long observedLength           = 0;

            var c = ch.ReadOutbound <IHttpContent>();

            observedLength += c.Content.ReadableBytes;
            Assert.Equal($"1f8b08000000000000{Platform}f248cdc9c9d75108cf2fca4901000000ffff", ByteBufferUtil.HexDump(c.Content));
            c.Release();

            c = ch.ReadOutbound <IHttpContent>();
            observedLength += c.Content.ReadableBytes;
            Assert.Equal("0300c6865b260c000000", ByteBufferUtil.HexDump(c.Content));
            c.Release();

            var last = ch.ReadOutbound <ILastHttpContent>();

            Assert.Equal(0, last.Content.ReadableBytes);
            last.Release();

            var next = ch.ReadOutbound();

            Assert.Null(next);
            Assert.Equal(contentLengthHeaderValue, observedLength);
        }
Пример #21
0
        public void PingFrame()
        {
            IByteBuffer pingData = Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes("Hello, world"));
            var         channel  = new EmbeddedChannel(new Handler());

            var inputMessage = new PingWebSocketFrame(pingData);

            Assert.False(channel.WriteInbound(inputMessage)); // the message was not propagated inbound

            // a Pong frame was written to the channel
            var response = channel.ReadOutbound <PongWebSocketFrame>();

            Assert.Equal(pingData, response.Content);

            pingData.Release();
            Assert.False(channel.Finish());
        }
Пример #22
0
        public void ChannelDataParserAsCommandReplyTest()
        {
            var eventData = AppDomain.CurrentDomain.BaseDirectory +
                            "\\Messages\\ChannelData.txt";
            var backgroundJobBytes = File.ReadAllBytes(eventData);
            var byteBuffer         = Unpooled.CopiedBuffer(backgroundJobBytes);
            var channel            = new EmbeddedChannel(new EslFrameDecoder());

            channel.WriteInbound(byteBuffer);

            var message      = channel.ReadInbound <EslMessage>();
            var commandReply = new CommandReply("connect", message);

            Assert.Equal("+OK", commandReply.ReplyText);
            Assert.Equal(true, commandReply.IsOk);
            Assert.Equal("command/reply", commandReply.ContentType);
        }
Пример #23
0
        static void LastResponseWithTrailingHeaderFragmented0(byte[] content, int fragmentSize)
        {
            var       ch           = new EmbeddedChannel(new HttpResponseDecoder());
            const int HeaderLength = 47;

            // split up the header
            for (int a = 0; a < HeaderLength;)
            {
                int amount = fragmentSize;
                if (a + amount > HeaderLength)
                {
                    amount = HeaderLength - a;
                }

                // if header is done it should produce an HttpRequest
                bool headerDone = a + amount == HeaderLength;
                Assert.Equal(headerDone, ch.WriteInbound(Unpooled.CopiedBuffer(content, a, amount)));
                a += amount;
            }

            ch.WriteInbound(Unpooled.CopiedBuffer(content, HeaderLength, content.Length - HeaderLength));
            var res = ch.ReadInbound <IHttpResponse>();

            Assert.Same(HttpVersion.Http11, res.ProtocolVersion);
            Assert.Equal(HttpResponseStatus.OK, res.Status);

            var lastContent = ch.ReadInbound <ILastHttpContent>();

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

            HttpHeaders headers = lastContent.TrailingHeaders;

            Assert.Equal(1, headers.Names().Count);
            IList <ICharSequence> values = headers.GetAll((AsciiString)"Set-Cookie");

            Assert.Equal(2, values.Count);
            Assert.True(values.Contains((AsciiString)"t1=t1v1"));
            Assert.True(values.Contains((AsciiString)"t2=t2v2; Expires=Wed, 09-Jun-2021 10:18:14 GMT"));
            lastContent.Release();

            Assert.False(ch.Finish());
            var last = ch.ReadInbound <IByteBufferHolder>();

            Assert.Null(last);
        }
Пример #24
0
        public void TestPaddingNewline()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                // TODO Azure DevOps X509Certificate.Export: System.Security.Cryptography.CryptographicException : ASN1 corrupted data.
                return;
            }
            string certString = "-----BEGIN CERTIFICATE-----\n" +
                                "MIICqjCCAjGgAwIBAgICI1YwCQYHKoZIzj0EATAmMSQwIgYDVQQDDBtUcnVzdGVk\n" +
                                "IFRoaW4gQ2xpZW50IFJvb3QgQ0EwIhcRMTYwMTI0MTU0OTQ1LTA2MDAXDTE2MDQy\n" +
                                "NTIyNDk0NVowYzEwMC4GA1UEAwwnREMgMGRlYzI0MGYtOTI2OS00MDY5LWE2MTYt\n" +
                                "YjJmNTI0ZjA2ZGE0MREwDwYDVQQLDAhEQyBJUFNFQzEcMBoGA1UECgwTVHJ1c3Rl\n" +
                                "ZCBUaGluIENsaWVudDB2MBAGByqGSM49AgEGBSuBBAAiA2IABOB7pZYC24sF5gJm\n" +
                                "OHXhasxmrNYebdtSAiQRgz0M0pIsogsFeTU/W0HTlTOqwDDckphHESAKHVxa6EBL\n" +
                                "d+/8HYZ1AaCmXtG73XpaOyaRr3TipJl2IaJzwuehgDHs0L+qcqOB8TCB7jAwBgYr\n" +
                                "BgEBEAQEJgwkMGRlYzI0MGYtOTI2OS00MDY5LWE2MTYtYjJmNTI0ZjA2ZGE0MCMG\n" +
                                "CisGAQQBjCHbZwEEFQwTNDkwNzUyMjc1NjM3MTE3Mjg5NjAUBgorBgEEAYwh22cC\n" +
                                "BAYMBDIwNTkwCwYDVR0PBAQDAgXgMAkGA1UdEwQCMAAwHQYDVR0OBBYEFGWljaKj\n" +
                                "wiGqW61PgLL/zLxj4iirMB8GA1UdIwQYMBaAFA2FRBtG/dGnl0iXP2uKFwJHmEQI\n" +
                                "MCcGA1UdJQQgMB4GCCsGAQUFBwMCBggrBgEFBQcDAQYIKwYBBQUHAwkwCQYHKoZI\n" +
                                "zj0EAQNoADBlAjAQFP8rMLUxl36u8610LsSCiRG8pP3gjuLaaJMm3tjbVue/TI4C\n" +
                                "z3iL8i96YWK0VxcCMQC7pf6Wk3RhUU2Sg6S9e6CiirFLDyzLkaWxuCnXcOwTvuXT\n" +
                                "HUQSeUCp2Q6ygS5qKyc=\n" +
                                "-----END CERTIFICATE-----";

            string expected = "MIICqjCCAjGgAwIBAgICI1YwCQYHKoZIzj0EATAmMSQwIgYDVQQDDBtUcnVzdGVkIFRoaW4gQ2xp\n" +
                              "ZW50IFJvb3QgQ0EwIhcRMTYwMTI0MTU0OTQ1LTA2MDAXDTE2MDQyNTIyNDk0NVowYzEwMC4GA1UE\n" +
                              "AwwnREMgMGRlYzI0MGYtOTI2OS00MDY5LWE2MTYtYjJmNTI0ZjA2ZGE0MREwDwYDVQQLDAhEQyBJ\n" +
                              "UFNFQzEcMBoGA1UECgwTVHJ1c3RlZCBUaGluIENsaWVudDB2MBAGByqGSM49AgEGBSuBBAAiA2IA\n" +
                              "BOB7pZYC24sF5gJmOHXhasxmrNYebdtSAiQRgz0M0pIsogsFeTU/W0HTlTOqwDDckphHESAKHVxa\n" +
                              "6EBLd+/8HYZ1AaCmXtG73XpaOyaRr3TipJl2IaJzwuehgDHs0L+qcqOB8TCB7jAwBgYrBgEBEAQE\n" +
                              "JgwkMGRlYzI0MGYtOTI2OS00MDY5LWE2MTYtYjJmNTI0ZjA2ZGE0MCMGCisGAQQBjCHbZwEEFQwT\n" +
                              "NDkwNzUyMjc1NjM3MTE3Mjg5NjAUBgorBgEEAYwh22cCBAYMBDIwNTkwCwYDVR0PBAQDAgXgMAkG\n" +
                              "A1UdEwQCMAAwHQYDVR0OBBYEFGWljaKjwiGqW61PgLL/zLxj4iirMB8GA1UdIwQYMBaAFA2FRBtG\n" +
                              "/dGnl0iXP2uKFwJHmEQIMCcGA1UdJQQgMB4GCCsGAQUFBwMCBggrBgEFBQcDAQYIKwYBBQUHAwkw\n" +
                              "CQYHKoZIzj0EAQNoADBlAjAQFP8rMLUxl36u8610LsSCiRG8pP3gjuLaaJMm3tjbVue/TI4Cz3iL\n" +
                              "8i96YWK0VxcCMQC7pf6Wk3RhUU2Sg6S9e6CiirFLDyzLkaWxuCnXcOwTvuXTHUQSeUCp2Q6ygS5q\n" +
                              "Kyc=";

            X509Certificate cert            = FromString(certString);
            IByteBuffer     src             = Unpooled.WrappedBuffer(cert.Export(X509ContentType.Cert));
            IByteBuffer     expectedEncoded = Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes(expected));

            this.TestEncode(src, expectedEncoded);
        }
        public void ClientRequestTrailingHeaders()
        {
            this.BootstrapEnv(1, 1, 1);
            string           text    = "some data";
            IByteBuffer      content = Unpooled.CopiedBuffer(Encoding.UTF8.GetBytes(text));
            IFullHttpRequest request = new DefaultFullHttpRequest(DotNetty.Codecs.Http.HttpVersion.Http11, HttpMethod.Get,
                                                                  "/some/path/resource2", content, true);

            try
            {
                HttpHeaders httpHeaders = request.Headers;
                httpHeaders.SetInt(HttpConversionUtil.ExtensionHeaderNames.StreamId, 3);
                httpHeaders.SetInt(HttpHeaderNames.ContentLength, text.Length);
                httpHeaders.SetShort(HttpConversionUtil.ExtensionHeaderNames.StreamWeight, 16);
                HttpHeaders trailingHeaders = request.TrailingHeaders;
                trailingHeaders.Set(AsciiString.Of("Foo"), AsciiString.Of("goo"));
                trailingHeaders.Set(AsciiString.Of("fOo2"), AsciiString.Of("goo2"));
                trailingHeaders.Add(AsciiString.Of("foO2"), AsciiString.Of("goo3"));
                var http2Headers = new DefaultHttp2Headers()
                {
                    Method = new AsciiString("GET"),
                    Path   = new AsciiString("/some/path/resource2"),
                };
                IHttp2Headers http2Headers2 = new DefaultHttp2Headers();
                http2Headers2.Set(new AsciiString("foo"), new AsciiString("goo"));
                http2Headers2.Set(new AsciiString("foo2"), new AsciiString("goo2"));
                http2Headers2.Add(new AsciiString("foo2"), new AsciiString("goo3"));
                Http2TestUtil.RunInChannel(this.clientChannel, () =>
                {
                    this.clientHandler.Encoder.WriteHeadersAsync(this.CtxClient(), 3, http2Headers, 0, false, this.NewPromiseClient());
                    this.clientHandler.Encoder.WriteDataAsync(this.CtxClient(), 3, content.RetainedDuplicate(), 0, false, this.NewPromiseClient());
                    this.clientHandler.Encoder.WriteHeadersAsync(this.CtxClient(), 3, http2Headers2, 0, true, this.NewPromiseClient());
                    this.clientChannel.Flush();
                });
                this.AwaitRequests();
                var requestCaptor = new ArgumentCaptor <IFullHttpMessage>();
                this.serverListener.Verify(x => x.MessageReceived(It.Is <IHttpObject>(v => requestCaptor.Capture((IFullHttpMessage)v))));
                this.capturedRequests = requestCaptor.GetAllValues();
                Assert.Equal(request, (IFullHttpRequest)this.capturedRequests[0]);
            }
            finally
            {
                request.Release();
            }
        }
Пример #26
0
 public static IByteBuffer GetContent(string webSocketLocation) => Unpooled.CopiedBuffer(
     "<html><head><title>Web Socket Test</title></head>" + Newline +
     "<body>" + Newline +
     "<script type=\"text/javascript\">" + Newline +
     "var socket;" + Newline +
     "if (!window.WebSocket) {" + Newline +
     "  window.WebSocket = window.MozWebSocket;" + Newline +
     '}' + Newline +
     "if (window.WebSocket) {" + Newline +
     "  socket = new WebSocket(\"" + webSocketLocation + "\");" + Newline +
     "  socket.onmessage = function(event) {" + Newline +
     "    var ta = document.getElementById('responseText');" + Newline +
     "    ta.value = ta.value + '\\n' + event.data" + Newline +
     "  };" + Newline +
     "  socket.onopen = function(event) {" + Newline +
     "    var ta = document.getElementById('responseText');" + Newline +
     "    ta.value = \"Web Socket opened!\";" + Newline +
     "  };" + Newline +
     "  socket.onclose = function(event) {" + Newline +
     "    var ta = document.getElementById('responseText');" + Newline +
     "    ta.value = ta.value + \"Web Socket closed\"; " + Newline +
     "  };" + Newline +
     "} else {" + Newline +
     "  alert(\"Your browser does not support Web Socket.\");" + Newline +
     '}' + Newline +
     Newline +
     "function send(message) {" + Newline +
     "  if (!window.WebSocket) { return; }" + Newline +
     "  if (socket.readyState == WebSocket.OPEN) {" + Newline +
     "    socket.send(message);" + Newline +
     "  } else {" + Newline +
     "    alert(\"The socket is not open.\");" + Newline +
     "  }" + Newline +
     '}' + Newline +
     "</script>" + Newline +
     "<form onsubmit=\"return false;\">" + Newline +
     "<input type=\"text\" name=\"message\" value=\"Hello, World!\"/>" +
     "<input type=\"button\" value=\"Send Web Socket Data\"" + Newline +
     "       onclick=\"send(this.form.message.value)\" />" + Newline +
     "<h3>Output</h3>" + Newline +
     "<textarea id=\"responseText\" style=\"width:500px;height:300px;\"></textarea>" + Newline +
     "</form>" + Newline +
     "</body>" + Newline +
     "</html>" + Newline,
     Encoding.ASCII);
Пример #27
0
        public void TestRandomDecode()
        {
            int minLength = 1;
            var rand      = new Random();
            int maxLength = rand.Next(1000, 3000);

            for (int i = 0; i < 16; ++i)
            {
                var bytes = new byte[rand.Next(minLength, maxLength)];
                rand.NextBytes(bytes);

                string      base64String    = Convert.ToBase64String(bytes);
                IByteBuffer buff            = Unpooled.CopiedBuffer(Encoding.ASCII.GetBytes(base64String));
                IByteBuffer expectedDecoded = Unpooled.CopiedBuffer(Convert.FromBase64String(base64String));

                TestDecode(buff, expectedDecoded);
            }
        }
Пример #28
0
 public override void ChannelRead(IChannelHandlerContext ctx, object msg)
 {
     if (msg is IHttp2HeadersFrame headersFrame && headersFrame.IsEndStream)
     {
         _executorService.Schedule(() =>
         {
             ctx.WriteAndFlushAsync(new DefaultHttp2HeadersFrame(new DefaultHttp2Headers(), false))
             .ContinueWith(t =>
             {
                 ctx.WriteAsync(new DefaultHttp2DataFrame(
                                    Unpooled.CopiedBuffer("Hello World", Encoding.ASCII),
                                    true));
                 ctx.Channel.EventLoop.Execute(() => ctx.Flush());
             }, TaskContinuationOptions.ExecuteSynchronously);
         }, TimeSpan.FromMilliseconds(500));
     }
     ReferenceCountUtil.Release(msg);
 }
Пример #29
0
        public async void SendMessage(DiscoveryMessage discoveryMessage)
        {
            byte[] message;

            try
            {
                _logger.Info($"Sending message: {discoveryMessage}");
                message = Seserialize(discoveryMessage);
            }
            catch (Exception e)
            {
                _logger.Error($"Error during serialization of the message: {discoveryMessage}", e);
                return;
            }

            IAddressedEnvelope <IByteBuffer> packet = new DatagramPacket(Unpooled.CopiedBuffer(message), discoveryMessage.FarAddress);
            await _channel.WriteAndFlushAsync(packet);
        }
Пример #30
0
        public void DecodeLastEmptyBuffer()
        {
            EmbeddedChannel channel = new EmbeddedChannel(new ActionByteToMessageDecoder((IChannelHandlerContext context, IByteBuffer input, List <object> output) =>
            {
                int readable = input.ReadableBytes;
                Assert.True(readable > 0);
                output.Add(input.ReadBytes(readable));
            }));

            byte[] bytes = new byte[1024];
            s_randomNumberGeneratorCsp.GetBytes(bytes);

            Assert.True(channel.WriteInbound(Unpooled.CopiedBuffer(bytes)));
            AssertEx.Equal(Unpooled.WrappedBuffer(bytes), channel.ReadInbound <IByteBuffer>(), true);
            Assert.Null(channel.ReadInbound <IByteBuffer>());
            Assert.False(channel.Finish());
            Assert.Null(channel.ReadInbound <IByteBuffer>());
        }