style: apply editorconfig style

This commit is contained in:
Timothy Schenk 2023-08-11 11:31:30 +02:00
parent 81829e87cb
commit 1de07e546a
22 changed files with 236 additions and 261 deletions

View file

@ -1,15 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<LangVersion>default</LangVersion> <LangVersion>default</LangVersion>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.13.7" /> <PackageReference Include="BenchmarkDotNet" Version="0.13.7"/>
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -21,29 +21,24 @@ public class BinaryConversionBenchmarks
[GlobalSetup] [GlobalSetup]
public void Setup() public void Setup()
{ {
data = RandomNumberGenerator.GetBytes(4000); this.data = RandomNumberGenerator.GetBytes(4000);
offset = RandomNumberGenerator.GetInt32(0, 3500); this.offset = RandomNumberGenerator.GetInt32(0, 3500);
} }
[Benchmark] [Benchmark]
public Int16 BitConverterTest() public short BitConverterTest() => BitConverter.ToInt16(this.data, this.offset);
{
return BitConverter.ToInt16(data, offset);
}
[Benchmark] [Benchmark]
public Int16 BinaryReader() public short BinaryReader()
{ {
using MemoryStream ms = new MemoryStream(data); using var ms = new MemoryStream(this.data);
using BinaryReader reader = new BinaryReader(ms); using var reader = new BinaryReader(ms);
reader.BaseStream.Position = offset; reader.BaseStream.Position = this.offset;
return reader.ReadInt16(); return reader.ReadInt16();
} }
[Benchmark] [Benchmark]
public Int16 BinaryPrimitives() public short BinaryPrimitives() =>
{ System.Buffers.Binary.BinaryPrimitives.ReadInt16LittleEndian(
return System.Buffers.Binary.BinaryPrimitives.ReadInt16LittleEndian( new ArraySegment<byte>(this.data, this.offset, sizeof(short)));
new ArraySegment<byte>(data, offset, sizeof(short))); }
}
}

View file

@ -5,8 +5,5 @@ namespace Benchmarks;
internal class Program internal class Program
{ {
public static void Main(string[] args) public static void Main(string[] args) => BenchmarkRunner.Run(Assembly.GetExecutingAssembly());
{ }
BenchmarkRunner.Run(Assembly.GetExecutingAssembly());
}
}

View file

@ -15,26 +15,30 @@ public class AuthSession : TcpSession
public AuthSession(TcpServer public AuthSession(TcpServer
server, IMediator mediator, ILogger<AuthSession> logger) : base(server) server, IMediator mediator, ILogger<AuthSession> logger) : base(server)
{ {
_mediator = mediator; this._mediator = mediator;
_logger = logger; this._logger = logger;
} }
public override long Send(byte[] buffer) public override long Send(byte[] buffer)
{ {
_logger.LogInformation("Data being sent is: {Data}", BitConverter.ToString(buffer)); this._logger.LogInformation("Data being sent is: {Data}", BitConverter.ToString(buffer));
return base.Send(buffer); return base.Send(buffer);
} }
public void Send(IPacket packet) public void Send(IPacket packet)
{ {
var type = packet.GetType(); var type = packet.GetType();
_logger.LogTrace("Packet of type {Type} is being serialized", type.Name); this._logger.LogTrace("Packet of type {Type} is being serialized", type.Name);
var packetIdAttribute = type.GetCustomAttribute<PacketId>(); var packetIdAttribute = type.GetCustomAttribute<PacketId>();
if (packetIdAttribute == null) return; if (packetIdAttribute == null)
{
return;
}
var opcode = packetIdAttribute.Code; var opcode = packetIdAttribute.Code;
Span<byte> packetData = packet.Serialize(); Span<byte> packetData = packet.Serialize();
ushort length = (ushort)(packetData.Length + 8); var length = (ushort)(packetData.Length + 8);
Span<byte> buffer = stackalloc byte[length]; Span<byte> buffer = stackalloc byte[length];
buffer.Clear(); buffer.Clear();
@ -42,20 +46,20 @@ public class AuthSession : TcpSession
var bytesOfLength = BitConverter.GetBytes(length); var bytesOfLength = BitConverter.GetBytes(length);
var bytesOfOpcode = BitConverter.GetBytes((ushort)opcode); var bytesOfOpcode = BitConverter.GetBytes((ushort)opcode);
for (int i = 0; i < bytesOfLength.Length || i < 2; i++) for (var i = 0; i < bytesOfLength.Length || i < 2; i++)
{ {
buffer[i] = bytesOfLength[i]; buffer[i] = bytesOfLength[i];
} }
for (int i = 0; i < bytesOfOpcode.Length || i < 2; i++) for (var i = 0; i < bytesOfOpcode.Length || i < 2; i++)
{ {
buffer[2 + i] = bytesOfOpcode[i]; buffer[2 + i] = bytesOfOpcode[i];
} }
_logger.LogTrace("Packet data being parsed is: {Data}", BitConverter.ToString(packetData.ToArray())); this._logger.LogTrace("Packet data being parsed is: {Data}", BitConverter.ToString(packetData.ToArray()));
_logger.LogTrace("Packet being parsed is: {Data}", BitConverter.ToString(buffer.ToArray())); this._logger.LogTrace("Packet being parsed is: {Data}", BitConverter.ToString(buffer.ToArray()));
Send(buffer); this.Send(buffer);
} }
protected override void OnReceived(byte[] buffer, long offset, long size) protected override void OnReceived(byte[] buffer, long offset, long size)
@ -64,7 +68,7 @@ public class AuthSession : TcpSession
Span<byte> decryptedBuffer = new byte[size]; Span<byte> decryptedBuffer = new byte[size];
// xor every value after the first 8 bytes // xor every value after the first 8 bytes
var dataBuffer = Decrypt(new ArraySegment<byte>(buffer, 8, (int)size - 8).ToArray()); var dataBuffer = this.Decrypt(new ArraySegment<byte>(buffer, 8, (int)size - 8).ToArray());
Console.WriteLine("Length " + BitConverter.ToUInt16(buffer, 0)); Console.WriteLine("Length " + BitConverter.ToUInt16(buffer, 0));
var opCode = BitConverter.ToUInt16(buffer.ToArray(), 2); var opCode = BitConverter.ToUInt16(buffer.ToArray(), 2);
@ -76,21 +80,20 @@ public class AuthSession : TcpSession
Console.WriteLine("Full buffer: " + Encoding.ASCII.GetString(dataBuffer.ToArray())); Console.WriteLine("Full buffer: " + Encoding.ASCII.GetString(dataBuffer.ToArray()));
RawPacket rawPacket = new RawPacket((OperationCode)opCode, dataBuffer, clientAliveTime, buffer[0], var rawPacket = new RawPacket((OperationCode)opCode, dataBuffer, clientAliveTime, buffer[0],
buffer[3], buffer[3], this.Id, this);
Id, this); Task.Run(() => this._mediator.Send(rawPacket));
Task.Run(() => _mediator.Send(rawPacket)); this._logger.LogInformation("Connection from: {@RemoteEndpoint}", this.Socket.RemoteEndPoint?.ToString());
_logger.LogInformation("Connection from: {@RemoteEndpoint}", Socket.RemoteEndPoint?.ToString());
base.OnReceived(decryptedBuffer.ToArray(), offset, decryptedBuffer.Length); base.OnReceived(decryptedBuffer.ToArray(), offset, decryptedBuffer.Length);
} }
private byte[] Decrypt(byte[] buffer) private byte[] Decrypt(byte[] buffer)
{ {
for (int i = 0; i < buffer.Length; ++i) for (var i = 0; i < buffer.Length; ++i)
{ {
buffer[i] = (byte)(buffer[i] ^ i ^ (3 * (0xFE - i))); buffer[i] = (byte)(buffer[i] ^ i ^ (3 * (0xFE - i)));
} }
return buffer; return buffer;
} }
} }

View file

@ -15,31 +15,33 @@ public class ChannelSession : TcpSession
.Reverse().ToArray(); .Reverse().ToArray();
private static readonly byte[] IV = new byte[] private static readonly byte[] IV = new byte[]
{ 0xfe, 220, 0xba, 0x98, 0x76, 0x54, 50, 0x10, 15, 30, 0x2d, 60, 0x4b, 90, 0x69, 120 }.Reverse().ToArray(); {
0xfe, 220, 0xba, 0x98, 0x76, 0x54, 50, 0x10, 15, 30, 0x2d, 60, 0x4b, 90, 0x69, 120
}.Reverse().ToArray();
private readonly ICryptoTransform _encryptor; private readonly ICryptoTransform _encryptor;
private readonly ICryptoTransform _decryptor; private readonly ICryptoTransform _decryptor;
public ChannelSession(TcpServer server, IMediator mediator, ILogger<ChannelSession> logger) : base(server) public ChannelSession(TcpServer server, IMediator mediator, ILogger<ChannelSession> logger) : base(server)
{ {
_mediator = mediator; this._mediator = mediator;
_logger = logger; this._logger = logger;
var aes = Aes.Create(); var aes = Aes.Create();
aes.Key = Key; aes.Key = Key;
aes.IV = IV; aes.IV = IV;
aes.Padding = PaddingMode.None; aes.Padding = PaddingMode.None;
aes.Mode = CipherMode.ECB; aes.Mode = CipherMode.ECB;
_decryptor = aes.CreateDecryptor(aes.Key, aes.IV); this._decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
_encryptor = aes.CreateEncryptor(aes.Key, aes.IV); this._encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
} }
protected override void OnReceived(byte[] buffer, long offset, long size) protected override void OnReceived(byte[] buffer, long offset, long size)
{ {
try try
{ {
using (var ms = new MemoryStream(Decrypt(buffer))) using (var ms = new MemoryStream(this.Decrypt(buffer)))
using (var cs = new CryptoStream(ms, _decryptor, CryptoStreamMode.Read)) using (var cs = new CryptoStream(ms, this._decryptor, CryptoStreamMode.Read))
{ {
cs.Read(buffer); cs.Read(buffer);
} }
@ -48,18 +50,18 @@ public class ChannelSession : TcpSession
} }
catch (CryptographicException ex) catch (CryptographicException ex)
{ {
_logger.LogError("An error has occured while decrypting: {ErrorMessage}", ex.Message); this._logger.LogError("An error has occured while decrypting: {ErrorMessage}", ex.Message);
_logger.LogError("Default buffer message: {Message}", Encoding.ASCII.GetString(buffer)); this._logger.LogError("Default buffer message: {Message}", Encoding.ASCII.GetString(buffer));
} }
} }
private byte[] Decrypt(byte[] buffer) private byte[] Decrypt(byte[] buffer)
{ {
for (int i = 0; i < buffer.Length; ++i) for (var i = 0; i < buffer.Length; ++i)
{ {
buffer[i] = (byte)(buffer[i] ^ i ^ (3 * (0xFE - i))); buffer[i] = (byte)(buffer[i] ^ i ^ (3 * (0xFE - i)));
} }
return buffer; return buffer;
} }
} }

View file

@ -8,14 +8,11 @@ public class PacketConsumer : IConsumer<RawPacket>
{ {
private readonly PacketDistributorService _distributorService; private readonly PacketDistributorService _distributorService;
public PacketConsumer(PacketDistributorService distributorService) public PacketConsumer(PacketDistributorService distributorService) => this._distributorService = distributorService;
{
_distributorService = distributorService;
}
public Task Consume(ConsumeContext<RawPacket> context) public Task Consume(ConsumeContext<RawPacket> context)
{ {
_distributorService.AddPacket(context.Message); this._distributorService.AddPacket(context.Message);
return Task.CompletedTask; return Task.CompletedTask;
} }
} }

View file

@ -6,14 +6,14 @@ public class Account : CouchDocument
{ {
public Account(string username, string password, string email, byte permissionLevel) public Account(string username, string password, string email, byte permissionLevel)
{ {
Username = username; this.Username = username;
Password = password; this.Password = password;
Email = email; this.Email = email;
PermissionLevel = permissionLevel; this.PermissionLevel = permissionLevel;
} }
public string Username { get; private set; } public string Username { get; private set; }
public string Password { get; private set; } public string Password { get; private set; }
public string Email { get; private set; } public string Email { get; private set; }
public byte PermissionLevel { get; private set; } public byte PermissionLevel { get; private set; }
} }

View file

@ -11,4 +11,4 @@ public class WonderkingContext : CouchContext
public WonderkingContext(CouchOptions<WonderkingContext> options) : base(options) public WonderkingContext(CouchOptions<WonderkingContext> options) : base(options)
{ {
} }
} }

View file

@ -6,4 +6,4 @@ namespace Server.PacketHandlers;
public interface IPacketHandler<in T> where T : IPacket public interface IPacketHandler<in T> where T : IPacket
{ {
public Task HandleAsync(T packet, TcpSession session); public Task HandleAsync(T packet, TcpSession session);
} }

View file

@ -16,46 +16,39 @@ public class LoginHandler : IPacketHandler<LoginInfoPacket>
public LoginHandler(ILogger<LoginHandler> logger, WonderkingContext wonderkingContext, IConfiguration configuration) public LoginHandler(ILogger<LoginHandler> logger, WonderkingContext wonderkingContext, IConfiguration configuration)
{ {
_logger = logger; this._logger = logger;
_wonderkingContext = wonderkingContext; this._wonderkingContext = wonderkingContext;
_configuration = configuration; this._configuration = configuration;
} }
public async Task HandleAsync(LoginInfoPacket packet, TcpSession session) public async Task HandleAsync(LoginInfoPacket packet, TcpSession session)
{ {
_logger.LogInformation("Login data: Username {Username} & Password {Password}", packet.Username, this._logger.LogInformation("Login data: Username {Username} & Password {Password}", packet.Username,
packet.Password); packet.Password);
var account = _wonderkingContext.Accounts.FirstOrDefault(a => a.Username == packet.Username); var account = this._wonderkingContext.Accounts.FirstOrDefault(a => a.Username == packet.Username);
if (account == null) if (account == null)
{ {
if (_configuration.GetSection("Testing").GetValue<bool>("CreateAccountOnLogin")) if (this._configuration.GetSection("Testing").GetValue<bool>("CreateAccountOnLogin"))
{ {
var result = _wonderkingContext.Accounts.AddAsync(new Account(packet.Username, packet.Password, "", 0)); var result =
this._wonderkingContext.Accounts.AddAsync(new Account(packet.Username, packet.Password, "", 0));
await result; await result;
} }
else else
{ {
// TODO: Send Message that account does not exist // TODO: Send Message that account does not exist
_logger.LogInformation("Requested account for user: {Username} does not exist", packet.Username); this._logger.LogInformation("Requested account for user: {Username} does not exist", packet.Username);
} }
} }
var loginResponsePacket = new LoginResponsePacket var loginResponsePacket = new LoginResponsePacket
{ {
LoginResponseReason = LoginResponseReason.OK, LoginResponseReason = LoginResponseReason.OK,
ChannelData = new[] ChannelData = new[] { new ServerChannelData { ChannelId = 0, LoadPercentage = 200, ServerId = 0 } },
{
new ServerChannelData
{
ChannelId = 0,
LoadPercentage = 200,
ServerId = 0
}
},
UnknownFlag = 1, UnknownFlag = 1,
IsGameMaster = true IsGameMaster = true
}; };
var sess = session as AuthSession; var sess = session as AuthSession;
sess.Send(loginResponsePacket); sess.Send(loginResponsePacket);
} }
} }

View file

@ -2,6 +2,6 @@
public interface IPacket public interface IPacket
{ {
public void Deserialize( byte[] data); public void Deserialize(byte[] data);
public byte[] Serialize(); public byte[] Serialize();
} }

View file

@ -11,25 +11,25 @@ public class LoginInfoPacket : IPacket
public void Deserialize(byte[] data) public void Deserialize(byte[] data)
{ {
Username = Encoding.ASCII.GetString(data, 0, 20); this.Username = Encoding.ASCII.GetString(data, 0, 20);
Password = Encoding.ASCII.GetString(data, 20, 31); this.Password = Encoding.ASCII.GetString(data, 20, 31);
} }
public byte[] Serialize() public byte[] Serialize()
{ {
Span<byte> dataSpan = stackalloc byte[20 + 31]; Span<byte> dataSpan = stackalloc byte[20 + 31];
var usernameBytes = Encoding.ASCII.GetBytes(Username); var usernameBytes = Encoding.ASCII.GetBytes(this.Username);
var passwordBytes = Encoding.ASCII.GetBytes(Password); var passwordBytes = Encoding.ASCII.GetBytes(this.Password);
for (int i = 0; i < 20 || i < Username.Length; i++) for (var i = 0; i < 20 || i < this.Username.Length; i++)
{ {
dataSpan[i] = usernameBytes[i]; dataSpan[i] = usernameBytes[i];
} }
for (int i = 0; i < 31 || i < Password.Length; i++) for (var i = 0; i < 31 || i < this.Password.Length; i++)
{ {
dataSpan[20 + i] = passwordBytes[i]; dataSpan[20 + i] = passwordBytes[i];
} }
return dataSpan.ToArray(); return dataSpan.ToArray();
} }
} }

View file

@ -4,4 +4,4 @@ public enum OperationCode : ushort
{ {
LoginInfo = 11, LoginInfo = 11,
LoginResponse = 12 LoginResponse = 12
} }

View file

@ -11,42 +11,42 @@ public class LoginResponsePacket : IPacket
public void Deserialize(byte[] data) public void Deserialize(byte[] data)
{ {
LoginResponseReason = (LoginResponseReason)data[0]; this.LoginResponseReason = (LoginResponseReason)data[0];
UnknownFlag = data[1]; this.UnknownFlag = data[1];
IsGameMaster = BitConverter.ToBoolean(data, 2); this.IsGameMaster = BitConverter.ToBoolean(data, 2);
var channelAmount = BitConverter.ToUInt16(data, 3); var channelAmount = BitConverter.ToUInt16(data, 3);
var sizeOfServerChannelData = 5; var sizeOfServerChannelData = 5;
ChannelData = Enumerable.Repeat(0, channelAmount).Select(i => new ServerChannelData this.ChannelData = Enumerable.Repeat(0, channelAmount).Select(i => new ServerChannelData
{ {
ServerId = BitConverter.ToUInt16(data, 5 + 0 + i * sizeOfServerChannelData), ServerId = BitConverter.ToUInt16(data, 5 + 0 + (i * sizeOfServerChannelData)),
ChannelId = BitConverter.ToUInt16(data, 5 + 2 + i * sizeOfServerChannelData), ChannelId = BitConverter.ToUInt16(data, 5 + 2 + (i * sizeOfServerChannelData)),
LoadPercentage = data[5 + 4 + i * sizeOfServerChannelData] LoadPercentage = data[5 + 4 + (i * sizeOfServerChannelData)]
}).ToArray(); }).ToArray();
} }
public byte[] Serialize() public byte[] Serialize()
{ {
var sizeOfServerChannelData = 5; var sizeOfServerChannelData = 5;
Span<byte> dataSpan = stackalloc byte[5 + ChannelData.Length * sizeOfServerChannelData]; Span<byte> dataSpan = stackalloc byte[5 + (this.ChannelData.Length * sizeOfServerChannelData)];
dataSpan.Clear(); dataSpan.Clear();
dataSpan[0] = (byte)LoginResponseReason; dataSpan[0] = (byte)this.LoginResponseReason;
dataSpan[1] = UnknownFlag; dataSpan[1] = this.UnknownFlag;
dataSpan[2] = BitConverter.GetBytes(IsGameMaster)[0]; dataSpan[2] = BitConverter.GetBytes(this.IsGameMaster)[0];
var bytesOfChannelAmount = BitConverter.GetBytes((ushort)ChannelData.Length); var bytesOfChannelAmount = BitConverter.GetBytes((ushort)this.ChannelData.Length);
dataSpan[3] = bytesOfChannelAmount[0]; dataSpan[3] = bytesOfChannelAmount[0];
dataSpan[4] = bytesOfChannelAmount[1]; dataSpan[4] = bytesOfChannelAmount[1];
for (var i = 0; i < ChannelData.Length; i++) for (var i = 0; i < this.ChannelData.Length; i++)
{ {
var bytesOfServerId = BitConverter.GetBytes(ChannelData[i].ServerId); var bytesOfServerId = BitConverter.GetBytes(this.ChannelData[i].ServerId);
var bytesOfChannelId = BitConverter.GetBytes(ChannelData[i].ChannelId); var bytesOfChannelId = BitConverter.GetBytes(this.ChannelData[i].ChannelId);
dataSpan[5 + 0 + i * sizeOfServerChannelData] = bytesOfServerId[0]; dataSpan[5 + 0 + (i * sizeOfServerChannelData)] = bytesOfServerId[0];
dataSpan[5 + 1 + i * sizeOfServerChannelData] = bytesOfServerId[1]; dataSpan[5 + 1 + (i * sizeOfServerChannelData)] = bytesOfServerId[1];
dataSpan[5 + 2 + i * sizeOfServerChannelData] = bytesOfChannelId[0]; dataSpan[5 + 2 + (i * sizeOfServerChannelData)] = bytesOfChannelId[0];
dataSpan[5 + 3 + i * sizeOfServerChannelData] = bytesOfChannelId[1]; dataSpan[5 + 3 + (i * sizeOfServerChannelData)] = bytesOfChannelId[1];
dataSpan[5 + 4 + i * sizeOfServerChannelData] = ChannelData[i].LoadPercentage; dataSpan[5 + 4 + (i * sizeOfServerChannelData)] = this.ChannelData[i].LoadPercentage;
} }
return dataSpan.ToArray(); return dataSpan.ToArray();
} }
} }

View file

@ -15,5 +15,5 @@ public enum LoginResponseReason : byte
ServerNotFoundOrDBProblem, ServerNotFoundOrDBProblem,
LockedDuePayment, LockedDuePayment,
UserDeletedBigpoint, UserDeletedBigpoint,
NoMoreTries, NoMoreTries
} }

View file

@ -5,4 +5,4 @@ public struct ServerChannelData
public ushort ServerId; public ushort ServerId;
public ushort ChannelId; public ushort ChannelId;
public byte LoadPercentage; public byte LoadPercentage;
} }

View file

@ -1,12 +1,8 @@
namespace Server.Packets; namespace Server.Packets;
public class PacketId : Attribute public class PacketId : Attribute
{ {
public readonly OperationCode Code; public readonly OperationCode Code;
public PacketId(OperationCode code) public PacketId(OperationCode code) => this.Code = code;
{ }
Code = code;
}
}

View file

@ -17,18 +17,18 @@ public class RawPacket
public RawPacket(OperationCode operationCode, byte[] messageBody, uint aliveTime, byte unknownValue2, public RawPacket(OperationCode operationCode, byte[] messageBody, uint aliveTime, byte unknownValue2,
byte unknownValue, Guid sessionId, AuthSession session) byte unknownValue, Guid sessionId, AuthSession session)
{ {
MessageBody = messageBody; this.MessageBody = messageBody;
UnknownValue2 = unknownValue2; this.UnknownValue2 = unknownValue2;
UnknownValue = unknownValue; this.UnknownValue = unknownValue;
SessionId = sessionId; this.SessionId = sessionId;
Session = session; this.Session = session;
OperationCode = operationCode; this.OperationCode = operationCode;
/* /*
* 20s = 5 * 20s = 5
* 15s = 4 * 15s = 4
* 10s = 3 * 10s = 3
* client alive time * 5s => uptime * client alive time * 5s => uptime
*/ */
ClientAliveTime = TimeSpan.FromSeconds(5 * aliveTime); this.ClientAliveTime = TimeSpan.FromSeconds(5 * aliveTime);
} }
} }

View file

@ -10,7 +10,7 @@ using Server.DB;
using Server.Services; using Server.Services;
var builder = Host.CreateApplicationBuilder(); var builder = Host.CreateApplicationBuilder();
var configurationRoot = builder.Configuration.AddJsonFile("settings.json", optional: false, reloadOnChange: true) var configurationRoot = builder.Configuration.AddJsonFile("settings.json", false, true)
.AddEnvironmentVariables().Build(); .AddEnvironmentVariables().Build();
builder.Services.AddLogging(); builder.Services.AddLogging();
builder.Logging.AddFile("Logs/Server-{Date}.log", LogLevel.Trace); builder.Logging.AddFile("Logs/Server-{Date}.log", LogLevel.Trace);
@ -34,5 +34,5 @@ builder.Services.AddHostedService<WonderkingAuthServer>(provider => new Wonderki
provider.GetService<ILogger<WonderkingAuthServer>>() ?? throw new InvalidOperationException(), provider.GetService<ILogger<WonderkingAuthServer>>() ?? throw new InvalidOperationException(),
provider.GetService<IServiceProvider>() ?? throw new InvalidOperationException())); provider.GetService<IServiceProvider>() ?? throw new InvalidOperationException()));
using IHost host = builder.Build(); using var host = builder.Build();
await host.RunAsync(); await host.RunAsync();

View file

@ -1,78 +1,78 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework> <TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS> <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<RootNamespace>Server</RootNamespace> <RootNamespace>Server</RootNamespace>
<LangVersion>default</LangVersion> <LangVersion>default</LangVersion>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Content Include="..\.dockerignore"> <Content Include="..\.dockerignore">
<Link>.dockerignore</Link> <Link>.dockerignore</Link>
</Content> </Content>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="CouchDB.NET" Version="3.4.0"/> <PackageReference Include="CouchDB.NET" Version="3.4.0"/>
<PackageReference Include="CouchDB.NET.DependencyInjection" Version="3.4.0"/> <PackageReference Include="CouchDB.NET.DependencyInjection" Version="3.4.0"/>
<PackageReference Include="CSharpGuidelinesAnalyzer" Version="3.8.3"> <PackageReference Include="CSharpGuidelinesAnalyzer" Version="3.8.3">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="ErrorProne.NET.CoreAnalyzers" Version="0.1.2"> <PackageReference Include="ErrorProne.NET.CoreAnalyzers" Version="0.1.2">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="JetBrains.Annotations" Version="2023.2.0"/> <PackageReference Include="JetBrains.Annotations" Version="2023.2.0"/>
<PackageReference Include="MassTransit" Version="8.0.16"/> <PackageReference Include="MassTransit" Version="8.0.16"/>
<PackageReference Include="MassTransit.Analyzers" Version="8.0.16"> <PackageReference Include="MassTransit.Analyzers" Version="8.0.16">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0"/> <PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0"/>
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0"/> <PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="7.0.0"/>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0"/> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0"/>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0"/> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0"/>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1"/> <PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.1"/>
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0"/> <PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0"/>
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0"/> <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="7.0.0"/>
<PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.7.30"> <PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" Version="17.7.30">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="NetCoreServer" Version="7.0.0"/> <PackageReference Include="NetCoreServer" Version="7.0.0"/>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3"/> <PackageReference Include="Newtonsoft.Json" Version="13.0.3"/>
<PackageReference Include="Nullable.Extended.Analyzer" Version="1.10.4539"> <PackageReference Include="Nullable.Extended.Analyzer" Version="1.10.4539">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Puma.Security.Rules.2022" Version="2.4.23"> <PackageReference Include="Puma.Security.Rules.2022" Version="2.4.23">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Roslynator.Analyzers" Version="4.4.0"> <PackageReference Include="Roslynator.Analyzers" Version="4.4.0">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Roslynator.CodeAnalysis.Analyzers" Version="4.4.0"> <PackageReference Include="Roslynator.CodeAnalysis.Analyzers" Version="4.4.0">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Roslynator.Formatting.Analyzers" Version="4.4.0"> <PackageReference Include="Roslynator.Formatting.Analyzers" Version="4.4.0">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0"/> <PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Remove="settings.json" /> <None Remove="settings.json"/>
<AdditionalFiles Include="settings.json"> <AdditionalFiles Include="settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</AdditionalFiles> </AdditionalFiles>
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -21,15 +21,15 @@ public class PacketDistributorService : IHostedService
public PacketDistributorService(ILogger<PacketDistributorService> logger, IServiceProvider serviceProvider) public PacketDistributorService(ILogger<PacketDistributorService> logger, IServiceProvider serviceProvider)
{ {
_concurrentQueue = new ConcurrentQueue<RawPacket>(); this._concurrentQueue = new ConcurrentQueue<RawPacket>();
_logger = logger; this._logger = logger;
_serviceProvider = serviceProvider; this._serviceProvider = serviceProvider;
_packetHandlers = new Dictionary<OperationCode, Type>(); this._packetHandlers = new Dictionary<OperationCode, Type>();
_packetsTypes = new Dictionary<OperationCode, Type>(); this._packetsTypes = new Dictionary<OperationCode, Type>();
var executingAssembly = Assembly.GetExecutingAssembly(); var executingAssembly = Assembly.GetExecutingAssembly();
_packetsTypes = GetPacketsWithId(executingAssembly); this._packetsTypes = this.GetPacketsWithId(executingAssembly);
_packetHandlers = GetAllPacketHandlersWithId(executingAssembly); this._packetHandlers = this.GetAllPacketHandlersWithId(executingAssembly);
} }
private Dictionary<OperationCode, Type> GetPacketsWithId(Assembly executingAssembly) private Dictionary<OperationCode, Type> GetPacketsWithId(Assembly executingAssembly)
@ -42,13 +42,13 @@ public class PacketDistributorService : IHostedService
{ {
packetsWithId.AsParallel().ForAll(packet => packetsWithId.AsParallel().ForAll(packet =>
{ {
_logger.LogTrace("Packet with ID: {PacketID} has been added as {PacketName}", packet.Key, this._logger.LogTrace("Packet with ID: {PacketID} has been added as {PacketName}", packet.Key,
packet.Value.FullName); packet.Value.FullName);
}); });
return packetsWithId; return packetsWithId;
} }
_logger.LogCritical("No Packets have been found"); this._logger.LogCritical("No Packets have been found");
throw new IncompleteInitialization(); throw new IncompleteInitialization();
} }
@ -65,34 +65,32 @@ public class PacketDistributorService : IHostedService
{ {
packetHandlersWithId.AsParallel().ForAll(packetHandler => packetHandlersWithId.AsParallel().ForAll(packetHandler =>
{ {
_logger.LogTrace("PacketHandler with ID: {PacketID} has been added as {PacketName}", packetHandler.Key, this._logger.LogTrace("PacketHandler with ID: {PacketID} has been added as {PacketName}",
packetHandler.Key,
packetHandler.Value.FullName); packetHandler.Value.FullName);
}); });
return packetHandlersWithId; return packetHandlersWithId;
} }
_logger.LogCritical("No PacketHandlers have been found"); this._logger.LogCritical("No PacketHandlers have been found");
throw new IncompleteInitialization(); throw new IncompleteInitialization();
} }
public Task StartAsync(CancellationToken cancellationToken) public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
{
return Task.CompletedTask;
}
public void AddPacket(RawPacket rawPacket) public void AddPacket(RawPacket rawPacket)
{ {
_concurrentQueue.Enqueue(rawPacket); this._concurrentQueue.Enqueue(rawPacket);
Task.Run(() => DequeueRawPacketAsync()); Task.Run(() => this.DequeueRawPacketAsync());
_logger.LogInformation("Packet with ID: {MessageOperationCode} has been received", this._logger.LogInformation("Packet with ID: {MessageOperationCode} has been received",
rawPacket.OperationCode); rawPacket.OperationCode);
} }
private async Task DequeueRawPacketAsync() private async Task DequeueRawPacketAsync()
{ {
if (_concurrentQueue.TryDequeue(out var item)) if (this._concurrentQueue.TryDequeue(out var item))
{ {
Task.Run(() => { InvokePacketHandler(item); }); Task.Run(() => { this.InvokePacketHandler(item); });
} }
else else
{ {
@ -102,24 +100,21 @@ public class PacketDistributorService : IHostedService
private void InvokePacketHandler(RawPacket? item) private void InvokePacketHandler(RawPacket? item)
{ {
_logger.LogTrace("[{TempId}] Packet with ID: {MessageOperationCode} is being dequeued", this._logger.LogTrace("[{TempId}] Packet with ID: {MessageOperationCode} is being dequeued",
item.Session.Id, item.OperationCode); item.Session.Id, item.OperationCode);
var packetType = _packetsTypes[item.OperationCode]; var packetType = this._packetsTypes[item.OperationCode];
var packet = (IPacket)Activator.CreateInstance(packetType)!; var packet = (IPacket)Activator.CreateInstance(packetType)!;
packet.Deserialize(item.MessageBody); packet.Deserialize(item.MessageBody);
var packetHandler = var packetHandler =
ActivatorUtilities.GetServiceOrCreateInstance(_serviceProvider, ActivatorUtilities.GetServiceOrCreateInstance(this._serviceProvider,
_packetHandlers[item.OperationCode]); this._packetHandlers[item.OperationCode]);
packetHandler.GetType().GetMethod("HandleAsync") packetHandler.GetType().GetMethod("HandleAsync")
?.Invoke(packetHandler, new Object[] { packet, item.Session }); ?.Invoke(packetHandler, new object[] { packet, item.Session });
_logger.LogDebug("Packet data {PacketData}", JsonConvert.SerializeObject(packet)); this._logger.LogDebug("Packet data {PacketData}", JsonConvert.SerializeObject(packet));
_logger.LogTrace("[{TempId}] Packet with ID: {MessageOperationCode} has finished", this._logger.LogTrace("[{TempId}] Packet with ID: {MessageOperationCode} has finished",
item.Session.Id, item.Session.Id,
item.OperationCode); item.OperationCode);
} }
public Task StopAsync(CancellationToken cancellationToken) public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
{ }
return Task.CompletedTask;
}
}

View file

@ -15,51 +15,48 @@ public class WonderkingAuthServer : TcpServer, IHostedService
public WonderkingAuthServer(IPAddress address, int port, ILogger<WonderkingAuthServer> logger, public WonderkingAuthServer(IPAddress address, int port, ILogger<WonderkingAuthServer> logger,
IServiceProvider serviceProvider) : base(address, port) IServiceProvider serviceProvider) : base(address, port)
{ {
_logger = logger; this._logger = logger;
_serviceProvider = serviceProvider; this._serviceProvider = serviceProvider;
} }
protected override TcpSession CreateSession() => protected override TcpSession CreateSession() =>
ActivatorUtilities.CreateInstance<AuthSession>(_serviceProvider,this); ActivatorUtilities.CreateInstance<AuthSession>(this._serviceProvider, this);
protected override void OnStarting() protected override void OnStarting()
{ {
_logger.LogInformation("Starting"); this._logger.LogInformation("Starting");
base.OnStarting(); base.OnStarting();
} }
protected override void OnStarted() protected override void OnStarted()
{ {
_logger.LogInformation("Started"); this._logger.LogInformation("Started");
base.OnStarted(); base.OnStarted();
} }
protected override void OnStopping() protected override void OnStopping()
{ {
_logger.LogInformation("Stopping"); this._logger.LogInformation("Stopping");
base.OnStopping(); base.OnStopping();
} }
protected override void OnStopped() protected override void OnStopped()
{ {
_logger.LogInformation("Stopped"); this._logger.LogInformation("Stopped");
base.OnStopped(); base.OnStopped();
} }
protected override void OnError(SocketError error) protected override void OnError(SocketError error) => this._logger.LogError("An error has occured {Error}", error);
{
_logger.LogError("An error has occured {Error}", error);
}
public Task StartAsync(CancellationToken cancellationToken) public Task StartAsync(CancellationToken cancellationToken)
{ {
Start(); this.Start();
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task StopAsync(CancellationToken cancellationToken) public Task StopAsync(CancellationToken cancellationToken)
{ {
Stop(); this.Stop();
return Task.CompletedTask; return Task.CompletedTask;
} }
} }