public void UdpUnreliableMessageSendTest()
        {
            byte[] TestData = new byte[] { 1, 2, 3, 4, 5, 6 };
            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
                using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
                {
                    MessageReader output = null;
                    listener.NewConnection += delegate(NewConnectionEventArgs e)
                    {
                        e.Connection.DataReceived += delegate(DataReceivedEventArgs evt)
                        {
                            output = evt.Message.Duplicate();
                        };
                    };

                    listener.Start();
                    connection.Connect();

                    for (int i = 0; i < 4; ++i)
                    {
                        var msg = MessageWriter.Get(SendOption.None);
                        msg.Write(TestData);
                        connection.Send(msg);
                        msg.Recycle();
                    }

                    Thread.Sleep(10);
                    for (int i = 0; i < TestData.Length; ++i)
                    {
                        Assert.AreEqual(TestData[i], output.ReadByte());
                    }
                }
        }
        public void ClientDisconnectTest()
        {
            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
                using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
                {
                    ManualResetEvent mutex  = new ManualResetEvent(false);
                    ManualResetEvent mutex2 = new ManualResetEvent(false);

                    listener.NewConnection += delegate(NewConnectionEventArgs args)
                    {
                        args.Connection.Disconnected += delegate(object sender2, DisconnectedEventArgs args2)
                        {
                            mutex2.Set();
                        };

                        mutex.Set();
                    };

                    listener.Start();

                    connection.Connect();

                    mutex.WaitOne(1000);
                    Assert.AreEqual(ConnectionState.Connected, connection.State);

                    connection.Disconnect("Testing");

                    mutex2.WaitOne(1000);
                    Assert.AreEqual(ConnectionState.NotConnected, connection.State);
                }
        }
示例#3
0
        // This was a thing that happened to us a DDoS. Mildly instructional that we straight up ignore it.
        public void SourceAmpAttack()
        {
            var localEp  = new IPEndPoint(IPAddress.Any, 11710);
            var serverEp = new IPEndPoint(IPAddress.Loopback, 11710);

            using (ThreadLimitedUdpConnectionListener listener = new ThreadLimitedUdpConnectionListener(4, localEp, new ConsoleLogger(true)))
            {
                listener.Start();

                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                socket.DontFragment = false;

                try
                {
                    const int SIO_UDP_CONNRESET = -1744830452;
                    socket.IOControl(SIO_UDP_CONNRESET, new byte[1], null);
                }
                catch { } // Only necessary on Windows

                string byteAsHex = "f23c 92d1 c277 001b 54c2 50c1 0800 4500 0035 7488 0000 3b11 2637 062f ac75 2d4f 0506 a7ea 5607 0021 5e07 ffff ffff 5453 6f75 7263 6520 456e 6769 6e65 2051 7565 7279 00";
                byte[] bytes     = StringToByteArray(byteAsHex.Replace(" ", ""));
                socket.SendTo(bytes, serverEp);

                while (socket.Poll(50000, SelectMode.SelectRead))
                {
                    byte[] buffer = new byte[1024];
                    int    len    = socket.Receive(buffer);
                    Console.WriteLine($"got {len} bytes: " + string.Join(" ", buffer.Select(b => b.ToString("X"))));
                    Console.WriteLine($"got {len} bytes: " + string.Join(" ", buffer.Select(b => (char)b)));
                }
            }
        }
        public void KeepAliveServerTest()
        {
            ManualResetEvent mutex = new ManualResetEvent(false);

            using (ThreadLimitedUdpConnectionListener listener = new ThreadLimitedUdpConnectionListener(2, new IPEndPoint(IPAddress.Any, 4296), new NullLogger()))
                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    UdpConnection client = null;
                    listener.NewConnection += delegate(NewConnectionEventArgs args)
                    {
                        client = (UdpConnection)args.Connection;
                        client.KeepAliveInterval = 100;

                        Thread.Sleep(1050); //Enough time for ~10 keep alive packets

                        mutex.Set();
                    };

                    listener.Start();

                    connection.Connect();

                    mutex.WaitOne();

                    Assert.AreEqual(ConnectionState.Connected, client.State);

                    Assert.IsTrue(
                        client.Statistics.TotalBytesSent >= 27 &&
                        client.Statistics.TotalBytesSent <= 50,
                        "Sent: " + client.Statistics.TotalBytesSent
                        );
                }
        }
        public void ServerExtraDataDisconnectTest()
        {
            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
                using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
                {
                    string           received = null;
                    ManualResetEvent mutex    = new ManualResetEvent(false);

                    connection.Disconnected += delegate(object sender, DisconnectedEventArgs args)
                    {
                        // We don't own the message, we have to read the string now
                        received = args.Message.ReadString();
                        mutex.Set();
                    };

                    listener.NewConnection += delegate(NewConnectionEventArgs args)
                    {
                        MessageWriter writer = MessageWriter.Get(SendOption.None);
                        writer.Write("Goodbye");
                        args.Connection.Disconnect("Testing", writer);
                    };

                    listener.Start();

                    connection.Connect();

                    mutex.WaitOne(5000);

                    Assert.IsNotNull(received);
                    Assert.AreEqual("Goodbye", received);
                }
        }
        public void ClientDisposeDisconnectTest()
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 4296);

            bool serverConnected    = false;
            bool serverDisconnected = false;
            bool clientDisconnected = false;

            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
                using (UdpConnection connection = this.CreateConnection(ep, new TestLogger()))
                {
                    listener.NewConnection += (evt) =>
                    {
                        serverConnected              = true;
                        evt.Connection.Disconnected += (o, et) => serverDisconnected = true;
                    };

                    connection.Disconnected += (o, et) => clientDisconnected = true;

                    listener.Start();
                    connection.Connect();

                    Thread.Sleep(100); // Gotta wait for the server to set up the events.
                    connection.Dispose();

                    Thread.Sleep(100);

                    Assert.IsTrue(serverConnected);
                    Assert.IsTrue(serverDisconnected);
                    Assert.IsFalse(clientDisconnected);
                }
        }
        public void ConnectLikeAJerkTest()
        {
            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
                using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                {
                    int connects = 0;
                    listener.NewConnection += (obj) =>
                    {
                        Interlocked.Increment(ref connects);
                    };

                    listener.Start();

                    socket.Bind(new IPEndPoint(IPAddress.Any, 0));
                    var bytes = new byte[2];
                    bytes[0] = (byte)UdpSendOption.Hello;
                    for (int i = 0; i < 10; ++i)
                    {
                        socket.SendTo(bytes, new IPEndPoint(IPAddress.Loopback, 4296));
                    }

                    Thread.Sleep(500);

                    Assert.AreEqual(0, listener.ReceiveQueueLength);
                    Assert.IsTrue(connects <= 1, $"Too many connections: {connects}");
                }
        }
        public void PingDisconnectClientTest()
        {
#if DEBUG && false
            using (ThreadLimitedUdpConnectionListener listener = new ThreadLimitedUdpConnectionListener(2, new IPEndPoint(IPAddress.Any, 4296), new NullLogger()))
                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    listener.Start();

                    connection.Connect();

                    // After connecting, quietly stop responding to all messages to fake connection loss.
                    Thread.Sleep(10);
                    // listener.TestDropRate = 1;

                    connection.KeepAliveInterval = 100;

                    Thread.Sleep(1050); //Enough time for ~10 keep alive packets

                    Assert.AreEqual(ConnectionState.NotConnected, connection.State);
                    Assert.AreEqual(3 * connection.MissingPingsUntilDisconnect + 4, connection.Statistics.TotalBytesSent); // + 4 for connecting overhead
                }
#else
            Assert.Inconclusive("Only works in DEBUG");
#endif
        }
        public void UdpIPv4ConnectionTest()
        {
            using (ThreadLimitedUdpConnectionListener listener = new ThreadLimitedUdpConnectionListener(2, new IPEndPoint(IPAddress.Any, 4296), new NullLogger()))
                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    listener.Start();

                    connection.Connect();
                }
        }
示例#10
0
        public void DtlsIPv4ConnectionTest()
        {
            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
                using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
                {
                    listener.Start();

                    connection.Connect();

                    Assert.AreEqual(ConnectionState.Connected, connection.State);
                }
        }
        public void UdpIPv6ConnectionTest()
        {
            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.IPv6Any, 4296), new TestLogger(), IPMode.IPv6))
            {
                listener.Start();

                using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4296), new TestLogger(), IPMode.IPv6))
                {
                    connection.Connect();
                }
            }
        }
        public void UdpIPv4ConnectionTest()
        {
            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
                using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
                {
                    listener.Start();

                    connection.Connect();

                    Assert.AreEqual(ConnectionState.Connected, connection.State);

                    Console.Write($"Client sent {connection.Statistics.TotalBytesSent} bytes ");
                }
        }
示例#13
0
        /// <summary>
        ///     Runs a general test on the given listener and connection.
        /// </summary>
        /// <param name="listener">The listener to test.</param>
        /// <param name="connection">The connection to test.</param>
        internal static void RunServerToClientTest(ThreadLimitedUdpConnectionListener listener, Connection connection, int dataSize, SendOption sendOption)
        {
            //Setup meta stuff
            byte[]           data  = BuildData(dataSize);
            ManualResetEvent mutex = new ManualResetEvent(false);

            //Setup listener
            listener.NewConnection += delegate(NewConnectionEventArgs ncArgs)
            {
                ncArgs.Connection.SendBytes(data, sendOption);
            };

            listener.Start();

            DataReceivedEventArgs?args = null;

            //Setup conneciton
            connection.DataReceived += delegate(DataReceivedEventArgs a)
            {
                Trace.WriteLine("Data was received correctly.");

                try
                {
                    args = a;
                }
                finally
                {
                    mutex.Set();
                }
            };

            connection.Connect();

            //Wait until data is received
            mutex.WaitOne();

            Assert.AreEqual(data.Length, args.Value.Message.Length);

            for (int i = 0; i < data.Length; i++)
            {
                Assert.AreEqual(data[i], args.Value.Message.ReadByte());
            }

            Assert.AreEqual(sendOption, args.Value.SendOption);
        }
示例#14
0
        /// <summary>
        ///     Runs a general test on the given listener and connection.
        /// </summary>
        /// <param name="listener">The listener to test.</param>
        /// <param name="connection">The connection to test.</param>
        internal static void RunClientToServerTest(ThreadLimitedUdpConnectionListener listener, Connection connection, int dataSize, SendOption sendOption)
        {
            //Setup meta stuff
            byte[]           data   = BuildData(dataSize);
            ManualResetEvent mutex  = new ManualResetEvent(false);
            ManualResetEvent mutex2 = new ManualResetEvent(false);

            //Setup listener
            DataReceivedEventArgs?result = null;

            listener.NewConnection += delegate(NewConnectionEventArgs args)
            {
                args.Connection.DataReceived += delegate(DataReceivedEventArgs innerArgs)
                {
                    Trace.WriteLine("Data was received correctly.");

                    result = innerArgs;

                    mutex2.Set();
                };

                mutex.Set();
            };

            listener.Start();

            //Connect
            connection.Connect();

            mutex.WaitOne();

            connection.SendBytes(data, sendOption);

            //Wait until data is received
            mutex2.WaitOne();

            Assert.AreEqual(data.Length, result.Value.Message.Length);

            for (int i = 0; i < data.Length; i++)
            {
                Assert.AreEqual(data[i], result.Value.Message.ReadByte());
            }

            Assert.AreEqual(sendOption, result.Value.SendOption);
        }
        public void UdpFieldTest()
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, 4296);

            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
                using (UdpConnection connection = this.CreateConnection(ep, new TestLogger()))
                {
                    listener.Start();

                    connection.Connect();

                    //Connection fields
                    Assert.AreEqual(ep, connection.EndPoint);

                    //UdpConnection fields
                    Assert.AreEqual(new IPEndPoint(IPAddress.Loopback, 4296), connection.EndPoint);
                    Assert.AreEqual(1, connection.Statistics.DataBytesSent);
                    Assert.AreEqual(0, connection.Statistics.DataBytesReceived);
                }
        }
        public virtual void KeepAliveClientTest()
        {
            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
                using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
                {
                    listener.Start();

                    connection.Connect();
                    connection.KeepAliveInterval = 100;

                    Thread.Sleep(1050); //Enough time for ~10 keep alive packets

                    Assert.AreEqual(ConnectionState.Connected, connection.State);
                    Assert.IsTrue(
                        connection.Statistics.TotalBytesSent >= 30 &&
                        connection.Statistics.TotalBytesSent <= 50,
                        "Sent: " + connection.Statistics.TotalBytesSent
                        );
                }
        }
        public void ServerDisconnectTest()
        {
            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
                using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
                {
                    SemaphoreSlim        mutex       = new SemaphoreSlim(0, 100);
                    ManualResetEventSlim serverMutex = new ManualResetEventSlim(false);

                    connection.Disconnected += delegate(object sender, DisconnectedEventArgs args)
                    {
                        mutex.Release();
                    };

                    listener.NewConnection += delegate(NewConnectionEventArgs args)
                    {
                        mutex.Release();

                        // This has to be on a new thread because the client will go straight from Connecting to NotConnected
                        ThreadPool.QueueUserWorkItem(_ =>
                        {
                            serverMutex.Wait(500);
                            args.Connection.Disconnect("Testing");
                        });
                    };

                    listener.Start();

                    connection.Connect();

                    mutex.Wait(500);
                    Assert.AreEqual(ConnectionState.Connected, connection.State);

                    serverMutex.Set();

                    mutex.Wait(500);
                    Assert.AreEqual(ConnectionState.NotConnected, connection.State);
                }
        }
        public void UdpHandshakeTest()
        {
            byte[] TestData = new byte[] { 1, 2, 3, 4, 5, 6 };
            using (ThreadLimitedUdpConnectionListener listener = this.CreateListener(2, new IPEndPoint(IPAddress.Any, 4296), new TestLogger()))
                using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Loopback, 4296), new TestLogger()))
                {
                    listener.Start();

                    MessageReader output = null;
                    listener.NewConnection += delegate(NewConnectionEventArgs e)
                    {
                        output = e.HandshakeData.Duplicate();
                    };

                    connection.Connect(TestData);

                    Thread.Sleep(10);
                    for (int i = 0; i < TestData.Length; ++i)
                    {
                        Assert.AreEqual(TestData[i], output.ReadByte());
                    }
                }
        }
        public void ServerDisconnectTest()
        {
            using (ThreadLimitedUdpConnectionListener listener = new ThreadLimitedUdpConnectionListener(2, new IPEndPoint(IPAddress.Any, 4296), new NullLogger()))
                using (UdpConnection connection = new UdpClientConnection(new IPEndPoint(IPAddress.Loopback, 4296)))
                {
                    ManualResetEvent mutex = new ManualResetEvent(false);

                    connection.Disconnected += delegate(object sender, DisconnectedEventArgs args)
                    {
                        mutex.Set();
                    };

                    listener.NewConnection += delegate(NewConnectionEventArgs args)
                    {
                        args.Connection.Disconnect("Testing");
                    };

                    listener.Start();

                    connection.Connect();

                    mutex.WaitOne();
                }
        }
        public void MixedConnectionTest()
        {
            using (ThreadLimitedUdpConnectionListener listener2 = this.CreateListener(4, new IPEndPoint(IPAddress.IPv6Any, 4296), new ConsoleLogger(true), IPMode.IPv6))
            {
                listener2.Start();

                listener2.NewConnection += (evt) =>
                {
                    Console.WriteLine($"Connection: {evt.Connection.EndPoint}");
                };

                using (UdpConnection connection = this.CreateConnection(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4296), new TestLogger()))
                {
                    connection.Connect();
                    Assert.AreEqual(ConnectionState.Connected, connection.State);
                }

                using (UdpConnection connection2 = this.CreateConnection(new IPEndPoint(IPAddress.IPv6Loopback, 4296), new TestLogger(), IPMode.IPv6))
                {
                    connection2.Connect();
                    Assert.AreEqual(ConnectionState.Connected, connection2.State);
                }
            }
        }