Checking buffer length is atleast 2 (#2433)

* checking buffer length is atleast 2

disconnect if invalid message

* using const instead of magic number

Adding test to make sure that writing id is the same size as IdSize

* adding comment

* renaming to HeaderSize
This commit is contained in:
James Frowen 2020-11-21 03:41:35 +00:00 committed by GitHub
parent 995fd06a77
commit 2bd6675d19
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 2 deletions

View File

@ -18,6 +18,11 @@ public static class MessagePacker
{
static readonly ILogger logger = LogFactory.GetLogger(typeof(MessagePacker));
/// <summary>
/// this is the minimum size of a message that mirror will accept
/// </summary>
internal const int HeaderSize = sizeof(ushort);
public static int GetId<T>() where T : struct, NetworkMessage
{
// paul: 16 bits is enough to avoid collisions

View File

@ -233,9 +233,10 @@ public bool InvokeHandler<T>(T msg, int channelId)
/// <param name="buffer">The data received.</param>
internal void TransportReceive(ArraySegment<byte> buffer, int channelId)
{
if (buffer.Count == 0)
if (buffer.Count < MessagePacker.HeaderSize)
{
logger.LogError($"ConnectionRecv {this} Message was empty");
logger.LogError($"ConnectionRecv {this} Message was too short (messages should start with message id)");
Disconnect();
return;
}

View File

@ -5,6 +5,8 @@ namespace Mirror.Tests
[TestFixture]
public class MessagePackerTest
{
public struct EmptyMessage : NetworkMessage { }
// helper function to pack message into a simple byte[]
public static byte[] PackToByteArray<T>(T message)
where T : struct, NetworkMessage
@ -113,5 +115,16 @@ public void UnpackInvalidMessage()
Assert.That(result2, Is.EqualTo(false));
Assert.That(msgType2, Is.EqualTo(0));
}
[Test]
public void MessageIdIsCorrectLength()
{
NetworkWriter writer = new NetworkWriter();
MessagePacker.Pack(new EmptyMessage(), writer);
ArraySegment<byte> segment = writer.ToArraySegment();
Assert.That(segment.Count, Is.EqualTo(MessagePacker.HeaderSize), "Empty message should have same size as HeaderSize");
}
}
}