Ejemplo n.º 1
0
        protected override void Encode(IChannelHandlerContext ctx, NumberObj obj, List <object> output)
        {
            IByteBuffer buffer = ctx.Allocator.Buffer();

            // Specify the protocol selector
            buffer.WriteByte((byte)'B');

            // BitConverter returns a Little-Endian byte array
            // But DotNetty defaults to Big-Endian - fixed by reversing the array, so the data is Little-Endian
            var data = BitConverter.GetBytes(obj.Number);

            Array.Reverse(data);
            buffer.WriteBytes(data);

            // Use Windows style newline to indicate the data frame is complete.
            // As the lenght of this message type is know, then the LineBasedFrameDecoder could be used at the server
            buffer.WriteByte('\r');
            buffer.WriteByte('\n');

            if (_logRawMessages)
            {
                Logger.Debug($"Decoding message: \n\r'{ByteBufferUtil.PrettyHexDump(buffer)}'");
            }

            output.Add(buffer);
        }
Ejemplo n.º 2
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);
            }
        }
Ejemplo n.º 3
0
        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);
#pragma warning disable CS1998 // 异步方法缺少 "await" 运算符,将以同步方式运行
                await ReadOutboundAsync(async() => ch.ReadInbound <IByteBuffer>(), expectedBuffer.ReadableBytes, finalReadBuffer, TestTimeout);

#pragma warning restore CS1998 // 异步方法缺少 "await" 运算符,将以同步方式运行
                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);
            }
        }
Ejemplo n.º 4
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            if (_logRawMessages)
            {
                Logger.Debug($"Decoding message: \n\r'{ByteBufferUtil.PrettyHexDump(input)}'");
            }

            if (input.ReadableBytes != 4)
            {
                return;
            }

            var number = input.ReadInt();  // Could have used .ReadIntLE() if the message was transfered as Little-Endian

            output.Add(item: new NumberObj()
            {
                Number = number
            });
        }
Ejemplo n.º 5
0
        void TestEncode(IByteBuffer src, IByteBuffer expected, bool breakLines)
        {
            IByteBuffer encoded = Base64.Encode(src, breakLines, Base64Dialect.STANDARD);

            try
            {
                Assert.NotNull(encoded);
                string expectedPretty = ByteBufferUtil.PrettyHexDump(expected);
                string actualPretty   = ByteBufferUtil.PrettyHexDump(encoded);
                this.output.WriteLine("expected:\n" + expectedPretty);
                this.output.WriteLine("actual:\n" + actualPretty);
                if (expectedPretty != actualPretty)
                {
                    Assert.Equal(expectedPretty, actualPretty);
                }
            }
            finally
            {
                src.Release();
                expected.Release();
                encoded.Release();
            }
        }
Ejemplo n.º 6
0
        protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List <object> output)
        {
            if (input is EmptyByteBuffer)
            {
                return;
            }

            if (ClientSettings.ClientSession.AuthKey == null)
            {
                throw new UserNotAuthorizeException();
            }

            var decodeBuffer = MtProtoHelper.FromServerDecrypt(input, ClientSettings.ClientSession, out var authKeyId, out var serverSalt, out var sessionId, out var messageId, out var seqNumber);

            try
            {
                var message = Serializer.Deserialize(decodeBuffer);

                Log.Debug($"#{ClientSettings.ClientSession.SessionId}: Receive the secure message {message}");

                output.Add(message);
            }
            catch
            {
                decodeBuffer.ResetReaderIndex();
                Log.Error($"#{ClientSettings.ClientSession.SessionId}: Can't deserialize message: \n{ByteBufferUtil.PrettyHexDump(decodeBuffer)}");
                throw;
            }
        }
Ejemplo n.º 7
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);
                await ReadOutboundAsync(async() => ch.ReadInbound <IByteBuffer>(), 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);
            }
        }
Ejemplo n.º 8
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 SingleThreadEventExecutor("test executor", TimeSpan.FromMilliseconds(10));

            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();
            }
            finally
            {
                await executor.ShutdownGracefullyAsync(TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(300));
            }
        }
Ejemplo n.º 9
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)}");
        }
Ejemplo n.º 10
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)}");
        }