public void TestText()
        {
            var algorithm  = new NetAesGcmEncryption(Peer);
            var outMessage = Peer.CreateMessage();

            outMessage.Write(LoremIpsumShort);

            var outBits = outMessage.LengthBits;

            var encryptSuccess = outMessage.Encrypt(algorithm);

            Assert.IsTrue(encryptSuccess, $"Failed to encrypt [length={LoremIpsumShort.Length}]");

            var inMessage = outMessage.ToIncomingMessage();

            Assert.IsNotNull(inMessage.Data);
            Assert.IsNotEmpty(inMessage.Data);

            var decryptSuccess = inMessage.Decrypt(algorithm);

            Assert.IsTrue(decryptSuccess, "Failed to decrypt");
            Assert.IsNotNull(inMessage.Data);
            Assert.IsNotEmpty(inMessage.Data);
            Assert.AreEqual(outBits, inMessage.LengthBits);

            var inText = inMessage.ReadString();

            Assert.AreEqual(LoremIpsumShort, inText, $"Expected '{LoremIpsumShort}' received '{inText}'.");
        }
Example #2
0
        private void SendExpandMTU(TimeSpan now, int size)
        {
            NetOutgoingMessage om = Peer.CreateMessage();

            om.WritePadBytes(size);
            om._messageType = NetMessageType.ExpandMTURequest;
            int length = 0;

            om.Encode(Peer._sendBuffer, ref length, 0);
            Peer.Recycle(om);

            if (!Peer.SendMTUPacket(length, RemoteEndPoint))
            {
                //m_peer.LogDebug("Send MTU failed for size " + size);

                // failure
                if (_smallestFailedMTU == -1 || size < _smallestFailedMTU)
                {
                    _smallestFailedMTU = size;
                    _mtuAttemptFails++;
                    if (_mtuAttemptFails >= _peerConfiguration.ExpandMTUFailAttempts)
                    {
                        FinalizeMTU(_largestSuccessfulMTU);
                        return;
                    }
                }
                ExpandMTU(now);
                return;
            }

            _lastSentMTUAttemptSize = size;
            _lastSentMTUAttemptTime = now;
        }
        public void TestPaddingText()
        {
            var length    = 0;
            var algorithm = new NetAesGcmEncryption(Peer);

            while (length++ < LoremIpsum.Length)
            {
                var substring  = LoremIpsum.Substring(0, length);
                var outMessage = Peer.CreateMessage();
                outMessage.Write(substring);

                var outBits = outMessage.LengthBits;

                var encryptSuccess = outMessage.Encrypt(algorithm);
                Assert.IsTrue(encryptSuccess, $"Failed to encrypt [length={length}]");

                var inMessage = outMessage.ToIncomingMessage();

                Assert.IsNotNull(inMessage.Data);
                Assert.IsNotEmpty(inMessage.Data);

                var decryptSuccess = inMessage.Decrypt(algorithm);
                Assert.IsTrue(decryptSuccess, "Failed to decrypt");
                Assert.IsNotNull(inMessage.Data);
                Assert.IsNotEmpty(inMessage.Data);
                Assert.AreEqual(outBits, inMessage.LengthBits);

                var inText = inMessage.ReadString();
                Assert.AreEqual(substring, inText, $"Expected '{substring}' received '{inText}'.");
            }
        }
Example #4
0
        internal void SendConnect(TimeSpan now)
        {
            Peer.AssertIsOnLibraryThread();

            int preAllocate = 13 + _peerConfiguration.AppIdentifier.Length;

            preAllocate += LocalHailMessage == null ? 0 : LocalHailMessage.ByteLength;

            NetOutgoingMessage om = Peer.CreateMessage(preAllocate);

            om._messageType = NetMessageType.Connect;
            om.Write(_peerConfiguration.AppIdentifier);
            om.Write(Peer.UniqueIdentifier);
            om.Write(now);

            WriteLocalHail(om);

            Peer.SendLibraryMessage(om, RemoteEndPoint);

            _connectRequested      = false;
            _lastHandshakeSendTime = now;
            _handshakeAttempts++;

            if (_handshakeAttempts > 1)
            {
                Peer.LogDebug(new NetLogMessage(NetLogCode.ResendingConnect));
            }
            SetStatus(NetConnectionStatus.InitiatedConnect);
        }
        public void TestPaddingBytes()
        {
            var bytes     = Encoding.UTF8.GetBytes(LoremIpsum);
            var length    = 0;
            var algorithm = new NetAesGcmEncryption(Peer);

            while (length++ < bytes.Length)
            {
                var outMessage = Peer.CreateMessage();
                outMessage.Write(bytes, 0, length);

                var outBits = outMessage.LengthBits;
                Assert.AreEqual(length << 3, outBits, $"Input data was {length}B ({length << 3}b), message is {outBits}b.");
                Assert.IsTrue(outMessage.Encrypt(algorithm), $"Failed to encrypt [length={length}]");

                var inMessage = outMessage.ToIncomingMessage();

                Assert.IsNotNull(inMessage.Data);
                Assert.IsNotEmpty(inMessage.Data);

                Assert.IsTrue(inMessage.Decrypt(algorithm), "Failed to decrypt");
                Assert.IsNotNull(inMessage.Data);
                Assert.IsNotEmpty(inMessage.Data);
                Assert.AreEqual(outBits, inMessage.LengthBits);

                var inData = inMessage.PeekDataBuffer();
                for (var index = 0; index < length; ++index)
                {
                    Assert.AreEqual(bytes[index], inData[index], $"Arrays differed at index {index} (out of {length}).\nExpected: {BitConverter.ToString(bytes)}\nReceived: {BitConverter.ToString(inData)}");
                }
            }
        }
Example #6
0
        public void TestEncryptorReuse(Type netEncryptionType, string key)
        {
            var algo = Activator.CreateInstance(netEncryptionType, Peer, key) as NetEncryption;

            for (var iteration = 0; iteration < 5; ++iteration)
            {
                var 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 = CreateIncomingMessage(om.PeekDataBuffer(), om.LengthBits);
                if (im.Data == null || im.Data.Length == 0)
                {
                    Assert.Fail("bad im!");
                }

                im.Decrypt(algo);

                if (im.Data == null || im.Data.Length == 0 || im.LengthBits != unencLen)
                {
                    Assert.Fail("Length fail");
                }

                var str = im.ReadString();
                if (str != "Hallon")
                {
                    Assert.Fail("fail");
                }

                if (im.ReadInt32() != 42)
                {
                    Assert.Fail("fail");
                }

                if (im.ReadInt32(5) != 5)
                {
                    Assert.Fail("fail");
                }

                if (im.ReadBoolean() != true)
                {
                    Assert.Fail("fail");
                }

                if (im.ReadString() != "kokos")
                {
                    Assert.Fail("fail");
                }
            }
        }
Example #7
0
        internal void ExecuteDisconnect(NetMessageType?reasonType)
        {
            NetOutgoingMessage?reason = null;

            if (reasonType.HasValue)
            {
                reason = Peer.CreateMessage();
                reason._messageType = reasonType.GetValueOrDefault();
            }
            ExecuteDisconnect(reason, reasonType.HasValue);
        }
Example #8
0
        private NetOutgoingMessage PrepareMessage(INetworkMessage message)
        {
            _writerStream.Clear();
            MessageTable.Serialize(_writerStream, message);

            var length = (int)_writerStream.Length;

            var msg = Peer.CreateMessage(length);

            msg.Write(_writerStream.GetBuffer(), 0, length);

            return(msg);
        }
Example #9
0
        private void SendMTUSuccess(int size)
        {
            NetOutgoingMessage om = Peer.CreateMessage();

            om.Write(size);
            om._messageType = NetMessageType.ExpandMTUSuccess;
            int length = 0;

            om.Encode(Peer._sendBuffer, ref length, 0);
            Peer.Recycle(om);

            Peer.SendPacket(length, RemoteEndPoint, 1);

            //m_peer.LogDebug("Received MTU expand request for " + size + " bytes");
        }
Example #10
0
        internal void SendConnectionEstablished()
        {
            NetOutgoingMessage om = Peer.CreateMessage();

            om._messageType = NetMessageType.ConnectionEstablished;
            om.Write(NetTime.Now);
            Peer.SendLibraryMessage(om, RemoteEndPoint);

            _handshakeAttempts = 0;

            InitializePing();
            if (Status != NetConnectionStatus.Connected)
            {
                SetStatus(NetConnectionStatus.Connected);
            }
        }
Example #11
0
        public void Update(GameTime time)
        {
            NetIncomingMessage im;

            while ((im = Peer.ReadMessage()) != null)
            {
                switch (im.MessageType)
                {
                case NetIncomingMessageType.StatusChanged:
                    NetConnectionStatus status = (NetConnectionStatus)im.ReadByte();

                    string reason = im.ReadString();

                    if (!GameRunning && status == NetConnectionStatus.Connected)
                    {
                        Sync.AddConnection(im.SenderConnection);
                        NewConnection?.Invoke(this, im.SenderConnection);
                    }

                    break;

                case NetIncomingMessageType.DiscoveryRequest:
                    // Respond to discovery requests with a json-serialized game info
                    // But only send the non-secret parts
                    var publicInfo     = GameInfo.PublicInfo();
                    var serializedInfo = JsonConvert.SerializeObject(publicInfo);
                    var response       = Peer.CreateMessage();
                    response.Write(serializedInfo);
                    Peer.SendDiscoveryResponse(response, im.SenderEndPoint);
                    break;

                case NetIncomingMessageType.Data:
                    Sync.ReadMessage(im);
                    break;
                }

                Peer.Recycle(im);
            }

            if (GameRunning && WorldSyncTimer.ElapsedMilliseconds > Network.WorldSyncIntervalMs)
            {
                // Send full world state on every frame.
                //Todo: Only send updates for world synchronization
                SendWorldState();
                WorldSyncTimer.Restart();
            }
        }
        public bool Connect(IPEndPoint endPoint)
        {
            if (Peer.Status == NetPeerStatus.NotRunning)
            {
                Open();
            }

            NetOutgoingMessage hail = Peer.CreateMessage();

            hail.Write(AppInfo.Version.ToString());
            Peer.Connect(endPoint, hail);

            int timeout = (int)((Peer.Configuration.ConnectionTimeout + 1) * 1000);

            return(_connectWaitHandle.WaitOne(timeout) &&
                   Peer.ConnectionStatus == NetConnectionStatus.Connected);
        }
Example #13
0
        public override void SendMessage(INetworkMessage message, DeliveryMethod method, int sequenceChannel)
        {
            if (ConnectionStatus != Networking.ConnectionStatus.Connected)
            {
                return;
            }

            _writerStream.Clear();
            MessageTable.Serialize(_writerStream, message);

            var length = (int)_writerStream.Length;

            var msg = Peer.CreateMessage(length);

            msg.Write(_writerStream.GetBuffer(), 0, length);

            Peer.SendMessage(msg, (NetDeliveryMethod)method, sequenceChannel);
        }
Example #14
0
        internal void SendDisconnect(NetOutgoingMessage?message, bool onLibraryThread)
        {
            if (onLibraryThread)
            {
                Peer.AssertIsOnLibraryThread();
            }

            if (message == null)
            {
                message = Peer.CreateMessage();
                message._messageType = NetMessageType.Disconnect;
            }

            if (onLibraryThread)
            {
                Peer.SendLibraryMessage(message, RemoteEndPoint);
            }
            else
            {
                Peer.UnsentUnconnectedMessages.Enqueue((RemoteEndPoint, message));
            }
        }
        public void TestShutdownMessageWithDebugString()
        {
            Assert.AreEqual(NetPeerStatus.Running, Peer.Status);
            Assert.IsNotNull(Connection);

            TestHelper.WaitForConnection(Connection);
            TestHelper.WaitFor(() => Server.ConnectionsCount != 0);

            var testString      = $"{nameof(TestShutdownMessage)}_{new CryptoRandom().NextUInt64()}";
            var outgoingMessage = Peer.CreateMessage();

            outgoingMessage.Write(testString);
            Peer.Shutdown(outgoingMessage, "debugMessage");

            TestHelper.WaitFor(() => Server.ConnectionsCount == 0);
            TestHelper.HasMessage(
                PeerMessages,
                NetIncomingMessageType.DebugMessage,
                message =>
                string.Equals(
                    "Shutdown requested (debugMessage)",
                    message.ReadString(),
                    StringComparison.Ordinal
                    )
                );

            var messageShutdownReason = ServerMessages.Last(
                message => NetIncomingMessageType.StatusChanged == message.MessageType
                );

            Assert.IsNotNull(messageShutdownReason);
            var status = (NetConnectionStatus)messageShutdownReason.ReadByte();

            Assert.AreEqual(NetConnectionStatus.Disconnected, status);
            Assert.AreEqual(testString, messageShutdownReason.ReadString());
        }
Example #16
0
        internal void SendConnectResponse(TimeSpan now, bool onLibraryThread)
        {
            if (onLibraryThread)
            {
                Peer.AssertIsOnLibraryThread();
            }

            NetOutgoingMessage om = Peer.CreateMessage(
                _peerConfiguration.AppIdentifier.Length + 13 +
                (LocalHailMessage == null ? 0 : LocalHailMessage.ByteLength));

            om._messageType = NetMessageType.ConnectResponse;
            om.Write(_peerConfiguration.AppIdentifier);
            om.Write(Peer.UniqueIdentifier);
            om.Write(now);

            WriteLocalHail(om);

            if (onLibraryThread)
            {
                Peer.SendLibraryMessage(om, RemoteEndPoint);
            }
            else
            {
                Peer.UnsentUnconnectedMessages.Enqueue((RemoteEndPoint, om));
            }

            _lastHandshakeSendTime = now;
            _handshakeAttempts++;

            if (_handshakeAttempts > 1)
            {
                Peer.LogDebug(new NetLogMessage(NetLogCode.ResendingRespondedConnect));
            }
            SetStatus(NetConnectionStatus.RespondedConnect);
        }
Example #17
0
        public void TestReadWrite()
        {
            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(ulong.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)
            {
                Assert.Fail("WriteVariable* wrote too many bytes!");
            }

            byte[] data = msg.Data;

            NetIncomingMessage inc = 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);

            if (ok == false)
            {
                Assert.Fail("Read/write failure");
            }

            bdr.Append(strResult);

            bdr.Append(inc.ReadByte());

            if (inc.PeekUInt16() != 44)
            {
                Assert.Fail("Read/write failure");
            }

            bdr.Append(inc.ReadUInt16());

            if (inc.PeekUInt64(64) != ulong.MaxValue)
            {
                Assert.Fail("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"))
            {
                // Console.WriteLine("Read/write tests OK");
            }
            else
            {
                Assert.Fail("Read/write tests FAILED!");
            }

            msg = Peer.CreateMessage();

            NetOutgoingMessage tmp = Peer.CreateMessage();

            tmp.Write(42, 14);

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

            if (msg.LengthBits != tmp.LengthBits * 2)
            {
                Assert.Fail("NetOutgoingMessage.Write(NetOutgoingMessage) failed!");
            }

            tmp = Peer.CreateMessage();

            var test = new Test {
                Number = 42, Name = "Hallon", Age = 8.2f
            };

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

            data = tmp.Data;

            inc = CreateIncomingMessage(data, tmp.LengthBits);

            var 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 = { 5, 6, 7, 8, 9 };
            msg.Write(tmparr);

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

            for (int i = 0; i < tmparr.Length; i++)
            {
                if (tmparr[i] != result[i])
                {
                    Assert.Fail("readbytes fail");
                }
            }
        }
 private NetOutgoingMessage CreateMessage <T>(T instanceToSend)
 {
     return(Peer.CreateMessage(SerializationAdapter.SerializeObject(instanceToSend)));
 }