コード例 #1
0
ファイル: TlsHandlerTest.cs プロジェクト: xunilrj/DotNetty
        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)}");
        }
コード例 #2
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);
            }
        }
コード例 #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);
                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);
            }
        }
コード例 #4
0
ファイル: TlsHandlerTest.cs プロジェクト: xunilrj/DotNetty
        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)}");
        }
コード例 #5
0
        static async Task <Tuple <EmbeddedChannel, SslStream> > SetupStreamAndChannelAsync(bool isClient, IEventExecutor executor, IWriteStrategy writeStrategy, SslProtocols protocol, List <Task> writeTasks)
        {
            X509Certificate2 tlsCertificate = TestResourceHelper.GetTestCertificate();
            string           targetHost     = tlsCertificate.GetNameInfo(X509NameType.DnsName, false);
            TlsHandler       tlsHandler     = isClient ?
                                              new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ClientTlsSettings(targetHost)) :
                                              TlsHandler.Server(tlsCertificate);
            //var ch = new EmbeddedChannel(new LoggingHandler("BEFORE"), tlsHandler, new LoggingHandler("AFTER"));
            var ch = new EmbeddedChannel(tlsHandler);

            IByteBuffer readResultBuffer = Unpooled.Buffer(4 * 1024);
            Func <ArraySegment <byte>, Task <int> > readDataFunc = async output =>
            {
                if (writeTasks.Count > 0)
                {
                    await Task.WhenAll(writeTasks).WithTimeout(TestTimeout);

                    writeTasks.Clear();
                }

                if (readResultBuffer.ReadableBytes < output.Count)
                {
                    await ReadOutboundAsync(async() => ch.ReadOutbound <IByteBuffer>(), output.Count - readResultBuffer.ReadableBytes, readResultBuffer, TestTimeout);
                }
                Assert.NotEqual(0, readResultBuffer.ReadableBytes);
                int read = Math.Min(output.Count, readResultBuffer.ReadableBytes);
                readResultBuffer.ReadBytes(output.Array, output.Offset, read);
                return(read);
            };
            var mediationStream = new MediationStream(readDataFunc, input =>
            {
                Task task = executor.SubmitAsync(() => writeStrategy.WriteToChannelAsync(ch, input)).Unwrap();
                writeTasks.Add(task);
                return(task);
            });

            var driverStream = new SslStream(mediationStream, true, (_1, _2, _3, _4) => true);

            if (isClient)
            {
                await Task.Run(() => driverStream.AuthenticateAsServerAsync(tlsCertificate)).WithTimeout(TimeSpan.FromSeconds(5));
            }
            else
            {
                await Task.Run(() => driverStream.AuthenticateAsClientAsync(targetHost, null, protocol, false)).WithTimeout(TimeSpan.FromSeconds(5));
            }
            writeTasks.Clear();

            return(Tuple.Create(ch, driverStream));
        }
コード例 #6
0
        static async Task <Tuple <EmbeddedChannel, SslStream> > SetupStreamAndChannelAsync(bool isClient, IEventExecutor executor, IWriteStrategy writeStrategy, SslProtocols protocol, List <Task> writeTasks, string targetHost)
        {
            IChannelHandler tlsHandler = isClient ?
                                         (IChannelHandler) new TlsHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) =>
            {
                Assert.Equal(targetHost, certificate.Issuer.Replace("CN=", string.Empty));
                return(true);
            }), new ClientTlsSettings(protocol, false, new List <X509Certificate>(), targetHost)) :
                                         new SniHandler(stream => new SslStream(stream, true, (sender, certificate, chain, errors) => true), new ServerTlsSniSettings(CertificateSelector));
            //var ch = new EmbeddedChannel(new LoggingHandler("BEFORE"), tlsHandler, new LoggingHandler("AFTER"));
            var ch = new EmbeddedChannel(tlsHandler);

            if (!isClient)
            {
                // check if in the beginning snihandler exists in the pipeline, but not tls handler
                Assert.NotNull(ch.Pipeline.Get <SniHandler>());
                Assert.Null(ch.Pipeline.Get <TlsHandler>());
            }

            IByteBuffer readResultBuffer = Unpooled.Buffer(4 * 1024);
            Func <ArraySegment <byte>, Task <int> > readDataFunc = async output =>
            {
                if (writeTasks.Count > 0)
                {
                    await Task.WhenAll(writeTasks).WithTimeout(TestTimeout);

                    writeTasks.Clear();
                }

                if (readResultBuffer.ReadableBytes < output.Count)
                {
                    if (ch.Active)
                    {
                        await ReadOutboundAsync(async() => ch.ReadOutbound <IByteBuffer>(), output.Count - readResultBuffer.ReadableBytes, readResultBuffer, TestTimeout, readResultBuffer.ReadableBytes != 0? 0 : 1);
                    }
                }
                int read = Math.Min(output.Count, readResultBuffer.ReadableBytes);
                readResultBuffer.ReadBytes(output.Array, output.Offset, read);
                return(read);
            };
            var mediationStream = new MediationStream(readDataFunc, input =>
            {
                Task task = executor.SubmitAsync(() => writeStrategy.WriteToChannelAsync(ch, input)).Unwrap();
                writeTasks.Add(task);
                return(task);
            });

            var driverStream = new SslStream(mediationStream, true, (_1, _2, _3, _4) => true);

            if (isClient)
            {
                ServerTlsSettings serverTlsSettings = CertificateSelector(targetHost).Result;
                await Task.Run(() => driverStream.AuthenticateAsServerAsync(serverTlsSettings.Certificate, false, protocol | serverTlsSettings.EnabledProtocols, false).WithTimeout(TimeSpan.FromSeconds(5)));
            }
            else
            {
                await Task.Run(() => driverStream.AuthenticateAsClientAsync(targetHost, null, protocol, false)).WithTimeout(TimeSpan.FromSeconds(5));
            }
            writeTasks.Clear();

            return(Tuple.Create(ch, driverStream));
        }
コード例 #7
0
 public App(IReadStrategy readStrategy, IWriteStrategy writeStrategy)
 {
     _readStrategy  = readStrategy;
     _writeStrategy = writeStrategy;
 }
コード例 #8
0
ファイル: TlsHandlerTest.cs プロジェクト: xunilrj/DotNetty
        static async Task<Tuple<EmbeddedChannel, SslStream>> SetupStreamAndChannelAsync(bool isClient, IWriteStrategy writeStrategy, SslProtocols protocol, List<Task> writeTasks)
        {
            var tlsCertificate = new X509Certificate2("dotnetty.com.pfx", "password");
            string targetHost = tlsCertificate.GetNameInfo(X509NameType.DnsName, false);
            TlsHandler tlsHandler = isClient ? TlsHandler.Client(targetHost, null, (_1, _2, _3, _4) => true) : TlsHandler.Server(tlsCertificate);
            //var ch = new EmbeddedChannel(new LoggingHandler("BEFORE"), tlsHandler, new LoggingHandler("AFTER"));
            var ch = new EmbeddedChannel(tlsHandler);

            IByteBuffer readResultBuffer = Unpooled.Buffer(4 * 1024);
            Func<ArraySegment<byte>, Task<int>> readDataFunc = async output =>
            {
                if (writeTasks.Count > 0)
                {
                    await Task.WhenAll(writeTasks).WithTimeout(TestTimeout);
                    writeTasks.Clear();
                }

                if (readResultBuffer.ReadableBytes < output.Count)
                {
                    await ReadOutboundAsync(() =>
                    {
                        var a = ch.ReadOutbound<IByteBuffer>();
                        return a;
                    }, output.Count - readResultBuffer.ReadableBytes, readResultBuffer, TestTimeout);
                }
                Assert.NotEqual(0, readResultBuffer.ReadableBytes);
                int read = Math.Min(output.Count, readResultBuffer.ReadableBytes);
                readResultBuffer.ReadBytes(output.Array, output.Offset, read);
                return read;
            };
            var mediationStream = new MediationStream(readDataFunc, input => writeTasks.Add(writeStrategy.WriteToChannelAsync(ch, input)));

            var driverStream = new SslStream(mediationStream, true, (_1, _2, _3, _4) => true);
            if (isClient)
            {
                await Task.Run(() => driverStream.AuthenticateAsServer(tlsCertificate)).WithTimeout(TimeSpan.FromSeconds(5));
            }
            else
            {
                await Task.Run(() => driverStream.AuthenticateAsClient(targetHost, null, protocol, false)).WithTimeout(TimeSpan.FromSeconds(5));
            }
            writeTasks.Clear();

            return Tuple.Create(ch, driverStream);
        }
コード例 #9
0
ファイル: TlsHandlerTest.cs プロジェクト: xunilrj/DotNetty
        static async Task <Tuple <EmbeddedChannel, SslStream> > SetupStreamAndChannelAsync(bool isClient, IWriteStrategy writeStrategy, SslProtocols protocol, List <Task> writeTasks)
        {
            var        tlsCertificate = new X509Certificate2("dotnetty.com.pfx", "password");
            string     targetHost     = tlsCertificate.GetNameInfo(X509NameType.DnsName, false);
            TlsHandler tlsHandler     = isClient ? TlsHandler.Client(targetHost, null, (_1, _2, _3, _4) => true) : TlsHandler.Server(tlsCertificate);
            //var ch = new EmbeddedChannel(new LoggingHandler("BEFORE"), tlsHandler, new LoggingHandler("AFTER"));
            var ch = new EmbeddedChannel(tlsHandler);

            IByteBuffer readResultBuffer = Unpooled.Buffer(4 * 1024);
            Func <ArraySegment <byte>, Task <int> > readDataFunc = async output =>
            {
                if (writeTasks.Count > 0)
                {
                    await Task.WhenAll(writeTasks).WithTimeout(TestTimeout);

                    writeTasks.Clear();
                }

                if (readResultBuffer.ReadableBytes < output.Count)
                {
                    await ReadOutboundAsync(() =>
                    {
                        var a = ch.ReadOutbound <IByteBuffer>();
                        return(a);
                    }, output.Count - readResultBuffer.ReadableBytes, readResultBuffer, TestTimeout);
                }
                Assert.NotEqual(0, readResultBuffer.ReadableBytes);
                int read = Math.Min(output.Count, readResultBuffer.ReadableBytes);
                readResultBuffer.ReadBytes(output.Array, output.Offset, read);
                return(read);
            };
            var mediationStream = new MediationStream(readDataFunc, input => writeTasks.Add(writeStrategy.WriteToChannelAsync(ch, input)));

            var driverStream = new SslStream(mediationStream, true, (_1, _2, _3, _4) => true);

            if (isClient)
            {
                await Task.Run(() => driverStream.AuthenticateAsServer(tlsCertificate)).WithTimeout(TimeSpan.FromSeconds(5));
            }
            else
            {
                await Task.Run(() => driverStream.AuthenticateAsClient(targetHost, null, protocol, false)).WithTimeout(TimeSpan.FromSeconds(5));
            }
            writeTasks.Clear();

            return(Tuple.Create(ch, driverStream));
        }
コード例 #10
0
        static async Task <Tuple <EmbeddedChannel, SslStream> > SetupStreamAndChannelAsync(bool isClient, IEventExecutor executor, IWriteStrategy writeStrategy, SslProtocols serverProtocol, SslProtocols clientProtocol, List <Task> writeTasks)
        {
            X509Certificate2 tlsCertificate = TestResourceHelper.GetTestCertificate();
            string           targetHost     = tlsCertificate.GetNameInfo(X509NameType.DnsName, false);
            TlsHandler       tlsHandler     = isClient ?
                                              new TlsHandler(new ClientTlsSettings(clientProtocol, false, new List <X509Certificate>(), targetHost).AllowAnyServerCertificate()) :
                                              new TlsHandler(new ServerTlsSettings(tlsCertificate, false, false, serverProtocol).AllowAnyClientCertificate());
            //var ch = new EmbeddedChannel(new LoggingHandler("BEFORE"), tlsHandler, new LoggingHandler("AFTER"));
            var ch = new EmbeddedChannel(tlsHandler);

            IByteBuffer readResultBuffer = Unpooled.Buffer(4 * 1024);
            Func <ArraySegment <byte>, Task <int> > readDataFunc = async output =>
            {
                if (writeTasks.Count > 0)
                {
                    await Task.WhenAll(writeTasks).WithTimeout(TestTimeout);

                    writeTasks.Clear();
                }

                if (readResultBuffer.ReadableBytes < output.Count)
                {
                    if (ch.IsActive)
                    {
#pragma warning disable CS1998 // 异步方法缺少 "await" 运算符,将以同步方式运行
                        await ReadOutboundAsync(async() => ch.ReadOutbound <IByteBuffer>(), output.Count - readResultBuffer.ReadableBytes, readResultBuffer, TestTimeout, readResultBuffer.ReadableBytes != 0? 0 : 1);

#pragma warning restore CS1998 // 异步方法缺少 "await" 运算符,将以同步方式运行
                    }
                }
                int read = Math.Min(output.Count, readResultBuffer.ReadableBytes);
                readResultBuffer.ReadBytes(output.Array, output.Offset, read);
                return(read);
            };
            var mediationStream = new MediationStream(readDataFunc, input =>
            {
                Task task = executor.SubmitAsync(() => writeStrategy.WriteToChannelAsync(ch, input)).Unwrap();
                writeTasks.Add(task);
                return(task);
            }, () =>
            {
                ch.CloseAsync();
            });

            var driverStream = new SslStream(mediationStream, true, (_1, _2, _3, _4) => true);

            if (isClient)
            {
                await Task.Run(() => driverStream.AuthenticateAsServerAsync(tlsCertificate, false, serverProtocol, false)).WithTimeout(TimeSpan.FromSeconds(5));
            }
            else
            {
                await Task.Run(() => driverStream.AuthenticateAsClientAsync(targetHost, null, clientProtocol, false)).WithTimeout(TimeSpan.FromSeconds(5));
            }
            writeTasks.Clear();

            return(Tuple.Create(ch, driverStream));
        }