Skip to content

Commit

Permalink
Small networking changes
Browse files Browse the repository at this point in the history
  • Loading branch information
DaXcess committed Sep 1, 2024
1 parent 7cc551d commit 72e9603
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
11 changes: 9 additions & 2 deletions Source/Networking/NetworkSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ namespace LCVR.Networking;
public class NetworkSystem : MonoBehaviour
{
/// Protocol Version, increase this every time a change is made that is not compatible with older versions
private const ushort PROTOCOL_VERSION = 6;
private const ushort PROTOCOL_VERSION = 7;

/// Packet size limit to prevent denial-of-service attacks
private const uint PACKET_MAX_SIZE = 4 * 1024;

private static NetworkSystem _instance;

Expand Down Expand Up @@ -298,7 +301,11 @@ private void HandleChannelMessage(ushort sender, BinaryReader reader)
if (!channels.TryGetValue(type, out var channelList))
return;

var data = reader.ReadBytes((int)reader.ReadUInt32());
var length = reader.ReadUInt32();
if (length > PACKET_MAX_SIZE)
return;

var data = reader.ReadBytes((int)length);

if (instanceId.HasValue)
channelList.Where(channel => channel.InstanceId == instanceId.Value)
Expand Down
9 changes: 9 additions & 0 deletions Source/Networking/Serialization.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ namespace LCVR.Networking;
/// </summary>
public static class Serialization
{
private const uint MAX_ARRAY_LENGTH = 4096;

private static readonly Dictionary<Type, FieldInfo[]> typeCache = [];

private static IEnumerable<FieldInfo> GetFields(Type type)
Expand Down Expand Up @@ -68,6 +70,9 @@ public static byte[] Serialize(object @object)
if (value.GetType().IsArray)
{
var array = (Array)value;
if (array.Length > MAX_ARRAY_LENGTH)
throw new ArgumentException($"Tried to serialize an array larger than {MAX_ARRAY_LENGTH} elements");

bw.Write(array.Length);

foreach (var arrayEl in array)
Expand Down Expand Up @@ -113,6 +118,10 @@ private static object DeserializeInternal(BinaryReader br, Type type)
if (field.FieldType.IsArray)
{
var size = br.ReadInt32();
if (size > MAX_ARRAY_LENGTH)
throw new ArgumentException(
$"Tried to deserialize an array larger than {MAX_ARRAY_LENGTH} elements");

var targetArray = Array.CreateInstance(field.FieldType.GetElementType()!, size);

for (var i = 0; i < size; i++)
Expand Down

0 comments on commit 72e9603

Please sign in to comment.