Exemplo n.º 1
0
        static void Main(string[] args)
        {
            NetPeerConfiguration config = new NetPeerConfiguration("unittests");

            config.EnableUPnP = true;
            NetPeer peer = new NetPeer(config);

            peer.Start();             // needed for initialization

            Console.WriteLine("Unique identifier is " + NetUtility.ToHexString(peer.UniqueIdentifier));

            ReadWriteTests.Run(peer);

            NetQueueTests.Run();

            MiscTests.Run(peer);

            BitVectorTests.Run();

            EncryptionTests.Run(peer);

            var om = peer.CreateMessage();

            peer.SendUnconnectedMessage(om, new IPEndPoint(IPAddress.Loopback, 14242));
            try
            {
                peer.SendUnconnectedMessage(om, new IPEndPoint(IPAddress.Loopback, 14242));
            }
            catch (NetException nex)
            {
                if (nex.Message != "This message has already been sent! Use NetPeer.SendMessage() to send to multiple recipients efficiently")
                {
                    throw nex;
                }
            }

            peer.Shutdown("bye");

            // read all message
            NetIncomingMessage inc;

            while ((inc = peer.ReadMessage()) != null)
            {
                switch (inc.MessageType)
                {
                case NetIncomingMessageType.DebugMessage:
                case NetIncomingMessageType.VerboseDebugMessage:
                case NetIncomingMessageType.WarningMessage:
                case NetIncomingMessageType.ErrorMessage:
                    Console.WriteLine("Peer message: " + inc.ReadString());
                    break;

                case NetIncomingMessageType.Error:
                    throw new Exception("Received error message!");
                }
            }

            Console.WriteLine("Done");
            Console.ReadKey();
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            NetPeerConfiguration config = new NetPeerConfiguration("unittests");
            NetPeer peer = new NetPeer(config);

            peer.Start();             // needed for initialization

            System.Threading.Thread.Sleep(50);

            Console.WriteLine("Unique identifier is " + NetUtility.ToHexString(peer.UniqueIdentifier));

            ReadWriteTests.Run(peer);

            NetQueueTests.Run();

            MiscTests.Run(peer);

            BitVectorTests.Run();

            EncryptionTests.Run(peer);

            peer.Shutdown("bye");

            // read all message
            NetIncomingMessage inc;

            while ((inc = peer.ReadMessage()) != null)
            {
                switch (inc.MessageType)
                {
                case NetIncomingMessageType.DebugMessage:
                case NetIncomingMessageType.VerboseDebugMessage:
                case NetIncomingMessageType.WarningMessage:
                case NetIncomingMessageType.ErrorMessage:
                    Console.WriteLine("Peer message: " + inc.ReadString());
                    break;

                case NetIncomingMessageType.Error:
                    throw new Exception("Received error message!");
                }
            }

            Console.WriteLine("Done");
            Console.ReadKey();
        }
Exemplo n.º 3
0
        public static void Run(NetPeer peer)
        {
            NetOutgoingMessage msg = peer.CreateMessage();

            msg.Write(false);
            msg.Write(-3, 6);
            msg.Write(42);
            msg.Write("duke of earl");
            msg.Write((byte)43);
            msg.Write((ushort)44);
            msg.Write(UInt64.MaxValue, 64);
            msg.Write(true);

            msg.WritePadBits();

            int bcnt = 0;

            msg.Write(567845.0f);
            msg.WriteVariableInt32(2115998022);
            msg.Write(46.0);
            msg.Write((ushort)14, 9);
            bcnt += msg.WriteVariableInt32(-47);
            msg.WriteVariableInt32(470000);
            msg.WriteVariableUInt32(48);
            bcnt += msg.WriteVariableInt64(-49);

            if (bcnt != 2)
            {
                throw new NetException("WriteVariable* wrote too many bytes!");
            }

            byte[] data = msg.Data;

            NetIncomingMessage inc = MiscTests.CreateIncomingMessage(data, msg.LengthBits);

            StringBuilder bdr = new StringBuilder();

            bdr.Append(inc.ReadBoolean());
            bdr.Append(inc.ReadInt32(6));
            bdr.Append(inc.ReadInt32());

            string strResult;
            bool   ok = inc.ReadString(out strResult);

            Assert.IsTrue(ok, "ReadWriteTests failed");

            if (ok == false)
            {
                throw new NetException("Read/write failure");
            }
            bdr.Append(strResult);

            bdr.Append(inc.ReadByte());

            if (inc.PeekUInt16() != (ushort)44)
            {
                throw new NetException("Read/write failure");
            }

            bdr.Append(inc.ReadUInt16());

            if (inc.PeekUInt64(64) != UInt64.MaxValue)
            {
                throw new NetException("Read/write failure");
            }

            bdr.Append(inc.ReadUInt64());
            bdr.Append(inc.ReadBoolean());

            inc.SkipPadBits();

            bdr.Append(inc.ReadSingle());
            bdr.Append(inc.ReadVariableInt32());
            bdr.Append(inc.ReadDouble());
            bdr.Append(inc.ReadUInt32(9));
            bdr.Append(inc.ReadVariableInt32());
            bdr.Append(inc.ReadVariableInt32());
            bdr.Append(inc.ReadVariableUInt32());
            bdr.Append(inc.ReadVariableInt64());

            if (bdr.ToString().Equals("False-342duke of earl434418446744073709551615True56784521159980224614-4747000048-49"))
            {
                TestContext.Out.WriteLine("Read/write tests OK");
            }
            else
            {
                throw new NetException("Read/write tests FAILED!");
            }

            msg = peer.CreateMessage();

            NetOutgoingMessage tmp = peer.CreateMessage();

            tmp.Write((int)42, 14);

            msg.Write(tmp);
            msg.Write(tmp);

            if (msg.LengthBits != tmp.LengthBits * 2)
            {
                throw new NetException("NetOutgoingMessage.Write(NetOutgoingMessage) failed!");
            }

            tmp = peer.CreateMessage();

            Test test = new Test();

            test.Number = 42;
            test.Name   = "Hallon";
            test.Age    = 8.2f;

            tmp.WriteAllFields(test, BindingFlags.Public | BindingFlags.Instance);

            data = tmp.Data;

            inc = MiscTests.CreateIncomingMessage(data, tmp.LengthBits);

            Test readTest = new Test();

            inc.ReadAllFields(readTest, BindingFlags.Public | BindingFlags.Instance);

            NetException.Assert(readTest.Number == 42);
            NetException.Assert(readTest.Name == "Hallon");
            NetException.Assert(readTest.Age == 8.2f);

            // test aligned WriteBytes/ReadBytes
            msg = peer.CreateMessage();
            byte[] tmparr = new byte[] { 5, 6, 7, 8, 9 };
            msg.Write(tmparr);

            inc = MiscTests.CreateIncomingMessage(msg.Data, msg.LengthBits);
            byte[] result = inc.ReadBytes(tmparr.Length);

            for (int i = 0; i < tmparr.Length; i++)
            {
                if (tmparr[i] != result[i])
                {
                    throw new Exception("readbytes fail");
                }
            }
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            //Span<byte> src = new byte[3] { 254, 255, 255 };
            //Span<byte> dst = new byte[3];
            //NetBitWriter.CopyBits(src, 1, 17, dst, 1);

            // TODO: check use of GetAddressBytes and optimize with span

            //Span<byte> src = new byte[] { 255, 255 }; // 0b00110010, 0b00111100 };
            //Span<byte> dst = new byte[3] { 0, 0, 0 };
            //NetBitWriter.CopyBits(src, 0, 16, dst, 9);
            //string r =
            //    Convert.ToString(dst[0], 2).PadLeft(8, '0') + "_" +
            //    Convert.ToString(dst[1], 2).PadLeft(8, '0') + "_" +
            //    Convert.ToString(dst[2], 2).PadLeft(8, '0');
            //Console.WriteLine(r);

            NetQueueTests.Run();

            BitArrayTests.Run();

            var config = new NetPeerConfiguration("unittests");

            config.EnableMessageType(NetIncomingMessageType.UnconnectedData);

            var peer = new NetPeer(config);

            peer.Start();

            peer.UPnP.DiscoverAsync().ContinueWith(async(t) =>
            {
                if (t.Result.Status == UPnPStatus.Available)
                {
                    var upnp = t.Result.UPnP;
                    int port = 9000;

                    Console.WriteLine("forwarded: " + await upnp.ForwardPortAsync(port, port, "hello"));

                    await Task.Delay(3000);

                    Console.WriteLine("deleted: " + await upnp.DeleteForwardingRuleAsync(port));
                }
            });

            Console.WriteLine("Unique identifier is " + NetUtility.ToHexString(peer.UniqueIdentifier));

            ReadWriteTests.Run(peer);

            MiscTests.Run();

            NetStreamingMessageTest.Run();

            //NetStreamTests.Run();

            //EncryptionTests.Run(peer);

            Console.WriteLine();

            // create threads that read all messages to test concurrency
            int readTimeout = 5000;
            var readThreads = new List <Thread>();

            for (int i = 0; i < 100; i++)
            {
                var thread = new Thread(() =>
                {
                    void Peer_ErrorMessage(NetPeer sender, NetLogLevel level, in NetLogMessage message)
                    {
                        Console.WriteLine("Peer " + level + ": " + message.Code);
                    }
                    peer.DebugMessage   += Peer_ErrorMessage;
                    peer.WarningMessage += Peer_ErrorMessage;
                    peer.ErrorMessage   += Peer_ErrorMessage;

                    while (peer.TryReadMessage(readTimeout, out var message))
                    {
                        switch (message.MessageType)
                        {
                        case NetIncomingMessageType.Error:
                            throw new Exception("Received error!");

                        case NetIncomingMessageType.Data:
                            Console.WriteLine("Data: " + message.ReadString());
                            break;

                        case NetIncomingMessageType.UnconnectedData:
                            Console.WriteLine("UnconnectedData: " + message.ReadString());
                            break;

                        default:
                            Console.WriteLine(message.MessageType);
                            break;
                        }
                    }
                });
                thread.Start();
                readThreads.Add(thread);
            }

            var om = peer.CreateMessage("henlo from myself");

            peer.SendUnconnectedMessage(om, new IPEndPoint(IPAddress.Loopback, peer.Port));
            try
            {
                peer.SendUnconnectedMessage(om, new IPEndPoint(IPAddress.Loopback, peer.Port));

                Console.WriteLine(nameof(CannotResendException) + " check failed");
            }
            catch (CannotResendException)
            {
                Console.WriteLine(nameof(CannotResendException) + " check OK");
            }

            Console.WriteLine($"Waiting for messages with {readTimeout}ms timeout...");
            foreach (var thread in readThreads)
            {
                thread.Join();
            }

            Console.WriteLine();
            Console.WriteLine("Tests finished");
        }
        public static void Run(NetPeer peer)
        {
            //
            // Test encryption
            //
            List <NetEncryption> algos = new List <NetEncryption>();

            algos.Add(new NetXorEncryption(peer, "TopSecret"));
            algos.Add(new NetXtea(peer, "TopSecret"));
            algos.Add(new NetAESEncryption(peer, "TopSecret"));
            algos.Add(new NetRC2Encryption(peer, "TopSecret"));
            algos.Add(new NetDESEncryption(peer, "TopSecret"));
            algos.Add(new NetTripleDESEncryption(peer, "TopSecret"));

            foreach (var algo in algos)
            {
                NetOutgoingMessage om = peer.CreateMessage();
                om.Write("Hallon");
                om.Write(42);
                om.Write(5, 5);
                om.Write(true);
                om.Write("kokos");
                int unencLen = om.LengthBits;
                om.Encrypt(algo);

                // convert to incoming message
                NetIncomingMessage im = MiscTests.CreateIncomingMessage(om.PeekDataBuffer(), om.LengthBits);
                if (im.Data == null || im.Data.Length == 0)
                {
                    throw new NetException("bad im!");
                }

                im.Decrypt(algo);

                if (im.Data == null || im.Data.Length == 0 || im.LengthBits != unencLen)
                {
                    throw new NetException("Length fail");
                }

                var str = im.ReadString();
                if (str != "Hallon")
                {
                    throw new NetException("fail");
                }
                if (im.ReadInt32() != 42)
                {
                    throw new NetException("fail");
                }
                if (im.ReadInt32(5) != 5)
                {
                    throw new NetException("fail");
                }
                if (im.ReadBoolean() != true)
                {
                    throw new NetException("fail");
                }
                if (im.ReadString() != "kokos")
                {
                    throw new NetException("fail");
                }

                TestContext.Out.WriteLine(algo.GetType().Name + " encryption verified");
            }

            for (int i = 0; i < 100; i++)
            {
                byte[] salt = NetSRP.CreateRandomSalt();
                byte[] x    = NetSRP.ComputePrivateKey("user", "password", salt);

                byte[] v = NetSRP.ComputeServerVerifier(x);
                //Console.WriteLine("v = " + NetUtility.ToHexString(v));

                byte[] a = NetSRP.CreateRandomEphemeral();                 //  NetUtility.ToByteArray("393ed364924a71ba7258633cc4854d655ca4ec4e8ba833eceaad2511e80db2b5");
                byte[] A = NetSRP.ComputeClientEphemeral(a);
                //Console.WriteLine("A = " + NetUtility.ToHexString(A));

                byte[] b = NetSRP.CreateRandomEphemeral();                 // NetUtility.ToByteArray("cc4d87a90db91067d52e2778b802ca6f7d362490c4be294b21b4a57c71cf55a9");
                byte[] B = NetSRP.ComputeServerEphemeral(b, v);
                //Console.WriteLine("B = " + NetUtility.ToHexString(B));

                byte[] u = NetSRP.ComputeU(A, B);
                //Console.WriteLine("u = " + NetUtility.ToHexString(u));

                byte[] Ss = NetSRP.ComputeServerSessionValue(A, v, u, b);
                //Console.WriteLine("Ss = " + NetUtility.ToHexString(Ss));

                byte[] Sc = NetSRP.ComputeClientSessionValue(B, x, u, a);
                //Console.WriteLine("Sc = " + NetUtility.ToHexString(Sc));

                if (Ss.Length != Sc.Length)
                {
                    throw new NetException("SRP non matching lengths!");
                }

                for (int j = 0; j < Ss.Length; j++)
                {
                    if (Ss[j] != Sc[j])
                    {
                        throw new NetException("SRP non matching session values!");
                    }
                }

                var test = NetSRP.CreateEncryption(peer, Ss);
            }

            TestContext.Out.WriteLine("Message encryption OK");
        }