Updated
This commit is contained in:
1 parent
2c5b69bf2c
commit
22dee59f47
132 files changed
+19653
-7192
No files matched your search
@@ -0,0 +1,30 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
|
||||
<Title>EonaCat.Connections.REST</Title>
|
||||
<Company>EonaCat</Company>
|
||||
<Copyright>Jeroen Saey</Copyright>
|
||||
<PackageId>EonaCat.Connections.REST</PackageId>
|
||||
<Version>1.0.0</Version>
|
||||
<Authors>Jeroen Saey</Authors>
|
||||
<Description>EonaCat.Connections.REST for REST client/servers with optional TLS, broadcast, and webhook support</Description>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<FrameworkReference Include="Microsoft.AspNetCore.App" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="EonaCat.Json" Version="2.2.5" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\EonaCat.Connections\EonaCat.Connections.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
|
||||
namespace EonaCat.Connections.REST
|
||||
{
|
||||
public class RestClientConnection : IDisposable
|
||||
{
|
||||
public string Id { get; set; } = string.Empty;
|
||||
public IPEndPoint? RemoteEndPoint { get; set; }
|
||||
public CancellationTokenSource? CancellationSource { get; set; }
|
||||
public DateTime ConnectedAt { get; set; }
|
||||
public DateTime LastActive { get; set; }
|
||||
public DateTime LastDataSent { get; set; }
|
||||
public DateTime LastDataReceived { get; set; }
|
||||
public DateTime LastPingSent { get; set; }
|
||||
public DateTime LastPongReceived { get; set; }
|
||||
|
||||
public long BytesSent { get; set; }
|
||||
public long BytesReceived { get; set; }
|
||||
public long MessagesSent { get; set; }
|
||||
public long MessagesReceived { get; set; }
|
||||
|
||||
private string? _nickname;
|
||||
public string Nickname
|
||||
{
|
||||
get => string.IsNullOrWhiteSpace(_nickname) ? Id : _nickname;
|
||||
set => _nickname = string.IsNullOrWhiteSpace(value) ? Id : value;
|
||||
}
|
||||
|
||||
public bool HasNickname => !string.IsNullOrWhiteSpace(_nickname) && _nickname != Id;
|
||||
|
||||
internal ConcurrentQueue<byte[]> PendingMessages { get; } = new();
|
||||
|
||||
public int PendingMessageCount => PendingMessages.Count;
|
||||
|
||||
public string? WebhookUrl { get; set; }
|
||||
|
||||
public Aes? AesInstance { get; set; }
|
||||
public byte[]? AesSalt { get; set; }
|
||||
public byte[]? AesIv { get; set; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
AesInstance?.Dispose();
|
||||
AesInstance = null;
|
||||
CancellationSource?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,859 @@
|
||||
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 System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using ErrorEventArgs = EonaCat.Connections.EventArguments.ErrorEventArgs;
|
||||
|
||||
namespace EonaCat.Connections.REST
|
||||
{
|
||||
public class RestNetworkClient : IAsyncDisposable, IDisposable
|
||||
{
|
||||
public static event EventHandler<LogMessage> OnLog;
|
||||
private readonly Configuration _config;
|
||||
private HttpClient? _httpClient;
|
||||
private Task? _pollTask;
|
||||
private Task? _autoReconnectTask;
|
||||
private Task? _pingTask;
|
||||
private Task? _pongMonitorTask;
|
||||
private CancellationTokenSource? _clientCts;
|
||||
private CancellationTokenSource? _autoReconnectSource;
|
||||
private bool _disposed;
|
||||
private bool _stopAutoReconnecting;
|
||||
private bool _wasConnected;
|
||||
private DisconnectReason _reason;
|
||||
private Aes? _aesInstance;
|
||||
|
||||
private WebApplication? _webhookApp;
|
||||
private CancellationTokenSource? _webhookCts;
|
||||
private Task? _webhookTask;
|
||||
private int _webhookPort;
|
||||
|
||||
private readonly SemaphoreSlim _connectLock = new(1, 1);
|
||||
|
||||
public string? ClientId { get; private set; }
|
||||
public bool IsConnected { get; private set; }
|
||||
public string? Nickname { get; private set; }
|
||||
public DateTime ConnectionTime { get; private set; }
|
||||
public TimeSpan Uptime => DateTime.UtcNow - ConnectionTime;
|
||||
public DateTime LastActive { get; internal set; }
|
||||
public DateTime LastDataSent { get; private set; }
|
||||
public DateTime LastDataReceived { get; private set; }
|
||||
public DateTime LastPingSent { get; private set; }
|
||||
public DateTime LastPongReceived { get; private set; }
|
||||
public DateTime DisconnectionTime { get; private set; }
|
||||
public bool IsAutoConnectStarted => _autoReconnectTask != null && !_autoReconnectTask.IsCompleted;
|
||||
public bool IsWebhookListenerActive => _webhookApp != null && _webhookCts != null && !_webhookCts.IsCancellationRequested;
|
||||
|
||||
public long BytesSent { get; private set; }
|
||||
public long BytesReceived { get; private set; }
|
||||
public long MessagesSent { get; private set; }
|
||||
public long MessagesReceived { get; private set; }
|
||||
|
||||
public event EventHandler<ConnectionEventArgs>? OnConnected;
|
||||
public event EventHandler<ConnectionEventArgs>? OnNicknameSend;
|
||||
public event EventHandler<DataReceivedEventArgs>? OnDataReceived;
|
||||
public event EventHandler<ConnectionEventArgs>? OnDisconnected;
|
||||
public event EventHandler<ErrorEventArgs>? OnGeneralError;
|
||||
public event EventHandler<PingEventArgs>? OnPingResponse;
|
||||
public event EventHandler<PingEventArgs>? OnPongResponse;
|
||||
|
||||
public WebhookManager Webhooks { get; } = new();
|
||||
|
||||
public RestNetworkClient(Configuration config)
|
||||
{
|
||||
_config = config ?? throw new ArgumentNullException(nameof(config));
|
||||
_clientCts = new CancellationTokenSource();
|
||||
}
|
||||
|
||||
private string BaseUrl
|
||||
{
|
||||
get
|
||||
{
|
||||
var scheme = _config.UseSsl ? "https" : "http";
|
||||
return $"{scheme}://{_config.Host}:{_config.Port}";
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> ConnectAsync()
|
||||
{
|
||||
await _connectLock.WaitAsync().ConfigureAwait(false);
|
||||
|
||||
try
|
||||
{
|
||||
if (_clientCts == null || _clientCts.IsCancellationRequested)
|
||||
{
|
||||
_clientCts?.Dispose();
|
||||
_clientCts = new CancellationTokenSource();
|
||||
}
|
||||
|
||||
if (IsConnected)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
_httpClient?.Dispose();
|
||||
|
||||
var handler = new HttpClientHandler();
|
||||
if (_config.UseSsl && _config.IsSelfSignedEnabled)
|
||||
{
|
||||
handler.ServerCertificateCustomValidationCallback = (_, _, _, _) => true;
|
||||
}
|
||||
|
||||
_httpClient = new HttpClient(handler)
|
||||
{
|
||||
BaseAddress = new Uri(BaseUrl),
|
||||
Timeout = _config.ConnectionTimeout
|
||||
};
|
||||
|
||||
var response = await _httpClient.PostAsync("/api/connect",
|
||||
new StringContent("{}", Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
|
||||
var doc = JObject.Parse(json);
|
||||
ClientId = (string)doc["clientId"];
|
||||
|
||||
if (string.IsNullOrEmpty(ClientId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
IsConnected = true;
|
||||
ConnectionTime = DateTime.UtcNow;
|
||||
LastActive = DateTime.UtcNow;
|
||||
LastPongReceived = DateTime.UtcNow;
|
||||
|
||||
if (_config.UseAesEncryption && !string.IsNullOrEmpty(_config.AesPassword))
|
||||
{
|
||||
await InitAesEncryptionAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_pollTask = Task.Run(() => PollLoopAsync(_clientCts.Token), _clientCts.Token);
|
||||
|
||||
if (_config.EnableHeartbeat)
|
||||
{
|
||||
_pingTask = Task.Run(() => PingLoopAsync(_clientCts.Token), _clientCts.Token);
|
||||
_pongMonitorTask = Task.Run(() => PongMonitorAsync(_clientCts.Token), _clientCts.Token);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(Nickname))
|
||||
{
|
||||
await SendNicknameAsync(Nickname).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (_config.EnableAutoReconnect &&
|
||||
(_autoReconnectTask == null || _autoReconnectTask.IsCompleted))
|
||||
{
|
||||
if (_autoReconnectSource == null || _autoReconnectSource.IsCancellationRequested)
|
||||
{
|
||||
_autoReconnectSource?.Dispose();
|
||||
_autoReconnectSource = new CancellationTokenSource();
|
||||
}
|
||||
_autoReconnectTask = Task.Run(() => AutoReconnectAsync(_autoReconnectSource.Token), _autoReconnectSource.Token);
|
||||
}
|
||||
|
||||
_wasConnected = true;
|
||||
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnConnected,
|
||||
this,
|
||||
new ConnectionEventArgs
|
||||
{
|
||||
ClientId = ClientId,
|
||||
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port)
|
||||
},
|
||||
nameof(OnConnected));
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnGeneralError,
|
||||
this,
|
||||
new ErrorEventArgs
|
||||
{
|
||||
Exception = exception,
|
||||
Message = "REST connection error"
|
||||
},
|
||||
nameof(OnGeneralError));
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
_connectLock.Release();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PollLoopAsync(CancellationToken token)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (!token.IsCancellationRequested && IsConnected)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_httpClient == null || string.IsNullOrEmpty(ClientId))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var response = await _httpClient.GetAsync($"/api/poll/{ClientId}", token).ConfigureAwait(false);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
|
||||
{
|
||||
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
await Task.Delay(1000, token).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
|
||||
var json = await response.Content.ReadAsStringAsync(token).ConfigureAwait(false);
|
||||
var doc = JObject.Parse(json);
|
||||
|
||||
if (doc.TryGetValue("messages", out var messagesToken) && messagesToken is JArray messagesArray)
|
||||
{
|
||||
foreach (var msg in messagesArray)
|
||||
{
|
||||
var base64 = (string)msg;
|
||||
if (string.IsNullOrEmpty(base64))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var data = Convert.FromBase64String(base64);
|
||||
|
||||
if (_config.UseAesEncryption && _aesInstance != null)
|
||||
{
|
||||
data = await AesKeyExchange.DecryptDataAsync(data, data.Length, _aesInstance).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
LastActive = DateTime.UtcNow;
|
||||
LastDataReceived = DateTime.UtcNow;
|
||||
BytesReceived += data.Length;
|
||||
MessagesReceived++;
|
||||
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnDataReceived,
|
||||
this,
|
||||
new DataReceivedEventArgs
|
||||
{
|
||||
ClientId = ClientId ?? "self",
|
||||
Data = data,
|
||||
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port),
|
||||
Nickname = Nickname
|
||||
},
|
||||
nameof(OnDataReceived));
|
||||
}
|
||||
}
|
||||
|
||||
await Task.Delay(500, token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnGeneralError,
|
||||
this,
|
||||
new ErrorEventArgs
|
||||
{
|
||||
Exception = exception,
|
||||
Message = "Error in REST poll loop"
|
||||
},
|
||||
nameof(OnGeneralError));
|
||||
await DisconnectAsync(DisconnectReason.Error, exception).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> SendAsync(byte[] data)
|
||||
{
|
||||
if (!IsConnected || _httpClient == null || string.IsNullOrEmpty(ClientId) || data == null || data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var sendData = data;
|
||||
if (_config.UseAesEncryption && _aesInstance != null)
|
||||
{
|
||||
sendData = await AesKeyExchange.EncryptDataAsync(data, data.Length, _aesInstance).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var payload = JsonHelper.ToJson(new
|
||||
{
|
||||
clientId = ClientId,
|
||||
data = Convert.ToBase64String(sendData)
|
||||
});
|
||||
|
||||
var response = await _httpClient.PostAsync("/api/send",
|
||||
new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
||||
|
||||
LastActive = DateTime.UtcNow;
|
||||
LastDataSent = DateTime.UtcNow;
|
||||
BytesSent += data.Length;
|
||||
MessagesSent++;
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await DisconnectAsync(DisconnectReason.Error, ex).ConfigureAwait(false);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> SendAsync(string message) => await SendAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false);
|
||||
|
||||
public async Task<bool> BroadcastAsync(byte[] data)
|
||||
{
|
||||
if (!IsConnected || _httpClient == null || string.IsNullOrEmpty(ClientId) || data == null || data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var broadcast_data = data;
|
||||
if (_config.UseAesEncryption && _aesInstance != null)
|
||||
{
|
||||
broadcast_data = await AesKeyExchange.EncryptDataAsync(data, data.Length, _aesInstance).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
var payload = JsonHelper.ToJson(new
|
||||
{
|
||||
clientId = ClientId,
|
||||
data = Convert.ToBase64String(broadcast_data)
|
||||
});
|
||||
|
||||
var response = await _httpClient.PostAsync("/api/broadcast",
|
||||
new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
||||
|
||||
return response.IsSuccessStatusCode;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnGeneralError,
|
||||
this,
|
||||
new ErrorEventArgs
|
||||
{
|
||||
Exception = ex,
|
||||
Message = "Error broadcasting via REST"
|
||||
},
|
||||
nameof(OnGeneralError));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> BroadcastAsync(string message) => await BroadcastAsync(Encoding.UTF8.GetBytes(message)).ConfigureAwait(false);
|
||||
|
||||
public async Task SendNicknameAsync(string nickname)
|
||||
{
|
||||
Nickname = nickname;
|
||||
if (IsConnected && _httpClient != null && !string.IsNullOrEmpty(ClientId))
|
||||
{
|
||||
var payload = JsonHelper.ToJson(new { clientId = ClientId, nickname });
|
||||
await _httpClient.PostAsync("/api/nickname",
|
||||
new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
||||
|
||||
OnNicknameSend?.Invoke(this, new ConnectionEventArgs
|
||||
{
|
||||
ClientId = ClientId,
|
||||
Nickname = nickname
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public async Task StartWebhookListenerAsync(int port)
|
||||
{
|
||||
_webhookPort = port;
|
||||
_webhookCts?.Cancel();
|
||||
_webhookCts?.Dispose();
|
||||
_webhookCts = new CancellationTokenSource();
|
||||
|
||||
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
|
||||
{
|
||||
Args = Array.Empty<string>()
|
||||
});
|
||||
|
||||
builder.WebHost.ConfigureKestrel(options =>
|
||||
{
|
||||
options.Listen(IPAddress.Loopback, port, listenOptions =>
|
||||
{
|
||||
listenOptions.Protocols = HttpProtocols.Http1AndHttp2;
|
||||
});
|
||||
});
|
||||
|
||||
_webhookApp = builder.Build();
|
||||
|
||||
_webhookApp.MapPost("/webhook", async (HttpContext ctx) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
using var reader = new System.IO.StreamReader(ctx.Request.Body);
|
||||
var json = await reader.ReadToEndAsync().ConfigureAwait(false);
|
||||
var doc = JObject.Parse(json);
|
||||
|
||||
if (doc.TryGetValue("data", out var dataToken))
|
||||
{
|
||||
var base64 = (string)dataToken;
|
||||
if (!string.IsNullOrEmpty(base64))
|
||||
{
|
||||
var data = Convert.FromBase64String(base64);
|
||||
LastActive = DateTime.UtcNow;
|
||||
LastDataReceived = DateTime.UtcNow;
|
||||
BytesReceived += data.Length;
|
||||
MessagesReceived++;
|
||||
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnDataReceived,
|
||||
this,
|
||||
new DataReceivedEventArgs
|
||||
{
|
||||
ClientId = ClientId ?? "self",
|
||||
Data = data,
|
||||
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port),
|
||||
Nickname = Nickname
|
||||
},
|
||||
nameof(OnDataReceived));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
return Results.Ok();
|
||||
});
|
||||
|
||||
_webhookTask = _webhookApp.RunAsync();
|
||||
}
|
||||
|
||||
public async Task RegisterWebhookAsync(string webhookServer = "https://127.0.0.1")
|
||||
{
|
||||
if (!IsConnected || _httpClient == null || string.IsNullOrEmpty(ClientId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var webhookUrl = $"{webhookServer}:{_webhookPort}/webhook";
|
||||
var payload = JsonHelper.ToJson(new { clientId = ClientId, url = webhookUrl });
|
||||
await _httpClient.PostAsync("/api/webhooks/register",
|
||||
new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task UnregisterWebhookAsync()
|
||||
{
|
||||
if (!IsConnected || _httpClient == null || string.IsNullOrEmpty(ClientId))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var payload = JsonHelper.ToJson(new { clientId = ClientId });
|
||||
await _httpClient.PostAsync("/api/webhooks/unregister",
|
||||
new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public async Task StopWebhookListenerAsync()
|
||||
{
|
||||
await UnregisterWebhookAsync().ConfigureAwait(false);
|
||||
|
||||
_webhookCts?.Cancel();
|
||||
|
||||
try
|
||||
{
|
||||
if (_webhookApp != null)
|
||||
{
|
||||
await _webhookApp.StopAsync().ConfigureAwait(false);
|
||||
await _webhookApp.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
_webhookApp = null;
|
||||
}
|
||||
|
||||
public async Task DisconnectAsync(DisconnectReason reason = DisconnectReason.ClientRequested, Exception? exception = null)
|
||||
{
|
||||
if (!IsConnected && _httpClient == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
IsConnected = false;
|
||||
DisconnectionTime = DateTime.UtcNow;
|
||||
_reason = reason;
|
||||
|
||||
_clientCts?.Cancel();
|
||||
|
||||
_aesInstance?.Dispose();
|
||||
_aesInstance = null;
|
||||
|
||||
try
|
||||
{
|
||||
if (_httpClient != null && !string.IsNullOrEmpty(ClientId))
|
||||
{
|
||||
var payload = JsonHelper.ToJson(new { clientId = ClientId });
|
||||
await _httpClient.PostAsync("/api/disconnect",
|
||||
new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_httpClient?.Dispose();
|
||||
_httpClient = null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
var determinedReason = ConnectionEventArgs.Determine(reason, exception);
|
||||
var initiator = DisconnectionDiagnostics.DetermineInitiator(determinedReason, exception);
|
||||
var reasonDetails = DisconnectionDiagnostics.GetDetailedReasonDescription(determinedReason, exception);
|
||||
|
||||
var diagnosticContext = new Dictionary<string, string>();
|
||||
if (exception is System.Net.Sockets.SocketException socketEx)
|
||||
{
|
||||
var socketContext = DisconnectionDiagnostics.AnalyzeSocketException(socketEx);
|
||||
foreach (var kvp in socketContext)
|
||||
{
|
||||
diagnosticContext[$"Socket_{kvp.Key}"] = kvp.Value;
|
||||
}
|
||||
}
|
||||
|
||||
diagnosticContext["IsLocalInitiated"] = initiator == "Local" ? "true" : "false";
|
||||
|
||||
var remoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port);
|
||||
var connectionEventArgs = new ConnectionEventArgs
|
||||
{
|
||||
ClientId = ClientId ?? "self",
|
||||
Reason = determinedReason,
|
||||
Exception = exception,
|
||||
RemoteEndPoint = remoteEndPoint,
|
||||
Initiator = initiator,
|
||||
ReasonDetails = reasonDetails,
|
||||
DiagnosticContext = diagnosticContext
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
var clientLogger = ConnectionLogManager.GetClientLogger();
|
||||
var localEndPoint = IsWebhookListenerActive ? $"127.0.0.1:{_webhookPort}" : "[Client-Local]";
|
||||
clientLogger.LogDisconnection(
|
||||
ClientId ?? "self",
|
||||
"[REST Client]",
|
||||
remoteEndPoint.ToString(),
|
||||
localEndPoint,
|
||||
determinedReason.ToString(),
|
||||
initiator,
|
||||
exception,
|
||||
diagnosticContext
|
||||
);
|
||||
}
|
||||
catch (Exception logEx)
|
||||
{
|
||||
|
||||
System.Diagnostics.Debug.WriteLine($"Failed to log disconnection: {logEx.Message}");
|
||||
}
|
||||
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnDisconnected,
|
||||
this,
|
||||
connectionEventArgs,
|
||||
nameof(OnDisconnected));
|
||||
}
|
||||
|
||||
private async Task PingLoopAsync(CancellationToken token)
|
||||
{
|
||||
var interval = TimeSpan.FromSeconds(_config.HeartbeatIntervalSeconds);
|
||||
|
||||
while (!token.IsCancellationRequested && IsConnected)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(interval, token).ConfigureAwait(false);
|
||||
|
||||
if (_httpClient == null || string.IsNullOrEmpty(ClientId))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var response = await _httpClient.GetAsync($"/api/ping/{ClientId}", token).ConfigureAwait(false);
|
||||
LastPingSent = DateTime.UtcNow;
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
LastPongReceived = DateTime.UtcNow;
|
||||
LastActive = DateTime.UtcNow;
|
||||
|
||||
if (_config.EnablePingPongLogs)
|
||||
{
|
||||
OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = $"[REST PING] Pong received at {DateTime.UtcNow:O}" });
|
||||
}
|
||||
|
||||
OnPongResponse?.Invoke(this, new PingEventArgs
|
||||
{
|
||||
Id = ClientId,
|
||||
Nickname = Nickname,
|
||||
ReceivedTime = DateTime.UtcNow,
|
||||
RemoteEndPoint = new IPEndPoint(IPAddress.Parse(_config.Host), _config.Port)
|
||||
});
|
||||
}
|
||||
else if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (HttpRequestException)
|
||||
{
|
||||
await DisconnectAsync(DisconnectReason.RemoteClosed).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
HandlingHelpers.SafeInvokeEventHandler(
|
||||
OnGeneralError,
|
||||
this,
|
||||
new ErrorEventArgs
|
||||
{
|
||||
Exception = ex,
|
||||
Message = "Error in REST ping loop"
|
||||
},
|
||||
nameof(OnGeneralError));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PongMonitorAsync(CancellationToken token)
|
||||
{
|
||||
while (!token.IsCancellationRequested && IsConnected)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(1000, token).ConfigureAwait(false);
|
||||
|
||||
var elapsed = (DateTime.UtcNow - LastPongReceived).TotalSeconds;
|
||||
|
||||
if (LastPongReceived != DateTime.MinValue &&
|
||||
elapsed > _config.HeartbeatIntervalSeconds * 5)
|
||||
{
|
||||
if (_config.DisconectOnMissedPong)
|
||||
{
|
||||
OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = $"[REST PONG] No pong for {elapsed:F0}s, disconnecting" });
|
||||
await DisconnectAsync(DisconnectReason.NoPongReceived).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task InitAesEncryptionAsync()
|
||||
{
|
||||
var salt = new byte[32];
|
||||
var iv = new byte[16];
|
||||
using (var rng = RandomNumberGenerator.Create())
|
||||
{
|
||||
rng.GetBytes(salt);
|
||||
rng.GetBytes(iv);
|
||||
}
|
||||
|
||||
var payload = JsonHelper.ToJson(new
|
||||
{
|
||||
salt = Convert.ToBase64String(salt),
|
||||
iv = Convert.ToBase64String(iv)
|
||||
});
|
||||
|
||||
var response = await _httpClient!.PostAsync($"/api/aes/init/{ClientId}",
|
||||
new StringContent(payload, Encoding.UTF8, "application/json")).ConfigureAwait(false);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
throw new InvalidOperationException("Failed to initialize AES encryption with server");
|
||||
}
|
||||
|
||||
using var pbkdf2 = new Rfc2898DeriveBytes(_config.AesPassword, salt, 800_000, HashAlgorithmName.SHA256);
|
||||
var key = pbkdf2.GetBytes(32);
|
||||
|
||||
_aesInstance?.Dispose();
|
||||
_aesInstance = Aes.Create();
|
||||
_aesInstance.KeySize = 256;
|
||||
_aesInstance.Mode = CipherMode.CBC;
|
||||
_aesInstance.Padding = PaddingMode.PKCS7;
|
||||
_aesInstance.Key = key;
|
||||
_aesInstance.IV = iv;
|
||||
}
|
||||
|
||||
private async Task AutoReconnectAsync(CancellationToken token)
|
||||
{
|
||||
while (!token.IsCancellationRequested && !_stopAutoReconnecting)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(_config.ReconnectDelayInSeconds), token).ConfigureAwait(false);
|
||||
|
||||
if (!IsConnected && _wasConnected)
|
||||
{
|
||||
OnLog?.Invoke(this, new LogMessage { Type = LogType.Trace, Message = "REST auto-reconnect: attempting reconnection..." });
|
||||
await ConnectAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
OnLog?.Invoke(this, new LogMessage { Type = LogType.Error, Message = $"REST auto-reconnect error: {ex.Message}" });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void StopAutoReconnect()
|
||||
{
|
||||
_stopAutoReconnecting = true;
|
||||
_autoReconnectSource?.Cancel();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
|
||||
_clientCts?.Cancel();
|
||||
_clientCts?.Dispose();
|
||||
_autoReconnectSource?.Cancel();
|
||||
_autoReconnectSource?.Dispose();
|
||||
_webhookCts?.Cancel();
|
||||
_webhookCts?.Dispose();
|
||||
|
||||
try
|
||||
{
|
||||
_httpClient?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_webhookApp?.DisposeAsync().AsTask().GetAwaiter().GetResult();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
_aesInstance?.Dispose();
|
||||
_aesInstance = null;
|
||||
_connectLock.Dispose();
|
||||
Webhooks.Dispose();
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
|
||||
_clientCts?.Cancel();
|
||||
_clientCts?.Dispose();
|
||||
_autoReconnectSource?.Cancel();
|
||||
_autoReconnectSource?.Dispose();
|
||||
_webhookCts?.Cancel();
|
||||
_webhookCts?.Dispose();
|
||||
|
||||
try
|
||||
{
|
||||
_httpClient?.Dispose();
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_webhookApp != null)
|
||||
{
|
||||
await _webhookApp.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
_aesInstance?.Dispose();
|
||||
_aesInstance = null;
|
||||
|
||||
_connectLock.Dispose();
|
||||
Webhooks.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,732 @@
|
||||
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<string, RestClientConnection> _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<ConnectionEventArgs>? OnConnected;
|
||||
public event EventHandler<DataReceivedEventArgs>? OnDataReceived;
|
||||
public event EventHandler<ConnectionEventArgs>? OnDisconnected;
|
||||
public event EventHandler<ErrorEventArgs>? 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<string>()
|
||||
});
|
||||
|
||||
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<string>();
|
||||
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<JToken?> 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<bool> 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<bool> SendToClientAsync(string clientId, string message)
|
||||
=> await SendToClientAsync(clientId, Encoding.UTF8.GetBytes(message)).ConfigureAwait(false);
|
||||
|
||||
public async Task<bool> 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<bool> BroadcastAsync(string message, string? excludeClientId = null)
|
||||
=> await BroadcastAsync(Encoding.UTF8.GetBytes(message), excludeClientId).ConfigureAwait(false);
|
||||
|
||||
public ConcurrentDictionary<string, RestClientConnection> 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<string, string>
|
||||
{
|
||||
{ "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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
using EonaCat.Json;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Text;
|
||||
|
||||
namespace EonaCat.Connections.REST
|
||||
{
|
||||
public class WebhookManager : IDisposable
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, HashSet<string>> _webhooks = new();
|
||||
private readonly HttpClient _httpClient = new();
|
||||
private bool _disposed;
|
||||
|
||||
public void Register(string eventName, string url)
|
||||
{
|
||||
var urls = _webhooks.GetOrAdd(eventName, _ => new HashSet<string>(StringComparer.OrdinalIgnoreCase));
|
||||
lock (urls)
|
||||
{
|
||||
urls.Add(url);
|
||||
}
|
||||
}
|
||||
|
||||
public void Unregister(string eventName, string url)
|
||||
{
|
||||
if (_webhooks.TryGetValue(eventName, out var urls))
|
||||
{
|
||||
lock (urls)
|
||||
{
|
||||
urls.Remove(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void UnregisterAll(string eventName)
|
||||
{
|
||||
_webhooks.TryRemove(eventName, out _);
|
||||
}
|
||||
|
||||
public async Task FireAsync(string eventName, object payload)
|
||||
{
|
||||
if (!_webhooks.TryGetValue(eventName, out var urls))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
string[] snapshot;
|
||||
lock (urls)
|
||||
{
|
||||
snapshot = urls.ToArray();
|
||||
}
|
||||
|
||||
var json = JsonHelper.ToJson(payload);
|
||||
|
||||
foreach (var url in snapshot)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var content = new StringContent(json, Encoding.UTF8, "application/json");
|
||||
await _httpClient.PostAsync(url, content).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public Dictionary<string, string[]> GetRegistrations()
|
||||
{
|
||||
var result = new Dictionary<string, string[]>();
|
||||
foreach (var kvp in _webhooks)
|
||||
{
|
||||
lock (kvp.Value)
|
||||
{
|
||||
result[kvp.Key] = kvp.Value.ToArray();
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
_httpClient.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user