Пример #1
0
        public async Task TlsRead(int[] frameLengths, bool isClient, IWriteStrategy writeStrategy, SslProtocols protocol)
        {
            this.Output.WriteLine("frameLengths: " + string.Join(", ", frameLengths));

            var writeTasks = new List <Task>();
            var pair       = await SetupStreamAndChannelAsync(isClient, writeStrategy, protocol, writeTasks);

            EmbeddedChannel ch           = pair.Item1;
            SslStream       driverStream = pair.Item2;

            int         randomSeed     = Environment.TickCount;
            var         random         = new Random(randomSeed);
            IByteBuffer expectedBuffer = Unpooled.Buffer(16 * 1024);

            foreach (int len in frameLengths)
            {
                var data = new byte[len];
                random.NextBytes(data);
                expectedBuffer.WriteBytes(data);
                await Task.Run(() => driverStream.Write(data)).WithTimeout(TimeSpan.FromSeconds(5));
            }
            await Task.WhenAll(writeTasks).WithTimeout(TimeSpan.FromSeconds(5));

            IByteBuffer finalReadBuffer = Unpooled.Buffer(16 * 1024);

            await ReadOutboundAsync(() => ch.ReadInbound <IByteBuffer>(), expectedBuffer.ReadableBytes, finalReadBuffer, TestTimeout);

            Assert.True(ByteBufferUtil.Equals(expectedBuffer, finalReadBuffer), $"---Expected:\n{ByteBufferUtil.PrettyHexDump(expectedBuffer)}\n---Actual:\n{ByteBufferUtil.PrettyHexDump(finalReadBuffer)}");
        }
        protected override void Decode(IChannelHandlerContext ctx, IByteBuffer input, List <object> output)
        {
            int prefaceLength = CONNECTION_PREFACE.ReadableBytes;
            int bytesRead     = Math.Min(input.ReadableBytes, prefaceLength);

            var pipeline = ctx.Pipeline;

            if (!ByteBufferUtil.Equals(CONNECTION_PREFACE, CONNECTION_PREFACE.ReaderIndex,
                                       input, input.ReaderIndex, bytesRead))
            {
                _ = pipeline.Remove(this);
            }
            else if (0u >= (uint)(bytesRead - prefaceLength))
            {
                // Full h2 preface match, removed source codec, using http2 codec to handle
                // following network traffic
                _ = pipeline
                    .Remove(_httpServerCodec)
                    .Remove(_httpServerUpgradeHandler);

                _ = pipeline.AddAfter(ctx.Name, null, _http2ServerHandler);
                _ = pipeline.Remove(this);

                _ = ctx.FireUserEventTriggered(PriorKnowledgeUpgradeEvent.Instance);
            }
        }
Пример #3
0
        public async Task TlsWrite(int[] frameLengths, bool isClient, SslProtocols protocol, string targetHost)
        {
            this.Output.WriteLine("frameLengths: " + string.Join(", ", frameLengths));
            this.Output.WriteLine($"protocol: {protocol}");
            this.Output.WriteLine($"targetHost: {targetHost}");

            var writeStrategy = new AsIsWriteStrategy();
            var executor      = new DefaultEventExecutor();

            try
            {
                var writeTasks = new List <Task>();
                var pair       = await SetupStreamAndChannelAsync(isClient, executor, writeStrategy, protocol, writeTasks, targetHost);

                EmbeddedChannel ch           = pair.Item1;
                SslStream       driverStream = pair.Item2;

                int         randomSeed     = Environment.TickCount;
                var         random         = new Random(randomSeed);
                IByteBuffer expectedBuffer = Unpooled.Buffer(16 * 1024);
                foreach (IEnumerable <int> lengths in frameLengths.Split(x => x < 0))
                {
                    ch.WriteOutbound(lengths.Select(len =>
                    {
                        var data = new byte[len];
                        random.NextBytes(data);
                        expectedBuffer.WriteBytes(data);
                        return((object)Unpooled.WrappedBuffer(data));
                    }).ToArray());
                }

                IByteBuffer finalReadBuffer = Unpooled.Buffer(16 * 1024);
                var         readBuffer      = new byte[16 * 1024 * 10];
                await ReadOutboundAsync(
                    async() =>
                {
                    int read = await driverStream.ReadAsync(readBuffer, 0, readBuffer.Length);
                    return(Unpooled.WrappedBuffer(readBuffer, 0, read));
                },
                    expectedBuffer.ReadableBytes, finalReadBuffer, TestTimeout);

                Assert.True(ByteBufferUtil.Equals(expectedBuffer, finalReadBuffer), $"---Expected:\n{ByteBufferUtil.PrettyHexDump(expectedBuffer)}\n---Actual:\n{ByteBufferUtil.PrettyHexDump(finalReadBuffer)}");

                if (!isClient)
                {
                    // check if snihandler got replaced with tls handler
                    Assert.Null(ch.Pipeline.Get <SniHandler>());
                    Assert.NotNull(ch.Pipeline.Get <TlsHandler>());
                }

                driverStream.Dispose();
                Assert.False(ch.Finish());
            }
            finally
            {
                await executor.ShutdownGracefullyAsync(TimeSpan.Zero, TimeSpan.Zero);
            }
        }
Пример #4
0
        public async Task TlsWrite(int[] frameLengths, bool isClient, SslProtocols serverProtocol, SslProtocols clientProtocol)
        {
            this.Output.WriteLine($"frameLengths: {string.Join(", ", frameLengths)}");
            this.Output.WriteLine($"isClient: {isClient}");
            this.Output.WriteLine($"serverProtocol: {serverProtocol}");
            this.Output.WriteLine($"clientProtocol: {clientProtocol}");

            var writeStrategy = new AsIsWriteStrategy();

            this.Output.WriteLine($"writeStrategy: {writeStrategy}");

            var executor = new SingleThreadEventExecutor("test executor", TimeSpan.FromMilliseconds(10));

            try
            {
                var writeTasks = new List <Task>();
                var pair       = await SetupStreamAndChannelAsync(isClient, executor, writeStrategy, serverProtocol, clientProtocol, writeTasks);

                EmbeddedChannel ch           = pair.Item1;
                SslStream       driverStream = pair.Item2;

                int         randomSeed     = Environment.TickCount;
                var         random         = new Random(randomSeed);
                IByteBuffer expectedBuffer = Unpooled.Buffer(16 * 1024);
                foreach (IEnumerable <int> lengths in frameLengths.Split(x => x < 0))
                {
                    ch.WriteOutbound(lengths.Select(len =>
                    {
                        var data = new byte[len];
                        random.NextBytes(data);
                        expectedBuffer.WriteBytes(data);
                        return((object)Unpooled.WrappedBuffer(data));
                    }).ToArray());
                }

                IByteBuffer finalReadBuffer = Unpooled.Buffer(16 * 1024);
                var         readBuffer      = new byte[16 * 1024 * 10];
                await ReadOutboundAsync(
                    async() =>
                {
                    int read = await driverStream.ReadAsync(readBuffer, 0, readBuffer.Length);
                    return(Unpooled.WrappedBuffer(readBuffer, 0, read));
                },
                    expectedBuffer.ReadableBytes, finalReadBuffer, TestTimeout);

                bool isEqual = ByteBufferUtil.Equals(expectedBuffer, finalReadBuffer);
                if (!isEqual)
                {
                    Assert.True(isEqual, $"---Expected:\n{ByteBufferUtil.PrettyHexDump(expectedBuffer)}\n---Actual:\n{ByteBufferUtil.PrettyHexDump(finalReadBuffer)}");
                }
                driverStream.Dispose();
                Assert.False(ch.Finish());
            }
            finally
            {
                await executor.ShutdownGracefullyAsync(TimeSpan.Zero, TimeSpan.Zero);
            }
        }
Пример #5
0
        public void DiscardReadBytes()
        {
            this.buffer.SetWriterIndex(0);
            for (int i = 0; i < this.buffer.Capacity; i += 4)
            {
                this.buffer.SetInt32(i, i, BitConverter.IsLittleEndian);
                this.buffer.SetWriterIndex(i + 4);
            }
            IArrayBuffer <byte> copy = Unpooled.CopiedBuffer(this.buffer);

            // Make sure there's no effect if called when readerIndex is 0.
            this.buffer.SetReaderIndex(Capacity / 4);
            this.buffer.MarkReaderIndex();
            this.buffer.SetWriterIndex(Capacity / 3);
            this.buffer.MarkWriterIndex();
            this.buffer.SetReaderIndex(0);
            this.buffer.SetWriterIndex(Capacity / 2);
            this.buffer.DiscardReadCount();

            Assert.Equal(0, this.buffer.ReaderIndex);
            Assert.Equal(Capacity / 2, this.buffer.WriterIndex);
            Assert.True(ByteBufferUtil.Equals(copy.Slice(0, Capacity / 2), this.buffer.Slice(0, Capacity / 2)));
            this.buffer.ResetReaderIndex();
            Assert.Equal(Capacity / 4, this.buffer.ReaderIndex);
            this.buffer.ResetWriterIndex();
            Assert.Equal(Capacity / 3, this.buffer.WriterIndex);

            // Make sure bytes after writerIndex is not copied.
            this.buffer.SetReaderIndex(1);
            this.buffer.SetWriterIndex(Capacity / 2);
            this.buffer.DiscardReadCount();

            Assert.Equal(0, this.buffer.ReaderIndex);
            Assert.Equal(Capacity / 2 - 1, this.buffer.WriterIndex);
            Assert.True(ByteBufferUtil.Equals(copy.Slice(1, Capacity / 2 - 1), this.buffer.Slice(0, Capacity / 2 - 1)));

            if (this.DiscardReadBytesDoesNotMoveWritableBytes())
            {
                // If writable bytes were copied, the test should fail to avoid unnecessary memory bandwidth consumption.
                Assert.False(ByteBufferUtil.Equals(copy.Slice(Capacity / 2, Capacity / 2), this.buffer.Slice(Capacity / 2 - 1, Capacity / 2)));
            }
            else
            {
                Assert.True(ByteBufferUtil.Equals(copy.Slice(Capacity / 2, Capacity / 2), this.buffer.Slice(Capacity / 2 - 1, Capacity / 2)));
            }

            // Marks also should be relocated.
            this.buffer.ResetReaderIndex();
            Assert.Equal(Capacity / 4 - 1, this.buffer.ReaderIndex);
            this.buffer.ResetWriterIndex();
            Assert.Equal(Capacity / 3 - 1, this.buffer.WriterIndex);

            copy.Release();
        }
Пример #6
0
        public async Task TlsRead(int[] frameLengths, bool isClient, IWriteStrategy writeStrategy, SslProtocols protocol, string targetHost)
        {
            this.Output.WriteLine($"frameLengths: {string.Join(", ", frameLengths)}");
            this.Output.WriteLine($"writeStrategy: {writeStrategy}");
            this.Output.WriteLine($"protocol: {protocol}");
            this.Output.WriteLine($"targetHost: {targetHost}");

            var executor = new SingleThreadEventExecutor("test executor", TimeSpan.FromMilliseconds(10));

            try
            {
                var writeTasks = new List <Task>();
                var pair       = await SetupStreamAndChannelAsync(isClient, executor, writeStrategy, protocol, writeTasks, targetHost).WithTimeout(TimeSpan.FromSeconds(10));

                EmbeddedChannel ch           = pair.Item1;
                SslStream       driverStream = pair.Item2;

                int         randomSeed     = Environment.TickCount;
                var         random         = new Random(randomSeed);
                IByteBuffer expectedBuffer = Unpooled.Buffer(16 * 1024);
                foreach (int len in frameLengths)
                {
                    var data = new byte[len];
                    random.NextBytes(data);
                    expectedBuffer.WriteBytes(data);
                    await driverStream.WriteAsync(data, 0, data.Length).WithTimeout(TimeSpan.FromSeconds(5));
                }
                await Task.WhenAll(writeTasks).WithTimeout(TimeSpan.FromSeconds(5));

                IByteBuffer finalReadBuffer = Unpooled.Buffer(16 * 1024);
#pragma warning disable CS1998 // 异步方法缺少 "await" 运算符,将以同步方式运行
                await ReadOutboundAsync(async() => ch.ReadInbound <IByteBuffer>(), expectedBuffer.ReadableBytes, finalReadBuffer, TestTimeout);

#pragma warning restore CS1998 // 异步方法缺少 "await" 运算符,将以同步方式运行
                Assert.True(ByteBufferUtil.Equals(expectedBuffer, finalReadBuffer), $"---Expected:\n{ByteBufferUtil.PrettyHexDump(expectedBuffer)}\n---Actual:\n{ByteBufferUtil.PrettyHexDump(finalReadBuffer)}");

                if (!isClient)
                {
                    // check if snihandler got replaced with tls handler
                    Assert.Null(ch.Pipeline.Get <SniHandler>());
                    Assert.NotNull(ch.Pipeline.Get <TlsHandler>());
                }

                driverStream.Dispose();
                Assert.False(ch.Finish());
            }
            finally
            {
                await executor.ShutdownGracefullyAsync(TimeSpan.Zero, TimeSpan.Zero);
            }
        }
Пример #7
0
        public void SetContentFromStream()
        {
            // definedSize=0
            TestHttpData test       = new TestHttpData("test", Encoding.UTF8, 0);
            string       contentStr = "foo_test";
            var          buf        = Unpooled.WrappedBuffer(Encoding.UTF8.GetBytes(contentStr));

            buf.MarkReaderIndex();
            var bs = new ByteBufferStream(buf);

            try
            {
                test.SetContent(bs);
                Assert.False(buf.IsReadable());
                Assert.Equal(test.GetString(Encoding.UTF8), contentStr);
                buf.ResetReaderIndex();
                Assert.True(ByteBufferUtil.Equals(buf, test.GetByteBuffer()));
            }
            finally
            {
                bs.Close();
            }

            var random = new Random();

            for (int i = 0; i < 20; i++)
            {
                // Generate input data bytes.
                int size  = random.Next(short.MaxValue);
                var bytes = new byte[size];

                random.NextBytes(bytes);

                // Generate parsed HTTP data block.
                var httpData = new TestHttpData("name", Encoding.UTF8, 0);

                httpData.SetContent(new MemoryStream(bytes));

                // Validate stored data.
                IByteBuffer buffer = httpData.GetByteBuffer();

                Assert.Equal(0, buffer.ReaderIndex);
                Assert.Equal(bytes.Length, buffer.WriterIndex);

                var data = new byte[bytes.Length];
                buffer.GetBytes(buffer.ReaderIndex, data);

                Assert.True(data.AsSpan().SequenceEqual(bytes));
            }
        }
Пример #8
0
        public void EqualsBufferSubsections()
        {
            var b1   = new byte[128];
            var b2   = new byte[256];
            var rand = new Random();

            rand.NextBytes(b1);
            rand.NextBytes(b2);
            int iB1    = b1.Length / 2;
            int iB2    = iB1 + b1.Length;
            int length = b1.Length - iB1;

            Array.Copy(b1, iB1, b2, iB2, length);
            Assert.True(ByteBufferUtil.Equals(Unpooled.WrappedBuffer(b1), iB1, Unpooled.WrappedBuffer(b2), iB2, length));
        }
Пример #9
0
        public void NotEqualsBufferUnderflow()
        {
            var b1   = new byte[8];
            var b2   = new byte[16];
            var rand = new Random();

            rand.NextBytes(b1);
            rand.NextBytes(b2);
            int iB1    = b1.Length / 2;
            int iB2    = iB1 + b1.Length;
            int length = b1.Length - iB1;

            Array.Copy(b1, iB1, b2, iB2, length - 1);
            Assert.Throws <ArgumentException>(() => ByteBufferUtil.Equals(Unpooled.WrappedBuffer(b1), iB1, Unpooled.WrappedBuffer(b2), iB2, -1));
        }
Пример #10
0
        public void TestConnectMessage(string clientId, bool cleanSession, int keepAlive, string userName,
                                       string password, string willTopicName, byte[] willMessage, QualityOfService?willQos, bool willRetain)
        {
            var packet = new ConnectPacket();

            packet.ClientId           = clientId;
            packet.CleanSession       = cleanSession;
            packet.KeepAliveInSeconds = keepAlive;
            if (userName != null)
            {
                packet.Username = userName;
                if (password != null)
                {
                    packet.Password = password;
                }
            }
            if (willTopicName != null)
            {
                packet.WillTopicName        = willTopicName;
                packet.WillMessage          = Unpooled.WrappedBuffer(willMessage);
                packet.WillQualityOfService = willQos ?? QualityOfService.AtMostOnce;
                packet.WillRetain           = willRetain;
            }

            ConnectPacket recoded = this.RecodePacket(packet, true, true);

            this.contextMock.Verify(x => x.FireChannelRead(It.IsAny <ConnectPacket>()), Times.Once);
            Assert.Equal(packet.ClientId, recoded.ClientId);
            Assert.Equal(packet.CleanSession, recoded.CleanSession);
            Assert.Equal(packet.KeepAliveInSeconds, recoded.KeepAliveInSeconds);
            Assert.Equal(packet.HasUsername, recoded.HasUsername);
            if (packet.HasUsername)
            {
                Assert.Equal(packet.Username, recoded.Username);
            }
            Assert.Equal(packet.HasPassword, recoded.HasPassword);
            if (packet.HasPassword)
            {
                Assert.Equal(packet.Password, recoded.Password);
            }
            if (packet.HasWill)
            {
                Assert.Equal(packet.WillTopicName, recoded.WillTopicName);
                Assert.True(ByteBufferUtil.Equals(Unpooled.WrappedBuffer(willMessage), recoded.WillMessage));
                Assert.Equal(packet.WillQualityOfService, recoded.WillQualityOfService);
                Assert.Equal(packet.WillRetain, recoded.WillRetain);
            }
        }
Пример #11
0
        public void EmptyFrameCompression()
        {
            EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerMessageDeflateEncoder(9, 15, false));

            TextWebSocketFrame emptyFrame = new TextWebSocketFrame("");

            Assert.True(encoderChannel.WriteOutbound(emptyFrame));
            var emptyDeflateFrame = encoderChannel.ReadOutbound <TextWebSocketFrame>();

            Assert.Equal(WebSocketRsv.Rsv1, emptyDeflateFrame.Rsv);
            Assert.True(ByteBufferUtil.Equals(DeflateDecoder.EmptyDeflateBlock, emptyDeflateFrame.Content));
            // Unreleasable buffer
            Assert.False(emptyDeflateFrame.Release());

            Assert.False(encoderChannel.Finish());
        }
Пример #12
0
        public void NotEqualsBufferOverflow()
        {
            var b1   = new byte[8];
            var b2   = new byte[16];
            var rand = new Random();

            rand.NextBytes(b1);
            rand.NextBytes(b2);
            int iB1    = b1.Length / 2;
            int iB2    = iB1 + b1.Length;
            int length = b1.Length - iB1;

            Array.Copy(b1, iB1, b2, iB2, length - 1);
            Assert.False(ByteBufferUtil.Equals(Unpooled.WrappedBuffer(b1), iB1, Unpooled.WrappedBuffer(b2), iB2,
                                               Math.Max(b1.Length, b2.Length) * 2));
        }
Пример #13
0
        public void BufferEquals()
        {
            Assert.False(this.buffer.Equals(null));
            Assert.False(this.buffer.Equals(new object()));

            var value = new byte[32];

            this.buffer.SetIndex(0, value.Length);
            this.random.NextBytes(value);
            this.buffer.Set(0, value);

            Assert.True(ByteBufferUtil.Equals(this.buffer, Unpooled.WrappedBuffer(value)));

            value[0]++;
            Assert.False(ByteBufferUtil.Equals(this.buffer, Unpooled.WrappedBuffer(value)));
            Assert.False(this.buffer.Equals(Unpooled.WrappedBuffer(value)));
        }
        public async Task TlsRead(int[] frameLengths, bool isClient, IWriteStrategy writeStrategy, SslProtocols serverProtocol, SslProtocols clientProtocol)
        {
            this.Output.WriteLine($"frameLengths: {string.Join(", ", frameLengths)}");
            this.Output.WriteLine($"isClient: {isClient}");
            this.Output.WriteLine($"writeStrategy: {writeStrategy}");
            this.Output.WriteLine($"serverProtocol: {serverProtocol}");
            this.Output.WriteLine($"clientProtocol: {clientProtocol}");

            var executor = new SingleThreadEventExecutor("test executor", TimeSpan.FromMilliseconds(10));

            try
            {
                var writeTasks = new List <Task>();
                var pair       = await SetupStreamAndChannelAsync(isClient, executor, writeStrategy, serverProtocol, clientProtocol, writeTasks).WithTimeout(TimeSpan.FromSeconds(10));

                EmbeddedChannel ch           = pair.Item1;
                SslStream       driverStream = pair.Item2;

                int         randomSeed     = Environment.TickCount;
                var         random         = new Random(randomSeed);
                IByteBuffer expectedBuffer = Unpooled.Buffer(16 * 1024);
                foreach (int len in frameLengths)
                {
                    var data = new byte[len];
                    random.NextBytes(data);
                    expectedBuffer.WriteBytes(data);
                    await driverStream.WriteAsync(data, 0, data.Length).WithTimeout(TimeSpan.FromSeconds(5));
                }
                await Task.WhenAll(writeTasks).WithTimeout(TimeSpan.FromSeconds(5));

                IByteBuffer finalReadBuffer = Unpooled.Buffer(16 * 1024);
                await ReadOutboundAsync(async() => ch.ReadInbound <IByteBuffer>(), expectedBuffer.ReadableBytes, finalReadBuffer, TestTimeout);

                bool isEqual = ByteBufferUtil.Equals(expectedBuffer, finalReadBuffer);
                if (!isEqual)
                {
                    Assert.True(isEqual, $"---Expected:\n{ByteBufferUtil.PrettyHexDump(expectedBuffer)}\n---Actual:\n{ByteBufferUtil.PrettyHexDump(finalReadBuffer)}");
                }
                driverStream.Dispose();
                Assert.False(ch.Finish());
            }
            finally
            {
                await executor.ShutdownGracefullyAsync(TimeSpan.Zero, TimeSpan.Zero);
            }
        }
Пример #15
0
        public void NotEqualsBufferSubsections()
        {
            var b1   = new byte[50];
            var b2   = new byte[256];
            var rand = new Random();

            rand.NextBytes(b1);
            rand.NextBytes(b2);
            int iB1    = b1.Length / 2;
            int iB2    = iB1 + b1.Length;
            int length = b1.Length - iB1;

            Array.Copy(b1, iB1, b2, iB2, length);
            // Randomly pick an index in the range that will be compared and make the value at that index differ between
            // the 2 arrays.
            int diffIndex = GetRandom(rand, iB1, iB1 + length - 1);

            ++b1[diffIndex];
            Assert.False(ByteBufferUtil.Equals(Unpooled.WrappedBuffer(b1), iB1, Unpooled.WrappedBuffer(b2), iB2, length));
        }
        public void DiscardReadBytes3()
        {
            IByteBuffer a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            IByteBuffer b = Unpooled.WrappedBuffer(
                Unpooled.WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 0, 5),
                Unpooled.WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, 5, 5));

            a.SkipBytes(6);
            a.MarkReaderIndex();
            b.SkipBytes(6);
            b.MarkReaderIndex();
            Assert.Equal(a.ReaderIndex, b.ReaderIndex);
            a.SetReaderIndex(a.ReaderIndex - 1);
            b.SetReaderIndex(b.ReaderIndex - 1);
            Assert.Equal(a.ReaderIndex, b.ReaderIndex);
            a.SetWriterIndex(a.WriterIndex - 1);
            a.MarkWriterIndex();
            b.SetWriterIndex(b.WriterIndex - 1);
            b.MarkWriterIndex();
            Assert.Equal(a.WriterIndex, b.WriterIndex);
            a.SetWriterIndex(a.WriterIndex + 1);
            b.SetWriterIndex(b.WriterIndex + 1);
            Assert.Equal(a.WriterIndex, b.WriterIndex);
            Assert.True(ByteBufferUtil.Equals(a, b));
            // now discard
            a.DiscardReadBytes();
            b.DiscardReadBytes();
            Assert.Equal(a.ReaderIndex, b.ReaderIndex);
            Assert.Equal(a.WriterIndex, b.WriterIndex);
            Assert.True(ByteBufferUtil.Equals(a, b));
            a.ResetReaderIndex();
            b.ResetReaderIndex();
            Assert.Equal(a.ReaderIndex, b.ReaderIndex);
            a.ResetWriterIndex();
            b.ResetWriterIndex();
            Assert.Equal(a.WriterIndex, b.WriterIndex);
            Assert.True(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();
        }
Пример #17
0
        public void TestPublishMessage(QualityOfService qos, bool dup, bool retain, int packetId, string topicName, byte[] payload)
        {
            var packet = new PublishPacket(qos, dup, retain);

            packet.TopicName = topicName;
            if (qos > QualityOfService.AtMostOnce)
            {
                packet.PacketId = packetId;
            }
            packet.Payload = payload == null ? null : Unpooled.WrappedBuffer(payload);

            PublishPacket recoded = this.RecodePacket(packet, false, true);

            this.contextMock.Verify(x => x.FireChannelRead(It.IsAny <PublishPacket>()), Times.Once);
            Assert.Equal(packet.TopicName, recoded.TopicName);
            if (packet.QualityOfService > QualityOfService.AtMostOnce)
            {
                Assert.Equal(packet.PacketId, recoded.PacketId);
            }
            Assert.True(ByteBufferUtil.Equals(payload == null ? Unpooled.Empty : Unpooled.WrappedBuffer(payload), recoded.Payload));
        }
        public async Task WriteBytesAsyncPartialWrite()
        {
            const int CopyLength     = 200 * 1024;
            const int SourceLength   = 300 * 1024;
            const int BufferCapacity = 400 * 1024;

            var bytes  = new byte[SourceLength];
            var random = new Random(Guid.NewGuid().GetHashCode());

            random.NextBytes(bytes);

            IByteBuffer buffer             = Unpooled.Buffer(BufferCapacity);
            int         initialWriterIndex = buffer.WriterIndex;

            using (var stream = new PortionedMemoryStream(bytes, Enumerable.Repeat(1, int.MaxValue).Select(_ => random.Next(1, 10240))))
            {
                await buffer.WriteBytesAsync(stream, CopyLength);
            }
            Assert.Equal(CopyLength, buffer.WriterIndex - initialWriterIndex);
            Assert.True(ByteBufferUtil.Equals(Unpooled.WrappedBuffer(bytes.Slice(0, CopyLength)), buffer));
        }
Пример #19
0
        public async Task TlsWrite(int[] frameLengths, bool isClient, SslProtocols protocol)
        {
            this.Output.WriteLine("frameLengths: " + string.Join(", ", frameLengths));

            var writeStrategy = new AsIsWriteStrategy();

            var writeTasks = new List <Task>();
            var pair       = await SetupStreamAndChannelAsync(isClient, writeStrategy, protocol, writeTasks);

            EmbeddedChannel ch           = pair.Item1;
            SslStream       driverStream = pair.Item2;

            int         randomSeed     = Environment.TickCount;
            var         random         = new Random(randomSeed);
            IByteBuffer expectedBuffer = Unpooled.Buffer(16 * 1024);

            foreach (IEnumerable <int> lengths in frameLengths.Split(x => x < 0))
            {
                ch.WriteOutbound(lengths.Select(len =>
                {
                    var data = new byte[len];
                    random.NextBytes(data);
                    expectedBuffer.WriteBytes(data);
                    return((object)Unpooled.WrappedBuffer(data));
                }).ToArray());
            }

            IByteBuffer finalReadBuffer = Unpooled.Buffer(16 * 1024);
            var         readBuffer      = new byte[16 * 1024 * 10];

            await ReadOutboundAsync(
                () =>
            {
                int read = driverStream.Read(readBuffer, 0, readBuffer.Length);
                return(Unpooled.WrappedBuffer(readBuffer, 0, read));
            },
                expectedBuffer.ReadableBytes, finalReadBuffer, TestTimeout);

            Assert.True(ByteBufferUtil.Equals(expectedBuffer, finalReadBuffer), $"---Expected:\n{ByteBufferUtil.PrettyHexDump(expectedBuffer)}\n---Actual:\n{ByteBufferUtil.PrettyHexDump(finalReadBuffer)}");
        }
Пример #20
0
        public void Equals()
        {
            // Different length.
            IByteBuffer a = WrappedBuffer(new byte[] { 1 });
            IByteBuffer b = WrappedBuffer(new byte[] { 1, 2 });

            Assert.False(ByteBufferUtil.Equals(a, b));
            a.Release();
            b.Release();

            // Same content, same firstIndex, short length.
            a = WrappedBuffer(new byte[] { 1, 2, 3 });
            b = WrappedBuffer(new byte[] { 1, 2, 3 });
            Assert.True(ByteBufferUtil.Equals(a, b));
            a.Release();
            b.Release();

            // Same content, different firstIndex, short length.
            a = WrappedBuffer(new byte[] { 1, 2, 3 });
            b = WrappedBuffer(new byte[] { 0, 1, 2, 3, 4 }, 1, 3);
            Assert.True(ByteBufferUtil.Equals(a, b));
            a.Release();
            b.Release();

            // Different content, same firstIndex, short length.
            a = WrappedBuffer(new byte[] { 1, 2, 3 });
            b = WrappedBuffer(new byte[] { 1, 2, 4 });
            Assert.False(ByteBufferUtil.Equals(a, b));
            a.Release();
            b.Release();

            // Different content, different firstIndex, short length.
            a = WrappedBuffer(new byte[] { 1, 2, 3 });
            b = WrappedBuffer(new byte[] { 0, 1, 2, 4, 5 }, 1, 3);
            Assert.False(ByteBufferUtil.Equals(a, b));
            a.Release();
            b.Release();

            // Same content, same firstIndex, long length.
            a = WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            b = WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            Assert.True(ByteBufferUtil.Equals(a, b));
            a.Release();
            b.Release();

            // Same content, different firstIndex, long length.
            a = WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            b = WrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, 1, 10);
            Assert.True(ByteBufferUtil.Equals(a, b));
            a.Release();
            b.Release();

            // Different content, same firstIndex, long length.
            a = WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            b = WrappedBuffer(new byte[] { 1, 2, 3, 4, 6, 7, 8, 5, 9, 10 });
            Assert.False(ByteBufferUtil.Equals(a, b));
            a.Release();
            b.Release();

            // Different content, different firstIndex, long length.
            a = WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            b = WrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 6, 7, 8, 5, 9, 10, 11 }, 1, 10);
            Assert.False(ByteBufferUtil.Equals(a, b));
            a.Release();
            b.Release();
        }
        public void WrittenBuffersEquals()
        {
            //XXX Same tests than testEquals with written AggregateChannelBuffers
            // Different length.
            IByteBuffer a = Unpooled.WrappedBuffer(new byte[] { 1 });
            IByteBuffer b = Unpooled.WrappedBuffer(Unpooled.WrappedBuffer(new byte[] { 1 }, new byte[1]));
            IByteBuffer c = Unpooled.WrappedBuffer(new byte[] { 2 });

            // to enable writeBytes
            b.SetWriterIndex(b.WriterIndex - 1);
            b.WriteBytes(c);
            Assert.False(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();
            c.Release();

            // Same content, same firstIndex, short length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3 });
            b = Unpooled.WrappedBuffer(Unpooled.WrappedBuffer(new byte[] { 1 }, new byte[2]));
            c = Unpooled.WrappedBuffer(new byte[] { 2 });

            // to enable writeBytes
            b.SetWriterIndex(b.WriterIndex - 2);
            b.WriteBytes(c);
            c.Release();
            c = Unpooled.WrappedBuffer(new byte[] { 3 });

            b.WriteBytes(c);
            Assert.True(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();
            c.Release();

            // Same content, different firstIndex, short length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3 });
            b = Unpooled.WrappedBuffer(Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 3, 4 }, 1, 3));
            c = Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 3, 4 }, 3, 1);
            // to enable writeBytes
            b.SetWriterIndex(b.WriterIndex - 1);
            b.WriteBytes(c);
            Assert.True(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();
            c.Release();

            // Different content, same firstIndex, short length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3 });
            b = Unpooled.WrappedBuffer(Unpooled.WrappedBuffer(new byte[] { 1, 2 }, new byte[1]));
            c = Unpooled.WrappedBuffer(new byte[] { 4 });
            // to enable writeBytes
            b.SetWriterIndex(b.WriterIndex - 1);
            b.WriteBytes(c);
            Assert.False(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();
            c.Release();

            // Different content, different firstIndex, short length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3 });
            b = Unpooled.WrappedBuffer(Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 4, 5 }, 1, 3));
            c = Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 4, 5 }, 3, 1);
            // to enable writeBytes
            b.SetWriterIndex(b.WriterIndex - 1);
            b.WriteBytes(c);
            Assert.False(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();
            c.Release();

            // Same content, same firstIndex, long length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            b = Unpooled.WrappedBuffer(Unpooled.WrappedBuffer(new byte[] { 1, 2, 3 }, new byte[7]));
            c = Unpooled.WrappedBuffer(new byte[] { 4, 5, 6 });

            // to enable writeBytes
            b.SetWriterIndex(b.WriterIndex - 7);
            b.WriteBytes(c);
            c.Release();
            c = Unpooled.WrappedBuffer(new byte[] { 7, 8, 9, 10 });
            b.WriteBytes(c);
            Assert.True(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();
            c.Release();

            // Same content, different firstIndex, long length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            b = Unpooled.WrappedBuffer(
                Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, 1, 10));
            c = Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, 6, 5);
            // to enable writeBytes
            b.SetWriterIndex(b.WriterIndex - 5);
            b.WriteBytes(c);
            Assert.True(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();
            c.Release();

            // Different content, same firstIndex, long length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            b = Unpooled.WrappedBuffer(Unpooled.WrappedBuffer(new byte[] { 1, 2, 3, 4, 6 }, new byte[5]));
            c = Unpooled.WrappedBuffer(new byte[] { 7, 8, 5, 9, 10 });
            // to enable writeBytes
            b.SetWriterIndex(b.WriterIndex - 5);
            b.WriteBytes(c);
            Assert.False(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();
            c.Release();

            // Different content, different firstIndex, long length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            b = Unpooled.WrappedBuffer(
                Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 6, 7, 8, 5, 9, 10, 11 }, 1, 10));
            c = Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 6, 7, 8, 5, 9, 10, 11 }, 6, 5);
            // to enable writeBytes
            b.SetWriterIndex(b.WriterIndex - 5);
            b.WriteBytes(c);
            Assert.False(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();
            c.Release();
        }
        public void SeveralBuffersEquals()
        {
            // XXX Same tests with several buffers in wrappedCheckedBuffer
            // Different length.
            IByteBuffer a = Unpooled.WrappedBuffer(new byte[] { 1 });
            IByteBuffer b = Unpooled.WrappedBuffer(
                Unpooled.WrappedBuffer(new byte[] { 1 }),
                Unpooled.WrappedBuffer(new byte[] { 2 }));

            Assert.False(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();

            // Same content, same firstIndex, short length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3 });
            b = Unpooled.WrappedBuffer(
                Unpooled.WrappedBuffer(new byte[] { 1 }),
                Unpooled.WrappedBuffer(new byte[] { 2 }),
                Unpooled.WrappedBuffer(new byte[] { 3 }));
            Assert.True(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();

            // Same content, different firstIndex, short length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3 });
            b = Unpooled.WrappedBuffer(
                Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 3, 4 }, 1, 2),
                Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 3, 4 }, 3, 1));
            Assert.True(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();

            // Different content, same firstIndex, short length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3 });
            b = Unpooled.WrappedBuffer(
                Unpooled.WrappedBuffer(new byte[] { 1, 2 }),
                Unpooled.WrappedBuffer(new byte[] { 4 }));
            Assert.False(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();

            // Different content, different firstIndex, short length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3 });
            b = Unpooled.WrappedBuffer(
                Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 4, 5 }, 1, 2),
                Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 4, 5 }, 3, 1));
            Assert.False(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();

            // Same content, same firstIndex, long length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            b = Unpooled.WrappedBuffer(
                Unpooled.WrappedBuffer(new byte[] { 1, 2, 3 }),
                Unpooled.WrappedBuffer(new byte[] { 4, 5, 6 }),
                Unpooled.WrappedBuffer(new byte[] { 7, 8, 9, 10 }));
            Assert.True(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();

            // Same content, different firstIndex, long length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            b = Unpooled.WrappedBuffer(
                Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, 1, 5),
                Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, 6, 5));
            Assert.True(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();

            // Different content, same firstIndex, long length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            b = Unpooled.WrappedBuffer(
                Unpooled.WrappedBuffer(new byte[] { 1, 2, 3, 4, 6 }),
                Unpooled.WrappedBuffer(new byte[] { 7, 8, 5, 9, 10 }));
            Assert.False(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();

            // Different content, different firstIndex, long length.
            a = Unpooled.WrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
            b = Unpooled.WrappedBuffer(
                Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 6, 7, 8, 5, 9, 10, 11 }, 1, 5),
                Unpooled.WrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 6, 7, 8, 5, 9, 10, 11 }, 6, 5));
            Assert.False(ByteBufferUtil.Equals(a, b));

            a.Release();
            b.Release();
        }