using ODMO.Commons.Entities;
using ODMO.Commons.Interfaces;
using ODMO.Commons.Packets.AuthenticationServer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
namespace ODMO.Account
{
public sealed class AuthenticationServer : GameServer, IHostedService
{
private readonly IHostApplicationLifetime _hostApplicationLifetime;
private readonly IConfiguration _configuration;
private readonly IProcessor _processor;
private readonly ILogger _logger;
private const int OnConnectEventHandshakeHandler = 65535;
public AuthenticationServer(IHostApplicationLifetime hostApplicationLifetime,
IConfiguration configuration,
IProcessor processor,
ILogger logger)
{
OnConnect += OnConnectEvent;
OnDisconnect += OnDisconnectEvent;
DataReceived += OnDataReceivedEvent;
_hostApplicationLifetime = hostApplicationLifetime;
_configuration = configuration;
_processor = processor;
_logger = logger;
}
///
/// Event triggered everytime that a game client connects to the server.
///
/// The object itself
/// Game client who connected
private void OnConnectEvent(object sender, GameClientEvent gameClientEvent)
{
var clientIpAddress = gameClientEvent.Client.ClientAddress.Split(':')?.FirstOrDefault();
//if (InvalidConnection(clientIpAddress))
//{
// _logger.Information($"Blocked connection event from {gameClientEvent.Client.HiddenAddress}. Blocked Addresses: {RefusedAddresses.Count}");
// if (!string.IsNullOrEmpty(clientIpAddress) && !RefusedAddresses.Contains(clientIpAddress))
// RefusedAddresses.Add(clientIpAddress);
// gameClientEvent.Client.Disconnect();
// RemoveClient(gameClientEvent.Client);
//}
//else
//{
// _logger.Information($"Accepted connection event from {gameClientEvent.Client.HiddenAddress}.");
// gameClientEvent.Client.SetHandshake((short)(DateTimeOffset.UtcNow.ToUnixTimeSeconds() & OnConnectEventHandshakeHandler));
// if (gameClientEvent.Client.IsConnected)
// {
// _logger.Debug($"Sending handshake for request source {gameClientEvent.Client.ClientAddress}.");
// gameClientEvent.Client.Send(new OnConnectEventConnectionPacket(gameClientEvent.Client.Handshake));
// }
// else
// _logger.Warning($"Request source {gameClientEvent.Client.ClientAddress} has been disconnected.");
//}
_logger.Information($"Accepted connection event from {gameClientEvent.Client.HiddenAddress}.");
gameClientEvent.Client.SetHandshake((short)(DateTimeOffset.UtcNow.ToUnixTimeSeconds() & OnConnectEventHandshakeHandler));
if (gameClientEvent.Client.IsConnected)
{
_logger.Debug($"Sending handshake for request source {gameClientEvent.Client.ClientAddress}.");
gameClientEvent.Client.Send(new OnConnectEventConnectionPacket(gameClientEvent.Client.Handshake));
}
else
_logger.Warning($"Request source {gameClientEvent.Client.ClientAddress} has been disconnected.");
}
///
/// Event triggered everytime the game client disconnects from the server.
///
/// The object itself
/// Game client who disconnected
private void OnDisconnectEvent(object sender, GameClientEvent gameClientEvent)
{
if (!string.IsNullOrEmpty(gameClientEvent.Client.ClientAddress))
{
var isExpectedHandoffDisconnect = gameClientEvent.Client.ExpectedDisconnect;
var expectedDisconnectReason = gameClientEvent.Client.ExpectedDisconnectReason;
if (isExpectedHandoffDisconnect)
_logger.Information($"Received expected handoff disconnect for {gameClientEvent.Client.HiddenAddress}. Reason: {expectedDisconnectReason}.");
else
_logger.Information($"Received disconnection event for {gameClientEvent.Client.HiddenAddress}.");
_logger.Debug($"Source disconnected: {gameClientEvent.Client.ClientAddress}. Account: {gameClientEvent.Client.AccountId}. ExpectedHandoff: {isExpectedHandoffDisconnect}. Reason: {expectedDisconnectReason}.");
gameClientEvent.Client.ClearExpectedDisconnect();
}
}
///
/// Event triggered everytime the game client sends a TCP packet.
///
/// The object itself
/// Game client who sent the packet
/// The packet content, in byte array
private void OnDataReceivedEvent(object sender, GameClientEvent gameClientEvent, byte[] data)
{
try
{
_logger.Debug($"Received {data.Length} bytes from {gameClientEvent.Client.ClientAddress}.");
_processor.ProcessPacketAsync(gameClientEvent.Client, data);
}
catch (Exception ex)
{
gameClientEvent.Client.SetGameQuit(true);
gameClientEvent.Client.Disconnect();
_logger.Error($"Process packet error: {ex.Message} {ex.InnerException} {ex.StackTrace}.");
try
{
var filePath = $"PacketErrors/{gameClientEvent.Client.AccountId}_{DateTime.Now.ToString("dd_MM_HH_mm_ss")}.txt";
Directory.CreateDirectory("/PacketErrors");
using var fs = File.Create(filePath);
fs.Write(data, 0, data.Length);
}
catch { }
//TODO: Salvar no banco com os parametros
}
}
///
/// The default hosted service "starting" method.
///
/// Control token for the operation
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.Information($"Starting {GetType().Name}...");
Console.Title = $"DMO - {GetType().Name}";
_hostApplicationLifetime.ApplicationStarted.Register(OnStarted);
_hostApplicationLifetime.ApplicationStopping.Register(OnStopping);
_hostApplicationLifetime.ApplicationStopped.Register(OnStopped);
return Task.CompletedTask;
}
///
/// The default hosted service "stopping" method
///
/// Control token for the operation
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
///
/// The default hosted service "started" method action
///
private void OnStarted()
{
if (!Listen(_configuration[AuthenticationServerAddress],
_configuration[AuthenticationServerPort],
_configuration[AuthenticationServerBacklog]))
{
_logger.Error("Unable to start. Check the binding configurations.");
_hostApplicationLifetime.StopApplication();
return;
}
_logger.Information($"{GetType().Name} started.");
}
///
/// The default hosted service "stopping" method action
///
private void OnStopping()
{
_logger.Information($"Disconnecting clients...");
Shutdown();
}
///
/// The default hosted service "stopped" method action
///
private void OnStopped()
{
_logger.Information($"{GetType().Name} stopped.");
}
}
}