using EonaCat.Json; using EonaCat.Json.Linq; using EonaCat.Connections.EventArguments; using EonaCat.Connections.Helpers; using EonaCat.Connections.Models; using EonaCat.Connections.ConnectionDiagnostics; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.Extensions.Hosting; using System.Collections.Concurrent; using System.Net; using System.Security.Authentication; using System.Security.Cryptography; using System.Text; using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs; namespace EonaCat.Connections.REST { public class RestNetworkServer : IDisposable { private readonly Configuration _config; private readonly Stats _stats; private readonly ConcurrentDictionary _clients = new(); private WebApplication? _app; private CancellationTokenSource? _serverCts; private Task? _serverTask; private bool _disposed; public bool IsStarted => _serverCts != null && !_serverCts.IsCancellationRequested; public int ActiveConnections => GetActiveConnectionCount(); public int MaxConnections => _config.MaxConnections; public string IpAddress => _config.Host; public int Port => _config.Port; public long BytesSent => _stats.BytesSent; public long BytesReceived => _stats.BytesReceived; public long MessagesSent => _stats.MessagesSent; public long MessagesReceived => _stats.MessagesReceived; public double MessagesPerSecond => _stats.MessagesPerSecond; public long TotalConnections => _stats.TotalConnections; public long DroppedConnections => _stats.DroppedConnections; public TimeSpan Uptime => _stats.Uptime; public DateTime StartTime => _stats.StartTime; public event EventHandler? OnConnected; public event EventHandler? OnDataReceived; public event EventHandler? OnDisconnected; public event EventHandler? OnGeneralError; public WebhookManager Webhooks { get; } = new(); public RestNetworkServer(Configuration config) { _config = config ?? throw new ArgumentNullException(nameof(config)); _stats = new Stats { StartTime = DateTime.UtcNow }; } public Stats GetStats() { _stats.ActiveConnections = GetActiveConnectionCount(); return _stats; } private int GetActiveConnectionCount() { if (_clients.IsEmpty) { return 0; } int activeCount = 0; foreach (var client in _clients.Values) { if (client?.CancellationSource != null && !client.CancellationSource.IsCancellationRequested) { activeCount++; } } return activeCount; } private bool CanAcceptConnection() { return _config.MaxConnections <= 0 || GetActiveConnectionCount() < _config.MaxConnections; } private void TrackDisconnect(DisconnectReason reason) { if (reason == DisconnectReason.Error || reason == DisconnectReason.Timeout || reason == DisconnectReason.SSLError || reason == DisconnectReason.NoPongReceived || reason == DisconnectReason.ProtocolError) { _stats.IncrementDroppedConnections(); } } public async Task StartAsync() { _serverCts?.Dispose(); _serverCts = new CancellationTokenSource(); var builder = WebApplication.CreateBuilder(new WebApplicationOptions { Args = Array.Empty() }); builder.WebHost.ConfigureKestrel(options => { options.Listen(IPAddress.Parse(_config.Host), _config.Port, listenOptions => { if (_config.Certificate != null && _config.UseSsl) { listenOptions.UseHttps(httpsOptions => { httpsOptions.ServerCertificate = _config.Certificate; httpsOptions.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13; }); } listenOptions.Protocols = HttpProtocols.Http1AndHttp2; }); }); _app = builder.Build(); MapEndpoints(_app); _serverTask = _app.RunAsync(_serverCts.Token); Console.WriteLine($"EonaCat REST server started on {_config.Host}:{_config.Port}"); } private void MapEndpoints(WebApplication app) { app.MapPost("/api/connect", async (HttpContext ctx) => { if (!CanAcceptConnection()) { _stats.IncrementDroppedConnections(); return Results.StatusCode(StatusCodes.Status429TooManyRequests); } var clientId = Guid.NewGuid().ToString("N"); IPEndPoint? remoteEndPoint = null; if (ctx.Connection.RemoteIpAddress != null) { remoteEndPoint = new IPEndPoint(ctx.Connection.RemoteIpAddress, ctx.Connection.RemotePort); } var clientCts = new CancellationTokenSource(); var connection = new RestClientConnection { Id = clientId, RemoteEndPoint = remoteEndPoint, ConnectedAt = DateTime.UtcNow, LastActive = DateTime.UtcNow, CancellationSource = clientCts }; if (!_clients.TryAdd(clientId, connection)) { _stats.IncrementDroppedConnections(); return Results.StatusCode(StatusCodes.Status409Conflict); } _stats.IncrementTotalConnections(); HandlingHelpers.SafeInvokeEventHandler( OnConnected, this, new ConnectionEventArgs { ClientId = clientId, RemoteEndPoint = remoteEndPoint }, nameof(OnConnected)); _ = HandlingHelpers.SafeFireAndForgetTaskAsync( () => Webhooks.FireAsync("connected", new { clientId, remoteEndPoint = remoteEndPoint?.ToString() }), "WebhookConnected"); return Results.Ok(new { clientId }); }); app.MapPost("/api/disconnect", async (HttpContext ctx) => { var body = await ReadJsonBodyAsync(ctx); var clientId = (string)body?["clientId"]; if (string.IsNullOrEmpty(clientId)) { return Results.BadRequest(new { error = "clientId is required" }); } await DisconnectClientAsync(clientId, DisconnectReason.ClientRequested); return Results.Ok(new { success = true }); }); app.MapPost("/api/send", async (HttpContext ctx) => { var body = await ReadJsonBodyAsync(ctx); var clientId = (string)body?["clientId"]; var dataBase64 = (string)body?["data"]; if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(dataBase64)) { return Results.BadRequest(new { error = "clientId and data are required" }); } if (!_clients.TryGetValue(clientId, out var client)) { return Results.NotFound(new { error = "Client not found" }); } byte[] data; try { data = Convert.FromBase64String(dataBase64); } catch { data = Encoding.UTF8.GetBytes(dataBase64); } if (_config.UseAesEncryption && client.AesInstance != null) { data = await AesKeyExchange.DecryptDataAsync(data, data.Length, client.AesInstance).ConfigureAwait(false); } client.LastActive = DateTime.UtcNow; client.LastDataReceived = DateTime.UtcNow; client.BytesReceived += data.Length; client.MessagesReceived++; _stats.AddBytesReceived(data.Length); _stats.IncrementMessagesReceived(); HandlingHelpers.SafeInvokeEventHandler( OnDataReceived, this, new DataReceivedEventArgs { ClientId = clientId, Data = data, RemoteEndPoint = client.RemoteEndPoint, Nickname = client.Nickname }, nameof(OnDataReceived)); _ = HandlingHelpers.SafeFireAndForgetTaskAsync( () => Webhooks.FireAsync("data_received", new { clientId, nickname = client.Nickname, data = Convert.ToBase64String(data) }), "WebhookDataReceived"); return Results.Ok(new { success = true }); }); app.MapGet("/api/poll/{clientId}", (string clientId) => { if (!_clients.TryGetValue(clientId, out var client)) { return Results.NotFound(new { error = "Client not found" }); } client.LastActive = DateTime.UtcNow; var messages = new List(); while (client.PendingMessages.TryDequeue(out var msg)) { messages.Add(Convert.ToBase64String(msg)); } return Results.Ok(new { messages }); }); app.MapPost("/api/broadcast", async (HttpContext ctx) => { var body = await ReadJsonBodyAsync(ctx); var senderClientId = (string)body?["clientId"]; var dataBase64 = (string)body?["data"]; if (string.IsNullOrEmpty(dataBase64)) { return Results.BadRequest(new { error = "data is required" }); } byte[] data; try { data = Convert.FromBase64String(dataBase64); } catch { data = Encoding.UTF8.GetBytes(dataBase64); } var sent = await BroadcastAsync(data, senderClientId); return Results.Ok(new { success = sent }); }); app.MapPost("/api/nickname", async (HttpContext ctx) => { var body = await ReadJsonBodyAsync(ctx); var clientId = (string)body?["clientId"]; var nickname = (string)body?["nickname"]; if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(nickname)) { return Results.BadRequest(new { error = "clientId and nickname are required" }); } if (!_clients.TryGetValue(clientId, out var client)) { return Results.NotFound(new { error = "Client not found" }); } client.Nickname = nickname; client.LastActive = DateTime.UtcNow; return Results.Ok(new { success = true }); }); app.MapPost("/api/webhooks/register", async (HttpContext ctx) => { var body = await ReadJsonBodyAsync(ctx); var clientId = (string)body?["clientId"]; var url = (string)body?["url"]; if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(url)) { return Results.BadRequest(new { error = "clientId and url are required" }); } if (!_clients.TryGetValue(clientId, out var client)) { return Results.NotFound(new { error = "Client not found" }); } client.WebhookUrl = url; client.LastActive = DateTime.UtcNow; return Results.Ok(new { success = true }); }); app.MapPost("/api/webhooks/unregister", async (HttpContext ctx) => { var body = await ReadJsonBodyAsync(ctx); var clientId = (string)body?["clientId"]; if (string.IsNullOrEmpty(clientId)) { return Results.BadRequest(new { error = "clientId is required" }); } if (_clients.TryGetValue(clientId, out var client)) { client.WebhookUrl = null; client.LastActive = DateTime.UtcNow; } return Results.Ok(new { success = true }); }); app.MapGet("/api/ping/{clientId}", (string clientId) => { if (!_clients.TryGetValue(clientId, out var client)) { return Results.NotFound(new { error = "Client not found" }); } client.LastActive = DateTime.UtcNow; client.LastPongReceived = DateTime.UtcNow; return Results.Ok(new { pong = true, time = DateTime.UtcNow }); }); app.MapPost("/api/aes/init/{clientId}", async (string clientId, HttpContext ctx) => { if (!_config.UseAesEncryption || string.IsNullOrEmpty(_config.AesPassword)) { return Results.BadRequest(new { error = "AES encryption not enabled on server" }); } if (!_clients.TryGetValue(clientId, out var client)) { return Results.NotFound(new { error = "Client not found" }); } var body = await ReadJsonBodyAsync(ctx); var saltBase64 = (string)body?["salt"]; var ivBase64 = (string)body?["iv"]; if (string.IsNullOrEmpty(saltBase64) || string.IsNullOrEmpty(ivBase64)) { return Results.BadRequest(new { error = "salt and iv are required" }); } var salt = Convert.FromBase64String(saltBase64); var iv = Convert.FromBase64String(ivBase64); var aes = CreateAesFromPassword(_config.AesPassword, salt, iv); client.AesInstance?.Dispose(); client.AesInstance = aes; client.AesSalt = salt; client.AesIv = iv; client.LastActive = DateTime.UtcNow; return Results.Ok(new { success = true }); }); } private static async Task ReadJsonBodyAsync(HttpContext ctx) { try { using var reader = new System.IO.StreamReader(ctx.Request.Body); var json = await reader.ReadToEndAsync().ConfigureAwait(false); return JToken.Parse(json); } catch { return null; } } public async Task SendToClientAsync(string clientId, byte[] data) { if (!_clients.TryGetValue(clientId, out var client)) { return false; } try { var payload = data; if (_config.UseAesEncryption && client.AesInstance != null) { payload = await AesKeyExchange.EncryptDataAsync(data, data.Length, client.AesInstance).ConfigureAwait(false); } if (!string.IsNullOrEmpty(client.WebhookUrl)) { await DeliverViaWebhookAsync(client, payload).ConfigureAwait(false); } else { client.PendingMessages.Enqueue(payload); int pendingMessageCount = client.PendingMessageCount; if (pendingMessageCount > 1000) { HandlingHelpers.SafeInvokeEventHandler( OnGeneralError, this, new ErrorEventArgs { ClientId = clientId, Nickname = client.Nickname, Message = $"WARNING: REST client message queue saturation - {pendingMessageCount} messages pending. Client may be slow to consume messages." }, nameof(OnGeneralError)); } } client.LastActive = DateTime.UtcNow; client.LastDataSent = DateTime.UtcNow; client.BytesSent += payload.Length; client.MessagesSent++; _stats.AddBytesSent(payload.Length); _stats.IncrementMessagesSent(); return true; } catch (Exception exception) { HandlingHelpers.SafeInvokeEventHandler( OnGeneralError, this, new ErrorEventArgs { ClientId = clientId, Nickname = client.Nickname, Exception = exception, Message = "Error sending data to REST client" }, nameof(OnGeneralError)); return false; } } public async Task SendToClientAsync(string clientId, string message) => await SendToClientAsync(clientId, Encoding.UTF8.GetBytes(message)).ConfigureAwait(false); public async Task BroadcastAsync(byte[] data, string? excludeClientId = null) { if (data == null || data.Length == 0) { return false; } bool any = false; foreach (var client in _clients) { if (client.Key == excludeClientId) { continue; } if (await SendToClientAsync(client.Key, data).ConfigureAwait(false)) { any = true; } } _ = Webhooks.FireAsync("broadcast", new { data = Convert.ToBase64String(data), excludeClientId }); return any; } public async Task BroadcastAsync(string message, string? excludeClientId = null) => await BroadcastAsync(Encoding.UTF8.GetBytes(message), excludeClientId).ConfigureAwait(false); public ConcurrentDictionary GetClients() => _clients; public async Task DisconnectClientAsync(string clientId, DisconnectReason reason = DisconnectReason.ServerShutdown) { if (!_clients.TryRemove(clientId, out var client)) { return; } try { client.CancellationSource?.Cancel(); client.CancellationSource?.Dispose(); } catch { } TrackDisconnect(reason); var initiator = DisconnectionDiagnostics.DetermineInitiator(reason, null); var reasonDetails = DisconnectionDiagnostics.GetDetailedReasonDescription(reason, null); var diagnosticContext = new Dictionary { { "IsLocalInitiated", initiator == "Local" ? "true" : "false" } }; var connectionEventArgs = new ConnectionEventArgs { ClientId = clientId, Nickname = client.Nickname, RemoteEndPoint = client.RemoteEndPoint, Reason = reason, Initiator = initiator, ReasonDetails = reasonDetails, DiagnosticContext = diagnosticContext }; try { var serverLogger = ConnectionLogManager.GetServerLogger(); var localEndPoint = $"{IpAddress}:{Port}"; serverLogger.LogDisconnection( clientId, client.Nickname, client.RemoteEndPoint?.ToString() ?? "[Unknown]", localEndPoint, reason.ToString(), initiator, null, diagnosticContext ); } catch (Exception logEx) { System.Diagnostics.Debug.WriteLine($"Failed to log disconnection: {logEx.Message}"); } HandlingHelpers.SafeInvokeEventHandler( OnDisconnected, this, connectionEventArgs, nameof(OnDisconnected)); _ = HandlingHelpers.SafeFireAndForgetTaskAsync( () => Webhooks.FireAsync("disconnected", new { clientId, nickname = client.Nickname, reason = reason.ToString() }), "WebhookDisconnected"); } private async Task DeliverViaWebhookAsync(RestClientConnection client, byte[] data) { using var httpClient = new HttpClient(); var payload = JsonHelper.ToJson(new { clientId = client.Id, nickname = client.Nickname, data = Convert.ToBase64String(data) }); var content = new StringContent(payload, Encoding.UTF8, "application/json"); await httpClient.PostAsync(client.WebhookUrl!, content).ConfigureAwait(false); } public void Stop() { _serverCts?.Cancel(); foreach (var client in _clients.Keys.ToList()) { DisconnectClientAsync(client, DisconnectReason.ServerShutdown).GetAwaiter().GetResult(); } _clients.Clear(); try { _app?.StopAsync().GetAwaiter().GetResult(); } catch { } try { _app?.DisposeAsync().AsTask().GetAwaiter().GetResult(); } catch { } _app = null; } public async Task StopAsync() { _serverCts?.Cancel(); foreach (var client in _clients.Keys.ToList()) { await DisconnectClientAsync(client, DisconnectReason.ServerShutdown).ConfigureAwait(false); } _clients.Clear(); try { if (_app != null) { await _app.StopAsync().ConfigureAwait(false); } } catch { } try { if (_app != null) { await _app.DisposeAsync().ConfigureAwait(false); } } catch { } _app = null; if (_serverTask != null) { try { await _serverTask.ConfigureAwait(false); } catch { } } } private static Aes CreateAesFromPassword(string password, byte[] salt, byte[] iv) { using var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 800_000, HashAlgorithmName.SHA256); var key = pbkdf2.GetBytes(32); var aes = Aes.Create(); aes.KeySize = 256; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = key; aes.IV = iv; return aes; } public void Dispose() { if (_disposed) { return; } _disposed = true; Stop(); foreach (var client in _clients.Values) { client.Dispose(); } _serverCts?.Dispose(); Webhooks.Dispose(); OnConnected = null; OnDisconnected = null; OnDataReceived = null; OnGeneralError = null; } } }