using System.Diagnostics; using System.Reflection; using System.Text; using MassTransit.Mediator; using Microsoft.Extensions.Logging; using NetCoreServer; using Server.Packets; using Buffer = System.Buffer; namespace Server; public class AuthSession : TcpSession { private readonly IMediator _mediator; private readonly ILogger _logger; public AuthSession(TcpServer server, IMediator mediator, ILogger logger) : base(server) { _mediator = mediator; _logger = logger; } public override long Send(byte[] buffer) { _logger.LogInformation("Data being sent is: {Data}", BitConverter.ToString(buffer)); return base.Send(buffer); } public void Send(IPacket packet) { var type = packet.GetType(); _logger.LogTrace("Packet of type {Type} is being serialized", type.Name); var packetIdAttribute = type.GetCustomAttribute(); if (packetIdAttribute == null) return; var opcode = packetIdAttribute.Code; Span packetData = packet.Serialize(); ushort length = (ushort)(packetData.Length + 8); Span buffer = stackalloc byte[length]; buffer.Clear(); packetData.CopyTo(buffer.Slice(8, length - 8)); var bytesOfLength = BitConverter.GetBytes(length); var bytesOfOpcode = BitConverter.GetBytes((ushort)opcode); for (int i = 0; i < bytesOfLength.Length || i < 2; i++) { buffer[i] = bytesOfLength[i]; } for (int i = 0; i < bytesOfOpcode.Length || i < 2; i++) { buffer[2 + i] = bytesOfOpcode[i]; } _logger.LogTrace("Packet data being parsed is: {Data}", BitConverter.ToString(packetData.ToArray())); _logger.LogTrace("Packet being parsed is: {Data}", BitConverter.ToString(buffer.ToArray())); Send(buffer); } protected override void OnReceived(byte[] buffer, long offset, long size) { Console.WriteLine($"Length: {size} & offset: {offset}"); Span decryptedBuffer = new byte[size]; // xor every value after the first 8 bytes var dataBuffer = Decrypt(new ArraySegment(buffer, 8, (int)size - 8).ToArray()); Console.WriteLine("Length " + BitConverter.ToUInt16(buffer, 0)); var opCode = BitConverter.ToUInt16(buffer.ToArray(), 2); Console.WriteLine("Packet Op Code: " + opCode); Console.WriteLine("Some Value: " + buffer[4]); var clientAliveTime = BitConverter.ToUInt16(buffer.ToArray(), 5); Console.WriteLine("Client Alive time: " + clientAliveTime); Console.WriteLine("Might be a flag:" + buffer[7]); Console.WriteLine("Full buffer: " + Encoding.ASCII.GetString(dataBuffer.ToArray())); RawPacket rawPacket = new RawPacket((OperationCode)opCode, dataBuffer, clientAliveTime, buffer[0], buffer[3], Id, this); Parallel.Invoke(() => _mediator.Send(rawPacket)); _logger.LogInformation("Connection from: {@RemoteEndpoint}", Socket.RemoteEndPoint?.ToString()); base.OnReceived(decryptedBuffer.ToArray(), offset, decryptedBuffer.Length); } private byte[] Decrypt(byte[] buffer) { for (int i = 0; i < buffer.Length; ++i) { buffer[i] = (byte)(buffer[i] ^ i ^ (3 * (0xFE - i))); } return buffer; } }