read packet with BinaryReader

This commit is contained in:
Sardelka
2022-08-06 11:40:38 +08:00
parent 4e33956acd
commit ca5ef8cf4c
19 changed files with 219 additions and 220 deletions

View File

@ -15,13 +15,13 @@ namespace RageCoop.Client
switch (t)
{
case 50:
return EntityPool.ServerProps[reader.ReadInt()].MainProp?.Handle;
return EntityPool.ServerProps[reader.ReadInt32()].MainProp?.Handle;
case 51:
return EntityPool.GetPedByID(reader.ReadInt())?.MainPed?.Handle;
return EntityPool.GetPedByID(reader.ReadInt32())?.MainPed?.Handle;
case 52:
return EntityPool.GetVehicleByID(reader.ReadInt())?.MainVehicle?.Handle;
return EntityPool.GetVehicleByID(reader.ReadInt32())?.MainVehicle?.Handle;
case 60:
return EntityPool.ServerBlips[reader.ReadInt()].Handle;
return EntityPool.ServerBlips[reader.ReadInt32()].Handle;
default:
throw new ArgumentException("Cannot resolve server side argument: "+t);

View File

@ -2,116 +2,30 @@
using System.Text;
using System.Linq;
using GTA.Math;
using System.IO;
namespace RageCoop.Core
{
internal class BitReader
internal class BitReader:BinaryReader
{
public int CurrentIndex { get; set; }
private byte[] ResultArray;
public BitReader(byte[] array)
public BitReader(byte[] array):base(new MemoryStream(array))
{
CurrentIndex = 0;
ResultArray = array;
}
~BitReader()
{
ResultArray = null;
Close();
Dispose();
}
public bool CanRead(int bytes)
{
return ResultArray.Length >= CurrentIndex + bytes;
}
public bool ReadBool()
{
bool value = BitConverter.ToBoolean(ResultArray, CurrentIndex);
CurrentIndex += 1;
return value;
}
public float ReadFloat()
{
float value = BitConverter.ToSingle(ResultArray, CurrentIndex);
CurrentIndex += 4;
return value;
}
public byte ReadByte()
{
byte value = ResultArray[CurrentIndex];
CurrentIndex += 1;
return value;
}
public byte[] ReadByteArray(int length)
{
byte[] value = new byte[length];
Array.Copy(ResultArray, CurrentIndex,value,0,length);
CurrentIndex += length;
return value;
}
public byte[] ReadByteArray()
{
return ReadByteArray(ReadInt());
return base.ReadBytes(ReadInt32());
}
public short ReadShort()
public override string ReadString()
{
short value = BitConverter.ToInt16(ResultArray, CurrentIndex);
CurrentIndex += 2;
return value;
}
public ushort ReadUShort()
{
ushort value = BitConverter.ToUInt16(ResultArray, CurrentIndex);
CurrentIndex += 2;
return value;
}
public int ReadInt()
{
int value = BitConverter.ToInt32(ResultArray, CurrentIndex);
CurrentIndex += 4;
return value;
}
public uint ReadUInt()
{
uint value = BitConverter.ToUInt32(ResultArray, CurrentIndex);
CurrentIndex += 4;
return value;
}
public long ReadLong()
{
long value = BitConverter.ToInt64(ResultArray, CurrentIndex);
CurrentIndex += 8;
return value;
}
public ulong ReadULong()
{
ulong value = BitConverter.ToUInt64(ResultArray, CurrentIndex);
CurrentIndex += 8;
return value;
}
public string ReadString(int index)
{
string value = Encoding.UTF8.GetString(ResultArray.Skip(CurrentIndex).Take(index).ToArray());
CurrentIndex += index;
return value;
}
public string ReadString()
{
var len = ReadInt();
string value = Encoding.UTF8.GetString(ResultArray.Skip(CurrentIndex).Take(len).ToArray());
CurrentIndex += len;
string value = Encoding.UTF8.GetString(ReadBytes(ReadInt32()));
return value;
}
@ -119,27 +33,27 @@ namespace RageCoop.Core
{
return new Vector3()
{
X = ReadFloat(),
Y = ReadFloat(),
Z = ReadFloat()
X = ReadSingle(),
Y = ReadSingle(),
Z = ReadSingle()
};
}
public Vector2 ReadVector2()
{
return new Vector2()
{
X = ReadFloat(),
Y = ReadFloat()
X = ReadSingle(),
Y = ReadSingle()
};
}
public Quaternion ReadQuaternion()
{
return new Quaternion()
{
X = ReadFloat(),
Y = ReadFloat(),
Z = ReadFloat(),
W = ReadFloat()
X = ReadSingle(),
Y = ReadSingle(),
Z = ReadSingle(),
W = ReadSingle()
};
}
}

View File

@ -66,6 +66,91 @@ namespace RageCoop.Core
return (0x0, null);
}
}
public static IPEndPoint StringToEndPoint(string endpointstring)
{
return StringToEndPoint(endpointstring, -1);
}
public static IPEndPoint StringToEndPoint(string endpointstring, int defaultport)
{
if (string.IsNullOrEmpty(endpointstring)
|| endpointstring.Trim().Length == 0)
{
throw new ArgumentException("Endpoint descriptor may not be empty.");
}
if (defaultport != -1 &&
(defaultport < IPEndPoint.MinPort
|| defaultport > IPEndPoint.MaxPort))
{
throw new ArgumentException(string.Format("Invalid default port '{0}'", defaultport));
}
string[] values = endpointstring.Split(new char[] { ':' });
IPAddress ipaddy;
int port = -1;
//check if we have an IPv6 or ports
if (values.Length <= 2) // ipv4 or hostname
{
if (values.Length == 1)
//no port is specified, default
port = defaultport;
else
port = getPort(values[1]);
//try to use the address as IPv4, otherwise get hostname
if (!IPAddress.TryParse(values[0], out ipaddy))
ipaddy = getIPfromHost(values[0]);
}
else if (values.Length > 2) //ipv6
{
//could [a:b:c]:d
if (values[0].StartsWith("[") && values[values.Length - 2].EndsWith("]"))
{
string ipaddressstring = string.Join(":", values.Take(values.Length - 1).ToArray());
ipaddy = IPAddress.Parse(ipaddressstring);
port = getPort(values[values.Length - 1]);
}
else //[a:b:c] or a:b:c
{
ipaddy = IPAddress.Parse(endpointstring);
port = defaultport;
}
}
else
{
throw new FormatException(string.Format("Invalid endpoint ipaddress '{0}'", endpointstring));
}
if (port == -1)
throw new ArgumentException(string.Format("No port specified: '{0}'", endpointstring));
return new IPEndPoint(ipaddy, port);
}
private static int getPort(string p)
{
int port;
if (!int.TryParse(p, out port)
|| port < IPEndPoint.MinPort
|| port > IPEndPoint.MaxPort)
{
throw new FormatException(string.Format("Invalid end point port '{0}'", p));
}
return port;
}
private static IPAddress getIPfromHost(string p)
{
var hosts = Dns.GetHostAddresses(p);
if (hosts == null || hosts.Length == 0)
throw new ArgumentException(string.Format("Host not found: {0}", p));
return hosts[0];
}
}
internal static class Extensions
@ -111,6 +196,10 @@ namespace RageCoop.Core
{
bytes.AddRange(BitConverter.GetBytes(i));
}
public static void AddBool(this List<byte> bytes, bool b)
{
bytes.Add(b? (byte)1 :(byte)0);
}
public static void AddString(this List<byte> bytes, string s)
{
var sb = Encoding.UTF8.GetBytes(s);

View File

@ -49,8 +49,7 @@ namespace RageCoop.Core
BitReader reader = new BitReader(array);
// Read username
int usernameLength = reader.ReadInt();
Username = reader.ReadString(usernameLength);
Username = reader.ReadString();
Message = decrypt(reader.ReadByteArray()).GetString();
#endregion

View File

@ -45,8 +45,8 @@ namespace RageCoop.Core
{
BitReader reader = new BitReader(array);
Hash = reader.ReadInt();
var len=reader.ReadInt();
Hash = reader.ReadInt32();
var len=reader.ReadInt32();
Args=new object[len];
for (int i = 0; i < len; i++)
{
@ -56,21 +56,21 @@ namespace RageCoop.Core
case 0x01:
Args[i]=reader.ReadByte(); break;
case 0x02:
Args[i]=reader.ReadShort(); break;
Args[i]=reader.ReadInt32(); break;
case 0x03:
Args[i]=reader.ReadUShort(); break;
Args[i]=reader.ReadUInt16(); break;
case 0x04:
Args[i]=reader.ReadInt(); break;
Args[i]=reader.ReadInt32(); break;
case 0x05:
Args[i]=reader.ReadUInt(); break;
Args[i]=reader.ReadUInt32(); break;
case 0x06:
Args[i]=reader.ReadLong(); break;
Args[i]=reader.ReadInt64(); break;
case 0x07:
Args[i]=reader.ReadULong(); break;
Args[i]=reader.ReadUInt64(); break;
case 0x08:
Args[i]=reader.ReadFloat(); break;
Args[i]=reader.ReadSingle(); break;
case 0x09:
Args[i]=reader.ReadBool(); break;
Args[i]=reader.ReadBoolean(); break;
case 0x10:
Args[i]=reader.ReadString(); break;
case 0x11:
@ -78,7 +78,7 @@ namespace RageCoop.Core
case 0x12:
Args[i]=reader.ReadQuaternion(); break;
case 0x13:
Args[i]=(GTA.Model)reader.ReadInt(); break;
Args[i]=(GTA.Model)reader.ReadInt32(); break;
case 0x14:
Args[i]=reader.ReadVector2(); break;
default:

View File

@ -48,14 +48,11 @@ namespace RageCoop.Core
public override void Deserialize(byte[] array)
{
#region NetIncomingMessageToPacket
BitReader reader = new BitReader(array);
ID = reader.ReadInt();
int nameArrayLength = reader.ReadInt();
Name = reader.ReadString(nameArrayLength);
FileLength = reader.ReadLong();
#endregion
ID = reader.ReadInt32();
Name = reader.ReadString();
FileLength = reader.ReadInt64();
}
}
@ -81,7 +78,7 @@ namespace RageCoop.Core
{
BitReader reader = new BitReader(array);
ID = reader.ReadInt();
ID = reader.ReadInt32();
Response = (FileResponse)reader.ReadByte();
}
}
@ -110,13 +107,10 @@ namespace RageCoop.Core
public override void Deserialize(byte[] array)
{
#region NetIncomingMessageToPacket
BitReader reader = new BitReader(array);
ID = reader.ReadInt();
int chunkLength = reader.ReadInt();
FileChunk = reader.ReadByteArray(chunkLength);
#endregion
ID = reader.ReadInt32();
FileChunk = reader.ReadByteArray();
}
}
@ -138,25 +132,15 @@ namespace RageCoop.Core
public override void Deserialize(byte[] array)
{
#region NetIncomingMessageToPacket
BitReader reader = new BitReader(array);
ID = reader.ReadInt();
#endregion
ID = reader.ReadInt32();
}
}
internal class AllResourcesSent : Packet
{
public override PacketType Type => PacketType.AllResourcesSent;
public override byte[] Serialize()
{
return new byte[0];
}
public override void Deserialize(byte[] array)
{
}
}
}
}

View File

@ -1,21 +1,40 @@
using System;
using System.Collections.Generic;
using Lidgren.Network;
using System.Net;
namespace RageCoop.Core
{
internal partial class Packets
{
/// <summary>
/// Used to measure the connection latency
/// </summary>
internal class PingPong : Packet
{
public override PacketType Type => PacketType.PingPong;
}
/// <summary>
/// Request direct connection to another client
/// </summary>
internal class ConnectionRequest : Packet
{
public int TargetID { get; set; }
public IPEndPoint InternalEndPoint { get; set; }
public override PacketType Type => PacketType.ConnectionRequest;
public override byte[] Serialize()
{
return new byte[0];
var data=new List<byte>(10);
data.AddInt(TargetID);
data.AddString(InternalEndPoint.ToString());
return data.ToArray();
}
public override void Deserialize(byte[] array)
{
var reader=new BitReader(array);
TargetID = reader.ReadInt32();
InternalEndPoint=CoreUtils.StringToEndPoint(reader.ReadString());
}
}
}

View File

@ -28,6 +28,8 @@ namespace RageCoop.Core
CustomEvent = 16,
CustomEventQueued = 17,
ConnectionRequest=18,
#region Sync
#region INTERVAL
@ -146,7 +148,11 @@ namespace RageCoop.Core
internal abstract class Packet : IPacket
{
public abstract PacketType Type { get; }
public abstract byte[] Serialize();
public virtual byte[] Serialize()
{
return new byte[0];
}
public virtual void Deserialize(byte[] array) { }
public void Pack(NetOutgoingMessage message)
{
var d=Serialize();
@ -154,6 +160,5 @@ namespace RageCoop.Core
message.Write(d.Length);
message.Write(d);
}
public abstract void Deserialize(byte[] array);
}
}

View File

@ -153,15 +153,15 @@ namespace RageCoop.Core
BitReader reader = new BitReader(array);
// Read player netHandle
ID = reader.ReadInt();
ID = reader.ReadInt32();
OwnerID=reader.ReadInt();
OwnerID=reader.ReadInt32();
// Read player flags
Flags = (PedDataFlags)reader.ReadUShort();
Flags = (PedDataFlags)reader.ReadUInt16();
// Read player health
Health = reader.ReadInt();
Health = reader.ReadInt32();
if (Flags.HasPedFlag(PedDataFlags.IsRagdoll))
{
@ -186,7 +186,7 @@ namespace RageCoop.Core
Speed = reader.ReadByte();
// Read player weapon hash
CurrentWeaponHash = reader.ReadUInt();
CurrentWeaponHash = reader.ReadUInt32();
// Try to read aim coords
if (Flags.HasPedFlag(PedDataFlags.IsAiming))
@ -195,24 +195,24 @@ namespace RageCoop.Core
AimCoords = reader.ReadVector3();
}
Heading=reader.ReadFloat();
Heading=reader.ReadSingle();
if (Flags.HasPedFlag(PedDataFlags.IsFullSync))
{
// Read player model hash
ModelHash = reader.ReadInt();
ModelHash = reader.ReadInt32();
// Read player clothes
Clothes =reader.ReadByteArray(36);
Clothes =reader.ReadBytes(36);
// Read player weapon components
if (reader.ReadBool())
if (reader.ReadBoolean())
{
WeaponComponents = new Dictionary<uint, bool>();
ushort comCount = reader.ReadUShort();
ushort comCount = reader.ReadUInt16();
for (ushort i = 0; i < comCount; i++)
{
WeaponComponents.Add(reader.ReadUInt(), reader.ReadBool());
WeaponComponents.Add(reader.ReadUInt32(), reader.ReadBoolean());
}
}
WeaponTint=reader.ReadByte();
@ -221,8 +221,8 @@ namespace RageCoop.Core
if ((byte)BlipColor!=255)
{
BlipSprite=(BlipSprite)reader.ReadUShort();
BlipScale=reader.ReadFloat();
BlipSprite=(BlipSprite)reader.ReadUInt16();
BlipScale=reader.ReadSingle();
}
}
#endregion

View File

@ -70,13 +70,13 @@ namespace RageCoop.Core
BitReader reader = new BitReader(array);
// Read player netHandle
PedID = reader.ReadInt();
PedID = reader.ReadInt32();
// Read Username
Username = reader.ReadString(reader.ReadInt());
Username = reader.ReadString();
// Read ModVersion
ModVersion = reader.ReadString(reader.ReadInt());
ModVersion = reader.ReadString();
AesKeyCrypted=reader.ReadByteArray();
@ -121,11 +121,10 @@ namespace RageCoop.Core
BitReader reader = new BitReader(array);
// Read player netHandle
PedID = reader.ReadInt();
PedID = reader.ReadInt32();
// Read Username
int usernameLength = reader.ReadInt();
Username = reader.ReadString(usernameLength);
Username = reader.ReadString();
#endregion
}
}
@ -150,7 +149,7 @@ namespace RageCoop.Core
#region NetIncomingMessageToPacket
BitReader reader = new BitReader(array);
PedID = reader.ReadInt();
PedID = reader.ReadInt32();
#endregion
}
}
@ -193,13 +192,12 @@ namespace RageCoop.Core
BitReader reader = new BitReader(array);
// Read player ID
PedID = reader.ReadInt();
PedID = reader.ReadInt32();
// Read Username
int usernameLength = reader.ReadInt();
Username = reader.ReadString(usernameLength);
Username = reader.ReadString();
Latency=reader.ReadFloat();
Latency=reader.ReadSingle();
}
}
@ -236,14 +234,6 @@ namespace RageCoop.Core
public class PublicKeyRequest : Packet
{
public override PacketType Type => PacketType.PublicKeyRequest;
public override byte[] Serialize()
{
return new byte[0];
}
public override void Deserialize(byte[] array)
{
}
}
}
}

View File

@ -48,8 +48,7 @@ namespace RageCoop.Core
// Write velocity
byteArray.AddVector3(Velocity);
if (Exploded) { byteArray.Add(1); }
byteArray.Add(Exploded?(byte)1:(byte)0);
return byteArray.ToArray();
@ -61,12 +60,12 @@ namespace RageCoop.Core
BitReader reader = new BitReader(array);
// Read id
ID = reader.ReadInt();
ID = reader.ReadInt32();
// Read ShooterID
ShooterID= reader.ReadInt();
ShooterID= reader.ReadInt32();
WeaponHash= reader.ReadUInt();
WeaponHash= reader.ReadUInt32();
// Read position
Position = reader.ReadVector3();
@ -77,7 +76,7 @@ namespace RageCoop.Core
// Read velocity
Velocity =reader.ReadVector3();
if (reader.CanRead(1))
if (reader.ReadBoolean())
{
Exploded=true;
}

View File

@ -47,10 +47,10 @@ namespace RageCoop.Core
BitReader reader = new BitReader(array);
// Read OwnerID
OwnerID=reader.ReadInt();
OwnerID=reader.ReadInt32();
// Read WeponHash
WeaponHash=reader.ReadUInt();
WeaponHash=reader.ReadUInt32();
// Read StartPosition
StartPosition=reader.ReadVector3();

View File

@ -24,7 +24,7 @@ namespace RageCoop.Core
byteArray.AddInt(PedID);
byteArray.AddInt(VehicleID);
byteArray.AddInt(VehicleSeat);
byteArray.AddShort(VehicleSeat);
return byteArray.ToArray();
@ -35,9 +35,9 @@ namespace RageCoop.Core
#region NetIncomingMessageToPacket
BitReader reader = new BitReader(array);
PedID=reader.ReadInt();
VehicleID=reader.ReadInt();
VehicleSeat=reader.ReadShort();
PedID=reader.ReadInt32();
VehicleID=reader.ReadInt32();
VehicleSeat=reader.ReadInt16();
#endregion
}

View File

@ -24,7 +24,7 @@ namespace RageCoop.Core
byteArray.AddInt(PedID);
byteArray.AddInt(VehicleID);
byteArray.AddInt(VehicleSeat);
byteArray.AddShort(VehicleSeat);
return byteArray.ToArray();
@ -35,9 +35,9 @@ namespace RageCoop.Core
#region NetIncomingMessageToPacket
BitReader reader = new BitReader(array);
PedID=reader.ReadInt();
VehicleID=reader.ReadInt();
VehicleSeat=reader.ReadShort();
PedID=reader.ReadInt32();
VehicleID=reader.ReadInt32();
VehicleSeat=reader.ReadInt16();
#endregion
}

View File

@ -31,7 +31,7 @@ namespace RageCoop.Core
#region NetIncomingMessageToPacket
BitReader reader = new BitReader(array);
ID=reader.ReadInt();
ID=reader.ReadInt32();
#endregion
}

View File

@ -21,7 +21,7 @@ namespace RageCoop.Core
List<byte> byteArray = new List<byte>();
byteArray.AddInt(VehicleID);
if (Hover) { byteArray.Add(1); }
byteArray.AddBool(Hover);
return byteArray.ToArray();
@ -31,8 +31,8 @@ namespace RageCoop.Core
{
#region NetIncomingMessageToPacket
BitReader reader = new BitReader(array);
VehicleID=reader.ReadInt();
Hover=reader.CanRead(1);
VehicleID=reader.ReadInt32();
Hover=reader.ReadBoolean();
#endregion
}

View File

@ -32,8 +32,8 @@ namespace RageCoop.Core
#region NetIncomingMessageToPacket
BitReader reader = new BitReader(array);
ID=reader.ReadInt();
NewOwnerID=reader.ReadInt();
ID=reader.ReadInt32();
NewOwnerID=reader.ReadInt32();
#endregion
}

View File

@ -29,7 +29,7 @@ namespace RageCoop.Core
#region NetIncomingMessageToPacket
BitReader reader = new BitReader(array);
VictimID=reader.ReadInt();
VictimID=reader.ReadInt32();
#endregion
}

View File

@ -174,11 +174,11 @@ namespace RageCoop.Core
BitReader reader = new BitReader(array);
// Read vehicle id
ID = reader.ReadInt();
ID = reader.ReadInt32();
OwnerID = reader.ReadInt();
OwnerID = reader.ReadInt32();
Flags=(VehicleDataFlags)reader.ReadUShort();
Flags=(VehicleDataFlags)reader.ReadUInt16();
// Read position
Position = reader.ReadVector3();
@ -195,27 +195,27 @@ namespace RageCoop.Core
RotationVelocity=reader.ReadVector3();
// Read throttle power
ThrottlePower=reader.ReadFloat();
ThrottlePower=reader.ReadSingle();
// Read brake power
BrakePower=reader.ReadFloat();
BrakePower=reader.ReadSingle();
// Read steering angle
SteeringAngle = reader.ReadFloat();
SteeringAngle = reader.ReadSingle();
if (Flags.HasVehFlag(VehicleDataFlags.IsDeluxoHovering))
{
DeluxoWingRatio = reader.ReadFloat();
DeluxoWingRatio = reader.ReadSingle();
}
if (Flags.HasVehFlag(VehicleDataFlags.IsFullSync))
{
// Read vehicle model hash
ModelHash = reader.ReadInt();
ModelHash = reader.ReadInt32();
// Read vehicle engine health
EngineHealth = reader.ReadFloat();
EngineHealth = reader.ReadSingle();
// Check
@ -238,15 +238,15 @@ namespace RageCoop.Core
// Create new Dictionary
Mods = new Dictionary<int, int>();
// Read count of mods
short vehModCount = reader.ReadShort();
short vehModCount = reader.ReadInt16();
// Loop
for (int i = 0; i < vehModCount; i++)
{
// Read the mod value
Mods.Add(reader.ReadInt(), reader.ReadInt());
Mods.Add(reader.ReadInt32(), reader.ReadInt32());
}
if (reader.ReadBool())
if (reader.ReadBoolean())
{
// Read vehicle damage model
DamageModel = new VehicleDamageModel()
@ -254,7 +254,7 @@ namespace RageCoop.Core
BrokenDoors = reader.ReadByte(),
OpenedDoors=reader.ReadByte(),
BrokenWindows = reader.ReadByte(),
BurstedTires = reader.ReadShort(),
BurstedTires = reader.ReadInt16(),
LeftHeadLightBroken = reader.ReadByte(),
RightHeadLightBroken = reader.ReadByte()
};
@ -263,12 +263,12 @@ namespace RageCoop.Core
// Read Passengers
Passengers=new Dictionary<int, int>();
int count = reader.ReadInt();
int count = reader.ReadInt32();
for (int i = 0; i<count; i++)
{
int seat, id;
seat = reader.ReadInt();
id = reader.ReadInt();
seat = reader.ReadInt32();
id = reader.ReadInt32();
Passengers.Add(seat, id);
}
@ -280,7 +280,7 @@ namespace RageCoop.Core
// Read RadioStation
RadioStation=reader.ReadByte();
LicensePlate=Encoding.ASCII.GetString(reader.ReadByteArray(8));
LicensePlate=Encoding.ASCII.GetString(reader.ReadBytes(8));
Livery=(int)(reader.ReadByte()-1);
}